text stringlengths 14 6.51M |
|---|
{*******************************************************}
{ }
{ EhLib v7.0 }
{ Register object that sort data in }
{ TADODataSet, TADOQuery }
{ (Build 7.0.03) }
{ }
{ Copyright (c) 2002, 2013 by Dmitry V. Bolshakov }
{ }
{*******************************************************}
{*******************************************************}
{ Add this unit to 'uses' clause of any unit of your }
{ project to allow TDBGridEh to sort data in }
{ TADOQuery automatically after sorting markers }
{ will be changed. }
{ TSQLDatasetFeaturesEh will try to find line in }
{ TADOQuery.SQL string that begin from 'ORDER BY' phrase}
{ and replace line by 'ORDER BY FieldNo1 [DESC],....' }
{ using SortMarkedColumns. }
{*******************************************************}
unit EhLibADO;
{$I EhLib.Inc}
interface
uses
DbUtilsEh, ADODB, DB, DBGridEh, ToolCtrlsEh;
implementation
uses Classes;
//type
// TADODataSetCr ack = class(TADODataSet);
function ADODataSetDriverName(DataSet: TADODataSet): String;
begin
if Assigned(DataSet.Connection) and
((Pos(WideString('SQLOLEDB'),DataSet.Connection.Provider)=1) or
(Pos(WideString('SQLNCLI'),DataSet.Connection.Provider)=1))
then
Result := 'MSSQL'
else
Result := 'MSACCESS';
end;
function DateValueToADOSQLStringProc(DataSet: TDataSet; Value: Variant): String;
begin
Result := DateValueToDataBaseSQLString(ADODataSetDriverName(TADODataSet(DataSet)), Value)
end;
type
TADOSQLDatasetFeaturesEh = class(TSQLDatasetFeaturesEh)
public
function NullComparisonSyntax(AGrid: TCustomDBGridEh; DataSet: TDataSet): TNullComparisonSyntaxEh; override;
procedure ApplySorting(Sender: TObject; DataSet: TDataSet; IsReopen: Boolean); override;
procedure SortDataInADODataSet(Grid: TCustomDBGridEh; DataSet: TCustomADODataSet);
constructor Create; override;
end;
TADOCommandTextDatasetFeaturesEh = class(TCommandTextDatasetFeaturesEh)
public
function NullComparisonSyntax(AGrid: TCustomDBGridEh; DataSet: TDataSet): TNullComparisonSyntaxEh; override;
procedure ApplySorting(Sender: TObject; DataSet: TDataSet; IsReopen: Boolean); override;
procedure SortDataInADODataSet(Grid: TCustomDBGridEh; DataSet: TCustomADODataSet);
constructor Create; override;
end;
//implementation
{ TADOSQLDatasetFeaturesEh }
procedure TADOSQLDatasetFeaturesEh.ApplySorting(Sender: TObject;
DataSet: TDataSet; IsReopen: Boolean);
begin
if Sender is TCustomDBGridEh then
if TCustomDBGridEh(Sender).SortLocal then
SortDataInADODataSet(TCustomDBGridEh(Sender), TCustomADODataSet(DataSet))
else
inherited ApplySorting(Sender, DataSet, IsReopen);
end;
constructor TADOSQLDatasetFeaturesEh.Create;
begin
inherited Create;
DateValueToSQLString := DateValueToADOSQLStringProc;
SupportsLocalLike := True;
end;
function TADOSQLDatasetFeaturesEh.NullComparisonSyntax(
AGrid: TCustomDBGridEh; DataSet: TDataSet): TNullComparisonSyntaxEh;
begin
if AGrid.STFilter.Local
then Result := ncsAsEqualToNullEh
else Result := ncsAsIsNullEh;
end;
procedure TADOSQLDatasetFeaturesEh.SortDataInADODataSet(
Grid: TCustomDBGridEh; DataSet: TCustomADODataSet);
begin
DataSet.Sort := BuildSortingString(Grid, DataSet);
end;
{ TADOCommandTextDatasetFeaturesEh }
procedure TADOCommandTextDatasetFeaturesEh.ApplySorting(Sender: TObject;
DataSet: TDataSet; IsReopen: Boolean);
begin
if Sender is TCustomDBGridEh then
if TCustomDBGridEh(Sender).SortLocal then
SortDataInADODataSet(TCustomDBGridEh(Sender), TCustomADODataSet(DataSet))
else
inherited ApplySorting(Sender, DataSet, IsReopen);
end;
constructor TADOCommandTextDatasetFeaturesEh.Create;
begin
inherited Create;
DateValueToSQLString := DateValueToADOSQLStringProc;
SupportsLocalLike := True;
end;
function TADOCommandTextDatasetFeaturesEh.NullComparisonSyntax(
AGrid: TCustomDBGridEh; DataSet: TDataSet): TNullComparisonSyntaxEh;
begin
if AGrid.STFilter.Local
then Result := ncsAsEqualToNullEh
else Result := ncsAsIsNullEh;
end;
procedure TADOCommandTextDatasetFeaturesEh.SortDataInADODataSet(
Grid: TCustomDBGridEh; DataSet: TCustomADODataSet);
begin
DataSet.Sort := BuildSortingString(Grid, DataSet);
end;
initialization
RegisterDatasetFeaturesEh(TADOSQLDatasetFeaturesEh, TADOQuery);
RegisterDatasetFeaturesEh(TADOCommandTextDatasetFeaturesEh, TCustomADODataSet);
end.
|
// RemObjects CS to Pascal 0.1
namespace UT3Bots.UTItems;
interface
uses
System,
System.Collections.Generic,
System.Linq,
System.Text,
UT3Bots.Communications;
type
UTBotOppState = public class(UTBotState)
private
//Opponent state variables
var _isReachable: Boolean;
var _ammoCount: Integer;
var _lastChatMessage: String := '';
var _lastUpdated: DateTime;
assembly
property CurrentAmmo: Integer read get_CurrentAmmo write set_CurrentAmmo;
method get_CurrentAmmo: Integer;
method set_CurrentAmmo(value: Integer);
property LastChatMessage: String read get_LastChatMessage write set_LastChatMessage;
method get_LastChatMessage: String;
method set_LastChatMessage(value: String);
property LastUpdated: DateTime read get_LastUpdated write set_LastUpdated;
method get_LastUpdated: DateTime;
method set_LastUpdated(value: DateTime);
public
constructor(Msg: Message);
/// <summary>
/// True if you can reach this bot, false if there is something between you (eg. A Pit)
/// </summary>
property IsReachable: Boolean read get_IsReachable;
method get_IsReachable: Boolean;
end;
implementation
constructor UTBotOppState(Msg: Message);
begin
if Msg.Info = InfoMessage.PLAYER_INFO then
begin
Self._id := new UTIdentifier(Msg.Arguments[0]);
Self._location := UTVector.Parse(Msg.Arguments[1]);
Self._rotation := UTVector.Parse(Msg.Arguments[2]);
Self._velocity := UTVector.Parse(Msg.Arguments[3]);
Self._name := Msg.Arguments[4];
Self._health := Integer.Parse(Msg.Arguments[5]);
Self._armor := Integer.Parse(Msg.Arguments[6]);
Self._weapon := Msg.Arguments[7].GetAsWeaponType();
Self._firingType := FireType((Integer.Parse(Msg.Arguments[8])));
Self._mesh := BotMesh((Integer.Parse(Msg.Arguments[9])));
Self._colour := BotColor((Integer.Parse(Msg.Arguments[10])));
Self._isReachable := Boolean.Parse(Msg.Arguments[11]);
if Msg.Arguments.Length > 12 then
begin
Self._ammoCount := Integer.Parse(Msg.Arguments[12])
end;
end;
end;
method UTBotOppState.get_IsReachable: Boolean;
begin
Result := Self._isReachable;
end;
method UTBotOppState.get_CurrentAmmo: Integer;
begin
Result := Self._ammoCount;
end;
method UTBotOppState.set_CurrentAmmo(value: Integer);
begin
Self._ammoCount := value;
OnPropertyChanged('CurrentAmmo')
end;
method UTBotOppState.get_LastChatMessage: String;
begin
Result := Self._lastChatMessage;
end;
method UTBotOppState.set_LastChatMessage(value: String);
begin
Self._lastChatMessage := value;
OnPropertyChanged('LastChatMessage')
end;
method UTBotOppState.get_LastUpdated: DateTime;
begin
Result := Self._lastUpdated;
end;
method UTBotOppState.set_LastUpdated(value: DateTime);
begin
Self._lastUpdated := value;
OnPropertyChanged('LastUpdated')
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Custom ODE collider implementations.
Credits :
Heightfield collider code originally adapted from Mattias Fagerlund's
DelphiODE terrain collision demo.
Website: http://www.cambrianlabs.com/Mattias/DelphiODE
}
unit VXS.ODECustomColliders;
interface
{$I VXScene.inc}
uses
System.Classes,
System.SysUtils,
VXS.OpenGL,
ODEImport,
VXS.ODEGL,
VXS.ODEManager,
VXS.VectorGeometry,
VXS.VectorLists,
VXS.Scene,
VXS.TerrainRenderer,
VXS.Graph,
VXS.XCollection,
VXS.Context,
VXS.Texture,
VXS.Color,
VXS.RenderContextInfo,
VXS.State;
type
TContactPoint = class
public
Position,
Normal: TAffineVector;
Depth: Single;
end;
{ The custom collider is designed for generic contact handling. There is a
contact point generator for sphere, box, capped cylinder, cylinder and
cone geoms.
Once the contact points for a collision are generated the abstract Collide
function is called to generate the depth and the contact position and
normal. These points are then sorted and the deepest are applied to ODE. }
TVXODECustomCollider = class(TVXODEBehaviour)
private
FGeom: PdxGeom;
FContactList, FContactCache: TList;
FTransform: TMatrix;
FContactResolution: Single;
FRenderContacts: Boolean;
FContactRenderPoints: TAffineVectorList;
FPointSize: Single;
FContactColor: TVXColor;
protected
procedure Initialize; override;
procedure Finalize; override;
procedure WriteToFiler(writer: TWriter); override;
procedure ReadFromFiler(reader: TReader); override;
// Test a position for a collision and fill out the contact information.
function Collide(aPos: TAffineVector; var Depth: Single;
var cPos, cNorm: TAffineVector): Boolean; virtual; abstract;
// Clears the contact list so it's ready for another collision.
procedure ClearContacts;
// Add a contact point to the list for ApplyContacts to processes.
procedure AddContact(x, y, z: TdReal); overload;
procedure AddContact(pos: TAffineVector); overload;
// Sort the current contact list and apply the deepest to ODE.
function ApplyContacts(o1, o2: PdxGeom; flags: Integer;
contact: PdContactGeom; skip: Integer): Integer;
{ Set the transform used that transforms contact points generated with
AddContact. }
procedure SetTransform(ATransform: TMatrix);
procedure SetContactResolution(const Value: Single);
procedure SetRenderContacts(const Value: Boolean);
procedure SetPointSize(const Value: Single);
procedure SetContactColor(const Value: TVXColor);
public
constructor Create(AOwner: TXCollection); override;
destructor Destroy; override;
procedure Render(var rci: TVXRenderContextInfo); override;
property Geom: PdxGeom read FGeom;
published
{ Defines the resolution of the contact points created for the colliding
Geom. The number of contact points generated change base don the size
of the object and the ContactResolution. Lower values generate higher
resolution contact boundaries, and thus smoother but slower collisions. }
property ContactResolution: Single read FContactResolution write SetContactResolution;
{ Toggle contact point rendering on and off. (Rendered through the assigned
Manager.RenderPoint. }
property RenderContacts: Boolean read FRenderContacts write SetRenderContacts;
// Contact point rendering size (in pixels).
property PointSize: Single read FPointSize write SetPointSize;
// Contact point rendering color.
property ContactColor: TVXColor read FContactColor write SetContactColor;
end;
{ Add this behaviour to a TVXHeightField or TVXTerrainRenderer to enable
height based collisions for spheres, boxes, capped cylinders, cylinders and cones. }
TVXODEHeightField = class(TVXODECustomCollider)
protected
procedure WriteToFiler(writer: TWriter); override;
procedure ReadFromFiler(reader: TReader); override;
function Collide(aPos: TAffineVector; var Depth: Single;
var cPos, cNorm: TAffineVector): Boolean; override;
public
constructor Create(AOwner: TXCollection); override;
class function FriendlyName: string; override;
class function FriendlyDescription: string; override;
class function UniqueItem: Boolean; override;
class function CanAddTo(collection: TXCollection): Boolean; override;
end;
function GetODEHeightField(obj: TVXBaseSceneObject): TVXODEHeightField;
function GetOrCreateODEHeightField(obj: TVXBaseSceneObject): TVXODEHeightField;
//---------------------------------------------------------
implementation
//---------------------------------------------------------
var
vCustomColliderClass: TdGeomClass;
vCustomColliderClassNum: Integer;
function GetODEHeightField(obj: TVXBaseSceneObject): TVXODEHeightField;
begin
result := TVXODEHeightField(obj.Behaviours.GetByClass(TVXODEHeightField));
end;
function GetOrCreateODEHeightField(obj: TVXBaseSceneObject): TVXODEHeightField;
begin
result := TVXODEHeightField(obj.GetOrCreateBehaviour(TVXODEHeightField));
end;
function GetColliderFromGeom(aGeom: PdxGeom): TVXODECustomCollider;
var
temp: TObject;
begin
Result := nil;
temp := dGeomGetData(aGeom);
if Assigned(temp) then
if temp is TVXODECustomCollider then
Result := TVXODECustomCollider(temp);
end;
function ContactSort(Item1, Item2: Pointer): Integer;
var
c1, c2: TContactPoint;
begin
c1 := TContactPoint(Item1);
c2 := TContactPoint(Item2);
if c1.Depth > c2.Depth then
result := -1
else if c1.Depth = c2.Depth then
result := 0
else
result := 1;
end;
function CollideSphere(o1, o2: PdxGeom; flags: Integer;
contact: PdContactGeom; skip: Integer): Integer; cdecl;
var
Collider: TVXODECustomCollider;
i, j, res: Integer;
pos: PdVector3;
R: PdMatrix3;
rmat, mat: TMatrix;
rad, dx, dy, dz: TdReal;
begin
Result := 0;
Collider := GetColliderFromGeom(o1);
if not Assigned(Collider) then
exit;
pos := dGeomGetPosition(o2);
R := dGeomGetRotation(o2);
ODERToVXSceneMatrix(mat, R^, pos^);
Collider.SetTransform(mat);
rad := dGeomSphereGetRadius(o2);
res := Round(10 * rad / Collider.ContactResolution);
if res < 8 then
res := 8;
Collider.AddContact(0, 0, -rad);
Collider.AddContact(0, 0, rad);
rmat := CreateRotationMatrixZ(2 * Pi / res);
for i := 0 to res - 1 do
begin
mat := MatrixMultiply(rmat, mat);
Collider.SetTransform(mat);
for j := -(res div 2) + 1 to (res div 2) - 1 do
begin
dx := rad * cos(j * Pi / res);
dy := 0;
dz := rad * sin(j * Pi / res);
Collider.AddContact(dx, dy, dz);
end;
end;
Result := Collider.ApplyContacts(o1, o2, flags, contact, skip);
Collider.SetTransform(IdentityHMGMatrix);
end;
function CollideBox(o1, o2: PdxGeom; flags: Integer;
contact: PdContactGeom; skip: Integer): Integer; cdecl;
var
Collider: TVXODECustomCollider;
i, j, res: Integer;
rcpres, len1, len2: Single;
s: TdVector3;
pos: PdVector3;
R: PdMatrix3;
mat: TMatrix;
begin
Result := 0;
Collider := GetColliderFromGeom(o1);
if not Assigned(Collider) then
exit;
pos := dGeomGetPosition(o2);
R := dGeomGetRotation(o2);
ODERToVXSceneMatrix(mat, R^, pos^);
Collider.SetTransform(mat);
dGeomBoxGetLengths(o2, s);
res := Round(Sqrt(MaxFloat([s[0], s[1], s[2]])) / Collider.ContactResolution);
if res < 1 then
res := 1;
rcpres := 1 / res;
s[0] := 0.5 * s[0];
s[1] := 0.5 * s[1];
s[2] := 0.5 * s[2];
with Collider do
begin
// Corners
AddContact(s[0], s[1], s[2]);
AddContact(s[0], s[1], -s[2]);
AddContact(s[0], -s[1], s[2]);
AddContact(s[0], -s[1], -s[2]);
AddContact(-s[0], s[1], s[2]);
AddContact(-s[0], s[1], -s[2]);
AddContact(-s[0], -s[1], s[2]);
AddContact(-s[0], -s[1], -s[2]);
// Edges
for i := -(res - 1) to (res - 1) do
begin
len1 := i * rcpres * s[0];
AddContact(len1, s[1], s[2]);
AddContact(len1, s[1], -s[2]);
AddContact(len1, -s[1], s[2]);
AddContact(len1, -s[1], -s[2]);
len1 := i * rcpres * s[1];
AddContact(s[0], len1, s[2]);
AddContact(s[0], len1, -s[2]);
AddContact(-s[0], len1, s[2]);
AddContact(-s[0], len1, -s[2]);
len1 := i * rcpres * s[2];
AddContact(s[0], s[1], len1);
AddContact(s[0], -s[1], len1);
AddContact(-s[0], s[1], len1);
AddContact(-s[0], -s[1], len1);
end;
// Faces
for i := -(res - 1) to (res - 1) do
for j := -(res - 1) to (res - 1) do
begin
len1 := i * rcpres * s[0];
len2 := j * rcpres * s[1];
AddContact(len1, len2, s[2]);
AddContact(len1, len2, -s[2]);
len2 := j * rcpres * s[2];
AddContact(len1, s[1], len2);
AddContact(len1, -s[1], len2);
len1 := i * rcpres * s[1];
AddContact(s[0], len1, len2);
AddContact(-s[0], len1, len2);
end;
end;
Result := Collider.ApplyContacts(o1, o2, flags, contact, skip);
Collider.SetTransform(IdentityHMGMatrix);
end;
function CollideCapsule(o1, o2: PdxGeom; flags: Integer;
contact: PdContactGeom; skip: Integer): Integer; cdecl;
var
Collider: TVXODECustomCollider;
i, j, res: Integer;
pos: PdVector3;
R: PdMatrix3;
mat, rmat: TMatrix;
rad, len, dx, dy, dz: TdReal;
begin
Result := 0;
Collider := GetColliderFromGeom(o1);
if not Assigned(Collider) then
exit;
pos := dGeomGetPosition(o2);
R := dGeomGetRotation(o2);
ODERToVXSceneMatrix(mat, R^, pos^);
Collider.SetTransform(mat);
dGeomCapsuleGetParams(o2, rad, len);
res := Round(5 * MaxFloat(4 * rad, len) / Collider.ContactResolution);
if res < 8 then
res := 8;
rmat := CreateRotationMatrixZ(2 * Pi / res);
with Collider do
begin
AddContact(0, 0, -rad - 0.5 * len);
AddContact(0, 0, rad + 0.5 * len);
for i := 0 to res - 1 do
begin
mat := MatrixMultiply(rmat, mat);
SetTransform(mat);
for j := 0 to res do
AddContact(rad, 0, len * (j / res - 0.5));
for j := 1 to (res div 2) - 1 do
begin
dx := rad * cos(j * Pi / res);
dy := 0;
dz := rad * sin(j * Pi / res);
Collider.AddContact(dx, dy, -dz - 0.5 * len);
Collider.AddContact(dx, dy, dz + 0.5 * len);
end;
end;
end;
Result := Collider.ApplyContacts(o1, o2, flags, contact, skip);
Collider.SetTransform(IdentityHMGMatrix);
end;
function CollideCylinder(o1, o2: PdxGeom; flags: Integer;
contact: PdContactGeom; skip: Integer): Integer; cdecl;
var
Collider: TVXODECustomCollider;
i, j, res: Integer;
pos: PdVector3;
R: PdMatrix3;
mat: TMatrix;
rad, len, dx, dy: TdReal;
begin
Result := 0;
Collider := GetColliderFromGeom(o1);
if not Assigned(Collider) then
exit;
pos := dGeomGetPosition(o2);
R := dGeomGetRotation(o2);
ODERToVXSceneMatrix(mat, R^, pos^);
Collider.SetTransform(mat);
dGeomCylinderGetParams(o2, rad, len);
res := Round(5 * MaxFloat(4 * rad, len) / Collider.ContactResolution);
if res < 8 then
res := 8;
with Collider do
begin
AddContact(0, -0.5 * len, 0);
AddContact(0, 0.5 * len, 0);
for i := 0 to res - 1 do
begin
SinCosine(2 * Pi * i / res, rad, dy, dx);
AddContact(dx, -0.5 * len, dy);
AddContact(dx, 0, dy);
AddContact(dx, 0.5 * len, dy);
for j := 0 to res do
AddContact(dx, len * (j / res - 0.5), dy);
for j := 1 to (res div 2) - 1 do
begin
SinCosine(2 * Pi * i / res, rad * j / (res div 2), dy, dx);
AddContact(dx, -0.5 * len, dy);
AddContact(dx, 0.5 * len, dy);
end;
end;
end;
Result := Collider.ApplyContacts(o1, o2, flags, contact, skip);
Collider.SetTransform(IdentityHMGMatrix);
end;
function GetCustomColliderFn(num: Integer): TdColliderFn; cdecl;
begin
if num = dSphereClass then
Result := CollideSphere
else if num = dBoxClass then
Result := CollideBox
else if num = dCapsuleClass then
Result := CollideCapsule
else if num = dCylinderClass then
Result := CollideCylinder
else
Result := nil;
end;
// ---------------
// --------------- TVXODECustomCollider --------------
// ---------------
constructor TVXODECustomCollider.Create(AOwner: TXCollection);
begin
inherited;
FContactList := TList.Create;
FContactCache := TList.Create;
FContactResolution := 1;
FRenderContacts := False;
FContactRenderPoints := TAffineVectorList.Create;
FContactColor := TVXColor.CreateInitialized(Self, clrRed, NotifyChange);
FPointSize := 3;
end;
destructor TVXODECustomCollider.Destroy;
var
i: integer;
begin
FContactList.Free;
for i := 0 to FContactCache.Count - 1 do
TContactPoint(FContactCache[i]).Free;
FContactCache.Free;
FContactRenderPoints.Free;
FContactColor.Free;
inherited;
end;
procedure TVXODECustomCollider.Initialize;
begin
if not Assigned(Manager) then
exit;
if not Assigned(Manager.Space) then
exit;
if vCustomColliderClassNum = 0 then
begin
with vCustomColliderClass do
begin
bytes := 0;
collider := GetCustomColliderFn;
aabb := dInfiniteAABB;
aabb_test := nil;
dtor := nil;
end;
vCustomColliderClassNum := dCreateGeomClass(vCustomColliderClass);
end;
FGeom := dCreateGeom(vCustomColliderClassNum);
dGeomSetData(FGeom, Self);
dSpaceAdd(Manager.Space, FGeom);
inherited;
end;
procedure TVXODECustomCollider.Finalize;
begin
if not Initialized then
exit;
if Assigned(FGeom) then
begin
dGeomDestroy(FGeom);
FGeom := nil;
end;
inherited;
end;
procedure TVXODECustomCollider.WriteToFiler(writer: TWriter);
begin
inherited;
with writer do
begin
WriteInteger(0); // Archive version
WriteFloat(FContactResolution);
WriteBoolean(FRenderContacts);
WriteFloat(FPointSize);
Write(PByte(FContactColor.AsAddress)^, 4);
end;
end;
procedure TVXODECustomCollider.ReadFromFiler(reader: TReader);
var
archiveVersion: Integer;
begin
inherited;
with reader do
begin
archiveVersion := ReadInteger;
Assert(archiveVersion = 0); // Archive version
FContactResolution := ReadFloat;
FRenderContacts := ReadBoolean;
FPointSize := ReadFloat;
Read(PByte(FContactColor.AsAddress)^, 4);
end;
end;
procedure TVXODECustomCollider.ClearContacts;
begin
FContactList.Clear;
end;
procedure TVXODECustomCollider.AddContact(x, y, z: TdReal);
begin
AddContact(AffineVectorMake(x, y, z));
end;
procedure TVXODECustomCollider.AddContact(pos: TAffineVector);
var
absPos, colPos, colNorm: TAffineVector;
depth: Single;
ContactPoint: TContactPoint;
begin
absPos := AffineVectorMake(VectorTransform(PointMake(pos), FTransform));
if Collide(absPos, depth, colPos, colNorm) then
begin
if FContactList.Count < FContactCache.Count then
ContactPoint := FContactCache[FContactList.Count]
else
begin
ContactPoint := TContactPoint.Create;
FContactCache.Add(ContactPoint);
end;
ContactPoint.Position := colPos;
ContactPoint.Normal := colNorm;
ContactPoint.Depth := depth;
FContactList.Add(ContactPoint);
end;
if FRenderContacts and Manager.Visible and Manager.VisibleAtRunTime then
FContactRenderPoints.Add(absPos);
end;
function TVXODECustomCollider.ApplyContacts(o1, o2: PdxGeom;
flags: Integer; contact: PdContactGeom; skip: Integer): Integer;
var
i, maxContacts: integer;
begin
FContactList.Sort(ContactSort);
Result := 0;
maxContacts := flags and $FFFF;
try
for i := 0 to FContactList.Count - 1 do
begin
if Result >= maxContacts then
Exit;
with TContactPoint(FContactList[i]) do
begin
contact.depth := Depth;
contact.pos[0] := Position.X;
contact.pos[1] := Position.Y;
contact.pos[2] := Position.Z;
contact.pos[3] := 1;
contact.normal[0] := -Normal.X;
contact.normal[1] := -Normal.Y;
contact.normal[2] := -Normal.Z;
contact.normal[3] := 0;
end;
contact.g1 := o1;
contact.g2 := o2;
contact := PdContactGeom(Integer(contact) + skip);
Inc(Result);
end;
finally
ClearContacts;
end;
end;
procedure TVXODECustomCollider.SetTransform(ATransform: TMatrix);
begin
FTransform := ATransform;
end;
procedure TVXODECustomCollider.SetContactResolution(const Value: Single);
begin
FContactResolution := Value;
if FContactResolution <= 0 then
FContactResolution := 0.01;
end;
procedure TVXODECustomCollider.Render(var rci: TVXRenderContextInfo);
var
i: Integer;
begin
if FRenderContacts and (FContactRenderPoints.Count > 0) then
begin
glColor3fv(FContactColor.AsAddress);
rci.VXStates.PointSize := FPointSize;
glBegin(GL_POINTS);
for i := 0 to FContactRenderPoints.Count - 1 do
glVertex3fv(@FContactRenderPoints.List[i]);
glEnd;
end;
FContactRenderPoints.Clear;
end;
procedure TVXODECustomCollider.SetRenderContacts(const Value: Boolean);
begin
if Value <> FRenderContacts then
begin
FRenderContacts := Value;
NotifyChange(Self);
end;
end;
procedure TVXODECustomCollider.SetContactColor(const Value: TVXColor);
begin
FContactColor.Assign(Value);
end;
procedure TVXODECustomCollider.SetPointSize(const Value: Single);
begin
if Value <> FPointSize then
begin
FPointSize := Value;
NotifyChange(Self);
end;
end;
// ---------------
// --------------- TVXODEHeightField --------------
// ---------------
constructor TVXODEHeightField.Create(AOwner: TXCollection);
var
Allow: Boolean;
begin
Allow := False;
if Assigned(AOwner) then
begin
if Assigned(AOwner.Owner) then
begin
if ((AOwner.Owner) is TVXTerrainRenderer)
or ((AOwner.Owner) is TVXHeightField) then
Allow := True;
end;
end;
if not Allow then
raise Exception.Create('This element must be a behaviour of a TVXTerrainRenderer or TVXHeightField');
inherited Create(AOwner);
end;
procedure TVXODEHeightField.WriteToFiler(writer: TWriter);
begin
inherited;
with writer do
begin
WriteInteger(0); // Archive version
end;
end;
procedure TVXODEHeightField.ReadFromFiler(reader: TReader);
var
archiveVersion: Integer;
begin
inherited;
with reader do
begin
archiveVersion := ReadInteger;
Assert(archiveVersion = 0); // Archive version
end;
end;
class function TVXODEHeightField.FriendlyName: string;
begin
Result := 'ODE HeightField Collider';
end;
class function TVXODEHeightField.FriendlyDescription: string;
begin
Result := 'A custom ODE collider powered by it''s parent TVXTerrainRenderer or TVXHeightField';
end;
class function TVXODEHeightField.UniqueItem: Boolean;
begin
Result := True;
end;
class function TVXODEHeightField.CanAddTo(collection: TXCollection): Boolean;
begin
Result := False;
if collection is TVXBehaviours then
if Assigned(TVXBehaviours(collection).Owner) then
if (TVXBehaviours(collection).Owner is TVXHeightField)
or (TVXBehaviours(collection).Owner is TVXTerrainRenderer) then
Result := True;
end;
function TVXODEHeightField.Collide(aPos: TAffineVector;
var Depth: Single; var cPos, cNorm: TAffineVector): Boolean;
function AbsoluteToLocal(vec: TVector): TVector;
var
mat: TMatrix;
begin
if Owner.Owner is TVXHeightField then
Result := TVXHeightField(Owner.Owner).AbsoluteToLocal(vec)
else if Owner.Owner is TVXTerrainRenderer then
begin
mat := TVXTerrainRenderer(Owner.Owner).AbsoluteMatrix;
NormalizeMatrix(mat);
InvertMatrix(mat);
Result := VectorTransform(vec, mat);
end
else
Assert(False);
end;
function LocalToAbsolute(vec: TVector): TVector;
var
mat: TMatrix;
begin
if Owner.Owner is TVXHeightField then
Result := TVXHeightField(Owner.Owner).LocalToAbsolute(vec)
else if Owner.Owner is TVXTerrainRenderer then
begin
mat := TVXTerrainRenderer(Owner.Owner).AbsoluteMatrix;
NormalizeMatrix(mat);
Result := VectorTransform(vec, mat);
end
else
Assert(False);
end;
function GetHeight(pos: TVector; var height: Single): Boolean;
var
dummy1: TVector;
dummy2: TTexPoint;
begin
Result := False;
if Owner.Owner is TVXTerrainRenderer then
begin
height := TVXTerrainRenderer(Owner.Owner).InterpolatedHeight(LocalToAbsolute(pos));
Result := True;
end
else if Owner.Owner is TVXHeightField then
begin
if Assigned(TVXHeightField(Owner.Owner).OnGetHeight) then
begin
TVXHeightField(Owner.Owner).OnGetHeight(pos.X, pos.Y, height, dummy1, dummy2);
Result := True;
end;
end;
end;
const
cDelta = 0.1;
var
localPos: TVector;
height: Single;
temp1, temp2: TAffineVector;
begin
localPos := AbsoluteToLocal(PointMake(aPos));
if GetHeight(localPos, height) then
begin
Depth := height - localPos.Z;
Result := (Depth > 0);
if Result then
begin
localPos.Z := height;
cPos := AffineVectorMake(LocalToAbsolute(localPos));
temp1.X := localPos.X + cDelta;
temp1.Y := localPos.Y;
temp1.Z := localPos.Z;
GetHeight(PointMake(temp1), temp1.Z);
temp2.X := localPos.X;
temp2.Y := localPos.Y + cDelta;
temp2.Z := localPos.Z;
GetHeight(PointMake(temp2), temp2.Z);
cNorm := CalcPlaneNormal(AffineVectorMake(localPos), temp1, temp2);
cNorm := AffineVectorMake(LocalToAbsolute(VectorMake(cNorm)));
end;
end
else
Result := False;
end;
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
RegisterXCollectionItemClass(TVXODEHeightField);
// ------------------------------------------------------------------
finalization
// ------------------------------------------------------------------
UnregisterXCollectionItemClass(TVXODEHeightField);
end.
|
{******************************************************************************}
{ CnPack For Delphi/C++Builder }
{ 中国人自己的开放源码第三方开发包 }
{ (C)Copyright 2001-2017 CnPack 开发组 }
{ ------------------------------------ }
{ }
{ 本开发包是开源的自由软件,您可以遵照 CnPack 的发布协议来修 }
{ 改和重新发布这一程序。 }
{ }
{ 发布这一开发包的目的是希望它有用,但没有任何担保。甚至没有 }
{ 适合特定目的而隐含的担保。更详细的情况请参阅 CnPack 发布协议。 }
{ }
{ 您应该已经和开发包一起收到一份 CnPack 发布协议的副本。如果 }
{ 还没有,可访问我们的网站: }
{ }
{ 网站地址:http://www.cnpack.org }
{ 电子邮件:master@cnpack.org }
{ }
{******************************************************************************}
unit CnClasses;
{* |<PRE>
================================================================================
* 软件名称:开发包基础库
* 单元名称:基本类定义单元
* 单元作者:周劲羽 (zjy@cnpack.org)
* 备 注:该单元定义了组件包的基础类库
* 开发平台:PWin98SE + Delphi 5.0
* 兼容测试:PWin9X/2000/XP + Delphi 5/6
* 本 地 化:该单元中的字符串均符合本地化处理方式
* 单元标识:$Id$
* 修改记录:2003.03.02 V1.3
* 新增 TCnLockObject 类
* 2002.09.10 V1.2
* 修改TCnComponent部分方法
* 2002.07.09 V1.1
* 新增少量属性
* 2002.04.08 V1.0
* 新增TCnComponent组件基类
* 2002.01.11 V0.01Demo
* 创建单元
================================================================================
|</PRE>}
interface
{$I CnPack.inc}
uses
Windows, SysUtils, Classes, TypInfo;
type
//==============================================================================
// 用于线程同步的对象类
//==============================================================================
{ TCnLockObject }
TCnLockObject = class (TObject)
{* 用于线程同步的对象类}
private
FLock: TRTLCriticalSection;
FLockCount: Integer;
function GetLocking: Boolean;
protected
property LockCount: Integer read FLockCount;
{* 当前Lock计数,只读属性}
public
constructor Create;
{* 构造器,用于产生一个该类的实例}
destructor Destroy; override;
procedure Lock;
{* 进入临界区,为保证多线程同步而加锁,必须与Unlock成对使用}
function TryLock: Boolean;
{* 如果当前Lock计数为零,则加锁返回真,否则返回假。
如果返回真,必须在操作完成后调用UnLock释放锁}
procedure Unlock;
{* 退出临界区,释放同步锁,必须与Lock成对使用}
property Locking: Boolean read GetLocking;
{* 取当前加锁状态}
end;
//==============================================================================
// 使用 RTTI 实现了 Assign 方法的 TPersistent 类
//==============================================================================
{ TCnAssignablePersistent }
TCnAssignablePersistent = class(TPersistent)
public
procedure Assign(Source: TPersistent); override;
end;
//==============================================================================
// 使用 RTTI 实现了 Assign 方法的 TCollectionItem 类
//==============================================================================
{ TCnAssignableCollectionItem }
TCnAssignableCollectionItem = class(TCollectionItem)
public
procedure Assign(Source: TPersistent); override;
end;
//==============================================================================
// 使用 RTTI 实现了 Assign 方法的 TCollection 类
//==============================================================================
{ TCnAssignableCollection }
TCnAssignableCollection = class(TCollection)
public
procedure Assign(Source: TPersistent); override;
end;
//==============================================================================
// 带更新通知、线程安全的持久性类
//==============================================================================
{ TCnPersistent }
TCnPersistent = class(TPersistent)
{* 带更新通知,线程安全的持久性类}
private
FUpdateCount: Integer;
FOnChanging: TNotifyEvent;
FOnChange: TNotifyEvent;
FOwner: TPersistent;
FLockObject: TCnLockObject;
function GetLocking: Boolean;
function GetLockObject: TCnLockObject;
protected
function GetOwner: TPersistent; override;
procedure Changing; virtual;
{* 对象内容开始更新,如果更新计数为0,产生OnChanging事件,可重载}
procedure Changed; virtual;
{* 对象内容已变更,如果更新计数为0,产生OnChange事件,可重载}
procedure SetUpdating(Updating: Boolean); virtual;
{* 更新状态变更过程,可重载。
默认为开始更新时调用Changing,结束时调用Changed}
function IsUpdating: Boolean;
{* 当前更新计数是否大于0(正在更新)}
procedure OnChildChanging(Sender: TObject); virtual;
{* 子属性开始更新事件处理过程,可做为参数传递给TCnPersistent.Create过程
默认为产生OnChanging事件,可重载}
procedure OnChildChange(Sender: TObject); virtual;
{* 子属性已变更事件处理过程,可做为参数传递给TCnPersistent.Create过程
默认为产生OnChange事件,可重载}
property Owner: TPersistent read FOwner write FOwner;
{* 对象的所有者 }
property LockObject: TCnLockObject read GetLockObject;
{* 线程同步对象 }
public
constructor Create; overload; virtual;
{* 构造器,用于产生一个该类的实例,可重载}
constructor Create(AOwner: TPersistent); overload;
{* 构造器,参数为实例的所有者,当类直接或间接包含TCollection,并需要作为
published 属性时使用}
constructor Create(ChangeProc: TNotifyEvent); overload;
{* 构造器,参数用于给OnChange事件指定一个初始值}
constructor Create(ChangingProc, ChangeProc: TNotifyEvent); overload;
{* 构造器,参数用于给OnChanging和OnChange事件指定一个初始值}
destructor Destroy; override;
procedure BeginUpdate; virtual;
{* 开始更新,如果当前更新计数为0,自动调用Changing方法,可重载。
在对成批属性进行修改时请调用该方法,注意必须与EndUpdate成对使用}
procedure EndUpdate; virtual;
{* 结束更新,如果当前更新计数为0,自动调用Change方法,可重载。
在对成批属性修改后请调用该方法,注意必须与BeginUpdate成对使用}
procedure Lock;
{* 进入临界区,为保证多线程同步而加锁,必须与Unlock成对使用}
function TryLock: Boolean;
{* 如果当前Lock计数为零,则加锁返回真,否则返回假。
如果返回真,必须在操作完成后调用UnLock释放锁}
procedure Unlock;
{* 退出临界区,释放同步锁,必须与Lock成对使用}
property Locking: Boolean read GetLocking;
{* 取当前加锁状态}
published
property OnChanging: TNotifyEvent read FOnChanging write FOnChanging;
{* 对象开始更新事件}
property OnChange: TNotifyEvent read FOnChange write FOnChange;
{* 对象属性已变更事件}
end;
//==============================================================================
// 带Enabled的更新通知持久性类
//==============================================================================
{ TCnEnabledPersistent }
TCnEnabledPersistent = class(TCnPersistent)
{* 带Enabled的更新通知持久性类}
private
FEnabled: Boolean;
protected
procedure SetEnabled(const Value: Boolean); virtual;
procedure SetUpdating(Updating: Boolean); override;
public
constructor Create; override;
{* 构造器,用于产生一个该类的实例}
procedure Assign(Source: TPersistent); override;
published
property Enabled: Boolean read FEnabled write SetEnabled default False;
{* Enabled属性,如果为假,对Changing、Changed方法的调用将不产生更新事件}
end;
//==============================================================================
// 带更新通知的持久性类
//==============================================================================
{ TCnNotifyClass }
TCnNotifyClass = class(TPersistent)
{* 带更新通知的持久性类,控件包中大部分持久类的基类,一般不需要直接使用}
private
FOnChanged: TNotifyEvent;
protected
FOwner: TPersistent;
procedure Changed; virtual;
procedure OnChildChanged(Sender: TObject); virtual;
function GetOwner: TPersistent; override;
public
constructor Create(ChangedProc: TNotifyEvent); virtual;
{* 类构造器,参数为通知事件}
procedure Assign(Source: TPersistent); override;
{* 对象赋值方法}
property OnChanged: TNotifyEvent read FOnChanged write FOnChanged;
{* 属性已变更事件}
end;
//==============================================================================
// 不可视组件基础类
//==============================================================================
{ TCnComponent }
TCnCopyright = type string;
TCnComponent = class(TComponent)
{* CnPack不可视组件基类}
private
FAbout: TCnCopyright;
procedure SetAbout(const Value: TCnCopyright);
protected
procedure GetComponentInfo(var AName, Author, Email, Comment: string); virtual;
abstract;
{* 取组件信息,用于提供组件的说明和版权信息。抽象方法,子类必须实现。
|<PRE>
var AName: string - 组件名称,可以是支持本地化的字符串
var Author: string - 组件作者,如果有多个作者,用分号分隔
var Email: string - 组件作者邮箱,如果有多个作者,用分号分隔
var Comment: - 组件说明,可以是支持本地化带换行符的字符串
|</PRE>}
public
constructor Create(AOwner: TComponent); override;
published
property About: TCnCopyright read FAbout write SetAbout stored False;
{* 组件版本属性,仅在设计期使用}
end;
//==============================================================================
// 单实例接口对象基础类
//==============================================================================
{ TSingletonInterfacedObject }
TSingletonInterfacedObject = class(TInterfacedObject)
protected
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
end;
procedure AssignPersistent(Source, Dest: TPersistent; UseDefineProperties:
Boolean = True);
implementation
uses
CnConsts;
type
TPersistentHack = class(TPersistent);
procedure AssignPersistent(Source, Dest: TPersistent; UseDefineProperties:
Boolean = True);
var
Stream: TMemoryStream;
Reader: TReader;
Writer: TWriter;
Count: Integer;
PropIdx: Integer;
PropList: PPropList;
PropInfo: PPropInfo;
begin
if Source is Dest.ClassType then
begin
// 使用 RTTI 来保证赋值所有 published 属性(流不能传递值为 Default 的属性)
Count := GetPropList(Dest.ClassInfo, tkProperties - [tkArray, tkRecord,
tkInterface], nil);
GetMem(PropList, Count * SizeOf(Pointer));
try
GetPropList(Source.ClassInfo, tkProperties - [tkArray, tkRecord,
tkInterface], @PropList^[0]);
for PropIdx := 0 to Count - 1 do
begin
PropInfo := PropList^[PropIdx];
case PropInfo^.PropType^^.Kind of
tkInteger, tkChar, tkWChar, tkClass, tkEnumeration, tkSet:
SetOrdProp(Dest, PropInfo, GetOrdProp(Source, PropInfo));
tkFloat:
SetFloatProp(Dest, PropInfo, GetFloatProp(Source, PropInfo));
tkString, tkLString, tkWString{$IFDEF UNICODE_STRING}, tkUString{$ENDIF}:
SetStrProp(Dest, PropInfo, GetStrProp(Source, PropInfo));
tkVariant:
SetVariantProp(Dest, PropInfo, GetVariantProp(Source, PropInfo));
tkInt64:
SetInt64Prop(Dest, PropInfo, GetInt64Prop(Source, PropInfo));
tkMethod:
SetMethodProp(Dest, PropInfo, GetMethodProp(Source, PropInfo));
end;
end;
finally
FreeMem(PropList);
end;
// 使用流来传递自定义的属性
if UseDefineProperties then
begin
Stream := nil;
Reader := nil;
Writer := nil;
try
Stream := TMemoryStream.Create;
Writer := TWriter.Create(Stream, 4096);
TPersistentHack(Source).DefineProperties(Writer);
Writer.FlushBuffer;
Stream.Position := 0;
Reader := TReader.Create(Stream, 4096);
TPersistentHack(Dest).DefineProperties(Reader);
finally
FreeAndNil(Reader);
FreeAndNil(Writer);
FreeAndNil(Stream);
end;
end;
end;
end;
//==============================================================================
// 支持线程安全的基础类
//==============================================================================
var
CounterLock: TRTLCriticalSection;
{ TCnLockObject }
// 初始化
constructor TCnLockObject.Create;
begin
inherited;
InitializeCriticalSection(FLock); // 初始化临界区
end;
// 释放
destructor TCnLockObject.Destroy;
begin
DeleteCriticalSection(FLock);
inherited;
end;
// 尝试进入临界区(如果已加锁返回 False)
function TCnLockObject.TryLock: Boolean;
begin
EnterCriticalSection(CounterLock);
try
Result := FLockCount = 0;
if Result then Lock;
finally
LeaveCriticalSection(CounterLock);
end;
end;
// 加锁
procedure TCnLockObject.Lock;
begin
EnterCriticalSection(CounterLock);
Inc(FLockCount);
LeaveCriticalSection(CounterLock);
EnterCriticalSection(FLock);
end;
// 释放锁
procedure TCnLockObject.Unlock;
begin
LeaveCriticalSection(FLock);
EnterCriticalSection(CounterLock);
Dec(FLockCount);
LeaveCriticalSection(CounterLock);
end;
function TCnLockObject.GetLocking: Boolean;
begin
Result := FLockCount > 0;
end;
//==============================================================================
// 使用 RTTI 实现了 Assign 方法的 TPersistent 类
//==============================================================================
{ TCnAssignablePersistent }
procedure TCnAssignablePersistent.Assign(Source: TPersistent);
begin
if Source is ClassType then
begin
AssignPersistent(Source, Self);
end
else
inherited Assign(Source);
end;
//==============================================================================
// 使用 RTTI 实现了 Assign 方法的 TCollectionItem 类
//==============================================================================
{ TCnAssignableCollectionItem }
procedure TCnAssignableCollectionItem.Assign(Source: TPersistent);
begin
if Source is ClassType then
begin
AssignPersistent(Source, Self);
end
else
inherited Assign(Source);
end;
//==============================================================================
// 使用 RTTI 实现了 Assign 方法的 TCollection 类
//==============================================================================
{ TCnAssignableCollection }
procedure TCnAssignableCollection.Assign(Source: TPersistent);
begin
if Source is ClassType then
begin
AssignPersistent(Source, Self);
end;
inherited Assign(Source);
end;
//==============================================================================
// 带更新通知、线程安全的持久性类
//==============================================================================
{ TCnPersistent }
// 初始化(供重载)
constructor TCnPersistent.Create;
begin
inherited;
FUpdateCount := 0;
end;
// 初始化,参数为实例的所有者
constructor TCnPersistent.Create(AOwner: TPersistent);
begin
Create;
FOwner := AOwner;
end;
// 初始化,参数为更新通知事件
constructor TCnPersistent.Create(ChangeProc: TNotifyEvent);
begin
Create;
FOnChange := ChangeProc;
end;
// 初始化,参数为更新通知事件
constructor TCnPersistent.Create(ChangingProc, ChangeProc: TNotifyEvent);
begin
Create;
FOnChanging := ChangingProc;
FOnChange := ChangeProc;
end;
destructor TCnPersistent.Destroy;
begin
if Assigned(FLockObject) then
FLockObject.Free;
inherited;
end;
//------------------------------------------------------------------------------
// 更新通知部分
//------------------------------------------------------------------------------
// 开始更新
procedure TCnPersistent.BeginUpdate;
begin
if not IsUpdating then SetUpdating(True); // 开始更新
Inc(FUpdateCount);
end;
// 结束更新
procedure TCnPersistent.EndUpdate;
begin // Assert不需要本地化
Assert(FUpdateCount > 0, 'Unpaired TCnPersistent.EndUpdate');
Dec(FUpdateCount);
if not IsUpdating then SetUpdating(False);
end;
// 正在变更
procedure TCnPersistent.Changing;
begin
if not IsUpdating and Assigned(FOnChanging) then FOnChanging(Self);
end;
// 变更结束
procedure TCnPersistent.Changed;
begin
if not IsUpdating and Assigned(FOnChange) then FOnChange(Self);
end;
// 取所有者
function TCnPersistent.GetOwner: TPersistent;
begin
Result := FOwner;
end;
// 正在更新
function TCnPersistent.IsUpdating: Boolean;
begin
Result := FUpdateCount > 0;
end;
// 更新状态变更过程
procedure TCnPersistent.SetUpdating(Updating: Boolean);
begin
if Updating then
Changing
else
Changed;
end;
// 子单位变更
procedure TCnPersistent.OnChildChanging(Sender: TObject);
begin
if not IsUpdating and Assigned(FOnChanging) then FOnChanging(Sender);
end;
// 子单位已变更
procedure TCnPersistent.OnChildChange(Sender: TObject);
begin
if not IsUpdating and Assigned(FOnChange) then FOnChange(Sender);
end;
//------------------------------------------------------------------------------
// 线程安全处理部分
//------------------------------------------------------------------------------
// 进入临界区,为保证多线程同步而加锁,必须与Unlock成对使用
procedure TCnPersistent.Lock;
begin
LockObject.Lock;
end;
// 如果当前Lock计数为零,则加锁返回真,否则返回假
function TCnPersistent.TryLock: Boolean;
begin
Result := LockObject.TryLock;
end;
// 退出临界区,释放同步锁,必须与Lock成对使用
procedure TCnPersistent.Unlock;
begin
LockObject.Unlock;
end;
// Locking 属性读方法
function TCnPersistent.GetLocking: Boolean;
begin
Result := LockObject.GetLocking;
end;
// LockObject 属性读方法,仅在需要时创建内部对象
function TCnPersistent.GetLockObject: TCnLockObject;
begin
if not Assigned(FLockObject) then
FLockObject := TCnLockObject.Create;
Result := FLockObject;
end;
//==============================================================================
// 带Enabled的更新通知持久性类
//==============================================================================
{ TCnEnabledPersistent }
// 赋值
procedure TCnEnabledPersistent.Assign(Source: TPersistent);
begin
if Source is TCnEnabledPersistent then
FEnabled := TCnEnabledPersistent(Source).FEnabled
else
inherited Assign(Source);
end;
// 更新通知
procedure TCnEnabledPersistent.SetUpdating(Updating: Boolean);
begin
if FEnabled then // 如果能用则通知
inherited SetUpdating(Updating);
end;
// 创建
constructor TCnEnabledPersistent.Create;
begin
inherited Create;
FEnabled := False;
end;
// 设置参数
procedure TCnEnabledPersistent.SetEnabled(const Value: Boolean);
begin
if FEnabled <> Value then
begin
FEnabled := True; // 允许通知
Changed;
FEnabled := Value;
end;
end;
{ TCnNotifyClass }
//--------------------------------------------------------//
//带更新通知的持久性类 //
//--------------------------------------------------------//
//赋值
procedure TCnNotifyClass.Assign(Source: TPersistent);
begin
if Source is TCnNotifyClass then
//
else
inherited Assign(Source);
end;
//更新通知
procedure TCnNotifyClass.Changed;
begin
if Assigned(FOnChanged) then
FOnChanged(Self);
end;
//创建
constructor TCnNotifyClass.Create(ChangedProc: TNotifyEvent);
begin
FOnChanged := ChangedProc;
end;
//取所有者
function TCnNotifyClass.GetOwner: TPersistent;
begin
Result := FOwner;
end;
//子单位更新通知
procedure TCnNotifyClass.OnChildChanged(Sender: TObject);
begin
Changed;
end;
//==============================================================================
// 不可视组件基础类
//==============================================================================
{ TCnComponent }
// 初始化
constructor TCnComponent.Create(AOwner: TComponent);
begin
inherited;
FAbout := SCnPackAbout;
end;
// 设置关于属性
procedure TCnComponent.SetAbout(const Value: TCnCopyright);
begin
// 不处理
end;
//==============================================================================
// 单实例接口对象基础类
//==============================================================================
{ TSingletonInterfacedObject }
function TSingletonInterfacedObject._AddRef: Integer;
begin
Result := 1;
end;
function TSingletonInterfacedObject._Release: Integer;
begin
Result := 1;
end;
initialization
InitializeCriticalSection(CounterLock);
finalization
DeleteCriticalSection(CounterLock);
end.
|
unit UFrmCadastroLote;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFrmCRUD, Menus, Buttons, StdCtrls, ExtCtrls, Mask
, ULote
, UUtilitarios
, URegraCRUDEmpresaMatriz
, URegraCRUDLote
;
type
TFrmCadastroLote = class(TFrmCRUD)
gbInformacoes: TGroupBox;
lbCodigoPais: TLabel;
edLote: TLabeledEdit;
btnLocalizarFornecedor: TButton;
edFornecedor: TEdit;
stNomeFornecedor: TStaticText;
edValidade: TMaskEdit;
Label1: TLabel;
procedure btnLocalizarFornecedorClick(Sender: TObject);
procedure edFornecedorExit(Sender: TObject);
private
{ Private declarations }
protected
FLOTE: TLOTE;
FRegraCRUDEMPRESA: TregraCRUDEEmpresaMatriz;
FregraCRUDLOTE: TRegraCRUDLote;
procedure Inicializa; override;
procedure Finaliza; override;
procedure PreencheEntidade; override;
procedure PreencheFormulario; override;
procedure PosicionaCursorPrimeiroCampo; override;
procedure HabilitaCampos(const ceTipoOperacaoUsuario: TTipoOperacaoUsuario); override;
public
{ Public declarations }
end;
var
FrmCadastroLote: TFrmCadastroLote;
implementation
uses
UOpcaoPesquisa
, UEntidade
, UFrmPesquisa
, UEmpresaMatriz
, UDialogo
;
{$R *.dfm}
{ TFrmCadastroLote }
procedure TFrmCadastroLote.btnLocalizarFornecedorClick(Sender: TObject);
begin
inherited;
edFornecedor.Text := TfrmPesquisa.MostrarPesquisa(TOpcaoPesquisa
.Create
.DefineVisao(VW_EMPRESA)
.DefineNomeCampoRetorno(VW_EMPRESA_ID)
.DefineNomePesquisa(STR_EMPRESAMATRIZ)
.AdicionaFiltro(VW_EMPRESA_NOME));
if Trim(edFornecedor.Text) <> EmptyStr then
edFornecedor.OnExit(btnLocalizarFornecedor);
end;
procedure TFrmCadastroLote.edFornecedorExit(Sender: TObject);
begin
inherited;
stNomeFornecedor.Caption := EmptyStr;
if Trim(edFornecedor.Text) <> EmptyStr then
try
FRegraCRUDEMPRESA.ValidaExistencia(StrToIntDef(edFornecedor.Text, 0));
FLOTE.EMPRESA := TEmpresa(
FRegraCRUDEMPRESA.Retorna(StrToIntDef(edFornecedor.Text, 0)));
stNomeFornecedor.Caption := FLOTE.EMPRESA.NOME;
except
on E: Exception do
begin
TDialogo.Excecao(E);
edFornecedor.SetFocus;
end;
end;
end;
procedure TFrmCadastroLote.Finaliza;
begin
inherited;
FreeAndNil(FRegraCRUDEMPRESA);
end;
procedure TFrmCadastroLote.HabilitaCampos(
const ceTipoOperacaoUsuario: TTipoOperacaoUsuario);
begin
inherited;
gbInformacoes.Enabled := FTipoOperacaoUsuario In [touInsercao, touAtualizacao];
end;
procedure TFrmCadastroLote.Inicializa;
begin
inherited;
DefineEntidade(@FLOTE, TLOTE);
DefineRegraCRUD(@FregraCRUDLOTE, TRegraCRUDLote);
AdicionaOpcaoPesquisa(TOpcaoPesquisa
.Create
.AdicionaFiltro(FLD_LOTE_CODIGO)
.DefineNomeCampoRetorno(FLD_ENTIDADE_ID)
.DefineNomePesquisa(STR_LOTE)
.DefineVisao(TBL_LOTE));
FRegraCRUDEMPRESA := TregraCRUDEEmpresaMatriz.Create;
end;
procedure TFrmCadastroLote.PosicionaCursorPrimeiroCampo;
begin
inherited;
edLote.SetFocus;
end;
procedure TFrmCadastroLote.PreencheEntidade;
begin
inherited;
FLOTE.VALIDADE := StrToDateDef(edValidade.Text, Now);
FLOTE.LOTE := edLote.Text;
end;
procedure TFrmCadastroLote.PreencheFormulario;
begin
inherited;
edLote.Text := FLOTE.LOTE;
edValidade.Text := DateToStr(FLOTE.VALIDADE);
edFornecedor.Text := IntToStr(FLOTE.EMPRESA.ID);
stNomeFornecedor.Caption := FLOTE.EMPRESA.NOME;
end;
end.
|
unit UnitOpenGLShadowMapMultisampleResolveShader;
{$ifdef fpc}
{$mode delphi}
{$ifdef cpui386}
{$define cpu386}
{$endif}
{$ifdef cpuamd64}
{$define cpux86_64}
{$endif}
{$ifdef cpu386}
{$define cpux86}
{$define cpu32}
{$asmmode intel}
{$endif}
{$ifdef cpux86_64}
{$define cpux64}
{$define cpu64}
{$asmmode intel}
{$endif}
{$ifdef FPC_LITTLE_ENDIAN}
{$define LITTLE_ENDIAN}
{$else}
{$ifdef FPC_BIG_ENDIAN}
{$define BIG_ENDIAN}
{$endif}
{$endif}
{-$pic off}
{$define caninline}
{$ifdef FPC_HAS_TYPE_EXTENDED}
{$define HAS_TYPE_EXTENDED}
{$else}
{$undef HAS_TYPE_EXTENDED}
{$endif}
{$ifdef FPC_HAS_TYPE_DOUBLE}
{$define HAS_TYPE_DOUBLE}
{$else}
{$undef HAS_TYPE_DOUBLE}
{$endif}
{$ifdef FPC_HAS_TYPE_SINGLE}
{$define HAS_TYPE_SINGLE}
{$else}
{$undef HAS_TYPE_SINGLE}
{$endif}
{$if declared(RawByteString)}
{$define HAS_TYPE_RAWBYTESTRING}
{$else}
{$undef HAS_TYPE_RAWBYTESTRING}
{$ifend}
{$if declared(UTF8String)}
{$define HAS_TYPE_UTF8STRING}
{$else}
{$undef HAS_TYPE_UTF8STRING}
{$ifend}
{$else}
{$realcompatibility off}
{$localsymbols on}
{$define LITTLE_ENDIAN}
{$ifndef cpu64}
{$define cpu32}
{$endif}
{$ifdef cpux64}
{$define cpux86_64}
{$define cpu64}
{$else}
{$ifdef cpu386}
{$define cpux86}
{$define cpu32}
{$endif}
{$endif}
{$define HAS_TYPE_EXTENDED}
{$define HAS_TYPE_DOUBLE}
{$ifdef conditionalexpressions}
{$if declared(RawByteString)}
{$define HAS_TYPE_RAWBYTESTRING}
{$else}
{$undef HAS_TYPE_RAWBYTESTRING}
{$ifend}
{$if declared(UTF8String)}
{$define HAS_TYPE_UTF8STRING}
{$else}
{$undef HAS_TYPE_UTF8STRING}
{$ifend}
{$else}
{$undef HAS_TYPE_RAWBYTESTRING}
{$undef HAS_TYPE_UTF8STRING}
{$endif}
{$endif}
{$ifdef win32}
{$define windows}
{$endif}
{$ifdef win64}
{$define windows}
{$endif}
{$ifdef wince}
{$define windows}
{$endif}
{$rangechecks off}
{$extendedsyntax on}
{$writeableconst on}
{$hints off}
{$booleval off}
{$typedaddress off}
{$stackframes off}
{$varstringchecks on}
{$typeinfo on}
{$overflowchecks off}
{$longstrings on}
{$openstrings on}
interface
uses {$ifdef fpcgl}gl,glext,{$else}dglOpenGL,{$endif}UnitOpenGLShader;
type TShadowMapMultisampleResolveShader=class(TShader)
public
uTexture:glInt;
uSamples:glInt;
public
constructor Create;
destructor Destroy; override;
procedure BindAttributes; override;
procedure BindVariables; override;
end;
implementation
constructor TShadowMapMultisampleResolveShader.Create;
var f,v:ansistring;
begin
v:='#version 430'+#13#10+
'out vec2 vTexCoord;'+#13#10+
'void main(){'+#13#10+
' vTexCoord = vec2((gl_VertexID >> 1) * 2.0, (gl_VertexID & 1) * 2.0);'+#13#10+
' gl_Position = vec4(((gl_VertexID >> 1) * 4.0) - 1.0, ((gl_VertexID & 1) * 4.0) - 1.0, 0.0, 1.0);'+#13#10+
'}'+#13#10;
f:='#version 430'+#13#10+
'in vec2 vTexCoord;'+#13#10+
'layout(location = 0) out vec4 oOutput;'+#13#10+
'uniform sampler2DMS uTexture;'+#13#10+
'uniform int uSamples;'+#13#10+
'void main(){'+#13#10+
' ivec2 position = ivec2(gl_FragCoord.xy);'+#13#10+
' vec4 sum = vec4(0.0);'+#13#10+
' for(int i = 0; i < uSamples; i++){'+#13#10+
' float d = texelFetch(uTexture, position, i).x, d2 = d * d;'+#13#10+
' sum += vec4(d, d2, d2 * d, d2 * d2);'+#13#10+
' }'+#13#10+
// ' oOutput = sum / float(uSamples);'+#13#10+
' oOutput = ((sum / float(uSamples)) *'+#13#10+
' mat4(-2.07224649, 32.23703778, -68.571074599, 39.3703274134,'+#13#10+
' 13.7948857237, -59.4683975703, 82.0359750338, -35.364903257,'+#13#10+
' 0.105877704, -1.9077466311, 9.3496555107, -6.6543490743,'+#13#10+
' 9.7924062118, -33.7652110555, 47.9456096605, -23.9728048165)) + vec2(0.035955884801, 0.0).xyyy;'+#13#10+{}
'}'+#13#10;
inherited Create(v,f);
end;
destructor TShadowMapMultisampleResolveShader.Destroy;
begin
inherited Destroy;
end;
procedure TShadowMapMultisampleResolveShader.BindAttributes;
begin
inherited BindAttributes;
end;
procedure TShadowMapMultisampleResolveShader.BindVariables;
begin
inherited BindVariables;
uTexture:=glGetUniformLocation(ProgramHandle,pointer(pansichar('uTexture')));
uSamples:=glGetUniformLocation(ProgramHandle,pointer(pansichar('uSamples')));
end;
end.
|
unit DgOut;
interface
uses Windows, Forms, Classes, DAQDefs,
pwrdaq32, pdfw_def, pd_hcaps;
type
// base acquisition thread
TDigitalOutput = class(TThread)
private
hAdapter: DWORD;
dwError: DWORD;
FFrequency: DWORD;
FOnUpdateView: TUpdateViewProc;
FOnGetData: TDataFunction;
protected
procedure DoTerminate; override;
public
constructor Create(Adapter: DWORD);
procedure Execute; override;
property Frequency: DWORD read FFrequency write FFrequency;
property OnUpdateView: TUpdateViewProc read FOnUpdateView write FOnUpdateView;
property OnGetData: TDataFunction read FOnGetData write FOnGetData;
end;
implementation
constructor TDigitalOutput.Create(Adapter: DWORD);
begin
hAdapter := Adapter;
Frequency := 500;
inherited Create(False);
end;
procedure TDigitalOutput.Execute;
var Value: WORD;
begin
Value := 0;
// digital output - init sequence
try
// initialize DInp subsystem
if not PdAdapterAcquireSubsystem(hAdapter, @dwError, DigitalOut, 1)
then raise TPwrDaqException.Create('PdAdapterAcquireSubsystem', dwError);
// thread loop
while not Terminated do try
// get data value
if Assigned(OnGetData) then Value := OnGetData;
// update view
if Assigned(OnUpdateView) then OnUpdateView(Value);
// output data
if not _PdDOutWrite(hAdapter, @dwError, Value)
then raise TPwrDaqException.Create('_PdDOutWrite', dwError);
try Sleep (10000 div Frequency); except end;
except
raise;
end;
except
Application.HandleException(Self);
end;
end;
procedure TDigitalOutput.DoTerminate;
begin
// stop input sequence
try
// release DInp subsystem and close adapter
if not PdAdapterAcquireSubsystem(hAdapter, @dwError, DigitalOut, 0)
then raise TPwrDaqException.Create('PdAdapterAcquireSubsystem', dwError);
except
// Handle any exception
Application.HandleException(Self);
end;
inherited;
end;
end.
|
unit GlobalObjects;
interface
uses UserModel, DatabaseConnection;
procedure WriteLog(logMessage : String); overload;
procedure WriteLog(logMessage : String; formatParams : array of Const); overload;
function InitializeApplication : Boolean;
procedure FinalizeApplication;
const
LogsDirName = 'Logs';
DataDirName = 'Data';
SqliteDatabaseFileName = 'data.sqlite';
// Directories to be created during system startup
DirectoriesToCreate : array[0..1] of string =
(
LogsDirName,
DataDirName
);
var
ApplicationDirectoryPath : String;
DbConnection : TDatabaseConnection;
LoggedUser : TUser;
implementation
uses
SysUtils, FileSystemHelper, LogHelper, ComandLineHelpers, TypInfo,
SqliteConnection;
procedure WriteLog(logMessage : String);
var
logFileDir : String;
begin
logFileDir := CombinePath([ApplicationDirectoryPath, LogsDirName]);
WriteLogFileByDay(logFileDir, '', logMessage);
end;
procedure WriteLog(logMessage : String; formatParams : array of Const);
begin
WriteLog(format(logMessage, formatParams));
end;
function CreateExtraDirectories : Boolean;
var
directory : String;
i : Integer;
begin
Result := False;
for i := 0 to Length(DirectoriesToCreate) - 1 do
begin
directory := DirectoriesToCreate[i];
if not CreateDirectory(directory) then
begin
// TODO: Write log
Exit;
end;
end;
Result := True;
end;
function ConnectToDatabase : Boolean;
var
databasePath : String;
begin
databasePath := CombinePath([ApplicationDirectoryPath, DataDirName, SqliteDatabaseFileName]);
DbConnection := TSqliteConnection.Create(nil, databasePath);
Result := DbConnection.Connect;
end;
function InitializeApplication : Boolean;
begin
ApplicationDirectoryPath := GetApplicationFullDirectoryPath;
Result := False;
if not CreateExtraDirectories then
begin
// TODO: Write log
Exit;
end;
if not ConnectToDatabase then
begin
// TODO: Write log
Exit;
end;
Result := True;
end;
procedure FinalizeApplication;
begin
DbConnection.Disconnect;
FreeAndNil(DbConnection);
if Assigned(LoggedUser) then
FreeAndNil(LoggedUser);
end;
end.
|
unit Objekt.Backupchecker;
interface
uses
SysUtils, Classes, Objekt.Option, Objekt.OptionList, Vcl.ExtCtrls,
Objekt.DateTime, Vcl.Controls, Vcl.Forms;
type
TStartBackupEvent = procedure(Sender: TObject; aOption: TOption) of object;
TEndBackupEvent = procedure(Sender: TObject; aOption: TOption) of object;
TBackupErrorEvent = procedure(Sender: TObject; aOption: TOption; aError: string) of object;
type
TBackupchecker = class
private
fOptionList: TOptionList;
fDataPfad: string;
fCheckTimer: TTimer;
fFullDataFilename: string;
fDateTime: TTbDateTime;
fTimerEnabled: Boolean;
fAktualData: Boolean;
fOnStartBackup: TStartBackupEvent;
fOnEndBackup: TEndBackupEvent;
fOnBackupError: TBackupErrorEvent;
procedure Check(Sender: TObject);
procedure setFullDataFilename(const Value: string);
function getStartZeit(aStartTime: TDateTime): TDateTime;
procedure setTimerEnabled(const Value: Boolean);
procedure ErrorBackup(Sender: TObject; aOption: TOption; aError: string);
public
constructor Create;
destructor Destroy; override;
property FullDataFilename: string read fFullDataFilename write setFullDataFilename;
property TimerEnabled: Boolean read fTimerEnabled write setTimerEnabled;
property AktualData: Boolean read fAktualData write fAktualData;
property OnStartBackup: TStartBackupEvent read fOnStartBackup write fOnStartBackup;
property OnEndBackup: TEndBackupEvent read fOnEndBackup write fOnEndBackup;
property OnBackupError: TBackupErrorEvent read fOnBackupError write fOnBackupError;
end;
implementation
{ TBackupchecker }
uses
Objekt.Backup, Objekt.Allgemein;
constructor TBackupchecker.Create;
begin
fOptionList := TOptionList.Create;
fDataPfad := '';
fTimerEnabled := false;
fCheckTimer := TTimer.Create(nil);
//fCheckTimer.Interval := 600000; // Alle 10 Minuten
//fCheckTimer.Interval := 1000; //
AllgemeinObj.Log.DebugInfo('Inifile=' + AllgemeinObj.Ini.IniFilename);
fCheckTimer.Interval := AllgemeinObj.Ini.CheckInterval;
fCheckTimer.Enabled := fTimerEnabled;
fCheckTimer.OnTimer := Check;
fDateTime := TTbDateTime.Create(nil);
fAktualData := false;
AllgemeinObj.Log.DebugInfo('TimerInterval=' + IntToStr(fCheckTimer.Interval));
end;
destructor TBackupchecker.Destroy;
begin
FreeAndNil(fCheckTimer);
FreeAndNil(fOptionList);
FreeAndNil(fDateTime);
inherited;
end;
procedure TBackupchecker.setFullDataFilename(const Value: string);
begin
fFullDataFilename := '';
if not FileExists(Value) then
begin
AllgemeinObj.Log.BackupInfo('Backupdatei exisitiert nicht: ' + Value);
exit;
end;
fDataPfad := ExtractFilePath(Value);
fFullDataFilename := Value;
fOptionList.LoadFromFile(fFullDataFilename);
fAktualData := false;
end;
procedure TBackupchecker.setTimerEnabled(const Value: Boolean);
begin
fTimerEnabled := Value;
fCheckTimer.Enabled := fTimerEnabled;
end;
procedure TBackupchecker.Check(Sender: TObject);
var
i1: Integer;
Option: TOption;
Startzeit : TDateTime;
Backup: TBackup;
//s: string;
Cur: TCursor;
begin
if fDataPfad = '' then
exit;
if fAktualData then
begin
fOptionList.LoadFromFile(fFullDataFilename);
fAktualData := false;
end;
if fOptionList.Count <= 0 then
begin
AllgemeinObj.Log.BackupInfo('OptionListCount=' + IntToStr(fOptionList.Count) + ' / Keine Backupinfo vorhanden.');
exit;
end;
Cur := Screen.Cursor;
try
fCheckTimer.Enabled := false;
for i1 := 0 to fOptionList.Count -1 do
begin
Option := fOptionList.Item[i1];
//s := Option.Datenbank + ' / ' + Option.Backupdatei + ' / ' + 'Start:' + FormatDateTime('hh:nn', Option.StartZeit) + ' / ' +
// 'Letztes Backup:' + FormatDateTime('dd.mm.yyyy', Option.LastBackupDate);
//AllgemeinObj.Log.BackupInfo(s);
//AllgemeinObj.Log.DebugInfo('LastBackup ' + FormatDateTime('dd.mm.yyyy hh:nn', Option.LastBackupDate));
if Option.LastBackupDate >= trunc(now) then
continue;
Startzeit := getStartZeit(Option.StartZeit);
//AllgemeinObj.Log.DebugInfo('Startzeit ' + FormatDateTime('dd.mm.yyyy hh:nn', Option.Startzeit));
if now < Startzeit then
continue;
Backup := TBackup.Create;
try
if Assigned(fOnStartBackup) then
fOnStartBackup(Self, Option);
Screen.Cursor := crHourglass;
Backup.BackupProtokollPfad := AllgemeinObj.Log.LogPath;
Backup.OnBackupError := ErrorBackup;
AllgemeinObj.Log.BackupInfo('Starte Backup - ' + Option.Datenbank);
Backup.StartBackup(Option);
Option.LastBackupDate := trunc(now);
AllgemeinObj.Log.BackupInfo('Ende Backup');
finally
FreeAndNil(Backup);
if Assigned(fOnEndBackup) then
fOnEndBackup(Self, Option);
end;
end;
finally
Screen.Cursor := Cur;
fCheckTimer.Enabled := true;
end;
end;
procedure TBackupchecker.ErrorBackup(Sender: TObject; aOption: TOption;
aError: string);
begin
aOption.StatusMeldung := 'Backup Error';
AllgemeinObj.Log.BackupInfo(aError);
AllgemeinObj.Log.DebugInfo(aError);
if Assigned(fOnBackupError) then
fOnBackupError(Self, aOption, aError);
end;
function TBackupChecker.getStartZeit(aStartTime: TDateTime): TDateTime;
begin
Result := fDateTime.SetTimeToDate(now, aStartTime);
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.OleServer, SpeechLib_TLB,activeX, comobj,
Vcl.StdCtrls;
type
TForm1 = class(TForm)
cbbSpeakers: TComboBox;
SpInprocRecognizer1: TSpInprocRecognizer;
Context1: TSpInProcRecoContext;
SpVoice1: TSpVoice;
cbbRecognizers: TComboBox;
Button3: TButton;
btnAdd: TButton;
Category1: TSpObjectTokenCategory;
Token1: TSpObjectToken;
Memo1: TMemo;
ListBox1: TListBox;
Label1: TLabel;
Edit1: TEdit;
btnRemove: TButton;
Label2: TLabel;
Label3: TLabel;
Button1: TButton;
procedure Button3Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure cbbSpeakersChange(Sender: TObject);
procedure cbbRecognizersChange(Sender: TObject);
procedure Context1Hypothesis(ASender: TObject; StreamNumber: Integer;
StreamPosition: OleVariant; const Result: ISpeechRecoResult);
procedure Context1Recognition(ASender: TObject; StreamNumber: Integer;
StreamPosition: OleVariant; RecognitionType: TOleEnum;
const Result: ISpeechRecoResult);
procedure FormShow(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
speechInitialized : boolean;
grammar: ISpRecoGrammar;
procedure ListAllRecognizers;
procedure ListAllSpeakers;
procedure releaseAllRecognizers;
procedure releaseAllSpeakers;
procedure InitializeSpeech;
function ReBuildGrammar : boolean;
function EnabledSpeech: boolean;
function DisabledSpeech: boolean;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses SpeechStringConstants;
function TForm1.EnabledSpeech:boolean;
begin
result := false;
if not speechInitialized then
initializeSpeech
else
rebuildGrammar;
result := true;
end;
function TForm1.DisabledSpeech: boolean;
begin
if speechInitialized then
context1.State := SRCS_Disabled;
result := true;
end;
function TForm1.ReBuildGrammar:boolean;
begin
end;
procedure TForm1.InitializeSpeech;
var
prop: SPPROPERTYINFO;
spStateHandle: pointer;
begin
Memo1.Lines.Add('Initializing objects.....');
try
Category1.SetId(SpeechCategoryAudioIn,false);
Token1.SetId(Category1.Default,Category1.Id,false);
Context1.Recognizer.AudioInput := Token1.DefaultInterface;
grammar := Context1.CreateGrammar(0) as ISpRecoGrammar;
{
grammar.GetRule(nil,1,SRATopLevel or SRADefaultToActive,1,spStateHandle);
grammar.AddWordTransition(spStateHandle,nil,'red',' ',SPWT_LEXICAL,1,prop);
grammar.GetRule(nil,2,SRATopLevel or SRADefaultToActive,1,spStateHandle);
grammar.AddWordTransition(spStateHandle,nil,'dog',' ',SPWT_LEXICAL,1,prop);
grammar.AddWordTransition(spStateHandle,nil,'cat',' ',SPWT_LEXICAL,1,prop);
grammar.GetRule(nil,3,SRATopLevel or SRADefaultToActive,1,spStateHandle);
grammar.AddWordTransition(spStateHandle,nil,'orange',' ',SPWT_LEXICAL,1,prop);
grammar.AddWordTransition(spStateHandle,nil,'apple',' ',SPWT_LEXICAL,1,prop);
grammar.Commit(0);
}
grammar.LoadCmdFromFile('d:\test\g.grxml',SPLO_STATIC );
grammar.SetRuleState('', nil, SPRS_ACTIVE);
// grammar.SetRuleIdState(2,SPRS_ACTIVE);
// context1.Recognizer.State := SRSActive;
speechInitialized := true;
except
showmessage('except');
end;
end;
procedure TForm1.ListAllRecognizers;
var
i: integer;
theRecognizers: ISpeechObjectTokens;
aRecognizer: ISpeechObjectToken;
begin
theRecognizers := SpInprocRecognizer1.GetRecognizers('','');
for i := 0 to theRecognizers.Count - 1 do
begin
aRecognizer := theRecognizers.Item(i);
cbbRecognizers.Items.AddObject(aRecognizer.GetDescription(0),Pointer(aRecognizer));
aRecognizer._AddRef;
end;
end;
procedure TForm1.ListAllSpeakers;
var
i: integer;
theVoices : ISpeechObjectTokens;
aVoice: ISpeechObjectToken;
begin
theVoices := spvoice1.GetVoices('','');
for i := 0 to theVoices.Count - 1 do
begin
aVoice := theVoices.Item(i);
cbbSpeakers.Items.AddObject(aVOice.GetDescription(0),Pointer(aVoice));
aVoice._AddRef;
end;
end;
procedure TForm1.releaseAllRecognizers;
var
i: integer;
begin
for I := 0 to cbbRecognizers.Items.Count-1 do
begin
ISPeechObjectToken(Pointer(cbbRecognizers.Items.Objects[i]))._Release;
end;
end;
procedure TForm1.releaseAllSpeakers;
var
i: integer;
begin
for i:=0 to cbbSpeakers.Items.Count - 1 do
begin
ISPeechObjectToken(Pointer(cbbSpeakers.Items.Objects[i]))._Release;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
context1.Recognizer.State := SRSActive;
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
spVoice1.Speak('i am awake',0);
end;
procedure TForm1.cbbSpeakersChange(Sender: TObject);
begin
if cbbSpeakers.ItemIndex >= 0 then
begin
SpVoice1.Voice := ISPeechObjectTOken(Pointer(cbbSpeakers.Items.Objects[cbbSpeakers.ItemIndex]));
end;
end;
procedure TForm1.cbbRecognizersChange(Sender: TObject);
begin
if cbbRecognizers.ItemIndex >= 0 then
begin
context1.Disconnect;
SpInProcRecognizer1.Recognizer := ISpeechObjectToken(Pointer(cbbRecognizers.Items.Objects[cbbRecognizers.ItemIndex]));
context1.ConnectTo(SpInProcRecognizer1.CreateRecoContext);
end;
end;
procedure TForm1.Context1Hypothesis(ASender: TObject; StreamNumber: Integer;
StreamPosition: OleVariant; const Result: ISpeechRecoResult);
var
e: ISPeechPhraseElement;
begin
e := result.PhraseInfo.Elements.Item(0);
memo1.Lines.Add('Hypothesis: '+ result.PhraseInfo.GetText(0,-1,true) + ', ' +
streamNumber.ToString()+', '+vartostr(streamPosition));
memo1.Lines.Add(format('%.1f',[e.EngineConfidence*100])+'%');
end;
procedure TForm1.Context1Recognition(ASender: TObject; StreamNumber: Integer;
StreamPosition: OleVariant; RecognitionType: TOleEnum;
const Result: ISpeechRecoResult);
var
e: ISPeechPhraseElement;
begin
e := result.PhraseInfo.Elements.Item(0);
Memo1.Lines.Add('Recognition: '+ result.PhraseInfo.GetText(0,-1,true)+', '+
streamNumber.ToString()+', '+vartostr(streamposition));
memo1.Lines.Add(format('EngineConfidence: %.1f',[e.EngineConfidence*100])+'%');
memo1.Lines.Add('RequiredConfidence: '+ vartostr(e.RequiredConfidence));
memo1.Lines.Add('ActualConfidnece: '+ vartostr(e.ActualConfidence));
memo1.Lines.Add(e.DisplayText);
memo1.Lines.Add(e.LexicalForm);
memo1.Lines.Add(e.Pronunciation[0]);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
speechInitialized := false;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
releaseAllRecognizers;
releaseAllSpeakers;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
listAllSpeakers;
listAllRecognizers;
if cbbSpeakers.Items.Count > 4 then
begin
cbbSpeakers.ItemIndex := 4;
cbbSpeakersChange(cbbSpeakers);
end;
if cbbRecognizers.Items.Count >4 then
begin
cbbRecognizers.ItemIndex := 4;
cbbRecognizersChange(cbbRecognizers);
end;
initializeSpeech;
end;
end.
|
namespace Sorter;
interface
uses
System.Threading,
System.Windows,
System.Windows.Controls,
System.Windows.Data,
System.Windows.Documents,
System.Windows.Media,
System.Windows.Media.Animation,
System.Windows.Navigation,
System.Windows.Shapes;
type
Window1 = public partial class(System.Windows.Window)
private
method Switch(aOne, aTwo, aDelay: Integer);
method Randomize(aSender: Object; aArgs: RoutedEventArgs);
method Sort(aSender: Object; aArgs: RoutedEventArgs);
method FillGrid;
method Sort(aLeft, aRight: Integer; var aDelay: Integer);
fRectangles: array of Rectangle;
fPositions: array of Double;
fRandom: Random := new Random();
fLoColor: array of Color := [Colors.Blue, Colors.Green, Colors.Yellow, Colors.Pink, Colors.Coral, Colors.Cyan, Colors.Salmon];
fHiColor: array of Color := [Colors.LightBlue, Colors.LightGreen, Colors.LightYellow, Colors.LightPink , Colors.LightCoral, Colors.LightCyan, Colors.LightSalmon];
public
constructor;
end;
implementation
constructor Window1;
begin
InitializeComponent();
FillGrid;
end;
method Window1.Sort(aSender: Object; aArgs: RoutedEventArgs);
var
lDelay: Integer := 0;
begin
Sort(0, fRectangles.Length -1, var lDelay);
end;
method Window1.Switch(aOne, aTwo, aDelay: Integer);
begin
var lDuration := new Duration(new TimeSpan(0,0,0,0,200)); // 0.5 second
var lStartDelay := new TimeSpan(0,0,0,aDelay / 4,(aDelay mod 4) * 250); // 0.5 second
var lAnim1 := new DoubleAnimation();
lAnim1.Duration := lDuration;
lAnim1.BeginTime := lStartDelay;
lAnim1.To := fPositions[aTwo];
var lAnim2 := new DoubleAnimation();
lAnim2.Duration := lDuration;
lAnim2.BeginTime := lStartDelay;
lAnim2.To := fPositions[aOne];
fRectangles[aOne].BeginAnimation(Canvas.LeftProperty, lAnim1, HandoffBehavior.Compose);
fRectangles[aTwo].BeginAnimation(Canvas.LeftProperty, lAnim2, HandoffBehavior.Compose);
var r: Rectangle := fRectangles[aOne];
fRectangles[aOne] := fRectangles[aTwo];
fRectangles[aTwo] := r;
end;
method Window1.FillGrid;
begin
MainCanvas.Children.Clear;
fRectangles := new Rectangle[50];
fPositions := new Double[50];
var lWidth: Double := Width / 52.0;
for i: Int32 := 0 to 49 do begin
//MainGrid.ColumnDefinitions.Add(new ColumnDefinition());
var r := new Rectangle();
r.HorizontalAlignment := HorizontalAlignment.Stretch;
r.VerticalAlignment := VerticalAlignment.Bottom;
r.Fill := new LinearGradientBrush(fLoColor[i mod fLoColor.Length], fHiColor[i mod fHiColor.Length], 20);
r.Height := fRandom.NextDouble()*(Height -80) +10;
r.Width := lWidth;
Canvas.SetLeft(r, i*r.Width);
Canvas.SetTop(r, -r.Height);
r.Opacity := 0.75;
Grid.SetColumn(r, i);
fRectangles[i] := r;
fPositions[i] := i*r.Width;
MainCanvas.Children.Add(r);
end;
end;
method Window1.Randomize(aSender: Object; aArgs: RoutedEventArgs);
begin
FillGrid;
end;
method Window1.Sort(aLeft, aRight: Integer; var aDelay: Integer);
begin
while aLeft < aRight do begin
var L: Integer := aLeft - 1;
var R: Integer := aRight + 1;
var Pivot: Double := fRectangles[(aLeft + aRight) div 2].Height;
loop begin
repeat
dec(R);
until fRectangles[R].Height <= Pivot;
repeat
inc(L);
until fRectangles[L].Height >= Pivot;
if L < R then begin
Switch(L, R, aDelay);
aDelay := aDelay + 1;
end else break;
end;
if aLeft < R then Sort(aLeft, R, var aDelay);
aLeft := R + 1;
end;
end;
end. |
unit uThreadForm;
interface
uses
System.Types,
System.Classes,
System.SyncObjs,
Vcl.Forms,
Vcl.Graphics,
Dmitry.Utils.System,
uDBForm,
uMemory,
uGUIDUtils;
type
TThreadForm = class(TDBForm)
private
FThreadList: TList;
FSync: TCriticalSection;
FStateID: TGUID;
FSubStateID: TGUID;
procedure ThreadTerminated(Sender : TObject);
protected
procedure TerminateAllThreads;
procedure NewFormState;
procedure StateChanged(OldState: TGUID); virtual;
public
procedure NewFormSubState;
procedure RegisterThreadAndStart(Thread: TThread);
function IsActualState(State: TGUID): Boolean;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property StateID: TGUID read FStateID;
property SubStateID: TGUID read FSubStateID;
function GetImage(FileName: string; Bitmap: TBitmap): Boolean;
end;
implementation
uses SysUtils, uThreadEx;
constructor TThreadForm.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSync := TCriticalSection.Create;
FThreadList := TList.Create;
end;
destructor TThreadForm.Destroy;
begin
if FSync <> nil then
TerminateAllThreads;
F(FThreadList);
F(FSync);
inherited;
end;
function TThreadForm.GetImage(FileName: string; Bitmap: TBitmap): Boolean;
begin
Result := False;
end;
function TThreadForm.IsActualState(State: TGUID): Boolean;
begin
//if FStateID equals - good, if not - check substate
Result := IsEqualGUID(State, FStateID) or IsEqualGUID(State, FSubStateID);
end;
procedure TThreadForm.NewFormState;
var
OldState: TGUID;
begin
OldState := FStateID;
FStateID := GetGUID;
NewFormSubState;
StateChanged(OldState);
end;
procedure TThreadForm.NewFormSubState;
begin
FSubStateID := GetGUID;
end;
procedure TThreadForm.RegisterThreadAndStart(Thread: TThread);
begin
FSync.Enter;
try
Thread.OnTerminate := ThreadTerminated;
FThreadList.Add(Thread);
finally
FSync.Leave;
end;
end;
procedure TThreadForm.StateChanged(OldState: TGUID);
begin
end;
procedure TThreadForm.TerminateAllThreads;
var
I: Integer;
begin
FSync.Enter;
try
for I := 0 to FThreadList.Count - 1 do
begin
TThread(FThreadList[I]).OnTerminate := nil;
TThreadEx(FThreadList[I]).DoTerminateThread;
end;
finally
FSync.Leave;
end;
end;
procedure TThreadForm.ThreadTerminated(Sender: TObject);
begin
FSync.Enter;
try
FThreadList.Remove(Sender);
finally
FSync.Leave;
end;
end;
end.
|
unit gsF_Glbl;
{-----------------------------------------------------------------------------
Global Values
gsF_Glbl Copyright (c) 1996 Griffin Solutions, Inc.
Date
4 Apr 1996
Programmer:
Richard F. Griffin tel: (912) 953-2680
Griffin Solutions, Inc. e-mail: grifsolu@hom.net
102 Molded Stone Pl
Warner Robins, GA 31088
Modified (m) 1997-2000 by Valery Votintsev 2:5021/22
-------------------------------------------------------------
This unit handles the types, constants, and variables that are
common to multiple units.
Changes:
18 Apr 96 - Added GSbytNextCentury variable in gsF_Glbl to allow
the programmer to determine a limit year that will
use the next century instead of the current century
when the actual century is unknown (e.g. 04/18/96).
Any year equal to or greater than GSbytNextCentury
will use the current centruy. Any value lower will
use the next century. Default is 0 (unused).
------------------------------------------------------------------------------}
{$I gsF_FLAG.PAS}
interface
uses
Strings;
const
{public}
gsF_Version = 'Halcyon Version 05.9.0 (11 May 98)';
{!!RFG 051198 Allowed character data fields to be > 255 bytes in 32-bit
Delphi. This accomodates Clipper fields that use the
decimals part of the field descriptor to allow large
character fields. This is not available in 16-bit programs
because of the limitation of strings to 255 bytes.
All units}
{!!RFG 050898 Fixed problem in the DoOnFilter by adding a try..finally
block to ensure the state was returned from dsFilter if
an exception occured. Also, added immediate exit in the
SetCurRecord method if State was dsFilter. This corrects
problems in handling filters when a DBGrid is used.
unit HalcnDB}
{!!RFG 043098 Made changes so that assigning an invalid index tag raises an
exception, instead of just returning quietly.
unit HalcnDB}
{!!RFG 042198 Changed InternalInitRecord to only update the original record
buffer if State was not dsEdit. Resolved problem with
TDataset.ClearFields.
unit HalcnDB}
{!!RFG 042198 Changed AdjustValue to reflect even digit count
for numeric BCD values. This matches how the
Database Desktop builds BCD values.
unit GSF_MDX}
{!!RFG 041398 Changed DoOnIndexFilesChange to exit in called while
reading the DFM stream on load. This was forcing Active
true in the loading process.
unit HalcnDB}
{!!RFG 041298 Restored line in THCBlobStream.Read to increment the stream
position. Line had somehow been deleted.
unit HalcnDB}
{!!RFG 040898 In GetFieldData, added test for memo/blob fields so that
TField.IsNull will return true if there is no memo pointer
for the memo.
unit HalcnDB}
{!!RFG 040698 Added call to Pack to ensure cache was off so the cached
Records would not be used on a Pack. This caused some
deleted records to still be included since they were still
undeleted in the cached area.
Unit HalcnDB}
{!!RFG 040698 Added InternalRecall and Recall to handle 'undeleting' deleted
records that were still in the file.
Unit HalcnDB}
{!!RFG 040698 Added code in gsPack to ensure record caching was cleared
in case deleted records were in cache as undeleted.
Unit GSF_DBsy}
{!!RFG 040598 Fixed problem in Index to call gsIndex instead of gsIndexRoute.
There were possible problems when passing multiple files with
"file not found".
Unit HalcnDB}
{!!RFG 040598 Removed forced RunError for some errors in DoOnHalcyonError.
Unit HalcnDB}
{!!RFG 040598 In Delphi, errors generate an exception instead of Halt.
Unit GSF_Eror}
{!!RFG 040298 Corrected problem with storing small integers in SetFieldData.
The SmallInt data type was not properly read from the buffer.
This was improperly fixed 021998 because of using shortint
instead of smallint. This only allowed values -128-127.
Unit HalcnDB}
{!!RFG 032598 Changed error reporting in gsNumberPutN to report the
Field name when a number is too large to fit in the field.
Unit GSF_DBF}
{!!RFG 032498 Changed gsSearchDBF so exact match compares ignore trailing
spaces.
Unit GSF_DBSY}
{!!RFG 031498 Ensured the correct value was stored as the Size property
for a TStringField. It was being returned with a value one
greater than the string length.
Unit HalcnDB}
{!!RFG 031398 Added an IndexFiles OnChange event for when IndexFiles has
entries added via IndexFiles.Add(). It should be calling
the Index command but did not get the notification. The
situation is that the IndexFiles list has all the index
files, but forgets to tell the Halcyon engine to use them.
This continues until the next time the table is closed
and reopened.
Unit HalcnDB}
{!!RFG 031098 Corrected code in gsIndexFileRemove and gsIndexFileKill to
ensure IndexMaster is not nil before comparing its Owner
property to the target file object.
Unit GSF_DBSY}
{!!RFG 022798 In gsGetRec, reversed sequence of checking Filter and
Deleted conditions so that the deleted condition is
checked first. This way the filter is not called for
deleted records when UseDeleted is false.
Unit GSF_DBSY}
{!!RFG 022798 Added code to Locate to ensure a physical table search used
ExactMatch if loPartialKey was not set.
Unit HalcnDB}
{!!RFG 022698 Added Alias support for DatabaseName. The dropdown combo
for the DatabaseName property will display alias names that
are available. The first one, 'Default Directory', just
assigns the same directory that the executable is in at
runtime. This allows easy linkage of databases that are
stored in the same directory as the executable. The file
'halcyon.cfg' can be used to add more alias names that may
be selected. This file must be in the Windows directory,
normally c:\windows. It is actually an 'ini' file that is
read using routines in the Inifiles unit. Format is:
[Alias]
DBDEMOS=C:\DELPHI16\DEMOS\DATA
QUIKQUOT=c:\qqdb
This may be used to add alias names and their related file
paths. The file path can be different for the same alias on
each machine running the program.
Unit HalcnDB}
{!!RFG 022198 Added code to gsGetRec to more efficiently handle a call
with RecNum set to 0. It avoids recursion to find the
first record in the file.
Unit GSF_DBSY}
{!!RFG 022198 Added code to gsGetRec to more efficiently handle a call
with RecNum set to 0.
Unit GSF_DBF}
{!!RFG 022198 Changed DBFFileName in header to store only the
first 8 chars of the file name. This errors out
in Database Desktop otherwise.
Unit GSF_MDX}
{!!RFG 022098 Removed code that automatically tried to open a file
in ReadOnly mode if it failed in ReadWrite. This was
included originally to allow CD-Rom files to be opened
without changing the mode in the program. It causes a
problem when opening against a file already opened in
Exclusive mode.
Unit GSF_Disk}
{!!RFG 022098 Ensured on tables with 0 records that Find, Locate, and Lookup
immediately return false without attempting to find a record.
Unit HalcnDB}
{!!RFG 021998 Correct problem with storing small integers in SetFieldValue.
The SmallInt data type was not properly read from the buffer.
Unit HalcnDB}
{!!RFG 021498 Corrected THCBlobStream.Destroy to properly update empty memo
fields. The memo field was not being updated when all characters
were deleted.
Unit HalcnDB}
{!!RFG 021098 Added a unit to allow Halcyon to be used with InfoPower. You
also need to have InfoPower 3.01, which can be downloaded from
the Woll2Woll website at http://www.woll2woll.com
Unit Halcn4ip}
{!!RFG 020998 Fixed memory access error in THCBlobStream, where the Translate
call could 'Translate' bytes beyond the end of the blob string
if it did not find a Zero termination. Added one extra byte to
the GetMem/FreeMem size of FMemory and inserted a #0.
Unit HalcnDB}
{!!RFG 020598 Now use the actual size of the file to compute the record
count instead of the count in the header. This is
consistent with dBase and avoids bad header data if the
header was not updated on a program failure.
recordcount = (filesize-headerlength) div recordsize
Unit GSF_DBF}
{!!RFG 020598 Removed Mutex waiting in gsUnlock to avoid possible
gridlock if another thread is attempting to lock and
owns the mutex. This would prevent the other thread
from unlocking the record the first thread is waiting for.
Unit GSF_Disk}
{!!RFG 020398 Added code in SetFieldData to ensure nil buffer values did not
generate an access protection error.
Unit HalcnDB}
{!!RFG 012298 Corrected problem where index files greater than 16MB can
cause a Range Error.
Unit GSF_CDX}
{!!RFG 012198 added test in CmprOEMBufr to test for unequal field
comparisons where the comparison was 1 and the compare
position was greater than the length of the first key.
This happened on keys where characters < #32 were used.
For example, 'PAUL' and 'PAUL'#31 would determine that
'PAUL' was greater than 'PAUL'#31 because the default
#32 would be compared against the #31 in the second key.
GSF_Xlat}
{!!RFG 012198 Added ability to handle the '-' concatanation, where
the element is trimmed of trailing spaces and they are
added to the end of the key. For example, 'LName-FName'
would trim LName, add FName, and pad the end of the
expression with the spaces that were trimmed to give the
correct expression length.
GSF_Expr}
{!!RFG 011498 Added ability to support logical fields in function
ResolveFieldValue. It will return 'T' or 'F'.
GSF_Expr}
{!!RFG 011498 Added ability to handle expressions surrounded by ().
GSF_Expr}
{!!RFG 011098 Repaired MDX numeric index key manipulation
routines to ensure the correct key digit count
was returned on a record update. The BCD field
requires a count of digits uses, and this was not
accurately returned in PageStore.
GSF_MDX}
{!!RFG 010998 Corrected Find to default to the last record in the table if
the key is not found and isNear is false. Locate still remains
on the original record if the record cannot be found.
Unit HalcnDB}
{!!RFG 010898 Added routine to automtatically set the correct date format
in Delphi. This is based on the Windows date format.
Unit GSF_Date}
{!!RFG 010898 Made changes to THCBlobStream to correct problems in NT4.0.
When run from the IDE, the program would hang on a hardware
breakpoint after termination. This took place in the
TMemoryStream.SetCapacity method at the GlobalFree command.
Unit HalcnDB}
{!!RFG 010898 Corrected problem in THCBlobstream.Create that caused an access
violation on an empty table if memos were to be loaded.
Unit HalcnDB}
{!!RFG 010898 Added gsHuntDuplicate method. This lets the programmer check
to see if the hunted key already exists in the index. Return
value is a longint that holds -1 if the tag cannot be found,
0 if the key does not duplicate one already in the index, or
the record number of the first record with a duplicate key.
Unit HalcnDB}
{!!RFG 010698 Included a line of code that was accidentally deleted at some
point in InternalOpen. This line raises an exception if the
table cannot be opened. The code was a safety valve since the
exception would normally be raised during the open attempt, and
thus should never be reached in any case. However, the missing
line of code caused the next line to be executed only if the
table opening was unsuccessful, which would have caused an
access violation. Since the table was successfully opened, the
line of code was skipped, which could cause the ReadOnly flag
to be incorrectly set instead.
Unit HalcnDB}
{!!RFG 121797 Changed InternalAddRecord to always append. This is consistent
with the BDE's DBIInsertRecord, which just does an append for
a dBase file. Note the help for Delphi's InsertRecord is wrong
when it says a record will be inserted at the current position.
Unit HalcnDB}
{!!RFG 121697 Ensured that the NotifyEvent function set Modified true if
the event was deFieldChange.
Unit HCL_Tabl}
{!!RFG 121097 Added Header locking at the beginning of the Append process
to ensure no other application will read an 'old' header.
Unit GSF_DBF}
{!!RFG 120997 Added error trap in InternalPost to ensure Append and Replace
return good results.
Unit HalcnDB}
{!!RFG 120897 Added TrimRight to GetFieldData for a Date field to remove the
exception error traps in debug mode when the date field is blank.
The StrToInt conversion caused the exception, which was trapped
and the result set to zero. This worked properly to find a
blank date, but was annoying in debug mode since the program
would halt at the exception unless Break On Exception was
off in the compiler.
Unit HalcnDB}
{!!RFG 120897 Corrected potential problem with filtered index updates in
TagUpdate, where filtered records might not be added to the
index.
Unit GSF_Indx}
{!!RFG 111897 Corrected Translate to test for a nil pointer passed as the
input string.
Corrected LookUp so that a FieldValues argument of null is
properly handled when assigned to a string.
Unit HalcnDB}
{!!RFG 111897 Added STRZERO function to the list of those handled.
Changed ResolveFieldValue to use calls to retrieve the
field data rather than directly accessing the buffer.
This allows a single access point to the buffer, which
means the location can be dynamically changed with no
impact on routines. This is needed for better interface
with Delphi standard data-aware components.
Unit GSF_Expr}
{!!RFG 111897 Ensured the memo files were properly closed in
gsCopyFromIndex.
Unit GSF_DBsy}
{!!RFG 111297 Changed CopyFile and SortFile to use an index if it exists.
Unit GSF_DBsy}
{!!RFG 103197 Fixed problem in DTOC and DTOS functions so that empty
dates for MDX and NDX indexes are properly handled. This
was a problem because empty dates for these indexes are
assigned 1E00 as a value.
Unit GSF_Expr}
{!!RFG 103197 Corrected bug in JulDateStr that could cause a date to
be flagged as empty.
Unit GSF_Indx}
{!!RFG 102797 Corrected Find to ensure the record was properly loaded when
Result was false but IsNear was true.
Unit HalcnDB}
{!!RFG 102697 Ensured the ActiveBuffer contents were copied to the Current
Record buffer during the CopyRecordTo function. It was possible
the Current Recrod buffer was not properly populated
Unit HalcnDB}
{!!RFG 102497 In TagUpdate, made sure there was no range error when
UpdtCtr is incremented beyond 32767.
Unit GSF_NTX}
{!!RFG 102097 In InternalPost, ensured that BeforeBOF and AfterEOF flags
were set false. On Append, the AfterEOF flag is set, and
was not properly cleared. This caused an exception in the
GetRecord Method.
All error messages are now in the constants area to make
language conversion easier.
Unit HalcnDB}
{!!RFG 102097 Added FoundError virtual method to pass errors to the
owning DBF object. This allows capture at a single
point regardless of the object that fails.
Unit GSF_Memo}
{!!RFG 101497 Fixed CompressExpression to allow a space between the
'!,=,<,> operators.
Unit GSF_Expr}
{!!RFG 101497 Added capability to use filtered indexes for NTX files.
Added ExternalChange function to see if the index has
been changed by an external application. This is called
from the Index Owner.
Unit GSF_NTX}
{!!RFG 100997 In THalcyonDataSet, Lookup and Locate have been implemented
to handle optimized searching. If an index exisits on the
field that is not filtered, it will be used. Otherwise, the
table will be searched in natural order.
Unit HalcnDB}
{!!RFG 100797 Corrected error in calculating MaxKeys that could cause
a Range Error on certain key lengths.
(Unit GSF_CDX}
{!RFG 100297 Added ExactMatch property so the current status could be
retrieved.
Unit HCL_Tabl}
{!!RFG 100297 Added code in HDBLookupComboBox to force the PickDBFTable's
SetExact property true when Style = csDropDownList. This
ensures an empty display field on Append or an empty file.
Unit HCL_LkUp}
{!!RFG 100297 Changed Bookmark values to be PChar values containing the
record number. It was just a longint, but the TDBGrid
treats it as a string for storage of multiselected rows.
Although it works properly, since only pointers are saved,
there could be problems with descendant third-party grids
that actually tried to copy or modify the bookmarks.
Added Try..Except block in SetIndexName to trap error on
Resync when setting an index tag on an empty file.
Unit HalcnDB}
{!!RFG 100197 Added GetCanModify method to override TDataSet to detect
ReadOnly
Added CompareBookmarks to overide TDataSet. Corrects error
in the DBGrid when multiselect option is enabled
Added code to GetActiveRecBuf to handle the TField.OldValue
function to return the original field information. The
TField.NewValue function also works now. CurValue is not
supported.
Unit HalcnDB}
{!!RFG 091797 Corrected KeyFind to return 0 if a matched key is not
in the current range.
Unit GSF_Indx}
{!!RFG 091697 Added more calls to gsHdrRead to ensure the NumRecs value
was current. Added in gsAppend, gsClose, and gsPutRec.
Unit GSF_DBF}
{!!RFG 091597 Corrected error in GetChild that caused an error on a
TagUpdate if Next Avail was -1. This fixes an error
introduced on 091197 in testing for corrupted indexes.
Unit GSF_Indx}
{!!RFG 091597 Modified GSGetExpandedFile to handle Netware Volumes.
Unit GSF_DOS}
{!!RFG 091397 Added GSFileDelete Function. Returns 0 if successful, -1
if not.
Unit GSF_DOS}
{!!RFG 091397 Added test to recreate the index if filesize was less than
or equal to CDXBlokSize. This allows the file to be
recreated by truncation to 0 bytes and using IndexOn in
a shared environment.
Unit GSF_CDX}
{!!RFG 091297 Made Index a function so error results could be returned.
Unit GSF_Shel}
{!!RFG 091297 In DefCapError, it now passes the Code value even when Info
is gsfMsgOnly. This allows cleaner error handling since
it can aviod calling Halt on all errors in the basic engine.
Unit GSF_EROR}
{!!RFG 091297 In HalcyonError, added test to handle gsfMsgOnly so that the
program is not halted when the code is in the Info argument.
Unit HCL_Tabl}
{!!RFG 091297 Rewrote the GSGetFAttr routine to replace The FindFirst
routine with the DOS $43 Get File Attributes call. This
was necessary because Novell file permissions could deny
users ScanFiles permissions, which prevents FindFirst from
working properly.
Unit GSF_DOS}
{!!RFG 091297 Made gsIndex a function so error results could be returned.
Unit GSF_DBSY}
{!!RFG 091297 Added testing for a corrupt index in IndexRoute and IndexTo.
Unit GSF_DBSY}
{!!RFG 091297 Added ExternalChange to test if the index has been
changed by another program.
Units GSF_CDX, GSF_Indx}
{!!RFG 091197 Added testing for corrupted indexes.
Units GSF_CDX, GSF_Indx}
{!!RFG 090997 Corrected problem with SetFieldData that caused a pointer error
or invalid date if a date field was empty.
unit HalcnDB}
{!!RFG 090697 Corrected problem with GetFieldData that failed to return a
false if character or date fields were empty.
unit HalcnDB}
{!!RFG 090597 Established an AdjustToSize property for the HDBLookupCombo
dropdown box. If true, the size of the dropdown box will shrink
if there are fewer entries than fit in the DropDownHeight size.
unit GSF_LkUp}
{!!RFG 090597 Restored variable sp in several methods. This var is needed
when the FOXGENERAL conditional define is on.
unit GSF_CDX}
{!!RFG 090597 Added ActiveRowsInGrid, which returns the number of records
in the browse array. This is handy for detecting empty grids
or determining if the grid is filled.
unit HCL_Grid}
{!!RFG 090597 In DoTakeAction, forced initial FDBFName to be uppercased.
The table name was still being compared case sensitive in
certain situations
unit HCL_Grid}
{!!RFG 090597 In HDBLookupCombo.DataChange, ensured that DBFTable is not nil
before attempting a StringGet against it. There is a possible
sequencing problem if DataModules are used as different forms
are opened and the components created on shared tables.
unit HCL_LkUp}
{!!RFG 090397 Corrected error in TCreateHalcyonDataSet where an empty
DBFTable DataBaseName field could cause a protection error.
unit HalcnDB}
{!!RFG 090397 Corrected a problem in SetFieldData where an empty Date field
caused a protection fault because TDataSet sends a nil buffer
pointer.
unit HalcnDB}
{!!RFG 090297 Fixed HDBLookupCombo so that the correct PickDisplayText shows
regardless of the sequence in which tables are opened. In the
past, the PickDBF file had to be opened first.
Blocked property PickDBFDisplay in in HDBLookupCombo so that if
Style is csDropDown, no field other than PickDBFField may be
used. This is essential since no relationship can be made if
there is a manual entry.
unit HCL_LkUp}
{!!RFG 090297 Changed HTable.Attach to send MessageDlg warning instead
of Exception when the table does not exist at design time.
This removes a problem where the table's Active property
is true, but the file does not exist for some reason. In
the past, an exception was generated and this kept the form
from loading. The only fix was to either put the file in
the proper directory or modify the DFM.
unit HCL_Tabl}
{!!RFG 090297 Corrected error in SubStr function that caused it to reject
if the last string position was used as the start position.
unit GSF_Expr}
{!!RFG 090297 added argument to CmprOEMBufr() to define the substitute
character to use for unequal field length comparisons.
Numeric fields in CDX indexes could fail.
units GSF_Xlat, GSF_Indx, GSF_Dbsy}
{!!RFG 090197 Corrected HDBEdit.WMPaint so that edit boxes that are
centered or right justified are displayed properly in Delphi
2 and 3. They had a heavy inside black line under most
conditions.
unit HCL_Ctrl}
{!!RFG 083097 Corrected broLnUp to ensure the same record was not
loaded into the array twice. This could happen in certain
situations where more than LinesAvail records get added to
the array. If this is the case, then the last record would
be added again in UpdateBrowse, since it assumes the current
record is the last record.
unit GSF_Brow}
{!!RFG 083097 Added gsvIndexState to flag Index conditions for faster
index operations. This is used in GSO_dBHandler.gsGetRec.
unit GSF_DBF}
{!!RFG 083097 In GSO_dBHandler.gsGetRec, added test for gsvIndexState so
that the I/O activity is reduced for indexing operations if
there are many rejected records via TestFilter or deleted
records. This prevents the forced positioning of the file
to the last good record, which requires a reread and test of
every record. This is needed during normal processing, but
is unnecessary in a controlled sequential read during
indexing.
unit GSF_DBSY}
{!!RFG 083097 In DoIndex, within the routine for memory indexing, added
code to set flag gsvIndexState in the DBF object to reduce
the record read activity when there are many records that
are rejected.
unit GSF_CDX}
{!!RFG 083097 Changed RecNo to ensure record number is properly returned
while in dsIndex state.
unit HCL_Tabl}
{!!RFG 082997 Added broLnSame to UpdateBrowse procedure to force an
insertion of the current record at the top of the list. This
is to speed arrow up scrolling in HCL_Grid.
unit GSF_Brow}
{!!RFG 082997 Changed SyncTable and added FSkipValue to allow one-record
movement on an up-arrow scroll. This already happened for
down-arrow moves, but scrolling up caused all grid records
to be reread, an unnecessarily slow operation.
unit HCL_Grid}
{!!RFG 082997 In KeyDown method, added test for VK_RIGHT and VK_LEFT. If
Permissions has dgRowSelected then these keys will now move
to the next or previous record. This caused 'strange' grid
displays before.
unit HCL_Grid}
{!!RFG 082897 Fixed recursion problem in gsExternalChange.
unit GSF_DBF}
{!!RFG 082397 Added .NOT.DELETED as another function to be tested.
unit GSF_Expr}
{!!RFG 082397 Changed Permissions property to make dgEditing a default.
unit HCL_Grid}
{!!QNT 082397 Added RecordInGrid function that returns true if the record
number passed is in the VisibleRow portion of the grid. To
test for the top record in the logical file, use 0 as the
argument value.
unit HCL_Grid}
{!!RFG 082097 Changed controls' DataChange to set the modified flag false.
The control could generate an error "Not in Edit Mode" when
focus was moved from the checkbox. Only the HDBEdit and
HDBList controls properly set the modified flag.
unit HCL_Ctrl}
{!!RFG 082097 Added code in GSO_dBaseDBF.Create to initialize RecModified
to false. There was a possibility of this indicationg true
in a Delphi application since Delphi does not initialize
objects memory to zeros.
unit GSF_DBF}
{!!RFG 082097 Added HuntDuplicate function. This lets the programmer
check to see if the hunted key already exists in the index.
Return value is a longint that holds -1 if the tag cannot
be found, 0 if the key does not duplicate one already in
the index, or the record number of the first record with a
duplicate key.
units GSF_Shel, HCL_Tabl, HalcnDB}
{!!RFG 082097 Changed Post method to ensure all controls were notified
to update changes prior to the call to OnValidate. The
active control thus will be notified and insert any change
in the record buffer. Previously, the focused control did
not update the record on a call to Post since its OnExit
event was not called. This meant the OnValidate event
did not see the latest change to the field. The UpdateData
notification just ocurred immediately before the physical
record write. Now, the OnValidate and BeforePost events
see all the record changes.
unit HCL_Tabl}
{!!RFG 082097 Added code in PostWrite NotifyEvent to set the new file
position properly when a record is updated. With
indexes, it will set the File_TOF/File_EOF if the new
indexed position is at the beginning or end of the
index. In natural order, if the first or last record is
updated, the proper TOF/EOF flag is set.
unit GSF_Dbsy}
{!!RFG 082097 Modified RetrieveKey to return BOF/EOF information. The
return integer will have bit 0 set for BOF, and bit 1 set
for EOF. This is used in TagOpen to set TagBOF and TagEOF.
Main use is on KeySync to get the position of the record
being synchronized.
unit GSG_Indx}
{!!RFG 081997 Added PopupMenu property.
unit HCL_Grid}
{!!RFG 081997 Changed gsLokOff so gsHdrWrite is only called if unlocking
a file lock. It is bypassed if it is a record lock, since
the header has already been updated.
unit GSF_DBF}
{!!RFG 081897 Fixed error in sorting unique indexes where the key was blank.
unit GSF_Sort}
{!!RFG 081897 Changed multi-user update testing by placing the time of the
update rather than maintaining a count. This eliminates the
header reading required for every record update. Also added
UserID information so that the User who last updated the table
is known.
Added ExternalChange function, which reports if this or
another application modified the table. A return of 0 means
no changes, 1 means this application made a change, 2 means
an external application changed the table, and 3 means there
was both an internal and external change, with the external
change ocurring last. All change flags are cleared when this
function is called.
Added gsExternalChange function, which returns true if
another application modified the table.
Added gsAssignUserID procedure, which assigns a longint id for
the current user. This id is placed in the DBF header each
time gsHdrWrite is called (normally for each ecord write).
The ID allows tracing file updates for debugging/audit
purposes.
Added gsReturnDateTimeUser procedure that returns the date,
time, and user for the last DBF file update. These are three
longint vars.
Replaced TableChanged boolean with ExtTableChg to indicate
another application changed something in the table. This
is set during gsHdrRead.
Replaced var UpdateCount with UpdateTime, which keeps the
time of the last update as computed in gsHdrWrite.
unit GSF_DBF}
{!!RFG 081897 Added ExternalChange function, which returns true if another
application modified the table.
Added AssignUserID procedure, which assigns a longint id for
the current user. This id is placed in the DBF header each
time gsHdrWrite is called (normally for each record write).
The ID allows tracing file updates for debugging/audit
purposes.
Added ReturnDateTimeUser procedure that returns the date,
time, and user for the last DBF file update. These are three
longint vars.
units GSF_Shel, HCL_Tabl, HalcnDB}
{!!RFG 081897 Corrected scrollbar positioning where upon a RefreshGrid
the Scrollbar would always drop out of the Top Record
indication. Also, on horizontal the scrollbar always
jumped to Top Record indication.
unit HCL_Grid}
{!!RFG 081397 Changed SyncWithPhysical to add brSame to possible
AlignRec options. This will reload all records in the
same position relative to the current record, if possible.
Upon return, the current record will be in the same position
in the array as upon entering, assuming it was not deleted
by another user. This keeps grids from jumping the current
record to the top or bottom on a resync.
unit GSF_Brow}
{!!RFG 081397 Changed RefreshGrid to refresh all records and leave the
current record in its same position in the grid, if possible.
Added ResyncGrid that has the same behavior as the old
RefreshGrid for order changes, table changes, append, etc.
unit HCL_Grid}
{!!RFG 081397 Added transliterate feature to HDBMemo. While it was
there for MemoLoad, it was omitted in UpdateData prior
to the MemoSave.
unit HCL_Ctrl}
{!!RFG 081397 Changed Clipper lock for index to the correct location
for 'old' Clipper index lock position.
unit GSF_Indx}
{!!RFG 081297 Fixes for error on getting a record from an empty file
unit HalcnDB}
{File Modes (including sharing)}
dfCreate = $0F;
fmOpenRead = $00;
fmOpenWrite = $01;
fmOpenReadWrite = $02;
fmShareCompat = $00;
fmShareExclusive = $10;
fmShareDenyWrite = $20;
fmShareDenyRead = $30;
fmShareDenyNone = $40;
Null_Record = 0; {file not accessed yet}
Next_Record = -1; {Token value passed to read next record}
Prev_Record = -2; {Token value passed to read previous record}
Top_Record = -3; {Token value passed to read first record}
Bttm_Record = -4; {Token value passed to read final record}
Same_Record = -5; {Token value passed to read record again}
ValueHigh = 1; {Token value passed for key comparison high}
ValueLow = -1; {Token value passed for key comparison low}
ValueEqual = 0; {Token value passed for key comparison equal}
MaxRecNum = $7FFFFFFF;
MinRecNum = 0;
IgnoreRecNum = -1;
LogicalTrue: string = 'TtYyJj';
LogicalFalse: string = 'FfNn';
dBaseMemoSize = 512; {Block size of dBase memo file data}
FoxMemoSize = 64; {Block size of FoxPro memo file data}
AreaLimit = 40;
dBaseJul19800101 = 2444240;
{private}
{Object type constants}
GSobtInitializing = $0001; {Object in Initialization}
GSobtIndexTag = $0010; {GSobjIndexTag}
GSobtCollection = $1000; {GSobjCollection}
GSobtSortedCollection = $1100; {GSobjSortedCollection}
GSobtStringCollection = $1200; {GSobjStringCollection}
GSobtLongIntColl = $1300; {GSobjLongIntColl}
GSobtFileColl = $1400; {GSobjFileColl}
GSobtRecordColl = $1500; {GSobjRecordColl}
GSobtIndexKey = $1600; {GSobjIndexKey}
GSobtDiskFile = $2000; {GSO_DiskFile}
GSobtIndexFile = $2001; {GSobjIndexFile}
GSobtDBase = $2100; {An xBase database file}
GSobtDBaseSys = $2101; {GSO_dBHandler}
GSobtDBFFile = $2111; {dBase file (DBF)}
GSobtDBTFile = $2121; {dbase Memo file (DBT)}
GSobtFPTFile = $2122; {FoxPro Memo file (FPT)}
GSobtNDXFile = $2131; {dBase NDX index}
GSobtMDXFile = $2132; {dBase MDX index}
GSobtNTXFile = $2133; {Clipper NTX File}
GSobtCDXFile = $2134; {FoxPro CDX file}
GSobtRYOFile = $2135; {"Roll Your Own" index file}
GSobtMIXFile = $2136; {In-Memory index file}
GSobtString = $4100; {GSobjString}
{ Globally used constants and types }
DB3File = $03; {First byte of dBase III(+) file}
DB4File = $03; {First byte of dBase IV file}
FxPFile = $03; {First byte of FoxPro file}
DB3WithMemo = $83; {First byte of dBase III(+) file with memo}
DB4WithMemo = $8B; {First byte of dBase IV file with memo}
FXPWithMemo = $F5; {First byte of FoxPro file with memo}
VFP3File = $30; {First byte of Visual FoxPro 3.0 file}
GS_dBase_UnDltChr = #$20; {Character for Undeleted Record}
GS_dBase_DltChr = #$2A; {Character for Deleted Record}
EOFMark : char = #$1A; {Character used for EOF in text files}
GSchrNull = #0;
GSMSecsInDay = 24 * 60 * 60 * 1000;
GSTimeStampDiff = 1721425;
{ Status Reporting Codes }
StatusStart = -1;
StatusStop = 0;
StatusIndexTo = 1;
StatusIndexWr = 2;
StatusSort = 5;
StatusCopy = 6;
StatusPack = 11;
StatusSearch = 21;
GenFStatus = 901;
type
{$IFNDEF WIN32}
SmallInt = integer;
{$ENDIF}
GSstrTinyString = string[15];
GSptrByteArray = ^GSaryByteArray;
GSaryByteArray = array[0..65519] of byte;
GSptrPointerArray = ^GSaryPointerArray;
GSaryPointerArray = array[0..16379] of pointer;
GSptrWordArray = ^GSaryWordArray;
GSaryWordArray = array[0..32759] of word;
GSptrLongIntArray = ^GSaryLongIntArray;
GSaryLongIntArray = array[0..16379] of longint;
GSptrCharArray = ^GSaryCharArray;
GSaryCharArray = array[0..65519] of char;
GSsetDateTypes = (American,ANSI,British,French,German,Italian,Japan,
USA, MDY, DMY, YMD);
GSsetSortStatus = (Ascending, Descending, SortUp, SortDown,
SortDictUp, SortDictDown, NoSort,
AscendingGeneral, DescendingGeneral);
GSsetFlushStatus = (NeverFlush,WriteFlush,AppendFlush,UnLockFlush);
GSsetLokProtocol = (Default, DB4Lock, ClipLock, FoxLock);
GSsetIndexUnique = (Unique, Duplicates);
{$IFOPT N+}
FloatNum = Extended;
{$ELSE}
FloatNum = Real;
{$ENDIF}
CaptureStatus = Procedure(stat1,stat2,stat3 : longint);
{$IFNDEF WIN32}
var
GSintLastError: integer;
{$ENDIF}
implementation
end.
|
unit fGridOpts;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.UITypes,
System.SysUtils,
System.Variants,
System.Classes,
System.Math,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.ExtCtrls,
Vcl.Buttons,
Vcl.ComCtrls,
Vcl.Menus,
uParser,
uGlobal;
type
TGridOptionsForm = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
EditMinY: TEdit;
EditMinX: TEdit;
EditMaxX: TEdit;
EditMaxY: TEdit;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
SpeedButton3: TSpeedButton;
SpeedButton4: TSpeedButton;
SpeedButton5: TSpeedButton;
SpeedButton6: TSpeedButton;
SpeedButton7: TSpeedButton;
SpeedButton8: TSpeedButton;
EditAxesPen: TEdit;
UpDown1: TUpDown;
EditMajorGrid: TEdit;
UpDown2: TUpDown;
EditMinorGrid: TEdit;
UpDown3: TUpDown;
GridStyles: TRadioGroup;
xTrackBar: TTrackBar;
yTrackBar: TTrackBar;
BitBtn1: TBitBtn;
ApplyBitBtn: TBitBtn;
ColorDialog: TColorDialog;
FontDialog: TFontDialog;
LogXCheck: TCheckBox;
LogYCheck: TCheckBox;
SaveSpeedButton: TSpeedButton;
RestoreSpeedButton: TSpeedButton;
procedure FormShow(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
procedure ApplyBitBtnClick(Sender: TObject);
procedure EditMinXKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure EditMaxXKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure EditMinYKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure EditMaxYKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure EditPenKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure EditPenChange(Sender: TObject);
procedure EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure ParseKeyPress(Sender: TObject; var Key: Char);
procedure IntKeyPress(Sender: TObject; var Key: Char);
procedure GridStylesClick(Sender: TObject);
procedure ColorClick(Sender: TObject);
procedure FontClick(Sender: TObject);
procedure LogXCheckClick(Sender: TObject);
procedure LogYCheckClick(Sender: TObject);
procedure Centre(Sender: TObject);
procedure EqualGrad(Sender: TObject);
procedure EqualRange(Sender: TObject);
procedure xTrackBarChange(Sender: TObject);
procedure yTrackBarChange(Sender: TObject);
procedure SaveSpeedButtonClick(Sender: TObject);
procedure RestoreSpeedButtonClick(Sender: TObject);
private
function AnyPolar: Boolean;
public
procedure ShowData;
end;
var
GridOptionsForm: TGridOptionsForm;
//========================================================================
implementation
//========================================================================
uses
fMain,
fTextBlocks,
fFuncts;
{$R *.dfm}
procedure TGridOptionsForm.FormShow(Sender: TObject);
begin
Caption := GraphFName;
ShowData;
end;
procedure TGridOptionsForm.BitBtn1Click(Sender: TObject);
begin
Close;
end;
procedure TGridOptionsForm.ApplyBitBtnClick(Sender: TObject);
procedure Swap(var n1, n2: extended);
var
n: extended;
begin
n := n1;
n1 := n2;
n2 := n;
end;
begin
with GraphData do
begin
if xMin = xMax then xMax := 1.1*xMin;
if yMin = yMax then yMax := 1.1*yMin;
if xMin > xMax then Swap(xMin, xMax);
if yMin > yMax then Swap(yMin, yMax);
end;
Altered := True;
MainForm.GLViewer.Invalidate;
ApplyBitBtn.Visible := False;
end;
procedure TGridOptionsForm.EditMinXKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
x: extended;
s: string;
e: byte;
begin
with GraphData do
begin
s := ScanText(EditMinX.Text);
x := ParseAndEvaluate(s, e);
if isNAN(x) or isInfinite(x) then x := 0;
if (e = 0) and((Grid.xAxisStyle <> asLog) or (x > 0)) then xMin := x
else if Grid.xAxisStyle = asLog then xMin := 0.1 else xMin := -0.1;
end;
end;
procedure TGridOptionsForm.EditMinYKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
y: extended;
s: string;
e: byte;
begin
with GraphData do
begin
s := ScanText(EditMinY.Text);
y := ParseAndEvaluate(s, e);
if isNAN(y) or isInfinite(y) then y := 0;
if (e = 0) and((Grid.yAxisStyle <> asLog) or (y > 0)) then yMin := y
else if Grid.yAxisStyle = asLog then yMin := 0.1 else yMin := -0.1;
end;
end;
procedure TGridOptionsForm.EditMaxXKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
x: extended;
s: string;
e: byte;
begin
with GraphData do
begin
s := ScanText(EditMaxX.Text);
x := ParseAndEvaluate(s, e);
if isNAN(x) or isInfinite(x) then x := 0;
if (e = 0) and((Grid.xAxisStyle <> asLog) or (x > 0)) then xMax := x
else xMax := 0.1;
end;
end;
procedure TGridOptionsForm.EditMaxYKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
y: extended;
s: string;
e: byte;
begin
with GraphData do
begin
s := ScanText(EditMaxY.Text);
y := ParseAndEvaluate(s, e);
if isNAN(y) or isInfinite(y) then y := 0;
if (e = 0) and((Grid.yAxisStyle <> asLog) or (y > 0)) then yMax := y
else yMax := 0.1;
end;
end;
procedure TGridOptionsForm.EditPenKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
w: integer;
begin
if Active then
with Sender as TEdit do
begin
try
w := StrToInt(Text);
except
w := 1;
end;
if w < 1 then w := 1;
with GraphData do
case Tag of
0:AxisWidth := w;
1:MajorWidth := w;
2:MinorWidth := w;
end;
Altered := True;
MainForm.GLViewer.Invalidate;
end;
end;
procedure TGridOptionsForm.EditPenChange(Sender: TObject);
var
k: word;
begin
k := 0;
EditPenKeyUp(Sender, k, []);
end;
procedure TGridOptionsForm.EditKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Active and ((Key = VK_DELETE) or (Key = VK_BACK))
then ApplyBitBtn.Visible := True;
end;
procedure TGridOptionsForm.ParseKeyPress(Sender: TObject; var Key: Char);
begin
with Sender as TEdit do
begin
if not CharInSet(UpCase(Key),
[' ', '!', '(', ')', '*', '+', '-', '.', ',', '/', '0'..'9',
'A'..'C', 'E', 'G'..'I', 'L', 'N'..'T', 'X', '^', '`', #8]) then
begin
Key := #0;
Exit;
end
else if Active then ApplyBitBtn.Visible := True;
if Key = '`' then Key := '°';
end;
end;
procedure TGridOptionsForm.IntKeyPress(Sender: TObject; var Key: Char);
begin
with Sender as TEdit do
if not CharInSet(Key, ['0'..'9', #8]) then Key := #0
end;
procedure TGridOptionsForm.xTrackBarChange(Sender: TObject);
begin
if Active then with GraphData do
begin
if xTrackBar.Position > 10
then xMinorGrad := 10*(xTrackBar.Position - 10)
else xMinorGrad := xTrackBar.Position;
xMajorGrad := 10*xMinorGrad;
Altered := True;
MainForm.GLViewer.Invalidate;
end;
end;
procedure TGridOptionsForm.yTrackBarChange(Sender: TObject);
begin
if Active then with GraphData do
begin
if yTrackBar.Position > 10
then yMinorGrad := 10*(yTrackBar.Position - 10)
else yMinorGrad := yTrackBar.Position;
yMajorGrad := 10*yMinorGrad;
Altered := True;
MainForm.GLViewer.Invalidate;
end;
end;
procedure TGridOptionsForm.GridStylesClick(Sender: TObject);
begin
if Active then
begin
with GridStyles, GraphData do Grid.GridStyle := TGridStyle(ItemIndex);
Altered := True;
MainForm.GLViewer.Invalidate;
end;
end;
procedure TGridOptionsForm.ColorClick(Sender: TObject);
begin
with GraphData do
begin
case TSpeedButton(Sender).Tag of
0:ColorDialog.Color := BackColor;
1:ColorDialog.Color := GridColor;
2:ColorDialog.Color := xAxisColor;
3:ColorDialog.Color := yAxisColor;
end;
if ColorDialog.Execute then
begin
case TSpeedButton(Sender).Tag of
0:begin
BackColor := ColorDialog.Color;
MainForm.GLViewer.Buffer.BackgroundColor := BackColor;
with TextBlocksForm
do if BlockListBox.Count > 0 then RichEdit.Color := BackColor;
end;
1:GridColor := ColorDialog.Color;
2:xAxisColor := ColorDialog.Color;
3:yAxisColor := ColorDialog.Color;
end;
Altered := True;
MainForm.GLViewer.Invalidate;
end;
end;
end;
procedure TGridOptionsForm.FontClick(Sender: TObject);
begin
with FontDialog, GraphData do
begin
case TSpeedButton(Sender).Tag of
0:begin
Font.Name := FontName;
Font.Style := FontStyle;
Font.Size := FontSize;
end;
end;
if Execute then
begin
case TSpeedButton(Sender).Tag of
0:begin
FontName := Font.Name;
FontStyle := Font.Style;
FontSize := Font.Size;
end;
end;
Altered := True;
NewFont := True;
MainForm.GLViewer.Invalidate;
end;
end;
end;
procedure TGridOptionsForm.LogXCheckClick(Sender: TObject);
var
d: extended;
begin
if AnyPolar then { can not use log axes }
begin
LogXCheck.Checked := False;
MainForm.StatusBar.Panels[2].Text := 'One or more Functions are Polar';
end
else
begin
with GraphData do
begin
if LogXCheck.Checked then
begin
with FunctionsForm do
begin
if Integrate2x.Checked then CloseIntegrateXForm;
if Integrate2y.Checked then CloseIntegrateYForm;
if Between1.Checked then CloseBetweenForm;
if Volumex1.Checked then CloseVolumeXForm;
if Volumey1.Checked then CloseVolumeYForm;
end;
Grid.xAxisStyle := asLog;
if xMin <= 0 then { xMin must be +ve }
begin
d := xMax - xMin;
xMin := (xMax - xMin)/MainForm.GLViewer.Width;
xMax := xMin + d;
EditMinX.Text := FloatToStr(xMin);
EditMaxX.Text := FloatToStr(xMax);
end;
end
else Grid.xAxisStyle := asLinear;
SpeedButton6.Enabled := (Grid.xAxisStyle = asLinear) and
(Grid.yAxisStyle = asLinear);
SpeedButton7.Enabled := SpeedButton6.Enabled or
((Grid.xAxisStyle = asLog) and
(Grid.yAxisStyle = asLog));
SpeedButton8.Enabled := SpeedButton6.Enabled or
((Grid.xAxisStyle = asLog) and
(Grid.yAxisStyle = asLog));
with FunctionsForm do
begin
SwitchButton.Visible := SpeedButton6.Enabled;
Integrate1.Enabled := SpeedButton6.Enabled;
end;
end;
Altered := True;
MainForm.GLViewer.Invalidate;
end;
end;
procedure TGridOptionsForm.LogYCheckClick(Sender: TObject);
var
d: extended;
begin
if AnyPolar then { can not use log axes }
begin
LogYCheck.Checked := False;
MainForm.StatusBar.Panels[2].Text := 'One or more Functions are Polar';
end
else
begin
with GraphData do
begin
if LogYCheck.Checked then
begin
with FunctionsForm do
begin
if Integrate2x.Checked then CloseIntegrateXForm;
if Integrate2y.Checked then CloseIntegrateYForm;
if Between1.Checked then CloseBetweenForm;
if Volumex1.Checked then CloseVolumeXForm;
if Volumey1.Checked then CloseVolumeYForm;
end;
Grid.yAxisStyle := asLog;
if yMin <= 0 then { yMin must be +ve }
begin
d := yMax - yMin;
yMin := (yMax - yMin)/MainForm.GLViewer.Height;
yMax := yMin + d;
EditMinY.Text := FloatToStr(yMin);
EditMaxY.Text := FloatToStr(yMax);
end;
end
else Grid.yAxisStyle := asLinear;
SpeedButton6.Enabled := (Grid.xAxisStyle = asLinear) and
(Grid.yAxisStyle = asLinear);
SpeedButton7.Enabled := SpeedButton6.Enabled or
((Grid.xAxisStyle = asLog) and
(Grid.yAxisStyle = asLog));
SpeedButton8.Enabled := SpeedButton6.Enabled or
((Grid.xAxisStyle = asLog) and
(Grid.yAxisStyle = asLog));
with FunctionsForm do
begin
SwitchButton.Visible := SpeedButton6.Enabled;
Integrate1.Enabled := SpeedButton6.Enabled;
end;
end;
Altered := True;
MainForm.GLViewer.Invalidate;
end;
end;
procedure TGridOptionsForm.RestoreSpeedButtonClick(Sender: TObject);
begin
with GraphData do
begin
if (SavexMin > 0) or (Grid.xAxisStyle = asLinear)
then xMin := SavexMin;
xMax := SavexMax;
if (SaveyMin > 0) or (Grid.yAxisStyle = asLinear)
then yMin := SaveyMin;
yMax := SaveyMax;
EditMinX.Text := FloatToStrF(xMin, ffGeneral, 13, 4);
EditMaxX.Text := FloatToStrF(xMax, ffGeneral, 13, 4);
EditMinY.Text := FloatToStrF(yMin, ffGeneral, 13, 4);
EditMaxY.Text := FloatToStrF(yMax, ffGeneral, 13, 4);
end;
Altered := True;
MainForm.GLViewer.Invalidate;
end;
procedure TGridOptionsForm.Centre(Sender: TObject);
var
x, y: extended;
begin
with GraphData do
begin
x := (xMax - xMin)/2;
xMin := -x;
xMax := x;
y := (yMax - yMin)/2;
yMin := -y;
yMax := y;
EditMinX.Text := FloatToStrF(xMin, ffGeneral, 13, 4);
EditMaxX.Text := FloatToStrF(xMax, ffGeneral, 13, 4);
end;
Altered := True;
MainForm.GLViewer.Invalidate;
end;
procedure TGridOptionsForm.EqualGrad(Sender: TObject);
var
x, y, r: extended;
begin
with GraphData do
begin
x := xMax - xMin;
y := yMax - yMin;
r := (x*MainForm.GLViewer.Height)/(y*Mainform.GLViewer.Width);
if x > y then
begin
yMax := yMax*r;
yMin := yMin*r;
end
else
begin
xMax := xMax/r;
xMin := xMin/r;
end;
EditMinX.Text := FloatToStrF(xMin, ffGeneral, 13, 4);
EditMaxX.Text := FloatToStrF(xMax, ffGeneral, 13, 4);
end;
Altered := True;
MainForm.GLViewer.Invalidate;
end;
procedure TGridOptionsForm.EqualRange(Sender: TObject);
var
x, y: extended;
begin
with GraphData do
begin
x := xMax - xMin;
y := yMax - yMin;
if x > y then
begin
xMax := yMax;
xMin := yMin;
end
else
begin
yMax := xMax;
yMin := xMin;
end;
EditMinX.Text := FloatToStrF(xMin, ffGeneral, 13, 4);
EditMaxX.Text := FloatToStrF(xMax, ffGeneral, 13, 4);
EditMinY.Text := FloatToStrF(yMin, ffGeneral, 13, 4);
EditMaxY.Text := FloatToStrF(yMax, ffGeneral, 13, 4);
end;
Altered := True;
MainForm.GLViewer.Invalidate;
end;
function TGridOptionsForm.AnyPolar: Boolean;
var
i: integer;
Found: Boolean;
begin
with FunctionsForm.CheckListBox do
begin
i := 0;
Found := False;
while not Found and (i < Count) do
begin
Found := not TPlotDataObject(Items.Objects[i]).Data.PlotAsFx
and Checked[i];
Inc(i);
end;
Result := Found;
end;
end;
procedure TGridOptionsForm.SaveSpeedButtonClick(Sender: TObject);
begin
with GraphData do
begin
SavexMin := xMin;
SavexMax := xMax;
SaveyMin := yMin;
SaveyMax := yMax;
RestoreSpeedButton.Visible := (SavexMin <> SavexMax) and
(SaveyMin <> SaveyMax);
end;
end;
procedure TGridOptionsForm.ShowData;
var
b: boolean;
begin
b := Altered;
with GraphData do
begin
RestoreSpeedButton.Visible := (SavexMin <> SavexMax) and
(SaveyMin <> SaveyMax);
EditMinX.Text := FloatToStrF(xMin, ffGeneral, 13, 4);
EditMaxX.Text := FloatToStrF(xMax, ffGeneral, 13, 4);
EditMinY.Text := FloatToStrF(yMin, ffGeneral, 13, 4);
EditMaxY.Text := FloatToStrF(yMax, ffGeneral, 13, 4);
if Active then
ApplyBitBtn.Visible := False;
UpDown1.Position := AxisWidth;
UpDown2.Position := MajorWidth;
UpDown3.Position := MinorWidth;
GridStyles.ItemIndex := Ord(Grid.GridStyle);
LogXCheck.Checked := Grid.xAxisStyle = asLog;
LogYCheck.Checked := Grid.yAxisStyle = asLog;
SpeedButton6.Enabled := not(LogXCheck.Checked or LogYCheck.Checked);
SpeedButton7.Enabled := SpeedButton6.Enabled or
((Grid.xAxisStyle = asLog) and
(Grid.yAxisStyle = asLog));
SpeedButton8.Enabled := SpeedButton6.Enabled or
((Grid.xAxisStyle = asLog) and
(Grid.yAxisStyle = asLog));
Label9.Font.Color := xAxisColor;
Label10.Font.Color := yAxisColor;
xTrackBar.Position := xMinorGrad;
yTrackBar.Position := yMinorGrad;
end;
Altered := b;
end;
end.
|
(*
Category: SWAG Title: STRING HANDLING ROUTINES
Original name: 0069.PAS
Description: Getting Initials
Author: GREG VIGNEAULT
Date: 01-27-94 12:09
*)
{
> 2: And with a string I want to read a specific string and
> get the first to letter of the 1st and last names.
> So for example: Mike Enos ==> ME-DATA.DAT.
>
> Function GetDatName : String;
[deleted]
To get the first letter of a surname, it might be better to scan
from the end of the string -- in case the person also uses their
middle name or initial...
}
PROGRAM Monogram;
VAR
PersonName : STRING[64]; (* person's name(s) *)
FileName : STRING[12]; (* file name *)
Index : WORD; (* character pointer *)
BEGIN
FileName := '??-DATA.DAT'; (* common file name *)
PersonName := 'Jack B. Nimble'; (* example name *)
(* the person's name MUST contain at least one space... *)
IF (Length(PersonName)=0) OR (Pos(' ',PersonName)=0) THEN BEGIN
WriteLn; WriteLn ('First AND Last names, please...');
Halt(1);
END;
(* assume there's no leading white spaces... *)
FileName[1] := UpCase (PersonName[1]); (* pick up 1st char *)
(* scan from the end of PersonName, looking for white space... *)
Index := Length (PersonName);
WHILE (Index > 0) AND (PersonName[Index] > ' ') DO DEC (Index);
INC (Index); (* ... 'cause we went one too many *)
FileName[2] := PersonName[Index]; (* get 1st char of surname *)
WriteLn;
WriteLn ('File name for "',PersonName,'" is ',FileName);
WriteLn;
END.
|
unit Dmitry.Controls.Rating;
interface
uses
System.SysUtils,
System.Classes,
Winapi.Windows,
Winapi.Messages,
Vcl.Graphics,
Vcl.Controls,
Vcl.ExtCtrls,
Vcl.Themes,
Dmitry.Memory,
Dmitry.Graphics.Types,
Dmitry.Graphics.LayeredBitmap,
Dmitry.Controls.Base;
type
TOnRatingMessage = procedure(Sender : TObject; Rating : Integer) of Object;
type
TRating = class(TBaseWinControl)
private
{ Private declarations }
FIsImageCreated: Boolean;
FRating: Integer;
FRatingRange: Integer;
FCanvas: TCanvas;
FIcons: array[0..5] of HIcon;
FDisabledImages: array[0..5] of TLayeredBitmap;
FNormalImages: array[0..5] of TLayeredBitmap;
FOnRating: TOnRatingMessage;
FOnRatingRange: TOnRatingMessage;
FBufferBitmap: TBitmap;
FOnChange: TNotifyEvent;
FIslayered: boolean;
FLayered: integer;
FOnMouseDown: TNotifyEvent;
FImageCanRegenerate: Boolean;
FIsMouseDown: Boolean;
FCanSelectRange: Boolean;
procedure SetRating(const Value: Integer);
procedure SetOnRating(const Value: TOnRatingMessage);
procedure SetOnChange(const Value: TNotifyEvent);
procedure SetIslayered(const Value: boolean);
procedure Setlayered(const Value: integer);
procedure SetOnMouseDown(const Value: TNotifyEvent);
procedure SetImageCanRegenerate(const Value: boolean);
procedure SetRatingRange(const Value: Integer);
procedure SetOnRatingRange(const Value: TOnRatingMessage);
public
{ Protected declarations }
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure Paint(var Message : Tmessage); message WM_PAINT;
procedure Erased(var Message: TWMEraseBkgnd); message WM_ERASEBKGND;
procedure WMMouseDown(var Message: TMessage); message WM_LBUTTONDOWN;
procedure WMMouseUp(var Message: TMessage); message WM_LBUTTONUP;
procedure WMMouseMove(var Message: TMessage); message WM_MOUSEMOVE;
procedure CMMouseLeave(var Message: TWMNoParams); message CM_MOUSELEAVE;
procedure WMSize(var Message : TMessage); message WM_SIZE;
procedure CMColorChanged(var Message: TMessage); message CM_COLORCHANGED;
procedure DoDrawImageByrating(HDC : THandle; X, Y, Rating : integer);
procedure RecreateBuffer;
procedure Refresh;
protected
{ Protected declarations }
procedure CreateLBMP;
published
{ Published declarations }
property Align;
property Anchors;
property Cursor;
property OnDblClick;
property OnClick;
property PopupMenu;
property ParentColor;
property Color;
property Hint;
property ShowHint;
property ParentShowHint;
property Visible;
property Rating: Integer read FRating write SetRating;
property RatingRange: Integer read FRatingRange write SetRatingRange;
property OnRating: TOnRatingMessage read FOnRating write SetOnRating;
property OnRatingRange: TOnRatingMessage read FOnRatingRange write SetOnRatingRange;
property OnChange: TNotifyEvent read FOnChange write SetOnChange;
property Islayered: Boolean Read FIslayered write SetIslayered;
property Layered: Integer Read FLayered write Setlayered;
property OnMouseDown: TNotifyEvent read FOnMouseDown write SetOnMouseDown;
property ImageCanRegenerate: boolean read FImageCanRegenerate write SetImageCanRegenerate;
property CanSelectRange: Boolean read FCanSelectRange write FCanSelectRange;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Dm', [TRating]);
end;
{ TRating }
{$R Ratingres.res}
procedure TRating.Refresh;
begin
RecreateBuffer;
Repaint;
end;
procedure TRating.WMMouseDown(var Message: TMessage);
begin
if not Enabled then
Exit;
FIsMouseDown := True;
Rating := Message.LParamLo div 16;
RatingRange := Rating;
if Assigned(FOnMouseDown) then
FOnMouseDown(Self);
end;
constructor TRating.Create(AOwner: TComponent);
var
I: Integer;
begin
inherited;
Height := 16;
Width := 6 * 16;
FRating := 0;
FRatingRange := 0;
FCanvas := TControlCanvas.Create;
TControlCanvas(FCanvas).Control := Self;
ControlStyle := ControlStyle - [csDoubleClicks];
DoubleBuffered := True;
FImageCanRegenerate := False;
FLayered := 100;
FIsLayered := False;
FBufferBitmap := TBitmap.Create;
FBufferBitmap.PixelFormat := pf24bit;
FBufferBitmap.SetSize(Width, Height);
for I := 0 to 5 do
begin
FNormalImages[I] := TLayeredBitmap.Create;
FNormalImages[I].IsLayered := True;
FDisabledImages[I] := TLayeredBitmap.Create;
FDisabledImages[I].IsLayered := True;
end;
FIcons[0] := LoadImage(Hinstance, 'TRATING_DEL', IMAGE_ICON, 16, 16, 0);
for I := 1 to 5 do
FIcons[I] := LoadImage(Hinstance, PChar('TRATING_' + IntToStr(I)), IMAGE_ICON, 16, 16, 0);
CreateLBMP;
FIsImageCreated := False;
FIsMouseDown := False;
end;
destructor TRating.Destroy;
var
I: Integer;
begin
F(FBufferBitmap);
F(FCanvas);
for I := 0 to 5 do
begin
FNormalImages[I].Free;
FDisabledImages[I].Free;
DestroyIcon(FIcons[I]);
end;
inherited;
end;
procedure TRating.Paint(var Message: Tmessage);
begin
inherited;
if not FIsImageCreated then
begin
FIsImageCreated := True;
RecreateBuffer;
end;
FCanvas.Draw(0, 0, FBufferBitmap);
end;
procedure TRating.SetRating(const Value: Integer);
begin
if FRating = Value then
Exit;
FRating := Value;
if not CanSelectRange then
FRatingRange := Value;
if Assigned(FOnRating) then
FOnRating(Self, FRating);
if Assigned(FOnChange) then
FOnChange(Self);
RecreateBuffer;
Repaint;
end;
procedure TRating.SetRatingRange(const Value: Integer);
begin
FRatingRange := Value;
if Assigned(FOnRatingRange) then
FOnRatingRange(Self, FRatingRange);
if Assigned(FOnChange) then
FOnChange(Self);
RecreateBuffer;
Repaint;
end;
procedure TRating.SetOnRating(const Value: TOnRatingMessage);
begin
FOnRating := Value;
end;
procedure TRating.SetOnRatingRange(const Value: TOnRatingMessage);
begin
FOnRatingRange := Value;
end;
procedure TRating.WMSize(var Message: Tmessage);
begin
Height := 16;
Width := 6 * 16;
end;
procedure LGrayScale(Image : TLayeredBitmap);
var
I, J, C : Integer;
P : PARGB32;
begin
for I := 0 to Image.Height - 1 do
begin
P := Image.ScanLine[I];
for J := 0 to Image.Width - 1 do
begin
C := (P[J].R * 77 + P[J].G * 151 + P[J].B * 28) shr 8;
P[J].R := C;
P[J].G := C;
P[J].B := C;
end;
end;
end;
procedure TRating.CreateLBMP;
var
I: Integer;
begin
for I := 0 to 5 do
begin
FNormalImages[I].LoadFromHIcon(FIcons[I]);
FDisabledImages[i].Load(FNormalImages[I]);
LGrayScale(FDisabledImages[I]);
end;
end;
procedure TRating.RecreateBuffer;
var
I: Integer;
function RatingBetween(RatingFrom, RatingTo, Rating : Integer) : Boolean;
var
Tmp: Integer;
begin
if RatingFrom > RatingTo then
begin
Tmp := RatingFrom;
RatingFrom := RatingTo;
RatingTo := Tmp;
end;
Result := (RatingFrom <= Rating) and (Rating <= RatingTo);
end;
begin
if (csReading in ComponentState) then
Exit;
if not FImageCanRegenerate and not (csDesigning in ComponentState) then
Exit;
DrawBackground(FBufferBitmap.Canvas);
for I := 0 to 5 do
if not FIsLayered then
begin
if RatingBetween(FRating, FRatingRange, I) then
FNormalImages[I].DoDraw(16 * I, 0, FBufferBitmap)
else
FDisabledImages[I].DoDraw(16 * I, 0, FBufferBitmap);
end else
begin
if RatingBetween(FRating, FRatingRange, I) then
FNormalImages[I].DolayeredDraw(16 * I, 0, FLayered, FBufferBitmap)
else
FDisabledImages[I].DolayeredDraw(16 * I, 0, FLayered, FBufferBitmap);
end;
end;
procedure TRating.SetOnChange(const Value: TNotifyEvent);
begin
FOnChange := Value;
end;
procedure TRating.SetIsLayered(const Value: boolean);
begin
if FIslayered <> Value then
begin
FIslayered := Value;
Refresh;
end;
end;
procedure TRating.SetLayered(const Value: integer);
begin
if FLayered <> Value then
begin
FLayered := Value;
Refresh;
end;
end;
procedure TRating.SetOnMouseDown(const Value: TNotifyEvent);
begin
FOnMouseDown := Value;
end;
procedure TRating.DoDrawImageByrating(HDC : THandle; X, Y, Rating: integer);
begin
DrawIconEx(HDC, X, Y, FIcons[Rating], 16, 16, 0, 0, DI_NORMAL);
end;
procedure TRating.Erased(var Message: TWMEraseBkgnd);
begin
Message.Result := 1;
end;
procedure TRating.SetImageCanRegenerate(const Value: boolean);
begin
FImageCanRegenerate := Value;
if Value then
RecreateBuffer;
end;
procedure TRating.WMMouseMove(var Message: TMessage);
var
NewRating : Integer;
begin
if FIsMouseDown and FCanSelectRange then
begin
NewRating := Message.LParamLo div 8;
if Rating * 2 <> NewRating then
RatingRange := NewRating div 2;
end;
end;
procedure TRating.WMMouseUp(var Message: TMessage);
begin
FIsMouseDown := False;
end;
procedure TRating.CMColorChanged(var Message: TMessage);
begin
RecreateBuffer;
end;
procedure TRating.CMMouseLeave(var Message: TWMNoParams);
begin
FIsMouseDown := False;
end;
end.
|
unit CDBMiddleEngine;
(*******************************************************************************
* CLASE: TDBMiddleEngine. *
* FECHA DE CREACIÓN: 30-07-2001 *
* PROGRAMADOR: Saulo Alvarado Mateos (CINCA) *
* DESCRIPCIÓN: *
* Hace las veces de interfaz entre los objetos con los que trabaja el *
* sistema y el soporte último en el que se almacenan, que en este caso se *
* trata de archivos almacenados individualmente. Por supuesto la idea es *
* que hereda de TCurstomDBMiddleEngine, para que se pueda, en el futuro, cam- *
* biar por cualquier otro soporte o BBDD. Cosa que desde luego no sucederá *
* estando yo por estos lares, claro. *
* *
* FECHA MODIFICACIÓN: 01-10-2001 *
* PROGRAMADOR: Saulo Alvarado Mateos (CINCA) *
* CAMBIOS (DESCRIPCIÓN): *
* A partir de ahora, el mismo "motor" se encarga de buscar y guardar *
* los soportes generados por el programa. *
* *
* FECHA MODIFICACIÓN: 05-10-2001 *
* PROGRAMADOR: Saulo Alvarado Mateos (CINCA) *
* CAMBIOS (DESCRIPCIÓN): *
* Se ha hecho una modificación en el procedimiento de asignar el *
* siguiente número libre para el soporte. A partir de ahora, si se ha borrado *
* uno anteriormente, se le asignará ese número (hueco) libre aunque existan *
* número de soporte posteriores. *
* *
* FECHA MODIFICACIÓN: 08-10-2001 *
* PROGRAMADOR: Saulo Alvarado Mateos (CINCA) *
* CAMBIOS (DESCRIPCIÓN): *
* Cuando se elimina un soporte hay que renumerar todos los que vienen *
* detrás. *
* *
* FECHA MODIFICACIÓN: 22-10-2001 *
* PROGRAMADOR: Saulo Alvarado Mateos (CINCA) *
* CAMBIOS (DESCRIPCION): *
* A partir de ahora, cuando se leen los datos de un registro también *
* se acompaña de la referencia al soporte en el que viajó *
* *
* FECHA MODIFICACIÓN: 04-11-2001 *
* PROGRAMADOR: Saulo Alvarado Mateos (CINCA) *
* CAMBIOS (DESCRIPCIÓN): *
* Se quieren incluir más información en el proxy de cada registro *
* para mostrarlo en la ventana de lectura y borrado. *
* *
* FECHA MODIFICACIÓN: 13-05-2002 *
* PROGRAMADOR: Saulo Alvarado Mateos (CINCA) *
* CAMBIOS (DESCRIPCIÓN): *
* Se añaden un conjunto de procedimientos necesario para poder mover *
* los registros "viejos" a las carpetas oportunas sin entrar en un posible *
* estado de inconsistencia. Hay que hacerlo en dos fases: cada vez que se lee *
* un registro, se debe crear un archivo de "bloqueo" en el directorio. De es- *
* ta forma se cancelará el proceso de intentar entrar en modo "Bloqueo total *
* de registros". Ahora bien, si se encuentra en ese modo, indicado a su vez *
* por un archivo, no se podrán leer registros mientras. *
* Estos cambios implican una serie de modificaciones importantes en *
* el código. *
* *
*******************************************************************************
* CLASE: TRecordProxy *
* FECHA DE CREACIÓN: 30-07-2001 *
* PROGRAMADOR: Saulo Alvarado Mateos (CINCA) *
* DESCRIPCIÓN: *
* Permite mantener información adicional sobre el archivo que contiene *
* objeto para cuando se vuelva a guardar. *
*******************************************************************************)
interface
uses
sysUtils,
UGlobalData,
contnrs, (* TObjectList *)
classes,
CCustomDBMiddleEngine, (* TCustomDBMiddleEngine *)
COpDivSystemRecord,
COpDivRecType02,
COpDivRecType03,
COpDivRecType04,
COpDivRecType05,
COpDivRecType06,
COpDivRecType07,
COpDivRecType08,
COpDivRecType09,
COpDivRecType10,
COpDivRecType12,
COpDivRecType14,
COpDivRecTypeDEV,
CSoporte;
const
kFileGenSopExt = '.033';
type
// *** declaraciones adelantadas
TOpDivRecordProxy = class;
TDBMiddleEngine = class;
// *** declaraciones de las clases
TOpDivRecordProxy = class( TCustomRecordProxy )
public
FileName: String;
OID: String;
StationID: String;
FechaHora: TDateTime;
TipoReg: String;
Descripcion: String;
// $ 4-11-2001 datos incluídos a partir de esta fecha
NatOp: String;
EntOfiDest: String;
ImportePrinOp: Double;
DivisaOp: String;
IncluirSop: String;
VinculasoSop: Boolean;
constructor Create; override;
function isAssignedToSoporte: Boolean;
end;
// 13.05.02 - se añade una clase de excepción para indicar que hay un bloque a nivel de terminal/registro
EDBMiddleTerminalLockedException = class( Exception )
public
constructor Create; overload; virtual;
end;
// 13.05.02 - se añade una clase de excepción para indicar que hay un bloque general de todos los registros
// (para hacer "limpieza").
EDBMiddleGeneralRecorsLockException = class( Exception )
public
constructor Create; overload; virtual;
end;
// 14.05.02 - se añade una excepción para indicar que hay un bloque a nivel de soportes
EDBMiddleSoporteLockedException = class( Exception )
public
constructor Create; overload; virtual;
end;
// 13.05.02 - parámetros del movimiento de archivos
TMoveRecFilesParams = class( TObject )
public
borrarDelFiles,
borrarOldFiles: Boolean;
fechaCorte: TDateTime;
constructor Create; virtual;
end;
//
TDBMiddleEngine = class( TCustomDBMiddleEngine )
protected
FDataDir: String;
FDataSoporteDir: String;
FDataSoporteGenDir: String; // se almacena una copia de los soportes generados por el programa como logs...
FDataAuxDir: String;
FAuxProxy: TOpDivRecordProxy;
FVinculadosFile: TStringList;
function factoryCreateRecordType( aRecProxy: TOpDivRecordProxy ): TOpDivSystemRecord;
// 13.05.02 - método que comprueba si existe un bloqueo de registros previo
function testLockRecords: Boolean;
// 13.05.02 - método que comprueba si hay algún terminal con un registro abierto o en uso
function testLockTerminal: Boolean;
public
// $$ constructores
constructor Create; override;
destructor Destroy; override;
// $$ métodos públicos
function getListOfRecords: TObjectList; override;
procedure clearProxy; virtual;
function readRecord( aRecProxy: TCustomRecordProxy ): TCustomSystemRecord; override;
function readRecordFromOID( anOID: String ): TOpDivSystemRecord; virtual;
procedure writeRecord( aSystemRecord: TCustomSystemRecord ); override;
procedure writeRecordNoProxy( aSystemRecord: TOpDivSystemRecord ); virtual;
procedure deleteRecord( aRecProxy: TCustomRecordProxy ); override;
// 13.05.02 - rutinas para crear, destruir, archivos de bloqueo de los terminales
procedure lockTerminal(const terminalId, recType: String);
procedure unlockTerminal(const terminalId: String);
// 14.05.02 - rutinas para bloqueo completo de los registros
procedure lockGlobalRecords(const terminalId: String); // se indica el terminal para saber quién lo generó
procedure unlockGlobalRecords;
// --- para los soportes
function beginSoporteSection: boolean; virtual;
function endSoporteSection: boolean; virtual;
function getNextNumSoporte: Integer;
procedure setLastNumSoporteUsed( aNumSoporte: Integer );
function getNextRefNumber: Integer;
procedure setLastRefNumberUsed( aRefNumber: Integer );
function getListOfSoportes( aDate: TDateTime ): TObjectList; virtual;
procedure writeSoporte( aSoporte: TSoporte ); virtual;
procedure deleteSoporte( aSoporte: TSoporte ); virtual;
procedure writeSopFile( const fileName: String; textoSoporte: TStrings ); virtual;
function recordIsInSoporte( aRecProxy: TOpDivRecordProxy ): boolean; virtual;
function getSoporteOfRecord(const anOID: String): String;
// 14.05.02 - rutinas auxiliares para mover los soportes
function getBriefListOfSoportes: TObjectList;
procedure moveOldSoporte( const theSoporteFileName: String; aMoveParams: TMoveRecFilesParams );
end;
// **** VARIABLES PÚBLICAS Y GLOBALES
var
TheDBMiddleEngine: TDBMiddleEngine;
implementation
uses
rxStrUtils,
Windows,
Messages,
Dialogs,
IniFiles,
Forms,
CCriptografiaCutre,
CQueryEngine;
(*****
CONSTANTES PRIVADAS PARA EL MÓDULO
*****)
const
kHeadSection = '[CABECERA]';
kDescripcionItem = 'DESCRIPCION';
kBodySection = '[DATOS]';
kRecSection = '[RECORD]';
kRecordItem = 'RECORD';
kCodeControlItem = 'CODECONTROL';
kFileExtension = '.ROD';
kSubdirAuxData = 'tablasAuxiliares';
kSubdirSoportes = 'soportes';
kSopBodySection = '[OIDS]';
kSopExtension = '.SOP';
kFileLookSoporte = 'soporte.lock';
kFileReferences = 'REFERENCES.LST';
kNumRefSoporte = 'SOPORTE';
kNumRefRecord = 'RECORD';
kFileVinculados = 'VINCULADOS.LST';
kSubdirSoportesGen = 'archivos';
// 13.05.02 - constantes para las utilidades de mover archivos
kSubdirObsoletos = 'obsoletos';
kExtBloqRecRead = '.lock' ; // si existe alguno en el directorio se debe evitar
// bloquear para mover registros
kFileLockRecords = 'registros.lock';
(***********************
TOpDivRecordProxy ...
***********************)
constructor TOpDivRecordProxy.Create;
begin
inherited ;
FileName := EmptyStr;
OID := EmptyStr;
StationID := EmptyStr;
FechaHora := 0.0;
TipoReg := EmptyStr;
Descripcion := EmptyStr;
end;
function TOpDivRecordProxy.isAssignedToSoporte: Boolean;
begin
Result := VinculasoSop;
end;
(***************************************
EDBMiddleEngineTerminalLockedException
***************************************)
constructor EDBMiddleTerminalLockedException.Create;
begin
inherited Create('Existe al menos un terminal con un registro bloqueado.')
end;
(************************************
EDBMiddleGeneralRecorsLockException
************************************)
constructor EDBMiddleGeneralRecorsLockException.Create;
begin
inherited Create('Existe un bloqueo general de los registros.' + #13
+ 'De persistir el problema hable con el departamento de informática o con el administardor de la red.' + #13
+ #13
+ 'Archivo de bloqueo: ' + kFileLockRecords );
end;
(*********************************
EDBMiddleSoporteLockedException
*********************************)
constructor EDBMiddleSoporteLockedException.Create;
begin
inherited Create('Existe un bloqueo a nivel de soportes.' + #13
+ 'De persistir el problema hable con el departamento de informática o con el administardor de la red.' + #13
+ #13
+ 'Archivo de bloqueo: ' + kFileLookSoporte );
end;
(********************
TMoveRecFilesParams
********************)
constructor TMoveRecFilesParams.Create;
begin
borrarDelFiles := TRUE;
borrarOldFiles := TRUE;
fechaCorte := date() - 31.0; // se desea que la fecha de corte sea de 30 días atrás
end;
(***********************
TDBMiddleEngine ...
***********************)
(*********
CONSTRUCTORES Y DESTRUCTORES
*********)
constructor TDBMiddleEngine.Create;
begin
FDataDir := getPathDBFiles();
if FDataDir[ length( FDataDir ) ] <> '\' then
FDataDir := FDataDir + '\';
// el directorio de las tablas auxiliares
FDataAuxDir := FDataDir + kSubdirAuxData + '\' ;
// el directorio donde se guardan las referencias de los soportes
FDataSoporteDir := FDataDir + kSubdirSoportes + '\' ;
if not DirectoryExists( FDataSoporteDir ) then
CreateDir( FDataSoporteDir );
// el directorio donde se guardará una copia de los soportes generados en disquete
FDataSoporteGenDir := FDataSoporteDir + kSubdirSoportesGen + '\';
if not DirectoryExists( FDataSoporteGenDir ) then
CreateDir( FDataSoporteGenDir );
// se crea el QueryManager (gestor global)
theQueryEngine := TQueryEngine.Create( FDataAuxDir );
end;
destructor TDBMiddleEngine.Destroy;
begin
theQueryEngine.Free;
inherited;
end;
(*********
MÉTODOS PRIVADOS
*********)
function TDBMiddleEngine.factoryCreateRecordType( aRecProxy: TOpDivRecordProxy ): TOpDivSystemRecord;
begin
Result := nil;
if aRecProxy.TipoReg = '01' then
else if aRecProxy.TipoReg = '02' then
Result := TOpDivRecType02.Create()
else if aRecProxy.TipoReg = '03' then
Result := TOpDivRecType03.Create()
else if aRecProxy.TipoReg = '04' then
Result := TOpDivRecType04.Create()
else if aRecProxy.TipoReg = '05' then
Result := TOpDivRecType05.Create()
else if aRecProxy.TipoReg = '06' then
Result := TOpDivRecType06.Create()
else if aRecProxy.TipoReg = '07' then
Result := TOpDivRecType07.Create()
else if aRecProxy.TipoReg = '08' then
Result := TOpDivRecType08.Create()
else if aRecProxy.TipoReg = '09' then
Result := TOpDivRecType09.Create()
else if aRecProxy.TipoReg = '10' then
Result := TOpDivRecType10.Create()
else if aRecProxy.TipoReg = '11' then
else if aRecProxy.TipoReg = '12' then
Result := TOpDivRecType12.Create()
else if aRecProxy.TipoReg = '13' then
else if aRecProxy.TipoReg = '14' then
Result := TOpDivRecType14.Create()
else if aRecProxy.TipoReg = 'DEV' then
Result := TOpDivRecTypeDEV.Create()
end; // a partir del objeto Proxy crea el adecuado objeto correspondiente al tipo oportuno.
// 13.05.02 - este método es bastante sencillo pues se basa en buscar un archivo cuyo nombre es constante
// devuelve TRUE si hay bloqueo
// FALSE si no lo hay
function TDBMiddleEngine.testLockRecords: Boolean;
begin
Result := FileExists( FDataDir + kFileLockRecords );
end;
// 13.05.02 - hay que buscar los archivos con determinada extensión.
// devuelve TRUE si hay bloqueo
// FALSE si no lo hay
function TDBMiddleEngine.testLockTerminal: Boolean;
var
iFounded: Integer;
sr: TSearchRec;
begin
// buscamos que exista algún registro de bloqueo
iFounded := FindFirst( FDataDir + '*' + kExtBloqRecRead, 0, sr );
Result := (iFounded = 0);
SysUtils.FindClose( sr );
end;
(*********
MÉTODOS PÚBLICOS
*********)
function TDBMiddleEngine.getListOfRecords: TObjectList;
const
klHeadSection = 'CABECERA';
klBodySection = 'DATOS';
var
newRecord: TOpDivRecordProxy;
theIniFile: TIniFile;
theStringList: TStringList;
sr: TSearchRec;
iFounded: integer;
auxStrToDate: String;
auxStr: String;
begin
Result := TObjectList.Create;
// 13.05.02 - si existe un bloque general, no se permite una lectura de los registros
if testLockRecords() then
raise EDBMiddleGeneralRecorsLockException.Create();
theStringList := TStringList.Create;
try
// buscamos el primero de la lista...
iFounded := FindFirst( FDataDir + '*' + kFileExtension, 0, sr );
try
while iFounded = 0 do
begin
// se debe cargar el archivo
theIniFile := TIniFile.Create( FDataDir + sr.Name );
try
newRecord := TOpDivRecordProxy.Create();
// se crea el registro y se añade a la lista de registros encontrados
// siempre que tanto la estación de grabación como el tipo pasen la prueba.
newRecord.FileName := FDataDir + sr.Name;
newRecord.OID := theIniFile.ReadString( klHeadSection, k00_OIDItem, '' );
newRecord.StationID := theIniFile.ReadString( klHeadSection, k00_StationIDItem, '' );
auxStrToDate := theIniFile.ReadString( klHeadSection, k00_DateCreationItem, '09/05/1972' );
newRecord.FechaHora := //SysUtils.strToDateTime( auxStrToDate );
strToDate( Copy(auxStrToDate, 1, 10) ) + strToTime( Copy(auxStrToDate, 12, 8) );
newRecord.TipoReg := theIniFile.ReadString( klHeadSection, k00_RecTypeItem, '' );
newRecord.Descripcion := theIniFile.ReadString( klHeadSection, kDescripcionItem, '' );
// $ 4-11-2001: se deben "cargar" los nuevos datos...
auxStr := theIniFile.ReadString(klHeadSection, k00_OpNatItem, EmptyStr);
if auxStr = '1' then
newRecord.NatOp := 'COBROS'
else if auxStr = '2' then
newRecord.NatOp := 'PAGOS'
else
newRecord.NatOp := '--ERR--';
auxStr := theIniFile.ReadString(klBodySection, k00_EntOficDestinoItem, EmptyStr);
newRecord.EntOfiDest := Copy(auxStr, 1, 4) + '-' + Copy(auxStr, 5, 4);
newRecord.ImportePrinOp := StrToFloat(ReplaceStr(theIniFile.ReadString(klBodySection, k00_ImportePrinOpItem, '0.0'), '.', ','));
auxStr := theIniFile.ReadString(klBodySection, k00_DivisaOperacionItem, '0');
if auxStr = '0' then
newRecord.DivisaOp := 'EUR'
else
newRecord.DivisaOp := 'PTA';
if StrToBool(theIniFile.ReadString(klBodySection, k00_IncluirSoporteItem, '0')) then
newRecord.IncluirSop := 'SI'
else
newRecord.IncluirSop := 'NO';
newRecord.VinculasoSop := (getSoporteOfRecord(newRecord.OID) <> EmptyStr);
if UGlobalData.testStation( newRecord.StationID ) then
begin
if newRecord.TipoReg <> 'DEV' then
begin
if UGlobalData.testDo( 'T' + newRecord.TipoReg ) then
Result.Add( newRecord );
end
else if UGlobalData.testDo( newRecord.TipoReg ) then
Result.Add(newRecord);
end;
// newRecord := nil;
finally
theIniFile.Free;
end;
// buscamos el siguiente registro
iFounded := FindNext( sr );
end;
finally
SysUtils.FindClose( sr );
end;
finally
// newRecord := nil;
theStringList.Free;
end
end;
// -- este procedimiento se añade para evitar problemas cuando se leen registros que luego no se van a emplear (sus proxies, que probablemente habrán
// -- sido eliminados de la memoria por la rutina llamadora. Esta rutina llamadora, debe evitar conflictos invocándo este método para que limpie el
// -- estado interno del "engine".
procedure TDBMiddleEngine.clearProxy;
begin
FAuxProxy := nil;
end;
function TDBMiddleEngine.readRecord( aRecProxy: TCustomRecordProxy ): TCustomSystemRecord;
var
theFile: TStringList;
begin
if not assigned( aRecProxy ) then
raise Exception.Create( 'Se tiene que indicar un registro existente.' );
if not FileExists( TopDivRecordProxy( aRecProxy ).FileName ) then
raise Exception.Create( 'El registro señalado no existe.' );
theFile := TStringList.Create();
try
FAuxProxy := TOpDivRecordProxy( aRecProxy );
theFile.LoadFromFile( FAuxProxy.FileName );
Result := factoryCreateRecordType( FAuxProxy );
Result.setData( theFile );
TOpDivSystemRecord(Result).Soporte := getSoporteOfRecord(Result.OID);
finally
theFile.Free;
end
end;
function TDBMiddleEngine.readRecordFromOID( anOID: String ): TOpDivSystemRecord;
const
klHeadSection = 'CABECERA';
var
theFile: TStringList;
theIniFile: TIniFile;
nameFile: String;
auxProxy: TOpDivRecordProxy;
begin
nameFile := FDataDir + anOID + kFileExtension;
if not FileExists( nameFile ) then
raise Exception.Create( 'El registro (OID=' + anOID + ') no existe.' );
theFile := TStringList.Create();
theIniFile := TIniFile.Create( nameFile );
auxProxy := TOpDivRecordProxy.Create();
try
// creamos el proxy-record para poder hacer uso de la factoría
auxProxy.FileName := nameFile;
auxProxy.OID := theIniFile.ReadString( klHeadSection, k00_OIDItem, '' );
auxProxy.StationID := theIniFile.ReadString( klHeadSection, k00_StationIDItem, '' );
auxProxy.FechaHora := strToDateTime( theIniFile.ReadString( klHeadSection, k00_DateCreationItem, '' ) );
auxProxy.TipoReg := theIniFile.ReadString( klHeadSection, k00_RecTypeItem, '' );
auxProxy.Descripcion := theIniFile.ReadString( klHeadSection, kDescripcionItem, '' );
// leemos el fichero
theFile.LoadFromFile( nameFile );
Result := factoryCreateRecordType( auxProxy );
Result.setData(theFile);
Result.Soporte := getSoporteOfRecord(Result.OID);
finally
theFile.Free();
theIniFile.Free();
auxProxy.Free();
end;
end;
procedure TDBMiddleEngine.writeRecord( aSystemRecord: TCustomSystemRecord );
var
descripcion: String;
fileRecord: TStringList;
anStringList: TStringList; // para interrogar al registro
begin
descripcion := EmptyStr;
fileRecord := TStringList.Create();
anStringList := TStringList.Create();
try
if assigned( FAuxProxy ) then
if FAuxProxy.OID = TOpDivSystemRecord( aSystemRecord ).OID then
begin
// -- se renombra el archivo destino
if FileExists( FAuxProxy.FileName + '.OLD' ) then
SysUtils.DeleteFile( FAuxProxy.FileName + '.OLD' );
RenameFile( FAuxProxy.FileName, FAuxProxy.FileName + '.OLD' );
descripcion := FAuxProxy.Descripcion ;
end
else
begin
// debemos desasignar el valor de FAuxProxu
FAuxProxy.Free();
FAuxProxy := nil;
end;
(*
if not assigned( FAuxProxy ) then
descripcion := UpperCase( InputBox( 'Guardar registro...', 'Descripcion', EmptyStr ) );
*)
descripcion := UpperCase( InputBox( 'Guardar registro...', 'Descripcion', descripcion ) );
fileRecord.Clear();
// se crea la cabecera del archivo
fileRecord.Add( kHeadSection );
TOpDivSystemRecord( aSystemRecord ).getHead( anStringList );
fileRecord.AddStrings( anStringList );
fileRecord.Add( kDescripcionItem + '=' + descripcion );
fileRecord.Add( kCodeControlItem + '=' + TOpDivSystemRecord( aSystemRecord ).getHeadCode() );
// ahora se recogen los datos del cuerpo
fileRecord.Add( EmptyStr );
fileRecord.Add( kBodySection );
TOpDivSystemRecord( aSystemRecord ).getData( anStringList );
fileRecord.AddStrings( anStringList );
fileRecord.Add( kCodeControlItem + '=' + TOpDivSystemRecord( aSystemRecord ).getDataCode() );
fileRecord.Add( EmptyStr );
// aprovechamos y se genera el registro...
fileRecord.Add( kRecSection );
fileRecord.Add( kRecordItem + '=' + TOpDivSystemRecord( aSystemRecord ).getDataAsFileRecord() );
fileRecord.Add( kCodeControlItem + '=' + theCutreCriptoEngine.getCodeA( TOpDivSystemRecord( aSystemRecord ).getDataAsFileRecord() ) );
// ahora se almacena el archivo
fileRecord.SaveToFile( FDataDir + TOpDivSystemRecord( aSystemRecord ).OID + kFileExtension );
finally
fileRecord.Free();
anStringList.Free();
if assigned( FAuxProxy ) then
begin
// FAuxProxy.Free();
// se encarga de borrarlo OpenRecord al destruirse...
FAuxProxy := nil;
end;
end;
end;
procedure TDBMiddleEngine.writeRecordNoProxy( aSystemRecord: TOpDivSystemRecord );
var
descripcion: String;
auxStringList: TStringList;
fileRecord: TStringList;
aStringList: TStringList;
nameFile: String;
begin
descripcion := EmptyStr;
auxStringList := TStringList.Create();
fileRecord := TStringList.Create();
aStringList := TStringList.Create();
nameFile := FDataDir + aSystemRecord.OID + kFileExtension;
try
// hay que tener en cuenta que la hora de guardar el registro debemos recuperar la descripción de la anterior versión para no perderla...
if FileExists( nameFile ) then
begin
auxStringList.LoadFromFile(nameFile);
descripcion := auxStringList.Values[kDescripcionItem];
auxStringList.Clear();
// de paso renombramos el archivo para no perder las versiones...
if FileExists(nameFile + '.OLD') then
SysUtils.DeleteFile(nameFile + '.OLD');
RenameFile(nameFile, nameFile + '.OLD');
end;
// procedemos a generar el archivo final
fileRecord.Clear();
// se crea la cabecera del archivo
fileRecord.Add( kHeadSection );
aSystemRecord.getHead( aStringList );
fileRecord.AddStrings( aStringList );
fileRecord.Add( kDescripcionItem + '=' + descripcion );
fileRecord.Add( kCodeControlItem + '=' + aSystemRecord.getHeadCode() );
// ahora se recogen los datos del cuerpo
fileRecord.Add( EmptyStr );
fileRecord.Add( kBodySection );
aSystemRecord.getData( aStringList );
fileRecord.AddStrings( aStringList );
fileRecord.Add( kCodeControlItem + '=' + aSystemRecord.getDataCode() );
fileRecord.Add( EmptyStr );
// aprovechamos y se genera el registro...
fileRecord.Add( kRecSection );
fileRecord.Add( kRecordItem + '=' + aSystemRecord.getDataAsFileRecord() );
fileRecord.Add( kCodeControlItem + '=' + theCutreCriptoEngine.getCodeA( aSystemRecord.getDataAsFileRecord() ) );
// ahora se almacena el archivo
fileRecord.SaveToFile( nameFile );
finally
auxStringList.Free();
fileRecord.Free();
aStringList.Free();
end;
end;
procedure TDBMiddleEngine.deleteRecord( aRecProxy: TCustomRecordProxy );
var
proxy: TOpDivRecordProxy ;
begin
proxy := TOpDivRecordProxy( aRecProxy );
if FileExists( proxy.FileName ) then
RenameFile( proxy.FileName, proxy.FileName + '.DEL' );
// aprovechamos para limpiar algunos restos indeseables de
if assigned( FAuxProxy ) then
FAuxProxy := nil;
end;
// 13.05.02 -- para bloquear/desbloquear terminales
procedure TDBMiddleEngine.lockTerminal(const terminalId, recType: String);
var
theLockFileName: String;
begin
theLockFileName := FDataDir + terminalId + '$' + recType + kExtBloqRecRead;
if not FileExists( theLockFileName ) then
FileClose( FileCreate( theLockFileName ) );
end;
procedure TDBMiddleEngine.unlockTerminal(const terminalId: String);
var
iFounded: Integer;
rs: TSearchRec;
begin
iFounded := FindFirst( FDataDir + terminalId + '*' + kExtBloqRecRead, 0, rs);
try
while iFounded = 0 do
begin
// borramos todos los registros que tengan la extensión de bloqueo y que sean del terminal
// Esto se hace así para evitar restos debidos a una salida brusca del programa. Sin dar
// tiempo a una limpieza anterior
SysUtils.DeleteFile( FDataDir + rs.Name );
iFounded := FindNext( rs );
end;
finally
SysUtils.FindClose( rs );
end;
end;
procedure TDBMiddleEngine.lockGlobalRecords(const terminalId: String);
var
idFile: Integer;
numCharsWrite: Cardinal;
textoToWrite: String;
begin
if FileExists( FDataSoporteDir + kFileLookSoporte ) then
raise EDBMiddleSoporteLockedException.Create();
if not FileExists( FDataDir + kFileLockRecords ) then
begin
idFile := FileCreate( FDataDir + kFileLockRecords );
numCharsWrite := Length( terminalId );
textoToWrite := terminalId;
FileWrite(idFile, terminalId, numCharsWrite);
SysUtils.FileClose( idFile );
// además abrimos el archivo de soportes vinculados para poder trabajar más rápido con él
FVinculadosFile := TStringList.Create();
if FileExists(FDataSoporteDir + kFileVinculados) then
FVinculadosFile.LoadFromFile(FDataSoporteDir + kFileVinculados);
end
else
raise EDBMiddleGeneralRecorsLockException.Create('Ya existe un bloque general.')
end;
procedure TDBMiddleEngine.unlockGlobalRecords;
begin
if FileExists( FDataDir + kFileLockRecords ) then
begin
FVinculadosFile.SaveToFile(FDataSoporteDir + kFileVinculados);
SysUtils.DeleteFile( FDataDir + kFileLockRecords );
end;
end;
// ~~~~~~~ para los Soportes ~~~~~~~~~~
function TDBMiddleEngine.beginSoporteSection: boolean;
begin
Result := false;
// 13.05.02 - sólo podremos entrar en la utilidad de soportes cuando no
// exista un bloqueo general de los registros (moviendo registros
// antiguos).
if testLockRecords() then
raise EDBMiddleGeneralRecorsLockException.Create();
if not FileExists( FDataSoporteDir + kFileLookSoporte ) then
begin
FileClose( FileCreate( FDataSoporteDir + kFileLookSoporte ) );
// de paso creamos y cargamos en memoria el archivo de vínculos
FVinculadosFile := TStringList.Create();
if FileExists(FDataSoporteDir + kFileVinculados) then
FVinculadosFile.LoadFromFile(FDataSoporteDir + kFileVinculados);
Result := true;
end;
end;
function TDBMiddleEngine.endSoporteSection: boolean;
begin
Result := false;
if FileExists( FDataSoporteDir + kFileLookSoporte ) then
begin
FVinculadosFile.SaveToFile(FDataSoporteDir + kFileVinculados);
SysUtils.DeleteFile( FDataSoporteDir + kFileLookSoporte );
Result := true;
end;
end;
function TDBMiddleEngine.getNextNumSoporte: Integer;
var
(*
listReferencias: TStringList;
nameItem: String;
*)
listSoportes: TObjectList;
huecos: array [1..100] of boolean;
iCont: Integer;
begin
listSoportes := getListOfSoportes( date() );
for iCont := 1 to 100 do huecos[iCont] := true;
try
// marcamos los huecos libres
for iCont := 0 to listSoportes.Count-1 do
huecos[TSoporte(listSoportes.Items[iCont]).NumOrden] := false;
// buscamos el primero que esté realmente libre
Result := 1;
while not huecos[Result] and (Result <= 100) do inc(Result);
if Result > 100 then
raise Exception.Create('Demasiados soportes');
finally
listSoportes.Free();
end;
(* Result := 1;
listReferencias := TStringList.Create();
try
if FileExists( FDataSoporteDir + kFileReferences ) then
begin
listReferencias.LoadFromFile( FDataSoporteDir + kFileReferences );
nameItem := kNumRefSoporte + formatDateTime('yyyymmdd',date());
if listReferencias.IndexOfName( nameItem ) >= 0 then
Result := strToInt( listReferencias.Values[nameItem] ) + 1;
end
finally
listReferencias.Free();
end;
*)
end;
procedure TDBMiddleEngine.setLastNumSoporteUsed( aNumSoporte: Integer );
var
listReferencias: TStringList;
nameFile: String;
nameItem: String;
begin
nameFile := FDataSoporteDir + kFileReferences;
nameItem := kNumRefSoporte + formatDateTime('yyyymmdd',date());
listReferencias := TStringList.Create();
try
if FileExists( nameFile ) then
listReferencias.LoadFromFile(nameFile);
listReferencias.Values[nameItem] := intToStr(aNumSoporte);
// volvemos a guardar el archivo de referencias
listReferencias.SaveToFile(nameFile);
finally
listReferencias.Free();
end
end;
function TDBMiddleEngine.getNextRefNumber: Integer;
var
listReferencias: TStringList;
nameFile: String;
nameItem: String;
begin
Result := 1;
nameFile := FDataSoporteDir + kFileReferences;
nameItem := kNumRefRecord + formatDateTime('yyyymmdd',date());
listReferencias := TStringList.Create();
try
if FileExists(nameFile) then
begin
listReferencias.LoadFromFile(nameFile);
if listReferencias.IndexOfName(nameItem) >= 0 then
Result := strToInt(listReferencias.Values[nameItem])+1;
end
finally
listReferencias.Free();
end
end;
procedure TDBMiddleEngine.setLastRefNumberUsed( aRefNumber: Integer );
var
nameFile: String;
nameItem: String;
listReferencias: TStringList;
begin
nameFile := FDataSoporteDir + kFileReferences;
nameItem := kNumRefRecord + formatDateTime('yyyymmdd',date());
listReferencias := TStringList.Create();
try
if FileExists(nameFile) then
listReferencias.LoadFromFile(nameFile);
listReferencias.Values[nameItem] := intToStr(aRefNumber);
// procedemos a guardar nuevamente el archivo de referencias
listReferencias.SaveToFile(nameFile);
finally
end;
end;
function TDBMiddleEngine.getListOfSoportes( aDate: TDateTime ): TObjectList;
var
newRecord: TSoporte;
newOpDiv: TOpDivSystemRecord;
theStringList: TStringList;
sr: TSearchRec;
iFounded: integer;
prefFechaFile: String;
iString: integer;
begin
Result := TObjectList.Create();
prefFechaFile := formatDateTime( 'yyyymmdd', aDate );
// buscamos el primero de la lista...
iFounded := FindFirst( FDataSoporteDir + prefFechaFile + '*' + kSopExtension, 0, sr );
try
while iFounded = 0 do
begin
// se debe cargar el archivo
theStringList := TStringList.Create();
theStringList.LoadFromFile( FDataSoporteDir + sr.Name );
try
newRecord := TSoporte.Create();
newRecord.OwnsRecordsPointers := true; // el es el encargado de eliminar sus registros relacionados
newRecord.Tipo := TSoporte.strToTipo( theStringList.Values[ kSopTipoItem ] );
newRecord.FechaSoporte := strToDateTime( theStringList.Values[ kSopFechaItem ] );
newRecord.NumOrden := strToInt( theStringList.Values[ kSopNumItem ] );
newRecord.StationID := theStringList.Values[kSopEstacionItem];
// ahora buscamos todos los registros que componen el soporte y los vamos incorporando...
while theStringList.Strings[0] <> kSopBodySection do theStringList.Delete(0);
for iString := 1 to theStringList.Count - 1 do
begin
newOpDiv := readRecordFromOID( theStringList.Strings[iString] );
newRecord.AddRegistro( newOpDiv );
end;
Result.Add( newRecord );
finally
theStringList.Free;
end;
// buscamos el siguiente registro
iFounded := FindNext( sr );
end;
finally
SysUtils.FindClose( sr );
end;
end;
procedure TDBMiddleEngine.writeSoporte( aSoporte: TSoporte );
var
fileRecord: TStringList;
registrosVinculados: TObjectList;
iRecord: Integer;
nameFile: String;
begin
nameFile := formatDateTime('yyyymmdd', aSoporte.FechaSoporte) + AddChar('0', intToStr(aSoporte.NumOrden), 3);
nameFIle := FDataSoporteDir + nameFile + kSopExtension;
fileRecord := TStringList.Create();
registrosVinculados := TObjectList.Create();
registrosVinculados.OwnsObjects := false;
try
// si existe el fichero se renombra para conservar una versión del mismo
if FileExists(nameFile) then
begin
if FileExists(nameFile + '.OLD') then
SysUtils.DeleteFile(nameFile + '.OLD');
RenameFile(nameFile, nameFile + '.OLD');
end;
// se comienza construyendo el registro en memoria con la cabecera
fileRecord.Clear();
fileRecord.Add(kHeadSection);
fileRecord.Add(kSopTipoItem + '=' + aSoporte.tipoToStr(aSoporte.Tipo));
fileRecord.Add(kSopFechaItem + '=' + dateTimeToStr(aSoporte.FechaSoporte));
fileRecord.Add(kSopNumItem + '=' + intToStr(aSoporte.NumOrden));
fileRecord.Add(kSopEstacionItem + '=' + getStationID() );
fileRecord.Add(EmptyStr);
// luego se introducen los OID's de los registros asociados
// -- se empieza solicitándolos al soporte con el número de referencia asociado
aSoporte.getRegistros(registrosVinculados);
fileRecord.Add(kSopBodySection);
for iRecord := 0 to registrosVinculados.Count - 1 do
begin
fileRecord.Add(TOpDivSystemRecord(registrosVinculados.Items[iRecord]).OID);
FVinculadosFile.Values[TOpDivSystemRecord(registrosVinculados.Items[iRecord]).OID] := aSoporte.getDesc();
end;
// se termina guardando el archivo
fileRecord.SaveToFile(nameFile);
finally
fileRecord.Free();
registrosVinculados.Free();
end;
end;
procedure TDBMiddleEngine.deleteSoporte( aSoporte: TSoporte );
var
fileRecords: TStringList;
nameFile: String;
iRecord: Integer;
maxNumero,
numeroSoporte: Integer;
listaSoportes: TObjectList;
otroSoporte: TSoporte;
begin
// se debe renombara el archivo del soporte para hacerlo "desaparecer", pero también hay que quitar las referencias
// del archivo de vínculos...
nameFile := FDataSoporteDir + formatDateTime( 'yyyymmdd', aSoporte.FechaSoporte ) + AddChar('0',intToStr(aSoporte.NumOrden),3) + kSopExtension;
if fileExists(nameFile) then
begin
// lo leemos
fileRecords := TStringList.Create();
try
fileRecords.LoadFromFile(nameFile);
// lo "borramos"
if FileExists(nameFile + '.DEL') then
SysUtils.DeleteFile(nameFile + '.DEL');
RenameFile(nameFile, nameFile + '.DEL');
// procedemos a limpiar los vínculos
while fileRecords.Strings[0] <> kSopBodySection do fileRecords.Delete(0);
for iRecord := 1 to fileRecords.Count - 1 do
FVinculadosFile.Values[fileRecords.Strings[iRecord]] := EmptyStr;
// (+)08-10-2001: Hay que renumerar los soportes que vienen detrás
// ^^^ CUIDADO PORQUE PUEDEN PRODUCIRSE INCONSISTENCIAS EN LAS REFERENCIAS CRUZADAS
// ENTRE SOPORTES Y REGISTROS....!!!!!!!!!!!!
maxNumero := 0;
listaSoportes := getListOfSoportes(aSoporte.FechaSoporte);
try
for numeroSoporte := 0 to listaSoportes.Count - 1 do
begin
otroSoporte := TSoporte(listaSoportes.Items[numeroSoporte]);
if otroSoporte.NumOrden > aSoporte.NumOrden then
begin
if maxNumero < otroSoporte.NumOrden then
maxNumero := otroSoporte.NumOrden;
otroSoporte.NumOrden := otroSoporte.NumOrden - 1;
writeSoporte(otroSoporte);
end;
end;
// debemos renombrar también el último de la lista, ya que el hueco se ha ido desplazando hacia arriba...
if maxNumero > 0 then
begin
nameFile := FDataSoporteDir + FormatDateTime('yyyymmdd', aSoporte.FechaSoporte) + AddChar('0', IntToStr(maxNumero), 3) + kSopExtension;
if not FileExists(nameFile) then
raise Exception.Create('POSTCONDICIÓN: Debería existir el último soporte');
if FileExists(nameFile + '.DEL') then
SysUtils.DeleteFile(nameFile + '.DEL');
RenameFile(nameFile, nameFile + '.DEL');
end
finally
listaSoportes.Free();
end;
finally
fileRecords.Free();
end;
end
end;
function TDBMiddleEngine.recordIsInSoporte( aRecProxy: TOpDivRecordProxy ): boolean;
begin
Result := (FVinculadosFile.IndexOfName(aRecProxy.OID) >= 0);
end;
function TDBMiddleEngine.getSoporteOfRecord(const anOID: String): String;
var
archivoVinculados: TStringList;
begin
Result := EmptyStr;
archivoVinculados := TStringList.Create();
try
archivoVinculados.LoadFromFile(FDataSoporteDir + kFileVinculados);
if archivoVinculados.IndexOfName(anOID) >= 0 then
begin
Result := archivoVinculados.Values[anOID];
Result := copy(Result, 1, 8) + '.' + copy(Result, 9, 3);
end
finally
archivoVinculados.Free();
end;
end;
procedure TDBMiddleEngine.writeSopFile( const fileName: String; textoSoporte: TStrings );
var
prefix: String;
endNameFile: String;
begin
prefix := formatDateTime( 'yyyymmddhhnnsszzz', now() );
endNameFile := FDataSoporteGenDir + prefix + '.' + fileName;
if FileExists(endNameFile) then
raise Exception.Create('No se puede tener dos nombre de archivo iguales.');
textoSoporte.SaveToFile(endNameFile);
end;
// 14.05.02 - se incluyen rutinas para permitir mover los archivos obsoletos
// el parámetro de entrada, que contiene los parámetros, a su vez, de las opciones elegidas para
// mover los archivos, se emplea para evitar devolver aquellos soportes que sean superiores a la fecha
// indicada.
function TDBMiddleEngine.getBriefListOfSoportes(aMoveParams: TMoveRecFilesParams): TObjectList;
begin
end;
// cuando se mueve el soporte se mueven todos los registros asociados, de tal forma que,
// a partir de los parámetros del "movimiento", se decide si se borran o se mueven también
// los archivos DEL y OLD.
// Pero para ello se debe asegurar que se está en modo "bloqueo general".
procedure TDBMiddleEngine.moveOldSoporte(const theSoporteFileName: String; aMoveParams: TMoveRecFilesParams );
begin
end;
initialization
theDBMiddleEngine := TDBMiddleEngine.Create;
finalization
theDBMiddleEngine.Free;
end.
|
unit Chapter02._03_Main;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
DeepStar.UString,
DeepStar.Utils;
procedure Main;
implementation
// O(1)
procedure SwapTwoInts(var a, b: integer);
var
temp: integer;
begin
temp := a;
a := b;
b := temp;
end;
// O(n)
function Sum(n: integer): integer;
var
res, i: integer;
begin
Assert(n >= 0);
res := 0;
for i := 0 to n do
res += i;
Result := res;
end;
// O(n)
procedure Reverse(var s: UString);
procedure __swap__(var a, b: UChar);
var
temp: UChar;
begin
temp := a;
a := b;
b := temp;
end;
var
n, i: integer;
begin
n := Length(s);
for i := 0 to n div 2 do
begin
__swap__(s[i + 1], s[n - i]);
end;
end;
// O(n^2) Time Complexity
procedure SelectionSort(arr: TArr_int);
var
i, minIndex, j: integer;
begin
for i := 0 to High(arr) do
begin
minIndex := i;
for j := i + 1 to High(arr) do
begin
if arr[j] < arr[minIndex] then
minIndex := j;
end;
SwapTwoInts(arr[i], arr[minIndex]);
end;
end;
// O(n) Time Complexity
procedure PrintInformation(n: integer);
var
i, j: integer;
begin
for i := 1 to n do
for j := 1 to 30 do
WriteLn('Class ', i, ' - ', 'No. ', j);
end;
// O(logn) Time Complexity
function BinarySearch(arr: TArr_int; target: integer): integer;
var
l, r, mid: integer;
begin
l := 0;
r := High(arr);
while l <= r do
begin
mid := l + (r - l) div 2;
if arr[mid] = target then
Exit(mid);
if arr[mid] > target then
r := mid - 1
else
l := mid + 1;
end;
Result := -1;
end;
// O(logn) Time Complexity
function IntToUString(num: integer): UString;
var
s, sign: UString;
temp: UChar;
res: UString;
begin
s := '';
sign := '+';
if num < 0 then
begin
num := -num;
sign := '-';
end;
while num <> 0 do
begin
temp := Chr(Ord('0') + num mod 10);
num := num div 10;
s += temp;
end;
if s = '' then
Exit('0');
Reverse(s);
if sign = '+' then
res := s
else
res := sign + s;
Result := res;
end;
// O(nlogn)
procedure Hello(n: integer);
var
sz, i: integer;
begin
sz := 1;
while sz < n do
begin
for i := 1 to n - 1 do
WriteLn('Hello, Algorithm!');
sz += sz;
end;
end;
// O(sqrt(n)) Time Complexity
function IsPrime(num: integer): boolean;
var
x: integer;
begin
x := 2;
while Sqr(x) <= num do
begin
if num mod x = 0 then
Exit(false);
x += 1;
end;
Result := true;
end;
function IsPrime2(num: integer): boolean;
var
x: integer;
begin
if num <= 1 then Exit(false);
if num = 2 then Exit(true);
if num mod 2 = 0 then Exit(false);
x := 3;
while Sqr(x) <= num do
begin
if num mod x = 0 then
Exit(false);
x += 2;
end;
Result := true;
end;
procedure Main;
var
s, i, l, r: integer;
b, e: double;
begin
l := 1000000;
r := 5000000;
s := 0;
b := Now;
for i := l to r do
begin
if IsPrime(i) then
s += 1;
end;
e := Now;
WriteLn('Count: ', s, ' time: ', e - b);
s := 0;
b := Now;
for i := l to r do
begin
if IsPrime2(i) then
s += 1;
end;
e := Now;
WriteLn('Count: ', s, ' time: ', e - b);
end;
end.
|
{-----------------------------------------------------------------------------
Unit Name: cFileSearch
Author: Kiriakos Vlahos
Date: 29-May-2005
Purpose:
History: Based on GExperts (www.gexperts.org) unit and covered by its licence
GExperts License Agreement
GExperts is copyright 1996-2005 by GExperts, Inc, Erik Berry, and several other
authors who have submitted their code for inclusion. This license agreement only covers code written by GExperts, Inc and Erik Berry. You should contact the other authors concerning their respective copyrights and conditions.
The rules governing the use of GExperts and the GExperts source code are derived
from the official Open Source Definition, available at http://www.opensource.org.
The conditions and limitations are as follows:
* Usage of GExperts binary distributions is permitted for all developers.
You may not use the GExperts source code to develop proprietary or
commercial products including plugins or libraries for those products.
You may use the GExperts source code in an Open Source project, under the
terms listed below.
* You may not use the GExperts source code to create and distribute custom
versions of GExperts under the "GExperts" name. If you do modify and
distribute custom versions of GExperts, the binary distribution must be
named differently and clearly marked so users can tell they are not using
the official GExperts distribution. A visible and unmodified version of
this license must appear in any modified distribution of GExperts.
* Custom distributions of GExperts must include all of the custom changes
as a patch file that can be applied to the original source code. This
restriction is in place to protect the integrity of the original author's
source code. No support for modified versions of GExperts will be provided
by the original authors or on the GExperts mailing lists.
* All works derived from GExperts must be distributed under a license
compatible with this license and the official Open Source Definition,
which can be obtained from http://www.opensource.org/.
* Please note that GExperts, Inc. and the other contributing authors hereby
state that this package is provided "as is" and without any express or
implied warranties, including, but not without limitation, the implied
warranties of merchantability and fitness for a particular purpose. In
other words, we accept no liability for any damage that may result from
using GExperts or programs that use the GExperts source code.
-----------------------------------------------------------------------------}
unit cFileSearch;
interface
uses
SysUtils, Classes, SynRegExpr;
type
TSearchOption = (soCaseSensitive, soWholeWord, soRegEx);
TSearchOptions = set of TSearchOption;
TFoundEvent = procedure(Sender: TObject; LineNo: Integer; const Line: string; SPos, EPos: Integer) of object;
ELineTooLong = class(Exception);
// We separate the grep code from the file management code in TSearcher
TBaseSearcher = class(TObject)
private
procedure SetBufSize(New: Integer);
protected
FOnFound: TFoundEvent;
FOnStartSearch: TNotifyEvent;
procedure SignalStartSearch; virtual;
procedure SignalFoundMatch(LineNo: Integer; const Line: string; SPos, EPos: Integer); virtual;
protected
BLine: PChar; // The current search line,
FLineNo: Integer;
FEof: Boolean;
FSearchBuffer: PChar;
FBufSize: Integer;
FBufferSearchPos: Integer;
FBufferDataCount: Integer;
FNoComments: Boolean;
FSearchOptions: TSearchOptions;
FCommentActive: Boolean;
FPattern: string;
FFileName: string;
FRegExpr : TRegExpr;
procedure DoSearch;
procedure FillBuffer;
procedure PatternMatch;
procedure ReadIntoBuffer(AmountOfBytesToRead: Cardinal); virtual; abstract;
procedure Seek(Offset: Longint; Direction: Integer); virtual; abstract;
public
constructor Create;
destructor Destroy; override;
procedure SetPattern(const Value: string);
property BufSize: Integer read FBufSize write SetBufSize;
property NoComments: Boolean read FNoComments write FNoComments;
property Pattern: string read FPattern write SetPattern;
property SearchOptions: TSearchOptions read FSearchOptions write FSearchOptions;
property OnFound: TFoundEvent read FOnFound write FOnFound;
property OnStartSearch: TNotifyEvent read FOnStartSearch write FOnStartSearch;
end;
TSearcher = class(TBaseSearcher)
private
FSearchStream: TStream;
procedure Reset;
protected
procedure SetFileName(const Value: string);
procedure FreeObjects;
protected
procedure ReadIntoBuffer(AmountOfBytesToRead: Cardinal); override;
procedure Seek(Offset: Longint; Direction: Integer); override;
public
constructor Create(const SearchFileName: string);
destructor Destroy; override;
procedure Execute;
published
property FileName: string read FFileName write SetFileName;
end;
implementation
uses
Windows, uEditAppIntfs, JclStrings, Dialogs;
const
SearchLineSize = 1024;
DefaultBufferSize = 2048;
{ TSearcher }
constructor TSearcher.Create(const SearchFileName: string);
begin
inherited Create;
if SearchFileName <> '' then
SetFileName(SearchFileName);
end;
destructor TSearcher.Destroy;
begin
FreeAndNil(FSearchStream);
inherited Destroy;
end;
procedure TSearcher.FreeObjects;
begin
if FFileName <> '' then
begin
FreeAndNil(FSearchStream);
end;
end;
procedure TSearcher.SetFileName(const Value: string);
function GetFileInterface: Boolean;
begin
Result := False;
if not FileExists(FFileName) then
Exit;
try
FSearchStream := TFileStream.Create(FFileName, fmOpenRead or fmShareDenyWrite);
Result := True;
except
// We cannot open the file for some reason
Result := False;
end;
end;
function GetModuleInterface: Boolean;
var
Editor : IEditor;
begin
Result := False;
Editor := GI_EditorFactory.GetEditorByNameOrTitle(FFileName);
if Assigned(Editor) then begin
FSearchStream := TStringStream.Create(Editor.SynEdit.Text);
Result := True;
end;
end;
begin
FreeObjects;
FFileName := Value;
if not GetModuleInterface and not GetFileInterface then
FFileName := '';
if FFileName <> '' then
Reset;
end;
procedure TSearcher.Reset;
resourcestring
SSearcherReset = 'Reset exception:' + sLineBreak;
begin
if FFileName = '' then
Exit;
FBufferSearchPos := 0;
FBufferDataCount := 0;
FLineNo := 0;
FEof := False;
FSearchStream.Position := 0;
FCommentActive := False;
end;
procedure TSearcher.Execute;
begin
Reset;
DoSearch;
end;
procedure TSearcher.ReadIntoBuffer(AmountOfBytesToRead: Cardinal);
begin
FBufferDataCount := FSearchStream.Read(FSearchBuffer^, AmountOfBytesToRead)
end;
procedure TSearcher.Seek(Offset, Direction: Integer);
begin
FSearchStream.Seek(Offset, Direction);
end;
{ TBaseSearcher }
constructor TBaseSearcher.Create;
begin
inherited Create;
FBufSize := DefaultBufferSize;
BLine := StrAlloc(SearchLineSize);
FRegExpr := nil;
end;
destructor TBaseSearcher.Destroy;
begin
StrDispose(FSearchBuffer);
FSearchBuffer := nil;
StrDispose(BLine);
BLine := nil;
FreeAndNil(FRegExpr);
inherited Destroy;
end;
procedure TBaseSearcher.FillBuffer;
resourcestring
SLineLengthError = 'File Search detected a line longer than %d characters in:'+sLineBreak+
'%s.' +sLineBreak+
'Likely, this is an unsupported binary file type.';
var
AmountOfBytesToRead: Integer;
SkippedCharactersCount: Integer;
LineEndScanner: PChar;
begin
if FSearchBuffer = nil then
FSearchBuffer := StrAlloc(FBufSize);
FSearchBuffer[0] := #0;
// Read at most (FBufSize - 1) bytes
AmountOfBytesToRead := FBufSize - 1;
ReadIntoBuffer(AmountOfBytesToRead);
FEof := (FBufferDataCount = 0);
// Reset buffer position to zero
FBufferSearchPos := 0;
// If we filled our buffer completely, there is a chance that
// the last line was read only partially.
// Since our search algorithm is line-based,
// skip back to the end of the last completely read line.
if FBufferDataCount = AmountOfBytesToRead then
begin
// Get pointer on last character of read data
LineEndScanner := FSearchBuffer + FBufferDataCount - 1;
// We have not skipped any characters yet
SkippedCharactersCount := 0;
// While we still have data in the buffer,
// do scan for a line break as characterised
// by a #13#10 or #10#13 or a single #10.
// Which sequence exactly we hit is not important,
// we just need to find and line terminating
// sequence.
while FBufferDataCount > 0 do
begin
if LineEndScanner^ = #10 then
begin
Seek(-SkippedCharactersCount, soFromCurrent);
// Finished with finding last complete line
Break;
end;
Inc(SkippedCharactersCount);
Dec(FBufferDataCount);
Dec(LineEndScanner);
end;
// With FBufferPos = 0 we have scanned back in our
// buffer and not found any line break; this means
// that we cannot employ our pattern matcher on a
// complete line -> Internal Error.
if FBufferDataCount = 0 then
raise ELineTooLong.CreateResFmt(@SLineLengthError, [FBufSize - 1, FFileName]);
end;
// Cut off everything beyond the line break
// Assert(FBufferDataCount >= 0);
FSearchBuffer[FBufferDataCount] := #0;
end;
procedure TBaseSearcher.DoSearch;
var
i: Integer;
LPos: Integer;
UseChar : boolean;
begin
SignalStartSearch;
LPos := 0;
while not FEof do
begin
// Read new data in
if (FBufferSearchPos >= FBufferDataCount) or (FBufferDataCount = 0) then
begin
try
FillBuffer;
except on E: ELineTooLong do
begin
MessageDlg(E.Message, mtWarning, [mbOK], 0);
Exit;
end;
end;
end;
if FEof then Exit;
i := FBufferSearchPos;
while i < FBufferDataCount do
begin
UseChar := False;
case FSearchBuffer[i] of
#0:
begin
FBufferSearchPos := FBufferDataCount + 1;
Break;
end;
#10:
begin
FBufferSearchPos := i + 1;
FCommentActive := False;
Break;
end;
#13:
begin
FBufferSearchPos := i + 1;
if FSearchBuffer[FBufferSearchPos] = #10 then Inc(FBufferSearchPos);
FCommentActive := False;
Break;
end;
else
if FNoComments then begin
if not FCommentActive then begin
if FSearchBuffer[i] = '#' then
FCommentActive := True
else
UseChar := True;
end;
end else
UseChar := True;
end;
if UseChar then
begin
//if not (soCaseSensitive in SearchOptions) then
BLine[LPos] := FSearchBuffer[i];
Inc(LPos);
if LPos >= SearchLineSize-1 then // Enforce maximum line length constraint
Exit; // Binary, not text file
end;
Inc(i);
end;
if FSearchBuffer[i] <> #0 then Inc(FLineNo);
BLine[LPos] := #0;
if BLine[0] <> #0 then PatternMatch;
LPos := 0;
if FBufferSearchPos < i then FBufferSearchPos := i;
end;
end;
procedure TBaseSearcher.SetBufSize(New: Integer);
begin
if (FSearchBuffer = nil) and (New <> FBufSize) then
FBufSize := New;
end;
procedure TBaseSearcher.SetPattern(const Value: string);
begin
fPattern := Value;
if soRegEx in SearchOptions then begin
if not Assigned(fRegExpr) then
fRegExpr := TRegExpr.Create();
fRegExpr.ModifierI := soCaseSensitive in SearchOptions;
try
fRegExpr.Expression := Value;
fRegExpr.Compile;
except
on E: ERegExpr do
raise Exception.Create('Invalid Regular expression: ' + E.Message);
end;
end;
end;
procedure TBaseSearcher.PatternMatch;
{
Use RegExpr if RegExpr soRegEx in SearchOptions.
Else use JclFind or JclSearch depending on whether the search is
case sensitive.
}
var
LinePos: Integer;
Found : Boolean;
EndPos : integer;
procedure IsFound;
// Deals with soWholeWord Search option
var
Start: Integer;
TestChar: Char;
begin
if soWholeWord in SearchOptions then
begin
Start := LinePos - 2; // Point to previous character (-2 since PChars are zero based)
if (Start >= 0) then
begin
TestChar := BLine[Start];
if IsCharAlphaNumeric(TestChar) or (TestChar = '_') then
Exit;
end;
TestChar := BLine[EndPos]; // Next Character
if TestChar <> #0 then
begin
if IsCharAlphaNumeric(TestChar) or (TestChar = '_') then
Exit;
end;
end;
SignalFoundMatch(FLineNo, BLine, LinePos, EndPos)
end;
begin
if soRegEx in SearchOptions then begin
Found := fRegExpr.Exec(BLine);
while Found do begin
LinePos := fRegExpr.MatchPos[0];
EndPos := LinePos + fRegExpr.MatchLen[0] - 1;
IsFound;
Found := fRegExpr.ExecNext;
end;
end else begin
EndPos := 0;
Repeat
if soCaseSensitive in SearchOptions then
LinePos := StrSearch(fPattern, BLine, EndPos + 1)
else
LinePos := StrFind(fPattern, BLine, EndPos + 1);
Found := LinePos > 0;
if Found then begin
EndPos := LinePos + Length(fPattern) - 1;
IsFound;
end;
Until not Found;
end;
end;
procedure TBaseSearcher.SignalStartSearch;
begin
if Assigned(FOnStartSearch) then
FOnStartSearch(Self);
end;
procedure TBaseSearcher.SignalFoundMatch(LineNo: Integer; const Line: string;
SPos, EPos: Integer);
begin
if Assigned(FOnFound) then
FOnFound(Self, LineNo, Line, SPos, EPos);
end;
end.
|
unit structure_unt;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxPC, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxStyles, cxEdit, cxTextEdit, cxVGrid,
cxInplaceContainer, dxDockControl, dxDockPanel, Vcl.ExtCtrls, dxBar, cxClasses,
Vcl.Buttons, Vcl.ImgList, cxCheckComboBox, cxCheckGroup, cxBarEditItem,
Vcl.ComCtrls, cxCustomData, cxTL, cxTLdxBarBuiltInMenu,
dataunt;
type
// Define a Node object
MStructure = object
procedure InitData;
procedure ReloadData;
procedure ProcessChildren(N: TcxTreeListNode; Recurse: Boolean);
procedure CheckChanged(Sender: TcxCustomTreeList;
ANode: TcxTreeListNode; AState: TcxCheckBoxState);
end;
var Structure : MStructure;
implementation
uses Main, nodeunt;
function AddNode(AParent: TcxTreeListNode; const AValues: Array of Variant; AImageIndex: Integer; enabled : boolean; checked : boolean): TcxTreeListNode;
begin
Result := mainform.tlStructure.AddChild(AParent);
Result.AssignValues(AValues);
Result.CheckGroupType := ncgCheckGroup;
//Result.Imageindex := AImageIndex;
Result.CheckGroupType := ncgCheckGroup;
Result.Expanded := true;
Result.Expand(true);
Result.Enabled := enabled;
Result.Checked := checked;
end;
procedure MStructure.CheckChanged(Sender: TcxCustomTreeList;
ANode: TcxTreeListNode; AState: TcxCheckBoxState);
var s : string;
j,n : integer;
begin
// if ANode = mainform.tlStructure.FocusedNode then
// begin
if not busy_create then
begin
s := ANode.Texts[0];
{if Pos('Cad', s) > 0 then
Dbase.cad_active := AState = cbsChecked; }
if Pos('Lines', s) > 0 then
begin
Dbase.Lines.active := AState = cbsChecked;
for j:=1 to dbase.Lines.no do
dbase.lines.line[j].switch_active(Dbase.Lines.active);
end;
if Pos('Circles', s) > 0 then
begin
Dbase.Circles.active := AState = cbsChecked;//true
for j:=1 to dbase.circles.no do
dbase.circles.circle[j].switch_active(Dbase.circles.active);
end;
if Pos('Sprinklers', s) > 0 then
begin
Dbase.Blocks.display_nodes[1] := AState = cbsChecked;//true
for j:=0 to Dbase.Blocks.No do
for n:=1 to Dbase.Blocks.Block[j].nonode do
with Dbase.Blocks.Block[j].node[n] do
switch_active(Dbase.Blocks.display_nodes[1]);
end;
{if Pos('Points', s) > 0 then
begin
if AState = cbsChecked then
Dbase.Points.show
else
Dbase.Points.hide;
end; }
//Dbase.draw;
end;
//end;
end;
procedure MStructure.InitData;
var
ARootNode, ATempNode, AChildNode, ASalesMarketingNode: TcxTreeListNode;
ANode: TcxTreeListNode;
AValues: Array of Variant;
node, childnode : TcxTreeListNode;
i, line_total, points_total : integer;
sTitle: String;
grp: TcxTreeListNode;
begin
mainform.tlStructure.Clear;
ARootNode := AddNode(nil, ['Dtm'], 8, true, true);
AChildNode := AddNode(ARootNode, ['Points'], 1, true, true);
AChildNode := AddNode(ARootNode, ['Triangles'], 1, false, true);
AChildNode := AddNode(ARootNode, ['Contours'], 1, false, true);
ARootNode := AddNode(nil, ['Cad'], 8, true, true);
AChildNode := AddNode(ARootNode, ['Lines'], 1, true, true);
AChildNode := AddNode(ARootNode, ['Circles'], 1, true, true);
AChildNode := AddNode(ARootNode, ['Patterns'], 1, false, true);
ARootNode := AddNode(nil, ['Irrigation'], 8, true, true);
ATempNode := AddNode(ARootNode, ['Pipes'], 1, true, true);
AChildNode := AddNode(ATempNode, ['Mainline'], 1, true, true);
AChildNode := AddNode(ATempNode, ['Laterals'], 1, true, true);
ATempNode := AddNode(ARootNode, ['Emitters'], 1, true, true);
AChildNode := AddNode(ATempNode, ['Pumps'], 1, true, true);
AChildNode := AddNode(ATempNode, ['Sprinklers'], 1, true, true);
AChildNode := AddNode(ATempNode, ['Valves'], 1, true, true);
AChildNode := AddNode(ATempNode, ['Fittings'], 1, true, true);
//AChildNode := AddNode(ATempNode, ['Regulators'], 1, true, true);
//AChildNode := AddNode(ATempNode, ['Boosters'], 1, true, true);
mainform.tlStructure.FullCollapse;
mainform.tlStructure.Root[0].Expanded := True;
mainform.tlStructure.Root[1].Expanded := True;
mainform.tlStructure.Root[2].Expanded := True;
ATempNode := mainform.tlStructure.Root[2].getFirstChild;
ATempNode.Expanded := True;
ATempNode.getNextSibling.Expanded := True;
end;
procedure MStructure.ProcessChildren(N: TcxTreeListNode; Recurse: Boolean);
var I: Integer;
val : array of variant;
s : string;
begin
s := N.Texts[0];
{if Pos('Dtm', s) > 0 then
N.Texts[0] := 'Dtm ' + '('+inttostr(Dtm.getTotal)+')';
if Pos('Points', s) > 0 then
N.Texts[0] := 'Points ' + '('+inttostr(Shapes.Points.total)+')';
}
{if Pos('Triangles', s) > 0 then
N.Texts[0] := 'Triangles ' + '('+inttostr(Points.total)+')';
if Pos('Contours', s) > 0 then
N.Texts[0] := 'Contours ' + '('+inttostr(Points.total)+')'; }
{if Pos('Cad', s) > 0 then
N.Texts[0] := 'Cad ' + '('+inttostr(Cad.getTotal)+')';
}
if Pos('Lines', s) > 0 then
N.Texts[0] := 'Lines ' + '('+inttostr(dbase.Lines.no)+')';
if Pos('Circles', s) > 0 then
N.Texts[0] := 'Circles ' + '('+inttostr(dbase.Circles.no)+')';
if Pos('Sprinklers', s) > 0 then
N.Texts[0] := 'Sprinklers ' + '('+inttostr(dbase.Blocks.CountAllNodeType(sprinkler))+')';
{if Pos('Patterns', s) > 0 then
N.Texts[0] := 'Patterns ' + '('+inttostr(Circles.total)+')';
if Pos('Irrigation', s) > 0 then
N.Texts[0] := 'Irrigation ' + '('+inttostr(Irrigation.getTotal)+')';
if Pos('Pipes', s) > 0 then
N.Texts[0] := 'Pipes ' + '('+inttostr(Circles.total)+')';
if Pos('Emitters', s) > 0 then
N.Texts[0] := 'Emitters ' + '('+inttostr(Circles.total)+')'; }
for I := 0 to N.Count - 1 do
begin
// ... To do something
if Recurse and N.HasChildren then
ProcessChildren(N[I], Recurse);
end;
end;
procedure MStructure.ReloadData;
var I: Integer;
begin
with mainform.tlStructure do
for I := 0 to Count - 1 do
begin
// ... To do something
ProcessChildren(Items[I], True);
end;
end;
end.
|
{-----------------------------------------------------------------------------
Unit Name: cPyDebugger
Author: Kiriakos Vlahos
Date: 23-Feb-2005
Purpose:
History: Origianlly Based on SynEdit IDE Demo debugger
-----------------------------------------------------------------------------}
unit cPyDebugger;
interface
uses
Windows, SysUtils, Classes, uEditAppIntfs, PythonEngine, Forms, Contnrs,
cPyBaseDebugger;
type
TFrameInfo = class(TBaseFrameInfo)
private
fPyFrame : Variant;
protected
// Implementation of the Base class for the internal debugger
function GetFunctionName : string; override;
function GetFileName : string; override;
function GetLine : integer; override;
public
constructor Create(Frame : Variant);
property PyFrame : Variant read fPyFrame;
end;
TNameSpaceItem = class(TBaseNameSpaceItem)
// Implementation of the Base class for the internal debugger
private
fPyObject : Variant;
fChildNodes : TStringList;
fName : string;
protected
function GetName : string; override;
function GetObjectType : string; override;
function GetValue : string; override;
function GetDocString : string; override;
function GetChildCount : integer; override;
function GetChildNode(Index: integer): TBaseNameSpaceItem; override;
public
constructor Create(aName : string; aPyObject : Variant);
destructor Destroy; override;
function IsDict : Boolean; override;
function IsModule : Boolean; override;
function IsFunction : Boolean; override;
function IsMethod : Boolean; override;
function Has__dict__ : Boolean; override;
function IndexOfChild(AName : string): integer; override;
procedure GetChildNodes; override;
end;
TPyDebugger = class(TPyBaseDebugger)
// pdb based internal debugger
private
fDebuggerCommand : TDebuggerCommand;
fCurrentFrame : Variant;
protected
procedure SetDebuggerBreakpoints;
procedure LoadLineCache;
procedure UserCall(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject);
procedure UserLine(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject);
procedure UserReturn(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject);
procedure UserException(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject);
procedure UserYield(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject);
property CurrentFrame : Variant read fCurrentFrame;
public
constructor Create;
procedure Run(Editor : IEditor; InitStepIn : Boolean = False); override;
procedure RunToCursor(Editor : IEditor; ALine: integer); override;
procedure StepInto(Editor : IEditor); override;
procedure StepOver; override;
procedure StepOut; override;
procedure Pause; override;
procedure Abort; override;
procedure Evaluate(const Expr : string; out ObjType, Value : string); override;
procedure GetCallStack(CallStackList : TObjectList); override;
function GetFrameGlobals(Frame : TBaseFrameInfo) : TBaseNameSpaceItem; override;
function GetFrameLocals(Frame : TBaseFrameInfo) : TBaseNameSpaceItem; override;
end;
implementation
uses dmCommands, frmPythonII, VarPyth, frmMessages, frmPyIDEMain,
MMSystem, Math, JvDockControlForm, JclFileUtils, Dialogs, uCommonFunctions,
cParameters, JclSysUtils, StringResources;
{ TFrameInfo }
constructor TFrameInfo.Create(Frame: Variant);
begin
fPyFrame := Frame;
inherited Create;
end;
function TFrameInfo.GetFileName: string;
begin
Result := fPyFrame.f_code.co_filename;
end;
function TFrameInfo.GetFunctionName: string;
begin
Result := fPyFrame.f_code.co_name;
end;
function TFrameInfo.GetLine: integer;
begin
Result := fPyFrame.f_lineno;
end;
{ TNameSpaceItem }
constructor TNameSpaceItem.Create(aName : string; aPyObject: Variant);
begin
fName := aName;
fPyObject := aPyObject;
end;
destructor TNameSpaceItem.Destroy;
begin
if Assigned(fChildNodes) then
fChildNodes.Free;
inherited;
end;
function TNameSpaceItem.GetChildCount: integer;
begin
if Assigned(fChildNodes) then
Result := fChildNodes.Count
else begin
try
if VarIsPythonDict(fPyObject) then
Result := len(fPyObject)
else if Has__dict__ then
Result := len(fPyObject.__dict__)
else
Result := 0;
except
Result := 0;
end;
end;
end;
function TNameSpaceItem.GetChildNode(Index: integer): TBaseNameSpaceItem;
begin
Assert(Index >= 0, 'TNameSpaceItem.GetChildNode');
if not Assigned(fChildNodes) then
GetChildNodes;
Assert(Index < fChildNodes.Count, 'TNameSpaceItem.GetChildNode');
Result := fChildNodes.Objects[Index] as TBaseNameSpaceItem;
end;
procedure TNameSpaceItem.GetChildNodes;
Var
Dict, DictKeys : Variant;
Count, i : integer;
Name : string;
NameSpaceItem : TNameSpaceItem;
SupressOutput : IInterface;
begin
if not Assigned(fChildNodes) then begin
SupressOutput := PythonIIForm.OutputSupressor; // Do not show errors
try
if VarIsPythonDict(fPyObject) then begin
Dict := fPyObject;
Count := len(fPyObject);
end else if Has__dict__ then begin
Dict := fPyObject.__dict__;
Count := len(Dict);
end else
Count := 0;
if Count > 0 then begin
fChildNodes := TStringList.Create;
fChildNodes.CaseSensitive := True;
fChildNodes.Duplicates := dupAccept;
DictKeys := Dict.keys();
for i := 0 to Count - 1 do begin
Name := DictKeys.GetItem(i);
NameSpaceItem := TNameSpaceItem.Create(Name,
Dict.GetItem(DictKeys.GetItem(i)));
fChildNodes.AddObject(Name, NameSpaceItem);
end;
fChildNodes.Sorted := True;
GotChildNodes := True;
end;
except
// fail quietly
end;
end;
end;
function TNameSpaceItem.GetDocString: string;
Var
SupressOutput : IInterface;
begin
SupressOutput := PythonIIForm.OutputSupressor; // Do not show errors
try
Result := Import('inspect').getdoc(fPyObject);
except
Result := '';
end;
end;
function TNameSpaceItem.GetName: string;
begin
Result := fName;
end;
function TNameSpaceItem.GetObjectType: string;
Var
SupressOutput : IInterface;
begin
SupressOutput := PythonIIForm.OutputSupressor; // Do not show errors
try
Result := _type(fPyObject).__name__;
except
Result := '';
end;
end;
function TNameSpaceItem.GetValue: string;
Var
SupressOutput : IInterface;
begin
SupressOutput := PythonIIForm.OutputSupressor; // Do not show errors
try
Result := PythonIIForm.II.saferepr(fPyObject);
except
Result := '';
end;
end;
function TNameSpaceItem.Has__dict__: Boolean;
begin
Result := (GetPythonEngine.PyObject_HasAttrString(
ExtractPythonObjectFrom(fPyObject), '__dict__') = 1) and
VarIsPythonDict(fPyObject.__dict__) // it can be None with extensions!;
end;
function TNameSpaceItem.IndexOfChild(AName: string): integer;
begin
if not Assigned(fChildNodes) then
GetChildNodes;
if Assigned(fChildNodes) then
Result := fChildNodes.IndexOf(AName)
else
Result := -1;
end;
function TNameSpaceItem.IsDict: Boolean;
begin
Result := VarIsPythonDict(fPyObject);
end;
function TNameSpaceItem.IsFunction: Boolean;
begin
Result := VarIsPythonFunction(fPyObject);
end;
function TNameSpaceItem.IsMethod: Boolean;
begin
Result := VarIsPythonMethod(fPyObject);
end;
function TNameSpaceItem.IsModule: Boolean;
begin
Result := VarIsPythonModule(fPyObject);
end;
{ TPyDebugger }
constructor TPyDebugger.Create;
begin
inherited Create;
fDebuggerCommand := dcNone;
end;
procedure TPyDebugger.Evaluate(const Expr : string; out ObjType, Value : string);
Var
SupressOutput : IInterface;
V : Variant;
begin
ObjType := SNotAvailable;
Value := SNotAvailable;
if fDebuggerState = dsPaused then begin
SupressOutput := PythonIIForm.OutputSupressor; // Do not show errors
try
V := PythonIIForm.BuiltIns.eval(Expr,
CurrentFrame.f_globals, CurrentFrame.f_locals);
ObjType := BuiltInModule.type(V).__name__;
Value := PythonIIForm.II.saferepr(V);
except
// fail quitely
end;
end;
end;
procedure TPyDebugger.GetCallStack(CallStackList: TObjectList);
Var
Frame : Variant;
begin
CallStackList.Clear;
if fDebuggerState <> dsPaused then
Exit;
Frame := CurrentFrame;
if VarIsPython(Frame) then
// We do not show the last two frames
while not VarIsNone(Frame.f_back) and not VarIsNone(Frame.f_back.f_back) do begin
CallStackList.Add(TFrameInfo.Create(Frame));
Frame := Frame.f_back;
end;
end;
function TPyDebugger.GetFrameGlobals(Frame: TBaseFrameInfo): TBaseNameSpaceItem;
begin
Result := nil;
if fDebuggerState <> dsPaused then
Exit;
Result := TNameSpaceItem.Create('globals', (Frame as TFrameInfo).fPyFrame.f_globals);
end;
function TPyDebugger.GetFrameLocals(Frame: TBaseFrameInfo): TBaseNameSpaceItem;
begin
Result := nil;
if fDebuggerState <> dsPaused then
Exit;
Result := TNameSpaceItem.Create('locals', (Frame as TFrameInfo).fPyFrame.f_locals);
end;
procedure TPyDebugger.Pause;
// Not pausible to implement with the debugger running in the main thread
begin
if fDebuggerState = dsRunning then
fWantedState := dsPaused;
DoStateChange;
end;
// Timer callback function
procedure TPyDebugger.Run(Editor : IEditor; InitStepIn : Boolean = False);
var
OldPS1, OldPS2 : string;
Code : Variant;
TI : TTracebackItem;
Path, OldPath : string;
PythonPathAdder : IInterface;
begin
// Repeat here to make sure it is set right
MaskFPUExceptions(CommandsDataModule.PyIDEOptions.MaskFPUExceptions);
fDebuggerCommand := dcRun;
if (fDebuggerState <> dsInactive) then exit; // pass control to user_line
//Compile
Code := Compile(Editor);
if VarIsPython(Code) then with PythonIIForm do begin
Path := ExtractFilePath(Editor.FileName);
OldPath := GetCurrentDir;
if Length(Path) > 1 then begin
Path := PathRemoveSeparator(Path);
// Add the path of the executed file to the Python path - Will be automatically removed
PythonPathAdder := AddPathToPythonPath(Path);
// Change the current path
try
ChDir(Path)
except
MessageDlg('Could not set the current directory to the script path', mtWarning, [mbOK], 0);
end;
end;
fWantedState := dsRunning;
DoStateChange;
// Set the layout to the Debug layout is it exists
MessagesWindow.ClearMessages;
if PyIDEMainForm.Layouts.IndexOf('Debug') >= 0 then begin
PyIDEMainForm.SaveLayout('Current');
PyIDEMainForm.LoadLayout('Debug');
Application.ProcessMessages;
end else
ShowDockForm(PythonIIForm);
try
OldPS1 := PS1;
PS1 := '[Dbg]' + PS1;
OldPS2 := PS2;
PS2 := '[Dbg]' + PS2;
AppendText(sLineBreak+PS1);
//attach debugger callback routines
DebugIDE.Events.Items[0].OnExecute := UserCall;
DebugIDE.Events.Items[1].OnExecute := UserLine;
DebugIDE.Events.Items[2].OnExecute := UserReturn;
DebugIDE.Events.Items[3].OnExecute := UserException;
DebugIDE.Events.Items[4].OnExecute := UserYield;
//set breakpoints
SetDebuggerBreakPoints;
// New Line for output
PythonIIForm.AppendText(sLineBreak);
// Set the command line parameters
SetCommandLine(Editor.GetFileNameOrTitle);
Debugger.InitStepIn := InitStepIn;
try
Debugger.run(Code);
except
// CheckError already called by VarPyth
on E: Exception do begin
MessagesWindow.ShowPythonTraceback;
MessagesWindow.AddMessage(E.Message);
with GetPythonEngine.Traceback do begin
if ItemCount > 0 then begin
TI := Items[ItemCount -1];
if PyIDEMainForm.ShowFilePosition(TI.FileName, TI.LineNo, 1) and
Assigned(GI_ActiveEditor)
then begin
FErrorPos.Editor := GI_ActiveEditor;
fErrorPos.Line := TI.LineNo;
DoErrorPosChanged;
end;
end;
end;
MessageDlg(E.Message, mtError, [mbOK], 0);
SysUtils.Abort;
end;
end;
finally
PS1 := OldPS1;
PS2 := OldPS2;
AppendText(sLineBreak+PS1);
// Restore the command line parameters
RestoreCommandLine;
// Change the back current path
ChDir(OldPath);
if PyIDEMainForm.Layouts.IndexOf('Debug') >= 0 then
PyIDEMainForm.LoadLayout('Current');
fWantedState := dsInactive;
DoStateChange;
end;
end;
end;
procedure TPyDebugger.RunToCursor(Editor : IEditor; ALine: integer);
Var
FName : string;
begin
// Set Temporary breakpoint
SetDebuggerBreakPoints; // So that this one is not cleared
FName := Editor.FileName;
if FName = '' then
FName := '<'+Editor.FileTitle+'>';
PythonIIForm.Debugger.set_break(FName, ALine, 1);
if fDebuggerState = dsInactive then
Run(Editor)
else
fDebuggerCommand := dcRunToCursor;
end;
procedure TPyDebugger.StepInto(Editor : IEditor);
begin
if fDebuggerState = dsInactive then
Run(Editor, True)
else
fDebuggerCommand := dcStepInto;
end;
procedure TPyDebugger.StepOver;
begin
fDebuggerCommand := dcStepOver;
end;
procedure TPyDebugger.StepOut;
begin
fDebuggerCommand := dcStepOut;
end;
procedure TPyDebugger.Abort;
begin
fDebuggerCommand := dcAbort;
end;
procedure TPyDebugger.UserCall(Sender: TObject; PSelf, Args: PPyObject;
var Result: PPyObject);
begin
// PythonIIForm.AppendText('UserCall'+sLineBreak);
Result := GetPythonEngine.ReturnNone;
end;
procedure TPyDebugger.UserException(Sender: TObject; PSelf,
Args: PPyObject; var Result: PPyObject);
begin
// PythonIIForm.AppendText('UserException'+sLineBreak);
Result := GetPythonEngine.ReturnNone;
end;
procedure TPyDebugger.UserLine(Sender: TObject; PSelf, Args: PPyObject;
var Result: PPyObject);
Var
Frame : Variant;
FName : string;
begin
Result := GetPythonEngine.ReturnNone;
Frame := VarPythonCreate(Args).GetItem(0);
FName := Frame.f_code.co_filename;
if (FName[1] ='<') and (FName[Length(FName)] = '>') then
FName := Copy(FName, 2, Length(FName)-2);
// PythonIIForm.AppendText('UserLine '+ FName + ' ' + IntToStr(Frame.f_lineno) +sLineBreak);
if PyIDEMainForm.ShowFilePosition(FName, Frame.f_lineno, 1) and
(Frame.f_lineno > 0) then
begin
FCurrentPos.Editor := GI_EditorFactory.GetEditorByNameOrTitle(FName);
FCurrentPos.Line := Frame.f_lineno;
FCurrentFrame := Frame;
Pause;
FDebuggerCommand := dcNone;
While FDebuggerCommand = dcNone do
DoYield(True);
VarClear(fCurrentFrame);
if fBreakPointsChanged then SetDebuggerBreakpoints;
fWantedState := dsRunning;
DoStateChange;
end;
case fDebuggerCommand of
dcRun : PythonIIForm.Debugger.set_continue();
dcStepInto : PythonIIForm.Debugger.set_step();
dcStepOver : PythonIIForm.Debugger.set_next(Frame);
dcStepOut : PythonIIForm.Debugger.set_return(Frame);
dcRunToCursor : PythonIIForm.Debugger.set_continue;
dcAbort : begin
PythonIIForm.Debugger.set_quit();
MessagesWindow.AddMessage('Debugging Aborted');
MessagesWindow.ShowWindow;
end;
end;
end;
procedure TPyDebugger.UserReturn(Sender: TObject; PSelf, Args: PPyObject;
var Result: PPyObject);
begin
// PythonIIForm.AppendText('UserReturn'+sLineBreak);
Result := GetPythonEngine.ReturnNone;
end;
procedure TPyDebugger.UserYield(Sender: TObject; PSelf, Args: PPyObject;
var Result: PPyObject);
begin
DoYield(False);
if fDebuggerCommand = dcAbort then begin
PythonIIForm.Debugger.set_quit();
MessagesWindow.AddMessage('Debugging Aborted');
MessagesWindow.ShowWindow;
end;
Result := GetPythonEngine.ReturnNone;
end;
procedure TPyDebugger.SetDebuggerBreakpoints;
var
i, j : integer;
FName : string;
V : Variant;
begin
if not fBreakPointsChanged then Exit;
LoadLineCache;
PythonIIForm.Debugger.clear_all_breaks();
for i := 0 to GI_EditorFactory.Count - 1 do
with GI_EditorFactory.Editor[i] do begin
FName := FileName;
if FName = '' then
FName := '<'+FileTitle+'>';
for j := 0 to BreakPoints.Count - 1 do begin
V := PythonIIForm.Debugger.set_break;
if TBreakPoint(BreakPoints[j]).Condition <> '' then begin
GetPythonEngine.EvalFunction(ExtractPythonObjectFrom(V),
[FName, TBreakPoint(BreakPoints[j]).LineNo,
0, TBreakPoint(BreakPoints[j]).Condition]);
// To avoid the implicit conversion of the filename to unicode
// which causes problems due to the strange behaviour of os.path.normcase
//PythonIIForm.Debugger.set_break(FName, TBreakPoint(BreakPoints[j]).LineNo,
// 0, TBreakPoint(BreakPoints[j]).Condition);
end else
GetPythonEngine.EvalFunction(ExtractPythonObjectFrom(V),
[FName, TBreakPoint(BreakPoints[j]).LineNo]);
//PythonIIForm.Debugger.set_break(FName, TBreakPoint(BreakPoints[j]).LineNo);
end;
end;
fBreakPointsChanged := False;
end;
procedure TPyDebugger.LoadLineCache;
Var
i : integer;
Source : string;
begin
// inject unsaved code into LineCache
PythonIIForm.LineCache.cache.clear();
for i := 0 to GI_EditorFactory.Count - 1 do
with GI_EditorFactory.Editor[i] do
if HasPythonfile and (FileName = '') then
begin
Source := CommandsDataModule.CleanEOLs(EncodedText+#10);
PythonIIForm.LineCache.cache.SetItem('<'+FileTitle+'>',
VarPythonCreate([0,0,Source, '<'+FileTitle+'>'], stTuple));
end;
end;
end.
|
unit Myloo.Strings.Utils;
interface
uses
SysUtils,
System.StrUtils,
System.Classes,
Vcl.Graphics,
Soap.EncdDecd,
Myloo.Comp.Coll.Base;
type
TSplitStringCollection = class(TSequence<string>)
private type
TEnumerator = class(TAbstractEnumerator<string>)
private
LNowIndex, LPrevIndex, FLength: NativeInt;
public
constructor Create(const AOwner: TSplitStringCollection);
function TryMoveNext(out ACurrent: string): Boolean; override;
end;
private
FInputString: string;
FSeparator: Char;
FCount: NativeInt;
protected
function GetCount(): NativeInt; override;
public
constructor Create(const AString: string; const ASeparator: Char = ' '); overload;
constructor Create(const ARules: TRules<string>; const AString: string; const ASeparator: Char = ' '); overload;
function Empty(): Boolean; override;
property Count: NativeInt read FCount;
function GetEnumerator(): IEnumerator<string>; override;
end;
function SplitString(const AString: string; const ASeparator: Char = ' '): ISequence<string>;
function ReturnSplitString(AText:string):TStrings;
function ReturnGroupString(AText:string):TStrings;
function RemoveAccents(AText: string): string;
function RemoveOfStr(AText:string;APattern:Array of string): string;
function RemoveDuplicate(AText: string): string;
function StrReplace(const AText: string;AOldChar:array of string;ANewChar:string):string;
function AdaptStr(AText: string): string;
function ReplaceInitialChar(AText:string;AOldChar:array of Char;ANewChar:Char): string;
function ReplaceFinalChar(AText:string;AOldChar:array of Char;ANewChar:Char): string;
function StrListJoin(AStrList:TStringList):string;
function Upper(AText:string):string;
function BitmapFromBase64(const base64: string): TBitmap;
function Base64FromBitmap(Bitmap: TBitmap): string;
function RemoveVowelLessStart(AText:string):string;
function ReplaceBetweenStr(AText:string;AOldChar:array of Char;ANewChar:Char):string;
function RemoveDuplicateStr(AText:string;AListChar:array of Char):string;
function RemoveInitialChar(AText:string;AListChar:array of Char): string;
function ReplaceBetweenVowel(AText:string;AOldChar:array of Char;ANewChar:Char):string;
function IsVowel(AChar:Char):Boolean;
function RemoveSpecialCharacters(AText:string):string;
implementation
function ReturnSplitString(AText:string):TStrings;
var
Values: TStrings;
LWord, LInput: string;
begin
Values := TStringList.Create;
LInput := AText;
//Values.add('Spliting the text: ');
for LWord in SplitString(LInput) do
Values.Add(LWord);
Result:= Values;
end;
function ReturnGroupString(AText:string):TStrings;
var
ValSplit, ValGroup: TStrings;
LWord, LInput: string;
LGroup: IGrouping<Integer, string>;
begin
ValSplit := TStringList.Create;
ValGroup := TStringList.Create;
LInput := AText;
//ValGroup.add('Write all words groupped by their length: ');
for LWord in SplitString(LInput) do
ValSplit.Add(LWord);
for LGroup in SplitString(LInput).
Op.GroupBy<Integer>(function(S: String): Integer begin Exit(Length(S)) end).
Ordered(function(const L, R: IGrouping<Integer, string>): Integer begin Exit(L.Key - R.Key) end) do
begin
ValGroup.Add(Format(' # %d characters: ',[LGroup.Key]));
for LWord in LGroup do
ValGroup.Add(LWord);
end;
Result := ValGroup;
end;
function SplitString(const AString: string; const ASeparator: Char): ISequence<string>;
begin
Result := TSplitStringCollection.Create(AString, ASeparator);
end;
{ TSplitStringCollection }
constructor TSplitStringCollection.Create(const AString: string; const ASeparator: Char);
begin
Create(TRules<string>.Default, AString, ASeparator);
end;
constructor TSplitStringCollection.Create(const ARules: TRules<string>; const AString: string; const ASeparator: Char);
var
LChar: Char;
begin
inherited Create(ARules);
FInputString := AString;
FSeparator := ASeparator;
if Length(AString) > 0 then
begin
FCount := 1;
for LChar in AString do
if LChar = ASeparator then
Inc(FCount);
end;
end;
function TSplitStringCollection.Empty: Boolean;
begin
Result := FCount > 0;
end;
function TSplitStringCollection.GetCount: NativeInt;
begin
Result := FCount;
end;
function TSplitStringCollection.GetEnumerator: IEnumerator<string>;
begin
Result := TEnumerator.Create(Self);
end;
{ TSplitStringCollection.TEnumerator }
constructor TSplitStringCollection.TEnumerator.Create(const AOwner: TSplitStringCollection);
begin
inherited Create(AOwner);
LPrevIndex := 1;
LNowIndex := 1;
FLength := Length(AOwner.FInputString);
end;
function TSplitStringCollection.TEnumerator.TryMoveNext(out ACurrent: string): Boolean;
var
LOwner: TSplitStringCollection;
begin
LOwner := TSplitStringCollection(Owner);
Result := false;
while LNowIndex <= FLength do
begin
if LOwner.FInputString[LNowIndex] = LOwner.FSeparator then
begin
ACurrent := System.Copy(LOwner.FInputString, LPrevIndex, (LNowIndex - LPrevIndex));
LPrevIndex := LNowIndex + 1;
Result := true;
end;
Inc(LNowIndex);
if Result then
Exit;
end;
if LPrevIndex < LNowIndex then
begin
ACurrent := Copy(LOwner.FInputString, LPrevIndex, FLength - LPrevIndex + 1);
LPrevIndex := LNowIndex + 1;
Result := true;
end;
end;
function AdaptStr(AText: string): string;
var
n:Integer;
NewStr:string;
begin
Result := EmptyStr;
for n := 1 to Length(AText) do
begin
case AText[n] of
'B','D','F','J','K','L','M','N','R','T','V','X': NewStr := Format('%s%s',[NewStr,AText[n]]);{Ignorar A,E,I,O,U,Y,H e Espaços}
'C': { CH = X}
begin
if AText[n+1] = 'H' then NewStr := Format('%sX',[NewStr]){CH = X}
else if CharInSet(AText[n+1],['A','O','U']) then NewStr := Format('%sK',[NewStr]) {Carol = Karol}
else if CharInSet(AText[n+1],['E','I']) then NewStr := Format('%sS',[NewStr]); {Celina = Selina, Cintia = Sintia}
end;
'G': if AText[n+n] = 'E' then NewStr := Format('%sJ',[NewStr]) else NewStr := Format('%sG',[NewStr]); {Jeferson = Geferson}
'P': if AText[n+1] = 'H' then NewStr := Format('%sF',[NewStr]) else NewStr := Format('%sP',[NewStr]); {Phelipe = Felipe}
'Q': if AText[n+1] = 'U' then NewStr := Format('%sK',[NewStr]) else NewStr := Format('%sQ',[NewStr]); {Keila = Queila}
'S': if AText[n+1] = 'H' then NewStr := Format('%sX',[NewStr]); {SH = X}
'A','E','I','O','U': if CharInSet(AText[n-1],['A','E','I','O','U']) then NewStr := Format('%sZ',[NewStr]) else NewStr := Format('%sS',[NewStr]); {S entre duas vogais = Z}
'W': NewStr := Format('%sV',[NewStr]); {Walter = Valter}
'Z': if ((n = Length(AText)) or (AText[n+1] = EmptyStr)) then NewStr := Format('%sS',[NewStr]) else NewStr := Format('%sZ',[NewStr]); {No final do nome Tem som de S -> Luiz = Luis}
end;
end;
Result := NewStr;
end;
function RemoveAccents(AText: string): string;
var
NewStr:string;
begin
Result := EmptyStr;
NewStr := Trim(Upper(AText));
NewStr := StrReplace(NewStr,['Á', 'Â', 'Ã', 'À', 'Ä', 'Å'],'A');
NewStr := StrReplace(NewStr,['É', 'Ê', 'È', 'Ë'],'E');
NewStr := StrReplace(NewStr,['Í', 'Î', 'Ì', 'Ï'],'I');
NewStr := StrReplace(NewStr,['Ó', 'Ô', 'Õ', 'Ò', 'Ö'],'O');
NewStr := StrReplace(NewStr,['Ú', 'Û', 'Ù', 'Ü'],'U');
NewStr := StrReplace(NewStr,['Ý', 'Ÿ', 'Y'],'Y');
NewStr := StrReplace(NewStr,['Ç'],'C');
NewStr := StrReplace(NewStr,['Ñ'],'N');
Result := NewStr;
end;
function RemoveDuplicate(AText: string): string;
var
n:Integer;
NewStr:string;
begin
Result := EmptyStr;
NewStr := Upper(Trim(AText));
for n := 1 to Pred(Length(AText)) do
begin
if NewStr[n] = NewStr[n+1] then
Delete(NewStr,n,1);
end;
Result := NewStr;
end;
function RemoveOfStr(AText: string;
APattern: array of string): string;
var
n,p:Integer;
NewStr:string;
begin
Result := EmptyStr;
NewStr := Upper(Trim(AText));
for n := low(APattern) to High(APattern) do
begin
p:= Pos(APattern[n],NewStr);
while p > 0 do
begin
Delete(NewStr,p,Length(APattern[n]));
p:= Pos(APattern[n],NewStr);
end;
end;
Result := NewStr;
end;
function StrReplace(const AText: string;
AOldChar: array of string; ANewChar: string): string;
var
n:Integer;
New:TStringBuilder;
begin
New := TStringBuilder.Create;
New.Clear;
New.Append(Trim(Upper(AText)));
for n := Low(AOldChar) to High(AOldChar) do
begin
New.Replace(AOldChar[n],ANewChar);
end;
Result := New.ToString;
end;
function ReplaceInitialChar(AText:string;AOldChar:array of Char;ANewChar:Char): string;
var
NewStrList,NewStrResult:TStringList;
NewStr:string;
n,i:Integer;
begin
Result := EmptyStr;
NewStrResult := TStringList.Create;
NewStrList := TStringList.Create;
NewStrList.AddStrings(ReturnSplitString(AText));
for n := 0 to Pred(NewStrList.Count) do
begin
NewStr := NewStrList[n];
for i := Low(AOldChar) to High(AOldChar) do
begin
if NewStr[1] = AOldChar[i] then
NewStr[1] := ANewChar;
end;
NewStrResult.Add(NewStr);
end;
Result := StrListJoin(NewStrResult);
end;
function ReplaceFinalChar(AText:string;AOldChar:array of Char;ANewChar:Char): string;
var
NewStrList,NewStrResult:TStringList;
NewStr:string;
n,i:Integer;
begin
Result := EmptyStr;
NewStrResult := TStringList.Create;
NewStrList := TStringList.Create;
NewStrList.AddStrings(ReturnSplitString(AText));
for n := 0 to Pred(NewStrList.Count) do
begin
NewStr := NewStrList[n];
for i := Low(AOldChar) to High(AOldChar) do
begin
if NewStr[Length(NewStr)] = AOldChar[i] then
NewStr[Length(NewStr)] := ANewChar;
end;
NewStrResult.Add(NewStr);
end;
Result := StrListJoin(NewStrResult);
end;
function StrListJoin(AStrList:TStringList):string;
var
n:Integer;
New:TStringBuilder;
begin
New := TStringBuilder.Create;
New.Clear;
for n := 0 to pred(AStrList.Count) do
begin
New.Append(Format('%s ',[AStrList[n]]));
end;
Result := New.ToString;
end;
function Upper(AText:string):string;
begin
StringReplace(AText,'á','Á',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'à','À',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'â','Â',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'å','Å',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'ã','Ã',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'ä','Ä',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'æ','Æ',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'á','Á',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'é','É',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'è','È',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'ê','Ê',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'ë','Ë',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'ð','Ð',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'í','Í',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'ì','Ì',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'î','Î',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'ï','Ï',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'ó','Ó',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'ò','Ò',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'ô','Ô',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'ø','Ø',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'õ','Õ',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'ö','Ö',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'ú','Ú',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'ù','Ù',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'û','Û',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'ü','Ü',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'ç','Ç',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'ñ','Ñ',[rfReplaceAll, rfIgnoreCase]);
StringReplace(AText,'ý','Ý',[rfReplaceAll, rfIgnoreCase]);
Result := AnsiUpperCase(AText)
end;
/////////////////////////////////////////////////////////
////// Converter BitMap/Base64 e Base64/BitMap /////////
////////////////////////////////////////////////////////
{ Example use
var
Bitmap: TBitmap;
s: string;
begin
Bitmap := TBitmap.Create;
Bitmap.SetSize(100,100);
Bitmap.Canvas.Brush.Color := clRed;
Bitmap.Canvas.FillRect(Rect(20, 20, 80, 80));
s := Base64FromBitmap(Bitmap);
Bitmap.Free;
Bitmap := BitmapFromBase64(s);
Bitmap.SaveToFile('C:\desktop\temp.bmp');
end.
}
function Base64FromBitmap(Bitmap: TBitmap): string;
var
Input: TBytesStream;
Output: TStringStream;
begin
Input := TBytesStream.Create;
try
Bitmap.SaveToStream(Input);
Input.Position := 0;
Output := TStringStream.Create('', TEncoding.ASCII);
try
Soap.EncdDecd.EncodeStream(Input, Output);
Result := Output.DataString;
finally
Output.Free;
end;
finally
Input.Free;
end;
end;
function BitmapFromBase64(const base64: string): TBitmap;
var
Input: TStringStream;
Output: TBytesStream;
begin
Input := TStringStream.Create(base64, TEncoding.ASCII);
try
Output := TBytesStream.Create;
try
Soap.EncdDecd.DecodeStream(Input, Output);
Output.Position := 0;
Result := TBitmap.Create;
try
Result.LoadFromStream(Output);
except
Result.Free;
raise;
end;
finally
Output.Free;
end;
finally
Input.Free;
end;
end;
/////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
function RemoveVowelLessStart(AText:string):string;
var
NewStrList,NewStrResult:TStringList;
NewStr,ParcStr:string;
n:Integer;
begin
Result := EmptyStr;
NewStrResult := TStringList.Create;
NewStrList := TStringList.Create;
NewStrList.AddStrings(ReturnSplitString(AText));
for n := 0 to Pred(NewStrList.Count) do
begin
NewStr := NewStrList[n];
ParcStr := copy(NewStr,2,Length(NewStr));
ParcStr := RemoveOfStr(ParcStr,['A','E','I','O','U']);
NewStrResult.Add(Format('%s%s',[NewStr[1],ParcStr]));
end;
Result := StrListJoin(NewStrResult);
end;
function ReplaceBetweenStr(AText:string;AOldChar:array of Char;ANewChar:Char):string;
var
NewStrList,NewStrResult:TStringList;
NewStr:string;
n,i,j:Integer;
begin
Result := EmptyStr;
NewStrResult := TStringList.Create;
NewStrList := TStringList.Create;
NewStrList.AddStrings(ReturnSplitString(AText));
for n := 0 to Pred(NewStrList.Count) do
begin
NewStr := NewStrList[n];
for i := Low(AOldChar) to High(AOldChar) do
begin
for j := 2 to Pred(Length(NewStr)) do
begin
if NewStr[j] = AOldChar[i] then
NewStr[j] := ANewChar;
end;
end;
NewStrResult.Add(NewStr);
end;
Result := StrListJoin(NewStrResult);
end;
function RemoveDuplicateStr(AText:string;AListChar:array of Char):string;
var
NewStrList,NewStrResult:TStringList;
NewStr:string;
n,i:Integer;
begin
Result := EmptyStr;
NewStrResult := TStringList.Create;
NewStrList := TStringList.Create;
NewStrList.AddStrings(ReturnSplitString(AText));
for n := 0 to Pred(NewStrList.Count) do
begin
NewStr := NewStrList[n];
for i := Low(AListChar) to High(AListChar) do
begin
NewStr := NewStrList[n];
StrReplace(NewStr,[AListChar[i]+AListChar[i]],AListChar[i]);
end;
NewStrResult.Add(NewStr);
end;
Result := StrListJoin(NewStrResult);
end;
function RemoveInitialChar(AText:string;AListChar:array of Char): string;
var
NewStrList,NewStrResult:TStringList;
NewStr:string;
n,i:Integer;
begin
Result := EmptyStr;
NewStrResult := TStringList.Create;
NewStrList := TStringList.Create;
NewStrList.AddStrings(ReturnSplitString(AText));
for n := 0 to Pred(NewStrList.Count) do
begin
NewStr := NewStrList[n];
for i := Low(AlistChar) to High(AListChar) do
begin
if NewStr[1] = AListChar[i] then
delete(NewStr,1, 1);
end;
NewStrResult.Add(NewStr);
end;
Result := StrListJoin(NewStrResult);
end;
function ReplaceBetweenVowel(AText:string;AOldChar:array of Char;ANewChar:Char):string;
var
NewStrList,NewStrResult:TStringList;
NewStr:string;
n,i,j:Integer;
AChar:Char;
begin
Result := EmptyStr;
NewStrResult := TStringList.Create;
NewStrList := TStringList.Create;
NewStrList.AddStrings(ReturnSplitString(AText));
for n := 0 to Pred(NewStrList.Count) do
begin
NewStr := NewStrList[n];
for i := Low(AOldChar) to High(AOldChar) do
begin
for j := 1 to Length(NewStr)do
begin
//AChar := NewStr[j];
if ((IsVowel(NewStr[j-1])) and (IsVowel(NewStr[j+1])) and (AOldChar[i] = NewStr[j])) then
NewStr[j] := ANewChar;
end;
end;
NewStrResult.Add(NewStr);
end;
Result := StrListJoin(NewStrResult);
end;
function IsVowel(AChar:Char):Boolean;
begin
Result := ((AChar='A')or(AChar='E')or(AChar='I')or(AChar='O')or(AChar='U'));
end;
function RemoveSpecialCharacters(AText:string):string;
const
xSpecChar: array[1..48] of string = ('<','>','!','@','#','$','%','¨','&','*',
'(',')','_','+','=','{','}','[',']','?',
';',':',',','|','*','"','~','^','´','`',
'¨','æ','Æ','ø','£','Ø','ƒ','ª','º','¿',
'®','½','¼','ß','µ','þ','ý','Ý');
var
i : Integer;
begin
for i:=1 to 48 do
Result := StringReplace(AText, xSpecChar[i], '', [rfreplaceall]);
end;
end.
|
unit u_gateway;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, u_rules, u_libs, fphttpclient;
function UploadBackups(AFileBackup: String): Boolean;
implementation
function UploadBackups(AFileBackup: String): Boolean;
var
S: TStringStream;
Vars: TStringList;
VInfo: IGetInfo;
begin
Result := False;
with TFPHTTPClient.Create(nil) do
begin
S := TStringStream.Create('');
try
Vars := TStringList.Create;
try
VInfo := TGetInfo.new;
Vars.Add('app=sabik_plus');
Vars.Add('id='+ VInfo.id_gateway.to_s);
Vars.Add('token='+ VInfo.token);
FileFormPost('http://chocobits.com.br/backups', Vars, 'upload', AFileBackup, S);
//FileFormPost('http://10.0.2.2:9393/backups', Vars, 'upload', AFileBackup, S);
finally
Vars.Free;
end;
finally
Result := UpperCase(S.DataString) = 'SUCESSO';
S.Free
end;
end;
end;
end.
|
program HowToCreateAnAnimation;
uses sgGraphics, sgSprites, sgTypes, sgImages, sgUtils, sgInput, sgAudio, sgAnimations;
procedure Main();
var
walking: Sprite;
fish: Bitmap;
begin
OpenAudio();
OpenGraphicsWindow('Walking Frog', 800, 600);
fish := LoadBitmapNamed('walking', 'frog.png');
BitmapSetCellDetails(fish, 73, 105, 4, 4, 16);
LoadAnimationScriptNamed('WalkingScrpt', 'kermit.txt');
walking := CreateSprite(fish, AnimationScriptNamed('WalkingScrpt'));
SpriteStartAnimation(walking, 'Dance');
SpriteSetX(walking, 400);
SpriteSetY(walking, 300);
repeat
ClearScreen(ColorWhite);
DrawSprite(walking);
RefreshScreen(60);
UpdateSprite(walking);
ProcessEvents();
until WindowCloseRequested();
Delay(800);
end;
begin
Main();
end. |
program questao17;
{
Autor: Hugo Deiró Data: 03/06/2012
- Este programa recebe um número representando um ano
e informa se este ano é bissexto ou não.
}
var
ano : integer;
begin
write('Insira um ano: ');
readln(ano);
if(ano > 0)then
if(ano mod 100 <> 0) and (ano mod 4 = 0) or (ano mod 400 = 0)then
writeln('O ano é bissexto!')
else
writeln('O ano não é bissexto!')
else
writeln('Ano Inválido!');
end.
|
unit uKForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ibase, FIBDatabase, pFIBDatabase, cxDropDownEdit, cxCalendar,
cxSpinEdit, cxCheckBox, cxControls, cxContainer, cxEdit, cxTextEdit,
cxMaskEdit, StdCtrls, DB, FIBDataSet, pFIBDataSet, ActnList, FIBQuery,
pFIBQuery, pFIBStoredProc, frxClass, frxDBSet, frxDesgn, uMainPerem, DateUtils,
cxLookAndFeelPainters, cxButtons;
type
TKassForm = class(TForm)
DatabaseWork: TpFIBDatabase;
lbl2: TLabel;
lbl7: TLabel;
cxPrintForm: TcxComboBox;
chbPrinter: TcxCheckBox;
chbChoosePrinter: TcxCheckBox;
lbl5: TLabel;
cxCopies: TcxSpinEdit;
cxDateBeg: TcxDateEdit;
Label1: TLabel;
cxDateEnd: TcxDateEdit;
frxReport: TfrxReport;
frxDesigner1: TfrxDesigner;
frxDBDataset1: TfrxDBDataset;
Transaction: TpFIBTransaction;
StPr: TpFIBStoredProc;
actlst1: TActionList;
actClose: TAction;
actPrint: TAction;
actdesigne: TAction;
DataSetWork: TpFIBDataSet;
cxButton1: TcxButton;
cxButton2: TcxButton;
cxCheckEdit: TcxCheckBox;
procedure actdesigneExecute(Sender: TObject);
procedure actCloseExecute(Sender: TObject);
procedure actPrintExecute(Sender: TObject);
private
DBHANDLE : TISC_DB_HANDLE;
public
constructor Create(AOwner:TComponent; DBHANDLE : TISC_DB_HANDLE);overload;
end;
procedure ShowKassDayForm(AOwner:TComponent; DBHANDLE : TISC_DB_HANDLE); stdcall;
exports ShowKassDayForm;
var
KassForm: TKassForm;
implementation
{$R *.dfm}
uses uWate;
constructor TKassForm.Create(AOwner:TComponent;DBHANDLE : TISC_DB_HANDLE);
begin
inherited Create(AOwner);
if Assigned(DBHandle)
then begin
Self.DBHANDLE := DBHandle;
Self.DatabaseWork.Close;
Self.DatabaseWork.Handle:=DBHANDLE;
Self.cxDateBeg.Date:=PERS_PAY_PERIOD;
Self.cxDateEnd.Date:=PERS_PAY_PERIOD;
self.cxPrintForm.ItemIndex:=0;
end;
end;
procedure ShowKassDayForm(AOwner:TComponent; DBHANDLE : TISC_DB_HANDLE);stdcall;
var
form : TKassForm;
begin
form := TKassForm.Create(AOwner, DBHANDLE);
Form.Show;// = mrOk then Form.free;;
// Form.Free;
end;
procedure TKassForm.actdesigneExecute(Sender: TObject);
begin
if cxCheckEdit.Visible = true then cxCheckEdit.Visible:=False
else cxCheckEdit.Visible:=True;
end;
procedure TKassForm.actCloseExecute(Sender: TObject);
begin
Close;
end;
procedure TKassForm.actPrintExecute(Sender: TObject);
var Wf:TWateForm;
period:string;
begin
Wf:=TWateForm.Create(Self);
Wf.cxLabel1.Caption:='';
Wf.cxLabel1.Caption:='Увага! Триває збір даних за рахунками! ';
Wf.Show;
Wf.Update;
DataSetWork.Close;
DataSetWork.SelectSQL.Clear;
DataSetWork.SelectSQL.Text:='select * from PC_KASS_DAY(:date_beg,:date_end,:id_reg)';
DataSetWork.Prepare;
DataSetWork.ParamByName('DATE_BEG').AsDateTime:=cxDateBeg.Date;
DataSetWork.ParamByName('DATE_END').AsDateTime:=cxDateEnd.Date;
DataSetWork.ParamByName('ID_REG').AsInteger:=ID_REG;
DataSetWork.CloseOpen(False);
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+ _PATH_REPORTS+ '\KasOtch.fr3');
period:='';
if cxDateBeg.Date=cxDateEnd.Date then period:= DatetoStr(cxDateBeg.Date)
else period:=' період з '+DateToStr(cxDateBeg.Date)+' по '+DateToStr(cxDateEnd.Date);
frxReport.Variables['PERIOD']:=''''+period+'''';
Wf.Free;
frxReport.PrepareReport;
if cxCopies.Value>1 then
frxReport.PrintOptions.Copies:=cxCopies.Value;
frxReport.PrintOptions.ShowDialog:=chbChoosePrinter.Checked;
frxReport.PrintOptions.ShowDialog:=True;
if cxCopies.Value>1 then
frxReport.PrintOptions.Copies:=cxCopies.Value;
frxReport.PrintOptions.ShowDialog:=chbChoosePrinter.Checked;
if chbPrinter.Checked then frxReport.Print
else frxReport.ShowReport;
if cxCheckEdit.Checked then frxReport.DesignReport;
end;
end.
|
program problem05;
uses crt;
(*
Problem: Smallest multiple
Problem 5
@Author: Chris M. Perez
@Date: 5/16/2017
*)
const
MAX: longint = 20;
function smallestMultiple(arg: longint): longint;
var
flag: boolean = true;
actualValue: longint = 20;
i: longint;
begin
while true do begin
for i := 1 to arg do begin
flag := true;
if actualValue mod i <> 0 then begin
flag := false;
break;
end;
end;
if flag then begin
break;
end;
actualValue := actualValue + 1;
end;
smallestMultiple := actualValue;
end;
var
result: longint = 0;
begin
result := smallestMultiple(MAX);
writeln(result);
readkey;
end.
|
unit descdac2B;
{Dans une version Beta, plusieurs paramètres integer étaient déclarés Smallint.
Pour pouvoir charger les fichiers data enregistrés pendant cette période, on déclare
le descripteur TDAC2DescriptorB}
interface
{$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF}
uses windows, Classes,SysUtils,
util1,dtf0,descac1,spk0,blocInf0,debug0,
stmDef;
{ un fichier DAC2 commence par typeHeaderDac2: le mot clé permet d'identifier le
type de fichier. TailleInfo donne la taille totale du bloc d'info qui précède les
données.
On trouve ensuite plusieurs sous-blocs qui commencent tous par un enregistrement
de type typeHeaderDac2 (id+taille).
Le premier bloc est appelé 'MAIN' et contient typeInfoDac2
Ensuite, on pourra trouver zéro plusieurs blocs. Par exemple, un bloc 'STIM'
et un bloc 'USER INFO' .
}
const
signatureDAC2='DAC2/GS/2000';
signatureDAC2Seq='DAC2SEQ';
signatureDAC2main='MAIN';
type
typeHeaderDac2B=object
id:string[15]; {garder 15 comme pour Acquis1}
tailleInfo:smallint;
procedure init(taille:integer);
procedure init2(ident:AnsiString;taille:integer);
procedure write(f:TfileStream);
end;
TAdcChannel=record
uY:string[10];
Dyu,Y0u:double;
end;
TextraInfoSeq=record
end;
typeInfoSeqDAC2B=
object
id:string[7]; {'DAC2SEQ'}
tailleInfo:smallint;
nbvoie:byte;
nbpt:integer;
tpData:typeTypeG;
postSeqI:integer;
uX:string[10];
Dxu,x0u:double;
adcChannel:array[1..16] of TAdcChannel;
extraInfo:TextraInfoSeq;
procedure init(nbvoie1:integer);
procedure write(f:TfileStream);
function seqSize:integer;
function dataSize:integer;
end;
typeInfoDAC2B=
object
id:string[15]; {garder 15 comme pour Acquis1}
tailleInfo:smallint;
nbvoie:byte;
nbpt:integer;
tpData:typeTypeG;
uX:string[10];
Dxu,x0u:double;
adcChannel:array[1..16] of TAdcChannel;
preseqI,postSeqI:smallint;
continu:boolean;
VariableEp:boolean;
WithTags:boolean;
procedure init(taille:integer);
procedure write( f:TfileStream);
procedure setInfoSeq(var infoSeq:typeInfoSeqDAC2B);
function controleOK:boolean;
end;
TDAC2DescriptorB=
class(TAC1Descriptor)
private
infoDac2:typeInfoDAC2B; { Bloc info brut tiré du fichier }
HeaderSize:integer;
protected
public
constructor create;override;
destructor destroy;override;
procedure readExtraInfo(f:TfileStream);
function initDF(st:AnsiString):boolean;
function init(st:AnsiString):boolean;override;
function nbvoie:integer;override;
function getData(voie,seq:integer;var evtMode:boolean):typeDataB;override;
function getTpNum(voie,seq:integer):typetypeG;override;
function getDataTag(voie,seq:integer):typeDataB;override;
function FichierContinu:boolean;override;
procedure displayInfo;override;
function unitX:AnsiString;override;
function unitY(num:integer):AnsiString;override;
function FileheaderSize:integer;
class function FileTypeName:AnsiString;override;
end;
implementation
{************************ Méthodes de TypeHeaderDAC2 ***********************}
procedure TypeHeaderDAC2B.init(taille:integer);
begin
fillchar(id,sizeof(id),0);
id:=signatureDAC2;
tailleInfo:=taille;
end;
procedure TypeHeaderDAC2B.init2(ident:AnsiString;taille:integer);
begin
fillchar(id,sizeof(id),0);
id:=ident;
tailleInfo:=taille;
end;
procedure TypeHeaderDAC2B.write(f:TfileStream);
begin
f.Write(self,sizeof(TypeHeaderDAC2B));
end;
{************************ Méthodes de TypeInfoDAC2 ***********************}
procedure TypeInfoDAC2B.init(taille:integer);
var
i:integer;
begin
fillchar(id,sizeof(id),0);
id:=signatureDac2Main;
tailleInfo:=taille;
nbvoie:=1;
nbpt:=1000;
uX:='';
Dxu:=1;
x0u:=0;
for i:=1 to 16 do
with adcChannel[i] do
begin
y0u:=0;
dyu:=1;
uy:='';
end;
continu:=false;
preseqI:=0;
postSeqI:=0;
tpData:=G_smallint;
end;
procedure TypeInfoDAC2B.write(f:TfileStream);
begin
f.Write(self,sizeof(TypeInfoDAC2B));
end;
procedure TypeInfoDAC2B.setInfoSeq(var infoSeq:typeInfoSeqDAC2B);
var
i:integer;
begin
infoSeq.init(nbvoie);
infoSeq.nbvoie:=nbvoie;
infoSeq.tpData:=tpData;
infoSeq.postSeqI:=postSeqI;
infoSeq.ux:=ux;
infoSeq.dxu:=dxu;
infoSeq.x0u:=x0u;
for i:=1 to nbvoie do
infoSeq.adcChannel[i]:=adcChannel[i];
end;
function typeInfoDac2B.controleOK:boolean;
var
i:integer;
begin
result:=false;
if (nbvoie<0) or (nbvoie>16) then
begin
messageCentral('Anomalous number of channels: '+Istr(nbvoie));
exit;
end;
if not (tpData in [G_smallint,G_single]) then
begin
messageCentral('Unrecognized number type '+Istr(byte(tpData)));
exit;
end;
if dxu<=0 then
begin
messageCentral('Anomalous X-scale parameters' );
exit;
end;
for i:=1 to nbvoie do
if adcChannel[i].Dyu=0 then
begin
messageCentral('Anomalous Y-scale parameters');
exit;
end;
result:=true;
end;
{******************** Méthodes de typeInfoSeqDAC2B *************************}
procedure typeInfoSeqDAC2B.init(nbvoie1:integer);
var
i:integer;
begin
id:=signatureDAC2Seq;
tailleInfo:=sizeof(typeInfoSeqDAC2B)-sizeof(TadcChannel)*(16-nbvoie1);
nbvoie:=nbvoie1;
nbpt:=1000;
uX:='';
Dxu:=1;
x0u:=0;
for i:=1 to 16 do
with adcChannel[i] do
begin
y0u:=0;
dyu:=1;
uy:='';
end;
postSeqI:=0;
tpData:=G_smallint;
end;
procedure typeInfoSeqDAC2B.write(f:TfileStream);
begin
f.Write(self,tailleInfo);
end;
function typeInfoSeqDAC2B.DataSize:integer;
begin
result:=nbpt*nbvoie*tailleTypeG[tpData];
end;
function typeInfoSeqDAC2B.seqSize:integer;
begin
result:=tailleInfo+dataSize+postSeqI;
end;
{****************** Méthodes de TDAC2DescriptorB ******************************}
constructor TDAC2DescriptorB.create;
begin
inherited;
end;
destructor TDAC2DescriptorB.destroy;
begin
inherited;
end;
procedure TDAC2DescriptorB.readExtraInfo( f:TfileStream);
var
header:TypeHeaderDAC2B;
p:integer;
res:intG;
userBlockSize:integer;
begin
while (f.Position<HeaderSize-1) do
begin
p:=f.Position;
f.read(header,sizeof(header));
if header.Id='USER INFO' then
begin
UserBlockSize:=header.tailleInfo-sizeof(header);
BlocFileInfo.free;
BlocFileInfo:=TblocInfo.create(UserBlockSize);
FileInfoOffset:=f.Position;
BlocFileInfo.read(f);
end
else exit;
end;
end;
{$O-}
function TDAC2DescriptorB.initDF(st:AnsiString):boolean;
var
res:intG;
i:integer;
f:TfileStream;
headerDac2:TypeHeaderDAC2B;
begin
initDF:=false;
stDat:=st;
f:=nil;
TRY
f:=TfileStream.create(stDat,fmOpenRead);
dateD:=FileGetDate(f.Handle);
{Identifier d'abord le fichier}
fillchar(headerDAc2,sizeof(headerDAc2),0);
f.read(headerDAc2,sizeof(headerDAc2));
if (headerDAc2.id<>signatureDAC2) then
begin
f.free;
exit;
end;
headerSize:=headerDac2.tailleInfo;
{Lire infoDac2}
fillchar(infoDAc2,sizeof(infoDAc2),0);
f.read(infoDAc2,sizeof(infoDAc2));
if (infoDAc2.id<>SignatureDAC2main) then
begin
f.free;
exit;
end;
{Controler le contenu de infoDac2}
if not infoDac2.controleOK then
begin
f.free;
exit;
end;
{en cas d'oubli, ajuster preseqI et postSeqI}
with infoDac2 do
if continu then
begin
preSeqI:=0;
postSeqI:=0;
end;
SampleSize:=tailleTypeG[infoDac2.tpData];
if infoDac2.continu
then nbptSeq0:=(f.size-headerSize) div (infoDac2.nbvoie*sampleSize)
else nbptSeq0:=infoDac2.nbpt;
longueurDat:=f.size-headerSize;
with infoDac2 do
tailleSeq:=preseqI+postSeqI+nbptSeq0*sampleSize*nbvoie;
if nbPtSeq0<>0
then nbSeqDat0:=(f.size-headerSize) div tailleSeq
else nbSeqDat0:=0;
readExtraInfo(f);
duree0:=infoDac2.dxu*nbPtSeq0;
BlocEpInfo.free;
BlocEpInfo:=TblocInfo.create(infoDac2.postSeqI);
result:=true;
f.free;
Except
f.free;
result:=false;
End;
{messageCentral('Dxu='+Estr(infoDac2.Dxu,6));}
end;
function TDAC2DescriptorB.init(st:AnsiString):boolean;
begin
Fdat:=initDF(st);
if Fdat then
begin
Fevt:=initEvt(ChangeFileExt(st,'.EVT'));
if Fevt then {cas de fichier DAT + fichier EVT }
begin
if nbSeqDat0<statEv.count then nbSeqDat0:=statEv.count;
if nbSeqDat0=0 then nbSeqDat0:=1;
end;
end
else
begin {cas de fichier EVT seul }
Fevt:=initEvt(st);
if FEvt then
begin
nbseqDat0:=statEv.count;
nbptSeq0:=0;
duree0:=statEv.dureeSeqSP;
end;
end;
init:=Fdat or Fevt;
end;
function TDAC2DescriptorB.getData(voie,seq:integer;var evtMode:boolean):typeDataB;
var
infoSeq:typeInfoSeqDAC2B;
res:intG;
f:TfileStream;
i:integer;
offsetS:integer;
data0:typeDataB;
begin
getData:=nil;
evtMode:=false;
if not Fdat or (voie<1) or (voie>nbvoie) or (seq>nbseqDat) then exit;
numSeqC:=seq;
with infoDac2 do
begin
offsetS:=headerSize+(seq-1)*tailleSeq;
f:=nil;
TRY
f:=TfileStream.create(stDat,fmOpenRead);
{lire et copier les info séquence dans infoDac2}
if not continu then
begin
f.Position:=offsetS;
fillchar(infoSeq,sizeof(infoSeq),0);
f.read(infoSeq,preSeqI);
infoDac2.uX:=infoSeq.ux;
infoDac2.Dxu:=infoSeq.Dxu;
infoDac2.X0u:=infoSeq.x0u;
for i:=1 to nbvoie do
infoDac2.adcChannel[i]:=infoSeq.adcChannel[i];
end
else preseqI:=0;
if ((voie=1) or (voie=0)) and (postSeqI<>0) then
begin
f.Position:=offsetS+tailleSeq-postSeqI;
BlocEpInfo.read(f);
end;
f.free;
Except
f.Free;
exit;
End;
if nbvoie=0 then exit;
offsetS:=offsetS+preseqI+sampleSize*(voie-1);
case Tpdata of
G_smallint: if withTags then
data0:=typedataFileIdigi.create
(stdat,offsetS,nbvoie,0,nbptSeq0-1,false,4)
else
data0:=typedataFileI.create
(stdat,offsetS,nbvoie,0,nbptSeq0-1,false);
G_single: data0:=typedataFileS.create
(stdat,offsetS,nbvoie,0,nbptSeq0-1,false);
end;
data0.setConversionX(Dxu,X0u);
data0.setConversionY(AdcChannel[voie].Dyu,AdcChannel[voie].Y0u);
end;
getData:=data0;
{messageCentral('Dxu='+Estr(infoDac2.Dxu,6)+' '+infoDac2.ux);}
end;
function TDAC2DescriptorB.getTpNum(voie,seq:integer):typetypeG;
begin
if Fdat then getTpNum:=infoDac2.tpdata
else getTpNum:=G_smallint;
end;
function TDAC2DescriptorB.getDataTag(voie,seq:integer):typeDataB;
var
res:intG;
f:file;
i:integer;
offsetS:integer;
data0:typeDataB;
begin
getDataTag:=nil;
if not Fdat or (voie<1) or (voie>2) or (seq>nbseqDat) or not infoDAc2.withTags
then exit;
numSeqC:=seq;
with infoDac2 do
begin
if nbvoie=0 then exit;
offsetS:=headerSize+(seq-1)*tailleSeq+preseqI;
data0:=typedataFileDigiTag.create
(stdat,offsetS,nbvoie,0,nbptSeq0-1,false,voie) ;
data0.setConversionX(Dxu,X0u);
end;
getDataTag:=data0;
end;
function TDAC2DescriptorB.nbVoie:integer;
begin
if Fdat then nbvoie:=infoDac2.nbvoie
else nbvoie:=0;
end;
function TDAC2DescriptorB.FichierContinu:boolean;
begin
FichierContinu:=Fdat and infoDac2.continu;
end;
procedure TDAC2DescriptorB.displayInfo;
var
BoiteInfo:typeBoiteInfo;
i,j:integer;
begin
with BoiteInfo do
begin
BoiteInfo.init('File Informations');
writeln(ExtractFileName(stDat)+' '+Udate(DateD)+' '+Utime(DateD) );
writeln('Format: DAC2 version B');
writeln('Header size: '+Istr(infoDac2.tailleInfo));
writeln('Episode header size: '+Istr(infoDac2.preseqI));
writeln('Episode info size: '+Istr(infoDac2.postSeqI));
if Fdat then
begin
write(Istr(nbVoie)+' channel');
if nbvoie>1 then write('s ') else write(' ');;
if not FichierContinu then
begin
writeln(' '+Istr(nbPtSeq0)+' samples/channel' );
writeln('Episode duration:'+Estr1(Duree0,10,3)+' '+infoDac2.uX);
write(Istr(nbSeqDat)+' episode');
if nbSeqDat>1 then writeln('s') else writeln('');
end
else
begin
writeln(' Continuous file');
writeln('Duration: '+Estr1(Duree0,10,3)+' '+infoDac2.uX);
writeln('Sampling interval per channel:'+Estr1(infoDac2.Dxu,10,6)+' '+infoDac2.uX);
end;
writeln('File info block size='+Istr(BlocFileInfo.tailleBuf));
writeln('Episode info block size='+Istr(infoDac2.postSeqI));
end;
if assigned(statEv) then
begin
writeln('');
writeln(' Numbers of events');
for i:=0 to 3 do
begin
for j:=1 to 4 do
write(Jgauche('E'+Istr(i*4+j)+':',5)
+Istr1(statEV.ntot[i*4+j-1],5)+' ');
writeln('');
end;
end;
done;
end;
end;
function TDAC2DescriptorB.unitX:AnsiString;
begin
if Fdat
then unitX:=infoDac2.ux
else unitX:=statEv.unitXSP;
end;
function TDAC2DescriptorB.unitY(num:integer):AnsiString;
begin
if Fdat
then unitY:=infoDac2.adcChannel[num].uy
else unitY:='';
end;
function TDAC2DescriptorB.FileheaderSize:integer;
begin
FileheaderSize:=HeaderSize;
end;
class function TDAC2DescriptorB.FileTypeName: AnsiString;
begin
result:='DAC2 beta';
end;
end.
|
unit GLDCamera;
interface
uses
Classes, GL, GLDTypes, GLDConst, GLDClasses, GLDObjects;
type
TGLDCamera = class;
TGLDPerspectiveCamera = class;
TGLDSideCamera = class;
TGLDFrontCamera = class;
TGLDBackCamera = class;
TGLDLeftCamera = class;
TGLDRightCamera = class;
TGLDTopCamera = class;
TGLDBottomCamera = class;
TGLDUserCamera = class;
TGLDCameraSystem = class;
TGLDUserCameraList = class;
TGLDCamera = class(TGLDVisualObject)
protected
procedure DoRender; override;
procedure SimpleRender; override;
public
procedure ApplyProjection; virtual; abstract;
procedure ApplyModelview; virtual; abstract;
procedure Apply; virtual;
procedure Reset; virtual;
class function SysClassType: TGLDSysClassType; override;
class function VisualObjectClassType: TGLDVisualObjectClass; override;
end;
TGLDPerspectiveCamera = class(TGLDCamera)
private
FZoom: GLfloat;
FRotation: TGLDRotation3DClass;
FOffset: TGLDVector4fClass;
procedure SetZoom(Value: GLfloat);
procedure SetRotation(Value: TGLDRotation3DClass);
procedure SetOffset(Value: TGLDVector4fClass);
function GetParams: TGLDPerspectiveCameraParams;
procedure SetParams(Value: TGLDPerspectiveCameraParams);
protected
procedure SetOnChange(Value: TNotifyEvent); override;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure ApplyProjection; override;
procedure ApplyModelview; override;
procedure Reset; override;
procedure Pan(const X, Y: GLint);
procedure ZoomD(const Delta: GLfloat);
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
class function SysClassType: TGLDSysClassType; override;
class function VisualObjectClassType: TGLDVisualObjectClass; override;
property Params: TGLDPerspectiveCameraParams read GetParams write SetParams;
published
property Zoom: GLfloat read FZoom write SetZoom;
property Rotation: TGLDRotation3DClass read FRotation write SetRotation;
property Offset: TGLDVector4fClass read FOffset write SetOffset;
end;
TGLDSideCamera = class(TGLDCamera)
private
FZoom: GLFloat;
FOffset: TGLDVector4fClass;
procedure SetZoom(Value: GLfloat);
procedure SetOffset(Value: TGLDVector4fClass);
function GetParams: TGLDSideCameraParams;
procedure SetParams(Value: TGLDSideCameraParams);
protected
procedure SetOnChange(Value: TNotifyEvent); override;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure ApplyProjection; override;
procedure ApplyModelview; override;
procedure Reset; override;
procedure Pan(const X, Y: GLint);
procedure ZoomD(const Delta: GLfloat);
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
class function SysClassType: TGLDSysClassType; override;
class function VisualObjectClassType: TGLDVisualObjectClass; override;
class function Rotation: TGLDRotation3D; virtual; abstract;
property Params: TGLDSideCameraParams read GetParams write SetParams;
published
property Zoom: GLfloat read FZoom write SetZoom;
property Offset: TGLDVector4fClass read FOffset write SetOffset;
end;
TGLDFrontCamera = class(TGLDSideCamera)
public
constructor Create(AOwner: TPersistent); override;
class function SysClassType: TGLDSysClassType; override;
class function VisualObjectClassType: TGLDVisualObjectClass; override;
class function Rotation: TGLDRotation3D; override;
end;
TGLDBackCamera = class(TGLDSideCamera)
public
constructor Create(AOwner: TPersistent); override;
class function SysClassType: TGLDSysClassType; override;
class function VisualObjectClassType: TGLDVisualObjectClass; override;
class function Rotation: TGLDRotation3D; override;
end;
TGLDLeftCamera = class(TGLDSideCamera)
public
constructor Create(AOwner: TPersistent); override;
class function SysClassType: TGLDSysClassType; override;
class function VisualObjectClassType: TGLDVisualObjectClass; override;
class function Rotation: TGLDRotation3D; override;
end;
TGLDRightCamera = class(TGLDSideCamera)
public
constructor Create(AOwner: TPersistent); override;
class function SysClassType: TGLDSysClassType; override;
class function VisualObjectClassType: TGLDVisualObjectClass; override;
class function Rotation: TGLDRotation3D; override;
end;
TGLDTopCamera = class(TGLDSideCamera)
public
constructor Create(AOwner: TPersistent); override;
class function SysClassType: TGLDSysClassType; override;
class function VisualObjectClassType: TGLDVisualObjectClass; override;
class function Rotation: TGLDRotation3D; override;
end;
TGLDBottomCamera = class(TGLDSideCamera)
public
constructor Create(AOwner: TPersistent); override;
class function SysClassType: TGLDSysClassType; override;
class function VisualObjectClassType: TGLDVisualObjectClass; override;
class function Rotation: TGLDRotation3D; override;
end;
TGLDUserCamera = class(TGLDCamera)
private
FTarget: TGLDVector4fClass;
FRotation: TGLDRotation3DClass;
FPosition: TGLDVector4fClass;
FZNear: GLfloat;
FZFar: GLfloat;
FProjectionMode: TGLDProjectionMode;
FZoom: GLfloat;
FFov: GLfloat;
FAspect: GLfloat;
FSelected: GLboolean;
FTargetSelected: GLboolean;
procedure SetTarget(Value: TGLDVector4fClass);
procedure SetRotation(Value: TGLDRotation3DClass);
procedure SetZNear(Value: GLfloat);
procedure SetZFar(Value: GLfloat);
procedure SetProjectionMode(Value: TGLDProjectionMode);
procedure SetZoom(Value: GLfloat);
procedure SetFov(Value: GLfloat);
procedure SetAspect(Value: GLfloat);
procedure SetSelected(Value: GLboolean);
procedure SetTargetSelected(Value: GLboolean);
function GetParams: TGLDUserCameraParams;
procedure SetParams(Value: TGLDUserCameraParams);
class function GetColor: TGLDColor4fClass;
class procedure SetColor(Value: TGLDColor4fClass);
class function GetTargetColor: TGLDColor4fClass;
class procedure SetTargetColor(Value: TGLDColor4fClass);
class function GetLineColor: TGLDColor4fClass;
class procedure SetLineColor(Value: TGLDColor4fClass);
function GetPosition: TGLDVector4fClass;
procedure SetPosition(Value: TGLDVector4fClass);
procedure PositionChanged(Sender: TObject);
protected
function Scale: GLfloat;
procedure DrawCamera(S: GLfloat);
procedure DrawTarget(S: GLfloat);
procedure DrawLine;
procedure DoRender; override;
procedure SimpleRender; override;
procedure SetOnChange(Value: TNotifyEvent); override;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure Render; override;
procedure RenderEdges; override;
procedure RenderWireframe; override;
procedure RenderBoundingBox; override;
procedure RenderForSelection(Idx: GLuint); override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
class function SysClassType: TGLDSysClassType; override;
class function VisualObjectClassType: TGLDVisualObjectClass; override;
procedure ApplyProjection; override;
procedure ApplyModelview; override;
procedure SetAspectFromViewport(const Viewport: TGLDViewport);
procedure SetAspectFromCurrentViewport;
procedure ZoomD(const Delta: GLfloat);
procedure MoveSelectedParts(const Vector: TGLDVector3f);
function ListIndex: GLuint;
property Params: TGLDUserCameraParams read GetParams write SetParams;
published
property Target: TGLDVector4fClass read FTarget write SetTarget;
property Rotation: TGLDRotation3DClass read FRotation write SetRotation;
property Position: TGLDVector4fClass read GetPosition write SetPosition stored False;
property ZNear: GLfloat read FZNear write SetZNear;
property ZFar: GLfloat read FZFar write SetZFar;
property ProjectionMode: TGLDProjectionMode read FProjectionMode write SetProjectionMode default GLD_USERCAMERA_PROJECTIONMODE_DEFAULT;
property Zoom: GLfloat read FZoom write SetZoom;
property Radius: GLfloat read FZoom write SetZoom;
property Fov: GLfloat read FFov write SetFov;
property Aspect: GLfloat read FAspect write SetAspect;
property Selected: GLboolean read FSelected write SetSelected default False;
property TargetSelected: GLboolean read FTargetSelected write SetTargetSelected default False;
property Color: TGLDColor4fClass read GetColor write SetColor;
property TargetColor: TGLDColor4fClass read GetTargetColor write SetTargetColor;
property LineColor: TGLDColor4fClass read GetLineColor write SetLineColor;
end;
PGLDUserCameraArray = ^TGLDUserCameraArray;
TGLDUserCameraArray = array[1..GLD_MAX_LISTITEMS] of TGLDUserCamera;
PGLDUsedCamera = ^TGLDUsedCamera;
TGLDUsedCamera =
(GLD_UC_PERSPECTIVE,
GLD_UC_FRONT,
GLD_UC_BACK,
GLD_UC_LEFT,
GLD_UC_RIGHT,
GLD_UC_TOP,
GLD_UC_BOTTOM,
GLD_UC_USER);
TGLDCameraSystem = class(TGLDSysClass)
private
FUsedCamera: TGLDUsedCamera;
FPerspectiveCamera: TGLDPerspectiveCamera;
FFrontCamera: TGLDFrontCamera;
FBackCamera: TGLDBackCamera;
FLeftCamera: TGLDLeftCamera;
FRightCamera: TGLDRightCamera;
FTopCamera: TGLDTopCamera;
FBottomCamera: TGLDBottomCamera;
FUserCamera: TGLDUserCamera;
procedure SetUsedCamera(Value: TGLDUsedCamera);
procedure SetPerspectiveCamera(Value: TGLDPerspectiveCamera);
procedure SetFrontCamera(Value: TGLDFrontCamera);
procedure SetBackCamera(Value: TGLDBackCamera);
procedure SetLeftCamera(Value: TGLDLeftCamera);
procedure SetRightCamera(Value: TGLDRightCamera);
procedure SetTopCamera(Value: TGLDTopCamera);
procedure SetBottomCamera(Value: TGLDBottomCamera);
procedure SetUserCamera(Value: TGLDUserCamera);
function GetRotation: TGLDRotation3DClass;
protected
procedure SetOnChange(Value: TNotifyEvent); override;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure Apply;
procedure Reset;
procedure Pan(const X, Y: GLint);
procedure Zoom(const Delta: GLfloat);
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
class function SysClassType: TGLDSysClassType; override;
property Rotation: TGLDRotation3DClass read GetRotation;
published
property UsedCamera: TGLDUsedCamera read FUsedCamera write SetUsedCamera default GLD_UC_PERSPECTIVE;
property PerspectiveCamera: TGLDPerspectiveCamera read FPerspectiveCamera write SetPerspectiveCamera;
property FrontCamera: TGLDFrontCamera read FFrontCamera write SetFrontCamera;
property BackCamera: TGLDBackCamera read FBackCamera write SetBackCamera;
property LeftCamera: TGLDLeftCamera read FLeftCamera write SetLeftCamera;
property RightCamera: TGLDRightCamera read FRightCamera write SetRightCamera;
property TopCamera: TGLDTopCamera read FTopCamera write SetTopCamera;
property BottomCamera: TGLDBottomCamera read FBottomCamera write SetBottomCamera;
property UserCamera: TGLDUserCamera read FUserCamera write SetUserCamera stored False;
end;
TGLDUserCameraList = class(TGLDSysClass)
private
FCapacity: GLuint;
FCount: GLuint;
FList: PGLDUserCameraArray;
procedure SetCapacity(NewCapacity: GLuint);
procedure SetCount(NewCount: GLuint);
function GetCamera(Index: GLuint): TGLDUserCamera;
procedure SetCamera(Index: GLuint; Camera: TGLDUserCamera);
function GetLast: TGLDUserCamera;
procedure SetLast(Camera: TGLDUserCamera);
protected
procedure SetOnChange(Value: TNotifyEvent); override;
procedure DefineProperties(Filer: TFiler); override;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure Render; overload;
procedure Render(Index: GLuint); overload;
procedure RenderWireframe; overload;
procedure RenderWireframe(Index: GLuint); overload;
procedure RenderForSelection(Offset: GLuint); overload;
procedure RenderForSelection(Index: GLuint; Offset: GLuint); overload;
procedure Select(Offset, Index: GLuint);
procedure SelectAllCameras;
procedure SelectAllTargets;
procedure SelectAll;
procedure AddSelection(Offset, Index: GLuint);
procedure DeleteSelections;
procedure InvertSelections;
procedure DeleteSelectedCameras;
procedure CopySelectedCamerasTo(CamList: TGLDUserCameraList);
procedure PasteCamerasFrom(CamList: TGLDUserCameraList);
function SelectionCount: GLuint;
function CameraSelectionCount: GLuint;
function FirstSelectedCamera: TGLDUserCamera;
function CenterOfSelectedObjects: TGLDVector3f;
function AverageOfRotations: TGLDRotation3D;
procedure MoveSelectedObjects(const Vector: TGLDVector3f);
procedure RotateSelectedObjects(const ARotation: TGLDRotation3D);
procedure Clear;
function CreateNew: GLuint;
function Add(Camera: TGLDUserCamera): GLuint; overload;
function Add(AParams: TGLDUserCameraParams): GLuint; overload;
function Delete(Index: GLuint): GLuint; overload;
function Delete(Camera: TGLDUserCamera): GLuint; overload;
function IndexOf(Camera: TGLDUserCamera): GLuint;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
class function SysClassType: TGLDSysClassType; override;
property Capacity: GLuint read FCapacity write SetCapacity;
property Count: GLuint read FCount write SetCount;
property List: PGLDUserCameraArray read FList;
property Items[index: GLuint]: TGLDUserCamera read GetCamera write SetCamera;
property Cameras[index: GLuint]: TGLDUserCamera read GetCamera write SetCamera; default;
property Last: TGLDUserCamera read GetLast write SetLast;
end;
function GLDGetStandardCamera: TGLDUserCamera;
procedure GLDReleaseStandardCamera;
const
GLD_USERCAMERA_STD_COLOR: TGLDColor4f = (R: 0.02; G: 0.20; B: 0.70);
GLD_USERCAMERA_TARGET_STD_COLOR: TGLDColor4f = (R: 0.02; G: 0.20; B: 0.70);
GLD_USERCAMERA_LINE_STD_COLOR: TGLDColor4f = (R: 0.60; G: 0.80; B: 0.90);
implementation
uses
GLDMain, SysUtils, GLDX, GLDSystem, GLDRepository;
var
vCameraCounter: GLuint = 0;
vStandardCamera: TGLDUserCamera = nil;
vUserCameraColor: TGLDColor4fClass = nil;
vUserCameraTargetColor: TGLDColor4fClass = nil;
vUserCameraLineColor: TGLDColor4fClass = nil;
function GLDGetStandardCamera: TGLDUserCamera;
begin
if not Assigned(vStandardCamera) then
begin
vStandardCamera := TGLDUserCamera.Create(nil);
vStandardCamera.FName := GLD_STANDARD_STR + GLD_CAMERA_STR;
Dec(vCameraCounter);
end;
Result := vStandardCamera;
end;
procedure GLDReleaseStandardCamera;
begin
if Assigned(vStandardCamera) then
vStandardCamera.Free;
vStandardCamera := nil;
end;
function GLDGetUserCameraColor: TGLDColor4fClass;
begin
if not Assigned(vUserCameraColor) then
vUserCameraColor := TGLDColor4fClass.Create(nil, GLD_USERCAMERA_STD_COLOR);
Result := vUserCameraColor;
end;
procedure GLDSetUserCameraColor(Value: TGLDColor4fClass);
begin
GLDGetUserCameraColor.Assign(Value);
end;
procedure GLDReleaseUserCameraColor;
begin
if not Assigned(vUserCameraColor) then Exit;
vUserCameraColor.Free;
vUserCameraColor := nil;
end;
function GLDGetUserCameraTargetColor: TGLDColor4fClass;
begin
if not Assigned(vUserCameraTargetColor) then
vUserCameraTargetColor := TGLDColor4fClass.Create(nil, GLD_USERCAMERA_TARGET_STD_COLOR);
Result := vUserCameraTargetColor;
end;
procedure GLDSetUserCameraTargetColor(Value: TGLDColor4fClass);
begin
GLDGetUserCameraTargetColor.Assign(Value);
end;
procedure GLDReleaseUserCameraTargetColor;
begin
if not Assigned(vUserCameraTargetColor) then Exit;
vUserCameraTargetColor.Free;
vUserCameraTargetColor := nil;
end;
function GLDGetUserCameraLineColor: TGLDColor4fClass;
begin
if not Assigned(vUserCameraLineColor) then
vUserCameraLineColor := TGLDColor4fClass.Create(nil, GLD_USERCAMERA_LINE_STD_COLOR);
Result := vUserCameraLineColor;
end;
procedure GLDSetUserCameraLineColor(Value: TGLDColor4fClass);
begin
GLDGetUserCameraLineColor.Assign(Value);
end;
procedure GLDReleaseUserCameraLineColor;
begin
if not Assigned(vUserCameraLineColor) then Exit;
vUserCameraLineColor.Free;
vUserCameraLineColor := nil;
end;
procedure TGLDCamera.Apply;
begin
ApplyProjection;
ApplyModelview;
end;
procedure TGLDCamera.DoRender;
begin
end;
procedure TGLDCamera.SimpleRender;
begin
DoRender;
end;
procedure TGLDCamera.Reset;
begin
end;
class function TGLDCamera.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_CAMERA;
end;
class function TGLDCamera.VisualObjectClassType: TGLDVisualObjectClass;
begin
Result := TGLDCamera;
end;
constructor TGLDPerspectiveCamera.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FZoom := 7;
FRotation := TGLDRotation3DClass.Create(Self);
FOffset := TGLDVector4fClass.Create(Self);
FName := GLD_PERSPECTIVECAMERA_STR;
end;
destructor TGLDPerspectiveCamera.Destroy;
begin
FRotation.Free;
FOffset.Free;
inherited Destroy;
end;
procedure TGLDPerspectiveCamera.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLDPerspectiveCamera) then Exit;
FZoom := TGLDPerspectiveCamera(Source).FZoom;
PGLDRotation3D(FRotation.GetPointer)^ := TGLDPerspectiveCamera(Source).FRotation.Params;
PGLDVector3f(FOffset.GetPointer)^ := TGLDPerspectiveCamera(Source).FOffset.Vector3f;
end;
procedure TGLDPerspectiveCamera.ApplyProjection;
var
Viewport: TGLDViewport;
begin
Viewport := GLDXGetViewport;
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
with Viewport do
if Height = 0 then
gluPerspective(45.0, 0, 0.1, 100)
else gluPerspective(45.0, Width / Height, 0.1, 100.0);
end;
procedure TGLDPerspectiveCamera.ApplyModelview;
begin
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
glTranslatef(0, 0, -FZoom);
FRotation.ApplyAsRotationZXY;
FOffset.ApplyAsTranslation;
end;
procedure TGLDPerspectiveCamera.Reset;
begin
FZoom := 7;
PGLDVector4f(FOffset.GetPointer)^ := GLD_VECTOR4F_IDENTITY;
PGLDRotation3D(FRotation.GetPointer)^ := GLDXRotation3D(45, 45, 0);
Change;
end;
procedure TGLDPerspectiveCamera.Pan(const X, Y: GLint);
var
Viewport: TGLDViewport;
O, T: TGLDVector3f;
begin
Viewport := GLDXGetViewport;
O := GLDXUnProject(GLDXVector3f(Viewport.Width / 2, Viewport.Height / 2, -1));
T := FOffset.Vector3f;
if X <> 0 then
begin
T := GLDXVectorSub(T, GLDXVectorScalar(GLDXVectorNormalize(
GLDXVectorSub(O, GLDXUnProject(GLDXVector3f(Viewport.Width / 2 + 10, Viewport.Height / 2, -1)))), 0.005 * X));
end;
if Y <> 0 then
begin
T := GLDXVectorAdd(T, GLDXVectorScalar(GLDXVectorNormalize(
GLDXVectorSub(O, GLDXUnProject(GLDXVector3f(Viewport.Width / 2, Viewport.Height / 2 - 10, -1)))), 0.005 * Y));
end;
FOffset.Vector3f := T;
end;
procedure TGLDPerspectiveCamera.ZoomD(const Delta: GLfloat);
begin
if Delta = 0 then Exit;
FZoom := FZoom + Delta;
Change;
end;
procedure TGLDPerspectiveCamera.LoadFromStream(Stream: TStream);
begin
Stream.Read(FZoom, SizeOf(GLfloat));
FRotation.LoadFromStream(Stream);
Stream.Read(FOffset.GetPointer^, SizeOf(TGLDVector3f));
end;
procedure TGLDPerspectiveCamera.SaveToStream(Stream: TStream);
begin
Stream.Write(FZoom, SizeOf(GLfloat));
FRotation.SaveToStream(Stream);
Stream.Write(FOffset.GetPointer^, SizeOf(TGLDVector3f));
end;
class function TGLDPerspectiveCamera.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_PERSPECTIVECAMERA;
end;
class function TGLDPerspectiveCamera.VisualObjectClassType: TGLDVisualObjectClass;
begin
Result := TGLDPerspectiveCamera;
end;
procedure TGLDPerspectiveCamera.SetOnChange(Value: TNotifyEvent);
begin
inherited SetOnChange(Value);
FRotation.OnChange := FOnChange;
FOffset.OnChange := FOnChange;
end;
procedure TGLDPerspectiveCamera.SetZoom(Value: GLfloat);
begin
if FZoom = Value then Exit;
FZoom := Value;
Change;
end;
procedure TGLDPerspectiveCamera.SetRotation(Value: TGLDRotation3DClass);
begin
if Assigned(Value) then
FRotation.Params := Value.Params;
end;
procedure TGLDPerspectiveCamera.SetOffset(Value: TGLDVector4fClass);
begin
if Assigned(Value) then
FOffset.Vector4f := Value.Vector4f;
end;
function TGLDPerspectiveCamera.GetParams: TGLDPerspectiveCameraParams;
begin
Result := GLDXPerspectiveCameraParams(FZoom,
FRotation.Params, FOffset.Vector3f);
end;
procedure TGLDPerspectiveCamera.SetParams(Value: TGLDPerspectiveCameraParams);
begin
if GLDXPerspectiveCameraParamsEqual(GetParams, Value) then Exit;
FZoom := Value.Zoom;
PGLDRotation3D(FRotation.GetPointer)^ := Value.Rotation;
PGLDVector3f(FOffset.GetPointer)^ := Value.Offset;
Change;
end;
constructor TGLDSideCamera.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FZoom := 6;
FOffset := TGLDVector4fClass.Create(Self);
FName := GLD_SIDECAMERA_STR;
end;
destructor TGLDSideCamera.Destroy;
begin
FOffset.Free;
inherited Destroy;
end;
procedure TGLDSideCamera.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLDSideCamera) then Exit;
SetParams(TGLDSideCamera(Source).GetParams);
end;
procedure TGLDSideCamera.ApplyProjection;
var
Viewport: TGLDViewport;
Z2, Aspect: GLfloat;
begin
Viewport := GLDXGetViewport;
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
with Viewport do
begin
Z2 := FZoom / 2;
if Height <> 0 then
begin
Aspect := Width / Height;
glOrtho(-Z2, Z2, -Z2 / Aspect, Z2 / Aspect, 0.1, 100)
end else glOrtho(Z2, Z2, 0, 0, 0.1, 100);
end;
end;
procedure TGLDSideCamera.ApplyModelview;
begin
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
glTranslatef(0, 0, -6);
TGLDRotation3DClass.ApplyRotationZXY(Rotation);
FOffset.ApplyAsTranslation;
end;
procedure TGLDSideCamera.Reset;
begin
FZoom := 6;
PGLDVector4f(FOffset.GetPointer)^ := GLD_VECTOR4F_IDENTITY;
Change;
end;
procedure TGLDSideCamera.Pan(const X, Y: GLint);
var
Viewport: TGLDViewport;
begin
Viewport := GLDXGetViewport;
FOffset.Vector3f := GLDXVectorAdd(FOffset.Vector3f, GLDXVectorSub(
GLDXUnProject(GLDXVector3f((Viewport.Width div 2) + X, (Viewport.Height div 2) + Y, -1)),
GLDXUnProject(GLDXVector3f((Viewport.Width div 2), (Viewport.Height div 2), -1))));
end;
procedure TGLDSideCamera.ZoomD(const Delta: GLfloat);
begin
if Delta = 0 then Exit;
FZoom := FZoom + Delta;
Change;
end;
procedure TGLDSideCamera.LoadFromStream(Stream: TStream);
begin
Stream.Read(FZoom, SizeOf(GLfloat));
Stream.Read(FOffset.GetPointer^, SizeOf(TGLDVector3f));
end;
procedure TGLDSideCamera.SaveToStream(Stream: TStream);
begin
Stream.Write(FZoom, SizeOf(GLfloat));
Stream.Write(FOffset.GetPointer^, SizeOf(TGLDVector3f));
end;
class function TGLDSideCamera.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_SIDECAMERA;
end;
class function TGLDSideCamera.VisualObjectClassType: TGLDVisualObjectClass;
begin
Result := TGLDSideCamera;
end;
procedure TGLDSideCamera.SetOnChange(Value: TNotifyEvent);
begin
inherited SetOnChange(Value);
FOffset.OnChange := FOnChange;
end;
procedure TGLDSideCamera.SetZoom(Value: GLfloat);
begin
if FZoom = Value then Exit;
FZoom := Value;
Change;
end;
procedure TGLDSideCamera.SetOffset(Value: TGLDVector4fClass);
begin
FOffset.Assign(Value);
end;
function TGLDSideCamera.GetParams: TGLDSideCameraParams;
begin
Result := GLDXSideCameraParams(FZoom, FOffset.Vector3f);
end;
procedure TGLDSideCamera.SetParams(Value: TGLDSideCameraParams);
begin
if GLDXSideCameraParamsEqual(GetParams, Value) then Exit;
FZoom := Value.Zoom;
PGLDVector3f(FOffset.GetPointer)^ := Value.Offset;
Change;
end;
constructor TGLDFrontCamera.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FName := GLD_FRONTCAMERA_STR;
end;
class function TGLDFrontCamera.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_FRONTCAMERA;
end;
class function TGLDFrontCamera.VisualObjectClassType: TGLDVisualObjectClass;
begin
Result := TGLDFrontCamera;
end;
class function TGLDFrontCamera.Rotation: TGLDRotation3D;
begin
Result := GLD_FRONTCAMERA_ROTATION;
end;
constructor TGLDBackCamera.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FName := GLD_BACKCAMERA_STR;
end;
class function TGLDBackCamera.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_BACKCAMERA;
end;
class function TGLDBackCamera.VisualObjectClassType: TGLDVisualObjectClass;
begin
Result := TGLDBackCamera;
end;
class function TGLDBackCamera.Rotation: TGLDRotation3D;
begin
Result := GLD_BACKCAMERA_ROTATION;
end;
constructor TGLDLeftCamera.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FName := GLD_LEFTCAMERA_STR;
end;
class function TGLDLeftCamera.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_LEFTCAMERA;
end;
class function TGLDLeftCamera.VisualObjectClassType: TGLDVisualObjectClass;
begin
Result := TGLDLeftCamera;
end;
class function TGLDLeftCamera.Rotation: TGLDRotation3D;
begin
Result := GLD_LEFTCAMERA_ROTATION;
end;
constructor TGLDRightCamera.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FName := GLD_RIGHTCAMERA_STR;
end;
class function TGLDRightCamera.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_RIGHTCAMERA;
end;
class function TGLDRightCamera.VisualObjectClassType: TGLDVisualObjectClass;
begin
Result := TGLDRightCamera;
end;
class function TGLDRightCamera.Rotation: TGLDRotation3D;
begin
Result := GLD_RIGHTCAMERA_ROTATION;
end;
constructor TGLDTopCamera.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FName := GLD_TOPCAMERA_STR;
end;
class function TGLDTopCamera.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_TOPCAMERA;
end;
class function TGLDTopCamera.VisualObjectClassType: TGLDVisualObjectClass;
begin
Result := TGLDTopCamera;
end;
class function TGLDTopCamera.Rotation: TGLDRotation3D;
begin
Result := GLD_TOPCAMERA_ROTATION;
end;
constructor TGLDBottomCamera.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FName := GLD_BOTTOMCAMERA_STR;
end;
class function TGLDBottomCamera.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_BOTTOMCAMERA;
end;
class function TGLDBottomCamera.VisualObjectClassType: TGLDVisualObjectClass;
begin
Result := TGLDBottomCamera;
end;
class function TGLDBottomCamera.Rotation: TGLDRotation3D;
begin
Result := GLD_BOTTOMCAMERA_ROTATION;
end;
constructor TGLDUserCamera.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FTarget := TGLDVector4fClass.Create(Self);
FTarget.Vector3f := GLD_USERCAMERA_TARGET_DEFAULT;
FTarget.OnChange := PositionChanged;
FRotation := TGLDRotation3DClass.Create(Self);
FRotation.Params := GLD_USERCAMERA_ROTATION_DEFAULT;
FPosition := TGLDVector4fClass.Create(Self);
FPosition.OnChange := PositionChanged;
FZNear := GLD_USERCAMERA_ZNEAR_DEFAULT;
FZFar := GLD_USERCAMERA_ZFAR_DEFAULT;
FProjectionMode := GLD_USERCAMERA_PROJECTIONMODE_DEFAULT;
FZoom := GLD_USERCAMERA_ZOOM_DEFAULT;
FFov := GLD_USERCAMERA_FOV_DEFAULT;
FAspect := GLD_USERCAMERA_ASPECT_DEFAULT;
Inc(vCameraCounter);
FName := GLD_CAMERA_STR + IntToStr(vCameraCounter);
end;
destructor TGLDUserCamera.Destroy;
begin
FTarget.Free;
FRotation.Free;
FPosition.Free;
inherited Destroy;
end;
procedure TGLDUserCamera.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLDUserCamera) then Exit;
SetParams(TGLDUserCamera(Source).GetParams);
end;
var
vAppliedUserCamera: TGLDUserCamera = nil;
procedure TGLDUserCamera.Render;
begin
RenderWireframe;
end;
procedure TGLDUserCamera.RenderEdges;
begin
RenderWireframe;
end;
procedure TGLDUserCamera.RenderWireframe;
var
S: GLfloat;
begin
if not FVisible then Exit;
if vAppliedUserCamera = Self then Exit;
glPushAttrib(GL_LIGHTING_BIT or GL_POLYGON_BIT or GL_DEPTH_BUFFER_BIT);
glDisable(GL_LIGHTING);
glDisable(GL_CULL_FACE);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glDisable(GL_DEPTH_TEST);
glDepthMask(False);
S := Scale;
if not FSelected then
glColor3fv(GLDGetUserCameraColor.GetPointer)
else glColor3fv(@GLD_COLOR3F_WHITE);
DrawCamera(S);
if not FTargetSelected then
glColor4fv(GLDGetUserCameraTargetColor.GetPointer)
else glColor3fv(@GLD_COLOR3F_WHITE);
DrawTarget(S);
glColor3fv(GLDGetUserCameraLineColor.GetPointer);
DrawLine;
glPopAttrib;
end;
procedure TGLDUserCamera.RenderBoundingBox;
begin
RenderWireframe;
end;
procedure TGLDUserCamera.RenderForSelection(Idx: GLuint);
var
Color: TGLDColor3ub;
S: GLfloat;
begin
if not FVisible then Exit;
if vAppliedUserCamera = Self then Exit;
Color := GLDXColor3ub(Longint(Idx));
glColor3ubv(@Color);
S := Scale;
DrawCamera(S);
Color := GLDXColor3ub(Longint(Idx + 1));
glColor3ubv(@Color);
DrawTarget(S);
end;
function TGLDUserCamera.Scale: GLfloat;
var
Viewport: TGLDViewport;
ModelviewMatrix: TGLDMatrixf;
V1, V2, V3: TGLDVector3f;
F: GLfloat;
begin
Viewport := GLDXGetViewport;
ModelviewMatrix := GLDXGetModelviewMatrix;
with Viewport do
begin
V1 := GLDXUnProject(GLDXVector3f(X + (Width / 2) - 50, Y + (Height / 2), -1));
V2 := GLDXUnProject(GLDXVector3f(X + (Width / 2) + 50, Y + (Height / 2), -1));
end;
if ((V1.X = V2.X) and (V1.Y = V2.Y)) or
((V1.X = V2.X) and (V1.Z = V2.Z)) or
((V1.Y = V2.Y) and (V1.Z = V2.Z)) then
begin
V3 := GLDXVectorSub(V2, V1);
F := Abs(GLDXVectorLength(V3));
end else F := Abs(ModelviewMatrix._43 / -6);
Result := F;
end;
procedure TGLDUserCamera.DrawCamera(S: GLfloat);
const
P1: array[1..10] of TGLDVector3f = (
(X: -0.35000; Y: 0.10000; Z: 0.12000),
(X: -0.35000; Y: 0.10000; Z: -0.12000),
(X: -0.35000; Y: -0.10000; Z: -0.12000),
(X: -0.35000; Y: -0.10000; Z: 0.12000),
(X: -0.35000; Y: 0.10000; Z: 0.12000),
(X: -0.30000; Y: 0.05000; Z: 0.06000),
(X: -0.30000; Y: 0.05000; Z: -0.06000),
(X: -0.30000; Y: -0.05000; Z: -0.06000),
(X: -0.30000; Y: -0.05000; Z: 0.06000),
(X: -0.30000; Y: 0.05000; Z: 0.06000));
P2: array[1..18] of TGLDVector3f = (
(X: -0.30000; Y: 0.00000; Z: 0.04000),
(X: -0.30000; Y: 0.02828; Z: 0.02828),
(X: -0.30000; Y: 0.04000; Z: 0.00000),
(X: -0.30000; Y: 0.02828; Z: -0.02828),
(X: -0.30000; Y: 0.00000; Z: -0.04000),
(X: -0.30000; Y: -0.02828; Z: -0.02828),
(X: -0.30000; Y: -0.04000; Z: 0.00000),
(X: -0.30000; Y: -0.02828; Z: 0.02828),
(X: -0.30000; Y: 0.00000; Z: 0.04000),
(X: -0.15000; Y: 0.00000; Z: 0.04000),
(X: -0.15000; Y: 0.02828; Z: 0.02828),
(X: -0.15000; Y: 0.04000; Z: 0.00000),
(X: -0.15000; Y: 0.02828; Z: -0.02828),
(X: -0.15000; Y: 0.00000; Z: -0.04000),
(X: -0.15000; Y: -0.02828; Z: -0.02828),
(X: -0.15000; Y: -0.04000; Z: 0.00000),
(X: -0.15000; Y: -0.02828; Z: 0.02828),
(X: -0.15000; Y: 0.00000; Z: 0.04000));
P3: array[1..2, 1..26] of TGLDVector3f = (
((X: 0.12500; Y: 0.20500; Z: 0.04500),
(X: 0.10825; Y: 0.26750; Z: 0.04500),
(X: 0.06250; Y: 0.31325; Z: 0.04500),
(X: 0.00000; Y: 0.33000; Z: 0.04500),
(X: -0.06250; Y: 0.31325; Z: 0.04500),
(X: -0.10825; Y: 0.26750; Z: 0.04500),
(X: -0.12500; Y: 0.20500; Z: 0.04500),
(X: -0.10825; Y: 0.14250; Z: 0.04500),
(X: -0.06250; Y: 0.09675; Z: 0.04500),
(X: 0.00000; Y: 0.08000; Z: 0.04500),
(X: 0.06250; Y: 0.09675; Z: 0.04500),
(X: 0.10825; Y: 0.14250; Z: 0.04500),
(X: 0.12500; Y: 0.20500; Z: 0.04500),
(X: 0.12500; Y: 0.20500; Z: -0.04500),
(X: 0.10825; Y: 0.26750; Z: -0.04500),
(X: 0.06250; Y: 0.31325; Z: -0.04500),
(X: 0.00000; Y: 0.33000; Z: -0.04500),
(X: -0.06250; Y: 0.31325; Z: -0.04500),
(X: -0.10825; Y: 0.26750; Z: -0.04500),
(X: -0.12500; Y: 0.20500; Z: -0.04500),
(X: -0.10825; Y: 0.14250; Z: -0.04500),
(X: -0.06250; Y: 0.09675; Z: -0.04500),
(X: 0.00000; Y: 0.08000; Z: -0.04500),
(X: 0.06250; Y: 0.09675; Z: -0.04500),
(X: 0.10825; Y: 0.14250; Z: -0.04500),
(X: 0.12500; Y: 0.20500; Z: -0.04500)),
((X: 0.33500; Y: 0.07500; Z: 0.04500),
(X: 0.31825; Y: 0.13750; Z: 0.04500),
(X: 0.27250; Y: 0.18325; Z: 0.04500),
(X: 0.21000; Y: 0.20000; Z: 0.04500),
(X: 0.14750; Y: 0.18325; Z: 0.04500),
(X: 0.10175; Y: 0.13750; Z: 0.04500),
(X: 0.08500; Y: 0.07500; Z: 0.04500),
(X: 0.10175; Y: 0.01250; Z: 0.04500),
(X: 0.14750; Y: -0.03325; Z: 0.04500),
(X: 0.21000; Y: -0.05000; Z: 0.04500),
(X: 0.27250; Y: -0.03325; Z: 0.04500),
(X: 0.31825; Y: 0.01250; Z: 0.04500),
(X: 0.33500; Y: 0.07500; Z: 0.04500),
(X: 0.33500; Y: 0.07500; Z: -0.04500),
(X: 0.31825; Y: 0.13750; Z: -0.04500),
(X: 0.27250; Y: 0.18325; Z: -0.04500),
(X: 0.21000; Y: 0.20000; Z: -0.04500),
(X: 0.14750; Y: 0.18325; Z: -0.04500),
(X: 0.10175; Y: 0.13750; Z: -0.04500),
(X: 0.08500; Y: 0.07500; Z: -0.04500),
(X: 0.10175; Y: 0.01250; Z: -0.04500),
(X: 0.14750; Y: -0.03325; Z: -0.04500),
(X: 0.21000; Y: -0.05000; Z: -0.04500),
(X: 0.27250; Y: -0.03325; Z: -0.04500),
(X: 0.31825; Y: 0.01250; Z: -0.04500),
(X: 0.33500; Y: 0.07500; Z: -0.04500)));
P4: array[1..16] of TGLDVector3f = (
(X: -0.15000; Y: -0.05000; Z: 0.05000),
(X: -0.15000; Y: -0.05000; Z: -0.05000),
(X: -0.15000; Y: 0.05000; Z: 0.05000),
(X: -0.15000; Y: 0.05000; Z: -0.05000),
(X: -0.08000; Y: 0.08000; Z: 0.05000),
(X: -0.08000; Y: 0.08000; Z: -0.05000),
(X: 0.05000; Y: 0.08000; Z: 0.05000),
(X: 0.05000; Y: 0.08000; Z: -0.05000),
(X: 0.15000; Y: -0.05000; Z: 0.05000),
(X: 0.15000; Y: -0.05000; Z: -0.05000),
(X: 0.10000; Y: -0.10000; Z: 0.05000),
(X: 0.10000; Y: -0.10000; Z: -0.05000),
(X: -0.10000; Y: -0.10000; Z: 0.05000),
(X: -0.10000; Y: -0.10000; Z: -0.05000),
(X: -0.15000; Y: -0.05000; Z: 0.05000),
(X: -0.15000; Y: -0.05000; Z: -0.05000));
var
i, j, k: GLubyte;
begin
glPushMatrix;
FTarget.ApplyAsTranslation;
FRotation.ApplyAsInverseRotationYXZ;
glTranslatef(0, 0, FZoom);
glRotatef(-90, 0, 1, 0);
glScalef(S, S, S);
glBegin(GL_QUAD_STRIP);
for i := 1 to 5 do
begin
glVertex3fv(@P1[i]);
glVertex3fv(@P1[i + 5]);
end;
glEnd;
glBegin(GL_QUAD_STRIP);
for i := 1 to 9 do
begin
glVertex3fv(@P2[i]);
glVertex3fv(@P2[i + 9]);
end;
glEnd;
for j := 1 to 2 do
begin
glBegin(GL_QUAD_STRIP);
for i := 1 to 13 do
begin
glVertex3fv(@P3[j, i]);
glVertex3fv(@P3[j, 13 + i]);
end;
glEnd;
end;
glBegin(GL_QUAD_STRIP);
for i := 1 to 16 do
glVertex3fv(@P4[i]);
glEnd;
for j := 1 to 2 do
for k := 0 to 1 do
begin
glBegin(GL_POLYGON);
for i := 1 to 13 do
glVertex3fv(@P3[j][k * 13 + i]);
glEnd;
end;
for j := 1 to 2 do
begin
glBegin(GL_POLYGON);
for i := 0 to 7 do
glVertex3fv(@P4[i * 2 + j]);
glEnd;
end;
glPopMatrix;
end;
procedure TGLDUserCamera.DrawTarget(S: GLfloat);
const
W = 0.1;
W2 = W / 2;
P: array[1..8] of TGLDVector3f = (
(X: -W2; Y: W2; Z: -W2),
(X: W2; Y: W2; Z: -W2),
(X: -W2; Y: -W2; Z: -W2),
(X: W2; Y: -W2; Z: -W2),
(X: -W2; Y: W2; Z: W2),
(X: W2; Y: W2; Z: W2),
(X: -W2; Y: -W2; Z: W2),
(X: W2; Y: -W2; Z: W2));
Q: array[1..6, 1..4] of GLubyte = (
(1, 3, 4, 2),
(2, 4, 8, 6),
(6, 8, 7, 5),
(5, 7, 3, 1),
(5, 1, 2, 6),
(3, 7, 8, 4));
var
i, j: GLubyte;
begin
glPushMatrix;
FTarget.ApplyAsTranslation;
glScalef(S, S, S);
glBegin(GL_QUADS);
for j := 1 to 6 do
for i := 1 to 4 do
glVertex3fv(@P[Q[j, i]]);
glEnd;
glPopMatrix;
end;
procedure TGLDUserCamera.DrawLine;
begin
glPushAttrib(GL_LINE_BIT);
glLineWidth(1);
glBegin(GL_LINES);
glVertex3fv(FTarget.GetPointer);
glVertex3fv(GetPosition.GetPointer);
glEnd;
glPopAttrib;
end;
procedure TGLDUserCamera.DoRender;
begin
RenderWireframe;
end;
procedure TGLDUserCamera.SimpleRender;
var
S: GLfloat;
begin
S := Scale;
DrawCamera(S);
DrawTarget(S);
DrawLine;
end;
procedure TGLDUserCamera.LoadFromStream(Stream: TStream);
begin
Stream.Read(FTarget.GetPointer^, SizeOf(TGLDVector3f));
FRotation.LoadFromStream(Stream);
Stream.Read(FZNear, SizeOf(GLfloat));
Stream.Read(FZFar, SizeOf(GLfloat));
Stream.Read(FProjectionMode, SizeOf(TGLDProjectionMode));
Stream.Read(FZoom, SizeOf(GLfloat));
Stream.Read(FFov, SizeOf(GLfloat));
Stream.Read(FAspect, SizeOf(GLfloat));
end;
procedure TGLDUserCamera.SaveToStream(Stream: TStream);
begin
Stream.Write(FTarget.GetPointer^, SizeOf(TGLDVector3f));
FRotation.SaveToStream(Stream);
Stream.Write(FZNear, SizeOf(GLfloat));
Stream.Write(FZFar, SizeOf(GLfloat));
Stream.Write(FProjectionMode, SizeOf(TGLDProjectionMode));
Stream.Write(FZoom, SizeOf(GLfloat));
Stream.Write(FFov, SizeOf(GLfloat));
Stream.Write(FAspect, SizeOf(GLfloat));
end;
class function TGLDUserCamera.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_USERCAMERA;
end;
class function TGLDUserCamera.VisualObjectClassType: TGLDVisualObjectClass;
begin
Result := TGLDUserCamera;
end;
procedure TGLDUserCamera.ApplyProjection;
var
Z2, Z3: GLfloat;
begin
vAppliedUserCamera := Self;
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
case FProjectionMode of
GLD_ORTHOGONAL:
begin
Z2 := FZoom / 2;
Z3 := Z2 / FAspect;
glOrtho(-Z2, Z2, -Z3, Z3, FZNear, FZFar);
end;
GLD_PERSPECTIVE:
gluPerspective(FFov, FAspect, FZNear, FZFar);
end;
end;
procedure TGLDUserCamera.ApplyModelview;
begin
vAppliedUserCamera := Self;
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
glTranslatef(0, 0, -Radius);
FRotation.ApplyAsRotationXZY;
with FTarget do
glTranslatef(-X, -Y, -Z);
end;
procedure TGLDUserCamera.SetAspectFromViewport(const Viewport: TGLDViewport);
begin
with Viewport do
if Height = 0 then
FAspect := 0
else FAspect := Width / Height;
end;
procedure TGLDUserCamera.SetAspectFromCurrentViewport;
var
Viewport: TGLDViewport;
begin
Viewport := GLDXGetViewport;
with Viewport do
if Height = 0 then
FAspect := 0
else FAspect := Width / Height;
end;
procedure TGLDUserCamera.ZoomD(const Delta: GLfloat);
begin
if Delta = 0 then Exit;
FZoom := FZoom + Delta;
Change;
end;
procedure TGLDUserCamera.MoveSelectedParts(const Vector: TGLDVector3f);
var
Event: TNotifyEvent;
begin
if FSelected and FTargetSelected then
begin
PGLDVector3f(FPosition.GetPointer)^ := GLDXVectorAdd(
PGLDVector3f(FPosition.GetPointer)^, Vector);
PGLDVector3f(FTarget.GetPointer)^ := GLDXVectorAdd(
PGLDVector3f(FTarget.GetPointer)^, Vector);
end else
if FSelected then
begin
Event := Self.OnChange;
Self.OnChange := nil;
FPosition.Vector3f :=
GLDXVectorAdd(FPosition.Vector3f, Vector);
Self.OnChange := Event;
end else
if FTargetSelected then
begin
Event := Self.OnChange;
Self.OnChange := nil;
FTarget.Vector3f :=
GLDXVectorAdd(FTarget.Vector3f, Vector);
Self.OnChange := Event;
end;
end;
function TGLDUserCamera.ListIndex: GLuint;
begin
if Assigned(Owner) and (Owner is TGLDUserCameraList) then
Result := TGLDUserCameraList(Owner).IndexOf(Self)
else Result := 0;
end;
procedure TGLDUserCamera.SetOnChange(Value: TNotifyEvent);
begin
inherited SetOnChange(Value);
FRotation.OnChange := FOnChange;
end;
procedure TGLDUserCamera.SetTarget(Value: TGLDVector4fClass);
begin
FTarget.Assign(Value);
end;
procedure TGLDUserCamera.SetRotation(Value: TGLDRotation3DClass);
begin
FRotation.Assign(Value);
end;
procedure TGLDUserCamera.SetZNear(Value: GLfloat);
begin
if FZNear = Value then Exit;
FZNear := Value;
if FZNear < 0.1 then FZNear := 0.1;
Change;
end;
procedure TGLDUserCamera.SetZFar(Value: GLfloat);
begin
if FZFar = Value then Exit;
FZFar := Value;
Change;
end;
procedure TGLDUserCamera.SetProjectionMode(Value: TGLDProjectionMode);
begin
if FProjectionMode = Value then Exit;
FProjectionMode := Value;
Change;
end;
procedure TGLDUserCamera.SetZoom(Value: GLfloat);
begin
if FZoom = Value then Exit;
FZoom := Value;
Change;
end;
procedure TGLDUserCamera.SetFov(Value: GLfloat);
begin
if FFov = Value then Exit;
FFov := Value;
Change;
end;
procedure TGLDUserCamera.SetAspect(Value: GLfloat);
begin
if FAspect = Value then Exit;
FAspect := Value;
Change;
end;
procedure TGLDUserCamera.SetSelected(Value: GLboolean);
begin
if FSelected = Value then Exit;
FSelected := Value;
Change;
end;
procedure TGLDUserCamera.SetTargetSelected(Value: GLboolean);
begin
if FTargetSelected = Value then Exit;
FTargetSelected := Value;
Change;
end;
function TGLDUserCamera.GetParams: TGLDUserCameraParams;
begin
Result := GLDXUserCameraParams(FTarget.Vector3f, FRotation.Params,
FProjectionMode, FZNear, FZFar, FZoom, FFov, FAspect);
end;
procedure TGLDUserCamera.SetParams(Value: TGLDUserCameraParams);
begin
if GLDXUserCameraParamsEqual(GetParams, Value) then Exit;
PGLDVector3f(FTarget.GetPointer)^ := Value.Target;
PGLDRotation3D(FRotation.GetPointer)^ := Value.Rotation;
FZNear := Value.ZNear;
FZFar := Value.ZFar;
FProjectionMode := Value.ProjectionMode;
FZoom := Value.Zoom;
FFov := Value.Fov;
FAspect := Value.Aspect;
Change;
end;
class function TGLDUserCamera.GetColor: TGLDColor4fClass;
begin
Result := GLDGetUserCameraColor;
end;
class procedure TGLDUserCamera.SetColor(Value: TGLDColor4fClass);
begin
GLDSetUserCameraColor(Value);
end;
class function TGLDUserCamera.GetTargetColor: TGLDColor4fClass;
begin
Result := GLDGetUserCameraTargetColor;
end;
class procedure TGLDUserCamera.SetTargetColor(Value: TGLDColor4fClass);
begin
GLDSetUserCameraTargetColor(Value);
end;
class function TGLDUserCamera.GetLineColor: TGLDColor4fClass;
begin
Result := GLDGetUserCameraLineColor;
end;
class procedure TGLDUserCamera.SetLineColor(Value: TGLDColor4fClass);
begin
GLDSetUserCameraLineColor(Value);
end;
function TGLDUserCamera.GetPosition: TGLDVector4fClass;
var
M: TGLDMatrixf;
begin
M := GLDXMatrixTranslation(FTarget.Vector3f);
with FRotation.Params do
M := GLDXMatrixMul(M,
GLDXMatrixRotationYXZ(-XAngle, -YAngle, -ZAngle));
M := GLDXMatrixMul(M, GLDXMatrixTranslation(0, 0, FZoom));
PGLDVector3f(FPosition.GetPointer)^ := GLDXVectorTransform(GLD_VECTOR3F_ZERO, M);
Result := FPosition;
end;
procedure TGLDUserCamera.SetPosition(Value: TGLDVector4fClass);
begin
FPosition.Assign(Value);
end;
procedure TGLDUserCamera.PositionChanged(Sender: TObject);
var
T, P, P1, L: TGLDVector3f;
D, D2, D3, DX, DY: GLdouble;
begin
// if Sender <> FPosition then Exit;
T := FTarget.Vector3f;
P := FPosition.Vector3f;
L := GLDXVectorSub(P, T);
P1 := L;
P1.Y := 0;
P1 := GLDXVectorNormalize(P1);
D := GLDXVectorDotProduct(GLD_NORMAL_POSITIVE_Z, P1);
//D2 := GLDXArcCos(GLDXVectorDotProduct(
// GLD_NORMAL_NEGATIVE_X, P1));
//D3 := GLDXArcCos(GLDXVectorDotProduct(
// GLD_NORMAL_POSITIVE_X, P1));
DY := GLDXArcCos(D);
//if (D2 - DY) >= (D3 - DY) then DY := -DY;
if P1.X > 0 then DY := -DY;
if GLDXVectorLength(P1) = 0 then DY := 0;
P1 := L;
P1.Z := GLDXPit(L.X, L.Z);
P1.X := 0;
P1 := GLDXVectorNormalize(P1);
//if P.Z < 0 then P1.Z := -P1.Z;
D := GLDXVectorDotProduct(GLD_NORMAL_POSITIVE_Z, P1);
D2 := GLDXArcCos(GLDXVectorDotProduct(
GLD_NORMAL_POSITIVE_Y, P1));
D3 := GLDXArcCos(GLDXVectorDotProduct(
GLD_NORMAL_NEGATIVE_Y, P1));
DX := GLDXArcCos(D);
if (D2 - DX) > (D3 - DX) then DX := -DX;
if GLDXVectorLength(P1) = 0 then DX := 0;
//if Sender = FPosition then
// if Abs(DY) > 90 then DX := 180 - DX;
PGLDRotation3D(FRotation.GetPointer)^.XAngle := DX;
PGLDRotation3D(FRotation.GetPointer)^.YAngle := DY;
FZoom := Abs(GLDXVectorLength(L));
Change;
end;
constructor TGLDCameraSystem.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FUsedCamera := GLD_UC_PERSPECTIVE;
FPerspectiveCamera := TGLDPerspectiveCamera.Create(Self);
FFrontCamera := TGLDFrontCamera.Create(Self);
FBackCamera := TGLDBackCamera.Create(Self);
FLeftCamera := TGLDLeftCamera.Create(Self);
FRightCamera := TGLDRightCamera.Create(Self);
FTopCamera := TGLDTopCamera.Create(Self);
FBottomCamera := TGLDBottomCamera.Create(Self);
FUserCamera := nil;
end;
destructor TGLDCameraSystem.Destroy;
begin
FPerspectiveCamera.Free;
FFrontCamera.Free;
FBackCamera.Free;
FLeftCamera.Free;
FRightCamera.Free;
FTopCamera.Free;
FBottomCamera.Free;
inherited Destroy;
end;
procedure TGLDCameraSystem.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLDCameraSystem) then Exit;
FUsedCamera := TGLDCameraSystem(Source).FUsedCamera;
FPerspectiveCamera.Assign(TGLDCameraSystem(Source).FPerspectiveCamera);
FFrontCamera.Assign(TGLDCameraSystem(Source).FFrontCamera);
FBackCamera.Assign(TGLDCameraSystem(Source).FBackCamera);
FLeftCamera.Assign(TGLDCameraSystem(Source).FLeftCamera);
FRightCamera.Assign(TGLDCameraSystem(Source).FRightCamera);
FTopCamera.Assign(TGLDCameraSystem(Source).FTopCamera);
FBottomCamera.Assign(TGLDCameraSystem(Source).FBottomCamera);
FUserCamera := TGLDCameraSystem(Source).FUserCamera;
end;
procedure TGLDCameraSystem.Apply;
begin
if FUsedCamera <> GLD_UC_USER then
vAppliedUserCamera := nil;
case FUsedCamera of
GLD_UC_PERSPECTIVE: FPerspectiveCamera.Apply;
GLD_UC_FRONT: FFrontCamera.Apply;
GLD_UC_BACK: FBackCamera.Apply;
GLD_UC_LEFT: FLeftCamera.Apply;
GLD_UC_RIGHT: FRightCamera.Apply;
GLD_UC_TOP: FTopCamera.Apply;
GLD_UC_BOTTOM: FBottomCamera.Apply;
GLD_UC_USER:
if Assigned(FUserCamera) then
begin
vAppliedUserCamera := FUserCamera;
FUserCamera.Apply;
end else FPerspectiveCamera.Apply;
end;
end;
procedure TGLDCameraSystem.Reset;
begin
case FUsedCamera of
GLD_UC_PERSPECTIVE: FPerspectiveCamera.Reset;
GLD_UC_FRONT: FFrontCamera.Reset;
GLD_UC_BACK: FBackCamera.Reset;
GLD_UC_LEFT: FLeftCamera.Reset;
GLD_UC_RIGHT: FRightCamera.Reset;
GLD_UC_TOP: FTopCamera.Reset;
GLD_UC_BOTTOM: FBottomCamera.Reset;
end;
end;
procedure TGLDCameraSystem.Pan(const X, Y: GLint);
begin
case FUsedCamera of
GLD_UC_PERSPECTIVE: FPerspectiveCamera.Pan(X, Y);
GLD_UC_FRONT: FFrontCamera.Pan(X, Y);
GLD_UC_BACK: FBackCamera.Pan(X, Y);
GLD_UC_LEFT: FLeftCamera.Pan(X, Y);
GLD_UC_RIGHT: FRightCamera.Pan(X, Y);
GLD_UC_TOP: FTopCamera.Pan(X, Y);
GLD_UC_BOTTOM: FBottomCamera.Pan(X, Y);
end;
end;
procedure TGLDCameraSystem.Zoom(const Delta: GLfloat);
begin
case FUsedCamera of
GLD_UC_PERSPECTIVE: FPerspectiveCamera.ZoomD(Delta * -0.002);
GLD_UC_FRONT: FFrontCamera.ZoomD(Delta * -0.0002);
GLD_UC_BACK: FBackCamera.ZoomD(Delta * -0.0002);
GLD_UC_LEFT: FLeftCamera.ZoomD(Delta * -0.0002);
GLD_UC_RIGHT: FRightCamera.ZoomD(Delta * -0.0002);
GLD_UC_TOP: FTopCamera.ZoomD(Delta * -0.0002);
GLD_UC_BOTTOM: FBottomCamera.ZoomD(Delta * -0.0002);
GLD_UC_USER:
if Assigned(FUserCamera) then
FUserCamera.ZoomD(Delta * -0.0002);
end;
end;
procedure TGLDCameraSystem.LoadFromStream(Stream: TStream);
var
Index: GLuint;
begin
Stream.Read(FUsedCamera, SizeOf(TGLDUsedCamera));
FPerspectiveCamera.LoadFromStream(Stream);
FFrontCamera.LoadFromStream(Stream);
FBackCamera.LoadFromStream(Stream);
FLeftCamera.LoadFromStream(Stream);
FRightCamera.LoadFromStream(Stream);
FTopCamera.LoadFromStream(Stream);
FBottomCamera.LoadFromStream(Stream);
Stream.Read(Index, SizeOf(GLuint));
FUserCamera := nil;
if (Index <> 0) and Assigned(Owner) then
if (Owner is TGLDSystem) and
Assigned(TGLDSystem(Owner).Repository) then
begin
FUserCamera := TGLDSystem(Owner).Repository.Cameras[Index];
end;
end;
procedure TGLDCameraSystem.SaveToStream(Stream: TStream);
var
Index: GLuint;
begin
Stream.Write(FUsedCamera, SizeOf(TGLDUsedCamera));
FPerspectiveCamera.SaveToStream(Stream);
FFrontCamera.SaveToStream(Stream);
FBackCamera.SaveToStream(Stream);
FLeftCamera.SaveToStream(Stream);
FRightCamera.SaveToStream(Stream);
FTopCamera.SaveToStream(Stream);
FBottomCamera.SaveToStream(Stream);
if Assigned(FUserCamera) then
Index := FUserCamera.ListIndex
else Index := 0;
Stream.Write(Index, SizeOf(GLuint));
end;
class function TGLDCameraSystem.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_CAMERASYSTEM;
end;
procedure TGLDCameraSystem.SetOnChange(Value: TNotifyEvent);
begin
inherited SetOnChange(Value);
FPerspectiveCamera.OnChange := FOnChange;
FFrontCamera.OnChange := FOnChange;
FBackCamera.OnChange := FOnChange;
FLeftCamera.OnChange := FOnChange;
FRightCamera.OnChange := FOnChange;
FTopCamera.OnChange := FOnChange;
FBottomCamera.OnChange := FOnChange;
end;
procedure TGLDCameraSystem.SetUsedCamera(Value: TGLDUsedCamera);
begin
if FUsedCamera = Value then Exit;
if (Value = GLD_UC_USER) and (FUserCamera = nil) then Exit;
FUsedCamera := Value;
Change;
end;
procedure TGLDCameraSystem.SetPerspectiveCamera(Value: TGLDPerspectiveCamera);
begin
FPerspectiveCamera.Assign(Value);
end;
procedure TGLDCameraSystem.SetFrontCamera(Value: TGLDFrontCamera);
begin
FFrontCamera.Assign(Value);
end;
procedure TGLDCameraSystem.SetBackCamera(Value: TGLDBackCamera);
begin
FBackCamera.Assign(Value);
end;
procedure TGLDCameraSystem.SetLeftCamera(Value: TGLDLeftCamera);
begin
FLeftCamera.Assign(Value);
end;
procedure TGLDCameraSystem.SetRightCamera(Value: TGLDRightCamera);
begin
FRightCamera.Assign(Value);
end;
procedure TGLDCameraSystem.SetTopCamera(Value: TGLDTopCamera);
begin
FTopCamera.Assign(Value);
end;
procedure TGLDCameraSystem.SetBottomCamera(Value: TGLDBottomCamera);
begin
FBottomCamera.Assign(Value);
end;
procedure TGLDCameraSystem.SetUserCamera(Value: TGLDUserCamera);
begin
FUserCamera := Value;
if (FUserCamera = nil) and (FUsedCamera = GLD_UC_USER) then
FUsedCamera := GLD_UC_PERSPECTIVE;
Change;
end;
function TGLDCameraSystem.GetRotation: TGLDRotation3DClass;
begin
if FUsedCamera = GLD_UC_PERSPECTIVE then
Result := FPerspectiveCamera.FRotation else
if (FUsedCamera = GLD_UC_USER) and Assigned(FUserCamera) then
Result := FUserCamera.FRotation
else Result := nil;
end;
constructor TGLDUserCameraList.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FCapacity := 0;
FCount := 0;
FList := nil;
end;
destructor TGLDUserCameraList.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TGLDUserCameraList.Assign(Source: TPersistent);
var
i: GLuint;
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLDUserCameraList) then Exit;
Clear;
SetCapacity(TGLDUserCameraList(Source).FCapacity);
FCount := TGLDUserCameraList(Source).FCount;
if FCount > 0 then
for i := 1 to FCount do
begin
FList^[i] := TGLDUserCamera.Create(Self);
FList^[i].Assign(TGLDUserCameraList(Source).FList^[i]);
FList^[i].OnChange := FOnChange;
end;
end;
procedure TGLDUserCameraList.Render;
var
i: GLuint;
begin
if FCount > 0 then
for i := 1 to FCount do
FList^[i].Render;
end;
procedure TGLDUserCameraList.Render(Index: GLuint);
begin
if (Index > 0) and (Index <= FCount) then
FList^[Index].Render;
end;
procedure TGLDUserCameraList.RenderWireframe;
var
i: GLuint;
begin
if FCount > 0 then
for i := 1 to FCount do
FList^[i].RenderWireframe;
end;
procedure TGLDUserCameraList.RenderWireframe(Index: GLuint);
begin
if (Index > 0) and (Index <= FCount) then
FList^[Index].RenderWireframe;
end;
procedure TGLDUserCameraList.RenderForSelection(Offset: GLuint);
var
i: GLuint;
begin
if FCount > 0 then
for i := 1 to FCount do
FList^[i].RenderForSelection(Offset + (i * 2) - 1);
end;
procedure TGLDUserCameraList.RenderForSelection(Index: GLuint; Offset: GLuint);
begin
if (Index > 0) and (Index <= FCount) then
FList^[Index].RenderForSelection(Offset + (Index * 2) - 1);
end;
procedure TGLDUserCameraList.Select(Offset, Index: GLuint);
begin
DeleteSelections;
AddSelection(Offset, Index);
end;
procedure TGLDUserCameraList.AddSelection(Offset, Index: GLuint);
begin
Index := Index - Offset;
if (Index > 0) and (Index <= FCount * 2) then
begin
case (Index mod 2) of
0: FList^[Index div 2].TargetSelected := True;
1: FList^[(Index + 1) div 2].Selected := True;
end;
end;
end;
procedure TGLDUserCameraList.SelectAllCameras;
var
i: GLuint;
begin
if FCount > 0 then
begin
for i := 1 to FCount do
FList^[i].FSelected := True;
Change;
end;
end;
procedure TGLDUserCameraList.SelectAllTargets;
var
i: GLuint;
begin
if FCount > 0 then
begin
for i := 1 to FCount do
FList^[i].FTargetSelected := True;
Change;
end;
end;
procedure TGLDUserCameraList.SelectAll;
var
I: GLuint;
begin
if FCount > 0 then
begin
for i := 1 to FCount do
with FList^[i] do
begin
FSelected := True;
FTargetSelected := True;
end;
Change;
end;
end;
procedure TGLDUserCameraList.DeleteSelections;
var
i: GLuint;
begin
if FCount > 0 then
begin
for i := 1 to FCount do
with FList^[i] do
begin
FSelected := False;
FTargetSelected := False;
end;
Change;
end;
end;
procedure TGLDUserCameraList.InvertSelections;
var
i: GLuint;
begin
if FCount > 0 then
begin
for i := 1 to FCount do
with FList^[i] do
begin
FSelected := not FSelected;
FTargetSelected := not FTargetSelected;
end;
Change;
end;
end;
procedure TGLDUserCameraList.DeleteSelectedCameras;
var
i: GLuint;
begin
if FCount > 0 then
begin
for i := FCount downto 1 do
if (FList^[i].FSelected) or (FList^[i].FTargetSelected) then
Delete(i);
Change;
end;
end;
procedure TGLDUserCameraList.CopySelectedCamerasTo(CamList: TGLDUserCameraList);
var
i: GLuint;
begin
if not Assigned(CamList) then Exit;
if FCount > 0 then
for i := 1 to FCount do
if FList^[i].FSelected then
begin
if CamList.Add(FList^[i]) > 0 then
begin
CamList.Last.FSelected := False;
CamList.Last.FTargetSelected := False;
CamList.Last.Name := CamList.Last.Name + '1';
end;
FList^[i].FTargetSelected := True;
end;
end;
procedure TGLDUserCameraList.PasteCamerasFrom(CamList: TGLDUserCameraList);
var
i: GLuint;
begin
if not Assigned(CamList) then Exit;
if CamList.FCount > 0 then
for i := 1 to CamList.FCount do
Add(CamList.FList^[i]);
Change;
end;
function TGLDUserCameraList.SelectionCount: GLuint;
var
i: GLuint;
begin
Result := 0;
if FCount > 0 then
for i := 1 to FCount do
with FList^[i] do
begin
if FSelected then Inc(Result);
if FTargetSelected then Inc(Result);
end;
end;
function TGLDUserCameraList.CameraSelectionCount: GLuint;
var
i: GLuint;
begin
Result := 0;
if FCount > 0 then
for i := 1 to FCount do
with FList^[i] do
if FSelected then Inc(Result);
end;
function TGLDUserCameraList.FirstSelectedCamera: TGLDUserCamera;
var
i: GLuint;
begin
Result := nil;
if FCount > 0 then
for i := 1 to FCount do
with FList^[i] do
if FSelected then
begin
Result := FList^[i];
Exit;
end;
end;
function TGLDUserCameraList.CenterOfSelectedObjects: TGLDVector3f;
var
i, Cnt: GLuint;
begin
Result := GLD_VECTOR3F_ZERO;
Cnt := 0;
if FCount > 0 then
for i := 1 to FCount do
with FList^[i] do
begin
if FSelected then
begin
Inc(Cnt);
Result := GLDXVectorAdd(Result, GetPosition.Vector3f);
end;
if FTargetSelected then
begin
Inc(Cnt);
Result := GLDXVectorAdd(Result, FTarget.Vector3f);
end;
end;
if Cnt > 0 then
begin
if Result.X <> 0 then Result.X := Result.X / Cnt;
if Result.Y <> 0 then Result.Y := Result.Y / Cnt;
if Result.Z <> 0 then Result.Z := Result.Z / Cnt;
end;
end;
function TGLDUserCameraList.AverageOfRotations: TGLDRotation3D;
var
i, Cnt: GLuint;
begin
Result := GLD_ROTATION3D_ZERO;
Cnt := 0;
if FCount > 0 then
for i := 1 to FCount do
with FList^[i] do
begin
if FSelected or FTargetSelected then
begin
Inc(Cnt);
Result := GLDXRotation3DAdd(Result, FRotation.Params);
end;
end;
if Cnt > 0 then
begin
if Result.XAngle <> 0 then Result.XAngle:= Result.XAngle / Cnt;
if Result.YAngle <> 0 then Result.YAngle := Result.YAngle / Cnt;
if Result.ZAngle <> 0 then Result.ZAngle := Result.ZAngle / Cnt;
end;
end;
procedure TGLDUserCameraList.MoveSelectedObjects(const Vector: TGLDVector3f);
var
i: GLuint;
begin
if FCount > 0 then
for i := 1 to FCount do
FList^[i].MoveSelectedParts(Vector);
end;
procedure TGLDUserCameraList.RotateSelectedObjects(const ARotation: TGLDRotation3D);
var
i: GLuint;
begin
if FCount > 0 then
for i := 1 to FCount do
with FList^[i], FList^[i].FRotation do
if FSelected or FTargetSelected then
PGLDRotation3D(GetPointer)^ :=
GLDXRotation3DAdd(PGLDRotation3D(GetPointer)^, ARotation);
end;
procedure TGLDUserCameraList.Clear;
var
i: GLuint;
begin
if FCount > 0 then
for i := 1 to FCount do
FList^[i].Free;
ReallocMem(FList, 0);
FCapacity := 0;
FCount := 0;
FList := nil;
end;
function TGLDUserCameraList.CreateNew: GLuint;
begin
Result := 0;
if FCount < GLD_MAX_CAMERAS then
begin
SetCount(FCount + 1);
Result := FCount;
end;
end;
function TGLDUserCameraList.Add(Camera: TGLDUserCamera): GLuint;
begin
Result := 0;
if Camera = nil then Exit;
Result := CreateNew;
if Result > 0 then
Last.Assign(Camera);
end;
function TGLDUserCameraList.Add(AParams: TGLDUserCameraParams): GLuint;
begin
Result := CreateNew;
if Result = 0 then Exit;
Last.SetParams(AParams);
end;
function TGLDUserCameraList.Delete(Index: GLuint): GLuint;
var
i: GLuint;
begin
Result := 0;
if (Index < 1) or (Index > FCount) then Exit;
FList^[Index].Free;
FList^[Index] := nil;
if Index < FCount then
for i := Index to FCount - 1 do
FList^[i] := FList^[i + 1];
Dec(FCount);
Result := Index;
end;
function TGLDUserCameraList.Delete(Camera: TGLDUserCamera): GLuint;
begin
Result := Delete(IndexOf(Camera));
end;
function TGLDUserCameraList.IndexOf(Camera: TGLDUserCamera): GLuint;
var
i: GLuint;
begin
Result := 0;
if Camera = nil then Exit;
if FCount > 0 then
for i := 1 to FCount do
if FList^[i] = Camera then
begin
Result := i;
Exit;
end;
end;
procedure TGLDUserCameraList.LoadFromStream(Stream: TStream);
var
ACapacity, ACount, i: GLuint;
begin
Clear;
Stream.Read(ACapacity, SizeOf(GLuint));
Stream.Read(ACount, SizeOf(GLuint));
SetCapacity(ACapacity);
if ACount > 0 then
begin
for i := 1 to ACount do
begin
FList^[i] := TGLDUserCamera.Create(Self);
FList^[i].LoadFromStream(Stream);
FList^[i].OnChange := FOnChange;
end;
FCount := ACount;
end;
end;
procedure TGLDUserCameraList.SaveToStream(Stream: TStream);
var
i: GLuint;
begin
Stream.Write(FCapacity, SizeOf(GLuint));
Stream.Write(FCount, SizeOf(GLuint));
if FCount > 0 then
for i := 1 to FCount do
FList^[i].SaveToStream(Stream);
end;
procedure TGLDUserCameraList.SetOnChange(Value: TNotifyEvent);
var
i: GLuint;
begin
if not Assigned(Self) then Exit;
if FCount > 0 then
for i := 1 to FCount do
FList^[i].OnChange := Value;
FOnChange := Value;
end;
procedure TGLDUserCameraList.DefineProperties(Filer: TFiler);
begin
Filer.DefineBinaryProperty('Data', LoadFromStream, SaveToStream, True);
end;
class function TGLDUserCameraList.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_CAMERALIST;
end;
procedure TGLDUserCameraList.SetCapacity(NewCapacity: GLuint);
var
i: GLuint;
begin
if (FCapacity = NewCapacity) or
(NewCapacity > GLD_MAX_CAMERAS) then Exit;
if NewCapacity <= 0 then
begin
Clear;
Exit;
end else
begin
if NewCapacity < FCount then
SetCount(NewCapacity);
ReallocMem(FList, NewCapacity * SizeOf(TGLDUserCamera));
if NewCapacity > FCapacity then
for i := FCapacity + 1 to NewCapacity do
FList^[i] := nil;
FCapacity := NewCapacity;
end;
end;
procedure TGLDUserCameraList.SetCount(NewCount: GLuint);
var
i: GLuint;
begin
if (NewCount = FCount) or
(NewCount > GLD_MAX_CAMERAS) then Exit;
if NewCount <= 0 then
begin
Clear;
Exit;
end else
begin
if NewCount > FCapacity then
SetCapacity(NewCount);
if NewCount > FCount then
begin
for i := FCount + 1 to NewCount do
begin
FList^[i] := TGLDUserCamera.Create(Self);
FList^[i].OnChange := FOnChange;
end;
end else
if NewCount < FCount then
for i := FCount downto NewCount + 1 do
begin
FList^[i].Free;
FList^[i] := nil;
end;
FCount := NewCount;
end;
end;
function TGLDUserCameraList.GetCamera(Index: GLuint): TGLDUserCamera;
begin
if (Index >= 1) and (Index <= FCount) then
Result := FList^[Index]
else Result := nil;
end;
procedure TGLDUserCameraList.SetCamera(Index: GLuint; Camera: TGLDUserCamera);
begin
if (Index < 1) or (Index > FCount + 1) then Exit;
if Index = FCount + 1 then Add(Camera) else
if Camera = nil then Delete(Index) else
FList^[Index].Assign(Camera);
end;
function TGLDUserCameraList.GetLast: TGLDUserCamera;
begin
if FCount > 0 then
Result := FList^[FCount]
else Result := nil;
end;
procedure TGLDUserCameraList.SetLast(Camera: TGLDUserCamera);
begin
if FCount > 0 then
SetCamera(FCount, Camera)
else Add(Camera);
end;
initialization
finalization
GLDReleaseStandardCamera;
GLDReleaseUserCameraColor;
GLDReleaseUserCameraTargetColor;
GLDReleaseUserCameraLineColor;
end.
|
unit DifferentMeshFaceTypePlugin;
interface
uses MeshPluginBase, BasicMathsTypes, BasicDataTypes, GlConstants, BasicConstants,
dglOpenGL, RenderingMachine, Material, MeshBRepGeometry;
type
TDifferentMeshFaceTypePlugin = class (TMeshPluginBase)
private
MeshNormalsType: byte;
VerticesPerFace: byte;
MeshVertices: PAVector3f;
MeshNormals: PAVector3f;
FaceType : GLINT;
NumNormals: integer;
Faces: auint32;
Colours: TAVector4f;
Render: TRenderingMachine;
Material: TMeshMaterial;
MyMesh: Pointer;
protected
procedure DoRender(); override;
procedure DoUpdate(_MeshAddress: Pointer); override;
public
constructor Create;
procedure Initialize; override;
procedure Clear; override;
// Copy
procedure Assign(const _Source: TMeshPluginBase); override;
end;
implementation
uses Mesh, Math3d;
constructor TDifferentMeshFaceTypePlugin.Create;
begin
FPluginType := C_MPL_MESH;
FaceType := GL_TRIANGLES;
VerticesPerFace := 3;
Initialize;
end;
procedure TDifferentMeshFaceTypePlugin.Initialize;
begin
inherited Initialize;
Material := TMeshMaterial.Create(nil);
Render := TRenderingMachine.Create;
end;
procedure TDifferentMeshFaceTypePlugin.Clear;
begin
Render.Free;
SetLength(Colours,0);
SetLength(Faces,0);
Material.Free;
end;
procedure TDifferentMeshFaceTypePlugin.DoUpdate(_MeshAddress: Pointer);
begin
MyMesh := _MeshAddress;
MeshNormalsType := (PMesh(MyMesh))^.NormalsType;
MeshVertices := PAVector3f(Addr((PMesh(MyMesh))^.Vertices));
if MeshNormalsType = C_NORMALS_PER_VERTEX then
begin
MeshNormals := PAVector3f(Addr((PMesh(MyMesh))^.Normals));
end
else
begin
(PMesh(MyMesh))^.Geometry.GoToFirstElement;
MeshNormals := PAVector3f(Addr(((PMesh(MyMesh))^.Geometry.Current^ as TMeshBRepGeometry).Normals));
end;
NumNormals := High(MeshNormals^)+1;
Render.ForceRefresh;
end;
// Rendering related.
procedure TDifferentMeshFaceTypePlugin.DoRender;
begin
// do nothing
Render.StartRender;
Material.Enable;
Render.RenderWithFaceNormalsAndColours(MeshVertices^,MeshNormals^,Colours,Faces,FaceType,VerticesPerFace,NumNormals);
Material.Disable;
Render.FinishRender(SetVector(0,0,0));
end;
// Copy
procedure TDifferentMeshFaceTypePlugin.Assign(const _Source: TMeshPluginBase);
var
i: integer;
begin
if _Source.PluginType = FPluginType then
begin
MeshNormalsType := (_Source as TDifferentMeshFaceTypePlugin).MeshNormalsType;
VerticesPerFace := (_Source as TDifferentMeshFaceTypePlugin).VerticesPerFace;
FaceType := (_Source as TDifferentMeshFaceTypePlugin).FaceType;
NumNormals := (_Source as TDifferentMeshFaceTypePlugin).NumNormals;
SetLength(Faces, High((_Source as TDifferentMeshFaceTypePlugin).Faces) + 1);
for i := Low(Faces) to High(Faces) do
begin
Faces[i] := (_Source as TDifferentMeshFaceTypePlugin).Faces[i];
end;
SetLength(Colours, High((_Source as TDifferentMeshFaceTypePlugin).Colours) + 1);
for i := Low(Colours) to High(Colours) do
begin
Colours[i].X := (_Source as TDifferentMeshFaceTypePlugin).Colours[i].X;
Colours[i].Y := (_Source as TDifferentMeshFaceTypePlugin).Colours[i].Y;
Colours[i].Z := (_Source as TDifferentMeshFaceTypePlugin).Colours[i].Z;
Colours[i].W := (_Source as TDifferentMeshFaceTypePlugin).Colours[i].W;
end;
end;
inherited Assign(_Source);
end;
end.
|
unit LoginForm;
interface
uses
{std}
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, StdCtrls,
{devex}
cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
cxContainer, cxEdit, cxButtons, cxLabel, cxTextEdit, dxSkinsCore,
dxSkinsDefaultPainters;
type
TLoginCallBack = procedure(Sender: TObject; N: integer;
Login, Password: String; const Cancel: boolean) of object;
TfLogin = class(TForm)
eLogin: TcxTextEdit;
lLogin: TcxLabel;
ePassword: TcxTextEdit;
lPassword: TcxLabel;
bOk: TcxButton;
bCancel: TcxButton;
procedure bOkClick(Sender: TObject);
procedure bCancelClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
procedure Execute(N: integer; ACaption, Login, Password: String;
CallBack: TLoginCallBack);
procedure SetLang;
{ Public declarations }
end;
var
fLogin: TfLogin = nil;
implementation
uses LangString;
{$R *.dfm}
var
FCallBack: TLoginCallBack;
FN: integer;
procedure TfLogin.bCancelClick(Sender: TObject);
begin
FCallBack(Self, FN, eLogin.Text, ePassword.Text, true);
// Close;
end;
procedure TfLogin.bOkClick(Sender: TObject);
begin
FCallBack(Self, FN, eLogin.Text, ePassword.Text, false);
bOk.Enabled := false;
end;
procedure TfLogin.Execute(N: integer; ACaption, Login, Password: String;
CallBack: TLoginCallBack);
begin
Caption := ACaption;
eLogin.Text := Login;
ePassword.Text := Password;
FN := N;
FCallBack := CallBack;
ShowModal;
end;
procedure TfLogin.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
fLogin := nil;
end;
procedure TfLogin.FormCreate(Sender: TObject);
begin
SetLang;
end;
procedure TfLogin.SetLang;
begin
lLogin.Caption := lang('_LOGIN_');
lPassword.Caption := lang('_PASSWORD_');
bOk.Caption := lang('_OK_');
bCancel.Caption := lang('_CANCEL_');
end;
end.
|
unit utiles;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,Dialogs, Controls, uEstructura;
const
SEPARADOR_MILES = ',';
SEPARADOR_DECIMAL = '.';
function like(campo,campoRegistro:cadena50):boolean;
function confirmarOperacion(pregunta:string):boolean;
function StringToFloat(cadena: String): Real;
function ValidarStock(stock:integer;articulo:TArticulo):boolean;
function CalculoImporte(Cantidad, PrecioUnitario:string):real;
implementation
function ValidarStock(stock:integer;articulo:TArticulo):boolean;
begin
ValidarStock:=true;
if articulo.stock<stock then
ValidarStock:=false;
end;
function CalculoImporte(Cantidad, PrecioUnitario:string):real;
var
cant, codigo:integer;
PrecioUni:real;
begin
cant:=strtoInt(Cantidad);
Val(PrecioUnitario,PrecioUni,codigo);
CalculoImporte:=(cant*PrecioUni);
end;
function like(campo,campoRegistro:cadena50):boolean;
var
coincidencia:boolean;
begin
coincidencia:=false;
campo:=UpperCase(campo);
campoRegistro:=UpperCase(campoRegistro);
if (pos(campo,campoRegistro)<>0) then
coincidencia:=true;
like:=coincidencia;
end;
function confirmarOperacion(pregunta:string):boolean;
var
confirmar:boolean;
begin
confirmar:=false;
if (MessageDlg(pregunta, mtConfirmation,[mbOk,mbCancel],0)=mrOk) then
confirmar:=true;
confirmarOperacion:=confirmar;
end;
function StringToFloat(cadena: String): Real;
var
format: TFormatSettings;
valor : Real;
begin
format.ThousandSeparator := SEPARADOR_MILES;
format.DecimalSeparator := SEPARADOR_DECIMAL;
valor:=StrToFloat(cadena, format);
StringToFloat := valor;
end;
end.
|
unit uCreditCardFunction;
interface
uses Classes, StrUtils;
type
TTransactionReturn = (ttrSuccessfull, ttrNotSuccessfull, ttrError, ttrException);
TNeedSwipeEvent = procedure(Sender: TObject; var SwipedTrack: WideString;
var ACanceled: Boolean) of object;
TAfterSucessfullSwipe = procedure(Sender: TObject; const ACardNumber,
ACardMember, ACardExpireDate: WideString) of object;
TNeedTroutDEvent = procedure(Sender: TObject; var ATrouD, ARefNo, AAuthCode: WideString;
var ACanceled: Boolean) of object;
function ParseTrack(const ATrack: String; var ACard, AName, ADate,
ATrack2: WideString): Boolean;
function CopyLevelIIData(ASwiped: WideString): WideString;
implementation
function CopyLevelIIData(ASwiped: WideString): WideString;
var
strTmp: WideString;
posSemicolumn, posQuestion: Integer;
begin
strTmp := ASwiped;
posSemicolumn := Pos(';', strTmp);
Delete(strTmp, 1, posSemicolumn);
posQuestion := Pos('?', strTmp);
strTmp := Copy(strTmp, 1, posQuestion - 1);
Result := strTmp;
end;
function ParseTrack(const ATrack: String; var ACard, AName, ADate,
ATrack2: WideString): Boolean;
var
n, n2, n3,
c, c2, c3,
e, e2, e3: Integer;
track, d, m, y: WideString;
t, t2, t3: integer;
begin
Result := False;
// try
track := ATrack;
if (Length(ATrack) > 0) and (RightStr(ATrack, 1) = '?') then
begin
c := PosEx(';', track);
if (c > 0) then
begin
c2 := PosEx('=', track);
c := c + 1;
c3 := c2 - c;
if (c3 > 0) then
begin
ACard := Copy(track, c , c3);
end;
end;
n := PosEx('^', track, 1);
if (n > 0) then
begin
n2 := PosEx('^', track, n + 1);
n := n + 1;
n3 := n2 - n;
if (n3 > 0) then
begin
AName := Copy(track, n, n3);
end;
end;
end;
e := PosEx('=', track, 1);
if (e > 0) then
begin
e := e + 1;
e2 := e + 4;
e3 := e2 - e;
if (e3 > 0) then
begin
d := Copy(Track, e, e3);
end;
m := Copy(d, 3, 2);
y := Copy(d, 1, 2);
ADate := m + y;
end;
t := PosEx(';', track, 1);
if (t > 0) then
begin
t2 := PosEx('?',track, t);
t := t + 1;
t3 := t2 - t;
if (t3 > 0) then
begin
ATrack2 := Copy(track, t, t3);
end;
end;
Result := True;
// except
// Result := False;
// end;
end;
end.
|
{*******************************************************}
{ }
{ soundex_audiere.pas Unit }
{ }
{ 版权所有 (C) 2009 NetCharm Studio! }
{ }
{*******************************************************}
//******************************************************************************
{*
* @file soundex_audiere.pas
* @version \$Id$
* @author netcharm
* @author Copyright © 2009 by NetCharm
* @date 2009/07/26
* @brief Audiere Lib v1.9.4 Delphi Binding and Components
* @remarks
*}
//******************************************************************************
unit soundex_audiere;
interface
uses
Windows, SysUtils, Classes, Contnrs, Audiere, ExtCtrls, JclFileUtils;
type
TErrorCode = (ecNoError, ecDevice, ecNoFile, ecLoading, ecOpening, ecPlaying, ecEnding, ecUnknwn);
{ TStopCallBack }
{*
* @brief
*}
TStopCallBack = class(TAdrCallback)
private
protected
public
FIsPlaying : boolean;
FResult : string;
g_sound : TAdrOutputStream;
g_stream : TAdrOutputStream;
constructor Create;
destructor Destroy; override;
procedure call(event : TAdrStopEvent);
procedure streamStopped(event : TAdrStopEvent);
published
end;
{ TAudioSystem }
{*
* @brief Audiere Lib System Component
*}
TAudioSystem = class(TComponent)
private
FDiscDevice : TStringList;
FAudioDevice : TStringList;
FFileFormat : TStringList;
FFileFilter : string;
FVersion : string;
protected
function getVersion:string;
function getDiscDevice:TStringList;
function getAudioDevice:TStringList;
function getFileFormat:TStringList;
public
constructor Create(AOwner: TComponent);
destructor Destroy; override;
published
property DiscDevice : TStringList read getDiscDevice;
property AudioDevice : TStringList read getAudioDevice;
property FileFormat : TStringList read getFileFormat;
property FileFilter : String read FFileFilter;
property Version : string read getVersion;
end;
{ TAudio }
{*
* @brief Basic Component of Audio Player
*}
//TAudio = class(TObject)
TAudio = class(TComponent)
private
pDevice : Pointer;
pSource : Pointer;
pOutput : Pointer;
AdrDevice : TAdrAudioDevice;
AdrSource : TAdrSampleSource;
AdrOutput : TAdrOutputStream;
AdrSound : TAdrOutputStream;
AdrEffect : TAdrSoundEffect;
AdrMIDI : TAdrMIDIDevice;
AdrMusic : TAdrMIDIStream;
FDevice : string;
FFileName : string;
FIsPlaying : boolean;
FIsPausing : boolean;
FBuffer : array of byte;
FFormat : string;
FLength : Integer;
FPosition : Integer;
FLastPos : Integer;
FVolume : Integer;
FSeekable : boolean;
FRepeat : boolean;
FTags : TStringList;
FErrorCode : TErrorCode;
protected
function getName: string;
function isSeekable: Boolean;
function getFormat:string;
function getLength:Integer;
procedure setVolume(aVolume:integer);
function getVolume:integer;
procedure setPosition(Position: Integer);
function getPosition: Integer;
procedure setRepeat(aRepeat: boolean);
function getRepeat: boolean;
function getTags:TStringList;
public
constructor Create(AOwner: TComponent);
destructor Destroy; override;
function isPlaying: Boolean;
function isPausing: Boolean;
published
property Device : string read getName;
property FileName : string read FFileName write FFileName;
property Playing : boolean read isPlaying;
property Pausing : boolean read isPausing;
property Format : string read getFormat;
property Length : integer read getLength;
property Position : integer read getPosition write setPosition;
property Volume : integer read getVolume write setVolume;
property Seekable : boolean read isSeekable;
property Loop : boolean read getRepeat write setRepeat;
property Tags : TStringList read FTags;
procedure open(aFile:string);
function read(sampleCount: Integer; aBuffer: Pointer): Integer;
procedure reset;
procedure play;virtual;
//procedure play(aName:string);overload;virtual;
procedure playStream;
procedure pause(OnOff:boolean);virtual;
procedure resume;virtual;
procedure stop;//virtual;
end;
{ TSound }
{*
* @brief Sound Player Component
*}
//TSound = class(TObject)
TSound = class(TAudio)
private
protected
public
constructor Create(AOwner: TComponent);
destructor Destroy; override;
published
//procedure play(aName:string);override;
procedure play;override;
//procedure stop;override;
end;
{ TMusic }
{*
* @brief MIDI Player Component
*}
TMusic = class(TAudio)
private
protected
public
constructor Create(AOwner: TComponent);
destructor Destroy; override;
published
procedure play;override;
end;
{ TEffect }
{*
* @brief Sound Effect Compnent
*}
TEffect = class(TAudio)
private
FType : TAdrSoundEffectType;
protected
public
constructor Create(AOwner: TComponent);
destructor Destroy; override;
published
property mode :TAdrSoundEffectType read FType write FType;
procedure play;override;
end;
{ TDisc }
{*
* @brief CD Player Conmponent
*}
TDisc = class(TAudio)
private
AdrDevice : TAdrCDDevice;
AdrOutput : TAdrCDDevice;
FHasCD : boolean;
FTrackCount : integer;
FTrackNumber : integer;
FDoorOpening : boolean;
protected
function isDoorOpen:boolean;
function isContainsCD:boolean;
function getTrackCount:integer;
procedure openDoor;
procedure closeDoor;
public
constructor Create(AOwner: TComponent);
destructor Destroy; override;
published
property HasCD :boolean read isContainsCD;
property DoorOpening :boolean read isDoorOpen;
property TrackCount :integer read getTrackCount;
property TrackNumber :integer read FTrackNumber;
procedure close;
procedure eject;
procedure play(aTrackNo:integer);//override;overload;
procedure pause(OnOff:boolean);
end;
{ TWaveGenerator }
{*
* @brief Generator Some Wave like single tone, Square Wave, White Noise, Pink Noise
*}
TWaveGenerator = class(TAudio)
private
protected
public
constructor Create(AOwner: TComponent);
destructor Destroy; override;
published
procedure MakePinkNoise;
procedure MakeSquareWave(aFrequency: Double);
procedure MakeTone(aFrequency: Double);
procedure MakeWhiteNoise;
procedure play;
procedure stop;
end;
TPlayMode = (pmSingle, pmSequence, pmRandom, pmRepeat, pmRepeatAll);
{ TPlayListItem }
{*
* @brief Playlist Item object
*}
TPlayListItem = class(TObject)
public
idx : LongInt;
Name : string;
Path : string;
Code : string;
Time : TDateTime;
Memo : string;
Pos : LongInt;
IsPlayed : boolean;
IsPlaying : boolean;
IsPausing : boolean;
//constructor Create(AOwner: TComponent);
constructor Create;
destructor Destroy; override;
end;
{ TPlayList }
{*
* @brief PlayList for medias
*}
TPlayList = class(TComponent)
private
FSysInfo : TAudioSystem;
FMultiPlay : boolean;
FSorting : boolean;
FIsPlaying : boolean;
FIsPausing : boolean;
FSortMode : Integer;
FCount : Integer;
FPlayMode : TPlayMode;
FFadingIn : boolean;
FFadingOut : boolean;
FItemIndex : integer;
FLastIndex : integer;
FChanged : boolean;
FItems : TObjectList;
FSound : TSound;
FTimer : TTimer;
FFilter : string;
FVolume : Integer;
protected
function GetChanged:boolean;
function GetAudio:TSound;
procedure SetAudio(aSound: TSound);
function GetItem(Index: Integer):TPlayListItem;
procedure SetItem(Index: Integer; Value: TPlayListItem);
procedure checkStatus;
function checkFile(index: integer):integer;
procedure onTimer(Sender: TObject);
procedure LoadFromList(aList: TStringList);
procedure SaveToList(var aList: TStringList);
public
//constructor Create(AOwner: TComponent);
constructor Create(AOwner: TComponent);
destructor Destroy; override;
procedure LoadFromFile(aFile: string);
procedure SaveToFile(aFile: string);
procedure Add(Value: TPlayListItem);overload;
procedure Add(Index: Integer; Value: TPlayListItem);overload;
procedure Delete(Index: Integer);
procedure Clear;
procedure Sort;
property Items[Index: Integer]: TPlayListItem read GetItem write SetItem; default;
published
property MultiPlay : boolean read FMultiPlay write FMultiPlay;
property Sorting : boolean read FSorting write FSorting;
property IsPlaying : boolean read FIsPlaying write FIsPlaying;
property IsPausing : boolean read FIsPausing write FIsPausing;
property FadingIn : boolean read FFadingIn write FFadingIn;
property FadingOut : boolean read FFadingOut write FFadingOut;
property Count : Integer read FCount write FCount;
property ItemIndex : Integer read FItemIndex write FItemIndex;
property FileFilter : string read FFilter;
property PlayMode : TPlayMode read FPlayMode write FPlayMode;
property Audio : TSound read GetAudio;// write FSound;
property Changed : boolean read GetChanged;// write FSound;
procedure play(index: integer);
procedure pause(OnOff:boolean);
procedure resume;
procedure stop;
procedure first;
procedure prev;
procedure next;
procedure last;
end;
implementation
resourcestring
DEVICE_AUTO_DETECT = 'AutoDetect: Choose default device';
{-------------------------------------------------------------------------------
过程名: Register
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
procedure Register;
begin
RegisterComponents('Audiere Lib', [TAudioSystem, TPlayList, TSound, TMusic, TEffect,
TDisc, TWaveGenerator]);
end;
{ TStopCallBack }
constructor TStopCallBack.Create;
begin
end;
destructor TStopCallBack.Destroy;
begin
inherited;
end;
procedure TStopCallBack.call(event: TAdrStopEvent);
begin
FIsPlaying := false;
FResult:='';
if event.getReason() = STOP_CALLED then
FResult := FResult+'Stop Called'+#$0a
else if event.getReason() = STREAM_ENDED then
FResult := FResult+'Stream Ended'+#$0a
else
FResult := FResult+'Unknown'+#$0a;
if (event.getOutputStream() = g_sound) then
begin
FResult := FResult+'Deleting sound'+#$0a;
g_sound := nil;
end
else if (event.getOutputStream() = g_stream) then
begin
FResult := FResult+'Deleting stream'+#$0a;
g_stream := nil;
end;
end;
{-------------------------------------------------------------------------------
过程名: TStopCallBack.streamStopped
作者: netcharm
日期: 2009.08.11
参数: event: TAdrStopEvent
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/08/11 : Original Version
* @param event TAdrStopEvent
* @result 无
* @brief
*}
//******************************************************************************
procedure TStopCallBack.streamStopped(event: TAdrStopEvent);
begin
FIsPlaying := false;
FResult:='';
if event.getReason() = STOP_CALLED then
FResult := FResult+'Stop Called'+#$0a
else if event.getReason() = STREAM_ENDED then
FResult := FResult+'Stream Ended'+#$0a
else
FResult := FResult+'Unknown'+#$0a;
if (event.getOutputStream() = g_sound) then
begin
FResult := FResult+'Deleting sound'+#$0a;
g_sound := nil;
end
else if (event.getOutputStream() = g_stream) then
begin
FResult := FResult+'Deleting stream'+#$0a;
g_stream := nil;
end;
end;
//
{ TWaveGenerator }
{-------------------------------------------------------------------------------
过程名: TWaveGenerator.Create
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
constructor TWaveGenerator.Create(AOwner: TComponent);
begin
inherited;
try
if not assigned(AdrDevice) then
AdrDevice := AdrOpenDevice('', '');
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TWaveGenerator.Destroy
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
destructor TWaveGenerator.Destroy;
begin
// if assigned(AdrOutput) then AdrOutput.UnRef;
// if assigned(AdrSource) then AdrSource.UnRef;
// if assigned(AdrDevice) then AdrDevice.UnRef;
inherited;
end;
{-------------------------------------------------------------------------------
过程名: TWaveGenerator.MakeSquareWave
作者: netcharm
日期: 2009.07.26
参数: aFrequency: Double
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @param aFrequency Double
* @result 无
* @brief
*}
//******************************************************************************
procedure TWaveGenerator.MakeSquareWave(aFrequency: Double);
begin
try
if assigned(AdrDevice) then
begin
//AdrSource:=TWaveSquareWaveBuffer.Create(aFrequency);
AdrSource:=AdrCreateSquareWave(aFrequency);
end;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TWaveGenerator.MakeTone
作者: netcharm
日期: 2009.07.26
参数: aFrequency: Double
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @param aFrequency Double
* @result 无
* @brief
*}
//******************************************************************************
procedure TWaveGenerator.MakeTone(aFrequency: Double);
begin
try
if assigned(AdrDevice) then
begin
//AdrSource:=TWaveToneBuffer.Create(aFrequency);
AdrSource:=AdrCreateTone(aFrequency);
end;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TWaveGenerator.MakePinkNoise
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
procedure TWaveGenerator.MakePinkNoise;
begin
try
if assigned(AdrDevice) then
begin
//AdrSource:=TWavePinkNoiseBuffer.Create;
AdrSource:=AdrCreatePinkNoise;
end;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TWaveGenerator.MakeWhiteNoise
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
procedure TWaveGenerator.MakeWhiteNoise;
begin
try
if assigned(AdrDevice) then
begin
//AdrSource:=TWaveWhiteNoiseBuffer.Create;
pSource := AdrCreateWhiteNoise;
AdrSource := pSource;
end;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TWaveGenerator.play
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
procedure TWaveGenerator.play;
begin
try
if assigned(AdrOutput) then
begin
if AdrOutput.isPlaying then AdrOutput.stop;
if AdrOutput.InstanceSize<4 then
begin
pOutput := AdrOpenSound(AdrDevice, AdrSource, true);
AdrOutput := pOutput;
end;
end
else
begin
pOutput := AdrOpenSound(AdrDevice, AdrSource, true);
AdrOutput := pOutput;
end;
AdrOutput.Ref;
AdrOutput.Play;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TWaveGenerator.stop
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
procedure TWaveGenerator.stop;
begin
try
if assigned(AdrOutput) then
begin
if AdrOutput.IsPlaying then
begin
AdrOutput.Stop;
AdrOutput.UnRef;
end;
AdrOutput:=nil;
end;
except
end;
inherited;
end;
{ TAudio }
{-------------------------------------------------------------------------------
过程名: TAudio.Create
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
constructor TAudio.Create(AOwner: TComponent);
begin
inherited;
FDevice := '';
FFileName := '';
FIsPlaying := false;
FFormat := '';
FLength := 0;
FPosition := 0;
FLastPos := 0;
FVolume := 0;
FSeekable := false;
FRepeat := false;
FIsPausing := false;
FTags := TStringList.Create;
end;
{-------------------------------------------------------------------------------
过程名: TAudio.Destroy
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
destructor TAudio.Destroy;
begin
try
if assigned(FTags) then FreeAndNil(FTags);
// if assigned(AdrOutput) then AdrOutput.UnRef;
// if assigned(AdrSource) then Adrsource.UnRef;
// if assigned(AdrDevice) then AdrDevice.UnRef;
// if assigned(AdrSound) then AdrSound.UnRef;
// if assigned(AdrEffect) then AdrEffect.UnRef;
// if assigned(AdrMIDI) then AdrMIDI.UnRef;
// if assigned(AdrMusic) then AdrMusic.UnRef;
// AdrSound := nil;
// AdrEffect := nil;
// AdrMIDI := nil;
// AdrMusic := nil;
// AdrOutput := nil;
// Adrsource := nil;
// AdrDevice := nil;
// pOutput := nil;
// pSource := nil;
// pDevice := nil;
AdrSound := nil;
AdrEffect := nil;
AdrMIDI := nil;
AdrMusic := nil;
AdrOutput := nil;
Adrsource := nil;
AdrDevice := nil;
pOutput := nil;
pSource := nil;
pDevice := nil;
except
end;
inherited;
end;
{-------------------------------------------------------------------------------
过程名: TAudio.getFormat
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: string
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result string
* @brief
*}
//******************************************************************************
function TAudio.getFormat: string;
begin
//AdrSource.get
end;
{-------------------------------------------------------------------------------
过程名: TAudio.getLength
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: Integer
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result Integer
* @brief
*}
//******************************************************************************
function TAudio.getLength: Integer;
begin
result:=0;
try
if assigned(AdrOutput) then
FLength:=AdrOutput.GetLength
else
FLength:=0;
result:=FLength;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TAudio.getName
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: string
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result string
* @brief
*}
//******************************************************************************
function TAudio.getName: string;
begin
result:='';
try
if assigned(AdrDevice) then
begin
FDevice:=AdrDevice.getName;
result:=FDevice;
end;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TAudio.getPosition
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: Integer
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result Integer
* @brief
*}
//******************************************************************************
function TAudio.getPosition: Integer;
begin
result:=0;
try
if isSeekable then
begin
begin
if assigned(AdrOutput) then
FPosition:=AdrOutput.GetPosition
else
FPosition:=0;
end;
end;
result:=FPosition;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TAudio.getRepeat
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: boolean
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result boolean
* @brief
*}
//******************************************************************************
function TAudio.getRepeat: boolean;
begin
result:=false;
try
if assigned(AdrOutput) then
FRepeat:=AdrOutput.GetRepeat
else
FRepeat:=false;
result:=FRepeat;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TAudio.getTags
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: TStringList
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result TStringList
* @brief
*}
//******************************************************************************
function TAudio.getTags: TStringList;
var
I: Integer;
tag:TTag;
begin
result:=nil;
if not assigned(FTags) then
FTags:=TStringList.Create;
try
FTags.Clear;
if assigned(AdrSource) then
begin
FTags.NameValueSeparator:='=';
for I := 0 to AdrSource.getTagCount - 1 do
begin
tag.key := Trim(AdrSource.getTagKey(I));
tag.value := Trim(AdrSource.getTagValue(I));
tag.category := Trim(AdrSource.getTagType(I));
if UTF8Decode(tag.key) <>'' then
tag.key := UTF8Decode(tag.key);
if UTF8Decode(tag.value) <>'' then
tag.value := UTF8Decode(tag.value);
if UTF8Decode(tag.category)<>'' then
tag.category := UTF8Decode(tag.category);
FTags.AddObject(tag.key+'='+tag.value,tag);
end;
end
finally
//Tags.Assign(FTags);
result:=FTags;
end;
end;
{-------------------------------------------------------------------------------
过程名: TAudio.getVolume
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: integer
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result integer
* @brief
*}
//******************************************************************************
function TAudio.getVolume: integer;
begin
result:=FVolume;
try
if assigned(AdrOutput) then
FVolume:=Trunc(AdrOutput.GetVolume*100);
result:=FVolume;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TAudio.isPlaying
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: Boolean
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result Boolean
* @brief
*}
//******************************************************************************
function TAudio.isPausing: Boolean;
begin
try
//if FIsPausing then
result:=FIsPausing;
except
result:=false;
end;
end;
function TAudio.isPlaying: Boolean;
begin
try
//if assigned(pOutput) then
if assigned(AdrOutput) then
FIsPlaying:=AdrOutput.IsPlaying
else
FIsPlaying:=false;
result:=FIsPlaying;
except
result:=false;
end;
end;
{-------------------------------------------------------------------------------
过程名: TAudio.isSeekable
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: Boolean
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result Boolean
* @brief
*}
//******************************************************************************
function TAudio.isSeekable: Boolean;
begin
result:=false;
try
if assigned(AdrOutput) then
FSeekable:=AdrOutput.IsSeekable
else
FSeekable:=false;
result:=FSeekable;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TAudio.open
作者: netcharm
日期: 2009.07.26
参数: aFile: string
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @param aFile string
* @result 无
* @brief
*}
//******************************************************************************
procedure TAudio.open(aFile: string);
begin
end;
{-------------------------------------------------------------------------------
过程名: TAudio.pause
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
procedure TAudio.pause(OnOff:boolean);
begin
FIsPausing:=OnOff;
try
if OnOff then
begin
if assigned(AdrOutput) then
begin
FLastPos:=AdrOutput.GetPosition;
AdrOutput.Stop;
end;
end
else
begin
if assigned(AdrOutput) then
begin
AdrOutput.SetPosition(FLastPos);
AdrOutput.Ref;
AdrOutput.Play;
end;
end;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TAudio.playStream
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
procedure TAudio.play;
begin
end;
procedure TAudio.playStream;
begin
end;
{-------------------------------------------------------------------------------
过程名: TAudio.read
作者: netcharm
日期: 2009.07.26
参数: sampleCount: Integer; aBuffer: Pointer
返回值: Integer
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @param sampleCount Integer
* @param aBuffer Pointer
* @result Integer
* @brief
*}
//******************************************************************************
function TAudio.read(sampleCount: Integer; aBuffer: Pointer): Integer;
begin
result:=0;
end;
{-------------------------------------------------------------------------------
过程名: TAudio.reset
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
procedure TAudio.reset;
begin
try
if assigned(AdrOutput) then
AdrOutput.Reset;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TAudio.resume
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
procedure TAudio.resume;
begin
FIsPausing:=false;
try
if assigned(AdrOutput) then
begin
AdrOutput.SetPosition(FLastPos);
AdrOutput.Ref;
AdrOutput.Play;
end;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TAudio.setPosition
作者: netcharm
日期: 2009.07.26
参数: Position: Integer
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @param Position Integer
* @result 无
* @brief
*}
//******************************************************************************
procedure TAudio.setPosition(Position: Integer);
begin
try
if isSeekable then
begin
FPosition:=Position;
if assigned(AdrOutput) then
AdrOutput.SetPosition(FPosition);
end;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TAudio.setRepeat
作者: netcharm
日期: 2009.07.26
参数: aRepeat: boolean
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @param aRepeat boolean
* @result 无
* @brief
*}
//******************************************************************************
procedure TAudio.setRepeat(aRepeat: boolean);
begin
try
FRepeat:=aRepeat;
if assigned(AdrOutput) then
AdrOutput.SetRepeat(FRepeat);
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TAudio.setVolume
作者: netcharm
日期: 2009.07.26
参数: aVolume: integer
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @param aVolume integer
* @result 无
* @brief
*}
//******************************************************************************
procedure TAudio.setVolume(aVolume: integer);
begin
try
FVolume:=aVolume;
if assigned(AdrOutput) then
AdrOutput.SetVolume(FVolume/100);
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TAudio.stop
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
procedure TAudio.stop;
begin
try
if assigned(AdrOutput) then
begin
if isPlaying then
begin
AdrOutput.Stop;
Sleep(50);
end;
if Position>=Length then
Sleep(100);
AdrOutput.Unref;
Sleep(50);
AdrOutput:=nil;
Sleep(100);
end;
except
end;
end;
{ TSound }
{-------------------------------------------------------------------------------
过程名: TSound.Create
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
constructor TSound.Create;
begin
inherited;
try
//if not assigned(pDevice) then
if not assigned(AdrDevice) then
begin
AdrDevice := AdrOpenDevice('', '');
//pDevice := AdrOpenDevice('', '');
//AdrDevice := pDevice;
FDevice := AdrDevice.getName;
// if Assigned(AdrDevice) then
// AdrDevice.Ref;
end;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TSound.Destroy
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
destructor TSound.Destroy;
begin
//if assigned(FTags) then FreeAndNil(FTags);
If FIsPlaying or FIsPausing then stop;
if assigned(AdrDevice) then AdrDevice.UnRef;
inherited;
end;
{-------------------------------------------------------------------------------
过程名: TSound.play
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
procedure TSound.play;
begin
try
FErrorCode:=ecNoError;
FIsPausing:=false;
if not assigned(AdrDevice) then
begin
AdrDevice := AdrOpenDevice('', '');
FDevice := AdrDevice.getName;
end;
if assigned(AdrDevice) then
begin
if not FileExists(FFileName) then
begin
FErrorCode:=ecNoFile;
exit;
end;
if AdrSource <> nil then AdrSource := nil;
AdrSource := AdrOpenSampleSource(PAnsiChar(FFileName),FF_AUTODETECT);
if AdrSource = nil then
begin
FErrorCode:=ecLoading;
exit;
end;
if AdrOutput <> nil then AdrOutput := nil;
AdrOutput := AdrOpenSound(AdrDevice, AdrSource, true);
if AdrOutput = nil then
begin
FErrorCode:=ecOpening;
exit;
end;
AdrOutput.Ref;
AdrOutput.SetVolume(FVolume/100);
AdrOutput.Play;
getTags;
end
else
FErrorCode:=ecDevice;
except
end;
end;
{ TMusic }
{-------------------------------------------------------------------------------
过程名: TMusic.Create
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
constructor TMusic.Create(AOwner: TComponent);
begin
inherited;
//FTags:=TStringList.Create;
try
if not assigned(AdrDevice) then
begin
//AdrDevice := AdrOpenMIDIDevice('');
pDevice := AdrOpenMIDIDevice('');
AdrMIDI := pDevice;
//FDevice := AdrDevice.GetName;
end;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TMusic.Destroy
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
destructor TMusic.Destroy;
begin
try
//if assigned(FTags) then FreeAndNil(FTags);
if assigned(AdrDevice) then
begin
AdrDevice.UnRef;
AdrDevice:=nil;
end;
except
end;
inherited;
end;
{-------------------------------------------------------------------------------
过程名: TMusic.play
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
procedure TMusic.play;
begin
try
if assigned(AdrDevice) then
begin
//AdrMusic:=AdrDevice.OpenStream(PChar(FFileName));
pOutput := AdrMIDI.OpenStream(PChar(FFileName));
AdrMusic := pOutput;
if AdrMusic.InstanceSize>4 then
begin
AdrMusic.Ref;
AdrMusic.play;
getTags;
end;
end;
finally
end;
end;
{ TEffect }
{-------------------------------------------------------------------------------
过程名: TEffect.Create
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
constructor TEffect.Create;
begin
inherited;
try
if not assigned(AdrDevice) then
begin
//AdrDevice := AdrOpenDevice('', '');
pDevice :=AdrOpenDevice('', '');
AdrDevice := pDevice;
end;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TEffect.Destroy
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
destructor TEffect.Destroy;
begin
try
if assigned(AdrEffect) then
begin
AdrEffect.UnRef;
AdrEffect:=nil;
end;
except
end;
inherited;
end;
{-------------------------------------------------------------------------------
过程名: TEffect.play
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
procedure TEffect.play;
begin
try
if assigned(AdrDevice) then
begin
//AdrSource := AdrOpenSampleSource(PAnsiChar(FFileName),FF_AUTODETECT);
pSource := AdrOpenSampleSource(PAnsiChar(FFileName),FF_AUTODETECT);
AdrSource := pSource;
AdrSource.ref;
//AdrEffect := AdrOpenSoundEffect(AdrDevice, AdrSource, Adr_SoundEffectType_Multiple);
pOutput := AdrOpenSoundEffect(AdrDevice, AdrSource, Adr_SoundEffectType_Multiple);
AdrOutput := pOutput;
AdrEffect := pOutput;
AdrEffect.Ref;
AdrEffect.Play;
getTags;
end;
except
end;
end;
{ TDisc }
{-------------------------------------------------------------------------------
过程名: TDisc.close
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
procedure TDisc.close;
begin
try
closeDoor;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TDisc.closeDoor
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
procedure TDisc.closeDoor;
begin
try
if assigned(AdrOutput) then
AdrOutput.closeDoor;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TDisc.Create
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
constructor TDisc.Create;
begin
inherited;
try
if not assigned(AdrOutput) then
AdrOutput := AdrOpenCDDevice('');
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TDisc.Destroy
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
destructor TDisc.Destroy;
begin
inherited;
end;
{-------------------------------------------------------------------------------
过程名: TDisc.eject
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
procedure TDisc.eject;
begin
try
openDoor;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TDisc.getTrackCount
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: integer
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result integer
* @brief
*}
//******************************************************************************
function TDisc.getTrackCount: integer;
begin
result:=-1;
try
if assigned(AdrOutput) then
FTrackCount:=AdrOutput.getTrackCount;
result:=FTrackCount;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TDisc.isContainsCD
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: boolean
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result boolean
* @brief
*}
//******************************************************************************
function TDisc.isContainsCD: boolean;
begin
result:=false;
FHasCD:=false;
try
if assigned(AdrOutput) then
FHasCD:=AdrOutput.containsCD;
result:=FHasCD;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TDisc.isDoorOpen
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: boolean
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result boolean
* @brief
*}
//******************************************************************************
function TDisc.isDoorOpen: boolean;
begin
result:=false;
FDoorOpening:=false;
try
if assigned(AdrOutput) then
FDoorOpening:=AdrOutput.isDoorOpen;
result:=FDoorOpening;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TDisc.openDoor
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
procedure TDisc.openDoor;
begin
try
if assigned(AdrOutput) then
AdrOutput.openDoor;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TDisc.play
作者: netcharm
日期: 2009.07.26
参数: aTrackNo: integer
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @param aTrackNo integer
* @result 无
* @brief
*}
//******************************************************************************
procedure TDisc.pause(OnOff:boolean);
begin
inherited;
end;
{-------------------------------------------------------------------------------
过程名: TDisc.play
作者: netcharm
日期: 2009.08.11
参数: aTrackNo: integer
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/08/11 : Original Version
* @param aTrackNo integer
* @result 无
* @brief
*}
//******************************************************************************
procedure TDisc.play(aTrackNo: integer);
begin
try
if assigned(AdrOutput) then
begin
AdrOutput.Ref;
AdrOutput.play(aTrackNo);
end;
except
end;
end;
{ TAudioSystem }
{-------------------------------------------------------------------------------
过程名: TAudioSystem.Create
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
constructor TAudioSystem.Create(AOwner: TComponent);
begin
inherited;
FVersion := '';
FDiscDevice := TStringList.Create;
FAudioDevice := TStringList.Create;
FFileFormat := TStringList.Create;
try
FDiscDevice.Delimiter := ';';
FAudioDevice.Delimiter := ';';
FFileFormat.Delimiter := ';';
getVersion;
getAudioDevice;
getDiscDevice;
getFileFormat;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TAudioSystem.Destroy
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
destructor TAudioSystem.Destroy;
begin
if assigned(FDiscDevice) then FreeAndNil(FDiscDevice);
if assigned(FAudioDevice) then FreeAndNil(FAudioDevice);
if assigned(FFileFormat) then FreeAndNil(FFileFormat);
inherited;
end;
{-------------------------------------------------------------------------------
过程名: TAudioSystem.getAudioDevice
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: TStringList
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result TStringList
* @brief
*}
//******************************************************************************
function TAudioSystem.getAudioDevice: TStringList;
var
device:TAudioDeviceDesc;
str:string;
idx,sep:integer;
begin
result:=nil;
try
str:=AdrGetSupportedAudioDevices+';';
FAudioDevice.Clear;
FAudioDevice.Append(DEVICE_AUTO_DETECT);
idx:=Pos(';',str);
repeat
FAudioDevice.Append(copy(str, 1, idx-1));
device.name:=copy(str, 1, idx-1);
sep:=Pos(':', device.name);
device.description:=copy(device.name, sep+1, length(device.name)-sep-1);
delete(device.name, sep, length(device.name)-sep);
delete(str,1,idx);
idx:=Pos(';',str);
until idx<=0;
//FAudioDevice.Append(_('AutoDetect: Choose default device'));
result:=FAudioDevice;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TAudioSystem.getDiscDevice
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: TStringList
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result TStringList
* @brief
*}
//******************************************************************************
function TAudioSystem.getDiscDevice: TStringList;
var
device:TAudioDeviceDesc;
str:string;
idx,sep:integer;
begin
result:=nil;
try
str:=AdrEnumerateCDDevices+';';
FDiscDevice.Clear;
FDiscDevice.Append(DEVICE_AUTO_DETECT);
idx:=Pos(';',str);
repeat
FDiscDevice.Append(copy(str, 1, idx-1));
device.name:=copy(str, 1, idx-1);
sep:=Pos(':', device.name);
device.description:=copy(device.name, sep+1, length(device.name)-sep-1);
delete(device.name, sep, length(device.name)-sep);
delete(str,1,idx);
idx:=Pos(';',str);
until idx<=0;
result:=FDiscDevice;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TAudioSystem.getFileFormat
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: TStringList
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result TStringList
* @brief
*}
//******************************************************************************
function TAudioSystem.getFileFormat: TStringList;
var
device:TAudioDeviceDesc;
str,strn:string;
idx,sep:integer;
I: Integer;
begin
result:=nil;
try
str:=AdrGetSupportedFileFormats+';';
FFileFormat.Clear;
FFileFormat.Append(DEVICE_AUTO_DETECT);
idx:=Pos(';',str);
repeat
strn := copy(str, 1, idx-1);
strn := StringReplace(strn,':',' (*.',[rfReplaceAll]);
strn := StringReplace(strn,',',';*.',[rfReplaceAll]);
strn := strn+')';
FFileFormat.Append(strn);
device.name:=copy(str, 1, idx-1);
sep:=Pos(':', device.name);
device.description:=copy(device.name, sep+1, length(device.name)-sep-1);
delete(device.name, sep, length(device.name)-sep);
delete(str,1,idx);
idx:=Pos(';',str);
until idx<=0;
FFileFilter := '';
for I := 1 to FFileFormat.Count - 1 do
begin
FFileFilter := FFileFilter + FFileFormat[I];
FFileFilter := StringReplace(FFileFilter, '(', '|', [rfReplaceAll]);
FFileFilter := StringReplace(FFileFilter, ')', '|', [rfReplaceAll]);
FFileFilter := StringReplace(FFileFilter, '"', '', [rfReplaceAll]);
end;
Delete(FFileFilter,Length(FFileFilter),1);
result:=FFileFormat;
except
end;
end;
{-------------------------------------------------------------------------------
过程名: TAudioSystem.getVersion
作者: netcharm
日期: 2009.07.26
参数: 无
返回值: string
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/07/26 : Original Version
* @result string
* @brief
*}
//******************************************************************************
function TAudioSystem.getVersion: string;
begin
result:='';
try
result:=AdrGetVersion;
except
end;
end;
{ TPlayList }
//constructor TPlayList.Create(AOwner: TComponent);
constructor TPlayList.Create(AOwner: TComponent);
begin
inherited;
FSysInfo := TAudioSystem.Create(AOwner);
FMultiPlay := false;
FSorting := true;
FPlayMode := pmSingle;
FSortMode := 0;
FCount := 0;
FFilter := 'Playlist File|*.m3u;';
FItems := TObjectList.Create;
FItems.Clear;
FTimer := TTimer.Create(Self);
FTimer.Enabled := false;
FTimer.Interval:= 75;
FTimer.OnTimer := onTimer;
FTimer.Enabled := true;
//FSound := TSound.Create;
end;
destructor TPlayList.Destroy;
begin
try
if assigned(FTimer) then
begin
FTimer.Enabled:=false;
FTimer.OnTimer:=nil;
FreeAndNil(FTimer);
end;
if assigned(FSysInfo) then FreeAndNil(FSysInfo);
if (FIsPlaying or FIsPausing) then stop;
sleep(100);
if assigned(FItems) then
begin
FItems.Clear;
FreeAndNil(FItems);
end;
if assigned(FSound) then
begin
FreeAndNil(FSound);
//FSound.Free;
end;
except
end;
inherited;
end;
procedure TPlayList.Add(Value: TPlayListItem);
begin
try
FItems.Add(Value);
FCount:=FItems.Count;
FChanged:=true;
except
end;
end;
procedure TPlayList.Add(Index: Integer; Value: TPlayListItem);
begin
try
FItems.Insert(Index, Value);
FCount:=FItems.Count;
FChanged:=true;
except
end;
end;
function TPlayList.checkFile(index: integer): integer;
var
rExt:string;
begin
result:=index;
try
while not FileExists(TPlayListItem(FItems[result]).Path) do
begin
result:=result+1;
if result>=FItems.Count then
begin
//result:=Fitems.Count-1;
result:=-1;
break;
end;
end ;
repeat
rExt:=ExtractFileExt(TPlayListItem(FItems[result]).Path);
result:=result+1;
if result>FItems.Count then
begin
//result:=Fitems.Count-1;
result:=0;
break;
end;
until (Pos(UpperCase(rExt), UpperCase(FSysInfo.FileFilter))>0);
result:=result-1;
except
result:=-1;
end;
end;
procedure TPlayList.checkStatus;
begin
try
exit;
if FIsPlaying then
begin
if FLastIndex=FItemIndex then Exit;
FLastIndex:=FItemIndex;
end;
except
end;
end;
procedure TPlayList.Clear;
begin
try
FItems.Clear;
FCount:=FItems.Count;
FItemIndex:=-1;
FChanged:=true;
except
end;
end;
procedure TPlayList.Delete(Index: Integer);
begin
try
if Index=FItemIndex then
begin
stop;
prev;
end
else if Index<FItemIndex then
FItemIndex:=FItemIndex-1;
FItems.Delete(index);
FCount:=FItems.Count;
if FCount<=0 then FItemIndex:=-1;
FChanged:=true;
except
end;
end;
procedure TPlayList.first;
begin
try
if FCount>0 then FItemIndex:=0
else FItemIndex:=-1;
checkStatus;
except
end;
end;
function TPlayList.GetAudio: TSound;
begin
result:=nil;
try
if assigned(FSound) then
result:=FSound;
except
end;
end;
function TPlayList.GetChanged: boolean;
begin
result:=FChanged;
FChanged:=false;
end;
function TPlayList.GetItem(Index: Integer): TPlayListItem;
begin
result:=nil;
try
if (Index<0) or (Index>=FCount) then
result:=nil
else
result:=TPlayListItem(FItems[Index]);
except
end;
end;
procedure TPlayList.last;
begin
try
if FCount>0 then FItemIndex:=FCount-1
else FItemIndex:=-1;
checkStatus;
except
end;
end;
procedure TPlayList.LoadFromFile(aFile: string);
var
I: Integer;
fPath, fName, dPath:string;
aFT: TStringList;
begin
if not FileExists(aFile) then exit;
aFT := TStringList.Create;
try
dPath:=ExtractFilePath(aFile);
aFT.LoadFromFile(aFile);
for I := 0 to aFT.Count - 1 do
begin
aFT[I]:=trim(aFT[I]);
if aFT[I]='' then continue;
if aFT[I][1]='#' then continue;
fPath:=ExtractFilePath(aFT[I]);
fName:=ExtractFileName(aFT[I]);
if fName='' then continue;
add(TPlayListItem.Create());
TPlayListItem(FItems.Last).idx := Count-1;
TPlayListItem(FItems.Last).Name := ChangeFileExt(fName,'');
if ExtractFileDrive(aFT[I])<>'' then
TPlayListItem(FItems.Last).Path := aFT[I]
else
TPlayListItem(FItems.Last).Path := dPath+aFT[I];
TPlayListItem(FItems.Last).Code := 'utf-8';
TPlayListItem(FItems.Last).Time := EncodeTime(0,0,0,0);
TPlayListItem(FItems.Last).Memo := '';
TPlayListItem(FItems.Last).Pos := 0;
end;
finally
aFT.Free;
FItemIndex:=0;
end;
end;
procedure TPlayList.LoadFromList(aList: TStringList);
var
I: Integer;
fN, fName:string;
begin
try
for I := 0 to aList.Count - 1 do
begin
fN := trim(aList[I]);
fName:=ExtractFileName(fN);
add(TPlayListItem.Create());
TPlayListItem(FItems.Last).idx := Count-1;
TPlayListItem(FItems.Last).Name := ChangeFileExt(fName,'');
TPlayListItem(FItems.Last).Path := fN;
TPlayListItem(FItems.Last).Code := 'utf-8';
TPlayListItem(FItems.Last).Time := EncodeTime(0,0,0,0);
TPlayListItem(FItems.Last).Memo := '';
TPlayListItem(FItems.Last).Pos := 0;
//FItems.Items.du
end;
finally
end;
end;
procedure TPlayList.SaveToFile(aFile: string);
var
I: Integer;
rPath, fPath, fName, dPath:string;
aFT: TStringList;
begin
aFT := TStringList.Create;
try
dPath:=ExtractFilePath(aFile);
aFT.Add('#EXTM3U');
for I := 0 to FItems.Count - 1 do
begin
//aFT.Add('');
aFT.Add('# '+TPlayListItem(FItems[I]).Name);
aFT.Add('# '+TPlayListItem(FItems[I]).Memo);
fPath:=ExtractFilePath(TPlayListItem(FItems[I]).Path);
fName:=ExtractFileName(TPlayListItem(FItems[I]).Path);
rPath:=PathGetRelativePath(rPath, dPath);
if dPath=fPath then
aFT.Add(fName)
else
aFT.Add(TPlayListItem(FItems[I]).Path);
end;
aFT.SaveToFile(aFile);
finally
aFT.Free;
end;
end;
procedure TPlayList.SaveToList(var aList: TStringList);
begin
end;
procedure TPlayList.next;
begin
try
if FCount>0 then
begin
if FItemIndex>=(FCount-1) then
FItemIndex:=FCount-1
else
FItemIndex:=FItemIndex+1;
end
else FItemIndex:=-1;
checkStatus;
except
end;
end;
procedure TPlayList.onTimer(Sender: TObject);
begin
//exit;
if (not (IsPlaying or IsPausing)) then exit;
if not assigned(FSound) then exit;
// if FSound.isPlaying or FSound.isPausing then
if FSound.isPlaying then
begin
FVolume:=FSound.Volume;
if FSound.Loop then
FSound.Loop:=false;
end;
try
//exit;
case FPlayMode of
pmSingle : begin
//if (not FSound.isPlaying) And (assigned(FSound))then
//if (assigned(FSound))then
begin
if not ((FSound.isPlaying or FSound.isPausing)) then stop;
end;
end;
pmSequence : begin
//if (not FSound.isPlaying) And (assigned(FSound)) then
if (not (FSound.isPlaying or FSound.isPausing)) then
begin
if FItemIndex+1<FCount then
play(FItemIndex+1)
else
stop;
end;
end;
pmRandom : begin
//if (not FSound.isPlaying) And (assigned(FSound))then
if (not (FSound.isPlaying or FSound.isPausing)) then
begin
play(Random(FCount));
end;
end;
pmRepeat : begin
//if (FSound.isPlaying) And (assigned(FSound))then
//if (assigned(FSound))then
//if (not (FSound.isPlaying or FSound.isPausing)) then
begin
FSound.Loop:=true;
end;
end;
pmRepeatAll : begin
//if (not FSound.isPlaying) And (assigned(FSound))then
if (not (FSound.isPlaying or FSound.isPausing)) then
begin
if FItemIndex+1>=FCount then FItemIndex:=-1;
sleep(50);
play(FItemIndex+1);
end;
end;
end;
except
end;
end;
procedure TPlayList.pause(OnOff:boolean);
begin
try
TPlayListItem(FItems[FItemIndex]).IsPausing:=OnOff;
FSound.pause(OnOff);
checkStatus;
except
end;
end;
procedure TPlayList.play(index: integer);
begin
if index<0 then exit;
if index>FCount-1 then exit;
if (index=FItemIndex) and (FIsPlaying) then exit;
try
if assigned(FTimer) then FTimer.Enabled:=false;
if FItemIndex>=0 then
begin
TPlayListItem(FItems[FItemIndex]).IsPlaying:=false;
TPlayListItem(FItems[FItemIndex]).IsPausing:=false;
stop;
end;
FItemIndex:=checkFile(index);
if FItemIndex=-1 then
begin
IsPlaying:=false;
IsPausing:=false;
exit;
end;
if not assigned(FSound) then FSound := TSound.Create(Self);
//FSound.open(TPlayListItem(FItems[index]).Path);
repeat
FSound.FileName:=TPlayListItem(FItems[FItemIndex]).Path;
FSound.SetVolume(FVolume);
FSound.play;
if FSound.FErrorCode<>ecNoError then
begin
Sleep(250);
FItemIndex:=FItemIndex+1;
if FItemIndex>=FCount then
begin
FSound.Stop;
//FSound.Free;
exit;
end;
end;
until FSound.FErrorCode=ecNoError;
TPlayListItem(FItems[FItemIndex]).IsPlaying:=FSound.isPlaying;
TPlayListItem(FItems[FItemIndex]).IsPausing:=False;
FIsPlaying:=FSound.isPlaying;
FIsPausing:=False;
FChanged:=true;
if assigned(FTimer) then FTimer.Enabled:=true;
except
end;
end;
procedure TPlayList.prev;
begin
try
if FCount>0 then
begin
if FItemIndex<=0 then
FItemIndex:=0
else
FItemIndex:=FItemIndex-1;
end
else FItemIndex:=-1;
checkStatus;
except
end;
end;
procedure TPlayList.resume;
begin
try
FSound.resume;
checkStatus;
except
end;
end;
procedure TPlayList.SetAudio(aSound: TSound);
begin
//
end;
procedure TPlayList.SetItem(Index: Integer; Value: TPlayListItem);
begin
try
if (Index>0) And (Index<FCount) then
begin
with TPlayListItem(FItems[Index]) do
begin
idx := Value.idx;
Name := Value.Name;
Path := Value.Path;
Code := Value.Code;
Time := Value.Time;
Memo := Value.Memo;
IsPlaying := Value.IsPlaying;
IsPausing := Value.IsPausing;
end;
end;
except
end;
end;
procedure TPlayList.Sort;
begin
try
//FItems.sor
checkStatus;
except
end;
end;
procedure TPlayList.stop;
begin
try
if FCount<=0 then exit;
if assigned(FTimer) then FTimer.Enabled:=false;
FIsPausing := false;
FIsPlaying := false;
if (FItemIndex>=0) and (FItemIndex<FCount) then
begin
TPlayListItem(FItems[FItemIndex]).IsPausing := false;
TPlayListItem(FItems[FItemIndex]).IsPlaying := false;
end;
if assigned(FSound) then
begin
//if FSound.isPlaying or FSound.isPausing then
FSound.stop;
//FSound.Free;
//FreeAndNil(FSound);
end;
checkStatus;
except
end;
end;
{ TPlayListItem }
constructor TPlayListItem.Create;
begin
inherited;
idx := 0;
Name := '';
Path := '';
Code := 'utf-8';
Time := EncodeTime(0,0,0,0);
Memo := '';
Pos := 0;
IsPlaying := false;
IsPausing := false;
end;
destructor TPlayListItem.Destroy;
begin
inherited;
end;
{-------------------------------------------------------------------------------
过程名: 不可用
作者: netcharm
日期: 2009.08.11
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/08/11 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
initialization
begin
AdrLoadDll;
end;
{-------------------------------------------------------------------------------
过程名: 不可用
作者: netcharm
日期: 2009.08.11
参数: 无
返回值: 无
-------------------------------------------------------------------------------}
//******************************************************************************
{*
* @author netcharm
* @date 2009/08/11 : Original Version
* @result 无
* @brief
*}
//******************************************************************************
finalization
begin
AdrUnLoadDLL;
end;
end.
|
// файл sphereUnit.pas
unit sphereUnit;
interface
uses figureUnit, vectorUnit, colorUnit;
//-----------------------------------
type Tsphere = class( Tfigure )
protected
radius : double;
procedure set_normal( point: Tvector ); override;
public
function intersection( ray_origin : Tvector;
ray_direction : Tvector ): double;
constructor birth( center0: Tvector; color0: Tcvet;
n_spec0, v_spec0, radius0: double );
end;
//-----------------------------------
implementation
//-----------------------------------
// определяет нормаль к сфере в т. point:
// N = OPoint - OCenter, normal = N/|N|
//-----------------------------------
procedure Tsphere.set_normal( point: Tvector );
var tmp : Tvector;
begin
tmp := mult_on_scal( -1.0, center );
normal.Free;
normal := summ_vectors( point, tmp );
tmp.Free;
normal.normalization;
end;
//-----------------------------------
// Возвращает множитель t, на который нужно умножить на-
// правляющий вектор луча ray_direction, чтобы луч попал
// на сферу, если пересечения нет, то возвращает -1.0.
// Множитель t определяется из векторного уравнения:
// |ray_origin + t*ray_direction - Center_sphere| = radius,
//-----------------------------------
function Tsphere.intersection( ray_origin : Tvector;
ray_direction : Tvector
): double;
var Center_sphere, V: Tvector;
t, scalar_dV, d_sqr, v_sqr, discriminant : double;
begin
Center_sphere := mult_on_scal( -1.0, center );
V := summ_vectors( ray_origin, Center_sphere );
scalar_dV := dot_product( ray_direction, V );
d_sqr := sqr( ray_direction.get_module );
V_sqr := sqr( V.get_module );
discriminant := sqr(scalar_dV) - d_sqr*(V_sqr - sqr(radius));
if ( discriminant < 0 ) then t := -1.0
else t := -scalar_dV - sqrt( discriminant )/d_sqr;
if ( abs( t ) < 1.0E-20 ) then t := -1;
Center_sphere.Free;
V.Free;
result := t;
end;
//-----------------------------------
constructor Tsphere.birth( center0: Tvector; color0: Tcvet;
n_spec0, v_spec0, radius0: double );
begin
inherited birth( center0, color0, n_spec0, v_spec0 );
radius := radius0;
end;
//-----------------------------------
end. // конец файла sphereUnit.pas
|
unit Demo.Miscellaneous.Crosshairs;
interface
uses
System.Classes, System.SysUtils, Demo.BaseFrame, cfs.GCharts;
type
TDemo_Miscellaneous_Crosshairs = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
uses
System.Math;
procedure TDemo_Miscellaneous_Crosshairs.GenerateChart;
var
Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally
I: Integer;
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_SCATTER_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber)
]);
for I := 0 to 99 do
Chart.Data.AddRow([Random(99), Random(99)]);
// Options
Chart.Options.Legend('position', 'none');
Chart.Options.Crosshair('trigger', 'both');
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody(
'<div style="width:100%;font-family: Arial; font-size:14px; text-align: center;"><br><br>Hover over the points below, or select them, to see crosshairs</div>'
+ '<div id="Chart" style="width:100%;height:90%;"></div>'
);
GChartsFrame.DocumentGenerate('Chart', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_Miscellaneous_Crosshairs);
end.
|
unit rtti_idebinder_uTallyBinders;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, rtti_broker_iBroker, grids, controls, fgl,
rtti_idebinder_iBindings, rtti_broker_uData, StdCtrls,
rtti_idebinder_uGridBinders;
type
EListBinder = class(Exception)
end;
{ TTallyBinder }
TTallyBinder = class(TInterfacedObject, IRBTallyBinder)
private
fControl: TWinControl;
fContext: IRBBinderContext;
fClass: TClass;
fClassData: IRBData;
fDataList: IRBDataList;
protected
property Control: TWinControl read fControl;
property DataList: IRBDataList read fDataList;
property ClassData: IRBData read fClassData;
procedure BindControl; virtual; abstract;
procedure RefreshData; virtual; abstract;
function GetCurrentListIndex: integer; virtual; abstract;
public
//procedure DataToControl; virtual; abstract;
procedure Bind(const AListControl: TWinControl; const AContext: IRBBinderContext;
const AClass: TClass);
procedure Reload;
function GetCurrentData: IRBData;
class function New(const AListControl: TWinControl; const AContext: IRBBinderContext;
const AClass: TClass): IRBTallyBinder;
end;
TGridColumnBinder = class
private
fColumn: TGridColumn;
fDataList: IRBDataList;
fDataItemIndex: integer;
fDataItemName: string;
fClassData: IRBData;
protected
property Column: TGridColumn read fColumn;
procedure ResetDataItemIndex;
public
function GetData(const ARow: integer): string;
procedure Bind(const AColumn: TGridColumn; const ADataList: IRBDataList; AClassData: IRBData);
end;
TGridColumnBinders = specialize TFPGObjectList<TGridColumnBinder>;
{ TCustomDrawGridHelper }
TCustomDrawGridHelper = class helper for TCustomDrawGrid
public
procedure DefaultDrawWithText(aCol,aRow: Integer; aRect: TRect; aState: TGridDrawState; aText: String);
end;
{ TDrawGridBinder }
TDrawGridBinder = class(TTallyBinder)
private
fColumnBinders: TGridColumnBinders;
function GetGrid: TCustomDrawGrid;
protected
procedure ResetColumnBinders;
procedure DrawCellEventHandler(Sender: TObject; aCol, aRow: Integer; aRect: TRect; aState:TGridDrawState);
property Grid: TCustomDrawGrid read GetGrid;
procedure BindControl; override;
procedure RefreshData; override;
function GetCurrentListIndex: integer; override;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
end;
{ TDrawGridBinder2 }
TDrawGridBinder2 = class(TTallyBinder, IGridData)
protected
// IGridData
procedure DeleteRow(ARow: integer);
procedure InsertRow(ARow: integer);
procedure EditRow(ARow: integer);
function GetDataColCount: integer;
function GetDataItemClass(ACol: integer): IRBDataItem;
function GetDataRowCount: integer;
function GetDataItem(ACol, ARow: integer): IRBDataItem;
function GetColumnHeader(ACol: integer): string;
function IndexOfCol(const AName: string): integer;
private
fGES: TGridBinder;
protected
procedure BindControl; override;
procedure RefreshData; override;
function GetCurrentListIndex: integer; override;
protected
function GetGrid: TCustomDrawGrid;
property Grid: TCustomDrawGrid read GetGrid;
public
destructor Destroy; override;
end;
{ TListBoxBinder }
TListBoxBinder = class(TTallyBinder)
private
fDataItemIndex: integer;
function GetListBox: TCustomListBox;
protected
procedure RefreshData; override;
property ListBox: TCustomListBox read GetListBox;
procedure BindControl; override;
function GetCurrentListIndex: integer; override;
end;
{ TComboBoxBinder }
TComboBoxBinder = class(TTallyBinder)
private
fDataItemIndex: integer;
function GetComboBox: TCustomComboBox;
protected
procedure RefreshData; override;
property ComboBox: TCustomComboBox read GetComboBox;
procedure BindControl; override;
function GetCurrentListIndex: integer; override;
end;
implementation
{ TDrawGridBinder2 }
procedure TDrawGridBinder2.DeleteRow(ARow: integer);
var
mData: IRBData;
begin
mData := GetCurrentData;
if mData <> nil then begin
fContext.DataStore.Delete(mData);
fContext.DataStore.Flush;
end;
DataList.Delete(ARow);
end;
function TDrawGridBinder2.GetDataColCount: integer;
begin
Result := fClassData.Count;
end;
function TDrawGridBinder2.GetDataItemClass(ACol: integer): IRBDataItem;
begin
Result := fClassData[ACol];
end;
function TDrawGridBinder2.GetDataRowCount: integer;
begin
Result := DataList.Count;
end;
procedure TDrawGridBinder2.InsertRow(ARow: integer);
var
mData: IRBData;
begin
mData := ClassData.ClassType.Create as IRBData;
DataList.InsertData(ARow, mData);
end;
procedure TDrawGridBinder2.EditRow(ARow: integer);
var
mData: IRBData;
begin
mData := GetCurrentData;
if mData <> nil then begin
fContext.DataStore.Save(mData);
fContext.DataStore.Flush;
end;
end;
function TDrawGridBinder2.GetDataItem(ACol, ARow: integer): IRBDataItem;
begin
Result := DataList.AsData[ARow][ACol];
end;
function TDrawGridBinder2.GetColumnHeader(ACol: integer): string;
begin
Result := ClassData.Items[ACol].Name;
end;
function TDrawGridBinder2.IndexOfCol(const AName: string): integer;
begin
Result := fClassData.ItemIndex[AName];
end;
function TDrawGridBinder2.GetGrid: TCustomDrawGrid;
begin
Result := inherited Control as TCustomDrawGrid;
end;
procedure TDrawGridBinder2.BindControl;
begin
FreeAndNil(fGES);
fGES := TGridBinder.Create;
end;
procedure TDrawGridBinder2.RefreshData;
begin
fGES.Bind(Grid, Self, fContext.DataQuery);
fGES.DataToControl;
end;
function TDrawGridBinder2.GetCurrentListIndex: integer;
begin
Result := Grid.Row - Grid.FixedRows;
end;
destructor TDrawGridBinder2.Destroy;
begin
FreeAndNil(fGES);
inherited Destroy;
end;
{ TComboBoxBinder }
function TComboBoxBinder.GetComboBox: TCustomComboBox;
begin
Result := inherited Control as TCustomComboBox;
end;
procedure TComboBoxBinder.RefreshData;
var
i: integer;
begin
ComboBox.Clear;
for i := 0 to DataList.Count - 1 do
begin
ComboBox.Items.Add(DataList.AsData[i][fDataItemIndex].AsString);
end;
end;
procedure TComboBoxBinder.BindControl;
begin
fDataItemIndex := 0;
if (ComboBox.Items.Count > 0) then
begin
fDataItemIndex := ClassData.ItemIndex[ComboBox.Items[0]];
if fDataItemIndex = -1 then
fDataItemIndex := 0;
end;
end;
function TComboBoxBinder.GetCurrentListIndex: integer;
begin
Result := ComboBox.ItemIndex;
end;
{ TListBoxBinder }
function TListBoxBinder.GetListBox: TCustomListBox;
begin
Result := inherited Control as TCustomListBox;
end;
procedure TListBoxBinder.RefreshData;
var
i: integer;
begin
ListBox.Clear;
for i := 0 to DataList.Count - 1 do
begin
ListBox.Items.Add(DataList.AsData[i][fDataItemIndex].AsString);
end;
end;
procedure TListBoxBinder.BindControl;
begin
fDataItemIndex := 0;
if (ListBox.Count > 0) then
begin
fDataItemIndex := ClassData.ItemIndex[ListBox.Items[0]];
if fDataItemIndex = -1 then
fDataItemIndex := 0;
end;
end;
function TListBoxBinder.GetCurrentListIndex: integer;
begin
Result := ListBox.ItemIndex;
end;
{ TCustomDrawGridHelper }
procedure TCustomDrawGridHelper.DefaultDrawWithText(aCol, aRow: Integer;
aRect: TRect; aState: TGridDrawState; aText: String);
begin
DefaultDrawCell(aCol, aRow, aRect, aState);
DrawCellText(aCol, aRow, aRect, aState, aText);
end;
{ TGridColumnBinder }
procedure TGridColumnBinder.ResetDataItemIndex;
var
mItemName: string;
begin
fDataItemIndex := -1;
fDataItemName := '';
if Column.PickList.Count > 0 then
begin
mItemName := Column.PickList[0];
fDataItemIndex := fClassData.ItemIndex[mItemName];
fDataItemName := mItemName;
end;
end;
function TGridColumnBinder.GetData(const ARow: integer): string;
begin
if fDataItemIndex = -1 then
Result := ''
else begin
if (ARow >= 0) and (ARow < fDataList.Count) then
Result := fDataList.AsData[ARow][fDataItemIndex].AsString
else
Result := '';
end;
end;
procedure TGridColumnBinder.Bind(const AColumn: TGridColumn;
const ADataList: IRBDataList; AClassData: IRBData);
begin
fColumn := AColumn;
fDataList := ADataList;
fClassData := AClassData;
ResetDataItemIndex;
end;
{ TDrawGridBinder }
function TDrawGridBinder.GetGrid: TCustomDrawGrid;
begin
Result := inherited Control as TCustomDrawGrid;
end;
procedure TDrawGridBinder.ResetColumnBinders;
var
i, mc: integer;
mBinder: TGridColumnBinder;
begin
fColumnBinders.Clear;
for i := 0 to Grid.Columns.Count - 1 do
begin
mBinder := TGridColumnBinder.Create;
mBinder.Bind(Grid.Columns[i], DataList, ClassData);
fColumnBinders.Add(mBinder);
end;
mc := fColumnBinders.Count;
end;
procedure TDrawGridBinder.DrawCellEventHandler(Sender: TObject; aCol,
aRow: Integer; aRect: TRect; aState: TGridDrawState);
var
mData: string;
mc: integer;
begin
mc := fColumnBinders.Count;
if (ACol < 0) or (ACol > mc - 1) then
Exit;
mData := fColumnBinders[aCol].GetData(aRow - 1);
//DataList.AsData[aRow - 1][aCol].AsString := '??';
TCustomDrawGrid(Sender).DefaultDrawWithText(aCol, aRow, aRect, aState, mData);
end;
procedure TDrawGridBinder.BindControl;
begin
//RefreshData;
Grid.DefaultDrawing := True;
Grid.OnDrawCell := @DrawCellEventHandler;
end;
procedure TDrawGridBinder.RefreshData;
begin
Grid.RowCount := Grid.FixedRows + DataList.Count;
ResetColumnBinders;
end;
function TDrawGridBinder.GetCurrentListIndex: integer;
begin
Result := Grid.Row - Grid.FixedRows;
end;
procedure TDrawGridBinder.AfterConstruction;
begin
inherited AfterConstruction;
fColumnBinders := TGridColumnBinders.Create;
end;
procedure TDrawGridBinder.BeforeDestruction;
begin
FreeAndNil(fColumnBinders);
inherited BeforeDestruction;
end;
{ TTallyBinder }
procedure TTallyBinder.Bind(const AListControl: TWinControl; const AContext: IRBBinderContext;
const AClass: TClass);
begin
fControl := AListControl;
//fDataList := ADataList;
fContext := AContext;
fClass := AClass;
fClassData := TRBData.Create(fClass, True);
BindControl;
Reload;
end;
procedure TTallyBinder.Reload;
begin
fDataList := fContext.DataQuery.Retrive(fClass.ClassName);
RefreshData;
end;
function TTallyBinder.GetCurrentData: IRBData;
var
mIndex: integer;
begin
mIndex := GetCurrentListIndex;
if mIndex = -1 then
Result := nil
else
Result := fDataList.AsData[mIndex];
end;
class function TTallyBinder.New(const AListControl: TWinControl; const AContext: IRBBinderContext;
const AClass: TClass): IRBTallyBinder;
begin
if AListControl is TCustomDrawGrid then
//Result := TDrawGridBinder.Create
Result := TDrawGridBinder2.Create
else
if AListControl is TCustomListBox then
Result := TListBoxBinder.Create
else
if AListControl is TCustomComboBox then
Result := TComboBoxBinder.Create
else
raise EListBinder.CreateFmt('For %s not existis binder', [AListControl.ClassName]);
Result.Bind(AListControl, AContext, AClass);
end;
end.
|
unit EditSubStockFrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, DBClient, StdCtrls, DBCtrls, Mask, RzEdit, RzDBEdit,
RzButton, RzLabel, ExtCtrls, RzPanel,CommonLIB;
type
TfrmEditSubStock = class(TForm)
RzPanel1: TRzPanel;
RzLabel1: TRzLabel;
RzLabel3: TRzLabel;
RzLabel2: TRzLabel;
btnSave: TRzBitBtn;
btnCancel: TRzBitBtn;
RzDBEdit17: TRzDBEdit;
RzDBEdit1: TRzDBEdit;
DBCheckBox1: TDBCheckBox;
RzDBEdit2: TRzDBEdit;
cdsSubStock: TClientDataSet;
dsSubStock: TDataSource;
procedure btnCancelClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
FSubStockCode: integer;
FAppParameter: TDLLParameter;
procedure SetSubStockCode(const Value: integer);
procedure SetAppParameter(const Value: TDLLParameter);
{ Private declarations }
public
{ Public declarations }
property SubStockCode : integer read FSubStockCode write SetSubStockCode;
property AppParameter : TDLLParameter read FAppParameter write SetAppParameter;
end;
var
frmEditSubStock: TfrmEditSubStock;
implementation
uses CdeLIB,STDLIB;
{$R *.dfm}
{ TfrmEditSubStock }
procedure TfrmEditSubStock.SetAppParameter(const Value: TDLLParameter);
begin
FAppParameter := Value;
end;
procedure TfrmEditSubStock.SetSubStockCode(const Value: integer);
begin
FSubStockCode := Value;
cdsSubStock.Data :=GetDataSet('select * from ICMTTWH1 where WH1COD='+IntToStr(FSubStockCode));
end;
procedure TfrmEditSubStock.btnCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfrmEditSubStock.btnSaveClick(Sender: TObject);
var IsNew : boolean;
begin
if cdsSubStock.State in [dsinsert] then
begin
IsNew := true;
cdsSubStock.FieldByName('WH1COD').AsInteger :=getCdeRun('SETTING','RUNNING','WH1COD','CDENM1');
if cdsSubStock.FieldByName('WH1ACT').IsNull then
cdsSubStock.FieldByName('WH1ACT').AsString:='A';
setEntryUSRDT(cdsSubStock,FAppParameter.UserID);
setSystemCMP(cdsSubStock,FAppParameter.Company,FAppParameter.Branch,FAppParameter.Department,FAppParameter.Section);
end;
if cdsSubStock.State in [dsinsert,dsedit] then
setModifyUSRDT(cdsSubStock,FAppParameter.UserID);
if cdsSubStock.State in [dsedit,dsinsert] then cdsSubStock.Post;
if cdsSubStock.ChangeCount>0 then
begin
UpdateDataset(cdsSubStock,'select * from ICMTTWH1 where WH1COD='+IntToStr(FSubStockCode)) ;
if IsNew then
setCdeRun('SETTING','RUNNING','WH1COD','CDENM1');
end;
FSubStockCode:= cdsSubStock.FieldByName('WH1COD').AsInteger;
Close;
end;
procedure TfrmEditSubStock.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key=VK_ESCAPE then btnCancelClick(nil);
if Key=VK_F11 then btnSaveClick(nil);
end;
end.
|
unit ufraBonusProduct;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, Mask, uConn, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter, cxData,
cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxGridLevel, cxClasses,
cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxGrid, Vcl.Menus, cxButtons, cxContainer, cxTextEdit, cxCurrencyEdit, cxLabel,
Vcl.ComCtrls, dxCore, cxDateUtils, cxMaskEdit, cxDropDownEdit, cxCalendar;
type
TSaveBonus = (sbAdd,sbEdit);
TfraBonusProduct = class(TFrame)
pnl1: TPanel;
pnl2: TPanel;
pnlAddEdit: TPanel;
lblDelete: TcxLabel;
lbl1: TLabel;
edtProductCodeBNS: TEdit;
edtProductNamebwh: TEdit;
lbl2: TLabel;
intedtQtyOrderFrom: TcxCurrencyEdit;
lbl3: TLabel;
intedtQtyOrderTo: TcxCurrencyEdit;
lbl4: TLabel;
dtFrom: TcxDateEdit;
lbl5: TLabel;
dtTo: TcxDateEdit;
pnl4: TPanel;
lblAdd: TcxLabel;
lbl7: TLabel;
lbl8: TLabel;
intedtQtyBnsSals: TcxCurrencyEdit;
intedtQtyBnsCS: TcxCurrencyEdit;
lbl10: TLabel;
intedtTotalBonus: TcxCurrencyEdit;
lblClose: TcxLabel;
pnl3: TPanel;
lbl11: TLabel;
edtProductNameUP: TEdit;
lblEdit: TcxLabel;
chkIsActive: TCheckBox;
edtUOMPurchase: TEdit;
edtUOMCS: TEdit;
edtUOMSales: TEdit;
cxGridViewBonusProduct: TcxGridDBTableView;
cxGridLevel1: TcxGridLevel;
cxGrid: TcxGrid;
btnSave: TcxButton;
btnCancel: TcxButton;
procedure lblAddClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure lblCloseClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure strgGridCanEditCell(Sender: TObject; ARow, ACol: Integer;
var CanEdit: Boolean);
procedure lblEditClick(Sender: TObject);
procedure strgGridRowChanging(Sender: TObject; OldRow, NewRow: Integer;
var Allow: Boolean);
procedure lblDeleteClick(Sender: TObject);
procedure edtProductCodeBNSKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edtProductCodeBNSChange(Sender: TObject);
procedure intedtQtyBnsCSKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure intedtQtyBnsSalsKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
dataBonusProduct: TDataSet;
dataUom: TDataSet;
FProductCode: string;
FUntID: Integer;
modeSaveBonus: TSaveBonus;
UOM: Variant;
procedure ParseHeaderGrid(jmlData: Integer);
procedure showEditBonus();
procedure SetProductCode(const Value: string);
procedure setUntID(const Value: Integer);
procedure ClearBonusEdit();
procedure checkEmptyUOM();
public
OP_ID: Integer;
procedure ShowBonusProduct(AProductCode: String; AuntId: Integer);
published
property ProductCode: string read FProductCode write SetProductCode;
property UntID: Integer read FUntID write setUntID;
end;
var
fraBonusProduct: TfraBonusProduct;
implementation
uses uTSCommonDlg,uConstanta, ufrmProduct, ufrmMaster;
{$R *.dfm}
procedure TfraBonusProduct.lblAddClick(Sender: TObject);
begin
if UntID = 0 then
begin
CommonDlg.ShowError('UNIT BELUM DIPILIH');
Exit;
end
else
begin
pnl3.Visible := false;
pnlAddEdit.Visible := true;
chkIsActive.Checked := True;
chkIsActive.Visible := False;
edtUOMPurchase.Text := frmProduct.edtUOMPurchaseCode.Text;
ClearBonusEdit();
modeSaveBonus := sbAdd;
end;
end;
procedure TfraBonusProduct.btnCancelClick(Sender: TObject);
begin
pnlAddEdit.Visible := false;
pnl3.Visible := true;
end;
procedure TfraBonusProduct.lblCloseClick(Sender: TObject);
begin
fraBonusProduct.Parent := nil;
frmProduct.SetActiveFooter5Button(True);
end;
procedure TfraBonusProduct.ShowBonusProduct(AProductCode: String; AuntId: Integer);
var arrParamSat: TArr;
intI: Integer;
tempBool: Boolean;
begin
{Tambahan Widi 14 Nov 2007}
UntID := AuntId;
{**** DONE****}
SetLength(arrParamSat,1);
arrParamSat[0].tipe := ptInteger;
arrParamSat[0].data := AuntId;
// if not Assigned(Satuan) then Satuan := TSatuan.Create;
// dataUom := Satuan.GetListSatuan(arrParamSat);
// LoadDropDownData(cbpUOMCS,dataUom.RecordCount);
// LoadDropDownData(cbpUOMSales,dataUom.RecordCount);
// if not Assigned(BonusProduct) then BonusProduct := TBonusProduct.Create;
// dataBonusProduct := BonusProduct.GetListDataBonusProduct(AuntId,AProductCode);
ParseHeaderGrid(dataBonusProduct.RecordCount);
// put code here to parse data bonus product
// ...
{
if dataBonusProduct.RecordCount > 0 then
begin
//initiate
intI := 1;
dataBonusProduct.First;
with strgGrid do
begin
while not(dataBonusProduct.Eof) do
begin
AddCheckBox(0,intI,False,false);
// write the data to strgGRID
Cells[1,intI] := dataBonusProduct.FieldByName('BNS_ORDER_FROM').AsString;
Cells[2,intI] := dataBonusProduct.FieldByName('BNS_ORDER_TO').AsString;
Cells[3,intI] := DateToStr(dataBonusProduct.FieldByName('BNS_DATE_FROM').AsDateTime);
Cells[4,intI] := DateToStr(dataBonusProduct.FieldByName('BNS_DATE_TO').AsDateTime);
Cells[5,intI] := dataBonusProduct.FieldByName('BNS_BRG_CODE_BNS').AsString;
Cells[6,intI] := FloatToStr(dataBonusProduct.FieldByName('BNS_QTY_SALES').AsFloat);
Cells[7,intI] := FloatToStr(dataBonusProduct.FieldByName('BNS_QTY_CS').AsFloat);
Cells[8,intI] := dataBonusProduct.FieldByName('BNS_SAT_CODE_BNS').AsString;
Cells[9,intI] := FloatToStr(dataBonusProduct.FieldByName('BNS_QTY').AsFloat);
Cells[10,intI] := dataBonusProduct.FieldByName('BNS_IS_ACTIVE').AsString;
Cells[11,intI] := dataBonusProduct.FieldByName('BRG_NAME').AsString;
Cells[12,intI] := dataBonusProduct.FieldByName('BNS_ID').AsString;
//====================
Inc(intI);
dataBonusProduct.Next;
end; //end while
end; //end whith str
end;
strgGrid.SetFocus;
strgGrid.AutoSize := true;
strgGrid.FixedRows := 1;
strgGridRowChanging(Self,1,1,tempBool); }
end;
procedure TfraBonusProduct.ParseHeaderGrid(jmlData: Integer);
begin
{with strgGrid do
begin
Clear;
RowCount := jmlData + 1;
ColCount := 11;
Cells[0,0] := ' ';
Cells[1,0] := 'ORDER FROM';
Cells[2,0] := 'ORDER TO';
Cells[3,0] := 'DATE FROM';
Cells[4,0] := 'DATE TO';
Cells[5,0] := 'BONUS CODE';
Cells[6,0] := 'QTY BNS SALES';
Cells[7,0] := 'QTY BNS CS';
Cells[8,0] := 'UOM';
Cells[9,0] := 'TOTAL QTY';
Cells[10,0] := 'STATUS';
if jmlData <= 0 then
begin
RowCount:= 2;
strgGrid.AddCheckBox(0,1,False,false);
Cells[0,1] := ' ';
Cells[1,1] := ' ';
Cells[2,1] := ' ';
Cells[3,1] := ' ';
Cells[4,1] := ' ';
Cells[5,1] := ' ';
Cells[6,1] := ' ';
Cells[7,1] := ' ';
Cells[8,1] := ' ';
Cells[9,1] := ' ';
Cells[10,1] := ' ';
Cells[11,1] := ' ';
Cells[12,1] := '0';
end;
end; }
end;
procedure TfraBonusProduct.btnSaveClick(Sender: TObject);
var chkint: Integer;
begin
if edtProductCodeBNS.Text = '' then
begin
CommonDlg.ShowErrorEmpty(' Product Bonus Code ');
Exit;
edtProductCodeBNS.SetFocus;
end
{else if cbpUOMCS.Value <> cbpUOMSales.Value then
begin
CommonDlg.ShowError('UOM CS and UOM Sales is Not Match');
Exit;
cbpUOMCS.SetFocus;
end}
else
begin
if modeSaveBonus = sbAdd then
begin
//insert data
{if not Assigned(BonusProduct) then BonusProduct := TBonusProduct.Create;
checkEmptyUOM();
if BonusProduct.InputDataBonusProduct(UntID,ProductCode,edtProductCodeBNS.Text,UOM,
intedtQtyOrderFrom.Value,intedtQtyOrderTo.Value,
dtFrom.Date,dtTo.Date,intedtQtyBnsCS.Value,intedtQtyBnsSals.Value,1,OP_ID) then
CommonDlg.ShowConfirm(atAdd);
}
end //end sbAdd
else
begin
if chkIsActive.Checked = True then chkint := 1 else chkint:= 0;
//update data
{if not Assigned(BonusProduct) then BonusProduct := TBonusProduct.Create;
checkEmptyUOM();
if BonusProduct.UpdateDataBonusProduct(edtProductCodeBNS.Text,UOM,
intedtQtyOrderFrom.Value,intedtQtyOrderTo.Value,dtFrom.Date,dtTo.Date,
intedtQtyBnsCS.Value,intedtQtyBnsSals.Value,chkint,
StrToInt(strgGrid.Cells[12,strgGrid.Row]),OP_ID) then
CommonDlg.ShowConfirm(atEdit);
}
end;//end else sbAdd
end; // if = ''
pnlAddEdit.Visible := false;
ShowBonusProduct(FProductCode,UntID);
end;
procedure TfraBonusProduct.SetProductCode(const Value: string);
begin
FProductCode := Value;
end;
procedure TfraBonusProduct.setUntID(const Value: Integer);
begin
FUntID := Value;
end;
procedure TfraBonusProduct.strgGridCanEditCell(Sender: TObject; ARow,
ACol: Integer; var CanEdit: Boolean);
begin
if (ACol = 0) then
CanEdit := true
else
CanEdit := false;
end;
procedure TfraBonusProduct.lblEditClick(Sender: TObject);
begin
if UntID = 0 then
begin
CommonDlg.ShowError('UNIT BELUM DIPILIH');
Exit;
end
else
begin
// if strgGrid.Cells[12,strgGrid.Row] = '0' then Exit
// else
begin
pnl3.Visible := false;
pnlAddEdit.Visible := true;
chkIsActive.Checked := True;
chkIsActive.Visible := True;
showEditBonus();
modeSaveBonus := sbEdit;
end;
end;
end;
procedure TfraBonusProduct.strgGridRowChanging(Sender: TObject; OldRow,
NewRow: Integer; var Allow: Boolean);
begin
// edtProductNameUP.Text := strgGrid.Cells[11,NewRow];
end;
procedure TfraBonusProduct.showEditBonus();
begin
{
edtProductNamebwh.Text := strgGrid.Cells[11,strgGrid.Row];
edtProductCodeBNS.Text := strgGrid.Cells[5,strgGrid.Row];
edtUOMSales.Text := strgGrid.Cells[8,strgGrid.Row];
edtUOMCS.Text := strgGrid.Cells[8,strgGrid.Row];
if strgGrid.Cells[10,strgGrid.Row] = '1' then chkIsActive.Checked := True
else chkIsActive.Checked := False;
try
intedtQtyOrderFrom.Value := StrToFloat(strgGrid.Cells[1,strgGrid.Row]);
except
intedtQtyOrderFrom.Value := 0;
end;
try
intedtQtyOrderTo.Value := StrToFloat(strgGrid.Cells[2,strgGrid.Row]);
except
intedtQtyOrderTo.Value := 0;
end;
try
dtFrom.Date := StrToDate(strgGrid.Cells[3,strgGrid.Row]);
except
//do nothing
end;
try
dtTo.Date := StrToDate(strgGrid.Cells[4,strgGrid.Row]);
except
//do nothing
end;
try
intedtQtyBnsSals.Value := StrToFloat(strgGrid.Cells[6,strgGrid.Row]);
except
intedtQtyBnsSals.Value := 0;
end;
try
intedtQtyBnsCS.Value := StrToFloat(strgGrid.Cells[7,strgGrid.Row]);
except
intedtQtyBnsCS.Value := 0;
end;
try
intedtTotalBonus.Value := StrToFloat(strgGrid.Cells[9,strgGrid.Row]);
except
intedtTotalBonus.Value := 0;
end;
}
end;
procedure TfraBonusProduct.ClearBonusEdit();
begin
dtFrom.Date := Now;
dtTo.Date := Now;
edtProductNamebwh.Text := '';
intedtQtyOrderFrom.Value := 0;
intedtQtyOrderTo.Value := 0;
edtProductCodeBNS.Text := '';
intedtQtyBnsSals.Value := 0;
intedtQtyBnsCS.Value := 0;
intedtTotalBonus.Value := 0;
chkIsActive.Checked := False;
end;
procedure TfraBonusProduct.lblDeleteClick(Sender: TObject);
var chkStatue,delStatue: Boolean;
intI: Integer;
begin
delStatue := False;
{if not Assigned(BonusProduct) then BonusProduct := TBonusProduct.Create;
for intI:=1 to strgGrid.RowCount-1 do
begin
strgGrid.SelectRows(intI,1);
strgGrid.GetCheckBoxState(0,strgGrid.Row,chkStatue);
if chkStatue then
if BonusProduct.DeleteDataBonusProduct(StrToInt(strgGrid.Cells[12,strgGrid.Row]))
then delStatue := True;
end;
if delStatue then CommonDlg.ShowConfirm(atDelete);
}
ShowBonusProduct(ProductCode,UntID);
end;
procedure TfraBonusProduct.edtProductCodeBNSKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if (Key = VK_F5) then
begin
// if not assigned(frmDialogSearchProduct) then
// frmDialogSearchProduct := TfrmDialogSearchProduct.Create(Application);
// frmDialogSearchProduct.DialogUnit := frmProduct.MasterNewUnit.ID;
// frmDialogSearchProduct.DialogCompany := frmProduct.MasterCompany.ID;
// frmDialogSearchProduct.Modul:= mNone;
// frmDialogSearchProduct.ShowModal;
// if frmDialogSearchProduct.IsProcessSuccessfull = True then
// begin
// edtProductCodeBNS.Text := frmDialogSearchProduct.ProductCode;
// edtProductNamebwh.Text := frmDialogSearchProduct.ProductName;
// edtUOMCS.Text := frmDialogSearchProduct.ProductSatuan;
// edtUOMSales.Text:= frmDialogSearchProduct.ProductSatuan;
// end;
//
// frmDialogSearchProduct.Free;
end;
end;
procedure TfraBonusProduct.edtProductCodeBNSChange(Sender: TObject);
begin
inherited;
{if not Assigned(BarangCompetitor) then
BarangCompetitor := TBarangCompetitor.Create;
edtProductNamebwh.Text := BarangCompetitor.SearchProductName(edtProductCodeBNS.Text);}
end;
procedure TfraBonusProduct.intedtQtyBnsCSKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
intedtTotalBonus.Value := intedtQtyBnsCS.Value + intedtQtyBnsSals.Value;
end;
procedure TfraBonusProduct.intedtQtyBnsSalsKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
intedtTotalBonus.Value := intedtQtyBnsCS.Value + intedtQtyBnsSals.Value;
end;
procedure TfraBonusProduct.checkEmptyUOM();
begin
if edtUOMCS.Text = '' then UOM := null
else UOM := edtUOMCS.Text;
end;
end.
|
unit TESTORCAMENTOFORNECEDORES.Entidade.Model;
interface
uses
DB,
Classes,
SysUtils,
Generics.Collections,
/// orm
ormbr.types.blob,
ormbr.types.lazy,
ormbr.types.mapping,
ormbr.types.nullable,
ormbr.mapping.classes,
ormbr.mapping.register,
ormbr.mapping.attributes,
TPAGFORNECEDOR.Entidade.Model,
TESTORCAMENTO.Entidade.Model;
type
[Entity]
[Table('TESTORCAMENTOFORNECEDORES', '')]
[PrimaryKey('ID', NotInc, NoSort, False, 'Chave primária')]
TTESTORCAMENTOFORNECEDORES = class
private
{ Private declarations }
FID: Integer;
FIDORCAMENTO: String;
FIDFORNECEDOR: String;
FDATA_CADASTRO: TDateTime;
FULTIMA_ATUALIZACAO: TDateTime;
FTESTORCAMENTO_0: TTESTORCAMENTO ;
FTPAGFORNECEDOR_1: TTPAGFORNECEDOR ;
function getDATA_CADASTRO: TDateTime;
function getULTIMA_ATUALIZACAO: TDateTime;
public
{ Public declarations }
constructor Create;
destructor Destroy; override;
[Restrictions([NotNull])]
[Column('ID', ftInteger)]
[Dictionary('ID', 'Mensagem de validação', '', '', '', taCenter)]
property ID: Integer read FID write FID;
[Restrictions([NotNull])]
[Column('IDORCAMENTO', ftString, 64)]
[ForeignKey('FK1_TESTORCAMENTOFORNECEDORES', 'IDORCAMENTO', 'TESTORCAMENTO', 'CODIGO', SetNull, SetNull)]
[Dictionary('IDORCAMENTO', 'Mensagem de validação', '', '', '', taLeftJustify)]
property IDORCAMENTO: String read FIDORCAMENTO write FIDORCAMENTO;
[Restrictions([NotNull])]
[Column('IDFORNECEDOR', ftString, 64)]
[ForeignKey('FK2_TESTORCAMENTOFORNECEDORES', 'IDFORNECEDOR', 'TPAGFORNECEDOR', 'CODIGO', SetNull, SetNull)]
[Dictionary('IDFORNECEDOR', 'Mensagem de validação', '', '', '', taLeftJustify)]
property IDFORNECEDOR: String read FIDFORNECEDOR write FIDFORNECEDOR;
[Restrictions([NotNull])]
[Column('DATA_CADASTRO', ftDateTime)]
[Dictionary('DATA_CADASTRO', 'Mensagem de validação', 'Now', '', '!##/##/####;1;_', taCenter)]
property DATA_CADASTRO: TDateTime read getDATA_CADASTRO write FDATA_CADASTRO;
[Restrictions([NotNull])]
[Column('ULTIMA_ATUALIZACAO', ftDateTime)]
[Dictionary('ULTIMA_ATUALIZACAO', 'Mensagem de validação', 'Now', '', '!##/##/####;1;_', taCenter)]
property ULTIMA_ATUALIZACAO: TDateTime read getULTIMA_ATUALIZACAO write FULTIMA_ATUALIZACAO;
[Association(OneToOne,'IDORCAMENTO','TESTORCAMENTO','CODIGO')]
property TESTORCAMENTO: TTESTORCAMENTO read FTESTORCAMENTO_0 write FTESTORCAMENTO_0;
[Association(OneToOne,'IDFORNECEDOR','TPAGFORNECEDOR','CODIGO')]
property TPAGFORNECEDOR: TTPAGFORNECEDOR read FTPAGFORNECEDOR_1 write FTPAGFORNECEDOR_1;
end;
implementation
constructor TTESTORCAMENTOFORNECEDORES.Create;
begin
FTESTORCAMENTO_0 := TTESTORCAMENTO.Create;
FTPAGFORNECEDOR_1 := TTPAGFORNECEDOR.Create;
end;
destructor TTESTORCAMENTOFORNECEDORES.Destroy;
begin
if Assigned(FTESTORCAMENTO_0) then
FTESTORCAMENTO_0.Free;
if Assigned(FTPAGFORNECEDOR_1) then
FTPAGFORNECEDOR_1.Free;
inherited;
end;
function TTESTORCAMENTOFORNECEDORES.getDATA_CADASTRO: TDateTime;
begin
if FDATA_CADASTRO = StrToDateTime('30/12/1899 00:00') then
FDATA_CADASTRO := Now;
Result := FDATA_CADASTRO;
end;
function TTESTORCAMENTOFORNECEDORES.getULTIMA_ATUALIZACAO: TDateTime;
begin
FULTIMA_ATUALIZACAO := Now;
Result := FULTIMA_ATUALIZACAO;
end;
initialization
TRegisterClass.RegisterEntity(TTESTORCAMENTOFORNECEDORES)
end.
|
{Escribir una declaración de tipo registro que almacene la sig. información sobre un disco de audio:
título, autor, año de publicación y duración en segundos.}
program TP10E1;
uses crt;
type t_registro=record
autor,titulo:string;
duracion,aniodp:byte;
end;
var rdaudio:t_registro;
procedure inicializar(var rda:t_registro);
begin
with rda do
begin
titulo:='';
autor:='';
aniodp:=0;
duracion:=0;
end;
end;
procedure cargar(var rda:t_registro);
begin
with rda do
begin
writeln('Ingrese los siguientes datos segun corresponda: ');
writeln('Titulo del disco de Audio.');
readln(titulo);
writeln;
writeln('Autor.');
readln(autor);
writeln;
writeln('Año de publicacion.');
readln(aniodp);
writeln;
writeln('Duracion en segundos.');
readln(duracion);
writeln;
end;
end;
procedure mostrar(var rda:t_registro);
begin
with rda do
begin
writeln('Titulo del disco de Audio: ',titulo);
writeln('Autor: ',autor);
writeln('Año de publicacion: ',aniodp);
writeln('Duracion en segundos: ',duracion);
end;
end;
begin
inicializar(rdaudio);
cargar(rdaudio);
writeln;
mostrar(rdaudio);
readkey;
end.
|
PROGRAM StringOperations;
(*Zeichen von einem String werden in einen anderen String kopiert
Dabei wird von der groessten Stelle runtergezaehlt und das jeweilige
Zeichen kopiert*)
FUNCTION Reversed(s : String): String;
VAR rev: STRING;
VAR i : INTEGER;
BEGIN
rev := '';
FOR i := Length(s) DOWNTO 1 DO
BEGIN
rev := Concat(rev, s[i]);
END;
Reversed := rev;
END;
(*StripBlanks kopiert nur ein Zeichen in einen anderen String wenn
dieses Zeichen kein Leerzeichen ist*)
PROCEDURE StripBlanks(VAR s : STRING);
VAR i : INTEGER;
VAR s_new : STRING;
BEGIN
s_new := '';
FOR i := 1 TO Length(s) DO
BEGIN
IF s[i] <> ' ' THEN
BEGIN
s_new := Concat(s_new, s[i]);
END;
END;
s := s_new;
END;
(*ReplaceAll ersetzt alle vorkommende Strings
dabei wird immer ein neuer subString erstellt dieser wird
wieder überprueft ob old darin vorkommt.*)
PROCEDURE ReplaceAll(old, _new : STRING; VAR s : STRING);
VAR Position, count : INTEGER;
VAR result, subString : STRING;
BEGIN
Position := Pos(old,s);
IF Position <> 0 THEN
BEGIN
result := '';
count := 0;
result := Concat(result,Copy(s,1,Position-1));
WHILE Position <> 0 DO
BEGIN
result := concat(result,_new);
subString := Copy(s,(count + Position + length(old)), Length(s));
count := count + Position + length(old)-1;
Position := Pos(old, subString);
result := Concat(result,Copy(subString,1,Position-1));
END;
s := result + subString;
END;
END;
VAR s, old, _new : STRING;
BEGIN
WriteLn(chr(205),chr(205),chr(185),' StringOperations ',chr(204),chr(205),chr(205));
WriteLn('Reverse:');
s := 'Hal lo';
WriteLn('Hal lo: ',Reversed(s),#13#10);
WriteLn('StripBlanks:');
StripBlanks(s);
WriteLn('Hal lo: ', s,#13#10);
WriteLn('ReplaceAll:');
s := 'Test Hallo das das hierdasenthalten';
WriteLn(s);
ReplaceAll('das','der',s);
WriteLn(s);
ReplaceAll('der','der das',s);
WriteLn(s);
END. |
{ The Computer Language Benchmarks Game
http://benchmarksgame.alioth.debian.org
contributed by Ian Osgood,
modified by Florian Klaempfl
modified by Ales Katona
modified by Vincent Snijders
}
{$mode objfpc}
program n_body;
uses Math;
type
Body = record
x, y, z,
vx, vy, vz,
mass : double;
end;
PBody = ^Body;
const pi = 3.141592653589793;
solarMass = 4 * sqr(pi);
daysPerYear = 365.24;
type
tbody = array[1..5] of Body;
const b : tbody = (
{ Sun }
( x:0; y:0; z:0; vx:0; vy:0; vz:0; mass: solarMass ),
{ Jupiter }
( x: 4.84143144246472090e+00;
y: -1.16032004402742839e+00;
z: -1.03622044471123109e-01;
vx: 1.66007664274403694e-03 * daysPerYear;
vy: 7.69901118419740425e-03 * daysPerYear;
vz: -6.90460016972063023e-05 * daysPerYear;
mass: 9.54791938424326609e-04 * solarMass ),
{ Saturn }
( x: 8.34336671824457987e+00;
y: 4.12479856412430479e+00;
z: -4.03523417114321381e-01;
vx: -2.76742510726862411e-03 * daysPerYear;
vy: 4.99852801234917238e-03 * daysPerYear;
vz: 2.30417297573763929e-05 * daysPerYear;
mass: 2.85885980666130812e-04 * solarMass ),
{ Uranus }
( x: 1.28943695621391310e+01;
y: -1.51111514016986312e+01;
z: -2.23307578892655734e-01;
vx: 2.96460137564761618e-03 * daysPerYear;
vy: 2.37847173959480950e-03 * daysPerYear;
vz: -2.96589568540237556e-05 * daysPerYear;
mass: 4.36624404335156298e-05 * solarMass ),
{ Neptune }
( x: 1.53796971148509165e+01;
y: -2.59193146099879641e+01;
z: 1.79258772950371181e-01;
vx: 2.68067772490389322e-03 * daysPerYear;
vy: 1.62824170038242295e-03 * daysPerYear;
vz: -9.51592254519715870e-05 * daysPerYear;
mass: 5.15138902046611451e-05 * solarMass )
);
procedure offsetMomentum;
var px,py,pz : double;
i : integer;
begin
px:=0.0; py:=0.0; pz:=0.0;
for i := low(b)+1 to high(b) do
with b[i] do
begin
px := px - vx * mass;
py := py - vy * mass;
pz := pz - vz * mass;
end;
b[low(b)].vx := px / solarMass;
b[low(b)].vy := py / solarMass;
b[low(b)].vz := pz / solarMass;
end;
function distance(i,j : integer) : double;
begin
distance := sqrt(sqr(b[i].x-b[j].x) + sqr(b[i].y-b[j].y) +
sqr(b[i].z-b[j].z));
end;
function energy : double;
var
i,j : integer;
begin
result := 0.0;
for i := low(b) to high(b) do
with b[i] do
begin
result := result + mass * (sqr(vx) + sqr(vy) + sqr(vz)) / 2;
for j := i+1 to high(b) do
result := result - mass * b[j].mass / distance(i,j);
end;
end;
procedure advance(dt : double);
var i,j : integer;
dx,dy,dz,mag : double;
bi,bj : PBody;
begin
bi:=@b[low(b)];
for i := low(b) to high(b)-1 do begin
bj := bi;
for j := i+1 to high(b) do
begin
inc(bj);
dx := bi^.x - bj^.x;
dy := bi^.y - bj^.y;
dz := bi^.z - bj^.z;
mag := dt / (sqrt(sqr(dx)+sqr(dy)+sqr(dz))*(sqr(dx)+sqr(dy)+sqr(dz)));
bi^.vx := bi^.vx - dx * bj^.mass * mag;
bi^.vy := bi^.vy - dy * bj^.mass * mag;
bi^.vz := bi^.vz - dz * bj^.mass * mag;
bj^.vx := bj^.vx + dx * bi^.mass * mag;
bj^.vy := bj^.vy + dy * bi^.mass * mag;
bj^.vz := bj^.vz + dz * bi^.mass * mag;
end;
inc(bi);
end;
bi:=@b[low(b)];
for i := low(b) to high(b) do begin
with bi^ do
begin
x := x + dt * vx;
y := y + dt * vy;
z := z + dt * vz;
end;
inc(bi);
end;
end;
var i : integer;
n : Integer;
begin
SetPrecisionMode(pmDouble);
offsetMomentum;
writeln(energy:0:9);
Val(ParamStr(1), n, i);
for i := 1 to n do advance(0.01);
writeln(energy:0:9);
end. |
UNIT UDate;
INTERFACE
{* Datatype which represents a valid Date *}
TYPE
Date = RECORD
day: 1..31; month: 1..12; year: INTEGER;
END;
{* Parses date string to a valid date of type Date. If ok parameter is true
* parsing was successfull.
*
* @paramIn s STRING Date String to be parsed. Strict Format: 'dd.mm.yyyy'
* @paramOut ok BOOLEAN Of value true if parsed date is valid, otherwise false
* @paramOut d Date Valid date
*}
PROCEDURE ParseDate(s: STRING; VAR ok: BOOLEAN; VAR d: Date);
{* Determines if on a timeline date1 occurs before date2
*
* @paramIn date1 Date First date to be compared
* @paramIn date2 Date Second date to be compared
* @return BOOELAN Is true if date1 lies before date2, otherwise returns false
*}
FUNCTION LiesBefore(date1, date2: Date): BOOLEAN;
{* Displays date in console in format 'dd.mm.yyyy' with leading zeros if necessary
*
* @paramIn d Date Date to be displayed
*}
PROCEDURE DisplayDate(d: Date);
IMPLEMENTATION
FUNCTION IsLeapYear(year: INTEGER): BOOLEAN;
BEGIN
IsLeapYear := false;
IF (year mod 100) = 0 THEN BEGIN
IF (year mod 400) = 0 THEN {* centurial exceptions *}
IsLeapYear := true;
END ELSE IF (year mod 4) = 0 THEN
IsLeapYear := true;
END;
FUNCTION GetDaysOfMonth(month, year: INTEGER): INTEGER;
VAR
daysPerMonth: ARRAY [1..12] OF INTEGER;
BEGIN
daysPerMonth[1] := 31; {* Define all months *}
daysPerMonth[2] := 28;
daysPerMonth[3] := 31;
daysPerMonth[4] := 30;
daysPerMonth[5] := 31;
daysPerMonth[6] := 30;
daysPerMonth[7] := 31;
daysPerMonth[8] := 31;
daysPerMonth[9] := 30;
daysPerMonth[10] := 31;
daysPerMonth[11] := 30;
daysPerMonth[12] := 31;
IF IsLeapYear(year) THEN {* check for leap years *}
daysPerMonth[2] := 29;
GetDaysOfMonth := 0;
IF (month < 13) and (month > 0) and (year <= 9999) and (year > 0) THEN
GetDaysOfMonth := daysPerMonth[month];
END;
FUNCTION IsValidDate(d: Date): BOOLEAN;
BEGIN
IsValidDate := false;
{* first check if day is inside range for the month *}
IF d.day <= GetDaysOfMonth(d.month, d.year) THEN
IF d.month <= 12 THEN
{* My defined range for years, similar to MS SQL Server *}
IF (d.year >= 1) and (d.year <= 9999) THEN
IsValidDate := true;
END;
PROCEDURE DisplayDate(d: Date);
VAR
dayLeadingZero, monthLeadingZero, yearLeadingZero: STRING;
count, i: INTEGER;
yearCopy: REAL;
BEGIN
IF IsValidDate(d) THEN BEGIN
count := 0;
dayLeadingZero := '';
monthLeadingZero := '';
yearLeadingZero := '';
yearCopy := d.year;
WHILE yearCopy >= 1 DO BEGIN {* find out how many figures the number has *}
yearCopy := yearCopy / 10;
count := count + 1;
END;
{* 4 is the max of figures a year should have,
the amount of leading zeros needed is
4 - count of existing figures
*}
FOR i := 1 TO 4 - count DO BEGIN
yearLeadingZero := yearLeadingZero + '0';
END;
{* Check if day or/and month needs a leading zero *}
IF d.day <= 9 THEN
dayLeadingZero := '0';
IF d.month <= 9 THEN
monthLeadingZero := '0';
Write(dayLeadingZero, d.day, '.', monthLeadingZero, d.month, '.', yearLeadingZero, d.year)
END ELSE WriteLn('Date is not valid !');
END;
FUNCTION LiesBefore(date1, date2: Date): BOOLEAN;
BEGIN
IF IsValidDate(date1) and IsValidDate(date2)THEN BEGIN
IF date1.Year < date2.Year THEN BEGIN
LiesBefore:= true;
END
ELSE IF date1.Year = date2.Year THEN BEGIN
IF date1.Month < date2.Month THEN BEGIN
LiesBefore:= true;
END
ELSE IF date1.Month = date2.Month THEN BEGIN
IF date1.Day <= date2.Day THEN BEGIN
LiesBefore:= true;
END
ELSE BEGIN
LiesBefore:= false;
END;
END
ELSE BEGIN
LiesBefore:= false;
END;
END
ELSE BEGIN
LiesBefore:= false;
END;
END;
END;
PROCEDURE AddDays(VAR d: Date; days: INTEGER);
VAR
i: INTEGER;
BEGIN
{* Check wether days should be added or subtracted *}
IF days >= 0 THEN BEGIN
FOR i := 1 TO days DO BEGIN
{* If the next day is not covered in the amount of days
a the month has to be increased and the day will be set
to 1 again.
*}
IF GetDaysOfMonth(d.month, d.year) < (d.day + 1) THEN BEGIN
d.day := 1;
{* If the next month would be out of the range it has to be
set to 1 again, also year has to be increased
*}
IF 12 < (d.month + 1) THEN BEGIN
d.month := 1;
{* If the next year would be out of the range there is a overflow
and the year is set to the opposite value of the exceeding limit
*}
IF 9999 < (d.year + 1) THEN BEGIN
d.year := 1; {* Overflow *}
END ELSE d.year := d.year + 1;
END ELSE d.month := d.month + 1;
END ELSE d.day := d.day + 1;
END;
END ELSE BEGIN
{* for the substraction of days a FOR .. DOWNTO loop is used.
The algorithm for the substraction is very similar to the above
for adding days.
*}
FOR i := -1 DOWNTO days DO BEGIN
IF 1 > (d.day - 1) THEN BEGIN
IF 1 > (d.month - 1) THEN BEGIN
d.month := 12;
IF 1 > (d.year - 1) THEN BEGIN
d.year := 9999; {* overflow *}
END ELSE d.year := d.year - 1;
END ELSE BEGIN
d.month := d.month - 1;
d.day := GetDaysOfMonth(d.month, d.year);
END;
END ELSE d.day := d.day - 1;
END;
END;
END;
PROCEDURE ParseDate(s: STRING; VAR ok: BOOLEAN; VAR d: Date);
VAR
day, month, year: INTEGER;
BEGIN
ok := false;
{* check if the format is right: DD.MM.YYYY = 10 *}
IF Length(s) = 10 THEN BEGIN
{* ord() of an char returns a char's number in ASCII.
ASCII's range for figures goes from 48 to 57, so
calculating x - 48 delivers the number itself. *}
day := ((ord(s[1]) - 48) * 10 + (ord(s[2]) - 48));
month := ((ord(s[4]) - 48) * 10 + (ord(s[5]) - 48));
year := ((ord(s[7]) - 48) * 1000 + (ord(s[8]) - 48) * 100 + (ord(s[9]) - 48) * 10 + (ord(s[10]) - 48));
{* Check if the ranges of day, month and year are correct
before assigning them to the properties of Date, otherwise there
could be runtime errors because of the range checks *}
IF (day <= 31) and (day > 0) THEN
IF (month <= 12) and (month > 0) THEN
IF (year <= 9999) and (year >= 1) THEN BEGIN
d.day := day;
d.month := month;
d.year := year;
ok := IsValidDate(d);
END;
END;
END;
BEGIN
END.
|
unit uGeoLocation;
interface
uses
System.Variants,
Winapi.ActiveX,
Vcl.OleCtrls,
SHDocVw,
MSHTML;
const
GoogleMapHTMLStr: string =
'<html> '+
'<head> '+
'<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' +
'<META HTTP-EQUIV="MSThemeCompatible" CONTENT="Yes">'+
'<meta name="viewport" content="initial-scale=1.0, user-scalable=yes" /> '+
'<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&language=%LANG%&libraries=panoramio"></script> '+
'<script type="text/javascript"> '+
''+
''+
' var geocoder; '+
' var maxZoomService; '+
' var map; '+
' var markersArray = [];'+
' var infoWindow;'+
' var mapLat;'+
' var mapLng;'+
' var currentImage;'+
' var currentLat;'+
' var currentLng;'+
' var imageLat;'+
' var imageLng;'+
' var currentDate;'+
' var canSave;'+
''+
''+
' function initialize() { '+
' geocoder = new google.maps.Geocoder();'+
' var latlng = new google.maps.LatLng(%START_LT%, %START_LN%); '+
' var myOptions = { '+
' zoom: %START_ZOOM%, '+
' center: latlng, '+
' mapTypeId: google.maps.MapTypeId.SATELLITE '+
' }; '+
' map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); '+
' map.set("streetViewControl", false);'+
' google.maps.event.addListener(map, "click", '+
' function(event){ '+
' mapLat = event.latLng.lat();' +
' mapLng = event.latLng.lng();' +
' currentLat = mapLat; '+
' currentLng = mapLng; '+
' if (external.CanSaveLocation(mapLat, mapLng, 1) > 0){' +
' canSave = true; '+
' PutMarker(mapLat, mapLng); '+
' } '+
' } '+
' ); '+
' google.maps.event.addListener(map, "bounds_changed", function() { '+
' external.ZoomPan(map.getCenter().lat(), map.getCenter().lng(), map.getZoom()) '+
' }); '+
' infoWindow = new google.maps.InfoWindow();'+
' maxZoomService = new google.maps.MaxZoomService(); '+
' google.maps.event.addListener(infoWindow, "domready", function () { '+
' external.UpdateEmbed(); '+
' if (canSave) ' +
' DisplaySave("block"); '+
' }); '+
' external.MapStarted(); '+
' } '+
''+
' function DisplaySave(Value) { '+
' var arr = document.getElementsByTagName("div"); '+
' for (i = 0; i < arr.length; i++) '+
' if (arr[i].className == "divSave") '+
' arr[i].style.display = Value; '+
' } '+
' function GotoLatLng(Lat, Lng) { '+
' var latlng = new google.maps.LatLng(Lat, Lng);'+
' map.setCenter(latlng);'+
' }'+
''+
' function SetMapBounds(Lat, Lang, Zoom) { '+
' var latlng = new google.maps.LatLng(Lat,Lang);'+
' map.setCenter(latlng);'+
' map.setZoom(Zoom);'+
' }'+
''+
' function SaveLocation() { '+
' external.SaveLocation(mapLat, mapLng, currentImage);'+
' }'+
''+
' var panoramioLayer = null; '+
' function showPanaramio() { '+
' if (panoramioLayer == null) { '+
' panoramioLayer = new google.maps.panoramio.PanoramioLayer(); '+
' } '+
' panoramioLayer.setMap(map); '+
' } '+
' function hidePanaramio() { '+
' if (panoramioLayer != null) { '+
' panoramioLayer.setMap(null); '+
' } '+
' } '+
'function ClearMarkers() { '+
' if (markersArray) { '+
' for (i in markersArray) { '+
' markersArray[i].setMap(null); '+
' } '+
' } '+
'} '+
''+
'function ResetLocation(){' +
' canSave = false; ' +
' external.CanSaveLocation(0, 0, -1);' +
' if ((imageLat != 0) && (imageLng != 0)) {'+
' PutMarker(imageLat, imageLng);' +
' currentLat = imageLat; '+
' currentLng = imageLng; '+
' } else {'+
' ClearMarkers();' +
' }' +
'} '+
'function SaveImageInfo(Name, Date){' +
' canSave = false; '+
' currentImage = Name; '+
' currentDate = Date; '+
' imageLat = 0; '+
' imageLng = 0; '+
'' +
'} '+
'function ShowImageLocation(Lat, Lng, Msg, Date) { '+
' canSave = false; '+
' currentLat = Lat; '+
' currentLng = Lng; '+
' imageLat = Lat; '+
' imageLng = Lng; '+
' currentImage = Msg; '+
' currentDate = Date; '+
' PutMarker(Lat, Lng); '+
'}' +
'function PutMarker(Lat, Lng) { '+
' ClearMarkers(); '+
' var html = document.getElementById("googlePopup").innerHTML;'+
' html = html.replace(/%NAME%/g, currentImage);'+
' html = html.replace(/%DATE%/g, currentDate);'+
' html = html.replace(/imageClass/g, "image");'+
' html = html.replace(/idSave/g, "divSave");'+
' if (canSave)' +
' html = html.replace(/1111/g, "350");'+
' else '+
' html = html.replace(/1111/g, "250");'+
' '+
' if (currentDate == "") '+
' html = html.replace(/inline/g, "none");'+
' var latlng = new google.maps.LatLng(Lat, Lng); '+
' var options = { '+
' position: latlng, '+
' map: map, '+
' icon: "http://www.google.com/mapfiles/marker.png", '+
' title: currentImage + " (" + Lat + ", " + Lng + ")", '+
' content: html '+
' }; '+
' var marker = new google.maps.Marker({ map: map });'+
' marker.setOptions(options); '+
' infoWindow.setOptions(options); '+
' infoWindow.open(map, marker); '+
' google.maps.event.addListener(marker, "click", function () { '+
' infoWindow.setOptions(options); '+
' infoWindow.open(map, marker); '+
' '+
' }); '+
' setTimeout("fixZoom()", 1); ' +
' markersArray.push(marker); '+
'}'+
''+
'function FindLocation(address) { '+
'geocoder.geocode( { "address": address}, function(results, status) { '+
' if (status == google.maps.GeocoderStatus.OK) { '+
' map.setCenter(results[0].geometry.location); '+
' if (results[0].geometry.bounds) '+
' map.fitBounds(results[0].geometry.bounds); '+
' } '+
' });' +
'}'+
''+
' function fixZoom() { '+
' maxZoomService.getMaxZoomAtLatLng(map.getCenter(), function(response) { '+
' if (response.status == google.maps.MaxZoomStatus.OK && response.zoom < map.getZoom()) { '+
' map.setZoom(response.zoom); '+
' } '+
' }); '+
' } '+
' function showMaxZoom() { '+
' maxZoomService.getMaxZoomAtLatLng(map.getCenter(), function(response) { '+
' if (response.status == google.maps.MaxZoomStatus.OK) { '+
' map.setZoom(response.zoom); '+
' } '+
' }); '+
' } '+
'function LoadLocationReply() { ' +
' if (locationReq && locationReq.readyState == 4) { ' +
' if (locationReq.status == 200) { ' +
' ' +
' } ' +
' } ' +
'}' +
'function TryToResolvePosition(json){' +
' if (map.getZoom()<=1) {' +
' var jsonObj = eval("(function(){return " + json + ";})()"); ' +
' if (jsonObj.text) {'+
' map.setMapTypeId(google.maps.MapTypeId.ROADMAP); '+
' FindLocation(jsonObj.text); ' +
' } ' +
' } ' +
'}' +
'function ZoomIn() { '+
' GotoLatLng(currentLat, currentLng); '+
' setTimeout("showMaxZoom()", 1); ' +
'}'+
''+
'google.maps.event.addDomListener(window, "load", initialize); ' +
'</script> '+
'<style>' +
'</style>' +
'</head> '+
''+
'<body style="margin:0; padding:0; overflow: hidden"> '+
' <div id="map_canvas" style="width:100%; height:100%"></div> '+
' <div id="googlePopup" style="display: none;"> '+
' <div style="height: 1111px; width: 230px; font-size: 12px;"> '+
' <p style="color: #000000; margin: 0"> '+
' <div style="text-align:center;"> '+
' <embed class="imageClass" width="204" height="204"></embed> '+
' </div> '+
' <span style="">%NAME_LABEL%: <strong>%NAME%</strong></span> '+
' <br /> '+
' <span style="display:inline">%DATE_LABEL%: %DATE%</span> '+
' <br /> '+
' <span style="padding-top: 5px; display:block;"><a onclick="ZoomIn();" href="javascript:;">%ZOOM_TEXT%</a></span> '+
' <div class="idSave" style="display: none; padding-top: 10px;"> '+
' <span style="padding: 5px;"><strong>%SAVE_TEXT%</strong></span> '+
' <br /> '+
' <input type="button" value="%YES%" onclick="SaveLocation()" style="width: 70px"> '+
' <input type="button" value="%NO%" onclick="ResetLocation()" style="width: 70px"> '+
' </div> '+
' </p> '+
' </div> '+
' </div> '+
'</body> '+
'</html> ';
//TODO: move this method to other unit
procedure ClearWebBrowser(WebBrowser: TWebBrowser);
implementation
procedure ClearWebBrowser(WebBrowser: TWebBrowser);
var
v: Variant;
HTMLDocument: IHTMLDocument2;
begin
if WebBrowser <> nil then
begin
HTMLDocument := WebBrowser.Document as IHTMLDocument2;
if HTMLDocument <> nil then
begin
v := VarArrayCreate([0, 0], varVariant);
v[0] := ''; //empty document
HTMLDocument.Write(PSafeArray(TVarData(v).VArray));
HTMLDocument.Close;
end;
end;
end;
end.
|
unit U_FrmOnLine;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
Vcl.Imaging.pngimage, U_User, U_FrmConversation, U_Central_Unit, U_StoredProceduresInterface;
type
Tfrm_OnLine = class(TForm)
lbl_User: TLabel;
lb_Contact: TListBox;
btn_Disconect: TButton;
img_avatar: TImage;
cb_ConnectState: TComboBox;
lbl_UserConnected: TLabel;
btn_AddContact: TButton;
e_AddContact: TEdit;
procedure btn_DisconectClick(Sender: TObject);
procedure lb_ContactDblClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frm_OnLine: Tfrm_OnLine;
ContactList: TList;
implementation
{$R *.dfm}
procedure Tfrm_OnLine.btn_DisconectClick(Sender: TObject);
begin
self.Close;
end;
procedure Tfrm_OnLine.FormCreate(Sender: TObject);
Var
I: Integer;
begin
// Configura Datos de Usuario DelphiChat.User
lbl_User.Caption:= DelphiChat.User.Nick;
DelphiChat.User.Nick:= StringReplace(DelphiChat.User.Nick,' ','', [rfReplaceAll]);
self.Caption:= DelphiChat.User.Nick + ' - ('+DelphiChat.User.Mail+')';
// Descarga Lista de Contactos
DelphiChat.Contacts:= GetContactList(DelphiChat.UsedConnection, DelphiChat.User.UserId);
// Arma Lista de Contactos
self.lb_Contact.Clear;
for I := 0 to DelphiChat.Contacts.Count-1 do
Self.lb_Contact.Items.Add(TContact(DelphiChat.Contacts.Items[I]).Nick + ' - ('+TContact(DelphiChat.Contacts.Items[I]).Mail+')');
end;
procedure Tfrm_OnLine.lb_ContactDblClick(Sender: TObject);
begin
//Si No tiene Ventana de Conversacion la crea, si tiene solo la muestra
if (TContact(DelphiChat.Contacts.Items[lb_Contact.ItemIndex]).WDW_Conversation=nil) then
begin
TContact(DelphiChat.Contacts.Items[lb_Contact.ItemIndex]).WDW_Conversation:= Tfrm_Conversation.Create(Owner);
TContact(DelphiChat.Contacts.Items[lb_Contact.ItemIndex]).WDW_Conversation.Caption:= TContact(DelphiChat.Contacts.Items[lb_Contact.ItemIndex]).Nick;
Tfrm_Conversation (TContact(DelphiChat.Contacts.Items[lb_Contact.ItemIndex]).WDW_Conversation).lbl_Contact.Caption:= TContact(DelphiChat.Contacts.Items[lb_Contact.ItemIndex]).Nick;
Tfrm_Conversation (TContact(DelphiChat.Contacts.Items[lb_Contact.ItemIndex]).WDW_Conversation).Index:= TContact(DelphiChat.Contacts.Items[lb_Contact.ItemIndex]).UserId;
//ConfigurarVentana
end;
Tfrm_Conversation (TContact(DelphiChat.Contacts.Items[lb_Contact.ItemIndex]).WDW_Conversation).Show;
end;
end.
|
namespace ConsoleApplication1;
//Sample .NET console application
//by Brian Long, 2009
//App is compiled against .NET assemblies and reports various bits of environment information
//Does Win32/Unix differentiation using directory separator check
//Does Linux/OS X differentiation using a Mono class (from Mono.Posix.dll) containing Unix calls
interface
type
ConsoleApp = class
private
class method IsWindows: Boolean;
//Note - only call these methods if IsWindows has returned False!
class method IsLinux: Boolean;
class method IsOSX: Boolean;
class Method IsMono: Boolean;
class Method IsDotNet: Boolean;
public
class method Main;
end;
implementation
class method ConsoleApp.IsWindows: Boolean;
begin
result := RemObjects.Elements.RTL.Environment.OS = RemObjects.Elements.RTL.OperatingSystem.Windows;
end;
class method ConsoleApp.IsLinux: Boolean;
begin
result := RemObjects.Elements.RTL.Environment.OS = RemObjects.Elements.RTL.OperatingSystem.Linux;
end;
class method ConsoleApp.IsOSX: Boolean;
begin
result := RemObjects.Elements.RTL.Environment.OS = RemObjects.Elements.RTL.OperatingSystem.macOS;
end;
class method ConsoleApp.IsMono: Boolean;
begin
exit &Type.GetType('Mono.Runtime') <> nil
end;
class method ConsoleApp.IsDotNet: Boolean;
begin
exit not IsMono()
end;
class method ConsoleApp.Main;
begin
Console.WriteLine(String.Format('Command line: {0}', Environment.CommandLine));
Console.WriteLine(String.Format('Current directory: {0}', Environment.CurrentDirectory));
Console.WriteLine(String.Format('#Processors: {0}', Environment.ProcessorCount));
Console.WriteLine(String.Format('User name: {0}', Environment.UserName));
Console.WriteLine(String.Format('Machine name: {0}', Environment.MachineName));
Console.WriteLine(String.Format('User domain: {0}', Environment.UserDomainName));
Console.WriteLine(String.Format('Reported OS Version summary: {0}', Environment.OSVersion.VersionString));
Console.WriteLine(String.Format('Reported OS platform: {0}', Environment.OSVersion.Platform));
Console.WriteLine(String.Format('Reported OS Version: {0}', Environment.OSVersion.Version));
Console.WriteLine(String.Format('Reported OS Service Pack: {0}', Environment.OSVersion.ServicePack));
Console.Write('Actual platform: ');
if IsWindows then
Console.WriteLine(String.Format('A Windows platform ({0})', Environment.OSVersion.Platform))
else if IsLinux then
Console.WriteLine('Linux')
else
Console.WriteLine('Mac OS X');
Console.WriteLine(String.Format('Execution engine version: {0}', Environment.Version));
Console.Write('Running .NET or Mono: ');
if &Type.GetType('Mono.Runtime') = nil then
Console.WriteLine('.NET')
else
Console.WriteLine('Mono');
Console.WriteLine(String.Format('System dir: {0}', Environment.SystemDirectory));
Console.WriteLine(String.Format('Application Data folder: {0}', Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)));
Console.WriteLine(String.Format('Desktop folder: {0}', Environment.GetFolderPath(Environment.SpecialFolder.Desktop)));
Console.WriteLine(String.Format('Local Application Data folder: {0}', Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)));
Console.WriteLine(String.Format('My Documents folder: {0}', Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)));
Console.WriteLine(String.Format('My Pictures folder: {0}', Environment.GetFolderPath(Environment.SpecialFolder.MyPictures)));
Console.WriteLine(String.Format('My Music folder: {0}', Environment.GetFolderPath(Environment.SpecialFolder.MyMusic)));
Console.WriteLine(String.Format('Personal folder: {0}', Environment.GetFolderPath(Environment.SpecialFolder.Personal)));
Console.ReadLine();
end;
end. |
unit UDPFRanges;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls, UCrpe32;
type
TCrpeParamFieldRangesDlg = class(TForm)
btnOk: TButton;
pnlPFValues: TPanel;
lblRangeStart: TLabel;
lblRangeEnd: TLabel;
editRangeStart: TEdit;
editRangeEnd: TEdit;
lblBounds: TLabel;
cbBounds: TComboBox;
lbNumbers: TListBox;
lblNumber: TLabel;
btnClear: TButton;
btnAdd: TButton;
btnDelete: TButton;
lblCount: TLabel;
editCount: TEdit;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure UpdateRanges;
procedure lbNumbersClick(Sender: TObject);
procedure cbBoundsChange(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure InitializeControls(OnOff: boolean);
procedure editRangeStartEnter(Sender: TObject);
procedure editRangeStartExit(Sender: TObject);
procedure editRangeEndEnter(Sender: TObject);
procedure editRangeEndExit(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Crr : TCrpeParamFieldRanges;
RIndex : integer;
PrevVal : string;
end;
var
CrpeParamFieldRangesDlg: TCrpeParamFieldRangesDlg;
implementation
{$R *.DFM}
uses UCrpeUtl;
{------------------------------------------------------------------------------}
{ FormCreate procedure }
{------------------------------------------------------------------------------}
procedure TCrpeParamFieldRangesDlg.FormCreate(Sender: TObject);
begin
LoadFormPos(Self);
btnOk.Tag := 1;
RIndex := -1;
end;
{------------------------------------------------------------------------------}
{ FormShow procedure }
{------------------------------------------------------------------------------}
procedure TCrpeParamFieldRangesDlg.FormShow(Sender: TObject);
begin
UpdateRanges;
end;
{------------------------------------------------------------------------------}
{ UpdateRanges procedure }
{------------------------------------------------------------------------------}
procedure TCrpeParamFieldRangesDlg.UpdateRanges;
var
OnOff : boolean;
i : integer;
begin
RIndex := -1;
{Enable/Disable controls}
if IsStrEmpty(Crr.Cr.ReportName) then
begin
OnOff := False;
btnAdd.Enabled := False;
end
else
begin
OnOff := (Crr.Count > 0);
btnAdd.Enabled := True;
{Get Ranges Index}
if OnOff then
begin
if Crr.ItemIndex > -1 then
RIndex := Crr.ItemIndex
else
RIndex := 0;
end;
end;
InitializeControls(OnOff);
{Update list box}
if OnOff then
begin
{Fill Numbers ListBox}
lbNumbers.Clear;
for i := 0 to Crr.Count - 1 do
lbNumbers.Items.Add(IntToStr(i));
editCount.Text := IntToStr(Crr.Count);
lbNumbers.ItemIndex := RIndex;
lbNumbersClick(self);
end;
end;
{------------------------------------------------------------------------------}
{ InitializeControls }
{------------------------------------------------------------------------------}
procedure TCrpeParamFieldRangesDlg.InitializeControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
if TComponent(Components[i]).Tag = 0 then
begin
if Components[i] is TButton then
TButton(Components[i]).Enabled := OnOff;
if Components[i] is TListBox then
begin
TListBox(Components[i]).Clear;
TListBox(Components[i]).Color := ColorState(OnOff);
TListBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TComboBox then
begin
TComboBox(Components[i]).Color := ColorState(OnOff);
TComboBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TEdit then
begin
TEdit(Components[i]).Text := '';
if TEdit(Components[i]).ReadOnly = False then
TEdit(Components[i]).Color := ColorState(OnOff);
TEdit(Components[i]).Enabled := OnOff;
end;
end;
end;
end;
{------------------------------------------------------------------------------}
{ lbNumbersClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeParamFieldRangesDlg.lbNumbersClick(Sender: TObject);
begin
RIndex := lbNumbers.ItemIndex;
editRangeStart.Text := Crr[RIndex].RangeStart;
editRangeEnd.Text := Crr[RIndex].RangeEnd;
cbBounds.ItemIndex := Ord(Crr[RIndex].Bounds);
end;
{------------------------------------------------------------------------------}
{ editRangeStartEnter procedure }
{------------------------------------------------------------------------------}
procedure TCrpeParamFieldRangesDlg.editRangeStartEnter(Sender: TObject);
begin
PrevVal := editRangeStart.Text;
end;
{------------------------------------------------------------------------------}
{ editRangeStartExit procedure }
{------------------------------------------------------------------------------}
procedure TCrpeParamFieldRangesDlg.editRangeStartExit(Sender: TObject);
begin
if IsStrEmpty(Crr.Cr.ReportName) then Exit;
if RIndex < 0 then Exit;
if IsFloating(editRangeStart.Text) then
Crr.Item.RangeStart := editRangeStart.Text
else
editRangeStart.Text := PrevVal;
end;
{------------------------------------------------------------------------------}
{ editRangeEndEnter procedure }
{------------------------------------------------------------------------------}
procedure TCrpeParamFieldRangesDlg.editRangeEndEnter(Sender: TObject);
begin
PrevVal := editRangeEnd.Text;
end;
{------------------------------------------------------------------------------}
{ editRangeEndExit procedure }
{------------------------------------------------------------------------------}
procedure TCrpeParamFieldRangesDlg.editRangeEndExit(Sender: TObject);
begin
if IsStrEmpty(Crr.Cr.ReportName) then Exit;
if RIndex < 0 then Exit;
if IsFloating(editRangeEnd.Text) then
Crr.Item.RangeEnd := editRangeEnd.Text
else
editRangeEnd.Text := PrevVal;
end;
{------------------------------------------------------------------------------}
{ cbBoundsChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeParamFieldRangesDlg.cbBoundsChange(Sender: TObject);
begin
Crr[RIndex].Bounds := TCrRangeBounds(cbBounds.ItemIndex);
end;
{------------------------------------------------------------------------------}
{ btnAddClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeParamFieldRangesDlg.btnAddClick(Sender: TObject);
begin
Crr.Add;
UpdateRanges;
end;
{------------------------------------------------------------------------------}
{ btnDeleteClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeParamFieldRangesDlg.btnDeleteClick(Sender: TObject);
begin
Crr.Delete(RIndex);
UpdateRanges;
end;
{------------------------------------------------------------------------------}
{ btnClearClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeParamFieldRangesDlg.btnClearClick(Sender: TObject);
begin
Crr.Clear;
UpdateRanges;
end;
{------------------------------------------------------------------------------}
{ btnOkClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeParamFieldRangesDlg.btnOkClick(Sender: TObject);
begin
SaveFormPos(Self);
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose procedure }
{------------------------------------------------------------------------------}
procedure TCrpeParamFieldRangesDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Release;
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2020 Kike Pérez
Unit : Quick.Logger.Provider.Email
Description : Log Email Provider
Author : Kike Pérez
Version : 1.24
Created : 15/10/2017
Modified : 24/04/2020
This file is part of QuickLogger: https://github.com/exilon/QuickLogger
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Logger.Provider.Email;
{$i QuickLib.inc}
interface
uses
Classes,
SysUtils,
Quick.Commons,
Quick.SMTP,
Quick.Logger;
type
{$M+}
TSMTPConfig = class
private
fHost : string;
fPort : Integer;
fUserName : string;
fPassword : string;
fServerAuth : Boolean;
fUseSSL : Boolean;
published
property Host : string read fHost write fHost;
property Port : Integer read fPort write fPort;
property UserName : string read fUserName write fUserName;
property Password : string read fPassword write fPassword;
property ServerAuth : Boolean read fServerAuth write fServerAuth;
property UseSSL : Boolean read fUseSSL write fUseSSL;
end;
{$M-}
{$M+}
TMailConfig = class
private
fSenderName : string;
fFrom : string;
fRecipient : string;
fSubject : string;
fBody : string;
fCC : string;
fBCC : string;
published
property SenderName : string read fSenderName write fSenderName;
property From : string read fFrom write fFrom;
property Recipient : string read fRecipient write fRecipient;
property Subject : string read fSubject write fSubject;
property Body : string read fBody write fBody;
property CC : string read fCC write fCC;
property BCC : string read fBCC write fBCC;
end;
{$M-}
TLogEmailProvider = class (TLogProviderBase)
private
fSMTP : TSMTP;
fMail : TMailMessage;
fSMTPConfig : TSMTPConfig;
fMailConfig : TMailConfig;
public
constructor Create; override;
destructor Destroy; override;
property SMTP : TSMTPConfig read fSMTPConfig write fSMTPConfig;
property Mail : TMailConfig read fMailConfig write fMailConfig;
procedure Init; override;
procedure Restart; override;
procedure WriteLog(cLogItem : TLogItem); override;
end;
var
GlobalLogEmailProvider : TLogEmailProvider;
implementation
constructor TLogEmailProvider.Create;
begin
inherited;
LogLevel := LOG_ALL;
fSMTPConfig := TSMTPConfig.Create;
fMailConfig := TMailConfig.Create;
fSMTP := TSMTP.Create;
IncludedInfo := [iiAppName,iiHost,iiUserName,iiOSVersion];
end;
destructor TLogEmailProvider.Destroy;
begin
fMail := nil;
if Assigned(fSMTP) then fSMTP.Free;
if Assigned(fSMTPConfig) then fSMTPConfig.Free;
if Assigned(fMailConfig) then fMailConfig.Free;
inherited;
end;
procedure TLogEmailProvider.Init;
begin
inherited;
fSMTP.Host := fSMTPConfig.Host;
fSMTP.Port := fSMTPConfig.Port;
fSMTP.Username := fSMTPConfig.UserName;
fSMTP.Password := fSMTPConfig.Password;
fSMTP.ServerAuth := fSMTPConfig.ServerAuth;
fSMTP.UseSSL := fSMTPConfig.UseSSL;
fSMTP.Mail.SenderName := fMailConfig.SenderName;
fSMTP.Mail.From := fMailConfig.From;
fSMTP.Mail.Recipient := fMailConfig.Recipient;
fSMTP.Mail.Subject := fMailConfig.Subject;
fSMTP.Mail.Body := fMailConfig.Body;
fSMTP.Mail.CC := fMailConfig.CC;
fSMTP.Mail.BCC := fMailConfig.BCC;
end;
procedure TLogEmailProvider.Restart;
begin
Stop;
Init;
end;
procedure TLogEmailProvider.WriteLog(cLogItem : TLogItem);
begin
if fSMTP.Mail.Subject = '' then fSMTP.Mail.Subject := Format('%s [%s] %s',[SystemInfo.AppName,EventTypeName[cLogItem.EventType],Copy(cLogItem.Msg,1,50)]);
if CustomMsgOutput then fSMTP.Mail.Body := LogItemToFormat(cLogItem)
else fSMTP.Mail.Body := LogItemToHtml(cLogItem);
fSMTP.SendMail;
end;
initialization
GlobalLogEmailProvider := TLogEmailProvider.Create;
finalization
if Assigned(GlobalLogEmailProvider) and (GlobalLogEmailProvider.RefCount = 0) then GlobalLogEmailProvider.Free;
end.
|
unit FastIMG;
interface
uses
Windows, Messages, Forms, Graphics, {DsgnIntf,} Classes, Controls, SysUtils,
Dialogs, FastRGB, FastBMP, Fast256;
type
TBMPFilename=type string;
{ TBMPFilenameProperty = class(TStringProperty)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end; }
TDrawStyle=(dsDraw,dsStretch,dsResize,dsTile,dsCenter);
TDataType=(dtFastBMP,dtFast256);
TFastIMG=class(TCustomControl)
private
fBmp: TFastRGB;
fDrawStyle: TDrawStyle;
fSmthSize,
fAutoSize: Boolean;
fDataType: TDataType;
fCMode: TConversionMode;
fFileName: TBMPFilename;
procedure SetBitmap(x:TFastRGB);
procedure SetSmthSize(x:Boolean);
procedure SetAutoSize(x:Boolean);
procedure SetDrawStyle(x:TDrawStyle);
procedure SetDataType(x:TDataType);
procedure SetConversionMode(x:TConversionMode);
procedure SetFileName(const x:TBMPFilename);
procedure Erase(var Msg:TWMEraseBkgnd); message WM_ERASEBKGND;
procedure Paint(var Msg:TWMPaint); message WM_PAINT;
public
constructor Create(AOwner:TComponent); override;
destructor Destroy; override;
procedure LoadFromFile(x:string);
property Bmp:TFastRGB read fBmp write SetBitmap;
published
property AutoSize:Boolean read fAutoSize write SetAutoSize;
property BilinearResize:Boolean read fSmthSize write SetSmthSize;
property DrawStyle:TDrawStyle read fDrawStyle write SetDrawStyle;
property DataType:TDataType read fDataType write SetDataType;
property Convert_256:TConversionMode read fCMode write SetConversionMode;
property FileName:TBMPFilename read fFileName write SetFileName;
property Align;
property Color;
property DragCursor;
property DragMode;
property Enabled;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Visible;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
end;
procedure register;
function IsPalette:Boolean;
implementation
function IsPalette:Boolean;
var
sdc: HDC;
begin
sdc:=GetDC(0);
Result:=GetDeviceCaps(sdc,BITSPIXEL)<9;
ReleaseDC(0,sdc);
end;
procedure register;
begin
RegisterComponents('Standard',[TFastIMG]);
// RegisterPropertyEditor(TypeInfo(TBMPFilename),nil,'',TBMPFilenameProperty);
end;
constructor TFastIMG.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
SetBounds(Left,Top,100,100);
end;
destructor TFastIMG.Destroy;
begin
fBmp:=nil;
inherited Destroy;
end;
procedure TFastIMG.Erase(var Msg:TWMEraseBkgnd);
begin
end;
procedure TFastIMG.SetBitmap(x:TFastRGB);
begin
fBmp:=x;
if fBmp is TFast256 then fDataType:=dtFast256 else
if fBmp is TFastBMP then fDataType:=dtFastBMP;
if fAutoSize then SetBounds(Left,Top,fBmp.Width,fBmp.Height);
end;
procedure TFastIMG.LoadFromFile(x:string);
begin
if FileExists(x) then
begin
if not Assigned(fBmp) then
begin
case fDataType of
dtFastBMP: fBmp:=TFastBMP.Create;
dtFast256: fBmp:=TFast256.Create;
end;
end;
case fDataType of
dtFastBMP: TFastBMP(fBmp).LoadFromFile(x);
dtFast256: TFast256(fBmp).LoadFromFile(x,fCMode);
end;
if fAutoSize then SetBounds(Left,Top,fBmp.Width,fBmp.Height);
end;
end;
procedure TFastIMG.SetAutoSize(x:Boolean);
begin
fAutoSize:=x;
if fAutoSize and Assigned(Bmp)then
begin
Align:=alNone;
SetBounds(Left,Top,Bmp.Width,Bmp.Height);
end;
end;
procedure TFastIMG.SetSmthSize(x:Boolean);
begin
fSmthSize:=x;
Refresh;
end;
procedure TFastIMG.SetDrawStyle(x:TDrawStyle);
begin
fDrawStyle:=x;
Refresh;
end;
procedure TFastIMG.SetDataType(x:TDataType);
begin
fDataType:=x;
if csDesigning in ComponentState then
begin
if Assigned(fBmp) then fBmp.Free;
case fDataType of
dtFastBMP: fBmp:=TFastBMP.Create;
dtFast256: fBmp:=TFast256.Create;
end;
if fFileName<>'' then LoadFromFile(fFileName);
Refresh;
end;
end;
procedure TFastIMG.SetConversionMode(x:TConversionMode);
begin
fCMode:=x;
if(csDesigning in ComponentState)and(fFileName<>'')then
LoadFromFile(fFileName);
Refresh;
end;
procedure TFastIMG.SetFileName(const x:TBMPFilename);
begin
if x='' then Bmp:=nil;
fFileName:=x;
LoadFromFile(x);
Refresh;
end;
procedure TFastIMG.Paint(var Msg:TWMPaint);
var
ps: TPaintStruct;
r1,r2: HRGN;
ax,ay: Single;
iw,ih,
cx,cy: Integer;
Tmp: TFastRGB;
begin
BeginPaint(Handle,ps);
if Assigned(Bmp)then case fDrawStyle of
dsDraw:
begin
if(Width>fBmp.Width)or(Height>fBmp.Height)then
begin
r1:=CreateRectRgn(0,0,Width,Height);
r2:=CreateRectRgn(0,0,fBmp.Width,fBmp.Height);
CombineRgn(r1,r1,r2,RGN_XOR);
DeleteObject(r2);
FillRgn(ps.hdc,r1,Brush.Handle);
DeleteObject(r1);
end;
fBmp.Draw(ps.hdc,0,0);
end;
dsStretch:
begin
if fSmthSize then
begin
case fDataType of
dtFastBMP: Tmp:=TFastBMP.Create;
dtFast256:
begin
Tmp:=TFast256.Create;
TFast256(Tmp).Colors^:=TFast256(fBmp).Colors^;
end;
end;
Tmp.SetSize(Width,Height);
fBmp.SmoothResize(Tmp);
Tmp.Draw(ps.hdc,0,0);
Tmp.Free;
end else
fBmp.Stretch(ps.hdc,0,0,Width,Height);
end;
dsResize:
begin
if fBmp.Width=0 then iw:=1 else iw:=fBmp.Width;
if fBmp.Height=0 then ih:=1 else ih:=fBmp.Height;
ax:=Width/iw;
ay:=Height/ih;
if ax>ay then
begin
ax:=fBmp.Width*ay; ay:=Height;
cx:=Round((Width-ax)/2); cy:=0;
end else
begin
ay:=fBmp.Height*ax; ax:=Width;
cy:=Round((Height-ay)/2); cx:=0;
end;
iw:=Round(ax); ih:=Round(ay);
if(cx<>0)or(cy<>0)then
begin
r1:=CreateRectRgn(0,0,Width,Height);
r2:=CreateRectRgn(cx,cy,iw+cx,ih+cy);
CombineRgn(r1,r1,r2,RGN_XOR);
DeleteObject(r2);
FillRgn(ps.hdc,r1,Brush.Handle);
DeleteObject(r1);
end;
if fSmthSize then
begin
case fDataType of
dtFastBMP:
begin
Tmp:=TFastBMP.Create;
TFastBMP(Tmp).SetSize(iw,ih);
end;
dtFast256:
begin
Tmp:=TFast256.Create;
TFast256(Tmp).SetSize(iw,ih);
TFast256(Tmp).Colors^:=TFast256(fBmp).Colors^;
end;
end;
fBmp.SmoothResize(Tmp);
Tmp.Draw(ps.hdc,cx,cy);
Tmp.Free;
end else
fBmp.Stretch(ps.hdc,cx,cy,iw,ih);
end;
dsTile: fBmp.TileDraw(ps.hdc,0,0,Width,Height);
dsCenter:
begin
cx:=(Width-fBmp.Width)div 2;
cy:=(Height-fBmp.Height)div 2;
if(Width>fBmp.Width)or(Height>fBmp.Height)then
begin
r1:=CreateRectRgn(0,0,Width,Height);
r2:=CreateRectRgn(cx,cy,fBmp.Width+cx,fBmp.Height+cy);
CombineRgn(r1,r1,r2,RGN_XOR);
DeleteObject(r2);
FillRgn(ps.hdc,r1,Brush.Handle);
DeleteObject(r1);
end;
fBmp.Draw(ps.hdc,cx,cy);
end;
end else //fBmp=nil
FillRect(ps.hdc,ps.rcPaint,Brush.Handle);
if(csDesigning in ComponentState)then
DrawFocusRect(ps.hdc,RECT(0,0,Width,Height));
EndPaint(Handle,ps);
end;
{TBMPFilenameProperty}
{procedure TBMPFilenameProperty.Edit;
begin
with TOpenDialog.Create(Application) do
begin
FileName:=GetValue;
Filter:='bitmaps (*.bmp)|*.bmp';
Options:=Options+[ofPathMustExist,ofFileMustExist,ofHideReadOnly];
if Execute then SetValue(Filename);
Free;
end;
end;
function TBMPFilenameProperty.GetAttributes: TPropertyAttributes;
begin
Result:=[paDialog,paRevertable];
end; }
end.
|
unit uPrK_Edit_Filtr_FndCompEdit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, ActnList, StdCtrls, cxButtons,
cxTextEdit, cxControls, cxContainer, cxEdit, cxLabel,AArray;
type
TFormPrK_Edit_Filtr_FndCompEdit = class(TForm)
cxLabelName: TcxLabel;
cxTextEditName: TcxTextEdit;
cxLabelID: TcxLabel;
cxTextEditID: TcxTextEdit;
cxButtonOK: TcxButton;
cxButtonCansel: TcxButton;
ActionListKlassSpravEdit: TActionList;
ActionOK: TAction;
ActionCansel: TAction;
procedure cxTextEditIDKeyPress(Sender: TObject; var Key: Char);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ActionCanselExecute(Sender: TObject);
procedure ActionOKExecute(Sender: TObject);
private
Layout: array[0.. KL_NAMELENGTH] of char;
DataVL :TAArray;
IndLang: int64;
procedure InicCaption;
public
constructor Create(aOwner: TComponent;aDataVL :TAArray);overload;
end;
var
FormPrK_Edit_Filtr_FndCompEdit: TFormPrK_Edit_Filtr_FndCompEdit;
implementation
uses
uPrK_Resources,uConstants;
{$R *.dfm}
procedure TFormPrK_Edit_Filtr_FndCompEdit.cxTextEditIDKeyPress(
Sender: TObject; var Key: Char);
begin
if (Key = '.') or (Key=',') then Key := Chr(0);
if ((Ord(Key) < 48) or (Ord(Key) > 57))
and (Ord(Key) <> 8)
and (Ord(Key) <> VK_DELETE)
then Key := Chr(0);
end;
constructor TFormPrK_Edit_Filtr_FndCompEdit.Create(aOwner: TComponent;
aDataVL: TAArray);
begin
DataVL :=aDataVL;
IndLang :=SelectLanguage;
inherited Create(aOwner);
inicCaption;
end;
procedure TFormPrK_Edit_Filtr_FndCompEdit.InicCaption;
begin
cxLabelName.Caption := nLabelName[IndLang];
cxLabelID.Caption := nLabelID[IndLang];
ActionOK.Caption :=nActiont_OK[IndLang];
ActionCansel.Caption :=nActiont_Cansel[IndLang];
ActionOK.Hint :=nHintActiont_OK[IndLang];
ActionCansel.Hint :=nHintActiont_Cansel[IndLang];
end;
procedure TFormPrK_Edit_Filtr_FndCompEdit.FormShow(Sender: TObject);
begin
{422-урк, 409-англ, 419-рус}
LoadKeyboardLayout( StrCopy(Layout,nLayoutLang[IndLang]),KLF_ACTIVATE);
end;
procedure TFormPrK_Edit_Filtr_FndCompEdit.FormCreate(Sender: TObject);
begin
cxTextEditName.Text :=DataVL['Name'].AsString;
cxTextEditID.Text :=DataVL['ID'].AsString;
end;
procedure TFormPrK_Edit_Filtr_FndCompEdit.ActionCanselExecute(
Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TFormPrK_Edit_Filtr_FndCompEdit.ActionOKExecute(Sender: TObject);
begin
if trim(cxTextEditName.Text)='' then
begin
ShowMessage(nMsgEmptyName[IndLang]);
cxTextEditName.SetFocus;
exit;
end;
if trim(cxTextEditId.Text)='' then
begin
ShowMessage(nMsgEmptyId[IndLang]);
cxTextEditId.SetFocus;
exit;
end;
DataVL['Name'].AsString :=cxTextEditName.Text;
DataVL['ID'].AsString :=cxTextEditId.Text;
ModalResult:=mrOk;
end;
end.
|
{Una entidad bancaria exige una las siguiente condiciones para otorgar un crédito a un cliente
- Es propietario de un inmueble tasado en $1000000 o mas y tiene un sueldo menor o igual a
$1000
- Es propietario de un inmueble tasado en hasta $1000000 y tiene un sueldo de mas de $1000
-No es propietario , pero tiene mas de 5 años de antigüedad en el trabajo y gana mas de $1500
mensuales.
Determine los datos que se requieren para ser merecedor de un crédito}
Program TP1eje8;
Var
antiguedad:byte;
inmueble,sueldo:real;
propietario:char;
Begin
write('Es propietario de algun inmueble ? S / N : ');readln(propietario);
write('Cual es el valor de su inmueble ? : ');readln(inmueble);
write('Ingrese su sueldo mensual : ');readln(sueldo);
write('Cuantos anios tiene de antiguedad en el trabajo? : ');readln(antiguedad);
If (propietario = 'S') and (inmueble >= 1000000) and (sueldo <= 1000) then
write('Es merecedor del credito')
Else
if (propietario = 'S') and (inmueble < 1000000) and (sueldo > 1000) then
write('Es merecedor del credito')
Else
if (propietario = 'N') and (antiguedad > 5) and (sueldo > 1500) then
write('Es merecedor del credito')
Else
write('No merece el credito');
end.
|
unit Cliente;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, StdCtrls, Mask, DBCtrls, XPMan, IBCustomDataSet,
IBQuery;
type
TF_Cliente = class(TForm)
BNovo: TButton;
BGravar: TButton;
BExcluir: TButton;
BEditar: TButton;
XPManifest1: TXPManifest;
BSair: TButton;
BConsultaCadastros: TButton;
LCODIGO: TLabel;
CODIGO: TDBEdit;
LNOME_FANTASIA: TLabel;
NOME_FANTASIA: TDBEdit;
LRAZAO_SOCIAL: TLabel;
RAZAO_SOCIAL: TDBEdit;
LCPF: TLabel;
CPF: TDBEdit;
LCODIGOCONCEITO: TLabel;
CODIGOCONCEITO: TDBEdit;
LImRelato: TLabel;
BImRelat: TButton;
LRuim: TLabel;
LBom: TLabel;
LOtimo: TLabel;
procedure BSairClick(Sender: TObject);
procedure BNovoClick(Sender: TObject);
procedure BConsultaCadastrosClick(Sender: TObject);
procedure BGravarClick(Sender: TObject);
procedure BExcluirClick(Sender: TObject);
procedure BEditarClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure NOME_FANTASIAKeyPress(Sender: TObject; var Key: Char);
procedure RAZAO_SOCIALKeyPress(Sender: TObject; var Key: Char);
procedure CPFKeyPress(Sender: TObject; var Key: Char);
procedure BNovoKeyPress(Sender: TObject; var Key: Char);
procedure BGravarKeyPress(Sender: TObject; var Key: Char);
procedure BExcluirKeyPress(Sender: TObject; var Key: Char);
procedure BEditarKeyPress(Sender: TObject; var Key: Char);
procedure BSairKeyPress(Sender: TObject; var Key: Char);
procedure BConsultaCadastrosKeyPress(Sender: TObject; var Key: Char);
procedure quebraconceito;
procedure totalgeral;
procedure RDprint1BeforeNewPage(Sender: TObject; Pagina: Integer);
procedure RDprint1NewPage(Sender: TObject; Pagina: Integer);
procedure BImRelatClick(Sender: TObject);
procedure CODIGOCONCEITOKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
{ Public declarations }
end;
var
F_Cliente: TF_Cliente;
linha : Integer;
subtotal : Integer;
var_conceito : string;
implementation
uses ModuloGeral, UnitConsultaCliente, DateUtils,
Math, TypInfo;
{$R *.dfm}
procedure TF_Cliente.BSairClick(Sender: TObject);
begin
Close;
end;
procedure TF_Cliente.BConsultaCadastrosClick(Sender: TObject);
begin
Application.CreateForm(TFConsultaCliente,FConsultaCliente);//chama o formulario de consulta de cliente
FConsultaCliente.Show;
end;
procedure TF_Cliente.BGravarClick(Sender: TObject);
begin
if NOME_FANTASIA.Text = '' then // Tratamento de campo obrigatorio
begin
Application.MessageBox('Campo NOME_FANTASIA Obrigatorio','Cadastro de Clientes',MB_OK+MB_ICONHAND);
NOME_FANTASIA.SetFocus;
Abort;
end;
if RAZAO_SOCIAL.Text = '' then // Tratamento de campo obrigatorio
begin
Application.MessageBox('Campo RAZAO_SOCIAL Obrigatorio','Cadastro de Clientes',MB_OK+MB_ICONHAND);
RAZAO_SOCIAL.SetFocus;
Abort;
end;
if CPF.Text = '' then // Tratamento de campo obrigatorio
begin
Application.MessageBox('Campo CPF Obrigatorio','Cadastro de Clientes',MB_OK+MB_ICONHAND);
CPF.SetFocus;
Abort;
end;
try //Tratamento de exeção
{With dmGeral.Cliente do //Determina um bloco de comandos para executar uma determinada ação
begin
Post; //
dmGeral.Dados.ApplyUpdates([dmGeral.Cliente]); // Atualiza a tabela e grava
dmGeral.Tr_Dados.CommitRetaining; // Método Responsavel por confirmar a transação, mas a mantém ativa
Refresh;
Close; //Fecha query o bloco de comandos
end; }
//Tratando os Butões do Cadastro
BNovo.Enabled := True; //ativa
BExcluir.Enabled := false;//desativa
BEditar.Enabled := false; //desativa
BGravar.Enabled := false; //desativa
BConsultaCadastros.Enabled := true; //ativa
Application.MessageBox('Cadastro Realizado Com Sucesso','Cadastro de Clientes',MB_OK+MB_OK);
except //Tratamento de Exeção, Se ocorrer um erro no processo de gravação no banco de dados
Application.MessageBox('Cadastro Não Realizado','Cadastro de Clientes',MB_OK+MB_OK);
end;
end;
procedure TF_Cliente.BExcluirClick(Sender: TObject);
begin
try //Tratamento de uma exeção
// With dmGeral.Cliente do //Determina um bloco de comandos para executar uma determinada ação
begin
// Delete; //Deleta um registro
Close; //fecha a query o bloco de comando
end;
//Tratamento dos butões
BNovo.Enabled := true;
BExcluir.Enabled := false;
BEditar.Enabled := false;
BGravar.Enabled := true;
BConsultaCadastros.Enabled := true;
NOME_FANTASIA.Enabled := true;
RAZAO_SOCIAL.Enabled := true;
CPF.Enabled := true;
NOME_FANTASIA.SetFocus;
Application.MessageBox('Exclusão Realizada Com Sucesso','Cadastro de Clientes',MB_OK+MB_ICONERROR);
except //Tratamento de Exeção, Se ocorrer um erro no processo de gravação no banco de dados
Application.MessageBox('Exclusão Não Realizada','Cadastro de Clientes',MB_OK+MB_ICONERROR);
end;
end;
procedure TF_Cliente.BEditarClick(Sender: TObject);
begin
//dmGeral.Cliente.Edit; // A query entra em modo de edição
// Tratando os butões
BNovo.Enabled := false;
BExcluir.Enabled := false;
BEditar.Enabled := false;
BGravar.Enabled := true;
BConsultaCadastros.Enabled := false;
NOME_FANTASIA.Enabled := true;
RAZAO_SOCIAL.Enabled := true;
CPF.Enabled := true;
end;
procedure TF_Cliente.BNovoClick(Sender: TObject);
begin
// With dmGeral.Cliente do //Determina um bloco de comandos para executar uma determinada ação
begin
// Close; //Fecha a Query
//Open; //Abre a Query
//Append; //
end;
//Tratamento dos butões
BNovo.Enabled := false;
BExcluir.Enabled := false;
BEditar.Enabled := false;
BGravar.Enabled := true;
BConsultaCadastros.Enabled := false;
NOME_FANTASIA.SetFocus;
end;
procedure TF_Cliente.FormCreate(Sender: TObject);
begin
//Tratamento dos butões
CODIGO.Enabled := False;
BGravar.Enabled := False;
BExcluir.Enabled := False;
BEditar.Enabled := False;
end;
procedure TF_Cliente.NOME_FANTASIAKeyPress(Sender: TObject; var Key: Char);
begin
if key=#13 then
begin
key := #0; // tira o tab pelo o enter.
Perform(WM_NEXTDLGCTL,0,0);
end;
end;
procedure TF_Cliente.RAZAO_SOCIALKeyPress(Sender: TObject; var Key: Char);
begin
if key=#13 then
begin
key := #0; // tira o tab pelo o enter.
Perform(WM_NEXTDLGCTL,0,0);
end;
end;
procedure TF_Cliente.CPFKeyPress(Sender: TObject; var Key: Char);
begin
if key=#13 then
begin
key := #0; // tira o tab pelo o enter.
Perform(WM_NEXTDLGCTL,0,0);
end;
end;
procedure TF_Cliente.BNovoKeyPress(Sender: TObject; var Key: Char);
begin
if key=#13 then
begin
key := #0; // tira o tab pelo o enter.
Perform(WM_NEXTDLGCTL,0,0);
end;
end;
procedure TF_Cliente.BGravarKeyPress(Sender: TObject; var Key: Char);
begin
if key=#13 then
begin
key := #0; // tira o tab pelo o enter.
Perform(WM_NEXTDLGCTL,0,0);
end;
end;
procedure TF_Cliente.BExcluirKeyPress(Sender: TObject; var Key: Char);
begin
if key=#13 then
begin
key := #0; // tira o tab pelo o enter.
Perform(WM_NEXTDLGCTL,0,0);
end;
end;
procedure TF_Cliente.BEditarKeyPress(Sender: TObject; var Key: Char);
begin
if key=#13 then
begin
key := #0; // tira o tab pelo o enter.
Perform(WM_NEXTDLGCTL,0,0);
end;
end;
procedure TF_Cliente.BSairKeyPress(Sender: TObject; var Key: Char);
begin
if key=#13 then
begin
key := #0; // tira o tab pelo o enter.
Perform(WM_NEXTDLGCTL,0,0);
end;
end;
procedure TF_Cliente.BConsultaCadastrosKeyPress(Sender: TObject; var Key: Char);
begin
if key=#13 then
begin
key := #0; // tira o tab pelo o enter.
Perform(WM_NEXTDLGCTL,0,0);
end;
end;
procedure TF_Cliente.quebraconceito;
begin
{ if linha > 59 then
rdprint1.novapagina;
// Imprime o cabecalho da quebra...
rdprint1.imp (linha,1,'-----------------------------------------------------------------------------------------------');
inc(linha);
rdprint1.impf(linha,1,'Conceito: ' + var_conceito,[negrito]);
inc(linha);
rdprint1.imp(Linha,1,'-----------------------------------------------------------------------------------------------');
inc(linha); }
end;
procedure TF_Cliente.totalgeral;
begin
{ if var_conceito = 'Forca quebra' then // Não tem sub-total ainda pois é o 1º vez
begin
var_conceito := IntToStr(dmGeral.ClienteCODIGOCONCEITO.Value); // atuvaliza a quebra...
Exit;
end;
// Imprime total da quebra...
if linha > 61 then
begin
rdprint1.novapagina;
quebraconceito;
end
else
begin
rdprint1.imp (linha,1,'-----------------------------------------------------------------------------------------------');
inc(linha);
end;
rdprint1.impf (linha,10,'Total de Conceito ==> ',[negrito]);
rdprint1.impval(linha,81,'###,###,##0.00',subtotal,[negrito]);
inc(linha);
// atualizo variaveis de controle da quebra...
var_conceito := IntToStr(dmGeral.ClienteCODIGOCONCEITO.Value); // atualiza a quebra...
subtotal := 0; }
end;
procedure TF_Cliente.RDprint1BeforeNewPage(Sender: TObject;
Pagina: Integer);
begin
// Rodapé...
{ rdprint1.imp (65,01,'===============================================================================================',clGreen);
rdprint1.impf(66,01,'Araguaia Sistemas',[italico],clGreen);
rdprint1.impf(66,65,'Relatório',[comp17],clGreen);}
end;
procedure TF_Cliente.RDprint1NewPage(Sender: TObject; Pagina: Integer);
begin
// Cabeçalho...
{ rdprint1.imp (01,01,'===============================================================================================',clred);
rdprint1.impc(02,48,'RELATÓRIO DE CLIENTES', [expandido,NEGRITO],clblue);
rdprint1.impf(03,01,'Araguaia Sistemas',[normal]);
rdprint1.impf(63,82,'Página: ' + formatfloat('000',pagina),[normal]);
rdprint1.imp (04,01,'===============================================================================================',clred);
rdprint1.imp (05,01,'[Cód][ Nome Fantasia ] [ Razão Social ] [ CFP ] [ Conceito]');
Linha := 6; }
end;
procedure TF_Cliente.BImRelatClick(Sender: TObject);
var
total_quebra : Integer;
begin
{ rdprint1.abrir;
linha := 7;
subtotal := 0;
total_quebra := 0;
dmGeral.Cliente.Active := True;
dmGeral.Cliente.First;
var_conceito := 'Forca quebra'; // Força 1º Quebra...
while not dmGeral.Cliente.Eof do
begin
if dmGeral.ClienteCODIGOCONCEITO.Value <> total_quebra then // Quebra a conceito...
begin
totalgeral; // total da quebra...
quebraconceito; // cabecalho do conceito...
subtotal := 0;
end;
if linha > 63 then // Salto de Pagina chama automaticamente cabecalho/rodape...
begin
rdprint1.novapagina;
quebraconceito;
end;
// Detalhes do relatório...
rdprint1.imp (linha,01,formatfloat('0000',dmGeral.ClienteCODIGO.value));
rdprint1.impF(linha,07,dmGeral.ClienteNOME_FANTASIA.value,[comp17]);
rdprint1.imp (linha,44,dmGeral.ClienteRAZAO_SOCIAL.value);
rdprint1.imp (linha,66,dmGeral.ClienteCPF.value);
//rdprint1.imp (linha,70,dmGeral.ClienteCODIGOCONCEITO.AsString);
// Este comando imprime valores alinhados à direita...
if dmGeral.ClienteCODIGOCONCEITO.value < 500 then
rdprint1.imp (linha,89,dmGeral.ClienteCODIGOCONCEITO.AsString)
else
rdprint1.imp (linha,89,dmGeral.ClienteCODIGOCONCEITO.AsString);
// rdprint1.ImpF(Linha,81,'###,###,##0.00',dmGeral.ClienteCODIGOCONCEITO.Value,[]);
inc(linha);
// Soma o totais...
subtotal := subtotal + 1;
//total_quebra := total_quebra + 1;
total_quebra := dmGeral.ClienteCODIGOCONCEITO.Value;
dmGeral.Cliente.Next;
end;
// Imprime o total da quebra...
total_quebra := dmGeral.Cliente.RecordCount;
totalgeral;
// Imprime total geral...
if linha > 61 then
rdprint1.novapagina;
rdprint1.imp(Linha,1,'-----------------------------------------------------------------------------------------------');
inc(linha);
rdprint1.impf (linha,10,'Total Geral de Conceito ==> ',[negrito]);
rdprint1.impval(linha,81,'###,###,##0.00', total_quebra,[negrito]);
rdprint1.fechar; // Encerra o relatório...
dmGeral.Cliente.active := false; // Fecha a tabela...
}
end;
//end;
procedure TF_Cliente.CODIGOCONCEITOKeyPress(Sender: TObject;
var Key: Char);
begin
if key=#13 then
begin
key := #0; // tira o tab pelo o enter.
Perform(WM_NEXTDLGCTL,0,0);
end;
if not (Key in ['1','2','3']) then
Key := #0;
end;
end.
|
unit SomeProcessor;
interface
type TSomeProcessor = class
end;
implementation
uses
AnotherProcessor,
SomeRegistry;
initialization
GetSomeRegistry.RegisterClass(TSomeProcessor);
finalization
GetSomeRegistry.DeregisterClass(TSomeProcessor);
end.
|
unit netcardinfo;
interface
uses Windows, SysUtils,Dialogs;
Const
MAX_ADAPTER_NAME_LENGTH = 256;
MAX_ADAPTER_DESCRIPTION_LENGTH = 128;
MAX_ADAPTER_ADDRESS_LENGTH = 8;
Type
TIPAddressString = Array[0..4*4-1] of Char;
PIPAddrString = ^TIPAddrString;
TIPAddrString = Record
Next : PIPAddrString;
IPAddress : TIPAddressString;
IPMask : TIPAddressString;
Context : Integer;
End;
PIPAdapterInfo = ^TIPAdapterInfo;
TIPAdapterInfo = Record { IP_ADAPTER_INFO }
Next : PIPAdapterInfo;
ComboIndex : Integer;
AdapterName : Array[0..MAX_ADAPTER_NAME_LENGTH+3] of Char;
Description : Array[0..MAX_ADAPTER_DESCRIPTION_LENGTH+3] of Char;
AddressLength : Integer;
Address : Array[1..MAX_ADAPTER_ADDRESS_LENGTH] of Byte;
Index : Integer;
_Type : Integer;
DHCPEnabled : Integer;
CurrentIPAddress : PIPAddrString;
IPAddressList : TIPAddrString;
GatewayList : TIPAddrString;
End;
function getnetcardinfo:string;
function getudpbroadaddr:string;
function getlocalip:string;
implementation
Function GetAdaptersInfo(AI : PIPAdapterInfo; Var BufLen : Integer) : Integer;
StdCall; External 'iphlpapi.dll' Name 'GetAdaptersInfo';
Function MACToStr(ByteArr : PByte; Len : Integer) : String;
Begin
Result := '';
While (Len > 0) do Begin
Result := Result+IntToHex(ByteArr^,2)+'-';
ByteArr := Pointer(Integer(ByteArr)+SizeOf(Byte));
Dec(Len);
End;
SetLength(Result,Length(Result)-1); { remove last dash }
End;
Function GetAddrString(Addr : PIPAddrString) : String;
Begin
Result := '';
While (Addr <> nil) do Begin
Result := Result+'A: '+Addr^.IPAddress+' M: '+Addr^.IPMask+#13;
Addr := Addr^.Next;
End;
End;
function getnetcardinfo:string;
var
AI,Work : PIPAdapterInfo;
Size : Integer;
Res : Integer;
s:string;
begin
Size := 5120;
GetMem(AI,Size);
work:=ai;
Res := GetAdaptersInfo(AI,Size);
If (Res <> ERROR_SUCCESS) Then
Begin
//SetLastError(Res);
//RaiseLastWin32Error;
result:=''; exit;
End;
s:='';
{
s:=s+'Adapter address: '+MACToStr(@Work^.Address,Work^.AddressLength);
repeat
s:=s+' IP addresses: '+GetAddrString(@Work^.IPAddressList);
work:=work^.Next ;
until (work=nil);
}
s:=GetAddrString(@Work^.IPAddressList);
result:=s;
end;
{
procedure TForm1.Button1Click(Sender: TObject);
var
AI,Work : PIPAdapterInfo;
Size : Integer;
Res : Integer;
begin
Size := 5120;
GetMem(AI,Size);
work:=ai;
Res := GetAdaptersInfo(AI,Size);
If (Res <> ERROR_SUCCESS) Then Begin
SetLastError(Res);
RaiseLastWin32Error;
End;
memo1.Lines.Add ('Adapter address: '+MACToStr(@Work^.Address,Work^.AddressLength));
repeat
memo1.Lines.add(' IP addresses: '+GetAddrString(@Work^.IPAddressList));
work:=work^.Next ;
until (work=nil);
end;
}
//------------
function getip(valuestr:string):string;
var i:integer;
s,a,b,c,d:string;
rets:string;
begin
rets:='0000';
s:=valuestr;
i:=pos('.',s);
if i=0 then
begin
result:='';
exit;
end;
a:=copy(s,1,i-1);
s:=copy(s,i+1,length(s));
i:=pos('.',s);
if i=0 then
begin
result:='';
exit;
end;
b:=copy(s,1,i-1);
s:=copy(s,i+1,length(s));
i:=pos('.',s);
if i=0 then
begin
result:='';
exit;
end;
c:=copy(s,1,i-1);
s:=copy(s,i+1,length(s));
d:=s;
try
if ((strtoint(a)>255) or (strtoint(a)<0)) then
begin
result:=''; exit;
end;
if ((strtoint(b)>255) or (strtoint(b)<0)) then
begin
result:=''; exit;
end;
if ((strtoint(c)>255) or (strtoint(c)<0)) then
begin
result:=''; exit;
end;
if ((strtoint(d)>255) or (strtoint(d)<0)) then
begin
result:=''; exit;
end;
rets[1]:=chr(strtoint(a));
rets[2]:=chr(strtoint(b));
rets[3]:=chr(strtoint(c));
rets[4]:=chr(strtoint(d));
except
result:='';
exit;
end;
result:=rets;
end;
function getlocalip:string;
var s,s2:string;
maskbytes:string;
ipaddrbytes:string;
pos1,pos2,pos3:integer;
tmps1,tmps2:string;
begin
s:=getnetcardinfo;
if s='' then
begin
result:='127.0.0.1';
exit;
end;
pos1:=pos('A:',s); pos2:=pos('M:',s); pos3:=pos(chr($D),s);
//ip addr
result:=trim(copy(s,pos1+2,pos2-pos1-2));
end;
function getudpbroadaddr:string;
var s,s2:string;
maskbytes:string;
ipaddrbytes:string;
pos1,pos2,pos3:integer;
tmps1,tmps2:string;
begin
s:=getnetcardinfo;
if s='' then
begin
showmessage('请检查本机网络连接是否正常');
end;
pos1:=pos('A:',s); pos2:=pos('M:',s); pos3:=pos(chr($D),s);
//ip addr
s2:=trim(copy(s,pos1+2,pos2-pos1-2));
if s2='0.0.0.0' then showmessage('请检查本机网络连接是否正常');
ipaddrbytes:=getip(s2);
//subnet
s2:=trim(copy(s,pos2+2,pos3-pos2-2));
maskbytes:=getip(s2);
tmps1:=chr(ord(ipaddrbytes[1]) and ord(maskbytes[1]))+
chr(ord(ipaddrbytes[2]) and ord(maskbytes[2]))+
chr(ord(ipaddrbytes[3]) and ord(maskbytes[3]))+
chr(ord(ipaddrbytes[4]) and ord(maskbytes[4]));
tmps2:=chr(ord(maskbytes[1]) xor $FF)+chr(ord(maskbytes[2]) xor $FF)+
chr(ord(maskbytes[3]) xor $FF)+chr(ord(maskbytes[4]) xor $FF);
//udp broadcast add
result:= inttostr( ord(tmps1[1])+ ord(tmps2[1]) ) +'.'+
inttostr( ord(tmps1[2])+ ord(tmps2[2]) ) +'.'+
inttostr( ord(tmps1[3])+ ord(tmps2[3]) ) +'.'+
inttostr( ord(tmps1[4])+ ord(tmps2[4]) ) ;
end;
//-----------
end.
|
unit uLotofacil;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, strUtils;
type
{ Lotofacil }
{ TLotofacil }
TLotofacil = class
procedure Analisar_Html(tokens_html: TStrings; out strErro: string);
end;
implementation
{ TLotofacil }
procedure TLotofacil.Analisar_Html(tokens_html: TStrings; out strErro: string);
var
uTag_Tabela_Inicio: Integer;
uTag_Tabela_Fim: Integer;
uIndice: Integer;
uIndice_Cabecalho_Inicio: Integer;
uIndice_Cabecalho_Fim: Integer;
uColuna_Quantidade: Integer;
begin
if Assigned(tokens_html) = false then begin
strErro:= 'tokens_html é nulo.';
Exit;
end;
if tokens_html.Count = 0 then begin
strErro:= 'tokens_html está vazio.';
end;
// Vamos verifica se existe um tag html de tabela.
uTag_Tabela_Inicio := tokens_html.IndexOf('<table');
// if uTag_Table_Posicao = -1, vamos verificar se esta na forma '<table'>
if uTag_Tabela_Inicio = -1 then begin
uTag_Tabela_Inicio := tokens_html.IndexOf('<table>');
if uTag_Tabela_Inicio = -1 then begin
strErro := 'Não existe uma tabela no conteúdo html.';
Exit;
end;
end;
// Vamos verifica se existe um tag html de fim de tabela: '</table>':
uTag_Tabela_Fim := tokens_html.IndexOf('</table');
if uTag_Tabela_Fim = -1 then begin
// Não encontramos o fim da tabela indicar um erro.
strErro:= 'Existe o tag de início de tabela, entretanto, não existe ' +
' o tag de fim de tabela.';
Exit;
end;
// Vamos apontar um token após '<table'
uIndice := uTag_Tabela_Inicio + 1;
// Vamos localizar o início do cabeçalho.
while (uIndice <= uTag_Tabela_Fim) and
(AnsiStartsStr('<tr', tokens_html.Strings[uIndice]) = false) do begin
Inc(uIndice);
end;
// Vamos verificar se realmente, encontramos o token '<tr>' ou '<tr'
if (tokens_html.Strings[uIndice] <> '<tr>') and
(tokens_html.Strings[uIndice] <> '<tr') then begin
strErro := 'Tag ''<tr'' ou ''<tr>'' não localizado.';
Exit;
end;
uIndice_Cabecalho_Inicio := uIndice;
// Vamos localizar o fim do cabeçalho.
while (uIndice <= uTag_Tabela_Fim) and
(tokens_html.Strings[uIndice] <> '</tr>') do begin
Inc(uIndice);
end;
if uIndice > uTag_Tabela_Fim then begin
strErro := 'Fim inesperado do arquivo, tag de fim de fileira de cabeçalho ' +
' não localizado.';
Exit;
end;
uIndice_Cabecalho_Fim := uIndice;
uColuna_Quantidade := 0;
end;
end.
|
unit UDemoMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ExtDlgs, ComCtrls;
type
TFrmDemoMain = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
ScrollBox1: TScrollBox;
Splitter1: TSplitter;
ScrollBox2: TScrollBox;
imgOriginal: TImage;
imgResized: TImage;
btnDoBicubic: TButton;
btnDoStretchBlt: TButton;
ckbEnableHalftone: TCheckBox;
btnDoOpenBMP: TButton;
OpenPictureDialog1: TOpenPictureDialog;
ProgressBar1: TProgressBar;
GroupBox1: TGroupBox;
TrackBar1: TTrackBar;
lblScaleValue: TLabel;
lblOriginalValue: TLabel;
lblResizedValue: TLabel;
Bevel1: TBevel;
procedure btnDoBicubicClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnDoStretchBltClick(Sender: TObject);
procedure btnDoOpenBMPClick(Sender: TObject);
procedure TrackBar1Change(Sender: TObject);
procedure Splitter1Moved(Sender: TObject);
procedure lblScaleValueClick(Sender: TObject);
private
{ Déclarations privées }
procedure SetScale;
public
{ Déclarations publiques }
end;
var
FrmDemoMain: TFrmDemoMain;
implementation
uses Bicubics;
{$R *.dfm}
var
aBmp: TBitmap;
ScaleValue: Extended = 1.0;
procedure TFrmDemoMain.btnDoBicubicClick(Sender: TObject);
begin
BiCubicScale(imgOriginal.Picture.Bitmap, imgOriginal.Picture.Bitmap.Width, imgOriginal.Picture.Bitmap.Height,
imgResized.Picture.Bitmap, imgResized.Picture.Bitmap.Width, imgResized.Picture.Bitmap.Height,
ProgressBar1.StepIt);
imgResized.Invalidate;
end;
procedure TFrmDemoMain.btnDoStretchBltClick(Sender: TObject);
var pt : TPoint;
begin
if ckbEnableHalftone.Checked then
if GetStretchBltMode(imgResized.Picture.Bitmap.Canvas.Handle) <> HalfTone then
begin
GetBrushOrgEx(imgResized.Picture.Bitmap.Canvas.Handle, pt);
SetStretchBltMode(imgResized.Picture.Bitmap.Canvas.Handle, HalfTone); { }
SetBrushOrgEx(imgResized.Picture.Bitmap.Canvas.Handle, pt.x, pt.y, @pt);
end;
StretchBlt(imgResized.Picture.Bitmap.Canvas.Handle, 0, 0,
imgResized.Picture.Bitmap.Width, imgResized.Picture.Bitmap.Height,
imgOriginal.Picture.Bitmap.Canvas.Handle, 0, 0,
imgOriginal.Picture.Bitmap.Width, imgOriginal.Picture.Bitmap.Height, SRCCOPY);
imgResized.Invalidate;
end;
procedure TFrmDemoMain.btnDoOpenBMPClick(Sender: TObject);
begin
if OpenPictureDialog1.Execute then
begin
imgOriginal.Picture.Bitmap.LoadFromFile(OpenPictureDialog1.FileName);
TrackBar1Change(self);
TrackBar1.SetFocus;
end;
end;
procedure TFrmDemoMain.FormCreate(Sender: TObject);
begin
aBmp := TBitmap.Create;
imgResized.Picture.Bitmap := aBmp;
TrackBar1Change(self);
imgResized.Picture.Bitmap.Canvas.Pixels[0,0] := imgResized.Picture.Bitmap.Canvas.Pixels[0,0];
end;
procedure TFrmDemoMain.FormDestroy(Sender: TObject);
begin
aBmp.Free;
end;
procedure TFrmDemoMain.lblScaleValueClick(Sender: TObject);
begin
TrackBar1.SetFocus;
end;
procedure TFrmDemoMain.SetScale;
begin
imgResized.Picture.Bitmap.Width := Round(imgOriginal.Picture.Bitmap.Width * ScaleValue);
imgResized.Picture.Bitmap.Height := Round(imgOriginal.Picture.Bitmap.Height * ScaleValue);
ProgressBar1.Max := imgResized.Picture.Bitmap.Height;
ProgressBar1.Position := 0;
end;
procedure TFrmDemoMain.Splitter1Moved(Sender: TObject);
begin
lblResizedValue.Left := ScrollBox2.Left + 6;
end;
procedure TFrmDemoMain.TrackBar1Change(Sender: TObject);
begin
ScaleValue := TrackBar1.Position / 100;
SetScale;
lblScaleValue.Caption := Format('%d%%', [TrackBar1.Position]);
lblOriginalValue.Caption := Format('Original Size: %dx%d', [imgOriginal.Picture.Bitmap.Width, imgOriginal.Picture.Bitmap.Height]);
lblResizedValue.Caption := Format('Resized at %s: %dx%d', [lblScaleValue.Caption, imgResized.Picture.Bitmap.Width, imgResized.Picture.Bitmap.Height]);
end;
end.
|
unit Odontologia.Modelo.Entidades.PedidoItems;
interface
uses
SimpleAttributes;
type
[Tabela('PEDIDO_ITEM')]
TPEDIDOITEM = class
private
FCANTIDAD: Currency;
FVALOR_TOTAL: Currency;
FID_PEDIDO: Integer;
FID_PRODUCTO: Integer;
FPRECIO: Currency;
FID: Integer;
procedure SetID(const Value: Integer);
procedure SetID_PEDIDO(const Value: Integer);
procedure SetID_PRODUCTO(const Value: Integer);
procedure SetCANTIDAD(const Value: Currency);
procedure SetPRECIO(const Value: Currency);
procedure SetVALOR_TOTAL(const Value: Currency);
published
[Campo('ID'), Pk, AutoInc]
property ID : Integer read FID write SetID;
[Campo('ID_PEDIDO')]
property ID_PEDIDO : Integer read FID_PEDIDO write SetID_PEDIDO;
[Campo('ID_PRODUCTO')]
property ID_PRODUCTO : Integer read FID_PRODUCTO write SetID_PRODUCTO;
[Campo('CANTIDAD')]
property CANTIDAD : Currency read FCANTIDAD write SetCANTIDAD;
[Campo('PRECIO')]
property PRECIO : Currency read FPRECIO write SetPRECIO;
[Campo('VALOR_TOTAL')]
property VALOR_TOTAL : Currency read FVALOR_TOTAL write SetVALOR_TOTAL;
end;
implementation
{ TPEDIDOITEM }
procedure TPEDIDOITEM.SetCANTIDAD(const Value: Currency);
begin
FCANTIDAD := VALUE;
end;
procedure TPEDIDOITEM.SetID(const Value: Integer);
begin
FID := Value;
end;
procedure TPEDIDOITEM.SetID_PEDIDO(const Value: Integer);
begin
FID_PEDIDO := Value;
end;
procedure TPEDIDOITEM.SetID_PRODUCTO(const Value: Integer);
begin
FID_PRODUCTO := Value;
end;
procedure TPEDIDOITEM.SetPRECIO(const Value: Currency);
begin
FPRECIO := Value;
end;
procedure TPEDIDOITEM.SetVALOR_TOTAL(const Value: Currency);
begin
FVALOR_TOTAL := Value;
end;
end.
|
unit Win32.MFMP2DLNA;
{$IFDEF FPC}
{$mode delphi}
{$ENDIF}
interface
uses
Windows, Classes, SysUtils,
CMC.MFObjects;
const
IID_IMFDLNASinkInit: TGUID = '{0c012799-1b61-4c10-bda9-04445be5f561}';
const
CLSID_MPEG2DLNASink: TGUID = '{fa5fe7c5-6a1d-4b11-b41f-f959d6c76500}';
MF_MP2DLNA_USE_MMCSS: TGUID = '{54f3e2ee-a2a2-497d-9834-973afde521eb}';
MF_MP2DLNA_VIDEO_BIT_RATE: TGUID = '{e88548de-73b4-42d7-9c75-adfa0a2a6e4c}';
MF_MP2DLNA_AUDIO_BIT_RATE: TGUID = '{2d1c070e-2b5f-4ab3-a7e6-8d943ba8d00a}';
MF_MP2DLNA_ENCODE_QUALITY: TGUID = '{b52379d7-1d46-4fb6-a317-a4a5f60959f8}';
MF_MP2DLNA_STATISTICS: TGUID = '{75e488a3-d5ad-4898-85e0-bcce24a722d7}';
type
IMFDLNASinkInit = interface(IUnknown)
['{0c012799-1b61-4c10-bda9-04445be5f561}']
function Initialize(pByteStream: IMFByteStream; fPal: boolean): HResult; stdcall;
end;
TMFMPEG2DLNASINKSTATS = record
cBytesWritten: DWORDLONG;
fPAL: boolean;
fccVideo: DWORD;
dwVideoWidth: DWORD;
dwVideoHeight: DWORD;
cVideoFramesReceived: DWORDLONG;
cVideoFramesEncoded: DWORDLONG;
cVideoFramesSkipped: DWORDLONG;
cBlackVideoFramesEncoded: DWORDLONG;
cVideoFramesDuplicated: DWORDLONG;
cAudioSamplesPerSec: DWORD;
cAudioChannels: DWORD;
cAudioBytesReceived: DWORDLONG;
cAudioFramesEncoded: DWORDLONG;
end;
PMFMPEG2DLNASINKSTATS = ^TMFMPEG2DLNASINKSTATS;
implementation
end.
|
unit UFrmAskPrice;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uPai, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls;
type
TFrmAskPrice = class(TFrmPai)
lbPrice: TLabel;
edtSalePrice: TEdit;
lbModel: TLabel;
lbMsg: TLabel;
procedure edtSalePriceKeyPress(Sender: TObject; var Key: Char);
procedure btCloseClick(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
FResult : Boolean;
function ValidateAmount : Boolean;
public
function Start(sModel:String):Currency;
end;
implementation
uses uNumericFunctions, uCharFunctions, uDM;
{$R *.dfm}
{ TFrmAskPrice }
function TFrmAskPrice.Start(sModel:String): Currency;
begin
Result := 0;
FResult := False;
lbModel.Caption := sModel;
lbMsg.Caption := 'Erro no prešo! Valor ultrapassou ' + FormatFloat('#,##0.00', DM.fCashRegister.MaxAmountAskPrice);
ShowModal;
if FResult then
Result := MyStrToMoney(edtSalePrice.Text);
end;
procedure TFrmAskPrice.edtSalePriceKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
Key := ValidateCurrency(Key);
lbMsg.Visible := False;
end;
procedure TFrmAskPrice.btCloseClick(Sender: TObject);
begin
inherited;
if not ValidateAmount then
ModalResult := mrNone
else
FResult := True;
end;
function TFrmAskPrice.ValidateAmount: Boolean;
var
FAmount : Currency;
begin
try
FAmount := MyStrToMoney(edtSalePrice.Text);
finally
if (FAmount > DM.fCashRegister.MaxAmountAskPrice) or (FAmount = 0) then
begin
lbMsg.Visible := True;
edtSalePrice.Clear;
Result := False;
end
else
Result := True;
end;
end;
procedure TFrmAskPrice.FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if key = VK_ESCAPE then
Close;
end;
end.
|
unit Demo.TimelineChart.Sample;
interface
uses
System.Classes, System.SysUtils, Demo.BaseFrame, cfs.GCharts;
type
TDemo_TimelineChart_Sample = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_TimelineChart_Sample.GenerateChart;
var
Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_TIMELINE_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'President'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtDate, 'Start'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtDate, 'End')
]);
Chart.Data.AddRow([ 'Washington', EncodeDate(1789, 4, 30), EncodeDate(1797, 3, 4) ]);
Chart.Data.AddRow([ 'Adams', EncodeDate(1797, 3, 4), EncodeDate(1801, 3, 4) ]);
Chart.Data.AddRow([ 'Jefferson', EncodeDate(1801, 3, 4), EncodeDate(1809, 3, 4) ]);
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody('<div id="Chart" style="width:900px; height:300px; margin:auto;position: absolute;top:0;bottom: 0;left: 0;right: 0;"></div>');
GChartsFrame.DocumentGenerate('Chart', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_TimelineChart_Sample);
end.
|
unit MilBilanCarbone;
////////-----------------------------------------------------////////
// Cette unité regroupe l'ensemble des procédures permettant
// le calcul de l'évolution du bilan carbonné pour la culture
// annuelle du Mil. Ces procédures sont basées sur
// l'unité biomasse.pas (de C. Baron) avec quelques modifications
// pour permettre une meilleur interchangabilité des modules du modèle.
// Toute variable préfixée "Delta" représente l'augmentation ou la diminution
// de la valeur qu'elle représente.
// Exemple: DeltaBiomasseTotale représente la quantité d'assimilat créé dans la
// journée par la culture, ce n'est pas un cumul.
//
// Auteur(s) : V. BONNAL d'après J.C. Combres
// Unité(s) à voir : BilEau.pas, Biomasse.pas
// Date de commencement : 21/06/2004
// Date de derniere modification : 25/06/2004
// Etat : en cours d'implémentation
////////-----------------------------------------------------////////
interface
uses Math,SysUtils,Dialogs;
implementation
uses GestionDesErreurs,Main,ModelsManage;
procedure InitiationCulture(const SeuilTempLevee, SeuilTempBVP, SeuilTempRPR,
SeuilTempMatu1, SeuilTempMatu2 : double;
var SommeDegresJourMaximale, NumPhase, BiomasseAerienne,
BiomasseVegetative, BiomasseTotale, BiomasseTiges,
BiomasseRacinaire, BiomasseFeuilles, SommeDegresJour,
DeltaBiomasseTotale, SeuilTempPhaseSuivante, Lai : Double);
begin
try
NumPhase := 0;
SommeDegresJourMaximale := SeuilTempLevee + SeuilTempBVP + SeuilTempRPR + SeuilTempMatu1 + SeuilTempMatu2;
SommeDegresJour := 0;
BiomasseAerienne := 0;
BiomasseVegetative := 0;
BiomasseTotale := 0;
BiomasseTiges := 0;
BiomasseRacinaire := 0;
BiomasseFeuilles := 0;
DeltaBiomasseTotale := 0;
SeuilTempPhaseSuivante:=0;
Lai := 0;
except
AfficheMessageErreur('InitiationCulture',UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
Procedure EvalDateLevee(const StockRacinaire:Double;
var NumPhase,ChangePhase:Double); { TODO : Jamis utilisé ds le modèle... voir avec JCC) }
// à ce jour, cette procédure ne fait que vérifier la viabilité du semi
begin
try
if ((NumPhase=1) and (StockRacinaire=0)) then
begin
NumPhase:=7; // tuer la culture, fin de simulation { TODO : mettre un avertissement et vérifier qu'on arrête bien...}
ChangePhase:=0;
mainForm.memDeroulement.Lines.Add(TimeToStr(Time)+#9+'####### LEVEE IMPOSSIBLE ######')
end;
except
AfficheMessageErreur('EvalDateLevee | StockRacinaire: '+FloatToStr(StockRacinaire)+
' NumPhase: '+FloatToStr(NumPhase),UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
// La température moyenne calculée est bornée à Topt
Procedure EvalDegresJourTOpt(const TOpt, TMoy, TBase:double; var DegresDuJour:Double);
begin
try
DegresDuJour:=Max(Min(TOpt,TMoy),TBase)-TBase;
except
AfficheMessageErreur('EvalDegresJour',UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
// Procédure classique en bornant la température maxi à Topt et la mini à Tbase
// avec cette proc. saisir Topt1 = Topt2
Procedure EvalDegresJourTborne(const TMax, TMin, TBase,TOpt:double; var DegresDuJour:Double);
begin
try
DegresDuJour:=(Max(TMin,TBase)+Min(TOpt,TMax))/2 -TBase;
except
AfficheMessageErreur('EvalDegresJourTborne',UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
{ On calcule la vitesse moyenne de développement en considérant qu'elle est linéaire
croissante de 0 à 1 entre Tbase et Topt1, puis constante et égale à 1 entre Topt1 et Topt2
puis décroissante de 1 à 0 entre Topt2 et Tlethale.
Puis on calcule la température équivalente comprise entre Tbase et Topt1 donnant la même
vitesse de développement.
On calcule les degrés jours à partir de cette température équivalente
}
procedure EvalDegresJourVitMoy(const TMax, TMin, TBase, TOpt1, TOpt2, TL : Double;
var DegresDuJour : Double);
var
v, v1, v2 : Double;
begin
try
v1 := ((max(TMin, TBase) + Min(TOpt1, min(TL, TMax)))/2 - TBase) / (TOpt1 - TBase);
v2 := (TL - (max(TMax, TOpt2) + TOpt2) / 2) / (TL - TOpt2);
v := (v1 * (min(min(TL, TMax), TOpt1) - TMin) + (min(TOpt2, max(TOpt1, min(TL, TMax))) - TOpt1) + v2 * (max(TOpt2, min(TL, TMax)) - TOpt2)) / (min(TL, TMax)- max(TMin, TBase));
DegresDuJour := v * (TOpt1 - TBase);
except
AfficheMessageErreur('EvalDegresJourVitMoy | TMax='+FloatToStr(TMax)+
' TMin='+FloatToStr(TMin)+ 'TBase='+FloatToStr(TBase)+' TOpt1='+FloatToStr(TOpt1)+
' TOpt2='+FloatToStr(TOpt2)+' TL='+FloatToStr(TL)+' DegresDuJour='+FloatToStr(DegresDuJour),UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
Procedure EvolPhenologieMilv2(const SeuilPP,SommeDegresJour,SeuilTempLevee,
SeuilTempBVP,SeuilTempRPR,SeuilTempMatu1,
SeuilTempMatu2,StockSurface,PourcRuSurfGermi,RuSurf,
SlaMax,BiomasseTotale,DateDuJour,DateSemis,stRu:Double;
Var SumPP,NumPhase,SommeDegresJourPhasePrec,
SeuilTempPhaseSuivante,BiomasseTotaleStadeIp,
BiomasseTotaleStadeFlo,CycleReel,ChangePhase,
DateMaturite:Double);
// Cette procédure est appelée en début de journée et fait évoluer les phase
// phénologiques. Pour celà, elle incrémente les numéro de phase et change la
// valeur du seuil de la phase suivante. ChangePhase est un booléen permettant
// d'informer le modèle pour connaître si un jour est un jour de changement
// de phase. Celà permets d'initialiser les variables directement dans les
// modules spécifiques.
// --> Stades phénologiques pour le modèle Mil réécrit:
// 0 : du jour de semis au début des conditions favorables pour la germination
// 1 : du début des conditions favorables pour la germination au jour de la levée
// 2 : du jour de la levée au début de la floraison
// 3 : du début de la floraison au début de la photosensibilité
// 4 : du début de la photosensibilité au début de la maturation
// 5 : du début de la maturation au début du séchage
// 6 : du début du séchage au jour de récolte
// 7 : du jour de récolte à la fin de la simulation
var ChangementDePhase:Boolean; // on passe en variable un pseudo booléen et non directement ce booléen (pb de moteur)
begin
try
ChangePhase:=0; // l'initialisation quotidiènne de cette variable à faux permet de stopper le marquage d'une journée de changement de phase
//mainForm.memDeroulement.Lines.Add('phase n°'+FloatToStr(NumPhase)+' StockSurface='+FloatToStr(StockSurface));
if NumPhase=0 then // la culture a été semée mais n'a pas germé
begin
if ((StockSurface>=PourcRuSurfGermi*RuSurf) or (stRu>StockSurface)) then
begin // on commence ds les conditions favo aujourd'hui
NumPhase:=1;
//mainForm.memDeroulement.Lines.Add('------> phase n°'+FloatToStr(NumPhase)+' (car StockSurface='+FloatToStr(StockSurface)+')');
ChangePhase:=1;
SeuilTempPhaseSuivante := SeuilTempLevee; { TODO : à vérif par JCC, le déclencheur étant en phase 0 les conditions favorables et non SeuilTempGermi }
end;
// else { TODO : Pas logique: inutile donc à revoir... }
// begin // on vérifie ne pas être arrivé à la fin de la simulation
// if SommeDegresJour>=SommeDegresJourMaximale then
// NumPhase:=7; // pas de germination réalisée { TODO : mettre un avertissement }
// ChangePhase:=True;
// end;
end // fin du if NumPhase=0
else
begin
// vérification d'un éventuel changement de phase
If NumPhase <> 3 Then
ChangementDePhase := (SommeDegresJour >= SeuilTempPhaseSuivante)
else // Phase photopériodique
ChangementDePhase := (sumPP >= seuilPP);
If ChangementDePhase then // on a changé de phase
begin
ChangePhase:=1;
NumPhase := NumPhase + 1;
//mainForm.memDeroulement.Lines.Add('------> phase n°'+FloatToStr(NumPhase));
SommeDegresJourPhasePrec := SeuilTempPhaseSuivante; // utilisé dans EvalConversion
Case Trunc(NumPhase) of
2 : begin // BVP Developpement vegetatif
SeuilTempPhaseSuivante := SeuilTempPhaseSuivante + SeuilTempBVP;
end;
3 : SumPP := 0; // PSP Photoperiode
4 : begin // RPR Stade initiation paniculaire
SeuilTempPhaseSuivante := SeuilTempPhaseSuivante + SeuilTempRPR;
BiomasseTotaleStadeIp := BiomasseTotale;
end;
5 : begin // Matu1 remplissage grains
SeuilTempPhaseSuivante := SeuilTempPhaseSuivante + SeuilTempMatu1;
BiomasseTotaleStadeFlo:=BiomasseTotale;
end;
6 : SeuilTempPhaseSuivante := SeuilTempPhaseSuivante + SeuilTempMatu2; // Matu2 dessication
7 : begin // Recolte
CycleReel := DateDuJour-DateSemis;
DateMaturite := DateDuJour;
// sortie de RendementDeLaCulture
end;
end; // Case NumPhase
end; // end change
end;
except
AfficheMessageErreur('EvolPhenologieTemperature | NumPhase: '+FloatToStr(NumPhase)+
' SommeDegresJour: '+FloatToStr(SommeDegresJour)+
' SeuilTempPhaseSuivante: '+FloatToStr(SeuilTempPhaseSuivante) ,UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvalConversion(const NumPhase, EpsiB, AssimBVP, SommeDegresJour,
SommeDegresJourPhasePrecedente, AssimMatu1, AssimMatu2,
SeuilTempPhaseSuivante : Double;
var Conversion : Double);
var
KAssim : Double;
begin
try
case Trunc(NumPhase) of
2 : KAssim := 1;
3..4 : KAssim := AssimBVP;
5 : KAssim := AssimBVP + (SommeDegresJour - SommeDegresJourPhasePrecedente) *
(AssimMatu1 - AssimBVP) / (SeuilTempPhaseSuivante - SommeDegresJourPhasePrecedente);
6 : KAssim := AssimMatu1 + (SommeDegresJour - SommeDegresJourPhasePrecedente) *
(AssimMatu2 - AssimMatu1) / (SeuilTempPhaseSuivante - SommeDegresJourPhasePrecedente);
else
KAssim := 0;
end;
Conversion:=KAssim*EpsiB;
except
AfficheMessageErreur('EvalConversion | NumPhase: '+FloatToStr(NumPhase)+
' SommeDegresJour: '+FloatToStr(SommeDegresJour),UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvalParIntercepte(const PAR, LTR : Double; var PARIntercepte : Double);
begin
try
PARIntercepte := PAR * (1 - LTR);
except
AfficheMessageErreur('EvalParIntercepte | PAR: '+FloatToStr(PAR)+
' LTR: '+FloatToStr(LTR),UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvalAssimPot(const PARIntercepte, Conversion : Double; var AssimPot : Double);
begin
try
AssimPot := PARIntercepte* Conversion * 10;
except
AfficheMessageErreur('EvalAssimPot | PAR Intercepté: '+FloatToStr(PARIntercepte)+
' Conversion: '+FloatToStr(Conversion),UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvalCstrAssim(const Cstr:Double; var CstrAssim:Double);
// formule simple permettant un éventuel changement de calcul (pour arachide par ex)
begin
try
CstrAssim:=Cstr;
except
AfficheMessageErreur('EvalCstrAssim | Cstr: '+FloatToStr(Cstr),UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvalVitesseRacinaire(Const VRacLevee,RootSpeedBVP,RootSpeedRPR,RootSpeedPSP,
RootSpeedMatu1,RootSpeedMatu2,NumPhase:Double;
var VitesseRacinaire:Double);
//Modif JCC du 15/03/2005 pour inclure VracLevée différente de VRacBVP
begin
try
Case Trunc(NumPhase) of
1 : VitesseRacinaire := VRacLevee ;
2 : VitesseRacinaire := RootSpeedBVP ;
3 : VitesseRacinaire := RootSpeedPSP ;
4 : VitesseRacinaire := RootSpeedRPR ;
5 : VitesseRacinaire := RootSpeedMatu1; { TODO : attention en cas de gestion du champ vide... }
6 : VitesseRacinaire := RootSpeedMatu2;
else
VitesseRacinaire := 0
end;
Except
AfficheMessageErreur('EvalVitesseRacinaire | NumPhase: '+FloatToStr(NumPhase),UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvalAssim(Const AssimPot,CstrAssim:Double; var Assim:Double);
begin
try
Assim:=AssimPot*CstrAssim;
except
AfficheMessageErreur('EvalAssim | AssimPot: '+FloatToStr(AssimPot)+
' CstrAssim: '+FloatToStr(CstrAssim),UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvalDeltaBiomTot(const Assimilats,RespMaint,NumPhase:Double;
var DeltaBiomasseTotale:Double);
begin
try
if NumPhase>=2 then
DeltaBiomasseTotale:=Assimilats-RespMaint
else
DeltaBiomasseTotale:=0;
except
AfficheMessageErreur('EvalBiomasseTotaleDuJour | Assim: '+FloatToStr(Assimilats)+
' RespMaint: '+FloatToStr(RespMaint)+
' NumPhase: '+FloatToStr(NumPhase),UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvalRdtPotTotGra(Const KRdt,BiomTotStadeFloraison,BiomTotStadeIp,NumPhase,KrdtB:Double;
Var RdtPot:Double);
begin
try
if NumPhase<5 then
RdtPot:=0
else
RdtPot:=KRdt*(BiomTotStadeFloraison-BiomTotStadeIp)+ KrdtB;
except
AfficheMessageErreur('EvalRdtPotTotGra | KRdt: '+FloatToStr(KRdt)+
' BiomTotStadeFloraison: '+FloatToStr(BiomTotStadeFloraison)+
' BiomTotStadeIp: '+FloatToStr(BiomTotStadeIp)+
' NumPhase: '+Floattostr(NumPhase),UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvalDRdtPot(Const NumPhase,RdtPot,DegresDuJour,SeuilTempMatu1:Double;
Var RdtPotDuJour:Double);
begin
try
if NumPhase=5 then
RdtPotDuJour := RdtPot*(DegresDuJour/SeuilTempMatu1)
else
RdtPotDuJour:=0;
except
AfficheMessageErreur('EvalDRdtPot | NumPhase: '+FloatToStr(NumPhase),UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvalReallocation(Const RdtPotDujour,DeltaBiomasseAerienne,KRealloc,NumPhase:Double;
Var Reallocation,ManqueAssim:Double);
begin
try
If NumPhase=5 then
begin
ManqueAssim:=Max(0,(RdtPotDuJour - max(0,DeltaBiomasseAerienne)));
if DeltaBiomasseAerienne<0 then
Reallocation:=0 //JCC 15/11/04
//Reallocation:= ManqueAssim*KRealloc*0.5
else
Reallocation:= ManqueAssim*KRealloc; {il faudra borner la réallocation à BiomFeuilles-10}
end
else
begin
ManqueAssim:=0;
Reallocation:=0;
end;
except
AfficheMessageErreur('EvalRealloc | RdtPotDujour: '+FloatToStr(RdtPotDujour)+
' DeltaBiomasseAerienne: '+FloatToStr(DeltaBiomasseAerienne)+
' KRealloc: '+FloatToStr(KRealloc)+
' NumPhase: '+FloatToStr(NumPhase),UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvalReallocation2(Const RdtPotDujour,DeltaBiomasseAerienne,KRealloc,NumPhase,PenalAlloc:Double;
Var Reallocation,ManqueAssim:Double);
begin
try
If NumPhase=5 then
begin
ManqueAssim:=Max(0,(RdtPotDuJour - max(0,DeltaBiomasseAerienne)));
if DeltaBiomasseAerienne<0 then
//Reallocation:=0 //JCC 15/11/04
Reallocation:= ManqueAssim*KRealloc*PenalAlloc
else
Reallocation:= ManqueAssim*KRealloc; {il faudra borner la réallocation à BiomFeuilles-10}
end
else
begin
ManqueAssim:=0;
Reallocation:=0;
end;
except
AfficheMessageErreur('EvalRealloc2 | RdtPotDujour: '+FloatToStr(RdtPotDujour)+
' DeltaBiomasseAerienne: '+FloatToStr(DeltaBiomasseAerienne)+
' KRealloc: '+FloatToStr(KRealloc)+
' NumPhase: '+FloatToStr(NumPhase),UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvolBiomasseTotale(Const DeltaBiomasseTotale,NumPhase,Densite,
KResGrain,BiomasseGrain,ChangePhase:Double;
Var BiomasseTotale:Double);
begin
try
if ((NumPhase=2) and (ChangePhase=1)) then // initialisation
BiomasseTotale := Densite * KResGrain * BiomasseGrain/1000 //Biomasse initiale au jour de la levée
else
BiomasseTotale:=BiomasseTotale+DeltaBiomasseTotale; // pas de gestion de phase,car gérée en amont
except
AfficheMessageErreur('EvolBiomTot | BiomasseTotale: '+FloatToStr(BiomasseTotale)+
' DeltaBiomasseTotale: '+FloatToStr(DeltaBiomasseTotale),UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvolBiomasseAerienne(Const DeltaBiomasseTotale,RatioAero,BiomasseTotale,NumPhase,
KPenteAero,KBaseAero,ChangePhase:Double;
Var DeltaBiomasseAerienne,BiomasseAerienne:Double);
var
BiomasseAeriennePrec:Double;
begin
try
if NumPhase<=1 then // la levée n'a pas eu lieu encore
begin
DeltaBiomasseAerienne:=0;
BiomasseAerienne:=0;
end
else
begin // BVP et sup
if ((NumPhase=2) and (ChangePhase=1)) then // initialisation
begin
//BiomasseAerienne := Min(0.9, KPenteAero * BiomasseTotale + KBaseAero)* BiomasseTotale; JCC 15/11/04
BiomasseAerienne := Min(0.9, KBaseAero)* BiomasseTotale; { TODO -oViB : passer ce 0,9 en paramètre? }
DeltaBiomasseAerienne:=BiomasseAerienne;
end
else
begin
BiomasseAeriennePrec := BiomasseAerienne;
if DeltaBiomasseTotale < 0 Then
BiomasseAerienne := max(0,BiomasseAerienne + DeltaBiomasseTotale)
else
BiomasseAerienne := RatioAero*BiomasseTotale;
DeltaBiomasseAerienne := BiomasseAerienne - BiomasseAeriennePrec;
end;
end;
except
AfficheMessageErreur('EvolBiomAero | DeltaBiomasseTotale: '+FloatToStr(DeltaBiomasseTotale)+
' RatioAero: '+FloatToStr(RatioAero)+
' BiomasseTotale: '+FloatToStr(BiomasseTotale)+
' BiomasseAerienne: '+FloatToStr(BiomasseAerienne),UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvalBiomasseRacinair(const BiomasseTotale, BiomasseAerienne : Double; var BiomasseRacinaire : Double);
begin
try
BiomasseRacinaire := BiomasseTotale - BiomasseAerienne;
except
AfficheMessageErreur('EvolBiomasseRacinair | BiomasseTotale: '+FloatToStr(BiomasseTotale)+
' BiomasseAerienne: '+FloatToStr(BiomasseAerienne)+
' BiomasseRacinaire: '+FloatToStr(BiomasseRacinaire),UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvalAllomTotAer(Const KPenteAero,BiomTot,KBaseAero:Double;
Var RatioAero:Double);
begin
try
RatioAero:=Min(0.9,KPenteAero*BiomTot + KBaseAero);
except
AfficheMessageErreur('EvolAllomTotAer | KPenteAero: '+FloatToStr(KPenteAero)+
' BiomTot: '+FloatToStr(BiomTot)+
' KBaseAero: '+FloatToStr(KBaseAero),UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvalAllomAeroFeuilV1(Const NumPhase,kBaseLaiDev,kPenteLaiDev,BiomasseAerienne:Double;
Var RatioFeuilles:Double);
// BiomFeuille=RatioFeuilles * BiomAero
Var bM,CM:Double;
begin
try
if ((NumPhase>1) AND (NumPhase<=4)) then // donc compris entre la phase d'emergence et reproductive inclus
begin
bM := kBaseLaiDev - 0.1;
cM := ((kPenteLaiDev*1000)/ bM + 0.78)/0.75;
RatioFeuilles := (0.1 + bM * power(cM,BiomasseAerienne/1000)); { TODO : qu'est ce ce / 1000? }
end
else
RatioFeuilles := 0;
except
AfficheMessageErreur('EvolAllomAeroFeuilV1',UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvalAllomAeroFeuilV2(Const Ma,Mb,Mc,BiomasseAerienne,Densite,NumPhase:Double;
Var RatioFeuilles:Double);
begin
try
if ((NumPhase>=1) AND (NumPhase <= 4)) then
begin
//RatioFeuilles := (Ma + Mb * power(Mc,BiomasseAerienne*12.346/Densite));
RatioFeuilles := (Ma + Mb * power(Mc,BiomasseAerienne/1000));
end
else
RatioFeuilles := 0;
except
AfficheMessageErreur('EvolAllomAeroFeuilV2',UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvolBiomasseFeuilles(Const DeltaBiomasseTotale,PartFeuillesTiges,
NumPhase,RatioFeuilles, Reallocation,
BiomasseAerienne,ChangePhase,kBaseLaiDev,
KPenteLaiDev:Double;
Var DeltaBiomFeuilles,BiomFeuilles:Double);
var BiomasseFeuillePrec:Double;
begin
try
BiomasseFeuillePrec:=BiomFeuilles;
if NumPhase<=1 then // la levée n'a pas eu lieu encore
Biomfeuilles:=0
else
begin
if ((NumPhase=2) and (ChangePhase=1)) then
//BiomFeuilles:=(kBaseLaiDev+KPenteLaiDev*BiomasseAerienne)*BiomasseAerienne JCC 15/11/04
BiomFeuilles:=kBaseLaiDev*BiomasseAerienne
else
begin
If NumPhase <= 4 then // de la levée à la phase reproductive
begin
if DeltaBiomasseTotale <0 Then
Biomfeuilles:= max(0,Biomfeuilles + DeltaBiomasseTotale*PartFeuillesTiges)
else
BiomFeuilles:= RatioFeuilles *BiomasseAerienne;
end
else // de la Maturation à la fin de la simulation { TODO -oViB : que se passe t'il en phase 7 après la récolte? }
BiomFeuilles:= max(10,BiomFeuilles - (Reallocation-min(0,DeltaBiomasseTotale))*PartFeuillesTiges) ;
//JCC 18/10/05 max (0,..) remplacé par max(10,..) pour éviter division par 0 dans Sla
end;
end;
DeltaBiomFeuilles:=BiomFeuilles-BiomasseFeuillePrec;
except
AfficheMessageErreur('EvolBiomFeuille | DeltaBiomasseTotale: '+FloatToStr(DeltaBiomasseTotale)+
' BiomasseAerienne: '+FloatToStr(BiomasseAerienne)+
' NumPhase: '+FloatToStr(NumPhase),UMilBilanCarbone);
end;
end;
////////////////////////////////////////////////////////////////////////////////
procedure EvolBiomasseFeuilles2(Const DeltaBiomasseTotale,PartFeuillesTiges,
NumPhase,RatioFeuilles, Reallocation,
BiomasseAerienne,ChangePhase,kBaseLaiDev,
KPenteLaiDev:Double;
Var DeltaBiomFeuilles,BiomFeuilles:Double);
var BiomasseFeuillePrec:Double;
begin
try
BiomasseFeuillePrec:=BiomFeuilles;
if NumPhase<=1 then // la levée n'a pas eu lieu encore
Biomfeuilles:=0
else
begin
if ((NumPhase=2) and (ChangePhase=1)) then
//BiomFeuilles:=(kBaseLaiDev+KPenteLaiDev*BiomasseAerienne)*BiomasseAerienne JCC 15/11/04
BiomFeuilles:=kBaseLaiDev*BiomasseAerienne
else
begin
If NumPhase <= 4 then // de la levée à la phase reproductive
begin
if DeltaBiomasseTotale <0 Then
Biomfeuilles:= max(10,Biomfeuilles + DeltaBiomasseTotale*PartFeuillesTiges)
//JCC 08/06/06 max (10.. oublié ici correction ce jour
else
BiomFeuilles:= max(10,RatioFeuilles *BiomasseAerienne);
//JCC 08/06/06 max (10.. oublié ici correction ce jour
end
else // de la Maturation à la fin de la simulation { TODO -oViB : que se passe t'il en phase 7 après la récolte? }
BiomFeuilles:= max(10,BiomFeuilles - (Reallocation-min(0,DeltaBiomasseTotale))*PartFeuillesTiges) ;
//JCC 18/10/05 max (0,..) remplacé par max(10,..) pour éviter division par 0 dans Sla
end;
end;
DeltaBiomFeuilles:=BiomFeuilles-BiomasseFeuillePrec;
except
AfficheMessageErreur('EvolBiomFeuille2 | DeltaBiomasseTotale: '+FloatToStr(DeltaBiomasseTotale)+
' BiomasseAerienne: '+FloatToStr(BiomasseAerienne)+
' NumPhase: '+FloatToStr(NumPhase),UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
Procedure EvalSlaRapBiomV2(Const SlaBVP, SlaRPR,KpenteSla, dayBiomLeaf, BiomLeaf,
NumPhase,ChangePhase: double;
Var sla : Double);
begin
try
if ((NumPhase=2) and (ChangePhase=1)) then
Sla := SlaBVP // soit SlaMax...
else
begin
if NumPhase>=2 then
begin
//If dayBiomLeaf >0 then Modif JCC du 07/04/05 suite à modif CB
//sla := (sla - KpenteSla * (sla- SlaRPR))* (BiomLeaf- dayBiomLeaf)/BiomLeaf+ SlaBVP * (dayBiomLeaf/BiomLeaf);
//JCC 05/11/04 nouvelle formule de MD et CB
sla := (sla - KpenteSla * (sla - SlaRPR))* (BiomLeaf- dayBiomLeaf)/BiomLeaf + (SlaBVP+sla)/2 * (dayBiomLeaf/BiomLeaf);
sla := min(SlaBVP,max(SlaRPR , sla));
end
else
Sla:=0;
end;
except
AfficheMessageErreur('EvalSlaRapBiomV2',UMilBilanCarbone);
end;
End;
////////------------------------------------------------------------------------
procedure EvolBiomasseTiges(Const DeltaBiomasseTotale,NumPhase,PartFeuillesTiges,
Reallocation,BiomasseFeuilles,BiomasseAerienne:Double;
Var BiomasseTiges:Double);
begin
try
if NumPhase<=1 then // la levée n'a pas eu lieu encore
BiomasseTiges:=0
else
begin
if NumPhase <= 4 then // de la phase germi à la phase reproductive
begin
if DeltaBiomasseTotale <0 then
BiomasseTiges:= max(0, BiomasseTiges + DeltaBiomasseTotale*(1-PartFeuillesTiges))
else
BiomasseTiges:= BiomasseAerienne - BiomasseFeuilles ;
end
else // de la photosensible à la fin de la simulation { TODO -oViB : que se passe t'il en phase 7 après la récolte? }
BiomasseTiges:= max(0, BiomasseTiges - (Reallocation-min(0,DeltaBiomasseTotale))*(1-PartFeuillesTiges)); // ce qui est réalloué est pris dans les feuilles et ds les tiges
end; { TODO : KRealloc ou Reallocation ??? }
except
AfficheMessageErreur('EvolBiomasseTiges',UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvalBiomasseVegetati(const BiomasseTiges, BiomasseFeuilles, NumPhase : Double;
var BiomasseVegetative : Double);
begin
try
BiomasseVegetative := BiomasseTiges +BiomasseFeuilles;
except
AfficheMessageErreur('EvolBiomasseVegetati | BiomasseTiges: '+FloatToStr(BiomasseTiges)+
' BiomasseFeuille: '+FloatToStr(BiomasseFeuilles),UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvalDeltaRdt(Const DeltaBiomasseAerienne,Reallocation,NumPhase,
RdtPotDuJour:Double;
Var DRdt:Double);
begin
try
if NumPhase=5 then
DRdt:=Min(RdtPotDuJour,Max(0,DeltaBiomasseAerienne)+Reallocation)
else
DRdt:=0;
except
AfficheMessageErreur('EvalRdtDuJour | DeltaBiomasseAerienne: '+FloatToStr(DeltaBiomasseAerienne)+
' Reallocation: '+FloatToStr(Reallocation)+
' NumPhase: '+Floattostr(NumPhase),UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvolRdtV2(Const DRdt,NumPhase:Double; Var Rdt:Double);
begin
try
if NumPhase<5 then
Rdt := 0
else
Rdt := Rdt+DRdt;
except
AfficheMessageErreur('EvolRdtV2 | DRdt: '+FloatToStr(DRdt)+
' Rdt: '+FloatToStr(Rdt),UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvolSomDegresJour(const DegresDuJour, NumPhase : Double;
var SommeDegresJour : Double);
begin
try
if (NumPhase >= 1) then
begin
SommeDegresJour := SommeDegresJour + DegresDuJour;
end
else
begin
SommeDegresJour := 0;
end;
except
AfficheMessageErreur('EvolSommeDegresJour | DegresDuJour: '+FloatToStr(DegresDuJour)+
' Phase n°'+FloatToStr(NumPhase)+
' SommeDegresJour: '+FloatToStr(SommeDegresJour)+
' SommeDegresJour: '+FloatToStr(SommeDegresJour),UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
Procedure EvolPhenoGraminees(const PPSens,SommeDegresJour,SeuilTempLevee,
SeuilTempBVP,SeuilTempRPR,SeuilTempMatu1,
SeuilTempMatu2,StockSurface,PourcRuSurfGermi,RuSurf,
DateDuJour,DateSemis,stRu:Double;
Var SumPP,NumPhase,SommeDegresJourPhasePrec,
SeuilTempPhaseSuivante,ChangePhase:Double);
// Cette procédure est appelée en début de journée et fait évoluer les phase
// phénologiques. Pour celà, elle incrémente les numéro de phase et change la
// valeur du seuil de la phase suivante. ChangePhase est un booléen permettant
// d'informer le modèle pour connaître si un jour est un jour de changement
// de phase. Celà permets d'initialiser les variables directement dans les
// modules spécifiques.
// --> Stades phénologiques pour le modèle Mil réécrit:
// 0 : du jour de semis au début des conditions favorables pour la germination et de la récolte à la fin de simulation (pas de culture)
// 1 : du début des conditions favorables pour la germination au jour de la levée
// 2 : du jour de la levée au début de la phase photopériodique
// 3 : du début de la phase photopériodiqueau début de la phase reproductive
// 4 : du début de la phase reproductive au début de la maturation
// 5 : du début de la maturation au début du séchage
// 6 : du début du séchage au jour de récolte
// 7 : le jour de la récolte
var ChangementDePhase:Boolean; // on passe en variable un pseudo booléen et non directement ce booléen (pb de moteur)
begin
try
ChangePhase:=0; // l'initialisation quotidiènne de cette variable à faux permet de stopper le marquage d'une journée de changement de phase
//mainForm.memDeroulement.Lines.Add('phase n°'+FloatToStr(NumPhase)+' StockSurface='+FloatToStr(StockSurface));
if NumPhase=0 then // la culture a été semée mais n'a pas germé
begin
if ((StockSurface>=PourcRuSurfGermi*RuSurf) or (stRu>StockSurface)) then
begin // on commence ds les conditions favo aujourd'hui
NumPhase:=1;
//mainForm.memDeroulement.Lines.Add('------> phase n°'+FloatToStr(NumPhase)+' (car StockSurface='+FloatToStr(StockSurface)+')');
ChangePhase:=1;
SeuilTempPhaseSuivante := SeuilTempLevee; { TODO : à vérif par JCC, le déclencheur étant en phase 0 les conditions favorables et non SeuilTempGermi }
end;
// else { TODO : Pas logique: inutile donc à revoir... }
// begin // on vérifie ne pas être arrivé à la fin de la simulation
// if SommeDegresJour>=SommeDegresJourMaximale then
// NumPhase:=7; // pas de germination réalisée { TODO : mettre un avertissement }
// ChangePhase:=True;
// end;
end // fin du if NumPhase=0
else
begin
// vérification d'un éventuel changement de phase
If NumPhase <> 3 Then
ChangementDePhase := (SommeDegresJour >= SeuilTempPhaseSuivante)
else // Phase photopériodique
ChangementDePhase := (sumPP <= PPSens);
If ChangementDePhase then // on a changé de phase
begin
ChangePhase:=1;
NumPhase := NumPhase + 1;
//mainForm.memDeroulement.Lines.Add('------> phase n°'+FloatToStr(NumPhase));
SommeDegresJourPhasePrec := SeuilTempPhaseSuivante; // utilisé dans EvalConversion
Case Trunc(NumPhase) of
2 : begin // BVP Developpement vegetatif
SeuilTempPhaseSuivante := SeuilTempPhaseSuivante + SeuilTempBVP;
end;
3 : SumPP := 0; // PSP Photoperiode
4 : begin // RPR Stade initiation paniculaire
SeuilTempPhaseSuivante := SeuilTempPhaseSuivante + SeuilTempRPR;
//BiomasseTotaleStadeIp := BiomasseTotale;
end;
5 : begin // Matu1 remplissage grains
SeuilTempPhaseSuivante := SeuilTempPhaseSuivante + SeuilTempMatu1;
//BiomasseTotaleStadeFlo:=BiomasseTotale;
end;
6 : SeuilTempPhaseSuivante := SeuilTempPhaseSuivante + SeuilTempMatu2; // Matu2 dessication
end; // Case NumPhase
end; // end change
end;
except
AfficheMessageErreur('EvolPhenologieTemperature | NumPhase: '+FloatToStr(NumPhase)+
' SommeDegresJour: '+FloatToStr(SommeDegresJour)+
' SeuilTempPhaseSuivante: '+FloatToStr(SeuilTempPhaseSuivante) ,UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
{ JCC le14/03/2005 on va faire calculer BiomTotStadeFloraison et BiomTotStadeIp dans ce module spécifique graminées
au lieu de le calculer dans EvonPhenoTemp }
procedure EvalRdtPotGramin(Const KRdt,BiomasseTotale,NumPhase,ChangePhase,KrdtB:Double;
Var RdtPot,BiomTotStadeFloraison,BiomTotStadeIp:Double);
begin
try
if ((NumPhase=4) and (ChangePhase=1)) then
BiomTotStadeIp := BiomasseTotale;
if NumPhase<5 then
RdtPot:=0
else
begin
if ((NumPhase=5) and (ChangePhase=1)) then
BiomTotStadeFloraison:=BiomasseTotale;
RdtPot:=KRdt*(BiomTotStadeFloraison-BiomTotStadeIp)+ KrdtB;
end ;
except
AfficheMessageErreur('EvalRdtPotGraminees | KRdt: '+FloatToStr(KRdt)+
' BiomasseTotale: '+FloatToStr(BiomasseTotale)+
' NumPhase: '+FloatToStr(NumPhase)+
' ChangePhase: '+Floattostr(ChangePhase) +
' KrdtB: '+Floattostr(KrdtB),UMilBilanCarbone);
end;
end;
//---------------------------------------------------------------------------------------
procedure EvolLAIPhases(const NumPhase, BiomasseFeuilles, sla : Double;
var LAI : Double);
begin
try
if (NumPhase <= 1) then
begin
LAI := 0
end
else
begin
if (NumPhase <= 6) then
begin
LAI:= BiomasseFeuilles * sla;
end
else
begin
LAI:=0;
end;
end;
except
AfficheMessageErreur('EvolLAIPhases: ',UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvalDRdtPotcstr (Const NumPhase,RdtPot,DegresDuJour,SeuilTempMatu1,cstr:Double;
Var RdtPotDuJour:Double);
{On pondère la demande journalière par cstr comme Christian Baron}
begin
try
if NumPhase=5 then
RdtPotDuJour := RdtPot*(DegresDuJour/SeuilTempMatu1)*cstr
else
RdtPotDuJour:=0;
except
AfficheMessageErreur('EvalDRdtPotcstr | NumPhase: '+FloatToStr(NumPhase),UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvolSomDegresJourcstr(Const stRuSurf,RuSurf,DegresDuJour,NumPhase:Double;
Var SommeDegresJour:Double);
{ on va multiplier DJ par cstr pour tenter de traduire le retard à la levée en cas de sécheresse}
begin
//try
if NumPhase<1 then // on ne cumule qu'après la germination
SommeDegresJour:=0
else
if NumPhase=1 then
SommeDegresJour := SommeDegresJour+ DegresDuJour*max(0.3,min(1,stRuSurf/(0.7*RuSurf)))
else
SommeDegresJour := SommeDegresJour+DegresDuJour ;
//except
// AfficheMessageErreur('EvolSommeDegresJour | DegresDuJour: '+FloatToStr(DegresDuJour)+
// ' Phase n°'+FloatToStr(NumPhase)+
// ' SommeDegresJour: '+FloatToStr(SommeDegresJour)+
// ' SommeDegresJour: '+FloatToStr(SommeDegresJour),UMilBilanCarbone);
//end;
end;
////////------------------------------------------------------------------------
Procedure EvalSlaRapBiom2(Const SlaBVP, SlaRPR,KpenteSla, BiomLeaf,dayBiomLeaf,
NumPhase,ChangePhase: double;
Var sla : Double);
begin
try
//if ((NumPhase=2) and (ChangePhase=1)) then // JCC 18/10/05
if NumPhase=2 then
Sla := SlaBVP // soit SlaMax...
else
begin
//if NumPhase>=2 then
if NumPhase>2 then
{Begin
if NumPhase<5 then}
begin
sla := min(sla,(sla - KpenteSla *min((SlaBVP-SlaRPR)/3.5,(sla - SlaRPR)))*
(BiomLeaf- max(0,dayBiomLeaf))/BiomLeaf + (SlaBVP+sla)/3 * max(0,dayBiomLeaf)/BiomLeaf);
sla := min(SlaBVP,max(SlaRPR , sla));
end
{ else
Sla:= SlaRPR
end }
else
Sla:=0;
end;
except
AfficheMessageErreur('EvalSlaRapBiom2',UMilBilanCarbone);
end;
End;
////////------------------------------------------------------------------------
procedure EvalAlloAeroFeuilLin(Const NumPhase,FeuilAeroBase,FeuilAeroPente,BiomasseAerienne:Double;
Var RatioFeuilles:Double);
// BiomFeuille=RatioFeuilles * BiomAero
begin
try
if ((NumPhase>1) AND (NumPhase<=4)) then // donc compris entre la phase d'emergence et reproductive inclus
RatioFeuilles := max(0.1,FeuilAeroBase + FeuilAeroPente * BiomasseAerienne)
else
RatioFeuilles := 0;
except
AfficheMessageErreur('EvalAlloAeroFeuilLin',UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
procedure EvalReallocationSorgho(Const RdtPotDujour,DeltaBiomasseAerienne,TxRealloc,NumPhase,PenalAlloc:Double;
Var Reallocation,ManqueAssim,ReallocationMax:Double);
begin
try
If NumPhase=5 then
begin
ManqueAssim:=Max(0,(RdtPotDuJour - max(0,DeltaBiomasseAerienne)));
if DeltaBiomasseAerienne<0 then
begin
If ReallocationMax>0 then // il y a encore des réserves Carbonnées à mobiliser
begin
Reallocation:= ManqueAssim*TxRealloc*PenalAlloc;
ReallocationMax:=ReallocationMax-Reallocation; // on diminue les réserves
end
else Reallocation:=0; // on a consommé toute la réserve on ne peut réalouer
//BiomTotStadeFloraison:=BiomTotStadeFloraison-Reallocation ;
end
else
Reallocation:= ManqueAssim*TxRealloc; {il faudra borner la réallocation à BiomFeuilles-10}
end
else
begin
ManqueAssim:=0;
Reallocation:=0;
end;
except
AfficheMessageErreur('EvalReallocationSorgho | RdtPotDujour: '+FloatToStr(RdtPotDujour)+
' DeltaBiomasseAerienne: '+FloatToStr(DeltaBiomasseAerienne)+
' TxRealloc: '+FloatToStr(TxRealloc)+
' NumPhase: '+FloatToStr(NumPhase),UMilBilanCarbone);
end;
end;
procedure EvalReallocationSorgho2(Const RdtPotDujour,DeltaBiomasseAerienne,TxRealloc,NumPhase,PenalAlloc:Double;
Var Reallocation,ManqueAssim,ReallocationMax:Double);
begin
try
If NumPhase=5 then
begin
ManqueAssim:=Max(0,(RdtPotDuJour - max(0,DeltaBiomasseAerienne)));
if DeltaBiomasseAerienne<0 then
begin
If ReallocationMax>0 then // il y a encore des réserves Carbonnées à mobiliser
begin
Reallocation:= min(ManqueAssim*TxRealloc*PenalAlloc,ReallocationMax);
end
else Reallocation:=0; // on a consommé toute la réserve on ne peut réalouer
//BiomTotStadeFloraison:=BiomTotStadeFloraison-Reallocation ;
end
else
Reallocation:= min(ManqueAssim*TxRealloc,ReallocationMax);
end
else
begin
ManqueAssim:=0;
Reallocation:=0;
end;
ReallocationMax:=max(0,ReallocationMax-Reallocation); // on diminue les réserves
except
AfficheMessageErreur('EvalReallocationSorgho2 | RdtPotDujour: '+FloatToStr(RdtPotDujour)+
' DeltaBiomasseAerienne: '+FloatToStr(DeltaBiomasseAerienne)+
' TxRealloc: '+FloatToStr(TxRealloc)+
' NumPhase: '+FloatToStr(NumPhase),UMilBilanCarbone);
end;
end;
////////////////////////////////////////////////////////////////////////////////
procedure EvalRdtPotSorgho(Const KRdt,BiomasseTotale,NumPhase,ChangePhase,KrdtB,
StressTMin,StressTMax,StressCstr,KRdtBiom,KReallocMax:Double;
Var RdtPot,BiomTotStadeFloraison,BiomTotStadeIp,ReallocationMax:Double);
begin
try
if ((NumPhase=4) and (ChangePhase=1)) then
BiomTotStadeIp := BiomasseTotale;
if NumPhase<5 then
begin
RdtPot:=0;
ReallocationMax:=0;
end
else
begin
if ((NumPhase=5) and (ChangePhase=1)) then
begin
BiomTotStadeFloraison:=BiomasseTotale;
ReallocationMax := BiomTotStadeFloraison* KReallocMax; // permet de définir le réservoir disponible et mobilisable
end;
RdtPot:=(KRdt*(BiomTotStadeFloraison-BiomTotStadeIp)+ KrdtB)*(StressTMin*StressTMax*StressCstr)+KRdtBiom*BiomTotStadeFloraison;
end ;
except
AfficheMessageErreur('EvalRdtPotSorgho',UMilBilanCarbone);
end;
end;
procedure EvalRdtPotSorgho2(Const BiomasseTotale,NumPhase,ChangePhase,
KRdtBiom,KReallocMax:Double;
Var RdtPot,BiomTotStadeFloraison,BiomTotStadeIp,ReallocationMax:Double);
begin
try
if ((NumPhase=4) and (ChangePhase=1)) then
BiomTotStadeIp := BiomasseTotale;
if NumPhase<5 then
begin
RdtPot:=0;
ReallocationMax:=0;
end
else
begin
if ((NumPhase=5) and (ChangePhase=1)) then
begin
BiomTotStadeFloraison:=BiomasseTotale;
ReallocationMax := BiomTotStadeFloraison* KReallocMax; // permet de définir le réservoir disponible et mobilisable
end;
RdtPot:=KRdtBiom*BiomTotStadeFloraison;
end ;
except
AfficheMessageErreur('EvalRdtPotSorgho2',UMilBilanCarbone);
end;
end;
////////------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////
// Liste de toutes les procedures redef en dyn de l'unite
// Rajouter stdcall à la fin pour permettre l'utilisation de procédures dans des dll.
/////////////////////////////////////////////////////////////////////////////////////
Procedure InitiationCultureDyn (Var T : TPointeurProcParam);
Begin
InitiationCulture(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8],T[9],
T[10],T[11],T[12],T[13],T[14],T[15],T[16]);
end;
Procedure EvalDateLeveeDyn (Var T : TPointeurProcParam);
Begin
EvalDateLevee(T[0],T[1],T[2]);
end;
Procedure EvalDegresJourTOptDyn (Var T : TPointeurProcParam);
Begin
EvalDegresJourTOpt(T[0],T[1],T[2],T[3]);
end;
Procedure EvalDegresJourTborneDyn (Var T : TPointeurProcParam);
Begin
EvalDegresJourTborne(T[0],T[1],T[2],T[3],T[4]);
end;
Procedure EvalDegresJourVitMoyDyn (Var T : TPointeurProcParam);
Begin
EvalDegresJourVitMoy(T[0],T[1],T[2],T[3],T[4],T[5],T[6]);
end;
Procedure EvolPhenologieMilv2Dyn (Var T : TPointeurProcParam);
Begin
EvolPhenologieMilv2(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8],T[9],
T[10],T[11],T[12],T[13],T[14],T[15],T[16],T[17],T[18],T[19],
T[20],T[21],T[22],T[23]);
end;
Procedure EvolPhenoGramineesDyn (Var T : TPointeurProcParam);
Begin
EvolPhenoGraminees(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8],T[9],
T[10],T[11],T[12],T[13],T[14],T[15],T[16],T[17]);
end;
Procedure EvalConversionDyn (Var T : TPointeurProcParam);
Begin
EvalConversion(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8]);
end;
Procedure EvalSlaRapBiomV2Dyn (Var T : TPointeurProcParam);
Begin
EvalSlaRapBiomV2(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7]);
end;
Procedure EvalParIntercepteDyn (Var T : TPointeurProcParam);
Begin
EvalParIntercepte(T[0],T[1],T[2]);
end;
Procedure EvalAssimPotDyn (Var T : TPointeurProcParam);
Begin
EvalAssimPot(T[0],T[1],T[2]);
end;
Procedure EvalCstrAssimDyn (Var T : TPointeurProcParam);
Begin
EvalCstrAssim(T[0],T[1]);
end;
Procedure EvalVitesseRacinaireDyn (Var T : TPointeurProcParam);
Begin
EvalVitesseRacinaire(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7]);
end;
Procedure EvalAssimDyn (Var T : TPointeurProcParam);
Begin
EvalAssim(T[0],T[1],T[2]);
end;
Procedure EvalDeltaBiomTotDyn (Var T : TPointeurProcParam);
Begin
EvalDeltaBiomTot(T[0],T[1],T[2],T[3]);
end;
Procedure EvalRdtPotTotGraDyn (Var T : TPointeurProcParam);
Begin
EvalRdtPotTotGra(T[0],T[1],T[2],T[3],T[4],T[5]);
end;
Procedure EvalRdtPotGraminDyn (Var T : TPointeurProcParam);
Begin
EvalRdtPotGramin(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7]);
end;
Procedure EvalDRdtPotDyn (Var T : TPointeurProcParam);
Begin
EvalDRdtPot(T[0],T[1],T[2],T[3],T[4]);
end;
Procedure EvalReallocationDyn (Var T : TPointeurProcParam);
Begin
EvalReallocation(T[0],T[1],T[2],T[3],T[4],T[5]);
end;
Procedure EvalReallocation2Dyn (Var T : TPointeurProcParam);
Begin
EvalReallocation2(T[0],T[1],T[2],T[3],T[4],T[5],T[6]);
end;
Procedure EvolBiomasseTotaleDyn (Var T : TPointeurProcParam);
Begin
EvolBiomasseTotale(T[0],T[1],T[2],T[3],T[4],T[5],T[6]);
end;
Procedure EvolBiomasseAerienneDyn (Var T : TPointeurProcParam);
Begin
EvolBiomasseAerienne(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8]);
end;
Procedure EvalBiomasseRacinairDyn (Var T : TPointeurProcParam);
Begin
EvalBiomasseRacinair(T[0],T[1],T[2]);
end;
Procedure EvalAllomTotAerDyn (Var T : TPointeurProcParam);
Begin
EvalAllomTotAer(T[0],T[1],T[2],T[3]);
end;
Procedure EvalAllomAeroFeuilV1Dyn (Var T : TPointeurProcParam);
Begin
EvalAllomAeroFeuilV1(T[0],T[1],T[2],T[3],T[4]);
end;
Procedure EvalAllomAeroFeuilV2Dyn (Var T : TPointeurProcParam);
Begin
EvalAllomAeroFeuilV2(T[0],T[1],T[2],T[3],T[4],T[5],T[6]);
end;
Procedure EvolBiomasseFeuillesDyn (Var T : TPointeurProcParam);
Begin
EvolBiomasseFeuilles(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8],T[9],T[10]);
end;
Procedure EvolBiomasseTigesDyn (Var T : TPointeurProcParam);
Begin
EvolBiomasseTiges(T[0],T[1],T[2],T[3],T[4],T[5],T[6]);
end;
Procedure EvalBiomasseVegetatiDyn (Var T : TPointeurProcParam);
Begin
EvalBiomasseVegetati(T[0],T[1],T[2],T[3]);
end;
Procedure EvalDeltaRdtDyn (Var T : TPointeurProcParam);
Begin
EvalDeltaRdt(T[0],T[1],T[2],T[3],T[4]);
end;
Procedure EvolRdtV2Dyn (Var T : TPointeurProcParam);
Begin
EvolRdtV2(T[0],T[1],T[2]);
end;
Procedure EvolSomDegresJourDyn (Var T : TPointeurProcParam);
Begin
EvolSomDegresJour(T[0],T[1],T[2]);
end;
Procedure EvolLAIPhasesDyn (Var T : TPointeurProcParam);
Begin
EvolLAIPhases(T[0],T[1],T[2],T[3]);
end;
Procedure EvalDRdtPotcstrDyn (Var T : TPointeurProcParam);
Begin
EvalDRdtPotcstr(T[0],T[1],T[2],T[3],T[4],T[5]);
end;
Procedure EvolSomDegresJourcstrDyn (Var T : TPointeurProcParam);
Begin
EvolSomDegresJourcstr(T[0],T[1],T[2],T[3],T[4]);
end;
Procedure EvalSlaRapBiom2Dyn (Var T : TPointeurProcParam);
Begin
EvalSlaRapBiom2(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7]);
end;
Procedure EvalAlloAeroFeuilLinDyn (Var T : TPointeurProcParam);
Begin
EvalAlloAeroFeuilLin(T[0],T[1],T[2],T[3],T[4]);
end;
Procedure EvalRdtPotSorghoDyn (Var T : TPointeurProcParam);
Begin
EvalRdtPotSorgho(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8],T[9],T[10],T[11],T[12],T[13]);
end;
Procedure EvalRdtPotSorgho2Dyn (Var T : TPointeurProcParam);
Begin
EvalRdtPotSorgho2(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8]);
end;
Procedure EvalReallocationSorghoDyn (Var T : TPointeurProcParam);
Begin
EvalReallocationSorgho(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7]);
end;
Procedure EvalReallocationSorgho2Dyn (Var T : TPointeurProcParam);
Begin
EvalReallocationSorgho2(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7]);
end;
Procedure EvolBiomasseFeuilles2Dyn (Var T : TPointeurProcParam);
Begin
EvolBiomasseFeuilles2(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8],T[9],T[10]);
end;
initialization
TabProc.AjoutProc('InitiationCulture', InitiationCultureDyn);
TabProc.AjoutProc('EvalDateLevee', EvalDateLeveeDyn);
TabProc.AjoutProc('EvalDegresJourTOpt', EvalDegresJourTOptDyn);
TabProc.AjoutProc('EvalDegresJourTborne', EvalDegresJourTborneDyn);
TabProc.AjoutProc('EvalDegresJourVitMoy', EvalDegresJourVitMoyDyn);
TabProc.AjoutProc('EvolPhenologieMilv2', EvolPhenologieMilv2Dyn);
TabProc.AjoutProc('EvolPhenoGraminees', EvolPhenoGramineesDyn);
TabProc.AjoutProc('EvalConversion', EvalConversionDyn);
TabProc.AjoutProc('EvalParIntercepte', EvalParIntercepteDyn);
TabProc.AjoutProc('EvalAssimPot', EvalAssimPotDyn);
TabProc.AjoutProc('EvalCstrAssim', EvalCstrAssimDyn);
TabProc.AjoutProc('EvalVitesseRacinaire', EvalVitesseRacinaireDyn);
TabProc.AjoutProc('EvalAssim', EvalAssimDyn);
TabProc.AjoutProc('EvalDeltaBiomTot', EvalDeltaBiomTotDyn);
TabProc.AjoutProc('EvalRdtPotTotGra', EvalRdtPotTotGraDyn);
TabProc.AjoutProc('EvalRdtPotGramin', EvalRdtPotGraminDyn);
TabProc.AjoutProc('EvalDRdtPot', EvalDRdtPotDyn);
TabProc.AjoutProc('EvalReallocation', EvalReallocationDyn);
TabProc.AjoutProc('EvalReallocation2', EvalReallocation2Dyn);
TabProc.AjoutProc('EvolBiomasseTotale', EvolBiomasseTotaleDyn);
TabProc.AjoutProc('EvolBiomasseAerienne', EvolBiomasseAerienneDyn);
TabProc.AjoutProc('EvalBiomasseRacinair', EvalBiomasseRacinairDyn);
TabProc.AjoutProc('EvalAllomTotAer', EvalAllomTotAerDyn);
TabProc.AjoutProc('EvalAllomAeroFeuilV1', EvalAllomAeroFeuilV1Dyn);
TabProc.AjoutProc('EvalAllomAeroFeuilV2', EvalAllomAeroFeuilV2Dyn);
TabProc.AjoutProc('EvolBiomasseFeuilles', EvolBiomasseFeuillesDyn);
TabProc.AjoutProc('EvolBiomasseTiges', EvolBiomasseTigesDyn);
TabProc.AjoutProc('EvalBiomasseVegetati', EvalBiomasseVegetatiDyn);
TabProc.AjoutProc('EvalDeltaRdt', EvalDeltaRdtDyn);
TabProc.AjoutProc('EvolRdtV2', EvolRdtV2Dyn);
TabProc.AjoutProc('EvolSomDegresJour', EvolSomDegresJourDyn);
TabProc.AjoutProc('EvalSlaRapBiomV2',EvalSlaRapBiomV2Dyn);
TabProc.AjoutProc('EvolLAIPhases',EvolLAIPhasesDyn);
TabProc.AjoutProc('EvalDRdtPotcstr',EvalDRdtPotcstrDyn);
TabProc.AjoutProc('EvolSomDegresJourcstr', EvolSomDegresJourcstrDyn);
TabProc.AjoutProc('EvalSlaRapBiom2', EvalSlaRapBiom2Dyn);
TabProc.AjoutProc('EvalAlloAeroFeuilLin', EvalAlloAeroFeuilLinDyn);
TabProc.AjoutProc('EvalRdtPotSorgho', EvalRdtPotSorghoDyn);
TabProc.AjoutProc('EvalRdtPotSorgho2', EvalRdtPotSorgho2Dyn);
TabProc.AjoutProc('EvalReallocationSorgho', EvalReallocationSorghoDyn);
TabProc.AjoutProc('EvalReallocationSorgho2', EvalReallocationSorgho2Dyn);
TabProc.AjoutProc('EvolBiomasseFeuilles2', EvolBiomasseFeuilles2Dyn);
end.
|
{ ****************************************************************************** }
{ * Delay trigger by qq600585 * }
{ * https://zpascal.net * }
{ * https://github.com/PassByYou888/zAI * }
{ * https://github.com/PassByYou888/ZServer4D * }
{ * https://github.com/PassByYou888/PascalString * }
{ * https://github.com/PassByYou888/zRasterization * }
{ * https://github.com/PassByYou888/CoreCipher * }
{ * https://github.com/PassByYou888/zSound * }
{ * https://github.com/PassByYou888/zChinese * }
{ * https://github.com/PassByYou888/zExpression * }
{ * https://github.com/PassByYou888/zGameWare * }
{ * https://github.com/PassByYou888/zAnalysis * }
{ * https://github.com/PassByYou888/FFMPEG-Header * }
{ * https://github.com/PassByYou888/zTranslate * }
{ * https://github.com/PassByYou888/InfiniteIoT * }
{ * https://github.com/PassByYou888/FastMD5 * }
{ ****************************************************************************** }
(*
update history
*)
unit NotifyObjectBase;
{$INCLUDE zDefine.inc}
interface
uses Variants, CoreClasses, DataFrameEngine, Cadencer;
type
TNotifyBase = class(TCoreClassInterfacedObject)
protected
FNotifyList: TCoreClassListForObj;
FSaveRegisted: TCoreClassListForObj;
procedure DeleteSaveNotifyIntf(p: TNotifyBase);
public
constructor Create; virtual;
destructor Destroy; override;
procedure RegisterNotify(v: TNotifyBase);
procedure UnRegisterNotify(v: TNotifyBase);
procedure DoExecute(const State: Variant); virtual;
procedure NotifyExecute(Sender: TNotifyBase; const State: Variant); virtual;
end;
TNProgressPost = class;
TNPostExecute = class;
TNPostExecuteCall = procedure(Sender: TNPostExecute);
TNPostExecuteCall_NP = procedure();
TNPostExecuteMethod = procedure(Sender: TNPostExecute) of object;
TNPostExecuteMethod_NP = procedure() of object;
{$IFDEF FPC}
TNPostExecuteProc = procedure(Sender: TNPostExecute) is nested;
TNPostExecuteProc_NP = procedure() is nested;
{$ELSE FPC}
TNPostExecuteProc = reference to procedure(Sender: TNPostExecute);
TNPostExecuteProc_NP = reference to procedure();
{$ENDIF FPC}
TNPostExecute = class(TCoreClassObject)
private
FOwner: TNProgressPost;
FDataEng: TDataFrameEngine;
ProcessedTime: Double;
public
Data1: TCoreClassObject;
Data2: TCoreClassObject;
Data3: Variant;
Data4: Variant;
Data5: Pointer;
Delay: Double;
OnExecuteCall: TNPostExecuteCall;
OnExecuteCall_NP: TNPostExecuteCall_NP;
OnExecuteMethod: TNPostExecuteMethod;
OnExecuteMethod_NP: TNPostExecuteMethod_NP;
OnExecuteProc: TNPostExecuteProc;
OnExecuteProc_NP: TNPostExecuteProc_NP;
property DataEng: TDataFrameEngine read FDataEng;
property Owner: TNProgressPost read FOwner;
constructor Create; virtual;
destructor Destroy; override;
procedure Execute; virtual;
end;
TNPostExecuteClass = class of TNPostExecute;
TNProgressPost = class(TCoreClassInterfacedObject)
protected
FPostProcessIsRun: Boolean;
FPostExecuteList: TCoreClassListForObj;
FPostClass: TNPostExecuteClass;
FBusy: Boolean;
FCurrentExecute: TNPostExecute;
FBreakProgress: Boolean;
FPaused: Boolean;
Critical: TCritical;
public
constructor Create;
destructor Destroy; override;
procedure ResetPost;
function PostExecute(): TNPostExecute; overload;
function PostExecute(DataEng: TDataFrameEngine): TNPostExecute; overload;
function PostExecute(Delay: Double): TNPostExecute; overload;
function PostExecute(Delay: Double; DataEng: TDataFrameEngine): TNPostExecute; overload;
function PostExecuteM(DataEng: TDataFrameEngine; OnExecuteMethod: TNPostExecuteMethod): TNPostExecute; overload;
function PostExecuteM(Delay: Double; DataEng: TDataFrameEngine; OnExecuteMethod: TNPostExecuteMethod): TNPostExecute; overload;
function PostExecuteM(Delay: Double; OnExecuteMethod: TNPostExecuteMethod): TNPostExecute; overload;
function PostExecuteM_NP(Delay: Double; OnExecuteMethod: TNPostExecuteMethod_NP): TNPostExecute; overload;
function PostExecuteC(DataEng: TDataFrameEngine; OnExecuteCall: TNPostExecuteCall): TNPostExecute; overload;
function PostExecuteC(Delay: Double; DataEng: TDataFrameEngine; OnExecuteCall: TNPostExecuteCall): TNPostExecute; overload;
function PostExecuteC(Delay: Double; OnExecuteCall: TNPostExecuteCall): TNPostExecute; overload;
function PostExecuteC_NP(Delay: Double; OnExecuteCall: TNPostExecuteCall_NP): TNPostExecute; overload;
function PostExecuteP(DataEng: TDataFrameEngine; OnExecuteProc: TNPostExecuteProc): TNPostExecute; overload;
function PostExecuteP(Delay: Double; DataEng: TDataFrameEngine; OnExecuteProc: TNPostExecuteProc): TNPostExecute; overload;
function PostExecuteP(Delay: Double; OnExecuteProc: TNPostExecuteProc): TNPostExecute; overload;
function PostExecuteP_NP(Delay: Double; OnExecuteProc: TNPostExecuteProc_NP): TNPostExecute; overload;
procedure PostDelayFreeObject(Delay: Double; Obj1_, Obj2_: TCoreClassObject);
procedure Delete(p: TNPostExecute); overload; virtual;
procedure Progress(deltaTime: Double);
property Paused: Boolean read FPaused write FPaused;
property Busy: Boolean read FBusy;
property CurrentExecute: TNPostExecute read FCurrentExecute;
property PostClass: TNPostExecuteClass read FPostClass write FPostClass;
end;
TNProgressPostWithCadencer = class(TNProgressPost, ICadencerProgressInterface)
protected
FCadencerEngine: TCadencer;
procedure CadencerProgress(const deltaTime, newTime: Double);
public
constructor Create;
destructor Destroy; override;
procedure Progress;
property CadencerEngine: TCadencer read FCadencerEngine;
end;
var
SystemPostProgress: TNProgressPostWithCadencer;
function SysPostProgress: TNProgressPostWithCadencer;
function SysPost: TNProgressPostWithCadencer;
procedure DelayFreeObject(Delay: Double; Obj1_, Obj2_: TCoreClassObject); overload;
procedure DelayFreeObject(Delay: Double; Obj1_: TCoreClassObject); overload;
implementation
var
Hooked_OnCheckThreadSynchronize: TCheckThreadSynchronize;
procedure DoCheckThreadSynchronize();
begin
if Assigned(Hooked_OnCheckThreadSynchronize) then
begin
try
Hooked_OnCheckThreadSynchronize();
except
end;
end;
SystemPostProgress.Progress;
end;
function SysPostProgress: TNProgressPostWithCadencer;
begin
Result := SystemPostProgress;
end;
function SysPost: TNProgressPostWithCadencer;
begin
Result := SystemPostProgress;
end;
procedure DelayFreeObject(Delay: Double; Obj1_, Obj2_: TCoreClassObject);
begin
SystemPostProgress.PostDelayFreeObject(Delay, Obj1_, Obj2_);
end;
procedure DelayFreeObject(Delay: Double; Obj1_: TCoreClassObject);
begin
SystemPostProgress.PostDelayFreeObject(Delay, Obj1_, nil);
end;
procedure DoDelayFreeObject(Sender: TNPostExecute);
begin
DisposeObject(Sender.Data1);
DisposeObject(Sender.Data2);
end;
procedure TNotifyBase.DeleteSaveNotifyIntf(p: TNotifyBase);
var
i: Integer;
begin
i := 0;
while i < FSaveRegisted.Count do
begin
if FSaveRegisted[i] = TNotifyBase(p) then
FSaveRegisted.Delete(i)
else
inc(i);
end;
end;
constructor TNotifyBase.Create;
begin
inherited Create;
FNotifyList := TCoreClassListForObj.Create;
FSaveRegisted := TCoreClassListForObj.Create;
end;
destructor TNotifyBase.Destroy;
begin
while FSaveRegisted.Count > 0 do
TNotifyBase(FSaveRegisted[0]).UnRegisterNotify(Self);
DisposeObject(FSaveRegisted);
while FNotifyList.Count > 0 do
UnRegisterNotify(TNotifyBase(FNotifyList[0]));
DisposeObject(FNotifyList);
inherited Destroy;
end;
procedure TNotifyBase.RegisterNotify(v: TNotifyBase);
begin
UnRegisterNotify(v);
FNotifyList.Add(v);
v.FSaveRegisted.Add(Self);
end;
procedure TNotifyBase.UnRegisterNotify(v: TNotifyBase);
var
i: Integer;
begin
i := 0;
while i < FNotifyList.Count do
begin
if FNotifyList[i] = TNotifyBase(v) then
FNotifyList.Delete(i)
else
inc(i);
end;
v.DeleteSaveNotifyIntf(Self);
end;
procedure TNotifyBase.DoExecute(const State: Variant);
var
i: Integer;
begin
i := 0;
while i < FNotifyList.Count do
begin
try
TNotifyBase(FNotifyList[i]).NotifyExecute(Self, State);
except
end;
inc(i);
end;
end;
procedure TNotifyBase.NotifyExecute(Sender: TNotifyBase; const State: Variant);
begin
end;
constructor TNPostExecute.Create;
begin
inherited Create;
FDataEng := TDataFrameEngine.Create;
ProcessedTime := 0;
Data1 := nil;
Data2 := nil;
Data3 := Null;
Data4 := Null;
Data5 := nil;
Delay := 0;
OnExecuteCall := nil;
OnExecuteCall_NP := nil;
OnExecuteMethod := nil;
OnExecuteMethod_NP := nil;
OnExecuteProc := nil;
OnExecuteProc_NP := nil;
end;
destructor TNPostExecute.Destroy;
var
i: Integer;
begin
if FOwner <> nil then
begin
if FOwner.CurrentExecute = Self then
FOwner.FBreakProgress := True;
i := 0;
while i < FOwner.FPostExecuteList.Count do
begin
if FOwner.FPostExecuteList[i] = Self then
FOwner.FPostExecuteList.Delete(i)
else
inc(i);
end;
FOwner := nil;
end;
DisposeObject(FDataEng);
inherited Destroy;
end;
procedure TNPostExecute.Execute;
begin
if Assigned(OnExecuteCall) then
begin
FDataEng.Reader.index := 0;
try
OnExecuteCall(Self);
except
end;
end;
if Assigned(OnExecuteCall_NP) then
begin
FDataEng.Reader.index := 0;
try
OnExecuteCall_NP();
except
end;
end;
if Assigned(OnExecuteMethod) then
begin
FDataEng.Reader.index := 0;
try
OnExecuteMethod(Self);
except
end;
end;
if Assigned(OnExecuteMethod_NP) then
begin
FDataEng.Reader.index := 0;
try
OnExecuteMethod_NP();
except
end;
end;
if Assigned(OnExecuteProc) then
begin
FDataEng.Reader.index := 0;
try
OnExecuteProc(Self);
except
end;
end;
if Assigned(OnExecuteProc_NP) then
begin
FDataEng.Reader.index := 0;
try
OnExecuteProc_NP();
except
end;
end;
end;
constructor TNProgressPost.Create;
begin
inherited Create;
FPostProcessIsRun := False;
FPostExecuteList := TCoreClassListForObj.Create;
FPostClass := TNPostExecute;
FBusy := False;
FCurrentExecute := nil;
FBreakProgress := False;
FPaused := False;
Critical := TCritical.Create;
end;
destructor TNProgressPost.Destroy;
begin
ResetPost;
DisposeObject(FPostExecuteList);
DisposeObject(Critical);
inherited Destroy;
end;
procedure TNProgressPost.ResetPost;
var
i: Integer;
begin
Critical.Acquire; // atom
try
try
for i := 0 to FPostExecuteList.Count - 1 do
begin
TNPostExecute(FPostExecuteList[i]).FOwner := nil;
DisposeObject(FPostExecuteList[i]);
end;
FPostExecuteList.Clear;
except
end;
finally
Critical.Release; // atom
end;
FBreakProgress := True;
end;
function TNProgressPost.PostExecute(): TNPostExecute;
begin
Result := FPostClass.Create;
Result.FOwner := Self;
Critical.Acquire; // atom
try
FPostExecuteList.Add(Result);
finally
Critical.Release; // atom
end;
end;
function TNProgressPost.PostExecute(DataEng: TDataFrameEngine): TNPostExecute;
begin
Result := PostExecute();
if DataEng <> nil then
Result.FDataEng.Assign(DataEng);
end;
function TNProgressPost.PostExecute(Delay: Double): TNPostExecute;
begin
Result := PostExecute();
Result.Delay := Delay;
end;
function TNProgressPost.PostExecute(Delay: Double; DataEng: TDataFrameEngine): TNPostExecute;
begin
Result := PostExecute(Delay);
if DataEng <> nil then
Result.FDataEng.Assign(DataEng);
end;
function TNProgressPost.PostExecuteM(DataEng: TDataFrameEngine; OnExecuteMethod: TNPostExecuteMethod): TNPostExecute;
begin
Result := PostExecute(DataEng);
Result.OnExecuteMethod := OnExecuteMethod;
end;
function TNProgressPost.PostExecuteM(Delay: Double; DataEng: TDataFrameEngine; OnExecuteMethod: TNPostExecuteMethod): TNPostExecute;
begin
Result := PostExecute(Delay, DataEng);
Result.OnExecuteMethod := OnExecuteMethod;
end;
function TNProgressPost.PostExecuteM(Delay: Double; OnExecuteMethod: TNPostExecuteMethod): TNPostExecute;
begin
Result := PostExecute(Delay);
Result.OnExecuteMethod := OnExecuteMethod;
end;
function TNProgressPost.PostExecuteM_NP(Delay: Double; OnExecuteMethod: TNPostExecuteMethod_NP): TNPostExecute;
begin
Result := PostExecute(Delay);
Result.OnExecuteMethod_NP := OnExecuteMethod;
end;
function TNProgressPost.PostExecuteC(DataEng: TDataFrameEngine; OnExecuteCall: TNPostExecuteCall): TNPostExecute;
begin
Result := PostExecute(DataEng);
Result.OnExecuteCall := OnExecuteCall;
end;
function TNProgressPost.PostExecuteC(Delay: Double; DataEng: TDataFrameEngine; OnExecuteCall: TNPostExecuteCall): TNPostExecute;
begin
Result := PostExecute(Delay, DataEng);
Result.OnExecuteCall := OnExecuteCall;
end;
function TNProgressPost.PostExecuteC(Delay: Double; OnExecuteCall: TNPostExecuteCall): TNPostExecute;
begin
Result := PostExecute(Delay);
Result.OnExecuteCall := OnExecuteCall;
end;
function TNProgressPost.PostExecuteC_NP(Delay: Double; OnExecuteCall: TNPostExecuteCall_NP): TNPostExecute;
begin
Result := PostExecute(Delay);
Result.OnExecuteCall_NP := OnExecuteCall;
end;
function TNProgressPost.PostExecuteP(DataEng: TDataFrameEngine; OnExecuteProc: TNPostExecuteProc): TNPostExecute;
begin
Result := PostExecute(DataEng);
Result.OnExecuteProc := OnExecuteProc;
end;
function TNProgressPost.PostExecuteP(Delay: Double; DataEng: TDataFrameEngine; OnExecuteProc: TNPostExecuteProc): TNPostExecute;
begin
Result := PostExecute(Delay, DataEng);
Result.OnExecuteProc := OnExecuteProc;
end;
function TNProgressPost.PostExecuteP(Delay: Double; OnExecuteProc: TNPostExecuteProc): TNPostExecute;
begin
Result := PostExecute(Delay);
Result.OnExecuteProc := OnExecuteProc;
end;
function TNProgressPost.PostExecuteP_NP(Delay: Double; OnExecuteProc: TNPostExecuteProc_NP): TNPostExecute;
begin
Result := PostExecute(Delay);
Result.OnExecuteProc_NP := OnExecuteProc;
end;
procedure TNProgressPost.PostDelayFreeObject(Delay: Double; Obj1_, Obj2_: TCoreClassObject);
var
tmp: TNPostExecute;
begin
tmp := PostExecute(Delay);
tmp.Data1 := Obj1_;
tmp.Data2 := Obj2_;
tmp.OnExecuteCall := {$IFDEF FPC}@{$ENDIF FPC}DoDelayFreeObject;
end;
procedure TNProgressPost.Delete(p: TNPostExecute);
var
i: Integer;
begin
Critical.Acquire; // atom
try
i := 0;
while i < FPostExecuteList.Count do
begin
if FPostExecuteList[i] = p then
begin
TNPostExecute(FPostExecuteList[i]).FOwner := nil;
DisposeObject(FPostExecuteList[i]);
FPostExecuteList.Delete(i);
end
else
inc(i);
end;
finally
Critical.Release; // atom
end;
end;
procedure TNProgressPost.Progress(deltaTime: Double);
var
i: Integer;
L: TCoreClassListForObj;
p: TNPostExecute;
begin
if FPaused then
Exit;
if FPostProcessIsRun then
Exit;
FPostProcessIsRun := True;
FBreakProgress := False;
L := TCoreClassListForObj.Create;
Critical.Acquire; // atom
i := 0;
try
while i < FPostExecuteList.Count do
begin
p := FPostExecuteList[i] as TNPostExecute;
p.ProcessedTime := p.ProcessedTime + deltaTime;
if p.ProcessedTime >= p.Delay then
begin
L.Add(p);
FPostExecuteList.Delete(i);
end
else
inc(i);
end;
finally
Critical.Release; // atom
end;
i := 0;
while (i < L.Count) do
begin
FBusy := True;
FCurrentExecute := TNPostExecute(L[i]);
try
FCurrentExecute.Execute;
except
end;
FBusy := False;
FCurrentExecute.FOwner := nil;
try
DisposeObject(FCurrentExecute);
except
end;
inc(i);
if FBreakProgress then
Break;
end;
DisposeObject(L);
FPostProcessIsRun := False;
end;
procedure TNProgressPostWithCadencer.CadencerProgress(const deltaTime, newTime: Double);
begin
inherited Progress(deltaTime);
end;
constructor TNProgressPostWithCadencer.Create;
begin
inherited Create;
FCadencerEngine := TCadencer.Create;
FCadencerEngine.OnProgressInterface := Self;
end;
destructor TNProgressPostWithCadencer.Destroy;
begin
FCadencerEngine.OnProgressInterface := nil;
DisposeObject(FCadencerEngine);
inherited Destroy;
end;
procedure TNProgressPostWithCadencer.Progress;
begin
FCadencerEngine.Progress;
end;
initialization
Hooked_OnCheckThreadSynchronize := CoreClasses.OnCheckThreadSynchronize;
CoreClasses.OnCheckThreadSynchronize := {$IFDEF FPC}@{$ENDIF FPC}DoCheckThreadSynchronize;
SystemPostProgress := TNProgressPostWithCadencer.Create;
finalization
CoreClasses.OnCheckThreadSynchronize := Hooked_OnCheckThreadSynchronize;
DisposeObject(SystemPostProgress);
end.
|
unit Pass_u;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, exUtils;
type
TdlgPassword = class(TForm)
lePassword: TLabeledEdit;
btnOk: TButton;
btnCancel: TButton;
bvlLine: TBevel;
procedure lePasswordKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
{ Public declarations }
end;
var
dlgPassword: TdlgPassword;
implementation
const
ValidAsciiChars = ['a'..'z', 'A'..'Z', '0'..'9',
'~', '`', '!', '@', '#', '%',
'^', '&', '*', '(', ')', '-',
'=', '_', '+', '[', ']', '{',
'}', ';', '''', ',', '.', '/',
':', '"', '<', '>', '?',#8,#46];
{$R *.dfm}
procedure TdlgPassword.lePasswordKeyPress(Sender: TObject; var Key: Char);
begin
if Length(lePassword.Text) >= 8 then
exShowWinMsg(lePassword.Handle,'Max 8 symbols!','Error',3,True);
if not (Key in ValidAsciiChars) then
begin
exShowWinMsg(lePassword.Handle,'Invalid symbol!','Error',2,True);
Key := #0;
end;
end;
end.
|
unit NLDSBExplorerBar;
{$WARN SYMBOL_PLATFORM OFF}
interface
uses
Windows,
Messages,
Forms,
SysUtils,
ActiveX,
Classes,
ComObj,
ShlObj,
Controls,
SHDocVw,
NLDSearchBar_TLB,
StdVcl;
const
IID_IBandClass: TGUID = '{81ED334A-1C4F-47FE-9EC0-C6B29116981D}';
type
{
:$ Provides an interface for the band class to get information
:$ about the environment
}
IBandClass = interface
['{81ED334A-1C4F-47FE-9EC0-C6B29116981D}']
procedure SetWebBrowserApp(const ABrowser: IWebBrowserApp);
end;
{
:$ Implements the Internet Explorer toolbar interfaces
}
TNLDSBExplorerBar = class(TTypedComObject, INLDSBExplorerBar, IOleWindow,
IDeskBand, IObjectWithSite, IPersistStream,
IContextMenu, IInputObject)
private
FBand: TWinControl;
FSite: IUnknown;
FParentWnd: HWND;
FHasFocus: Boolean;
FOldWndProc: TWndMethod;
procedure WndProc(var Message: TMessage);
procedure FocusChange(const AFocus: Boolean);
protected
// IOleWindow
function GetWindow(out wnd: HWnd): HResult; virtual; stdcall;
function ContextSensitiveHelp(fEnterMode: BOOL): HResult; stdcall;
// IDockingWindow (implicit interface from IDeskBand)
function ShowDW(fShow: BOOL): HResult; stdcall;
function CloseDW(dwReserved: DWORD): HResult; stdcall;
function ResizeBorderDW(var prcBorder: TRect; punkToolbarSite: IUnknown;
fReserved: BOOL): HResult; stdcall;
// IDeskBand
function GetBandInfo(dwBandID, dwViewMode: DWORD; var pdbi: TDeskBandInfo):
HResult; stdcall;
// IObjectWithSite
function SetSite(const pUnkSite: IUnknown ):HResult; stdcall;
function GetSite(const riid: TIID; out site: IUnknown):HResult; stdcall;
// IPersist (implicit interface from IPersistStream)
function GetClassID(out classID: TCLSID): HResult; stdcall;
// IPersistStream
function IsDirty: HResult; stdcall;
function Load(const stm: IStream): HResult; stdcall;
function Save(const stm: IStream; fClearDirty: BOOL): HResult; stdcall;
function GetSizeMax(out cbSize: Largeint): HResult; stdcall;
// IContextMenu
function QueryContextMenu(Menu: HMENU; indexMenu, idCmdFirst, idCmdLast,
uFlags: UINT): HResult; stdcall;
function InvokeCommand(var lpici: TCMInvokeCommandInfo): HResult; stdcall;
function GetCommandString(idCmd, uType: UINT; pwReserved: PUINT;
pszName: LPSTR; cchMax: UINT): HResult; stdcall;
// IInputObject
function UIActivateIO(fActivate: BOOL; var lpMsg: TMsg): HResult; stdcall;
function HasFocusIO(): HResult; stdcall;
function TranslateAcceleratorIO(var lpMsg: TMsg): HResult; stdcall;
public
property Band: TWinControl read FBand write FBand;
property Site: IUnknown read FSite write FSite;
end;
{
:$ Handles the registration of the DeskBand
}
TNLDSBFactory = class(TTypedComObjectFactory)
protected
procedure AddKeys(); virtual;
procedure RemoveKeys(); virtual;
public
procedure UpdateRegistry(Register: Boolean); override;
end;
var
BandClass: TWinControlClass;
const
CBarName: String = '&NLDelphi ZoekBar';
implementation
uses
ComServ,
Registry;
type
// Provides access to the protected members
THackWinControl = class(TWinControl);
const
KEY_Discardable = 'Software\Microsoft\Windows\CurrentVersion\Explorer\' +
'Discardable\PostSetup\Component Categories\%s\Enum';
KEY_Vertical = '{00021493-0000-0000-C000-000000000046}';
KEY_Horizontal = '{00021494-0000-0000-C000-000000000046}';
{********************** TNLDSBExplorerBar
Focus
****************************************}
procedure TNLDSBExplorerBar.FocusChange;
var
ifSite: IInputObjectSite;
begin
FHasFocus := AFocus;
if Assigned(FSite) then
if Supports(FSite, IInputObjectSite, ifSite) then begin
ifSite.OnFocusChangeIS(Self, FHasFocus);
ifSite := nil;
end;
end;
{********************** TNLDSBExplorerBar
IOleWindow
****************************************}
function TNLDSBExplorerBar.ContextSensitiveHelp;
begin
Result := E_NOTIMPL;
end;
function TNLDSBExplorerBar.GetWindow;
begin
wnd := FBand.Handle;
Result := S_OK;
end;
{********************** TNLDSBExplorerBar
IDockingWindow
****************************************}
function TNLDSBExplorerBar.ShowDW;
begin
FocusChange(fShow);
Result := S_OK;
end;
function TNLDSBExplorerBar.CloseDW;
begin
FreeAndNil(FBand);
Result := S_OK;
end;
function TNLDSBExplorerBar.ResizeBorderDW;
begin
Result := E_NOTIMPL;
end;
{********************** TNLDSBExplorerBar
IDeskBand
****************************************}
function TNLDSBExplorerBar.GetBandInfo;
// Returns -1 if the value is 0, the value otherwise...
function HandleZero(const AValue: Integer): Integer;
begin
if AValue = 0 then
Result := -1
else
Result := AValue;
end;
var
sCaption: String;
iLength: Integer;
begin
// Minimum size
if (pdbi.dwMask and DBIM_MINSIZE) = DBIM_MINSIZE then begin
pdbi.ptMinSize.x := HandleZero(FBand.Constraints.MinWidth);
pdbi.ptMinSize.y := HandleZero(FBand.Constraints.MinHeight);
end;
// Maximum size
if (pdbi.dwMask and DBIM_MAXSIZE) = DBIM_MAXSIZE then begin
pdbi.ptMaxSize.x := HandleZero(FBand.Constraints.MaxWidth);
pdbi.ptMaxSize.y := HandleZero(FBand.Constraints.MaxHeight);
end;
// Ideal size
if (pdbi.dwMask and DBIM_ACTUAL) = DBIM_ACTUAL then begin
pdbi.ptActual.x := FBand.Width;
pdbi.ptActual.y := FBand.Height;
end;
// Integral size
if (pdbi.dwMask and DBIM_INTEGRAL) = DBIM_INTEGRAL then begin
pdbi.ptIntegral.x := 1;
pdbi.ptIntegral.y := 1;
end;
// Mode
if (pdbi.dwMask and DBIM_MODEFLAGS) = DBIM_MODEFLAGS then
pdbi.dwModeFlags := DBIMF_NORMAL;
// Back color
if (pdbi.dwMask and DBIM_BKCOLOR) = DBIM_BKCOLOR then
pdbi.dwMask := pdbi.dwMask and (not DBIM_BKCOLOR);
// Title
if (pdbi.dwMask and DBIM_TITLE) = DBIM_TITLE then begin
// Use a maximum of 255 characters
sCaption := Copy(THackWinControl(FBand).Text, 1, 255);
iLength := Length(sCaption) + 1;
// Convert to wide string
FillChar(pdbi.wszTitle, iLength, #0);
StringToWideChar(sCaption, @pdbi.wszTitle, iLength);
end;
Result := S_OK;
end;
{********************** TNLDSBExplorerBar
IObjectWithSite
****************************************}
function TNLDSBExplorerBar.SetSite;
var
ifProvider: IServiceProvider;
ifBandClass: IBandClass;
ifBrowser: IWebBrowserApp;
ifWindow: IOleWindow;
begin
FSite := pUnkSite;
FParentWnd := 0;
if Assigned(FSite) then begin
// Get parent window
if Supports(FSite, IOleWindow, ifWindow) then begin
ifWindow.GetWindow(FParentWnd);
ifWindow := nil;
end;
// Create a new band window...
FBand := BandClass.CreateParented(FParentWnd);
FOldWndProc := FBand.WindowProc;
FBand.WindowProc := Self.WndProc;
// Get browser reference
if Supports(FBand, IBandClass, ifBandClass) then begin
if Supports(FSite, IServiceProvider, ifProvider) then begin
if ifProvider.QueryService(IWebbrowserApp,
IWebbrowser2, ifBrowser) = 0 then begin
ifBandClass.SetWebBrowserApp(ifBrowser);
ifBrowser := nil;
end;
ifProvider := nil;
end;
ifBandClass := nil;
end;
end else
// No site provided, close the bar...
CloseDW(0);
Result := S_OK;
end;
function TNLDSBExplorerBar.GetSite;
begin
Result := FSite.QueryInterface(riid, site);
end;
{********************** TNLDSBExplorerBar
IPersist
****************************************}
function TNLDSBExplorerBar.GetClassID(out classID: TCLSID): HResult;
begin
classID := CLASS_NLDSBExplorerBar;
Result := S_OK;
end;
{********************** TNLDSBExplorerBar
IPersistStream
****************************************}
function TNLDSBExplorerBar.IsDirty;
begin
Result := E_NOTIMPL;
end;
function TNLDSBExplorerBar.Load;
begin
Result := E_NOTIMPL;
end;
function TNLDSBExplorerBar.Save;
begin
Result := E_NOTIMPL;
end;
function TNLDSBExplorerBar.GetSizeMax;
begin
Result := E_NOTIMPL;
end;
{********************** TNLDSBExplorerBar
IContextMenu
****************************************}
function TNLDSBExplorerBar.QueryContextMenu;
begin
InsertMenu(Menu, 0, MF_BYPOSITION, idCmdFirst, '&Over NLDSearchBar...');
InsertMenu(Menu, 1, MF_BYPOSITION or MF_SEPARATOR, 0, nil);
Result := 2;
end;
function TNLDSBExplorerBar.InvokeCommand;
begin
case LOWORD(lpici.lpVerb) of
0:
MessageBox(lpici.hwnd, 'NLDSearchBar - http://www.nldelphi.com/', 'About...', MB_OK or
MB_ICONINFORMATION);
end;
Result := S_OK;
end;
function TNLDSBExplorerBar.GetCommandString;
begin
Result := E_NOTIMPL;
end;
{********************** TNLDSBExplorerBar
IInputObject
****************************************}
function TNLDSBExplorerBar.UIActivateIO;
begin
FHasFocus := fActivate;
if FHasFocus then
FBand.SetFocus();
Result := S_OK;
end;
function TNLDSBExplorerBar.HasFocusIO;
begin
Result := Integer(not FHasFocus);
end;
function TNLDSBExplorerBar.TranslateAcceleratorIO;
begin
if lpMsg.WParam <> VK_TAB then begin
TranslateMessage(lpMSg);
DispatchMessage(lpMsg);
Result := S_OK;
end else
Result := S_FALSE;
end;
{********************** TNLDSBExplorerBar
Window Procedure
****************************************}
procedure TNLDSBExplorerBar.WndProc;
begin
if (Message.Msg = WM_PARENTNOTIFY) then
FocusChange(True);
FOldWndProc(Message);
end;
{****************************************
TNLDSBFactory
****************************************}
procedure TNLDSBFactory.UpdateRegistry;
begin
inherited;
if Register then
AddKeys()
else
RemoveKeys();
end;
procedure TNLDSBFactory.AddKeys;
var
sGUID: String;
sKey: String;
begin
sGUID := GUIDToString(Self.ClassID);
with TRegistry.Create() do
try
RootKey := HKEY_CURRENT_USER;
// http://support.microsoft.com/support/kb/articles/Q247/7/05.ASP
sKey := Format(KEY_Discardable, [KEY_Vertical]);
DeleteKey(sKey);
sKey := Format(KEY_Discardable, [KEY_Horizontal]);
DeleteKey(sKey);
RootKey := HKEY_CLASSES_ROOT;
// Register band
if OpenKey('CLSID\' + sGUID, True) then begin
WriteString('', CBarName);
CloseKey();
end;
if OpenKey('CLSID\' + sGUID + '\InProcServer32', True) then begin
WriteString('ThreadingModel', 'Apartment');
CloseKey();
end;
if OpenKey('CLSID\' + sGUID + '\Implemented Categories\' + KEY_Horizontal, True) then
CloseKey();
RootKey := HKEY_LOCAL_MACHINE;
if OpenKey('SOFTWARE\Microsoft\Internet Explorer\Toolbar', True) then begin
WriteString(sGUID, '');
CloseKey();
end;
finally
Free();
end;
end;
procedure TNLDSBFactory.RemoveKeys;
var
sGUID: String;
begin
sGUID := GUIDToString(Self.ClassID);
with TRegistry.Create() do
try
RootKey := HKEY_CLASSES_ROOT;
DeleteKey('CLSID\' + sGUID + '\Implemented Categories\' + KEY_Horizontal);
DeleteKey('CLSID\' + sGUID + '\InProcServer32');
DeleteKey('CLSID\' + sGUID);
RootKey := HKEY_LOCAL_MACHINE;
if OpenKey('Software\Microsoft\Internet Explorer\Toolbar', False) then begin
DeleteValue(sGUID);
CloseKey();
end;
finally
Free();
end;
end;
initialization
TNLDSBFactory.Create(ComServer, TNLDSBExplorerBar, Class_NLDSBExplorerBar,
ciMultiInstance, tmApartment);
end.
|
{*******************************************************}
{ }
{ 基于HCView的电子病历程序 作者:荆通 }
{ }
{ 此代码仅做学习交流使用,不可用于商业目的,由此引发的 }
{ 后果请使用者承担,加入QQ群 649023932 来获取更多的技术 }
{ 交流。 }
{ }
{*******************************************************}
unit frm_DataElement;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.StdCtrls, Vcl.ExtCtrls,
Vcl.Menus, Vcl.ComCtrls;
type
TfrmDataElement = class(TForm)
pnl2: TPanel;
lblDeHint: TLabel;
edtPY: TEdit;
sgdDE: TStringGrid;
pmDE: TPopupMenu;
mniNew: TMenuItem;
mniEdit: TMenuItem;
mniDelete: TMenuItem;
mniN6: TMenuItem;
mniDomain: TMenuItem;
mniN5: TMenuItem;
mniInsertAsDeItem: TMenuItem;
mniInsertAsDeGroup: TMenuItem;
mniInsertAsEdit: TMenuItem;
mniInsertAsCombobox: TMenuItem;
mniInsertAsDateTime: TMenuItem;
mniInsertAsRadioGroup: TMenuItem;
mniInsertAsCheckBox: TMenuItem;
mniN4: TMenuItem;
mniRefresh: TMenuItem;
pgcDE: TPageControl;
tsDE: TTabSheet;
tsList: TTabSheet;
tv1: TTreeView;
mniInsertAsFloatBarCode: TMenuItem;
mniInsertAsImage: TMenuItem;
procedure edtPYKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormShow(Sender: TObject);
procedure sgdDEDblClick(Sender: TObject);
procedure mniInsertAsDeItemClick(Sender: TObject);
procedure mniInsertAsDeGroupClick(Sender: TObject);
procedure mniInsertAsEditClick(Sender: TObject);
procedure mniInsertAsComboboxClick(Sender: TObject);
procedure mniInsertAsDateTimeClick(Sender: TObject);
procedure mniInsertAsRadioGroupClick(Sender: TObject);
procedure mniInsertAsCheckBoxClick(Sender: TObject);
procedure lblDeHintClick(Sender: TObject);
procedure mniRefreshClick(Sender: TObject);
procedure pmDEPopup(Sender: TObject);
procedure sgdDEClick(Sender: TObject);
procedure mniDeleteClick(Sender: TObject);
procedure mniDomainClick(Sender: TObject);
procedure mniEditClick(Sender: TObject);
procedure mniNewClick(Sender: TObject);
procedure mniInsertAsFloatBarCodeClick(Sender: TObject);
procedure mniInsertAsImageClick(Sender: TObject);
private
{ Private declarations }
FSelectRow: Integer;
FDomainID: Integer; // 当前查看的值域ID
FOnSelectChange, FOnInsertAsDeItem, FOnInsertAsDeGroup, FOnInsertAsDeEdit,
FOnInsertAsDeCombobox, FOnInsertAsDeDateTime, FOnInsertAsDeRadioGroup,
FOnInsertAsDeCheckBox, FOnInsertAsDeFloatBarCode, FOnInsertAsDeImage: TNotifyEvent;
procedure ShowDataElement;
//procedure DoInsertAsDE(const AIndex, AName: string);
public
{ Public declarations }
function GetDomainID: Integer;
function GetDeName: string;
function GetDeIndex: string;
property OnInsertAsDeItem: TNotifyEvent read FOnInsertAsDeItem write FOnInsertAsDeItem;
property OnInsertAsDeGroup: TNotifyEvent read FOnInsertAsDeGroup write FOnInsertAsDeGroup;
property OnInsertAsDeEdit: TNotifyEvent read FOnInsertAsDeEdit write FOnInsertAsDeEdit;
property OnInsertAsDeCombobox: TNotifyEvent read FOnInsertAsDeCombobox write FOnInsertAsDeCombobox;
property OnInsertAsDeDateTime: TNotifyEvent read FOnInsertAsDeDateTime write FOnInsertAsDeDateTime;
property OnInsertAsDeRadioGroup: TNotifyEvent read FOnInsertAsDeRadioGroup write FOnInsertAsDeRadioGroup;
property OnInsertAsDeCheckBox: TNotifyEvent read FOnInsertAsDeCheckBox write FOnInsertAsDeCheckBox;
property OnInsertAsDeFloatBarCode: TNotifyEvent read FOnInsertAsDeFloatBarCode write FOnInsertAsDeFloatBarCode;
property OnInsertAsDeImage: TNotifyEvent read FOnInsertAsDeImage write FOnInsertAsDeImage;
property OnSelectChange: TNotifyEvent read FOnSelectChange write FOnSelectChange;
end;
implementation
uses
emr_Common, emr_BLLInvoke, FireDAC.Comp.Client, Data.DB, HCEmrElementItem,
frm_DeInfo, frm_Domain;
{$R *.dfm}
{procedure TfrmDataElement.DoInsertAsDE(const AIndex, AName: string);
begin
if Assigned(FOnInsertAsDE) then
FOnInsertAsDE(AIndex, AName);
end;}
procedure TfrmDataElement.edtPYKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
begin
ClientCache.DataElementDT.FilterOptions := [foCaseInsensitive{不区分大小写, foNoPartialCompare不支持通配符(*)所表示的部分匹配}];
if edtPY.Text = '' then
ClientCache.DataElementDT.Filtered := False
else
begin
ClientCache.DataElementDT.Filtered := False;
if IsPY(edtPY.Text[1]) then
ClientCache.DataElementDT.Filter := 'py like ''%' + edtPY.Text + '%'''
else
ClientCache.DataElementDT.Filter := 'dename like ''%' + edtPY.Text + '%''';
ClientCache.DataElementDT.Filtered := True;
end;
ShowDataElement;
end;
end;
procedure TfrmDataElement.FormShow(Sender: TObject);
begin
FSelectRow := -1;
sgdDE.RowCount := 1;
sgdDE.Cells[0, 0] := '序';
sgdDE.Cells[1, 0] := '名称';
sgdDE.Cells[2, 0] := '编码';
sgdDE.Cells[3, 0] := '拼音';
sgdDE.Cells[4, 0] := '类型';
sgdDE.Cells[5, 0] := '值域';
edtPY.Clear;
sgdDE.RowCount := 1;
pgcDE.ActivePageIndex := 0;
ShowDataElement; // 数据元列表
//值域
FDomainID := 0;
end;
function TfrmDataElement.GetDeIndex: string;
begin
if FSelectRow >= 0 then
Result := sgdDE.Cells[0, FSelectRow]
else
Result := '';
end;
function TfrmDataElement.GetDeName: string;
begin
if FSelectRow > 0 then
Result := sgdDE.Cells[1, FSelectRow]
else
Result := '';
end;
function TfrmDataElement.GetDomainID: Integer;
begin
if FSelectRow > 0 then
Result := StrToInt(sgdDE.Cells[5, FSelectRow])
else
Result := 0;
end;
procedure TfrmDataElement.lblDeHintClick(Sender: TObject);
begin
mniRefreshClick(Sender);
end;
procedure TfrmDataElement.mniDeleteClick(Sender: TObject);
begin
if sgdDE.Row >= 0 then
begin
if MessageDlg('确定要删除数据元【' + sgdDE.Cells[1, sgdDE.Row] + '】吗?',
mtWarning, [mbYes, mbNo], 0) = mrYes
then
begin
if StrToInt(sgdDE.Cells[5, sgdDE.Row]) <> 0 then
begin
if MessageDlg('如果' + sgdDE.Cells[1, sgdDE.Row] + '对应的值域【' + sgdDE.Cells[5, sgdDE.Row] + '】不再使用,请注意及时删除,继续删除数据元?',
mtWarning, [mbYes, mbNo], 0) <> mrYes
then
Exit;
end;
BLLServerExec(
procedure(const ABLLServerReady: TBLLServerProxy)
begin
ABLLServerReady.Cmd := BLL_DELETEDE; // 删除数据元
ABLLServerReady.ExecParam.I['DeID'] := StrToInt(sgdDE.Cells[0, sgdDE.Row]);
end,
procedure(const ABLLServer: TBLLServerProxy; const AMemTable: TFDMemTable = nil)
begin
if not ABLLServer.MethodRunOk then
ShowMessage(ABLLServer.MethodError)
else
begin
ShowMessage('删除成功!');
mniRefreshClick(Sender);
end;
end);
end;
end;
end;
procedure TfrmDataElement.mniDomainClick(Sender: TObject);
var
vFrmDomain: TfrmDomain;
begin
vFrmDomain := TfrmDomain.Create(nil);
try
vFrmDomain.PopupParent := Self;
vFrmDomain.ShowModal;
finally
FreeAndNil(vFrmDomain);
end;
end;
procedure TfrmDataElement.mniEditClick(Sender: TObject);
var
vFrmDeInfo: TfrmDeInfo;
begin
if sgdDE.Row > 0 then
begin
vFrmDeInfo := TfrmDeInfo.Create(nil);
try
vFrmDeInfo.DeID := StrToInt(sgdDE.Cells[0, sgdDE.Row]);
vFrmDeInfo.PopupParent := Self;
vFrmDeInfo.ShowModal;
if vFrmDeInfo.ModalResult = mrOk then
mniRefreshClick(Sender);
finally
FreeAndNil(vFrmDeInfo);
end;
end;
end;
procedure TfrmDataElement.mniInsertAsCheckBoxClick(Sender: TObject);
begin
if sgdDE.Row < 0 then Exit;
if Assigned(FOnInsertAsDeCheckBox) then
FOnInsertAsDeCheckBox(Self);
end;
procedure TfrmDataElement.mniInsertAsComboboxClick(Sender: TObject);
begin
if sgdDE.Row < 0 then Exit;
if Assigned(FOnInsertAsDeCombobox) then
FOnInsertAsDeCombobox(Self);
end;
procedure TfrmDataElement.mniInsertAsDateTimeClick(Sender: TObject);
begin
if sgdDE.Row < 0 then Exit;
if Assigned(FOnInsertAsDeDateTime) then
FOnInsertAsDeDateTime(Self);
end;
procedure TfrmDataElement.mniInsertAsDeItemClick(Sender: TObject);
begin
if sgdDE.Row < 0 then Exit;
if Assigned(FOnInsertAsDeItem) then
FOnInsertAsDeItem(Self);
end;
procedure TfrmDataElement.mniInsertAsDeGroupClick(Sender: TObject);
begin
if sgdDE.Row < 0 then Exit;
if Assigned(FOnInsertAsDeGroup) then
FOnInsertAsDeGroup(Self);
end;
procedure TfrmDataElement.mniInsertAsEditClick(Sender: TObject);
begin
if sgdDE.Row < 0 then Exit;
if Assigned(FOnInsertAsDeEdit) then
FOnInsertAsDeEdit(Self);
end;
procedure TfrmDataElement.mniInsertAsRadioGroupClick(Sender: TObject);
begin
if sgdDE.Row < 0 then Exit;
if Assigned(FOnInsertAsDeRadioGroup) then
FOnInsertAsDeRadioGroup(Self);
end;
procedure TfrmDataElement.mniInsertAsFloatBarCodeClick(Sender: TObject);
begin
if sgdDE.Row < 0 then Exit;
if Assigned(FOnInsertAsDeFloatBarCode) then
FOnInsertAsDeFloatBarCode(Self);
end;
procedure TfrmDataElement.mniInsertAsImageClick(Sender: TObject);
begin
if sgdDE.Row < 0 then Exit;
if Assigned(FOnInsertAsDeImage) then
FOnInsertAsDeImage(Self);
end;
procedure TfrmDataElement.mniNewClick(Sender: TObject);
var
vFrmDeInfo: TfrmDeInfo;
begin
vFrmDeInfo := TfrmDeInfo.Create(nil);
try
vFrmDeInfo.DeID := 0;
vFrmDeInfo.PopupParent := Self;
vFrmDeInfo.ShowModal;
if vFrmDeInfo.ModalResult = mrOk then
mniRefreshClick(Sender);
finally
FreeAndNil(vFrmDeInfo);
end;
end;
procedure TfrmDataElement.mniRefreshClick(Sender: TObject);
begin
edtPY.Clear();
HintFormShow('正在刷新数据元...', procedure(const AUpdateHint: TUpdateHint)
var
vTopRow, vRow: Integer;
begin
//FOnFunctionNotify(PluginID, FUN_REFRESHCLIENTCACHE, nil); // 重新获取客户端缓存
ClientCache.GetDataElementTable;
SaveStringGridRow(vRow, vTopRow, sgdDE);
ShowDataElement; // 刷新数据元信息
RestoreStringGridRow(vRow, vTopRow, sgdDE);
end);
end;
procedure TfrmDataElement.pmDEPopup(Sender: TObject);
begin
mniEdit.Enabled := sgdDE.Row > 0;
mniDelete.Enabled := sgdDE.Row > 0;
mniInsertAsDeItem.Visible := Assigned(FOnInsertAsDeItem) and (sgdDE.Row > 0);
mniInsertAsDeGroup.Visible := Assigned(FOnInsertAsDeGroup) and (sgdDE.Row > 0);
mniInsertAsEdit.Visible := Assigned(FOnInsertAsDeEdit) and (sgdDE.Row > 0);
mniInsertAsCombobox.Visible := Assigned(FOnInsertAsDeCombobox) and (sgdDE.Row > 0);
mniInsertAsDateTime.Visible := Assigned(FOnInsertAsDeDateTime) and (sgdDE.Row > 0);
mniInsertAsRadioGroup.Visible := Assigned(FOnInsertAsDeRadioGroup) and (sgdDE.Row > 0);
mniInsertAsCheckBox.Visible := Assigned(FOnInsertAsDeCheckBox) and (sgdDE.Row > 0);
mniInsertAsImage.Visible := Assigned(FOnInsertAsDeImage) and (sgdDE.Row > 0);
mniInsertAsFloatBarCode.Visible := Assigned(FOnInsertAsDeFloatBarCode) and (sgdDE.Row > 0);
end;
procedure TfrmDataElement.sgdDEClick(Sender: TObject);
begin
if FSelectRow <> sgdDE.Row then
begin
FSelectRow := sgdDE.Row;
if Assigned(FOnSelectChange) then
FOnSelectChange(Sender);
end;
end;
procedure TfrmDataElement.sgdDEDblClick(Sender: TObject);
begin
mniInsertAsDeItemClick(Sender);
end;
procedure TfrmDataElement.ShowDataElement;
var
vRow: Integer;
begin
vRow := 1;
sgdDE.RowCount := ClientCache.DataElementDT.RecordCount + 1;
with ClientCache.DataElementDT do
begin
First;
while not Eof do
begin
sgdDE.Cells[0, vRow] := FieldByName('deid').AsString;;
sgdDE.Cells[1, vRow] := FieldByName('dename').AsString;
sgdDE.Cells[2, vRow] := FieldByName('decode').AsString;
sgdDE.Cells[3, vRow] := FieldByName('py').AsString;
sgdDE.Cells[4, vRow] := FieldByName('frmtp').AsString;
sgdDE.Cells[5, vRow] := FieldByName('domainid').AsString;
Inc(vRow);
Next;
end;
end;
if sgdDE.RowCount > 1 then
sgdDE.FixedRows := 1;
sgdDEClick(sgdDE);
end;
end.
|
unit ibSHDMLHistoryFrm;
interface
uses
SHDesignIntf, SHEvents, ibSHDesignIntf, ibSHComponentFrm, ibSHConsts,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ToolWin, ExtCtrls, SynEdit, pSHSynEdit, SynEditTypes,
VirtualTrees, Contnrs, ImgList, AppEvnts, ActnList, StrUtils, Menus,
pSHSqlTxtRtns,
ibSHValues;
type
TibSHDMLHistoryForm = class(TibBTComponentForm, IibSHDMLHistoryForm)
Panel1: TPanel;
Splitter1: TSplitter;
Panel2: TPanel;
Panel3: TPanel;
pSHSynEdit1: TpSHSynEdit;
Tree: TVirtualStringTree;
SaveDialog1: TSaveDialog;
ImageList1: TImageList;
procedure pSHSynEdit1DblClick(Sender: TObject);
procedure TreeMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure pSHSynEdit1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
private
{ Private declarations }
FTopLine: Integer;
FSQLParser: TSQLParser;
FTreePopupMenu: TPopupMenu;
{ Tree }
procedure TreeGetNodeDataSize(Sender: TBaseVirtualTree;
var NodeDataSize: Integer);
procedure TreeFreeNode(Sender: TBaseVirtualTree;
Node: PVirtualNode);
procedure TreeGetImageIndex(Sender: TBaseVirtualTree;
Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
var Ghosted: Boolean; var ImageIndex: Integer);
procedure TreeGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
procedure TreeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure TreeDblClick(Sender: TObject);
function CalcImageIndex(ASQLKind: TSQLKind): Integer;
procedure SelectTopLineBlock(ATopLine: Integer);
procedure DoOnEnter;
function GetDMLHistory: IibSHDMLHistory;
protected
procedure FillPopupMenu; override;
procedure DoOnPopup(Sender: TObject); override;
procedure DoOnPopupTreeMenu(Sender: TObject);
//Popup menu methods
procedure mnSendToSQLEditorFromEditorClick(Sender: TObject);
procedure mnSendToSQLEditorFromTreeClick(Sender: TObject);
procedure mnDeleteStatementFromTreeClick(Sender: TObject);
procedure FillTree(AStatementNo: Integer);
{ IibSHDMLHistoryForm }
function GetRegionVisible: Boolean;
procedure FillEditor;
procedure ChangeNotification(AOldItem: Integer; Operation: TOperation);
function GetCanSendToSQLEditor: Boolean;
procedure IibSHDMLHistoryForm.SendToSQLEditor = ISendToSQLEditor;
procedure ISendToSQLEditor;
{ ISHFileCommands }
function GetCanSave: Boolean; override;
procedure Save; override;
procedure SaveAs; override;
{ ISHEditCommands }
function GetCanClearAll: Boolean; override;
procedure ClearAll; override;
{ ISHRunCommands }
function GetCanRun: Boolean; override;
function GetCanPause: Boolean; override;
function GetCanRefresh: Boolean; override;
procedure Run; override;
procedure Pause; override;
procedure Refresh; override;
procedure ShowHideRegion(AVisible: Boolean); override;
procedure SinhronizeTreeByEditor;
procedure SendToSQLEditorFromTree;
procedure SendToSQLEditor(const AStatementNo: Integer);
function DoOnOptionsChanged: Boolean; override;
procedure DoOnSpecialLineColors(Sender: TObject;
Line: Integer; var Special: Boolean; var FG, BG: TColor); override;
public
{ Public declarations }
constructor Create(AOwner: TComponent; AParent: TWinControl;
AComponent: TSHComponent; ACallString: string); override;
destructor Destroy; override;
property DMLHistory: IibSHDMLHistory read GetDMLHistory;
property TopLine: Integer read FTopLine write FTopLine;
end;
var
ibSHDMLHistoryForm: TibSHDMLHistoryForm;
implementation
uses
ibSHMessages;
{$R *.dfm}
const
img_select = 6;
img_update = 7;
img_insert = 4;
img_delete = 8;
img_execute = 5;
img_other = 3;
type
PTreeRec = ^TTreeRec;
TTreeRec = record
FirstWord: string;
ExecutedAt: string;
SQLKind: TSQLKind;
TopLine: Integer;
StatementNo: Integer;
ExecuteTime: Cardinal;
PrepareTime: Cardinal;
FetchTime: Cardinal;
IndexedReads: Cardinal;
NonIndexedReads: Cardinal;
Inserts: Cardinal;
Updates: Cardinal;
Deletes: Cardinal;
ImageIndex: Integer;
end;
{ TibSHDMLHistoryForm }
constructor TibSHDMLHistoryForm.Create(AOwner: TComponent; AParent: TWinControl;
AComponent: TSHComponent; ACallString: string);
begin
FTreePopupMenu := TPopupMenu.Create(Self);
FTreePopupMenu.OnPopup := DoOnPopupTreeMenu;
inherited Create(AOwner, AParent, AComponent, ACallString);
Editor := pSHSynEdit1;
Editor.Lines.Clear;
FocusedControl := Editor;
RegisterEditors;
ShowHideRegion(False);
DoOnOptionsChanged;
Tree.OnGetNodeDataSize := TreeGetNodeDataSize;
Tree.OnFreeNode := TreeFreeNode;
Tree.OnGetImageIndex := TreeGetImageIndex;
Tree.OnGetText := TreeGetText;
Tree.OnDblClick := TreeDblClick;
Tree.OnKeyDown := TreeKeyDown;
Tree.PopupMenu := FTreePopupMenu;
FSQLParser := TSQLParser.Create;
FillEditor;
CurrentFile := DMLHistory.GetHistoryFileName;
end;
destructor TibSHDMLHistoryForm.Destroy;
begin
FTreePopupMenu.Free;
FSQLParser.Free;
inherited Destroy;
end;
function TibSHDMLHistoryForm.CalcImageIndex(ASQLKind: TSQLKind): Integer;
begin
case ASQLKind of
skUnknown, skDDL: Result := img_other;
skSelect: Result := img_select;
skUpdate: Result := img_update;
skInsert: Result := img_insert;
skDelete: Result := img_delete;
skExecuteProc: Result := img_execute;
skExecuteBlock: Result := img_execute;//!!!
else
Result := img_other;
end;
end;
procedure TibSHDMLHistoryForm.SelectTopLineBlock(ATopLine: Integer);
var
BlockBegin, BlockEnd: TBufferCoord;
begin
// Editor.CaretY := ATopLine;
// Editor.EnsureCursorPosVisibleEx(True);
Editor.BeginUpdate;
Editor.TopLine := ATopLine + 1;
BlockBegin.Char := 1;
BlockBegin.Line := ATopLine + 1;
BlockEnd.Char := 0;
BlockEnd.Line := ATopLine + 2;
Editor.CaretXY := BlockBegin;
Editor.BlockBegin := BlockBegin;
Editor.BlockEnd := BlockEnd;
Editor.LeftChar := 1;
Editor.EndUpdate;
end;
procedure TibSHDMLHistoryForm.DoOnEnter;
var
Data: PTreeRec;
begin
if Assigned(Tree.FocusedNode) then
begin
Data := Tree.GetNodeData(Tree.FocusedNode);
SelectTopLineBlock(Data.TopLine);
end;
end;
function TibSHDMLHistoryForm.GetDMLHistory: IibSHDMLHistory;
begin
Supports(Component, IibSHDMLHistory, Result);
end;
procedure TibSHDMLHistoryForm.FillPopupMenu;
begin
if Assigned(EditorPopupMenu) then
begin
AddMenuItem(EditorPopupMenu.Items, SSendToSQLEditor,
mnSendToSQLEditorFromEditorClick, ShortCut(VK_RETURN, [ssShift]));
AddMenuItem(FEditorPopupMenu.Items, '-', nil, 0, -2);
end;
if Assigned(FTreePopupMenu) then
begin
AddMenuItem(FTreePopupMenu.Items, SSendToSQLEditor,
mnSendToSQLEditorFromTreeClick, ShortCut(VK_RETURN, [ssShift]));
AddMenuItem(FTreePopupMenu.Items, '-', nil, 0, -3);
AddMenuItem(FTreePopupMenu.Items, SDeleteCurrentHistoryStatement,
mnDeleteStatementFromTreeClick);
end;
inherited FillPopupMenu;
end;
procedure TibSHDMLHistoryForm.DoOnPopup(Sender: TObject);
var
vCurrentMenuItem: TMenuItem;
begin
vCurrentMenuItem := MenuItemByName(EditorPopupMenu.Items, SSendToSQLEditor);
if Assigned(vCurrentMenuItem) then
begin
vCurrentMenuItem.Visible := GetCanSendToSQLEditor;
vCurrentMenuItem.Enabled := GetCanSendToSQLEditor;
end;
vCurrentMenuItem := MenuItemByName(EditorPopupMenu.Items, '-', -2);
if Assigned(vCurrentMenuItem) then
vCurrentMenuItem.Visible := GetCanSendToSQLEditor;
inherited DoOnPopup(Sender);
end;
procedure TibSHDMLHistoryForm.DoOnPopupTreeMenu(Sender: TObject);
var
vCurrentMenuItem: TMenuItem;
begin
vCurrentMenuItem := MenuItemByName(FTreePopupMenu.Items, SSendToSQLEditor);
if Assigned(vCurrentMenuItem) then
begin
vCurrentMenuItem.Visible := GetCanSendToSQLEditor and Assigned(Tree.FocusedNode);
vCurrentMenuItem.Enabled := GetCanSendToSQLEditor and Assigned(Tree.FocusedNode);
end;
vCurrentMenuItem := MenuItemByName(FTreePopupMenu.Items, '-', -2);
if Assigned(vCurrentMenuItem) then
vCurrentMenuItem.Visible := GetCanSendToSQLEditor and Assigned(Tree.FocusedNode);
//Delete
vCurrentMenuItem := MenuItemByName(FTreePopupMenu.Items, SDeleteCurrentHistoryStatement);
if Assigned(vCurrentMenuItem) then
begin
vCurrentMenuItem.Visible := GetCanSendToSQLEditor and Assigned(Tree.FocusedNode);
vCurrentMenuItem.Enabled := GetCanSendToSQLEditor and Assigned(Tree.FocusedNode);
end;
vCurrentMenuItem := MenuItemByName(FTreePopupMenu.Items, '-', -3);
if Assigned(vCurrentMenuItem) then
vCurrentMenuItem.Visible := GetCanSendToSQLEditor and Assigned(Tree.FocusedNode);
end;
procedure TibSHDMLHistoryForm.mnSendToSQLEditorFromEditorClick(
Sender: TObject);
begin
SinhronizeTreeByEditor;
SendToSQLEditorFromTree;
end;
procedure TibSHDMLHistoryForm.mnSendToSQLEditorFromTreeClick(
Sender: TObject);
begin
SendToSQLEditorFromTree;
end;
procedure TibSHDMLHistoryForm.mnDeleteStatementFromTreeClick(
Sender: TObject);
var
NodeData: PTreeRec;
begin
if Assigned(Tree.FocusedNode) then
begin
NodeData := Tree.GetNodeData(Tree.FocusedNode);
DMLHistory.DeleteStatement(NodeData.StatementNo);
end;
end;
procedure TibSHDMLHistoryForm.FillTree(AStatementNo: Integer);
var
StatementNode: PVirtualNode;
NodeData: PTreeRec;
vItem: string;
vPos: Integer;
vStatistics: TStringList;
function GetFirstWord: string;
var
I: Integer;
vSQLText: string;
begin
I := FSQLParser.FirstPos;
vSQLText := DMLHistory.Statement(AStatementNo);
while (I < Length(vSQLText)) and (not (vSQLText[I] in CharsAfterClause)) do Inc(I);
Result := Trim(AnsiUpperCase(System.Copy(vSQLText, FSQLParser.FirstPos, I - FSQLParser.FirstPos + 1)));
end;
begin
Tree.BeginUpdate;
StatementNode := Tree.AddChild(nil);
NodeData := Tree.GetNodeData(StatementNode);
vItem := DMLHistory.Item(AStatementNo);
vPos := Pos('*/', vItem);
if vPos > 0 then
begin
NodeData.ExecutedAt := Trim(System.Copy(vItem, Length(sHistorySQLHeader) + 1, vPos - Length(sHistorySQLHeader) - 1));
end
else
NodeData.ExecutedAt := DateTimeToStr(Now);
FSQLParser.SQLText := DMLHistory.Statement(AStatementNo);
NodeData.SQLKind := FSQLParser.SQLKind;
NodeData.ImageIndex := CalcImageIndex(NodeData.SQLKind);
NodeData.TopLine := Editor.Lines.Count;
NodeData.StatementNo := AStatementNo;
NodeData.FirstWord := GetFirstWord;
vStatistics := TStringList.Create;
try
vStatistics.Text := DMLHistory.Statistics(AStatementNo);
if vStatistics.Count > 0 then
begin
NodeData.ExecuteTime := StrToIntDef(vStatistics.Values[SHistoryExecute], 0);
NodeData.PrepareTime := StrToIntDef(vStatistics.Values[SHistoryPrepare], 0);
NodeData.FetchTime := StrToIntDef(vStatistics.Values[SHistoryFetch], 0);
NodeData.IndexedReads := StrToIntDef(vStatistics.Values[SHistoryIndexedReads], 0);
NodeData.NonIndexedReads := StrToIntDef(vStatistics.Values[SHistoryNonIndexedReads], 0);
NodeData.Inserts := StrToIntDef(vStatistics.Values[SHistoryInserts], 0);
NodeData.Updates := StrToIntDef(vStatistics.Values[SHistoryUpdates], 0);
NodeData.Deletes := StrToIntDef(vStatistics.Values[SHistoryDeletes], 0);
end;
finally
vStatistics.Free;
end;
Tree.EndUpdate;
end;
function TibSHDMLHistoryForm.GetRegionVisible: Boolean;
begin
Result := Panel1.Visible;
end;
procedure TibSHDMLHistoryForm.FillEditor;
var
I: Integer;
begin
if Assigned(DMLHistory) then
begin
Tree.Clear;
Editor.Clear;
for I := 0 to Pred(DMLHistory.Count) do
begin
FillTree(I);
Designer.TextToStrings(DMLHistory.Item(I), Editor.Lines);
end;
Editor.CaretY := Editor.Lines.Count;
SinhronizeTreeByEditor;
DoOnEnter;
end;
// Editor.Lines.Objects[Editor.Lines.Count - 1] := TObject(CalcImageIndex(EventDescr.OperationName));
// SelectTopLineBlock(TopLine);
end;
procedure TibSHDMLHistoryForm.ChangeNotification(AOldItem: Integer; Operation: TOperation);
procedure DeleteItem(AStatementNo: Integer);
var
Node: PVirtualNode;
NextNode: PVirtualNode;
NodeData: PTreeRec;
vTopLine: Integer;
I: Integer;
vLinesDeleted: Integer;
begin
if AStatementNo > -1 then
begin
Node := Tree.GetLast;
NextNode := nil;
vTopLine := -1;
//Удаляем старый нод
while Assigned(Node) do
begin
NodeData := Tree.GetNodeData(Node);
if NodeData.StatementNo = AStatementNo then
begin
vTopLine := NodeData.TopLine;
NextNode := Tree.GetNextSibling(Node);
Tree.DeleteNode(Node);
Break;
end
else
Node := Tree.GetPreviousSibling(Node);
end;
//Удаляем старый текст из эдитора
vLinesDeleted := 0;
if vTopLine > -1 then
begin
if vTopLine < Editor.Lines.Count then
Editor.Lines.Delete(vTopLine);
Inc(vLinesDeleted);
while (vTopLine < Editor.Lines.Count) and
(Pos(sHistorySQLHeader, Editor.Lines[vTopLine]) = 0) do
begin
Inc(vLinesDeleted);
Editor.Lines.Delete(vTopLine);
end;
end;
//Переиндексируем все ноды после удаленного
I := AStatementNo;
while Assigned(NextNode) do
begin
NodeData := Tree.GetNodeData(NextNode);
NodeData.StatementNo := I;
NodeData.TopLine := NodeData.TopLine - vLinesDeleted;
Inc(I);
NextNode := Tree.GetNextSibling(NextNode);
end;
end;
end;
begin
if Assigned(DMLHistory) then
begin
if Operation = opInsert then
begin
DeleteItem(AOldItem);
FillTree(DMLHistory.Count - 1);
Designer.TextToStrings(DMLHistory.Item(DMLHistory.Count - 1), Editor.Lines);
Editor.CaretY := Editor.Lines.Count;
SinhronizeTreeByEditor;
DoOnEnter;
end
else
begin
DeleteItem(AOldItem);
end;
end;
end;
function TibSHDMLHistoryForm.GetCanSendToSQLEditor: Boolean;
begin
Result := Assigned(Designer.GetComponent(IibSHSQLEditor)) and
Assigned(DMLHistory) and (DMLHistory.Count > 0) and
DMLHistory.BTCLDatabase.Connected;
end;
procedure TibSHDMLHistoryForm.ISendToSQLEditor;
begin
SinhronizeTreeByEditor;
SendToSQLEditorFromTree;
end;
function TibSHDMLHistoryForm.GetCanSave: Boolean;
begin
Result := Assigned(DMLHistory);
end;
procedure TibSHDMLHistoryForm.Save;
begin
if GetCanSave then
DMLHistory.SaveToFile;
end;
procedure TibSHDMLHistoryForm.SaveAs;
begin
if GetCanSaveAs then
begin
FSaveDialog.FileName := DoOnGetInitialDir + DMLHistory.BTCLDatabase.Alias + ' ' + Component.Caption;
if FSaveDialog.Execute then
begin
Screen.Cursor := crHourGlass;
try
DoSaveToFile(FSaveDialog.FileName);
finally
Screen.Cursor := crDefault;
end;
end;
ShowFileName;
end;
end;
function TibSHDMLHistoryForm.GetCanClearAll: Boolean;
begin
Result := Assigned(DMLHistory) and (DMLHistory.Count > 0);
end;
procedure TibSHDMLHistoryForm.ClearAll;
begin
if GetCanClearAll and
Designer.ShowMsg(Format(SClearDMLHistoryWorning,
[DMLHistory.BTCLDatabase.Alias]), mtConfirmation) then
begin
DMLHistory.Clear;
end;
end;
function TibSHDMLHistoryForm.GetCanRun: Boolean;
begin
Result := Assigned(DMLHistory) and not DMLHistory.Active;
end;
function TibSHDMLHistoryForm.GetCanPause: Boolean;
begin
Result := Assigned(DMLHistory) and DMLHistory.Active;
end;
function TibSHDMLHistoryForm.GetCanRefresh: Boolean;
begin
Result := Assigned(DMLHistory) and Assigned(Editor) and Editor.Modified;
end;
procedure TibSHDMLHistoryForm.Run;
begin
if Assigned(DMLHistory) then
begin
DMLHistory.Active := True;
Designer.UpdateObjectInspector;
end;
end;
procedure TibSHDMLHistoryForm.Pause;
begin
if Assigned(DMLHistory) then
begin
DMLHistory.Active := False;
Designer.UpdateObjectInspector;
end;
end;
procedure TibSHDMLHistoryForm.Refresh;
begin
if GetCanRefresh then
begin
Save;
DMLHistory.LoadFromFile;
FillEditor;
end;
end;
procedure TibSHDMLHistoryForm.ShowHideRegion(AVisible: Boolean);
begin
Panel1.Visible := AVisible;
Splitter1.Visible := AVisible;
if AVisible then Splitter1.Left := Panel1.Left + Panel1.Width + 1;
end;
procedure TibSHDMLHistoryForm.SinhronizeTreeByEditor;
var
Node: PVirtualNode;
NodeData: PTreeRec;
begin
Node := Tree.GetLast;
if Assigned(Node) then
begin
NodeData := Tree.GetNodeData(Node);
while Assigned(Node) and (NodeData.TopLine > (Editor.CaretY - 1)) do
begin
Node := Tree.GetPrevious(Node);
NodeData := Tree.GetNodeData(Node);
end;
if Assigned(Node) then
Tree.FocusedNode := Node
else
Tree.FocusedNode := Tree.GetLast;
Tree.Selected[Tree.FocusedNode] := True;
end;
end;
procedure TibSHDMLHistoryForm.SendToSQLEditorFromTree;
var
NodeData: PTreeRec;
begin
if Assigned(Tree.FocusedNode) then
begin
NodeData := Tree.GetNodeData(Tree.FocusedNode);
SendToSQLEditor(NodeData.StatementNo);
end;
end;
procedure TibSHDMLHistoryForm.SendToSQLEditor(const AStatementNo: Integer);
var
vComponent: TSHComponent;
vSQLEditorForm: IibSHSQLEditorForm;
function TrimLeftEpmtyStr(AString: string): string;
var
vStrList: TStringList;
begin
vStrList := TStringList.Create;
Result := AString;
try
vStrList.Text := AString;
while (vStrList.Count > 0) and (Length(vStrList[0]) = 0) do
vStrList.Delete(0);
Result := TrimRight(vStrList.Text);
finally
vStrList.Free;
end;
end;
begin
if Assigned(DMLHistory) and (AStatementNo >= 0) and
(AStatementNo < DMLHistory.Count) then
begin
vComponent := Designer.FindComponent(Component.OwnerIID, IibSHSQLEditor);
if not Assigned(vComponent) then
vComponent := Designer.CreateComponent(Component.OwnerIID, IibSHSQLEditor, '');
if Assigned(vComponent) then
begin
Designer.ChangeNotification(vComponent, SCallSQLText, opInsert);
if vComponent.GetComponentFormIntf(IibSHSQLEditorForm, vSQLEditorForm) then
begin
vSQLEditorForm.InsertStatement(TrimLeftEpmtyStr(DMLHistory.Statement(AStatementNo)));
Designer.JumpTo(Component.InstanceIID, IibSHSQLEditor, vComponent.Caption);
// Designer.ChangeNotification(vComponent, SCallSQLText, opInsert);
end;
end;
end;
end;
function TibSHDMLHistoryForm.DoOnOptionsChanged: Boolean;
begin
Result := inherited DoOnOptionsChanged;
if Result then
begin
Editor.ReadOnly := True;
Editor.Options := Editor.Options + [eoScrollPastEof];
// Editor.RightEdge := 0;
// Editor.BottomEdgeVisible := False;
end;
end;
procedure TibSHDMLHistoryForm.DoOnSpecialLineColors(Sender: TObject;
Line: Integer; var Special: Boolean; var FG, BG: TColor);
begin
Special := False;
if (Pos('->', pSHSynEdit1.Lines[Line - 1]) > 0) then
begin
Special := True;
FG := RGB(130, 220, 160);
end else
if (Pos('<-', pSHSynEdit1.Lines[Line - 1]) > 0) then
begin
Special := True;
FG := RGB(140,170, 210);
end else
if (Pos('>>', pSHSynEdit1.Lines[Line - 1]) > 0) then
begin
Special := True;
BG := RGB(235, 235, 235);
FG := RGB(140, 170, 210);
end;
end;
procedure TibSHDMLHistoryForm.pSHSynEdit1DblClick(Sender: TObject);
begin
SinhronizeTreeByEditor;
end;
procedure TibSHDMLHistoryForm.TreeMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if (Button = mbLeft) and (ssCtrl in Shift) then
SendToSQLEditorFromTree;
end;
procedure TibSHDMLHistoryForm.pSHSynEdit1MouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if (Button = mbLeft) and (ssCtrl in Shift) then
begin
SinhronizeTreeByEditor;
SendToSQLEditorFromTree;
end;
end;
{ Tree }
procedure TibSHDMLHistoryForm.TreeGetNodeDataSize(Sender: TBaseVirtualTree;
var NodeDataSize: Integer);
begin
NodeDataSize := SizeOf(TTreeRec);
end;
procedure TibSHDMLHistoryForm.TreeFreeNode(Sender: TBaseVirtualTree;
Node: PVirtualNode);
var
Data: PTreeRec;
begin
Data := Sender.GetNodeData(Node);
if Assigned(Data) then Finalize(Data^);
end;
procedure TibSHDMLHistoryForm.TreeGetImageIndex(Sender: TBaseVirtualTree;
Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
var Ghosted: Boolean; var ImageIndex: Integer);
var
Data: PTreeRec;
begin
// ImageIndex := -1;
// Data := Sender.GetNodeData(Node);
// if Tree.Header.Columns[Column].Tag = 9 then
// ImageIndex := CalcImageIndex(Data.SQLKind)
// else
// ImageIndex := -1;
// if (Kind = ikNormal) or (Kind = ikSelected) then ImageIndex := CalcImageIndex(Data.SQLKind);
if (Kind = ikNormal) or (Kind = ikSelected) then
begin
ImageIndex := -1;
if (Tree.Header.Columns[Column].Tag = 9) and Assigned(Node) then
begin
Data := Sender.GetNodeData(Node);
if Assigned(Data) then
ImageIndex := Data.ImageIndex;
end;
end;
end;
procedure TibSHDMLHistoryForm.TreeGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
var
Data: PTreeRec;
begin
Data := Sender.GetNodeData(Node);
case TextType of
ttNormal:
begin
case Tree.Header.Columns[Column].Tag of
0: CellText := Data.ExecutedAt;
1: CellText := msToStr(Data.ExecuteTime);
2: CellText := msToStr(Data.PrepareTime);
3: CellText := msToStr(Data.FetchTime);
4: CellText := FormatFloat('###,###,###,##0', Data.IndexedReads);
5: CellText := FormatFloat('###,###,###,##0', Data.NonIndexedReads);
6: CellText := FormatFloat('###,###,###,##0', Data.Inserts);
7: CellText := FormatFloat('###,###,###,##0', Data.Updates);
8: CellText := FormatFloat('###,###,###,##0', Data.Deletes);
9: CellText := Data.FirstWord;
end;
end;
end;
end;
procedure TibSHDMLHistoryForm.TreeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then DoOnEnter;
end;
procedure TibSHDMLHistoryForm.TreeDblClick(Sender: TObject);
begin
DoOnEnter;
end;
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* 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 owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFBrowserProcessHandler;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes, uCEFApplication;
type
TCefBrowserProcessHandlerOwn = class(TCefBaseRefCountedOwn, ICefBrowserProcessHandler)
protected
procedure OnContextInitialized; virtual; abstract;
procedure OnBeforeChildProcessLaunch(const commandLine: ICefCommandLine); virtual; abstract;
procedure OnRenderProcessThreadCreated(const extraInfo: ICefListValue); virtual; abstract;
function GetPrintHandler : ICefPrintHandler; virtual;
procedure OnScheduleMessagePumpWork(const delayMs: Int64); virtual; abstract;
public
constructor Create; virtual;
end;
TCefCustomBrowserProcessHandler = class(TCefBrowserProcessHandlerOwn)
protected
FCefApp : TCefApplication;
procedure OnContextInitialized; override;
procedure OnBeforeChildProcessLaunch(const commandLine: ICefCommandLine); override;
procedure OnRenderProcessThreadCreated(const extraInfo: ICefListValue); override;
procedure OnScheduleMessagePumpWork(const delayMs: Int64); override;
public
constructor Create(const aCefApp : TCefApplication); reintroduce;
destructor Destroy; override;
end;
implementation
uses
uCEFMiscFunctions, uCEFLibFunctions, uCEFCommandLine, uCEFListValue, uCEFConstants;
procedure cef_browser_process_handler_on_context_initialized(self: PCefBrowserProcessHandler); stdcall;
var
TempObject : TObject;
begin
TempObject := CefGetObject(self);
if (TempObject <> nil) and (TempObject is TCefBrowserProcessHandlerOwn) then
TCefBrowserProcessHandlerOwn(TempObject).OnContextInitialized;
end;
procedure cef_browser_process_handler_on_before_child_process_launch(self : PCefBrowserProcessHandler;
command_line : PCefCommandLine); stdcall;
var
TempObject : TObject;
begin
TempObject := CefGetObject(self);
if (TempObject <> nil) and (TempObject is TCefBrowserProcessHandlerOwn) then
TCefBrowserProcessHandlerOwn(TempObject).OnBeforeChildProcessLaunch(TCefCommandLineRef.UnWrap(command_line));
end;
procedure cef_browser_process_handler_on_render_process_thread_created(self : PCefBrowserProcessHandler;
extra_info : PCefListValue); stdcall;
var
TempObject : TObject;
begin
TempObject := CefGetObject(self);
if (TempObject <> nil) and (TempObject is TCefBrowserProcessHandlerOwn) then
TCefBrowserProcessHandlerOwn(TempObject).OnRenderProcessThreadCreated(TCefListValueRef.UnWrap(extra_info));
end;
function cef_browser_process_handler_get_print_handler(self: PCefBrowserProcessHandler): PCefPrintHandler; stdcall;
var
TempObject : TObject;
begin
TempObject := CefGetObject(self);
if (TempObject <> nil) and (TempObject is TCefBrowserProcessHandlerOwn) then
Result := CefGetData(TCefBrowserProcessHandlerOwn(TempObject).GetPrintHandler)
else
Result := nil;
end;
procedure cef_browser_process_handler_on_schedule_message_pump_work(self : PCefBrowserProcessHandler;
delay_ms : Int64); stdcall;
var
TempObject : TObject;
begin
TempObject := CefGetObject(self);
if (TempObject <> nil) and (TempObject is TCefBrowserProcessHandlerOwn) then
TCefBrowserProcessHandlerOwn(TempObject).OnScheduleMessagePumpWork(delay_ms);
end;
constructor TCefBrowserProcessHandlerOwn.Create;
begin
inherited CreateData(SizeOf(TCefBrowserProcessHandler));
with PCefBrowserProcessHandler(FData)^ do
begin
on_context_initialized := cef_browser_process_handler_on_context_initialized;
on_before_child_process_launch := cef_browser_process_handler_on_before_child_process_launch;
on_render_process_thread_created := cef_browser_process_handler_on_render_process_thread_created;
get_print_handler := cef_browser_process_handler_get_print_handler;
on_schedule_message_pump_work := cef_browser_process_handler_on_schedule_message_pump_work;
end;
end;
function TCefBrowserProcessHandlerOwn.GetPrintHandler : ICefPrintHandler;
begin
Result := nil; // only linux
end;
// TCefCustomBrowserProcessHandler
constructor TCefCustomBrowserProcessHandler.Create(const aCefApp : TCefApplication);
begin
inherited Create;
FCefApp := aCefApp;
end;
destructor TCefCustomBrowserProcessHandler.Destroy;
begin
FCefApp := nil;
inherited Destroy;
end;
procedure TCefCustomBrowserProcessHandler.OnContextInitialized;
begin
if (FCefApp <> nil) then FCefApp.Internal_OnContextInitialized;
end;
procedure TCefCustomBrowserProcessHandler.OnBeforeChildProcessLaunch(const commandLine: ICefCommandLine);
begin
if (FCefApp <> nil) then FCefApp.Internal_OnBeforeChildProcessLaunch(commandLine);
end;
procedure TCefCustomBrowserProcessHandler.OnRenderProcessThreadCreated(const extraInfo: ICefListValue);
begin
if (FCefApp <> nil) then FCefApp.Internal_OnRenderProcessThreadCreated(extraInfo);
end;
procedure TCefCustomBrowserProcessHandler.OnScheduleMessagePumpWork(const delayMs: Int64);
begin
if (FCefApp <> nil) then FCefApp.Internal_OnScheduleMessagePumpWork(delayMs);
end;
end.
|
{******************************************************************************}
{ @UnitName : lib.PnLocker.pas }
{ @Project : PonyWorkEx }
{ @Copyright : - }
{ @Author : 奔腾的心(7180001) }
{ @Description : PonyWorkEx 加强锁处理类 }
{ @FileVersion : 1.0.0.1 }
{ @CreateDate : 2011-04-28 }
{ @Comment : - }
{ @LastUpdate : 2011-07-09 }
{******************************************************************************}
unit lib.PnLocker;
interface
{.$DEFINE TMonitor}
{$DEFINE CSLock}
{.$DEFINE TSpinLock}
uses
System.SysUtils,
System.Classes,
System.SyncObjs;
type
TPnLocker = class
private
FLockName: string;
{$IFDEF TMonitor}
FLock: TObject;
{$ELSEIF defined(CSLock)}
FCSLock: TCriticalSection;
{$ELSEIF defined(TSpinLock)}
FSpLock: TSpinLock;
{$ENDIF}
function GetLockName: string;
public
constructor Create(const ALockName: string);
destructor Destroy; override;
procedure Lock; inline;
procedure UnLock; inline;
property LockName: string read GetLockName;
end;
implementation
constructor TPnLocker.Create(const ALockName: string);
begin
inherited Create;
FLockName := ALockName;
{$IFDEF TMonitor}
FLock := TObject.Create;
{$ELSEIF defined(CSLock)}
FCSLock := TCriticalSection.Create;
{$ELSEIF defined(TSpinLock)}
FSpLock := TSpinLock.Create(False);
{$ENDIF}
end;
destructor TPnLocker.Destroy;
begin
{$IFDEF TMonitor}
FreeAndNil(FLock);
{$ELSEIF defined(CSLock)}
FreeAndNil(FCSLock);
{$ELSEIF defined(TSpinLock)}
FreeAndNil(FSpLock);
{$ENDIF}
inherited Destroy;
end;
procedure TPnLocker.Lock;
begin
{$IFDEF TMonitor}
System.TMonitor.Enter(FLock);
{$ELSEIF defined(CSLock)}
FCSLock.Enter;
{$ELSEIF defined(TSpinLock)}
FSpLock.Enter;
{$ENDIF}
end;
procedure TPnLocker.UnLock;
begin
{$IFDEF TMonitor}
System.TMonitor.Exit(FLock);
{$ELSEIF defined(CSLock)}
FCSLock.Leave;
{$ELSEIF defined(TSpinLock)}
FSpLock.Exit;
{$ENDIF}
end;
function TPnLocker.GetLockName: string;
begin
Result := FLockName;
end;
end.
|
unit Globals;
interface
type
TAuthParams = record
// Параметры redirect_uri при успешной аутентификации
Status: string;
access_token: String;
expires_at: string;
account_id: string;
nickname: string;
// Параметры redirect_uri при ошибке аутентификации
StatusErr: string;
CodeErr: string;
MessageErr: string;
end;
var
g_AuthParams: TAuthParams;
procedure SetAuthParams(Status, access_token, expires_at,
account_id, nickname: string);
implementation
procedure SetAuthParams(Status, access_token, expires_at,
account_id, nickname: string);
Begin
FillChar(g_AuthParams, SizeOf(TAuthParams), #0); // Очищаем запись
try
g_AuthParams.Status := Status;
g_AuthParams.access_token := access_token;
g_AuthParams.expires_at := expires_at;
g_AuthParams.account_id := account_id;
g_AuthParams.nickname := nickname;
finally
end;
End;
end.
|
unit eUsusario.View.Conexao.Faredac;
interface
uses
eUsusario.View.Conexao.Interfaces, Data.DB, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf,
FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys,
FireDAC.Phys.FB, FireDAC.Phys.FBDef, FireDAC.VCLUI.Wait, FireDAC.Stan.Param,
FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet,
FireDAC.Comp.Client;
Type
TModelConexaoFaredac = class (TInterfacedObject, iConexao)
private
FConexao: TFDConnection;
public
constructor Create;
destructor Destroy; override;
class function New : iConexao;
function Connection : TCustomConnection;
end;
implementation
uses
System.SysUtils;
{ TModelConexaoFaredac }
function TModelConexaoFaredac.Connection: TCustomConnection;
begin
Result := FConexao;
end;
constructor TModelConexaoFaredac.Create;
begin
FConexao := TFDConnection.Create(nil);
FConexao.DriverName := 'FB';
FConexao.Params.Database := 'D:\SoNotasNFe\Dados\ACCESS_PRINT\SoNotasNFe.FDB';
FConexao.Params.UserName := 'SYSDBA';
FConexao.Params.Password := 'masterkey';
FConexao.Connected := True;
end;
destructor TModelConexaoFaredac.Destroy;
begin
FreeAndNil(FConexao);
inherited;
end;
class function TModelConexaoFaredac.New: iConexao;
begin
Result := Self.Create;
end;
end.
|
unit Forms.Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VCL.TMSFNCTypes, VCL.TMSFNCUtils, VCL.TMSFNCGraphics,
VCL.TMSFNCGraphicsTypes, VCL.TMSFNCMapsCommonTypes, VCL.TMSFNCCustomControl, VCL.TMSFNCWebBrowser,
VCL.TMSFNCMaps, Vcl.StdCtrls;
type
TFrmMain = class(TForm)
Map: TTMSFNCMaps;
cbLanguages: TComboBox;
procedure FormCreate(Sender: TObject);
procedure MapMapInitialized(Sender: TObject);
procedure cbLanguagesChange(Sender: TObject);
private
{ Private declarations }
procedure InitCombo;
procedure UpdateLanguage;
public
{ Public declarations }
end;
var
FrmMain: TFrmMain;
implementation
{$R *.dfm}
uses Flix.Utils.Maps, IOUtils;
const
C_LOCALES : Array[0..6] of string =
( 'de-DE|German, Germany', 'en-US|English, United States',
'en-GB|English, Great Britain', 'fr-FR|French, France',
'nl-NL|Dutch, Netherlands', 'it-IT|Italian, Italy',
'pt-BR|Portuguese, Brazil' );
procedure TFrmMain.cbLanguagesChange(Sender: TObject);
begin
UpdateLanguage;
end;
procedure TFrmMain.FormCreate(Sender: TObject);
var
LKeys: TServiceAPIKeys;
begin
cbLanguages.Items.Clear;
LKeys := TServiceAPIKeys.Create( TPath.Combine( TTMSFNCUtils.GetAppPath, 'apikeys.config' ) );
try
Map.APIKey := LKeys.GetKey( msGoogleMaps );
finally
LKeys.Free;
end;
end;
procedure TFrmMain.InitCombo;
var
LLang : String;
LSplits: TArray<string>;
begin
if cbLanguages.Items.Count = 0 then
begin
for LLang in C_LOCALES do
begin
LSplits := LLang.Split(['|']);
cbLanguages.Items.Add( LSplits[1] );
end;
cbLanguages.ItemIndex := 0;
UpdateLanguage;
end;
end;
procedure TFrmMain.MapMapInitialized(Sender: TObject);
begin
InitCombo;
end;
procedure TFrmMain.UpdateLanguage;
var
LLang : String;
LSplits: TArray<string>;
begin
if cbLanguages.ItemIndex > -1 then
begin
LLang := C_LOCALES[ cbLanguages.ItemIndex ];
LSplits := LLang.Split(['|']);
Map.Options.Locale := LSplits[0];
Map.ReInitialize;
end;
end;
end.
|
//*****************************************************************//
// //
// TMapStream //
// Copyrightę BrandsPatch LLC //
// http://www.explainth.at //
// //
// All Rights Reserved //
// //
// Permission is granted to use, modify and redistribute //
// the code in this Delphi unit on the condition that this //
// notice is retained unchanged. //
// //
// BrandsPatch declines all responsibility for any losses, //
// direct or indirect, that may arise as a result of using //
// this code. //
// //
//*****************************************************************//
unit MapStream;
interface
uses Windows,
SysUtils,
JclStrings,
Classes,
uFileDir,
SyncObjs,
uHashTable;
const
//MAXCARDINALMINUS = (4294967295 - 1);
MAXINTMINUS = MAXINT - 1;
INVALID_SIZE = -1;
MAP_DEBUG='MAP.LOG';
type
TMapBytes = array[0..MAXINTMINUS] of Byte;
PMapBytes = ^TMapBytes;
TMapStream = class(TObject)
private
FHandle : THandle;
FPosition:Cardinal;
FSize:Cardinal;
FTimeOut:Integer;
FName : string;
//This is the object that created the the Stream. This is because
// the only object that should delete the stream should be object that created it
procedure SetPosition(Value:Cardinal);
function CountGood(Count:Cardinal):Boolean;
function GrabEvent:Boolean;
procedure ReleaseEvent;
constructor CreateEx(const AName: String; ASize: Cardinal;
ATimeOut: Integer);
function CopyFrom(AStream:TStream;Count:Cardinal):Boolean;
function CopyTo(AStream: TStream ): Boolean;
protected
FEvent:TEvent;
FMemory:PMapBytes;
property Name : string read FName write FName;
public
property Position:Cardinal read FPosition write SetPosition;
property MMHandle:THandle read FHandle write FHandle;
constructor Create( const AName:String;ASize:Cardinal;ATimeOut:Integer); overload;
constructor Create( const AName:String;ASize:Cardinal); overload;
constructor Create( const AName:String); overload;
destructor Destroy;override;
function Clear : Boolean;
function ReadBuffer(P:Pointer;Count:Cardinal):Boolean;
function WriteBuffer(P:Pointer;Count:Cardinal):Boolean;
function Read( var str : string ):Boolean; overload;
function Read( streamToWriteTo : TStream ):Boolean; overload;
function Write( const str : string; DoClearFirst : boolean = false ):Boolean; overload;
function Write( streamToReadFrom : TStream; DoClearFirst : boolean = false ):Boolean; overload;
end;
TMSDataType = ( dtString );
TMSData = record
DataType: TMSDataType;
StringValue: AnsiString;
class operator Implicit( const aValue: AnsiString ): TMSData;
end;
TMemoryStreamPlus = class( TMemoryStream )
private
public
function Read( const DataTypeToReturn : TMSDataType = dtString ) : TMSData;
function Write( const Value: TMSData ) : boolean;
destructor Destroy; override;
constructor Create( Value: TMSData ); overload; dynamic;
constructor Create(); overload; dynamic;
end;
type
ENoMapping = class(Exception);
implementation
{ TMSData }
class operator TMSData.Implicit(const aValue: AnsiString): TMSData;
begin
Result.DataType := dtString;
Result.StringValue := aValue;
end;
{ TMapStream }
//....................................................MapStream Create & Destroy
constructor TMapStream.Create( const AName: String; ASize: Cardinal;
ATimeOut: Integer);
begin
CreateEx(AName, ASize, ATimeOut );
end;
constructor TMapStream.Create( const AName: String; ASize: Cardinal);
begin
self.CreateEx( AName, ASize, 2000 );
end;
constructor TMapStream.Create( const AName: String);
begin
self.CreateEx( AName, MAXWORD, 2000 );
end;
constructor TMapStream.CreateEx(const AName:String; ASize:Cardinal; ATimeOut:Integer);
Begin
inherited Create;
FHandle := 0;
FSize:=ASize;
FTimeOut:=ATimeOut;
FName := AName;
// This code will make sure that the entry has been added into the memory stream manager
//if (FSize < 1) or (FSize > MAXCARDINALMINUS) then FSize:=MAXWORD;
if ((FSize < 1) or (FSize > MAXINTMINUS)) then
raise Exception.Create( 'Size specified is out of range (1 - ' + IntToStr(MAXINTMINUS) + ')' );
//2000ms timeout for safety
if ((FTimeOut < 1) or (FTimeOut > 5000)) then FTimeOut:=2000;
//if (( ActiveMemoryMaps <> nil ) and (ActiveMemoryMaps.Exists( AName ))) then
// FTimeOut := FTimeOut * 1;
//raise Exception.Create( 'A Memory Map of name ' + AName + ' has already been allocated.' );
FHandle:=CreateFileMapping($FFFFFFFF,nil,PAGE_READWRITE,0,FSize,PChar(AName));
//See the Windows Kernel32 CreateFileMapping function for information
if (FHandle = 0) then
ENoMapping.Create(Format('%s file mapping failed.',[AName]))
else begin
//if ( ActiveMemoryMaps <> nil ) then ActiveMemoryMaps.Add( self );
FMemory:=MapViewOfFile( FHandle,FILE_MAP_ALL_ACCESS,0,0,0 );
if ( FMemory = nil ) then
raise Exception.Create( 'MapViewOfFile Failed. ' + SysErrorMessage(GetLastError));
//WriteString( uFileDir.GetModuleName() + '| MAP Allocated... Name=' + AName + ' Size=' + IntToStr(ASize) + ' Views Open=' + IntToStr(nOpenView), MAP_DEBUG, true );
FEvent:=TEvent.Create(nil,True,True,Format('ExplainThat_%s_MAP',[AName]));
end;
End;
destructor TMapStream.Destroy;
Begin
//if (( ActiveMemoryMaps <> nil ) and (ActiveMemoryMaps.Exists( self.FName ))) then
// ActiveMemoryMaps.Delete( self.FName );
//WriteString(uFileDir.GetModuleName() + '| MAP CLOSE... Name=' + self.FName + ' Size=' + IntToStr(self.FSize) + ' Views Open=' + IntToStr(nOpenView), MAP_DEBUG, true );
UnMapViewOfFile(FMemory);
CloseHandle(FHandle);
FEvent.Free;
inherited;
End;
//.........................................................
function TMapStream.CountGood(Count:Cardinal):Boolean;
Begin
Result:=(FPosition + Count < FSize);
End;
function TMapStream.GrabEvent:Boolean;
Begin
Result:=True;
with FEvent do
begin
case WaitFor(FTimeOut) of
wrSignaled:ReSetEvent;
{locks the event for exclusive use by this app. Funny name, ReSetEvent, not
our choice!}
else Result:=False;
end;
end;
End;
procedure TMapStream.ReleaseEvent;
Begin
FEvent.SetEvent;//unlock the event so other apps can use it
End;
//========================================================MapStream Manipulation
function TMapStream.Clear:Boolean;
Begin
if GrabEvent then
try
//FillChar(FMemory^[0],FSize,0);
FillChar( FMemory^, FSize, 0 );
FPosition:=0;
Result:=True;
finally
ReleaseEvent
end
else
Result:=False;
End;
function TMapStream.CopyFrom(AStream:TStream;Count:Cardinal):Boolean;
function SizeGood:Boolean;
var i,ASize:Int64;
begin
ASize:=AStream.Size;
if (Count = 0) or (Count > ASize) then
begin
Count:=ASize;
AStream.Position:=0;
end;
Result:=(FPosition + Count < FSize);
{make sure the copy block is not too big. Incidentally, also make Count = 0
as in Delphi.TStream}
end;
Begin
if SizeGood and GrabEvent then
try
AStream.ReadBuffer(Byte(FMemory^[FPosition]),Count);
Result:=True;
finally ReleaseEvent end else Result:=False;
End;
function TMapStream.CopyTo(AStream:TStream):Boolean;
var
Count : Int64;
ASize : Int64;
P:PChar;
Begin
if ( AStream = nil ) then
raise Exception.Create( 'Passed Stream must not be nil');
self.Position := 0;
ReadBuffer(@ASize,sizeof(Integer));//read the mapped text size
//AStream.Size := ASize;
AStream.WriteBuffer( Byte(FMemory^[FPosition]), ASize );
End;
function TMapStream.Read(var str: string): Boolean;
var ASize, iMemSize:Integer;
P : PChar;
begin
Result := false;
with Self do
begin
Position:=0;
ReadBuffer(@ASize,sizeof(Integer));//read the mapped text size
inc(ASize);
iMemSize := ASize;
P:=AllocMem( iMemSize );//create a buffer big enough to hold it
P[iMemSize - 1]:=#0;//so we don't show garbage beyond the last character
dec(ASize);
try
//WriteString(uFileDir.GetModuleName() + '| ' + FName + ' Read(str): DataLen=' + IntToStr(ASize), MAP_DEBUG, true );
ReadBuffer( P, ASize );//read the mapped text
//not doing this results in a memory leak which can bring down the app!
str:= string( P );
Result := true;
finally
FreeMem( P, iMemSize );
iMemSize := 0;
end;
end;
end;
function TMapStream.Read(streamToWriteTo: TStream): Boolean;
var
ASize, iMemSize:Integer;
begin
Result := false;
with Self do
begin
Position:=0;
ASize := streamToWriteTo.Size;
ReadBuffer(@ASize,sizeof(Integer));//read the mapped text size
inc(ASize);
iMemSize := ASize;
dec(ASize);
try
//WriteString(uFileDir.GetModuleName() + '| ' + FName + ' Read(streamToWriteTo): DataLen=' + IntToStr(ASize), MAP_DEBUG, true );
streamToWriteTo.Position := 0;
streamToWriteTo.Write( Byte(FMemory^[FPosition]), ASize );
inc(FPosition,ASize);
streamToWriteTo.Position := 0;
Result := true;
finally
iMemSize := 0;
end;
end;
end;
function TMapStream.ReadBuffer(P:Pointer;Count:Cardinal):Boolean;
Begin
if CountGood(Count) and GrabEvent then
try
//WriteString(uFileDir.GetModuleName() + '| ' + FName + ' ReadBuffer(P): DataLen=' + IntToStr(Count), MAP_DEBUG, true );
Move(FMemory^[FPosition],P^,Count);
inc(FPosition,Count);
Result:=True;
finally ReleaseEvent end else Result:=False;
End;
function TMapStream.Write(const str: string; DoClearFirst : boolean ): Boolean;
Var
i,ASize:Integer;
AText:String;
Begin
//WriteString(uFileDir.GetModuleName() + '| ' + FName + ' Write(str): DataLen=' + IntToStr(Length(str)), MAP_DEBUG, true );
Result := false;
AText:=str;
ASize:=Length(AText);
with Self do
begin
if DoClearFirst then Clear;
WriteBuffer(@ASize,sizeof(Integer));//first write the text length
WriteBuffer(PChar(AText),ASize);//then write the text itself
Result := true;
end;
//i:=BSM_APPLICATIONS;
//BroadcastSystemMessage(BSF_IGNORECURRENTTASK or BSF_POSTMESSAGE,
// @i,FMessage,0,0);
End;
function TMapStream.Write(streamToReadFrom: TStream; DoClearFirst : boolean ): Boolean;
Var
i,ASize:Integer;
Begin
Result := false;
ASize:=streamToReadFrom.Size;
FPosition := 0;
if (FPosition + sizeof(Integer) + ASize > FSize) then
raise Exception.Create('Size of stream to write into Memory map (' + IntToStr(ASize) + ') is too big (Max=(' + IntToStr(FSize) + '))');
with Self do
begin
if DoClearFirst then Clear;
try
//WriteString(uFileDir.GetModuleName() + '| ' + FName + ' Write(streamToReadFrom): DataLen=' + IntToStr(ASize), MAP_DEBUG, true );
WriteBuffer(@ASize,sizeof(Integer));//first write the text length
streamToReadFrom.Position := 0;
streamToReadFrom.ReadBuffer(Byte(FMemory^[FPosition]),ASize);
except
raise;
end;
Result := true;
end;
//i:=BSM_APPLICATIONS;
//BroadcastSystemMessage(BSF_IGNORECURRENTTASK or BSF_POSTMESSAGE,
// @i,FMessage,0,0);
End;
function TMapStream.WriteBuffer(P:Pointer;Count:Cardinal):Boolean;
Begin
if CountGood(Count) and GrabEvent then
try
//WriteString(uFileDir.GetModuleName() + '| ' + FName + ' WriteBuffer(P): DataLen=' + IntToStr(Count), MAP_DEBUG, true );
Move(P^,FMemory^[FPosition],Count);
inc(FPosition,Count);
Result:=True;
finally ReleaseEvent end else Result:=False;
End;
procedure TMapStream.SetPosition(Value:Cardinal);
Begin
if (Value < FSize) and (Value >= 0) then FPosition:=Value;
End;
{ TMemoryStreamPlus }
constructor TMemoryStreamPlus.Create(Value: TMSData);
begin
self.Write( Value );
end;
constructor TMemoryStreamPlus.Create;
begin
end;
destructor TMemoryStreamPlus.Destroy;
begin
inherited;
end;
function TMemoryStreamPlus.Read(const DataTypeToReturn: TMSDataType): TMSData;
var
lng : integer;
s:string;
Begin
if ( DataTypeToReturn = dtString ) then begin
self.Position := 0;
self.ReadBuffer(lng, SizeOf(lng));
SetLength(s, lng);
self.ReadBuffer(s[1], lng);
Result := s;
end;
End;
function TMemoryStreamPlus.Write(const Value: TMSData): boolean;
var
lng : integer;
Begin
Result := false;
try
if ( Value.DataType = dtString ) then begin
lng := Length( Value.StringValue );
self.WriteBuffer(lng, SizeOf(lng));
// Write the string to the stream. We want to write from SourceString's
// data, starting at a pointer to SourceString (this returns a pointer to
// the first character), dereferenced (this gives the actual character).
self.WriteBuffer(Value.StringValue[1], Length(Value.StringValue));
Result := true;
end;
finally
end;
End;
initialization
finalization
END.
|
unit TestctsObjectStructure;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, ctsTypesDef, ctsBaseInterfaces, ctsCommons, ctsObserver,
ctsBaseClasses, ctsSyncObjects, ctsObjectInterface, ctsMemoryPools,
ctsObjectStructure;
type
// Test methods for class TctsVector
TestTctsVector = class(TTestCase)
private
FctsVector: TctsVector;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestAdd;
procedure TestClear;
procedure TestContain;
procedure TestDelete;
procedure TestFirst;
procedure TestGetArray;
procedure TestIndexOf;
procedure TestInsert;
procedure TestIsSorted;
procedure TestLast;
procedure TestPack;
procedure TestRemove;
procedure TestSetCapacity;
procedure TestSort;
end;
// Test methods for class TctsLinkedList
TestTctsLinkedList = class(TTestCase)
private
FctsLinkedList: TctsLinkedList;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestAdd;
procedure TestClear;
procedure TestContain;
procedure TestDeleteNode;
procedure TestFirst;
procedure TestGetHead;
procedure TestGetTail;
procedure TestInsertNode;
procedure TestIsSorted;
procedure TestLast;
procedure TestPack;
procedure TestRemove;
procedure TestSort;
end;
// Test methods for class TctsStackVector
TestTctsStackVector = class(TTestCase)
private
FctsStackVector: TctsStackVector;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestPop;
procedure TestPush;
procedure TestTop;
end;
// Test methods for class TctsStackLinked
TestTctsStackLinked = class(TTestCase)
private
FctsStackLinked: TctsStackLinked;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestPop;
procedure TestPush;
procedure TestTop;
end;
// Test methods for class TctsQueueVector
TestTctsQueueVector = class(TTestCase)
private
FctsQueueVector: TctsQueueVector;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestBack;
procedure TestFront;
procedure TestPop;
procedure TestPush;
end;
// Test methods for class TctsQueueLinked
TestTctsQueueLinked = class(TTestCase)
private
FctsQueueLinked: TctsQueueLinked;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestBack;
procedure TestFront;
procedure TestPop;
procedure TestPush;
end;
implementation
procedure TestTctsVector.SetUp;
begin
FctsVector := TctsVector.Create;
end;
procedure TestTctsVector.TearDown;
begin
FctsVector.Free;
FctsVector := nil;
end;
procedure TestTctsVector.TestAdd;
var
AItem: System.TObject;
begin
// TODO: Setup method call parameters
FctsVector.Add(AItem);
// TODO: Validate method results
end;
procedure TestTctsVector.TestClear;
begin
FctsVector.Clear;
// TODO: Validate method results
end;
procedure TestTctsVector.TestContain;
var
ReturnValue: Boolean;
AItem: System.TObject;
begin
// TODO: Setup method call parameters
ReturnValue := FctsVector.Contain(AItem);
// TODO: Validate method results
end;
procedure TestTctsVector.TestDelete;
var
AIndex: System.Integer;
begin
// TODO: Setup method call parameters
FctsVector.Delete(AIndex);
// TODO: Validate method results
end;
procedure TestTctsVector.TestFirst;
var
ReturnValue: IctsIterator;
begin
ReturnValue := FctsVector.First;
// TODO: Validate method results
end;
procedure TestTctsVector.TestGetArray;
var
ReturnValue: PctsDataTypeArray;
begin
ReturnValue := FctsVector.GetArray;
// TODO: Validate method results
end;
procedure TestTctsVector.TestIndexOf;
var
ReturnValue: System.Integer;
AItem: System.TObject;
begin
// TODO: Setup method call parameters
ReturnValue := FctsVector.IndexOf(AItem);
// TODO: Validate method results
end;
procedure TestTctsVector.TestInsert;
var
AItem: System.TObject;
AIndex: System.Integer;
begin
// TODO: Setup method call parameters
FctsVector.Insert(AIndex, AItem);
// TODO: Validate method results
end;
procedure TestTctsVector.TestIsSorted;
var
ReturnValue: Boolean;
begin
ReturnValue := FctsVector.IsSorted;
// TODO: Validate method results
end;
procedure TestTctsVector.TestLast;
var
ReturnValue: IctsIterator;
begin
ReturnValue := FctsVector.Last;
// TODO: Validate method results
end;
procedure TestTctsVector.TestPack;
begin
FctsVector.Pack;
// TODO: Validate method results
end;
procedure TestTctsVector.TestRemove;
var
ReturnValue: Boolean;
AItem: System.TObject;
begin
// TODO: Setup method call parameters
ReturnValue := FctsVector.Remove(AItem);
// TODO: Validate method results
end;
procedure TestTctsVector.TestSetCapacity;
var
AValue: System.Integer;
begin
// TODO: Setup method call parameters
FctsVector.SetCapacity(AValue);
// TODO: Validate method results
end;
procedure TestTctsVector.TestSort;
begin
FctsVector.Sort;
// TODO: Validate method results
end;
procedure TestTctsLinkedList.SetUp;
begin
FctsLinkedList := TctsLinkedList.Create;
end;
procedure TestTctsLinkedList.TearDown;
begin
FctsLinkedList.Free;
FctsLinkedList := nil;
end;
procedure TestTctsLinkedList.TestAdd;
var
AItem: System.TObject;
begin
// TODO: Setup method call parameters
FctsLinkedList.Add(AItem);
// TODO: Validate method results
end;
procedure TestTctsLinkedList.TestClear;
begin
FctsLinkedList.Clear;
// TODO: Validate method results
end;
procedure TestTctsLinkedList.TestContain;
var
ReturnValue: Boolean;
AItem: System.TObject;
begin
// TODO: Setup method call parameters
ReturnValue := FctsLinkedList.Contain(AItem);
// TODO: Validate method results
end;
procedure TestTctsLinkedList.TestDeleteNode;
var
aNode: PNode;
begin
// TODO: Setup method call parameters
FctsLinkedList.DeleteNode(aNode);
// TODO: Validate method results
end;
procedure TestTctsLinkedList.TestFirst;
var
ReturnValue: IctsIterator;
begin
ReturnValue := FctsLinkedList.First;
// TODO: Validate method results
end;
procedure TestTctsLinkedList.TestGetHead;
var
ReturnValue: PNode;
begin
ReturnValue := FctsLinkedList.GetHead;
// TODO: Validate method results
end;
procedure TestTctsLinkedList.TestGetTail;
var
ReturnValue: PNode;
begin
ReturnValue := FctsLinkedList.GetTail;
// TODO: Validate method results
end;
procedure TestTctsLinkedList.TestInsertNode;
var
AItem: System.TObject;
aNode: PNode;
begin
// TODO: Setup method call parameters
FctsLinkedList.InsertNode(aNode, AItem);
// TODO: Validate method results
end;
procedure TestTctsLinkedList.TestIsSorted;
var
ReturnValue: Boolean;
begin
ReturnValue := FctsLinkedList.IsSorted;
// TODO: Validate method results
end;
procedure TestTctsLinkedList.TestLast;
var
ReturnValue: IctsIterator;
begin
ReturnValue := FctsLinkedList.Last;
// TODO: Validate method results
end;
procedure TestTctsLinkedList.TestPack;
begin
FctsLinkedList.Pack;
// TODO: Validate method results
end;
procedure TestTctsLinkedList.TestRemove;
var
ReturnValue: Boolean;
AItem: System.TObject;
begin
// TODO: Setup method call parameters
ReturnValue := FctsLinkedList.Remove(AItem);
// TODO: Validate method results
end;
procedure TestTctsLinkedList.TestSort;
begin
FctsLinkedList.Sort;
// TODO: Validate method results
end;
procedure TestTctsStackVector.SetUp;
begin
FctsStackVector := TctsStackVector.Create;
end;
procedure TestTctsStackVector.TearDown;
begin
FctsStackVector.Free;
FctsStackVector := nil;
end;
procedure TestTctsStackVector.TestPop;
begin
FctsStackVector.Pop;
// TODO: Validate method results
end;
procedure TestTctsStackVector.TestPush;
var
aItem: System.TObject;
begin
// TODO: Setup method call parameters
FctsStackVector.Push(aItem);
// TODO: Validate method results
end;
procedure TestTctsStackVector.TestTop;
var
ReturnValue: System.TObject;
begin
ReturnValue := FctsStackVector.Top;
// TODO: Validate method results
end;
procedure TestTctsStackLinked.SetUp;
begin
FctsStackLinked := TctsStackLinked.Create;
end;
procedure TestTctsStackLinked.TearDown;
begin
FctsStackLinked.Free;
FctsStackLinked := nil;
end;
procedure TestTctsStackLinked.TestPop;
begin
FctsStackLinked.Pop;
// TODO: Validate method results
end;
procedure TestTctsStackLinked.TestPush;
var
aItem: System.TObject;
begin
// TODO: Setup method call parameters
FctsStackLinked.Push(aItem);
// TODO: Validate method results
end;
procedure TestTctsStackLinked.TestTop;
var
ReturnValue: System.TObject;
begin
ReturnValue := FctsStackLinked.Top;
// TODO: Validate method results
end;
procedure TestTctsQueueVector.SetUp;
begin
FctsQueueVector := TctsQueueVector.Create;
end;
procedure TestTctsQueueVector.TearDown;
begin
FctsQueueVector.Free;
FctsQueueVector := nil;
end;
procedure TestTctsQueueVector.TestBack;
var
ReturnValue: System.TObject;
begin
ReturnValue := FctsQueueVector.Back;
// TODO: Validate method results
end;
procedure TestTctsQueueVector.TestFront;
var
ReturnValue: System.TObject;
begin
ReturnValue := FctsQueueVector.Front;
// TODO: Validate method results
end;
procedure TestTctsQueueVector.TestPop;
begin
FctsQueueVector.Pop;
// TODO: Validate method results
end;
procedure TestTctsQueueVector.TestPush;
var
aItem: System.TObject;
begin
// TODO: Setup method call parameters
FctsQueueVector.Push(aItem);
// TODO: Validate method results
end;
procedure TestTctsQueueLinked.SetUp;
begin
FctsQueueLinked := TctsQueueLinked.Create;
end;
procedure TestTctsQueueLinked.TearDown;
begin
FctsQueueLinked.Free;
FctsQueueLinked := nil;
end;
procedure TestTctsQueueLinked.TestBack;
var
ReturnValue: System.TObject;
begin
ReturnValue := FctsQueueLinked.Back;
// TODO: Validate method results
end;
procedure TestTctsQueueLinked.TestFront;
var
ReturnValue: System.TObject;
begin
ReturnValue := FctsQueueLinked.Front;
// TODO: Validate method results
end;
procedure TestTctsQueueLinked.TestPop;
begin
FctsQueueLinked.Pop;
// TODO: Validate method results
end;
procedure TestTctsQueueLinked.TestPush;
var
aItem: System.TObject;
begin
// TODO: Setup method call parameters
FctsQueueLinked.Push(aItem);
// TODO: Validate method results
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTctsVector.Suite);
RegisterTest(TestTctsLinkedList.Suite);
RegisterTest(TestTctsStackVector.Suite);
RegisterTest(TestTctsStackLinked.Suite);
RegisterTest(TestTctsQueueVector.Suite);
RegisterTest(TestTctsQueueLinked.Suite);
end.
|
unit EditMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, AppEvnts,
Node, Box, Flow, EditBox;
type
TForm2 = class(TForm)
ApplicationEvents1: TApplicationEvents;
procedure FormPaint(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure FormDeactivate(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
private
{ Private declarations }
procedure AddKey(Key: Char);
procedure ValidateCursor;
procedure SetCaret;
procedure FindCaret;
procedure PaintBlock;
public
{ Public declarations }
Block: TEditBox;
Node: TNode;
Text: string;
Cursor: Integer;
CaretPos: TPoint;
end;
var
Form2: TForm2;
implementation
uses
Text;
{$R *.dfm}
procedure TForm2.FormCreate(Sender: TObject);
begin
DoubleBuffered := true;
Block := TEditBox.Create;
Node := TNode.Create;
Node.Text := 'Now is the time for all good men to come to the aid of their party. ';
Block.AddBox.Node := Node;
Node := TNode.Create;
Node.Text := 'The quick brown fox jumped over the lazy dog.';
Block.AddBox.Node := Node;
Block.Top := 100;
Block.Canvas := Canvas;
Block.WrapLines(ClientWidth);
FindCaret;
end;
procedure TForm2.FormActivate(Sender: TObject);
begin
CreateCaret(Handle, 0, 2, 13);
SetCaret;
ShowCaret(Handle);
end;
procedure TForm2.FormDeactivate(Sender: TObject);
begin
HideCaret(Handle);
DestroyCaret;
end;
procedure TForm2.FormResize(Sender: TObject);
begin
Block.WrapLines(ClientWidth);
ValidateCursor;
FindCaret;
SetCaret;
Invalidate;
end;
procedure TForm2.FormPaint(Sender: TObject);
begin
PaintBlock;
end;
procedure TForm2.FindCaret;
begin
CaretPos := Block.FindCaret(Cursor);
end;
procedure TForm2.SetCaret;
begin
SetCaretPos(CaretPos.X, CaretPos.Y);
end;
procedure TForm2.ValidateCursor;
begin
if Cursor < 0 then
Cursor := 0
// else if Cursor > Length(Text) then
// Cursor := Length(Text);
end;
procedure TForm2.PaintBlock;
begin
HideCaret(Handle);
Block.PaintLines;
ShowCaret(Handle);
end;
procedure TForm2.AddKey(Key: Char);
begin
case Key of
#$08: // backspace
begin
with Block, Block.CursorBox.Node do
Text := Copy(Text, 1, CursorIndex - 1) + Copy(Text, CursorIndex + 1, MAXINT);
Dec(Cursor);
end;
#$01:; // linefeed
#$1b:; // escape
#$09:; // tab
#$0D:; // return
else
begin
with Block, Block.CursorBox.Node do
Text := Copy(Text, 1, CursorIndex) + Key + Copy(Text, CursorIndex + 1, MAXINT);
Inc(Cursor);
end;
end;
Block.WrapLines(ClientWidth);
ValidateCursor;
FindCaret;
SetCaret;
Repaint;
end;
procedure TForm2.FormKeyPress(Sender: TObject; var Key: Char);
begin
Block.FindCursor(Self.Cursor);
if Block.CursorBox <> nil then
AddKey(Key);
end;
procedure TForm2.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_HOME: Cursor := 0;
VK_END: Cursor := MAXINT;
VK_LEFT: Dec(Cursor);
VK_RIGHT: Inc(Cursor);
else exit;
end;
ValidateCursor;
FindCaret;
SetCaret;
end;
end.
|
(*
Category: SWAG Title: MATH ROUTINES
Original name: 0076.PAS
Description: Random Gaussian Variables
Author: RANDALL ELTON DING
Date: 08-25-94 09:08
*)
(*
From: randyd@alpha2.csd.uwm.edu (Randall Elton Ding)
>I a program I'm currently struggeling with, I need to get a random number
>from a Gaussian distribution. Anybody got any ideas or anybody able to point
>to something which does the job.
This does a pretty good job of generating a gaussian random variable
with mean `a` and standard deviation `d`.
This program also does a graphic plot to demonstrate the function.
First, here is the origional C source if the gaussian function
which I transcribed to beloved pascal..
/* ------------------------------------------------ *
* gaussian -- generates a gaussian random variable *
* with mean a and standard deviation d *
* ------------------------------------------------ */
double gaussian(a,d)
double a,d;
{
static double t = 0.0;
double x,v1,v2,r;
if (t == 0) {
do {
v1 = 2.0 * rnd() - 1.0;
v2 = 2.0 * rnd() - 1.0;
r = v1 * v1 + v2 * v2;
} while (r>=1.0);
r = sqrt((-2.0*log(r))/r);
t = v2*r;
return(a+v1*r*d);
}
else {
x = t;
t = 0.0;
return(a+x*d);
}
}
* ----------------------------------------------------------------------
* now, the same thing in pascal
* ----------------------------------------------------------------------
*)
program testgaussian;
uses graph,crt;
const
bgipath = 'e:\bp\bgi';
procedure initbgi;
var
errcode,grdriver,grmode: integer;
begin
grdriver:= detect;
grmode:= 0;
initgraph (grdriver,grmode,bgipath);
errcode:= graphresult;
if errcode <> grok then begin
writeln ('Graphics error: ',grapherrormsg (errcode));
halt (1);
end;
end;
function rnd: double; { this isn't the best, but it works }
var { returns a random number between 0 and 1 }
i: integer;
r: double;
begin
r:= 0;
for i:= 1 to 15 do begin
r:= r + random(10);
r:= r/10;
end;
rnd:= r;
end;
function gaussian(a,d: double): double; { a is mean }
const { d is standard deviation }
t: double = 0; { pascal's equivalent to C's static variable }
var
x,v1,v2,r: double;
begin
if t=0 then begin
repeat
v1:= 2*rnd-1;
v2:= 2*rnd-1;
r:= v1*v1+v2*v2
until r<1;
r:= sqrt((-2*ln(r))/r);
t:= v2*r;
gaussian:= a+v1*r*d;
end
else begin
x:= t;
t:= 0;
gaussian:= a+x*d;
end;
end;
procedure testplot;
var
x,mx,my,y1: word;
y: array[1..999] of word;
{ ^^^ make this bigger if you have incredible graphics }
begin
initbgi;
mx:= getmaxx+1;
my:= getmaxy;
fillchar(y,sizeof(y),#0);
repeat
x:= trunc(gaussian(mx/2,50));
y1:= y[x];
putpixel(x,my-y1,white);
y[x]:= y1+1;
until keypressed;
closegraph;
end;
begin
randomize;
testplot;
end.
|
unit Ils.Utils.Debug;
interface
uses
SysUtils, Registry, PsAPI, TlHelp32, Windows, TypInfo, StrUtils;
type
TEnumConverter = class
public
class function EnumToInt<T>(const EnumValue: T): Integer;
class function EnumToString<T>(EnumValue: T): string;
class function StringToEnum<T>(strValue: String): T;
end;
function IsAppRunning(const AFileName: string): boolean;
function GetDelphiXE2LocationExeName: string;
procedure SleepIfIdeRunning(milliseconds: Integer);
function MemoryUsed: Int64;
function MemoryUsedDelphi: Int64;
function MemoryUsedWindows: Int64;
function FormatMemoryUsed(const AMessage: string): string;
implementation
procedure SleepIfIdeRunning(milliseconds: Integer);
begin
// if DebugHook <> 0 then
if IsAppRunning('bds.exe') then
Sleep(milliseconds);
end;
function ProcessFileName(dwProcessId: DWORD): string;
var
hModule: Cardinal;
begin
Result := '';
hModule := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, dwProcessId);
if hModule <> 0 then
try
SetLength(Result, MAX_PATH);
if GetModuleFileNameEx(hModule, 0, PChar(Result), MAX_PATH) > 0 then
SetLength(Result, StrLen(PChar(Result)))
else
Result := '';
finally
CloseHandle(hModule);
end;
end;
function IsAppRunning(const AFileName: string): boolean;
var
hSnapshot : Cardinal;
EntryParentProc: TProcessEntry32;
begin
Result := False;
hSnapshot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if hSnapshot = INVALID_HANDLE_VALUE then
exit;
try
EntryParentProc.dwSize := SizeOf(EntryParentProc);
if Process32First(hSnapshot, EntryParentProc) then
repeat
if CompareText(ExtractFileName(AFileName), EntryParentProc.szExeFile) = 0 then
// if CompareText(ProcessFileName(EntryParentProc.th32ProcessID), AFileName) = 0 then
begin
Result := True;
break;
end;
until not Process32Next(hSnapshot, EntryParentProc);
finally
CloseHandle(hSnapshot);
end;
end;
function RegReadStr(const RegPath, RegValue: string; var Str: string;
const RootKey: HKEY): boolean;
var
Reg: TRegistry;
begin
try
Reg := TRegistry.Create;
try
Reg.RootKey := RootKey;
Result := Reg.OpenKey(RegPath, True);
if Result then
Str := Reg.ReadString(RegValue);
finally
Reg.Free;
end;
except
Result := False;
end;
end;
function RegKeyExists(const RegPath: string; const RootKey: HKEY): boolean;
var
Reg: TRegistry;
begin
try
Reg := TRegistry.Create;
try
Reg.RootKey := RootKey;
Result := Reg.KeyExists(RegPath);
finally
Reg.Free;
end;
except
Result := False;
end;
end;
function GetDelphiXE2LocationExeName: string;
const
Key = '\Software\Embarcadero\BDS\9.0';
begin
Result:='';
if RegKeyExists(Key, HKEY_CURRENT_USER) then
begin
RegReadStr(Key, 'App', Result, HKEY_CURRENT_USER);
exit;
end;
if RegKeyExists(Key, HKEY_LOCAL_MACHINE) then
RegReadStr(Key, 'App', Result, HKEY_LOCAL_MACHINE);
end;
{
example app:
Var
Bds : String;
begin
try
Bds:=GetDelphiXE2LocationExeName;
if Bds<>'' then
begin
if IsAppRunning(Bds) then
Writeln('The Delphi XE2 IDE Is running')
else
Writeln('The Delphi XE2 IDE Is not running')
end
else
Writeln('The Delphi XE2 IDE Is was not found');
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.
}
function MemoryUsed: Int64;
begin
//{$ifdef FASTMM4}
Result := MemoryUsedWindows;
//{$else}
// Result := MemoryUsedDelphi;
//{$endif}
end;
function MemoryUsedDelphi: Int64;
var
st: TMemoryManagerState;
sb: TSmallBlockTypeState;
begin
GetMemoryManagerState(st);
Result :=
st.TotalAllocatedMediumBlockSize * st.AllocatedMediumBlockCount +
st.TotalAllocatedLargeBlockSize * st.AllocatedLargeBlockCount;
for sb in st.SmallBlockTypeStates do
Result := Result + sb.UseableBlockSize * sb.AllocatedBlockCount;
end;
function MemoryUsedWindows: Int64;
var
mc: TProcessMemoryCounters;
sz: Integer;
begin
Result := 0;
sz := SizeOf(mc);
FillChar(mc, sz, 0);
if GetProcessMemoryInfo(GetCurrentProcess, @mc, sz) then
// Result := mc.PageFileUsage;
Result := mc.WorkingSetSize;
end;
function FormatMemoryUsed(const AMessage: string): string;
var
fs: TFormatSettings;
mu: Double;
begin
fs := TFormatSettings.Create;
fs.ThousandSeparator := '''';
mu := MemoryUsed;// ProcessMemoryUsed;
Result := Format('%.0n', [mu], fs) + IfThen(AMessage<>'', ' ', '') + AMessage;
end;
class function TEnumConverter.EnumToInt<T>(const EnumValue: T): Integer;
begin
Result := 0;
Move(EnumValue, Result, sizeOf(EnumValue));
end;
class function TEnumConverter.EnumToString<T>(EnumValue: T): string;
begin
Result := GetEnumName(TypeInfo(T), EnumToInt(EnumValue));
end;
class function TEnumConverter.StringToEnum<T>(strValue: String): T;
var
TypInfo : PTypeInfo;
Temp: Integer;
PTemp : Pointer;
begin
TypInfo := TypeInfo(T);
Temp := GetEnumValue(TypInfo, strValue);
PTemp := @Temp;
Result := T(PTemp^);
end;
end.
|
Function Rat(OQue: String; Onde: String) : Integer;
//
// Procura uma string dentro de outra, da direita para esquerda
//
// Retorna a posição onde foi encontrada ou 0 caso não seja encontrada
//
var
Pos : Integer;
Tam1 : Integer;
Tam2 : Integer;
Achou : Boolean;
begin
Tam1 := Length(OQue);
Tam2 := Length(Onde);
Pos := Tam2-Tam1+1;
Achou := False;
while (Pos >= 1) and not Achou do
begin
if Copy(Onde, Pos, Tam1) = OQue then
begin
Achou := True
end
else
begin
Pos := Pos - 1;
end;
end;
Result := Pos;
end;
|
unit FunctionManager;
interface
uses ShellAPI, Windows, CurrentDateDisplay, System.Classes, SysUtils;
type
TFunctionManager = class
public
procedure OpenNotePad();
procedure SpawnDateWindow();
procedure GenerateAddRandomNumbers(numbersToGenerate: string; numberStringList: TStrings);
end;
implementation
procedure TFunctionManager.GenerateAddRandomNumbers(numbersToGenerate: string; numberStringList: TStrings);
var
idx: integer;
numberCount: integer;
randomizedNumber: integer;
begin
numberCount := StrToInt(numbersToGenerate);
randomize();
for idx := 0 to numberCount do
begin
randomizedNumber := random(1000)+1;
numberStringList.Add(IntToStr(randomizedNumber));
end;
end;
procedure TFunctionManager.OpenNotePad;
begin
ShellExecute(0, 'open', 'notepad.exe', nil, nil, SW_SHOW)
end;
procedure TFunctionManager.SpawnDateWindow;
begin
formCurrentDateDisplay.Show();
end;
end.
|
UNIT UPointeurs;
INTERFACE
USES UStructures,UEquipes;
FUNCTION creerNoeud(e:equipe):ptrNoeud;
FUNCTION longueur (tete : ptrNoeud): INTEGER;
PROCEDURE afficherListe (tete : ptrNoeud);
FUNCTION parcourirListe (n : INTEGER ;tete : ptrNoeud): ptrNoeud;
PROCEDURE ajouterDebut (equ : equipe ; VAR tete : ptrNoeud);
PROCEDURE supprimerDebut(VAR tete : ptrNoeud);
PROCEDURE supprimerFin(VAR tete : ptrNoeud);
FUNCTION supprimerListe(VAR tete : ptrNoeud):ptrNoeud;
IMPLEMENTATION
FUNCTION creerNoeud(e:equipe):ptrNoeud;
VAR nv: ptrNoeud;
BEGIN
new(nv);
nv^.eq.nom := e.nom;
nv^.eq.rg := e.rg;
nv^.eq.grp := e.grp;
nv^.eq.pays := e.pays;
nv^.suivant := Nil;
creerNoeud := nv;
END;
PROCEDURE afficherListe (tete : ptrNoeud);
VAR tmp : ptrNoeud;
i : INTEGER;
BEGIN
IF tete = Nil THEN writeln('Liste vide')
ELSE BEGIN
i := 1;
tmp := tete;
WHILE (tmp <> Nil) DO BEGIN
writeln('element ', i,': ',tmp^.eq.nom);
tmp := tmp^.suivant;
Inc(i);
END;
writeln;
END;
END;
FUNCTION longueur (tete : ptrNoeud): INTEGER;
VAR n : INTEGER;
tmp : ptrNoeud;
BEGIN
n := 0;
tmp := tete;
WHILE (tmp <> Nil) DO BEGIN
Inc(n);
tmp := tmp^.suivant;
END;
longueur := n;
END;
//renvoi le nieme element de la liste
FUNCTION parcourirListe (n : INTEGER ;tete : ptrNoeud): ptrNoeud;
VAR tmp : ptrNoeud;
BEGIN
tmp := tete;
WHILE (tmp <> nil) AND (n > 1) DO BEGIN
tmp := tmp^.suivant;
Dec(n);
END;
parcourirListe := tmp;
END;
PROCEDURE ajouterDebut (equ : equipe ; VAR tete : ptrNoeud); // besoin de l'addresse du premier élément
VAR nd : ptrNoeud;
BEGIN
nd := creerNoeud(equ);
nd^.suivant := tete;
tete := nd;
END;
PROCEDURE supprimerDebut(VAR tete : ptrNoeud);
VAR ptr_supp : ptrNoeud;
BEGIN
IF tete^.suivant = Nil THEN BEGIN
dispose(tete);
tete:= NIL;
END
ELSE
ptr_supp := tete;
tete := ptr_supp^.suivant;
dispose(ptr_supp);
END;
PROCEDURE supprimerFin(VAR tete : ptrNoeud);
VAR tmp:ptrNoeud;
ptr_supp : ptrNoeud;
BEGIN
IF tete = Nil THEN BEGIN
dispose(tete);
tete:= NIL;
END
ELSE BEGIN
tmp := tete;
WHILE (tmp^.suivant^.suivant <> Nil) DO
tmp := tmp^.suivant;
ptr_supp := tmp^.suivant;
tmp^.suivant := Nil;
dispose(ptr_supp);
END;
END;
//problème rencontré : les éléments des deux listes ont les même adresses donc en supprimant une liste on perd l'autre
FUNCTION supprimerListe(VAR tete : ptrNoeud):ptrNoeud;
VAR ptr_supp : ptrNoeud;
BEGIN
IF tete = Nil THEN supprimerListe := Nil
ELSE BEGIN
IF tete^.suivant = Nil THEN BEGIN //si liste à un élément
ptr_supp := tete;
tete := ptr_supp^.suivant;
dispose(ptr_supp);
END
ELSE BEGIN // liste à plus de 1 élément donc boucle de suppression
WHILE (tete <> Nil) DO BEGIN
writeln('enter');
ptr_supp := tete;
tete := ptr_supp^.suivant;
dispose(ptr_supp);
END;
END;
supprimerListe:= Nil;
END;
END;
END.
|
unit uFrmApplyItemTax;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, PaideTodosGeral, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls,
Mask, SuperComboADO, ADODB, DB;
type
TFrmApplyItemTax = class(TFrmParentAll)
btnApply: TButton;
Label29: TLabel;
scSaleTax: TSuperComboADO;
cmdApplyItemTax: TADOCommand;
cmdApplyHoldTax: TADOCommand;
spUpdateTotal: TADOStoredProc;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btCloseClick(Sender: TObject);
procedure btnApplyClick(Sender: TObject);
private
FIDPreSale : Integer;
FIDPreInvMov : Integer;
FApplied : Boolean;
procedure UpdateItemTax;
procedure UpdateHoldTax;
procedure CalcTotal;
public
function Start(IDPreSale, IDPreInvMov : Integer):Boolean;
end;
implementation
uses uDM;
{$R *.dfm}
procedure TFrmApplyItemTax.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
function TFrmApplyItemTax.Start(IDPreSale, IDPreInvMov: Integer): Boolean;
begin
FIDPreSale := IDPreSale;
FIDPreInvMov := IDPreInvMov;
FApplied := False;
ShowModal;
Result := FApplied;
end;
procedure TFrmApplyItemTax.btCloseClick(Sender: TObject);
begin
inherited;
FApplied := False;
Close;
end;
procedure TFrmApplyItemTax.btnApplyClick(Sender: TObject);
begin
inherited;
if FIDPreInvMov <> -1 then
UpdateItemTax
else
UpdateHoldTax;
CalcTotal;
FApplied := True;
Close;
end;
procedure TFrmApplyItemTax.UpdateItemTax;
begin
with cmdApplyItemTax do
begin
if scSaleTax.LookUpValue <> '' then
Parameters.ParamByName('TaxID').Value := StrToInt(scSaleTax.LookUpValue)
else
Parameters.ParamByName('TaxID').Value := Null;
Parameters.ParamByName('IDPreInventoryMov').Value := FIDPreInvMov;
Execute;
end;
end;
procedure TFrmApplyItemTax.UpdateHoldTax;
begin
with cmdApplyHoldTax do
begin
if scSaleTax.LookUpValue <> '' then
Parameters.ParamByName('IDTax').Value := StrToInt(scSaleTax.LookUpValue)
else
Parameters.ParamByName('IDTax').Value := Null;
Parameters.ParamByName('IDPreSale').Value := FIDPreSale;
Execute;
end;
end;
procedure TFrmApplyItemTax.CalcTotal;
begin
with spUpdateTotal do
begin
Parameters.ParamByName('@Date').Value := Now;
Parameters.ParamByName('@PreSaleID').Value := FIDPreSale;
ExecProc;
end;
end;
end.
|
unit EditTuning;
interface
uses vcl.StdCtrls, vcl.Graphics, vcl.ExtCtrls, Vcl.Controls, vcl.Mask;
type
TEdit = class(vcl.StdCtrls.TEdit)
private
FOldColor: TColor;
protected
procedure DoEnter; override; { Estamos reescrevendo o método DoEnter, para adaptar de acordo com a nossa necessidade}
procedure DoExit; override; { Estamos reescrevendo o método DoExit, para adaptar de acordo com a nossa necessidade}
public
procedure AfterConstruction; override;
Published
// property Color default clGradientInactiveCaption ;
end;
type
TButtonedEdit = class(vcl.ExtCtrls.TButtonedEdit)
private
FOldColor: TColor;
protected
procedure DoEnter; override; { Estamos reescrevendo o método DoEnter, para adaptar de acordo com a nossa necessidade}
procedure DoExit; override; { Estamos reescrevendo o método DoExit, para adaptar de acordo com a nossa necessidade}
public
procedure AfterConstruction; override;
end;
type
TMaskEdit = class(vcl.Mask.TMaskEdit)
private
FOldColor: TColor;
protected
procedure DoEnter; override; { Estamos reescrevendo o método DoEnter, para adaptar de acordo com a nossa necessidade}
procedure DoExit; override; { Estamos reescrevendo o método DoExit, para adaptar de acordo com a nossa necessidade}
public
procedure AfterConstruction; override;
end;
implementation
uses Un_Funcoes;
{ TEdit }
const
COLOR_CONS = $00DFFFFF;
COLOR_GETS = clGradientInactiveCaption;
COLOR_FONT = clBlack;
procedure TEdit.DoEnter;
begin
inherited;
{ Observe a variável/field FOldColor, onde ela guarda a cor anterior }
FOldColor := COLOR_CONS;
{ Observe neste ponto dizemos que a cor ao entrar no Edit será clYellow }
Color := COLOR_GETS;
Font.Color := COLOR_FONT;
end;
procedure TEdit.DoExit;
begin
inherited;
{ Observe a cor agora irá receber o conteúdo da variável/field FOldColor }
Color := COLOR_CONS;
Font.Color := COLOR_FONT;
end;
procedure TEdit.AfterConstruction;
begin
inherited;
Self.Color := COLOR_CONS;
Self.Font.Color := COLOR_FONT;
end;
// Metodos do ButtonEdit
procedure TButtonedEdit.DoEnter;
begin
inherited;
{ Observe a variável/field FOldColor, onde ela guarda a cor anterior }
FOldColor := COLOR_CONS;
{ Observe neste ponto dizemos que a cor ao entrar no Edit será clYellow }
Color := COLOR_GETS;
Font.Color := COLOR_FONT;
end;
procedure TButtonedEdit.DoExit;
begin
inherited;
{ Observe a cor agora irá receber o conteúdo da variável/field FOldColor }
Color := COLOR_CONS;
Font.Color := COLOR_FONT;
end;
procedure TButtonedEdit.AfterConstruction;
begin
inherited;
Self.Color := COLOR_CONS;
Self.Font.Color := COLOR_FONT;
end;
// Metodos do TMaskEditt
procedure TMaskEdit.DoEnter;
begin
inherited;
{ Observe a variável/field FOldColor, onde ela guarda a cor anterior }
FOldColor := COLOR_CONS;
{ Observe neste ponto dizemos que a cor ao entrar no Edit será clYellow }
Color := COLOR_GETS;
Font.Color := COLOR_FONT;
end;
procedure TMaskEdit.DoExit;
begin
inherited;
{ Observe a cor agora irá receber o conteúdo da variável/field FOldColor }
Color := COLOR_CONS;
Font.Color := COLOR_FONT;
end;
procedure TMaskEdit.AfterConstruction;
begin
inherited;
Self.Color := COLOR_CONS;
Self.Font.Color := COLOR_FONT;
end;
end.
|
unit srvDaftarU;
interface
uses Dialogs, Classes, srvCommonsU, System.SysUtils, System.StrUtils;
type
srvDaftar = class(srvCommon)
private
// function jsonToSql(table : string = 'simpus.m_instalasi'; json : string = ''; update : Boolean = False; pkey : string = '') : string;
function ambilJsonDaftarGagalFcmPost(puskesmas : integer; tanggal : TDateTime) : string;
function ambilJsonDaftarAndroPost(puskesmas : integer; tanggal : TDateTime) : string;
function ambilJsonDaftarPost(puskesmas : Integer; tanggal : TDate) : string;
function ambilJsonDaftarFcmPost(id : string) : string;
function ambilJsonDaftarTopikFcmPost(id : string) : string;
procedure masukkanGetDaftarAndro(puskesmas : integer; tanggal : TDateTime);
procedure masukkanPostDaftar(idxstr : string);
procedure masukkanPostDaftarAndro(id : string);
procedure masukkanPostDaftarFcm(id : string);
procedure masukkanPostDaftarGagalFcm(id : string);
public
aScript : TStringList;
constructor Create;
destructor destroy;
function getDaftarAndro(puskesmas : integer; tanggal : TDateTime) : Boolean;
function postDaftar(puskesmas: Integer; tanggal : TDate) : Boolean;
function postDaftarAndro(puskesmas : Integer; tanggal : TDateTime) : Boolean;
function postDaftarFcm(id : string; logOnly : Boolean) : Boolean;
function postDaftarGagalFcm(puskesmas : integer; tanggal : TDateTime; logOnly : Boolean) : Boolean;
// property Uri : string;
end;
implementation
uses SynCommons, mORMot, synautil;
{ srvDaftarAndro }
function srvDaftar.ambilJsonDaftarFcmPost(id: string): string;
var sql0, sql1, tanggalStr : string;
V1 : Variant;
begin
parameter_bridging('daftar fcm', 'post');
V1 := _Json(FormatJson);
Result := '';
sql0 := 'select * from andro.daftar_fcm_view where id = %s and token is not null and fcm = false;';
sql1 := Format(sql0, [QuotedStr(id)]);
fdQuery.Close;
fdQuery.SQL.Clear;
fdQuery.SQL.Add(sql1);
fdQuery.Active := true;
if not fdQuery.IsEmpty then
begin
// DateTimeToString(tanggalStr, 'yyyy-MM-dd', fdQuery.FieldByName('tanggal').AsDateTime);
//ShowMessage(VariantSaveJSON(V1));
V1.id := id;
V1.rm := fdQuery.FieldByName('rm').AsString;
V1.poli := fdQuery.FieldByName('poli').AsString;
V1.nomor := fdQuery.FieldByName('nomor').AsInteger;
V1.token := fdQuery.FieldByName('token').AsString;
fdQuery.Close;
Result := VariantSaveJSON(V1);
end else fdQuery.Close;
end;
function srvDaftar.ambilJsonDaftarGagalFcmPost(puskesmas : integer; tanggal : TDateTime): string;
var sql0, sql1, tanggalStr : string;
V0, V1, V2 : Variant;
begin
DateTimeToString(tanggalStr, 'YYYY-MM-DD', tanggal);
parameter_bridging('daftar fcm gagal', 'post');
V0 := _Arr([]);
V2 := _Json(FormatJson);
Result := '';
sql0 := 'select * from andro.daftar_andro where puskesmas = %s and tanggal = %s and fcm = false and length(alasan) > 5;';
sql1 := Format(sql0, [IntToStr(puskesmas), QuotedStr(tanggalStr)]);
fdQuery.Close;
fdQuery.SQL.Clear;
fdQuery.SQL.Add(sql1);
fdQuery.Active := true;
if not fdQuery.IsEmpty then
begin
fdQuery.First;
while not fdQuery.Eof do
begin
VarClear(V1);
V1 := V2;
V1.id := fdQuery.FieldByName('id').AsString;;
V1.rm := fdQuery.FieldByName('rm').AsString;
V1.poli := fdQuery.FieldByName('poli').AsString;
V1.token := fdQuery.FieldByName('token').AsString;
V1.nomor := 0;
V1.alasan := fdQuery.FieldByName('alasan').AsString;
V0.add(V1);
fdQuery.Next;
end;
//ShowMessage(VariantSaveJSON(V1));
fdQuery.Close;
Result := VariantSaveJSON(V0);
end else fdQuery.Close;
end;
function srvDaftar.ambilJsonDaftarPost(puskesmas : Integer; tanggal: TDate): string;
var sql0, sql1, tanggalStr : string;
V0,V1, V2 : Variant;
begin
DateTimeToString(tanggalStr, 'yyyy-MM-dd', tanggal);
parameter_bridging('daftar', 'post');
V0 := _Arr([]);
V2 := _Json(FormatJson);
Result := '';
sql0 := 'select * from simpus.daftar where puskesmas = %s and tanggal = %s and dari_server is null;';
sql1 := Format(sql0, [intToStr(puskesmas), QuotedStr(tanggalStr)]);
fdQuery.Close;
fdQuery.SQL.Clear;
fdQuery.SQL.Add(sql1);
fdQuery.Active := true;
//ShowMessage('tes');
if not fdQuery.IsEmpty then
begin
// ShowMessage(VariantSaveJSON(V2));
fdQuery.First;
while not fdQuery.Eof do
begin
VarClear(V1);
V1 := V2;
V1.idxstr := fdQuery.FieldByName('idxstr').AsString;
V1.puskesmas := fdQuery.FieldByName('puskesmas').AsInteger;
V1.tanggal := tanggalStr;
V1.nomor := fdQuery.FieldByName('nomor').AsInteger;
V1.antri := fdQuery.FieldByName('antri').AsInteger;
V1.poliTujuan := fdQuery.FieldByName('poli_tujuan').AsString;
if not fdQuery.FieldByName('andro').IsNull then
V1.andro := fdQuery.FieldByName('andro').AsString;
{
if not fdQuery.FieldByName('token').IsNull then
V1.token := fdQuery.FieldByName('token').AsString;
}
if not fdQuery.FieldByName('dari_server').IsNull then
V1.dariServer := fdQuery.FieldByName('dari_server').AsString;
V0.Add(V1);
fdQuery.Next;
end;
fdQuery.Close;
Result := VariantSaveJSON(V0);
end else fdQuery.Close;
end;
function srvDaftar.ambilJsonDaftarTopikFcmPost(id: string): string;
begin
end;
function srvDaftar.ambilJsonDaftarAndroPost(puskesmas : integer; tanggal : TDateTime): string;
var sql0, sql1, tanggalStr : string;
V2, V1, V0 : Variant;
begin
DateTimeToString(tanggalStr, 'yyyy-MM-dd', tanggal);
parameter_bridging('daftar andro', 'post');
V0 := _Arr([]);
V2 := _Json(FormatJson);
Result := '';
sql0 := 'select * from andro.daftar_andro where puskesmas = %s and tanggal = %s and dari_server is null;';
sql1 := Format(sql0, [IntToStr(puskesmas), QuotedStr(tanggalStr)]);
fdQuery.Close;
fdQuery.SQL.Clear;
fdQuery.SQL.Add(sql1);
fdQuery.Active := true;
if not fdQuery.IsEmpty then
begin
fdQuery.First;
while not fdQuery.Eof do
begin
VarClear(V1);
V1 := V2;
V1.id := fdQuery.FieldByName('id').AsString;
V1.puskesmas := fdQuery.FieldByName('puskesmas').AsInteger;
V1.tanggal := tanggalStr;
V1.idx := fdQuery.FieldByName('idx').AsInteger;
V1.diambil := 1;
V1.rm := fdQuery.FieldByName('rm').AsString;
V1.biaya := fdQuery.FieldByName('biaya').AsString;
V1.poli := fdQuery.FieldByName('poli').AsString;
if not fdQuery.FieldByName('token').IsNull then
V1.token := fdQuery.FieldByName('token').AsString;
if not fdQuery.FieldByName('alasan').IsNull then
V1.alasan := fdQuery.FieldByName('alasan').AsString;
if not fdQuery.FieldByName('idxstr').IsNull then
V1.idxstr := fdQuery.FieldByName('idxstr').AsString;
V0.Add(V1);
fdQuery.Next;
end;
fdQuery.Close;
Result := VariantSaveJSON(V0);
end else fdQuery.Close;
end;
constructor srvDaftar.Create;
begin
inherited Create;
aScript := TStringList.Create;
end;
destructor srvDaftar.destroy;
begin
aScript.Free;
inherited;
end;
function srvDaftar.getDaftarAndro(puskesmas : integer; tanggal : TDateTime): Boolean;
var sql0, sql1, strTgl : string;
begin
parameter_bridging('daftar andro', 'get');
DateTimeToString(strTgl, 'YYYY-MM-DD', tanggal);
Result := False;
//ShowMessage(uri);
Uri := ReplaceStr(Uri, '{puskesmas}', IntToStr(puskesmas));
Uri := ReplaceStr(Uri, '{tanggal}', strTgl);
//ShowMessage(uri);
Result:= httpGet(uri);
if Result then masukkanGetDaftarAndro(puskesmas, tanggal);
FDConn.Close;
end;
procedure srvDaftar.masukkanGetDaftarAndro(puskesmas : integer; tanggal : TDateTime);
var dataResp, dataList : Variant;
i : Integer;
tSl : TStringList;
sqlx0, sqlx1 : string;
sql0, sql1 : string;
dId, dRm, dBiaya, dPoli, dToken, strTgl : string;
dIdx : Integer;
adlAktif : Boolean;
begin
// ShowMessage('awal masukkan get');
sql0 := 'insert into andro.daftar_andro(id, puskesmas, tanggal, idx, rm, biaya, poli, token) ' +
'values(%s, %s, %s, %s, %s, %s, %s, %s) on conflict (id) do nothing;';
tsL := TStringList.Create;
DateTimeToString(strTgl, 'YYYY-MM-DD', tanggal);
// ShowMessage(tsResponse.Text);
dataResp := _jsonFast(tsResponse.Text);
if dataResp._count > 0 then
begin
try
for I := 0 to dataResp._count - 1 do
begin
dId := dataResp.Value(i).id;
// ShowMessage('id : ' + dId);
dIdx := dataResp.Value(i).idx;
// ShowMessage('nik : ' + dNik);
dRm := dataResp.Value(i).rm;
dBiaya := dataResp.Value(i).biaya;
dPoli := dataResp.Value(i).poli;
dToken := dataResp.Value(i).token;
// ShowMessage('token : ' + dToken);
sql1 := Format(sql0, [
QuotedStr(dId),
IntToStr(puskesmas),
QuotedStr(strTgl),
IntTostr(dIdx),
QuotedStr(dRm),
QuotedStr(dBiaya),
QuotedStr(dPoli),
QuotedStr(dToken)
]);
tSl.Add(sql1);
// showMessage(sqlDel1);
// showMessage(sql1);
end;
finally
aScript.Assign(tSl);
jalankanScript(tSl);
FreeAndNil(tSl);
end;
end;
end;
procedure srvDaftar.masukkanPostDaftar(idxstr: string);
var
V1 : Variant;
dariServer : string;
sql0, sql1 : string;
tSL : TStringList;
begin
//ShowMessage(tsResponse.Text);
V1 := _Json(tsResponse.Text);
dariServer := V1.dariServer;
sql0 := 'update simpus.daftar set dari_server = %s where idxstr = %s;';
sql1 := Format(sql0,[
QuotedStr(dariServer),
QuotedStr(idxstr)
]);
tSL := TStringList.Create;
try
tSL.Add(sql1);
jalankanScript(tSL);
finally
tSL.Free;
end;
end;
procedure srvDaftar.masukkanPostDaftarAndro(id: string);
var
V1 : Variant;
dariServer : string;
sql0, sql1 : string;
tSL : TStringList;
begin
//ShowMessage(tsResponse.Text);
V1 := _Json(tsResponse.Text);
dariServer := V1.dariServer;
sql0 := 'update andro.daftar_andro set diambil = 1 and dari_server = %s where id = %s;';
sql1 := Format(sql0,[
QuotedStr(dariServer),
QuotedStr(id)
]);
tSL := TStringList.Create;
try
tSL.Add(sql1);
jalankanScript(tSL);
finally
tSL.Free;
end;
end;
procedure srvDaftar.masukkanPostDaftarFcm(id: string);
var
V1 : Variant;
dariServer : string;
sql0, sql1 : string;
tSL : TStringList;
begin
//ShowMessage(tsResponse.Text);
// V1 := _Json(tsResponse.Text);
sql0 := 'update andro.daftar_andro set fcm = true where id = %s;';
sql1 := Format(sql0,[
QuotedStr(id)
]);
tSL := TStringList.Create;
try
tSL.Add(sql1);
jalankanScript(tSL);
finally
tSL.Free;
end;
end;
procedure srvDaftar.masukkanPostDaftarGagalFcm(id : string);
var
V1 : Variant;
dariServer : string;
sql0, sql1 : string;
tSL : TStringList;
begin
//ShowMessage(tsResponse.Text);
// V1 := _Json(tsResponse.Text);
sql0 := 'update andro.daftar_andro set fcm = true where id = %s;';
sql1 := Format(sql0,[
QuotedStr(id)
]);
tSL := TStringList.Create;
try
tSL.Add(sql1);
jalankanScript(tSL);
finally
tSL.Free;
end;
end;
function srvDaftar.postDaftar(puskesmas : Integer; tanggal : TDate): Boolean;
var
mStream : TMemoryStream;
js, jsX, idxstr, Uri0 : string;
V0, V1 : Variant;
i : Integer;
begin
Result := False;
js := ambilJsonDaftarPost(puskesmas, tanggal);
if Length(js) > 20 then
begin
V0 := _Json(js);
if V0._count > 0 then
begin
for I := 0 to V0._count - 1 do
begin
Result := False;
VarClear(V1);
V1 := V0.Value(i);
_Unique(V1);
idxstr := V1.idxstr;
Uri0 := ReplaceStr(Uri, '{idxsr}', idxstr);
//V1.token := Uri0;
jsX := VariantSaveJSON(V1);
mStream := TMemoryStream.Create;
WriteStrToStream(mStream, jsX);
Result:= httpPost(Uri0, mStream);
// FileFromString(jsX, 'jsX' + IntToStr(i) + '.json');
mStream.Free;
if Result then jika_berhasil('simpus.daftar', idxstr) else
jika_gagal('post', Uri0, jsX, 'simpus.daftar', idxstr);
if Result then masukkanPostDaftar(idxstr);
end;
end;
end;
FDConn.Close;
end;
function srvDaftar.postDaftarAndro(puskesmas : Integer; tanggal : TDateTime): Boolean;
var
mStream : TMemoryStream;
V1, V2 : Variant;
js, jsX, id, Uri0 : string;
i : Integer;
begin
Result := False;
js := ambilJsonDaftarAndroPost(puskesmas, tanggal);
if Length(js) > 10 then
begin
V1 := _Json(js);
if V1._count > 0 then
begin
for I := 0 to V1._count - 1 do
begin
Result := False;
VarClear(V2);
V2 := V1.Value(i);
_Unique(V2);
id := V2.id;
Uri0 := ReplaceStr(Uri, '{id}', id);
jsX := VariantSaveJSON(V2);
mStream := TMemoryStream.Create;
WriteStrToStream(mStream, jsX);
Result:= httpPost(Uri0, mStream);
mStream.Free;
//FileFromString(jsX, 'jsX' + IntToStr(i)+'.json');
if Result then jika_berhasil('andro.daftar_andro', id) else
jika_gagal('post', Uri, js, 'andro.daftar_andro', id);
if Result then masukkanPostDaftarAndro(id);
end;
end;
end;
FDConn.Close;
end;
function srvDaftar.postDaftarFcm(id: string; logOnly : Boolean): Boolean;
var
mStream : TMemoryStream;
js : string;
begin
Result := False;
js := ambilJsonDaftarFcmPost(id);
if Length(js) > 10 then
begin
mStream := TMemoryStream.Create;
WriteStrToStream(mStream, js);
//Uri := ReplaceStr(Uri, '{id}', id);
if not logOnly then Result:= httpPost(Uri, mStream);
FormatJson := js;
mStream.Free;
if Result then jika_berhasil('andro.daftar_fcm_view', id) else
jika_gagal('post', Uri, js, 'andro.daftar_fcm_view', id);
if Result then masukkanPostDaftarFcm(id);
end;
FDConn.Close;
end;
function srvDaftar.postDaftarGagalFcm(puskesmas : integer; tanggal : TDateTime; logOnly: Boolean): Boolean;
var
mStream : TMemoryStream;
js, jsX, id : string;
V0, V1 : Variant;
I: Integer;
begin
Result := False;
js := ambilJsonDaftarGagalFcmPost(puskesmas, tanggal);
if Length(js) > 10 then
begin
V0 := _Json(js);
if V0._count > 0 then
begin
for I := 0 to V0._count - 1 do
begin
Result := False;
VarClear(V1);
V1 := V0.Value(i);
_Unique(V1);
id := V1.id;
jsX := VariantSaveJSON(V1);
mStream := TMemoryStream.Create;
WriteStrToStream(mStream, jsX);
//Uri := ReplaceStr(Uri, '{id}', id);
if not logOnly then Result:= httpPost(Uri, mStream);
FormatJson := jsX;
FileFromString(FormatJson, 'jsX'+ IntToStr(i)+ '.json');
mStream.Free;
if Result then jika_berhasil('andro.daftar_andro', id) else
jika_gagal('post', Uri, jsX, 'andro.daftar_andro', id);
if Result then masukkanPostDaftarGagalFcm(id);
end;
end;
end;
FDConn.Close;
end;
end.
|
unit UDPFCValues;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, UCrpe32;
type
TCrpePFCurrentValuesDlg = class(TForm)
pnlValues: TPanel;
lblText: TLabel;
editText: TEdit;
lbNumbers: TListBox;
lblNumber: TLabel;
btnOk: TButton;
btnAdd: TButton;
btnDelete: TButton;
lblCount: TLabel;
editCount: TEdit;
btnClear: TButton;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnOkClick(Sender: TObject);
procedure UpdateCurrentValues;
procedure lbNumbersClick(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure InitializeControls(OnOff: boolean);
procedure editTextExit(Sender: TObject);
procedure btnClearClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Crv : TCrpeParamFieldCurrentValues;
CVIndex : integer;
end;
var
CrpePFCurrentValuesDlg: TCrpePFCurrentValuesDlg;
implementation
{$R *.DFM}
uses UCrpeUtl;
{------------------------------------------------------------------------------}
{ FormCreate procedure }
{------------------------------------------------------------------------------}
procedure TCrpePFCurrentValuesDlg.FormCreate(Sender: TObject);
begin
LoadFormPos(Self);
btnOk.Tag := 1;
CVIndex := -1;
end;
{------------------------------------------------------------------------------}
{ FormShow procedure }
{------------------------------------------------------------------------------}
procedure TCrpePFCurrentValuesDlg.FormShow(Sender: TObject);
begin
UpdateCurrentValues;
end;
{------------------------------------------------------------------------------}
{ UpdateCurrentValues procedure }
{------------------------------------------------------------------------------}
procedure TCrpePFCurrentValuesDlg.UpdateCurrentValues;
var
OnOff : boolean;
i : integer;
begin
CVIndex := -1;
{Enable/Disable controls}
if IsStrEmpty(Crv.Cr.ReportName) then
begin
OnOff := False;
btnAdd.Enabled := False;
end
else
begin
OnOff := (Crv.Count > 0);
btnAdd.Enabled := True;
{Get CurrentValues Index}
if OnOff then
begin
if Crv.ItemIndex > -1 then
CVIndex := Crv.ItemIndex
else
CVIndex := 0;
end;
end;
InitializeControls(OnOff);
{Update list box}
if OnOff then
begin
{Fill Numbers ListBox}
lbNumbers.Clear;
for i := 0 to Crv.Count - 1 do
lbNumbers.Items.Add(IntToStr(i));
editCount.Text := IntToStr(Crv.Count);
lbNumbers.ItemIndex := CVIndex;
lbNumbersClick(self);
end;
end;
{------------------------------------------------------------------------------}
{ InitializeControls }
{------------------------------------------------------------------------------}
procedure TCrpePFCurrentValuesDlg.InitializeControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
if TComponent(Components[i]).Tag = 0 then
begin
if Components[i] is TButton then
TButton(Components[i]).Enabled := OnOff;
if Components[i] is TListBox then
begin
TListBox(Components[i]).Clear;
TListBox(Components[i]).Color := ColorState(OnOff);
TListBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TEdit then
begin
if not OnOff then
TEdit(Components[i]).Text := '';
if TEdit(Components[i]).ReadOnly = False then
TEdit(Components[i]).Color := ColorState(OnOff);
TEdit(Components[i]).Enabled := OnOff;
end;
end;
end;
end;
{------------------------------------------------------------------------------}
{ lbNumbersClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpePFCurrentValuesDlg.lbNumbersClick(Sender: TObject);
begin
CVIndex := lbNumbers.ItemIndex;
editText.Text := Crv[CVIndex].Text;
end;
{------------------------------------------------------------------------------}
{ editTextExit procedure }
{------------------------------------------------------------------------------}
procedure TCrpePFCurrentValuesDlg.editTextExit(Sender: TObject);
begin
if IsStrEmpty(Crv.Cr.ReportName) then Exit;
if CVIndex < 0 then Exit;
Crv[CVIndex].Text := editText.Text;
UpdateCurrentValues;
end;
{------------------------------------------------------------------------------}
{ btnAddClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpePFCurrentValuesDlg.btnAddClick(Sender: TObject);
var
s : string;
begin
if InputQuery('CurrentValues.Add', 'Add Current Value: ', s) then
begin
Crv.Add(s);
UpdateCurrentValues;
end;
end;
{------------------------------------------------------------------------------}
{ btnDeleteClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpePFCurrentValuesDlg.btnDeleteClick(Sender: TObject);
begin
Crv.Delete(lbNumbers.ItemIndex);
UpdateCurrentValues;
end;
{------------------------------------------------------------------------------}
{ btnClearClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpePFCurrentValuesDlg.btnClearClick(Sender: TObject);
begin
Crv.Clear;
UpdateCurrentValues;
end;
{------------------------------------------------------------------------------}
{ btnOkClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpePFCurrentValuesDlg.btnOkClick(Sender: TObject);
begin
editTextExit(editText);
SaveFormPos(Self);
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose procedure }
{------------------------------------------------------------------------------}
procedure TCrpePFCurrentValuesDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Release;
end;
end.
|
(*
Category: SWAG Title: DISK DRIVE HANDLING ROUTINES
Original name: 0007.PAS
Description: Drive ID
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:38
*)
Program DriveID;
Uses
Dos;
Const
First : Boolean = True;
Var
Count : Integer;
begin
Write('You have the following Drives: ');
For Count := 3 to 26 do
if DiskSize(Count) > 0 then
begin
if not First then
Write(', ');
First := False;
Write(UpCase(Chr(ord('a') - 1 + Count)),':')
end;
WriteLn;
end.
|
unit DSA.Interfaces.DataStructure;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
DSA.Graph.Edge;
type
generic IStack<T> = interface
['{F4C21C9B-5BB0-446D-BBA0-43343B7E8A04}']
function GetSize: integer;
function IsEmpty: boolean;
procedure Push(e: T);
function Pop: T;
function Peek: T;
end;
generic IQueue<T> = interface
['{1454F65C-3628-488C-891A-4A4F6EDECCDA}']
function GetSize: integer;
function IsEmpty: boolean;
procedure EnQueue(e: T);
function DeQueue: T;
function Peek: T;
end;
generic ISet<T> = interface
['{EB3DEBD8-1473-4AD1-90B2-C5CEF2AD2A97}']
procedure Add(e: T);
procedure Remove(e: T);
function Contains(e: T): boolean;
function GetSize: integer;
function IsEmpty: boolean;
end;
generic TPtr_V<V> = packed object
private
type
Ptr_V = ^V;
public
PValue: Ptr_V;
end;
generic IMap<K, V> = interface
['{4D344A23-A724-4120-80D8-C7F07F33D367}']
function Contains(key: K): boolean;
function Get(key: K): specialize TPtr_V<V>;
function GetSize: integer;
function IsEmpty: boolean;
function Remove(key: K): specialize TPtr_V<V>;
procedure Add(key: K; Value: V);
procedure Set_(key: K; Value: V);
end;
generic IMerger<T> = interface
['{B417FA36-9603-4CDA-9AAE-1EA445B6E63E}']
function Merge(Left, Right: T): T;
end;
IUnionFind = interface
['{3EFCB11A-32EE-4852-8D5D-AFC6F3665933}']
function GetSize: integer;
function IsConnected(p, q: integer): boolean;
procedure UnionElements(p, q: integer);
end;
IGraph = interface
['{CEBEE316-FBAD-4C3D-A39E-B324AD097827}']
function Vertex: integer;
function Edge: integer;
function HasEdge(v: integer; w: integer): boolean;
procedure AddEdge(v: integer; w: integer);
function AdjIterator(v: integer): specialize TArray<integer>;
procedure Show;
end;
IIterator = interface
['{9D13D226-BE98-4658-B9A4-53513A3E24C7}']
function Start: integer;
function Next: integer;
function Finished: boolean;
end;
generic TWeightGraph<T> = class abstract
protected type
TEdge_T = specialize TEdge<T>;
TArrEdge = specialize TArray<TEdge_T>;
public
function Vertex: integer; virtual; abstract;
function Edge: integer; virtual; abstract;
function HasEdge(v: integer; w: integer): boolean; virtual; abstract;
function AdjIterator(v: integer): TArrEdge; virtual; abstract;
procedure AddEdge(v, w: integer; weight: T); virtual; abstract;
procedure Show; virtual; abstract;
end;
implementation
end.
|
unit glSQL;
interface
uses
SysUtils, Classes;
type
TglSQLQuery = class(TCollectionItem)
private
fSQL: TStringList;
protected
procedure SetSQL(value: TStringList);
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
published
property SQL: TStringList read fSQL write SetSQL;
end;
TglSQL = class;
TItemChangeEvent = procedure(Item: TCollectionItem) of object;
TSQLCollection = class(TCollection)
private
fMainSQL: TglSQL;
fOnItemChange: TItemChangeEvent;
function GetItem(Index: Integer): TglSQLQuery;
procedure SetItem(Index: Integer; const value: TglSQLQuery);
protected
function GetOwner: TPersistent; override;
procedure Update(Item: TCollectionItem); override;
procedure DoItemChange(Item: TCollectionItem); dynamic;
public
constructor Create(Owner: TglSQL);
function Add: TglSQLQuery;
property Items[Index: Integer]: TglSQLQuery read GetItem
write SetItem; default;
published
property OnItemChange: TItemChangeEvent read fOnItemChange
write fOnItemChange;
end;
TglSQL = class(TComponent)
private
fSQLCollection: TSQLCollection;
procedure SetSQLCollection(const value: TSQLCollection);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property QueryBox: TSQLCollection read fSQLCollection
write SetSQLCollection;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Golden Line', [TglSQL]);
end;
{ TglSQLQuery }
constructor TglSQLQuery.Create(Collection: TCollection);
begin
inherited;
fSQL := TStringList.Create;
end;
destructor TglSQLQuery.Destroy;
begin
fSQL.Free;
inherited;
end;
procedure TglSQLQuery.SetSQL(value: TStringList);
begin
if (fSQL <> value) then
begin
fSQL := value;
Changed(False);
end;
end;
{ TSQLCollection }
function TSQLCollection.Add: TglSQLQuery;
begin
Result := TglSQLQuery(inherited Add);
end;
constructor TSQLCollection.Create(Owner: TglSQL);
begin
inherited Create(TglSQLQuery);
fMainSQL := Owner;
end;
procedure TSQLCollection.DoItemChange(Item: TCollectionItem);
begin
if Assigned(fOnItemChange) then
fOnItemChange(Item);
end;
function TSQLCollection.GetItem(Index: Integer): TglSQLQuery;
begin
Result := TglSQLQuery(inherited GetItem(Index));
end;
function TSQLCollection.GetOwner: TPersistent;
begin
Result := fMainSQL;
end;
procedure TSQLCollection.SetItem(Index: Integer; const value: TglSQLQuery);
begin
inherited SetItem(Index, value);
end;
procedure TSQLCollection.Update(Item: TCollectionItem);
begin
inherited Update(Item);
DoItemChange(Item);
end;
{ TglSQL }
constructor TglSQL.Create(AOwner: TComponent);
begin
inherited;
fSQLCollection := TSQLCollection.Create(Self);
end;
destructor TglSQL.Destroy;
begin
fSQLCollection.Free;
inherited;
end;
procedure TglSQL.SetSQLCollection(const value: TSQLCollection);
begin
fSQLCollection.Assign(value);
end;
end.
|
PROGRAM DCLA;
TYPE
Node = ^NodeRec;
NodeRec = RECORD
value: REAL;
next, prev: Node;
END;
List = Node;
PROCEDURE InitList(VAR l: List);
VAR
n: Node;
BEGIN
New(n);
n^.next := n; (*!!!!*)
n^.prev := n; (*!!!!*)
l := n;
END;
(* ToDo *)
PROCEDURE DisposeList(l: List);
VAR
n, next: Node;
BEGIN
n := l^.next; {*!!!*}
WHILE n <> l DO BEGIN {*!!!*}
next := n^.next;
Dispose(n);
n := next;
END;
// l^.next := l; l^.prev := l; (* repair it for clearing but keeping anchor *) (*!!!*)
Dispose(l); (* also destroy anchor *)
END;
PROCEDURE DisplayList(l: List);
VAR
n: Node;
BEGIN
n := l^.next; (*!!!!*)
WHILE n <> l DO BEGIN {* !!!! *}
Write(n^.value:0:0, ' ');
n := n^.next;
END;
WriteLn;
END;
{* reduced structural complexity by one with SCLA *}
(* AGAIN reduced structural complexity by one with DCLA *)
PROCEDURE AddValueToList(l: List; value: REAL);
VAR
n, newNode: Node;
BEGIN
New(newNode);
newNode^.value := value;
newNode^.next := l; (*!!!*)
// l kann nicht mehr NIL sein
// NO LONGER NEEDED --> looking for the end of the list not necessary
// n := l^.next; {*!!!*}
// WHILE n^.next <> l DO BEGIN {*!!!*}
// n := n^.next;
// END;
newNode^.prev := l^.prev; (* NEW *)
l^.prev^.next := newNode;
l^.prev := newNode; (* NEW *)
END;
FUNCTION ContainsValue(l: List; value: REAL): BOOLEAN;
VAR
n: Node;
BEGIN
n := l^.next; {*!!!*}
WHILE (n <> l) AND (n^.value <> value) DO {*!!!*}
n := n^.next;
ContainsValue := n <> l; {*!!!*}
END;
(* we are using prepend because it is fun, we don't need it anymore !!!!*)
{* we are using prepend because append is too slow... :( *}
{* Strukturkomplexität gleich 1 / vom append wärs 3 *}
PROCEDURE PrependValueToList(l: List; value: REAL);
VAR
newNode: Node;
BEGIN
New(newNode);
newNode^.value := value;
newNode^.prev := l; (*!!!!*)
newNode^.next := l^.next; {*!!!*}
l^.next^.prev := newNode; (*!!!*)
l^.next := newNode; {*!!!*}
END;
(* still works of course but no longer needed !!!!*)
{* we introduce invert to fix the "wrong order problem" introduced with prepend... 8( *}
PROCEDURE InvertList(l: List);
VAR
invList: List;
n, next: Node;
BEGIN
// IF (l^.next = l) OR (l^.next^.next = l) THEN {*!!!*}
// {* nothing to do - list just stays the same *}
// ELSE BEGIN
{* invert with logic of prepend *}
invList := l^.next;
n := l^.next^.next;
invList^.next := l;
WHILE n <> l DO BEGIN
next := n^.next;
(* lets prepend n to invlist :) *)
n^.next := invList;
invList := n;
n := next;
END;
l^.next := invList;
// END;
END;
VAR
l: List;
i: LONGINT;
BEGIN
// InitList(l);
// AddValueToList(l, 2);
// AddValueToList(l, 5);
// AddValueToList(l, 7);
// WriteLn(ContainsValue(l, 2));
// WriteLn(ContainsValue(l, 5));
// WriteLn(ContainsValue(l, 7));
// WriteLn(ContainsValue(l, 8));
// DisplayList(l);
// DisposeList(l);
// InitList(l);
// FOR i := 1 TO 1000 DO
// PrependValueToList(l, i);
// InvertList(l);
DisplayList(l);
DisposeList(l);
END. |
//***********************************************************************
//* Проект "Студгородок" *
//* Справочник льгот - добавление процента *
//* Выполнил: Чернявский А.Э. 2004-2005 г. *
//***********************************************************************
unit uSp_lgota_Persent_AE;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxTextEdit, cxLabel, cxMaskEdit,
cxDropDownEdit, cxCalendar, cxControls, cxContainer, cxEdit, cxGroupBox,
StdCtrls, cxButtons, cxCurrencyEdit, st_ConstUnit, uSp_Lgota_DM,
st_common_funcs, cxButtonEdit, st_common_types, iBase, st_common_loader,
cxRadioGroup;
type
TfrmLgota_Procent_AE = class(TForm)
OKButton: TcxButton;
CancelButton: TcxButton;
cxGroupBox1: TcxGroupBox;
cxLabel1: TcxLabel;
PercentEdit: TcxCurrencyEdit;
Button_name: TcxButtonEdit;
RadioButton_procent: TcxRadioButton;
RadioButton_sum: TcxRadioButton;
procedure OKButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure DateEndEditKeyPress(Sender: TObject; var Key: Char);
procedure PercentEditKeyPress(Sender: TObject; var Key: Char);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button_namePropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
private
PLanguageIndex: byte;
procedure FormIniLanguage();
public
Date_last_end : TDate;
aHandle : TISC_DB_HANDLE;
is_admin : Boolean;
id_serves : Int64;
{ Public declarations }
end;
var
frmLgota_Procent_AE: TfrmLgota_Procent_AE;
implementation
{$R *.dfm}
procedure TfrmLgota_Procent_AE.FormIniLanguage();
begin
// индекс языка (1-укр, 2 - рус)
PLanguageIndex := stLanguageIndex;
//названия кнопок
OKButton.Caption := st_ConstUnit.st_Accept[PLanguageIndex];
CancelButton.Caption := st_ConstUnit.st_Cancel[PLanguageIndex];
cxLabel1.Caption := st_ConstUnit.st_NameLable[PLanguageIndex];
RadioButton_procent.Caption := st_ConstUnit.st_PercentOnly[PLanguageIndex];
end;
procedure TfrmLgota_Procent_AE.OKButtonClick(Sender: TObject);
begin
If Button_name.Text = '' then
begin
ShowMessage('Необхідно обрати послугу!!!');
Button_name.SetFocus;
exit;
end;
if PercentEdit.Text = '' then
begin
ShowMessage(pchar(st_ConstUnit.st_Percent_need[PLanguageIndex]));
PercentEdit.SetFocus;
exit;
end;
if not FloatCheck(PercentEdit.Text) then
begin
ShowMessage(pchar(st_ConstUnit.st_PercentNotCorrect[PLanguageIndex]));
PercentEdit.SetFocus;
exit;
end;
if ((PercentEdit.Value > 100.0000) and (RadioButton_procent.Checked)) then
begin
ShowMessage(pchar(st_ConstUnit.st_PercentMoreCTONotCorrect[PLanguageIndex]));
PercentEdit.SetFocus;
exit;
end;
ModalResult := mrOK;
end;
procedure TfrmLgota_Procent_AE.CancelButtonClick(Sender: TObject);
begin
close;
end;
procedure TfrmLgota_Procent_AE.DateEndEditKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then PercentEdit.SetFocus;
end;
procedure TfrmLgota_Procent_AE.PercentEditKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then OKButton.SetFocus;
end;
procedure TfrmLgota_Procent_AE.FormShow(Sender: TObject);
begin
PercentEdit.SetFocus;
end;
procedure TfrmLgota_Procent_AE.FormCreate(Sender: TObject);
begin
FormIniLanguage();
end;
procedure TfrmLgota_Procent_AE.Button_namePropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
aParameter : TstSimpleParams;
res : Variant;
begin
aParameter := TstSimpleParams.Create;
aParameter.Owner := self;
aParameter.Db_Handle := aHandle;
AParameter.Formstyle := fsNormal;
AParameter.WaitPakageOwner := self;
aParameter.is_admin := is_admin;
res := RunFunctionFromPackage(aParameter, 'Studcity\st_services.bpl', 'getServices');
If VarArrayDimCount(res) <>0 then
begin
id_serves := res[0];
Button_name.Text := res[1];
end;
aParameter.Free;
end;
end.
|
unit uMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls;
type
TForm1 = class(TForm)
edtUserKey: TEdit;
edtIV: TEdit;
edtText: TEdit;
btnTest: TButton;
Memo1: TMemo;
Panel1: TPanel;
Button1: TButton;
procedure btnTestClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses
Seed, SeedEncDec;
{$R *.dfm}
procedure TForm1.btnTestClick(Sender: TObject);
var
Seed : ISeed;
EncData : string;
DecData : string;
begin
Memo1.Clear;
Seed := TSeed.Create;
Memo1.Lines.Add('Mode : ECB');
Seed.InitForECB(edtUserKey.Text);
EncData := Seed.Encrypt(edtText.Text);
Memo1.Lines.Add('------Encrypt------');
Memo1.Lines.Add('KeyToHex : ' + sLineBreak + TSeed(Seed).getKeyToHex(','));
Memo1.Lines.Add('InDataToHex : ' + sLineBreak + TSeed(Seed).getInDataToHex(','));
Memo1.Lines.Add('EncDataToHex : ' + sLineBreak + TSeed(Seed).getOutDataToHex(','));
Memo1.Lines.Add('EncData : ' + sLineBreak + EncData);
Seed.Burn;
Seed.InitForECB(edtUserKey.Text);
DecData := Seed.Decrypt(EncData);
Memo1.Lines.Add('------Decrypt------');
Memo1.Lines.Add('KeyToHex : ' + sLineBreak + TSeed(Seed).getKeyToHex(','));
Memo1.Lines.Add('InDataToHex : ' + sLineBreak + TSeed(Seed).getInDataToHex(','));
Memo1.Lines.Add('DecDataToHex : ' + sLineBreak + TSeed(Seed).getOutDataToHex(','));
Memo1.Lines.Add('DecData : ' + sLineBreak + DecData);
Memo1.Lines.Add('-------------------');
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Seed : ISeed;
EncData : string;
DecData : string;
begin
Memo1.Clear;
Seed := TSeed.Create;
Memo1.Lines.Add('Mode : CBC');
// Seed.InitForCBC(edtUserKey.Text, edtIV.Text);
// EncData := Seed.Encrypt(edtText.Text);
EncData := Seed.EncryptForCBC(edtUserKey.Text, edtIV.Text, edtText.Text);
Memo1.Lines.Add('------Encrypt------');
Memo1.Lines.Add('KeyToHex : ' + sLineBreak + TSeed(Seed).getKeyToHex(','));
Memo1.Lines.Add('InDataToHex : ' + sLineBreak + TSeed(Seed).getInDataToHex(','));
Memo1.Lines.Add('EncDataToHex : ' + sLineBreak + TSeed(Seed).getOutDataToHex(','));
Memo1.Lines.Add('EncData : ' + sLineBreak + EncData);
Seed.Burn;
// Seed.InitForCBC(edtUserKey.Text, edtIV.Text);
// DecData := Seed.Decrypt(EncData);
DecData := Seed.DecryptForCBC(edtUserKey.Text, edtIV.Text, EncData);
Memo1.Lines.Add('------Decrypt------');
Memo1.Lines.Add('KeyToHex : ' + sLineBreak + TSeed(Seed).getKeyToHex(','));
Memo1.Lines.Add('InDataToHex : ' + sLineBreak + TSeed(Seed).getInDataToHex(','));
Memo1.Lines.Add('DecDataToHex : ' + sLineBreak + TSeed(Seed).getOutDataToHex(','));
Memo1.Lines.Add('DecData : ' + sLineBreak + DecData);
Memo1.Lines.Add('-------------------');
end;
end.
|
unit Server.Configuration;
interface
type
TConfiguration = class
private
FDatabaseConnectionName: String;
FLogFileName: String;
FLogLevel: String;
FServerPort: Integer;
public
constructor Create;
property DatabaseConnectionName: String read FDatabaseConnectionName write FDatabaseConnectionName;
property LogFileName: String read FLogFileName;
property LogLevel: String read FLogLevel write FLogLevel;
property ServerPort: Integer read FServerPort write FServerPort;
end;
implementation
uses
System.IniFiles
, System.IOUtils
, System.SysUtils
;
type
TPersistentConfiguration = class
public
class procedure Load(const AConfiguration: TConfiguration);
end;
const
CONNECTION_NAME_DEFAULT = 'ERGO';
LOG_FILENAME = 'WiRLServerTemplate_%s.log';
LOG_LEVEL = 'ERROR';
SERVER_PORT = 20010;
{ TConfiguration }
{======================================================================================================================}
constructor TConfiguration.Create;
{======================================================================================================================}
begin
TPersistentConfiguration.Load(Self);
end;
{ TPersistentConfiguration }
{======================================================================================================================}
class procedure TPersistentConfiguration.Load(const AConfiguration: TConfiguration);
{======================================================================================================================}
var
appPath: String;
appName: String;
tmpPath: String;
iniFileName: String;
ini: TIniFile;
begin
appPath := IncludeTrailingBackslash(TPath.GetDirectoryName(ParamStr(0)));
appName := TPath.GetFileNameWithoutExtension(ParamStr(0));
iniFileName := appPath + appName + '.ini';
ini := TIniFile.Create(iniFileName);
try
tmpPath := TPath.GetTempPath;
AConfiguration.FDatabaseConnectionName := ini.ReadString('SERVICE', 'DBNAME', CONNECTION_NAME_DEFAULT);
AConfiguration.FLogFileName := ini.ReadString('SERVICE', 'LOG_FILENAME', tmpPath + LOG_FILENAME);
AConfiguration.FLogLevel := ini.ReadString('SERVICE', 'LOG_LEVEL', LOG_LEVEL);
AConfiguration.FServerPort := ini.ReadInteger('SERVICE', 'SERVER_PORT', SERVER_PORT);
finally
FreeAndNil(ini);
end;
end;
end.
|
unit GameControl;
interface
uses
Math, TypeControl;
type
TGame = class
private
FRandomSeed: Int64;
FTickCount: LongInt;
FWorldWidth: LongInt;
FWorldHeight: LongInt;
FTrackTileSize: Double;
FTrackTileMargin: Double;
FLapCount: LongInt;
FLapTickCount: LongInt;
FInitialFreezeDurationTicks: LongInt;
FBurningTimeDurationFactor: Double;
FFinishTrackScores: TLongIntArray;
FFinishLapScore: LongInt;
FLapWaypointsSummaryScoreFactor: Double;
FCarDamageScoreFactor: Double;
FCarEliminationScore: LongInt;
FCarWidth: Double;
FCarHeight: Double;
FCarEnginePowerChangePerTick: Double;
FCarWheelTurnChangePerTick: Double;
FCarAngularSpeedFactor: Double;
FCarMovementAirFrictionFactor: Double;
FCarRotationAirFrictionFactor: Double;
FCarLengthwiseMovementFrictionFactor: Double;
FCarCrosswiseMovementFrictionFactor: Double;
FCarRotationFrictionFactor: Double;
FThrowProjectileCooldownTicks: LongInt;
FUseNitroCooldownTicks: LongInt;
FSpillOilCooldownTicks: LongInt;
FNitroEnginePowerFactor: Double;
FNitroDurationTicks: LongInt;
FCarReactivationTimeTicks: LongInt;
FBuggyMass: Double;
FBuggyEngineForwardPower: Double;
FBuggyEngineRearPower: Double;
FJeepMass: Double;
FJeepEngineForwardPower: Double;
FJeepEngineRearPower: Double;
FBonusSize: Double;
FBonusMass: Double;
FPureScoreAmount: LongInt;
FWasherRadius: Double;
FWasherMass: Double;
FWasherInitialSpeed: Double;
FWasherDamage: Double;
FSideWasherAngle: Double;
FTireRadius: Double;
FTireMass: Double;
FTireInitialSpeed: Double;
FTireDamageFactor: Double;
FTireDisappearSpeedFactor: Double;
FOilSlickInitialRange: Double;
FOilSlickRadius: Double;
FOilSlickLifetime: LongInt;
FMaxOiledStateDurationTicks: LongInt;
function GetRandomSeed: Int64;
function GetTickCount: LongInt;
function GetWorldWidth: LongInt;
function GetWorldHeight: LongInt;
function GetTrackTileSize: Double;
function GetTrackTileMargin: Double;
function GetLapCount: LongInt;
function GetLapTickCount: LongInt;
function GetInitialFreezeDurationTicks: LongInt;
function GetBurningTimeDurationFactor: Double;
function GetFinishTrackScores: TLongIntArray;
function GetFinishLapScore: LongInt;
function GetLapWaypointsSummaryScoreFactor: Double;
function GetCarDamageScoreFactor: Double;
function GetCarEliminationScore: LongInt;
function GetCarWidth: Double;
function GetCarHeight: Double;
function GetCarEnginePowerChangePerTick: Double;
function GetCarWheelTurnChangePerTick: Double;
function GetCarAngularSpeedFactor: Double;
function GetCarMovementAirFrictionFactor: Double;
function GetCarRotationAirFrictionFactor: Double;
function GetCarLengthwiseMovementFrictionFactor: Double;
function GetCarCrosswiseMovementFrictionFactor: Double;
function GetCarRotationFrictionFactor: Double;
function GetThrowProjectileCooldownTicks: LongInt;
function GetUseNitroCooldownTicks: LongInt;
function GetSpillOilCooldownTicks: LongInt;
function GetNitroEnginePowerFactor: Double;
function GetNitroDurationTicks: LongInt;
function GetCarReactivationTimeTicks: LongInt;
function GetBuggyMass: Double;
function GetBuggyEngineForwardPower: Double;
function GetBuggyEngineRearPower: Double;
function GetJeepMass: Double;
function GetJeepEngineForwardPower: Double;
function GetJeepEngineRearPower: Double;
function GetBonusSize: Double;
function GetBonusMass: Double;
function GetPureScoreAmount: LongInt;
function GetWasherRadius: Double;
function GetWasherMass: Double;
function GetWasherInitialSpeed: Double;
function GetWasherDamage: Double;
function GetSideWasherAngle: Double;
function GetTireRadius: Double;
function GetTireMass: Double;
function GetTireInitialSpeed: Double;
function GetTireDamageFactor: Double;
function GetTireDisappearSpeedFactor: Double;
function GetOilSlickInitialRange: Double;
function GetOilSlickRadius: Double;
function GetOilSlickLifetime: LongInt;
function GetMaxOiledStateDurationTicks: LongInt;
public
property RandomSeed: Int64 read GetRandomSeed;
property TickCount: LongInt read GetTickCount;
property WorldWidth: LongInt read GetWorldWidth;
property WorldHeight: LongInt read GetWorldHeight;
property TrackTileSize: Double read GetTrackTileSize;
property TrackTileMargin: Double read GetTrackTileMargin;
property LapCount: LongInt read GetLapCount;
property LapTickCount: LongInt read GetLapTickCount;
property InitialFreezeDurationTicks: LongInt read GetInitialFreezeDurationTicks;
property BurningTimeDurationFactor: Double read GetBurningTimeDurationFactor;
property FinishTrackScores: TLongIntArray read GetFinishTrackScores;
property FinishLapScore: LongInt read GetFinishLapScore;
property LapWaypointsSummaryScoreFactor: Double read GetLapWaypointsSummaryScoreFactor;
property CarDamageScoreFactor: Double read GetCarDamageScoreFactor;
property CarEliminationScore: LongInt read GetCarEliminationScore;
property CarWidth: Double read GetCarWidth;
property CarHeight: Double read GetCarHeight;
property CarEnginePowerChangePerTick: Double read GetCarEnginePowerChangePerTick;
property CarWheelTurnChangePerTick: Double read GetCarWheelTurnChangePerTick;
property CarAngularSpeedFactor: Double read GetCarAngularSpeedFactor;
property CarMovementAirFrictionFactor: Double read GetCarMovementAirFrictionFactor;
property CarRotationAirFrictionFactor: Double read GetCarRotationAirFrictionFactor;
property CarLengthwiseMovementFrictionFactor: Double read GetCarLengthwiseMovementFrictionFactor;
property CarCrosswiseMovementFrictionFactor: Double read GetCarCrosswiseMovementFrictionFactor;
property CarRotationFrictionFactor: Double read GetCarRotationFrictionFactor;
property ThrowProjectileCooldownTicks: LongInt read GetThrowProjectileCooldownTicks;
property UseNitroCooldownTicks: LongInt read GetUseNitroCooldownTicks;
property SpillOilCooldownTicks: LongInt read GetSpillOilCooldownTicks;
property NitroEnginePowerFactor: Double read GetNitroEnginePowerFactor;
property NitroDurationTicks: LongInt read GetNitroDurationTicks;
property CarReactivationTimeTicks: LongInt read GetCarReactivationTimeTicks;
property BuggyMass: Double read GetBuggyMass;
property BuggyEngineForwardPower: Double read GetBuggyEngineForwardPower;
property BuggyEngineRearPower: Double read GetBuggyEngineRearPower;
property JeepMass: Double read GetJeepMass;
property JeepEngineForwardPower: Double read GetJeepEngineForwardPower;
property JeepEngineRearPower: Double read GetJeepEngineRearPower;
property BonusSize: Double read GetBonusSize;
property BonusMass: Double read GetBonusMass;
property PureScoreAmount: LongInt read GetPureScoreAmount;
property WasherRadius: Double read GetWasherRadius;
property WasherMass: Double read GetWasherMass;
property WasherInitialSpeed: Double read GetWasherInitialSpeed;
property WasherDamage: Double read GetWasherDamage;
property SideWasherAngle: Double read GetSideWasherAngle;
property TireRadius: Double read GetTireRadius;
property TireMass: Double read GetTireMass;
property TireInitialSpeed: Double read GetTireInitialSpeed;
property TireDamageFactor: Double read GetTireDamageFactor;
property TireDisappearSpeedFactor: Double read GetTireDisappearSpeedFactor;
property OilSlickInitialRange: Double read GetOilSlickInitialRange;
property OilSlickRadius: Double read GetOilSlickRadius;
property OilSlickLifetime: LongInt read GetOilSlickLifetime;
property MaxOiledStateDurationTicks: LongInt read GetMaxOiledStateDurationTicks;
constructor Create(const ARandomSeed: Int64; const ATickCount: LongInt; const AWorldWidth: LongInt;
const AWorldHeight: LongInt; const ATrackTileSize: Double; const ATrackTileMargin: Double;
const ALapCount: LongInt; const AlapTickCount: LongInt; const AInitialFreezeDurationTicks: LongInt;
const ABurningTimeDurationFactor: Double; const AFinishTrackScores: TLongIntArray;
const AFinishLapScore: LongInt; const ALapWaypointsSummaryScoreFactor: Double;
const ACarDamageScoreFactor: Double; const ACarEliminationScore: LongInt; const ACarWidth: Double;
const ACarHeight: Double; const ACarEnginePowerChangePerTick: Double;
const ACarWheelTurnChangePerTick: Double; const ACarAngularSpeedFactor: Double;
const ACarMovementAirFrictionFactor: Double; const ACarRotationAirFrictionFactor: Double;
const ACarLengthwiseMovementFrictionFactor: Double;
const ACarCrosswiseMovementFrictionFactor: Double; const ACarRotationFrictionFactor: Double;
const AThrowProjectileCooldownTicks: LongInt; const AUseNitroCooldownTicks: LongInt;
const ASpillOilCooldownTicks: LongInt; const ANitroEnginePowerFactor: Double;
const ANitroDurationTicks: LongInt; const ACarReactivationTimeTicks: LongInt;
const ABuggyMass: Double; const ABuggyEngineForwardPower: Double;
const ABuggyEngineRearPower: Double; const AJeepMass: Double;
const AJeepEngineForwardPower: Double; const AJeepEngineRearPower: Double;
const ABonusSize: Double; const ABonusMass: Double; const APureScoreAmount: LongInt;
const AWasherRadius: Double; const AWasherMass: Double; const AWasherInitialSpeed: Double;
const AWasherDamage: Double; const ASideWasherAngle: Double; const ATireRadius: Double;
const ATireMass: Double; const ATireInitialSpeed: Double; const ATireDamageFactor: Double;
const ATireDisappearSpeedFactor: Double; const AOilSlickInitialRange: Double;
const AOilSlickRadius: Double; const AOilSlickLifetime: LongInt;
const AMaxOiledStateDurationTicks: LongInt);
destructor Destroy; override;
end;
TGameArray = array of TGame;
implementation
function TGame.GetRandomSeed: Int64;
begin
Result := FRandomSeed;
end;
function TGame.GetTickCount: LongInt;
begin
Result := FTickCount;
end;
function TGame.GetWorldWidth: LongInt;
begin
Result := FWorldWidth;
end;
function TGame.GetWorldHeight: LongInt;
begin
Result := FWorldHeight;
end;
function TGame.GetTrackTileSize: Double;
begin
Result := FTrackTileSize;
end;
function TGame.GetTrackTileMargin: Double;
begin
Result := FTrackTileMargin;
end;
function TGame.GetLapCount: LongInt;
begin
Result := FLapCount;
end;
function TGame.GetLapTickCount: LongInt;
begin
Result := FLapTickCount;
end;
function TGame.GetInitialFreezeDurationTicks: LongInt;
begin
Result := FInitialFreezeDurationTicks;
end;
function TGame.GetBurningTimeDurationFactor: Double;
begin
Result := FBurningTimeDurationFactor;
end;
function TGame.GetFinishTrackScores: TLongIntArray;
begin
if Assigned(FFinishTrackScores) then
Result := Copy(FFinishTrackScores, 0, Length(FFinishTrackScores))
else
Result := nil;
end;
function TGame.GetFinishLapScore: LongInt;
begin
Result := FFinishLapScore;
end;
function TGame.GetLapWaypointsSummaryScoreFactor: Double;
begin
Result := FLapWaypointsSummaryScoreFactor;
end;
function TGame.GetCarDamageScoreFactor: Double;
begin
Result := FCarDamageScoreFactor;
end;
function TGame.GetCarEliminationScore: LongInt;
begin
Result := FCarEliminationScore;
end;
function TGame.GetCarWidth: Double;
begin
Result := FCarWidth;
end;
function TGame.GetCarHeight: Double;
begin
Result := FCarHeight;
end;
function TGame.GetCarEnginePowerChangePerTick: Double;
begin
Result := FCarEnginePowerChangePerTick;
end;
function TGame.GetCarWheelTurnChangePerTick: Double;
begin
Result := FCarWheelTurnChangePerTick;
end;
function TGame.GetCarAngularSpeedFactor: Double;
begin
Result := FCarAngularSpeedFactor;
end;
function TGame.GetCarMovementAirFrictionFactor: Double;
begin
Result := FCarMovementAirFrictionFactor;
end;
function TGame.GetCarRotationAirFrictionFactor: Double;
begin
Result := FCarRotationAirFrictionFactor;
end;
function TGame.GetCarLengthwiseMovementFrictionFactor: Double;
begin
Result := FCarLengthwiseMovementFrictionFactor;
end;
function TGame.GetCarCrosswiseMovementFrictionFactor: Double;
begin
Result := FCarCrosswiseMovementFrictionFactor;
end;
function TGame.GetCarRotationFrictionFactor: Double;
begin
Result := FCarRotationFrictionFactor;
end;
function TGame.GetThrowProjectileCooldownTicks: LongInt;
begin
Result := FThrowProjectileCooldownTicks;
end;
function TGame.GetUseNitroCooldownTicks: LongInt;
begin
Result := FUseNitroCooldownTicks;
end;
function TGame.GetSpillOilCooldownTicks: LongInt;
begin
Result := FSpillOilCooldownTicks;
end;
function TGame.GetNitroEnginePowerFactor: Double;
begin
Result := FNitroEnginePowerFactor;
end;
function TGame.GetNitroDurationTicks: LongInt;
begin
Result := FNitroDurationTicks;
end;
function TGame.GetCarReactivationTimeTicks: LongInt;
begin
Result := FCarReactivationTimeTicks;
end;
function TGame.GetBuggyMass: Double;
begin
Result := FBuggyMass;
end;
function TGame.GetBuggyEngineForwardPower: Double;
begin
Result := FBuggyEngineForwardPower;
end;
function TGame.GetBuggyEngineRearPower: Double;
begin
Result := FBuggyEngineRearPower;
end;
function TGame.GetJeepMass: Double;
begin
Result := FJeepMass;
end;
function TGame.GetJeepEngineForwardPower: Double;
begin
Result := FJeepEngineForwardPower;
end;
function TGame.GetJeepEngineRearPower: Double;
begin
Result := FJeepEngineRearPower;
end;
function TGame.GetBonusSize: Double;
begin
Result := FBonusSize;
end;
function TGame.GetBonusMass: Double;
begin
Result := FBonusMass;
end;
function TGame.GetPureScoreAmount: LongInt;
begin
Result := FPureScoreAmount;
end;
function TGame.GetWasherRadius: Double;
begin
Result := FWasherRadius;
end;
function TGame.GetWasherMass: Double;
begin
Result := FWasherMass;
end;
function TGame.GetWasherInitialSpeed: Double;
begin
Result := FWasherInitialSpeed;
end;
function TGame.GetWasherDamage: Double;
begin
Result := FWasherDamage;
end;
function TGame.GetSideWasherAngle: Double;
begin
Result := FSideWasherAngle;
end;
function TGame.GetTireRadius: Double;
begin
Result := FTireRadius;
end;
function TGame.GetTireMass: Double;
begin
Result := FTireMass;
end;
function TGame.GetTireInitialSpeed: Double;
begin
Result := FTireInitialSpeed;
end;
function TGame.GetTireDamageFactor: Double;
begin
Result := FTireDamageFactor;
end;
function TGame.GetTireDisappearSpeedFactor: Double;
begin
Result := FTireDisappearSpeedFactor;
end;
function TGame.GetOilSlickInitialRange: Double;
begin
Result := FOilSlickInitialRange;
end;
function TGame.GetOilSlickRadius: Double;
begin
Result := FOilSlickRadius;
end;
function TGame.GetOilSlickLifetime: LongInt;
begin
Result := FOilSlickLifetime;
end;
function TGame.GetMaxOiledStateDurationTicks: LongInt;
begin
Result := FMaxOiledStateDurationTicks;
end;
constructor TGame.Create(const ARandomSeed: Int64; const ATickCount: LongInt; const AWorldWidth: LongInt;
const AWorldHeight: LongInt; const ATrackTileSize: Double; const ATrackTileMargin: Double;
const ALapCount: LongInt; const AlapTickCount: LongInt; const AInitialFreezeDurationTicks: LongInt;
const ABurningTimeDurationFactor: Double; const AFinishTrackScores: TLongIntArray;
const AFinishLapScore: LongInt; const ALapWaypointsSummaryScoreFactor: Double;
const ACarDamageScoreFactor: Double; const ACarEliminationScore: LongInt; const ACarWidth: Double;
const ACarHeight: Double; const ACarEnginePowerChangePerTick: Double;
const ACarWheelTurnChangePerTick: Double; const ACarAngularSpeedFactor: Double;
const ACarMovementAirFrictionFactor: Double; const ACarRotationAirFrictionFactor: Double;
const ACarLengthwiseMovementFrictionFactor: Double;
const ACarCrosswiseMovementFrictionFactor: Double; const ACarRotationFrictionFactor: Double;
const AThrowProjectileCooldownTicks: LongInt; const AUseNitroCooldownTicks: LongInt;
const ASpillOilCooldownTicks: LongInt; const ANitroEnginePowerFactor: Double;
const ANitroDurationTicks: LongInt; const ACarReactivationTimeTicks: LongInt;
const ABuggyMass: Double; const ABuggyEngineForwardPower: Double;
const ABuggyEngineRearPower: Double; const AJeepMass: Double;
const AJeepEngineForwardPower: Double; const AJeepEngineRearPower: Double;
const ABonusSize: Double; const ABonusMass: Double; const APureScoreAmount: LongInt;
const AWasherRadius: Double; const AWasherMass: Double; const AWasherInitialSpeed: Double;
const AWasherDamage: Double; const ASideWasherAngle: Double; const ATireRadius: Double;
const ATireMass: Double; const ATireInitialSpeed: Double; const ATireDamageFactor: Double;
const ATireDisappearSpeedFactor: Double; const AOilSlickInitialRange: Double;
const AOilSlickRadius: Double; const AOilSlickLifetime: LongInt;
const AMaxOiledStateDurationTicks: LongInt);
begin
FRandomSeed := ARandomSeed;
FTickCount := ATickCount;
FWorldWidth := AWorldWidth;
FWorldHeight := AWorldHeight;
FTrackTileSize := ATrackTileSize;
FTrackTileMargin := ATrackTileMargin;
FLapCount := ALapCount;
FLapTickCount := ALapTickCount;
FInitialFreezeDurationTicks := AInitialFreezeDurationTicks;
FBurningTimeDurationFactor := ABurningTimeDurationFactor;
if Assigned(AFinishTrackScores) then
FFinishTrackScores := Copy(AFinishTrackScores, 0, Length(AFinishTrackScores))
else
FFinishTrackScores := nil;
FFinishLapScore := AFinishLapScore;
FLapWaypointsSummaryScoreFactor := AlapWaypointsSummaryScoreFactor;
FCarDamageScoreFactor := ACarDamageScoreFactor;
FCarEliminationScore := ACarEliminationScore;
FCarWidth := ACarWidth;
FCarHeight := AcarHeight;
FCarEnginePowerChangePerTick := ACarEnginePowerChangePerTick;
FCarWheelTurnChangePerTick := ACarWheelTurnChangePerTick;
FCarAngularSpeedFactor := AcarAngularSpeedFactor;
FCarMovementAirFrictionFactor := ACarMovementAirFrictionFactor;
FCarRotationAirFrictionFactor := ACarRotationAirFrictionFactor;
FCarLengthwiseMovementFrictionFactor := ACarLengthwiseMovementFrictionFactor;
FCarCrosswiseMovementFrictionFactor := ACarCrosswiseMovementFrictionFactor;
FCarRotationFrictionFactor := ACarRotationFrictionFactor;
FThrowProjectileCooldownTicks := AThrowProjectileCooldownTicks;
FUseNitroCooldownTicks := AUseNitroCooldownTicks;
FSpillOilCooldownTicks := ASpillOilCooldownTicks;
FNitroEnginePowerFactor := ANitroEnginePowerFactor;
FNitroDurationTicks := ANitroDurationTicks;
FCarReactivationTimeTicks := ACarReactivationTimeTicks;
FBuggyMass := ABuggyMass;
FBuggyEngineForwardPower := ABuggyEngineForwardPower;
FBuggyEngineRearPower := ABuggyEngineRearPower;
FJeepMass := AJeepMass;
FJeepEngineForwardPower := AJeepEngineForwardPower;
FJeepEngineRearPower := AJeepEngineRearPower;
FBonusSize := ABonusSize;
FBonusMass := AbonusMass;
FPureScoreAmount := APureScoreAmount;
FWasherRadius := AWasherRadius;
FWasherMass := AWasherMass;
FWasherInitialSpeed := AWasherInitialSpeed;
FWasherDamage := AWasherDamage;
FSideWasherAngle := ASideWasherAngle;
FTireRadius := ATireRadius;
FTireMass := ATireMass;
FTireInitialSpeed := ATireInitialSpeed;
FTireDamageFactor := ATireDamageFactor;
FTireDisappearSpeedFactor := ATireDisappearSpeedFactor;
FOilSlickInitialRange := AOilSlickInitialRange;
FOilSlickRadius := AOilSlickRadius;
FOilSlickLifetime := AOilSlickLifetime;
FMaxOiledStateDurationTicks := AMaxOiledStateDurationTicks;
end;
destructor TGame.Destroy;
begin
inherited;
end;
end.
|
unit HVA;
// HVA Unit By Stucuk
// Written using the tibsun-hva.doc by The Profound Eol And DMV
interface
uses OpenGl15,geometry,dialogs,sysutils,math3d, voxel, math,VH_Types;
// Enable it for HVA debug purposes only.
//{$define DEBUG_HVA_FILE}
Procedure LoadHVA(const Filename : string);
Procedure LoadHVA2(var HVAFile : THVA; var HVAOpen : Boolean; const Filename,Ext : string);
Procedure SaveHVA(const Filename : string);
Procedure SaveHVA2(var HVAFile : THVA; const Filename,Ext : string);
procedure ClearHVA(var _HVA : THVA);
Function ApplyMatrixToVector(const HVAFile : THVA; const VoxelFile : TVoxel; Position, Scale : TVector3f; Section,Frames : Integer) : TVector3f;
Function ApplyMatrix(const HVAFile : THVA; const VoxelFile : TVoxel; Scale : TVector3f; Section, Frames : Integer) : TVector3f;
Procedure CreateHVA(const Vxl : TVoxel; var HVA : THVA);
Procedure SetHVAPos(Var HVA : THVA; Const Section : Integer; X,Y,Z : single);
Procedure SetHVAPos2(Var HVA : THVA; Const Voxel : TVoxel; Section : Integer; Position : TVector3f);
Function GetHVAPos(const HVA : THVA; const Voxel : TVoxel; Section : Integer) : TVector3f;
Function SETHVAAngle(var HVAFile : THVA; const Section,Frames : Integer; x,y,z : single) : TVector3f;
Function SETHVAAngle2(var HVAFile : THVA; const Section,Frames : Integer; x,y,z : single) : TVector3f;
Function GETHVAAngle_DEG(const HVAFile : THVA; Section,Frames : Integer) : TVector3f;
Procedure AddHVAFrame(Var HVAFile : THVA);
Procedure InsertHVAFrame(Var HVAFile : THVA);
Procedure DeleteHVAFrame(Var HVAFile : THVA);
Procedure CopyHVAFrame(Var HVAFile : THVA);
Procedure SetCharArray(const Name : String; Var CharArr : Array of Char);
Function GetCurrentFrame : Integer;
Function GetCurrentFrame2(_Type : Integer) : Integer;
Procedure SetCurrentFrame(Value : Integer);
Function GetCurrentHVA : PHVA;
Function GetCurrentHVAB : Boolean;
Function GetTMValue(const HVAFile : THVA; Row,Col,Section,Frames : integer) : single;
implementation
Uses VH_Global;
Procedure LoadHVA(const Filename : string);
begin
LoadHVA2(HVAFile,HVAOpen,Filename,'.hva');
If not HVAOpen then
CreateHVA(VoxelFile,HVAFile);
CurrentHVA := @HVAFile;
If VoxelOpenT then
begin
LoadHVA2(HVATurret,HVAOpenT,Filename,'tur.hva');
If not HVAOpenT then
CreateHVA(VoxelTurret,HVATurret);
end
else
begin
if HVAOpenT then
ClearHVA(HVATurret);
HVAOpenT := false;
end;
If VoxelOpenB then
begin
LoadHVA2(HVABarrel,HVAOpenB,Filename,'barl.hva');
If not HVAOpenB then
CreateHVA(VoxelBarrel,HVABarrel);
end
else
begin
if HVAOpenB then
ClearHVA(HVABarrel);
HVAOpenB := false;
end;
end;
Procedure LoadHVA2(var HVAFile : THVA; var HVAOpen : Boolean; const Filename,Ext : string);
var
f : file;
x : integer;
TFilename : string;
begin
if HVAOpen then
ClearHVA(HVAFile);
TFilename := extractfiledir(Filename) + '\' + copy(Extractfilename(Filename),1,Length(Extractfilename(Filename))-Length('.hva')) + Ext;
HVAOpen := false;
if not FileExists(TFilename) then
exit;
AssignFile(F,TFilename); // Open file
Reset(F,1); // Goto first byte?
BlockRead(F,HVAFile.Header,Sizeof(THVA_Main_Header)); // Read Header
HVAFile.Data_no := HVAFile.Header.N_Sections;
SetLength(HVAFile.Data,HVAFile.Data_no);
For x := 0 to HVAFile.Header.N_Sections-1 do
BlockRead(F,HVAFile.Data[x].SectionName,Sizeof(TSectionName));
SetLength(HVAFile.TransformMatrixs,HVAFile.Header.N_Frames*HVAFile.Header.N_Sections);
For x := 0 to HVAFile.Header.N_Sections * HVAFile.Header.N_Frames-1 do
BlockRead(F,HVAFile.TransformMatrixs[x],Sizeof(TTransformMatrix));
CloseFile(f);
HVAOpen := True;
If HVAFile.Header.N_Frames < 1 then
HVAOpen := False;
// Clear memory
TFilename := '';
end;
Procedure SaveHVA(const Filename : string);
begin
SaveHVA2(HVAFile,Filename,'.hva');
// Save Turret And Barrel
if VoxelOpenT then
SaveHVA2(HVATurret,Filename,'tur.hva');
if VoxelOpenB then
SaveHVA2(HVABarrel,Filename,'barl.hva');
end;
procedure ClearHVA(var _HVA : THVA);
begin
SetLength(_HVA.Data, 0);
SetLength(_HVA.TransformMatrixs, 0);
_HVA.Data_no := 0;
_HVA.HigherLevel := nil;
_HVA.Header.N_Frames := 0;
_HVA.Header.N_Sections := 0;
end;
Procedure SaveHVA2(var HVAFile : THVA; const Filename,Ext : string);
var
f : file;
wrote,x : integer;
TFilename : string;
begin
TFilename := extractfiledir(Filename) + '\' + copy(Extractfilename(Filename),1,Length(Extractfilename(Filename))-Length('.hva')) + Ext;
//SetCharArray('',HVAFile.Header.FilePath);
for x := 1 to 16 do
HVAFile.Header.FilePath[x] := #0;
AssignFile(F,TFilename); // Open file
Rewrite(F,1); // Goto first byte?
BlockWrite(F,HVAFile.Header,Sizeof(THVA_Main_Header),wrote); // Write Header
{$ifdef DEBUG_HVA_FILE}
Showmessage(TFilename);
showmessage(inttostr(HVAFile.Header.N_Sections));
showmessage(inttostr(HVAFile.Header.N_Frames));
showmessage(inttostr(wrote));
{$endif}
For x := 0 to HVAFile.Header.N_Sections-1 do
BlockWrite(F,HVAFile.Data[x].SectionName,Sizeof(TSectionName),wrote);
{$ifdef DEBUG_HVA_FILE}
showmessage(inttostr(wrote));
{$endif}
For x := 0 to HVAFile.Header.N_Sections * HVAFile.Header.N_Frames-1 do
BlockWrite(F,HVAFile.TransformMatrixs[x],Sizeof(TTransformMatrix),wrote);
{$ifdef DEBUG_HVA_FILE}
showmessage(inttostr(wrote));
{$endif}
// Clear memory
CloseFile(f);
TFilename := '';
end;
Function GetTMValue(const HVAFile : THVA; Row,Col,Section,Frames : integer) : single;
begin
Result := HVAFile.TransformMatrixs[Frames*HVAFile.Header.N_Sections+Section][Row][Col];
end;
Function ApplyMatrix(const HVAFile : THVA; const VoxelFile : TVoxel; Scale : TVector3f; Section, Frames : Integer) : TVector3f;
var
Matrix : TGLMatrixf4;
begin
if Section = -1 then
begin
Exit;
end;
HVAScale := VoxelFile.Section[Section].Tailer.Det;
Matrix[0,0] := GetTMValue(HVAFile,1,1,Section,Frames);
Matrix[0,1] := GetTMValue(HVAFile,2,1,Section,Frames);
Matrix[0,2] := GetTMValue(HVAFile,3,1,Section,Frames);
Matrix[0,3] := 0;
Matrix[1,0] := GetTMValue(HVAFile,1,2,Section,Frames);
Matrix[1,1] := GetTMValue(HVAFile,2,2,Section,Frames);
Matrix[1,2] := GetTMValue(HVAFile,3,2,Section,Frames);
Matrix[1,3] := 0;
Matrix[2,0] := GetTMValue(HVAFile,1,3,Section,Frames);
Matrix[2,1] := GetTMValue(HVAFile,2,3,Section,Frames);
Matrix[2,2] := GetTMValue(HVAFile,3,3,Section,Frames);
Matrix[2,3] := 0;
Matrix[3,0] := (GetTMValue(HVAFile,1,4,Section,Frames)* HVAScale) * Scale.X * 2;
Matrix[3,1] := (GetTMValue(HVAFile,2,4,Section,Frames)* HVAScale) * Scale.Y * 2;
Matrix[3,2] := (GetTMValue(HVAFile,3,4,Section,Frames)* HVAScale) * Scale.Z * 2;
Matrix[3,3] := 1;
glMultMatrixf(@Matrix[0,0]);
end;
Function ApplyMatrixToVector(const HVAFile : THVA; const VoxelFile : TVoxel; Position, Scale : TVector3f; Section, Frames : Integer) : TVector3f;
begin
if Section = -1 then
begin
Result := Position;
Exit;
end;
HVAScale := VoxelFile.Section[Section].Tailer.Det;
Result.X := (Position.X * GetTMValue(HVAFile,1,1,Section,Frames) + Position.Y * GetTMValue(HVAFile,1,2,Section,Frames) + Position.Z * GetTMValue(HVAFile,1,3,Section,Frames) + Scale.x * GetTMValue(HVAFile,1,4,Section,Frames) * HVAScale);
Result.Y := (Position.X * GetTMValue(HVAFile,2,1,Section,Frames) + Position.Y * GetTMValue(HVAFile,2,2,Section,Frames) + Position.Z * GetTMValue(HVAFile,2,3,Section,Frames) + Scale.y * GetTMValue(HVAFile,2,4,Section,Frames) * HVAScale);
Result.Z := (Position.X * GetTMValue(HVAFile,3,1,Section,Frames) + Position.Y * GetTMValue(HVAFile,3,2,Section,Frames) + Position.Z * GetTMValue(HVAFile,3,3,Section,Frames) + Scale.z * GetTMValue(HVAFile,3,4,Section,Frames) * HVAScale);
end;
Procedure ClearMatrix(Var TM : TTransformMatrix);
var
x,y : integer;
begin
for x := 1 to 3 do
for y := 1 to 4 do
TM[x][y] := 0;
TM[1][1] := 1;
TM[2][2] := 1;
TM[3][3] := 1;
end;
Function CreateTM : TTransformMatrix;
var
x,y : integer;
begin
for x := 1 to 3 do
for y := 1 to 4 do
Result[x][y] := 0;
Result[1][1] := 1;
Result[2][2] := 1;
Result[3][3] := 1;
end;
Procedure SetCharArray(const Name : String; Var CharArr : Array of Char);
const
MAX_LEN = 16;
var
i: integer;
begin
for i:=1 to 16 do
CharArr[i]:=' ';
for i := 1 to Length(Name) do
begin
if i > MAX_LEN then
break;
CharArr[i] := Name[i];
end;
end;
Procedure CreateHVA(const Vxl : TVoxel; var HVA : THVA);
var
i,x : integer;
//S : string;
begin
if (Vxl = nil) or (not Vxl.Loaded) then
exit;
HVA.Header.N_Frames := 1;
HVA.Header.N_Sections := Vxl.Header.NumSections;
{S := 'OS_HVA_BUILDER ';
for i := 1 to length(S) do
HVA.Header.FilePath[i] := s[i]; }
//SetCharArray('OS_HVA_BUILDER',HVA.Header.FilePath);
for x := 1 to 16 do
HVAFile.Header.FilePath[x] := #0;
HVA.Data_no := HVA.Header.N_Sections;
Setlength(HVA.Data,HVA.Data_no);
for i := 0 to Vxl.Header.NumSections-1 do
for x := 1 to 16 do
HVA.Data[i].SectionName[x] := vxl.section[i].Header.Name[x];
Setlength(HVA.TransformMatrixs,HVA.Data_no);
for i := 0 to Vxl.Header.NumSections-1 do
HVA.TransformMatrixs[i] := CreateTM;
end;
Procedure SetHVAPos(Var HVA : THVA; Const Section : Integer; X,Y,Z : single);
var
HVAD : integer;
begin
HVAD := HVAFrame*HVA.Header.N_Sections+Section;
HVA.TransformMatrixs[HVAD][1][4] := HVA.TransformMatrixs[HVAD][1][4] + (X);
HVA.TransformMatrixs[HVAD][2][4] := HVA.TransformMatrixs[HVAD][2][4] + (Y);
HVA.TransformMatrixs[HVAD][3][4] := HVA.TransformMatrixs[HVAD][3][4] + (Z);
end;
Procedure SetHVAPos2(Var HVA : THVA; Const Voxel : TVoxel; Section : Integer; Position : TVector3f);
var
HVAD : integer;
Det : single;
begin
HVAD := HVAFrame*HVA.Header.N_Sections+Section;
Det := Voxel.Section[Section].Tailer.Det;
HVA.TransformMatrixs[HVAD][1][4] := Position.X / Det;
HVA.TransformMatrixs[HVAD][2][4] := Position.Y / Det;
HVA.TransformMatrixs[HVAD][3][4] := Position.Z / Det;
end;
Function GetHVAPos(const HVA : THVA; const Voxel : TVoxel; Section : Integer) : TVector3f;
var
HVAD : integer;
Det : single;
begin
HVAD := HVAFrame*HVA.Header.N_Sections+Section;
Det := Voxel.Section[Section].Tailer.Det;
Result := SetVector(0,0,0);
if HVA.TransformMatrixs[HVAD][1][4] > 0 then
Result.X := HVA.TransformMatrixs[HVAD][1][4] * Det;
if HVA.TransformMatrixs[HVAD][2][4] > 0 then
Result.Y := HVA.TransformMatrixs[HVAD][2][4] * Det;
if HVA.TransformMatrixs[HVAD][3][4] > 0 then
Result.Z := HVA.TransformMatrixs[HVAD][3][4] * Det;
end;
Procedure AddHVAFrame(Var HVAFile : THVA);
var
x : integer;
begin
HVAFile.Header.N_Frames := HVAFile.Header.N_Frames + 1;
SetLength(HVAFile.TransformMatrixs,HVAFile.Header.N_Frames*HVAFile.Header.N_Sections);
for x := 0 to HVAFile.Header.N_Sections-1 do
HVAFile.TransformMatrixs[(HVAFile.Header.N_Frames-1)*HVAFile.Header.N_Sections+x] := CreateTM;
end;
Function HVAToMatrix(const HVAFile : THVA; Section,Frames : Integer) : TMatrix;
var
x,y : integer;
begin
Result := IdentityMatrix;
for x := 1 to 3 do
for y := 1 to 4 do
Result[x-1][y-1] := GetTMValue(HVAFile,x,y,Section,Frames);
end;
Procedure MatrixToHVA(var HVAFile : THVA; const M : TMatrix; Section : Integer);
var
x,y : integer;
begin
for x := 1 to 3 do
for y := 1 to 4 do
HVAFile.TransformMatrixs[HVAFrame*HVAFile.Header.N_Sections+Section][x][y] := m[x-1][y-1];
end;
Function GETHVAAngle_RAD(const HVAFile : THVA; Section,Frames : Integer) : TVector3f;
var
M : TMatrix;
T : TTransformations;
begin
M := HVAToMatrix(HVAFile,Section,Frames);
MatrixDecompose(M,T);
Result.X := T[ttRotateX];
Result.Y := T[ttRotateY];
Result.Z := T[ttRotateZ];
{
for x := 0 to 2 do
M[3][x] := 0;
M[3][3] := 1; }
{
SETHVATM(HVAFile,Section,1,1,CosAngles.Y*CosAngles.Z);
SETHVATM(HVAFile,Section,1,2,-(CosAngles.Y*SinAngles.Z));
SETHVATM(HVAFile,Section,1,3,-(SinAngles.Y));
SETHVATM(HVAFile,Section,2,1,(CosAngles.X*SinAngles.Z)-(SinAngles.X*SinAngles.Y*CosAngles.Z));
SETHVATM(HVAFile,Section,2,2,(SinAngles.X*SinAngles.Y*SinAngles.Z)+(CosAngles.X*CosAngles.Z));
SETHVATM(HVAFile,Section,2,3,-(SinAngles.X*CosAngles.Y));
SETHVATM(HVAFile,Section,3,1,(CosAngles.X*SinAngles.Y*CosAngles.Z)+(SinAngles.X*SinAngles.Z));
SETHVATM(HVAFile,Section,3,2,(SinAngles.X*CosAngles.Z)-(CosAngles.X*SinAngles.Y*SinAngles.Z));
SETHVATM(HVAFile,Section,3,3,(CosAngles.X*CosAngles.Y));}
{
Y := ArcSin(-GetTMValue2(HVAFile,1,3,Section));
cy := Cos(Y);
Z := ArcSin((-GetTMValue2(HVAFile,1,2,Section))/cy);
X := ArcSin((-GetTMValue2(HVAFile,2,3,Section))/cy);
Result.X := X;
Result.Y := Y;
Result.Z := Z; }
end;
Function GETHVAAngle_DEG(const HVAFile : THVA; Section,Frames : Integer) : TVector3f;
var
Angles : TVector3f;
begin
Angles := GETHVAAngle_RAD(HVAFile,Section,Frames);
Result.X := RadToDeg(Angles.X);
Result.Y := RadToDeg(Angles.Y);
Result.Z := RadToDeg(Angles.Z);
end;
Function CorrectAngle(Angle : Single) : Single;
begin
Angle := RadToDeg(Angle);
If Angle < -90 then
Angle := 180 + Angle;
If Angle > 90 then
Angle := 90 - Angle;
Result := DegToRad(Angle);
end;
Function CorrectAngles(Angle : TVector3f) : TVector3f;
var
Angles : TVector3f;
begin
Angles.X := CorrectAngle(Angle.X);
Angles.Y := CorrectAngle(Angle.Y);
Angles.Z := CorrectAngle(Angle.Z);
Result := Angles;
end;
Procedure SETHVATM(var HVAFile : THVA; const Section,Row,Col : Integer; Value : single);
begin
HVAFile.TransformMatrixs[HVAFrame*HVAFile.Header.N_Sections+Section][Row][Col] := Value;
end;
Function SETHVAAngle(var HVAFile : THVA; const Section,Frames : Integer; x,y,z : single) : TVector3f;
var
M : TMatrix;
begin
M := HVAToMatrix(HVAFile,Section,Frames);
M := Pitch(M,DegtoRad(X));
M := Turn(M,DegtoRad(Y));
M := Roll(M,DegtoRad(Z));
MatrixToHVA(HVAFile,M,Section);
end;
Function SETHVAAngle2(var HVAFile : THVA; const Section,Frames : Integer; x,y,z : single) : TVector3f;
var
Angles,NewAngles,N : TVector3f;
M : TMatrix;
begin
M := HVAToMatrix(HVAFile,Section,Frames);
Angles := GETHVAAngle_DEG(HVAFile,Section,Frames);
NewAngles.X := X;
NewAngles.Y := Y;
NewAngles.Z := Z;
N := SubtractVector(NewAngles,Angles);
M := Pitch(M,DegtoRad(N.X));
M := Turn(M,DegtoRad(N.Y));
M := Roll(M,DegtoRad(N.Z));
MatrixToHVA(HVAFile,M,Section);
{
Angles.X := DegToRad(X);
Angles.Y := DegToRad(Y);
Angles.Z := DegToRad(Z);
CosAngles.X := Cos(Angles.X);
CosAngles.Y := Cos(Angles.Y);
CosAngles.Z := Cos(Angles.Z);
SinAngles.X := Sin(Angles.X);
SinAngles.Y := Sin(Angles.Y);
SinAngles.Z := Sin(Angles.Z);
SETHVATM(HVAFile,Section,1,1,CosAngles.Y*CosAngles.Z);
SETHVATM(HVAFile,Section,1,2,-(CosAngles.Y*SinAngles.Z));
SETHVATM(HVAFile,Section,1,3,-(SinAngles.Y));
SETHVATM(HVAFile,Section,2,1,(CosAngles.X*SinAngles.Z)-(SinAngles.X*SinAngles.Y*CosAngles.Z));
SETHVATM(HVAFile,Section,2,2,(SinAngles.X*SinAngles.Y*SinAngles.Z)+(CosAngles.X*CosAngles.Z));
SETHVATM(HVAFile,Section,2,3,-(SinAngles.X*CosAngles.Y));
SETHVATM(HVAFile,Section,3,1,(CosAngles.X*SinAngles.Y*CosAngles.Z)+(SinAngles.X*SinAngles.Z));
SETHVATM(HVAFile,Section,3,2,(SinAngles.X*CosAngles.Z)-(CosAngles.X*SinAngles.Y*SinAngles.Z));
SETHVATM(HVAFile,Section,3,3,(CosAngles.X*CosAngles.Y));
}
end;
Procedure InsertHVAFrame(Var HVAFile : THVA);
var
x,y,z,i,Frames : integer;
TransformMatrixs : array of TTransformMatrix;
begin
If @HVAFile = @HVABarrel then
Frames := HVAFrameB
else If @HVAFile = @HVATurret then
Frames := HVAFrameT
else
Frames := HVAFrame;
SetLength(TransformMatrixs,HVAFile.Header.N_Frames*HVAFile.Header.N_Sections);
for x := 0 to HVAFile.Header.N_Frames-1 do
for i := 0 to HVAFile.Header.N_Sections-1 do
for y := 1 to 3 do
for z := 1 to 4 do
TransformMatrixs[x*HVAFile.Header.N_Sections+i][y][z] := HVAFile.TransformMatrixs[x*HVAFile.Header.N_Sections+i][y][z];
Inc(HVAFile.Header.N_Frames);
SetLength(HVAFile.TransformMatrixs,HVAFile.Header.N_Frames*HVAFile.Header.N_Sections);
if Frames > 0 then
for x := 0 to Frames do
for i := 0 to HVAFile.Header.N_Sections-1 do
for y := 1 to 3 do
for z := 1 to 4 do
HVAFile.TransformMatrixs[x*HVAFile.Header.N_Sections+i][y][z] := TransformMatrixs[x*HVAFile.Header.N_Sections+i][y][z];
for i := 0 to HVAFile.Header.N_Sections-1 do
HVAFile.TransformMatrixs[(Frames+1)*HVAFile.Header.N_Sections+i] := CreateTM;
if Frames+1 < HVAFile.Header.N_Frames-1 then
for x := Frames+2 to HVAFile.Header.N_Frames-1 do
for i := 0 to HVAFile.Header.N_Sections-1 do
for y := 1 to 3 do
for z := 1 to 4 do
HVAFile.TransformMatrixs[x*HVAFile.Header.N_Sections+i][y][z] := TransformMatrixs[(x-1)*HVAFile.Header.N_Sections+i][y][z];
// Clear memory
SetLength(TransformMatrixs,0);
end;
Procedure CopyHVAFrame(Var HVAFile : THVA);
var
y,z,i,Frames : integer;
begin
If @HVAFile = @HVABarrel then
Frames := HVAFrameB
else If @HVAFile = @HVATurret then
Frames := HVAFrameT
else
Frames := HVAFrame;
InsertHVAFrame(HVAFile);
for i := 0 to HVAFile.Header.N_Sections-1 do
for y := 1 to 3 do
for z := 1 to 4 do
HVAFile.TransformMatrixs[(Frames+1)*HVAFile.Header.N_Sections+i][y][z] := HVAFile.TransformMatrixs[(Frames)*HVAFile.Header.N_Sections+i][y][z];
end;
Procedure DeleteHVAFrame(Var HVAFile : THVA);
var
x,y,z,i,Frames : integer;
TransformMatrixs : array of TTransformMatrix;
begin
If @HVAFile = @HVABarrel then
Frames := HVAFrameB
else If @HVAFile = @HVATurret then
Frames := HVAFrameT
else
Frames := HVAFrame;
SetLength(TransformMatrixs,HVAFile.Header.N_Frames*HVAFile.Header.N_Sections);
for x := 0 to HVAFile.Header.N_Frames-1 do
for i := 0 to HVAFile.Header.N_Sections-1 do
for y := 1 to 3 do
for z := 1 to 4 do
TransformMatrixs[x*HVAFile.Header.N_Sections+i][y][z] := HVAFile.TransformMatrixs[x*HVAFile.Header.N_Sections+i][y][z];
if Frames > 0 then
for x := 0 to Frames do
for i := 0 to HVAFile.Header.N_Sections-1 do
for y := 1 to 3 do
for z := 1 to 4 do
HVAFile.TransformMatrixs[x*HVAFile.Header.N_Sections+i][y][z] := TransformMatrixs[x*HVAFile.Header.N_Sections+i][y][z];
Dec(HVAFile.Header.N_Frames);
SetLength(HVAFile.TransformMatrixs,HVAFile.Header.N_Frames*HVAFile.Header.N_Sections);
for x := Frames+1 to HVAFile.Header.N_Frames-1 do
for i := 0 to HVAFile.Header.N_Sections-1 do
for y := 1 to 3 do
for z := 1 to 4 do
HVAFile.TransformMatrixs[(x-1)*HVAFile.Header.N_Sections+i][y][z] := TransformMatrixs[x*HVAFile.Header.N_Sections+i][y][z];
end;
Function GetCurrentFrame : Integer;
begin
if HVACurrentFrame = 1 then
Result := HVAFrameT
else if HVACurrentFrame = 2 then
Result := HVAFrameB
else
Result := HVAFrame;
end;
Function GetCurrentFrame2(_Type : Integer) : Integer;
begin
Result := 0;
if HVACurrentFrame <> _Type then exit;
if HVACurrentFrame = 1 then
Result := HVAFrameT
else if HVACurrentFrame = 2 then
Result := HVAFrameB
else
Result := HVAFrame;
end;
procedure SetCurrentFrame(Value : Integer);
begin
if HVACurrentFrame = 1 then
HVAFrameT := Value
else if HVACurrentFrame = 2 then
HVAFrameB := Value
else
HVAFrame := Value;
end;
Function GetCurrentHVA : PHVA;
begin
if HVACurrentFrame = 1 then
Result := @HVATurret
else if HVACurrentFrame = 2 then
Result := @HVABarrel
else
Result := @HVAFile;
end;
Function GetCurrentHVAB : Boolean;
begin
if HVACurrentFrame = 1 then
Result := HVAOpenT
else if HVACurrentFrame = 2 then
Result := HVAOpenB
else
Result := HVAOpen;
end;
end.
|
unit UDemoBitmaps2Video;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UBitmaps2Video, Vcl.StdCtrls,
Vcl.Imaging.jpeg, Vcl.ExtCtrls, Vcl.Samples.Spin, Vcl.ComCtrls,
Vcl.Imaging.pngImage,
Vcl.ExtDlgs, UFormats, FFMPeg;
type
TForm1 = class(TForm)
Edit1: TEdit;
Button2: TButton;
Label1: TLabel;
SD: TSaveDialog;
SpinEdit1: TSpinEdit;
Label2: TLabel;
Label3: TLabel;
HC: TComboBox;
OPD: TOpenPictureDialog;
OD: TOpenDialog;
Label6: TLabel;
CodecCombo: TComboBox;
Label7: TLabel;
RateCombo: TComboBox;
Label8: TLabel;
FormatCombo: TComboBox;
Button5: TButton;
OVD: TOpenDialog;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
TabSheet3: TTabSheet;
TabSheet4: TTabSheet;
Image1: TImage;
Button3: TButton;
rgrpZoom: TRadioGroup;
Button1: TButton;
Label4: TLabel;
ProgressBar1: TProgressBar;
Label9: TLabel;
Button7: TButton;
Button6: TButton;
Button4: TButton;
Label5: TLabel;
Label10: TLabel;
RadioGroup1: TRadioGroup;
Label11: TLabel;
Label12: TLabel;
Label13: TLabel;
Label14: TLabel;
Memo1: TMemo;
Label15: TLabel;
Label16: TLabel;
ProgressBar2: TProgressBar;
MemoProps: TMemo;
Image2: TImage;
FrameSpin: TSpinEdit;
Label17: TLabel;
Label18: TLabel;
BgCombo: TComboBox;
EditVideoFile: TEdit;
Label19: TLabel;
Button8: TButton;
Button9: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure FormatComboChange(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure HCChange(Sender: TObject);
procedure RateComboChange(Sender: TObject);
procedure SpinEdit1Change(Sender: TObject);
procedure CodecComboChange(Sender: TObject);
procedure Button6Click(Sender: TObject);
procedure Button7Click(Sender: TObject);
procedure FrameSpinChange(Sender: TObject);
procedure Button8Click(Sender: TObject);
private
fVideoFile: string;
procedure UpdateCodecCombo;
procedure UpdateSizeinMB;
procedure InsertVideo(UpdateProc: TVideoProgressEvent);
{ Private declarations }
public
{ Public declarations }
VideoAspect: double;
TheProgressbar: TProgressBar;
procedure UpdateVideo(Videotime: int64);
procedure UpdateVideoThreaded(Videotime: int64);
end;
// Example for a new TCodecSetupClass
TRawSetup = class(TBaseCodecSetup)
public
Constructor Create(CodecID: TAVCodecID); override;
// for raw video the bitrate is automatic, so we return 0
function QualityToBitrate(Quality: byte; Width, Height, Rate: integer)
: int64; override;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses mmSystem, System.Types, math, UTools, Winapi.ShlObj, Winapi.ActiveX,
System.Threading;
const
Aspects: array [0 .. 2] of double = (16 / 9, 4 / 3, 3 / 2);
BgColors: array [0 .. 3] of byte = (0, 255, 40, 180);
function PIDLToPath(IdList: PItemIDList): string;
begin
SetLength(Result, MAX_PATH);
if SHGetPathFromIdList(IdList, PChar(Result)) then
SetLength(Result, StrLen(PChar(Result)))
else
Result := '';
end;
function PidlFree(var IdList: PItemIDList): boolean;
var
Malloc: IMalloc;
begin
Result := false;
if IdList = nil then
Result := true
else
begin
if Succeeded(SHGetMalloc(Malloc)) and (Malloc.DidAlloc(IdList) > 0) then
begin
Malloc.Free(IdList);
IdList := nil;
Result := true;
end;
end;
end;
function GetDesktopFolder: string;
var
FolderPidl: PItemIDList;
begin
if Succeeded(SHGetSpecialFolderLocation(0, $0000, FolderPidl)) then
begin
Result := PIDLToPath(FolderPidl);
PidlFree(FolderPidl);
end
else
Result := '';
end;
procedure TForm1.Button1Click(Sender: TObject);
var
bm: TBitmap;
bme: TBitmapEncoder;
h, w, bw, bh: integer;
t: int64;
fps: double;
ZoomTarget, ZoomSource, ZoomTarget2: TZoom;
ZoomOption: TZoomOption;
begin
if (not assigned(Image1.Picture.Graphic)) then
begin
Vcl.Dialogs.ShowMessage('Load a picture first');
exit;
end;
VideoAspect := Aspects[RadioGroup1.ItemIndex];
t := TimeGetTime;
bm := TBitmap.Create;
try
bm.Assign(Image1.Picture.Graphic);
bm.PixelFormat := pf32bit;
bw := bm.Width;
bh := bm.Height;
h := StrToInt(HC.Text);
w := round(h * VideoAspect);
if odd(w) then
w := w - 1;
ZoomSource := MakeZoom(0, 0, 1);
// half of original size, offset by left, top which are random in the top-left quarter
ZoomTarget2 := MakeZoom(0.5 * random, 0.5 * random, 0.5);
// 0.3 times original size, centered
ZoomTarget := MakeZoom(0.35, 0.35, 0.3);
ZoomOption := zoAAx2; // eliminate compiler warning
case rgrpZoom.ItemIndex of
0:
ZoomOption := zoAAx2;
1:
ZoomOption := zoAAx4;
2:
ZoomOption := zoAAx6;
3:
ZoomOption := zoResample;
end;
bme := TBitmapEncoder.Create(Edit1.Text + FormatCombo.Text, w, h,
StrToInt(RateCombo.Text), SpinEdit1.Value,
TAVCodecID(CodecCombo.Items.Objects[CodecCombo.ItemIndex]), vsBiCubic,
BgColors[BgCombo.ItemIndex]);
// vsBiCubic: if it needs to scale it scales nicely
try
TheProgressbar := ProgressBar1;
ProgressBar1.Max := 19000;
ProgressBar1.Position := 0;
bme.OnProgress := UpdateVideo;
// 20 seconds of movie
bme.AddStillImage(bm, 1000);
bme.ZoomPan(bm, ZoomSource, ZoomTarget, 6000, ZoomOption, zeFastSlow);
bme.Freeze(1000);
bme.ZoomPan(bm, ZoomTarget, ZoomTarget2, 5000, ZoomOption, zeSlowSlow);
bme.Freeze(1000);
bme.ZoomPan(bm, ZoomTarget2, ZoomSource, 5000, ZoomOption, zeSlowFast);
bme.Freeze(1000);
bme.CloseFile; // movie should be done
t := TimeGetTime - t;
fps := 1000 * bme.framecount / t;
finally
bme.Free;
end;
finally
bm.Free;
end;
Label4.Caption := 'Writing Speed: ' + FloatToStrF(fps, ffFixed, 5, 2)
+ ' fps';
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
if SD.Execute then
begin
Edit1.Text := Copy(SD.FileName, 1, length(SD.FileName) -
length(ExtractFileExt(SD.FileName)));
FormatCombo.ItemIndex := FormatCombo.Items.IndexOf
(ExtractFileExt(SD.FileName));
UpdateCodecCombo;
end;
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
if OPD.Execute then
Image1.Picture.LoadFromFile(OPD.FileName);
end;
procedure TForm1.Button4Click(Sender: TObject);
var
Tempfile, Videofile, Audiofile: string;
begin
if not OD.Execute then
exit;
Try
Label5.Caption := 'Writing audio';
Audiofile := OD.FileName;
Videofile := Edit1.Text + FormatCombo.Text;
if not FileExists(Videofile) then
begin
ShowMessage('Make a Movie first');
exit;
end;
Tempfile := GetTempFolder + '\_VideoTemp' + ExtractFileExt(Videofile);
CopyFile(PWideChar(Videofile), PWideChar(Tempfile), false);
MuxStreams2(Tempfile, Audiofile, Videofile);
DeleteFile(Tempfile);
Label5.Caption := 'Audio track now contains ' + ExtractFilename(Audiofile);
except
ShowMessage('Audio format not supported by container format ' +
ExtractFileExt(Videofile));
// Restore orignal video
CopyFile(PWideChar(Tempfile), PWideChar(Videofile), false);
End;
end;
procedure TForm1.Button5Click(Sender: TObject);
begin
if RegisterEncoder(AV_CODEC_ID_RAWVIDEO, TRawSetup, false) then
MessageBeep(0);
UpdateCodecCombo;
end;
procedure TextOnBitmap(const bm: TBitmap; const _text: string);
var
r: TRect;
r1: TRectF;
begin
bm.Canvas.Lock;
try
bm.Canvas.Font.Color := clWhite;
bm.Canvas.Brush.style := bsClear;
bm.Canvas.Font.Size := 32;
r := Rect(0, 0, bm.Width, bm.Height);
DrawText(bm.Canvas.Handle, PChar(_text), length(_text), r,
dt_Center or dt_CalcRect);
r1 := TRectF(r);
CenterRect(r1, RectF(0, 0, bm.Width, bm.Height));
r := r1.round;
DrawText(bm.Canvas.Handle, PChar(_text), length(_text), r, dt_Center);
Finally
bm.Canvas.Unlock;
End;
end;
procedure BlackBitmap(const bm: TBitmap; w, h: integer);
begin
bm.PixelFormat := pf32bit;
bm.SetSize(w, h);
bm.Canvas.Lock; // necessary for threads
BitBlt(bm.Canvas.Handle, 0, 0, w, h, 0, 0, 0, BLACKNESS);
bm.Canvas.Unlock;
end;
procedure TForm1.Button6Click(Sender: TObject);
var
bme: TBitmapEncoder;
bm: TBitmap;
begin
if not OVD.Execute then
exit;
Label15.Caption := 'Working';
Label15.Repaint;
bme := TBitmapEncoder.CreateFromVideo(OVD.FileName, Edit1.Text, vsBiCubic,
BgColors[BgCombo.ItemIndex]);
try
bm := TBitmap.Create;
try
BlackBitmap(bm, bme.VideoWidth, bme.VideoHeight);
TextOnBitmap(bm, 'End Slide Added');
bme.AddStillImage(bm, 4000);
finally
bm.Free;
end;
bme.CloseFile;
finally
bme.Free;
end;
Label15.Caption := 'Done';
end;
procedure TForm1.Button7Click(Sender: TObject);
var
P: TVideoProps;
begin
if not OVD.Execute then
exit;
fVideoFile := OVD.FileName;
EditVideoFile.Text := fVideoFile;
FrameSpinChange(nil);
P := GetVideoProps(fVideoFile);
MemoProps.Clear;
With MemoProps.Lines do
begin
add('Properties of');
add(ExtractFilename(fVideoFile) + ':');
add('Width: ' + IntTostr(P.Width));
add('True Height: ' + IntTostr(P.TrueHeight));
add('Frame rate: ' + IntTostr(P.FrameRate));
add('No. video streams: ' + IntTostr(P.nrVideostreams));
add('No. audio streams: ' + IntTostr(P.nrAudiostreams));
add('Duration: ' + FloatToStrF(0.001 * P.Duration, ffFixed, 8, 2) + ' sec');
add('Video codec: ' + avCodec_Find_Decoder(P.VideoCodec).name);
end;
end;
procedure TForm1.Button8Click(Sender: TObject);
var
UpdateProc: TVideoProgressEvent;
aTask: iTask;
begin
Label12.Caption := 'Working';
Label12.Repaint;
ProgressBar2.Max := GetVideoTime(fVideoFile);
ProgressBar2.Position := 0;
TheProgressbar := ProgressBar2;
if Sender = Button8 then
begin
UpdateProc := UpdateVideo;
InsertVideo(UpdateProc);
end
else
begin
UpdateProc := UpdateVideoThreaded;
aTask := TTask.Create(
procedure
begin
InsertVideo(UpdateProc);
end);
aTask.Start;
end;
end;
procedure TForm1.InsertVideo(UpdateProc: TVideoProgressEvent);
var
bm: TBitmap;
w, h: integer;
bme: TBitmapEncoder;
t: int64;
f: integer;
begin
t := TimeGetTime;
VideoAspect := Aspects[RadioGroup1.ItemIndex];
bm := TBitmap.Create;
try
h := StrToInt(HC.Text);
w := round(VideoAspect * h);
// video sizes must be even
if odd(w) then
dec(w);
// load the 1st frame from the video
try
GrabFrame(bm, fVideoFile, 1);
except
// We catch the exception, since GrabFrame does not
// yet work reliably with foreign video content
BlackBitmap(bm, w, h);
end;
bme := TBitmapEncoder.Create(Edit1.Text + FormatCombo.Text, w, h,
StrToInt(RateCombo.Text), SpinEdit1.Value,
TAVCodecID(CodecCombo.Items.Objects[CodecCombo.ItemIndex]), vsBiCubic,
BgColors[BgCombo.ItemIndex]);
try
bme.OnProgress := UpdateProc;
TextOnBitmap(bm, 'Intro Screen');
bme.AddStillImage(bm, 5000);
bme.AddVideo(fVideoFile);
// bme.LastVideoFrameCount always contains the frame count of the last
// added video.
try
GrabFrame(bm, fVideoFile, bme.LastVideoFrameCount - 2);
except
BlackBitmap(bm, w, h);
end;
TextOnBitmap(bm, 'The End');
bme.AddStillImage(bm, 5000);
f:=bme.FrameCount;
bme.CloseFile;
finally
bme.Free;
end;
finally
bm.Free;
end;
t:=TimeGetTime-t;
TThread.Synchronize(TThread.Current,
procedure
begin
Label12.Caption := 'Writing speed: '#13+FloatToStrF(1000*f/t,ffFixed,6,2)+' fps';
end);
end;
procedure TForm1.CodecComboChange(Sender: TObject);
begin
UpdateSizeinMB;
end;
procedure TForm1.UpdateCodecCombo;
var
Index: integer;
begin
ListSupportedCodecs(FormatCombo.Text, CodecCombo.Items, Index);
if Index >= 0 then
CodecCombo.ItemIndex := Index;
end;
procedure TForm1.UpdateSizeinMB;
var
VideoWidth: integer;
begin
if (Image1.Picture = nil) or (Image1.Picture.Height = 0) then
exit;
VideoWidth := round(StrToInt(HC.Text) * Image1.Picture.Width /
Image1.Picture.Height);
Label9.Caption := FloatToStrF(VideoSizeinMB(30000,
TAVCodecID(CodecCombo.Items.Objects[CodecCombo.ItemIndex]), VideoWidth,
StrToInt(HC.Text), StrToInt(RateCombo.Text), SpinEdit1.Value), ffFixed, 6,
2) + ' MB';
end;
procedure TForm1.FormatComboChange(Sender: TObject);
begin
UpdateCodecCombo;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Edit1.Text := GetDesktopFolder + '\Example';
ListSupportedFileFormats(FormatCombo.Items);
FormatCombo.ItemIndex := 1;
UpdateCodecCombo;
if FileExists('GoodTestPicture.png') then
Image1.Picture.LoadFromFile('GoodTestPicture.png');
UpdateSizeinMB;
VideoAspect := 16 / 9;
Randomize;
end;
procedure TForm1.FrameSpinChange(Sender: TObject);
var
bm: TBitmap;
begin
if not FileExists(fVideoFile) then
exit;
bm := TBitmap.Create;
try
GrabFrame(bm, fVideoFile, FrameSpin.Value);
Image2.Picture.Bitmap := bm;
finally
bm.Free;
end;
end;
procedure TForm1.HCChange(Sender: TObject);
begin
UpdateSizeinMB;
end;
procedure TForm1.RateComboChange(Sender: TObject);
begin
UpdateSizeinMB;
end;
procedure TForm1.SpinEdit1Change(Sender: TObject);
begin
UpdateSizeinMB;
end;
procedure TForm1.UpdateVideo(Videotime: int64);
begin
TheProgressbar.Position := Videotime;
TheProgressbar.Update;
end;
procedure TForm1.UpdateVideoThreaded(Videotime: int64);
begin
TThread.Synchronize(TThread.Current,
procedure
begin
TheProgressbar.Position := Videotime;
TheProgressbar.Update;
end);
end;
{ TRawSetup }
constructor TRawSetup.Create(CodecID: TAVCodecID);
begin
inherited;
fPreferredOutputPixelFormat := AV_PIX_FMT_YUV420P;
end;
function TRawSetup.QualityToBitrate(Quality: byte;
Width, Height, Rate: integer): int64;
begin
Result := 0;
end;
initialization
ReportMemoryLeaksOnShutDown := true;
end.
|
(* ADS Unit Test 2 19.04.2017 *)
(* ---------- *)
(* *)
(* ================================================== *)
PROGRAM StackTADS2;
USES
StackADT2;
VAR
s1, s2: Stack;
e: INTEGER;
i: INTEGER;
BEGIN
NewStack(s1);
NewStack(s2);
FOR i := 1 TO 10 DO BEGIN
WriteLn('Push: ',i);
Push(s1, i);
END;
FOR i := 1 TO 10 DO BEGIN
WriteLn('Push2: ',i*i);
Push(s2, i*i);
END;
FOR i := 1 TO 10 DO BEGIN
Pop(s2, e);
WriteLn('Pop2: ',e);
END;
FOR i := 1 TO 10 DO BEGIN
Pop(s1, e);
WriteLn('Pop: ',e);
END;
DisposeStack(s1);
DisposeStack(s2);
END. (* StackTADS2 *) |
//------------------------------------------------------------------------------
//The contents of this file are subject to the Mozilla Public License
//Version 1.1 (the "License"); you may not use this file except in compliance
//with the License. You may obtain a copy of the License at
//http://www.mozilla.org/MPL/ Software distributed under the License is
//distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
//or implied. See the License for the specific language governing rights and
//limitations under the License.
//
//The Original Code is SndTypes.pas.
//
//The Initial Developer of the Original Code is Alex Shovkoplyas, VE3NEA.
//Portions created by Alex Shovkoplyas are
//Copyright (C) 2008 Alex Shovkoplyas. All Rights Reserved.
//------------------------------------------------------------------------------
unit SndTypes;
interface
uses
SysUtils;
const
TWO_PI = 2 * Pi;
type
TComplex = record Re, Im: Single; end;
TIntegerArray = array of integer;
TSingleArray = array of Single;
TDataBufferF = array of TSingleArray;
TDataBufferI = array of TIntegerArray;
TSingleArray2D = array of TSingleArray;
TByteArray = array of Byte;
TComplexArray = array of TComplex;
implementation
end.
|
{
Aerodynamica TAsSynAutoCorrect 1.03
by Aaron Chan and Greg Nixon
http://aerodynamica2.port5.com
aerodynamica@email.com
This component can be freely distributed.
But I do have one request, that is to send
me a copy if you modify this component to
fix a bug or make it better.
Version History
---------------
1.03 -
Added a component editor, improved
property editor, tidy-up in code and
a few tweaks and bug fixes.
1.02 -
Property editor added (by Greg) and
changed to using only one TStrings for
faster performance.
1.01 -
A lot of bugs were fixed (mostly by Greg).
1.00 -
First release version of TAsSynAutoCorrect.
}
unit AsSynAutoCorrect;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
SynEditTypes, SynEditHighlighter, SynEdit, Registry, IniFiles;
type
TRecordEditorVars = record
kd: TKeyEvent;
md: TMouseEvent;
end;
PRecordEditorVars = ^TRecordEditorVars;
TAsSynAutoCorrect = class(TComponent)
private
{ Private declarations }
FAutoCorrectOnMouseDown: Boolean;
FBeepOnAutoCorrect: Boolean;
FEnabled: Boolean;
FEditor: TCustomSynEdit;
FEditVars: PRecordEditorVars;
FIgnoreCase: Boolean;
FReplaceItems: TStrings;
FOnReplaceText: TReplaceTextEvent;
PrevLine: Integer;
FMaintainCase: Boolean; // GN
// GN
function CorrectItemStart(EditLine: String; SearchString: String; StartPos: LongInt; frMatchCase, frWholeWord: Boolean): LongInt;
Function FindAndCorrect(var EditLine: String; SearchString, ReplaceText: String; var CurrentX: Integer): Boolean;
function PreviousToken: String;
function GetReplaceItems: TStrings;
procedure SetReplaceItems(const Value: TStrings);
protected
{ Protected declarations }
procedure EditorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); virtual;
procedure EditorMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); virtual;
procedure SetEditor(Value: TCustomSynEdit);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Add(sReplaceFrom: String; sReplaceTo: String);
procedure AutoCorrectAll();
procedure Delete(iItemIndex: Integer);
procedure Edit(iItemIndex: Integer; sReplaceFrom: String; sReplaceTo: String);
procedure LoadFromIni(FileName: String; Section: String);
procedure SaveToIni(FileName: String; Section: String);
procedure LoadFromRegistry(RegistryRoot: DWORD; RegistryKey: String);
procedure SaveToRegistry(RegistryRoot: DWORD; RegistryKey: String);
published
{ Published declarations }
property AutoCorrectOnMouseDown: Boolean read FAutoCorrectOnMouseDown write FAutoCorrectOnMouseDown;
property BeepOnAutoCorrect: Boolean read FBeepOnAutoCorrect write FBeepOnAutoCorrect;
property Enabled: Boolean read FEnabled write FEnabled;
property Editor: TCustomSynEdit read FEditor write SetEditor;
property IgnoreCase: Boolean read FIgnoreCase write FIgnoreCase;
property ReplaceItems: TStrings read GetReplaceItems write SetReplaceItems;
// GN
property MaintainCase: Boolean read FMaintainCase write FMaintainCase default True;
property OnReplaceText: TReplaceTextEvent read FOnReplaceText write FOnReplaceText;
end;
const
DELIMITERS: set of Byte = [0..255] - [0..32, 65..90, 96..105, 46];
NUMBERS: set of Byte = [48..57];
function HalfString(Str: String; FirstHalf: Boolean): String;
function StrLeft(const S: AnsiString; Count: Integer): AnsiString;
function StringsToStr(const List: TStrings; Sep: AnsiString): AnsiString;
procedure StrToStrings(S: AnsiString; Sep: AnsiString; const List: TStrings);
procedure Register;
implementation
uses AsSynAutoCorrectEditor, DsgnIntf;
type
TAutoCorrectionProperty = class(TPropertyEditor)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
function GetValue:string; override;
end;
TAsSynAutoCorrectComponentEditor = class(TDefaultEditor)
procedure Edit; override;
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
procedure TAsSynAutoCorrectComponentEditor.Edit;
begin
frmAutoCorrectEditor := TfrmAutoCorrectEditor.Create(Application);
frmAutoCorrectEditor.AsSynAutoCorrect := TAsSynAutoCorrect(Component);
frmAutoCorrectEditor.ShowModal;
frmAutoCorrectEditor.Free;
Designer.Modified;
end;
procedure TAsSynAutoCorrectComponentEditor.ExecuteVerb(Index: Integer);
begin
case Index of
0: Edit;
end;
end;
function TAsSynAutoCorrectComponentEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := '&Edit...';
end;
end;
function TAsSynAutoCorrectComponentEditor.GetVerbCount: Integer;
begin
Result := 1;
end;
procedure TAutoCorrectionProperty.Edit;
begin
frmAutoCorrectEditor := TfrmAutoCorrectEditor.Create(Application);
frmAutoCorrectEditor.AsSynAutoCorrect := TAsSynAutoCorrect(GetComponent(0));
frmAutoCorrectEditor.ShowModal;
frmAutoCorrectEditor.Free;
Designer.Modified;
end;
function TAutoCorrectionProperty.GetAttributes: TPropertyAttributes;
begin
GetAttributes := [paDialog, paReadOnly];
end;
function TAutoCorrectionProperty.GetValue: String;
begin
GetValue := '(AutoCorrections)';
end;
// utilities
function HalfString(Str: String; FirstHalf: Boolean): String;
var
ResultArray: array[Boolean] of String;
BreakPoint: Integer;
begin
BreakPoint := LastDelimiter(#44, Str);
if BreakPoint = 0 then
BreakPoint := MaxInt-1;
ResultArray[True] := Copy(Str, 1, BreakPoint - 1);
ResultArray[False] := Copy(Str, BreakPoint + 1, MaxInt);
Result := ResultArray[FirstHalf];
end;
function StrLeft(const S: AnsiString; Count: Integer): AnsiString;
begin
Result := Copy(S, 1, Count);
end;
function StringsToStr(const List: TStrings; Sep: AnsiString): AnsiString;
var
I, L: Integer;
begin
Result := '';
for I := 0 to List.Count - 1 do
begin
Result := Result + List[I];
Result := Result + Sep;
end;
if List.Count <> 0 then
begin
L := Length(Sep);
system.Delete(Result, Length(Result) - L + 1, L);
end;
end;
procedure StrToStrings(S: AnsiString; Sep: AnsiString; const List: TStrings);
var
I, L: Integer;
Left: AnsiString;
begin
Assert(List <> nil);
List.Clear;
L := Length(Sep);
I := Pos(Sep, S);
while (I > 0) do
begin
Left := StrLeft(S, I - 1);
List.Add(Left);
System.Delete(S, 1, I + L - 1);
I := Pos(Sep, S);
end;
if S <> '' then
List.Add(S);
end;
type
TAsCustomSynEdit = class(TCustomSynEdit);
procedure TAsSynAutoCorrect.LoadFromIni(FileName: String; Section: String);
var
Reg: TIniFile;
begin
Reg := TIniFile.Create(FileName);
try
StrToStrings(Reg.ReadString(Section, 'ReplaceItems', ''), ';', FReplaceItems);
finally
Reg.Free;
end;
end;
procedure TAsSynAutoCorrect.SaveToIni(FileName: String; Section: String);
var
Reg: TIniFile;
begin
Reg := TIniFile.Create(FileName);
try
Reg.WriteString(Section, 'ReplaceItems', StringsToStr(FReplaceItems, ';'));
finally
Reg.Free;
end;
end;
procedure TAsSynAutoCorrect.LoadFromRegistry(RegistryRoot: DWORD; RegistryKey: String);
var
Reg: TRegIniFile;
begin
Reg := TRegIniFile.Create('');
try
Reg.RootKey := RegistryRoot;
Reg.OpenKey(RegistryKey, True);
StrToStrings(Reg.ReadString('', 'ReplaceItems', ''), ';', FReplaceItems);
finally
Reg.Free;
end;
end;
procedure TAsSynAutoCorrect.SaveToRegistry(RegistryRoot: DWORD; RegistryKey: String);
var
Reg: TRegIniFile;
begin
Reg := TRegIniFile.Create('');
try
Reg.RootKey := RegistryRoot;
Reg.OpenKey(RegistryKey, True);
Reg.WriteString('', 'ReplaceItems', StringsToStr(FReplaceItems, ';'));
finally
Reg.Free;
end;
end;
procedure TAsSynAutoCorrect.SetEditor(Value: TCustomSynEdit);
begin
FEditor := Value;
if FEditor <> nil then
begin
New(FEditVars);
FEditVars.kd := Editor.OnKeyDown;
FEditVars.md := TAsCustomSynEdit(Editor).OnMouseDown;
Editor.FreeNotification(Self);
if not (csDesigning in ComponentState) then
begin
Editor.OnKeyDown := EditorKeyDown;
TAsCustomSynEdit(Editor).OnMouseDown := EditorMouseDown;
end;
end;
end;
procedure TAsSynAutoCorrect.Add(sReplaceFrom: String; sReplaceTo: String);
begin
FReplaceItems.Add(sReplaceFrom + #44 + sReplaceTo);
end;
procedure TAsSynAutoCorrect.Delete(iItemIndex: Integer);
begin
FReplaceItems.Delete(iItemIndex);
end;
procedure TAsSynAutoCorrect.Edit(iItemIndex: Integer; sReplaceFrom: String; sReplaceTo: String);
var
s: String;
begin
if (iItemIndex < 0) then Exit;
s := sReplaceFrom;
s := s + #44 + sReplaceTo;
FReplaceItems[iItemIndex] := s;
end;
procedure TAsSynAutoCorrect.AutoCorrectAll;
var
i: Integer;
EditBuf: String;
CaretX: Integer;
ReplaceFrom: String;
ReplaceTo: String;
CurrentText: String;
begin
if Editor = nil then Exit;
EditBuf := Editor.Lines.Text;
CaretX := -1;
for i := 0 to FReplaceItems.Count - 1 do
begin
CurrentText := FReplaceItems[i];
ReplaceFrom := HalfString(CurrentText, True);
ReplaceTo := HalfString(CurrentText, False);
FindAndCorrect(EditBuf, ReplaceFrom, ReplaceTo, CaretX);
end;
Editor.Lines.Text := EditBuf;
end;
procedure TAsSynAutoCorrect.EditorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
var
i: Integer;
bSuccess: Boolean;
EditBuf: String;
CaretX: Integer;
ReplaceFrom: String;
ReplaceTo: String;
CurrentText: String;
begin
if Assigned(TRecordEditorVars(FEditVars^).kd) then
TRecordEditorVars(FEditVars^).kd(Sender, Key, Shift);
if Editor = nil then Exit;
if Enabled = False then Exit;
PrevLine := Editor.CaretY;
if ((ssShift in Shift) and (Key <> 16) and (Key in DELIMITERS)) or ((Key in DELIMITERS) and not (Key in NUMBERS)) or (Key = 13) or (Key = 9) or (Key = 32) or (Key = 37) or (Key = 38) or (Key = 39) or (Key = 40) then
begin
bSuccess := False;
EditBuf := PreviousToken;
If EditBuf <> '' then begin
CaretX := Editor.CaretX;
for i := 0 to FReplaceItems.Count - 1 do begin
CurrentText := FReplaceItems[i];
ReplaceFrom := HalfString(CurrentText, True);
ReplaceTo := HalfString(CurrentText, False);
bSuccess := bSuccess or FindAndCorrect(EditBuf, ReplaceFrom, ReplaceTo, CaretX);
end;
if bSuccess then begin
if FBeepOnAutoCorrect then
MessageBeep(0);
end;
end;
end;
end;
procedure TAsSynAutoCorrect.EditorMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
i: Integer;
bSuccess: Boolean;
EditBuf: String;
CaretX: Integer;
ReplaceFrom: String;
ReplaceTo: String;
CurrentText: String;
Action: TSynReplaceAction;
begin
if Assigned(TRecordEditorVars(FEditVars^).md) then
TRecordEditorVars(FEditVars^).md(Sender, Button, Shift, X, Y);
if FAutoCorrectOnMouseDown = False then Exit;
if Editor = nil then Exit;
if Enabled = False then Exit;
if PrevLine = -1 then Exit;
bSuccess := False;
EditBuf := Editor.Lines.Strings[PrevLine - 1];
CaretX := -1;
for i := 0 to FReplaceItems.Count - 1 do
begin
CurrentText := FReplaceItems[i];
ReplaceFrom := HalfString(CurrentText,True);
ReplaceTo := HalfString(CurrentText,False);
bSuccess := bSuccess or FindAndCorrect(EditBuf, ReplaceFrom, ReplaceTo, CaretX);
end;
if bSuccess then begin
if Assigned(fOnReplaceText) then begin
Action := raReplace;
FOnReplaceText(Self, Editor.Lines.Strings[PrevLine - 1], EditBuf, Editor.CaretY, 0, Action);
if Action = raCancel then
Exit;
end;
Editor.Lines.Strings[PrevLine - 1] := EditBuf;
if FBeepOnAutoCorrect then
MessageBeep(0);
end;
end;
constructor TAsSynAutoCorrect.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FReplaceItems := TStringList.Create;
PrevLine := -1;
FAutoCorrectOnMouseDown := False;
FBeepOnAutoCorrect := True;
FEnabled := True;
FEditor := nil;
FIgnoreCase := True;
// GN
FMaintainCase := True;
end;
destructor TAsSynAutoCorrect.Destroy;
begin
FReplaceItems.Free;
Dispose(FEditVars);
inherited;
end;
// GN
function TAsSynAutoCorrect.PreviousToken: String;
var
i: Integer;
X: Integer;
begin
Result := Editor.LineText;
X := Editor.CaretX;
i := X - 1;
if i <= Length(Result) then begin
while (i > 0) and (Result[i] > ' ') do
Dec(i);
Inc(i);
Result := Copy(Result, i, X - i);
end
else
Result := '';
end;
function TAsSynAutoCorrect.FindAndCorrect(var EditLine: String; SearchString, ReplaceText: String; var CurrentX: Integer): Boolean;
var
StartPos: LongInt;
EndPos: Integer;
FoundText: String;
ReplaceDefText: String;
// RepLen: Integer;
p: TPoint;
Action: TSynReplaceAction;
function FirstCapCase(S: String): String;
begin
if S <> '' then begin
CharLowerBuff(@S[1],length(S));
CharUpperBuff(@S[1], 1);
end;
Result := S;
end;
begin
Result := False;
ReplaceDefText := ReplaceText;
StartPos := 0;
EndPos := Length(SearchString);
// RepLen := Length(ReplaceText);
if (Editor <> nil) and not (Editor.ReadOnly) then
begin
StartPos := CorrectItemStart(EditLine, SearchString, StartPos, not IgnoreCase, True);
while StartPos > -1 do
begin
if fMaintainCase then
begin
ReplaceText := ReplaceDefText;
FoundText := Copy(EditLine,StartPos+1,EndPos);
if FoundText = AnsiUpperCase(FoundText) then
ReplaceText := AnsiUpperCase(ReplaceText)
else
begin
if FoundText = AnsiLowerCase(FoundText) then
ReplaceText := AnsiLowerCase(ReplaceText)
else
begin
if FoundText = FirstCapCase(FoundText) then
ReplaceText := FirstCapCase(ReplaceText);
end;
end;
end;
if CurrentX > - 1 then
begin
p := Editor.CaretXY;
if Assigned(fOnReplaceText) then
begin
Action := raReplace;
FOnReplaceText(Self, SearchString, ReplaceText, P.Y, P.x, Action);
if Action = raCancel then
Break;
end;
Editor.BeginUpdate;
try
if p.x = 0 then
Editor.BlockBegin := Point(p.x - 1 - EndPos, p.y)
else
Editor.BlockBegin := Point(p.x - EndPos, p.y);
Editor.BlockEnd := p;
p := Editor.BlockBegin;
Editor.SelText := ReplaceText;
Result := True;
finally
Editor.EndUpdate;
end;
Break;
end
else
begin
Result := True;
EditLine := Copy(EditLine, 1, StartPos) + ReplaceText + Copy(EditLine, StartPos + EndPos + 1, MaxInt);
Inc(StartPos, EndPos);
StartPos := CorrectItemStart(EditLine, SearchString, StartPos, not IgnoreCase, True);
end;
end;
end;
end;
function TAsSynAutoCorrect.CorrectItemStart(EditLine: String; SearchString: String; StartPos: LongInt; frMatchCase, frWholeWord: Boolean): LongInt;
var
SearchCount, I: Integer;
C: Char;
// Direction: Shortint;
CharMap: array [Char] of Char;
CurBuf, Buf: PChar;
BufLen: Integer;
const
WordDelimiters: set of Char = [#0..#32];
function FindNextWordStart(var BufPtr: PChar): Boolean;
begin
// Result := False;
while (SearchCount > 0) and (BufPtr^ in WordDelimiters) do
begin
Inc(BufPtr, 1);
Dec(SearchCount);
end;
Result := SearchCount >= 0;
end;
function ScanText(var BufPtr: PChar): Boolean;
begin
Result := False;
while SearchCount >= 0 do
begin
if frWholeWord then
if not FindNextWordStart(BufPtr) then Break;
I := 0;
while (CharMap[BufPtr[I]] = SearchString[I+1]) do begin
Inc(I);
if I >= Length(SearchString) then
begin
if (not frWholeWord) or (SearchCount = 0) or (BufPtr[I] in WordDelimiters) then
begin
Result := True;
Exit;
end;
Break;
end;
end;
Inc(BufPtr);
Dec(SearchCount);
end;
end;
begin
Result := -1;
BufLen := Length(EditLine);
Buf := PChar(EditLine);
if BufLen > 0 then
begin
SearchCount := succ(BufLen - StartPos - Length(SearchString));
if (SearchCount >= 0) and (SearchCount <= BufLen) and (StartPos + SearchCount <= BufLen) then
begin
CurBuf := @Buf[StartPos];
for C := Low(CharMap) to High(CharMap) do
CharMap[C] := C;
if not frMatchCase then
begin
CharUpperBuff(PChar(@CharMap), sizeof(CharMap));
CharUpperBuff(@SearchString[1], Length(SearchString));
end;
if not ScanText(CurBuf) then
CurBuf := nil
else
begin
if CurBuf <> nil then
Result := CurBuf - Buf;
end;
end;
end;
// Buf := nil;
CurBuf := nil;
end;
function TAsSynAutoCorrect.GetReplaceItems: TStrings;
begin
Result := FReplaceItems;
end;
procedure TAsSynAutoCorrect.SetReplaceItems(const Value: TStrings);
begin
FReplaceItems.Assign(Value);
end;
procedure Register;
begin
RegisterComponents('SynEdit', [TAsSynAutoCorrect]);
RegisterPropertyEditor(TypeInfo(TStrings), TAsSynAutoCorrect, 'ReplaceItems', TAutoCorrectionProperty);
RegisterComponentEditor(TAsSynAutoCorrect, TAsSynAutoCorrectComponentEditor);
end;
end.
|
UNIT classmseq;
(*
Auteur Yann LE GUENNO
Version objet
Date: 08/03/99
*)
INTERFACE
type
vectap = array[8..16] of byte;
vec = array[0..65535] of word;
Pvec = ^vec;
(* Définition de la classe Tmseq, avec ses attributs et méthodes *)
Tmseq = class
public
n : byte; //de 1 à 16
R : Pvec; //vecteur des valeurs de la mseq
T : byte; //feedback tap, déterminé par n
l : word; //au max (lgueur de la mseq)-1, 2^16-1=65535 au plus
constructor create(b:byte);
procedure calcul;
private
q,masque : word; //pour les manipulations de bit
function deuxpuiss(a:byte) : cardinal;
end; //fin classe
var
valtap : vectap; //valeurs possibles du feedback tap (voir initializaion)
mseq : Tmseq;
IMPLEMENTATION
(* constructeur *)
constructor Tmseq.create(b:byte);
var
toto : cardinal;
begin
//inherited create;
n:=b;
T:=valtap[n];
toto:=self.deuxpuiss(n)-1;
l:=word (toto);
masque:=l;
toto:=self.deuxpuiss(n-1);
q:=word (toto);
GetMem(R,l*sizeof(word));
R^[0]:=1;
end;
(* fonction calculant 2^a *)
function Tmseq.deuxpuiss;
var
k : integer;
calc : cardinal; (* intermédiaire de calcul *)
begin
calc:=1;
for k:=1 to a do calc:=2*calc;
deuxpuiss:=calc;
end;
(* fin fonction *)
(* calcul de la mseq *)
procedure Tmseq.calcul;
var
i : cardinal;
x1,x2,x3 : word; (* intermédiaires de calcul pour affecter R *)
begin
for i:=1 to l do
begin
x1:=R^[i-1];
x2:=x1 shl 1;
if (x1 and q)<>q then x3:= (x2 and masque)
else x3:= (x2 and masque) xor T;
R^[i]:=x3;
end;
end;
(* valeurs possibles du feedback tap *)
initialization
//valeurs déterminées d'après test
valtap[8]:=29;
valtap[9]:=17;
valtap[10]:=9;
valtap[11]:=5;
valtap[12]:=83;
valtap[13]:=27;
valtap[14]:=43;
valtap[15]:=3;
valtap[16]:=45;
(* fin unité *)
end.
|
unit Mac.Utils;
interface
uses
Macapi.Foundation, Macapi.CocoaTypes;
function NSStringToString(APtr: Pointer): string; overload;
function NSStringToString(AStr: NSString): string; overload;
function NSDateToDateTime(APtr: Pointer): TDateTime; overload;
function NSDateToDateTime(ADate: NSDate): TDateTime; overload;
function NSNumberToInt(ANumber: NSNumber): Integer; overload;
function NSNumberToInt(APtr: Pointer): Integer; overload;
function NSNumberToLongInt(ANumber: NSNumber): LongInt; overload;
function NSNumberToLongInt(APtr: Pointer): LongInt; overload;
function NSNumberToDouble(ANumber: NSNumber): Double; overload;
function NSNumberToDouble(APtr: Pointer): Double; overload;
function NSObjectToString(AObject: NSObject): string; overload;
function NSObjectToString(APtr: Pointer): string; overload;
function DateTimeToNSDate(ADateTime: TDateTime): NSDate;
function NSStrPtr(AString: string): Pointer;
function PtrForObject(AObject: NSObject): Pointer;
{$ENDIF}
implementation
{$IFDEF MACOS}
uses
Macapi.ObjectiveC, System.SysUtils;
function NSStringToString(APtr: Pointer): string;
begin
//TODO: Rewrite using routines from
//http://delphihaven.wordpress.com/2011/09/26/converting-from-a-cocoa-string-to-a-delphi-string/
Result := NSStringToString(TNSString.Wrap(APtr));
end;
function NSStringToString(AStr: NSString): string;
begin
//TODO: Rewrite using routines from
//http://delphihaven.wordpress.com/2011/09/26/converting-from-a-cocoa-string-to-a-delphi-string/
Result := string(AStr.UTF8String);
end;
function NSStrPtr(AString: string): Pointer;
begin
Result := TNSString.OCClass.stringWithUTF8String(PAnsiChar(UTF8String(AString)));
end;
function PtrForObject(AObject: NSObject): Pointer;
begin
Result := (AObject as ILocalObject).GetObjectID;
end;
function DateTimeToNSDate(ADateTime: TDateTime): NSDate;
const
cnDateFmt = '%.4d-%.2d-%.2d %.2d:%.2d:%.2d +0000';
var
Day, Month, Year, Hour, Min, Sec, MSec: Word;
DateStr: string;
Tmp: NSDate;
begin
DecodeDate(ADateTime, Year, Month, Day);
DecodeTime(ADateTime, Hour, Min, Sec, MSec);
DateStr := Format(cnDateFmt, [Year, Month, Day, Hour, Min, Sec, 0]);
Tmp := TNSDate.Create;
try
Tmp.initWithString(NSStr(DateStr));
Result := TNSDate.Wrap(Tmp.addTimeInterval(MSec / 1000));
Result.retain;
finally
Tmp.release;
end;
end;
function NSDateToDateTime(APtr: Pointer): TDateTime;
begin
Result := NSDateToDateTime(TNSDate.Wrap(APtr));
end;
function NSDateToDateTime(ADate: NSDate): TDateTime;
var
lCalendar: NSCalendar;
lComps: NSDateComponents;
lUnits: Cardinal;
begin
lCalendar := TNSCalendar.Wrap(TNSCalendar.OCClass.currentCalendar);
lUnits := NSYearCalendarUnit or NSMonthCalendarUnit or NSDayCalendarUnit or
NSHourCalendarUnit or NSMinuteCalendarUnit or NSSecondCalendarUnit;
lComps := lCalendar.components(lUnits, ADate);
Result := EncodeDate(lComps.year, lComps.month, lComps.day) +
EncodeTime(lComps.hour, lComps.minute, lComps.second, 0);
end;
function NSObjectToString(AObject: NSObject): string;
var
lNum: NSNumber;
lStr: NSString;
lDate: NSDate;
begin
if True then
Result := NSStringToString(NSString(AObject))
else if Supports(AObject, NSString, lStr) then
Result := NSStringToString(lStr)
else if Supports(AObject, NSNumber, lNum) then
Result := IntToStr(NSNumberToInt(lNum))
else if Supports(AObject, NSDate, lDate) then
Result := DateTimeToStr(NSDateToDateTime(lDate))
else
Result := '';
end;
function NSObjectToString(APtr: Pointer): string;
begin
Result := NSObjectToString(TNSObject.Wrap(APtr));
end;
function NSNumberToInt(ANumber: NSNumber): Integer;
begin
Result := ANumber.integerValue;
end;
function NSNumberToInt(APtr: Pointer): Integer;
begin
Result := NSNumberToInt(TNSNumber.Wrap(APtr));
end;
function NSNumberToLongInt(ANumber: NSNumber): LongInt;
begin
Result := ANumber.longLongValue;
end;
function NSNumberToLongInt(APtr: Pointer): LongInt;
begin
Result := NSNumberToLongInt(TNSNumber.Wrap(APtr));
end;
function NSNumberToDouble(ANumber: NSNumber): Double;
begin
Result := ANumber.doubleValue;
end;
function NSNumberToDouble(APtr: Pointer): Double;
begin
Result := NSNumberToDouble(TNSNumber.Wrap(APtr));
end;
end.
|
unit FileDialogs;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, FileCtrl, Grids, Shlobj, ComCtrls, Files, FileOperations,
Misc_utils, GlobalVars;
type
TGetFileOpen = class(TForm)
EBFname: TEdit;
BNOpen: TButton;
BNCancel: TButton;
CBFilter: TFilterComboBox;
Label1: TLabel;
Label2: TLabel;
Label4: TLabel;
DirList: TListBox;
Label3: TLabel;
LBContainer: TLabel;
LBFileSize: TLabel;
OpenDialog: TOpenDialog;
procedure FormCreate(Sender: TObject);
procedure EBFnameChange(Sender: TObject);
procedure DirListClick(Sender: TObject);
procedure CBFilterChange(Sender: TObject);
procedure DirListDblClick(Sender: TObject);
procedure BNOpenClick(Sender: TObject);
private
DirControl:TMaskedDirectoryControl;
Dir:TContainerFile;
Fname:String;
Procedure SetFilter(const filter:String);
Procedure SetFName(const name:String);
Procedure SetContainer(const container:String);
{ Private declarations }
public
{ Public declarations }
Property FileName:String read Fname write SetFname;
Property Filter:String write SetFilter;
Function Execute:boolean;
end;
TDirPicker=class
Private
FCaption,
FDir:String;
Public
Property Directory:String read FDir write FDir;
Property Caption:String read FCaption write FCaption;
Function Execute:boolean;
end;
var
GetFileOpen: TGetFileOpen;
implementation
Uses Unit1;
{$R *.DFM}
Function TDirPicker.Execute:boolean;
var Dir:Array[0..255] of char;
Bi:TBrowseInfo;
ShellFolder:IShellFolder;
begin
StrCopy(Dir,Pchar(FDir));
With Bi do
begin
hwndOwner:=Screen.ActiveForm.Handle;
pidlRoot:=nil;
pszDisplayName:=Dir;
lpszTitle:=PChar(FCaption);
ulFlags:=BIF_RETURNONLYFSDIRS;
lpfn:=nil;
lParam:=0;
iImage:=0;
end;
if ShBrowseForFolder(bi)=nil then result:=false
else
begin
FDir:=bi.pszDisplayName;
end;
end;
procedure TGetFileOpen.FormCreate(Sender: TObject);
begin
ClientWidth:=Label4.Left+DirList.Left+DirList.Width;
ClientHeight:=Label4.Top+CBFilter.Top+CBFilter.Height;
DirControl:=TMaskedDirectoryControl.CreateFromLB(DirList);
OpenDialog.FileName:='*.*';
end;
Procedure TGetFileOpen.SetFilter(const filter:String);
begin
OpenDialog.Filter:=filter;
CBFilter.Filter:=Filter;
end;
Procedure TGetFileOpen.SetFname(Const name:String);
var path:String;
begin
if IsInContainer(Name) then
begin
path:=ExtractPath(Name);
If Path[length(Path)]='>' then SetLength(Path,length(path)-1);
OpenDialog.FileName:=Path;
EBFname.Text:=ExtractName(Name);
end
else OpenDialog.FileName:=Name;
FName:=name;
end;
Procedure TGetFileOpen.SetContainer(Const container:String);
begin
Caption:='Files inside '+Container;
Dir:=OpenContainer(Container);
DirControl.SetDir(Dir);
DirControl.SetMask(CBFilter.Mask);
LBContainer.Caption:=Container;
end;
Function TGetFileOpen.Execute:boolean;
begin
Result:=false;
Repeat
result:=OpenDialog.Execute;
if not result then exit;
if IsContainer(OpenDialog.FileName) then
begin
SetContainer(OpenDialog.FileName);
DirList.Sorted:=true;
if ShowModal=mrOK then
begin
Fname:=OpenDialog.FileName+'>'+EBFname.Text;
DirControl.SetDir(Nil);
Dir.Free;
result:=true;
exit;
end;
Dir.Free;
DirControl.SetDir(Nil);
end
else begin FName:=OpenDialog.FileName; exit; end;
Until false;
end;
procedure TGetFileOpen.EBFnameChange(Sender: TObject);
var i:Integer;
begin
i:=DirList.Items.IndexOf(EBFname.Text);
if i<>-1 then DirList.ItemIndex:=i;
end;
procedure TGetFileOpen.DirListClick(Sender: TObject);
var TI:TFileInfo;
i:Integer;
begin
i:=DirList.ItemIndex;
If i<0 then exit;
EBFName.Text:=DirList.Items[i];
if DirList.Items[i]='' then;
Ti:=TFileInfo(DirList.Items.Objects[i]);
LBFileSize.Caption:=IntToStr(ti.size);
end;
procedure TGetFileOpen.CBFilterChange(Sender: TObject);
begin
DirControl.SetMask(CBFilter.Mask);
end;
procedure TGetFileOpen.DirListDblClick(Sender: TObject);
begin
BNOpen.Click;
end;
procedure TGetFileOpen.BNOpenClick(Sender: TObject);
begin
If Dir.ListFiles.IndexOf(EBFname.Text)=-1 then
MsgBox('The file '+EBFname.Text+' is not in the container','Error',mb_ok)
else begin ModalResult:=mrOk; Hide; end;
begin
end;
end;
Initialization
Finalization
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.