text stringlengths 14 6.51M |
|---|
{*********************************************************************
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Autor: Brovin Y.D.
* E-mail: y.brovin@gmail.com
*
********************************************************************}
unit FGX.FlipView.Types;
interface
{$SCOPEDENUMS ON}
uses
System.Classes, FMX.Filter.Effects, FGX.Types;
type
{ TfgFlipViewSlideOptions }
/// <summary>Direction of switching images in [Sliding] mode</summary>
TfgSlideDirection = (Horizontal, Vertical);
/// <summary>Way of switching image slides</summary>
/// <remarks>
/// <list type="bullet">
/// <item><c>Effects</c> - switching slides by transition effects</item>
/// <item><c>Sliding</c> - switching slides by shifting of images</item>
/// <item><c>Custom</c> - user's way. Requires implementation a presentation with name <b>FlipView-Custom</b></item>
/// </list>
/// </remarks>
TfgFlipViewMode = (Effects, Sliding, Custom);
/// <summary>Direction of sliding</summary>
TfgDirection = (Forward, Backward);
TfgChangingImageEvent = procedure (Sender: TObject; const NewItemIndex: Integer) of object;
IfgFlipViewNotifications = interface
['{0D4A9AF7-4B56-4972-8EF2-5693AFBD2857}']
procedure StartChanging;
procedure FinishChanging;
end;
/// <summary>Settings of slider in [Sliding] mode</summary>
TfgFlipViewSlideOptions = class(TfgPersistent)
public const
DefaultDirection = TfgSlideDirection.Horizontal;
DefaultDuration = 0.4;
private
FDirection: TfgSlideDirection;
FDuration: Single;
procedure SetSlideDirection(const Value: TfgSlideDirection);
procedure SetDuration(const Value: Single);
function IsDurationStored: Boolean;
protected
procedure AssignTo(Dest: TPersistent); override;
public
constructor Create(AOwner: TComponent); override;
function IsDefaultValues: Boolean; override;
published
property Direction: TfgSlideDirection read FDirection write SetSlideDirection default DefaultDirection;
property Duration: Single read FDuration write SetDuration stored IsDurationStored nodefault;
end;
{ TfgEffectSlidingOptions }
TfgImageFXEffectClass = class of TImageFXEffect;
TfgTransitionEffectKind = (Random, Blind, Line, Crumple, Fade, Ripple, Dissolve, Circle, Drop, Swirl, Magnify, Wave,
Blood, Blur, Water, Wiggle, Shape, RotateCrumple, Banded, Saturate, Pixelate);
/// <summary>Settings of slider in [Effect] mode</summary>
TfgFlipViewEffectOptions = class(TfgPersistent)
public const
DefaultKind = TfgTransitionEffectKind.Random;
DefaultDuration = 0.4;
private
FKind: TfgTransitionEffectKind;
FDuration: Single;
procedure SetKind(const Value: TfgTransitionEffectKind);
procedure SetDuration(const Value: Single);
function GetTransitionEffectClass: TfgImageFXEffectClass;
function IsDurationStored: Boolean;
protected
procedure AssignTo(Dest: TPersistent); override;
public
constructor Create(AOwner: TComponent); override;
function IsDefaultValues: Boolean; override;
property TransitionEffectClass: TfgImageFXEffectClass read GetTransitionEffectClass;
published
property Kind: TfgTransitionEffectKind read FKind write SetKind default DefaultKind;
property Duration: Single read FDuration write SetDuration stored IsDurationStored nodefault;
end;
{ TfgFlipViewSlideShowOptions }
TfgFlipViewSlideShowOptions = class(TfgPersistent)
public const
DefaultEnabled = False;
DefaultDuration = 4;
private
FEnabled: Boolean;
FDuration: Integer;
procedure SetDuration(const Value: Integer);
procedure SetEnabled(const Value: Boolean);
protected
procedure AssignTo(Dest: TPersistent); override;
public
constructor Create(AOwner: TComponent); overload; override;
function IsDefaultValues: Boolean; override;
published
property Duration: Integer read FDuration write SetDuration default DefaultDuration;
property Enabled: Boolean read FEnabled write SetEnabled default DefaultEnabled;
end;
implementation
uses
System.Math, FGX.Consts, FGX.Asserts;
const
TRANSITION_EFFECTS: array [TfgTransitionEffectKind] of TfgImageFXEffectClass = (nil, TBlindTransitionEffect,
TLineTransitionEffect, TCrumpleTransitionEffect, TFadeTransitionEffect, TRippleTransitionEffect,
TDissolveTransitionEffect, TCircleTransitionEffect, TDropTransitionEffect, TSwirlTransitionEffect,
TMagnifyTransitionEffect, TWaveTransitionEffect, TBloodTransitionEffect, TBlurTransitionEffect,
TWaterTransitionEffect, TWiggleTransitionEffect, TShapeTransitionEffect, TRotateCrumpleTransitionEffect,
TBandedSwirlTransitionEffect, TSaturateTransitionEffect, TPixelateTransitionEffect);
{ TfgSlidingOptions }
procedure TfgFlipViewSlideOptions.AssignTo(Dest: TPersistent);
begin
AssertIsNotNil(Dest);
if Dest is TfgFlipViewSlideOptions then
begin
TfgFlipViewSlideOptions(Dest).Direction := Direction;
TfgFlipViewSlideOptions(Dest).Duration := Duration;
end
else
inherited AssignTo(Dest);
end;
constructor TfgFlipViewSlideOptions.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDirection := DefaultDirection;
FDuration := DefaultDuration;
end;
function TfgFlipViewSlideOptions.IsDefaultValues: Boolean;
begin
Result := (Direction = DefaultDirection) and not IsDurationStored;
end;
function TfgFlipViewSlideOptions.IsDurationStored: Boolean;
begin
Result := not SameValue(Duration, DefaultDuration, EPSILON_SINGLE);
end;
procedure TfgFlipViewSlideOptions.SetDuration(const Value: Single);
begin
Assert(Value >= 0);
if not SameValue(Value, Duration, EPSILON_SINGLE) then
begin
FDuration := Max(0, Value);
DoInternalChanged;
end;
end;
procedure TfgFlipViewSlideOptions.SetSlideDirection(const Value: TfgSlideDirection);
begin
if Direction <> Value then
begin
FDirection := Value;
DoInternalChanged;
end;
end;
{ TfgEffectSlidingOptions }
procedure TfgFlipViewEffectOptions.AssignTo(Dest: TPersistent);
var
DestOptions: TfgFlipViewEffectOptions;
begin
AssertIsNotNil(Dest);
if Dest is TfgFlipViewEffectOptions then
begin
DestOptions := TfgFlipViewEffectOptions(Dest);
DestOptions.Kind := Kind;
DestOptions.Duration := Duration;
end
else
inherited AssignTo(Dest);
end;
constructor TfgFlipViewEffectOptions.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FKind := DefaultKind;
FDuration := DefaultDuration;
end;
function TfgFlipViewEffectOptions.GetTransitionEffectClass: TfgImageFXEffectClass;
var
RandomEffectKind: TfgTransitionEffectKind;
begin
if Kind = TfgTransitionEffectKind.Random then
begin
RandomEffectKind := TfgTransitionEffectKind(Random(Integer(High(TfgTransitionEffectKind))) + 1);
Result := TRANSITION_EFFECTS[RandomEffectKind];
end
else
Result := TRANSITION_EFFECTS[Kind];
AssertIsNotNil(Result, 'TfgFlipViewEffectOptions.GetTransitionEffectClass must return class of effect.');
end;
function TfgFlipViewEffectOptions.IsDefaultValues: Boolean;
begin
Result := not IsDurationStored and (Kind = DefaultKind);
end;
function TfgFlipViewEffectOptions.IsDurationStored: Boolean;
begin
Result := not SameValue(Duration, DefaultDuration, EPSILON_SINGLE);
end;
procedure TfgFlipViewEffectOptions.SetKind(const Value: TfgTransitionEffectKind);
begin
if Kind <> Value then
begin
FKind := Value;
DoInternalChanged;
end;
end;
procedure TfgFlipViewEffectOptions.SetDuration(const Value: Single);
begin
Assert(Value >= 0);
if not SameValue(Value, Duration, EPSILON_SINGLE) then
begin
FDuration := Max(0, Value);
DoInternalChanged;
end;
end;
{ TfgFlipViewSlideShowOptions }
procedure TfgFlipViewSlideShowOptions.AssignTo(Dest: TPersistent);
var
DestOptions: TfgFlipViewSlideShowOptions;
begin
AssertIsNotNil(Dest);
if Dest is TfgFlipViewSlideShowOptions then
begin
DestOptions := TfgFlipViewSlideShowOptions(Dest);
DestOptions.Enabled := Enabled;
DestOptions.Duration := Duration;
end
else
inherited AssignTo(Dest);
end;
constructor TfgFlipViewSlideShowOptions.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FEnabled := DefaultEnabled;
FDuration := DefaultDuration;
end;
function TfgFlipViewSlideShowOptions.IsDefaultValues: Boolean;
begin
Result := (Duration = DefaultDuration) and (Enabled = DefaultEnabled);
end;
procedure TfgFlipViewSlideShowOptions.SetDuration(const Value: Integer);
begin
Assert(Value >= 0);
if Duration <> Value then
begin
FDuration := Max(0, Value);
DoInternalChanged;
end;
end;
procedure TfgFlipViewSlideShowOptions.SetEnabled(const Value: Boolean);
begin
if Enabled <> Value then
begin
FEnabled := Value;
DoInternalChanged;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi LiveBindings Framework }
{ }
{ Copyright(c) 2011-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit GraphView;
interface
uses
System.SysUtils, System.Classes, Vcl.Controls, Vcl.Graphics, System.Math, System.Types,
System.Generics.Collections, BindingGraphResStrs;
type
TGraph = class;
TGraphNode = class;
TGraphEdge = class;
TGraphView = class;
TGraphNodeClass = class of TGraphNode;
TGraphEdgeClass = class of TGraphEdge;
TGraphEntity = class(TPersistent)
private
FOwner: TGraph;
FColor: TColor;
FCaption: String;
FRect: TRect;
FTextColor: TColor;
// sets Field to Value only if they are different; if so, it calls Update
procedure SetRectField(var Field: Integer; Value: Integer);
protected
function GetCaption: String; virtual;
function GetRect(const Index: TAlign): Integer; virtual;
function GetWholeRect: TRect; virtual;
procedure SetCaption(const Value: String); virtual;
procedure SetColor(const Value: TColor); virtual;
procedure SetRect(const Index: TAlign; Value: Integer); virtual;
procedure SetTextColor(const Value: TColor); virtual;
procedure SetWholeRect(const Value: TRect); virtual;
// if the node is attached to a graph, it updates the graphs whenever
// something changes within the entity; whenever you want to visually reflect
// some change in the internal data of the entity, call this method
procedure Update; virtual;
public
constructor Create(Owner: TGraph); virtual;
// owner of the entity
property Owner: TGraph read FOwner;
property Color: TColor read FColor write SetColor;
property TextColor: TColor read FTextColor write SetTextColor;
property Caption: String read GetCaption write SetCaption;
// position and dimensions of the entity within the graph
property Rect: TRect read GetWholeRect write SetWholeRect;
property Left: Integer index alLeft read GetRect write SetRect;
property Top: Integer index alTop read GetRect write SetRect;
property Right: Integer index alRight read GetRect write SetRect;
property Bottom: Integer index alBottom read GetRect write SetRect;
end;
// TGraphNode - a node inside a list of nodes
TGraphNode = class(TGraphEntity)
private
FIndex: Integer;
FContent: String;
FFitText: Boolean;
FKeepHeight: Boolean;
FKeepWidth: Boolean;
protected
function GetContent: String; virtual;
function GetHeight: Integer; virtual;
function GetWidth: Integer; virtual;
procedure SetContent(const Value: String); virtual;
procedure SetHeight(const Value: Integer); virtual;
procedure SetWidth(const Value: Integer); virtual;
procedure SetFitText(const Value: Boolean); virtual;
procedure SetCaption(const Value: String); override;
procedure SetRect(const Index: TAlign; Value: Integer); override;
// if FitText is True, it updates the dimensions of the rectangle so that
// it at least fits the text inside
procedure UpdateFitText; virtual;
public
// index of the graph node within the list of nodes of the graph
property Index: Integer read FIndex;
property Width: Integer read GetWidth write SetWidth;
property Height: Integer read GetHeight write SetHeight;
// additional information that is displayed below the caption
property Content: String read GetContent write SetContent;
// if True when you change the Left coordinate, the Right property is changed
// so that Width remains the same
property KeepWidth: Boolean read FKeepWidth write FKeepWidth;
// if True when you change the Top coordinate, the Bottom property is changed
// so that Height remains the same
property KeepHeight: Boolean read FKeepHeight write FKeepHeight;
// changes the right and bottom so that the node fits the text
property FitText: Boolean read FFitText write SetFitText;
end;
// TGraphEdge - an edge inside the list of edges
TGraphEdge = class(TGraphEntity)
private
FEndNode: TGraphNode;
FStartNode: TGraphNode;
public
property StartNode: TGraphNode read FStartNode;
property EndNode: TGraphNode read FEndNode;
end;
// TGraph - represents an entire graph and contains some shortcuts to handle
// nodes and edges in it
EGraphError = class(Exception);
TGraph = class(TPersistent)
public
type
TFindGraphNodeCallback = reference to function (Node: TGraphNode): Boolean;
TOutgoingEdges = TObjectList<TGraphEdge>;
protected
type
TEdgeData = TObjectList<TOutgoingEdges>;
TNodeData = TObjectList<TGraphNode>;
private
var
FNodeData: TNodeData;
FEdgeData: TEdgeData;
FEdgeCount: Integer; // caches the value so that we don't have to iterate through EdgeData to calculate it
FNodeClass: TGraphNodeClass;
FEdgeClass: TGraphEdgeClass;
FUpdateCount: Integer;
protected
// checks if the specified node index is valid within the graph
procedure CheckIndex(Index: Integer);
// checks if the owner of the given Entity is the current Graph
procedure CheckOwner(Entity: TGraphEntity);
function GetNodeCount: Integer; inline;
function GetNodes(Index: Integer): TGraphNode; inline;
function GetEdges(NodeIndex: Integer): TOutgoingEdges;
// some node properties use these methods to determine their dimensions
// based on the contained text; they return 0 in this class, but descendants
// can override these in order to return more significant values
function GetTextWidth(const Text: String): Integer; virtual;
function GetTextHeight(const Text: String): Integer; virtual;
// called by EndUpdate whenever UpdateCount is zero; it can be
// used by descendants to update other classes
procedure Update; virtual;
// the number of BeginUpdate-s called
property UpdateCount: Integer read FUpdateCount;
// access to the internal data structure for storing the nodes
property NodeData: TNodeData read FNodeData;
// internal data structure that stores the edges
property EdgeData: TEdgeData read FEdgeData;
public
constructor Create;
destructor Destroy; override;
// when large amounts of operations are done on the graph, do them between
// this couple of routines to update at the end the; you must call them in
// pairs to have the UpdateCount property zero
procedure BeginUpdate; inline;
procedure EndUpdate;
// Node specific routines
// adds a node to the graph and returns a reference to it
function AddNode: TGraphNode;
// deletes the node at the specified index; if there are any edges that
// use the node, it removes them from the graph
procedure DeleteNode(Index: Integer);
// deletes the specified node from the graph and returns the index where
// it was located before the deletion
function RemoveNode(Node: TGraphNode): Integer;
// Edge specific routines
// adds a new edge to the graph between the specified node indexes
function AddEdge(StartIndex, EndIndex: Integer): TGraphEdge;
procedure DeleteEdge(StartIndex, EndIndex: Integer);
function RemoveEdge(Edge: TGraphEdge): Integer;
// searches for the edge that starts from the StartIndex node and ends in
// the EndIndex node; if it succeeds, it returns the index of the edge
// in the adiacent list of the start index node; if not, it returns -1
function FindEdge(StartIndex, EndIndex: Integer; out Edge: TGraphEdge): Integer;
function FindNode(out Node: TGraphNode; Callback: TFindGraphNodeCallback): Boolean;
// clear all nodes and edges
procedure Clear;
// clear all edges
procedure ClearEdges;
// the nodes in the graph
property Nodes[Index: Integer]: TGraphNode read GetNodes;
// the number of nodes in the graph
property NodeCount: Integer read GetNodeCount;
// returns the list of outgoing edges for the specified node index
property Edges[NodeIndex: Integer]: TOutgoingEdges read GetEdges;
// the total number of edges
property EdgeCount: Integer read FEdgeCount;
// the class ref of the node that is to be used to create instances of nodes
property NodeClass: TGraphNodeClass read FNodeClass write FNodeClass;
// the class ref of the edge that is to be used to create instances of edges
property EdgeClass: TGraphEdgeClass read FEdgeClass write FEdgeClass;
end;
// TGraphViewData - graph instantiated internally by a TGraphView
TGraphViewGraph = class(TGraph)
private
FGraphView: TGraphView;
protected
function GetTextWidth(const Text: String): Integer; override;
function GetTextHeight(const Text: String): Integer; override;
procedure Update; override;
// the graph view to which the graph is attached
property GraphView: TGraphView read FGraphView;
public
constructor Create(GraphView: TGraphView);
end;
// TGraphView - shows a graph
TGraphView = class(TCustomControl)
public
const
CBulletSize: TPoint = (X: 4; Y: 4);
private
FGraph: TGraph;
FBulletSize: TPoint;
FDraggedNode: TGraphNode;
FBulletColor: TColor;
FNodeDragging: Boolean;
// prevents the node to stick to the mouse when double clicked and node dragging
// enabled; it happens when, i.e. you show a modal form in OnDblClick and then
// close it
FDblClicked: Boolean;
procedure SetBulletSize(const Value: TPoint);
procedure SetBulletColor(const Value: TColor);
// returns the closest cross of the line that starts at LineStart and
// which ends in the center of the node;
// it doesn't handle situations in which the line is vertical or horizontal
function GetLineToNodeCross(LineStart: TPoint; ARect: TRect): TPoint;
protected
// adds the coordinates of R1 to R2 and returns the new rect
function AddRects(const R1, R2: TRect): TRect; inline;
// returns the X coordinate of a point situated on the line defined by StartPt and EndPt
function PtXOnLine(StartPt, EndPt: TPoint; PtY: Integer): Integer;
// returns the Y coordinate of a point situated on the line defined by StartPt and EndPt
function PtYOnLine(StartPt, EndPt: TPoint; PtX: Integer): Integer;
// returns the length of the line
function LineLength(StartPt, EndPt: TPoint): Integer;
procedure PaintNode(Node: TGraphNode);
procedure PaintNodes;
procedure PaintEdge(Edge: TGraphEdge);
procedure PaintEdges;
procedure Paint; override;
procedure DblClick; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
// returns the graph node located at the given point; if at that point
// there is no node, it returns nil
function GetNodeFromPoint(Point: TPoint): TGraphNode;
// moves the center of the specified Node at the X and Y coordinates
procedure MoveNode(Node: TGraphNode; X, Y: Integer);
// the graph object that is shown by the control
property Graph: TGraph read FGraph;
// bullets are represented as small squares that indicate the end of an edge
property BulletSize: TPoint read FBulletSize write SetBulletSize;
// the color of the bullets
property BulletColor: TColor read FBulletColor write SetBulletColor;
// the node that is currently being dragged; it is Nil if no node is being dragged
property DraggedNode: TGraphNode read FDraggedNode;
// specifies whether nodes can be dragged with the mouse
[Default(True)]
property NodeDragging: Boolean read FNodeDragging write FNodeDragging default True;
published
[Default(True)]
property DoubleBuffered default True;
property Color default clWhite;
property BevelKind default bkFlat;
property OnClick;
property OnDblClick;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
end;
implementation
{ TGraphView }
function TGraphView.AddRects(const R1, R2: TRect): TRect;
begin
Result := System.Types.Rect(
R1.Left + R2.Left,
R1.Top + R2.Top,
R1.Right + R2.Right,
R1.Bottom + R2.Bottom);
end;
constructor TGraphView.Create(AOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle + [csOpaque, csClickEvents];
DoubleBuffered := True;
Color := clWhite;
Width := 50;
Height := 50;
BevelKind := bkFlat;
FBulletSize := CBulletSize;
FBulletColor := clWhite;
FNodeDragging := True;
FGraph := TGraphViewGraph.Create(Self);
end;
procedure TGraphView.DblClick;
begin
FDraggedNode := nil;
FDblClicked := True;
inherited;
end;
destructor TGraphView.Destroy;
begin
FGraph.Free;
inherited;
end;
function TGraphView.GetLineToNodeCross(LineStart: TPoint;
ARect: TRect): TPoint;
type
TSquareSide = (sqLeft, sqRight, sqTop, sqBottom);
TSquareCrosses = array [TSquareSide] of TPoint;
var
Crosses: TSquareCrosses;
CenterPt: TPoint;
CurrLength: Integer;
MinLength: Integer;
Side: TSquareSide;
begin
CenterPt := CenterPoint(ARect);
// intersect the line from the other end to all the square sides
Crosses[sqLeft].X := ARect.Left;
Crosses[sqLeft].Y := PtYOnLine(LineStart, CenterPt, Crosses[sqLeft].X);
Crosses[sqRight].X := ARect.Right;
Crosses[sqRight].Y := PtYOnLine(LineStart, CenterPt, Crosses[sqRight].X);
Crosses[sqTop].Y := ARect.Top;
Crosses[sqTop].X := PtXOnLine(LineStart, CenterPt, Crosses[sqTop].Y);
Crosses[sqBottom].Y := ARect.Bottom;
Crosses[sqBottom].X := PtXOnLine(LineStart, CenterPt, Crosses[sqBottom].Y);
// inflate it to permit PtInRect to return the True when the cross point
// has coordinates equal to one of the right or bottom sides
Inc(ARect.Right);
Inc(ARect.Bottom);
// determine the minimum length segment that intersects the square
// for which the intersection point is on the square side
MinLength := MaxInt;
for Side := Low(Crosses) to High(Crosses) do
begin
CurrLength := LineLength(Crosses[Side], LineStart);
if (CurrLength <= MinLength) and ARect.Contains(Crosses[Side]) then
begin
MinLength := CurrLength;
Result := Crosses[Side];
end;
end;
end;
function TGraphView.GetNodeFromPoint(Point: TPoint): TGraphNode;
var
NodeRect: TRect;
i: Integer;
begin
Result := nil;
for i := 0 to Graph.NodeCount - 1 do
begin
NodeRect := Graph.Nodes[i].Rect;
Inc(NodeRect.Right);
Inc(NodeRect.Bottom);
if NodeRect.Contains(Point) then
Exit(Graph.Nodes[i])
end;
end;
function TGraphView.LineLength(StartPt, EndPt: TPoint): Integer;
begin
Result := Round(Sqrt(Sqr(EndPt.X - StartPt.X) + Sqr(EndPt.Y - StartPt.Y)));
end;
procedure TGraphView.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
inherited;
if (Button = mbLeft) and NodeDragging and not FDblClicked then
begin
FDraggedNode := GetNodeFromPoint(Point(X, Y));
if Assigned(FDraggedNode) then
MoveNode(DraggedNode, X, Y);
end;
end;
procedure TGraphView.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
if Assigned(DraggedNode) then
MoveNode(DraggedNode, X, Y);
end;
procedure TGraphView.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
FDblClicked := False;
if (Button = mbLeft) and Assigned(DraggedNode) then
begin
MoveNode(DraggedNode, X, Y);
FDraggedNode := nil;
end;
end;
procedure TGraphView.MoveNode(Node: TGraphNode; X, Y: Integer);
var
NodeRect: TRect;
CenterPt: TPoint;
begin
NodeRect := Node.Rect;
CenterPt := CenterPoint(NodeRect);
OffsetRect(NodeRect, X - CenterPt.X, Y - CenterPt.Y);
Node.Rect := NodeRect;
end;
procedure TGraphView.Paint;
begin
inherited;
PaintNodes;
PaintEdges;
end;
procedure TGraphView.PaintEdge(Edge: TGraphEdge);
var
StartPt: TPoint; // center point of the start rect
EndPt: TPoint; // center point of the end rect
LineStart: TPoint;
begin
Canvas.Brush.Style := bsSolid;
Canvas.Brush.Color := Edge.Color;
Canvas.Pen.Style := psSolid;
Canvas.Pen.Width := 2;
Canvas.Pen.Color := Edge.Color;
StartPt := CenterPoint(Edge.StartNode.Rect);
EndPt := CenterPoint(Edge.EndNode.Rect);
// the center points are on the same vertical line
if StartPt.X = EndPt.X then
if StartPt.Y < EndPt.Y then
begin
StartPt.Y := Edge.StartNode.Bottom;
EndPt.Y := Edge.EndNode.Top;
end
else
begin
StartPt.Y := Edge.StartNode.Top;
EndPt.Y := Edge.EndNode.Bottom;
end
else
// the center points are on the same horizontal line
if StartPt.Y = EndPt.Y then
if StartPt.X < EndPt.X then
begin
StartPt.X := Edge.StartNode.Right;
EndPt.X := Edge.EndNode.Left;
end
else
begin
StartPt.X := Edge.StartNode.Left;
EndPt.X := Edge.EndNode.Right;
end
else // the points have no same coordinates one with each other
begin
LineStart := StartPt;
StartPt := GetLineToNodeCross(EndPt, Edge.StartNode.Rect);
EndPt := GetLineToNodeCross(LineStart, Edge.EndNode.Rect);
end;
// draw the line of the edge
Canvas.MoveTo(StartPt.X, StartPt.Y);
Canvas.LineTo(EndPt.X, EndPt.Y);
// draw the bullet of the edge
Canvas.Brush.Color := BulletColor;
Canvas.Rectangle(
EndPt.X - BulletSize.X,
EndPt.Y + BulletSize.Y,
EndPt.X + BulletSize.X,
EndPt.Y - BulletSize.Y)
end;
procedure TGraphView.PaintEdges;
var
i, j: Integer;
begin
for i := 0 to Graph.NodeCount - 1 do
for j := 0 to Graph.Edges[i].Count - 1 do
PaintEdge(Graph.Edges[i][j]);
end;
procedure TGraphView.PaintNode(Node: TGraphNode);
var
NodeRect: TRect;
NodeText: String;
begin
NodeRect := Node.Rect;
// draw the rectangle of the node
Canvas.Brush.Style := bsSolid;
Canvas.Brush.Color := Node.Color;
Canvas.Pen.Style := psSolid;
Canvas.Pen.Color := Node.Color;
Canvas.Rectangle(NodeRect);
// draw the caption of the node
Canvas.Brush.Style := bsClear;
Canvas.Font.Color := Node.TextColor;
NodeText := Node.Caption + sLineBreak + Node.Content;
Canvas.TextRect(NodeRect, NodeText, [tfCenter, tfWordBreak]);
end;
procedure TGraphView.PaintNodes;
var
i: Integer;
begin
for i := 0 to Graph.NodeCount - 1 do
PaintNode(Graph.Nodes[i]);
end;
function TGraphView.PtXOnLine(StartPt, EndPt: TPoint; PtY: Integer): Integer;
begin
Result := Round((PtY - StartPt.Y) / (EndPt.Y - StartPt.Y) * (EndPt.X - StartPt.X) + StartPt.X);
end;
function TGraphView.PtYOnLine(StartPt, EndPt: TPoint; PtX: Integer): Integer;
begin
Result := Round((PtX - StartPt.X) / (EndPt.X - StartPt.X) * (EndPt.Y - StartPt.Y) + StartPt.Y);
end;
procedure TGraphView.SetBulletColor(const Value: TColor);
begin
if Value <> FBulletColor then
begin
FBulletColor := Value;
Invalidate;
end;
end;
procedure TGraphView.SetBulletSize(const Value: TPoint);
begin
if not CompareMem(@FBulletSize, @Value, SizeOf(TPoint)) then
begin
FBulletSize := Value;
Invalidate;
end;
end;
{ TGraphEntity }
constructor TGraphEntity.Create(Owner: TGraph);
begin
inherited Create;
FOwner := Owner;
end;
function TGraphEntity.GetCaption: String;
begin
Result := FCaption;
end;
function TGraphEntity.GetRect(const Index: TAlign): Integer;
begin
Result := 0;
case Index of
alLeft: Result := FRect.Left;
alRight: Result := FRect.Right;
alTop: Result := FRect.Top;
alBottom: Result := FRect.Bottom;
end;
end;
function TGraphEntity.GetWholeRect: TRect;
begin
Result := FRect;
end;
procedure TGraphEntity.SetCaption(const Value: String);
begin
if FCaption <> Value then
begin
FCaption := Value;
Update;
end;
end;
procedure TGraphEntity.SetColor(const Value: TColor);
begin
if Value <> FColor then
begin
FColor := Value;
Update;
end;
end;
procedure TGraphEntity.SetRect(const Index: TAlign; Value: Integer);
begin
case Index of
alLeft: SetRectField(FRect.Left, Value);
alRight: SetRectField(FRect.Right, Value);
alTop: SetRectField(FRect.Top, Value);
alBottom: SetRectField(FRect.Bottom, Value);
end;
end;
procedure TGraphEntity.SetWholeRect(const Value: TRect);
begin
if not CompareMem(@Value, @FRect, SizeOf(TRect)) then
begin
FRect := Value;
Update;
end;
end;
procedure TGraphEntity.SetRectField(var Field: Integer; Value: Integer);
begin
if Field <> Value then
begin
Field := Value;
Update;
end;
end;
procedure TGraphEntity.SetTextColor(const Value: TColor);
begin
if FTextColor <> Value then
begin
FTextColor := Value;
Update;
end;
end;
procedure TGraphEntity.Update;
begin
if Assigned(Owner) and (Owner.UpdateCount = 0) then
Owner.Update;
end;
{ TGraph }
function TGraph.AddEdge(StartIndex, EndIndex: Integer): TGraphEdge;
begin
CheckIndex(StartIndex);
CheckIndex(EndIndex);
if FindEdge(StartIndex, EndIndex, Result) = -1 then
try
BeginUpdate;
// create the new edge and set its nodes
Result := EdgeClass.Create(Self);
Result.FStartNode := NodeData[StartIndex];
Result.FEndNode := NodeData[EndIndex];
// add the node to the internal structure storing the edges
EdgeData[StartIndex].Add(Result);
Inc(FEdgeCount);
finally
EndUpdate;
end;
end;
function TGraph.AddNode: TGraphNode;
begin
try
BeginUpdate;
// add the new node and point to the result to it
Result := NodeClass.Create(Self);
Result.FIndex := NodeData.Add(Result);
// add the list in edges data that will store incident edges for this node
EdgeData.Add(TOutgoingEdges.Create);
finally
EndUpdate;
end;
end;
procedure TGraph.BeginUpdate;
begin
Inc(FUpdateCount);
end;
procedure TGraph.CheckIndex(Index: Integer);
begin
if (Index < 0) or (Index >= NodeCount) then
raise EGraphError.CreateFmt(sInvalidNodeIndex, [Index]);
end;
procedure TGraph.CheckOwner(Entity: TGraphEntity);
begin
if not Assigned(Entity) or not (Entity.Owner <> Self) then
raise EGraphError.Create(sInvalidOwner);
end;
procedure TGraph.Clear;
begin
ClearEdges;
NodeData.Clear;
end;
procedure TGraph.ClearEdges;
begin
BeginUpdate;
EdgeData.Clear;
FEdgeCount := 0;
EndUpdate;
end;
constructor TGraph.Create;
begin
inherited;
FNodeData := TNodeData.Create;
FEdgeData := TEdgeData.Create;
FNodeClass := TGraphNode;
FEdgeClass := TGraphEdge;
end;
procedure TGraph.DeleteEdge(StartIndex, EndIndex: Integer);
var
Edge: TGraphEdge;
EdgeIdx: Integer;
begin
CheckIndex(StartIndex);
CheckIndex(EndIndex);
try
BeginUpdate;
EdgeIdx := FindEdge(StartIndex, EndIndex, Edge);
if EdgeIdx <> -1 then
begin
EdgeData[StartIndex].Delete(EdgeIdx);
Dec(FEdgeCount);
end;
finally
EndUpdate;
end;
end;
procedure TGraph.DeleteNode(Index: Integer);
var
i, j: Integer;
begin
CheckIndex(Index);
try
BeginUpdate;
// delete the outgoing edges and the data specific to the node
EdgeData.Delete(Index);
NodeData.Delete(Index);
// delete the incoming edges to the Index node
for i := 0 to EdgeData.Count - 1 do
for j := EdgeData[i].Count - 1 downto 0 do
if EdgeData[i][j].EndNode.Index = Index then
EdgeData[i].Delete(j);
finally
EndUpdate;
end;
end;
destructor TGraph.Destroy;
begin
FEdgeData.Free;
FNodeData.Free;
inherited;
end;
procedure TGraph.EndUpdate;
begin
if UpdateCount > 0 then
Dec(FUpdateCount);
if UpdateCount = 0 then
Update;
end;
function TGraph.FindEdge(StartIndex, EndIndex: Integer;
out Edge: TGraphEdge): Integer;
var
i: Integer;
begin
CheckIndex(StartIndex);
CheckIndex(EndIndex);
Result := -1;
for i := 0 to EdgeData[StartIndex].Count - 1do
begin
Edge := EdgeData[StartIndex][i];
if (StartIndex = Edge.StartNode.Index) and (EndIndex = Edge.EndNode.Index) then
Exit(i);
end;
end;
function TGraph.FindNode(out Node: TGraphNode; Callback: TFindGraphNodeCallback): Boolean;
var
i: Integer;
begin
Result := False;
Node := nil;
if Assigned(Callback) then
for i := 0 to NodeCount - 1 do
begin
Result := Callback(Nodes[i]);
if Result then
begin
Node := Nodes[i];
Exit(True);
end;
end;
end;
function TGraph.GetEdges(NodeIndex: Integer): TOutgoingEdges;
begin
CheckIndex(NodeIndex);
Result := EdgeData[NodeIndex];
end;
function TGraph.GetNodeCount: Integer;
begin
Result := NodeData.Count;
end;
function TGraph.GetNodes(Index: Integer): TGraphNode;
begin
CheckIndex(Index);
Result := NodeData[Index];
end;
function TGraph.GetTextHeight(const Text: String): Integer;
begin
Result := 0;
end;
function TGraph.GetTextWidth(const Text: String): Integer;
begin
Result := 0;
end;
function TGraph.RemoveEdge(Edge: TGraphEdge): Integer;
begin
CheckOwner(Edge);
CheckOwner(Edge.StartNode);
CheckIndex(Edge.StartNode.Index);
try
BeginUpdate;
Result := EdgeData[Edge.StartNode.Index].Remove(Edge);
if Result <> -1 then
Dec(FEdgeCount);
finally
EndUpdate;
end;
end;
function TGraph.RemoveNode(Node: TGraphNode): Integer;
begin
CheckOwner(Node);
Result := Node.Index;
DeleteNode(Result);
end;
procedure TGraph.Update;
begin
// descendants can write their code here
end;
{ TGraphViewData }
constructor TGraphViewGraph.Create(GraphView: TGraphView);
begin
inherited Create;
if not Assigned(GraphView) then
raise EGraphError.Create(sUnattachedGraphView);
FGraphView := GraphView;
FNodeClass := TGraphNode;
FEdgeClass := TGraphEdge;
end;
function TGraphViewGraph.GetTextHeight(const Text: String): Integer;
var
LText: String;
LRect: TRect;
begin
LText := Text;
LRect := Rect(0, 0, 0, 0);
GraphView.Canvas.TextRect(LRect, LText, [tfCalcRect]);
Result := LRect.Bottom - LRect.Top;
end;
function TGraphViewGraph.GetTextWidth(const Text: String): Integer;
begin
Result := GraphView.Canvas.TextWidth(Text);
end;
procedure TGraphViewGraph.Update;
begin
GraphView.Invalidate;
end;
{ TGraphNode }
function TGraphNode.GetContent: String;
begin
Result := FContent;
end;
function TGraphNode.GetHeight: Integer;
begin
Result := Bottom - Top;
end;
function TGraphNode.GetWidth: Integer;
begin
Result := Right - Left;
end;
procedure TGraphNode.SetCaption(const Value: String);
begin
if Value <> Caption then
begin
UpdateFitText;
inherited;
end;
end;
procedure TGraphNode.SetContent(const Value: String);
begin
if Value <> FContent then
begin
FContent := Value;
UpdateFitText;
Update;
end;
end;
procedure TGraphNode.SetFitText(const Value: Boolean);
begin
if FFitText <> Value then
begin
FFitText := Value;
UpdateFitText;
Update;
end;
end;
procedure TGraphNode.SetHeight(const Value: Integer);
var
OldKeepHeight: Boolean;
begin
if (GetHeight <> Value) and not KeepHeight then
begin
OldKeepHeight := KeepHeight;
FKeepHeight := False;
Bottom := Top + Value;
FKeepHeight := OldKeepHeight;
end;
end;
procedure TGraphNode.SetRect(const Index: TAlign; Value: Integer);
var
CurrWidth: Integer;
CurrHeight: Integer;
begin
Owner.BeginUpdate;
// store the current width and height
CurrWidth := Width;
CurrHeight := Height;
// set the field to the specified value
inherited;
// adjust the width if necessary
if KeepWidth then
case Index of
alLeft: inherited SetRect(alRight, Left + CurrWidth);
alRight: inherited SetRect(alLeft, Right - CurrWidth);
end;
// adjust the height if needed
if KeepHeight then
case Index of
alTop: inherited SetRect(alBottom, Top + CurrHeight);
alBottom: inherited SetRect(alTop, Bottom - CurrHeight);
end;
Owner.EndUpdate;
end;
procedure TGraphNode.SetWidth(const Value: Integer);
var
OldKeepWidth: Boolean;
begin
if (GetWidth <> Value) and not KeepWidth then
begin
OldKeepWidth := FKeepWidth;
FKeepWidth := False;
Right := Left + Value;
FKeepWidth := OldKeepWidth;
end;
end;
procedure TGraphNode.UpdateFitText;
var
CurrWidth: Integer;
CurrHeight: Integer;
begin
if FitText then
begin
Owner.BeginUpdate;
// store the current width and height
CurrWidth := Width;
CurrHeight := Height;
CurrWidth := Max(CurrWidth, Owner.GetTextWidth(Caption));
CurrHeight := Max(CurrHeight, Owner.GetTextHeight(Caption + sLineBreak + Content));
Rect := System.Types.Rect(Left, Top, Left + CurrWidth, Top + CurrHeight);
Owner.EndUpdate;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi LiveBindings Framework }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit BindCompDsnResStrs;
interface
resourcestring
SBindCompListEdit = '&Binding Components...';
SBindCompExpressionEdit = '&Expressions...';
SEvaluateFormat = 'Format';
SEvaluateClear = 'Clear';
SEvaluate = 'Evaluate';
SBindFillList = 'Fill List';
SBindClearList = 'Clear List';
SBindFillGrid = 'Fill Grid';
SBindClearGrid = 'Clear Grid';
sAllCollections = '(All Collections)';
SNewBindingDlgCommand = 'New LiveBinding...';
SNewDBLinkFieldDlgCommand = 'Link to DB Field...';
SNewDBLinkDataSourceDlgCommand = 'Link to DB DataSource...';
SNewDataBinding = 'New %s';
SNewDataBindingHint = 'New %s|Create new %s';
SCreateNewDataBinding = 'New Binding Component';
SDeleteDataBinding = 'Delete';
SSelectDataBinding = 'Select';
SDataBindingCategoryNone = '(No Category)';
SDataBindingCategoryAll = '(All LiveBindings)';
SDataBindingListEditorCaption = 'Editing %s%s%s';
sCaptionName = 'Name';
sCaptionOutputScope = 'Output Scope';
sCaptionOutputExpr = 'Output Expr';
sCaptionValueScope = 'Value Scope';
sCaptionValueExpr = 'Value Expr';
sCaptionControl = 'Control';
sCaptionSource = 'Source';
sCaptionOperation = 'Operation';
sAssignToControl = 'Assign to control';
sAssignToSource = 'Assign to source';
sAssignBidirectional = 'Bidirectional assignment';
sControlExpressionFor = 'Control expression for %s:';
sSourceExpressionFor = 'Source expression for %s:';
sControlExpression = 'Control expression:';
sSourceExpression = 'Source expression:';
sStringVisualizer = 'String';
sTypeVisualizer = 'Type';
sPictureVisualizer = 'Picture';
sBindLinkDescription = 'Link control "%0:s" to source "%1:s"';
sBindGridLinkDescription = 'Link grid control "%0:s" to source "%1:s"';
sBindExpressionDescription = 'Bind control "%0:s" from source "%1:s"';
sBindExprItemsDescription = 'Bind control "%0:s" from source "%1:s" (%2:d expressions)';
sBindListDescription = 'Populate list control "%0:s" from source "%1:s"';
sBindPositionDescription = 'Position link using control "%0:s" from source "%1:s"';
SConfirmDelete = 'Delete %s?';
SDeleteColumnsQuestion = 'Delete existing columns?';
SDBGridColEditor = 'Co&lumns Editor...';
sSelectAdDataSource = 'Select a data source';
sSelectAField = 'Select a field';
// Expression collection names
sParse = 'Parse';
sFormat = 'Format';
sFormatCell = 'CellFormat';
sFormatColumn = 'ColFormat';
sParseCell = 'CellParse';
sClear = 'Clear';
sPosControl = 'PosControl';
sPosSource = 'PosSource';
sPosClear = 'PosClear';
sColumns = 'Columns';
sFormatControl = 'FormatControl';
sClearControl = 'ClearControl';
sExpression = 'Expression';
implementation
end.
|
unit frmBuscar;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Grids, DBGrids, DB, ZAbstractRODataset, ZDataset, global,
Buttons;
type
Tfrm_Buscar = class(TForm)
Label9: TLabel;
tsBuscar: TEdit;
cbBusqueda: TComboBox;
GridClientes: TDBGrid;
btnSeleccionar: TButton;
btnSalir: TButton;
BuscaObjeto: TZReadOnlyQuery;
BuscaObjetosNombre: TStringField;
BuscaObjetosAP: TStringField;
BuscaObjetosAM: TStringField;
BuscaObjetosDomicilio: TStringField;
BuscaObjetosTelefono: TStringField;
BuscaObjetosCP: TStringField;
ds_buscaobjeto: TDataSource;
BuscaObjetoiIdUsuario: TIntegerField;
BuscaObjetosIdComunidad: TStringField;
BuscaObjetosNombreCompleto: TStringField;
btnInserta: TSpeedButton;
procedure btnSalirClick(Sender: TObject);
procedure btnSeleccionarClick(Sender: TObject);
procedure cbBusquedaChange(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure tsBuscarChange(Sender: TObject);
procedure GridClientesDblClick(Sender: TObject);
procedure tsBuscarKeyPress(Sender: TObject; var Key: Char);
procedure btnInsertaClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frm_Buscar: Tfrm_Buscar;
implementation
uses frmNuevoUsuario;
{$R *.dfm}
procedure Tfrm_Buscar.btnSeleccionarClick(Sender: TObject);
begin
iIdUsuarioBusqueda := BuscaObjeto.FieldByName('iIdUsuario').AsInteger ;
close
end;
procedure Tfrm_Buscar.btnSalirClick(Sender: TObject);
begin
close
end;
procedure Tfrm_Buscar.cbBusquedaChange(Sender: TObject);
var
sParametro : String ;
begin
sParametro := '%' + tsBuscar.Text + '%' ;
If cbBusqueda.Text = 'Buscar por Nombre Completo' Then
begin
BuscaObjeto.Active := False ;
BuscaObjeto.Sql.Clear ;
BuscaObjeto.Sql.Add('select * from con_catalogodeusuarios where sNombreCompleto Like :Parametro Order By sNombreCompleto, sDomicilio')
end;
If cbBusqueda.Text = 'Buscar por A. Paterno' Then
begin
BuscaObjeto.Active := False ;
BuscaObjeto.Sql.Clear ;
BuscaObjeto.Sql.Add('select * from con_catalogodeusuarios where sAP Like :Parametro Order By sNombreCompleto, sDomicilio')
end;
If cbBusqueda.Text = 'Buscar por A. Materno' Then
begin
BuscaObjeto.Active := False ;
BuscaObjeto.Sql.Clear ;
BuscaObjeto.Sql.Add('select * from con_catalogodeusuarios where sAM Like :Parametro Order By sNombreCompleto, sDomicilio')
end;
If cbBusqueda.Text = 'Buscar por Domicilio' Then
begin
BuscaObjeto.Active := False ;
BuscaObjeto.Sql.Clear ;
BuscaObjeto.Sql.Add('select * from con_catalogodeusuarios where sDomicilio Like :Parametro Order By sNombreCompleto, sDomicilio')
end;
BuscaObjeto.Params.ParamByName('Parametro').DataType := ftString ;
BuscaObjeto.Params.ParamByName('Parametro').Value := sParametro ;
BuscaObjeto.Open ;
end;
procedure Tfrm_Buscar.FormShow(Sender: TObject);
begin
cbBusqueda.ItemIndex := 0 ;
tsBuscar.Text := '' ;
if global_Usuario <> '' then
begin
BuscaObjeto.Active := False ;
BuscaObjeto.Sql.Clear ;
BuscaObjeto.Sql.Add('select * from con_catalogodeusuarios where sNombreCompleto Like :Parametro ' +
'Order By sNombreCompleto, sDomicilio') ;
BuscaObjeto.Params.ParamByName('Parametro').Value := '%%' ;
BuscaObjeto.Open ;
end;
tsBuscar.SetFocus
end;
procedure Tfrm_Buscar.GridClientesDblClick(Sender: TObject);
begin
iIdUsuarioBusqueda := BuscaObjeto.FieldValues['IIdUsuario'] ;
frm_NuevoUsuario.ShowModal ;
BuscaObjeto.Refresh ;
BuscaObjeto.Locate('iIdUsuario', iIdUsuarioBusqueda, [loCaseInsensitive]) ;
iIdUsuarioBusqueda := -1
end;
procedure Tfrm_Buscar.btnInsertaClick(Sender: TObject);
var
sParametro : String ;
begin
//####### Desabilitado Temporalmente ######
// Application.CreateForm(Tfrm_NuevoUsuario, frm_NuevoUsuario);
// frm_NuevoUsuario.ShowModal ;
// sParametro := '%' + tsBuscar.Text + '%' ;
// BuscaObjeto.Active := False ;
// BuscaObjeto.Params.ParamByName('Parametro').DataType := ftString ;
// BuscaObjeto.Params.ParamByName('Parametro').Value := sParametro ;
// BuscaObjeto.Open ;
end;
procedure Tfrm_Buscar.tsBuscarChange(Sender: TObject);
var
sParametro : String ;
begin
// sParametro := '%' + tsBuscar.Text + '%' ;
// BuscaObjeto.Active := False ;
// BuscaObjeto.Params.ParamByName('Parametro').DataType := ftString ;
// BuscaObjeto.Params.ParamByName('Parametro').Value := sParametro ;
// BuscaObjeto.Open ;
end;
procedure Tfrm_Buscar.tsBuscarKeyPress(Sender: TObject; var Key: Char);
var
sParametro : String ;
begin
if Key = #13 then
begin
// if BuscaObjeto.RecordCount > 0 then
// begin
// btnSeleccionar.Click
// end;
sParametro := '%' + tsBuscar.Text + '%' ;
BuscaObjeto.Active := False ;
BuscaObjeto.Params.ParamByName('Parametro').DataType := ftString ;
BuscaObjeto.Params.ParamByName('Parametro').Value := sParametro ;
BuscaObjeto.Open ;
end;
end;
end.
|
unit CategoryParametersGroupUnit2;
interface
uses
QueryGroupUnit2, NotifyEvents, System.Classes,
System.Generics.Collections, CategoryParametersQuery2, ParamSubParamsQuery,
SearchParamDefSubParamQuery, SearchParamSubParamQuery,
UpdateNegativeOrdQuery, FireDAC.Comp.Client, Data.DB;
type
TCategoryFDMemTable = class(TFDMemTable)
private
FInUpdate: Boolean;
function GetID: TField;
function GetIsAttribute: TField;
function GetOrd: TField;
function GetPK: TField; virtual;
function GetPosID: TField;
protected
procedure DeleteTail(AFromRecNo: Integer);
function LocateByField(const AFieldName: string; AValue: Variant;
TestResult: Boolean = False): Boolean;
public
procedure AppendFrom(ASource: TCategoryFDMemTable);
function GetFieldValues(const AFieldName: string): String;
procedure LoadRecFrom(ADataSet: TDataSet; AFieldList: TStrings);
function LocateByPK(AField: TField; AValue: Integer; TestResult: Boolean =
False): Boolean;
procedure SetOrder(AOrder: Integer);
procedure Update(ASource: TCategoryFDMemTable);
procedure UpdateFrom(ASource: TCategoryFDMemTable);
procedure UpdatePK(APKDictionary: TDictionary<Integer, Integer>);
property ID: TField read GetID;
property InUpdate: Boolean read FInUpdate;
property IsAttribute: TField read GetIsAttribute;
property Ord: TField read GetOrd;
property PK: TField read GetPK;
property PosID: TField read GetPosID;
end;
TQryCategoryParameters = class(TCategoryFDMemTable)
private
function GetIDParameter: TField;
function GetIsDefault: TField;
function GetParameterType: TField;
function GetPK: TField; override;
function GetTableName: TField;
function GetValue: TField;
function GetValueT: TField;
function GetVID: TField;
protected
public
constructor Create(AOwner: TComponent); override;
procedure AppendR(AVID, AID, AIDParameter: Integer;
const AValue, ATableName, AValueT, AParameterType: String;
AIsAttribute, AIsDefault, APosID, AOrd: Integer);
function LocateByParameterID(AIDParameter: Integer): Boolean;
function LocateByVID(AValue: Integer; TestResult: Boolean = False): Boolean;
property IDParameter: TField read GetIDParameter;
property IsDefault: TField read GetIsDefault;
property ParameterType: TField read GetParameterType;
property TableName: TField read GetTableName;
property Value: TField read GetValue;
property ValueT: TField read GetValueT;
property VID: TField read GetVID;
end;
TQryCategorySubParameters = class(TCategoryFDMemTable)
private
function GetIDParameter: TField;
function GetIDParent: TField;
function GetIDSubParameter: TField;
function GetName: TField;
function GetParamSubParamID: TField;
function GetTranslation: TField;
protected
public
constructor Create(AOwner: TComponent); override;
procedure AppendR(AID, AIDParent, AIDParameter, AParamSubParamId,
AIDSubParameter: Integer; const AName, ATranslation: String;
AIsAttribute, APosID, AOrd: Integer);
procedure DeleteByIDParent(AIDCategoryParam: Integer);
procedure FilterByIDParent(AIDCategoryParam: Integer);
procedure FilterByIDParameter(AParameterID: Integer);
function Locate2(AIDParent, AIDSubParameter: Integer;
TestResult: Boolean = False): Boolean;
property IDParameter: TField read GetIDParameter;
property IDParent: TField read GetIDParent;
property IDSubParameter: TField read GetIDSubParameter;
property Name: TField read GetName;
property ParamSubParamID: TField read GetParamSubParamID;
property Translation: TField read GetTranslation;
end;
TCategoryParametersGroup2 = class(TQueryGroup2)
private
FAfterUpdateData: TNotifyEventsEx;
FBeforeUpdateData: TNotifyEventsEx;
FDataLoading: Boolean;
FFDQCategoryParameters: TQryCategoryParameters;
FFDQCategorySubParameters: TQryCategorySubParameters;
FFullUpdate: Boolean;
FIDDic: TDictionary<Integer, Integer>;
FOnIsAttributeChange: TNotifyEventsEx;
FqCategoryParameters: TQueryCategoryParameters2;
FqCatParams: TQryCategoryParameters;
FqCatSubParams: TQryCategorySubParameters;
FqParamSubParams: TQueryParamSubParams;
FqSearchParamDefSubParam: TQuerySearchParamDefSubParam;
FqSearchParamSubParam: TQuerySearchParamSubParam;
FqUpdNegativeOrd: TQueryUpdNegativeOrd;
FVID: Integer;
procedure DoAfterOpenOrRefresh(Sender: TObject);
function GetIsAllQuerysActive: Boolean;
function GetqParamSubParams: TQueryParamSubParams;
function GetqSearchParamDefSubParam: TQuerySearchParamDefSubParam;
function GetqSearchParamSubParam: TQuerySearchParamSubParam;
function GetqUpdNegativeOrd: TQueryUpdNegativeOrd;
protected
procedure AppendParameter(AParamSubParamId, AOrd, AIsAttribute, APosID,
AIDParameter, AIDSubParameter: Integer; const AValue, ATableName, AValueT,
AParameterType, AName, ATranslation: String; AIsDefault: Integer);
procedure AppendSubParameter(AID, ASubParamID: Integer);
procedure DoOnIsAttributeChange(Sender: TField);
function GetHaveAnyChanges: Boolean; override;
function GetVirtualID(AID: Integer; AUseDic: Boolean): Integer;
property qParamSubParams: TQueryParamSubParams read GetqParamSubParams;
property qSearchParamDefSubParam: TQuerySearchParamDefSubParam
read GetqSearchParamDefSubParam;
property qSearchParamSubParam: TQuerySearchParamSubParam
read GetqSearchParamSubParam;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AddClient; override;
procedure AddOrDeleteParameters(AParamIDList: string; APosID: Integer);
procedure AddOrDeleteSubParameters(AID: Integer; ASubParamIDList: string);
function ApplyOrCancelUpdates: Boolean;
function ApplyUpdates: Boolean; override;
procedure CancelUpdates; override;
procedure DeleteParameters(APKValues: array of Integer);
procedure DeleteSubParameters(APKValues: array of Integer);
function GetIDList(AID: Integer): TArray<Integer>;
procedure LoadData;
procedure MoveParameters(IDArr: TArray<Integer>; TargetID: Integer;
AUp: Boolean);
procedure MoveSubParameters(IDArr: TArray<Integer>; TargetID: Integer; AUp:
Boolean);
procedure RefreshData; override;
procedure RemoveClient; override;
procedure SetPos(AIDArray: TArray<Integer>; AWithSubParams: Boolean;
APosID: Integer);
procedure UpdateData;
property AfterUpdateData: TNotifyEventsEx read FAfterUpdateData;
property BeforeUpdateData: TNotifyEventsEx read FBeforeUpdateData;
property IsAllQuerysActive: Boolean read GetIsAllQuerysActive;
property OnIsAttributeChange: TNotifyEventsEx read FOnIsAttributeChange;
property DataLoading: Boolean read FDataLoading;
property FullUpdate: Boolean read FFullUpdate;
property qCategoryParameters: TQueryCategoryParameters2
read FqCategoryParameters;
property qCatParams: TQryCategoryParameters read FqCatParams;
property qCatSubParams: TQryCategorySubParameters read FqCatSubParams;
property qUpdNegativeOrd: TQueryUpdNegativeOrd read GetqUpdNegativeOrd;
end;
implementation
uses
System.SysUtils, MoveHelper, System.StrUtils, System.Variants;
constructor TCategoryParametersGroup2.Create(AOwner: TComponent);
begin
inherited;
FqCategoryParameters := TQueryCategoryParameters2.Create(Self);
FFDQCategoryParameters := TQryCategoryParameters.Create(Self);
FFDQCategorySubParameters := TQryCategorySubParameters.Create(Self);
FqCatParams := TQryCategoryParameters.Create(Self);
FqCatParams.IsAttribute.OnChange := DoOnIsAttributeChange;
FqCatSubParams := TQryCategorySubParameters.Create(Self);
TNotifyEventWrap.Create(FqCategoryParameters.W.AfterOpen,
DoAfterOpenOrRefresh, EventList);
TNotifyEventWrap.Create(FqCategoryParameters.W.AfterRefresh,
DoAfterOpenOrRefresh, EventList);
FBeforeUpdateData := TNotifyEventsEx.Create(Self);
FAfterUpdateData := TNotifyEventsEx.Create(Self);
FOnIsAttributeChange := TNotifyEventsEx.Create(Self);
FIDDic := TDictionary<Integer, Integer>.Create;
end;
destructor TCategoryParametersGroup2.Destroy;
begin
FreeAndNil(FIDDic);
FreeAndNil(FBeforeUpdateData);
FreeAndNil(FAfterUpdateData);
FreeAndNil(FOnIsAttributeChange);
inherited;
end;
procedure TCategoryParametersGroup2.AddClient;
begin
FqCategoryParameters.AddClient;
end;
procedure TCategoryParametersGroup2.AddOrDeleteParameters(AParamIDList: string;
APosID: Integer);
var
AIDParam: String;
m: TArray<String>;
S: string;
begin
// Нужно добавить или удалить параметры
// Список идентификаторов параметров нашей категории, которые не имеют подпараметров!
qCategoryParameters.W.FilterByIsDefault(1);
try
S := qCategoryParameters.W.IDParameter.AllValues(',');
finally
qCategoryParameters.FDQuery.Filtered := False;
end;
m := S.Split([',']);
S := Format(',%s,', [S]);
// Цикл по параметрам для категории
for AIDParam in m do
begin
// Если галочку с одного из параметров категории сняли
if AParamIDList.IndexOf(',' + AIDParam + ',') < 0 then
begin
// Надо найти параметр без подпараметров
qCategoryParameters.W.LocateDefault(AIDParam.ToInteger, True);
DeleteParameters([qCategoryParameters.W.PK.AsInteger]);
end;
end;
m := AParamIDList.Trim([',']).Split([',']);
// Цикл по отмеченным в справочнике параметрам
for AIDParam in m do
begin
// Если галочку поставили
if S.IndexOf(',' + AIDParam + ',') < 0 then
begin
// ищем полную информацию об этом параметре
qSearchParamDefSubParam.SearchByID(AIDParam.ToInteger, 1);
// Добавляем параметр
AppendParameter(qSearchParamDefSubParam.W.ParamSubParamID.F.Value,
qCategoryParameters.NextOrder, 1, APosID,
qSearchParamDefSubParam.W.PK.Value,
qSearchParamDefSubParam.W.IDSubParameter.F.Value,
qSearchParamDefSubParam.W.Value.F.Value,
qSearchParamDefSubParam.W.TableName.F.Value,
qSearchParamDefSubParam.W.ValueT.F.Value,
qSearchParamDefSubParam.W.ParameterType.F.Value, '', '', 1);
end;
end;
LoadData;
end;
procedure TCategoryParametersGroup2.AddOrDeleteSubParameters(AID: Integer;
ASubParamIDList: string);
var
AIDParameter: Integer;
m: TArray<String>;
S: String;
S2: string;
S1: String;
begin
// Нужно добавить или удалить подпараметры
// Ищем связку категория-параметр
qCategoryParameters.W.LocateByPK(AID, True);
AIDParameter := qCategoryParameters.W.IDParameter.F.AsInteger;
// получаем все подпараметры нашего параметра
// Они могут быть расположены в разных группах!!!
S1 := Format(',%s,', [qCategoryParameters.GetAllIDSubParamList]);
// Обработка добавленных галочек - подпараметров
m := ASubParamIDList.Split([',']);
for S in m do
begin
// Если хотим добавить новый подпараметр
if S1.IndexOf(Format(',%s,', [S])) = -1 then
AppendSubParameter(AID, S.ToInteger);
end;
// Обработка снятых галочек - подпараметров
S2 := Format(',%s,', [ASubParamIDList]);
m := S1.Trim([',']).Split([',']);
for S in m do
begin
// Если хотим удалить старый подпараметр
if S2.IndexOf(Format(',%s,', [S])) = -1 then
begin
// Мы знаем код параметра и код подпараметра для удаления
// Ищем запись об удаляемом подпараметре
qCategoryParameters.W.Locate(AIDParameter, S.ToInteger, True);
// Удаляем такой подпараметр
DeleteSubParameters([qCategoryParameters.W.PK.AsInteger]);
end;
end;
LoadData;
end;
procedure TCategoryParametersGroup2.AppendParameter(AParamSubParamId, AOrd,
AIsAttribute, APosID, AIDParameter, AIDSubParameter: Integer;
const AValue, ATableName, AValueT, AParameterType, AName,
ATranslation: String; AIsDefault: Integer);
begin
FqCategoryParameters.W.AppendR(AParamSubParamId, AOrd, AIsAttribute, APosID,
AIDParameter, AIDSubParameter, AValue, ATableName, AValueT, AParameterType,
AName, ATranslation, AIsDefault);
end;
procedure TCategoryParametersGroup2.AppendSubParameter(AID,
ASubParamID: Integer);
var
ACloneW: TCategoryParameters2W;
AOrder: Integer;
APosID: Integer;
rc: Integer;
begin
Assert(AID <> 0);
Assert(ASubParamID > 0);
// Ищем связку категория-параметр
qCategoryParameters.W.LocateByPK(AID, True);
// Нужно добавить подпараметр к параметру, если у него его ещё не было
rc := qParamSubParams.SearchBySubParam
(qCategoryParameters.W.IDParameter.F.AsInteger, ASubParamID);
// Если у этого параметра нет такого подпараметра
if rc = 0 then
begin
qParamSubParams.W.AppendSubParameter
(qCategoryParameters.W.IDParameter.F.AsInteger, ASubParamID);
Assert(qParamSubParams.FDQuery.RecordCount > 0);
end;
// Выбираем полную информацию о этом подпараметре
qSearchParamSubParam.SearchByID(qParamSubParams.W.PK.Value, 1);
// Получам подпараметры текущего параметра
ACloneW := qCategoryParameters.CreateSubParamsClone;
try
// Если этот параметр ещё не имеет подпараметров
if (ACloneW.DataSet.RecordCount = 1) and
(qCategoryParameters.W.IsDefault.F.AsInteger = 1) then
begin
// Надо заменить подпараметр по умолчанию на добавляемый подпараметр
qCategoryParameters.W.TryEdit;
qCategoryParameters.W.ParamSubParamID.F.AsInteger :=
qParamSubParams.W.PK.Value;
qCategoryParameters.W.Name.F.Value := qParamSubParams.W.Name.F.Value;
qCategoryParameters.W.Translation.F.Value :=
qParamSubParams.W.Translation.F.Value;
qCategoryParameters.W.IsDefault.F.AsInteger := 0;
qCategoryParameters.W.TryPost;
end
else
begin
// Добавлять подпараметр будем в конец!
ACloneW.DataSet.Last;
// новое значение порядка
AOrder := ACloneW.Ord.F.AsInteger + 1;
APosID := qCategoryParameters.W.PosID.F.AsInteger;
// увеличим значение порядка всех параметров/подпараметров на 1.
// Они сместятся вниз!
qCategoryParameters.IncOrder(AOrder);
// Добавляем подпараметр
qCategoryParameters.W.AppendR(qSearchParamSubParam.W.PK.Value, AOrder, 1,
APosID, qSearchParamSubParam.W.IDParameter.F.Value,
qSearchParamSubParam.W.IDSubParameter.F.Value,
qSearchParamSubParam.W.Value.F.Value,
qSearchParamSubParam.W.TableName.F.Value,
qSearchParamSubParam.W.ValueT.F.Value,
qSearchParamSubParam.W.ParameterType.F.Value,
qSearchParamSubParam.W.Name.F.Value,
qSearchParamSubParam.W.Translation.F.Value,
qSearchParamSubParam.W.IsDefault.F.Value);
end;
finally
qCategoryParameters.W.DropClone(ACloneW.DataSet as TFDMemTable);
end;
end;
function TCategoryParametersGroup2.ApplyOrCancelUpdates: Boolean;
begin
Result := ApplyUpdates;
// Result := False;
// Если не удалось сохранить изменения
if not Result then
CancelUpdates;
end;
function TCategoryParametersGroup2.ApplyUpdates: Boolean;
var
AID: Integer;
AKey: Integer;
ok: Boolean;
VID: Integer;
begin
ok := not FqCategoryParameters.FDQuery.Connection.InTransaction;
Assert(ok);
// Сами начинаем транзакцию!!
FqCategoryParameters.FDQuery.Connection.StartTransaction;
// Тут все сделанные изменения применятся рекурсивно ко всей БД
FqCategoryParameters.ApplyUpdates;
// Проверяем, успешно ли
Result := not FqCategoryParameters.HaveAnyChanges;
if not Result then
begin
FqCategoryParameters.FDQuery.Connection.Rollback;
Exit;
end;
// Меняем отрицательный порядок на положительный!
qUpdNegativeOrd.FDQuery.ExecSQL;
if FqCategoryParameters.PKDictionary.Count > 0 then
begin
// Тут надо обновить виртуальные идентификаторы на реальные
FFDQCategoryParameters.UpdatePK(FqCategoryParameters.PKDictionary);
FFDQCategorySubParameters.UpdatePK(FqCategoryParameters.PKDictionary);
qCatParams.UpdatePK(FqCategoryParameters.PKDictionary);
qCatSubParams.UpdatePK(FqCategoryParameters.PKDictionary);
for AKey in FqCategoryParameters.PKDictionary.Keys do
begin
// Если такой ключ принадлежит подпараметру
if not FIDDic.ContainsKey(AKey) then
Continue;
AID := FqCategoryParameters.PKDictionary[AKey];
// Новый ключ БД -> VID
VID := FIDDic[AKey];
FIDDic.Add(AID, VID);
FIDDic.Remove(AKey);
end;
end;
FqCategoryParameters.FDQuery.Connection.Commit;
ok := not FqCategoryParameters.FDQuery.Connection.InTransaction;
Assert(ok);
end;
procedure TCategoryParametersGroup2.CancelUpdates;
begin
// Тут все сделанные изменения отменяются
FqCategoryParameters.CancelUpdates;
LoadData;
end;
procedure TCategoryParametersGroup2.DeleteParameters
(APKValues: array of Integer);
var
ACloneW: TCategoryParameters2W;
AID: Integer;
begin
for AID in APKValues do
begin
qCategoryParameters.W.LocateByPK(AID);
// Получаем все подпараметры, относящиеся к текущей записи
ACloneW := qCategoryParameters.CreateSubParamsClone;
try
// Удаляем всё
ACloneW.DeleteAll;
finally
qCategoryParameters.W.DropClone(ACloneW.DataSet as TFDMemTable);
end;
end;
LoadData;
end;
procedure TCategoryParametersGroup2.DeleteSubParameters
(APKValues: array of Integer);
var
ACloneW: TCategoryParameters2W;
AID: Integer;
VID: Integer;
begin
for AID in APKValues do
begin
qCategoryParameters.W.LocateByPK(AID, True);
ACloneW := qCategoryParameters.CreateSubParamsClone;
try
// Если этот параметр имел единстенный подпараметр
if ACloneW.DataSet.RecordCount = 1 then
begin
// Выбираем информацию о том, какой подпараметр "по умолчанию" у нашего параметра
qSearchParamDefSubParam.SearchByID
(qCategoryParameters.W.IDParameter.F.AsInteger, 1);
qCategoryParameters.W.TryEdit;
// Меняем ссылку на связанный с параметром подпараметр
qCategoryParameters.W.ParamSubParamID.F.Value :=
qSearchParamDefSubParam.W.ParamSubParamID.F.Value;
qCategoryParameters.W.IDSubParameter.F.Value :=
qSearchParamDefSubParam.W.IDSubParameter.F.Value;
qCategoryParameters.W.IsDefault.F.AsInteger := 1;
qCategoryParameters.W.Name.F.Value :=
qSearchParamDefSubParam.W.Name.F.Value;
qCategoryParameters.W.Translation.F.Value :=
qSearchParamDefSubParam.W.Translation.F.Value;
qCategoryParameters.W.TryPost;
end
else
begin
// Удаляем подпараметр;
qCategoryParameters.FDQuery.Delete;
Assert(ACloneW.DataSet.RecordCount > 0);
// Если мы удалили первый подпараметр
if FIDDic.ContainsKey(AID) then
begin
// Виртуальный ID соотв. удалённому
VID := FIDDic[AID];
FIDDic.Remove(AID);
// Добавляем идентификатор первого подпараметра
FIDDic.Add(ACloneW.ID.F.AsInteger, VID);
end;
end;
finally
qCategoryParameters.W.DropClone(ACloneW.DataSet as TFDMemTable);
end;
end;
LoadData;
end;
procedure TCategoryParametersGroup2.DoAfterOpenOrRefresh(Sender: TObject);
begin
FVID := 0;
FIDDic.Clear;
FFullUpdate := True;
try
LoadData;
finally
FFullUpdate := False;
end;
end;
procedure TCategoryParametersGroup2.DoOnIsAttributeChange(Sender: TField);
begin
if qCatParams.InUpdate then
Exit;
// Выполняем изменения в плоском наборе данных
qCategoryParameters.SetIsAttribute(qCatParams.ID.AsInteger,
qCatParams.IsAttribute.AsInteger);
LoadData;
FOnIsAttributeChange.CallEventHandlers(Self);
end;
function TCategoryParametersGroup2.GetHaveAnyChanges: Boolean;
begin
Result := qCategoryParameters.HaveAnyChanges;
end;
function TCategoryParametersGroup2.GetIDList(AID: Integer): TArray<Integer>;
var
ACloneW: TCategoryParameters2W;
L: TList<Integer>;
begin
Assert(AID > 0);
// Хотябы одна группа должна существовать
Assert(qCategoryParameters.FDQuery.RecordCount > 0);
L := TList<Integer>.Create;
try
qCategoryParameters.W.LocateByPK(AID, True);
ACloneW := qCategoryParameters.CreateSubParamsClone;
try
// Составляем список идентификаторов текущего бэнда
while not ACloneW.DataSet.Eof do
begin
L.Add(ACloneW.ID.F.AsInteger);
ACloneW.DataSet.Next;
end;
Result := L.ToArray;
finally
qCategoryParameters.W.DropClone(ACloneW.DataSet as TFDMemTable);
end;
finally
FreeAndNil(L);
end;
end;
function TCategoryParametersGroup2.GetIsAllQuerysActive: Boolean;
begin
Result := qCategoryParameters.FDQuery.Active and
FFDQCategoryParameters.Active and FFDQCategorySubParameters.Active;
end;
function TCategoryParametersGroup2.GetqParamSubParams: TQueryParamSubParams;
begin
if FqParamSubParams = nil then
FqParamSubParams := TQueryParamSubParams.Create(Self);
Result := FqParamSubParams;
end;
function TCategoryParametersGroup2.GetqSearchParamDefSubParam
: TQuerySearchParamDefSubParam;
begin
if FqSearchParamDefSubParam = nil then
FqSearchParamDefSubParam := TQuerySearchParamDefSubParam.Create(Self);
Result := FqSearchParamDefSubParam;
end;
function TCategoryParametersGroup2.GetqSearchParamSubParam
: TQuerySearchParamSubParam;
begin
if FqSearchParamSubParam = nil then
FqSearchParamSubParam := TQuerySearchParamSubParam.Create(Self);
Result := FqSearchParamSubParam;
end;
function TCategoryParametersGroup2.GetqUpdNegativeOrd: TQueryUpdNegativeOrd;
begin
if FqUpdNegativeOrd = nil then
FqUpdNegativeOrd := TQueryUpdNegativeOrd.Create(Self);
Result := FqUpdNegativeOrd;
end;
function TCategoryParametersGroup2.GetVirtualID(AID: Integer;
AUseDic: Boolean): Integer;
begin
Assert(not AUseDic or (AUseDic and (FIDDic.Count > 0)));
// Если значение виртуального идентификатора берём из словаря
if AUseDic and FIDDic.ContainsKey(AID) then
begin
Result := FIDDic[AID]
end
else
begin
// В словаре такой записи нет. Видимо эту запись добавили
Assert(FVID >= 0);
Inc(FVID);
FIDDic.Add(AID, FVID);
Result := FVID;
end;
end;
procedure TCategoryParametersGroup2.LoadData;
var
AFieldList: TStringList;
AUseDic: Boolean;
VID: Integer;
begin
AUseDic := FIDDic.Count > 0;
AFieldList := TStringList.Create;
try
FFDQCategorySubParameters.EmptyDataSet;
FFDQCategoryParameters.EmptyDataSet;
FFDQCategoryParameters.Fields.GetFieldNames(AFieldList);
// Эти поля могут отличаться при группировке
AFieldList.Delete(AFieldList.IndexOf(FFDQCategoryParameters.ID.FieldName));
AFieldList.Delete
(AFieldList.IndexOf(FFDQCategoryParameters.IsAttribute.FieldName));
AFieldList.Delete(AFieldList.IndexOf(FFDQCategoryParameters.Ord.FieldName));
Assert(AFieldList.Count > 0);
qCategoryParameters.FDQuery.DisableControls;
try
qCategoryParameters.FDQuery.First;
FFDQCategoryParameters.First;
while not qCategoryParameters.FDQuery.Eof do
begin
FFDQCategoryParameters.LoadRecFrom(qCategoryParameters.FDQuery,
AFieldList);
if FFDQCategoryParameters.ID.IsNull then
begin
VID := GetVirtualID(qCategoryParameters.W.PK.AsInteger, AUseDic);
FFDQCategoryParameters.Edit;
FFDQCategoryParameters.VID.AsInteger := VID;
FFDQCategoryParameters.ID.AsInteger :=
qCategoryParameters.W.PK.AsInteger;
FFDQCategoryParameters.IsAttribute.Value :=
qCategoryParameters.W.IsAttribute.F.Value;
FFDQCategoryParameters.Ord.Value := qCategoryParameters.W.Ord.F.Value;
FFDQCategoryParameters.Post;
end;
if qCategoryParameters.W.IsDefault.F.AsInteger = 0 then
begin
FFDQCategorySubParameters.LoadRecFrom
(qCategoryParameters.FDQuery, nil);
FFDQCategorySubParameters.Edit;
FFDQCategorySubParameters.IDParent.AsInteger :=
FFDQCategoryParameters.VID.AsInteger;
FFDQCategorySubParameters.Post;
end;
qCategoryParameters.FDQuery.Next;
end;
finally
qCategoryParameters.FDQuery.EnableControls;
end;
finally
FreeAndNil(AFieldList);
end;
UpdateData;
end;
procedure TCategoryParametersGroup2.MoveParameters(IDArr: TArray<Integer>;
TargetID: Integer; AUp: Boolean);
var
ACloneW: TCategoryParameters2W;
AID: Integer;
L: TDictionary<Integer, Integer>;
ACount: Integer;
AIDList: TList<Integer>;
begin
Assert(Length(IDArr) > 0);
Assert(TargetID <> 0);
ACount := 0;
AIDList := TList<Integer>.Create();
L := TDictionary<Integer, Integer>.Create;
try
AIDList.AddRange(IDArr);
AIDList.Add(TargetID);
for AID in AIDList do
begin
if AID = TargetID then
ACount := L.Count; // Количество переносимых записей
qCategoryParameters.W.LocateByPK(AID, True);
ACloneW := qCategoryParameters.CreateSubParamsClone;
try
while not ACloneW.DataSet.Eof do
begin
L.Add(ACloneW.ID.F.AsInteger, ACloneW.Ord.F.AsInteger);
ACloneW.DataSet.Next;
end;
finally
qCategoryParameters.W.DropClone(ACloneW.DataSet as TFDMemTable);
end;
end;
qCategoryParameters.W.Move(TMoveHelper.Move(L.ToArray, AUp, ACount));
finally
FreeAndNil(L);
FreeAndNil(AIDList);
end;
LoadData;
end;
procedure TCategoryParametersGroup2.MoveSubParameters(IDArr: TArray<Integer>;
TargetID: Integer; AUp: Boolean);
var
ACloneW: TCategoryParameters2W;
AID: Integer;
L: TDictionary<Integer, Integer>;
ACount: Integer;
AIDList: TList<Integer>;
ANewID: Integer;
AVID: Integer;
begin
Assert(Length(IDArr) > 0);
Assert(TargetID <> 0);
ACount := 0;
AIDList := TList<Integer>.Create();
L := TDictionary<Integer, Integer>.Create;
try
AIDList.AddRange(IDArr);
AIDList.Add(TargetID);
for AID in AIDList do
begin
if AID = TargetID then
ACount := L.Count; // Количество переносимых записей
qCategoryParameters.W.LocateByPK(AID, True);
L.Add(qCategoryParameters.W.PK.Value, qCategoryParameters.W.Ord.F.Value);
end;
ACloneW := qCategoryParameters.CreateSubParamsClone;
try
// Идентификатор первого подпараметра
AID := ACloneW.ID.F.AsInteger;
// Просим произвести перенос
qCategoryParameters.W.Move(TMoveHelper.Move(L.ToArray, AUp, ACount));
ANewID := ACloneW.ID.F.AsInteger;
finally
qCategoryParameters.W.DropClone(ACloneW.DataSet as TFDMemTable);
end;
// Если в ходе перемещения, на первое место встал другой подпараметр
if ANewID <> AID then
begin
AVID := FIDDic[AID];
FIDDic.Add(ANewID, AVID);
FIDDic.Remove(AID);
end;
finally
FreeAndNil(L);
FreeAndNil(AIDList);
end;
LoadData;
end;
procedure TCategoryParametersGroup2.RefreshData;
begin
qCategoryParameters.W.RefreshQuery;
LoadData;
end;
procedure TCategoryParametersGroup2.RemoveClient;
begin
FqCategoryParameters.RemoveClient;
end;
procedure TCategoryParametersGroup2.SetPos(AIDArray: TArray<Integer>;
AWithSubParams: Boolean; APosID: Integer);
var
ACloneW: TCategoryParameters2W;
AID: Integer;
AIDList: TList<Integer>;
begin
AIDList := TList<Integer>.Create;
try
for AID in AIDArray do
begin
qCategoryParameters.W.LocateByPK(AID);
if AWithSubParams then
begin
ACloneW := qCategoryParameters.CreateSubParamsClone;
try
while not ACloneW.DataSet.Eof do
begin
AIDList.Add(ACloneW.ID.F.AsInteger);
ACloneW.DataSet.Next;
end;
finally
qCategoryParameters.W.DropClone(ACloneW.DataSet as TFDMemTable);
end;
end
else
AIDList.Add(qCategoryParameters.W.PK.AsInteger);
end;
// Просим изменить положение всех этих записей
qCategoryParameters.W.SetPos(AIDList.ToArray, APosID);
finally
FreeAndNil(AIDList);
end;
LoadData;
end;
procedure TCategoryParametersGroup2.UpdateData;
begin
FDataLoading := True;
FBeforeUpdateData.CallEventHandlers(Self);
try
qCatParams.Update(FFDQCategoryParameters);
qCatSubParams.Update(FFDQCategorySubParameters);
finally
FAfterUpdateData.CallEventHandlers(Self);
FDataLoading := False;
end;
end;
procedure TCategoryFDMemTable.AppendFrom(ASource: TCategoryFDMemTable);
var
F: TField;
begin
Assert(ASource <> nil);
Append;
for F in Fields do
F.Value := ASource.FieldByName(F.FieldName).Value;
Post;
end;
procedure TCategoryFDMemTable.DeleteTail(AFromRecNo: Integer);
begin
if RecordCount < AFromRecNo then
Exit;
DisableControls;
try
while RecordCount >= AFromRecNo do
begin
RecNo := AFromRecNo;
Delete;
end;
finally
EnableControls;
end;
end;
function TCategoryFDMemTable.GetFieldValues(const AFieldName: string): String;
begin
Result := '';
First;
while not Eof do
begin
Result := Result + IfThen(Result <> '', ',', '') +
FieldByName(AFieldName).AsString;
Next;
end;
end;
function TCategoryFDMemTable.GetID: TField;
begin
Result := FieldByName('ID');
end;
function TCategoryFDMemTable.GetIsAttribute: TField;
begin
Result := FieldByName('IsAttribute');
end;
function TCategoryFDMemTable.GetOrd: TField;
begin
Result := FieldByName('Ord');
end;
function TCategoryFDMemTable.GetPK: TField;
begin
Result := ID;
end;
function TCategoryFDMemTable.GetPosID: TField;
begin
Result := FieldByName('PosID');
end;
procedure TCategoryFDMemTable.LoadRecFrom(ADataSet: TDataSet;
AFieldList: TStrings);
var
AFieldName: String;
AFL: TStrings;
AUF: TDictionary<String, Variant>;
F: TField;
FF: TField;
NeedEdit: Boolean;
begin
Assert(ADataSet <> nil);
Assert(ADataSet.RecordCount > 0);
if AFieldList = nil then
begin
AFL := TStringList.Create;
ADataSet.Fields.GetFieldNames(AFL);
end
else
AFL := AFieldList;
Assert(AFL.Count > 0);
NeedEdit := False;
AUF := TDictionary<String, Variant>.Create;
try
// Цикл по всем полям
for F in ADataSet.Fields do
begin
if AFL.IndexOf(F.FieldName) = -1 then
Continue;
FF := FindField(F.FieldName);
if (FF <> nil) then
begin
NeedEdit := NeedEdit or (FF.Value <> F.Value);
AUF.Add(FF.FieldName, F.Value);
end;
end;
// Если есть отличающиеся заначения
if NeedEdit then
begin
Append;
for AFieldName in AUF.Keys do
begin
FieldByName(AFieldName).Value := AUF[AFieldName];
end;
Post;
end;
finally
FreeAndNil(AUF);
if AFieldList = nil then
FreeAndNil(AFL);
end;
end;
function TCategoryFDMemTable.LocateByField(const AFieldName: string;
AValue: Variant; TestResult: Boolean = False): Boolean;
begin
Assert(not AFieldName.IsEmpty);
Result := LocateEx(AFieldName, AValue);
if TestResult then
Assert(Result);
end;
function TCategoryFDMemTable.LocateByPK(AField: TField; AValue: Integer;
TestResult: Boolean = False): Boolean;
begin
Assert(AValue <> 0);
Result := LocateEx(AField.FieldName, AValue);
if TestResult then
Assert(Result);
end;
procedure TCategoryFDMemTable.SetOrder(AOrder: Integer);
begin
Assert(AOrder > 0);
Assert(RecordCount > 0);
Edit;
Ord.AsInteger := AOrder;
Post;
end;
procedure TCategoryFDMemTable.Update(ASource: TCategoryFDMemTable);
var
AID: Integer;
begin
Assert(ASource <> nil);
DisableControls;
try
FInUpdate := True; // Ставим флаг сигнализирующий о том, что мы обновляемся
AID := PK.AsInteger;
ASource.First;
while not ASource.Eof do
begin
// Если такой записи у нас ещё нет
if not LocateByPK(ID, ASource.ID.AsInteger) then
AppendFrom(ASource)
else
UpdateFrom(ASource);
ASource.Next;
end;
// Удаляем то, чего уже нет
First;
while not Eof do
begin
if not ASource.LocateByPK(ASource.ID, ID.AsInteger) then
Delete
else
Next;
end;
if AID <> 0 then
LocateByPK(PK, AID);
finally
FInUpdate := False;
EnableControls;
end;
end;
procedure TCategoryFDMemTable.UpdateFrom(ASource: TCategoryFDMemTable);
var
AFieldName: string;
F: TField;
UpdatedFields: TDictionary<String, Variant>;
begin
UpdatedFields := TDictionary<String, Variant>.Create;
try
Assert(ASource <> nil);
for F in Fields do
begin
if F.Value <> ASource.FieldByName(F.FieldName).Value then
UpdatedFields.Add(F.FieldName, ASource.FieldByName(F.FieldName).Value);
end;
if UpdatedFields.Count > 0 then
begin
// Производим обновление записи
Edit;
for AFieldName in UpdatedFields.Keys do
FieldByName(AFieldName).Value := UpdatedFields[AFieldName];
Post;
end;
finally
FreeAndNil(UpdatedFields)
end;
end;
procedure TCategoryFDMemTable.UpdatePK(APKDictionary
: TDictionary<Integer, Integer>);
var
AClone: TFDMemTable;
AField: TField;
AID: Integer;
begin
AClone := TFDMemTable.Create(Self);
try
AClone.CloneCursor(Self);
AField := AClone.FieldByName(ID.FieldName);
for AID in APKDictionary.Keys do
begin
if not AClone.LocateEx(ID.FieldName, AID) then
Continue;
AClone.Edit;
AField.AsInteger := APKDictionary[AField.AsInteger];
AClone.Post;
end;
finally
FreeAndNil(AClone);
end;
end;
constructor TQryCategoryParameters.Create(AOwner: TComponent);
begin
inherited;
FieldDefs.Add('VID', ftInteger);
FieldDefs.Add('ID', ftInteger);
FieldDefs.Add('IDParameter', ftInteger);
FieldDefs.Add('Value', ftWideString, 200);
FieldDefs.Add('TableName', ftWideString, 200);
FieldDefs.Add('ValueT', ftWideString, 200);
FieldDefs.Add('ParameterType', ftWideString, 30);
FieldDefs.Add('IsAttribute', ftInteger);
FieldDefs.Add('IsDefault', ftInteger);
FieldDefs.Add('PosID', ftInteger);
FieldDefs.Add('Ord', ftInteger);
CreateDataSet;
IndexFieldNames := Format('%s;%s', [PosID.FieldName, Ord.FieldName]);
end;
procedure TQryCategoryParameters.AppendR(AVID, AID, AIDParameter: Integer;
const AValue, ATableName, AValueT, AParameterType: String;
AIsAttribute, AIsDefault, APosID, AOrd: Integer);
begin
Append;
VID.Value := AVID;
ID.Value := AID;
IDParameter.Value := AIDParameter;
Value.Value := AValue;
TableName.Value := ATableName;
ValueT.Value := AValueT;
ParameterType.Value := AParameterType;
IsAttribute.Value := AIsAttribute;
IsDefault.Value := AIsDefault;
PosID.Value := APosID;
Ord.AsInteger := AOrd;
Post;
end;
function TQryCategoryParameters.GetIDParameter: TField;
begin
Result := FieldByName('IDParameter');
end;
function TQryCategoryParameters.GetIsDefault: TField;
begin
Result := FieldByName('IsDefault');
end;
function TQryCategoryParameters.GetParameterType: TField;
begin
Result := FieldByName('ParameterType');
end;
function TQryCategoryParameters.GetPK: TField;
begin
Result := VID;
end;
function TQryCategoryParameters.GetTableName: TField;
begin
Result := FieldByName('TableName');
end;
function TQryCategoryParameters.GetValue: TField;
begin
Result := FieldByName('Value');
end;
function TQryCategoryParameters.GetValueT: TField;
begin
Result := FieldByName('ValueT');
end;
function TQryCategoryParameters.GetVID: TField;
begin
Result := FieldByName('VID');
end;
function TQryCategoryParameters.LocateByParameterID(AIDParameter
: Integer): Boolean;
begin
Assert(AIDParameter > 0);
Result := LocateEx(IDParameter.FieldName, AIDParameter);
end;
function TQryCategoryParameters.LocateByVID(AValue: Integer;
TestResult: Boolean = False): Boolean;
begin
Assert(AValue <> 0);
Result := LocateEx(VID.FieldName, AValue);
if TestResult then
Assert(Result);
end;
constructor TQryCategorySubParameters.Create(AOwner: TComponent);
begin
inherited;
FieldDefs.Add('ID', ftInteger);
FieldDefs.Add('IDParent', ftInteger);
FieldDefs.Add('IDParameter', ftInteger);
FieldDefs.Add('ParamSubParamID', ftInteger);
FieldDefs.Add('IDSubParameter', ftInteger);
FieldDefs.Add('Name', ftWideString, 200);
FieldDefs.Add('Translation', ftWideString, 200);
FieldDefs.Add('IsAttribute', ftInteger);
FieldDefs.Add('PosID', ftInteger);
FieldDefs.Add('Ord', ftInteger);
CreateDataSet;
IndexFieldNames := Format('%s;%s;%s', [IDParent.FieldName, PosID.FieldName,
Ord.FieldName]);
end;
procedure TQryCategorySubParameters.AppendR(AID, AIDParent, AIDParameter,
AParamSubParamId, AIDSubParameter: Integer; const AName, ATranslation: String;
AIsAttribute, APosID, AOrd: Integer);
begin
Append;
ID.Value := AID;
IDParent.Value := AIDParent;
IDParameter.Value := AIDParameter;
ParamSubParamID.Value := AParamSubParamId;
IDSubParameter.Value := AIDSubParameter;
Name.Value := AName;
Translation.Value := ATranslation;
IsAttribute.Value := AIsAttribute;
PosID.Value := APosID;
Ord.AsInteger := AOrd;
Post;
end;
procedure TQryCategorySubParameters.DeleteByIDParent(AIDCategoryParam: Integer);
begin
Assert(AIDCategoryParam > 0);
DisableControls;
try
while LocateEx(IDParent.FieldName, AIDCategoryParam) do
Delete;
finally
EnableControls;
end;
end;
procedure TQryCategorySubParameters.FilterByIDParent(AIDCategoryParam: Integer);
begin
Assert(AIDCategoryParam <> 0);
Filter := Format('%s = %d', [IDParent.FieldName, AIDCategoryParam]);
Filtered := True;
end;
procedure TQryCategorySubParameters.FilterByIDParameter(AParameterID: Integer);
begin
Assert(AParameterID <> 0);
Filter := Format('%s = %d', [IDParameter.FieldName, AParameterID]);
Filtered := True;
end;
function TQryCategorySubParameters.GetIDParameter: TField;
begin
Result := FieldByName('IDParameter');
end;
function TQryCategorySubParameters.GetIDParent: TField;
begin
Result := FieldByName('IDParent');
end;
function TQryCategorySubParameters.GetIDSubParameter: TField;
begin
Result := FieldByName('IDSubParameter');
end;
function TQryCategorySubParameters.GetName: TField;
begin
Result := FieldByName('Name');
end;
function TQryCategorySubParameters.GetParamSubParamID: TField;
begin
Result := FieldByName('ParamSubParamID');
end;
function TQryCategorySubParameters.GetTranslation: TField;
begin
Result := FieldByName('Translation');
end;
function TQryCategorySubParameters.Locate2(AIDParent, AIDSubParameter: Integer;
TestResult: Boolean = False): Boolean;
var
AFieldNames: string;
begin
Assert(AIDParent > 0);
Assert(AIDSubParameter > 0);
AFieldNames := Format('%s;%s', [IDParent.FieldName,
IDSubParameter.FieldName]);
Result := LocateEx(AFieldNames, VarArrayOf([AIDParent, AIDSubParameter]));
if TestResult then
Assert(Result);
end;
end.
|
unit rhlFNV1a64;
interface
uses
rhlCore;
type
{ TrhlFNV1a64 }
TrhlFNV1a64 = class(TrhlHash)
private
m_hash: QWord;
protected
procedure UpdateBytes(const ABuffer; ASize: LongWord); override;
public
constructor Create; override;
procedure Init; override;
procedure Final(var ADigest); override;
end;
implementation
{ TrhlFNV1a64 }
procedure TrhlFNV1a64.UpdateBytes(const ABuffer; ASize: LongWord);
var
b: PByte;
begin
b := @ABuffer;
while ASize > 0 do
begin
m_hash := (m_hash xor b^) * 1099511628211;
Inc(b);
Dec(ASize);
end;
end;
constructor TrhlFNV1a64.Create;
begin
HashSize := 8;
BlockSize := 1;
end;
procedure TrhlFNV1a64.Init;
begin
inherited Init;
m_hash := 14695981039346656037;
end;
procedure TrhlFNV1a64.Final(var ADigest);
begin
Move(m_hash, ADigest, SizeOf(m_hash));
end;
end.
|
unit uAction_b;
interface
uses
uQueryServer_a, uQueryCommon_a, uConst_h,
Classes, SyncObjs;
type
TAction_b = class(TAction_a)
private
...
protected
property Request: TMessage_a read FRequest write setRequest;
property Status: integer read FStatus write FStatus;
property AbortAction: boolean read FAbortAction write SetAbortAction;
public
function RemoveAfterExecute: Boolean; override;
function HasFatalError(var AStatusCode: Integer): Boolean; override;
procedure Abort; override;
function IsAborted: Boolean; override;
property ProviderID: Integer read FProviderID;
function EnterLock(ALockList: TActionLockList_a): Boolean; override;
procedure LeaveLock(ALockList: TActionLockList_a); override;
function GetRequestValue(AParam: string): Variant;
procedure Log(const AMsg: string; const ALogKey: Integer = CltLog;
const ASendToClient: Boolean = True; const AStatusCode: Integer = CAH_OK); overload;
procedure OnRequestDeleted; override;
end;
implementation
uses
uStubManager_a, uQueryServer,
uFileUtil, Variants;
//----------------------------------------------------------------------------
// N,PS:
function TAction_b.HasFatalError(var AStatusCode: Integer): Boolean;
begin
// no inherited (abstract)
Result := false;
AStatusCode := COK;
end;
//----------------------------------------------------------------------------
// N,PS:
function TAction_b.GetRequestValue(AParam: string): variant;
begin
// no inherited (private)
Result := Request.GetParamValue(AParam);
if Result = unassigned then
begin
Log(SErrorWhileGettingRequestValue);
AbortAction := True;
raise EUsrInfo.fireFmt(Self, SAutoRSMandatoryRequestParamNotSet,
[AParam]);
end;
end;
//----------------------------------------------------------------------------
// N,PS T475:
procedure TAction_b.Log(const AMsg, ANonTranslatedMsg: string; Args: array of const;
const ALogKey: Integer = CltLog; const ASendToClient: Boolean = True;
const AStatusCode: Integer = CAH_OK);
var
lTranslated, lNonTranslated: string;
begin
lTranslated := Fmt(AMsg, Args);
lNonTranslated := Fmt(ANonTranslatedMsg, Args);
LogToLog(lNonTranslated, ALogKey);
if ASendToClient then
LogToClient(lTranslated, AStatusCode);
end;
//----------------------------------------------------------------------------
// N,PS T475: split from log
procedure TAction_b.LogToClient(const AMsg: string; const AStatusCode: Integer = COK);
var
lServerStub_a: TServerStub_a;
lEvent: TNotifyEvent;
lResult: Boolean;
begin
lServerStub_a := StubManager.GetServerStub;
if lServerStub_a is TServer then
begin
lEvent := TServer(lServerStub_a).GetNotifyEvent(...);
if Assigned(lEvent) then
begin
lEvent(ntRequestMessage, AStatusCode, AMsg, lResult);
// Nothing to do with lResult since this is just a logmessage.
end;
end
else
raise EIntern.Fire(Self, 'Implementation of TServerStub_a is not a TServer');
end;
//----------------------------------------------------------------------------
// N,PS:
function TAction_b.RemoveAfterExecute: Boolean;
begin
// no inherited (abstract)
Result := true;
end;
end.
|
unit mCoverSheetDisplayPanel_CPRS;
{
================================================================================
*
* Application: CPRS - CoverSheet
* Developer: doma.user@domain.ext
* Site: Salt Lake City ISC
* Date: 2015-12-04
*
* Description: Inherited from TfraCoverSheetDisplayPanel. This display
* panel provides the minimum functionality for displaying
* CPRS data in the CoverSheet.
*
* Notes: This frame is an ancestor object and heavily inherited from.
* ABSOLUTELY NO CHANGES SHOULD BE MADE WITHOUT FIRST
* CONFERRING WITH THE CPRS DEVELOPMENT TEAM ABOUT POSSIBLE
* RAMIFICATIONS WITH DESCENDANT FRAMES.
*
================================================================================
}
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
System.UITypes,
System.ImageList,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.Menus,
Vcl.ImgList,
Vcl.StdCtrls,
Vcl.Buttons,
Vcl.ExtCtrls,
Vcl.ComCtrls,
mCoverSheetDisplayPanel,
iCoverSheetIntf,
iGridPanelIntf,
oDelimitedString,
mGridPanelFrame;
type
TfraCoverSheetDisplayPanel_CPRS = class(TfraCoverSheetDisplayPanel, ICoverSheetDisplayPanel)
tmr: TTimer;
lvData: TListView;
procedure lvDataEnter(Sender: TObject);
procedure lvDataExit(Sender: TObject);
procedure lvDataMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer);
procedure lvDataSelectItem(Sender: TObject; Item: TListItem; Selected: boolean);
procedure tmrTimer(Sender: TObject);
procedure lvDataKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
{ Private declarations }
procedure DisplayItemDetail(Sender: TObject; aItem: TListItem; Button: TMouseButton);
protected
fBackgroundLoading: boolean;
fBackgroundLoadTry: integer;
fFinished: boolean;
fColumns: TStringList;
fLastItemIndex: integer;
fAllowDetailDisplay: boolean;
{ Overridden events - TfraGridPanelFrame }
procedure OnSetFontSize(Sender: TObject; aNewSize: integer); override;
procedure OnPopupMenu(Sender: TObject); override;
procedure OnPopupMenuInit(Sender: TObject); override;
procedure OnRefreshDisplay(Sender: TObject); override; final;
procedure OnLoadError(Sender: TObject; E: Exception); override; final;
procedure OnShowError(Sender: TObject); override; final;
{ Overridden events - TfraCoverSheetDisplayPanel }
procedure OnBeginUpdate(Sender: TObject); override;
procedure OnClearPtData(Sender: TObject); override;
procedure OnEndUpdate(Sender: TObject); override;
{ Overridden methods - TfraCoverSheetDisplayPanel }
function getIsFinishedLoading: boolean; override;
{ Introduced events }
procedure OnStartBackgroundLoad(Sender: TObject); virtual;
procedure OnCompleteBackgroundLoad(Sender: TObject); virtual;
procedure OnAddItems(aList: TStrings); virtual;
procedure OnGetDetail(aRec: TDelimitedString; aResult: TStrings); virtual;
procedure OnShowDetail(aText: TStrings; aTitle: string = ''; aPrintable: boolean = false); virtual;
{ Introduced methods }
function AddColumn(aIndex: integer; aCaption: string): integer; virtual; final;
function ClearListView(aListView: TListView): boolean; virtual;
function CollapseColumns: integer; virtual; final;
function ExpandColumns: integer; virtual; final;
function ListViewItemIEN: integer; virtual;
function ListViewItemRec: TDelimitedString; virtual;
function CPRSParams: ICoverSheetParam_CPRS; virtual; final;
procedure SetListViewColumn(aIndex: integer; aCaption: string; aAutoSize: boolean; aWidth: integer); virtual;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
end;
var
fraCoverSheetDisplayPanel_CPRS: TfraCoverSheetDisplayPanel_CPRS;
implementation
{$R *.dfm}
{ fraCoverSheetDisplayPanel_CPRS }
uses
uCore,
uConst,
fRptBox,
DateUtils,
ORFn,
ORNet,
VAUtils;
const
UPDATING_FOREGROUND = 'Updating ...';
UPDATING_BACKGROUND = 'Loading in Background ...';
UPDATING_FAILURE = 'Update failed.';
UPDATING_ATTEMPTS = 100; // Max try to get data from background job
UPDATING_WAIT_TIME = 3000; // milliseconds
constructor TfraCoverSheetDisplayPanel_CPRS.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
with lvData do
begin
ShowColumnHeaders := false;
ViewStyle := vsReport;
readonly := True;
RowSelect := True;
Columns.Add.AutoSize := True;
end;
fColumns := TStringList.Create;
fLastItemIndex := -1;
fAllowDetailDisplay := True;
tmr.Interval := UPDATING_WAIT_TIME;
tmr.Enabled := false;
end;
destructor TfraCoverSheetDisplayPanel_CPRS.Destroy;
begin
ClearListView(lvData);
FreeAndNil(fColumns);
inherited;
end;
function TfraCoverSheetDisplayPanel_CPRS.ClearListView(aListView: TListView): boolean;
begin
aListView.Items.BeginUpdate;
try
while aListView.Items.Count > 0 do
begin
if aListView.Items[0].Data <> nil then
try
TObject(aListView.Items[0].Data).Free;
finally
aListView.Items[0].Data := nil;
end;
aListView.Items.Delete(0);
end;
aListView.Items.EndUpdate;
fLastItemIndex := -1;
Result := True;
except
Result := false;
end;
end;
procedure TfraCoverSheetDisplayPanel_CPRS.OnClearPtData(Sender: TObject);
begin
ClearListView(lvData);
end;
procedure TfraCoverSheetDisplayPanel_CPRS.OnCompleteBackgroundLoad(Sender: TObject);
begin
// virtual method for child frames;
end;
function TfraCoverSheetDisplayPanel_CPRS.CollapseColumns: integer;
begin
try
lvData.Columns.BeginUpdate;
lvData.Columns.Clear;
if fColumns.Count = 0 then
with lvData.Columns.Add do
begin
Caption := '';
AutoSize := True;
Width := lvData.ClientWidth;
lvData.ShowColumnHeaders := false;
end
else
with lvData.Columns.Add do
begin
Caption := fColumns[0];
AutoSize := True;
Width := lvData.ClientWidth;
lvData.ShowColumnHeaders := True;
end;
finally
lvData.Columns.EndUpdate;
end;
Result := lvData.Columns.Count;
end;
function TfraCoverSheetDisplayPanel_CPRS.CPRSParams: ICoverSheetParam_CPRS;
begin
// Supports(fParam, ICoverSheetParam_CPRS, Result);
getParam.QueryInterface(ICoverSheetParam_CPRS, Result);
end;
function TfraCoverSheetDisplayPanel_CPRS.AddColumn(aIndex: integer; aCaption: string): integer;
begin
while fColumns.Count < (aIndex + 1) do
fColumns.Add('');
fColumns[aIndex] := aCaption;
Result := fColumns.Count;
end;
procedure TfraCoverSheetDisplayPanel_CPRS.OnAddItems(aList: TStrings);
var
aRec: TDelimitedString;
aStr: string;
begin
if aList.Count = 0 then
aList.Add('^No data found.^');
for aStr in aList do
with lvData.Items.Add do
begin
aRec := TDelimitedString.Create(aStr);
Caption := aRec.GetPiece(2);
Data := aRec;
end;
end;
procedure TfraCoverSheetDisplayPanel_CPRS.OnBeginUpdate(Sender: TObject);
begin
ClearListView(lvData);
CollapseColumns;
if CPRSParams.HighlightText then
begin
lvData.Font.Color := clHighlight;
lvData.Font.Style := [fsBold];
end;
with lvData.Items.Add do
if CPRSParams.LoadInBackground then
Caption := UPDATING_BACKGROUND
else
Caption := UPDATING_FOREGROUND;
Application.ProcessMessages;
fFinished := false;
end;
procedure TfraCoverSheetDisplayPanel_CPRS.OnEndUpdate(Sender: TObject);
begin
fFinished := True;
end;
function TfraCoverSheetDisplayPanel_CPRS.ExpandColumns: integer;
var
aStr: string;
begin
try
lvData.Columns.BeginUpdate;
lvData.Columns.Clear;
if fColumns.Count = 0 then
with lvData.Columns.Add do
begin
Caption := '';
AutoSize := True;
Width := lvData.ClientWidth;
lvData.ShowColumnHeaders := false;
end
else
for aStr in fColumns do
with lvData.Columns.Add do
begin
Caption := aStr;
AutoSize := True;
Width := lvData.ClientWidth div fColumns.Count;
lvData.ShowColumnHeaders := True;
end;
finally
lvData.Columns.EndUpdate;
end;
Result := lvData.Columns.Count;
end;
function TfraCoverSheetDisplayPanel_CPRS.getIsFinishedLoading: boolean;
begin
Result := fFinished and (not tmr.Enabled)
end;
procedure TfraCoverSheetDisplayPanel_CPRS.OnGetDetail(aRec: TDelimitedString; aResult: TStrings);
begin
try
CallVistA(CPRSParams.DetailRPC, [Patient.DFN, aRec.GetPiece(1)], aResult);
except
on E: Exception do
ShowMessage('Default Detail Failed. ' + E.Message);
end;
end;
procedure TfraCoverSheetDisplayPanel_CPRS.OnLoadError(Sender: TObject; E: Exception);
begin
inherited;
lvData.Items.Clear;
with lvData.Items.Add do
Caption := '** Error Loading Data **';
lvData.Enabled := True;
lvData.Hint := getLoadErrorMessage;
lvData.ShowHint := True;
end;
function TfraCoverSheetDisplayPanel_CPRS.ListViewItemIEN: integer;
begin
if lvData.Selected <> nil then
if lvData.Selected.Data <> nil then
Result := TDelimitedString(lvData.Selected.Data).GetPieceAsInteger(1)
else
Result := -1
else
Result := -1;
end;
function TfraCoverSheetDisplayPanel_CPRS.ListViewItemRec: TDelimitedString;
begin
if lvData.Selected <> nil then
if lvData.Selected.Data <> nil then
Result := TDelimitedString(lvData.Selected.Data)
else
Result := nil
else
Result := nil;
end;
procedure TfraCoverSheetDisplayPanel_CPRS.lvDataEnter(Sender: TObject);
begin
if (fLastItemIndex > -1) and (lvData.Items.Count > fLastItemIndex) then
begin
lvData.Items[fLastItemIndex].Selected := True;
lvData.Items[fLastItemIndex].Focused := True;
end
else if lvData.Items.Count > 0 then
begin
lvData.Items[0].Selected := True;
lvData.Items[0].Focused := True;
end;
end;
procedure TfraCoverSheetDisplayPanel_CPRS.lvDataExit(Sender: TObject);
begin
lvData.Selected := nil;
end;
procedure TfraCoverSheetDisplayPanel_CPRS.lvDataKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if (Key = VK_RETURN) or (Key = VK_SPACE) then
begin
DisplayItemDetail(Sender, lvData.Selected, mbLeft);
end
else
inherited;
end;
procedure TfraCoverSheetDisplayPanel_CPRS.DisplayItemDetail(Sender: TObject; aItem: TListItem; Button: TMouseButton);
var
aDetail: TStringList;
aParam: ICoverSheetParam_CPRS;
begin
if aItem <> nil then
begin
fLastItemIndex := aItem.Index;
if (Button = mbLeft) and (aItem.Data <> nil) then
if TDelimitedString(aItem.Data).GetPiece(1) <> '' then
try
// Get the detail text
aDetail := TStringList.Create;
OnGetDetail(TDelimitedString(aItem.Data), aDetail);
// Check to see if it's printable
if getParam.QueryInterface(ICoverSheetParam_CPRS, aParam) = 0 then
OnShowDetail(aDetail, '', aParam.AllowDetailPrint)
else
OnShowDetail(aDetail);
finally
FreeAndNil(aDetail);
end;
end
else
lvDataEnter(Sender);
end;
procedure TfraCoverSheetDisplayPanel_CPRS.lvDataMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer);
var
aItem: TListItem;
begin
if fAllowDetailDisplay then
begin
aItem := lvData.GetItemAt(X, Y);
DisplayItemDetail(Sender, aItem, Button);
end;
end;
procedure TfraCoverSheetDisplayPanel_CPRS.lvDataSelectItem(Sender: TObject; Item: TListItem; Selected: boolean);
begin
if Selected then
fLastItemIndex := Item.Index;
end;
procedure TfraCoverSheetDisplayPanel_CPRS.OnPopupMenu(Sender: TObject);
begin
inherited;
pmnRefresh.Enabled := (Patient.DFN <> '');
end;
procedure TfraCoverSheetDisplayPanel_CPRS.OnPopupMenuInit(Sender: TObject);
begin
inherited;
pmnRefresh.Visible := True;
pmnRefresh.Enabled := True;
end;
procedure TfraCoverSheetDisplayPanel_CPRS.OnRefreshDisplay(Sender: TObject);
var
aRet: TStringList;
aRPC: string;
begin
inherited;
ClearListView(lvData);
if Patient.DFN = '' then
begin
lvData.Items.Add.Caption := 'No Patient Selected.';
lvData.Repaint;
Exit;
end;
if not CPRSParams.IsApplicable then
begin
with lvData.Items.Add do
begin
Caption := 'Not Applicable.';
Data := NewDelimitedString('-1^Not Applicable', '^');
end;
lvData.Repaint;
Exit;
end;
if CPRSParams.LoadInBackground then
begin
OnStartBackgroundLoad(Self);
fBackgroundLoadTry := 0;
fBackgroundLoading := True;
tmr.Enabled := True; // Start up the timer!
CPRSParams.LoadInBackground := false; // Only loads background when the coversheet says so.
Application.ProcessMessages;
Exit;
end;
try
try
ClearLoadError;
OnBeginUpdate(Sender);
aRet := TStringList.Create;
aRPC := CPRSParams.MainRPC;
{ todo - move these calls into a GetList method that can then be overridden by the inheritors }
// GetList(aRet); Every inheritor will have the params and access to Patient.DFN
if CPRSParams.Param1 <> '' then
CallVistA(aRPC, [Patient.DFN, CPRSParams.Param1], aRet)
else
CallVistA(aRPC, [Patient.DFN], aRet);
if CPRSParams.Invert then
InvertStringList(aRet);
ClearListView(lvData); // Must be re-cleared to flush anything from the OnBeginUpdate messages.
OnAddItems(aRet);
except
on E: Exception do
OnLoadError(Self, E);
end;
finally
OnEndUpdate(Sender);
FreeAndNil(aRet);
end;
end;
procedure TfraCoverSheetDisplayPanel_CPRS.OnSetFontSize(Sender: TObject; aNewSize: integer);
begin
inherited;
lvData.Font.Size := aNewSize;
end;
procedure TfraCoverSheetDisplayPanel_CPRS.SetListViewColumn(aIndex: integer; aCaption: string; aAutoSize: boolean; aWidth: integer);
begin
while lvData.Columns.Count < (aIndex + 1) do
lvData.Columns.Add;
lvData.ShowColumnHeaders := True;
with lvData.Columns[aIndex] do
begin
Caption := aCaption;
AutoSize := aAutoSize;
Width := aWidth;
end;
lvData.ColumnClick := false; // This is a default on setup. If setting up a sort, enable it.
end;
procedure TfraCoverSheetDisplayPanel_CPRS.OnShowDetail(aText: TStrings; aTitle: string = ''; aPrintable: boolean = false);
begin
if aTitle = '' then
aTitle := getTitle + ' Item Detail: ' + lvData.Selected.Caption;
ReportBox(aText, aTitle, aPrintable);
end;
procedure TfraCoverSheetDisplayPanel_CPRS.OnShowError(Sender: TObject);
begin
ShowMessage('CPRS does this by itself with a copy to clipboard option' + #13 + getLoadErrorMessage);
end;
procedure TfraCoverSheetDisplayPanel_CPRS.OnStartBackgroundLoad(Sender: TObject);
begin
ClearListView(lvData);
lvData.Items.Add.Caption := UPDATING_BACKGROUND;
Application.ProcessMessages;
end;
procedure TfraCoverSheetDisplayPanel_CPRS.tmrTimer(Sender: TObject);
var
aLst: TStringList;
aParam: ICoverSheetParam_CPRS;
i: integer;
begin
tmr.Interval := UPDATING_WAIT_TIME;
tmr.Enabled := fBackgroundLoading;
// if try = 0 then it just hit from getting set to fire, give server a free loop
if fBackgroundLoadTry = 0 then
begin
ClearListView(lvData);
lvData.Items.Add.Caption := UPDATING_BACKGROUND;
inc(fBackgroundLoadTry);
Application.ProcessMessages;
Exit;
end;
ClearListView(lvData);
if not tmr.Enabled then
begin
lvData.Items.Add.Caption := 'Exit, timer not enabled';
Exit;
end;
if getParam.QueryInterface(ICoverSheetParam_CPRS, aParam) <> 0 then
begin
lvData.Items.Add.Caption := 'Invalid param set for display.';
tmr.Enabled := false;
Exit;
end
else if aParam.PollingID = '' then
begin
lvData.Items.Add.Caption := 'Invalid PollingID in param set.';
tmr.Enabled := false;
Exit;
end;
// Do the call here and determine if we can load anything
try
aLst := TStringList.Create;
CallVistA('ORWCV POLL', [Patient.DFN, CoverSheet.IPAddress, CoverSheet.UniqueID, aParam.PollingID], aLst);
if aLst.Count > 0 then
begin
for i := aLst.Count - 1 downto 0 do
begin
if Copy(aLst[i], 1, 1) = '~' then
aLst.Delete(i)
else if Copy(aLst[i], 1, 1) = 'i' then
aLst[i] := Copy(aLst[i], 2, Length(aLst[i]));
end;
ClearListView(lvData);
if CPRSParams.Invert then
InvertStringList(aLst);
OnAddItems(aLst);
tmr.Enabled := false;
OnCompleteBackgroundLoad(Self);
Exit;
end;
finally
FreeAndNil(aLst);
end;
inc(fBackgroundLoadTry);
fBackgroundLoading := (fBackgroundLoadTry <= UPDATING_ATTEMPTS);
if fBackgroundLoading then
lvData.Items.Add.Caption := Format(UPDATING_BACKGROUND + '%s', [Copy('..........', 1, fBackgroundLoadTry)])
else
begin
tmr.Enabled := false;
lvData.Items.Add.Caption := UPDATING_FAILURE;
end;
Application.ProcessMessages;
end;
end.
|
{$I ..\DelphiVersions.Inc}
unit Amazon.SignatureV4;
interface
Uses Classes, Amazon.Utils, SysUtils, IdGlobal, Amazon.Interfaces,
Amazon.Request;
const
awsALGORITHM = 'AWS4-HMAC-SHA256';
awsSIGN = 'AWS4';
awsContent_typeV4 = 'application/x-amz-json-1.0';
{$IFDEF DELPHIXE8_UP}
function GetSignatureV4Key(aSecret_Access_Key, adateStamp, aregionName, aserviceName: UTF8String): TBytes;
{$ELSE}
function GetSignatureV4Key(aSecret_Access_Key, adateStamp, aregionName,
aserviceName: UTF8String): TidBytes;
{$ENDIF}
{$IFDEF DELPHIXE8_UP}
function GetSignatureV4(aSignatureV4Key: TBytes; aString_to_sign: UTF8String)
: UTF8String;
{$ELSE}
function GetSignatureV4(aSignatureV4Key: TidBytes; aString_to_sign: UTF8String)
: UTF8String;
{$ENDIF}
type
TAmazonSignatureV4 = class(TInterfacedObject, IAmazonSignature)
protected
private
fsmethod: UTF8String;
fscontent_type: UTF8String;
fsresponse: UTF8String;
fscanonical_uri: UTF8String;
fscanonical_queryString: UTF8String;
fscanonical_headers: UTF8String;
fssigned_headers: UTF8String;
fspayload_hash: UTF8String;
fscanonical_request: UTF8String;
fsalgorithm: UTF8String;
fscredential_scope: UTF8String;
fsString_to_sign: UTF8String;
{$IFDEF DELPHIXE8_UP}
fSignatureV4Key: TBytes;
{$ELSE}
fSignatureV4Key: TidBytes;
{$ENDIF}
fsSignature: UTF8String;
fsauthorization_header: UTF8String;
function getsignature: UTF8String;
function getauthorization_header: UTF8String;
public
procedure Sign(aRequest: IAmazonRequest);
function GetContent_type: UTF8String;
property Signature: UTF8String read getsignature;
property Authorization_header: UTF8String read getauthorization_header;
end;
implementation
{$IFDEF DELPHIXE8_UP}
function GetSignatureV4Key(aSecret_Access_Key, adateStamp, aregionName,
aserviceName: UTF8String): TBytes;
Var
kService: TBytes;
kRegion: TBytes;
kSecret: TBytes;
kDate: TBytes;
kSigning: TBytes;
begin
kSecret := BytesOf(UTF8Encode(awsSIGN + aSecret_Access_Key));
kDate := HmacSHA256Ex(kSecret, adateStamp);
kRegion := HmacSHA256Ex(kDate, aregionName);
kService := HmacSHA256Ex(kRegion, aserviceName);
kSigning := HmacSHA256Ex(kService, 'aws4_request');
Result := kSigning;
end;
{$ELSE}
function GetSignatureV4Key(aSecret_Access_Key, adateStamp, aregionName,
aserviceName: UTF8String): TidBytes;
Var
kService: TidBytes;
kRegion: TidBytes;
kSecret: TidBytes;
kDate: TidBytes;
kSigning: TidBytes;
begin
kSecret := ToBytes(UTF8Encode(awsSIGN + aSecret_Access_Key));
kDate := HmacSHA256Ex(kSecret, adateStamp);
kRegion := HmacSHA256Ex(kDate, aregionName);
kService := HmacSHA256Ex(kRegion, aserviceName);
kSigning := HmacSHA256Ex(kService, 'aws4_request');
Result := kSigning;
end;
{$ENDIF}
{$IFDEF DELPHIXE8_UP}
function GetSignatureV4(aSignatureV4Key: TBytes; aString_to_sign: UTF8String)
: UTF8String;
begin
Result := BytesToHex(HmacSHA256Ex(aSignatureV4Key, aString_to_sign));
end;
{$ELSE}
function GetSignatureV4(aSignatureV4Key: TidBytes; aString_to_sign: UTF8String)
: UTF8String;
begin
Result := BytesToHex(HmacSHA256Ex(aSignatureV4Key, aString_to_sign));
end;
{$ENDIF}
procedure TAmazonSignatureV4.Sign(aRequest: IAmazonRequest);
begin
fsSignature := '';
fsauthorization_header := '';
fsmethod := 'POST';
fscontent_type := GetContent_type;
fscanonical_uri := '/';
fscanonical_queryString := '';
fscanonical_headers := 'content-type:' + fscontent_type + char(10) + 'host:' +
aRequest.host + char(10) + 'x-amz-date:' + aRequest.amz_date + char(10) +
'x-amz-target:' + aRequest.targetPrefix + '.' + aRequest.operationName
+ char(10);
fssigned_headers := 'content-type;host;x-amz-date;x-amz-target';
fspayload_hash := HashSHA256(aRequest.request_parameters);
fscanonical_request := fsmethod + char(10) + fscanonical_uri + char(10) +
fscanonical_queryString + char(10) + fscanonical_headers + char(10) +
fssigned_headers + char(10) + fspayload_hash;
fsalgorithm := awsALGORITHM;
fscredential_scope := aRequest.date_stamp + '/' + aRequest.region + '/' +
aRequest.service + '/' + 'aws4_request';
fsString_to_sign := fsalgorithm + char(10) + aRequest.amz_date + char(10) +
fscredential_scope + char(10) + HashSHA256(fscanonical_request);
fSignatureV4Key := GetSignatureV4Key(aRequest.secret_key, aRequest.date_stamp,
aRequest.region, aRequest.service);
fsSignature := GetSignatureV4(fSignatureV4Key, fsString_to_sign);
fsauthorization_header := fsalgorithm + ' ' + 'Credential=' +
aRequest.access_key + '/' + fscredential_scope + ', ' + 'SignedHeaders=' +
fssigned_headers + ', ' + 'Signature=' + fsSignature;
end;
function TAmazonSignatureV4.getsignature: UTF8String;
begin
Result := fsSignature;
end;
function TAmazonSignatureV4.getauthorization_header: UTF8String;
begin
Result := fsauthorization_header;
end;
function TAmazonSignatureV4.GetContent_type: UTF8String;
begin
Result := awsContent_typeV4;
end;
end.
|
unit uiProjeto_Interface;
interface
type
iProjeto = interface
procedure SetId(const Value: Integer);
procedure SetNome(const Value: String);
procedure SetValor(const Value: Currency);
end;
implementation
end.
|
unit js_gencode;
interface
{$M+}
uses js_codeformat,js_parser,js_tokens,fw_utils,fw_vm_types,fw_vm_constants;
type
TJs_CodeGen=class(TJs_Parser)
private
cur_thisK:cardinal;
cur_thisV:longint;
err_ident:cardinal; // Ident que esta actuando de error, solo tiene un valor dentro de un bloque catch
func_ident:cardinal; // Ident de la funcion actual
cb:pJs_Function; // Current block
function c_incLabel:longint;
function c_emit(c:cardinal;k1:cardinal;v1:longint;k2:cardinal;v2:longint):pJS_CodeNode;
function c_emitVar(f:pJs_Function;p:p_node;kind:cardinal):boolean;
function c_result(p:p_node):boolean;
function c_Locate(p:p_node;var k1:cardinal;var v1:longint):boolean;
function c_IsCatch(p:p_node;var k1:cardinal;var v1:longint):boolean;
function c_allocreg(p:p_node):longint;
procedure c_unallocreg(k1:cardinal;v1:longint);
procedure c_unallocregs;
function c_tokenToFlag(k:cardinal;OnTrue:boolean):cardinal;
function c_FunctionRealName(s:string):string;
function c_CatchLevel(p:p_node):longint;
procedure c_MakeSureOutOfTry(p:p_node); // Salimos de cualquier bloque try-catch-finally en el que podamos estar
procedure c_MakeSureFinal;
procedure c_DiscardFrame(k:cardinal);
function c_IsProperty(p:p_node):boolean;
procedure c_LocateVar(p:p_node;var k1:cardinal;var v1:longint);
function c_ParentVar(p:p_node):p_node;
function c_Propagate(what:p_node):p_node;
procedure c_MakeClosured(p:p_node);
function c_NewLabel:pJs_CodeNode;
function GenCodeStatement(p:p_node):boolean;
function GenFunctionBody(p:p_node):boolean;
function GenCodeBreak(p:p_node):boolean;
function GenCodeBreakHelper(p:p_node):boolean;
function GenCodeIf(p:p_node):boolean;
function GenCodeThrow(p:p_node):boolean;
function GenCodeTry(p:p_node):boolean;
function GenCodeWhile(p:p_node):boolean;
function GenCodeFor(p:p_node):boolean;
function GenCodeGetterSetter(p:p_node;dt:cardinal;dv:longint):boolean;
function GenCodeForIn(p:p_node):boolean;
function GenCodeExpressionGroup(p:p_node;dt:cardinal;dv:longint):boolean;
function GenCodeFlaggedExpresssion(p:p_node):longint;
function GenCodeFloat(p:p_node;dt:cardinal;dv:longint):boolean;
function GenCodeOrExpression(p:p_node;dt:cardinal;dv:longint):boolean;
function GenCodeAndExpression(p:p_node;dt:cardinal;dv:longint):boolean;
function GenCodeExpression(p:p_node;dt:cardinal;dv:longint):boolean;
function GenCodeCall(p:p_node;dt:cardinal;dv:longint):boolean;
function GenCodeUnaryOperator(p:p_node;dt:cardinal;dv:longint):boolean;
function GenCodeIfOperator(p:p_node;dt:cardinal;dv:longint):boolean;
function GenCodeBinOperator(p:p_node;dt:cardinal;dv:longint):boolean;
function GenCodeAssign(p:p_node;dt:cardinal;dv:longint):boolean;
function GenCodeCarryAssign(p:p_node;dt:cardinal;dv:longint):boolean;
function GenCodePostInc(p:p_node;dt:cardinal;dv,k:longint):boolean;
function GenCodePreInc(p:p_node;dt:cardinal;dv,k:longint):boolean;
function GenCodeIndex(p:p_node;dt:cardinal;dv:longint):boolean;
function GenCodeNewExpression(p:p_node;dt:cardinal;dv:longint):boolean;
function GenCodeIdent(p:p_node;dt:cardinal;dv:longint):boolean;
function GenCodeReturn(p:p_node):boolean;
function GenCodeFuncExpression(p:p_node;dt:cardinal;dv:longint):boolean;
function GenCodeObject(p:p_node;dt:cardinal;dv:longint):boolean;
function GenCodeArrayDef(p:p_node;dt:cardinal;dv:longint):boolean;
published
function c_InvertFlag(k:longint):longint;
public
programa:pJs_Program;
regs:pointer;
destructor Destroy; override;
constructor Create;
function GenCode:boolean;
function c_Error(s:string;p:p_node):boolean;
// procedure PrintCode;
end;
implementation
uses js_lexer;
var gen_code_debug:boolean=false;
JS_BoolOpRes:array [jst_Min_BoolOp..jst_Max_boolOp,false..true] of cardinal;
constructor TJs_CodeGen.Create;
begin
inherited Create;
programa:=js_program_create;
regs:=l_create(SizeOf(POINTER),0);
err_ident:=0;
end;
destructor TJs_CodeGen.Destroy;
begin
programa:=js_program_free(programa);
regs:=l_free(regs);
inherited destroy;
end;
function TJs_CodeGen.c_incLabel:longint;
begin
result:=cb.nlabels;inc(cb.nlabels);
end;
function TJs_CodeGen.c_NewLabel:pJs_CodeNode;
begin
result:=c_Emit(op_Label,opt_Label,c_incLabel,opt_None,0);
end;
function TJs_CodeGen.GenCode:boolean;
var p1:p_node;
oc:pJs_Function;
begin
result:=true;vars:=root.first;func_ident:=0;
vars.hash:=js_program_AddFunction(programa,'#@Globals'); // Generamos el bloque de Globals y lo guardamos en vars.HASH. Lo hacemos aqui para que sea el bloque 0
p1:=vars.next.first;while p1<>nil do begin p1.value:=js_program_AddFunction(programa,p1.text);p1:=p1.next;end; // Generamos el resto de funciones definidas en el orden en que aparecen
p1:=n_LastBrother(root.first.next.first);while (p1<>nil) and result do begin c_unallocregs;result:=GenFunctionBody(p1);p1:=p1.prev;end; // Generamos el codigo en orden inverso, lo hacemos para tener cubiertas los accesos indirectos (que se descubren en una closure definida a posteriori)
cb:=js_function_create;oc:=cb;p1:=root.first.next.next; // Ahora el codigo de main en un cb flotante
while (p1<>nil) and result do begin result:=GenCodeStatement(p1);p1:=p1.next;end;
vars:=root.first;p1:=vars.first;cb:=js_program_FunctionByIndex(programa,vars.hash); // Generamos el codigo de las variables globales
while (p1<>nil) and result do begin result:=c_emitVar(cb,p1,opT_Gvar);p1:=p1.next;end;
js_function_move(cb,oc);cb.nlabels:=oc.nlabels;js_function_Free(oc); // Copiamos el codigo de main tras las variables
c_Emit(op_Ret,opT_Flag,opF_InMainBody,opt_Flag,opF_NoFlag); // Y emitimos el Ret final
programa.n_regs:=l_count(regs); // Finalmente guardamos cuantos registros necesitamos y cuantas variables globales
programa.n_vars:=vars.value;
end;
// Pending: iniciarlo todo como se hacen las funciones
// Var se queda como esta
// ExtValue se ha de transformar en un define y un extern
// Param se ha de transformar en un define y en un param
// IndParam se ha de transformar en un define y en un IndParam
// IndVar se ha de transformar en un define y en un IndVar
// Link se ha de transformar en un define y en un Link
// y finalmente todos los defines se adelantan
function TJs_CodeGen.c_emitVar(f:pJs_Function;p:p_node;kind:cardinal):boolean;
var l0:longint;
begin
l0:=js_program_AddCodeString(programa,p.text); // l0 es la posicion de memoria donde esta esta el nombre de la variable
l_pushi(f.var_names,l0); // Pusheamos l0 en la lista de var_names de la funcion
result:=true;
case p.kind of
jst_Param: begin c_Emit(op_Move,opt_Var,p.value,opt_RParam,p.value);inc(cb.nvars_p);end; // Los parametros se copian sin mas, los numeros de orden coinciden
jst_ExtValue: c_Emit(op_Extern,kind,p.value,opt_ExtPchar,l0); // Los valores externos se importan
jst_IndVar: c_emit(op_GCVar,kind,p.value,opt_None,0); // Crea una variable GC con valor opt_None, hace que kind|p.value apunte a la misma
jst_IndParam: c_emit(op_GCVar,kind,p.value,opt_RParam,p.value); // Crea una variable GC con valor el del Own_Param recibido
jst_LinkCopy: begin // Esta es una variable que debe ser "capturad" ya que es usada por una funcion de Closure
if cb.nvars_ex=-1 then cb.nvars_ex:=js_program_AddCodeInteger(cb.programa,0); // Si no teniamos ninguna variable capturada, ponemos a 0 el contador
js_program_AddCodeInteger(cb.programa,p.number); // Aņdimos la variable padre a la lista de variables a capturar al iniciar la funcion
c_Emit(op_Link,kind,p.value,opt_CVar,b_inc(cb.programa.integers,cb.nvars_ex)); // Aņadimos codigo para que la variable local apunta a la capturada
end;
jst_GCopy: begin
if cb.nvars_ex=-1 then cb.nvars_ex:=js_program_AddCodeInteger(cb.programa,0); // Si no teniamos ninguna variable capturada, ponemos a 0 el contador
js_program_AddCodeInteger(cb.programa,-p.number-1); // Aņdimos la variable GLOBAL a la lista de variables a capturar al iniciar la funcion. El signo diferencia entre Var_Ancestors y globales. Aņadimos -1 porque +0=-0
c_Emit(op_Link,kind,p.value,opt_CVar,b_inc(cb.programa.integers,cb.nvars_ex)); // Aņadimos codigo para que la variable local apunta a la capturada
end;
jst_Var: begin end; //if kind=opT_Gvar then c_emit(op_Define,kind,p.value,opt_ExtPchar,l0);
else result:=c_Error('Bad kind in GLOBAL VARS '+s_i2s(p.kind)+' '+js_token2str(p.kind),p);
end;
if result and n_kindIs(p.first,jst_FuncDef) then result:=GenCodeFuncExpression(p.first,kind,p.value);
end;
function TJs_CodeGen.c_emit(c:cardinal;k1:cardinal;v1:longint;k2:cardinal;v2:longint):pJS_CodeNode;
begin
if c<>op_Move then begin result:=js_program_AddCode(cb,c,k1,k2,v1,v2);exit;end;
// Si tenemos un move a nada, o un move a si mismo, salimos
if (k1=opT_none) then begin result:=nil;exit;end;
if (k1=k2) and (v1=v2) then begin result:=nil;exit;end;
// Generamos el move
result:=js_program_AddCode(cb,c,k1,k2,v1,v2);
end;
function TJs_CodeGen.c_Error(s:string;p:p_node):boolean;
begin
result:=false;
if error='' then begin
error:='GenCode error: '+s;
if p<>nil then begin
error:=error+#13#10+js_token2str(p.kind);
if p.text<>'' then error:=error+' ['+p.text+']';
if p.pos>0 then error:=error+#13#10+CalcXY(pchar(src+p.pos));end;
end;
token:=jst_Error;
end;
// Todo ident que exista debe de ser un GVar o Var, c_Locate se encarga de averiguar cual
function TJs_CodeGen.GenCodeIdent(p:p_node;dt:cardinal;dv:longint):boolean;
var et:cardinal;
ev:longint;
begin
result:=c_Locate(p,et,ev); // Localizamos el objeto
if result and (dt<>opT_None) then c_Emit(op_Move,dt,dv,et,ev);
c_unallocreg(et,ev);
end;
// p es un nodo VAR y queremos ir al VAR del padre
function TJs_CodeGen.c_ParentVar(p:p_node):p_node;
begin
// si el padre es root salimos, si no vamos a la funcion (parent),luego a donde esta definida (data) y luego al vars (first)
if p.parent=root then result:=nil else result:=p.parent.data.first;
end;
function TJs_CodeGen.c_CatchLevel(p:p_node):longint;
var k,m:cardinal;
begin
k:=p.hash;p:=p.parent;result:=0;m:=0;
while (result=0) and (p.parent<>root) do begin
if (p.kind=jst_catch) then begin
if (n_kind(p.first)=jst_ident) then if p.first.hash=k then result:=m;
m:=m+1;
end;
p:=p.parent;
end;
end;
// Caso especial, cuando localizamos una variable cuyo nombre coincide con el valor de CATCH(nombre)
function TJs_CodeGen.c_IsCatch(p:p_node;var k1:cardinal;var v1:longint):boolean;
begin
if err_ident<>0 then begin
if p.hash=err_ident then begin k1:=opT_CatchVar;v1:=0;result:=true;exit;end;
v1:=c_CatchLevel(p);if v1<>0 then begin k1:=opT_CatchVar;result:=true;exit;end;
end;
result:=false;
end;
// En tiempo de ejecucion: toda variable a la que tiene acceso una funcion es a traves de las variables del Runner actual, es decir de pRt_Runner.locals
// Existen variables de scope local y de scope global
// Las variables de scope local: son las definidas con VAR dentro de la propia funcion y los parametros de llamada a la funcion RPARAM
// Las variabels de scope global: son las globales y las closures
procedure TJs_CodeGen.c_LocateVar(p:p_node;var k1:cardinal;var v1:longint);
var p0,p1:p_node;
begin
if c_IsCatch(p,k1,v1) then exit; // Caso especial, es el ident de un bloque de catch
if p.hash=func_ident then begin k1:=opt_Single;v1:=opS_CurF;exit;end; // Caso especial, es el nombre de la funcion actual, solo se utiliza en expresiones recursivas cuando el nombre de la funcion es optativo (si es obligatorio iremos a la definicion de la funcion)
p1:=p.data; // Localizamos en p1 la definicion de la variable (que debe colgar de cur_func.vars = jst_vars)
if p1=nil then begin // Si no tenemos una definicion
p0:=vars; // Las primeras variables en las que buscamos son las locales
repeat
p1:=n_FindChildHash(p0,p.hash); // Buscamos el nodo en las variables locales
if p1=nil then p0:=c_ParentVar(p0); // Si no lo encontramos subimos a la funcion padre de la actual
until (p0=nil) or (p1<>nil); // Se acaba cuando lo encontramos o llegamos a tope de la cadea
if p1=nil then begin p1:=n_CreateT(root.first,jst_ExtValue,p.text);p1.value:=n_ValuePP(root.first);end // Si no lo hemos encontrado la creamos en root como valor global (y/p externo)
else p1:=c_propagate(p1); // Si la hemos encontrado nos aseguramos que se defina como indirecta y que propague en las funciones intermedias
end;
if vars=root.first then begin k1:=opt_GVar;p.data:=p1;v1:=p1.value;exit;end; // Si estamos en la funcion Global, solo puede ser una variable global que seguro hemos localizado (si no existia la hemos creado)
if (p1.parent.parent.kind=jst_Root) then begin // Si se trata de una variable Global !!!
k1:=p1.value;p1:=n_CreateT(vars,jst_GCopy,p.text);p1.value:=n_ValuePP(vars);p1.number:=k1; // Creamos una variable local, cuyo origen es una referencia a una Global
end;
k1:=opT_Var;p.data:=p1;v1:=p1.value;
end;
procedure TJS_CodeGen.c_MakeClosured(p:p_node);
begin
if not (p.kind in [jst_Param,jst_Var]) then exit;
p.number:=n_NumberPP(p.parent); // Asignamos a what un nš de variable de closure
if p.kind=jst_Param then p.kind:=jst_IndParam else
//if p.kind=jst_Var then
p.kind:=jst_IndVar;
end;
// Cuando llegamos aqui, what es una definicion de variable que esta en una funcion que
// engloba (o no) a la actual
function TJs_CodeGen.c_Propagate(what:p_node):p_node;
var p1,p2a,p2b:p_node;
begin
if (what.parent=vars) or (what.parent=root.first) then begin result:=what;exit;end; // Si el nodo pertenece a Vars de la funcion actual o Vars global, es accesible directamente y no hay posibilidad de closure
c_MakeClosured(what); // La variable se define como closured
result:=n_CreateT(vars,jst_LinkCopy,what.text);result.value:=n_ValuePP(vars); // Creamos en vars de la funcion actual el nodo que devolveremos
result.data:=pointer(10);
p1:=c_ParentVar(vars);p2a:=result;
while p1<>what.parent do begin
p2b:=n_CreateT(p1,jst_LinkCopy,what.text);
p2b.value:=n_ValuePP(p1);
p2a.number:=//(1 shl 16) or
p2b.value;
p2a:=p2b;
p1:=c_ParentVar(p1);
end; // Vamos subiendo e incrementando el nivel hasta que coincida
p2a.number:=what.value;
end;
{
// Cuando llegamos aqui, what es una definicion de variable que esta en una funcion que
// engloba (o no) a la actual
function TJs_CodeGen.c_Propagate(what:p_node):p_node;
var p0,p1:p_node;
begin
if (what.parent=vars) or (what.parent=root.first) then begin result:=what;exit;end; // Si el nodo pertenece a Vars de la funcion actual o Vars global, es accesible directamente y no hay posibilidad de closure
if what.kind in [jst_Param,jst_Var] then begin // Si aun no era una variable de closure
what.number:=n_NumberPP(what.parent); // Asignamos a what un nš de variable de closure
if what.kind=jst_Param then what.kind:=jst_IndParam else what.kind:=jst_IndVar; // Nos aseguramos de que se inicie correctamente
end;
result:=n_CreateT(vars,jst_LinkCopy,what.text);result.value:=n_ValuePP(result.parent); // Creamos en vars de la funcion actual el nodo que devolveremos
vars.hash:=vars.hash+1; // Marcamos que hay una variable capturada que se utilizara
p1:=vars;
while p1<>what.parent do begin inc(result.number);p1:=c_ParentVar(p1);end; // Vamos subiendo e incrementando el nivel hasta que coincida
//s_alert('Para acceder a '+what.text+' niveles a subir '+s_i2s(result.number)+#13+
// 'Para acceder a '+what.text+' el nš de captured var es '+s_i2s(what.number)+#13+'Que se codifica como '+s_i2h(result.number shl 16 or what.number));
result.number:=result.number shl 16 or what.number; // Los niveles a subir son 4 bytes a la izquierda
end;
}
function TJs_CodeGen.GenCodeFloat(p:p_node;dt:cardinal;dv:longint):boolean;
var k1:cardinal;v1:longint;
begin
result:=s_s2f(p.text,k1,v1);if not result then exit;
c_emit(op_Move,dt,dv,k1,k1);
end;
function TJs_CodeGen.c_Locate(p:p_node;var k1:cardinal;var v1:longint):boolean;
begin
result:=true;
case p.kind of
jst_Ident: if c_IsProperty(p) then begin k1:=opT_ExtPChar;v1:=js_program_AddCodeString(programa,p.text);end else c_LocateVar(p,k1,v1);
jst_Integer: begin k1:=opT_Integer;v1:=s_s2i(p.text);end;
jst_float: result:=s_s2f(p.text,k1,v1);
jst_PChar: begin k1:=opT_ExtPChar;v1:=js_program_AddCodeString(programa,p.text);end;
jst_This: begin k1:=opt_Single;v1:=opS_This;end;
else begin k1:=opT_reg;v1:=c_allocreg(p);result:=GenCodeExpression(p,opT_reg,v1);end;
end;
end;
function TJs_CodeGen.c_allocreg(p:p_node):longint;
begin
result:=l_count(regs)-1;
while (result>=0) and (l_get(regs,result)<>nil) do result:=result-1;
if result>=0 then l_set(regs,result,p) else result:=l_push(regs,p);
end;
procedure TJs_CodeGen.c_unallocreg(k1:cardinal;v1:longint);
begin
if k1=opT_Reg then l_set(regs,v1,nil);
end;
procedure TJs_CodeGen.c_unallocregs;
var i:longint;
begin
for i:=0 to l_count(regs)-1 do l_set(regs,i,nil);
end;
function TJs_CodeGen.GenCodeStatement(p:p_node):boolean;
begin
if p=nil then begin result:=true;exit;end; // El statement vacio no genera codigo
cur_ThisK:=opT_Single;cur_ThisV:=opS_This;
case p.kind of
jst_Begin: begin p:=p.first;result:=true;while (p<>nil) and result do begin result:=GenCodeStatement(p);p:=p.next;end;end;
jst_Return: result:=GenCodeReturn(p);
jst_If: result:=GenCodeIf(p);
jst_Throw: result:=GenCodeThrow(p);
jst_Try: result:=GenCodeTry(p);
jst_finally: result:=GencodeStatement(p.first);
jst_While: result:=GenCodeWhile(p);
jst_BreakHelper: result:=GenCodeBreakHelper(p);
jst_Break: result:=GenCodeBreak(p);
jst_For: result:=GenCodeFor(p);
jst_ForIn: result:=GenCodeForIn(p);
else result:=GenCodeExpression(p,opT_None,0);
end;
end;
function TJs_CodeGen.GenCodeReturn(p:p_node):boolean;
var flag_root,flag_return:cardinal;
begin
if p.first<>nil then begin result:=GenCodeExpression(p.first,opt_Single,ops_Result);flag_return:=opF_WithReturn;end else begin result:=true;flag_return:=opF_NoFlag;end;
if not result then exit;
c_MakeSureOutOfTry(p); // Salimos de cualquier bloque try-catch-finally en el que podamos estar
flag_root:=opF_InMainBody;
while (flag_root=opF_InMainBody) and (p<>nil) do if p.kind=jst_Functions then flag_root:=opF_NoFlag else p:=p.parent;
c_Emit(op_Ret,opT_Flag,flag_root,opt_Flag,flag_return);
end;
procedure TJs_CodeGen.c_DiscardFrame(k:cardinal);
begin
c_Emit(op_PopFrame,opt_FrameError,k,opt_None,0)
end;
procedure TJs_CodeGen.c_MakeSureFinal;
var c:pJs_CodeNode;
begin
c:=c_Emit(op_PatchFrame,opt_FrameError,opFr_TryFrame,opt_Label,c_incLabel);
c_Emit(op_PopFrame,opt_FrameError,opFr_FinalFrame,opt_None,0); // Ejecutamos Frame_Final, el control pasara al bloque Final que cuando acabe ejecutara Frame_Try
c_Emit(op_Label,opT_Label,c.v2,opt_None,0); // Que nos llevara aqui
end;
// La estructura es
// finally
// try
// ---- Try Code
// catch
// --- Catch Code
// --- Finally Code
// Esta funcion se llama cuando se ejecuta alguna instruccion que rompe el flujo normal: RET, BREAK o CONTINUE.
// Justo antes del salto. Comprueba si estamos en un bloque TRY-CATCH-FINALLY y actua en consecuenta
procedure TJs_CodeGen.c_MakeSureOutOfTry(p:p_node);
var s:string;
p1:p_node;
begin
// Podemos estar en alguna de estas situaciones en el STACK
// -> Sin FRAMES antes de la vuelta
// -> Si estamos en codigo TRY: y tenemos CATCH|FINAL Descartamos CATCH, modificamos TRY para que vuelva a LABEL y hacemos POP_FINAL
// -> y tenemos CATCH Descartamos CATCH, y descartamos TRY
// -> y tenemos FINAL Modificamos TRY para que vuelva a LABEL y hacemos POP_FINAL
// -> Si estamos en codigo CATCH: y tenemos CATCH|FINAL Modificamos TRY para que vuelva a LABEL y hacemos POP_FINAL
// -> y tenemos CATCH Descartamos TRY
// -> Si estamos en codigo FINAL: y tenemos FINAL Descartamos TRY
// -> y tenemos CATCH|FINAL Descartamos TRY
s:='';p1:=nil;
repeat
if (p.kind in [jst_try,jst_catch,jst_finally]) and (p1=nil) then p1:=p;
if p.kind=jst_Try then begin
if p.first.next<>nil then s:='C' else s:='';
if p.parent.kind=jst_Finally then begin s:=s+'F';p:=p.parent;end;
if (p1.kind=jst_Try) and (s='CF') then begin c_DiscardFrame(opFr_CatchFrame);c_MakeSureFinal;p1:=nil;end else
if (p1.kind=jst_Try) and (s='C') then begin c_DiscardFrame(opFr_CatchFrame);c_DiscardFrame(opFr_TryFrame);p1:=nil;end else
if (p1.kind=jst_Try) and (s='F') then begin c_MakeSureFinal;p1:=nil;end else
if (p1.kind=jst_catch) and (s='CF') then begin c_MakeSureFinal;p1:=nil;end else
if (p1.kind=jst_catch) and (s='C') then begin c_DiscardFrame(opFr_TryFrame);p1:=nil;end else
if (p1.kind=jst_finally) and (s='CF') then begin c_DiscardFrame(opFr_TryFrame);p1:=nil;end else
if (p1.kind=jst_finally) and (s='F') then begin c_DiscardFrame(opFr_TryFrame);p1:=nil;end;
end;
p:=p.parent;
until p.kind=jst_Root;
end;
// Si tenemos a+=b, se genera codigo para result=a+b y ahora hacemos a=result
function TJs_CodeGen.GenCodeCarryAssign(p:p_node;dt:cardinal;dv:longint):boolean;
var o1:cardinal;
v1:longint;
begin
case p.kind of
jst_ident: begin result:=true;c_emit(op_Move,dt,dv,opt_Single,ops_Result);end;
jst_Index,jst_member: begin
result:=c_Locate(p.first,o1,v1) and c_Locate(p.first.next,dt,dv); // Localizamos el objeto y su propiedad
c_Emit(op_SetProperty,o1,v1,dt,dv);
c_unallocreg(o1,v1);c_unallocreg(dt,dv);
end;
else result:=c_Error('Only referencec can be assigned',p);
end;
end;
function IsResult(os:cardinal;ov:longint):boolean;
begin
result:=(os=opt_Single) and (ov=opS_result);
end;
// Podemos tener las siguientes opciones
// UN ASSIGN SIMPLE a=(expresion) a...b=(expresion)
// UN ASSIGN MULTIPLE a=b=c=(expresion) a...b=c=d=(expresion)
function TJs_CodeGen.GenCodeAssign(p:p_node;dt:cardinal;dv:longint):boolean;
var p1,p2:p_node;
o1,o2,os:cardinal;
v1,v2,vs:longint;
begin
p2:=n_LastBrother(p.first);p1:=p2.prev; // p1 = parte izquierda de la expresion ; p2 = expresion a asignar
case p1.kind of
jst_Ident: begin result:=c_Locate(p1,os,vs);if result then result:=GenCodeExpression(p2,os,vs);c_unallocreg(os,vs);end; // Tenemos en os,vs el valor asignado
jst_Index,jst_Member: begin
result:=c_Locate(p1.first,o1,v1);
result:=result and c_Locate(p1.first.next,o2,v2); // Localizamos el objeto y su propiedad
if result then result:=GenCodeExpression(p2,opt_Single,ops_Result);
c_Emit(op_SetProperty,o1,v1,o2,v2);
c_unallocreg(o1,v1);c_unallocreg(o2,v2);
os:=opt_Single;vs:=ops_Result;
end;
else result:=c_Error('Can''t assign',p1);
end;
if not result then exit;
p1:=p1.prev;
// Si tenemos un assign encadenado y ya hemos "Ocupado" result, comprobamos si es necesario un registro
// podemos evitar esto SI SABEMOS que en todos los p1.prev NO se utiliza result (es decir NO hay index, ni CALls, ni se definen
// objetos,..) pero de momento NO LO HACEMOS.
if (p1<>nil) and IsResult(os,vs) then begin os:=opt_reg;vs:=c_allocreg(p2);c_Emit(op_Move,opt_reg,vs,opt_Single,ops_Result);end;
while result and (p1<>nil) do begin
if p1.kind=jst_Ident then begin result:=c_Locate(p1,o2,v2);c_Emit(op_Move,o2,v2,os,vs);c_unallocreg(o2,v2);end else
if (p1.kind=jst_Index) or (p1.kind=jst_Member) then begin
result:=c_Locate(p1.first,o1,v1) and c_Locate(p1.first.next,o2,v2); // Localizamos el objeto y su propiedad
if result then begin if not IsResult(os,vs) then c_Emit(op_Move,opt_Single,ops_Result,os,vs);c_Emit(op_SetProperty,o1,v1,o2,v2);end;
c_unallocreg(o1,v1);c_unallocreg(o2,v2);
end
else result:=c_Error('Can''t assign',p1);
p1:=p1.prev;
end;
// Arrastramos el move
c_emit(op_Move,dt,dv,os,vs);
c_unallocreg(os,vs);
end;
function TJs_CodeGen.GenCodeUnaryOperator(p:p_node;dt:cardinal;dv:longint):boolean;
var os:cardinal;
vs:longint;
begin
result:=c_Locate(p.first,os,vs); // Localizamos el valor (que pasara a result)
c_emit(p.kind,dt,dv,os,vs); // Se ejecuta el operador y el resultado pasa al destino esperado
c_unallocreg(os,vs); // Por si acaso !!
end;
function TJs_CodeGen.GenCodePreInc(p:p_node;dt:cardinal;dv,k:longint):boolean;
var o1,o2,os:cardinal;
v1,v2,vs:longint;
begin
p:=p.first;if not (p.kind in [jst_ident,jst_Index,jst_member]) then begin result:=c_Error('Can''t autoincrement',p);exit;end;
if p.kind=jst_Ident then begin
result:=c_Locate(p,os,vs);
c_emit(jst_Add,os,vs,opT_Integer,k);
c_emit(op_Move,os,vs,opt_Single,ops_Result);
c_unallocreg(os,vs);
c_emit(op_Move,dt,dv,opt_Single,ops_Result);
exit;
end;
// Si llegamos aqui se trata de un jst_Index
result:=c_Locate(p.first,o1,v1) and c_Locate(p.first.next,o2,v2); // Localizamos el objeto y su propiedad
c_Emit(op_GetProperty,o1,v1,o2,v2);
c_emit(jst_Add,opt_Single,ops_Result,opT_Integer,k);
c_Emit(op_SetProperty,o1,v1,o2,v2);
c_unallocreg(o1,v1);c_unallocreg(o2,v2);
c_emit(op_Move,dt,dv,opt_Single,ops_Result);
end;
function TJs_CodeGen.GenCodePostInc(p:p_node;dt:cardinal;dv,k:longint):boolean;
var o1,o2,os:cardinal;
v1,v2,vs:longint;
begin
p:=p.first;if not (p.kind in [jst_ident,jst_Index,jst_member]) then begin result:=c_Error('Can''t autoincrement',p);exit;end;
if p.kind=jst_Ident then begin
result:=c_Locate(p,os,vs); // Localizamos el identificador
c_emit(op_Move,dt,dv,os,vs); // Lo copiamos al destino
c_emit(jst_Add,os,vs,opT_Integer,k); // Lo incrementamos
c_emit(op_Move,os,vs,opt_Single,ops_Result); // Y guardamos el cambio
c_unallocreg(os,vs);
exit;
end;
// Si llegamos aqui se trata de un jst_Index
result:=c_Locate(p.first,o1,v1) and c_Locate(p.first.next,o2,v2); // Localizamos el objeto y su propiedad
c_Emit(op_GetProperty,o1,v1,o2,v2); // Sacamos el valor de la propiedad
c_emit(op_Move,dt,dv,opt_Single,ops_Result); // La copiamos en el destino
c_emit(jst_Add,opt_Single,ops_Result,opT_Integer,k); // La incrementamos
c_Emit(op_SetProperty,o1,v1,o2,v2); // Y la guardamos
c_unallocreg(o1,v1);c_unallocreg(o2,v2);
end;
// Nos dice si p ESCRIBE el valor de result
function TJs_CodeGen.c_result(p:p_node):boolean;
begin
result:=(p.kind=jst_Index) or (p.kind=jst_member) or (p.kind=jst_fcall) or js_tokenIsUnaryPreOp(p.kind) or js_tokenIsUnaryPostOp(p.kind) or js_kindIsBinOp(p.kind);
end;
function TJs_CodeGen.c_IsProperty(p:p_node):boolean;
begin
result:=(p.parent.kind=jst_member) and (p.prev<>nil);
end;
function TJs_CodeGen.c_tokenToFlag(k:cardinal;OnTrue:boolean):cardinal;
begin
if not js_flaggedOp(k) then k:=opF_Eq;
result:=JS_BoolOpRes[k,OnTrue];
end;
function TJs_CodeGen.c_FunctionRealName(s:string):string;
var i:longint;
begin
i:=length(s)-1;
while (i>0) and (s[i]<>'#') do i:=i-1;
if (i>0) and (s[i+1]<>'!') then result:=copy(s,i+1,length(s)) else result:='';
end;
function TJs_CodeGen.c_InvertFlag(k:longint):longint;
var i:longint;
begin
if (k=opF_BADFLAG) or (k=opF_NoFlag) then begin result:=k;exit;end;
if k=opF_True then begin result:=opF_False;exit;end;
if k=opF_False then begin result:=opF_True;exit;end;
result:=0;
i:=jst_Min_BoolOp;while (result=0) and (i<=jst_Max_boolOp) do if JS_BoolOpRes[i,true]=k then result:=JS_BoolOpRes[i,false] else i:=i+1;
if result<>0 then exit;
i:=jst_Min_BoolOp;while (result=0) and (i<=jst_Max_boolOp) do if JS_BoolOpRes[i,false]=k then result:=JS_BoolOpRes[i,true] else i:=i+1;
end;
function TJs_CodeGen.GenCodeAndExpression(p:p_node;dt:cardinal;dv:longint):boolean;
var l,f:longint;
k:Cardinal;
begin
p:=p.first;result:=true;l:=c_incLabel;
while (p<>nil) and result do begin
// Si es un boolean
// SI es FALSO emitiremos un salto, Si es TRUE lo ignoramos
if p.kind=jst_bool then begin if p.value=0 then begin k:=opt_None;f:=opF_NoFlag;p:=n_LastBrother(p);end;end
else begin k:=opt_Flag;f:=c_InvertFlag(GenCodeFlaggedExpresssion(p));result:=f<>opF_BADFLAG;end;
if result then c_emit(op_JumpR,k,f,opt_Label,l);
p:=p.next;
end;
c_emit(op_Label,opT_Label,l,opt_None,0); // La etiqueta de salida
if dt<>opT_None then c_emit(op_SetOn,dt,dv,opT_Flag,opF_False); // Si hubo algun salto
end;
function TJs_CodeGen.GenCodeOrExpression(p:p_node;dt:cardinal;dv:longint):boolean;
var l,f:longint;
k:Cardinal;
begin
p:=p.first;result:=true;l:=c_incLabel;k:=opt_None;f:=opF_NoFlag;
while (p<>nil) and result do begin
// Si es un boolean
// TRUE: SI es cierto emitiremos un salto, Si es falso lo ignoramos
if p.kind=jst_bool then begin if p.value<>0 then begin k:=opt_None;f:=opF_NoFlag;p:=n_LastBrother(p);end;end
else begin k:=opt_Flag;f:=GenCodeFlaggedExpresssion(p);result:=f<>opF_BADFLAG;end;
if result then c_emit(op_JumpR,k,f,opt_Label,l);
p:=p.next;
end;
c_emit(op_Label,opT_Label,l,opt_None,0); // La etiqueta de salida
if dt<>opT_None then c_emit(op_SetOn,dt,dv,opT_Flag,opF_True); // Si hubo algun salto
end;
// El unico operador binario de derercha a izquierda es assign, asi que los
// gestionamos a piņon de izquierda a derecha
function TJs_CodeGen.GenCodebinOperator(p:p_node;dt:cardinal;dv:longint):boolean;
var p1:p_node;
o1,o2:cardinal;
v1,v2:longint;
copied:boolean;
begin
p1:=p.first; result:=c_Locate(p1,o1,v1);if not result then exit; // Localizamos el primer operador
p1:=p1.next; result:=c_Locate(p1,o2,v2);if not result then exit; // Y el segundo
copied:=false;
if js_flaggedOp(p.kind) then begin
c_emit(op_Compare,o1,v1,o2,v2);
// La expresion 1==1==5==3 da true (se toma el primer resultado), que en este caso ya estaria copiado
if (dt<>opT_None) and (dt<>opT_Flag) then begin copied:=true;c_emit(op_SetOn,dt,dv,opT_Flag,c_tokenToFlag(p.kind,true));end;
end else c_emit(p.kind,o1,v1,o2,v2);
if js_IsAssignOp(p.kind) then result:=GenCodeCarryAssign(p.first,o1,v1); // Si se trata de +=,-=,... hemos de copiar result en p.first
p1:=p1.next;
c_unallocreg(o1,v1);c_unallocreg(o2,v2);
while result and (p1<>nil) do begin
if c_result(p1) then begin o1:=opT_reg;v1:=c_allocreg(p1);c_emit(op_Move,opT_Reg,v1,opt_Single,ops_Result);end
else if not js_IsAssignOp(p.kind) then begin o1:=opt_Single;v1:=ops_Result;end else c_emit(op_Move,o1,v1,opt_Single,ops_Result);
result:=c_Locate(p1,o2,v2);
if result then begin
if js_flaggedOp(p.kind) then c_emit(op_Compare,o1,v1,o2,v2) else c_emit(p.kind,o1,v1,o2,v2);
if js_IsAssignOp(p.kind) then result:=GenCodeCarryAssign(p.first,o1,v1); // Si se trata de +=,-=,... hemos de copiar result en p.first
end; // Emitimos
c_unallocreg(o2,v2);
c_unallocreg(o1,v1);
p1:=p1.next; // Si tenemos mas de dos operadores, el primero sera result
end;
// Si tenemos un destino
if not copied then c_emit(op_Move,dt,dv,opt_Single,ops_Result);
end;
function TJs_CodeGen.GenCodeArrayDef(p:p_node;dt:cardinal;dv:longint):boolean;
var c:pJs_CodeNode;
o1:cardinal;
v1:longint;
begin
p:=p.first;result:=true;
if dt=opt_Param then begin o1:=opt_Reg;v1:=c_allocreg(p);end else begin o1:=dt;v1:=dv;end;
c:=c_emit(op_CreateParams,opT_Integer,0,opT_none,0); // Generamos un frame de llamada
while (p<>nil) and result do begin
result:=GenCodeExpression(p,opT_Param,c.v1);
c.v1:=c.v1+1;
p:=p.next;
end;
c_emit(op_NewArray,o1,v1,opt_None,0); // Creamos el array en dt,dv
c_emit(op_DestroyParams,opt_None,0,opt_None,0); // Destruimos los parametros
if dt=opt_Param then begin c_emit(op_Move,dt,dv,opt_Reg,v1);c_unallocreg(opt_Reg,v1);end;
end;
function TJs_CodeGen.GenCodeNewExpression(p:p_node;dt:cardinal;dv:longint):boolean;
var o1,o2:cardinal;
v1,v2:longint;
c:pJs_CodeNode;
b:boolean;
begin
if p.kind=jst_Begin then p:=p.first; // Si tenemos parametros lo tendremos agrupado con un jst_Begin (es un "error" del parser)
result:=c_Locate(p,o1,v1);if not result then exit; // Localizamos el constructos
c:=c_emit(op_CreateParams,opT_Integer,0,opT_none,0); // Generamos un frame
p:=p.next; // Pasamos a los parametros (si lo hay)
while (p<>nil) and result do begin result:=GenCodeExpression(p,opT_Param,c.v1);c.v1:=c.v1+1;p:=p.next;end;
if not result then exit;
b:=dt=opt_None;
if b then begin dt:=opt_reg;dv:=c_allocreg(p);end; // Por si acaso NO teniamos donde recoger el objeto
// Si dt es result la llamada al call lo machacara,
// Si dt es opt_Param se refiere al parametro del frame precedente
// En ambos casos usaremos un registro intermedio
if (IsResult(dt,dv)) or (dt=opt_Param) then begin o2:=opT_reg;v2:=c_allocreg(p);end else begin o2:=dt;v2:=dv;end;
c_emit(op_NewObject,o2,v2,o1,v1); // Creamos el objeto, indicando que hemos de copiar el prototype
c_emit(op_Call,o2,v2,o1,v1); // Ejecutamos el constructor (this sera restaurado a la vuelta)
c_emit(op_Construct,o2,v2,opT_None,0); // Comprobamos si hay algo que restaurar
// Si dt era result emitimos el move
if (IsResult(dt,dv)) or (dt=opt_Param) then c_emit(op_Move,dt,dv,o2,v2);
c_unallocreg(o2,v2);
c_unallocreg(o1,v1);
if b then c_unallocreg(dt,dv);
c_emit(op_DestroyParams,opT_None,0,opT_none,0); // Generamos un frame
end;
function TJs_CodeGen.GenCodeForIn(p:p_node):boolean;
var o1,o2,os:cardinal;
v1,v2,v3,vs:longint;
c1,c2:pJs_CodeNode;
p1:p_node;
begin
p:=p.first; // Esta es la clausula IN
if n_ChildCount(p)<>2 then begin result:=c_Error('Bad encoding in For In',p);exit;end; // Que solo puede tener dos hijos
p1:=p.first.next;result:=c_Locate(p1,o2,v2);if not result then exit; // El segundo ha de ser un objeto
v3:=c_allocreg(p); // Reservamos un registro V3 donde guardar el iterador
c_emit(op_NewIter,opT_reg,v3,o2,v2); // Generamos el iterador (sin asignar) en el registro V3
c_unallocreg(o2,v2); // Ya no necesitamos el objeto
p1:=p.first; // Esta es la referencia que recibira el valor del iterador
c1:=c_NewLabel; // La etiqueta de vuelta
if p1.kind=jst_Ident then result:=c_Locate(p1,os,vs) else // Si la referencia es una variable
if p1.kind in [jst_Index,jst_Member] then begin // Si es un Objeto
result:=c_Locate(p1.first,o1,v1); // Localizamos el Objeto
result:=result and c_Locate(p1.first.next,o2,v2); // Localizamos el objeto y su propiedad
os:=opt_Single;vs:=ops_Result;
end else result:=c_Error('For IN needs a reference',p);
if not result then exit;
c_emit(op_IterNext,os,vs,opT_reg,v3); // Copia el valor del iterador en os,vs y avanza
c2:=c_emit(op_Jump,opT_Flag,opF_NEq,opT_Label,c_incLabel); // Saltamos a la salida
if os=opt_Single then begin
c_Emit(op_SetProperty,o1,v1,o2,v2); // Si se trataba de un Objeto
c_unallocreg(o1,v1);c_unallocreg(o2,v2);
end;
result:=GenCodeStatement(p.next);if not result then exit; // Generamos el codigo
c_emit(op_Jump,opT_None,0,opT_Label,c1.v1); // Volvemos al principio
c_emit(op_Label,opT_Label,c2.v2,opt_None,0); // La etiqueta de salida
c_unallocreg(opT_reg,v3);
c_unallocreg(o1,v1);
end;
function TJs_CodeGen.GenCodeFor(p:p_node):boolean;
var c1,c2:pJS_CodeNode;
k1:cardinal;
f,k2:longint;
begin
p:=p.first;
result:=GenCodeStatement(p);if not result then exit; //
c1:=c_NewLabel; // El inicio del bucle
p:=p.next; // La condicion de salida
if p.kind<>jst_None then begin
// Si la expresion activa flags, la generamos directamente, sino la localizamos
if js_flaggedOp(p.kind) then begin result:=GenCodeExpression(p,opT_None,0);f:=c_tokenToFlag(p.kind,false);end
else begin result:=c_Locate(p,k1,k2);c_emit(op_Compare,k1,k2,opt_Null,0);c_unallocreg(k1,k2);f:=opF_NEq;end;
if not result then exit;
// Si la expresion no se cumple saltamos al final
c2:=c_emit(op_Jump,opT_Flag,f,opt_Label,c_incLabel);
end else c2:=nil;
p:=p.next;
// Emitimos el codigo
result:=GenCodeStatement(p.next);if not result then exit;
// Emitimos el incremento
if p.kind<>jst_None then result:=GenCodeStatement(p);
// Volvemos al principio
c_emit(op_Jump,opt_None,0,opt_Label,c1.v1);
// Salida del bucle
if c2<>nil then c_emit(op_Label,opT_Label,c2.v2,opt_None,0);
end;
function TJs_CodeGen.GenCodeBreak(p:p_node):boolean;
begin
p.value:=c_incLabel;
result:=c_emit(op_Jump,opT_None,0,opt_Label,p.value)<>nil;
end;
function TJs_CodeGen.GenCodeBreakHelper(p:p_node):boolean;
begin
result:=c_Emit(op_Label,opt_Label,p.data.value,opt_None,0)<>nil;
end;
// Genera codigo para una expresion que es convertible a BOOLEANA, devuelve
// los flags que se activan si la expresion es TRUE -> Si falla devuelve opF_BADFLAG
function TJs_CodeGen.GenCodeFlaggedExpresssion(p:p_node):longint;
var k1:cardinal;
k2:longint;
begin
result:=opF_BADFLAG;
// Si la expresion es de tipo flagged la hacemos y devolvemos el FLAG que se activa si la expresion es cierta
if js_flaggedOp(p.kind) then begin if GenCodeExpression(p,opT_None,0) then result:=c_tokenToFlag(p.kind,true);exit;end;
// Si llegamos aqui se trata de una expresion que no activa Flags Directamente
if not c_Locate(p,k1,k2) then exit; // Calculamos la expresion
c_emit(op_Compare,k1,k2,opt_Null,0); // La comparamos con NULL
c_unallocreg(k1,k2);
result:=opF_NEq; // La expresion sera OK si se activa el FLAG de EQUAL
end;
function TJs_CodeGen.GenCodeWhile(p:p_node):boolean;
var p1:p_node;
c1,c2:pJs_CodeNode;
f:longint;
begin
p1:=p.first;result:=true;
// En el caso particular de siempre false, se trata de DeadCode que nunca se ejecuta
if (p1.kind=jst_bool) and (p1.value=0) then exit;
// Generamos una etiqueta
c1:=c_NewLabel;
// Si tenemos un booleano solo puede ser true (la expresion nunca falla), en otro caso generamos codigo para calcular la expression
if p1.kind<>jst_bool then begin
f:=GenCodeFlaggedExpresssion(p1);result:=f<>opF_BADFLAG;if not result then exit;
c2:=c_emit(op_Jump,opT_Flag,c_InvertFlag(f),opt_Label,c_incLabel); // Si la expresion falla salimos
end else c2:=nil;
p1:=p1.next;
result:=GenCodeStatement(p1);
c_emit(op_Jump,opt_None,0,opT_Label,c1.v1); // Volvemos al principio
if c2<>nil then c_Emit(op_Label,opt_Label,c2.v2,opt_None,0); // El punto de salida
end;
function TJs_CodeGen.GenCodeTry(p:p_node):boolean;
var nc,nf:p_node;
i1,i2,old_err_ident:longint;
begin
if n_kind(p.parent)=jst_finally then begin nf:=p.next;nf.value:=c_incLabel;end else nf:=nil; // nf nos dice si tenemos nodo de finally
if n_kind(p.first.next)=jst_catch then begin nc:=p.first.next.first;nc.value:=c_incLabel;end else nc:=nil; // nc nos dice si tenemos node de catch
i1:=c_incLabel; // La etiqueta de final de bloque
i2:=c_incLabel; // La etiqueta de salida del codigo
c_emit(op_PushFrame,opt_FrameError,opFr_TryFrame,opt_Offset,1); // Iniciamos un bloque de Try, necesario. El retorno es +1
// para instrucciones que rompen el flujo: return, break,...
if nf<>nil then c_emit(op_PushFrame,opt_FrameError,opFr_FinalFrame,opT_Label,nf.value); // Pusheamos la direccion de Finally
if nc<>nil then c_emit(op_PushFrame,opt_FrameError,opFr_CatchFrame,opT_Label,nc.value); // Pusheamos la direccion de Catch
result:=GenCodeStatement(p.first);if not result then exit; // Hacemos el codigo del Try
if nc<>nil then c_emit(op_PopFrame,opt_FrameError,opFr_CatchFrame,opt_None,0); // Si hemos llegado aqui no ha habido error y eliminamos el CatchFrame
if nf<>nil then c_emit(op_PopFrame,opt_FrameError,opFr_FinalFrame,opt_None,0) // Si tenemos un FinalFrame lo ejecutamos
else c_emit(op_Jump,opt_None,0,opT_Label,i2); // Sino saltamos a detras del bloque TRY|CATCH|FINALLY
if nc<>nil then begin // Si hay un error
c_emit(op_Label,opT_Label,nc.value,opt_None,0); // Aqui comienza el bloque de catch
old_err_ident:=err_ident;err_ident:=nc.hash; // Dentro del Catch tenemos activa la variable ERROR
result:=GenCodeStatement(nc.next);if not result then exit; // Hacemos el codigo del Catch
err_ident:=old_err_ident; // Desactivamos el acceso al ident de error dentro del catch
if nf<>nil then c_emit(op_PopFrame,opt_FrameError,opFr_FinalFrame,opt_None,0) // Si tenemos un FinalFrame lo ejecutamos
else c_emit(op_Jump,opt_None,0,opT_Label,i2); // Sino saltamos a detras del bloque TRY|CATCH|FINALLY
end;
if nf<>nil then begin
c_emit(op_Label,opT_Label,nf.value,opt_None,0); // Aqui comienza el bloque de finally
result:=GenCodeStatement(nf); // Generamos el codigo de Finally
end;
c_emit(op_Label,opT_Label,i2,opt_None,0); // Esto es el final del bloque TRY|CATCH|FINALLY
c_emit(op_PopFrame,opt_FrameError,opFr_TryFrame,opt_None,0); // Salimos del todo
c_emit(op_Label,opT_Label,i1,opt_None,0); // Esto es el despues del bloque TRY|CATCH|FINALLY
end;
function TJs_CodeGen.GenCodeThrow(p:p_node):boolean;
var et:cardinal;
ev:longint;
begin
result:=c_Locate(p.first,et,ev); // Localizamos la expresion a lanzar
c_emit(op_Throw,et,ev,opt_none,0); // La lanzamos
c_unallocreg(et,ev); // La "deslocalizamos"
end;
function TJs_CodeGen.GenCodeIf(p:p_node):boolean;
var p1:p_node;
c1,c2:pJs_CodeNode;
f:longint;
begin
p1:=p.first;
// Si siempre es true o false NO generamos codigo para la parte que no se ejecuta nunca
if p1.kind=jst_bool then begin p:=p1.next;if p1.value=0 then p:=n_next(p);p:=n_first(p);result:=GenCodeStatement(p);exit;end;
// Generamos codigo para la expresion, devuelve el FLAG si la expresion es cierta
f:=GenCodeFlaggedExpresssion(p1);result:=f<>opF_BADFLAG;if not result then exit;
// Si la expresion NO Se cumple saltamos al final o al else
c1:=c_emit(op_Jump,opT_Flag,c_InvertFlag(f),opt_Label,c_incLabel);
p1:=p1.next;result:=GenCodeStatement(p1);if not result then exit; // Generamos codigo para el bloque de true
p1:=p1.next;
if p1<>nil then c2:=c_Emit(op_Jump,opt_None,0,opt_Label,c_incLabel); // Si tenemos un bloque de else nos lo saltamos
c_Emit(op_Label,opt_Label,c1.v2,opt_None,0);
if p1<>nil then begin result:=GenCodeStatement(p1);c_Emit(op_Label,opt_Label,c2.v2,opt_None,0);end;
end;
function TJs_CodeGen.GenCodeIfOperator(p:p_node;dt:cardinal;dv:longint):boolean;
var p1:p_node;
c1,c2:pJs_CodeNode;
k1:cardinal;
f,k2:longint;
begin
p1:=p.first;
// Si siempre es true o false NO generamos codigo para la parte que no se ejecuta nunca
if p1.kind=jst_bool then begin p:=p1.next;if p1.value=0 then p:=n_next(p);p:=n_first(p);result:=GenCodeStatement(p);exit;end;
// Si la expresion activa flags, la geeneramos directamente, sino la localizamos
if js_flaggedOp(p1.kind) then begin result:=GenCodeExpression(p1,opT_None,0);f:=c_tokenToFlag(p1.kind,false);end
else begin result:=c_Locate(p1,k1,k2);c_emit(op_Compare,k1,k2,opt_Null,0);c_unallocreg(k1,k2);f:=opF_NEq;end;
if not result then exit;
c1:=c_emit(op_Jump,opT_Flag,f,opt_Label,c_incLabel);
p1:=p1.next;result:=GenCodeExpression(p1,dt,dv);if not result then exit; // Generamos codigo para el bloque de true
p1:=p1.next;
if p1<>nil then c2:=c_Emit(op_Jump,opt_None,0,opt_Label,c_incLabel);
// Emitimos un label
c_Emit(op_Label,opt_Label,c1.v2,opt_None,0);
if p1<>nil then begin result:=GenCodeExpression(p1,dt,dv);c_Emit(op_Label,opt_Label,c2.v2,opt_None,0);end;
end;
function TJs_CodeGen.GenCodeCall(p:p_node;dt:cardinal;dv:longint):boolean;
var ok,o1:cardinal;
ov,v1:longint;
c:pJs_CodeNode;
p1:p_node;
begin
p1:=p.first;result:=true; // Este es el nodo con a que llamamos
p:=p1.next;c:=c_emit(op_CreateParams,opT_Integer,0,opT_none,0); // Vamos a los parametros y generamos un frame de llamada
while (p<>nil) and result do begin result:=GenCodeExpression(p,opT_Param,c.v1);c.v1:=c.v1+1;p:=p.next;end; // Y metemos en el mismo los parametros
if not result then exit; // Si ha ocurrido algun fallo salimos
if p1.kind in [jst_Index,jst_Member] then begin ok:=cur_ThisK;ov:=cur_thisV;end else ok:=opt_None; // Si la funcion a llamar es un miembro o indice, en el calculo de la misma se sobreescribira Cur_This
result:=c_Locate(p1,o1,v1);if not result then exit; // Localizamos la funcion a llamar
c_emit(op_Call,cur_ThisK,cur_thisV,o1,v1); // Generamos el call
c_emit(op_DestroyParams,opt_None,0,opt_None,0); // Devolvemos los parametros (NO COPIA result)
c_emit(op_Move,dt,dv,opt_Single,ops_Result); // Copiamos result
c_unallocreg(o1,v1); // Por si acaso hemos hecho un alloc de o1,v1
if (ok<>cur_ThisK) then begin // Si se ha modificado This
c_unallocreg(cur_ThisK,cur_ThisV); // Liberamos
cur_ThisK:=ok;cur_thisV:=ov; // Y restauramos
end;
end;
function TJs_CodeGen.GenCodeIndex(p:p_node;dt:cardinal;dv:longint):boolean;
var r,v1,v2:longint;
o1,o2:cardinal;
keep_this:boolean;
begin
keep_this:=p.parent.kind=jst_fcall; // Marcamos si estamos en un call
p:=p.first;result:=c_Locate(p,o1,v1);if not result then exit; // Obtenemos la base
p:=p.next; // Ahora la referencia
if (p.parent.kind=jst_member) then begin o2:=opT_ExtPChar;v2:=js_program_AddCodeString(programa,p.text);end // . ident lo tratamos como ['ident']
else begin result:=c_Locate(p,o2,v2);if not result then exit;end; // Cualquier otra expresion la resolvemos
if keep_this then begin
if o1<>opt_Reg then r:=c_allocreg(p) else r:=v1;
c_emit(op_ToObject,opt_Reg,r,o1,v1);
o1:=opt_Reg;v1:=r;
end;
c_emit(op_GetProperty,o1,v1,o2,v2); // Obtenemos la propiedad
c_emit(op_Move,dt,dv,opt_Single,ops_Result); // La copiamos en result
if not keep_this then c_unallocreg(o1,v1) else begin cur_thisK:=o1;cur_thisV:=v1;end; // Si no estamos en call hacemos unalloc. Si estamos en call aun lo necesitaremos
c_unallocreg(o2,v2);
end;
function TJs_CodeGen.GenCodeExpressionGroup(p:p_node;dt:cardinal;dv:longint):boolean;
begin
p:=p.first;result:=true;
while (p.next<>nil) and result do begin result:=GenCodeExpression(p,opT_None,0);p:=p.next;end;
if not result then exit;
result:=GenCodeExpression(p,dt,dv);
end;
function TJs_CodeGen.GenCodeExpression(p:p_node;dt:cardinal;dv:longint):boolean;
begin
if p=nil then begin s_alert('GenCodeExpression for nil');result:=false;Exit;end;
case p.kind of
jst_New: result:=GenCodeNewExpression(p.first,dt,dv);
jst_ExpGroup: result:=GenCodeExpressionGroup(p,dt,dv);
jst_FuncDef: result:=GenCodeFuncExpression(p,dt,dv);
jst_Assign: result:=GenCodeAssign(p,dt,dv);
jst_Index: result:=GenCodeIndex(p,dt,dv);
jst_member: result:=GenCodeIndex(p,dt,dv);
jst_fcall: result:=GenCodeCall(p,dt,dv);
jst_pchar: begin c_emit(op_Move,dt,dv,opT_ExtPChar,js_program_AddCodeString(programa,p.text));result:=true;end;
jst_Integer: begin c_emit(op_Move,dt,dv,opT_Integer,s_s2i(p.text));result:=true;end;
jst_This: begin c_emit(op_Move,dt,dv,opt_Single,opS_This);result:=true;end; // c_emit ya filtra los automove(s)
jst_Null: begin c_emit(op_Move,dt,dv,opt_Null,0);result:=true;end;
jst_bool: begin c_emit(op_Move,dt,dv,opt_Boolean,p.value);result:=true;end;
jst_ident: result:=GenCodeIdent(p,dt,dv);
jst_ObjectDef: result:=GenCodeObject(p,dt,dv);
jst_ArrayDef: result:=GenCodeArrayDef(p,dt,dv);
jst_CondIf: result:=GenCodeIfOperator(p,dt,dv);
jst_PostInc: result:=GenCodePostInc(p,dt,dv,1);
jst_PostDec: result:=GenCodePostInc(p,dt,dv,-1);
jst_PreInc: result:=GenCodePreInc(p,dt,dv,1);
jst_PreDec: result:=GenCodePreInc(p,dt,dv,-1);
jst_Or: result:=GenCodeOrExpression(p,dt,dv);
jst_And: result:=GenCodeAndExpression(p,dt,dv);
jst_Float: result:=GenCodeFloat(p,dt,dv);
jst_None: result:=true;
jst_TypeOf,jst_Not,jst_Negative,jst_Positive,jst_bNot: result:=GenCodeUnaryOperator(p,dt,dv);
//jst_Begin: begin result:=true;p:=p.first;while result and (p<>nil) do begin result:=GenCode
else if js_kindIsBinOp(p.kind) then result:=GenCodeBinOperator(p,dt,dv)
else result:=c_error('Not implemented genCode for '+s_i2s(p.kind),p);
end;
end;
function TJs_CodeGen.GenCodeFuncExpression(p:p_node;dt:cardinal;dv:longint):boolean;
var p1:p_node;
begin
// Nos aseguramos de que la Function_Expresion tenga codigo asociado
p1:=p.data;if n_kind(p1)<>jst_CodeDef then begin result:=c_Error('Internal error FE without body',p);exit;end;
// El codigo asociado debe de tener un bloque de generacion de codigo, lo creamos ya.
if p1.value=0 then p1.value:=js_program_AddFunction(programa,p1.text);
// Creamos un objeto funcion en dt,dv y que llame el bloque de codigo
c_emit(op_NewFunc,dt,dv,opT_Block,p1.value);
// Queda pendiente la copia de variables en el objeto a efectos de closures !!
result:=true;
end;
function TJs_CodeGen.GenCodeGetterSetter(p:p_node;dt:cardinal;dv:longint):boolean;
var p1,p2:p_node;
k:cardinal;
l:longint;
begin
l:=js_program_AddCodeString(programa,p.text);p1:=p.first; // Guardamos el nombre y vamos al primer hijo
while p1<>nil do begin
p2:=p1.data; // Vamos al primer Getter o Setter
if n_kind(p2)<>jst_CodeDef then begin result:=c_Error('Internal error GET-SET without body',p1);exit;end; // Que debe tener codigo
if p2.value=0 then p2.value:=js_program_AddFunction(programa,p2.text); // Que debe haber generado un bloque
c_emit(op_NewFunc,opt_Single,ops_Result,opT_Block,p2.value); // Creamos una funcion que apunta a ese bloque
if p1.kind=jst_Getter then k:=op_Getter else k:=op_Setter; // ŋ Es un getter o un setter ?
c_emit(k,dt,dv,opT_ExtPChar,l); // Emitimos la creacion del mismo
p1:=p1.next;
end;
result:=true;
end;
function TJs_CodeGen.GenCodeObject(p:p_node;dt:cardinal;dv:longint):boolean;
var et:cardinal;
ev:longint;
begin
// A no se que se trate del objeto vacio, vamos a machacar RESULT, asi que si lo necesitamos...
if (IsResult(dt,dv)) and (p.first<>nil) then begin et:=opt_reg;ev:=c_allocreg(p);end else begin et:=dt;ev:=dv;end;
// Generamos el objeto y lo guardamos en dt,dv
c_emit(op_NewObject,et,ev,opt_none,0);
// ahora vamos a hacer las propiedades y metodos del objetos
p:=p.first;result:=true;
while (p<>nil) and (result) do begin
case p.kind of
jst_Member: begin result:=genCodeExpression(p.first,opt_Single,ops_Result);c_Emit(op_SetProperty,et,ev,opT_ExtPChar,js_program_AddCodeString(programa,p.text));end;
jst_GetSet: result:=GenCodeGetterSetter(p,et,ev);
else result:=c_Error('Internal Error in Object members',p);
end;
p:=p.next;
end;
if (et<>dt) then begin c_emit(op_Move,dt,dv,et,ev);c_unallocreg(et,ev);end;
end;
// Genera el codigo de una funcion, durante la generacion del codigo pueden "crearse" en el nodo de variables
// las variables indirectas (que corresponden a closures). Como cuando se conoce esto ya se han emitido los opcodes de variables
// hay dos posibilidades: insertar los opcodes de variables tras la generacion de statements
// generar el codigo fuera de PROGRAM, luego las variables en PROGRAM y mover el codigo a PROGRAM (esta es la opcion implementada)
function TJs_CodeGen.GenFunctionBody(p:p_node):boolean;
var oc:pJs_Function;
pfunc_ident:cardinal;
pv,p1:p_node;
s:string;
begin
pv:=vars;s:=c_FunctionRealName(p.text); // Este es el nombre real de la funcion
pfunc_ident:=func_ident;if (s<>'') and (p.number=1) then func_ident:=s_hash(s) else func_ident:=0; // Si la funcion era anonima y tenia un nombre usaremos CurFunc para implementar recursividad
result:=p.value<>0;if not result then begin c_Error('Missing function code',p);exit;end; // No deberia de ocurrir nunca, para eso esta el parser
vars:=p.first;cb:=js_function_create;oc:=cb; // Creamos un bloque de codigo nuevo, y lo hacemos CB (current_block)
p1:=vars.next;while (p1<>nil) and result do begin result:=GenCodeStatement(p1);p1:=p1.next;end; // Generamos el codigo
if result then begin // Si todo ha ido bien
cb:=js_program_FunctionByIndex(programa,p.value); // Volvemos al bloque que habiamos reservado para la funcion
cb.src_start:=p.pos;cb.src_len:=p.len; // guardamos donde comienza y la longitud del bloque (solo tiene sentido para funciones)
p1:=vars.first;cb.nvars:=vars.value;cb.nvars_cl:=vars.number; // Guardamos cuantas variables se definen en stack y cuantas en GC
while (p1<>nil) and result do begin result:=c_emitVar(cb,p1,opT_Var);p1:=p1.next;end; // Y emitimos el codigo para generar las variables, incluidas las capturadas !!
b_pad(cb.programa.integers,4); // Padeamos
js_function_move(cb,oc); // Finalmente movemos el codigo de oc a cb
cb.nlabels:=oc.nlabels;
if n_kind(n_LastBrother(p.first))<>jst_Return then c_Emit(op_Ret,opT_None,0,opt_None,0); // Si la ultima instruccion NO es return aņadimos un return
end;
js_function_Free(oc); // Liberamos la funcion
vars:=pv;func_ident:=pfunc_ident;
end;
{
procedure TJs_CodeGen.PrintCode;
var p:pjs_smalllist;
n,k:longint;
d:pJs_CodeNode;
s,r1,r2:string;
begin
js_print(' ');
p:=programa.blocks;k:=js_smalllist_count(p);n:=0;
while k>0 do begin
cb:=p^;
js_print('----------------------------------------------------------------------');
js_print('Block: '+js_i2s(n)+' '+js_program_Pchar(programa,cb.name));
d:=cb.first;
while d<>nil do begin
s:=js_pad(js_LCode2Str(d.opcode,d.k1,d.v1,d.k2,d.v2),50);
if d.k1=opT_PChar then r1:=js_pad('p1='+js_program_Pchar(programa,d.v1),15)+' ' else r1:='';
if d.k2=opT_PChar then r2:=js_pad('p2='+js_program_Pchar(programa,d.v2),15) else r2:='';
if (r1<>'') or (r2<>'') then s:=s+'; ';
if r1<>'' then s:=s+r1;
if r2<>'' then s:=s+r2;
js_print( js_pad( js_Pointer2Str(d),15)+s);
d:=d.next;
end;
k:=k-1;inc(p);n:=n+1;
end;
end;
}
initialization
// Cuando se ejecute una comparacion Booleana, el flag que se activa, dependera del resultado de la operacion. Esto se mapea aqui para
// cada operador
JS_BoolOpRes[jst_Equals ,true]:=opF_Eq;
JS_BoolOpRes[jst_Diff ,true]:=opF_NEq;
JS_BoolOpRes[jst_strictEq ,true]:=opF_Eq;
JS_BoolOpRes[jst_strictDif ,true]:=opF_NEq;
JS_BoolOpRes[jst_Big ,true]:=opF_Big;
JS_BoolOpRes[jst_BigEq ,true]:=opF_BigEq;
JS_BoolOpRes[jst_Less ,true]:=opF_Less;
JS_BoolOpRes[jst_LessEq ,true]:=opF_LessEq;
JS_BoolOpRes[jst_In ,true]:=opF_Eq;
JS_BoolOpRes[jst_Equals ,false]:=opF_NEq;
JS_BoolOpRes[jst_Diff ,false]:=opF_Eq;
JS_BoolOpRes[jst_strictEq ,false]:=opF_NEq;
JS_BoolOpRes[jst_strictDif,false]:=opF_Eq;
JS_BoolOpRes[jst_Big ,false]:=opF_NBig;
JS_BoolOpRes[jst_BigEq ,false]:=opF_NBigEq;
JS_BoolOpRes[jst_Less ,false]:=opF_NLess;
JS_BoolOpRes[jst_LessEq ,false]:=opF_NLessEq;
JS_BoolOpRes[jst_In ,false]:=opF_NEq;
end.
|
unit uCardForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, jpeg, ExtCtrls;
type
TCardForm = class(TForm)
Image1: TImage;
cbCard: TComboBox;
lbCard: TLabel;
btnTake: TButton;
procedure btnTakeClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure cbCardChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
CardForm: TCardForm;
card_to_load: integer;
implementation
uses uMainForm, uCommon;
{$R *.dfm}
procedure TCardForm.btnTakeClick(Sender: TObject);
begin
if cbCard.ItemIndex = -1 then
ShowMessage('Please choose a card.')
else
Close;
end;
procedure TCardForm.FormShow(Sender: TObject);
var
i: integer;
begin
cbCard.Clear;
case card_to_load of
CT_COMMON_ITEM: for i := 1 to gCurrentPlayer.ItemsCount do cbCard.Items.Add(IntToStr(gCurrentPlayer.Cards[i]));
//CT_UNIQUE_ITEM: for i := 1 to Unique_Items_Count do cbCard.Items.Add(IntToStr(Unique_Items_Deck.card[i]));
//CT_SPELL: for i := 1 to Spells_Count do cbCard.Items.Add(IntToStr(Spells_Deck.card[i]));
//CT_SKILL: for i := 1 to Skills_Count do cbCard.Items.Add(IntToStr(Skills_Deck.card[i]));
end;
end;
procedure TCardForm.cbCardChange(Sender: TObject);
begin
case card_to_load of
CT_COMMON_ITEM: Image1.Picture.LoadFromFile(ExtractFilePath(Application.ExeName) + '\CardsData\CommonItems\' + cbCard.Text + '.jpg');
CT_UNIQUE_ITEM: Image1.Picture.LoadFromFile(ExtractFilePath(Application.ExeName) + '\CardsData\UniqueItems\' + cbCard.Text + '.jpg');
CT_SPELL: Image1.Picture.LoadFromFile(ExtractFilePath(Application.ExeName) + '\CardsData\Spells\' + cbCard.Text + '.jpg');
CT_SKILL: Image1.Picture.LoadFromFile(ExtractFilePath(Application.ExeName) + '\CardsData\Skills\' + cbCard.Text + '.jpg');
end;
end;
end.
|
unit ClassDodaci;
interface
uses Classes, Typy;
type PDodaciPol = ^TDodaciPol;
TDodaciPol = record
Nazov : string;
Jednotka : string;
Mnozstvo : string;
ZarDoba : string;
SerCisla : array of string;
end;
TDodaci = class
private
FPolozky : TList;
FKtoVys : string;
FDatVys : string;
FKtoPri : string;
FDatPri : string;
FKtoSch : string;
FDatSch : string;
FOdberatel : TSpolocnost;
FFileName : string;
function GetPolozky( Polozka : pointer ) : TDodaciPol;
function GetPolozkyCount : integer;
function GetOdberatel( I : integer ) : string;
function GetOdberatelCount : integer;
procedure SetPolozky( Polozka : pointer; Pol : TDodaciPol );
procedure SetOdberatel( I : integer; New : string );
procedure SetOdberatelCount( New : integer );
procedure Clear;
public
constructor Create;
destructor Destroy; override;
procedure New; overload;
function New( Faktura : TFaktura ) : boolean; overload;
function Open( FileName : string ) : boolean;
function Save( FileName : string ) : boolean;
function GetPolozka( Index : integer ) : pointer;
function AddPolozka : pointer;
procedure DeletePolozka( Polozka : pointer );
procedure DeleteAllPolozky;
property Polozky[Polozka : pointer] : TDodaciPol read GetPolozky write SetPolozky;
property PolozkyCount : integer read GetPolozkyCount;
property KtoVys : string read FKtoVys write FKtoVys;
property DatVys : string read FDatVys write FDatVys;
property KtoPri : string read FKtoPri write FKtoPri;
property DatPri : string read FDatPri write FDatPri;
property KtoSch : string read FKtoSch write FKtoSch;
property DatSch : string read FDatSch write FDatSch;
property Odberatel[I : integer] : string read GetOdberatel write SetOdberatel;
property OdberatelCount : integer read GetOdberatelCount write SetOdberatelCount;
property ICO : string read FOdberatel.ICO write FOdberatel.ICO;
property FileName : string read FFileName;
end;
var Dodaci : TDodaci;
implementation
uses ClassGlobals;
constructor TDodaci.Create;
begin
FPolozky := TList.Create;
FKtoVys := '';
FDatVys := '';
FKtoPri := '';
FDatPri := '';
FKtoSch := '';
FDatSch := '';
FOdberatel.Adresa := TStringList.Create;
FOdberatel.ICO := '';
FFileName := '';
end;
destructor TDodaci.Destroy;
begin
DeleteAllPolozky;
FPolozky.Free;
FOdberatel.Adresa.Free;
end;
//==============================================================================
// P R I V A T E
//==============================================================================
function TDodaci.GetPolozky( Polozka : pointer ) : TDodaciPol;
var I : integer;
begin
I := FPolozky.IndexOf( Polozka );
if ((I < 0) or
(I >= FPolozky.Count)) then
begin
Result.Nazov := '';
Result.Jednotka := '';
Result.Mnozstvo := '';
Result.ZarDoba := '';
SetLength( Result.SerCisla , 0 );
end
else
Result := TDodaciPol( FPolozky[I]^ );
end;
function TDodaci.GetPolozkyCount : integer;
begin
Result := FPolozky.Count;
end;
function TDodaci.GetOdberatel( I : integer ) : string;
begin
if ((I < 0) or
(I >= FOdberatel.Adresa.Count)) then
Result := ''
else
Result := FOdberatel.Adresa[I];
end;
function TDodaci.GetOdberatelCount : integer;
begin
Result := FOdberatel.Adresa.Count;
end;
procedure TDodaci.SetPolozky( Polozka : pointer; Pol : TDodaciPol );
var I : integer;
begin
I := FPolozky.IndexOf( Polozka );
if ((I < 0) or
(I >= FPolozky.Count)) then
exit
else
TDodaciPol( FPolozky[I]^ ) := Pol;
end;
procedure TDodaci.SetOdberatel( I : integer; New : string );
begin
if ((I < 0) or
(I >= FOdberatel.Adresa.Count-1)) then
exit;
FOdberatel.Adresa[I] := New;
end;
procedure TDodaci.SetOdberatelCount( New : integer );
var I, Count : integer;
begin
Count := FOdberatel.Adresa.Count;
if (New > Count) then
begin
for I := Count to New do
FOdberatel.Adresa.Add( '' );
end
else
if (New < Count) then
begin
for I := New-1 to Count-1 do
FOdberatel.Adresa.Delete( I );
end
end;
procedure TDodaci.Clear;
var I : integer;
begin
for I := 0 to FPolozky.Count-1 do
begin
SetLength( PDodaciPol( FPolozky[I] )^.SerCisla , 0 );
Dispose( PDodaciPol( FPolozky[I] ) );
FPolozky[I] := nil;
end;
FPolozky.Clear;
FKtoVys := '';
FDatVys := '';
FKtoPri := '';
FDatPri := '';
FKtoSch := '';
FDatSch := '';
FOdberatel.Adresa.Clear;
FOdberatel.ICO := '';
end;
//==============================================================================
// P U B L I C
//==============================================================================
procedure TDodaci.New;
begin
Clear;
FFileName := Globals.GetNewFileName( Globals.DodacieDir , Globals.DodacieExt );
end;
function TDodaci.New( Faktura : TFaktura ) : boolean;
begin
Result := false;
Clear;
end;
function TDodaci.Open( FileName : string ) : boolean;
var F : TextFile;
I, J, Count, Count2 : integer;
Pol : ^TDodaciPol;
S : string;
begin
Clear;
AssignFile( F , FileName );
Reset( F );
Readln( F , Count );
for I := 0 to Count-1 do
begin
System.New( Pol );
FPolozky.Add( Pol );
Readln( F , Pol^.Nazov );
Readln( F , Pol^.Jednotka );
Readln( F , Pol^.Mnozstvo );
Readln( F , Pol^.ZarDoba );
Readln( F , Count2 );
SetLength( Pol^.SerCisla , Count2 );
for J := 0 to Count2-1 do
Readln( F , Pol^.SerCisla[J] );
end;
Readln( F , FKtoVys );
Readln( F , FDatVys );
Readln( F , FKtoPri );
Readln( F , FDatPri );
Readln( F , FKtoSch );
Readln( F , FDatSch );
Readln( F , Count );
for I := 0 to Count-1 do
begin
Readln( F , S );
FOdberatel.Adresa.Add( S );
end;
Readln( F , FOdberatel.ICO );
CloseFile( F );
Result := true;
FFileName := FileName;
end;
function TDodaci.Save( FileName : string ) : boolean;
var F : TextFile;
I, J : integer;
Pol : TDodaciPol;
begin
AssignFile( F , FileName );
Rewrite( F );
// Save data
Writeln( F , FPolozky.Count );
for I := 0 to FPolozky.Count-1 do
begin
Pol := TDodaciPol( FPolozky[I]^ );
Writeln( F , Pol.Nazov );
Writeln( F , Pol.Jednotka );
Writeln( F , Pol.Mnozstvo );
Writeln( F , Pol.ZarDoba );
Writeln( F , Length( Pol.SerCisla ) );
for J := 0 to Length( Pol.SerCisla )-1 do
Writeln( F , Pol.SerCisla[J] );
end;
Writeln( F , FKtoVys );
Writeln( F , FDatVys );
Writeln( F , FKtoPri );
Writeln( F , FDatPri );
Writeln( F , FKtoSch );
Writeln( F , FDatSch );
Writeln( F , FOdberatel.Adresa.Count );
for I := 0 to FOdberatel.Adresa.Count-1 do
Writeln( F , FOdberatel.Adresa[I] );
Writeln( F , FOdberatel.ICO );
CloseFile( F );
Result := true;
FFileName := FileName;
end;
function TDodaci.GetPolozka( Index : integer ) : pointer;
begin
Result := nil;
if ((Index < 0) or
(Index >= FPolozky.Count)) then
exit;
Result := FPolozky[Index];
end;
function TDodaci.AddPolozka : pointer;
var Pol : ^TDodaciPol;
begin
// Allocate memory
System.New( Pol );
// Set result value
Result := Pol;
// Add new item
FPolozky.Add( Pol );
// Reset values
Pol^.Nazov := '';
Pol^.Jednotka := '';
Pol^.Mnozstvo := '';
Pol^.ZarDoba := '';
SetLength( Pol^.SerCisla , 0 );
end;
procedure TDodaci.DeletePolozka( Polozka : pointer );
var Index : integer;
begin
Index := FPolozky.IndexOf( Polozka );
if ((Index < 0) or
(Index >= PolozkyCount)) then
exit;
// Free memory
System.Dispose( FPolozky.Items[Index] );
FPolozky.Delete( Index );
end;
procedure TDodaci.DeleteAllPolozky;
var I : integer;
begin
for I := 0 to FPolozky.Count-1 do
System.Dispose( FPolozky.Items[I] );
FPolozky.Clear;
end;
end.
|
unit MediaStream.PtzProtocol.Base;
interface
type
TPtzProtocol = class
//Движение
procedure PtzMoveUp(aDuration: cardinal; aSpeed: byte); virtual; abstract;
procedure PtzMoveUpStop; virtual; abstract;
procedure PtzMoveDown(aDuration: cardinal; aSpeed: byte); virtual; abstract;
procedure PtzMoveDownStop; virtual; abstract;
procedure PtzMoveLeft(aDuration: cardinal; aSpeed: byte); virtual; abstract;
procedure PtzMoveLeftStop; virtual; abstract;
procedure PtzMoveRight(aDuration: cardinal; aSpeed: byte); virtual; abstract;
procedure PtzMoveRightStop; virtual; abstract;
//===== Перемещение на заданную позицию
//Движение на указанную точку-пресет
procedure PtzMoveToPoint(aId: cardinal); virtual; abstract;
//Движение в указанную позицию. Позиция указывается по оси X и Y в градусах
procedure PtzMoveToPosition(const aPositionPan,aPositionTilt: double); virtual; abstract;
//Масштаб
procedure PtzZoomIn(aDuration: cardinal); virtual; abstract;
procedure PtzZoomInStop; virtual; abstract;
procedure PtzZoomOut(aDuration: cardinal); virtual; abstract;
procedure PtzZoomOutStop; virtual; abstract;
//Фокус
procedure PtzFocusIn(aDuration: cardinal); virtual; abstract;
procedure PtzFocusInStop; virtual; abstract;
procedure PtzFocusOut(aDuration: cardinal); virtual; abstract;
procedure PtzFocusOutStop; virtual; abstract;
//Апертура (способность собирать свет и противостоять дифракционному размытию деталей изображения)
procedure PtzApertureIncrease(aDuration: cardinal); virtual; abstract;
procedure PtzApertureIncreaseStop; virtual; abstract;
procedure PtzApertureDecrease(aDuration: cardinal); virtual; abstract;
procedure PtzApertureDecreaseStop; virtual; abstract;
end;
implementation
end.
|
unit ksVirtualListViewTest;
interface
uses
DUnitX.TestFramework,
ksTypes,
ksCommon,
ksVirtualListView;
type
[TestFixture]
TksVirtualListViewTest = class(TObject)
private
FListView: TksVirtualListView;
FEventFired: Boolean;
procedure Add100Items;
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
// tests...
[Test] procedure TestGetCheckedCount;
[Test] procedure Test1000Items;
[Test] procedure TestClearItems;
[Test] procedure TestScrollToLastItem;
[Test] procedure TestAccessories;
[Test] procedure TestGetItemFromPos;
[Test] procedure TestTotalItemHeight;
[Test] procedure TestTopItem;
[Test] procedure TestItemHorzAlignments;
[Test] procedure TestItemVertAlignments;
[Test] procedure TestTextWidth;
[Test] procedure TestTextHeight;
[Test] procedure TestTextHeightMultiLine;
end;
implementation
uses SysUtils, System.UITypes, System.UIConsts, System.Classes;
//----------------------------------------------------------------------------------------------------
procedure TksVirtualListViewTest.Setup;
begin
FListView := TksVirtualListView.Create(nil);
FEventFired := False;
end;
procedure TksVirtualListViewTest.TearDown;
begin
FListView.Free;
end;
//----------------------------------------------------------------------------------------------------
procedure TksVirtualListViewTest.Add100Items;
var
ICount: integer;
begin
// arrange
// act
FListView.BeginUpdate;
try
for ICount := 1 to 100 do
FListView.Items.Add('Item '+IntToStr(ICount), 'a sub title', 'the detail', atNone);
finally
FListView.EndUpdate;
end;
end;
procedure TksVirtualListViewTest.TestGetCheckedCount;
var
ICount: integer;
begin
FListView.CheckBoxes.Visible := True;
FListView.CheckBoxes.Mode := TksSelectionType.ksMultiSelect;
Add100Items;
for ICount := 1 to 100 do
begin
if ICount mod 2 = 0 then
FListView.Items[ICount-1].Checked := True;
end;
Assert.AreEqual(50, FListView.Items.CheckedCount);
end;
procedure TksVirtualListViewTest.TestGetItemFromPos;
var
AItem: TksVListItem;
begin
Add100Items;
AItem := FListView.Items.ItemAtPos(10, 600);
Assert.AreEqual(13, AItem.Index);
end;
procedure TksVirtualListViewTest.TestItemHorzAlignments;
var
ICount: TAlignment;
begin
for ICount := Low(TAlignment) to High(TAlignment) do
begin
with FListView.Items.Add('', '', '') do
AddText(30, 0, 'TEST').HorzAlign := ICount;
end;
Assert.AreEqual(3, FListView.Items.Count);
end;
procedure TksVirtualListViewTest.TestItemVertAlignments;
var
ICount: TVerticalAlignment;
begin
for ICount := Low(TVerticalAlignment) to High(TVerticalAlignment) do
begin
with FListView.Items.Add('', '', '') do
AddText(30, 0, 'TEST').VertAlign := ICount;
end;
Assert.AreEqual(3, FListView.Items.Count);
end;
procedure TksVirtualListViewTest.Test1000Items;
var
ICount: integer;
begin
// arrange
// act
FListView.BeginUpdate;
try
for ICount := 1 to 1000 do
FListView.Items.Add('Item '+IntToStr(ICount), 'a sub title', 'the detail', atNone);
finally
FListView.EndUpdate;
end;
// assert
Assert.AreEqual(1000, FListView.Items.Count);
end;
procedure TksVirtualListViewTest.TestAccessories;
var
ICount: TksAccessoryType;
begin
FListView.BeginUpdate;
for ICount := Low(TksAccessoryType) to High(TksAccessoryType) do
FListView.Items.Add('Item', '', '', ICount);
FListView.EndUpdate;
end;
procedure TksVirtualListViewTest.TestClearItems;
begin
// arrange
Add100Items;
// act
FListView.ClearItems;
// assert
Assert.AreEqual(True, FListView.IsEmpty);
end;
procedure TksVirtualListViewTest.TestScrollToLastItem;
var
AResult: Extended;
begin
// arrange
Add100Items;
// act
FListView.ScrollToBottom(False);
// assert
AResult := FListView.ScrollPos;
Assert.AreEqual(4350.0, AResult);
end;
procedure TksVirtualListViewTest.TestTextHeight;
var
AHeight: string;
begin
FListView.Items.Add('This is a test', '', '');
AHeight := FormatFloat('0.00', FListView.Items[0].Title.Height);
Assert.AreEqual('18.29', AHeight);
end;
procedure TksVirtualListViewTest.TestTextHeightMultiLine;
var
AHeight: string;
begin
FListView.Items.Add('This is a test'+#13+'This is the second line...'+#13+'And the third :-)', '', '');
AHeight := FormatFloat('0.00', FListView.Items[0].Title.Height);
Assert.AreEqual('52.87', AHeight);
end;
procedure TksVirtualListViewTest.TestTextWidth;
var
AWidth: string;
begin
FListView.Items.Add('This is a test', '', '');
AWidth := FormatFloat('0.00', FListView.Items[0].Title.Width);
Assert.AreEqual('70.92', AWidth);
end;
procedure TksVirtualListViewTest.TestTopItem;
begin
Add100Items;
Assert.AreEqual(0, FListView.TopItem.Index);
end;
procedure TksVirtualListViewTest.TestTotalItemHeight;
begin
Add100Items;
Assert.AreEqual(4400, Integer(Round(FListView.TotalItemHeight)));
end;
initialization
TDUnitX.RegisterTestFixture(TksVirtualListViewTest);
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ SOAP Support }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Soap.SOAPEnv;
interface
uses
Soap.OPConvert, Xml.XMLIntf;
type
TSoapEnvelope = class
public
function MakeEnvelope(Doc: IXMLDocument; Options: TSOAPConvertOptions): IXMLNode;
function MakeHeader(ParentNode: IXMLNode; Options: TSOAPConvertOptions): IXMLNode;
function MakeBody(ParentNode: IXMLNode; Options: TSOAPConvertOptions): IXMLNode;
function MakeFault(ParentNode: IXMLNode; Options: TSOAPConvertOptions): IXMLNode;
end;
implementation
uses
Soap.SOAPConst, Soap.OpConvertOptions;
function TSoapEnvelope.MakeEnvelope(Doc: IXMLDocument; Options: TSOAPConvertOptions): IXMLNode;
begin
Doc.AddChild(SSoapNameSpacePre + ':' + SSoapEnvelope, SoapEnvelopeNamespaces[soSOAP12 in Options]);
Result := Doc.DocumentElement;
Result.DeclareNamespace(SXMLSchemaNameSpacePre, XMLSchemaNameSpace);
Result.DeclareNamespace(SXMLSchemaInstNameSpace99Pre, XMLSchemaInstNameSpace);
if not (soDocument in Options) then
Result.DeclareNamespace(SSoapEncodingPre, SoapEncodingNamespaces[soSOAP12 in Options]);
end;
function TSoapEnvelope.MakeBody(ParentNode: IXMLNode; Options: TSOAPConvertOptions): IXMLNode;
begin
Result := ParentNode.AddChild(SSoapNameSpacePre + ':' + SSoapBody, SoapEnvelopeNamespaces[soSOAP12 in Options]);
end;
function TSoapEnvelope.MakeHeader(ParentNode: IXMLNode; Options: TSOAPConvertOptions): IXMLNode;
begin
Result := ParentNode.AddChild(SSoapNameSpacePre + ':' + SSoapHeader, SoapEnvelopeNamespaces[soSOAP12 in Options]);
end;
function TSoapEnvelope.MakeFault(ParentNode: IXMLNode; Options: TSOAPConvertOptions): IXMLNode;
begin
Result := ParentNode.AddChild(SSoapNameSpacePre + ':' + SSoapFault, SoapEnvelopeNamespaces[soSOAP12 in Options]);
end;
end.
|
unit Filer;
interface
uses
Classes, IniFiles, Graphics, Dialogs,
MetroBase, MetroVisCom, StringValidators;
type
//----------------------------------------------------------------------------
// TNetworkFiler is a class with some routines for reading/writing
// a network from/to a .nwk file
//----------------------------------------------------------------------------
TNetworkFiler = class(TObject)
protected
FIniFile: TMemIniFile;
FFileSections: TStringList;
procedure ReadStations(var ANetwork: TNetwork);
// pre: FIniFile contains the description of a network (N, SS, LS), where
// N is the networkname, SS is the stationset and LS is the lineset
// post: ANetwork.GetStationSet = SS
procedure ReadLines(var ANetwork: TNetwork);
// pre: FIniFile contains the description of a network (N, SS, LS), where
// N is the networkname, SS is the stationset and LS is the lineset
// post: ANetwork.GetLineSet = LS
public
// construction/destruction ------------------------------------------------
constructor Create(const AFileName: String);
// pre: True
// post: FIniFile is a copy in the internal memory of the ini-file AFileName
// and
// FFileSections contains the filesections of AFileName
destructor Destroy; override;
// pre: True
// effect: FIniFile and FFileSections are freed
// commands ----------------------------------------------------------------
function LoadNetwork: TNetwork;
// pre: FIniFile contains the description of a network (N, SS, LS), where
// N is the networkname, SS is the stationset and LS is the lineset
// ret: the network (N, SS, LS)
procedure WriteNetwork(ANetwork: TNetwork);
// pre: ANetwork is the network (N, SS, LS), where
// N is the networkname, SS is the stationset and LS is the lineset
// post: The internal representation of ANetwork in FIniFile is written to
// disk
end;
//----------------------------------------------------------------------------
// TMapFiler is a class with some routines for reading/writing
// a map from/to a .map file
//----------------------------------------------------------------------------
TMapFiler = class(TObject)
protected
FIniFile: TMemIniFile;
FFileSections: TStringList;
procedure ReadStations(var AMap: TMetroMap);
// pre: FIniFile contains the description of a map (N, B, SS, LS, LaS, TS),
// where N is the mapname, B is the filename of the background,
// SS is the set of stations, LS is the set of lines,
// LaS is the set of landmarks and TS is the set of texts
// post: AMap.AbstrStations = SS
procedure ReadLines(var AMap: TMetroMap);
// pre: FIniFile contains the description of a map (N, B, SS, LS, LaS, TS),
// where N is the mapname, B is the filename of the background,
// SS is the set of stations, LS is the set of lines,
// LaS is the set of landmarks and TS is the set of texts
// post: AMap.AbstrStations = LS
procedure ReadLandmarks(var AMap: TMetroMap);
// pre: FIniFile contains the description of a map (N, B, SS, LS, LaS, TS),
// where N is the mapname, B is the filename of the background,
// SS is the set of stations, LS is the set of lines,
// LaS is the set of landmarks and TS is the set of texts
// post: AMap.AbstrStations = LaS
procedure ReadTexts(var AMap: TMetroMap);
// pre: FIniFile contains the description of a map (N, B, SS, LS, LaS, TS),
// where N is the mapname, B is the filename of the background,
// SS is the set of stations, LS is the set of lines,
// LaS is the set of landmarks and TS is the set of texts
// post: AMap.AbstrStations = TS
public
// construction/destruction ------------------------------------------------
constructor Create(const AFileName: String);
// pre: True
// post: FIniFile is a copy in the internal memory of the ini-file AFileName
// and
// FFileSections contains the filesections of AFileName
destructor Destroy; override;
// pre: True
// effect: FIniFile and FFileSections are freed
// commands ----------------------------------------------------------------
function LoadMap: TMetroMap;
// pre: FIniFile contains the description of a map (N, B, SS, LS, LaS, TS),
// where N is the mapname, B is the filename of the background,
// SS is the set of stations, LS is the set of lines,
// LaS is the set of landmarks and TS is the set of texts
// ret: the map (N, B, SS, LS, LaS, TS)
procedure WriteMap(AMap: TMetroMap);
// pre: FIniFile contains the description of a map (N, B, SS, LS, LaS, TS),
// where N is the mapname, B is the filename of the background,
// SS is the set of stations, LS is the set of lines,
// LaS is the set of landmarks and TS is the set of texts
// post: The internal representation of AMap in FIniFile is written to disk
end;
//----------------------------------------------------------------------------
// TFiler is a class with some routines for reading/writing
// a map from/to a .map file and a network from/to a .nwk file
//----------------------------------------------------------------------------
TFiler = class(TObject)
protected
FMapFiler: TMapFiler;
FNetworkFiler: TNetworkFiler;
public
// construction/destruction ------------------------------------------------
constructor Create(AMapFileName: String; ANetworkFileName: String);
// pre: True
// post: FMapFiler.Create(AMapFile).post
// and
// FNetworkFiler.Create(ANetworkFileName).post
destructor Destroy; override;
// pre: True
// effect: FMapFiler and FNetworkFiler are freed
// derived queries ---------------------------------------------------------
function LoadNetwork: TNetwork;
// pre: True
// ret: FNetworkFiler.LoadNetwork
function LoadMap: TMetroMap;
// pre: True
// ret: FMapFiler.LoadMap
// commands ----------------------------------------------------------------
procedure WriteNetwork(ANetwork: TNetwork);
// pre: True
// post: FNetworkFiler.WriteNetwork(ANetwork).post
procedure WriteMap(AMap: TMetroMap);
// pre: True
// post: FMapFiler.WriteMap(AMap).post
end;
implementation
uses
SysUtils, StrUtils,
Auxiliary;
{ TFiler }
constructor TFiler.Create(AMapFileName: String; ANetworkFileName: String);
begin
FNetworkFiler := TNetworkFiler.Create(ANetworkFileName);
FMapFiler := TMapFiler.Create(AMapFileName)
end;
destructor TFiler.Destroy;
begin
FMapFiler.Free;
FNetworkFiler.Free;
inherited
end;
function TFiler.LoadMap: TMetroMap;
begin
Result := FMapFiler.LoadMap
end;
function TFiler.LoadNetwork: TNetwork;
begin
Result := FNetworkFiler.LoadNetwork
end;
procedure TFiler.WriteMap(AMap: TMetroMap);
begin
FMapFiler.WriteMap(AMap)
end;
procedure TFiler.WriteNetwork(ANetwork: TNetwork);
begin
FNetworkFiler.WriteNetwork(ANetwork)
end;
{ TNetworkFiler }
constructor TNetworkFiler.Create(const AFileName: string);
begin
FIniFile := TMemIniFile.Create(AFileName);
FFileSections := TStringList.Create;
FIniFile.ReadSections(FFileSections)
end;
destructor TNetworkFiler.Destroy;
begin
FFileSections.Free;
FIniFile.Free;
inherited
end;
function TNetworkFiler.LoadNetwork: TNetwork;
var
VNetwork: TNetwork;
VNetworkName: String;
begin
VNetworkName := FIniFile.ReadString('#Main', 'name', '<unknown>');
VNetwork := TNetwork.CreateEmpty(VNetworkName);
ReadStations(VNetwork);
ReadLines(VNetwork);
Result := VNetwork
end;
procedure TNetworkFiler.ReadLines(var ANetwork: TNetwork);
var
E, I, J, H: Integer;
VSectionName: String;
VLineName, VLineCode: String;
VLine: TLineRW;
VOneWay: Boolean;
VCircular: Boolean;
VLineOptions: TLineOptionS;
VStopCode: String;
VStop: TStationR;
VStops: TStringList;
begin
// filter out line sections (beginning with 'L_') and read their attributes
// and corresponding station lists
for I := 0 to FFileSections.Count - 1 do begin
VSectionName := FFileSections.Strings[I];
if AnSiStartsStr('L_', VSectionName) then begin
VLineCode := AnsiRightStr(VSectionName, Length(VSectionName) - 2);
// read line name
VLineName := FIniFile.ReadString(VSectionName, 'name', '<unknown>');
// read line options
VLineOptions := [];
VOneWay := FIniFile.ReadBool(VSectionName, 'oneway', False);
if VOneWay then VLineOptions := VLineOptions + [loOneWay];
VCircular := FIniFile.ReadBool(VSectionName, 'circular', False);
if VCircular then VLineOptions := VLineOptions + [loCircular];
// create line (with empty stationlist)
VLine := TLineRW.Create(VLineCode, VLineName, VLineOptions);
// read stops from corresponding 'P_' section and add them to line
VStops := TStringList.Create;
FIniFile.ReadSectionValues('P_' + VLineCode, VStops);
for J := 0 to VStops.Count - 1 do begin
E := Pos('=', VStops.Strings[J]);
VStopCode := RightStr(VStops.Strings[J], Length(VStops.Strings[J]) - E);
if ValidStationCode(VStopCode) then begin
with ANetwork.GetStationSet do begin
H := IndexOfCode(VStopCode);
Assert( H <> -1,
Format('TMetroFiler.Readlines: Unknown stop code: %s',
[VStopCode]));
VStop := GetStation(H);
VLine.AddStop(VStop)
end
end
else begin
{skip}
end
end;
ANetwork.AddLine(VLine);
VStops.Free
end
end
end;
procedure TNetworkFiler.ReadStations(var ANetwork: TNetwork);
var
I: Integer;
VSectionName: String;
VStationName, VStationCode: String;
begin
// filter out station sections (beginning with 'S_') and read their name
for I := 0 to FFileSections.Count - 1 do begin
VSectionName := FFileSections.Strings[I];
if AnSiStartsStr('S_', VSectionName) then begin
VStationCode := AnsiRightStr(VSectionName, Length(VSectionName) - 2);
VStationName := FIniFile.ReadString(VSectionName, 'name', '<unknown>');
ANetwork.AddStation(TStationRW.Create(VStationCode, VStationName))
end
end
end;
procedure TNetworkFiler.WriteNetwork(ANetwork: TNetwork);
var
I, J: Integer;
VStation: TStationR;
VLine: TLineR;
begin
FIniFile.Clear;
FIniFile.WriteString('#Main', 'name', ANetwork.GetName);
with ANetwork.GetStationSet do begin
for I := 0 to Count - 1 do begin
VStation := GetStation(I);
FIniFile.WriteString('S_' + VStation.GetCode, 'name',
VStation.GetName)
end
end;
with ANetwork.GetLineSet do begin
for I := 0 to Count - 1 do begin
VLine := GetLine(I);
FIniFile.WriteString('L_' + VLine.GetCode, 'name',
VLine.GetName);
FIniFile.WriteBool('L_' + VLine.GetCode, 'oneway',
VLine.IsOneWay);
FIniFile.WriteBool('L_' + VLine.GetCode, 'circular',
VLine.IsCircular);
for J := 0 to VLine.Count - 1 do begin
FIniFile.WriteString('P_' + VLine.GetCode,
'S' + IntToStr(J),
VLine.Stop(J).GetCode)
end
end
end;
FIniFile.UpdateFile;
end;
{ TMapFiler }
constructor TMapFiler.Create(const AFileName: string);
begin
FIniFile := TMemIniFile.Create(AFileName);
FFileSections := TStringList.Create;
FIniFile.ReadSections(FFileSections)
end;
destructor TMapFiler.Destroy;
begin
FFileSections.Free;
FIniFile.Free;
inherited
end;
function TMapFiler.LoadMap: TMetroMap;
var
VMap: TMetroMap;
VBlankPicture, VBackgroundPicture: TBitmap;
VBackgroundName, VBackgroundFilename: String;
VName: String;
begin
VName := FIniFile.ReadString('#Main', 'name', '<unknown>');
// Load background picture
VBackgroundName := FIniFile.ReadString('#Main', 'background', '<unknown>');
if VBackgroundName = '<unknown>' then begin
VBackgroundPicture := TBitmap.Create;
VBlankPicture := TBitmap.Create;
end
else begin
VBackgroundFileName :=
Format('../Images/Backgrounds/%s', [VBackgroundName]);
VBackgroundPicture := TBitmap.Create;
if FileExists(VBackgroundFileName) then begin
VBackgroundPicture.LoadFromFile(VBackgroundFileName)
end
else begin
MessageDlg('The image that should be used as the background of ' +
'this map does not exist in the directory "Images\Backgrounds".',
mtError, [mbOK], 0)
end;
VBlankPicture := TBitmap.Create;
VBlankPicture.Height := VBackgroundPicture.Height;
VBlankPicture.Width := VBackgroundPicture.Width;
VBlankPicture.Canvas.Pen.Color := clWhite;
VBlankPicture.Canvas.Brush.Color := clWhite;
VBlankPicture.Canvas.Rectangle(0, 0, VBackGroundPicture.Width,
VBackGroundPicture.Height)
end;
VMap := TMetroMap.Create(VName, nil, VBlankPicture, VBackgroundPicture,
VBackgroundName);
ReadStations(VMap);
ReadLines(VMap);
ReadLandmarks(VMap);
ReadTexts(VMap);
Result := VMap;
end;
procedure TMapFiler.ReadLandmarks(var AMap: TMetroMap);
var
I: Integer;
VSectionName: String;
VLandmarkCode: String;
VBitMapName: String;
VBitmapFileName: String;
VBitmap: TBitmap;
VX, VY: Integer;
begin
// filter out landmark sections (beginning with 'M_') and read their props
for I := 0 to FFileSections.Count - 1 do begin
VSectionName := FFileSections.Strings[I];
if AnSiStartsStr('M_', VSectionName) then begin
VLandmarkCode := AnsiRightStr(VSectionName, Length(VSectionName) - 2);
VBitmapName := FIniFile.ReadString(VSectionName, 'bitmap', '<unknown>');
VX := FIniFile.ReadInteger(VSectionName, 'x', -1);
VY := FIniFile.ReadInteger(VSectionName, 'y', -1);
if (VX <> -1) and (VY <> -1) and
(VBitmapName <> '<unknown>') then begin
VBitmap := TBitmap.Create;
VBitmapFileName :=
Format('../Images/Landmarks/%s', [VBitmapName]);
if FileExists(VBitmapFileName) then begin
VBitmap.LoadFromFile(VBitmapFileName)
end
else begin
MessageDlg('The image used to depict the landmark with code "' +
VLandmarkCode + '" can not be found in the directory ' +
'"Images\Landmarks".', mtError, [mbOK], 0);
VBitmap.LoadFromFile('../Images/Bitmaps/NoImage.bmp')
end;
AMap.Add(TVisLandmark.Create(VLandmarkCode, nil, VX, VY, VBitmap,
VBitmapName))
end
else if (VX <> -1) and (VY <> -1) and
(VBitmapName = '<unknown') then begin
VBitmap := TBitmap.Create;
AMap.Add(TVisLandmark.Create(VLandmarkCode, nil, VX, VY, VBitmap,
VBitmapName))
end
end
end
end;
procedure TMapFiler.ReadLines(var AMap: TMetroMap);
var
E, I, J: Integer;
VSectionName: String;
VLineName, VLineCode: String;
VLineColorName: String;
VLineColor: TColor;
VStation: TVisStation;
VLine: TVisLine;
VStopCode: String;
VStops: TStringList;
begin
// filter out line sections (beginning with 'L_') and read their attributes
// and corresponding station lists
for I := 0 to FFileSections.Count - 1 do begin
VSectionName := FFileSections.Strings[I];
if AnSiStartsStr('L_', VSectionName) then begin
VLineCode := AnsiRightStr(VSectionName, Length(VSectionName) - 2);
// read line name
VLineName := FIniFile.ReadString(VSectionName, 'name', '<unknown>');
// read line color
VLineColorName :=
FIniFile.ReadString(VSectionName, 'color', 'clBlack');
VLineColor := ColorNameToColor(VLineColorName);
// create line (with empty stationlist)
VLine := TVisLine.Create(VLineCode, nil, VLineColor);
// read stops from corresponding 'P_' section and add them to line
VStops := TStringList.Create;
FIniFile.ReadSectionValues('P_' + VLineCode, VStops);
for J := 0 to VStops.Count - 1 do begin
E := Pos('=', VStops.Strings[J]);
VStopCode := RightStr(VStops.Strings[J],
Length(VStops.Strings[J]) - E);
if ValidStationCode(VStopCode) then begin
VStation := AMap.GetStation(VStopCode);
VLine.AddStation(VStation);
end
end;
AMap.Add(VLine);
VStops.Free
end
end
end;
procedure TMapFiler.ReadStations(var AMap: TMetroMap);
var
I: Integer;
VSectionName: String;
VStationCode: String;
VStationKind: String;
VX, VY: Integer;
begin
// filter out station sections (beginning with 'S_') and read their name
for I := 0 to FFileSections.Count - 1 do begin
VSectionName := FFileSections.Strings[I];
if AnSiStartsStr('S_', VSectionName) then begin
VStationCode := AnsiRightStr(VSectionName, Length(VSectionName) - 2);
VStationKind := FIniFile.ReadString(VSectionName, 'kind', '<unknown>');
VX := FIniFile.ReadInteger(VSectionName, 'x', -1);
VY := FIniFile.ReadInteger(VSectionName, 'y', -1);
if (VX <> -1) and (VY <> -1) then begin
if VStationKind = 'stop' then begin
AMap.Add(TVisStationStop.Create(VStationCode, nil, VX, VY))
end
else if VStationKind = 'transfer' then begin
AMap.Add(TVisStationTransfer.Create(VStationCode, nil, VX, VY))
end
else if VStationKind = 'dummy' then begin
AMap.Add(TvisStationDummy.Create(VStationCode, VX, VY))
end
else
Assert(False, 'Unknown station kind in TMetroFiler.LoadMap')
end
end
end
end;
procedure TMapFiler.ReadTexts(var AMap: TMetroMap);
var
I: Integer;
VSectionName: String;
VTextCode: String;
VX, VY: Integer;
VText: String;
VTextPosString: String;
begin
// filter out text sections (beginning with 'T_') and read their props
for I := 0 to FFileSections.Count - 1 do begin
VSectionName := FFileSections.Strings[I];
if AnSiStartsStr('T_', VSectionName) then begin
VTextCode := AnsiRightStr(VSectionName, Length(VSectionName) - 2);
VX := FIniFile.ReadInteger(VSectionName, 'x', -1);
VY := FIniFile.ReadInteger(VSectionName, 'y', -1);
VText := FIniFile.ReadString(VSectionName, 'text', '<unknown>');
VTextPosString := FIniFile.ReadString(VSectionName, 'pos', '<unknown>');
if (VX <> -1) and (VY <> -1) and (VTextPosString <> '<unknown>') then begin
AMap.Add(TVisText.Create(VTextCode, nil, VX, VY, VText,
StringToTextPos(VTextPosString)))
end
end
end
end;
procedure TMapFiler.WriteMap(AMap: TMetroMap);
var
I, J: Integer;
begin
FIniFile.Clear;
FIniFile.WriteString('#Main', 'name', AMap.GetMapName);
FIniFile.WriteString('#Main', 'background', AMap.GetBackgroundFileName);
with AMap do begin
for I := 0 to VisComCount - 1 do begin
if GetVisCom(I) is TVisStationStop then begin
FIniFile.WriteString('S_' + GetVisCom(I).GetCode,
'kind', 'stop');
FIniFile.WriteString('S_' + GetVisCom(I).GetCode,
'x', IntToStr(TVisStationStop(GetVisCom(I)).X));
FIniFile.WriteString('S_' + GetVisCom(I).GetCode,
'y', IntToStr(TVisStationStop(GetVisCom(I)).Y))
end;
if GetVisCom(I) is TVisStationTransfer then begin
FIniFile.WriteString('S_' + GetVisCom(I).GetCode,
'kind', 'transfer');
FIniFile.WriteString('S_' + GetVisCom(I).GetCode,
'x', IntToStr(TVisStationTransfer(GetVisCom(I)).X));
FIniFile.WriteString('S_' + GetVisCom(I).GetCode,
'y', IntToStr(TVisStationTransfer(GetVisCom(I)).Y))
end;
if GetVisCom(I) is TVisStationDummy then begin
FIniFile.WriteString('S_' + GetVisCom(I).GetCode,
'kind', 'dummy');
FIniFile.WriteString('S_' + GetVisCom(I).GetCode,
'x', IntToStr(TVisStationDummy(GetVisCom(I)).X));
FIniFile.WriteString('S_' + GetVisCom(I).GetCode,
'y', IntToStr(TVisStationDummy(GetVisCom(I)).Y))
end
end
end;
with AMap do begin
for I := 0 to VisComCount - 1 do begin
if GetVisCom(I) is TVisLine then begin
FIniFile.WriteString('L_' + GetVisCom(I).GetCode, 'color',
ColorToColorName(TVisLine(GetVisCom(I)).GetColor));
for J := 0 to TVisLine(GetVisCom(I)).StationCount - 1 do begin
FIniFile.WriteString('P_' + GetVisCom(I).GetCode,
'S' + IntToStr(J),
TVisLine(GetVisCom(I)).GetStation(J).GetCode)
end
end
end
end;
with AMap do begin
for I := 0 to VisComCount - 1 do begin
if GetVisCom(I) is TVisLandmark then begin
FIniFile.WriteString('M_' + GetVisCom(I).GetCode,
'x', IntToStr(TVisLandmark(GetVisCom(I)).X));
FIniFile.WriteString('M_' + GetVisCom(I).GetCode,
'y', IntToStr(TVisLandmark(GetVisCom(I)).Y));
FIniFile.WriteString('M_' + GetVisCom(I).GetCode,
'bitmap', TVisLandmark(GetVisCom(I)).GetBitmapFileName)
end
end
end;
with AMap do begin
for I := 0 to VisComCount - 1 do begin
if GetVisCom(I) is TVisText then begin
FIniFile.WriteString('T_' + GetVisCom(I).GetCode,
'x', IntToStr(TVisText(GetVisCom(I)).X));
FIniFile.WriteString('T_' + GetVisCom(I).GetCode,
'y', IntToStr(TVisText(GetVisCom(I)).Y));
FIniFile.WriteString('T_' + GetVisCom(I).GetCode,
'text', TVisText(GetVisCom(I)).GetText);
FIniFile.WriteString('T_' + GetVisCom(I).GetCode,
'pos', TextPosToString(TVisText(GetVisCom(I)).GetTextPos));
end
end
end;
FIniFile.UpdateFile;
end;
end.
|
unit UOfficalLogin;
interface
uses IdSSL, IdSSLOpenSSL, Classes, IdHTTP;
type
ILogin = interface
function Login(usr, pwd: String):Boolean;
end;
TOfficalLogin = class(TInterfacedObject, ILogin)
public
Session, ProfileId, ProfileName: String;
function Login(usr, pwd: String):Boolean;
end;
implementation
function SplitString(const Source,ch:String):TStringList;
var
temp:String;
i:Integer;
begin
SplitString:=TStringList.Create;
//如果是空自符串则返回空列表
if Source='' then exit;
temp:=Source;
i:=pos(ch,Source);
while i<>0 do
begin
SplitString.add(copy(temp,0,i-1));
Delete(temp,1,i);
i:=pos(ch,temp);
end;
SplitString.add(temp);
end;
function TOfficalLogin.Login(usr: string; pwd: string):Boolean;
var
ssl:TIdSSLIOHandlerSocketOpenSSL;
http: TIDHttp;
ans: String;
sl: TStringList;
postDataStream, paramData: TStringStream;
begin
paramData := TStringStream.Create('user=' + usr + '&password=' + pwd + '&version=13');
postDataStream := TStringStream.Create('');
ssl := TIdSSLIOHandlerSocketOpenSSL.Create;
http := TIDHttp.Create;
http.IOHandler := ssl;
http.Post('https://login.minecraft.net', paramData, postDataStream);
postDataStream.Position := 0;
ans := postDataStream.DataString;
sl := SplitString(ans, ':');
if sl.Count = 5 then
begin
ProfileName := sl[2];
Session := sl[3];
ProfileId := sl[4];
exit(true);
end
else
exit(false);
end;
end.
|
unit TrayMenu.MainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, Menus, ImgList, ShlObj;
type
TFileInfo = record
Description: string;
IconIndex: integer;
end;
TMainForm = class(TForm)
TrayIcon: TTrayIcon;
PopupMenu: TPopupMenu;
est11: TMenuItem;
PopupIcons: TImageList;
DirectoryWatcherTimer: TTimer;
procedure FormCreate(Sender: TObject);
procedure TrayIconMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormDestroy(Sender: TObject);
procedure PopupMenuPopup(Sender: TObject);
procedure DirectoryWatcherTimerTimer(Sender: TObject);
protected
FRootPath: string;
procedure ParseCommandLine;
protected
FPopupMenuDirty: boolean;
procedure ReloadMenu;
procedure ReloadSubmenu(AParent: TMenuItem; const APath: string);
procedure SortSubmenu(AParent: TMenuItem);
function CompareMenuItems(A, B: TMenuItem): integer;
protected
procedure TryReadInfo(const AFilename: string; out AInfo: TFileInfo);
function GetShellLink(const AFilename: string): IShellLink;
function CopyIcon(const AIcon: HICON): integer;
protected
FHDir: THandle;
FHDirBuf: array[0..1024-1] of byte;
FHDirOverlapped: TOverlapped;
procedure SetupDirectoryWatcher;
procedure CleanupDirectoryWatcher;
procedure DirectoryWatcherRearm;
end;
TDirMenuItem = class(TMenuItem)
end;
TLinkMenuItem = class(TMenuItem)
protected
FFilename: string;
public
constructor Create(AOwner: TComponent; const AFilename: string); reintroduce;
procedure Click; override;
end;
var
MainForm: TMainForm;
implementation
uses SystemUtils, FilenameUtils, CommCtrl, ActiveX, ShellApi;
{$R *.dfm}
procedure TMainForm.FormCreate(Sender: TObject);
begin
inherited;
CoInitialize(nil);
OleInitialize(nil);
FRootPath := GetSpecialFolderPath(CSIDL_APPDATA)+'\TrayMenu'; //by default
ParseCommandLine;
ReloadMenu;
SetupDirectoryWatcher;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
CleanupDirectoryWatcher;
end;
type
EBadUsage = class(Exception);
procedure TMainForm.ParseCommandLine;
var i: integer;
s: string;
begin
i := 1;
while i < ParamCount do begin
s := AnsiLowerCase(Trim(ParamStr(i)));
if s='' then begin
Inc(i);
continue;
end;
if s='/path' then begin
Inc(i);
if i > ParamCount then
raise EBadUsage.Create('/path requires specifying path');
Self.FRootPath := CanonicalizePath(ParamStr(i), GetCurrentDir);
end;
raise EBadUsage.Create('Unknown parameter: "'+s+'"');
Inc(i);
end;
end;
procedure TMainForm.SetupDirectoryWatcher;
var res: integer;
begin
FHDir := CreateFile(PChar(Self.FRootPath), FILE_LIST_DIRECTORY, //or GENERIC_READ
FILE_SHARE_READ or FILE_SHARE_WRITE or FILE_SHARE_DELETE, nil,
OPEN_EXISTING, FILE_FLAG_OVERLAPPED or FILE_FLAG_BACKUP_SEMANTICS, 0);
if FHDir = INVALID_HANDLE_VALUE then FHDir := 0;
if FHDir = 0 then begin
res := GetLastError;
OutputDebugString('Cannot open target path with backup semantics, change notifications will be unavailable');
OutputDebugString(PChar('GetLastError='+IntToStr(res)));
exit;
end;
DirectoryWatcherRearm;
end;
procedure TMainForm.CleanupDirectoryWatcher;
begin
if FHDir <> 0 then begin
CancelIo(FHDir);
CloseHandle(FHDir);
end;
end;
//Do not call directly, done automatically
procedure TMainForm.DirectoryWatcherRearm;
var res: integer;
dwBytes: dword;
begin
if Self.FHDir = 0 then exit; //can't anything
FillChar(FHDirOverlapped, SizeOf(FHDirOverlapped), 0);
//Would be better to assign a completion routine but those don't run without
//us doing SleepEx or WaitForMessagesEx somewhere
if not ReadDirectoryChangesW(Self.FHDir, @FHDirBuf[0], SizeOf(FHDirBuf),
true, //monitor children
FILE_NOTIFY_CHANGE_FILE_NAME or FILE_NOTIFY_CHANGE_DIR_NAME or
FILE_NOTIFY_CHANGE_ATTRIBUTES or FILE_NOTIFY_CHANGE_SIZE or
FILE_NOTIFY_CHANGE_LAST_WRITE or FILE_NOTIFY_CHANGE_CREATION,
@dwBytes,
@FHDirOverlapped, nil) then
begin
res := GetLastError;
OutputDebugString('Cannot rearm change notifications, further change notifications will be unavailable');
OutputDebugString(PChar('GetLastError='+IntToStr(res)));
//Can't do much on error, won't get any more notifications, sad
end;
end;
procedure TMainForm.DirectoryWatcherTimerTimer(Sender: TObject);
var dwBytes: dword;
begin
if Self.FHDir = 0 then exit;
if GetOverlappedResult(Self.FHDir, Self.FHDirOverlapped, dwBytes, false) then begin
FPopupMenuDirty := true;
DirectoryWatcherRearm;
end;
end;
procedure TMainForm.PopupMenuPopup(Sender: TObject);
begin
if FPopupMenuDirty then
ReloadMenu;
end;
procedure TMainForm.ReloadMenu;
begin
FPopupMenuDirty := false;
PopupIcons.Clear;
ReloadSubmenu(PopupMenu.Items, FRootPath);
end;
procedure TMainForm.ReloadSubmenu(AParent: TMenuItem; const APath: string);
var sr: TSearchRec;
res: integer;
item: TMenuItem;
info: TFileInfo;
begin
AParent.Clear;
if APath = '' then exit;
res := SysUtils.FindFirst(APath+'\*.*', faAnyFile, sr);
while res = 0 do begin
if (sr.Name='') or (sr.Name='.') or (sr.Name='..') then begin
res := SysUtils.FindNext(sr);
continue;
end;
if (sr.Name[1]='.') or (sr.Attr and faHidden <> 0) then begin
res := SysUtils.FindNext(sr);
continue;
end;
if sr.Attr and faDirectory <> 0 then begin
item := TDirMenuItem.Create(Self.PopupMenu);
item.Caption := sr.Name;
TryReadInfo(APath+'\'+sr.Name, info);
item.ImageIndex := info.IconIndex;
AParent.Add(item);
ReloadSubmenu(item, APath+'\'+sr.Name);
end else begin
item := TLinkMenuItem.Create(Self.PopupMenu, APath+'\'+sr.Name);
item.Caption := ChangeFileExt(sr.Name, '');
TryReadInfo(APath+'\'+sr.Name, info);
item.Hint := info.Description;
item.ImageIndex := info.IconIndex;
AParent.Add(item);
end;
res := SysUtils.FindNext(sr);
end;
SysUtils.FindClose(sr);
SortSubmenu(AParent);
end;
procedure TMainForm.SortSubmenu(AParent: TMenuItem);
var i, j: integer;
item: TMenuItem;
begin
i := 0;
while i < AParent.Count-1 do begin
j := i-1;
while j >= 0 do begin
if CompareMenuItems(AParent.Items[j], AParent.Items[i]) <= 0 then begin
if j<i-1 then begin
item := AParent.Items[i];
AParent.Remove(item);
AParent.Insert(j+1, item);
end;
break;
end;
Dec(j);
end;
if j < 0 then begin
item := AParent.Items[i];
AParent.Remove(item);
AParent.Insert(0, item);
end;
Inc(i);
end;
end;
function TMainForm.CompareMenuItems(A, B: TMenuItem): integer;
var AD, BD: boolean;
begin
AD := (A is TDirMenuItem);
BD := (B is TDirMenuItem);
if AD <> BD then begin
if AD then
Result := -1
else
Result := +1;
exit;
end;
Result := CompareText(A.Caption, B.Caption);
end;
procedure TMainForm.TryReadInfo(const AFilename: string; out AInfo: TFileInfo);
var psl: IShellLink;
shInfo: SHFILEINFO;
res: integer;
begin
AInfo.Description := '';
AInfo.IconIndex := -1;
//If this is a link, we can query its link description
psl := Self.GetShellLink(AFilename);
if psl <> nil then begin
SetLength(AInfo.Description, MAX_PATH+1);
if SUCCEEDED(psl.GetDescription(PChar(AInfo.Description), MAX_PATH)) then
SetLength(AInfo.Description, StrLen(PChar(AInfo.Description))) //trim
else
AInfo.Description := '';
end;
//For files and folders we can query their explorer icons + type descriptions
res := ShellApi.SHGetFileInfo(PChar(AFilename), 0, shInfo, SizeOf(shInfo), SHGFI_TYPENAME or SHGFI_SMALLICON or SHGFI_SYSICONINDEX);
if res <> 0 then begin
if AInfo.Description='' then
AInfo.Description := shInfo.szTypeName;
//Icon from hIcon has [link] overlay, we prefer to get the system index and query directly
if shInfo.hIcon <> 0 then
DestroyIcon(shInfo.hIcon);
if (AInfo.IconIndex < 0) and (shInfo.iIcon <> 0) then begin
shInfo.hIcon := ImageList_GetIcon(res, shInfo.iIcon, ILD_NORMAL);
if shInfo.hIcon = 0 then
shInfo.hIcon := GetLastError;
AInfo.IconIndex := Self.CopyIcon(shInfo.hIcon);
DestroyIcon(shInfo.hIcon);
end;
end;
end;
function TMainForm.GetShellLink(const AFilename: string): IShellLink;
var ppf: IPersistFile;
begin
Result := nil;
if FAILED(CoCreateInstance(CLSID_ShellLink, nil, CLSCTX_INPROC_SERVER, IID_IShellLink, Result)) then
exit;
if FAILED(Result.QueryInterface(IPersistFile, ppf))
or FAILED(ppf.Load(PChar(AFilename), STGM_READ)) then begin
Result := nil;
exit;
end;
end;
function TMainForm.CopyIcon(const AIcon: HICON): integer;
var icon: TIcon;
begin
icon := TIcon.Create;
icon.Handle := AIcon;
Result := PopupIcons.AddIcon(icon);
end;
procedure TMainForm.TrayIconMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then begin
SetForegroundWindow(Application.Handle);
Application.ProcessMessages;
PopupMenu.AutoPopup := False;
PopupMenu.PopupComponent := TrayIcon;
PopupMenu.Popup(X, Y);
end;
end;
constructor TLinkMenuItem.Create(AOwner: TComponent; const AFilename: string);
begin
inherited Create(AOwner);
Self.FFilename := AFilename;
end;
procedure TLinkMenuItem.Click;
begin
inherited;
ShellExecute(0, PChar('open'), PChar(Self.FFilename), nil, nil, SW_SHOW);
end;
end.
|
unit netmapclasses;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, netaddrutils;
type
TCgnatNetmap = class(TCollectionItem)
private
FValidPrefix: Boolean;
FValidPrivateNw: Boolean;
FValidPublicNw: Boolean;
FValidDivision: Boolean;
FIntPrivateNw: UInt32;
FIntPublicNw: UInt32;
FPrefix: Integer;
FPrivateNw: String;
FPublicNw: String;
FDivision: Integer;
procedure SetPrefix(Value: Integer);
procedure SetPrivateNw(Value: String);
procedure SetPublicNw(Value: String);
procedure SetDivision(Value: Integer);
procedure Recalculate;
public
constructor Create(ACollection: TCollection); override;
destructor Destroy; override;
procedure Change(APrefix: Integer; APrivateNw, APublicNw: String; ADivision: Integer);
property Prefix: Integer read FPrefix write SetPrefix;
property PrivateNw: String read FPrivateNw write SetPrivateNw;
property PublicNw: String read FPublicNw write SetPublicNw;
property Division: Integer read FDivision write SetDivision;
property IntPrivateNw: UInt32 read FIntPrivateNw;
property IntPublicNw: UInt32 read FIntPublicNw;
end;
TCgnatNetmapList = class(TCollection)
private
function GetItem(Index: Integer): TCgnatNetmap;
procedure SetItem(Index: Integer; Value: TCgnatNetmap);
public
constructor Create;
destructor Destroy; override;
function Add: TCgnatNetmap;
function Add(APrefix: Integer; APrivateNw, APublicNw: String; ADivision: Integer): TCgnatNetmap;
function Insert(Index: Integer): TCgnatNetmap;
property Items[Index: Integer]: TCgnatNetmap read GetItem write SetItem; default;
end;
implementation
{ TCgnatNetmap }
constructor TCgnatNetmap.Create(ACollection: TCollection);
begin
inherited Create(ACollection);
FPrefix := 27;
FPrivateNw := '0.0.0.0';
FPublicNw := '0.0.0.0';
FDivision := 32;
end;
destructor TCgnatNetmap.Destroy;
begin
inherited Destroy;
end;
procedure TCgnatNetmap.SetPrefix(Value: Integer);
begin
FPrefix := Value;
Recalculate;
end;
procedure TCgnatNetmap.SetPrivateNw(Value: String);
begin
FPrivateNw := Value;
Recalculate;
end;
procedure TCgnatNetmap.SetPublicNw(Value: String);
begin
FPublicNw := Value;
Recalculate;
end;
procedure TCgnatNetmap.SetDivision(Value: Integer);
begin
FDivision := Value;
Recalculate;
end;
procedure TCgnatNetmap.Change(APrefix: Integer; APrivateNw, APublicNw: String; ADivision: Integer);
begin
FPrefix := APrefix;
FPrivateNw := APrivateNw;
FPublicNw := APublicNw;
FDivision := ADivision;
Recalculate;
end;
procedure TCgnatNetmap.Recalculate;
begin
FValidPrefix := (FPrefix >= 22) and (FPrefix <= 30);
FValidPrivateNw := AddressToInt(FPrivateNw, FIntPrivateNw);
FValidPublicNw := AddressToInt(FPublicNw, FIntPublicNw);
FValidDivision := (FDivision >= 2) and (FDivision <= 64);
FIntPrivateNw := IntAddrToIntNetwork(FIntPrivateNw, FPrefix);
FIntPublicNw := IntAddrToIntNetwork(FIntPublicNw, FPrefix);
if FValidPrefix and FValidPrivateNw then
FPrivateNw := IntToAddress(FIntPrivateNw);
if FValidPrefix and FValidPublicNw then
FPublicNw := IntToAddress(FIntPublicNw);
end;
{ TCgnatNetmapList }
constructor TCgnatNetmapList.Create;
begin
inherited Create(TCgnatNetmap);
end;
destructor TCgnatNetmapList.Destroy;
begin
inherited Destroy;
end;
function TCgnatNetmapList.Add: TCgnatNetmap;
begin
Result := TCgnatNetmap(inherited Add);
end;
function TCgnatNetmapList.Add(APrefix: Integer; APrivateNw, APublicNw: String; ADivision: Integer): TCgnatNetmap;
begin
Result := TCgnatNetmap(inherited Add);
Result.FPrefix := APrefix;
Result.FPrivateNw := APrivateNw;
Result.FPublicNw := APublicNw;
Result.FDivision := ADivision;
Result.Recalculate;
end;
function TCgnatNetmapList.Insert(Index: Integer): TCgnatNetmap;
begin
Result := TCgnatNetmap(inherited Insert(Index));
end;
function TCgnatNetmapList.GetItem(Index: Integer): TCgnatNetmap;
begin
Result := TCgnatNetmap(inherited GetItem(Index));
end;
procedure TCgnatNetmapList.SetItem(Index: Integer; Value: TCgnatNetmap);
begin
inherited SetItem(Index, Value);
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.
*****************************************************************
The following delphi code is based on Emule (0.46.2.26) Kad's implementation http://emule.sourceforge.net
and KadC library http://kadc.sourceforge.net/
*****************************************************************
}
{
Description:
DHT types
}
unit dhttypes;
interface
uses
classes,classes2,sysutils,windows,keywfunc,blcksock;
type
precord_DHT_keywordFilePublishReq=^record_DHT_keywordFilePublishReq;
record_DHT_keywordFilePublishReq=record
keyW:string;
crc:word; // last two bytes of 20 byte sha1
fileHashes:tmystringlist;
end;
type
precord_dht_source=^record_dht_source;
record_dht_source=record
ip:cardinal;
raw:string;
lastSeen:cardinal;
prev,next:precord_dht_source;
end;
type
precord_dht_outpacket=^record_dht_outpacket;
record_dht_outpacket=record
destIP:cardinal;
destPort:word;
buffer:string;
end;
type
precord_DHT_firewallcheck=^record_DHT_firewallcheck;
record_DHT_firewallcheck=record
RemoteIp:cardinal;
RemoteUDPPort:word;
RemoteTCPPort:word;
started:cardinal;
sockt:HSocket;
end;
type
precord_DHT_hash=^record_dht_hash;
record_dht_hash=record
hashValue:array[0..19] of byte;
crc:word;
count:word; // number of items
lastSeen:cardinal;
firstSource:precord_dht_source;
prev,next:precord_dht_hash;
end;
type
precord_DHT_hashfile=^record_DHT_hashfile;
record_DHT_hashfile=record
HashValue:array[0..19] of byte;
end;
type
precord_dht_storedfile=^record_dht_storedfile;
record_dht_storedfile=record
hashValue:array[0..19] of byte;
crc:word;
amime:byte;
ip:cardinal; //last publish source is available immediately
port:word;
count:word;
lastSeen:cardinal;
fsize:int64;
param1,param3:cardinal;
info:string;
numKeywords:byte;
keywords:PWordsArray;
prev,next:precord_dht_storedfile;
end;
type
PDHTKeyWordItem=^TDHTKeyWordItem;
TDHTKeywordItem = packed record
share : precord_dht_storedfile;
prev, next : PDHTKeywordItem;
end;
PDHTKeyword = ^TDHTKeyword;
TDHTKeyword = packed record // structure that manages one keyword
keyword : array of char; // keyword
count : cardinal;
crc : word;
firstitem : PDHTKeywordItem; // pointer to first full item
prev, next : PDHTKeyword; // pointer to previous and next PKeyword items in global list
end;
type
tdhtsearchtype=(
UNDEFINED,
NODE,
NODECOMPLETE,
KEYWORD,
STOREFILE,
STOREKEYWORD,
FINDSOURCE
);
implementation
end. |
unit ATipoMateriaPrima;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, Componentes1, ExtCtrls, PainelGradiente, BotaoCadastro,
StdCtrls, Buttons, Grids, DBGrids, Tabela, DBKeyViolation, Localizacao, Mask, DBCtrls, DB, DBClient, CBancoDados;
type
TFTipoMateriaPrima = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
PanelColor2: TPanelColor;
TipoMateriaPrima: TRBSQL;
TipoMateriaPrimaCODTIPOMATERIAPRIMA: TFMTBCDField;
TipoMateriaPrimaNOMTIPOMATERIAPRIMA: TWideStringField;
Label1: TLabel;
DataTipoMateriaPrima: TDataSource;
ECodigo: TDBKeyViolation;
Label2: TLabel;
DBEditColor1: TDBEditColor;
Bevel1: TBevel;
Label3: TLabel;
EConsulta: TLocalizaEdit;
GridIndice1: TGridIndice;
MoveBasico1: TMoveBasico;
BotaoCadastrar1: TBotaoCadastrar;
BotaoAlterar1: TBotaoAlterar;
BotaoExcluir1: TBotaoExcluir;
BotaoGravar1: TBotaoGravar;
BotaoCancelar1: TBotaoCancelar;
BFechar: TBitBtn;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BFecharClick(Sender: TObject);
procedure GridIndice1Ordem(Ordem: string);
procedure TipoMateriaPrimaAfterInsert(DataSet: TDataSet);
procedure TipoMateriaPrimaAfterPost(DataSet: TDataSet);
procedure TipoMateriaPrimaAfterEdit(DataSet: TDataSet);
procedure TipoMateriaPrimaBeforePost(DataSet: TDataSet);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FTipoMateriaPrima: TFTipoMateriaPrima;
implementation
uses APrincipal;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFTipoMateriaPrima.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
end;
{ **************************************************************************** }
procedure TFTipoMateriaPrima.GridIndice1Ordem(Ordem: string);
begin
EConsulta.AOrdem := Ordem;
end;
{ **************************************************************************** }
procedure TFTipoMateriaPrima.TipoMateriaPrimaAfterEdit(DataSet: TDataSet);
begin
ECodigo.ReadOnly := true;
end;
procedure TFTipoMateriaPrima.TipoMateriaPrimaAfterInsert(DataSet: TDataSet);
begin
ECodigo.ProximoCodigo;
ECodigo.ReadOnly := false;
end;
{ **************************************************************************** }
procedure TFTipoMateriaPrima.TipoMateriaPrimaAfterPost(DataSet: TDataSet);
begin
EConsulta.AtualizaConsulta;
end;
{ **************************************************************************** }
procedure TFTipoMateriaPrima.TipoMateriaPrimaBeforePost(DataSet: TDataSet);
begin
if TipoMateriaPrima.State = dsinsert then
ECodigo.VerificaCodigoUtilizado;
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFTipoMateriaPrima.BFecharClick(Sender: TObject);
begin
close;
end;
{ **************************************************************************** }
procedure TFTipoMateriaPrima.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFTipoMateriaPrima]);
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2016-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Vcl.AppAnalytics;
interface
uses System.Types, System.Classes, Winapi.Windows, Winapi.Messages, Vcl.ExtCtrls,
Vcl.Controls, Vcl.Forms, System.SysUtils, System.Math, Vcl.AppAnalytics.Consts;
type
TAnalyticsOption = (aoTrackStartup, aoTrackFormActivate, aoTrackControlFocus,
aoTrackExceptions);
TAnalyticsOptions = set of TAnalyticsOption;
/// <Summary>An event handler that is fired when the privacy message is shown
/// to an end user on startup. See the OnPrivacyMessage event in the TAppAnalytics
/// component.
/// To collect data from the user, set Activate to True. Set Activate to False
/// to exclude the user from data collection.</Summary>
TAnalyticsPrivacyMessageEvent = procedure(Sender: TObject; var Activate: Boolean) of Object;
/// <Summary>Usage tracking and data collection component for AppAnalytics. This
/// component collects data about the various ways that users interact with
/// your application and sends the data to the AppAnalytics web application for
/// processing and analysis.</Summary>
[ComponentPlatformsAttribute(pfidWindows)]
TAppAnalytics = class(TComponent)
private
FOptions: TAnalyticsOptions;
FApplicationID: string;
FPrivacyMessage: TStrings;
FOnPrivacyMessage: TAnalyticsPrivacyMessageEvent;
FCBTHookHandle: THandle;
FActive: Boolean;
FDataCache: TStringList;
FUpdateTimer: TTimer;
FMaxCacheSize: Integer;
FUserID: string; //ANONYMOUS ID used to track this user through a session
FSessionID: string;
FEventCount: Cardinal;
FActiveForm: TObject; //Might be a VCL form or an FMX form
FFocusedControl: TControl;
FOSVersion: string;
FCPUInfo: string;
FAppVersion: string;
FLastWindowClassName, FLastWindowName, FLastControlClassName, FLastControlName: string;
FServerAddress: string;
FOldExceptionHandler: TExceptionEvent;
procedure InstallHooks;
procedure RemoveHooks;
procedure Log(AMessage: string);
procedure SendDataNoIndy;
procedure UpdateTimerFire(Sender: TObject);
procedure TrackException(Sender: TObject; E:Exception);
procedure InstallExceptionHandler;
procedure RemoveExceptionHandler;
//ResetApp is for RTL testing only. Do not use in a real production application
class procedure ResetApp;
protected
procedure SetActive(const Value: Boolean);
/// <Summary>Sends data that has been accumulated to the server. There generally isn't a need to call this,
/// as AppAnalytics will send data automatically at a time interval, when the cache exceeds a certain size,
/// or when the app exits.</Summary>
procedure SendData;
/// <Summary>Reader for the UpdateInterval property</Summary>
function GetUpdateInterval: Integer;
/// <Summary>Setter for the UpdateInterval property</Summary>
procedure SetUpdateInterval(const Value: Integer);
/// <Summary>Call this to track that application has started. Generally no need to call; use the aoTrackStartup option instead</Summary>
procedure TrackApplicationStarted;
/// <Summary>Call this to track that application has exited. Generally no need to call; use the aoTrackStartup option instead</Summary>
procedure TrackApplicationExit;
/// <Summary>Call this to track that a window has been activated. Generally no need to call; use the aoTrackFormActivate option instead</Summary>
procedure TrackWindowActivated(AHandle: THandle); virtual;
/// <Summary>Call this to track that a control has received focus. Generally no need to call; use the aoTrackControlFocus option instead</Summary>
procedure TrackControlFocused(AHandle: THandle); virtual;
/// <Summary>Setter for the CacheSize property</Summary>
procedure SetCacheSize(const Value: Integer);
/// <Summary>Setter for the Options property</Summary>
procedure SetOptions(const Value: TAnalyticsOptions);
/// <Summary>Setter for the PrivacyMessage propety</Summary>
procedure SetPrivacyMessage(const Value: TStrings);
/// <Summary>Setter for the OnPrivacyMessage event</Summary>
procedure SetOnPrivacyMessage(const Value: TAnalyticsPrivacyMessageEvent);
procedure Loaded; override;
/// <Summary>Reader for the UserID property</Summary>
function GetUserID: string;
/// <Summary>Reader for the AllowTracking property</Summary>
function GetAllowTracking: Boolean;
/// <Summary>Returns the current time in the string format that AppAnalytics delivers to the server</Summary>
function GetTimestamp: string;
/// <Summary>UserID is a GUID used by the AppAnalytics server to track how many distinct users perform certain actions
/// across multiple sections. Changing this value may cause data on the server to be incorrect, so it's read-only</Summary>
property UserID: string read GetUserID;
public
/// <Summary>Creates an instance of the TAppAnalytics component</Summary>
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
/// <Summary>Track a custom event. Call this method to do your own event
/// tracking. You might use this to track feature usage, performance data, or
/// anything else you like, provided the information remains anonymous.
/// ACategory, AAction, ALabel, and AValue are fields you can define to describe the event being tracked.
/// Only ACategory is required. The AppAnalytics service will record the first 64 characters of each of ACategory, AAction, and ALabel.
/// </Summary>
procedure TrackEvent(ACategory: string; AAction: string = '';
ALabel: string = ''; AValue: Double = 0.0);
/// <Summary>Send data to the server. Data is automatically sent on a timer, when the event cache is filled, and when the application exits.
/// Call StartSending to send data at a time other than this. Returns a handle to a thread that sends the data. The thread will terminate
/// after the data has been sent.</Summary>
function StartSending: THandle;
/// <Summary>Show the notification/permission dialog to the end user, and reset
/// their tracking preference, if applicable</Summary>
function CheckPrivacy: Boolean;
/// <Summary>The address of the server where AppAnalytics will send its event data.
/// There isn't a reason to change this unless specifically instructed by
/// Embarcadero</Summary>
property ServerAddress: string read FServerAddress write FServerAddress;
published
/// <Summary>This event is called when AppAnalytics needs to notify the end user that their actions are being tracked (and preferably get permission).
/// This happens the first time the application is started for a given end user (combination of computer/user, as defined by HKEY_CURRENT_USER registry key),
/// and can be made to happen at any time by calling CheckPrivacy</Summary>
property OnPrivacyMessage: TAnalyticsPrivacyMessageEvent read
FOnPrivacyMessage write SetOnPrivacyMessage;
/// <Summary>The ID of the application assigned in the AppAnalytics web interface.
/// To find your application's ID, log in to the AppAnalytics web service and view your Application's properties.</Summary>
property ApplicationID: string read FApplicationID write FApplicationID;
/// <Summary>Controls whther the component is actively collection application usage data. Set Active to true to collect data.
/// If the Active property is set to True as design time, AppAnalytics will automatically collect data for the entire usage session.
/// </Summary>
property Active: Boolean read FActive write SetActive;
/// <Summary>The maximum number of events that AppAnalytics will collect before sending them to the server for analysis.
/// The default is 500. AppAnalytics will send usage data to the server whenever the UpdateInterval has expired or the CacheSize is reached.
/// (AppAnalytics will also send a final update when the application exits.)</Summary>
property CacheSize: Integer read FMaxCacheSize write SetCacheSize;
/// <Summary>The interval, in seconds, at which AppAnalytics will automatically send whatever data it has collected to the server for Analysis.
/// The default is 600 seconds, or 10 minutes. AppAnalytics will send usage data to the server whenever the UpdateInterval has expired, or the CacheSize has been reached.
/// (AppAnalytics will also send a final update when the application exits.)</Summary>
property UpdateInterval: Integer read GetUpdateInterval write
SetUpdateInterval;
/// <Summary>Various options that determine what data AppAnalytics automatically collects. Choose any combination of the following:
/// aoTrackStartup: Specifically track each time the application starts and closes. It is recommended to always use this option.
/// aoTrackFormActivate: Track each time the active form in the application changes. This is useful for tracking the "flow" of a user through your application, and is tied to incredible visualization tools in the AppAnalytics web application.
/// aoTrackControlFocus: Track each time the focused control in the application changes. This is useful for tracking the "flow" of a user through your application.
/// aoTrackExceptions: Track each time an exception rises to the top and is caught at the Application level.
/// This option utilizes the Application.OnException event.
/// If you have your own Application.OnException event handler, AppAnalytics will try to use your exception handler as well
/// (Note that it is possible for your Application.OnException event handler to interfere with AppAnalytics, if your event handler is installed AFTER AppAnalytics is activated).
/// </Summary>
property Options: TAnalyticsOptions read FOptions write SetOptions;
/// <Summary>The text of the message shown to users when AppAnalytics is activated in a given application for the first time.
/// This message is shown in a dialog box with an "OK" message, and does not give users the option to opt-in or opt-out.
/// If you wish to give your users the opportunity to opt-in or opt-out (which is recommended), use the OnPrivacyMessage event.
/// </Summary>
property PrivacyMessage: TStrings read FPrivacyMessage write
SetPrivacyMessage;
end;
//Various error classes
/// <Summary>Exception raised when AppAnalytics is used incorrectly (for example, one more than one AppAnalytics component is used in an application)</Summary>
EInvalidAnalyticsUsage = class(Exception)
end;
/// <Summary>Exception raised if AppAnalytics initalization fails for some reason</Summary>
EAnalyticsInitializationFailed = class(Exception)
end;
/// <Summary>Returns the AppAnalytics instance for the Application(there can be only one per application).
/// This is useful for tracking things outside of the main form, where the component may actually "live,"
/// without having to add the main form to the uses clause</Summary>
function GetAppAnalytics: TAppAnalytics;
implementation
uses System.SyncObjs, System.DateUtils, System.Win.Registry, WinApi.WinINet,
Vcl.Dialogs, System.NetEncoding;
type
TAnalyticsThread = class(TThread)
public
procedure Execute; override;
end;
var
GlobalAnalytics: TAppAnalytics = nil;
AnalyticsCriticalSection: TCriticalSection;
function GetAppAnalytics: TAppAnalytics;
begin
Result := GlobalAnalytics;
end;
//Non-OO Hook callbacks
function CBTHookProc(nCode: Integer; WPARAM: WPARAM; LPARAM: LPARAM): LRESULT;
stdcall;
{var
MouseStruct: PMouseHookStruct; //Reserved for later
TargetHandle: THandle; //Reserved for later
TargetControl: TControl; //Reserved for later}
begin
if GlobalAnalytics <> nil then
begin
case nCode of
HCBT_ACTIVATE:
if aoTrackFormActivate in GlobalAnalytics.Options then
GlobalAnalytics.TrackWindowActivated(WPARAM);
HCBT_MINMAX:;
HCBT_MOVESIZE:;
HCBT_SETFOCUS:
if aoTrackControlFocus in GlobalAnalytics.Options then
GlobalAnalytics.TrackControlFocused(WPARAM);
HCBT_SYSCOMMAND:;
HCBT_CLICKSKIPPED:
{begin
MouseStruct := PMouseHookStruct(Pointer(LPARAM));
TargetHandle := MouseStruct^.hwnd;
TargetControl := FindControl(TargetHandle);
if TargetControl <> nil then
begin
if WPARAM = WM_LBUTTONDOWN then
GlobalAnalytics.Log(Format('Mouse Click: %s (%s)', [TargetControl.Name, TargetControl.ClassName]));
if WPARAM = WM_RBUTTONDOWN then
GlobalAnalytics.Log(Format('Mouse Right Click: %s (%s)', [TargetControl.Name, TargetControl.ClassName]));;
if WPARAM = WM_LBUTTONDBLCLK then
GlobalAnalytics.Log(Format('Mouse Double Click: %s (%s)', [TargetControl.Name, TargetControl.ClassName]));;
end;
end};
HCBT_KEYSKIPPED:;
end;
end;
Result := CallNextHookEx(GlobalAnalytics.FCBTHookHandle, nCode, WPARAM, LPARAM);
end;
//Misc. Support Routines
function GetCPUName: string;
var
Reg: TRegistry;
begin
Result := '';
Reg := TRegistry.Create(KEY_READ);
try
Reg.RootKey := HKEY_LOCAL_MACHINE;
if Reg.OpenKey('Hardware\Description\System\CentralProcessor\0', False) then //Do not localize
Result := Reg.ReadString('ProcessorNameString') //Do not localize
else
Result := '(CPU Unidentified)'; //Do not localize
finally
Reg.Free;
end;
end;
function GetCpuSpeed: string;
var
Reg: TRegistry;
begin
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_LOCAL_MACHINE;
if Reg.OpenKey('Hardware\Description\System\CentralProcessor\0', False) then //Do not localize
begin
Result := IntToStr(Reg.ReadInteger('~MHz')) + ' MHz'; //Do not localize
Reg.CloseKey;
end;
finally
Reg.Free;
end;
end;
procedure GetBuildInfo(var V1, V2, V3, V4: word);
var
VerInfoSize, VerValueSize, Dummy: Cardinal;
VerInfo: Pointer;
VerValue: PVSFixedFileInfo;
begin
VerInfoSize := GetFileVersionInfoSize(PChar(ParamStr(0)), Dummy);
if VerInfoSize > 0 then
begin
GetMem(VerInfo, VerInfoSize);
try
if GetFileVersionInfo(PChar(ParamStr(0)), 0, VerInfoSize, VerInfo) then
begin
VerQueryValue(VerInfo, '\', Pointer(VerValue), VerValueSize);
with VerValue^ do
begin
V1 := dwFileVersionMS shr 16;
V2 := dwFileVersionMS and $FFFF;
V3 := dwFileVersionLS shr 16;
V4 := dwFileVersionLS and $FFFF;
end;
end;
finally
FreeMem(VerInfo, VerInfoSize);
end;
end;
end;
function GetBuildInfoAsString: string;
var
V1, V2, V3, V4: word;
begin
GetBuildInfo(V1, V2, V3, V4);
Result := IntToStr(V1) + '.' + IntToStr(V2) + '.' +
IntToStr(V3) + '.' + IntToStr(V4);
end;
{ TApplicationAnalytics }
function TAppAnalytics.CheckPrivacy: Boolean;
var
AllowTracking: Boolean;
Reg: TRegistry;
begin
AllowTracking := True;
if Assigned(FOnPrivacyMessage) then
begin
FOnPrivacyMessage(Self, AllowTracking);
if not AllowTracking then
begin
Active := False;
end;
end
else
begin
ShowMessage(PrivacyMessage.Text);
end;
Reg := TRegistry.Create(KEY_READ);
try
Reg.RootKey := HKEY_CURRENT_USER;
Reg.Access := KEY_WRITE;
Reg.OpenKey('Software\Embarcadero\AppAnalytics\' + ApplicationID, True); //Do not localize
Reg.WriteBool('A', AllowTracking);
finally
Reg.CloseKey;
Reg.Free;
end;
Result := AllowTracking;
end;
constructor TAppAnalytics.Create(AOwner: TComponent);
var
GUID: TGUID;
begin
inherited;
if not (csDesigning in ComponentState) then
begin
if GlobalAnalytics <> nil then
begin
raise EInvalidAnalyticsUsage.Create(SOneAnalyticsComponentAllowed);
end;
GlobalAnalytics := Self;
CreateGUID(GUID);
FSessionID := GUIDToString(GUID);
FEventCount := 0;
end;
Options := [aoTrackStartup, aoTrackFormActivate, aoTrackExceptions];
FActive := False;
FDataCache := TStringList.Create;
FMaxCacheSize := 500;
FUpdateTimer := TTimer.Create(Self);
FUpdateTimer.Interval := 600000; //Default update interval: 10 minutes
FUpdateTimer.OnTimer := UpdateTimerFire;
FPrivacyMessage := TStringList.Create;
FPrivacyMessage.Text := sPrivacyMessage;
FLastWindowClassName := '';
FLastWindowName := '';
FLastControlClassName := '';
FLastControlName := '';
FUserID := '';
ServerAddress := 'appanalytics.embarcadero.com';
end;
destructor TAppAnalytics.Destroy;
begin
//Send any remaining data, if possible
Active := False;
FPrivacyMessage.Free;
FDataCache.Free;
if not (csDesigning in ComponentState) then
GlobalAnalytics := nil;
inherited;
end;
function TAppAnalytics.GetAllowTracking: Boolean;
var
Reg: TRegistry;
begin
try
Reg := TRegistry.Create(KEY_READ);
try
Reg.RootKey := HKEY_CURRENT_USER;
Reg.OpenKey('Software\Embarcadero\AppAnalytics\' + ApplicationID, True); //Do not localize
if Reg.ValueExists('A') then
begin
Result := Reg.ReadBool('A');
end else
begin
Result := CheckPrivacy;
end;
finally
Reg.CloseKey;
Reg.Free;
end;
except
Result := False;
end;
end;
function TAppAnalytics.GetTimestamp: string;
var
UTC: TSystemTime;
begin
GetSystemTime(UTC);
Result := Format('%d-%d-%d %d:%d:%d.%d',
[UTC.wYear, UTC.wMonth, UTC.wDay,
UTC.wHour, UTC.wMinute, UTC.wSecond, UTC.wMilliseconds]);
end;
function TAppAnalytics.GetUpdateInterval: Integer;
begin
Result := FUpdateTimer.Interval div 1000;
end;
function TAppAnalytics.GetUserID: string;
var
Reg: TRegistry;
GUID: TGUID;
begin
Result := '';
if FUserID = '' then
begin
Reg := TRegistry.Create(KEY_READ);
try
Reg.RootKey := HKEY_CURRENT_USER;
Reg.OpenKey('Software\Embarcadero\AppAnalytics\' + ApplicationID, True); //Do not localize
if Reg.ValueExists('U')
{$IFDEF DEBUG} and (ParamStr(1) <> 'reset_user'){$ENDIF}
then
begin
FUserID := Reg.ReadString('U');
end else
begin
Reg.CloseKey;
Reg.Access := KEY_WRITE;
Reg.OpenKey('Software\Embarcadero\AppAnalytics\' + ApplicationID, True); //Do not localize
CreateGUID(GUID);
FUserID := GuidToString(GUID);
Reg.WriteString('U', FUserID);
end;
finally
Reg.CloseKey;
Reg.Free;
end;
end;
Result := FUserID;
end;
procedure TAppAnalytics.InstallExceptionHandler;
begin
FOldExceptionHandler := Application.OnException;
Application.OnException := TrackException;
end;
procedure TAppAnalytics.InstallHooks;
begin
FCBTHookHandle := SetWindowsHookEx(WH_CBT, CBTHookProc, 0, GetCurrentThreadID);
if FCBTHookHandle = 0 then
begin
raise EAnalyticsInitializationFailed.Create(Format(SCBTHookFailed, [GetLastError]));
end;
if aoTrackExceptions in Options then
InstallExceptionHandler;
end;
procedure TAppAnalytics.Loaded;
begin
inherited;
//This is here to make sure that the Active property setter gets fully
//executed AFTER the OnPrivacyMessage event gets set
if FActive then
begin
FActive := False;
Active := True;
end;
end;
procedure TAppAnalytics.Log(AMessage: string);
begin
{$IF DEFINED(DEBUG) AND DEFINED(MSWINDOWS)}
OutputDebugString(PChar('AppAnalytics: ' + AMessage));
{$ENDIF}
AnalyticsCriticalSection.Enter;
try
FDataCache.Add(IntToStr(FEventCount) + '|' + AMessage);
Inc(FEventCount);
finally
AnalyticsCriticalSection.Leave;
end;
if (FDataCache.Count > FMaxCacheSize) and (not Application.Terminated) then
StartSending;
end;
procedure TAppAnalytics.RemoveExceptionHandler;
begin
Application.OnException := FOldExceptionHandler;
end;
procedure TAppAnalytics.RemoveHooks;
begin
if aoTrackExceptions in Options then
RemoveExceptionHandler;
UnhookWindowsHookEx(FCBTHookHandle);
end;
class procedure TAppAnalytics.ResetApp;
begin
if GlobalAnalytics <> nil then
begin
GlobalAnalytics.FDataCache.Clear;
GlobalAnalytics.Free;
end;
GlobalAnalytics := nil;
end;
//This method should generally be called from the analytics thread, but
//it can be called from main UI thread if needed.
//Note that it will BLOCK on network access, so running it in the main
//Thread is discouraged
procedure TAppAnalytics.SendData;
{$IFDEF APPANALYTICS_USEINDY}
var
http: TIdHttp;
DataCount, I: Integer;
ParamList: TStrings;
HttpResult: string;
{$ENDIF}
begin
{$IFDEF APPANALYTICS_USEINDY}
ParamList := TStringList.Create;
http := TIdHTTP.Create(Self);
try
AnalyticsCriticalSection.Enter;
try
DataCount := FDataCache.Count;
if DataCount = 0 then
Exit;
ParamList.Add(Format('V=%d', [2]));
ParamList.Add(Format('I=%s', [TNetEncoding.URL.Encode(ApplicationID)]));
ParamList.Add(Format('U=%s', [TNetEncoding.URL.Encode(UserID)]));
ParamList.Add(Format('S=%s', [TNetEncoding.URL.Encode(FSessionID)]));
ParamList.Add(Format('N=%d', [DataCount]));
ParamList.Add(Format('OS=%s', [TNetEncoding.URL.Encode(FOSVersion)]));
ParamList.Add(Format('APPVER=%s', [TNetEncoding.URL.Encode(FAppVersion)]));
ParamList.Add(Format('CPU=%s', [TNetEncoding.URL.Encode(FCPUInfo)]));
for I := 0 to DataCount - 1 do
begin
ParamList.Add(Format('L%d=%s',[I, TNetEncoding.URL.Encode(FDataCache[0])]));
FDataCache.Delete(0);
end;
finally
AnalyticsCriticalSection.Leave;
end;
try
HttpResult := http.Post('http://' + ServerAddress + '/d.php', ParamList);
except
//If anything goes wrong, suppress the error. We don't want the end user to be interrupted
end;
finally
http.Free;
ParamList.Free;
end;
{$ENDIF}
SendDataNoIndy;
end;
procedure TAppAnalytics.SendDataNoIndy;
var
HSession, HConnect, HRequest: HINTERNET;
ParamList: TStrings;
Content, EncodedData: string;
Header: String;
ANSIContent: ANSIString;
DataCount, I: Integer;
begin
ParamList := TStringList.Create;
try
try
AnalyticsCriticalSection.Enter;
DataCount := FDataCache.Count;
if DataCount = 0 then
Exit;
ParamList.Add(Format('V=%d', [2]));
ParamList.Add(Format('I=%s', [TNetEncoding.URL.Encode(ApplicationID)]));
ParamList.Add(Format('U=%s', [TNetEncoding.URL.Encode(UserID)]));
ParamList.Add(Format('S=%s', [TNetEncoding.URL.Encode(FSessionID)]));
ParamList.Add(Format('N=%d', [DataCount]));
ParamList.Add(Format('OS=%s', [TNetEncoding.URL.Encode(FOSVersion)]));
ParamList.Add(Format('APPVER=%s', [TNetEncoding.URL.Encode(FAppVersion)]));
ParamList.Add(Format('CPU=%s', [TNetEncoding.URL.Encode(FCPUInfo)]));
for I := 0 to DataCount - 1 do
begin
ParamList.Add(Format('L%d=%s',[I, TNetEncoding.URL.Encode(FDataCache[0])]));
FDataCache.Delete(0);
end;
finally
AnalyticsCriticalSection.Leave;
end;
Content := '';
for I := 0 to ParamList.Count - 1 do
begin
EncodedData := ParamList[I];
Content := Content + EncodedData;
if I < ParamList.Count - 1 then
begin
Content := Content + '&';
end;
end;
ANSIContent := AnsiString(Content);
HSession := InternetOpen('AppAnalytics', INTERNET_OPEN_TYPE_PRECONFIG,
nil, nil, 0);
{$IFDEF APPANALYTICS_DEBUG}
if HSession = nil then
ShowMessage(IntToStr(GetLastError));
{$ENDIF}
try
HConnect := InternetConnect(HSession, PChar(ServerAddress),
INTERNET_DEFAULT_HTTPS_PORT, nil, nil,
INTERNET_SERVICE_HTTP, 0, 0);
{$IFDEF APPANLYTICS_DEBUG}
if HConnect = nil then
ShowMessage(IntToStr(GetLastError));
{$ENDIF}
try
HRequest := HTTPOpenRequest(HConnect, 'POST', '/d.php', nil, nil, nil,
INTERNET_FLAG_SECURE, 0);
{$IFDEF APPANALYTICS_DEBUG}
if HRequest = nil then
ShowMessage(IntToStr(GetLastError));
{$ENDIF}
try
Header := 'Content-Type: application/x-www-form-urlencoded';
if not HTTPSendRequest(HRequest, PChar(Header), Length(Header),
PAnsiChar(ANSIContent), Length(ANSIContent) * Sizeof(ANSIChar)) then
{$IFDEF APPANALYTICS_DEBUG}
ShowMessage(IntToStr(GetLastError))
{$ENDIF};
finally
InternetCloseHandle(HRequest);
end;
finally
InternetCloseHandle(HConnect);
end;
finally
InternetCloseHandle(HSession);
end;
finally
ParamList.Free;
end;
end;
procedure TAppAnalytics.SetActive(const Value: Boolean);
var
AllowTracking: Boolean;
begin
if Value then
begin
if ApplicationID = '' then
raise EAnalyticsInitializationFailed.Create(SInvalidApplicationID);
if (FActive <> Value) and
not (csDesigning in ComponentState) and
not (csLoading in ComponentState) then
begin
GetUserID;
AllowTracking := GetAllowTracking;
if AllowTracking then
begin
InstallHooks;
TrackApplicationStarted;
FUpdateTimer.Enabled := True;
end else
begin
//The user has declined the tracking, so we can't set it to active
Active := False;
Exit;
end;
end;
end else
if (FActive <> Value) and
not (csLoading in ComponentState) and
not (csDesigning in ComponentState) then
begin
TrackApplicationExit;
SendData;
RemoveHooks;
FUpdateTimer.Enabled := False;
end;
FActive := Value;
end;
procedure TAppAnalytics.SetCacheSize(const Value: Integer);
begin
FMaxCacheSize := Value;
if csDesigning in ComponentState then
Exit;
if FDataCache.Count >= Value then
StartSending;
end;
procedure TAppAnalytics.SetOnPrivacyMessage(
const Value: TAnalyticsPrivacyMessageEvent);
begin
FOnPrivacyMessage := Value;
end;
procedure TAppAnalytics.SetOptions(const Value: TAnalyticsOptions);
begin
FOptions := Value;
end;
procedure TAppAnalytics.SetPrivacyMessage(const Value: TStrings);
begin
FPrivacyMessage.Assign(Value);
end;
procedure TAppAnalytics.SetUpdateInterval(const Value: Integer);
begin
FUpdateTimer.Interval := Value * 1000;
end;
function TAppAnalytics.StartSending: THandle;
var
SendThread: TAnalyticsThread;
begin
if csDesigning in ComponentState then
begin
Result := 0;
Exit;
end;
SendThread := TAnalyticsThread.Create(True);
Result := SendThread.Handle;
SendThread.FreeOnTerminate := True;
SendThread.Start;
end;
procedure TAppAnalytics.TrackApplicationExit;
var
S: string;
begin
S := 'AppExit|' + GetTimestamp; //Do not localize
Log(S);
end;
procedure TAppAnalytics.TrackApplicationStarted;
var
S: string;
OSVersion: string;
VersionInfo: TOSVersionInfo;
MajorVersion, MinorVersion: Cardinal;
CPUName: string;
BuildVersion: string;
begin
VersionInfo.dwOSVersionInfoSize := SizeOf(VersionInfo);
GetVersionEx(VersionInfo);
MajorVersion := VersionInfo.dwMajorVersion;
MinorVersion := VersionInfo.dwMinorVersion;
OSVersion := Format('%d.%d' , [MajorVersion, MinorVersion]);
CPUName := GetCPUName;
BuildVersion := GetBuildInfoAsString;
S := 'AppStart|' + GetTimestamp + '|' + OSVersion + '|' + CPUName + '|' + BuildVersion; //Do not localize
Log(S);
FOSVersion := OSVersion;
FAppVersion := BuildVersion;
FCPUInfo := CPUName;
end;
procedure TAppAnalytics.TrackControlFocused(AHandle: THandle);
var
S: string;
TargetControl: TControl;
begin
S := 'ControlFocus|' + GetTimestamp; //Do not localize
TargetControl := FindControl(AHandle);
if (TargetControl <> nil) and (TargetControl <> FFocusedControl) then
begin
S := S + '|' + TargetControl.ClassName + '|' + TargetControl.Name +
'|' + FLastControlClassName + '|' + FLastControlName;
Log(S);
FFocusedControl := TargetControl;
FLastControlClassName := TargetControl.ClassName;
FLastControlName := TargetControl.Name;
end;
end;
procedure TAppAnalytics.TrackEvent(ACategory: string;
AAction: string = ''; ALabel: string = ''; AValue: Double = 0.0);
var
S: string;
begin
if not Active then
Exit;
S := ACategory;
if AAction <> '' then
begin
S := S + '|' + AAction;
if ALabel <> '' then
begin
S := S + '|' + ALabel;
S := S + '|' + FloatToStr(AValue);
end;
end;
Log('TrackEvent|' + GetTimestamp + '|' + S); //Do not localize
end;
procedure TAppAnalytics.TrackException(Sender: TObject; E: Exception);
begin
Log('AppCrash|' + GetTimestamp + '|' + E.ClassName + '|' + E.Message); //Do not localize
if Assigned(FOldExceptionHandler) then
FOldExceptionHandler(Sender, E)
else
Application.ShowException(E);
end;
procedure TAppAnalytics.TrackWindowActivated(AHandle: THandle);
var
S: string;
TargetForm: TControl;
begin
S := 'FormActivate|' + GetTimestamp; //Do not localize
TargetForm := FindControl(AHandle);
if (TargetForm <> nil) and (TargetForm <> FActiveForm) then
begin
S := S + '|' + TargetForm.ClassName + '|' + TargetForm.Name +
'|' + FLastWindowClassName + '|' + FLastWindowName;
Log(S);
FActiveForm := TForm(TargetForm);
FLastWindowClassName := TargetForm.ClassName;
FLastWindowName := TargetForm.Name;
end;
end;
procedure TAppAnalytics.UpdateTimerFire(Sender: TObject);
begin
if not (csDesigning in ComponentState) then
StartSending;
end;
{ TAnalyticsThread }
procedure TAnalyticsThread.Execute;
begin
if GlobalAnalytics <> nil then
GlobalAnalytics.SendData;
end;
initialization
AnalyticsCriticalSection := TCriticalSection.Create;
finalization
AnalyticsCriticalSection.Free;
end.
|
unit BackgroundWorker;
{
The following code example demonstrates the basics of the BackgroundWorker class
for executing a time-consuming operation asynchronously. The following illustration
shows an example of the output.
}
interface
uses
{$IF CompilerVersion > 22}
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
{$ELSE}
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,
{$IFEND}
CNClrLib.Control.Base, CNClrLib.Component.BackgroundWorker;
type
TForm12 = class(TForm)
startAsyncButton: TButton;
cancelAsyncButton: TButton;
resultLabel: TLabel;
CnBackgroundWorker1: TCnBackgroundWorker;
procedure startAsyncButtonClick(Sender: TObject);
procedure cancelAsyncButtonClick(Sender: TObject);
procedure CnBackgroundWorker1DoWork(Sender: TObject; E: _DoWorkEventArgs);
procedure CnBackgroundWorker1ProgressChanged(Sender: TObject;
E: _ProgressChangedEventArgs);
procedure CnBackgroundWorker1RunWorkerCompleted(Sender: TObject;
E: _RunWorkerCompletedEventArgs);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form12: TForm12;
implementation
{$R *.dfm}
procedure TForm12.cancelAsyncButtonClick(Sender: TObject);
begin
if CnBackgroundWorker1.WorkerSupportsCancellation then
begin
// Cancel the asynchronous operation.
CnBackgroundWorker1.CancelAsync();
end;
end;
procedure TForm12.CnBackgroundWorker1DoWork(Sender: TObject;
E: _DoWorkEventArgs);
var
worker: TCnBackgroundWorker;
I: Integer;
begin
worker := Sender as TCnBackgroundWorker;
for I := 0 to 10 do
begin
if worker.CancellationPending then
begin
E.Cancel := True;
Break;
end
else
begin
// Perform a time consuming operation and report progress.
Sleep(500);
worker.ReportProgress(I * 10);
end;
end;
end;
procedure TForm12.CnBackgroundWorker1ProgressChanged(Sender: TObject;
E: _ProgressChangedEventArgs);
begin
resultLabel.Caption := (IntToStr(E.ProgressPercentage) + '%');
end;
procedure TForm12.CnBackgroundWorker1RunWorkerCompleted(Sender: TObject;
E: _RunWorkerCompletedEventArgs);
begin
if e.Cancelled then
resultLabel.Caption := 'Canceled!'
else if e.Error <> nil then
resultLabel.Caption := 'Error: ' + e.Error.Message
else
resultLabel.Caption := 'Done!';
end;
procedure TForm12.FormCreate(Sender: TObject);
begin
CnBackgroundWorker1.WorkerReportsProgress := true;
CnBackgroundWorker1.WorkerSupportsCancellation := true;
end;
procedure TForm12.startAsyncButtonClick(Sender: TObject);
begin
if not CnBackgroundWorker1.IsBusy then
begin
// Start the asynchronous operation.
CnBackgroundWorker1.RunWorkerAsync();
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Data.DBXSqlScanner;
interface
uses
Data.DBXPlatform;
type
TDBXSqlScanner = class
public
constructor Create(const QuoteChar: string; const QuotePrefix: string; const QuoteSuffix: string);
destructor Destroy; override;
procedure RegisterId(const Id: string; const Token: Integer);
procedure Init(const Query: string); overload;
procedure Init(const Query: string; const StartIndex: Integer); overload;
function LookAtNextToken: Integer;
function NextToken: Integer;
function IsKeyword(const Keyword: string): Boolean;
protected
function GetId: string;
private
class function ToQuoteChar(const QuoteString: string): Char; static;
procedure ResetId;
function ScanNumber: Integer;
function QuotedToken: Integer;
function PrefixQuotedToken: Integer;
function UnquotedToken: Integer;
function ScanSymbol: Integer;
procedure SkipToEndOfLine;
private
FQuotePrefix: string;
FQuoteSuffix: string;
FQuote: string;
FQuotePrefixChar: Char;
FQuoteSuffixChar: Char;
FQuoteChar: Char;
FKeywords: TDBXObjectStore;
FQuery: string;
FQueryLength: Integer;
FIndex: Integer;
FStartOfId: Integer;
FEndOfId: Integer;
FId: string;
FWasId: Boolean;
FWasQuoted: Boolean;
FSymbol: Char;
public
property Id: string read GetId;
property Quoted: Boolean read FWasQuoted;
property Symbol: Char read FSymbol;
property SqlQuery: string read FQuery;
property NextIndex: Integer read FIndex;
public
const TokenEos = -1;
const TokenId = -2;
const TokenComma = -3;
const TokenPeriod = -4;
const TokenSemicolon = -5;
const TokenOpenParen = -6;
const TokenCloseParen = -7;
const TokenNumber = -8;
const TokenSymbol = -9;
const TokenError = -10;
end;
implementation
uses
Data.DBXMetaDataUtil,
System.SysUtils,
Data.DBXCommonResStrs;
constructor TDBXSqlScanner.Create(const QuoteChar: string; const QuotePrefix: string; const QuoteSuffix: string);
begin
inherited Create;
FQuotePrefix := QuotePrefix;
FQuoteSuffix := QuoteSuffix;
FQuote := QuoteChar;
FQuotePrefixChar := ToQuoteChar(QuotePrefix);
FQuoteSuffixChar := ToQuoteChar(QuoteSuffix);
FQuoteChar := ToQuoteChar(QuoteChar);
end;
destructor TDBXSqlScanner.Destroy;
begin
FreeAndNil(FKeywords);
inherited Destroy;
end;
procedure TDBXSqlScanner.RegisterId(const Id: string; const Token: Integer);
begin
if FKeywords = nil then
FKeywords := TDBXObjectStore.Create(True);
FKeywords[LowerCase(Id)] := TDBXInt32Object.Create(Token);
end;
procedure TDBXSqlScanner.Init(const Query: string);
begin
Init(Query, 0);
end;
procedure TDBXSqlScanner.Init(const Query: string; const StartIndex: Integer);
begin
FQuery := Query;
FQueryLength := Query.Length;
FIndex := StartIndex;
ResetId;
end;
class function TDBXSqlScanner.ToQuoteChar(const QuoteString: string): Char;
begin
if QuoteString.IsEmpty or (QuoteString.Length = 0) then
Result := #$0
else if QuoteString.Length > 1 then
raise Exception.Create(SIllegalArgument)
else
Result := QuoteString.Chars[0];
end;
function TDBXSqlScanner.LookAtNextToken: Integer;
var
Save: Integer;
Token: Integer;
begin
Save := FIndex;
Token := NextToken;
FIndex := Save;
Result := Token;
end;
function TDBXSqlScanner.NextToken: Integer;
var
Ch: Char;
begin
ResetId;
while FIndex < FQueryLength do
begin
Ch := FQuery.Chars[IncrAfter(FIndex)];
case Ch of
' ',
#$9,
#$d,
#$a:;
'(':
begin
FSymbol := Ch;
Exit(TokenOpenParen);
end;
')':
begin
FSymbol := Ch;
Exit(TokenCloseParen);
end;
',':
begin
FSymbol := Ch;
Exit(TokenComma);
end;
'.':
begin
FSymbol := Ch;
Exit(TokenPeriod);
end;
';':
begin
FSymbol := Ch;
Exit(TokenSemicolon);
end;
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9':
Exit(ScanNumber);
else
if Ch = FQuoteChar then
Exit(QuotedToken)
else if Ch = FQuotePrefixChar then
Exit(PrefixQuotedToken)
else if IsIdentifierStart(Ch) then
Exit(UnquotedToken)
else if (Ch = '-') and (FIndex < FQueryLength) and (FQuery.Chars[FIndex] = '-') then
SkipToEndOfLine
else
Exit(ScanSymbol);
end;
end;
Result := TokenEos;
end;
function TDBXSqlScanner.GetId: string;
begin
if FId.IsEmpty then
begin
FId := FQuery.Substring(FStartOfId, FEndOfId - FStartOfId);
if FWasQuoted then
FId := TDBXMetaDataUtil.UnquotedIdentifier(FId, FQuote, FQuotePrefix, FQuoteSuffix);
end;
Result := FId;
end;
function TDBXSqlScanner.IsKeyword(const Keyword: string): Boolean;
begin
Result := FWasId and (Keyword = Id);
end;
procedure TDBXSqlScanner.ResetId;
begin
FId := NullString;
FStartOfId := 0;
FEndOfId := 0;
FWasId := False;
FWasQuoted := False;
FSymbol := #$0;
end;
function TDBXSqlScanner.ScanNumber: Integer;
var
Ch: Char;
begin
FStartOfId := FIndex - 1;
while FIndex < FQueryLength do
begin
Ch := FQuery.Chars[IncrAfter(FIndex)];
case Ch of
'.',
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9':;
else
begin
Dec(FIndex);
FEndOfId := FIndex;
Exit(TokenNumber);
end;
end;
end;
FEndOfId := FIndex - 1;
Result := TokenNumber;
end;
function TDBXSqlScanner.QuotedToken: Integer;
var
Ch: Char;
begin
FStartOfId := FIndex - 1;
while FIndex < FQueryLength do
begin
Ch := FQuery.Chars[IncrAfter(FIndex)];
if Ch = FQuoteChar then
begin
if (FIndex = FQueryLength) or (FQuery.Chars[FIndex] <> FQuoteChar) then
begin
FEndOfId := FIndex;
FWasId := True;
FWasQuoted := True;
Exit(TokenId);
end;
IncrAfter(FIndex);
end;
end;
Result := TokenError;
end;
function TDBXSqlScanner.PrefixQuotedToken: Integer;
var
Ch: Char;
begin
FStartOfId := FIndex - 1;
while FIndex < FQueryLength do
begin
Ch := FQuery.Chars[IncrAfter(FIndex)];
if Ch = FQuoteSuffixChar then
begin
FEndOfId := FIndex;
FWasId := True;
FWasQuoted := True;
Exit(TokenId);
end;
end;
Result := TokenError;
end;
function TDBXSqlScanner.UnquotedToken: Integer;
var
Token: Integer;
Ch: Char;
Keyword: TDBXInt32Object;
begin
Token := TokenId;
FStartOfId := FIndex - 1;
while FIndex < FQueryLength do
begin
Ch := FQuery.Chars[IncrAfter(FIndex)];
if not IsIdentifierPart(Ch) then
begin
Dec(FIndex);
break;
end;
end;
FEndOfId := FIndex;
FWasId := True;
if FKeywords <> nil then
begin
Keyword := TDBXInt32Object(FKeywords[LowerCase(Id)]);
if Keyword <> nil then
Token := Keyword.IntValue;
end;
Result := Token;
end;
function TDBXSqlScanner.ScanSymbol: Integer;
begin
FSymbol := FQuery.Chars[FIndex - 1];
Result := TokenSymbol;
end;
procedure TDBXSqlScanner.SkipToEndOfLine;
var
Ch: Char;
begin
Ch := '-';
while ((Ch <> #$d) and (Ch <> #$a)) and (FIndex < FQueryLength) do
Ch := FQuery.Chars[IncrAfter(FIndex)];
end;
end.
|
(* ListStackUnit: MM, 2020-05-27 *)
(* ------ *)
(* A stack which stores elements in a single linked list *)
(* ========================================================================= *)
UNIT ListStackUnit;
INTERFACE
USES StackUnit;
TYPE
List = ^Node;
NodePtr = ^Node;
Node = RECORD
value: INTEGER;
next: NodePtr;
END;
ListStack = ^ListStackObj;
ListStackObj = OBJECT(StackObj)
PUBLIC
CONSTRUCTOR Init;
DESTRUCTOR Done;
PROCEDURE Push(e: INTEGER); VIRTUAL;
PROCEDURE Pop(VAR e: INTEGER); VIRTUAL;
FUNCTION IsEmpty: BOOLEAN; VIRTUAL;
PRIVATE
data: List;
END; (* ListStackObj *)
FUNCTION NewListStack(size: INTEGER): ListStack;
IMPLEMENTATION
FUNCTION NewNode(value: INTEGER): NodePtr;
VAR n: NodePtr;
BEGIN (* NewNode *)
New(n);
n^.next := NIL;
n^.value := value;
NewNode := n;
END; (* NewNode *)
CONSTRUCTOR ListStackObj.Init;
BEGIN
SELF.data := NIL;
END;
DESTRUCTOR ListStackObj.Done;
VAR n: NodePtr;
BEGIN
WHILE (data <> NIL) DO BEGIN
n := data;
data := data^.next;
Dispose(n);
END; (* WHILE *)
INHERITED Done;
END;
PROCEDURE ListStackObj.Push(e: INTEGER);
VAR n: NodePtr;
BEGIN
n := NewNode(e);
n^.next := data;
data := n;
END;
PROCEDURE ListStackObj.Pop(VAR e: INTEGER);
VAR n: NodePtr;
BEGIN
n := data;
data := data^.next;
e := n^.value;
Dispose(n);
END;
FUNCTION ListStackObj.IsEmpty: BOOLEAN;
BEGIN (* ArrayStackObj.IsEmpty *)
IsEmpty := data = NIL;
END; (* ArrayStackObj.IsEmpty *)
FUNCTION NewListStack(size: INTEGER): ListStack;
BEGIN (* NewListStack *)
END; (* NewListStack *)
END. (* ListStackUnit *) |
// -------------------------------------------------------------------------------
// Descrição: Escreva programa Pascal que leia dois valores para as variáveis X e Y,
// calculando e exibindo a diferença absoluta destes (por exemplo se X=9 e Y=7, a
// diferença absoluta será 2).
// -------------------------------------------------------------------------------
// Autor : Fernando Gomes
// Data : 23/08/2021
// -------------------------------------------------------------------------------
Program Diferenca_absoluta ;
var
x, y, res: real;
op: char;
Begin
write('Digite o primeiro número: ');
readln(x);
write('Digite o segundo número: ');
readln(y);
res := abs(x-y);
write('A diferenca absoluta entre ',x:6:2, ' e ',y:6:2, ' e: ',res:6:2);
End. |
{Ejercicio 4
Escriba un programa en PASCAL que lea de la entrada estándar tres números naturales a, b, n.
El programa debe exhibir en pantalla todos los múltiplos de n que haya entre a y b.
Ejemplo de entrada:
a=3
b=17
n=4
Ejemplo de salida:
4 8 12 16}
program ejercicio4;
var a, b, n, i, j, multiplo, tope : integer;
begin
writeln('Ingrese los valores de a b y n separados por un espacio.');
read(a,b,n);
tope := b - a;
i := a;
for j := 1 to tope do
begin
multiplo := i mod n;
if multiplo = 0 then
write(i,' ');
i := i + 1;
end
end. |
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit REST.Backend.EMSFireDAC;
{$SCOPEDENUMS ON}
interface
uses
System.Classes, System.SysUtils, System.Generics.Collections, System.JSON,
REST.Backend.EMSProvider, FireDAC.Comp.Client, REST.Backend.Endpoint,
REST.Client, REST.Backend.Providers, REST.Backend.ServiceComponents,
REST.Backend.ServiceTypes;
type
/// <summary>
/// <para>
/// TEMSFireDACClient implements REST requests to the EMS server
/// </para>
/// </summary>
TCustomEMSFireDACClient = class(TComponent)
private
FProvider: TEMSProvider;
FSchemaAdapter: TFDSchemaAdapter;
FGetEndpoint: TCustomBackendEndpoint;
FGetResponse: TCustomRESTResponse;
FApplyEndpoint: TCustomBackendEndpoint;
FApplyResponse: TCustomRESTResponse;
FResource: string;
FAuth: IBackendAuthReg;
procedure SetProvider(const Value: TEMSProvider);
procedure SetSchemaAdapter(const Value: TFDSchemaAdapter);
procedure CheckProvider;
procedure CheckSchemaAdapter;
procedure UpdateEndpoints;
procedure CheckResource;
function GetCanPostUpdates: Boolean;
procedure SetAuth(const Value: IBackendAuthReg);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure GetData;
procedure PostUpdates;
property GetEndpoint: TCustomBackendEndpoint read FGetEndpoint;
property ApplyEndpoint: TCustomBackendEndpoint read FApplyEndpoint;
property CanPostUpdates: Boolean read GetCanPostUpdates;
property Provider: TEMSProvider read FProvider write SetProvider;
property SchemaAdapter: TFDSchemaAdapter read FSchemaAdapter write SetSchemaAdapter;
property Resource: string read FResource write FResource;
property Auth: IBackendAuthReg read FAuth write SetAuth;
end;
TEMSFireDACClient = class(TCustomEMSFireDACClient)
published
property Provider;
property SchemaAdapter;
property Resource;
property Auth;
end;
TEEMSFireDACClientError = class(Exception);
implementation
uses FireDAC.Stan.Intf, REST.Types, Data.DB, REST.Backend.EMSFireDACConsts,
FireDAC.Stan.StorageJSON; // Support JSON format
{ TCustomEMSFireDACClient }
constructor TCustomEMSFireDACClient.Create(AOwner: TComponent);
begin
inherited;
FGetEndpoint := TCustomBackendEndpoint.Create(nil);
FGetEndpoint.Method := TRESTRequestMethod.rmGET;
FGetResponse := TCustomRESTResponse.Create(nil);
FGetEndPoint.Response := FGetResponse;
FApplyEndpoint := TCustomBackendEndpoint.Create(nil);
FApplyEndpoint.Method := TRESTRequestMethod.rmPOST;
FApplyResponse := TCustomRESTResponse.Create(nil);
FApplyEndpoint.Response := FApplyResponse;
end;
destructor TCustomEMSFireDACClient.Destroy;
begin
FGetEndpoint.Free;
FApplyEndPoint.Free;
FGetResponse.Free;
FApplyResponse.Free;
inherited;
end;
procedure TCustomEMSFireDACClient.CheckResource;
begin
if FResource = '' then
raise TEEMSFireDACClientError.Create(sResourceMustNotBeBlank);
end;
procedure TCustomEMSFireDACClient.UpdateEndpoints;
begin
CheckResource;
FGetEndpoint.Resource := FResource;
FApplyEndpoint.Resource := FResource;
FGetEndpoint.Provider := FProvider;
FApplyEndpoint.Provider := FProvider;
FGetEndpoint.Auth := Auth;
FApplyEndpoint.Auth := Auth;
end;
procedure TCustomEMSFireDACClient.CheckSchemaAdapter;
begin
if FSchemaAdapter = nil then
raise TEEMSFireDACClientError.Create(sSchemaAdapterIsRequired);
if FSchemaAdapter.Count = 0 then
raise TEEMSFireDACClientError.CreateFmt(sSchemaAdapterHasNoData, [FSchemaAdapter.Name]);
end;
procedure TCustomEMSFireDACClient.CheckProvider;
begin
if FProvider = nil then
raise TEEMSFireDACClientError.CreateFmt(sProviderIsRequired, [Self.Name]);
end;
function TCustomEMSFireDACClient.GetCanPostUpdates: Boolean;
var
I: Integer;
LDataSet: TFDAdaptedDataSet;
begin
Result := (FSchemaAdapter <> nil) and (FProvider <> nil);
if Result then
begin
Result := False;
for I := 0 to FSchemaAdapter.Count - 1 do
begin
LDataSet := FSchemaAdapter.DataSets[I];
if LDataSet.UpdatesPending or (LDataSet.State in dsEditModes) then
begin
Result := True;
break;
end;
end;
end;
end;
procedure TCustomEMSFireDACClient.GetData;
var
LStream: TStream;
begin
CheckSchemaAdapter;
CheckProvider;
UpdateEndpoints;
FGetEndpoint.Accept := CONTENTTYPE_APPLICATION_VND_EMBARCADERO_FIREDAC_JSON;
FGetEndpoint.Execute;
if not SameText(FGetEndpoint.Response.ContentType, CONTENTTYPE_APPLICATION_VND_EMBARCADERO_FIREDAC_JSON) then
raise EEMSProviderError.CreateFmt(sUnexpectedContentType, [FGetEndpoint.Response.ContentType]);
if Length(FGetResponse.RawBytes) = 0 then
raise EEMSProviderError.Create(sResponseHasNoContent);
LStream := TMemoryStream.Create;
try
LStream.Write(FGetResponse.RawBytes, Length(FGetResponse.RawBytes));
LStream.Position := 0;
FSchemaAdapter.LoadFromStream(LStream, TFDStorageFormat.sfJSON);
finally
LStream.Free;
end;
end;
procedure TCustomEMSFireDACClient.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if Operation = opRemove then
begin
if AComponent = SchemaAdapter then
SchemaAdapter := nil
else if AComponent = Provider then
Provider := nil
else if (Auth is TComponent) and (TComponent(Auth) = AComponent) then
Auth := nil;
end;
end;
procedure TCustomEMSFireDACClient.PostUpdates;
var
LStream: TStream;
begin
CheckSchemaAdapter;
CheckProvider;
UpdateEndpoints;
LStream := TMemoryStream.Create;
try
FSchemaAdapter.ResourceOptions.StoreItems := [siDelta, siMeta];
FSchemaAdapter.SaveToStream(LStream, TFDStorageFormat.sfJSON);
LStream.Position := 0;
FApplyEndpoint.Params.Clear;
FApplyEndpoint.AddBody(LStream, TRESTContentType.ctAPPLICATION_VND_EMBARCADERO_FIREDAC_JSON);
FApplyEndpoint.Execute;
// FSchemaAdapter.Reconcile;
if Length(FApplyResponse.RawBytes) <> 0 then
if not SameText(FApplyEndpoint.Response.ContentType, CONTENTTYPE_APPLICATION_VND_EMBARCADERO_FIREDAC_JSON) then
raise EEMSProviderError.CreateFmt(sUnexpectedContentType, [FApplyEndpoint.Response.ContentType])
else
raise EEMSProviderError.CreateFmt(sErrorsOnApplyUpdates, [FApplyEndpoint.Response.Content])
else
FSchemaAdapter.CommitUpdates;
finally
LStream.Free;
end;
end;
procedure TCustomEMSFireDACClient.SetAuth(const Value: IBackendAuthReg);
begin
if FAuth <> Value then
begin
if FAuth <> nil then
begin
if FAuth is TComponent then
TComponent(FAuth).RemoveFreeNotification(Self);
end;
FAuth := Value;
if FAuth <> nil then
begin
if FAuth is TComponent then
TComponent(FAuth).FreeNotification(Self);
end;
end;
end;
procedure TCustomEMSFireDACClient.SetProvider(const Value: TEMSProvider);
begin
if Value <> FProvider then
begin
if FProvider <> nil then
FProvider.RemoveFreeNotification(Self);
FProvider := Value;
if FProvider <> nil then
FProvider.FreeNotification(self);
end;
end;
procedure TCustomEMSFireDACClient.SetSchemaAdapter(
const Value: TFDSchemaAdapter);
begin
if Value <> FSchemaAdapter then
begin
if FSchemaAdapter <> nil then
FSchemaAdapter.RemoveFreeNotification(Self);
FSchemaAdapter := Value;
if FSchemaAdapter <> nil then
FSchemaAdapter.FreeNotification(self);
end;
end;
end.
|
unit MgScene;
interface
uses
Classes, SysUtils, MgPrimitives;
type
TMgScene = class(TComponent)
private
FPrimitiveList: TList;
function GetCount: Cardinal;
function GetPrimitive(Index: Cardinal): TMgCustomPrimitive;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AddPrimitive(Primitive: TMgCustomPrimitive);
procedure Clear;
property Primitive[Index: Cardinal]: TMgCustomPrimitive read GetPrimitive; default;
property Count: Cardinal read GetCount;
end;
implementation
resourcestring
RCStrIndexOutOfBounds = 'Index out of bounds (%d)';
{ TMgScene }
constructor TMgScene.Create(AOwner: TComponent);
begin
inherited;
FPrimitiveList := TList.Create;
end;
destructor TMgScene.Destroy;
begin
FPrimitiveList.Free;
inherited;
end;
procedure TMgScene.AddPrimitive(Primitive: TMgCustomPrimitive);
begin
FPrimitiveList.Add(Primitive)
end;
procedure TMgScene.Clear;
begin
FPrimitiveList.Clear;
end;
function TMgScene.GetCount: Cardinal;
begin
Result := FPrimitiveList.Count;
end;
function TMgScene.GetPrimitive(Index: Cardinal): TMgCustomPrimitive;
begin
if Index < FPrimitiveList.Count then
Result := TMgCustomPrimitive(FPrimitiveList.Items[Index])
else
raise Exception.CreateFmt(RCStrIndexOutOfBounds, [Index]);
end;
end.
|
unit ImportPolynomial;
{$mode objfpc}{$H+}
interface
type
TPolynomial = Pointer;
TCopyFunc = function (P: TPolynomial): TPolynomial;
TConstructor = function: TPolynomial; cdecl;
TDestructor = procedure (var P: TPolynomial); cdecl;
TGetIntegerFunc = function (P: TPolynomial): Integer; cdecl;
TSetIntegerProc = procedure (P: TPolynomial; AValue: Integer); cdecl;
TGetDoubleAtIndex = function (P: TPolynomial; AnIndex: Integer): Double; cdecl;
TSetDoubleAtIndex = procedure (P: TPolynomial; AnIndex: Integer; AValue: Double); cdecl;
TGetValueFromArg = function (P: TPolynomial; x: Double): Double; cdecl;
TGetDerivation = function(P: TPolynomial; n: Integer): TPolynomial; cdecl;
TGetSecant = function(P: TPolynomial; a, b: Double): TPolynomial; cdecl;
TGetTangent = function (P: TPolynomial; x0: Double): TPolynomial; cdecl;
var
CreatePolynomial: TConstructor;
CreateCopy: TCopyFunc;
DestroyPolynomial: TDestructor;
GetDegree: TGetIntegerFunc;
SetDegree: TSetIntegerProc;
GetCoefficient: TGetDoubleAtIndex;
SetCoefficient: TSetDoubleAtIndex;
GetPolynomialValue: TGetValueFromArg;
GetDerivation: TGetDerivation;
GetSecant: TGetSecant;
GetTangent: TGetTangent;
LibLoaded: Boolean;
implementation
uses DynLibs, SysUtils;
const
LibFileName = '/Users/andreas/.lib/libpolynomial.dylib';
procedure LinkProc(Lib: TLibHandle; AFuncName: string; var AFuncVar);
begin
Pointer(AFuncVar) := GetProcedureAddress(Lib, AFuncName);
if Pointer(AFuncVar) = nil then
raise Exception.CreateFmt('"%s" is not found in "%s"', [AFuncName, LibFileName]);
end;
var
LibHandle: TLibHandle;
initialization
LibHandle := LoadLibrary(LibFileName);
if LibHandle <> NilHandle then begin
LinkProc(LibHandle, 'CreatePolynomial', CreatePolynomial);
LinkProc(LibHandle, 'CreateCopy', CreateCopy);
LinkProc(LibHandle, 'DestroyPolynomial', DestroyPolynomial);
LinkProc(LibHandle, 'GetDegree', GetDegree);
LinkProc(LibHandle, 'SetDegree', SetDegree);
LinkProc(LibHandle, 'GetCoefficient', GetCoefficient);
LinkProc(LibHandle, 'SetCoefficient', SetCoefficient);
LinkProc(LibHandle, 'GetPolynomialValue', GetPolynomialValue);
LinkProc(LibHandle, 'GetDerivation', GetDerivation);
LinkProc(LibHandle, 'GetSecant', GetSecant);
LinkProc(LibHandle, 'GetTangent', GetTangent);
LibLoaded := True;
end
else raise Exception.Create(GetLoadErrorStr);
finalization
LibLoaded := False;
if not UnloadLibrary(LibHandle) then
raise Exception.CreateFmt('Unloading of "%s" is not possibly', [LibFileName]);
end.
|
(*
* cifra de cesar v0.1b
* --------------------
*
* por : bleno vinicius
* e-mail: blenolopes@gmail.com
* site : www.blenolopes.com
* versao: 0.1 beta
*
* -[ info ]-
*
* Simples programa que demostra o uso da cifra de césar para criptografar
* strings. A cifra de césar é uma técnica simples que consiste em trocar cada
* letra de uma palavra pela terceira préxima letra do alfabeto. Neste caso,
* por exemplo, a letra "a" seria representada pela letra "d".
* Programa de cunho acadêmico. Use-o a vontade, mas conserve os créditos
* do autor.
*
* -[ compilação ]-
*
* compilador: Free Pascal v2.2.0 for i386
* S.O. : Ubuntu 8.04
* kernel : 2.6.24-19
*
*)
program ccesar;
(*
* units
*)
uses
crt;
(*
* variaveis globais
*)
var
escolha : integer;
(*
* procedure info;
* ---------------
* Mostra cabeçalho de informações
* sobre o ccesar v0.1b.
*)
procedure info;
begin
writeln;
writeln('x. Cifra de César v0.1b');
writeln('x. ^^^^^ ^^ ^^^^^ ^^^^^');
writeln;
writeln('x. por : Bleno Vinicius');
writeln('x. e-mail : blenolopes@gmail.com');
writeln('x. site : http://www.bleno.org');
writeln;
end;
(* procedure cifrar
* ----------------
* Procedimento para cifrar a frase
* informada pelo usuário.
*)
procedure cifrar;
var
c : char;
i, j : integer;
contador : integer;
frase : string;
alfa : array[1..26] of char;
begin
contador := 1;
writeln;
write('x. Digite a frase: ');
readln(frase);
for c := 'a' to 'z' do
begin
alfa[contador] := c;
contador := contador + 1;
end;
for i := 1 to length(frase) do
for j := 1 to 26 do
if (frase[i] = alfa[j]) then
frase[i] := chr(ord(j + 64 + 3));
writeln('x. Frase cifrada: ', frase);
readkey;
end;
(* procedure cifrar
* ----------------
* Procedimento para decifrar a frase
* informada pelo usuário.
*)
procedure decifrar;
var
c : char;
i, j : integer;
contador : integer;
frase : string;
alfa : array[1..26] of char;
begin
contador := 1;
writeln;
write('x. Digite a frase: ');
readln(frase);
for c := 'A' to 'Z' do
begin
alfa[contador] := c;
contador := contador + 1;
end;
for i := 1 to length(frase) do
for j := 1 to 26 do
if (frase[i] = alfa[j]) then
frase[i] := chr(ord(j + 96 - 3));
writeln('x. Frase decifrada: ', frase);
readkey;
end;
(*
* begin ;P
*)
begin
escolha := 0;
while (escolha <> 3) do
begin
clrscr;
info;
writeln('1 : Cifrar');
writeln('2 : Decifrar');
writeln('3 : Sair');
writeln;
write('Escolha: ');
readln(escolha);
if (escolha = 1) then
cifrar
else
if (escolha = 2) then
decifrar
else
if (escolha = 3) then
begin
clrscr;
writeln('bye ;)');
end else
begin
writeln;
writeln('x. Escolha invalida!');
writeln('x. pressione [enter]...');
readkey;
end;
end;
end.
{ data: 25/08/2008 - 19:52 }
{ EOF }
|
/////////////////////////////////////////////////////////
// //
// FlexGraphics library //
// Copyright (c) 2002-2009 FlexGraphics software. //
// //
// Utility procedures and functions //
// //
/////////////////////////////////////////////////////////
unit FlexUtils;
{$I FlexDefs.inc}
interface
uses
Windows, Forms, Dialogs, Controls, Messages, Classes,
{$IFDEF FG_D6} Variants, RTLConsts, {$ENDIF} SysUtils,
TypInfo, Graphics, ClipBrd, Consts;
const
// FlexGraphics document clipboard format
CF_FLEXDOC : Word = 0;
// Reserved word's in fxd format
fcDocument = 'document';
fcClipboard = 'clipboard';
fcLibrary = 'library';
fcObject = 'object';
fcProperty = 'property';
fcEnd = 'end';
fcBinary = 'flexbinary';
// array of all reserved words
fcReserved: array[0..6] of string = (
fcDocument, fcClipboard, fcLibrary, fcObject, fcProperty, fcEnd, fcBinary );
IndentStep = ' ';
BooleanWords: array[boolean] of string = ( 'False', 'True' );
// Flex binary commands
fbcUnknown = $0000; // Not a commmand (unknown command)
fbcDocument = $0001; // Key0: Document name, No data
fbcClipboard = $0002; // No keys, No data
fbcLibrary = $0003; // Key0: Library name, No data
fbcObject = $0004; // Key0: Object name, Key1: Class name, No data
fbcProperty = $0005; // Key0: Property name, [Key1: property value],
// DataBlock: TFlexBinPropertyData
fbcComplexProperty = $0006; // Key0: Property name, No data
fbcEnd = $0007; // No keys, No data
fbcReduceDictionary = $0008; // No keys,
// DataBlock: TFlexBinReduceDictionaryData
fbcBinaryEnd = $0009; // No keys, No data
fbcUser = $1000; // 0..65535 keys, [DataBlock: User type]
// Flex binary key flags
fbkIndexSizeMask = $03; // 2 bits
fbkIndexByte = $01; // Next number is byte
fbkIndexWord = $02; // Next number is word
fbkIndexDWord = $03; // Next number is double word
fbkIsIndex = $04; // 1 bit - Next number is index in keys dictinary
// Else is length of the following
// key string
fbkDontStore = $08; // 1 bit - This new key must not be stored in
// keys dictionary
// FlexBinary supported properties types
fbpEmpty = $0000; { vt_empty 0 }
fbpNull = $0001; { vt_null 1 }
fbpSmallint = $0002; { vt_i2 2 }
fbpInteger = $0003; { vt_i4 3 }
fbpSingle = $0004; { vt_r4 4 }
fbpDouble = $0005; { vt_r8 5 }
fbpCurrency = $0006; { vt_cy 6 }
fbpDate = $0007; { vt_date 7 }
// fbpOleStr = $0008; { vt_bstr 8 }
// fbpDispatch = $0009; { vt_dispatch 9 }
// fbpError = $000A; { vt_error 10 }
fbpBoolean = $000B; { vt_bool 11 }
// fbpVariant = $000C; { vt_variant 12 }
// fbpUnknown = $000D; { vt_unknown 13 }
fbpShortInt = $0010; { vt_i1 16 }
fbpByte = $0011; { vt_ui1 17 }
fbpWord = $0012; { vt_ui2 18 }
fbpLongWord = $0013; { vt_ui4 19 }
fbpInt64 = $0014; { vt_i8 20 }
fbpString = $0100; { Pascal string 256 } {not OLE compatible }
fbpStrList = $0200; { FlexGraphics string list }
fbpHexData = $0201; { FlexGraphics hex data block }
// Cursors in InDesign mode
crShapeCursor = 1;
crShapeAddCursor = 2;
crShapeDelCursor = 3;
crShapeCloseCursor = 4;
crShapeMoveCursor = 5;
crShapeMoveCurveCursor = 6;
crCreateControlCursor = 7;
crCreateRectCursor = 8;
crCreateEllipseCursor = 9;
crCreateTextCursor = 10;
crCreatePicCursor = 11;
crCreatePolyCursor = 12;
crZoomInCursor = 13;
crZoomOutCursor = 14;
crPanCursor = 15;
crPanningCursor = 16;
crShapeContinueCursor = 17;
crShapeMoveLineCursor = 18;
crLastFlexCursor = 49;
// Scaling
FloatDisplayFormat: string = '%.3f';
PixelScaleFactor = 1000;
type
TFlexNotify = (
fnName, fnID, fnRect, fnAnchorPoints, fnEditPoints, fnLinkPoints,
fnOrder, fnParent, fnLoaded,
fnLayers, fnSchemes, fnCreated, fnDestroyed, fnSelect, fnSelectPoint,
fnScale, fnPan, fnChange{User generic} );
PTranslateInfo = ^TTranslateInfo;
TTranslateInfo = record
Center: TPoint; // in document (owner) coordinate system
Rotate: integer; // counterclockwise degree
Mirror: boolean; // horizontal mirroring
end;
TBitmapDisplay = ( bdCenter, bdTile, bdStretch );
PTiledBitmapCache = ^TTiledBitmapCache;
TTiledBitmapCache = record
Handle: HBitmap;
Width: integer;
Height: integer;
end;
TBooleanArray = array of boolean;
TGradientStyle = (
gsHorizontal, gsVertical, gsSquare, gsElliptic,
gsTopLeft, gsTopRight, gsBottomLeft, gsBottomRight );
TFlexFiler = class;
TFlexFilerProcess = ( ppUnknown, ppLoad, ppSave, ppCopy );
// Flex binary command
// <Header> [<Keys>] [<Data>]
// <Header>: <TFlexBinHeader>
// <Keys>: { <Key>, ... }
// <Key>: <KeyOptions>: byte, <KeyIndexOrLen>: Byte..DWord, [ <Key chars> ]
// KeyIndexOrLen = 0 - Empty string
// KeyIndexOrLen > 0 - Index of key in dictionary OR
// Length of new key to load
// (depend from <KeyOptions> flags)
// <Data>: <TFlexBinPropertyData> | <User defined type>
PFlexBinHeader = ^TFlexBinHeader;
TFlexBinHeader = packed record
Command: word;
KeyCount: word;
Size: integer;
end;
PFlexBinPropertyData = ^TFlexBinPropertyData;
TFlexBinPropertyData = packed record
case PropType: cardinal of
fbpEmpty,
fbpNull: ( );
fbpSmallint: ( VSmallInt: SmallInt );
fbpInteger: ( VInteger: integer );
fbpSingle: ( VSingle: single );
fbpDouble: ( VDouble: double );
fbpCurrency: ( VCurrency: currency );
fbpDate: ( VDate: {$IFDEF FG_CBUILDER} double
{$ELSE} TDateTime {$ENDIF} );
fbpBoolean: ( VBoolean: integer {!} );
fbpShortInt: ( VShortInt: ShortInt );
fbpByte: ( VByte: Byte );
fbpWord: ( VWord: Word );
fbpLongWord: ( VLongWord: LongWord );
fbpInt64: ( VInt64: Int64 );
fbpString: ( VString: integer {KeyIndex arg number} );
fbpStrList: ( VStrings: record
StrCount: integer;
StrData: record end; {<Len: Int>[<Chars>], ...}
end );
fbpHexData: ( VHexData: record end ); // <Binary block data>
end;
PFlexBinReduceDicData = ^TFlexBinReduceDicData;
TFlexBinReduceDicData = packed record
DeleteCount: integer;
end;
TFlexBinKeyStore = (
fbsObjectName, fbsClassName, fbsPropertyName, fbsPropertyValue );
TFlexBinKeyStoreSet = set of TFlexBinKeyStore;
TFlexBinaryData = class
protected
FOwner: TFlexFiler;
FProcess: TFlexFilerProcess;
FFinished: boolean;
// Keys dictionary
FDictionary: TStringList;
FDicCapacity: integer;
FDicDeleteCount: integer;
// Key types don't store options
FKeyDontStore: TFlexBinKeyStoreSet;
// Keys for Read/Write commands
FCmdKeys: TStringList;
FCmdKeyCount: integer;
FCmdKeysSize: integer;
// Last ReadCommand() data
FCmdReadHeader: TFlexBinHeader;
FCmdReadDataSize: integer;
FCmdReadUserData: pointer;
FCmdReadUserDataSize: integer;
FCmdReadDataAhead: boolean;
// Helpers for LoadStrCheck()
FReadPropLines: TStringList;
FReadPropLine: integer;
// Helpers for SaveStr()
FWritePropType: integer;
FWritePropName: string;
FWritePropData: pointer;
FWritePropDataPos: integer;
FWritePropDataSize: integer;
procedure SetProcess(const Value: TFlexFilerProcess);
procedure SetDicCapacity(const Value: integer);
procedure SetDicDeleteCount(const Value: integer);
function GetReadKey(Index: integer): string;
function GetPropertyDataSize(PropType: integer;
const Value: Variant): integer;
function AddKey(const Key: string; var KeyIndex: integer): boolean;
function AddWriteKey(const Key: string; DontStore: boolean = false): integer;
function ReadKey: boolean;
procedure WriteKey(const Key: string; KeyIndex: integer;
DontStore: boolean = false);
procedure ResetWriteKeys;
function ReadCommandHeaderAndKeys(var Header: TFlexBinHeader): boolean;
function WriteCommandHeaderAndKeys(Command: word;
DataSize: integer): boolean;
function ReadPropertyData(var Value: Variant;
var PropType: integer): boolean;
function AllocReadData: pointer;
procedure ClearReadData;
function GrowWriteData(Size: integer): pointer;
procedure ClearWriteData;
procedure CheckDontStore(Command: word;
var DontStoreKey1, DontStoreKey2: boolean);
procedure ReduceDictionary(ACount: integer);
public
constructor Create(AOwner: TFlexFiler);
destructor Destroy; override;
procedure Reset;
function LoadStrCheck(out s: string): boolean;
procedure SaveStr(const s: string);
procedure SaveStrBuf(Buf: pointer; BufSize: integer);
function ReadCommand: boolean;
function ReadCommandData(out Value: Variant): integer;
function ReadCommandUserData: pointer;
function WritePropertyCommand(const PropName: string; PropType: integer;
const Value: Variant; DontStoreValueKey: boolean = false): boolean;
procedure WriteSimpleCommand(Command: word; KeyCount: integer = 0;
const Key1: string = ''; const Key2: string = '';
DontStoreKey1: boolean = false; DontStoreKey2: boolean = false);
procedure WriteDataCommand(Command: word; var Data; DataSize: integer;
KeyCount: integer = 0; const Key1: string = ''; const Key2: string = '';
DontStoreKey1: boolean = false; DontStoreKey2: boolean = false);
function GetPropertyType(const PropValue: Variant): integer;
property Process: TFlexFilerProcess read FProcess;
property KeyDontStore: TFlexBinKeyStoreSet read FKeyDontStore write
FKeyDontStore;
property Finished: boolean read FFinished;
property DicCapacity: integer read FDicCapacity write SetDicCapacity;
property DicDeleteCount: integer read FDicDeleteCount
write SetDicDeleteCount;
property ReadCmdCommand: word read FCmdReadHeader.Command;
property ReadCmdSize: integer read FCmdReadHeader.Size;
property ReadCmdDataSize: integer read FCmdReadDataSize;
property ReadCmdKeyCount: word read FCmdReadHeader.KeyCount;
property ReadCmdKeys[Index: integer]: string read GetReadKey;
property ReadCmdKeysSize: integer read FCmdKeysSize;
end;
TFlexProgressEvent = procedure(Sender: TObject; Progress: integer;
Process: TFlexFilerProcess) of object;
TFlexFiler = class
private
FStream: TStream;
FBuffer: Pointer;
FBufSize: Integer;
FBufPos: Integer;
FBufEnd: Integer;
FTotal: integer;
FSaved: integer;
FLoaded: integer;
FProgress: integer;
FLastProcess: TFlexFilerProcess;
FBinary: boolean;
FCompleteBinary: boolean;
FBinaryData: TFlexBinaryData;
FOnProgress: TFlexProgressEvent;
procedure SetSaved(const Value: integer);
procedure SetTotal(const Value: integer);
procedure SetBinary(const Value: boolean);
protected
procedure ReadBuffer;
procedure DoProgress(Process: TFlexFilerProcess);
function GetStreamSize: integer;
function ReadBufCheck(Buf: pointer; BufSize: integer): boolean;
procedure ReadBuf(var Buf; BufSize: integer);
function ReadSkipBuf(BufSize: integer): boolean;
procedure WriteBuf(const Buf; BufSize: integer);
procedure ReadError(const Msg: string = ''); virtual;
procedure WriteError(const Msg: string = ''); virtual;
property Stream: TStream read FStream;
public
constructor Create(AStream: TStream; ACompleteBinary: boolean = false);
destructor Destroy; override;
procedure SaveStr(const s: string);
procedure SaveBuf(Buf: pointer; BufSize: integer);
function LoadStr: string;
function LoadStrCheck(out s: string): boolean;
procedure LoadSkipToEnd;
function CheckLoadSkipToEnd(const First: string): boolean;
function IsEndOfStream: boolean;
procedure Rewind;
property Binary: boolean read FBinary write SetBinary;
property CompleteBinary: boolean read FCompleteBinary;
property BinaryData: TFlexBinaryData read FBinaryData;
property Total: integer read FTotal write SetTotal;
property Saved: integer read FSaved write SetSaved;
property Loaded: integer read FLoaded;
property StreamSize: integer read GetStreamSize;
property Progress: integer read FProgress;
property OnProgress: TFlexProgressEvent read FOnProgress write FOnProgress;
end;
TIdPool = class
private
FPool: TList;
function GetUsed(Value: cardinal): boolean;
public
constructor Create;
destructor Destroy; override;
function Generate: cardinal;
function Use(Value: cardinal): boolean;
function Release(Value: cardinal): boolean;
function NextUsed(Value: cardinal; var Index: integer): cardinal;
procedure Clear;
property Used[Value: cardinal]: boolean read GetUsed;
property PoolList: TList read FPool;
end;
TNotifyLink = class;
TNotifyLinkCode = ( ncInfo, ncDestroy, ncPropBeforeChanged, ncPropChanged,
ncControlNotify );
PNotifyLinkInfo = ^TNotifyLinkInfo;
TNotifyLinkInfo = record
case Code: TNotifyLinkCode of
ncInfo:
( WParam: integer;
LParam: integer ); // Generic notification
ncDestroy: ();
ncPropBeforeChanged,
ncPropChanged:
( Prop: TObject {TCustomProp} );
ncControlNotify:
( Control: TObject {TFlexControl};
ControlNotify: TFlexNotify );
end;
TNotifyLinkEvent = procedure(Sender: TObject; Source: TNotifyLink;
const Info: TNotifyLinkInfo) of object;
TNotifyLink = class
private
FLinks: TList;
FOwner: TObject;
FTag: integer;
FDestroying: boolean;
FOnNotify: TNotifyLinkEvent;
FOnFreeNotify: TNotifyLinkEvent;
function GetLink(Index: integer): TNotifyLink;
function GetLinkCount: integer;
function GetLinkRefCount(Index: integer): integer;
public
constructor Create(AOwner: TObject);
destructor Destroy; override;
function IndexOf(Link: TNotifyLink): integer;
function Subscribe(Link: TNotifyLink): integer;
function Unsubscribe(Link: TNotifyLink): integer;
function Notify(const Info: TNotifyLinkInfo): integer;
procedure DestroyNotify;
function PropNotify(AProp: TObject; IsBeforeNotify: boolean): integer;
function ControlNotify(AControl: TObject; ANotify: TFlexNotify): integer;
property Owner: TObject read FOwner;
property LinkCount: integer read GetLinkCount;
property Links[Index: integer]: TNotifyLink read GetLink; default;
property LinksRefCount[Index: integer]: integer read GetLinkRefCount;
property Tag: integer read FTag write FTag;
property Destroying: boolean read FDestroying;
property OnNotify: TNotifyLinkEvent read FOnNotify write FOnNotify;
property OnFreeNotify: TNotifyLinkEvent read FOnFreeNotify
write FOnFreeNotify;
end;
var
SysGradientChecked: boolean = false;
SysGradientEnabled: boolean = false;
SysGradientEllipticSteps: integer = 256;
procedure LoadFlexCursors;
function FlexStrNeedQuote(const s: string): boolean;
function StrBeginsFrom(const S1, S2: string): boolean;
function ExtractWord(const s: string; NumWord: integer; Delimiter: char): string;
function HexCharsToByte(cw: word): byte;
function ByteToHexChars(b: byte): word;
procedure GetPicReadWrite(Picture: TPicture;
out ReadProc, WriteProc: TStreamProc);
function NormalizeRect(const R: TRect): TRect;
function PointInRect(const p: TPoint; const R: TRect): boolean;
function IntersectClipRgn(ACanvas: TCanvas; ClipRgn: HRGN): HRGN;
function IntersectClipPath(DC: HDC): HRGN;
procedure PaintGradient(ACanvas: TCanvas; ARect: TRect; Style: TGradientStyle;
Color, EndColor: TColor; PenMode: TPenMode);
procedure PaintBitmap(ACanvas: TCanvas; const PaintRect, RefreshRect: TRect;
ABitmap: TBitmap; BitmapDisplay: TBitmapDisplay;
BitmapCache: PTiledBitmapCache = Nil; Scale: integer = 100;
ClipTransparent: boolean = false);
procedure PaintTailed(ACanvas: TCanvas; const PaintRect, RefreshRect: TRect;
ABitmap: TBitmap; BitmapCache: PTiledBitmapCache = Nil);
function CreateTransparentClipRgn(DC: HDC; Width, Height: integer;
var Dest: TRect; TransparentColor: TColor): HRGN;
procedure ExcludeBitmapTransparency(Bmp: TBitmap; var R: TRect;
var ClipRgn: HRGN);
function ScaleValue(Value, Scale: integer): integer;
function UnScaleValue(Value, Scale: integer): integer;
function ScalePixels(Value: integer): integer;
function UnScalePixels(Value: integer): integer;
function ListScan(Value, List: Pointer; Count: integer): integer;
function ListScanEx(Value, List: Pointer; Index, Count: integer): integer;
function ListScanLess(Value, List: Pointer; Count: integer): integer;
type
TSortedListCompare = function(Item1, Item2: Pointer): Integer of object;
// Find Item index in alredy sorted list
function SortedListFind(List: PPointerList; Count: integer; Item: Pointer;
Compare: TSortedListCompare; Exact: boolean): integer;
// Return new index for item with ItemIndex in already sorted list. This
// function must be called after some changes in the item to keep list sorted.
// Caller must move item at ItemIndex to resulting index after call.
function ListSortItem(List: PPointerList; Count: integer; ItemIndex: integer;
Compare: TSortedListCompare): integer;
// Sort List in order defined by Compare method
procedure ListQuickSort(List: PPointerList; L, R: Integer;
Compare: TSortedListCompare);
function IsClassParent(AClass, AParentClass: TClass): boolean;
function DotFloatToStr(const Value: extended): string;
function DotStrToFloat(Value: string): extended;
{$IFNDEF FG_D5}
procedure FreeAndNil(var Obj);
function GetPropValue(Instance: TObject; const PropName: string;
PreferStrings: Boolean): Variant;
procedure SetPropValue(Instance: TObject; const PropName: string;
const Value: Variant);
function PropType(AClass: TClass; const PropName: string): TTypeKind;
{$ENDIF}
{$IFNDEF FG_D6}
{ Copied from Delphi7 System.pas unit }
const
varByte = $0011; { vt_ui1 }
varWord = $0012; { vt_ui2 }
varLongWord = $0013; { vt_ui4 }
varInt64 = $0014; { vt_i8 }
varShortInt = $0010; { vt_i1 16 }
type
TVarType = Word;
{ PChar/PWideChar Unicode <-> UTF8 conversion }
type
UTF8String = type string;
PUTF8String = ^UTF8String;
// UnicodeToUTF8(3):
// UTF8ToUnicode(3):
// Scans the source data to find the null terminator, up to MaxBytes
// Dest must have MaxBytes available in Dest.
// MaxDestBytes includes the null terminator (last char in the buffer will be set to null)
// Function result includes the null terminator.
function UnicodeToUtf8(Dest: PChar; Source: PWideChar; MaxBytes: Integer): Integer; overload;
function Utf8ToUnicode(Dest: PWideChar; Source: PChar; MaxChars: Integer): Integer; overload;
// UnicodeToUtf8(4):
// UTF8ToUnicode(4):
// MaxDestBytes includes the null terminator (last char in the buffer will be set to null)
// Function result includes the null terminator.
// Nulls in the source data are not considered terminators - SourceChars must be accurate
function UnicodeToUtf8(Dest: PChar; MaxDestBytes: Cardinal; Source: PWideChar; SourceChars: Cardinal): Cardinal; overload;
function Utf8ToUnicode(Dest: PWideChar; MaxDestChars: Cardinal; Source: PChar; SourceBytes: Cardinal): Cardinal; overload;
{ WideString <-> UTF8 conversion }
function UTF8Encode(const WS: WideString): UTF8String;
function UTF8Decode(const S: UTF8String): WideString;
{ Ansi <-> UTF8 conversion }
function AnsiToUtf8(const S: string): UTF8String;
function Utf8ToAnsi(const S: UTF8String): string;
{$ENDIF}
{$IFNDEF FG_D7}
{ Copied from Delphi7 Classes.pas unit}
type
TGetLookupInfoEvent = procedure(var Ancestor: TPersistent;
var Root, LookupRoot, RootAncestor: TComponent) of object;
function AncestorIsValid(Ancestor: TPersistent; Root,
RootAncestor: TComponent): Boolean;
function IsDefaultPropertyValue(Instance: TObject; PropInfo: PPropInfo;
OnGetLookupInfo: TGetLookupInfoEvent): Boolean;
{$ENDIF}
{$IFNDEF FG_D12}
function RectWidth(const ARect: TRect): integer;
function RectHeight(const ARect: TRect): integer;
{$ENDIF}
implementation
{$R cursors.res}
{$IFDEF FG_D12}
uses Types;
{$ENDIF}
const
fbCmdKeyMask = $3FFFFFFF;
fbCmdKeyNew = $40000000;
fbCmdKeyDontStore = $80000000;
// TFlexBinaryData ////////////////////////////////////////////////////////////
constructor TFlexBinaryData.Create(AOwner: TFlexFiler);
begin
FOwner := AOwner;
FKeyDontStore := [ ]; // [ fbsPropertyValue ];
FDictionary := TStringList.Create;
FCmdKeys := TStringList.Create;
FReadPropLines := TStringList.Create;
FDicCapacity := 65536;
FDicDeleteCount := 8192;
Reset;
end;
destructor TFlexBinaryData.Destroy;
begin
inherited;
ClearReadData;
ClearWriteData;
FDictionary.Free;
FCmdKeys.Free;
FReadPropLines.Free;
end;
procedure TFlexBinaryData.SetProcess(const Value: TFlexFilerProcess);
var s: AnsiString;
begin
if (FProcess = Value) or (FProcess <> ppUnknown) then exit;
FProcess := Value;
if FProcess = ppSave then begin
// Dictionary must be sorted in ppSave process only
FDictionary.Sorted := true;
if not FOwner.CompleteBinary then begin
// Write binary keyword first
s := fcBinary + #$0D#$0A;
FOwner.WriteBuf(s[1], Length(s));
end;
end;
end;
procedure TFlexBinaryData.SetDicCapacity(const Value: integer);
begin
if FProcess <> ppUnknown then exit;
FDicCapacity := Value;
end;
procedure TFlexBinaryData.SetDicDeleteCount(const Value: integer);
begin
if FProcess <> ppUnknown then exit;
FDicDeleteCount := Value;
end;
function TFlexBinaryData.GetReadKey(Index: integer): string;
var KeyIndex: integer;
begin
Result := '';
if (FProcess <> ppLoad) or
(Index < 0) or (Index >= FCmdKeyCount) then exit;
KeyIndex := integer(FCmdKeys.Objects[Index]);
if KeyIndex and fbCmdKeyNew = 0
then Result := FDictionary[KeyIndex]
else Result := FCmdKeys[Index];
end;
procedure TFlexBinaryData.Reset;
begin
FDictionary.Clear;
FDictionary.Sorted := false;
FDictionary.Add('');
FProcess := ppUnknown;
FFinished := false;
FReadPropLines.Clear;
ClearWriteData;
ClearReadData;
end;
function TFlexBinaryData.AddKey(const Key: string;
var KeyIndex: integer): boolean;
var DicCount: integer;
begin
if Key = '' then begin
// Empty key string
KeyIndex := 0;
Result := false;
end else
if FProcess = ppSave then begin
// Add key if not exist
DicCount := FDictionary.Count;
//KeyIndex := FDictionary.AddObject(Key, pointer(DicCount));
KeyIndex := FDictionary.Add(Key);
Result := DicCount < FDictionary.Count;
if Result then begin
// New key added
FDictionary.Objects[KeyIndex] := pointer(DicCount);
// Check dictionary reduction
if (FDicCapacity > 0) and (FDictionary.Count > FDicCapacity) then
ReduceDictionary(FDicDeleteCount);
end else
// Get original (without sorting) index for key
KeyIndex := integer(FDictionary.Objects[KeyIndex]);
end else begin
KeyIndex := FDictionary.Add(Key);
Result := true;
end;
end;
procedure TFlexBinaryData.ReduceDictionary(ACount: integer);
var Limit, i: integer;
Index, DicIndex: integer;
Header: TFlexBinHeader;
ReduceData: TFlexBinReduceDicData;
begin
if ACount <= 0 then exit;
Limit := FDictionary.Count - ACount;
if Limit < 1 then Limit := 1;
case FProcess of
ppLoad:
// Just delete last ACount items
while FDictionary.Count > Limit do FDictionary.Delete(FDictionary.Count-1);
ppSave:
begin
// Fix current command keys
for i:=0 to FCmdKeyCount-1 do begin
DicIndex := integer(FCmdKeys.Objects[i]);
Index := DicIndex and fbCmdKeyMask;
if (DicIndex and fbCmdKeyNew = 0) and (Index >= Limit) then begin
// This key must be deleted now. Make new key
FCmdKeys[i] := FDictionary[Index];
FCmdKeys.Objects[i] := pointer(fbCmdKeyNew); // Can't have DontStore flag!
end;
end;
// Delete all items with real index greater then Limit
for i:=FDictionary.Count-1 downto 0 do
if integer(FDictionary.Objects[i]) >= Limit then FDictionary.Delete(i);
// Save reduce dictionary command
Header.Command := fbcReduceDictionary;
Header.KeyCount := 0;
Header.Size := SizeOf(Header) + SizeOf(ReduceData);
FOwner.WriteBuf(Header, SizeOf(Header));
ReduceData.DeleteCount := ACount;
FOwner.WriteBuf(ReduceData, SizeOf(ReduceData));
end;
end;
end;
procedure TFlexBinaryData.WriteKey(const Key: string; KeyIndex: integer;
DontStore: boolean = false);
var AnsiKey: AnsiString;
Len: integer;
KeyHead: array[0..4] of byte;
KeyHeadSize: integer;
begin
AnsiKey := AnsiString(Key);
Len := Length(AnsiKey);
if Len > 0 then KeyIndex := Len;
// Setup key head size: key options + key index or len
if KeyIndex <= High(Byte) then begin
KeyHead[0] := fbkIndexByte;
KeyHead[1] := KeyIndex and $FF;
KeyHeadSize := 2;
end else
if KeyIndex <= High(Word) then begin
KeyHead[0] := fbkIndexWord;
KeyHead[1] := KeyIndex and $FF;
KeyHead[2] := KeyIndex and $FF00 shr 8;
KeyHeadSize := 3;
end else begin
KeyHead[0] := fbkIndexDWord;
KeyHead[1] := KeyIndex and $FF;
KeyHead[2] := (KeyIndex shr 8) and $FF;
KeyHead[3] := (KeyIndex shr 16) and $FF;
KeyHead[4] := KeyIndex shr 24;
KeyHeadSize := 5;
end;
if DontStore then KeyHead[0] := KeyHead[0] or fbkDontStore;
if Len = 0 then
KeyHead[0] := KeyHead[0] or fbkIsIndex;
// Save key head
FOwner.WriteBuf(KeyHead, KeyHeadSize);
// Save key string
if Len > 0 then FOwner.WriteBuf(AnsiKey[1], Len);
end;
function TFlexBinaryData.ReadKey: boolean;
var KeyFirst: word;
KeyOptions: byte;
KeyIndex: integer;
KeyIndexOrLen: array[0..3] of byte;
AddSize: integer;
procedure ReadKeyFromStream(Len: integer; Store: boolean);
var s: AnsiString;
KeyIndex: integer;
begin
SetLength(s, Len);
FOwner.ReadBuf(s[1], Len);
inc(FCmdKeysSize, Len);
// Add key to dictionary
if Store
then AddKey(String(s), KeyIndex)
else KeyIndex := 0;
KeyIndex := KeyIndex or fbCmdKeyNew;
// Save Key in FCmdKeys
if FCmdKeys.Count = FCmdKeyCount then
FCmdKeys.AddObject(String(s), pointer(KeyIndex))
else begin
FCmdKeys[FCmdKeyCount] := String(s);
FCmdKeys.Objects[FCmdKeyCount] := pointer(KeyIndex);
end;
inc(FCmdKeyCount);
end;
begin
Result := true;
FOwner.ReadBuf(KeyFirst, SizeOf(KeyFirst));
inc(FCmdKeysSize, SizeOf(KeyFirst));
KeyOptions := KeyFirst and $FF;
// Define key length
case KeyOptions and fbkIndexSizeMask of
fbkIndexByte : AddSize := 0;
fbkIndexWord : AddSize := 1;
fbkIndexDWord : AddSize := 3;
else begin
FOwner.ReadError;
AddSize := 0;
end;
end;
if AddSize > 0 then begin
// Read key index or length
KeyIndexOrLen[0] := KeyFirst shr 8;
FOwner.ReadBuf(KeyIndexOrLen[1], AddSize);
inc(FCmdKeysSize, AddSize);
if AddSize = 1 then
KeyIndex := word(KeyIndexOrLen[0] or KeyIndexOrLen[1] shl 8)
else
KeyIndex := KeyIndexOrLen[0] or KeyIndexOrLen[1] shl 8 or
KeyIndexOrLen[2] shl 16 or KeyIndexOrLen[3] shl 24;
end else
// Index size is one byte
KeyIndex := byte(KeyFirst shr 8);
if KeyOptions and fbkIsIndex <> 0 then begin
// Read key from dictionary
// KeyIndex := -KeyIndex;
// Save KeyIndex only in FCmdKeys
if FCmdKeys.Count = FCmdKeyCount
then FCmdKeys.AddObject('', pointer(KeyIndex))
else FCmdKeys.Objects[FCmdKeyCount] := pointer(KeyIndex);
inc(FCmdKeyCount);
end else
// Read key from stream and save in FCmdKeys
ReadKeyFromStream(KeyIndex, KeyOptions and fbkDontStore = 0);
end;
{$HINTS OFF}
function TFlexBinaryData.GetPropertyDataSize(PropType: integer;
const Value: Variant): integer;
var PropData: TFlexBinPropertyData;
Count, i: integer;
begin
case PropType of
fbpEmpty,
fbpNull: Result := 0;
fbpSmallint: Result := SizeOf(PropData.VSmallInt);
fbpInteger: Result := SizeOf(PropData.VInteger);
fbpSingle: Result := SizeOf(PropData.VSingle);
fbpDouble: Result := SizeOf(PropData.VDouble);
fbpCurrency: Result := SizeOf(PropData.VCurrency);
fbpDate: Result := SizeOf(PropData.VDate);
fbpBoolean: Result := SizeOf(PropData.VBoolean);
fbpShortInt: Result := SizeOf(PropData.VShortInt);
fbpByte: Result := SizeOf(PropData.VByte);
fbpWord: Result := SizeOf(PropData.VWord);
fbpLongWord: Result := SizeOf(PropData.VLongWord);
fbpInt64: Result := SizeOf(PropData.VInt64);
fbpString: Result := SizeOf(PropData.VString);
fbpStrList,
fbpHexData:
if VarIsEmpty(Value) or VarIsNull(Value) then
Result := 0
else
if VarType(Value) and varArray = 0 then
Result := -1
else begin
Count := VarArrayHighBound(Value, 1) + 1;
if PropType = fbpHexData then
Result := Count
else begin
Result := SizeOf(Count);
for i:=0 to Count-1 do inc(Result, SizeOf(Count) + Length(Value[i]));
end;
end;
else
Result := -1;
end;
if Result >= 0 then inc(Result, SizeOf(PropData.PropType));
end;
{$HINTS ON}
function TFlexBinaryData.GetPropertyType(const PropValue: Variant): integer;
begin
case VarType(PropValue) of
varEmpty : Result := fbpEmpty;
varNull : Result := fbpNull;
varSmallInt : Result := fbpSmallint;
varInteger : Result := fbpInteger;
varSingle : Result := fbpSingle;
varDouble : Result := fbpDouble;
varCurrency : Result := fbpCurrency;
varDate : Result := fbpDate;
varBoolean : Result := fbpBoolean;
varShortInt : Result := fbpShortInt;
varByte : Result := fbpByte;
varWord : Result := fbpWord;
varLongWord : Result := fbpLongWord;
varInt64 : Result := fbpInt64;
varString : Result := fbpString;
else Result := fbpString;
end;
end;
procedure TFlexBinaryData.ClearReadData;
begin
if not Assigned(FCmdReadUserData) then exit;
FreeMem(FCmdReadUserData);
FCmdReadUserData := Nil;
FCmdReadUserDataSize := 0;
end;
function TFlexBinaryData.AllocReadData: pointer;
begin
if Assigned(FCmdReadUserData) then ClearReadData;
if FCmdReadDataSize > 0 then begin
GetMem(FCmdReadUserData, FCmdReadDataSize);
FCmdReadUserDataSize := FCmdReadDataSize;
end;
Result := FCmdReadUserData;
end;
function TFlexBinaryData.GrowWriteData(Size: integer): pointer;
const GrowSize = 65536;
var NewSize: integer;
begin
Result := FWritePropData;
NewSize := FWritePropDataPos + Size;
if NewSize <= FWritePropDataSize then exit;
NewSize := (NewSize div GrowSize +1) * GrowSize;
if Assigned(FWritePropData)
then ReallocMem(FWritePropData, NewSize)
else GetMem(FWritePropData, NewSize);
FWritePropDataSize := NewSize;
if NewSize < FWritePropDataPos then FWritePropDataPos := NewSize;
Result := FWritePropData;
end;
procedure TFlexBinaryData.ClearWriteData;
begin
if not Assigned(FWritePropData) then exit;
FreeMem(FWritePropData);
FWritePropData := Nil;
FWritePropDataSize := 0;
FWritePropDataPos := 0;
FWritePropType := fbpEmpty;
end;
function TFlexBinaryData.ReadCommandHeaderAndKeys(
var Header: TFlexBinHeader): boolean;
var i: integer;
begin
Result := false;
if (FProcess = ppSave) or FFinished then exit;
if FProcess = ppUnknown then SetProcess(ppLoad);
// Check skip data block
if FCmdReadDataAhead then begin
// FOwner.Stream.Position := FOwner.Stream.Position + FCmdReadDataSize;
FOwner.ReadSkipBuf(FCmdReadDataSize);
FCmdReadDataSize := 0;
FCmdReadDataAhead := false;
end else
ClearReadData;
// Check finished
if FFinished then exit;
// Read header
FOwner.ReadBuf(Header, SizeOf(Header));
if (@FCmdReadHeader <> @Header) then FCmdReadHeader := Header;
// Read keys
FCmdKeyCount := 0;
FCmdKeysSize := 0;
for i:=0 to Header.KeyCount-1 do ReadKey;
// Calculate data size
FCmdReadDataSize :=
FCmdReadHeader.Size - SizeOf(FCmdReadHeader) - FCmdKeysSize;
FCmdReadDataAhead := FCmdReadDataSize > 0;
// Check dictionary reduction
if Header.Command = fbcReduceDictionary then begin
// Reduce dictionary
ReduceDictionary( PFlexBinReduceDicData(ReadCommandUserData).DeleteCount );
end;
// Update finished
FFinished := Header.Command = fbcBinaryEnd;
if FFinished then FOwner.Binary := false;
end;
function TFlexBinaryData.WriteCommandHeaderAndKeys(Command: word;
DataSize: integer): boolean;
var Header: TFlexBinHeader;
i: integer;
DicIndex: cardinal;
DontStore: boolean;
begin
Result := false;
if (FProcess = ppLoad) or FFinished then exit;
if FProcess = ppUnknown then SetProcess(ppSave);
// Check finished
if FFinished then exit;
// Write header
Header.Command := Command;
Header.KeyCount := FCmdKeyCount;
Header.Size := SizeOf(Header) + FCmdKeysSize + DataSize;
FOwner.WriteBuf(Header, SizeOf(Header));
// Write keys
for i:=0 to FCmdKeyCount-1 do begin
DicIndex := cardinal(FCmdKeys.Objects[i]);
DontStore := DicIndex and fbCmdKeyDontStore <> 0;
if DicIndex and fbCmdKeyNew <> 0
then WriteKey(FCmdKeys[i], -1, DontStore)
else WriteKey('', DicIndex and fbCmdKeyMask, DontStore);
end;
// Update finished
FFinished := Command = fbcBinaryEnd;
if FFinished then FOwner.Binary := false;
Result := true;
end;
procedure TFlexBinaryData.ResetWriteKeys;
begin
if FProcess = ppUnknown then SetProcess(ppSave);
FCmdKeyCount := 0;
FCmdKeysSize := 0;
end;
function TFlexBinaryData.AddWriteKey(const Key: string;
DontStore: boolean = false): integer;
var KeyIndex, DicIndex, Len: integer;
Size: integer;
begin
// Test key length
Len := Length(Key);
if Len > fbCmdKeyMask then FOwner.WriteError;
// Store key in dictinary
if DontStore or AddKey(Key, KeyIndex) then begin
// New key in dictionary. Set KeyIndex as length
KeyIndex := Len;
DicIndex := fbCmdKeyNew;
end else
// Key already exist
DicIndex := KeyIndex;
// Add DontStore flag if necessary
if DontStore then DicIndex := integer(Cardinal(DicIndex) or fbCmdKeyDontStore);
// Calc key size
if KeyIndex <= High(Byte) then
Size := 2
else
if KeyIndex <= High(Word) then
Size := 3
else
Size := 5;
if DicIndex and fbCmdKeyNew <> 0 then inc(Size, Len);
// Change command keys size
inc(FCmdKeysSize, Size);
// Save Key in FCmdWriteKeys
if FCmdKeys.Count = FCmdKeyCount then
FCmdKeys.AddObject(Key, pointer(DicIndex))
else begin
FCmdKeys[FCmdKeyCount] := Key;
FCmdKeys.Objects[FCmdKeyCount] := pointer(DicIndex);
end;
Result := FCmdKeyCount;
inc(FCmdKeyCount);
end;
procedure TFlexBinaryData.CheckDontStore(Command: word; var DontStoreKey1,
DontStoreKey2: boolean);
begin
case Command of
fbcDocument,
fbcLibrary,
fbcObject:
begin
DontStoreKey1 := DontStoreKey1 or (fbsObjectName in FKeyDontStore);
DontStoreKey2 := DontStoreKey2 or (fbsClassName in FKeyDontStore);
end;
fbcProperty,
fbcComplexProperty:
begin
DontStoreKey1 := DontStoreKey1 or (fbsPropertyName in FKeyDontStore);
DontStoreKey2 := DontStoreKey2 or (fbsPropertyValue in FKeyDontStore);
end;
end;
end;
procedure TFlexBinaryData.WriteSimpleCommand(Command: word;
KeyCount: integer = 0; const Key1: string = ''; const Key2: string = '';
DontStoreKey1: boolean = false; DontStoreKey2: boolean = false);
begin
if FFinished then exit;
ResetWriteKeys;
CheckDontStore(Command, DontStoreKey1, DontStoreKey2);
if KeyCount > 0 then AddWriteKey(Key1, DontStoreKey1);
if KeyCount > 1 then AddWriteKey(Key2, DontStoreKey2);
WriteCommandHeaderAndKeys(Command, 0);
end;
procedure TFlexBinaryData.WriteDataCommand(Command: word; var Data;
DataSize: integer; KeyCount: integer = 0;
const Key1: string = ''; const Key2: string = '';
DontStoreKey1: boolean = false; DontStoreKey2: boolean = false);
begin
if FFinished then exit;
ResetWriteKeys;
CheckDontStore(Command, DontStoreKey1, DontStoreKey2);
if KeyCount > 0 then AddWriteKey(Key1, DontStoreKey1);
if KeyCount > 1 then AddWriteKey(Key2, DontStoreKey2);
if WriteCommandHeaderAndKeys(Command, DataSize) then
FOwner.WriteBuf(Data, DataSize);
end;
function TFlexBinaryData.WritePropertyCommand(const PropName: string;
PropType: integer; const Value: Variant;
DontStoreValueKey: boolean = false): boolean;
var DataSize: integer;
PropData: TFlexBinPropertyData;
PropDataPtr: PFlexBinPropertyData;
HexData: pointer;
HexDataSize: integer;
i: integer;
StrCount: integer;
StrPtr: PAnsiChar;
StrLen: integer;
s: AnsiString;
NameDontStore: boolean;
begin
Result := false;
if FFinished then exit;
// Calc DataSize
DataSize := GetPropertyDataSize(PropType, Value);
if DataSize < 0 then exit;
// Check DontStore flags for keys
NameDontStore := false;
CheckDontStore(fbcProperty, NameDontStore, DontStoreValueKey);
// Init write keys
ResetWriteKeys;
AddWriteKey(PropName, NameDontStore);
// Fill PropData
PropData.PropType := PropType;
PropDataPtr := @PropData;
try
case PropType of
fbpSmallint : PropData.VSmallInt := Value;
fbpInteger : PropData.VInteger := Value;
fbpSingle : PropData.VSingle := Value;
fbpDouble : PropData.VDouble := Value;
fbpCurrency : PropData.VCurrency := Value;
fbpDate : PropData.VDate := Value;
fbpBoolean : PropData.VBoolean := Value;
fbpShortInt : PropData.VShortInt := Value;
fbpByte : PropData.VByte := Value;
fbpWord : PropData.VWord := Value;
fbpLongWord : PropData.VLongWord := Value;
fbpInt64:
{$IFDEF FG_D6}
PropData.VInt64 := Value;
{$ELSE}
FOwner.WriteError;
{$ENDIF}
fbpString:
PropData.VString := AddWriteKey(Value, DontStoreValueKey);
fbpStrList:
begin
GetMem(PropDataPtr, DataSize);
PropDataPtr.PropType := PropType;
if not VarIsEmpty(Value) and not VarIsNull(Value) then begin
// Save string count
StrCount := VarArrayHighBound(Value, 1) + 1;
PropDataPtr.VStrings.StrCount := StrCount;
// Save strings
StrPtr := @PropDataPtr.VStrings.StrData;
for i:=0 to StrCount-1 do begin
s := AnsiString(Value[i]);
StrLen := Length(s);
PInteger(StrPtr)^ := StrLen;
inc(StrPtr, SizeOf(StrLen));
Move(s[1], StrPtr^, StrLen);
inc(StrPtr, StrLen);
end;
end;
end;
fbpHexData:
begin
GetMem(PropDataPtr, DataSize);
PropDataPtr.PropType := PropType;
HexDataSize :=
DataSize - (PAnsiChar(@PropDataPtr.VHexData) - PAnsiChar(PropDataPtr));
if HexDataSize > 0 then begin
// Move block
HexData := VarArrayLock(Value);
try
Move(HexData^, PropDataPtr.VHexData, HexDataSize);
finally
VarArrayUnlock(Value);
end;
end;
end;
else
exit;
end;
// Write command
if WriteCommandHeaderAndKeys(fbcProperty, DataSize) then
FOwner.WriteBuf(PropDataPtr^, DataSize);
finally
if PropDataPtr <> @PropData then FreeMem(PropDataPtr);
end;
Result := true;
end;
function TFlexBinaryData.ReadPropertyData(var Value: Variant;
var PropType: integer): boolean;
var PropSimpleData: TFlexBinPropertyData;
PropData: PFlexBinPropertyData;
//KeyIndex: integer;
i: integer;
StrPtr: PAnsiChar;
StrLen: integer;
StrCount: integer;
s: AnsiString;
HexData: pointer;
HexDataSize: integer;
begin
Result := false;
if FCmdReadDataSize < SizeOf(PropData.PropType) then exit;
PropData := @PropSimpleData;
try
if FCmdReadDataSize > SizeOf(PropSimpleData) then
GetMem(PropData, FCmdReadDataSize);
if FCmdReadDataAhead then begin
FOwner.ReadBuf(PropData^, FCmdReadDataSize);
FCmdReadDataAhead := false;
end else
exit;
PropType := PropData.PropType;
case PropType of
fbpSmallint : Value := PropData.VSmallInt;
fbpInteger : Value := PropData.VInteger;
fbpSingle : Value := PropData.VSingle;
fbpDouble : Value := PropData.VDouble;
fbpCurrency : Value := PropData.VCurrency;
fbpDate : Value := PropData.VDate;
fbpBoolean : if PropData.VBoolean = 0
then Value := false
else Value := true;
fbpShortInt : Value := PropData.VShortInt;
fbpByte : Value := PropData.VByte;
fbpWord : Value := PropData.VWord;
{$IFDEF FG_D6}
fbpLongWord : Value := PropData.VLongWord;
fbpInt64 : Value := PropData.VInt64;
{$ELSE}
fbpLongWord : Value := integer(PropData.VLongWord);
fbpInt64 : FOwner.ReadError;
{$ENDIF}
fbpString:
begin
{KeyIndex := integer(FCmdKeys[PropData.VString]);
if KeyIndex = 0
then Value := ''
else Value := FDictionary[KeyIndex];}
Value := ReadCmdKeys[PropData.VString];
end;
fbpStrList:
begin
// Read strings count and create variant array
StrCount := PropData.VStrings.StrCount;
Value := VarArrayCreate([0, StrCount-1], varVariant);
// Read strings
StrPtr := @PropData.VStrings.StrData;
for i:=0 to StrCount-1 do begin
// Read string length
StrLen := PInteger(StrPtr)^;
inc(StrPtr, SizeOf(StrLen));
SetLength(s, StrLen);
// Read string chars
Move(StrPtr^, s[1], StrLen);
inc(StrPtr, StrLen);
// Set string in value
Value[i] := s;
end;
end;
fbpHexData:
begin
HexDataSize := FCmdReadDataSize -
(PAnsiChar(@PropData.VHexData) - PAnsiChar(PropData));
if HexDataSize > 0 then begin
// Create byte array
Value := VarArrayCreate([0, HexDataSize-1], varByte);
// Move block
HexData := VarArrayLock(Value);
try
Move(PropData.VHexData, HexData^, HexDataSize);
finally
VarArrayUnlock(Value);
end;
end else
VarClear(Value);
end;
end;
finally
if PropData <> @PropSimpleData then FreeMem(PropData);
end;
Result := true;
end;
function TFlexBinaryData.LoadStrCheck(out s: string): boolean;
var Value: Variant;
PropType: integer;
NotSupported: boolean;
i, Last, Size: integer;
HexLine: AnsiString;
HexData, Pos: PAnsiChar;
begin
Result := false;
if (FProcess = ppSave) or FFinished then exit;
// Check continue reading property lines
if FReadPropLines.Count > 0 then begin
s := FReadPropLines[FReadPropLine];
inc(FReadPropLine);
if FReadPropLine = FReadPropLines.Count then begin
FReadPropLines.Clear;
FReadPropLine := 0;
end;
end else begin
// Read new command
ReadCommandHeaderAndKeys(FCmdReadHeader);
case FCmdReadHeader.Command of
fbcDocument:
s := fcDocument + ' ' + ReadCmdKeys[0];
fbcClipboard:
s := fcClipboard;
fbcLibrary:
s := fcLibrary + ' ' + ReadCmdKeys[0];
fbcObject:
s := fcObject + ' ' + ReadCmdKeys[0] + ': ' + ReadCmdKeys[1];
fbcComplexProperty:
s := fcProperty + ' ' + ReadCmdKeys[0];
fbcEnd:
s := fcEnd;
fbcBinaryEnd:
exit;
fbcProperty:
// Read property
if not ReadPropertyData(Value, PropType) then
// Read error. Skip line
s := ''
else begin
// Convert property data to string
NotSupported := false;
case PropType of
fbpSmallint,
fbpInteger,
fbpShortInt,
fbpByte,
fbpWord,
fbpLongWord,
fbpInt64:
s := Value;
fbpSingle,
fbpDouble,
fbpCurrency,
fbpDate:
s := DotFloatToStr(Value);
fbpBoolean:
s := BooleanWords[boolean(Value)];
fbpString:
begin
s := Value;
if FlexStrNeedQuote(s) then s := '''' + s + '''';
end;
fbpStrList:
if VarIsEmpty(Value) or VarIsNull(Value) then
s := '( )'
else begin
s := '(';
// Generate string list lines in FReadPropLines for further calls
Last := VarArrayHighBound(Value, 1);
for i:=0 to Last do
if i = Last
then FReadPropLines.Add('''' + string(Value[i]) + ''' )')
else FReadPropLines.Add('''' + string(Value[i]) + '''');
end;
fbpHexData:
if VarIsEmpty(Value) or VarIsNull(Value) then
s := '{ }'
else begin
s := '{';
// Generate hex lines list in FReadPropLines for further calls
Last := VarArrayHighBound(Value, 1);
Size := 2*(Last+1) +2;
SetLength(HexLine, Size);
Pos := PAnsiChar(HexLine);
HexData := VarArrayLock(Value);
try
for i:=0 to Last do begin
pword(Pos)^ := ByteToHexChars(byte(HexData[i]));
inc(Pos, 2);
end;
Pos^ := ' ';
Pos[1] := '}';
finally
VarArrayUnlock(Value);
end;
end;
else
// Unknown or unsupported property type
NotSupported := true;
end;
if NotSupported
then s := ''
else s := ReadCmdKeys[0] + ' = ' + s;
end;
else
if FCmdReadHeader.Command >= fbcUser then
// User commands
s := ''
else
// Unknown command;
exit;
end;
end;
Result := true;
end;
procedure TFlexBinaryData.SaveStr(const s: string);
const
KeyWords: array[0..6] of record
KeyWord: String;
Command: integer;
end = (
( KeyWord: fcDocument; Command: fbcDocument ),
( KeyWord: fcClipboard; Command: fbcClipboard ),
( KeyWord: fcLibrary; Command: fbcLibrary ),
( KeyWord: fcObject; Command: fbcObject ),
( KeyWord: fcProperty; Command: fbcComplexProperty ),
( KeyWord: fcEnd; Command: fbcEnd ),
( KeyWord: fcBinary; Command: -1 )
);
procedure WriteProp;
begin
// Write buffer
WriteDataCommand(fbcProperty, FWritePropData^, FWritePropDataPos, 1,
FWritePropName);
// Reset write buffer
FWritePropDataPos := 0;
FWritePropType := fbpEmpty;
end;
function ThisWord(const s: string; Pos, Len: integer;
const AWord: string): boolean;
var i: integer;
LastLen: integer;
begin
LastLen := Len - Pos +1;
Result := LastLen = Length(AWord);
if not Result then exit;
for i:=1 to LastLen do
if s[Pos + i -1] <> AWord[i] then begin
Result := false;
break;
end;
end;
var Line, Name, Value, NewValue: string;
AnsiLine: AnsiString;
Command: integer;
i, j, Len, KeyEnd, Size: integer;
PropData: TFlexBinPropertyData;
LastLine, IsIntNumber: boolean;
Buf: PAnsiChar;
IntNumber: integer;
begin
if (FProcess = ppLoad) or FFinished then exit;
// Skip left blanks
Line := TrimLeft(s);
AnsiLine := AnsiString(Line);
Len := Length(Line);
// Check string list or hex block saving
case FWritePropType of
fbpStrList:
begin
LastLine := AnsiLine[Len] = ')';
if LastLine then dec(Len);
while (Len > 0) and (AnsiLine[Len] = ' ') do dec(Len);
if (Len > 1) and (AnsiLine[1] = '''') and (AnsiLine[Len] = '''') then begin
// Add new line to write buffer
dec(Len, 2);
Size := SizeOf(Integer) + Len;
GrowWriteData(Size);
Buf := PAnsiChar(FWritePropData) + FWritePropDataPos;
PInteger(Buf)^ := Len;
inc(PInteger(Buf));
for i:=0 to Len-1 do Buf[i] := AnsiLine[i+2];
inc(FWritePropDataPos, Size);
// Increment line count
inc(PFlexBinPropertyData(FWritePropData).VInteger);
end;
if LastLine then WriteProp;
end;
fbpHexData:
begin
LastLine := AnsiLine[Len] = '}';
if LastLine then dec(Len);
while (Len > 0) and (AnsiLine[Len] = ' ') do dec(Len);
if Len > 1 then begin
// Add new line to write buffer
Size := Len div 2;
GrowWriteData(Size);
Buf := PAnsiChar(FWritePropData) + FWritePropDataPos;
for i:=0 to Size-1 do
Buf[i] := AnsiChar(
HexCharsToByte(Byte(AnsiLine[2*i+1]) shl 8 or Byte(AnsiLine[2*i+2]))
);
inc(FWritePropDataPos, Size);
end;
if LastLine then WriteProp;
end;
else
begin
// Define command
KeyEnd := 1;
Command := fbcProperty;
for i:=Low(KeyWords) to High(KeyWords) do
if StrBeginsFrom(KeyWords[i].KeyWord, Line) then begin
Command := KeyWords[i].Command;
KeyEnd := Length(KeyWords[i].KeyWord);
inc(KeyEnd);
if (Length(Line) > KeyEnd) and (Line[KeyEnd+1] = ' ') then inc(KeyEnd);
break;
end;
// Check binary keyword. Since we already in binary mode nothing need to save
if Command < 0 then exit;
// Save command
case Command of
fbcDocument,
fbcLibrary,
fbcComplexProperty:
// Get name from line
WriteSimpleCommand(Command, 1, copy(Line, KeyEnd+1, MaxInt));
fbcClipboard,
fbcEnd:
// Command without keys
WriteSimpleCommand(Command);
fbcObject:
begin
// Find class name start
i := Len;
while (i >= KeyEnd) and (Line[i] <> ':') do dec(i);
if Line[i] <> ':' then
raise EWriteError.Create(SWriteError);
// Save command
WriteSimpleCommand(Command, 2,
Trim(copy(Line, KeyEnd, i - KeyEnd)), // Object name
Trim(copy(Line, i+1, MaxInt)) // Class name
);
end;
fbcProperty:
begin
i := 1;
while (i <= Len) and (Line[i] <> '=') do inc(i);
if Line[i] <> '=' then FOwner.WriteError;
// Get property name
Name := Trim(copy(Line, 1, i-1));
// Skip blanks
inc(i);
while (i <= Len) and (Line[i] = ' ') do inc(i);
// Define property type
case Line[i] of
'1'..'9', '-': // Without leading zero!!
// Integer Number
begin
// Check all chars
IsIntNumber := false;
for j:=i+1 to Len do begin
IsIntNumber := (Line[j] >= '0') and (Line[j] <= '9');
if not IsIntNumber then break;
end;
Value := copy(Line, i, MaxInt);
if IsIntNumber then
try
IntNumber := StrToInt(Value);
// Test successful conversion
NewValue := IntToStr(IntNumber);
for j:=i to Len do
if Line[j] <> NewValue[j-i+1] then begin
IsIntNumber := false;
break;
end;
if IsIntNumber then
WritePropertyCommand(Name, fbpInteger, IntNumber);
except
IsIntNumber := false;
end;
if not IsIntNumber then
// Save as string
WritePropertyCommand(Name, fbpString, Value);
end;
'''':
if Line[Len] = '''' then
// String
WritePropertyCommand(Name, fbpString, copy(Line, i+1, Len-i -1))
else
raise EWriteError.Create(SWriteError);
'(':
begin
Size := SizeOf(PropData.PropType) + SizeOf(PropData.VInteger);
if Line[Len] = ')' then begin
// Write empty list
PropData.PropType := fbpStrList;
PropData.VInteger := 0; // Line count
WriteDataCommand(fbcProperty, PropData, Size, 1, Name);
end else begin
// Start collecting string list lines
with PFlexBinPropertyData(GrowWriteData(Size))^ do begin
PropType := fbpStrList;
VInteger := 0; // Line count
end;
inc(FWritePropDataPos, Size);
FWritePropName := Name;
FWritePropType := fbpStrList;
end;
end;
'{':
begin
Size := SizeOf(PropData.PropType);
if Line[Len] = '}' then begin
// Write empty hex block
PropData.PropType := fbpHexData;
WriteDataCommand(fbcProperty, PropData, Size, 1, Name);
end else begin
// Start collecting hex block lines
PFlexBinPropertyData(GrowWriteData(Size))^.PropType :=
fbpHexData;
inc(FWritePropDataPos, Size);
FWritePropName := Name;
FWritePropType := fbpHexData;
end;
end;
else
// Check TRUE
if ThisWord(Line, i, Len, BooleanWords[True]) then
WritePropertyCommand(Name, fbpBoolean, true)
else
// Check FALSE
if ThisWord(Line, i, Len, BooleanWords[False]) then
WritePropertyCommand(Name, fbpBoolean, false)
else
// Simple string or Enum name. Save as is
WritePropertyCommand(Name, fbpString, copy(Line, i, MaxInt));
end;
end;
else
// Unkonwn command
raise EWriteError.Create(SWriteError);
end;
end;
end;
end;
procedure TFlexBinaryData.SaveStrBuf(Buf: pointer; BufSize: integer);
var Start, Pos, Finish: PAnsiChar;
Delim: AnsiChar;
Len: integer;
Line: AnsiString;
i: integer;
begin
if BufSize <= 0 then exit;
Pos := PAnsiChar(Buf);
Finish := PAnsiChar(Buf) + BufSize;
repeat
Start := Pos;
while (Pos < Finish) and (Pos^ <> #$0D) and (Pos^ <> #$0A) do inc(Pos);
Len := Pos - Start;
if Len > 0 then begin
// Get line
SetLength(Line, Len);
for i:=1 to Len do Line[i] := Start[i-1];
// Parse line
SaveStr(String(Line));
end;
// Skip delims
if Pos < Finish then begin
Delim := Pos^;
inc(Pos);
if (Pos < Finish) and
((Pos^ = #$0D) or (Pos^ = #$0A)) and (Pos^ <> Delim) then
// Skip second delim
inc(Pos);
end;
until (Pos >= Finish);
end;
function TFlexBinaryData.ReadCommand: boolean;
begin
ReadCommandHeaderAndKeys(FCmdReadHeader);
Result := true;
end;
function TFlexBinaryData.ReadCommandData(out Value: Variant): integer;
var PropType: integer;
begin
if not ReadPropertyData(Value, PropType)
then Result := -1
else Result := PropType;
end;
function TFlexBinaryData.ReadCommandUserData: pointer;
begin
Result := FCmdReadUserData;
if not FCmdReadDataAhead then exit;
AllocReadData;
FOwner.ReadBuf(FCmdReadUserData^, FCmdReadUserDataSize);
FCmdReadDataAhead := false;
Result := FCmdReadUserData;
end;
// TFlexFiler ////////////////////////////////////////////////////////////////
constructor TFlexFiler.Create(AStream: TStream;
ACompleteBinary: boolean = false);
begin
inherited Create;
FStream := AStream;
FCompleteBinary := ACompleteBinary;
FBufSize := 65536; //4096;
GetMem(FBuffer, FBufSize);
try
FTotal := GetStreamSize;
FLoaded := FStream.Seek(0, soFromCurrent);
except
end;
Binary := FCompleteBinary;
end;
destructor TFlexFiler.Destroy;
begin
{try
// If was binary mode we need save fbcBinaryEnd command
Binary := false;
except
end;}
FBinaryData.Free;
if Assigned(FBuffer) then begin
FreeMem(FBuffer, FBufSize);
FBuffer := Nil;
end;
inherited;
end;
procedure TFlexFiler.ReadBuffer;
begin
FBufEnd := FStream.Read(FBuffer^, FBufSize);
//if FBufEnd = 0 then raise EReadError.CreateRes(@SReadError);
FBufPos := 0;
inc(FLoaded, FBufEnd);
end;
function TFlexFiler.ReadSkipBuf(BufSize: integer): boolean;
var Size: integer;
begin
Result := BufSize <= 0;
if Result or (FBufEnd = 0) then exit;
repeat
if FBufPos = FBufEnd then begin
ReadBuffer;
if FBufEnd = 0 then break;
end;
if FBufPos + BufSize > FBufEnd
then Size := FBufEnd - FBufPos
else Size := BufSize;
inc(FBufPos, Size);
dec(BufSize, Size);
Result := BufSize = 0;
until Result;
DoProgress(ppLoad);
end;
function TFlexFiler.ReadBufCheck(Buf: pointer; BufSize: integer): boolean;
var LoadBufPos: PAnsiChar;
Size: integer;
begin
Result := BufSize <= 0;
if Result or (FBufEnd = 0) then exit;
LoadBufPos := PAnsiChar(Buf);
repeat
if FBufPos = FBufEnd then begin
ReadBuffer;
if FBufEnd = 0 then break;
end;
if FBufPos + BufSize > FBufSize
then Size := FBufSize - FBufPos
else Size := BufSize;
Move((PAnsiChar(FBuffer) + FBufPos)^, LoadBufPos^, Size);
inc(LoadBufPos, Size);
inc(FBufPos, Size);
dec(BufSize, Size);
Result := BufSize = 0;
until Result;
DoProgress(ppLoad);
end;
procedure TFlexFiler.ReadBuf(var Buf; BufSize: integer);
begin
if not ReadBufCheck(@Buf, BufSize) then ReadError;
end;
procedure TFlexFiler.WriteBuf(const Buf; BufSize: integer);
begin
FStream.WriteBuffer(Buf, BufSize);
end;
procedure TFlexFiler.SaveStr(const s: string);
const EOLN: word = $0A0D;
{$IFDEF FG_D12}
var a: AnsiString;
{$ENDIF}
begin
if FBinary then
FBinaryData.SaveStr(s)
else begin
if Length(s) > 0 then begin
{$IFDEF FG_D12}
a := AnsiString(s);
FStream.Write(a[1], Length(a));
{$ELSE}
FStream.Write(s[1], Length(s));
{$ENDIF}
end;
FStream.Write(EOLN, SizeOf(EOLN));
end;
FLastProcess := ppSave;
end;
procedure TFlexFiler.SaveBuf(Buf: pointer; BufSize: integer);
begin
if FBinary
then FBinaryData.SaveStrBuf(Buf, BufSize)
else FStream.WriteBuffer(Buf^, BufSize);
FLastProcess := ppSave;
end;
function TFlexFiler.LoadStr: string;
begin
LoadStrCheck(Result);
end;
function TFlexFiler.LoadStrCheck(out s: string): boolean;
var StrBeg, StrEnd, Len: integer;
Delim: AnsiChar;
a: AnsiString;
begin
if FBinary then
Result := FBinaryData.LoadStrCheck(s)
else begin
a := '';
StrBeg := -1;
StrEnd := -1;
repeat
if (FBufPos = FBufEnd) then begin
ReadBuffer;
if FBufEnd = 0 then break;
StrBeg := FBufPos;
end;
if StrEnd < 0 then begin
StrBeg := FBufPos;
while (StrBeg < FBufEnd) and (PAnsiChar(FBuffer)[StrBeg] = ' ') do inc(StrBeg);
FBufPos := StrBeg;
if FBufPos = FBufEnd then continue;
end;
StrEnd := StrBeg;
while (StrEnd < FBufEnd) and (PAnsiChar(FBuffer)[StrEnd] <> #$0D) and
(PAnsiChar(FBuffer)[StrEnd] <> #$0A) do inc(StrEnd);
Delim := PAnsiChar(FBuffer)[StrEnd];
FBufPos := StrEnd;
if StrEnd > StrBeg then begin
Len := Length(a);
SetLength(a, Len + (StrEnd - StrBeg));
Move(PAnsiChar(FBuffer)[StrBeg], a[Len+1], StrEnd - StrBeg);
end;
if FBufPos = FBufEnd then continue;
inc(FBufPos);
if FBufPos = FBufEnd then begin
ReadBuffer;
if FBufEnd = 0 then break;
end;
if ((PAnsiChar(FBuffer)[FBufPos] = #$0D) or (PAnsiChar(FBuffer)[FBufPos] = #$0A)) and
(PAnsiChar(FBuffer)[FBufPos] <> Delim) then
inc(FBufPos);
break;
until false;
Result := FBufEnd > 0;
{ if Result and (FBufPos = FBufEnd) then begin
ReadBuffer;
Result := FBufEnd > 0;
end; }
s := String(a);
end;
DoProgress(ppLoad);
if not FBinary and
(Length(s) = Length(fcBinary)) and StrBeginsFrom(fcBinary, s) then
Binary := true;
end;
procedure TFlexFiler.LoadSkipToEnd;
var s: string;
Level: integer;
begin
Level := 1;
while Level > 0 do
if Binary then begin
if not BinaryData.ReadCommand then break;
case BinaryData.ReadCmdCommand of
fbcObject,
fbcComplexProperty : inc(Level);
fbcEnd : dec(Level)
end;
end else
if not LoadStrCheck(s) then
break
else
if StrBeginsFrom(s, fcEnd) then
dec(Level)
else
if StrBeginsFrom(s, fcObject) or StrBeginsFrom(s, fcProperty) then
inc(level);
end;
function TFlexFiler.CheckLoadSkipToEnd(const First: string): boolean;
begin
Result :=
StrBeginsFrom(First, fcDocument) or
StrBeginsFrom(First, fcClipboard) or
StrBeginsFrom(First, fcLibrary) or
StrBeginsFrom(First, fcObject) or
StrBeginsFrom(First, fcProperty);
if Result then LoadSkipToEnd;
end;
function TFlexFiler.IsEndOfStream: boolean;
var EndPos, Pos: Longint;
begin
Pos := FStream.Seek(0, soFromCurrent);
EndPos := FStream.Seek(0, soFromEnd);
FStream.Seek(Pos, soFromBeginning);
Result := Pos = EndPos;
end;
procedure TFlexFiler.Rewind;
begin
Binary := false;
FStream.Position := 0;
FLoaded := 0;
FSaved := 0;
FLastProcess := ppUnknown;
end;
function TFlexFiler.GetStreamSize: integer;
var Pos: integer;
begin
try
Pos := FStream.Seek(0, soFromCurrent);
Result:= FStream.Seek(0, soFromEnd);
FStream.Seek(Pos, soFromBeginning);
except
Result := 0;
end;
end;
procedure TFlexFiler.SetSaved(const Value: integer);
begin
if Value = FSaved then exit;
FSaved := Value;
DoProgress(ppSave);
end;
procedure TFlexFiler.SetTotal(const Value: integer);
begin
if Value = FTotal then exit;
FTotal := Value;
end;
procedure TFlexFiler.DoProgress(Process: TFlexFilerProcess);
var NewProgress: integer;
begin
if not Assigned(FOnProgress) or (FTotal = 0) then exit;
case Process of
ppLoad: NewProgress := Round((FLoaded - FBufEnd + FBufPos) / FTotal * 100);
ppSave: NewProgress := Round(FSaved / FTotal * 100);
else exit;
end;
FLastProcess := Process;
if NewProgress <> FProgress then begin
FProgress := NewProgress;
FOnProgress(Self, FProgress, Process);
end;
end;
procedure TFlexFiler.SetBinary(const Value: boolean);
begin
if Value = FBinary then exit;
if CompleteBinary then begin
if not Value and Assigned(FBinaryData) then FBinaryData.Reset;
exit;
end;
FBinary := Value;
if FBinary then begin
if not Assigned(FBinaryData)
then FBinaryData := TFlexBinaryData.Create(Self)
else FBinaryData.Reset;
end else
if Assigned(FBinaryData) and not FBinary and
(FBinaryData.Process = ppSave) and not FBinaryData.Finished then begin
// Save binary end command and reset
FBinaryData.WriteSimpleCommand(fbcBinaryEnd);
FBinaryData.Reset;
end;
end;
procedure TFlexFiler.ReadError(const Msg: string);
begin
if Msg <> '' then
raise EReadError.Create(Msg)
else
{$IFDEF FG_D5}
raise EReadError.CreateRes(@SReadError)
{$ELSE}
raise EReadError.Create(SReadError);
{$ENDIF}
end;
procedure TFlexFiler.WriteError(const Msg: string);
begin
if Msg <> '' then
raise EWriteError.Create(Msg)
else
{$IFDEF FG_D5}
raise EWriteError.CreateRes(@SWriteError)
{$ELSE}
raise EWriteError.Create(SWriteError);
{$ENDIF}
end;
// TIdPool ///////////////////////////////////////////////////////////////
constructor TIdPool.Create;
begin
FPool := TList.Create;
end;
destructor TIdPool.Destroy;
begin
FPool.Free;
inherited;
end;
function TIdPool.Generate: cardinal;
begin
if FPool.Count = 0 then begin
// Generate first identifier
FPool.Add(pointer(1));
FPool.Add(pointer(1));
Result := 1;
end else
if integer(FPool[0]) > 1 then begin
// The indentifier 1 is not used
if integer(FPool[0]) = 2 then begin
FPool[0] := pointer(1);
Result := 1;
end else begin
FPool.Insert(0, pointer(1));
FPool.Insert(0, pointer(1));
Result := 1;
end;
end else begin
Result := cardinal(FPool[1]);
inc(Result);
if (FPool.Count > 2) and (cardinal(FPool[2]) = Result+1) then begin
// Combine neighbor regions
FPool.Delete(2);
FPool.Delete(1);
end else
// Use identifier
FPool[1] := pointer(Result);
end;
end;
function TIdPool.GetUsed(Value: cardinal): boolean;
var Index: integer;
begin
Result := false;
if Value <= 0 then exit;
Index := ListScanLess(pointer(Value), FPool.List, FPool.Count);
Result := (Index < FPool.Count) and
((Index and 1 <> 0) or (cardinal(FPool[Index]) = Value));
end;
function TIdPool.Use(Value: cardinal): boolean;
var Index: integer;
begin
Result := false;
if Value <= 0 then exit;
Index := ListScanLess(pointer(Value), FPool.List, FPool.Count);
if Index = FPool.Count then begin
// Value greater then last used identifier or FPool is empty
if (FPool.Count > 0) and (cardinal(FPool[FPool.Count-1]) = Value-1) then
FPool[FPool.Count-1] := pointer(Value)
else begin
FPool.Add(pointer(Value));
FPool.Add(pointer(Value));
end;
Result := true;
end else
if (cardinal(FPool[Index]) <> Value) and (Index and 1 = 0) then begin
// Value is not in use
if cardinal(FPool[Index]) = Value+1 then begin
// Insert value in used region
if (Index > 0) and (cardinal(FPool[Index-1]) = Value-1) then begin
// Cancat with previous region
FPool.Delete(Index);
FPool.Delete(Index-1);
end else
// insert
FPool[Index] := pointer(Value);
end else
if (Index > 0) and (cardinal(FPool[Index-1]) = Value-1) then
// Insert value in previous region
FPool[Index-1] := pointer(Value)
else begin
// Create new region
FPool.Insert(Index, pointer(Value));
FPool.Insert(Index, pointer(Value));
end;
Result := true;
end;
end;
function TIdPool.Release(Value: cardinal): boolean;
var Index: integer;
begin
Result := false;
if Value <= 0 then exit;
Index := ListScanLess(pointer(Value), FPool.List, FPool.Count);
if Index = FPool.Count then exit; // Value not used
// Value can be in use
if cardinal(FPool[Index]) = Value then begin
// Released value is start or end of used region
if Index and 1 = 0 then begin
// It is start of region
if cardinal(FPool[Index+1]) = Value then begin
// Delete region
FPool.Delete(Index+1);
FPool.Delete(Index);
end else
// Move start of region
FPool[Index] := pointer(Value+1);
end else begin
// It is end of region
if cardinal(FPool[Index-1]) = Value then begin
// Delete region
FPool.Delete(Index);
FPool.Delete(Index-1);
end else
// Move end of region
FPool[Index] := pointer(Value-1);
end;
Result := true;
end else
if Index and 1 <> 0 then begin
// Break region
FPool.Insert(Index, pointer(Value+1));
FPool.Insert(Index, pointer(Value-1));
Result := true;
end;
end;
function TIdPool.NextUsed(Value: cardinal; var Index: integer): cardinal;
begin
Result := 0;
if Index < 0 then begin
if FPool.Count = 0 then exit;
Index := 0;
Result := cardinal(FPool[Index]);
end else
if (Index < FPool.Count-1) and (Index and 1 = 0) then begin
Result := Value + 1;
while (Index < FPool.Count-1) and (Result > cardinal(FPool[Index+1])) do
inc(Index, 2);
if Index = FPool.Count then
Result := 0
else
if Result < cardinal(FPool[Index]) then
Result := cardinal(FPool[Index]);
end;
end;
procedure TIdPool.Clear;
begin
FPool.Clear;
end;
// TNotifyLink //////////////////////////////////////////////////////////////////
constructor TNotifyLink.Create(AOwner: TObject);
begin
if not Assigned(AOwner) then raise Exception.Create('Owner must exist');
FOwner := AOwner;
FLinks := TList.Create;
end;
destructor TNotifyLink.Destroy;
begin
DestroyNotify;
FLinks.Free;
inherited;
end;
function TNotifyLink.GetLinkCount: integer;
begin
Result := FLinks.Count div 2;
end;
function TNotifyLink.GetLink(Index: integer): TNotifyLink;
begin
Result := TNotifyLink(FLinks[Index*2+1]);
end;
function TNotifyLink.GetLinkRefCount(Index: integer): integer;
begin
Result := integer(FLinks[Index*2]);
end;
function TNotifyLink.IndexOf(Link: TNotifyLink): integer;
var i: integer;
begin
Result := -1;
i := 0;
while i < FLinks.Count do
if FLinks[i+1] = Link then begin
Result := i;
break;
end else
inc(i, 2);
end;
function TNotifyLink.Notify(const Info: TNotifyLinkInfo): integer;
var i: integer;
begin
Result := 0;
if FDestroying then exit;
i := 0;
while i < FLinks.Count do with TNotifyLink(FLinks[i+1]) do begin
if (integer(Self.FLinks[i]) > 0) and Assigned(FOnNotify) and
not FDestroying then begin
try
FOnNotify(Self.FLinks[i+1], Self, Info);
except
Application.HandleException(Self);
end;
inc(Result);
end;
inc(i, 2);
end;
end;
function TNotifyLink.ControlNotify(AControl: TObject;
ANotify: TFlexNotify): integer;
var Info: TNotifyLinkInfo;
begin
Info.Code := ncControlNotify;
Info.Control := AControl;
Info.ControlNotify := ANotify;
Result := Notify(Info);
end;
function TNotifyLink.PropNotify(AProp: TObject;
IsBeforeNotify: boolean): integer;
var Info: TNotifyLinkInfo;
begin
if IsBeforeNotify
then Info.Code := ncPropBeforeChanged
else Info.Code := ncPropChanged;
Info.Prop := AProp;
Result := Notify(Info);
end;
procedure TNotifyLink.DestroyNotify;
var Index: integer;
Link: TNotifyLink;
Info: TNotifyLinkInfo;
begin
FillChar(Info, SizeOf(Info), 0);
Info.Code := ncDestroy;
if not FDestroying then begin
FDestroying := true;
if Assigned(FOnFreeNotify) then FOnFreeNotify(Self, Nil, Info);
end;
while FLinks.Count > 0 do begin
Link := TNotifyLink(FLinks[FLinks.Count-1]);
with Link do begin
Index := IndexOf(Self);
if Index >= 0 then begin
// Fully unsubscribe
if Assigned(FOnFreeNotify) then begin
try
FOnFreeNotify(Link, Self, Info);
except
Application.HandleException(Self);
end;
Index := IndexOf(Self);
end;
if Index >= 0 then begin
FLinks.Delete(Index);
FLinks.Delete(Index);
end;
end;
end;
FLinks.Count := FLinks.Count - 2;
end;
end;
function TNotifyLink.Subscribe(Link: TNotifyLink): integer;
var Index: integer;
begin
if not Assigned(Link) or FDestroying then begin
Result := -1;
exit;
end;
Index := IndexOf(Link);
if Index = -1 then begin
// New subscription
FLinks.Add(pointer(1));
FLinks.Add(Link);
Link.FLinks.Add(pointer(0));
Link.FLinks.Add(Self);
Result := 1;
end else begin
// Increase subscription count
Result := integer(FLinks[Index]) + 1;
FLinks[Index] := pointer(Result);
end;
end;
function TNotifyLink.Unsubscribe(Link: TNotifyLink): integer;
var Index, LinkIndex: integer;
begin
Result := -1;
if not Assigned(Link) or FDestroying then exit;
Index := IndexOf(Link);
if Index < 0 then exit; // Nothing unsubscribe
// Decrease subscription count
Result := integer(FLinks[Index]) - 1;
if Result < 0 then exit; // already unsubscribed
FLinks[Index] := pointer(Result);
if Result = 0 then begin
// Check fully unsubscribe
LinkIndex := Link.IndexOf(Self);
if (LinkIndex >= 0) and (integer(Link.FLinks[LinkIndex]) = 0) then begin
FLinks.Delete(Index);
FLinks.Delete(Index);
Link.FLinks.Delete(LinkIndex);
Link.FLinks.Delete(LinkIndex);
end;
end;
end;
///////////////////////////////////////////////////////////////////////////////
procedure LoadFlexCursors;
begin
Screen.Cursors[crShapeCursor] := LoadCursor(HInstance, 'SHAPE_CUR');
if Screen.Cursors[crShapeCursor] = 0 then
Screen.Cursors[crShapeCursor] := LoadCursor(HInstance, IDC_UPARROW);
Screen.Cursors[crShapeAddCursor] := LoadCursor(HInstance, 'SHAPE_ADD_CUR');
Screen.Cursors[crShapeDelCursor] := LoadCursor(HInstance, 'SHAPE_DEL_CUR');
Screen.Cursors[crShapeCloseCursor] := LoadCursor(HInstance, 'SHAPE_CLOSE_CUR');
Screen.Cursors[crShapeMoveCursor] := LoadCursor(HInstance, 'SHAPE_MOVE_CUR');
Screen.Cursors[crShapeMoveCurveCursor] := LoadCursor(HInstance, 'SHAPE_MOVE_CURVE_CUR');
Screen.Cursors[crShapeMoveLineCursor] := LoadCursor(HInstance, 'SHAPE_MOVE_LINE_CUR');
Screen.Cursors[crCreateControlCursor] := LoadCursor(HInstance, 'CREATE_CTRL_CUR');
Screen.Cursors[crCreateRectCursor] := LoadCursor(HInstance, 'CREATE_RECT_CUR');
Screen.Cursors[crCreateEllipseCursor] := LoadCursor(HInstance, 'CREATE_ELLIPSE_CUR');
Screen.Cursors[crCreateTextCursor] := LoadCursor(HInstance, 'CREATE_TEXT_CUR');
Screen.Cursors[crCreatePicCursor] := LoadCursor(HInstance, 'CREATE_PIC_CUR');
Screen.Cursors[crCreatePolyCursor] := LoadCursor(HInstance, 'CREATE_POLY_CUR');
Screen.Cursors[crZoomInCursor] := LoadCursor(HInstance, 'ZOOM_IN_CUR');
Screen.Cursors[crZoomOutCursor] := LoadCursor(HInstance, 'ZOOM_OUT_CUR');
Screen.Cursors[crPanCursor] := LoadCursor(HInstance, 'PAN_CUR');
Screen.Cursors[crPanningCursor] := LoadCursor(HInstance, 'PANNING_CUR');
Screen.Cursors[crShapeContinueCursor] :=LoadCursor(HInstance, 'CONT_POLY_CUR');
end;
///////////////////////////////////////////////////////////////////////////////
function StrBeginsFrom(const S1, S2: string): boolean; assembler;
asm
PUSH ESI
PUSH EDI
MOV ESI,EAX
MOV EDI,EDX
OR EAX,EAX
JE @@1
MOV EAX,[EAX-4]
@@1: OR EDX,EDX
JE @@2
MOV EDX,[EDX-4]
@@2: MOV ECX,EAX
CMP ECX,EDX
JBE @@3
MOV ECX,EDX
@@3: XOR EAX,EAX
CMP ECX,ECX
{$IFDEF UNICODE}
REPE CMPSW
{$ELSE}
REPE CMPSB
{$ENDIF}
JE @@4
DEC EAX
@@4: INC EAX
POP EDI
POP ESI
end;
function FlexStrNeedQuote(const s: string): boolean;
var i: integer;
begin
Result := (Length(s) > 0) and ( (s[1] = '(') or (s[1] = '{') );
if Result then exit;
for i:=1 to Length(s) do
if (s[i] <= ' ') or (s[i] = '''') then begin
Result := True;
break;
end;
end;
function ExtractWord(const s: string; NumWord: integer; Delimiter: char): string;
var i, WordBeg, WordEnd: integer;
Len: integer;
begin
Len := Length(s);
if (NumWord < 1) or (Len = 0) then begin
Result := '';
exit;
end;
WordBeg := 1;
WordEnd := Len;
for i:=1 to Len do
if s[i] = Delimiter then begin
dec(NumWord);
if NumWord = 1 then
WordBeg := i+1
else
if NumWord = 0 then begin
WordEnd := i-1;
break;
end;
end;
if NumWord <= 1
then Result := copy(s, WordBeg, WordEnd - WordBeg + 1)
else Result := '';
end;
const
HexCodes: array[0..15+7] of byte = (
0,1,2,3,4,5,6,7,8,9,0,0,0,0,0,0,0,10,11,12,13,14,15
);
function HexCharsToByte(cw: word): byte; assembler;
asm
push ebx
push edi
lea edi, HexCodes
movzx eax, ax
sub eax, 00003030h
movzx ebx, al
movzx ebx, byte ptr [edi + ebx]
shr eax, 8
movzx eax, byte ptr [edi + eax]
shl eax, 4
or eax, ebx
pop edi
pop ebx
end;
const
HexWords: array[0..255] of word = (
$3030, $3130, $3230, $3330, $3430, $3530, $3630, $3730,
$3830, $3930, $4130, $4230, $4330, $4430, $4530, $4630,
$3031, $3131, $3231, $3331, $3431, $3531, $3631, $3731,
$3831, $3931, $4131, $4231, $4331, $4431, $4531, $4631,
$3032, $3132, $3232, $3332, $3432, $3532, $3632, $3732,
$3832, $3932, $4132, $4232, $4332, $4432, $4532, $4632,
$3033, $3133, $3233, $3333, $3433, $3533, $3633, $3733,
$3833, $3933, $4133, $4233, $4333, $4433, $4533, $4633,
$3034, $3134, $3234, $3334, $3434, $3534, $3634, $3734,
$3834, $3934, $4134, $4234, $4334, $4434, $4534, $4634,
$3035, $3135, $3235, $3335, $3435, $3535, $3635, $3735,
$3835, $3935, $4135, $4235, $4335, $4435, $4535, $4635,
$3036, $3136, $3236, $3336, $3436, $3536, $3636, $3736,
$3836, $3936, $4136, $4236, $4336, $4436, $4536, $4636,
$3037, $3137, $3237, $3337, $3437, $3537, $3637, $3737,
$3837, $3937, $4137, $4237, $4337, $4437, $4537, $4637,
$3038, $3138, $3238, $3338, $3438, $3538, $3638, $3738,
$3838, $3938, $4138, $4238, $4338, $4438, $4538, $4638,
$3039, $3139, $3239, $3339, $3439, $3539, $3639, $3739,
$3839, $3939, $4139, $4239, $4339, $4439, $4539, $4639,
$3041, $3141, $3241, $3341, $3441, $3541, $3641, $3741,
$3841, $3941, $4141, $4241, $4341, $4441, $4541, $4641,
$3042, $3142, $3242, $3342, $3442, $3542, $3642, $3742,
$3842, $3942, $4142, $4242, $4342, $4442, $4542, $4642,
$3043, $3143, $3243, $3343, $3443, $3543, $3643, $3743,
$3843, $3943, $4143, $4243, $4343, $4443, $4543, $4643,
$3044, $3144, $3244, $3344, $3444, $3544, $3644, $3744,
$3844, $3944, $4144, $4244, $4344, $4444, $4544, $4644,
$3045, $3145, $3245, $3345, $3445, $3545, $3645, $3745,
$3845, $3945, $4145, $4245, $4345, $4445, $4545, $4645,
$3046, $3146, $3246, $3346, $3446, $3546, $3646, $3746,
$3846, $3946, $4146, $4246, $4346, $4446, $4546, $4646
);
function ByteToHexChars(b: byte): word; assembler;
asm
movzx eax, al
movzx eax, word ptr [HexWords + eax*2]
end;
{$IFNDEF FG_D12}
function RectWidth(const ARect: TRect): integer; assembler;
asm
PUSH [EAX].TRect.Left
MOV EAX, [EAX].TRect.Right
SUB EAX, [ESP]
ADD ESP, 4
end;
function RectHeight(const ARect: TRect): integer; assembler;
asm
PUSH [EAX].TRect.Top
MOV EAX, [EAX].TRect.Bottom
SUB EAX, [ESP]
ADD ESP, 4
end;
{$ENDIF}
{ TDummyPicture }
type
TDummyPicture = class(TPicture)
public
procedure CallFiler(Filer: TFiler);
end;
procedure TDummyPicture.CallFiler(Filer: TFiler);
begin
DefineProperties(Filer);
end;
{ TDummyFiler }
type
TDummyFiler = class(TFiler)
public
ReadProc, WriteProc: TStreamProc;
procedure DefineProperty(const Name: string;
ReadData: TReaderProc; WriteData: TWriterProc;
HasData: Boolean); override;
procedure DefineBinaryProperty(const Name: string;
ReadData, WriteData: TStreamProc;
HasData: Boolean); override;
procedure FlushBuffer; override;
end;
procedure TDummyFiler.DefineBinaryProperty(const Name: string; ReadData,
WriteData: TStreamProc; HasData: Boolean);
begin
ReadProc := ReadData;
WriteProc := WriteData;
end;
procedure TDummyFiler.FlushBuffer; begin end;
procedure TDummyFiler.DefineProperty(const Name: string;
ReadData: TReaderProc; WriteData: TWriterProc; HasData: Boolean); begin end;
procedure GetPicReadWrite(Picture: TPicture;
out ReadProc, WriteProc: TStreamProc);
var Filer: TDummyFiler;
begin
Filer := TDummyFiler.Create(Nil, 0);
try
TDummyPicture(Picture).CallFiler(Filer);
ReadProc := Filer.ReadProc;
WriteProc := Filer.WriteProc;
finally
Filer.Free;
end;
end;
///////////////////////////////////////////////////////////////////////////////
function NormalizeRect(const R: TRect): TRect;
begin
if R.Left > R.Right then begin
Result.Left := R.Right;
Result.Right := R.Left;
end else begin
Result.Left := R.Left;
Result.Right := R.Right;
end;
if R.Top > R.Bottom then begin
Result.Top := R.Bottom;
Result.Bottom := R.Top;
end else begin
Result.Top := R.Top;
Result.Bottom := R.Bottom;
end;
end;
function PointInRect(const p: TPoint; const R: TRect): boolean;
begin
Result := (p.X >= R.Left) and (p.X <= R.Right) and
(p.Y >= R.Top) and (p.Y <= R.Bottom);
end;
///////////////////////////////////////////////////////////////////////////////
function IntersectClipRgn(ACanvas: TCanvas; ClipRgn: HRGN): HRGN;
begin
Result := CreateRectRgn(0, 0, 1, 1);
try
if GetClipRgn(ACanvas.Handle, Result) <> 1 then begin
DeleteObject(Result);
Result := 0;
SelectClipRgn(ACanvas.Handle, ClipRgn);
end else
ExtSelectClipRgn(ACanvas.Handle, ClipRgn, RGN_AND);
except
DeleteObject(Result);
raise;
end;
end;
function IntersectClipPath(DC: HDC): HRGN;
begin
Result := CreateRectRgn(0, 0, 1, 1);
try
if GetClipRgn(DC, Result) <> 1 then begin
DeleteObject(Result);
Result := 0;
if not SelectClipPath(DC, RGN_COPY) then begin
// Path error. Mask all output
Result := CreateRectRgn(0, 0, 0, 0);
SelectClipRgn(DC, Result);
DeleteObject(Result);
Result := 0;
end;
end else
SelectClipPath(DC, RGN_AND);
except
DeleteObject(Result);
raise;
end;
end;
{$IFNDEF FG_CBUILDER}
{$IFNDEF FG_D4}
{$DEFINE USE_SYS_GRADIENT}
{$ENDIF}
{$ENDIF}
{$IFDEF USE_SYS_GRADIENT}
function SysPaintGradient(DC: HDC; ARect: TRect; Style: TGradientStyle;
Color, EndColor: TColor): boolean;
type
PWinTriVertex = ^TWinTriVertex;
TWinTriVertex = {TTriVertex;} packed record
x: Longint;
y: Longint;
Red: word;
Green: word;
Blue: word;
Alpha: word;
end;
PVertexArray = ^TVertexArray;
TVertexArray = array[0..MaxInt div SizeOf(TWinTriVertex) -1] of TWinTriVertex;
PIntArray = ^TIntArray;
TIntArray = array[0..MaxInt div SizeOf(Integer) -1] of integer;
const
HVMesh: array[0..5] of cardinal = ( 0, 1, 2, 0, 1, 3 );
CenterMesh: array[0..11] of cardinal = (0, 1, 4, 1, 2, 4, 2, 3, 4, 3, 0, 4);
Mode: array[TGradientStyle] of cardinal = (
GRADIENT_FILL_RECT_H, GRADIENT_FILL_RECT_V,
GRADIENT_FILL_TRIANGLE, GRADIENT_FILL_TRIANGLE,
GRADIENT_FILL_TRIANGLE, GRADIENT_FILL_TRIANGLE,
GRADIENT_FILL_TRIANGLE, GRADIENT_FILL_TRIANGLE );
var
Vertex: PVertexArray;
CornerMesh: array[0..5] of cardinal;
Index: integer;
procedure SetVertexCount(Count: integer);
begin
if Assigned(Vertex)
then ReallocMem(Vertex, Count * SizeOf(Vertex[0]))
else GetMem(Vertex, Count * SizeOf(Vertex[0]));
end;
procedure SetVertex(Index, x, y: integer; Color: TColor);
begin
Vertex[Index].x := x;
Vertex[Index].y := y;
with Vertex[Index] do begin
Red := GetRValue(Color) shl 8;
Green := GetGValue(Color) shl 8;
Blue := GetBValue(Color) shl 8;
Alpha := 0;
end;
end;
begin
Result := false;
Vertex := Nil;
try
// Try using WinAPI GradientFill
case Style of
gsVertical,
gsHorizontal:
begin
SetVertexCount(2);
SetVertex(0, ARect.Left, ARect.Top, Color);
SetVertex(1, ARect.Right, ARect.Bottom, EndColor);
Result := GradientFill(DC, PTriVertex(Vertex), 2, @HVMesh[0], 2,
Mode[Style]);
end;
gsSquare:
begin
SetVertexCount(5);
with ARect do begin
SetVertex(0, Left, Top, Color);
SetVertex(1, Right, Top, Color);
SetVertex(2, Right, Bottom, Color);
SetVertex(3, Left, Bottom, Color);
SetVertex(4, (Left+Right) div 2, (Top+Bottom) div 2, EndColor);
end;
Result := GradientFill(DC, PTriVertex(Vertex), 5, @CenterMesh[0], 4,
Mode[Style]);
end;
gsElliptic:
begin
// Not implemented
end;
gsTopLeft,
gsTopRight,
gsBottomLeft,
gsBottomRight:
begin
SetVertexCount(4);
with ARect do begin
SetVertex(0, Left, Top, EndColor);
SetVertex(1, Right, Top, EndColor);
SetVertex(2, Right, Bottom, EndColor);
SetVertex(3, Left, Bottom, EndColor);
end;
Index := 0;
case Style of
gsTopLeft : Index := 0;
gsTopRight : Index := 1;
gsBottomLeft : Index := 3;
gsBottomRight : Index := 2;
end;
with Vertex[Index] do SetVertex(Index, x, y, Color);
CornerMesh[0] := Index;
CornerMesh[1] := (Index + 1) mod 4;
CornerMesh[2] := (Index + 2) mod 4;
CornerMesh[3] := Index;
CornerMesh[4] := (Index + 3) mod 4;
CornerMesh[5] := (Index + 2) mod 4;
Result := GradientFill(DC, PTriVertex(Vertex), 4, @CornerMesh[0], 2,
Mode[Style]);
end;
end;
finally
if Assigned(Vertex) then FreeMem(Vertex);
end;
end;
{$ENDIF}
procedure PaintGradient(ACanvas: TCanvas; ARect: TRect; Style: TGradientStyle;
Color, EndColor: TColor; PenMode: TPenMode);
var i, W, H, x, y, MaxWH: integer;
AColor: TColor;
Start: TRect;
DeltaR, DeltaG, DeltaB: integer;
StartR, StartG, StartB: integer;
MaxDelta: integer;
OldPenMode: TPenMode;
{$IFDEF USE_SYS_GRADIENT} DC: HDC; {$ENDIF}
begin
if IsRectEmpty(ARect) then exit;
W := ARect.Right - ARect.Left;
H := ARect.Bottom - ARect.Top;
if W > H
then MaxWH := W
else MaxWH := H;
Color := ColorToRGB(Color);
EndColor := ColorToRGB(EndColor);
if not SysGradientChecked or SysGradientEnabled then begin
{$IFDEF USE_SYS_GRADIENT}
OldPenMode := ACanvas.Pen.Mode;
ACanvas.Pen.Style := psClear;
ACanvas.Pen.Mode := PenMode;
DC := ACanvas.Handle;
SysGradientEnabled := SysPaintGradient(DC, ARect, Style, Color, EndColor);
ACanvas.Pen.Mode := OldPenMode;
SysGradientChecked := true;
if SysGradientEnabled then exit;
{$ENDIF}
end;
if Style in [gsTopLeft..gsBottomRight] then begin
AColor := Color;
Color := EndColor;
EndColor := AColor;
end;
StartR := GetRValue(Color);
StartG := GetGValue(Color);
StartB := GetBValue(Color);
DeltaR := GetRValue(EndColor) - StartR;
DeltaG := GetGValue(EndColor) - StartG;
DeltaB := GetBValue(EndColor) - StartB;
if Abs(DeltaR) > Abs(DeltaG)
then MaxDelta := Abs(DeltaR)
else MaxDelta := Abs(DeltaG);
if MaxDelta < Abs(DeltaB) then MaxDelta := Abs(DeltaB);
if MaxDelta < 1 then MaxDelta := 1;
case Style of
gsHorizontal : if MaxDelta > W then MaxDelta := W;
gsVertical : if MaxDelta > H then MaxDelta := H;
gsSquare,
gsElliptic : if MaxDelta > MaxWH div 2 then MaxDelta := MaxWH div 2;
gsTopLeft,
gsTopRight,
gsBottomLeft,
gsBottomRight : if MaxDelta > MaxWH then MaxDelta := MaxWH;
end;
case Style of
gsHorizontal,
gsVertical : Start := Rect(0, 0, W, H);
gsSquare,
gsElliptic : Start := Rect(W div 2, H div 2, W div 2, H div 2);
gsTopLeft : Start := Rect(0, 0, 1, 1);
gsTopRight : Start := Rect(W, 1, W+1, 0);
gsBottomLeft : Start := Rect(1, H, 0, H+1);
gsBottomRight : Start := Rect(W, H, W+1, H+1);
end;
OffsetRect(Start, ARect.Left, ARect.Top);
with ACanvas do begin
OldPenMode := Pen.Mode;
Brush.Style := bsSolid;
Pen.Style := psClear;
Pen.Mode := PenMode;
//dec(MaxDelta);
for i := 0 to MaxDelta-1 do with Start do begin
if MaxDelta > 1 then
Brush.Color :=
RGB( StartR + i * DeltaR div (MaxDelta-1),
StartG + i * DeltaG div (MaxDelta-1),
StartB + i * DeltaB div (MaxDelta-1) )
else
Brush.Color := Color;
case Style of
gsHorizontal:
begin
Rectangle(
Left + MulDiv(i, W, MaxDelta), Top,
Left + MulDiv(i+1, W, MaxDelta) +1, Bottom +1 );
end;
gsVertical:
begin
Rectangle(
Left, Top + MulDiv(i, H, MaxDelta),
Right +1, Top + MulDiv(i+1, H, MaxDelta) +1 );
end;
gsSquare:
begin
x := MulDiv((MaxDelta-i), W, MaxDelta) div 2;
y := MulDiv((MaxDelta-i), H, MaxDelta) div 2;
Rectangle(Left - x, Top - y, Left + x +2, Top + y +2);
end;
gsElliptic:
begin
x := Round(MulDiv((MaxDelta-i), W, MaxDelta) / 1.4);
y := Round(MulDiv((MaxDelta-i), H, MaxDelta) / 1.4);
Ellipse(Left - x, Top - y, Left + x, Top + y);
end;
gsTopLeft..gsBottomRight:
begin
x := MulDiv((MaxDelta-i), W, MaxDelta);
y := MulDiv((MaxDelta-i), H, MaxDelta);
case Style of
gsTopLeft : Rectangle(Left, Top, Right + x, Bottom + y);
gsTopRight : Rectangle(Left - x, Top + y, Right, Bottom);
gsBottomLeft : Rectangle(Left + x, Top - y, Right, Bottom);
gsBottomRight : Rectangle(Left - x, Top - y, Right, Bottom);
end;
end;
end;
end;
Pen.Mode := OldPenMode;
end;
end;
function CreateTransparentClipRgn(DC: HDC; Width, Height: integer;
var Dest: TRect; TransparentColor: TColor): HRGN;
type
PRects = ^TRects;
TRects = array[0..MaxInt div SizeOf(TRect) -1] of TRect;
var VisibleRgn, TempRgn: HRGN;
TranspColor: TColorRef;
i, x, y, Start: integer;
RgnData: PRgnData;
RgnSize: integer;
RgnRects: PRects;
CoeffX, CoeffY: extended;
begin
Result := 0;
if (Width = 0) or (Height = 0) then exit;
// Create visible region
VisibleRgn := 0;
TranspColor := ColorToRGB(TransparentColor) and $00FFFFFF;
for y:=0 to Height-1 do begin
x := 0;
repeat
// Skip transparent pixels
while (x < Width) and (GetPixel(DC, x, y) = TranspColor) do inc(x);
if x = Width then break;
// Start visible pixels
Start := x;
// Find next first transparent pixel
while (x < Width) and (GetPixel(DC, x, y) <> TranspColor) do inc(x);
// Include visible pixels in VisibleRgn
TempRgn := CreateRectRgn(Start, y, x, y+1);
if VisibleRgn = 0 then
VisibleRgn := TempRgn
else begin
CombineRgn(VisibleRgn, VisibleRgn, TempRgn, RGN_OR);
DeleteObject(TempRgn);
end;
until x = Width;
end;
if VisibleRgn = 0 then exit;
if (Dest.Right - Dest.Left <> Width) or
(Dest.Bottom - Dest.Top <> Height) then begin
// Calc scale coeffs
CoeffX := RectWidth(Dest) / Width;
CoeffY := RectHeight(Dest) / Height;
// Scale VisibleRgn
RgnSize := GetRegionData(VisibleRgn, 0, Nil);
GetMem(RgnData, RgnSize);
try
GetRegionData(VisibleRgn, RgnSize, RgnData);
// Get rects pointer
RgnRects := @RgnData.Buffer;
// Scale rects
for i:=0 to RgnData.rdh.nCount-1 do with RgnRects[i] do begin
Left := Round(Left * CoeffX);
Top := Round(Top * CoeffY);
Right := Round((Right{-1}) * CoeffX) {+1};
Bottom := Round((Bottom{-1}) * CoeffY) {+1};
end;
// Create new scaled region
DeleteObject(VisibleRgn);
VisibleRgn := ExtCreateRegion(Nil, RgnSize, RgnData^);
finally
FreeMem(RgnData);
end;
end;
// Offset region
OffsetRgn(VisibleRgn, Dest.Left, Dest.Top);
Result := VisibleRgn;
end;
procedure ExcludeBitmapTransparency(Bmp: TBitmap; var R: TRect;
var ClipRgn: HRGN);
var NewRgn: HRGN;
begin
NewRgn := CreateTransparentClipRgn(Bmp.Canvas.Handle, Bmp.Width, Bmp.Height,
R, Bmp.TransparentColor);
if NewRgn = 0 then exit;
CombineRgn(ClipRgn, ClipRgn, NewRgn, RGN_AND);
DeleteObject(NewRgn);
end;
procedure PaintTailed(ACanvas: TCanvas; const PaintRect, RefreshRect: TRect;
ABitmap: TBitmap; BitmapCache: PTiledBitmapCache = Nil);
begin
PaintBitmap(ACanvas, PaintRect, RefreshRect, ABitmap, bdTile, BitmapCache);
end;
procedure PaintBitmap(ACanvas: TCanvas; const PaintRect, RefreshRect: TRect;
ABitmap: TBitmap; BitmapDisplay: TBitmapDisplay;
BitmapCache: PTiledBitmapCache = Nil; Scale: integer = 100;
ClipTransparent: boolean = false);
var W, H: integer;
Pos, RSize, BSize: TPoint;
R: TRect;
MemDC, CanvasDC, BmpDC: HDC;
MemBmp, MemSavedBmp: HBitmap;
MaskDC: HDC;
MaskBmp, MaskSavedBmp: HBitmap;
IsMasked, BuildBmp: boolean;
MaskedColor: TColor;
PrevRgn, ClipRgn: HRGN;
begin
IntersectRect(R, PaintRect, RefreshRect);
if not Assigned(ABitmap) or IsRectEmpty(R) or ABitmap.Empty then exit;
W := ABitmap.Width;
H := ABitmap.Height;
if (W = 0) or (H = 0) then exit;
PrevRgn := 0;
IsMasked := ABitmap.Transparent;
MaskedColor := ColorToRGB(ABitmap.TransparentColor);
case BitmapDisplay of
bdStretch,
bdCenter:
begin
if BitmapDisplay = bdStretch then
R := PaintRect
else begin
R.Right := MulDiv(W, Scale, 100);
R.Bottom := MulDiv(H, Scale, 100);
R.Left := (PaintRect.Left + PaintRect.Right - R.Right) div 2;
R.Top := (PaintRect.Top + PaintRect.Bottom - R.Bottom) div 2;
inc(R.Right, R.Left);
inc(R.Bottom, R.Top);
end;
if ClipTransparent and IsMasked then begin
{ ClipRgn := CreateRectRgnIndirect(R);
ExcludeBitmapTransparency(ABitmap, R, ClipRgn);
PrevRgn := IntersectClipRgn(ACanvas, ClipRgn);
ACanvas.StretchDraw(R, ABitmap);
SelectClipRgn(ACanvas.Handle, PrevRgn);
DeleteObject(PrevRgn);
DeleteObject(ClipRgn); }
// Create transparent clipping region for bitmap
CanvasDC := ACanvas.Handle;
BmpDC := ABitmap.Canvas.Handle;
ClipRgn := CreateTransparentClipRgn(BmpDC, W, H, R, MaskedColor);
try
// Select ClipRgn in CanvasDC
if ClipRgn <> 0 then begin
PrevRgn := CreateRectRgn(0, 0, 1, 1);
if GetClipRgn(CanvasDC, PrevRgn) <> 1 then begin
DeleteObject(PrevRgn);
PrevRgn := 0;
SelectClipRgn(CanvasDC, ClipRgn);
end else
ExtSelectClipRgn(CanvasDC, ClipRgn, RGN_AND);
end else
PrevRgn := 0;
// Draw
StretchBlt(CanvasDC, R.Left, R.Top, R.Right - R.Left, R.Bottom - R.Top,
BmpDC, 0, 0, W, H, SRCCOPY);
finally
// Restore clipping region
if ClipRgn <> 0 then begin
SelectObject(CanvasDC, PrevRgn);
DeleteObject(PrevRgn);
DeleteObject(ClipRgn);
end;
end;
end else
ACanvas.StretchDraw(R, ABitmap);
end;
bdTile:
begin
RSize.X := RectWidth(R);
RSize.Y := RectHeight(R);
Pos.X := (R.Left - PaintRect.Left) mod W;
Pos.Y := (R.Top - PaintRect.Top) mod H;
BSize.X := Pos.X + RSize.X;
BSize.Y := Pos.Y + RSize.Y;
CanvasDC := ACanvas.Handle;
MemDC := 0;
MemBmp := 0;
MemSavedBmp := 0;
try
{MemDC := CreateCompatibleDC(CanvasDC);
MemBmp := CreateCompatibleBitmap(CanvasDC, BSize.X, BSize.Y); }
BmpDC := ABitmap.Canvas.Handle;
MemDC := CreateCompatibleDC(BmpDC);
if not Assigned(BitmapCache) then begin
MemBmp := 0;
BuildBmp := true;
end else begin
// Try use cached bitmap
BuildBmp :=
(BitmapCache.Width < BSize.X) or
(BitmapCache.Height < BSize.Y);
if BuildBmp and (BitmapCache.Handle <> 0) then begin
// Need recreate bitmap
DeleteObject(BitmapCache.Handle);
MemBmp := 0;
end else
// Use cached bitmap
MemBmp := BitmapCache.Handle;
end;
// Check building tiled bitmap
if BuildBmp then begin
// Create bitmap if needed
if MemBmp = 0 then begin
MemBmp := CreateCompatibleBitmap(BmpDC, BSize.X, BSize.Y);
if Assigned(BitmapCache) then with BitmapCache^ do begin
// Store created bitmap in cache
Handle := MemBmp;
Width := BSize.X;
Height := BSize.Y;
end;
end;
// Select bitmap
MemSavedBmp := SelectObject(MemDC, MemBmp);
// Create tiled bitmap
BitBlt(MemDC, 0, 0, W, H, ABitmap.Canvas.Handle, 0, 0, SRCCOPY);
while H < BSize.Y do begin
if 2*H > BSize.Y
then BitBlt(MemDC, 0, H, W, BSize.Y - H, MemDC, 0, 0, SRCCOPY)
else BitBlt(MemDC, 0, H, W, H, MemDC, 0, 0, SRCCOPY);
inc(H, H);
end;
while W < BSize.X do begin
if 2*W > BSize.X
then BitBlt(MemDC, W, 0, BSize.X - W, BSize.Y, MemDC, 0, 0, SRCCOPY)
else BitBlt(MemDC, W, 0, W, BSize.Y, MemDC, 0, 0, SRCCOPY);
inc(W, W);
end;
end else
// Select bitmap
MemSavedBmp := SelectObject(MemDC, MemBmp);
// Draw tailed bitmap
if IsMasked then begin
if ClipTransparent then begin
// Draw bitmap with transparent clipping region
R.Right := R.Left + RSize.X;
R.Bottom := R.Top + RSize.Y;
// Create transparent clipping region for bitmap
ClipRgn := CreateTransparentClipRgn(MemDC, RSize.X, RSize.Y,
R, MaskedColor);
try
// Select ClipRgn in CanvasDC
if ClipRgn <> 0 then begin
PrevRgn := CreateRectRgn(0, 0, 1, 1);
if GetClipRgn(CanvasDC, PrevRgn) <> 1 then begin
DeleteObject(PrevRgn);
PrevRgn := 0;
SelectClipRgn(CanvasDC, ClipRgn);
end else
ExtSelectClipRgn(CanvasDC, ClipRgn, RGN_AND);
end else
PrevRgn := 0;
// Draw
BitBlt(CanvasDC, R.Left, R.Top, RSize.X, RSize.Y,
MemDC, Pos.X, Pos.Y, SRCCOPY);
finally
// Restore clipping region
if ClipRgn <> 0 then begin
SelectObject(CanvasDC, PrevRgn);
DeleteObject(PrevRgn);
DeleteObject(ClipRgn);
end;
end;
end else begin
// Draw bitmap with transparency
MaskDC := 0;
MaskBmp := 0;
MaskSavedBmp := 0;
try
MaskDC := CreateCompatibleDC(0);
MaskBmp := CreateBitmap(RSize.X, RSize.Y, 1, 1, Nil);
MaskSavedBmp := SelectObject(MaskDC, MaskBmp);
SelectObject(MaskDC, MaskBmp);
SetTextColor(MemDC, clWhite);
SetBkColor(MemDC, MaskedColor);
BitBlt(MaskDC, 0, 0, RSize.X, RSize.Y, MemDC, Pos.X, Pos.Y, SRCCOPY);
TransparentStretchBlt(CanvasDC, R.Left, R.Top, RSize.X, RSize.Y,
MemDC, Pos.X, Pos.Y, RSize.X, RSize.Y, MaskDC, 0, 0);
finally
SelectObject(MaskDC, MaskSavedBmp);
DeleteObject(MaskDC);
{ ///// DEBUG /////
with TBitmap.Create do begin
Handle := MaskBmp;
SaveToFile('d:\testmask.bmp');
free;
end;
{ ///////////////// }
DeleteObject(MaskBmp);
end;
end;
end else
// Draw bitmap as is
BitBlt(CanvasDC, R.Left, R.Top, RSize.X, RSize.Y,
MemDC, Pos.X, Pos.Y, SRCCOPY);
// Reset MemBmp if it use in BitmapCache
if Assigned(BitmapCache) then MemBmp := 0;
finally
if MemSavedBmp <> 0 then SelectObject(MemDC, MemSavedBmp);
if MemBmp <> 0 then DeleteObject(MemBmp);
DeleteDC(MemDC);
end;
end;
end;
end;
// Scaling routines ///////////////////////////////////////////////////////////
function ScaleValue(Value, Scale: integer): integer;
begin
Result := MulDiv(Value, Scale, 100 * PixelScaleFactor);
end;
function UnScaleValue(Value, Scale: integer): integer;
begin
Result := MulDiv(Value, 100 * PixelScaleFactor, Scale);
end;
function ScalePixels(Value: integer): integer;
begin
Result := Value * PixelScaleFactor;
end;
function UnScalePixels(Value: integer): integer;
begin
Result := Value div PixelScaleFactor;
end;
// List scan routines /////////////////////////////////////////////////////////
function ListScan(Value, List: Pointer; Count: integer): integer; assembler;
asm
PUSH EDI
MOV EDI,EDX
OR EDI,EDI
JE @@2
REPNE SCASD
JE @@1
MOV EDI,EDX
@@1: SUB EDI,EDX
SHR EDI,2
@@2: MOV EAX,EDI
DEC EAX
POP EDI
end;
function ListScanEx(Value, List: Pointer; Index, Count: integer): integer;
begin
if Index >= Count then
Result := -1
else begin
List := PAnsiChar(List) + Index * SizeOf(pointer);
dec(Count, Index);
Result := ListScan(Value, List, Count);
if Result >= 0 then inc(Result, Index);
end;
end;
function ListScanLess(Value, List: Pointer; Count: integer): integer; assembler;
asm
PUSH EDI
MOV EDI,EDX
OR EDI,EDI
JE @@2
OR ECX,ECX
JLE @@2
@@1: SCASD
JLE @@3
LOOP @@1
@@2: ADD EDI,4
@@3: SUB EDI,EDX
SHR EDI,2
MOV EAX,EDI
DEC EAX
POP EDI
end;
function SortedListFind(List: PPointerList; Count: integer; Item: Pointer;
Compare: TSortedListCompare; Exact: boolean): integer;
var L, H, I, C: Integer;
Found: boolean;
begin
Found := False;
L := 0;
H := Count - 1;
while L <= H do begin
I := (L + H) shr 1;
C := Compare(List^[I], Item);
if C > 0 then
L := I + 1
else begin
H := I - 1;
if C = 0 then begin
Found := True;
// L := I;
end;
end;
end;
if Found or not Exact
then Result := L
else Result := -1;
end;
function ListSortItem(List: PPointerList; Count: integer; ItemIndex: integer;
Compare: TSortedListCompare): integer;
var Item: pointer;
L, H, I, II, C: Integer;
begin
Result := -1;
if (ItemIndex < 0) or (ItemIndex >= Count) then exit;
Item := List^[ItemIndex];
L := 0;
H := Count - 2;
while L <= H do begin
I := (L + H) shr 1;
II := I;
if I >= ItemIndex then inc(II);
C := Compare(List^[II], Item);
if C > 0 then
L := I + 1
else
H := I - 1;
end;
Result := L;
end;
procedure ListQuickSort(List: PPointerList; L, R: Integer;
Compare: TSortedListCompare);
var
I, J: Integer;
P, T: Pointer;
begin
repeat
I := L;
J := R;
P := List^[(L + R) shr 1];
repeat
while Compare(List^[I], P) < 0 do Inc(I);
while Compare(List^[J], P) > 0 do Dec(J);
if I <= J then begin
T := List^[I];
List^[I] := List^[J];
List^[J] := T;
Inc(I);
Dec(J);
end;
until I > J;
if L < J then ListQuickSort(List, L, J, Compare);
L := I;
until I >= R;
end;
function IsClassParent(AClass, AParentClass: TClass): boolean;
begin
Result := false;
while Assigned(AClass) do
if AClass = AParentClass then begin
Result := true;
break;
end else
AClass := AClass.ClassParent;
end;
function DotFloatToStr(const Value: extended): string;
var i: integer;
begin
Result := FloatToStr(Value);
if FormatSettings.DecimalSeparator <> '.' then
for i:=1 to Length(Result) do
if Result[i] = FormatSettings.DecimalSeparator then begin
Result[i] := '.';
break;
end;
end;
function DotStrToFloat(Value: string): extended;
var i: integer;
begin
if FormatSettings.DecimalSeparator <> '.' then
for i:=1 to Length(Value) do
if Value[i] = '.' then begin
Value[i] := FormatSettings.DecimalSeparator;
break;
end;
Result := StrToFloat(Value);
end;
{$IFNDEF FG_D5} ///////////////////////////////////////////////////////////////
procedure FreeAndNil(var Obj);
var
P: TObject;
begin
P := TObject(Obj);
TObject(Obj) := nil; // clear the reference before destroying the object
P.Free;
end;
type
{ Set access to an integer }
TIntegerSet = set of 0..SizeOf(Integer) * 8 - 1;
EPropertyError = class(Exception);
EPropertyConvertError = class(Exception);
function GetSetProp(Instance: TObject; PropInfo: PPropInfo;
Brackets: Boolean): string;
var
S: TIntegerSet;
TypeInfo: PTypeInfo;
I: Integer;
begin
Integer(S) := GetOrdProp(Instance, PropInfo);
TypeInfo := GetTypeData(PropInfo^.PropType^)^.CompType^;
for I := 0 to SizeOf(Integer) * 8 - 1 do
if I in S then
begin
if Result <> '' then
Result := Result + ',';
Result := Result + GetEnumName(TypeInfo, I);
end;
if Brackets then
Result := '[' + Result + ']';
end;
procedure SetSetProp(Instance: TObject; PropInfo: PPropInfo;
const Value: string);
var
Left, EnumName: string;
Data, EnumValue: Longint;
EnumInfo: PTypeInfo;
// grab the next enum name
function NextWord: string;
begin
Result := '';
// while we are still dealing with non-whitespace
while not (Left[1] in [',', ' ']) do
begin
Result := Result + Left[1];
Delete(Left, 1, 1);
if Left = '' then
Exit;
end;
// skip any whitespace
while Left[1] in [',', ' '] do
Delete(Left, 1, 1);
end;
begin
// bracket reduction
Left := Value;
if Left[1] = '[' then
Delete(Left, 1, 1);
if Left[Length(Left)] = ']' then
Delete(Left, Length(Left), 1);
// loop it dude!
EnumInfo := GetTypeData(PropInfo^.PropType^)^.CompType^;
Data := 0;
while Left <> '' do
begin
EnumName := NextWord;
if EnumName = '' then
Break;
EnumValue := GetEnumValue(EnumInfo, EnumName);
if EnumValue < 0 then
raise EPropertyConvertError.CreateFmt('Invalid property element: %s', [EnumName]);
Include(TIntegerSet(Data), EnumValue);
end;
SetOrdProp(Instance, PropInfo, Data);
end;
procedure SetEnumProp(Instance: TObject; PropInfo: PPropInfo;
const Value: string);
var
Data: Longint;
begin
Data := GetEnumValue(PropInfo^.PropType^, Value);
if Data < 0 then
raise EPropertyConvertError.CreateFmt('Invalid property element: %s', [Value]);
SetOrdProp(Instance, PropInfo, Data);
end;
function GetPropValue(Instance: TObject; const PropName: string;
PreferStrings: Boolean): Variant;
var
PropInfo: PPropInfo;
TypeData: PTypeData;
begin
// assume failure
Result := Null;
// get the prop info
PropInfo := GetPropInfo(PTypeInfo(Instance.ClassType.ClassInfo), PropName);
if PropInfo <> nil then
begin
TypeData := GetTypeData(PropInfo^.PropType^);
// return the right type
case PropInfo^.PropType^^.Kind of
tkInteger, tkChar, tkWChar, tkClass:
Result := GetOrdProp(Instance, PropInfo);
tkEnumeration:
if PreferStrings then
Result := GetEnumName(PropInfo^.PropType^, GetOrdProp(Instance, PropInfo))
else if TypeData^.BaseType^ = TypeInfo(Boolean) then
Result := Boolean(GetOrdProp(Instance, PropInfo))
else
Result := GetOrdProp(Instance, PropInfo);
tkSet:
if PreferStrings then
Result := GetSetProp(Instance, PropInfo, False)
else
Result := GetOrdProp(Instance, PropInfo);
tkFloat:
{begin}
Result := GetFloatProp(Instance, PropInfo);
{if not SimpleConvert and
(TypeData^.BaseType^ = TypeInfo(TDateTime)) then
Result := VarAsType(Result, varDate);
end;}
tkMethod:
Result := PropInfo^.PropType^.Name;
tkString, tkLString, tkWString:
Result := GetStrProp(Instance, PropInfo);
tkVariant:
Result := GetVariantProp(Instance, PropInfo);
tkInt64:
Result := GetInt64Prop(Instance, PropInfo) + 0.0;
else
raise EPropertyConvertError.CreateFmt('Invalid property type: %s',
[PropInfo.PropType^^.Name]);
end;
end;
end;
procedure SetPropValue(Instance: TObject; const PropName: string;
const Value: Variant);
function RangedValue(const AMin, AMax: Int64): Int64;
begin
Result := Trunc(Value);
if Result < AMin then
Result := AMin;
if Result > AMax then
Result := AMax;
end;
var
PropInfo: PPropInfo;
TypeData: PTypeData;
begin
// get the prop info
PropInfo := GetPropInfo(PTypeInfo(Instance.ClassType.ClassInfo), PropName);
if PropInfo <> nil then
begin
TypeData := GetTypeData(PropInfo^.PropType^);
// set the right type
case PropInfo.PropType^^.Kind of
tkInteger, tkChar, tkWChar:
SetOrdProp(Instance, PropInfo, RangedValue(TypeData^.MinValue,
TypeData^.MaxValue));
tkEnumeration:
if VarType(Value) = varString then
SetEnumProp(Instance, PropInfo, VarToStr(Value))
else
SetOrdProp(Instance, PropInfo, RangedValue(TypeData^.MinValue,
TypeData^.MaxValue));
tkSet:
if VarType(Value) = varInteger then
SetOrdProp(Instance, PropInfo, Value)
else
SetSetProp(Instance, PropInfo, VarToStr(Value));
tkFloat:
SetFloatProp(Instance, PropInfo, Value);
tkString, tkLString, tkWString:
SetStrProp(Instance, PropInfo, VarToStr(Value));
tkVariant:
SetVariantProp(Instance, PropInfo, Value);
tkInt64:
SetInt64Prop(Instance, PropInfo, RangedValue(TypeData^.MinInt64Value,
TypeData^.MaxInt64Value));
else
raise EPropertyConvertError.CreateFmt('Invalid property type: %s',
[PropInfo.PropType^^.Name]);
end;
end;
end;
function PropType(AClass: TClass; const PropName: string): TTypeKind;
var
PropInfo: PPropInfo;
begin
PropInfo := GetPropInfo(AClass.ClassInfo, PropName);
if PropInfo = nil then
raise EPropertyError.Create('Property does not exist');
Result := PropInfo^.PropType^^.Kind;
end;
{$ENDIF} //////////////////////////////////////////////////////////////////////
{$IFNDEF FG_D6} ///////////////////////////////////////////////////////////////
{ Copied from Delphi7 System.pas unit }
// UnicodeToUTF8(3):
// Scans the source data to find the null terminator, up to MaxBytes
// Dest must have MaxBytes available in Dest.
function UnicodeToUtf8(Dest: PChar; Source: PWideChar; MaxBytes: Integer): Integer;
var
len: Cardinal;
begin
len := 0;
if Source <> nil then
while Source[len] <> #0 do
Inc(len);
Result := UnicodeToUtf8(Dest, MaxBytes, Source, len);
end;
// UnicodeToUtf8(4):
// MaxDestBytes includes the null terminator (last char in the buffer will be set to null)
// Function result includes the null terminator.
// Nulls in the source data are not considered terminators - SourceChars must be accurate
function UnicodeToUtf8(Dest: PChar; MaxDestBytes: Cardinal; Source: PWideChar; SourceChars: Cardinal): Cardinal;
var
i, count: Cardinal;
c: Cardinal;
begin
Result := 0;
if Source = nil then Exit;
count := 0;
i := 0;
if Dest <> nil then
begin
while (i < SourceChars) and (count < MaxDestBytes) do
begin
c := Cardinal(Source[i]);
Inc(i);
if c <= $7F then
begin
Dest[count] := Char(c);
Inc(count);
end
else if c > $7FF then
begin
if count + 3 > MaxDestBytes then
break;
Dest[count] := Char($E0 or (c shr 12));
Dest[count+1] := Char($80 or ((c shr 6) and $3F));
Dest[count+2] := Char($80 or (c and $3F));
Inc(count,3);
end
else // $7F < Source[i] <= $7FF
begin
if count + 2 > MaxDestBytes then
break;
Dest[count] := Char($C0 or (c shr 6));
Dest[count+1] := Char($80 or (c and $3F));
Inc(count,2);
end;
end;
if count >= MaxDestBytes then count := MaxDestBytes-1;
Dest[count] := #0;
end
else
begin
while i < SourceChars do
begin
c := Integer(Source[i]);
Inc(i);
if c > $7F then
begin
if c > $7FF then
Inc(count);
Inc(count);
end;
Inc(count);
end;
end;
Result := count+1; // convert zero based index to byte count
end;
function Utf8ToUnicode(Dest: PWideChar; Source: PChar; MaxChars: Integer): Integer;
var
len: Cardinal;
begin
len := 0;
if Source <> nil then
while Source[len] <> #0 do
Inc(len);
Result := Utf8ToUnicode(Dest, MaxChars, Source, len);
end;
function Utf8ToUnicode(Dest: PWideChar; MaxDestChars: Cardinal; Source: PChar; SourceBytes: Cardinal): Cardinal;
var
i, count: Cardinal;
c: Byte;
wc: Cardinal;
begin
if Source = nil then
begin
Result := 0;
Exit;
end;
Result := Cardinal(-1);
count := 0;
i := 0;
if Dest <> nil then
begin
while (i < SourceBytes) and (count < MaxDestChars) do
begin
wc := Cardinal(Source[i]);
Inc(i);
if (wc and $80) <> 0 then
begin
if i >= SourceBytes then Exit; // incomplete multibyte char
wc := wc and $3F;
if (wc and $20) <> 0 then
begin
c := Byte(Source[i]);
Inc(i);
if (c and $C0) <> $80 then Exit; // malformed trail byte or out of range char
if i >= SourceBytes then Exit; // incomplete multibyte char
wc := (wc shl 6) or (c and $3F);
end;
c := Byte(Source[i]);
Inc(i);
if (c and $C0) <> $80 then Exit; // malformed trail byte
Dest[count] := WideChar((wc shl 6) or (c and $3F));
end
else
Dest[count] := WideChar(wc);
Inc(count);
end;
if count >= MaxDestChars then count := MaxDestChars-1;
Dest[count] := #0;
end
else
begin
while (i < SourceBytes) do
begin
c := Byte(Source[i]);
Inc(i);
if (c and $80) <> 0 then
begin
if i >= SourceBytes then Exit; // incomplete multibyte char
c := c and $3F;
if (c and $20) <> 0 then
begin
c := Byte(Source[i]);
Inc(i);
if (c and $C0) <> $80 then Exit; // malformed trail byte or out of range char
if i >= SourceBytes then Exit; // incomplete multibyte char
end;
c := Byte(Source[i]);
Inc(i);
if (c and $C0) <> $80 then Exit; // malformed trail byte
end;
Inc(count);
end;
end;
Result := count+1;
end;
function Utf8Encode(const WS: WideString): UTF8String;
var
L: Integer;
Temp: UTF8String;
begin
Result := '';
if WS = '' then Exit;
SetLength(Temp, Length(WS) * 3); // SetLength includes space for null terminator
L := UnicodeToUtf8(PChar(Temp), Length(Temp)+1, PWideChar(WS), Length(WS));
if L > 0 then
SetLength(Temp, L-1)
else
Temp := '';
Result := Temp;
end;
function Utf8Decode(const S: UTF8String): WideString;
var
L: Integer;
Temp: WideString;
begin
Result := '';
if S = '' then Exit;
SetLength(Temp, Length(S));
L := Utf8ToUnicode(PWideChar(Temp), Length(Temp)+1, PChar(S), Length(S));
if L > 0 then
SetLength(Temp, L-1)
else
Temp := '';
Result := Temp;
end;
function AnsiToUtf8(const S: string): UTF8String;
begin
Result := Utf8Encode(S);
end;
function Utf8ToAnsi(const S: UTF8String): string;
begin
Result := Utf8Decode(S);
end;
{$ENDIF} //////////////////////////////////////////////////////////////////////
{$IFNDEF FG_D7} ///////////////////////////////////////////////////////////////
{ Copied from Delphi7 Classes.pas unit }
{$IFNDEF FG_D6}
function SameText(const S1, S2: string): Boolean; assembler;
asm
CMP EAX,EDX
JZ @1
OR EAX,EAX
JZ @2
OR EDX,EDX
JZ @3
MOV ECX,[EAX-4]
CMP ECX,[EDX-4]
JNE @3
CALL CompareText
TEST EAX,EAX
JNZ @3
@1: MOV AL,1
@2: RET
@3: XOR EAX,EAX
end;
{$ENDIF}
function AncestorIsValid(Ancestor: TPersistent;
Root, RootAncestor: TComponent): Boolean;
begin
Result := (Ancestor <> nil) and (RootAncestor <> nil) and
Root.InheritsFrom(RootAncestor.ClassType);
end;
function IsDefaultPropertyValue(Instance: TObject; PropInfo: PPropInfo;
OnGetLookupInfo: TGetLookupInfoEvent): Boolean;
var
PropType: PTypeInfo;
Ancestor: TPersistent;
LookupRoot: TComponent;
RootAncestor: TComponent;
Root: TComponent;
AncestorValid: Boolean;
function IsDefaultOrdProp: Boolean;
var
Value: Longint;
Default: LongInt;
begin
Value := GetOrdProp(Instance, PropInfo);
if AncestorValid then
Result := Value = GetOrdProp(Ancestor, PropInfo)
else
begin
Default := PPropInfo(PropInfo)^.Default;
Result := (Default <> LongInt($80000000)) and (Value = Default);
end;
end;
function IsDefaultFloatProp: Boolean;
var
Value: Extended;
begin
Value := GetFloatProp(Instance, PropInfo);
if AncestorValid then
Result := Value = GetFloatProp(Ancestor, PropInfo)
else
Result := Value = 0;;
end;
function IsDefaultInt64Prop: Boolean;
var
Value: Int64;
begin
Value := GetInt64Prop(Instance, PropInfo);
if AncestorValid then
Result := Value = GetInt64Prop(Ancestor, PropInfo)
else
Result := Value = 0;
end;
function IsDefaultStrProp: Boolean;
var
{$IFNDEF FG_D6}
Value: string;
{$ELSE}
Value: WideString;
{$ENDIF}
begin
{$IFNDEF FG_D6}
Value := GetStrProp(Instance, PropInfo);
if AncestorValid
then Result := Value = GetStrProp(Ancestor, PropInfo)
else Result := Value = '';
{$ELSE}
Value := GetWideStrProp(Instance, PropInfo);
if AncestorValid then
Result := Value = GetWideStrProp(Ancestor, PropInfo)
else
Result := Value = '';
{$ENDIF}
end;
function ObjectAncestorMatch(AncestorValue, Value: TComponent): Boolean;
begin
Result := (AncestorValue <> nil) and (AncestorValue.Owner = RootAncestor) and
(Value <> nil) and (Value.Owner = Root) and
SameText(AncestorValue.Name, Value.Name);
end;
function IsDefaultObjectProp: Boolean;
var
Value: TObject;
function IsDefault: Boolean;
var
AncestorValue: TObject;
begin
AncestorValue := nil;
if AncestorValid then
begin
AncestorValue := TObject(GetOrdProp(Ancestor, PropInfo));
if ObjectAncestorMatch(TComponent(AncestorValue), TComponent(Value)) then
AncestorValue := Value;
end;
Result := Value = AncestorValue;
end;
begin
Result := True;
Value := TObject(GetOrdProp(Instance, PropInfo));
if (Value = nil) and not IsDefault then
begin
Result := False; // nil wasn't the "default" value
end
else if Value is TPersistent then
begin
if (Value is TComponent)
{$IFDEF FG_D6}
and not (csSubComponent in TComponent(Value).ComponentStyle)
{$ENDIF}
then
begin
if not IsDefault then
begin
// A non sub-component TComponent is only non-default if
// it actually has a name (that way, it can be streamed out -
// it can't be streamed without a name).
if TComponent(Value).Name <> '' then
Result := False;
end
end else
begin
Result := False; // The TPersistent should be checked for default's by the caller
end;
end;
end;
{$IFDEF FG_D6}
function IsDefaultInterfaceProp: Boolean;
var
Intf: IInterface;
Value: TComponent;
function IsDefaultValue: Boolean;
var
AncestorIntf: IInterface;
ASR: IInterfaceComponentReference;
begin
Result := Intf = nil;
if AncestorValid then
begin
AncestorIntf := GetInterfaceProp(Ancestor, PropInfo);
Result := Intf = AncestorIntf;
if not Result then
begin
if Supports(AncestorIntf, IInterfaceComponentReference, ASR) then
Result := ObjectAncestorMatch(ASR.GetComponent, Value);
end;
end;
end;
var
SR: IInterfaceComponentReference;
begin
Result := True;
Intf := GetInterfaceProp(Instance, PropInfo);
if (Intf = nil) or (not Supports(Intf, IInterfaceComponentReference, SR)) then
begin
if AncestorValid and (GetInterfaceProp(Ancestor, PropInfo) <> nil) then
Result := False;
end
else
begin
Value := SR.GetComponent;
if not IsDefaultValue then
begin
// We can only stream out components (ie: non-default ones)
// if they actually have a name
if Value.Name <> '' then
Result := False;
end;
end;
end;
{$ENDIF}
function IsDefaultMethodProp: Boolean;
var
Value: TMethod;
DefaultCode: Pointer;
begin
Value := GetMethodProp(Instance, PropInfo);
DefaultCode := nil;
if AncestorValid then
DefaultCode := GetMethodProp(Ancestor, PropInfo).Code;
Result := (Value.Code = DefaultCode) or
((Value.Code <> nil) and (LookupRoot.MethodName(Value.Code) = ''));
end;
function IsDefaultVariantProp: Boolean;
var
Value: Variant;
begin
Value := GetVariantProp(Instance, PropInfo);
{$IFNDEF FG_D6}
if AncestorValid
then Result := Value = GetVariantProp(Ancestor, PropInfo)
else Result := VarIsEmpty(Value);
{$ELSE}
if AncestorValid then
Result := VarSameValue(Value, GetVariantProp(Ancestor, PropInfo))
else
Result := VarIsClear(Value);
{$ENDIF}
end;
begin
Ancestor := nil;
Root := nil;
LookupRoot := nil;
RootAncestor := nil;
if Assigned(OnGetLookupInfo) then
OnGetLookupInfo(Ancestor, Root, LookupRoot, RootAncestor);
AncestorValid := AncestorIsValid(Ancestor, Root, RootAncestor);
Result := True;
if (PropInfo^.GetProc <> nil) and
((PropInfo^.SetProc <> nil) or
((PropInfo^.PropType^.Kind = tkClass) and
(TObject(GetOrdProp(Instance, PropInfo)) is TComponent)
{$IFDEF FG_D6}
and (csSubComponent in TComponent(GetOrdProp(Instance, PropInfo)).ComponentStyle)
{$ENDIF}
) ) then
begin
PropType := PropInfo^.PropType^;
case PropType^.Kind of
tkInteger, tkChar, tkEnumeration, tkSet:
Result := IsDefaultOrdProp;
tkFloat:
Result := IsDefaultFloatProp;
tkString, tkLString, tkWString:
Result := IsDefaultStrProp;
tkClass:
Result := IsDefaultObjectProp;
tkMethod:
Result := IsDefaultMethodProp;
tkVariant:
Result := IsDefaultVariantProp;
tkInt64:
Result := IsDefaultInt64Prop;
{$IFDEF FG_D6}
tkInterface:
Result := IsDefaultInterfaceProp;
{$ENDIF}
end;
end;
end;
{$ENDIF} //////////////////////////////////////////////////////////////////////
initialization
CF_FLEXDOC := RegisterClipboardFormat('FlexGraphics controls');
end.
|
{
Copyright (c) 2020, Loginov Dmitry Sergeevich
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
}
unit TimeIntervals;
interface
uses
Windows, SysUtils, Classes, DateUtils, StrUtils;
type
{ TTimeInterval is designed to accurately measure time,
passed after the start of measurement.
Attention! Microsecond measurements
performed with an error of several microseconds (despite
using the variable PerformanceIgnoredTicks }
TTimeInterval = record
private
FStartCounter: Int64;
FIsRunning: Boolean;
FElapsedTicks: Int64;
public
// Starts measuring
procedure Start;
// For supporting inline variables (var ti := TTimeInterval.StartNew)
class function StartNew: TTimeInterval; static;
// Finishes measuring. Updates the FElapsedTicks field. After the Stop method
// is called, the ElapsedXXX methods will return the value stored in FElapsedTicks
procedure Stop;
// Returns the number of milliseconds after the start of measurement
function ElapsedMilliseconds(AStartNew: Boolean = False): Int64;
// Returns the number of microseconds after the start of measurements
function ElapsedMicroseconds(AStartNew: Boolean = False): Int64;
// Returns the number of seconds after the start of measurement
function ElapsedSeconds(AStartNew: Boolean = False): Double;
// Returns the number of ticks from the beginning of measurements
function ElapsedTicks(AStartNew: Boolean = False): Int64;
// Returns the time (TDateTime) elapsed since the start of measurement
function ElapsedTime(AStartNew: Boolean = False): TDateTime;
// Returns True if measurements are running.
property IsRunning: Boolean read FIsRunning;
end;
TTimeIntervalEvent = record
// Date / time of the beginning and end of the event (according to the standard system timer)
BegDateTime: TDateTime;
EndDateTime: TDateTime;
EventName: string; // Event name
BegCounter: Int64; // Counter value at the beginning of the event
EndCounter: Int64; // Counter value at the end of the event
function ElapsedTicks: Int64;
function ElapsedMilliseconds: Int64;
function ElapsedMicroseconds: Int64;
function ElapsedSeconds: Double;
procedure Start(AName: string);
procedure Stop;
end;
TTimeIntervalGetEventsOption = (eoWriteStartTime, eoWriteStopTime, eoWriteAllTime,
eoWriteBegTime, eoWriteEndTime, eoUseMicroSec, eoWriteFromStart, eoWriteDate);
TTimeIntervalGetEventsOptions = set of TTimeIntervalGetEventsOption;
// TTimeIntervalEvents - record for event duration logging
TTimeIntervalEvents = record
Events: array of TTimeIntervalEvent;
// Starts measurement of a new event.
procedure StartEvent(EventName: string);
// Stops event measurement. You can indicate EventName for
// illustration purposes only.
procedure StopEvent(EventName: string = '');
// Returns event duration measurement information
function GetEventsAsString(EvOp: TTimeIntervalGetEventsOptions): string;
end;
var
PerformanceFrequency: Int64;
UsePerformanceCounter: Boolean;
// The number of ticks that must be ignored to more accurately measure time intervals
PerformanceIgnoredTicks: Int64 = 0;
implementation
var
GetTickCount64Ref: function: UInt64;
GetTickCount64NotSupported: Boolean;
function InternalGetTickCount64: UInt64;
begin
if (@GetTickCount64Ref = nil) and (not GetTickCount64NotSupported) then // Функция не реализована в WinXP
begin
@GetTickCount64Ref := GetProcAddress(GetModuleHandle('kernel32.dll'), 'GetTickCount64');
if @GetTickCount64Ref = nil then
GetTickCount64NotSupported := True;
end;
if Assigned(GetTickCount64Ref) then
Result := GetTickCount64Ref
else
Result := GetTickCount;
end;
{ TTimeInterval }
function TTimeInterval.ElapsedMicroseconds(AStartNew: Boolean = False): Int64;
begin
Result := Round(ElapsedSeconds(AStartNew) * 1000000);
end;
function TTimeInterval.ElapsedMilliseconds(AStartNew: Boolean = False): Int64;
begin
Result := Round(ElapsedSeconds(AStartNew) * 1000);
end;
function TTimeInterval.ElapsedSeconds(AStartNew: Boolean = False): Double;
begin
Result := ElapsedTicks(AStartNew) / PerformanceFrequency;
end;
function TTimeInterval.ElapsedTicks(AStartNew: Boolean = False): Int64;
var
ACounter: Int64;
begin
if FIsRunning then
begin // If measurements are started, then return the current value
if UsePerformanceCounter then
QueryPerformanceCounter(ACounter)
else
ACounter := InternalGetTickCount64;
Result := ACounter - FStartCounter - PerformanceIgnoredTicks;
if Result < 0 then
Result := 0;
end else
begin // Measurements stopped - return the value at the time of stop
Result := FElapsedTicks
end;
if AStartNew then
Start;
end;
function TTimeInterval.ElapsedTime(AStartNew: Boolean): TDateTime;
begin
Result := IncMilliSecond(0, ElapsedMilliseconds(AStartNew));
end;
procedure TTimeInterval.Start;
begin
FIsRunning := True;
FElapsedTicks := 0;
// Request a counter at the very end of the method
if UsePerformanceCounter then
QueryPerformanceCounter(FStartCounter)
else
FStartCounter := InternalGetTickCount64;
end;
class function TTimeInterval.StartNew: TTimeInterval;
begin
Result.Start;
end;
procedure TTimeInterval.Stop;
var
ACounter: Int64;
begin
// Request a counter at the very beginning of the method
if UsePerformanceCounter then
QueryPerformanceCounter(ACounter)
else
ACounter := InternalGetTickCount64;
FIsRunning := False;
FElapsedTicks := ACounter - FStartCounter - PerformanceIgnoredTicks;
if FElapsedTicks < 0 then
FElapsedTicks := 0;
end;
{ TTimeIntervalEvent }
function TTimeIntervalEvent.ElapsedMilliseconds: Int64;
begin
Result := Round(ElapsedSeconds * 1000);
end;
function TTimeIntervalEvent.ElapsedMicroseconds: Int64;
begin
Result := Round(ElapsedSeconds * 1000000);
end;
function TTimeIntervalEvent.ElapsedSeconds: Double;
begin
Result := ElapsedTicks / PerformanceFrequency;
end;
function TTimeIntervalEvent.ElapsedTicks: Int64;
begin
Result := EndCounter - BegCounter;
end;
procedure TTimeIntervalEvent.Start(AName: string);
begin
BegDateTime := Now;
EventName := AName;
if UsePerformanceCounter then
QueryPerformanceCounter(BegCounter)
else
BegCounter := InternalGetTickCount64;
end;
procedure TTimeIntervalEvent.Stop;
begin
if UsePerformanceCounter then
QueryPerformanceCounter(EndCounter)
else
EndCounter := InternalGetTickCount64;
EndCounter := EndCounter - PerformanceIgnoredTicks;
if EndCounter < BegCounter then
EndCounter := BegCounter;
EndDateTime := Now;
end;
{ TTimeIntervalEvents }
function TTimeIntervalEvents.GetEventsAsString(
EvOp: TTimeIntervalGetEventsOptions): string;
var
Ev, EvFirst: TTimeIntervalEvent;
s, sTimeMask: string;
I: Integer;
AllTime, AllTicks: Int64;
Sec: Double;
begin
Result := '';
if Length(Events) = 0 then
begin
Result := 'Events array is empty';
Exit;
end;
if eoWriteDate in EvOp then
sTimeMask := 'dd.mm.yy hh:nn:ss.zzz'
else
sTimeMask := 'hh:nn:ss.zzz';
EvFirst := Events[0];
if eoWriteStartTime in EvOp then
begin
Result := 'StartTime: ' + FormatDateTime(sTimeMask, EvFirst.BegDateTime);
if eoWriteAllTime in EvOp then
Result := Result + '; ';
end;
if eoWriteAllTime in EvOp then
begin
Result := Result + 'AllTime: ';
AllTicks := 0;
for Ev in Events do
AllTicks := AllTicks + Ev.ElapsedTicks;
Sec := AllTicks / PerformanceFrequency;
if eoUseMicroSec in EvOp then
AllTime := Round(Sec * 1000000)
else
AllTime := Round(Sec * 1000);
Result := Result + IntToStr(AllTime) + IfThen(eoUseMicroSec in EvOp, ' us', ' ms') + '; ';
end;
for I := 0 to High(Events) do
begin
Ev := Events[I];
Result := Result + Ev.EventName + ':[';
if eoUseMicroSec in EvOp then
s := IntToStr(Ev.ElapsedMicroseconds) + ' us'
else
s := IntToStr(Ev.ElapsedMilliseconds) + ' ms';
if eoWriteBegTime in EvOp then
s := s + '; BegTime: ' + FormatDateTime(sTimeMask, Ev.BegDateTime);
if eoWriteEndTime in EvOp then
s := s + '; EndTime: ' + FormatDateTime(sTimeMask, Ev.EndDateTime);
if eoWriteFromStart in EvOp then
begin
s := s + '; FromStart: ';
AllTicks := Ev.EndCounter - EvFirst.BegCounter;
Sec := AllTicks / PerformanceFrequency;
if eoUseMicroSec in EvOp then
AllTime := Round(Sec * 1000000)
else
AllTime := Round(Sec * 1000);
s := s + IntToStr(AllTime) + IfThen(eoUseMicroSec in EvOp, ' us', ' ms');
end;
Result := Result + s + ']';
if I < High(Events) then
Result := Result + '; ';
end;
end;
procedure TTimeIntervalEvents.StartEvent(EventName: string);
var
Cnt: Integer;
begin
Cnt := Length(Events);
if (Cnt > 0) and (Events[Cnt - 1].EndCounter = 0) then
StopEvent();
SetLength(Events, Cnt + 1);
Events[Cnt].Start(EventName);
end;
procedure TTimeIntervalEvents.StopEvent(EventName: string = '');
var
Idx: Integer;
begin
Idx := High(Events);
if Idx >= 0 then
Events[Idx].Stop;
end;
procedure CalcIgnoredPerformanceTicks;
var
p1, p2: Int64;
begin
QueryPerformanceCounter(p1);
QueryPerformanceCounter(p2);
PerformanceIgnoredTicks := p2 - p1;
// If you do not need adjustment, then just assign:
// PerformanceIgnoredTicks := 0
end;
initialization
// We get the frequency of the high-frequency timer
UsePerformanceCounter := QueryPerformanceFrequency(PerformanceFrequency);
if UsePerformanceCounter then
CalcIgnoredPerformanceTicks
else
PerformanceFrequency := 1000; // impossible condition ???
end. |
(* Syntaxtree Canon: MM, 2020-05-01 *)
(* ------ *)
(* A unit to display syntax trees in canonical form *)
(* ========================================================================= *)
UNIT syntaxtree_canon;
INTERFACE
TYPE SynTree = POINTER;
PROCEDURE NewTree(VAR t: SynTree);
PROCEDURE DisposeTree(VAR t: SynTree);
PROCEDURE WriteTree(t: SynTree);
PROCEDURE S(VAR t: SynTree);
VAR line: STRING;
IMPLEMENTATION
TYPE
NodePtr = ^Node;
Node = RECORD
firstChild, sibling: NodePtr;
val: STRING;
END;
TreePtr = NodePtr;
(* Functions for Tree *)
PROCEDURE NewTree(VAR t: SynTree);
BEGIN (* NewTree *)
TreePtr(t) := NIL;
END; (* NewTree *)
PROCEDURE DisposeTree(VAR t: SynTree);
BEGIN (* DisposeTree *)
IF (TreePtr(t) <> NIL) THEN BEGIN
DisposeTree(TreePtr(t)^.firstChild);
DisposeTree(TreePtr(t)^.sibling);
Dispose(TreePtr(t));
END; (* IF *)
END; (* DisposeTree *)
FUNCTION NewNode(x: STRING): NodePtr;
VAR n: NodePtr;
BEGIN (* NewNode *)
New(n);
n^.val := x;
n^.firstChild := NIL;
n^.sibling := NIL;
NewNode := n;
END; (* NewNode *)
PROCEDURE WriteTreeRec(t: SynTree; space: INTEGER);
VAR i: INTEGER;
BEGIN (* WriteTree *)
IF (t <> NIL) THEN BEGIN
space := space + 10;
WriteTreeRec(TreePtr(t)^.sibling, space);
WriteLn;
FOR i := 10 TO space DO BEGIN
Write(' ');
END; (* FOR *)
WriteLn(TreePtr(t)^.val);
WriteTreeRec(TreePtr(t)^.firstChild, space);
END; (* IF *)
END; (* WriteTree *)
PROCEDURE WriteTree(t: Syntree);
BEGIN (* WriteTree *)
WriteTreeRec(t, 0);
END; (* WriteTree *)
(* END Functions for Tree *)
(* Functions for Data Analysis *)
CONST
EOS_CH = Chr(0);
TYPE
SymbolCode = (noSy, (* error symbol *)
eosSy, (* end of string symbol*)
plusSy, minusSy, timesSy, divSy,
leftParSy, rightParSy,
number);
VAR
ch: CHAR;
cnr: INTEGER;
sy: SymbolCode;
numberVal: INTEGER;
success: BOOLEAN;
PROCEDURE Expr(VAR e: TreePtr) FORWARD;
PROCEDURE Term(VAR t: TreePtr) FORWARD;
PROCEDURE Fact(VAR f: TreePtr) FORWARD;
(* SCANNER *)
PROCEDURE NewCh;
BEGIN (* NewCh *)
IF (cnr < Length(line)) THEN BEGIN
Inc(cnr);
ch := line[cnr];
END ELSE BEGIN
ch := EOS_CH;
END; (* IF *)
END; (* NewCh *)
PROCEDURE NewSy;
BEGIN (* NewSy *)
WHILE (ch = ' ') DO BEGIN
NewCh;
END; (* WHILE *)
CASE ch OF
EOS_CH: BEGIN sy := eosSy; END;
'+': BEGIN sy := plusSy; NewCh; END;
'-': BEGIN sy := minusSy; NewCh; END;
'*': BEGIN sy := timesSy; NewCh; END;
'/': BEGIN sy := divSy; NewCh; END;
'(': BEGIN sy := leftParSy; NewCh; END;
')': BEGIN sy := rightParSy; NewCh; END;
'0'..'9': BEGIN
sy := number;
numberVal := 0;
WHILE ((ch >= '0') AND (ch <= '9')) DO BEGIN
numberVal := numberVal * 10 + Ord(ch) - Ord('0');
NewCh;
END; (* WHILE *)
END;
ELSE BEGIN
sy := noSy;
END;
END; (* CASE *)
END; (* NewSy *)
(* END SCANNER *)
(* PARSER *)
PROCEDURE InitParser;
BEGIN (* InitParser *)
success := TRUE;
cnr := 0;
END; (* InitParser *)
PROCEDURE S(VAR t: SynTree);
BEGIN (* S *)
InitParser;
NewCh;
NewSy;
Expr(TreePtr(t));
IF (NOT success) THEN BEGIN
DisposeTree(t);
t := NIL;
Exit;
END; (* IF *)
IF (sy <> eosSy) THEN BEGIN
success := FALSE;
EXIT;
END; (* IF *)
END; (* S *)
PROCEDURE Expr(VAR e: TreePtr);
VAR t, t2: TreePtr;
BEGIN (* Expr *)
e := NewNode('Expr');
Term(t); IF (NOT success) THEN Exit;
(* SEM *) e^.firstChild := t;
WHILE ((sy = plusSy) OR (sy = minusSy)) DO BEGIN
CASE sy OF
plusSy: BEGIN
NewSy;
t2 := NewNode('+');
Term(t2^.sibling); IF (NOT success) THEN Exit;
t^.sibling := t2;
END;
minusSy: BEGIN
NewSy;
t2 := NewNode('-');
Term(t2^.sibling); IF (NOT success) THEN Exit;
t^.sibling := t2;
END;
END; (* CASE *)
END; (* WHILE *)
END; (* Expr *)
PROCEDURE Term(VAR t: TreePtr);
VAR f: TreePtr;
BEGIN (* Term *)
t := NewNode('Term');
Fact(f); IF (NOT success) THEN Exit;
(* SEM *) t^.firstChild := f;
WHILE ((sy = timesSy) OR (sy = divSy)) DO BEGIN
CASE sy OF
timesSy: BEGIN
NewSy;
f := NewNode('*');
Fact(f^.sibling); IF (NOT success) THEN Exit;
t^.sibling := f;
END;
divSy: BEGIN
NewSy;
f := NewNode('/');
Fact(f^.sibling); IF (NOT success) THEN Exit;
t^.sibling := f;
END;
END; (* CASE *)
END; (* WHILE *)
END; (* Term *)
PROCEDURE Fact(VAR f: TreePtr);
VAR e: TreePtr;
BEGIN (* Fact *)
f := NewNode('Fact');
CASE sy OF
number: BEGIN
f^.firstChild := NewNode(Chr(Ord(numberVal) + Ord('0')));
NewSy;
END;
leftParSy: BEGIN
NewSy;
e := NewNode('(');
Expr(e^.sibling); IF (NOT success) THEN Exit;
IF (sy <> rightParSy) THEN BEGIN
success := FALSE;
Exit;
END; (* IF *)
f^.sibling := e;
NewSy;
END;
ELSE BEGIN
success := FALSE;
Exit;
END;
END; (* CASE *)
END; (* Fact *)
(* END PARSER *)
BEGIN (* syntaxtree_canon *)
END. (* syntaxtree_canon *) |
unit UserPermissions;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, dmSkin,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, dxSkinOffice2010Silver,
dxSkinscxPCPainter, cxContainer, cxEdit, dxLayoutcxEditAdapters, dxLayoutContainer, cxLabel, dxLayoutLookAndFeels, cxClasses, dxLayoutControl,
dxLayoutControlAdapters, Vcl.Menus, cxCheckListBox, Vcl.StdCtrls, cxButtons, cxTextEdit, cxMaskEdit, cxDropDownEdit, GMGlobals;
type
TUsersDlg = class(TForm)
dxLayoutControl1Group_Root: TdxLayoutGroup;
dxLayoutControl1: TdxLayoutControl;
labelState: TcxLabel;
dxLayoutItem1: TdxLayoutItem;
cmbUsers: TcxComboBox;
dxLayoutItem2: TdxLayoutItem;
buttonAddUser: TcxButton;
dxLayoutItem3: TdxLayoutItem;
dxLayoutAutoCreatedGroup1: TdxLayoutAutoCreatedGroup;
cxButton2: TcxButton;
dxLayoutItem4: TdxLayoutItem;
clbRoles: TcxCheckListBox;
dxLayoutItem5: TdxLayoutItem;
cxButton3: TcxButton;
dxLayoutItem6: TdxLayoutItem;
dxLayoutGroupUserProperties: TdxLayoutGroup;
dxLayoutGroup2: TdxLayoutGroup;
dxLayoutGroup3: TdxLayoutGroup;
cmbUserState: TcxComboBox;
dxLayoutItem7: TdxLayoutItem;
dxLayoutGroup4: TdxLayoutGroup;
dxLayoutGroup5: TdxLayoutGroup;
clbObjects: TcxCheckListBox;
dxLayoutItem8: TdxLayoutItem;
dxLayoutSplitterItem1: TdxLayoutSplitterItem;
cxButton4: TcxButton;
dxLayoutItem9: TdxLayoutItem;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure cmbUsersPropertiesChange(Sender: TObject);
procedure cxButton2Click(Sender: TObject);
procedure buttonAddUserClick(Sender: TObject);
procedure clbRolesClickCheck(Sender: TObject; AIndex: Integer; APrevState, ANewState: TcxCheckBoxState);
procedure clbObjectsClickCheck(Sender: TObject; AIndex: Integer; APrevState, ANewState: TcxCheckBoxState);
private
FLoading: bool;
procedure LoadUsers;
procedure UpdateSecurityState;
procedure LoadRoles;
procedure LoadObjects;
function GetUserId: int;
procedure UpdateObjectPermissions;
procedure UpdateRoles;
procedure UpdateUserState;
procedure UpdateClbFromQuery(clb: TcxCheckListBox; const sql, fieldId: string);
procedure CheckRolesEnabled;
property UserId: int read GetUserId;
public
{ Public declarations }
end;
var
UsersDlg: TUsersDlg;
implementation
uses
GMSqlQuery, UsefulQueries, GMConst, User;
{$R *.dfm}
procedure TUsersDlg.LoadUsers();
begin
cmbUsers.Properties.Items.Clear();
ReadFromQuery('select * from Users order by Login',
procedure (q: TGMSqlQuery)
begin
cmbUsers.Properties.Items.AddObject(q.FieldByName('Login').AsString, pointer(q.FieldByName('ID_User').AsInteger))
end);
if cmbUsers.Properties.Items.Count > 0 then
cmbUsers.ItemIndex := 0;
end;
procedure TUsersDlg.LoadRoles();
var
item: TcxCheckListBoxItem;
begin
clbRoles.Items.Clear();
ReadFromQueryFmt('select * from Users where State in (%d, %d) order by Login', [USER_STATE_GROUP, USER_STATE_ADMIN_GROUP],
procedure (q: TGMSqlQuery)
begin
item := clbRoles.Items.Add();
item.Text := q.FieldByName('Login').AsString;
item.Tag := q.FieldByName('ID_User').AsInteger;
end);
end;
procedure TUsersDlg.LoadObjects();
var
item: TcxCheckListBoxItem;
begin
clbObjects.Items.Clear();
ReadFromQuery('select * from Objects order by Name',
procedure (q: TGMSqlQuery)
begin
item := clbObjects.Items.Add();
item.Text := q.FieldByName('Name').AsString + '(' + q.FieldByName('N_Car').AsString + ')';
item.Tag := q.FieldByName('ID_Obj').AsInteger;
end);
end;
procedure TUsersDlg.UpdateSecurityState();
begin
if SQLReq_ConfigParam(SYS_CONFIG_PARAM_AUTH_REQUIRED) = '' then
labelState.Caption := 'Âõîä áåç ïàðîëÿ ÐÀÇÐÅØÅÍ'
else
labelState.Caption := 'Âõîä áåç ïàðîëÿ ÇÀÏÐÅÙÅÍ';
end;
procedure TUsersDlg.clbObjectsClickCheck(Sender: TObject; AIndex: Integer; APrevState, ANewState: TcxCheckBoxState);
begin
if FLoading then
Exit;
if ANewState = cbsChecked then
ExecSQLFmt('insert into ObjectPermissions(ID_User, ID_Obj) select %d, %d', [UserId, clbObjects.Items[AIndex].Tag])
else
ExecSQLFmt('delete from ObjectPermissions where ID_User = %d and ID_Obj = %d', [UserId, clbObjects.Items[AIndex].Tag]);
end;
procedure TUsersDlg.clbRolesClickCheck(Sender: TObject; AIndex: Integer; APrevState, ANewState: TcxCheckBoxState);
begin
if FLoading then
Exit;
if ANewState = cbsChecked then
ExecSQLFmt('insert into UserGroups(ID_User, ID_Group) select %d, %d', [UserId, clbRoles.Items[AIndex].Tag])
else
ExecSQLFmt('delete from UserGroups where ID_User = %d and ID_Group = %d', [UserId, clbRoles.Items[AIndex].Tag]);
end;
procedure TUsersDlg.cmbUsersPropertiesChange(Sender: TObject);
begin
dxLayoutGroupUserProperties.Enabled := UserId > 0;
if UserId <= 0 then
Exit;
FLoading := true;
try
UpdateUserState();
UpdateRoles();
UpdateObjectPermissions();
finally
FLoading := false;
end;
end;
procedure TUsersDlg.UpdateUserState();
begin
SelectCmbObject(cmbUserState, StrToIntDef(QueryResultFmt('select State from Users where ID_User = %d', [UserId]), USER_STATE_COMMON));
end;
procedure TUsersDlg.UpdateClbFromQuery(clb: TcxCheckListBox; const sql, fieldId: string);
var
i: int;
begin
for i := 0 to clb.Items.Count - 1 do
clb.Items[i].Checked := false;
ReadFromQuery(sql,
procedure(q: TGMSqlQuery)
var
i: int;
begin
for i := 0 to clb.Items.Count - 1 do
if clb.Items[i].Tag = q.FieldByName(fieldId).AsInteger then
begin
clb.Items[i].Checked := true;
break;
end;
end);
end;
procedure TUsersDlg.CheckRolesEnabled();
var
i: int;
begin
for i := 0 to clbRoles.Items.Count - 1 do
clbRoles.Items[i].Enabled := true;
ReadFromQueryFmt('select *, CanAddUserToGroup(%d, ID_User) as Allow from Users', [UserId],
procedure (q: TGMSqlQuery)
var
i: int;
begin
for i := 0 to clbRoles.Items.Count - 1 do
if clbRoles.Items[i].Tag = q.FieldByName('ID_User').AsInteger then
begin
clbRoles.Items[i].Enabled := q.FieldByName('Allow').AsInteger = 1;
break;
end;
end);
end;
procedure TUsersDlg.UpdateRoles();
begin
UpdateClbFromQuery(clbRoles, Format('select * from UserGroups where ID_User = %d', [UserId]), 'ID_Group');
CheckRolesEnabled();
end;
procedure TUsersDlg.UpdateObjectPermissions();
begin
UpdateClbFromQuery(clbObjects, Format('select * from ObjectPermissions where ID_User = %d', [UserId]), 'ID_Obj');
end;
procedure TUsersDlg.buttonAddUserClick(Sender: TObject);
begin
if UserDlg.ShowModal(-1) <> mrOk then Exit;
ExecSQLFmt('insert into Users(Login, Password, State) select %s, %s, %d',
[QuotedStr(UserDlg.Login), QuotedStr(CalcMD5(UserDlg.Password)), UserDlg.UserState]);
LoadUsers();
cmbUsers.ItemIndex := cmbUsers.Properties.Items.IndexOf(UserDlg.Login);
end;
procedure TUsersDlg.cxButton2Click(Sender: TObject);
begin
if UserId <= 0 then
Exit;
if ShowMessageBox('Óäàëèòü ïîëüçîâàòåëÿ ' + cmbUsers.Text, MB_ICONEXCLAMATION or MB_YESNO) <> IDYES then
Exit;
ExecSQLFmt('delete from Users where ID_User = %d', [UserId]);
end;
procedure TUsersDlg.FormCreate(Sender: TObject);
begin
TUserDlg.UserStateList(cmbUserState.Properties.Items);
end;
procedure TUsersDlg.FormShow(Sender: TObject);
begin
dxLayoutGroupUserProperties.Enabled := false;
UpdateSecurityState();
LoadRoles();
LoadObjects();
LoadUsers();
end;
function TUsersDlg.GetUserId: int;
begin
Result := CmbSelectedObj(cmbUsers);
end;
end.
|
{***********************************<_INFO>************************************}
{ <Проект> Библиотека медиа-обработки }
{ }
{ <Область> 16:Медиа-контроль }
{ }
{ <Задача> Декодер для видео-вывода, формат RGB }
{ }
{ <Автор> Фадеев Р.В. }
{ }
{ <Дата> 14.01.2011 }
{ }
{ <Примечание> Нет примечаний. }
{ }
{ <Атрибуты> ООО НПП "Спецстрой-Связь", ООО "Трисофт" }
{ }
{***********************************</_INFO>***********************************}
unit Player.VideoOutput.BMP;
interface
uses Windows, SysUtils, Classes, Player.VideoOutput.Base,MediaProcessing.Definitions;
type
TVideoOutputDecoder_BMP = class (TVideoOutputDecoder)
private
FDibBuffer: pointer;
FBmpInfoHeader: BITMAPINFOHEADER;
FReverseVertical:boolean;
protected
function DoDecodeData(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal):TVideoOutputDecoderDecodeResult; override;
public
class function SupportedStreamTypes: TArray<TStreamType>; override;
procedure CopyDecoderImageToSurface(aSurface: TSurface); override;
function GetCurrentDecodedBuffer(out aFormat: TMediaStreamDataHeader;
out aData: pointer; out aDataSize: cardinal;
out aInfo: pointer; out aInfoSize: cardinal): TVideoOutputDecoderCurrentDecodedBufferAccess; override;
procedure SaveDecoderImageToStream(aStream: TStream);
procedure SaveDecoderImageToFile(const aFileName:string);
end;
implementation
uses BitPlane;
{ TVideoOutputDecoder_BMP }
function TVideoOutputDecoder_BMP.DoDecodeData(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal):TVideoOutputDecoderDecodeResult;
begin
Assert(aData<>nil);
Assert(aFormat.biMediaType=mtVideo);
FDibBuffer:=aData;
FBmpInfoHeader:=aFormat.ToBitmapInfoHeader(aDataSize);
Assert(FBmpInfoHeader.biSizeImage=aDataSize);
FReverseVertical:=not aFormat.VideoReversedVertical;
SetImageSize(aFormat.VideoWidth,aFormat.VideoHeight);
result:=drSuccess;
end;
function TVideoOutputDecoder_BMP.GetCurrentDecodedBuffer(
out aFormat: TMediaStreamDataHeader; out aData: pointer;
out aDataSize: cardinal; out aInfo: pointer;
out aInfoSize: cardinal): TVideoOutputDecoderCurrentDecodedBufferAccess;
begin
aFormat.Assign(FBmpInfoHeader);
aData:=FDibBuffer;
aDataSize:=FBmpInfoHeader.biSizeImage;
aInfo:=nil;
aInfoSize:=0;
result:=dbaOK;
end;
procedure TVideoOutputDecoder_BMP.SaveDecoderImageToFile(const aFileName: string);
var
aStream: TFileStream;
begin
aStream:=TFileStream.Create(aFileName,fmCreate);
try
SaveDecoderImageToStream(aStream);
finally
aStream.Free;
end;
end;
procedure TVideoOutputDecoder_BMP.SaveDecoderImageToStream(aStream: TStream);
var
FBmpFileHeader: BITMAPFILEHEADER;
begin
FBmpFileHeader.bfType := $4d42; //"BM"
FBmpFileHeader.bfReserved1 := 0;
FBmpFileHeader.bfReserved2 := 0;
FBmpFileHeader.bfOffBits := sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
FBmpFileHeader.bfSize := FBmpInfoHeader.biSizeImage + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
aStream.WriteBuffer(FBmpFileHeader, SizeOf(FBmpFileHeader));
aStream.WriteBuffer(FBmpInfoHeader, SizeOf(FBmpInfoHeader));
aStream.WriteBuffer(FDibBuffer^, FBmpInfoHeader.biSizeImage)
end;
class function TVideoOutputDecoder_BMP.SupportedStreamTypes: TArray<TStreamType>;
begin
SetLength(result,1);
result[0]:=stRGB;
end;
procedure TVideoOutputDecoder_BMP.CopyDecoderImageToSurface(aSurface: TSurface);
begin
case FBmpInfoHeader.biBitCount of
15: aSurface.DrawRGB15(FDibBuffer,FBmpInfoHeader.biSizeImage,FReverseVertical);
16: aSurface.DrawRGB15(FDibBuffer,FBmpInfoHeader.biSizeImage,FReverseVertical);
24: aSurface.DrawRGB24(FDibBuffer,FBmpInfoHeader.biSizeImage,FReverseVertical);
32: aSurface.DrawRGB32(FDibBuffer,FBmpInfoHeader.biSizeImage,FReverseVertical);
end;
end;
initialization
PlayerVideoOutputDecoderFactory.RegisterDecoderClass(TVideoOutputDecoder_BMP);
end.
|
unit SrcUtils;
interface
uses SysUtils, Classes;
function RemoveComments(Lines: TStrings): Boolean; overload;
function RemoveComments(const FileName: string): Boolean; overload;
type
MultiLineComment = record
Opened, Closed: string;
end;
const
LineComments: array[0..0] of string =
('//');
MultiLineComments: array[0..1] of MultiLineComment =
(
(Opened: '{'; Closed: '}'),
(Opened: '(*'; Closed: '*)')
);
implementation
function RemoveLineComment(var Line: string): Boolean;
var
CommentPos, QuotePos: Integer;
LineComment: string;
begin
Result := False;
for LineComment in LineComments do begin
CommentPos := Pos(LineComment, Line);
if CommentPos > 0 then begin
QuotePos := Pos('''', Line);
if (QuotePos > 0) and (QuotePos < CommentPos) then begin
{ TODO : Quotes }
end
else begin
Result := True;
Line := Copy(Line, 1, CommentPos - 1);
end;
Break;
end;
end;
end;
function RemoveComments(Lines: TStrings): Boolean;
var
i: Integer;
Line: string;
begin
Result := False;
i:=0;
while i < Lines.Count do begin
Line := Lines[i];
if RemoveLineComment(Line) then begin
Lines[i] := Line;
Result := True;
end;
Inc(i);
end;
end;
function RemoveComments(const FileName: string): Boolean; overload;
var
Lines: TStrings;
begin
Lines := TStringList.Create;
try
Lines.LoadFromFile(FileName);
Result := RemoveComments(Lines);
Lines.SaveToFile(FileName);
finally
FreeAndNil(Lines);
end;
end;
end.
|
unit GC.LaserCutBoxes.Forms.Main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, PairSplitter,
ExtCtrls, Menus, ActnList, StdActns, LCLType;
{ TfrmMain }
type
TfrmMain = class(TForm)
alMain: TActionList;
actFileExit: TFileExit;
mnuFileExit: TMenuItem;
mnuFile: TMenuItem;
mmMain: TMainMenu;
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
psVertical: TPairSplitter;
pssTop: TPairSplitterSide;
pssBottom: TPairSplitterSide;
psHorizontal: TPairSplitter;
pssLeft: TPairSplitterSide;
pssRight: TPairSplitterSide;
procedure FormCreate(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: boolean);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
private
{ private declarations }
procedure AssignShortCuts;
public
{ public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.lfm}
{ TfrmMain }
procedure TfrmMain.FormCreate(Sender: TObject);
begin
AssignShortCuts;
end;
procedure TfrmMain.AssignShortCuts;
begin
{$IFDEF LINUX}
actFileExit.ShortCut := KeyToShortCut(VK_Q, [ssCtrl]);
{$ENDIF}
{$IFDEF WINDOWS}
actFileExit.ShortCut := KeyToShortCut(VK_X, [ssAlt]);
{$ENDIF}
end;
procedure TfrmMain.FormCloseQuery(Sender: TObject; var CanClose: boolean);
begin
CanClose := True;
end;
procedure TfrmMain.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
CloseAction := caFree;
end;
end.
|
{
Oracle Deploy System ver.1.0 (ORDESY)
by Volodymyr Sedler aka scribe
2016
Desc: wrap/deploy/save objects of oracle database.
No warranty of using this program.
Just Free.
With bugs, suggestions please write to justscribe@yahoo.com
On Github: github.com/justscribe/ORDESY
Module to save current expand state of TTreeView after update.
classes:
TLazyTreeState - record of info about node state
TLazyStateList - the list of LazyTreeState, saving/loading/reading/appending states.
}
unit uLazyTreeState;
interface
uses
// ORDESY Modules
uErrorHandle, uFileRWTypes,
// Delphi Modules
SysUtils, Windows, Forms, ComCtrls;
const
TREESTATENAME = 'LAZY TREE STATE';
TREESTATEVERSION = '1.0';
type
TLazyTreeState = record
ParentName: string;
CurrentName: string;
Expanded: string;
Procedure Clear;
end;
TLazyStateList = class
FLazyList: array of TLazyTreeState;
FSaved: boolean;
FUpdating: boolean;
FCount: integer;
private
procedure GetNodeData(aNode: TTreeNode; var aPName, aCName, aExpanded: string);
function AddState(const aPName, aCName, aExpanded: string): boolean;
function SetNodeState(aNode: TTreeNode): boolean;
protected
function ShowContents: string;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure ReadState(aList: TTreeView);
procedure AppendState(aList: TTreeView);
function SaveStateToFile(const aFileName: string = 'tree_state.data'): boolean;
function LoadStateFromFile(const aFileName: string = 'tree_state.data'): boolean;
property Saved: boolean read FSaved;
property Count: integer read FCount;
end;
implementation
{ TLazyStateList }
constructor TLazyStateList.Create;
begin
FSaved:= false;
FUpdating:= false;
end;
destructor TLazyStateList.Destroy;
begin
Clear;
inherited;
end;
procedure TLazyStateList.Clear;
var
i: integer;
begin
for i := 0 to high(FLazyList) do
FLazyList[i].Clear;
SetLength(FLazyList, 0);
FSaved:= false;
FCount:= 0;
end;
procedure TLazyStateList.GetNodeData(aNode: TTreeNode; var aPName, aCName, aExpanded: string);
begin
try
if not Assigned(aNode) then
Exit;
aCName:= aNode.Text;
aExpanded:= BoolToStr(aNode.Expanded, true);
if Assigned(aNode.Parent) then
aPName:= aNode.Parent.Text
else
aPName:= '';
except
on E: Exception do
HandleError([ClassName, 'GetNodeData', E.Message]);
end;
end;
function TLazyStateList.AddState(const aPName, aCName, aExpanded: string): boolean;
begin
Result:= false;
try
SetLength(FLazyList, length(FLazyList) + 1);
FLazyList[High(FLazyList)].ParentName:= aPName;
FLazyList[High(FLazyList)].CurrentName:= aCName;
FLazyList[High(FLazyList)].Expanded:= aExpanded;
FSaved:= false;
FCount:= Length(FLazyList);
Result:= true;
except
on E: Exception do
HandleError([ClassName, 'AddState', E.Message]);
end;
end;
function TLazyStateList.SetNodeState(aNode: TTreeNode): boolean;
var
i: integer;
ParentName: string;
begin
Result:= false;
try
for i := 0 to high(FLazyList) do
begin
if Assigned(aNode.Parent) then
ParentName:= aNode.Parent.Text
else
ParentName:= '';
if (FLazyList[i].ParentName = ParentName) and (FLazyList[i].CurrentName = aNode.Text) then
begin
if FLazyList[i].Expanded = 'True' then
aNode.Expanded:= true
else
aNode.Expanded:= false;
end;
end;
Result:= true;
except
on E: Exception do
HandleError([ClassName, 'SetNodeState', E.Message]);
end;
end;
function TLazyStateList.ShowContents: string;
var
i: integer;
begin
for i := 0 to high(FLazyList) do
Result:= Result + FLazyList[i].ParentName + '|' + FLazyList[i].CurrentName + '|' + FLazyList[i].Expanded + #13#10;
end;
procedure TLazyStateList.ReadState(aList: TTreeView);
var
i: integer;
iPName, iCName, iExpanded: string;
begin
if FUpdating then
Exit;
try
Clear;
for i := 0 to aList.Items.Count - 1 do
begin
GetNodeData(aList.Items[i], iPName, iCName, iExpanded);
AddState(iPName, iCName, iExpanded);
end;
except
on E: Exception do
HandleError([ClassName, 'ReadState', E.Message]);
end;
end;
procedure TLazyStateList.AppendState(aList: TTreeView);
var
i: integer;
begin
try
try
aList.Items.BeginUpdate;
FUpdating:= true;
for i := 0 to aList.Items.Count - 1 do
SetNodeState(aList.Items[i]);
FUpdating:= false;
finally
aList.Items.EndUpdate;
end;
except
on E: Exception do
HandleError([ClassName, 'AppendState', E.Message]);
end;
end;
function TLazyStateList.LoadStateFromFile(const aFileName: string): boolean;
var
iHandle, iCount, i: integer;
iFileHeader, iFileVersion, ParentName, CurrentName, Expanded: string;
begin
Result:= false;
if not FileExists(aFileName) then
begin
Result := true;
Exit;
end;
try
try
Clear;
iHandle := FileOpen(aFileName, fmOpenRead);
if iHandle = -1 then
raise Exception.Create(SysErrorMessage(GetLastError));
FileReadString(iHandle, iFileHeader); // Name
FileReadString(iHandle, iFileVersion); // Version
if (iFileHeader <> TREESTATENAME) or (iFileVersion <> TREESTATEVERSION) then
raise Exception.Create(Format('Incorrect version! Need: %s:%s', [TREESTATENAME, TREESTATEVERSION]));
FileReadInteger(iHandle, iCount); // Count
for i := 0 to iCount - 1 do
begin
FileReadString(iHandle, ParentName); // ParentName
FileReadString(iHandle, CurrentName); // CurrentName
FileReadString(iHandle, Expanded); // Expanded
AddState(ParentName, CurrentName, Expanded);
end;
FSaved:= true;
Result:= true;
except
on E: Exception do
HandleError([ClassName, 'LoadStateFromFile', E.Message]);
end;
finally
FileClose(iHandle);
end;
end;
function TLazyStateList.SaveStateToFile(const aFileName: string): boolean;
var
iHandle, iCount, i: integer;
begin
Result:= false;
try
try
iHandle := FileCreate(aFileName);
FileWriteString(iHandle, TREESTATENAME); // Name
FileWriteString(iHandle, TREESTATEVERSION); // Version
iCount:= FCount;
FileWrite(iHandle, iCount, SizeOf(iCount));
for i := 0 to iCount - 1 do
begin
FileWriteString(iHandle, FLazyList[i].ParentName); // ParentName
FileWriteString(iHandle, FLazyList[i].CurrentName); // CurrentName
FileWriteString(iHandle, FLazyList[i].Expanded); // Expanded
end;
FSaved:= true;
Result:= true;
except
on E: Exception do
HandleError([ClassName, 'SaveStateToFile', E.Message]);
end;
finally
FileClose(iHandle);
end;
end;
{ TLazyTreeState }
procedure TLazyTreeState.Clear;
begin
Self:= default(TLazyTreeState);
end;
end.
|
unit Ex8Unit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, MTUtils, ComCtrls, ExtCtrls, SyncObjs, TimeIntervals;
type
TMyThread = class(TThread)
private
FMaxValue: Integer;
FResult: Int64;
FCurrValue: Integer;
// Информация о текущем состоянии потока
FThreadStateInfo: string;
function GetThreadStateInfo: string;
procedure SetThreadStateInfo(const Value: string);
public
constructor Create(MaxValue: Integer);
procedure Execute; override;
property CalcResult: Int64 read FResult;
property CurrValue: Integer read FCurrValue;
// Свойство для доступа к строке FThreadStateInfo с помощью
// потокозащищенных методов GetThreadStateInfo и SetThreadStateInfo
property ThreadStateInfo: string read GetThreadStateInfo write SetThreadStateInfo;
end;
TForm1 = class(TForm)
btnRunInParallelThread: TButton;
ProgressBar1: TProgressBar;
Label1: TLabel;
labResult: TLabel;
edMaxValue: TEdit;
Timer1: TTimer;
Label2: TLabel;
labThreadStateInfo: TLabel;
procedure btnRunInParallelThreadClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
{ Private declarations }
FMyThread: TMyThread;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btnRunInParallelThreadClick(Sender: TObject);
var
MaxValue: Integer;
begin
// Уничтожаем запущенный поток
if Assigned(FMyThread) then
FreeAndNil(FMyThread);
MaxValue := StrToInt(edMaxValue.Text);
ProgressBar1.Max := MaxValue;
ProgressBar1.Position := 0;
labResult.Caption := '0';
labThreadStateInfo.Caption := '???';
FMyThread := TMyThread.Create(MaxValue);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FreeAndNil(FMyThread);
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
if Assigned(FMyThread) then
begin
ProgressBar1.Position := FMyThread.CurrValue;
labResult.Caption := IntToStr(FMyThread.CalcResult);
labThreadStateInfo.Caption := FMyThread.ThreadStateInfo;
end;
end;
{ TMyThread }
constructor TMyThread.Create(MaxValue: Integer);
begin
FMaxValue := MaxValue;
inherited Create(False);
end;
procedure TMyThread.Execute;
begin
ThreadStateInfo := 'Start';
while FCurrValue < FMaxValue do
begin
if Terminated then Break;
Inc(FCurrValue);
FResult := FResult + FCurrValue;
ThreadStateInfo := Format('Progress: %f%%',
[FCurrValue / FMaxValue * 100]);
end;
ThreadStateInfo := 'Complete';
end;
function TMyThread.GetThreadStateInfo: string;
begin
// Защищаем строку с помощью критической секции. Если её убрать,
// то в главном потоке периодически будет возникать ошибка
// "Invalid pointer operation" либо "Out of memory"
StringProtectSection.Enter; // Входим в режим защиты
Result := FThreadStateInfo;
StringProtectSection.Leave; // Выходим из режима защиты
end;
procedure TMyThread.SetThreadStateInfo(const Value: string);
begin
StringProtectSection.Enter; // Входим в режим защиты
FThreadStateInfo := Value;
StringProtectSection.Leave; // Выходим из режима защиты
end;
end.
|
unit in0k_hintDOC_core_parserSettings;
{$mode objfpc}{$H+}
{/$define _DEBUG_}
{$ifnDef _DEBUG_}
{$define _INLINE_}
{$endIf}
interface
uses
Classes, SysUtils;
type
// Настройки для ПАРСЕРА
tInkHD_parserSettings=record
tokenLabel:string; //< выбранный МеткаТокена (если="" => НЕ установлен)
tokenStart:string; //< начальный токен, ПОСЛЕ которого парсим
tokenFinal:string; //< конечный токен, ДО которого парсим
tokenStrEX:string; //< токен "Строки-РАСШИРИТЕЛЬ"
//---
tokenStartMustBe:boolean; //< начальный токен ДОЛЖЕН быть
tokenFinalMustBe:boolean; //< конечный токен ДОЛЖЕН быть
//---
extractStringEXT:boolean; //< выделять "символ Строки-РАСШИРИТЕЛЬ"
end;
pInkHD_parserSettings=^tInkHD_parserSettings;
//-------------------------------------
procedure InkHD_parserSettings_CLR(const obj:pInkHD_parserSettings);
function InkHD_parserSettings_CRT:pInkHD_parserSettings;
procedure InkHD_parserSettings_CRT(out obj:pInkHD_parserSettings);
procedure InkHD_parserSettings_DST(const obj:pInkHD_parserSettings);
//---
procedure InkHD_parserSettings_SET__tokenLabel(const obj:pInkHD_parserSettings; const value:string); {$ifDef _INLINE}inline;{$endIf}
function InkHD_parserSettings_GET__tokenLabel(const obj:pInkHD_parserSettings):string; {$ifDef _INLINE}inline;{$endIf}
procedure InkHD_parserSettings_SET__tokenStart(const obj:pInkHD_parserSettings; const value:string); {$ifDef _INLINE}inline;{$endIf}
function InkHD_parserSettings_GET__tokenStart(const obj:pInkHD_parserSettings):string; {$ifDef _INLINE}inline;{$endIf}
procedure InkHD_parserSettings_SET__tokenFinal(const obj:pInkHD_parserSettings; const value:string); {$ifDef _INLINE}inline;{$endIf}
function InkHD_parserSettings_GET__tokenFinal(const obj:pInkHD_parserSettings):string; {$ifDef _INLINE}inline;{$endIf}
procedure InkHD_parserSettings_SET__tokenStrEX(const obj:pInkHD_parserSettings; const value:string); {$ifDef _INLINE}inline;{$endIf}
function InkHD_parserSettings_GET__tokenStrEX(const obj:pInkHD_parserSettings):string; {$ifDef _INLINE}inline;{$endIf}
//---
procedure InkHD_parserSettings_SET__tokenStartMustBe(const obj:pInkHD_parserSettings; const value:boolean); {$ifDef _INLINE}inline;{$endIf}
function InkHD_parserSettings_GET__tokenStartMustBe(const obj:pInkHD_parserSettings):boolean; {$ifDef _INLINE}inline;{$endIf}
procedure InkHD_parserSettings_SET__tokenFinalMustBe(const obj:pInkHD_parserSettings; const value:boolean); {$ifDef _INLINE}inline;{$endIf}
function InkHD_parserSettings_GET__tokenFinalMustBe(const obj:pInkHD_parserSettings):boolean; {$ifDef _INLINE}inline;{$endIf}
procedure InkHD_parserSettings_SET__extractStringEXT(const obj:pInkHD_parserSettings; const value:boolean); {$ifDef _INLINE}inline;{$endIf}
function InkHD_parserSettings_GET__extractStringEXT(const obj:pInkHD_parserSettings):boolean; {$ifDef _INLINE}inline;{$endIf}
implementation
procedure InkHD_parserSettings_CLR(const obj:pInkHD_parserSettings);
begin
with obj^ do begin
tokenLabel:='';
tokenStart:='';
tokenFinal:='';
tokenStrEX:='';
//---
tokenStartMustBe:=false;
tokenFinalMustBe:=false;
extractStringEXT:=false;
end;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function InkHD_parserSettings_CRT:pInkHD_parserSettings;
begin
new(result);
InkHD_parserSettings_CLR(result);
end;
procedure InkHD_parserSettings_CRT(out obj:pInkHD_parserSettings);
begin
obj:=InkHD_parserSettings_CRT;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
procedure InkHD_parserSettings_DST(const obj:pInkHD_parserSettings);
begin
{$ifDef _DEBUG_}
Assert( Assigned(obj) ,'InkHD_parserSettings_DST: obj isNULL');
{$endIf}
InkHD_parserSettings_CLR(obj); //< параноя
dispose(obj)
end;
//------------------------------------------------------------------------------
procedure InkHD_parserSettings_SET__tokenLabel(const obj:pInkHD_parserSettings; const value:string);
begin
obj^.tokenLabel:=value;
end;
function InkHD_parserSettings_GET__tokenLabel(const obj:pInkHD_parserSettings):string;
begin
result:=obj^.tokenLabel;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
procedure InkHD_parserSettings_SET__tokenStart(const obj:pInkHD_parserSettings; const value:string);
begin
obj^.tokenStart:=value;
end;
function InkHD_parserSettings_GET__tokenStart(const obj:pInkHD_parserSettings):string;
begin
result:=obj^.tokenStart;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
procedure InkHD_parserSettings_SET__tokenFinal(const obj:pInkHD_parserSettings; const value:string);
begin
obj^.tokenFinal:=value;
end;
function InkHD_parserSettings_GET__tokenFinal(const obj:pInkHD_parserSettings):string;
begin
result:=obj^.tokenFinal;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
procedure InkHD_parserSettings_SET__tokenStrEX(const obj:pInkHD_parserSettings; const value:string);
begin
obj^.tokenStrEX:=value;
end;
function InkHD_parserSettings_GET__tokenStrEX(const obj:pInkHD_parserSettings):string;
begin
result:=obj^.tokenStrEX;
end;
//------------------------------------------------------------------------------
procedure InkHD_parserSettings_SET__tokenStartMustBe(const obj:pInkHD_parserSettings; const value:boolean);
begin
obj^.tokenStartMustBe:=value;
end;
function InkHD_parserSettings_GET__tokenStartMustBe(const obj:pInkHD_parserSettings):boolean;
begin
result:=obj^.tokenStartMustBe;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
procedure InkHD_parserSettings_SET__tokenFinalMustBe(const obj:pInkHD_parserSettings; const value:boolean);
begin
obj^.tokenFinalMustBe:=value;
end;
function InkHD_parserSettings_GET__tokenFinalMustBe(const obj:pInkHD_parserSettings):boolean;
begin
result:=obj^.tokenFinalMustBe;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
procedure InkHD_parserSettings_SET__extractStringEXT(const obj:pInkHD_parserSettings; const value:boolean);
begin
obj^.extractStringEXT:=value;
end;
function InkHD_parserSettings_GET__extractStringEXT(const obj:pInkHD_parserSettings):boolean;
begin
result:=obj^.extractStringEXT;
end;
end.
|
{ This file is part of CodeSharkFCs
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
}
unit FreeCad;
{$IFDEF FPC} {$MODE Delphi} {$ENDIF}
// Getting Path from Shape from https://www.freecadweb.org/wiki/index.php?title=Path_scripting
// - use to replace PathKurveUtils?
// Assign the shape of wire Part to a normal Path object, using Path.fronShape() script function
// (or more powerful Path.fronShapes()). By giving as parameter a wire Part object,
// its path will be automatically calculated from the shape.
// Note that in this case the placement is automatically set to the first point of the wire,
// and the object is therefore not movable anymore by changing its placement.
// To move it, the underlying shape itself must be moved.
// path0 = Path.fromShapes(wire0, start=wire0.Vertexes[0].Point, preamble=False, verbose=False)
// will require creation of
// To Fix:
// The selection observer script is very simple.
// It assumes it is dealing with edges or points.
// At this time is does not work well with Faces.
// look at ..\FreeCadNotes\ListSelectedObjects.py on how to parse thru all components of an object
// (find the componentv via name? or label? then output its geometry?)
// Floating point division by zero when first run import (python 3.6)
// add MaskFPUExceptions(True);
// before loading the python library and before executing each script.
// see https://github.com/pyscripter/python4delphi/issues/69
// Py_Initialize raised exception class External: ?
// set PythonEngine1.SetPythonHome to PythonHome in PythonEngine1BeforeLoad
// Error - could not load a Python engine
// FreeCAD does not ?always? load all the required Python files for python4delphi to interface properly.
// Installing python from python.org (currently version Python 3.6.6). Fixes this issue.
// Error - This application failed to start because it could not find or load the Qt platform plugin "windows"
// Problem with QT5 looking for ..\platforms\ in the directory of the executable (in this case CodeSharkFC.exe).
// You should be able to set environment variables to point to ..\FreeCAD19\bin\platforms but I have not had any luck with this.
// Work around is to copy contents of ..\FreeCAD19\bin\platforms to ..\CodeSharkFC\platforms
// Notes for developement:
// Selecting mulitple circles to return location to editor
// look at Shift+B creates selection box
// look up way to parse all selected elements
// for o in Gui.Selection.getSelectionEx():
// print o.ObjectName
// for s in o.SubElementNames:
// print "name: ",s
// for s in o.SubObjects:
// print "object: ",s
// the python wrappers into libarea are created via boost python.
// look in: \FreeCAD-0.xx\src\Mod\Path\libarea\PythonStuff
// we may need to clean up our selector script (way in which we determine if selection is point circle line etc...
// see use of geomType in cleanedges()
// defined in \FreeCAD\Mod\Path\PathScripts\PathUtils
// This also shows how to convert BSplines and Bezier to arcs add to pick geometry??
// procedure WrtArc(InData : TArray<String>);
// look at the our selector script and
// procedure WrtUser(Id : Integer; InData : TArray<String>);
// -- load and save params to ini file (SetFCparmsFrm.LoadIni SetFCparmsFrm.SaveIni)
// FreeCAD interface via python4delphi
/// / THIS IS IMPORTANT READ BELOW !!!! //////
// P4D uses a define (DEFINE PYTHONxx) to build for a specific python version,
// we need to set and recompile based on what version of Python FreeCAD is bundled with
// current version is Python36 and PYTHON36 is defined in
// C:\...\python4delphi\PythonForDelphi\Components\Sources\Core\Definition.Inc
// If you are getting a message about not finding python36.dll check the following:
// Did you set the default python version in:
// ..\python4delphi-master\PythonForDelphi\Components\Sources\Core\Definition.inc ?
// PythonEngine1 properties set correctly, especially:
// PyFlags -> pgIgnorEnvironmentFlag
// DLLName -> python36.dll
// UseLastKnownVersion -> False
// We also depend on the following values being defined in CodeSharkFC.ini
// [Paths]
// PythonHome=C:\FreeCad\bin
// FreeCadMod=C:\FreeCad\Mod
// Then set these values with
// PythonEngine1.SetPythonHome to PythonHome
// PythonEngine1.DllPath to PythonHome
// We want (need?) to have P4D use the python interpreter imbedded with FreeCad, to do this we need tell the pythonengine where to look.
// see PythonEngine1BeforeLoad
// PythonEngine1.DllPath := Trim(SetFCparmsFrm.PythonHome.Text);
// note: if we set at design time it does not seem to take.
// Steps taken to fire off FreeCAD
// Feed the python interpreter the following scripts
// LoadStartupScript
// LoadPanelViewScript
// LoadObserverScript
// on exit we close FreeCAD
// LoadStopScript FreeCADGui.getMainWindow().close()
interface
uses
{$IFDEF FPC}
{$IFDEF MSWINDOWS}
Windows, //JwaPsApi, JwaTlHelp32,
{$ELSE}
Process,
{$ENDIF}
Classes, SysUtils, FileUtil, Forms, Controls, Graphics,
ComCtrls,
Dialogs, ExtCtrls, StdCtrls, PythonEngine, PythonGUIInputOutput;
{$ELSE}
Windows, PsAPI, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, PythonEngine, Vcl.StdCtrls,
Vcl.PythonGUIInputOutput, Vcl.ComCtrls, Vcl.ExtCtrls, TLHelp32;
{$ENDIF}
type
// { TFreeCadFrm }
{ TFreeCadFrm }
TFreeCadFrm = class(TForm)
{$IFDEF FPC}
Label5: TLabel;
Label6: TLabel;
{$ENDIF}
PythonEngine1: TPythonEngine;
ExeMemo: TMemo;
PyOutMemo: TMemo;
Label1: TLabel;
Label2: TLabel;
btnExeFC: TButton;
Panel1: TPanel;
cbRawOut: TCheckBox;
pnlPickGeo: TPanel;
cbIncludeZ: TCheckBox;
Label3: TLabel;
PythonModule1: TPythonModule;
UpDown1: TUpDown;
EdtUpDown: TEdit;
pnlPath: TPanel;
cbBypassSel: TCheckBox;
btnSetTool: TButton;
btnGenPath: TButton;
Label4: TLabel;
lblEdgeCnt: TLabel;
PythonDelphiVar1: TPythonDelphiVar;
btnPathShapes: TButton;
PythonGUIInputOutput1: TPythonGUIInputOutput;
procedure btnExeFCClick(Sender: TObject);
procedure PythonModule1Initialization(Sender: TObject);
procedure LoadStartupScript;
procedure LoadWindowScript;
procedure LoadPanelViewScript;
procedure LoadObserverScript;
procedure LoadWindowActionScript(Action: integer);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure btnGenPathClick(Sender: TObject);
procedure btnSetToolClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnPathShapesClick(Sender: TObject);
private
procedure WrtDebugInfo(Indata: array of string);
procedure WrtPoint(Indata: array of string);
procedure WrtLine(Indata: array of string);
procedure WrtCircle(Indata: array of string);
procedure WrtArc(Indata: array of string);
procedure WrtArvMove(GCode, PosX, PosY, PosZ, CtrX, CtrY, CtrZ: string);
procedure WrtUser(Id: integer; Indata: array of string);
procedure WrtToEditor(Data: string);
procedure OutPutPoint(PosX, PosY, PosZ: string);
procedure SaveLastPoint(PosX, PosY, PosZ: string);
function ExeScript(ScriptLns: TStringList; ScriptFname: TFilename): boolean;
function IsSamePoint(PosX, PosY, PosZ: string): boolean;
public
{ Public declarations }
end;
function WrtArgsToEditor(self, args: PPyObject): PPyObject; cdecl;
function ParseFreeCADString(Indata: string): boolean;
var
FreeCadFrm: TFreeCadFrm;
FreeCADPid: integer; // PID of FreeCAD process, returned by startup script
implementation
{$IFDEF FPC}
{$R *.lfm}
{$ELSE}
{$R *.dfm}
{$ENDIF}
uses
srcMain, SetFCparms, SetTool;
const
// Define data line sent back by FreeCAD Note, Paramsz must = number of fields passed, it sizes array used to store
// individual fields!
CrLf = #13#10;
// Array locations for individual passed fields
Geo = 0;
X1 = 1;
Y1 = 2;
Z1 = 3;
X2 = 4;
Y2 = 5;
Z2 = 6;
Rad = 7;
CtrX = 8;
CtrY = 9;
CtrZ = 10;
ParamSz = 10; // Constant to size array to hold fields
// Define Geo values sent back by FreeCAD
Path = 'path';
Point = 'point';
Circle = 'circle';
Arc = 'arc';
Line = 'line';
User1 = 'user1';
User2 = 'user2';
User3 = 'user3';
OtherData = 'otherdata';
Unknown = 'unknown';
// custom script files found in AppData (C:\Users\**username**\AppData\Local\CodeSharkFC)
StartupScript = 'StartupScript.py';
PanelViewScript = 'PanelViewScript.py';
ObserverScript = 'ObserverScript.py';
WindowCloseScript = 'WindowCloseScript.py';
WindowHideScript = 'WindowHideScript.py';
WindowShowScript = 'WindowShowScript.py';
cFreeCADScreenName = 'FreeCAD(CSFC';
//Name we will assign to FreeCAD window in LoadWindowScript
// LoadWindowActionScript actions
WindowShow = 0;
WindowHide = 1;
WindowClose = 2;
var
StartupLoaded, PanelViewLoaded, ObserverLoaded: boolean;
ScriptLns: TStringList;
LastX, LastY, LastZ: string; // last point processed
FreeCADScreenName: string;
//Name we will assign to FreeCAD window in LoadWindowScript
FreeCADFound: boolean; // Our FreeCAD Screen Name Found with FindFreeCADWindow
function WrtArgsToEditor(self, args: PPyObject): PPyObject; cdecl;
// define the function we will use in the python scripts to get the data into the codeshark programing window
// NOTE*** There is something stange with referenceing objects on FreeCad dialog in the functions that will
// be called via python. Using the local namespace ie FreeCadFrm.lblEdgeCnt.Caption or FreeCADFrm.PyOutMemo.Lines.Add('xyz')
// results in an access viloation. I suspect this is because FreeCADFrm is dynamically created in srcMain.
// However, if we reference it from the creator (scrMain ie srcMain.MyFreeCADFrm.lblEdgeCnt.Caption ) we can get this to work
// lots more work to do here, lets just get the basics to work for now
begin
with GetPythonEngine do
begin
srcMain.MyFreeCADFrm.lblEdgeCnt.Caption :=
srcMain.MyFreeCADFrm.PythonDelphiVar1.ValueAsString;
ParseFreeCADString(PyObjectAsString(args));
// FrmMain.Synedit.Lines.Add(PyObjectAsString(args));
Result := ReturnNone;
end;
end;
function ParseFreeCADString(Indata: string): boolean;
// Format of Indata:
// (Geometry,Point1_X,Point1_Y,Point1_Z,Point2_X,Point2_Y,Point2_Z,Radius,Center_X,Center_Y,Center_Z)
// Geometry - 'point', 'circle', 'line', 'User1', 'User2', 'User3', 'unknown (with type after unknown)
// 'User1', 'User2', 'User3', - not sure what the point of this is but add for flexiblity
// Point1_X,Point1_Y,Point1_Z,Point2_X,Point2_Y,Point2_Z,Radius,Center_X,Center_Y,Center_Z - 5 place decimal string value or empty string
// ie: ('line', '0.0', '0.0', '0.0', '50.0', '0.0', '0.0', '', '', '', '')
var
Params: array [0 .. ParamSz] of string;
TempStr, ParseParam, MyPid: string;
i, x: integer;
begin
Result := True;
TempStr := StringReplace(Indata, '(', '', [rfReplaceAll, rfIgnoreCase]);
TempStr := StringReplace(TempStr, ')', '', [rfReplaceAll, rfIgnoreCase]);
TempStr := StringReplace(TempStr, '''', '', [rfReplaceAll, rfIgnoreCase]);
TempStr := StringReplace(TempStr, ' ', '', [rfReplaceAll, rfIgnoreCase]);
x := 0;
ParseParam := '';
if length(TempStr) > 0 then
begin
for i := 1 to length(TempStr) do
begin
if TempStr[i] = ',' then
begin
Params[x] := ParseParam;
Inc(x);
ParseParam := '';
if x > ParamSz then
begin
// prevent array overflow condition, someone added fields to passed string but did not increase Paramsz constant to match
ShowMessage
('More Fields passed than expected, Unable to complete parsing' +
CrLf + '(' + TempStr + ')');
if SetFCparms.ExtraDebugging then
FreeCadFrm.WrtToEditor('(' + TempStr + ')');
Result := False;
Exit;
end;
end
else
ParseParam := ParseParam + TempStr[i];
end;
Params[x] := ParseParam; // save last parameter
end
else // somethng rotten here, exit with return code falses
begin
Result := False;
Exit;
end;
// FrmMain.SynEdit.Lines.Add(TempStr);
// Params := TempStr.Split([',']);
if srcMain.MyFreeCADFrm.cbRawOut.Checked then
srcMain.MyFreeCADFrm.PyOutMemo.Lines.Add(Indata);
if Params[Geo] = OtherData then
// look to see what data we send back from FreeCAD
begin
if Params[X1] = 'PID' then
begin
// we have FreeCAD windows PID, save for shutdown testing
MyPid := Params[Y1];
srcMain.MyFreeCADFrm.PyOutMemo.Lines.Add('FreeCAD PID = :' + MyPid + ':');
try
FreeCADPid := StrToInt(MyPid)
except
FreeCADPid := 0
end;
end
else
srcMain.MyFreeCADFrm.PyOutMemo.Lines.Add('Unknow Other Data Passed: ' + Indata);
end
else if Params[Geo] = Path then
// generate path
begin
// add the path statements to the memo
// for now all code dumps out in X1 data position
FreeCadFrm.WrtToEditor(Params[X1]);
end
else
// write selections to the editor memo only if cbBypassSel not checked
begin
if ExtraDebugging then
FreeCADFrm.WrtDebugInfo(Params);
if not (srcMain.MyFreeCADFrm.cbBypassSel.Checked) then
if (Params[Geo] = Point) then
// point type
FreeCADFrm.WrtPoint(Params)
else if (Params[Geo] = Line) then
// line type
FreeCADFrm.WrtLine(Params)
else if (Params[Geo] = Circle) then
// circle type
FreeCADFrm.WrtCircle(Params)
else if (Params[Geo] = Arc) then
// arc type
FreeCADFrm.WrtArc(Params)
else if Params[Geo] = User1 then
// User1
FreeCADFrm.WrtUser(1, Params)
else if Params[Geo] = User2 then
// User2
FreeCADFrm.WrtUser(2, Params)
else if Params[Geo] = User3 then
// User3
FreeCADFrm.WrtUser(3, Params)
else
srcMain.MyFreeCADFrm.PyOutMemo.Lines.Add('Unknow Data Passed: ' + Indata);
end;
end;
// following is how we determine if the FreeCAD Window Name (we assigned in PanelViewScript.py) is still active
// we need to have a linux and windows version of this code
// so here it is
// Note in both versions of FindFreeCADWindow we shamelessly use ths global variables:
// FreeCADScreenName Name we will assign to FreeCAD window in LoadWindowScript
// FreeCADFound Our FreeCAD Screen Name Found T/F
{$IFDEF LINUX}
procedure FindFreeCADWindow;
var
AProcess: TProcess;
List: TStringList = nil;
Result: boolean;
i: integer;
begin
Result := False;
FreeCADFound := False;
// use wmctrl to get a list of all windows
AProcess := TProcess.Create(nil);
AProcess.Executable := 'wmctrl';
AProcess.Parameters.Add('-l');
AProcess.Options := AProcess.Options + [poWaitOnExit, poUsePipes];
try
AProcess.Execute;
Result := (AProcess.ExitStatus = 0); // says at least one packet got back
except
on
E: EProcess do
ShowMessage('Process execution failed: ' + E.Message);
end;
if Result then
begin
List := TStringList.Create;
List.LoadFromStream(AProcess.Output); // Get the output from wmcttl
for i := 0 to List.Count - 1 do // look for the our FreeCAD window
if Pos(FreeCADScreenName, List[i]) > 0 then
begin
FreeCADFound := True;
Exit;
end;
List.Free;
AProcess.Free;
end
else
ShowMessage('wmctrl returned no windows');
end;
{$ELSE}
function EnumWinProc(wHandle: hWnd; lparam: integer): Bool; stdcall;
const
MAX_TEXT = MAX_PATH;
var
strText, strClass: array [0 .. MAX_TEXT] of char;
IsAppMainWin: boolean;
ProcId: cardinal;
begin
// Check if the window is a application main window.
IsAppMainWin :=
(GetWindow(wHandle, GW_OWNER) = 0) and // Not owned by other windows
(GetParent(wHandle) = 0) and // Does not have any parent
(GetWindowLong(wHandle, GWL_EXSTYLE) and WS_EX_TOOLWINDOW = 0); // Not a tool window
if IsAppMainWin then
begin
GetWindowText(wHandle, strText, MAX_TEXT);
// GetClassName(wHandle, strClass, MAX_TEXT);
// GetWindowThreadProcessID(wHandle, ProcId);
if strText = FreeCADScreenName then
FreeCADFound := True;
end;
Result := True;
end;
procedure FindFreeCADWindow;
var
FirstWnd: cardinal;
begin
FreeCADFound := False;
EnumWindows(@EnumWinProc, LPARAM(@FirstWnd));
end;
{$ENDIF}
function EnsurePathHasDoubleSlashes(Path: string): string;
begin
Result := StringReplace(Path, '\', '\\', [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '\\\', '\\', [rfReplaceAll, rfIgnoreCase]);
end;
function TFreeCadFrm.IsSamePoint(PosX, PosY, PosZ: string): boolean;
begin
if (PosX = LastX) and (PosY = LastY) and (PosZ = LastZ) then
Result := True
else
Result := False;
end;
procedure TFreeCadFrm.SaveLastPoint(PosX, PosY, PosZ: string);
begin
LastX := PosX;
LastY := PosY;
LastZ := PosZ;
end;
procedure TFreeCadFrm.OutPutPoint(PosX, PosY, PosZ: string);
var
MemoLine: string;
begin
if SetFCparms.FormatForPathDisplay then
MemoLine := 'G1 X' + PosX + ' Y' + PosY
else
MemoLine := 'X' + PosX + ' Y' + PosY;
if srcMain.MyFreeCADFrm.cbIncludeZ.Checked then
MemoLine := MemoLine + ' Z' + PosZ;
WrtToEditor(MemoLine);
SaveLastPoint(PosX, PosY, PosZ);
end;
procedure TFreeCadFrm.WrtDebugInfo(Indata: array of string);
begin
// some debugging stuff
WrtToEditor('(Last XYZ: ' + LastX + ' ' + LastY + ' ' + LastZ + ')');
WrtToEditor('(Geo: ' + Indata[Geo] + ')');
WrtToEditor('(XYZ1: ' + Indata[X1] + ' ' + Indata[Y1] + ' ' + Indata[Z1] + ')');
WrtToEditor('(XYZ2: ' + Indata[X2] + ' ' + Indata[Y2] + ' ' + Indata[Z2] + ')');
WrtToEditor('(Rad: ' + Indata[Rad] + ' Cntr XYZ: ' + Indata[CtrX] +
' ' + Indata[CtrY] + ' ' + Indata[CtrZ] + ')');
end;
procedure TFreeCadFrm.WrtPoint(Indata: array of string);
// Var
// MemoLine: String;
begin
OutPutPoint(Indata[X1], Indata[Y1], Indata[Z1]);
end;
procedure TFreeCadFrm.WrtLine(Indata: array of string);
// Var
// MemoLine: String;
begin
if length(LastX) > 0 then // Have we output at least one point?
// Yes, is it the same as the start of this line?
// if so only output ending point
if IsSamePoint(Indata[X1], Indata[Y1], Indata[Z1]) then
OutPutPoint(Indata[X2], Indata[Y2], Indata[Z2])
// if not is it the same as the end of this line?
// if so output point at other end of line (flip direction)
else if IsSamePoint(Indata[X2], Indata[Y2], Indata[Z2]) then
OutPutPoint(Indata[X1], Indata[Y1], Indata[Z1])
else
begin // not contiguous with last point, output both points as received
OutPutPoint(Indata[X1], Indata[Y1], Indata[Z1]);
OutPutPoint(Indata[X2], Indata[Y2], Indata[Z2]);
end
else
begin // no previous point, output as received
OutPutPoint(Indata[X1], Indata[Y1], Indata[Z1]);
OutPutPoint(Indata[X2], Indata[Y2], Indata[Z2]);
end;
end;
procedure TFreeCadFrm.WrtCircle(Indata: array of string);
var
SaveFormatForPathDisplay: boolean;
// for circles we write out center point
begin
SaveFormatForPathDisplay := FormatForPathDisplay;
// for circle center point never send g code regarless of flag
FormatForPathDisplay := False;
OutPutPoint(Indata[CtrX], Indata[CtrY], Indata[CtrZ]);
FormatForPathDisplay := SaveFormatForPathDisplay;
end;
procedure TFreeCadFrm.WrtArc(Indata: array of string);
// WrtArc - We need to determine if arc is G2 (cw) or G3 (ccw)
// The way we do this is assume all arcs are CCW in open cascade (OCC).
// So if the user's last point selected is the starting point of the arc, then the movement arc should be CCW (G3).
// If the user's last point selected is the ending point of the arc, then the the movement arc should be CW (G2)
// NOTE we are assuming XY Plane (G17) !!!!!
begin
if length(LastX) > 0 then // Have we output at least one point?
else
begin
// started on arc, can only assume CCW
// output start point
// assign to last point
OutPutPoint(Indata[X1], Indata[Y1], Indata[Z1]);
end;
if IsSamePoint(Indata[X1], Indata[Y1], Indata[Z1]) then
// Start point of arc is at last position, G3 move
WrtArvMove('G3', Indata[X2], Indata[Y2], Indata[Z2], Indata[CtrX],
Indata[CtrY], Indata[CtrZ])
else if IsSamePoint(Indata[X2], Indata[Y2], Indata[Z2]) then
// End point of arc is at last postions, G2 move
WrtArvMove('G2', Indata[X1], Indata[Y1], Indata[Z1], Indata[CtrX],
Indata[CtrY], Indata[CtrZ])
else
ShowMessage
('Unable to calculate Arc Move, Suggest Selection of End Point Elements vs Edges (Lines)');
end;
procedure TFreeCadFrm.WrtArvMove(GCode, PosX, PosY, PosZ, CtrX, CtrY, CtrZ: string);
var
Ipos: double;
// offset from starting x (LastX) coordinate to center x coordinate
JPos: double;
// offset from starting y (LastY) coordinate to center y coordinate
GCodeString: string;
begin
try
Ipos := (strTofloat(LastX) - strTofloat(CtrX)) * -1.0;
// calculate offset from starting x (LastX) coordinate to center x coordinate
JPos := (strTofloat(LastY) - strTofloat(CtrY)) * -1.0; // same for y
GCodeString := GCode + 'X' + PosX + 'Y' + PosY + 'I' + floatToStr(Ipos) +
'J' + floatToStr(JPos);
WrtToEditor(GCodeString);
SaveLastPoint(PosX, PosY, PosZ); // save ending postion
except
// catch conversion issues here
on E: Exception do
ShowMessage('Unable to calculate arc: ' + E.Message);
end;
end;
procedure TFreeCadFrm.WrtUser(Id: integer; Indata: array of string);
// user defined, for now we just add second passed parameter
begin
WrtToEditor(Indata[X1]);
end;
{ procedure TFreeCadFrm.XScriptClick(Sender: TObject);
begin
if ExeMemo.Lines.Count > 0 then
Begin
ScriptLns.Clear;
ScriptLns.AddStrings(ExeMemo.Lines);
ExeScript(ScriptLns);
End;
end; }
procedure TFreeCadFrm.WrtToEditor(Data: string);
begin
if FrmMain.SynEdit.Lines.Text = '' then
FrmMain.SynEdit.Lines.Insert(0, Data)
else
FrmMain.SynEdit.Lines.Insert(FrmMain.SynEdit.CaretY, Data);
FrmMain.SynEdit.CaretY := FrmMain.SynEdit.CaretY + 1;
end;
procedure TFreeCadFrm.PythonModule1Initialization(Sender: TObject);
begin
// Add the delphi defined fuction into the python interpreter
// to use in python:
// import CaptureFC <-- this is the name we gave the module (PythonModule1.ModuleName)
// CaputureFC.WrtArgs('1 2 3', 1) <- WrtArgs is the name of the method (assigned below)
// this command with result in ('1 2 3', 1) being added to the editor window
// CaputureFC.WrtArgs(x) <- this will result in ('1 2 3') begin added to the editor window
with Sender as TPythonModule do
begin
AddMethod('WrtArgs', WrtArgsToEditor,
'Function writes args to CodeShark Editor');
end;
end;
procedure TFreeCadFrm.btnGenPathClick(Sender: TObject);
var
PathKurveStr, MsgText, ScriptFn: string;
begin
// create script to generate cnc path on selected edges
// we break process down into steps to hopefully catch errors and stop the process
// at the error
// we shall see how well it works......
// Edges are saved in MyEdgeList as user clicks on object (line or arc for now)
if StrToInt(PythonDelphiVar1.ValueAsString) <= 1 then
begin
MsgText := 'Not Enough Edges Selected (>1), Path generation not possible';
MessageDlg(MsgText, mtWarning, [mbOK], 0);
Exit;
end;
ScriptLns.Clear;
ExeMemo.Lines.Clear;
ScriptLns.Add('print(''Edges: '' + str(len(MyEdgeList)))');
PyOutMemo.Lines.Add('Execute script to get the edge list');
if not (ExeScript(ScriptLns, '')) then
Exit;
// create MyCurve
ScriptLns.Clear;
ExeMemo.Lines.Clear;
ScriptFn := FrmMain.AppDataPath + PathDelim + '1CreateCurve.py';
ScriptLns.Add('if len(MyEdgeList) > 1:'); // need at least 2 edges
PathKurveStr := ' MyCurve = PathKurveUtils.makeAreaCurve(MyEdgeList,';
if SetToolFrm.rbCCW.Checked then
PathKurveStr := PathKurveStr + '''CCW'')'
else
PathKurveStr := PathKurveStr + '''CW'')';
ScriptLns.Add(PathKurveStr);
PyOutMemo.Lines.Add('Execute script to create MyCurve');
PyOutMemo.Lines.Add(PathKurveStr);
if not (ExeScript(ScriptLns, ScriptFn)) then
Exit;
// create the PathKurveUtils.profile function call
ScriptLns.Clear;
ExeMemo.Lines.Clear;
ScriptFn := FrmMain.AppDataPath + PathDelim + '2PathKurveUtilsProfile.py';
ScriptLns.Add('if len(MyEdgeList) > 1:'); // need at least 2 edges
PathKurveStr := ' goutput = PathKurveUtils.profile(MyCurve, ';
if SetToolFrm.rbOnLine.Checked then
PathKurveStr := PathKurveStr + '''On'', '
else if SetToolFrm.rbRightofLine.Checked then
PathKurveStr := PathKurveStr + '''Right'', '
else
PathKurveStr := PathKurveStr + '''Left'', ';
PathKurveStr := PathKurveStr + SetToolFrm.RadiusEdt.Text + ', ' +
SetToolFrm.VertFeedEdt.Text + ', ' + SetToolFrm.HorzFeedEdt.Text +
', ' + SetToolFrm.OffsetExtraEdt.Text + ', ' + SetToolFrm.RapidSafeSpaceEdt.Text +
', ' + SetToolFrm.ClearanceEdt.Text + ', ' + SetToolFrm.StartDepthEdt.Text +
', ' + SetToolFrm.StepdownEdt.Text + ', ' + SetToolFrm.FinalDepthEdt.Text + ')';
ScriptLns.Add(PathKurveStr);
PyOutMemo.Lines.Add('Execute script PathKurveUtils.profile function call');
PyOutMemo.Lines.Add(PathKurveStr);
if not (ExeScript(ScriptLns, ScriptFn)) then
Exit;
// send the gcode to the editor
ScriptLns.Clear;
ExeMemo.Lines.Clear;
ScriptFn := FrmMain.AppDataPath + PathDelim + '3GcodeToEditor.py';
ScriptLns.Add('if len(goutput) != 0:'); // any output?
ScriptLns.Add(' for gcodeln in goutput.splitlines():'); // any output?
ScriptLns.Add(' CaptureFC.WrtArgs(''' + Path +
''',gcodeln,'''','''','''','''','''','''','''','''','''')');
ScriptLns.Add('else:');
ScriptLns.Add(' CaptureFC.WrtArgs(''' + Path +
''','' error generating G-Code'','''','''','''','''','''','''','''','''','''')');
PyOutMemo.Lines.Add('Execute script Retrieve goutput ');
if not (ExeScript(ScriptLns, ScriptFn)) then
Exit;
// finally show the path
ScriptLns.Clear;
ScriptFn := FrmMain.AppDataPath + PathDelim + '4ShowPath.py';
// ExeMemo.Lines.Clear;
ScriptLns.Add('if len(goutput) != 0:'); // any output?
ScriptLns.Add(' p = Path.Path(goutput)');
ScriptLns.Add
(' myPath = FreeCAD.ActiveDocument.addObject("Path::Feature","Import")');
ScriptLns.Add(' myPath.Path = p');
ScriptLns.Add(' FreeCAD.ActiveDocument.recompute()');
ExeScript(ScriptLns, ScriptFn);
// clear the slected edge list
PyOutMemo.Lines.Add('Execute script Clear Edge List');
ScriptLns.Clear;
ScriptLns.Add('goutput = ''''');
ScriptLns.Add('MyEdgeList = []');
ScriptLns.Add('EdgeCnt.Value = 0');
lblEdgeCnt.Caption := '0';
ExeScript(ScriptLns, '');
end;
procedure TFreeCadFrm.btnPathShapesClick(Sender: TObject);
var
MsgText, Vector, ScriptFn: string;
begin
// NOTES https://wiki.freecadweb.org/Path_FromShapes/en
// Path FromShapes doesn't match the current Path workflow. For that reason it's moved to the experimental features.
// This tool generates tool-paths from Path Object edges. Tool-paths are uncompensated for tool radius.
// There is no Tool controller associated with the generated tool-paths .
// Path.fromShapes(shapes, start=Vector(), return_end=False arc_plane=1, sort_mode=1, min_dist=0.0, abscissa=3.0,
// nearest_k=3, orientation=0, direction=0, threshold=0.0, retract_axis=2, retraction=0.0, resume_height=0.0,
// segmentation=0.0, feedrate=0.0, feedrate_v=0.0, verbose=true, abs_center=false, preamble=true, deflection=0.01)
// Edges are saved in MyEdgeList as user clicks on object (line or arc for now)
if StrToInt(PythonDelphiVar1.ValueAsString) <= 1 then
begin
MsgText := 'Not Enough Edges Selected (>1), Path generation not possible';
MessageDlg(MsgText, mtWarning, [mbOK], 0);
Exit;
end;
ScriptLns.Clear;
ExeMemo.Lines.Clear;
ScriptLns.Add('print(''Edges: '' + str(len(MyEdgeList)))');
PyOutMemo.Lines.Add('Execute script to get the edge list');
if not (ExeScript(ScriptLns, '')) then
Exit;
// create Path FromShapes
ScriptLns.Clear;
ExeMemo.Lines.Clear;
ScriptFn := FrmMain.AppDataPath + PathDelim + 'PathFromShape.py';
ScriptLns.Add('if len(MyEdgeList) > 1:'); // need at least 2 edges
ScriptLns.Add(' aWire=Part.Wire(MyEdgeList)');
ScriptLns.Add(' obj = FreeCAD.ActiveDocument.addObject("Path::Feature","myPath")');
Vector := 'FreeCAD.Vector(' + SetToolFRM.StartXEdt.Text + ',' +
SetToolFRM.StartYEdt.Text + ',' + SetToolFRM.StartZEdt.Text + ')';
if SetToolFrm.rbCCW.Checked then
ScriptLns.Add(' obj.Path = Path.fromShapes(aWire, start=' +
Vector + ', orientation=0)')
else
ScriptLns.Add(' obj.Path = Path.fromShapes(aWire, start=' +
Vector + ', orientation=1)');
ScriptLns.Add(' p = obj.Path');
ScriptLns.Add(' for gcodeln in p.toGCode().splitlines():');
ScriptLns.Add(' CaptureFC.WrtArgs(''' + Path +
''',gcodeln,'''','''','''','''','''','''','''','''','''')');
PyOutMemo.Lines.Add('Execute script Retrieve goutput ');
if not (ExeScript(ScriptLns, ScriptFn)) then
Exit;
// clear the slected edge list
PyOutMemo.Lines.Add('Execute script Clear Edge List');
ScriptLns.Clear;
ScriptLns.Add('goutput = ''''');
ScriptLns.Add('MyEdgeList = []');
ScriptLns.Add('EdgeCnt.Value = 0');
lblEdgeCnt.Caption := '0';
ExeScript(ScriptLns, '');
end;
function TFreeCadFrm.ExeScript(ScriptLns: TStringList; ScriptFname: TFilename): boolean;
begin
Result := True;
ExeMemo.Lines.Assign(ScriptLns);
if Length(ScriptFname) > 0 then // if we passed a filename save the script text
ExeMemo.Lines.SaveToFile(ScriptFname);
// execute the script
try
MaskFPUExceptions(True);
PythonEngine1.ExecStrings(ExeMemo.Lines);
except
on E: Exception do
begin
ShowMessage('Exception On Generate Path Script, class name = ' +
E.ClassName + CrLf + 'Exception message = ' + E.Message);
Result := False;
end;
end;
end;
procedure TFreeCadFrm.btnSetToolClick(Sender: TObject);
begin
SetToolFrm.ShowModal;
end;
procedure TFreeCadFrm.FormClose(Sender: TObject; var Action: TCloseAction);
var
MsgText: string;
begin
Action := caHide;
if StartupLoaded then
LoadWindowActionScript(WindowHide);
end;
procedure TFreeCadFrm.FormCreate(Sender: TObject);
var
MyPyDllPath: string;
begin
ScriptLns := TStringList.Create;
StartupLoaded := False;
ObserverLoaded := False;
FreeCADFound := False;
FreeCADPid := -1;
LastX := '';
LastY := '';
LastZ := ''; // init last point position
ObserverLoaded := False; // observer not loaded at this point
// Set up PythonEngine to use python user selected (hopefully the FreeCAD Python Interperter
PythonEngine1.DllPath := Trim(SetFCparmsFrm.PythonHome.Text);
PythonEngine1.DllName := Trim(SetFCparmsFrm.PyDllName.Text);
PythonEngine1.RegVersion := SetFCparms.PyRegVersion;
{$IFDEF MSWINDOWS}
// need to set PYTHONHOME before startup or we will fail
// Note setting env PYTHONHOME does not seem to work, use dll call
PythonEngine1.SetPythonHome(SetFCparmsFrm.PythonHome.Text);
{$ENDIF}
MyPyDllPath := IncludeTrailingPathDelimiter(PythonEngine1.DllPath) +
PythonEngine1.DllName;
if not (FileExists(MyPyDllPath)) then
begin
ShowMessage('Cannot Find Python dll: ' + MyPyDllPath +
' Python dll path and or name not set, or set incorrectly');
ShowMessage('Cannot Start FreeCAD without Python!');
end
else
begin
PythonEngine1.LoadDll;
MaskFPUExceptions(True);
end;
end;
procedure TFreeCadFrm.FormDestroy(Sender: TObject);
var
MsgText: string;
begin
if StartupLoaded then
begin
// see if we still have a FreeCAD window (user did not close)
FindFreeCADWindow;
if FreeCADFound then
begin
LoadWindowActionScript(WindowClose);
// PythonEngine1.Finalize; we now autofinalize
end
else
begin
MsgText := 'The ' + FreeCADScreenName + ' Window Cannot Be Found.' + CrLf;
MsgText := MsgText + 'We Cannot Cleanly Unload The Interface To FreeCAD.'
+ CrLf;
MsgText := MsgText +
'THIS WILL MOST LIKELY RESULT IN AN APPLICATION ERROR WHEN THE PROGRAM IS CLOSED!'
+
CrLf;
MsgText := MsgText + 'PLEASE SAVE YOUR WORK NOW!' + CrLf;
MsgText := MsgText +
'In The Future, Please Close FreeCAD By Closing The CodeShark/FreeCAD Interface Dialog';
MessageDlg(MsgText, mtWarning, [mbOK], 0);
end;
end;
ScriptLns.Free;
end;
procedure TFreeCadFrm.FormShow(Sender: TObject);
begin
if StartupLoaded then
LoadWindowActionScript(WindowShow);
{$IFDEF FPC}
btnGenPath.Caption := 'Path by' + LineEnding + 'PathKurveUtils'; // no word wrap property on FPC
{$ENDIF}
end;
procedure TFreeCadFrm.LoadStartupScript;
var
scriptFn: string;
PyPath: string;
begin
ScriptLns.Clear;
ExeMemo.Lines.Clear;
scriptFn := FrmMain.AppDataPath + PathDelim + StartupScript;
// if custom script file exists and load custom specified
if SetFCparmsFrm.cbCustStart.Checked and FileExists(scriptFn) then
begin
// load ExeMemo.Lines from custom script file
Label2.Caption := scriptFn;
ExeMemo.Lines.LoadFromFile(scriptFn);
end
else
begin
// else load default
Label2.Caption := 'Default Startup Script';
ScriptLns.Add('import sys, os, fnmatch');
// paths needing to be set differ between Linux and Windows version
// setup here
{$IFDEF LINUX}
ScriptLns.Add('sys.path.append(''' + SetFCparmsFrm.FreeCadMod.Text + ''')');
{$ELSE}
PyPath := EnsurePathHasDoubleSlashes(SetFCparmsFrm.PythonHome.Text);
ScriptLns.Add('sys.path.append(''' + PyPath + ''')');
PyPath := EnsurePathHasDoubleSlashes(SetFCparmsFrm.PythonHome.Text);
ScriptLns.Add('sys.path.append(''' + PyPath +
'\\lib\\site-packages\\PySide2'')');
PyPath := EnsurePathHasDoubleSlashes(SetFCparmsFrm.FreeCadMod.Text);
ScriptLns.Add('sys.path.append(''' + PyPath + '\\Part'')');
ScriptLns.Add('sys.path.append(''' + PyPath + '\\Drawing'')');
PyPath := EnsurePathHasDoubleSlashes(ExtractFileDir(ParamStr(0)));
ScriptLns.Add('sys.path.append(''' + PyPath + ''')');
{$ENDIF}
// we expect to find PathKurveUtils & PathSelection in CodeSharkFC exe
// // directory, as of FC.17 it is no longer part of Path (PathScripts)
ScriptLns.Add('import FreeCADGui,FreeCAD');
ScriptLns.Add('from PySide import QtCore, QtGui');
// stop the start page from showing up
ScriptLns.Add
('grp=FreeCAD.ParamGet("User parameter:BaseApp/Preferences/General")');
ScriptLns.Add('grp.SetString("AutoloadModule","PartWorkbench")');
// turn of TUX
ScriptLns.Add
('grp=FreeCAD.ParamGet("User parameter:Tux/NavigationIndicator")');
ScriptLns.Add('grp.SetBool("Enabled",False)');
// finally import our module (must match ModuleName of TPythonModule on form!
ScriptLns.Add('import CaptureFC');
// finally fire up FreeCAD
ScriptLns.Add('FreeCADGui.showMainWindow()');
// our copied version of PathKurveUtils - note importing before showMainWindow messing FreeCADGui settings
ScriptLns.Add('import PathKurveUtils');
// and save the process id of FreeCAD
ScriptLns.Add('MyPid = os.getpid()');
ScriptLns.Add('CaptureFC.WrtArgs(''otherdata'',''PID'',MyPid)');
ScriptLns.Add('EdgeCnt.Value = 0');
ExeMemo.Lines.Assign(ScriptLns);
end;
// save copy of Script?
if not FileExists(scriptFn) then
ExeMemo.Lines.SaveToFile(scriptFn)
else if SetFCparmsFrm.cbOverWriteScript.Checked then
ExeMemo.Lines.SaveToFile(scriptFn);
// execute the script
try
MaskFPUExceptions(True);
PythonEngine1.ExecStrings(ExeMemo.Lines);
StartupLoaded := True;
PyOutMemo.Lines.Add('Startup Script Executed');
except
on E: Exception do
begin
ShowMessage('Exception On Startup Script, class name = ' +
E.ClassName + CrLf + 'Exception message = ' + E.Message);
end;
end;
end;
procedure TFreeCadFrm.LoadWindowScript;
var
scriptFn: string;
begin
//Include in FreeCAD window name the PID we are running as
FreeCADScreenName := cFreeCADScreenName + IntToStr(FreeCADPid) + ')';
ScriptLns.Clear;
ExeMemo.Lines.Clear;
Label2.Caption := 'Window Setting Script Script';
ScriptLns.Add('mainWindow = FreeCADGui.getMainWindow()');
// now mod the window to include pid in window title
ScriptLns.Add('mainWindow.setWindowTitle("' + FreeCADScreenName + '")');
// change the window flags to not include the close X on the main window
ScriptLns.Add
('flags = QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowMaximizeButtonHint | QtCore.Qt.CustomizeWindowHint');
ScriptLns.Add('mainWindow.setWindowFlags(flags)');
ScriptLns.Add('mainWindow.show()');
ExeMemo.Lines.Assign(ScriptLns);
// execute the script
try
MaskFPUExceptions(True);
PythonEngine1.ExecStrings(ExeMemo.Lines);
PanelViewLoaded := True;
PyOutMemo.Lines.Add('Window Setting Script Executed');
except
on E: Exception do
begin
ShowMessage('Exception On Window Setting Script, class name = ' +
E.ClassName + CrLf + 'Exception message = ' + E.Message);
end;
end;
end;
procedure TFreeCadFrm.LoadPanelViewScript;
var
scriptFn: string;
begin
ScriptLns.Clear;
ExeMemo.Lines.Clear;
scriptFn := FrmMain.AppDataPath + PathDelim + PanelViewScript;
// if custom script file exists and load custom specified
if SetFCparmsFrm.cbCustPanel.Checked and FileExists(scriptFn) then
begin
// load ExeMemo.Lines from custom script file
Label2.Caption := scriptFn;
ExeMemo.Lines.LoadFromFile(scriptFn);
end
else
begin
// else load default
Label2.Caption := 'Default Panel View Script';
ScriptLns.Add('mainWindow = FreeCADGui.getMainWindow()');
// set the panels we want visible
ScriptLns.Add('dockWidgets = mainWindow.findChildren(QtGui.QDockWidget)');
ScriptLns.Add('for dw in dockWidgets:');
ScriptLns.Add(' if dw.objectName() == "Tree view":');
ScriptLns.Add(' dw.hide()');
ScriptLns.Add(' if dw.objectName() == "Combo View":');
ScriptLns.Add(' dw.showNormal()');
ScriptLns.Add(' if dw.objectName() == "Property view":');
ScriptLns.Add(' dw.hide()');
ScriptLns.Add(' if dw.objectName() == "Report view":');
ScriptLns.Add(' dw.showNormal()');
ScriptLns.Add(' if dw.objectName() == "Python console":');
ScriptLns.Add(' dw.showNormal()');
ExeMemo.Lines.Assign(ScriptLns);
end;
// save copy of Script?
if not FileExists(scriptFn) then
ExeMemo.Lines.SaveToFile(scriptFn)
else if SetFCparmsFrm.cbOverWriteScript.Checked then
ExeMemo.Lines.SaveToFile(scriptFn);
// execute the script
try
MaskFPUExceptions(True);
PythonEngine1.ExecStrings(ExeMemo.Lines);
PanelViewLoaded := True;
PyOutMemo.Lines.Add('Panel View Script Executed');
except
on E: Exception do
begin
ShowMessage('Exception On Panel View Script, class name = ' +
E.ClassName + CrLf + 'Exception message = ' + E.Message);
end;
end;
end;
procedure TFreeCadFrm.LoadObserverScript;
// note: other scripting ways to get arc / circle info:
// print Gui.Selection.getSelectionEx()[0].SubObjects[0].Curve.Center
// returns Vector (0.0, 0.0, 10.0)
// print Gui.Selection.getSelectionEx()[0].SubObjects[0].Curve.Center.x
// print Gui.Selection.getSelectionEx()[0].SubObjects[0].Curve.Center.y
// print Gui.Selection.getSelectionEx()[0].SubObjects[0].Curve.Center.z
var
scriptFn: string;
testprecision: integer;
DecPrecision: string;
begin
ScriptLns.Clear;
ExeMemo.Lines.Clear;
scriptFn := FrmMain.AppDataPath + PathDelim + ObserverScript;
// if custom script file exists and load custom specified
if SetFCparmsFrm.cbCustSelectObs.Checked and FileExists(scriptFn) then
begin
// load ExeMemo.Lines from custom script file
Label2.Caption := scriptFn;
ExeMemo.Lines.LoadFromFile(scriptFn);
end
else
begin
try
testprecision := StrToInt(EdtUpDown.Text);
DecPrecision := EdtUpDown.Text;
except
ShowMessage('Bad precision value: ' + EdtUpDown.Text + ' using 4');
DecPrecision := '4';
end;
// else load default
Label2.Caption := 'Default Observer Script';
ScriptLns.Add('def MyStr(InData):');
ScriptLns.Add(' result = ''{:.' + DecPrecision + 'f}''.format(InData)');
ScriptLns.Add(' return result');
ScriptLns.Add('class SelObserver:');
ScriptLns.Add(' def addSelection(self,doc,obj,sub,pnt):');
ScriptLns.Add(' global MyEdgeList');
ScriptLns.Add(' MyGeo = ''unknown''');
ScriptLns.Add(' MyX1 = ''''');
ScriptLns.Add(' MyY1 = ''''');
ScriptLns.Add(' MyZ1 = ''''');
ScriptLns.Add(' MyX2 = ''''');
ScriptLns.Add(' MyY2 = ''''');
ScriptLns.Add(' MyZ2 = ''''');
ScriptLns.Add(' MyRad = ''''');
ScriptLns.Add(' MyCtrX = ''''');
ScriptLns.Add(' MyCtrY = ''''');
ScriptLns.Add(' MyCtrZ = ''''');
ScriptLns.Add(' sel = FreeCADGui.Selection.getSelection()');
ScriptLns.Add(' SubObject = str(sub)');
ScriptLns.Add(' if fnmatch.fnmatch(SubObject, ''Vertex*''):');
// sub object is a Vertex therefore we have a point
ScriptLns.Add(' MyGeo = ''point''');
ScriptLns.Add(' MyX1 = MyStr(pnt[0])');
ScriptLns.Add(' MyY1 = MyStr(pnt[1])');
ScriptLns.Add(' MyZ1 = MyStr(pnt[2])');
ScriptLns.Add(' elif fnmatch.fnmatch(str(obj), ''Face*''): ');
ScriptLns.Add
(' MyGeo = ''unknown-Object:'' + str(obj) + ''-subobject:'' + SubObject');
ScriptLns.Add(' elif fnmatch.fnmatch(SubObject, ''Edge*''): ');
// could be Line, Circle or Arc
ScriptLns.Add(' try:');
ScriptLns.Add
(' MyRad = str(sel[0].Shape.Edges[0].Curve.Radius)');
ScriptLns.Add(' MyCtr = sel[0].Shape.Edges[0].Curve.Center');
ScriptLns.Add(' MyCtrX = MyStr(MyCtr.x)');
ScriptLns.Add(' MyCtrY = MyStr(MyCtr.y)');
ScriptLns.Add(' MyCtrZ = MyStr(MyCtr.z)');
// if we made it here we could be a circle or and arc, lets test number of vertices
ScriptLns.Add(' a = sel[0].Shape.Edges[0].Vertexes[0]');
ScriptLns.Add(' MyX1 = MyStr(a.Point.x)');
ScriptLns.Add(' MyY1 = MyStr(a.Point.y)');
ScriptLns.Add(' MyZ1 = MyStr(a.Point.z)');
ScriptLns.Add(' try:');
ScriptLns.Add(' a = sel[0].Shape.Edges[0].Vertexes[1]');
ScriptLns.Add(' MyGeo = ''arc''');
ScriptLns.Add(' MyX2 = MyStr(a.Point.x)');
ScriptLns.Add(' MyY2 = MyStr(a.Point.y)');
ScriptLns.Add(' MyZ2 = MyStr(a.Point.z)');
ScriptLns.Add
(' MyEdgeList.append(sel[0].Shape.Edges[0])');
ScriptLns.Add(' except:');
ScriptLns.Add(' MyGeo = ''circle''');
ScriptLns.Add(' except:');
// we have a line
ScriptLns.Add(' MyGeo = ''line''');
ScriptLns.Add(' a = sel[0].Shape.Edges[0].Vertexes[0]');
ScriptLns.Add(' MyX1 = MyStr(a.Point.x)');
ScriptLns.Add(' MyY1 = MyStr(a.Point.y)');
ScriptLns.Add(' MyZ1 = MyStr(a.Point.z)');
ScriptLns.Add(' a = sel[0].Shape.Edges[0].Vertexes[1]');
ScriptLns.Add(' MyX2 = MyStr(a.Point.x)');
ScriptLns.Add(' MyY2 = MyStr(a.Point.y)');
ScriptLns.Add(' MyZ2 = MyStr(a.Point.z)');
ScriptLns.Add(' MyEdgeList.append(sel[0].Shape.Edges[0])');
ScriptLns.Add(' else:');
// unknown (or un handled) type
ScriptLns.Add(' MyGeo = ''unknown: '' + SubObject');
ScriptLns.Add
(' print( ''Object: '' + str(obj) + '' subobject: '' + SubObject)');
ScriptLns.Add(' print( ''Geo: '' + MyGeo)');
ScriptLns.Add(' EdgeCnt.Value = len(MyEdgeList)');
ScriptLns.Add
(' print( ''Point1: '' + MyX1 + '','' + MyY1 + '','' +MyZ1)');
ScriptLns.Add
(' print( ''Point2: '' + MyX2 + '','' + MyY2 + '','' +MyZ2)');
ScriptLns.Add(' print( ''Radius: '' + MyRad)');
ScriptLns.Add
(' print( ''Center: '' + MyCtrX + '','' + MyCtrY + '','' + MyCtrZ )');
ScriptLns.Add
(' CaptureFC.WrtArgs(MyGeo,MyX1,MyY1,MyZ1,MyX2,MyY2,MyZ2,MyRad,MyCtrX,MyCtrY,MyCtrZ)');
// init our edge list
ScriptLns.Add('MyEdgeList = []');
ScriptLns.Add('EdgeCnt.Value = len(MyEdgeList)');
// create an instance of our observer
ScriptLns.Add('s=SelObserver()');
// and tell freecad to use it
ScriptLns.Add('FreeCADGui.Selection.addObserver(s)');
// Execute the script
ExeMemo.Lines.Assign(ScriptLns);
end;
// save copy of Script?
if not FileExists(scriptFn) then
ExeMemo.Lines.SaveToFile(scriptFn)
else if SetFCparmsFrm.cbOverWriteScript.Checked then
ExeMemo.Lines.SaveToFile(scriptFn);
// execute the script
try
MaskFPUExceptions(True);
PythonEngine1.ExecStrings(ExeMemo.Lines);
ObserverLoaded := True;
PyOutMemo.Lines.Add('Observer Script Executed');
except
on E: Exception do
begin
ShowMessage('Exception On Observer Script, class name = ' +
E.ClassName + CrLf + 'Exception message = ' + E.Message);
end;
end;
end;
procedure TFreeCadFrm.LoadWindowActionScript(Action: integer);
// LoadWindowActionScript actions
// WindowShow = 0;
// WindowHide = 1;
// WindowClose = 2;
var
scriptFn, WindowActionFN, WindowAction: string;
begin
case Action of
WindowShow:
begin
WindowActionFN := WindowShowScript;
WindowAction := 'FreeCADGui.getMainWindow().show()';
end;
WindowHide:
begin
WindowActionFN := WindowHideScript;
WindowAction := 'FreeCADGui.getMainWindow().hide()';
end;
WindowClose:
begin
WindowActionFN := WindowCloseScript;
WindowAction := 'FreeCADGui.getMainWindow().close()';
end
end;
ScriptLns.Clear;
ExeMemo.Lines.Clear;
scriptFn := FrmMain.AppDataPath + PathDelim + WindowActionFN;
// if custom script file exists and load custom specified
if SetFCparmsFrm.cbCustWindowAction.Checked and FileExists(scriptFn) then
begin
// load ExeMemo.Lines from custom script file
Label2.Caption := scriptFn;
ExeMemo.Lines.LoadFromFile(scriptFn);
end
else
begin
// else load default
Label2.Caption := 'Default Window Action Script';
ScriptLns.Add(WindowAction);
ExeMemo.Lines.Assign(ScriptLns);
end;
// save copy of Script?
if not FileExists(scriptFn) then
ExeMemo.Lines.SaveToFile(scriptFn)
else if SetFCparmsFrm.cbOverWriteScript.Checked then
ExeMemo.Lines.SaveToFile(scriptFn);
// execute the script
try
MaskFPUExceptions(True);
// PythonEngine1.ExecStrings(ExeMemo.Lines);
PythonEngine.GetPythonEngine.ExecStrings(ExeMemo.Lines);
// ShowMessage('FreeCad sent Shutdown Message');
except
on E: Exception do
begin
ShowMessage('Exception On ' + Label2.Caption + ' Script, class name = ' +
E.ClassName + CrLf + 'Exception message = ' + E.Message);
end;
end;
end;
procedure TFreeCadFrm.btnExeFCClick(Sender: TObject);
var
MsgText: string;
begin
if not SetFCparmsFrm.cbFreeCADWarnDisable.Checked then
begin
MsgText := 'Please Note:' + CrLf;
MsgText := MsgText +
'The Close "X" on the FreeCAD Application Window has been disabled. ' + CrLf;
MsgText := MsgText +
'Please Close FreeCAD By Closing The CodeShark/FreeCAD Interface Dialog' + CrLf;
MsgText := MsgText +
'FAILURE TO FOLLOW THIS INSTRUCTION WILL MOST LIKELY RESULT IN AN APPLICATION ERROR WHEN THE PROGRAM IS CLOSED!'
+ CrLf;
MsgText := MsgText +
'To Disable This Warning Check "Disable FreeCAD Window Warning" in the CodeSharkFC - FreeCAD Setup Parameters Dialog'
+ CrLf;
MessageDlg(MsgText, mtWarning, [mbOK], 0);
end;
{$IFDEF MSWINDOWS}
// -- windows only problem ? --
// Note (or warn) for QT bug, "/platforms" directory must be local to codeshark exe, look for it
// 01/22/2020 this looks like it has been fixed, do not warn
// 02/18/2020 when using FreeCAD_0.19.19635_x64_Conda_Py3QT5-WinVS2015 it is back again!
if not DirectoryExists(ExtractFilePath(ParamStr(0)) + PathDelim + 'platforms') then
ShowMessage
('Warning ... Due to QT5 issue on some platforms, "platforms" directory may need to be copied from FreeCad ../bin/platforms to directory containing CodeSharkFC exe file, it was not found.');
{$ENDIF}
FrmMain.Cursor := crHourGlass;
FrmMain.StatusBar.Panels[0].Text := 'Script Statup';
FrmMain.Refresh;
try
LoadStartupScript;
LoadWindowScript;
LoadPanelViewScript;
LoadObserverScript;
finally
btnExeFC.Enabled := False; // do not let user select again
btnGenPath.Enabled := True;
btnPathShapes.Enabled := True;
FrmMain.Cursor := crDefault;
if cbBypassSel.Checked then
FrmMain.StatusBar.Panels[0].Text :=
'Bypass Insertion of Clicked on Geometry '
else
FrmMain.StatusBar.Panels[0].Text := 'Insert Clicked on Geometry';
end;
end;
end.
|
unit ncaConfigRecibo;
interface
uses SysUtils, Classes, ncClassesBase, Printers;
const
autoprint_nao = 0;
autoprint_pagamento = 1;
autoprint_venda = 2;
type
TncConfigRecibo = class ( TStringList )
private
procedure LoadFromGConfig;
function FName: String;
function TemOpcoes: Boolean;
function RecIniExists: Boolean;
function GetBobina(aTipo: Byte): Boolean;
function GetImpressora(aTipo: Byte): String;
function GetImpSerial: Boolean;
function GetImpWindows: Boolean;
function GetLarguraBobina: Integer;
function GetPortaSerial: Byte;
function GetSaltoFimRecibo: Integer;
function GetSomenteTexto: Boolean;
procedure SetImpressora(aTipo: Byte; const Value: String);
procedure SetLarguraBobina(const Value: Integer);
procedure SetPortaSerial(const Value: Byte);
procedure SetSaltoFimRecibo(const Value: Integer);
procedure SetSomenteTexto(const Value: Boolean);
function GetCortarPapel: Boolean;
procedure SetCortarPapel(const Value: Boolean);
function GetDirectPrintFormat: String;
procedure SetDirectPrintFormat(const Value: String);
function GetCmdAbreGaveta: String;
procedure SetCmdAbreGaveta(const Value: String);
function GetAbrirGaveta: Byte;
function GetMostrarGaveta: Boolean;
procedure SetAbrirGaveta(const Value: Byte);
procedure SetMostrarGaveta(const Value: Boolean);
function GetIntModelo(aTipo: Byte): String;
function GetModelo(aTipo: Byte): String;
procedure SetModelo(aTipo: Byte; const Value: String);
procedure SetBobina(aTipo: Byte; const Value: Boolean);
function GetCopias(aTipo: Byte): Byte;
procedure SetCopias(aTipo: Byte; const Value: Byte);
function GetDemDebBob: Boolean;
procedure SetDemDebBob(const Value: Boolean);
function GetModeloEmailOrc: String;
procedure SetModeloEmailOrc(const Value: String);
function GetAutoPrint: Byte;
procedure SetAutoPrint(const Value: Byte);
function GetImpAuto(aTipo: Byte): Boolean;
procedure SetImpAuto(aTipo: Byte; const Value: Boolean);
function oldImprimir: Boolean;
function GetImprimir(aTipo: Byte): Boolean;
procedure SetImprimir(aTipo: Byte; const Value: Boolean);
public
constructor Create;
procedure ImportarModelos;
procedure Load;
procedure Save;
function UsarSerial: Boolean;
function IsSomenteTexto: Boolean;
function StrAbreGaveta: AnsiString;
function DocOk(aTipo: Byte): Boolean;
function DocEmailOrcOk: Boolean;
function ImpressoraOk(aTipo: Byte): Boolean;
function GetIntBobina(aTipo: Byte): Boolean;
property DemDebBob: Boolean
read GetDemDebBob write SetDemDebBob;
property Copias[aTipo: Byte]: Byte
read GetCopias write SetCopias;
property Modelo[aTipo: Byte]: String
read GetModelo write SetModelo;
property ModeloEmailOrc: String
read GetModeloEmailOrc write SetModeloEmailOrc;
property CmdAbreGaveta: String
read GetCmdAbreGaveta write SetCmdAbreGaveta;
property MostrarGaveta: Boolean
read GetMostrarGaveta write SetMostrarGaveta;
property AbrirGaveta: Byte
read GetAbrirGaveta write SetAbrirGaveta;
property DirectPrintFormat: String
read GetDirectPrintFormat write SetDirectPrintFormat;
property Imprimir[aTipo: Byte]: Boolean
read GetImprimir write SetImprimir;
property ImpAuto[aTipo: Byte]: Boolean
read GetImpAuto write SetImpAuto;
property oldAutoPrint: Byte
read GetAutoPrint write SetAutoPrint;
property ImpWindows: Boolean
read GetImpWindows;
property ImpSerial: Boolean
read GetImpSerial;
property CortarPapel: Boolean
read GetCortarPapel write SetCortarPapel;
property PortaSerial: Byte
read GetPortaSerial write SetPortaSerial;
property LarguraBobina: Integer
read GetLarguraBobina write SetLarguraBobina;
property SaltoFimRecibo: Integer
read GetSaltoFimRecibo write SetSaltoFimRecibo;
property Bobina[aTipo: Byte]: Boolean
read GetBobina write SetBobina;
property SomenteTexto: Boolean
read GetSomenteTexto write SetSomenteTexto;
property Impressora[aTipo: Byte]: String
read GetImpressora write SetImpressora;
end;
function ModeloPadrao(aTipo: Byte; aBobina, aSomenteTexto: Boolean): String;
var
gRecibo : TncConfigRecibo = nil;
implementation
uses uNexTransResourceStrings_PT, ncDebug, ncaDM, ncaDMComp, ncaDMOrc;
{ TncConfigRecibo }
function PropTipoStr(aProp: String; aTipo: Byte): String;
begin
Result := aProp;
if aTipo<>tipodoc_venda then
{ case aTipo of
tipodoc_venda : ;
tipodoc_pgdebito : if not aVendasDebUnico then
Result := Result+IntToStr(aTipo);
else }
Result := Result+IntToStr(aTipo);
// end;
end;
function ModeloPadrao(aTipo: Byte; aBobina, aSomenteTexto: Boolean): String;
begin
case aTipo of
tipodoc_venda :
if not aBobina then
Result := '{1BB75B13-B043-4376-9271-49C982340D9E}'
else
if aSomenteTexto then
Result := '{2AB1E0A2-7DE4-4AAB-8DF3-38F5B5B9D6BC}'
else
Result := '{E0635987-6641-4FD7-AD4B-962BB4DB665C}';
tipodoc_orcamento :
Result := '{46FC1498-D24F-4BC0-88E2-3F8FA0FAC13A}';
tipodoc_pgdebito :
if not aBobina then
Result := '{5546BCAC-31DF-4FB4-859C-E4CFE54FABE0}'
else
if aSomenteTexto then
Result := '{79B60B54-29E9-4822-851F-ADA0882E5582}'
else
Result := '{4456B67E-A47E-4D6A-BE13-90925C4A5ACE}';
else
Result := '';
end;
end;
const BoolChar : Array[boolean] of char = ('0', '1');
function TncConfigRecibo.RecIniExists: Boolean;
begin
Result := FileExists(FName);
end;
constructor TncConfigRecibo.Create;
begin
inherited;
end;
function TncConfigRecibo.DocEmailOrcOk: Boolean;
begin
Result := Dados.FindDoc(ModeloEmailOrc);
end;
function TncConfigRecibo.DocOk(aTipo: Byte): Boolean;
begin
DebugMsg('TncConfigRecibo.DocOk(aTipo: '+IntToStr(aTipo)+')');
Result := Dados.FindDoc(Modelo[aTipo]);
end;
function TncConfigRecibo.FName: String;
begin
Result := ExtractFilePath(ParamStr(0))+'custom\rec.ini';
end;
function TncConfigRecibo.GetAbrirGaveta: Byte;
begin
Result := StrToIntDef(Values['abrirgaveta'], 0);
end;
function TncConfigRecibo.GetAutoPrint: Byte;
begin
if Values['autoprint']>'' then
Result := StrToIntDef(Values['autoprint'], autoprint_nao)
else
if Values['imprimir']='2' then
Result := autoprint_pagamento
else
Result := autoprint_nao;
end;
function TncConfigRecibo.GetBobina(aTipo: Byte): Boolean;
begin
Result := GetIntBobina(aTipo) and gConfig.IsPremium;
end;
function TncConfigRecibo.GetCmdAbreGaveta: String;
begin
if IndexOfName('cmd_abregaveta')<0 then begin
Values['cmd_abregaveta'] := '#27,#118,#140';
Save;
end;
Result := Values['cmd_abregaveta'];
end;
function TncConfigRecibo.GetCopias(aTipo: Byte): Byte;
begin
Result := StrToIntDef(Values[PropTipoStr('copias', aTipo)], 1);
end;
function TncConfigRecibo.GetCortarPapel: Boolean;
begin
Result := (Values['cortarpapel']='1');
end;
function TncConfigRecibo.GetDemDebBob: Boolean;
begin
Result := (Values['demdebbob']='1');
end;
function TncConfigRecibo.GetDirectPrintFormat: String;
begin
Result := Trim(Values['directprintformat']);
if (Result='') then Result := 'TEXT';
end;
function TncConfigRecibo.GetImpAuto(aTipo: Byte): Boolean;
var S: String;
function _Value: String;
begin
Result := Values[PropTipoStr('imp_auto', aTipo)];
end;
begin
S := _Value;
if (S='') and (aTipo=tipodoc_pgdebito) then begin
aTipo := tipodoc_venda;
S := _Value;
end;
if (S='') and (aTipo=tipodoc_venda) then
Result := (oldAutoPrint>0) else
Result := StrToBool(S);
end;
function TncConfigRecibo.GetImpressora(aTipo: Byte): String;
var S: String;
function _Value: String;
begin
Result := Values[PropTipoStr('impressora', aTipo)];
end;
begin
S := _Value;
if (S='') and (aTipo=tipodoc_pgdebito) then
aTipo := tipodoc_venda;
Result := _Value;
end;
function TncConfigRecibo.GetImprimir(aTipo: Byte): Boolean;
var S: String;
function _Value: String;
begin
Result := Values[PropTipoStr('imprimir_rec', aTipo)];
end;
begin
S := _Value;
if (S='') and (aTipo in [tipodoc_venda, tipodoc_pgdebito]) then
Result := oldImprimir else
Result := StrToBool(S);
end;
function TncConfigRecibo.oldImprimir: Boolean;
begin
if Values['imprimirrec']>'' then
Result := (Values['imprimirrec']='1')
else
Result := (Values['imprimir']='1') or (Values['imprimir']='2');
end;
function TncConfigRecibo.GetImpSerial: Boolean;
begin
Result := SameText(Impressora[tipodoc_venda], SncaFrmConfigRec_OutraSerial);
end;
function TncConfigRecibo.GetImpWindows: Boolean;
begin
Result := (not ImpSerial);
end;
function TncConfigRecibo.GetIntBobina(aTipo: Byte): Boolean;
begin
Result := (Values[PropTipoStr('tipopapel', aTipo)]='1');
end;
function TncConfigRecibo.GetIntModelo(aTipo: Byte): String;
begin
Result := Values[PropTipoStr('modelo', aTipo)];
end;
function TncConfigRecibo.GetLarguraBobina: Integer;
begin
Result := StrToIntDef(Values['largura'], 40);
end;
function TncConfigRecibo.GetModelo(aTipo: Byte): String;
var aPadrao: String;
begin
DebugMsg('TncConfigRecibo.GetModelo(aTipo: '+IntToStr(aTipo)+')');
Result := GetIntModelo(aTipo);
if (not gConfig.IsPremium) and (Result>'') then begin
aPadrao := ModeloPadrao(aTipo, False, False);
if aPadrao>'' then
Result := aPadrao;
end;
DebugMsg('TncConfigRecibo.GetModelo - Res: '+Result);
end;
function TncConfigRecibo.GetModeloEmailOrc: String;
begin
Result := Values['modelo_email_orc'];
end;
function TncConfigRecibo.GetMostrarGaveta: Boolean;
begin
Result := (Values['mostrargaveta']='1');
end;
function TncConfigRecibo.GetPortaSerial: Byte;
begin
Result := StrToIntDef(Values['porta'], 1);
end;
function TncConfigRecibo.GetSaltoFimRecibo: Integer;
begin
Result := StrToIntDef(Values['salto'], 0);
end;
function TncConfigRecibo.GetSomenteTexto: Boolean;
begin
Result := (Values['somentetexto']='1');
end;
procedure TncConfigRecibo.ImportarModelos;
begin
if Values['importoumodelos']='' then begin
CriaDMComp;
CriaDMOrc;
dmComp.ImportarModelos;
dmOrc.ImportarModelos;
Dados.ImportarModelosEtq;
Values['importoumodelos'] := '1';
Save;
end;
end;
function TncConfigRecibo.ImpressoraOk(aTipo: Byte): Boolean;
begin
Result := (Impressora[aTipo]>'') and (Printer.Printers.IndexOf(Impressora[aTipo])>=0);
end;
function TncConfigRecibo.IsSomenteTexto: Boolean;
begin
Result := SomenteTexto or (Pos('Generic', Impressora[tipodoc_venda])>0);
end;
procedure TncConfigRecibo.Load;
begin
if not TemOpcoes then begin
if RecIniExists then
LoadFromFile(FName) else
LoadFromGConfig;
Save;
end else
Text := Dados.tbTermOpcoes.Value;
end;
procedure TncConfigRecibo.LoadFromGConfig;
begin
Imprimir[tipodoc_venda] := (gConfig.RecImprimir>0);
ImpAuto[tipodoc_venda] := (gConfig.RecImprimir=2);
Impressora[tipodoc_venda] := gConfig.RecTipoImpressora;
PortaSerial := StrToIntDef(gConfig.RecPorta, 1);
LarguraBobina := gConfig.RecLargura;
SaltoFimRecibo := gConfig.RecSalto;
Bobina[tipodoc_venda] := gConfig.RecMatricial;
SomenteTexto := gConfig.RecPrinterGeneric or ImpSerial;
CortarPapel := gConfig.RecCortaFolha;
Save;
end;
procedure TncConfigRecibo.Save;
begin
try
if Values['directprintformat']='' then Values['directprintformat'] := 'TEXT';
// ForceDirectories(ExtractFilePath(ParamStr(0))+'custom');
// SaveToFile(FName);
Dados.tbTerm.Edit;
Dados.tbTermOpcoes.Value := Text;
Dados.tbTerm.Post;
except
on e: exception do
DebugMsg('TncConfigRecibo.Save - Exception: ' + E.Message);
end;
end;
procedure TncConfigRecibo.SetAbrirGaveta(const Value: Byte);
begin
Values['abrirgaveta'] := IntToStr(Value);
end;
procedure TncConfigRecibo.SetAutoPrint(const Value: Byte);
begin
Values['autoprint'] := IntToStr(Value);
end;
procedure TncConfigRecibo.SetBobina(aTipo: Byte; const Value: Boolean);
begin
Values[PropTipoStr('tipopapel', aTipo)] := BoolChar[Value];
end;
procedure TncConfigRecibo.SetCmdAbreGaveta(const Value: String);
begin
Values['cmd_abregaveta'] := Value;
end;
procedure TncConfigRecibo.SetCopias(aTipo: Byte; const Value: Byte);
begin
Values[PropTipoStr('copias', aTipo)] := IntToStr(Value);
end;
procedure TncConfigRecibo.SetCortarPapel(const Value: Boolean);
begin
Values['cortarpapel'] := BoolChar[Value];
end;
procedure TncConfigRecibo.SetDemDebBob(const Value: Boolean);
begin
Values['demdebbob'] := BoolChar[Value];
end;
procedure TncConfigRecibo.SetDirectPrintFormat(const Value: String);
begin
Values['directprintformat'] := Value;
end;
procedure TncConfigRecibo.SetImpAuto(aTipo: Byte; const Value: Boolean);
begin
Values[PropTipoStr('imp_auto', aTipo)] := BoolChar[Value];
end;
procedure TncConfigRecibo.SetImpressora(aTipo: Byte; const Value: String);
begin
Values[PropTipoStr('impressora', aTipo)] := Value;
end;
procedure TncConfigRecibo.SetImprimir(aTipo: Byte; const Value: Boolean);
begin
Values[PropTipoStr('imprimir_rec', aTipo)] := BoolChar[Value];
end;
procedure TncConfigRecibo.SetLarguraBobina(const Value: Integer);
begin
Values['largurabobina'] := IntToStr(Value);
end;
procedure TncConfigRecibo.SetModelo(aTipo: Byte; const Value: String);
begin
Values[PropTipoStr('modelo', aTipo)] := Value;
end;
procedure TncConfigRecibo.SetModeloEmailOrc(const Value: String);
begin
Values['modelo_email_orc'] := Value;
end;
procedure TncConfigRecibo.SetMostrarGaveta(const Value: Boolean);
begin
Values['mostrargaveta'] := BoolChar[Value];
end;
procedure TncConfigRecibo.SetPortaSerial(const Value: Byte);
begin
Values['porta'] := IntToStr(Value);
end;
procedure TncConfigRecibo.SetSaltoFimRecibo(const Value: Integer);
begin
Values['saltofimrecibo'] := IntToStr(Value);
end;
procedure TncConfigRecibo.SetSomenteTexto(const Value: Boolean);
begin
Values['somentetexto'] := BoolChar[Value];
end;
function StrToChar(S: String): AnsiString;
begin
S := Trim(S);
if S>'' then
if S[1]='#' then begin
Delete(S, 1, 1);
Result := AnsiChar(StrToIntDef(S, 0));
end else
Result := S;
end;
function TncConfigRecibo.StrAbreGaveta: AnsiString;
var
S: String;
procedure AddCmd;
var P, I: Integer;
begin
P := Pos(',', S);
if P>0 then begin
Result := Result + StrToChar(Copy(S, 1, P-1));
System.Delete(S, 1, P);
end else begin
Result := Result + StrToChar(S);
S := '';
end;
end;
begin
S := CmdAbreGaveta;
Result := '';
while S>'' do AddCmd;
end;
function TncConfigRecibo.TemOpcoes: Boolean;
begin
Result := (Dados.tbTermOpcoes.Value>'');
end;
function TncConfigRecibo.UsarSerial: Boolean;
begin
Result := IsSomenteTexto or ImpSerial;
end;
initialization
gRecibo := TncConfigRecibo.Create;
finalization
gRecibo.Free;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, TAGraph, TAFuncSeries, TASeries, Forms, Controls,
Graphics, Dialogs, ExtCtrls, ComCtrls, Menus, Buttons, StdCtrls,
fpexprpars_wp, FPMathExpressionBridge, dlgAbout;
type
{ TForm1 }
TForm1 = class(TForm)
Chart1: TChart;
Chart1ParametricCurveSeries1: TParametricCurveSeries;
FPMathExpressionBridge1: TFPMathExpressionBridge;
FPMathExpressionBridge2: TFPMathExpressionBridge;
ImageList1: TImageList;
Label1: TLabel;
MenuItem10: TMenuItem;
MenuItem12: TMenuItem;
MenuItem13: TMenuItem;
MenuItem14: TMenuItem;
MenuItem17: TMenuItem;
MenuItem2: TMenuItem;
MenuItem5: TMenuItem;
Panel1: TPanel;
PopupMenu1: TPopupMenu;
StatusBar1: TStatusBar;
ToolBar1: TToolBar;
ToolButton1: TToolButton;
ToolButton4: TToolButton;
procedure Chart1ParametricCurveSeries1Calculate(const AT: Double; out AX,
AY: Double);
procedure FormCreate(Sender: TObject);
procedure FormDeactivate(Sender: TObject);
procedure FPMathExpressionBridge1ConstantParse(Index: integer; AName: string; out
AValue: real);
procedure FPMathExpressionBridge2ConstantParse(Index: integer; AName: string; out
AValue: real);
procedure MenuItem12Click(Sender: TObject);
procedure MenuItem13Click(Sender: TObject);
procedure MenuItem14Click(Sender: TObject);
procedure MenuItem2Click(Sender: TObject);
procedure MenuItem5Click(Sender: TObject);
procedure PopupMenu1Close(Sender: TObject);
procedure ToolButton4Click(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
uses
mpspe_wp;
{ TForm1 }
procedure TForm1.PopupMenu1Close(Sender: TObject);
var
sText: string;
begin
sText:= (Sender as TMenuItem).Caption;
if CompareText(sText, 'Exit') = 0 then Application.Terminate;
end;
procedure TForm1.Chart1ParametricCurveSeries1Calculate(const AT: Double; out
AX, AY: Double);
var
R1: TEvalueteResult;
R2: TEvalueteResult;
begin
R1:= FPMathExpressionBridge1.EvalFunc(AT);
if R1.IsValid then
begin
AX:= R1.Value
end
else AX:= 0; {or others things....}
R2:= FPMathExpressionBridge2.EvalFunc(AT);
if R2.IsValid then
begin
AY:= R2.Value
end
else AY:= 0; {or others things....}
end;
//cycloid
procedure TForm1.MenuItem12Click(Sender: TObject);
begin
Chart1ParametricCurveSeries1.Active:=False;
FPMathExpressionBridge1.VariableOfFunc:= 't';
FPMathExpressionBridge1.Expression:= 'h*t - r*sin(h*t)'; //x
FPMathExpressionBridge2.VariableOfFunc:= 't';
FPMathExpressionBridge2.Expression:= 'h - r*cos(h*t)'; //y
Chart1ParametricCurveSeries1.Active:=True;
end;
//Tractrix
procedure TForm1.MenuItem13Click(Sender: TObject);
begin
Chart1ParametricCurveSeries1.Active:=False;
FPMathExpressionBridge1.VariableOfFunc:= 't';
FPMathExpressionBridge1.Expression:= 'p*(1/cosh(t))'; //x
FPMathExpressionBridge2.VariableOfFunc:= 't';
FPMathExpressionBridge2.Expression:='p*(t - tanh(t))'; //y
Chart1ParametricCurveSeries1.Active:=True;
end;
//deltoid
procedure TForm1.MenuItem5Click(Sender: TObject);
begin
Chart1ParametricCurveSeries1.Active:=False;
FPMathExpressionBridge1.VariableOfFunc:= 't';
FPMathExpressionBridge1.Expression:= '2*r*cos(t)+r*cos(2*t)'; //x
FPMathExpressionBridge2.VariableOfFunc:= 't';
FPMathExpressionBridge2.Expression:= '2*r*sin(t)-r*sin(2*t)'; //y
Chart1ParametricCurveSeries1.Active:=True;
end;
//projectile motion
procedure TForm1.MenuItem14Click(Sender: TObject);
begin
Chart1ParametricCurveSeries1.Active:=False;
FPMathExpressionBridge1.VariableOfFunc:= 't';
FPMathExpressionBridge1.Expression:= 'Vo*cos(angle)*t'; //x
FPMathExpressionBridge2.VariableOfFunc:= 't';
FPMathExpressionBridge2.Expression:= '(-1/2)*sqr(t)*G + (Vo*sin(angle))*t'; //y
Chart1ParametricCurveSeries1.Active:=True;
end;
//cardioid
procedure TForm1.MenuItem2Click(Sender: TObject);
begin
Chart1ParametricCurveSeries1.Active:=False;
FPMathExpressionBridge1.VariableOfFunc:= 't';
FPMathExpressionBridge1.Expression:= 'd*(2*cos(t)-cos(2*t))'; //x
FPMathExpressionBridge2.VariableOfFunc:= 't';
FPMathExpressionBridge2.Expression:= 'd*(2*sin(t)-sin(2*t))'; //y
Chart1ParametricCurveSeries1.Active:=True;
end;
//call after Expression set...
procedure TForm1.FPMathExpressionBridge2ConstantParse(Index: integer; AName: string; out
AValue: real);
begin //Case Insensitive!
if CompareText(AName,'r')=0 then AValue:= 1;
if CompareText(AName,'d')=0 then AValue:= 0.75;
if CompareText(AName,'angle')=0 then AValue:= 3.14/8;
if CompareText(AName,'Vo')=0 then AValue:= 4;
if CompareText(AName,'G')=0 then AValue:= 9.8;
if CompareText(AName,'h')=0 then AValue:= 2.5;
if CompareText(AName,'p')=0 then AValue:= 1.5;
end;
//call after Expression set...
procedure TForm1.FPMathExpressionBridge1ConstantParse(Index: integer; AName: string; out AValue: real);
begin //Case Insensitive!
if CompareText(AName,'r')=0 then AValue:= 1;
if CompareText(AName,'d')=0 then AValue:= 0.75;
if CompareText(AName,'angle')=0 then AValue:= 3.14/8;
if CompareText(AName,'Vo')=0 then AValue:= 4;
if CompareText(AName,'h')=0 then AValue:= 2.5;
if CompareText(AName,'p')=0 then AValue:= 1.5;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
//here just for example....
//MathExpressionBridge 1 - Case Insensitive!
FPMathExpressionBridge1.AddConstant('R');
FPMathExpressionBridge1.AddConstant('d');
FPMathExpressionBridge1.AddConstant('angle');
FPMathExpressionBridge1.AddConstant('Vo');
FPMathExpressionBridge1.AddConstant('h');
FPMathExpressionBridge1.AddConstant('p');
FPMathExpressionBridge1.AddVariable('t');
//MathExpressionBridge 2 - Case Insensitive!
FPMathExpressionBridge2.AddConstant('R');
FPMathExpressionBridge2.AddConstant('d');
FPMathExpressionBridge2.AddConstant('angle');
FPMathExpressionBridge2.AddConstant('Vo');
FPMathExpressionBridge2.AddConstant('G');
FPMathExpressionBridge2.AddConstant('h');
FPMathExpressionBridge2.AddConstant('p');
FPMathExpressionBridge2.AddVariable('t');
end;
procedure TForm1.FormDeactivate(Sender: TObject);
begin
Close;
end;
//About-Help
procedure TForm1.ToolButton4Click(Sender: TObject);
var
strAbout: TStringList;
begin
strAbout:= TStringList.Create;
strAbout.Add('TFPMathExpressionBridge - Version 0.1 - 02/2013');
strAbout.Add('Author: Jose Marques Pessoa : jmpessoa__hotmail_com');
strAbout.Add('Acknowledgment: Thank you WP!');
strAbout.Add('TFPMathExpressionBridge is a warapper for [math]* subset');
strAbout.Add('of TFPExpressionParse** attempting to establish a easy semantics');
strAbout.Add('for construction of function graph and expression evaluete.');
strAbout.Add('0. Warning: at the moment this code is just a "proof-of-concept".');
strAbout.Add('1.Data');
strAbout.Add('1.1 Add Data');
strAbout.Add('Add Constants');
strAbout.Add('Add Variables');
strAbout.Add('Add Expressions');
strAbout.Add('use: AddConstant(''k'')');
strAbout.Add('AddVariable(''x'')');
strAbout.Add('AddExpression(''kx+1'')');
strAbout.Add('Obs.: Data are Case Insensitive!');
strAbout.Add('1.2 Set Data');
strAbout.Add('Set Expression //triggers OnConstantParse...');
strAbout.Add('use: Expression:= ''k*x+1''');
strAbout.Add('Helpers:');
strAbout.Add('procedure SetExpressionByIndex(Index: integer);');
strAbout.Add('function GetExpressionByIndex(Index: integer): string;');
strAbout.Add('function GetExpressionIndexByName(AName: string): integer;');
strAbout.Add('Set VariableOfFunc //variable of "functions of one variable"');
strAbout.Add('use: VariableOfFunc:= ''x''');
strAbout.Add('2.Evaluete');
strAbout.Add('2.1 Function Evaluete');
strAbout.Add('function EvalFunc(AValue: real) //eval function for one variable....');
strAbout.Add('use: EvalFunc(AValue)');
strAbout.Add('function EvalFunc(AValues: array of real) //eval function for many variables...');
strAbout.Add('EvalFunc([AValue1, AValue2, AValue3])');
strAbout.Add('2.2 Expression Evaluete //event driver');
strAbout.Add('function EvalExpr(Expr: string; ANamesVar: array of string)');
strAbout.Add('use: EvalExpr(''A*x**x+ B*x + C'', [''x'',''A'',''B'',''C'']) //triggers OnVariableParse');
strAbout.Add('function EvalExpr' );
strAbout.Add('use:');
strAbout.Add('AddConstant(''A'')');
strAbout.Add('AddConstant(''B'')');
strAbout.Add('AddConstant(''C'')');
strAbout.Add('AddVariable(''x'')');
strAbout.Add('Expression:= ''A*x**x+ B*x + k*C''');
strAbout.Add('EvalExpr; //triggers OnVariableParse');
strAbout.Add('3. Events');
strAbout.Add('3.1 OnConstantParse //triggers every time Expression is Set.....');
strAbout.Add('use: set constant value');
strAbout.Add('3.2 OnVariableParse //triggers every time EvalExpr is called.....');
strAbout.Add('use: set variable value');
strAbout.Add('4.Add "building" function');
strAbout.Add('//signature:');
strAbout.Add('type');
strAbout.Add('TExprFunc = procedure(Var Result: TFPExpressionResult; Const Args: TExprParameterArray);');
strAbout.Add('//"Add building" funtion code example:');
strAbout.Add('Procedure ExprDelta(Var Result: TFPExpressionResult; Const Args: TExprParameterArray);');
strAbout.Add('var');
strAbout.Add('a,b,c: Double;');
strAbout.Add('begin');
strAbout.Add('a := ArgToFloat(Args[0]);');
strAbout.Add('b := ArgToFloat(Args[1]);');
strAbout.Add('c := ArgToFloat(Args[2]);');
strAbout.Add('if IsNumber(a) and IsNumber(b) and IsNumber(c) then');
strAbout.Add('Result.resFloat := b*b - 4*a*c');
strAbout.Add('else');
strAbout.Add('result.resFloat := NaN;');
strAbout.Add('end;');
strAbout.Add('4.1 AddFunction(AName: string; paramCount: integer; callFunc: TExprFunc)');
strAbout.Add('Use:');
strAbout.Add('AddFunction(''Delta'', 3, @ExprDelta);');
strAbout.Add('Use:');
strAbout.Add('Expression:=''Delta(2,4,1)'';');
strAbout.Add('EvalExpr;');
strAbout.Add('5. Have Fun!');
//--------------------------------
strAbout.Add('*FParser.BuiltIns:= [bcMath]');
strAbout.Add('**(freepascal fpexprpars.pas) More specifically a WP revision and addOns.');
strAbout.Add('(Thank you WP!)');
strAbout.Add('See: http://www.lazarus.freepascal.org/index.php/topic,19627.0.html');
AboutBridge.MemoAbout.Append(strAbout.Text);
AboutBridge.Execute;
strAbout.Free;
end;
end.
|
program QuickSort;
type
NumberArray = Array [0..9] of Integer;
procedure QSort(var numbers : NumberArray; left : Integer; right : Integer);
var pivot, l_ptr, r_ptr : Integer;
begin
l_ptr := left;
r_ptr := right;
pivot := numbers[left];
while (left < right) do
begin
while ((numbers[right] >= pivot) and (left < right)) do
right := right - 1;
If (left <> right) then
begin
numbers[left] := numbers[right];
left := left + 1;
end;
while ((numbers[left] <= pivot) and (left < right)) do
left := left + 1;
If (left <> right) then
begin
numbers[right] := numbers[left];
right := right - 1;
end;
end;
numbers[left] := pivot;
pivot := left;
left := l_ptr;
right := r_ptr;
If (left < pivot) then
QSort(numbers, left, pivot-1);
If (right > pivot) then
QSort(numbers, pivot+1, right);
end;
var
numbers : NumberArray;
i : Integer;
begin
numbers[0] := 123;
numbers[1] := 1;
numbers[2] := 98;
numbers[3] := 5;
numbers[5] := 13;
numbers[4] := 20;
numbers[6] := 25;
numbers[7] := 22;
numbers[8] := 21;
numbers[9] := 5;
QSort(numbers, 0, 9);
for i := 0 to 9 do
WriteLn(i, ': ', numbers[i]);
end.
|
unit smf_const;
interface
uses
{$ifdef Win32}Windows,{$endif}
SysUtils,
Classes;
const
//MIDIイベントのステータス
EVENT_NOTE_OFF = $80;
EVENT_NOTE_ON = $90;
EVENT_KEY_PRESSURE = $A0; //アフタータッチ
EVENT_CONTROL_CHANGE = $B0; //コントロールチェンジ
EVENT_PROGRAM_CHANGE = $C0;
EVENT_CHANNEL_PRESSURE = $D0;
EVENT_PITCH_BEND = $E0;
EVENT_SYS_EX = $F0;
EVENT_META = $F7;
//ControlChange
CC_BANK_MSB = $00;
CC_BANK_LSB = $20;
//
CC_RPN_MSB = 101;
CC_RPN_LSB = 100;
CC_NRPN_MSB = 99;
CC_NRPN_LSB = 98;
CC_DATA_ENTRY = 6;
//META Event
META_END_OF_TRACK = #$FF#$2F#00;
META_TYPE_END_OF_TRACK = $2F;
//
META_TEMPO = $51;//3BYTE
META_SEQ_NO = $00;//2BYTE
META_TEXT = $01;
META_COPYRIGHT = $02;
META_TRACK_NAME = $03;
META_INST_NAME = $04;
META_LYRIC = $05;
META_MARKER = $06;
META_CUE_POINT = $07;
META_CH_PREFIX = $20;//1BYTE
META_SMPTE = $54;//5BYTE
META_TIME_SIG = $58;//4BYTE
META_KEY_SIG = $59;//2BYTE
META_SEQ_SPRC = $7F;
META_PORT = $21;//1BYTE
//MIDI送信時のイベント
EVENT_SYSTE_EXCLUSIVE = $F0;
EVENT_MIDI_TIMECODE = $F1;
EVENT_SONG_POSITION = $F2;
EVENT_SONG_SELECT = $F3;
EVENT_TUNE_REQUEST = $F4;
EVENT_START = $FA;
EVENT_CONTINUE = $FB;
EVENT_STOP = $FC;
EVENT_ACTIVE_SENSING = $FE;
EVENT_SYSTEM_RESET = $FF;
implementation
end.
|
unit uCefUtilType;
interface
uses
System.SysUtils, System.Types;
type
TCefControllerBase = class
public
Cursor: TPoint;
Speed: Integer;
constructor Create;
end;
implementation
uses
uCefUtilConst;
{ TCefControllerBase }
constructor TCefControllerBase.Create;
begin
Cursor := TPoint.Create(0, 0);
Speed := SPEED_DEF;
end;
end.
|
unit uCliente;
interface
uses uCidade;
// criacao do objeto modelo Cliente
type
TCliente = class
private
codigo: Integer;
ativo: char;
razaoSocial: String;
fantasia: String;
endereco: String;
numero: String;
bairro: String;
complemento: String;
telefone: String;
cnpjcpf: String;
ierg: String;
email: String;
tipo: char;
cidade: TCidade;
public
// contrutor da classe
constructor TClienteCreate;
// destrutor da classe
destructor TClienteDestroy;
// metodo "procedimento" set do Objeto
procedure setCodigo(param: Integer);
procedure setAtivo(param: char);
procedure setRazaoSocial(param: String);
procedure setFantasia(param: String);
procedure setEndereco(param: String);
procedure setNumero(param: String);
procedure setBairro(param: String);
procedure setComplemento(param: String);
procedure setTelefone(param: String);
procedure setCnpjCpf(param: String);
procedure setIeRg(param: String);
procedure setEmail(param: String);
procedure setTipo(param: char);
procedure setCidade(param: TCidade);
// metodo "funcoes" get do Objeto
function getCodigo: Integer;
function getAtivo: char;
function getRazaoSocial: String;
function getFantasia: String;
function getEndereco: String;
function getNumero: String;
function getBairro: String;
function getComplemento: String;
function getTelefone: String;
function getCnpjCpf: String;
function getIeRg: String;
function getEmail: String;
function getTipo: char;
function getCidade: TCidade;
end;
var
cliente : TCliente;
implementation
{ TCliente implemenetacao dos metodos Get e sey }
function TCliente.getAtivo: char;
begin
Result := ativo;
end;
function TCliente.getBairro: String;
begin
Result := bairro;
end;
function TCliente.getCidade: TCidade;
begin
Result := cidade;
end;
function TCliente.getCnpjCpf: String;
begin
Result := cnpjcpf;
end;
function TCliente.getCodigo: Integer;
begin
Result := codigo;
end;
function TCliente.getComplemento: String;
begin
Result := complemento;
end;
function TCliente.getEmail: String;
begin
Result := email;
end;
function TCliente.getEndereco: String;
begin
Result := endereco;
end;
function TCliente.getFantasia: String;
begin
Result := fantasia;
end;
function TCliente.getIeRg: String;
begin
Result := ierg;
end;
function TCliente.getNumero: String;
begin
Result := numero;
end;
function TCliente.getRazaoSocial: String;
begin
Result := razaoSocial;
end;
function TCliente.getTelefone: String;
begin
Result := telefone;
end;
function TCliente.getTipo: char;
begin
Result := tipo;
end;
procedure TCliente.setAtivo(param: char);
begin
ativo := param;
end;
procedure TCliente.setBairro(param: String);
begin
bairro := param;
end;
procedure TCliente.setCidade(param: TCidade);
begin
cidade := param;
end;
procedure TCliente.setCnpjCpf(param: String);
begin
cnpjcpf := param;
end;
procedure TCliente.setCodigo(param: Integer);
begin
codigo := param;
end;
procedure TCliente.setComplemento(param: String);
begin
complemento := param;
end;
procedure TCliente.setEmail(param: String);
begin
email := param;
end;
procedure TCliente.setEndereco(param: String);
begin
endereco := param;
end;
procedure TCliente.setFantasia(param: String);
begin
fantasia := param;
end;
procedure TCliente.setIeRg(param: String);
begin
ierg := param;
end;
procedure TCliente.setNumero(param: String);
begin
numero := param;
end;
procedure TCliente.setRazaoSocial(param: String);
begin
razaoSocial := param;
end;
procedure TCliente.setTelefone(param: String);
begin
telefone := param;
end;
procedure TCliente.setTipo(param: char);
begin
tipo := param;
end;
constructor TCliente.TClienteCreate;
begin
codigo := 0;
ativo := 'S';
razaoSocial := '';
fantasia := '';
endereco := '';
numero := '';
bairro := '';
complemento := '';
telefone := '';
cnpjcpf := '';
ierg := '';
email := '';
tipo := 'F';
cidade.TCidadeCreate;
end;
destructor TCliente.TClienteDestroy;
begin
cidade.TCidadeDestroy;
FreeInstance;
end;
end.
|
unit u_xml;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, DOM;
const
//Schema_Collection Strings
K_XML_STR_Name = 'name';
K_XML_STR_XplSchema = 'xplSchema';
K_XML_STR_XplSchemaCol = 'xplSchemaCollection';
// XPL Plugin Strings
K_XML_STR_Beta_version = 'beta_version';
K_XML_STR_COMMAND = 'command';
K_XML_STR_COMMENT = 'comment';
K_XML_STR_ConditionalV = 'conditional-visibility';
K_XML_STR_ConfigItem = 'configItem';
K_XML_STR_Control_type = 'control_type';
K_XML_STR_Default = 'default';
K_XML_STR_Description = 'description';
K_XML_STR_Device = 'device';
K_XML_STR_Download_url = 'download_url';
K_XML_STR_Element = 'element';
K_XML_STR_Format = 'format';
K_XML_STR_CONFIGTYPE = 'configtype';
K_XML_STR_MAXVALUE = 'maxvalues';
K_XML_STR_Id = 'id';
K_XML_STR_Info_url = 'info_url';
K_XML_STR_LABEL = 'label';
K_XML_STR_MIN_VAL = 'min_val';
K_XML_STR_MAX_VAL = 'max_val';
K_XML_STR_LISTEN = 'listen';
K_XML_STR_MENUITEM = 'menuItem';
K_XML_STR_MSG_SCHEMA = 'msg_schema';
K_XML_STR_MSG_TYPE = 'msg_type';
K_XML_STR_Option = 'option';
K_XML_STR_Platform = 'platform';
K_XML_STR_PLUGIN_URL = 'plugin_url';
K_XML_STR_Regexp = 'regexp';
K_XML_STR_Schema = 'schema';
K_XML_STR_STATUS = 'status';
K_XML_STR_Trigger = 'trigger';
K_XML_STR_Type = 'type';
K_XML_STR_VALUE = 'value';
K_XML_STR_Vendor = 'vendor';
K_XML_STR_Version = 'version';
K_XML_STR_XplMsg = 'xplMsg';
K_XML_STR_XplPlugin = 'xpl-plugin';
K_XML_STR_XplhalmgrPlugin = 'xplhalmgr-plugin';
// Globals Strings
K_XML_STR_Expires = 'expires';
K_XML_STR_CREATE = 'createts';
K_XML_STR_FORMER = 'former';
K_XML_STR_EXPIRE = 'expirets';
K_XML_STR_Global = 'global';
K_XML_STR_Lastupdate = 'lastupdate';
// Event Strings
K_XML_STR_Dow = 'dow';
K_XML_STR_Endtime = 'endtime';
K_XML_STR_Event = 'event';
K_XML_STR_Eventdatetim = 'eventdatetime';
K_XML_STR_Eventruntime = 'eventruntime';
K_XML_STR_Init = 'init';
K_XML_STR_Interval = 'interval';
K_XML_STR_Param = 'param';
K_XML_STR_Randomtime = 'randomtime';
K_XML_STR_Recurring = 'recurring';
K_XML_STR_Runsub = 'runsub';
K_XML_STR_Starttime = 'starttime';
K_XML_STR_TAG = 'tag';
// Timer Strings
K_XML_STR_ESTIMATED_END_TIME = 'estimatedend';
K_XML_STR_FREQUENCY = 'frequency';
K_XML_STR_MODE = 'mode';
K_XML_STR_REMAINING = 'remaining';
// Determinator Strings
K_XML_STR_Determinator = 'determinator';
K_XML_STR_Display_name = 'display_name';
K_XML_STR_Enabled = 'enabled';
K_XML_STR_ExecuteOrder = 'executeOrder';
K_XML_STR_Expression = 'expression';
K_XML_STR_GroupName = 'groupName';
K_XML_STR_Input = 'input';
K_XML_STR_IsGroup = 'IsGroup';
K_XML_STR_Match = 'match';
K_XML_STR_Msg_target = 'msg_target';
K_XML_STR_MSG_SOURCE = 'msg_source';
K_XML_STR_Operator = 'operator';
K_XML_STR_Output = 'output';
K_XML_STR_Schema_class = 'schema_class';
K_XML_STR_Schema_type = 'schema_type';
K_XML_STR_Source_devic = 'source_device';
K_XML_STR_Source_insta = 'source_instance';
K_XML_STR_Source_vendo = 'source_vendor';
K_XML_STR_Target_devic = 'target_device';
K_XML_STR_Target_insta = 'target_instance';
K_XML_STR_Target_vendo = 'target_vendor';
K_XML_STR_XplAction = 'xplAction';
K_XML_STR_XplActionPar = 'xplActionParam';
K_XML_STR_XplCondition = 'xplCondition';
// Cache Manager Strings
K_XML_STR_Cacheentry = 'cacheentry';
K_XML_STR_Cacheobjectn = 'cacheobjectname';
K_XML_STR_Cacheprefix = 'cacheprefix';
K_XML_STR_StatusTag = 'statustag';
K_XML_STR_DeviceType = 'devicetype';
K_XML_STR_Fieldmap = 'fieldmap';
K_XML_STR_Filter = 'filter';
K_XML_STR_Xpltagname = 'xpltagname';
// Plugins Strings
K_XML_STR_Location = 'location';
K_XML_STR_Plugin = 'plugin';
K_XML_STR_Url = 'url';
// XPL Configuration Strings
K_XML_STR_Key = 'key';
K_XML_STR_XplConfigura = 'xplConfiguration';
type
{ T_clinique_DOMElementList }
T_clinique_DOMElement = class(TDOMElement)
public
function SafeReadNode(const aValue : String) : string;
function SafeFindNode(const aValue : String) : string;
procedure SafeChangeNode(const aNodeName: String; const aValue : string);
procedure SafeAddNode(const aNodeName: String; const aValue : string);
end;
T_clinique_DOMElementList = class(TDOMElementList)
public
function SafeReadNode(const aValue : String) : string;
procedure SafeChangeNode(const aNodeName: String; const aValue : string);
// procedure SafeWriteNode(const aName: String; const aValue : string);
end;
{ TXMLElementList }
generic TXMLElementList<_T> = class(T_clinique_DOMElementList)
private
fKeyName : string;
function GetDocument: TXMLDocument;
function Get_ElementByName(aName : string): _T;
protected
fRootNode : TDOMNode;
fKeyWord : string; // Name of the attribute used as a key in the list
function Get_Element (Index: Integer): _T;
public
constructor Create(const aDocument : TXMLDocument; const aLabel : string; const aKeyName : string); overload;
constructor Create(const aNode : TDOMNode; const aLabel : string; const aKeyName : string); overload;
function AddElement(const aName : string) : _T;
// function Exists(const aName : string) : boolean;
procedure RemoveElement(const aName : string);
procedure EmptyList;
property Element[Index: Integer]: _T read Get_Element; default;
property ElementByName[aName : string] : _T read Get_ElementByName;
property RootNode : TDOMNode read fRootNode;
property Document : TXMLDocument read GetDocument;
end;
implementation
function T_clinique_DOMElement.SafeReadNode(const aValue: String): string;
var DevNode : TDOMNode;
begin
result := '';
DevNode := Attributes.GetNamedItem(aValue);
if DevNode<>nil then result := DevNode.NodeValue;
end;
function T_clinique_DOMElement.SafeFindNode(const aValue: String): string;
var DevNode : TDOMNode;
begin
result := '';
DevNode := FindNode(aValue);
if DevNode = nil then exit;
DevNode := DevNode.FirstChild;
if DevNode<>nil then result := DevNode.NodeValue;
end;
procedure T_clinique_DOMElement.SafeChangeNode(const aNodeName: String; const aValue : string);
var OldNode, NewNode : TDOMNode;
begin
OldNode := FindNode(aNodeName);
if OldNode = nil then exit;
DetachChild(OldNode);
NewNode := OwnerDocument.CreateElement(aNodeName);
NewNode.AppendChild(OwnerDocument.CreateTextNode(aValue));
AppendChild(NewNode);
end;
procedure T_clinique_DOMElement.SafeAddNode(const aNodeName: String; const aValue: string);
var NewNode : TDOMNode;
begin
NewNode := OwnerDocument.CreateElement(aNodeName);
NewNode.AppendChild(OwnerDocument.CreateTextNode(aValue));
AppendChild(NewNode);
end;
{ T_clinique_DOMElementList }
function T_clinique_DOMElementList.SafeReadNode(const aValue: String): string;
var DevNode : TDOMNode;
begin
result := '';
DevNode := FNode.Attributes.GetNamedItem(aValue);
if DevNode<>nil then result := DevNode.NodeValue;
end;
procedure T_clinique_DOMElementList.SafeChangeNode(const aNodeName: String; const aValue: string);
begin
TDOMElement(FNode).SetAttribute(aNodeName,aValue);
end;
{ TXMLElementList }
function TXMLElementList.AddElement(const aName : string) : _T;
var child : TDOMNode;
begin
result := ElementByName[aName];
if TObject(result) = nil then begin
child := Document.CreateElement(fKeyword);
fRootNode.AppendChild(child);
TDOMElement(Child).SetAttribute(fKeyName, aName);
fList.Add(child);
result := _T(child);
end;
end;
{function TXMLElementList.Exists(const aName: string): boolean;
var i : integer;
begin
result := true;
i := count;
for i := 0 to Count-1 do
if _T(Item[i]).GetAttribute(fKeyName) = aName then exit;
result := false;
end;}
procedure TXMLElementList.RemoveElement(const aName: string);
var child : TDOMNode;
begin
child := fRootNode.FirstChild;
repeat
if TDOMElement(Child).GetAttribute(UnicodeString(fKeyName)) = UnicodeString(aName) then begin
fRootNode.RemoveChild(child);
child := nil;
end else child := child.NextSibling;
until (child = nil);
end;
procedure TXMLElementList.EmptyList;
begin
while fRootNode.HasChildNodes do
fRootNode.RemoveChild(RootNode.FirstChild);
end;
function TXMLElementList.GetDocument: TXMLDocument;
begin
result := TXMLDocument(RootNode.OwnerDocument);
end;
function TXMLElementList.Get_ElementByName(aName : string): _T;
var i : integer;
begin
result := nil;
i := count;
for i := 0 to Count-1 do
if _T(Item[i]).GetAttribute(fKeyName) = aName then result := _T(Item[i]);
end;
function TXMLElementList.Get_Element(Index: Integer): _T;
begin
Result := _T(Item[Index]);
end;
constructor TXMLElementList.Create(const aDocument : TXMLDocument; const aLabel : string; const aKeyName : string);
begin
Create(aDocument.FirstChild,aLabel,aKeyName);
end;
constructor TXMLElementList.Create(const aNode : TDOMNode; const aLabel : string; const aKeyName : string);
begin
fRootNode := aNode;
fKeyWord := aLabel;
fKeyName := aKeyName;
inherited Create(fRootNode,fKeyWord);
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC SQLite Call Interface }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.SQLiteCli;
interface
uses
{$IFDEF MSWINDOWS}
Winapi.Windows,
{$ENDIF}
FireDAC.Stan.Intf, FireDAC.Stan.Consts;
{$IFNDEF FireDAC_SQLITE_STATIC}
const
{$IFDEF MSWINDOWS}
C_SQLiteDll: String = 'sqlite3' + C_FD_DLLExt;
C_BDBDll: String = 'libdb_sql51' + C_FD_DLLExt;
{$ENDIF}
{$IFDEF ANDROID}
C_SQLiteDll: String = 'libsqlite' + C_FD_DLLExt;
C_BDBDll: String = 'libdb_sql' + C_FD_DLLExt;
{$ELSE}
{$IFDEF POSIX}
C_CGSQLiteDll: String = 'libcgsqlite3' + C_FD_DLLExt;
C_SQLiteDll: String = 'libsqlite3' + C_FD_DLLExt;
C_BDBDll: String = 'libdb_sql' + C_FD_DLLExt;
{$ENDIF}
{$ENDIF}
{$ENDIF}
type
PUtf8 = PFDAnsiString;
PPUtf8 = ^PUtf8;
sqlite3_int64 = Int64;
sqlite3_uint64 = UInt64;
sqlite3_rtree_dbl = Double;
psqlite3_rtree_dbl = ^sqlite3_rtree_dbl;
// -------------------------------------------------------------------------
// Handles
psqlite3 = Pointer;
psqlite3_blob = Pointer;
psqlite3_context = Pointer;
psqlite3_stmt = Pointer;
psqlite3_value = Pointer;
ppsqlite3_value = ^psqlite3_value;
psqlite3_backup = Pointer;
psqlite3_index_info = ^sqlite3_index_info;
psqlite3_index_constraint = ^sqlite3_index_constraint;
psqlite3_index_orderby = ^sqlite3_index_orderby;
psqlite3_index_constraint_usage = ^sqlite3_index_constraint_usage;
psqlite3_module = ^sqlite3_module;
psqlite3_vtab = ^sqlite3_vtab;
psqlite3_vtab_cursor = ^sqlite3_vtab_cursor;
psqlite3_mem_methods = ^sqlite3_mem_methods;
psqlite3_file = ^sqlite3_file;
psqlite3_io_methods = ^sqlite3_io_methods;
psqlite3_vfs = ^sqlite3_vfs;
psqlite3_rtree_geometry = ^sqlite3_rtree_geometry;
psqlite3_rtree_query_info = ^sqlite3_rtree_query_info;
// -------------------------------------------------------------------------
// Callbacks
Tsqlite3_busy_callback = function (userdata: Pointer; times: Integer): Integer; cdecl;
Tsqlite3_func_callback = procedure (context: psqlite3_context; nargs: Integer;
args: ppsqlite3_value); cdecl;
Tsqlite3_step_callback = procedure (context: psqlite3_context; nargs: Integer;
args: ppsqlite3_value); cdecl;
Tsqlite3_final_callback = procedure (context: psqlite3_context); cdecl;
Tsqlite3_destroy_callback = procedure (value: Pointer); cdecl;
Tsqlite3_commit_callback = function (userdata: Pointer): Integer; cdecl;
Tsqlite3_rollback_callback = procedure (userdata: Pointer); cdecl;
Tsqlite3_trace_callback = procedure (userdata: Pointer; zSql: PUtf8); cdecl;
Tsqlite3_profile_callback = procedure (userdata: Pointer; zSql: PUtf8;
time: sqlite3_uint64); cdecl;
Tsqlite3_auth_callback = function (userdata: Pointer; code: Integer;
zArg1, zArg2, zArg3, zArg4: PUtf8): Integer; cdecl;
Tsqlite3_update_callback = procedure (userdata: Pointer; oper: Integer;
zDb, zTable: PUtf8; rowid: sqlite3_int64); cdecl;
Tsqlite3_collation_callback = procedure (userdata: Pointer; db: psqlite3;
eTextRep: Integer; name: Pointer {utf8/utf16}); cdecl;
Tsqlite3_compare_callback = function (userdata: Pointer; len1: Integer;
str1: Pointer {utf8/utf16}; len2: Integer; str2: Pointer {utf8/utf16}): Integer; cdecl;
Tsqlite3_progress_callback = function (userdata: Pointer): Integer; cdecl;
Tsqlite3_wal_callback = function (userdata: Pointer; db: psqlite3;
name: PByte; nPages: Integer): Integer; cdecl;
Tsqlite3_rtree_xGeom_callback = function (geom: psqlite3_rtree_geometry; nCoord: Integer;
aCoord: psqlite3_rtree_dbl; var pRes: Integer): Integer; cdecl;
Tsqlite3_rtree_xQuery_callback = function (info: psqlite3_rtree_query_info): Integer; cdecl;
Tsqlite3_rtree_xDelUser_callback = procedure (userdata: Pointer); cdecl;
// -------------------------------------------------------------------------
// Virtual Table Object
// Virtual Table Indexing Information
sqlite3_index_constraint = record
iColumn: Integer; // Column on left-hand side of constraint
op: Byte; // Constraint operator
usable: Byte; // True if this constraint is usable
iTermOffset: Integer; // Used internally - xBestIndex should ignore
end;
sqlite3_index_orderby = record
iColumn: Integer; // Column number
desc: Byte; // True for DESC. False for ASC.
end;
sqlite3_index_constraint_usage = record
argvIndex: Integer; // if >0, constraint is part of argv to xFilter
omit: Byte; // Do not code a test for this constraint
end;
sqlite3_index_info = record
// Inputs
nConstraint: Integer; // Number of entries in aConstraint
aConstraint: psqlite3_index_constraint; // Table of WHERE clause constraints
nOrderBy: Integer; // Number of terms in the ORDER BY clause
aOrderBy: psqlite3_index_orderby; // The ORDER BY clause
// Outputs
aConstraintUsage: psqlite3_index_constraint_usage;
idxNum: Integer; // Number used to identify the index
idxStr: PUtf8; // String, possibly obtained from sqlite3_malloc
needToFreeIdxStr: Integer; // Free idxStr using sqlite3_free() if true
orderByConsumed: Integer; // True if output is already ordered
estimatedCost: Double; // Estimated cost of using this index
// Fields below are only available in SQLite 3.8.2 and later
estimatedRows: sqlite3_int64; // Estimated number of rows returned
// Fields below are only available in SQLite 3.9.0 and later
idxFlags: Integer; // Mask of SQLITE_INDEX_SCAN_* flags
// Fields below are only available in SQLite 3.10.0 and later
colUsed: sqlite3_uint64; // Input: Mask of columns used by statement
end;
sqlite3_module = record
iVersion: Integer;
xCreate: function(db: psqlite3; pAux: Pointer; argc: Integer; argv: PPUtf8;
var ppVTab: psqlite3_vtab; var pzErr: PUtf8): Integer; cdecl;
xConnect: function (db: psqlite3; pAux: Pointer; argc: Integer; argv: PPUtf8;
var ppVTab: psqlite3_vtab; var pzErr: PUtf8): Integer; cdecl;
xBestIndex: function (pVTab: psqlite3_vtab; info: psqlite3_index_info): Integer; cdecl;
xDisconnect: function (pVTab: psqlite3_vtab): Integer; cdecl;
xDestroy: function (pVTab: psqlite3_vtab): Integer; cdecl;
xOpen: function (pVTab: psqlite3_vtab; var ppCursor: psqlite3_vtab_cursor): Integer; cdecl;
xClose: function (cursor: psqlite3_vtab_cursor): Integer; cdecl;
xFilter: function (cursor: psqlite3_vtab_cursor; idxNum: Integer; idxStr: PUtf8;
argc: Integer; argv: ppsqlite3_value): Integer; cdecl;
xNext: function (cursor: psqlite3_vtab_cursor): Integer; cdecl;
xEof: function (cursor: psqlite3_vtab_cursor): Integer; cdecl;
xColumn: function (cursor: psqlite3_vtab_cursor; context: psqlite3_context;
index: Integer): Integer; cdecl;
xRowid: function (cursor: psqlite3_vtab_cursor; var pRowid: sqlite3_int64): Integer; cdecl;
xUpdate: function (pVTab: psqlite3_vtab; nArg: Integer; apArgs: ppsqlite3_value;
var rowid: sqlite3_int64): Integer; cdecl;
xBegin: function (pVTab: psqlite3_vtab): Integer; cdecl;
xSync: function (pVTab: psqlite3_vtab): Integer; cdecl;
xCommit: function (pVTab: psqlite3_vtab): Integer; cdecl;
xRollback: function (pVTab: psqlite3_vtab): Integer; cdecl;
xFindFunction: function (pVTab: psqlite3_vtab; nArg: Integer; zName: PUtf8;
var pxFunc: Tsqlite3_func_callback; var ppArg: Pointer): Integer; cdecl;
xRename: function (pVTab: psqlite3_vtab; zNew: PUtf8): Integer; cdecl;
// The methods above are in version 1 of the sqlite_module object. Those
// below are for version 2 and greater.
// SQLite 3.7.7
xSavepoint: function (pVTab: psqlite3_vtab; p: Integer): Integer; cdecl;
xRelease: function (pVTab: psqlite3_vtab; p: Integer): Integer; cdecl;
xRollbackTo: function (pVTab: psqlite3_vtab; p: Integer): Integer; cdecl;
end;
// Virtual Table Instance Object
sqlite3_vtab = record
pModule: psqlite3_module; // The module for this virtual table
nRef: Integer; // Used internally
zErrMsg: PUtf8; // Error message from sqlite3_mprintf()
// Virtual table implementations will typically add additional fields
end;
// Virtual Table Cursor Object
sqlite3_vtab_cursor = record
pVtab: psqlite3_vtab; // Virtual table of this cursor
// Virtual table implementations will typically add additional fields
end;
// -------------------------------------------------------------------------
// OS abstraction layer
// Memory Allocation Routines
sqlite3_mem_methods = record
xMalloc: function (size: Integer): Pointer; cdecl; // Memory allocation function
xFree: procedure (ptr: Pointer); cdecl; // Free a prior allocation
xRealloc: function (ptr: Pointer; size: Integer): Pointer; cdecl; // Resize an allocation
xSize: function (ptr: Pointer): Integer; cdecl; // Return the size of an allocation
xRoundup: function (size: Integer): Integer; cdecl; // Round up request size to allocation size
xInit: function (data: Pointer): Integer; cdecl; // Initialize the memory allocator
xShutdown: procedure (data: Pointer); cdecl; // Deinitialize the memory allocator
pAppData: Pointer; // Argument to xInit() and xShutdown()
end;
// OS Interface Open File Handle
sqlite3_file = record
pMethods: psqlite3_io_methods; // Methods for an open file
end;
// OS Interface File Virtual Methods Object
sqlite3_io_methods = record
iVersion: Integer;
xClose: function (pFile: psqlite3_file): Integer; cdecl;
xRead: function (pFile: psqlite3_file; buf: Pointer; iAmt: Integer; iOfst: sqlite3_int64): Integer; cdecl;
xWrite: function (pFile: psqlite3_file; bug: Pointer; iAmt: Integer; iOfst: sqlite3_int64): Integer; cdecl;
xTruncate: function (pFile: psqlite3_file; size: sqlite3_int64): Integer; cdecl;
xSync: function (pFile: psqlite3_file; flags: Integer): Integer; cdecl;
xFileSize: function (pFile: psqlite3_file; var pSize: sqlite3_int64): Integer; cdecl;
xLock: function (pFile: psqlite3_file; mode: Integer): Integer; cdecl;
xUnlock: function (pFile: psqlite3_file; mode: Integer): Integer; cdecl;
xCheckReservedLock: function (pFile: psqlite3_file; var pResOut: Integer): Integer; cdecl;
xFileControl: function (pFile: psqlite3_file; op: Integer; pArg: Pointer): Integer; cdecl;
xSectorSize: function (pFile: psqlite3_file): Integer; cdecl;
xDeviceCharacteristics: function (pFile: psqlite3_file): Integer; cdecl;
// Methods above are valid for version 1
xShmMap: function (pFile: psqlite3_file; iPg: Integer; pgsz: Integer; i: Integer; p: PPointer): Integer; cdecl;
xShmLock: function (pFile: psqlite3_file; offset: Integer; n: Integer; flags: Integer): Integer; cdecl;
xShmBarrier: procedure (pFile: psqlite3_file); cdecl;
xShmUnmap: function (pFile: psqlite3_file; deleteFlag: Integer): Integer; cdecl;
// Methods above are valid for version 2
xFetch: function (pFile: sqlite3_file; iOfst: sqlite3_int64; iAmt: Integer; pp: PPointer): Integer; cdecl;
xUnfetch: function (pFile: sqlite3_file; iOfst: sqlite3_int64; p: Pointer): Integer; cdecl;
// Methods above are valid for version 3
// Additional methods may be added in future releases
end;
// OS Interface Object
Tsqlite3_vfs_xOpen = function (pVfs: psqlite3_vfs; zName: PFDAnsiString; pFile: psqlite3_file;
flags: Integer; var pOutFlags: Integer): Integer; cdecl;
Tsqlite3_syscall_ptr = procedure (); cdecl;
sqlite3_vfs = record
iVersion: Integer; // Structure version number
szOsFile: Integer; // Size of subclassed sqlite3_file
mxPathname: Integer; // Maximum file pathname length
pNext: psqlite3_vfs; // Next registered VFS
zName: PFDAnsiString; // Name of this virtual file system
pAppData: Pointer; // Pointer to application-specific data
xOpen: Tsqlite3_vfs_xOpen;
xDelete: function (pVfs: psqlite3_vfs; zName: PFDAnsiString; syncDir: Integer): Integer; cdecl;
xAccess: function (pVfs: psqlite3_vfs; zName: PFDAnsiString; flags: Integer; var pResOut: Integer): Integer; cdecl;
xFullPathname: function (pVfs: psqlite3_vfs; zName: PFDAnsiString; nOut: Integer; zOut: PFDAnsiString): Integer; cdecl;
xDlOpen: function (pVfs: psqlite3_vfs; zFilename: PFDAnsiString): Pointer; cdecl;
xDlError: procedure (pVfs: psqlite3_vfs; nByte: Integer; zErrMsg: PFDAnsiString); cdecl;
xDlSym: function (pVfs: psqlite3_vfs; ptr: Pointer; zSymbol: PFDAnsiString): Pointer; cdecl;
xDlClose: procedure (pVfs: psqlite3_vfs; ptr: Pointer); cdecl;
xRandomness: function (pVfs: psqlite3_vfs; nByte: Integer; zOut: PFDAnsiString): Integer; cdecl;
xSleep: function (pVfs: psqlite3_vfs; microseconds: Integer): Integer; cdecl;
xCurrentTime: function (pVfs: psqlite3_vfs; var tm: double): Integer; cdecl;
xGetLastError: function (pVfs: psqlite3_vfs; l: Integer; v: PFDAnsiString): Integer; cdecl;
//
// The methods above are in version 1 of the sqlite_vfs object
// definition. Those that follow are added in version 2 or later
//
xCurrentTimeInt64: function (pVfs: psqlite3_vfs; var tm: sqlite3_int64): Integer; cdecl;
//
// The methods above are in versions 1 and 2 of the sqlite_vfs object.
// New fields may be appended in figure versions. The iVersion
// value will increment whenever this happens.
xSetSystemCall: function (pVfs: psqlite3_vfs; zName: PFDAnsiString; p: Tsqlite3_syscall_ptr): Integer; cdecl;
xGetSystemCall: function (pVfs: psqlite3_vfs; zName: PFDAnsiString): Tsqlite3_syscall_ptr; cdecl;
xNextSystemCall: function (pVfs: psqlite3_vfs; zName: PFDAnsiString): PFDAnsiString; cdecl;
//
// The methods above are in versions 1 through 3 of the sqlite_vfs object.
// New fields may be appended in figure versions. The iVersion
// value will increment whenever this happens.
//
end;
// -------------------------------------------------------------------------
// RTree support
sqlite3_rtree_geometry = record
pContext: Pointer; // Copy of pContext passed to s_r_g_c()
nParam: Integer; // Size of array aParam[]
aParam: psqlite3_rtree_dbl; // Parameters passed to SQL geom function
pUser: Pointer; // Callback implementation user data
xDelUser: Tsqlite3_rtree_xDelUser_callback; // Called by SQLite to clean up pUser
end;
sqlite3_rtree_query_info = record
pContext: Pointer; // pContext from when function registered
nParam: Integer; // Number of function parameters
aParam: psqlite3_rtree_dbl; // value of function parameters
pUser: Pointer; // callback can use this, if desired
xDelUser: Tsqlite3_rtree_xDelUser_callback; // function to free pUser
aCoord: psqlite3_rtree_dbl; // Coordinates of node or entry to check
anQueue: PCardinal; // Number of pending entries in the queue
nCoord: Integer; // Number of coordinates
iLevel: Integer; // Level of current node or entry
mxLevel: Integer; // The largest iLevel value in the tree
iRowid: sqlite3_int64; // Rowid for current entry
rParentScore: sqlite3_rtree_dbl; // Score of parent node
eParentWithin: Integer; // Visibility of parent node
eWithin: Integer; // OUT: Visiblity
rScore: sqlite3_rtree_dbl; // OUT: Write the score here
end;
const
// Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
NOT_WITHIN = 0; // Object completely outside of query region
PARTLY_WITHIN = 1; // Object partially overlaps query region
FULLY_WITHIN = 2; // Object fully contained within query region
const
// -------------------------------------------------------------------------
// Flags For File Open Operations
SQLITE_OPEN_READONLY = $00000001; // Ok for sqlite3_open_v2()
SQLITE_OPEN_READWRITE = $00000002; // Ok for sqlite3_open_v2()
SQLITE_OPEN_CREATE = $00000004; // Ok for sqlite3_open_v2()
SQLITE_OPEN_DELETEONCLOSE = $00000008; // VFS only
SQLITE_OPEN_EXCLUSIVE = $00000010; // VFS only
SQLITE_OPEN_MAIN_DB = $00000100; // VFS only
SQLITE_OPEN_TEMP_DB = $00000200; // VFS only
SQLITE_OPEN_TRANSIENT_DB = $00000400; // VFS only
SQLITE_OPEN_MAIN_JOURNAL = $00000800; // VFS only
SQLITE_OPEN_TEMP_JOURNAL = $00001000; // VFS only
SQLITE_OPEN_SUBJOURNAL = $00002000; // VFS only
SQLITE_OPEN_MASTER_JOURNAL = $00004000; // VFS only
SQLITE_OPEN_NOMUTEX = $00008000; // Ok for sqlite3_open_v2()
SQLITE_OPEN_FULLMUTEX = $00010000; // Ok for sqlite3_open_v2()
// SQLite 3.7
SQLITE_OPEN_SHAREDCACHE = $00020000; // Ok for sqlite3_open_v2()
SQLITE_OPEN_PRIVATECACHE = $00040000; // Ok for sqlite3_open_v2()
SQLITE_OPEN_WAL = $00080000; // VFS only
// Authorizer Return Codes
SQLITE_DENY = 1; // Abort the SQL statement with an error
SQLITE_IGNORE = 2; // Don't allow access, but don't generate an error
// Status Parameters
SQLITE_STATUS_MEMORY_USED = 0;
SQLITE_STATUS_PAGECACHE_USED = 1;
SQLITE_STATUS_PAGECACHE_OVERFLOW = 2;
SQLITE_STATUS_SCRATCH_USED = 3;
SQLITE_STATUS_SCRATCH_OVERFLOW = 4;
SQLITE_STATUS_MALLOC_SIZE = 5;
SQLITE_STATUS_PARSER_STACK = 6;
SQLITE_STATUS_PAGECACHE_SIZE = 7;
SQLITE_STATUS_SCRATCH_SIZE = 8;
SQLITE_STATUS_MALLOC_COUNT = 9;
// Status Parameters for database connections
SQLITE_DBSTATUS_LOOKASIDE_USED = 0;
SQLITE_DBSTATUS_CACHE_USED = 1;
SQLITE_DBSTATUS_SCHEMA_USED = 2;
SQLITE_DBSTATUS_STMT_USED = 3;
SQLITE_DBSTATUS_LOOKASIDE_HIT = 4;
SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE = 5;
SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL = 6;
SQLITE_DBSTATUS_CACHE_HIT = 7;
SQLITE_DBSTATUS_CACHE_MISS = 8;
SQLITE_DBSTATUS_CACHE_WRITE = 9;
SQLITE_DBSTATUS_DEFERRED_FKS = 10;
SQLITE_DBSTATUS_MAX = 10; // Largest defined DBSTATUS
// Status Parameters for prepared statements
SQLITE_STMTSTATUS_FULLSCAN_STEP = 1;
SQLITE_STMTSTATUS_SORT = 2;
SQLITE_STMTSTATUS_AUTOINDEX = 3;
SQLITE_STMTSTATUS_VM_STEP = 4;
SQLITE_STMTSTATUS_REPREPARE = 5;
SQLITE_STMTSTATUS_RUN = 6;
SQLITE_STMTSTATUS_MEMUSED = 99;
// Result Codes
SQLITE_OK = 0; // Successful result
// beginning-of-error-codes
SQLITE_ERROR = 1; // SQL error or missing database
SQLITE_INTERNAL = 2; // Internal logic error in SQLite
SQLITE_PERM = 3; // Access permission denied
SQLITE_ABORT = 4; // Callback routine requested an abort
SQLITE_BUSY = 5; // The database file is locked
SQLITE_LOCKED = 6; // A table in the database is locked
SQLITE_NOMEM = 7; // A malloc() failed
SQLITE_READONLY = 8; // Attempt to write a readonly database
SQLITE_INTERRUPT = 9; // Operation terminated by sqlite3_interrupt()
SQLITE_IOERR = 10; // Some kind of disk I/O error occurred
SQLITE_CORRUPT = 11; // The database disk image is malformed
SQLITE_NOTFOUND = 12; // Unknown opcode in sqlite3_file_control()
SQLITE_FULL = 13; // Insertion failed because database is full
SQLITE_CANTOPEN = 14; // Unable to open the database file
SQLITE_PROTOCOL = 15; // Database lock protocol error
SQLITE_EMPTY = 16; // Database is empty
SQLITE_SCHEMA = 17; // The database schema changed
SQLITE_TOOBIG = 18; // String or BLOB exceeds size limit
SQLITE_CONSTRAINT = 19; // Abort due to constraint violation
SQLITE_MISMATCH = 20; // Data type mismatch
SQLITE_MISUSE = 21; // Library used incorrectly
SQLITE_NOLFS = 22; // Uses OS features not supported on host
SQLITE_AUTH = 23; // Authorization denied
SQLITE_FORMAT = 24; // Auxiliary database format error
SQLITE_RANGE = 25; // 2nd parameter to sqlite3_bind out of range
SQLITE_NOTADB = 26; // File opened that is not a database file
SQLITE_NOTICE = 27; // Notifications from sqlite3_log()
SQLITE_WARNING = 28; // Warnings from sqlite3_log()
SQLITE_ROW = 100; // sqlite3_step() has another row ready
SQLITE_DONE = 101; // sqlite3_step() has finished executing
// Extended Result Codes
SQLITE_IOERR_READ = (SQLITE_IOERR or (1 shl 8));
SQLITE_IOERR_SHORT_READ = (SQLITE_IOERR or (2 shl 8));
SQLITE_IOERR_WRITE = (SQLITE_IOERR or (3 shl 8));
SQLITE_IOERR_FSYNC = (SQLITE_IOERR or (4 shl 8));
SQLITE_IOERR_DIR_FSYNC = (SQLITE_IOERR or (5 shl 8));
SQLITE_IOERR_TRUNCATE = (SQLITE_IOERR or (6 shl 8));
SQLITE_IOERR_FSTAT = (SQLITE_IOERR or (7 shl 8));
SQLITE_IOERR_UNLOCK = (SQLITE_IOERR or (8 shl 8));
SQLITE_IOERR_RDLOCK = (SQLITE_IOERR or (9 shl 8));
SQLITE_IOERR_DELETE = (SQLITE_IOERR or (10 shl 8));
SQLITE_IOERR_BLOCKED = (SQLITE_IOERR or (11 shl 8));
SQLITE_IOERR_NOMEM = (SQLITE_IOERR or (12 shl 8));
SQLITE_IOERR_ACCESS = (SQLITE_IOERR or (13 shl 8));
SQLITE_IOERR_CHECKRESERVEDLOCK = (SQLITE_IOERR or (14 shl 8));
SQLITE_IOERR_LOCK = (SQLITE_IOERR or (15 shl 8));
SQLITE_IOERR_CLOSE = (SQLITE_IOERR or (16 shl 8));
SQLITE_IOERR_DIR_CLOSE = (SQLITE_IOERR or (17 shl 8));
SQLITE_IOERR_SHMOPEN = (SQLITE_IOERR or (18 shl 8));
SQLITE_IOERR_SHMSIZE = (SQLITE_IOERR or (19 shl 8));
SQLITE_IOERR_SHMLOCK = (SQLITE_IOERR or (20 shl 8));
SQLITE_IOERR_SHMMAP = (SQLITE_IOERR or (21 shl 8));
SQLITE_IOERR_SEEK = (SQLITE_IOERR or (22 shl 8));
SQLITE_IOERR_DELETE_NOENT = (SQLITE_IOERR or (23 shl 8));
SQLITE_IOERR_MMAP = (SQLITE_IOERR or (24 shl 8));
SQLITE_IOERR_GETTEMPPATH = (SQLITE_IOERR or (25 shl 8));
SQLITE_IOERR_CONVPATH = (SQLITE_IOERR or (26 shl 8));
SQLITE_IOERR_VNODE = (SQLITE_IOERR or (27 shl 8));
SQLITE_LOCKED_SHAREDCACHE = (SQLITE_LOCKED or (1 shl 8));
SQLITE_BUSY_RECOVERY = (SQLITE_BUSY or (1 shl 8));
SQLITE_BUSY_SNAPSHOT = (SQLITE_BUSY or (2 shl 8));
SQLITE_CANTOPEN_NOTEMPDIR = (SQLITE_CANTOPEN or (1 shl 8));
SQLITE_CANTOPEN_ISDIR = (SQLITE_CANTOPEN or (2 shl 8));
SQLITE_CANTOPEN_FULLPATH = (SQLITE_CANTOPEN or (3 shl 8));
SQLITE_CANTOPEN_CONVPATH = (SQLITE_CANTOPEN or (4 shl 8));
SQLITE_CORRUPT_VTAB = (SQLITE_CORRUPT or (1 shl 8));
SQLITE_READONLY_RECOVERY = (SQLITE_READONLY or (1 shl 8));
SQLITE_READONLY_CANTLOCK = (SQLITE_READONLY or (2 shl 8));
SQLITE_READONLY_ROLLBACK = (SQLITE_READONLY or (3 shl 8));
SQLITE_READONLY_DBMOVED = (SQLITE_READONLY or (4 shl 8));
SQLITE_ABORT_ROLLBACK = (SQLITE_ABORT or (2 shl 8));
SQLITE_CONSTRAINT_CHECK = (SQLITE_CONSTRAINT or (1 shl 8));
SQLITE_CONSTRAINT_COMMITHOOK = (SQLITE_CONSTRAINT or (2 shl 8));
SQLITE_CONSTRAINT_FOREIGNKEY = (SQLITE_CONSTRAINT or (3 shl 8));
SQLITE_CONSTRAINT_FUNCTION = (SQLITE_CONSTRAINT or (4 shl 8));
SQLITE_CONSTRAINT_NOTNULL = (SQLITE_CONSTRAINT or (5 shl 8));
SQLITE_CONSTRAINT_PRIMARYKEY = (SQLITE_CONSTRAINT or (6 shl 8));
SQLITE_CONSTRAINT_TRIGGER = (SQLITE_CONSTRAINT or (7 shl 8));
SQLITE_CONSTRAINT_UNIQUE = (SQLITE_CONSTRAINT or (8 shl 8));
SQLITE_CONSTRAINT_VTAB = (SQLITE_CONSTRAINT or (9 shl 8));
SQLITE_CONSTRAINT_ROWID = (SQLITE_CONSTRAINT or(10 shl 8));
SQLITE_NOTICE_RECOVER_WAL = (SQLITE_NOTICE or (1 shl 8));
SQLITE_NOTICE_RECOVER_ROLLBACK = (SQLITE_NOTICE or (2 shl 8));
SQLITE_WARNING_AUTOINDEX = (SQLITE_WARNING or (1 shl 8));
SQLITE_AUTH_USER = (SQLITE_AUTH or (1 shl 8));
// Boolean results
SQLITE_FALSE = 0;
SQLITE_TRUE = 1;
// Fundamental Datatypes
SQLITE_INTEGER = 1;
SQLITE_FLOAT = 2;
SQLITE_TEXT = 3;
SQLITE_BLOB = 4;
SQLITE_NULL = 5;
// Authorizer Action Codes
// *********************************** 3rd *********** 4th ***********
SQLITE_CREATE_INDEX = 1; // Index Name Table Name
SQLITE_CREATE_TABLE = 2; // Table Name NULL
SQLITE_CREATE_TEMP_INDEX = 3; // Index Name Table Name
SQLITE_CREATE_TEMP_TABLE = 4; // Table Name NULL
SQLITE_CREATE_TEMP_TRIGGER = 5; // Trigger Name Table Name
SQLITE_CREATE_TEMP_VIEW = 6; // View Name NULL
SQLITE_CREATE_TRIGGER = 7; // Trigger Name Table Name
SQLITE_CREATE_VIEW = 8; // View Name NULL
SQLITE_DELETE = 9; // Table Name NULL
SQLITE_DROP_INDEX = 10; // Index Name Table Name
SQLITE_DROP_TABLE = 11; // Table Name NULL
SQLITE_DROP_TEMP_INDEX = 12; // Index Name Table Name
SQLITE_DROP_TEMP_TABLE = 13; // Table Name NULL
SQLITE_DROP_TEMP_TRIGGER = 14; // Trigger Name Table Name
SQLITE_DROP_TEMP_VIEW = 15; // View Name NULL
SQLITE_DROP_TRIGGER = 16; // Trigger Name Table Name
SQLITE_DROP_VIEW = 17; // View Name NULL
SQLITE_INSERT = 18; // Table Name NULL
SQLITE_PRAGMA = 19; // Pragma Name 1st arg or NULL
SQLITE_READ = 20; // Table Name Column Name
SQLITE_SELECT = 21; // NULL NULL
SQLITE_TRANSACTION = 22; // NULL NULL
SQLITE_UPDATE = 23; // Table Name Column Name
SQLITE_ATTACH = 24; // Filename NULL
SQLITE_DETACH = 25; // Database Name NULL
SQLITE_ALTER_TABLE = 26; // Database Name Table Name
SQLITE_REINDEX = 27; // Index Name NULL
SQLITE_ANALYZE = 28; // Table Name NULL
SQLITE_CREATE_VTABLE = 29; // Table Name Module Name
SQLITE_DROP_VTABLE = 30; // Table Name Module Name
SQLITE_FUNCTION = 31; // Function Name NULL
SQLITE_SAVEPOINT = 32; // Operation Savepoint Name
SQLITE_COPY = 0; // No longer used
SQLITE_RECURSIVE = 33; // NULL NULL
// Configuration Options
SQLITE_CONFIG_SINGLETHREAD = 1; // nil
SQLITE_CONFIG_MULTITHREAD = 2; // nil
SQLITE_CONFIG_SERIALIZED = 3; // nil
SQLITE_CONFIG_MALLOC = 4; // sqlite3_mem_methods*
SQLITE_CONFIG_GETMALLOC = 5; // sqlite3_mem_methods*
SQLITE_CONFIG_SCRATCH = 6; // void*, int sz, int N
SQLITE_CONFIG_PAGECACHE = 7; // void*, int sz, int N
SQLITE_CONFIG_HEAP = 8; // void*, int nByte, int min
SQLITE_CONFIG_MEMSTATUS = 9; // boolean
SQLITE_CONFIG_MUTEX = 10; // sqlite3_mutex_methods*
SQLITE_CONFIG_GETMUTEX = 11; // sqlite3_mutex_methods*
SQLITE_CONFIG_CHUNKALLOC = 12; // int threshold
// previously SQLITE_CONFIG_LOOKASIDE = 13 which is now unused.
SQLITE_CONFIG_PCACHE = 14; // sqlite3_pcache_methods*
SQLITE_CONFIG_GETPCACHE = 15; // sqlite3_pcache_methods*
SQLITE_CONFIG_LOG = 16; // xFunc, void*
SQLITE_CONFIG_URI = 17; // int
SQLITE_CONFIG_PCACHE2 = 18; // sqlite3_pcache_methods2*
SQLITE_CONFIG_GETPCACHE2 = 19; // sqlite3_pcache_methods2*
SQLITE_CONFIG_COVERING_INDEX_SCAN = 20; // int
SQLITE_CONFIG_SQLLOG = 21; // xSqllog, void*
SQLITE_CONFIG_MMAP_SIZE = 22; // sqlite3_int64, sqlite3_int64
SQLITE_CONFIG_WIN32_HEAPSIZE = 23; // int nByte
SQLITE_CONFIG_PCACHE_HDRSZ = 24; // int *psz
SQLITE_CONFIG_PMASZ = 25; // unsigned int szPma
// Configuration Options
SQLITE_DBCONFIG_LOOKASIDE = 1001; // void* int int
SQLITE_DBCONFIG_ENABLE_FKEY = 1002; // int int*
SQLITE_DBCONFIG_ENABLE_TRIGGER = 1003; // int int*
// Virtual Table Indexing Information
SQLITE_INDEX_CONSTRAINT_EQ = 2;
SQLITE_INDEX_CONSTRAINT_GT = 4;
SQLITE_INDEX_CONSTRAINT_LE = 8;
SQLITE_INDEX_CONSTRAINT_LT = 16;
SQLITE_INDEX_CONSTRAINT_GE = 32;
SQLITE_INDEX_CONSTRAINT_MATCH = 64;
// 3.10.0
SQLITE_INDEX_CONSTRAINT_LIKE = 65;
SQLITE_INDEX_CONSTRAINT_GLOB = 66;
SQLITE_INDEX_CONSTRAINT_REGEXP = 67;
// 3.21.0
SQLITE_INDEX_CONSTRAINT_NE = 68;
SQLITE_INDEX_CONSTRAINT_ISNOT = 69;
SQLITE_INDEX_CONSTRAINT_ISNOTNULL = 70;
SQLITE_INDEX_CONSTRAINT_ISNULL = 71;
SQLITE_INDEX_CONSTRAINT_IS = 72;
// Virtual Table Scan Flags
SQLITE_INDEX_SCAN_UNIQUE = 1; // Scan visits at most 1 row
// Virtual Table Safecall result
E_SQLITE_VTAB_RES = HRESULT($8000);
// Run-Time Limit Categories
SQLITE_LIMIT_LENGTH = 0;
SQLITE_LIMIT_SQL_LENGTH = 1;
SQLITE_LIMIT_COLUMN = 2;
SQLITE_LIMIT_EXPR_DEPTH = 3;
SQLITE_LIMIT_COMPOUND_SELECT = 4;
SQLITE_LIMIT_VDBE_OP = 5;
SQLITE_LIMIT_FUNCTION_ARG = 6;
SQLITE_LIMIT_ATTACHED = 7;
SQLITE_LIMIT_LIKE_PATTERN_LENGTH = 8;
SQLITE_LIMIT_VARIABLE_NUMBER = 9;
SQLITE_LIMIT_TRIGGER_DEPTH = 10;
SQLITE_LIMIT_WORKER_THREADS = 11;
// Constants Defining Special Destructor Behavior
var
SQLITE_STATIC: Tsqlite3_destroy_callback;
SQLITE_TRANSIENT: Tsqlite3_destroy_callback;
const
// Text Encodings
SQLITE_UTF16NATIVE = 0;
SQLITE_UTF8 = 1;
SQLITE_UTF16LE = 2;
SQLITE_UTF16BE = 3;
SQLITE_UTF16 = 4; // Use native byte order
SQLITE_ANY = 5; // sqlite3_create_function only
SQLITE_UTF16_ALIGNED = 8; // sqlite3_create_collation only
// Function flags
SQLITE_DETERMINISTIC = $800;
// VTab index modes
SQLITE_VTAB_DS_ROWID_IDX = 1;
SQLITE_VTAB_DS_KEY_IDX = 2;
SQLITE_VTAB_DS_ORD_IDX = 4;
// VTab configuration options
SQLITE_VTAB_CONSTRAINT_SUPPORT = 1;
// VTab conflict resolution modes
SQLITE_ROLLBACK = 1;
// SQLITE_IGNORE = 2; // Also used by sqlite3_authorizer() callback */
SQLITE_FAIL = 3;
// SQLITE_ABORT = 4; // Also an error code */
SQLITE_REPLACE = 5;
{$IFDEF FireDAC_SQLITE_STATIC}
const
{$IFDEF FireDAC_SQLITE_EXTERNAL}
{$IFDEF UNDERSCOREIMPORTNAME}
_SLU = '_';
{$ELSE}
_SLU = '';
{$ENDIF}
{$IF DEFINED(MACOS) and not DEFINED(IOS)}
C_FD_SQLiteLib = 'libcgsqlite3.dylib';
{$ELSE}
C_FD_SQLiteLib = 'libsqlite.a';
{$ENDIF}
{$ELSE}
{$IFDEF FireDAC_32}
C_FD_SQLiteLib = 'sqlite3_x86.obj';
{$L sqlite3_x86.obj}
{$ENDIF}
{$IFDEF FireDAC_64}
C_FD_SQLiteLib = 'sqlite3_x64.obj';
{$L sqlite3_x64.obj}
{$ENDIF}
{$ENDIF}
function sqlite3_libversion(): PFDAnsiString; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_libversion' {$ENDIF};
function sqlite3_libversion_number(): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_libversion_number' {$ENDIF};
function sqlite3_compileoption_used(zOptName: PFDAnsiString): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_compileoption_used' {$ENDIF};
function sqlite3_compileoption_get(N: Integer): PFDAnsiString; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_compileoption_get' {$ENDIF};
function sqlite3_enable_shared_cache(onoff: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_enable_shared_cache' {$ENDIF};
function sqlite3_release_memory(amount: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_release_memory' {$ENDIF};
procedure sqlite3_soft_heap_limit(amount: Integer); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_soft_heap_limit' {$ENDIF};
function sqlite3_status(op: Integer; var pCurrent: Integer; var pHighwater: Integer; resetFlag: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_status' {$ENDIF};
function sqlite3_initialize(): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_initialize' {$ENDIF};
function sqlite3_shutdown(): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_shutdown' {$ENDIF};
function sqlite3_malloc(n: Integer): Pointer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_malloc' {$ENDIF};
function sqlite3_memory_used(): sqlite3_int64; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_memory_used' {$ENDIF};
function sqlite3_memory_highwater(resetFlag: Integer): sqlite3_int64; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_memory_highwater' {$ENDIF};
procedure sqlite3_free(APtr: Pointer); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_free' {$ENDIF};
function sqlite3_config(option: Integer): Integer; cdecl varargs; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_config' {$ENDIF};
function sqlite3_open(filename: PByte; var ppDb: psqlite3): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_open' {$ENDIF};
function sqlite3_open16(filename: PByte; var ppDb: psqlite3): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_open16' {$ENDIF};
function sqlite3_open_v2(filename: PUtf8; var ppDb: psqlite3; flags: Integer; zVfs: PFDAnsiString): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_open_v2' {$ENDIF};
function sqlite3_close(db: psqlite3): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_close' {$ENDIF};
function sqlite3_busy_timeout(db: psqlite3; ms: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_busy_timeout' {$ENDIF};
function sqlite3_busy_handler(db: psqlite3; callback: Tsqlite3_busy_callback; userdata: Pointer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_busy_handler' {$ENDIF};
function sqlite3_trace(db: psqlite3; xTrace: Tsqlite3_trace_callback; userdata: Pointer): Pointer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_trace' {$ENDIF};
function sqlite3_profile(db: psqlite3; xProfile: Tsqlite3_profile_callback; userdata: Pointer): Pointer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_profile' {$ENDIF};
function sqlite3_set_authorizer(db: psqlite3; xAuth: Tsqlite3_auth_callback; userdata: Pointer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_set_authorizer' {$ENDIF};
function sqlite3_get_autocommit(db: psqlite3): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_get_autocommit' {$ENDIF};
function sqlite3_commit_hook(db: psqlite3; callback: Tsqlite3_commit_callback; userdata: Pointer): Pointer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_commit_hook' {$ENDIF};
function sqlite3_rollback_hook(db: psqlite3; callback: Tsqlite3_rollback_callback; userdata: Pointer): Pointer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_rollback_hook' {$ENDIF};
function sqlite3_table_column_metadata(db: psqlite3; zDbName: PUtf8; zTableName: PUtf8; zColumnName: PUtf8; var pzDataType: PUtf8; var pzCollSeq: PUtf8; var pNotNull: Integer; var pPrimaryKey: Integer; var pAutoinc: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_table_column_metadata' {$ENDIF};
function sqlite3_update_hook(db: psqlite3; callback: Tsqlite3_update_callback; userdata: Pointer): Pointer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_update_hook' {$ENDIF};
function sqlite3_limit(db: psqlite3; id: Integer; newVal: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_limit' {$ENDIF};
function sqlite3_collation_needed(db: psqlite3; userdata: Pointer; callback: Tsqlite3_collation_callback): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_collation_needed' {$ENDIF};
function sqlite3_create_collation(db: psqlite3; zName: PByte; eTextRep: Integer; userdata: Pointer; callback: Tsqlite3_compare_callback): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_create_collation' {$ENDIF};
function sqlite3_collation_needed16(db: psqlite3; userdata: Pointer; callback: Tsqlite3_collation_callback): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_collation_needed16' {$ENDIF};
function sqlite3_create_collation16(db: psqlite3; zName: PByte; eTextRep: Integer; userdata: Pointer; callback: Tsqlite3_compare_callback): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_create_collation16' {$ENDIF};
procedure sqlite3_progress_handler(db: psqlite3; nOpers: Integer; callback: Tsqlite3_progress_callback; userdata: Pointer); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_progress_handler' {$ENDIF};
function sqlite3_errcode(db: psqlite3): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_errcode' {$ENDIF};
function sqlite3_errmsg(db: psqlite3): PByte; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_errmsg' {$ENDIF};
function sqlite3_errmsg16(db: psqlite3): PByte; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_errmsg16' {$ENDIF};
function sqlite3_extended_result_codes(db: psqlite3; onoff: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_extended_result_codes' {$ENDIF};
function sqlite3_errstr(code: Integer): PByte; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_errstr' {$ENDIF};
function sqlite3_changes(db: psqlite3): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_changes' {$ENDIF};
function sqlite3_total_changes(db: psqlite3): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_total_changes' {$ENDIF};
procedure sqlite3_interrupt(db: psqlite3); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_interrupt' {$ENDIF};
function sqlite3_last_insert_rowid(db: psqlite3): sqlite3_int64; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_last_insert_rowid' {$ENDIF};
function sqlite3_db_filename(db: psqlite3; zDbName: PUtf8): PUtf8; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_db_filename' {$ENDIF};
function sqlite3_db_readonly(db: psqlite3; zDbName: PUtf8): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_db_readonly' {$ENDIF};
function sqlite3_db_status(db: psqlite3; op: Integer; var pCurrent: Integer; var pHighwater: Integer; resetFlag: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_db_status' {$ENDIF};
function sqlite3_exec(db: psqlite3; zSql: PByte; callback: Pointer; data: Pointer; errmsg: PPByte): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_exec' {$ENDIF};
function sqlite3_prepare(db: psqlite3; zSql: PByte; nByte: Integer; var ppStmt: psqlite3_stmt; var pzTail: PByte): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_prepare' {$ENDIF};
function sqlite3_prepare16(db: psqlite3; zSql: PByte; nByte: Integer; var ppStmt: psqlite3_stmt; var pzTail: PByte): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_prepare16' {$ENDIF};
function sqlite3_prepare_v2(db: psqlite3; zSql: PByte; nByte: Integer; var ppStmt: psqlite3_stmt; var pzTail: PByte): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_prepare_v2' {$ENDIF};
function sqlite3_prepare16_v2(db: psqlite3; zSql: PByte; nByte: Integer; var ppStmt: psqlite3_stmt; var pzTail: PByte): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_prepare16_v2' {$ENDIF};
function sqlite3_step(stmt: psqlite3_stmt): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_step' {$ENDIF};
function sqlite3_reset(stmt: psqlite3_stmt): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_reset' {$ENDIF};
function sqlite3_finalize(stmt: psqlite3_stmt): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_finalize' {$ENDIF};
function sqlite3_stmt_readonly(stmt: psqlite3_stmt): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_stmt_readonly' {$ENDIF};
function sqlite3_stmt_busy(stmt: psqlite3_stmt): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_stmt_busy' {$ENDIF};
function sqlite3_stmt_status(stmt: psqlite3_stmt; op: Integer; resetFlg: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_stmt_status' {$ENDIF};
function sqlite3_clear_bindings(stmt: psqlite3_stmt): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_clear_bindings' {$ENDIF};
function sqlite3_bind_parameter_count(stmt: psqlite3_stmt): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_bind_parameter_count' {$ENDIF};
function sqlite3_bind_parameter_index(stmt: psqlite3_stmt; zName: PUtf8): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_bind_parameter_index' {$ENDIF};
function sqlite3_bind_parameter_name(stmt: psqlite3_stmt; index: Integer): PUtf8; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_bind_parameter_name' {$ENDIF};
function sqlite3_bind_blob(stmt: psqlite3_stmt; index: Integer; value: Pointer; nBytes: Integer; destr: Tsqlite3_destroy_callback): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_bind_blob' {$ENDIF};
function sqlite3_bind_blob64(stmt: psqlite3_stmt; index: Integer; value: Pointer; nBytes: sqlite3_uint64; destr: Tsqlite3_destroy_callback): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_bind_blob64' {$ENDIF};
function sqlite3_bind_double(stmt: psqlite3_stmt; index: Integer; value: double): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_bind_double' {$ENDIF};
function sqlite3_bind_int(stmt: psqlite3_stmt; index: Integer; value: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_bind_int' {$ENDIF};
function sqlite3_bind_int64(stmt: psqlite3_stmt; index: Integer; value: sqlite3_int64): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_bind_int64' {$ENDIF};
function sqlite3_bind_null(stmt: psqlite3_stmt; index: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_bind_null' {$ENDIF};
function sqlite3_bind_text(stmt: psqlite3_stmt; index: Integer; value: PByte; nBytes: Integer; destr: Tsqlite3_destroy_callback): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_bind_text' {$ENDIF};
function sqlite3_bind_text16(stmt: psqlite3_stmt; index: Integer; value: PByte; nBytes: Integer; destr: Tsqlite3_destroy_callback): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_bind_text16' {$ENDIF};
function sqlite3_bind_text64(stmt: psqlite3_stmt; index: Integer; value: PByte; nBytes: sqlite3_uint64; destr: Tsqlite3_destroy_callback; encoding: Byte): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_bind_text64' {$ENDIF};
function sqlite3_bind_value(stmt: psqlite3_stmt; index: Integer; value: psqlite3_value): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_bind_value' {$ENDIF};
function sqlite3_bind_zeroblob(stmt: psqlite3_stmt; index: Integer; nBytes: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_bind_zeroblob' {$ENDIF};
function sqlite3_column_count(stmt: psqlite3_stmt): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_column_count' {$ENDIF};
function sqlite3_column_type(stmt: psqlite3_stmt; iCol: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_column_type' {$ENDIF};
function sqlite3_column_name(stmt: psqlite3_stmt; iCol: Integer): PByte; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_column_name' {$ENDIF};
function sqlite3_column_name16(stmt: psqlite3_stmt; iCol: Integer): PByte; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_column_name16' {$ENDIF};
function sqlite3_column_database_name(stmt: psqlite3_stmt; iCol: Integer): PByte; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_column_database_name' {$ENDIF};
function sqlite3_column_database_name16(stmt: psqlite3_stmt; iCol: Integer): PByte; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_column_database_name16' {$ENDIF};
function sqlite3_column_table_name(stmt: psqlite3_stmt; iCol: Integer): PByte; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_column_table_name' {$ENDIF};
function sqlite3_column_table_name16(stmt: psqlite3_stmt; iCol: Integer): PByte; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_column_table_name16' {$ENDIF};
function sqlite3_column_origin_name(stmt: psqlite3_stmt; iCol: Integer): PByte; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_column_origin_name' {$ENDIF};
function sqlite3_column_origin_name16(stmt: psqlite3_stmt; iCol: Integer): PByte; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_column_origin_name16' {$ENDIF};
function sqlite3_column_decltype(stmt: psqlite3_stmt; iCol: Integer): PByte; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_column_decltype' {$ENDIF};
function sqlite3_column_decltype16(stmt: psqlite3_stmt; iCol: Integer): PByte; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_column_decltype16' {$ENDIF};
function sqlite3_column_blob(stmt: psqlite3_stmt; iCol: Integer): Pointer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_column_blob' {$ENDIF};
function sqlite3_column_bytes(stmt: psqlite3_stmt; iCol: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_column_bytes' {$ENDIF};
function sqlite3_column_bytes16(stmt: psqlite3_stmt; iCol: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_column_bytes16' {$ENDIF};
function sqlite3_column_double(stmt: psqlite3_stmt; iCol: Integer): Double; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_column_double' {$ENDIF};
function sqlite3_column_int(stmt: psqlite3_stmt; iCol: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_column_int' {$ENDIF};
function sqlite3_column_int64(stmt: psqlite3_stmt; iCol: Integer): sqlite3_int64; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_column_int64' {$ENDIF};
function sqlite3_column_text(stmt: psqlite3_stmt; iCol: Integer): PByte; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_column_text' {$ENDIF};
function sqlite3_column_text16(stmt: psqlite3_stmt; iCol: Integer): PByte; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_column_text16' {$ENDIF};
function sqlite3_column_value(stmt: psqlite3_stmt; iCol: Integer): psqlite3_value; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_column_value' {$ENDIF};
function sqlite3_blob_open(db: psqlite3; zDb: PUtf8; zTable: PUtf8; zColumn: PUtf8; iRow: sqlite3_int64; flags: Integer; var ppBlob: psqlite3_blob): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_blob_open' {$ENDIF};
function sqlite3_blob_close(blob: psqlite3_blob): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_blob_close' {$ENDIF};
function sqlite3_blob_bytes(blob: psqlite3_blob): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_blob_bytes' {$ENDIF};
function sqlite3_blob_read(blob: psqlite3_blob; Z: Pointer; N: Integer; iOffset: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_blob_read' {$ENDIF};
function sqlite3_blob_write(blob: psqlite3_blob; Z: Pointer; N: Integer; iOffset: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_blob_write' {$ENDIF};
function sqlite3_create_function(db: psqlite3; zFunctionName: PByte; nArg: Integer; eTextRep: Integer; pApp: Pointer; xFunc: Tsqlite3_func_callback; xStep: Tsqlite3_step_callback; xFinal: Tsqlite3_final_callback): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_create_function' {$ENDIF};
function sqlite3_create_function16(db: psqlite3; zFunctionName: PByte; nArg: Integer; eTextRep: Integer; pApp: Pointer; xFunc: Tsqlite3_func_callback; xStep: Tsqlite3_step_callback; xFinal: Tsqlite3_final_callback): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_create_function16' {$ENDIF};
function sqlite3_user_data(context: psqlite3_context): Pointer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_user_data' {$ENDIF};
function sqlite3_aggregate_context(context: psqlite3_context; nBytes: Integer): Pointer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_aggregate_context' {$ENDIF};
function sqlite3_context_db_handle(context: psqlite3_context): psqlite3; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_context_db_handle' {$ENDIF};
function sqlite3_get_auxdata(context: psqlite3_context; N: Integer): Pointer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_get_auxdata' {$ENDIF};
procedure sqlite3_set_auxdata(context: psqlite3_context; N: Integer; data: Pointer; destr: Tsqlite3_destroy_callback); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_set_auxdata' {$ENDIF};
function sqlite3_auto_extension(xEntryPoint: Pointer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_auto_extension' {$ENDIF};
procedure sqlite3_reset_auto_extension(); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_reset_auto_extension' {$ENDIF};
function sqlite3_enable_load_extension(db: psqlite3; onoff: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_enable_load_extension' {$ENDIF};
function sqlite3_load_extension(db: psqlite3; zFile, zProc: PByte; var pzErrMsg: PByte): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_load_extension' {$ENDIF};
function sqlite3_create_module(db: psqlite3; zName: PUtf8; module: psqlite3_module; userdata: Pointer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_create_module' {$ENDIF};
function sqlite3_create_module_v2(db: psqlite3; zName: PUtf8; module: psqlite3_module; userdata: Pointer; destr: Tsqlite3_destroy_callback): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_create_module_v2' {$ENDIF};
function sqlite3_declare_vtab(db: psqlite3; zCreateTable: PUtf8): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_declare_vtab' {$ENDIF};
function sqlite3_overload_function(db: psqlite3; zFuncName: PUtf8; nArg: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_overload_function' {$ENDIF};
function sqlite3_value_blob(value: psqlite3_value): Pointer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_value_blob' {$ENDIF};
function sqlite3_value_bytes(value: psqlite3_value): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_value_bytes' {$ENDIF};
function sqlite3_value_bytes16(value: psqlite3_value): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_value_bytes16' {$ENDIF};
function sqlite3_value_double(value: psqlite3_value): Double; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_value_double' {$ENDIF};
function sqlite3_value_int(value: psqlite3_value): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_value_int' {$ENDIF};
function sqlite3_value_int64(value: psqlite3_value): sqlite3_int64; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_value_int64' {$ENDIF};
function sqlite3_value_text(value: psqlite3_value): PByte; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_value_text' {$ENDIF};
function sqlite3_value_text16(value: psqlite3_value): PByte; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_value_text16' {$ENDIF};
function sqlite3_value_type(value: psqlite3_value): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_value_type' {$ENDIF};
function sqlite3_value_numeric_type(value: psqlite3_value): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_value_numeric_type' {$ENDIF};
procedure sqlite3_result_blob(context: psqlite3_context; value: Pointer; nBytes: Integer; destr: Tsqlite3_destroy_callback); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_result_blob' {$ENDIF};
procedure sqlite3_result_blob64(context: psqlite3_context; value: Pointer; nBytes: sqlite3_uint64; destr: Tsqlite3_destroy_callback); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_result_blob64' {$ENDIF};
procedure sqlite3_result_double(context: psqlite3_context; value: Double); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_result_double' {$ENDIF};
procedure sqlite3_result_int(context: psqlite3_context; value: Integer); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_result_int' {$ENDIF};
procedure sqlite3_result_int64(context: psqlite3_context; value: sqlite3_int64); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_result_int64' {$ENDIF};
procedure sqlite3_result_null(context: psqlite3_context); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_result_null' {$ENDIF};
procedure sqlite3_result_text(context: psqlite3_context; value: PByte; nBytes: Integer; destr: Tsqlite3_destroy_callback); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_result_text' {$ENDIF};
procedure sqlite3_result_text16(context: psqlite3_context; value: PByte; nBytes: Integer; destr: Tsqlite3_destroy_callback); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_result_text16' {$ENDIF};
procedure sqlite3_result_text64(context: psqlite3_context; value: PByte; nBytes: sqlite3_uint64; destr: Tsqlite3_destroy_callback; encoding: Byte); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_result_text64' {$ENDIF};
procedure sqlite3_result_value(context: psqlite3_context; value: psqlite3_value); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_result_value' {$ENDIF};
procedure sqlite3_result_zeroblob(context: psqlite3_context; n: Integer); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_result_zeroblob' {$ENDIF};
procedure sqlite3_result_error(context: psqlite3_context; msg: PByte; nBytes: Integer); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_result_error' {$ENDIF};
procedure sqlite3_result_error16(context: psqlite3_context; msg: PByte; nBytes: Integer); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_result_error16' {$ENDIF};
procedure sqlite3_result_error_toobig(context: psqlite3_context); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_result_error_toobig' {$ENDIF};
procedure sqlite3_result_error_nomem(context: psqlite3_context); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_result_error_nomem' {$ENDIF};
procedure sqlite3_result_error_code(context: psqlite3_context; code: Integer); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_result_error_code' {$ENDIF};
function sqlite3_vfs_find(zVfsName: PFDAnsiString): psqlite3_vfs; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_vfs_find' {$ENDIF};
function sqlite3_vfs_register(pVfs: psqlite3_vfs; makeDflt: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_vfs_register' {$ENDIF};
function sqlite3_vfs_unregister(pVfs: psqlite3_vfs): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_vfs_unregister' {$ENDIF};
function sqlite3_key(db: psqlite3; zKey: PByte; nKey: Integer): Integer; cdecl;
function sqlite3_rekey(db: psqlite3; zKey: PByte; nKey: Integer): Integer; cdecl;
function sqlite3_key_v2(db: psqlite3; zDbName: PByte; zKey: PByte; nKey: Integer): Integer; cdecl;
function sqlite3_rekey_v2(db: psqlite3; zDbName: PByte; zKey: PByte; nKey: Integer): Integer; cdecl;
procedure sqlite3_activate_see(see: PFDAnsiString); cdecl;
procedure sqlite3CodecGetKey(db: psqlite3; nDb: Integer; zKey: PPointer; nKey: PInteger); cdecl;
function sqlite3CodecAttach(db: psqlite3; nDb: Integer; zKey: Pointer; nKey: Integer): Integer; cdecl;
function ad_sqlite3GetCacheSize(db: psqlite3): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'ad_sqlite3GetCacheSize' {$ENDIF};
function ad_sqlite3GetEncoding(db: psqlite3): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'ad_sqlite3GetEncoding' {$ENDIF};
function ad_sqlite3GetEncryptionMode(db: psqlite3; var name: PFDAnsiString; var len: Integer): Integer;
function ad_sqlite3GetEncryptionError(db: psqlite3; var error: PFDAnsiString; var len: Integer; var error_code: Integer): Integer;
procedure ad_sqlite3Error(db: psqlite3; err_code: Integer; zMessage: PByte); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'ad_sqlite3Error' {$ENDIF};
function sqlite3_backup_init(pDest: psqlite3; zDestName: PByte; pSource: psqlite3; zSourceName: PByte): psqlite3_backup; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_backup_init' {$ENDIF};
function sqlite3_backup_step(p: psqlite3_backup; nPage: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_backup_step' {$ENDIF};
function sqlite3_backup_finish(p: psqlite3_backup): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_backup_finish' {$ENDIF};
function sqlite3_backup_remaining(p: psqlite3_backup): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_backup_remaining' {$ENDIF};
function sqlite3_backup_pagecount(p: psqlite3_backup): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_backup_pagecount' {$ENDIF};
function sqlite3_wal_hook(db: psqlite3; callback: Tsqlite3_wal_callback; userdata: Pointer): Pointer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_wal_hook' {$ENDIF};
function sqlite3_wal_autocheckpoint(db: psqlite3; N: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_wal_autocheckpoint' {$ENDIF};
function sqlite3_wal_checkpoint(db: psqlite3; zDb: PFDAnsiString): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_wal_checkpoint' {$ENDIF};
function sqlite3_rtree_geometry_callback(db: psqlite3; zGeom: PByte; xGeom: Tsqlite3_rtree_xGeom_callback; pContext: Pointer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_rtree_geometry_callback' {$ENDIF};
function sqlite3_rtree_query_callback(db: psqlite3; zQueryFunc: PByte; xQueryFunc: Tsqlite3_rtree_xQuery_callback; pContext: Pointer; xDestructor: Tsqlite3_rtree_xDelUser_callback): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_rtree_query_callback' {$ENDIF};
function sqlite3_vtab_config(db: psqlite3; op: Integer): Integer; cdecl varargs; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_vtab_config' {$ENDIF};
function sqlite3_vtab_on_conflict(db: psqlite3): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_vtab_on_conflict' {$ENDIF};
{$ENDIF}
type
Tsqlite3_libversion = function (): PFDAnsiString; cdecl;
Tsqlite3_libversion_number = function (): Integer; cdecl;
Tsqlite3_compileoption_used = function (zOptName: PFDAnsiString): Integer; cdecl;
Tsqlite3_compileoption_get = function (N: Integer): PFDAnsiString; cdecl;
Tsqlite3_enable_shared_cache = function (onoff: Integer): Integer; cdecl;
Tsqlite3_release_memory = function (amount: Integer): Integer; cdecl;
Tsqlite3_soft_heap_limit = procedure (amount: Integer); cdecl;
Tsqlite3_status = function (op: Integer; var pCurrent: Integer;
var pHighwater: Integer; resetFlag: Integer): Integer; cdecl;
Tsqlite3_initialize = function (): Integer; cdecl;
Tsqlite3_shutdown = function (): Integer; cdecl;
Tsqlite3_malloc = function (n: Integer): Pointer; cdecl;
Tsqlite3_memory_used = function (): sqlite3_int64; cdecl;
Tsqlite3_memory_highwater = function (resetFlag: Integer): sqlite3_int64; cdecl;
Tsqlite3_free = procedure (APtr: Pointer); cdecl;
Tsqlite3_config = function (option: Integer): Integer; cdecl varargs;
Tsqlite3_open {.|16} = function (filename: PByte; var ppDb: psqlite3): Integer; cdecl;
Tsqlite3_open_v2 = function (filename: PUtf8; var ppDb: psqlite3;
flags: Integer; zVfs: PFDAnsiString): Integer; cdecl;
Tsqlite3_key = function (db: psqlite3; key: PByte; nKey: Integer): Integer; cdecl;
Tsqlite3_rekey = function (db: psqlite3; key: PByte; nKey: Integer): Integer; cdecl;
Tsqlite3_key_v2 = function (db: psqlite3; zDbName: PByte; zKey: PByte; nKey: Integer): Integer; cdecl;
Tsqlite3_rekey_v2 = function (db: psqlite3; zDbName: PByte; zKey: PByte; nKey: Integer): Integer; cdecl;
Tsqlite3_close = function (db: psqlite3): Integer; cdecl;
Tsqlite3_busy_timeout = function (db: psqlite3; ms: Integer): Integer; cdecl;
Tsqlite3_busy_handler = function (db: psqlite3;
callback: Tsqlite3_busy_callback; userdata: Pointer): Integer; cdecl;
Tsqlite3_trace = function (db: psqlite3; xTrace: Tsqlite3_trace_callback;
userdata: Pointer): Pointer; cdecl;
Tsqlite3_profile = function (db: psqlite3; xProfile: Tsqlite3_profile_callback;
userdata: Pointer): Pointer; cdecl;
Tsqlite3_set_authorizer = function (db: psqlite3; xAuth: Tsqlite3_auth_callback;
userdata: Pointer): Integer; cdecl;
Tsqlite3_get_autocommit = function (db: psqlite3): Integer; cdecl;
Tsqlite3_commit_hook = function (db: psqlite3; callback: Tsqlite3_commit_callback;
userdata: Pointer): Pointer; cdecl;
Tsqlite3_rollback_hook = function (db: psqlite3; callback: Tsqlite3_rollback_callback;
userdata: Pointer): Pointer; cdecl;
Tsqlite3_table_column_metadata = function (db: psqlite3; zDbName: PUtf8;
zTableName: PUtf8; zColumnName: PUtf8; var pzDataType: PUtf8;
var pzCollSeq: PUtf8; var pNotNull: Integer; var pPrimaryKey: Integer;
var pAutoinc: Integer): Integer; cdecl;
Tsqlite3_update_hook = function (db: psqlite3; callback: Tsqlite3_update_callback;
userdata: Pointer): Pointer; cdecl;
Tsqlite3_limit = function (db: psqlite3; id: Integer; newVal: Integer): Integer; cdecl;
Tsqlite3_collation_needed {.|16} = function (db: psqlite3; userdata: Pointer;
callback: Tsqlite3_collation_callback): Integer; cdecl;
Tsqlite3_create_collation {.|16} = function (db: psqlite3; zName: PByte;
eTextRep: Integer; userdata: Pointer; callback: Tsqlite3_compare_callback): Integer; cdecl;
Tsqlite3_progress_handler = procedure (db: psqlite3; nOpers: Integer;
callback: Tsqlite3_progress_callback; userdata: Pointer); cdecl;
Tsqlite3_errcode = function (db: psqlite3): Integer; cdecl;
Tsqlite3_errmsg {.|16} = function (db: psqlite3): PByte; cdecl;
Tsqlite3_extended_result_codes = function (db: psqlite3; onoff: Integer): Integer; cdecl;
Tsqlite3_errstr = function (code: Integer): PByte; cdecl;
Tsqlite3_changes = function (db: psqlite3): Integer; cdecl;
Tsqlite3_total_changes = function (db: psqlite3): Integer; cdecl;
Tsqlite3_interrupt = procedure (db: psqlite3); cdecl;
Tsqlite3_last_insert_rowid = function (db: psqlite3): sqlite3_int64; cdecl;
Tsqlite3_db_filename = function (db: psqlite3; zDbName: PUtf8): PUtf8; cdecl;
Tsqlite3_db_readonly = function (db: psqlite3; zDbName: PUtf8): Integer; cdecl;
Tsqlite3_db_status = function (db: psqlite3; op: Integer; var pCurrent: Integer;
var pHighwater: Integer; resetFlag: Integer): Integer; cdecl;
Tsqlite3_exec = function (db: psqlite3; zSql: PByte; callback: Pointer;
data: Pointer; errmsg: PPByte): Integer; cdecl;
Tsqlite3_prepare {.|16} {.|_v2} = function (db: psqlite3; zSql: PByte;
nByte: Integer; var ppStmt: psqlite3_stmt; var pzTail: PByte): Integer; cdecl;
Tsqlite3_step = function (stmt: psqlite3_stmt): Integer; cdecl;
Tsqlite3_reset = function (stmt: psqlite3_stmt): Integer; cdecl;
Tsqlite3_finalize = function (stmt: psqlite3_stmt): Integer; cdecl;
Tsqlite3_stmt_readonly = function (stmt: psqlite3_stmt): Integer; cdecl;
Tsqlite3_stmt_busy = function (stmt: psqlite3_stmt): Integer; cdecl;
Tsqlite3_stmt_status = function (stmt: psqlite3_stmt; op: Integer;
resetFlg: Integer): Integer; cdecl;
Tsqlite3_clear_bindings = function (stmt: psqlite3_stmt): Integer; cdecl;
Tsqlite3_bind_parameter_count = function (stmt: psqlite3_stmt): Integer; cdecl;
Tsqlite3_bind_parameter_index = function (stmt: psqlite3_stmt; zName: PUtf8): Integer; cdecl;
Tsqlite3_bind_parameter_name = function (stmt: psqlite3_stmt; index: Integer): PUtf8; cdecl;
Tsqlite3_bind_blob = function (stmt: psqlite3_stmt; index: Integer; value: Pointer;
nBytes: Integer; destr: Tsqlite3_destroy_callback): Integer; cdecl;
Tsqlite3_bind_blob64 = function (stmt: psqlite3_stmt; index: Integer; value: Pointer;
nBytes: sqlite3_uint64; destr: Tsqlite3_destroy_callback): Integer; cdecl;
Tsqlite3_bind_double = function (stmt: psqlite3_stmt; index: Integer;
value: double): Integer; cdecl;
Tsqlite3_bind_int = function (stmt: psqlite3_stmt; index: Integer;
value: Integer): Integer; cdecl;
Tsqlite3_bind_int64 = function (stmt: psqlite3_stmt; index: Integer;
value: sqlite3_int64): Integer; cdecl;
Tsqlite3_bind_null = function (stmt: psqlite3_stmt; index: Integer): Integer; cdecl;
Tsqlite3_bind_text {.|16} = function (stmt: psqlite3_stmt; index: Integer;
value: PByte; nBytes: Integer; destr: Tsqlite3_destroy_callback): Integer; cdecl;
Tsqlite3_bind_text64 = function (stmt: psqlite3_stmt; index: Integer;
value: PByte; nBytes: sqlite3_uint64; destr: Tsqlite3_destroy_callback; encoding: Byte): Integer; cdecl;
Tsqlite3_bind_value = function (stmt: psqlite3_stmt; index: Integer;
value: psqlite3_value): Integer; cdecl;
Tsqlite3_bind_zeroblob = function (stmt: psqlite3_stmt; index: Integer;
nBytes: Integer): Integer; cdecl;
Tsqlite3_column_count = function (stmt: psqlite3_stmt): Integer; cdecl;
Tsqlite3_column_type = function (stmt: psqlite3_stmt; iCol: Integer): Integer; cdecl;
Tsqlite3_column_name {.|16} = function (stmt: psqlite3_stmt; iCol: Integer): PByte; cdecl;
Tsqlite3_column_database_name {.|16} = function (stmt: psqlite3_stmt; iCol: Integer): PByte; cdecl;
Tsqlite3_column_table_name {.|16} = function (stmt: psqlite3_stmt; iCol: Integer): PByte; cdecl;
Tsqlite3_column_origin_name {.|16} = function (stmt: psqlite3_stmt; iCol: Integer): PByte; cdecl;
Tsqlite3_column_decltype {.|16} = function (stmt: psqlite3_stmt; iCol: Integer): PByte; cdecl;
Tsqlite3_column_blob = function (stmt: psqlite3_stmt; iCol: Integer): Pointer; cdecl;
Tsqlite3_column_bytes {.|16} = function (stmt: psqlite3_stmt; iCol: Integer): Integer; cdecl;
Tsqlite3_column_double = function (stmt: psqlite3_stmt; iCol: Integer): Double; cdecl;
Tsqlite3_column_int = function (stmt: psqlite3_stmt; iCol: Integer): Integer; cdecl;
Tsqlite3_column_int64 = function (stmt: psqlite3_stmt; iCol: Integer): sqlite3_int64; cdecl;
Tsqlite3_column_text {.|16} = function (stmt: psqlite3_stmt; iCol: Integer): PByte; cdecl;
Tsqlite3_column_value = function (stmt: psqlite3_stmt; iCol: Integer): psqlite3_value; cdecl;
Tsqlite3_blob_open = function (db: psqlite3; zDb: PUtf8; zTable: PUtf8;
zColumn: PUtf8; iRow: sqlite3_int64; flags: Integer;
var ppBlob: psqlite3_blob): Integer; cdecl;
Tsqlite3_blob_close = function (blob: psqlite3_blob): Integer; cdecl;
Tsqlite3_blob_bytes = function (blob: psqlite3_blob): Integer; cdecl;
Tsqlite3_blob_read = function (blob: psqlite3_blob; Z: Pointer; N: Integer;
iOffset: Integer): Integer; cdecl;
Tsqlite3_blob_write = function (blob: psqlite3_blob; Z: Pointer; N: Integer;
iOffset: Integer): Integer; cdecl;
Tsqlite3_create_function {.|16} = function (db: psqlite3; zFunctionName: PByte;
nArg: Integer; eTextRep: Integer; pApp: Pointer; xFunc: Tsqlite3_func_callback;
xStep: Tsqlite3_step_callback; xFinal: Tsqlite3_final_callback): Integer; cdecl;
Tsqlite3_user_data = function (context: psqlite3_context): Pointer; cdecl;
Tsqlite3_aggregate_context = function (context: psqlite3_context;
nBytes: Integer): Pointer; cdecl;
Tsqlite3_context_db_handle = function (context: psqlite3_context): psqlite3; cdecl;
Tsqlite3_get_auxdata = function (context: psqlite3_context; N: Integer): Pointer; cdecl;
Tsqlite3_set_auxdata = procedure (context: psqlite3_context; N: Integer; data: Pointer;
destr: Tsqlite3_destroy_callback); cdecl;
Tsqlite3_auto_extension = function (xEntryPoint: Pointer): Integer; cdecl;
Tsqlite3_reset_auto_extension = procedure (); cdecl;
Tsqlite3_enable_load_extension = function (db: psqlite3; onoff: Integer): Integer; cdecl;
Tsqlite3_load_extension = function (db: psqlite3; zFile, zProc: PByte;
var pzErrMsg: PByte): Integer; cdecl;
Tsqlite3_create_module = function (db: psqlite3; zName: PUtf8; module: psqlite3_module;
userdata: Pointer): Integer; cdecl;
Tsqlite3_create_module_v2 = function (db: psqlite3; zName: PUtf8; module: psqlite3_module;
userdata: Pointer; destr: Tsqlite3_destroy_callback): Integer; cdecl;
Tsqlite3_declare_vtab = function (db: psqlite3; zCreateTable: PUtf8): Integer; cdecl;
Tsqlite3_overload_function = function (db: psqlite3; zFuncName: PUtf8;
nArg: Integer): Integer; cdecl;
Tsqlite3_value_blob = function (value: psqlite3_value): Pointer; cdecl;
Tsqlite3_value_bytes {.|16} = function (value: psqlite3_value): Integer; cdecl;
Tsqlite3_value_double = function (value: psqlite3_value): Double; cdecl;
Tsqlite3_value_int = function (value: psqlite3_value): Integer; cdecl;
Tsqlite3_value_int64 = function (value: psqlite3_value): sqlite3_int64; cdecl;
Tsqlite3_value_text {.|16} = function (value: psqlite3_value): PByte; cdecl;
Tsqlite3_value_type = function (value: psqlite3_value): Integer; cdecl;
Tsqlite3_value_numeric_type = function (value: psqlite3_value): Integer; cdecl;
Tsqlite3_result_blob = procedure (context: psqlite3_context; value: Pointer;
nBytes: Integer; destr: Tsqlite3_destroy_callback); cdecl;
Tsqlite3_result_blob64 = procedure (context: psqlite3_context; value: Pointer;
nBytes: sqlite3_uint64; destr: Tsqlite3_destroy_callback); cdecl;
Tsqlite3_result_double = procedure (context: psqlite3_context; value: Double); cdecl;
Tsqlite3_result_int = procedure (context: psqlite3_context; value: Integer); cdecl;
Tsqlite3_result_int64 = procedure (context: psqlite3_context; value: sqlite3_int64); cdecl;
Tsqlite3_result_null = procedure (context: psqlite3_context); cdecl;
Tsqlite3_result_text {.|16} = procedure (context: psqlite3_context; value: PByte;
nBytes: Integer; destr: Tsqlite3_destroy_callback); cdecl;
Tsqlite3_result_text64 = procedure (context: psqlite3_context; value: PByte;
nBytes: sqlite3_uint64; destr: Tsqlite3_destroy_callback; encoding: Byte); cdecl;
Tsqlite3_result_value = procedure (context: psqlite3_context; value: psqlite3_value); cdecl;
Tsqlite3_result_zeroblob = procedure (context: psqlite3_context; n: Integer); cdecl;
Tsqlite3_result_error {.|16} = procedure (context: psqlite3_context; msg: PByte;
nBytes: Integer); cdecl;
Tsqlite3_result_error_toobig = procedure (context: psqlite3_context); cdecl;
Tsqlite3_result_error_nomem = procedure (context: psqlite3_context); cdecl;
Tsqlite3_result_error_code = procedure (context: psqlite3_context; code: Integer); cdecl;
Tsqlite3_vfs_find = function(zVfsName: PFDAnsiString): psqlite3_vfs; cdecl;
Tsqlite3_vfs_register = function(pVfs: psqlite3_vfs; makeDflt: Integer): Integer; cdecl;
Tsqlite3_vfs_unregister = function(pVfs: psqlite3_vfs): Integer; cdecl;
Tsqlite3_backup_init = function (pDest: psqlite3; zDestName: PByte; pSource: psqlite3;
zSourceName: PByte): psqlite3_backup; cdecl;
Tsqlite3_backup_step = function (p: psqlite3_backup; nPage: Integer): Integer; cdecl;
Tsqlite3_backup_finish = function (p: psqlite3_backup): Integer; cdecl;
Tsqlite3_backup_remaining = function (p: psqlite3_backup): Integer; cdecl;
Tsqlite3_backup_pagecount = function (p: psqlite3_backup): Integer; cdecl;
Tsqlite3_wal_hook = function (db: psqlite3; callback: Tsqlite3_wal_callback; userdata: Pointer): Pointer; cdecl;
Tsqlite3_wal_autocheckpoint = function (db: psqlite3; N: Integer): Integer; cdecl;
Tsqlite3_wal_checkpoint = function (db: psqlite3; zDb: PFDAnsiString): Integer; cdecl;
Tsqlite3_rtree_geometry_callback = function (db: psqlite3; zGeom: PByte;
xGeom: Tsqlite3_rtree_xGeom_callback; pContext: Pointer): Integer; cdecl;
Tsqlite3_rtree_query_callback = function (db: psqlite3; zQueryFunc: PByte;
xQueryFunc: Tsqlite3_rtree_xQuery_callback; pContext: Pointer;
xDestructor: Tsqlite3_rtree_xDelUser_callback): Integer; cdecl;
Tsqlite3_vtab_config = function(db: psqlite3; op: Integer): Integer; cdecl varargs;
Tsqlite3_vtab_on_conflict = function(db: psqlite3): Integer; cdecl;
Tsqlite3_activate_see = procedure(see: PFDAnsiString); cdecl;
Tsqlite3CodecGetKey = procedure(db: psqlite3; nDb: Integer; zKey: PPointer; nKey: PInteger); cdecl;
Tsqlite3CodecAttach = function(db: psqlite3; nDb: Integer; zKey: Pointer; nKey: Integer): Integer; cdecl;
implementation
{$IFDEF FireDAC_SQLITE_STATIC}
uses
System.SysUtils, System.Classes, System.SyncObjs,
{$IFDEF MSWINDOWS}
System.Win.Crtl,
{$ENDIF}
FireDAC.Stan.Util, FireDAC.Stan.Cipher;
// FireDAC SQLite driver encryption feature is derived from the following work:
(*
** SQLCipher
** crypto.c developed by Stephen Lombardo (Zetetic LLC)
** sjlombardo at zetetic dot net
** http://zetetic.net
**
** Copyright (c) 2009, ZETETIC LLC
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** * Neither the name of the ZETETIC LLC nor the
** names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY
** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY
** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
*)
type
// Internal structures
_pPgHdr = Pointer;
_pPager = Pointer;
_pBtree = Pointer;
_pDb = ^_Db;
_Pgno = Cardinal;
_Db = record
zName: PFDAnsiString;
pBt: _pBtree;
// .................
end;
{-----------------------------------------------------------------------------}
// Codec private structures
PSQLiteCipherCtx = ^TSQLiteCipherCtx;
TSQLiteCipherCtx = record
derive_key: Boolean;
evp_cipher_class: TFDCipherClass;
evp_cipher: TFDCipher;
key_sz: Integer;
pass_sz: Integer;
iv_sz: Integer;
name_sz: Integer;
pass: PFDAnsiString;
end;
PSQLiteCodecCtx = ^TSQLiteCodecCtx;
TSQLiteCodecCtx = record
page_size: Integer;
kdf_salt_sz: Integer;
buffer_sz: Integer;
kdf_salt: PByte;
buffer: PByte;
read_ctx: PSQLiteCipherCtx;
write_ctx: PSQLiteCipherCtx;
mode_rekey: Boolean;
error: PFDAnsiString;
error_sz: Integer;
error_code: Integer;
end;
TSQLiteCodecProc = function (iCtx: Pointer; data: Pointer; pgn: _Pgno; mode: Integer): Pointer; cdecl;
TSQLiteCodecSizeChngProc = procedure (iCtx: Pointer; pageSize: Integer; nReserve: Integer); cdecl;
TSQLiteCodecFreeProc = procedure (iCtx: Pointer); cdecl;
const
// Adjust SQLite file header size to make the payload size equal to factor
// of C_FD_AESBlockSize. SQLite is using only <= 70 bytes in the header.
C_SQLiteFileHeaderSize = 100 - 100 mod C_FD_AESBlockSize;
C_SQLiteWellKnownSize = 16;
C_SQLiteMaxKeyLength = 32;
C_SQLiteDefaultKeyLength = 32;
C_SQLiteDefaultCipherClass: TFDCipherClass = TFDCipherAES;
C_SQLiteReservedSpace = 32;
var
GCodecAttachLock: TCriticalSection;
// sqlite3.obj must export these entries
procedure sqlite3_randomness(N: Integer; P: Pointer); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'sqlite3_randomness' {$ENDIF};
procedure ad_sqlite3PagerSetCodec(pPager: _pPager; xCodec: TSQLiteCodecProc; xCodecSizeChng: TSQLiteCodecSizeChngProc; xCodecFree: TSQLiteCodecFreeProc; pCodec: Pointer); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'ad_sqlite3PagerSetCodec' {$ENDIF};
function ad_sqlite3BtreeGetPageSize(p: _pBtree): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'ad_sqlite3BtreeGetPageSize' {$ENDIF};
function ad_sqlite3BtreeSetPageSize(p: _pBtree; pageSize: Integer; nReserve: Integer; iFix: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'ad_sqlite3BtreeSetPageSize' {$ENDIF};
function ad_sqlite3BtreeGetPager(p: _pBtree): _pPager; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'ad_sqlite3BtreeGetPager' {$ENDIF};
function ad_sqlite3BtreeBeginTrans(p: _pBtree; wrflag: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'ad_sqlite3BtreeBeginTrans' {$ENDIF};
function ad_sqlite3BtreeCommit(p: _pBtree): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'ad_sqlite3BtreeCommit' {$ENDIF};
function ad_sqlite3BtreeRollback(p: _pBtree): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'ad_sqlite3BtreeRollback' {$ENDIF};
function ad_sqlite3PagerGetFd(pPager: _pPager): psqlite3_file; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'ad_sqlite3PagerGetFd' {$ENDIF};
function ad_sqlite3PagerGetCodec(pPager: _pPager): Pointer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'ad_sqlite3PagerGetCodec' {$ENDIF};
procedure ad_sqlite3PagerPagecount(pPager: _pPager; var pnPage: Integer); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'ad_sqlite3PagerPagecount' {$ENDIF};
function ad_sqlite3PagerIsMjPgno(pPager: _pPager; pgn: _Pgno): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'ad_sqlite3PagerIsMjPgno' {$ENDIF};
function ad_sqlite3PagerGet(pPager: _pPager; pgn: _Pgno; var ppPage: _pPgHdr): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'ad_sqlite3PagerGet' {$ENDIF};
function ad_sqlite3PagerWrite(pPage: _pPgHdr): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'ad_sqlite3PagerWrite' {$ENDIF};
procedure ad_sqlite3PagerUnref(pPage: _pPgHdr); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'ad_sqlite3PagerUnref' {$ENDIF};
function ad_sqlite3GetBackend(db: psqlite3; nDb: Integer): _pDb; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'ad_sqlite3GetBackend' {$ENDIF};
procedure ad_sqlite3SetNextPagesize(db: psqlite3; size: Integer); cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'ad_sqlite3SetNextPagesize' {$ENDIF};
function ad_sqlite3GetFileHeader(): PFDAnsiString; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'ad_sqlite3GetFileHeader' {$ENDIF};
function ad_sqlite3RunVacuum(db: psqlite3; pDb: _pDb; nReserved: Integer): Integer; cdecl; external {$IFDEF FireDAC_SQLITE_EXTERNAL} C_FD_SQLiteLib name _SLU + 'ad_sqlite3RunVacuum' {$ENDIF};
{$IFDEF FireDAC_SQLITE_EXTERNAL}
// sqlite3_fd_glue.obj must export this entry
procedure ad_sqlite3SetEncryptionCallbacks(cb_activate_see: Tsqlite3_activate_see; cb_key_v2: Tsqlite3_key_v2; cb_rekey_v2: Tsqlite3_rekey_v2; cb_CodecGetKey: Tsqlite3CodecGetKey; cb_CodecAttach: Tsqlite3CodecAttach); cdecl; external C_FD_SQLiteLib name _SLU + 'ad_sqlite3SetEncryptionCallbacks';
{$ENDIF}
{-------------------------------------------------------------------------------}
procedure SetCodecError(ctx: PSQLiteCodecCtx; const AMsg: String; AErrorCode: Integer);
var
sMsg: TFDByteString;
begin
if ctx^.error <> nil then begin
FreeMem(ctx^.error, ctx^.error_sz);
ctx^.error := nil;
ctx^.error_sz := 0;
ctx^.error_code := 0;
end;
if AMsg <> '' then begin
sMsg := TFDEncoder.Enco('Cipher: ' + AMsg, ecANSI);
ctx^.error_sz := TFDEncoder.EncoLength(sMsg, ecANSI);
GetMem(ctx^.error, ctx^.error_sz);
Move(PByte(sMsg)^, ctx^.error^, ctx^.error_sz);
ctx^.error_code := AErrorCode;
end;
end;
{-------------------------------------------------------------------------------}
function sqlite3Codec(iCtx: Pointer; data: Pointer; pgn: _Pgno; mode: Integer): Pointer; cdecl;
var
pCtx: PSQLiteCodecCtx;
iPageSize: Integer;
iOffset: Integer;
pData: PByte;
function KeyDerive(ctx: PSQLiteCodecCtx; c_ctx: PSQLiteCipherCtx): Integer;
begin
// if pass is not null
if (c_ctx^.pass <> nil) and (c_ctx^.pass_sz <> 0) then begin
if c_ctx^.evp_cipher = nil then
c_ctx^.evp_cipher := c_ctx^.evp_cipher_class.Create;
c_ctx^.evp_cipher.Initialize(PByte(c_ctx^.pass), c_ctx^.pass_sz,
PAESBlock(ctx^.kdf_salt)^, ctx^.kdf_salt_sz, c_ctx^.key_sz * 8);
Result := SQLITE_OK;
end
else begin
SetCodecError(ctx, 'Password must be not empty', er_FD_SQLitePwdInvalid);
Result := SQLITE_ERROR;
end;
end;
function Cipher(ctx: PSQLiteCodecCtx; c_ctx: PSQLiteCipherCtx; AEncrypt: Boolean;
ASize: Integer; ASrc, ADest: Pointer; APageNum: Cardinal): Integer;
begin
Result := SQLITE_OK;
if c_ctx^.key_sz = 0 then
Move(ASrc^, ADest^, ASize)
else if not Assigned(c_ctx^.evp_cipher) then begin
SetCodecError(ctx, 'Algorythm is not assigned', er_FD_SQLiteAlgFailure);
Result := SQLITE_ERROR;
end
else if (ASize mod C_FD_AESBlockSize) <> 0 then begin
SetCodecError(ctx, 'Invalid block size', er_FD_SQLiteAlgFailure);
Result := SQLITE_ERROR;
end
else
case c_ctx^.evp_cipher.Process(PAESBlock(ASrc), PAESBlock(ADest),
ASize div C_FD_AESBlockSize, APageNum, AEncrypt) of
1:
begin
if (pgn = 1) and (mode in [0, 2, 3]) and
CompareMem(ad_sqlite3GetFileHeader(), data, C_SQLiteWellKnownSize) then
SetCodecError(ctx, 'DB is not encrypted', er_FD_SQLiteDBUnencrypted)
else
SetCodecError(ctx, 'Invalid password is specified or DB is corrupted', er_FD_SQLitePwdInvalid);
Result := SQLITE_ERROR;
end;
2:
begin
SetCodecError(ctx, 'Failed to initialize algorythm', er_FD_SQLiteAlgFailure);
Result := SQLITE_ERROR;
end;
3:
if (pgn = 1) and (mode in [0, 2, 3]) and
CompareMem(ad_sqlite3GetFileHeader(), data, C_SQLiteWellKnownSize) then begin
SetCodecError(ctx, 'DB is not encrypted', er_FD_SQLiteDBUnencrypted);
Result := SQLITE_ERROR;
end;
end;
end;
begin
pCtx := PSQLiteCodecCtx(iCtx);
try
iPageSize := pCtx^.page_size;
pData := PByte(data);
// derive key on first use if necessary
if pCtx^.read_ctx^.derive_key then begin
KeyDerive(pCtx, pCtx^.read_ctx);
pCtx^.read_ctx^.derive_key := False;
end;
if pCtx^.write_ctx^.derive_key then begin
KeyDerive(pCtx, pCtx^.write_ctx);
pCtx^.write_ctx^.derive_key := False;
end;
// adjust buffer size is a page size is changed
if iPageSize > pCtx^.buffer_sz then begin
pCtx^.buffer_sz := iPageSize;
ReallocMem(pCtx^.buffer, iPageSize);
end;
// adjust starting pointers in data page for header iOffset on first page
if pgn = 1 then
iOffset := C_SQLiteFileHeaderSize
else
iOffset := 0;
case mode of
// decrypt
0, 2, 3:
begin
if Cipher(pCtx, pCtx^.read_ctx, False, iPageSize - iOffset,
PFDAnsiString(pData) + iOffset, PFDAnsiString(pCtx^.buffer) + iOffset, pgn) = SQLITE_OK then begin
// copy file header to the first 16 bytes of the page
if pgn = 1 then begin
Move(ad_sqlite3GetFileHeader()^, pCtx^.buffer^, C_SQLiteWellKnownSize);
Move((PFDAnsiString(pData) + C_SQLiteWellKnownSize)^,
(PFDAnsiString(pCtx^.buffer) + C_SQLiteWellKnownSize)^,
C_SQLiteFileHeaderSize - C_SQLiteWellKnownSize);
end;
// copy buffer data back to pData and return
Move(pCtx^.buffer^, pData^, iPageSize);
Result := pData;
end
else
Result := nil;
end;
// encrypt
6, 7:
begin
if Cipher(pCtx, pCtx^.write_ctx, True, iPageSize - iOffset,
PFDAnsiString(pData) + iOffset, PFDAnsiString(pCtx^.buffer) + iOffset, pgn) = SQLITE_OK then begin
// copy salt to output buffer
if pgn = 1 then begin
if pCtx^.write_ctx^.key_sz = 0 then
Move(pData^, pCtx^.buffer^, iOffset)
else begin
Move(pCtx^.kdf_salt^, pCtx^.buffer^, C_SQLiteWellKnownSize);
Move((PFDAnsiString(pData) + C_SQLiteWellKnownSize)^,
(PFDAnsiString(pCtx^.buffer) + C_SQLiteWellKnownSize)^,
C_SQLiteFileHeaderSize - C_SQLiteWellKnownSize);
end;
end;
// return persistent buffer data, pData remains intact
Result := pCtx^.buffer;
end
else
Result := nil;
end;
else
Result := pData;
end;
if Result <> nil then
SetCodecError(pCtx, '', 0);
except
on E: Exception do begin
SetCodecError(pCtx, E.Message, er_FD_SQLiteAlgFailure);
Result := nil;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure sqlite3CodecFree(iCtx: Pointer); cdecl;
procedure FreeCiperCtx(var ApCtx: PSQLiteCipherCtx);
begin
if ApCtx = nil then
Exit;
if ApCtx^.pass <> nil then
FreeMem(ApCtx^.pass);
FDFreeAndNil(ApCtx^.evp_cipher);
FreeMem(ApCtx);
ApCtx := nil;
end;
var
pCtx: PSQLiteCodecCtx;
begin
pCtx := PSQLiteCodecCtx(iCtx);
if pCtx = nil then
Exit;
FreeMem(pCtx^.kdf_salt, 0);
FreeMem(pCtx^.buffer, 0);
FreeCiperCtx(pCtx^.read_ctx);
FreeCiperCtx(pCtx^.write_ctx);
SetCodecError(pCtx, '', 0);
FreeMem(pCtx);
end;
{-------------------------------------------------------------------------------}
procedure sqlite3CodecSizeChng(iCtx: Pointer; pageSize, nReserve: Integer); cdecl;
var
pCtx: PSQLiteCodecCtx;
begin
pCtx := PSQLiteCodecCtx(iCtx);
if pCtx = nil then
Exit;
pCtx^.page_size := pageSize;
end;
{-------------------------------------------------------------------------------}
procedure SetPasswordCtx(ApCtx: PSQLiteCipherCtx; zKey: Pointer; nKey: Integer);
begin
ApCtx^.pass_sz := nKey;
ApCtx^.key_sz := 0;
ApCtx^.iv_sz := 0;
if ApCtx^.pass <> nil then begin
FreeMem(ApCtx^.pass, ApCtx^.pass_sz);
ApCtx^.pass := nil;
end;
if nKey <> 0 then begin
GetMem(ApCtx^.pass, nKey);
Move(zKey^, ApCtx^.pass^, nKey);
if not FDCipherParsePassword(zKey, nKey, ApCtx^.evp_cipher_class,
ApCtx^.key_sz, ApCtx^.name_sz) then begin
ApCtx^.evp_cipher_class := C_SQLiteDefaultCipherClass;
ApCtx^.key_sz := C_SQLiteDefaultKeyLength;
end;
ApCtx^.iv_sz := ApCtx^.evp_cipher_class.ReserveLength;
end;
ApCtx^.derive_key := True;
end;
{-------------------------------------------------------------------------------}
function ComparePasswordCtx(ApCtx: PSQLiteCipherCtx; zKey: Pointer; nKey: Integer): Integer;
begin
Result := FDCompareByteStr(PByte(ApCtx^.pass), PByte(zKey),
ApCtx^.pass_sz, nKey);
end;
{-------------------------------------------------------------------------------}
function sqlite3CodecAttach(db: psqlite3; nDb: Integer; zKey: Pointer;
nKey: Integer): Integer; cdecl;
procedure NewCipherCtx(var ApCtx: PSQLiteCipherCtx);
begin
GetMem(ApCtx, SizeOf(TSQLiteCipherCtx));
FillChar(ApCtx^, SizeOf(TSQLiteCipherCtx), 0);
end;
var
pDb: _pDb;
pCtx: PSQLiteCodecCtx;
pPager: _pPager;
fd: psqlite3_file;
iPageSize: Integer;
begin
GCodecAttachLock.Acquire;
try
try
pDb := ad_sqlite3GetBackend(db, nDb);
if pDb^.pBt <> nil then begin
pPager := ad_sqlite3BtreeGetPager(pDb^.pBt);
iPageSize := ad_sqlite3BtreeGetPageSize(pDb^.pBt);
pCtx := ad_sqlite3PagerGetCodec(pPager);
if pCtx <> nil then
pCtx^.page_size := iPageSize;
if (pCtx <> nil) and (pCtx^.read_ctx <> nil) and (pCtx.read_ctx^.key_sz <> 0) then begin
if ComparePasswordCtx(pCtx.read_ctx, zKey, nKey) <> 0 then begin
SetCodecError(pCtx, 'Invalid password is specified', er_FD_SQLitePwdInvalid);
Result := SQLITE_ERROR;
end
else
Result := SQLITE_OK;
Exit;
end;
if (nKey = 0) or (zKey = nil) then begin
Result := SQLITE_OK;
Exit;
end;
GetMem(pCtx, SizeOf(TSQLiteCodecCtx));
FillChar(pCtx^, SizeOf(TSQLiteCodecCtx), 0);
pCtx^.page_size := iPageSize;
NewCipherCtx(pCtx^.read_ctx);
NewCipherCtx(pCtx^.write_ctx);
// pre-allocate a page buffer of PageSize bytes. This will
// be used as a persistent buffer for encryption and decryption
// operations to avoid overhead of multiple memory allocations
pCtx^.buffer_sz := iPageSize;
GetMem(pCtx^.buffer, iPageSize);
// allocate space for salt data. Then read the first 16 bytes
// directly off the database file. This is the salt for the
// key derivation function. If we get a short read allocate
// a new random salt value
pCtx^.kdf_salt_sz := C_SQLiteWellKnownSize;
GetMem(pCtx^.kdf_salt, pCtx^.kdf_salt_sz);
// if unable to read the bytes, generate random salt
fd := ad_sqlite3PagerGetFd(pPager);
if (fd = nil) or
(fd^.pMethods^.xRead(fd, pCtx^.kdf_salt, C_SQLiteWellKnownSize, 0) <> SQLITE_OK) then
sqlite3_randomness(C_SQLiteWellKnownSize, PFDAnsiString(pCtx^.kdf_salt));
ad_sqlite3PagerSetCodec(pPager, sqlite3Codec, sqlite3CodecSizeChng, sqlite3CodecFree, pCtx);
SetPasswordCtx(pCtx^.read_ctx, zKey, nKey);
SetPasswordCtx(pCtx^.write_ctx, zKey, nKey);
// Do not check result - it will be SQLITE_READONLY for not empty DB
ad_sqlite3BtreeSetPageSize(pDb^.pBt, iPageSize, pCtx^.read_ctx^.iv_sz, 0);
end;
Result := SQLITE_OK;
except
on E: Exception do begin
ad_sqlite3Error(db, SQLITE_ERROR,
PByte(TFDEncoder.Enco('Cipher: ' + E.Message, ecANSI)));
Result := SQLITE_ERROR;
end;
end;
finally
GCodecAttachLock.Release;
end;
end;
{-------------------------------------------------------------------------------}
function sqlite3_key(db: psqlite3; zKey: PByte; nKey: Integer): Integer; cdecl;
begin
// attach key if db and zKey are not null and nKey is > 0
if (db <> nil) and (zKey <> nil) and (nKey > 0) then begin
// operate only on the main db
sqlite3CodecAttach(db, 0, zKey, nKey);
Result := SQLITE_OK;
end
else begin
if db <> nil then
ad_sqlite3Error(db, SQLITE_ERROR,
PByte(TFDEncoder.Enco('Cipher: Password must be not empty', ecANSI)));
Result := SQLITE_ERROR;
end;
end;
{-------------------------------------------------------------------------------}
function sqlite3_key_v2(db: psqlite3; zDbName: PByte; zKey: PByte; nKey: Integer): Integer; cdecl;
begin
ad_sqlite3Error(db, SQLITE_ERROR,
PByte(TFDEncoder.Enco('Cipher: sqlite3_key_v2 is not supported', ecANSI)));
Result := SQLITE_ERROR;
end;
{-------------------------------------------------------------------------------}
function sqlite3_rekey(db: psqlite3; zKey: PByte; nKey: Integer): Integer; cdecl;
var
pDb: _pDb;
pCtx: PSQLiteCodecCtx;
rc: Integer;
page_count, pgn: _Pgno;
pPage: _pPgHdr;
pPager: _pPager;
begin
try
if db <> nil then begin
pDb := ad_sqlite3GetBackend(db, 0);
rc := SQLITE_OK;
if pDb^.pBt <> nil then begin
pPager := ad_sqlite3BtreeGetPager(pDb^.pBt);
pCtx := ad_sqlite3PagerGetCodec(pPager);
// no codec and no encryption requested
if (pCtx = nil) and ((nKey = 0) or (zKey = nil)) then begin
Result := SQLITE_OK;
Exit;
end;
if pCtx = nil then begin
// there was no codec attached to this database, so attach one now with a null password
sqlite3CodecAttach(db, 0, zKey, nKey);
pCtx := ad_sqlite3PagerGetCodec(pPager);
// prepare this setup as if it had already been initialized
sqlite3_randomness(pCtx^.kdf_salt_sz, pCtx^.kdf_salt);
pCtx^.read_ctx^.key_sz := 0;
pCtx^.read_ctx^.pass_sz := 0;
pCtx^.read_ctx^.iv_sz := 0;
end;
SetPasswordCtx(pCtx^.write_ctx, zKey, nKey);
pCtx^.mode_rekey := True;
if pCtx^.read_ctx^.iv_sz <> pCtx^.write_ctx^.iv_sz then begin
rc := ad_sqlite3RunVacuum(db, pDb, pCtx^.write_ctx^.iv_sz);
if rc <> SQLITE_OK then begin
ad_sqlite3Error(db, SQLITE_ERROR,
PByte(TFDEncoder.Enco('Cipher: failed to reserve an envelope space', ecANSI)));
Result := rc;
Exit;
end;
end;
// do stuff here to rewrite the database
// 1. Create a transaction on the database
// 2. Iterate through each page, reading it and then writing it.
// 3. If that goes ok then commit and put zKey into read_ctx
// begin write transaction
rc := ad_sqlite3BtreeBeginTrans(pDb^.pBt, 1);
if rc = SQLITE_OK then begin
ad_sqlite3PagerPagecount(pPager, Integer(page_count));
// pgno's start at 1 see pager.c:pagerAcquire
pgn := 1;
while (rc = SQLITE_OK) and (pgn <= page_count) do begin
// skip this page (see pager.c:pagerAcquire for reasoning)
if ad_sqlite3PagerIsMjPgno(pPager, pgn) = 0 then begin
rc := ad_sqlite3PagerGet(pPager, pgn, pPage);
// write page see pager_incr_changecounter for example
if rc = SQLITE_OK then begin
rc := ad_sqlite3PagerWrite(pPage);
if rc = SQLITE_OK then
ad_sqlite3PagerUnref(pPage);
end;
end;
Inc(pgn);
end;
// if commit was successful commit and copy the rekey data to
// current key, else rollback to release locks
if rc = SQLITE_OK then begin
ad_sqlite3SetNextPagesize(db, ad_sqlite3BtreeGetPageSize(pDb^.pBt));
rc := ad_sqlite3BtreeCommit(pDb^.pBt);
if rc = SQLITE_OK then
SetPasswordCtx(pCtx^.read_ctx, zKey, nKey);
end
else
rc := ad_sqlite3BtreeRollback(pDb^.pBt);
end;
if rc <> SQLITE_OK then
ad_sqlite3Error(db, SQLITE_ERROR,
PByte(TFDEncoder.Enco('Cipher: failed to change the DB password', ecANSI)));
pCtx^.mode_rekey := False;
end;
Result := rc;
end
else
Result := SQLITE_ERROR;
except
on E: Exception do begin
ad_sqlite3Error(db, SQLITE_ERROR,
PByte(TFDEncoder.Enco('Cipher: ' + E.Message, ecANSI)));
Result := SQLITE_ERROR;
end;
end;
end;
{-------------------------------------------------------------------------------}
function sqlite3_rekey_v2(db: psqlite3; zDbName: PByte; zKey: PByte; nKey: Integer): Integer; cdecl;
begin
ad_sqlite3Error(db, SQLITE_ERROR,
PByte(TFDEncoder.Enco('Cipher: sqlite3_rekey_v2 is not supported', ecANSI)));
Result := SQLITE_ERROR;
end;
{-------------------------------------------------------------------------------}
procedure sqlite3_activate_see(see: PFDAnsiString); cdecl;
begin
// do nothing, security enhancements are always active
end;
{-------------------------------------------------------------------------------}
procedure sqlite3CodecGetKey(db: psqlite3; nDb: Integer; zKey: PPointer;
nKey: PInteger); cdecl;
var
pDb: _pDb;
pPager: _pPager;
pCtx: PSQLiteCodecCtx;
begin
pDb := ad_sqlite3GetBackend(db, nDb);
if pDb^.pBt <> nil then begin
pPager := ad_sqlite3BtreeGetPager(pDb^.pBt);
pCtx := ad_sqlite3PagerGetCodec(pPager);
// if the codec has an attached codec_context user the raw key data
if pCtx <> nil then begin
zKey^ := pCtx^.read_ctx^.pass;
nKey^ := pCtx^.read_ctx^.pass_sz;
end
else begin
zKey^ := nil;
nKey^ := 0;
end;
end;
end;
{-------------------------------------------------------------------------------}
function ad_sqlite3GetEncryptionMode(db: psqlite3; var name: PFDAnsiString;
var len: Integer): Integer;
var
pDb: _pDb;
pCtx: PSQLiteCodecCtx;
pPager: _pPager;
begin
name := nil;
len := 0;
Result := SQLITE_ERROR;
pDb := ad_sqlite3GetBackend(db, 0);
if pDb^.pBt <> nil then begin
pPager := ad_sqlite3BtreeGetPager(pDb^.pBt);
pCtx := ad_sqlite3PagerGetCodec(pPager);
if (pCtx <> nil) and (pCtx^.write_ctx <> nil) then begin
name := FDCipherGetName(pCtx^.write_ctx^.evp_cipher_class, pCtx^.write_ctx^.key_sz);
if name <> nil then begin
len := FDAnsiStrLen(name);
Result := SQLITE_OK;
end;
end;
end;
end;
{-------------------------------------------------------------------------------}
function ad_sqlite3GetEncryptionError(db: psqlite3; var error: PFDAnsiString;
var len: Integer; var error_code: Integer): Integer;
var
pDb: _pDb;
pCtx: PSQLiteCodecCtx;
pPager: _pPager;
begin
error := nil;
len := 0;
error_code := 0;
Result := SQLITE_OK;
pDb := ad_sqlite3GetBackend(db, 0);
if pDb^.pBt <> nil then begin
pPager := ad_sqlite3BtreeGetPager(pDb^.pBt);
pCtx := ad_sqlite3PagerGetCodec(pPager);
if (pCtx <> nil) and (pCtx^.error <> nil) then begin
error := pCtx^.error;
len := pCtx^.error_sz;
error_code := pCtx^.error_code;
Result := SQLITE_ERROR;
end;
end;
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
initialization
SQLITE_STATIC := nil;
SQLITE_TRANSIENT := Tsqlite3_destroy_callback(Pointer({$IFDEF FireDAC_32} $FFFFFFFF {$ENDIF}
{$IFDEF FireDAC_64} $FFFFFFFFFFFFFFFF {$ENDIF}));
{$IFDEF FireDAC_SQLITE_STATIC}
GCodecAttachLock := TCriticalSection.Create;
{$IFDEF FireDAC_SQLITE_EXTERNAL}
ad_sqlite3SetEncryptionCallbacks(@sqlite3_activate_see, @sqlite3_key_v2,
@sqlite3_rekey_v2, @sqlite3CodecGetKey, @sqlite3CodecAttach);
{$ENDIF}
finalization
FDFreeAndNil(GCodecAttachLock);
{$ENDIF}
end.
|
{
GMElevation unit
ES: contiene las clases bases necesarias para calcular elevaciones de terreno
de un conjunto de LatLng
EN: includes the base classes needed for calculate a terrain elevations of a
set of LatLng
=========================================================================
MODO DE USO/HOW TO USE
ES: poner el componente en el formulario, linkarlo a un TGMMap, establecer
las lat/lng y ejecutar
EN: put the component into a form, link to a TGMMap, establish the lat/lng and
execute
=========================================================================
History:
ver 1.0.0
ES:
error: error corregido en TCustomGMElevation.Execute en la 1era búsqeda.
EN:
bug: bug fixed into TCustomGMElevation.Execute on the first request.
ver 0.1.9
ES:
nuevo: documentación
nuevo: se hace compatible con FireMonkey
EN:
new: documentation
new: now compatible with FireMonkey
ver 0.1.8:
ES- primera versión
EN- first version
=========================================================================
IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras,
ampliaciones, errores y/o cualquier otro tipo de sugerencia, envíame un correo a:
gmlib@cadetill.com
IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements,
errors and/or any another type of suggestion, please send me a mail to:
gmlib@cadetill.com
=========================================================================
Copyright (©) 2012, by Xavier Martinez (cadetill)
@author Xavier Martinez (cadetill)
@web http://www.cadetill.com
}
{*------------------------------------------------------------------------------
The GMElevation unit includes the base classes needed for calculate a terrain elevations of a set of LatLng.
@author Xavier Martinez (cadetill)
@version 1.5.3
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
La unit GMElevation contiene las clases bases necesarias para calcular elevaciones de terreno de un conjunto de LatLng.
@author Xavier Martinez (cadetill)
@version 1.5.3
-------------------------------------------------------------------------------}
unit GMElevation;
{$I ..\gmlib.inc}
interface
uses
{$IFDEF DELPHIXE2}
System.Classes, System.Contnrs, Data.DB,
{$ELSE}
Classes, Contnrs, DB,
{$ENDIF}
GMMap, GMClasses, GMConstants, GMMarker, GMPolyline;
type
{*------------------------------------------------------------------------------
The result of an ElevationService request.
More information at https://developers.google.com/maps/documentation/javascript/reference?hl=en#ElevationResult
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Resultado de una llamada a ElevationService.
Más información en https://developers.google.com/maps/documentation/javascript/reference?hl=en#ElevationResult
-------------------------------------------------------------------------------}
TElevationResult = class
private
{*------------------------------------------------------------------------------
The location of this elevation result.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Ubicación de este resultado de la elevación.
-------------------------------------------------------------------------------}
FLocation: TLatLng;
{*------------------------------------------------------------------------------
The distance, in meters, between sample points from which the elevation was interpolated.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Distancia, en metros, entre los puntos de muestreo de la elevación interpolada.
-------------------------------------------------------------------------------}
FResolution: Real;
{*------------------------------------------------------------------------------
The elevation of this point on Earth, in meters above sea level.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Elevación del punto terrestre, en metro sobre el nivel del mar.
-------------------------------------------------------------------------------}
FElevation: Real;
public
{*------------------------------------------------------------------------------
Constructor class
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Constructor de la clase
-------------------------------------------------------------------------------}
constructor Create; virtual;
{*------------------------------------------------------------------------------
Destructor class
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Destructor de la clase
-------------------------------------------------------------------------------}
destructor Destroy; override;
property Location: TLatLng read FLocation;
property Elevation: Real read FElevation;
property Resolution: Real read FResolution;
end;
{*------------------------------------------------------------------------------
Class for elevations collection.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Clase para la colección de elevaciones.
-------------------------------------------------------------------------------}
TElevationResults = class
private
FElevationResult: TObjectList;
FStatus: TElevationStatus;
function GetItems(Index: Integer): TElevationResult;
function GetCount: Integer;
procedure ParseElevations(Elevations: string);
function AddElevationResult(Elevation, Resolution, Lat, Lng: string): Integer;
public
{*------------------------------------------------------------------------------
Constructor class
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Constructor de la clase
-------------------------------------------------------------------------------}
constructor Create; virtual;
{*------------------------------------------------------------------------------
Destructor class
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Destructor de la clase
-------------------------------------------------------------------------------}
destructor Destroy; override;
{*------------------------------------------------------------------------------
Deletes all items from the elevations collection.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Borra todos los elementos de la colección de elevaciones.
-------------------------------------------------------------------------------}
procedure Clear;
{*------------------------------------------------------------------------------
The status returned by the ElevationService upon completion of an elevation request.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Estado devuelto por ElevationService tras la finalización de una solicitud de elevación.
-------------------------------------------------------------------------------}
property Status: TElevationStatus read FStatus;
{*------------------------------------------------------------------------------
Elevations list.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Lista de elevaciones.
-------------------------------------------------------------------------------}
property Items[Index: Integer]: TElevationResult read GetItems; default;
{*------------------------------------------------------------------------------
Count of elevations.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Cantidad de elevaciones.
-------------------------------------------------------------------------------}
property Count: Integer read GetCount;
end;
{*------------------------------------------------------------------------------
Base class for calculating elevations.
More information at:
https://developers.google.com/maps/documentation/javascript/reference?hl=en#ElevationService
https://developers.google.com/maps/documentation/javascript/elevation
https://developers.google.com/maps/documentation/elevation/index
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Clase base para el cálculo de elevaciones.
Más información en:
https://developers.google.com/maps/documentation/javascript/reference?hl=en#ElevationService
https://developers.google.com/maps/documentation/javascript/elevation
https://developers.google.com/maps/documentation/elevation/index
-------------------------------------------------------------------------------}
TCustomGMElevation = class(TGMObjects, ILinePoint)
private
{*------------------------------------------------------------------------------
The path along which to collect elevation values.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Camino a lo largo del cual recoger el valor de las elevaciones.
-------------------------------------------------------------------------------}
FLinePoints: TLinePoints;
{*------------------------------------------------------------------------------
The number of equidistant points along the given path for which to retrieve elevation data, including the endpoints. The number of samples must be a value between 2 and 512 inclusive. Valid only for ElevationType = etAlongPath.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Número de puntos equidistantes a lo largo del camino dado para los que recuperar el valor de la elevación, incluido el punto final. El numero de muestras debe ser un valor entre 2 y 512 incluidos. Sólo aplicable a ElevationType = etAlongPath.
-------------------------------------------------------------------------------}
FSamples: Integer;
{*------------------------------------------------------------------------------
Elevations type search.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Tipo de búsqueda para las elevaciones.
-------------------------------------------------------------------------------}
FElevationType: TElevationType;
{*------------------------------------------------------------------------------
Search result.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Resultado de la búsqueda.
-------------------------------------------------------------------------------}
FElevationResult: TElevationResults;
function GetCountLinePoints: Integer;
function GetItems(I: Integer): TLinePoint;
procedure SetSamples(const Value: Integer);
protected
function GetAPIUrl: string; override;
procedure DeleteMapObjects; override;
procedure ShowElements; override;
procedure EventFired(EventType: TEventType; Params: array of const); override;
{ ILinePoint }
procedure LinePointChanged;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
{*------------------------------------------------------------------------------
Creates a new LinePoint point.
@param LatLng The Lat/Lng of the point.
@return New TLinePoint.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Crea un nuevo punto LinePoint.
@param Lat Latitud/Longitud del punto.
@return Nuevo TLinePoint.
-------------------------------------------------------------------------------}
function AddLatLng(LatLng: TLatLng): TLinePoint; overload;
{*------------------------------------------------------------------------------
Creates a new LinePoint point.
@param Lat Point latitude.
@param Lng Point longitude.
@return New TLinePoint.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Crea un nuevo punto LinePoint.
@param Lat Latitud del punto.
@param Lng Longitud del punto.
@return Nuevo TLinePoint.
-------------------------------------------------------------------------------}
function AddLatLng(Lat, Lng: Real): TLinePoint; overload;
{*------------------------------------------------------------------------------
Adds points from CSV file.
@param LatColumn Column with latitude.
@param LngColumn Column with longitude.
@param FileName CSV file name.
@param Delimiter Delimiter used into CSV file (usually "," or ";").
@param DeleteBeforeLoad If true, delete all existing points before load CSV file.
@param WithRownTitle If true, the first row of CSV file contain the column titles.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Añade puntos desde un archivo CSV.
@param LatColumn Columna con la latitud.
@param LngColumn Columna con la longitud.
@param FileName Nombre del fichero CSV.
@param Delimiter Delimitador usado en el fichero CSV (usualmente "," o ";").
@param DeleteBeforeLoad Si true, elimina todos los puntos existentes antes de cargar el archivo CSV.
@param WithRownTitle Si true, la primera fila del archivo CSV contendrá el título de las columnas.
-------------------------------------------------------------------------------}
procedure AddLatLngFromCSV(LatColumn, LngColumn: Integer; FileName: string;
Delimiter: Char = ','; DeleteBeforeLoad: Boolean = True; WithRownTitle: Boolean = True);
{*------------------------------------------------------------------------------
Adds points from DataSet.
@param DataSet DataSet where get the data.
@param LatField Field with latitude.
@param LngField Field with longitude.
@param DeleteBeforeLoad If true, delete all existing points before load DataSet.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Añade puntos desde un DataSet.
@param DataSet DataSet de donde obtener los datos.
@param LatField Campo con la latitud.
@param LngField Campo con la longitud.
@param DeleteBeforeLoad Si true, elimina todos los puntos existentes antes de cargar el DataSet.
-------------------------------------------------------------------------------}
procedure AddLatLngFromDataSet(DataSet: TDataSet; LatField, LngField: string;
DeleteBeforeLoad: Boolean = True);
{*------------------------------------------------------------------------------
Adds points from TBasePolyline (TPolygon or TPolyline).
@param Poly TBasePolyline where get the data.
@param DeleteBeforeLoad If true, delete all existing points before load TBasePolyline.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Añade puntos desde un TBasePolyline (TPolygon o TPolyline).
@param Poly TBasePolyline de donde obtener los datos.
@param DeleteBeforeLoad Si true, elimina todos los puntos existentes antes de cargar el TBasePolyline.
-------------------------------------------------------------------------------}
procedure AddLatLngFromPoly(Poly: TBasePolyline; DeleteBeforeLoad: Boolean = True); virtual;
{*------------------------------------------------------------------------------
Deletes all points.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Borra todos los puntos.
-------------------------------------------------------------------------------}
procedure Clear;
{*------------------------------------------------------------------------------
Deletes a specified points.
@param Index Index of the point to delete.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Borra un punto específico.
@param Index Índice del punto a borrar.
-------------------------------------------------------------------------------}
procedure DelLatLng(Index: Integer);
{*------------------------------------------------------------------------------
Search the elevations according to the specified parameters.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Busca las elevaciones según los parámetros especificados.
-------------------------------------------------------------------------------}
procedure Execute;
{*------------------------------------------------------------------------------
Count of points.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Cantidad de puntos.
-------------------------------------------------------------------------------}
property CountLinePoints: Integer read GetCountLinePoints;
{*------------------------------------------------------------------------------
Array with the collection items.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Array con la colección de elementos.
-------------------------------------------------------------------------------}
property Items[I: Integer]: TLinePoint read GetItems; default;
property ElevationResult: TElevationResults read FElevationResult;
published
property LinePoints: TLinePoints read FLinePoints write FLinePoints;
property Samples: Integer read FSamples write SetSamples default 2;
property ElevationType: TElevationType read FElevationType write FElevationType default etForLocations;
end;
implementation
uses
{$IFDEF DELPHIXE2}
System.SysUtils,
{$ELSE}
SysUtils,
{$ENDIF}
Lang, GMFunctions;
{ TCustomGMElevation }
function TCustomGMElevation.AddLatLng(LatLng: TLatLng): TLinePoint;
begin
Result := AddLatLng(LatLng.Lat, LatLng.Lng);
end;
function TCustomGMElevation.AddLatLng(Lat, Lng: Real): TLinePoint;
begin
Result := FLinePoints.Add;
Result.Lat := Lat;
Result.Lng := Lng;
end;
procedure TCustomGMElevation.AddLatLngFromCSV(LatColumn, LngColumn: Integer;
FileName: string; Delimiter: Char; DeleteBeforeLoad, WithRownTitle: Boolean);
var
L1, L2: TStringList;
i: Integer;
Point: TLinePoint;
Stop: Boolean;
begin
if not FileExists(FileName) then
raise Exception.Create(GetTranslateText('El fichero no existe', Language));
if DeleteBeforeLoad then FLinePoints.Clear;
L1 := TStringList.Create;
L2 := TStringList.Create;
try
L1.LoadFromFile(FileName);
if WithRownTitle then L1.Delete(0);
L2.Delimiter := Delimiter;
{$IFDEF DELPHI2005}
L2.StrictDelimiter := True;
{$ENDIF}
for i := 0 to L1.Count - 1 do
begin
L2.DelimitedText := L1[i];
if (LatColumn > L2.Count) or (LngColumn > L2.Count) then
raise Exception.Create(GetTranslateText('El número de columna es incorrecto', Language));
Point := LinePoints.Add;
Point.Lat := Point.StringToReal(L2[LatColumn]);
Point.Lng := Point.StringToReal(L2[LngColumn]);
Stop := False;
if Stop then Break;
end;
finally
if Assigned(L1) then FreeAndNil(L1);
if Assigned(L2) then FreeAndNil(L2);
end;
end;
procedure TCustomGMElevation.AddLatLngFromDataSet(DataSet: TDataSet; LatField,
LngField: string; DeleteBeforeLoad: Boolean);
var
Bkm: TBookmark;
Point: TLinePoint;
begin
if not DataSet.Active then DataSet.Open;
if DeleteBeforeLoad then FLinePoints.Clear;
DataSet.DisableControls;
Bkm := DataSet.GetBookmark;
try
DataSet.First;
while not DataSet.Eof do
begin
Point := LinePoints.Add;
Point.Lat := DataSet.FieldByName(LatField).AsFloat;
Point.Lng := DataSet.FieldByName(LngField).AsFloat;
DataSet.Next;
end;
finally
DataSet.GotoBookmark(Bkm);
DataSet.FreeBookmark(Bkm);
DataSet.EnableControls;
end;
end;
procedure TCustomGMElevation.AddLatLngFromPoly(Poly: TBasePolyline;
DeleteBeforeLoad: Boolean);
var
Point: TLinePoint;
i: Integer;
begin
if DeleteBeforeLoad then FLinePoints.Clear;
for i := 0 to Poly.CountLinePoints - 1 do
begin
Point := LinePoints.Add;
Point.Assign(Poly[i]);
end;
// if (Poly is TPolygon) and (Poly.CountLinePoints > 0) then //<- dependence of framework
// begin
// Point := LinePoints.Add;
// Point.Assign(Poly[0]);
// end;
end;
procedure TCustomGMElevation.Clear;
begin
FLinePoints.Clear;
FElevationResult.Clear;
end;
constructor TCustomGMElevation.Create(aOwner: TComponent);
begin
inherited;
FLinePoints := TLinePoints.Create(Self, TLinePoint);
FSamples := 2;
FElevationType := etForLocations;
FElevationResult := TElevationResults.Create;
end;
procedure TCustomGMElevation.DeleteMapObjects;
begin
inherited;
end;
procedure TCustomGMElevation.DelLatLng(Index: Integer);
begin
FLinePoints.Delete(Index);
end;
destructor TCustomGMElevation.Destroy;
begin
if Assigned(FLinePoints) then FreeAndNil(FLinePoints);
if Assigned(FElevationResult) then FreeAndNil(FElevationResult);
inherited;
end;
procedure TCustomGMElevation.EventFired(EventType: TEventType;
Params: array of const);
begin
inherited;
end;
procedure TCustomGMElevation.Execute;
const
StrParams = '%s,%s,%s';
var
Params: string;
Tmp: string;
Points: array of TLatLng;
i: Integer;
begin
if not Assigned(Map) then
raise Exception.Create(GetTranslateText('Mapa no asignado', Language));
SetLength(Points, CountLinePoints);
for i := 0 to LinePoints.Count - 1 do
Points[i] := LinePoints[i].GetLatLng;
Params := Format(StrParams, [
QuotedStr(TCustomTransform.ElevationTypeToStr(FElevationType)),
QuotedStr(TGMGenFunc.PointsToStr(Points, GetMapPrecision)),
IntToStr(Samples)
]);
ExecuteScript('GetElevations', Params);
repeat
TGMGenFunc.ProcessMessages;
until (GetIntegerField(ElevationsForm, ElevationsFormResponse) = 1);
ElevationResult.Clear;
Tmp := GetStringField(ElevationsForm, ElevationsFormStatus);
ElevationResult.FStatus := TCustomTransform.StrToElevationStatus('es' + Tmp);
Tmp := GetStringField(ElevationsForm, ElevationsFormElevations);
ElevationResult.ParseElevations(Tmp);
end;
function TCustomGMElevation.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference#ElevationService';
end;
function TCustomGMElevation.GetCountLinePoints: Integer;
begin
Result := LinePoints.Count;
end;
function TCustomGMElevation.GetItems(I: Integer): TLinePoint;
begin
Result := TLinePoint(FLinePoints[i]);
end;
procedure TCustomGMElevation.LinePointChanged;
begin
end;
procedure TCustomGMElevation.SetSamples(const Value: Integer);
begin
if FSamples = Value then Exit;
FSamples := Value;
if FSamples < 2 then FSamples := 2;
if FSamples > 512 then FSamples := 512;
end;
procedure TCustomGMElevation.ShowElements;
begin
end;
{ TElevationResults }
function TElevationResults.AddElevationResult(Elevation, Resolution, Lat,
Lng: string): Integer;
var
ElevRes: TElevationResult;
begin
ElevRes := TElevationResult.Create;
ElevRes.FLocation.Lat := ElevRes.FLocation.StringToReal(Lat);
ElevRes.FLocation.Lng := ElevRes.FLocation.StringToReal(Lng);
ElevRes.FResolution := ElevRes.FLocation.StringToReal(Resolution);
ElevRes.FElevation := ElevRes.FLocation.StringToReal(Elevation);
Result := FElevationResult.Add(ElevRes);
end;
procedure TElevationResults.Clear;
begin
FStatus := esNO_REQUEST;
FElevationResult.Clear;
end;
constructor TElevationResults.Create;
begin
FElevationResult := TObjectList.Create;
end;
destructor TElevationResults.Destroy;
begin
if Assigned(FElevationResult) then FreeAndNil(FElevationResult);
inherited;
end;
function TElevationResults.GetCount: Integer;
begin
Result := FElevationResult.Count;
end;
function TElevationResults.GetItems(Index: Integer): TElevationResult;
begin
Result := TElevationResult(FElevationResult[Index]);
end;
procedure TElevationResults.ParseElevations(Elevations: string);
var
T1, T2: TStringList;
i: Integer;
begin
T1 := TStringList.Create;
T2 := TStringList.Create;
try
T1.Delimiter := ';';
T2.Delimiter := '|';
{$IFDEF DELPHI2005}
T1.StrictDelimiter := True;
T2.StrictDelimiter := True;
{$ENDIF}
T1.DelimitedText := Elevations;
for i := 0 to T1.Count - 1 do
begin
T2.DelimitedText := T1[i];
if T2.Count <> 4 then Continue;
AddElevationResult(T2[0], T2[1], T2[2], T2[3]);
end;
finally
if Assigned(T1) then FreeAndNil(T1);
if Assigned(T2) then FreeAndNil(T2);
end;
end;
{ TElevationResult }
constructor TElevationResult.Create;
begin
FLocation := TLatLng.Create;
FResolution := 0;
FElevation := 0;
end;
destructor TElevationResult.Destroy;
begin
if Assigned(FLocation) then FreeAndNil(FLocation);
inherited;
end;
end.
|
//Algorithme : croix2
//But : Demander à l'utilisateur un caractère et une taille et effectuer une croix avec ces données.
//VAR
//car : caractère
//taille, height, width : entier
//DEBUT
//ECRIRE "Veuillez entrer le caractère que vous voulez utiliser pour réaliser la croix"
//LIRE car
//ECRIRE "Veuillez entrer la taille de la croix"
//LIRE taille
//TANT QUE (height<taille) FAIRE
//DEBUT
//POUR width<--0 A taille<--1 FAIRE
//DEBUT
//SI (height=width) OU (width=((taille-1)-height)) ALORS
//DEBUT
//ECRIRE car;
//FIN
//SINON
//DEBUT
//ECRIRE " ";
//FIN;
//FIN;
//ECRIRE;
//height<--height+1;
//FIN;
//FIN
//FIN.
PROGRAM croix;
uses crt;
VAR
car : char;
taille, height, width : integer;
BEGIN
writeln('Veuillez entrer le caractère que vous voulez utiliser pour réaliser la croix');
readln(car);
writeln('Veuillez entrer la taille de la croix');
readln(taille);
WHILE (height<taille) DO
BEGIN
FOR width:=0 TO taille-1 DO
BEGIN
IF (height=width) OR (width=((taille-1)-height)) THEN
BEGIN
write(car);
END
ELSE
BEGIN
write(' ');
END;
END;
writeln();
height:=height+1;
END;
readln;
END.
|
unit uEngine2DObject;
{$ZEROBASEDSTRINGS OFF}
interface
uses
System.Classes,System.UITypes, FMX.Types,FMX.Objects,uGeometryClasses,
System.JSon, uEngineResource, FMX.Graphics, uEngineUtils, uEngine2DInvade,
System.SysUtils, System.Types,uEngine2DClasses,uEngineAnimation;
const DRAW_INTERVAL = 40; // unit : ms
Type
// TReceiveMouseEventType = (rtNone,rtAll,rtMouseDownAndUp);
{TEngine2DObject 类是动画元素的基类,该类集成了动画元素的通用属性}
TEngine2DObject = class
const
DEFAULT_WIDTH = 50;
DEFAULT_HEIGHT = 50;
private
FSendToBack, FBringToFront: TNotifyEvent;
FInvadeManager : T2DInvadeManager;
AllInvadeData : Array Of TOriInvadePoints;
function IsInSquare(X,Y:Single):boolean;
protected
FSpriteName : String; //精灵名称
FPosition : T2DPosition; // 当前的Object的位置和大小的参数...
FParentPosition : T2DPosition; // 这个Object的Parent的位置和大小的参数...
FVisible : boolean;
FOpacity : Single;
FHitTest : Boolean;
FDrag : boolean;
FAlign : TObjectAlign;
// FIsMouseMove : boolean;
FIsMouseEnter : boolean;
FBitmap : TBitmap;
FResManager : TEngineResManager;
FAnimation : T2DNameList<T2DAnimation>;
FAnimationFinishList : TStringList; // 执行完了的动画的姓名列表....
FMouseIsDown : Boolean; // 是否鼠标按下了...
FInitPosition : TPointF; // 为了拖拽的效果,记录下初始点...
FMouseDownPoint : TPointF; // 鼠标Down的时候的点....
FOnMouseDown,FOnMouseUp : TMouseEvent;
FOnMouseMove : TMouseMoveEvent;
FOnMouseEnter,FOnMouseLeave : TNotifyEvent;
procedure SetInitX(value : Single);
procedure SetInitY(value : Single);
procedure SetX(value : Single); virtual;
procedure SetY(value : Single); virtual;
procedure SetRotate(value : Single); virtual;
procedure SetScaleX(value : Single);virtual;
procedure SetScaleY(value : Single);virtual;
procedure SetWidth(value : Single); virtual;
procedure SetHeight(value : Single);virtual;
function GetWidth : Single;virtual;
function GetHeight : Single;virtual;
public
Constructor Create(AImage : TBitmap);
Destructor Destroy;override;
procedure BringToFront;
procedure SendToBack;
Procedure AcceptAInvade(S1, S2, S3, S4 : String);
Procedure UpdateInvadePoints; // 当大小或者Visible改变的时候,更新下当前的INvade点的坐标值...
procedure Repaint;virtual;
procedure LoadConfig(AConfig : String);virtual;abstract;
procedure ClearOldStatus;virtual;abstract;
procedure Resize(TheParentPosition : T2DPosition);virtual;abstract;
Procedure ReadFromJSONObject(Var inJObj : TJSONObject); virtual; abstract;
function IsMouseMove(Shift: TShiftState; X,Y: Single) : Boolean;
function IsMouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single) : Boolean;
function IsMouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single) : Boolean;
property OnMouseDown : TMouseEvent read FOnMouseDown write FOnMouseDown;
property OnMouseUp : TMouseEvent read FOnMouseUp write FOnMouseUp;
property OnMouseMove : TMouseMoveEvent read FOnMouseMove write FOnMouseMove;
property OnBringToFront : TNotifyEvent read FBringToFront write FBringToFront;
property OnSendToBack : TNotifyEvent read FSendToBack write FSendToBack;
property Position : T2DPosition read FPosition write FPosition;
property X : Single read FPosition.X write SetX;
property Y : Single read FPosition.Y write SetY;
property InitX : Single read FPosition.InitX write SetInitX;
property InitY : Single read FPosition.InitY write SetInitY;
property ScaleX : Single read FPosition.ScaleX write SetScaleX;
property ScaleY : Single read FPosition.ScaleY write SetScaleY;
property Rotate : Single read FPosition.Rotate write SetRotate;
property Width : Single read GetWidth write SetWidth;
property Height : Single read GetHeight write SetHeight;
property InitWidth : Single read FPosition.InitWidth write FPosition.InitWidth;
property InitHeight: Single read FPosition.InitHeight write FPosition.InitHeight;
property InitParentWidth : Single read FParentPosition.InitWidth ; // 这个Object的Parent的大小设置为只读选项,实际上这个Object也没有权限改变Parent 的大小...
property InitParentHeight : Single read FParentPosition.InitHeight;
property Opacity : Single read FOpacity write FOpacity;
property Align : TObjectAlign read FAlign write FAlign;
property SpriteName : String read FSpriteName write FSpriteName;
property Visible : boolean read FVisible write FVisible;
Property HitTest : Boolean Read FHitTest Write FHitTest;
property Drag : boolean read FDrag write FDrag;
property ResManager : TEngineResManager Read FResManager Write FResManager;
Property InvadeManager : T2DInvadeManager Read FInvadeManager Write FInvadeManager;
end;
implementation
{ TEngine2DObject }
procedure TEngine2DObject.BringToFront;
begin
if Assigned(FBringToFront) then
FBringToFront(Self);
end;
constructor TEngine2DObject.Create(AImage : TBitmap);
begin
FBitmap := AImage;
FPosition.Zero;
FParentPosition.Zero;
FVisible := false;
FOpacity := 1;
FAlign := oaNone;
// FIsMouseMove := false;
FIsMouseEnter := false;
FHitTest := false;
FDrag := false;
FMouseIsDown := false;
FAnimation := T2DNameList<T2DAnimation>.Create;
FAnimationFinishList := TStringList.Create;
SetLength(AllInvadeData, 0);
end;
destructor TEngine2DObject.Destroy;
begin
SetLength(AllInvadeData, 0);
FAnimation.DisposeOf;
FAnimationFinishList.DisposeOf;
inherited;
end;
function TEngine2DObject.GetHeight: Single;
begin
result := FPosition.Height;
end;
function TEngine2DObject.GetWidth: Single;
begin
result := FPosition.Width;
end;
function TEngine2DObject.IsInSquare(X, Y: Single): boolean;
begin
result := false;
x := x - Position.X;
if x < 0 then exit;
if x > FPosition.Width then exit;
y := y - Position.Y;
if y < 0 then exit;
if y > FPosition.Height then exit;
result := True;
end;
function TEngine2DObject.IsMouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Single): Boolean;
begin
result := false;
if not FVisible then
exit;
if not FHitTest then exit;
if not IsInSquare(X, Y) then exit;
if not assigned(FOnMouseDown) then
exit;
FMouseIsDown := true;
FMouseDownPoint := PointF(X, Y);
// if FDrag then
// begin
// Self.FInitPosition := PointF(X,Y);
// end;
FOnMouseDown(Self, Button, Shift, X, Y);
result := true;
end;
function TEngine2DObject.IsMouseMove(Shift: TShiftState; X, Y: Single): Boolean;
begin
result := false;
if not FVisible then exit;
if not FHitTest then exit;
if not IsInSquare(X, Y) then
begin
if FIsMouseEnter then
begin
FIsMouseEnter := false;
if Assigned(FOnMouseLeave) then
FOnMouseLeave(Self);
end;
exit;
end;
if not FIsMouseEnter then
begin
FIsMouseEnter := true;
if Assigned(FOnMouseEnter) then
FOnMouseEnter(Self);
end;
if Assigned(FOnMouseMove) then
FOnMouseMove(Self, Shift, X, Y);
// FIsMouseMove := true;
result := true;
end;
function TEngine2DObject.IsMouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Single): Boolean;
begin
result := false;
if not FVisible then
exit;
FMouseIsDown := false;
if not FHitTest then exit;
if not IsInSquare(X,Y) then exit;
if not assigned(FOnMouseUp) then
exit;
FOnMouseUp(Self, Button, Shift, X, Y);
result := true;
end;
procedure TEngine2DObject.Repaint;
var
I : Integer;
S : String;
tmpAnimation : T2DAnimation;
begin
// 检查下执行完成了动画...
if FAnimationFinishList.Count > 0 then
begin
for I := 0 to FAnimationFinishList.Count - 1 do
begin
S := FAnimationFinishList.Strings[i];
tmpAnimation := FAnimation.Has(S);
if tmpAnimation <> nil then
begin
if tmpAnimation.FreeOnFinish then
begin
// 如果这个动画自动销毁的话,那么在这里直接进行销毁...
FAnimation.Remove(S);
end;
end;
end;
FAnimationFinishList.Clear;
end;
// 检查下动画...
for I := 0 to FAnimation.ItemCount - 1 do
begin
if FAnimation.Items[i].Enabled then
begin
FAnimation.Items[i].DoAnimation(DRAW_INTERVAL);
end;
end;
end;
procedure TEngine2DObject.SendToBack;
begin
if Assigned(FSendToBack) then
FSendToBack(Self);
end;
Procedure TEngine2DObject.AcceptAInvade(S1: string; S2: string;S3 :String; S4:String);
Var
_Len, _Len1 : Integer;
XX, YY : Integer;
S : String;
begin
_Len := Length(Self.AllInvadeData);
_Len := _Len + 1;
SetLength(AllInvadeData, _Len);
AllInvadeData[_Len-1].FName := S1;
AllInvadeData[_Len-1].InfluenceName := S3;
if S4 <> '' then
begin
GetHeadString(S4,'(');
S := GetHeadString(S4,')');
XX := StrToIntDef(GetHeadString(S,','),0);
YY := StrToIntDef(S,0);
AllInvadeData[_Len-1].DstOriPoints := PointF(XX + FPosition.InitX ,YY + FPosition.InitY);
AllInvadeData[_Len-1].DstCurPoints := PointF(XX,YY);
end;
_Len1 := 0;
while S2 <> '' do
begin
GetHeadString(S2,'(');
S := GetHeadString(S2,')');
try
XX := StrToInt(GetHeadString(S,','));
YY := StrToInt(S);
except
continue;
end;
_Len1 := _Len1 + 1;
SetLength(AllInvadeData[_Len-1].FPoints, _Len1);
AllInvadeData[_Len-1].FPoints[_Len1-1] := PointF(XX, YY);
end;
end;
Procedure TEngine2DObject.UpdateInvadePoints;
Var
I, J : Integer;
S,S1 : String;
XX, YY : Integer;
DX, DY : Single;
AllPoints : Array of TPointF;
begin
if not FVisible then
begin
exit;
end;
if Self.Align = oaClient then
begin
DX := Self.FParentPosition.Width/Self.FParentPosition.InitWidth;
DY := Self.FParentPosition.Height/Self.FParentPosition.InitHeight;
end else
begin
DX := Self.Position.Width/Self.Position.InitWidth;
DY := Self.Position.Height/Self.Position.InitHeight;
end;
for I := 0 to High(AllInvadeData) do
begin
for J := 0 to High(AllInvadeData[I].FPoints) do
begin
SetLength(AllPoints, J+1);
AllPoints[J].X := AllInvadeData[I].FPoints[J].X*DX + Self.Position.X + Self.FParentPosition.X;
AllPoints[J].Y := AllInvadeData[I].FPoints[J].Y*DY + Self.Position.Y + Self.FParentPosition.Y;
end;
AllInvadeData[I].DstCurPoints.X := (AllInvadeData[I].DstOriPoints.X - FPosition.InitX)*DX + Self.Position.X + Self.FParentPosition.X;
AllInvadeData[I].DstCurPoints.Y := (AllInvadeData[I].DstOriPoints.Y - FPosition.InitY)*DY + Self.Position.Y + Self.FParentPosition.Y;
if FInvadeManager <> nil then
begin
FInvadeManager.UpdateAnINvadeData(AllInvadeData[I].FName,
AllInvadeData[I].InfluenceName,
AllPoints,
AllInvadeData[I].DstOriPoints,
AllInvadeData[I].DstCurPoints);
end;
end;
SetLength(AllPoints, 0);
end;
procedure TEngine2DObject.SetHeight(value: Single);
begin
FPosition.Height := value;
end;
procedure TEngine2DObject.SetInitX(value: Single);
begin
FPosition.InitX := value;
end;
procedure TEngine2DObject.SetInitY(value: Single);
begin
FPosition.InitY := value;
end;
procedure TEngine2DObject.SetRotate(value: Single);
begin
FPosition.Rotate := value;
end;
procedure TEngine2DObject.SetScaleX(value: Single);
begin
FPosition.ScaleX := value;
end;
procedure TEngine2DObject.SetScaleY(value: Single);
begin
FPosition.ScaleY := value;
end;
procedure TEngine2DObject.SetWidth(value: Single);
begin
FPosition.Width := value;
end;
procedure TEngine2DObject.SetX(value: Single);
begin
FPosition.X := value;
end;
procedure TEngine2DObject.SetY(value: Single);
begin
FPosition.Y := value;
end;
end.
|
{$R-} {Range checking off}
{$B+} {Boolean complete evaluation on}
{$S+} {Stack checking on}
{$I+} {I/O checking on}
{$N-} {No numeric coprocessor}
unit FileOps;
interface
uses
CRT, { AssignCRT }
DOS, {FindFirst, FindNext, SearchRec}
Printer; {PRN}
CONST
nofile = '';
procedure GetDirectory(pattern : string;
VAR Dir : POINTER;
VAR firstfilename : string);
{ DIR = NIL if error }
function GetNextFile(VAR Directory : POINTER) : string;
{ returns '' if nothing }
procedure StripExtension(VAR name: string);
function Exist(NameofFile: string):Boolean;
procedure DirectOutput(VAR out : TEXT);
procedure CheckPath(path : string);
implementation
var
dest : char;
infile : file;
out : text;
Directory : string;
n : integer;
ExitPtr : Pointer;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
procedure GetDirectory(pattern : string;
VAR Dir : POINTER;
VAR firstfilename : string);
{ DIR = NIL if error }
var
DirInfo : SearchRec;
begin
FindFirst(pattern,Archive,DirInfo);
IF DOSError <> 0 THEN
Dir := NIL
ELSE
BEGIN
firstfilename := DirInfo.Name;
Dir := @DirInfo;
END;
END; {GetDirectory}
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
function GetNextFile(VAR Directory : POINTER) : string;
{ returns '' if nothing }
var
DirInfo : ^SearchRec;
begin
DirInfo := Directory;
FindNext(DirInfo^);
IF DOSError <> 0 THEN
GetNextFile := ''
ELSE
GetNextFile := DirInfo^.Name;
END;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
procedure StripExtension(VAR name: string);
CONST
dot = '.';
BEGIN
name := copy(name,1,pos(dot,name)-1);
END;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
function Exist(NameofFile: string):Boolean;
var
Fil: file;
begin
Assign(Fil,NameOfFile);
{$I-}
Reset(Fil);
close(Fil);
{$I+}
Exist := (IOresult = 0);
end; {exist}
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
procedure DirectOutput(VAR out : TEXT);
var
answer : string;
begin
write('Direct Output to (S)creen, (P)rinter or (F)ile? ');
readln(answer);
dest := upcase(answer[1]);
case dest of
'S' : AssignCRT(out);
'P' : Assign(out,'PRN');
'F' : begin
write('Enter name of File: ');
readln(answer);
assign(out,answer);
if exist(answer) then
begin
write('FILE EXISTS! Overwrite it? ');
readln(answer);
if (upcase(answer[1]) <> 'Y') then
DirectOutput(out);
end;
end;
end; {case}
rewrite(out);
end; {directoutput}
procedure CheckPath(path : string);
var
answer : string;
begin
{$I-}
ChDir(Path + paramstr(1));
{$I+}
if (IOresult <> 0) or (length(paramstr(1)) < 1) then
repeat
Writeln('Path missing or incorrect. Please specify: ');
write(path);
readln(answer);
{$I-}
ChDir(Path + answer);
{$I+}
until (IOResult = 0);
end; {checkpath}
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
{$F+} PROCEDURE CleanUp; {$F-}
{ restore original directory }
BEGIN
ChDir(Directory);
ExitProc := ExitPtr;
END;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
begin {MAIN}
{ Install Termination Code }
ExitPtr := ExitProc;
ExitProc := @CleanUp;
GetDir(0,Directory); {remember where we started from}
end.
|
{ **********************************************************************}
{ }
{ DeskMetrics DLL - dskMetricsWinInfo.pas }
{ Copyright (c) 2010-2011 DeskMetrics Limited }
{ }
{ http://deskmetrics.com }
{ http://support.deskmetrics.com }
{ }
{ support@deskmetrics.com }
{ }
{ This code is provided under the DeskMetrics Modified BSD License }
{ A copy of this license has been distributed in a file called }
{ LICENSE with this source code. }
{ }
{ **********************************************************************}
unit dskMetricsWinInfo;
interface
uses
Windows, SysUtils;
const
// These Windows-defined constants are required for use with TOSVersionInfoEx
VER_NT_WORKSTATION = 1;
VER_NT_DOMAIN_CONTROLLER = 2;
VER_NT_SERVER = 3;
PROCESSOR_ARCHITECTURE_AMD64 = 9; // x64 (AMD or Intel) *
SM_TABLETPC = 86; // Detects XP Tablet Edition
SM_MEDIACENTER = 87; // Detects XP Media Center Edition
SM_STARTER = 88; // Detects Vista Starter Edition
SM_SERVERR2 = 89; // Detects Windows Server 2003 R2
type
TWindowsPlatform = (
ospWinNT, // Windows NT platform
ospWin9x, // Windows 9x platform
ospWin32s // Win32s platform
);
var
Win32HaveExInfo: Boolean = False;
Win32ProductType: Integer = 0;
pvtProcessorArchitecture: Word = 0;
function _GetOperatingSystemArchictetureInternal: Integer;
function _GetWindowsVersionName: string;
function _GetWindowsChar: Char;
function _GetTemporaryFolder: string;
implementation
uses
dskMetricsConsts, dskMetricsCommon;
function _GetOperatingSystemArchictetureInternal: Integer;
begin
{$IFDEF CPUX64}
try
Result := 64;
except
Result := -1;
end;
{$ENDIF}
{$IFDEF CPUX86}
Result := 32;
try
if GetEnvironmentVariable('ProgramW6432') <> '' then
Result := 64;
except
Result := -1;
end;
{$ENDIF}
end;
function _GetWindowsVersion: string;
function _GetWindowsSystemWow64Folder: string;
type
{$IFDEF WARNDIRS}{$WARN UNSAFE_TYPE OFF}{$ENDIF}
// type of GetSystemWow64DirectoryFn API function
TGetSystemWow64Directory = function(lpBuffer: PChar; uSize: UINT): UINT; stdcall;
{$IFDEF WARNDIRS}{$WARN UNSAFE_TYPE ON}{$ENDIF}
var
PFolder: array[0..MAX_PATH] of Char;
GetSystemWow64Directory: TGetSystemWow64Directory;
begin
Result := '';
try
GetSystemWow64Directory := _LoadKernelFunc('GetSystemWow64DirectoryW');
if not Assigned(GetSystemWow64Directory) then
Exit;
if GetSystemWow64Directory(PFolder, MAX_PATH) <> 0 then
Result := IncludeTrailingPathDelimiter(PFolder);
except
end;
end;
function _GetWindowsSystemFolder: string;
var
PFolder: array[0..MAX_PATH] of Char;
begin
if GetSystemDirectory(PFolder, MAX_PATH) <> 0 then
Result := IncludeTrailingPathDelimiter(PFolder)
end;
begin
try
if _GetOperatingSystemArchictetureInternal = 64 then
Result := _GetExecutableVersion(_GetWindowsSystemWow64Folder + 'kernel32.dll')
else
Result := _GetExecutableVersion(_GetWindowsSystemFolder + 'kernel32.dll');
if Result = '' then
Result := '0';
except
Result := '0';
end;
end;
function _GetWindowsMajorVersion: Integer;
var
FVersion: string;
begin
try
FVersion := _GetWindowsVersion;
if FVersion <> '0' then
Result := StrToInt(FVersion[1])
else
Result := Win32MajorVersion;
except
Result := Win32MajorVersion;
end;
end;
function _GetWindowsMinorVersion: Integer;
var
FVersion: string;
begin
try
FVersion := _GetWindowsVersion;
if FVersion <> '0' then
Result := StrToInt(FVersion[3])
else
Result := Win32MinorVersion;
except
Result := Win32MinorVersion;
end;
end;
function _GetWindowsPlatform: TWindowsPlatform;
begin
Result := ospWinNT;
try
case Win32Platform of
VER_PLATFORM_WIN32_NT: Result := ospWinNT;
VER_PLATFORM_WIN32_WINDOWS: Result := ospWin9x;
VER_PLATFORM_WIN32s: Result := ospWin32s;
end;
except
Result := ospWinNT;
end;
end;
function _GetWindowsIsServer: Boolean;
begin
Result := False;
try
if Win32HaveExInfo then
Result := Win32ProductType <> VER_NT_WORKSTATION;
except
Result := False;
end;
end;
function _GetWindowsVersionName: string;
begin
Result := UNKNOWN_STR;
try
case _GetWindowsPlatform of
ospWin9x: Result := 'Windows 95/98';
ospWinNT:
begin
// NT platform OS
Result := 'Windows NT';
case _GetWindowsMajorVersion of
5:
begin
// Windows 2000 or XP
case _GetWindowsMinorVersion of
0:
Result := 'Windows 2000';
1:
Result := 'Windows XP';
2:
begin
if GetSystemMetrics(SM_SERVERR2) <> 0 then
Result := 'Windows Server 2003 R2'
else
begin
if not _GetWindowsIsServer and
(pvtProcessorArchitecture = PROCESSOR_ARCHITECTURE_AMD64) then
Result := 'Windows XP'
else
Result := 'Windows Server 2003'
end
end;
end;
end;
6:
begin
case _GetWindowsMinorVersion of
0:
if not _GetWindowsIsServer then
Result := 'Windows Vista'
else
Result := 'Windows Server 2008';
1:
if not _GetWindowsIsServer then
Result := 'Windows 7'
else
Result := 'Windows Server 2008 R2';
end;
end;
end;
end;
end;
except
Result := UNKNOWN_STR;
end;
end;
function _GetWindowsFolder: string;
var
FBuffer:array[0..MAX_PATH] of WideChar;
begin
try
GetWindowsDirectory(FBuffer,MAX_PATH);
Result := IncludeTrailingPathDelimiter(_GetLongPath(StrPas(FBuffer)));
except
Result := '';
end;
end;
function _GetWindowsChar: Char;
begin
Result := 'C';
try
Result := _GetWindowsFolder[1];
except
end;
end;
function _GetTemporaryFolder: string;
var
FTempBuffer: array [0..MAX_PATH] of Char;
begin
try
GetTempPath(MAX_PATH, FTempBuffer);
Result := IncludeTrailingPathDelimiter(_GetLongPath(StrPas(FTempBuffer)));
except
Result := '';
end;
end;
procedure InitializeEx;
{Initialise global variables with extended OS version information if possible.
}
type
// Function type of the GetProductInfo API function
TGetProductInfo = function(OSMajor, OSMinor, SPMajor, SPMinor: DWORD;
out ProductType: DWORD): BOOL; stdcall;
// Function type of the GetNativeSystemInfo and GetSystemInfo functions
TGetSystemInfo = procedure(var lpSystemInfo: TSystemInfo); stdcall;
var
OSVI: TOSVersionInfoEx; // extended OS version info structure
POSVI: POSVersionInfo; // pointer to OS version info structure
GetSystemInfoFn: TGetSystemInfo; // fn used to get system info
SI: TSystemInfo; // structure from GetSystemInfo API call
begin
// Clear the structure
FillChar(OSVI, SizeOf(OSVI), 0);
try
// Get pointer to structure of non-extended type (GetVersionEx
// requires a non-extended structure and we need this pointer to get
// it to accept our extended structure!!)
{$IFDEF WARNDIRS}{$WARN UNSAFE_CODE OFF}{$ENDIF}
{$TYPEDADDRESS OFF}
POSVI := @OSVI;
{$TYPEDADDRESS ON}
// Try to get exended information
OSVI.dwOSVersionInfoSize := SizeOf(TOSVersionInfoEx);
Win32HaveExInfo := GetVersionEx(POSVI^);
{$IFDEF WARNDIRS}{$WARN UNSAFE_CODE ON}{$ENDIF}
if Win32HaveExInfo then
Win32ProductType := OSVI.wProductType;
// Get processor architecture
// prefer to use GetNativeSystemInfo() API call if available, otherwise use
// GetSystemInfo()
GetSystemInfoFn := _LoadKernelFunc('GetNativeSystemInfo');
if not Assigned(GetSystemInfoFn) then
GetSystemInfoFn := Windows.GetSystemInfo;
GetSystemInfoFn(SI);
pvtProcessorArchitecture := SI.wProcessorArchitecture;
except
end;
end;
initialization
InitializeEx;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Classes,
Vcl.Graphics, Vcl.Imaging.Jpeg, Vcl.Controls, Vcl.Forms,
//GLS
GLScene, GLVectorFileObjects, GLObjects, GLWin32Viewer,
GLFile3ds, GLCadencer, GLGeomObjects, GLVectorGeometry,
GLShadowPlane, GLParticleFX, GLPerlinPFX, GLCrossPlatform, GLCoordinates,
GLBaseClasses, GLUtils;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
GLCamera1: TGLCamera;
GLDummyCube1: TGLDummyCube;
GLLightSource1: TGLLightSource;
GLFreeForm1: TGLFreeForm;
GLCadencer1: TGLCadencer;
GLCylinder1: TGLCylinder;
GLCylinder2: TGLCylinder;
GLShadowPlane1: TGLShadowPlane;
GLPerlinPFXManager1: TGLPerlinPFXManager;
GLDummyCube3: TGLDummyCube;
GLParticleFXRenderer1: TGLParticleFXRenderer;
GLPolygonPFXManager1: TGLPolygonPFXManager;
GLParticleFXRenderer2: TGLParticleFXRenderer;
procedure FormActivate(Sender: TObject);
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure GLSceneViewer1DblClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
mx, my : Integer;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormActivate(Sender: TObject);
begin
SetGLSceneMediaDir;
GLFreeForm1.LoadFromFile('beer.3ds');
GLFreeForm1.Material.Texture.Image.LoadFromFile('clouds.jpg');
GLShadowPlane1.Material.Texture.Image.LoadFromFile('ashwood.jpg');
GetOrCreateSourcePFX(GLDummyCube3).Burst(0, 150);
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
begin
GLCamera1.MoveAroundTarget(0, 10*deltatime);
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if ssLeft in Shift then
GLCamera1.MoveAroundTarget(my-y, mx-x);
mx:=x; my:=y;
end;
procedure TForm1.GLSceneViewer1DblClick(Sender: TObject);
begin
GLCadencer1.Enabled:=not GLCadencer1.Enabled;
end;
end.
|
{
This unit is part of the LaKraven Studios Standard Library (LKSL).
Copyright (C) 2011, LaKraven Studios Ltd.
Copyright Protection Packet(s): LKSL001
--------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and
limitations under the License.
--------------------------------------------------------------------
Unit: LKSL.Smart.Interfaces.pas
Created: 16th March 2012
Modified: 16th March 2012
Changelog:
16th March 2012
- Added TInterfacedPersistent
}
unit LKSL.Smart.Interfaces;
interface
{$I LKSL.inc}
uses
{$IFDEF DELPHIXE2}
System.Classes;
{$ELSE}
Classes;
{$ENDIF}
type
{
TInterfacedPersistent
- Basically a base object for non-reference-counted Interfaced Objects.
Makes Interfaced Objects behave like Persistent Objects, so you need to
call .Free MANUALLY (great for ensuring references can only be freed
when YOU want them to be (and not when Delphi's MM thinks they should)
}
{$REGION 'TInterfacedPersistent'}
TInterfacedPersistent = class(TPersistent, IInterface)
protected
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
end;
{$ENDREGION}
implementation
{$REGION 'TInterfacedPersistent'}
{ TInterfacedPersistent }
function TInterfacedPersistent.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if GetInterface(IID, Obj) then
Result := 0
else
Result := E_NOINTERFACE;
end;
function TInterfacedPersistent._AddRef: Integer;
begin
Result := 0;
end;
function TInterfacedPersistent._Release: Integer;
begin
Result := 0;
end;
{$ENDREGION}
end.
|
{$apptype windows}
program spectrum_analyzer;
uses graphAbc;
const
screen_width = 1000; {ширина графического окна}
screen_height = 500; {высота графического окна}
margin_x = 30;
margin_y = 30;
zero_x = margin_x; {начальная координа по х}
zero_y = screen_height - margin_y; {начальная координа по у}
length_x = screen_width - 2 * margin_x; {длина оси х}
length_y = screen_height - 2 * margin_y; {длина оси у}
max_data = 4096;
data_size = 100;
max_level = 1000;
type
input_array = array[1..max_data] of word;
output_array = array[1..max_data] of real;
var
input_data:input_array;
{Рисование координатных осей}
procedure DrawAxis;
begin
line(zero_x, zero_y, zero_x + length_x, zero_y);
line(zero_x, zero_y, zero_x, zero_y - length_y);
end;
{Рисование одной полосы спектра}
procedure DrawSpectrumBar (index, width:integer; value:real);
begin
FillRect(zero_x + (index - 1) * width, zero_y, zero_x + width * index - 1, zero_y - round(length_y * value));
end;
{Процедура преобразования сигнала с фиксированной точкой в сигнал с плавующей точкой}
procedure PrepareData(var src_data:input_array; var dst_data:output_array; count:integer; max_level:word);
var i:integer;
begin
for i := 1 to count do
begin
dst_data[i] := src_data[i] / max_level;
end;
end;
procedure fill_data(var data:input_array; size:integer; max_value:word);
var
i:integer;
begin
for i:= 1 to size do
data[i] := random(max_value);
end;
{Процедура рисования полос спектра}
procedure DrawSpectrum (var data:input_array; count:integer; max_level:word; c:color);
var
column_width, i:integer;
out_data:output_array;
begin
Window.Clear;
DrawAxis;
{TODO обработать случай, когда элементов массива больше, чем доступных точек}
PrepareData(data, out_data, count, max_level);
column_width := length_x div count;
SetBrushColor(c);
SetPenWidth(0);
for i := 1 to count do
begin
DrawSpectrumBar(i, column_width, out_data[i]);
end;
Redraw;
end;
function CheckData(data: input_array; data_size: integer):boolean;
var
fl:boolean;
i:integer;
begin
fl := true;
i := 1;
while (i < data_size) and fl do
begin
if data[i] > data[i + 1] then
fl := false;
inc(i);
end;
CheckData := fl;
end;
{procedure SelectionSort(var data: input_array; data_size: integer);
var
i, j, min_index:integer;
min_value:word;
begin
for i := 1 to data_size do
begin
min_index := i;
min_value := data[i];
for j := i + 1 to data_size do
begin
if data[j] < min_value then
begin
min_index := j;
min_value := data[min_index];
end;
end;
DrawSpectrum(data, data_size, max_level, clBlack);
data[min_index] := data[i];
data[i] := min_value;
end;
end;}
procedure SelectionSort (var a:input_array; n:integer);
var
x: integer;
i,j,k: integer;
begin
for i := 1 to N - 1 do
begin
k := i;
x := a[i];
for j := i + 1 to N do
begin
if a[j] < x then
begin
k := j;
x := a[k];
DrawSpectrum(a, n, max_level, clBlack);
end;
end;
a[k] := a[i];
a[i] := x;
end;
end;
{Процедура инициализации}
procedure Setup;
begin
SetWindowCaption('Сортировка выбором (' + IntToStr(data_size) + ' элементов)');
SetWindowSize(screen_width, screen_height);
CenterWindow;
LockDrawing;
end;
begin
Setup;
fill_data(input_data, data_size, max_level);
SelectionSort(input_data, data_size);
if CheckData(input_data, data_size) then
DrawSpectrum(input_data, data_size, max_level, clGreen)
else
DrawSpectrum(input_data, data_size, max_level, clRed);
end. |
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm1 = class(TForm)
pathTEdit: TEdit;
OpenDialog1: TOpenDialog;
runBtn: TButton;
GroupBox1: TGroupBox;
RadioButton1: TRadioButton;
RadioButton2: TRadioButton;
logMemo: TMemo;
openBtn: TButton;
procedure FormCreate(Sender: TObject);
procedure openBtnClick(Sender: TObject);
procedure runBtnClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
OpenDir : String;
implementation
uses
TRegFunctions, strConsts, CreateProcFunctions;
{$R *.dfm}
///////////////////////////////FormCreate////////////////////////////////////
procedure TForm1.FormCreate(Sender: TObject);
begin
if (regKeyExists(LAST_PATH)) then begin
pathTEdit.Text := regRead(LAST_PATH);
OpenDir := pathTEdit.Text;
end
else
begin
openDialog1.InitialDir := DEFAULT_DIRECTORY;
end;
end;
///////////////////////////////openBtnClick////////////////////////////////////
procedure TForm1.openBtnClick(Sender: TObject);
var
pathText : String;
begin
if (OpenDialog1.Execute()) then
begin
pathText := OpenDialog1.FileName;
pathTEdit.Text := pathText;
logMemo.Lines.Add(String.Format('Added new path: %s',[pathText]));
OpenDir := pathTEdit.Text;
regWrite(pathText);
end;
end;
///////////////////////////////runBtnClick////////////////////////////////////
procedure TForm1.runBtnClick(Sender: TObject);
begin
if (RadioButton1.Checked) then createProc(OpenDir)
else
begin
shellExProc(OpenDir, Self);
end;
end;
end.
|
unit zpipe;
(*************************************************************************
DESCRIPTION : zlib's inflate() and deflate() made easy
REQUIREMENTS : TP7, D1-D7/9/10, FPC, VP
EXTERNAL DATA : ---
MEMORY USAGE : zlib memory + (2 buffers on stack)
DISPLAY MODE : ---
REFERENCES : zpipe.c: example of proper use of zlib's inflate() and
deflate(), Version 1.2, 9 Nov. 2004 Mark Adler
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 08.04.05 WEhrhardt Pascal translation of zpipe.c
0.11 03.05.05 we separated unit and test program
0.12 13.07.08 we avoid buggy Delphi eof for large files
**************************************************************************)
{$i-,x+}
interface
uses zlibh, zlib;
function def(var source, dest: file; level: int): int;
{-Compress from file source to file dest until EOF on source.
def() returns Z_OK on success, Z_MEM_ERROR if memory could not be
allocated for processing, Z_STREAM_ERROR if an invalid compression
level is supplied, Z_VERSION_ERROR if the version of zlib.h and the
version of the library linked do not match, or Z_ERRNO if there is
an error reading or writing the files.}
function inf(var source, dest: file): int;
{-Decompress from file source to file dest until stream ends or EOF.
inf() returns Z_OK on success, Z_MEM_ERROR if memory could not be
allocated for processing, Z_DATA_ERROR if the deflate data is
invalid or incomplete, Z_VERSION_ERROR if the version of zlib.h and
the version of the library linked do not match, or Z_ERRNO if there
is an error reading or writing the files.}
implementation
{buffer size for Inflate/Deflate buffers}
const
CHUNK=$1000;
{---------------------------------------------------------------------------}
function def(var source, dest: file; level: int): int;
{-Compress from file source to file dest until EOF on source.
def() returns Z_OK on success, Z_MEM_ERROR if memory could not be
allocated for processing, Z_STREAM_ERROR if an invalid compression
level is supplied, Z_VERSION_ERROR if the version of zlib.h and the
version of the library linked do not match, or Z_ERRNO if there is
an error reading or writing the files.}
var
ret, flush: int;
have,n: unsigned;
strm: z_stream;
inb, outb: array[0..CHUNK-1] of byte;
begin
{allocate deflate state}
strm.zalloc := nil;
strm.zfree := nil;
strm.opaque := nil;
ret := deflateInit(strm, level);
if ret<>Z_OK then begin
def := ret;
exit;
end;
{compress until end of file}
repeat
blockread(source, inb, CHUNK, strm.avail_in);
if IOResult<>0 then begin
deflateEnd(strm);
def := Z_ERRNO;
exit;
end;
{0.12: avoid buggy Delphi eof for large files and use}
{strm.avail_in=0 for eof(source)}
if strm.avail_in=0 then flush := Z_FINISH else flush := Z_NO_FLUSH;
strm.next_in := pBytef(@inb);
{run deflate() on input until output buffer not full, finish
compression if all of source has been read in}
repeat
strm.avail_out := CHUNK;
strm.next_out := pBytef(@outb);
deflate(strm, flush); {no bad return value}
{assert(ret != Z_STREAM_ERROR); /* state not clobbered */}
have := CHUNK - strm.avail_out;
blockwrite(dest, outb, have, n);
if (IOresult<>0) or (have<>n) then begin
deflateEnd(strm);
def := Z_ERRNO;
exit;
end;
until strm.avail_out<>0;
{assert(strm.avail_in == 0); /* all input will be used */}
{done when last data in file processed}
until flush=Z_FINISH;
{assert(ret == Z_STREAM_END); /* stream will be complete */}
{clean up and return}
deflateEnd(strm);
def := Z_OK;
end;
{---------------------------------------------------------------------------}
function inf(var source, dest: file): int;
{-Decompress from file source to file dest until stream ends or EOF.
inf() returns Z_OK on success, Z_MEM_ERROR if memory could not be
allocated for processing, Z_DATA_ERROR if the deflate data is
invalid or incomplete, Z_VERSION_ERROR if the version of zlib.h and
the version of the library linked do not match, or Z_ERRNO if there
is an error reading or writing the files.}
var
ret: int;
have,n: unsigned;
strm: z_stream;
inb, outb: array[0..CHUNK-1] of byte;
begin
{allocate inflate state}
strm.zalloc := nil;
strm.zfree := nil;
strm.opaque := nil;
strm.avail_in := 0;
strm.next_in := nil;
ret := inflateInit(strm);
if ret<>Z_OK then begin
inf := ret;
exit;
end;
{decompress until deflate stream ends or end of file}
repeat
blockread(source, inb, chunk, strm.avail_in);
if IOResult<>0 then begin
inflateEnd(strm);
inf := Z_ERRNO;
exit;
end;
if strm.avail_in=0 then break;
strm.next_in := pBytef(@inb);
{run inflate() on input until output buffer not full}
repeat
strm.avail_out := CHUNK;
strm.next_out := pBytef(@outb);
ret := inflate(strm, Z_NO_FLUSH);
{assert(ret != Z_STREAM_ERROR); /* state not clobbered */}
case ret of
Z_NEED_DICT: begin
inf := Z_DATA_ERROR;
inflateEnd(strm);
exit;
end;
Z_MEM_ERROR,
Z_DATA_ERROR: begin
inflateEnd(strm);
inf := ret;
exit;
end;
end;
have := CHUNK - strm.avail_out;
blockwrite(dest, outb, have, n);
if (IOresult<>0) or (have<>n) then begin
inflateEnd(strm);
inf := Z_ERRNO;
exit;
end;
until strm.avail_out<>0;
{assert(strm.avail_in == 0); /* all input will be used */}
{done when inflate() says it's done}
until ret=Z_STREAM_END;
{clean up and return}
inflateEnd(strm);
if ret=Z_STREAM_END then inf := Z_OK
else inf := Z_DATA_ERROR;
end;
end.
|
{
ID: a2peter1
PROG: milk3
LANG: PASCAL
}
{$B-,I-,Q-,R-,S-}
const
problem = 'milk3';
MaxC = 20;
var
A,B,C,i,j : longint;
mark : array[0..MaxC,0..MaxC] of boolean;
procedure find(j,k: longint);
var i : longint;
begin
if mark[j,k] then exit;
mark[j,k] := true;
i := C - j - k;
if A < j + i then find(j + i - A,k) else find(0,k);
if A < k + i then find(j,k + i - A) else find(j,0);
if B < j + i then find(B,k) else find(j + i,k);
if B < k + j then find(B,k + j - B) else find(k + j,0);
if C < k + j then find(k + j - C,C) else find(0,k + j);
if C < k + i then find(j,C) else find(j,k + i);
end;{find}
begin
assign(input,problem + '.in'); reset(input);
assign(output,problem + '.out'); rewrite(output);
readln(A,B,C);
find(0,C);
j := 0;
for i := 0 to C do
if mark[C - i,i] then inc(j);
for i := 0 to C do
if mark[C - i,i] then
begin
dec(j);
if j = 0 then writeln(i)
else write(i,' ');
end;{then}
close(output);
end.{main}
|
unit MainU;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Threading, Vcl.StdCtrls, Vcl.ExtCtrls,
Winapi.Hooks;
type
TFormMain = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
FHook: THook;
public
{ Public declarations }
end;
var
FormMain: TFormMain;
implementation
{$R *.dfm}
procedure TFormMain.Button1Click(Sender: TObject);
const
Captions: array [Boolean] of string = ('Decativate', 'Active');
begin
FHook.Active := not FHook.Active;
Button1.Caption := Captions[not FHook.Active];
end;
procedure TFormMain.FormCreate(Sender: TObject);
begin
FHook := THookInstance<TLowLevelKeyboardHook>.CreateHook(Self);
FHook.OnPreExecute := procedure(Hook: THook; var HookMsg: THookMessage)
var
LLKeyBoardHook: TLowLevelKeyboardHook;
ScanCode: integer;
begin
LLKeyBoardHook := TLowLevelKeyboardHook(Hook);
if LLKeyBoardHook.LowLevelKeyStates.KeyState <> ksKeyDown then
exit;
ScanCode := LLKeyBoardHook.KeyName.ScanCode;
if not(ScanCode in [VK_NUMPAD0 .. VK_NUMPAD9, VK_0 .. VK_9]) then
begin
Caption := 'Got ya! Key [' + LLKeyBoardHook.KeyName.KeyExtName + '] blocked.';
HookMsg.Result := 1;
end
else
Caption := '';
end;
end;
end.
|
unit RoomsList;
interface
uses
Classes, Contnrs, StdCtrls, SysUtils,
Room, CommonUtils;
type
ERoomNotFounded = class(Exception);
TRoomsList = class(TObjectList)
constructor Create;
public
procedure AddRoom(RoomName: string);
procedure RemoveRoom(RoomName: string);
function IsRoomExists(RoomName: string) : boolean;
function GetRoomByName(RoomName: string) : TRoom;
function View : TListBox;
procedure SetView(var ListBox: TListBox);
// Удалить комнату, если она пустая
function RemoveEmpty(Room: TRoom) : boolean;
// Синхронизация с отображением
procedure Sync;
private
dView: TListBox;
end;
implementation
{ TRoomsLists }
constructor TRoomsList.Create;
begin
Inherited;
end;
procedure TRoomsList.Sync;
var
i: integer;
Room: TRoom;
buff: TStrings;
begin
buff := TStringList.Create;
for i := 0 to Self.Count - 1 do
begin
Room := Self.Items[i] as TRoom;
buff.Add(Room.RoomName);
end;
AlphabeticSort(buff);
dView.Items := buff;
end;
procedure TRoomsList.AddRoom(RoomName: string);
var
Room: TRoom;
begin
if ValidateRoomName(RoomName) then
if not IsRoomExists(RoomName) then
begin
Room := TRoom.Create(RoomName);
Add(Room);
Sync;
end
else
raise ERoomExists.Create('Room is already exists: ' + RoomName)
else
raise EIncorrectRoomName.Create('Incorrect room name: ' + RoomName);
end;
procedure TRoomsList.RemoveRoom(RoomName: string);
var
i: integer;
tmpRoom: TRoom;
begin
for i := 0 to Count - 1 do
begin
tmpRoom := Items[i] as TRoom;
if tmpRoom.dRoomName = RoomName then
begin
Delete(i);
Break;
end;
end;
Sync;
end;
function TRoomsList.IsRoomExists(RoomName: string) : boolean;
var
flag: boolean;
i: integer;
tmpRoom: TRoom;
begin
flag := False;
for i := 0 to Count - 1 do
begin
tmpRoom := Items[i] as TRoom;
if tmpRoom.dRoomName = RoomName then
begin
flag := True;
Break;
end;
end;
Result := flag;
end;
function TRoomsList.GetRoomByName(RoomName: string) : TRoom;
var
i: integer;
tmpRoom: TRoom;
begin
for i := 0 to Count - 1 do
begin
tmpRoom := Items[i] as TRoom;
if tmpRoom.dRoomName = RoomName then
begin
Result := tmpRoom;
Exit;
end;
end;
Result := nil;
end;
function TRoomsList.View;
begin
Result := dView;
end;
procedure TRoomsList.SetView(var ListBox: TListBox);
begin
dView := ListBox;
end;
function TRoomsList.RemoveEmpty(Room: TRoom) : boolean;
var
i: integer;
begin
Result := False;
i := IndexOf(Room);
if i <> -1 then
if Room.dUsers.Count = 0 then
begin
Delete(i);
Sync;
Result := True;
end;
end;
end.
|
{-----------------------------------------------------------------------------
Author: Roman Fadeyev
Purpose: Специальный класc, реализующий заглушку для брокера, используется
тестером для эмуляции торгов по истории
History:
-----------------------------------------------------------------------------}
unit FC.Trade.Brokers.Stub.Broker;
{$I Compiler.inc}
interface
uses Windows, Classes, BaseUtils, SysUtils,
FC.Definitions,StockChart.Definitions,
FC.Trade.Brokers.BrokerBase,
FC.Trade.Brokers.Stub.Order,Contnrs;
type
TBrokerGettingPriceType = (gptMedian,gptPessimistic,gptUltraPessimistic, gptOptimistic, gptUltraOptimistic,gptClose,gptOpen);
const
TraderGetPriceTypeNames : array [TBrokerGettingPriceType] of string =
('Median','Pessimistic','Ultra Pessimistic', 'Optimistic', 'Ultra Optimistic','Close','Open');
type
TStockBroker = class (TStockBrokerBase,IStockBroker,IStockBrokerStubSupport)
private
FDeposit: TStockRealNumber;
FSpread : TStockRealNumber;
FSymbol : TStockSymbolInfo;
FStopLevel : integer; //Минимальный отступ от маркет-цены при установке SL, TP или PendingOrders
FRealTime : boolean;
FMinutes : ISCInputDataCollection;
FTickCacheStart,FTickCacheStop: TDateTime;
FEmulateTickInMinute : boolean;
FGettingPriceType : TBrokerGettingPriceType;
FCurrentMinuteTicks: IStockTickCollectionWriteable;
FCurrentTickIndex: integer;
FCurrentTimeIndex: integer;
FCurrentBid,FCurrentAsk: TStockRealNumber;
FCurrentTime : TDateTime;
FOrders : TList;
procedure SetGettingPriceType(const Value: TBrokerGettingPriceType);
procedure AddOrder(aOrder: TStockOrder);
procedure DeleteOrder(index: integer);
procedure ClearOrders;
function GetOrder(index:integer): TStockOrder; inline;
public
//IStockObjct
//from IStockBroker
//Идентификация Account
function GetAccount: string;
function GetBalance: TStockRealNumber;
function GetEquity: TStockRealNumber;
function GetCurrentPrice(const aSymbol: string; aKind: TStockBrokerPriceKind): TStockRealNumber;
function GetCurrentTime: TDateTime;
function GetMargin: integer;
function IsRealTime: boolean;
//Получение информации о параметрах торговли
function GetMarketInfo(const aSymbol: string):TStockMarketInfo;
//Создать пустой ордер
function CreateOrder(aTrader: IStockTrader): IStockOrder;
//Дать все ордера у брокера (закрытые, открытые...)
function GetAllOrders: IStockOrderCollection;
//Дать все текущие открытые у брокера ордера
function GetOpenedOrders: IStockOrderCollection;
//Дать все отложенные ордера (стоповые и лимитные)
function GetPendingOrders: IStockOrderCollection;
//Кол-во точек после запятой
function GetPricePrecision(const aSymbol: string) : integer; override;
//Коэффициент трансформации из точки в цену, для EURUSD=10000, для USDJPY=100
function GetPricesInPoint(const aSymbol: string): integer; override;
//end of IStockBroker
//from IBrokerStubExtension
procedure OnModifyOrder(const aOrder: IStockOrder; const aModifyEventArgs: TStockOrderModifyEventArgs);
//end of IBrokerStubExtension
procedure SetDeposit(const aValue: TStockRealNumber);
procedure SetSpread(const aValue: integer);
procedure SetStopLevel(const aValue: integer);
procedure SetParams(const aSymbol:TStockSymbolInfo; const a1MinBarCollection: ISCInputDataCollection; const aStart,aStop: TDateTime; aEmulateTickInMinute: boolean);
procedure Reset;
procedure StartTicking;
function Tick: boolean;
procedure AfterTick;
property CurrentTime: TDateTime read GetCurrentTime;
property CurrentBidPrice: TStockRealNumber read FCurrentBid;
property CurrentAskPrice: TStockRealNumber read FCurrentAsk;
property GettingPriceType : TBrokerGettingPriceType read FGettingPriceType write SetGettingPriceType;
property RealTime: boolean read FRealTime write FRealTime;
constructor Create;
destructor Destroy; override;
end;
implementation
uses Math,FC.DataUtils,FC.Trade.OrderCollection, FC.StockData.StockTickCollection,FC.Singletons;
{ TStockBroker }
procedure TStockBroker.AfterTick;
begin
RaiseOnNewDataEvent(FSymbol.Name);
end;
procedure TStockBroker.ClearOrders;
begin
while FOrders.Count>0 do
DeleteOrder(0);
end;
constructor TStockBroker.Create;
begin
inherited Create;
FCurrentMinuteTicks:=TStockTickCollection.Create;
FGettingPriceType:=gptPessimistic;
FOrders:=TList.Create;
end;
destructor TStockBroker.Destroy;
begin
inherited;
FMinutes:=nil;;
FCurrentMinuteTicks:=nil;
ClearOrders;
end;
function TStockBroker.CreateOrder(aTrader: IStockTrader): IStockOrder;
var
aOrder: TStockOrder;
begin
aOrder:=TStockOrder.Create(self,aTrader);
AddOrder(aOrder);
RaiseOnNewOrderEvent(aOrder);
result:=aOrder;
end;
procedure TStockBroker.DeleteOrder(index: integer);
begin
TStockOrder(FOrders[index]).Dispose;
IInterface(TStockOrder(FOrders[index]))._Release;
FOrders.Delete(index);
end;
function TStockBroker.GetBalance: TStockRealNumber;
begin
result:=FDeposit;
end;
function TStockBroker.GetEquity: TStockRealNumber;
var
i: integer;
aDelta : TStockRealNumber;
aOrder: TStockOrder;
begin
aDelta:=0;
for i := 0 to FOrders.Count - 1 do
begin
aOrder:=GetOrder(i);
if aOrder.GetState=osOpened then
aDelta:=aDelta+PriceToMoney(aOrder.GetSymbol,aOrder.GetCurrentProfit,aOrder.GetLots);
end;
result:=aDelta+FDeposit;
end;
procedure TStockBroker.SetDeposit(const aValue: TStockRealNumber);
begin
FDeposit:=aValue;
end;
procedure TStockBroker.SetSpread(const aValue: integer);
begin
FSpread:=PointToPrice(FSymbol.Name,aValue);
end;
procedure TStockBroker.SetStopLevel(const aValue: integer);
begin
FStopLevel:=aValue;
end;
function TStockBroker.GetCurrentPrice(const aSymbol: string; aKind: TStockBrokerPriceKind): TStockRealNumber;
begin
if not AnsiSameText(aSymbol,FSymbol.Name) then
raise EStockError.Create('Unsupported symbol');
if aKind=bpkAsk then
result:=FCurrentAsk
else
result:=FCurrentBid;
Assert(result>0);
end;
procedure TStockBroker.OnModifyOrder(const aOrder: IStockOrder; const aModifyEventArgs: TStockOrderModifyEventArgs);
var
aProfitMoney : TStockRealNumber;
begin
if aModifyEventArgs.ModifyType=omtClose then
begin
aProfitMoney:=PriceToMoney(aOrder.GetSymbol,aOrder.GetCurrentProfit,aOrder.GetLots);
FDeposit:=FDeposit+aProfitMoney;
end;
RaiseOnModifyOrderEvent(aOrder,aModifyEventArgs);
end;
procedure TStockBroker.Reset;
begin
ClearOrders;
end;
procedure TStockBroker.AddOrder(aOrder: TStockOrder);
begin
IInterface(aOrder)._AddRef;
FOrders.Add(aOrder);
end;
procedure TStockBroker.SetParams(const aSymbol:TStockSymbolInfo; const a1MinBarCollection: ISCInputDataCollection; const aStart,aStop: TDateTime; aEmulateTickInMinute: boolean);
begin
FSymbol:=aSymbol;
FMinutes:=a1MinBarCollection;
FTickCacheStart:=aStart;
FTickCacheStop:=aStop;
FEmulateTickInMinute:=aEmulateTickInMinute;
end;
procedure TStockBroker.SetGettingPriceType(const Value: TBrokerGettingPriceType);
begin
if FGettingPriceType<>Value then
begin
FGettingPriceType := Value;
FTickCacheStart:=-1;
FTickCacheStop:=-1;
end;
end;
function TStockBroker.Tick: boolean;
var
i: integer;
aResultAsk: TStockRealNumber;
aResultBid: TStockRealNumber;
aDataLow,aDataHigh: TStockRealNumber;
begin
result:=false;
//Если режим тиков внутри минутки, и при этом в этой минутке еще есть
//тики, берем их
inc(FCurrentTickIndex);
if FEmulateTickInMinute and (FCurrentTickIndex<FCurrentMinuteTicks.Count) then
begin
FCurrentBid:=FCurrentMinuteTicks.GetValue(FCurrentTickIndex);
FCurrentAsk:=FCurrentBid+FSpread;
FCurrentTime:=FCurrentMinuteTicks.GetDateTime(FCurrentTickIndex);
for i:=0 to FOrders.Count-1 do
GetOrder(i).Tick;
result:=true;
exit;
end;
inc(FCurrentTimeIndex);
if FCurrentTimeIndex>=FMinutes.Count then
exit;
FCurrentTime:=FMinutes.DirectGetItem_DataDateTime(FCurrentTimeIndex);
if FCurrentTime>FTickCacheStop then
exit;
if not FEmulateTickInMinute then
begin
aDataLow:=FMinutes.DirectGetItem_DataLow(FCurrentTimeIndex);
aDataHigh:=FMinutes.DirectGetItem_DataHigh(FCurrentTimeIndex);
case FGettingPriceType of
gptMedian: begin
aResultAsk:=(aDataHigh+aDataLow)/2;
aResultBid:=aResultAsk;
end;
gptPessimistic: begin
aResultAsk:=Max(aDataHigh,aDataLow)-(aDataHigh-aDataLow)/4;
aResultBid:=Min(aDataHigh,aDataLow)+(aDataHigh-aDataLow)/4;
end;
gptUltraPessimistic: begin
aResultAsk:=Max(aDataHigh,aDataLow);
aResultBid:=Min(aDataHigh,aDataLow);
end;
gptOptimistic: begin
aResultBid:=Max(aDataHigh,aDataLow)-(aDataHigh-aDataLow)/4;
aResultAsk:=Min(aDataHigh,aDataLow)+(aDataHigh-aDataLow)/4;
end;
gptUltraOptimistic: begin
aResultBid:=Max(aDataHigh,aDataLow);
aResultAsk:=Min(aDataHigh,aDataLow);
end;
gptClose: begin
aResultBid:=FMinutes.DirectGetItem_DataClose(FCurrentTimeIndex);
aResultAsk:=aResultBid;
end;
gptOpen: begin
aResultBid:=FMinutes.DirectGetItem_DataOpen(FCurrentTimeIndex);
aResultAsk:=aResultBid;
end;
else
raise EAlgoError.Create;
end;
//07.08.06 Так как общепринятым является хранение котировок по Bid, то мы добавляем Spread к Ask
FCurrentAsk:=RoundPrice(FSymbol.Name, aResultAsk+FSpread);
FCurrentBid:=RoundPrice(FSymbol.Name, aResultBid);
end
//Эмулируем тики
else begin
FCurrentMinuteTicks.Clear;
TStockDataUtils.GenerateTicksInBar(FMinutes,FCurrentTimeIndex,FCurrentMinuteTicks);
Assert(FCurrentMinuteTicks.Count>0);
FCurrentTickIndex:=0;
FCurrentTime:=FCurrentMinuteTicks.GetDateTime(FCurrentTickIndex);
FCurrentBid:=RoundPrice(FSymbol.Name,FCurrentMinuteTicks.GetValue(FCurrentTickIndex));
FCurrentAsk:=RoundPrice(FSymbol.Name,FCurrentBid+FSpread);
end;
for i:=0 to FOrders.Count-1 do
GetOrder(i).Tick;
result:=true;
end;
procedure TStockBroker.StartTicking;
begin
if FMinutes.Count=0 then
FCurrentTimeIndex:=0
else begin
//Находим начальную дату
if FTickCacheStart<=FMinutes.DirectGetItem_DataDateTime(0) then
FCurrentTimeIndex:=0
else
FCurrentTimeIndex:=FMinutes.FindBestMatched(FTickCacheStart);
if FCurrentTimeIndex=-1 then
FCurrentTimeIndex:=FMinutes.Count;
end;
dec(FCurrentTimeIndex);
FCurrentMinuteTicks.Clear;
FCurrentTickIndex:=0;
RaiseOnStartEvent;
end;
function TStockBroker.GetMargin: integer;
begin
result:=100;
end;
function TStockBroker.GetMarketInfo(const aSymbol: string): TStockMarketInfo;
begin
FillChar(result,sizeof(result),0);
result.Spread:=PriceToPoint(FSymbol.Name,FSpread);
result.StopLevel:=FStopLevel;
end;
function TStockBroker.GetOpenedOrders: IStockOrderCollection;
var
aCollection: TStockOrderCollection;
i: integer;
begin
aCollection:=TStockOrderCollection.Create();
for i := 0 to FOrders.Count - 1 do
if GetOrder(i).GetState=osOpened then
aCollection.Add(GetOrder(i));
result:=aCollection;
end;
function TStockBroker.GetPendingOrders: IStockOrderCollection;
var
aCollection: TStockOrderCollection;
i: integer;
begin
aCollection:=TStockOrderCollection.Create();
for i := 0 to FOrders.Count - 1 do
if (GetOrder(i).GetState=osPending) then
aCollection.Add(GetOrder(i));
result:=aCollection;
end;
function TStockBroker.GetPricePrecision(const aSymbol: string): integer;
begin
result:=FSymbol.Digits;
end;
function TStockBroker.GetPricesInPoint(const aSymbol: string): integer;
begin
result:=Round(1/FSymbol.Point);
end;
function TStockBroker.IsRealTime: boolean;
begin
result:=FRealTime;
end;
function TStockBroker.GetAccount: string;
begin
result:='';
end;
function TStockBroker.GetAllOrders: IStockOrderCollection;
var
aCollection: TStockOrderCollection;
i: integer;
begin
aCollection:=TStockOrderCollection.Create();
for i := 0 to FOrders.Count - 1 do
aCollection.Add(GetOrder(i));
result:=aCollection;
end;
function TStockBroker.GetOrder(index: integer): TStockOrder;
begin
result:=FOrders[index];
end;
function TStockBroker.GetCurrentTime: TDateTime;
begin
result:=FCurrentTime;
end;
end.
|
{ Routines for interfacing the CAN library to custom application-supplied
* drivers.
*
* The purpose of the CAN library is to provide generic routines for
* manipulating CAN frames, and to provide a device-independent CAN frame I/O
* interface.
*
* Drivers for some known CAN I/O devices are built into the CAN library.
* These can never include all possible CAN I/O means. The routines in this
* module provide a mechanism for applications to supply the minimum necessary
* device-dependent routines themselves, and then be able to use the normal
* CAN library device-independent interface for sending and receiving CAN
* frames.
*
* CAN_OPEN_CUSTOM is used to set up a CAN library use state with application
* supplied low level drivers for CAN frame I/O. CAN_OPEN_CUSTOM initializes
* the CAN library use state, then calls the application-specific open routine
* supplied to it.
*
* The CAN library use state is initialized to the following state before the
* custom open routine is called:
*
* - MEM_P is pointing to a memory context that is private to this CAN
* library use state.
*
* - DAT_P, SEND_P, RECV_P, and CLOSE_P are all initialized to NIL.
*
* - DEV is initialized to empty and unused. DEV.NAME and DEV.PATH are
* empty strings, all the SPEC bytes are initialized to 0, and NSPEC is
* set to 0. It is intended that custom drivers not use DEV.
*
* - The input queue (INQ) is set up and initialized to empty.
*
* The responsibilities of the custom open routine are:
*
* - Set CL.SEND_P pointing to the device-specific CAN frame send routine, if
* the interface is capable of sending CAN frames. If not, leave SEND_P
* NIL. In that case, CAN_SEND will silently ignore requests to send
* frames.
*
* - Set CL.RECV_P pointing to the device-specific CAN frame receiving
* routine, if the interface is capable of receiving CAN frames and the CAN
* library code needs to specifically ask for each received frame.
*
* If not, leave RECV_P NIL. In that case, it is assumed that the driver
* will automatically push received frames onto the input queue without
* explicit action by the CAN library to cause it. If no frames are ever
* pushed onto the queue, then no frames will be received at the
* application level.
*
* - Set CL.CLOSE_P pointing to a custom close routine, if one is needed.
* When such a routine is referenced, it will be called by CAN_CLOSE before
* any CAN library memory is deallocated. A custom close routine is only
* required if additional actions need to be taken to deallocate system
* resources other than those built into the CAN library use, and that are
* not deallocated by deleting the memory context pointed to by CL.MEM_P.
* CAN_CLOSE always deallocates the resources built into the CAN library
* use state, which includes deleting the CL.MEM_P memory context as the
* last step.
*
* - CL.DAT_P can be used to provide use-specific persistant state between
* calls to the low level driver routines. DAT_P is a generic pointer left
* for exclusive use by driver routines. It should point to memory that is
* allocated under the CL.MEM_P^ context. This causes such memory to be
* automatically deallocated when the CAN library use state is closed.
*
* - Set STAT on error. STAT is initialized to no error before the open
* routine is called. When the open routine detects a error, it should
* set STAT accordingly. This will be passed to the caller of
* CAN_OPEN_CUSTOM. In that case, CAN_OPEN_CUSTOM will deallocate any
* system resources allocated to that CAN library use, and return the
* library use descriptor invalid.
*
* When the open routine returns with STAT indicating error, it must not
* have any additional system resources allocated. The custom close
* routine, if any, will not be called.
*
* The CAN library use state always includes a queue for received CAN frames,
* although custom receive routines need not be aware of this. The application
* interface for receiving frames is thru this queue. The driver can supply
* received CAN frames in two different ways:
*
* - Supply a explicit receive routine via the RECV_P pointer. The CAN
* library will automatically call this routine when the application
* requests a CAN frame and the input queue is empty.
*
* - Push received frames asynchronously onto the input queue. In this case,
* RECV_P should be left NIL.
*
* If a queue for sending CAN frames is desirable for the driver, then it must
* create such a queue itself.
*
* Sending and receiving drivers only need to be simple, but can be arbitrarily
* complex as desired. Additional tasks can be launched, various system
* resources, allocated, etc. The only restriction is that a custom close
* routine must then be provided to deallocate any such system resources other
* than dynamic memory under the CL.MEM_P^ context.
*
* RECV_P routine
*
* This routine is optional. The driver needs to do nothing at all if it
* is not capable of receiving CAN frames. Otherwise, there are two choices.
* The driver can asynchronously push received CAN frames onto the input
* queue, or it can provide a routine for the CAN library to explicitly call
* via the RECV_P pointer. There is no mutex around calling RECV_P^. If the
* application will call CAN_RECV from multiple threads, then the driver
* should push received frames onto the input queue. Reads and writes to and
* from the queue are multi-thread safe.
*
* SEND_P routine
*
* The CAN library has no queue for sending CAN frames. Each frame is passed
* to the driver when CAN_SEND is called. A mutex is used to guarantee that
* only one thread at a time is calling SEND_P^, even if multiple threads
* call CAN_SEND simultaneously.
}
module can_custom;
define can_open_custom;
%include 'can2.ins.pas';
{
********************************************************************************
*
* Subroutine CAN_OPEN_CUSTOM (CL, OPEN_P, CFG, PNT, STAT)
*
* Initialize and set up the CAN library use state CL with custom routines for
* sending and receiving CAN frames.
*
* OPEN_P points to the application routine to call to install the custom
* driver routines. See the header comments of this module for details.
*
* I32 and PNT are optional configuration parameters that are passed to the
* custom open routine pointed to by OPEN_P.
}
procedure can_open_custom ( {create new CAN library use, custom driver}
out cl: can_t; {library use state to initialize and open}
in open_p: can_open_p_t; {pointer to routine to perform custom open}
in cfg: sys_int_conv32_t; {optional 32 bit configuration parameter}
in pnt: univ_ptr; {optional pointer to configuration parameters}
out stat: sys_err_t); {completion status}
val_param;
var
stat2: sys_err_t; {to avoid corrupting STAT}
begin
sys_error_none (stat); {init to no error encountered}
can_init (cl); {init CAN library state descriptor}
open_p^ (cl, cfg, pnt, stat); {call app routine to install drivers}
if sys_error(stat) then begin {driver not installed ?}
cl.close_p := nil; {do not run any custom close routine}
can_close (cl, stat2); {deallocate resources, CL invalid}
end;
end;
|
program minigzip;
(************************************************************************
minigzip.c -- simulate gzip using the zlib compression library
Copyright (C) 1995-1998 Jean-loup Gailly.
minigzip is a minimal implementation of the gzip utility. This is
only an example of using zlib and isn't meant to replace the
full-featured gzip. No attempt is made to deal with file systems
limiting names to 14 or 8+3 characters, etc... Error checking is
very limited. So use minigzip only for testing; use gzip for the
real thing. On MSDOS, use only on file names without extension
or in pipe mode.
Pascal translation based on code contributed by Francisco Javier Crespo
Copyright (C) 1998 by Jacques Nomssi Nzali
For conditions of distribution and use, see copyright notice in readme.txt
------------------------------------------------------------------------
Modifications by W.Ehrhardt:
Feb 2002
- global {$i-}
- Reintroduced Z_OK
- Erase infile after -d
- option loop until ParamCount-1
- source code reformating/reordering
Mar 2005
- Code cleanup for WWW upload
Jul 2008
- Replace two ioerr := IOResult to avoid warnungs
- some typecasts for len
Jul 2009
- D12 fixes
------------------------------------------------------------------------
*************************************************************************)
{$ifdef WIN32}
{$ifndef VirtualPascal}
{$apptype console}
{$endif}
{$endif}
{$ifdef WIN64}
{$apptype console}
{$endif}
{$i-}
uses
{$ifdef VER80}
WinCrt,
{$endif}
gzio, ZLibH;
const
BUFLEN = 16384;
GZ_SUFFIX = '.gz';
{$define MAXSEG_64K} {*we W0800, replace MAXSEF_64K}
var
buf : packed array[0..BUFLEN-1] of byte; { Global uses BSS instead of stack }
prog: str255;
{---------------------------------------------------------------------------}
procedure error(const msg: str255);
{-Display error message and halt}
begin
writeln(prog,': ',msg);
halt(1);
end;
{---------------------------------------------------------------------------}
procedure gz_compress(var infile: file; outfile: gzFile);
{-Compress input to output then close both files}
var
len : uInt;
ioerr: integer;
err : int;
begin
while true do begin
blockread(infile, buf, BUFLEN, len);
ioerr := IOResult;
if ioerr<>0 then begin
writeln('read error: ',ioerr);
halt(1);
end;
if len=0 then break;
if gzwrite(outfile, @buf, len)<>int(len) then error(gzerror(outfile, err)); {Jul 2008}
end;
if gzclose(outfile)<>Z_OK then error('gzclose error');
close(infile);
if IOResult<>0 then {??}; {Jul 2008}
end;
{---------------------------------------------------------------------------}
procedure gz_uncompress(infile: gzFile; var outfile: file);
{-Uncompress input to output then close both files}
var
len : int;
written: uInt;
ioerr : integer;
err : int;
begin
while true do begin
len := gzread(infile, @buf, BUFLEN);
if len<0 then error(gzerror(infile, err));
if len=0 then break;
blockwrite(outfile, buf, len, written);
if written<>uInt(len) then error('write error'); {Jul 2008}
end;
close(outfile);
ioerr := IOResult;
if ioerr<>0 then begin
writeln('close error: ',ioerr);
halt(1);
end;
if gzclose(infile)<>Z_OK then error('gzclose error');
end;
{---------------------------------------------------------------------------}
procedure file_compress(const filename, mode: str255);
{-Compress the given file: create a corresponding .gz file and remove the original}
var
infile : file;
outfile: gzFile;
ioerr : integer;
outname: str255;
begin
system.assign(infile, {$ifdef unicode} string {$endif}(filename));
reset(infile,1);
ioerr := IOResult;
if ioerr<>0 then begin
writeln('open error: ',ioerr);
halt(1);
end;
outname := filename + GZ_SUFFIX;
outfile := gzopen(outname, mode);
if outfile=nil then begin
writeln(prog,': can''t gzopen ',outname);
halt(1);
end;
gz_compress(infile, outfile);
{*we: infile is closed}
erase(infile);
if IOResult<>0 then {??}; {Jul 2008}
end;
{---------------------------------------------------------------------------}
procedure file_uncompress(const filename: str255);
{-Uncompress the given file and remove the original}
var
infile : gzFile;
outfile: file;
ioerr : integer;
len : integer;
inname : str255;
outname: str255;
begin
len := length(filename);
if copy(filename,len-2,3)=GZ_SUFFIX then begin
inname := filename;
outname := copy(filename,0,len-3);
end
else begin
inname := filename + GZ_SUFFIX;
outname := filename;
end;
infile := gzopen(inname, 'r');
if infile=nil then begin
writeln(prog,': can''t gzopen ',inname);
halt(1);
end;
system.assign(outfile, {$ifdef unicode} string {$endif}(outname));
rewrite(outfile,1);
ioerr := IOResult;
if ioerr<>0 then begin
writeln('open error: ',ioerr);
halt(1);
end;
gz_uncompress(infile, outfile);
{*we: outfile is closed, renable erasing of infile}
system.assign(outfile, {$ifdef unicode} string {$endif}(inname));
erase(outfile);
ioerr := IOResult;
if ioerr<>0 then begin
writeln(': can''t erase ',inname);
halt(1);
end;
end;
var
uncompr: boolean;
outmode: string[20];
i : integer;
option : string[2];
begin
uncompr := false;
outmode := 'w6 ';
prog := {$ifdef unicode} str255 {$endif}(paramstr(0));
GZ_windowBits := 13;
GZ_memLevel := 6;
if (ParamCount = 0) then begin
writeln('Error: STDIO/STDOUT not supported yet');
writeln;
writeln('Usage: minigzip [-d] [-f] [-h] [-1 to -9] <file>');
writeln(' -d : decompress');
writeln(' -f : compress with Z_FILTERED');
writeln(' -h : compress with Z_HUFFMAN_ONLY');
writeln(' -1 to -9 : compression level');
exit;
end;
for i:=1 to ParamCount-1 do begin
option := {$ifdef unicode} str255 {$endif}(paramstr(i));
if (option = '-d') then uncompr := true;
if (option = '-f') then outmode[3] := 'f';
if (option = '-h') then outmode[3] := 'h';
if (option[1] = '-') and (option[2] >= '1') and (option[2] <= '9') then outmode[2] := option[2];
end;
if uncompr then file_uncompress({$ifdef unicode} str255 {$endif}(ParamStr(ParamCount)))
else file_compress({$ifdef unicode} str255 {$endif}(ParamStr(ParamCount)), outmode);
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:
main bittorrent constants
}
unit bittorrentConst;
interface
uses
classes,helper_datetime,const_ares;
const
TIMEOUTTCPCONNECTION=10*SECOND;
TIMEOUTTCPRECEIVE=15*SECOND;
TIMEOUTTCPCONNECTIONTRACKER=15*SECOND;
TIMEOUTTCPRECEIVETRACKER=30*SECOND;
BTSOURCE_CONN_ATTEMPT_INTERVAL=MINUTE;
BT_MAXSOURCE_FAILED_ATTEMPTS=2;
BTKEEPALIVETIMEOUT=2*MINUTE;
BITTORRENT_PIECE_LENGTH=16*KBYTE;
EXPIRE_OUTREQUEST_INTERVAL=60*SECOND;
INTERVAL_REREQUEST_WHENNOTCHOCKED=10*SECOND;
TRACKER_NUMPEER_REQUESTED=100;
BITTORRENT_INTERVAL_BETWEENCHOKES=10*SECOND;
BITTORENT_MAXNUMBER_CONNECTION_ESTABLISH = 35;
BITTORENT_MAXNUMBER_CONNECTION_ACCEPTED = 55;
TRACKERINTERVAL_WHENFAILED=2*MINUTE;
BITTORRENT_MAX_ALLOWED_SOURCES = 300;
BITTORRENT_DONTASKMORESOURCES = 200;
SEVERE_LEECHING_RATIO=10;
NUMMAX_SOURCES_DOWNLOADING = 4;
MAX_OUTGOING_ATTEMPTS = 3;
MAXNUM_OUTBUFFER_PACKETS = 10;
NUMMAX_TRANSFER_HASHFAILS = 8;
NUMMAX_SOURCE_HASHFAILS = 4;
STR_BITTORRENT_PROTOCOL_HANDSHAKE=chr(19)+'BitTorrent protocol';
STR_BITTORRENT_PROTOCOL_EXTENSIONS=CHRNULL{chr($80)}+CHRNULL+CHRNULL+CHRNULL+
CHRNULL+chr($10)+CHRNULL+chr(1); // support extension protocol + dht
TORRENT_DONTSHARE_INTERVAL=2592000;//30 days
CMD_BITTORRENT_CHOKE = 0;
CMD_BITTORRENT_UNCHOKE = 1;
CMD_BITTORRENT_INTERESTED = 2;
CMD_BITTORRENT_NOTINTERESTED = 3;
CMD_BITTORRENT_HAVE = 4;
CMD_BITTORRENT_BITFIELD = 5;
CMD_BITTORRENT_REQUEST = 6;
CMD_BITTORRENT_PIECE = 7;
CMD_BITTORRENT_CANCEL = 8;
CMD_BITTORRENT_DHTUDPPORT = 9;
// fast peer extensions
CMD_BITTORRENT_SUGGESTPIECE = 13;
CMD_BITTORRENT_HAVEALL = 14;
CMD_BITTORRENT_HAVENONE = 15;
CMD_BITTORRENT_REJECTREQUEST = 16;
CMD_BITTORRENT_ALLOWEDFAST = 17;
// extension protocol
CMD_BITTORRENT_EXTENSION = 20;
OPCODE_EXTENDED_HANDSHAKE = 0;
OUR_UT_PEX_OPCODE = 1;
OUR_UT_METADATA_OPCODE = 2;
// dummy value for addpacket procedure
CMD_BITTORRENT_KEEPALIVE = 100;
CMD_BITTORRENT_UNKNOWN = 101;
implementation
end. |
unit consts_float_0;
interface
implementation
var G: Float32;
procedure Test;
begin
G := 2.4;
end;
initialization
Test();
finalization
Assert(G = 2.4);
end. |
{
Ultibo RTL Builder Tool.
Copyright (C) 2022 - 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
==========
RTL Builder
===========
The Ultibo RTL builder provides the capability to update the RTL and Packages to
the latest version available from GitHub and supports options to check for, download,
install and rebuild the RTL without user intervention.
You can also perform any one of the above steps individually if required.
To provide consistent and reliable functionality the RTL builder now also supports
downloading the latest tested versions of the Raspberry Pi firmware and extracting
them to the firmware folder of your Ultibo installation.
The RTL builder creates a Windows batch file or Linux shell script which compiles
the RTL and Packages for any of the supported architectures and displays the output
in a window during the compile.
While the tool is designed to determine the correct paths and locations without
configuration it does support creating a BuildRTL.ini file in the same directory
and setting a number of parameters to adjust the behavior.
The format of the INI file is:
[BuildRTL]
PathPrefix=
InstallPath=
CompilerName=
CompilerPath=
CompilerVersion=
SourcePath=
FirmwarePath=
BranchName=
ARMCompiler=
AARCH64Compiler=
BuildRTL=
BuildPackages=
PlatformARMv6=
PlatformARMv7=
PlatformARMv8=
A brief explanation of each parameter along with the standard default value:
PathPrefix - A text value to prepend to the path variable in the batch file (Default: <Blank>)
InstallPath - The path where Ultibo core is installed (Default Windows: C:\Ultibo\Core) (Detected from the application path)
( Linux: $HOME/ultibo/core)
CompilerName - The name of the Free Pascal compiler (Default Windows: fpc.exe)
( Linux: fpc)
CompilerPath - The path where the Ultibo version of FPC is installed (Default Windows: <InstallPath>\fpc\<CompilerVersion>)
( Linux: <InstallPath>/fpc)
CompilerVersion - The version of the FPC compiler (Default: 3.2.2)
SourcePath - The path to RTL and Packages source code (Default Windows: <CompilerPath>\source)
( Linux: <CompilerPath>/source)
FirmwarePath - The path where firmware files are located (Default Windows: <InstallPath>\firmware)
( Linux: <InstallPath>/firmware)
BranchName - The name of the Git branch to use when checking for and downloading updates
ARMCompiler - The name of the Free Pascal ARM Compiler or Cross Compiler (Default: <Blank>)
AARCH64Compiler - The name of the Free Pascal AARCH64 Compiler or Cross Compiler (Default: <Blank>)
BuildRTL - Enable or disable building the RTL (0=Disable / 1=Enable) (Default: 1)
BuildPackages - Enable or disable building the Packages (0=Disable / 1=Enable) (Default: 1)
PlatformARMv6 - Build the RTL and Packages for ARMv6 architecture (0=Disable / 1=Enable) (Default: 1)
PlatformARMv7 - Build the RTL and Packages for ARMv7 architecture (0=Disable / 1=Enable) (Default: 1)
PlatformARMv8 - Build the RTL and Packages for ARMv8 architecture (0=Disable / 1=Enable) (Default: 1)
Please note that compiling BuildRTL requires Lazarus 2.0.10 (with FPC 3.2.0) or above.
}
program BuildRTL;
{$MODE Delphi}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Forms,
Interfaces,
Main in 'Main.pas' {frmMain};
{$R *.res}
begin
RequireDerivedFormResource := True;
Application.Initialize;
Application.Title := 'Ultibo RTL Builder';
Application.CreateForm(TfrmMain, frmMain);
Application.Run;
end.
|
unit PascalCoin.Update.Interfaces;
interface
uses Spring, PascalCoin.RPC.Interfaces, PascalCoin.Utils.Interfaces,
System.Classes;
type
{$SCOPEDENUMS ON}
TAccountUpdateStatus = (NotFound, NoChange, Changed, Added, Deleted);
{$SCOPEDENUMS OFF}
IUpdatedAccount = Interface
['{17DDA9D7-C141-4FAE-BAC6-63E69BE28E76}']
function GetAccount: IPascalCoinAccount;
procedure SetAccount(Value: IPascalCoinAccount);
function GetStatus: TAccountUpdateStatus;
procedure SetStatus(const Value: TAccountUpdateStatus);
function GetUpdateId: Integer;
procedure SetUpdateId(const Value: Integer);
property Account: IPascalCoinAccount read GetAccount write SetAccount;
property Status: TAccountUpdateStatus read GetStatus write SetStatus;
property UpdateId: Integer read GetUpdateId write SetUpdateId;
End;
IUpdatedAccounts = IPascalCoinList<IUpdatedAccount>;
TOnAccountsUpdated = procedure(Value: IUpdatedAccounts) of object;
IFetchAccountData = interface
['{1E8237E8-69F8-4196-A5CB-A0BBE07A6223}']
function GetOnSync: IEvent<TOnAccountsUpdated>;
function GetSleepInterval: integer;
procedure SetSleepInterval(const Value: integer);
procedure SetKeyStyle(const Value: TKeyStyle);
function GetIsRunning: boolean;
function GetPause: Boolean;
procedure SetPause(const Value: boolean);
procedure SetURI(const Value: string);
procedure AddPublicKey(const Value: string);
procedure AddPublicKeys(Value: TStrings);
function Execute: boolean;
procedure Terminate;
/// <summary>
/// How long the thread sleeps before iterating through the list again
/// (milliseconds: default 10000)
/// </summary>
property SleepInterval: integer read GetSleepInterval
write SetSleepInterval;
property OnSync: IEvent<TOnAccountsUpdated> read GetOnSync;
property KeyStyle: TKeyStyle write SetKeyStyle;
property IsRunning: boolean read GetIsRunning;
property NodeURI: string write SetURI;
property Pause: boolean read GetPause write SetPause;
end;
implementation
end.
|
unit uSkinDLL;
interface
uses
Classes;
type
TAssignSkinsProc = procedure(AStringList: TStringList); stdcall;
TSkinDLL = class
private
FSkinsDLL: THandle;
FAssignSkinsProc: TAssignSkinsProc;
FAvailSkins: TStringList;
FSkinName: string;
IsReadingPrefs: Boolean;
function GetDllLoaded: boolean;
procedure LoadSkin(SkinName, ResName: variant); overload;
procedure LoadSkin(SkinName, ResName: string); overload;
procedure ReadPrefs;
public
constructor Create;
destructor Destroy; override;
function GetAvailableSkins: TStringList;
function GetSkinName: string;
procedure SetSkinName(Value: string);
end;
function GetSkinDLL: TSkinDLL;
implementation
uses
Windows, Variants, dxSkinsDefaultPainters, dxSkinsStrs, SysUtils, Registry,
Controls, Forms, dmSkins, Dialogs;
const
LOW_REG_PATH = 'Software\Koplin\SkinnedApp';
LOW_SKIN_NAME_KEY = 'SkinName';
var
gSkinDLL: TSkinDLL;
function GetSkinDLL: TSkinDLL;
begin
if not Assigned(gSkinDLL) then
gSkinDLL := TSkinDLL.Create;
Result := gSkinDLL;
end;
{ TSkinDLL }
constructor TSkinDLL.Create;
var
procName: string;
begin
Self.FSkinsDLL := LoadLibrary('SKINS.DLL');
procName := 'AssignSkinNames';
if (Self.FSkinsDLL < HINSTANCE_ERROR) then
raise Exception.Create('SKINS.DLL não pôde ser carregado.' + SysErrorMessage(GetLastError));
if Self.GetDllLoaded then
Self.FAssignSkinsProc := TAssignSkinsProc(GetProcAddress(Self.FSkinsDLL, 'AssignSkins'))
else
Self.FAssignSkinsProc := nil;
Self.FAvailSkins := TStringList.Create;
if Assigned(Self.FAssignSkinsProc) then
Self.FAssignSkinsProc(Self.FAvailSkins);
Self.ReadPrefs;
end;
destructor TSkinDLL.Destroy;
begin
FreeAndNil(Self.FAvailSkins);
if Self.GetDllLoaded then
FreeLibrary(Self.FSkinsDLL);
inherited;
end;
function TSkinDLL.GetDllLoaded: boolean;
begin
Result := fSkinsDLL <> INVALID_HANDLE_VALUE;
end;
procedure TSkinDLL.LoadSkin(SkinName, ResName: variant);
begin
Self.LoadSkin(VarToStrDef(SkinName, ''), VarToStrDef(ResName, ''));
end;
procedure TSkinDLL.LoadSkin(SkinName, ResName: string);
var
r: TResourceStream;
begin
if Assigned(Self.FAssignSkinsProc) and (SkinName <> '') and (ResName <> '') then
begin
r := TResourceStream.Create(Self.FSkinsDLL, ResName, PWideChar(sdxResourceType));
try
try
dxSkinsUserSkinLoadFromStream(r, SkinName);
except
on e: Exception do
ShowMessage('Erro ao carregar o tema ' + SkinName + ': ' + e.Message);
end;
finally
r.Free;
end;
end;
end;
function TSkinDLL.GetAvailableSkins: TStringList;
begin
Result := FAvailSkins;
end;
function TSkinDLL.GetSkinName: string;
begin
Result := Self.FSkinName;
end;
procedure TSkinDLL.ReadPrefs;
var
Reg: TRegistry;
SvCursor: TCursor;
begin
SvCursor := Screen.Cursor;
Screen.Cursor := crHourglass;
Self.IsReadingPrefs := true;
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_CURRENT_USER;
Reg.LazyWrite := False;
if Reg.OpenKey(LOW_REG_PATH, True) then
begin
if Reg.ValueExists(LOW_SKIN_NAME_KEY) then
SetSkinName(Reg.ReadString(LOW_SKIN_NAME_KEY))
else
SetSkinName('');
Reg.CloseKey;
end
else
raise Exception.Create('Não foi possível ler a chave de registro: ' + LOW_REG_PATH);
finally
Screen.Cursor := SvCursor;
FreeAndNil(Reg);
Self.IsReadingPrefs := false;
end;
end;
procedure TSkinDLL.SetSkinName(Value: string);
var
i: Integer;
Reg: TRegistry;
SvCursor: TCursor;
begin
if Value <> Self.FSkinName then
begin
Self.FSkinName := Value;
if Assigned(Self.FAssignSkinsProc) then
begin
if Self.FSkinName <> '' then
begin
for i := 0 to Pred(Self.FAvailSkins.Count) do
begin
if Self.FSkinName = Self.FAvailSkins.Names[i] then
begin
Self.LoadSkin(Self.FAvailSkins.Names[i], Self.FAvailSkins.ValueFromIndex[i]);
break;
end;
end;
end;
end;
DMSkin.dxSkinController1.SkinName := 'UserSkin';// Self.FSkinName; a manha esta em voltar o nome para UserSkin
if not Self.IsReadingPrefs then
begin
SvCursor := Screen.Cursor;
Screen.Cursor := crHourglass;
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_CURRENT_USER;
Reg.LazyWrite := False;
if Reg.OpenKey(LOW_REG_PATH, False) then
begin
Reg.WriteString(LOW_SKIN_NAME_KEY, Value);
Reg.CloseKey;
end;
finally
Screen.Cursor := SvCursor;
FreeAndNil(Reg);
end;
end;
end;
end;
initialization
finalization
gSkinDLL.Free;
end.
|
unit udmMain;
interface
uses
System.SysUtils,
System.Classes,
FireDAC.Stan.Intf,
FireDAC.Stan.Option,
FireDAC.Stan.Error,
FireDAC.UI.Intf,
FireDAC.Phys.Intf,
FireDAC.Stan.Def,
FireDAC.Stan.Pool,
FireDAC.Stan.Async,
FireDAC.Phys,
FireDAC.Stan.Param,
FireDAC.DatS,
FireDAC.DApt.Intf,
FireDAC.DApt,
Data.DB,
FireDAC.Comp.DataSet,
FireDAC.Comp.Client,
MemDS,
DBAccess,
Uni,
UniProvider,
PostgreSQLUniProvider,
clsTDBUtils;
type
TdmMain = class(TDataModule)
UniConnection1: TUniConnection;
qryClientes_: TUniQuery;
PostgreSQLUniProvider1: TPostgreSQLUniProvider;
qryEnderecos_: TUniQuery;
qryTelefones_: TUniQuery;
qryClientes_id: TLargeintField;
qryClientes_nome: TStringField;
qryClientes_apelido: TStringField;
qryClientes_telefone_padrao: TLargeintField;
qryEnderecos_id: TLargeintField;
qryEnderecos_cep: TStringField;
qryEnderecos_logradouro: TStringField;
qryEnderecos_complemento: TStringField;
qryEnderecos_bairro: TStringField;
qryEnderecos_cidade: TStringField;
qryEnderecos_uf: TStringField;
qryEnderecos_ibge: TStringField;
qryEnderecos_gia: TStringField;
qryEnderecos_descricao: TStringField;
qryTelefones_id: TLargeintField;
qryTelefones_numero: TStringField;
qryTelefones_tipo_telefone: TStringField;
qryProdutos_: TUniQuery;
qryProdutos_id: TLargeintField;
qryProdutos_descricao: TStringField;
qryProdutos_prešo_unitario: TFloatField;
qryPedidos_: TUniQuery;
qryPedidoXitems_: TUniQuery;
qryPedidoXitems_id: TLargeintField;
qryPedidoXitems_pedido_id: TLargeintField;
qryPedidoXitems_produto_id: TLargeintField;
qryPedidoXitems_qtde: TFloatField;
qryPedidoXitems_valor_unitario: TFloatField;
qryPedidoXitems_valor_total: TFloatField;
qryEnderecos_numero: TStringField;
qryClienteXEnderecos_: TUniQuery;
qryClienteXEnderecos_id: TLargeintField;
qryClienteXEnderecos_cliente_id: TLargeintField;
qryClienteXEnderecos_endereco_id: TLargeintField;
qryClienteXTelefones_: TUniQuery;
qryClienteXTelefones_id: TLargeintField;
qryClienteXTelefones_cliente_id: TLargeintField;
qryClienteXTelefones_telefone_id: TLargeintField;
qryProdutos_cod_catalogo: TStringField;
qryProdutos_conteudo: TStringField;
procedure DataModuleCreate(Sender: TObject);
procedure qryEnderecos_BeforePost(DataSet: TDataSet);
procedure qryTelefones_BeforePost(DataSet: TDataSet);
procedure qryEnderecos_AfterPost(DataSet: TDataSet);
procedure qryTelefones_AfterPost(DataSet: TDataSet);
procedure qryClientes_AfterScroll(DataSet: TDataSet);
private
{ Private declarations }
Utils: TDBUtils;
function NextVal(SequenceName: String): Integer;
function ConectarComBanco: Boolean;
procedure VinculaClienteXTelefone(ClienteID, TelefoneID: Integer);
procedure VinculaClienteXEndereco(ClienteID, EnderecoID: Integer);
public
{ Public declarations }
function InserirCliente: Boolean;
function InserirTelefone: Boolean;
function InserirEndereco: Boolean;
function SalvarCliente: Boolean;
function SalvarEndereco(ClienteID: Integer): Boolean;
function SalvarTelefone(ClienteID: Integer; NumeroTelefone: String): Boolean;
function ExcluirCliente(ClienteID: Integer): Boolean;
function ExcluirTelefone(TelefoneID: Integer): Boolean;
function ExcluirEndereco(EnderecoID: Integer): Boolean;
procedure FiltraCliente(ClienteID: Integer);
procedure FiltraEnderecos(ClienteID: Integer);
procedure FiltraTelefones(ClienteID: Integer);
procedure FiltraProduto(Descricao: String);
procedure ResetCads;
function BuscarPorTelefone(Telefone: String): Boolean;
end;
var
dmMain: TdmMain;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
uses
Forms;
function TdmMain.BuscarPorTelefone(Telefone: String): Boolean;
var
qry: TUniQuery;
cliente_id: Integer;
telefone_id: Integer;
begin
qry:=TUniQuery.Create(nil);
qry.Connection := UniConnection1;
qry.Close;
qry.SQL.Clear;
qry.SQL.Add('select id from "DaVinci".telefones where numero = '+QuotedStr(Telefone));
qry.Open;
Result := qry.RecordCount > 0;
if Result then
begin
telefone_id := qry.Fields.Fields[0].AsInteger;
qry.Close;
qry.SQL.Clear;
qry.SQL.Add('select cliente_id from "DaVinci".ClienteXTelefones where telefone_id = '+IntToStr(telefone_id));
qry.Open;
cliente_id := qry.Fields.Fields[0].AsInteger;
FiltraCliente(cliente_id);
end;
qry.Close;
qry.SQL.Clear;
FreeAndNil(qry);
end;
function TdmMain.ConectarComBanco: Boolean;
var
strl: TStringList;
begin
Result := False;
if FileExists(ExtractFilePath(Application.ExeName)+'connectionstring.cfg') then
begin
if UniConnection1.Connected then
UniConnection1.Disconnect;
strl:=TStringList.Create;
strl.LoadFromFile(ExtractFilePath(Application.ExeName)+'connectionstring.cfg');
UniConnection1.ConnectString := strl.Text;
UniConnection1.Connected := True;
FreeAndNil(strl);
Result := UniConnection1.Connected;
end;
if not (Assigned(Self.Utils)) then
begin
Self.Utils := TDBUtils.Create(TColDevConnection(UniConnection1));
end;
end;
procedure TdmMain.DataModuleCreate(Sender: TObject);
var
strl: TStringList;
i: Integer;
begin
try
if Self.ConectarComBanco then
begin
for I := 0 to Self.ComponentCount - 1 do
begin
if Self.Components[i].ClassType = TUniQuery then
begin
TUniQuery(Self.Components[i]).Close;
TUniQuery(Self.Components[i]).Open;
end;
end;
end;
finally
end;
end;
function TdmMain.ExcluirCliente(ClienteID: Integer): Boolean;
var
q: TColDevQuery;
begin
Result := False;
q:=Self.Utils.QueryFactory('DELETE FROM "DaVinci".clientes where id = '+IntToStr(ClienteID));
try
q.ExecSQL;
Result := True;
except
end;
end;
function TdmMain.ExcluirEndereco(EnderecoID: Integer): Boolean;
var
q: TColDevQuery;
begin
Result := False;
q:=Self.Utils.QueryFactory('DELETE FROM "DaVinci".enderecos where id = '+IntToStr(EnderecoID));
try
q.ExecSQL;
Result := True;
except
end;
end;
function TdmMain.ExcluirTelefone(TelefoneID: Integer): Boolean;
var
q: TColDevQuery;
begin
Result := False;
q:=Self.Utils.QueryFactory('DELETE FROM "DaVinci".telefones where id = '+IntToStr(TelefoneID));
try
q.ExecSQL;
Result := True;
except
end;
end;
procedure TdmMain.FiltraCliente(ClienteID: Integer);
begin
qryClientes_.Close;
qryClientes_.ParamByName('cliente_id').AsInteger := ClienteID;
qryClientes_.Open;
end;
procedure TdmMain.FiltraEnderecos(ClienteID: Integer);
begin
qryEnderecos_.Close;
qryEnderecos_.ParamByName('cliente_id').AsInteger := qryClientes_id.AsInteger;
qryEnderecos_.Open;
end;
procedure TdmMain.FiltraProduto(Descricao: String);
begin
qryProdutos_.Close;
qryProdutos_.SQL.Clear;
qryProdutos_.SQL.Add(' SELECT * ');
qryProdutos_.SQL.Add(' FROM "DaVinci".produtos ');
if Descricao <> EmptyStr then
begin
qryProdutos_.SQL.Add(' WHERE descricao like('+QuotedStr(Descricao)+')');
end;
qryProdutos_.SQL.Add(' order by descricao ');
qryProdutos_.Open;
end;
procedure TdmMain.FiltraTelefones(ClienteID: Integer);
begin
qryTelefones_.Close;
qryTelefones_.ParamByName('cliente_id').AsInteger := qryClientes_id.AsInteger;
qryTelefones_.Open;
end;
function TdmMain.InserirCliente;
begin
Result := False;
try
qryClientes_.Insert;
Result := True;
except
end;
end;
function TdmMain.InserirEndereco: Boolean;
begin
Result := False;
try
qryEnderecos_.Insert;
Result := True;
except
end;
end;
function TdmMain.InserirTelefone: Boolean;
begin
Result := False;
try
qryTelefones_.Insert;
Result := True;
except
end;
end;
function TdmMain.NextVal(SequenceName: String): Integer;
var
qry: TUniQuery;
begin
qry:=TUniQuery.Create(Application);
qry.Connection := UniConnection1;
qry.SQL.Clear;
qry.SQL.Add('SELECT NEXTVAL('+QuotedStr('"DaVinci".'+SequenceName)+')');
qry.Open;
Result := qry.Fields.Fields[0].AsInteger;
qry.Close;
qry.SQL.Clear;
FreeAndNil(qry);
end;
procedure TdmMain.qryClientes_AfterScroll(DataSet: TDataSet);
begin
FiltraTelefones(qryClientes_id.AsInteger);
FiltraEnderecos(qryClientes_id.AsInteger);
end;
procedure TdmMain.qryEnderecos_AfterPost(DataSet: TDataSet);
begin
qryClienteXEnderecos_.Post;
end;
procedure TdmMain.qryEnderecos_BeforePost(DataSet: TDataSet);
var
endereco_id: Integer;
begin
if qryClientes_id.AsInteger > 0 then
begin
qryClienteXEnderecos_.Insert;
endereco_id := NextVal('endereco_id');
qryClienteXEnderecos_cliente_id.AsInteger := qryClientes_id.AsInteger;
qryClienteXEnderecos_endereco_id.AsInteger := endereco_id;
qryEnderecos_id.AsInteger := endereco_id;
end;
end;
procedure TdmMain.qryTelefones_AfterPost(DataSet: TDataSet);
begin
qryClienteXTelefones_.Post;
end;
procedure TdmMain.qryTelefones_BeforePost(DataSet: TDataSet);
var
telefone_id: Integer;
begin
if qryClientes_id.AsInteger > 0 then
begin
qryClienteXTelefones_.Insert;
telefone_id := NextVal('telefone_id');
qryClienteXTelefones_cliente_id.AsInteger := qryClientes_id.AsInteger;
qryClienteXTelefones_telefone_id.AsInteger := telefone_id;
qryTelefones_id.AsInteger := telefone_id;
// qryClienteXTelefones_.Post;
end;
end;
procedure TdmMain.ResetCads;
begin
qryClientes_.Close;
qryClientes_.ParamByName('cliente_id').Clear;
qryClientes_.Open;
end;
function TdmMain.SalvarCliente;
var
id: Integer;
begin
Result := False;
try
id := NextVal('cliente_id');
qryClientes_id.AsInteger := id;
qryClientes_.Post;
qryClientes_.Refresh;
qryClientes_.Locate('ID', id, []);
Result := True;
except
end;
end;
function TdmMain.SalvarEndereco(ClienteID: Integer): Boolean;
var
end_id: Integer;
begin
Result := False;
case qryEnderecos_.State of
dsEdit:
begin
end;
dsInsert:
begin
if qryEnderecos_descricao.AsString <> EmptyStr then
begin
end_id := NextVal('endereco_id');
qryEnderecos_id.AsInteger := end_id;
qryEnderecos_.Post;
VinculaClienteXEndereco(ClienteID, end_id);
FiltraEnderecos(ClienteID);
Result := True;
end;
end;
end;
end;
function TdmMain.SalvarTelefone(ClienteID: Integer; NumeroTelefone: String): Boolean;
var
tel_id: Integer;
begin
Result := False;
case qryTelefones_.State of
dsEdit:
begin
end;
dsInsert:
begin
qryTelefones_numero.AsString := NumeroTelefone;
if qryTelefones_numero.AsString <> EmptyStr then
begin
tel_id := NextVal('telefone_id');
qryTelefones_id.AsInteger := tel_id;
qryTelefones_.Post;
VinculaClienteXTelefone(qryClientes_id.AsInteger, tel_id);
FiltraTelefones(qryClientes_id.AsInteger);
Result := False;
end;
end;
end;
end;
procedure TdmMain.VinculaClienteXEndereco(ClienteID, EnderecoID: Integer);
var
q: TColDevQuery;
begin
q:=Self.Utils.QueryFactory('INSERT INTO "DaVinci".ClienteXEnderecos(cliente_id, endereco_id) VALUES('+IntToStr(ClienteID)+', '+IntToStr(EnderecoID)+')');
q.Execute;
FreeAndNil(q);
end;
procedure TdmMain.VinculaClienteXTelefone(ClienteID, TelefoneID: Integer);
var
q: TColDevQuery;
begin
q:=Self.Utils.QueryFactory('INSERT INTO "DaVinci".ClienteXTelefones(cliente_id, telefone_id) VALUES('+IntToStr(ClienteID)+', '+IntToStr(TelefoneID)+')');
q.Execute;
FreeAndNil(q);
end;
end.
|
{ }
{ Random number functions v3.09 }
{ }
{ This unit is copyright © 1999-2004 by David J Butler }
{ }
{ This unit is part of Delphi Fundamentals. }
{ Its original file name is cRandom.pas }
{ The latest version is available from the Fundamentals home page }
{ http://fundementals.sourceforge.net/ }
{ }
{ I invite you to use this unit, free of charge. }
{ I invite you to distibute this unit, but it must be for free. }
{ I also invite you to contribute to its development, }
{ but do not distribute a modified copy of this file. }
{ }
{ A forum is available on SourceForge for general discussion }
{ http://sourceforge.net/forum/forum.php?forum_id=2117 }
{ }
{ }
{ Revision history: }
{ 1999/11/07 0.01 Add RandomSeed. }
{ 1999/12/01 0.02 Add RandomUniform. }
{ 1999/12/03 0.03 Add RandomNormal. }
{ 2000/01/23 1.04 Add RandomPseudoWord. }
{ 2000/07/13 1.05 Fix bug reported by Andrew Driazgov. }
{ 2000/08/22 1.06 Add RandomHex. }
{ 2000/09/20 1.07 Improve RandomSeed. }
{ 2002/06/01 3.08 Create cRandom unit. }
{ 2003/08/09 3.09 Replace random number generator. }
{ }
{$INCLUDE ..\cDefines.inc}
unit cRandom;
interface
{ }
{ RandomSeed }
{ Returns a random seed value based on various system states. }
{ }
function RandomSeed: LongWord;
{ }
{ Uniform random number generator }
{ Returns a random number from a uniform density distribution (ie all number }
{ have an equal probability of being 'chosen') }
{ RandomFloat returns an random floating point value between 0 and 1. }
{ RandomPseudoWord returns a random word-like string. }
{ }
function RandomUniform: LongWord; overload;
function RandomUniform(const N: Integer): Integer; overload;
function RandomBoolean: Boolean;
function RandomByte: Byte;
function RandomInt64: Int64; overload;
function RandomInt64(const N: Int64): Int64; overload;
function RandomHex(const Digits: Integer = 8): String;
function RandomFloat: Extended;
function RandomAlphaStr(const Length: Integer): String;
function RandomPseudoWord(const Length: Integer): String;
// Alternative random number generators
function mwcRandomLongWord: LongWord;
function urnRandomLongWord: LongWord;
function moaRandomFloat: Extended;
function mwcRandomFloat: Extended;
{ }
{ Normal distribution random number generator }
{ RandomNormalF returns a random number that has a Normal(0,1) distribution }
{ (Gaussian distribution) }
{ }
function RandomNormalF: Extended;
{ }
{ GUIDs }
{ }
type
TGUID128 = Array[0..3] of LongWord;
function GenerateGUID32: LongWord;
function GenerateGUID64: Int64;
function GenerateGUID128: TGUID128;
function GUID128ToHex(const GUID: TGUID128): String;
implementation
uses
{ Delphi }
{$ifdef windows} Windows,{$endif}
SysUtils,
Math;
{ }
{ Linear Congruential Random Number Generators }
{ The general form of a linear congruential generator is: }
{ SEED = (A * SEED + C) mod M }
{ }
function lcRandom1(const Seed: LongWord): LongWord;
begin
Result := LongWord(29943829 * Int64(Seed) - 1);
end;
function lcRandom2(const Seed: LongWord): LongWord;
begin
Result := LongWord(69069 * Int64(Seed) + 1);
end;
function lcRandom3(const Seed: LongWord): LongWord;
begin
Result := LongWord(1103515245 * Int64(Seed) + 12345);
end;
function lcRandom4(const Seed: LongWord): LongWord;
begin
Result := LongWord(214013 * Int64(Seed) + 2531011);
end;
function lcRandom5(const Seed: LongWord): LongWord;
begin
Result := LongWord(134775813 * Int64(Seed) + 1);
end;
{ }
{ RandomSeed }
{ }
var
StartupSeed : Int64 = 0;
FixedSeedInit : Boolean = False;
FixedSeed : LongWord = 0;
VariableSeed : LongWord = 0;
procedure InitFixedSeed;
var L : LongWord;
B : Array[0..258] of Byte;
function ApplyBuffer(const S: LongWord): LongWord;
var I : Integer;
begin
Result := S;
if L > 0 then
For I := 0 to StrLen(PChar(@B)) - 1 do
Result := Result xor (LongWord(B[I]) shl ((I mod 7) * 4));
end;
var S : LongWord;
P : Int64;
Q : Pointer;
T : LongWord;
begin
S := $A5F04182;
{ Pointer values }
Q := @FixedSeed;
S := LongWord(Int64(S) + LongWord(Q));
Q := @B;
S := LongWord(Int64(S) + LongWord(Q));
{ Startup Seed }
S := S xor LongWord(StartupSeed) xor LongWord(StartupSeed shr 32);
{$IFDEF OS_WIN32}
{ CPU Frequency }
if QueryPerformanceFrequency(P) then
S := S xor LongWord(P) xor LongWord(P shr 32);
{ OS User Name }
L := 256;
if GetUserName(@B, L) then
S := ApplyBuffer(S);
{ OS Computer Name }
L := 256;
if GetComputerName(@B, L) then
S := ApplyBuffer(S);
{ OS Timing }
T := GetTickCount;
While GetTickCount = T do
begin
Sleep(0);
S := lcRandom4(S);
if QueryPerformanceCounter(P) then
S := LongWord(Int64(S) + LongWord(P) + LongWord(P shr 32));
end;
{$ENDIF}
{ Randomize bits }
S := lcRandom2(lcRandom1(S));
{ Save fixed seed }
FixedSeed := S;
FixedSeedInit := True;
end;
function RandomSeed: LongWord;
var P : Int64;
Ye, Mo, Da : Word;
H, Mi, S, S1 : Word;
begin
{$IFDEF CPU_INTEL386}
{ CPU Registers }
asm
lahf
add eax, ebx
adc eax, ecx
adc eax, edx
adc eax, esi
adc eax, edi
mov Result, eax
end;
{$ELSE}
Result := 0;
{$ENDIF}
{ Fixed Seed }
if not FixedSeedInit then
InitFixedSeed;
Result := Result xor FixedSeed;
{ System Date }
DecodeDate(Date, Ye, Mo, Da);
Result := Result xor Ye xor (Mo shl 16) xor (Da shl 24);
{ System Time }
DecodeTime(Time, H, Mi, S, S1);
Result := Result xor H xor (Mi shl 8) xor (S1 shl 16) xor (S shl 24);
{$IFDEF OS_WIN32}
{ OS Counter }
Result := Result xor GetTickCount;
{ OS Handles }
Result := Result xor GetCurrentProcessID
xor GetCurrentThreadID;
{ CPU Counter }
if QueryPerformanceCounter(P) then
Result := LongWord(Int64(Result) + LongWord(P) + LongWord(P shr 32));
{$ENDIF}
{ Variable Seed }
Result := LongWord(Int64(Result) + VariableSeed);
VariableSeed := lcRandom5(lcRandom4(Result));
{ Randomize bits }
Result := lcRandom3(lcRandom1(Result));
end;
{ }
{ Mother-of-All pseudo random number generator }
{ This is a multiply-with-carry or recursion-with-carry generator. }
{ It has a cycle length of 3E+47. }
{ It was invented by George Marsaglia. }
{ }
var
moaSeeded : Boolean = False;
moaX : Array[0..3] of LongWord;
moaC : LongWord;
procedure moaInitSeed(const Seed: LongWord);
var I : Integer;
S : LongWord;
begin
S := Seed;
For I := 0 to 3 do
begin
S := lcRandom1(S);
moaX[I] := S;
end;
moaC := lcRandom1(S);
moaSeeded := True;
end;
function moaRandomLongWord: LongWord;
var S : Int64;
Xn : LongWord;
begin
if not moaSeeded then
moaInitSeed(RandomSeed);
S := 2111111111 * Int64(moaX[0]) +
1492 * Int64(moaX[1]) +
1776 * Int64(moaX[2]) +
5115 * Int64(moaX[3]) +
Int64(moaC);
moaC := LongWord(S shr 32);
Xn := LongWord(S);
moaX[0] := moaX[1];
moaX[1] := moaX[2];
moaX[2] := moaX[3];
moaX[3] := Xn;
Result := Xn;
end;
function moaRandomFloat: Extended;
begin
Result := moaRandomLongWord / High(LongWord);
end;
{ }
{ Multiply-With-Carry pseudo random number generator mentioned by George }
{ Marsaglia in his paper on the Mother-of-All generator: }
{ " Here is an interesting simple MWC generator with period > 2^92, for }
{ 32-bit arithmetic: }
{ x[n]=1111111464*(x[n-1]+x[n-2]) + carry mod 2^32. }
{ Suppose you have functions, say top() and bot(), that give the top and }
{ bottom halves of a 64-bit result. Then, with initial 32-bit x, y and }
{ carry c, simple statements such as }
{ y=bot(1111111464*(x+y)+c) }
{ x=y }
{ c=top(y) }
{ will, repeated, give over 2^92 random 32-bit y's. " }
{ }
var
mwcSeeded : Boolean = False;
mwcX : LongWord;
mwcY : LongWord;
mwcC : LongWord;
procedure mwcInitSeed(const Seed: LongWord);
begin
mwcX := lcRandom2(Seed);
mwcY := lcRandom2(mwcX);
mwcC := lcRandom2(mwcY);
mwcSeeded := True;
end;
function mwcRandomLongWord: LongWord;
var S : Int64;
begin
if not mwcSeeded then
mwcInitSeed(RandomSeed);
S := 1111111464 * (Int64(mwcX) + mwcY) + mwcC;
Result := LongWord(S);
mwcX := mwcY;
mwcY := Result;
mwcC := LongWord(S shr 32);
end;
function mwcRandomFloat: Extended;
begin
Result := mwcRandomLongWord / High(LongWord);
end;
{ }
{ Universal random number generator proposed by Marsaglia, Zaman, and Tsang. }
{ FSU-SCRI-87-50 }
{ It has a period of 2^144 = 2E+43. }
{ Only 24 bits are guarantueed to be completely random. }
{ This generator passes all known statistical tests on randomness. }
{ The algorithm is a combination of a Fibonacci sequence and an arithmetic }
{ sequence. }
{ }
var
urnSeeded : Boolean = False;
urnU : Array[1..97] of Double;
urnC : Double;
urnCD : Double;
urnCM : Double;
urnI : Integer;
urnJ : Integer;
procedure urnInit(const IJ, KL: Integer);
var I, J, K, L : Integer;
F, G, M : Integer;
S, T : Double;
begin
Assert((IJ >= 0) and (IJ <= 31328) and (KL >= 0) and (KL <= 30081));
I := (IJ div 177) mod 177 + 2;
J := IJ mod 177 + 2;
K := (KL div 169) mod 178 + 1;
L := KL mod 169;
for F := 1 to 97 do
begin
S := 0.0;
T := 0.5;
for G := 1 to 24 do
begin
M := (((I * J) mod 179) * K) mod 179;
I := J;
J := K;
K := M;
L := (53 * L + 1) mod 169;
if ((L * M) mod 64 >= 32) then
S := S + T;
T := T * 0.5;
end;
urnU[F] := S;
end;
urnC := 362436.0 / 16777216.0;
urnCD := 7654321.0 / 16777216.0;
urnCM := 16777213.0 / 16777216.0;
urnI := 97;
urnJ := 33;
urnSeeded := True;
end;
procedure urnInitSeed(const Seed: LongWord);
begin
urnInit((Seed and $FFFF) mod 30000, (Seed shr 16) mod 30000);
end;
function urnRandomFloat: Double;
var R : Double;
begin
if not urnSeeded then
urnInitSeed(RandomSeed);
R := urnU[urnI] - urnU[urnJ];
if R < 0.0 then
R := R + 1.0;
urnU[urnI] := R;
Dec(urnI);
if urnI = 0 then
urnI := 97;
Dec(urnJ);
if urnJ = 0 then
urnJ := 97;
urnC := urnC - urnCD;
if urnC < 0.0 then
urnC := urnC + urnCM;
R := R - urnC;
if R < 0.0 then
R := R + 1.0;
Result := R;
end;
function urnRandomLongWord: LongWord;
begin
Result := LongWord(Trunc(urnRandomFloat * 4294967295.0));
end;
{ }
{ Uniform Random }
{ }
function RandomUniform: LongWord;
begin
Result := moaRandomLongWord;
end;
function RandomUniform(const N: Integer): Integer;
begin
if N <= 0 then
Result := 0
else
Result := Integer(RandomUniform mod LongWord(N));
end;
function RandomBoolean: Boolean;
begin
Result := RandomUniform and 1 = 1;
end;
function RandomByte: Byte;
begin
Result := Byte(RandomUniform and $FF);
end;
function RandomFloat: Extended;
begin
Result := urnRandomFloat;
end;
function RandomInt64: Int64;
begin
Int64Rec(Result).Lo := RandomUniform;
Int64Rec(Result).Hi := RandomUniform;
end;
function RandomInt64(const N: Int64): Int64;
begin
if N <= 0 then
Result := 0
else
begin
Result := RandomInt64;
if Result < 0 then
Result := -Result;
Result := Result mod N;
end;
end;
function RandomHex(const Digits: Integer): String;
var I : Integer;
begin
Result := '';
Repeat
I := Digits - Length(Result);
if I > 0 then
Result := Result + IntToHex(RandomUniform, 8);
Until I <= 0;
SetLength(Result, Digits);
end;
function RandomAlphaStr(const Length: Integer): String;
var I : Integer;
begin
if Length <= 0 then
begin
Result := '';
exit;
end;
SetLength(Result, Length);
For I := 1 to Length do
Result[I] := Char(Ord('A') + RandomUniform(26));
end;
function RandomPseudoWord(const Length: Integer): String;
const Vowels = 'AEIOUY';
Consonants = 'BCDFGHJKLMNPQRSTVWXZ';
var I, A, P, T : Integer;
begin
if Length <= 0 then
begin
Result := '';
exit;
end;
SetLength(Result, Length);
P := -1;
A := RandomUniform(2);
For I := 1 to Length do
begin
Case A of
0 : Result[I] := Vowels[RandomUniform(6) + 1];
1 : Result[I] := Consonants[RandomUniform(20) + 1];
end;
T := A;
if A = P then
A := A xor 1
else
A := RandomUniform(2);
P := T;
end;
end;
{ }
{ Normal Random }
{ }
var
HasRandomNormal : Boolean = False;
ARandomNormal : Extended;
function RandomNormalF: Extended;
var fac, r, v1, v2: Extended;
begin
if not HasRandomNormal then
begin
Repeat
v1 := 2.0 * RandomFloat - 1.0;
v2 := 2.0 * RandomFloat - 1.0;
r := Sqr(v1) + Sqr(v2);
Until r < 1.0;
fac := Sqrt(-2.0 * ln(r) / r);
ARandomNormal := v1 * fac;
Result := v2 * fac;
HasRandomNormal := True;
end else
begin
Result := ARandomNormal;
HasRandomNormal := False;
end;
end;
{ }
{ GUID }
{ }
var
GUIDInit : Boolean = False;
GUIDBase : TGUID128 = (0, 0, 0, 0);
procedure InitGUID;
var I : Integer;
begin
GUIDBase[0] := RandomSeed;
For I := 1 to 3 do
GUIDBase[I] := RandomUniform;
GUIDInit := True;
end;
function GenerateGUID32: LongWord;
begin
if not GUIDInit then
InitGUID;
Result := GUIDBase[3];
GUIDBase[3] := LongWord(GUIDBase[3] + 1);
end;
function GenerateGUID64: Int64;
begin
if not GUIDInit then
InitGUID;
Int64Rec(Result).Hi := GUIDBase[2];
Int64Rec(Result).Lo := GUIDBase[3];
GUIDBase[3] := LongWord(GUIDBase[3] + 1);
end;
function GenerateGUID128: TGUID128;
begin
if not GUIDInit then
InitGUID;
Result := GUIDBase;
GUIDBase[3] := LongWord(GUIDBase[3] + 1);
if GUIDBase[3] = 0 then
GUIDBase[2] := LongWord(GUIDBase[2] + 1);
GUIDBase[1] := RandomUniform;
end;
function GUID128ToHex(const GUID: TGUID128): String;
begin
Result := IntToHex(GUIDBase[0], 8) +
IntToHex(GUIDBase[1], 8) +
IntToHex(GUIDBase[2], 8) +
IntToHex(GUIDBase[3], 8);
end;
initialization
{$IFDEF OS_WIN32}
QueryPerformanceCounter(StartupSeed);
StartupSeed := StartupSeed xor GetTickCount;
{$ENDIF}
end.
|
{
AD.A.P.T. Library
Copyright (C) 2014-2018, Simon J Stuart, All Rights Reserved
Original Source Location: https://github.com/LaKraven/ADAPT
Subject to original License: https://github.com/LaKraven/ADAPT/blob/master/LICENSE.md
}
unit ADAPT.Comparers.Intf;
{$I ADAPT.inc}
interface
uses
{$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES}
System.Classes,
{$ELSE}
Classes,
{$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES}
ADAPT.Intf;
{$I ADAPT_RTTI.inc}
type
/// <summary><c>Used to Compare two Values of a Generic Type.</c></summary>
IADComparer<T> = interface(IADInterface)
function AEqualToB(const A, B: T): Boolean;
function AGreaterThanB(const A, B: T): Boolean;
function AGreaterThanOrEqualToB(const A, B: T): Boolean;
function ALessThanB(const A, B: T): Boolean;
function ALessThanOrEqualToB(const A, B: T): Boolean;
end;
/// <summary><c>Used to compare two Values of a Generic Ordinal Type.</c></summary>
/// <remarks><c>Provides basic Mathematical Functions as well as Equality Comparers.</c></summary>
IADOrdinalComparer<T> = interface(IADComparer<T>)
/// <returns><c>The Sum of both given Values.<c></returns>
function Add(const A, B: T): T;
/// <returns><c>The Sum of ALL given Values.</c></returns>
function AddAll(const Values: Array of T): T;
/// <returns><c>The Difference between the two given Values.</c></returns>
function Difference(const A, B: T): T;
/// <returns><c>Value A divided by Value B.</c></returns>
function Divide(const A, B: T): T;
/// <returns><c>Value A multiplied by Value B.</c></returns>
function Multiply(const A, B: T): T;
/// <returns><c>Value B Subtracted from Value A.</c></returns>
function Subtract(const A, B: T): T;
end;
/// <summary><c>Provides Getter and Setter for any Type utilizing a Comparer Type.</c></summary>
IADComparable<T> = interface(IADInterface)
['{88444CD4-80FD-495C-A3D7-121CA14F7AC7}'] // If we don't provide a GUID here, we cannot cast-reference Collections as "Comparables".
// Getters
function GetComparer: IADComparer<T>;
// Setters
procedure SetComparer(const AComparer: IADComparer<T>);
// Properties
property Comparer: IADComparer<T> read GetComparer write SetComparer;
end;
IADOrdinalComparable<T> = interface(IADInterface)
['{A745312E-B645-4645-8A72-5CD50B263067}']
// Getters
function GetComparer: IADOrdinalComparer<T>;
// Setters
procedure SetComparer(const AComparer: IADOrdinalComparer<T>);
// Properties
property Comparer: IADOrdinalComparer<T> read GetComparer write SetComparer;
end;
implementation
end.
|
////////////////////////////////////////////////////////////////////////////////
//
//
// FileName : SUITabControl.pas
// Creator : Shen Min
// Date : 2002-09-10 V1-V3
// 2003-07-10 V4
// Comment :
//
// Copyright (c) 2002-2003 Sunisoft
// http://www.sunisoft.com
// Email: support@sunisoft.com
//
////////////////////////////////////////////////////////////////////////////////
unit SUITabControl;
interface
{$I SUIPack.inc}
uses Windows, Messages, SysUtils, Classes, Controls, ExtCtrls, Forms, Graphics,
ComCtrls, Math,
SUIThemes, SUIMgr;
const
SUI_TABCONTROL_MAXTABS = 64;
type
TsuiTabPosition = (suiTop, suiBottom);
TsuiTab = class;
TTabActiveNotify = procedure (Sender : TObject; TabIndex : Integer) of object;
TsuiTabControlTopPanel = class(TCustomPanel)
private
m_Tabs : TStrings;
m_UIStyle : TsuiUIStyle;
m_FileTheme : TsuiFileTheme;
m_TabIndex : Integer;
m_LeftMargin : Integer;
m_TabPos : array [0 .. SUI_TABCONTROL_MAXTABS - 1] of Integer;
m_TabHeight : Integer;
m_UserChanging : Boolean;
m_Passed : Integer;
m_ShowButton : Boolean;
m_InButtons : Integer;
m_BtnSize : TPoint;
m_AutoFit : Boolean;
m_ActiveTab, m_InactiveTab, m_Line : TBitmap;
m_TabPosition : TsuiTabPosition;
procedure OnTabsChange(Sender : TObject);
procedure SetTabs(const Value: TStrings);
procedure SetUIStyle(const Value: TsuiUIStyle);
procedure SetLeftMargin(const Value: Integer);
procedure SetTabIndex(const Value: Integer);
procedure SetFileTheme(const Value: TsuiFileTheme);
procedure SetTabPosition(const Value: TsuiTabPosition);
procedure WMERASEBKGND(var Msg : TMessage); message WM_ERASEBKGND;
function PaintTabs(const Buf : TBitmap) : Integer;
procedure PaintButtons(const Buf : TBitmap);
protected
m_TabControl : TsuiTab;
procedure Paint(); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure RequestAlign; override;
procedure Resize(); override;
public
m_TabVisible : array [0 .. SUI_TABCONTROL_MAXTABS - 1] of Boolean;
constructor Create(AOwner : TComponent; TabControl : TsuiTab); reintroduce;
destructor Destroy(); override;
published
property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme;
property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle;
property Tabs : TStrings read m_Tabs write SetTabs;
property TabIndex : Integer read m_TabIndex write SetTabIndex;
property LeftMargin : Integer read m_LeftMargin write SetLeftMargin;
property TabPosition : TsuiTabPosition read m_TabPosition write SetTabPosition;
end;
TsuiTab = class(TCustomPanel)
private
m_UIStyle : TsuiUIStyle;
m_FileTheme: TsuiFileTheme;
m_BorderColor : TColor;
m_Font : TFont;
m_TabPosition : TsuiTabPosition;
m_OnTabActive : TTabActiveNotify;
m_OnChange : TNotifyEvent;
m_OnChanging : TTabChangingEvent;
procedure SetFileTheme(const Value: TsuiFileTheme);
procedure SetUIStyle(const Value: TsuiUIStyle);
procedure SetTabs(const Value: TStrings);
function GetTabs() : TStrings;
function GetLeftMargin: Integer;
function GetTabIndex: Integer;
procedure SetLeftMargin(const Value: Integer);
procedure SetBorderColor(const Value: TColor);
procedure SetFont(const Value: TFont);
procedure SetTabPosition(const Value: TsuiTabPosition);
procedure CMCursorChanged(var Message: TMessage); message CM_CURSORCHANGED;
procedure WMERASEBKGND(var Message : TMessage); message WM_ERASEBKGND;
procedure TopPanelClick(Sender : TObject);
procedure TopPanelDblClick(Sender : TObject);
protected
m_TopPanel : TsuiTabControlTopPanel;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure Paint(); override;
function CreateTopPanel() : TsuiTabControlTopPanel; virtual; abstract;
procedure SetTabIndex(const Value: Integer); virtual;
procedure BorderColorChanged(); virtual;
procedure AlignControls(AControl: TControl; var Rect: TRect); override;
procedure Resize(); override;
property Tabs : TStrings read GetTabs write SetTabs;
property TabIndex : Integer read GetTabIndex write SetTabIndex;
procedure TabActive(TabIndex : Integer); virtual;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy(); override;
procedure UpdateUIStyle(UIStyle : TsuiUIStyle; FileTheme : TsuiFileTheme); virtual;
property DockManager;
published
property Align;
property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme;
property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle;
property LeftMargin : Integer read GetLeftMargin write SetLeftMargin;
property BorderColor : TColor read m_BorderColor write SetBorderColor;
property Color;
property Font : TFont read m_Font write SetFont;
property Visible;
property TabPosition : TsuiTabPosition read m_TabPosition write SetTabPosition;
property Anchors;
property BiDiMode;
property Constraints;
property UseDockManager default True;
property DockSite;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property FullRepaint;
property Locked;
property ParentBiDiMode;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property OnCanResize;
property OnClick;
property OnConstrainedResize;
property OnContextPopup;
property OnDockDrop;
property OnDockOver;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnGetSiteInfo;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnStartDock;
property OnStartDrag;
property OnUnDock;
property OnTabActive : TTabActiveNotify read m_OnTabActive write m_OnTabActive;
property OnChange : TNotifyEvent read m_OnChange write m_OnChange;
property OnChanging : TTabChangingEvent read m_OnChanging write m_OnChanging;
end;
TsuiTabControl = class(TsuiTab)
protected
function CreateTopPanel() : TsuiTabControlTopPanel; override;
published
property Tabs;
property TabIndex;
end;
implementation
uses SUIPublic;
{ TsuiTabControlTopPanel }
constructor TsuiTabControlTopPanel.Create(AOwner: TComponent; TabControl : TsuiTab);
var
i : Integer;
begin
inherited Create(AOwner);
ControlStyle := ControlStyle - [csAcceptsControls];
m_ActiveTab := TBitmap.Create();
m_InactiveTab := TBitmap.Create();
m_Line := TBitmap.Create();
m_Tabs := TStringList.Create();
(m_Tabs as TStringList).OnChange := OnTabsChange;
m_Tabs.Add('Tab1');
m_TabControl := TabControl;
Caption := ' ';
BevelInner := bvNone;
BevelOuter := bvNone;
BorderWidth := 0;
Align := alNone;
m_LeftMargin := 10;
m_TabIndex := 0;
m_UserChanging := false;
m_Passed := 0;
m_AutoFit := false;
m_ShowButton := false;
m_InButtons := 0;
m_BtnSize.X := 0;
m_BtnSize.Y := 0;
m_TabPosition := suiTop;
for i := 0 to SUI_TABCONTROL_MAXTABS - 1 do
begin
m_TabPos[i] := -1;
m_TabVisible[i] := true;
end;
end;
destructor TsuiTabControlTopPanel.Destroy;
begin
m_Tabs.Free();
m_Tabs := nil;
m_ActiveTab.Free();
m_InactiveTab.Free();
m_Line.Free();
inherited;
end;
procedure TsuiTabControlTopPanel.MouseDown(Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
i : Integer;
nLeft : Integer;
nRight : Integer;
begin
inherited;
if Button <> mbLeft then
Exit;
Repaint();
if m_InButtons = -1 then
Dec(m_Passed)
else if (m_InButtons = 1) and m_ShowButton then
Inc(m_Passed);
if m_InButtons <> 0 then
begin
if m_Passed < 0 then
m_Passed := 0;
if m_Passed > m_Tabs.Count then
m_Passed := m_Tabs.Count;
Repaint();
Exit;
end;
nRight := m_LeftMargin;
for i := m_Passed to m_Tabs.Count - 1 do
begin
if m_TabPos[i] = -1 then
break;
nLeft := nRight;
Inc(nRight, m_TabPos[i]);
if (X < nRight) and (X > nLeft) and (Y > 0) and (Y < m_TabHeight) then
begin
m_UserChanging := true;
TabIndex := i;
m_AutoFit := true;
Repaint();
m_AutoFit := false;
m_UserChanging := false;
break;
end;
end;
end;
procedure TsuiTabControlTopPanel.MouseMove(Shift: TShiftState; X,
Y: Integer);
begin
inherited;
if m_ShowButton then
Repaint();
end;
procedure TsuiTabControlTopPanel.OnTabsChange(Sender: TObject);
begin
Repaint();
end;
procedure TsuiTabControlTopPanel.Paint;
var
Buf : TBitmap;
begin
Buf := TBitmap.Create();
Buf.Width := Width;
Buf.Height := Height;
DoTrans(Buf.Canvas, m_TabControl);
m_InButtons := 0;
if m_AutoFit then
begin
while PaintTabs(Buf) < m_TabIndex do
begin
Inc(m_Passed);
PaintTabs(Buf);
end;
end
else
PaintTabs(Buf);
PaintButtons(Buf);
BitBlt(Canvas.Handle, 0, 0, Buf.Width, Buf.Height, Buf.Canvas.Handle, 0, 0, SRCCOPY);
Buf.Free();
end;
procedure TsuiTabControlTopPanel.PaintButtons(const Buf: TBitmap);
var
BtnBuf : TBitmap;
BtnRect : TRect;
MousePoint : TPoint;
OutUIStyle : TsuiUIStyle;
nLeft : Integer;
nTop : Integer;
nIndex : Integer;
begin
if (not m_ShowButton) and (m_Passed = 0) then
Exit;
GetCursorPos(MousePoint);
MousePoint := ScreenToClient(MousePoint);
m_InButtons := 0;
BtnBuf := TBitmap.Create();
BtnBuf.Transparent := true;
nLeft := Width - 2 - m_BtnSize.X;
if m_TabPosition = suiTop then
begin
if m_BtnSize.Y + 4 < Buf.Height then
nTop := (Buf.Height - m_BtnSize.Y) div 2 - 2
else
nTop := 0;
end
else
begin
if m_BtnSize.Y + 4 < Buf.Height then
nTop := (Buf.Height - m_BtnSize.Y) div 2 + 2
else
nTop := Buf.Height - m_BtnSize.Y;
end;
// Right Button
BtnRect := Rect(nLeft, nTop, Width - 2, nTop + m_BtnSize.Y);
if InRect(MousePoint, BtnRect) then
begin
nIndex := 2;
m_InButtons := 1;
end
else
nIndex := 1;
if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then
m_FileTheme.GetBitmap(SUI_THEME_SCROLLBUTTON_IMAGE, BtnBuf, 4, nIndex)
else
GetInsideThemeBitmap(OutUIStyle, SUI_THEME_SCROLLBUTTON_IMAGE, BtnBuf, 4, nIndex);
Buf.Canvas.Draw(nLeft, nTop, BtnBuf);
// Left Button
BtnRect := Rect(nLeft - m_BtnSize.X, nTop, nLeft, nTop + m_BtnSize.Y);
if InRect(MousePoint, BtnRect) then
begin
nIndex := 4;
m_InButtons := -1;
end
else
nIndex := 3;
if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then
m_FileTheme.GetBitmap(SUI_THEME_SCROLLBUTTON_IMAGE, BtnBuf, 4, nIndex)
else
GetInsideThemeBitmap(OutUIStyle, SUI_THEME_SCROLLBUTTON_IMAGE, BtnBuf, 4, nIndex);
Buf.Canvas.Draw(nLeft - m_BtnSize.X, nTop, BtnBuf);
BtnBuf.Free();
end;
function TsuiTabControlTopPanel.PaintTabs(const Buf: TBitmap) : Integer;
var
nLeft : Integer;
nWidth : Integer;
i : Integer;
nShowed : Integer;
R : TRect;
RightBorder : Integer;
RightBorder1, RightBorder2 : Integer;
OverRightBorder : Boolean;
ATrans, ITrans : Boolean;
ASampleTop, ISampleTop : Boolean;
T1, T2, T3, T4 : Integer;
begin
RightBorder1 := Width - 2 * m_BtnSize.X - 2;
RightBorder2 := Width - 10;
RightBorder := 0;
ASampleTop := true;
if m_ActiveTab.Canvas.Pixels[0, 0] = clFuchsia then
begin
ATrans := true;
end
else if m_ActiveTab.Canvas.Pixels[0, m_ActiveTab.Height - 1] = clFuchsia then
begin
ATrans := true;
ASampleTop := false;
end
else
ATrans := false;
ISampleTop := true;
if m_InactiveTab.Canvas.Pixels[0, 0] = clFuchsia then
begin
ITrans := true;
end
else if m_InactiveTab.Canvas.Pixels[0, m_InactiveTab.Height - 1] = clFuchsia then
begin
ITrans := true;
ISampleTop := false;
end
else
ITrans := false;
m_TabHeight := m_ActiveTab.Height;
if m_TabPosition = suiTop then
begin
Buf.Canvas.StretchDraw(
Rect(1, m_InactiveTab.Height, Width - 1, m_InactiveTab.Height + m_Line.Height),
m_Line
);
Buf.Canvas.Pen.Color := m_TabControl.BorderColor;
Buf.Canvas.MoveTo(0, m_InactiveTab.Height);
Buf.Canvas.LineTo(0, m_InactiveTab.Height + m_Line.Height);
Buf.Canvas.MoveTo(Width - 1, m_InactiveTab.Height);
Buf.Canvas.LineTo(Width - 1, m_InactiveTab.Height + m_Line.Height);
T1 := 0;
T2 := m_InactiveTab.Height;
T3 := T1 + 1;
T4 := T2 + 1;
end
else
begin
Buf.Canvas.StretchDraw(
Rect(1, 0, Width - 1, m_Line.Height),
m_Line
);
Buf.Canvas.Pen.Color := m_TabControl.BorderColor;
Buf.Canvas.MoveTo(0, 0);
Buf.Canvas.LineTo(0, m_Line.Height);
Buf.Canvas.MoveTo(Width - 1, 0);
Buf.Canvas.LineTo(Width - 1, m_Line.Height);
T1 := Height - m_InactiveTab.Height;
T2 := Height;
T3 := T1 - 1;
T4 := T2 - 1;
end;
nLeft := m_LeftMargin;
Buf.Canvas.Font := m_TabControl.Font;
nShowed := 0;
OverRightBorder := false;
Result := m_Tabs.Count - 1;
for i := 0 to m_Tabs.Count - 1 do
begin
if i = m_Tabs.Count - 1 then
RightBorder := RightBorder2
else
RightBorder := RightBorder1;
if not m_TabVisible[i] then
begin
m_TabPos[i] := 0;
continue;
end;
if OverRightBorder then
break;
if m_Tabs[i] <> '' then
nWidth := Buf.Canvas.TextWidth(m_Tabs[i]) + 20
else
nWidth := 80;
if nWidth < 15 then
nWidth := 15;
if i < SUI_TABCONTROL_MAXTABS - 1 then
m_TabPos[i] := nWidth;
Inc(nShowed);
if nShowed <= m_Passed then
continue;
if m_TabIndex = i then
begin
R := Rect(nLeft, T3, nWidth + nLeft, T4);
if R.Right > RightBorder then
begin
R.Right := RightBorder1;
OverRightBorder := true;
Result := i - 1;
end;
SpitDrawHorizontal(m_ActiveTab, Buf.Canvas, R, ATrans, ASampleTop);
end
else
begin
R := Rect(nLeft, T1, nWidth + nLeft, T2);
if R.Right > RightBorder then
begin
R.Right := RightBorder1;
m_TabPos[i] := R.Right - R.Left;
OverRightBorder := true;
Result := i - 1;
end;
SpitDrawHorizontal(m_InactiveTab, Buf.Canvas, R, ITrans, ISampleTop);
end;
Inc(nLeft, nWidth);
Buf.Canvas.Brush.Style := bsClear;
if OverRightBorder then
begin
R.Left := R.Left + 10;
R.Right := R.Right - 4;
DrawText(Buf.Canvas.Handle, PAnsiChar(m_Tabs[i]), -1, R, DT_SINGLELINE or DT_VCENTER);
end
else
DrawText(Buf.Canvas.Handle, PAnsiChar(m_Tabs[i]), -1, R, DT_CENTER or DT_SINGLELINE or DT_VCENTER);
end;
if ((nLeft > RightBorder) or OverRightBorder) and (m_Tabs.Count <> 0) then
m_ShowButton := true
else
m_ShowButton := false;
end;
procedure TsuiTabControlTopPanel.RequestAlign;
var
R : TRect;
begin
if m_TabControl <> nil then
begin
if m_TabPosition = suiTop then
R := Rect(0, 0, m_TabControl.Width, Height)
else
R := Rect(0, m_TabControl.Height - Height, m_TabControl.Width, m_TabControl.Height);
PlaceControl(self, R);
end
else
inherited;
end;
procedure TsuiTabControlTopPanel.Resize;
begin
inherited;
if m_TabControl <> nil then
begin
if m_TabPosition = suiTop then
SetBounds(0, 0, m_TabControl.Width, Height)
else
begin
Top := m_TabControl.Height - Height;
Left := 0;
Width := m_TabControl.Width;
end;
end;
end;
procedure TsuiTabControlTopPanel.SetFileTheme(const Value: TsuiFileTheme);
begin
m_FileTheme := Value;
SetUIStyle(m_UIStyle);
end;
procedure TsuiTabControlTopPanel.SetLeftMargin(const Value: Integer);
begin
m_LeftMargin := Value;
Repaint();
end;
procedure TsuiTabControlTopPanel.SetTabIndex(const Value: Integer);
var
bAllow : Boolean;
begin
if m_TabIndex = Value then
Exit;
if m_Tabs.Count = 0 then
begin
m_TabIndex := -1;
Repaint();
Exit;
end;
if (
(Value < -1) or
(Value > m_Tabs.Count -1)
) then
begin
Repaint();
Exit;
end;
if m_UserChanging then
begin
bAllow := true;
if Assigned(m_TabControl.m_OnChanging) then
m_TabControl.m_OnChanging(m_TabControl, bAllow);
if not bAllow then
Exit;
end;
m_TabIndex := Value;
m_AutoFit := true;
Repaint();
m_AutoFit := false;
m_TabControl.TabActive(m_TabIndex);
end;
procedure TsuiTabControlTopPanel.SetTabPosition(const Value: TsuiTabPosition);
begin
if m_TabPosition = Value then
Exit;
m_TabPosition := Value;
RoundPicture2(m_ActiveTab);
RoundPicture2(m_InactiveTab);
RoundPicture2(m_Line);
Repaint();
end;
procedure TsuiTabControlTopPanel.SetTabs(const Value: TStrings);
begin
m_Tabs.Assign(Value);
end;
procedure TsuiTabControlTopPanel.SetUIStyle(const Value: TsuiUIStyle);
var
BtnBitmap : TBitmap;
OutUIStyle : TsuiUIStyle;
begin
m_UIStyle := Value;
BtnBitmap := TBitmap.Create();
if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then
begin
m_FileTheme.GetBitmap(SUI_THEME_TABCONTROL_TAB_IMAGE, m_ActiveTab, 2, 1);
m_FileTheme.GetBitmap(SUI_THEME_TABCONTROL_TAB_IMAGE, m_InactiveTab, 2, 2);
m_FileTheme.GetBitmap(SUI_THEME_TABCONTROL_BAR_IMAGE, m_Line);
m_FileTheme.GetBitmap(SUI_THEME_SCROLLBUTTON_IMAGE, BtnBitmap, 4, 1);
end
else
begin
GetInsideThemeBitmap(OutUIStyle, SUI_THEME_TABCONTROL_TAB_IMAGE, m_ActiveTab, 2, 1);
GetInsideThemeBitmap(OutUIStyle, SUI_THEME_TABCONTROL_TAB_IMAGE, m_InactiveTab, 2, 2);
GetInsideThemeBitmap(OutUIStyle, SUI_THEME_TABCONTROL_BAR_IMAGE, m_Line);
GetInsideThemeBitmap(OutUIStyle, SUI_THEME_SCROLLBUTTON_IMAGE, BtnBitmap, 4, 1);
end;
if m_TabPosition = suiBottom then
begin
RoundPicture2(m_ActiveTab);
RoundPicture2(m_InactiveTab);
RoundPicture2(m_Line);
end;
Height := m_ActiveTab.Height + m_Line.Height;
m_BtnSize.X := BtnBitmap.Width;
m_BtnSize.Y := BtnBitmap.Height;
BtnBitmap.Free();
Repaint();
end;
procedure TsuiTabControlTopPanel.WMERASEBKGND(var Msg: TMessage);
begin
// do nothing
end;
function TsuiTab.GetLeftMargin: Integer;
begin
Result := m_TopPanel.LeftMargin;
end;
function TsuiTab.GetTabIndex: Integer;
begin
Result := m_TopPanel.TabIndex;
end;
function TsuiTab.GetTabs: TStrings;
begin
Result := m_TopPanel.Tabs;
end;
procedure TsuiTab.Paint;
var
R : TRect;
begin
Canvas.Brush.Color := Color;
if m_TabPosition = suiTop then
R := Rect(ClientRect.Left, m_TopPanel.Height, ClientRect.Right, ClientRect.Bottom)
else
R := Rect(ClientRect.Left, 0, ClientRect.Right, ClientRect.Bottom - m_TopPanel.Height);
Canvas.FillRect(R);
Canvas.Pen.Color := m_BorderColor;
if m_TabPosition = suiTop then
begin
Canvas.MoveTo(0, R.Top - 1);
Canvas.LineTo(0, R.Bottom - 1);
Canvas.LineTo(R.Right - 1, R.Bottom - 1);
Canvas.LineTo(R.Right - 1, R.Top - 1);
end
else
begin
Canvas.MoveTo(R.Right - 1, R.Bottom - 1);
Canvas.LineTo(R.Right - 1, R.Top);
Canvas.LineTo(0, R.Top);
Canvas.LineTo(0, R.Bottom);
end;
end;
procedure TsuiTab.SetBorderColor(const Value: TColor);
begin
m_BorderColor := Value;
BorderColorChanged();
Repaint();
m_TopPanel.Repaint();
end;
procedure TsuiTab.SetFont(const Value: TFont);
begin
m_Font.Assign(Value);
m_TopPanel.Repaint();
end;
procedure TsuiTab.SetLeftMargin(const Value: Integer);
begin
m_TopPanel.LeftMargin := Value;
end;
procedure TsuiTab.SetTabIndex(const Value: Integer);
begin
m_TopPanel.TabIndex := Value;
end;
procedure TsuiTab.SetTabs(const Value: TStrings);
begin
m_TopPanel.Tabs := Value;
end;
procedure TsuiTab.SetUIStyle(const Value: TsuiUIStyle);
var
OutUIStyle : TsuiUIStyle;
begin
m_UIStyle := Value;
m_TopPanel.FileTheme := m_FileTheme;
m_TopPanel.UIStyle := m_UIStyle;
m_TopPanel.Repaint();
UpdateUIStyle(m_UIStyle, m_FileTheme);
if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then
begin
m_TopPanel.Color := m_FileTheme.GetColor(SUI_THEME_CONTROL_BACKGROUND_COLOR);
m_BorderColor := m_FileTheme.GetColor(SUI_THEME_CONTROL_BORDER_COLOR);
Color := m_FileTheme.GetColor(SUI_THEME_CONTROL_BACKGROUND_COLOR);
end
else
begin
m_TopPanel.Color := GetInsideThemeColor(OutUIStyle, SUI_THEME_CONTROL_BACKGROUND_COLOR);
m_BorderColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_CONTROL_BORDER_COLOR);
if {$IFDEF RES_WINXP}m_UIStyle <> WinXP{$ELSE} True {$ENDIF} then
Color := GetInsideThemeColor(OutUIStyle, SUI_THEME_CONTROL_BACKGROUND_COLOR)
else
Color := clWhite;
end;
Repaint();
end;
procedure TsuiTab.UpdateUIStyle(UIStyle: TsuiUIStyle; FileTheme : TsuiFileTheme);
begin
ContainerApplyUIStyle(self, UIStyle, FileTheme);
end;
constructor TsuiTab.Create(AOwner: TComponent);
begin
inherited;
m_TopPanel := CreateTopPanel();
m_TopPanel.Parent := self;
m_TopPanel.OnClick := TopPanelClick;
m_TopPanel.OnDblClick := TopPanelDblClick;
m_TabPosition := suiTop;
m_Font := TFont.Create();
Caption := ' ';
BevelInner := bvNone;
BevelOuter := bvNone;
BorderWidth := 0;
Height := 80;
UIStyle := GetSUIFormStyle(AOwner);
m_TopPanel.SetBounds(0, 0, Width, m_TopPanel.Height);
end;
destructor TsuiTab.Destroy;
begin
m_Font.Free();
m_Font := nil;
m_TopPanel.Free();
m_TopPanel := nil;
inherited;
end;
{ TsuiTabControl }
function TsuiTabControl.CreateTopPanel: TsuiTabControlTopPanel;
begin
Result := TsuiTabControlTopPanel.Create(self, self);
end;
procedure TsuiTab.TabActive(TabIndex : Integer);
begin
if not (csLoading in ComponentState) then
begin
if Assigned(m_OnTabActive) then
m_OnTabActive(self, TabIndex);
if Assigned(m_OnChange) then
m_OnChange(self);
end;
end;
procedure TsuiTab.BorderColorChanged;
begin
// do nothing
end;
procedure TsuiTab.CMCursorChanged(var Message: TMessage);
begin
m_TopPanel.Cursor := Cursor;
inherited;
end;
procedure TsuiTab.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (
(Operation = opRemove) and
(AComponent = m_FileTheme)
)then
begin
m_FileTheme := nil;
SetUIStyle(SUI_THEME_DEFAULT);
end;
end;
procedure TsuiTab.SetFileTheme(const Value: TsuiFileTheme);
begin
m_FileTheme := Value;
SetUIStyle(m_UIStyle);
end;
procedure TsuiTab.AlignControls(AControl: TControl; var Rect: TRect);
begin
if m_TabPosition = suiTop then
begin
Rect.Left := Rect.Left + 3;
Rect.Right := Rect.Right - 3;
Rect.Bottom := Rect.Bottom - 3;
Rect.Top := Rect.Top + m_TopPanel.Height + 3;
end
else
begin
Rect.Left := Rect.Left + 3;
Rect.Right := Rect.Right - 3;
Rect.Top := Rect.Top + 3;
Rect.Bottom := Rect.Bottom - m_TopPanel.Height - 3;
end;
inherited AlignControls(AControl, Rect);
end;
procedure TsuiTab.Resize;
begin
inherited;
if m_TabPosition = suiTop then
m_TopPanel.SetBounds(0, 0, Width, m_TopPanel.Height)
else
begin
m_TopPanel.Top := Height - m_TopPanel.Height;
m_TopPanel.Left := 0;
m_TopPanel.Width := Width;
end;
end;
procedure TsuiTab.WMERASEBKGND(var Message: TMessage);
begin
// do nothing
end;
procedure TsuiTab.TopPanelClick(Sender: TObject);
begin
if Assigned(OnClick) then
OnClick(self);
end;
procedure TsuiTab.TopPanelDblClick(Sender: TObject);
begin
if Assigned(OnDblClick) then
OnDblClick(self);
end;
procedure TsuiTab.SetTabPosition(const Value: TsuiTabPosition);
begin
if m_TabPosition = Value then
Exit;
m_TabPosition := Value;
m_TopPanel.TabPosition := Value;
m_TopPanel.RequestAlign();
Realign();
end;
end.
|
unit uNR_chaveseg;
{
ResourceString: Dario 13/03/13
}
interface
uses sysutils, classes, md5, SyncObjs, Windows;
type
Tchaves = class
private
FItens : TStrings;
FCS : TCriticalSection;
procedure DeletaChavesAntigas;
public
constructor Create;
destructor Destroy;
function NovaChave: String;
function ValidaChave(aChave, aSenha: String): Boolean;
end;
function gerasenhaseg(achave: string): string;
procedure InicializaGChaves;
var
gChaves : TChaves;
implementation
function gerasenhaseg(achave: string): string;
begin
Result := getmd5str('>LKHASDIUywefd7kdsf_)(*!@Tkjhasfdkxzxxx7777!38213zxc%nbv'+aChave); // do not localize
end;
procedure InicializaGChaves;
begin
if gChaves=nil then gChaves := TChaves.Create;
end;
{ Tchaves }
constructor Tchaves.Create;
begin
FCS := TCriticalSection.Create;
FItens := TStringList.Create;
end;
procedure Tchaves.DeletaChavesAntigas;
var Corte : Cardinal;
begin
Corte := GetTickCount - 120000;
while (FItens.Count>0) and (Cardinal(FItens.Objects[0])<Corte) do FItens.Delete(0);
end;
destructor Tchaves.Destroy;
begin
FItens.Free;
FCS.Free;
inherited;
end;
function Tchaves.NovaChave: String;
begin
Result := IntToStr(Random(High(Integer))) + IntToStr(Random(High(Integer)));
FCS.Enter;
try
DeletaChavesAntigas;
FItens.AddObject(Result, TObject(GetTickCount));
finally
FCS.Leave;
end;
end;
function Tchaves.ValidaChave(aChave, aSenha: String): Boolean;
var I : Integer;
begin
Result := False;
FCS.Enter;
try
DeletaChavesAntigas;
I := FItens.IndexOf(aChave);
if I>=0 then FItens.Delete(I);
Result := (I>=0) and (aSenha=GeraSenhaSeg(aChave));
finally
FCS.Leave;
end;
end;
initialization
Randomize;
gChaves := nil;
finalization
if Assigned(gChaves) then
FreeAndNil(gChaves);
end.
|
{ Copyright (C) 1998-2008, written by Mike Shkolnik, Scalabium Software
E-Mail: mshkolnik@scalabium
WEB: http://www.scalabium.com
Const strings for localization freeware SMComponent library}
{translation by
- sam francke s.j.francke@hccnet.nl
- Martijn Terwoert www.smarty.nl
- Hubert Duijvewaardt <hubert@compsol.be> }
unit SMCnst;
interface
{Dutch strings}
const
strMessage = 'Print...';
strSaveChanges = 'Wilt u werkelijk de veranderingen bewaren op de Database Server?';
strErrSaveChanges = 'Kan data niet bewaren ! Check Server verbinding of validate de data.';
strDeleteWarning = 'Wilt u werkelijk tabel %s verwijderen ?';
strEmptyWarning = 'Wilt u werkelijk tabel %s leegmaken?';
const
PopUpCaption: array [0..24] of string[33] =
('Record toevoegen',
'Record invoegen',
'Wijzig record',
'Verwijder record',
'-',
'Print ...',
'Export ...',
'Filter ...',
'Zoeken ...',
'-',
'Bewaar veranderingen',
'Doe veranderingen teniet',
'Verversen',
'-',
'Selecteer/Deselecteer records',
'Selecteer record',
'Selecteer alle records',
'-',
'Deselecteer record',
'Deselecteer alle records',
'-',
'Bewaar kolom layout',
'Herstel kolom layout',
'-',
'Setup...');
const //for TSMSetDBGridDialog
SgbTitle = ' titel ';
SgbData = ' gegevens ';
STitleCaption = 'kop:';
STitleAlignment = 'uitlijnen:';
STitleColor = 'achtergrond:';
STitleFont = 'font:';
SWidth = 'breedte:';
SWidthFix = 'letters';
SAlignLeft = 'links uitlijnen';
SAlignRight = 'rechts uitlijnen';
SAlignCenter = 'centreren';
const //for TSMDBFilterDialog
strEqual = 'gelijk';
strNonEqual = 'niet gelijk';
strNonMore = 'niet groter';
strNonLess = 'niet minder';
strLessThan = 'minder dan';
strLargeThan = 'groter dan';
strExist = 'leeg';
strNonExist = 'niet leeg';
strIn = 'in lijst';
strBetween = 'tussen';
strLike = 'zelfde';
strOR = 'of';
strAND = 'en';
strField = 'Veld';
strCondition = 'Conditie';
strValue = 'Waarde';
strAddCondition = ' Stel aanvullende condities in:';
strSelection = ' Selecteer de records volgens deze condities:';
strAddToList = 'Toevoegen aan lijst';
strEditInList = 'Bewerken in lijst';
strDeleteFromList = 'Delete van lijst';
strTemplate = 'Filter template dialoog';
strFLoadFrom = 'Openen...';
strFSaveAs = 'Opslaan als..';
strFDescription = 'Beschrijving';
strFFileName = 'Bestands naam';
strFCreate = 'Gemaakt: %s';
strFModify = 'Aangepast: %s';
strFProtect = 'Beveilig tegen overschrijven';
strFProtectErr = 'Bestand is beveiligd!';
const //for SMDBNavigator
SFirstRecord = 'eerste record';
SPriorRecord = 'vorige record';
SNextRecord = 'volgende record';
SLastRecord = 'laatste record';
SInsertRecord = 'voeg record in';
SCopyRecord = 'kopieer record';
SDeleteRecord = 'verwijder record';
SEditRecord = 'wijzig record';
SFilterRecord = 'filter voorwaarden';
SFindRecord = 'zoek het record';
SPrintRecord = 'print de records';
SExportRecord = 'exporteer de records';
SImportRecord = 'importeer de records';
SPostEdit = 'bewaar veranderingen';
SCancelEdit = 'doe veranderingen teniet';
SRefreshRecord = 'ververs data';
SChoice = 'kies record';
SClear = 'Clear record keuze';
SDeleteRecordQuestion = 'verwijder record?';
SDeleteMultipleRecordsQuestion = 'alle geselecteerde records verwijderen?';
SRecordNotFound = 'geen record gevonden';
SFirstName = 'eerste';
SPriorName = 'vorige';
SNextName = 'volgende';
SLastName = 'laatste';
SInsertName = 'invoegen';
SCopyName = 'kopieer';
SDeleteName = 'verwijder';
SEditName = 'wijzig';
SFilterName = 'filter';
SFindName = 'vind';
SPrintName = 'print';
SExportName = 'export';
SImportName = 'import';
SPostName = 'bewaar';
SCancelName = 'afbreken';
SRefreshName = 'ververs';
SChoiceName = 'kies';
SClearName = 'maak leeg';
SBtnOk = 'OK';
SBtnCancel = 'annuleren';
SBtnLoad = 'openen';
SBtnSave = 'opslaan';
SBtnCopy = 'kopieren';
SBtnPaste = 'plakken';
SBtnClear = 'Clear';
SRecNo = 'rec.';
SRecOf = ' van ';
const //for EditTyped
etValidNumber = 'geldig nummer';
etValidInteger = 'geldig integer nummer';
etValidDateTime = 'geldige datum/tijd';
etValidDate = 'geldige datum';
etValidTime = 'geldige tijd';
etValid = 'geldig(e)';
etIsNot = 'is geen';
etOutOfRange = 'waarde %s buiten bereik %s..%s';
SApplyAll = 'Toepassen op Alle';
SNoDataToDisplay = '<No data to display>';
implementation
end.
|
unit U_LogObject;
interface
uses
Classes, System.SyncObjs, Winapi.Windows, SysUtils,
System.DateUtils, Vcl.Forms, Winapi.SHFolder, CodeSiteLogging;
type
ILoggerInterface = interface(IInterface)
['{076BB521-F79C-4991-A5E8-3F50CE0E1CA2}']
Function GetLogFileName(): String;
procedure SetActive(aValue: Boolean);
Function GetActive: Boolean;
procedure LogText(Action, MessageTxt: String);
property LogFile: String read GetLogFileName;
Property Active: Boolean read GetActive write SetActive;
end;
TLogComponent = class(TInterfacedObject, ILoggerInterface)
private
FCriticalSection: TCriticalSection;
fOurLogFile: String;
fActive: Boolean;
procedure SetActive(aValue: Boolean);
Function GetActive: Boolean;
Function GetLogFileName(): String;
Function ThePurge: String;
Function RightPad(S: string; ch: char; Len: Integer): string;
public
constructor Create();
destructor Destroy; override;
procedure LogText(Action, MessageTxt: String);
property LogFile: String read GetLogFileName;
Property Active: Boolean read GetActive write SetActive;
end;
function LogInterface: ILoggerInterface;
implementation
var
fLogInterface: ILoggerInterface;
function LogInterface: ILoggerInterface;
begin
if not Assigned(fLogInterface) then
TLogComponent.Create.GetInterface(ILoggerInterface, fLogInterface);
fLogInterface.QueryInterface(ILoggerInterface, Result);
end;
constructor TLogComponent.Create();
begin
inherited Create();
FCriticalSection := TCriticalSection.Create;
end;
destructor TLogComponent.Destroy;
begin
FCriticalSection.Free;
inherited Destroy;
end;
function TLogComponent.GetLogFileName(): String;
Var
OurLogFile, LocalOnly, AppDir, AppName: string;
// ******************************************************************
// Finds the users special directory
// ******************************************************************
function LocalAppDataPath: string;
const
SHGFP_TYPE_CURRENT = 0;
var
path: array [0 .. MAX_PATH] of char;
begin
SHGetFolderPath(0, CSIDL_LOCAL_APPDATA, 0, SHGFP_TYPE_CURRENT, @path[0]);
Result := StrPas(path);
end;
begin
if Trim(fOurLogFile) <> '' then
Result := fOurLogFile
else
begin
OurLogFile := LocalAppDataPath;
if (Copy(OurLogFile, Length(OurLogFile), 1) <> '\') then
OurLogFile := OurLogFile + '\';
LocalOnly := OurLogFile;
// Now set the application level
OurLogFile := OurLogFile + ExtractFileName(Application.ExeName);
if (Copy(OurLogFile, Length(OurLogFile), 1) <> '\') then
OurLogFile := OurLogFile + '\';
AppDir := OurLogFile;
// try to create or use base direcrtory
if not DirectoryExists(AppDir) then
if not ForceDirectories(AppDir) then
OurLogFile := LocalOnly;
// Get the application name
AppName := ExtractFileName(Application.ExeName);
AppName := Copy(AppName, 0, Pos('.', AppName) - 1);
OurLogFile := OurLogFile + AppName + '_' + IntToStr(GetCurrentProcessID) +
'_' + FormatDateTime('mm_dd_yy_hh_mm', now) + '_JawsLog.TXT';
fOurLogFile := OurLogFile;
Result := OurLogFile;
end;
end;
procedure TLogComponent.LogText(Action, MessageTxt: string);
const
PadLen: Integer = 18;
VAR
AddText: TStringList;
X: Integer;
TextToAdd, Suffix, Suffix2: String;
myFile: TextFile;
begin
if not fActive then
exit;
Action := RightPad(Action, ' ', 11);
FCriticalSection.Acquire;
try
// Clean the old dir on first run
if Trim(fOurLogFile) = '' then
TextToAdd := ThePurge + TextToAdd;
// This should never be blank
if fOurLogFile = '' then
fOurLogFile := GetLogFileName;
if Trim(fOurLogFile) = '' then
fOurLogFile := GetLogFileName;
AddText := TStringList.Create;
try
AddText.Text := MessageTxt;
Suffix := FormatDateTime('hh:mm:ss', now) + ' [' +
UpperCase(Action) + ']';
if AddText.Count > 1 then
begin
Suffix2 := FormatDateTime('hh:mm:ss', now) + ' [' +
StringOfChar('^', Length(Action)) + ']';
for X := 1 to AddText.Count - 1 do
AddText.Strings[X] := Suffix2.PadRight(PadLen) + ' - ' +
AddText.Strings[X];
end;
TextToAdd := Suffix.PadRight(PadLen) + ' - ' + Trim(AddText.Text);
// Asign our file
AssignFile(myFile, fOurLogFile);
if FileExists(fOurLogFile) then
Append(myFile)
else
ReWrite(myFile);
// Write this final line
WriteLn(myFile, TextToAdd);
CloseFile(myFile);
finally
AddText.Free;
end;
finally
FCriticalSection.Release;
end;
end;
Function TLogComponent.ThePurge: String;
const
aFileMask = '*_JawsLog.txt';
var
searchResult: TSearchRec;
iDelCnt, iErrorCnt, iFile: Integer;
dtFileDate, dtNow: TDateTime;
sFilePath: string;
begin
// Init variables
iDelCnt := 0;
iErrorCnt := 0;
dtNow := Date;
sFilePath := ExtractFilePath(GetLogFileName);
// Loop through dir looking for the files
iFile := FindFirst(sFilePath + aFileMask, faAnyFile, searchResult);
while iFile = 0 do
begin
// Make sure we are on a file and not a directory
if (searchResult.Name <> '.') and (searchResult.Name <> '..') and
((searchResult.Attr and faDirectory) <> faDirectory) then
begin
// Check the date of the file
{$IFDEF VER180}
dtFileDate := searchResult.Time;
{$ELSE}
dtFileDate := searchResult.TimeStamp;
{$ENDIF}
if trunc(dtNow - dtFileDate) + 1 > 60 then
begin
// Try to delete and update the count as needed
if not SysUtils.DeleteFile(sFilePath + searchResult.Name) then
Inc(iErrorCnt)
else
Inc(iDelCnt);
end;
end;
// Grab the next file
iFile := FindNext(searchResult);
end;
// Free up memory allocation
SysUtils.FindClose(searchResult);
// If any files were purged or errored then add this to the return message
if (iErrorCnt > 0) or (iDelCnt > 0) then
begin
Result := (StringOfChar(' ', 15) + 'Log Purge Information');
Result := Result + #13#10 + (RightPad('', '=', 50));
Result := Result + #13#10 + (RightPad('Days', ' ', 10) + ': ' +
IntToStr(60));
Result := Result + #13#10 + (RightPad('Purged', ' ', 10) + ': ' +
IntToStr(iDelCnt));
Result := Result + #13#10 + (RightPad('NA', ' ', 10) + ': ' +
IntToStr(iErrorCnt));
Result := Result + #13#10 + #13#10;
end
else
Result := '';
end;
function TLogComponent.RightPad(S: string; ch: char; Len: Integer): string;
var
RestLen: Integer;
begin
Result := S;
RestLen := Len - Length(S);
if RestLen < 1 then
exit;
Result := S + StringOfChar(ch, RestLen);
end;
procedure TLogComponent.SetActive(aValue: Boolean);
begin
fActive := aValue;
end;
Function TLogComponent.GetActive: Boolean;
begin
Result := fActive;
end;
end.
|
unit FIToolkit.Reports.Parser.Types;
interface
uses
System.SysUtils, System.Generics.Defaults;
type
TFixInsightMessageType = (fimtUnknown, fimtWarning, fimtOptimization, fimtCodingConvention, fimtFatal, fimtTrial);
TFixInsightMessage = record
private
type
IFixInsightMessageComparer = IComparer<TFixInsightMessage>;
strict private
FColumn,
FLine : Integer;
FFileName,
FFullFileName : TFileName;
FID,
FText : String;
FMsgType : TFixInsightMessageType;
private
function GetMsgTypeByID(const MsgID : String) : TFixInsightMessageType;
public
class function GetComparer : IFixInsightMessageComparer; static;
constructor Create(const AFileName : TFileName; ALine, AColumn : Integer; const AID, AText : String); overload;
constructor Create(const AFileName, AFullFileName : TFileName; ALine, AColumn : Integer;
const AID, AText : String); overload;
property Column : Integer read FColumn;
property FileName : TFileName read FFileName;
property FullFileName : TFileName read FFullFileName;
property ID : String read FID;
property Line : Integer read FLine;
property MsgType : TFixInsightMessageType read FMsgType;
property Text : String read FText;
end;
implementation
uses
System.RegularExpressions, System.Types, System.Math,
FIToolkit.Commons.Utils,
FIToolkit.Reports.Parser.Consts;
{ TFixInsightMessage }
constructor TFixInsightMessage.Create(const AFileName : TFileName; ALine, AColumn : Integer; const AID, AText : String);
begin
FFileName := AFileName;
FLine := ALine;
FColumn := AColumn;
FID := AID;
FText := AText;
FMsgType := GetMsgTypeByID(FID);
end;
constructor TFixInsightMessage.Create(const AFileName, AFullFileName : TFileName; ALine, AColumn : Integer;
const AID, AText : String);
begin
Create(AFileName, ALine, AColumn, AID, AText);
FFullFileName := AFullFileName;
end;
class function TFixInsightMessage.GetComparer : IFixInsightMessageComparer;
begin
Result := TComparer<TFixInsightMessage>.Construct(
function (const Left, Right : TFixInsightMessage) : Integer
begin
if Left.FullFileName.IsEmpty or Right.FullFileName.IsEmpty then
Result := AnsiCompareText(Left.FileName, Right.FileName)
else
Result := AnsiCompareText(Left.FullFileName, Right.FullFileName);
if Result = EqualsValue then
Result := CompareValue(Left.Line, Right.Line);
if Result = EqualsValue then
Result := CompareValue(Left.Column, Right.Column);
end
);
end;
function TFixInsightMessage.GetMsgTypeByID(const MsgID : String) : TFixInsightMessageType;
var
MT : TFixInsightMessageType;
begin
Result := fimtUnknown;
for MT := Low(TFixInsightMessageType) to High(TFixInsightMessageType) do
if (MT <> fimtUnknown) and TRegEx.IsMatch(MsgID, ARR_MSGTYPE_TO_MSGID_REGEX_MAPPING[MT]) then
Exit(MT);
end;
end.
|
unit ClientMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Corba, StdCtrls, Account_I, Account_C;
type
TForm1 = class(TForm)
Button1: TButton;
Label1: TLabel;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ private declarations }
protected
{ protected declarations }
Acct : Account;
myArray : ArrayType;
procedure InitCorba;
public
{ public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.InitCorba;
begin
CorbaInitialize;
Acct := TAccountHelper.bind;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
j: Integer;
begin
InitCorba;
for j := 0 to 2 do
myArray[j] := (j + 1) * 100;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Label1.Caption := FormatFloat('Balance = $#,##0.00', Acct.balance(myArray));
end;
end. |
unit amqp.consumer;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
{$INCLUDE config.inc}
interface
uses {$IFNDEF FPC}
{$IFDEF _WIN32}
Net.Winsock2,
{$ELSE}
Net.SocketAPI,
{$ENDIF}
{$ELSE}
Winsock2,
{$ENDIF}
amqp.mem, amqp.table, amqp.socket, AMQP.Types;
function amqp_consume_message(Astate : Pamqp_connection_state;
out Aenvelope : Tamqp_envelope;
const Atimeout: Ptimeval;
Aflags: int ):Tamqp_rpc_reply;
function amqp_read_message(state : Pamqp_connection_state;
channel : amqp_channel_t;
out Amessage : Tamqp_message;
flags: int):Tamqp_rpc_reply;
function amqp_basic_consume( state : Pamqp_connection_state;
channel : amqp_channel_t;
queue, consumer_tag : Tamqp_bytes;
no_local, no_ack, exclusive : amqp_boolean_t;
arguments : Tamqp_table): Pamqp_basic_consume_ok;
implementation
function amqp_basic_consume( state : Pamqp_connection_state;
channel : amqp_channel_t;
queue, consumer_tag : Tamqp_bytes;
no_local, no_ack, exclusive : amqp_boolean_t;
arguments : Tamqp_table): Pamqp_basic_consume_ok;
var
req : Tamqp_basic_consume;
begin
req.ticket := 0;
req.queue := queue;
req.consumer_tag := consumer_tag;
req.no_local := no_local;
req.no_ack := no_ack;
req.exclusive := exclusive;
req.nowait := 0;
req.arguments := arguments;
Result := amqp_simple_rpc_decoded(state, channel, AMQP_BASIC_CONSUME_METHOD,
AMQP_BASIC_CONSUME_OK_METHOD, @req);
end;
function amqp_consume_message(Astate : Pamqp_connection_state;
out Aenvelope : Tamqp_envelope;
const Atimeout: Ptimeval; Aflags: int):Tamqp_rpc_reply;
var
res : integer;
Lframe : Tamqp_frame;
delivery_method : Pamqp_basic_deliver;
ret : Tamqp_rpc_reply;
label error_out1;
label error_out2;
begin
memset(ret, 0, sizeof(ret));
memset(Aenvelope, 0, sizeof(Tamqp_envelope));
res := amqp_simple_wait_frame_noblock(Astate, Lframe, Atimeout);
if Int(AMQP_STATUS_OK) <> res then
begin
ret.reply_type := AMQP_RESPONSE_LIBRARY_EXCEPTION;
ret.library_error := res;
goto error_out1;
end;
if (AMQP_FRAME_METHOD <> Lframe.frame_type) or
(AMQP_BASIC_DELIVER_METHOD <> Lframe.payload.method.id) then
begin
amqp_put_back_frame(Astate, @Lframe);
ret.reply_type := AMQP_RESPONSE_LIBRARY_EXCEPTION;
ret.library_error := Int(AMQP_STATUS_UNEXPECTED_STATE);
goto error_out1;
end;
delivery_method := Pamqp_basic_deliver(Lframe.payload.method.decoded);
Aenvelope.channel := Lframe.channel;
Aenvelope.consumer_tag := (@delivery_method.consumer_tag);
Aenvelope.exchange := (@delivery_method.exchange);
Aenvelope.routing_key := (@delivery_method.routing_key);
Aenvelope.delivery_tag := delivery_method.delivery_tag;
Aenvelope.redelivered := delivery_method.redelivered;
if (Aenvelope.consumer_tag.malloc_dup_failed > 0) or
(Aenvelope.exchange.malloc_dup_failed > 0) or
(Aenvelope.routing_key.malloc_dup_failed > 0) then
begin
ret.reply_type := AMQP_RESPONSE_LIBRARY_EXCEPTION;
ret.library_error := Int(AMQP_STATUS_NO_MEMORY);
goto error_out2;
end;
ret := amqp_read_message(Astate, Aenvelope.channel, Aenvelope.message, 0);
if AMQP_RESPONSE_NORMAL <> ret.reply_type then
begin
goto error_out2;
end;
ret.reply_type := AMQP_RESPONSE_NORMAL;
Exit(ret);
error_out2:
Aenvelope.routing_key.Destroy;
Aenvelope.exchange.Destroy;
Aenvelope.consumer_tag.Destroy;
error_out1:
Result := ret;
end;
function amqp_read_message(state : Pamqp_connection_state;
channel : amqp_channel_t;
out Amessage : Tamqp_message; flags: int):Tamqp_rpc_reply;
var
frame : Tamqp_frame;
ret : Tamqp_rpc_reply;
body_read : size_t;
body_read_ptr : PAMQPChar;
res : integer;
label error_out1;
label error_out2;
label error_out3;
begin
memset(ret, 0, sizeof(ret));
memset(Amessage, 0, sizeof( Tamqp_message));
res := amqp_simple_wait_frame_on_channel(state, channel, frame);
if Int(AMQP_STATUS_OK) <> res then
begin
ret.reply_type := AMQP_RESPONSE_LIBRARY_EXCEPTION;
ret.library_error := res;
goto error_out1;
end;
if frame.frame_type <> AMQP_FRAME_HEADER then
begin
if (AMQP_FRAME_METHOD = frame.frame_type) and
( (AMQP_CHANNEL_CLOSE_METHOD = frame.payload.method.id) or
(AMQP_CONNECTION_CLOSE_METHOD = frame.payload.method.id) ) then
begin
ret.reply_type := AMQP_RESPONSE_SERVER_EXCEPTION;
ret.reply := frame.payload.method;
end
else
begin
ret.reply_type := AMQP_RESPONSE_LIBRARY_EXCEPTION;
ret.library_error := Int(AMQP_STATUS_UNEXPECTED_STATE);
amqp_put_back_frame(state, @frame);
end;
goto error_out1;
end;
//init_amqp_pool(@Amessage.pool, 4096);
Amessage.pool.Create(4096);
res := Pamqp_basic_properties(frame.payload.properties.decoded)^.clone(
Amessage.properties, @Amessage.pool);
if Int(AMQP_STATUS_OK) <> res then
begin
ret.reply_type := AMQP_RESPONSE_LIBRARY_EXCEPTION;
ret.library_error := res;
goto error_out3;
end;
if 0 = frame.payload.properties.body_size then
begin
Amessage.body := amqp_empty_bytes;
end
else
begin
if SIZE_MAX < frame.payload.properties.body_size then
begin
ret.reply_type := AMQP_RESPONSE_LIBRARY_EXCEPTION;
ret.library_error := Int(AMQP_STATUS_NO_MEMORY);
goto error_out1;
end;
Amessage.body := Tamqp_bytes.Create(size_t(frame.payload.properties.body_size));
if nil = Amessage.body.bytes then
begin
ret.reply_type := AMQP_RESPONSE_LIBRARY_EXCEPTION;
ret.library_error := Int(AMQP_STATUS_NO_MEMORY);
goto error_out1;
end;
end;
body_read := 0;
body_read_ptr := Amessage.body.bytes;
while body_read < Amessage.body.len do
begin
res := amqp_simple_wait_frame_on_channel(state, channel, &frame);
if Int(AMQP_STATUS_OK) <> res then
begin
ret.reply_type := AMQP_RESPONSE_LIBRARY_EXCEPTION;
ret.library_error := res;
goto error_out2;
end;
if AMQP_FRAME_BODY <> frame.frame_type then
begin
if (AMQP_FRAME_METHOD = frame.frame_type ) and
( (AMQP_CHANNEL_CLOSE_METHOD = frame.payload.method.id) or
(AMQP_CONNECTION_CLOSE_METHOD = frame.payload.method.id)) then
begin
ret.reply_type := AMQP_RESPONSE_SERVER_EXCEPTION;
ret.reply := frame.payload.method;
end
else
begin
ret.reply_type := AMQP_RESPONSE_LIBRARY_EXCEPTION;
ret.library_error := Int(AMQP_STATUS_BAD_AMQP_DATA);
end;
goto error_out2;
end;
if body_read + frame.payload.body_fragment.len > Amessage.body.len then
begin
ret.reply_type := AMQP_RESPONSE_LIBRARY_EXCEPTION;
ret.library_error := Int(AMQP_STATUS_BAD_AMQP_DATA);
goto error_out2;
end;
memcpy(body_read_ptr, frame.payload.body_fragment.bytes,
frame.payload.body_fragment.len);
body_read := body_read + frame.payload.body_fragment.len;
body_read_ptr := body_read_ptr + frame.payload.body_fragment.len;
end;
ret.reply_type := AMQP_RESPONSE_NORMAL;
Exit(ret);
error_out2:
Amessage.body.Destroy;
error_out3:
Amessage.pool.empty;
error_out1:
Result := ret;
end;
end.
|
unit uPCE;
interface
uses Windows, SysUtils, Classes, ORFn, uConst, ORCtrls, ORClasses,UBAGlobals, ComCtrls;
type
TPCEProviderRec = record
IEN: int64;
Name: string;
Primary: boolean;
Delete: boolean;
end;
TPCEProviderList = class(TORStringList)
private
FNoUpdate: boolean;
FOnPrimaryChanged: TNotifyEvent;
FPendingDefault: string;
FPendingUser: string;
FPCEProviderIEN: Int64;
FPCEProviderName: string;
function GetProviderData(Index: integer): TPCEProviderRec;
procedure SetProviderData(Index: integer; const Value: TPCEProviderRec);
function GetPrimaryIdx: integer;
procedure SetPrimaryIdx(const Value: integer);
procedure SetPrimary(index: integer; Primary: boolean);
public
function Add(const S: string): Integer; override;
function AddProvider(AIEN, AName: string; APrimary: boolean): integer;
procedure Assign(Source: TPersistent); override;
function PCEProvider: Int64;
function PCEProviderName: string;
function IndexOfProvider(AIEN: string): integer;
procedure Merge(AList: TPCEProviderList);
procedure Clear; override;
procedure Delete(Index: Integer); override;
function PrimaryIEN: int64;
function PrimaryName: string;
function PendingIEN(ADefault: boolean): Int64;
function PendingName(ADefault: boolean): string;
property ProviderData[Index: integer]: TPCEProviderRec read GetProviderData
write SetProviderData; default;
property PrimaryIdx: integer read GetPrimaryIdx write SetPrimaryIdx;
property OnPrimaryChanged: TNotifyEvent read FOnPrimaryChanged
write FOnPrimaryChanged;
end;
TPCEItem = class(TObject)
{base class for PCE items}
private
FDelete: Boolean; //flag for deletion
FSend: Boolean; //flag to send to broker
FComment: String;
protected
procedure SetComment(const Value: String);
public
// Provider: Int64;
Provider: Int64;
Code: string;
Category: string;
Narrative: string;
FGecRem: string;
procedure Assign(Src: TPCEItem); virtual;
procedure Clear; virtual;
function DelimitedStr: string; virtual;
function DelimitedStr2: string; virtual;
function ItemStr: string; virtual;
function Match(AnItem: TPCEItem): Boolean;
function MatchPOV(AnItem: TPCEItem): Boolean;
// function MatchProvider(AnItem: TPCEItem):Boolean;
function MatchProvider(AnItem: TPCEItem):Boolean;
procedure SetFromString(const x: string); virtual;
function HasCPTStr: string; virtual;
property Comment: String read FComment write SetComment;
property GecRem: string read FGecRem write FGecRem;
end;
TPCEItemClass = class of TPCEItem;
TPCEProc = class(TPCEItem)
{class for procedures}
public
FIsOldProcedure: boolean;
Quantity: Integer;
Modifiers: string; // Format Modifier1IEN;Modifier2IEN;Modifier3IEN; Trailing ; needed
// Provider: Int64; {jm 9/8/99}
Provider: Int64; {jm 9/8/99}
procedure Assign(Src: TPCEItem); override;
procedure Clear; override;
function DelimitedStr: string; override;
// function DelimitedStrC: string;
// function Match(AnItem: TPCEProc): Boolean;
function ModText: string;
function ItemStr: string; override;
procedure SetFromString(const x: string); override;
procedure CopyProc(Dest: TPCEProc);
function Empty: boolean;
end;
TPCEDiag = class(TPCEItem)
{class for diagnosis}
public
fProvider: Int64;
Primary: Boolean;
AddProb: Boolean;
OldComment: string;
SaveComment: boolean;
OldNarrative: string;
procedure Assign(Src: TPCEItem); override;
procedure Clear; override;
function DelimitedStr: string; override;
function DelimitedStr2: string; override;
// function delimitedStrC: string;
function ItemStr: string; override;
procedure SetFromString(const x: string); override;
procedure Send;
end;
TPCEExams = class(TPCEItem)
{class for Examinations}
public
// Provider: Int64;
Results: String;
procedure Assign(Src: TPCEItem); override;
procedure Clear; override;
function DelimitedStr: string; override;
// function delimitedStrC: string;
function ItemStr: string; override;
procedure SetFromString(const x: string); override;
function HasCPTStr: string; override;
end;
TPCEHealth = class(TPCEItem)
{class for Health Factors}
public
// Provider: Int64; {jm 9/8/99}
Level: string;
procedure Assign(Src: TPCEItem); override;
procedure Clear; override;
function DelimitedStr: string; override;
// function delimitedStrC: string;
function ItemStr: string; override;
procedure SetFromString(const x: string); override;
function HasCPTStr: string; override;
end;
TPCEImm = class(TPCEItem)
{class for immunizations}
public
// Provider: Int64; {jm 9/8/99}
Series: String;
Reaction: String;
Refused: Boolean; //not currently used
Contraindicated: Boolean;
procedure Assign(Src: TPCEItem); override;
procedure Clear; override;
function DelimitedStr: string; override;
// function delimitedStrC: string;
function ItemStr: string; override;
procedure SetFromString(const x: string); override;
function HasCPTStr: string; override;
end;
TPCEPat = class(TPCEItem)
{class for patient Education}
public
// Provider: Int64; {jm 9/8/99}
Level: String;
procedure Assign(Src: TPCEItem); override;
procedure Clear; override;
function DelimitedStr: string; override;
// function delimitedStrC: string;
function ItemStr: string; override;
procedure SetFromString(const x: string); override;
function HasCPTStr: string; override;
end;
TPCESkin = class(TPCEItem)
{class for skin tests}
public
// Provider: Int64; {jm 9/8/99}
Results: String; //Do not confuse for reserved word "result"
// Reading: Integer;
Reading: string;
DTRead: TFMDateTime;
DTGiven: TFMDateTime;
procedure Assign(Src: TPCEItem); override;
procedure Clear; override;
function DelimitedStr: string; override;
// function delimitedStrC: string;
function ItemStr: string; override;
procedure SetFromString(const x: string); override;
function HasCPTStr: string; override;
end;
// TPCEData = class;
TGenFindings = class(TPCEItem)
{class for Reminder General Findings only used for displaying in the
encounter pane note}
public
end;
tRequiredPCEDataType = (ndDiag, ndProc, ndSC); {jm 9/9/99}
tRequiredPCEDataTypes = set of tRequiredPCEDataType;
//modified: 6/9/99
//By: Robert Bott
//Location: ISL
//Purpose: Changed to allow capture of multiple providers.
TPCEData = class
{class for data to be passed to and from broker}
private
FUpdated: boolean;
FEncDateTime: TFMDateTime; //encounter date & time
FNoteDateTime: TFMDateTime; //Note date & time
FEncLocation: Integer; //encounter location
FEncSvcCat: Char; //
FEncInpatient: Boolean; //Inpatient flag
FEncUseCurr: Boolean; //
FSCChanged: Boolean; //
FSCRelated: Integer; //service con. related?
FAORelated: Integer; //
FIRRelated: Integer; //
FECRelated: Integer; //
FMSTRelated: Integer; //
FHNCRelated: Integer; //
FCVRelated: Integer; //
FSHADRelated: Integer; //
FCLRelated: Integer; //
FVisitType: TPCEProc; //
FProviders: TPCEProviderList;
FDiagnoses: TList; //pointer list for diagnosis
FProcedures: TList; //pointer list for Procedures
FImmunizations: TList; //pointer list for Immunizations
FSkinTests: TList; //pointer list for skin tests
FPatientEds: TList;
FHealthFactors: TList;
FGenFindings: TList;
fExams: TList;
FNoteTitle: Integer;
FNoteIEN: Integer;
FParent: string; // Parent Visit for secondary encounters
FHistoricalLocation: string; // Institution IEN^Name (if IEN=0 Piece 4 = outside location)
FStandAlone: boolean;
FStandAloneLoaded: boolean;
FProblemAdded: Boolean; // Flag set when one or more Dx are added to PL
function GetVisitString: string;
function GetCPTRequired: Boolean;
function getDocCount: Integer;
function MatchItem(AList: TList; AnItem: TPCEItem): Integer;
function MatchPOVItems(AList: TList; AnItem: TPCEItem): Integer;
procedure MarkDeletions(PreList: TList; PostList: TStrings);
procedure SetSCRelated(Value: Integer);
procedure SetAORelated(Value: Integer);
procedure SetIRRelated(Value: Integer);
procedure SetECRelated(Value: Integer);
procedure SetMSTRelated(Value: Integer);
procedure SetHNCRelated(Value: Integer);
procedure SetCVRelated(Value: Integer);
procedure SetSHADRelated(Value: Integer);
procedure SetCLRelated(Value: Integer);
procedure SetEncUseCurr(Value: Boolean);
function GetHasData: Boolean;
procedure GetHasCPTList(AList: TStrings);
procedure CopyPCEItems(Src: TList; Dest: TObject; ItemClass: TPCEItemClass);
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure CopyPCEData(Dest: TPCEData);
function Empty: boolean;
procedure PCEForNote(NoteIEN: Integer; EditObj: TPCEData);(* overload;
procedure PCEForNote(NoteIEN: Integer; EditObj: TPCEData; DCSummAdmitString: string); overload;*)
procedure Save;
procedure CopyDiagnoses(Dest: TCaptionListView); // ICDcode^P|S^Category^Narrative^P|S Text
procedure CopyProcedures(Dest: TCaptionListView); // CPTcode^Qty^Category^Narrative^Qty Text
procedure CopyImmunizations(Dest: TCaptionListView); //
procedure CopySkinTests(Dest: TCaptionListView); //
procedure CopyPatientEds(Dest: TCaptionListView);
procedure CopyHealthFactors(Dest: TCaptionListView);
procedure CopyExams(Dest: TCaptionListView);
procedure CopyGenFindings(Dest: TCaptionListView);
procedure SetDiagnoses(Src: TStrings; FromForm: boolean = TRUE); // ICDcode^P|S^Category^Narrative^P|S Text
procedure SetExams(Src: TStrings; FromForm: boolean = TRUE);
Procedure SetHealthFactors(Src: TStrings; FromForm: boolean = TRUE);
procedure SetImmunizations(Src: TStrings; FromForm: boolean = TRUE); // IMMcode^
Procedure SetPatientEds(Src: TStrings; FromForm: boolean = TRUE);
procedure SetSkinTests(Src: TStrings; FromForm: boolean = TRUE); //
procedure SetProcedures(Src: TStrings; FromForm: boolean = TRUE); // CPTcode^Qty^Category^Narrative^Qty Text
procedure SetGenFindings(Src: TStrings; FromForm: boolean = TRUE);
procedure SetVisitType(Value: TPCEProc); // CPTcode^1^Category^Narrative
function StrDiagnoses: string; // Diagnoses: ...
function StrImmunizations: string; // Immunizzations: ...
function StrProcedures: string; // Procedures: ...
function StrSkinTests: string;
function StrPatientEds: string;
function StrHealthFactors: string;
function StrExams: string;
function StrGenFindings: string;
function StrVisitType(const ASCRelated, AAORelated, AIRRelated, AECRelated,
AMSTRelated, AHNCRelated, ACVRelated, ASHADRelated, ACLRelated: Integer): string; overload;
function StrVisitType: string; overload;
function StandAlone: boolean;
procedure AddStrData(List: TStrings);
procedure AddVitalData(Data, List: TStrings);
function NeededPCEData: tRequiredPCEDataTypes;
function OK2SignNote: boolean;
function PersonClassDate: TFMDateTime;
function VisitDateTime: TFMDateTime;
function IsSecondaryVisit: boolean;
function NeedProviderInfo: boolean;
property HasData: Boolean read GetHasData;
property CPTRequired: Boolean read GetCPTRequired;
property ProblemAdded: Boolean read FProblemAdded;
property Inpatient: Boolean read FEncInpatient;
property UseEncounter: Boolean read FEncUseCurr write SetEncUseCurr;
property SCRelated: Integer read FSCRelated write SetSCRelated;
property AORelated: Integer read FAORelated write SetAORelated;
property IRRelated: Integer read FIRRelated write SetIRRelated;
property ECRelated: Integer read FECRelated write SetECRelated;
property MSTRelated: Integer read FMSTRelated write SetMSTRelated;
property HNCRelated: Integer read FHNCRelated write SetHNCRelated;
property CVRelated: Integer read FCVRelated write SetCVRelated;
property SHADRelated: Integer read FSHADRelated write SetSHADRelated;
property CLRelated: Integer read FCLRelated write SetCLRelated;
property VisitType: TPCEProc read FVisitType write SetVisitType;
property VisitString: string read GetVisitString;
property VisitCategory:char read FEncSvcCat write FEncSvcCat;
property DateTime: TFMDateTime read FEncDateTime write FEncDateTime;
property NoteDateTime: TFMDateTime read FNoteDateTime write FNoteDateTime;
property Location: Integer Read FencLocation;
property NoteTitle: Integer read FNoteTitle write FNoteTitle;
property NoteIEN: Integer read FNoteIEN write FNoteIEN;
property DocCOunt: Integer read GetDocCount;
property Providers: TPCEProviderList read FProviders;
property Parent: string read FParent write FParent;
property HistoricalLocation: string read FHistoricalLocation write FHistoricalLocation;
property Updated: boolean read FUpdated write FUpdated;
end;
type
TPCEType = (ptEncounter, ptReminder, ptTemplate);
const
PCETypeText: array[TPCEType] of string = ('encounter', 'reminder', 'template');
function InvalidPCEProviderTxt(AIEN: Int64; ADate: TFMDateTime): string;
function MissingProviderInfo(PCEEdit: TPCEData; PCEType: TPCEType = ptEncounter): boolean;
function IsOK2Sign(const PCEData: TPCEData; const IEN: integer) :boolean;
function FutureEncounter(APCEData: TPCEData): boolean;
function CanEditPCE(APCEData: TPCEData): boolean;
procedure GetPCECodes(List: TStrings; CodeType: integer);
procedure GetComboBoxMinMax(dest: TORComboBox; var Min, Max: integer);
procedure PCELoadORCombo(dest: TORComboBox); overload;
procedure PCELoadORCombo(dest: TORComboBox; var Min, Max: integer); overload;
function GetPCEDisplayText(ID: string; Tag: integer): string;
procedure SetDefaultProvider(ProviderList: TPCEProviderList; APCEData: TPCEData);
function ValidateGAFDate(var GafDate: TFMDateTime): string;
procedure GetVitalsFromDate(VitalStr: TStrings; PCEObj: TPCEData);
procedure GetVitalsFromNote(VitalStr: TStrings; PCEObj: TPCEData; ANoteIEN: Int64);
type
TPCEDataCat = (pdcVisit, pdcDiag, pdcProc, pdcImm, pdcSkin, pdcPED, pdcHF,
pdcExam, pdcVital, pdcOrder, pdcMH, pdcMST, pdcHNC, pdcWHR, pdcWH, pdcGenFinding);
function GetPCEDataText(Cat: TPCEDataCat; Code, Category, Narrative: string;
PrimaryDiag: boolean = FALSE; Qty: integer = 0): string;
const
PCEDataCatText: array[TPCEDataCat] of string =
{ dcVisit } ('',
{ dcDiag } 'Diagnoses: ',
{ dcProc } 'Procedures: ',
{ dcImm } 'Immunizations: ',
{ dcSkin } 'Skin Tests: ',
{ dcPED } 'Patient Educations: ',
{ dcHF } 'Health Factors: ',
{ dcExam } 'Examinations: ',
{ dcVital } '',
{ dcOrder } 'Orders: ',
{ dcMH } 'Mental Health: ',
{ dcMST } 'MST History: ',
{ dcHNC } 'Head and/or Neck Cancer: ',
{ dcWHR } 'Women''s Health Procedure: ',
{ dcWH } 'WH Notification: ',
{ dcGF } 'General Findings: ');
NoPCEValue = '@';
TAB_STOP_CHARS = 7;
TX_NO_VISIT = 'Insufficient Visit Information';
TX_NEED_PROV1 = 'The provider responsible for this encounter must be entered before ';
TX_NEED_PROV2 = ' information may be entered.';
// TX_NEED_PROV3 = 'you can sign the note.';
TX_NO_PROV = 'Missing Provider';
TX_BAD_PROV = 'Invalid Provider';
TX_NOT_ACTIVE = ' does not have an active person class.';
TX_NOT_PROV = ' is not a known Provider.';
TX_MISSING = 'Required Information Missing';
TX_REQ1 = 'The following required fields have not been entered:' + CRLF;
TC_REQ = 'Required Fields';
TX_ADDEND_AD = 'Cannot make an addendum to an addendum' + CRLF +
'Please select the parent note or document, and try again.';
TX_ADDEND_MK = 'Unable to Make Addendum';
TX_DEL_CNF = 'Confirm Deletion';
TX_IN_AUTH = 'Insufficient Authorization';
TX_NOPCE = '<No encounter information entered>';
TX_NEED_T = 'Missing Encounter Information';
TX_NEED1 = 'This note title is marked to prompt for the following missing' + CRLF +
'encounter information:' + CRLF;
TX_NEED_DIAG = ' A diagnosis.';
TX_NEED_PROC = ' A visit type or procedure.';
TX_NEED_SC = ' One or more service connected questions.';
TX_NEED2 = 'Would you like to enter encounter information now?';
TX_NEED3 = 'You must enter the encounter information before you can sign the note.';
TX_NEEDABORT = 'Document not signed.';
TX_COS_REQ = 'A cosigner is required for this document.';
TX_COS_SELF = 'You cannot make yourself a cosigner.';
TX_COS_AUTH = ' is not authorized to cosign this document.';
TC_COS = 'Select Cosigner';
TAG_IMMSERIES = 10;
TAG_IMMREACTION= 20;
TAG_SKRESULTS = 30;
TAG_PEDLEVEL = 40;
TAG_HFLEVEL = 50;
TAG_XAMRESULTS = 60;
TAG_HISTLOC = 70;
{ These piece numbers are used by both the PCE objects and reminders }
pnumCode = 2;
pnumPrvdrIEN = 2;
pnumCategory = 3;
pnumNarrative = 4;
pnumExamResults = 5;
pnumSkinResults = 5;
pnumHFLevel = 5;
pnumImmSeries = 5;
pnumProcQty = 5;
pnumPEDLevel = 5;
pnumDiagPrimary = 5;
pnumPrvdrName = 5;
pnumProvider = 6;
pnumPrvdrPrimary = 6;
pnumSkinReading = 7;
pnumImmReaction = 7;
pnumDiagAdd2PL = 7;
pnumSkinDTRead = 8;
pnumImmContra = 8;
pnumSkinDTGiven = 9;
pnumImmRefused = 9;
pnumCPTMods = 9;
pnumComment = 10;
pnumWHPapResult =11;
pnumWHNotPurp =12;
pnumDate = 13;
pnumRemGenFindID = 14;
pnumRemGenFindNewData = 16;
pnumRemGenFindGroup = 17;
pnumGFPrint = 18;
USE_CURRENT_VISITSTR = -2;
implementation
uses uCore, rPCE, rCore, rTIU, fEncounterFrame, uVitals, fFrame,
fPCEProvider, rVitals, uReminders, rMisc, uGlobalVar;
const
FN_NEW_PERSON = 200;
function InvalidPCEProviderTxt(AIEN: Int64; ADate: TFMDateTime): string;
begin
Result := '';
if(not CheckActivePerson(IntToStr(AIEN), ADate)) then
Result := TX_NOT_ACTIVE
else
if(not IsUserAProvider(AIEN, ADate)) then
Result := TX_NOT_PROV;
end;
function MissingProviderInfo(PCEEdit: TPCEData; PCEType: TPCEType = ptEncounter): boolean;
begin
if(PCEEdit.Empty and (PCEEdit.Location <> Encounter.Location) and (not Encounter.NeedVisit)) then
PCEEdit.UseEncounter := TRUE;
Result := NoPrimaryPCEProvider(PCEEdit.Providers, PCEEdit);
if(Result) then
InfoBox(TX_NEED_PROV1 + PCETypeText[PCEType] + TX_NEED_PROV2,
TX_NO_PROV, MB_OK or MB_ICONWARNING);
end;
var
UNxtCommSeqNum: integer;
function IsOK2Sign(const PCEData: TPCEData; const IEN: integer) :boolean;
var
TmpPCEData: TPCEData;
begin
if(assigned(PCEData)) then
PCEData.FUpdated := FALSE;
if(assigned(PCEData) and (PCEData.VisitString <> '') and
(VisitStrForNote(IEN) = PCEData.VisitString)) then
begin
if(PCEData.FNoteIEN <= 0) then
PCEData.FNoteIEN := IEN;
Result := PCEData.OK2SignNote
end
else
begin
TmpPCEData := TPCEData.Create;
try
TmpPCEData.PCEForNote(IEN, nil);
Result := TmpPCEData.OK2SignNote;
finally
TmpPCEData.Free;
end;
end;
end;
function FutureEncounter(APCEData: TPCEData): boolean;
begin
Result := (Int(APCEData.FEncDateTime + 0.0000001) > Int(FMToday + 0.0000001));
end;
function CanEditPCE(APCEData: TPCEData): boolean;
begin
if(GetAskPCE(APCEData.FEncLocation) = apDisable) then
Result := FALSE
else
Result := (not FutureEncounter(APCEData));
end;
procedure GetComboBoxMinMax(dest: TORComboBox; var Min, Max: integer);
var
DC: HDC;
SaveFont: HFont;
TextSize: TSize;
TLen, i: integer;
x: string;
begin
Min := MaxInt;
Max := 0;
DC := GetDC(0);
try
SaveFont := SelectObject(DC, dest.Font.Handle);
try
for i := 0 to dest.Items.Count-1 do
begin
x := dest.DisplayText[i];
GetTextExtentPoint32(DC, PChar(x), Length(x), TextSize);
TLen := TextSize.cx;
if(TLen > 0) and (Min > TLen) then
Min := TLen;
if(Max < TLen) then
Max := TLen;
end;
finally
SelectObject(DC, SaveFont);
end;
finally
ReleaseDC(0, DC);
end;
if(Min > Max) then Min := Max;
inc(Min, ScrollBarWidth + 8);
inc(Max, ScrollBarWidth + 8);
end;
type
TListMinMax = (mmMin, mmMax, mmFont);
var
PCESetsOfCodes: TStringList = nil;
HistLocations: TORStringList = nil;
WHNotPurpose: TORStringList = nil;
WHPapResult: TORStringList = nil;
WHMammResult: TORStringList = nil;
WHUltraResult: TORStringList = nil;
const
SetOfCodesHeader = '{^~Codes~^}';
SOCHeaderLen = length(SetOfCodesHeader);
ListMinMax: array[1..7, TListMinMax] of integer =
((0,0,-1), // TAG_IMMSERIES
(0,0,-1), // TAG_IMMREACTION
(0,0,-1), // TAG_SKRESULTS
(0,0,-1), // TAG_PEDLEVEL
(0,0,-1), // TAG_HFLEVEL
(0,0,-1), // TAG_XAMRESULTS
(0,0,-1)); // TAG_HISTLOC
function CodeSetIndex(CodeType: integer): integer;
var
TempSL: TStringList;
Hdr: string;
begin
Hdr := SetOfCodesHeader + IntToStr(CodeType);
Result := PCESetsOfCodes.IndexOf(Hdr);
if(Result < 0) then
begin
TempSL := TStringList.Create;
try
case CodeType of
TAG_IMMSERIES: LoadImmSeriesItems(TempSL);
TAG_IMMREACTION: LoadImmReactionItems(TempSL);
TAG_SKRESULTS: LoadSkResultsItems(TempSL);
TAG_PEDLEVEL: LoadPEDLevelItems(TempSL);
TAG_HFLEVEL: LoadHFLevelItems(TempSL);
TAG_XAMRESULTS: LoadXAMResultsItems(TempSL);
else
KillObj(@TempSL);
end;
if(assigned(TempSL)) then
begin
Result := PCESetsOfCodes.Add(Hdr);
FastAddStrings(TempSL, PCESetsOfCodes);
end;
finally
KillObj(@TempSL);
end;
end;
end;
procedure GetPCECodes(List: TStrings; CodeType: integer);
var
idx: integer;
begin
if(CodeType = TAG_HISTLOC) then
begin
if(not assigned(HistLocations)) then
begin
HistLocations := TORStringList.Create;
LoadHistLocations(HistLocations);
HistLocations.SortByPiece(2);
HistLocations.Insert(0,'0');
end;
FastAddStrings(HistLocations, List);
end
else
begin
if(not assigned(PCESetsOfCodes)) then
PCESetsOfCodes := TStringList.Create;
idx := CodeSetIndex(CodeType);
if(idx >= 0) then
begin
inc(idx);
while((idx < PCESetsOfCodes.Count) and
(copy(PCESetsOfCodes[idx],1,SOCHeaderLen) <> SetOfCodesHeader)) do
begin
List.Add(PCESetsOfCodes[idx]);
inc(idx);
end;
end;
end;
end;
function GetPCECodeString(CodeType: integer; ID: string): string;
var
idx: integer;
begin
Result := '';
if(CodeType <> TAG_HISTLOC) then
begin
if(not assigned(PCESetsOfCodes)) then
PCESetsOfCodes := TStringList.Create;
idx := CodeSetIndex(CodeType);
if(idx >= 0) then
begin
inc(idx);
while((idx < PCESetsOfCodes.Count) and
(copy(PCESetsOfCodes[idx],1,SOCHeaderLen) <> SetOfCodesHeader)) do
begin
if(Piece(PCESetsOfCodes[idx], U, 1) = ID) then
begin
Result := Piece(PCESetsOfCodes[idx], U, 2);
break;
end;
inc(idx);
end;
end;
end;
end;
procedure PCELoadORComboData(dest: TORComboBox; GetMinMax: boolean; var Min, Max: integer);
var
idx: integer;
begin
if(dest.items.count < 1) then
begin
dest.Clear;
GetPCECodes(dest.Items, dest.Tag);
dest.itemindex := 0;
if(GetMinMax) and (dest.Items.Count > 0) then
begin
idx := dest.Tag div 10;
if(idx > 0) and (idx < 8) then
begin
if(ListMinMax[idx, mmFont] <> integer(dest.Font.Handle)) then
begin
GetComboBoxMinMax(dest, Min, Max);
ListMinMax[idx, mmMin] := Min;
ListMinMax[idx, mmMax] := Max;
end
else
begin
Min := ListMinMax[idx, mmMin];
Max := ListMinMax[idx, mmMax];
end;
end;
end;
end;
end;
procedure PCELoadORCombo(dest: TORComboBox);
var
tmp: integer;
begin
PCELoadORComboData(dest, FALSE, tmp, tmp);
end;
procedure PCELoadORCombo(dest: TORComboBox; var Min, Max: integer);
begin
PCELoadORComboData(dest, TRUE, Min, Max);
end;
function GetPCEDisplayText(ID: string; Tag: integer): string;
var
Hdr: string;
idx: integer;
TempSL: TStringList;
begin
Result := '';
if(Tag = TAG_HISTLOC) then
begin
if(not assigned(HistLocations)) then
begin
HistLocations := TORStringList.Create;
LoadHistLocations(HistLocations);
HistLocations.SortByPiece(2);
HistLocations.Insert(0,'0');
end;
idx := HistLocations.IndexOfPiece(ID);
if(idx >= 0) then
Result := Piece(HistLocations[idx], U, 2);
end
else
begin
if(not assigned(PCESetsOfCodes)) then
PCESetsOfCodes := TStringList.Create;
Hdr := SetOfCodesHeader + IntToStr(Tag);
idx := PCESetsOfCodes.IndexOf(Hdr);
if(idx < 0) then
begin
TempSL := TStringList.Create;
try
case Tag of
TAG_IMMSERIES: LoadImmSeriesItems(TempSL);
TAG_IMMREACTION: LoadImmReactionItems(TempSL);
TAG_SKRESULTS: LoadSkResultsItems(TempSL);
TAG_PEDLEVEL: LoadPEDLevelItems(TempSL);
TAG_HFLEVEL: LoadHFLevelItems(TempSL);
TAG_XAMRESULTS: LoadXAMResultsItems(TempSL);
else
KillObj(@TempSL);
end;
if(assigned(TempSL)) then
begin
idx := PCESetsOfCodes.Add(Hdr);
FastAddStrings(TempSL, PCESetsOfCodes);
end;
finally
KillObj(@TempSL);
end;
end;
if(idx >= 0) then
begin
inc(idx);
while((idx < PCESetsOfCodes.Count) and
(copy(PCESetsOfCodes[idx],1,SOCHeaderLen) <> SetOfCodesHeader)) do
begin
if(Piece(PCESetsOfCodes[idx], U, 1) = ID) then
begin
Result := Piece(PCESetsOfCodes[idx], U, 2);
break;
end;
inc(idx);
end;
end;
end;
end;
function GetPCEDataText(Cat: TPCEDataCat; Code, Category, Narrative: string;
PrimaryDiag: boolean = FALSE; Qty: integer = 0): string;
begin
Result := '';
case Cat of
pdcVisit: if Code <> '' then Result := Category + ' ' + Narrative;
pdcDiag: begin
Result := GetDiagnosisText(Narrative, Code);
if PrimaryDiag then Result := Result + ' (Primary)';
end;
pdcProc: begin
Result := Narrative;
if Qty > 1 then Result := Result + ' (' + IntToStr(Qty) + ' times)';
end;
else Result := Narrative;
end;
end;
procedure SetDefaultProvider(ProviderList: TPCEProviderList; APCEData: TPCEData);
var
SIEN, tmp: string;
DefUser, AUser: Int64;
UserName: string;
begin
DefUser := Encounter.Provider;
if(DefUser <> 0) and (InvalidPCEProviderTxt(DefUser, APCEData.PersonClassDate) <> '') then
DefUser := 0;
if(DefUser <> 0) then
begin
AUser := DefUser;
UserName := Encounter.ProviderName;
end
else
if(InvalidPCEProviderTxt(User.DUZ, APCEData.PersonClassDate) = '') then
begin
AUser := User.DUZ;
UserName := User.Name;
end
else
begin
AUser := 0;
UserName := '';
end;
if(AUser = 0) then
ProviderList.FPendingUser := ''
else
ProviderList.FPendingUser := IntToStr(AUser) + U + UserName;
ProviderList.FPendingDefault := '';
tmp := DefaultProvider(APCEData.Location, DefUser, APCEData.PersonClassDate, APCEData.NoteIEN);
SIEN := IntToStr(StrToIntDef(Piece(tmp,U,1),0));
if(SIEN <> '0') then
begin
if(CheckActivePerson(SIEN, APCEData.PersonClassDate)) then
begin
if(piece(TIUSiteParams, U, 8) = '1') and // Check to see if DEFAULT PRIMARY PROVIDER is by Location
(SIEN = IntToStr(User.DUZ)) then
ProviderList.AddProvider(SIEN, Piece(tmp,U,2) ,TRUE)
else
ProviderList.FPendingDefault := tmp;
end;
end;
end;
function ValidateGAFDate(var GafDate: TFMDateTime): string;
var
DateMsg: string;
OKDate: TFMDateTime;
begin
Result := '';
if(Patient.DateDied > 0) and (FMToday > Patient.DateDied) then
begin
DateMsg := 'Date of Death';
OKDate := Patient.DateDied;
end
else
begin
DateMsg := 'Today';
OKDate := FMToday;
end;
if(GafDate <= 0) then
begin
Result := 'A date is required to enter a GAF score. Date Determined changed to ' + DateMsg + '.';
GafDate := OKDate;
end
else
if(Patient.DateDied > 0) and (GafDate > Patient.DateDied) then
begin
Result := 'This patient died ' + FormatFMDateTime('mmm dd, yyyy hh:nn', Patient.DateDied) +
'. Date GAF determined can not ' + CRLF +
'be later than the date of death, and has been changed to ' + DateMsg + '.';
GafDate := OKDate;
end;
end;
procedure GetVitalsFromDate(VitalStr: TStrings; PCEObj: TPCEData);
var
dte: TFMDateTime;
begin
if(PCEObj.IsSecondaryVisit) then
dte := PCEObj.NoteDateTime
else
dte := PCEObj.DateTime;
GetVitalsFromEncDateTime(VitalStr, Patient.DFN, dte);
end;
procedure GetVitalsFromNote(VitalStr: TStrings; PCEObj: TPCEData; ANoteIEN: Int64);
begin
if(PCEObj.IsSecondaryVisit) then
GetVitalsFromEncDateTime(VitalStr, Patient.DFN, PCEObj.NoteDateTime)
else
GetVitalFromNoteIEN(VitalStr, Patient.DFN, ANoteIEN);
end;
{ TPCEItem methods ------------------------------------------------------------------------- }
//function TPCEItem.DelimitedStr2: string;
//added: 6/17/98
//By: Robert Bott
//Location: ISL
//Purpose: Return comment string to be passed in RPC call.
function TPCEItem.DelimitedStr2: string;
{created delimited string to pass to broker}
begin
If Comment = '' then
begin
result := 'COM' + U + IntToStr(UNxtCommSeqNum) + U + NoPCEValue;
end
else
begin
Result := 'COM' + U + IntToStr(UNxtCommSeqNum) + U + Comment;
end;
Inc(UNxtCommSeqNum); //set up for next comment
end;
procedure TPCEItem.Assign(Src: TPCEItem);
begin
FDelete := Src.FDelete;
FSend := Src.FSend;
Code := Src.Code;
Category := Src.Category;
Narrative := Src.Narrative;
Provider := Src.Provider;
Comment := Src.Comment;
end;
procedure TPCEItem.SetComment(const Value: String);
begin
FComment := Value;
while (length(FComment) > 0) and (FComment[1] = '?') do
delete(FComment,1,1);
end;
//procedure TPCEItem.Clear;
//modified: 6/17/98
//By: Robert Bott
//Location: ISL
//Purpose: Add Comments to PCE Items.
procedure TPCEItem.Clear;
{clear fields(properties) of class}
begin
FDelete := False;
FSend := False;
Code := '';
Category := '';
Narrative := '';
Provider := 0;
Comment := '';
end;
//function TPCEItem.DelimitedStr: string;
//modified: 6/17/98
//By: Robert Bott
//Location: ISL
//Purpose: Add Comments to PCE Items.
function TPCEItem.DelimitedStr: string;
{created delimited string to pass to broker}
var
DelFlag: Char;
begin
if FDelete then DelFlag := '-' else DelFlag := '+';
Result := DelFlag + U + Code + U + Category + U + Narrative;
end;
function TPCEItem.ItemStr: string;
{returns string to be assigned to Tlist in PCEData object}
begin
Result := Narrative;
end;
function TPCEItem.Match(AnItem: TPCEItem): Boolean;
{checks for match of Code, Category. and Item}
begin
Result := False;
if (Code = AnItem.Code) and (Category = AnItem.Category) and (Narrative = AnItem.Narrative)
then Result := True;
end;
function TPCEItem.HasCPTStr: string;
begin
Result := '';
end;
//procedure TPCEItem.SetFromString(const x: string);
//modified: 6/17/98
//By: Robert Bott
//Location: ISL
//Purpose: Add Comments to PCE Items.
procedure TPCEItem.SetFromString(const x: string);
{ sets fields to pieces passed from server: TYP ^ Code ^ Category ^ Narrative }
begin
Code := Piece(x, U, pnumCode);
Category := Piece(x, U, pnumCategory);
Narrative := Piece(x, U, pnumNarrative);
Provider := StrToInt64Def(Piece(x, U, pnumProvider), 0);
Comment := Piece(x, U, pnumComment);
end;
{ TPCEExams methods ------------------------------------------------------------------------- }
procedure TPCEExams.Assign(Src: TPCEItem);
begin
inherited Assign(Src);
Results := TPCEExams(Src).Results;
if Results = '' then Results := NoPCEValue;
end;
procedure TPCEExams.Clear;
{clear fields(properties) of class}
begin
inherited Clear;
// Provider := 0;
Results := NoPCEValue;
end;
//function TPCEExams.DelimitedStr: string;
//modified: 6/17/98
//By: Robert Bott
//Location: ISL
//Purpose: Add Comments to PCE Items.
function TPCEExams.DelimitedStr: string;
{created delimited string to pass to broker}
begin
Result := inherited DelimitedStr;
//Result := 'XAM' + Result + U + Results + U + IntToStr(Provider) +U + U + U +
Result := 'XAM' + Result + U + Results + U +U + U + U +
U + IntToStr(UNxtCommSeqNum);
end;
(*function TPCEExams.delimitedStrC: string;
begin
Result := inherited DelimitedStr;
Result := 'XAM' + Result + U + Results + U + IntToStr(Provider) +U + U + U +
U + comment;
end;
*)
function TPCEExams.HasCPTStr: string;
begin
Result := Code + ';AUTTEXAM(';
end;
function TPCEExams.ItemStr: string;
{returns string to be assigned to Tlist in PCEData object}
begin
if(Results <> NoPCEValue) then
Result := GetPCECodeString(TAG_XAMRESULTS, Results)
else
Result := '';
Result := Result + U + inherited ItemStr;
end;
procedure TPCEExams.SetFromString(const x: string);
{ sets fields to pieces passed from server: TYP ^ Code ^ Category ^ Narrative ^ Qty ^ Prov }
begin
inherited SetFromString(x);
// Provider := StrToInt64Def(Piece(x, U, pnumProvider), 0);
Results := Piece(x, U, pnumExamResults);
If results = '' then results := NoPCEValue;
end;
{ TPCESkin methods ------------------------------------------------------------------------- }
procedure TPCESkin.Assign(Src: TPCEItem);
var
SKSrc: TPCESkin;
begin
inherited Assign(Src);
SKSrc := TPCESkin(Src);
Results := SKSrc.Results;
Reading := SKSrc.Reading;
DTRead := SKSrc.DTRead;
DTGiven := SKSrc.DTGiven;
if Results = '' then Results := NoPCEValue;
end;
procedure TPCESkin.Clear;
{clear fields(properties) of class}
begin
inherited Clear;
// Provider := 0;
Results := NoPCEValue;
Reading := '0';
DTRead := 0.0; //What should dates be ititialized to?
DTGiven := 0.0;
end;
//function TPCESkin.DelimitedStr: string;
//modified: 6/17/98
//By: Robert Bott
//Location: ISL
//Purpose: Add Comments to PCE Items.
function TPCESkin.DelimitedStr: string;
{created delimited string to pass to broker}
var
ReadingToPassIn : String;
begin
Result := inherited DelimitedStr;
//Result := 'SK' + Result + U + results + U + IntToStr(Provider) + U +
if Uppercase(results) = 'O' then ReadingToPassIn := '@'
else ReadingToPassIn := Reading;
Result := 'SK' + Result + U + results + U + U +
ReadingToPassIn + U + U + U + IntToStr(UNxtCommSeqNum);
//+ FloatToStr(DTRead) + U + FloatToStr(DTGiven);
end;
(*function TPCESkin.delimitedStrC: string;
begin
Result := inherited DelimitedStr;
Result := 'SK' + Result + U + results + U + IntToStr(Provider) + U +
IntToStr(Reading) + U + U + U + comment;
end;
*)
function TPCESkin.HasCPTStr: string;
begin
Result := Code + ';AUTTSK(';
end;
function TPCESkin.ItemStr: string;
{returns string to be assigned to Tlist in PCEData object}
begin
if(Results <> NoPCEValue) then
Result := GetPCECodeString(TAG_SKRESULTS, Results)
else
Result := '';
Result := Result + U;
// if(Reading <> 0) then
// Result := Result + IntToStr(Reading);
Result := Result + Reading;
Result := Result + U + inherited ItemStr;
end;
procedure TPCESkin.SetFromString(const x: string);
{ sets fields to pieces passed from server: TYP ^ Code ^ Category ^ Narrative ^ Qty ^ Prov }
var
sRead, sDTRead, sDTGiven: String;
begin
inherited SetFromString(x);
// Provider := StrToInt64Def(Piece(x, U, pnumProvider), 0);
Results := Piece(x, U, pnumSkinResults);
sRead := Piece(x, U, pnumSkinReading);
sDTRead := Piece(x, U, pnumSkinDTRead);
sDtGiven := Piece(x, U, pnumSkinDTGiven);
If results = '' then results := NoPCEValue;
if sRead <> '' then
// Reading := StrToInt(sRead);
Reading := sRead;
if sDTRead <> '' then
DTRead := StrToFMDateTime(sDTRead);
if sDTGiven <> '' then
DTGiven := StrToFMDateTime(sDTGiven);
end;
{ TPCEHealth methods ------------------------------------------------------------------------- }
procedure TPCEHealth.Assign(Src: TPCEItem);
begin
inherited Assign(Src);
Level := TPCEHealth(Src).Level;
if Level = '' then Level := NoPCEValue;
end;
procedure TPCEHealth.Clear;
{clear fields(properties) of class}
begin
inherited Clear;
// Provider := 0;
Level := NoPCEValue;
end;
//function TPCEHealth.DelimitedStr: string;
//modified: 6/17/98
//By: Robert Bott
//Location: ISL
//Purpose: Add Comments to PCE Items.
function TPCEHealth.DelimitedStr: string;
{created delimited string to pass to broker}
begin
Result := inherited DelimitedStr;
// Result := 'HF' + Result + U + Level + U + IntToStr(Provider) + U + U + U +
Result := 'HF' + Result + U + Level + U + U + U + U +
U + IntToStr(UNxtCommSeqNum)+ U + GecRem;
end;
(*function TPCEHealth.delimitedStrC: string;
begin
Result := inherited DelimitedStr;
Result := 'HF' + Result + U + Level + U + IntToStr(Provider) + U + U + U +
U + comment;
end;
*)
function TPCEHealth.HasCPTStr: string;
begin
Result := Code + ';AUTTHF(';
end;
function TPCEHealth.ItemStr: string;
{returns string to be assigned to Tlist in PCEData object}
begin
if(Level <> NoPCEValue) then
Result := GetPCECodeString(TAG_HFLEVEL, Level)
else
Result := '';
Result := Result + U + inherited ItemStr;
end;
procedure TPCEHealth.SetFromString(const x: string);
{ sets fields to pieces passed from server: TYP ^ Code ^ Category ^ Narrative ^ Qty ^ Prov }
begin
inherited SetFromString(x);
// Provider := StrToInt64Def(Piece(x, U, pnumProvider), 0);
Level := Piece(x, U, pnumHFLevel);
if level = '' then level := NoPCEValue;
end;
{ TPCEImm methods ------------------------------------------------------------------------- }
procedure TPCEImm.Assign(Src: TPCEItem);
var
IMMSrc: TPCEImm;
begin
inherited Assign(Src);
IMMSrc := TPCEImm(Src);
Series := IMMSrc.Series;
Reaction := IMMSrc.Reaction;
Refused := IMMSrc.Refused;
Contraindicated := IMMSrc.Contraindicated;
if Series = '' then Series := NoPCEValue;
if Reaction ='' then Reaction := NoPCEValue;
end;
procedure TPCEImm.Clear;
{clear fields(properties) of class}
begin
inherited Clear;
// Provider := 0;
Series := NoPCEValue;
Reaction := NoPCEValue;
Refused := False; //not currently used
Contraindicated := false;
end;
//function TPCEImm.DelimitedStr: string;
//modified: 6/17/98
//By: Robert Bott
//Location: ISL
//Purpose: Add Comments to PCE Items.
function TPCEImm.DelimitedStr: string;
{created delimited string to pass to broker}
begin
Result := inherited DelimitedStr;
//Result := 'IMM' + Result + U + Series + U + IntToStr(Provider) + U + Reaction;
Result := 'IMM' + Result + U + Series + U + U + Reaction;
if Contraindicated then Result := Result + U + '1'
else Result := Result + U + '0';
Result := Result + U + U + IntToStr(UNxtCommSeqNum);
{the following two lines are not yet implemented in PCE side}
//if Refused then Result := Result + U + '1'
//else Result := Result + U + '0';
end;
(*function TPCEImm.delimitedStrC: string;
begin
Result := inherited DelimitedStr;
Result := 'IMM' + Result + U + Series + U + IntToStr(Provider) + U + Reaction;
if Contraindicated then Result := Result + U + '1'
else Result := Result + U + '0';
Result := Result + U + U + comment;
{the following two lines are not yet implemented in PCE side}
//if Refused then Result := Result + U + '1'
//else Result := Result + U + '0';
end;
*)
function TPCEImm.HasCPTStr: string;
begin
Result := Code + ';AUTTIMM(';
end;
function TPCEImm.ItemStr: string;
{returns string to be assigned to Tlist in PCEData object}
begin
if(Series <> NoPCEValue) then
Result := GetPCECodeString(TAG_IMMSERIES, Series)
else
Result := '';
Result := Result + U;
if(Reaction <> NoPCEValue) then
Result := Result + GetPCECodeString(TAG_IMMREACTION, Reaction);
Result := Result + U;
if(Contraindicated) then
Result := Result + 'X';
Result := Result + U + inherited ItemStr;
end;
procedure TPCEImm.SetFromString(const x: string);
{ sets fields to pieces passed from server: TYP ^ Code ^ Category ^ Narrative ^ Qty ^ Prov }
var
temp: String;
begin
inherited SetFromString(x);
// Provider := StrToInt64Def(Piece(x, U, pnumProvider), 0);
Series := Piece(x, U, pnumImmSeries);
Reaction := Piece(x, U, pnumImmReaction);
temp := Piece(x, U, pnumImmRefused);
if temp = '1' then refused := true else refused := false;
temp := Piece(x, U, pnumImmContra);
if temp = '1' then Contraindicated := true else Contraindicated := false;
if Series = '' then series := NoPCEValue;
if Reaction ='' then reaction := NoPCEValue;
end;
{ TPCEProc methods ------------------------------------------------------------------------- }
procedure TPCEProc.Assign(Src: TPCEItem);
begin
inherited Assign(Src);
Quantity := TPCEProc(Src).Quantity;
Modifiers := TPCEProc(Src).Modifiers;
Provider := TPCEProc(Src).Provider;
end;
procedure TPCEProc.Clear;
{clear fields(properties) of class}
begin
inherited Clear;
Quantity := 0;
Modifiers := '';
// Provider := 0;
Provider := 0;
end;
procedure TPCEProc.CopyProc(Dest: TPCEProc);
begin
Dest.FDelete := FDelete;
Dest.FSend := Fsend; //flag to send to broker
// Dest.Provider := Provider;
Dest.Provider := Provider;
Dest.Code := Code;
Dest.Category := Category;
Dest.Narrative := Narrative;
Dest.Comment := Comment;
Dest.Modifiers := Modifiers;
end;
//function TPCEProc.DelimitedStr: string;
//modified: 6/17/98
//By: Robert Bott
//Location: ISL
//Purpose: Add Comments to PCE Items.
function TPCEProc.DelimitedStr: string;
var
i, cnt: integer;
Mods, ModIEN, tmpProv: string;
{created delimited string to pass to broker}
begin
i := 1;
cnt := 0;
Mods := '';
repeat
ModIEN := piece(Modifiers, ';', i);
if(ModIEN <> '') then
begin
inc(cnt);
Mods := Mods + ';' + ModifierCode(ModIEN) + '/' + ModIEN;
inc(i);
end;
until (ModIEN = '');
Result := inherited DelimitedStr;
if Provider > 0 then tmpProv := IntToStr(Provider) else tmpProv := '';
Result := 'CPT' + Result + U + IntToStr(Quantity) + U + tmpProv
+ U + U + U + IntToStr(cnt) + Mods + U + IntToStr(UNxtCommSeqNum) + U;
if Length(Result) > 250 then SetPiece(Result, U, 4, '');
end;
(*function TPCEProc.delimitedStrC: string;
begin
Result := inherited DelimitedStr;
Result := 'CPT' + Result + U + IntToStr(Quantity) + U + IntToStr(Provider) +
U + U + U + U + comment;
end;
*)
function TPCEProc.Empty: boolean;
begin
Result := (Code = '') and (Category = '') and (Narrative = '') and
(Comment = '') and (Quantity = 0) and (Provider = 0) and (Modifiers = '');
end;
(*function TPCEProc.Match(AnItem: TPCEProc): Boolean; {NEW CODE - v20 testing only - RV}
begin
Result := inherited Match(AnItem) and (Modifiers = AnItem.Modifiers);
end;*)
function TPCEProc.ModText: string;
var
i: integer;
tmp: string;
begin
Result := '';
if(Modifiers <> '') then
begin
i := 1;
repeat
tmp := Piece(Modifiers,';',i);
if(tmp <> '') then
begin
tmp := ModifierName(tmp);
Result := Result + ' - ' + tmp;
end;
inc(i);
until (tmp = '');
end;
end;
function TPCEProc.ItemStr: string;
{returns string to be assigned to Tlist in PCEData object}
begin
if(Quantity > 1) then
Result := IntToStr(Quantity) + ' times'
else
Result := '';
Result := Result + U + inherited ItemStr + ModText;
end;
procedure TPCEProc.SetFromString(const x: string);
var
i, cnt: integer;
Mods: string;
{ sets fields to pieces passed from server: TYP ^ Code ^ Category ^ Narrative ^ Qty ^ Prov }
begin
inherited SetFromString(x);
Quantity := StrToIntDef(Piece(x, U, pnumProcQty), 1);
// Provider := StrToInt64Def(Piece(x, U, pnumProvider), 0);
Provider := StrToInt64Def(Piece(x, U, pnumProvider), 0);
Modifiers := '';
Mods := Piece(x, U, pnumCPTMods);
cnt := StrToIntDef(Piece(Mods, ';', 1), 0);
if(cnt > 0) then
for i := 1 to cnt do
Modifiers := Modifiers + Piece(Piece(Mods, ';' , i+1), '/', 2) + ';';
end;
{ TPCEPat methods ------------------------------------------------------------------------- }
procedure TPCEPat.Assign(Src: TPCEItem);
begin
inherited Assign(Src);
Level := TPCEPat(Src).Level;
if Level = '' then Level := NoPCEValue;
end;
procedure TPCEPat.Clear;
{clear fields(properties) of class}
begin
inherited Clear;
// Provider := 0;
Level := NoPCEValue;
end;
//function TPCEPat.DelimitedStr: string;
//modified: 6/17/98
//By: Robert Bott
//Location: ISL
//Purpose: Add Comments to PCE Items.
function TPCEPat.DelimitedStr: string;
{created delimited string to pass to broker}
begin
Result := inherited DelimitedStr;
//Result := 'PED' + Result + U + Level + U + IntToStr(Provider) + U + U + U +
Result := 'PED' + Result + U + Level + U+ U + U + U +
U + IntToStr(UNxtCommSeqNum);
end;
(*function TPCEPat.delimitedStrC: string;
begin
Result := inherited DelimitedStr;
Result := 'PED' + Result + U + Level + U + IntToStr(Provider) + U + U + U +
U + comment;
end;
*)
function TPCEPat.HasCPTStr: string;
begin
Result := Code + ';AUTTEDT(';
end;
function TPCEPat.ItemStr: string;
{returns string to be assigned to Tlist in PCEData object}
begin
if(Level <> NoPCEValue) then
Result := GetPCECodeString(TAG_PEDLEVEL, Level)
else
Result := '';
Result := Result + U + inherited ItemStr;
end;
procedure TPCEPat.SetFromString(const x: string);
{ sets fields to pieces passed from server: TYP ^ Code ^ Category ^ Narrative ^ Qty ^ Prov }
begin
inherited SetFromString(x);
// Provider := StrToInt64Def(Piece(x, U, pnumProvider), 0);
Level := Piece(x, U, pnumPEDLevel);
if level = '' then level := NoPCEValue;
end;
{ TPCEDiag methods ------------------------------------------------------------------------- }
procedure TPCEDiag.Assign(Src: TPCEItem);
begin
inherited Assign(Src);
Primary := TPCEDiag(Src).Primary;
AddProb := TPCEDiag(Src).AddProb;
OldNarrative := TPCEDiag(Src).OldNarrative;
end;
//procedure TPCEDiag.Clear;
//modified: 6/17/98
//By: Robert Bott
//Location: ISL
//Purpose: Clear a diagnosis object.
procedure TPCEDiag.Clear;
{clear fields(properties) of class}
begin
inherited Clear;
Primary := False;
//Provider := 0;
AddProb := False;
OldNarrative := '';
end;
//function TPCEDiag.DelimitedStr: string;
//modified: 6/17/98
//By: Robert Bott
//Location: ISL
//Purpose: Create delimited string to pass to Broker.
function TPCEDiag.DelimitedStr: string;
{created delimited string to pass to broker}
var
ProviderStr: string; {jm 9/8/99}
begin
Result := inherited DelimitedStr;
if(AddProb) then
ProviderStr := IntToStr(fProvider)
else
ProviderStr := '';
Result := 'POV' + Result + U + BOOLCHAR[Primary] + U + ProviderStr + U +
BOOLCHAR[AddProb] + U + U + U;
if(SaveComment) then Result := Result + IntToStr(UNxtCommSeqNum);
if Length(Result) > 250 then SetPiece(Result, U, 4, '');
end;
function TPCEDiag.DelimitedStr2: string;
begin
If Comment = '' then
begin
SaveComment := (OldComment <> '') or (not AddProb);
if(SaveComment) then
result := 'COM' + U + IntToStr(UNxtCommSeqNum) + U + NoPCEValue
else
result := '';
end
else
begin
Result := 'COM' + U + IntToStr(UNxtCommSeqNum) + U + Comment;
SaveComment := TRUE;
end;
Inc(UNxtCommSeqNum);
end;
(*function TPCEDiag.DelimitedStrC: string;
{created delimited string for internal use - keep comment in same string.}
begin
Result := inherited DelimitedStr;
Result := 'POV' + Result + U + BOOLCHAR[Primary] + U + IntToStr(Provider)+
U + BOOLCHAR[AddProb] + U + U + U + comment;
end;
*)
function TPCEDiag.ItemStr: string;
{returns string to be assigned to Tlist in PCEData object}
begin
if Primary then
Result := 'Primary'
else
Result := 'Secondary';
// This may change in the future if we add a check box to the grid
if(AddProb) then
Result := 'Add' + U + Result
else
Result := U + Result;
Result := Result + U + GetDiagnosisText((inherited ItemStr), Code);
end;
procedure TPCEDiag.Send;
//marks diagnosis to be sent;
begin
Fsend := True;
end;
//procedure TPCEDiag.SetFromString(const x: string);
//modified: 6/17/98
//By: Robert Bott
//Location: ISL
//Purpose: Sets fields to pieces passed from server.
procedure TPCEDiag.SetFromString(const x: string);
{ sets fields to pieces passed from server: TYP ^ Code ^ Category ^ Narrative ^ Primary ^ ^ ^ Comment }
begin
inherited SetFromString(x);
OldComment := Comment;
Primary := (Piece(x, U, pnumDiagPrimary) = '1');
//Provider := StrToInt64Def(Piece(x, U, pnumProvider),0);
AddProb := (Piece(x, U, pnumDiagAdd2PL) = '1');
end;
{ TPCEData methods ------------------------------------------------------------------------- }
constructor TPCEData.Create;
begin
FDiagnoses := TList.Create;
FProcedures := TList.Create;
FImmunizations := TList.Create;
FSkinTests := TList.Create;
FVisitType := TPCEProc.Create;
FPatientEds := TList.Create;
FHealthFactors := TList.Create;
fExams := TList.Create;
FGenFindings := TList.Create;
FProviders := TPCEProviderList.Create;
FSCRelated := SCC_NA;
FAORelated := SCC_NA;
FIRRelated := SCC_NA;
FECRelated := SCC_NA;
FMSTRelated := SCC_NA;
FHNCRelated := SCC_NA;
FCVRelated := SCC_NA;
FSHADRelated := SCC_NA;
FCLRelated := SCC_NA;
FSCChanged := False;
end;
destructor TPCEData.Destroy;
var
i: Integer;
begin
with FDiagnoses do for i := 0 to Count - 1 do TPCEDiag(Items[i]).Free;
with FProcedures do for i := 0 to Count - 1 do TPCEProc(Items[i]).Free;
with FImmunizations do for i := 0 to Count - 1 do TPCEImm(Items[i]).Free;
with FSkinTests do for i := 0 to Count - 1 do TPCESkin(Items[i]).Free;
with FPatientEds do for i := 0 to Count - 1 do TPCEPat(Items[i]).Free;
with FHealthFactors do for i := 0 to Count - 1 do TPCEHealth(Items[i]).Free;
with FExams do for i := 0 to Count - 1 do TPCEExams(Items[i]).Free;
with FGenFindings do for i := 0 to Count - 1 do TGenFindings(Items[i]).Free;
FVisitType.Free;
FDiagnoses.Free;
FProcedures.Free;
FImmunizations.Free;
FSkinTests.free;
FPatientEds.Free;
FHealthFactors.Free;
FExams.Free;
FProviders.Free;
FGenFindings.Free;
inherited Destroy;
end;
procedure TPCEData.Clear;
procedure ClearList(AList: TList);
var
i: Integer;
begin
for i := 0 to AList.Count - 1 do
TObject(AList[i]).Free;
AList.Clear;
end;
begin
FEncDateTime := 0;
FNoteDateTime := 0;
FEncLocation := 0;
FEncSvcCat := 'A';
FEncInpatient := FALSE;
FProblemAdded := False;
FEncUseCurr := FALSE;
FStandAlone := FALSE;
FStandAloneLoaded := FALSE;
FParent := '';
FHistoricalLocation := '';
FSCRelated := SCC_NA;
FAORelated := SCC_NA;
FIRRelated := SCC_NA;
FECRelated := SCC_NA;
FMSTRelated := SCC_NA;
FHNCRelated := SCC_NA;
FCVRelated := SCC_NA;
FSHADRelated := SCC_NA;
FCLRelated := SCC_NA;
ClearList(FDiagnoses);
ClearList(FProcedures);
ClearList(FImmunizations);
ClearList(FSkinTests);
ClearList(FPatientEds);
ClearList(FHealthFactors);
ClearList(FExams);
ClearList(FGenFindings);
FVisitType.Clear;
FProviders.Clear;
FSCChanged := False;
FNoteIEN := 0;
FNoteTitle := 0;
end;
procedure TPCEData.CopyDiagnoses(Dest: TCaptionListView);
begin
CopyPCEItems(FDiagnoses, Dest, TPCEDiag);
end;
procedure TPCEData.CopyProcedures(Dest: TCaptionListView);
begin
CopyPCEItems(FProcedures, Dest, TPCEProc);
end;
procedure TPCEData.CopyImmunizations(Dest: TCaptionListView);
begin
CopyPCEItems(FImmunizations, Dest, TPCEImm);
end;
procedure TPCEData.CopySkinTests(Dest: TCaptionListView);
begin
CopyPCEItems(FSkinTests, Dest, TPCESkin);
end;
procedure TPCEData.CopyPatientEds(Dest: TCaptionListView);
begin
CopyPCEItems(FPatientEds, Dest, TPCEPat);
end;
procedure TPCEData.CopyHealthFactors(Dest: TCaptionListView);
begin
CopyPCEItems(FHealthFactors, Dest, TPCEHealth);
end;
procedure TPCEData.CopyExams(Dest: TCaptionListView);
begin
CopyPCEItems(FExams, Dest, TPCEExams);
end;
procedure TPCEData.CopyGenFindings(Dest: TCaptionListView);
begin
CopyPCEItems(FGenFindings, Dest, TGenFindings);
end;
function TPCEData.GetVisitString: string;
begin
Result := IntToStr(FEncLocation) + ';' + FloatToStr(VisitDateTime) + ';' + FEncSvcCat;
end;
function TPCEData.GetCPTRequired: Boolean;
begin
Result := (([ndDiag, ndProc] * NeededPCEData) <> []);
end;
procedure TPCEData.PCEForNote(NoteIEN: Integer; EditObj: TPCEData);
(*const
NULL_STR = '';
begin
PCEForNote(NoteIEN, EditObj, NULL_STR);
end;
procedure TPCEData.PCEForNote(NoteIEN: Integer; EditObj: TPCEData; DCSummAdmitString: string);*)
var
i, j: Integer;
TmpCat, TmpVStr: string;
x: string;
DoCopy, IsVisit: Boolean;
PCEList, VisitTypeList: TStringList;
ADiagnosis: TPCEDiag;
AProcedure: TPCEProc;
AImmunization: TPCEImm;
ASkinTest: TPCESkin;
APatientEd: TPCEPat;
AHealthFactor: TPCEHealth;
AExam: TPCEExams;
AGenFind: TGenFindings;
FileVStr: string;
FileIEN: integer;
GetCat, DoRestore: boolean;
FRestDate: TFMDateTime;
// AProvider: TPCEProvider; {6/9/99}
function SCCValue(x: string): Integer;
begin
Result := SCC_NA;
if Piece(x, U, 3) = '1' then Result := SCC_YES;
if Piece(x, U, 3) = '0' then Result := SCC_NO;
end;
function AppendComment(x: string): String;
begin
//check for comment append string if a comment exists
If (((i+1) <= (PCEList.Count - 1)) and (Copy(PCEList[(i+1)], 1, 3) = 'COM')) then
begin
//remove last piece (comment sequence number) from x.
While x[length(x)] <> U do
x := Copy(X,0,(length(x)-1));
//add last piece of comment to x
x := X + Piece (PCEList[(i+1)],U,3);
end;
result := x;
end;
begin
if(NoteIEN < 1) then
TmpVStr := Encounter.VisitStr
else
begin
TmpVStr := VisitStrForNote(NoteIEN);
if(FEncSvcCat = #0) then
GetCat :=TRUE
else
if(GetVisitString = '0;0;A') then
begin
FEncLocation := StrToIntDef(Piece(TmpVStr, ';', 1), 0);
FEncDateTime := StrToFloatDef(Piece(TmpVStr, ';', 2),0);
GetCat :=TRUE
end
else
GetCat := FALSE;
if(GetCat) then
begin
TmpCat := Piece(TmpVStr, ';', 3);
if(TmpCat <> '') then
FEncSvcCat := TmpCat[1];
end;
end;
if(assigned(EditObj)) then
begin
if(copy(TmpVStr,1,2) <> '0;') and // has location
(pos(';0;',TmpVStr) = 0) and // has time
(EditObj.GetVisitString = TmpVStr) then
begin
if(FEncSvcCat = 'H') and (FEncInpatient) then
DoCopy := (FNoteDateTime = EditObj.FNoteDateTime)
else
DoCopy := TRUE;
if(DoCopy) then
begin
if(EditObj <> Self) then
begin
EditObj.CopyPCEData(Self);
FNoteTitle := 0;
FNoteIEN := NOTEIEN;
end;
exit;
end;
end;
end;
TmpCat := Piece(TmpVStr, ';', 3);
if(TmpCat <> '') then
FEncSvcCat := TmpCat[1]
else
FEncSvcCat := #0;
FEncLocation := StrToIntDef(Piece(TmpVStr,';',1),0);
FEncDateTime := StrToFloatDef(Piece(TmpVStr, ';', 2),0);
if(IsSecondaryVisit and (FEncLocation > 0)) then
begin
FileIEN := USE_CURRENT_VISITSTR;
FileVStr := IntToStr(FEncLocation) + ';' + FloatToStr(FNoteDateTime) + ';' +
GetLocSecondaryVisitCode(FEncLocation);
DoRestore := TRUE;
FRestDate := FEncDateTime;
end
else
begin
DoRestore := FALSE;
FRestDate := 0;
FileIEN := NoteIEN;
(* if DCSummAdmitString <> '' then
FileVStr := DCSummAdmitString
else*) if(FileIEN < 0) then
FileVStr := Encounter.VisitStr
else
FileVStr := '';
end;
Clear;
PCEList := TStringList.Create;
VisitTypeList := TStringList.Create;
try
LoadPCEDataForNote(PCEList, FileIEN, FileVStr); // calls broker RPC to load data
FNoteIEN := NoteIEN;
for i := 0 to PCEList.Count - 1 do
begin
x := PCEList[i];
if Copy(x, 1, 4) = 'HDR^' then // HDR ^ Inpatient ^ ProcReq ^ VStr ^ Provider
{header information-------------------------------------------------------------}
begin
FEncInpatient := Piece(x, U, 2) = '1';
//FCPTRequired := Piece(x, U, 3) = '1';
//FNoteHasCPT := Piece(x, U, 6) = '1'; //4/21/99 error! PIECE 3 = cptRequired, not HasCPT!
FEncLocation := StrToIntDef(Piece(Piece(x, U, 4), ';', 1), 0);
if DoRestore then
begin
FEncSvcCat := 'H';
FEncDateTime := FRestDate;
FNoteDateTime := MakeFMDateTime(Piece(Piece(x, U, 4), ';', 2));
end
else
begin
FEncDateTime := MakeFMDateTime(Piece(Piece(x, U, 4), ';', 2));
FEncSvcCat := CharAt(Piece(Piece(x, U, 4), ';', 3), 1);
end;
//FEncProvider := StrToInt64Def(Piece(x, U, 5), 0);
ListVisitTypeByLoc(VisitTypeList, FEncLocation, FEncDateTime);
//set the values needed fot the RPCs
SetRPCEncLocation(FEncLocation);
// SetRPCEncDateTime(FEncDateTime);
end;
{visit information--------------------------------------------------------------}
if Copy(x, 1, 7) = 'VST^DT^' then
begin
if DoRestore then
begin
FEncDateTime := FRestDate;
FNoteDateTime := MakeFMDateTime(Piece(x, U, 3));
end
else
FEncDateTime := MakeFMDateTime(Piece(x, U, 3));
end;
if Copy(x, 1, 7) = 'VST^HL^' then FEncLocation := StrToIntDef(Piece(x, U, 3), 0);
if Copy(x, 1, 7) = 'VST^VC^' then
begin
if DoRestore then
FEncSvcCat := 'H'
else
FEncSvcCat := CharAt(x, 8);
end;
if Copy(x, 1, 7) = 'VST^PS^' then FEncInpatient := CharAt(x, 8) = '1';
{6/10/99}//if Copy(x, 1, 4) = 'PRV^' then FEncProvider := StrToInt64Def(Piece(x, U, 2), 0);
if Copy(x, 1, 7) = 'VST^SC^' then FSCRelated := SCCValue(x);
if Copy(x, 1, 7) = 'VST^AO^' then FAORelated := SCCValue(x);
if Copy(x, 1, 7) = 'VST^IR^' then FIRRelated := SCCValue(x);
if Copy(x, 1, 7) = 'VST^EC^' then FECRelated := SCCValue(x);
if Copy(x, 1, 8) = 'VST^MST^' then FMSTRelated := SCCValue(x);
// if HNCOK and (Copy(x, 1, 8) = 'VST^HNC^') then
if Copy(x, 1, 8) = 'VST^HNC^' then FHNCRelated := SCCValue(x);
if Copy(x, 1, 7) = 'VST^CV^' then FCVRelated := SCCValue(x);
if Copy(x, 1, 9) = 'VST^SHAD^' then FSHADRelated := SCCValue(x);
if IsLejeuneActive then
if Copy(x, 1, 7) = 'VST^CL^' then FCLRelated := SCCValue(x);
if (Copy(x, 1, 3) = 'PRV') and (CharAt(x, 4) <> '-') then
{Providers---------------------------------------------------------------------}
begin
FProviders.Add(x);
end;
if (Copy(x, 1, 3) = 'POV') and (CharAt(x, 4) <> '-') then
{'POV'=Diagnosis--------------------------------------------------------------}
begin
//check for comment append string if a comment exists
x := AppendComment(x);
ADiagnosis := TPCEDiag.Create;
ADiagnosis.SetFromString(x);
FDiagnoses.Add(ADiagnosis);
end;
if (Copy(x, 1, 3) = 'CPT') and (CharAt(x, 4) <> '-') then
{CPT (procedure) information--------------------------------------------------}
begin
x := AppendComment(x);
IsVisit := False;
with VisitTypeList do for j := 0 to Count - 1 do
if Pieces(x, U, 2, 4) = Strings[j] then IsVisit := True;
if IsVisit and (FVisitType.Code = '') then FVisitType.SetFromString(x) else
begin
AProcedure := TPCEProc.Create;
AProcedure.SetFromString(x);
AProcedure.fIsOldProcedure := TRUE;
FProcedures.Add(AProcedure);
end; {if IsVisit}
end; {if Copy}
if (Copy(x, 1, 3) = 'IMM') and (CharAt(x, 4) <> '-') then
{Immunizations ---------------------------------------------------------------}
begin
x := AppendComment(x);
AImmunization := TPCEImm.Create;
AImmunization.SetFromString(x);
FImmunizations.Add(AImmunization);
end;
if (Copy(x, 1, 2) = 'SK') and (CharAt(x, 3) <> '-') then
{Skin Tests-------------------------------------------------------------------}
begin
x := AppendComment(x);
ASkinTest := TPCESkin.Create;
ASkinTest.SetFromString(x);
FSkinTests.Add(ASkinTest);
end;
if (Copy(x, 1, 3) = 'PED') and (CharAt(x, 3) <> '-') then
{Patient Educations------------------------------------------------------------}
begin
x := AppendComment(x);
APatientEd := TPCEpat.Create;
APatientEd.SetFromString(x);
FpatientEds.Add(APatientEd);
end;
if (Copy(x, 1, 2) = 'HF') and (CharAt(x, 3) <> '-') then
{Health Factors----------------------------------------------------------------}
begin
x := AppendComment(x);
AHealthFactor := TPCEHealth.Create;
AHealthFactor.SetFromString(x);
FHealthFactors.Add(AHealthFactor);
end;
if (Copy(x, 1, 3) = 'XAM') and (CharAt(x, 3) <> '-') then
{Exams ------------------------------------------------------------------------}
begin
x := AppendComment(x);
AExam := TPCEExams.Create;
AExam.SetFromString(x);
FExams.Add(AExam);
end;
if (copy(x, 1, 5) = 'GFIND') and (CharAt(x, 4) <> '-') then
begin
AGenFind := TGenFindings.create;
AGenFind.SetFromString(x);
FGenFindings.add(AGenFind);
end;
end;
finally
PCEList.Free;
VisitTypeList.Free;
end;
end;
//procedure TPCEData.Save;
//modified: 6/17/98
//By: Robert Bott
//Location: ISL
//Purpose: Add Comments to PCE Items.
procedure TPCEData.Save;
{ pass the changes to the encounter to DATA2PCE,
Pieces: Subscript^Code^Qualifier^Category^Narrative^Delete }
var
i: Integer;
x, AVisitStr, EncName, Temp2: string;
PCEList: TStringList;
FileCat: char;
FileDate: TFMDateTime;
FileNoteIEN: integer;
dstring1,dstring2: pchar; //used to separate former DelimitedStr variable
// into two strings, the second being for the comment.
begin
PCEList := TStringList.Create;
UNxtCommSeqNum := 1;
try
with PCEList do
begin
if(IsSecondaryVisit) then
begin
FileCat := GetLocSecondaryVisitCode(FEncLocation);
FileDate := FNoteDateTime;
FileNoteIEN := NoteIEN;
if((NoteIEN > 0) and ((FParent = '') or (FParent = '0'))) then
FParent := GetVisitIEN(NoteIEN);
end
else
begin
FileCat := FEncSvcCat;
FileDate := FEncDateTime;
FileNoteIEN := 0;
end;
AVisitStr := IntToStr(FEncLocation) + ';' + FloatToStr(FileDate) + ';' + FileCat;
Add('HDR^' + BOOLCHAR[FEncInpatient] + U + U + AVisitStr);
// Add('HDR^' + BOOLCHAR[FEncInpatient] + U + BOOLCHAR[FNoteHasCPT] + U + AVisitStr);
// set up list that can be passed via broker to set up array for DATA2PCE
Add('VST^DT^' + FloatToStr(FileDate)); // Encounter Date/Time
Add('VST^PT^' + Patient.DFN); // Encounter Patient //*DFN*
if(FEncLocation > 0) then
Add('VST^HL^' + IntToStr(FEncLocation)); // Encounter Location
Add('VST^VC^' + FileCat); // Encounter Service Category
if(StrToIntDef(FParent,0) > 0) then
Add('VST^PR^' + FParent); // Parent for secondary visit
if(FileCat = 'E') and (FHistoricalLocation <> '') then
Add('VST^OL^' + FHistoricalLocation); // Outside Location
FastAddStrings(FProviders, PCEList);
if FSCChanged then
begin
if FSCRelated <> SCC_NA then Add('VST^SC^' + IntToStr(FSCRelated));
if FAORelated <> SCC_NA then Add('VST^AO^' + IntToStr(FAORelated));
if FIRRelated <> SCC_NA then Add('VST^IR^' + IntToStr(FIRRelated));
if FECRelated <> SCC_NA then Add('VST^EC^' + IntToStr(FECRelated));
if FMSTRelated <> SCC_NA then Add('VST^MST^' + IntToStr(FMSTRelated));
if FHNCRelated <> SCC_NA then Add('VST^HNC^'+ IntToStr(FHNCRelated));
if FCVRelated <> SCC_NA then Add('VST^CV^' + IntToStr(FCVRelated));
if FSHADRelated <> SCC_NA then Add('VST^SHD^'+ IntToStr(FSHADRelated));
if IsLejeuneActive then
if FCLRelated <> SCC_NA then Add('VST^CL^'+ IntToStr(FCLRelated));
end;
with FDiagnoses do for i := 0 to Count - 1 do with TPCEDiag(Items[i]) do
if FSend then
begin
Temp2 := DelimitedStr2; // Call first to make sure SaveComment is set.
if(SaveComment) then
dec(UNxtCommSeqNum);
fProvider := FProviders.PCEProvider;
// Provides user with list of dx when signing orders - Billing Aware
PCEList.Add(DelimitedStr);
if(SaveComment) then
begin
inc(UNxtCommSeqNum);
if(Temp2 <> '') then
PCEList.Add(Temp2);
end;
end;
with FProcedures do for i := 0 to Count - 1 do with TPCEProc(Items[i]) do
if FSend then
begin
PCEList.Add(DelimitedStr);
PCEList.Add(DelimitedStr2);
end;
with FImmunizations do for i := 0 to Count - 1 do with TPCEImm(Items[i]) do
if FSend then
begin
PCEList.Add(DelimitedStr);
PCEList.Add(DelimitedStr2);
end;
with FSkinTests do for i := 0 to Count - 1 do with TPCESkin(Items[i]) do
if FSend then
begin
PCEList.Add(DelimitedStr);
PCEList.Add(DelimitedStr2);
end;
with FPatientEds do for i := 0 to Count - 1 do with TPCEPat(Items[i]) do
if FSend then
begin
PCEList.Add(DelimitedStr);
PCEList.Add(DelimitedStr2);
end;
with FHealthFactors do for i := 0 to Count - 1 do with TPCEHealth(Items[i]) do
if FSend then
begin
PCEList.Add(DelimitedStr);
PCEList.Add(DelimitedStr2);
end;
with FExams do for i := 0 to Count - 1 do with TPCEExams(Items[i]) do
if FSend then
begin
PCEList.Add(DelimitedStr);
PCEList.Add(DelimitedStr2);
end;
with FVisitType do
begin
if Code = '' then Fsend := false;
if FSend then
begin
PCEList.Add(DelimitedStr);
PCEList.Add(DelimitedStr2);
end;
end;
// call DATA2PCE (in background)
SavePCEData(PCEList, FileNoteIEN, FEncLocation);
// turn off 'Send' flags and remove items that were deleted
with FDiagnoses do for i := Count - 1 downto 0 do with TPCEDiag(Items[i]) do
begin
FSend := False;
// for diags, toggle off AddProb flag as well
AddProb := False;
if FDelete then
begin
TPCEDiag(Items[i]).Free;
Delete(i);
end;
end;
with FProcedures do for i := Count - 1 downto 0 do with TPCEProc(Items[i]) do
begin
FSend := False;
if FDelete then
begin
TPCEProc(Items[i]).Free;
Delete(i);
end;
end;
with FImmunizations do for i := Count - 1 downto 0 do with TPCEImm(Items[i]) do
begin
FSend := False;
if FDelete then
begin
TPCEImm(Items[i]).Free;
Delete(i);
end;
end;
with FSkinTests do for i := Count - 1 downto 0 do with TPCESkin(Items[i]) do
begin
FSend := False;
if FDelete then
begin
TPCESkin(Items[i]).Free;
Delete(i);
end;
end;
with FPatientEds do for i := Count - 1 downto 0 do with TPCEPat(Items[i]) do
begin
FSend := False;
if FDelete then
begin
TPCEPat(Items[i]).Free;
Delete(i);
end;
end;
with FHealthFactors do for i := Count - 1 downto 0 do with TPCEHealth(Items[i]) do
begin
FSend := False;
if FDelete then
begin
TPCEHealth(Items[i]).Free;
Delete(i);
end;
end;
with FExams do for i := Count - 1 downto 0 do with TPCEExams(Items[i]) do
begin
FSend := False;
if FDelete then
begin
TPCEExams(Items[i]).Free;
Delete(i);
end;
end;
for i := FProviders.Count - 1 downto 0 do
begin
if(FProviders.ProviderData[i].Delete) then
FProviders.Delete(i);
end;
if FVisitType.FDelete then FVisitType.Clear else FVisitType.FSend := False;
end; {with PCEList}
//if (FProcedures.Count > 0) or (FVisitType.Code <> '') then FCPTRequired := False;
// update the Changes object
EncName := FormatFMDateTime('mmm dd,yy hh:nn', FileDate);
x := StrVisitType;
if Length(x) > 0 then Changes.Add(CH_PCE, 'V' + AVisitStr, x, EncName, CH_SIGN_NA);
x := StrProcedures;
if Length(x) > 0 then Changes.Add(CH_PCE, 'P' + AVisitStr, x, EncName, CH_SIGN_NA);
x := StrDiagnoses;
if Length(x) > 0 then Changes.Add(CH_PCE, 'D' + AVisitStr, x, EncName, CH_SIGN_NA,
Parent, User.DUZ, '', False, False, ProblemAdded);
x := StrImmunizations;
if Length(x) > 0 then Changes.Add(CH_PCE, 'I' + AVisitStr, x, EncName, CH_SIGN_NA);
x := StrSkinTests;
if Length(x) > 0 then Changes.Add(CH_PCE, 'S' + AVisitStr, x, EncName, CH_SIGN_NA);
x := StrPatientEds;
if Length(x) > 0 then Changes.Add(CH_PCE, 'A' + AVisitStr, x, EncName, CH_SIGN_NA);
x := StrHealthFactors;
if Length(x) > 0 then Changes.Add(CH_PCE, 'H' + AVisitStr, x, EncName, CH_SIGN_NA);
x := StrExams;
if Length(x) > 0 then Changes.Add(CH_PCE, 'E' + AVisitStr, x, EncName, CH_SIGN_NA);
finally
PCEList.Free;
end;
end;
function TPCEData.MatchItem(AList: TList; AnItem: TPCEItem): Integer;
{ return index in AList of matching item }
var
i: Integer;
begin
Result := -1;
with AList do for i := 0 to Count - 1 do with TPCEItem(Items[i]) do if Match(AnItem) and MatchProvider(AnItem)then
begin
Result := i;
break;
end;
end;
function TPCEData.MatchPOVItems(AList: TList; AnItem: TPCEItem): Integer;
var
i: Integer;
begin
Result := -1;
with AList do for i := 0 to Count - 1 do with TPCEItem(Items[i]) do if MatchPOV(AnItem) and MatchProvider(AnItem)then
begin
Result := i;
break;
end;
end;
procedure TPCEData.MarkDeletions(PreList: TList; PostList: TStrings);
{mark items that need deleted}
var
i, j: Integer;
MatchFound: Boolean;
PreItem, PostItem: TPCEItem;
begin
with PreList do for i := 0 to Count - 1 do
begin
PreItem := TPCEItem(Items[i]);
MatchFound := False;
with PostList do for j := 0 to Count - 1 do
begin
PostItem := TPCEItem(Objects[j]);
//fix to not mark the ICD-10 diagnosis for deletion when selected to add to the Problem List.
if (Piece(PostItem.DelimitedStr, '^', 1)='POV+') and (Piece(PostItem.DelimitedStr, '^', 7)='1') and
(PreItem.Code = PostItem.Code) and (Pos('SNOMED', Piece(PostItem.DelimitedStr, '^', 4)) > 0) then
MatchFound := True
else if (PreItem.Match(PostItem) and (PreItem.MatchProvider(PostItem))) then MatchFound := True;
end;
if not MatchFound then
begin
PreItem.FDelete := True;
PreItem.FSend := True;
end;
end;
end;
procedure TPCEData.SetDiagnoses(Src: TStrings; FromForm: boolean = TRUE);
{ load diagnoses for this encounter into TPCEDiag records, assumes all diagnoses for the
encounter will be listed in Src and marks those that are not in Src for deletion }
var
i, MatchIndex: Integer;
SrcDiagnosis, CurDiagnosis, PrimaryDiag: TPCEDiag;
begin
if FromForm then MarkDeletions(FDiagnoses, Src);
PrimaryDiag := nil;
for i := 0 to Src.Count - 1 do
begin
SrcDiagnosis := TPCEDiag(Src.Objects[i]);
MatchIndex := MatchPOVItems(FDiagnoses, SrcDiagnosis);
if MatchIndex > -1 then //found in fdiagnoses
begin
CurDiagnosis := TPCEDiag(FDiagnoses.Items[MatchIndex]);
if ((SrcDiagnosis.Primary <> CurDiagnosis.Primary) or
(SrcDiagnosis.Comment <> CurDiagnosis.Comment) or
(SrcDiagnosis.AddProb <> CurDiagnosis.Addprob) or
(SrcDiagnosis.Narrative <> CurDiagnosis.Narrative)) then
begin
CurDiagnosis.Primary := SrcDiagnosis.Primary;
CurDiagnosis.Comment := SrcDiagnosis.Comment;
CurDiagnosis.AddProb := SrcDiagnosis.AddProb;
CurDiagnosis.Narrative := SrcDiagnosis.Narrative;
CurDiagnosis.FSend := True;
end;
end
else
begin
CurDiagnosis := TPCEDiag.Create;
CurDiagnosis.Assign(SrcDiagnosis);
CurDiagnosis.FSend := True;
FDiagnoses.Add(CurDiagnosis);
end; {if MatchIndex}
if(CurDiagnosis.Primary and (not assigned(PrimaryDiag))) then
PrimaryDiag := CurDiagnosis;
if (CurDiagnosis.AddProb) then
FProblemAdded := True;
end; {for}
if(assigned(PrimaryDiag)) then
begin
for i := 0 to FDiagnoses.Count - 1 do
begin
CurDiagnosis := TPCEDiag(FDiagnoses[i]);
if(CurDiagnosis.Primary) and (CurDiagnosis <> PrimaryDiag) then
begin
CurDiagnosis.Primary := FALSE;
CurDiagnosis.FSend := True;
end;
end;
end;
end;
procedure TPCEData.SetProcedures(Src: TStrings; FromForm: boolean = TRUE);
{ load Procedures for this encounter into TPCEProc records, assumes all Procedures for the
encounter will be listed in Src and marks those that are not in Src for deletion }
var
i, MatchIndex: Integer;
SrcProcedure, CurProcedure, oldProcedure: TPCEProc;
begin
if FromForm then MarkDeletions(FProcedures, Src);
for i := 0 to Src.Count - 1 do
begin
SrcProcedure := TPCEProc(Src.Objects[i]);
MatchIndex := MatchItem(FProcedures, SrcProcedure);
if MatchIndex > -1 then
begin
CurProcedure := TPCEProc(FProcedures.Items[MatchIndex]);
(* if (SrcProcedure.Provider <> CurProcedure.Provider) then
begin
OldProcedure := TPCEProc.Create;
OldProcedure.Assign(CurProcedure);
OldProcedure.FDelete := TRUE;
OldProcedure.FSend := TRUE;
FProcedures.Add(OldProcedure);
end;*)
if (SrcProcedure.Quantity <> CurProcedure.Quantity) or
(SrcProcedure.Provider <> CurProcedure.Provider) or
(Curprocedure.Comment <> SrcProcedure.Comment) or
(Curprocedure.Modifiers <> SrcProcedure.Modifiers)then
begin
OldProcedure := TPCEProc.Create;
OldProcedure.Assign(CurProcedure);
OldProcedure.FDelete := TRUE;
OldProcedure.FSend := TRUE;
FProcedures.Add(OldProcedure);
CurProcedure.Quantity := SrcProcedure.Quantity;
CurProcedure.Provider := SrcProcedure.Provider;
CurProcedure.Comment := SrcProcedure.Comment;
CurProcedure.Modifiers := SrcProcedure.Modifiers;
CurProcedure.FSend := True;
end;
end else
begin
CurProcedure := TPCEProc.Create;
CurProcedure.Assign(SrcProcedure);
CurProcedure.FSend := True;
FProcedures.Add(CurProcedure);
end; {if MatchIndex}
end; {for}
end;
procedure TPCEData.SetImmunizations(Src: TStrings; FromForm: boolean = TRUE);
{ load Immunizations for this encounter into TPCEImm records, assumes all Immunizations for the
encounter will be listed in Src and marks those that are not in Src for deletion }
var
i, MatchIndex: Integer;
SrcImmunization, CurImmunization: TPCEImm;
begin
if FromForm then MarkDeletions(FImmunizations, Src);
for i := 0 to Src.Count - 1 do
begin
SrcImmunization := TPCEImm(Src.Objects[i]);
MatchIndex := MatchItem(FImmunizations, SrcImmunization);
if MatchIndex > -1 then
begin
CurImmunization := TPCEImm(FImmunizations.Items[MatchIndex]);
//set null strings to NoPCEValue
if SrcImmunization.Series = '' then SrcImmunization.Series := NoPCEValue;
if SrcImmunization.Reaction = '' then SrcImmunization.Reaction := NoPCEValue;
if CurImmunization.Series = '' then CurImmunization.Series := NoPCEValue;
if CurImmunization.Reaction = '' then CurImmunization.Reaction := NoPCEValue;
if(SrcImmunization.Series <> CurImmunization.Series) or
(SrcImmunization.Reaction <> CurImmunization.Reaction) or
(SrcImmunization.Refused <> CurImmunization.Refused) or
(SrcImmunization.Contraindicated <> CurImmunization.Contraindicated) or
(CurImmunization.Comment <> SrcImmunization.Comment)then
begin
CurImmunization.Series := SrcImmunization.Series;
CurImmunization.Reaction := SrcImmunization.Reaction;
CurImmunization.Refused := SrcImmunization.Refused;
CurImmunization.Contraindicated := SrcImmunization.Contraindicated;
CurImmunization.Comment := SrcImmunization.Comment;
CurImmunization.FSend := True;
end;
end else
begin
CurImmunization := TPCEImm.Create;
CurImmunization.Assign(SrcImmunization);
CurImmunization.FSend := True;
FImmunizations.Add(CurImmunization);
end; {if MatchIndex}
end; {for}
end;
procedure TPCEData.SetSkinTests(Src: TStrings; FromForm: boolean = TRUE);
{ load SkinTests for this encounter into TPCESkin records, assumes all SkinTests for the
encounter will be listed in Src and marks those that are not in Src for deletion }
var
i, MatchIndex: Integer;
SrcSkinTest, CurSkinTest: TPCESkin;
begin
if FromForm then MarkDeletions(FSKinTests, Src);
for i := 0 to Src.Count - 1 do
begin
SrcSkinTest := TPCESkin(Src.Objects[i]);
MatchIndex := MatchItem(FSKinTests, SrcSkinTest);
if MatchIndex > -1 then
begin
CurSkinTest := TPCESKin(FSkinTests.Items[MatchIndex]);
if CurSkinTest.Results = '' then CurSkinTest.Results := NoPCEValue;
if SrcSkinTest.Results = '' then SrcSkinTest.Results := NoPCEValue;
if(SrcSkinTest.Results <> CurSkinTest.Results) or
(SrcSkinTest.Reading <> CurSkinTest.Reading) or
(CurSkinTest.Comment <> SrcSkinTest.Comment) then
begin
CurSkinTest.Results := SrcSkinTest.Results;
CurSkinTest.Reading := SrcSkinTest.Reading;
CurSkinTest.Comment := SrcSkinTest.Comment;
CurSkinTest.FSend := True;
end;
end else
begin
CurSKinTest := TPCESkin.Create;
CurSkinTest.Assign(SrcSkinTest);
CurSkinTest.FSend := True;
FSkinTests.Add(CurSkinTest);
end; {if MatchIndex}
end; {for}
end;
procedure TPCEData.SetPatientEds(Src: TStrings; FromForm: boolean = TRUE);
var
i, MatchIndex: Integer;
SrcPatientEd, CurPatientEd: TPCEPat;
begin
if FromForm then MarkDeletions(FPatientEds, Src);
for i := 0 to Src.Count - 1 do
begin
SrcPatientEd := TPCEPat(Src.Objects[i]);
MatchIndex := MatchItem(FPatientEds, SrcPatientEd);
if MatchIndex > -1 then
begin
CurPatientEd := TPCEPat(FPatientEds.Items[MatchIndex]);
if CurPatientEd.level = '' then CurPatientEd.level := NoPCEValue;
if SrcPatientEd.level = '' then SrcPatientEd.level := NoPCEValue;
if(SrcPatientEd.Level <> CurPatientEd.Level) or
(CurPatientEd.Comment <> SrcPatientEd.Comment) then
begin
CurPatientEd.Level := SrcPatientEd.Level;
CurPatientEd.Comment := SrcPatientEd.Comment;
CurPatientEd.FSend := True;
end;
end else
begin
CurPatientEd := TPCEPat.Create;
CurPatientEd.Assign(SrcPatientEd);
CurPatientEd.FSend := True;
FPatientEds.Add(CurPatientEd);
end; {if MatchIndex}
end; {for}
end;
procedure TPCEData.SetHealthFactors(Src: TStrings; FromForm: boolean = TRUE);
var
i, MatchIndex: Integer;
SrcHealthFactor, CurHealthFactor: TPCEHealth;
begin
if FromForm then MarkDeletions(FHealthFactors, Src);
for i := 0 to Src.Count - 1 do
begin
SrcHealthFactor := TPCEHealth(Src.Objects[i]);
MatchIndex := MatchItem(FHealthFactors, SrcHealthFactor);
if MatchIndex > -1 then
begin
CurHealthFactor := TPCEHealth(FHealthFactors.Items[MatchIndex]);
if CurHealthFactor.level = '' then CurHealthFactor.level := NoPCEValue;
if SrcHealthFactor.level = '' then SrcHealthFactor.level := NoPCEValue;
if(SrcHealthFactor.Level <> CurHealthFactor.Level) or
(CurHealthFactor.Comment <> SrcHealthFactor.Comment) then
begin
CurHealthFactor.Level := SrcHealthFactor.Level;
CurHealthFactor.Comment := SrcHealthFactor.Comment;
CurHealthFactor.FSend := True;
end;
if(SrcHealthFactor.GecRem <> CurHealthFactor.GecRem) then
CurHealthFactor.GecRem := SrcHealthFactor.GecRem;
end else
begin
CurHealthFactor := TPCEHealth.Create;
CurHealthFactor.Assign(SrcHealthFactor);
CurHealthFactor.FSend := True;
CurHealthFactor.GecRem := SrcHealthFactor.GecRem;
FHealthFactors.Add(CurHealthFactor);
end; {if MatchIndex}
end; {for}
end;
procedure TPCEData.SetExams(Src: TStrings; FromForm: boolean = TRUE);
var
i, MatchIndex: Integer;
SrcExam, CurExam: TPCEExams;
begin
if FromForm then MarkDeletions(FExams, Src);
for i := 0 to Src.Count - 1 do
begin
SrcExam := TPCEExams(Src.Objects[i]);
MatchIndex := MatchItem(FExams, SrcExam);
if MatchIndex > -1 then
begin
CurExam := TPCEExams(FExams.Items[MatchIndex]);
if CurExam.Results = '' then CurExam.Results := NoPCEValue;
if SrcExam.Results = '' then SrcExam.Results := NoPCEValue;
if(SrcExam.Results <> CurExam.Results) or
(CurExam.Comment <> SrcExam.Comment) then
begin
CurExam.Results := SrcExam.Results;
CurExam.Comment := SrcExam.Comment;
CurExam.Fsend := True;
end;
end else
begin
CurExam := TPCEExams.Create;
CurExam.Assign(SrcExam);
CurExam.FSend := True;
FExams.Add(CurExam);
end; {if MatchIndex}
end; {for}
end;
procedure TPCEData.SetGenFindings(Src: TStrings; FromForm: boolean);
var
i, MatchIndex: Integer;
SrcGFind, CurGFind: TGenFindings;
begin
//set for general findings from Reminder Dialog
if FromForm then MarkDeletions(FGenFindings, Src);
for i := 0 to Src.Count - 1 do
begin
SrcGFind := TGenFindings(Src.Objects[i]);
MatchIndex := MatchItem(FGenFindings, SrcGFind);
if MatchIndex = -1 then
begin
CurGFind := TGenFindings.Create;
CurGFind.Assign(SrcGFind);
CurGFind.FSend := True;
FGenFindings.Add(CurGFind);
end; {if MatchIndex}
end; {for}
end;
procedure TPCEData.SetVisitType(Value: TPCEProc);
var
VisitDelete: TPCEProc;
begin
if (not FVisitType.Match(Value)) or
(FVisitType.Modifiers <> Value.Modifiers) then {causes CPT delete/re-add}
begin
if FVisitType.Code <> '' then // add old visit to procedures for deletion
begin
VisitDelete := TPCEProc.Create;
VisitDelete.Assign(FVisitType);
VisitDelete.FDelete := True;
VisitDelete.FSend := True;
FProcedures.Add(VisitDelete);
end;
FVisitType.Assign(Value);
FVisitType.Quantity := 1;
FVisitType.FSend := True;
end;
end;
procedure TPCEData.SetSCRelated(Value: Integer);
begin
if Value <> FSCRelated then
begin
FSCRelated := Value;
FSCChanged := True;
end;
end;
procedure TPCEData.SetAORelated(Value: Integer);
begin
if Value <> FAORelated then
begin
FAORelated := Value;
FSCChanged := True;
end;
end;
procedure TPCEData.SetIRRelated(Value: Integer);
begin
if Value <> FIRRelated then
begin
FIRRelated := Value;
FSCChanged := True;
end;
end;
procedure TPCEData.SetECRelated(Value: Integer);
begin
if Value <> FECRelated then
begin
FECRelated := Value;
FSCChanged := True;
end;
end;
procedure TPCEData.SetMSTRelated(Value: Integer);
begin
if Value <> FMSTRelated then
begin
FMSTRelated := Value;
FSCChanged := True;
end;
end;
procedure TPCEData.SetHNCRelated(Value: Integer);
begin
// if HNCOK and (Value <> FHNCRelated) then
if Value <> FHNCRelated then
begin
FHNCRelated := Value;
FSCChanged := True;
end;
end;
procedure TPCEData.SetCVRelated(Value: Integer);
begin
if (Value <> FCVRelated) then
begin
FCVRelated := Value;
FSCChanged := True;
end;
end;
procedure TPCEData.SetSHADRelated(Value: Integer);
begin
if (Value <> FSHADRelated) then
begin
FSHADRelated := Value;
FSCChanged := True;
end;
end;
procedure TPCEData.SetCLRelated(Value: Integer);
begin
if (Value <> FCLRelated) then
begin
FCLRelated := Value;
FSCChanged := True;
end;
end;
procedure TPCEData.SetEncUseCurr(Value: Boolean);
begin
FEncUseCurr := Value;
if FEncUseCurr then
begin
FEncDateTime := Encounter.DateTime;
FEncLocation := Encounter.Location;
//need to add to full list of providers
FEncSvcCat := Encounter.VisitCategory;
FStandAlone := Encounter.StandAlone;
FStandAloneLoaded := TRUE;
FEncInpatient := Encounter.Inpatient;
end else
begin
FEncDateTime := 0;
FEncLocation := 0;
FStandAlone := FALSE;
FStandAloneLoaded := FALSE;
FProviders.PrimaryIdx := -1;
FEncSvcCat := 'A';
FEncInpatient := False;
end;
//
SetRPCEncLocation(FEncLocation);
end;
function TPCEData.StrDiagnoses: string;
{ returns the list of diagnoses for this encounter as a single comma delimited string }
var
i: Integer;
begin
Result := '';
with FDiagnoses do for i := 0 to Count - 1 do with TPCEDiag(Items[i]) do
if not FDelete then
Result := Result + GetPCEDataText(pdcDiag, Code, Category, Narrative, Primary) + CRLF;
if Length(Result) > 0 then Result := PCEDataCatText[pdcDiag] + CRLF + Copy(Result, 1, Length(Result) - 2) + CRLF;
end;
function TPCEData.StrProcedures: string;
{ returns the list of procedures for this encounter as a single comma delimited string }
var
i: Integer;
begin
Result := '';
with FProcedures do for i := 0 to Count - 1 do with TPCEProc(Items[i]) do
if not FDelete then
Result := Result + GetPCEDataText(pdcProc, Code, Category, Narrative, FALSE, Quantity) +
ModText + CRLF;
if Length(Result) > 0 then Result := PCEDataCatText[pdcProc] + CRLF + Copy(Result, 1, Length(Result) - 2) + CRLF;
end;
function TPCEData.StrImmunizations: string;
{ returns the list of Immunizations for this encounter as a single comma delimited string }
var
i: Integer;
begin
Result := '';
with FImmunizations do for i := 0 to Count - 1 do with TPCEImm(Items[i]) do
if not FDelete then
Result := Result + GetPCEDataText(pdcImm, Code, Category, Narrative) + CRLF;
if Length(Result) > 0 then Result := PCEDataCatText[pdcImm] + CRLF + Copy(Result, 1, Length(Result) - 2) + CRLF;
end;
function TPCEData.StrSkinTests: string;
{ returns the list of Immunizations for this encounter as a single comma delimited string }
var
i: Integer;
begin
Result := '';
with FSkinTests do for i := 0 to Count - 1 do with TPCESkin(Items[i]) do
if not FDelete then
Result := Result + GetPCEDataText(pdcSkin, Code, Category, Narrative) + CRLF;
if Length(Result) > 0 then Result := PCEDataCatText[pdcSkin] + CRLF + Copy(Result, 1, Length(Result) - 2) + CRLF;
end;
function TPCEData.StrPatientEds: string;
var
i: Integer;
begin
Result := '';
with FPatientEds do for i := 0 to Count - 1 do with TPCEPat(Items[i]) do
if not FDelete then
Result := Result + GetPCEDataText(pdcPED, Code, Category, Narrative) + CRLF;
if Length(Result) > 0 then Result := PCEDataCatText[pdcPED] + CRLF + Copy(Result, 1, Length(Result) - 2) + CRLF;
end;
function TPCEData.StrHealthFactors: string;
var
i: Integer;
begin
Result := '';
with FHealthFactors do for i := 0 to Count - 1 do with TPCEHealth(Items[i]) do
if not FDelete then
Result := Result + GetPCEDataText(pdcHF, Code, Category, Narrative) + CRLF;
if Length(Result) > 0 then Result := PCEDataCatText[pdcHF] + CRLF + Copy(Result, 1, Length(Result) - 2) + CRLF;
end;
function TPCEData.StrExams: string;
var
i: Integer;
begin
Result := '';
with FExams do for i := 0 to Count - 1 do with TPCEExams(Items[i]) do
if not FDelete then
Result := Result + GetPCEDataText(pdcExam, Code, Category, Narrative) + CRLF;
if Length(Result) > 0 then Result := PCEDataCatText[pdcExam] + CRLF + Copy(Result, 1, Length(Result) - 2) + CRLF;
end;
function TPCEData.StrGenFindings: string;
var
i: Integer;
begin
with FGenFindings do for i := 0 to Count - 1 do with TGenFindings(Items[i]) do
if not FDelete then
Result := Result + GetPCEDataText(pdcGenFinding, Code, Category, Narrative) + CRLF;
if Length(Result) > 0 then Result := PCEDataCatText[pdcGenFinding] + CRLF + Copy(Result, 1, Length(Result) - 2) + CRLF;
end;
function TPCEData.StrVisitType(const ASCRelated, AAORelated, AIRRelated,
AECRelated, AMSTRelated, AHNCRelated, ACVRelated, ASHADRelated, ACLRelated: Integer): string;
{ returns as a string the type of encounter (according to CPT) & related contitions treated }
procedure AddTxt(txt: string);
begin
if(Result <> '') then
Result := Result + ',';
Result := Result + ' ' + txt;
end;
begin
Result := '';
if ASCRelated = SCC_YES then AddTxt('Service Connected Condition');
if AAORelated = SCC_YES then AddTxt('Agent Orange Exposure');
if AIRRelated = SCC_YES then AddTxt('Ionizing Radiation Exposure');
if AECRelated = SCC_YES then AddTxt('Environmental Contaminants');
if AMSTRelated = SCC_YES then AddTxt('MST');//'Military Sexual Trauma';
// if HNCOK and (AHNCRelated = SCC_YES) then AddTxt('Head and/or Neck Cancer');
if AHNCRelated = SCC_YES then AddTxt('Head and/or Neck Cancer');
if ACVRelated = SCC_YES then AddTxt('Combat Veteran Related');
if ASHADRelated = SCC_YES then AddTxt('Shipboard Hazard and Defense');
if ACLRelated = SCC_YES then AddTxt('Camp Lejeune'); //Camp Lejeune
if Length(Result) > 0 then Result := ' Related to: ' + Result;
// Result := Trim(Result);
end;
function TPCEData.StrVisitType: string;
{ returns as a string the type of encounter (according to CPT) & related contitions treated }
begin
Result := '';
with FVisitType do
begin
Result := GetPCEDataText(pdcVisit, Code, Category, Narrative);
if Length(ModText) > 0 then Result := Result + ModText + ', ';
end;
Result := Trim(Result + StrVisitType(FSCRelated, FAORelated, FIRRelated,
FECRelated, FMSTRelated, FHNCRelated, FCVRelated, FSHADRelated, FCLRelated));
end;
function TPCEData.StandAlone: boolean;
var
Sts: integer;
begin
if(not FStandAloneLoaded) and ((FNoteIEN > 0) or ((FEncLocation > 0) and (FEncDateTime > 0))) then
begin
Sts := HasVisit(FNoteIEN, FEncLocation, FEncDateTime);
FStandAlone := (Sts <> 1);
if(Sts >= 0) then
FStandAloneLoaded := TRUE;
end;
Result := FStandAlone;
end;
function TPCEData.getDocCount: Integer;
begin
rESULT := 1;
// result := DocCount(vISIT);
end;
{function TPCEItem.MatchProvider(AnItem: TPCEItem): Boolean;
begin
Result := False;
if (Provider = AnItem.Provider) then Result := True;
end;
}
function TPCEItem.MatchPOV(AnItem: TPCEItem): Boolean;
begin
Result := False;
if (Code = AnItem.Code) and (Category = AnItem.Category)
then Result := True;
end;
function TPCEItem.MatchProvider(AnItem: TPCEItem): Boolean;
begin
Result := False;
if (Provider = AnItem.Provider) then Result := True;
end;
function TPCEData.GetHasData: Boolean;
begin
result := True;
if ((FDiagnoses.count = 0)
and (FProcedures.count = 0)
and (FImmunizations.count = 0)
and (FSkinTests.count = 0)
and (FPatientEds.count = 0)
and (FHealthFactors.count = 0)
and (fExams.count = 0) and
(FvisitType.Quantity = 0))then
result := False;
end;
procedure TPCEData.CopyPCEData(Dest: TPCEData);
begin
Dest.Clear;
Dest.FEncDateTime := FEncDateTime;
Dest.FNoteDateTime := FNoteDateTime;
Dest.FEncLocation := FEncLocation;
Dest.FEncSvcCat := FEncSvcCat;
Dest.FEncInpatient := FEncInpatient;
Dest.FStandAlone := FStandAlone;
Dest.FStandAloneLoaded := FStandAloneLoaded;
Dest.FEncUseCurr := FEncUseCurr;
Dest.FSCChanged := FSCChanged;
Dest.FSCRelated := FSCRelated;
Dest.FAORelated := FAORelated;
Dest.FIRRelated := FIRRelated;
Dest.FECRelated := FECRelated;
Dest.FMSTRelated := FMSTRelated;
Dest.FHNCRelated := FHNCRelated;
Dest.FCVRelated := FCVRelated;
Dest.FSHADRelated := FSHADRelated;
if IsLejeuneActive then
Dest.fCLRelated := FCLRelated; //Camp Lejeune
FVisitType.CopyProc(Dest.VisitType);
Dest.FProviders.Assign(FProviders);
CopyPCEItems(FDiagnoses, Dest.FDiagnoses, TPCEDiag);
CopyPCEItems(FProcedures, Dest.FProcedures, TPCEProc);
CopyPCEItems(FImmunizations, Dest.FImmunizations, TPCEImm);
CopyPCEItems(FSkinTests, Dest.FSkinTests, TPCESkin);
CopyPCEItems(FPatientEds, Dest.FPatientEds, TPCEPat);
CopyPCEItems(FHealthFactors, Dest.FHealthFactors, TPCEHealth);
CopyPCEItems(FExams, Dest.FExams, TPCEExams);
CopyPCEITems(FGenFindings, Dest.FGenFindings, TGenFindings);
Dest.FNoteTitle := FNoteTitle;
Dest.FNoteIEN := FNoteIEN;
Dest.FParent := FParent;
Dest.FHistoricalLocation := FHistoricalLocation;
end;
function TPCEData.NeededPCEData: tRequiredPCEDataTypes;
var
EC: TSCConditions;
NeedSC: boolean;
TmpLst: TStringList;
NeedDx: Boolean;
I : Integer;
begin
Result := [];
if(not FutureEncounter(Self)) then
begin
if(PromptForWorkload(FNoteIEN, FNoteTitle, FEncSvcCat, StandAlone)) then
begin
//assume we need a DX
NeedDx := true;
for i := 0 to fdiagnoses.count -1 do
begin
if TPCEDiag(FDiagnoses[i]).Primary then
begin
NeedDX := false;
break;
end;
end;
if NeedDX then Include(result, ndDiag);
if((fprocedures.count <= 0) and (fVisitType.Code = '')) then
begin
TmpLst := TStringList.Create;
try
GetHasCPTList(TmpLst);
if(not DataHasCPTCodes(TmpLst)) then
Include(Result, ndProc);
finally
TmpLst.Free;
end;
end;
if(RequireExposures(FNoteIEN, FNoteTitle)) then
begin
NeedSC := FALSE;
EC := EligbleConditions;
if (EC.SCAllow and (SCRelated = SCC_NA)) then
NeedSC := TRUE
else if(SCRelated <> SCC_YES) then //if screlated = yes, the others are not asked.
begin
if(EC.AOAllow and (AORelated = SCC_NA)) then NeedSC := TRUE
else if(EC.IRAllow and (IRRelated = SCC_NA)) then NeedSC := TRUE
else if(EC.ECAllow and (ECRelated = SCC_NA)) then NeedSC := TRUE
end;
if(EC.MSTAllow and (MSTRelated = SCC_NA)) then NeedSC := TRUE;
// if HNCOK and (EC.HNCAllow and (HNCRelated = SCC_NA)) then NeedSC := TRUE;
if(EC.HNCAllow and (HNCRelated = SCC_NA)) then NeedSC := TRUE;
if(EC.CVAllow and (CVRelated = SCC_NA) and (SHADRelated = SCC_NA)) then NeedSC := TRUE;
if(NeedSC) then
Include(Result, ndSC);
end;
(* if(Result = []) and (FNoteIEN > 0) then // **** block removed in v19.1 {RV} ****
ClearCPTRequired(FNoteIEN);*)
end;
end;
end;
function TPCEData.OK2SignNote: boolean;
var
Req: tRequiredPCEDataTypes;
msg: string;
Asked, DoAsk, Primary, Needed: boolean;
Outpatient, First, DoSave, NeedSave, Done: boolean;
Ans: integer;
Flags: word;
Ask: TAskPCE;
procedure Add(Typ: tRequiredPCEDataType; txt: string);
begin
if(Typ in Req) then
msg := msg + txt + CRLF;
end;
begin
if not CanEditPCE(Self) then
begin
Result := TRUE;
exit;
end;
if IsNonCountClinic(FEncLocation) then
begin
Result := TRUE;
exit;
end;
if IsCancelOrNoShow(NoteIEN) then
begin
Result := TRUE;
exit;
end;
Ask := GetAskPCE(FEncLocation);
if(Ask = apNever) or (Ask = apDisable) then
Result := TRUE
else
begin
DoSave := FALSE;
try
Asked := FALSE;
First := TRUE;
Outpatient := ((FEncSvcCat = 'A') or (FEncSvcCat = 'I') or (FEncSvcCat = 'T'));
repeat
Result := TRUE;
Done := TRUE;
Req := NeededPCEData;
Needed := (Req <> []);
if(First) then
begin
if Needed and (not Outpatient) then
OutPatient := TRUE;
if((Ask = apPrimaryAlways) or Needed or
((Ask = apPrimaryOutpatient) and Outpatient)) then
begin
if(Providers.PrimaryIdx < 0) then
begin
NoPrimaryPCEProvider(FProviders, Self);
if(not DoSave) then
DoSave := (Providers.PrimaryIdx >= 0);
if(DoSave and (FProviders.PendingIEN(FALSE) <> 0) and
(FProviders.IndexOfProvider(IntToStr(FProviders.PendingIEN(FALSE))) < 0)) then
FProviders.AddProvider(IntToStr(FProviders.PendingIEN(FALSE)), FProviders.PendingName(FALSE), FALSE);
end;
end;
First := FALSE;
end;
Primary := (Providers.PrimaryIEN = User.DUZ);
case Ask of
apPrimaryOutpatient: DoAsk := (Primary and Outpatient);
apPrimaryAlways: DoAsk := Primary;
apNeeded: DoAsk := Needed;
apOutpatient: DoAsk := Outpatient;
apAlways: DoAsk := TRUE;
else
{ apPrimaryNeeded } DoAsk := (Primary and Needed);
end;
if(DoAsk) then
begin
if(Asked and ((not Needed) or (not Primary))) then
exit;
if(Needed) then
begin
msg := TX_NEED1;
Add(ndDiag, TX_NEED_DIAG);
Add(ndProc, TX_NEED_PROC);
Add(ndSC, TX_NEED_SC);
if(Primary and ForcePCEEntry(FEncLocation)) then
begin
Flags := MB_OKCANCEL;
msg := msg + CRLF + TX_NEED3;
end
else
begin
if(Primary) then
Flags := MB_YESNOCANCEL
else
Flags := MB_YESNO;
msg := msg + CRLF + TX_NEED2;
end;
Flags := Flags + MB_ICONWARNING;
end
else
begin
Flags := MB_YESNO + MB_ICONQUESTION;
msg := TX_NEED2;
end;
Ans := InfoBox(msg, TX_NEED_T, Flags);
if(Ans = ID_CANCEL) then
begin
Result := FALSE;
InfoBox(TX_NEEDABORT, TX_NEED_T, MB_OK);
exit;
end;
Result := (Ans = ID_NO);
if(not Result) then
begin
if(not MissingProviderInfo(Self)) then
begin
NeedSave := UpdatePCE(Self, FALSE);
if(not DoSave) then
DoSave := NeedSave;
FUpdated := TRUE;
end;
done := frmFrame.Closing;
Asked := TRUE;
end;
end;
until(Done);
finally
if(DoSave) then
Save;
end;
end;
end;
procedure TPCEData.AddStrData(List: TStrings);
procedure Add(Txt: string);
begin
if(length(Txt) > 0) then List.Add(Txt);
end;
begin
Add(StrVisitType);
Add(StrDiagnoses);
Add(StrProcedures);
Add(StrImmunizations);
Add(StrSkinTests);
Add(StrPatientEds);
Add(StrHealthFactors);
Add(StrExams);
Add(StrGenFindings);
end;
procedure TPCEData.AddVitalData(Data, List: TStrings);
var
i: integer;
begin
for i := 0 to Data.Count-1 do
List.Add(FormatVitalForNote(Data[i]));
end;
function TPCEData.PersonClassDate: TFMDateTime;
begin
if(FEncSvcCat = 'H') then
Result := FMToday
else
Result := FEncDateTime; //Encounter.DateTime;
end;
function TPCEData.VisitDateTime: TFMDateTime;
begin
if(IsSecondaryVisit) then
Result := FNoteDateTime
else
Result := FEncDateTime;
end;
function TPCEData.IsSecondaryVisit: boolean;
begin
Result := ((FEncSvcCat = 'H') and (FNoteDateTime > 0) and (FEncInpatient));
end;
function TPCEData.NeedProviderInfo: boolean;
var
i: integer;
TmpLst: TStringList;
begin
if(FProviders.PrimaryIdx < 0) then
begin
Result := AutoCheckout(FEncLocation);
if not Result then
begin
for i := 0 to FDiagnoses.Count - 1 do
begin
if not TPCEDiag(FDiagnoses[i]).FDelete then
begin
Result := TRUE;
break;
end;
end;
end;
if not Result then
begin
for i := 0 to FProcedures.Count - 1 do
begin
if not TPCEProc(FProcedures[i]).FDelete then
begin
Result := TRUE;
break;
end;
end;
end;
if not Result then
begin
for i := 0 to FProviders.Count - 1 do
begin
if not FProviders[i].Delete then
begin
Result := TRUE;
break;
end;
end;
end;
if not Result then
begin
TmpLst := TStringList.Create;
try
GetHasCPTList(TmpLst);
if(DataHasCPTCodes(TmpLst)) then
Result := TRUE;
finally
TmpLst.Free;
end;
end;
end
else
Result := FALSE;
end;
procedure TPCEData.GetHasCPTList(AList: TStrings);
procedure AddList(List: TList);
var
i: integer;
tmp: string;
begin
for i := 0 to List.Count-1 do
begin
tmp := TPCEItem(List[i]).HasCPTStr;
if(tmp <> '') then
AList.Add(tmp);
end;
end;
begin
AddList(FImmunizations);
AddList(FSkinTests);
AddList(FPatientEds);
AddList(FHealthFactors);
AddList(FExams);
end;
procedure TPCEData.CopyPCEItems(Src: TList; Dest: TObject; ItemClass: TPCEItemClass);
Type
fDestType = (CopyCaptionList, CopyStrings, CopyList);
var
AItem: TPCEItem;
i: Integer;
DestType: fDestType;
begin
if (Dest is TCaptionListView) then
DestType := CopyCaptionList
else if(Dest is TStrings) then
DestType := CopyStrings
else
if(Dest is TList) then
DestType := CopyList
else
exit;
for i := 0 to Src.Count - 1 do
begin
if(not TPCEItem(Src[i]).FDelete) then
begin
AItem := ItemClass.Create;
AItem.Assign(TPCEItem(Src[i]));
case DestType of
CopyCaptionList: TCaptionListView(Dest).AddObject(AItem.ItemStr, AItem);
CopyStrings: TStrings(Dest).AddObject(AItem.ItemStr, AItem);
CopyList: TList(Dest).Add(AItem);
end;
end;
end;
end;
function TPCEData.Empty: boolean;
begin
Result := (FProviders.Count = 0);
if(Result) then Result := (FSCRelated = SCC_NA);
if(Result) then Result := (FAORelated = SCC_NA);
if(Result) then Result := (FIRRelated = SCC_NA);
if(Result) then Result := (FECRelated = SCC_NA);
if(Result) then Result := (FMSTRelated = SCC_NA);
// if(Result) and HNCOK then Result := (FHNCRelated = SCC_NA);
if(Result) then Result := (FHNCRelated = SCC_NA);
if(Result) then Result := (FCVRelated = SCC_NA);
if(Result) then Result := (FSHADRelated = SCC_NA);
if(Result) then Result := (FCLRelated = SCC_NA); //Camp Lejeune
if(Result) then Result := (FDiagnoses.Count = 0);
if(Result) then Result := (FProcedures.Count = 0);
if(Result) then Result := (FImmunizations.Count = 0);
if(Result) then Result := (FSkinTests.Count = 0);
if(Result) then Result := (FPatientEds.Count = 0);
if(Result) then Result := (FHealthFactors.Count = 0);
if(Result) then Result := (fExams.Count = 0);
if(Result) then Result := (FVisitType.Empty);
end;
{ TPCEProviderList }
function TPCEProviderList.Add(const S: string): Integer;
var
SIEN: string;
LastPrimary: integer;
begin
SIEN := IntToStr(StrToInt64Def(Piece(S, U, pnumPrvdrIEN), 0));
if(SIEN = '0') then
Result := -1
else
begin
LastPrimary := PrimaryIdx;
Result := IndexOfProvider(SIEN);
if(Result < 0) then
Result := inherited Add(S)
else
Strings[Result] := S;
if(Piece(S, U, pnumPrvdrPrimary) = '1') then
begin
FNoUpdate := TRUE;
try
SetPrimaryIdx(Result);
finally
FNoUpdate := FALSE;
end;
if(assigned(FOnPrimaryChanged) and (LastPrimary <> PrimaryIdx)) then
FOnPrimaryChanged(Self);
end;
end;
end;
function TPCEProviderList.AddProvider(AIEN, AName: string; APrimary: boolean): integer;
var
tmp: string;
begin
tmp := 'PRV' + U + AIEN + U + U + U + AName + U;
if(APrimary) then tmp := tmp + '1';
Result := Add(tmp);
end;
procedure TPCEProviderList.Clear;
var
DoNotify: boolean;
begin
DoNotify := (assigned(FOnPrimaryChanged) and (GetPrimaryIdx >= 0));
FPendingDefault := '';
FPendingUser := '';
FPCEProviderIEN := 0;
FPCEProviderName := '';
inherited;
if(DoNotify) then
FOnPrimaryChanged(Self);
end;
procedure TPCEProviderList.Delete(Index: Integer);
var
DoNotify: boolean;
begin
DoNotify := (assigned(FOnPrimaryChanged) and (Piece(Strings[Index], U, pnumPrvdrPrimary) = '1'));
inherited Delete(Index);
if(DoNotify) then
FOnPrimaryChanged(Self);
end;
function TPCEProviderList.PCEProvider: Int64;
function Check(AIEN: Int64): Int64;
begin
if(AIEN = 0) or (IndexOfProvider(IntToStr(AIEN)) < 0) then
Result := 0
else
Result := AIEN;
end;
begin
Result := Check(Encounter.Provider);
if(Result = 0) then Result := Check(User.DUZ);
if(Result = 0) then Result := PrimaryIEN;
end;
function TPCEProviderList.PCEProviderName: string;
var
NewProv: Int64;
begin
NewProv := PCEProvider;
if(FPCEProviderIEN <> NewProv) then
begin
FPCEProviderIEN := NewProv;
FPCEProviderName := ExternalName(PCEProvider, FN_NEW_PERSON);
end;
Result := FPCEProviderName;
end;
function TPCEProviderList.GetPrimaryIdx: integer;
begin
Result := IndexOfPiece('1', U, pnumPrvdrPrimary);
end;
function TPCEProviderList.GetProviderData(Index: integer): TPCEProviderRec;
var
X: string;
begin
X := Strings[Index];
Result.IEN := StrToInt64Def(Piece(X, U, pnumPrvdrIEN), 0);
Result.Name := Piece(X, U, pnumPrvdrName);
Result.Primary := (Piece(X, U, pnumPrvdrPrimary) = '1');
Result.Delete := (Piece(X, U, 1) = 'PRV-');
end;
function TPCEProviderList.IndexOfProvider(AIEN: string): integer;
begin
Result := IndexOfPiece(AIEN, U, pnumPrvdrIEN);
end;
procedure TPCEProviderList.Merge(AList: TPCEProviderList);
var
i, idx: integer;
tmp: string;
begin
for i := 0 to Count-1 do
begin
tmp := Strings[i];
idx := AList.IndexOfProvider(Piece(tmp, U, pnumPrvdrIEN));
if(idx < 0) then
begin
SetPiece(tmp, U, 1, 'PRV-');
Strings[i] := tmp;
end;
end;
for i := 0 to AList.Count-1 do
Add(AList.Strings[i]); // Add already filters out duplicates
end;
function TPCEProviderList.PendingIEN(ADefault: boolean): Int64;
begin
if(ADefault) then
Result := StrToInt64Def(Piece(FPendingDefault, U, 1), 0)
else
Result := StrToInt64Def(Piece(FPendingUser, U, 1), 0);
end;
function TPCEProviderList.PendingName(ADefault: boolean): string;
begin
if(ADefault) then
Result := Piece(FPendingDefault, U, 2)
else
Result := Piece(FPendingUser, U, 2);
end;
function TPCEProviderList.PrimaryIEN: int64;
var
idx: integer;
begin
idx := GetPrimaryIdx;
if(idx < 0) then
Result := 0
else
Result := StrToInt64Def(Piece(Strings[idx], U, pnumPrvdrIEN), 0);
end;
function TPCEProviderList.PrimaryName: string;
var
idx: integer;
begin
idx := GetPrimaryIdx;
if(idx < 0) then
Result := ''
else
Result := Piece(Strings[idx], U, pnumPrvdrName);
end;
procedure TPCEProviderList.SetPrimary(index: integer; Primary: boolean);
var
tmp, x: string;
begin
tmp := Strings[index];
if(Primary) then
x := '1'
else
x := '';
SetPiece(tmp, U, pnumPrvdrPrimary, x);
Strings[Index] := tmp;
end;
procedure TPCEProviderList.SetPrimaryIdx(const Value: integer);
var
LastPrimary, idx: integer;
Found: boolean;
begin
LastPrimary := GetPrimaryIdx;
idx := -1;
Found := FALSE;
repeat
idx := IndexOfPiece('1', U, pnumPrvdrPrimary, idx);
if(idx >= 0) then
begin
if(idx = Value) then
Found := TRUE
else
SetPrimary(idx, FALSE);
end;
until(idx < 0);
if(not Found) and (Value >= 0) and (Value < Count) then
SetPrimary(Value, TRUE);
if((not FNoUpdate) and assigned(FOnPrimaryChanged) and (LastPrimary <> Value)) then
FOnPrimaryChanged(Self);
end;
procedure TPCEProviderList.SetProviderData(Index: integer;
const Value: TPCEProviderRec);
var
tmp, SIEN: string;
begin
if(Value.IEN = 0) or (index < 0) or (index >= Count) then exit;
SIEN := IntToStr(Value.IEN);
if(IndexOfPiece(SIEN, U, pnumPrvdrIEN) = index) then
begin
tmp := 'PRV';
if(Value.Delete) then tmp := tmp + '-';
tmp := tmp + U + SIEN + U + U + U + Value.Name + U;
Strings[index] := tmp;
if Value.Primary then
SetPrimaryIdx(Index);
end;
end;
procedure TPCEProviderList.Assign(Source: TPersistent);
var
Src: TPCEProviderList;
begin
inherited Assign(Source);
if(Source is TPCEProviderList) then
begin
Src := TPCEProviderList(Source);
Src.FOnPrimaryChanged := FOnPrimaryChanged;
Src.FPendingDefault := FPendingDefault;
Src.FPendingUser := FPendingUser;
Src.FPCEProviderIEN := FPCEProviderIEN;
Src.FPCEProviderName := FPCEProviderName;
end;
end;
{ TGenFindings }
initialization
finalization
KillObj(@PCESetsOfCodes);
KillObj(@HistLocations);
end.
|
{*********************************************************************
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Autor: Brovin Y.D.
* E-mail: y.brovin@gmail.com
*
********************************************************************}
unit FGX.ActionSheet.iOS;
interface
uses
System.Classes, System.Generics.Collections, System.TypInfo, Macapi.ObjectiveC, iOSapi.CocoaTypes, iOSapi.UIKit,
iOSapi.Foundation, FMX.Helpers.iOS, FGX.ActionSheet, FGX.ActionSheet.Types;
type
{ TiOSActionSheetService }
TiOSActionSheetDelegate = class;
TiOSActionSheetService = class(TInterfacedObject, IFGXActionSheetService)
private
[Weak] FActions: TfgActionsCollections;
FActionsLinks: TDictionary<NSInteger, TfgActionCollectionItem>;
FActionSheet: UIActionSheet;
FDelegate: TiOSActionSheetDelegate;
protected
procedure DoButtonClicked(const AButtonIndex: Integer); virtual;
function CreateActionButton(const Action: TfgActionCollectionItem): NSInteger; virtual;
procedure CreateSheetActions(const AUseUIGuidline: Boolean); virtual;
public
constructor Create;
destructor Destroy; override;
{ IFGXActionSheetService }
procedure Show(const Title: string; Actions: TfgActionsCollections; const UseUIGuidline: Boolean = True);
end;
TNotifyButtonClicked = procedure (const AButtonIndex: Integer) of object;
IFGXDelayedQueueMessages = interface(NSObject)
['{E75C798C-C506-4ED5-B643-11C3E25417EA}']
procedure Invoke; cdecl;
end;
TfgDelayedQueueMessages = class(TOCLocal)
protected
FButtonIndex: Integer;
FOnInovoke: TNotifyButtonClicked;
function GetObjectiveCClass: PTypeInfo; override;
public
procedure Invoke; cdecl;
public
property ButtonIndex: Integer read FButtonIndex write FButtonIndex;
property OnInovoke: TNotifyButtonClicked read FOnInovoke write FOnInovoke;
end;
TiOSActionSheetDelegate = class(TOCLocal, UIActionSheetDelegate)
private
FQueue: TfgDelayedQueueMessages;
FOnButtonClicked: TNotifyButtonClicked;
public
constructor Create(const AOnButtonClicked: TNotifyButtonClicked);
destructor Destroy; override;
{ UIActionSheetDelegate }
procedure actionSheet(actionSheet: UIActionSheet; clickedButtonAtIndex: NSInteger); cdecl;
procedure actionSheetCancel(actionSheet: UIActionSheet); cdecl;
procedure didPresentActionSheet(actionSheet: UIActionSheet); cdecl;
procedure willPresentActionSheet(actionSheet: UIActionSheet); cdecl;
end;
procedure RegisterService;
implementation
uses
System.SysUtils, System.Devices, Macapi.Helpers, FMX.Platform, FGX.Helpers.iOS, FGX.Asserts,
Macapi.ObjCRuntime;
procedure RegisterService;
begin
TPlatformServices.Current.AddPlatformService(IFGXActionSheetService, TiOSActionSheetService.Create);
end;
{ TiOSActionSheetService }
constructor TiOSActionSheetService.Create;
begin
FDelegate := TiOSActionSheetDelegate.Create(DoButtonClicked);
FActionsLinks := TDictionary<NSInteger, TfgActionCollectionItem>.Create;
end;
function TiOSActionSheetService.CreateActionButton(const Action: TfgActionCollectionItem): NSInteger;
begin
AssertIsNotNil(Action);
AssertIsNotNil(FActionsLinks);
Result := FActionSheet.addButtonWithTitle(StrToNSStr(Action.Caption));
FActionsLinks.Add(Result, Action);
end;
procedure TiOSActionSheetService.CreateSheetActions(const AUseUIGuidline: Boolean);
function GetDeviceClass: TDeviceInfo.TDeviceClass;
var
DeviceService: IFMXDeviceService;
begin
if TPlatformServices.Current.SupportsPlatformService(IFMXDeviceService, DeviceService) then
Result := DeviceService.GetDeviceClass
else
Result := TDeviceInfo.TDeviceClass.Unknown;
end;
var
Action: TfgActionCollectionItem;
I: Integer;
Index: Integer;
begin
AssertIsNotNil(FActions);
AssertIsNotNil(FActionsLinks);
AssertIsNotNil(FActionSheet);
FActionsLinks.Clear;
if AUseUIGuidline then
begin
{ Get destructive action caption }
Index := FActions.IndexOfDestructiveButton;
if Index <> -1 then
begin
CreateActionButton(FActions[Index]);
FActionSheet.setDestructiveButtonIndex(0);
end;
end;
for I := 0 to FActions.Count - 1 do
begin
Action := FActions[I];
if not Action.Visible then
Continue;
if (AUseUIGuidline and (Action.Style = TfgActionStyle.Normal)) or not AUseUIGuidline then
CreateActionButton(Action);
end;
if AUseUIGuidline then
{ Apple doesn't recommend to use Cancel button on iPad
See: https://developer.apple.com/library/ios/documentation/uikit/reference/UIActionSheet_Class/Reference/Reference.html#//apple_ref/occ/instp/UIActionSheet/cancelButtonIndex }
if GetDeviceClass <> TDeviceInfo.TDeviceClass.Tablet then
begin
Index := FActions.IndexOfCancelButton;
if Index <> -1 then
begin
CreateActionButton(FActions[Index]);
FActionSheet.setCancelButtonIndex(FActionsLinks.Count - 1);
end;
end;
end;
destructor TiOSActionSheetService.Destroy;
begin
FActions := nil;
FreeAndNil(FActionsLinks);
if FActionSheet <> nil then
begin
FActionSheet.release;
FActionSheet := nil;
end;
FreeAndNil(FDelegate);
inherited Destroy;
end;
procedure TiOSActionSheetService.DoButtonClicked(const AButtonIndex: Integer);
function TryFindCancelAction: TfgActionCollectionItem;
var
IndexOfCancelButton: Integer;
begin
IndexOfCancelButton := FActions.IndexOfCancelButton;
if IndexOfCancelButton = -1 then
Result := nil
else
Result := FActions[IndexOfCancelButton];
end;
var
Action: TfgActionCollectionItem;
begin
AssertIsNotNil(FActions);
AssertIsNotNil(FActionsLinks);
AssertInRange(AButtonIndex, -1, FActionsLinks.Count - 1);
// iPad doesn't show Cancel button, so ipad AButtonIndex can be -1. It means, that user cancels actions.
if AButtonIndex = -1 then
Action := TryFindCancelAction
else
Action := FActionsLinks.Items[AButtonIndex];
if Action <> nil then
begin
if Assigned(Action.OnClick) then
Action.OnClick(Action)
else if Action.Action <> nil then
Action.Action.ExecuteTarget(nil);
end;
end;
procedure TiOSActionSheetService.Show(const Title: string; Actions: TfgActionsCollections; const UseUIGuidline: Boolean);
begin
AssertIsNotNil(Actions);
AssertIsNotNil(SharedApplication);
AssertIsNotNil(SharedApplication.keyWindow);
AssertIsNotNil(SharedApplication.keyWindow.rootViewController);
FActions := Actions;
{ Removing old UIActionSheet and get new instance }
if FActionSheet <> nil then
FActionSheet.release;
FActionSheet := TUIActionSheet.Alloc;
if Title.IsEmpty then
begin
FActionSheet.init;
FActionSheet.setDelegate((FDelegate as ILocalObject).GetObjectID);
end
else
FActionSheet.initWithTitle(StrToNSStr(Title), (FDelegate as ILocalObject).GetObjectID, nil, nil, nil);
CreateSheetActions(UseUIGuidline);
{ Displaying }
FActionSheet.showInView(SharedApplication.keyWindow.rootViewController.view);
end;
{ TiOSActionSheetDelegate }
procedure TiOSActionSheetDelegate.actionSheet(actionSheet: UIActionSheet; clickedButtonAtIndex: NSInteger);
begin
FQueue.ButtonIndex := clickedButtonAtIndex;
FQueue.OnInovoke := FOnButtonClicked;
NSObject(FQueue.Super).performSelector(sel_getUid('Invoke'), FQueue.GetObjectID, 1);
end;
procedure TiOSActionSheetDelegate.actionSheetCancel(actionSheet: UIActionSheet);
begin
end;
constructor TiOSActionSheetDelegate.Create(const AOnButtonClicked: TNotifyButtonClicked);
begin
inherited Create;
FQueue := TfgDelayedQueueMessages.Create;
FOnButtonClicked := AOnButtonClicked;
end;
destructor TiOSActionSheetDelegate.Destroy;
begin
FreeAndNil(FQueue);
inherited;
end;
procedure TiOSActionSheetDelegate.didPresentActionSheet(actionSheet: UIActionSheet);
begin
end;
procedure TiOSActionSheetDelegate.willPresentActionSheet(actionSheet: UIActionSheet);
begin
end;
{ TiOSQueue }
function TfgDelayedQueueMessages.GetObjectiveCClass: PTypeInfo;
begin
Result := TypeInfo(IFGXDelayedQueueMessages);
end;
procedure TfgDelayedQueueMessages.Invoke;
begin
if Assigned(OnInovoke) then
OnInovoke(FButtonIndex);
end;
end.
|
{
> I'm interested in how to change the default mouse cursor to
> another user defined shape. if you know how to do that, can you
> please post the source For it? Thanks in advance.
}
Uses
Dos, Graph,SeAnHelp;
Var
Regs : Registers;
Type
CursorType = Array[0..31] of Word; { to store the cursor shape }
{ define a cursor shape }
Const HourGlass : CursorType =
{ this specific Constant, when used in the Procedure to change the cursor
shape will change it to an hourglass shaped cursor. of course you can
define your own cursor shape to suit your needs.
the comments beside the hex numbers are what it will look like (binary),
they help TREMendOUSLY in designing a cursor shape. }
{ Screen mask : the 0's will show up as the background colour, the 1's
will show whatever is on the screen at that location }
($0001, { 0000000000000001 }
$0001, { 0000000000000001 }
$8003, { 1000000000000011 }
$C7C7, { 1100011111000111 }
$E38F, { 1110001110001111 }
$F11F, { 1111000100011111 }
$F83F, { 1111100000111111 }
$FC7F, { 1111110001111111 }
$F83F, { 1111100000111111 }
$F11F, { 1111000100011111 }
$E38F, { 1110001110001111 }
$C7C7, { 1100011111000111 }
$8003, { 1000000000000011 }
$0001, { 0000000000000001 }
$0001, { 0000000000000001 }
$0000, { 0000000000000000 }
{ Cursor mask : the 1's will show up as white (or whatever color you have
reassigned it to if you have done a SetPalette or SetRGBPalette) }
$0000, { 0000000000000000 }
$7FFC, { 0111111111111100 }
$2008, { 0010000000001000 }
$1010, { 0001000000010000 }
$0820, { 0000100000100000 }
$0440, { 0000010001000000 }
$0280, { 0000001010000000 }
$0100, { 0000000100000000 }
$0280, { 0000001010000000 }
$0440, { 0000010001000000 }
$0820, { 0000100000100000 }
$1010, { 0001000000010000 }
$2008, { 0010000000001000 }
$7FFC, { 0111111111111100 }
$0000, { 0000000000000000 }
$0000); { 0000000000000000 }
Procedure SetMouseCursor(HotX, HotY: Integer; Var Pattern : CursorType);
begin
Regs.AX := 9; { Function 9 }
Regs.BX := HotX; { X-ordinate of hot spot }
Regs.CX := HotY; { Y-ordinate of hot spot }
{ the hot spots are the co-ordinates that will show up as being where
the mouse is when reading the co-ordinates of the mouse }
Regs.DX := ofs(Pattern);
Regs.ES := Seg(Pattern);
Intr($33, Regs);
end;
begin
GraphMode(Driver,Mode);
{ [...initialize the Graphics screen etc...] }
SetMouseCursor(7, 7, HourGlass);
{ this will set the mouse cursor to an hourglass shape With the hot spot
right in the centre at position 7,7 from the top left of the shape }
{ [...continue Program...] }
end.
|
(* Calculator: MM, 2020-04-22 *)
(* ------ *)
(* Scanner and parser for computing simple arithmatic expressions *)
(* ========================================================================= *)
PROGRAM Calculator;
CONST
EOF_CH = Chr(0);
TYPE
SymbolCode = (noSy, (* error symbol *)
eofSy,
plusSy, minusSy, timesSy, divSy,
leftParSy, rightParSy,
number);
VAR
line: STRING;
ch: CHAR;
cnr: INTEGER;
sy: SymbolCode;
numberVal: INTEGER;
success: BOOLEAN;
PROCEDURE S FORWARD;
PROCEDURE Expr(VAR e: INTEGER) FORWARD;
PROCEDURE Term(VAR t: INTEGER) FORWARD;
PROCEDURE Fact(VAR f: INTEGER) FORWARD;
PROCEDURE NewCh;
BEGIN (* NewCh *)
IF (cnr < Length(line)) THEN BEGIN
Inc(cnr);
ch := line[cnr];
END ELSE BEGIN
ch := EOF_CH;
END; (* IF *)
END; (* NewCh *)
PROCEDURE NewSy;
BEGIN (* NewSy *)
WHILE (ch = ' ') DO BEGIN
NewCh;
END; (* WHILE *)
CASE ch OF
EOF_CH: BEGIN sy := eofSy; END;
'+': BEGIN sy := plusSy; NewCh; END;
'-': BEGIN sy := minusSy; NewCh; END;
'*': BEGIN sy := timesSy; NewCh; END;
'/': BEGIN sy := divSy; NewCh; END;
'(': BEGIN sy := leftParSy; NewCh; END;
')': BEGIN sy := rightParSy; NewCh; END;
'0'..'9': BEGIN
sy := number;
numberVal := 0;
WHILE ((ch >= '0') AND (ch <= '9')) DO BEGIN
numberVal := numberVal * 10 + Ord(ch) - Ord('0');
NewCh;
END; (* WHILE *)
END;
ELSE BEGIN sy := noSy; END;
END; (* Case *)
END; (* NewSy *)
(* Expr = Term { "+" | "-" Term] . *)
PROCEDURE Expr(VAR e: INTEGER);
VAR t: INTEGER;
BEGIN (* Expr *)
Term(e); IF (NOT success) THEN Exit;
WHILE ((sy = plusSy) OR (sy = minusSy)) DO BEGIN
CASE sy OF
plusSy: BEGIN
NewSy;
Term(t); IF (NOT success) THEN Exit;
(*SEM*) e := e + t;
END;
minusSy: BEGIN
NewSy;
Term(t); IF (NOT success) THEN Exit;
(*SEM*) e := e - t;
END;
END; (* CASE *)
END; (* WHILE *)
END; (* Expr *)
(* Term = Fact { "*" Fact | */* Fact} . *)
PROCEDURE Term(VAR t: INTEGER);
VAR f: INTEGER;
BEGIN (* Term *)
Fact(t); IF (NOT success) THEN Exit;
WHILE ((sy = timesSy) OR (sy = divSy)) DO BEGIN
CASE sy OF
timesSy: BEGIN
NewSy;
Fact(f); IF (NOT success) THEN Exit;
(*SEM*) t := t * f; (*ENDSEM*)
END;
divSy: BEGIN
NewSy;
Fact(f); IF (NOT success) THEN Exit;
(*SEM*) t := t DIV f; (*ENDSEM*)
END;
END; (* CASE *)
END; (* WHILE *)
END; (* Term *)
(* Fact = number | "(" Expr ")" . *)
PROCEDURE Fact(VAR f: INTEGER);
BEGIN (* Fact *)
CASE sy OF
number: BEGIN
(*SEM*) f := numberVal; (*ENDSEM*)
NewSy;
END;
leftParSy: BEGIN
NewSy;
Expr(f); IF (NOT success) THEN Exit;
IF (sy <> rightParSy) THEN BEGIN
success := FALSE;
Exit;
END; (* IF *)
NewSy;
END;
ELSE BEGIN
success := FALSE;
Exit;
END; (* ELSE *)
END; (* CASE *)
END; (* Fact *)
PROCEDURE S;
VAR e: INTEGER;
BEGIN (* S *)
Expr(e); IF (NOT success) THEN Exit;
IF (sy <> eofSy) THEN BEGIN
success := FALSE;
Exit;
END; (* IF *)
(*SEM*) WriteLn('Result: ', e);
END; (* S *)
BEGIN (* Calculator *)
REPEAT
Write('expr > ');
ReadLn(line);
cnr := 0;
NewCh;
NewSy;
success := TRUE;
S;
IF (success) THEN BEGIN
WriteLn('syntax valid');
END ELSE BEGIN
WriteLn('syntax error in column ', cnr);
END; (* IF *)
WriteLn;
UNTIL (Length(line) = 0); (* REPEAT *)
END. (* Calculator *) |
unit fLabCollTimes;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ORCtrls, ORDtTm, ORFn, ExtCtrls, ComCtrls, fBase508Form,
VA508AccessibilityManager;
type
TfrmLabCollectTimes = class(TfrmBase508Form)
calLabCollect: TORDateBox;
lstLabCollTimes: TORListBox;
cmdOK: TButton;
cmdCancel: TButton;
lblFutureTimes: TMemo;
calMonth: TMonthCalendar;
procedure calLabCollectChange(Sender: TObject);
procedure cmdOKClick(Sender: TObject);
procedure cmdCancelClick(Sender: TObject);
procedure calMonthClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure calMonthKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
FFutureLabCollTime: string;
public
{ Public declarations }
end;
function GetFutureLabTime(ACollDate: TFMDateTime): string;
implementation
uses
rCore, uCore, ORNet, rODLab, VAUtils;
{$R *.DFM}
function GetFutureLabTime(ACollDate: TFMDateTime): string;
var
frmLabCollectTimes: TfrmLabCollectTimes;
begin
frmLabCollectTimes := TfrmLabCollectTimes.Create(Application);
try
with frmLabCollectTimes do
begin
calLabCollect.FMDateTime := Trunc(ACollDate);
calMonth.Date := FMDateTimeToDateTime(calLabCollect.FMDateTime);
FFutureLabCollTime := '';
ShowModal;
Result := FFutureLabCollTime;
end; {with frmLabCollectTimes}
finally
frmLabCollectTimes.Release;
end;
end;
procedure TfrmLabCollectTimes.calLabCollectChange(Sender: TObject);
begin
with lstLabColltimes do
begin
Clear;
GetLabTimesForDate(Items, calLabCollect.FMDateTime, Encounter.Location);
ItemIndex := 0;
end;
end;
procedure TfrmLabCollectTimes.cmdOKClick(Sender: TObject);
begin
if lstLabCollTimes.ItemIEN > 0 then
begin
with calLabCollect, lstLabCollTimes do
FFutureLabCollTime := RelativeTime + '@' + ItemID;
Close;
end
else
FFutureLabCollTime := '';
end;
procedure TfrmLabCollectTimes.cmdCancelClick(Sender: TObject);
begin
FFutureLabCollTime := '';
Close;
end;
procedure TfrmLabCollectTimes.calMonthClick(Sender: TObject);
begin
calLabCollect.FMDateTime := DateTimeToFMDateTime(calMonth.Date);
calMonth.SetFocus;
end;
procedure TfrmLabCollectTimes.FormCreate(Sender: TObject);
begin
ResizeAnchoredFormToFont(self);
end;
procedure TfrmLabCollectTimes.calMonthKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
case Key of
VK_LEFT: calMonth.Date := calMonth.Date - 1;
VK_RIGHT: calMonth.Date := calMonth.Date + 1;
VK_UP: calMonth.Date := calMonth.Date - 7;
VK_DOWN: calMonth.Date := calMonth.Date + 7;
end;
end;
end.
|
unit GMDock;
interface
uses Windows, Classes, Forms, Controls, GMGlobals, cxScrollBox, dxDockControl, dxDockPanel, ControlFrame,
Graphics, Messages, GMConst, IniFiles;
type
TCheckPanelFunctionRef = reference to function (p: TdxDockPanel): bool;
TGMDockPanel = class(TdxDockPanel)
private
FGMForm: TGMForm;
FScrollbox: TcxScrollBox;
procedure ScrollboxResize(Sender: TObject);
procedure WMAfterConstruction(var Msg: TMessage); message WM_AFTER_CONSTRUCTION;
procedure DockPanelClose(Sender: TdxCustomDockControl);
procedure DockPanelCloseQuery(Sender: TdxCustomDockControl; var CanClose: Boolean);
protected
procedure InsertForm(gmFormClass: TGMFormClass);
procedure CreateWnd; override;
procedure LoadLayoutFromCustomIni(AIniFile: TCustomIniFile; AParentForm: TCustomForm;
AParentControl: TdxCustomDockControl; ASection: string); override;
procedure SaveLayoutToCustomIni(AIniFile: TCustomIniFile; ASection: string); override;
function NeedDestroyOnClose: bool; virtual;
public
property GMForm: TGMForm read FGMForm;
class function FindAnyPanelAsDockDestination(checkPanelFunc: TCheckPanelFunctionRef): TGMDockPanel;
class procedure CloseAll();
end;
implementation
{ TGMDockPanel }
uses dxStandardControlsSkinHelper, EsLogging;
class procedure TGMDockPanel.CloseAll();
var
i, n: int;
b: bool;
begin
// всякие отщепенцы
while true do
begin
n := dxDockingController().DockControlCount;
b := false;
for i := n - 1 downto 0 do
begin
if dxDockingController().DockControls[i] is TGMDockPanel then
begin
dxDockingController().DockControls[i].OnCloseQuery := nil;
dxDockingController().DockControls[i].Free();
b := true;
end;
end;
if not b then break;
end;
end;
procedure TGMDockPanel.InsertForm(gmFormClass: TGMFormClass);
begin
FScrollbox := TcxScrollBox.Create(self);
FScrollbox.Parent := self;
FScrollbox.Align := alClient;
FScrollbox.OnResize := ScrollboxResize;
FScrollbox.HorzScrollBar.Tracking := true;
FScrollbox.VertScrollBar.Tracking := true;
FGMForm := gmFormClass.Create(self);
FGMForm.Left := 0;
FGMForm.Top := 0;
Width := FGMForm.Width;
Height := FGMForm.Height;
end;
class function TGMDockPanel.FindAnyPanelAsDockDestination(checkPanelFunc: TCheckPanelFunctionRef): TGMDockPanel;
var
p: TdxCustomDockControl;
i: int;
begin
for i := 0 to dxDockingController().DockControlCount - 1 do
begin
p := dxDockingController().DockControls[i];
if (p is TdxDockPanel)
and (not Assigned(checkPanelFunc) or checkPanelFunc(TdxDockPanel(p)))
and (p.Visible)
and (p.DockState = dsDocked)//это условие необходимо, потому что при закрытии FloatDockSite, на котором Notebook (более одного окна задочено), будет исключение
then
begin
Result := TGMDockPanel(p);
Exit;
end;
end;
Result := nil;
end;
procedure TGMDockPanel.LoadLayoutFromCustomIni(AIniFile: TCustomIniFile; AParentForm: TCustomForm;
AParentControl: TdxCustomDockControl; ASection: string);
begin
inherited;
end;
procedure TGMDockPanel.CreateWnd;
begin
inherited;
FGMForm.Parent := FScrollBox;
PostMessage(Handle, WM_AFTER_CONSTRUCTION, 0, 0);
end;
function TGMDockPanel.NeedDestroyOnClose(): bool;
begin
Result := false;
end;
procedure TGMDockPanel.DockPanelClose(Sender: TdxCustomDockControl);
begin
if NeedDestroyOnClose() then
GMPostMessage(WM_DESTROY_OBJECT, WParam(self), 0, DefaultLogger);
end;
procedure TGMDockPanel.DockPanelCloseQuery(Sender: TdxCustomDockControl; var CanClose: Boolean);
begin
CanClose := Dockable;
end;
procedure TGMDockPanel.WMAfterConstruction(var Msg: TMessage);
begin
FGMForm.Visible := true;
FGMForm.BorderStyle := bsNone;
FGMForm.Font.Quality := fqClearType;
FGMForm.Color := GetSkinFormContentColor();
Caption := FGMForm.Caption;
Constraints.MinWidth := 200;
Constraints.MinHeight := 200;
OnClose := DockPanelClose;
OnCloseQuery := DockPanelCloseQuery;
ScrollBoxResize(FScrollBox);
end;
procedure TGMDockPanel.SaveLayoutToCustomIni(AIniFile: TCustomIniFile; ASection: string);
begin
inherited;
end;
procedure TGMDockPanel.ScrollboxResize(Sender: TObject);
var scrollbox: TcxScrollBox;
minWidth, minHeight, vertScrollbarWidth, horzScrollbarHeight: int;
begin
scrollbox := TcxScrollBox(Sender);
FGMForm.Align := alNone;
vertScrollbarWidth := GetSystemMetrics(SM_CXVSCROLL);
horzScrollbarHeight := GetSystemMetrics(SM_CYHSCROLL);
minWidth := FGMForm.GetMinWidth() + vertScrollbarWidth;
if scrollbox.ClientBounds.Width < minWidth then
begin
FGMForm.Width := minWidth;
scrollbox.HorzScrollBar.Range := FGMForm.Width;
end
else
begin
FGMForm.Width := scrollbox.ClientBounds.Width;
if FGMForm.Width > scrollbox.ClientBounds.Width then
scrollbox.HorzScrollBar.Range := FGMForm.Width
else
scrollbox.HorzScrollBar.Range := 0;
end;
minHeight := FGMForm.GetMinHeight() + horzScrollbarHeight;
if scrollbox.ClientBounds.Height < minHeight then
begin
FGMForm.Height := minHeight;
scrollbox.VertScrollBar.Range := minHeight;
end
else
begin
FGMForm.Height := scrollbox.ClientBounds.Height;
scrollbox.VertScrollBar.Range := 0;
end;
end;
end.
|
unit uAndroidApplication;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Rtti,
System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Controls.Presentation, FMX.Edit, FMX.Layouts, FMX.ListBox, FMX.TabControl,
FMX.Objects, System.Actions, FMX.ActnList, FMX.MediaLibrary.Actions,
FMX.StdActns, System.IOUtils, Inifiles, System.threading,
uTravel,
uEvent, Users, uUsersOfTravelProgress, uUsersOfTravel, Action,
FMX.ScrollBox, FMX.Memo;
type
TClientForm = class(TForm)
AndoidTabControl: TTabControl;
AutorizationTab: TTabItem;
RegistrationTab: TTabItem;
edLogin: TEdit;
edPassword: TEdit;
btLogIn: TCornerButton;
btRegistr: TCornerButton;
UserStatusTab: TTabItem;
lbHelloUser: TLabel;
TravelStatus: TProgressBar;
edLog: TEdit;
edPas: TEdit;
edReturnPas: TEdit;
btRegistration: TCornerButton;
StyleBook1: TStyleBook;
GoInTravel: TCornerButton;
TravelList: TTabItem;
TravelListBox: TListBox;
lbHelp: TLabel;
EventTab: TTabItem;
EventList: TListBox;
lbEventHelp: TLabel;
ActionTab: TTabItem;
lbActionHelp: TLabel;
cbEvents: TComboBox;
mmOpinion: TMemo;
btEndEvent: TCornerButton;
Layout1: TLayout;
Layout2: TLayout;
Layout4: TLayout;
Layout5: TLayout;
Layout6: TLayout;
Layout7: TLayout;
Layout8: TLayout;
Layout3: TLayout;
procedure edLoginClick(Sender: TObject);
procedure edPasswordClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btRegistrClick(Sender: TObject);
procedure btLogInClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btRegistrationClick(Sender: TObject);
procedure GoInTravelClick(Sender: TObject);
procedure TravelListBoxItemClick(const Sender: TCustomListBox;
const Item: TListBoxItem);
procedure EventListItemClick(const Sender: TCustomListBox;
const Item: TListBoxItem);
procedure btEndEventClick(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char;
Shift: TShiftState);
procedure mmOpinionClick(Sender: TObject);
private
{ Private declarations }
public
User: TUsers;
ListOfTravel: TTravelList;
ListOfAction: TActionList;
ListOfEvent: TEventList;
IdTravel: string;
ListOfUsersOfTravel: TUsersOfTravellist;
ListOfUsersOfTravelProgress: TUsersOfTravelProgressList;
Procedure RefreshTravels;
Procedure RefreshActions;
{ Public declarations }
end;
var
ClientForm: TClientForm;
implementation
{$R *.fmx}
procedure TClientForm.btEndEventClick(Sender: TObject);
var
Item: TUsersOfTravel;
Guid: TGUID;
Status: TUsersOfTravelProgress;
cout: integer;
begin
cout := ListOfUsersOfTravelProgress.SelectByUserIdCount(User.Id);
if cout >= User.ActionCount then
begin
showmessage('Ваше путешествие завершено');
ClientForm.Close;
end
else
begin
if cbEvents.ItemIndex >= 0 then
begin
CreateGUID(Guid);
Item := TUsersOfTravel.Create(nil);
Try
Status := TUsersOfTravelProgress.Create(nil);
try
Item.Id := Guid.ToString;
Item.IdUser := User.Id;
Item.IdTravel := IdTravel;
Item.Opinion := mmOpinion.Text;
Item.State := 'Выполняется';
ListOfUsersOfTravel.UpdateOrInsert(Item);
Status.IdUsersOfTravelProgress := '';
Status.IdUser := User.Id;
Status.ActionId := Item.IdTravel;
Status.EventId := TEvent(ListOfEvent.items[cbEvents.ItemIndex]).Id;
Status.State := 'Выполнено';
ListOfUsersOfTravelProgress.SaveInDB(Status);
finally
freeandnil(Status);
end;
Finally
freeandnil(Item);
End;
end;
showmessage('Мерориятие завершено');
AndoidTabControl.SetActiveTabWithTransition(EventTab, TTabTransition.Slide);
end;
end;
procedure TClientForm.btLogInClick(Sender: TObject);
var
Logic: Boolean;
Casing: integer;
Status: integer;
param: string;
begin
Logic := User.LogInCheck(edLogin.Text, edPassword.Text);
if Logic = true then
begin
AndoidTabControl.SetActiveTabWithTransition(UserStatusTab,
TTabTransition.Slide);
User.SelectUserFromDb(edLogin.Text);
lbHelloUser.Text := User.Login + ', Здравствуйте';
Status := ListOfUsersOfTravelProgress.SelectByUserIdCount(User.Id);
TravelStatus.Value := (100 / User.ActionCount) * Status;
if TravelStatus.Value > 0 then
begin
param := ListOfUsersOfTravelProgress.SelectByUserId(User.Id);
ListOfAction.SelectingByMyId(param);
end
else
begin
lbHelloUser.Text := User.Login +
', Здравствуйте. Ваше путешествие еще не было начато';
end;
if TravelStatus.Value >= 100 then
begin
showmessage('Ваше путешествие было завершено');
ClientForm.Close;
end;
end
else
showmessage('Логин или пароль не совпадают');
end;
procedure TClientForm.btRegistrationClick(Sender: TObject);
var
Logic: Boolean;
Casing: integer;
begin
if edReturnPas.Text <> edPas.Text then
showmessage('Введеные вами пароли не совпадают')
else
begin
Logic := User.CheckUser(edLog.Text);
if Logic = true then
showmessage('Такой Логин уже занят =(')
else
begin
User.Login := edLog.Text;
User.Password := edPas.Text;
User.ActionCount := 0;
User.AddUserInDb;
showmessage('Поздравляем!!! Регистрация успешно завершена');
AndoidTabControl.SetActiveTabWithTransition(AutorizationTab,
TTabTransition.Slide);
edLogin.Text := User.Login;
edPassword.Text := User.Password;
end;
end;
end;
procedure TClientForm.btRegistrClick(Sender: TObject);
begin
AndoidTabControl.SetActiveTabWithTransition(RegistrationTab,
TTabTransition.Slide);
end;
procedure TClientForm.edLoginClick(Sender: TObject);
begin
if edLogin.Text = 'Введите Логин' then
edLogin.Text := '';
end;
procedure TClientForm.edPasswordClick(Sender: TObject);
begin
if edPassword.Text = 'Введите Пароль' then
edPassword.Text := '';
end;
procedure TClientForm.EventListItemClick(const Sender: TCustomListBox;
const Item: TListBoxItem);
var
I: integer;
begin
ListOfEvent.Clear;
User.ActionCount := ListOfAction.Count;
User.UpDatingCount(User.Login);
lbActionHelp.Text := 'Мероприятия события' +
TAction(ListOfAction.items[Item.index]).AcName;
ListOfEvent.SelectByEventId(TAction(ListOfAction.items[Item.index]).Id);
cbEvents.Clear;
cbEvents.BeginUpdate;
try
for I := 0 to ListOfEvent.Count - 1 do
cbEvents.items.Add(TEvent(ListOfEvent.items[I]).EvName);
finally
cbEvents.EndUpdate;
end;
AndoidTabControl.SetActiveTabWithTransition(ActionTab, TTabTransition.Slide);
mmOpinion.Enabled := true;
end;
procedure TClientForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
ListOfTravel.Clear;
ListOfAction.Clear;
ListOfEvent.Clear;
ListOfUsersOfTravelProgress.Clear;
freeandnil(ListOfUsersOfTravelProgress);
freeandnil(ListOfTravel);
freeandnil(ListOfAction);
freeandnil(ListOfEvent);
freeandnil(User);
end;
procedure TClientForm.FormCreate(Sender: TObject);
begin
AndoidTabControl.TabPosition := TTabPosition.None;
AndoidTabControl.ActiveTab := AutorizationTab;
ListOfTravel := TTravelList.Create(Ttravel);
ListOfAction := TActionList.Create(TAction);
ListOfEvent := TEventList.Create(TEvent);
ListOfUsersOfTravelProgress := TUsersOfTravelProgressList.Create
(TUsersOfTravelProgress);
User := TUsers.Create;
ListOfTravel.LoadAllTravels;
end;
procedure TClientForm.FormKeyUp(Sender: TObject; var Key: Word;
var KeyChar: Char; Shift: TShiftState);
begin
if AndoidTabControl.ActiveTab = ActionTab then
if (Key = vkHardwareBack) or (Key = vkBack) then
begin
AndoidTabControl.SetActiveTabWithTransition(EventTab,
TTabTransition.Slide);
Key := 0;
exit;
end;
if AndoidTabControl.ActiveTab = EventTab then
if (Key = vkHardwareBack) or (Key = vkBack) then
begin
AndoidTabControl.SetActiveTabWithTransition(TravelList,
TTabTransition.Slide);
Key := 0;
exit;
end;
if AndoidTabControl.ActiveTab = TravelList then
if (Key = vkHardwareBack) or (Key = vkBack) then
begin
AndoidTabControl.SetActiveTabWithTransition(UserStatusTab,
TTabTransition.Slide);
Key := 0;
exit;
end;
if AndoidTabControl.ActiveTab = UserStatusTab then
if (Key = vkHardwareBack) or (Key = vkBack) then
begin
AndoidTabControl.SetActiveTabWithTransition(AutorizationTab,
TTabTransition.Slide);
Key := 0;
exit;
end;
end;
procedure TClientForm.GoInTravelClick(Sender: TObject);
begin
lbHelp.Text := User.Login + ' , вам доступны следующие путешествия.' +
' Для выбора нажмите на одно из понравишихся в списке.';
if TravelStatus.Value <= 0 then
begin
RefreshTravels;
AndoidTabControl.SetActiveTabWithTransition(TravelList,
TTabTransition.Slide);
end
else
begin
RefreshActions;
AndoidTabControl.SetActiveTabWithTransition(EventTab, TTabTransition.Slide);
end;
end;
procedure TClientForm.mmOpinionClick(Sender: TObject);
begin
mmOpinion.Lines.Clear;
end;
procedure TClientForm.RefreshActions;
var
I: integer;
NewItem: TListBoxItem;
begin
EventList.BeginUpdate;
try
EventList.Clear;
for I := 0 to ListOfAction.Count - 1 do
begin
NewItem := TListBoxItem.Create(nil);
NewItem.Parent := EventList;
NewItem.StyleLookup := 'TravelStyle';
NewItem.Height := NewItem.Height + 40;
NewItem.StylesData['Name.text'] := TAction(ListOfAction.items[I]).AcName;
EventList.AddObject(NewItem);
end;
finally
EventList.EndUpdate;
end;
end;
procedure TClientForm.RefreshTravels;
var
I: integer;
NewItem: TListBoxItem;
begin
TravelListBox.BeginUpdate;
try
TravelListBox.Clear;
for I := 0 to ListOfTravel.Count - 1 do
begin
NewItem := TListBoxItem.Create(nil);
NewItem.Parent := TravelListBox;
NewItem.StyleLookup := 'TravelStyle';
NewItem.Height := NewItem.Height + 40;
NewItem.StylesData['Name.text'] := Ttravel(ListOfTravel.items[I]).name;
TravelListBox.AddObject(NewItem);
end;
finally
TravelListBox.EndUpdate;
end;
end;
procedure TClientForm.TravelListBoxItemClick(const Sender: TCustomListBox;
const Item: TListBoxItem);
begin
ListOfAction.Clear;
IdTravel := Ttravel(ListOfTravel.items[Item.index]).Id;
ListOfAction.SelectingByTravelId(Ttravel(ListOfTravel.items[Item.index]).Id);
RefreshActions;
lbEventHelp.Text := 'В путешествии' + ' ' +
Ttravel(ListOfTravel.items[Item.index]).name + ' ' + 'доступно' + ' ' +
inttostr(ListOfAction.Count) + ' ' + 'этапa(ов)';
AndoidTabControl.SetActiveTabWithTransition(EventTab, TTabTransition.Slide);
end;
end.
|
unit UnitMain;
{
OSS Mail Server v1.0.0 - Main Form
The MIT License (MIT)
Copyright (c) 2012 Guangzhou Cloudstrust Software Development Co., Ltd
http://cloudstrust.com/
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
}
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Layouts,
FMX.Objects, FMX.ListBox, FMX.Ani, FMX.Gestures, Vcl.IdAntiFreeze, ALIOSS,
IdContext, IdSMTPServer, IdPOP3Server, IdBaseComponent, IdComponent,
IdCustomTCPServer, IdTCPServer, IdCmdTCPServer, IdExplicitTLSClientServerBase,
IdIMAP4Server, IdCommandHandlers, FMX.Memo, IdTCPConnection, IdTCPClient,
IdMessageClient, IdSMTPBase, IdSMTPRelay;
type
TIniData = record
//OSS settings
OssHostname: string;
AccessId: string;
AccessKey: string;
//Mail settings
MailHostname: string;
MailSMTPLogin: boolean;
MailBucket: string;
//Accounts
Accounts: TStringList;
end;
TfrmMain = class(TForm)
styleMain: TStyleBook;
loToolbar: TLayout;
ppToolbar: TPopup;
ppToolbarAnimation: TFloatAnimation;
loMain: TLayout;
loHeader: TLayout;
laTitle: TLabel;
sbMain: THorzScrollBox;
loMenu: TLayout;
lbMenu: TListBox;
lbiMenuMail: TMetropolisUIListBoxItem;
laMenuTitle: TLabel;
tbMain: TToolBar;
btnMinimize: TButton;
btnAbout: TButton;
btnClose: TButton;
imgMailOn: TImage;
imgMailOff: TImage;
lbiMenuSettings: TMetropolisUIListBoxItem;
loLogs: TLayout;
laLogsTitle: TLabel;
tmrDeferredInit: TTimer;
tmrDeferredLog: TTimer;
imgSettingsOff: TImage;
imgOssOff: TImage;
lbiMenuAccounts: TMetropolisUIListBoxItem;
imgAccountsOff: TImage;
pop3: TIdPOP3Server;
smtp: TIdSMTPServer;
mmLogs: TMemo;
imgOssOn: TImage;
imgAccountsOn: TImage;
imgAddAccountOn: TImage;
imgAddAccountOff: TImage;
smtpRelay: TIdSMTPRelay;
procedure btnMinimizeClick(Sender: TObject);
procedure FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
procedure FormGesture(Sender: TObject; const EventInfo: TGestureEventInfo;
var Handled: Boolean);
procedure FormActivate(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char;
Shift: TShiftState);
procedure btnCloseClick(Sender: TObject);
procedure btnAboutClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure lbiMenuSettingsClick(Sender: TObject);
procedure lbiMenuMailClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure tmrDeferredInitTimer(Sender: TObject);
procedure tmrDeferredLogTimer(Sender: TObject);
procedure pop3Connect(AContext: TIdContext);
procedure pop3Disconnect(AContext: TIdContext);
procedure pop3Delete(aCmd: TIdCommand; AMsgNo: Integer);
procedure pop3List(aCmd: TIdCommand; AMsgNo: Integer);
procedure pop3Stat(aCmd: TIdCommand; out oCount, oSize: Integer);
procedure pop3CheckUser(aContext: TIdContext;
aServerContext: TIdPOP3ServerContext);
procedure pop3Reset(aCmd: TIdCommand);
procedure pop3Retrieve(aCmd: TIdCommand; AMsgNo: Integer);
procedure pop3Quit(aCmd: TIdCommand);
procedure pop3Top(aCmd: TIdCommand; aMsgNo, aLines: Integer);
procedure pop3UIDL(aCmd: TIdCommand; AMsgNo: Integer);
procedure pop3BeforeCommandHandler(ASender: TIdCmdTCPServer;
var AData: string; AContext: TIdContext);
procedure smtpMsgReceive(ASender: TIdSMTPServerContext; AMsg: TStream;
var VAction: TIdDataReply);
procedure smtpBeforeCommandHandler(ASender: TIdCmdTCPServer;
var AData: string; AContext: TIdContext);
procedure smtpConnect(AContext: TIdContext);
procedure smtpDisconnect(AContext: TIdContext);
procedure smtpMailFrom(ASender: TIdSMTPServerContext;
const AAddress: string; AParams: TStrings; var VAction: TIdMailFromReply);
procedure smtpRcptTo(ASender: TIdSMTPServerContext; const AAddress: string;
AParams: TStrings; var VAction: TIdRCPToReply; var VForward: string);
procedure smtpReceived(ASender: TIdSMTPServerContext;
var AReceived: string);
procedure smtpUserLogin(ASender: TIdSMTPServerContext; const AUsername,
APassword: string; var VAuthenticated: Boolean);
procedure lbiMenuAccountsClick(Sender: TObject);
procedure laLogsTitleClick(Sender: TObject);
private
FGestureOrigin: TPointF;
FGestureInProgress: Boolean;
FAntiFreeze: TIdAntiFreeze;
FCachedLogs: TStringList;
{ Private declarations }
// Common Utilities
procedure ShowToolbar(const AShow: Boolean);
procedure SwitchSubTitle(lb: TMetropolisUIListBoxItem);
function ClickTest: boolean;
procedure LoadIniFile;
procedure ClearLogs;
// Mail Server
function StartMail: boolean;
function StopMail: boolean;
{ Private declarations }
public
{ Public declarations }
IniData: TIniData;
CachedBuckets: TStringList;
procedure SwitchIcon(lb: TMetropolisUIListBoxItem; const imgName: string);
procedure SaveIniFile;
procedure LoadCachedBuckets(pVolumns: PAliOssVolumnInfoList = nil);
procedure AddLog(log: string);
end;
function PopString(var src: string): string;
procedure CopyBitmap(dest, src: FMX.Types.TBitmap);
var
frmMain: TfrmMain;
down: boolean;
force_mail_stop: boolean;
implementation
{$R *.fmx}
uses DateUtils, IniFiles, UnitMessage, ALIOSSUTIL, ALIOSSOPT, Windows, IdMessage, IdEmailAddress;
const
OK = '+OK';
var
lastClickTime: TDateTime;
currentUsername: string;
currentGuid: string;
currentMails: TAliOssFileInfoList;
deleteMarkers: array of boolean;
function PopString(var src: string): string;
var
p: integer;
begin
p := pos('|', src);
if p <> 0 then
begin
result := copy(src, 1, p-1);
delete(src, 1, p);
end
else
begin
result := src;
src := '';
end;
end;
procedure CopyBitmap(dest, src: FMX.Types.TBitmap);
begin
dest.Assign(src);
end;
procedure TfrmMain.laLogsTitleClick(Sender: TObject);
begin
MessageDlg('test', 'hello, world', 'OK', 'Cancel');
end;
procedure TfrmMain.lbiMenuAccountsClick(Sender: TObject);
var
Form: TCommonCustomForm;
begin
Form := Application.GetDeviceForm('Accounts');
if Assigned(Form) then
Form.Show;
end;
procedure TfrmMain.lbiMenuMailClick(Sender: TObject);
var
lb: TMetropolisUIListBoxItem;
begin
if not ClickTest then exit;
lb := self.FindComponent('lbiMenuMail') as TMetropolisUIListBoxItem;
if (lb.TagString = 'imgMailOn') and (self.StopMail) then
begin
lb.StyleLookup := 'collectionlistboxitem';
self.SwitchIcon(lb, 'imgMailOff');
self.SwitchSubTitle(lb);
end
else if (lb.TagString = 'imgMailOff') and (self.StartMail) then
begin
lb.StyleLookup := 'checkedpanel';
self.SwitchIcon(lb, 'imgMailOn');
self.SwitchSubTitle(lb);
end;
//mark current time
ClickTest;
end;
procedure TfrmMain.lbiMenuSettingsClick(Sender: TObject);
var
Form: TCommonCustomForm;
begin
Form := Application.GetDeviceForm('Settings');
if Assigned(Form) then
Form.Show;
end;
procedure TfrmMain.LoadCachedBuckets(pVolumns: PAliOssVolumnInfoList);
var
ossfs: TAliOssFileSystem;
volumns: TAliOssVolumnInfoList;
I: Integer;
success: boolean;
begin
success := false;
if (pVolumns <> nil) then
begin
success := true;
volumns := pVolumns^;
end
else
begin
if (self.IniData.OssHostname <> '')
or (self.IniData.AccessId <> '')
or (self.IniData.AccessKey <> '') then
begin
try
ossfs := TAliOssFileSystem.Create(self.IniData.AccessId, self.IniData.AccessKey, self.IniData.OssHostname);
if ossfs.ListVolumns(volumns) then
success := true;
ossfs.Destroy;
except
end;
end;
end;
if success then
begin
self.CachedBuckets.Clear;
for I := Low(volumns) to High(volumns) do
begin
self.CachedBuckets.Add(volumns[I].name);
end;
self.AddLog('已缓存bucket列表');
end
else
self.AddLog('缓存bucket列表失败');
end;
procedure TfrmMain.LoadIniFile;
var
filename: string;
ini: TIniFile;
I: Integer;
count: integer;
begin
filename := StringReplace(ParamStr(0), '.exe', '.ini', [rfReplaceAll]);
if FileExists(filename) then
begin
ini := TIniFile.Create(filename);
//OSS
self.IniData.OssHostname := ini.ReadString('OSS', 'Hostname', '');
self.IniData.AccessId := ini.ReadString('OSS', 'AccessId', '');
self.IniData.AccessKey := ini.ReadString('OSS', 'AccessKey', '');
//Mail
self.IniData.MailHostname := ini.ReadString('Mail', 'Hostname', 'localhost');
self.IniData.MailSMTPLogin := ini.ReadBool('Mail', 'SMTPLogin', true);
self.IniData.MailBucket := ini.ReadString('Mail', 'Bucket', '');
//Accounts
count := ini.ReadInteger('Accounts', 'Count', 0);
self.IniData.Accounts.Clear;
for I := 1 to count do
begin
self.IniData.Accounts.Add(ini.ReadString('Accounts', 'Account'+IntToStr(i), ''));
end;
ini.Free;
self.AddLog('已载入配置文件');
LoadCachedBuckets;
end
else
begin
//default values
self.IniData.MailHostname := 'localhost';
self.IniData.MailSMTPLogin := true;
self.AddLog('未找到配置文件,请首先进行参数设置');
end;
end;
procedure TfrmMain.pop3BeforeCommandHandler(ASender: TIdCmdTCPServer;
var AData: string; AContext: TIdContext);
var
cmd: string;
begin
if UpperCase(Copy(AData, 1, 4)) = 'PASS' then
cmd := 'PASS ******'
else
cmd := AData;
self.AddLog('[POP3] 客户端命令:' + cmd);
end;
procedure TfrmMain.pop3CheckUser(aContext: TIdContext;
aServerContext: TIdPOP3ServerContext);
var
data, guid, username, password, lockstr: string;
I: Integer;
found, locked: boolean;
begin
found := false;
locked := false;
for I := 0 to self.IniData.Accounts.Count - 1 do
begin
data := self.IniData.Accounts[I];
guid := PopString(data);
username := PopString(data);
password := PopString(data);
lockstr := PopString(data);
if ((username = aServerContext.Username) or (username + '@' + self.IniData.MailHostname = aServerContext.Username)) and
(password = aServerContext.Password) then
begin
found := true;
locked := lockstr = 'true';
break;
end;
end;
if not found then
begin
self.AddLog('[POP3] 身份验证失败,用户名='+aServerContext.Username);
raise Exception.Create('Authentication failed');
end
else
begin
if locked then
begin
self.AddLog('[POP3] 身份验证失败,该用户被锁定,用户名='+aServerContext.Username);
raise Exception.Create('User is locked');
end
else
begin
self.AddLog('[POP3] 身份验证成功,用户名='+aServerContext.Username);
currentUsername := username;
currentGuid := guid;
SetLength(currentMails, 0);
SetLength(deleteMarkers, 0);
end;
end;
end;
procedure TfrmMain.pop3Connect(AContext: TIdContext);
begin
self.AddLog('[POP3] 接受客户端连接,IP地址:'+AContext.Binding.PeerIP);
end;
//mark a mail to delete
procedure TfrmMain.pop3Delete(aCmd: TIdCommand; AMsgNo: Integer);
begin
if (AMsgNo >= 1) and (AMsgNo <= length(currentMails)) then
begin
deleteMarkers[AMsgNo - 1] := true;
aCmd.Reply.SetReply(OK, 'message '+IntTostr(AMsgNo)+' deleted');
aCmd.SendReply;
self.AddLog('[POP3][DELE] 标记“'+currentUsername+'”用户的邮件:'+currentMails[AMsgNo-1].name);
end
else
begin
self.AddLog('[POP3][DELE] 客户端命令编号错误:'+IntToStr(AMsgNo));
raise Exception.Create('Invalid message number');
end;
end;
procedure TfrmMain.pop3Disconnect(AContext: TIdContext);
begin
if not force_mail_stop then
self.AddLog('[POP3] 客户端断开连接,IP地址:'+AContext.Binding.PeerIP);
end;
//list sing mail or all mails
procedure TfrmMain.pop3List(aCmd: TIdCommand; AMsgNo: Integer);
var
size: integer;
ossfs: TAliOssFileSystem;
I: Integer;
begin
ossfs := TAliOssFileSystem.Create(self.IniData.AccessId, self.IniData.AccessKey, self.IniData.OssHostname);
ossfs.ChangeVolumn(self.IniData.MailBucket);
if AMsgNo = -1 then
begin
//list all mails
size := 0;
for I := Low(currentMails) to High(currentMails) do
size := size + currentMails[I].size;
aCmd.Reply.SetReply(OK, IntToStr(length(currentMails))+' message ('+IntToStr(size)+' octets)');
aCmd.SendReply;
for I := Low(currentMails) to High(currentMails) do
aCmd.Context.Connection.IOHandler.WriteLn(IntToStr(i+1)+' '+IntToStr(currentMails[I].size));
aCmd.Context.Connection.IOHandler.WriteLn('.');
self.AddLog('[POP3][LIST] 列出“'+currentUsername+'”用户的'+IntToStr(length(currentMails))+'封邮件');
end
else
begin
//list single mail
if (AMsgNo >= 1) and (AMsgNo <= length(currentMails)) then
begin
size := currentMails[AMsgNo-1].size;
aCmd.Reply.SetReply(OK, IntToStr(AMsgNo)+' '+IntToStr(size));
aCmd.SendReply;
self.AddLog('[POP3][LIST] 列出“'+currentUsername+'”用户的1封邮件');
end
else
begin
self.AddLog('[POP3][LIST] 客户端命令编号错误:'+IntToStr(AMsgNo));
raise Exception.Create('Invalid message number');
end;
end;
ossfs.Free;
end;
//quit, delete all marked mails
procedure TfrmMain.pop3Quit(aCmd: TIdCommand);
var
ossfs: TAliOssFileSystem;
I: Integer;
begin
self.AddLog('[POP3][QUIT] “'+currentUsername+'”用户注销登录');
ossfs := TAliOssFileSystem.Create(self.IniData.AccessId, self.IniData.AccessKey, self.IniData.OssHostname);
ossfs.ChangeVolumn(self.IniData.MailBucket);
for I := Low(deleteMarkers) to High(deleteMarkers) do
begin
if deleteMarkers[I] then
begin
//delete this mail
ossfs.RemoveFile(currentGuid+'/'+currentMails[I].name);
self.AddLog('[POP3][QUIT] 删除“'+currentUsername+'”用户的邮件:'+currentMails[I].name);
end;
end;
aCmd.Reply.SetReply(OK, 'Server signing off (maildrop empty)');
aCmd.SendReply;
end;
//reset delete markers
procedure TfrmMain.pop3Reset(aCmd: TIdCommand);
var
I: Integer;
begin
for I := Low(deleteMarkers) to High(deleteMarkers) do
deleteMarkers[I] := false;
aCmd.Reply.SetReply(OK, IntTostr(length(deleteMarkers)) + ' messages available');
aCmd.SendReply;
self.AddLog('[POP3][RSET] 撤销删除“'+currentUsername+'”用户的邮件');
end;
//download a mail
procedure TfrmMain.pop3Retrieve(aCmd: TIdCommand; AMsgNo: Integer);
var
oss: TAliOss;
obj: string;
ret: TAliOssReturnType;
body: string;
mail: TStringList;
begin
if (AMsgNo >= 1) and (AMsgNo <= length(currentMails)) then
begin
obj := currentGuid + '/' + currentMails[AMsgNo-1].name;
oss := TAliOss.Create(self.IniData.AccessId, self.IniData.AccessKey, self.IniData.OssHostname);
ret := oss.GetObject(self.IniData.MailBucket, obj);
if ret.status = 200 then
begin
body := ret.body.DataString;
aCmd.Reply.SetReply(OK, IntToStr(length(body))+' octets');
aCmd.SendReply;
mail := TStringList.Create;
mail.Text := body;
aCmd.Context.Connection.WriteRFCStrings(mail);
mail.Free;
self.AddLog('[POP3][RETR] 成功获取“'+currentUsername+'”用户的邮件:'+obj);
end
else
begin
self.AddLog('[POP3][RETR] 无法获取“'+currentUsername+'”用户的邮件:'+obj);
end;
oss.Free;
end
else
begin
self.AddLog('[POP3][RETR] 客户端命令编号错误:'+IntToStr(AMsgNo));
raise Exception.Create('Invalid message number');
end;
end;
//get new mail information
procedure TfrmMain.pop3Stat(aCmd: TIdCommand; out oCount, oSize: Integer);
var
ossfs: TAliOssFileSystem;
mails: TAliOssFileInfoList;
I: Integer;
len: Integer;
size: integer;
begin
ossfs := TAliOssFileSystem.Create(self.IniData.AccessId, self.IniData.AccessKey, self.IniData.OssHostname);
ossfs.ChangeVolumn(self.IniData.MailBucket);
len := 0;
size := 0;
if ossfs.ListDirectory(currentGuid, mails) then
begin
SetLength(currentMails, length(mails));
for I := Low(mails) to High(mails) do
begin
if mails[I].isFile then
begin
currentMails[len] := mails[I];
inc(len);
size := size + mails[I].size;
end;
end;
end;
SetLength(currentMails, len);
SetLength(deleteMarkers, len);
for I := Low(deleteMarkers) to High(deleteMarkers) do
begin
deleteMarkers[I] := false;
end;
ossfs.Free;
oCount := len;
oSize := size;
self.AddLog('[POP3][STAT] 找到“'+currentUsername+'”用户的'+IntToStr(len)+'封邮件,总大小:'+IntToStr(size)+'字节');
end;
//send headers of the message, a blank line, and the first 10 lines of the mail body
procedure TfrmMain.pop3Top(aCmd: TIdCommand; aMsgNo, aLines: Integer);
begin
//not used
end;
//send unique id listing for single mail or all mails
procedure TfrmMain.pop3UIDL(aCmd: TIdCommand; AMsgNo: Integer);
var
data: TStringList;
I: Integer;
begin
if AMsgNo = -1 then
begin
//list all mails
aCmd.Reply.SetReply(OK, 'unique-id listing follows');
aCmd.SendReply;
data := TStringList.Create;
for I := Low(currentMails) to High(currentMails) do
data.Add(IntToStr(i+1)+' '+currentMails[i].name);
data.Add('.');
aCmd.Context.Connection.WriteRFCStrings(data);
data.Free;
self.AddLog('[POP3][UIDL] 列出“'+currentUsername+'”用户的'+IntToStr(length(currentMails))+'封邮件ID');
end
else
begin
//list single mail
if (AMsgNo >= 1) and (AMsgNo <= length(currentMails)) then
begin
aCmd.Reply.SetReply(OK, IntToStr(AMsgNo)+' '+currentMails[AMsgNo-1].Name);
aCmd.SendReply;
self.AddLog('[POP3][UIDL] 列出“'+currentUsername+'”用户的1封邮件ID');
end
else
begin
self.AddLog('[POP3][UIDL] 客户端命令编号错误:'+IntToStr(AMsgNo));
raise Exception.Create('Invalid message number');
end;
end;
end;
procedure TfrmMain.AddLog(log: string);
begin
self.FCachedLogs.Add(TimeToStr(Now)+ ' ' + log);
end;
procedure TfrmMain.btnAboutClick(Sender: TObject);
var
msg: string;
begin
msg := '软件版本:1.0.0'#13#10
+ '基础类库:OSS (Open Storage Services) Delphi SDK v1.0.0'#13#10
+ '软件授权:MIT许可证 (The MIT License)'#13#10
+ '软件开发:广州云信软件开发有限公司 http://cloudstrust.com'#13#10
+ '联系方式:menway@gmail.com';
MessageDlg('关于 '+self.Caption, msg, '确定');
end;
procedure TfrmMain.btnCloseClick(Sender: TObject);
begin
Application.MainForm.Close;
end;
procedure TfrmMain.btnMinimizeClick(Sender: TObject);
begin
Application.MainForm.WindowState := TWindowState.wsMinimized;
end;
procedure TfrmMain.ClearLogs;
begin
self.FCachedLogs.Clear;
end;
function TfrmMain.ClickTest: boolean;
begin
result := MilliSecondsBetween(Now, lastClickTime) > 100;
lastClickTime := Now;
end;
procedure TfrmMain.FormActivate(Sender: TObject);
begin
self.loToolbar.BringToFront;
end;
procedure TfrmMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
self.FAntiFreeze.Free;
self.FCachedLogs.Free;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
self.IniData.Accounts := TStringList.Create;
FCachedLogs := TStringList.Create;
self.tmrDeferredLog.Enabled := true;
self.ClearLogs;
self.AddLog('应用程序启动');
self.SwitchIcon(self.lbiMenuMail, 'imgMailOff');
CopyBitmap(self.lbiMenuSettings.Icon, self.imgSettingsOff.Bitmap);
CopyBitmap(self.lbiMenuAccounts.Icon, self.imgAccountsOff.Bitmap);
lastClickTime := Now;
self.FAntiFreeze := TIdAntiFreeze.Create(self);
self.FAntiFreeze.IdleTimeOut := 100;
self.FAntiFreeze.Active := true;
CachedBuckets := TStringList.Create;
self.tmrDeferredInit.Enabled := true;
force_mail_stop := false;
end;
procedure TfrmMain.FormGesture(Sender: TObject;
const EventInfo: TGestureEventInfo; var Handled: Boolean);
var
DX, DY : Single;
begin
if EventInfo.GestureID = igiPan then
begin
if (TInteractiveGestureFlag.gfBegin in EventInfo.Flags)
and ((Sender = ppToolbar)
or (EventInfo.Location.Y > (ClientHeight - 70))) then
begin
FGestureOrigin := EventInfo.Location;
FGestureInProgress := True;
end;
if FGestureInProgress and (TInteractiveGestureFlag.gfEnd in EventInfo.Flags) then
begin
FGestureInProgress := False;
DX := EventInfo.Location.X - FGestureOrigin.X;
DY := EventInfo.Location.Y - FGestureOrigin.Y;
if (Abs(DY) > Abs(DX)) then
ShowToolbar(DY < 0);
end;
end
end;
procedure TfrmMain.FormKeyDown(Sender: TObject; var Key: Word;
var KeyChar: Char; Shift: TShiftState);
begin
if Key = vkEscape then
ShowToolbar(not ppToolbar.IsOpen);
end;
procedure TfrmMain.FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
begin
if Button = TMouseButton.mbRight then
ShowToolbar(True)
else
ShowToolbar(False);
end;
procedure TfrmMain.SaveIniFile;
var
filename: string;
ini: TIniFile;
I: integer;
begin
filename := StringReplace(ParamStr(0), '.exe', '.ini', [rfReplaceAll]);
ini := TIniFile.Create(filename);
//OSS
ini.WriteString('OSS', 'Hostname', self.IniData.OssHostname);
ini.WriteString('OSS', 'AccessId', self.IniData.AccessId);
ini.WriteString('OSS', 'AccessKey', self.IniData.AccessKey);
//Mail
ini.WriteString('Mail', 'Hostname', self.IniData.MailHostname);
ini.WriteBool('Mail', 'SMTPLogin', self.IniData.MailSMTPLogin);
ini.WriteString('Mail', 'Bucket', self.IniData.MailBucket);
//Accounts
ini.WriteInteger('Accounts', 'Count', self.IniData.Accounts.Count);
for I := 1 to self.IniData.Accounts.Count do
begin
ini.WriteString('Accounts', 'Account'+IntToStr(i), self.IniData.Accounts[i-1]);
end;
ini.Free;
self.AddLog('已保存配置文件');
end;
procedure TfrmMain.ShowToolbar(const AShow: Boolean);
begin
ppToolbar.Width := ClientWidth;
ppToolbar.PlacementRectangle.Rect := TRectF.Create(0, ClientHeight-ppToolbar.Height, ClientWidth-1, ClientHeight-1);
ppToolbarAnimation.StartValue := ppToolbar.Height;
ppToolbarAnimation.StopValue := 0;
ppToolbar.IsOpen := AShow;
end;
procedure TfrmMain.smtpBeforeCommandHandler(ASender: TIdCmdTCPServer;
var AData: string; AContext: TIdContext);
begin
self.AddLog('[SMTP] 客户端命令:' + AData);
end;
procedure TfrmMain.smtpConnect(AContext: TIdContext);
begin
self.AddLog('[SMTP] 接受客户端连接,IP地址:'+AContext.Binding.PeerIP);
end;
procedure TfrmMain.smtpDisconnect(AContext: TIdContext);
begin
if not force_mail_stop then
self.AddLog('[SMTP] 客户端断开连接,IP地址:'+AContext.Binding.PeerIP);
end;
//send mail, from field
procedure TfrmMain.smtpMailFrom(ASender: TIdSMTPServerContext;
const AAddress: string; AParams: TStrings; var VAction: TIdMailFromReply);
begin
// The following actions can be returned to the server:
{ mAccept, mReject }
if Pos('@', AAddress) > 0 then
begin
VAction:= mAccept;
self.AddLog('[SMTP][MAIL FROM] 来源邮箱正常');
end
else
begin
VAction := mReject;
self.AddLog('[SMTP][MAIL FROM] 来源邮箱错误');
end;
end;
//save mail to oss or relay to other server
procedure TfrmMain.smtpMsgReceive(ASender: TIdSMTPServerContext; AMsg: TStream;
var VAction: TIdDataReply);
var
msg: TIdMessage;
str: TStringStream;
oss: TAliOss;
ret: TAliOssReturnType;
opt: TAliOssOption;
I: Integer;
guid, username: string;
addr: string;
local: boolean;
J: Integer;
data: string;
found: boolean;
timestamp: string;
LRelayRecipients: TIdEMailAddressList;
begin
try
//decode mail message
msg := TIdMessage.Create(self);
msg.LoadFromStream(AMsg);
LRelayRecipients := nil;
for I := 0 to ASender.RCPTList.Count - 1 do
begin
addr := ASender.RCPTList[I].Address;
local := lowercase(self.IniData.MailHostname) = lowercase(ASender.RCPTList[I].Domain);
if local then
begin
//local address
username := ASender.RCPTList[I].User;
found := false;
for J := 0 to self.IniData.Accounts.Count - 1 do
begin
data := self.IniData.Accounts[J];
guid := PopString(data);
if lowercase(username) = lowercase(PopString(data)) then
begin
found := true;
//save to oss
oss := TAliOss.Create(self.IniData.AccessId, self.IniData.AccessKey, self.IniData.OssHostname);
opt := TAliOssOption.Create;
str := TStringStream.Create;
str.LoadFromStream(AMsg);
opt.Values[OSS_CONTENT] := str.DataString;
str.Free;
timestamp := FormatDateTime('yyyymmddhhmmsszzz', Now);
ret := oss.UploadFileByContent(self.IniData.MailBucket, guid+'/'+timestamp+'.eml', opt);
if ret.status = 200 then
begin
self.AddLog('[SMTP][RCPT] 用户“'+currentUsername+'”成功发送内部邮件到:'+addr);
end
else
begin
self.AddLog('[SMTP][RCPT] 用户“'+currentUsername+'”无法发送内部邮件到:'+addr+',未知错误');
end;
oss.Free;
opt.Free;
end;
end;
if not found then
begin
self.AddLog('[SMTP][RCPT] 用户“'+currentUsername+'”无法发送内部邮件到:'+addr+',收件人账户不存在');
end;
end
else
begin
//remote address
if not Assigned(LRelayRecipients) then LRelayRecipients := TIdEMailAddressList.Create(nil);
LRelayRecipients.Add.Assign(ASender.RCPTList[I]);
self.AddLog('[SMTP][RCPT] 用户“'+currentUsername+'”发送外部邮件到:'+addr);
end;
end;
//relay
if Assigned(LRelayRecipients) then
begin
self.smtpRelay.Send(msg, LRelayRecipients);
end;
LRelayRecipients.Free;
msg.Free;
except
end;
end;
procedure TfrmMain.smtpRcptTo(ASender: TIdSMTPServerContext;
const AAddress: string; AParams: TStrings; var VAction: TIdRCPToReply;
var VForward: string);
begin
// The following actions can be returned to the server:
{
rAddressOk, //address is okay
rRelayDenied, //we do not relay for third-parties
rInvalid, //invalid address
rWillForward, //not local - we will forward
rNoForward, //not local - will not forward - please use
rTooManyAddresses, //too many addresses
rDisabledPerm, //disabled permanently - not accepting E-Mail
rDisabledTemp //disabled temporarily - not accepting E-Mail
}
if Pos('@', AAddress) > 0 then
begin
VAction := rAddressOk;
self.AddLog('[SMTP][RCPT TO] 目的邮箱正常');
end
else
begin
VAction :=rInvalid;
self.AddLog('[SMTP][RCPT TO] 目的邮箱错误');
end;
{
//rWillForward will cause a 251 prompt at user client - ignore it for now
if Pos('@'+self.IniData.MailHostname, AAddress) = 0 then
begin
//remote address
VAction := rWillForward;
VForward := AAddress;
end
}
end;
//control "Received" header
procedure TfrmMain.smtpReceived(ASender: TIdSMTPServerContext;
var AReceived: string);
begin
//not used
AReceived := '';
end;
procedure TfrmMain.smtpUserLogin(ASender: TIdSMTPServerContext; const AUsername,
APassword: string; var VAuthenticated: Boolean);
var
I: Integer;
data: string;
guid, username, password, lockstr: string;
begin
if not self.IniData.MailSMTPLogin then
begin
//do not validate user info
VAuthenticated := true;
self.AddLog('[SMTP] 跳过身份验证');
exit;
end;
VAuthenticated := false;
for I := 0 to self.IniData.Accounts.Count - 1 do
begin
data := self.IniData.Accounts[I];
guid := PopString(data);
username := PopString(data);
password := PopString(data);
lockstr := PopString(data);
if ((username = AUsername) or (username+'@'+self.IniData.MailHostname = AUsername)) and (password = APassword) then
begin
if lockstr = 'true' then
begin
self.AddLog('[SMTP] 身份验证失败,该用户被锁定,用户名='+AUsername);
exit;
end;
currentUsername := username;
currentGuid := guid;
VAuthenticated := true;
self.AddLog('[SMTP] 身份验证成功,用户名='+AUsername);
exit;
end;
end;
self.AddLog('[SMTP] 身份验证失败,用户名='+AUsername);
end;
//POP3 implementation: ref http://www.devarticles.com/c/a/Delphi-Kylix/Creating-a-POP3-Server
//POP3 workflow: USER -> PASS -> STAT -> LIST -> UIDL -> RETR x -> QUIT
//SMTP implementation: ref http://www.devarticles.com/c/a/Delphi-Kylix/Creating-an-SMTP-Server/
//SMTP workflow: EHLO -> AUTH LOGIN -> MAIL FROM: xxx -> RCPT TO: xxx -> DATA -> QUIT
function TfrmMain.StartMail: boolean;
var
success: boolean;
begin
success := false;
try
self.pop3.Active := true;
self.smtp.Active := true;
success := true;
except
end;
if success then
self.AddLog('邮件服务器已启动')
else
MessageDlg('错误', '邮件服务器启动失败,请检查具体设置。', '确定');
result := success;
end;
function TfrmMain.StopMail: boolean;
begin
result := false;
try
force_mail_stop := true;
self.pop3.Active := false;
self.smtp.Active := false;
force_mail_stop := false;
result := true;
self.AddLog('邮件服务器已停止');
except
end;
end;
procedure TfrmMain.SwitchIcon(lb: TMetropolisUIListBoxItem;
const imgName: string);
var
img: TImage;
begin
if (Assigned(lb)) then
begin
lb.TagString := imgName;
img := self.FindComponent(imgName) as TImage;
if Assigned(img) then
lb.Icon.Assign(img.Bitmap);
end;
end;
procedure TfrmMain.SwitchSubTitle(lb: TMetropolisUIListBoxItem);
const
switchFrom: array[1..4] of string = ('启动', '停止', 'start', 'stop');
switchTo: array[1..4] of string = ('停止', '启动', 'stop', 'start');
var
I: Integer;
begin
for I := 1 to 4 do
begin
if Pos(switchFrom[I], lb.SubTitle) <> 0 then
begin
lb.SubTitle := StringReplace(lb.SubTitle, switchFrom[I], switchTo[I], [rfReplaceAll]);
exit;
end;
end;
end;
procedure TfrmMain.tmrDeferredInitTimer(Sender: TObject);
begin
self.tmrDeferredInit.Enabled := false;
self.LoadIniFile;
end;
procedure TfrmMain.tmrDeferredLogTimer(Sender: TObject);
var
I: Integer;
begin
self.tmrDeferredLog.Enabled := false;
try
if self.FCachedLogs.Count <> 0 then
begin
for I := 0 to self.FCachedLogs.Count - 1 do
begin
self.mmLogs.Lines.Add(self.FCachedLogs[I]);
end;
while (self.mmLogs.VScrollBar.Visible) and (self.mmLogs.Lines.Count > 0) do
self.mmLogs.Lines.Delete(0);
self.FCachedLogs.Clear;
end;
except
end;
self.tmrDeferredLog.Enabled := true;
end;
end.
|
unit uMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, RpCon, RpBase, RpSystem, RpDefine, RpRave, StdCtrls, Buttons;
type
TfmMain = class(TForm)
bbPrint: TBitBtn;
rpReport: TRvProject;
rsSystem: TRvSystem;
rcCustom: TRvCustomConnection;
meLeft: TMemo;
meRight: TMemo;
bbOpenLeft: TBitBtn;
bbClearLeft: TBitBtn;
dlgOpen: TOpenDialog;
bbOpenRight: TBitBtn;
bbClearRight: TBitBtn;
procedure bbPrintClick(Sender: TObject);
procedure rcCustomOpen(Connection: TRvCustomConnection);
procedure rcCustomGetCols(Connection: TRvCustomConnection);
procedure rcCustomGetRow(Connection: TRvCustomConnection);
procedure bbOpenLeftClick(Sender: TObject);
procedure bbClearLeftClick(Sender: TObject);
procedure bbOpenRightClick(Sender: TObject);
procedure bbClearRightClick(Sender: TObject);
private
i: integer;
public
{ Public declarations }
end;
var
fmMain: TfmMain;
implementation
{$R *.dfm}
uses Math;
procedure TfmMain.bbPrintClick(Sender: TObject);
begin
rpReport.Execute;
end;
procedure TfmMain.rcCustomOpen(Connection: TRvCustomConnection);
begin
Connection.DataRows := Max(meLeft.Lines.Count, meRight.Lines.Count);
i := 0;
end;
procedure TfmMain.rcCustomGetCols(Connection: TRvCustomConnection);
begin
Connection.WriteField('LeftColumn', dtString, 40, 'LeftColumn', '');
Connection.WriteField('RightColumn', dtString, 40, 'RightColumn', '');
end;
procedure TfmMain.rcCustomGetRow(Connection: TRvCustomConnection);
begin
if meLeft.Lines.Count >= i
then Connection.WriteStrData('', meLeft.Lines[i])
else Connection.WriteNullData;
if meRight.Lines.Count >= i
then Connection.WriteStrData('', meRight.Lines[i])
else Connection.WriteNullData;
Inc(i);
end;
procedure TfmMain.bbOpenLeftClick(Sender: TObject);
begin
if dlgOpen.Execute then
begin
meLeft.Clear;
meLeft.Lines.LoadFromFile(dlgOpen.FileName);
end;
end;
procedure TfmMain.bbClearLeftClick(Sender: TObject);
begin
meLeft.Clear;
end;
procedure TfmMain.bbOpenRightClick(Sender: TObject);
begin
if dlgOpen.Execute then
begin
meRight.Clear;
meRight.Lines.LoadFromFile(dlgOpen.FileName);
end;
end;
procedure TfmMain.bbClearRightClick(Sender: TObject);
begin
meRight.Clear;
end;
end.
|
unit umainform;
{$mode objfpc}{$H+}
interface
uses
SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, Buttons, StdCtrls,
Spin, ueverettrandom;
type
{ Tmainform }
Tmainform = class(TForm)
cmdSplit: TBitBtn;
cmdClose: TBitBtn;
grpNumElements: TGroupBox;
grp_HexSize: TGroupBox;
grpResults: TGroupBox;
lstResults: TListBox;
pnlMain: TPanel;
rgSingleElement: TRadioGroup;
spArrayNumber: TSpinEdit;
spHexSize: TSpinEdit;
procedure cmdSplitClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
private
myEverett: TEverett;
public
end;
var
mainform: Tmainform;
implementation
{$R *.lfm}
{ Tmainform }
procedure Tmainform.FormCreate(Sender: TObject);
begin
Caption:=Application.Name;
Icon:=Application.Icon;
myEverett := TEverett.Create(Self);
// Set up dialog
// MyEverett.WaitDialogCaption:='Please wait. contacting server';
MyEverett.ShowWaitDialog:=TRUE;
end;
procedure Tmainform.FormResize(Sender: TObject);
begin
// Set minimum size
if Width < 300 then
Width := 300;
if Height < 500 then
Height := 500;
end;
procedure Tmainform.cmdSplitClick(Sender: TObject);
var
s: string;
ct:Integer;
begin
lstResults.Clear;
MyEverett.ArraySize:=spArrayNumber.Value;
MyEverett.HexSize:=spHexSize.Value;
case rgSingleElement.ItemIndex of
0:begin
MyEverett.GetInteger8BitArray;
for ct:=0 to Pred(MyEverett.ArraySize) do
lstResults.Items.Add(InttoStr(MyEverett.IntegerArray[ct]));
end;
1:begin
MyEverett.GetInteger16BitArray;
for ct:=0 to Pred(MyEverett.ArraySize) do
lstResults.Items.Add(InttoStr(MyEverett.IntegerArray[ct]));
end;
2:begin
MyEverett.GetHexArray;
for ct:=0 to Pred(MyEverett.ArraySize) do
lstResults.Items.Add(MyEverett.HexArray[ct]);
end;
end;
s := 'Universe sucessfully split' + LineEnding;
ShowMessageFmt('%s%d times!',[s,spArrayNumber.Value]);
end;
end.
|
unit uGMV_Log;
interface
uses
Classes
, SysUtils
, uROR_RPCBroker
, fROR_PCall
;
type
TRPCEventItem = class(TObject)
public
Start: TDateTime;
Stop: TDateTime;
RPC: string;
Params: TStrings;
Results: TStrings;
constructor Create;
destructor Destroy; override;
end;
TActionEventItem = class(TObject)
public
Start: TDateTime;
Stop: TDateTime;
Action: string;
Actor: string;
Comments: TStrings;
constructor Create;
destructor Destroy; override;
end;
function RegisterActionStart: TDateTime;
function getRPCEventItem(
aStart, aStop: TDateTime;
RemoteProcedure: string;
Parameters: array of string; MultList: TStringList = nil;
RPCMode: TRPCMode = []; RetList: TStrings = nil): TRPCEventItem;
(*
procedure RegisterActionItem(
aStart,aStop:TDateTime;
anAction,anActor:String;
aComments: String ='');
*)
function EventStart(anEventName: string; anEventComment: string = ''): TDateTime;
procedure EventRegister(aStart, aStop: TDateTime;anEvent: string;aComments: string = '');
function EventStop(anEventName: string; anEventComment: string = ''; aStart: TDateTime = 0): TDateTime;
function EventAdd(anEventName: string; anEventComment: string = ''; aTime: TDateTime = 0): TDateTime;
var
RPCLog: TStrings;
RPCCount: Integer;
ActionLog: TStrings;
ActionMargin: string;
const
ActionMarginDelta = ' ';
implementation
uses fGMV_RPCLog;
function getActionEventItem(
aStart, aStop: TDateTime;
anAction, anActor: string;
aComments: string = ''): TActionEventItem;
var
Item: TActionEventItem;
begin
Item := TActionEventItem.Create;
Item.Start := aStart;
Item.Stop := aStop;
Item.Action := anAction;
Item.Actor := anActor;
if aComments <> '' then
Item.Comments.Text := aComments;
Result := Item;
end;
procedure RegisterActionItem(
aStart, aStop: TDateTime;
anAction, anActor: string;
aComments: string = '');
var
Item: TActionEventItem;
iLimit: Integer;
begin
// use SHOWLOG directive to work with the log
{$IFNDEF SHOWLOG} exit; {$ENDIF}
Item := getActionEventItem(aStart, aStop, anAction, anActor, aComments);
ActionLog.InsertObject(0,
FormatDateTime('hh:mm:ss.zzz', aStop) + ' ' + ActionMargin + AnActor + ': ' + AnAction, Item);
iLimit := 300;
if assigned(frmGMV_RPCLog) then
iLimit := StrToIntDef(frmGMV_RPCLog.ComboBox2.Text, iLimit);
while ActionLog.Count > iLimit do
begin
if ActionLog.Objects[ActionLog.Count - 1] <> nil then
TActionEventItem(ActionLog.Objects[ActionLog.Count - 1]).Free;
ActionLog.Delete(ActionLog.Count - 1);
end;
if assigned(frmGMV_RPCLog) then
begin
frmGMV_RPCLog.lbRoutines.Items.Assign(ActionLog);
frmGMV_RPCLog.lbRoutines.ItemIndex := 0;
frmGMV_RPCLog.lbRoutinesClick(nil);
end;
ActionMargin := copy(ActionMargin, 1, Length(ActionMargin) - Length(ActionMarginDelta));
end;
function RegisterActionStart: TDateTime;
begin
Result := Now;
ActionMargin := ActionMargin + ActionMarginDelta;
end;
////////////////////////////////////////////////////////////////////////////////
procedure EventRegister(
aStart, aStop: TDateTime;
anEvent: string;
aComments: string = '');
var
Item: TActionEventItem;
iLimit: Integer;
begin
// use SHOWLOG directive to work with the log
{$IFNDEF SHOWLOG} exit; {$ENDIF}
Item := getActionEventItem(aStart, aStop, anEvent, '', aComments);
ActionLog.InsertObject(0,
FormatDateTime('hh:mm:ss.zzz', aStop) + ' ' + ActionMargin + AnEvent,
Item);
iLimit := 300;
if assigned(frmGMV_RPCLog) then
iLimit := StrToIntDef(frmGMV_RPCLog.ComboBox2.Text, iLimit);
while ActionLog.Count > iLimit do
begin
if ActionLog.Objects[ActionLog.Count - 1] <> nil then
TActionEventItem(ActionLog.Objects[ActionLog.Count - 1]).Free;
ActionLog.Delete(ActionLog.Count - 1);
end;
try
if assigned(frmGMV_RPCLog) and Assigned(frmGMV_RPCLog.lbRoutines) then
begin
frmGMV_RPCLog.lbRoutines.Items.Assign(ActionLog);
frmGMV_RPCLog.lbRoutines.ItemIndex := 0;
frmGMV_RPCLog.lbRoutinesClick(nil);
end;
except
end;
end;
function EventStart(anEventName: string; anEventComment: string = ''): TDateTime;
var
s: string;
begin
Result := Now;
s := anEventComment;
if s = '' then s := 'Start';
EventRegister(Result, Result, anEventName, s);
ActionMargin := ActionMargin + ActionMarginDelta;
end;
function EventStop(anEventName: string; anEventComment: string = ''; aStart: TDateTime = 0): TDateTime;
var
s: string;
begin
s := anEventComment;
if s = '' then s := 'Stop';
Result := Now;
ActionMargin := copy(ActionMargin, 1, Length(ActionMargin) - Length(ActionMarginDelta));
EventRegister(aStart, Result, anEventName, s);
end;
function EventAdd(anEventName: string; anEventComment: string = ''; aTime: TDateTime = 0): TDateTime;
begin
Result := Now;
EventRegister(aTime, Result, anEventName, anEventComment);
end;
////////////////////////////////////////////////////////////////////////////////
function getRPCEventItem(
aStart, aStop: TDateTime;
RemoteProcedure: string;
Parameters: array of string; MultList: TStringList = nil;
RPCMode: TRPCMode = []; RetList: TStrings = nil): TRPCEventItem;
var
Item: TRPCEventItem;
i, j: Integer;
begin
Item := TRPCEventItem.Create;
Item.Start := aStart;
Item.Stop := aStop;
Item.RPC := RemoteProcedure;
Item.Params.Add('Params: ---------------------------------------------------');
i := 0;
while i <= High(Parameters) do
begin
if (Copy(Parameters[i], 1, 1) = '@') and (Parameters[i] <> '@') then
begin
Item.Params.Add('Reference ' + IntToStr(i) + ' <' + Copy(Parameters[i], 2, Length(Parameters[i])) + '>');
end
else
begin
Item.Params.Add('Literal ' + IntToStr(i) + ' <' + Parameters[i] + '>');
end;
Inc(i);
end;
if MultList <> nil then
if MultList.Count > 0 then
begin
Item.Params.Add('List:');
for j := 1 to MultList.Count do
Item.Params.Add(MultList[j - 1]);
end;
if RetList <> nil then
if RetList.Count > 0 then
begin
Item.Results.Add('Results: --------------------------------------------------');
for j := 0 to RetList.Count - 1 do
Item.Results.Add(RetList[j]);
end;
Result := Item;
end;
constructor TRPCEventItem.Create;
begin
inherited;
Params := TStringList.Create;
Results := TStringList.Create;
end;
destructor TRPCEventItem.Destroy;
begin
if Assigned(Params) then
FreeAndNil(Params);
if Assigned(Results) then
FreeAndNil(Results);
inherited;
end;
////////////////////////////////////////////////////////////////////////////////
constructor TActionEventItem.Create;
begin
inherited;
Comments := TStringList.Create;
end;
destructor TActionEventItem.Destroy;
begin
Comments.Free;
inherited;
end;
initialization
RPCLog := TStringList.Create;
ActionLog := TStringList.Create;
ActionMargin := '';
RPCCount := 0;
finalization
//exit;
while RPCLog.Count > 0 do
begin
try
if RPCLog.Objects[0] <> nil then
begin
if RPCLog.Objects[0] is TRPCEventItem then
TRPCEventItem(RPCLog.Objects[0]).Free
else
TObject(RPCLog.Objects[0]).Free;
end;
RPCLog.Delete(0);
except
end;
end;
FreeAndNil(RPCLog);
while ActionLog.Count > 0 do
begin
try
if ActionLog.Objects[0] <> nil then
TActionEventItem(ActionLog.Objects[0]).Free;
ActionLog.Delete(0);
except
end;
end;
FreeAndNil(ActionLog);
end.
|
unit DirectOutput_explicit;
interface
uses Windows, Dialogs, SysUtils;
const
X52PRO_GUID : TGuid = '{29DAD506-F93B-4F20-85FA-1E02C04FAC17}';
// the callback functions
type
PFN_DIRECTOUTPUT_DEVICE_CALLBACK = procedure(hDevice:LongInt; bAdded: Boolean; lContext: LongInt); stdcall;
PFN_DIRECTOUTPUT_SOFTBUTTON_CALLBACK = procedure (hDevice, lButtons, lContext: Longint); stdcall;
PFN_DIRECTOUTPUT_PAGE_CALLBACK = procedure(hDevice, lPage : LongInt; bActivated: Boolean; lContext: Longint); stdcall;
procedure FreeDLL;
procedure LoadDLL(PathToDll: WideString);
var
DllLoaded : Boolean = False;
/// Initializes the DirectOutput library.
/// <param name="wszAppName">A null-terminated wide character string that specifies the name of the application.</param>
/// returns:
/// S_OK: The call completed successfully.
/// E_OUTOFMEMORY: Insufficient memory to complete the request.
/// E_INVALIDARG: The argument is invalid. (According to Saitek. Not sure what would cause this in practice.)
/// E_HANDLE: The DirectOutputManager process could not be found.
/// This function must be called before calling any others. Call this function when you want to initialize the DirectOutput library.
DirectOutput_Initialize : function(const wszAppName: PWideString): HRESULT cdecl stdcall;
/// Cleans up the DirectOutput library.
/// returns
/// S_OK: The call completed successfully.
/// E_HANDLE: DirectOutput was not initialized or was already deinitialized.
/// This function must be called before termination. Call this function to clean up any resources allocated by DirectOutput_Initialize.
DirectOutput_Deinitialize : function(): HRESULT cdecl stdcall;
/// Registers a callback function to be called when a device is added or removed.
/// <param name="pfnCb">A pointer to the callback function, to be called whenever a device is added or removed.</param>
/// <param name="pCtxt">An application supplied context pointer that will be passed to the callback function.</param>
/// returns:
/// S_OK: The call completed successfully.
/// E_HANDLE: DirectOutput was not initialized.
/// Passing a NULL function pointer will disable the callback.
DirectOutput_RegisterDeviceChangeCallback : function (pfnCb: PFN_DIRECTOUTPUT_DEVICE_CALLBACK; pCtxt: LongInt): HRESULT cdecl stdcall;
/// Enumerates all currently attached DirectOutput devices.
/// returns:
/// S_OK: The call completed successfully.
/// E_HANDLE: DirectOutput was not initialized.
/// Call this third when using the Saitek SDK; it must be called after registering a device change callback via RegisterDeviceChange().
DirectOutput_Enumerate : function(): HRESULT cdecl stdcall;
/// Registers a callback with a device, that gets called whenever a "Soft Button" is pressed or released.
/// <param name="hDevice">A handle to a device.</param>
/// <param name="lButtons">A pointer to the callback function to be called whenever a "Soft Button" is pressed or released.</param>
/// <param name="lContext">An application supplied context pointer that will be passed to the callback function.</param>
/// returns:
/// S_OK: The call completed successfully.
/// E_HANDLE: The device handle specified is invalid.
/// Passing a NULL function pointer will disable the callback.
DirectOutput_RegisterSoftButtonChangeCallback : function (hDevice: LongInt; pfnCb: PFN_DIRECTOUTPUT_SOFTBUTTON_CALLBACK;
pCtxt: Longint): HRESULT cdecl stdcall;
/// Registers a callback with a device, that gets called whenever the active page is changed.
/// <param name="hDevice">A handle to a device</param>
/// <param name="pfnCb">A pointer to the callback function to be called whenever the active page is changed.</param>
/// <param name="pCtxt">An application supplied context pointer that will be passed to the callback function.</param>
/// returns:
/// S_OK: The call completed successfully.
/// E_HANDLE: The device handle specified is invalid.
DirectOutput_RegisterPageChangeCallback : function (hDevice: LongInt; pfnCb: PFN_DIRECTOUTPUT_PAGE_CALLBACK;
pCtxt: LongInt): HRESULT cdecl stdcall;
/// Adds a page to the specified device.
/// <param name="hDevice">A handle to a device.</param>
/// <param name="dwPage">A numeric identifier of a page. Usually this is the 0 based number of the page.</param>
/// <param name="wszValue">A string that specifies the name of this page.</param>
/// <param name="bSetAsActive">If this is true, then this page will become the active page. If false, this page will not change the active page.</param>
/// returns:
/// S_OK: The call completed successfully.
/// E_OUTOFMEMORY: Insufficient memory to complete the request.
/// E_INVALIDARG: The dwPage parameter already exists.
/// E_HANDLE: The device handle specified is invalid.
/// Only one page per application should have bSetActive set to true.
/// The driver-defined default page is 0; adding another page 0 will overwrite the default page.
DirectOutput_AddPage : function(hDevice: LongInt; dwPage: LongInt;
wszValue: PWideString; bSetAsActive: Boolean): HRESULT cdecl stdcall;
/// Removes a page.
/// <param name="hDevice">A handle to a device.</param>
/// <param name="dwPage">A numeric identifier of a page. Usually this is the 0 based number of the page.</param>
/// returns:
/// S_OK: The call completed successfully.
/// E_INVALIDARG: The dwPage argument does not reference a valid page id.
/// E_HANDLE: The device handle specified is invalid.
DirectOutput_RemovePage : function(hDevice: LongInt; dwPage: Longint): HRESULT cdecl stdcall;
/// Sets the state of a given LED indicator.
/// <param name="hDevice">A handle to a device.</param>
/// <param name="dwPage">A numeric identifier of a page. Usually this is the 0 based number of the page.</param>
/// <param name="dwIndex">A numeric identifier of the LED. Refer to the data sheet for each device to determine what LEDs are present.</param>
/// <param name="dwValue">The numeric value of a given state of a LED. For the x52 Pro, 0 is off and 1 is on.</param>
/// returns:
/// S_OK: The call completes successfully.
/// E_INVALIDARG: The dwPage argument does not reference a valid page id, or the dwLed argument does not specifiy a valid LED id.
/// E_HANDLE: The device handle specified is invalid.
/// To make a button's LED appear amber, enable both the Red and Yellow LEDs for that button.
DirectOutput_SetLed : function(hDevice: LongInt; dwPage: Longint; dwIndex: Longint; dwValue: Longint): HRESULT cdecl stdcall;
/// Sets text strings on the MFD.
/// <param name="hDevice">A handle to a device.</param>
/// <param name="dwPage">A numeric identifier of a page. Usually this is the 0 based number of the page.</param>
/// <param name="dwIndex">A numeric identifier of the string. Refer to the data sheet for each device to determine what strings are present.</param>
/// <param name="cchValue">The number of wide characters in the string.</param>
/// <param name="wszValue">A null-terminated wide character string that specifies the value to display. Providing a null pointer will clear the string.</param>
/// returns:
/// S_OK: The call completed successfully.
/// E_INVALIDARG: The dwPage argument does not reference a valid page id, or the dwString argument does not reference a valid string id.
/// E_OUTOFMEMORY: Insufficient memory to complete the request.
/// E_HANDLE: The device handle specified is invalid.
/// AddPage() needs to be called before a string can be displayed.
/// The x52 Pro has only 3 lines/page, and any string longer than 16 characters will automatically scroll.
DirectOutput_SetString : function(hDevice, dwPage, dwIndex, cchValue: Longint; wszValue: PWideString): HRESULT cdecl stdcall;
// pGdDevice & pGdInstance are pointers to a GUID structure:
{ The LPGUID structure represents a long pointer to a GUID.
typedef struct _GUID
ULONG Data1;
USHORT Data2;
USHORT Data3;
UCHAR Data4[8]; }
DirectOutput_GetDeviceType: function(hDevice: LongInt; pGdDevice: pointer): HRESULT cdecl stdcall;
DirectOutput_GetDeviceInstance: function(hDevice: LongInt; pGdInstance: pointer): HRESULT cdecl stdcall;
// not implemented:
// DirectOutput_SetImage: function(var hDevice: IN VOID; dwPage: IN Longint; dwIndex: IN Longint;
// cbValue: IN Longint; const pbValue: PIN UNSIGNED CHAR): HRESULT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
// DirectOutput_SetProfile: function(var hDevice: IN VOID; cchFilename: IN Longint;
// const wszFilename: PIN WCHAR_T): HRESULT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
implementation
uses main;
var
SaveExit: pointer;
DLLHandle: THandle;
procedure UnloadLibrary; far;
begin
ExitProc := SaveExit;
FreeLibrary(DLLHandle);
end {NewExit};
procedure FreeDLL;
begin
if DLLLoaded then
begin
UnloadLibrary();
DLLLoaded:=False;
end;
end;
procedure LoadDLL(PathToDll: WideString);
begin
if DLLLoaded then Exit;
DLLHandle := LoadLibrary(PWideChar(PathToDll));
if DLLHandle >= 32 then
begin
DLLLoaded := True;
SaveExit := ExitProc;
ExitProc := @UnloadLibrary;
@DirectOutput_Initialize := GetProcAddress(DLLHandle,'DirectOutput_Initialize');
Assert(@DirectOutput_Initialize <> nil);
@DirectOutput_Deinitialize := GetProcAddress(DLLHandle,'DirectOutput_Deinitialize');
Assert(@DirectOutput_Deinitialize <> nil);
@DirectOutput_RegisterDeviceChangeCallback := GetProcAddress(DLLHandle,'DirectOutput_RegisterDeviceChangeCallback');
Assert(@DirectOutput_RegisterDeviceChangeCallback <> nil);
@DirectOutput_Enumerate := GetProcAddress(DLLHandle,'DirectOutput_Enumerate');
Assert(@DirectOutput_Enumerate <> nil);
@DirectOutput_RegisterSoftButtonChangeCallback := GetProcAddress(DLLHandle,'DirectOutput_RegisterSoftButtonChangeCallback');
Assert(@DirectOutput_RegisterSoftButtonChangeCallback <> nil);
@DirectOutput_RegisterPageChangeCallback := GetProcAddress(DLLHandle,'DirectOutput_RegisterPageChangeCallback');
Assert(@DirectOutput_RegisterPageChangeCallback <> nil);
@DirectOutput_AddPage := GetProcAddress(DLLHandle,'DirectOutput_AddPage');
Assert(@DirectOutput_AddPage <> nil);
@DirectOutput_RemovePage := GetProcAddress(DLLHandle,'DirectOutput_RemovePage');
Assert(@DirectOutput_RemovePage <> nil);
@DirectOutput_SetLed := GetProcAddress(DLLHandle,'DirectOutput_SetLed');
Assert(@DirectOutput_SetLed <> nil);
@DirectOutput_SetString := GetProcAddress(DLLHandle,'DirectOutput_SetString');
Assert(@DirectOutput_SetString <> nil);
@DirectOutput_GetDeviceType := GetProcAddress(DLLHandle,'DirectOutput_GetDeviceType');
Assert(@DirectOutput_GetDeviceType <> nil);
@DirectOutput_GetDeviceInstance := GetProcAddress(DLLHandle,'DirectOutput_GetDeviceInstance');
Assert(@DirectOutput_GetDeviceInstance <> nil);
// @DirectOutput_SetImage := GetProcAddress(DLLHandle,'DirectOutput_SetImage');
// Assert(@DirectOutput_SetImage <> nil);
// @DirectOutput_SetProfile := GetProcAddress(DLLHandle,'DirectOutput_SetProfile');
// Assert(@DirectOutput_SetProfile <> nil);
end
else
begin
DLLLoaded := False;
{ Error: DIRECTOUTPUT.DLL could not be loaded !! }
Form1.Memo1.Lines.add('Error loading DirectOutput.dll, error code: '+InttoStr(GetLastError));
end;
end;
begin
// LoadDLL; // this is called from the main app instead after letting the user to set the path
end.
|
unit ltr42api;
interface
uses SysUtils, ltrapitypes, ltrapidefine, ltrapi;
const
// Коды ошибок
LTR42_NO_ERR =0;
LTR42_ERR_WRONG_MODULE_DESCR =-8001;
LTR42_ERR_CANT_OPEN =-8002;
LTR42_ERR_INVALID_CRATE_SN =-8003;
LTR42_ERR_INVALID_SLOT_NUM =-8004;
LTR42_ERR_CANT_SEND_COMMAND =-8005;
LTR42_ERR_CANT_RESET_MODULE =-8006;
LTR42_ERR_MODULE_NO_RESPONCE =-8007;
LTR42_ERR_CANT_SEND_DATA =-8008;
LTR42_ERR_CANT_CONFIG =-8009;
LTR42_ERR_CANT_LAUNCH_SEC_MARK =-8010;
LTR42_ERR_CANT_STOP_SEC_MARK =-8011;
LTR42_ERR_CANT_LAUNCH_START_MARK =-8012;
LTR42_ERR_DATA_TRANSMISSON_ERROR =-8013;
LTR42_ERR_LESS_WORDS_RECEIVED =-8014;
LTR42_ERR_PARITY_TO_MODULE =-8015;
LTR42_ERR_PARITY_FROM_MODULE =-8016;
LTR42_ERR_WRONG_SECOND_MARK_CONF =-8017;
LTR42_ERR_WRONG_START_MARK_CONF =-8018;
LTR42_ERR_CANT_READ_DATA =-8019;
LTR42_ERR_CANT_WRITE_EEPROM =-8020;
LTR42_ERR_CANT_READ_EEPROM =-8021;
LTR42_ERR_WRONG_EEPROM_ADDR =-8022;
LTR42_ERR_CANT_READ_CONF_REC =-8023;
LTR42_ERR_WRONG_CONF_REC =-8024;
LTR42_MARK_MODE_INTERNAL = 0;
LTR42_MARK_MODE_MASTER = 1;
LTR42_MARK_MODE_EXTERNAL = 2;
LTR42_EEPROM_SIZE = 512;
type
{$A4}
// Структура описания модуля
TINFO_LTR42 = record
Name :array[0..15]of AnsiChar;
Serial:array[0..23]of AnsiChar;
FirmwareVersion:array[0..7]of AnsiChar;// Версия БИОСа
FirmwareDate :array[0..15]of AnsiChar; // Дата создания данной версии БИОСа
end;
pTINFO_LTR42 = ^TINFO_LTR42;
TLTR42_Marks = record
SecondMark_Mode:integer; // Режим меток. 0 - внутр., 1-внутр.+выход, 2-внешн
StartMark_Mode:integer; //
end;
TLTR42 = record
Channel:TLTR;
size:integer; // размер структуры
AckEna:boolean;
Marks:TLTR42_Marks; // Структура для работы с временными метками
ModuleInfo:TINFO_LTR42;
end;
pTLTR42=^TLTR42;// Структура описания модуля
{$A+}
Function LTR42_Init (module:pTLTR42):Integer; {$I ltrapi_callconvention};
Function LTR42_Open (module:pTLTR42; net_addr:LongWord;net_port:WORD; crate_snCHAR:Pointer; slot_num:integer):Integer; {$I ltrapi_callconvention};
Function LTR42_Close (module:pTLTR42):Integer; {$I ltrapi_callconvention};
Function LTR42_WritePort (module:pTLTR42;OutputData:LongWord):Integer; {$I ltrapi_callconvention};
Function LTR42_WriteArray (module:pTLTR42; OutputArrayDWORD:Pointer; ArraySize:byte):Integer; {$I ltrapi_callconvention};
Function LTR42_Config (module:pTLTR42):Integer; {$I ltrapi_callconvention};
Function LTR42_StartSecondMark (module:pTLTR42):Integer; {$I ltrapi_callconvention};
Function LTR42_StopSecondMark (module:pTLTR42):Integer; {$I ltrapi_callconvention};
Function LTR42_GetErrorString (err:integer):string; {$I ltrapi_callconvention};
Function LTR42_MakeStartMark (module:pTLTR42):Integer; {$I ltrapi_callconvention};
Function LTR42_WriteEEPROM (module:pTLTR42; Address:integer;val:byte):Integer; {$I ltrapi_callconvention};
Function LTR42_ReadEEPROM (module:pTLTR42;Address:integer;valBYTE:Pointer):Integer; {$I ltrapi_callconvention};
Function LTR42_IsOpened (module:pTLTR42):Integer; {$I ltrapi_callconvention};
implementation
Function LTR42_Init (module:pTLTR42):Integer; {$I ltrapi_callconvention}; external 'ltr42api';
Function LTR42_Open (module:pTLTR42; net_addr:LongWord;net_port:WORD; crate_snCHAR:Pointer; slot_num:integer):Integer; {$I ltrapi_callconvention}; external 'ltr42api';
Function LTR42_Close (module:pTLTR42):Integer; {$I ltrapi_callconvention}; external 'ltr42api';
Function LTR42_WritePort (module:pTLTR42;OutputData:LongWord):Integer; {$I ltrapi_callconvention}; external 'ltr42api';
Function LTR42_WriteArray (module:pTLTR42; OutputArrayDWORD:Pointer; ArraySize:byte):Integer; {$I ltrapi_callconvention}; external 'ltr42api';
Function LTR42_Config (module:pTLTR42):Integer; {$I ltrapi_callconvention}; external 'ltr42api';
Function LTR42_StartSecondMark (module:pTLTR42):Integer; {$I ltrapi_callconvention}; external 'ltr42api';
Function LTR42_StopSecondMark (module:pTLTR42):Integer; {$I ltrapi_callconvention}; external 'ltr42api';
Function LTR42_MakeStartMark (module:pTLTR42):Integer; {$I ltrapi_callconvention}; external 'ltr42api';
Function LTR42_WriteEEPROM (module:pTLTR42; Address:integer;val:byte):Integer; {$I ltrapi_callconvention}; external 'ltr42api';
Function LTR42_ReadEEPROM (module:pTLTR42;Address:integer;valBYTE:Pointer):Integer; {$I ltrapi_callconvention}; external 'ltr42api';
Function LTR42_IsOpened (module:pTLTR42):Integer; {$I ltrapi_callconvention}; external 'ltr42api';
Function _get_err_str(err : integer) : PAnsiChar; {$I ltrapi_callconvention}; external 'ltr42api' name 'LTR42_GetErrorString';
Function LTR42_GetErrorString(err: Integer) : string; {$I ltrapi_callconvention};
begin
LTR42_GetErrorString:=string(_get_err_str(err));
end;
end.
|
unit UnLembrete;
{Verificado
-.edit;
}
interface
uses
Classes, UnDados, Forms, SQLExpr, Tabela,db;
type
TRBFuncoesLembrete = class
private
Cadastro,
Tabela,
Aux: TSQL;
procedure ApagaDLembreteItem(VpaSeqLembrete: Integer);
procedure CarDUsuariosLembrete(VpaSeqLembrete: Integer; VpaDLembreteCorpo: TRBDLembreteCorpo);
function GravaDLembreteItem(VpaDLembreteCorpo: TRBDLembreteCorpo): String;
function RSeqLembreteDisponivel: Integer;
public
constructor Cria(VpaBaseDados : TSQLConnection);
destructor Destroy; override;
procedure CarDLembrete(VpaSeqLembrete: Integer; VpaDLembreteCorpo: TRBDLembreteCorpo);
procedure CarDUsuariosSistema(VpaUsuarios: TList; VpaCodGrupo: Integer = 0);
function GravaDLembrete(VpaDLembreteCorpo: TRBDLembreteCorpo): String;
function UsuarioLeuLembrete(VpaSeqLembrete, VpaCodUsuario: Integer): String;
end;
implementation
uses
FunSql, FunData, SysUtils, FunObjeto, Constantes;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
TRBFuncoesLembrete
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
constructor TRBFuncoesLembrete.Cria(VpaBaseDados : TSQLConnection);
begin
inherited Create;
Cadastro:= TSQL.Create(Application);
Cadastro.ASQlConnection := VpaBaseDados;
Tabela:= TSQL.Create(Application);
Tabela.ASqlConnection := VpaBaseDados;
Aux:= TSQL.Create(Application);
Aux.ASqlConnection := VpaBaseDados;
//Cadastro.RequestLive:= True;
end;
{******************************************************************************}
destructor TRBFuncoesLembrete.Destroy;
begin
Cadastro.Close;
Tabela.Close;
Aux.Close;
Cadastro.Free;
Tabela.Free;
Aux.Free;
inherited Destroy;
end;
{******************************************************************************}
procedure TRBFuncoesLembrete.ApagaDLembreteItem(VpaSeqLembrete: Integer);
begin
ExecutaComandoSql(Tabela,'DELETE FROM LEMBRETEUSUARIO'+
' WHERE SEQLEMBRETE = '+IntToStr(VpaSeqLembrete));
Tabela.Close;
end;
{******************************************************************************}
function TRBFuncoesLembrete.RSeqLembreteDisponivel: Integer;
begin
AdicionaSQLAbreTabela(Aux,'SELECT MAX(SEQLEMBRETE) ULTIMO FROM LEMBRETECORPO');
Result:= Aux.FieldByName('ULTIMO').AsInteger + 1;
Aux.Close;
end;
{******************************************************************************}
function TRBFuncoesLembrete.GravaDLembrete(VpaDLembreteCorpo: TRBDLembreteCorpo): String;
begin
Result:= '';
ApagaDLembreteItem(VpaDLembreteCorpo.SeqLembrete);
AdicionaSQLAbreTabela(Cadastro,'SELECT * FROM LEMBRETECORPO'+
' WHERE SEQLEMBRETE = '+IntToStr(VpaDLembreteCorpo.SeqLembrete));
if Cadastro.Eof then
Cadastro.Insert
else
Cadastro.Edit;
Cadastro.FieldByName('DATLEMBRETE').AsDateTime:= VpaDLembreteCorpo.DatLembrete;
Cadastro.FieldByName('CODUSUARIO').AsInteger:= VpaDLembreteCorpo.CodUsuario;
Cadastro.FieldByName('INDAGENDAR').AsString:= VpaDLembreteCorpo.IndAgendar;
if VpaDLembreteCorpo.DatAgenda > MontaData(1,1,1900) then
Cadastro.FieldByName('DATAGENDA').AsDateTime:= VpaDLembreteCorpo.DatAgenda
else
Cadastro.FieldByName('DATAGENDA').Clear;
Cadastro.FieldByName('INDTODOS').AsString:= VpaDLembreteCorpo.IndTodos;
Cadastro.FieldByName('DESTITULO').AsString:= VpaDLembreteCorpo.DesTitulo;
Cadastro.FieldByName('DESLEMBRETE').AsString:= VpaDLembreteCorpo.DesLembrete;
if Cadastro.State = dsInsert then
VpaDLembreteCorpo.SeqLembrete:= RSeqLembreteDisponivel;
Cadastro.FieldByName('SEQLEMBRETE').AsInteger:= VpaDLembreteCorpo.SeqLembrete;
try
Cadastro.Post;
if Result = '' then
Result:= GravaDLembreteItem(VpaDLembreteCorpo);
except
on E:Exception do
Result:= 'ERRO AO GRAVAR O LEMBRETE!!!'#13+E.Message;
end;
Cadastro.Close;
end;
{******************************************************************************}
function TRBFuncoesLembrete.GravaDLembreteItem(VpaDLembreteCorpo: TRBDLembreteCorpo): String;
var
VpfLaco: Integer;
VpfDLembreteItem: TRBDLembreteItem;
begin
Result:= '';
AdicionaSQLAbreTabela(Cadastro,'SELECT * FROM LEMBRETEUSUARIO');
for VpfLaco:= 0 to VpaDLembreteCorpo.Usuarios.Count -1 do
begin
VpfDLembreteItem:= TRBDLembreteItem(VpaDLembreteCorpo.Usuarios.Items[VpfLaco]);
if VpfDLembreteItem.CodUsuario <> 0 then
begin
Cadastro.Insert;
Cadastro.FieldByName('SEQLEMBRETE').AsInteger:= VpaDLembreteCorpo.SeqLembrete;
Cadastro.FieldByName('CODUSUARIO').AsInteger:= VpfDLembreteItem.CodUsuario;
try
Cadastro.Post;
except
on E:Exception do
Result:= 'ERRO AO GRAVAR OS USUARIOS DO LEMBRETE!!!'#13+E.Message;
end;
if Result <> '' then
Break;
end;
end;
Cadastro.Close;
end;
{******************************************************************************}
function TRBFuncoesLembrete.UsuarioLeuLembrete(VpaSeqLembrete, VpaCodUsuario: Integer): String;
begin
Result:= '';
AdicionaSQLAbreTabela(Cadastro,'SELECT * FROM LEMBRETEITEM'+
' WHERE SEQLEMBRETE = '+IntToStr(VpaSeqLembrete)+
' AND CODUSUARIO = '+IntToStr(VpaCodUsuario));
if Cadastro.Eof then
Cadastro.Insert
else
Cadastro.Edit;
Cadastro.FieldByName('SEQLEMBRETE').AsInteger:= VpaSeqLembrete;
Cadastro.FieldByName('CODUSUARIO').AsInteger:= VpaCodUsuario;
Cadastro.FieldByName('INDLIDO').AsString:= 'S';
Cadastro.FieldByName('QTDVISUALIZACAO').AsInteger:= Cadastro.FieldByName('QTDVISUALIZACAO').AsInteger+1;
try
Cadastro.Post;
except
on E:Exception do
Result:= 'ERRO AO ATUALIZAR A TABELA DE LEITURA DOS LEMBRETES'#13+E.Message;
end;
Cadastro.Close;
end;
{******************************************************************************}
procedure TRBFuncoesLembrete.CarDLembrete(VpaSeqLembrete: Integer; VpaDLembreteCorpo: TRBDLembreteCorpo);
begin
AdicionaSQLAbreTabela(Tabela,'SELECT * FROM LEMBRETECORPO'+
' WHERE SEQLEMBRETE = '+IntToStr(VpaSeqLembrete));
VpaDLembreteCorpo.SeqLembrete:= Tabela.FieldByName('SEQLEMBRETE').AsInteger;
VpaDLembreteCorpo.CodUsuario:= Tabela.FieldByName('CODUSUARIO').AsInteger;
VpaDLembreteCorpo.DatLembrete:= Tabela.FieldByName('DATLEMBRETE').AsDateTime;
VpaDLembreteCorpo.DatAgenda:= Tabela.FieldByName('DATAGENDA').AsDateTime;
VpaDLembreteCorpo.IndAgendar:= Tabela.FieldByName('INDAGENDAR').AsString;
VpaDLembreteCorpo.IndTodos:= Tabela.FieldByName('INDTODOS').AsString;
VpaDLembreteCorpo.DesTitulo:= Tabela.FieldByName('DESTITULO').AsString;
VpaDLembreteCorpo.DesLembrete:= Tabela.FieldByName('DESLEMBRETE').AsString;
Tabela.Close;
CarDUsuariosLembrete(VpaSeqLembrete, VpaDLembreteCorpo);
end;
{******************************************************************************}
procedure TRBFuncoesLembrete.CarDUsuariosLembrete(VpaSeqLembrete: Integer; VpaDLembreteCorpo: TRBDLembreteCorpo);
var
VpfDLembreteItem: TRBDLembreteItem;
begin
AdicionaSQLAbreTabela(Tabela,'SELECT * FROM LEMBRETEUSUARIO'+
' WHERE SEQLEMBRETE = '+IntToStr(VpaSeqLembrete));
while not Tabela.Eof do
begin
VpfDLembreteItem:= VpaDLembreteCorpo.AddUsuario;
VpfDLembreteItem.CodUsuario:= Tabela.FieldByName('CODUSUARIO').AsInteger;
Tabela.Next;
end;
Tabela.Close;
end;
{******************************************************************************}
procedure TRBFuncoesLembrete.CarDUsuariosSistema(VpaUsuarios: TList; VpaCodGrupo: Integer = 0);
var
VpfDUsuario: TRBDLembreteItem;
begin
FreeTObjectsList(VpaUsuarios);
Tabela.Close;
Tabela.SQL.Clear;
Tabela.SQL.Add('SELECT * FROM CADUSUARIOS');
Tabela.SQL.Add(' WHERE C_USU_ATI = ''S''');
if VpaCodGrupo <> 0 then
Tabela.SQL.Add(' AND I_COD_GRU = '+IntToStr(VpaCodGrupo));
Tabela.SQL.Add(' AND I_EMP_FIL = '+IntToStr(Varia.CodigoEmpFil));
Tabela.SQL.Add(' ORDER BY C_NOM_USU');
Tabela.Open;
while not Tabela.Eof do
begin
VpfDUsuario:= TRBDLembreteItem.Cria(False);
VpaUsuarios.Add(VpfDUsuario);
VpfDUsuario.CodUsuario:= Tabela.FieldByName('I_COD_USU').AsInteger;
VpfDUsuario.NomUsuario:= Tabela.FieldByName('C_NOM_USU').AsString;
Tabela.Next;
end;
Tabela.Close;
end;
end.
|
unit adot.VCL.MouseWheelRedirector;
(*******************************************************************************
Info : Enhanced processing of mouse wheel messages (app-wide).
Author : Andrei Galatyn
Date : 10.07.2015
Application-wide mouse wheel redirector:
- Redirects mouse wheel messages to control at mouse position (Delphi sends such messages to focused control).
- If control doesn't process wheel message, then redirect it to parent (up to main form).
- Add mouse wheel support for TScrollbox/TcxScrollBox.
- Direct mouse wheel messages to combo box control only if it has focus AND pointed by mouse at same time.
- If there is no control pointed by mouse, then scroll focused control instead (but not ComboBox).
- If MDI main form is pointed by mouse, then focused control/form should be scrolled.
To enable mouse wheel redirector, include the unit to project.
*******************************************************************************)
{$DEFINE MWR_DevExpress}
interface
implementation
uses
{$IFDEF MWR_DevExpress}
cxDropDownEdit, cxGridCustomView, cxControls, cxScrollBox,
{$ENDIF}
System.SysUtils, Winapi.Windows, Winapi.Messages, Vcl.Controls, Vcl.Forms,
System.Math, Vcl.StdCtrls, Vcl.AppEvnts, System.Classes;
type
{$IFDEF MWR_DevExpress}
TcxControlAccess = class(TcxControl);
{$ENDIF}
TWinControlAccess = class(TWinControl);
TMouseWheelRedirector = class
protected
class var
FInstance: TMouseWheelRedirector;
var
Events: TApplicationEvents;
procedure AppOnMessage(var Msg: TMsg; var Handled: Boolean);
class function VScrollControl(C: TWinControl; Down: Boolean; LineCount: integer): Boolean; static;
public
constructor Create;
destructor Destroy; override;
end;
function FindSubcontrolAtPos(AControl: TControl; AScreenPos, AClientPos: TPoint): TControl;
var
i: Integer;
C: TControl;
begin
Result := nil;
C := AControl;
if (C=nil) or not C.Visible or not TRect.Create(C.Left, C.Top, C.Left+C.Width, C.Top+C.Height).Contains(AClientPos) then
Exit;
Result := AControl;
if AControl is TWinControl then
for i := 0 to TWinControl(AControl).ControlCount-1 do
begin
C := FindSubcontrolAtPos(TWinControl(AControl).Controls[i], AScreenPos, AControl.ScreenToClient(AScreenPos));
if C<>nil then
Result := C;
end;
end;
function FindControlAtPos(AScreenPos: TPoint): TControl;
var
i: Integer;
f,m: TForm;
p: TPoint;
r: TRect;
begin
Result := nil;
for i := Screen.FormCount-1 downto 0 do
begin
f := Screen.Forms[i];
if f.Visible and (f.Parent=nil) and (f.FormStyle<>fsMDIChild) and
TRect.Create(f.Left, f.Top, f.Left+f.Width, f.Top+f.Height).Contains(AScreenPos)
then
Result := f;
end;
Result := FindSubcontrolAtPos(Result, AScreenPos, AScreenPos);
if (Result is TForm) and (TForm(Result).ClientHandle<>0) then
begin
WinAPI.Windows.GetWindowRect(TForm(Result).ClientHandle, r);
p := TPoint.Create(AScreenPos.X-r.Left, AScreenPos.Y-r.Top);
m := nil;
for i := TForm(Result).MDIChildCount-1 downto 0 do
begin
f := TForm(Result).MDIChildren[i];
if TRect.Create(f.Left, f.Top, f.Left+f.Width, f.Top+f.Height).Contains(p) then
m := f;
end;
if m<>nil then
Result := FindSubcontrolAtPos(m, AScreenPos, p);
end;
end;
function VertScrollBarVisible(WindowHandle: THandle): Boolean;
begin
Result := (GetWindowlong(WindowHandle, GWL_STYLE) AND WS_VSCROLL) <> 0
end;
{$IFDEF MWR_DevExpress}
function cxGridIsFocused: Boolean;
var
C: TWinControl;
begin
C := Screen.ActiveControl;
while C<>nil do
begin
if C is TcxGridSite then
begin
result := True;
Exit;
end;
C := C.Parent;
end;
result := False;
end;
function cxScrollGrid(ASite: TcxGridSite; ADelta: integer): Boolean;
var
i,j,p: Integer;
begin
j := ASite.VScrollBar.Position;
for i := 0 to 2 do
begin
p := ASite.VScrollBar.Position;
if ADelta>0 then
TcxControlAccess(ASite).Scroll(sbVertical, scLineUp, p)
else
TcxControlAccess(ASite).Scroll(sbVertical, scLineDown, p);
end;
result := j<>ASite.VScrollBar.Position;
end;
{$ENDIF}
{ TMouseWheelRedirector }
{
j := SetScrollInfo(TcxCustomComboBox(C).Handle, ???
1. SetScrollPos changes position of bar, but content doesn't scroll (msg processed by bar, not by control)
SetScrollPos(TWinControl(C).Handle, SB_VERT, i-Delta, True);
2. Normally SendMessage works fine, but cxGrid installs message hook (seems so).
When grid is focused, we can't deliver the message to the recipient (it is hooked&processed by grid instead).
SendMessage(TWinControl(C).Handle, Msg.Message, Msg.wParam, Msg.lParam);
3. Same problem as with direct call of WndProc - when cxGrid is focused, destination control
doesn't process the message (when grid is not focused everything is ok).
TWinControlAccess(C).WndProc(M);
4. We don't have access to WMVScroll method ("private" section).
TWinControlAccess(C).WMVScroll(
}
class function TMouseWheelRedirector.VScrollControl(C: TWinControl;
Down: Boolean; LineCount: integer): Boolean;
var
Msg: TWMScroll;
VPos: Integer;
begin
FillChar(Msg, SizeOf(Msg), 0);
Msg.Msg := WM_VSCROLL;
Msg.ScrollCode := IfThen(Down, SB_LINEDOWN, SB_LINEUP);
VPos := GetScrollPos(C.Handle, SB_VERT);
while LineCount>0 do
begin
SendMessage(C.Handle, WM_VSCROLL, TMessage(Msg).WParam, TMessage(Msg).LParam);
Dec(LineCount);
end;
Result := VPos<>GetScrollPos(C.Handle, SB_VERT);
end;
procedure TMouseWheelRedirector.AppOnMessage(var Msg: TMsg;
var Handled: Boolean);
var
i,Delta: Integer;
M: TMessage;
C: TControl;
AutoPointed: Boolean;
begin
if (Msg.Message<>WM_MOUSEWHEEL) and (Msg.Message<>WM_MOUSEHWHEEL) then
Exit;
M.Msg := Msg.message;
M.WParam := Msg.wParam;
M.LParam := Msg.lParam;
M.Result := 0;
// TMSHMouseWheel differ from TWMMouseWheel in Delphi, but according to MSDN
// they are equal, so we use TWMMouseWheel for both Message types.
Delta := TWMMouseWheel(M).WheelDelta;
C := FindControlAtPos(TPoint.Create(TWMMouseWheel(M).XPos, TWMMouseWheel(M).YPos));
AutoPointed := False; // FindControlAtPos returns actual control pointed by mouse.
if (C=nil) or (C=Application.MainForm) and (Application.MainForm.FormStyle=fsMDIForm) then
begin
C := Screen.ActiveControl;
AutoPointed := True; // If there is no pointed control, we use focused instead.
end;
if C=nil then
Exit;
repeat
if (C is TWinControl) and C.Enabled and C.Visible then
if False then begin end
// TScrollBox doesn't support mouse wheel (XE8), we have to workaround it.
// We can use general VScrollControl function, but it is better to
// use specific method and scroll pos according to Delta.
else
if (C is TScrollingWinControl) and TScrollingWinControl(C).VertScrollbar.Visible then
begin
i := TScrollingWinControl(C).VertScrollbar.Position;
TScrollingWinControl(C).VertScrollbar.Position := TScrollingWinControl(C).VertScrollbar.Position - Delta;
Handled := i<>TScrollingWinControl(C).VertScrollbar.Position;
end
{$IFDEF MWR_DevExpress}
else
if (C is TcxCustomScrollBox) and TcxCustomScrollBox(C).VertScrollbar.Visible then
begin
i := TcxCustomScrollBox(C).VertScrollbar.Position;
TcxCustomScrollBox(C).VertScrollbar.Position := TcxCustomScrollBox(C).VertScrollbar.Position - Delta;
Handled := i<>TcxCustomScrollBox(C).VertScrollbar.Position;
end
{$ENDIF}
// General VScrollControl function works fine for TMemo/TcxMemo.
// TcxMemo will be processed here too, because TcxCustomInnerMemo is
// inherited from TCustomMemo.
// else
// if C is TCustomMemo then
// begin
// i := SendMessage(TCustomMemo(C).Handle, EM_GETFIRSTVISIBLELINE, 0,0);
// SendMessage(TCustomMemo(C).Handle, EM_LINESCROLL, 0, -Sign(Delta)*3);
// Handled := i<>SendMessage(TCustomMemo(C).Handle, EM_GETFIRSTVISIBLELINE, 0,0);
// end
// TComboBox / TcxComboBox (they don't have scrollbar)
// It is dangerous to scroll combo by wheel, we allow it
// only if combo is focused and pointed by mouse at same time.
else
if not AutoPointed and TWinControl(C).Focused and (C is TCustomComboBox) then
begin
i := TCustomComboBox(C).ItemIndex;
SendMessage(TComboBox(C).Handle, Msg.Message, Msg.wParam, Msg.lParam);
Handled := i<>TCustomComboBox(C).ItemIndex;
end
{$IFDEF MWR_DevExpress}
else
if TWinControl(C).Focused and (C is TcxCustomComboBox) then
begin
i := TcxCustomComboBox(C).ItemIndex;
SendMessage(TcxCustomComboBox(C).Handle, Msg.Message, Msg.wParam, Msg.lParam);
Handled := i<>TcxCustomComboBox(C).ItemIndex;
end
else
if C is TcxGridSite then
Handled := cxScrollGrid(TcxGridSite(C), Delta)
{$ENDIF}
// Any scrollable WinControl (even if vertical scrollbar is not visible)
else
//if VertScrollBarVisible(TWinControl(C).Handle) then
Handled := VScrollControl(TWinControl(C), Delta<0, 3);
C := C.Parent;
until (C=nil) or Handled;
// If we didn't process the wheel message, then control should process it by default.
// Handled := Handled
// or (Screen.ActiveControl is TComboBox)
// {$IFDEF MWR_DevExpress}
// or (Screen.ActiveControl<>nil) and (Screen.ActiveControl.Parent is TcxComboBox)
// {$ENDIF}
// ;
// We have to disable default wheel processing for controls, because it is hard
// to eliminate all side effects. Another reason - if we don't support some
// component, we should know it as soons as possible.
Handled := True;
end;
constructor TMouseWheelRedirector.Create;
begin
Events := TApplicationEvents.Create(nil);
Events.OnMessage := AppOnMessage;
end;
destructor TMouseWheelRedirector.Destroy;
begin
FreeAndNil(Events);
inherited;
end;
initialization
TMouseWheelRedirector.FInstance := TMouseWheelRedirector.Create;
finalization
FreeAndNil(TMouseWheelRedirector.FInstance);
end. |
unit ReadingSQLUnit;
interface
uses
JoanModule,
TestClasses,Windows, Messages, Dialogs,
SysUtils, Generics.Collections, Classes, Contnrs;
type
TReadingSQL = class
function ReadingTextSelect(TestIndex: Integer): TObjectList<TReading>;
procedure ReadingTextInsert(Reading: TReading; TestIndex: Integer);
procedure ReadingTextUpdate(Reading: TReading; TestIndex: Integer);
procedure ReadingTextDelete(TestIndex, ExampleNumber: Integer);
procedure ReadingQuestionInsert(Question: TLRQuiz; ExampleIndex: Integer);
procedure ReadingQuestionUpdate(Question: TLRQuiz; QuizIndex: Integer);
procedure ReadingQuestionDelete(QuestionIndex: Integer);
end;
implementation
{ TReadingSQL }
procedure TReadingSQL.ReadingQuestionDelete(QuestionIndex: Integer);
begin
with Joan.JoanQuery do
begin
Close;
SQL.Clear;
SQL.Text :=
'DELETE FROM reading_example_quiz ' +
'WHERE quiz_idx = :questionindex;';
ParamByName('questionindex').AsInteger := QuestionIndex;
ExecSQL();
Close;
SQL.Clear;
SQL.Text := 'DELETE FROM quiz WHERE idx = :questionindex;';
ParamByName('questionindex').AsInteger := QuestionIndex;
ExecSQL();
end;
end;
procedure TReadingSQL.ReadingQuestionInsert(Question: TLRQuiz; ExampleIndex: Integer);
var
LastInsertID: Integer;
begin
with Joan.JoanQuery do
begin
Close;
SQL.Clear;
SQL.Text :=
'SELECT f_insert_quiz' +
'(:number, :question, :a, :b, :c, :d, :answer) AS last_insert_id';
ParamByName('number').AsInteger := Question.QuizNumber;
ParamByName('question').Asstring := Question.Quiz;
ParamByName('A').Asstring := Question.A;
ParamByName('B').Asstring := Question.B;
ParamByName('C').Asstring := Question.C;
ParamByName('D').Asstring := Question.D;
ParamByName('answer').Asstring := Question.Answer;
Open;
LastInsertID := FieldByName('last_insert_id').AsInteger;
Close;
SQL.Clear;
SQL.Text :=
'INSERT INTO reading_example_quiz ' +
'(reading_idx, quiz_idx) ' +
'VALUES ' +
'(:exampleidx, :quiz_idx)';
ParamByName('exampleidx').AsInteger := ExampleIndex;
ParamByName('quiz_idx').AsInteger := LastInsertID;
ExecSQL();
end;
end;
procedure TReadingSQL.ReadingQuestionUpdate(Question: TLRQuiz; QuizIndex: Integer);
begin
with Joan.JoanQuery do
begin
Close;
SQL.Clear;
SQL.Text :=
'UPDATE quiz SET ' +
'number = :quiznumber, question = :quiz, ' +
'A = :A, B = :B, C = :C, D = :D, answer = :answer ' +
'WHERE idx = :quizindex;';
ParamByName('quizindex').AsInteger := QuizIndex;
ParamByName('quiznumber').AsInteger := Question.QuizNumber;
ParamByName('quiz').Asstring := Question.Quiz;
ParamByName('A').Asstring := Question.A;
ParamByName('B').Asstring := Question.B;
ParamByName('C').Asstring := Question.C;
ParamByName('D').Asstring := Question.D;
ParamByName('answer').Asstring := Question.Answer;
ExecSQL();
end;
end;
procedure TReadingSQL.ReadingTextDelete(TestIndex, ExampleNumber: Integer);
var
ReadingIndex : Integer;
begin
Joan.JoanQuery.Close;
Joan.JoanQuery.SQL.Clear;
Joan.JoanQuery.SQL.Text :=
'SELECT idx FROM reading ' +
'WHERE (test_idx = :testindex) AND (example_seq = :examplenumber);';
Joan.JoanQuery.ParamByName('testindex').AsInteger := TestIndex;
Joan.JoanQuery.ParamByName('examplenumber').AsInteger := ExampleNumber;
Joan.JoanQuery.Open;
ReadingIndex := Joan.JoanQuery.FieldByName('idx').AsInteger;
Joan.JoanQuery.Close;
Joan.JoanQuery.SQL.Clear;
Joan.JoanQuery.SQL.Text :=
'DELETE FROM quiz ' +
'WHERE idx in ' +
'(SELECT quiz_idx FROM reading_example_quiz ' +
' WHERE reading_idx = :readingindex);';
Joan.JoanQuery.ParamByName('readingindex').AsInteger := ReadingIndex;
Joan.JoanQuery.ExecSQL();
Joan.JoanQuery.Close;
Joan.JoanQuery.SQL.Clear;
Joan.JoanQuery.SQL.Text :=
'DELETE FROM reading ' +
'WHERE (test_idx = :testindex) AND (example_seq = :examplenumber);';
Joan.JoanQuery.ParamByName('testindex').AsInteger := TestIndex;
Joan.JoanQuery.ParamByName('examplenumber').AsInteger := ExampleNumber;
Joan.JoanQuery.ExecSQL();
end;
procedure TReadingSQL.ReadingTextInsert(Reading: TReading; TestIndex: Integer);
begin
with Joan.JoanQuery do
begin
Close;
SQL.Clear;
SQL.Text :=
'INSERT INTO reading ' +
'(test_idx, example_seq, example_text) ' +
'VALUES ' +
'(:testindex, :examplenumber, :exampletext);';
ParamByName('testindex').Asinteger := TestIndex;
ParamByName('examplenumber').AsInteger := Reading.ExampleNumber;
ParamByName('exampletext').AsString := Reading.ExampleText;
ExecSQL();
end;
end;
function TReadingSQL.ReadingTextSelect(TestIndex: Integer): TObjectList<TReading>;
var
Reading: TReading;
I: Integer;
Quiz: TLRQuiz;
begin
Result := TObjectList<TReading>.Create;
Joan.JoanQuery.SQL.Clear;
Joan.JoanQuery.SQL.Text :=
'SELECT * FROM reading WHERE test_idx = :idx ORDER BY example_seq ';
Joan.JoanQuery.ParamByName('idx').AsInteger := TestIndex;
Joan.JoanQuery.Open;
while not Joan.JoanQuery.Eof do
begin
Reading := TReading.Create;
Reading.ExampleIdx := Joan.JoanQuery.FieldByName('idx').AsInteger;
Reading.ExampleNumber := Joan.JoanQuery.FieldByName('example_seq').AsInteger;
Reading.ExampleText := Joan.JoanQuery.FieldByName('example_text').AsString;
Result.Add(Reading);
Joan.JoanQuery.Next;
end;
for I := 0 to Result.Count - 1 do
begin
Joan.JoanQuery.SQL.Clear;
Joan.JoanQuery.SQL.Text :=
'SELECT t2.* FROM ' +
'(SELECT * FROM reading_example_quiz ' +
'WHERE reading_idx = :idx) t1 ' +
'INNER JOIN quiz t2 ' +
'ON t1.quiz_idx = t2.idx; ';
Joan.JoanQuery.ParamByName('idx').AsInteger := Result.Items[I].ExampleIdx;
Joan.JoanQuery.Open;
while not Joan.JoanQuery.Eof do
begin
Quiz := TLRQuiz.Create;
Quiz.QuizIdx := Joan.JoanQuery.FieldByName('idx').AsInteger;
Quiz.QuizNumber := Joan.JoanQuery.FieldByName('number').AsInteger;
Quiz.Quiz := Joan.JoanQuery.FieldByName('question').Asstring;
Quiz.A := Joan.JoanQuery.FieldByName('A').Asstring;
Quiz.B := Joan.JoanQuery.FieldByName('B').Asstring;
Quiz.C := Joan.JoanQuery.FieldByName('C').Asstring;
Quiz.D := Joan.JoanQuery.FieldByName('D').Asstring;
Quiz.Answer := Joan.JoanQuery.FieldByName('answer').Asstring;
Result.Items[I].QuizList.Add(Quiz);
Joan.JoanQuery.Next;
end;
end;
end;
procedure TReadingSQL.ReadingTextUpdate(Reading: TReading; TestIndex: Integer);
begin
with Joan.JoanQuery do
begin
Close;
SQL.Clear;
SQL.Text :=
'UPDATE reading SET ' +
'example_text = :exampletext ' +
'WHERE (test_idx = :testindex) and (example_seq = :examplenumber);';
ParamByName('testindex').Asinteger := TestIndex;
ParamByName('examplenumber').AsInteger := Reading.ExampleNumber;
ParamByName('exampletext').AsString := Reading.ExampleText;
ExecSQL();
end;
end;
end.
|
unit main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, SynMemo, SynHighlighterPHP, SynCompletion,
SynHighlighterHTML, SynHighlighterCss, Forms, Controls, Graphics, Dialogs,
ActnList, StdCtrls, ExtCtrls, AsyncProcess, ComCtrls;
const
NORMALIZE_MIN_CSS : String = 'https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.min.css';
JQUERY_MIN_JS : String = 'https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js' ;
JQUERY_UI_MIN_JS : String = 'https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js';
JQUERY_UI_CSS : String = 'https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css';
BOOTSTRAP_MIN_JS : String = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js';
BOOTSTRAP_MIN_CSS : String = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css';
MODERNIZR_MIN_JS : String = 'https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js';
LODASH_MIN_JS : String = 'https://cdnjs.cloudflare.com/ajax/libs/lodash-compat/3.9.3/lodash.min.js';
HTML5SHIV1_MIN_JS : String = 'https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.min.js';
HTML5SHIV2_MIN_JS : String = 'https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv-printshiv.min.js';
BACKBONE_MIN_JS : String = 'https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.1/backbone-min.js';
UNDERSCORE_MIN_JS : String = 'https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js';
PURE_MIN_CSS : String = 'http://yui.yahooapis.com/pure/0.6.0/pure-min.css';
SKELETON_MIN_CSS : String = 'https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css';
TOAST_MIN_CSS : String = 'https://cdnjs.cloudflare.com/ajax/libs/toast-css/1.0.0/grid.min.css';
REQUIRE_MIN_JS : String = 'https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.18/require.min.js';
// template engines
//Mustache.js
MUSTACHE_MIN_JS : String = 'https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.1.2/mustache.min.js';
// Nunjucks
NUNJUCKS_MIN_JS : String = 'https://mozilla.github.io/nunjucks/files/nunjucks.min.js';
// ANIMA.js
ANIMA_MIN_JS : String = 'https://cdnjs.cloudflare.com/ajax/libs/anima/0.4.0/anima.min.js';
// Transparency
TRANSPARENCY_MIN_JS : String = 'https://raw.github.com/leonidas/transparency/master/dist/transparency.min.js';
// velocity.js
VELOCITY_MIN_JS : String = 'https://cdnjs.cloudflare.com/ajax/libs/velocity/1.2.2/velocity.min.js';
//doT.js
DOT_MIN_JS : String = 'https://cdnjs.cloudflare.com/ajax/libs/dot/1.0.3/doT.min.js';
//dust.js (LinkedIn)
DUST_MIN_JS : String = 'https://cdnjs.cloudflare.com/ajax/libs/dustjs-linkedin/2.7.2/dust-full.min.js';
// ejs
EJS_MIN_JS : String = 'https://raw.githubusercontent.com/tj/ejs/master/ejs.min.js';
// Handlebars.js
HANDLEBARS_MIN_JS : array[0..1] of String =
('https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.3/handlebars.amd.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.3/handlebars.min.js'
);
//Hogan.js
HOGAN_MIN_JS : Array[0..1] of String =
(
'https://cdnjs.cloudflare.com/ajax/libs/hogan.js/3.0.2/hogan.js',
'https://cdnjs.cloudflare.com/ajax/libs/hogan.js/3.0.2/hogan.min.amd.js'
);
// ICanHaz.js
ICANHAZ_MIN_JS : String = 'https://cdnjs.cloudflare.com/ajax/libs/ICanHaz.js/0.10.3/ICanHaz.min.js';
// JADE
JADE_MIN_JS : String = 'https://cdnjs.cloudflare.com/ajax/libs/jade/1.11.0/jade.min.js';
// JsRender
THREEJS_MIN_JS : String = 'https://cdnjs.cloudflare.com/ajax/libs/three.js/r71/three.min.js';
// Markup.js
MARKUP_MIN_JS : String = 'https://raw.githubusercontent.com/adammark/Markup.js/master/src/markup.min.js';
ANGULAR_MIN_JS : String = 'https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js';
ANGULAR_MATERIAL_MIN_JS : String = 'https://ajax.googleapis.com/ajax/libs/angular_material/0.10.0/angular-material.min.js';
DOJO_JS : String = 'https://ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js';
EXT_CORE_JS : String = 'https://ajax.googleapis.com/ajax/libs/ext-core/3.1.0/ext-core.js';
MOOTOOLS_MIN_JS : String = 'https://ajax.googleapis.com/ajax/libs/mootools/1.5.1/mootools-yui-compressed.js';
PROTOTYPE_MIN_JS : String = 'https://ajax.googleapis.com/ajax/libs/prototype/1.7.2.0/prototype.js';
SCRIPTACULOUS_MIN_JS : String = 'https://ajax.googleapis.com/ajax/libs/scriptaculous/1.9.0/scriptaculous.js';
SPF_JS : String = 'https://ajax.googleapis.com/ajax/libs/spf/2.2.0/spf.js';
SWFObject_JS : String = 'https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js';
WEBFONTLOADER_JS : String = 'https://ajax.googleapis.com/ajax/libs/webfont/1.5.18/webfont.js';
MATERIAL_DESIGN_CSS : Array[0..1] of String =
(
'https://storage.googleapis.com/code.getmdl.io/1.0.0/material.indigo-pink.min.css',
'https://fonts.googleapis.com/icon?family=Material+Icons');
MATERIAL_DESIGN_JS : String = 'https://storage.googleapis.com/code.getmdl.io/1.0.0/material.min.js';
GRIDIFIER_MIN_JS : String = 'https://raw.githubusercontent.com/nix23/gridifier/master/build/gridifier.min.js';
RACTIVE_JS : String = 'http://cdn.ractivejs.org/latest/ractive.js';
type
TArrayStr = record
count : byte;
items : array[byte] Of String[255];
end;
{ TmainForm }
TmainForm = class(TForm)
btnCreateLanding: TButton;
btnMakeFS: TButton;
btnSaveToFile: TButton;
btnBooster: TButton;
chkRactiveJS: TCheckBox;
chkGridifier: TCheckBox;
chkMaterialDesign: TCheckBox;
chkSwfObject: TCheckBox;
chkWebFontLoader: TCheckBox;
chkMootools: TCheckBox;
chkPrototype: TCheckBox;
chkScriptaculous: TCheckBox;
chkSpf: TCheckBox;
chkExtCore: TCheckBox;
chkDojo: TCheckBox;
chkAngularMaterial: TCheckBox;
chkAngular: TCheckBox;
chkAnima: TCheckBox;
chkJade: TCheckBox;
chkThreeJS: TCheckBox;
chkMarkup: TCheckBox;
chkDotJS: TCheckBox;
chkVelocityJS: TCheckBox;
chkTransparency: TCheckBox;
chkDust: TCheckBox;
chkEJS: TCheckBox;
chkHandlebars: TCheckBox;
chkHogan: TCheckBox;
chkICanHaz: TCheckBox;
chkNunjucks: TCheckBox;
chkMustache: TCheckBox;
chkRequireJS: TCheckBox;
chkToastCSS: TCheckBox;
chkSkeletonCSS: TCheckBox;
chkPureCSS: TCheckBox;
chkUnderscore: TCheckBox;
chkBackbone: TCheckBox;
chkHtml5Shiv: TCheckBox;
chkModernizr: TCheckBox;
chkBootstrap: TCheckBox;
chkJQ: TCheckBox;
chkNormalize: TCheckBox;
chkLodash: TCheckBox;
cbSyntax: TComboBox;
edJS: TLabeledEdit;
edCSS: TLabeledEdit;
edTitle: TLabeledEdit;
Label1: TLabel;
lbSyntaxHighlight: TLabel;
Label2: TLabel;
Label3: TLabel;
edOtherFiles: TLabeledEdit;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
lbBuild: TLabel;
mmBuild: TSynMemo;
mmTemplate: TSynMemo;
OS: TAsyncProcess;
PageControl1: TPageControl;
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
Panel4: TPanel;
Panel5: TPanel;
Panel6: TPanel;
Panel7: TPanel;
SaveDialog1: TSaveDialog;
SynAutoComplete1: TSynAutoComplete;
synCssTemplate: TSynCssSyn;
synCssBuild: TSynCssSyn;
synHtmlTemplate: TSynHTMLSyn;
synHtmlBuild: TSynHTMLSyn;
synTemplate_PHP: TSynPHPSyn;
synBuild_PHP: TSynPHPSyn;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
TabSheet3: TTabSheet;
TabSheet4: TTabSheet;
procedure btnCreateLandingClick(Sender: TObject);
procedure btnMakeFSClick(Sender: TObject);
procedure btnSaveToFileClick(Sender: TObject);
procedure btnBoosterClick(Sender: TObject);
procedure cbSyntaxChange(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
procedure SplitString(Delim : Char; t: String; var q : TArrayStr);
function stylesheet(href : String) : String;
function script(href : String) : String;
function tag(t, elClasses, elID, wrap : String) : String;
end;
var
mainForm: TmainForm;
implementation
{$R *.lfm}
{ TmainForm }
procedure tmainForm.SplitString(Delim : char; t: String; var q: TArrayStr);
var
n : integer;
buf : string;
ps : integer;
begin
q.count := 0;
buf:='';
ps:=0;
for n := 1 to Length(t) do
begin
buf := buf + t[n];
if t[n] = Delim then
begin
//mmBuild.lines.add(IntToStr(n));
// mmBuild.lines.add(buf);
if buf<>'' then begin
ps:=n;
q.items[q.count]:=Copy(buf, 1, length(buf)-1);
Inc(q.count);
buf:='';
end;
end;
end;
Inc(q.count);
q.items[q.count-1]:=Copy(t, ps+1, length(t)-ps+1);
end;
function TmainForm.stylesheet(href: String): String;
begin
Result := '<link rel="stylesheet" type="text/css" href="'+href +'">';
end;
function TmainForm.script(href: String): String;
begin
Result := '<script type="text/javascript" href="'+href+'">'
end;
function TmainForm.tag(t, elClasses, elID, wrap: String): String;
var classPart : String; idPart : String; endTag : String; openTag : String;
endHead : String;
begin
openTag:='<'+t;
endHead := '>';
endTag:='</'+t+'>';
if elClasses<>'' then
classPart := ' class="'+ elClasses+'" ';
if elID<>'' then
idPart:=' id="'+ elID + '"';
Result:=sLineBreak+openTag+classPart+idPart+endHead+sLineBreak+wrap+sLineBreak+endTag+sLineBreak;
end;
procedure TmainForm.btnCreateLandingClick(Sender: TObject);
var q : TArrayStr;
n : integer;
begin
mmBuild.lines.clear();
mmBuild.lines.add('<!DOCTYPE html>');
mmBuild.lines.add('<html>');
mmBuild.lines.add('<head>');
mmBuild.lines.add('<title>'+edTitle.text+'</title>');
q.count:=0;
SplitString(',', edCSS.text, q);
// stylesheets
if chkNormalize.checked then
begin
mmBuild.lines.add(stylesheet(NORMALIZE_MIN_CSS));
end;
if chkBootstrap.checked then
begin
mmBuild.lines.add(stylesheet(BOOTSTRAP_MIN_CSS));
end;
if chkJQ.checked then
begin
mmBuild.lines.add(stylesheet(JQUERY_UI_CSS));
end;
if chkPureCSS.checked then
begin
mmBuild.lines.add(stylesheet(PURE_MIN_CSS));
end;
if chkSkeletonCSS.checked then
begin
mmBuild.lines.add(stylesheet(SKELETON_MIN_CSS));
end;
if chkToastCSS.checked then
begin
mmBuild.lines.add(stylesheet(TOAST_MIN_CSS));
end;
if chkMaterialDesign.checked then
begin
for n:=0 to 1 do
mmBuild.lines.add(stylesheet(MATERIAL_DESIGN_CSS[n]));
end;
for n:=0 to q.count-1 do
begin
mmBuild.lines.add(stylesheet(q.items[n]));
end;
mmBuild.lines.add('</head>');
mmBuild.lines.add('<body>');
for n:=0 to mmTemplate.lines.count-1 do
begin
mmBuild.lines.add(mmTemplate.lines[n]);
end;
// scripts
SplitString(',', edJS.text, q);
if chkJQ.checked then
begin
mmBuild.lines.add(script(JQUERY_MIN_JS));
mmBuild.lines.add(script(JQUERY_UI_MIN_JS));
end;
if chkBootstrap.checked then
mmBuild.lines.add(script(BOOTSTRAP_MIN_JS));
if chkLodash.checked then
mmBuild.lines.add(script(LODASH_MIN_JS));
if chkModernizr.checked then
mmBuild.lines.add(script(MODERNIZR_MIN_JS));
if chkHtml5Shiv.checked then
begin
mmBuild.lines.add(script(HTML5SHIV1_MIN_JS));
mmBuild.lines.add(script(HTML5SHIV2_MIN_JS));
end;
if chkBackbone.checked then
begin
mmBuild.lines.add(script(BACKBONE_MIN_JS));
end;
if chkUnderscore.checked then
begin
mmBuild.lines.add(script(UNDERSCORE_MIN_JS));
end;
if chkRequireJS.checked then
begin
mmBuild.lines.add(script(REQUIRE_MIN_JS));
end;
if chkMustache.checked then
begin
mmBuild.lines.add(script(MUSTACHE_MIN_JS));
end;
if chkNunjucks.checked then
begin
mmBuild.lines.add(script(NUNJUCKS_MIN_JS));
end;
if chkAnima.checked then
begin
mmBuild.lines.add(script(ANIMA_MIN_JS));
end;
if chkDotJs.checked then
begin
mmBuild.lines.add(script(DOT_MIN_JS));
end;
if chkVelocityJS.checked then
begin
mmBuild.lines.add(script(VELOCITY_MIN_JS));
end;
if chkTransparency.checked then
begin
mmBuild.lines.add(script(TRANSPARENCY_MIN_JS));
end;
if chkDust.checked then
begin
mmBuild.lines.add(script(DUST_MIN_JS));
end;
if chkEJS.checked then
begin
mmBuild.lines.add(script(EJS_MIN_JS));
end;
if chkHandleBars.checked then
begin
mmBuild.lines.add(script(HANDLEBARS_MIN_JS[0]));
mmBuild.lines.add(script(HANDLEBARS_MIN_JS[1]));
end;
if chkHogan.checked then
begin
mmBuild.lines.add(script(HOGAN_MIN_JS[0]));
mmBuild.lines.add(script(HOGAN_MIN_JS[1]));
end;
if chkICANHAZ.checked then
begin
mmBuild.lines.add(script(ICANHAZ_MIN_JS));
end;
if chkHogan.checked then
begin
mmBuild.lines.add(script(JADE_MIN_JS));
end;
if chkThreeJS.checked then
begin
mmBuild.lines.add(script(THREEJS_MIN_JS));
end;
if chkThreeJS.checked then
begin
mmBuild.lines.add(script(MARKUP_MIN_JS));
end;
if chkAngular.checked then
begin
mmBuild.lines.add(script(ANGULAR_MIN_JS));
end;
if chkAngularMaterial.checked then
begin
mmBuild.lines.add(script(ANGULAR_MATERIAL_MIN_JS));
end;
if chkDojo.checked then
begin
mmBuild.lines.add(script(DOJO_JS));
end;
if chkExtCore.checked then
begin
mmBuild.lines.add(script(EXT_CORE_JS));
end;
if chkMootools.checked then
begin
mmBuild.lines.add(script(MOOTOOLS_MIN_JS));
end;
if chkPrototype.checked then
begin
mmBuild.lines.add(script(PROTOTYPE_MIN_JS));
end;
if chkScriptaculous.checked then
begin
mmBuild.lines.add(script(SCRIPTACULOUS_MIN_JS));
end;
if chkSpf.checked then
begin
mmBuild.lines.add(script(Spf_JS));
end;
if chkSwfObject.checked then
begin
mmBuild.lines.add(script(SwfObject_JS));
end;
if chkWebFontLoader.checked then
begin
mmBuild.lines.add(script(WEBFONTLOADER_JS));
end;
if chkMaterialDesign.checked then
begin
mmBuild.lines.add(script(MATERIAL_DESIGN_JS));
end;
if chkGridifier.checked then
begin
mmBuild.lines.add(script(GRIDIFIER_MIN_JS));
end;
if chkRactiveJS.checked then
begin
mmBuild.lines.add(script(RACTIVE_JS));
end;
for n:=0 to q.count-1 do
begin
mmBuild.lines.add(script(q.items[n]));
end;
mmBuild.lines.add('</body>');
mmBuild.lines.add('</html>');
end;
procedure TmainForm.btnMakeFSClick(Sender: TObject);
var JS, CSS, OtherFiles : TArrayStr; n : integer;
begin
CSS.count:=0;
JS.count:=0;
OtherFiles.count:=0;
SplitString(',', edCSS.text, CSS);
SplitString(',', edCSS.text, JS);
SplitString(',', edOtherFiles.text, OtherFiles);
for n:=0 to CSS.count - 1 do
begin
if not FileExists(CSS.items[n]) then
begin
OS.commandline:='touch '+CSS.items[n];
OS.execute();
end;
end;
for n:=0 to JS.count - 1 do
begin
if not FileExists(JS.items[n]) then
begin
OS.commandline:='touch '+JS.items[n];
OS.execute();
end;
end;
for n:=0 to OtherFiles.count - 1 do
begin
if not FileExists(OtherFiles.items[n]) then
begin
OS.commandline:='touch '+OtherFiles.items[n];
OS.execute();
end;
end;
end;
procedure TmainForm.btnSaveToFileClick(Sender: TObject);
begin
SaveDialog1.InitialDir := ExtractFilePath(Application.ExeName);
SaveDialog1.FileName := 'index.php';
if SaveDialog1.Execute then
mmBuild.Lines.SaveToFile(SaveDialog1.FileName);
end;
procedure TmainForm.btnBoosterClick(Sender: TObject);
var n, z, k : integer; s : String;
asBoost : TArrayStr;
asElem : TArrayStr;
mytag, temp, id, wrap, classes : String;
repeats, rp : integer;
mmTemp : TMemo;
Strings: TStrings;
begin
mmTemp := TMemo.Create(Self);
mmTemp.Clear();
for n:=0 to mmTemplate.Lines.Count-1 do
mmTemp.Lines.Add(mmTemplate.lines[n]);
for n:=0 to mmTemplate.Lines.Count-1 do
begin
s:=mmTemp.Lines[n];
if (Pos('>', s)>1) and (Pos('<', s)=0) then
begin
asBoost.count:=0;
SplitString('>',s, asBoost);
wrap:='';
for z:=asBoost.count-1 downto 0 do
begin
asElem.count:=0;
SplitString(',', asBoost.items[z],asElem);
// format repeats,tag,id,classes
repeats:=1;
if Trim(asElem.items[0])<>'' then
repeats:=StrToInt(Trim(asElem.items[0]));
mytag:=Trim(asElem.items[1]);
id:=Trim(asElem.items[2]);
classes:='';
for k:=3 to asElem.count-1 do
begin
classes:=classes+' '+Trim(asElem.items[k]);
end;
wrap:=tag(mytag, classes, id, wrap);
temp:='';
for rp:=1 to repeats do
temp:=temp+wrap;
wrap:=temp;
end;
mmTemp.lines[n]:=wrap;
end;
end;
Strings := TStringList.Create;
try
Strings.Assign(mmTemp.Lines); // Assuming you use a TMemo
mmTemp.Text := Strings.Text;
finally
Strings.Free;
end;
mmTemplate.clear;
for n:=0 to mmTemp.Lines.Count-1 do
mmTemplate.Lines.add(mmTemp.Lines[n]);
mmTemp.clear();
mmTemp.free();
end;
procedure TmainForm.cbSyntaxChange(Sender: TObject);
begin
case cbSyntax.itemindex of
0 : begin
mmTemplate.Highlighter := synTemplate_PHP;
mmBuild.Highlighter := synBuild_PHP;
end;
1 : begin
mmTemplate.Highlighter := synHtmlTemplate;
mmBuild.Highlighter := synHtmlBuild;
end;
2 : begin
mmTemplate.Highlighter := synCssTemplate;
mmBuild.Highlighter := synCssBuild;
end;
end;
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Core.Package.Installer;
//TODO : Lots of common code between install and restore - refactor!
interface
uses
VSoft.Awaitable,
Spring.Collections,
DPM.Core.Types,
DPM.Core.Logging,
DPM.Core.Options.Cache,
DPM.Core.Options.Search,
DPM.Core.Options.Install,
DPM.Core.Options.Uninstall,
DPM.Core.Options.Restore,
DPM.Core.Project.Interfaces,
DPM.Core.Spec.Interfaces,
DPM.Core.Package.Interfaces,
DPM.Core.Configuration.Interfaces,
DPM.Core.Repository.Interfaces,
DPM.Core.Cache.Interfaces,
DPM.Core.Dependency.Interfaces,
DPM.Core.Compiler.Interfaces;
type
TPackageInstaller = class(TInterfacedObject, IPackageInstaller)
private
FLogger : ILogger;
FConfigurationManager : IConfigurationManager;
FRepositoryManager : IPackageRepositoryManager;
FPackageCache : IPackageCache;
FDependencyResolver : IDependencyResolver;
FContext : IPackageInstallerContext;
FCompilerFactory : ICompilerFactory;
protected
function GetPackageInfo(const cancellationToken : ICancellationToken; const packageId : IPackageId) : IPackageInfo;
function CreateProjectRefs(const cancellationToken: ICancellationToken; const node: IGraphNode; const seenPackages: IDictionary<string, IPackageInfo>;
const projectReferences: IList<TProjectReference>): boolean;
function CollectSearchPaths(const packageGraph : IGraphNode; const resolvedPackages : IList<IPackageInfo>; const compiledPackages : IList<IPackageInfo>; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const searchPaths : IList<string> ) : boolean;
procedure GenerateSearchPaths(const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; packageSpec : IPackageSpec; const searchPaths : IList<string>);
function DownloadPackages(const cancellationToken : ICancellationToken; const resolvedPackages : IList<IPackageInfo>; var packageSpecs : IDictionary<string, IPackageSpec>) : boolean;
function CollectPlatformsFromProjectFiles(const options : TInstallOptions; const projectFiles : TArray <string> ; const config : IConfiguration) : boolean;
function GetCompilerVersionFromProjectFiles(const options : TInstallOptions; const projectFiles : TArray <string> ; const config : IConfiguration) : boolean;
function CompilePackage(const cancellationToken : ICancellationToken; const compiler : ICompiler; const packageInfo : IPackageInfo; const graphNode : IGraphNode; const packageSpec : IPackageSpec; const force : boolean) : boolean;
function BuildDependencies(const cancellationToken : ICancellationToken; const packageCompiler : ICompiler; const projectPackageGraph : IGraphNode;
const packagesToCompile : IList<IPackageInfo>; const compiledPackages : IList<IPackageInfo>; packageSpecs : IDictionary<string, IPackageSpec>;
const options : TSearchOptions) : boolean;
function CopyLocal(const cancellationToken : ICancellationToken; const resolvedPackages : IList<IPackageInfo>; const packageSpecs : IDictionary<string, IPackageSpec>; const projectEditor : IProjectEditor; const platform : TDPMPlatform) : boolean;
function DoRestoreProject(const cancellationToken : ICancellationToken; const options : TRestoreOptions; const projectFile : string; const projectEditor : IProjectEditor; const platform : TDPMPlatform; const config : IConfiguration) : boolean;
function DoInstallPackage(const cancellationToken : ICancellationToken; const options : TInstallOptions; const projectFile : string; const projectEditor : IProjectEditor; const platform : TDPMPlatform; const config : IConfiguration) : boolean;
function DoUninstallFromProject(const cancellationToken : ICancellationToken; const options : TUnInstallOptions; const projectFile : string; const projectEditor : IProjectEditor; const platform : TDPMPlatform; const config : IConfiguration) : boolean;
function DoCachePackage(const cancellationToken : ICancellationToken; const options : TCacheOptions; const platform : TDPMPlatform) : boolean;
//works out what compiler/platform then calls DoInstallPackage
function InstallPackage(const cancellationToken : ICancellationToken; const options : TInstallOptions; const projectFile : string; const config : IConfiguration) : boolean;
//user specified a package file - will install for single compiler/platform - calls InstallPackage
function InstallPackageFromFile(const cancellationToken : ICancellationToken; const options : TInstallOptions; const projectFiles : TArray <string> ; const config : IConfiguration) : boolean;
//resolves package from id - calls InstallPackage
function InstallPackageFromId(const cancellationToken : ICancellationToken; const options : TInstallOptions; const projectFiles : TArray <string> ; const config : IConfiguration) : boolean;
//calls either InstallPackageFromId or InstallPackageFromFile depending on options.
function Install(const cancellationToken : ICancellationToken; const options : TInstallOptions) : Boolean;
function UnInstall(const cancellationToken : ICancellationToken; const options : TUnInstallOptions) : boolean;
function UnInstallFromProject(const cancellationToken : ICancellationToken; const options : TUnInstallOptions; const projectFile : string; const config : IConfiguration) : Boolean;
function RestoreProject(const cancellationToken : ICancellationToken; const options : TRestoreOptions; const projectFile : string; const config : IConfiguration) : Boolean;
//calls restore project
function Restore(const cancellationToken : ICancellationToken; const options : TRestoreOptions) : Boolean;
function Remove(const cancellationToken : ICancellationToken; const options : TUninstallOptions) : boolean;
function Cache(const cancellationToken : ICancellationToken; const options : TCacheOptions) : boolean;
function Context : IPackageInstallerContext;
public
constructor Create(const logger : ILogger; const configurationManager : IConfigurationManager;
const repositoryManager : IPackageRepositoryManager; const packageCache : IPackageCache;
const dependencyResolver : IDependencyResolver; const context : IPackageInstallerContext;
const compilerFactory : ICompilerFactory);
end;
implementation
uses
System.IOUtils,
System.Types,
System.SysUtils,
Spring,
Spring.Collections.Extensions,
VSoft.AntPatterns,
DPM.Core.Constants,
DPM.Core.Compiler.BOM,
DPM.Core.Utils.Path,
DPM.Core.Utils.Files,
DPM.Core.Utils.System,
DPM.Core.Project.Editor,
DPM.Core.Project.GroupProjReader,
DPM.Core.Options.List,
DPM.Core.Dependency.Graph,
DPM.Core.Dependency.Version,
DPM.Core.Package.Metadata,
DPM.Core.Spec.Reader;
{ TPackageInstaller }
function TPackageInstaller.Cache(const cancellationToken : ICancellationToken; const options : TCacheOptions) : boolean;
var
config : IConfiguration;
platform : TDPMPlatform;
platforms : TDPMPlatforms;
begin
result := false;
if (not options.Validated) and (not options.Validate(FLogger)) then
exit
else if not options.IsValid then
exit;
config := FConfigurationManager.LoadConfig(options.ConfigFile);
if config = nil then
exit;
FPackageCache.Location := config.PackageCacheLocation;
if not FRepositoryManager.Initialize(config) then
begin
FLogger.Error('Unable to initialize the repository manager.');
exit;
end;
platforms := options.Platforms;
if platforms = [] then
platforms := AllPlatforms(options.CompilerVersion);
result := true;
for platform in platforms do
begin
if cancellationToken.IsCancelled then
exit;
options.Platforms := [platform];
result := DoCachePackage(cancellationToken, options, platform) and result;
end;
end;
function TPackageInstaller.CollectPlatformsFromProjectFiles(const options : TInstallOptions; const projectFiles : TArray <string> ; const config : IConfiguration) : boolean;
var
projectFile : string;
projectEditor : IProjectEditor;
begin
result := true;
for projectFile in projectFiles do
begin
projectEditor := TProjectEditor.Create(FLogger, config, options.CompilerVersion);
result := result and projectEditor.LoadProject(projectFile);
if result then
options.Platforms := options.Platforms + projectEditor.Platforms;
end;
end;
function TPackageInstaller.CollectSearchPaths(const packageGraph : IGraphNode; const resolvedPackages : IList<IPackageInfo>; const compiledPackages : IList<IPackageInfo>; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const searchPaths : IList<string> ) : boolean;
var
packageInfo : IPackageInfo;
packageMetadata : IPackageMetadata;
packageSearchPath : IPackageSearchPath;
packageBasePath : string;
begin
result := true;
//we need to apply usesource from the graph to the package info's
packageGraph.VisitDFS(
procedure(const node : IGraphNode)
var
pkgInfo : IPackageInfo;
begin
//not the most efficient thing to do
pkgInfo := resolvedPackages.Where(
function(const pkg : IPackageInfo) : boolean
begin
result := SameText(pkg.Id, node.Id);
end).FirstOrDefault;
Assert(pkgInfo <> nil, 'pkgInfo is null, but should never be');
pkgInfo.UseSource := pkgInfo.UseSource or node.UseSource;
end);
//reverse the list so that we add the paths in reverse order, small optimisation for the compiler.
resolvedPackages.Reverse;
for packageInfo in resolvedPackages do
begin
if (not packageInfo.UseSource) and compiledPackages.Contains(packageInfo) then
begin
packageBasePath := packageInfo.Id + PathDelim + packageInfo.Version.ToStringNoMeta + PathDelim;
searchPaths.Add(packageBasePath + 'lib');
end
else
begin
packageMetadata := FPackageCache.GetPackageMetadata(packageInfo);
if packageMetadata = nil then
begin
FLogger.Error('Unable to get metadata for package ' + packageInfo.ToString);
exit(false);
end;
packageBasePath := packageMetadata.Id + PathDelim + packageMetadata.Version.ToStringNoMeta + PathDelim;
for packageSearchPath in packageMetadata.SearchPaths do
searchPaths.Add(packageBasePath + packageSearchPath.Path);
end;
end;
end;
function TPackageInstaller.CompilePackage(const cancellationToken: ICancellationToken; const compiler: ICompiler; const packageInfo : IPackageInfo; const graphNode : IGraphNode; const packageSpec : IPackageSpec; const force : boolean): boolean;
var
buildEntry : ISpecBuildEntry;
packagePath : string;
projectFile : string;
searchPaths : IList<string>;
childNode: IGraphNode;
bomNode : IGraphNode;
bomFile : string;
childSearchPath : string;
procedure DoCopyFiles(const entry : ISpecBuildEntry);
var
copyEntry : ISpecCopyEntry;
antPattern : IAntPattern;
fsPatterns : TArray<IFileSystemPattern>;
fsPattern : IFileSystemPattern;
searchBasePath : string;
files : TStringDynArray;
f : string;
destFile : string;
begin
for copyEntry in entry.CopyFiles do
begin
FLogger.Debug('Post Compile Copy [' + copyEntry.Source + ']..');
try
//note : this can throw if the source path steps outside of the base path.
searchBasePath := TPathUtils.StripWildCard(TPathUtils.CompressRelativePath(packagePath, copyEntry.Source));
searchBasePath := ExtractFilePath(searchBasePath);
antPattern := TAntPattern.Create(packagePath);
fsPatterns := antPattern.Expand(copyEntry.Source);
for fsPattern in fsPatterns do
begin
ForceDirectories(fsPattern.Directory);
files := TDirectory.GetFiles(fsPattern.Directory, fsPattern.FileMask, TSearchOption.soTopDirectoryOnly);
for f in files do
begin
//copy file to lib directory.
if copyEntry.flatten then
destFile := compiler.LibOutputDir + '\' + ExtractFileName(f)
else
destFile := compiler.LibOutputDir + '\' + TPathUtils.StripBase(searchBasePath, f);
ForceDirectories(ExtractFilePath(destFile));
//FLogger.Debug('Copying "' + f + '" to "' + destFile + '"');
TFile.Copy(f, destFile, true);
end;
end;
except
on e : Exception do
begin
FLogger.Error('Error copying files to lib folder : ' + e.Message);
raise;
end;
end;
FLogger.Debug('Post Compile Copy [' + copyEntry.Source + ']..');
end;
end;
begin
result := true;
packagePath := FPackageCache.GetPackagePath(packageInfo);
bomFile := TPath.Combine(packagePath, 'package.bom');
if (not force) and FileExists(bomFile) then
begin
//Compare Bill of materials file against node dependencies to determine if we need to compile or not.
//if the bom file exists that means it was compiled before. We will check that the bom matchs the dependencies
//in the graph
bomNode := TBOMFile.LoadFromFile(FLogger, bomFile);
if bomNode <> nil then
begin
if bomNode.AreEqual(graphNode) then
begin
exit;
end;
end;
end;
//if we get here the previous compliation was done with different dependency versions,
//so we delete the bom and compile again
DeleteFile(bomFile);
for buildEntry in packageSpec.TargetPlatform.BuildEntries do
begin
FLogger.Information('Building project : ' + buildEntry.Project);
projectFile := TPath.Combine(packagePath, buildEntry.Project);
projectFile := TPathUtils.CompressRelativePath('',projectFile);
// if it's a design time package then we need to do a lot more work.
// design time packages are win32 (as the IDE is win32) - since we can
// only have one copy of the design package installed we need to check if
// it has already been installed via another platform.
if buildEntry.DesignOnly and ( packageInfo.Platform <> TDPMPlatform.Win32) then
begin
compiler.BPLOutputDir := TPath.Combine(packagePath, buildEntry.BplOutputDir);
compiler.LibOutputDir := TPath.Combine(packagePath, buildEntry.LibOutputDir);
compiler.Configuration := buildEntry.Config;
if compiler.Platform <> TDPMPlatform.Win32 then
begin
compiler.BPLOutputDir := TPath.Combine(compiler.BPLOutputDir, 'win32');
compiler.LibOutputDir := TPath.Combine(compiler.LibOutputDir, 'win32');
end
else
begin
graphNode.LibPath := compiler.LibOutputDir;
graphNode.BplPath := compiler.BPLOutputDir;
end;
if graphNode.HasChildren then
begin
searchPaths := TCollections.CreateList<string>;
for childNode in graphNode.ChildNodes do
begin
childSearchPath := FPackageCache.GetPackagePath(childNode.Id, childNode.Version.ToStringNoMeta, compiler.CompilerVersion, compiler.Platform );
childSearchPath := TPath.Combine(childSearchPath, 'lib\win32');
searchPaths.Add(childSearchPath);
end;
compiler.SetSearchPaths(searchPaths);
end
else
compiler.SetSearchPaths(nil);
FLogger.Information('Building project [' + projectFile + '] for design time...');
result := compiler.BuildProject(cancellationToken, projectFile, buildEntry.Config, packageInfo.Version, true);
if result then
FLogger.Success('Project [' + buildEntry.Project + '] build succeeded.')
else
begin
if cancellationToken.IsCancelled then
FLogger.Error('Building project [' + buildEntry.Project + '] cancelled.')
else
FLogger.Error('Building project [' + buildEntry.Project + '] failed.');
exit;
end;
FLogger.NewLine;
end
else
begin
//note we are assuming the build entry paths are all relative.
compiler.BPLOutputDir := TPath.Combine(packagePath, buildEntry.BplOutputDir);
compiler.LibOutputDir := TPath.Combine(packagePath, buildEntry.LibOutputDir);
compiler.Configuration := buildEntry.Config;
graphNode.LibPath := compiler.LibOutputDir;
graphNode.BplPath := compiler.BPLOutputDir;
if graphNode.HasChildren then
begin
searchPaths := TCollections.CreateList<string>;
for childNode in graphNode.ChildNodes do
begin
childSearchPath := FPackageCache.GetPackagePath(childNode.Id, childNode.Version.ToStringNoMeta, compiler.CompilerVersion, compiler.Platform);
childSearchPath := TPath.Combine(childSearchPath, 'lib');
searchPaths.Add(childSearchPath);
end;
compiler.SetSearchPaths(searchPaths);
end
else
compiler.SetSearchPaths(nil);
result := compiler.BuildProject(cancellationToken, projectFile, buildEntry.Config, packageInfo.Version );
if result then
FLogger.Success('Project [' + buildEntry.Project + '] build succeeded.')
else
begin
if cancellationToken.IsCancelled then
FLogger.Error('Building project [' + buildEntry.Project + '] cancelled.')
else
FLogger.Error('Building project [' + buildEntry.Project + '] failed.');
exit;
end;
FLogger.NewLine;
if buildEntry.BuildForDesign and (compiler.Platform <> TDPMPlatform.Win32) then
begin
FLogger.Information('Building project [' + projectFile + '] for design time support...');
//if buildForDesign is true, then it means the design time bpl's also reference
//this bpl, so if the platform isn't win32 then we need to build it for win32
compiler.BPLOutputDir := TPath.Combine(compiler.BPLOutputDir, 'win32');
compiler.LibOutputDir := TPath.Combine(compiler.LibOutputDir, 'win32');
if graphNode.HasChildren then
begin
searchPaths := TCollections.CreateList<string>;
for childNode in graphNode.ChildNodes do
begin
childSearchPath := FPackageCache.GetPackagePath(childNode.Id, childNode.Version.ToStringNoMeta, compiler.CompilerVersion, compiler.Platform );
childSearchPath := TPath.Combine(childSearchPath, 'lib\win32');
searchPaths.Add(childSearchPath);
end;
compiler.SetSearchPaths(searchPaths);
end
else
compiler.SetSearchPaths(nil);
result := compiler.BuildProject(cancellationToken, projectFile, buildEntry.Config, packageInfo.Version, true);
if result then
FLogger.Success('Project [' + buildEntry.Project + '] Compiled for designtime Ok.')
else
begin
if cancellationToken.IsCancelled then
FLogger.Error('Building project [' + buildEntry.Project + '] cancelled.')
else
FLogger.Error('Building project [' + buildEntry.Project + '] failed.');
exit;
end;
end;
if buildEntry.CopyFiles.Any then
DoCopyFiles(buildEntry);
end;
end;
//save the bill of materials file for future reference.
TBOMFile.SaveToFile(FLogger, bomFile, graphNode);
end;
function TPackageInstaller.Context : IPackageInstallerContext;
begin
result := FContext;
end;
function TPackageInstaller.CopyLocal(const cancellationToken : ICancellationToken;const resolvedPackages: IList<IPackageInfo>; const packageSpecs: IDictionary<string, IPackageSpec>;
const projectEditor: IProjectEditor; const platform: TDPMPlatform): boolean;
var
configName : string;
projectConfig : IProjectConfiguration;
packageSpec : IPackageSpec;
resolvedPackage : IPackageInfo;
configNames : IReadOnlyList<string>;
outputDir : string;
lastOutputDir : string;
bplSourceFile : string;
bplTargetFile : string;
packageFolder : string;
runtimeCopyLocalFiles : TArray<ISpecBPLEntry>;
runtimeEntry : ISpecBPLEntry;
begin
result := true;
configNames := projectEditor.GetConfigNames;
for resolvedPackage in resolvedPackages do
begin
packageSpec := packageSpecs[LowerCase(resolvedPackage.Id)];
Assert(packageSpec <> nil);
//FLogger.Debug('Copylocal for package [' + resolvedPackage.Id + ']');
//TODO : Is there any point in the copylocal option now.. shouldn't all runtime bpls be copied?
runtimeCopyLocalFiles := packageSpec.TargetPlatform.RuntimeFiles.Where(
function(const entry : ISpecBPLEntry) : boolean
begin
result := entry.CopyLocal;
end).ToArray;
//if no runtime bpl's are defined with copylocal in the dspec then there is nothing to do.
if Length(runtimeCopyLocalFiles) = 0 then
continue;
lastOutputDir := '';
packageFolder := FPackageCache.GetPackagePath(resolvedPackage);
//FLogger.Debug('Package folder [' + packageFolder + ']');
for configName in configNames do
begin
if configName = 'Base' then
continue;
//FLogger.Debug('Config [' + configName + ']');
projectConfig := projectEditor.GetProjectConfiguration(configName, platform);
//we're only doing this for projects using runtime configs.
if not projectConfig.UsesRuntimePackages then
continue;
//FLogger.Debug('uses runtime packages');
outputDir := projectConfig.OutputDir;
if (outputDir <> '') and (not SameText(outputDir, lastOutputDir)) then
begin
lastOutputDir := outputDir;
for runtimeEntry in runtimeCopyLocalFiles do
begin
bplSourceFile := TPath.Combine(packageFolder,runtimeEntry.Source);
if not FileExists(bplSourceFile) then
begin
FLogger.Warning('Unabled to find runtime package [' + bplSourceFile + '] during copy local');
continue;
end;
bplTargetFile := TPath.Combine(outputDir, ExtractFileName(bplSourceFile));
if TPathUtils.IsRelativePath(bplTargetFile) then
begin
bplTargetFile := TPath.Combine(ExtractFilePath(projectEditor.ProjectFile),bplTargetFile);
bplTargetFile := TPathUtils.CompressRelativePath('',bplTargetFile );
end;
//if the file exists already, then we need to work out if they are the same or not.
if FileExists(bplTargetFile) and TFileUtils.AreSameFiles(bplSourceFile, bplTargetFile) then
continue;
//now actually copy files.
try
ForceDirectories(ExtractFilePath(bplTargetFile));
TFile.Copy(bplSourceFile, bplTargetFile, true);
except
on e : Exception do
begin
FLogger.Warning('Unable to copy runtime package [' + bplSourceFile + '] to [' + bplTargetFile + '] during copy local');
FLogger.Warning(' ' + e.Message);
end;
end;
end;
end;
end;
end;
end;
constructor TPackageInstaller.Create(const logger : ILogger; const configurationManager : IConfigurationManager;
const repositoryManager : IPackageRepositoryManager; const packageCache : IPackageCache;
const dependencyResolver : IDependencyResolver; const context : IPackageInstallerContext;
const compilerFactory : ICompilerFactory);
begin
FLogger := logger;
FConfigurationManager := configurationManager;
FRepositoryManager := repositoryManager;
FPackageCache := packageCache;
FDependencyResolver := dependencyResolver;
FContext := context;
FCompilerFactory := compilerFactory;
end;
function TPackageInstaller.GetPackageInfo(const cancellationToken : ICancellationToken; const packageId : IPackageId) : IPackageInfo;
begin
result := FPackageCache.GetPackageInfo(cancellationToken, packageId); //faster
if result = nil then
result := FRepositoryManager.GetPackageInfo(cancellationToken, packageId); //slower
end;
function TPackageInstaller.DoCachePackage(const cancellationToken : ICancellationToken; const options : TCacheOptions; const platform : TDPMPlatform) : boolean;
var
packageIdentity : IPackageIdentity;
searchResult : IList<IPackageIdentity>;
packageFileName : string;
begin
result := false;
if not options.Version.IsEmpty then
//sourceName will be empty if we are installing the package from a file
packageIdentity := TPackageIdentity.Create(options.PackageId, '', options.Version, options.CompilerVersion, platform, '')
else
begin
//no version specified, so we need to get the latest version available;
searchResult := FRepositoryManager.List(cancellationToken, options);
packageIdentity := searchResult.FirstOrDefault;
if packageIdentity = nil then
begin
FLogger.Error('Package [' + options.PackageId + '] for platform [' + DPMPlatformToString(platform) + '] not found on any sources');
exit;
end;
end;
FLogger.Information('Caching package ' + packageIdentity.ToString);
if not FPackageCache.EnsurePackage(packageIdentity) then
begin
//not in the cache, so we need to get it from the the repository
if not FRepositoryManager.DownloadPackage(cancellationToken, packageIdentity, FPackageCache.PackagesFolder, packageFileName) then
begin
if cancellationToken.IsCancelled then
FLogger.Error('Downloading package [' + packageIdentity.ToString + '] cancelled.')
else
FLogger.Error('Failed to download package [' + packageIdentity.ToString + ']');
exit;
end;
if not FPackageCache.InstallPackageFromFile(packageFileName, true) then
begin
FLogger.Error('Failed to cache package file [' + packageFileName + '] into the cache');
exit;
end;
end;
result := true;
end;
function TPackageInstaller.CreateProjectRefs(const cancellationToken : ICancellationToken; const node : IGraphNode; const seenPackages : IDictionary<string, IPackageInfo>; const projectReferences : IList<TProjectReference>) : boolean;
var
child : IGraphNode;
info : IPackageInfo;
projectRef : TProjectReference;
begin
result := true;
if not node.IsRoot then
begin
if seenPackages.TryGetValue(LowerCase(node.Id), info) then
begin
//if a node uses source then we need to find the projectRef and update i
if node.UseSource then
info.UseSource := true;
exit;
end;
info := GetPackageInfo(cancellationToken, node);
if info = nil then
begin
FLogger.Error('Unable to resolve package : ' + node.ToIdVersionString);
exit(false);
end;
info.UseSource := node.UseSource;
projectRef.Package := info;
projectRef.VersionRange := node.SelectedOn;
projectRef.ParentId := node.Parent.id;
seenPackages[LowerCase(node.Id)] := info;
projectReferences.Add(projectRef);
end;
if node.HasChildren then
for child in node.ChildNodes do
begin
result := CreateProjectRefs(cancellationToken,child, seenPackages, projectReferences);
if not result then
exit;
end;
end;
function TPackageInstaller.DoInstallPackage(const cancellationToken : ICancellationToken; const options : TInstallOptions; const projectFile : string; const projectEditor : IProjectEditor; const platform : TDPMPlatform; const config : IConfiguration) : boolean;
var
newPackageIdentity : IPackageIdentity;
searchResult : IList<IPackageIdentity>;
packageFileName : string;
packageInfo : IPackageInfo; //includes dependencies;
existingPackageRef : IGraphNode;
projectPackageGraph : IGraphNode;
packageSpecs : IDictionary<string, IPackageSpec>;
projectReferences : IList<TProjectReference>;
resolvedPackages : IList<IPackageInfo>;
packagesToCompile : IList<IPackageInfo>;
compiledPackages : IList<IPackageInfo>;
packageSearchPaths : IList<string>;
childNode : IGraphNode;
packageCompiler : ICompiler;
seenPackages : IDictionary<string, IPackageInfo>;
begin
result := false;
projectPackageGraph := projectEditor.GetPackageReferences(platform); //can return nil
if projectPackageGraph = nil then
projectPackageGraph := TGraphNode.CreateRoot(options.CompilerVersion, platform);
//see if it's already installed.
existingPackageRef := projectPackageGraph.FindChild(options.PackageId);
if (existingPackageRef <> nil) then
begin
//if it's installed already and we're not forcing it to install then we're done.
if not options.Force then
begin
//Note this error won't show from the IDE as we always force install from the IDE.
FLogger.Error('Package [' + options.PackageId + '] is already installed. Use option -force to force reinstall.');
exit;
end;
//remove it so we can force resolution to happen later.
projectPackageGraph.RemoveNode(existingPackageRef);
existingPackageRef := nil; //we no longer need it.
end;
//We could have a transitive dependency that is being promoted.
//Since we want to control what version is installed, we will remove
//any transitive references to that package so the newly installed version
//will take precedence when resolving.
childNode := projectPackageGraph.FindFirstNode(options.PackageId);
while childNode <> nil do
begin
projectPackageGraph.RemoveNode(childNode);
childNode := projectPackageGraph.FindFirstNode(options.PackageId);
end;
//if the user specified a version, either the on the command line or via a file then we will use that
if not options.Version.IsEmpty then
//sourceName will be empty if we are installing the package from a file
newPackageIdentity := TPackageIdentity.Create(options.PackageId, '', options.Version, options.CompilerVersion, platform, '')
else
begin
//no version specified, so we need to get the latest version available;
searchResult := FRepositoryManager.List(cancellationToken, options);
newPackageIdentity := searchResult.FirstOrDefault;
if newPackageIdentity = nil then
begin
FLogger.Error('Package [' + options.PackageId + '] for platform [' + DPMPlatformToString(platform) + '] not found on any sources');
exit;
end;
end;
FLogger.Information('Installing package ' + newPackageIdentity.ToString);
if not FPackageCache.EnsurePackage(newPackageIdentity) then
begin
//not in the cache, so we need to get it from the the repository
if not FRepositoryManager.DownloadPackage(cancellationToken, newPackageIdentity, FPackageCache.PackagesFolder, packageFileName) then
begin
FLogger.Error('Failed to download package [' + newPackageIdentity.ToString + ']');
exit;
end;
if not FPackageCache.InstallPackageFromFile(packageFileName, true) then
begin
FLogger.Error('Failed to install package file [' + packageFileName + '] into the cache');
exit;
end;
end;
//get the package info, which has the dependencies.
packageInfo := GetPackageInfo(cancellationToken, newPackageIdentity);
if packageInfo = nil then
begin
FLogger.Error('Unable to get package info for package [' + newPackageIdentity.ToIdVersionString + ']');
exit(false);
end;
packageInfo.UseSource := options.UseSource; //we need this later when collecting search paths.
seenPackages := TCollections.CreateDictionary<string, IPackageInfo>;
projectReferences := TCollections.CreateList<TProjectReference>;
if not CreateProjectRefs(cancellationtoken, projectPackageGraph, seenPackages, projectReferences) then
exit;
if not FDependencyResolver.ResolveForInstall(cancellationToken, options, packageInfo, projectReferences, projectPackageGraph, packageInfo.CompilerVersion, platform, resolvedPackages) then
exit;
if resolvedPackages = nil then
begin
FLogger.Error('Resolver returned no packages!');
exit(false);
end;
//get the package we were installing.
packageInfo := resolvedPackages.FirstOrDefault(function(const info : IPackageInfo) : boolean
begin
result := SameText(info.Id, packageInfo.Id);
end);
//this is just a sanity check, should never happen.
if packageInfo = nil then
begin
FLogger.Error('Something went wrong, resolution did not return installed package!');
exit(false);
end;
//downloads the package files to the cache if they are not already there and
//returns the deserialized dspec as we need it for search paths and
if not DownloadPackages(cancellationToken, resolvedPackages, packageSpecs) then
exit;
compiledPackages := TCollections.CreateList<IPackageInfo>;
packagesToCompile := TCollections.CreateList<IPackageInfo>(resolvedPackages);
packageSearchPaths := TCollections.CreateList<string>;
packageCompiler := FCompilerFactory.CreateCompiler(options.CompilerVersion, platform);
if not BuildDependencies(cancellationToken,packageCompiler, projectPackageGraph, packagesToCompile, compiledPackages, packageSpecs, options ) then
exit;
if not CollectSearchPaths(projectPackageGraph, resolvedPackages, compiledPackages, projectEditor.CompilerVersion, platform, packageSearchPaths) then
exit;
if not CopyLocal(cancellationToken, resolvedPackages, packageSpecs, projectEditor, platform) then
exit;
if not projectEditor.AddSearchPaths(platform, packageSearchPaths, config.PackageCacheLocation) then
exit;
projectEditor.UpdatePackageReferences(projectPackageGraph, platform);
result := projectEditor.SaveProject();
end;
function TPackageInstaller.DoRestoreProject(const cancellationToken : ICancellationToken; const options : TRestoreOptions; const projectFile : string; const projectEditor : IProjectEditor; const platform : TDPMPlatform; const config : IConfiguration) : boolean;
var
projectPackageGraph : IGraphNode;
packageSpecs : IDictionary<string, IPackageSpec>;
projectReferences : IList<TProjectReference>;
resolvedPackages : IList<IPackageInfo>;
packagesToCompile : IList<IPackageInfo>;
compiledPackages : IList<IPackageInfo>;
packageSearchPaths : IList<string>;
packageCompiler : ICompiler;
seenPackages : IDictionary<string, IPackageInfo>;
begin
result := false;
projectPackageGraph := projectEditor.GetPackageReferences(platform); //can return nil
//if there is no project package graph then there is nothing to do.
if projectPackageGraph = nil then
exit(true);
seenPackages := TCollections.CreateDictionary<string, IPackageInfo>;
projectReferences := TCollections.CreateList<TProjectReference>;
//TODO : Can packagerefs be replaced by just adding the info to the nodes?
if not CreateProjectRefs(cancellationtoken, projectPackageGraph, seenPackages, projectReferences) then
exit;
if not FDependencyResolver.ResolveForRestore(cancellationToken, options, projectReferences, projectPackageGraph, projectEditor.CompilerVersion, platform, resolvedPackages) then
exit;
//TODO : The code from here on is the same for install/uninstall/restore - refactor!!!
if resolvedPackages = nil then
begin
FLogger.Error('Resolver returned no packages!');
exit(false);
end;
//downloads the package files to the cache if they are not already there and
//returns the deserialized dspec as we need it for search paths and
if not DownloadPackages(cancellationToken, resolvedPackages, packageSpecs) then
exit;
compiledPackages := TCollections.CreateList<IPackageInfo>;
packagesToCompile := TCollections.CreateList<IPackageInfo>(resolvedPackages);
packageSearchPaths := TCollections.CreateList<string>;
packageCompiler := FCompilerFactory.CreateCompiler(options.CompilerVersion, platform);
if not BuildDependencies(cancellationToken,packageCompiler, projectPackageGraph, packagesToCompile, compiledPackages, packageSpecs, options ) then
exit;
if not CollectSearchPaths(projectPackageGraph, resolvedPackages, compiledPackages, projectEditor.CompilerVersion, platform, packageSearchPaths) then
exit;
if not CopyLocal(cancellationToken, resolvedPackages, packageSpecs, projectEditor, platform) then
exit;
if not projectEditor.AddSearchPaths(platform, packageSearchPaths, config.PackageCacheLocation) then
exit;
projectEditor.UpdatePackageReferences(projectPackageGraph, platform);
result := projectEditor.SaveProject();
end;
function TPackageInstaller.DoUninstallFromProject(const cancellationToken: ICancellationToken; const options: TUnInstallOptions; const projectFile: string;
const projectEditor: IProjectEditor; const platform: TDPMPlatform; const config: IConfiguration): boolean;
var
projectPackageGraph : IGraphNode;
foundReference : IGraphNode;
packageSpecs : IDictionary<string, IPackageSpec>;
projectReferences : IList<TProjectReference>;
resolvedPackages : IList<IPackageInfo>;
packagesToCompile : IList<IPackageInfo>;
compiledPackages : IList<IPackageInfo>;
packageSearchPaths : IList<string>;
packageCompiler : ICompiler;
seenPackages : IDictionary<string, IPackageInfo>;
begin
result := false;
projectPackageGraph := projectEditor.GetPackageReferences(platform); //can return nil
//if there is no project package graph then there is nothing to do.
if projectPackageGraph = nil then
begin
FLogger.Information('Package [' + options.PackageId + '] was not referenced in project [' + projectFile + '] for platform [' + DPMPlatformToString(platform) + '] - nothing to do.');
exit(true);
end;
foundReference := projectPackageGraph.FindChild(options.PackageId);
if foundReference = nil then
begin
FLogger.Information('Package [' + options.PackageId + '] was not referenced in project [' + projectFile + '] for platform [' + DPMPlatformToString(platform) + '] - nothing to do.');
//TODO : Should this fail with an error? It's a noop
exit(true);
end;
projectPackageGraph.RemoveNode(foundReference);
seenPackages := TCollections.CreateDictionary<string, IPackageInfo>;
projectReferences := TCollections.CreateList<TProjectReference>;
//TODO : Can packagerefs be replaced by just adding the info to the nodes?
if not CreateProjectRefs(cancellationtoken, projectPackageGraph, seenPackages, projectReferences) then
exit;
if not FDependencyResolver.ResolveForRestore(cancellationToken, options, projectReferences, projectPackageGraph, projectEditor.CompilerVersion, platform, resolvedPackages) then
exit;
if resolvedPackages = nil then
begin
FLogger.Error('Resolver returned no packages!');
exit;
end;
//downloads the package files to the cache if they are not already there and
//returns the deserialized dspec as we need it for search paths and
if not DownloadPackages(cancellationToken, resolvedPackages, packageSpecs) then
exit;
compiledPackages := TCollections.CreateList<IPackageInfo>;
packagesToCompile := TCollections.CreateList<IPackageInfo>(resolvedPackages);
packageSearchPaths := TCollections.CreateList<string>;
packageCompiler := FCompilerFactory.CreateCompiler(options.CompilerVersion, platform);
//even though we are just uninstalling a package here.. we still need to run the compiliation stage to collect paths
//it will mostly be a no-op as everyhing is likely already compiled.
if not BuildDependencies(cancellationToken,packageCompiler, projectPackageGraph, packagesToCompile, compiledPackages, packageSpecs, options) then
exit;
if not CollectSearchPaths(projectPackageGraph, resolvedPackages, compiledPackages, projectEditor.CompilerVersion, platform, packageSearchPaths) then
exit;
if not projectEditor.AddSearchPaths(platform, packageSearchPaths, config.PackageCacheLocation) then
exit;
projectEditor.UpdatePackageReferences(projectPackageGraph, platform);
result := projectEditor.SaveProject();
end;
function TPackageInstaller.BuildDependencies(const cancellationToken : ICancellationToken; const packageCompiler : ICompiler; const projectPackageGraph : IGraphNode; const packagesToCompile : IList<IPackageInfo>;
const compiledPackages : IList<IPackageInfo>; packageSpecs : IDictionary<string, IPackageSpec>; const options : TSearchOptions) : boolean;
begin
result := false;
try
//build the dependency graph in the correct order.
projectPackageGraph.VisitDFS(
procedure(const node : IGraphNode)
var
pkgInfo : IPackageInfo;
spec : IPackageSpec;
otherNodes : IList<IGraphNode>;
forceCompile : boolean;
begin
Assert(node.IsRoot = false, 'graph should not visit root node');
pkgInfo := packagesToCompile.FirstOrDefault(
function(const value : IPackageInfo) : boolean
begin
result := SameText(value.Id, node.Id);
end);
//if it's not found that means we have already processed the package elsewhere in the graph
if pkgInfo = nil then
exit;
//do we need an option to force compilation when restoring?
forceCompile := options.force and SameText(pkgInfo.Id, options.SearchTerms); //searchterms backs packageid
//removing it so we don't process it again
packagesToCompile.Remove(pkgInfo);
spec := packageSpecs[LowerCase(node.Id)];
Assert(spec <> nil);
if spec.TargetPlatform.BuildEntries.Any then
begin
//we need to build the package.
if not CompilePackage(cancellationToken, packageCompiler, pkgInfo, node, spec, forceCompile) then
begin
if cancellationToken.IsCancelled then
raise Exception.Create('Compiling package [' + pkgInfo.ToIdVersionString + '] cancelled.' )
else
raise Exception.Create('Compiling package [' + pkgInfo.ToIdVersionString + '] failed.' );
end;
compiledPackages.Add(pkgInfo);
//compiling updates the node searchpaths and libpath, so just copy to any same package nodes
otherNodes := projectPackageGraph.FindNodes(node.Id);
if otherNodes.Count > 1 then
otherNodes.ForEach(procedure(const otherNode : IGraphNode)
begin
otherNode.SearchPaths.Clear;
otherNode.SearchPaths.AddRange(node.SearchPaths);
otherNode.LibPath := node.LibPath;
otherNode.BplPath := node.BplPath;
end);
end;
if spec.TargetPlatform.DesignFiles.Any then
begin
//we have design time packages to install.
end;
end);
result := true;
except
on e : Exception do
begin
FLogger.Error(e.Message);
exit;
end;
end;
end;
(*
function TPackageInstaller.DoUninstallFromProject(const cancellationToken: ICancellationToken; const options: TUnInstallOptions; const projectFile: string;
const projectEditor: IProjectEditor; const platform: TDPMPlatform; const config: IConfiguration): boolean;
var
packageReference : IGraphNode;
packageReferences : IList<IGraphNode>;
projectPackageInfos : IList<IPackageInfo>;
projectPackageInfo : IPackageInfo;
resolvedPackages : IList<IPackageInfo>;
compiledPackages : IList<IPackageInfo>;
packageSpecs : IDictionary<string, IPackageSpec>;
packageSearchPaths : IList<string>;
conflictDetect : IDictionary<string, TPackageVersion>;
dependencyGraph : IGraphNode;
projectReferences : IList<TProjectReference>;
foundReference : IGraphNode;
begin
result := false;
//get the packages already referenced by the project for the platform
packageReferences := TCollections.CreateList<IGraphNode>;
conflictDetect := TCollections.CreateDictionary < string, TPackageVersion > ;
dependencyGraph := TGraphNode.CreateRoot(options.CompilerVersion, platform);
foundReference := nil;
for packageReference in projectEditor.PackageReferences.Where(
function(const packageReference : IGraphNode) : boolean
begin
result := platform = packageReference.Platform;
end) do
begin
if not SameText(packageReference.Id, options.PackageId) then
begin
BuildGraph(packageReference, dependencyGraph);
AddPackageReference(packageReference, packageReferences, conflictDetect);
end
else
foundReference := packageReference;
end;
if foundReference = nil then
begin
FLogger.Information('Package [' + options.PackageId + '] was not referenced in project [' + projectFile + '] for platform [' + DPMPlatformToString(platform) + '] - nothing to do.');
//TODO : Should this fail with an error? It's a noop
exit(true);
end;
projectEditor.PackageReferences.Remove(foundReference);
//NOTE : Even though there might be no package references after this, we still need to do the restore process to update search paths etc.
projectPackageInfos := TCollections.CreateList<IPackageInfo>;
for packageReference in packageReferences do
begin
projectPackageInfo := GetPackageInfo(cancellationToken, packageReference);
if projectPackageInfo = nil then
begin
FLogger.Error('Unable to resolve package : ' + packageReference.ToString);
exit;
end;
projectPackageInfos.Add(projectPackageInfo);
end;
projectReferences := TCollections.CreateList<TProjectReference>;
if packageReferences.Any then
projectReferences.AddRange(TEnumerable.Select<IPackageInfo, TProjectReference>(projectPackageInfos,
function(const info : IPackageInfo) : TProjectReference
var
node : IGraphNode;
parentNode : IGraphNode;
begin
result.Package := info;
node := dependencyGraph.FindFirstNode(info.Id);
if node <> nil then
begin
result.VersionRange := node.SelectedOn;
parentNode := node.Parent;
result.ParentId := parentNode.Id;
end
else
begin
result.VersionRange := TVersionRange.Empty;
result.ParentId := 'root';
end;
end));
//NOTE : The resolver may modify the graph.
result := FDependencyResolver.ResolveForRestore(cancellationToken, options, projectReferences, dependencyGraph, options.CompilerVersion, platform, resolvedPackages);
if not result then
exit;
if resolvedPackages = nil then
begin
FLogger.Error('Resolver returned no packages!');
exit(false);
end;
if resolvedPackages.Any then
begin
for projectPackageInfo in resolvedPackages do
begin
FLogger.Information('Resolved : ' + projectPackageInfo.ToIdVersionString);
end;
result := DownloadPackages(cancellationToken, resolvedPackages, packageSpecs );
if not result then
exit;
end;
//TODO : Detect if anything has actually changed and only do this if we need to
packageSearchPaths := TCollections.CreateList <string> ;
if not CollectSearchPaths(resolvedPackages, compiledPackages, projectEditor.CompilerVersion, platform, packageSearchPaths) then
exit;
if not projectEditor.AddSearchPaths(platform, packageSearchPaths, config.PackageCacheLocation) then
exit;
packageReferences.Clear;
GeneratePackageReferences(dependencyGraph, nil, packageReferences, options.CompilerVersion, platform);
projectEditor.UpdatePackageReferences(packageReferences, platform);
result := projectEditor.SaveProject();
end;
*)
function TPackageInstaller.DownloadPackages(const cancellationToken : ICancellationToken; const resolvedPackages : IList<IPackageInfo>; var packageSpecs : IDictionary<string, IPackageSpec>) : boolean;
var
packageInfo : IPackageInfo;
packageFileName : string;
spec : IPackageSpec;
begin
result := false;
packageSpecs := TCollections.CreateDictionary<string, IPackageSpec>;
for packageInfo in resolvedPackages do
begin
if cancellationToken.IsCancelled then
exit;
if not FPackageCache.EnsurePackage(packageInfo) then
begin
//not in the cache, so we need to get it from the the repository
if not FRepositoryManager.DownloadPackage(cancellationToken, packageInfo, FPackageCache.PackagesFolder, packageFileName) then
begin
FLogger.Error('Failed to download package [' + packageInfo.ToString + ']');
exit;
end;
if not FPackageCache.InstallPackageFromFile(packageFileName, true) then
begin
FLogger.Error('Failed to install package file [' + packageFileName + '] into the cache');
exit;
end;
if cancellationToken.IsCancelled then
exit;
end;
if not packageSpecs.ContainsKey(LowerCase(packageInfo.Id)) then
begin
spec := FPackageCache.GetPackageSpec(packageInfo);
packageSpecs[LowerCase(packageInfo.Id)] := spec;
end;
end;
result := true;
end;
function TPackageInstaller.InstallPackage(const cancellationToken : ICancellationToken; const options : TInstallOptions; const projectFile : string; const config : IConfiguration) : boolean;
var
projectEditor : IProjectEditor;
platforms : TDPMPlatforms;
platform : TDPMPlatform;
platformResult : boolean;
ambiguousProjectVersion : boolean;
ambiguousVersions : string;
begin
result := false;
//make sure we can parse the dproj
projectEditor := TProjectEditor.Create(FLogger, config, options.CompilerVersion);
if not projectEditor.LoadProject(projectFile) then
begin
FLogger.Error('Unable to load project file, cannot continue');
exit;
end;
ambiguousProjectVersion := IsAmbigousProjectVersion(projectEditor.ProjectVersion, ambiguousVersions);
if ambiguousProjectVersion and (options.CompilerVersion = TCompilerVersion.UnknownVersion) then
FLogger.Warning('ProjectVersion [' + projectEditor.ProjectVersion + '] is ambiguous (' + ambiguousVersions +'), recommend specifying compiler version on command line.');
//if the compiler version was specified (either on the command like or through a package file)
//then make sure our dproj is actually for that version.
if options.CompilerVersion <> TCompilerVersion.UnknownVersion then
begin
if projectEditor.CompilerVersion <> options.CompilerVersion then
begin
if not ambiguousProjectVersion then
FLogger.Warning('ProjectVersion [' + projectEditor.ProjectVersion + '] does not match the compiler version.');
projectEditor.CompilerVersion := options.CompilerVersion;
end;
end
else
options.CompilerVersion := projectEditor.CompilerVersion;
//if the platform was specified (either on the command like or through a package file)
//then make sure our dproj is actually for that platform.
if options.Platforms <> [] then
begin
platforms := options.Platforms * projectEditor.Platforms; //gets the intersection of the two sets.
if platforms = [] then //no intersection
begin
FLogger.Warning('Skipping project file [' + projectFile + '] as it does not match target specified platforms.');
exit;
end;
//TODO : what if only some of the platforms are supported, what should we do?
end
else
platforms := projectEditor.Platforms;
result := true;
for platform in platforms do
begin
if cancellationToken.IsCancelled then
exit;
options.Platforms := [platform];
FLogger.Information('Installing [' + options.SearchTerms + '-' + DPMPlatformToString(platform) + '] into [' + projectFile + ']', true);
platformResult := DoInstallPackage(cancellationToken, options, projectFile, projectEditor, platform, config);
if not platformResult then
FLogger.Error('Install failed for [' + options.SearchTerms + '-' + DPMPlatformToString(platform) + ']')
else
FLogger.Success('Install succeeded for [' + options.SearchTerms + '-' + DPMPlatformToString(platform) + ']', true);
result := platformResult and result;
FLogger.Information('');
end;
//TODO : collect errored platforms so we can list them here!
if not result then
FLogger.Error('Install failed for [' + options.SearchTerms + '] on 1 or more platforms')
end;
procedure TPackageInstaller.GenerateSearchPaths(const compilerVersion: TCompilerVersion; const platform: TDPMPlatform; packageSpec: IPackageSpec;
const searchPaths: IList<string>);
var
packageBasePath : string;
packageSearchPath : ISpecSearchPath;
begin
packageBasePath := packageSpec.MetaData.Id + PathDelim + packageSpec.MetaData.Version.ToStringNoMeta + PathDelim;
for packageSearchPath in packageSpec.TargetPlatform.SearchPaths do
searchPaths.Add(packageBasePath + packageSearchPath.Path);
end;
function TPackageInstaller.GetCompilerVersionFromProjectFiles(const options : TInstallOptions; const projectFiles : TArray <string> ; const config : IConfiguration) : boolean;
var
projectFile : string;
projectEditor : IProjectEditor;
compilerVersion : TCompilerVersion;
bFirst : boolean;
begin
result := true;
compilerVersion := TCompilerVersion.UnknownVersion;
bFirst := true;
for projectFile in projectFiles do
begin
projectEditor := TProjectEditor.Create(FLogger, config, options.CompilerVersion);
result := result and projectEditor.LoadProject(projectFile);
if result then
begin
if not bFirst then
begin
if projectEditor.CompilerVersion <> compilerVersion then
begin
FLogger.Error('Projects are not all the for same compiler version.');
result := false;
end;
end;
compilerVersion := options.CompilerVersion;
options.CompilerVersion := projectEditor.CompilerVersion;
bFirst := false;
end;
end;
end;
function TPackageInstaller.Install(const cancellationToken : ICancellationToken; const options : TInstallOptions) : Boolean;
var
projectFiles : TArray<string>;
config : IConfiguration;
groupProjReader : IGroupProjectReader;
projectList : IList<string>;
i : integer;
projectRoot : string;
begin
result := false;
try
if (not options.Validated) and (not options.Validate(FLogger)) then
exit
else if not options.IsValid then
exit;
config := FConfigurationManager.LoadConfig(options.ConfigFile);
if config = nil then
exit;
FPackageCache.Location := config.PackageCacheLocation;
if not FRepositoryManager.Initialize(config) then
begin
FLogger.Error('Unable to initialize the repository manager.');
exit;
end;
if not FRepositoryManager.HasSources then
begin
FLogger.Error('No package sources are defined. Use `dpm sources add` command to add a package source.');
exit;
end;
if FileExists(options.ProjectPath) then
begin
if ExtractFileExt(options.ProjectPath) = '.groupproj' then
begin
groupProjReader := TGroupProjectReader.Create(FLogger);
if not groupProjReader.LoadGroupProj(options.ProjectPath) then
exit;
projectList := TCollections.CreateList <string> ;
if not groupProjReader.ExtractProjects(projectList) then
exit;
//projects in a project group are likely to be relative, so make them full paths
projectRoot := ExtractFilePath(options.ProjectPath);
for i := 0 to projectList.Count - 1 do
begin
//sysutils.IsRelativePath returns false with paths starting with .\
if TPathUtils.IsRelativePath(projectList[i]) then
//TPath.Combine really should do this but it doesn't
projectList[i] := TPathUtils.CompressRelativePath(projectRoot, projectList[i])
end;
projectFiles := projectList.ToArray;
end
else
begin
SetLength(projectFiles, 1);
projectFiles[0] := options.ProjectPath;
end;
end
else if DirectoryExists(options.ProjectPath) then
begin
projectFiles := TArray <string> (TDirectory.GetFiles(options.ProjectPath, '*.dproj'));
if Length(projectFiles) = 0 then
begin
FLogger.Error('No dproj files found in projectPath : ' + options.ProjectPath);
exit;
end;
FLogger.Information('Found ' + IntToStr(Length(projectFiles)) + ' dproj file(s) to install into.');
end
else
begin
//should never happen when called from the commmand line, but might from the IDE plugin.
FLogger.Error('The projectPath provided does no exist, no project to install to');
exit;
end;
if options.PackageFile <> '' then
begin
if not FileExists(options.PackageFile) then
begin
//should never happen if validation is called on the options.
FLogger.Error('The specified packageFile [' + options.PackageFile + '] does not exist.');
exit;
end;
result := InstallPackageFromFile(cancellationToken, options, TArray <string> (projectFiles), config);
end
else
result := InstallPackageFromId(cancellationToken, options, TArray <string> (projectFiles), config);
except
on e : Exception do
begin
FLogger.Error(e.Message);
result := false;
end;
end;
end;
function TPackageInstaller.InstallPackageFromFile(const cancellationToken : ICancellationToken; const options : TInstallOptions; const projectFiles : TArray <string> ; const config : IConfiguration) : boolean;
var
packageIdString : string;
packageIdentity : IPackageIdentity;
projectFile : string;
i : integer;
begin
//get the package into the cache first then just install as normal
result := FPackageCache.InstallPackageFromFile(options.PackageFile, true);
if not result then
exit;
//get the identity so we can get the compiler version
packageIdString := ExtractFileName(options.PackageFile);
packageIdString := ChangeFileExt(packageIdString, '');
if not TPackageIdentity.TryCreateFromString(FLogger, packageIdString, '', packageIdentity) then
exit;
//update options so we can install from the packageid.
options.PackageFile := '';
options.PackageId := packageIdentity.Id + '.' + packageIdentity.Version.ToStringNoMeta;
options.CompilerVersion := packageIdentity.CompilerVersion; //package file is for single compiler version
options.Platforms := [packageIdentity.Platform]; //package file is for single platform.
FContext.Reset;
try
for i := 0 to Length(projectFiles) -1 do
begin
if cancellationToken.IsCancelled then
exit;
if TPathUtils.IsRelativePath(projectFile) then
begin
projectFile := TPath.Combine(GetCurrentDir, projectFile);
projectFile := TPathUtils.CompressRelativePath(projectFile);
end;
result := InstallPackage(cancellationToken, options, projectFile, config) and result;
end;
finally
FContext.Reset; //free up memory as this might be used in the IDE
end;
end;
function TPackageInstaller.InstallPackageFromId(const cancellationToken : ICancellationToken; const options : TInstallOptions; const projectFiles : TArray <string> ; const config : IConfiguration) : boolean;
var
projectFile : string;
i : integer;
begin
result := true;
FContext.Reset;
try
for i := 0 to Length(projectFiles) - 1 do
begin
if cancellationToken.IsCancelled then
exit;
projectFile := projectFiles[0];
if TPathUtils.IsRelativePath(projectFile) then
begin
projectFile := TPath.Combine(GetCurrentDir, projectFile);
projectFile := TPathUtils.CompressRelativePath(projectFile);
end;
result := InstallPackage(cancellationToken, options, projectFile, config) and result;
end;
finally
FContext.Reset;
end;
end;
function TPackageInstaller.Remove(const cancellationToken : ICancellationToken; const options : TUninstallOptions) : boolean;
begin
result := false;
end;
function TPackageInstaller.Restore(const cancellationToken : ICancellationToken; const options : TRestoreOptions) : Boolean;
var
projectFiles : TArray<string>;
projectFile : string;
config : IConfiguration;
groupProjReader : IGroupProjectReader;
projectList : IList<string>;
i : integer;
projectRoot : string;
begin
result := false;
try
//commandline would have validated already, but IDE probably not.
if (not options.Validated) and (not options.Validate(FLogger)) then
exit
else if not options.IsValid then
exit;
config := FConfigurationManager.LoadConfig(options.ConfigFile);
if config = nil then //no need to log, config manager will
exit;
FPackageCache.Location := config.PackageCacheLocation;
if not FRepositoryManager.Initialize(config) then
begin
FLogger.Error('Unable to initialize the repository manager.');
exit;
end;
if not FRepositoryManager.HasSources then
begin
FLogger.Error('No package sources are defined. Use `dpm sources add` command to add a package source.');
exit;
end;
if FileExists(options.ProjectPath) then
begin
//TODO : If we are using a groupProj then we shouldn't allow different versions of a package in different projects
//need to work out how to detect this.
if ExtractFileExt(options.ProjectPath) = '.groupproj' then
begin
groupProjReader := TGroupProjectReader.Create(FLogger);
if not groupProjReader.LoadGroupProj(options.ProjectPath) then
exit;
projectList := TCollections.CreateList <string> ;
if not groupProjReader.ExtractProjects(projectList) then
exit;
//projects in a project group are likely to be relative, so make them full paths
projectRoot := ExtractFilePath(options.ProjectPath);
for i := 0 to projectList.Count - 1 do
begin
//sysutils.IsRelativePath returns false with paths starting with .\
if TPathUtils.IsRelativePath(projectList[i]) then
//TPath.Combine really should do this but it doesn't
projectList[i] := TPathUtils.CompressRelativePath(projectRoot, projectList[i])
end;
projectFiles := projectList.ToArray;
end
else
begin
SetLength(projectFiles, 1);
projectFiles[0] := options.ProjectPath;
end;
end
else if DirectoryExists(options.ProjectPath) then
begin
//todo : add groupproj support!
projectFiles := TArray <string> (TDirectory.GetFiles(options.ProjectPath, '*.dproj'));
if Length(projectFiles) = 0 then
begin
FLogger.Error('No project files found in projectPath : ' + options.ProjectPath);
exit;
end;
FLogger.Information('Found ' + IntToStr(Length(projectFiles)) + ' project file(s) to restore.');
end
else
begin
//should never happen when called from the commmand line, but might from the IDE plugin.
FLogger.Error('The projectPath provided does no exist, no project to install to');
exit;
end;
result := true;
//TODO : create some sort of context object here to pass in so we can collect runtime/design time packages
for i := 0 to Length(projectFiles) -1 do
begin
if cancellationToken.IsCancelled then
exit;
projectFile := projectFiles[i];
if TPathUtils.IsRelativePath(projectFile) then
begin
projectFile := TPath.Combine(GetCurrentDir, projectFile);
projectFile := TPathUtils.CompressRelativePath(projectFile);
end;
result := RestoreProject(cancellationToken, options, projectFile, config) and result;
end;
except
on e : Exception do
begin
FLogger.Error(e.Message);
result := false;
end;
end;
end;
function TPackageInstaller.RestoreProject(const cancellationToken : ICancellationToken; const options : TRestoreOptions; const projectFile : string; const config : IConfiguration) : Boolean;
var
projectEditor : IProjectEditor;
platforms : TDPMPlatforms;
platform : TDPMPlatform;
platformResult : boolean;
ambiguousProjectVersion : boolean;
ambiguousVersions : string;
begin
result := false;
//make sure we can parse the dproj
projectEditor := TProjectEditor.Create(FLogger, config, options.CompilerVersion);
if not projectEditor.LoadProject(projectFile) then
begin
FLogger.Error('Unable to load project file, cannot continue');
exit;
end;
if cancellationToken.IsCancelled then
exit;
ambiguousProjectVersion := IsAmbigousProjectVersion(projectEditor.ProjectVersion, ambiguousVersions);
if ambiguousProjectVersion and (options.CompilerVersion = TCompilerVersion.UnknownVersion) then
FLogger.Warning('ProjectVersion [' + projectEditor.ProjectVersion + '] is ambiguous (' + ambiguousVersions +'), recommend specifying compiler version on command line.');
//if the compiler version was specified (either on the command like or through a package file)
//then make sure our dproj is actually for that version.
if options.CompilerVersion <> TCompilerVersion.UnknownVersion then
begin
if projectEditor.CompilerVersion <> options.CompilerVersion then
begin
if not ambiguousProjectVersion then
FLogger.Warning('ProjectVersion [' + projectEditor.ProjectVersion + '] does not match the compiler version.');
projectEditor.CompilerVersion := options.CompilerVersion;
end;
end
else
options.CompilerVersion := projectEditor.CompilerVersion;
FLogger.Information('Restoring for compiler version [' + CompilerToString(options.CompilerVersion) + '].', true);
//if the platform was specified (either on the command like or through a package file)
//then make sure our dproj is actually for that platform.
if options.Platforms <> [] then
begin
platforms := options.Platforms * projectEditor.Platforms; //gets the intersection of the two sets.
if platforms = [] then //no intersection
begin
FLogger.Warning('Skipping project file [' + projectFile + '] as it does not match specified platforms.');
exit;
end;
//TODO : what if only some of the platforms are supported, what should we do?
end
else
platforms := projectEditor.Platforms;
result := true;
for platform in platforms do
begin
if cancellationToken.IsCancelled then
exit(false);
options.Platforms := [platform];
FLogger.Information('Restoring project [' + projectFile + '] for [' + DPMPlatformToString(platform) + ']', true);
platformResult := DoRestoreProject(cancellationToken, options, projectFile, projectEditor, platform, config);
if not platformResult then
begin
if cancellationToken.IsCancelled then
FLogger.Error('Restore Cancelled.')
else
FLogger.Error('Restore failed for ' + DPMPlatformToString(platform))
end
else
FLogger.Success('Restore succeeded for ' + DPMPlatformToString(platform), true);
result := platformResult and result;
FLogger.Information('');
end;
end;
function TPackageInstaller.UnInstall(const cancellationToken: ICancellationToken; const options: TUnInstallOptions): boolean;
var
projectFiles : TArray<string>;
projectFile : string;
config : IConfiguration;
groupProjReader : IGroupProjectReader;
projectList : IList<string>;
i : integer;
projectRoot : string;
begin
result := false;
//commandline would have validated already, but IDE probably not.
if (not options.Validated) and (not options.Validate(FLogger)) then
exit
else if not options.IsValid then
exit;
config := FConfigurationManager.LoadConfig(options.ConfigFile);
if config = nil then //no need to log, config manager will
exit;
FPackageCache.Location := config.PackageCacheLocation;
if not FRepositoryManager.Initialize(config) then
begin
FLogger.Error('Unable to initialize the repository manager.');
exit;
end;
if FileExists(options.ProjectPath) then
begin
//TODO : If we are using a groupProj then we shouldn't allow different versions of a package in different projects
//need to work out how to detect this.
if ExtractFileExt(options.ProjectPath) = '.groupproj' then
begin
groupProjReader := TGroupProjectReader.Create(FLogger);
if not groupProjReader.LoadGroupProj(options.ProjectPath) then
exit;
projectList := TCollections.CreateList <string> ;
if not groupProjReader.ExtractProjects(projectList) then
exit;
//projects in a project group are likely to be relative, so make them full paths
projectRoot := ExtractFilePath(options.ProjectPath);
for i := 0 to projectList.Count - 1 do
begin
//sysutils.IsRelativePath returns false with paths starting with .\
if TPathUtils.IsRelativePath(projectList[i]) then
//TPath.Combine really should do this but it doesn't
projectList[i] := TPathUtils.CompressRelativePath(projectRoot, projectList[i])
end;
projectFiles := projectList.ToArray;
end
else
begin
SetLength(projectFiles, 1);
projectFiles[0] := options.ProjectPath;
end;
end
else if DirectoryExists(options.ProjectPath) then
begin
//todo : add groupproj support!
projectFiles := TArray <string> (TDirectory.GetFiles(options.ProjectPath, '*.dproj'));
if Length(projectFiles) = 0 then
begin
FLogger.Error('No project files found in projectPath : ' + options.ProjectPath);
exit;
end;
FLogger.Information('Found ' + IntToStr(Length(projectFiles)) + ' project file(s) to uninstall from.');
end
else
begin
//should never happen when called from the commmand line, but might from the IDE plugin.
FLogger.Error('The projectPath provided does no exist, no project to install to');
exit;
end;
result := true;
//TODO : create some sort of context object here to pass in so we can collect runtime/design time packages
for projectFile in projectFiles do
begin
if cancellationToken.IsCancelled then
exit;
result := UnInstallFromProject(cancellationToken, options, projectFile, config) and result;
end;
end;
function TPackageInstaller.UnInstallFromProject(const cancellationToken: ICancellationToken; const options: TUnInstallOptions; const projectFile: string; const config: IConfiguration): Boolean;
var
projectEditor : IProjectEditor;
platforms : TDPMPlatforms;
platform : TDPMPlatform;
platformResult : boolean;
ambiguousProjectVersion : boolean;
ambiguousVersions : string;
begin
result := false;
//make sure we can parse the dproj
projectEditor := TProjectEditor.Create(FLogger, config, options.CompilerVersion);
if not projectEditor.LoadProject(projectFile) then
begin
FLogger.Error('Unable to load project file, cannot continue');
exit;
end;
if cancellationToken.IsCancelled then
exit;
ambiguousProjectVersion := IsAmbigousProjectVersion(projectEditor.ProjectVersion, ambiguousVersions);
if ambiguousProjectVersion and (options.CompilerVersion = TCompilerVersion.UnknownVersion) then
FLogger.Warning('ProjectVersion [' + projectEditor.ProjectVersion + '] is ambiguous (' + ambiguousVersions +'), recommend specifying compiler version on command line.');
//if the compiler version was specified (either on the command like or through a package file)
//then make sure our dproj is actually for that version.
if options.CompilerVersion <> TCompilerVersion.UnknownVersion then
begin
if projectEditor.CompilerVersion <> options.CompilerVersion then
begin
if not ambiguousProjectVersion then
FLogger.Warning('ProjectVersion [' + projectEditor.ProjectVersion + '] does not match the compiler version.');
projectEditor.CompilerVersion := options.CompilerVersion;
end;
end
else
options.CompilerVersion := projectEditor.CompilerVersion;
FLogger.Information('Uninstalling for compiler version [' + CompilerToString(options.CompilerVersion) + '].',true);
//if the platform was specified (either on the command like or through a package file)
//then make sure our dproj is actually for that platform.
if options.Platforms <> [] then
begin
platforms := options.Platforms * projectEditor.Platforms; //gets the intersection of the two sets.
if platforms = [] then //no intersection
begin
FLogger.Warning('Skipping project file [' + projectFile + '] as it does not match specified platforms.');
exit;
end;
//TODO : what if only some of the platforms are supported, what should we do?
end
else
platforms := projectEditor.Platforms;
result := true;
for platform in platforms do
begin
if cancellationToken.IsCancelled then
exit(false);
options.Platforms := [platform];
FLogger.Information('Uninstalling from project [' + projectFile + '] for [' + DPMPlatformToString(platform) + ']', true);
platformResult := DoUninstallFromProject(cancellationToken, options, projectFile, projectEditor, platform, config);
if not platformResult then
FLogger.Error('Uninstall failed for ' + DPMPlatformToString(platform))
else
FLogger.Success('Uninstall succeeded for ' + DPMPlatformToString(platform), true);
result := platformResult and result;
FLogger.Information('');
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.