text stringlengths 14 6.51M |
|---|
unit EditVideoController;
interface
uses
Generics.Collections,
Video, MediaFile, Artist, VideoFormat,
Aurelius.Engine.ObjectManager;
type
TEditVideoController = class
private
FManager: TObjectManager;
FVideo: TVideo;
public
constructor Create;
destructor Destroy; override;
procedure SaveVideo(Video: TVideo);
procedure Load(VideoId: Variant);
function GetAlbums: TList<TAlbum>;
function GetArtists: TList<TArtist>;
function GetVideoFormats: TList<TVideoFormat>;
property Video: TVideo read FVideo;
end;
implementation
uses
DBConnection;
{ TMusicasController }
constructor TEditVideoController.Create;
begin
FVideo := TVideo.Create;
FManager := TDBConnection.GetInstance.CreateObjectManager;
end;
destructor TEditVideoController.Destroy;
begin
if not FManager.IsAttached(FVideo) then
FVideo.Free;
FManager.Free;
inherited;
end;
function TEditVideoController.GetAlbums: TList<TAlbum>;
begin
Result := FManager.FindAll<TAlbum>;
end;
function TEditVideoController.GetArtists: TList<TArtist>;
begin
Result := FManager.FindAll<TArtist>;
end;
function TEditVideoController.GetVideoFormats: TList<TVideoFormat>;
begin
Result := FManager.FindAll<TVideoFormat>;
end;
procedure TEditVideoController.Load(VideoId: Variant);
begin
if not FManager.IsAttached(FVideo) then
FVideo.Free;
FVideo := FManager.Find<TVideo>(VideoId);
end;
procedure TEditVideoController.SaveVideo(Video: TVideo);
begin
if not FManager.IsAttached(Video) then
FManager.SaveOrUpdate(Video);
FManager.Flush;
end;
end.
|
unit Unit1;
// EMS Resource Module
interface
uses
System.SysUtils, System.Classes, System.JSON,
EMS.Services, EMS.ResourceAPI, EMS.ResourceTypes;
type
[ResourceName('MyTest')]
TMyTestResource1 = class(TDataModule)
private
function MakeJSON(i: integer): TJSONObject;
published
procedure Get(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
[ResourceSuffix('{item}')]
procedure GetItem(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
end;
const
TestValues: array[0..2] of string = ('a', 'b', 'c');
procedure Register;
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
{$R *.dfm}
procedure TMyTestResource1.Get(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
var
LJSON: TJSONArray;
I: Integer;
begin
LJSON := TJSONArray.Create;
for I := Low(TestValues) to High(TestValues) do
LJSON.Add(MakeJSON(I));
AResponse.Body.SetValue(LJSON, True) // True causes AResponse to free JSON
end;
procedure TMyTestResource1.GetItem(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
var
I: Integer;
begin
if not TryStrToInt(ARequest.Params.Values['item'], I) then
AResponse.RaiseBadRequest('Index expected');
if (I < 0) or (I >= Length(TestValues)) then
AResponse.RaiseBadRequest('Index out of range');
AResponse.Body.SetValue(MakeJSON(I), True); // True causes AResponse to free JSON
end;
function TMyTestResource1.MakeJSON(i: integer): TJSONObject;
begin
Result := TJSONObject.Create;
Result.AddPair('index', TJSONNumber.Create(i));
Result.AddPair('value', TJSONString.Create(TestValues[i]));
end;
procedure Register;
begin
RegisterResource(TypeInfo(TMyTestResource1));
end;
end.
|
// ************************************************************************ //
// The types declared in this file were generated from data read from the
// WSDL File described below:
// WSDL : http://localhost:54326/PILABService/PILABService.asmx?WSDL
// Encoding : utf-8
// Version : 1.0
// (17.06.2015 9:16:24 - 1.33.2.5)
// ************************************************************************ //
unit PILABService;
interface
uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns;
type
// ************************************************************************ //
// The following types, referred to in the WSDL document are not being represented
// in this file. They are either aliases[@] of other types represented or were referred
// to but never[!] declared in the document. The types from the latter category
// typically map to predefined/known XML or Borland types; however, they could also
// indicate incorrect WSDL documents that failed to declare or import a schema type.
// ************************************************************************ //
// !:string - "http://www.w3.org/2001/XMLSchema"
// !:dateTime - "http://www.w3.org/2001/XMLSchema"
// !:long - "http://www.w3.org/2001/XMLSchema"
// !:float - "http://www.w3.org/2001/XMLSchema"
LabArg = class; { "http://tempuri.org/" }
LabResult = class; { "http://tempuri.org/" }
PIResult = class; { "http://tempuri.org/" }
PIArg = class; { "http://tempuri.org/" }
// ************************************************************************ //
// Namespace : http://tempuri.org/
// ************************************************************************ //
LabArg = class(TRemotable)
private
FDocumentReference: WideString;
FStandardNr: WideString;
FTest: WideString;
FDate: TXSDateTime;
public
destructor Destroy; override;
published
property DocumentReference: WideString read FDocumentReference write FDocumentReference;
property StandardNr: WideString read FStandardNr write FStandardNr;
property Test: WideString read FTest write FTest;
property Date: TXSDateTime read FDate write FDate;
end;
// ************************************************************************ //
// Namespace : http://tempuri.org/
// ************************************************************************ //
LabResult = class(TRemotable)
private
FDate: TXSDateTime;
FValue: WideString;
FStatus: Int64;
public
destructor Destroy; override;
published
property Date: TXSDateTime read FDate write FDate;
property Value: WideString read FValue write FValue;
property Status: Int64 read FStatus write FStatus;
end;
ArrayOfLabArg = array of LabArg; { "http://tempuri.org/" }
ArrayOfLabResult = array of LabResult; { "http://tempuri.org/" }
// ************************************************************************ //
// Namespace : http://tempuri.org/
// ************************************************************************ //
PIResult = class(TRemotable)
private
FTimeStamp: TXSDateTime;
FValue: Single;
FStatus: Int64;
public
destructor Destroy; override;
published
property TimeStamp: TXSDateTime read FTimeStamp write FTimeStamp;
property Value: Single read FValue write FValue;
property Status: Int64 read FStatus write FStatus;
end;
ArrayOfString = array of WideString; { "http://tempuri.org/" }
ArrayOfPIResult = array of PIResult; { "http://tempuri.org/" }
// ************************************************************************ //
// Namespace : http://tempuri.org/
// ************************************************************************ //
PIArg = class(TRemotable)
private
FTag: WideString;
FTimeStamp: TXSDateTime;
public
destructor Destroy; override;
published
property Tag: WideString read FTag write FTag;
property TimeStamp: TXSDateTime read FTimeStamp write FTimeStamp;
end;
ArrayOfPIArg = array of PIArg; { "http://tempuri.org/" }
// ************************************************************************ //
// Namespace : http://tempuri.org/
// soapAction: http://tempuri.org/%operationName%
// transport : http://schemas.xmlsoap.org/soap/http
// binding : PILABServiceSoap
// service : PILABService
// port : PILABServiceSoap
// URL : http://localhost:54326/PILABService/PILABService.asmx
// ************************************************************************ //
PILABServiceSoap = interface(IInvokable)
['{9417094D-BD9D-9824-959B-C36696B90D53}']
function GetLabValue(const arg: LabArg): LabResult; stdcall;
function GetLabValues(const arg: ArrayOfLabArg): ArrayOfLabResult; stdcall;
function GetPISnapshotValue(const Tag: WideString): PIResult; stdcall;
function GetPISnapshotValues(const Tags: ArrayOfString): ArrayOfPIResult; stdcall;
function GetPIValue(const arg: PIArg): PIResult; stdcall; //
function GetPIValues(const arg: ArrayOfPIArg): ArrayOfPIResult; stdcall;
end;
function GetPILABServiceSoap(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): PILABServiceSoap;
implementation
function GetPILABServiceSoap(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): PILABServiceSoap;
const
defWSDL = 'http://localhost:32768/PILABService.asmx?WSDL';
defURL = 'http://localhost:32768/PILABService.asmx';
defSvc = 'PILABService';
defPrt = 'PILABServiceSoap';
var
RIO: THTTPRIO;
begin
Result := nil;
if (Addr = '') then
begin
if UseWSDL then
Addr := defWSDL
else
Addr := defURL;
end;
if HTTPRIO = nil then
RIO := THTTPRIO.Create(nil)
else
RIO := HTTPRIO;
try
Result := (RIO as PILABServiceSoap);
if UseWSDL then
begin
RIO.WSDLLocation := Addr;
RIO.Service := defSvc;
RIO.Port := defPrt;
end else
RIO.URL := Addr;
finally
if (Result = nil) and (HTTPRIO = nil) then
RIO.Free;
end;
end;
destructor LabArg.Destroy;
begin
if Assigned(FDate) then
FDate.Free;
inherited Destroy;
end;
destructor LabResult.Destroy;
begin
if Assigned(FDate) then
FDate.Free;
inherited Destroy;
end;
destructor PIResult.Destroy;
begin
if Assigned(FTimeStamp) then
FTimeStamp.Free;
inherited Destroy;
end;
destructor PIArg.Destroy;
begin
if Assigned(FTimeStamp) then
FTimeStamp.Free;
inherited Destroy;
end;
initialization
InvRegistry.RegisterInterface(TypeInfo(PILABServiceSoap), 'http://tempuri.org/', 'utf-8');
InvRegistry.RegisterDefaultSOAPAction(TypeInfo(PILABServiceSoap), 'http://tempuri.org/%operationName%');
InvRegistry.RegisterInvokeOptions(TypeInfo(PILABServiceSoap), ioDocument);
RemClassRegistry.RegisterXSClass(LabArg, 'http://tempuri.org/', 'LabArg');
RemClassRegistry.RegisterXSClass(LabResult, 'http://tempuri.org/', 'LabResult');
RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfLabArg), 'http://tempuri.org/', 'ArrayOfLabArg');
RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfLabResult), 'http://tempuri.org/', 'ArrayOfLabResult');
RemClassRegistry.RegisterXSClass(PIResult, 'http://tempuri.org/', 'PIResult');
RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfString), 'http://tempuri.org/', 'ArrayOfString');
RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfPIResult), 'http://tempuri.org/', 'ArrayOfPIResult');
RemClassRegistry.RegisterXSClass(PIArg, 'http://tempuri.org/', 'PIArg');
RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfPIArg), 'http://tempuri.org/', 'ArrayOfPIArg');
end. |
unit SimpleAttributes;
interface
uses
System.RTTI, System.Variants, System.Classes;
type
TJoin = (InnerJoin, LeftJoin, RightJoin, FullJoin);
Tabela = class(TCustomAttribute)
private
FName: string;
public
constructor Create(aName: string);
property Name: string read FName;
end;
Campo = class(TCustomAttribute)
private
FName: string;
public
Constructor Create(aName: string);
property Name: string read FName;
end;
PK = class(TCustomAttribute)
end;
FK = class(TCustomAttribute)
private
FColumnName: string;
FRefTableName: string;
FRefColumnName: string;
FRefColumnNameSelect: String;
FJoin: TJoin;
FAlias: string;
public
constructor Create(AColumnName, ARefTableName, ARefColumnName,
ARefColumnNameSelect: String; AJoin: TJoin = InnerJoin; AAlias: string = '');
property ColumnName: string read FColumnName;
property RefColumnName: string read FRefColumnName;
property RefTableName: string read FRefTableName;
property RefColumnNameSelect: string read FRefColumnNameSelect;
property Join: TJoin read FJoin;
property Alias: string read FAlias;
end;
NotNull = class(TCustomAttribute)
end;
SaveNull = class(TCustomAttribute)
end;
Ignore = class(TCustomAttribute)
end;
AutoInc = class(TCustomAttribute)
end;
NumberOnly = class(TCustomAttribute)
end;
Bind = class(TCustomAttribute)
private
FField: String;
procedure SetField(const Value: String);
public
constructor Create (aField : String);
published
property Field : String read FField write SetField;
end;
Format = class(TCustomAttribute)
private
FMaxSize: integer;
FPrecision: integer;
FMask: string;
FMinSize: integer;
public
property MaxSize: integer read FMaxSize write FMaxSize;
property MinSize: integer read FMinSize write FMinSize;
property Precision: integer read FPrecision write FPrecision;
property Mask: string read FMask write FMask;
function GetNumericMask: string;
constructor Create(const aSize: Integer; const aPrecision: integer = 0); overload;
constructor Create(const aMask: string); overload;
constructor Create(const aRange: array of Integer); overload;
end;
Display = class(TCustomAttribute)
private
FName: string;
public
constructor Create(const aName: string);
property Name: string read FName write FName;
end;
Relationship = class abstract(TCustomAttribute)
private
FEntityName: string;
public
constructor Create(const aEntityName: string);
property EntityName: string read FEntityName write FEntityName;
end;
HasOne = class(Relationship)
end;
BelongsTo = class(Relationship)
end;
HasMany = class(Relationship)
end;
BelongsToMany = class(Relationship)
end;
implementation
{ Bind }
constructor Bind.Create(aField: String);
begin
FField := aField;
end;
procedure Bind.SetField(const Value: String);
begin
FField := Value;
end;
{ Tabela }
constructor Tabela.Create(aName: string);
begin
FName := aName;
end;
{ Campo }
constructor Campo.Create(aName: string);
begin
FName := aName;
end;
{ FK }
constructor FK.Create(AColumnName, ARefTableName, ARefColumnName,
ARefColumnNameSelect: String; AJoin: TJoin = InnerJoin; AAlias: string = '');
begin
FColumnName := AColumnName;
FRefTableName := ARefTableName;
FRefColumnName := ARefColumnName;
FRefColumnNameSelect := ARefColumnNameSelect;
FJoin := AJoin;
FAlias := AAlias;
end;
{ Display }
constructor Display.Create(const aName: string);
begin
FName := aName;
end;
{ Formato }
constructor Format.Create(const aSize, aPrecision: integer);
begin
FMaxSize := aSize;
FPrecision := aPrecision;
end;
constructor Format.Create(const aMask: string);
begin
FMask := aMask;
end;
constructor Format.Create(const aRange: array of Integer);
begin
FMinSize := aRange[0];
FMaxSize := aRange[High(aRange)];
end;
function Format.GetNumericMask: string;
var
sTamanho, sPrecisao: string;
begin
sTamanho := StringOfChar('0', FMaxSize - FPrecision);
sPrecisao := StringOfChar('0', FPrecision);
Result := sTamanho + '.' + sPrecisao;
end;
{ Relationship }
constructor Relationship.Create(const aEntityName: string);
begin
FEntityName := aEntityName;
end;
end.
|
namespace RemObjects.Elements.EUnit;
interface
type
Assert = public partial static class {$IF NOUGAT}mapped to Object{$ENDIF}
public
method AreEqual(Actual, Expected : Int32; Message: String := nil);
method AreNotEqual(Actual, Expected: Int32; Message: String := nil);
method Greater(Actual, Expected: Int32; Message: String := nil);
method GreaterOrEquals(Actual, Expected: Int32; Message: String := nil);
method Less(Actual, Expected: Int32; Message: String := nil);
method LessOrEquals(Actual, Expected: Int32; Message: String := nil);
method AreEqual(Actual, Expected : Int64; Message: String := nil);
method AreNotEqual(Actual, Expected: Int64; Message: String := nil);
method Greater(Actual, Expected: Int64; Message: String := nil);
method GreaterOrEquals(Actual, Expected: Int64; Message: String := nil);
method Less(Actual, Expected: Int64; Message: String := nil);
method LessOrEquals(Actual, Expected: Int64; Message: String := nil);
end;
implementation
class method Assert.AreNotEqual(Actual: Integer; Expected: Integer; Message: String := nil);
begin
FailIfNot(Actual <> Expected, Actual, Expected, coalesce(Message, AssertMessages.Equal));
end;
class method Assert.AreEqual(Actual: Integer; Expected: Integer; Message: String := nil);
begin
FailIfNot(Actual = Expected, Actual, Expected, coalesce(Message, AssertMessages.NotEqual));
end;
class method Assert.Greater(Actual: Integer; Expected: Integer; Message: String := nil);
begin
FailIfNot(Actual > Expected, Actual, Expected, coalesce(Message, AssertMessages.GreaterExpected));
end;
class method Assert.GreaterOrEquals(Actual: Integer; Expected: Integer; Message: String := nil);
begin
FailIfNot(Actual >= Expected, Actual, Expected, coalesce(Message, AssertMessages.GreaterOrEqualExpected));
end;
class method Assert.Less(Actual: Integer; Expected: Integer; Message: String := nil);
begin
FailIfNot(Actual < Expected, Actual, Expected, coalesce(Message, AssertMessages.LessExpected));
end;
class method Assert.LessOrEquals(Actual: Integer; Expected: Integer; Message: String := nil);
begin
FailIfNot(Actual <= Expected, Actual, Expected, coalesce(Message, AssertMessages.LessOrEqualExpected));
end;
class method Assert.AreEqual(Actual: Int64; Expected: Int64; Message: String := nil);
begin
FailIfNot(Actual = Expected, Actual, Expected, coalesce(Message, AssertMessages.NotEqual));
end;
class method Assert.AreNotEqual(Actual: Int64; Expected: Int64; Message: String := nil);
begin
FailIfNot(Actual <> Expected, Actual, Expected, coalesce(Message, AssertMessages.Equal));
end;
class method Assert.Greater(Actual: Int64; Expected: Int64; Message: String := nil);
begin
FailIfNot(Actual > Expected, Actual, Expected, coalesce(Message, AssertMessages.GreaterExpected));
end;
class method Assert.GreaterOrEquals(Actual: Int64; Expected: Int64; Message: String := nil);
begin
FailIfNot(Actual >= Expected, Actual, Expected, coalesce(Message, AssertMessages.GreaterOrEqualExpected));
end;
class method Assert.Less(Actual: Int64; Expected: Int64; Message: String := nil);
begin
FailIfNot(Actual < Expected, Actual, Expected, coalesce(Message, AssertMessages.LessExpected));
end;
class method Assert.LessOrEquals(Actual: Int64; Expected: Int64; Message: String := nil);
begin
FailIfNot(Actual <= Expected, Actual, Expected, coalesce(Message, AssertMessages.LessOrEqualExpected));
end;
end. |
unit CameraUnit;
interface
uses Maths3D;
type
TCamera = Class(TObject)
public
X_Angle,
Y_Angle : Single;
Position : TVec3;
moveForward,
moveBackward,
moveLeft,
moveRight,
moveUp,
moveDown : Boolean;
velocity : TVec3;
acceleration,
friction,
fov,
max_speed,
move_mouse_x,
move_mouse_y : Single;
FWaitTime : Single;
constructor Create;
Procedure ApplyCamera;
function Update(speed : single; IgnoreMouse : Boolean) : boolean;
property WaitTime : Single read FWaitTime write FWaitTime;
end;
var
Camera : TCamera;
implementation
uses OpenGL15, Math;
constructor TCamera.Create;
begin
acceleration := 2000;
friction := 1000*1.5;
max_speed := 200*2;
fov := 90;
Position := SetVector(0,0,0);
end;
Procedure TCamera.ApplyCamera;
begin
glRotatef(X_Angle, 1, 0, 0); // pitch
glRotatef(Y_Angle, 0, 1, 0); // roll
glTranslatef(-Position[0],-Position[1],-Position[2]);
end;
function TCamera.Update(speed : single; IgnoreMouse : Boolean) : boolean;
var dir, versor, desp, temp : TVec3;
rad_yaw, vel, ivel : single;
label MouseAction;
begin
if FWaitTime > 0 then
begin
FWaitTime := FWaitTime - Speed;
exit;
end;
dir := SetVector(0,0,0);
versor := SetVector( 0,0,0);
if (X_Angle < -90.0) or (X_Angle > 90.0) then
begin
moveForward := false;
moveBackward := false;
moveLeft := false;
moveRight := false;
velocity[0] := 0;
velocity[2] := 0;
end;
if (moveForward) then versor[2] := versor[2]-1.0;
if (moveBackward) then versor[2] := versor[2]+1.0;
if (moveUp) then versor[1] := versor[1]+1.0;
if (moveDown) then versor[1] := versor[1]-1.0;
if (moveLeft) then versor[0] := versor[0]-1.0;
if (moveRight) then versor[0] := versor[0]+1.0;
rad_yaw := DEG2RAD(Y_Angle);
// strafe
if (versor[0] <> 0) then begin
dir[0] := dir[0] + versor[0]*Cos(rad_yaw);
dir[2] := dir[2] + versor[0]*Sin(rad_yaw);
end;
// move
if ((X_Angle < -88.0) or (X_Angle > 88.0)) then
else
if (versor[2] <> 0) then begin
dir[0] := dir[0] - versor[2]*Sin(rad_yaw);
dir[2] := dir[2] + versor[2]*Cos(rad_yaw);
end;
IF X_Angle > 90 then
X_Angle := 90
else
IF X_Angle < -90 then
X_Angle := -90;
if X_angle = 90 then
rad_yaw := DEG2RAD(-x_angle)
else
if X_angle = -90 then
rad_yaw := DEG2RAD(-x_angle)
else
rad_yaw := DEG2RAD(x_angle);
// move
if (versor[1] <> 0) then begin
dir[1] := dir[1] - versor[1]*Tan(rad_yaw);
end;
rad_yaw := DEG2RAD(y_angle);
if (Normalize(versor) > 0) then begin
velocity[0] := velocity[0] + dir[0]*speed*acceleration;
velocity[1] := velocity[1] + dir[1]*speed*acceleration;
velocity[2] := velocity[2] + dir[2]*speed*acceleration;
end;
// Speed
temp := velocity;
vel := Normalize(temp);
velocity[0] := velocity[0] - temp[0]*speed*friction;
velocity[1] := velocity[1] - temp[1]*speed*friction;
velocity[2] := velocity[2] - temp[2]*speed*friction;
if (((temp[0] > 0) and (velocity[0] < 0)) or ((temp[0] < 0) and (velocity[0] > 0))) then
velocity[0] := 0;
if (((temp[1] > 0) and (velocity[1] < 0)) or ((temp[1] < 0) and (velocity[1] > 0))) then
velocity[1] := 0;
if (((temp[2] > 0) and (velocity[2] < 0)) or ((temp[2] < 0) and (velocity[2] > 0))) then
velocity[2] := 0;
if (vel > max_speed) then begin
ivel := 1/vel*max_speed;
velocity := MultiplyVector(velocity, ivel);
end;
// Position
desp := MultiplyVector(velocity, speed);
Position := AddVector(desp, Position);
MouseAction:
// Rotation
If Not IgnoreMouse then
begin
if (move_mouse_x <> 0) then begin
y_angle := y_angle + move_mouse_x*fov/M_TWO_PI; // the rotation is proportionnal to camera fov
end;
if (move_mouse_y <> 0) then begin
x_angle := x_angle + move_mouse_y*fov/M_TWO_PI;
end;
end;
// dont go out of bounds
if (x_angle < -90.0) then
x_angle := -90.0
else if (x_angle > 90.0) then
x_angle := 90.0;
move_mouse_x := 0;
move_mouse_y := 0;
moveForward := false;
moveBackward := false;
moveLeft := false;
moveRight := false;
moveUp := false;
moveDown := false;
end;
begin
Camera := TCamera.Create;
end.
|
unit GuiaAlvo.Model.RedesSociais;
interface
type
TRedeSocial = class
private
FAPPLECOM: String;
FTUBECOM: String;
FGOOGLECOM: String;
FUBEREATSCOM: String;
FAPPCOM: String;
FTWITERCOM: String;
FINSTACOM: String;
FEMAILCOM: String;
FSITECOM: String;
FFACECOM: String;
procedure SetAPPCOM(const Value: String);
procedure SetAPPLECOM(const Value: String);
procedure SetEMAILCOM(const Value: String);
procedure SetFACECOM(const Value: String);
procedure SetGOOGLECOM(const Value: String);
procedure SetINSTACOM(const Value: String);
procedure SetSITECOM(const Value: String);
procedure SetTUBECOM(const Value: String);
procedure SetTWITERCOM(const Value: String);
procedure SetUBEREATSCOM(const Value: String);
public
property SITECOM : String read FSITECOM write SetSITECOM;
property EMAILCOM : String read FEMAILCOM write SetEMAILCOM;
property FACECOM : String read FFACECOM write SetFACECOM;
property INSTACOM : String read FINSTACOM write SetINSTACOM;
property TWITERCOM : String read FTWITERCOM write SetTWITERCOM;
property GOOGLECOM : String read FGOOGLECOM write SetGOOGLECOM;
property TUBECOM : String read FTUBECOM write SetTUBECOM;
property APPCOM : String read FAPPCOM write SetAPPCOM;
property UBEREATSCOM : String read FUBEREATSCOM write SetUBEREATSCOM;
property APPLECOM : String read FAPPLECOM write SetAPPLECOM;
end;
implementation
{ TRedeSocial }
procedure TRedeSocial.SetAPPCOM(const Value: String);
begin
FAPPCOM := Value;
end;
procedure TRedeSocial.SetAPPLECOM(const Value: String);
begin
FAPPLECOM := Value;
end;
procedure TRedeSocial.SetEMAILCOM(const Value: String);
begin
FEMAILCOM := Value;
end;
procedure TRedeSocial.SetFACECOM(const Value: String);
begin
FFACECOM := Value;
end;
procedure TRedeSocial.SetGOOGLECOM(const Value: String);
begin
FGOOGLECOM := Value;
end;
procedure TRedeSocial.SetINSTACOM(const Value: String);
begin
FINSTACOM := Value;
end;
procedure TRedeSocial.SetSITECOM(const Value: String);
begin
FSITECOM := Value;
end;
procedure TRedeSocial.SetTUBECOM(const Value: String);
begin
FTUBECOM := Value;
end;
procedure TRedeSocial.SetTWITERCOM(const Value: String);
begin
FTWITERCOM := Value;
end;
procedure TRedeSocial.SetUBEREATSCOM(const Value: String);
begin
FUBEREATSCOM := Value;
end;
end.
|
unit FScanArchive;
(*====================================================================
Dialog box for asking, whether to scan the contents of specified archive.
By default asking is disabled, and probably nobody uses it...
======================================================================*)
interface
uses
SysUtils,
{$ifdef mswindows}
WinTypes,WinProcs,
{$ELSE}
LCLIntf, LCLType, LMessages,
{$ENDIF}
Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, UTypes;
type
TFormScanArchive = class(TForm)
LabelMsg: TLabel;
ButtonYes: TButton;
ButtonNo: TButton;
ButtonYesAll: TButton;
ButtonNoAll: TButton;
procedure ButtonYesClick(Sender: TObject);
procedure ButtonYesAllClick(Sender: TObject);
procedure ButtonNoClick(Sender: TObject);
procedure ButtonNoAllClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
private
{ Private declarations }
public
Response: word;
procedure DefaultHandler(var Message); override;
end;
var
FormScanArchive: TFormScanArchive;
implementation
uses UCallbacks, FSettings;
{$R *.dfm}
//-----------------------------------------------------------------------------
procedure TFormScanArchive.ButtonYesClick(Sender: TObject);
begin
Response := cmYes;
ModalResult := mrOK;
end;
//-----------------------------------------------------------------------------
procedure TFormScanArchive.ButtonYesAllClick(Sender: TObject);
begin
Response := cmYesAll;
ModalResult := mrOK;
end;
//-----------------------------------------------------------------------------
procedure TFormScanArchive.ButtonNoClick(Sender: TObject);
begin
Response := cmNo;
ModalResult := mrOK;
end;
//-----------------------------------------------------------------------------
procedure TFormScanArchive.ButtonNoAllClick(Sender: TObject);
begin
Response := cmNoAll;
ModalResult := mrOK;
end;
//-----------------------------------------------------------------------------
procedure TFormScanArchive.FormActivate(Sender: TObject);
begin
Response := cmNo;
end;
//-----------------------------------------------------------------------------
// Disables CD AutoRun feature - Windows send the message QueryCancelAutoPlay
// to the top window, so we must have this handler in all forms.
procedure TFormScanArchive.DefaultHandler(var Message);
begin
with TMessage(Message) do
if (Msg = g_CommonOptions.dwQueryCancelAutoPlay) and
g_CommonOptions.bDisableCdAutorun
then
Result := 1
else
inherited DefaultHandler(Message)
end;
//-----------------------------------------------------------------------------
end.
|
program sudoku;
uses SysUtils;
const n_mat = 9;
version = '1.4.0';
autor = 'Micu Matei-Marius';
git_repo = 'https://github.com/micumatei/solve-sudoku';
gmail = 'micumatei@gmail.com';
licenta = 'The MIT License (MIT)';
type point = record
x, y :byte;
end;
vector = array[1..81] of point;
nod = record
liber :boolean; { daca locul e liber, adica la citirea matrici nu se aflau valori in nod }
valoare :byte; { ce valoare are }
end;
matrice_adj = array[1..81, 1..81] of boolean;
matrice_nod = array[1..9, 1..9] of nod;
var mat_a :matrice_adj;
mat_n :matrice_nod;
vec_goale :vector;
n, i :byte;
{ POINT functions / procedures }
function new_point(i, j :byte):point;
begin
with new_point do
begin
x := i;
y := j;
end;
end;
{ NOD functions / procedures }
procedure init_nod(var n :nod);
{ initializam un nod }
begin
with n do
begin
liber := false;
valoare := 0;
end;
end;
function new_nod(x :byte):nod;
{ cream un nod cu valoarea <x> }
begin
init_nod(new_nod); { initializam nodul }
with new_nod do
begin
valoare := x;
liber := (x = 0);
end;
end;
{ AJUTATOAREA functions / procedures}
procedure afis_mat_n(var m_n :matrice_nod);
var i, j :byte;
begin
for i := 1 to n_mat do
begin
for j := 1 to n_mat do
write(m_n[i, j].valoare:4, ' ');
writeln;
end;
end;
procedure init_mat_a(var m_a:matrice_adj);
{ initializam matricea de adiacenta }
var i, j:byte;
begin
for i := 1 to n_mat * n_mat do
for j := 1 to n_mat * n_mat do
m_a[i, j] := false;
end;
procedure afis_mat_a(var m_a:matrice_adj);
{ afisam matricea de adiacenta }
var i, j :integer;
begin
write(' ');
for i := 1 to n_mat * n_mat do
write('|',i);
writeln('|');
for i := 1 to n_mat * n_mat do
begin
write(i);
for j := 1 to n_mat * n_mat do
if m_a[i, j] then
write('x|')
else
write('0|');
writeln('|');
end;
end;
function generate_vec_poz(i, j:byte):byte;
{ returnam pozitia in vector a elementului din matrice de pe pozitia <i>, <j> }
begin
generate_vec_poz := (i-1)*n_mat + j;
end;
function generate_poz_p(a :byte):point;
var i, j :integer;
begin
with generate_poz_p do
begin
j := a mod n_mat;
if j = 0 then
j := 9;
i := ((a - j) div n_mat) + 1;
x := i;
y := j;
end;
end;
{ MAIN functions / procedures }
procedure init_program;
begin
n := 0; { numarul de elemente goale }
end;
procedure gen_mat_adj(var m_a:matrice_adj);
{ generam matricea de adiacenta }
var i, j, aux, i2, j2 :byte;
function get_corner(x :byte):byte;
{ cautam coltul patratului mic care compune matricea }
begin
get_corner := (((x-1) div 3)*3) + 1;
end;
begin
init_mat_a(m_a); { initializam matricea cu false }
for i := 1 to n_mat do
for j := 1 to n_mat do
begin
aux := generate_vec_poz(i, j); { locul elementului [i, j] in vectorul de elemente }
{ mergem pe coloane }
for j2 := 1 to n_mat do
if j2 <> j then
m_a[aux, generate_vec_poz(i, j2)] := true;
{ mergem pe linii }
for i2 := 1 to n_mat do
if i2 <> i then
m_a[generate_vec_poz(i2, j), j] := true;
{ circulam elementele din patratul mic }
for i2 := get_corner(i) to get_corner(i) + 2 do
for j2 := get_corner(j) to get_corner(j) + 2 do
if (i2 <>i) AND (j2 <> j) then
begin
m_a[aux, generate_vec_poz(i2, j2)] := true;
end;
end;
end;
procedure citire(var m_n :matrice_nod; s :string);
{ citim matricea cu elemente }
var i, j, aux :byte;
f :text;
begin
assign(f, s);
reset(f);
i := 0;
while not eof(f) do
begin
i := i + 1;
j := 0;
while not eoln(f) do
begin
j := j + 1;
read(f, aux);
m_n[i, j] := new_nod(aux);
if m_n[i, j].liber then { retinem punctul acesta ca element liber }
begin
n := n + 1;
vec_goale[n] := new_point(i, j); { retinem faptul ca acest element e gol si il putem modifica }
end;
end;
readln(f);
end;
close(f);
gen_mat_adj(mat_a); { generam matricea de adiacenta}
end;
procedure start_solve;
{ rezolvam matricea }
var rezolvat :boolean;
function get_nr_var(e :byte):byte;
{ returnam numarul de variabile pe care le poate lua elementul vec_goale[e] }
var v :array[1..n_mat] of boolean;
aux_p, aux_p2 :point;
i, aux :byte;
begin
{ initializam v cu false }
for i := 1 to n_mat do
v[i] := false;
aux_p := vec_goale[e];
get_nr_var := 0;
if mat_n[aux_p.x, aux_p.y].valoare = 0 then { cat timp nu am incercat deja o valoare aici}
begin
for i := 1 to n_mat * n_mat do
if mat_a[generate_vec_poz(aux_p.x, aux_p.y), i] then { exista legatura intre aux_p si i }
begin
aux_p2 := generate_poz_p(i);
aux := mat_n[aux_p2.x, aux_p2.y].valoare;
if aux <> 0 then
v[aux] := true;
end;
for i := 1 to n_mat do
if not v[i] then
inc(get_nr_var);
end
else
get_nr_var := 10;
end;
function get_min_var:byte;
var i, min, aux :byte;
{ returnam elementul liber care are minimul de variante posibile }
begin
min := 10;
for i := 1 to n do { circulam prin toate elementele libere }
begin
aux := get_nr_var(i);
if aux < min then
begin
min := aux;
get_min_var := i;
end;
end;
end;
function get_valid_var(e :byte):byte;
{ returnam urmatoarea varianta posibila }
var i, aux :byte;
v :array[1..n_mat] of boolean;
aux_p, aux_p2 :point;
begin
{ initializam v cu false }
for i := 1 to n_mat do
v[i] := false;
aux_p := vec_goale[e];
for i := 1 to n_mat * n_mat do
if mat_a[generate_vec_poz(aux_p.x, aux_p.y), i] then { exista legatura intre aux_p si i }
begin
aux_p2 := generate_poz_p(i);
aux := mat_n[aux_p2.x, aux_p2.y].valoare;
if aux <> 0 then
v[aux] := true;
end;
get_valid_var := 0;
for i := mat_n[aux_p.x, aux_p.y].valoare + 1 to n_mat do
if not v[i] then
begin
get_valid_var := i;
break;
end;
end;
procedure re_init(e :byte);
var aux_p :point;
begin
aux_p := vec_goale[e];
mat_n[aux_p.x, aux_p.y].valoare := 0;
end;
function solutie(e :byte):boolean;
begin
solutie := (e = n);
end;
procedure back(e :byte);
var aux_p :point;
{ procedura recursiva }
begin
aux_p := vec_goale[e];
if not rezolvat then
begin
re_init(e);
while ((get_valid_var(e) <> 0) AND (not rezolvat) ) do
begin
mat_n[aux_p.x, aux_p.y].valoare := get_valid_var(e);
if solutie(e) then
rezolvat := true
else
back(get_min_var);
end;
end;
end;
begin
if n > 0 then
begin
rezolvat := false;
back(get_min_var);
end
else
rezolvat := true;
if rezolvat then
afis_mat_n(mat_n)
else
writeln('Nu are solutie');
end;
procedure test;
{ teste }
begin
writeln('Am rulat !');
citire(mat_n, 'input.txt');
writeln('Am citit (2) :');
afis_mat_n(mat_n);
writeln('INitializam mat_adj');
writeln('Rezolvam:');
start_solve;
end;
begin
init_program;
if ParamCount > 0 then { s-a transmis un parametru }
begin
if (lowercase(ParamStr(1)) = '-h') OR (lowercase(ParamStr(1)) = '--help') OR (lowercase(ParamStr(1)) = '-?') then
begin
writeln;
writeln(' Acest program rezolva o matrice sudoku 9x9');
writeln(' Programul primeste ca parametri calea relativa catre fisierele care contin matricea .');
writeln(' Puteti afisa acest help message folosit comanda -h, --help sau -? .');
writeln(' Autor :', autor);
writeln(' GitHug :', git_repo);
writeln(' Gmail ', gmail);
writeln(' Licenta :', licenta);
writeln;
end
else
for i := 1 to ParamCount do
begin
writeln(' Citim fisierul : ', ParamStr(i));
if FileExists(ParamStr(i)) then
begin
citire(mat_n, ParamStr(i));
start_solve;
writeln;
end
else
begin
writeln(' Nu am gasit fisierul :', ParamStr(i) ,' ,va rugam verificati : ', git_repo);
writeln(' pentru mai multe informatii sau <-h> !');
end;
end;
end
else { nu s-a transmis nici un paramteru }
begin
writeln(' Nu s-a transmis un fisier, va rugam verificati : ', git_repo);
writeln(' pentru mai multe informatii sau <-h> !');
end;
end.
|
unit GameEngine;
interface
uses Tree, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, resource;
type
TGameEngine=class
private
Tree:TTree;
InitialState: TData;
FState:integer;
nilGraphic, cross, toe:TBitmap;
public
procedure Draw(Canvas:TCanvas);
procedure PlayerClick(X, Y:integer);
procedure EnimyClick;
function State:integer;
constructor Create;
destructor Destroy;
end;
var n:integer;
implementation
uses TicTacToe;
{ TGameEngine }
constructor TGameEngine.Create;
var
i,j:integer;
begin
for I := 0 to 2 do
for j := 0 to 2 do
InitialState[i,j]:=0;
nilgraphic:=TBitmap.Create;
cross:=TBitmap.Create;
toe:=TBitmap.Create;
n:=9;
FState:=-1;
toe:=GetToe;
cross:=GetCross;
nilGraphic:=GetNil;
nilGraphic.TransparentColor:=clwhite;
cross.Transparent:=true;
toe.Transparent:=true;
end;
destructor TGameEngine.Destroy;
begin
nilGraphic.Destroy;
cross.Destroy;
toe.Destroy;
end;
procedure TGameEngine.Draw(Canvas: TCanvas);
var
i,j:integer;
begin
Canvas.Pen.Width:=3;
for I := 0 to 2 do
for j := 0 to 2 do
if InitialState[i,j]=0 then
Canvas.Draw(i*96,j*96,nilGraphic)
else
if InitialState[i,j]=1 then
Canvas.Draw(i*96,j*96,cross)
else
if InitialState[i,j]=2 then
Canvas.Draw(i*96,j*96,toe);
Canvas.MoveTo(96,0);
Canvas.LineTo(96, 288);
Canvas.MoveTo(192, 0);
Canvas.LineTo(192, 288);
Canvas.MoveTo(0,96);
Canvas.LineTo(288, 96);
Canvas.MoveTo(0, 192);
Canvas.LineTo(288, 192);
end;
procedure TGameEngine.EnimyClick;
var key:integer;
begin
Tree:=TTree.Create;
Tree.InitializationTree(Tree.Root,InitialState,n,nil);
InitialState:=Tree.SearchState(Tree.Root, InitialState);
Tree.Destroy;
n:=n-1;
end;
procedure TGameEngine.PlayerClick(X, Y: integer);
begin
if InitialState[X div 96, Y div 96]=0 then
begin
InitialState[X div 96, Y div 96]:=1;
form1.Label5.Caption:='59';
form1.Timer3.Enabled:=true;
n:=n-1;
end;
end;
function TGameEngine.State: integer;
var key, p: integer;
I: Integer;
j: Integer;
begin
p:=0;
key:=keywin(InitialState);
if (Key=0) then
FState:=0 else
if (Key=5) then
FState:=1;
for I := 0 to 2 do
for j := 0 to 2 do
begin
if InitialState[i,j]<>0 then
p:=p+1;
end;
if (p=9) and (FState<>0) and (FState<>1)then
Fstate:=2;
result:=FState;
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
A collection of pure abstract classes - descendants of TVXShader, which are
used for purpose of not having to write the same stuff all over and over
again in your own shader classes.
It also contains a procedures and function that can be used in all shaders.
}
unit VXS.CustomShader;
interface
{$I VXScene.inc}
uses
System.Classes,
System.SysUtils,
VXS.OpenGL,
VXS.VectorGeometry,
VXS.VectorTypes,
VXS.Texture,
VXS.Cadencer,
VXS.Scene,
VXS.Strings,
VXS.Context,
VXS.RenderContextInfo,
VXS.Material,
VXS.VectorLists,
VXS.TextureFormat,
VXS.GLSLParameter;
const
vxsShaderMaxLightSources = 8;
type
TVXShaderFogSupport = (sfsEnabled, sfsDisabled, sfsAuto);
TVXTransformFeedBackMode = (tfbmInterleaved, tfbmSeparate);
EVXCustomShaderException = class(EVXShaderException);
TVXCustomShader = class;
TVXVertexProgram = class;
TVXFragmentProgram = class;
TVXGeometryProgram = class;
TVXShaderEvent = procedure(Shader: TVXCustomShader) of object;
TVXShaderUnAplyEvent = procedure(Shader: TVXCustomShader; var ThereAreMorePasses: Boolean) of object;
TVXLightSourceEnum = 1..vxsShaderMaxLightSources;
TVXLightSourceSet = set of TVXLightSourceEnum;
{ This interface describes user shaders, in order to be able to access them
via a unified interface. If user shader does not support some option, don't
raise an axception, just ignore it.
}
IGLShaderDescription = interface
['{04089C64-60C2-43F5-AC9C-38ED46264812}']
procedure SetShaderTextures(const Textures: array of TVXTexture);
procedure GetShaderTextures(var Textures: array of TVXTexture);
procedure SetShaderColorParams(const AAmbientColor, ADiffuseColor, ASpecularcolor: TVector4f);
procedure GetShaderColorParams(var AAmbientColor, ADiffuseColor, ASpecularcolor: TVector4f);
procedure SetShaderMiscParameters(const ACadencer: TVXCadencer; const AMatLib: TVXMaterialLibrary; const ALightSources: TVXLightSourceSet);
procedure GetShaderMiscParameters(var ACadencer: TVXCadencer; var AMatLib: TVXMaterialLibrary; var ALightSources: TVXLightSourceSet);
function GetShaderAlpha: Single;
procedure SetShaderAlpha(const Value: Single);
function GetShaderDescription: string;
end;
{ Used in the TVXPostShaderHolder component. }
IVXPostShader = interface
['{68A62362-AF0A-4CE8-A9E1-714FE02AFA4A}']
{ Called on every pass. }
procedure DoUseTempTexture(const TempTexture: TVXTextureHandle;
TextureTarget: TVXTextureTarget);
{ Called to determine if it is compatible. }
function GetTextureTarget: TVXTextureTarget;
end;
{ A pure abstract class, must be overriden. }
TVXCustomShader = class(TVXShader)
private
FFragmentProgram: TVXFragmentProgram;
FVertexProgram: TVXVertexProgram;
FGeometryProgram: TVXGeometryProgram;
FTagObject: TObject;
procedure SetFragmentProgram(const Value: TVXFragmentProgram);
procedure SetGeometryProgram(const Value: TVXGeometryProgram);
procedure SetVertexProgram(const Value: TVXVertexProgram);
function StoreFragmentProgram: Boolean;
function StoreGeometryProgram: Boolean;
function StoreVertexProgram: Boolean;
protected
FDebugMode: Boolean;
procedure SetDebugMode(const Value: Boolean); virtual;
property FragmentProgram: TVXFragmentProgram read FFragmentProgram write SetFragmentProgram stored StoreFragmentProgram;
property VertexProgram: TVXVertexProgram read FVertexProgram write SetVertexProgram stored StoreVertexProgram;
property GeometryProgram: TVXGeometryProgram read FGeometryProgram write SetGeometryProgram stored StoreGeometryProgram;
{ Treats warnings as errors and displays this error,
instead of a general shader-not-supported message. }
property DebugMode: Boolean read FDebugMode write SetDebugMode default False;
property TagObject: TObject read FTagObject write FTagObject default nil;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure LoadShaderPrograms(const VPFilename, FPFilename: string; GPFilename: string = '');
end;
{ A custom shader program. }
TVXShaderProgram = class(TPersistent)
private
FParent: TVXCustomShader;
FEnabled: Boolean;
FCode: TStrings;
procedure SetCode(const Value: TStrings);
procedure SetEnabled(const Value: Boolean);
procedure OnChangeCode(Sender: TObject);
protected
function GetOwner: TPersistent; override;
public
procedure LoadFromFile(const AFileName: string);
procedure Apply; virtual;
constructor Create(const AParent: TVXCustomShader); virtual;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
published
property Code: TStrings read FCode write SetCode;
property Enabled: Boolean read FEnabled write SetEnabled default False;
end;
TVXVertexProgram = class(TVXShaderProgram)
published
property Code;
property Enabled;
end;
TVXFragmentProgram = class(TVXShaderProgram)
published
property Code;
property Enabled;
end;
TVXGeometryProgram = class(TVXShaderProgram)
private
FInputPrimitiveType: TVXgsInTypes;
FOutputPrimitiveType: TVXgsOutTypes;
FVerticesOut: GLint;
procedure SetInputPrimitiveType(const Value: TVXgsInTypes);
procedure SetOutputPrimitiveType(const Value: TVXgsOutTypes);
procedure SetVerticesOut(const Value: GLint);
public
constructor Create(const AParent: TVXCustomShader); override;
published
property Code;
property Enabled;
property InputPrimitiveType: TVXgsInTypes read FInputPrimitiveType write SetInputPrimitiveType default gsInPoints;
property OutputPrimitiveType: TVXgsOutTypes read FOutputPrimitiveType write SetOutputPrimitiveType default gsOutPoints;
property VerticesOut: GLint read FVerticesOut write SetVerticesOut default 0;
end;
{ Wrapper around a parameter of the main program. }
TVXCustomShaderParameter = class(TObject)
private
protected
function GetAsVector1f: Single; virtual; abstract;
function GetAsVector2f: TVector2f; virtual; abstract;
function GetAsVector3f: TVector3f; virtual; abstract;
function GetAsVector4f: TVector; virtual; abstract;
function GetAsVector1i: Integer; virtual; abstract;
function GetAsVector2i: TVector2i; virtual; abstract;
function GetAsVector3i: TVector3i; virtual; abstract;
function GetAsVector4i: TVector4i; virtual; abstract;
function GetAsVector1ui: GLuint; virtual; abstract;
function GetAsVector2ui: TVector2ui; virtual; abstract;
function GetAsVector3ui: TVector3ui; virtual; abstract;
function GetAsVector4ui: TVector4ui; virtual; abstract;
procedure SetAsVector1f(const Value: Single); virtual; abstract;
procedure SetAsVector2f(const Value: TVector2f); virtual; abstract;
procedure SetAsVector3f(const Value: TVector3f); virtual; abstract;
procedure SetAsVector4f(const Value: TVector4f); virtual; abstract;
procedure SetAsVector1i(const Value: Integer); virtual; abstract;
procedure SetAsVector2i(const Value: TVector2i); virtual; abstract;
procedure SetAsVector3i(const Value: TVector3i); virtual; abstract;
procedure SetAsVector4i(const Value: TVector4i); virtual; abstract;
procedure SetAsVector1ui(const Value: GLuint); virtual; abstract;
procedure SetAsVector2ui(const Value: TVector2ui); virtual; abstract;
procedure SetAsVector3ui(const Value: TVector3ui); virtual; abstract;
procedure SetAsVector4ui(const Value: TVector4ui); virtual; abstract;
function GetAsMatrix2f: TMatrix2f; virtual; abstract;
function GetAsMatrix3f: TMatrix3f; virtual; abstract;
function GetAsMatrix4f: TMatrix4f; virtual; abstract;
procedure SetAsMatrix2f(const Value: TMatrix2f); virtual; abstract;
procedure SetAsMatrix3f(const Value: TMatrix3f); virtual; abstract;
procedure SetAsMatrix4f(const Value: TMatrix4f); virtual; abstract;
procedure SetAsTexture(const TextureIndex: Integer;
const Value: TVXTexture);
procedure SetAsTexture1D(const TextureIndex: Integer;
const Value: TVXTexture);
procedure SetAsTexture2D(const TextureIndex: Integer;
const Value: TVXTexture);
procedure SetAsTexture3D(const TextureIndex: Integer;
const Value: TVXTexture);
procedure SetAsTextureCube(const TextureIndex: Integer;
const Value: TVXTexture);
procedure SetAsTextureRect(const TextureIndex: Integer;
const Value: TVXTexture);
function GetAsCustomTexture(const TextureIndex: Integer;
TextureTarget: TVXTextureTarget): Cardinal; virtual; abstract;
procedure SetAsCustomTexture(const TextureIndex: Integer;
TextureTarget: TVXTextureTarget; const Value: Cardinal); virtual; abstract;
function GetAsUniformBuffer: GLenum; virtual; abstract;
procedure SetAsUniformBuffer(UBO: GLenum); virtual; abstract;
public
{ This overloaded SetAsVector accepts open array as input. e.g.
SetAsVectorF([0.1, 0.2]). Array length must between 1-4. }
procedure SetAsVectorF(const Values: array of Single); overload;
procedure SetAsVectorI(const Values: array of Integer); overload;
{ SetToTextureOf determines texture type on-the-fly.}
procedure SetToTextureOf(const LibMaterial: TVXLibMaterial; const TextureIndex: Integer); overload;
procedure SetToTextureOf(const Texture: TVXTexture; const TextureIndex: Integer); overload;
// friendly properties.
property AsVector: TVector read GetAsVector4f write SetAsVector4f;
property AsAffineVector: TAffineVector read GetAsVector3f write SetAsVector3f;
// Standard types.
property AsFloat: Single read GetAsVector1f write SetAsVector1f;
property AsInteger: Integer read GetAsVector1i write SetAsVector1i;
// Float vector types.
property AsVector1f: Single read GetAsVector1f write SetAsVector1f;
property AsVector2f: TVector2f read GetAsVector2f write SetAsVector2f;
property AsVector3f: TVector3f read GetAsVector3f write SetAsVector3f;
property AsVector4f: TVector4f read GetAsVector4f write SetAsVector4f;
// Integer vector types.
property AsVector1i: Integer read GetAsVector1i write SetAsVector1i;
property AsVector2i: TVector2i read GetAsVector2i write SetAsVector2i;
property AsVector3i: TVector3i read GetAsVector3i write SetAsVector3i;
property AsVector4i: TVector4i read GetAsVector4i write SetAsVector4i;
// Unsigned integer vector types.
property AsVector1ui: GLuint read GetAsVector1ui write SetAsVector1ui;
property AsVector2ui: TVector2ui read GetAsVector2ui write SetAsVector2ui;
property AsVector3ui: TVector3ui read GetAsVector3ui write SetAsVector3ui;
property AsVector4ui: TVector4ui read GetAsVector4ui write SetAsVector4ui;
// Matrix Types.
property AsMatrix2f: TMatrix2f read GetAsMatrix2f write SetAsMatrix2f;
property AsMatrix3f: TMatrix3f read GetAsMatrix3f write SetAsMatrix3f;
property AsMatrix4f: TMatrix4f read GetAsMatrix4f write SetAsMatrix4f;
// Texture Types.
property AsTexture [const TextureIndex: Integer]: TVXTexture write SetAsTexture;
property AsTexture1D [const TextureIndex: Integer]: TVXTexture write SetAsTexture1D;
property AsTexture2D [const TextureIndex: Integer]: TVXTexture write SetAsTexture2D;
property AsTexture3D [const TextureIndex: Integer]: TVXTexture write SetAsTexture3D;
property AsTextureRect[const TextureIndex: Integer]: TVXTexture write SetAsTextureRect;
property AsTextureCube[const TextureIndex: Integer]: TVXTexture write SetAsTextureCube;
property AsCustomTexture[const TextureIndex: Integer; TextureTarget: TVXTextureTarget]: Cardinal read GetAsCustomTexture write SetAsCustomTexture;
property AsUniformBuffer: GLenum read GetAsUniformBuffer write SetAsUniformBuffer;
end;
{ Adds two more blending modes to standard ones.
Not sure how to name them or if they should be included in TBlending mode,
so I created a new type here. }
TVXBlendingModeEx = (bmxOpaque, bmxTransparency, bmxAdditive,
bmxAlphaTest50, bmxAlphaTest100, bmxModulate,
bmxDestColorOne, bmxDestAlphaOne);
// Exported procedures.
procedure ApplyBlendingModeEx(const BlendingMode: TVXBlendingModeEx);
procedure UnApplyBlendingModeEx;
procedure InitTexture(
const TextureHandle: Cardinal;
const TextureSize: TVXSize;
const TextureTarget: TVXTextureTarget = ttTexture2D);
// Probably need to give them proper names, instead of numbers...
procedure DrawTexturedScreenQuad;
procedure DrawTexturedScreenQuad2(const ViewPortSize: TVXSize);
procedure DrawTexturedScreenQuad3;
procedure DrawTexturedScreenQuad4(const ViewPortSize: TVXSize);
procedure DrawTexturedScreenQuad5(const ViewPortSize: TVXSize);
procedure DrawTexturedScreenQuad6(const ViewPortSize: TVXSize);
procedure CopyScreentoTexture(const ViewPortSize: TVXSize; const TextureTarget: Word = GL_TEXTURE_2D);
procedure CopyScreentoTexture2(const ViewPortSize: TVXSize; const TextureTarget: Word = GL_TEXTURE_2D);
function IsFogEnabled(const AFogSupportMode: TVXShaderFogSupport; var rci: TVXRenderContextInfo): Boolean;
procedure GetActiveLightsList(const ALightIDs: TIntegerList);
implementation
uses
VXS.State;
procedure GetActiveLightsList(const ALightIDs: TIntegerList);
var
I: Integer;
begin
ALightIDs.Clear;
with CurrentVXContext.VxStates do
begin
for I := 0 to MaxLights - 1 do
begin
if LightEnabling[I] then
ALightIDs.Add(I);
end;
end;
end;
function IsFogEnabled(const AFogSupportMode: TVXShaderFogSupport; var rci: TVXRenderContextInfo): Boolean;
begin
case AFogSupportMode of
sfsEnabled: Result := True;
sfsDisabled: Result := False;
sfsAuto: Result := TVXSceneBuffer(rci.buffer).FogEnable;
else
Result := False;
Assert(False, strUnknownType);
end;
end;
procedure CopyScreentoTexture(const ViewPortSize: TVXSize; const TextureTarget: Word = GL_TEXTURE_2D);
begin
glCopyTexSubImage2D(TextureTarget, 0, 0, 0, 0, 0, ViewPortSize.cx, ViewPortSize.cy);
end;
procedure CopyScreentoTexture2(const ViewPortSize: TVXSize; const TextureTarget: Word = GL_TEXTURE_2D);
begin
glCopyTexImage2D(TextureTarget, 0, GL_RGB, 0, 0, ViewPortSize.cx, ViewPortSize.cy, 0);
end;
procedure ApplyBlendingModeEx(const BlendingMode: TVXBlendingModeEx);
begin
with CurrentVXContext.VxStates do
begin
Enable(stBlend);
case BlendingMode of
bmxOpaque: SetBlendFunc(bfSRCALPHA, bfONE);
bmxTransparency: SetBlendFunc(bfSRCALPHA, bfONEMINUSSRCALPHA);
bmxAdditive: SetBlendFunc(bfSRCALPHA, bfONE);
bmxAlphaTest50: SetAlphaFunction(cfGEQUAL, 0.5);
bmxAlphaTest100: SetAlphaFunction(cfGEQUAL, 1.0);
bmxModulate: SetBlendFunc(bfDSTCOLOR, bfZERO);
bmxDestColorOne: SetBlendFunc(bfDSTCOLOR, bfONE);
bmxDestAlphaOne: SetBlendFunc(bfDSTALPHA, bfONE);
else
Assert(False, strErrorEx + strUnknownType);
end;
end;
end;
procedure UnApplyBlendingModeEx;
begin
end;
procedure DrawTexturedScreenQuad;
begin
glMatrixMode(GL_MODELVIEW);
glPushMatrix;
glLoadIdentity;
glMatrixMode(GL_PROJECTION);
glPushMatrix;
glLoadIdentity;
// drawing rectangle over screen
glDisable(GL_DEPTH_TEST);
DrawTexturedScreenQuad3;
glEnable(GL_DEPTH_TEST);
glPopMatrix;
glMatrixMode(GL_MODELVIEW);
glPopMatrix;
end;
procedure DrawTexturedScreenQuad2(const ViewPortSize: TVXSize);
begin
glPushMatrix;
glMatrixMode(GL_PROJECTION);
glPushMatrix;
glLoadIdentity;
glOrtho(0, ViewPortSize.cx, ViewPortSize.cy, 0, 0, 1);
glDisable(GL_DEPTH_TEST);
glDepthMask(GLboolean(False));
glBegin(GL_QUADS);
glTexCoord2f(0.0, ViewPortSize.cy); glVertex2f(0, 0);
glTexCoord2f(0.0, 0.0); glVertex2f(0, ViewPortSize.cy);
glTexCoord2f(ViewPortSize.cx, 0.0); glVertex2f(ViewPortSize.cx, ViewPortSize.cy);
glTexCoord2f(ViewPortSize.cx, ViewPortSize.cy); glVertex2f(ViewPortSize.cx, 0);
glEnd;
glDepthMask(GLboolean(True));
glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glPopMatrix;
glMatrixMode(GL_MODELVIEW);
glPopMatrix;
end;
procedure DrawTexturedScreenQuad4(const ViewPortSize: TVXSize);
begin
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex2f(-1, -1);
glTexCoord2f(ViewPortSize.cx, 0); glVertex2f( 1, -1);
glTexCoord2f(ViewPortSize.cx, ViewPortSize.cy); glVertex2f( 1, 1);
glTexCoord2f(0, ViewPortSize.cy); glVertex2f(-1, 1);
glEnd;
end;
procedure DrawTexturedScreenQuad5(const ViewPortSize: TVXSize);
begin
glMatrixMode( GL_PROJECTION );
glPushMatrix;
glLoadIdentity;
glOrtho( 0, ViewPortSize.cx, ViewPortSize.cy, 0, 0, 1 );
glMatrixMode(GL_MODELVIEW);
glPushMatrix;
glLoadIdentity;
glDisable(GL_DEPTH_TEST);
glDepthMask(GLboolean(False));
DrawTexturedScreenQuad3;
glDepthMask(GLboolean(True));
glEnable(GL_DEPTH_TEST);
glPopMatrix;
glMatrixMode( GL_PROJECTION );
glPopMatrix;
glMatrixMode( GL_MODELVIEW );
end;
procedure DrawTexturedScreenQuad6(const ViewPortSize: TVXSize);
begin
glMatrixMode( GL_PROJECTION );
glPushMatrix;
glLoadIdentity;
glOrtho( 0, ViewPortSize.cx, ViewPortSize.cy, 0, 0, 1 );
glMatrixMode(GL_MODELVIEW);
glPushMatrix;
glLoadIdentity;
glDisable(GL_DEPTH_TEST);
glDepthMask(GLboolean(FALSE));
DrawTexturedScreenQuad4(ViewPortSize);;
glDepthMask(GLboolean(True));
glEnable(GL_DEPTH_TEST);
glPopMatrix;
glMatrixMode(GL_PROJECTION );
glPopMatrix;
glMatrixMode(GL_MODELVIEW );
end;
procedure DrawTexturedScreenQuad3;
begin
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex2f(-1, -1);
glTexCoord2f(1, 0); glVertex2f(1, -1);
glTexCoord2f(1, 1); glVertex2f(1, 1);
glTexCoord2f(0, 1); glVertex2f(-1, 1);
glEnd;
end;
procedure InitTexture(
const TextureHandle: Cardinal;
const TextureSize: TVXSize;
const TextureTarget: TVXTextureTarget = ttTexture2D);
var
glTarget: GLEnum;
begin
with CurrentVXContext.VxStates do
begin
TextureBinding[ActiveTexture, TextureTarget] := TextureHandle;
end;
glTarget := DecodeTextureTarget(TextureTarget);
glTexParameteri(glTarget, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(glTarget, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(glTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(glTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glCopyTexImage2D(glTarget, 0, GL_RGBA8, 0, 0, TextureSize.cx, TextureSize.cy, 0);
end;
{ TVXShaderProgram }
procedure TVXShaderProgram.Apply;
begin
FParent.FinalizeShader;
end;
procedure TVXShaderProgram.Assign(Source: TPersistent);
begin
if Source = nil then
Exit;
if (Source is TVXShaderProgram) then
begin
FEnabled := TVXShaderProgram(Source).FEnabled;
FCode.Assign(TVXShaderProgram(Source).FCode);
end
else
inherited; //die, die, die!!!
end;
constructor TVXShaderProgram.Create(const AParent: TVXCustomShader);
begin
FParent := AParent;
FCode := TStringList.Create;
TStringList(FCode).OnChange := OnChangeCode;
FEnabled := False;
end;
destructor TVXShaderProgram.Destroy;
begin
FCode.Destroy;
end;
function TVXShaderProgram.GetOwner: TPersistent;
begin
Result := FParent;
end;
procedure TVXShaderProgram.LoadFromFile(const AFileName: string);
begin
FCode.LoadFromFile(AFileName);
FEnabled := True;
end;
procedure TVXShaderProgram.OnChangeCode(Sender: TObject);
begin
FEnabled := True;
FParent.NotifyChange(self);
end;
procedure TVXShaderProgram.SetCode(const Value: TStrings);
begin
FCode.Assign(Value);
FParent.NotifyChange(self);
end;
procedure TVXShaderProgram.SetEnabled(const Value: Boolean);
begin
if Value = FEnabled then
Exit;
FEnabled := Value;
if FEnabled then
FParent.FinalizeShader;
end;
{ TVXCustomShader }
procedure TVXCustomShader.Assign(Source: TPersistent);
begin
if Source is TVXCustomShader then
begin
FFragmentProgram.Assign(TVXCustomShader(Source).FFragmentProgram);
FVertexProgram.Assign(TVXCustomShader(Source).FVertexProgram);
FGeometryProgram.Assign(TVXCustomShader(Source).FGeometryProgram);
FTagObject := TVXCustomShader(Source).FTagObject;
end;
inherited;
end;
constructor TVXCustomShader.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDebugMode := False;
FFragmentProgram := TVXFragmentProgram.Create(Self);
FVertexProgram := TVXVertexProgram.Create(Self);
FGeometryProgram := TVXGeometryProgram.Create(Self);
end;
destructor TVXCustomShader.Destroy;
begin
FFragmentProgram.Destroy;
FVertexProgram.Destroy;
FGeometryProgram.Destroy;
inherited;
end;
procedure TVXCustomShader.LoadShaderPrograms(const VPFilename, FPFilename: string; GPFilename: string = '');
begin
If VPFilename <> '' then VertexProgram.LoadFromFile(VPFilename);
If FPFilename <> '' then FragmentProgram.LoadFromFile(FPFilename);
If GPFilename <> '' then GeometryProgram.LoadFromFile(GPFilename);
end;
procedure TVXCustomShader.SetDebugMode(const Value: Boolean);
begin
if FDebugMode <> Value then
begin
FDebugMode := Value;
if FDebugMode then
FailedInitAction := fiaReRaiseException
else
FailedInitAction := fiaRaiseStandardException;
end;
end;
procedure TVXCustomShader.SetFragmentProgram(const Value: TVXFragmentProgram);
begin
FFragmentProgram.Assign(Value);
end;
procedure TVXCustomShader.SetGeometryProgram(const Value: TVXGeometryProgram);
begin
FGeometryProgram.Assign(Value);
end;
procedure TVXCustomShader.SetVertexProgram(const Value: TVXVertexProgram);
begin
FVertexProgram.Assign(Value);
end;
function TVXCustomShader.StoreFragmentProgram: Boolean;
begin
Result := FFragmentProgram.Enabled or (FFragmentProgram.Code.Text <> '')
end;
function TVXCustomShader.StoreGeometryProgram: Boolean;
begin
Result := FGeometryProgram.Enabled or (FGeometryProgram.Code.Text <> '')
end;
function TVXCustomShader.StoreVertexProgram: Boolean;
begin
Result := FVertexProgram.Enabled or (FVertexProgram.Code.Text <> '')
end;
{ TVXCustomShaderParameter }
procedure TVXCustomShaderParameter.SetAsTexture(
const TextureIndex: Integer; const Value: TVXTexture);
begin
SetAsCustomTexture(TextureIndex, Value.TextureHandle.Target, Value.Handle);
end;
procedure TVXCustomShaderParameter.SetAsTexture1D(
const TextureIndex: Integer; const Value: TVXTexture);
begin
SetAsCustomTexture(TextureIndex, ttTexture1D, Value.Handle);
end;
procedure TVXCustomShaderParameter.SetAsTexture2D(
const TextureIndex: Integer; const Value: TVXTexture);
begin
SetAsCustomTexture(TextureIndex, ttTexture2D, Value.Handle);
end;
procedure TVXCustomShaderParameter.SetAsTexture3D(
const TextureIndex: Integer; const Value: TVXTexture);
begin
SetAsCustomTexture(TextureIndex, ttTexture3D, Value.Handle);
end;
procedure TVXCustomShaderParameter.SetAsTextureCube(
const TextureIndex: Integer; const Value: TVXTexture);
begin
SetAsCustomTexture(TextureIndex, ttTextureCube, Value.Handle);
end;
procedure TVXCustomShaderParameter.SetAsTextureRect(
const TextureIndex: Integer; const Value: TVXTexture);
begin
SetAsCustomTexture(TextureIndex, ttTextureRect, Value.Handle);
end;
procedure TVXCustomShaderParameter.SetAsVectorF(const Values: array of Single);
begin
case Length(Values) of
1: SetAsVector1f(Values[0]);
2: SetAsVector2f(Vector2fMake(Values[0], Values[1]));
3: SetAsVector3f(Vector3fMake(Values[0], Values[1], Values[2]));
4: SetAsVector4f(Vector4fMake(Values[0], Values[1], Values[2], Values[3]));
else
Assert(False, 'Vector length must be between 1 to 4');
end;
end;
procedure TVXCustomShaderParameter.SetAsVectorI(const Values: array of Integer);
begin
case Length(Values) of
1: SetAsVector1i(Values[0]);
2: SetAsVector2i(Vector2iMake(Values[0], Values[1]));
3: SetAsVector3i(Vector3iMake(Values[0], Values[1], Values[2]));
4: SetAsVector4i(Vector4iMake(Values[0], Values[1], Values[2], Values[3]));
else
Assert(False, 'Vector length must be between 1 to 4');
end;
end;
procedure TVXCustomShaderParameter.SetToTextureOf(
const LibMaterial: TVXLibMaterial; const TextureIndex: Integer);
begin
SetToTextureOf(LibMaterial.Material.Texture, TextureIndex);
end;
procedure TVXCustomShaderParameter.SetToTextureOf(
const Texture: TVXTexture; const TextureIndex: Integer);
begin
SetAsCustomTexture(TextureIndex, Texture.Image.NativeTextureTarget, Texture.Handle);
end;
constructor TVXGeometryProgram.Create(const AParent: TVXCustomShader);
begin
inherited Create(AParent);
FInputPrimitiveType := gsInPoints;
FOutputPrimitiveType := gsOutPoints;
FVerticesOut := 0;
end;
procedure TVXGeometryProgram.SetInputPrimitiveType(const Value: TVXgsInTypes);
begin
if Value <> FInputPrimitiveType then
begin
FInputPrimitiveType := Value;
FParent.NotifyChange(Self);
end;
end;
procedure TVXGeometryProgram.SetOutputPrimitiveType(const Value: TVXgsOutTypes);
begin
if Value<>FOutputPrimitiveType then
begin
FOutputPrimitiveType := Value;
FParent.NotifyChange(Self);
end;
end;
procedure TVXGeometryProgram.SetVerticesOut(const Value: GLint);
begin
if Value<>FVerticesOut then
begin
FVerticesOut := Value;
FParent.NotifyChange(Self);
end;
end;
initialization
RegisterClasses([TVXCustomShader, TVXShaderProgram,
TVXVertexProgram, TVXFragmentProgram, TVXGeometryProgram]);
end. |
(*
Category: SWAG Title: MEMORY/DPMI MANAGEMENT ROUTINES
Original name: 0027.PAS
Description: Loading a file on HEAP
Author: GUY MCLOUGHLIN
Date: 08-27-93 21:32
*)
{
GUY MCLOUGHLIN
>How would I load a file straight into memory, and access it directly
>using pointers?
Load file data onto the HEAP memory-pool.
}
program LoadFileOnHEAP;
type
{ Array type used to define the data buffer. }
arby_60K = array[1..61440] of byte;
{ Pointer type used to allocate the data buffer on the HEAP memory pool. }
po_60KBuff = ^arby_60K;
const
{ Buffer size in bytes constant. }
co_BuffSize = sizeof(arby_60K);
{ Check for IO errors, close data file if necessary. }
procedure CheckForErrors(var fi_Temp : file; bo_CloseFile : boolean);
var
by_Temp : byte;
begin
by_Temp := ioresult;
if (by_Temp <> 0) then
begin
writeln('FILE ERROR = ', by_Temp);
if bo_CloseFile then
close(fi_Temp);
halt(1)
end
end;
var
wo_BuffIndex,
wo_BytesRead : word;
po_Buffer : po_60KBuff;
fi_Temp : file;
BEGIN
assign(fi_Temp, 'EE.PAS');
{$I-}
reset(fi_Temp, 1);
{$I+}
CheckForErrors(fi_Temp, false);
{ Check if there is enough free memory on the HEAP. }
{ If there is, then allocate buffer on the HEAP. }
{if (maxavail > co_BuffSize) then}
new(po_Buffer);
{else
begin
close(fi_Temp);
writeln('ERROR: Insufficient HEAP memory!')
end;}
{ Load file-data into buffer. }
blockread(fi_Temp, po_Buffer^, co_BuffSize, wo_BytesRead);
CheckForErrors(fi_Temp, true);
{ Display each byte that was read-in. }
for wo_BuffIndex := 1 to wo_BytesRead do
write(chr(po_Buffer^[wo_BuffIndex]));
close(fi_Temp)
END.
|
unit FHIRServerConstants;
interface
Const
SERVER_VERSION = '1.00.000';
SERVER_RELEASE_DATE = '2014-07-23';
implementation
end.
|
{: Parallel projection demo.<p>
This simple demo shows how to do parallel projection and blend some custom
OpenGL calls into the scene.<br>
You can change the viewpoint with left clic drags, change the plane orientation
with right clic drags, and move the plane up/down with the wheel.<p>
The points and plane are rendered directly with regular scene objects,
but the projection lines between the points and the plane are computed
and rendered on the fly in a TGLDirectOpenGL. This is a typical case where
a little bit of custom code helps a lot: we could have used many TGLLines
object to draw the lines, but this would have resulted in a lot of object
creation and update code, and ultimately in rather poor performance.<br>
Note the position of the plane in the scene hierarchy: it is last as it is
a blended object. Try making it the first object, it will appear opaque
(though it is still transparent!).
}
unit Unit1;
{$MODE Delphi}
interface
uses
SysUtils, Classes, Controls, Forms, GLScene, GLObjects,
GLLCLViewer, OpenGLTokens, GLContext, GLTexture, GLVectorGeometry, GLGraph,
GLGeomObjects, GLCrossPlatform, GLCoordinates,
GLRenderContextInfo, GLState;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
SceneViewer: TGLSceneViewer;
GLCamera: TGLCamera;
GLDummyCube: TGLDummyCube;
GLPlane: TGLPlane;
GLPoints: TGLPoints;
DirectOpenGL: TGLDirectOpenGL;
GLArrowLine1: TGLArrowLine;
GLLightSource1: TGLLightSource;
GLXYZGrid1: TGLXYZGrid;
procedure FormCreate(Sender: TObject);
procedure DirectOpenGLRender(Sender: TObject; var rci: TRenderContextInfo);
procedure SceneViewerMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: integer);
procedure SceneViewerMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: integer);
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: integer; MousePos: TPoint; var Handled: boolean);
private
{ Private declarations }
public
{ Public declarations }
mx, my: integer;
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
procedure TForm1.FormCreate(Sender: TObject);
var
i: integer;
begin
// generate a bunch of random points
for i := 1 to 100 do
GLPoints.Positions.Add((Random - 0.5) * 5, (Random - 0.5) * 5, (Random - 0.5) * 5);
end;
procedure TForm1.DirectOpenGLRender(Sender: TObject; var rci: TRenderContextInfo);
var
i: integer;
mat: TMatrix;
p, pProj: TVector;
planePoint, planeNormal: TVector;
plane: THmgPlane;
begin
// Here we recover our plane point and normal...
planePoint := GLPlane.Position.AsVector;
planeNormal := GLPlane.Direction.AsVector;
// ...which we use to create a plane (equation)
plane := PlaneMake(planePoint, planeNormal);
// from that plane equation and our pojection direction
// (which is here the plane normal)
mat := MakeParallelProjectionMatrix(plane, planeNormal);
// save state, turn off lighting and specify the lines color
rci.GLStates.Disable(stLighting);
GL.Color3f(1, 1, 0);
// we'll be drawing a bunch of lines, to specify a line in OpenGL,
// you only need to specify the line start and end vertices
GL.Begin_(GL_LINES);
for i := 0 to GLPoints.Positions.Count - 1 do
begin
// read the point coordinates, directly from the TGLPoints list
MakePoint(p, GLPoints.Positions.List[i]);
// project this point on the plane with the matrix
pProj := VectorTransform(p, mat);
// specify the two vertices
GL.Vertex3fv(@p);
GL.Vertex3fv(@pProj);
end;
GL.End_;
end;
procedure TForm1.SceneViewerMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: integer);
begin
mx := x;
my := y;
end;
procedure TForm1.SceneViewerMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: integer);
begin
if Shift = [ssLeft] then
GLCamera.MoveAroundTarget(my - y, mx - x)
else if Shift = [ssRight] then
GLCamera.RotateObject(GLPlane, my - y, mx - x);
mx := x;
my := y;
end;
procedure TForm1.FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: integer; MousePos: TPoint; var Handled: boolean);
begin
GLPlane.Position.Y := GLPlane.Position.Y + WheelDelta * 0.001;
end;
end.
|
unit TestThItemCircle;
{
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, BaseTestUnit, FMX.Types, FMX.Forms,
System.UITypes, System.Types, System.SysUtils, FMX.Controls, System.UIConsts;
type
// Test methods for class TThCircle
// #21 캔버스에 원을 추가한다.
TestTThCircle = class(TThCanvasBaseTestUnit)
published
procedure TestItemFactory;
// #116 마우스 드래그로 시작점과 끝점을 이용해 도형을 그린다.
procedure TestDrawCircle;
// #117 끝점이 시작점의 앞에 있어도 그려져야 한다.
procedure TestDrawCircleRightToLeft;
// #118 최소 크기로 그려진다.
procedure TestDrawCircleMinimum;
// #120 크기 조정이 가능해야 한다.
procedure TestCircleResize;
// #121 반대방향으로도 크기조정이 가능해야 한다.
procedure TestCircleResizeLeftToRight;
procedure TestCircleResizeTopToBottom;
procedure TestCircleResizeRightToLeft;
procedure TestCircleResizeBottomToTop;
// #119 크기조정 시 최소 크기가 적용되어야 한다.
procedure TestCircleResizeEx;
end;
implementation
uses
FMX.TestLib, ThItem, ThShapeItem, ThItemFactory, ThConsts;
{ TestTThCircle }
procedure TestTThCircle.TestItemFactory;
var
Item: TThItem;
begin
// 1300 is Circle
Item := ItemFactory.Get(1300);
try
Check(Assigned(Item));
finally
if Assigned(Item) then
Item.Free;
end;
end;
procedure TestTThCircle.TestDrawCircle;
var
Item: TThItem;
begin
DrawCircle(50, 50, 200, 200);
TestLib.RunMouseClick(100, 100);
Item := FCanvas.SelectedItem;
Check(Assigned(Item), 'Check SelectedItem');
Check(Item.ClassType = TThCircle, 'Check Class type');
Check(Item.Position.X = -100, Format('X = %f', [Item.Position.X]));
Check(Item.Width = 150, Format('Width = %f', [Item.Width]));
end;
procedure TestTThCircle.TestDrawCircleRightToLeft;
var
Item: TThItem;
begin
DrawCircle(200, 200, 50, 50);
TestLib.RunMouseClick(100, 100);
Item := FCanvas.SelectedItem;
Check(Assigned(Item), 'Check SelectedItem');
Check(Item.ClassType = TThCircle, 'Check Class type');
Check(Item.Position.X = -100, Format('X = %f', [Item.Position.X]));
Check(Item.Width = 150, Format('Width = %f', [Item.Width]));
end;
procedure TestTThCircle.TestDrawCircleMinimum;
var
Item: TThItem;
begin
DrawCircle(50, 50, 50, 50);
TestLib.RunMouseClick(65, 65);
Item := FCanvas.SelectedItem;
Check(Assigned(Item), 'Check SelectedItem');
Check(Item.ClassType = TThCircle, 'Check Class type');
Check(Item.Width = 30, Format('Width = %f', [Item.Width]));
end;
procedure TestTThCircle.TestCircleResize;
begin
DrawCircle(50, 50, 100, 100);
TestLib.RunMouseClick(65, 65);
MousePath.New
.Add(100, 75)
.Add(120, 75)
.Add(150, 75);
TestLib.RunMousePath(MousePath.Path);
TestLib.RunMouseClick(150, 150);
TestLib.RunMouseClick(130, 75);
Check(Assigned(FCanvas.SelectedItem), 'Not assigned');
Check((FCanvas.SelectedItem.Width = 100) and (FCanvas.SelectedItem.Height = 50),
Format('W,H : %f, %f', [FCanvas.SelectedItem.Width, FCanvas.SelectedItem.Height]));
end;
procedure TestTThCircle.TestCircleResizeLeftToRight;
begin
DrawCircle(50, 50, 150, 150);
TestLib.RunMouseClick(100, 100);
MousePath.New
.Add(50, 100)
.Add(150, 100)
.Add(200, 100);
TestLib.RunMousePath(MousePath.Path);
TestLib.RunMouseClick(0, 0);
TestLib.RunMouseClick(175, 100);
Check(Assigned(FCanvas.SelectedItem), 'Not assigned');
Check((Round(FCanvas.SelectedItem.Width) = 50) and (FCanvas.SelectedItem.Height = 100),
Format('W,H : %f, %f', [FCanvas.SelectedItem.Width, FCanvas.SelectedItem.Height]));
end;
procedure TestTThCircle.TestCircleResizeTopToBottom;
begin
DrawCircle(50, 50, 150, 150);
TestLib.RunMouseClick(100, 100);
MousePath.New
.Add(100, 50)
.Add(100, 150)
.Add(100, 200);
TestLib.RunMousePath(MousePath.Path);
TestLib.RunMouseClick(0, 0);
TestLib.RunMouseClick(100, 175);
Check(Assigned(FCanvas.SelectedItem), 'Not assigned');
Check((FCanvas.SelectedItem.Width = 100) and (Round(FCanvas.SelectedItem.height) = 50),
Format('W,H : %f, %f', [FCanvas.SelectedItem.Width, FCanvas.SelectedItem.Height]));
end;
procedure TestTThCircle.TestCircleResizeRightToLeft;
begin
DrawCircle(150, 150, 250, 250);
TestLib.RunMouseClick(200, 200);
MousePath.New
.Add(250, 200)
.Add(150, 200)
.Add(50, 200);
TestLib.RunMousePath(MousePath.Path);
TestLib.RunMouseClick(0, 0);
TestLib.RunMouseClick(100, 200);
Check(Assigned(FCanvas.SelectedItem), 'Not assigned');
Check((Round(FCanvas.SelectedItem.Width) = 100) and (Round(FCanvas.SelectedItem.Height) = 100),
Format('W,H : %f, %f', [FCanvas.SelectedItem.Width, FCanvas.SelectedItem.Height]));
end;
procedure TestTThCircle.TestCircleResizeBottomToTop;
begin
DrawCircle(100, 100, 200, 200);
TestLib.RunMouseClick(165, 165);
//크기 조정(50, 50, 150, 100)
MousePath.New
.Add(150, 200)
.Add(150, 100)
.Add(150, 50);
TestLib.RunMousePath(MousePath.Path);
TestLib.RunMouseClick(0, 0);
TestLib.RunMouseClick(150, 75);
Check(Assigned(FCanvas.SelectedItem), 'Not assigned');
Check((FCanvas.SelectedItem.Width = 100) and (FCanvas.SelectedItem.height = 50),
Format('W,H : %f, %f', [FCanvas.SelectedItem.Width, FCanvas.SelectedItem.Height]));
end;
procedure TestTThCircle.TestCircleResizeEx;
begin
DrawCircle(100, 100, 200, 200);
TestLib.RunMouseClick(165, 165);
//크기 조정(50, 50, 150, 100)
MousePath.New
.Add(150, 100)
// .Add(150, 185)
.Add(200, 185)
.Add(150, 190);
TestLib.RunMousePath(MousePath.Path);
TestLib.RunMouseClick(0, 0);
TestLib.RunMouseClick(150, 185);
Check(Assigned(FCanvas.SelectedItem), 'Not assigned');
Check((FCanvas.SelectedItem.Width = 100) and (FCanvas.SelectedItem.height = 30),
Format('W,H : %f, %f', [FCanvas.SelectedItem.Width, FCanvas.SelectedItem.Height]));
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTThCircle.Suite);
end.
|
{-------------------------------------------------------------------------
Copyright by Haeger + Busch, Germany / >>>>>>>>> /-----
Ingenieurbuero fuer Kommunikationslösungen / <<<<<<<<< /
----------------------------------------------------/ >>>>>>>>> /
Homepage : http://www.hbTapi.com
EMail : info@hbTapi.com
Package : hbTapi Components
-------------------------------------------------------------------------}
unit hbTapiDlgA;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, hbTapiComm;
type
TComPortSettingsDlg = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
ButtonCancel: TButton;
ButtonOk: TButton;
Label6: TLabel;
Bevel1: TBevel;
Label_Port: TLabel;
cbPort: TComboBox;
cbBaud: TComboBox;
cbDataBits: TComboBox;
cbParity: TComboBox;
cbStopBits: TComboBox;
cbHandshake: TComboBox;
procedure FormCreate(Sender: TObject);
procedure DoChangePort(Sender: TObject);
private
FPortName : String;
function GetMode: String;
function GetBaud: Integer;
procedure Set_Baud(const Value: Integer);
function GetParity: Byte;
procedure Set_Parity(Value: Byte);
function GetDatabits: Integer;
procedure Set_DataBits(const Value: Integer);
procedure Set_Port(const Value: String);
function GetPort: String;
function GetStopbits: Integer;
procedure Set_StopBits(Value: Integer);
function GetHandshake: DWORD;
procedure Set_Handshake(const Value: DWORD);
public
function Execute: Boolean;
property PortName : String read GetPort write Set_Port;
property Baud : Integer read GetBaud write Set_Baud;
property Parity : Byte read GetParity write Set_Parity;
property DataBits : Integer read GetDatabits write Set_DataBits;
property StopBits : Integer read GetStopbits write Set_StopBits;
property Handshake: DWORD read GetHandshake write Set_Handshake;
end;
implementation
uses winspool;
{$R *.DFM}
function TComPortSettingsDlg.Execute: Boolean;
begin
result := ShowModal = mrOK;
end;
function TComPortSettingsDlg.GetMode: String;
begin
// Port, Baud
result := Format('%s: baud=%d', [PortName, Baud]);
// Parity
case cbParity.ItemIndex of
0: result := result + ' parity=n'; // Keine
1: result := result + ' parity=o'; // Ungerade
2: result := result + ' parity=e'; // Gerade
3: result := result + ' parity=m'; // Markierung
4: result := result + ' parity=s'; // Leerzeichen
end;
// Datenbits
result := result + ' data=' + cbDataBits.Text;
// Stopbits
result := result + ' stop=' + cbStopBits.Text;
// Protocol
if cbHandshake.ItemIndex = 1 then // Software
begin
result := result + ' xon=on octs=off rts=off';
end
else if cbHandshake.ItemIndex = 2 then // Hardware
begin
result := result + ' xon=off octs=on rts=hs';
end
else
begin
result := result + ' xon=off octs=off rts=off';
end;
end;
function TComPortSettingsDlg.GetBaud: Integer;
begin
result := StrToIntDef(cbBaud.Text, 19200);
end;
function TComPortSettingsDlg.GetParity: Byte;
begin
case cbParity.ItemIndex of
1 : result := ODDPARITY;
2 : result := EVENPARITY;
3 : result := MARKPARITY;
4 : result := SPACEPARITY;
else
result := NOPARITY;
end;
end;
procedure TComPortSettingsDlg.Set_Baud(const Value: Integer);
var i : integer;
begin
i := cbBaud.Items.IndexOf(IntToStr(Value));
if i >= 0 then
cbBaud.ItemIndex := i;
end;
procedure TComPortSettingsDlg.Set_Parity(Value: Byte);
begin
case Value of
ODDPARITY : cbParity.ItemIndex := 1;
EVENPARITY : cbParity.ItemIndex := 2;
MARKPARITY : cbParity.ItemIndex := 3;
SPACEPARITY : cbParity.ItemIndex := 4;
else
cbParity.ItemIndex := 0; // NOPARITY
end;
end;
procedure TComPortSettingsDlg.FormCreate(Sender: TObject);
begin
EnumSerialPorts(cbPort.Items);
Set_Baud (19200);
Set_Databits(8);
set_StopBits(ONESTOPBIT);
Set_Parity (NOPARITY);
end;
function TComPortSettingsDlg.GetDatabits: Integer;
begin
result := StrToIntDef( cbDatabits.Text, 8);
end;
procedure TComPortSettingsDlg.Set_DataBits(const Value: Integer);
var i : integer;
begin
i := cbDatabits.Items.IndexOf(IntToStr(Value));
if i >= 0 then
cbDatabits.ItemIndex := i;
end;
procedure TComPortSettingsDlg.Set_Port(const Value: String);
begin
Label_Port.Caption := Value;
FPortName := Value;
cbPort.OnChange := nil;
cbPort.ItemIndex := cbPort.Items.IndexOf(FPortName);
cbPort.OnChange := DoChangePort;
end;
function TComPortSettingsDlg.GetPort: String;
begin
result := FPortName;
end;
function TComPortSettingsDlg.GetStopbits: Integer;
begin
case cbStopbits.ItemIndex of
1 : result := ONE5STOPBITS;
2 : result := TWOSTOPBITS;
else
result := ONESTOPBIT;
end;
end;
procedure TComPortSettingsDlg.Set_StopBits(Value: Integer);
begin
case Value of
ONE5STOPBITS : cbStopbits.ItemIndex := 1;
TWOSTOPBITS : cbStopbits.ItemIndex := 2;
else
cbStopbits.ItemIndex := 0
end;
end;
procedure TComPortSettingsDlg.DoChangePort(Sender: TObject);
begin
Set_Port(cbPort.Text);
end;
function TComPortSettingsDlg.GetHandshake: DWORD;
begin
case cbHandshake.ItemIndex of
1: result := COMPORTHANDSHAKE_XONXOFF;
2: result := COMPORTHANDSHAKE_RTSCTS;
3: result := COMPORTHANDSHAKE_DTRDSR;
else
result := COMPORTHANDSHAKE_NONE;
end;
end;
procedure TComPortSettingsDlg.Set_Handshake(const Value: DWORD);
begin
case Value of
COMPORTHANDSHAKE_XONXOFF : cbHandshake.ItemIndex := 1;
COMPORTHANDSHAKE_RTSCTS : cbHandshake.ItemIndex := 2;
COMPORTHANDSHAKE_DTRDSR : cbHandshake.ItemIndex := 3;
else
cbHandshake.ItemIndex := 0;
end;
end;
end.
|
unit ufrmDialogIGRADesc;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterDialog, ufraFooterDialog2Button, ExtCtrls,
StdCtrls, uRetnoUnit, System.Actions, Vcl.ActnList, ufraFooterDialog3Button;
type
TFormMode = (fmAdd, fmEdit);
TfrmDialogIGRADesc = class(TfrmMasterDialog)
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure footerDialogMasterbtnSaveClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
FIsProcessSuccessfull: Boolean;
FIGRADescId: Integer;
FFormMode: TFormMode;
{ Private declarations }
function SaveIGRADesc: Boolean;
function UpdateIGRADesc: Boolean;
procedure SetFormMode(const Value: TFormMode);
procedure SetIsProcessSuccessfull(const Value: Boolean);
procedure SetIGRADescId(const Value: Integer);
procedure showDataEdit(code,descrp: string);
procedure prepareAddData;
public
code,descrp: string;
{ Public declarations }
published
property FormMode: TFormMode read FFormMode write SetFormMode;
property IGRADescId: Integer read FIGRADescId write SetIGRADescId;
property IsProcessSuccessfull: Boolean read FIsProcessSuccessfull write SetIsProcessSuccessfull;
end;
var
frmDialogIGRADesc: TfrmDialogIGRADesc;
implementation
uses uIGRADesc, uTSCommonDlg, uConn;
{$R *.dfm}
procedure TfrmDialogIGRADesc.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TfrmDialogIGRADesc.FormDestroy(Sender: TObject);
begin
inherited;
frmDialogIGRADesc := nil;
end;
procedure TfrmDialogIGRADesc.footerDialogMasterbtnSaveClick(Sender: TObject);
begin
if (FormMode = fmAdd) then
begin
FIsProcessSuccessfull := SaveIGRADesc;
if FIsProcessSuccessfull then
Close;
end
else
begin
FIsProcessSuccessfull := UpdateIGRADesc;
if FIsProcessSuccessfull then
Close;
end;
end;
procedure TfrmDialogIGRADesc.SetFormMode(const Value: TFormMode);
begin
FFormMode := Value;
end;
procedure TfrmDialogIGRADesc.SetIsProcessSuccessfull(const Value: boolean);
begin
FIsProcessSuccessfull := Value;
end;
procedure TfrmDialogIGRADesc.SetIGRADescId(const Value: integer);
begin
FIGRADescId := Value;
end;
procedure TfrmDialogIGRADesc.FormShow(Sender: TObject);
begin
inherited;
if (FFormMode = fmEdit) then
showDataEdit(code,descrp)
else
prepareAddData();
end;
procedure TfrmDialogIGRADesc.showDataEdit(code,descrp: string);
begin
edtCode.Text := code;
edtDescrp.Text := descrp;
end;
procedure TfrmDialogIGRADesc.prepareAddData;
begin
edtCode.Clear;
edtDescrp.Clear;
end;
function TfrmDialogIGRADesc.SaveIGRADesc: Boolean;
var fid : Integer;
begin
Result := False;
if edtCode.Text='' then
begin
CommonDlg.ShowErrorEmpty('CODE');
edtCode.SetFocus;
Exit;
end;
if edtDescrp.Text='' then
begin
CommonDlg.ShowErrorEmpty('DESCRIPTIONS');
edtDescrp.SetFocus;
Exit;
end;
if not assigned(IGRADesc) then
IGRADesc := TIGRADesc.Create;
if IGRADesc.IsCodeExist(edtCode.Text,DialogUnit) then
begin
CommonDlg.ShowErrorExist('CODE',edtCode.Text);
edtCode.SetFocus;
FreeAndNil(IGRADesc);
Exit;
end;
fid := cGetNextID('GEN_IGRA_KETERANGAN_ID');
Result:= IGRADesc.InsertIGRADesc(fid,DialogUnit,edtCode.Text,edtDescrp.Text,FLoginId);
end;
function TfrmDialogIGRADesc.UpdateIGRADesc: Boolean;
begin
Result := false;
if edtCode.Text='' then
begin
CommonDlg.ShowErrorEmpty('CODE');
edtCode.SetFocus;
Exit;
end;
if edtDescrp.Text='' then
begin
CommonDlg.ShowErrorEmpty('DESCRIPTIONS');
edtDescrp.SetFocus;
Exit;
end;
if not assigned(IGRADesc) then
IGRADesc := TIGRADesc.Create;
if IGRADesc.IsCodeExist(edtCode.Text,DialogUnit,IGRADescId) then
begin
CommonDlg.ShowErrorExist('CODE',edtCode.Text);
edtCode.SetFocus;
FreeAndNil(IGRADesc);
Exit;
end;
Result:=IGRADesc.UpdateIGRADesc(DialogUnit,edtCode.Text,edtDescrp.Text,FLoginId,IGRADescId);
end;
end.
|
unit EanDBQr;
interface
{$I ean.inc}
{$ifndef PSOFT_CLX}
uses EanKod,EanQr,DB,DBTables,DBCtrls,Messages,Controls,Classes;
type
TQrDBEan = Class(TQrEan)
private
FDataLink: TFieldDataLink;
function GetDataField: string;
function GetDataSource: TDataSource;
function GetField: TField;
function GetFieldText: string;
procedure SetDataField(const Value: string);
procedure SetDataSource(Value: TDataSource);
procedure CMGetDataLink(var Message: TMessage); message CM_GETDATALINK;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure DataChange(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Loaded; override;
property Field: TField read GetField;
published
property DataField: string read GetDataField write SetDataField;
property DataSource: TDataSource read GetDataSource write SetDataSource;
end;
{$endif}
implementation
{$ifndef PSOFT_CLX}
constructor TQrDBEan.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle + [csReplicatable];
FDataLink := TFieldDataLink.Create;
FDataLink.Control := TWinControl(Self);
FDataLink.OnDataChange := DataChange;
end;
destructor TQrDBEan.Destroy;
begin
FDataLink.Free;
FDataLink := nil;
inherited Destroy;
end;
procedure TQrDBEan.Loaded;
begin
inherited Loaded;
if (csDesigning in ComponentState) then DataChange(Self);
end;
procedure TQrDBEan.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (FDataLink <> nil) and
(AComponent = DataSource) then DataSource := nil;
end;
function TQrDBEan.GetDataSource: TDataSource;
begin
Result := FDataLink.DataSource;
end;
procedure TQrDBEan.SetDataSource(Value: TDataSource);
begin
FDataLink.DataSource := Value;
if Value <> nil then Value.FreeNotification(Self);
end;
function TQrDBEan.GetDataField: string;
begin
Result := FDataLink.FieldName;
end;
procedure TQrDBEan.SetDataField(const Value: string);
begin
FDataLink.FieldName := Value;
end;
function TQrDBEan.GetField: TField;
begin
Result := FDataLink.Field;
end;
function TQrDBEan.GetFieldText: string;
begin
if FDataLink.Field <> nil then
Result := FDataLink.Field.DisplayText
else
if csDesigning in ComponentState then Result := Name else Result := '';
end;
procedure TQrDBEan.DataChange(Sender: TObject);
begin
FEan.BarCode:= GetFieldText;
end;
procedure TQrDBEan.CMGetDataLink(var Message: TMessage);
begin
Message.Result := Integer(FDataLink);
end;
{$endif}
end.
|
(* parsing functions generated from file 'EBNF.syn' *)
FUNCTION SyIsNot(expectedSy: Symbol): BOOLEAN;
BEGIN
success:= success AND (sy = expectedSy);
SyIsNot := NOT success;
END; (*SyIsNot*)
PROCEDURE Grammar;
BEGIN
Rule; IF NOT success THEN Exit;
WHILE sy = ... DO BEGIN
Rule; IF NOT success THEN Exit;
END; (*WHILE*)
END; (*Grammar*)
PROCEDURE Rule;
BEGIN
IF SyIsNot(identSy) THEN Exit;
NewSy;
IF SyIsNot(equalSy) THEN Exit;
NewSy;
Expr; IF NOT success THEN Exit;
END; (*Rule*)
PROCEDURE Expr;
BEGIN
IF sy = ... THEN BEGIN
Term; IF NOT success THEN Exit;
END (*IF*)
ELSE IF sy = ... THEN BEGIN
IF SyIsNot(ltSy) THEN Exit;
NewSy;
Term; IF NOT success THEN Exit;
WHILE sy = ... DO BEGIN
IF SyIsNot(barSy) THEN Exit;
NewSy;
Term; IF NOT success THEN Exit;
END; (*WHILE*)
IF SyIsNot(gtSy) THEN Exit;
NewSy;
END (*IF*)
ELSE
success := FALSE;
END; (*Expr*)
PROCEDURE Term;
BEGIN
Fact; IF NOT success THEN Exit;
WHILE sy = ... DO BEGIN
Fact; IF NOT success THEN Exit;
END; (*WHILE*)
END; (*Term*)
PROCEDURE Fact;
BEGIN
IF sy = ... THEN BEGIN
IF SyIsNot(identSy) THEN Exit;
NewSy;
END (*IF*)
ELSE IF sy = ... THEN BEGIN
IF SyIsNot(leftParSy) THEN Exit;
NewSy;
Expr; IF NOT success THEN Exit;
IF SyIsNot(rightParSy) THEN Exit;
NewSy;
END (*IF*)
ELSE IF sy = ... THEN BEGIN
IF SyIsNot(leftOptSy) THEN Exit;
NewSy;
Expr; IF NOT success THEN Exit;
IF SyIsNot(rightOptSy) THEN Exit;
NewSy;
END (*IF*)
ELSE IF sy = ... THEN BEGIN
IF SyIsNot(leftIterSy) THEN Exit;
NewSy;
Expr; IF NOT success THEN Exit;
IF SyIsNot(rightIterSy) THEN Exit;
NewSy;
END (*IF*)
ELSE
success := FALSE;
END; (*Fact*)
(* generation ended succesfully *)
|
unit ThreadQueue;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
{ TThreadQueue }
TThreadQueue = class(TThreadList)
public
procedure Push(Item: Pointer);
function Front: Pointer;
function Count: Integer;
procedure Pop;
end;
implementation
{ TThreadQueue }
procedure TThreadQueue.Push(Item: Pointer);
var
List: TList;
begin
List := LockList;
try
List.Add(Item);
finally
UnlockList;
end;
end;
function TThreadQueue.Front: Pointer;
var
List: TList;
begin
List := LockList;
try
Result := List.First;
finally
UnlockList;
end;
end;
function TThreadQueue.Count: Integer;
var
List: TList;
begin
List := LockList;
try
Result := List.Count;
finally
UnlockList;
end;
end;
procedure TThreadQueue.Pop;
var
List: TList;
begin
List := LockList;
try
List.Delete(0);
finally
UnlockList;
end;
end;
end.
|
{Part 8 of regression test for SPECFUNX unit (c) 2012 W.Ehrhardt}
unit t_sfx8;
{$i STD.INC}
{$ifdef BIT16}
{$N+}
{$ifndef Windows}
{$O+}
{$endif}
{$endif}
interface
procedure test_zetax;
procedure test_zeta1px;
procedure test_zetaintx;
{$ifndef VER50}
procedure test_zetam1x;
procedure test_etam1x;
procedure test_etax;
procedure test_LerchPhix;
procedure test_DirichletBetax;
procedure test_DirichletLambdax;
procedure test_LegendreChix;
procedure test_polylogx;
procedure test_polylogrx;
procedure test_fermi_diracx;
procedure test_fermi_dirac_halfx;
{$endif}
implementation
uses
amath, specfunx, t_sfx0;
{---------------------------------------------------------------------------}
procedure test_zetax;
var
x,y,f: extended;
cnt, failed: integer;
const
NE = 8;
NE1 = 350; { s < MaxGAMX}
NE2 = 3500; { s < MaxGAMX, |Zeta| > 1e4900}
begin
cnt := 0;
failed := 0;
writeln('Function: ','zetax');
x := 0.0;
y := zetax(x);
f := -0.5;
testrel( 1, NE, y, f, cnt,failed);
x := 0.5;
y := zetax(x);
f := -1.460354508809586813;
testrel( 2, NE, y, f, cnt,failed);
x := 0.9990234375;
y := zetax(x);
f := -1023.422855448942979;
testrel( 3, NE, y, f, cnt,failed);
x := 1.0009765625;
y := zetax(x);
f := 1024.577286769504594;
testrel( 4, NE, y, f, cnt,failed);
x := 1.5;
y := zetax(x);
f := 2.6123753486854883433;
testrel( 5, NE, y, f, cnt,failed);
x := 1.9990234375;
y := zetax(x);
f := 1.645850590810321192;
testrel( 6, NE, y, f, cnt,failed);
x := 2.0009765625;
y := zetax(x);
f := 1.644019440013418371;
testrel( 7, NE, y, f, cnt,failed);
x := 3.0;
y := zetax(x);
f := 1.202056903159594285;
testrel( 8, NE, y, f, cnt,failed);
x := 3.9990234375;
y := zetax(x);
f := 1.082390560902667758;
testrel( 9, NE, y, f, cnt,failed);
x := 4.0009765625;
y := zetax(x);
f := 1.082255968563913698;
testrel(10, NE, y, f, cnt,failed);
x := 6;
y := zetax(x);
f := power(Pi,6)/945.0;
testrel(11, NE, y, f, cnt,failed);
x := 6.9990234375;
y := zetax(x);
f := 1.008355171623342114;
testrel(12, NE, y, f, cnt,failed);
x := 7.0009765625;
y := zetax(x);
f := 1.008343387409452773;
testrel(13, NE, y, f, cnt,failed);
x := 14;
y := zetax(x);
f := 2.0*power(Pi,14)/18243225.0;
testrel(14, NE, y, f, cnt,failed);
x := 14.9990234375;
y := zetax(x);
f := 1.000030608976823097;
testrel(15, NE, y, f, cnt,failed);
x := 15.0009765625;
y := zetax(x);
f := 1.0000305675098559807;
testrel(16, NE, y, f, cnt,failed);
x := 30.0;
y := zetax(x);
f := 1.0000000009313274324;
testrel(17, NE, y, f, cnt,failed);
x := 41.9990234375;
y := zetax(x);
f := 1.00000000000022752765;
testrel(18, NE, y, f, cnt,failed);
x := 42.0009765625;
y := zetax(x);
f := 1.00000000000022721983;
testrel(19, NE, y, f, cnt,failed);
x := 60.0;
y := zetax(x);
f := 1.00000000000000000087;
testrel(20, NE, y, f, cnt,failed);
x := 64.0;
y := zetax(x);
f := 1.0;
testrel(21, NE, y, f, cnt,failed);
x := -1.0;
y := zetax(x);
f := -1.0/12.0;
testrel(22, NE, y, f, cnt,failed);
x := -1.5;
y := zetax(x);
f := -0.2548520188983303595e-1;
testrel(23, NE, y, f, cnt,failed);
x := -2.0;
y := zetax(x);
f := 0.0;
testrel(24, NE, y, f, cnt,failed);
x := -2.0009765625;
y := zetax(x);
f := 0.29703475770457122976e-4;
testrel(25, NE, y, f, cnt,failed);
x := -3.0;
y := zetax(x);
f := 1.0/120.0;
testrel(26, NE, y, f, cnt,failed);
x := -55.5;
y := zetax(x);
f := 0.10719086258305834165e30;
testrel(27, NE, y, f, cnt,failed);
y := zetax(1.5e-10);
f := -0.5000000001378407800;
testrel(28, NE, y, f, cnt,failed);
y := zetax(-1e-10);
f := -0.4999999999081061467;
testrel(29, NE, y, f, cnt,failed);
y := zetax(-1757.5);
f := -0.1598717401109931383e3539;
testrel(30, NE1, y, f, cnt,failed);
y := zetax(-2302.5);
f := 0.1333575536670891486e4906;
testrel(31, NE2, y, f, cnt,failed);
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{---------------------------------------------------------------------------}
procedure test_zeta1px;
var
x,y,f: extended;
cnt, failed: integer;
const
NE = 6;
begin
cnt := 0;
failed := 0;
writeln('Function: ','zeta1px');
x := 1.0;
y := zeta1px(x);
f := 1.64493406684822643647;
testrel( 1, NE, y, f, cnt,failed);
x := -0.9990234375;
y := zeta1px(x);
f := -0.500898358549607584099;
testrel( 2, NE, y, f, cnt,failed);
x := -1e-5;
y := zeta1px(x);
f := -99999.4227850632574065;
testrel( 3, NE, y, f, cnt,failed);
x := +1e-5;
y := zeta1px(x);
f := 100000.577216393059503;
testrel( 4, NE, y, f, cnt,failed);
x := -1e-10;
y := zeta1px(x);
f := -9999999999.42278433511;
testrel( 5, NE, y, f, cnt,failed);
x := +1e-10;
y := zeta1px(x);
f := 10000000000.5772156649;
testrel( 6, NE, y, f, cnt,failed);
x := -1e-18;
y := zeta1px(x);
f := -999999999999999999.423;
testrel( 7, NE, y, f, cnt,failed);
x := +1e-18;
y := zeta1px(x);
f := 1000000000000000000.58;
testrel( 8, NE, y, f, cnt,failed);
x := +1e-25;
y := zeta1px(x);
f := 1/x;
testrel( 9, NE, y, f, cnt,failed);
x := -1e-25;
y := zeta1px(x);
f := 1/x;
testrel(10, NE, y, f, cnt,failed);
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{---------------------------------------------------------------------------}
procedure test_zetaintx;
var
x,y,f: extended;
i: integer;
begin
{Because zeta now uses zetaint test with zeta(succ(i)) and a suitable tolerance}
writeln('Function: ','zetaintx');
for i:=-2300 to 100 do if i<>1 then begin
if i<-MAXGAMX then x := abs(i*eps_x*12)
else if i<0 then x := abs(i*eps_x*8)
else x := 8*eps_x;
y := zetaintx(i);
if (i<0) and (i and 1 = 0) then f := 0.0
else f := zetax(succx(i));
if IsInf(y) and IsInf(f) then begin
if f<>y then begin
writeln('*** failed first for ',i);
inc(total_failed);
exit;
end;
end
else if abs(y-f) > x*abs(f) then begin
writeln('*** failed first for ',i);
inc(total_failed);
exit;
end;
end;
writeln(' Test OK');
end;
{$ifndef ver50}
{---------------------------------------------------------------------------}
procedure test_zetam1x;
var
x,y,f: extended;
cnt, failed: integer;
const
NE = 8;
begin
cnt := 0;
failed := 0;
writeln('Function: ','zetam1x');
x := 0.0;
y := zetam1x(x);
f := -1.5;
testrel( 1, NE, y, f, cnt,failed);
x := 0.5;
y := zetam1x(x);
f := -2.4603545088095868129;
testrel( 2, NE, y, f, cnt,failed);
x := 0.9990234375;
y := zetam1x(x);
f := -1024.4228554489429787;
testrel( 3, NE, y, f, cnt,failed);
x := 1.0009765625;
y := zetam1x(x);
f := 1023.57728676950459406;
testrel( 4, NE, y, f, cnt,failed);
x := 1.5;
y := zetam1x(x);
f := 1.61237534868548834335;
testrel( 5, NE, y, f, cnt,failed);
x := 1.9990234375;
y := zetam1x(x);
f := 0.64585059081032119165;
testrel( 6, NE, y, f, cnt,failed);
x := 2.0009765625;
y := zetam1x(x);
f := 0.64401944001341837056;
testrel( 7, NE, y, f, cnt,failed);
x := 3.0;
y := zetam1x(x);
f := 0.20205690315959428540;
testrel( 8, NE, y, f, cnt,failed);
x := 6.0;
y := zetam1x(x);
f := 0.17343061984449139715e-1;
testrel( 9, NE, y, f, cnt,failed);
x := 20;
y := zetam1x(x);
f := 0.95396203387279611315e-6;
testrel(10, NE, y, f, cnt,failed);
x := 40.0;
y := zetam1x(x);
f := 0.90949478402638892825e-12;
testrel(11, NE, y, f, cnt,failed);
x := 64.0;
y := zetam1x(x);
f := 0.54210108624566454109e-19;
testrel(12, NE, y, f, cnt,failed);
x := 100.0;
y := zetam1x(x);
f := 0.7888609052210118074e-30;
testrel(13, NE, y, f, cnt,failed);
x := 1000.0;
y := zetam1x(x);
f := 9.33263618503218879e-302;
testrel(14, NE, y, f, cnt,failed);
x := 12500.0;
y := zetam1x(x);
f := 0.1333687866894593844e-3762;
testrel(15, NE, y, f, cnt,failed);
x := -1.0;
y := zetam1x(x);
f := -1.083333333333333333;
testrel(16, NE, y, f, cnt,failed);
x := -1.5;
y := zetam1x(x);
f := -1.025485201889833036;
testrel(17, NE, y, f, cnt,failed);
x := -2.0;
y := zetam1x(x);
f := -1.0;
testrel(18, NE, y, f, cnt,failed);
x := -2.0009765625;
y := zetam1x(x);
f := -0.999970296524229543;
testrel(19, NE, y, f, cnt,failed);
x := -19.25;
y := zetam1x(x);
f := 31.49461534567477545;
testrel(20, NE, y, f, cnt,failed);
x := -55.5;
y := zetam1x(x);
f := 0.10719086258305834166e30;
testrel(21, NE, y, f, cnt,failed);
x := 25000.0;
y := zetam1x(x);
f := 0;
testrel(22, NE, y, f, cnt,failed);
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{---------------------------------------------------------------------------}
procedure test_etam1x;
var
x,y,f: extended;
cnt, failed: integer;
const
NE = 8;
begin
cnt := 0;
failed := 0;
writeln('Function: ','etam1x');
{etam1 := x -> Zeta(x)*(1-2^(1-x)) - 1.0;}
x := 0.0;
y := etam1x(x);
f := -0.5;
testrel( 1, NE, y, f, cnt,failed);
x := 0.5;
y := etam1x(x);
f := -0.3951013565783696298;
testrel( 2, NE, y, f, cnt,failed);
x := 0.9990234375;
y := etam1x(x);
f := -0.3070089725899074737;
testrel( 3, NE, y, f, cnt,failed);
x := 1.0009765625;
y := etam1x(x);
f := -0.3066967286343630638;
testrel( 4, NE, y, f, cnt,failed);
x := 1.5;
y := etam1x(x);
f := -0.2348529753745920546;
testrel( 5, NE, y, f, cnt,failed);
x := 1.9990234375;
y := etam1x(x);
f := -0.1776319325704589369;
testrel( 6, NE, y, f, cnt,failed);
x := 2.0009765625;
y := etam1x(x);
f := -0.1774340486232085190;
testrel( 7, NE, y, f, cnt,failed);
x := 3.0;
y := etam1x(x);
f := -0.9845732263030428595e-1;
testrel( 8, NE, y, f, cnt,failed);
x := 6.0;
y := etam1x(x);
f := -0.1444890870256489590e-1;
testrel( 9, NE, y, f, cnt,failed);
x := 20;
y := etam1x(x);
f := -0.9533884184778849492e-6;
testrel(10, NE, y, f, cnt,failed);
x := 40.0;
y := etam1x(x);
f := -0.9094946195211219090e-12;
testrel(11, NE, y, f, cnt,failed);
x := 64.0;
y := etam1x(x);
f := -0.5421010862398398930e-19;
testrel(12, NE, y, f, cnt,failed);
x := 100.0;
y := etam1x(x);
f := -0.7888609052210118035e-30;
testrel(13, NE, y, f, cnt,failed);
x := 1000.0;
y := etam1x(x);
f := -9.33263618503218879e-302;
testrel(14, NE, y, f, cnt,failed);
x := 12500.0;
y := etam1x(x);
f := -0.1333687866894593844e-3762;
testrel(15, NE, y, f, cnt,failed);
x := -1.0;
y := etam1x(x);
f := -0.75;
testrel(16, NE, y, f, cnt,failed);
x := -1.5;
y := etam1x(x);
f := -0.8813191292801597880;
testrel(17, NE, y, f, cnt,failed);
x := -2.0;
y := etam1x(x);
f := -1.0;
testrel(18, NE, y, f, cnt,failed);
x := -2.0009765625;
y := etam1x(x);
f := -1.0002080852354742793;
testrel(19, NE, y, f, cnt,failed);
x := -19.25;
y := etam1x(x);
f := -40519910.275413219422;
testrel(20, NE, y, f, cnt,failed);
x := -55.5;
y := etam1x(x);
f := -0.10923266281825727645e47;
testrel(21, NE, y, f, cnt,failed);
x := 25000.0;
y := etam1x(x);
f := 0;
testrel(22, NE, y, f, cnt,failed);
x := -1e-9;
y := etam1x(x);
f := -0.5000000002257913527;
testrel(23, NE, y, f, cnt,failed);
x := 1e-10;
y := etam1x(x);
f := -0.4999999999774208647;
testrel(24, NE, y, f, cnt,failed);
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{---------------------------------------------------------------------------}
procedure test_etax;
var
x,y,f: extended;
cnt, failed: integer;
const
NE = 8;
begin
cnt := 0;
failed := 0;
writeln('Function: ','etax');
{eta := x -> Zeta(x)*(1-2^(1-x));}
x := 0.0;
y := etax(x);
f := 0.5;
testrel( 1, NE, y, f, cnt,failed);
x := 0.5;
y := etax(x);
f := 0.6048986434216303702;
testrel( 2, NE, y, f, cnt,failed);
x := 1.0;
y := etax(x);
f := ln(2);
testrel( 3, NE, y, f, cnt,failed);
x := 1.5;
y := etax(x);
f := 0.7651470246254079454;
testrel( 4, NE, y, f, cnt,failed);
x := 2.0;
y := etax(x);
f := 0.8224670334241132182;
testrel( 5, NE, y, f, cnt,failed);
x := 5.0;
y := etax(x);
f := 0.9721197704469093060;
testrel( 6, NE, y, f, cnt,failed);
x := 10.0;
y := etax(x);
f := 0.9990395075982715656;
testrel( 7, NE, y, f, cnt,failed);
x := 20;
y := etax(x);
f := 0.9999990466115815221;
testrel( 8, NE, y, f, cnt,failed);
x := 40.0;
y := etax(x);
f := 0.9999999999990905054;
testrel( 9, NE, y, f, cnt,failed);
x := 64.0;
y := etax(x);
f := 1.0;
testrel(10, NE, y, f, cnt,failed);
x := -0.5;
y := etax(x);
f := 0.3801048126096840168;
testrel(11, NE, y, f, cnt,failed);
x := -1.0;
y := etax(x);
f := 0.25;
testrel(12, NE, y, f, cnt,failed);
x := -1.5;
y := etax(x);
f := 0.1186808707198402120;
testrel(13, NE, y, f, cnt,failed);
x := -2.0;
y := etax(x);
f := 0;
testrel(14, NE, y, f, cnt,failed);
x := -7.5;
y := etax(x);
f := -1.180249705900827553;
testrel(15, NE, y, f, cnt,failed);
x := -19.25;
y := etax(x);
f := -40519909.27541321942;
testrel(16, NE, y, f, cnt,failed);
x := -55.5;
y := etax(x);
f := -0.10923266281825727645e47;
testrel(17, NE, y, f, cnt,failed);
x := -1e-9;
y := etax(x);
f := 0.4999999997742086473;
testrel(18, NE, y, f, cnt,failed);
x := 1e-10;
y := etax(x);
f := 0.5000000000225791353;
testrel(19, NE, y, f, cnt,failed);
x := 1+1e-6;
y := etax(x);
f := 0.6931473404288163656;
testrel(20, NE, y, f, cnt,failed);
x := 1-1e-6;
y := etax(x);
f := 0.6931470206910088807;
testrel(21, NE, y, f, cnt,failed);
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{---------------------------------------------------------------------------}
procedure test_LerchPhix;
var
y,f,z,s,a: extended;
cnt, failed: integer;
const
NE = 6;
{$ifdef BIT16}
NE2 = 10;
{$else}
NE2 = 25; {???}
{$endif}
begin
cnt := 0;
failed := 0;
writeln('Function: ','LerchPhix');
z := -1;
y := LerchPhix(z, 2, 3);
f := 0.7246703342411321824e-1;
testrel( 1, NE, y, f, cnt,failed);
y := LerchPhix(z, 100, 3);
f := 1.940325217482010536e-48;
testrel( 2, NE, y, f, cnt,failed);
y := LerchPhix(z, 0.125, 5);
f := 0.4139549024672754777;
testrel( 3, NE, y, f, cnt,failed);
y := LerchPhix(z, 16, 0.5);
f := 65535.99847798871839;
testrel( 4, NE, y, f, cnt,failed);
y := LerchPhix(z, 2, 0.5);
f := 3.663862376708876060;
testrel( 5, NE, y, f, cnt,failed);
y := LerchPhix(0.5, 16, 1e-19);
f := 1e304;
testrel( 6, NE, y, f, cnt,failed);
y := LerchPhix(0.5, 2, 3);
f := 0.1579242117201000472;
testrel( 7, NE, y, f, cnt,failed);
z := -1+ldexp(1,-52);
y := LerchPhix(z, 1+1/128, 1e10);
f := 4.176812734999603534e-11;
testrel( 8, NE, y, f, cnt,failed);
z := 1-ldexp(1,-52);
y := LerchPhix(z, 1+1/128, 1e10);
f := 9.89847701124157791;
testrel( 9, NE, y, f, cnt,failed);
y := LerchPhix(0.75, 1+1/128, 200);
f := 0.1890864747918034799e-1;
testrel(10, NE, y, f, cnt,failed);
y := LerchPhix(-0.75, 1+1/128, 200);
f := 0.2747206889737371425e-2;
testrel(11, NE, y, f, cnt,failed);
y := LerchPhix(-0.75, 1+1/128, 30);
f := 0.1881378370869183099e-1;
testrel(12, NE, y, f, cnt,failed);
z := 1-1/16;
y := LerchPhix(z, 2, 10000);
f := 1.595222182725875097e-7;
testrel(13, NE, y, f, cnt,failed);
y := LerchPhix(z, 2, 1000);
f := 0.1554103481247648889e-4;
testrel(14, NE, y, f, cnt,failed);
y := LerchPhix(0.3,0.1,100);
f := 0.9009852125614140412;
testrel(14, NE, y, f, cnt,failed);
y := LerchPhix(-0.3,0.1,100);
f := 0.4854634757432184874;
testrel(15, NE, y, f, cnt,failed);
y := LerchPhix(-0.3,100,100);
f := 0.9002485412225464125e-200;
testrel(16, NE, y, f, cnt,failed);
y := LerchPhix(0.75,3,1e-10);
f := 1e30;
testrel(18, NE, y, f, cnt,failed);
y := LerchPhix(0.75,3,1e-4);
f := 0.1000000000000844188e13;
testrel(19, NE, y, f, cnt,failed);
z := -0.96875;
s := 16;
y := LerchPhix(z,s,0.25);
f := 4.294967295972734281e9;
testrel(20, NE, y, f, cnt,failed);
z := -0.96875;
y := LerchPhix(z,s,1/64);
f := 7.922816251426433759e28;
testrel(21, NE, y, f, cnt,failed);
z := -0.96875;
y := LerchPhix(z,s,1);
f := 0.9999852396432582781;
testrel(22, NE, y, f, cnt,failed);
z := -0.96875;
s := 4;
y := LerchPhix(z,s,0.25);
f := 255.6336018166029893;
testrel(23, NE, y, f, cnt,failed);
y := LerchPhix(z,s,0.015625);
f := 0.1677721513782503849e8;
testrel(24, NE, y, f, cnt,failed);
y := LerchPhix(z,s,0.75);
f := 3.070223141356004934;
testrel(25, NE, y, f, cnt,failed);
z := 0.96875;
s := 16;
y := LerchPhix(z, s, 1/16);
f := 1.844674407370955162e19;
testrel(26, NE, y, f, cnt,failed);
y := LerchPhix(z, s, 1/8);
f := 2.814749767106561472e14;
testrel(27, NE, y, f, cnt,failed);
y := LerchPhix(z, s, 2);
f := 0.1528151848585480626e-4;
testrel(28, NE, y, f, cnt,failed);
y := LerchPhix(z, s, 20);
f := 2.813806862758912383e-21;
testrel(29, NE, y, f, cnt,failed);
y := LerchPhix(z, s, 1);
f := 1.000014803971033172;
testrel(30, NE, y, f, cnt,failed);
y := LerchPhix(z, s, 0.5);
f := 65536.00147526752452;
testrel(31, NE, y, f, cnt,failed);
y := LerchPhix(z, 2, 1e100);
f := 32e-200;
testrel(32, NE, y, f, cnt,failed);
y := LerchPhix(z, 2, 1000);
f := 0.3018300795020214889e-4;
testrel(33, NE, y, f, cnt,failed);
y := LerchPhix(z, 8, 1/1024);
f := 1.208925819614629175e24;
testrel(34, NE, y, f, cnt,failed);
y := LerchPhix(z, 32, 1/128);
f := 2.695994666715063979e67;
testrel(35, NE, y, f, cnt,failed);
y := LerchPhix(z, 32, 1/64);
f := 6.277101735386680764e57;
testrel(36, NE, y, f, cnt,failed);
y := LerchPhix(z, 32, 1);
f := 1.000000000225555193;
testrel(37, NE, y, f, cnt,failed);
y := LerchPhix(z, 32, 2);
f := 2.328311664999511981e-10;
testrel(38, NE, y, f, cnt,failed);
{Test cases from Aksenov/Jentschura}
{Run 5}
z := 0.99999;
s := 2;
a := 1;
y := LerchPhix(z, s, a);
f := 1.644825385246778980;
testrel(39, NE, y, f, cnt,failed);
{Run 6}
z := -0.99999;
s := 2;
a := 1;
y := LerchPhix(z, s, a);
f := 8.224683266259164962E-1;
testrel(40, NE, y, f, cnt,failed);
{Run 9}
z := 1e-5;
s := 2;
a := 1;
y := LerchPhix(z, s, a);
f := 1.000002500011111174;
testrel(41, NE, y, f, cnt,failed);
{Run 10}
z := -6.3E-5;
s := 2;
a := 1;
y := LerchPhix(z, s, a);
f := 0.999984250440984373;
testrel(42, NE, y, f, cnt,failed);
{Run 11}
z := 3.4709929976435479E-6;
s := 1;
a := 1.5172413793103448;
y := LerchPhix(z, s, a);
f := 0.6590922879819636657;
testrel(43, NE, y, f, cnt,failed);
{More z=-1 cases}
y := LerchPhix(-1, 16, 10);
f := 0.82489438389165980294e-16;
testrel(44, NE, y, f, cnt,failed);
y := LerchPhix(-1, 2, 1e-10);
f := 1e20;
testrel(45, NE, y, f, cnt,failed);
y := LerchPhix(-1, 1+1/128, 1e-10);
f := 0.1197085030426290549e11;
testrel(46, NE, y, f, cnt,failed);
f := 0.5000000004e-160;
y := LerchPhix(-1, 16, 1e10);
testrel(47, NE, y, f, cnt,failed);
y := LerchPhix(-1, 16, 1);
f := 0.9999847642149061064;
testrel(48, NE, y, f, cnt,failed);
y := LerchPhix(-1, 16, 1e-10);
f := 1e160;
testrel(49, NE, y, f, cnt,failed);
y := LerchPhix(-1,0.125,1e24);
f := 0.5e-3;
testrel(50, NE, y, f, cnt,failed);
{extended only}
z := 1-ldexp(1,-60);
y := LerchPhix(z, 2, 10000);
f := 0.1000050001666390831e-3;
testrel(51, NE, y, f, cnt,failed);
z := -1+ldexp(1,-63);
y := LerchPhix(z, 1+1/128, 5e14);
f := 7.676518428535961828e-16;
testrel(52, NE, y, f, cnt,failed);
z := 1-ldexp(1,-63);
y := LerchPhix(z, 1+1/128, 5e20);
f := 0.1248383340162846057e-1;
testrel(53, NE, y, f, cnt,failed);
y := LerchPhix(0.75,1350,4400);
f := 0.4869860564540355629e-4918;
testrel(54, NE, y, f, cnt,failed);
y := LerchPhix(0.75,1200,10000);
f := 0.2986948567427072304e-4799;
testrel(55, NE, y, f, cnt,failed);
y := LerchPhix(0.96875, 1000, 20000);
f := 1.189350965834466343e-4300;
testrel(56, NE, y, f, cnt,failed);
y := LerchPhix(-0.3,2400,100);
f := 0.9999999999872407785e-4800;
testrel(57, NE, y, f, cnt,failed);
y := LerchPhix(-1, 16, 1e-300);
f := 1e4800;
testrel(58, NE2, y, f, cnt,failed);
y := LerchPhix(-1, 16, 1e300);
f := 0.5e-4800;
testrel(59, NE2, y, f, cnt,failed);
{Tests for s<0}
y := LerchPhix(-0.9921875, -0.9375, 5);
f := 2.057733305230137650;
testrel(60, NE, y, f, cnt,failed);
y := LerchPhix(-0.9921875, -0.5, 5);
f := 1.066663573920271744;
testrel(61, NE, y, f, cnt,failed);
y := LerchPhix(-0.9921875, -0.125, 5);
f := 0.6062199942770585427;
testrel(62, NE, y, f, cnt,failed);
y := LerchPhix(-0.25, -0.9375, 7.5);
f := 5.158129174261488297;
testrel(63, NE, y, f, cnt,failed);
y := LerchPhix(-0.25, -0.5, 7.5);
f := 2.162257387021207087;
testrel(64, NE, y, f, cnt,failed);
y := LerchPhix(-0.25, -0.125, 7.5);
f := 1.025823888398309961;
testrel(65, NE, y, f, cnt,failed);
y := LerchPhix(0.375, -0.9375, 2.5);
f := 4.609912789035665679;
testrel(66, NE, y, f, cnt,failed);
y := LerchPhix(0.375, -0.5, 2.5);
f := 2.788814534753693403;
testrel(67, NE, y, f, cnt,failed);
y := LerchPhix(0.375, -0.125, 2.5);
f := 1.835284527035582744;
testrel(68, NE, y, f, cnt,failed);
y := LerchPhix(0.75, -0.9375, 12.5);
f := 52.17092092836499335;
testrel(69, NE, y, f, cnt,failed);
y := LerchPhix(0.75, -0.5, 12.5);
f := 15.66354877711018779;
testrel(70, NE, y, f, cnt,failed);
y := LerchPhix(0.75, -0.125, 12.5);
f := 5.621603260975934263;
testrel(71, NE, y, f, cnt,failed);
y := LerchPhix(-0.875, -0.125, 1000);
f := 1.264658869110458885;
testrel(72, NE, y, f, cnt,failed);
y := LerchPhix(0.875, -0.125, 1000);
f := 18.98748182387054361;
testrel(73, NE, y, f, cnt,failed);
y := LerchPhix(-0.375, -0.125, 2000);
f := 1.880696209365743222;
testrel(74, NE, y, f, cnt,failed);
y := LerchPhix(0.375, -0.125, 2000);
f := 4.137757266383553387;
testrel(75, NE, y, f, cnt,failed);
y := LerchPhix(0.375, -0.125, 1e6);
f := 8.997461877854526012;
testrel(76, NE, y, f, cnt,failed);
y := LerchPhix(-0.75, -0.125, 1e6);
f := 3.213378828942416160;
testrel(77, NE, y, f, cnt,failed);
y := LerchPhix(-0.75, -1, 5);
f := 2.612244897959183673;
testrel(78, NE, y, f, cnt,failed);
y := LerchPhix(0.375, -1, 5);
f := 8.96;
testrel(79, NE, y, f, cnt,failed);
{z=1, no special case}
y := LerchPhix(1,0.75,1.5);
f := -4.028036535056665957;
testrel(80, NE, y, f, cnt,failed);
y := LerchPhix(1,-0.75,1.5);
f := -0.5404252521791210354;
testrel(81, NE, y, f, cnt,failed);
{z=0}
y := LerchPhix(0,0.75,1.5);
f := 0.7377879464668810616;
testrel(82, NE, y, f, cnt,failed);
y := LerchPhix(0,-0.75, 0.5);
f := 0.5946035575013605334;
testrel(83, NE, y, f, cnt,failed);
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{---------------------------------------------------------------------------}
procedure test_DirichletBetax;
var
y,f: extended;
cnt, failed: integer;
const
NE = 6;
NE2 = 20;
NE3 = 300;
begin
cnt := 0;
failed := 0;
writeln('Function: ','DirichletBetax');
y := DirichletBetax(40.5);
f := 1.0;
testrel( 1, NE, y, f, cnt,failed);
y := DirichletBetax(32);
f := 0.9999999999999994603;
testrel( 2, NE, y, f, cnt,failed);
y := DirichletBetax(27.6);
f := 0.9999999999999321651;
testrel( 3, NE, y, f, cnt,failed);
y := DirichletBetax(22.8);
f := 0.9999999999867678140;
testrel( 4, NE, y, f, cnt,failed);
y := DirichletBetax(22.0);
f := 0.999999999968134064;
testrel( 5, NE, y, f, cnt,failed);
y := DirichletBetax(10.0);
f := 0.9999831640261968774;
testrel( 6, NE, y, f, cnt,failed);
y := DirichletBetax(5.0);
f := 0.996157828077088064;
testrel( 7, NE, y, f, cnt,failed);
y := DirichletBetax(2.0); {Catalan}
f := 0.9159655941772190151;
testrel( 8, NE, y, f, cnt,failed);
y := DirichletBetax(1.0);
f := Pi/4;
testrel( 9, NE, y, f, cnt,failed);
y := DirichletBetax(0.25);
f := 0.5907230564424947319;
testrel(10, NE, y, f, cnt,failed);
y := DirichletBetax(1/128);
f := 0.5030522278808478693;
testrel(11, NE, y, f, cnt,failed);
y := DirichletBetax(ldexp(1,-30));
f := 0.5000000003647006979;
testrel(12, NE, y, f, cnt,failed);
y := DirichletBetax(1e-10);
f := 0.5000000000391594393;
testrel(13, NE, y, f, cnt,failed);
y := DirichletBetax(ldexp(1,-42));
f := 0.5000000000000890383;
testrel(14, NE, y, f, cnt,failed);
y := DirichletBetax(0);
f := 0.5;
testrel(15, NE, y, f, cnt,failed);
y := DirichletBetax(-1/1024);
f := 0.4996174725733061643;
testrel(16, NE, y, f, cnt,failed);
y := DirichletBetax(-0.75);
f := 0.1425165634878215728;
testrel(17, NE, y, f, cnt,failed);
y := DirichletBetax(-3);
f := 0.0;
testrel(18, NE, y, f, cnt,failed);
y := DirichletBetax(-3.25);
f := 0.4612305190414612658;
testrel(19, NE, y, f, cnt,failed);
y := DirichletBetax(-4);
f := 5/2;
testrel(20, NE, y, f, cnt,failed);
y := DirichletBetax(-9.875);
f := -19551.74572283995210;
testrel(21, NE, y, f, cnt,failed);
y := DirichletBetax(-10.125);
f := -31440.68339647519141;
testrel(22, NE, y, f, cnt,failed);
y := DirichletBetax(-13);
f := 0;
testrel(23, NE, y, f, cnt,failed);
y := DirichletBetax(-13.03125);
f := -586962.5557661498894;
testrel(24, NE, y, f, cnt,failed);
y := DirichletBetax(-100 + 1/16);
f := 1.114115509708245184e138;
testrel(25, NE2, y, f, cnt,failed);
y := DirichletBetax(-100 - 1/16);
f := 1.873640276815095868e138;
testrel(26, NE2, y, f, cnt,failed);
y := DirichletBetax(-1700.5);
f := 0.1752739075344393927e4424;
testrel(27, NE3, y, f, cnt,failed);
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{---------------------------------------------------------------------------}
procedure test_DirichletLambdax;
var
y,f: extended;
cnt, failed: integer;
const
NE = 5;
NE2 = 80;
NE3 = 800;
begin
cnt := 0;
failed := 0;
writeln('Function: ','DirichletLambdax');
y := DirichletLambdax(40);
f := 1.0;
testrel( 1, NE, y, f, cnt,failed);
y := DirichletLambdax(20);
f := 1.000000000286807697;
testrel( 2, NE, y, f, cnt,failed);
y := DirichletLambdax(10);
f := 1.000017041363044825;
testrel( 3, NE, y, f, cnt,failed);
y := DirichletLambdax(2);
f := 1.233700550136169827;
testrel( 4, NE, y, f, cnt,failed);
y := DirichletLambdax(1.125);
f := 4.649432303012021381;
testrel( 5, NE, y, f, cnt,failed);
y := DirichletLambdax(0.96875);
f := -15.36847262070367157;
testrel( 6, NE, y, f, cnt,failed);
y := DirichletLambdax(0.5);
f := -0.4277279326939782213;
testrel( 7, NE, y, f, cnt,failed);
y := DirichletLambdax(1e-20);
f := -3.465735902799726547e-21;
testrel( 8, NE, y, f, cnt,failed);
y := DirichletLambdax(0);
f := 0;
testabs( 9, 0, y, f, cnt,failed);
y := DirichletLambdax(-1e-10);
f := 3.465735902282880147e-11;
testrel(10, NE, y, f, cnt,failed);
y := DirichletLambdax(-5.5);
f := 0.1182249311977602014;
testrel(11, NE, y, f, cnt,failed);
y := DirichletLambdax(-9);
f := 511/132;
testrel(12, NE, y, f, cnt,failed);
y := DirichletLambdax(-9.5);
f := 4.824496622405952553;
testrel(13, NE, y, f, cnt,failed);
y := DirichletLambdax(-215);
f := -0.1914521579845423869e303;
testrel(14, NE2, y, f, cnt,failed);
y := DirichletLambdax(-1753);
f := 0.1126151884810807157e4056;
testrel(15, NE3, y, f, cnt,failed);
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{---------------------------------------------------------------------------}
procedure test_LegendreChix;
var
s,x,y,f: extended;
cnt, failed: integer;
const
NE = 5;
begin
cnt := 0;
failed := 0;
writeln('Function: ','LegendreChix');
{lchi := (s,x) -> (polylog(s,x)-polylog(s,-x))/2;}
y := LegendreChix(27.6,1);
f := 1.000000000000067835;
testrel( 1, NE, y, f, cnt,failed);
y := LegendreChix(27.6,0.25);
f := 0.2500000000000010599;
testrel( 2, NE, y, f, cnt,failed);
y := LegendreChix(22.8,1);
f := 1.000000000013232417;
testrel( 3, NE, y, f, cnt,failed);
y := LegendreChix(22.8,0.25);
f := 0.2500000000002067548;
testrel( 4, NE, y, f, cnt,failed);
y := LegendreChix(41,1);
f := 1;
testrel( 5, NE, y, f, cnt,failed);
y := LegendreChix(41,0.9);
f := 0.9;
testrel( 6, NE, y, f, cnt,failed);
y := LegendreChix(41,0.1);
f := 0.1;
testrel( 7, NE, y, f, cnt,failed);
x := 1-ldexp(1,-40);
y := LegendreChix(0,x);
f := 549755813887.7499999;
testrel( 8, NE, y, f, cnt,failed);
y := LegendreChix(1,x);
f := 14.20951720147865147;
testrel( 9, NE, y, f, cnt,failed);
y := LegendreChix(1.5,x);
f := 1.688759496312122536;
testrel(10, NE, y, f, cnt,failed);
y := LegendreChix(2,x);
f := 1.233700550122791599;
testrel(11, NE, y, f, cnt,failed);
y := LegendreChix(1.9375,x);
f := 1.261856101682040955;
testrel(12, NE, y, f, cnt,failed);
x := 0.9375;
y := LegendreChix(3,x);
f := 0.9773160665376878901;
testrel(13, NE, y, f, cnt,failed);
y := LegendreChix(2,x);
f := 1.090626526643523340;
testrel(14, NE, y, f, cnt,failed);
y := LegendreChix(1,x);
f := 1.716993602242573123;
testrel(15, NE, y, f, cnt,failed);
y := LegendreChix(0.125,x);
f := 5.935102407465141301;
testrel(16, NE, y, f, cnt,failed);
y := LegendreChix(0,x);
f := 7.74193548387096774193548387097;
testrel(17, NE, y, f, cnt,failed);
s := 1+ldexp(1,-30);
y := LegendreChix(s,1);
f := 536870912.6351814228;
testrel(18, NE, y, f, cnt,failed);
s := 1+ldexp(1,-30);
y := LegendreChix(s,0.99609375);
f := 3.118184789086591631;
testrel(19, NE, y, f, cnt,failed);
y := LegendreChix(2,0.5);
f := 0.5153273666943293542;
testrel(20, NE, y, f, cnt,failed);
y := LegendreChix(Pi,0.5);
f := 0.5041812993238665247;
testrel(21, NE, y, f, cnt,failed);
y := LegendreChix(Pi,1);
f := 1.042956220681483755;
testrel(22, NE, y, f, cnt,failed);
y := LegendreChix(0,3/4);
f := 12/7;
testrel(23, NE, y, f, cnt,failed);
y := LegendreChix(2,1-ldexp(1,-50));
f := 1.233700550136153684;
testrel(24, NE, y, f, cnt,failed);
y := LegendreChix(2,0.1);
f := 0.1001115131643563575;
testrel(25, NE, y, f, cnt,failed);
y := LegendreChix(2,0.99);
f := 1.202075664776857538;
testrel(26, NE, y, f, cnt,failed);
y := LegendreChix(2,1);
f := sqr(Pi)/8;
testrel(27, NE, y, f, cnt,failed);
y := LegendreChix(17,1-ldexp(1,-50));
f := 1.000000007744838568;
testrel(28, NE, y, f, cnt,failed);
y := LegendreChix(17,0.125);
f := 0.125000000015124111;
testrel(29, NE, y, f, cnt,failed);
y := LegendreChix(17,0.99);
f := 0.990000007514784503;
testrel(30, NE, y, f, cnt,failed);
y := LegendreChix(17,1);
f := 1.000000007744839456;
testrel(31, NE, y, f, cnt,failed);
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{---------------------------------------------------------------------------}
procedure test_polylogx;
var
x,y,f: extended;
cnt, failed: integer;
const
NE = 8;
NE2 = 16;
NE3 = 160;
begin
cnt := 0;
failed := 0;
writeln('Function: ','polylogx');
x := -4;
y := polylogx(-10,x);
f := -9.179867136;
testrel( 1, NE, y, f, cnt,failed);
x := -2;
y := polylogx(-10,x);
f := 12.98673982624599909;
testrel( 2, NE, y, f, cnt,failed);
x := -0.9375;
y := polylogx(-10,x);
f := -5.513617961192165296;
{$ifdef BASM}
testrel( 3, NE, y, f, cnt,failed);
{$else}
testrel( 3, 30, y, f, cnt,failed); {!!!????}
{$endif}
x := -0.375;
y := polylogx(-10,x);
f := 2.7526396512211967113;
testrel( 4, NE, y, f, cnt,failed);
x := -0.125;
y := polylogx(-10,x);
f := -0.4948902328188429910;
testrel( 5, NE, y, f, cnt,failed);
x := 0.125;
y := polylogx(-10,x);
f := 1154.3834518967005141;
testrel( 6, NE, y, f, cnt,failed);
x := 0.375;
y := polylogx(-10,x);
f := 4489888.134893568;
testrel( 7, NE, y, f, cnt,failed);
x := 0.9375;
y := polylogx(-10,x);
f := 44849120154417799440.0;
testrel( 8, NE, y, f, cnt,failed);
x := 4;
y := polylogx(-10,x);
f := -99851.129401005944216;
testrel( 9, NE, y, f, cnt,failed);
x := -4;
y := polylogx(-5,x);
f := 0.11648;
testrel(10, NE, y, f, cnt,failed);
x := -2;
y := polylogx(-5,x);
f := -0.57613168724279835391e-1;
testrel(11, NE, y, f, cnt,failed);
x := -0.9375;
y := polylogx(-5,x);
f := -0.24779282014042711334;
testrel(12, NE, y, f, cnt,failed);
x := -0.375;
y := polylogx(-5,x);
f := 0.45505630345215321403e-1;
testrel(13, NE, y, f, cnt,failed);
x := -0.125;
y := polylogx(-5,x);
f := 0.78262685792025831654e-1;
testrel(14, NE, y, f, cnt,failed);
x := 0.125;
y := polylogx(-5,x);
f := 1.4851634948023357615;
testrel(15, NE, y, f, cnt,failed);
x := 0.375;
y := polylogx(-5,x);
f := 134.77632;
testrel(16, NE, y, f, cnt,failed);
x := 0.9375;
y := polylogx(-5,x);
f := 1660608240.0;
testrel(17, NE, y, f, cnt,failed);
x := 4;
y := polylogx(-5,x);
f := 16.905349794238683128;
testrel(18, NE, y, f, cnt,failed);
x := -4;
y := polylogx(3,x);
f := -2.9671076939431944597;
testrel(19, NE, y, f, cnt,failed);
x := -2;
y := polylogx(3,x);
f := -1.6682833639665712120;
testrel(20, NE, y, f, cnt,failed);
x := -1.25;
y := polylogx(3,x);
f := -1.1032795677851719720;
testrel(21, NE, y, f, cnt,failed);
x := -0.9375;
y := polylogx(3,x);
f := -0.84988320611888332528;
testrel(22, NE, y, f, cnt,failed);
x := -0.625;
y := polylogx(3,x);
f := -0.58339381700091951204;
testrel(23, NE, y, f, cnt,failed);
x := -0.375;
y := polylogx(3,x);
f := -0.35911489585411991165;
testrel(24, NE, y, f, cnt,failed);
x := -0.125;
y := polylogx(3,x);
f := -0.12311562602883607226;
testrel(25, NE, y, f, cnt,failed);
x := 0.125;
y := polylogx(3,x);
f := 0.12702954097934859904;
testrel(26, NE, y, f, cnt,failed);
x := 0.375;
y := polylogx(3,x);
f := 0.3949165234332217059;
testrel(27, NE, y, f, cnt,failed);
x := 0.9375;
y := polylogx(3,x);
f := 1.104748926956492455;
testrel(28, NE, y, f, cnt,failed);
x := -4;
y := polylogx(10,x);
f := -3.9852813502030905105;
testrel(29, NE, y, f, cnt,failed);
x := -2;
y := polylogx(10,x);
f := -1.9962164930503395001;
testrel(30, NE, y, f, cnt,failed);
x := -1.25;
y := polylogx(10,x);
f := -1.2485051313747192922;
testrel(31, NE, y, f, cnt,failed);
x := -0.9375;
y := polylogx(10,x);
f := -0.93665497525551672216;
testrel(32, NE, y, f, cnt,failed);
x := -0.625;
y := polylogx(10,x);
f := -0.62462252819071471797;
testrel(33, NE, y, f, cnt,failed);
x := -0.375;
y := polylogx(10,x);
f := -0.37486354581717511487;
testrel(34, NE, y, f, cnt,failed);
x := -0.125;
y := polylogx(10,x);
f := -0.12498477405751377867;
testrel(35, NE, y, f, cnt,failed);
x := 0.125;
y := polylogx(10,x);
f := 0.12501529210142635343;
testrel(36, NE, y, f, cnt,failed);
x := 0.375;
y := polylogx(10,x);
f := 0.37513824183158653697;
testrel(37, NE, y, f, cnt,failed);
x := 0.9375;
y := polylogx(10,x);
f := 0.93837308609808966430;
testrel(38, NE, y, f, cnt,failed);
x := -4;
y := polylogx(6,x);
f := -3.8050745875177576463;
testrel(39, NE, y, f, cnt,failed);
x := -2;
y := polylogx(6,x);
f := -1.9458305048460724536;
testrel(40, NE, y, f, cnt,failed);
x := -1.25;
y := polylogx(6,x);
f := -1.2278089280721467032;
testrel(41, NE, y, f, cnt,failed);
x := -0.9375;
y := polylogx(6,x);
f := -0.9247444157530764757;
testrel(42, NE, y, f, cnt,failed);
x := -0.625;
y := polylogx(6,x);
f := -0.619199203891737450347;
testrel(43, NE, y, f, cnt,failed);
x := -0.375;
y := polylogx(6,x);
f := -0.3728706669691755157;
testrel(44, NE, y, f, cnt,failed);
x := -0.125;
y := polylogx(6,x);
f := -0.12475848082937029109;
testrel(45, NE, y, f, cnt,failed);
x := 0.125;
y := polylogx(6,x);
f := 0.12524688145264086435;
testrel(46, NE, y, f, cnt,failed);
x := 0.375;
y := polylogx(6,x);
f := 0.37727497647999170526;
testrel(47, NE, y, f, cnt,failed);
x := 0.9375;
y := polylogx(6,x);
f := 0.95262262228338317537;
testrel(48, NE, y, f, cnt,failed);
x := -2;
y := polylogx(-9,x);
f := 3.4540466392318244170;
testrel(49, NE, y, f, cnt,failed);
y := polylogx(-8,x);
f := -2.0256058527663465935;
testrel(50, NE, y, f, cnt,failed);
y := polylogx(-7,x);
f := -0.14540466392318244170;
testrel(51, NE, y, f, cnt,failed);
y := polylogx(-6,x);
f := 0.40329218106995884774;
testrel(52, NE, y, f, cnt,failed);
y := polylogx(-5,x);
f := -0.57613168724279835391e-1;
testrel(53, NE, y, f, cnt,failed);
y := polylogx(-4,x);
f := -0.12345679012345679012;
testrel(54, NE, y, f, cnt,failed);
y := polylogx(-3,x);
f := 2/27;
testrel(55, NE, y, f, cnt,failed);
y := polylogx(-2,x);
f := 2/27;
testrel(56, NE, y, f, cnt,failed);
y := polylogx(-1,x);
f := -2/9;
testrel(57, NE, y, f, cnt,failed);
y := polylogx( 0,x);
f := -2/3;
testrel(58, NE, y, f, cnt,failed);
y := polylogx(1,x);
f := -1.0986122886681096914;
testrel(59, NE, y, f, cnt,failed);
y := polylogx(2,x);
f := -1.4367463668836809464;
testrel(60, NE, y, f, cnt,failed);
x := -0.125;
y := polylogx(-9,x);
f := -1.1418293161051686144;
testrel(61, NE, y, f, cnt,failed);
y := polylogx(-8,x);
f := -0.44952366987487850701;
testrel(62, NE, y, f, cnt,failed);
y := polylogx(-7,x);
f := -0.86590567490610957336e-2;
testrel(63, NE, y, f, cnt,failed);
y := polylogx(-6,x);
f := 0.10864046996750344817;
testrel(64, NE, y, f, cnt,failed);
y := polylogx(-5,x);
f := 0.78262685792025831654e-1;
testrel(65, NE, y, f, cnt,failed);
y := polylogx(-4,x);
f := 0.14225473759081440837e-1;
testrel(66, NE, y, f, cnt,failed);
y := polylogx(-3,x);
f := -0.40237768632830361225e-1;
testrel(67, NE, y, f, cnt,failed);
y := polylogx(-2,x);
f := -0.76817558299039780521e-1;
testrel(68, NE, y, f, cnt,failed);
y := polylogx(-1,x);
f := -0.987654320987654321e-1;
testrel(69, NE, y, f, cnt,failed);
y := polylogx( 0,x);
f := -1/9;
testrel(70, NE, y, f, cnt,failed);
y := polylogx(1,x);
f := -0.11778303565638345454;
testrel(71, NE, y, f, cnt,failed);
y := polylogx(2,x);
f := -0.12129662872272647871;
testrel(72, NE, y, f, cnt,failed);
x := 0.75;
y := polylogx(-9,x);
f := 93461994732.0;
testrel(73, NE, y, f, cnt,failed);
y := polylogx(-8,x);
f := 2987482260.0;
testrel(74, NE, y, f, cnt,failed);
y := polylogx(-7,x);
f := 107430636.0;
testrel(75, NE, y, f, cnt,failed);
y := polylogx(-6,x);
f := 4415124.0;
testrel(76, NE, y, f, cnt,failed);
y := polylogx(-5,x);
f := 211692.0;
testrel(77, NE, y, f, cnt,failed);
y := polylogx(-4,x);
f := 12180.0;
testrel(78, NE, y, f, cnt,failed);
y := polylogx(-3,x);
f := 876.0;
testrel(79, NE, y, f, cnt,failed);
y := polylogx(-2,x);
f := 84.0;
testrel(80, NE, y, f, cnt,failed);
y := polylogx(-1,x);
f := 12.0;
testrel(81, NE, y, f, cnt,failed);
y := polylogx( 0,x);
f := 3.0;
testrel(82, NE, y, f, cnt,failed);
y := polylogx(1,x);
f := 1.3862943611198906188;
testrel(83, NE, y, f, cnt,failed);
y := polylogx(2,x);
f := 0.97846939293030610374;
testrel(84, NE, y, f, cnt,failed);
{larger negative n, x < -4}
y := polylogx(-16, -20);
f := -225.6984685459220749;
testrel(85, NE, y, f, cnt,failed);
y := polylogx(-16, -12);
f := 2208.471352806776057;
testrel(86, NE2, y, f, cnt,failed);
y := polylogx(-16, -10);
f := 3714.753659565581804;
testrel(87, NE3, y, f, cnt,failed);
y := polylogx(-16, -5);
f := -20022.19871067531485;
testrel(88, NE2, y, f, cnt,failed);
y := polylogx(42, -0.75);
f := -0.7499999999998721023;
testrel(89, NE, y, f, cnt,failed);
y := polylogx(64, 0.75);
f := 0.75;
testrel(90, NE, y, f, cnt,failed);
y := polylogx(16,1.0);
f := 0.50000764112970432594*2; {=1.000015282259408651872}
testrel(91, NE, y, f, cnt,failed);
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{---------------------------------------------------------------------------}
procedure test_polylogrx;
var
s,y,f: extended;
cnt, failed: integer;
const
NE = 6;
NE2 = 10;
NE3 = 40;
begin
cnt := 0;
failed := 0;
writeln('Function: ','polylogrx');
y := polylogrx(5,0.75);
f := 0.7697354105997573810;
testrel( 1, NE, y, f, cnt,failed);
y := polylogrx(42.5,-0.75);
f := -0.7499999999999095627;
testrel( 2, NE, y, f, cnt,failed);
y := polylogrx(42.5,0.75);
f := 0.7500000000000904373;
testrel( 3, NE, y, f, cnt,failed);
y := polylogrx(42.5,1);
f := 1.000000000000160777;
testrel( 4, NE, y, f, cnt,failed);
y := polylogrx(42.5,-1);
f := -0.9999999999998392225;
testrel( 5, NE, y, f, cnt,failed);
y := polylogrx(40.5,-1);
f := -0.9999999999993568902;
testrel( 6, NE, y, f, cnt,failed);
y := polylogrx(40.5, 1);
f := 1.000000000000643110;
testrel( 7, NE, y, f, cnt,failed);
y := polylogrx(40.5,-0.75);
f := -0.7499999999996382507;
testrel( 8, NE, y, f, cnt,failed);
y := polylogrx(40.5, 0.75);
f := 0.7500000000003617493;
testrel( 9, NE, y, f, cnt,failed);
y := polylogrx(40.25,-1);
f := -0.9999999999992352092;
testrel(10, NE, y, f, cnt,failed);
y := polylogrx(40.25, 1);
f := 1.000000000000764791;
testrel(11, NE, y, f, cnt,failed);
y := polylogrx(40.25,-0.75);
f := -0.7499999999995698052;
testrel(12, NE, y, f, cnt,failed);
y := polylogrx(40.25, 0.75);
f := 0.7500000000004301949;
testrel(13, NE, y, f, cnt,failed);
y := polylogrx(40,-0.75);
f := -0.7499999999994884093;
testrel(14, NE, y, f, cnt,failed);
y := polylogrx(40, 0.75);
f := 0.75000000000051159080;
testrel(15, NE, y, f, cnt,failed);
y := polylogrx(0,0.75);
f := 3;
testrel(16, NE, y, f, cnt,failed);
y := polylogrx(2.5,0.5);
f := 0.5549972787175122932;
testrel(17, NE, y, f, cnt,failed);
y := polylogrx(2.5,-0.5);
f := -0.4622977821900634382;
testrel(18, NE, y, f, cnt,failed);
y := polylogrx(2.5,0.50390625);
f := 0.5598843647061405067;
testrel(19, NE, y, f, cnt,failed);
y := polylogrx(2.5,-0.50390625);
f := -0.4656545654919774045;
testrel(20, NE, y, f, cnt,failed);
y := polylogrx(2.5,0.9921875);
f := 1.322594574342688176;
testrel(21, NE, y, f, cnt,failed);
y := polylogrx(2.5,-0.9921875);
f := -0.8612172798686255019;
testrel(22, NE, y, f, cnt,failed);
y := polylogrx(2.5,1);
f := 1.341487257250917180;
testrel(23, NE, y, f, cnt,failed);
y := polylogrx(2.5,-1);
f := -0.8671998890121841382;
testrel(24, NE, y, f, cnt,failed);
y := polylogrx(0.5,-1);
f := -0.6048986434216303702;
testrel(25, NE, y, f, cnt,failed);
y := polylogrx(0.5,0.9990234375);
f := 55.244520579175209022;
testrel(26, NE2, y, f, cnt,failed); {?????}
y := polylogrx(0.5,1-ldexp(1,-40));
f := 0.1858551108812170978e7;
testrel(27, NE, y, f, cnt,failed);
y := polylogrx(0.5,1.0);
{f := PosInf_x;
testabs(28, 0, y, f, cnt,failed);}
f := -1.460354508809586813;
testrel(28, NE, y, f, cnt,failed); {change: polylog(s,1)=zeta(s)}
s := 1+ldexp(1,-40);
y := polylogrx(s,1);
f := 0.1099511627776577216e13;
testrel(29, NE, y, f, cnt,failed);
y := polylogrx(s,-1);
f := -0.6931471805600907093;
testrel(30, NE, y, f, cnt,failed);
y := polylogrx(s,0.75);
f := 1.386294361119239802;
testrel(31, NE, y, f, cnt,failed);
y := polylogrx(s,-0.75);
f := -0.5596157879355182278;
testrel(32, NE, y, f, cnt,failed);
y := polylogrx(s,0.25);
f := 0.2876820724517544193;
testrel(33, NE, y, f, cnt,failed);
y := polylogrx(s,-0.25);
f := -0.2231435513142252513;
testrel(34, NE, y, f, cnt,failed);
y := polylogrx(-0.9921875, -0.9375);
f := -0.2517042218174219566;
testrel(35, NE3, y, f, cnt,failed);
y := polylogrx(-0.9921875, -0.5);
f := -0.2232513428133884107;
testrel(36, NE, y, f, cnt,failed);
y := polylogrx(-0.9921875, -0.375);
f := -0.1990593704344978727;
testrel(37, NE, y, f, cnt,failed);
y := polylogrx(-0.375, -0.9375);
f := -0.4014043247268414126;
testrel(38, NE, y, f, cnt,failed);
y := polylogrx(-0.375, -0.5);
f := -0.2965680466460651464;
testrel(39, NE, y, f, cnt,failed);
y := polylogrx(-0.375, -0.125);
f := -0.1073243322124273833;
testrel(40, NE, y, f, cnt,failed);
y := polylogrx(-0.75, -1);
f := -0.3158761453565543129;
testrel(41, NE, y, f, cnt,failed);
y := polylogrx(0.875, -1);
f := -0.6726499691730939986;
testrel(42, NE, y, f, cnt,failed);
y := polylogrx(-0.75, 1);
f := -0.1336427744365845624; {mpmath 0.17}
testrel(43, NE, y, f, cnt,failed);
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{---------------------------------------------------------------------------}
procedure test_fermi_diracx;
var
y,f: extended;
cnt, failed: integer;
const
NE = 4;
NE2 = 8;
begin
cnt := 0;
failed := 0;
writeln('Function: ','fermi_diracx');
{Maple: fd := (n,x) -> -polylog(n+1,-exp(x));}
y := fermi_diracx(0,1);
f := 1.313261687518222834;
testrel(1, NE, y, f, cnt,failed);
y := fermi_diracx(0,-1);
f := 0.3132616875182228340;
testrel(2, NE, y, f, cnt,failed);
y := fermi_diracx(1,1);
f := 1.806286070444774257;
testrel(3, NE, y, f, cnt,failed);
y := fermi_diracx(-1,1);
f := 0.7310585786300048793;
testrel(4, NE, y, f, cnt,failed);
y := fermi_diracx(1,-1);
f := 0.3386479964034521798;
testrel(5, NE, y, f, cnt,failed);
y := fermi_diracx(-1,-1);
f := 0.2689414213699951207;
testrel(6, NE, y, f, cnt,failed);
y := fermi_diracx(-2,1);
f := 0.1966119332414818525;
testrel(7, NE, y, f, cnt,failed);
y := fermi_diracx(-3,1);
f := -0.9085774767294840944e-1;
testrel(8, NE, y, f, cnt,failed);
y := fermi_diracx(-2,-1);
f := 0.1966119332414818525;
testrel(9, NE, y, f, cnt,failed);
y := fermi_diracx(-3,-1);
f := 0.9085774767294840944e-1;
testrel(10, NE, y, f, cnt,failed);
y := fermi_diracx(-4,1e-5);
f := -0.1249999999875000000;
testrel(11, NE, y, f, cnt,failed);
y := fermi_diracx(-4,-1e-5);
f := -0.1249999999875000000;
testrel(12, NE, y, f, cnt,failed);
y := fermi_diracx(4,1e-5);
f := 0.9721292408202815493;
testrel(13, NE, y, f, cnt,failed);
y := fermi_diracx(4,-1e-5);
f := 0.9721103001636913303;
testrel(14, NE, y, f, cnt,failed);
y := fermi_diracx(8,10);
f := 7946.319776573429079;
testrel(15, NE, y, f, cnt,failed);
y := fermi_diracx(8,-10);
f := 0.4539992573679893686e-4;
testrel(16, NE, y, f, cnt,failed);
y := fermi_diracx(9,10);
f := 10388.99016731291248;
testrel(17, NE, y, f, cnt,failed);
y := fermi_diracx(9,-10);
f := 0.4539992774964110184e-4;
testrel(18, NE, y, f, cnt,failed);
y := fermi_diracx(-3,10);
f := -0.4539168599011319565e-4;
testrel(19, NE, y, f, cnt,failed);
y := fermi_diracx(-3,-10);
f := 0.4539168599011319565e-4;
testrel(20, NE, y, f, cnt,failed);
y := fermi_diracx(8,10000);
f := 0.2755735186158236597e31;
testrel(21, NE, y, f, cnt,failed);
y := fermi_diracx(8,15000);
f := 0.1059396483983069418e33;
testrel(22, NE, y, f, cnt,failed);
y := fermi_diracx(5,20000);
f := 0.8888889985511638002e23;
testrel(23, NE, y, f, cnt,failed);
y := fermi_diracx(1,12000);
f := 0.7200000164493406684823e8;
testrel(24, NE, y, f, cnt,failed);
y := fermi_diracx(0,12000);
f := 12000;
testrel(25, NE, y, f, cnt,failed);
y := fermi_diracx(-1,12000);
f := 1;
testrel(26, NE, y, f, cnt,failed);
y := fermi_diracx(-2,12000);
f := 0;
testabs(27, 0, y, f, cnt,failed);
y := fermi_diracx(100,200);
f := 0.4216103500655924161e73;
testrel(28, NE2, y, f, cnt,failed);
y := fermi_diracx(200,100);
f := 0.2688117141816135437e44;
testrel(29, NE2, y, f, cnt,failed);
y := fermi_diracx(-100,200);
f := 0.1383896526736737531e-86;
testrel(30, NE2, y, f, cnt,failed);
y := fermi_diracx(-200,100);
f := -0.1111917984507457867e-26;
testrel(31, NE2, y, f, cnt,failed);
y := fermi_diracx(500,10);
f := 22026.46579480671652;
testrel(32, NE, y, f, cnt,failed);
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{---------------------------------------------------------------------------}
procedure test_fermi_dirac_halfx;
var
y,f: extended;
cnt, failed: integer;
const
NE = 4;
{$ifdef FPC271or3}
NE1 = 5;
{$endif}
begin
cnt := 0;
failed := 0;
writeln('Function: ','fermi_dirac_m05x/p05x/p15x/p25x');
y := fermi_dirac_m05x(-20);
f := 0.2061153619434517730e-8;
testrel(1, NE, y, f, cnt,failed);
y := fermi_dirac_m05x(-10);
f := 0.4539847236080549532e-4;
testrel(2, NE, y, f, cnt,failed);
y := fermi_dirac_m05x(-2);
f := 0.1236656218012099427;
testrel(3, NE, y, f, cnt,failed);
y := fermi_dirac_m05x(-0.5);
f := 0.4312314419263970869;
testrel(4, NE, y, f, cnt,failed);
y := fermi_dirac_m05x(0);
f := 0.6048986434216303702;
testrel(5, NE, y, f, cnt,failed);
y := fermi_dirac_m05x(1);
f := 1.027057125474350689;
testrel(6, NE, y, f, cnt,failed);
y := fermi_dirac_m05x(3.5);
f := 2.026193699100460058;
testrel(7, NE, y, f, cnt,failed);
y := fermi_dirac_m05x(4);
f := 2.185869690623811946;
testrel(8, NE, y, f, cnt,failed);
y := fermi_dirac_m05x(4.5);
f := 2.334245766142244249;
testrel(9, NE, y, f, cnt,failed);
y := fermi_dirac_m05x(10);
f := 3.552779239536617160;
testrel(10, NE, y, f, cnt,failed);
y := fermi_dirac_m05x(13.5);
f := 4.136326785587186739;
testrel(11, NE, y, f, cnt,failed);
y := fermi_dirac_m05x(14);
f := 4.212933653105178558;
testrel(12, NE, y, f, cnt,failed);
y := fermi_dirac_m05x(14.5);
f := 4.288146102878802782;
testrel(13, NE, y, f, cnt,failed);
y := fermi_dirac_m05x(20);
f := 5.041018507535328603;
testrel(14, NE, y, f, cnt,failed);
y := fermi_dirac_m05x(39.5);
f := 7.089878704263408613;
testrel(15, NE, y, f, cnt,failed);
y := fermi_dirac_m05x(40);
f := 7.134657233550764731;
testrel(16, NE, y, f, cnt,failed);
y := fermi_dirac_m05x(40.5);
f := 7.179155892384824069;
testrel(17, NE, y, f, cnt,failed);
y := fermi_dirac_m05x(100);
f := 11.28332744292768060;
testrel(18, NE, y, f, cnt,failed);
y := fermi_dirac_m05x(1000);
f := 35.68246764915936962; {alpha}
testrel(19, NE, y, f, cnt,failed);
y := fermi_dirac_m05x(10000);
f := 112.8379162455239043; {alpha}
testrel(20, NE, y, f, cnt,failed);
y := fermi_dirac_m05x(1000000);
f := 1128.379167095048547; {alpha}
testrel(21, NE, y, f, cnt,failed);
{---------}
y := fermi_dirac_p05x(-20);
f := 0.2061153620936537778e-8;
testrel(22, NE, y, f, cnt,failed);
y := fermi_dirac_p05x(-10);
f := 0.4539920105264132755e-4;
testrel(23, NE, y, f, cnt,failed);
y := fermi_dirac_p05x(-2);
f := 0.1292985133200755911;
testrel(24, NE, y, f, cnt,failed);
y := fermi_dirac_p05x(-0.5);
f := 0.5075371035546378361;
testrel(25, NE, y, f, cnt,failed);
y := fermi_dirac_p05x(0);
f := 0.7651470246254079454;
testrel(26, NE, y, f, cnt,failed);
y := fermi_dirac_p05x(1);
f := 1.575640776151300231;
testrel(27, NE, y, f, cnt,failed);
y := fermi_dirac_p05x(3.5);
f := 5.458044388745459911;
testrel(28, NE, y, f, cnt,failed);
y := fermi_dirac_p05x(4);
f := 6.511567592754791415;
testrel(29, NE, y, f, cnt,failed);
y := fermi_dirac_p05x(4.5);
f := 7.642031275793455330;
testrel(30, NE, y, f, cnt,failed);
y := fermi_dirac_p05x(9);
f := 20.62401821156795236;
testrel(31, NE, y, f, cnt,failed);
y := fermi_dirac_p05x(11.5);
f := 29.61226879150170305;
testrel(32, NE, y, f, cnt,failed);
y := fermi_dirac_p05x(12);
f := 31.54020328704424259;
testrel(33, NE, y, f, cnt,failed);
y := fermi_dirac_p05x(12.5);
f := 33.50923983932172004;
testrel(34, NE, y, f, cnt,failed);
y := fermi_dirac_p05x(20);
f := 67.49151222165892049;
testrel(35, NE, y, f, cnt,failed);
y := fermi_dirac_p05x(35.5);
f := 159.2691126191554513;
testrel(36, NE, y, f, cnt,failed);
y := fermi_dirac_p05x(36);
f := 162.6413796464579914;
testrel(37, NE, y, f, cnt,failed);
y := fermi_dirac_p05x(36.5);
f := 166.0371774151569984;
testrel(38, NE, y, f, cnt,failed);
y := fermi_dirac_p05x(100);
f := 752.3455915521961188;
testrel(39, NE, y, f, cnt,failed);
y := fermi_dirac_p05x(10000);
f := 752252.7873442217908; {alpha}
testrel(40, NE, y, f, cnt,failed);
y := fermi_dirac_p05x(1000000);
f := 7.522527780646031039e8; {alpha}
testrel(41, NE, y, f, cnt,failed);
{---------}
y := fermi_dirac_p15x(-20);
f := 0.2061153621687547803e-8;
testrel(42, NE, y, f, cnt,failed);
y := fermi_dirac_p15x(-10);
f := 0.4539956540456176333e-4;
testrel(43, NE, y, f, cnt,failed);
y := fermi_dirac_p15x(-2);
f := 0.1322467822517723668;
testrel(44, NE, y, f, cnt,failed);
y := fermi_dirac_p15x(-0.5);
f := 0.5526495259473540854;
testrel(45, NE, y, f, cnt,failed);
y := fermi_dirac_p15x(0);
f := 0.8671998890121841382;
testrel(46, NE, y, f, cnt,failed);
y := fermi_dirac_p15x(1);
f := 2.002258148778464457;
testrel(47, NE, y, f, cnt,failed);
y := fermi_dirac_p15x(3.5);
f := 10.27141115061732259;
testrel(48, NE, y, f, cnt,failed);
y := fermi_dirac_p15x(4);
f := 13.26048817729106850;
testrel(49, NE, y, f, cnt,failed);
y := fermi_dirac_p15x(4.5);
f := 16.79579730928991532;
testrel(50, NE, y, f, cnt,failed);
y := fermi_dirac_p15x(9);
f := 78.66626344736753771;
testrel(51, NE, y, f, cnt,failed);
y := fermi_dirac_p15x(11.5);
f := 141.2287997372907052;
testrel(52, NE, y, f, cnt,failed);
y := fermi_dirac_p15x(12);
f := 156.5151864279572804;
testrel(53, NE, y, f, cnt,failed);
y := fermi_dirac_p15x(12.5);
f := 172.7758530334651074;
testrel(54, NE, y, f, cnt,failed);
y := fermi_dirac_p15x(20);
f := 546.5630100657601959;
testrel(55, NE, y, f, cnt,failed);
y := fermi_dirac_p15x(35.5);
f := 2270.464576509283294;
testrel(56, NE, y, f, cnt,failed);
y := fermi_dirac_p15x(36);
f := 2350.941215700957481;
testrel(57, NE, y, f, cnt,failed);
y := fermi_dirac_p15x(36.5);
f := 2433.109877926863218;
testrel(58, NE, y, f, cnt,failed);
y := fermi_dirac_p15x(100);
f := 30108.67168135486936;
testrel(59, NE, y, f, cnt,failed);
y := fermi_dirac_p15x(10000);
f := 3.009011297865632890e9; {alpha}
testrel(60, NE, y, f, cnt,failed);
y := fermi_dirac_p15x(20000);
f := 1.702153755962129317e10; {alpha}
testrel(61, NE, y, f, cnt,failed);
y := fermi_dirac_p15x(1000000);
f := 3.00901111227325e14; {GSL/double}
testrele(62, 5e-15, y, f, cnt,failed);
{---------}
y := fermi_dirac_p25x(-20);
f := 0.2061153622063052815e-8;
testrel(63, NE, y, f, cnt,failed);
y := fermi_dirac_p25x(-10);
f := 0.4539974758252285430e-4;
testrel(64, NE, y, f, cnt,failed);
y := fermi_dirac_p25x(-2);
f := 0.1337669290459732776;
testrel(65, NE, y, f, cnt,failed);
y := fermi_dirac_p25x(-0.5);
f := 0.5779521605410086652;
testrel(66, NE, y, f, cnt,failed);
y := fermi_dirac_p25x(0);
f := 0.9275535777739480351;
testrel(67, NE, y, f, cnt,failed);
y := fermi_dirac_p25x(1);
f := 2.294832963121518129;
testrel(68, NE, y, f, cnt,failed);
y := fermi_dirac_p25x(3.5);
f := 15.60768391014749828;
testrel(69, NE, y, f, cnt,failed);
y := fermi_dirac_p25x(4);
f := 21.46870822801142616;
testrel(70, NE, y, f, cnt,failed);
y := fermi_dirac_p25x(4.5);
f := 28.959226461407335057;
{$ifdef FPC271or3}
testrel(71, NE1, y, f, cnt,failed);
{$else}
testrel(71, NE, y, f, cnt,failed);
{$endif}
y := fermi_dirac_p25x(9);
f := 221.7903608693186891;
testrel(72, NE, y, f, cnt,failed);
y := fermi_dirac_p25x(11.5);
f := 491.9765499165918583;
testrel(73, NE, y, f, cnt,failed);
y := fermi_dirac_p25x(12);
f := 566.3723808356910136;
testrel(74, NE, y, f, cnt,failed);
y := fermi_dirac_p25x(12.5);
{$ifdef BIT16}
f := 1297.308237613687465*0.5;
{$else}
f := 648.654118806843732657;
{$endif}
{$ifdef FPC271or3}
testrel(75, NE1, y, f, cnt,failed);
{$else}
testrel(75, NE, y, f, cnt,failed);
{$endif}
y := fermi_dirac_p25x(20);
f := 3186.735096831265885;
testrel(76, NE, y, f, cnt,failed);
y := fermi_dirac_p25x(35.5);
f := 23178.76346773165267;
testrel(77, NE, y, f, cnt,failed);
y := fermi_dirac_p25x(36);
f := 24334.04466016358338;
testrel(78, NE, y, f, cnt,failed);
y := fermi_dirac_p25x(36.5);
f := 25529.98668772732444;
testrel(79, NE, y, f, cnt,failed);
y := fermi_dirac_p25x(100);
f := 860954.9737352777100;
testrel(80, NE, y, f, cnt,failed);
y := fermi_dirac_p25x(1000);
f := 0.2718704450106142809e10;
testrel(81, NE, y, f, cnt,failed);
y := fermi_dirac_p25x(5000);
f := 0.7598904953966710865e12;
testrel(82, NE, y, f, cnt,failed);
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{$endif}
end.
|
unit U_Raise_Add;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uDateControl, uCharControl, uFloatControl, uFControl,
uLabeledFControl, uSpravControl, StdCtrls, Buttons, DB, FIBDataSet,
pFIBDataSet, U_SPPost_DataModule;
type
TAddRaiseForm = class(TForm)
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
qFSC_Raise: TqFSpravControl;
qFFC_Percent: TqFFloatControl;
qFDC_Beg: TqFDateControl;
qFDC_End: TqFDateControl;
pFIBDS_Raise: TpFIBDataSet;
procedure qFSC_RaiseOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
procedure BitBtn1Click(Sender: TObject);
procedure BitBtn2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
DMod:TDMSPPost;
{ Public declarations }
end;
var
AddRaiseForm: TAddRaiseForm;
implementation
{$R *.dfm}
uses uCommonSp, SpCommon, qFTools;
procedure TAddRaiseForm.qFSC_RaiseOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: String);
var
sp: TSprav;
begin
try // создать справочник
sp := GetSprav('ASUP\SpRaise');
if sp <> nil then
begin
// заполнить входные параметры
with sp.Input do
begin
Append;
// присвоить хэндл базы данных
FieldValues['DBHandle'] := Integer(pFIBDS_Raise.Database.Handle);
// модально
FieldValues['ShowStyle'] := 0;
// выбор
FieldValues['Select'] := 1;
// смотрим на текущую дату
FieldValues['Actual_Date'] := Date;
Post;
end;
end;
// просто показать справочник
sp.Show;
sp.Output.Open;
if not sp.Output.IsEmpty then
begin
value:=sp.Output['id_raise'];
pFIBDS_Raise.ParamByName('id_raise').AsInteger:=sp.Output['id_raise'];
pFIBDS_Raise.ParamByName('act_date').AsDate:=Date;
pFIBDS_Raise.Open;
DisplayText:=pFIBDS_Raise['full_name'];
qFFC_Percent.Value:=pFIBDS_Raise['RAISE_DEFAULT'];
pFIBDS_Raise.Close;
end;
{ while not sp.Output.Eof do
begin
RxMD_Raise.Open;
RxMD_Raise.First;
flag:=False;
while (not RxMD_Raise.Eof)and(not flag) do
begin
flag:=RxMD_Raise['id_raise']=sp.Output['id_raise'];
RxMD_Raise.Next;
end;
if not flag then
begin
RxMD_Raise.Append;
RxMD_Raise['id_raise']:=sp.Output['id_raise'];
RxMD_Raise.Post;
RxMD_Raises.Append;
RxMD_Raises['id_raise']:=sp.Output['id_raise'];
RxMD_Raises['id_post_base_salary']:=id_bs;
RxMD_Raises['name_post_salary']:=RxMD_PS['name_post_salary'];
RxMD_Raises['pps_koef']:=RxMD_PS['pps_koef'];
RxMD_Raises['id_post_salary']:=RxMD_PS['id_post_salary'];
RxMD_Raises.Post;
end;
sp.Output.Next;
end;
Refresh; }
except on e:exception do
MessageDlg('Не вдалося завантажити довідник "ASUP\SpRaise":'+#13+e.Message,mtError,[mbYes],0);
end;
end;
procedure TAddRaiseForm.BitBtn1Click(Sender: TObject);
begin
if VarIsNull(qFSC_Raise.Value) then
begin
ShowMessage('Не обрана надбавка!');
ModalResult:=0;
Exit;
end;
if VarIsNull(qFFC_Percent.Value) then
begin
ShowMessage('Не задан відсоток!');
ModalResult:=0;
Exit;
end;
if VarIsNull(qFDC_Beg.Value) then
begin
ShowMessage('Не має дати початку!');
ModalResult:=0;
Exit;
end;
if VarIsNull(qFDC_End.Value) then
begin
ShowMessage('Не має дати кінця');
ModalResult:=0;
Exit;
end;
if VarToDateTime(qFDC_End.Value)<=VarToDateTime(qFDC_Beg.Value) then
begin
ShowMessage('Дата кінця має бути більшою за дату початка!');
ModalResult:=0;
Exit;
end;
ModalResult:=MrOk;
end;
procedure TAddRaiseForm.BitBtn2Click(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TAddRaiseForm.FormCreate(Sender: TObject);
begin
qFAutoLoadFromRegistry(Self, nil);
end;
procedure TAddRaiseForm.FormDestroy(Sender: TObject);
begin
qFAutoSaveIntoRegistry(Self, nil);
end;
end.
|
unit tuo1;
INTERFACE
uses util1,debug0;
{ typeListeUO est une liste chaŒn‚e utilis‚e par le compilateur Ncompil.
Elle recense tous les objets d‚clar‚s dans le programme.
Tous les objets doivent descendre d'un mˆme ancˆtre mais la liste ne fait
aucune hypothŠse sur leur type et manipule de simples pointeurs.
Dans Acquis1, les objets descendent de typeUO (PUO=^typeUO).
typeUO doit au minimum contenir un nom, ce nom doit pouvoir ˆtre renvoy‚
par getIdent
Chaque ‚l‚ment de la liste contient un pointeur ou un tableau de pointeur,
ce qui correspond … la d‚claration d'une variable simple ou d'une variable
tableau.
Une application doit cr‚er une liste descendant de typeListeUO qui
surchargera certaines m‚thodes, en particulier disposeUO et getIdent.
La m‚thode VIDER permet de vider la liste en d‚truisant tous les objets.
Le programme PG1 manipule les adresses des pointeurs. Une m‚thode PG1 re‡oit
toujours l'adresse du pointeur comme paramŠtre et non pas le pointeur
lui-mˆme, ce qui permet de contr“ler que l'objet a bien ‚t‚ cr‚‚.
(Quand le pointeur vaut nil, l'objet n'a pas ‚t‚ cr‚‚)
La liste contient un nombre vob qui identifie le type des objets.
Avec ajoute(v,n) on ajoute n pointeurs valant nil dans la liste, avec le
type v. Ajoute renvoie l'adresse de ce bloc de pointeurs (PPUO)
disposeUO(p:pointer); est une m‚thode virtuelle qui doit contenir
dispose(PUO(p),done)
getIdent(p:pointer):string; est une m‚thode virtuelle qui doit contenir
if PUO(p)^.ident=nil then getIdent:=''
else getIdent:=PUO(p)^.ident^;
initRejouer et rejouer sont utilis‚s par la table des symboles au moment
d'une recherche d'erreur: … ce moment, on recompile mais il ne faut pas
modifier la liste des objets.
getAd renvoie l'adresse d'un objet (PUO) connaissant un nom
nil si l'objet n'existe pas.
NbName renvoie le nombre d'objets initilis‚s et portant un nom.
getFirst et getNext (PPUO) permettent de parcourir la liste. Typiquement:
p:=getFirst;
while p<>nil do
begin
..... traitement
p:=getNext;
end;
}
type
PLUO=^typeLUO; {El‚ment de la liste UO}
typeLUO=
record
suivant:PLUO;
vob:smallInt;
nbelt:smallInt;
case smallInt of
1:(p:pointer); {PUO}
2:(pt:array[1..10000] of pointer); {PUO}
end;
typeListeUO= {Liste des user objects}
object
ps:PLUO;
ns:smallInt;
premier:PLUO;
pJ:pLUO;
constructor init;
function ajoute(v,n:smallInt):pointer; {PPUO}
procedure InitRejouer;
function rejouer(v,n:smallInt):pointer;
procedure disposeUO(p:pointer);virtual;
procedure vider;
procedure libererObjet(pu:pointer);
procedure EffacerObjet(pu:pointer);
function getIdent(p:pointer):string;virtual;
function getAd(st:string):pointer; {PUO}
function NbName:smallInt;
function getFirst:pointer; {PPUO}
function getNext:pointer; {PPUO}
end;
PlisteUO=^typeListeUO;
IMPLEMENTATION
{**************************** M‚thodes de typeListeUO ********************}
constructor typeListeUO.init;
begin
premier:=nil;
end;
function typeListeUO.ajoute(v,n:smallInt):pointer;
var
p0,p1:pLUO;
begin
p0:=@self;
p1:=premier;
while (p1<>nil) do
begin
p0:=p1;
p1:=p1^.suivant;
end;
getmem(p1,8+n*4);
with p1^ do
begin
suivant:=nil;
nbelt:=n;
vob:=v;
fillchar(p,n*4,0);
end;
if p0=@self then premier:=p1
else p0^.suivant:=p1;
ajoute:=@p1^.p;
end;
procedure typeListeUO.initRejouer;
begin
pJ:=getFirst;
end;
function typeListeUO.rejouer(v,n:smallInt):pointer;
var
i:smallInt;
begin
rejouer:=pJ;
for i:=1 to n do pJ:=getNext;
end;
procedure typeListeUO.disposeUO(p:pointer);
begin
{doit contenir dispose(PUO(p),done)}
end;
{
procedure typeListeUO.vider;
var
p1,p2:pLUO;
i,nb:smallInt;
begin
p1:=premier;
while (p1<>nil) do
begin
nb:=p1^.nbElt;
for i:=1 to p1^.nbElt do
if p1^.pt[i]<>nil then disposeUO(p1^.pt[i]);
p2:=p1^.suivant;
freemem(p1,8+4*nb);
p1:=p2;
end;
premier:=nil;
end;
}
procedure typeListeUO.vider;
var
p1,p2:pLUO;
i,nb:smallInt;
begin
{Vider d'abord le contenu}
p1:=premier;
while (p1<>nil) do
begin
nb:=p1^.nbElt;
for i:=1 to p1^.nbElt do
if p1^.pt[i]<>nil then
begin
disposeUO(p1^.pt[i]);
p1^.pt[i]:=nil;
end;
p1:=p1^.suivant;
end;
{Détruire ensuite}
p1:=premier;
while (p1<>nil) do
begin
nb:=p1^.nbElt;
p2:=p1^.suivant;
freemem(p1,8+4*nb);
p1:=p2;
end;
premier:=nil;
end;
procedure typeListeUO.libererObjet(pu:pointer);
var
p1:pLUO;
i,nb:smallInt;
begin
if pu=nil then exit;
p1:=premier;
while (p1<>nil) do
begin
nb:=p1^.nbElt;
for i:=1 to p1^.nbElt do
if p1^.pt[i]=pu then
begin
disposeUO(p1^.pt[i]);
p1^.pt[i]:=nil;
end;
p1:=p1^.suivant;
end;
end;
procedure typeListeUO.EffacerObjet(pu:pointer);
var
p1:pLUO;
i,nb:smallInt;
begin
if pu=nil then exit;
p1:=premier;
while (p1<>nil) do
begin
nb:=p1^.nbElt;
for i:=1 to p1^.nbElt do
if p1^.pt[i]=pu then
begin
p1^.pt[i]:=nil;
end;
p1:=p1^.suivant;
end;
end;
function typeListeUO.getIdent(p:pointer):string;
begin
{doit contenir
if PUO(p)^.ident=nil then getIdent:=''
else getIdent:=PUO(p)^.ident^;
}
end;
function typeListeUO.getAd(st:string):pointer;
var
p1:pLUO;
i:smallInt;
begin
getAd:=nil;
p1:=premier;
while (p1<>nil) do
begin
for i:=1 to p1^.nbElt do
if (p1^.pt[i]<>nil)
and (Fmaj(getIdent(p1^.pt[i]))=Fmaj(st)) then
begin
getAd:=p1^.pt[i];
exit;
end;
p1:=p1^.suivant;
end;
end;
function typeListeUO.NbName:smallInt;
var
p1,p2:pLUO;
i,nb,n:smallInt;
begin
p1:=premier;
n:=0;
while (p1<>nil) do
begin
nb:=p1^.nbElt;
for i:=1 to p1^.nbElt do
if (p1^.pt[i]<>nil) and (getIdent(p1^.pt[i])<>'') then inc(n);
p2:=p1^.suivant;
p1:=p2;
end;
nbName:=n;
end;
function typeListeUO.getFirst:pointer;
begin
ps:=premier;
ns:=1;
if ps=nil
then getFirst:=nil
else getFirst:=@ps^.pt[ns];
end;
function typeListeUO.getNext:pointer;
begin
if ps=nil then
begin
getNext:=nil;
exit;
end;
if ns<ps^.nbElt then
begin
inc(ns);
getNext:=@ps^.pt[ns];
end
else
begin
ns:=1;
ps:=ps^.suivant;
if ps=nil
then getNext:=nil
else getNext:=@ps^.pt[ns];
end;
end;
end. |
{$I-,Q-,R-,S-}
{Problema 8: Fiesta Vacuna Plata [Richard Ho, 2006]
Una vaca de cada una de N granjas (1 <= N <= 1000) convenientemente
numeradas 1..N van a ir a una gran fiesta vacuna que tendrá lugar en
la granja #X (1 <= X <= N). Un total de M (1 <= M <= 100,000)
carreteras unidireccionlaes (de un sentido) conectan pares de granjas;
la carretera i requiere Ti (1 <= Ti <= 100) unidades de tiempo para
recorrerse.
Cada vaca debe caminar a la fiesta, y luego cuando se acabe la fiesta,
volver a su granja. Cada vaca es floja y por lo tanto elige una ruta
óptima con el tiempo más corta. La ruta de regreso de una vaca podría
ser diferente de su ruta original debido a que las carreteras son de
un sentido.
De todas las vacas, ¿cuál es la cantidad más grande de tiempo que una
vaca debe gastar caminando a la fiesta y devolviéndose?
NOMBRE DEL PROBLEMA: sparty
FORMATO DE ENTRADA:
* Línea 1: Tres enteros separados por espacios, respectivamente N y M
y x.
* Líneas 2..M+1: La línea i+1 describe la carretera i con tres enteros
separados por espacios: Ai, Bi, y Ti. La carretera descrita va
de la granja Ai a la granja Bi, requiriendo Ti unidades para
recorrerse
ENTRADA EJEMPLO (archivo sparty.in):
4 8 2
1 2 4
1 3 2
1 4 7
2 1 1
2 3 5
3 1 2
3 4 4
4 2 3
DETALLES DE LA ENTRADA:
Cuatro vacas, ocho carreteras: la fiesta es en la granja 2.
FORMATO DE LA SALIDA:
* Línea 1: Un entero: La máxima cantidad de tiempo que cualquier vaca
debe caminar.
SALIDA EJEMPLO (archivo sparty.out):
10
DETALLES DE LA SALIDA:
La vaca 4 va directamente a la fiesta (3 unidades) y se devuelve via
las granjas 1 y 3 (7 unidades), para un total de 10 unidades de
tiempo.
}
{ Free Pascal , Dos Dijkstra }
const
max = 100001;
cow = 1001;
var
fe,fs : text;
n,m,sol,p : longint;
tab : array[1..max,1..5] of longint;
cam : array[1..cow,1..2] of longint;
suma,d : array[0..cow] of longint;
s : array[1..cow] of boolean;
procedure open;
var
i : longint;
begin
assign(fe,'sparty.in'); reset(fe);
assign(fs,'sparty.out'); rewrite(fs);
readln(fe,n,m,p);
for i:=1 to m do
begin
readln(fe,tab[i,1],tab[i,2],tab[i,3]);
tab[i,4]:=cam[tab[i,1],1]; cam[tab[i,1],1]:=i;
tab[i,5]:=cam[tab[i,2],2]; cam[tab[i,2],2]:=i;
end;
close(fe);
end;
procedure dijkstra(node,ini,fin : longint);
var
i,j,k,x : longint;
begin
fillchar(s,sizeof(s),false);
s[node]:=true; d[node]:=0; x:=node;
for i:=1 to n-1 do
begin
j:=cam[x,ini];
while (j <> 0) do
begin
k:=d[x] + tab[j,3];
if d[tab[j,fin]] > k then
d[tab[j,fin]]:=k;
j:=tab[j,3+ini];
end;
x:=0;
for j:=1 to n do
if (not s[j]) and (d[j] < d[x]) then
x:=j;
s[x]:=true;
end;
end;
procedure work;
var
i : longint;
begin
sol:=0;
fillchar(d,sizeof(d),127);
d[0]:=maxlongint;
dijkstra(p,2,1);
for i:=1 to n do
begin
suma[i]:=d[i];
end;
fillchar(d,sizeof(d),127);
d[0]:=maxlongint;
dijkstra(p,1,2);
for i:=1 to n do
begin
suma[i]:=suma[i] + d[i];
if suma[i] > sol then
sol:=suma[i];
end;
end;
procedure closer;
begin
writeln(fs,sol);
close(fs);
end;
begin
open;
work;
closer;
end. |
//***********************************************************************
//* Проект "Студгородок" *
//* Добавление льготы *
//* Выполнил: Чернявский А.Э. 2004-2005 г. *
//***********************************************************************
unit uSp_effective_area_AE;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxStyles, cxCustomData, cxGraphics,
cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxCalendar,
cxCurrencyEdit, cxGridLevel, cxGridCustomTableView, cxGridTableView,
cxClasses, cxControls, cxGridCustomView, cxGridDBTableView, cxGrid,
Buttons, cxCheckBox, cxTextEdit, cxLabel, cxContainer, cxGroupBox,
StdCtrls, cxButtons, FIBDataSet, pFIBDataSet, st_ConstUnit,
uSp_effective_area_DM, st_common_funcs, iBase,
st_Common_Messages, st_Consts_Messages, st_common_types, cxMaskEdit,
cxDropDownEdit, cxButtonEdit, St_Loader_Unit;
type
Tfrm_effective_area_AE = class(TForm)
cxGroupBox1: TcxGroupBox;
NameLabel: TcxLabel;
OKButton: TcxButton;
CancelButton: TcxButton;
Label_koef: TcxLabel;
CurrencyEdit_koef: TcxCurrencyEdit;
cxButtonEdit_Builds: TcxButtonEdit;
DateEdit_beg: TcxDateEdit;
DateEdit_end: TcxDateEdit;
cxLabel1: TcxLabel;
cxLabel2: TcxLabel;
procedure CancelButtonClick(Sender: TObject);
procedure OKButtonClick(Sender: TObject);
procedure MedCheckKeyPress(Sender: TObject; var Key: Char);
procedure cxButtonEdit_BuildsPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
private
PLanguageIndex: byte;
procedure FormIniLanguage;
public
aHandle : TISC_DB_HANDLE;
is_admin : Boolean;
id_build : Int64;
DM : Tfrm_effective_area_DM;
constructor Create(aOwner : TComponent; aHandle : TISC_DB_HANDLE; id_build : int64);reintroduce;
end;
var
frm_effective_area_AE: Tfrm_effective_area_AE;
implementation
{$R *.dfm}
procedure Tfrm_effective_area_AE.FormIniLanguage();
begin
// индекс языка (1-укр, 2 - рус)
PLanguageIndex:= stLanguageIndex;
//названия кнопок
OKButton.Caption := st_ConstUnit.st_Accept[PLanguageIndex];
CancelButton.Caption := st_ConstUnit.st_Cancel[PLanguageIndex];
end;
procedure Tfrm_effective_area_AE.CancelButtonClick(Sender: TObject);
begin
Close;
end;
procedure Tfrm_effective_area_AE.OKButtonClick(Sender: TObject);
begin
if cxButtonEdit_Builds.Text = '' then
Begin
ShowMessage('Необхідно обрати гуртожиток!');
cxButtonEdit_Builds.SetFocus;
exit;
end;
if DateEdit_end.EditValue <= DateEdit_beg.EditValue then
Begin
ShowMessage('Дата початку повинна бути менше дати закінчення!');
DateEdit_beg.SetFocus;
exit;
end;
if CurrencyEdit_koef.EditValue = 0 then
Begin
ShowMessage('Необхідно ввести коефіцієнт житлової площі!');
CurrencyEdit_koef.SetFocus;
exit;
end;
ModalResult := mrOK;
end;
procedure Tfrm_effective_area_AE.MedCheckKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then OKButton.SetFocus;
end;
constructor Tfrm_effective_area_AE.Create(aOwner: TComponent;
aHandle: TISC_DB_HANDLE; id_build: int64);
begin
inherited Create(aOwner);
self.id_build := id_build;
self.aHandle := aHandle;
DM := Tfrm_effective_area_DM.Create(self);
DM.DB.Handle := aHandle;
DM.DB.Connected := True;
DM.Transaction_Read.StartTransaction;
FormIniLanguage;
end;
procedure Tfrm_effective_area_AE.cxButtonEdit_BuildsPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
ResOpl:Variant;
BuildInfo: TBuildsInfo;
begin
BuildInfo.id_build:= -1;
BuildInfo.N_Room := '';
ResOpl:= Load_st_Builds(self, DM.DB.Handle, true, false, BuildInfo);
if VarArrayDimCount(ResOpl)>0 then
begin
id_build := ResOpl[0];
cxButtonEdit_Builds.Text := ResOpl[2];
end;
end;
end.
|
unit uNTierConsts;
interface
const
CON_TYPE_DCOM = 'DCOM';
CON_TYPE_SOCKET = 'SOCKET';
CON_TYPE_WEB = 'WEB';
CON_PARAM_TYPE = 'Type';
CON_PARAM_CLIENT_ID = 'ClientID';
CON_PARAM_HOST = 'Host';
CON_PARAM_PORT = 'Port';
CON_PARAM_SOFTWARE = 'Software';
implementation
end.
|
unit DataSetExport;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,IBase, FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet,
Halcn6db, ComCtrls, StdCtrls, cxLookAndFeelPainters, cxButtons,
cxControls, cxContainer, cxEdit, cxProgressBar, cxTextEdit, ZMessages,
zProc, cxMaskEdit, cxButtonEdit, cxLabel, pfibquery, cxShellDlgs,
cxShellBrowserDialog;
function ExpBankDataSet(AOwner:TComponent;DataSet:TpFIBDataSet;IdBank:integer):Variant;stdcall;
exports ExpBankDataSet;
type
TBankExportForm = class(TForm)
DSet: TpFIBDataSet;
DbfExport: THalcyonDataSet;
SaveDialog: TSaveDialog;
CreateDBUniver: TCreateHalcyonDataSet;
LabelFile: TcxLabel;
ProgressBar: TcxProgressBar;
StartBtn: TcxButton;
ExitBtn: TcxButton;
cxshlbrwsrdlg1: TcxShellBrowserDialog;
eFileNameEdit: TcxButtonEdit;
procedure StartBtnClick(Sender: TObject);
procedure FileNameEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure ExitBtnClick(Sender: TObject);
private
pIdBank:integer;
fType : integer;
pl_num : integer;
procedure GenFileName(Path : string);
public
constructor Create(AOwner:TComponent;DataSet:TpFIBDataSet;IdBank:integer);reintroduce;
procedure ExportDefault(DataSet : TpFIBDataSet);
procedure ExportExim(DataSet : TpFIBDataSet);
procedure ExportProminvest(DataSet: TpFIBDataSet);
procedure ExportPrivat(DataSet: TpFIBDataSet);
procedure ExportTxt(DataSet: TpFIBDataSet);
end;
implementation
uses StrUtils, DateUtils;
function ExpBankDataSet(AOwner:TComponent;DataSet:TpFIBDataSet;IdBank:integer):Variant;
var
form : TBankExportForm;
q : TpFIBQuery;
begin
form := TBankExportForm.Create(AOwner, DataSet, IdBank);
q := TpFIBQuery.Create(form);
q.Database := DataSet.Database;
q.Transaction := DataSet.Transaction;
q.SQL.Text := 'select DEFAULT_PATH, EXPORT_PROC from z_sp_type_payment where id_mfo = :id_bank';
q.Prepare;
q.ParamByName('ID_BANK').AsInt64 := IdBank;
try
q.ExecQuery;
except
ZShowMessage('Помилка!', 'Неможливо получити шлях за замовчуванням!', mtError, [mbOk]);
q.Close;
form.free;
exit;
end;
form.fType := 0;
if q.RecordCount = 0 then
begin
ZShowMessage('Помилка!', 'Неможливо получити шлях за замовчуванням!', mtError, [mbOk]);
q.Close;
form.free;
exit;
end;
if VarIsNull(q['DEFAULT_PATH'].AsVariant) then
begin
ZShowMessage('Помилка!', 'Неможливо получити шлях за замовчуванням!', mtError, [mbOk]);
q.Close;
form.free;
exit;
end;
if q['EXPORT_PROC'].AsString = 'ExportExim' then form.fType := 1;
if q['EXPORT_PROC'].AsString = 'ExportProminvest' then form.fType := 2;
if q['EXPORT_PROC'].AsString = 'ExportPrivat' then form.fType := 3;
if q['EXPORT_PROC'].AsString = 'ExportTxt' then form.fType := 4;
form.GenFileName(q['DEFAULT_PATH'].AsString);
q.Close;
form.ShowModal;
form.Free;
end;
Constructor TBankExportForm.Create(AOwner:TComponent;DataSet:TpFIBDataSet;IdBank:integer);
begin
inherited Create(AOwner);
DSet := DataSet;
pl_num := DataSet['NUM_DOC'];
pIdBank := IdBank;
end;
{$R *.dfm}
procedure TBankExportForm.StartBtnClick(Sender: TObject);
begin
if eFileNameEdit.Text<>'' then
begin
case fType of
0 : ExportDefault(DSet);
1 : ExportExim(DSet);
2 : ExportProminvest(DSet);
3 : ExportPrivat(DSet);
4 : ExportTxt(DSet);
end;
end else ZShowMessage('Увага!','Не знайден шлях експорту!', mtInformation, [mbOk]);
end;
procedure TBankExportForm.FileNameEditPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
begin
if not cxshlbrwsrdlg1.Execute then exit;
GenFileName(cxshlbrwsrdlg1.Path);
end;
procedure TBankExportForm.ExitBtnClick(Sender: TObject);
begin
DSet := nil;
Close;
end;
procedure TBankExportForm.ExportExim(DataSet: TpFIBDataSet);
var
RecordCount : integer;
begin
DbfExport.Close;
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
CreateDBUniver.CreateFields.Clear;
CreateDBUniver.CreateFields.Add('TRAN_DATE;D;8;0');
CreateDBUniver.CreateFields.Add('CARD_ACCT;C;10;0');
CreateDBUniver.CreateFields.Add('AMOUNT;N;10;2');
CreateDBUniver.CreateFields.Add('CURRENCY;C;3;0');
CreateDBUniver.CreateFields.Add('FIO;C;50;0');
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(DbfExport.DatabaseName + '\' + DbfExport.TableName));
if not CreateDBUniver.Execute then
begin
ZShowMessage('Помилка!', 'Неможливо створити файл!', mtError, [mbOk]);
Exit;
end;
DbfExport.Exclusive:=False;
DbfExport.Open;
try
While not(DSet.Eof) do
begin
DbfExport.Append;
DbfExport['TRAN_DATE'] := DSet['EXPORT_DAY'];
DbfExport['CARD_ACCT'] := DSet['ACCT_CARD'];
DbfExport['AMOUNT'] := DSet['SUMMA'];
DbfExport['CURRENCY'] := 'UAH';
DbfExport['FIO'] := DSet['FIO'];
DbfExport.Post;
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
end;
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
DbfExport.Close;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportProminvest(DataSet: TpFIBDataSet);
var
RecordCount : integer;
begin
DbfExport.Close;
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
CreateDBUniver.CreateFields.Clear;
CreateDBUniver.CreateFields.Add('A;C;16;0');
CreateDBUniver.CreateFields.Add('B;C;45;0');
CreateDBUniver.CreateFields.Add('C;N;11;2');
CreateDBUniver.CreateFields.Add('COMPANY;C;30;0');
CreateDBUniver.CreateFields.Add('INN;C;10;0');
CreateDBUniver.CreateFields.Add('T_N;C;32;0');
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(DbfExport.DatabaseName + '\' + DbfExport.TableName));
if not CreateDBUniver.Execute then
begin
ZShowMessage('Помилка!', 'Неможливо створити файл!', mtError, [mbOk]);
Exit;
end;
DbfExport.Exclusive:=False;
DbfExport.Open;
try
While not(DSet.Eof) do
begin
DbfExport.Append;
DbfExport['A'] := DSet['ACCT_CARD'];
DbfExport['B'] := DSet['FIO'];
DbfExport['C'] := DSet['SUMMA'];
DbfExport['COMPANY'] := DSet['NAME_CUSTOMER_NATIVE'];
DbfExport['INN'] := DSet['TIN'];
DbfExport['T_N'] := '';
DbfExport.Post;
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
end;
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
DbfExport.Close;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportDefault(DataSet: TpFIBDataSet);
var
TotalRecord:Integer;
Flag:boolean;
begin
DbfExport.Close;
DSet.Open;
DSet.Last;
Totalrecord := DSet.RecordCount;
DSet.First;
ProgressBar.Properties.Max:=TotalRecord;
Flag := CreateDBUniver.Execute;
if Flag then
begin
DbfExport.Exclusive:=True;
DbfExport.Open;
end
else
begin
ZShowMessage('Помилка!','Неможливо створити файл!',mtError,[mbOk]);
Exit;
end;
while(not DbfExport.Eof) do
begin
DbfExport.Delete;
DbfExport.Next;
end;
DbfExport.Close;
DbfExport.Exclusive:=False;
DbfExport.Open;
try
While not(DSet.Eof) do
begin
DbfExport.Append;
DbfExport['ID_MAN'] := DSet['ID_MAN'];
DbfExport['TN'] := DSet['TN'];
DbfExport['FIO'] := DSet['FIO'];
DbfExport['SUMMA'] := DSet['SUMMA'];
DbfExport['ACCT_CARD'] := DSet['ACCT_CARD'];
DbfExport['TIN'] := DSet['TIN'];
DbfExport.Post;
DSet.Next;
ProgressBar.Position := ProgressBar.Position+1;
Application.ProcessMessages;
end;
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
DbfExport.Close;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportPrivat(DataSet: TpFIBDataSet);
var
RecordCount : integer;
s : string;
begin
DbfExport.Close;
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
CreateDBUniver.CreateFields.Clear;
CreateDBUniver.CreateFields.Add('PERIOD;C;22;0');
CreateDBUniver.CreateFields.Add('TN;N;10;0');
CreateDBUniver.CreateFields.Add('LSTBL;C;16;0');
CreateDBUniver.CreateFields.Add('FAM;C;20;0');
CreateDBUniver.CreateFields.Add('NAME;C;20;0');
CreateDBUniver.CreateFields.Add('OT;C;20;0');
CreateDBUniver.CreateFields.Add('RLSUM;N;16;2');
CreateDBUniver.CreateFields.Add('RLKOD;C;1;0');
CreateDBUniver.CreateFields.Add('TIN;C;10;0');
CreateDBUniver.CreateFields.Add('DATE_RO;D;8;0');
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(DbfExport.DatabaseName + '\' + DbfExport.TableName));
if not CreateDBUniver.Execute then
begin
ZShowMessage('Помилка!', 'Неможливо створити файл!', mtError, [mbOk]);
Exit;
end;
DbfExport.Exclusive:=False;
DbfExport.Open;
try
While not(DSet.Eof) do
begin
DbfExport.Append;
s := '';
case MonthOf(DSet['EXPORT_DAY'])of
1: s := 'январь';
2: s := 'февраль';
3: s := 'март';
4: s := 'апрель';
5: s := 'май';
6: s := 'июнь';
7: s := 'июль';
8: s := 'август';
9: s := 'сентябрь';
10: s := 'октябрь';
11: s := 'ноябрь';
12: s := 'декабрь';
end;
DbfExport['PERIOD'] := s + ' месяц ' + IntToStr(YearOf(DSet['EXPORT_DAY'])) + ' год';
DbfExport['TN'] := DSet['ID_MAN'];
DbfExport['LSTBL'] := DSet['ACCT_CARD'];
DbfExport['FAM'] := DSet['FAMILIYA'];
DbfExport['NAME'] := DSet['IMYA'];
DbfExport['OT'] := DSet['OTCHESTVO'];
DbfExport['RLSUM'] := DSet['SUMMA'];
DbfExport['RLKOD'] := 'з';
DbfExport['TIN'] := DSet['TIN'];
DbfExport['DATE_RO'] := DSet['BIRTH_DATE'];
DbfExport.Post;
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
end;
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
DbfExport.Close;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
end;
procedure TBankExportForm.ExportTxt(DataSet: TpFIBDataSet);
var
RecordCount : integer;
sl : TStringList;
i : integer;
idx : integer;
str, s : PAnsiChar;
test_str : string;
sum_str : string;
sum : Currency;
begin
DSet.Open;
DSet.FetchAll;
RecordCount := DSet.RecordCount;
DSet.First;
ProgressBar.Properties.Max := RecordCount;
ProgressBar.Position := 0;
DeleteFile(PChar(eFileNameEdit.Text));
sl := TStringList.Create;
DecimalSeparator := '.';
sl.Add('Реєстр зарахувань на картрахунки');
sl.Add('органiзацiї ' + AnsiUpperCase(DSet['NAME_CUSTOMER_NATIVE']));
sl.Add('до платiжного документа N ' + IntToStr(DSet['NUM_DOC']));
sl.Add('вiд ' + StringReplace(FormatDateTime('dd/mm/yy', DSet['EXPORT_DAY']), '.', '/', [rfReplaceAll]));
sl.Add('iм''я файлу: ' + ExtractFileName(eFileNameEdit.Text));
sl.Add('МФО банку платника: ' + DSet['MFO_CUST']);
sl.Add('Поточний рахунок платника: ' + DSet['RATE_ACCOUNT_CUST']);
sl.Add('Код ЕДРПОУ платника: ' + DSet['KOD_EDRPOU_CUST']);
sl.Add('Загальна суму до зарахування: ' + FormatFloat('0.00', DSet['SUMMA_ALL']));
sl.Add('Валюта зарахування: 980');
//Если вызывается из договоров то это відрядження
if Owner.ClassName = 'TplatForm' then
sl.Add('Призначення: зарахування видатків на відрядження')
else
sl.Add('Призначення: зарахування зароботной плати');
sl.Add('---------------------------------------------------------------------');
idx := 1;
try
While not(DSet.Eof) do
begin
if idx < 10 then test_str := ' ' + IntToStr(idx)
else
if idx < 100 then test_str := ' ' + IntToStr(idx)
else
if idx < 1000 then test_str := ' ' + IntToStr(idx)
else
if idx < 10000 then test_str := ' ' + IntToStr(idx)
else
test_str := IntToStr(idx);
sum := DSet.FBN('SUMMA').AsCurrency;
if sum < 10 then sum_str := ' ' + FormatFloat('0.00', DSet.FBN('SUMMA').AsCurrency)
else
if sum < 100 then sum_str := ' ' + FormatFloat('0.00', DSet.FBN('SUMMA').AsCurrency)
else
if sum < 1000 then sum_str := ' ' + FormatFloat('0.00', DSet.FBN('SUMMA').AsCurrency)
else
if sum < 10000 then sum_str := ' ' + FormatFloat('0.00', DSet.FBN('SUMMA').AsCurrency)
else
sum_str := FormatFloat('0.00', DSet.FBN('SUMMA').AsCurrency);
sl.Add(test_str + ' ' + DSet['ACCT_CARD'] + ' ' + sum_str + ' ' + DSet['FIO']);
inc(idx);
DSet.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
end;
for i := 0 to sl.Count - 1 do
begin
s := PAnsiChar(sl.Strings[i]);
GetMem(str, Length(s) + 2);
CharToOem(s, Str);
sl.Strings[i] := StrPas(Str);;
end;
sl.SaveToFile(eFileNameEdit.Text);
except
on e:Exception do
begin
ZShowMessage('Помилка!', 'Неможливо зробити імпорт!' + #13 + e.Message, mtError, [mbOk]);
exit;
end;
end;
sl.Free;
ZShowMessage('Завершення','Данні експортовано.',mtInformation, [mbOk]);
DecimalSeparator := ',';
end;
procedure TBankExportForm.GenFileName(Path : string);
var
s : string;
sr : TSearchRec;
mask : string;
num : integer;
function GetExt : string;
begin
if fType = 4 then Result := '.txt' else Result := '.dbf';
end;
begin
if path[Length(path)] <> '\' then path := path + '\';
// s := FormatDateTime('mmdd', date);
s := IntToStr(pl_num);
case fType of
0 : s := 'DF' + s;
1 : s := 'EX' + s;
2 : s := 'PR' + s;
3 : S := 'PV' + S;
4 : s := 'US' + s;
end;
{ num := 0;
while FileExists(path + s + IfThen(num < 10, '0' + IntToStr(num), IntToStr(num)) + GetExt) do
begin
inc(num);
end;}
// s := path + s + IfThen(num < 10, '0' + IntToStr(num), IntToStr(num)) + GetExt;
if Owner.ClassName = 'TplatForm' then
s := path + s + 'P' + GetExt
else
s := path + s + GetExt;
eFileNameEdit.Text := s;
DbfExport.DatabaseName := ExtractFilePath(s);;
DbfExport.TableName := ExtractFileName(s);
end;
end.
|
(****************************************************************************
*
* WinLIRC plug-in for jetAudio
*
* Copyright (c) 2016 Tim De Baets
*
****************************************************************************
*
* 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.
*
****************************************************************************
*
* Helper class to make stdcall virtual methods callable as thiscall
*
****************************************************************************)
unit ThisCall;
interface
uses Windows, Classes;
type
PPointer = ^Pointer;
// thunk for translating thiscall calls to stdcall (ECX -> stack)
TThisCallThunk = record
PopEAX: Byte; // $58, pop ret address from stack
PushECX: Byte; // $51, push 'this' argument
PushEAX: Byte; // $50, push ret address back to stack
Jmp: Byte; // $E9, relative jump
JmpAddress: DWORD; // original proc - addr(TThisCallThunk) - sizeof(TThisCallThunk)
end;
PThisCallThunk = ^TThisCallThunk;
TThisCallThunks = class
public
constructor Create(Obj: TObject; NumVirtualMethods: Integer);
destructor Destroy; override;
private
fThunks: TList;
procedure PatchMethod(PVTable: Pointer; MethodIdx: Integer);
procedure FreeThunks;
end;
implementation
constructor TThisCallThunks.Create(Obj: TObject; NumVirtualMethods: Integer);
var
i: Integer;
begin
inherited Create;
fThunks := TList.Create;
for i := 0 to NumVirtualMethods - 1 do
PatchMethod(PPointer(Obj)^, i);
end;
destructor TThisCallThunks.Destroy;
begin
FreeThunks;
fThunks.Free;
inherited Destroy;
end;
procedure TThisCallThunks.PatchMethod(PVTable: Pointer; MethodIdx: Integer);
var
pThunk: PThisCallThunk;
pTableEntry: Pointer;
OrigAddress: Pointer;
Bytes: Cardinal;
begin
pTableEntry := Pointer(Integer(PVTable) + MethodIdx * SizeOf(Pointer));
OrigAddress := PPointer(pTableEntry)^;
// DEP compatible!
pThunk := VirtualAlloc(nil, SizeOf(TThisCallThunk), MEM_COMMIT,
PAGE_EXECUTE_READWRITE);
pThunk.PopEAX := $58;
pThunk.PushECX := $51;
pThunk.PushEAX := $50;
pThunk.Jmp := $E9;
pThunk.JmpAddress := Integer(OrigAddress) - Integer(pThunk) -
SizeOf(TThisCallThunk);
if WriteProcessMemory(GetCurrentProcess, pTableEntry, @pThunk, SizeOf(Pointer),
Bytes) then
fThunks.Add(pThunk)
else
VirtualFree(pThunk, SizeOf(TThisCallThunk), MEM_DECOMMIT);
end;
procedure TThisCallThunks.FreeThunks;
var
pThunk: PThisCallThunk;
begin
while fThunks.Count > 0 do begin
pThunk := fThunks.First;
fThunks.Delete(0);
VirtualFree(pThunk, SizeOf(TThisCallThunk), MEM_DECOMMIT);
end;
end;
end.
|
//------------------------------------------------------------------------------
//MapList UNIT
//------------------------------------------------------------------------------
// What it does -
// A list of TMaps
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
unit MapList;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
Map,
ContNrs;
type
//------------------------------------------------------------------------------
//TMapList CLASS
//------------------------------------------------------------------------------
TMapList = Class(TObject)
Private
fList : TObjectList;
fOwnsObject : Boolean;
Function GetValue(Index : Integer) : TMap;
Procedure SetValue(Index : Integer; Value : TMap);
Function GetCount : Integer;
Public
Constructor Create(OwnsMaps : Boolean);
Destructor Destroy; override;
Property Items[Index : Integer] : TMap
read GetValue write SetValue;default;
Procedure Add(const AMap : TMap);
Procedure Insert(const AMap : TMap; Index : Integer);
Procedure Delete(Index : Integer);
Procedure Clear();
Function IndexOf(const MapName : String) : Integer;
Property Count : Integer
read GetCount;
end;
//------------------------------------------------------------------------------
implementation
//------------------------------------------------------------------------------
//Create CONSTRUCTOR
//------------------------------------------------------------------------------
// What it does -
// Initializes our Maplist. Creates a storage area.
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
constructor TMapList.Create(OwnsMaps : Boolean);
begin
inherited Create;
fOwnsObject := OwnsMaps;
fList := TObjectList.Create(FALSE);
end;{Create}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Destroy DESTRUCTOR
//------------------------------------------------------------------------------
// What it does -
// Destroys our list and frees any memory used.
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
destructor TMapList.Destroy;
var
Index : Integer;
begin
if fOwnsObject AND (fList.Count >0) then
begin
for Index := fList.Count -1 downto 0 do
fList.Items[Index].Free;
end;
fList.Free;
// Call TObject destructor
inherited;
end;{Destroy}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Add PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Adds a TMap to the list.
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
procedure TMapList.Add(const AMap : TMap);
begin
fList.Add(AMap);
end;{Add}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Insert PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Inserts a TMap at Index Position.
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
procedure TMapList.Insert(const AMap : TMap; Index: Integer);
begin
fList.Insert(Index, AMap);
end;{Insert}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Delete PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Removes a TMap at Index from the list.
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
procedure TMapList.Delete(Index : Integer);
begin
if fOwnsObject then
fList.Items[Index].Free;
fList.Delete(Index);
end;{Delete}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//IndexOf FUNCTION
//------------------------------------------------------------------------------
// What it does -
// Returns the index in the list of the TMap;
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
function TMapList.IndexOf(const MapName : String): Integer;
var
Index : Integer;
begin
Index := fList.Count-1;
Result := -1;
while (Index >= 0) do
begin
if MapName = Items[Index].Name then
begin
Result := Index;
Exit;
end;
dec(Index, 1);
end;
end;{IndexOf}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Clear PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Clears the list.
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
procedure TMapList.Clear;
var
Index : Integer;
begin
if fOwnsObject AND (fList.Count >0) then
begin
for Index := fList.Count -1 downto 0 do
fList.Items[Index].Free;
end;
fList.Clear;
end;{Clear}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//GetValue FUNCTION
//------------------------------------------------------------------------------
// What it does -
// Returns a TMap at the index.
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
function TMapList.GetValue(Index : Integer): TMap;
begin
Result := TMap(fList.Items[Index]);
end;{GetValue}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//SetValue PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Sets a TMap into the list at Index.
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
procedure TMapList.SetValue(Index : Integer; Value : TMap);
begin
fList.Items[Index] := Value;
end;{SetValue}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//GetCount PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Gets the count from the fList object
//
// Changes -
// October 30th, 2007 - RaX - Created.
//------------------------------------------------------------------------------
Function TMapList.GetCount : Integer;
begin
Result := fList.Count;
end;{GetCount}
//------------------------------------------------------------------------------
end.
|
namespace TicTacToe;
interface
uses
UIKit;
type TGridInfoArray=array[0..2, 0..2] of NSString;
type
[IBObject]
Board = public class(UIControl)
private
fGridOffset: CGPoint;
fStatusLabel: UILabel;
fTentativeView: UIImageView;
fTentativeGridIndex: GridIndex;
fTentativeInfo: String;
fTentativeOk: Boolean;
fTurnCount: Int32;
fGridImages: NSMutableArray<UIImageView> := new NSMutableArray<UIImageView>;
fGridInfo: array[0..2, 0..2] of NSString;
const
X1 = 92;
X2 = 217;
Y1 = 93;
Y2 = 200;
method gridIndexForPoint(aPoint: CGPoint): GridIndex;
method drawingOffsetForGridIndex(aGridIndex: GridIndex): CGPoint;
method playerAtCoordinates(x: Int32; y: Int32): String;
method addMarkerNotAnimated(aX: Int32; aY: Int32; aPlayerAndVersion: String);
method nextPlayerImageForTurn(aPlayer: String): String;
method playerImage(aPlayerInfo: String): UIImageView;
method getGridInfo(aX: Int32; aY: Int32): String;
public
method initWithFrame(aFrame: CGRect): id; override;
property &delegate: weak IBoardDelegate;
property player: String := 'X';
property acceptingTurn: Boolean;
property GridInfo[x,y: Int32]: String read getGridInfo;
method markGrid(aX: Int32; aY: Int32; aPlayer: String);
method makeComputerMove(aPlayer: String);
method isFull: Boolean;
method isEmpty: Boolean;
method isGameOver: Boolean;
method markWinner: String;
method clear(aCompletion: block := nil; aClearAnimated: Boolean);
method saveToNSDictionary(aDictionary: NSMutableDictionary; aXPlayerID: String; aOPlayerID: String);
method loadFromNSDictionary(aDictionary: NSDictionary; aXPlayerID: String; aOPlayerID: String);
method setStatus(aStatus: String);
method beginTrackingWithTouch(aTouch: not nullable UITouch) withEvent(aEvent: UIEvent): Boolean; override;
method continueTrackingWithTouch(aTouch: not nullable UITouch) withEvent(aEvent: UIEvent): Boolean; override;
method endTrackingWithTouch(aTouch: UITouch) withEvent(aEvent: UIEvent); override;
end;
IBoardDelegate = public interface(INSObject)
method board(aBoard: Board) playerWillSelectGridIndex(aGridIndex: GridIndex): Boolean;
method board(aBoard: Board) playerDidSelectGridIndex(aGridIndex: GridIndex);
end;
GridIndex = public record
public
X, Y: Integer;
end;
implementation
method Board.initWithFrame(aFrame: CGRect): id;
begin
self := inherited initWithFrame(aFrame);
if assigned(self) then begin
addSubview(new UIImageView withImage(UIImage.imageNamed('Paper')));
var lGridImage := UIImage.imageNamed('Grid');
var fGrid := new UIImageView withImage(lGridImage);
fGrid.frame := CGRectMake( (frame.size.width-lGridImage.size.width)/2,
(frame.size.width-lGridImage.size.width)*2,
lGridImage.size.width,
lGridImage.size.height);
fGridOffset := fGrid.frame.origin;
addSubview(fGrid);
var lFont := UIFont.fontWithName('Bradley Hand') size(32);
var f := frame;
f.origin.y := fGrid.frame.origin.y + fGrid.frame.size.height + 10; // 30 on 4"?
f.size.height := 'Xy'.sizeWithFont(lFont).height;
fStatusLabel := new UILabel withFrame(f);
fStatusLabel.opaque := false;
fStatusLabel.backgroundColor := UIColor.colorWithRed(0) green(0) blue(0) alpha(0);
fStatusLabel.font := lFont;
fStatusLabel.textAlignment := NSTextAlignment.NSTextAlignmentCenter;
fStatusLabel.lineBreakMode := NSLineBreakMode.NSLineBreakByTruncatingMiddle;
addSubview(fStatusLabel);
end;
result := self;
end;
method Board.nextPlayerImageForTurn(aPlayer: String): String;
begin
var lTurnSuffix := (fTurnCount/2+1).stringValue;
inc(fTurnCount);
result := aPlayer+lTurnSuffix;
end;
method Board.playerImage(aPlayerInfo: String): UIImageView;
begin
result := new UIImageView withImage(UIImage.imageNamed(aPlayerInfo));
end;
method Board.addMarkerNotAnimated(aX: Int32; aY: Int32; aPlayerAndVersion: String);
begin
var lNewView := playerImage(aPlayerAndVersion);
var g: GridIndex; g.X := aX; g.Y := aY;
var f: CGRect;
f.origin := drawingOffsetForGridIndex(g);
f.size := lNewView.image.size;
lNewView.frame := f;
addSubview(lNewView);
fGridImages.addObject(lNewView);
end;
method Board.markGrid(aX: Int32; aY: Int32; aPlayer: String);
require
0 ≤ aX ≤ 2;
0 ≤ aY ≤ 2;
fGridInfo[aX, aY] = nil;
aPlayer in ['X','O'];
begin
var lInfo := nextPlayerImageForTurn(aPlayer);
fGridInfo[aX, aY] := lInfo;
var lNewView := playerImage(lInfo);
lNewView.alpha := 0;
var f: CGRect;
var g: GridIndex; g.X := aX; g.Y := aY;
f.origin := drawingOffsetForGridIndex(g);
f.size := lNewView.image.size;
lNewView.frame := f;
addSubview(lNewView);
fGridImages.addObject(lNewView);
UIView.animateWithDuration(0.5)
animations(method begin
lNewView.alpha := 1;
end);
end;
method Board.beginTrackingWithTouch(aTouch: not nullable UITouch) withEvent(aEvent: UIEvent): Boolean;
begin
if not acceptingTurn then exit false;
continueTrackingWithTouch(aTouch) withEvent(aEvent);
result := true;
end;
method Board.continueTrackingWithTouch(aTouch: not nullable UITouch) withEvent(aEvent: UIEvent): Boolean;
begin
var lFirst: Boolean;
if not assigned(fTentativeView) then begin
fTentativeInfo := nextPlayerImageForTurn(player);
fTentativeView := playerImage(fTentativeInfo);
fTentativeView.alpha := 0;
addSubview(fTentativeView);
lFirst := true;
end;
var lTouchLocation := aTouch.locationInView(self);
fTentativeGridIndex := gridIndexForPoint(lTouchLocation);
fTentativeOk := fGridInfo[fTentativeGridIndex.X, fTentativeGridIndex.Y] = nil;
var f: CGRect;
f.origin := drawingOffsetForGridIndex(fTentativeGridIndex);
f.size := fTentativeView.image.size;
if lFirst then
fTentativeView.frame := f;
UIView.animateWithDuration(0.1)
animations(method begin
fTentativeView.frame := f;
if fTentativeOk then
fTentativeView.alpha := 0.8
else
fTentativeView.alpha := 0.0;
end);
result := true;
end;
method Board.endTrackingWithTouch(aTouch: UITouch) withEvent(aEvent: UIEvent);
begin
if assigned(fTentativeView) then begin
continueTrackingWithTouch(aTouch) withEvent(aEvent);
if fTentativeOk then begin
fGridImages.addObject(fTentativeView);
fGridInfo[fTentativeGridIndex.X, fTentativeGridIndex.Y] := fTentativeInfo;
if assigned(&delegate) then
&delegate.board(self) playerDidSelectGridIndex(fTentativeGridIndex);
var lTempView := fTentativeView;
UIView.animateWithDuration(0.1)
animations(method begin
lTempView.alpha := 1.0;
end);
end
else begin
var lTempView := fTentativeView;
UIView.animateWithDuration(0.1)
animations(method begin
fTentativeView.alpha := 0;
end)
completion(method begin
lTempView.removeFromSuperview();
end);
end;
end;
fTentativeView := nil;
end;
method Board.gridIndexForPoint(aPoint: CGPoint): GridIndex;
begin
aPoint.x := aPoint.x-fGridOffset.x;
aPoint.y := aPoint.y-fGridOffset.y;
// := new GridIndex;
result.X := if aPoint.x < X1 then 0 else if aPoint.x < X2 then 1 else 2;
result.Y := if aPoint.y < Y1 then 0 else if aPoint.y < Y2 then 1 else 2;
end;
method Board.drawingOffsetForGridIndex(aGridIndex: GridIndex): CGPoint;
begin
{result.x := case aGridIndex.X of
0: 10;
1: X1+10;
2: X2+10;
end;
result.y := case aGridIndex.Y of
0: 10;
1: Y1+10;
2: Y2+10;
end;}
result := CGPointMake(10+110*aGridIndex.X+fGridOffset.x, 10+100*aGridIndex.Y+fGridOffset.y);
end;
method Board.makeComputerMove(aPlayer: String);
begin
var aMove:= new ComputerPlayer();
aMove.makeBestMove(aPlayer, self);
end;
method Board.isFull: Boolean;
begin
for x: Int32 := 0 to 2 do
for y: Int32 := 0 to 2 do
if not assigned(fGridInfo[x,y]) then begin
exit false;
end;
result := true;
end;
method Board.isEmpty: Boolean;
begin
for x: Int32 := 0 to 2 do
for y: Int32 := 0 to 2 do
if assigned(fGridInfo[x,y]) then begin
exit false;
end;
result := true;
end;
method Board.isGameOver: Boolean;
begin
result := isFull or assigned(markWinner); // ToDo: refactor once markWinner does more than just CALCULATE the winner
end;
method Board.playerAtCoordinates(x, y: Int32): String;
begin
result := fGridInfo[x,y]:substringToIndex(1);
end;
method Board.markWinner: String;
begin
// won't win any nobel prizes for achievements in the computer sciences, but gets the job done:
// horizontals
for x: Int32 := 0 to 2 do begin
if assigned(playerAtCoordinates(x, 0)) and
(playerAtCoordinates(x, 0) = playerAtCoordinates(x, 1)) and
(playerAtCoordinates(x, 0) = playerAtCoordinates(x, 2)) then exit playerAtCoordinates(x, 0);
end;
// verticals
for y: Int32 := 0 to 2 do begin
if assigned(playerAtCoordinates(0, y)) and
(playerAtCoordinates(0, y) = playerAtCoordinates(1, y)) and
(playerAtCoordinates(0, y) = playerAtCoordinates(2, y)) then exit playerAtCoordinates(0, y);
end;
// diagonally
if assigned(playerAtCoordinates(0, 0)) and
(playerAtCoordinates(0, 0) = playerAtCoordinates(1, 1)) and
(playerAtCoordinates(0, 0) = playerAtCoordinates(2, 2)) then exit playerAtCoordinates(0, 0);
if assigned(playerAtCoordinates(0, 2)) and
(playerAtCoordinates(0, 2) = playerAtCoordinates(1, 1)) and
(playerAtCoordinates(0, 2) = playerAtCoordinates(2, 0)) then exit playerAtCoordinates(0, 2);
exit nil;
end;
method Board.setStatus(aStatus: String);
begin
if length(fStatusLabel.text) > 0 then begin
UIView.animateWithDuration(0.1)
animations(method begin
fStatusLabel.alpha := 0;
end)
completion(method begin
fStatusLabel.text := aStatus;
if length(aStatus) > 0 then begin
UIView.animateWithDuration(0.3)
animations(method begin
fStatusLabel.alpha := 1.0;
end);
end;
end);
end
else begin
fStatusLabel.text := aStatus;
if length(aStatus) > 0 then begin
UIView.animateWithDuration(0.3)
animations(method begin
fStatusLabel.alpha := 1.0;
end);
end;
end;
end;
method Board.clear(aCompletion: block := nil; aClearAnimated: Boolean);
begin
var lTempImages := fGridImages.copy;
var lTempTentativeView := fTentativeView;
fGridImages.removeAllObjects();
for x: Int32 := 0 to 2 do
for y: Int32 := 0 to 2 do
fGridInfo[x,y] := nil;
fTurnCount := 0;
if aClearAnimated then begin
UIView.animateWithDuration(0.5)
animations(method begin
for each i in lTempImages do
i.alpha := 0.0;
if assigned(lTempTentativeView) then
lTempTentativeView.alpha := 0;
end)
completion(method begin
for each i in lTempImages do
i.removeFromSuperview();
if assigned(lTempTentativeView) then
lTempTentativeView.removeFromSuperview();
if assigned(aCompletion) then
aCompletion();
end);
end
else begin
for each i in lTempImages do
i.removeFromSuperview();
if assigned(lTempTentativeView) then
lTempTentativeView.removeFromSuperview();
if assigned(aCompletion) then
aCompletion();
end;
end;
method Board.saveToNSDictionary(aDictionary: NSMutableDictionary; aXPlayerID: String; aOPlayerID: String);
begin
if not assigned(aOPlayerID) then aOPlayerID := 'unknown';
for x: Int32 := 0 to 2 do begin
for y: Int32 := 0 to 2 do begin
var v := fGridInfo[x,y];
if length(v) > 0 then begin
var lKey := x.stringValue+'/'+y.stringValue;
var lPlayer := if v.hasPrefix('X') then aXPlayerID else aOPlayerID;
var lTokenVersion := v.substringFromIndex(1);
aDictionary.setValue(NSArray.arrayWithObjects(lPlayer, lTokenVersion, nil)) forKey(lKey);
end;
end;
end;
//NSLog('saved %@ *X: %@, O: %@)', aDictionary, aXPlayerID, aOPlayerID);
end;
method Board.loadFromNSDictionary(aDictionary: NSDictionary; aXPlayerID: String; aOPlayerID: String);
begin
clear(nil, false);
//NSLog('loading %@ *X: %@, O: %@)', aDictionary, aXPlayerID, aOPlayerID);
for x: Int32 := 0 to 2 do begin
for y: Int32 := 0 to 2 do begin
var lKey := x.stringValue+'/'+y.stringValue;
var lInfo := aDictionary.valueForKey(lKey);
if assigned(lInfo) and (lInfo.count = 2) then begin
var lPlayer := (if lInfo[0]:isEqualToString(aXPlayerID)then "X" else "O")+lInfo[1];
fGridInfo[x,y] := lPlayer;
addMarkerNotAnimated(x, y, lPlayer);
inc(fTurnCount);
end;
end;
end;
end;
method Board.getGridInfo(aX: Int32; aY: Int32): String;
require
0 ≤ aX ≤ 2;
0 ≤ aY ≤ 2;
begin
result := fGridInfo[aX, aY];
end;
end.
|
unit uFrameFreeManualActivation;
interface
uses
Winapi.Windows,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.Clipbrd,
Vcl.StdCtrls,
Vcl.ExtCtrls,
Dmitry.Controls.Base,
Dmitry.Controls.WebLink,
uInternetUtils,
uFrameWizardBase,
uConstants,
uActivationUtils,
uMemory;
type
TFrameFreeManualActivation = class(TFrameWizardBase)
LbManualActivationInfo: TLabel;
MemInfo: TMemo;
WlMail: TWebLink;
procedure WlMailClick(Sender: TObject);
private
{ Private declarations }
FProgramStarted: Boolean;
protected
function GetCanGoNext: Boolean; override;
procedure LoadLanguage; override;
public
{ Public declarations }
procedure Execute; override;
procedure SendRegistrationEmail;
procedure Init(Manager: TWizardManagerBase; FirstInitialization: Boolean); override;
function IsFinal: Boolean; override;
end;
implementation
uses
uFrameFreeActivation;
{$R *.dfm}
{ TFrameFreeManualActivation }
procedure TFrameFreeManualActivation.Execute;
begin
inherited;
if not FProgramStarted then
SendRegistrationEmail;
IsStepComplete := True;
Changed;
end;
function TFrameFreeManualActivation.GetCanGoNext: Boolean;
begin
Result := False;
end;
procedure TFrameFreeManualActivation.Init(Manager: TWizardManagerBase; FirstInitialization: Boolean);
var
Step: TFrameFreeActivation;
begin
inherited;
MemInfo.Clear;
Step := TFrameFreeActivation(Manager.GetStepByType(TFrameFreeActivation));
MemInfo.Lines.Add(L('Program code') + ': ' + TActivationManager.Instance.ApplicationCode);
MemInfo.Lines.Add(L('First name') + '(*): ' + Step.EdFirstName.Text);
MemInfo.Lines.Add(L('Last name') + '(*): ' + Step.EdLastName.Text);
MemInfo.Lines.Add(L('Phone') + ': ' + Step.EdPhone.Text);
MemInfo.Lines.Add(L('Country') + ': ' + Step.EdCountry.Text);
MemInfo.Lines.Add(L('City') + ': ' + Step.EdCity.Text);
MemInfo.Lines.Add(L('Address') + ': ' + Step.EdAddress.Text);
MemInfo.Lines.Add(L('(*) - required fields'));
end;
function TFrameFreeManualActivation.IsFinal: Boolean;
begin
Result := True;
end;
procedure TFrameFreeManualActivation.LoadLanguage;
begin
inherited;
WlMail.Text := ProgramMail;
LbManualActivationInfo.Caption := L('To manually activate the program you need to send a letter with the following information to') + ':';
end;
procedure TFrameFreeManualActivation.SendRegistrationEmail;
var
Files: TStrings;
begin
Files := TStringList.Create;
try
SendEMail(Handle, ProgramMail, '', ProductName + ': REGISTRATION CODE = ' + TActivationManager.Instance.ApplicationCode, MemInfo.Text, Files);
finally
F(Files);
end;
end;
procedure TFrameFreeManualActivation.WlMailClick(Sender: TObject);
begin
inherited;
FProgramStarted := True;
SendRegistrationEmail;
end;
end.
|
unit uGynboSyncClasses;
interface
uses SysUtils, Classes, SOAPHTTPTrans, DateUtils;
const
GC_TRANS_CREDIT = 1;
GC_TRAN_DEBIT = 2;
GC_TRAN_VOID = 3;
type
TXMLContent = class
private
FXML: String;
function GetTagValue(ATagName: String): String;
public
function GetTagInteger(ATagName: String): Integer;
function GetTagBoolean(ATagName: String): Boolean;
function GetTagDouble(ATagName: String): Double;
function GetTagString(ATagName: String): String;
function GetTagDateTime(ATagName: String): TDateTime;
property XML: String read FXML write FXML;
end;
TgbParentSync = class
protected
FHTTPReqResp: THTTPReqResp;
FURLSite: String;
FPartnerEmail: String;
FPartnerPW: String;
FIDStore: Integer;
FXMLContent: TXMLContent;
FIDResult : Integer;
FResultMessage : String;
FXMLRequest : WideString;
FSoapAction : String;
function GetWebServiceURL: String;
function GetSoapActionURL: String;
function HasExecutionError: Boolean;
function GetExecutionErrorMessage: String;
function FormatarDataXML(AData: TDateTime): String;
function ExecuteRequest: Boolean;
procedure AfterExecuteResult; virtual;
public
constructor Create;
destructor Destroy; override;
procedure Init(AHTTPReqResp: THTTPReqResp; AURLSite, AURLUser, AURLPW, APartnerEmail, APartnerPW: String; AIDStore : Integer);
property XMLContent: TXMLContent read FXMLContent write FXMLContent;
property IDResult : Integer read FIDResult write FIDResult;
property ResultMessage : String read FResultMessage write FResultMessage;
end;
TbgBonusSync = class(TgbParentSync)
private
FBonusCode: String;
FInvoiceNumber: String;
FInvoiceDate: TDateTime;
FMemberEmail: String;
FBonusValue: Currency;
FValidFrom: TDateTime;
FExpirationDate: TDateTime;
FNotes: String;
FMemberCard : String;
protected
function GetXMLGenerateRequest: WideString;
function GetXMLUseRequest: WideString;
procedure AfterExecuteResult; override;
public
property BonusCode: String read FBonusCode write FBonusCode;
property InvoiceNumber: String read FInvoiceNumber write FInvoiceNumber;
property InvoiceDate: TDateTime read FInvoiceDate write FInvoiceDate;
property MemberEmail: String read FMemberEmail write FMemberEmail;
property BonusValue: Currency read FBonusValue write FBonusValue;
property ValidFrom: TDateTime read FValidFrom write FValidFrom;
property ExpirationDate: TDateTime read FExpirationDate write FExpirationDate;
property Notes: String read FNotes write FNotes;
property MemberCard: String read FMemberCard write FMemberCard;
function Generate: Boolean;
function Use: Boolean;
function Void: Boolean;
function UnUse: Boolean;
end;
TbgGiftCardSync = class(TgbParentSync)
private
FCardNumber : String;
FCVV : String;
FExpirationDate : TDateTime;
FBalance : Currency;
FNotes : string;
FTransactionAmount : Currency;
FUseType : Integer;
procedure setTransactionAmount(const Value: Currency);
procedure setCVV(const Value: String);
protected
function GetXMLGenerateRequest: WideString;
function GetXMLUseRequest: WideString;
function GetXMLVoidRequest: WideString;
procedure AfterExecuteResult; override;
public
property CardNumber : String read FCardNumber write FCardNumber;
property CVV : String read FCVV write setCVV;
property ExpirationDate : TDateTime read FExpirationDate write FExpirationDate;
property Balance : Currency read FBalance;
property Notes : string read FNotes write FNotes;
property TransactionAmount : Currency read FTransactionAmount write setTransactionAmount;
function Generate: Boolean;
function Use: Boolean;
function Void: Boolean;
function UnUse: Boolean;
end;
implementation
{ TgbParentSync }
constructor TgbParentSync.Create;
begin
try
FXMLContent := TXMLContent.Create;
except
raise Exception.Create(self.ClassName + '.Create');
end;
end;
destructor TgbParentSync.Destroy;
begin
try
FXMLContent.Free;
inherited Destroy;
except
raise Exception.Create(self.ClassName + '.Destroy');
end;
end;
function TgbParentSync.HasExecutionError: Boolean;
begin
Result := (FXMLContent.GetTagString('faultcode') <> '');
end;
function TgbParentSync.FormatarDataXML(AData: TDateTime): String;
var
sYear, sMonth, sDay: String;
Year, Month, Day: Word;
begin
DecodeDate(AData, Year, Month, Day);
sYear := IntToStr(Year);
if Length(sYear) = 2 then
sYear := '20' + sYear;
sMonth := IntToStr(Month);
if Length(sMonth) = 1 then
sMonth := '0' + sMonth;
sDay := IntToStr(Day);
if Length(sDay) = 1 then
sDay := '0' + sDay;
Result := sYear + '-' + sMonth + '-' + sDay + 'T00:00:00';
end;
function TgbParentSync.GetExecutionErrorMessage: String;
begin
Result := FXMLContent.GetTagString('faultstring');
end;
procedure TgbParentSync.Init(AHTTPReqResp: THTTPReqResp; AURLSite, AURLUser, AURLPW, APartnerEmail,
APartnerPW: String; AIDStore : Integer);
begin
try
FHTTPReqResp := AHTTPReqResp;
FPartnerEmail := APartnerEmail;
FPartnerPW := APartnerPW;
FIDStore := AIDStore;
FURLSite := AURLSite;
FHTTPReqResp.URL := GetWebServiceURL;
FHTTPReqResp.UserName := AURLUser;
FHTTPReqResp.Password := AURLPW;
FHTTPReqResp.UseUTF8InHeader := True;
except
raise Exception.Create(self.ClassName + '.Init');
end;
end;
function TgbParentSync.ExecuteRequest: Boolean;
var
ContentStream: TStream;
ContentStringStream: TStringStream;
begin
Result := False;
ContentStream := TMemoryStream.Create;
ContentStringStream := TStringStream.Create('');
try
try
FHTTPReqResp.SoapAction := GetSoapActionURL + FSoapAction;
FHTTPReqResp.Execute(UTF8Encode(FXMLRequest), ContentStream);
ContentStringStream.CopyFrom(ContentStream, 0);
FXMLContent.XML := UTF8Decode(ContentStringStream.DataString);
AfterExecuteResult;
if HasExecutionError then
raise Exception.Create(GetExecutionErrorMessage);
Result := True;
except
on E: Exception do
raise Exception.Create(self.ClassName + '.'+FSoapAction+'. - ' + E.Message);
end;
finally
ContentStream.Free;
ContentStringStream.Free;
end;
end;
function TgbParentSync.GetSoapActionURL: String;
begin
Result := 'gynbowebservice/';
end;
function TgbParentSync.GetWebServiceURL: String;
begin
Result := '';
if FURLSite <> '' then
Result := FURLSite + 'webservice/GynboWebService.asmx?wsdl';
end;
procedure TgbParentSync.AfterExecuteResult;
begin
FIDResult := FXMLContent.GetTagInteger('idresult');
FResultMessage := FXMLContent.GetTagString('resultmessage');
end;
{ TbgBonusSync }
procedure TbgBonusSync.AfterExecuteResult;
begin
inherited;
FBonusCode := FXMLContent.GetTagString('bonuscode');
FBonusValue := FXMLContent.GetTagDouble('bonusvalue');
end;
function TbgBonusSync.Generate: Boolean;
begin
FXMLRequest := GetXMLGenerateRequest;
FSoapAction := 'GenerateBonus';
Result := ExecuteRequest;
end;
function TbgBonusSync.Use: Boolean;
begin
FXMLRequest := GetXMLUseRequest;
FSoapAction := 'UseBonus';
Result := ExecuteRequest;
end;
function TbgBonusSync.GetXMLGenerateRequest: WideString;
begin
Result := '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:gyn="gynbowebservice"> ' +
' <soap:Header/> ' +
' <soap:Body> ' +
' <gyn:GenerateBonus> ' +
' <!--Optional:--> ' +
' <gyn:PartnerEmail>'+ FPartnerEmail + '</gyn:PartnerEmail> ' +
' <!--Optional:--> ' +
' <gyn:PartnerPW>'+ FPartnerPW + '</gyn:PartnerPW> ' +
' <!--Optional:--> ' +
' <gyn:InvoiceNumber>'+ FInvoiceNumber +'</gyn:InvoiceNumber> ' +
' <gyn:InvoiceDate>'+ FormatarDataXML(FInvoiceDate) +'</gyn:InvoiceDate> ' +
' <gyn:IDStore>' + IntToStr(FIDStore) + '</gyn:IDStore> ' +
' <!--Optional:--> ' +
' <gyn:MemberEmail>' + FMemberEmail + '</gyn:MemberEmail> ' +
' <gyn:BonusValue>' + FloatToStr(FBonusValue) + '</gyn:BonusValue> ' +
' <gyn:ValidFrom>' + FormatarDataXML(FValidFrom) + '</gyn:ValidFrom> ' +
' <gyn:ExpirationDate>' + FormatarDataXML(FExpirationDate) + '</gyn:ExpirationDate> ' +
' <!--Optional:--> ' +
' <gyn:Notes>' + FNotes + '</gyn:Notes> ' +
' </gyn:GenerateBonus> ' +
' </soap:Body> ' +
'</soap:Envelope> ';
end;
function TbgBonusSync.GetXMLUseRequest: WideString;
begin
Result := '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:gyn="gynbowebservice"> ' +
' <soap:Header/> ' +
' <soap:Body> ' +
' <gyn:UseBonus> ' +
' <!--Optional:--> ' +
' <gyn:PartnerEmail>' + FPartnerEmail + '</gyn:PartnerEmail> ' +
' <!--Optional:--> ' +
' <gyn:PartnerPW>' + FPartnerPW + '</gyn:PartnerPW> ' +
' <gyn:IDStore>' + IntToStr(FIDStore) + '</gyn:IDStore> ' +
' <!--Optional:--> ' +
' <gyn:BonusCode>' + FBonusCode + '</gyn:BonusCode> ' +
' <!--Optional:--> ' +
' <gyn:Notes>' + FNotes + '</gyn:Notes> ' +
' </gyn:UseBonus> ' +
' </soap:Body> ' +
'</soap:Envelope> ';
end;
function TbgBonusSync.UnUse: Boolean;
begin
Result := False;
end;
function TbgBonusSync.Void: Boolean;
begin
Result := False;
end;
{ TbgGiftCardSync }
function TbgGiftCardSync.Generate: Boolean;
begin
FXMLRequest := GetXMLGenerateRequest;
FSoapAction := 'GenerateGiftCard';
Result := ExecuteRequest;
end;
function TbgGiftCardSync.Use: Boolean;
begin
FXMLRequest := GetXMLUseRequest;
FSoapAction := 'UseGiftCard';
Result := ExecuteRequest;
end;
function TbgGiftCardSync.Void: Boolean;
begin
FXMLRequest := GetXMLVoidRequest;
FSoapAction := 'VoidGiftCard';
Result := ExecuteRequest;
end;
function TbgGiftCardSync.GetXMLGenerateRequest: WideString;
begin
Result := '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:gyn="gynbowebservice"> ' +
' <soap:Header/> ' +
' <soap:Body> ' +
' <gyn:GenerateGiftCard> ' +
' <!--Optional:--> ' +
' <gyn:PartnerEmail>'+ FPartnerEmail + '</gyn:PartnerEmail> ' +
' <!--Optional:--> ' +
' <gyn:PartnerPW>'+ FPartnerPW + '</gyn:PartnerPW> ' +
' <gyn:IDStore>' + IntToStr(FIDStore) + '</gyn:IDStore> ' +
' <!--Optional:--> ' +
' <gyn:CardNumber>'+ FCardNumber +'</gyn:CardNumber> ' +
' <gyn:CVV>'+ FCVV +'</gyn:CVV> ' +
' <gyn:ExpirationDate>'+ FormatarDataXML(FExpirationDate) +'</gyn:ExpirationDate> ' +
' <gyn:Balance>' + FloatToStr(FTransactionAmount) + '</gyn:Balance> ' +
' <!--Optional:--> ' +
' <gyn:Notes>' + FNotes + '</gyn:Notes> ' +
' </gyn:GenerateGiftCard> ' +
' </soap:Body> ' +
'</soap:Envelope> ';
end;
function TbgGiftCardSync.GetXMLUseRequest: WideString;
begin
Result := '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:gyn="gynbowebservice"> ' +
' <soap:Header/> ' +
' <soap:Body> ' +
' <gyn:UseGiftCard> ' +
' <!--Optional:--> ' +
' <gyn:PartnerEmail>'+ FPartnerEmail + '</gyn:PartnerEmail> ' +
' <!--Optional:--> ' +
' <gyn:PartnerPW>'+ FPartnerPW + '</gyn:PartnerPW> ' +
' <gyn:IDStore>' + IntToStr(FIDStore) + '</gyn:IDStore> ' +
' <!--Optional:--> ' +
' <gyn:CardNumber>'+ FCardNumber +'</gyn:CardNumber> ' +
' <gyn:CVV>'+ FCVV +'</gyn:CVV> ' +
' <gyn:Amount>' + FloatToStr(FTransactionAmount) + '</gyn:Amount> ' +
' <gyn:UseType>' + IntToStr(FUseType) + '</gyn:UseType> ' +
' <!--Optional:--> ' +
' <gyn:Notes>' + FNotes + '</gyn:Notes> ' +
' </gyn:UseGiftCard> ' +
' </soap:Body> ' +
'</soap:Envelope> ';
end;
function TbgGiftCardSync.GetXMLVoidRequest: WideString;
begin
Result := '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:gyn="gynbowebservice"> ' +
' <soap:Header/> ' +
' <soap:Body> ' +
' <gyn:VoidGiftCard> ' +
' <!--Optional:--> ' +
' <gyn:PartnerEmail>'+ FPartnerEmail + '</gyn:PartnerEmail> ' +
' <!--Optional:--> ' +
' <gyn:PartnerPW>'+ FPartnerPW + '</gyn:PartnerPW> ' +
' <gyn:IDStore>' + IntToStr(FIDStore) + '</gyn:IDStore> ' +
' <!--Optional:--> ' +
' <gyn:CardNumber>'+ FCardNumber +'</gyn:CardNumber> ' +
' <gyn:CVV>'+ FCVV +'</gyn:CVV> ' +
' <!--Optional:--> ' +
' <gyn:Notes>' + FNotes + '</gyn:Notes> ' +
' </gyn:VoidGiftCard> ' +
' </soap:Body> ' +
'</soap:Envelope> ';
end;
procedure TbgGiftCardSync.setCVV(const Value: String);
begin
FCVV := Value;
if FCVV = '' then
FCVV := '0';
end;
procedure TbgGiftCardSync.setTransactionAmount(const Value: Currency);
begin
FTransactionAmount := Value;
if FTransactionAmount > 0 then
FUseType := GC_TRANS_CREDIT
else
FUseType := GC_TRAN_DEBIT;
end;
procedure TbgGiftCardSync.AfterExecuteResult;
begin
inherited;
FBalance := FXMLContent.GetTagDouble('balance');
end;
function TbgGiftCardSync.UnUse: Boolean;
begin
Result := False;
end;
{ TXMLContent }
function TXMLContent.GetTagBoolean(ATagName: String): Boolean;
begin
Result := StrToBool(GetTagValue(ATagName));
end;
function TXMLContent.GetTagDateTime(ATagName: String): TDateTime;
var
sValue: String;
Year, Month, Day, Hour, Minute, Second, MilliSecond: Word;
begin
sValue := GetTagValue(ATagName);
Year := StrToInt(Copy(sValue, 1, 4));
Month := StrToInt(Copy(sValue, 6, 2));
Day := StrToInt(Copy(sValue, 9, 2));
Hour := StrToInt(Copy(sValue, 12, 2));
Minute := StrToInt(Copy(sValue, 15, 2));
Second := StrToInt(Copy(sValue, 18, 2));
MilliSecond := 0;
Result := EncodeDateTime(Year, Month, Day, Hour, Minute, Second, MilliSecond);
//Result := Now;
end;
function TXMLContent.GetTagDouble(ATagName: String): Double;
var
sValue: String;
begin
sValue := GetTagValue(ATagName);
Result := StrToFloat(sValue);
end;
function TXMLContent.GetTagInteger(ATagName: String): Integer;
var
sTagValue: String;
begin
sTagValue := GetTagValue(ATagName);
if sTagValue = '' then
Result := -1
else
Result := StrToInt(sTagValue);
end;
function TXMLContent.GetTagString(ATagName: String): String;
begin
Result := GetTagValue(ATagName);
end;
function TXMLContent.GetTagValue(ATagName: String): String;
var
iBegin, iEnd, iSize: Integer;
begin
iBegin := Pos('<' + ATagName + '>', XML);
iEnd := Pos('</' + ATagName + '>', XML);
iSize := Length('<' + ATagName + '>');
Result := Copy(XML, iBegin + iSize, iEnd - (iBegin + iSize));
end;
end.
|
unit TestCalculator;
interface
uses
SampleCalculator
, DelphiSpec.StepDefinitions;
type
TCalculatorTestContext = class(TStepDefinitions)
private
FCalc: TCalculator;
public
procedure SetUp; override;
procedure TearDown; override;
end;
implementation
uses
System.SysUtils
, DelphiSpec.Core
, DelphiSpec.Assert
, DelphiSpec.Parser
, DelphiSpec.Attributes;
{$I TestCalculator.inc}
{ TCalculatorTest }
procedure TCalculatorTest.Given_I_have_entered_value_in_calculator(
const value: Integer);
begin
FCalc.Push(value);
end;
procedure TCalculatorTest.Then_the_result_should_be_value_on_the_screen(
const value: Integer);
begin
Assert.AreEqual(Int64(Value), FCalc.Value,
'Incorrect result on calculator screen');
end;
procedure TCalculatorTest.When_I_press_Add;
begin
FCalc.Add;
end;
procedure TCalculatorTest.When_I_press_mul;
begin
FCalc.Mul;
end;
{ TCalculatorTestContext }
procedure TCalculatorTestContext.SetUp;
begin
FCalc := TCalculator.Create;
end;
procedure TCalculatorTestContext.TearDown;
begin
FCalc.Free;
end;
initialization
RegisterCalculatorTest;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, IdBaseComponent, IdComponent, IdTCPConnection,
IdTCPClient, IdFTP, ComCtrls, IdExplicitTLSClientServerBase;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Edit1: TEdit;
Memo1: TMemo;
Label1: TLabel;
OpenDialog1: TOpenDialog;
IdFTP1: TIdFTP;
ProgressBar1: TProgressBar;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure IdFTP1Status(ASender: TObject; const AStatus: TIdStatus;
const AStatusText: string);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
function MsgBox(Msg: string; iValue: integer): integer;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses IdFTPList, IdFTPCommon;
{$R *.dfm}
function TForm1.MsgBox(Msg: string; iValue: integer): integer;
begin
Result := MessageBox(application.Handle, pChar(Msg), '系统信息', iValue + MB_APPLMODAL);
end;
//设置文件修改时间
Function SetFileDateTime(FileName : String; NewDateTime : TDateTime): Boolean;
var FileHandle: Integer;
FileTime: TFileTime;
LFT: TFileTime;
LST: TSystemTime;
begin
Result := False;
try
DecodeDate(NewDateTime, LST.wYear, LST.wMonth, LST.wDay);
DecodeTime(NewDateTime, LST.wHour, LST.wMinute, LST.wSecond, LST.wMilliSeconds);
IF SystemTimeToFileTime(LST, LFT) Then
begin
IF LocalFileTimeToFileTime(LFT, FileTime) Then
begin
FileHandle := FileOpen(FileName, fmOpenReadWrite or fmShareExclusive);
IF SetFileTime(FileHandle, NIL, NIL, @FileTime) Then Result := True;
end;
end;
finally
FileClose(FileHandle);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
tr: Tstrings;
begin //连接
tr := TStringlist.Create;
try
try
idftp1.Passive := True;
idftp1.Host := '192.180.0.98'; //FTP服务器地址
idftp1.Username := 'guest'; //FTP服务器用户名
idftp1.Password := ''; //FTP服务器密码
idftp1.Connect(); //连接到ftp
//idftp1.ChangeDir('client'); //进入到client子目录
//idftp1.ChangeDir('..'); //回到上一级目录
Edit1.Text := idftp1.RetrieveCurrentDir; //得到初始目录
idftp1.List(tr, '', false); //得到client目录下所有文件列表
Memo1.Lines.Assign(tr);
except
on E: Exception do
begin
MessageBox(Self.Handle, Pchar('系统提示您:' + e.Message), Pchar(self.Caption), MB_OK + MB_ICONERROR);
// memo2.Lines.Add('Exception');
end;
end;
finally
tr.Free;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
Dir_List: TStringList;
i: integer;
new_file_datetime:TDateTime;
begin //下载
// if not IdFTP1.Connected then IdFTP1.Connected;
//if not IdFTP1.Connected then idftp1.Connect(True);
//Dir_List := TStringList.Create;
// IdFTP1.Connect();
IdFTP1.TransferType := ftASCII; //ftBinary; //指定为二进制文件 或文本文件ftASCII
//IdFTP1.List(Dir_List,'',true);
// idftp1.List(Dir_List, '', true);
// Memo1.Clear;
//memo1.Lines.Assign(Dir_List);
IDFTP1.TransferType := ftBinary; //更改传输类型
ProgressBar1.Min := 0;
ProgressBar1.Max := memo1.Lines.Count;
// Memo1.Lines
for i := 0 to memo1.Lines.Count - 1 do
begin
// memo2.Lines.Add(IdFTP1.DirectoryListing.Items[i].FileName+' ('+IntToStr(IdFTP1.DirectoryListing.Items[i].Size)+' Byte) Start Download....');
{ try
IdFTP1.Get(IdFTP1.DirectoryListing.Items[i].FileName,'d:\FTPtest\'+IdFTP1.DirectoryListing.Items[i].FileName,true,True); //下载到本地,并为覆盖,且支持断点续传
except
end; }
// IdFTP1.Get(IdFTP1.DirectoryListing.Items[i].FileName, 'd:\FTPtest\' + IdFTP1.DirectoryListing.Items[i].FileName, true);
//ShowMessage(DateTimeToStr(IdFTP1.DirectoryListing.Items[i].ModifiedDate));
new_file_datetime:= idFTP1.FileDate(memo1.Lines[i]);
IdFTP1.Get(memo1.Lines[i], 'd:\FTPtest\' + memo1.Lines[i], true);
SetFileDateTime('d:\FTPtest\' + memo1.Lines[i],new_file_datetime);
// ShowMessage(IdFTP1.DirectoryListing.Items[i].FileName);
{ 原处理过程,带提示可选
if FileExists('d:\FTPtest\' + IdFTP1.DirectoryListing.Items[i].FileName) then
case MsgBox(IdFTP1.DirectoryListing.Items[i].FileName + '文件已经存在,要续传吗?'#13#10'是——续传'#10#13'否——覆盖'#13#10'取消——取消操作', MB_YESNOCANCEL + MB_ICONINFORMATION) of
IDYES: begin
//参数说明: 源文件,目标文件,是否覆盖,是否触发异常(True为不触发)。
IdFTP1.Get(IdFTP1.DirectoryListing.Items[i].FileName, 'd:\FTPtest\' + IdFTP1.DirectoryListing.Items[i].FileName, False, True);
end;
IDNO: begin
IdFTP1.Get(IdFTP1.DirectoryListing.Items[i].FileName, 'd:\FTPtest\' + IdFTP1.DirectoryListing.Items[i].FileName, true);
end;
IDCANCEL:
begin
end;
end
else
IdFTP1.Get(IdFTP1.DirectoryListing.Items[i].FileName, 'd:\FTPtest\' + IdFTP1.DirectoryListing.Items[i].FileName);
end;
原处理过程结束}
ProgressBar1.Position := i + 1;
end;
MessageBox(Self.Handle, Pchar('系统提示您:本次操作完毕。'), Pchar(self.Caption), MB_OK + MB_ICONINFORMATION);
ProgressBar1.Position := 0;
end;
procedure TForm1.Button3Click(Sender: TObject);
var
fi: string;
begin //上传
if OpenDialog1.Execute then
begin
fi := OpenDialog1.FileName;
IdFTP1.Put(fi, ExtractFileName(fi)); //上传,
end;
end;
procedure TForm1.IdFTP1Status(ASender: TObject; const AStatus: TIdStatus;
const AStatusText: string);
begin
// Memo2.Clear;
// memo2.Lines.Add(AStatusText)
end;
procedure TForm1.FormShow(Sender: TObject);
var
tr: Tstrings;
begin //连接
{ tr := TStringlist.Create;
try
try
idftp1.Passive := True;
idftp1.Host := '192.180.0.98'; //FTP服务器地址
idftp1.Username := 'guest'; //FTP服务器用户名
idftp1.Password := ''; //FTP服务器密码
idftp1.Connect(); //连接到ftp
//idftp1.ChangeDir('client'); //进入到client子目录
//idftp1.ChangeDir('..'); //回到上一级目录
Edit1.Text := idftp1.RetrieveCurrentDir; //得到初始目录
idftp1.List(tr, '', true); //得到client目录下所有文件列表
Memo1.Lines.Assign(tr);
// memo1.Lines.Assign(Dir_List);
except
on E: Exception do
begin
MessageBox(Self.Handle, Pchar('系统提示您:' + e.Message), Pchar(self.Caption), MB_OK + MB_ICONERROR);
// memo2.Lines.Add('Exception');
end;
end;
finally
tr.Free;
end; }
end;
end.
|
unit Constants;
interface
uses Messages;
const
LATIN_WORD_LETTERS = ['-', 'A'..'Z', 'a'..'z'];
ROME_DIGITS = ['I', 'i', 'V', 'v', 'X', 'x'];
CYRILLIC_WORD_LETTERS = ['À'..'ß','à'..'ÿ'];
STR_FILTERNAME_DIRECTSOUND = 'DirectSound';
STR_EXTENTIONS = '*.AVI;*.mkv;*.mp4;*.MPG;*.MPEG;*.ASF';
DIC_SEPARATOR = '_____';
DIR_DIC = 'dicts\';
FILENAME_MUELLER_DICT = 'mueller-base';
FILENAME_FREQ_DICT = 'freq';
FILENAME_POST_DICT = 'posts';
FILENAME_PREF_DICT = 'prefs';
FILENAME_ALIAS_DICT = 'alias';
FILENAME_ADDITIONAL_DICT = 'additional';
FILENAME_TRANSLATED = 'translated.txt';
FILENAME_SETTINGS = 'settings.ini';
INI_VOICE_SECTION = 'voice';
INI_VOICE_NAME = 'name';
WORD_COLORS: array[0..3] of String =
('green', 'orange', 'blue', 'red');
ALERT_PREFIX_GOTO = 'goto:';
ALERT_PREFIX_SPEAK = 'speak:';
ALERT_PREFIX_FIND = 'find:';
ALERT_PREFIX_NOTIFICATION = 'notification:';
ALERT_PREFIX_EVENT = 'event:';
EVENT_PLAY = 'play';
EVENT_PAUSE = 'pause';
EVENT_SEEK = 'seek';
EVENT_VOLUME = 'volume';
EVENT_SLIDERCHANGE = 'sliderchange';
NOTIFICATION_PHRASE = 'phrase';
NOTIFICATION_MAIN = 'main';
NOTIFICATION_UI = 'UI';
LINK_GOOGLE_MASK = 'http://translate.google.ru/#en|ru|%s';
LINK_URBANDIC_MASK = 'http://www.urbandictionary.com/define.php?term=%s';
LINK_WIKTIONARY_MASK = 'http://en.wiktionary.org/wiki/%s';
LINK_WIKIPEDIA_MASK = 'http://en.wikipedia.org/wiki/%s';
COLOR_VIDEOWINDOW_BACKGROUND = $111111;
MAX_TRANSLATE_SYMBOLS = 300;
VIDEO_UNITS_IN_ONE_MILLISECOND = 10000;
SUBTITLE_SEEK_PREFIX_TIME = VIDEO_UNITS_IN_ONE_MILLISECOND * 1000 div 5; // 1/5 of second
DELIMITER_ALIAS = '=';
DELIMITER_DIC_REFERENCE1 = ' îò ';
DELIMITER_DIC_REFERENCE2 = ' = ';
DELIMITER_DIC_REFERENCE3 = ' ñì. ';
TIME_DIFF_REWIND = 5000; //ms
TIME_DIFF_FORWARD = 5000; //ms
TIME_WAIT_UNTIL_LOAD = 20; // 1/2 sec
FN_NAME_TRANSLATE = 'translate';
FN_NAME_FINDWORD = 'findWord';
FN_GET_TRANSLATOR_OBJECT = 'GetTranslatorObject';
STR_FILTERNAME_VOBSUB = 'VobSub';
WM_HOOKKEYDOWN = WM_USER + $10;
WM_HOOKKEYUP = WM_USER + $11;
UI_SLIDER_MAX = 2000;
DS_ENGLISH_STREAM_NUM = 1;
CAPTION_MSG_RECEIVER_WINDOW = 'NOG MESSAGE RECEIVER WINDOW 7445253';
implementation
end.
|
unit LrStreamable;
interface
uses
SysUtils, Classes;
type
TLrStreamable = class(TComponent)
protected
procedure ReadError(Reader: TReader; const Message: string;
var Handled: Boolean);
public
function SaveToText: string;
procedure LoadBinaryFromStream(inStream: TStream);
procedure LoadFromFile(const inFilename: string); virtual;
procedure LoadFromStream(inStream: TStream);
procedure LoadFromText(const inText: string);
procedure SaveBinaryToStream(inStream: TStream);
procedure SaveToFile(const inFilename: string); virtual;
procedure SaveToStream(inStream: TStream);
end;
implementation
uses
LrVclUtils;
{ TLrStreamable }
procedure TLrStreamable.SaveToStream(inStream: TStream);
begin
LrSaveComponentToStream(Self, inStream);
end;
function TLrStreamable.SaveToText: string;
begin
Result := LrSaveComponentToString(Self);
end;
procedure TLrStreamable.SaveToFile(const inFilename: string);
begin
LrSaveComponentToFile(Self, inFilename);
end;
procedure TLrStreamable.ReadError(Reader: TReader; const Message: string;
var Handled: Boolean);
begin
Handled := true;
end;
procedure TLrStreamable.LoadFromStream(inStream: TStream);
begin
LrLoadComponentFromStream(Self, inStream, ReadError);
end;
procedure TLrStreamable.LoadFromText(const inText: string);
begin
LrLoadComponentFromString(inText, Self, ReadError);
end;
procedure TLrStreamable.LoadFromFile(const inFilename: string);
begin
LrLoadComponentFromFile(Self, inFilename, ReadError);
end;
procedure TLrStreamable.SaveBinaryToStream(inStream: TStream);
var
ms: TMemoryStream;
sz: Int64;
begin
ms := TMemoryStream.Create;
try
ms.WriteComponent(Self);
ms.Position := 0;
with inStream do
begin
sz := ms.Size;
Write(sz, 8);
CopyFrom(ms, sz);
end;
finally
ms.Free;
end;
end;
procedure TLrStreamable.LoadBinaryFromStream(inStream: TStream);
var
ms: TMemoryStream;
sz: Int64;
begin
ms := TMemoryStream.Create;
try
inStream.Read(sz, 8);
ms.CopyFrom(inStream, sz);
ms.Position := 0;
ms.ReadComponent(Self);
finally
ms.Free;
end;
end;
end.
|
unit ImplicitConvertOpTest;
interface
uses
DUnitX.TestFramework,
uIntX;
type
[TestFixture]
TImplicitConvertOpTest = class(TObject)
public
[Test]
procedure ConvertAllExceptInt64();
[Test]
procedure ConvertInt64();
end;
implementation
[Test]
procedure TImplicitConvertOpTest.ConvertAllExceptInt64();
var
int1: TIntX;
begin
int1 := Integer(0);
Assert.IsTrue(int1 = 0);
int1 := UInt32(0);
Assert.IsTrue(int1 = 0);
int1 := Byte(0);
Assert.IsTrue(int1 = 0);
int1 := ShortInt(0);
Assert.IsTrue(int1 = 0);
int1 := ShortInt(0);
Assert.IsTrue(int1 = 0);
int1 := Word(0);
Assert.IsTrue(int1 = 0);
end;
[Test]
procedure TImplicitConvertOpTest.ConvertInt64();
var
int1: TIntX;
begin
int1 := Int64(0);
Assert.IsTrue(int1 = 0);
int1 := UInt64(0);
Assert.IsTrue(int1 = 0);
int1 := -123123123123;
Assert.IsTrue(int1 = -123123123123);
end;
initialization
TDUnitX.RegisterTestFixture(TImplicitConvertOpTest);
end.
|
unit rtti_idebinder_uDataBinder;
interface
uses
Classes, SysUtils, Controls,
rtti_broker_iBroker, rtti_idebinder_uDataSlots, rtti_idebinder_iBindings;
type
{ TRBDataBinder }
TRBDataBinder = class(TInterfacedObject, IRBDataBinder)
private
fDataSlots: TDataSlots;
protected
// IRBDataBinder
procedure Bind(AContainer: TWinControl; const AData: IRBData; const ADataQuery: IRBDataQuery);
procedure DataChange;
function GetData: IRBData;
procedure SetData(AValue: IRBData);
property AData: IRBData read GetData write SetData;
public
destructor Destroy; override;
end;
implementation
{ TRBDataBinder }
destructor TRBDataBinder.Destroy;
begin
FreeAndNil(fDataSlots);
inherited Destroy;
end;
procedure TRBDataBinder.Bind(AContainer: TWinControl; const AData: IRBData;
const ADataQuery: IRBDataQuery);
begin
FreeAndNil(fDataSlots);
fDataSlots := TDataSlots.Create;
fDataSlots.Bind(AContainer, AData, ADataQuery);
end;
procedure TRBDataBinder.DataChange;
begin
fDataSlots.DataChange;
end;
function TRBDataBinder.GetData: IRBData;
begin
Result := fDataSlots.Data;
end;
procedure TRBDataBinder.SetData(AValue: IRBData);
begin
fDataSlots.Data := AValue;
end;
end.
|
unit ScrollListBox;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, ComCtrls, StdCtrls;
type
THScrollListBox = class(TListBox)
private
MaxExtent: integer; { maximum length of the strings in the listbox (in pixel) }
function GetStringExtent( s: string ): integer;
protected
public
constructor Create( AOwner: TComponent ); override;
function InsertString(Index:integer; s:string; Data:TObject):integer;
function AddString(s:string; Data:TObject):integer;
procedure DeleteString(i:integer); override;
procedure ClearList;
procedure AdjustWidth;
published
end;
procedure Register;
implementation
constructor THScrollListBox.Create( AOwner: TComponent );
begin
inherited Create( AOwner );
MaxExtent := 0;
end;
function THScrollListBox.GetStringExtent( s: string ): integer;
var
dwExtent: DWORD;
hDCListBox: HDC;
hFontOld, hFontNew: HFONT;
tm: TTextMetric;
Size: TSize;
begin
hDCListBox := GetDC( Handle );
hFontNew := SendMessage( Handle, WM_GETFONT, 0, 0 );
hFontOld := SelectObject( hDCListBox, hFontNew );
GetTextMetrics( hDCListBox, tm );
{ the following two lines should be modified for Delphi 1.0: call GetTextExtent }
GetTextExtentPoint32( hDCListBox, PChar(s), Length(s), Size );
dwExtent := Size.cx + tm.tmAveCharWidth;
SelectObject( hDCListBox, hFontOld );
ReleaseDC( Handle, hDCListBox );
GetStringExtent := LOWORD( dwExtent );
end;
function THScrollListBox.InsertString(Index:integer; s:string; Data:TObject):integer;
var
StrExtent: integer;
begin
StrExtent := GetStringExtent( s );
if StrExtent > MaxExtent then
begin
MaxExtent := StrExtent;
SendMessage( Handle, LB_SETHORIZONTALEXTENT, MaxExtent, 0 );
end;
{ adds the string to the listbox }
Items.InsertObject(Index, s, Data);
result:=Index;
end;
function THScrollListBox.AddString(s:string; Data:TObject):integer;
begin
result:=InsertString(Items.Count, s, Data);
end;
procedure THScrollListBox.DeleteString(i:integer);
begin
Items.Delete(i);
AdjustWidth;
end;
procedure THScrollListBox.ClearList;
begin
MaxExtent := 0;
SendMessage( Handle, LB_SETHORIZONTALEXTENT, 0, 0 );
{ scrolls the listbox to the left }
SendMessage( Handle, WM_HSCROLL, SB_TOP, 0 );
{ clears the listbox }
Items.Clear;
AdjustWidth;
end;
procedure THScrollListBox.AdjustWidth;
var
i :integer;
StrExtent :integer;
begin
SendMessage( Handle, WM_HSCROLL, SB_TOP, 0 );
MaxExtent:=0;
i:=0;
while (i<Items.Count) do begin
StrExtent:=GetStringExtent(Items[i]);
if (StrExtent>MaxExtent) then
MaxExtent := StrExtent;
inc(i);
end;
SendMessage( Handle, LB_SETHORIZONTALEXTENT, MaxExtent, 0 );
end;
procedure Register;
begin
RegisterComponents('ConTEXT Components', [THScrollListBox]);
end;
end.
|
unit o_BinConverter;
interface
uses
Classes, SysUtils;
function BinToHexString(aStream: TStream): WideString;
function BinFileToHexString(aFullFilename: string): WideString;
procedure HexStringToBin(const aHex: string; aStream: TStream);
procedure HexStringToFile(aHex, aFullFilename: string);
implementation
function BinToHexString(aStream: TStream): WideString;
var
nChars: Integer;
LStr1, LStr2: Widestring;
begin
aStream.Position := 0;
nChars := astream.Size div SizeOf(LStr1[1]);
SetLength(LStr1, nChars);
if nChars > 0 then
astream.ReadBuffer(LStr1[1], nChars * SizeOf(LStr1[1]));
SetLength(LStr2, Length(LStr1) * 4);
BinToHex(LStr1[1], PWideChar(LStr2), Length(LStr1) * SizeOf(Char));
Result := LStr2;
end;
function BinFileToHexString(aFullFilename: string): WideString;
var
m: TMemoryStream;
begin
m := TMemoryStream.Create;
try
m.LoadFromFile(aFullFileName);
Result := BinToHexString(m);
finally
FreeAndNil(m);
end;
end;
procedure HexStringToBin(const aHex: string; aStream: TStream);
var
LStr1, LStr2: WideString;
l: Integer;
begin
LStr1 := aHex;
SetLength(LStr2, Length(LStr1) div 4);
HexToBin(PWideChar(LStr1), LStr2[1], Length(LStr1) div SizeOf(Char));
aStream.Position := 0;
l := Length(lstr2) * SizeOf(WideChar);
aStream.Write(lstr2[1], l);
end;
procedure HexStringToFile(aHex, aFullFilename: string);
var
m: TMemoryStream;
begin
m := TMemoryStream.Create;
try
HexStringToBin(aHex, m);
m.Position := 0;
m.SaveToFile(aFullFileName);
finally
FreeAndNil(m);
end;
end;
end.
|
unit u_ast_expression_blocks;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
u_ast_blocks,
u_tokens;
type
TMashASTB_Expression = class(TMashASTBlock)
public
tokens: TList;
ast: TObject; //TMashASTExpression
constructor Create;
destructor Destroy; override;
end;
TMashASTP_Operator = class(TMashASTBlock)
public
Op: TMashToken;
constructor Create(_Op: TMashToken);
end;
TMashASTE_Operation = class(TMashASTBlock)
public
Op: TMashASTP_Operator;
A: TMashASTBlock;
constructor Create(_Op: TMashASTP_Operator; _A: TMashASTBlock);
end;
TMashASTE_OperationLR = class(TMashASTBlock)
public
Op: TMashASTP_Operator;
L: TMashASTBlock;
R: TMashASTBlock;
constructor Create(_Op: TMashASTP_Operator; _L, _R: TMashASTBlock);
end;
TMashASTP_SimpleObject = class(TMashASTBlock)
public
Obj: TMashToken;
constructor Create(_Obj: TMashToken);
end;
TMashASTP_Reference = class(TMashASTBlock)
public
ObjPath: TList;
constructor Create;
destructor Destroy; override;
end;
TMashASTP_IndexedObject = class(TMashASTBlock)
public
Obj: TMashASTBlock;
Indexes: TList;
constructor Create(_Obj: TMashASTBlock);
destructor Destroy; override;
end;
TMashASTP_Enum = class(TMashASTBlock)
public
Objects: TList;
constructor Create;
destructor Destroy; override;
end;
TMashASTP_Call = class(TMashASTBlock)
public
Obj: TMashASTBlock;
Args: TMashASTP_Enum;
constructor Create(_Obj: TMashASTBlock; _Args: TMashASTP_Enum);
end;
implementation
uses
u_ast_expression;
constructor TMashASTB_Expression.Create;
begin
inherited Create(btExpression);
self.tokens := TList.Create;
self.ast := TMashASTExpression.Create(self.tokens);
end;
destructor TMashASTB_Expression.Destroy;
begin
FreeAndNil(self.tokens);
FreeAndNil(self.ast);
inherited;
end;
constructor TMashASTE_Operation.Create(_Op: TMashASTP_Operator; _A: TMashASTBlock);
begin
inherited Create(btEOperation);
self.Op := _Op;
self.A := _A;
end;
constructor TMashASTE_OperationLR.Create(_Op: TMashASTP_Operator; _L, _R: TMashASTBlock);
begin
inherited Create(btEOperationLR);
self.Op := _Op;
self.L := _L;
self.R := _R;
end;
constructor TMashASTP_SimpleObject.Create(_Obj: TMashToken);
begin
inherited Create(btPSimpleObject);
self.Obj := _Obj;
end;
constructor TMashASTP_Reference.Create;
begin
inherited Create(btPReference);
self.ObjPath := TList.Create;
end;
destructor TMashASTP_Reference.Destroy;
begin
FreeAndNil(self.ObjPath);
inherited;
end;
constructor TMashASTP_IndexedObject.Create(_Obj: TMashASTBlock);
begin
inherited Create(btPIndexedObject);
self.Obj := _Obj;
self.Indexes := TList.Create;
end;
destructor TMashASTP_IndexedObject.Destroy;
begin
FreeAndNil(self.Indexes);
inherited;
end;
constructor TMashASTP_Call.Create(_Obj: TMashASTBlock; _Args: TMashASTP_Enum);
begin
inherited Create(btPCall);
self.Obj := _Obj;
self.Args := _Args;
end;
constructor TMashASTP_Enum.Create;
begin
inherited Create(btPEnum);
self.Objects := TList.Create;
end;
destructor TMashASTP_Enum.Destroy;
begin
FreeAndNil(self.Objects);
inherited;
end;
constructor TMashASTP_Operator.Create(_Op: TMashToken);
begin
inherited Create(btPOperator);
self.Op := _Op;
end;
end.
|
{******************************************************************************}
{* frxEditMvxParams.pas *}
{* This module is part of Internal Project but is released under *}
{* the MIT License: http://www.opensource.org/licenses/mit-license.php *}
{* Copyright (c) 2006 by Jaimy Azle *}
{* All rights reserved. *}
{******************************************************************************}
{* Desc: *}
{******************************************************************************}
unit frxEditMvxParams;
interface
{$I frx.inc}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, StdCtrls, Buttons, DB, frxCustomDB, frxCtrls, ExtCtrls,
frxMvxComponents
{$IFDEF Delphi6}
, Variants
{$ENDIF};
type
TfrxMvxParamsEditorForm = class(TForm)
ParamsLV: TListView;
TypeCB: TComboBox;
ValueE: TEdit;
OkB: TButton;
CancelB: TButton;
ButtonPanel: TPanel;
ExpressionB: TSpeedButton;
procedure ParamsLVSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure FormShow(Sender: TObject);
procedure ParamsLVMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure OkBClick(Sender: TObject);
procedure FormHide(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ValueEButtonClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
FParams: TfrxMvxParams;
public
property Params: TfrxMvxParams read FParams write FParams;
end;
implementation
{$R *.DFM}
uses frxClass, frxRes;
{ TfrxParamEditorForm }
procedure TfrxMvxParamsEditorForm.FormShow(Sender: TObject);
var
i: Integer;
t: TFieldType;
Item: TListItem;
begin
for i := 0 to Params.Count - 1 do
begin
Item := ParamsLV.Items.Add;
Item.Caption := Params[i].Name;
Item.SubItems.Add(FieldTypeNames[Params[i].DataType]);
Item.SubItems.Add(Params[i].Expression);
end;
for t := Low(TFieldType) to High(TFieldType) do
TypeCB.Items.Add(FieldTypeNames[t]);
ParamsLV.Selected := ParamsLV.Items[0];
ValueE.Height := TypeCB.Height;
ButtonPanel.Height := TypeCB.Height - 2;
ExpressionB.Height := TypeCB.Height - 2;
end;
procedure TfrxMvxParamsEditorForm.FormHide(Sender: TObject);
var
i: Integer;
t: TFieldType;
Item: TListItem;
begin
if ModalResult <> mrOk then Exit;
for i := 0 to ParamsLV.Items.Count - 1 do
begin
Item := ParamsLV.Items[i];
for t := Low(TFieldType) to High(TFieldType) do
if Item.SubItems[0] = FieldTypeNames[t] then
begin
Params[i].DataType := t;
break;
end;
Params[i].Expression := Item.SubItems[1];
end;
end;
procedure TfrxMvxParamsEditorForm.ParamsLVSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
begin
if Selected then
begin
TypeCB.Top := ParamsLV.Top + Item.Top;
ValueE.Top := TypeCB.Top;
ButtonPanel.Top := TypeCB.Top;
TypeCB.ItemIndex := TypeCB.Items.IndexOf(Item.SubItems[0]);
ValueE.Text := Item.SubItems[1];
end
else
begin
Item.SubItems[0] := TypeCB.Text;
Item.SubItems[1] := ValueE.Text;
end;
end;
procedure TfrxMvxParamsEditorForm.ParamsLVMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
ParamsLV.Selected := ParamsLV.GetItemAt(5, Y);
ParamsLV.ItemFocused := ParamsLV.Selected;
end;
procedure TfrxMvxParamsEditorForm.OkBClick(Sender: TObject);
begin
ParamsLV.Selected := ParamsLV.Items[0];
end;
procedure TfrxMvxParamsEditorForm.ValueEButtonClick(Sender: TObject);
var
s: String;
begin
s := TfrxCustomDesigner(Owner).InsertExpression(ValueE.Text);
if s <> '' then
ValueE.Text := s;
end;
procedure TfrxMvxParamsEditorForm.FormCreate(Sender: TObject);
begin
Caption := frxGet(3700);
OkB.Caption := frxGet(1);
CancelB.Caption := frxGet(2);
ParamsLV.Columns[0].Caption := frxResources.Get('qpName');
ParamsLV.Columns[1].Caption := frxResources.Get('qpDataType');
ParamsLV.Columns[2].Caption := frxResources.Get('qpValue');
end;
procedure TfrxMvxParamsEditorForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_F1 then
frxResources.Help(Self);
end;
end.
//a229a6876583724e39a193cc768e8ca7
|
unit FormHeightmap;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls;
type
TFrmHeightMap = class(TForm)
EdImage: TEdit;
BtBrowseImage: TButton;
BtBrowseHeightmap: TButton;
EdHeightmap: TEdit;
Label1: TLabel;
Panel2: TPanel;
BtCancel: TButton;
BtOK: TButton;
Bevel3: TBevel;
Label2: TLabel;
Label3: TLabel;
OpenDialog: TOpenDialog;
procedure BtCancelClick(Sender: TObject);
procedure BtOKClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure BtBrowseHeightmapClick(Sender: TObject);
procedure BtBrowseImageClick(Sender: TObject);
private
{ Private declarations }
public
OK: boolean;
{ Public declarations }
end;
implementation
{$R *.dfm}
procedure TFrmHeightMap.BtBrowseHeightmapClick(Sender: TObject);
begin
if OpenDialog.Execute then
begin
EdHeightmap.Text := OpenDialog.FileName;
if FileExists(EdImage.Text) and FileExists(EdHeightmap.Text) then
begin
BtOK.Enabled := true;
end
else
begin
BtOK.Enabled := false;
end;
end;
end;
procedure TFrmHeightMap.BtBrowseImageClick(Sender: TObject);
begin
if OpenDialog.Execute then
begin
EdImage.Text := OpenDialog.FileName;
if FileExists(EdImage.Text) and FileExists(EdHeightmap.Text) then
begin
BtOK.Enabled := true;
end
else
begin
BtOK.Enabled := false;
end;
end;
end;
procedure TFrmHeightMap.BtCancelClick(Sender: TObject);
begin
Close;
end;
procedure TFrmHeightMap.BtOKClick(Sender: TObject);
begin
BtOK.Enabled := false;
OK := true;
close;
end;
procedure TFrmHeightMap.FormShow(Sender: TObject);
begin
OK := false;
end;
end.
|
unit Nullpobug.Example.Spring4d.LocalMathService;
interface
implementation
uses
Nullpobug.Example.Spring4d.ServiceLocator
, Nullpobug.Example.Spring4d.MathServiceIntf
;
type
TLocalMathServiceImpl = class(TInterfacedObject, IMathService)
function Add(A, B: integer): Integer;
function Multiply(A, B: integer): Integer;
function Name: String;
end;
{ TLocalMathServiceImpl }
function TLocalMathServiceImpl.Add(A, B: Integer): Integer;
begin
Result := A + B;
end;
function TLocalMathServiceImpl.Multiply(A, B: Integer): Integer;
begin
Result := A * B;
end;
function TLocalMathServiceImpl.Name: String;
begin
Result := ToString;
end;
procedure RegisterLocalMathService;
begin
ServiceLocator.RegisterComponent<TLocalMathServiceImpl>.Implements<IMathService>;
ServiceLocator.Build;
end;
initialization
RegisterLocalMathService;
end.
|
unit wwspin;
interface
uses Wintypes, winprocs, Classes, StdCtrls, ExtCtrls, Controls, Messages, SysUtils,
Forms, Graphics, Menus, Buttons;
const
InitRepeatPause = 400; { pause before repeat timer (ms) }
RepeatPause = 100; { pause before hint window displays (ms)}
type
TwwTimerSpeedButton = class;
TwwSpinButton = class (TWinControl)
private
FUpButton: TwwTimerSpeedButton;
FDownButton: TwwTimerSpeedButton;
{ FFocusedButton: TwwTimerSpeedButton;}
FOnUpClick: TNotifyEvent;
FOnDownClick: TNotifyEvent;
function CreateButton: TwwTimerSpeedButton;
function GetUpGlyph: TBitmap;
function GetDownGlyph: TBitmap;
procedure SetUpGlyph(Value: TBitmap);
procedure SetDownGlyph(Value: TBitmap);
procedure BtnClick(Sender: TObject);
procedure AdjustSize (var W: Integer; var H: Integer);
procedure WMSize(var Message: TWMSize); message WM_SIZE;
procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE;
protected
procedure Loaded; override;
public
constructor Create(AOwner: TComponent); override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
property DownGlyph: TBitmap read GetDownGlyph write SetDownGlyph;
property UpGlyph: TBitmap read GetUpGlyph write SetUpGlyph;
property OnDownClick: TNotifyEvent read FOnDownClick write FOnDownClick;
property OnUpClick: TNotifyEvent read FOnUpClick write FOnUpClick;
end;
{ TwwTimerSpeedButton }
TTimeBtnState = set of (tbFocusRect, tbAllowTimer);
TwwTimerSpeedButton = class(TSpeedButton)
private
FRepeatTimer: TTimer;
FTimeBtnState: TTimeBtnState;
procedure TimerExpired(Sender: TObject);
protected
procedure Paint; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
public
destructor Destroy; override;
property TimeBtnState: TTimeBtnState read FTimeBtnState write FTimeBtnState;
end;
implementation
{ TwwSpinButton }
constructor TwwSpinButton.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle - [csAcceptsControls, csSetCaption] +
[csFramed, csOpaque];
FUpButton := CreateButton;
FDownButton := CreateButton;
UpGlyph := nil;
DownGlyph := nil;
Width := 20;
Height := 25;
{ FFocusedButton := FUpButton;}
end;
function TwwSpinButton.CreateButton: TwwTimerSpeedButton;
begin
Result := TwwTimerSpeedButton.Create (Self);
Result.OnClick := BtnClick;
Result.Visible := True;
Result.Enabled := True;
Result.TimeBtnState := [tbAllowTimer];
Result.NumGlyphs := 1;
Result.Parent := Self;
end;
procedure TwwSpinButton.AdjustSize (var W: Integer; var H: Integer);
begin
if (FUpButton = nil) or (csLoading in ComponentState) then Exit;
if W < 15 then W := 15;
FUpButton.SetBounds (0, 0, W, H div 2);
FDownButton.SetBounds (0, FUpButton.Height - 1, W, H - FUpButton.Height + 1);
end;
procedure TwwSpinButton.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
var
W, H: Integer;
begin
W := AWidth;
H := AHeight;
AdjustSize (W, H);
inherited SetBounds (ALeft, ATop, W, H);
end;
procedure TwwSpinButton.WMSize(var Message: TWMSize);
var
W, H: Integer;
begin
inherited;
{ check for minimum size }
W := Width;
H := Height;
AdjustSize (W, H);
if (W <> Width) or (H <> Height) then
inherited SetBounds(Left, Top, W, H);
Message.Result := 0;
end;
procedure TwwSpinButton.BtnClick(Sender: TObject);
begin
if Sender = FUpButton then
begin
if Assigned(FOnUpClick) then FOnUpClick(Self);
end
else
if Assigned(FOnDownClick) then FOnDownClick(Self);
end;
procedure TwwSpinButton.WMGetDlgCode(var Message: TWMGetDlgCode);
begin
Message.Result := DLGC_WANTARROWS;
end;
procedure TwwSpinButton.Loaded;
var
W, H: Integer;
begin
inherited Loaded;
W := Width;
H := Height;
AdjustSize (W, H);
if (W <> Width) or (H <> Height) then
inherited SetBounds (Left, Top, W, H);
end;
function TwwSpinButton.GetUpGlyph: TBitmap;
begin
Result := FUpButton.Glyph;
end;
procedure TwwSpinButton.SetUpGlyph(Value: TBitmap);
begin
if Value <> nil then
FUpButton.Glyph := Value
else
begin
FUpButton.Glyph.Handle := LoadBitmap(HInstance, 'wwSpinUp');
FUpButton.NumGlyphs := 1;
FUpButton.Invalidate;
end;
end;
function TwwSpinButton.GetDownGlyph: TBitmap;
begin
Result := FDownButton.Glyph;
end;
procedure TwwSpinButton.SetDownGlyph(Value: TBitmap);
begin
if Value <> nil then
FDownButton.Glyph := Value
else
begin
FDownButton.Glyph.Handle := LoadBitmap(HInstance, 'wwSpinDown');
FDownButton.NumGlyphs := 1;
FDownButton.Invalidate;
end;
end;
{TwwTimerSpeedButton}
destructor TwwTimerSpeedButton.Destroy;
begin
if FRepeatTimer <> nil then
FRepeatTimer.Free;
inherited Destroy;
end;
procedure TwwTimerSpeedButton.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
inherited MouseDown (Button, Shift, X, Y);
if tbAllowTimer in FTimeBtnState then
begin
if FRepeatTimer = nil then
FRepeatTimer := TTimer.Create(Self);
FRepeatTimer.OnTimer := TimerExpired;
FRepeatTimer.Interval := InitRepeatPause;
FRepeatTimer.Enabled := True;
end;
end;
procedure TwwTimerSpeedButton.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
inherited MouseUp (Button, Shift, X, Y);
if FRepeatTimer <> nil then
FRepeatTimer.Enabled := False;
end;
procedure TwwTimerSpeedButton.TimerExpired(Sender: TObject);
begin
FRepeatTimer.Interval := RepeatPause;
if (FState = bsDown) and MouseCapture then
begin
try
Click;
except
FRepeatTimer.Enabled := False;
raise;
end;
end;
end;
procedure TwwTimerSpeedButton.Paint;
var
R: TRect;
begin
inherited Paint;
if tbFocusRect in FTimeBtnState then
begin
R := Bounds(0, 0, Width, Height);
InflateRect(R, -3, -3);
if FState = bsDown then
OffsetRect(R, 1, 1);
DrawFocusRect(Canvas.Handle, R);
end;
end;
end.
|
unit UnitFormReg;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, IdTCPServer, UnitPrincipal;
type
TFormReg = class(TForm)
LabelNombre: TLabel;
EditNombreValor: TEdit;
LabelInformacion: TLabel;
MemoInformacionValor: TMemo;
BtnAceptar: TSpeedButton;
BtnCancelar: TSpeedButton;
procedure BtnCancelarClick(Sender: TObject);
procedure BtnAceptarClick(Sender: TObject);
procedure MemoInformacionValorKeyPress(Sender: TObject; var Key: Char);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
private
Servidor: PConexao;
Ruta, Tipo: String;
procedure CerrarVentana();
{ Private declarations }
public
constructor Create(aOwner: TComponent; ConAux: PConexao; RegistroRuta, RegistroTipo: String);
{ Public declarations }
end;
var
FormReg: TFormReg;
implementation
uses
UnitComandos,
UnitStrings,
UnitConexao;
{$R *.dfm}
constructor TFormReg.Create(aOwner: TComponent; ConAux: PConexao; RegistroRuta, RegistroTipo: String);
begin
inherited Create(aOwner);
Servidor := ConAux;
Ruta := RegistroRuta;
Tipo := RegistroTipo;
Caption := pchar(traduzidos[257]) + ' ' + Tipo;
end;
procedure TFormReg.CerrarVentana();
begin
//Deja todo como estaba
EditNombreValor.Text := '';
EditNombreValor.Enabled := True;
MemoInformacionValor.Text := '';
MemoInformacionValor.Enabled := True;
Close;
end;
procedure TFormReg.BtnCancelarClick(Sender: TObject);
begin
CerrarVentana();
end;
procedure TFormReg.BtnAceptarClick(Sender: TObject);
begin
EnviarString(Servidor.Athread, ADICIONARVALOR + '|' + Ruta +
EditNombreValor.Text + '|' + Tipo + '|' + MemoInformacionValor.Text + '|');
CerrarVentana();
end;
procedure TFormReg.MemoInformacionValorKeyPress(Sender: TObject;
var Key: Char);
begin
if (Tipo = REG_SZ_) or (Tipo = REG_EXPAND_SZ_) then
if (key = #10) or (key = #13) then
begin
MessageDlg(pchar(traduzidos[258]), mtwarning, [mbok], 0);
Key := #0;
MessageBeep($FFFFFFFF);
end;
if Tipo = REG_BINARY_ then //Si es un valor binario solo deja introducir valores hexadeciamles y espacios
if not (key in ['0'..'9', 'A'..'F', 'a'..'f', ' ', #8]) then //#8 es el backspace, borrar
begin
key := #0;
MessageBeep($FFFFFFFF);
end;
if Tipo = REG_DWORD_ then //Si es un valor binario solo deja introducir números
if not (key in ['0'..'9', #8]) then
begin
key := #0;
MessageBeep($FFFFFFFF);
end;
end;
procedure TFormReg.FormCreate(Sender: TObject);
begin
FormPrincipal.ImageListIcons.GetBitmap(249, btnAceptar.Glyph);
FormPrincipal.ImageListIcons.GetBitmap(279, btnCancelar.Glyph);
end;
procedure TFormReg.FormShow(Sender: TObject);
begin
btnaceptar.Caption := traduzidos[58];
btncancelar.Caption := traduzidos[59];
labelnombre.Caption := traduzidos[231];
labelinformacion.Caption := traduzidos[232];
end;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2015 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of an Embarcadero developer tools product.
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit uMain;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, System.Sensors, FMX.StdCtrls,
FMX.Edit, FMX.WebBrowser, FMX.ListBox, FMX.Layouts, System.Sensors.Components,
FMX.Controls.Presentation, FMX.EditBox, FMX.NumberBox;
type
TLocationForm = class(TForm)
LocationSensor1: TLocationSensor;
WebBrowser1: TWebBrowser;
ListBox1: TListBox;
lbLocationSensor: TListBoxItem;
swLocationSensorActive: TSwitch;
lbTriggerDistance: TListBoxItem;
nbTriggerDistance: TNumberBox;
Button1: TButton;
Button2: TButton;
lbAccuracy: TListBoxItem;
Button3: TButton;
Button4: TButton;
nbAccuracy: TNumberBox;
lbLatitude: TListBoxItem;
lbLongitude: TListBoxItem;
ToolBar1: TToolBar;
Label1: TLabel;
procedure LocationSensor1LocationChanged(Sender: TObject; const OldLocation, NewLocation: TLocationCoord2D);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure swLocationSensorActiveSwitch(Sender: TObject);
procedure nbTriggerDistanceChange(Sender: TObject);
procedure nbAccuracyChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
LocationForm: TLocationForm;
implementation
uses
System.Permissions,
{$IFDEF ANDROID}
Androidapi.JNI.Os,
Androidapi.JNI.JavaTypes,
Androidapi.Helpers,
{$ENDIF}
FMX.DialogService;
{$R *.fmx}
procedure TLocationForm.Button1Click(Sender: TObject);
begin
nbTriggerDistance.Value := nbTriggerDistance.Value - 1;
end;
procedure TLocationForm.Button2Click(Sender: TObject);
begin
nbTriggerDistance.Value := nbTriggerDistance.Value + 1;
end;
procedure TLocationForm.Button3Click(Sender: TObject);
begin
nbAccuracy.Value := nbAccuracy.Value - 1;
end;
procedure TLocationForm.Button4Click(Sender: TObject);
begin
nbAccuracy.Value := nbAccuracy.Value + 1;
end;
procedure TLocationForm.LocationSensor1LocationChanged(Sender: TObject; const OldLocation, NewLocation: TLocationCoord2D);
const
LGoogleMapsURL: String = 'https://maps.google.com/maps?q=%s,%s';
var
ENUSLat, ENUSLong: String; // holders for URL strings
begin
ENUSLat := NewLocation.Latitude.ToString(ffGeneral, 5, 2, TFormatSettings.Create('en-US'));
ENUSLong := NewLocation.Longitude.ToString(ffGeneral, 5, 2, TFormatSettings.Create('en-US'));
{ convert the location to latitude and longitude }
lbLatitude.Text := 'Latitude: ' + ENUSLat;
lbLongitude.Text := 'Longitude: ' + ENUSLong;
{ and track the location via Google Maps }
WebBrowser1.Navigate(Format(LGoogleMapsURL, [ENUSLat, ENUSLong]));
end;
procedure TLocationForm.nbAccuracyChange(Sender: TObject);
begin
{ set the precision }
LocationSensor1.Accuracy := nbAccuracy.Value;
end;
procedure TLocationForm.nbTriggerDistanceChange(Sender: TObject);
begin
{ set the triggering distance }
LocationSensor1.Distance := nbTriggerDistance.Value;
end;
procedure TLocationForm.swLocationSensorActiveSwitch(Sender: TObject);
begin
{$IFDEF ANDROID}
if swLocationSensorActive.IsChecked then
PermissionsService.RequestPermissions([JStringToString(TJManifest_permission.JavaClass.ACCESS_FINE_LOCATION)],
procedure(const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>)
begin
if (Length(AGrantResults) = 1) and (AGrantResults[0] = TPermissionStatus.Granted) then
{ activate or deactivate the location sensor }
LocationSensor1.Active := True
else
begin
swLocationSensorActive.IsChecked := False;
TDialogService.ShowMessage('Location permission not granted');
end;
end)
else
LocationSensor1.Active := False;
{$ENDIF}
end;
end.
|
//*****************************************//
// Carlo Pasolini //
// http://pasotech.altervista.org //
// email: cdpasop@hotmail.it //
//*****************************************//
//http://pasotech.altervista.org/delphi/articolo95.htm
unit uCodeInjection_RemoteUncrypt;
interface
uses
Windows;
function RemoteUncrypt(PID: Cardinal; Data: Pointer; DataSize: Cardinal; NamedPipeName: PAnsiChar; var outValue: Cardinal; var codError: Cardinal; synch: Boolean): Boolean;
implementation
uses
uCodeInjection, uDecls;
//, uUtils;
type
PDATA_BLOB = ^DATA_BLOB;
DATA_BLOB = record
cbData: Cardinal;
pbData: PByte;
end;
PCRYPTPROTECT_PROMPTSTRUCT = ^CRYPTPROTECT_PROMPTSTRUCT;
CRYPTPROTECT_PROMPTSTRUCT = packed record
cbSize: Cardinal; // Size of this structure (bytes).
dwPromptFlags: Cardinal; // Prompt flags.
hwndApp: Cardinal; // Handle to parent window.
szPrompt: PWideChar // Prompt to display to user.
end;
function RemoteUncrypt(PID: Cardinal; //PID del processo remoto
//...; //dichiarazione di tutti i parametri che vogliamo
Data: Pointer;
DataSize: Cardinal;
NamedPipeName: PAnsiChar;
var outValue: Cardinal; //valore importante ottenuto dalla funzione remota
var codError: Cardinal; //errore riscontrato dalla funzione remota
synch: Boolean): Boolean; //esecuzione sincrona del thread remoto
type
TRemoteUncryptData = record
errorcod: Cardinal; //codice di errore rilevato nella funzione remota
output: Cardinal; //risultato significativo nella funzione remota
//Indirizzi delle API usate: elenco puntatori a funzioni; N.B. rigorosamente stdcall
//Es. pLoadLibraryA: function(pLibFileName: PAnsiChar): Cardinal; stdcall;
pExitThread: procedure (dwExitCode: Cardinal); stdcall; //API obbligatoria
pGetLastError: function(): Cardinal; stdcall;
pCreateFileA: function(
lpFileName: PAnsiChar;
dwDesiredAccess,
dwShareMode: Cardinal;
lpSecurityAttributes: Pointer;
dwCreationDisposition,
dwFlagsAndAttributes: Cardinal;
hTemplateFile: Cardinal
): Cardinal; stdcall;
pWriteFile: function(
hFile: Cardinal;
const Buffer;
//Buffer: Pointer;
nNumberOfBytesToWrite: Cardinal;
var lpNumberOfBytesWritten: Cardinal;
lpOverlapped: Pointer
): Boolean; stdcall;
pCloseHandle: function(
hnd: Cardinal
): Boolean; stdcall;
pCryptUnprotectData: function(
pDataIn: PDATA_BLOB;
var ppszDataDescr: PWideChar;
pOptionalEntropy: PDATA_BLOB;
pvReserved: Pointer;
pPromptStruct: PCRYPTPROTECT_PROMPTSTRUCT;
dwFlags: Cardinal;
var pDataOut: DATA_BLOB
): Boolean; stdcall;
pLocalFree: function(
hMem: Pointer
): Cardinal;
//Puntatori a dati; Es. tutte le stringhe vanno messe qui dentro
//Es. pNomeDll: Pointer;
pData: Pointer;
pNamedPipeName: Pointer;
fDataSize: Cardinal;
end;
var
hProcess: Cardinal; //handle al processo remoto
RemoteUncryptData: TRemoteUncryptData;
pRemoteUncryptData: Pointer; //indirizzo del record nello spazio di memoria del processo remoto
pRemoteUncryptThread: Pointer; //indirizzo della funzione del thread nello spazio di memoria del processo remoto
output_value: Cardinal;
error_code: Cardinal;
//indirizzi di base delle dll che ci interessano, nello spazio di memoria del processo remoto
hKernel32, hCrypt32: Cardinal;
FuncAddr: Cardinal;
functionSize, parameterSize: Cardinal;
procedure RemoteUncryptThread(lpParameter: pointer); stdcall;
//qui posso definire delle variabili locali
var
i: Cardinal;
//interazione col named pipe
PipeKeys: Cardinal;
BytesWritten: Cardinal;
sMessage: String;
Data_in, Data_out: DATA_BLOB;
szDescription: PWideChar;
//
begin
with TRemoteUncryptData(lpParameter^) do
begin
//implementazione: tutte le API vengono chiamate tramite i puntatori nel record
//apriamo il named pipe creato dal processo chiamante
PipeKeys := pCreateFileA(pNamedPipeName,
GENERIC_WRITE,
0,
nil,
//CREATE_NEW
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);
if (PipeKeys = INVALID_HANDLE_VALUE) then
begin
errorcod := pGetLastError;
pExitThread(0);
end;
//verifico se i dati sono stati copiati correttamente nello spazio di memoria del processo remoto
//BytesWritten := 0;
//pWriteFile(PipeKeys, pData^, fDataSize, BytesWritten, nil);
//pWriteFile(PipeKeys, pNamedPipeName^, 18, BytesWritten, nil);
Data_in.cbData := fDataSize;
Data_in.pbData := pData;
Data_out.cbData := 0;
Data_out.pbData := nil;
if not pCryptUnprotectData(@Data_in, szDescription, nil, nil, nil, 0, Data_out) then
begin
pCloseHandle(PipeKeys);
pExitThread(0);
end;
//scrivo il buffer decodificato sul named pipe
//pWriteFile(PipeKeys, Data_in.pbData, Data_in.cbData, BytesWritten, nil);
//pWriteFile(PipeKeys, pData, fDataSize, BytesWritten, nil);
pWriteFile(PipeKeys, (Data_out.pbData)^, Data_out.cbData, BytesWritten, nil);
pLocalFree(@Data_out);
pCloseHandle(PipeKeys);
pExitThread(1);
//N.B. chiamare sempre pExitCodeThread per definire il codice di uscita del thread
//Es. pExitCodeThread(1) significa successo
// pExitCodeThread(0) significa fallimento
end;
end;
//dealloco la memoria in remoto
function RemoteUncryptUnloadData(): Boolean;
begin
Result := False;
with RemoteUncryptData do
begin
//chiamo UnloadData su tutti i puntatori a dati inclusi nel record
UnloadData(hProcess, pData);
UnloadData(hProcess, pNamedPipeName);
end;
//deallocazione spazio per il parametro
UnloadData(hProcess, pRemoteUncryptData);
//deallocazione spazio per la funzione
UnloadData(hProcess, pRemoteUncryptThread);
Result := True;
end;
//definisco i valori dei campi del record e copio i dati in remoto
function RemoteUncryptInjectData(): Boolean;
begin
Result := False;
try
//inizializzazione valori campi del record:
with RemoteUncryptData do
begin
errorcod := 0;
output := 0;
fDataSize := DataSize;
//determino l'indirizzo di base di caricamento di kernel32.dll e advapi32.dll nello spazio
//di memoria del processo remoto
if not RemoteGetModuleHandle(
hProcess,
'kernel32.dll',
hKernel32
) then
begin
Exit;
end;
if not RemoteGetModuleHandle(
hProcess,
'crypt32.dll',
hCrypt32
) then
begin
Exit;
end;
//assegno i valori ai puntatori a funzione (tramite RemoteGetProcAddress)
if not RemoteGetProcAddress(
hProcess,
hKernel32,
'ExitThread',
FuncAddr
) then
begin
Exit;
end;
pExitThread := Pointer(FuncAddr);
if not RemoteGetProcAddress(
hProcess,
hKernel32,
'GetLastError',
FuncAddr
) then
begin
Exit;
end;
pGetLastError := Pointer(FuncAddr);
if not RemoteGetProcAddress(
hProcess,
hKernel32,
'CreateFileA',
FuncAddr
) then
begin
Exit;
end;
pCreateFileA := Pointer(FuncAddr);
if not RemoteGetProcAddress(
hProcess,
hKernel32,
'WriteFile',
FuncAddr
) then
begin
Exit;
end;
pWriteFile := Pointer(FuncAddr);
if not RemoteGetProcAddress(
hProcess,
hKernel32,
'CloseHandle',
FuncAddr
) then
begin
Exit;
end;
pCloseHandle := Pointer(FuncAddr);
if not RemoteGetProcAddress(
hProcess,
hKernel32,
'LocalFree',
FuncAddr
) then
begin
Exit;
end;
pLocalFree := Pointer(FuncAddr);
if not RemoteGetProcAddress(
hProcess,
hCrypt32,
'CryptUnprotectData',
FuncAddr
) then
begin
Exit;
end;
pCryptUnprotectData := Pointer(FuncAddr);
//assegno i valori ai puntatori ai dati (tramite InjectData);
//N.B. se una InjectData ritorna False allora bisogna chiamare Exit
//ScriviLog(DumpData(Data, DataSize));
if not InjectData(hProcess,
Data,
DataSize,
False,
pData) then
begin
Exit;
end;
if not InjectData(hProcess,
NamedPipeName,
Length(NamedPipeName),
False,
pNamedPipeName) then
begin
Exit;
end;
end;
//copio il parametro
parameterSize := SizeOf(RemoteUncryptData);
if not InjectData(hProcess,
@RemoteUncryptData,
parameterSize,
False,
pRemoteUncryptData) then
begin
Exit;
end;
//copio la funzione
functionSize := SizeOfProc(@RemoteUncryptThread);
if not InjectData(hProcess,
@RemoteUncryptThread,
functionSize,
True,
pRemoteUncryptThread) then
begin
Exit;
end;
Result := True;
finally
if not Result then
begin
RemoteUncryptUnloadData;
end;
end;
end;
begin
//inizializzo a zero le variabili locali
hProcess := 0;
pRemoteUncryptData := nil;
pRemoteUncryptThread := nil;
output_value := 0;
error_code := 0;
try
//ScriviLog(DumpData(Data, DataSize));
hProcess := OpenProcessEx(PROCESS_CREATE_THREAD +
PROCESS_QUERY_INFORMATION +
PROCESS_VM_OPERATION +
PROCESS_VM_WRITE +
PROCESS_VM_READ,
False,
PID
);
if hProcess = 0 then
begin
//ErrStr('OpenProcess');
Exit;
end;
if not RemoteUncryptInjectData() then
Exit;
if not InjectThread(hProcess,
pRemoteUncryptThread,
pRemoteUncryptData,
output_value,
error_code,
synch) then
Exit;
//output_value e error_code sono stati inizializzati a 0.
//sono stati modificati dalla InjectThread solo se synch = true;
//se synch=false sono rimasti uguali a zero
outvalue := output_value;
codError := error_code;
Result := True;
finally
if synch or (not Result) then
begin
RemoteUncryptUnloadData;
end;
if hProcess <> 0 then
begin
if not CloseHandle(hProcess) then
begin
//ErrStr('CloseHandle');
end;
end;
end;
end;
end.
|
unit GCDOpTest;
{$mode objfpc}{$H+}
interface
uses
fpcunit,
testregistry,
uIntX;
type
{ TTestGCDOp }
TTestGCDOp = class(TTestCase)
published
procedure GCDIntXBothPositive();
procedure GCDIntXBothNegative();
procedure GCDIntXBothSigns();
end;
implementation
{ TTestGCDOp }
procedure TTestGCDOp.GCDIntXBothPositive;
var
res: TIntX;
begin
res := TIntX.GCD(4, 6);
AssertTrue(res = 2);
res := TIntX.GCD(24, 18);
AssertTrue(res = 6);
res := TIntX.GCD(234, 100);
AssertTrue(res = 2);
res := TIntX.GCD(235, 100);
AssertTrue(res = 5);
end;
procedure TTestGCDOp.GCDIntXBothNegative;
var
res: TIntX;
begin
res := TIntX.GCD(-4, -6);
AssertTrue(res = 2);
res := TIntX.GCD(-24, -18);
AssertTrue(res = 6);
res := TIntX.GCD(-234, -100);
AssertTrue(res = 2);
end;
procedure TTestGCDOp.GCDIntXBothSigns;
var
res: TIntX;
begin
res := TIntX.GCD(-4, +6);
AssertTrue(res = 2);
res := TIntX.GCD(+24, -18);
AssertTrue(res = 6);
res := TIntX.GCD(-234, +100);
AssertTrue(res = 2);
end;
initialization
RegisterTest(TTestGCDOp);
end.
|
unit Objekt.Maildat;
interface
uses
SysUtils, Classes, Vcl.ExtCtrls,
Objekt.DateTime, Vcl.Controls, Vcl.Forms;
type
TProvider=(pvExchange, pvGmail, pvWeb);
type
TMailDat = class
private
fProgrammPfad: string;
fDataFile: string;
fProvider: TProvider;
fMail: string;
fHost: string;
fUser: string;
fPasswort: string;
fBetreff: string;
fMailAn: string;
public
property Provider: TProvider read fProvider write fProvider;
property Host: string read fHost write fHost;
property Mail: string read fMail write fMail;
property User: string read fUser write fUser;
property Passwort: string read fPasswort write fPasswort;
property Betreff: string read fBetreff write fBetreff;
property MailAn: string read fMailAn write fMailAn;
constructor Create;
destructor Destroy; override;
procedure Init;
procedure Load;
procedure Save;
end;
implementation
{ TMailDat }
uses
Objekt.Allgemein;
constructor TMailDat.Create;
begin
fProgrammpfad := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0)));
fDataFile := fProgrammpfad + 'Mail.dat';
Init;
end;
destructor TMailDat.Destroy;
begin
inherited;
end;
procedure TMailDat.Init;
begin
fProvider := pvExchange;
fHost := '';
fUser := '';
fMail := '';
fPasswort := '';
fBetreff := '';
fMailAn := '';
end;
procedure TMailDat.Load;
var
List: TStringList;
List2: TStringList;
iProvider: Integer;
begin
init;
if not FileExists(fDataFile) then
exit;
List2 := TStringList.Create;
List := TStringList.Create;
try
List2.Delimiter := ';';
List2.StrictDelimiter := true;
List.LoadFromFile(fDataFile);
List2.DelimitedText := AllgemeinObj.Entschluesseln(List.Text);
if List2.Count < 7 then
exit;
if not TryStrToInt(List2.Strings[0], iProvider) then
iProvider := 0;
fProvider := TProvider(iProvider);
fHost := List2.Strings[1];
fUser := List2.Strings[2];
fMail := List2.Strings[3];
fPasswort := List2.Strings[4];
fBetreff := List2.Strings[5];
fMailAn := List2.Strings[6];
finally
FreeAndNil(List);
FreeAndNil(List2);
end;
end;
procedure TMailDat.Save;
var
List: TStringList;
s: string;
begin
List := TStringList.Create;
try
s := IntToStr(Ord(fProvider)) + ';' +
fHost + ';' + fUser + ';' + fMail + ';' + fPasswort + ';' + fBetreff + ';' + fMailAn;
List.Text := AllgemeinObj.Verschluesseln(s);
List.SaveToFile(fDataFile);
finally
FreeAndNil(List);
end;
end;
end.
|
unit BaseTypes;
interface
uses
Classes,Windows,SysUtils,ScktComp,superobject,Common,ComObj,OPCtypes,OPCDA, OPCutils,ActiveX,ExtCtrls;
type
TOnDataChange = procedure (dwTransid: DWORD; hGroup: OPCHANDLE;hrMasterquality: HResult; hrMastererror: HResult; dwCount: DWORD;phClientItems: POPCHANDLEARRAY; pvValues: POleVariantArray;pwQualities: PWordArray; pftTimeStamps: PFileTimeArray;pErrors: PResultList;ServerName:string) of object;
TOnReadComplete = procedure (dwTransid: DWORD; hGroup: OPCHANDLE;hrMasterquality: HResult; hrMastererror: HResult; dwCount: DWORD; phClientItems: POPCHANDLEARRAY; pvValues: POleVariantArray;pwQualities: PWordArray; pftTimeStamps: PFileTimeArray;pErrors: PResultList)of object;
TOnWriteComplete = procedure (dwTransid: DWORD; hGroup: OPCHANDLE;hrMastererr: HResult; dwCount: DWORD; pClienthandles: POPCHANDLEARRAY;pErrors: PResultList)of object;
TOnCancelComplete = procedure (dwTransid: DWORD; hGroup: OPCHANDLE) of object;
TOnNewData = procedure(LogicDeviceId:string;ItemHandel:Opchandle;ItemValue:string) of object;
TOPCDataCallback = class(TInterfacedObject, IOPCDataCallback)
private
ServerName : string;
VOnDataChange : TOnDataChange;
VOnReadComplete : TOnReadComplete;
VOnWriteComplete : TOnWriteComplete;
VOnCancelComplete: TOnCancelComplete;
function OnDataChange(dwTransid: DWORD; hGroup: OPCHANDLE;hrMasterquality: HResult; hrMastererror: HResult; dwCount: DWORD;phClientItems: POPCHANDLEARRAY; pvValues: POleVariantArray;pwQualities: PWordArray; pftTimeStamps: PFileTimeArray;pErrors: PResultList): HResult; stdcall;
function OnReadComplete(dwTransid: DWORD; hGroup: OPCHANDLE;hrMasterquality: HResult; hrMastererror: HResult; dwCount: DWORD; phClientItems: POPCHANDLEARRAY; pvValues: POleVariantArray;pwQualities: PWordArray; pftTimeStamps: PFileTimeArray;pErrors: PResultList): HResult; stdcall;
function OnWriteComplete(dwTransid: DWORD; hGroup: OPCHANDLE;hrMastererr: HResult; dwCount: DWORD; pClienthandles: POPCHANDLEARRAY;pErrors: PResultList): HResult; stdcall;
function OnCancelComplete(dwTransid: DWORD; hGroup: OPCHANDLE):HResult; stdcall;
public
property POnDataChange : TOnDataChange read VOnDataChange write VOnDataChange;
property POnReadComplete: TOnReadComplete read VOnReadComplete write VOnReadComplete;
property POnWriteComplete: TOnWriteComplete read VOnWriteComplete write VOnWriteComplete;
property POnCancelComplete: TOnCancelComplete read VOnCancelComplete write VOnCancelComplete;
property PServerName: string read ServerName write ServerName;
end;
TStringMap = class(TPersistent)
private
function GetItems(Key: string): string;
function GetCount: Integer;
public
Keys: TStrings;
Values: array of string;
property Items[Key: string]: string read GetItems; default;
property Count: Integer read GetCount;
function Add(Key: string; Value: string): Integer;
procedure clear;
function Remove(Key: string): Integer;
constructor Create; overload;
end;
TItem = class(TObject)
ItemHandel : Opchandle;
LogicDeviceId :TStrings;
ItemValue:string;
ItemName : string;
end;
TItems = class(TPersistent)
private
function GetItems(Key: string): TItem;
function GetCount: Integer;
public
Keys: TStrings;
Values: array of TItem;
property Items[Key: string]: TItem read GetItems; default;
property Count: Integer read GetCount;
function Add(Key: string; Value: TItem): Integer;
procedure clear;
function Remove(Key: string): Integer;
constructor Create; overload;
end;
TServer = class(TObject)
public
ServerName : string;
ServerIf : IOPCServer;
GroupIf : IOPCItemMgt;
GroupHandle : Cardinal;
Items : TItems;
destructor Destroy; override;
constructor Create; overload;
function Init :Boolean;
function Add(ALogicDeviceId:string;ItemName:string;var isAdd : Boolean):Opchandle;
procedure Clear;
end;
TServers = class(TPersistent)
private
function GetItems(Key: string): TServer;
function GetCount: Integer;
public
Keys: TStrings;
Values: array of TServer;
property Items[Key: string]: TServer read GetItems; default;
property Count: Integer read GetCount;
function Add(Key: string; Value: TServer): Integer;
procedure clear;
function Remove(Key: string): Integer;
constructor Create; overload;
procedure RemoveErrors(itemNames:TStrings);
end;
TLogicDevice = class(TObject)
private
public
ID : string;
Address : string;
ItemsValues : TStringMap;
constructor Create; overload;
function getValueString :string;
end;
TLogicDevices = class(TPersistent)
private
function GetItems(Key: string): TLogicDevice;
function GetCount: Integer;
public
Keys: TStrings;
Values: array of TLogicDevice;
property Items[Key: string]: TLogicDevice read GetItems; default;
property Count: Integer read GetCount;
function Add(Key: string; Value: TLogicDevice): Integer;
procedure clear;
function Remove(Key: string): Integer;
constructor Create; overload;
end;
TScokets = class(TPersistent)
private
function GetItems(Key: string): TCustomWinSocket;
function GetCount: Integer;
public
Keys: TStrings;
Values: array of TCustomWinSocket;
property Items[Key: string]: TCustomWinSocket read GetItems; default; //获取其单一元素
property Count: Integer read GetCount; //获取个数
function Add(Key: string; Value: TCustomWinSocket): Integer; //添加元素
procedure clear;
function Remove(Key: string): Integer; //移除
constructor Create; overload;
end;
TPreSend = class(TObject)
public
LogicDeviceId : TStrings;
ItemHandel : Opchandle;
ItemValue : string;
end;
TPreSends = array of TPreSend;
implementation
uses
MainLib;
constructor TStringMap.Create;
begin
Keys := TStringList.Create;
SetLength(Values, 0);
end;
procedure TStringMap.clear;
begin
SetLength(Values, 0);
Keys.Clear;
end;
function TStringMap.GetItems(Key: string): string;
var
KeyIndex: Integer;
begin
KeyIndex := Keys.IndexOf(Key);
if KeyIndex <> -1 then
Result := Values[KeyIndex]
else
Result := '';
end;
function TStringMap.Add(Key: string; Value: string): Integer;
var
I:Integer;
begin
if Value = '' then Exit;
I := Keys.IndexOf(Key);
if I = -1 then
begin
Keys.Add(Key);
SetLength(Values, Length(Values) + 1);
Values[Length(Values) - 1] := Value;
end
else
Values[I] := Value;
Result := Length(Values) - 1;
end;
function TStringMap.GetCount: Integer;
begin
Result := Keys.Count;
end;
function TStringMap.Remove(Key: string): Integer;
var
Index : Integer;
Count : Integer;
begin
Index := Keys.IndexOf(Key);
Count := Length(Values);
if Index <> -1 then
begin
Keys.Delete(Index);
Move(Values[Index + 1], Values[Index], (Count - Index) * SizeOf(Values[0]));
SetLength(Values, Count - 1);
end;
Result := Count - 1;
end;
constructor TServer.Create;
begin
Items := TItems.Create;
inherited Create;
end;
destructor TServer.Destroy;
begin
Clear;
if Assigned(GroupIf) then
ServerIf.RemoveGroup(GroupHandle, False);
end;
function TServer.Init:Boolean;
var
Hr : HResult;
begin
Result := True;
try
ServerIf := CreateComObject(ProgIDToClassID(ServerName)) as IOPCServer;
except
Result := False;
Exit;
end;
Hr := ServerAddGroup(ServerIf, ServerName + ' g1', True, 5000, 0,GroupIf, GroupHandle);
if not Succeeded(HR) then
begin
Result := False;
Exit;
end;
end;
function TServer.Add(ALogicDeviceId:string;ItemName:string;var isAdd : Boolean):Opchandle;
var
Hr : HRESULT;
ItemHandle : Opchandle;
ItemType : TVarType;
Item : TItem;
begin
Item := Items.Items[ItemName];
if Assigned(Item) then
begin
Result := Item.ItemHandel;
Item.LogicDeviceId.Add(ALogicDeviceId);
Items.Add(ItemName ,Item);
isAdd := False;
end
else
begin
Hr := GroupAddItem(GroupIf,ItemName, 0, VT_EMPTY,ItemHandle,ItemType);
if not Succeeded(Hr) then
begin
Result := 0;
Exit;
end;
isAdd := True;
Item := TItem.Create;
Item.ItemHandel := ItemHandle;
Item.ItemName := ItemName;
Item.LogicDeviceId := TStringList.Create;
Item.LogicDeviceId.Add(ALogicDeviceId);
Item.ItemValue := '';
Items.Add(ItemName ,Item);
Result := ItemHandle;
end;
end;
procedure TServer.Clear;
begin
Items.clear;
end;
constructor TServers.Create;
begin
Keys := TStringList.Create;
SetLength(Values, 0);
end;
procedure TServers.clear;
begin
SetLength(Values, 0);
Keys.Clear;
end;
function TServers.GetItems(Key: string): TServer;
var
KeyIndex: Integer;
begin
KeyIndex := Keys.IndexOf(Key);
if KeyIndex <> -1 then
Result := Values[KeyIndex]
else
Result := nil;
end;
function TServers.Add(Key: string; Value: TServer): Integer;
begin
if Keys.IndexOf(Key) = -1 then
begin
Keys.Add(Key);
SetLength(Values, Length(Values) + 1);
Values[Length(Values) - 1] := Value;
end
else
Values[Keys.IndexOf(Key)] := Value;
Result := Length(Values) - 1;
end;
function TServers.GetCount: Integer;
begin
Result := Keys.Count;
end;
function TServers.Remove(Key: string): Integer;
var
Index : Integer;
Count : Integer;
begin
Index := Keys.IndexOf(Key);
Count := Length(Values);
if Index <> -1 then
begin
Keys.Delete(Index);
Move(Values[Index + 1], Values[Index], (Count - Index) * SizeOf(Values[0]));
SetLength(Values, Count - 1);
end;
Result := Count - 1;
end;
procedure TServers.RemoveErrors(itemNames:TStrings);
var
I,K:Integer;
begin
for I := 0 to Count - 1 do
begin
for K := 0 to itemNames.Count - 1 do
begin
Values[I].Items.Remove(itemNames[K]);
end;
end;
end;
constructor TItems.Create;
begin
Keys := TStringList.Create;
SetLength(Values, 0);
end;
procedure TItems.clear;
begin
SetLength(Values, 0);
Keys.Clear;
end;
function TItems.GetItems(Key: string): TItem;
var
KeyIndex: Integer;
begin
KeyIndex := Keys.IndexOf(Key);
if KeyIndex <> -1 then
Result := Values[KeyIndex]
else
Result := nil;
end;
function TItems.Add(Key: string; Value: TItem): Integer;
begin
if Keys.IndexOf(Key) = -1 then
begin
Keys.Add(Key);
SetLength(Values, Length(Values) + 1);
Values[Length(Values) - 1] := Value;
end
else
Values[Keys.IndexOf(Key)] := Value;
Result := Length(Values) - 1;
end;
function TItems.GetCount: Integer;
begin
Result := Keys.Count;
end;
function TItems.Remove(Key: string): Integer;
var
Index : Integer;
Count : Integer;
begin
Index := Keys.IndexOf(Key);
Count := Length(Values);
if Index <> -1 then
begin
Keys.Delete(Index);
Move(Values[Index + 1], Values[Index], (Count - Index) * SizeOf(Values[0]));
SetLength(Values, Count - 1);
end;
Result := Count - 1;
end;
constructor TScokets.Create;
begin
Keys := TStringList.Create;
SetLength(Values, 0);
end;
procedure TScokets.clear;
begin
SetLength(Values, 0);
Keys.Clear;
end;
function TScokets.GetItems(Key: string): TCustomWinSocket;
var
KeyIndex: Integer;
begin
KeyIndex := Keys.IndexOf(Key);
if KeyIndex <> -1 then
Result := Values[KeyIndex]
else
Result := nil;
end;
function TScokets.Add(Key: string; Value: TCustomWinSocket): Integer;
begin
if Keys.IndexOf(Key) = -1 then
begin
Keys.Add(Key);
SetLength(Values, Length(Values) + 1);
Values[Length(Values) - 1] := Value;
end
else
Values[Keys.IndexOf(Key)] := Value;
Result := Length(Values) - 1;
end;
function TScokets.GetCount: Integer;
begin
Result := Keys.Count;
end;
function TScokets.Remove(Key: string): Integer;
var
Index : Integer;
Count : Integer;
begin
Index := Keys.IndexOf(Key);
Count := Length(Values);
if Index <> -1 then
begin
Keys.Delete(Index);
Move(Values[Index + 1], Values[Index], (Count - Index) * SizeOf(Values[0]));
SetLength(Values, Count - 1);
end;
Result := Count - 1;
end;
constructor TLogicDevice.Create;
begin
ItemsValues := TStringMap.Create;
end;
function TLogicDevice.getValueString:string;
var
I :Integer;
RObject :ISuperObject;
begin
Result := '';
RObject := SO('{}');
RObject.S['id'] := ID;
for I := 0 to ItemsValues.Count - 1 do
begin
if ItemsValues.Values[I] = '-' then Exit;
RObject['value[]'] := SO(ItemsValues.Values[I]);
end;
Result := RObject.AsString;
end;
constructor TLogicDevices.Create;
begin
Keys := TStringList.Create;
SetLength(Values, 0);
end;
procedure TLogicDevices.clear;
begin
SetLength(Values, 0);
Keys.Clear;
end;
function TLogicDevices.GetItems(Key: string): TLogicDevice;
var
KeyIndex: Integer;
begin
KeyIndex := Keys.IndexOf(Key);
if KeyIndex <> -1 then
Result := Values[KeyIndex]
else
Result := nil;
end;
function TLogicDevices.Add(Key: string; Value: TLogicDevice): Integer;
begin
if Keys.IndexOf(Key) = -1 then
begin
Keys.Add(Key);
SetLength(Values, Length(Values) + 1);
Values[Length(Values) - 1] := Value;
end
else
Values[Keys.IndexOf(Key)] := Value;
Result := Length(Values) - 1;
end;
function TLogicDevices.GetCount: Integer;
begin
Result := Keys.Count;
end;
function TLogicDevices.Remove(Key: string): Integer;
var
Index : Integer;
Count : Integer;
begin
Index := Keys.IndexOf(Key);
Count := Length(Values);
if Index <> -1 then
begin
Keys.Delete(Index);
Move(Values[Index + 1], Values[Index], (Count - Index) * SizeOf(Values[0]));
SetLength(Values, Count - 1);
end;
Result := Count - 1;
end;
function TOPCDataCallback.OnDataChange(dwTransid: DWORD; hGroup: OPCHANDLE;hrMasterquality: HResult; hrMastererror: HResult; dwCount: DWORD;phClientItems: POPCHANDLEARRAY; pvValues: POleVariantArray;pwQualities: PWordArray; pftTimeStamps: PFileTimeArray;pErrors: PResultList): HResult;
begin
Result := S_OK;
if Assigned(VOnDataChange) then VOnDataChange(dwTransid,hGroup,hrMasterquality,hrMastererror,dwCount,phClientItems,pvValues,pwQualities,pftTimeStamps,pErrors,ServerName);
end;
function TOPCDataCallback.OnReadComplete(dwTransid: DWORD; hGroup: OPCHANDLE;hrMasterquality: HResult; hrMastererror: HResult; dwCount: DWORD;phClientItems: POPCHANDLEARRAY; pvValues: POleVariantArray;pwQualities: PWordArray; pftTimeStamps: PFileTimeArray;pErrors: PResultList): HResult;
begin
Result := S_OK;
if Assigned(VOnReadComplete) then VOnReadComplete(dwTransid,hGroup,hrMasterquality,hrMastererror,dwCount,phClientItems,pvValues,pwQualities, pftTimeStamps,pErrors);
end;
function TOPCDataCallback.OnWriteComplete(dwTransid: DWORD; hGroup: OPCHANDLE;hrMastererr: HResult; dwCount: DWORD; pClienthandles: POPCHANDLEARRAY;pErrors: PResultList): HResult;
begin
Result := S_OK;
if Assigned(VOnWriteComplete) then VOnWriteComplete(dwTransid,hGroup,hrMastererr,dwCount,pClienthandles,pErrors);
end;
function TOPCDataCallback.OnCancelComplete(dwTransid: DWORD;hGroup: OPCHANDLE): HResult;
begin
Result := S_OK;
if Assigned(VOnCancelComplete) then VOnCancelComplete(dwTransid,hGroup);
end;
end.
|
(*
Category: SWAG Title: TEXT/GRAPHICS COLORS
Original name: 0017.PAS
Description: Background/Foreground
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:34
*)
{
YZ> Does anyone know how to "extract" the Foreground and
YZ> background colours from
YZ> TextAttr?
or, For simplicity, use:
FC := TextAttr MOD 16;
BC := TextAttr div 16;
}
program colors;
uses crt;
var
fc, bc: byte;
begin
textAttr := 30;
WriteLn('Hi!');
FC := TextAttr MOD 16;
BC := TextAttr div 16;
WriteLn('FC=',fc,' BC=',bc);
textcolor(fc);
textbackground(bc);
WriteLn('Hi 2!');
end.
|
unit fmRazpDelOpt;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Buttons;
type
TfmRazpDeleteOpt = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
bbOk: TBitBtn;
bbCancel: TBitBtn;
gbTurnus: TGroupBox;
rbDelAll: TRadioButton;
rbDelTur: TRadioButton;
cbIzmena1: TCheckBox;
cbIzmena2: TCheckBox;
cbIzmena3: TCheckBox;
cbPrazniki: TCheckBox;
cbDelovniki: TCheckBox;
cbSobote: TCheckBox;
cbNedelje: TCheckBox;
procedure rbDelAllClick(Sender: TObject);
procedure rbDelTurClick(Sender: TObject);
private
{ Private declarations }
procedure EnableDisableCB;
public
{ Public declarations }
end;
var
fmRazpDeleteOpt: TfmRazpDeleteOpt;
implementation
{$R *.dfm}
procedure TfmRazpDeleteOpt.EnableDisableCB;
begin
if rbDelAll.Checked then begin
cbIzmena1.Enabled := false;
cbIzmena2.Enabled := false;
cbIzmena3.Enabled := false;
cbPrazniki.Enabled := false;
cbDelovniki.Enabled := false;
cbSobote.Enabled := false;
cbNedelje.Enabled := false;
end else begin
cbIzmena1.Enabled := true;
cbIzmena2.Enabled := true;
cbIzmena3.Enabled := true;
cbPrazniki.Enabled := true;
cbDelovniki.Enabled := true;
cbSobote.Enabled := true;
cbNedelje.Enabled := true;
end;
end;
procedure TfmRazpDeleteOpt.rbDelAllClick(Sender: TObject);
begin
EnableDisableCB;
end;
procedure TfmRazpDeleteOpt.rbDelTurClick(Sender: TObject);
begin
EnableDisableCB;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [COMPRA_PEDIDO]
The MIT License
Copyright: Copyright (C) 2015 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit CompraPedidoVO;
{$mode objfpc}{$H+}
interface
uses
VO, Classes, SysUtils, FGL,
ViewPessoaFornecedorVO, CompraTipoPedidoVO, CompraPedidoDetalheVO,
CompraCotacaoPedidoDetalheVO;
type
TCompraPedidoVO = class(TVO)
private
FID: Integer;
FID_COMPRA_TIPO_PEDIDO: Integer;
FID_FORNECEDOR: Integer;
FDATA_PEDIDO: TDateTime;
FDATA_PREVISTA_ENTREGA: TDateTime;
FDATA_PREVISAO_PAGAMENTO: TDateTime;
FLOCAL_ENTREGA: String;
FLOCAL_COBRANCA: String;
FCONTATO: String;
FVALOR_SUBTOTAL: Extended;
FTAXA_DESCONTO: Extended;
FVALOR_DESCONTO: Extended;
FVALOR_TOTAL_PEDIDO: Extended;
FTIPO_FRETE: String;
FFORMA_PAGAMENTO: String;
FBASE_CALCULO_ICMS: Extended;
FVALOR_ICMS: Extended;
FBASE_CALCULO_ICMS_ST: Extended;
FVALOR_ICMS_ST: Extended;
FVALOR_TOTAL_PRODUTOS: Extended;
FVALOR_FRETE: Extended;
FVALOR_SEGURO: Extended;
FVALOR_OUTRAS_DESPESAS: Extended;
FVALOR_IPI: Extended;
FVALOR_TOTAL_NF: Extended;
FQUANTIDADE_PARCELAS: Integer;
FDIAS_PRIMEIRO_VENCIMENTO: Integer;
FDIAS_INTERVALO: Integer;
//Transientes
FFornecedorNome: String;
FCompraTipoPedidoNome: String;
FFornecedorVO: TViewPessoaFornecedorVO;
FCompraTipoPedidoVO: TCompraTipoPedidoVO;
FListaCompraPedidoDetalheVO: TListaCompraPedidoDetalheVO;
FListaCompraCotacaoPedidoDetalheVO: TListaCompraCotacaoPedidoDetalheVO;
published
constructor Create; override;
destructor Destroy; override;
property Id: Integer read FID write FID;
property IdCompraTipoPedido: Integer read FID_COMPRA_TIPO_PEDIDO write FID_COMPRA_TIPO_PEDIDO;
property CompraTipoPedidoNome: String read FCompraTipoPedidoNome write FCompraTipoPedidoNome;
property IdFornecedor: Integer read FID_FORNECEDOR write FID_FORNECEDOR;
property FornecedorNome: String read FFornecedorNome write FFornecedorNome;
property DataPedido: TDateTime read FDATA_PEDIDO write FDATA_PEDIDO;
property DataPrevistaEntrega: TDateTime read FDATA_PREVISTA_ENTREGA write FDATA_PREVISTA_ENTREGA;
property DataPrevisaoPagamento: TDateTime read FDATA_PREVISAO_PAGAMENTO write FDATA_PREVISAO_PAGAMENTO;
property LocalEntrega: String read FLOCAL_ENTREGA write FLOCAL_ENTREGA;
property LocalCobranca: String read FLOCAL_COBRANCA write FLOCAL_COBRANCA;
property Contato: String read FCONTATO write FCONTATO;
property ValorSubtotal: Extended read FVALOR_SUBTOTAL write FVALOR_SUBTOTAL;
property TaxaDesconto: Extended read FTAXA_DESCONTO write FTAXA_DESCONTO;
property ValorDesconto: Extended read FVALOR_DESCONTO write FVALOR_DESCONTO;
property ValorTotalPedido: Extended read FVALOR_TOTAL_PEDIDO write FVALOR_TOTAL_PEDIDO;
property TipoFrete: String read FTIPO_FRETE write FTIPO_FRETE;
property FormaPagamento: String read FFORMA_PAGAMENTO write FFORMA_PAGAMENTO;
property BaseCalculoIcms: Extended read FBASE_CALCULO_ICMS write FBASE_CALCULO_ICMS;
property ValorIcms: Extended read FVALOR_ICMS write FVALOR_ICMS;
property BaseCalculoIcmsSt: Extended read FBASE_CALCULO_ICMS_ST write FBASE_CALCULO_ICMS_ST;
property ValorIcmsSt: Extended read FVALOR_ICMS_ST write FVALOR_ICMS_ST;
property ValorTotalProdutos: Extended read FVALOR_TOTAL_PRODUTOS write FVALOR_TOTAL_PRODUTOS;
property ValorFrete: Extended read FVALOR_FRETE write FVALOR_FRETE;
property ValorSeguro: Extended read FVALOR_SEGURO write FVALOR_SEGURO;
property ValorOutrasDespesas: Extended read FVALOR_OUTRAS_DESPESAS write FVALOR_OUTRAS_DESPESAS;
property ValorIpi: Extended read FVALOR_IPI write FVALOR_IPI;
property ValorTotalNf: Extended read FVALOR_TOTAL_NF write FVALOR_TOTAL_NF;
property QuantidadeParcelas: Integer read FQUANTIDADE_PARCELAS write FQUANTIDADE_PARCELAS;
property DiasPrimeiroVencimento: Integer read FDIAS_PRIMEIRO_VENCIMENTO write FDIAS_PRIMEIRO_VENCIMENTO;
property DiasIntervalo: Integer read FDIAS_INTERVALO write FDIAS_INTERVALO;
//Transientes
property CompraTipoPedidoVO: TCompraTipoPedidoVO read FCompraTipoPedidoVO write FCompraTipoPedidoVO;
property FornecedorVO: TViewPessoaFornecedorVO read FFornecedorVO write FFornecedorVO;
property ListaCompraPedidoDetalheVO: TListaCompraPedidoDetalheVO read FListaCompraPedidoDetalheVO write FListaCompraPedidoDetalheVO;
property ListaCompraCotacaoPedidoDetalheVO: TListaCompraCotacaoPedidoDetalheVO read FListaCompraCotacaoPedidoDetalheVO write FListaCompraCotacaoPedidoDetalheVO;
end;
TListaCompraPedidoVO = specialize TFPGObjectList<TCompraPedidoVO>;
implementation
constructor TCompraPedidoVO.Create;
begin
inherited;
FFornecedorVO := TViewPessoaFornecedorVO.Create;
FCompraTipoPedidoVO := TCompraTipoPedidoVO.Create;
FListaCompraPedidoDetalheVO := TListaCompraPedidoDetalheVO.Create;
FListaCompraCotacaoPedidoDetalheVO := TListaCompraCotacaoPedidoDetalheVO.Create;
end;
destructor TCompraPedidoVO.Destroy;
begin
FreeAndNil(FFornecedorVO);
FreeAndNil(FCompraTipoPedidoVO);
FreeAndNil(FListaCompraPedidoDetalheVO);
FreeAndNil(FListaCompraCotacaoPedidoDetalheVO);
inherited;
end;
initialization
Classes.RegisterClass(TCompraPedidoVO);
finalization
Classes.UnRegisterClass(TCompraPedidoVO);
end.
|
unit Grijjy.OpenSSL.API;
{ Provides an interface to OpenSSL }
{$I Grijjy.inc}
interface
uses
System.Classes,
{$IF Defined(MSWINDOWS)}
Windows,
{$ELSEIF Defined(LINUX)}
{$ELSE}
{$MESSAGE Error 'Unsupported Platform'}
{$ENDIF}
System.SyncObjs,
System.SysUtils;
const
{$IFNDEF MSWINDOWS}
SSLEAY_DLL = 'libssl.so.1.0.0';
LIBEAY_DLL = 'libcrypto.so.1.0.0';
{$ELSE}
SSLEAY_DLL = 'ssleay32.dll';
LIBEAY_DLL = 'libeay32.dll';
{$ENDIF}
const
SSL_ERROR_NONE = 0;
SSL_ERROR_SSL = 1;
SSL_ERROR_WANT_READ = 2;
SSL_ERROR_WANT_WRITE = 3;
SSL_ERROR_WANT_X509_LOOKUP = 4;
SSL_ERROR_SYSCALL = 5;
SSL_ERROR_ZERO_RETURN = 6;
SSL_ERROR_WANT_CONNECT = 7;
SSL_ERROR_WANT_ACCEPT = 8;
SSL_ST_CONNECT = $1000;
SSL_ST_ACCEPT = $2000;
SSL_ST_MASK = $0FFF;
SSL_ST_INIT = (SSL_ST_CONNECT or SSL_ST_ACCEPT);
SSL_ST_BEFORE = $4000;
SSL_ST_OK = $03;
SSL_ST_RENEGOTIATE = ($04 or SSL_ST_INIT);
SSL_OP_ALL = $000FFFFF;
SSL_OP_NO_SSLv2 = $01000000;
SSL_OP_NO_SSLv3 = $02000000;
SSL_OP_NO_COMPRESSION = $00020000;
SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS = $00000800;
BIO_CTRL_INFO = 3;
BIO_CTRL_PENDING = 10;
SSL_VERIFY_NONE = $00;
CRYPTO_LOCK = 1;
CRYPTO_UNLOCK = 2;
CRYPTO_READ = 4;
CRYPTO_WRITE = 8;
BIO_FLAGS_READ = 1;
BIO_FLAGS_WRITE = 2;
BIO_FLAGS_IO_SPECIAL = 4;
BIO_FLAGS_RWS = (BIO_FLAGS_READ or BIO_FLAGS_WRITE or BIO_FLAGS_IO_SPECIAL);
BIO_FLAGS_SHOULD_RETRY = 8;
BIO_NOCLOSE = 0;
BIO_CLOSE = 1;
type
size_t = NativeUInt;
TSSL_METHOD = packed record
end;
PSSL_METHOD = ^TSSL_METHOD;
TSSL_CTX = packed record
end;
PSSL_CTX = ^TSSL_CTX;
TBIO = packed record
end;
PBIO = ^TBIO;
PPBIO = ^PBIO;
TSSL = packed record
end;
PSSL = ^TSSL;
TX509_STORE = packed record
end;
PX509_STORE = ^TX509_STORE;
TEVP_PKEY = packed record
end;
PEVP_PKEY = ^TEVP_PKEY;
PPEVP_PKEY = ^PEVP_PKEY;
PEVP_PKEY_CTX = Pointer;
PEVP_MD_CTX = Pointer;
PEVP_MD = Pointer;
ENGINE = Pointer;
TX509 = packed record
end;
PX509 = ^TX509;
PPX509 = ^PX509;
TASN1_STRING = record
length: Integer;
type_: Integer;
data: MarshaledAString;
flags: Longword;
end;
PASN1_STRING = ^TASN1_STRING;
TASN1_OCTET_STRING = TASN1_STRING;
PASN1_OCTET_STRING = ^TASN1_OCTET_STRING;
TASN1_BIT_STRING = TASN1_STRING;
PASN1_BIT_STRING = ^TASN1_BIT_STRING;
TSetVerify_cb = function(Ok: Integer; StoreCtx: PX509_STORE): Integer; cdecl;
TCRYPTO_THREADID = packed record
end;
PCRYPTO_THREADID = ^TCRYPTO_THREADID;
TCRYPTO_dynlock_value = record
Mutex: TCriticalSection;
end;
PCRYPTO_dynlock_value = ^TCRYPTO_dynlock_value;
CRYPTO_dynlock_value = TCRYPTO_dynlock_value;
TBIO_METHOD = packed record
end;
PBIO_METHOD = ^TBIO_METHOD;
TX509_NAME = packed record
end;
PX509_NAME = ^TX509_NAME;
TSTACK = packed record
end;
PSTACK = ^TSTACK;
TASN1_OBJECT = packed record
end;
PASN1_OBJECT = ^TASN1_OBJECT;
TStatLockLockCallback = procedure(Mode: Integer; N: Integer; const _File: MarshaledAString; Line: Integer); cdecl;
TStatLockIDCallback = function: Longword; cdecl;
TCryptoThreadIDCallback = procedure(ID: PCRYPTO_THREADID) cdecl;
TDynLockCreateCallback = function(const _file: MarshaledAString; Line: Integer): PCRYPTO_dynlock_value; cdecl;
TDynLockLockCallback = procedure(Mode: Integer; L: PCRYPTO_dynlock_value; _File: MarshaledAString; Line: Integer); cdecl;
TDynLockDestroyCallback = procedure(L: PCRYPTO_dynlock_value; _File: MarshaledAString; Line: Integer); cdecl;
pem_password_cb = function(buf: Pointer; size: Integer; rwflag: Integer; userdata: Pointer): Integer; cdecl;
TgoSSLHelper = class
private class var
FTarget: Integer;
public
class procedure LoadSSL;
class procedure UnloadSSL;
class procedure SetCertificate(ctx: PSSL_CTX; const ACertificate, APrivateKey: TBytes;
const APassword: UnicodeString = ''); overload;
class procedure SetCertificate(ctx: PSSL_CTX; const ACertificateFile, APrivateKeyFile: UnicodeString;
const APassword: UnicodeString = ''); overload;
public
class function Sign_RSASHA256(const AData: TBytes; const APrivateKey: TBytes;
out ASignature: TBytes): Boolean;
end;
var
SSL_library_init: function: Integer; cdecl = nil;
SSL_load_error_strings: procedure; cdecl = nil;
SSLv3_method: function: PSSL_METHOD; cdecl = nil;
SSLv23_method: function: PSSL_METHOD; cdecl = nil;
TLSv1_method: function: PSSL_METHOD; cdecl = nil;
TLSv1_1_method: function: PSSL_METHOD; cdecl = nil;
SSL_CTX_new: function(meth: PSSL_METHOD): PSSL_CTX; cdecl = nil;
SSL_CTX_free: procedure(ctx: PSSL_CTX); cdecl = nil;
SSL_CTX_set_verify: procedure(ctx: PSSL_CTX; mode: Integer; callback: TSetVerify_cb); cdecl = nil;
SSL_CTX_use_PrivateKey: function(ctx: PSSL_CTX; pkey: PEVP_PKEY): Integer; cdecl = nil;
SSL_CTX_use_RSAPrivateKey: function(ctx: PSSL_CTX; pkey: PEVP_PKEY): Integer; cdecl = nil;
SSL_CTX_use_certificate: function(ctx: PSSL_CTX; x: PX509): Integer; cdecl = nil;
SSL_CTX_check_private_key: function(ctx: PSSL_CTX): Integer; cdecl = nil;
SSL_CTX_use_certificate_file: function(ctx: PSSL_CTX; f: MarshaledAString; t: Integer): Integer; cdecl = nil;
SSL_CTX_use_RSAPrivateKey_file: function(ctx: PSSL_CTX; f: MarshaledAString; t: Integer): Integer; cdecl = nil;
SSL_CTX_get_cert_store: function(ctx: PSSL_CTX): PX509_STORE; cdecl = nil;
SSL_CTX_ctrl: function(ctx: PSSL_CTX; cmd, i: integer; p: pointer): Integer; cdecl = nil;
SSL_CTX_load_verify_locations: function(ctx: PSSL_CTX; CAFile: MarshaledAString; CAPath: MarshaledAString): Integer; cdecl = nil;
SSL_CTX_use_certificate_chain_file: function(ctx: PSSL_CTX; CAFile: MarshaledAString): Integer; cdecl = nil;
SSL_CTX_set_alpn_protos: function(ctx: PSSL_CTX; protos: MarshaledAString; protos_len: Integer): Integer; cdecl = nil;
SSL_new: function(ctx: PSSL_CTX): PSSL; cdecl = nil;
SSL_set_bio: procedure(s: PSSL; rbio, wbio: PBIO); cdecl = nil;
SSL_get_peer_certificate: function(s: PSSL): PX509; cdecl = nil;
SSL_get_error: function(s: PSSL; ret_code: Integer): Integer; cdecl = nil;
SSL_shutdown: function(s: PSSL): Integer; cdecl = nil;
SSL_free: procedure(s: PSSL); cdecl = nil;
SSL_connect: function(s: PSSL): Integer; cdecl = nil;
SSL_set_connect_state: procedure(s: PSSL); cdecl = nil;
SSL_set_accept_state: procedure(s: PSSL); cdecl = nil;
SSL_read: function(s: PSSL; buf: Pointer; num: Integer): Integer; cdecl = nil;
SSL_write: function(s: PSSL; const buf: Pointer; num: Integer): Integer; cdecl = nil;
SSL_state: function(s: PSSL): Integer; cdecl = nil;
SSL_pending: function(s: PSSL): Integer; cdecl = nil;
SSL_set_cipher_list: function(s: PSSL; ciphers: MarshaledAString): Integer; cdecl = nil;
SSL_get0_alpn_selected: procedure (s: PSSL; out data: MarshaledAString; out len: Integer); cdecl = nil;
SSL_clear: function(s: PSSL): Integer; cdecl = nil;
CRYPTO_num_locks: function: Integer; cdecl = nil;
CRYPTO_set_locking_callback: procedure(callback: TStatLockLockCallback); cdecl = nil;
CRYPTO_set_dynlock_create_callback: procedure(callback: TDynLockCreateCallBack); cdecl = nil;
CRYPTO_set_dynlock_lock_callback: procedure(callback: TDynLockLockCallBack); cdecl = nil;
CRYPTO_set_dynlock_destroy_callback: procedure(callback: TDynLockDestroyCallBack); cdecl = nil;
CRYPTO_cleanup_all_ex_data: procedure; cdecl = nil;
ERR_remove_state: procedure(tid: Cardinal); cdecl = nil;
ERR_free_strings: procedure; cdecl = nil; // thread-unsafe, Application-global cleanup functions
ERR_error_string_n: procedure(err: Cardinal; buf: MarshaledAString; len: size_t); cdecl = nil;
ERR_get_error: function: Cardinal; cdecl = nil;
ERR_remove_thread_state: procedure(pid: Cardinal); cdecl = nil;
ERR_load_BIO_strings: function: Cardinal; cdecl = nil;
EVP_cleanup: procedure; cdecl = nil;
EVP_PKEY_free: procedure(pkey: PEVP_PKEY); cdecl = nil;
BIO_new: function(BioMethods: PBIO_METHOD): PBIO; cdecl = nil;
BIO_ctrl: function(bp: PBIO; cmd: Integer; larg: Longint; parg: Pointer): Longint; cdecl = nil;
BIO_new_mem_buf: function(buf: Pointer; len: Integer): PBIO; cdecl = nil;
BIO_free: function(b: PBIO): Integer; cdecl = nil;
BIO_s_mem: function: PBIO_METHOD; cdecl = nil;
BIO_read: function(b: PBIO; Buf: Pointer; Len: Integer): Integer; cdecl = nil;
BIO_write: function(b: PBIO; Buf: Pointer; Len: Integer): Integer; cdecl = nil;
BIO_new_socket: function(sock: Integer; close_flag: Integer): PBIO; cdecl = nil;
X509_get_issuer_name: function(cert: PX509): PX509_NAME; cdecl = nil;
X509_get_subject_name: function(cert: PX509): PX509_NAME; cdecl = nil;
X509_free: procedure(cert: PX509); cdecl = nil;
X509_NAME_print_ex: function(bout: PBIO; nm: PX509_NAME; indent: Integer; flags: Cardinal): Integer; cdecl = nil;
sk_num: function(stack: PSTACK): Integer; cdecl = nil;
sk_pop: function(stack: PSTACK): Pointer; cdecl = nil;
ASN1_BIT_STRING_get_bit: function(a: PASN1_BIT_STRING; n: Integer): Integer; cdecl = nil;
OBJ_obj2nid: function(o: PASN1_OBJECT): Integer; cdecl = nil;
OBJ_nid2sn: function(n: Integer): MarshaledAString; cdecl = nil;
ASN1_STRING_data: function(x: PASN1_STRING): Pointer; cdecl = nil;
PEM_read_bio_X509: function(bp: PBIO; x: PX509; cb: pem_password_cb; u: Pointer): PX509; cdecl = nil;
PEM_read_bio_PrivateKey: function(bp: PBIO; x: PPEVP_PKEY; cb: pem_password_cb; u: Pointer): PEVP_PKEY; cdecl = nil;
PEM_read_bio_RSAPrivateKey: function(bp: PBIO; x: PPEVP_PKEY; cb: pem_password_cb; u: Pointer): PEVP_PKEY; cdecl = nil;
EVP_MD_CTX_create: function: PEVP_MD_CTX; cdecl = nil;
EVP_MD_CTX_destroy: procedure(ctx: PEVP_MD_CTX); cdecl = nil;
EVP_sha256: function: PEVP_MD; cdecl = nil;
EVP_PKEY_size: function(key: PEVP_PKEY): Integer; cdecl = nil;
EVP_DigestSignInit: function(aCtx: PEVP_MD_CTX; aPCtx: PEVP_PKEY_CTX; aType: PEVP_MD; aEngine: ENGINE; aKey: PEVP_PKEY): Integer; cdecl = nil;
EVP_DigestUpdate: function(ctx: PEVP_MD_CTX; const d: Pointer; cnt: Cardinal): Integer; cdecl = nil;
EVP_DigestSignFinal: function(ctx : PEVP_MD_CTX; const d: PByte; var cnt: Cardinal): Integer; cdecl = nil;
EVP_DigestVerifyInit: function(aCtx: PEVP_MD_CTX; aPCtx: PEVP_PKEY_CTX; aType: PEVP_MD; aEngine: ENGINE; aKey: pEVP_PKEY): Integer; cdecl = nil;
EVP_DigestVerifyFinal: function(ctx : pEVP_MD_CTX; const d: PByte; cnt: Cardinal) : Integer; cdecl = nil;
CRYPTO_malloc: function(aLength : LongInt; const f : MarshaledAString; aLine : Integer): Pointer; cdecl= nil;
CRYPTO_free: procedure(str: Pointer); cdecl= nil;
function BIO_pending(bp: PBIO): Integer; inline;
function BIO_get_mem_data(bp: PBIO; parg: Pointer): Integer; inline;
function BIO_get_flags(b: PBIO): Integer; inline;
function BIO_should_retry(b: PBIO): Boolean; inline;
function SSL_CTX_set_options(ctx: pointer; op: integer): integer;
function SSL_is_init_finished(s: PSSL): Boolean; inline;
function SSL_is_fatal_error(ssl_error: Integer): Boolean;
function SSL_error(ssl: PSSL; ret_code: Integer; out AErrorMsg: UnicodeString): Integer;
function sk_ASN1_OBJECT_num(stack: PSTACK): Integer; inline;
function sk_GENERAL_NAME_num(stack: PSTACK): Integer; inline;
function sk_GENERAL_NAME_pop(stack: PSTACK): Pointer; inline;
implementation
uses
System.IOUtils;
var
_SSLEAYHandle, _LIBEAYHandle: HMODULE;
_FSSLLocks: TArray<TCriticalSection>;
function BIO_pending(bp: PBIO): Integer;
begin
Result := BIO_ctrl(bp, BIO_CTRL_PENDING, 0, nil);
end;
function BIO_get_mem_data(bp: PBIO; parg: Pointer): Integer;
begin
Result := BIO_ctrl(bp, BIO_CTRL_INFO, 0, parg);
end;
function sk_ASN1_OBJECT_num(stack: PSTACK): Integer;
begin
Result := sk_num(stack);
end;
function sk_GENERAL_NAME_num(stack: PSTACK): Integer;
begin
Result := sk_num(stack);
end;
function sk_GENERAL_NAME_pop(stack: PSTACK): Pointer;
begin
Result := sk_pop(stack);
end;
function BIO_get_flags(b: PBIO): Integer;
begin
Result := PInteger(MarshaledAString(b) + 3 * SizeOf(Pointer) + 2 * SizeOf(Integer))^;
end;
function BIO_should_retry(b: PBIO): Boolean;
begin
Result := ((BIO_get_flags(b) and BIO_FLAGS_SHOULD_RETRY) <> 0);
end;
function SSL_CTX_set_options(ctx: pointer; op: integer): integer;
const
SSL_CTRL_OPTIONS = 32;
begin
result := SSL_CTX_ctrl(ctx, SSL_CTRL_OPTIONS, op, nil);
end;
function SSL_is_init_finished(s: PSSL): Boolean; inline;
begin
Result := (SSL_state(s) = SSL_ST_OK);
end;
function SSL_is_fatal_error(ssl_error: Integer): Boolean;
begin
case ssl_error of
SSL_ERROR_NONE,
SSL_ERROR_WANT_READ,
SSL_ERROR_WANT_WRITE,
SSL_ERROR_WANT_CONNECT,
SSL_ERROR_WANT_ACCEPT: Result := False;
else
Result := True;
end;
end;
function SSL_error(ssl: PSSL; ret_code: Integer; out AErrorMsg: UnicodeString): Integer;
var
error, error_log: Integer;
ErrorBuf: TBytes;
begin
error := SSL_get_error(ssl, ret_code);
if(error <> SSL_ERROR_NONE) then
begin
error_log := error;
while (error_log <> SSL_ERROR_NONE) do
begin
SetLength(ErrorBuf, 512);
ERR_error_string_n(error_log, @ErrorBuf[0], Length(ErrorBuf));
if (SSL_is_fatal_error(error_log)) then
AErrorMsg := StringOf(ErrorBuf);
error_log := ERR_get_error();
end;
end;
Result := error;
end;
function LoadLib(const ALibFile: String): HMODULE;
begin
Result := LoadLibrary(PChar(ALibFile));
if (Result = 0) then
raise Exception.CreateFmt('load %s failed', [ALibFile]);
end;
function FreeLib(ALibModule: HMODULE): Boolean;
begin
Result := FreeLibrary(ALibModule);
end;
function GetProc(AModule: HMODULE; const AProcName: String): Pointer;
begin
Result := GetProcAddress(AModule, PChar(AProcName));
if (Result = nil) then
raise Exception.CreateFmt('%s is not found', [AProcName]);
end;
procedure LoadSSLEAY;
begin
if (_SSLEAYHandle <> 0) then Exit;
_SSLEAYHandle := LoadLib(SSLEAY_DLL);
if (_SSLEAYHandle = 0) then
begin
raise Exception.CreateFmt('Load %s failed', [SSLEAY_DLL]);
Exit;
end;
SSL_library_init := GetProc(_SSLEAYHandle, 'SSL_library_init');
SSL_load_error_strings := GetProc(_SSLEAYHandle, 'SSL_load_error_strings');
SSLv3_method := GetProc(_SSLEAYHandle, 'SSLv3_method');
SSLv23_method := GetProc(_SSLEAYHandle, 'SSLv23_method');
TLSv1_method := GetProc(_SSLEAYHandle, 'TLSv1_method');
TLSv1_1_method := GetProc(_SSLEAYHandle, 'TLSv1_1_method');
SSL_CTX_new := GetProc(_SSLEAYHandle, 'SSL_CTX_new');
SSL_CTX_free := GetProc(_SSLEAYHandle, 'SSL_CTX_free');
SSL_CTX_set_verify := GetProc(_SSLEAYHandle, 'SSL_CTX_set_verify');
SSL_CTX_use_PrivateKey := GetProc(_SSLEAYHandle, 'SSL_CTX_use_PrivateKey');
SSL_CTX_use_RSAPrivateKey := GetProc(_SSLEAYHandle, 'SSL_CTX_use_RSAPrivateKey');
SSL_CTX_use_certificate := GetProc(_SSLEAYHandle, 'SSL_CTX_use_certificate');
SSL_CTX_check_private_key := GetProc(_SSLEAYHandle, 'SSL_CTX_check_private_key');
SSL_CTX_use_certificate_file := GetProc(_SSLEAYHandle, 'SSL_CTX_use_certificate_file');
SSL_CTX_use_RSAPrivateKey_file := GetProc(_SSLEAYHandle, 'SSL_CTX_use_RSAPrivateKey_file');
SSL_CTX_get_cert_store := GetProc(_SSLEAYHandle, 'SSL_CTX_get_cert_store');
SSL_CTX_ctrl := GetProc(_SSLEAYHandle, 'SSL_CTX_ctrl');
SSL_CTX_load_verify_locations := GetProc(_SSLEAYHandle, 'SSL_CTX_load_verify_locations');
SSL_CTX_use_certificate_chain_file := GetProc(_SSLEAYHandle, 'SSL_CTX_use_certificate_chain_file');
SSL_CTX_set_alpn_protos := GetProc(_SSLEAYHandle, 'SSL_CTX_set_alpn_protos');
SSL_new := GetProc(_SSLEAYHandle, 'SSL_new');
SSL_set_bio := GetProc(_SSLEAYHandle, 'SSL_set_bio');
SSL_get_peer_certificate := GetProc(_SSLEAYHandle, 'SSL_get_peer_certificate');
SSL_get_error := GetProc(_SSLEAYHandle, 'SSL_get_error');
SSL_shutdown := GetProc(_SSLEAYHandle, 'SSL_shutdown');
SSL_free := GetProc(_SSLEAYHandle, 'SSL_free');
SSL_connect := GetProc(_SSLEAYHandle, 'SSL_connect');
SSL_set_connect_state := GetProc(_SSLEAYHandle, 'SSL_set_connect_state');
SSL_set_accept_state := GetProc(_SSLEAYHandle, 'SSL_set_accept_state');
SSL_read := GetProc(_SSLEAYHandle, 'SSL_read');
SSL_write := GetProc(_SSLEAYHandle, 'SSL_write');
SSL_state := GetProc(_SSLEAYHandle, 'SSL_state');
SSL_pending := GetProc(_SSLEAYHandle, 'SSL_pending');
SSL_set_cipher_list := GetProc(_SSLEAYHandle, 'SSL_set_cipher_list');
SSL_get0_alpn_selected := GetProc(_SSLEAYHandle, 'SSL_get0_alpn_selected');
SSL_clear := GetProc(_SSLEAYHandle, 'SSL_clear');
end;
procedure UnloadSSLEAY;
begin
if (_SSLEAYHandle = 0) then Exit;
FreeLib(_SSLEAYHandle);
_SSLEAYHandle := 0;
end;
procedure LoadLIBEAY;
begin
if (_LIBEAYHandle <> 0) then Exit;
_LIBEAYHandle := LoadLib(LIBEAY_DLL);
if (_LIBEAYHandle = 0) then
begin
raise Exception.CreateFmt('Load %s failed', [LIBEAY_DLL]);
Exit;
end;
CRYPTO_malloc := GetProc(_LIBEAYHandle, 'CRYPTO_malloc');
CRYPTO_free := GetProc(_LIBEAYHandle, 'CRYPTO_free');
CRYPTO_num_locks := GetProc(_LIBEAYHandle, 'CRYPTO_num_locks');
CRYPTO_set_locking_callback := GetProc(_LIBEAYHandle, 'CRYPTO_set_locking_callback');
CRYPTO_set_dynlock_create_callback := GetProc(_LIBEAYHandle, 'CRYPTO_set_dynlock_create_callback');
CRYPTO_set_dynlock_lock_callback := GetProc(_LIBEAYHandle, 'CRYPTO_set_dynlock_lock_callback');
CRYPTO_set_dynlock_destroy_callback := GetProc(_LIBEAYHandle, 'CRYPTO_set_dynlock_destroy_callback');
CRYPTO_cleanup_all_ex_data := GetProc(_LIBEAYHandle, 'CRYPTO_cleanup_all_ex_data');
ERR_remove_state := GetProc(_LIBEAYHandle, 'ERR_remove_state');
ERR_free_strings := GetProc(_LIBEAYHandle, 'ERR_free_strings');
ERR_error_string_n := GetProc(_LIBEAYHandle, 'ERR_error_string_n');
ERR_get_error := GetProc(_LIBEAYHandle, 'ERR_get_error');
ERR_remove_thread_state := GetProc(_LIBEAYHandle, 'ERR_remove_thread_state');
ERR_load_BIO_strings := GetProc(_LIBEAYHandle, 'ERR_load_BIO_strings');
EVP_cleanup := GetProc(_LIBEAYHandle, 'EVP_cleanup');
EVP_MD_CTX_create := GetProc(_LIBEAYHandle, 'EVP_MD_CTX_create');
EVP_MD_CTX_destroy := GetProc(_LIBEAYHandle, 'EVP_MD_CTX_destroy');
EVP_sha256 := GetProc(_LIBEAYHandle, 'EVP_sha256');
EVP_PKEY_size := GetProc(_LIBEAYHandle, 'EVP_PKEY_size');
EVP_DigestSignInit := GetProc(_LIBEAYHandle, 'EVP_DigestSignInit');
EVP_DigestUpdate := GetProc(_LIBEAYHandle, 'EVP_DigestUpdate');
EVP_DigestSignFinal := GetProc(_LIBEAYHandle, 'EVP_DigestSignFinal');
EVP_DigestVerifyInit := GetProc(_LIBEAYHandle, 'EVP_DigestVerifyInit');
EVP_DigestVerifyFinal := GetProc(_LIBEAYHandle, 'EVP_DigestVerifyFinal');
EVP_PKEY_free := GetProc(_LIBEAYHandle, 'EVP_PKEY_free');
BIO_new := GetProc(_LIBEAYHandle, 'BIO_new');
BIO_ctrl := GetProc(_LIBEAYHandle, 'BIO_ctrl');
BIO_new_mem_buf := GetProc(_LIBEAYHandle, 'BIO_new_mem_buf');
BIO_free := GetProc(_LIBEAYHandle, 'BIO_free');
BIO_s_mem := GetProc(_LIBEAYHandle, 'BIO_s_mem');
BIO_read := GetProc(_LIBEAYHandle, 'BIO_read');
BIO_write := GetProc(_LIBEAYHandle, 'BIO_write');
BIO_new_socket := GetProc(_LIBEAYHandle, 'BIO_new_socket');
X509_get_issuer_name := GetProc(_LIBEAYHandle, 'X509_get_issuer_name');
X509_get_subject_name := GetProc(_LIBEAYHandle, 'X509_get_subject_name');
X509_free := GetProc(_LIBEAYHandle, 'X509_free');
X509_NAME_print_ex := GetProc(_LIBEAYHandle, 'X509_NAME_print_ex');
sk_num := GetProc(_LIBEAYHandle, 'sk_num');
sk_pop := GetProc(_LIBEAYHandle, 'sk_pop');
ASN1_BIT_STRING_get_bit := GetProc(_LIBEAYHandle, 'ASN1_BIT_STRING_get_bit');
OBJ_obj2nid := GetProc(_LIBEAYHandle, 'OBJ_obj2nid');
OBJ_nid2sn := GetProc(_LIBEAYHandle, 'OBJ_nid2sn');
ASN1_STRING_data := GetProc(_LIBEAYHandle, 'ASN1_STRING_data');
PEM_read_bio_X509 := GetProc(_LIBEAYHandle, 'PEM_read_bio_X509');
PEM_read_bio_PrivateKey := GetProc(_LIBEAYHandle, 'PEM_read_bio_PrivateKey');
PEM_read_bio_RSAPrivateKey := GetProc(_LIBEAYHandle, 'PEM_read_bio_RSAPrivateKey');
end;
procedure UnloadLIBEAY;
begin
if (_LIBEAYHandle = 0) then Exit;
FreeLib(_LIBEAYHandle);
_LIBEAYHandle := 0;
end;
procedure ssl_lock_callback(Mode, N: Integer; const _File: MarshaledAString; Line: Integer); cdecl;
begin
if(mode and CRYPTO_LOCK <> 0) then
_FSSLLocks[N].Enter
else
_FSSLLocks[N].Leave;
end;
procedure ssl_lock_dyn_callback(Mode: Integer; L: PCRYPTO_dynlock_value; _File: MarshaledAString; Line: Integer); cdecl;
begin
if (Mode and CRYPTO_LOCK <> 0) then
L.Mutex.Enter
else
L.Mutex.Leave;
end;
function ssl_lock_dyn_create_callback(const _file: MarshaledAString; Line: Integer): PCRYPTO_dynlock_value; cdecl;
begin
New(Result);
Result.Mutex := TCriticalSection.Create;
end;
procedure ssl_lock_dyn_destroy_callback(L: PCRYPTO_dynlock_value; _File: MarshaledAString; Line: Integer); cdecl;
begin
L.Mutex.Free;
Dispose(L);
end;
procedure SslInit;
var
LNumberOfLocks, I: Integer;
begin
if (_SSLEAYHandle = 0) or (_LIBEAYHandle = 0) then Exit;
LNumberOfLocks := CRYPTO_num_locks();
if(LNumberOfLocks > 0) then
begin
SetLength(_FSSLLocks, LNumberOfLocks);
for I := Low(_FSSLLocks) to High(_FSSLLocks) do
_FSSLLocks[I] := TCriticalSection.Create;
end;
CRYPTO_set_locking_callback(ssl_lock_callback);
CRYPTO_set_dynlock_create_callback(ssl_lock_dyn_create_callback);
CRYPTO_set_dynlock_lock_callback(ssl_lock_dyn_callback);
CRYPTO_set_dynlock_destroy_callback(ssl_lock_dyn_destroy_callback);
SSL_load_error_strings();
SSL_library_init();
end;
procedure SslUninit;
var
I: Integer;
begin
if (_SSLEAYHandle = 0) or (_LIBEAYHandle = 0) then Exit;
CRYPTO_set_locking_callback(nil);
CRYPTO_set_dynlock_create_callback(nil);
CRYPTO_set_dynlock_lock_callback(nil);
CRYPTO_set_dynlock_destroy_callback(nil);
EVP_cleanup();
CRYPTO_cleanup_all_ex_data();
ERR_remove_state(0);
ERR_free_strings();
for I := Low(_FSSLLocks) to High(_FSSLLocks) do
_FSSLLocks[I].Free;
_FSSLLocks := nil;
end;
{ TgoSSLHelper }
class procedure TgoSSLHelper.LoadSSL;
begin
if (TInterlocked.Increment(FTarget) = 1) then
begin
LoadLIBEAY;
LoadSSLEAY;
SslInit;
end;
end;
class procedure TgoSSLHelper.UnloadSSL;
begin
{$IFDEF FPC}
if (InterlockedDecrement(FTarget) = 0) then
{$ELSE}
if (TInterlocked.Decrement(FTarget) = 0) then
{$ENDIF}
begin
SslUninit;
UnloadSSLEAY;
UnloadLIBEAY;
end;
end;
class procedure TgoSSLHelper.SetCertificate(ctx: PSSL_CTX; const ACertificate, APrivateKey: TBytes;
const APassword: UnicodeString = '');
var
BIOCert, BIOPrivateKey: PBIO;
Certificate: PX509;
PrivateKey: PEVP_PKEY;
Password: RawByteString;
begin
BIOCert := BIO_new_mem_buf(@ACertificate[0], Length(ACertificate));
BIOPrivateKey := BIO_new_mem_buf(@APrivateKey[0], Length(APrivateKey));
Certificate := PEM_read_bio_X509(BIOCert, nil, nil, nil);
if APassword <> '' then
begin
Password := RawByteString(APassword);
PrivateKey := PEM_read_bio_PrivateKey(BIOPrivateKey, nil, nil, MarshaledAString(Password));
end
else
PrivateKey := PEM_read_bio_PrivateKey(BIOPrivateKey, nil, nil, nil);
SSL_CTX_use_certificate(ctx, Certificate);
SSL_CTX_use_privatekey(ctx, PrivateKey);
X509_free(Certificate);
EVP_PKEY_free(PrivateKey);
BIO_free(BIOCert);
BIO_free(BIOPrivateKey);
if (SSL_CTX_check_private_key(ctx) = 0) then
raise Exception.Create('Private key does not match the certificate public key');
end;
class procedure TgoSSLHelper.SetCertificate(ctx: PSSL_CTX; const ACertificateFile, APrivateKeyFile: UnicodeString;
const APassword: UnicodeString = '');
var
Certificate, PrivateKey: TBytes;
begin
Certificate := TFile.ReadAllBytes(ACertificateFile);
PrivateKey := TFile.ReadAllBytes(APrivateKeyFile);
SetCertificate(ctx, Certificate, PrivateKey, APassword);
end;
class function TgoSSLHelper.Sign_RSASHA256(const AData: TBytes; const APrivateKey: TBytes;
out ASignature: TBytes): Boolean;
var
BIOPrivateKey: PBIO;
PrivateKey: PEVP_PKEY;
Ctx: PEVP_MD_CTX;
SHA256: PEVP_MD;
Size: Cardinal;
begin
BIOPrivateKey := BIO_new_mem_buf(@APrivateKey[0], Length(APrivateKey));
PrivateKey := PEM_read_bio_PrivateKey(BIOPrivateKey, nil, nil, nil);
Ctx := EVP_MD_CTX_create;
try
SHA256 := EVP_sha256;
if (EVP_DigestSignInit(Ctx, nil , SHA256, nil, PrivateKey) > 0) and
(EVP_DigestUpdate(Ctx, @AData[0], Length(AData)) > 0) and
(EVP_DigestSignFinal(Ctx, nil, Size) > 0) then
begin
SetLength(ASignature, Size);
Result := EVP_DigestSignFinal(Ctx, @ASignature[0], Size) > 0;
end
else
Result := False;
finally
EVP_MD_CTX_destroy(Ctx);
end;
end;
end.
|
(*----------------------------------------------------------------------------*
* Direct3D sample from DirectX 9.0 SDK December 2006 *
* Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) *
* *
* Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 *
* *
* Latest version can be downloaded from: *
* http://www.clootie.ru *
* http://sourceforge.net/projects/delphi-dx9sdk *
*----------------------------------------------------------------------------*
* $Id: MeshLoader.pas,v 1.17 2007/02/05 22:21:10 clootie Exp $
*----------------------------------------------------------------------------*)
//--------------------------------------------------------------------------------------
// File: MeshLoader.h, MeshLoader.cpp
//
// Wrapper class for ID3DXMesh interface. Handles loading mesh data from an .obj file
// and resource management for material textures.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
{$I DirectX.inc}
unit MeshLoader;
interface
uses
Windows, Classes, SysUtils, StrSafe,
DXTypes, Direct3D9, D3DX9, DXErr9,
DXUTcore, DXUTMisc;
type
// Vertex format
PVertex = ^TVertex;
TVertex = record
position: TD3DXVector3;
normal: TD3DXVector3;
texcoord: TD3DXVector2;
end;
// Used for a hashtable vertex cache when creating the mesh from a .obj file
PCacheEntry = ^TCacheEntry;
TCacheEntry = record
index: LongWord;
pNext: PCacheEntry;
end;
// Material properties per mesh subset
PMaterial = ^TMaterial;
TMaterial = record
strName: array[0..MAX_PATH-1] of WideChar;
vAmbient: TD3DXVector3;
vDiffuse: TD3DXVector3;
vSpecular: TD3DXVector3;
nShininess: Integer;
fAlpha: Single;
bSpecular: Boolean;
strTexture: array[0..MAX_PATH-1] of WideChar;
pTexture: IDirect3DTexture9; //todo: Warning!!!
hTechnique: TD3DXHandle;
end;
CMeshLoader = class
private
m_pd3dDevice: IDirect3DDevice9; // Direct3D Device object associated with this mesh
m_pMesh: ID3DXMesh; // Encapsulated D3DX Mesh
m_VertexCache: array of PCacheEntry; // Hashtable cache for locating duplicate vertices
m_Vertices: array of TVertex; // Filled and copied to the vertex buffer
m_Indices: array of DWORD; // Filled and copied to the index buffer
m_Attributes: array of DWORD; // Filled and copied to the attribute buffer
m_Materials: array of PMaterial; // Holds material properties per subset
m_strMediaDir: array[0..MAX_PATH-1] of WideChar; // Directory where the mesh was found
function LoadGeometryFromOBJ(const strFilename: PWideChar): HRESULT;
function LoadMaterialsFromMTL(const strFileName: WideString): HRESULT;
procedure InitMaterial(var pMaterial: TMaterial);
function AddVertex(hash: Integer; pVer: PVertex): DWORD;
procedure DeleteCache;
// function GetMesh() { return m_pMesh; }
function GetMediaDirectory: PWideChar; { return m_strMediaDir; }
public
constructor Create;
destructor Destroy; override;
function CreateMesh(const pd3dDevice: IDirect3DDevice9; const strFilename: PWideChar): HRESULT;
procedure DestroyMesh;
function GetNumMaterials: LongWord; // const { return m_Materials.GetSize(); }
function GetMaterial(iMaterial: LongWord): PMaterial; { return m_Materials.GetAt( iMaterial ); }
property Mesh: ID3DXMesh read m_pMesh;
property MediaDirectory: PWideChar read GetMediaDirectory;
property NumMaterials: LongWord read GetNumMaterials;
property Material[iMaterial: LongWord]: PMaterial read GetMaterial;
end;
implementation
//--------------------------------------------------------------------------------------
// File: MeshLoader.cpp
//
// Wrapper class for ID3DXMesh interface. Handles loading mesh data from an .obj file
// and resource management for material textures.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
const
// Vertex declaration
VERTEX_DECL: array[0..3] of TD3DVertexElement9 =
(
(Stream: 0; Offset: 0; _Type: D3DDECLTYPE_FLOAT3; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_POSITION; UsageIndex: 0),
(Stream: 0; Offset: 12; _Type: D3DDECLTYPE_FLOAT3; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_NORMAL; UsageIndex: 0),
(Stream: 0; Offset: 24; _Type: D3DDECLTYPE_FLOAT2; Method: D3DDECLMETHOD_DEFAULT; Usage: D3DDECLUSAGE_TEXCOORD; UsageIndex: 0),
{D3DDECL_END()}(Stream:$FF; Offset:0; _Type:D3DDECLTYPE_UNUSED; Method:TD3DDeclMethod(0); Usage:TD3DDeclUsage(0); UsageIndex:0)
);
{ CMeshLoader }
//--------------------------------------------------------------------------------------
constructor CMeshLoader.Create;
begin
m_pd3dDevice := nil;
m_pMesh := nil;
ZeroMemory(@m_strMediaDir, SizeOf(m_strMediaDir));
end;
//--------------------------------------------------------------------------------------
destructor CMeshLoader.Destroy;
begin
DestroyMesh;
inherited;
end;
//--------------------------------------------------------------------------------------
procedure CMeshLoader.DestroyMesh;
var
iMaterial: Integer;
pMat, pCur: PMaterial;
x: Integer;
begin
for iMaterial := 0 to Length(m_Materials) - 1 do
begin
pMat := m_Materials[iMaterial];
// Avoid releasing the same texture twice
for x := iMaterial+1 to Length(m_Materials) - 1 do
begin
pCur := m_Materials[x];
if (pCur.pTexture = pMat.pTexture) then pCur.pTexture := nil;
end;
pMat.pTexture := nil;
//todo: ?
FreeMem(pMat); // SAFE_DELETE(pMaterial);
end;
m_Materials := nil; // .RemoveAll;
m_Vertices := nil; // .RemoveAll;
m_Indices := nil; // .RemoveAll;
m_Attributes := nil; // .RemoveAll;
m_pMesh := nil;
m_pd3dDevice := nil;
end;
//--------------------------------------------------------------------------------------
function CMeshLoader.CreateMesh(const pd3dDevice: IDirect3DDevice9;
const strFilename: PWideChar): HRESULT;
var
str, wstrOldDir: array[0..MAX_PATH-1] of WideChar;
iMaterial: Integer;
pMat, pCur: PMaterial;
bFound: Boolean;
x: Integer;
pMesh: ID3DXMesh;
pVert: PVertex;
pIndex: PDWORD;
pSubset: PDWORD;
aAdjacency: PDWORD;
begin
ZeroMemory(@str, SizeOf(str));
// Start clean
DestroyMesh;
// Store the device pointer
m_pd3dDevice := pd3dDevice;
// Load the vertex buffer, index buffer, and subset information from a file. In this case,
// an .obj file was chosen for simplicity, but it's meant to illustrate that ID3DXMesh objects
// can be filled from any mesh file format once the necessary data is extracted from file.
Result:= LoadGeometryFromOBJ(strFilename);
if V_Failed(Result) then Exit;
// Set the current directory based on where the mesh was found
// WCHAR wstrOldDir[MAX_PATH] = {0};
GetCurrentDirectoryW(MAX_PATH, wstrOldDir);
SetCurrentDirectoryW(m_strMediaDir);
// Load material textures
for iMaterial := 0 to Length(m_Materials) - 1 do
begin
pMat := m_Materials[iMaterial];
if (pMat.strTexture[0] <> #0) then
begin
// Avoid loading the same texture twice
bFound := False;
for x := 0 to iMaterial - 1 do
begin
pCur := m_Materials[x];
if (0 = lstrcmpW(pCur.strTexture, pMat.strTexture)) then
begin
bFound := True;
pMat.pTexture := pCur.pTexture;
Break;
end;
end;
// Not found, load the texture
if not bFound then
begin
Result := DXUTFindDXSDKMediaFile(str, MAX_PATH, pMat.strTexture);
if V_Failed(Result) then Exit;
Result := D3DXCreateTextureFromFileW(pd3dDevice, pMat.strTexture,
pMat.pTexture);
if V_Failed(Result) then Exit;
end;
end;
end;
// Restore the original current directory
SetCurrentDirectoryW(wstrOldDir);
// Create the encapsulated mesh
Result := D3DXCreateMesh(Length(m_Indices) div 3, Length(m_Vertices),
D3DXMESH_MANAGED or D3DXMESH_32BIT, @VERTEX_DECL,
pd3dDevice, pMesh);
if V_Failed(Result) then Exit;
// Copy the vertex data
Result := pMesh.LockVertexBuffer(0, Pointer(pVert));
if V_Failed(Result) then Exit;
CopyMemory(pVert, m_Vertices, Length(m_Vertices)*SizeOf(TVertex));
pMesh.UnlockVertexBuffer;
m_Vertices := nil; // RemoveAll;
// Copy the index data
Result:= pMesh.LockIndexBuffer(0, Pointer(pIndex));
if V_Failed(Result) then Exit;
CopyMemory(pIndex, m_Indices, Length(m_Indices)*SizeOf(DWORD));
pMesh.UnlockIndexBuffer;
m_Indices := nil; // RemoveAll;
// Copy the attribute data
Result:= pMesh.LockAttributeBuffer(0, pSubset);
if V_Failed(Result) then Exit;
CopyMemory(pSubset, m_Attributes, Length(m_Attributes)*SizeOf(DWORD));
pMesh.UnlockAttributeBuffer;
m_Attributes := nil; // RemoveAll;
// Reorder the vertices according to subset and optimize the mesh for this graphics
// card's vertex cache. When rendering the mesh's triangle list the vertices will
// cache hit more often so it won't have to re-execute the vertex shader.
try
GetMem(aAdjacency, SizeOf(DWORD)*pMesh.GetNumFaces*3);
except
Result:= E_OUTOFMEMORY;
Exit;
end;
V(pMesh.GenerateAdjacency(1e-6, aAdjacency));
V(pMesh.OptimizeInplace(D3DXMESHOPT_ATTRSORT or D3DXMESHOPT_VERTEXCACHE, aAdjacency, nil, nil, nil));
FreeMem(aAdjacency);
m_pMesh := pMesh;
Result:= S_OK;
end;
type
TWifStream = class
private
FHandle: THandle; // File handle
FMappingHandle: THandle; // File Mapping handle
FFilePointer, FFileEnd: PAnsiChar;
FFileSize: LongWord;
//---------------------
FFileName: String;
FDelimiters: String;
FBufferPos, FDelimPos: PChar;
function GetPeek: Char;
function GetRelativeChar(i: Integer): Char;
function GetEOF: Boolean;
public
constructor Create(const aFileName: String);
destructor Destroy; override;
function GetNextToken: String;
function GetNextTokenAsInt(out i: Integer): String;
function GetNextTokenAsFloat(out f: Single): String;
procedure Ignore(Count: Integer = 1; ch: Char = #0);
property Delimiters: String read FDelimiters write FDelimiters;
property Peek: Char read GetPeek;
property RelativeChar[i: Integer]: Char read GetRelativeChar;
property FileName: String read FFileName;
property EOF: Boolean read GetEOF;
end;
{ TWifStream }
constructor TWifStream.Create(const aFileName: String);
begin
FFileName:= aFileName;
FDelimiters:= ' /\,'#9#10#13;
FHandle:= FileOpen(FileName, fmOpenRead);
FFileSize:= GetFileSize(FHandle, nil);
FMappingHandle:= CreateFileMapping(FHandle, nil, PAGE_READONLY, 0, 0, nil);
FFilePointer:= MapViewOfFile(FMappingHandle, FILE_MAP_READ, 0, 0, 0);
FFileEnd:= FFilePointer + FFileSize;
FBufferPos:= FFilePointer;
end;
destructor TWifStream.Destroy;
begin
UnmapViewOfFile(FFilePointer);
CloseHandle(FMappingHandle);
CloseHandle(FHandle);
inherited;
end;
function TWifStream.GetPeek: Char;
begin
// return next character, unconsumed
Result:= FBufferPos^;
end;
function TWifStream.GetRelativeChar(i: Integer): Char;
begin
Result:= (FBufferPos+i)^;
end;
function TWifStream.GetEOF: Boolean;
begin
Result:= (FBufferPos >= FFileEnd); // EOF...
end;
function TWifStream.GetNextToken: String;
var
StartPos: PChar;
begin
// Skip all Delimiters
while (FBufferPos < FFileEnd) do
begin
if StrScan(PAnsiChar(FDelimiters), FBufferPos^) = nil then Break;
Inc(FBufferPos);
end;
StartPos:= FBufferPos;
// Skip all NON-delimiters
while (FBufferPos < FFileEnd) do
begin
if StrScan(PAnsiChar(FDelimiters), FBufferPos^) <> nil then Break;
Inc(FBufferPos);
end;
FDelimPos:= FBufferPos;
SetLength(Result, FDelimPos - StartPos);
Move(StartPos^, Result[1], FDelimPos - StartPos);
end;
function TWifStream.GetNextTokenAsInt(out i: Integer): String;
begin
Result:= GetNextToken;
i:= StrToInt(Result); //todo: or StrToIntDef ???
end;
function TWifStream.GetNextTokenAsFloat(out f: Single): String;
{$IFDEF COMPILER7_UP}
var
FmtSettings: TFormatSettings;
begin
Result:= GetNextToken;
GetLocaleFormatSettings(GetThreadLocale, FmtSettings);
FmtSettings.DecimalSeparator:= '.'; // override System specified DecimalSeparator
f:= StrToFloat(Result, FmtSettings);
end;
{$ELSE}
begin
Result:= GetNextToken;
DecimalSeparator:= '.';
f:= StrToFloat(Result);
end;
{$ENDIF}
procedure TWifStream.Ignore(Count: Integer = 1; ch: Char = #0);
var
StartPos: PChar;
begin
StartPos:= FBufferPos;
while (FBufferPos < FFileEnd) and (FBufferPos - StartPos < Count) do
begin
if (FBufferPos^ = ch) then Break;
Inc(FBufferPos);
end;
end;
//--------------------------------------------------------------------------------------
function CMeshLoader.LoadGeometryFromOBJ(const strFilename: PWideChar): HRESULT;
var
strMaterialFilename: WideString;
wstr: array[0..MAX_PATH-1] of WideChar;
str: array[0..MAX_PATH-1] of Char;
pch: PWideChar;
// Create temporary storage for the input data. Once the data has been loaded into
// a reasonable format we can create a D3DXMesh object and load it with the mesh data.
Positions: array of TD3DXVector3;
TexCoords: array of TD3DXVector2;
Normals: array of TD3DXVector3;
pMat: PMaterial;
dwCurSubset: DWORD;
strCommand: String;
l: Integer;
InFile: TWifStream;
x, y, z: Single;
u, v: Single;
iPosition, iTexCoord, iNormal: Integer;
vertex: TVertex;
iFace: LongWord;
index: DWORD;
strName: WideString;
bFound: Boolean;
iMaterial: Integer;
pCurMaterial: PMaterial;
begin
// Find the file
Result:= DXUTFindDXSDKMediaFile(wstr, MAX_PATH, strFileName);
if V_Failed(Result) then Exit;
WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, MAX_PATH, nil, nil);
// Store the directory where the mesh was found
StringCchCopy(m_strMediaDir, MAX_PATH-1, wstr);
pch := WideStrRScan(m_strMediaDir, '\');
if (pch <> nil) then pch^ := #0;
// The first subset uses the default material
try
pMat := New(PMaterial);
except
Result:= E_OUTOFMEMORY;
Exit;
end;
InitMaterial(pMat^);
StringCchCopy(pMat.strName, MAX_PATH-1, 'default');
// m_Materials.Add(pMaterial);
l:= Length(m_Materials);
SetLength(m_Materials, l+1);
m_Materials[l]:= pMat;
dwCurSubset := 0;
// File input
FillChar(strCommand, SizeOf(strCommand), 0);
InFile:= TWifStream.Create(str);
if (InFile.FHandle = 0) then
begin
Result:= DXTRACE_ERR('wifstream.open', E_FAIL);
Exit;
end;
while True do
begin
strCommand := InFile.GetNextToken;
if InFile.EOF then Break;
if (strCommand = '#') then
begin
// Comment
end
else if (strCommand = 'v') then
begin
// Vertex Position
InFile.GetNextTokenAsFloat(x);
InFile.GetNextTokenAsFloat(y);
InFile.GetNextTokenAsFloat(z);
// Positions.Add(D3DXVector3(x, y, z));
l:= Length(Positions);
SetLength(Positions, l+1);
Positions[l]:= D3DXVector3(x, y, z);
end
else if (strCommand = 'vt') then
begin
// Vertex TexCoord
InFile.GetNextTokenAsFloat(u);
InFile.GetNextTokenAsFloat(v);
// TexCoords.Add(D3DXVector2(u, v));
l:= Length(TexCoords);
SetLength(TexCoords, l+1);
TexCoords[l]:= D3DXVector2(u, v);
end
else if (strCommand = 'vn') then
begin
// Vertex Normal
InFile.GetNextTokenAsFloat(x);
InFile.GetNextTokenAsFloat(y);
InFile.GetNextTokenAsFloat(z);
// Normals.Add(D3DXVector3(x, y, z));
l:= Length(Normals);
SetLength(Normals, l+1);
Normals[l]:= D3DXVector3(x, y, z);
end
else if (strCommand = 'f') then
begin
// Face
for iFace:= 0 to 2 do
begin
ZeroMemory(@vertex, SizeOf(TVertex));
// OBJ format uses 1-based arrays
InFile.GetNextTokenAsInt(iPosition);
vertex.position := Positions[iPosition-1];
if ('/' = InFile.Peek) then
begin
InFile.Ignore;
if ('/' <> InFile.Peek) then
begin
// Optional texture coordinate
InFile.GetNextTokenAsInt(iTexCoord);
vertex.texcoord := TexCoords[iTexCoord-1];
end;
if ('/' = InFile.Peek) then
begin
InFile.ignore;
// Optional vertex normal
InFile.GetNextTokenAsInt(iNormal);
vertex.normal := Normals[iNormal-1];
end;
end;
// If a duplicate vertex doesn't exist, add this vertex to the Vertices
// list. Store the index in the Indices array. The Vertices and Indices
// lists will eventually become the Vertex Buffer and Index Buffer for
// the mesh.
index := AddVertex(iPosition, @vertex);
// m_Indices.Add(index);
l:= Length(m_Indices);
SetLength(m_Indices, l+1);
m_Indices[l]:= index;
end;
// m_Attributes.Add(dwCurSubset);
l:= Length(m_Attributes);
SetLength(m_Attributes, l+1);
m_Attributes[l]:= dwCurSubset;
end
else if (strCommand = 'mtllib') then
begin
// Material library
strMaterialFilename:= InFile.GetNextToken;
end
else if (strCommand = 'usemtl') then
begin
// Material
strName := InFile.GetNextToken;
bFound := False;
for iMaterial:=0 to Length(m_Materials) - 1 do
begin
pCurMaterial := m_Materials[iMaterial];
{$IFDEF FPC}
if lstrcmpW(pCurMaterial.strName, PWideChar(strName)) = 0 then
{$ELSE}
if (pCurMaterial.strName = strName) then
{$ENDIF}
begin
bFound := True;
dwCurSubset := iMaterial;
Break;
end;
end;
if not bFound then
begin
try
pMat := New(PMaterial);
except
Result:= E_OUTOFMEMORY;
Exit;
end;
dwCurSubset := Length(m_Materials);
InitMaterial(pMat^);
StringCchCopy(pMat.strName, MAX_PATH-1, @strName[1]);
// m_Materials.Add(pMat);
l:= Length(m_Materials);
SetLength(m_Materials, l+1);
m_Materials[l]:= pMat;
end;
end
else
begin
// Unimplemented or unrecognized command
end;
InFile.Ignore(1000, #10);
end;
// Cleanup
// InFile.Close;
InFile.Free;
DeleteCache;
// If an associated material file was found, read that in as well.
if (strMaterialFilename <> '') then
begin
Result:= LoadMaterialsFromMTL(strMaterialFilename);
if V_Failed(Result) then Exit;
end;
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
function CMeshLoader.AddVertex(hash: Integer; pVer: PVertex): DWORD;
var
bFoundInList: Boolean;
index, l: DWORD;
pEntry: PCacheEntry;
pCacheVertex: PVertex;
pNewEntry: PCacheEntry;
pCurEntry: PCacheEntry;
begin
// If this vertex doesn't already exist in the Vertices list, create a new entry.
// Add the index of the vertex to the Indices list.
bFoundInList := False;
index := 0;
// Since it's very slow to check every element in the vertex list, a hashtable stores
// vertex indices according to the vertex position's index as reported by the OBJ file
if (Length(m_VertexCache) > hash) then
begin
pEntry := m_VertexCache[hash];
while (pEntry <> nil) do
begin
pCacheVertex := @m_Vertices[pEntry.index];
// If this vertex is identical to the vertex already in the list, simply
// point the index buffer to the existing vertex
if CompareMem(pVer, pCacheVertex, SizeOf(TVertex)) then
begin
bFoundInList := True;
index := pEntry.index;
Break;
end;
pEntry := pEntry.pNext;
end;
end;
// Vertex was not found in the list. Create a new entry, both within the Vertices list
// and also within the hashtable cache
if not bFoundInList then
begin
// Add to the Vertices list
index := Length(m_Vertices);
// m_Vertices.Add(pVertex^);
l:= index;
SetLength(m_Vertices, l+1);
m_Vertices[l]:= pVer^;
// Add this to the hashtable
try
pNewEntry := New(PCacheEntry);
except
Result:= DWORD(E_OUTOFMEMORY); //todo: ???
Exit;
end;
pNewEntry.index := index;
pNewEntry.pNext := nil;
// Grow the cache if needed
while (Length(m_VertexCache) <= hash) do
begin
// m_VertexCache.Add(nil);
l:= Length(m_VertexCache);
SetLength(m_VertexCache, l+1);
m_VertexCache[l]:= nil;
end;
// Add to the end of the linked list
pCurEntry := m_VertexCache[hash];
if (pCurEntry = nil) then
begin
// This is the head element
m_VertexCache[hash] := pNewEntry;
end else
begin
// Find the tail
while (pCurEntry.pNext <> nil) do
pCurEntry := pCurEntry.pNext;
pCurEntry.pNext := pNewEntry;
end;
end;
Result:= index;
end;
//--------------------------------------------------------------------------------------
procedure CMeshLoader.DeleteCache;
var
i: Integer;
pEntry: PCacheEntry;
pNext: PCacheEntry;
begin
// Iterate through all the elements in the cache and subsequent linked lists
for i := 0 to Length(m_VertexCache)-1 do
begin
pEntry := m_VertexCache[i];
while (pEntry <> nil) do
begin
pNext := pEntry.pNext;
Dispose(pEntry);
pEntry := pNext;
end;
end;
m_VertexCache := nil; // RemoveAll;
end;
//--------------------------------------------------------------------------------------
function CMeshLoader.LoadMaterialsFromMTL(const strFileName: WideString): HRESULT;
var
wstrOldDir: array[0..MAX_PATH-1] of WideChar;
strPath: array[0..MAX_PATH-1] of WideChar;
cstrPath: array[0..MAX_PATH-1] of AnsiChar;
strCommand: String;
InFile: TWifStream;
pMat: PMaterial;
strName: WideString;
i: Integer;
pCurMaterial: PMaterial;
r, g, b: Single;
nShininess: Integer;
illumination: Integer;
fAlpha: Single;
begin
// Set the current directory based on where the mesh was found
GetCurrentDirectoryW(MAX_PATH, wstrOldDir);
SetCurrentDirectoryW(m_strMediaDir);
// Find the file
Result:= DXUTFindDXSDKMediaFile(strPath, MAX_PATH, PWideChar(strFileName));
if V_Failed(Result) then Exit;
WideCharToMultiByte(CP_ACP, 0, strPath, -1, cstrPath, MAX_PATH, nil, nil);
// File input
InFile:= TWifStream.Create(cstrPath);
if (InFile.FHandle = 0) then
begin
Result:= DXTRACE_ERR('wifstream.open', E_FAIL);
Exit;
end;
// Restore the original current directory
SetCurrentDirectoryW(wstrOldDir);
pMat := nil;
while True do
begin
strCommand := InFile.GetNextToken;
if InFile.EOF then Break;
if (strCommand = 'newmtl') then
begin
// Switching active materials
strName := InFile.GetNextToken;
pMat := nil;
for i := 0 to Length(m_Materials) do
begin
pCurMaterial := m_Materials[i];
// if (pCurMaterial.strName = strName) then //This is "proper" way
// if PWideChar(@pCurMaterial.strName) = strName then //todo: This is FreePascal compatible way
if lstrcmpW(pCurMaterial.strName, PWideChar(strName)) = 0 then //too C/C++ way althrow fastest of above... :-)
begin
pMat := pCurMaterial;
Break;
end;
end;
end;
// The rest of the commands rely on an active material
if (pMat = nil) then Continue;
if (strCommand = '#') then
begin
// Comment
end
else if (strCommand = 'Ka') then
begin
// Ambient color
InFile.GetNextTokenAsFloat(r);
InFile.GetNextTokenAsFloat(g);
InFile.GetNextTokenAsFloat(b);
pMat.vAmbient := D3DXVector3(r, g, b);
end
else if (strCommand = 'Kd') then
begin
// Diffuse color
InFile.GetNextTokenAsFloat(r);
InFile.GetNextTokenAsFloat(g);
InFile.GetNextTokenAsFloat(b);
pMat.vDiffuse := D3DXVector3(r, g, b);
end
else if (strCommand = 'Ks') then
begin
// Specular color
InFile.GetNextTokenAsFloat(r);
InFile.GetNextTokenAsFloat(g);
InFile.GetNextTokenAsFloat(b);
pMat.vSpecular := D3DXVector3(r, g, b);
end
else if (strCommand = 'd') or
(strCommand = 'Tr') then
begin
// Alpha
InFile.GetNextTokenAsFloat(fAlpha);
end
else if (strCommand = 'Ns') then
begin
// Shininess
InFile.GetNextTokenAsInt(nShininess);
pMat.nShininess := nShininess;
end
else if (strCommand = 'illum') then
begin
// Specular on/off
InFile.GetNextTokenAsInt(illumination);
pMat.bSpecular := (illumination = 2);
end
else if (strCommand = 'map_Kd') then
begin
// Texture
strName:= InFile.GetNextToken;
lstrcpynW(pMat.strTexture, @strName[1], MAX_PATH-1); //todo: DEbug is it right order?
end
else
begin
// Unimplemented or unrecognized command
end;
InFile.Ignore(1000, #10);
end;
InFile.Free;
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
procedure CMeshLoader.InitMaterial(var pMaterial: TMaterial);
begin
ZeroMemory(@pMaterial, SizeOf(TMaterial));
pMaterial.vAmbient := D3DXVector3(0.2, 0.2, 0.2);
pMaterial.vDiffuse := D3DXVector3(0.8, 0.8, 0.8);
pMaterial.vSpecular := D3DXVector3(1.0, 1.0, 1.0);
pMaterial.nShininess := 0;
pMaterial.fAlpha := 1.0;
pMaterial.bSpecular := False;
pMaterial.pTexture := nil;
end;
function CMeshLoader.GetMaterial(iMaterial: LongWord): PMaterial;
begin
Result:= m_Materials[iMaterial];
end;
function CMeshLoader.GetMediaDirectory: PWideChar;
begin
Result:= m_strMediaDir;
end;
function CMeshLoader.GetNumMaterials: LongWord;
begin
Result:= Length(m_Materials);
end;
end.
|
{================================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmFormEditBinding
Purpose : dialog form for choosing key binding combinations
Date : 10-26-2000
Author : Ryan J. Mills
Version : 1.92
================================================================================}
unit rmFormEditBinding;
interface
{$I CompilerDefines.INC}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls, Menus;
type
TrmFrmEditBinding = class(TForm)
GroupBox1: TGroupBox;
cbAlt: TCheckBox;
cbCTRL: TCheckBox;
cbShift: TCheckBox;
cbxKey: TComboBox;
Button1: TButton;
Button2: TButton;
private
function GetBinding: TShortcut;
procedure SetBinding(const Value: TShortcut);
{ Private declarations }
public
{ Public declarations }
property Binding:TShortcut read GetBinding write SetBinding default scNone;
end;
implementation
{$R *.DFM}
{ TrmFrmEditBinding }
function TrmFrmEditBinding.GetBinding: TShortcut;
var
wKey : Word;
wShift : TShiftState;
begin
if cbxKey.ItemIndex = 0 then
result := scNone
else
begin
ShortCutToKey(TextToShortCut(cbxKey.Text), wKey, wShift);
wShift := [];
if cbAlt.checked then
wShift := wShift + [ssAlt];
if cbCtrl.checked then
wShift := wShift + [ssCtrl];
if cbShift.checked then
wShift := wShift + [ssShift];
result := ShortCut(wKey, wShift);
end;
end;
procedure TrmFrmEditBinding.SetBinding(const Value: TShortcut);
var
wKey : Word;
wShift : TShiftState;
begin
ShortCutToKey(Value, wkey, wShift);
cbAlt.checked := (ssAlt in wShift);
cbCTRL.checked := (ssCtrl in wShift);
cbShift.checked := (ssShift in wShift);
cbxKey.ItemIndex := cbxKey.items.IndexOf(ShortCutToText(Shortcut(wKey, [])));
end;
end.
|
{
Lua4Lazarus
TLuaObject
License: New BSD
Copyright(c)2010- Malcome@Japan All rights reserved.
Version History:
1.54.200703 by Malcome Japan.
- Test Lazarus 2.0.8 (FPC 3.0.4)
- for Lua 5.4
1.53.150205 by Malcome Japan.
- Test Lazarus 1.4RC1 (FPC 2.6.4), Lazarus 1.5 (FPC 3.0.1)
- for Lua 5.3
1.52.0 by Malcome Japan.
- Test Lazarus 1.3 (FPC 2.6.2)
- for Lua 5.2
1.0.0 by Malcome@Japan.
- Test Lazarus 0.9.29 (FPC 2.4.1)
- for Lua 5.1
License for Lua 5.0 and later versions:
Copyright(c)1994-2015 Lua.org, PUC-Rio.
}
unit l4l_object;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, lua54;
type
{ TLuaObject }
TLuaObject = class(TPersistent)
private
FLS: Plua_State;
protected
property LS: Plua_State read FLS;
function Iterator({%H-}index: integer): integer; virtual;
public
constructor Create(L : Plua_State); virtual;
published
end;
procedure l4l_SetLuaObject(obj: TLuaObject);
procedure l4l_PushLuaObject(obj: TLuaObject);
function l4l_isobject(L : Plua_State; n: Integer): boolean;
function l4l_isobject(L : Plua_State; n: Integer; c: TClass): boolean;
function l4l_toobject(L : Plua_State; n: Integer): TLuaObject;
implementation
uses
typinfo;
const
FIELD_OBJ = '___l4lObject___';
FIELD_FN = '___l4lFuncName___';
FIELD_IC = '___l4lIteCount___';
PROP_HEAD = 'l4l_';
function gc(L : Plua_State) : Integer; cdecl;
var
p: PPointer;
begin
p:= lua_touserdata(L, 1);
try TLuaObject(p^).Free; except end;
Result:= 0;
end;
function call(L : Plua_State) : Integer; cdecl;
var
p: PPointer;
obj: TLuaObject;
method: function:integer of object;
begin
lua_getfield(L, 1, FIELD_OBJ);
p:= lua_touserdata(L, -1);
lua_remove(L, -1);
obj:= TLuaObject(p^);
lua_getfield(L, 1, FIELD_FN);
lua_remove(L, 1);
p:= lua_touserdata(L, -1);
lua_remove(L, -1);
TMethod(method).Data := obj;
TMethod(method).Code := p^;
try
Result := method();
except
on E: Exception do luaL_error(L, PChar(E.Message));
end;
end;
function Index(L : Plua_State) : Integer; cdecl;
var
p: PPointer;
key: string;
obj: TLuaObject;
pi: PPropInfo;
o: TObject;
begin
Result := 0;
lua_getfield(L, 1, FIELD_OBJ);
p:= lua_touserdata(L, -1);
obj:= TLuaObject(p^);
key := lua_tostring(L, 2);
if Assigned(obj.MethodAddress(PROP_HEAD + key)) then begin
lua_getfield(L, 1, PChar(LowerCase(key)));
end else begin
try
pi := FindPropInfo(obj, PROP_HEAD + LowerCase(key));
except
luaL_error(L, 'Unknown property: "%s".', PChar(key));
end;
try
case pi^.PropType^.Kind of
tkInteger, tkQWord:
lua_pushinteger(L, GetOrdProp(obj, pi));
tkInt64: lua_pushinteger(L, GetInt64Prop(obj, pi));
tkFloat: lua_pushnumber(L, GetFloatProp(obj, pi));
tkBool: begin
if GetOrdProp(obj, pi) = 0 then
lua_pushboolean(L, False)
else
lua_pushboolean(L, True);
end;
tkClass: begin
o:= GetObjectProp(obj, pi);
if o is TLuaObject then begin
l4l_PushLuaObject(o as TLuaObject);
end else begin
lua_pushnil(L);
end;
end;
else begin
lua_pushstring(L, PChar(GetStrProp(obj, pi)));
end;
end;
except
on E: Exception do luaL_error(L, PChar(E.Message));
end;
end;
Result := 1;
end;
function NewIndex(L : Plua_State) : Integer; cdecl;
var
p: PPointer;
key: string;
obj: TLuaObject;
pi: PPropInfo;
begin
Result:=0;
lua_getfield(L, 1, FIELD_OBJ);
p:= lua_touserdata(L, -1);
obj:= TLuaObject(p^);
key := lua_tostring(L, 2);
try
pi := FindPropInfo(obj, PROP_HEAD + LowerCase(key));
except
luaL_error(L, 'Unknown property: "%s".', PChar(key));
end;
try
case pi^.PropType^.Kind of
tkInteger, tkInt64, tkQWord:
SetOrdProp(obj, pi, lua_tointeger(L, 3));
tkFloat: SetFloatProp(obj, pi, lua_tonumber(L, 3));
tkBool: SetOrdProp(obj, pi, Ord(lua_toboolean(L, 3)));
tkClass: begin
lua_getfield(L, 3, FIELD_OBJ);
p:= lua_touserdata(L, -1);
if Assigned(p) and Assigned(p^) then begin
SetObjectProp(obj, pi, TObject(p^));
end else
SetObjectProp(obj, pi, TObject(nil));
end;
else begin
SetStrProp(obj, pi, lua_tostring(L, 3));
end;
end;
except
on E: Exception do luaL_error(L, PChar(E.Message));
end;
end;
function iterator(L : Plua_State) : Integer; cdecl;
var
i: integer;
p: PPointer;
obj: TLuaObject;
begin
Result:= 0;
lua_getfield(L, 1, FIELD_OBJ);
p:= lua_touserdata(L, -1);
obj:= TLuaObject(p^);
if lua_isnil(L, 3) then begin
i := 0;
end else begin
lua_pushstring(L, FIELD_IC);
lua_rawget(L, 1);
i:= lua_tointeger(L, -1) + 1;
end;
lua_pushstring(L, FIELD_IC);
lua_pushinteger(L, i);
lua_rawset(L, 1);
try
Result := obj.Iterator(i);
except
on E: Exception do luaL_error(L, PChar(E.Message));
end;
end;
procedure l4l_SetLuaObject(obj: TLuaObject);
type
TMethodRec = packed record
name : pshortstring;
addr : pointer;
end;
TMethodTable = packed record
count : dword;
entries : packed array[0..0] of TMethodRec;
end;
PMethodTable = ^TMethodTable;
var
p: PPointer;
i, t: integer;
mt: PMethodTable;
s:string;
cl: TClass;
begin
t:= lua_gettop(obj.LS);
lua_pushstring(obj.LS, FIELD_OBJ);
p:= lua_newuserdata(obj.LS, SizeOf(Pointer));
p^:=obj;
if lua_getmetatable(obj.LS, -1) = 0 then lua_newtable(obj.LS);
lua_pushstring(obj.LS, '__gc');
lua_pushcfunction(obj.LS, @gc);
lua_settable(obj.LS, -3);
lua_setmetatable(obj.LS, -2);
lua_settable(obj.LS, -3);
cl:= obj.ClassType;
while Assigned(cl) do begin
p := Pointer(PAnsiChar(cl) + vmtMethodtable);
mt := p^;
if Assigned(mt) then begin
for i:=0 to mt^.count-1 do begin
s:= LowerCase(mt^.entries[i].name^);
if Copy(s, 1, 4) <> PROP_HEAD then continue;
Delete(s, 1, 4);
lua_pushstring(obj.LS, PChar(s));
lua_newtable(obj.LS);
lua_pushstring(obj.LS, FIELD_FN);
p:= lua_newuserdata(obj.LS, SizeOf(Pointer));
p^:= mt^.entries[i].addr;
lua_settable(obj.LS, -3);
lua_newtable(obj.LS);
lua_pushstring(obj.LS, '__call');
lua_pushcfunction(obj.LS, @call);
lua_settable(obj.LS, -3);
lua_pushstring(obj.LS, '__index');
lua_pushvalue(obj.LS, t); // SuperClass
lua_settable(obj.LS, -3);
lua_setmetatable(obj.LS, -2);
lua_settable(obj.LS, -3);
end;
end;
cl := cl.ClassParent;
end;
lua_newtable(obj.LS);
lua_pushstring(obj.LS, '__newindex');
lua_pushcfunction(obj.LS, @NewIndex);
lua_settable(obj.LS, -3);
lua_pushstring(obj.LS, '__index');
lua_pushcfunction(obj.LS, @Index);
lua_settable(obj.LS, -3);
lua_pushstring(obj.LS, '__call');
lua_pushcfunction(obj.LS, @iterator);
lua_settable(obj.LS, -3);
lua_setmetatable(obj.LS, -2);
end;
procedure l4l_PushLuaObject(obj: TLuaObject);
begin
lua_newtable(obj.LS);
l4l_SetLuaObject(obj);
end;
function l4l_isobject(L : Plua_State; n: Integer): boolean;
begin
Result:= l4l_isobject(L, n, TLuaObject);
end;
function l4l_isobject(L : Plua_State; n: Integer; c: TClass): boolean;
var
p: PPointer;
begin
Result:= False;
if lua_istable(L, n) then begin
lua_getfield(L, n, FIELD_OBJ);
if not lua_isnil(L, -1) then begin
p:= lua_touserdata(L, -1);
Result := TObject(p^) is c;
end;
lua_remove(L, -1);
end;
end;
function l4l_toobject(L: Plua_State; n: Integer): TLuaObject;
var
p: PPointer;
begin
Result:= nil;
if lua_istable(L, n) then begin
lua_getfield(L, n, FIELD_OBJ);
if not lua_isnil(L, -1) then begin
p:= lua_touserdata(L, -1);
Result := TLuaObject(p^);
end;
lua_remove(L, -1);
end;
end;
{ TLuaObject }
function TLuaObject.Iterator(index: integer): integer;
begin
Result := 0;
end;
constructor TLuaObject.Create(L: Plua_State);
begin
FLS := L;
end;
end.
|
unit Mesh;
interface
uses dglOpenGL, GLConstants, Graphics, Normals, BasicMathsTypes, BasicDataTypes,
BasicRenderingTypes, Palette, Dialogs, SysUtils, IntegerList, StopWatch,
ShaderBank, ShaderBankItem, TextureBank, TextureBankItem, IntegerSet,
Material, Vector3fSet, MeshPluginBase, MeshGeometryList, MeshGeometryBase,
Histogram, Debug;
{$INCLUDE source/Global_Conditionals.inc}
type
TGetCardinalAttr = function: cardinal of object;
TMesh = class
protected
ColourGenStructure : byte;
TransparencyLevel : single;
FOpened : boolean;
NumVertices: cardinal;
LastVertex: cardinal;
// Gets
function GetNumVerticesCompressed: cardinal;
function GetNumVerticesUnCompressed: cardinal;
function GetLastVertexCompressed: cardinal;
function GetLastVertexUnCompressed: cardinal;
// Sets
// Render
procedure CommonRenderingProcedure;
// Materials
procedure AddMaterial;
procedure DeleteMaterial(_ID: integer);
procedure ClearMaterials;
// Misc
procedure OverrideTransparency;
public
// These are the formal atributes
Name : string;
ID : longword;
Next : integer;
Son : integer; // not implemented yet.
// Graphical atributes goes here
// FaceType : GLINT; // GL_QUADS for quads, and GL_TRIANGLES for triangles
// VerticesPerFace : byte; // for optimization purposes only.
ColoursType : byte;
NormalsType : byte;
NumFaces : longword;
Vertices : TAVector3f;
Normals : TAVector3f;
Colours : TAVector4f;
// Faces : auint32;
TexCoords : TAVector2f;
Geometry: CMeshGeometryList;
GetNumVertices: TGetCardinalAttr;
GetLastVertex: TGetCardinalAttr;
// FaceNormals : TAVector3f;
Materials : TAMeshMaterial;
// Graphical and colision
BoundingBox : TRectangle3f;
Scale : TVector3f;
BoundingScale: TVector3f;
IsColisionEnabled : boolean;
IsVisible : boolean;
// Rendering optimization
RenderingProcedure : TRenderProc;
// List : Integer;
// Connect to the correct shader bank
ShaderBank : PShaderBank;
// GUI
IsSelected : boolean;
// Additional Features
Plugins: PAMeshPluginBase;
// Constructors And Destructors
constructor Create(_ID,_NumVertices,_NumFaces : longword; _BoundingBox : TRectangle3f; _VerticesPerFace, _ColoursType, _NormalsType : byte; _ShaderBank : PShaderBank); overload;
constructor Create(const _Mesh : TMesh); overload;
destructor Destroy; override;
procedure Clear;
// Sets
procedure SetColoursType(_ColoursType: integer);
procedure SetColourGenStructure(_ColoursType: integer);
procedure SetNormalsType(_NormalsType: integer);
procedure SetColoursAndNormalsType(_ColoursType, _NormalsType: integer);
procedure ForceColoursRendering;
// Gets
function IsOpened: boolean;
// Texture related.
procedure AddTextureToMesh(_MaterialID, _TextureType, _ShaderID: integer; _Texture:PTextureBankItem);
procedure ExportTextures(const _BaseDir, _Ext : string; var _UsedTextures : CIntegerSet; _previewTextures: boolean);
procedure SetTextureNumMipMaps(_NumMipMaps, _TextureType: integer);
// Rendering methods
procedure Render; overload;
procedure Render(var _Polycount: longword); overload;
procedure RenderVectorial;
procedure ForceRefresh;
// Copies
procedure Assign(const _Mesh : TMesh); virtual;
// Texture related
function CollectColours(var _ColourMap: auint32): TAVector4f;
// Model optimization
procedure RemoveInvisibleFaces;
// Materials
function GetLastTextureID(_MaterialID: integer): integer;
function GetNextTextureID(_MaterialID: integer): integer;
function GetTextureSize(_MaterialID,_TextureID: integer): integer;
// Quality Assurance
procedure FillAspectRatioHistogram(var _Histogram: THistogram);
procedure FillSkewnessHistogram(var _Histogram: THistogram);
procedure FillSmoothnessHistogram(var _Histogram: THistogram);
// Plugins
procedure AddNormalsPlugin;
procedure AddNeighborhoodPlugin;
procedure AddBumpMapDataPlugin;
procedure AddHalfEdgePlugin; overload;
procedure AddHalfEdgePlugin(_ID: integer); overload;
procedure RemovePlugin(_PluginType: integer);
procedure ClearPlugins;
function IsPluginEnabled(_PluginType: integer): boolean;
function GetPlugin(_PluginType: integer): PMeshPluginBase;
// Miscelaneous
procedure ForceTransparencyLevel(_TransparencyLevel : single);
// Uncompres to let it add vertices faster. Compress (default) to make it more compact.
procedure UncompressMesh;
procedure CompressMesh;
procedure AddVertices(_NumVertices: cardinal);
// Debug
procedure Debug(const _Debug:TDebugFile);
procedure DebugVertexPositions(const _Debug:TDebugFile);
procedure DebugVertexNormals(const _Debug:TDebugFile);
procedure DebugVertexColours(const _Debug:TDebugFile);
procedure DebugVertexTexCoordss(const _Debug:TDebugFile);
property Opened: boolean read FOpened;
end;
PMesh = ^TMesh;
implementation
uses GlobalVars, VoxelMeshGenerator, NormalsMeshPlugin, NeighborhoodDataPlugin,
MeshBRepGeometry, BumpMapDataPlugin, BasicConstants, BasicFunctions,
Math3d, NeighborDetector, HalfEdgePlugin;
constructor TMesh.Create(_ID,_NumVertices,_NumFaces : longword; _BoundingBox : TRectangle3f; _VerticesPerFace, _ColoursType, _NormalsType : byte; _ShaderBank : PShaderBank);
begin
// Set basic variables:
ShaderBank := _ShaderBank;
ID := _ID;
// VerticesPerFace := _VerticesPerFace;
NumFaces := _NumFaces;
SetColoursAndNormalsType(_ColoursType,_NormalsType);
ColourGenStructure := _ColoursType;
Geometry := CMeshGeometryList.Create();
Geometry.Add;
//Geometry.Current^ := TMeshBRepGeometry.Create(_NumFaces,_VerticesPerFace,_ColoursType,_NormalsType);
// Let's set the array sizes.
SetLength(Vertices,_NumVertices);
SetLength(TexCoords,_NumVertices);
SetLength(Normals,_NumVertices);
SetLength(Colours,_NumVertices);
// The rest
BoundingBox.Min.X := _BoundingBox.Min.X;
BoundingBox.Min.Y := _BoundingBox.Min.Y;
BoundingBox.Min.Z := _BoundingBox.Min.Z;
BoundingBox.Max.X := _BoundingBox.Max.X;
BoundingBox.Max.Y := _BoundingBox.Max.Y;
BoundingBox.Max.Z := _BoundingBox.Max.Z;
Scale := SetVector(1,1,1);
BoundingScale := SetVector(1,1,1);
IsColisionEnabled := false; // Temporarily, until colision is implemented.
IsVisible := true;
TransparencyLevel := C_TRP_OPAQUE;
FOpened := false;
IsSelected := false;
AddMaterial;
Next := -1;
Son := -1;
SetLength(Plugins,0);
GetNumVertices := GetNumVerticesCompressed;
GetLastVertex := GetLastVertexCompressed;
end;
constructor TMesh.Create(const _Mesh : TMesh);
begin
Assign(_Mesh);
GetNumVertices := GetNumVerticesCompressed;
GetLastVertex := GetLastVertexCompressed;
end;
destructor TMesh.Destroy;
begin
Clear;
Geometry.Free;
inherited Destroy;
end;
procedure TMesh.Clear;
begin
FOpened := false;
ForceRefresh;
SetLength(Vertices,0);
SetLength(Colours,0);
SetLength(Normals,0);
SetLength(TexCoords,0);
Geometry.Clear;
ClearMaterials;
ClearPlugins;
end;
// Texture related.
procedure TMesh.AddTextureToMesh(_MaterialID, _TextureType, _ShaderID: integer; _Texture:PTextureBankItem);
begin
while High(Materials) < _MaterialID do
begin
AddMaterial;
end;
Materials[_MaterialID].AddTexture(_TextureType,_Texture);
if ShaderBank <> nil then
Materials[_MaterialID].Shader := ShaderBank^.Get(_ShaderID)
else
Materials[_MaterialID].Shader := nil;
if _TextureType = C_TTP_DOT3BUMP then
begin
AddBumpMapDataPlugin;
Geometry.GoToFirstElement;
while Geometry.Current <> nil do
begin
(Geometry.Current^ as TMeshBRepGeometry).SetBumpMappingShader;
Geometry.GoToNextElement;
end;
end;
SetColoursType(C_COLOURS_FROM_TEXTURE);
end;
// Sets
procedure TMesh.SetColoursType(_ColoursType: integer);
var
CurrentGeometry: PMeshGeometryBase;
begin
ColoursType := _ColoursType and 3;
Geometry.GoToFirstElement;
CurrentGeometry := Geometry.Current;
while CurrentGeometry <> nil do
begin
CurrentGeometry^.SetColoursType(ColoursType);
Geometry.GoToNextElement;
CurrentGeometry := Geometry.Current;
end;
end;
procedure TMesh.SetColourGenStructure(_ColoursType: integer);
var
CurrentGeometry: PMeshGeometryBase;
begin
ColourGenStructure := _ColoursType and 3;
Geometry.GoToFirstElement;
CurrentGeometry := Geometry.Current;
while CurrentGeometry <> nil do
begin
CurrentGeometry^.SetColourGenStructure(ColoursType);
Geometry.GoToNextElement;
CurrentGeometry := Geometry.Current;
end;
end;
procedure TMesh.ForceColoursRendering;
begin
SetColoursType(ColourGenStructure);
end;
procedure TMesh.SetNormalsType(_NormalsType: integer);
var
CurrentGeometry: PMeshGeometryBase;
begin
NormalsType := _NormalsType and 3;
Geometry.GoToFirstElement;
CurrentGeometry := Geometry.Current;
while CurrentGeometry <> nil do
begin
CurrentGeometry^.SetNormalsType(NormalsType);
Geometry.GoToNextElement;
CurrentGeometry := Geometry.Current;
end;
end;
procedure TMesh.SetColoursAndNormalsType(_ColoursType, _NormalsType: integer);
var
CurrentGeometry: PMeshGeometryBase;
begin
ColoursType := _ColoursType and 3;
NormalsType := _NormalsType and 3;
Geometry.GoToFirstElement;
CurrentGeometry := Geometry.Current;
while CurrentGeometry <> nil do
begin
CurrentGeometry^.SetColoursAndNormalsType(ColoursType,NormalsType);
Geometry.GoToNextElement;
CurrentGeometry := Geometry.Current;
end;
end;
// Gets
function TMesh.IsOpened: boolean;
begin
Result := FOpened;
end;
// Rendering methods.
procedure TMesh.Render;
begin
if IsVisible and FOpened then
begin
CommonRenderingProcedure;
end;
end;
procedure TMesh.Render(var _PolyCount: longword);
begin
if IsVisible and FOpened then
begin
inc(_PolyCount,NumFaces);
CommonRenderingProcedure;
end;
end;
procedure TMesh.CommonRenderingProcedure;
var
i : integer;
CurrentGeometry: PMeshGeometryBase;
begin
Geometry.GoToFirstElement;
CurrentGeometry := Geometry.Current;
while CurrentGeometry <> nil do
begin
CurrentGeometry^.PreRender(Addr(self));
Geometry.GoToNextElement;
CurrentGeometry := Geometry.Current;
end;
// Move accordingly to the bounding box position.
glTranslatef(BoundingBox.Min.X, BoundingBox.Min.Y, BoundingBox.Min.Z);
glScalef(BoundingScale.X, BoundingScale.Y, BoundingScale.Z);
Geometry.GoToFirstElement;
CurrentGeometry := Geometry.Current;
while CurrentGeometry <> nil do
begin
CurrentGeometry^.Render;
Geometry.GoToNextElement;
CurrentGeometry := Geometry.Current;
end;
for i := Low(Plugins) to High(Plugins) do
begin
if Plugins[i] <> nil then
begin
Plugins[i]^.Render;
end;
end;
end;
procedure TMesh.RenderVectorial();
var
i : integer;
CurrentGeometry: PMeshGeometryBase;
begin
if IsVisible and FOpened then
begin
// Move accordingly to the bounding box position.
glTranslatef(BoundingBox.Min.X, BoundingBox.Min.Y, BoundingBox.Min.Z);
Geometry.GoToFirstElement;
CurrentGeometry := Geometry.Current;
while CurrentGeometry <> nil do
begin
CurrentGeometry^.RenderVectorial(Addr(self));
Geometry.GoToNextElement;
CurrentGeometry := Geometry.Current;
end;
for i := Low(Plugins) to High(Plugins) do
begin
if Plugins[i] <> nil then
begin
Plugins[i]^.Render;
end;
end;
end;
end;
// Basically clears the OpenGL List, so the RenderingProcedure may run next time it renders the mesh.
procedure TMesh.ForceRefresh;
var
i : integer;
CurrentGeometry: PMeshGeometryBase;
begin
Geometry.GoToFirstElement;
CurrentGeometry := Geometry.Current;
while CurrentGeometry <> nil do
begin
CurrentGeometry^.ForceRefresh;
Geometry.GoToNextElement;
CurrentGeometry := Geometry.Current;
end;
for i := Low(Plugins) to High(Plugins) do
begin
if Plugins[i] <> nil then
begin
Plugins[i]^.Update(Addr(self));
end;
end;
end;
// Copies
procedure TMesh.Assign(const _Mesh : TMesh);
var
i : integer;
CurrentGeometry: PMeshGeometryBase;
begin
ShaderBank := _Mesh.ShaderBank;
NormalsType := _Mesh.NormalsType;
ColoursType := _Mesh.ColoursType;
TransparencyLevel := _Mesh.TransparencyLevel;
FOpened := _Mesh.FOpened;
Name := CopyString(_Mesh.Name);
ID := _Mesh.ID;
Son := _Mesh.Son;
Scale.X := _Mesh.Scale.X;
Scale.Y := _Mesh.Scale.Y;
Scale.Z := _Mesh.Scale.Z;
IsColisionEnabled := _Mesh.IsColisionEnabled;
IsVisible := _Mesh.IsVisible;
IsSelected := _Mesh.IsSelected;
BoundingBox.Min.X := _Mesh.BoundingBox.Min.X;
BoundingBox.Min.Y := _Mesh.BoundingBox.Min.Y;
BoundingBox.Min.Z := _Mesh.BoundingBox.Min.Z;
BoundingBox.Max.X := _Mesh.BoundingBox.Max.X;
BoundingBox.Max.Y := _Mesh.BoundingBox.Max.Y;
BoundingBox.Max.Z := _Mesh.BoundingBox.Max.Z;
SetLength(Vertices,High(_Mesh.Vertices) + 1);
for i := Low(Vertices) to High(Vertices) do
begin
Vertices[i].X := _Mesh.Vertices[i].X;
Vertices[i].Y := _Mesh.Vertices[i].Y;
Vertices[i].Z := _Mesh.Vertices[i].Z;
end;
SetLength(Normals,High(_Mesh.Normals)+1);
for i := Low(Normals) to High(Normals) do
begin
Normals[i].X := _Mesh.Normals[i].X;
Normals[i].Y := _Mesh.Normals[i].Y;
Normals[i].Z := _Mesh.Normals[i].Z;
end;
SetLength(Colours,High(_Mesh.Colours)+1);
for i := Low(Colours) to High(Colours) do
begin
Colours[i].X := _Mesh.Colours[i].X;
Colours[i].Y := _Mesh.Colours[i].Y;
Colours[i].Z := _Mesh.Colours[i].Z;
Colours[i].W := _Mesh.Colours[i].W;
end;
SetLength(TexCoords,High(_Mesh.TexCoords)+1);
for i := Low(TexCoords) to High(TexCoords) do
begin
TexCoords[i].U := _Mesh.TexCoords[i].U;
TexCoords[i].V := _Mesh.TexCoords[i].V;
end;
SetLength(Materials,High(Materials)+1);
for i := Low(Materials) to High(Materials) do
begin
Materials[i].Assign(Materials[i]);
end;
_Mesh.Geometry.GoToFirstElement;
CurrentGeometry := _Mesh.Geometry.Current;
Geometry := CMeshGeometryList.Create();
while CurrentGeometry <> nil do
begin
Geometry.Add(C_GEO_BREP);
Geometry.Current^.Assign(CurrentGeometry^);
_Mesh.Geometry.GoToNextElement;
CurrentGeometry := _Mesh.Geometry.Current;
end;
SetLength(Plugins, High(_Mesh.Plugins) + 1);
for i := Low(Plugins) to High(Plugins) do
begin
new(Plugins[i]);
case _Mesh.Plugins[i]^.PluginType of
C_MPL_BUMPMAPDATA:
begin
Plugins[i]^ := TBumpMapDataPlugin.Create(_Mesh.Plugins[i]^ as TBumpMapDataPlugin);
end;
C_MPL_NEIGHBOOR:
begin
Plugins[i]^ := TNeighborhoodDataPlugin.Create(_Mesh.Plugins[i]^ as TNeighborhoodDataPlugin);
end;
C_MPL_NORMALS:
begin
Plugins[i]^ := TNormalsMeshPlugin.Create(_Mesh.Plugins[i]^ as TNormalsMeshPlugin);
end;
C_MPL_HALFEDGE:
begin
Plugins[i]^ := THalfEdgePlugin.Create(_Mesh.Plugins[i]^ as THalfEdgePlugin);
end;
end;
end;
Next := _Mesh.Next;
end;
// Texture related
function TMesh.CollectColours(var _ColourMap: auint32): TAVector4f;
var
i,f: integer;
found : boolean;
begin
SetLength(Result,0);
SetLength(_ColourMap,High(Colours)+1);
for f := Low(Colours) to High(Colours) do
begin
i := Low(Result);
found := false;
while (i < High(Result)) and (not found) do
begin
if (Colours[f].X = Result[i].X) and (Colours[f].Y = Result[i].Y) and (Colours[f].Z = Result[i].Z) and (Colours[f].W = Result[i].W) then
begin
found := true;
_ColourMap[f] := i;
end
else
inc(i);
end;
if not found then
begin
SetLength(Result,High(Result)+2);
Result[High(Result)].X := Colours[f].X;
Result[High(Result)].Y := Colours[f].Y;
Result[High(Result)].Z := Colours[f].Z;
Result[High(Result)].W := Colours[f].W;
_ColourMap[f] := High(Result);
end;
end;
end;
// Materials
procedure TMesh.AddMaterial;
begin
SetLength(Materials,High(Materials)+2);
Materials[High(Materials)] := TMeshMaterial.Create(ShaderBank);
end;
procedure TMesh.DeleteMaterial(_ID: integer);
var
i: integer;
begin
i := _ID;
while i < High(Materials) do
begin
Materials[i].Assign(Materials[i+1]);
inc(i);
end;
Materials[High(Materials)].Free;
SetLength(Materials,High(Materials));
end;
procedure TMesh.ClearMaterials;
var
i: integer;
begin
for i := Low(Materials) to High(Materials) do
begin
Materials[i].Free;
end;
SetLength(Materials,0);
end;
function TMesh.GetLastTextureID(_MaterialID: integer): integer;
begin
if (_MaterialID >= 0) and (_MaterialID <= High(Materials)) then
begin
Result := Materials[_MaterialID].GetLastTextureID;
end
else
begin
Result := -1;
end;
end;
function TMesh.GetNextTextureID(_MaterialID: integer): integer;
begin
if (_MaterialID >= 0) and (_MaterialID <= High(Materials)) then
begin
Result := Materials[_MaterialID].GetNextTextureID;
end
else
begin
Result := 0;
end;
end;
function TMesh.GetTextureSize(_MaterialID,_TextureID: integer): integer;
begin
if (_MaterialID >= 0) and (_MaterialID <= High(Materials)) then
begin
Result := Materials[_MaterialID].GetTextureSize(_TextureID);
end
else
begin
Result := 0;
end;
end;
procedure TMesh.ExportTextures(const _BaseDir, _Ext : string; var _UsedTextures : CIntegerSet; _previewTextures: boolean);
var
mat: integer;
begin
for mat := Low(Materials) to High(Materials) do
begin
Materials[mat].ExportTextures(_BaseDir,Name + '_' + IntToStr(ID) + '_' + IntToStr(mat),_Ext,_UsedTextures,_previewTextures);
end;
end;
procedure TMesh.SetTextureNumMipMaps(_NumMipMaps, _TextureType: integer);
var
mat : integer;
begin
for mat := Low(Materials) to High(Materials) do
begin
Materials[mat].SetTextureNumMipmaps(_NumMipMaps,_TextureType);
end;
end;
// Quality Assurance
procedure TMesh.FillAspectRatioHistogram(var _Histogram: THistogram);
var
CurrentGeometry: PMeshGeometryBase;
begin
Geometry.GoToFirstElement;
CurrentGeometry := Geometry.Current;
while CurrentGeometry <> nil do
begin
(CurrentGeometry^ as TMeshBRepGeometry).FillAspectRatioHistogram(_Histogram,Vertices);
Geometry.GoToNextElement;
CurrentGeometry := Geometry.Current;
end;
end;
procedure TMesh.FillSkewnessHistogram(var _Histogram: THistogram);
var
CurrentGeometry: PMeshGeometryBase;
begin
Geometry.GoToFirstElement;
CurrentGeometry := Geometry.Current;
while CurrentGeometry <> nil do
begin
(CurrentGeometry^ as TMeshBRepGeometry).FillSkewnessHistogram(_Histogram,Vertices);
Geometry.GoToNextElement;
CurrentGeometry := Geometry.Current;
end;
end;
procedure TMesh.FillSmoothnessHistogram(var _Histogram: THistogram);
var
CurrentGeometry: PMeshGeometryBase;
NeighborhoodPlugin: PMeshPluginBase;
FaceNeighbors: TNeighborDetector;
begin
Geometry.GoToFirstElement;
CurrentGeometry := Geometry.Current;
NeighborhoodPlugin := GetPlugin(C_MPL_NEIGHBOOR);
if NeighborhoodPlugin <> nil then
begin
FaceNeighbors := TNeighborhoodDataPlugin(NeighborhoodPlugin^).FaceFaceNeighbors;
end
else
begin
FaceNeighbors := TNeighborDetector.Create(C_NEIGHBTYPE_FACE_FACE_FROM_EDGE);
FaceNeighbors.BuildUpData((CurrentGeometry^ as TMeshBRepGeometry).Faces,(CurrentGeometry^ as TMeshBRepGeometry).VerticesPerFace,High(Vertices)+1);
end;
while CurrentGeometry <> nil do
begin
(CurrentGeometry^ as TMeshBRepGeometry).FillSmoothnessHistogram(_Histogram,Vertices,FaceNeighbors);
Geometry.GoToNextElement;
CurrentGeometry := Geometry.Current;
end;
end;
// Plugins
procedure TMesh.AddNormalsPlugin;
var
NewPlugin : PMeshPluginBase;
begin
new(NewPlugin);
NewPlugin^ := TNormalsMeshPlugin.Create();
SetLength(Plugins,High(Plugins)+2);
Plugins[High(Plugins)] := NewPlugin;
ForceRefresh;
end;
procedure TMesh.AddNeighborhoodPlugin;
var
NewPlugin : PMeshPluginBase;
begin
new(NewPlugin);
Geometry.GoToFirstElement;
NewPlugin^ := TNeighborhoodDataPlugin.Create(Geometry,High(Vertices)+1);
SetLength(Plugins,High(Plugins)+2);
Plugins[High(Plugins)] := NewPlugin;
ForceRefresh;
end;
procedure TMesh.AddBumpMapDataPlugin;
var
NewPlugin : PMeshPluginBase;
begin
new(NewPlugin);
Geometry.GoToFirstElement;
NewPlugin^ := TBumpMapDataPlugin.Create(Vertices,Normals,TexCoords,(Geometry.Current^ as TMeshBRepGeometry).Faces,(Geometry.Current^ as TMeshBRepGeometry).VerticesPerFace);
SetLength(Plugins,High(Plugins)+2);
Plugins[High(Plugins)] := NewPlugin;
ForceRefresh;
end;
procedure TMesh.AddHalfEdgePlugin(_ID: integer);
var
NewPlugin : PMeshPluginBase;
i: integer;
begin
Geometry.GoToFirstElement;
i := 0;
while i < _ID do
begin
Geometry.GoToNextElement;
inc(i);
end;
if Geometry.Current <> nil then
begin
new(NewPlugin);
NewPlugin^ := THalfEdgePlugin.Create(i,Vertices,(Geometry.Current^ as TMeshBRepGeometry).Faces,(Geometry.Current^ as TMeshBRepGeometry).VerticesPerFace);
SetLength(Plugins,High(Plugins)+2);
Plugins[High(Plugins)] := NewPlugin;
ForceRefresh;
end;
end;
procedure TMesh.AddHalfEdgePlugin;
var
NewPlugin : PMeshPluginBase;
i: integer;
begin
Geometry.GoToFirstElement;
i := 0;
while Geometry.Current <> nil do
begin
new(NewPlugin);
NewPlugin^ := THalfEdgePlugin.Create(i,Vertices,(Geometry.Current^ as TMeshBRepGeometry).Faces,(Geometry.Current^ as TMeshBRepGeometry).VerticesPerFace);
SetLength(Plugins,High(Plugins)+2);
Plugins[High(Plugins)] := NewPlugin;
Geometry.GoToNextElement;
inc(i);
end;
ForceRefresh;
end;
procedure TMesh.RemovePlugin(_PluginType: integer);
var
i : integer;
begin
i := Low(Plugins);
while i <= High(Plugins) do
begin
if Plugins[i] <> nil then
begin
if Plugins[i]^.PluginType = _PluginType then
begin
Plugins[i]^.Free;
while i < High(Plugins) do
begin
Plugins[i] := Plugins[i+1];
inc(i);
end;
end;
end;
inc(i);
end;
SetLength(Plugins,High(Plugins));
ForceRefresh;
end;
procedure TMesh.ClearPlugins;
var
i : integer;
begin
for i := Low(Plugins) to High(Plugins) do
begin
if Plugins[i] <> nil then
begin
Plugins[i]^.Free;
end;
end;
SetLength(Plugins,0);
end;
function TMesh.IsPluginEnabled(_PluginType: integer): boolean;
var
i : integer;
begin
Result := false;
i := Low(Plugins);
while i <= High(Plugins) do
begin
if Plugins[i] <> nil then
begin
if Plugins[i]^.PluginType = _PluginType then
begin
Result := true;
exit;
end;
end;
inc(i);
end;
end;
function TMesh.GetPlugin(_PluginType: integer): PMeshPluginBase;
var
i : integer;
begin
i := Low(Plugins);
while i <= High(Plugins) do
begin
if Plugins[i] <> nil then
begin
if Plugins[i]^.PluginType = _PluginType then
begin
Result := Plugins[i];
exit;
end;
end;
inc(i);
end;
Result := nil;
end;
// Miscelaneous
procedure TMesh.OverrideTransparency;
var
c : integer;
CurrentGeometry: PMeshGeometryBase;
begin
for c := Low(Colours) to High(Colours) do
begin
Colours[c].W := TransparencyLevel;
end;
Geometry.GoToFirstElement;
CurrentGeometry := Geometry.Current;
while CurrentGeometry <> nil do
begin
(CurrentGeometry^ as TMeshBRepGeometry).OverrideTransparency(TransparencyLevel);
Geometry.GoToNextElement;
CurrentGeometry := Geometry.Current;
end;
end;
procedure TMesh.ForceTransparencyLevel(_TransparencyLevel : single);
begin
TransparencyLevel := _TransparencyLevel;
OverrideTransparency;
ForceRefresh;
end;
procedure TMesh.RemoveInvisibleFaces;
var
CurrentGeometry: PMeshGeometryBase;
begin
Geometry.GoToFirstElement;
CurrentGeometry := Geometry.Current;
while CurrentGeometry <> nil do
begin
(CurrentGeometry^ as TMeshBRepGeometry).RemoveInvisibleFaces(Addr(Self));
Geometry.GoToNextElement;
CurrentGeometry := Geometry.Current;
end;
end;
// Mesh compression and uncompression
function TMesh.GetNumVerticesCompressed: cardinal;
begin
Result := High(Vertices) + 1;
end;
function TMesh.GetNumVerticesUnCompressed: cardinal;
begin
Result := NumVertices;
end;
function TMesh.GetLastVertexCompressed: cardinal;
begin
Result := High(Vertices);
end;
function TMesh.GetLastVertexUnCompressed: cardinal;
begin
Result := LastVertex;
end;
procedure TMesh.UncompressMesh;
begin
NumVertices := High(Vertices)+1;
LastVertex := High(Vertices);
GetNumVertices := GetNumVerticesUncompressed;
GetLastVertex := GetLastVertexUncompressed;
end;
procedure TMesh.CompressMesh;
begin
if High(TexCoords) = High(Vertices) then
SetLength(TexCoords, NumVertices);
if High(Normals) = High(Vertices) then
SetLength(Normals, NumVertices);
if High(Colours) = High(Vertices) then
SetLength(Colours, NumVertices);
SetLength(Vertices, NumVertices);
GetNumVertices := GetNumVerticesCompressed;
GetLastVertex := GetLastVertexCompressed;
end;
procedure TMesh.AddVertices(_NumVertices: Cardinal);
var
NewSize: cardinal;
begin
NumVertices := NumVertices + _NumVertices;
LastVertex := NumVertices - 1;
if NumVertices >= High(Vertices) then
begin
NewSize := NumVertices * 2;
if High(TexCoords) = High(Vertices) then
SetLength(TexCoords, NewSize);
if High(Normals) = High(Vertices) then
SetLength(Normals, NewSize);
if High(Colours) = High(Vertices) then
SetLength(Colours, NewSize);
SetLength(Vertices, NewSize);
end;
end;
// Debug
procedure TMesh.Debug(const _Debug:TDebugFile);
var
i: integer;
CurrentGeometry: PMeshGeometryBase;
begin
_Debug.Add('Mesh ' + Name + ' with ID ' + IntToStr(ID) + ' Starts Here:' + #13#10);
if High(Vertices) > 0 then
begin
_Debug.Add(IntToStr(High(Vertices)+1) + ' vertices:' + #13#10);
for i := Low(Vertices) to High(Vertices) do
begin
_Debug.Add(IntToStr(i) + ' = [' + FloatToStr(Vertices[i].X) + ' ' + FloatToStr(Vertices[i].Y) + ' ' + FloatToStr(Vertices[i].Z) + ']');
end;
if (High(Normals) > 0) then
begin
_Debug.Add(#13#10 + 'Vertex normals:' + #13#10);
for i := Low(Normals) to High(Normals) do
begin
_Debug.Add(IntToStr(i) + ' = [' + FloatToStr(Normals[i].X) + ' ' + FloatToStr(Normals[i].Y) + ' ' + FloatToStr(Normals[i].Z) + ']');
end;
end;
if (High(Colours) > 0) then
begin
_Debug.Add(#13#10 + 'Vertex colours:' + #13#10);
for i := Low(Colours) to High(Colours) do
begin
_Debug.Add(IntToStr(i) + ' = [' + FloatToStr(Colours[i].X) + ' ' + FloatToStr(Colours[i].Y) + ' ' + FloatToStr(Colours[i].Z) + ' ' + FloatToStr(Colours[i].W) + ']');
end;
end;
if (High(TexCoords) > 0) then
begin
_Debug.Add(#13#10 + 'Texture coordinates:' + #13#10);
for i := Low(TexCoords) to High(TexCoords) do
begin
_Debug.Add(IntToStr(i) + ' = [' + FloatToStr(TexCoords[i].U) + ' ' + FloatToStr(TexCoords[i].V) + ']');
end;
end;
end;
Geometry.GoToFirstElement;
CurrentGeometry := Geometry.Current;
while CurrentGeometry <> nil do
begin
(CurrentGeometry^ as TMeshBRepGeometry).Debug(_Debug);
Geometry.GoToNextElement;
CurrentGeometry := Geometry.Current;
end;
end;
procedure TMesh.DebugVertexPositions(const _Debug:TDebugFile);
var
i: integer;
begin
if High(Vertices) > 0 then
begin
_Debug.Add('Mesh ' + Name + ' with ID ' + IntToStr(ID) + ' has the following ' + IntToStr(High(Vertices)+1) + ' vertices:' + #13#10);
for i := Low(Vertices) to High(Vertices) do
begin
_Debug.Add(IntToStr(i) + ' = [' + FloatToStr(Vertices[i].X) + ' ' + FloatToStr(Vertices[i].Y) + ' ' + FloatToStr(Vertices[i].Z) + ']');
end;
end;
end;
procedure TMesh.DebugVertexNormals(const _Debug:TDebugFile);
var
i: integer;
begin
if High(Normals) > 0 then
begin
_Debug.Add('Mesh ' + Name + ' with ID ' + IntToStr(ID) + ' has the following ' + IntToStr(High(Vertices)+1) + ' normals:' + #13#10);
for i := Low(Normals) to High(Normals) do
begin
_Debug.Add(IntToStr(i) + ' = [' + FloatToStr(Normals[i].X) + ' ' + FloatToStr(Normals[i].Y) + ' ' + FloatToStr(Normals[i].Z) + ']');
end;
end;
end;
procedure TMesh.DebugVertexColours(const _Debug:TDebugFile);
var
i: integer;
begin
if High(Colours) > 0 then
begin
_Debug.Add('Mesh ' + Name + ' with ID ' + IntToStr(ID) + ' has the following ' + IntToStr(High(Vertices)+1) + ' colours:' + #13#10);
for i := Low(Colours) to High(Colours) do
begin
_Debug.Add(IntToStr(i) + ' = [' + FloatToStr(Colours[i].X) + ' ' + FloatToStr(Colours[i].Y) + ' ' + FloatToStr(Colours[i].Z) + ' ' + FloatToStr(Colours[i].W) + ']');
end;
end;
end;
procedure TMesh.DebugVertexTexCoordss(const _Debug:TDebugFile);
var
i: integer;
begin
if High(TexCoords) > 0 then
begin
_Debug.Add('Mesh ' + Name + ' with ID ' + IntToStr(ID) + ' has the following ' + IntToStr(High(Vertices)+1) + ' texture coordinates:' + #13#10);
for i := Low(TexCoords) to High(TexCoords) do
begin
_Debug.Add(IntToStr(i) + ' = [' + FloatToStr(TexCoords[i].U) + ' ' + FloatToStr(TexCoords[i].V) + ']');
end;
end;
end;
end.
|
unit UPedidoVenda;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.Grids, Vcl.DBGrids,
Datasnap.DBClient, Vcl.StdCtrls, Vcl.ExtCtrls, FireDAC.Phys.MySQLDef,
FireDAC.Stan.Intf, FireDAC.Phys, FireDAC.Phys.MySQL, Vcl.Buttons, Vcl.ComCtrls;
type
TFrmPedidoVenda = class(TForm)
pnlInferior: TPanel;
btnFechar: TButton;
btnGravarPedido: TButton;
pnlCabecalho: TPanel;
pnlItens: TPanel;
CDSItens: TClientDataSet;
DItens: TDataSource;
DBGridItens: TDBGrid;
pnlCadastroItem: TPanel;
EditCliente: TLabeledEdit;
btnPesqPedidos: TSpeedButton;
EditDtEmissao: TDateTimePicker;
Label1: TLabel;
EditNomeCliente: TEdit;
EditVlrTotal: TLabeledEdit;
Panel1: TPanel;
btnInserirItem: TButton;
btnAlterarItem: TButton;
btnExcluirItem: TButton;
CDSItensProduto: TIntegerField;
CDSItensDescricao: TStringField;
CDSItensQuantidade: TFloatField;
CDSItensVlr_Unit: TFloatField;
CDSItensVlr_Total: TFloatField;
Panel2: TPanel;
BtnCancelarItem: TButton;
btnConfirmarItem: TButton;
EditProduto: TLabeledEdit;
EditDescricaoProduto: TEdit;
EditVlrUnit: TLabeledEdit;
EditQtde: TLabeledEdit;
lblTotalPedido: TLabel;
EditPedido: TLabeledEdit;
EditCidade: TEdit;
EditUF: TEdit;
pnlPedido: TPanel;
EditPedidoPesquisa: TLabeledEdit;
btnConfirmaPedidoPesquisa: TButton;
CDSItensItem: TIntegerField;
procedure btnFecharClick(Sender: TObject);
procedure EditClienteExit(Sender: TObject);
procedure EditClienteEnter(Sender: TObject);
procedure btnExcluirItemClick(Sender: TObject);
procedure DBGridItensKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure DBGridItensKeyPress(Sender: TObject; var Key: Char);
procedure DBGridItensDrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
procedure DBGridItensDblClick(Sender: TObject);
procedure btnAlterarItemClick(Sender: TObject);
procedure BtnCancelarItemClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure EditProdutoExit(Sender: TObject);
procedure btnConfirmarItemClick(Sender: TObject);
procedure btnInserirItemClick(Sender: TObject);
procedure EditVlrUnitExit(Sender: TObject);
procedure EditQtdeExit(Sender: TObject);
procedure btnPesqPedidosClick(Sender: TObject);
procedure btnConfirmaPedidoPesquisaClick(Sender: TObject);
procedure btnGravarPedidoClick(Sender: TObject);
private
function StringToValor(pValor: String): Double;
function ValorToString(pValor: Double; const pMoeda: Boolean = True): String;
function FormataVlrString(pValor: String): String;
function ItemValido: Boolean;
procedure LimparTelaItens;
procedure CarregaItem;
procedure CalculaTotal;
procedure ChamaTelaItem;
procedure FechaTelaItem;
procedure CarregaPedido(pPedido: Integer);
procedure GravarPedido;
function PedidoValido: Boolean;
procedure LimparTela;
{ Private declarations }
public
{ Public declarations }
end;
var
FrmPedidoVenda: TFrmPedidoVenda;
implementation
{$R *.dfm}
uses ClassCliente, ClassConexao, ClassProduto, ClassPedido;
procedure TFrmPedidoVenda.btnAlterarItemClick(Sender: TObject);
begin
CDSItens.Edit;
CarregaItem;
ChamaTelaItem;
end;
procedure TFrmPedidoVenda.CarregaItem;
begin
EditProduto.Text := CDSItensProduto.AsString;
EditDescricaoProduto.Text := CDSItensDescricao.AsString;
EditQtde.Text := ValorToString(CDSItensQuantidade.AsFloat, False);
EditVlrUnit.Text := ValorToString(CDSItensVlr_Unit.AsFloat);
end;
procedure TFrmPedidoVenda.BtnCancelarItemClick(Sender: TObject);
begin
LimparTelaItens;
FechaTelaItem;
end;
procedure TFrmPedidoVenda.ChamaTelaItem;
begin
if EditCliente.Text <> '' then begin
pnlInferior.Enabled := False;
pnlCadastroItem.Visible := True;
EditProduto.SetFocus;
end else begin
Application.MessageBox('Informe o cliente ou selecione um pedido para continuar.', 'Atenção', MB_ICONINFORMATION + MB_OK);
end;
end;
procedure TFrmPedidoVenda.FechaTelaItem;
begin
pnlInferior.Enabled := True;
pnlCadastroItem.Visible := False;
end;
procedure TFrmPedidoVenda.btnExcluirItemClick(Sender: TObject);
begin
if not CDSItens.IsEmpty then begin
if Application.MessageBox(PChar('Deseja realmente excluir o produto: ' + CDSItensProduto.AsString + '?'),
'Atenção', MB_ICONINFORMATION + MB_YESNO) = mrYes then begin
CDSItens.Delete;
CalculaTotal;
end;
end;
end;
procedure TFrmPedidoVenda.btnFecharClick(Sender: TObject);
begin
Close;
end;
procedure TFrmPedidoVenda.btnGravarPedidoClick(Sender: TObject);
begin
if PedidoValido then begin
GravarPedido;
LimparTela;
end;
end;
procedure TFrmPedidoVenda.LimparTela;
begin
CDSItens.EmptyDataSet;
CDSItens.Close;
CDSItens.Open;
EditDtEmissao.Date := Date;
EditCliente.Clear;
EditNomeCliente.Clear;
EditCidade.Clear;
EditUF.Clear;
EditVlrTotal.Text := ValorToString(0);
EditPedido.Clear;
CalculaTotal;
EditCliente.SetFocus;
end;
procedure TFrmPedidoVenda.GravarPedido;
var
Pedido: TPedido;
nI: Integer;
begin
Pedido := TPedido.Create;
try
if EditPedido.Text <> '' then begin
Pedido.NumPedido := StrToInt(EditPedido.Text);
end;
Pedido.DtEmissao := EditDtEmissao.DateTime;
Pedido.VlrTotal := StringToValor(EditVlrTotal.Text);
Pedido.CodCliente:= StrToInt(EditCliente.Text);
CDSItens.First;
while not CDSItens.Eof do begin
Pedido.ListaItens.Add(TPedido.TItensPedido.Create);
nI := Pedido.ListaItens.Count - 1;
Pedido.ListaItens[nI].Item := CDSItensItem.AsInteger;
Pedido.ListaItens[nI].NumPedido := Pedido.NumPedido;
Pedido.ListaItens[nI].CodProduto := CDSItensProduto.AsInteger;
Pedido.ListaItens[nI].Quantidade := CDSItensQuantidade.AsFloat;
Pedido.ListaItens[nI].VlrUnit := CDSItensVlr_Unit.AsFloat;
Pedido.ListaItens[nI].VlrTotal := CDSItensVlr_Total.AsFloat;
CDSItens.Next;
end;
if Pedido.GravarPedido then begin
Application.MessageBox(PChar('Pedido: ' + IntToStr(Pedido.NumPedido) + ' realizado com sucesso.'), 'Atenção', MB_ICONINFORMATION + MB_OK);
end else begin
Application.MessageBox(PChar('Erro ao gravar pedido. Erro :' + Pedido.MsgErro), 'Erro', MB_ICONERROR + MB_OK);
end;
finally
FreeAndNil(Pedido);
end;
end;
function TFrmPedidoVenda.PedidoValido: Boolean;
begin
Result := True;
if (EditCliente.Text = '') or (EditCliente.Color = clRed) then begin
Application.MessageBox('Cliente inválido. Favor verificar!', 'Atenção', MB_ICONINFORMATION + MB_OK);
EditCliente.SetFocus;
Result := False;
end;
if (EditDtEmissao.Date < Date) and (Result) then begin
Application.MessageBox('Data deve ser maior ou igual a data atual. Favor verificar!', 'Atenção', MB_ICONINFORMATION + MB_OK);
EditDtEmissao.SetFocus;
Result := False;
end;
// if (EditPedido.Text = '') and (Result) then begin
// Application.MessageBox('Número do pedido deve ser informado. Favor verificar!', 'Atenção', MB_ICONINFORMATION + MB_OK);
// EditPedido.SetFocus;
// Result := False;
// end;
if CDSItens.IsEmpty then begin
Application.MessageBox('Pedido sem itens. Favor verificar!', 'Atenção', MB_ICONINFORMATION + MB_OK);
Result := False;
end;
end;
procedure TFrmPedidoVenda.btnConfirmaPedidoPesquisaClick(Sender: TObject);
begin
if EditPedidoPesquisa.Text <> '' then begin
CarregaPedido(StrToInt(EditPedidoPesquisa.Text));
end else begin
pnlPedido.Visible := False;
// Application.MessageBox('Informe o código do pedido para pesquisar.', 'Atenção', MB_ICONINFORMATION + MB_OK);
end;
end;
procedure TFrmPedidoVenda.btnConfirmarItemClick(Sender: TObject);
var
bFechaTela: Boolean;
begin
if ItemValido then begin
bFechaTela := CDSItens.State in [dsEdit];
CDSItensItem.AsInteger := CDSItens.RecordCount + 1;
CDSItensProduto.AsInteger := StrToInt(EditProduto.Text);
CDSItensDescricao.AsString:= EditDescricaoProduto.Text;
CDSItensQuantidade.AsFloat:= StringToValor(EditQtde.Text);
CDSItensVlr_Unit.AsFloat := StringToValor(EditVlrUnit.Text);
CDSItensVlr_Total.AsFloat := CDSItensQuantidade.AsFloat * CDSItensVlr_Unit.AsFloat;
CDSItens.Post;
LimparTelaItens;
CalculaTotal;
if bFechaTela then begin
FechaTelaItem;
end else begin
CDSItens.Insert;
EditProduto.SetFocus;
end;
end;
end;
procedure TFrmPedidoVenda.CalculaTotal;
var
nTotal: Double;
begin
CDSItens.First;
nTotal := 0;
while not CDSItens.Eof do begin
nTotal := nTotal + CDSItensVlr_Total.AsFloat;
CDSItens.Next;
end;
EditVlrTotal.Text := ValorToString(nTotal);
lblTotalPedido.Caption := 'Valor Total: ' + ValorToString(nTotal);
end;
procedure TFrmPedidoVenda.btnInserirItemClick(Sender: TObject);
begin
CDSItens.Insert;
ChamaTelaItem;
end;
procedure TFrmPedidoVenda.btnPesqPedidosClick(Sender: TObject);
begin
pnlPedido.Visible := True;
EditPedidoPesquisa.SetFocus;
end;
procedure TFrmPedidoVenda.CarregaPedido(pPedido: Integer);
var
Pedido: TPedido;
Produto: TProduto;
nI: Integer;
begin
Pedido := TPedido.Create;
Produto := TProduto.Create;
try
if Pedido.CarregaPedido(StrToInt(EditPedidoPesquisa.Text)) then begin
EditPedido.Text := IntToStr(Pedido.NumPedido);
EditDtEmissao.DateTime := Pedido.DtEmissao;
EditVlrTotal.Text := ValorToString(Pedido.VlrTotal);
EditCliente.Text := IntToStr(Pedido.CodCliente);
for nI := 0 to Pedido.ListaItens.Count - 1 do begin
CDSItens.Insert;
CDSItensItem.AsInteger := Pedido.ListaItens[nI].Item;
CDSItensProduto.AsInteger := Pedido.ListaItens[nI].CodProduto;
Produto.ValidaExiste(CDSItensProduto.AsInteger);
CDSItensDescricao.AsString := Produto.Descricao;
CDSItensQuantidade.AsFloat := Pedido.ListaItens[nI].Quantidade;
CDSItensVlr_Unit.AsFloat := Pedido.ListaItens[nI].VlrUnit;
CDSItensVlr_Total.AsFloat := Pedido.ListaItens[nI].VlrTotal;
CDSItens.Post;
end;
CalculaTotal;
EditClienteExit(EditCliente);
pnlPedido.Visible := False;
end else begin
Application.MessageBox('Pedido não encontrado.', 'Atenção', MB_ICONINFORMATION + MB_OK);
LimparTela;
EditPedidoPesquisa.SetFocus;
end;
finally
FreeAndNil(Produto);
FreeAndNil(Pedido);
end;
end;
procedure TFrmPedidoVenda.LimparTelaItens;
begin
CDSItens.Cancel;
EditProduto.Text := '';
EditDescricaoProduto.Text := '';
EditQtde.Text := ValorToString(0, False);
EditVlrUnit.Text := ValorToString(0);
end;
function TFrmPedidoVenda.ItemValido: Boolean;
begin
Result := True;
if (EditProduto.Text = '') or (EditProduto.Color = clRed) then begin
Application.MessageBox('Produto inválido. Favor verificar!', 'Atenção', MB_ICONINFORMATION + MB_OK);
EditProduto.SetFocus;
Result := False;
end;
if (StringToValor(EditQtde.Text) = 0) and (Result) then begin
Application.MessageBox('Quantidade deve ser informada. Favor verificar!', 'Atenção', MB_ICONINFORMATION + MB_OK);
EditQtde.SetFocus;
Result := False;
end;
if (StringToValor(EditVlrUnit.Text) = 0) and (Result) then begin
Application.MessageBox('Valor unitário deve ser informado. Favor verificar!', 'Atenção', MB_ICONINFORMATION + MB_OK);
EditVlrUnit.SetFocus;
Result := False;
end;
end;
procedure TFrmPedidoVenda.DBGridItensDblClick(Sender: TObject);
begin
btnAlterarItem.Click;
end;
procedure TFrmPedidoVenda.DBGridItensDrawColumnCell(Sender: TObject;
const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
if not CDSItens.IsEmpty then begin
if not odd(DItens.DataSet.RecNo) then begin
if not (gdSelected in State) then begin
DBGridItens.Canvas.Brush.Color := clGradientActiveCaption;
DBGridItens.Canvas.FillRect(Rect);
DBGridItens.DefaultDrawDataCell(rect,Column.Field,State);
DBGridItens.DefaultDrawColumnCell(rect,DataCol,Column,state);
end;
end;
end;
end;
procedure TFrmPedidoVenda.DBGridItensKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_DELETE then begin
btnExcluirItem.Click;
end;
end;
procedure TFrmPedidoVenda.DBGridItensKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then begin
btnAlterarItem.Click;
end;
end;
procedure TFrmPedidoVenda.EditClienteEnter(Sender: TObject);
begin
TLabeledEdit(Sender).Color := clWindow;
end;
procedure TFrmPedidoVenda.EditClienteExit(Sender: TObject);
var
Cliente: TCliente;
begin
if EditCliente.Text <> '' then begin
Cliente := TCliente.Create;
try
if Cliente.ValidaExiste(StrToInt(EditCliente.Text)) then begin
EditNomeCliente.Text := Cliente.Nome;
EditCidade.Text := Cliente.Cidade;
EditUF.Text := Cliente.UF;
EditCliente.Color := clGreen;
end else begin
Application.MessageBox('Cliente não cadastrado. Favor verificar!', 'Atenção', MB_ICONEXCLAMATION+MB_OK);
EditCliente.Color := clRed;
end;
finally
Cliente.Free;
end;
end else begin
EditCliente.Color := clRed;
// LimparTela;
end;
btnPesqPedidos.Visible := EditCliente.Text = '';
end;
procedure TFrmPedidoVenda.EditProdutoExit(Sender: TObject);
var
Produto: TProduto;
begin
if EditProduto.Text <> '' then begin
Produto := TProduto.Create;
try
if Produto.ValidaExiste(StrToInt(EditProduto.Text)) then begin
EditDescricaoProduto.Text := Produto.Descricao;
EditVlrUnit.Text := ValorToString(Produto.PrecoVenda);
EditProduto.Color := clGreen;
end else begin
Application.MessageBox('Produto não cadastrado. Favor verificar!', 'Atenção', MB_ICONEXCLAMATION+MB_OK);
EditProduto.Color := clRed;
end;
finally
Produto.Free;
end;
end else begin
EditProduto.Color := clRed;
end;
end;
procedure TFrmPedidoVenda.EditQtdeExit(Sender: TObject);
begin
EditQtde.Text := ValorToString(StringToValor(EditQtde.Text), False);
end;
procedure TFrmPedidoVenda.EditVlrUnitExit(Sender: TObject);
begin
EditVlrUnit.Text := ValorToString(StringToValor(EditVlrUnit.Text));
end;
procedure TFrmPedidoVenda.FormClose(Sender: TObject; var Action: TCloseAction);
begin
CDSItens.Close;
end;
procedure TFrmPedidoVenda.FormShow(Sender: TObject);
begin
CDSItens.CreateDataSet;
LimparTela;
end;
function TFrmPedidoVenda.ValorToString(pValor: Double; const pMoeda: Boolean = True): String;
begin
if pMoeda then begin
Result := FormatCurr('R$ ###,##0.00', pValor);
end else begin
Result := FormatFloat('#,##0.00', pValor);
end;
end;
function TFrmPedidoVenda.StringToValor(pValor: String): Double;
begin
Result := StrToFloat(FormataVlrString(pValor));
end;
function TFrmPedidoVenda.FormataVlrString(pValor: String): String;
begin
Result := StringReplace(pValor, '.', '', [rfReplaceAll]);
Result := StringReplace(Result, 'R', '', [rfReplaceAll]);
Result := StringReplace(Result, '$', '', [rfReplaceAll]);
Result := StringReplace(Result, ' ', '', [rfReplaceAll]);
end;
end.
|
unit FormPreferences;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ImgList, StdCtrls, ComCtrls, ExtCtrls, Registry, Voxel_Engine;
type
TFrmPreferences = class(TForm)
GroupBox1: TGroupBox;
Pref_List: TTreeView;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
AssociateCheck: TCheckBox;
GroupBox3: TGroupBox;
IconPrev: TImage;
IconID: TTrackBar;
BtnApply: TButton;
TabSheet2: TTabSheet;
CheckBox1: TCheckBox;
Label1: TLabel;
Label2: TLabel;
ComboBox2: TComboBoxEx;
ComboBox1: TComboBoxEx;
Bevel2: TBevel;
Panel1: TPanel;
Image1: TImage;
Label9: TLabel;
Label10: TLabel;
Bevel3: TBevel;
Panel2: TPanel;
Button4: TButton;
Button1: TButton;
procedure BtnApplyClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure IconIDChange(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Pref_ListClick(Sender: TObject);
procedure Pref_ListKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure Pref_ListKeyPress(Sender: TObject; var Key: Char);
procedure Pref_ListKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure CheckBox1Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
IconPath: String;
procedure ExtractIcon;
procedure GetSettings;
end;
var
FrmPreferences: TFrmPreferences;
implementation
uses FormMain;
{$R *.dfm}
procedure TFrmPreferences.ExtractIcon;
var
sWinDir: String;
iLength: Integer;
{Res: TResourceStream; }
MIcon: TIcon;
begin
// Initialize Variable
iLength := 255;
setLength(sWinDir, iLength);
iLength := GetWindowsDirectory(PChar(sWinDir), iLength);
setLength(sWinDir, iLength);
IconPath := sWinDir + '\vxlse'+inttostr(IconID.Position)+'.ico';
MIcon := TIcon.Create;
FrmMain.IconList.GetIcon(IconID.Position,MIcon);
MIcon.SaveToFile(IconPath);
MIcon.Free;
end;
procedure TFrmPreferences.GetSettings;
begin
IconIDChange(Self);
end;
procedure TFrmPreferences.BtnApplyClick(Sender: TObject);
var
Reg: TRegistry;
begin
ExtractIcon;
Reg :=TRegistry.Create;
Reg.RootKey := HKEY_CLASSES_ROOT;
Config.Icon := IconID.Position;
Config.Assoc := AssociateCheck.Checked;
Config.Palette := CheckBox1.Checked;
if ComboBox1.ItemIndex = 0 {< 1}then
Config.TS := 'TS'
else if ComboBox1.ItemIndex = 1 then
Config.TS := 'RA2'
else
begin
ShowMessage('I am going here with ' + IntToStr(ComboBox1.ItemIndex));
Config.TS := ComboBox1.Items.Strings[ComboBox1.ItemIndex];
end;
if ComboBox2.ItemIndex = 0 then
Config.RA2 := 'TS'
else if (ComboBox2.ItemIndex = 1) then// or (frm.ComboBox2.ItemIndex = -1) then
Config.RA2 := 'RA2'
else
Config.RA2 := ComboBox2.Items.Strings[ComboBox2.ItemIndex];
if Reg.OpenKey('\VXLSe\DefaultIcon\',true) then
begin
Reg.WriteString('',IconPath);
Reg.CloseKey;
end;
if AssociateCheck.Checked = true then
begin
Reg.RootKey := HKEY_CLASSES_ROOT;
if Reg.OpenKey('\.vxl\',true) then
begin
Reg.WriteString('','VXLSe');
Reg.CloseKey;
Reg.RootKey := HKEY_CLASSES_ROOT;
if Reg.OpenKey('\VXLSe\shell\',true) then
begin
Reg.WriteString('','Open');
if Reg.OpenKey('\VXLSe\shell\open\command\',true) then
begin
Reg.WriteString('',ParamStr(0)+' %1');
end;
Reg.CloseKey;
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKey('\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.vxl\',true) then
begin
Reg.WriteString('Application',ParamStr(0)+' "%1"');
Reg.CloseKey;
end
else
begin
ShowMessage('VXLSE III was not able to associate .vxl files because you are under a non-administrative account or does not have enough rights to do it. Contact the system administrator if you need any help');
end;
end
else
begin
ShowMessage('VXLSE III was not able to associate .vxl files because you are under a non-administrative account or does not have enough rights to do it. Contact the system administrator if you need any help');
close;
end;
end
else
begin
ShowMessage('VXLSE III was not able to associate .vxl files because you are under a non-administrative account or does not have enough rights to do it. Contact the system administrator if you need any help');
close;
end;
end
else
begin
Reg.RootKey := HKEY_CLASSES_ROOT;
Reg.DeleteKey('.vxl');
Reg.CloseKey;
Reg.RootKey := HKEY_CLASSES_ROOT;
Reg.DeleteKey('\VXLSe\');
Reg.CloseKey;
Reg.RootKey := HKEY_CURRENT_USER;
Reg.DeleteKey('\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.vxl\');
Reg.CloseKey;
end;
Reg.Free;
end;
function GetComboBoxNo(filename:string; default : cardinal): cardinal;
var
f_name : string;
begin
f_name := ansilowercase(filename);
result := default;
if f_name = 'vxlseii_ts.vpal' then
result := 0
else if f_name = 'vxlseii_ra2.vpal' then
result := 1
else if f_name = 'vxlseii.vpal' then
result := 2
end;
function GetFilenameFromNo(itemindex:cardinal): string;
begin
if itemindex = 0 then
result := 'vxlseii_ts.vpal'
else if itemindex = 1 then
result := 'vxlseii_ra2.vpal'
else if itemindex = 2 then
result := 'vxlseii.vpal';
end;
procedure TFrmPreferences.FormShow(Sender: TObject);
begin
GetSettings;
PageControl1.ActivePageIndex := 0;
GroupBox1.Caption := 'File Associations';
ComboBox1.ItemIndex := 0;
ComboBox2.ItemIndex := 1;
end;
procedure TFrmPreferences.IconIDChange(Sender: TObject);
var
MIcon: TIcon;//Icon: TResourceStream;
begin
// Icon := TResourceStream.Create(hInstance,'Icon_'+IntToStr(IconID.Position+1),RT_RCDATA);
MIcon := TIcon.Create;
FrmMain.IconList.GetIcon(IconID.Position,MIcon);
IconPrev.Picture.Icon := MIcon;
// Icon.Free;
MIcon.Free;
end;
procedure TFrmPreferences.Button2Click(Sender: TObject);
begin
Close;
end;
procedure TFrmPreferences.Pref_ListClick(Sender: TObject);
begin
if pref_list.SelectionCount > 0 then
begin
if pref_list.Selected.Text = 'File Associations' then
PageControl1.ActivePageIndex := 0;
if pref_list.Selected.Text = 'Palette' then
PageControl1.ActivePageIndex := 1;
GroupBox1.Caption := pref_list.Selected.Text;
end;
end;
procedure TFrmPreferences.Pref_ListKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
Pref_ListClick(sender);
end;
procedure TFrmPreferences.Pref_ListKeyPress(Sender: TObject;
var Key: Char);
begin
Pref_ListClick(sender);
end;
procedure TFrmPreferences.Pref_ListKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
Pref_ListClick(sender);
end;
procedure TFrmPreferences.CheckBox1Click(Sender: TObject);
begin
Label1.Enabled := CheckBox1.Checked;
Label2.Enabled := CheckBox1.Checked;
ComboBox1.Enabled := CheckBox1.Checked;
ComboBox2.Enabled := CheckBox1.Checked;
end;
procedure TFrmPreferences.Button4Click(Sender: TObject);
begin
BtnApplyClick(Sender);
Close;
end;
procedure TFrmPreferences.FormCreate(Sender: TObject);
var
x : integer;
begin
Panel1.DoubleBuffered := true;
Image1.Picture := FrmMain.TopBarImageHolder.Picture;
IconID.Max := FrmMain.IconList.Count-1;
IconID.Position := Config.Icon;
AssociateCheck.Checked := Config.Assoc;
CheckBox1.Checked := Config.Palette;
ComboBox1.Clear;
ComboBox1.Items.Add('unittem.pal');
ComboBox1.ItemsEX.Items[ComboBox1.Items.Count-1].ImageIndex := 15;
ComboBox1.Items.Add('unittem.pal');
ComboBox1.ItemsEX.Items[ComboBox1.Items.Count-1].ImageIndex := 16;
if PaletteList.Data_no > 0 then
for x := 0 to PaletteList.Data_no-1 do
begin
ComboBox1.Items.Add(ExtractFileName(PaletteList.Data[x]));
ComboBox1.ItemsEX.Items[ComboBox1.Items.Count-1].ImageIndex := 24;
end;
ComboBox2.Clear;
ComboBox2.Items.Add('unittem.pal');
ComboBox2.ItemsEX.Items[ComboBox2.Items.Count-1].ImageIndex := 15;
ComboBox2.Items.Add('unittem.pal');
ComboBox2.ItemsEX.Items[ComboBox2.Items.Count-1].ImageIndex := 16;
if PaletteList.Data_no > 0 then
for x := 0 to PaletteList.Data_no-1 do
begin
ComboBox2.Items.Add(ExtractFileName(PaletteList.Data[x]));
ComboBox2.ItemsEX.Items[ComboBox2.Items.Count-1].ImageIndex := 24;
end;
end;
end.
|
unit Parser;
{$mode objfpc}
{$H+}
interface
uses contnrs, regexpr, fpexprpars, classes, SysUtils;
type
TParserDefinitions = class
private
m_table : TFPStringHashTable;
procedure CopyIterateFn(Item: String; const Key: String; var Continue: Boolean);
function GetItem(Id: string): string;
procedure SetItem(Id: string; Val: string);
protected
public
constructor New;
constructor Inherit(env : TParserDefinitions);
destructor Destroy; override;
procedure Substitute(s: string; var expr: TFPExpressionParser);
property Definition[Id: string] : string read GetItem write SetItem;
end;
TDefReplaceHelper = class
s: string;
expr: TFPExpressionParser;
env: TParserDefinitions;
procedure it(Item: string; const Key: string; var Continue: Boolean);
end;
TParser = class
private
m_env : TParserDefinitions;
m_buffer : TStringStream;
procedure AddLine(s: string);
procedure ParseIncludeDefs(s: string; var env: TParserDefinitions);
procedure ParseAssignation(captured: string; var env: TParserDefinitions);
function GetBufferAsString: string;
protected
public
constructor New(env : TParserDefinitions);
destructor Destroy; override;
procedure Enter(path : string);
property Buffer : string read GetBufferAsString;
end;
function SuperReplace(who, first, last, s: string): string;
procedure mytest;
implementation
(* TDefReplaceHelper *)
procedure TDefReplaceHelper.it(Item: String; const Key: String; var Continue: Boolean);
begin
if pos(key, s) > 0 then
try
expr.Identifiers.AddIntegerVariable(key, StrToInt(Item));
except
on ex: Exception do begin
writeln(StdErr, ex.Message);
expr.Identifiers.AddStringVariable(key, Item);
end;
end;
end;
(* TParserDefinitions *)
constructor TParserDefinitions.New;
begin
m_table := TFPStringHashTable.Create;
end;
constructor TParserDefinitions.Inherit(env : TParserDefinitions);
var
table: TFPStringHashTable;
begin
table := env.m_table;
m_table := TFPStringHashTable.Create;
table.Iterate(@Self.CopyIterateFn);
end;
destructor TParserDefinitions.Destroy;
begin
m_table.Free;
Inherited;
end;
procedure TParserDefinitions.CopyIterateFn(Item: string; const Key: string; var Continue: Boolean);
begin
m_table.Add(Key, Item);
end;
function TParserDefinitions.GetItem(Id: string): string;
begin
Result := m_table.Items[Id];
end;
procedure TParserDefinitions.SetItem(Id: string; Val: string);
begin
if m_table.Find(Id) <> Nil then
m_table.Items[Id] := Val
else
m_table.Add(Id, Val);
end;
procedure TParserDefinitions.Substitute(s: string; var expr: TFPExpressionParser);
var
obj: TDefReplaceHelper;
begin
obj := tDefReplaceHelper.Create;
obj.s := s;
obj.expr := expr;
obj.env := Self;
m_table.Iterate(@obj.it);
obj.Free;
end;
(* TParser *)
constructor TParser.New(env : TParserDefinitions);
begin
m_env := TParserDefinitions.Inherit(env);
m_buffer := TStringStream.Create('');
end;
destructor TParser.Destroy;
begin
m_buffer.Free;
m_env.Free;
Inherited;
end;
function TParser.GetBufferAsString: string;
begin
Result := m_buffer.DataString;
end;
procedure TParser.AddLine(s: string);
begin
m_buffer.WriteString(s + LineEnding);
end;
procedure TParser.ParseAssignation(captured: string; var env: TParserDefinitions);
var
sleft, sexpr: string;
exprParser: TFPExpressionParser;
exprResult: TFPExpressionResult;
begin
if pos(':=', captured) > 0 then begin
sleft := copy(captured, 1, pos(':=', captured) - 1);
sexpr := copy(captured, pos(':=', captured) + 2, length(captured));
exprParser := TFPExpressionParser.Create(nil);
exprParser.Builtins := [bcMath, bcConversion, bcStrings];
(* replace variables with values *)
env.Substitute(sexpr, exprParser);
try
exprParser.Expression := sexpr;
exprResult := exprParser.Evaluate;
case exprResult.ResultType of
rtFloat: env.Definition[sleft] := IntToStr(Trunc(exprResult.ResFloat));
rtInteger: env.Definition[sleft] := IntToStr(exprResult.ResInteger);
rtString: env.Definition[sleft] := exprResult.ResString;
end;
except
on e: Exception do begin
writeln(e.ClassName);
writeln(e.Message);
end;
end;
exprParser.Free;
end else begin
sleft := copy(captured, 1, pos('=', captured) - 1);
sexpr := copy(captured, pos('=', captured) + 1, length(captured));
env.Definition[sleft] := sexpr;
end;
end;
procedure TParser.ParseIncludeDefs(s: string; var env: TParserDefinitions);
var
endPos: integer;
beginPos: integer;
expr: string;
begin
endPos := length(s);
beginPos := 1;
while pos('$', s) > 0 do begin
beginPos := pos('$', s);
endPos := length(s);
if pos('$', copy(s, beginPos + 1, length(s))) > 0 then
endPos := pos('$', copy(s, beginPos + 1, length(s)));
expr := copy(s, beginPos + 1, endPos - beginPos);
s := copy(s, endPos + 1, length(s));
ParseAssignation(expr, env);
end;
end;
procedure TParser.Enter(path: string);
var
f: TextFile;
line: string;
captured: string;
r_angular, r_square, r_curly: TRegExpr;
r_any: TRegExpr;
r: TRegExpr;
sleft, sexpr: string;
r_parseSquare: TRegExpr;
r_count, r_file, s: string;
r_aggregate: string;
nbOfInserts: integer;
newEnv: TParserDefinitions;
newParser: TParser;
comment: string;
begin
(* open file
for each line
regex <.*>, [.*], {.*} non greedy
update env if [] or {}
call reentrant parser if {}
inject new text if <> or {}
*)
AssignFile(f, path);
r_angular:= TRegExpr.Create;
r_square := TRegExpr.Create;
r_curly := TRegExpr.Create;
r_any := TRegExpr.Create;
r_parseSquare := TRegExpr.Create;
r_Square.Expression := '\[([^\]]*)\]';
r_angular.Expression := '<([^>]*)>';
r_curly.Expression := '\{([^\}]*)\}';
r_any.Expression := '([\[{<])';
//r_parseSquare.Expression := '^([0-9]+x)?([^\$]*)(\$.*)$';
r_parseSquare.Expression := '^([0-9]+x)?([^\$]*)(\$.*)?$';
try
Reset(f);
repeat
readln(f, line);
if pos('#', line) > 0 then begin
comment := copy(line, pos('#', line), length(line));
line := copy(line, 1, pos('#', line) - 1);
end else
comment := '';
while r_any.Exec(line) do begin
case r_any.Match[1][1] of
'[': begin
r_square.Exec(line);
captured := r_square.Match[1];
if pos('=', captured) <= 0 then begin
writeln('Error: invalid assignation');
halt(1);
end;
ParseAssignation(captured, m_env);
line := SuperReplace(line, '[', ']', '');
end;
'<': begin
r_angular.Exec(line);
line := SuperReplace(line, '<', '>', m_env.Definition[r_angular.Match[1]]);
end;
'{': begin
newEnv := TParserDefinitions.Inherit(m_env);
(* parse string => count, filename, def's *)
if not r_curly.Exec(line) then
writeln('regex failed???');
if not r_parseSquare.Exec(r_curly.Match[1]) then
writeln('other regex failed???');
r_count := r_parseSquare.Match[1];
r_file := r_parseSquare.Match[2];
s := r_parseSquare.Match[3];
if length(r_count) > 0 then
nbOfInserts := StrToInt(copy(r_count, 1, length(r_count) - 1))
else
nbOfInserts := 1;
ParseIncludeDefs(s, newEnv);
(* launch a new parser *)
newParser := TParser.New(newEnv);
newEnv.Free;
newParser.Enter(r_file);
(* replace include with the parser's buffer *)
r_aggregate := '';
while nbOfInserts > 0 do begin
r_aggregate := r_aggregate + newParser.Buffer;
dec(nbOfInserts);
end;
line := SuperReplace(line, '{', '}', r_aggregate);
newParser.Free;
end;
end;
end;
AddLine(line + comment);
until(EOF(f));
finally
CloseFile(f);
end;
r_angular.Free;
r_square.Free;
r_curly.Free;
r_parseSquare.Free;
end;
(* SuperReplace *)
function SuperReplace(who, first, last, s: string): string;
var
intermed, rema: string;
begin
intermed := copy(who, 1, pos(first, who) - 1);
rema := copy(who, pos(first, who) + 1, length(who));
Result := intermed + s + copy(rema, pos(last, rema) + 1, length(rema))
end;
(* mytest *)
procedure mytest;
begin
writeln('hello!');
end;
end.
|
unit ContadorController;
interface
uses
System.Generics.Collections,
//
Aurelius.Engine.ObjectManager, Aurelius.Criteria.Base, Aurelius.Criteria.Expression, Aurelius.Criteria.Linq, Aurelius.Criteria.Projections,
//
Contador;
type
TContadorController = class
private
class var FManager: TObjectManager;
public
class procedure Save(AContador: TContador);
class function Update(AContador: TContador): Boolean;
class function Delete(AContador: TContador): Boolean;
class function FindObject(AFilter: TCustomCriterion): TContador;
class function FindObjectList(AFilter: TCustomCriterion): TObjectList<TContador>;
class function FindCriteria(AFilter: TCustomCriterion): TCriteria;
end;
implementation
uses
ConnectionModule;
class procedure TContadorController.Save(AContador: TContador);
begin
FManager := TObjectManager.Create(TFireDacFirebirdConnection.CreateConnection);
try
FManager.Save(AContador);
finally
FManager.Free;
end;
end;
class function TContadorController.Update(AContador: TContador): Boolean;
begin
FManager := TObjectManager.Create(TFireDacFirebirdConnection.CreateConnection);
try
FManager.Update(AContador);
Result := True;
finally
FManager.Free;
end;
end;
class function TContadorController.Delete(AContador: TContador): Boolean;
begin
FManager := TObjectManager.Create(TFireDacFirebirdConnection.CreateConnection);
try
FManager.Remove(AContador);
Result := True;
finally
FManager.Free;
end;
end;
class function TContadorController.FindObject(AFilter: TCustomCriterion): TContador;
begin
FManager := TObjectManager.Create(TFireDacFirebirdConnection.CreateConnection);
try
FManager.OwnsObjects := False;
Result := FManager.CreateCriteria<TContador>.Add(AFilter).UniqueResult;
finally
FManager.Free;
end;
end;
class function TContadorController.FindObjectList(AFilter: TCustomCriterion): TObjectList<TContador>;
begin
FManager := TObjectManager.Create(TFireDacFirebirdConnection.CreateConnection);
try
FManager.OwnsObjects := False;
Result := FManager.CreateCriteria<TContador>.Add(AFilter).List;
finally
FManager.Free;
end;
end;
class function TContadorController.FindCriteria(AFilter: TCustomCriterion): TCriteria;
begin
FManager := TObjectManager.Create(TFireDacFirebirdConnection.CreateConnection);
try
FManager.OwnsObjects := False;
Result := FManager.CreateCriteria<TContador>.Add(AFilter);
finally
FManager.Free;
end;
end;
end.
|
unit uSM;
interface
uses System.SysUtils, System.Classes, Datasnap.DSServer, Datasnap.DSAuth,
DataSnap.DSSession;
type
TSM = class(TDSServerModule)
private
{ Private declarations }
public
{ Public declarations }
function EchoString(Value: string): string;
[TRoleAuth('admin','user')]
function ReverseString(Value: string): string;
function MinhaSessao(): String;
function AddValue(key, value: String): String;
function GetValue(key: String): String;
function GetObject(key: String): TObject;
end;
implementation
{$R *.dfm}
uses System.StrUtils;
function TSM.AddValue(key, value: String): String;
var
mySession: TDSSession;
begin
mySession := TDSSessionManager.GetThreadSession;
mySession.PutData(key,value);
result := 'valor colocado em sessao';
end;
function TSM.EchoString(Value: string): string;
begin
Result := Value;
end;
function TSM.GetObject(key: String): TObject;
begin
Result := TDSSessionManager.GetThreadSession.GetObject(key);
end;
function TSM.GetValue(key: String): String;
var
mySession: TDSSession;
begin
mySession := TDSSessionManager.GetThreadSession;
result := mySession.GetData(key);
end;
function TSM.MinhaSessao: String;
begin
result := TDSSessionManager.GetThreadSession.Id.ToString;
end;
function TSM.ReverseString(Value: string): string;
begin
Result := System.StrUtils.ReverseString(Value);
end;
end.
|
{================================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmWordTree
Purpose : The TrmWordTree is a non-visual component provides a dictionary type
word lookup interface. You provide it with a list of words and then
you can verify words against it or it will provide a list of similar
words based on the soundex of the given word.
Date : 05-01-01
Author : Ryan J. Mills
Version : 1.92
================================================================================}
unit rmWordTree;
interface
{$I CompilerDefines.INC}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
type
TAddMode = (taAddFirst, taAdd) ;
TNodeAttachMode = (naAdd, naAddFirst, naAddChild, naAddChildFirst, naInsert) ;
PWTNodeInfo = ^TWTNodeInfo;
TWTNodeInfo = packed record
Letter: Char;
Count: Word;
Complete: Boolean;
end;
TCustomrmWordTree = class;
TrmWordTreeNodes = class;
TrmWordTreeNode = class;
TrmWordTreeNode = class(TPersistent)
private
FOwner: TrmWordTreeNodes;
FParent: TrmWordTreeNode;
FLetter: Char;
FComplete: boolean;
FChildList: TList;
FDeleting: Boolean;
function GetLevel: Integer;
procedure SetParent(Value: TrmWordTreeNode) ;
function GetChildren: Boolean;
function GetIndex: Integer;
function GetItem(Index: Integer) : TrmWordTreeNode;
function GetCount: Integer;
function GetWTTreeNonView: TCustomrmWordTree;
procedure ReadData(Stream: TStream; Info: PWTNodeInfo) ;
procedure SetItem(Index: Integer; Value: TrmWordTreeNode) ;
procedure WriteData(Stream: TStream; Info: PWTNodeInfo) ;
function IsEqual(Node: TrmWordTreeNode) : Boolean;
function getWord: string;
public
constructor Create(AOwner: TrmWordTreeNodes) ;
destructor Destroy; override;
procedure Assign(Source: TPersistent) ; override;
procedure Delete;
procedure DeleteChildren;
function GetFirstChild: TrmWordTreeNode;
function GetLastChild: TrmWordTreeNode;
function GetNext: TrmWordTreeNode;
function GetNextChild(Value: TrmWordTreeNode) : TrmWordTreeNode;
function GetNextSibling: TrmWordTreeNode;
function GetPrev: TrmWordTreeNode;
function GetPrevChild(Value: TrmWordTreeNode) : TrmWordTreeNode;
function getPrevSibling: TrmWordTreeNode;
function HasAsParent(Value: TrmWordTreeNode) : Boolean;
function IndexOf(Value: TrmWordTreeNode) : Integer;
property Count: Integer read GetCount;
property Complete: boolean read FComplete write fComplete;
property Deleting: Boolean read FDeleting;
property HasChildren: Boolean read GetChildren;
property Index: Integer read GetIndex;
property Item[Index: Integer]: TrmWordTreeNode read GetItem write SetItem; default;
property Level: Integer read GetLevel;
property Owner: TrmWordTreeNodes read FOwner;
property Parent: TrmWordTreeNode read FParent write SetParent;
property WTTreeNonView: TCustomrmWordTree read GetWTTreeNonView;
property Letter: Char read FLetter write FLetter;
property Word : string read getWord;
end;
TrmWordTreeNodes = class(TPersistent)
private
FOwner: TCustomrmWordTree;
FRootNodeList: TList;
function GetNodeFromIndex(Index: Integer) : TrmWordTreeNode;
procedure ReadData(Stream: TStream) ;
procedure WriteData(Stream: TStream) ;
protected
function InternalAddObject(Node: TrmWordTreeNode; const Letter: Char; Complete: boolean; AddMode: TAddMode) : TrmWordTreeNode;
procedure DefineProperties(Filer: TFiler) ; override;
function GetCount: Integer;
procedure SetItem(Index: Integer; Value: TrmWordTreeNode) ;
public
constructor Create(AOwner: TCustomrmWordTree) ;
destructor Destroy; override;
function AddChild(Node: TrmWordTreeNode; const Letter: Char) : TrmWordTreeNode;
function Add(Node: TrmWordTreeNode; const Letter: Char) : TrmWordTreeNode;
procedure Assign(Source: TPersistent) ; override;
procedure Clear;
procedure Delete(Node: TrmWordTreeNode) ;
function GetFirstNode: TrmWordTreeNode;
property Count: Integer read GetCount;
property Item[Index: Integer]: TrmWordTreeNode read GetNodeFromIndex; default;
property Owner: TCustomrmWordTree read FOwner;
end;
{ TWTCustomrmWordTree }
EWTTreeNonViewError = class(Exception) ;
TCustomrmWordTree = class(TComponent)
private
FTreeNodes: TrmWordTreeNodes;
procedure SetrmWordTreeNodes(Value: TrmWordTreeNodes) ;
protected
function CreateNode: TrmWordTreeNode; virtual;
property Items: TrmWordTreeNodes read FTreeNodes write SeTrmWordTreeNodes;
public
constructor Create(AOwner: TComponent) ; override;
destructor Destroy; override;
function AddWord(word: string) : TrmWordTreeNode;
function IsWord(word: string) : Boolean;
function LocateWord(Word: string) : TrmWordTreeNode;
procedure LoadPartialMatches(Word: String; MatchList: TStrings);
procedure LoadSEMatches(Word: String; MatchList: TStrings);
end;
TrmWordTree = class(TCustomrmWordTree)
private
{ Private declarations }
protected
{ Protected declarations }
public
{ Public declarations }
published
{ Published declarations }
property Items;
end;
implementation
uses rmLibrary;
procedure WTTreeNonViewError(const Msg: string) ;
begin
raise EWTTreeNonViewError.Create(Msg) ;
end;
constructor TrmWordTreeNode.Create(AOwner: TrmWordTreeNodes) ;
begin
inherited Create;
FOwner := AOwner;
FChildList := TList.Create;
end;
destructor TrmWordTreeNode.Destroy;
begin
FDeleting := True;
FChildList.Free;
inherited Destroy;
end;
function TrmWordTreeNode.GetWTTreeNonView: TCustomrmWordTree;
begin
Result := Owner.Owner;
end;
function TrmWordTreeNode.HasAsParent(Value: TrmWordTreeNode) : Boolean;
begin
if Value <> Nil then
begin
if Parent = nil then
Result := False
else
if Parent = Value then
Result := True
else
Result := Parent.HasAsParent(Value) ;
end
else
Result := True;
end;
function TrmWordTreeNode.GetChildren: Boolean;
begin
Result := FChildList.Count > 0;
end;
procedure TrmWordTreeNode.SetParent(Value: TrmWordTreeNode) ;
begin
if (fParent <> nil) then
fParent.FChildList.delete(fParent.FChildList.indexOf(self) ) ;
if value <> nil then
begin
FParent := Value;
if fParent.FChildList.indexof(self) = -1 then
fParent.FChildList.Add(self) ;
end;
end;
function TrmWordTreeNode.GetNextSibling: TrmWordTreeNode;
var
CurIdx: Integer;
begin
if Parent <> nil then
begin
CurIdx := Parent.FChildList.IndexOf(Self) ;
if (CurIdx + 1) < Parent.FChildList.Count then
Result := Parent.FChildList.Items[CurIdx + 1]
else
Result := nil;
end
else
begin
CurIdx := Owner.FRootNodeList.IndexOf(Self) ;
if (CurIdx + 1) < Owner.FRootNodeList.Count then
Result := Owner.FRootNodeList.Items[CurIdx + 1]
else
Result := nil;
end;
end;
function TrmWordTreeNode.GetPrevSibling: TrmWordTreeNode;
var
CurIdx: Integer;
begin
if Parent <> nil then
begin
CurIdx := Parent.FChildList.IndexOf(Self) ;
if (CurIdx - 1) >= 0 then
Result := Parent.FChildList.Items[CurIdx - 1]
else
Result := nil;
end
else
begin
CurIdx := Owner.FRootNodeList.IndexOf(Self) ;
if (CurIdx - 1) >= Owner.FRootNodeList.Count then
Result := Owner.FRootNodeList.Items[CurIdx - 1]
else
Result := nil;
end;
end;
function TrmWordTreeNode.GetNextChild(Value: TrmWordTreeNode) : TrmWordTreeNode;
begin
if Value <> nil then
Result := Value.GetNextSibling
else
Result := nil;
end;
function TrmWordTreeNode.GetPrevChild(Value: TrmWordTreeNode) : TrmWordTreeNode;
begin
if Value <> nil then
Result := Value.GetPrevSibling
else
Result := nil;
end;
function TrmWordTreeNode.GetFirstChild: TrmWordTreeNode;
begin
if FChildList.Count > 0 then
Result := FChildList.Items[0]
else
Result := nil;
end;
function TrmWordTreeNode.GetLastChild: TrmWordTreeNode;
begin
if FChildList.Count > 0 then
Result := FChildList.Items[FChildList.Count - 1]
else
Result := nil;
end;
function TrmWordTreeNode.GetNext: TrmWordTreeNode;
var
N: TrmWordTreeNode;
P: TrmWordTreeNode;
begin
if HasChildren then
N := GetFirstChild
else
begin
N := GetNextSibling;
if N = nil then
begin
P := Parent;
while P <> nil do
begin
N := P.GetNextSibling;
if N <> nil then
Break;
P := P.Parent;
end;
end;
end;
Result := N;
end;
function TrmWordTreeNode.GetPrev: TrmWordTreeNode;
var
Node: TrmWordTreeNode;
begin
Result := GetPrevSibling;
if Result <> nil then
begin
Node := Result;
repeat
Result := Node;
Node := Result.GetLastChild;
until Node = nil;
end
else
Result := Parent;
end;
function TrmWordTreeNode.GetIndex: Integer;
var
node : TrmWordTreeNode;
begin
Result := -1;
Node := parent;
if Node = nil then
begin
if fowner <> nil then
FOwner.FRootNodeList.indexof(self)
end
else
result := parent.FChildList.indexof(self);
end;
function TrmWordTreeNode.GetItem(Index: Integer) : TrmWordTreeNode;
begin
if (index >= 0) and (index < FChildList.count) then
Result := fchildlist[index]
else
begin
result := nil;
WTTreeNonViewError('List Index Out of Bounds') ;
end;
end;
procedure TrmWordTreeNode.SetItem(Index: Integer; Value: TrmWordTreeNode) ;
begin
item[Index].Assign(Value) ;
end;
function TrmWordTreeNode.IndexOf(Value: TrmWordTreeNode) : Integer;
begin
Result := fChildList.indexof(Value) ;
end;
function TrmWordTreeNode.GetCount: Integer;
begin
result := FChildList.count;
end;
function TrmWordTreeNode.GetLevel: Integer;
var
Node: TrmWordTreeNode;
begin
Result := 0;
Node := Parent;
while Node <> nil do
begin
Inc(Result) ;
Node := Node.Parent;
end;
end;
procedure TrmWordTreeNode.Delete;
begin
if HasChildren then
DeleteChildren;
if Parent <> nil then
begin
Parent.FChildList.Delete(Parent.FChildList.IndexOf(Self) ) ;
Parent.FChildList.Pack;
end
else
begin
Owner.FRootNodeList.Delete(Owner.FRootNodeList.IndexOf(Self) ) ;
Owner.FRootNodeList.Pack;
end;
Free;
end;
procedure TrmWordTreeNode.DeleteChildren;
var
Node: TrmWordTreeNode;
begin
Node := GetFirstChild;
while Node <> nil do
begin
Node.Delete;
Node := GetFirstChild;
end;
end;
procedure TrmWordTreeNode.ReadData(Stream: TStream; Info: PWTNodeInfo) ;
var
I, Size, ItemCount: Integer;
begin
Stream.ReadBuffer(Size, SizeOf(Size) ) ;
Stream.ReadBuffer(Info^, Size) ;
Letter := Info^.Letter;
ItemCount := Info^.Count;
Complete := Info^.Complete;
for I := 0 to ItemCount - 1 do
Owner.AddChild(Self, #0) .ReadData(Stream, Info) ;
end;
procedure TrmWordTreeNode.WriteData(Stream: TStream; Info: PWTNodeInfo) ;
var
I,
Size,
ItemCount: Integer;
begin
Size := SizeOf(TWTNodeInfo) ;
Info^.Letter := Letter;
ItemCount := Count;
Info^.Count := ItemCount;
Info^.Complete := Complete;
Stream.WriteBuffer(Size, SizeOf(Size) ) ;
Stream.WriteBuffer(Info^, Size) ;
for I := 0 to ItemCount - 1 do
Item[I].WriteData(Stream, Info) ;
end;
{ TrmWordTreeNodes }
constructor TrmWordTreeNodes.Create(AOwner: TCustomrmWordTree) ;
begin
inherited Create;
FOwner := AOwner;
FRootNodeList := TList.Create;
end;
destructor TrmWordTreeNodes.Destroy;
begin
Clear;
FRootNodeList.Free;
inherited Destroy;
end;
function TrmWordTreeNodes.GetCount: Integer;
var
N: TrmWordTreeNode;
begin
N := GetFirstNode;
Result := 0;
while N <> nil do
begin
Result := Result + 1;
N := N.GetNext;
end;
end;
procedure TrmWordTreeNodes.Delete(Node: TrmWordTreeNode) ;
begin
Node.Delete;
end;
procedure TrmWordTreeNodes.Clear;
var
N: TrmWordTreeNode;
begin
N := GetFirstNode;
While N <> nil do
begin
N.Delete;
N := GetFirstNode;
end;
end;
function TrmWordTreeNodes.AddChild(Node: TrmWordTreeNode; const Letter: char) : TrmWordTreeNode;
begin
Result := InternalAddObject(Node, Letter, False, taAdd) ;
end;
function TrmWordTreeNodes.Add(Node: TrmWordTreeNode; const Letter: char) : TrmWordTreeNode;
begin
if Node <> nil then Node := Node.Parent;
Result := InternalAddObject(Node, Letter, False, taAdd) ;
end;
function TrmWordTreeNodes.InternalAddObject(Node: TrmWordTreeNode; const Letter: char;
Complete: boolean; AddMode: TAddMode) : TrmWordTreeNode;
begin
Result := Owner.CreateNode;
try
case AddMode of
taAddFirst:
begin
if Node = nil then
begin
FRootNodeList.Insert(0, Result) ;
Result.Parent := nil;
end
else
begin
Node.FChildList.Insert(0, Result) ;
Result.Parent := Node;
end;
try
Result.Complete := complete;
Result.Letter := Letter;
except
raise;
end;
end;
taAdd:
begin
if Node = nil then
begin
FRootNodeList.Add(Result) ;
Result.Parent := nil;
end
else
begin
Node.FChildList.Add(Result) ;
Result.Parent := Node;
end;
try
Result.Complete := complete;
Result.Letter := Letter;
except
raise;
end;
end;
end;
except
raise;
end;
end;
function TrmWordTreeNodes.GetFirstNode: TrmWordTreeNode;
begin
if FRootNodeList.Count = 0 then
Result := nil
else
Result := FRootNodeList.Items[0];
end;
function TrmWordTreeNodes.GetNodeFromIndex(Index: Integer) : TrmWordTreeNode;
var
I: Integer;
begin
Result := GetFirstNode;
I := Index;
while (I <> 0) and (Result <> nil) do
begin
Result := Result.GetNext;
Dec(I) ;
end;
if Result = nil then
WTTreeNonViewError('Index out of range') ;
end;
procedure TrmWordTreeNodes.SetItem(Index: Integer; Value: TrmWordTreeNode) ;
begin
GetNodeFromIndex(Index) .Assign(Value) ;
end;
procedure TrmWordTreeNodes.Assign(Source: TPersistent) ;
var
TreeNodes: TrmWordTreeNodes;
MemStream: TMemoryStream;
begin
if Source is TrmWordTreeNodes then
begin
TreeNodes := TrmWordTreeNodes(Source) ;
Clear;
MemStream := TMemoryStream.Create;
try
TreeNodes.WriteData(MemStream) ;
MemStream.Position := 0;
ReadData(MemStream) ;
finally
MemStream.Free;
end;
end
else inherited Assign(Source) ;
end;
procedure TrmWordTreeNodes.DefineProperties(Filer: TFiler) ;
function WriteNodes: Boolean;
var
I: Integer;
Nodes: TrmWordTreeNodes;
begin
Nodes := TrmWordTreeNodes(Filer.Ancestor) ;
if Nodes = nil then
Result := Count > 0
else if Nodes.Count <> Count then
Result := True
else
begin
Result := False;
for I := 0 to Count - 1 do
begin
Result := not Item[I].IsEqual(Nodes[I]) ;
if Result then Break;
end
end;
end;
begin
inherited DefineProperties(Filer) ;
Filer.DefineBinaryProperty('Data', ReadData, WriteData, WriteNodes) ;
end;
procedure TrmWordTreeNodes.ReadData(Stream: TStream) ;
var
I, Count: Integer;
Info: TWTNodeInfo;
begin
Clear;
Stream.ReadBuffer(Count, SizeOf(Count) ) ;
for I := 0 to Count - 1 do
Add(nil, #0) .ReadData(Stream, @Info) ;
end;
procedure TrmWordTreeNodes.WriteData(Stream: TStream) ;
var
I: Integer;
Node: TrmWordTreeNode;
Info: TWTNodeInfo;
begin
I := 0;
Node := GetFirstNode;
while Node <> nil do
begin
Inc(I) ;
Node := Node.GetNextSibling;
end;
Stream.WriteBuffer(I, SizeOf(I) ) ;
Node := GetFirstNode;
while Node <> nil do
begin
Node.WriteData(Stream, @Info) ;
Node := Node.GetNextSibling;
end;
end;
{ TCustomrmWordTree }
constructor TCustomrmWordTree.Create(AOwner: TComponent) ;
begin
inherited Create(AOwner) ;
FTreeNodes := TrmWordTreeNodes.Create(Self) ;
end;
destructor TCustomrmWordTree.Destroy;
begin
Items.Free;
inherited Destroy;
end;
procedure TCustomrmWordTree.SetrmWordTreeNodes(Value: TrmWordTreeNodes) ;
begin
Items.Assign(Value) ;
end;
function TCustomrmWordTree.CreateNode: TrmWordTreeNode;
begin
Result := TrmWordTreeNode.Create(Items) ;
end;
function TrmWordTreeNode.IsEqual(Node: TrmWordTreeNode) : Boolean;
begin
Result := (Letter = Node.Letter) and (Complete = Node.Complete) ;
end;
procedure TrmWordTreeNode.Assign(Source: TPersistent) ;
var
Node: TrmWordTreeNode;
begin
if Source is TrmWordTreeNode then
begin
Node := TrmWordTreeNode(Source) ;
Letter := Node.Letter;
Complete := Node.Complete;
end
else
inherited Assign(Source) ;
end;
function TCustomrmWordTree.AddWord(word: string) : TrmWordTreeNode;
var
wNode, wLastNode: TrmWordTreeNode;
wIndex, wLen: integer;
begin
result := nil;
if Word = '' then
exit;
wNode := LocateWord(word) ;
if wNode = nil then
begin
wIndex := 1;
wLen := Length(word);
wLastNode := nil;
wNode := FTreeNodes.GetFirstNode;
while (wNode <> nil) and (wIndex <= wLen) do
begin
wLastNode := wNode;
if wNode.Letter = Word[wIndex] then
begin
if wIndex < wLen then
begin
wNode := wNode.GetFirstChild;
inc(wIndex) ;
end
else
wNode := nil;
end
else
begin
if wNode.GetNextSibling = nil then
begin
wLastNode := wNode.parent;
wNode := nil;
end
else
wNode := wNode.GetNextSibling;
end;
end;
if (wIndex <= wLen) then
begin
if wIndex > 1 then
wNode := wLastNode
else
wNode := nil;
while wIndex <= wLen do
begin
wNode := fTreeNodes.AddChild(wNode, word[wIndex]) ;
inc(wIndex) ;
end;
wNode.Complete := true;
end;
end
else
wNode.Complete := true;
result := wNode;
end;
function TCustomrmWordTree.IsWord(word: string) : Boolean;
var
wNode : TrmWordTreeNode;
begin
wNode := locateWord(word);
result := (wNode <> nil) and (wNode.Complete);
end;
function TCustomrmWordTree.LocateWord(Word: string) : TrmWordTreeNode;
var
wNode, wLastNode: TrmWordTreeNode;
wIndex, wLen: integer;
begin
result := nil;
if Word = '' then
exit;
wIndex := 1;
wLen := Length(word);
wLastNode := nil;
wNode := FTreeNodes.GetFirstNode;
while (wNode <> nil) and (wIndex <= wLen) do
begin
wLastNode := wNode;
if wNode.Letter = Word[wIndex] then
begin
if wIndex < wLen then
begin
wNode := wNode.GetFirstChild;
inc(wIndex) ;
end
else
wNode := nil;
end
else
wNode := wNode.GetNextSibling;
end;
if assigned(wLastNode) then
begin
if wLastNode.Complete and (wLastNode.Word = Word) then
result := wLastNode;
end
end;
procedure TCustomrmWordTree.LoadPartialMatches(Word: String; MatchList: TStrings) ;
procedure RecurseNodes(Node: TrmWordTreeNode) ;
var
wChild: TrmWordTreeNode;
begin
if Node <> nil then
begin
if Node.Complete then
MatchList.Add(Node.Word) ;
wChild := Node.GetFirstChild;
while wChild <> nil do
begin
RecurseNodes(wChild) ;
wChild := Node.GetNextChild(wChild) ;
end;
end;
end;
var
wLastNode, wNode: TrmWordTreeNode;
wLen, wIndex: integer;
begin
MatchList.clear;
wNode := FTreeNodes.GetFirstNode;
if Word = '' then
begin
While wNode <> nil do
begin
RecurseNodes(wNode) ;
wNode := wNode.GetNextSibling;
end;
end
else
begin
wIndex := 1;
wLen := Length(word);
wLastNode := nil;
while (wNode <> nil) and (wIndex <= wLen) do
begin
wLastNode := wNode;
if wNode.Letter = Word[wIndex] then
begin
if wIndex < wLen then
begin
wNode := wNode.GetFirstChild;
inc(wIndex) ;
end
else
wNode := nil;
end
else
wNode := wNode.GetNextSibling;
end;
if assigned(wLastNode) then
RecurseNodes(wLastNode) ;
end;
end;
function TrmWordTreeNode.getWord: string;
var
wNode : TrmWordTreeNode;
begin
result := '';
if not Complete then
exit;
wNode := self;
while wNode <> nil do
begin
result := wNode.letter + result;
wNode := wNode.Parent;
end;
end;
procedure TCustomrmWordTree.LoadSEMatches(Word: String; MatchList: TStrings);
var
wNode: TrmWordTreeNode;
wChar : char;
wWordSE : string;
wSELen : integer;
wloop : integer;
wSEChar : string;
wWordLen : integer;
wUpWord : string;
function TestWord(NodeWord:string):boolean;
var
wCount : integer;
wloop : integer;
begin
result := false;
if uppercase(NodeWord) = wUpWord then
exit;
if (wWordSE = soundex(NodeWord, true, wSELen)) then
begin
wcount := 0;
for wloop := 1 to wSELen do
begin
if pos(wSEChar[wloop], NodeWord) = 0 then
inc(wcount);
end;
result := (wCount < 2) and (abs(length(NodeWord) - wWordLen) < 2);
end;
end;
procedure RecurseNodes(Node: TrmWordTreeNode) ;
var
wChild: TrmWordTreeNode;
begin
if Node <> nil then
begin
if Node.Complete and TestWord(Node.word) then
MatchList.Add(Node.Word + ' ('+Soundex(Node.Word, true, wSELen)+')' ) ;
wChild := Node.GetFirstChild;
while wChild <> nil do
begin
RecurseNodes(wChild) ;
wChild := Node.GetNextChild(wChild) ;
end;
end;
end;
begin
MatchList.Clear;
word := trim(word);
if word = '' then
exit;
wSELen := 0;
wloop := length(word);
wSEChar := '';
while wloop > 1 do
begin
if not (word[wloop] in ['A','E','I','O','U']) then
begin
inc(wSELen);
if (wSEChar = '') or ((wSEChar <> '') and (word[wloop] <> wSEChar[1])) then
wSEChar := word[wloop] + wSEChar;
end;
dec(wLoop);
end;
if wSELen < 4 then
wSELen := 4;
wWordSE := Soundex(Word, true, wSELen);
wChar := word[1];
wNode := FTreeNodes.GetFirstNode;
wWordLen := length(word);
wUpWord := uppercase(word);
While wNode <> nil do
begin
if lowercase(wNode.Letter) = lowercase(wChar) then
RecurseNodes(wNode);
wNode := wNode.GetNextSibling;
end;
end;
end.
|
unit ZabbixSender;
interface
uses
System.SysUtils,
System.DateUtils,
System.JSON,
System.Generics.Collections,
IdGlobal,
IdIOHandler,
IdTCPClient;
type
TZabbixMetric = record
private
Host : string;
Key : string;
Value : string;
Clock : Int64;
public
class function Create(const AHost: string; const AKey: string; const AValue: string; ATimeStamp: Boolean = true): TZabbixMetric; overload; static;
class function Create(const AHost: string; const AKey: string; const AValue: Integer; ATimeStamp: Boolean = true): TZabbixMetric; overload; static;
class function Create(const AHost: string; const AKey: string; const AValue: Double; ATimeStamp: Boolean = true): TZabbixMetric; overload; static;
class function Create(const AHost: string; const AKey: string; const AValue: Boolean; ATimeStamp: Boolean = true): TZabbixMetric; overload; static;
end;
type
TZabbixSender = class( TList<TZabbixMetric>)
private
FServer : string;
FPort : Word;
function Write(const ZabbixData: string): TBytes;
public
constructor Create(const AServer: string; APort: word = 10051); overload;
destructor Destroy; override;
function Send(): TJSONObject;
end;
implementation
function SwapInt64(Value: Int64): Int64;
var
P: PInteger;
begin
Result := (Value shl 32) or (Value shr 32);
P := @Result;
P^ := (Swap(P^) shl 16) or (Swap(P^ shr 16));
Inc(P);
P^ := (Swap(P^) shl 16) or (Swap(P^ shr 16));
end;
class function TZabbixMetric.Create(const AHost: string; const AKey: string; const AValue: string; ATimeStamp: Boolean = true): TZabbixMetric;
begin
result.Host := AHost;
result.Key := AKey;
result.Value := AValue;
result.Clock := 0;
if ATimeStamp then
result.Clock := System.DateUtils.DateTimeToUnix(Now, false);
end;
class function TZabbixMetric.Create(const AHost: string; const AKey: string; const AValue: Integer; ATimeStamp: Boolean = true): TZabbixMetric;
begin
result.Host := AHost;
result.Key := AKey;
result.Value := IntToStr(AValue);
result.Clock := 0;
if ATimeStamp then
result.Clock := System.DateUtils.DateTimeToUnix(Now, false);
end;
class function TZabbixMetric.Create(const AHost: string; const AKey: string; const AValue: Double; ATimeStamp: Boolean = true): TZabbixMetric;
begin
result.Host := AHost;
result.Key := AKey;
result.Value := FloatToStr(AValue);
result.Clock := 0;
if ATimeStamp then
result.Clock := System.DateUtils.DateTimeToUnix(Now, false);
end;
class function TZabbixMetric.Create(const AHost: string; const AKey: string; const AValue: Boolean; ATimeStamp: Boolean = true): TZabbixMetric;
begin
result.Host := AHost;
result.Key := AKey;
result.Value := BoolToStr(AValue);
result.Clock := 0;
if ATimeStamp then
result.Clock := System.DateUtils.DateTimeToUnix(Now, false);
end;
//
constructor TZabbixSender.Create(const AServer: string; APort: word = 10051);
begin
inherited Create;
Self.FServer := AServer;
Self.FPort := APort;
end;
destructor TZabbixSender.Destroy;
begin
inherited Destroy;
end;
(*
* Header and data length
* Overview
* Header and data length are present in response and request messages between Zabbix components. It is required to determine the length of message.
*
* <HEADER> - "ZBXD\x01" (5 bytes)
* <DATALEN> - data length (8 bytes). 1 will be formatted as 01/00/00/00/00/00/00/00 (eight bytes, 64 bit number in little-endian format)
* To not exhaust memory (potentially) Zabbix protocol is limited to accept only 128MB in one connection.
**)
function TZabbixSender.write(const ZabbixData: string): TBytes;
var
lTcpClient : TIdTcpClient;
lBuffer : TIdBytes;
lHeader : string;
lSize : Int64;
begin
lTcpClient := TIdTcpClient.Create(nil);
try
lTcpClient.Host := Self.FServer;
lTcpClient.Port := Self.FPort;
lTcpClient.ReadTimeout := 1000;
lTcpClient.Connect;
if not lTcpClient.Connected then
raise Exception.Create('Client not connected to carbon server');
lTcpClient.IOHandler.WriteBufferOpen;
try
lTcpClient.IOHandler.Write('ZBXD' + #01, IndyTextEncoding(TEncoding.ASCII));
lTcpClient.IOHandler.Write(SwapInt64(Int64(Length(ZabbixData))));
lTcpClient.IOHandler.Write(ZabbixData, IndyTextEncoding(TEncoding.ASCII));
lTcpClient.IOHandler.WriteBufferFlush;
finally
lTcpClient.IOHandler.WriteBufferClose;
end;
lHeader := LTcpClient.IOHandler.WaitFor('ZBXD'+#01, true, true, IndyTextEncoding(TEncoding.ASCII), 5000);
lSize:= SwapInt64(LTcpClient.IOHandler.ReadInt64());
repeat
AppendByte(lBuffer, LTcpClient.IOHandler.ReadByte);
until lTcpClient.IOHandler.InputBufferIsEmpty;
result := TEncoding.UTF8.Convert(TEncoding.ASCII, TEncoding.UTF8, TBytes(lBuffer));
finally
FreeAndNil(lTcpClient);
end;
end;
(*
* Overview
* Zabbix sender request
* Zabbix server response
* Alternatively Zabbix sender can send request with a timestamp
* Zabbix server response
* 4 Trapper items
* Overview
* Zabbix server uses a JSON- based communication protocol for receiving data from Zabbix sender with the help of trapper item.
*
* For definition of header and data length please refer to protocol details section.
*
* Zabbix sender request
* {
* "request":"sender data",
* "data":[
* {
* "host":"<hostname>",
* "key":"trap",
* "value":"test value"
* }
* ]
* }
* Zabbix server response
* {
* "response":"success",
* "info":"processed: 1; failed: 0; total: 1; seconds spent: 0.060753"
* }
* Alternatively Zabbix sender can send request with a timestamp
* {
* "request":"sender data",
* "data":[
* {
* "host":"<hostname>",
* "key":"trap",
* "value":"test value",
* "clock":1516710794
* },
* {
* "host":"<hostname>",
* "key":"trap",
* "value":"test value",
* "clock":1516710795
* }
* ],
* "clock":1516712029,
* "ns":873386094
* }
* Zabbix server response
* {
* "response":"success",
* "info":"processed: 2; failed: 0; total: 2; seconds spent: 0.060904"
* }
**)
function TZabbixSender.Send(): TJSONObject;
var
i : Integer;
lRequestObj : TJSONObject;
lDataArr : TJSONArray;
lDataItem : TJSONObject;
lResponseObj : TJSONObject;
begin
lRequestObj := TJSONObject.Create;
try
lRequestObj.AddPair(TJSONPair.Create('request', TJSONString.Create('sender data')));
lDataArr := TJSONArray.Create;
try
for I := 0 to Self.Count - 1 do
begin
lDataItem := TJSONObject.Create;
try
lDataItem.AddPair(TJSONPair.Create('host', TJSONString.Create(Self.Items[i].Host)));
lDataItem.AddPair(TJSONPair.Create('key', TJSONString.Create(Self.Items[i].Key)));
lDataItem.AddPair(TJSONPair.Create('value', TJSONString.Create(Self.Items[i].Value)));
lDataItem.AddPair(TJSONPair.Create('clock', TJSONNumber.Create(Self.Items[i].Clock)));
finally
lDataArr.AddElement(lDataItem);
end;
end;
finally
lRequestObj.AddPair(TJSONPair.Create('data', lDataArr));
end;
lRequestObj.AddPair(TJSONPair.Create('clock', TJSONNumber.Create(System.DateUtils.DateTimeToUnix(Now, false))));
lResponseObj := TJSONObject.Create;
try
try
lResponseObj.Parse(Self.Write(lRequestObj.ToJSON), 0, true);
Self.Clear;
except
on E:Exception do
lResponseObj.AddPair(TJSONPair.Create('exception', TJSONString.Create(E.Message)));
end;
result := lResponseObj.Clone as TJSONObject;
finally
FreeAndNil(lResponseObj);
end;
finally
FreeAndNil(lRequestObj)
end;
end;
end.
|
unit luaConfig;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, lua, pLua, pLuaRecord;
implementation
uses
MainForm;
function GetCaption(RecordPointer : pointer; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
// Get the value of the caption and put it on the stack
plua_pushstring(l, frmMain.Caption);
result := 1;
end;
function SetCaption(RecordPointer : pointer; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
// Get the new caption from the stack and set frmMain.Caption to it
frmMain.Caption := plua_tostring(L, paramidxstart);
result := 0;
end;
function GetColor(RecordPointer : pointer; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
// Get the value of the Color and put it on the stack
lua_pushinteger(l, frmMain.Color);
result := 1;
end;
function SetColor(RecordPointer : pointer; l : Plua_State; paramidxstart, paramcount : integer) : Integer;
begin
// Get the new Color from the stack and set frmMain.Color to it
frmMain.Color := lua_tointeger(L, paramidxstart);
result := 0;
end;
procedure Init;
var
ri : PLuaRecordInfo;
begin
// Create a virtual "Config" global variable (record) that will allow
// the lua script to access application properties.
ri := RecordTypesList.Add('TConfig');
plua_AddRecordProperty(ri^, 'Caption', @GetCaption, @SetCaption);
plua_AddRecordProperty(ri^, 'Color', @GetColor, @SetColor);
end;
initialization
Init;
finalization
end.
|
unit htControls;
interface
uses
SysUtils, Types, Classes, Controls, Graphics,
LrControls,
htInterfaces, htMarkup, htStyle, htJavaScript;
type
ThtGraphicControl = class(TLrGraphicControl, IhtControl)
private
FCtrlStyle: ThtStyle;
FExtraAttributes: string;
FJavaScript: ThtJavaScriptEvents;
FOutline: Boolean;
FStyle: ThtStyle;
FStyleClass: string;
protected
function GetCtrlStyle: ThtStyle;
function GetStyle: ThtStyle;
function GetStyleClass: string;
function GetBoxHeight: Integer; virtual;
function GetBoxRect: TRect; virtual;
function GetBoxWidth: Integer; virtual;
//:$ <br>Build the Style property.
//:: Builds the read-only Style property by combining the SheetStyle,
//:: the Style, and the page default styles.
procedure BuildStyle; virtual;
procedure Generate(const inContainer: string;
inMarkup: ThtMarkup); virtual;
procedure GenerateStyle(const inSelector: string; inMarkup: ThtMarkup);
procedure Paint; override;
procedure SetExtraAttributes(const Value: string);
procedure SetJavaScript(const Value: ThtJavaScriptEvents);
procedure SetOutline(const Value: Boolean);
procedure SetStyle(const Value: ThtStyle);
procedure SetStyleClass(const Value: string);
procedure StyleChange(inSender: TObject);
procedure StyleControl; virtual;
procedure StylePaint; virtual;
procedure UpdateStyle;
//:$ <br>Local style properties for the control.
//:: The CtrlStyle for the control is a combination of the SheetStyle
//:: and the Style. Style properties take precedence over
//:: SheetStyle style properties.
property Style: ThtStyle read GetStyle write SetStyle;
//:$ <br>The CSS class to assign to this control.
//:: If the specified class belongs to a StyleSheet on the same page,
//:: the control is painted using the specified style.
//:: The final control for the style (the CtrlStyle) is a combination of
//:: the SheetStyle and the Style. Style property takes precendence.
property StyleClass: string read GetStyleClass write SetStyleClass;
public
constructor Create(inOwner: TComponent); override;
destructor Destroy; override;
//:$ <br>Combined style properties for the control.
//:: This is the style resulting from a blend of the default styles,
//:: the SheetStyle, and the Style.
property CtrlStyle: ThtStyle read GetCtrlStyle;
property Outline: Boolean read FOutline write SetOutline;
property BoxHeight: Integer read GetBoxHeight;
property BoxRect: TRect read GetBoxRect;
property BoxWidth: Integer read GetBoxWidth;
published
property ExtraAttributes: string read FExtraAttributes
write SetExtraAttributes;
property JavaScript: ThtJavaScriptEvents read FJavaScript write
SetJavaScript;
end;
//
ThtCustomControl = class(TLrCustomControl, IhtControl)
private
FCtrlStyle: ThtStyle;
FExtraAttributes: string;
FJavaScript: ThtJavaScriptEvents;
FOutline: Boolean;
FStyle: ThtStyle;
FStyleClass: string;
protected
function GetCtrlStyle: ThtStyle;
function GetStyle: ThtStyle;
function GetStyleClass: string;
function GetBoxHeight: Integer; virtual;
function GetBoxRect: TRect; virtual;
function GetBoxWidth: Integer; virtual;
//:$ <br>Build the Style property.
//:: Builds the read-only Style property by combining the SheetStyle,
//:: the Style, and the page default styles.
procedure BuildStyle; virtual;
procedure Generate(const inContainer: string;
inMarkup: ThtMarkup); virtual;
procedure GenerateStyle(const inSelector: string; inMarkup: ThtMarkup);
procedure Paint; override;
procedure PaintBackground(inCanvas: TCanvas; inOffset: TPoint);
procedure SetExtraAttributes(const Value: string);
procedure SetJavaScript(const Value: ThtJavaScriptEvents);
procedure SetOutline(const Value: Boolean);
procedure SetStyle(const Value: ThtStyle);
procedure SetStyleClass(const Value: string);
procedure StyleChange(inSender: TObject);
procedure StyleControl; virtual;
procedure StylePaint; virtual;
procedure UpdateStyle;
//:$ <br>Local style properties for the control.
//:: The CtrlStyle for the control is a combination of the SheetStyle
//:: and the Style. Style properties take precedence over
//:: SheetStyle style properties.
property Style: ThtStyle read GetStyle write SetStyle;
//:$ <br>The CSS class to assign to this control.
//:: If the specified class belongs to a StyleSheet on the same page,
//:: the control is painted using the specified style.
//:: The final control for the style (the CtrlStyle) is a combination of
//:: the SheetStyle and the Style. Style property takes precendence.
property StyleClass: string read GetStyleClass write SetStyleClass;
public
constructor Create(inOwner: TComponent); override;
destructor Destroy; override;
//:$ <br>Combined style properties for the control.
//:: This is the style resulting from a blend of the default styles,
//:: the SheetStyle, and the Style.
property CtrlStyle: ThtStyle read GetCtrlStyle;
property Outline: Boolean read FOutline write SetOutline;
property BoxHeight: Integer read GetBoxHeight;
property BoxRect: TRect read GetBoxRect;
property BoxWidth: Integer read GetBoxWidth;
published
property ExtraAttributes: string read FExtraAttributes
write SetExtraAttributes;
property JavaScript: ThtJavaScriptEvents read FJavaScript write
SetJavaScript;
end;
implementation
uses
LrVclUtils, htUtils, htPaint, htStylePainter;
type
TCrackedControl = class(TControl);
{ ThtGraphicControl }
constructor ThtGraphicControl.Create(inOwner: TComponent);
begin
inherited;
FJavaScript := ThtJavaScriptEvents.Create(Self);
FStyle := ThtStyle.Create(Self);
FStyle.OnChange := StyleChange;
FCtrlStyle := ThtStyle.Create(Self);
BuildStyle;
SetBounds(0, 0, 86, 64);
end;
destructor ThtGraphicControl.Destroy;
begin
FCtrlStyle.Free;
FStyle.Free;
FJavaScript.Free;
inherited;
end;
function ThtGraphicControl.GetStyle: ThtStyle;
begin
Result := FStyle;
end;
function ThtGraphicControl.GetStyleClass: string;
begin
Result := FStyleClass;
end;
function ThtGraphicControl.GetCtrlStyle: ThtStyle;
begin
Result := FCtrlStyle;
end;
procedure ThtGraphicControl.SetStyle(const Value: ThtStyle);
begin
FStyle.Assign(Value);
UpdateStyle;
end;
procedure ThtGraphicControl.SetStyleClass(const Value: string);
begin
FStyleClass := Value;
UpdateStyle;
end;
procedure ThtGraphicControl.SetOutline(const Value: Boolean);
begin
FOutline := Value;
Invalidate;
end;
procedure ThtGraphicControl.SetExtraAttributes(const Value: string);
begin
FExtraAttributes := Value;
end;
procedure ThtGraphicControl.SetJavaScript(const Value: ThtJavaScriptEvents);
begin
FJavaScript.Assign(Value);
end;
procedure ThtGraphicControl.BuildStyle;
begin
CtrlStyle.Assign(Style);
//
//CtrlStyle.Inherit(SheetStyle);
//CtrlStyle.Font.Inherit(PageStyle.Font);
//
//if not htVisibleColor(Color) {and DesignOpaque} and (Parent <> nil) then
// Color := TCrackedControl(Parent).Color;
end;
procedure ThtGraphicControl.StyleControl;
begin
CtrlStyle.Font.ToFont(Font);
Canvas.Font := Font;
Color := CtrlStyle.Color;
end;
procedure ThtGraphicControl.UpdateStyle;
begin
BuildStyle;
StyleControl;
Invalidate;
AdjustSize;
//Realign;
end;
procedure ThtGraphicControl.StyleChange(inSender: TObject);
begin
UpdateStyle;
end;
function ThtGraphicControl.GetBoxRect: TRect;
begin
Result := CtrlStyle.UnboxRect(ClientRect);
end;
function ThtGraphicControl.GetBoxHeight: Integer;
begin
Result := ClientHeight - CtrlStyle.GetBoxHeightMargin;
end;
function ThtGraphicControl.GetBoxWidth: Integer;
begin
Result := ClientWidth - CtrlStyle.GetBoxWidthMargin;
end;
procedure ThtGraphicControl.Paint;
begin
inherited;
StylePainter.Prepare(Canvas, Color, CtrlStyle, ClientRect);
StylePaint;
end;
procedure ThtGraphicControl.StylePaint;
begin
StylePainter.PaintBackground;
StylePainter.PaintBorders;
if Outline then
htPaintOutline(Canvas, ClientRect);
end;
procedure ThtGraphicControl.GenerateStyle(const inSelector: string;
inMarkup: ThtMarkup);
var
s: string;
begin
s := Style.InlineAttribute;
if (s <> '') then
inMarkup.Styles.Add(Format('%s { %s }', [ inSelector, s ]));
end;
procedure ThtGraphicControl.Generate(const inContainer: string;
inMarkup: ThtMarkup);
begin
//
end;
{ ThtCustomControl }
constructor ThtCustomControl.Create(inOwner: TComponent);
begin
inherited;
Transparent := true;
FJavaScript := ThtJavaScriptEvents.Create(Self);
FStyle := ThtStyle.Create(Self);
FStyle.OnChange := StyleChange;
FCtrlStyle := ThtStyle.Create(Self);
BuildStyle;
SetBounds(0, 0, 86, 64);
end;
destructor ThtCustomControl.Destroy;
begin
FCtrlStyle.Free;
FStyle.Free;
FJavaScript.Free;
inherited;
end;
function ThtCustomControl.GetStyle: ThtStyle;
begin
Result := FStyle;
end;
function ThtCustomControl.GetStyleClass: string;
begin
Result := FStyleClass;
end;
function ThtCustomControl.GetCtrlStyle: ThtStyle;
begin
Result := FCtrlStyle;
end;
procedure ThtCustomControl.SetStyle(const Value: ThtStyle);
begin
FStyle.Assign(Value);
UpdateStyle;
end;
procedure ThtCustomControl.SetStyleClass(const Value: string);
begin
FStyleClass := Value;
UpdateStyle;
end;
procedure ThtCustomControl.SetOutline(const Value: Boolean);
begin
FOutline := Value;
Invalidate;
end;
procedure ThtCustomControl.SetExtraAttributes(const Value: string);
begin
FExtraAttributes := Value;
end;
procedure ThtCustomControl.SetJavaScript(const Value: ThtJavaScriptEvents);
begin
FJavaScript.Assign(Value);
end;
procedure ThtCustomControl.BuildStyle;
begin
CtrlStyle.Assign(Style);
//
//CtrlStyle.Inherit(SheetStyle);
//CtrlStyle.Font.Inherit(PageStyle.Font);
//
// if not htVisibleColor(Color) and not Transparent and (Parent <> nil) then
// Color := TCrackedControl(Parent).Color;
end;
procedure ThtCustomControl.StyleControl;
begin
CtrlStyle.Font.ToFont(Font);
Canvas.Font := Font;
Color := CtrlStyle.Color;
end;
procedure ThtCustomControl.UpdateStyle;
begin
BuildStyle;
StyleControl;
Invalidate;
AdjustSize;
Realign;
end;
procedure ThtCustomControl.StyleChange(inSender: TObject);
begin
UpdateStyle;
end;
function ThtCustomControl.GetBoxRect: TRect;
begin
Result := CtrlStyle.UnboxRect(ClientRect);
end;
function ThtCustomControl.GetBoxHeight: Integer;
begin
Result := ClientHeight - CtrlStyle.GetBoxHeightMargin;
end;
function ThtCustomControl.GetBoxWidth: Integer;
begin
Result := ClientWidth - CtrlStyle.GetBoxWidthMargin;
end;
procedure ThtCustomControl.Paint;
begin
inherited;
PaintBackground(Canvas, Point(0, 0));
StylePainter.Prepare(Canvas, Color, CtrlStyle, ClientRect);
StylePaint;
end;
procedure ThtCustomControl.PaintBackground(inCanvas: TCanvas; inOffset: TPoint);
var
c: ThtCustomControl;
r: TRect;
begin
r := ClientRect;
OffsetRect(r, -inOffset.X, -inOffset.Y);
StylePainter.Prepare(inCanvas, Color, CtrlStyle, r);
//
if htVisibleColor(Color) or CtrlStyle.Background.Picture.HasGraphic then
StylePainter.PaintBackground
else if (Parent is ThtCustomControl) then
begin
c := ThtCustomControl(Parent);
inOffset := Point(inOffset.X + Left, inOffset.Y + Top);
c.PaintBackground(inCanvas, inOffset);
end else
begin
if (Parent <> nil) then
StylePainter.Color := TCrackedControl(Parent).Color
else
StylePainter.Color := clWhite;
StylePainter.PaintBackground;
end;
end;
procedure ThtCustomControl.StylePaint;
begin
StylePainter.PaintBorders;
if Outline then
htPaintOutline(Canvas, ClientRect);
end;
procedure ThtCustomControl.GenerateStyle(const inSelector: string;
inMarkup: ThtMarkup);
var
s: string;
begin
s := Style.InlineAttribute;
if (s <> '') then
inMarkup.Styles.Add(Format('%s { %s }', [ inSelector, s ]));
end;
procedure ThtCustomControl.Generate(const inContainer: string;
inMarkup: ThtMarkup);
begin
//
end;
end.
|
object Form1: TForm1
Left = 385
Top = 200
BorderIcons = [biSystemMenu]
BorderStyle = bsSingle
Caption = 'List & Label advanced sample program'
ClientHeight = 126
ClientWidth = 439
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -13
Font.Name = 'System'
Font.Style = []
Menu = MainMenu1
OldCreateOrder = True
Position = poScreenCenter
OnCreate = FormCreate
PixelsPerInch = 96
TextHeight = 16
object Label3: TLabel
Left = 8
Top = 16
Width = 415
Height = 15
Caption =
'D: Dieses Beispiel demonstriert das Designen und Drucken von Et' +
'iketten,'
Font.Charset = DEFAULT_CHARSET
Font.Color = clBlack
Font.Height = -12
Font.Name = 'Arial'
Font.Style = [fsBold]
ParentFont = False
end
object Label4: TLabel
Left = 31
Top = 32
Width = 144
Height = 15
Caption = 'Listen und User-Objekten'
Font.Charset = DEFAULT_CHARSET
Font.Color = clBlack
Font.Height = -12
Font.Name = 'Arial'
Font.Style = [fsBold]
ParentFont = False
end
object Label5: TLabel
Left = 8
Top = 56
Width = 425
Height = 15
Caption =
'US: This example demonstrates how to design and print labels, re' +
'ports and'
Font.Charset = DEFAULT_CHARSET
Font.Color = clBlack
Font.Height = -12
Font.Name = 'Arial'
Font.Style = [fsBold]
ParentFont = False
end
object Label6: TLabel
Left = 31
Top = 72
Width = 72
Height = 15
Caption = 'user-objects'
Font.Charset = DEFAULT_CHARSET
Font.Color = clBlack
Font.Height = -12
Font.Name = 'Arial'
Font.Style = [fsBold]
ParentFont = False
end
object DebugCheckBox: TCheckBox
Left = 344
Top = 104
Width = 89
Height = 17
Caption = '&Debug output'
Font.Charset = DEFAULT_CHARSET
Font.Color = clBlack
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
ParentFont = False
TabOrder = 0
OnClick = DebugCheckBoxClick
end
object MainMenu1: TMainMenu
Top = 88
object File1: TMenuItem
Caption = '&File'
object Exit1: TMenuItem
Caption = '&Exit'
OnClick = Exit1Click
end
end
object Edit1: TMenuItem
Caption = '&Edit'
object Label1: TMenuItem
Caption = '&Label...'
OnClick = Label1Click
end
object Report1: TMenuItem
Caption = '&Report...'
OnClick = Report1Click
end
end
object Print1: TMenuItem
Caption = '&Print'
object Label2: TMenuItem
Caption = '&Label...'
OnClick = PrintLabelClick
end
object Report2: TMenuItem
Caption = '&Report...'
OnClick = PrintListClick
end
end
object Options1: TMenuItem
Caption = '&Options'
object Usecallbacksfortablecoloring1: TMenuItem
Caption = '&Use callbacks for table coloring'
OnClick = Usecallbacksfortablecoloring1Click
end
end
end
object LL: TL28_
EMFResolution = 100
PhantomspaceRepresentationCode = #11
LocknextcharRepresentationCode = '`'
MaxRTFVersion = 65280
SortVariables = Yes
UnitSystem = usHiInch
CompressStorage = Yes
Buttons3D = Yes
ButtonsWithBitmaps = No
OnTableField = LLTableField
OnTableLine = LLTableLine
OnVarHelpText = LLVarHelpText
OnDefineVariables = LLDefineVariables
OnDefineFields = LLDefineFields
Left = 32
Top = 88
end
object ADOConnection1: TADOConnection
LoginPrompt = False
Mode = cmShareDenyNone
Provider = 'Microsoft.Jet.OLEDB.4.0'
Left = 64
Top = 88
end
object ADOTableArticle: TADOTable
Connection = ADOConnection1
Left = 96
Top = 88
end
end
|
unit FormNewSectionSizeUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls;
type
TFrmNewSectionSize = class(TForm)
lblCaption: TLabel;
txtZ: TEdit;
lblX: TLabel;
lblY: TLabel;
txtX: TEdit;
lblZ: TLabel;
txtY: TEdit;
lblName: TLabel;
txtName: TEdit;
lblPosition: TLabel;
chkBefore: TRadioButton;
chkAfter: TRadioButton;
Bevel1: TBevel;
BtOK: TButton;
BtCancel: TButton;
procedure FormActivate(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
before,
aborted: boolean;
X, Y, Z: integer;
Name: array[1..16] of Char;
end;
implementation
{$R *.DFM}
procedure TFrmNewSectionSize.FormActivate(Sender: TObject);
begin
aborted := true;
end;
procedure TFrmNewSectionSize.btnCancelClick(Sender: TObject);
begin
aborted := true;
Close;
end;
procedure TFrmNewSectionSize.btnOKClick(Sender: TObject);
function CheckName: boolean;
var
ch: char;
i: integer;
begin
Result := (Length(txtName.Text) in [1..16]);
if not Result then
begin
MessageDlg('Name must be between 1 and 16 characters long!',mtError,[mbOK],0);
Exit;
end;
txtName.Text := UpperCase(txtName.Text);
for i := 1 to Length(txtName.Text) do
begin
ch := txtName.Text[i];
if not (ch in ['A'..'Z','0'..'9']) then
begin
Result := False;
MessageDlg('Name can only contain letters and digits!',mtError,[mbOK],0);
txtName.SetFocus;
Exit;
end;
Name[i] := ch;
end;
//Code changed to get rid of compiler warning. This is better anyway.
for i := Length(txtName.Text)+1 to 16 do
begin
Name[i] := #0; // zero-terminated
end;
end;
var
code: integer;
procedure ValError(v: string; Ctrl: TEdit);
begin
MessageDlg(v + ' must be an integer number between 1 and 255', mtError,[mbOK],0);
Ctrl.SetFocus;
end;
begin
// Name
if not CheckName then
Exit;
// X
Val(txtX.Text,X,code);
if (code <> 0) or not (X in [1..255]) then
begin
ValError('x',txtX);
Exit;
end;
// Y
Val(txtY.Text,Y,code);
if (code <> 0) or not (Y in [1..255]) then
begin
ValError('y',txtY);
Exit;
end;
// Z
Val(txtZ.Text,Z,code);
if (code <> 0) or not (Z in [1..255]) then
begin
ValError('z',txtZ);
Exit;
end;
btOK.Enabled := false;
before := chkBefore.Checked;
aborted := false;
Close;
end;
end.
|
unit TextDocument;
interface
uses
Classes,
LrDocument;
type
TTextDocument = class(TLrDocument)
private
FText: TStringList;
protected
procedure SetText(const Value: TStringList);
public
constructor Create; override;
destructor Destroy; override;
procedure Load; override;
procedure Save; override;
property Text: TStringList read FText write SetText;
end;
implementation
{ TTextDocument }
constructor TTextDocument.Create;
begin
inherited;
FText := TStringList.Create;
end;
destructor TTextDocument.Destroy;
begin
FText.Free;
inherited;
end;
procedure TTextDocument.SetText(const Value: TStringList);
begin
FText.Assign(Value);
end;
procedure TTextDocument.Save;
begin
inherited;
FText.SaveToFile(Filename);
end;
procedure TTextDocument.Load;
begin
inherited;
FText.LoadFromFile(Filename);
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, VirtualExplorerTree, VirtualTrees, VirtualShellUtilities,
StdCtrls;
type
TForm1 = class(TForm)
ExplorerListview1: TVirtualExplorerListview;
ExplorerTreeview1: TVirtualExplorerTreeview;
procedure ExplorerListview1GetVETText(
Sender: TCustomVirtualExplorerTree; Column: TColumnIndex;
Node: PVirtualNode; Namespace: TNamespace; var Text: WideString);
procedure ExplorerListview1AddCustomShellColumn(
Sender: TCustomVirtualExplorerTree;
const FirstAvailableIndex: Integer; Header: TVTHeader);
procedure ExplorerListview1CustomColumnCompare(
Sender: TCustomVirtualExplorerTree; Column: TColumnIndex; Node1,
Node2: PVirtualNode; var Result: Integer);
private
{ Private declarations }
public
{ Public declarations }
CustomIndex: integer;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.ExplorerListview1GetVETText(
Sender: TCustomVirtualExplorerTree; Column: TColumnIndex; Node: PVirtualNode;
Namespace: TNamespace; var Text: WideString);
var
NS: TNamespace;
begin
if Sender.ValidateNamespace(Node, NS) then
begin
if Column = CustomIndex then
Text := ExtractFileExt(NS.NameParseAddress);
if Column = CustomIndex + 1 then
Text := 'CustomColumn 2'
end;
end;
procedure TForm1.ExplorerListview1AddCustomShellColumn(
Sender: TCustomVirtualExplorerTree; const FirstAvailableIndex: Integer;
Header: TVTHeader);
var
NewColumn: TVETColumn;
begin
CustomIndex := FirstAvailableIndex;
NewColumn := TVETColumn( Header.Columns.Add);
NewColumn.ColumnDetails := cdCustom;
NewColumn.Text := 'Extension';
NewColumn.Width := 60;
NewColumn := TVETColumn( Header.Columns.Add);
NewColumn.ColumnDetails := cdCustom;
NewColumn.Text := 'Second Custom';
end;
procedure TForm1.ExplorerListview1CustomColumnCompare(
Sender: TCustomVirtualExplorerTree; Column: TColumnIndex; Node1,
Node2: PVirtualNode; var Result: Integer);
var
NS1, NS2: TNamespace;
s1, s2: string;
begin
if Sender.ValidateNamespace(Node1, NS1) and Sender.ValidateNamespace(Node2, NS2) then
begin
if Column = CustomIndex then
begin
{ Win9x compatible }
s1 := ExtractFileExt(NS1.NameParseAddress);
s2 := ExtractFileExt(NS2.NameParseAddress);
Result := lstrcmp(PChar(s1), PChar(s2));
{ If equal use the name ordering as a secondary sort }
if Result = 0 then
begin
s1 := NS1.NameNormal;
s2 := NS2.NameNormal;
Result := lstrcmp(PChar(s1), PChar(s2));
end;
end
end;
end;
end.
|
unit SmGlobalWizardIntf;
interface
uses AppStruClasses, Forms, Classes, Ibase, Messages, Windows,
Dialogs, SysUtils, SmGlobalWizardForm, Controls,
pFibDataBase, pFibDataSet, pFibQuery;
type
TBUGlobalWizard=class(TFMASAppModule,IFMASModule)
private
WorkMainForm:TForm;
public
Count:Integer;
procedure Run;
procedure OnLanguageChange(var Msg:TMessage); message FMAS_MESS_CHANGE_LANG;
procedure OnGridStylesChange(var Msg:TMessage); message FMAS_MESS_CHANGE_GSTYLE;
{$WARNINGS OFF}
destructor Destroy; override;
{$WARNINGS ON}
end;
implementation
{ TUPFilter }
{$WARNINGS OFF}
destructor TBUGlobalWizard.Destroy;
begin
if Assigned(self.WorkMainForm) then self.WorkMainForm.Free;
self.WorkMainForm:=nil;
inherited Destroy;
end;
{$WARNINGS ON}
procedure TBUGlobalWizard.OnGridStylesChange(var Msg: TMessage);
begin
//Для будущей реализации
end;
procedure TBUGlobalWizard.OnLanguageChange(var Msg: TMessage);
begin
//Для будущей реализации
end;
procedure TBUGlobalWizard.Run;
begin
if not Assigned(WorkMainForm)
then begin
WorkMainForm:=TfrmSmGlobalWizard.Create(TComponent(self.InParams.Items['AOwner']^),
TISC_DB_HANDLE(PInteger(self.InParams.Items['DbHandle'])^),
PInteger(self.InParams.Items['Id_User'])^,
PInteger(self.InParams.Items['FirstOnce'])^);
end;
end;
initialization
//Регистрация класса в глобальном реестре
RegisterAppModule(TBUGlobalWizard,'SmGlobalWizard');
end.
|
unit brKunjunganU;
interface
uses Dialogs, Classes, brCommonsU, System.SysUtils, System.StrUtils, synautil;
type
brKunjungan = class(bridgeCommon)
private
// procedure masukkanGetPendaftaranUrut;
is_post : Boolean;
//no_kartu : string;
// no_kunjungan : string;
procedure masukkanPostKunjungan(idxstr : string);
procedure masukkanPutKunjungan(idxstr : string);
function masukkanGetRujukan(idxstr, noKunjungan : string) : Boolean;
function cek_isPost(idxstr : string) : Boolean;
function StrToPostgesDate (strDate : string) : string;
public
aScript : TStringList;
function ambilJsonKunjungan(idxstr : string) : string;
function postKunjungan(idxstr : string) : Boolean;
function postKunjunganX(idxstr, dataStr : string) : Boolean;
function getRujukan(idxstr : string) : Boolean;
constructor Create;
destructor destroy;
// property Uri : string;
end;
implementation
uses SynCommons;
{ brKunjungan }
function brKunjungan.ambilJsonKunjungan(idxstr : string): String;
var sql0, sql1 : string;
tglStr, tglPulangStr, noKunjungan, noKartu : string;
i : Integer;
V1 : Variant;
begin
Result := '';
parameter_bridging('KUNJUNGAN', 'POST');
V1 := _Json(FormatJson);
sql0 := 'select * from jkn.kunjungan_view where idxstr = %s and kunj_sakit = true;';
sql1 := Format(sql0,[QuotedStr(idxstr)]);
fdQuery.Close;
fdQuery.SQL.Clear;
fdQuery.SQL.Add(sql1);
fdQuery.Open;
if not fdQuery.IsEmpty then
begin
// ShowMessage('not empty');
DateTimeToString(tglStr, 'DD-MM-YYYY', fdQuery.FieldByName('tanggal').AsDateTime);
DateTimeToString(tglPulangStr, 'DD-MM-YYYY', fdQuery.FieldByName('pulang_tanggal').AsDateTime);
noKartu := fdQuery.FieldByName('no_kartu').AsString;
if fdQuery.FieldByName('bpjs_kunjungan').IsNull then is_post := true else
begin
is_post := False;
noKunjungan := fdQuery.FieldByName('bpjs_kunjungan').AsString;
V1.noKunjungan := noKunjungan;
end;
V1.noKartu := noKartu;
V1.tglDaftar := tglStr;
V1.kdPoli := fdQuery.FieldByName('kd_poli').AsString;
V1.keluhan := fdQuery.FieldByName('keluhan').AsString;
V1.kdSadar := fdQuery.FieldByName('kd_sadar').AsString;
V1.sistole := fdQuery.FieldByName('sistole').AsInteger;
V1.diastole := fdQuery.FieldByName('diastole').AsInteger;
V1.beratBadan := fdQuery.FieldByName('berat_badan').AsInteger;
V1.tinggiBadan := fdQuery.FieldByName('tinggi_badan').AsInteger;
V1.respRate := fdQuery.FieldByName('respiratory').AsInteger;
V1.heartRate := fdQuery.FieldByName('heart').AsInteger;
V1.terapi := fdQuery.FieldByName('tindakan').AsString;
{
if not fdQuery.FieldByName('kd_provider').IsNull then
V1.kdProviderRujukLanjut := fdQuery.FieldByName('kd_provider').AsString;
}
V1.kdStatusPulang := fdQuery.FieldByName('kd_pulang').AsString;
V1.tglPulang := tglPulangStr;
V1.kdDokter := fdQuery.FieldByName('dokter').AsString;
V1.kdDiag1 := fdQuery.FieldByName('kd_diag1').AsString;
if not fdQuery.FieldByName('kd_diag2').IsNull then
V1.kdDiag2 := fdQuery.FieldByName('kd_diag2').AsString;
if not fdQuery.FieldByName('kd_diag3').IsNull then
V1.kdDiag3 := fdQuery.FieldByName('kd_diag3').AsString;
// rujukIntrnal masih kosong
if (fdQuery.FieldByName('pulang_sebab').AsString = 'Rujuk Internal') then
V1.kdPoliRujukInternal := fdQuery.FieldByName('poli_rujukan').AsString;
V1.kdTacc := fdQuery.FieldByName('kd_tacc').AsInteger;
if not fdQuery.FieldByName('alasan_tacc').IsNull then
V1.alasanTacc := fdQuery.FieldByName('alasan_tacc').AsString;
fdQuery.Close;
Result := VariantSaveJSON(V1);
end else fdQuery.Close;
//FileFromString(Result, 'kunjunganxxx.json');
//ShowMessage(Result);
end;
function brKunjungan.cek_isPost(idxstr: string): Boolean;
var
sql0, sql1 : string;
begin
parameter_bridging('KUNJUNGAN', 'POST');
sql0 := 'select * from jkn.kunjungan_view where idxstr = %s;';
sql1 := Format(sql0,[QuotedStr(idxstr)]);
fdQuery.Close;
fdQuery.SQL.Clear;
fdQuery.SQL.Add(sql1);
fdQuery.Open;
Result := True;
if not fdQuery.IsEmpty then
begin
//ShowMessage('not empty');
if fdQuery.FieldByName('bpjs_kunjungan').IsNull then Result := true else
begin
Result := False;
end;
end;
fdQuery.Close;
end;
constructor brKunjungan.Create;
begin
inherited Create;
aScript := TStringList.Create;
//no_kunjungan := '';
end;
destructor brKunjungan.destroy;
begin
aScript.Free;
inherited;
end;
function brKunjungan.getRujukan(idxstr: string): Boolean;
var sql0, sql1 : string;
no_kunjungan : string;
begin
Result := False;
parameter_bridging('RUJUKAN', 'GET');
sql0 := 'select bpjs_kunjungan from jkn.kunjungan_view where idxstr = %s;';
sql1 := Format(sql0, [QuotedStr(idxstr)]);
fdQuery.Close;
fdQuery.SQL.Clear;
fdQuery.SQL.Add(sql1);
fdQuery.Open();
if not fdQuery.IsEmpty then
begin
no_kunjungan := fdQuery.FieldByName('bpjs_kunjungan').AsString;
fdQuery.Close;
//ShowMessage(uri);
Uri := StringReplace( Uri, '{noKunjungan}', no_kunjungan, []);
//ShowMessage(uri);
Result:= httpGet(uri);
if Result then
begin
Result := masukkanGetRujukan(idxstr, no_kunjungan);
end;
end else fdQuery.Close;
FDConn.Close;
end;
function brKunjungan.masukkanGetRujukan(idxstr, noKunjungan: string) : Boolean;
var
tSL : TStringList;
dataResp, ppk : Variant;
sqlDel0, sqlDel1, sql0, sql1 : string;
noRujukan, tglKunjungan, nokaPst, nmPst, tglLahir, sex, pisa, ketPisa, kdPPK, nmPPK, kdKC, nmKC, nmDati, kdDati, kdKR, nmKR,
kdPoli, nmPoli, kdDiag1, nmDiag1, kdDiag2, nmDiag2, kdDiag3, nmDiag3, kdDokter, nmDokter, nmTacc, alasanTacc,
catatan, infoDenda, catatanRujuk, tglEstRujuk, tglAkhirRujuk, jadwal : string;
begin
sql0 := 'INSERT INTO jkn.rujukan ("idxstr", "noRujukan", "tglKunjungan", "nokaPst", "nmPst", "tglLahir", "sex", "pisa", "ketPisa", "kdPPK", "nmPPK", "kdKC", "nmKC", "nmDati", "kdDati", "kdKR", "nmKR", ' +
'"kdPoli", "nmPoli", "kdDiag1", "nmDiag1", "kdDiag2", "nmDiag2", "kdDiag3", "nmDiag3", "kdDokter", "nmDokter", "nmTacc", "alasanTacc", "catatan", "infoDenda", "catatanRujuk", "tglEstRujuk", "tglAkhirRujuk", "jadwal") ' +
'VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);';
Result := logRest('GET', 'RUJUKAN', tsResponse.Text);
if Result then
begin
tsL := TStringList.Create;
try
dataResp := _jsonFast(tsResponse.Text);
//ShowMessage(tsResponse.Text);
// NoKunjungan := dataResp.response.message;
sqlDel0 := 'delete from jkn.rujukan where "idxstr" = %s;';
sqlDel1 := Format(sqlDel0, [QuotedStr(idxstr)]);
tSl.Add(sqlDel1);
noRujukan := dataResp.response.noRujukan;
tglKunjungan := StrToPostgesDate(dataResp.response.tglKunjungan);
nokaPst := dataResp.response.nokaPst;
nmPst := dataResp.response.nmPst;
tglLahir := StrToPostgesDate(dataResp.response.tglLahir);
pisa := dataResp.response.pisa;
ketPisa := dataResp.response.ketPisa;
sex := dataResp.response.sex;
if VarIsEmptyOrNull(dataResp.response.catatan) then catatan := '-' else
catatan := dataResp.response.catatan;
if VarIsEmptyOrNull(dataResp.response.infoDenda) then infoDenda := '-' else
infoDenda := dataResp.response.infoDenda;
if VarIsEmptyOrNull(dataResp.response.catatanRujuk) then catatanRujuk := '-' else
catatanRujuk := dataResp.response.catatanRujuk;
tglEstRujuk := StrToPostgesDate(dataResp.response.tglEstRujuk);
tglAkhirRujuk := StrToPostgesDate(dataResp.response.tglAkhirRujuk);
if VarIsEmptyOrNull(dataResp.response.jadwal) then jadwal := '-' else
jadwal := dataResp.response.jadwal;
kdPoli := dataResp.response.poli.kdPoli;
nmPoli := dataResp.response.poli.nmPoli;
if VarIsEmptyOrNull(dataResp.response.diag1) then
begin
kdDiag1 := 'null';
nmDiag1 := 'null';
end else
begin
kdDiag1 := QuotedStr(dataResp.response.diag1.kdDiag);
nmDiag1 := QuotedStr(dataResp.response.diag1.nmDiag);
end;
if VarIsEmptyOrNull(dataResp.response.diag2) then
begin
kdDiag2 := 'null';
nmDiag2 := 'null';
end else
begin
kdDiag2 := QuotedStr(dataResp.response.diag2.kdDiag);
nmDiag2 := QuotedStr(dataResp.response.diag2.nmDiag);
end;
if VarIsEmptyOrNull(dataResp.response.diag3) then
begin
kdDiag3 := 'null';
nmDiag3 := 'null';
end else
begin
kdDiag3 := QuotedStr(dataResp.response.diag3.kdDiag);
nmDiag3 := QuotedStr(dataResp.response.diag3.nmDiag);
end;
if VarIsEmptyOrNull(dataResp.response.dokter) then
begin
kdDokter := 'null';
nmDokter := 'null';
end else
begin
kdDokter := QuotedStr(dataResp.response.dokter.kdDokter);
nmDokter := QuotedStr(dataResp.response.dokter.nmDokter);
end;
if VarIsEmptyOrNull(dataResp.response.tacc) then
begin
nmTacc := 'null';
alasanTacc := 'null';
end else
begin
if VarIsEmptyOrNull(dataResp.response.tacc.nmTacc) then nmTacc := 'null' else
nmTacc := QuotedStr(dataResp.response.tacc.nmTacc);
if VarIsEmptyOrNull(dataResp.response.tacc.alasanTacc) then alasanTacc := 'null'
else alasanTacc := QuotedStr(dataResp.response.tacc.alasanTacc);
end;
ppk := dataResp.response.ppk;
_Unique(ppk);
kdPPK := ppk.kdPPK;
nmPPK := ppk.nmPPK;
kdKC := ppk.kc.kdKC;
nmKC := ppk.kc.nmKC;
nmDati := ppk.kc.dati.nmDati;
kdDati := ppk.kc.dati.kdDati;
kdKR := ppk.kc.kdKR.kdKR;
nmKR := ppk.kc.kdKR.nmKR;
sql1 := Format(sql0, [
QuotedStr(idxstr),
QuotedStr(noRujukan),
QuotedStr(tglKunjungan),
QuotedStr(nokaPst),
QuotedStr(nmPst),
QuotedStr(tglLahir),
QuotedStr(sex),
QuotedStr(pisa),
QuotedStr(ketPisa),
QuotedStr(kdPPK),
QuotedStr(nmPPK),
QuotedStr(kdKC),
QuotedStr(nmKC),
QuotedStr(nmDati),
QuotedStr(kdDati),
QuotedStr(kdKR),
QuotedStr(nmKR),
QuotedStr(kdPoli),
QuotedStr(nmPoli),
kdDiag1,
nmDiag1,
kdDiag2,
nmDiag2,
kdDiag3,
nmDiag3,
kdDokter,
nmDokter,
nmTacc,
alasanTacc,
QuotedStr(catatan),
QuotedStr(infoDenda),
QuotedStr(catatanRujuk),
QuotedStr(tglEstRujuk),
QuotedStr(tglAkhirRujuk),
QuotedStr(jadwal)
]);
tSL.Add(sql1);
aScript.Assign(tSL);
jalankanScript(tSl);
finally
FreeAndNil(tSl);
end;
end;
end;
procedure brKunjungan.masukkanPostKunjungan(idxstr : string);
var dataResp, dataList : Variant;
i : Integer;
tSl : TStringList;
sqlDel0, sqlDel1, sql0, sql1 : string;
kdDiag, nmDiag : string;
tglStr : string;
nonSpesialis : Boolean;
noUrut : integer;
noKunjungan : string;
begin
// ShowMessage(tsResponse.Text);
if logRest('POST', 'KUNJUNGAN', tsResponse.Text) then
begin
tsL := TStringList.Create;
try
dataResp := _jsonFast(tsResponse.Text);
// ShowMessage(tsResponse.Text);
NoKunjungan := dataResp.response.message;
sqlDel0 := 'update simpus.pasien_kunjungan set bpjs_kunjungan = %s where idxstr = %s;';
sqlDel1 := Format(sqlDel0, [QuotedStr(NoKunjungan), quotedStr(idxstr)]);
tSl.Add(sqlDel1);
jalankanScript(tSl);
finally
FreeAndNil(tSl);
end;
end;
end;
procedure brKunjungan.masukkanPutKunjungan(idxstr : string);
begin
logRest('PUT', 'KUNJUNGAN', tsResponse.Text);
end;
function brKunjungan.postKunjungan(idxstr : string): Boolean;
var
mStream : TMemoryStream;
js : string;
begin
js := ambilJsonKunjungan(idxstr);
if Length(js) > 10 then
begin
mStream := TMemoryStream.Create;
try
Result := False;
WriteStrToStream(mStream, js);
if is_post then
begin
//Uri := ReplaceStr(Uri, '{puskesmas}', puskesmas);
Result:= httpPost(Uri, mStream);
jejakIdxstr := idxstr;
FormatJson := js;
if Result then masukkanPostKunjungan(idxstr);
end else
begin
//Uri := ReplaceStr(Uri, '{nokartu}', no_kartu);
Result := httpPut(Uri, mStream);
FormatJson := js;
if Result then masukkanPutKunjungan(idxstr);
end;
finally
mStream.Free;
end;
end;
FDConn.Close;
end;
function brKunjungan.postKunjunganX(idxstr, dataStr: string): Boolean;
var
mStream : TMemoryStream;
begin
//js := ambilJsonKunjungan(idxstr);
is_post := cek_isPost(idxstr);
if Length(dataStr) > 10 then
begin
mStream := TMemoryStream.Create;
try
Result := False;
WriteStrToStream(mStream, dataStr);
if is_post then
begin
//Uri := ReplaceStr(Uri, '{puskesmas}', puskesmas);
Result:= httpPost(Uri, mStream);
jejakIdxstr := idxstr;
FormatJson := dataStr;
if Result then masukkanPostKunjungan(idxstr);
end else
begin
//Uri := ReplaceStr(Uri, '{nokartu}', no_kartu);
Result := httpPut(Uri, mStream);
jejakIdxstr := idxstr;
FormatJson := dataStr;
if Result then masukkanPutKunjungan(idxstr);
end;
finally
mStream.Free;
end;
end;
FDConn.Close;
end;
function brKunjungan.StrToPostgesDate(strDate: string): string;
var
formatAsli : Char;
myDate : TDateTime;
myDateStr : string;
begin
formatAsli := FormatSettings.DateSeparator;
FormatSettings.DateSeparator := '-';
myDate := StrToDate(strDate);
DateTimeToString(myDateStr, 'YYYY-MM-DD', myDate);
FormatSettings.DateSeparator := formatAsli;
Result := myDateStr;
end;
end.
|
unit ThPanel;
interface
uses
Windows, Classes, Controls, StdCtrls, ExtCtrls, Graphics, Messages, SysUtils,
Types,
ThWebControl, ThAttributeList, ThTag, ThTextPaint;
type
TThCustomPanel = class(TThWebControl)
private
FShowOutline: Boolean;
FShowGrid: Boolean;
FVAlign: TThVAlign;
protected
function GetGeneratorHtml: string;
function GetOutlineColor: TColor; virtual;
procedure SetShowGrid(const Value: Boolean);
procedure SetShowOutline(const Value: Boolean);
procedure SetVAlign(const Value: TThVAlign);
protected
procedure AlignControls(AControl: TControl; var Rect: TRect); override;
procedure Paint; override;
procedure Tag(inTag: TThTag); override;
procedure UnoverlapControls;
protected
property OutlineColor: TColor read GetOutlineColor;
property ShowGrid: Boolean read FShowGrid write SetShowGrid default false;
property ShowOutline: Boolean read FShowOutline write SetShowOutline
default true;
property VAlign: TThVAlign read FVAlign write SetVAlign default vaDefault;
public
constructor Create(AOwner: TComponent); override;
end;
//
TThPanel = class(TThCustomPanel)
public
constructor Create(AOwner: TComponent); override;
procedure CellTag(inTag: TThTag); override;
published
property Align;
property DesignOpaque;
property ShowGrid;
property ShowOutline;
property Style;
property StyleClass;
property VAlign;
property Visible;
end;
implementation
uses
ThComponentIterator, {TbhContentView,} ThAlignUtils, ThStylePainter,
ThGenerator, ThLabel;
{ TThCustomPanel }
constructor TThCustomPanel.Create(AOwner: TComponent);
begin
inherited;
FShowGrid := false;
FShowOutline := true;
end;
procedure TThCustomPanel.Paint;
var
l, t, i, j: Integer;
begin
inherited;
if ShowGrid then
begin
l := 0; //Left mod 4;
t := 0; //Top mod 4;
// Aligning with the form dots is tricky because the panel
// doesn't redraw when moved (the pixels are blitted)
for j := 0 to Height div 4 do
for i := 0 to Width div 4 do
Canvas.Pixels[i * 4 - l, j * 4 - t] := clGray;
end;
if ShowOutline then
ThPaintOutline(Canvas, AdjustedClientRect, OutlineColor);
end;
procedure TThCustomPanel.Tag(inTag: TThTag);
begin
with inTag do
begin
Element := '';
{
Content := #13'<!--BEGIN m' + Name + ' -->' //#13
+ GetGeneratorHtml
+ #13'<!--END m' + Name + ' -->'#13;
}
Content := GetGeneratorHtml;
end;
end;
function TThCustomPanel.GetGeneratorHtml: string;
begin
with TThGenerator.Create do
try
Container := Self;
Result := Html;
finally
Free;
end;
end;
procedure TThCustomPanel.AlignControls(AControl: TControl; var Rect: TRect);
begin
inherited;
Changed;
//UnoverlapControls;
end;
procedure TThCustomPanel.UnoverlapControls;
var
i, j: TThCtrlIterator;
begin
i := TThCtrlIterator.Create(Self);
try
j := TThCtrlIterator.Create(Self);
try
ThAlignUtils.UnoverlapControls(i, j);
finally
j.Free;
end;
finally
i.Free;
end;
end;
procedure TThCustomPanel.SetShowGrid(const Value: Boolean);
begin
FShowGrid := Value;
Invalidate;
end;
procedure TThCustomPanel.SetShowOutline(const Value: Boolean);
begin
FShowOutline := Value;
Invalidate;
end;
function TThCustomPanel.GetOutlineColor: TColor;
begin
Result := clBlack;
end;
procedure TThCustomPanel.SetVAlign(const Value: TThVAlign);
begin
FVAlign := Value;
end;
{ TThPanel }
constructor TThPanel.Create(AOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle + [ csAcceptsControls ];
end;
procedure TThPanel.CellTag(inTag: TThTag);
begin
inherited;
case VAlign of
vaMiddle, vaBottom: inTag.Attributes['valign'] := ssVAlign[VAlign];
end;
StylizeTag(inTag);
ListJsAttributes(inTag.Attributes);
// case VAlign of
// vaMiddle: inTag.Attributes['valign'] = 'middle';
// vaBottom: inTag.Attributes['valign'] = 'Bottom';
// end;
end;
end.
|
unit uCadImagem;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, DB, ADODB, funcoes, funcsql, StdCtrls, Grids, DBGrids,
RpCon, RpConDS, RpBase, RpSystem, RpDefine, RpRave, adLabelEdit,
TFlatButtonUnit, TFlatCheckBoxUnit, jpeg, FileCtrl;
type
TfmCadastro = class(TForm)
edCodigo: TadLabelEdit;
edDescricao: TadLabelEdit;
pnBotoes: TPanel;
lbIs_ref: TLabel;
btConsultar: TFlatButton;
btIncluir: TFlatButton;
btAlterar: TFlatButton;
btExcluir: TFlatButton;
CheckBox1: TFlatCheckBox;
Panel1: TPanel;
lbDiretorios: TDirectoryListBox;
cbUnidades: TDriveComboBox;
FlatButton1: TFlatButton;
FlatButton2: TFlatButton;
FlatButton3: TFlatButton;
lbArquivos: TFileListBox;
lbTotalArquivos: TLabel;
Panel2: TPanel;
Image1: TImage;
procedure btConsultarClick(Sender: TObject);
procedure Image1DblClick(Sender: TObject);
procedure edCodigoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure LimparCampos();
procedure btIncluirClick(Sender:Tobject);
procedure incluirImgagem(mostraMsg:Boolean);
procedure cadastraProduto(is_ref:String);
procedure btAlterarClick(Sender: TObject);
procedure CheckBox1Click(Sender: TObject);
procedure btExcluirClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
function ConverterJPegParaBmp(Arquivo: string):String;
procedure FlatButton2Click(Sender: TObject);
procedure lbDiretoriosChange(Sender: TObject);
procedure carregaimagem(narquivo:String);
procedure ajustaDimensaoBitmap(arq:String);
procedure FlatButton1Click(Sender: TObject);
procedure FlatButton3Click(Sender: TObject);
procedure contaArquivos();
procedure chamaAlteracaoProduto(mostraMsg:boolean);
private
{ Private declarations }
public
{ Public declarations }
end;
var
fmCadastro: TfmCadastro;
implementation
uses uMain, cf;
{$R *.dfm}
function TfmCadastro.ConverterJPegParaBmp(Arquivo: string):String;
var
JPeg: TJPegImage;
Bmp: TBitmap;
nArquivo:String;
begin
JPeg := TJPegImage.Create;
try
JPeg.LoadFromFile(Arquivo);
Bmp := TBitmap.Create;
try
Bmp.Assign(JPeg);
// nArquivo := SysUtils.ChangeFileExt(Arquivo, '_.bmp');
nArquivo := funcoes.getDirLogs() + 'arq.bmp';
Bmp.SaveToFile(nArquivo);
finally
Bmp.Free;
end;
finally
JPeg.Free;
result :=nArquivo;
end;
end;
procedure TfmCadastro.btConsultarClick(Sender: TObject);
var
cmd,is_ref:String;
dsImagem, dsProduto:TdataSet;
begin
image1.Picture.Assign(nil);
image1.Refresh();
screen.Cursor := crHourglass;
dsProduto := cf.getDadosProd( fmMain.getUoLogada(), edCodigo.Text, '', '101', true );
if (dsProduto.IsEmpty = false ) then
begin
edCodigo.Text := dsProduto.fieldByname('codigo').asString;
lbIs_ref.Caption := dsProduto.fieldByname('is_ref').asString;
edDescricao.Text := dsProduto.fieldByname('DESCRICAO').asString;
dsImagem := cf.getImagemProduto(lbIs_ref.Caption);
Image1.Picture.Assign( dsImagem.FieldByName('imagem'));
end
else
begin
edDescricao.Text := '';
lbIs_ref.Caption := '';
end;
if (edCodigo.Visible = true) then
edCodigo.SetFocus();
screen.Cursor := crDefault;
dsProduto.Free();
end;
procedure TfmCadastro.carregaImagem(nArquivo:String);
var
delTemp:boolean;
begin
if (nArquivo <> '') then
begin
funcoes.gravaLog('carregando arquivo:' + nArquivo);
if ( pos('.JPG', nArquivo) > 0) then
begin
fmMain.msgStatus('Imagem carregada é jpg, convertendo...');
nArquivo := ConverterJPegParaBmp(nArquivo);
delTemp := true;
end
else
if ( tamArquivo(nArquivo) > 25000000 ) then
ajustaDimensaoBitmap(nArquivo);
begin
Image1.Picture.LoadFromFile( nArquivo );
if (delTemp = true )then
deleteFile(nArquivo);
end;
end;
fmMain.msgStatus('');
end;
procedure TfmCadastro.Image1DblClick(Sender:TObject);
var
nArquivo:String;
begin
nArquivo := funcoes.DialogAbrArq('Arquivos bmp,jpg |*.bmp;*.jpg','c:\');
if (nArquivo <> '') then
carregaimagem(nArquivo);
end;
procedure TfmCadastro.edCodigoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if (key = VK_RETURN) then
btConsultarClick(nil);
end;
procedure TfmCadastro.LimparCampos;
begin
image1.Picture := nil;
image1.Refresh();
edCodigo.Text := '';
edDescricao.Text := '';
lbIs_ref.Caption := '';
if (edCodigo.Visible = true) then
edCodigo.SetFocus();
end;
procedure TfmCadastro.btAlterarClick(Sender: TObject);
begin
chamaAlteracaoProduto(true);
end;
procedure TfmCadastro.CheckBox1Click(Sender: TObject);
begin
Image1.Stretch := CheckBox1.Checked ;
end;
procedure TfmCadastro.btExcluirClick(Sender: TObject);
begin
if (lbIs_ref.Caption <> '') then
if (msgTela('', 'Deseja excluir a imagem ?', MB_ICONQUESTION + MB_YESNO) = mrYes ) then
begin
funcSQl.execSQL('Delete from zcf_crefe_imagens where is_ref = ' + lbIs_ref.Caption, fmMain.Conexao );
LimparCampos();
msgTela('', 'Imagem Excluída.',MB_OK + MB_ICONEXCLAMATION);
LimparCampos();
end;
end;
procedure TfmCadastro.FormClose(Sender: TObject; var Action: TCloseAction);
begin
fmCadastro := nil;
action := caFree;
end;
procedure TfmCadastro.FlatButton2Click(Sender: TObject);
var
nArquivos,i:integer;
nArquivo:String;
begin
// pega o codigo do produto no nome do arquivo e tenta incluir.
nArquivos := 0;
for i:=0 to lbArquivos.Items.Count -1 do
if (pos('.JPG', UPPERCASE(lbArquivos.Items.Strings[i]) ) > 0) or (pos('.BMP', UPPERCASE(lbArquivos.Items.Strings[i]) ) > 0) then
begin
fmMain.msgStatus('Processando ' + intToStr(i+1) +' de '+ intToStr( lbArquivos.Items.Count) );
nArquivos := nArquivos+1;
nArquivo := ExtractFileName(lbArquivos.Items.Strings[i]);
delete(nArquivo, length(nArquivo)-3,04);
edCodigo.Text := funcoes.SohNumeros(nArquivo);
btConsultarClick(nil);
if (Image1.Picture.Width <= 1 ) and (edDescricao.Text <> '') then
begin
fmMain.msgStatus(edCodigo.Text + ' ' + edDescricao.Text + #13+ 'Imagem não cadastrada, incluir');
carregaimagem( lbArquivos.Items.Strings[i] );
incluirImgagem(false);
end
else
begin
fmMain.msgStatus(edCodigo.Text + ' ' + edDescricao.Text + #13+ 'Imagem já cadastrada, alterar' );
carregaimagem( lbArquivos.Items.Strings[i] );
chamaAlteracaoProduto(false);
end;
end;
if nArquivos > 0 then
MsgTela('','Processo concluido',0 + MB_ICONWARNING )
else
MsgTela('','Não encontrei nenhum arquivo para processar.',0 + MB_ICONWARNING );
FlatButton1Click(nil);
end;
procedure TfmCadastro.lbDiretoriosChange(Sender: TObject);
begin
lbArquivos.Directory := lbDiretorios.Directory;
contaArquivos();
end;
procedure TfmCadastro.ajustaDimensaoBitmap(arq:String);
var
bitmap, resizedbitmap : tbitmap; newheight, newwidth : integer; stretchrect : trect;
begin
bitmap := tbitmap.create;
resizedbitmap := tbitmap.create;
bitmap.loadfromfile( arq );
if bitmap.Width <> bitmap.height then begin
if bitmap.height > bitmap.width then begin
newheight := 768;
newwidth := (newheight * bitmap.width) div bitmap.height;
end
else begin
newwidth := 1024;
newheight := (newwidth * bitmap.height) div bitmap.width;
end;
end
else begin
newheight := 1024;
newwidth := 768;
end;
if (bitmap.Width > 1024) or (bitmap.Height > 768) then
begin
stretchrect.left := 0;
stretchrect.Top := 0;
stretchrect.right := newwidth;
stretchrect.bottom := newheight;
resizedbitmap.Width := newwidth;
resizedbitmap.height := newheight;
resizedbitmap.Canvas.StretchDraw(stretchrect, bitmap);
resizedbitmap.SaveToFile(arq);
end;
end;
procedure TfmCadastro.FlatButton1Click(Sender: TObject);
begin
Panel1.Visible := false;
pnBotoes.Visible :=true;
edCodigo.Visible := true;
edDescricao.Visible := true;
end;
procedure TfmCadastro.FlatButton3Click(Sender: TObject);
begin
LimparCampos();
pnBotoes.Visible := false;
edCodigo.Visible := false;
edDescricao.Visible := false;
Panel1.Visible := true;
cbUnidades.Refresh;
end;
procedure TfmCadastro.contaArquivos;
var
i,j:integer;
begin
j:=0;
for i:=0 to lbArquivos.Items.Count -1 do
if (pos('.JPG', UPPERCASE(lbArquivos.Items.Strings[i]) ) > 0) or
(pos('.BMP', UPPERCASE(lbArquivos.Items.Strings[i]) ) > 0) then
inc(j);
lbTotalArquivos.Caption := 'Arq bmp/jpg: ' + intToStr(j);
end;
procedure TfmCadastro.cadastraProduto(is_ref: String);
var
tb:TADOTable;
cmd:String;
begin
funcSQl.getTable(fmMain.Conexao, tb, 'is_ref int, imagem image');
tb.Open();
tb.Append();
tb.fieldByName('is_ref').AsString := is_ref;
tb.fieldByName('imagem').Assign( Image1.Picture );
tb.Post();
tb.Close();
cmd := 'insert zcf_crefe_imagens select is_ref, imagem from ' + tb.TableName;
fmMain.execSQL(cmd);
tb.Free();
end;
procedure TfmCadastro.incluirImgagem(mostraMsg: Boolean);
var
is_ref:String;
erro: String;
begin
screen.Cursor := crHourglass;
erro := '';
is_ref := lbIs_ref.Caption;
if (edCodigo.Text = '') then
erro := erro+' - Informe um código.'+#13;
if (is_ref = '') then
erro := erro+' - Esse produto não é cadastrado.'+#13
else
if (edCodigo.Text <> '') then
if ( funcSql.openSQL('Select is_ref from zcf_crefe_imagens where is_ref = ' + is_ref, 'is_ref', fmMain.Conexao ) <> '' )then
erro := erro+' - Esse código já tem uma imagem cadastrada.'+#13;
if (Image1.Picture = nil) then
erro := erro+' - Selecione uma imagem.'+#13;
if erro <> '' then
msgTela('', erro, MB_ICONERROR + mb_ok)
else
begin
cadastraProduto(is_ref);
if (mostraMsg = true) then
msgTela('', 'Inclusão efetuada.',MB_OK + MB_ICONEXCLAMATION);
LimparCampos();
end;
screen.Cursor := crdefault;
end;
procedure TfmCadastro.btIncluirClick(Sender:TObject);
begin
incluirImgagem(true);
end;
procedure TfmCadastro.chamaAlteracaoProduto(mostraMsg: boolean);
var
altera:boolean;
begin
altera := true;
if (mostraMsg = true) then
if( MsgTela('','Deseja alterar a imagem desse produto? ', MB_YESNO + MB_ICONQUESTION) = mrNo ) then
altera := false;
if (altera = true) then
if (lbIs_ref.Caption <> '') then
begin
funcSQl.execSQL('Delete from zcf_crefe_imagens where is_ref = ' + lbIs_ref.Caption, fmMain.Conexao );
incluirImgagem(false);
LimparCampos();
if (mostraMsg = true) then
msgTela('', 'Alteração efetuada.',MB_OK + MB_ICONEXCLAMATION);
end;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [VIEW_SPED_C190]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit ViewSpedC190VO;
{$mode objfpc}{$H+}
interface
uses
VO, Classes, SysUtils, FGL;
type
TViewSpedC190VO = class(TVO)
private
FID: Integer;
FCST_ICMS: String;
FCFOP: Integer;
FALIQUOTA_ICMS: Extended;
FDATA_HORA_EMISSAO: TDateTime;
FSOMA_VALOR_OPERACAO: Extended;
FSOMA_BASE_CALCULO_ICMS: Extended;
FSOMA_VALOR_ICMS: Extended;
FSOMA_BASE_CALCULO_ICMS_ST: Extended;
FSOMA_VALOR_ICMS_ST: Extended;
FSOMA_VL_RED_BC: Extended;
FSOMA_VALOR_IPI: Extended;
published
property Id: Integer read FID write FID;
property CstIcms: String read FCST_ICMS write FCST_ICMS;
property Cfop: Integer read FCFOP write FCFOP;
property AliquotaIcms: Extended read FALIQUOTA_ICMS write FALIQUOTA_ICMS;
property DataHoraEmissao: TDateTime read FDATA_HORA_EMISSAO write FDATA_HORA_EMISSAO;
property SomaValorOperacao: Extended read FSOMA_VALOR_OPERACAO write FSOMA_VALOR_OPERACAO;
property SomaBaseCalculoIcms: Extended read FSOMA_BASE_CALCULO_ICMS write FSOMA_BASE_CALCULO_ICMS;
property SomaValorIcms: Extended read FSOMA_VALOR_ICMS write FSOMA_VALOR_ICMS;
property SomaBaseCalculoIcmsSt: Extended read FSOMA_BASE_CALCULO_ICMS_ST write FSOMA_BASE_CALCULO_ICMS_ST;
property SomaValorIcmsSt: Extended read FSOMA_VALOR_ICMS_ST write FSOMA_VALOR_ICMS_ST;
property SomaVlRedBc: Extended read FSOMA_VL_RED_BC write FSOMA_VL_RED_BC;
property SomaValorIpi: Extended read FSOMA_VALOR_IPI write FSOMA_VALOR_IPI;
end;
TListaViewSpedC190VO = specialize TFPGObjectList<TViewSpedC190VO>;
implementation
initialization
Classes.RegisterClass(TViewSpedC190VO);
finalization
Classes.UnRegisterClass(TViewSpedC190VO);
end.
|
unit Compute.Future.Detail;
interface
uses
Compute.OpenCL;
type
IFuture<T> = interface
function GetDone: boolean;
function GetValue: T;
function GetPeekValue: T;
function GetEvent: CLEvent;
procedure Wait;
property Done: boolean read GetDone;
property Value: T read GetValue;
property PeekValue: T read GetPeekValue; // non-blocking, a hack but hey
property Event: CLEvent read GetEvent;
end;
TReadyFutureImpl<T> = class(TInterfacedObject, IFuture<T>)
strict private
FValue: T;
FEvent: CLEvent;
public
// Value must be reference type
constructor Create(const Value: T);
function GetDone: boolean;
function GetValue: T;
function GetPeekValue: T;
function GetEvent: CLEvent;
procedure Wait;
end;
TOpenCLFutureImpl<T> = class(TInterfacedObject, IFuture<T>)
strict private
FValue: T;
FEvent: CLEvent;
public
// Value must be reference type
constructor Create(const Event: CLEvent; const Value: T);
function GetDone: boolean;
function GetValue: T;
function GetPeekValue: T;
function GetEvent: CLEvent;
procedure Wait;
property Event: CLEvent read FEvent;
end;
implementation
{ TReadyFutureImpl<T> }
constructor TReadyFutureImpl<T>.Create(const Value: T);
begin
inherited Create;
FValue := Value;
end;
function TReadyFutureImpl<T>.GetDone: boolean;
begin
result := True;
end;
function TReadyFutureImpl<T>.GetEvent: CLEvent;
begin
result := nil;
end;
function TReadyFutureImpl<T>.GetPeekValue: T;
begin
result := FValue;
end;
function TReadyFutureImpl<T>.GetValue: T;
begin
result := FValue;
end;
procedure TReadyFutureImpl<T>.Wait;
begin
end;
{ TOpenCLFutureImpl<T> }
constructor TOpenCLFutureImpl<T>.Create(const Event: CLEvent; const Value: T);
begin
inherited Create;
FEvent := Event;
FValue := Value;
end;
function TOpenCLFutureImpl<T>.GetDone: boolean;
begin
result := (Event.CommandExecutionStatus = ExecutionStatusComplete);
end;
function TOpenCLFutureImpl<T>.GetEvent: CLEvent;
begin
result := Event;
end;
function TOpenCLFutureImpl<T>.GetPeekValue: T;
begin
result := FValue;
end;
function TOpenCLFutureImpl<T>.GetValue: T;
var
done: boolean;
begin
done := not GetDone();
if (not done) then
Wait();
result := FValue;
end;
procedure TOpenCLFutureImpl<T>.Wait;
begin
Event.Wait;
end;
end.
|
unit Level;
interface
uses Classes;
Const
SECFLAG1_EXTCEILING = $00000001; // Exterior Ceiling
SECFLAG1_EXTFLOOR = $00000002; // Exterior Floor
SECFLAG1_EXTTOPADJOIN = $00000004; // Exterior top adjoin
SECFLAG1_EXTBTMADJOIN = $00000008; // Exterior bottom adjoin
SECFLAG1_NOWALLS = $00000010; // Sector is an automatic door
SECFLAG1_NOSLIP = $00000020; // no gravity slide on slope (meaningless on flat floor)
SECFLAG1_VELFLOORONLY = $00000040; // sector vel applies to floor only
SECFLAG1_WATER = $00000080;
SECFLAG1_DOOR = $00000100; // Sector is an automatic door
SECFLAG1_REVERSE = $00000200; // reverse swing direction of auto door
SECFLAG1_USE_SUN_ANGLE = $00000400; // use the sun angle specified for the level
SECFLAG1_SWIRLFLOORTEX = $00000800;
SECFLAG1_SECRET_AREA = $00001000;
SECFLAG1_REVERB_LOW = $00002000; // unused
SECFLAG1_REVERB_MED = $00004000; // unused
SECFLAG1_REVERB_HIGH = $00008000; // unused
SECFLAG1_UNUSED_8 = $00010000;
SECFLAG1_UNUSED_9 = $00020000;
SECFLAG1_SECDAMAGE_SML = $00040000; // small sector damage
SECFLAG1_SECDAMAGE_LGE = $00080000; // large sector damage
SECFLAG1_SECDAMAGE_DIE = $00100000; // deadly sector damage
SECFLAG1_FLRDAMAGE_SML = $00200000; // small floor damage
SECFLAG1_FLRDAMAGE_LGE = $00400000; // large floor damage
SECFLAG1_FLRDAMAGE_DIE = $00800000; // deadly floor damage
SECFLAG1_SEC_TERMINATE = $01000000;
SECFLAG1_SECRET_TAG = $02000000; // secret sector tag USED ONLY FOR COUNTING SECRETS FOUND...
SECFLAG1_NOSHADEFLOOR = $04000000; // don't shade the floor
SECFLAG1_RAIL_PULL = $08000000; // rail track pull chain
SECFLAG1_RAIL_LINE = $10000000; // rail line...
SECFLAG1_NOSHOW = $20000000; // don't show sector to player on map...
SECFLAG1_SLOPEDFLOOR = $40000000; // Sector has sloped floor
SECFLAG1_SLOPEDCEILING = $80000000; // Sector has sloped ceiling
WALLFLAG1_MIDTEX = $00000001; // Wall has adjoining middle texture
WALLFLAG1_LITSIGN = $00000002; // Wall has illuminated sign
WALLFLAG1_HFLIP = $00000004; // Wall texture is flipped horizontally
WALLFLAG1_ANCHOR = $00000008; // Wall textures are anchored
WALLFLAG1_ANCHORSIGN = $00000010; // sign texture is anchored
WALLFLAG1_TINT = $00000020; // transparency with tinting - srs
WALLFLAG1_MOVE = $00000040; // move the left vertice when rotating or moving the wall
WALLFLAG1_SCROLLTOP = $00000080;
WALLFLAG1_SCROLLMID = $00000100;
WALLFLAG1_SCROLLBOTTOM = $00000200;
WALLFLAG1_SCROLLSIGN = $00000400;
WALLFLAG1_NOPASS = $00000800; // can't walk through
WALLFLAG1_FORCEPASS = $00001000; // ignore height check
WALLFLAG1_FENCE = $00002000; // badguy no pass
WALLFLAG1_SHATTER = $00004000; // Shatter glass - srs
WALLFLAG1_PROJECTILE_OK = $00008000; // Projectile's pass through... -srs
WALLFLAG1_NORAIL = $00010000; // not a rail in a rail sector...
WALLFLAG1_NOSHOW = $00020000; // don't show this wall to the player....
WALLFLAG1_SECRET_AREA = $00040000; // a secret area, don't show on cheats...
// flags1 of the object declaration
LEV_OBJ_FLAG1_TYPE_PT_SOUND = $00000001;
LEV_OBJ_FLAG1_TYPE_3DO = $00000008;
LEV_OBJ_FLAG1_AUTO_VELOCITY = $00000010;
// flags2 of the object declaration
LEV_OBJ_FLAG2_OBJECT_MULTI_AI = $00200000;
LEV_OBJ_FLAG2_OBJECT_DMATCH = $00400000;
LEV_OBJ_FLAG2_OBJECT_CAPTURE_FLAG = $00800000;
LEV_OBJ_FLAG2_OBJECT_TAG = $01000000;
LEV_OBJ_FLAG2_OBJECT_MAN_BALL = $02000000;
LEV_OBJ_FLAG2_OBJECT_SECRET_DOC = $04000000;
LEV_OBJ_FLAG2_OBJECT_TEAM_PLAY = $08000000;
LEV_OBJ_FLAG2_OBJECT_NOVICE = $10000000;
LEV_OBJ_FLAG2_OBJECT_NORMAL = $20000000;
LEV_OBJ_FLAG2_OBJECT_ADVANCED = $40000000;
LEV_OBJ_FLAG2_OBJECT_EXPERT = $80000000;
{reserved object names...
start positions (need at least 1 per game)
player - player start pos (for single player)
startpos - additional start positions for mp
flagstar - flag start point (for CTF)
ballstar - chicken start point for KFC}
LIFLAG_DUMP_WEAPONS = $00000001;
LIFLAG_DUMP_AMMO = $00000002;
LIFLAG_DUMP_HEALTH = $00000004;
LIFLAG_DUMP_OIL = $00000008;
LIFLAG_DUMP_ALL = $00000010;
LIFLAG_SHOW_SCORE = $00000020;
LIFLAG_DROP_NONNATIVE = $00000040;
Type
TLevel=class;
TSector=class;
TVector=record
dx,dy,dz:double;
end;
TVertexClip=record
X,Z:Double;
end;
TVertex=class
X,Z:Double;
mark:Integer;
Function IsSameXZ(V:TVertex):Boolean;
end;
TClipString=String[31];
TOBClip=record
Name:TClipString;
X,Y,Z:Double;
PCH,YAW,ROL:Double;
Flags1,Flags2:Longint;
end;
TOB=class
HexID:Longint;
Name:String;
Sector:Integer;
X,Y,Z:Double;
PCH,YAW,ROL:Double;
flags1,Flags2:Longint;
Procedure Assign(o:TOB);
procedure CopyToClip(var Clip:TOBCLip);
procedure PasteFromClip(const Clip:TOBClip);
end;
TMyList=class(TList)
Procedure Delete(I:integer);
end;
TObjects=class(TMyList)
private
function GetObject(n:Integer):TOB;
procedure SetObject(n:Integer;LevelObject:TOB);
public
Property Items[n:Integer]:TOB read GetObject write SetObject; default;
end;
TTexture=record
Name:String;
offsx,offsy:double;
end;
TTXClip=record
Name:TClipString;
offsx,offsy:double;
end;
TWallClip=record
V1,V2:Integer;
Mid,Top,Bot:TTXClip;
OverLay:TTXClip;
Flags:Longint;
Light:Byte;
end;
TWall=class
HexID:Longint;
V1,V2:Integer;
Mid,Top,Bot:TTexture;
OverLay:TTexture;
Adjoin,DAdjoin:Integer;
Mirror,DMirror:Integer;
Flags:Longint;
Light:Byte;
Trigger,elevator:Boolean;
Mark, Mark1:Integer;
procedure CopyToClip(var Clip:TWallClip);
procedure PasteFromClip(const Clip:TWallClip);
Function IsFlagSet(flag:Integer):Boolean;
Procedure Assign(w:TWall);
Private
IMID,ITOP,IBOT,IOverlay:Integer; {Undices of textures. Used when saving}
end;
TWalls=class(TMyList)
private
function GetWall(n:Integer):TWall;
procedure SetWall(n:Integer;wall:TWall);
public
Property Items[n:Integer]:TWall read GetWall write SetWall; default;
end;
TVertices=class(TMyList)
private
function GetVertex(n:Integer):TVertex;
procedure SetVertex(n:Integer;vertex:TVertex);
public
Property Items[n:Integer]:TVertex read GetVertex write SetVertex; default;
end;
TSlope=record
sector,wall:Integer;
angle:Double;
end;
TSectorClip=record
nVertices,NWalls:Integer;
Name:TClipString;
Ambient:byte;
Palette:TClipString;
ColorMap:TClipString;
Friction:double;
Gravity: Double;
Elasticity: Double;
Velocity: TVector;
Floor_Sound: TClipString;
Floor_Y: Double;
Floor_TX:TTXClip;
Floor_extra:double;
Ceiling_Y: Double;
Ceiling_TX: TTXClip;
Ceiling_Extra:Double;
F_Overlay_TX:TTXClip;
F_Overlay_Extra:Double;
C_Overlay_TX:TTXClip;
C_Overlay_Extra:Double;
Flags: Longint;
FloorSlope,
CeilingSlope:TSlope;
Layer: integer;
end;
TSector=class
private
fvertices:TVertices;
fwalls:TWalls;
Function IsSecret:Boolean;
Public
HexID:Longint;
Elevator:Boolean;
Trigger:Boolean;
Name:String;
Ambient:Byte;
Palette:String;
ColorMap:String;
Friction:double;
Gravity: Double;
Elasticity: Double;
Velocity: TVector;
VAdjoin: Integer;
Floor_Sound: String;
Floor_Y: Double;
Floor_Texture:TTexture;
Floor_extra:double;
Ceiling_Y: Double;
Ceiling_Texture: TTexture;
Ceiling_Extra:Double;
F_Overlay_texture:TTexture;
F_Overlay_Extra:Double;
C_Overlay_texture:TTexture;
C_Overlay_Extra:Double;
floor_offsets: Integer;
Flags: Longint;
FloorSlope,
CeilingSlope:TSlope;
Layer: integer;
procedure CopyToClip(var Clip:TSectorClip);
procedure PasteFromClip(const Clip:TSectorClip);
Constructor Create;
Destructor Destroy;override;
Property Vertices: Tvertices read fvertices;
Property Walls: TWalls read fwalls;
Property Secret:Boolean read IsSecret;
Function IsFlagSet(flag:Integer):Boolean;
Procedure Assign(s:TSector);
Function GetWallByID(ID:Longint):Integer;
Function IsWLValid(wl:Integer):Boolean;
Function IsVXValid(VX:Integer):Boolean;
Private
IFloor_TX,ICeiling_TX,ICOVR_TX,IFOVR_TX:Integer;
IPalette,ICmap:Integer;
end;
TSectors=class(TMyList)
private
function GetSector(n:Integer):TSector;
procedure SetSector(n:Integer;sector:TSector);
public
Property Items[n:Integer]:TSector read GetSector write SetSector; default;
end;
TShade=class
r,g,b:byte;
b4:byte;
c1:char;
end;
TShades=class(TMyList)
private
function GetShade(n:Integer):TShade;
procedure SetShade(n:Integer;shade:TShade);
public
Property Items[n:Integer]:TShade read GetShade write SetShade; default;
end;
TLevel=class
Private
fsectors:TSectors;
fshades:TShades;
fobjects:TObjects;
LastID:LongInt;
Public
Name:String;
Music:String;
Version:Double;
Parallax_x,Parallax_y:Double;
{extra variables}
MinX,MinY,MinZ,MaxX,MaxY,MaxZ:Double;
MinLayer,MaxLayer:Integer;
Constructor Create;
Destructor Destroy;Override;
Property Sectors:TSectors read fsectors;
Property Shades:TShades read fshades;
Property Objects:TObjects read fobjects;
Procedure Clear;
Procedure Load(FName:String);
Procedure Save(FName:String);
Procedure ImportLEV(FName:String);
Procedure ImportWAD(FName:String);
Procedure ImportMAP(FName:String);
Function GetNewSectorID:Longint;
Function GetNewWallID:Longint;
Function GetNewObjectID:Longint;
Function GetSectorbyID(ID:Longint):Integer;
Function GetObjectbyID(ID:Longint):Integer;
Procedure FindLimits;
Procedure FindLayers;
Procedure FindMaxID;
{Helper routines}
Function NewVertex:TVertex; {For creating new items with default
properties. Also sets the HexID field right}
Function NewWall:TWall;
Function NewSector:TSector;
Function NewObject:TOB;
Procedure SetDefaultShades;
Function IsSCValid(sc:Integer):Boolean;
end;
implementation
uses Files, FileOperations, Misc_Utils, SysUtils, ProgressDialog, GlobalVars;
Procedure TXToClip(Var Clip:TTXClip;TX:TTexture);
begin
Clip.Name:=TX.Name;
Clip.OffsX:=TX.OffsX;
Clip.OffsY:=TX.OffsY;
end;
Procedure ClipToTX(TX:TTexture;Const Clip:TTXClip);
begin
TX.Name:=Clip.Name;
TX.OffsX:=Clip.OffsX;
TX.OffsY:=Clip.OffsY;
end;
Procedure TMyList.Delete(I:integer);
begin
Inherited Delete(i);
Pack;
end;
function TWalls.GetWall(n:Integer):TWall;
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('Wall index is out of bounds: %d',[n])
else Result:=TWall(List[n]);
end;
procedure TWalls.SetWall(n:Integer;wall:TWall);
begin
Tlist(self).Items[n]:=wall;
end;
function TObjects.GetObject(n:Integer):TOB;
begin
if (n<0) or (n>=count) then raise EListError.Create('Object index is out of bounds')
else Result:=TOB(List[n]);
end;
procedure TObjects.SetObject(n:Integer;LevelObject:TOB);
begin
List[n]:=LevelObject;
end;
function TVertices.GetVertex(n:Integer):TVertex;
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('Vertex index is out of bounds: %d',[n])
else Result:=TVertex(List[n]);
end;
procedure TVertices.SetVertex(n:Integer;vertex:TVertex);
begin
Tlist(self).Items[n]:=Vertex;
end;
function TSectors.GetSector(n:Integer):TSector;
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('Sector index is out of bounds: %d',[n])
else Result:=TSector(List[n]);
end;
procedure TSectors.SetSector(n:Integer;sector:TSector);
begin
List[n]:=Sector;
end;
function TShades.GetShade(n:Integer):TShade;
begin
if n>=count then raise EListError.Create('Shade index is out of bounds')
else Result:=TShade(List[n]);
end;
procedure TShades.SetShade(n:Integer;Shade:TShade);
begin
List[n]:=Shade;
end;
{TSector Methods}
Constructor TSector.Create;
begin
fwalls:=TWalls.Create;
fvertices:=TVertices.Create;
end;
Function TSector.IsVXValid(VX:Integer):Boolean;
begin
Result:=(VX>=0) and (VX<Vertices.count);
end;
Function TSector.GetWallByID(ID:Longint):Integer;
var i:Integer;
begin
Result:=-1;
for i:=0 to Walls.count-1 do
if Walls[i].HexID=ID then begin Result:=i; exit; end;
end;
Function TSector.IsWLValid(wl:Integer):Boolean;
begin
if (wl<0) or (wl>=Walls.Count) then result:=false
else Result:=true;
end;
Destructor TSector.Destroy;
var i:integer;
begin
for i:=0 to vertices.count-1 do vertices[i].free;
for i:=0 to walls.count-1 do walls[i].free;
vertices.free;
walls.free;
end;
procedure TSector.CopyToClip(var Clip:TSectorClip);
begin
Clip.nVertices:=Vertices.Count;
Clip.NWalls:=Walls.Count;
Clip.Name:=Name;
Clip.Ambient:=Ambient;
Clip.Palette:=Palette;
Clip.ColorMap:=ColorMap;
Clip.Friction:=Friction;
Clip.Gravity:=Gravity;
Clip.Elasticity:=Elasticity;
Clip.Velocity:=Velocity;
Clip.Floor_Sound:=Floor_Sound;
Clip.Floor_Y:=Floor_y;
TXToCLip(Clip.Floor_TX,Floor_Texture);
Clip.Floor_extra:=Floor_Extra;
Clip.Ceiling_Y:=Ceiling_Y;
TXToClip(Clip.Ceiling_TX,Ceiling_Texture);
Clip.Ceiling_Extra:=Ceiling_Extra;
TXToClip(Clip.F_Overlay_TX,F_Overlay_Texture);
Clip.F_Overlay_Extra:=F_Overlay_Extra;
TXToClip(Clip.C_Overlay_TX,C_Overlay_Texture);
Clip.C_Overlay_Extra:=C_Overlay_Extra;
Clip.Flags:=Flags;
Clip.FloorSlope:=FloorSlope;
Clip.CeilingSlope:=CeilingSlope;
Clip.Layer:=Layer;
end;
procedure TSector.PasteFromClip(const Clip:TSectorClip);
begin
Name:=Clip.Name;
Ambient:=Clip.Ambient;
Palette:=Clip.Palette;
ColorMap:=Clip.ColorMap;
Friction:=Clip.Friction;
Gravity:=Clip.Gravity;
Elasticity:=Clip.Elasticity;
Velocity:=Clip.Velocity;
Floor_Sound:=Clip.Floor_Sound;
Floor_Y:=Clip.Floor_y;
CLipToTX(Floor_Texture,Clip.Floor_TX);
Floor_extra:=Clip.Floor_Extra;
Ceiling_Y:=Clip.Ceiling_Y;
ClipToTX(Ceiling_Texture,Clip.Ceiling_TX);
Ceiling_Extra:=Clip.Ceiling_Extra;
ClipToTX(F_Overlay_Texture,Clip.F_Overlay_TX);
F_Overlay_Extra:=Clip.F_Overlay_Extra;
ClipToTX(C_Overlay_Texture,Clip.C_Overlay_TX);
C_Overlay_Extra:=Clip.C_Overlay_Extra;
Flags:=Clip.Flags;
FloorSlope:=Clip.FloorSlope;
CeilingSlope:=Clip.CeilingSlope;
Layer:=Clip.Layer;
end;
Procedure TSector.Assign;
begin
Ambient:=s.Ambient;
Palette:=s.Palette;
ColorMap:=s.ColorMap;
Friction:=s.Friction;
Gravity:=s.Gravity;
Elasticity:=s.Elasticity;
Velocity:=s.Velocity;
Floor_Sound:=s.Floor_Sound;
Floor_Y:=s.Floor_Y;
Floor_Texture:=s.Floor_Texture;
Floor_extra:=s.Floor_extra;
Ceiling_Y:=s.Ceiling_Y;
Ceiling_Texture:=s.Ceiling_Texture;
Ceiling_Extra:=s.Ceiling_Extra;
F_Overlay_texture:=s.F_Overlay_texture;
F_Overlay_Extra:=s.F_Overlay_Extra;
C_Overlay_texture:=s.C_Overlay_texture;
C_Overlay_Extra:=s.C_Overlay_Extra;
Flags:=s.Flags;
FloorSlope:=s.FloorSlope;
CeilingSlope:=s.CeilingSlope;
Layer:=s.Layer;
end;
Function TSector.IsSecret:Boolean;
begin
Result:=(flags and SECFLAG1_SECRET_TAG)<>0;
end;
{TLevel methods}
Constructor TLevel.Create;
var i:Integer;
begin
fsectors:=TSectors.Create;
fshades:=TShades.Create;
fobjects:=TObjects.Create;
Version:=1535.022197;
Music:='NULL';
Parallax_x:=1024;
Parallax_y:=1024;
{extra variables}
end;
Function TLevel.IsSCValid(sc:Integer):Boolean;
begin
if (sc<0) or (sc>=sectors.Count) then result:=false
else Result:=true;
end;
Procedure TLevel.SetDefaultShades;
var i:Integer;
begin
Shades.Clear;
For i:=0 to 12 do Shades.Add(TShades.Create);
With Shades[0] do begin r:=200; g:=200; b:=200; b4:=10; c1:='L' end;
With Shades[1] do begin r:=200; g:=200; b:=200; b4:=25; c1:='L' end;
With Shades[2] do begin r:=200; g:=200; b:=200; b4:=50; c1:='L' end;
With Shades[3] do begin r:=200; g:=200; b:=200; b4:=75; c1:='L' end;
With Shades[4] do begin r:=0; g:=0; b:=0; b4:=85; c1:='G' end;
With Shades[5] do begin r:=0; g:=0; b:=0; b4:=70; c1:='G' end;
With Shades[6] do begin r:=0; g:=0; b:=0; b4:=55; c1:='G' end;
With Shades[7] do begin r:=0; g:=0; b:=255; b4:=10; c1:='T' end;
With Shades[8] do begin r:=0; g:=0; b:=255; b4:=30; c1:='T' end;
With Shades[9] do begin r:=0; g:=0; b:=255; b4:=50; c1:='T' end;
With Shades[10] do begin r:=255; g:=0; b:=0; b4:=10; c1:='T' end;
With Shades[11] do begin r:=255; g:=0; b:=0; b4:=30; c1:='T' end;
With Shades[12] do begin r:=255; g:=0; b:=0; b4:=50; c1:='T' end;
end;
Destructor TLevel.Destroy;
var i:integer;
begin
Clear;
Sectors.free;
fshades.free;
end;
Procedure TLevel.Clear;
var i:Integer;
begin
For i:=0 to sectors.count-1 do sectors[i].free;
for i:=0 to fshades.count-1 do fshades[i].free;
For i:=0 to fobjects.count-1 do fobjects[i].free;
Sectors.Clear;
Shades.Clear;
Objects.Clear;
LastID:=$10;
end;
Procedure TLevel.FindMaxID;
var i,s,w:Integer;
CurID:Longint;
Function DWBigger(a,b:Longint):boolean;assembler;
asm
Mov eax,a
cmp eax,b
mov al,FALSE
jbe @below
mov al,TRUE
@Below:
end;
begin
LastID:=$10;
For s:=0 to sectors.count-1 do
With Sectors[s] do
begin
if DWBigger(HexID,LastID) then LastID:=HexID;
For w:=0 to Walls.count-1 do
begin
CurID:=Walls[w].HexID;
if DWBigger(CurID,LastID) then LastID:=CurID;
end;
end;
For i:=0 to objects.count-1 do
begin
CurID:=Objects[i].HexID;
if DWBigger(CurID,LastID) then LastID:=CurID;
end;
end;
Function TLevel.GetNewSectorID:Longint;
begin
Inc(LastID);
Result:=LastID;
end;
Function TLevel.GetNewWallID:Longint;
begin
Inc(LastID);
Result:=LastID;
end;
Function TLevel.GetNewObjectID:Longint;
begin
Inc(LastID);
Result:=LastID;
end;
Function TLevel.GetSectorbyID(ID:Longint):Integer;
var i:integer;
begin
result:=-1;
for i:=0 to sectors.count-1 do
if sectors[i].HexID=ID then begin result:=i; exit; end;
end;
Function TLevel.GetObjectbyID(ID:Longint):Integer;
var i:integer;
begin
result:=-1;
for i:=0 to objects.count-1 do
if objects[i].HexID=ID then begin result:=i; exit; end;
end;
Procedure TWall.Assign(w:TWall);
begin
Mid:=w.Mid;
Top:=w.Top;
Bot:=w.Bot;
OverLay:=w.Overlay;
Flags:=w.Flags;
Light:=w.Light;
end;
procedure TWall.CopyToClip(var Clip:TWallClip);
begin
Clip.V1:=V1;
Clip.V2:=V2;
TXToClip(Clip.Mid,Mid);
TXToClip(Clip.Bot,Bot);
TXToClip(Clip.Top,Top);
TXToClip(Clip.Overlay,Overlay);
Clip.Flags:=Flags;
Clip.Light:=Light;
end;
procedure TWall.PasteFromClip(const Clip:TWallClip);
begin
V1:=Clip.V1;
V2:=Clip.V2;
ClipToTX(Mid,Clip.Mid);
ClipToTX(Bot,Clip.Bot);
ClipToTX(Top,Clip.Top);
ClipToTX(Overlay,Clip.Overlay);
Flags:=Clip.Flags;
Light:=Clip.Light;
end;
Function TWall.IsFlagSet(flag:Integer):Boolean;
begin
Result:=flags and flag<>0;
end;
Function TSector.IsFlagSet(flag:Integer):Boolean;
begin
Result:=flags and flag<>0;
end;
Procedure TLevel.FindLimits;
var i,j : Integer;
TheSector : TSector;
TheVertex : TVertex;
begin
minX := 99999;
minY := 99999;
minZ := 99999;
maxX := -99999;
maxY := -99999;
maxZ := -99999;
for i := 0 to Sectors.Count - 1 do
begin
TheSector := Sectors[i];
if TheSector.Ceiling_Y > maxY then maxY := TheSector.Ceiling_Y;
if TheSector.Floor_Y < minY then minY := TheSector.Floor_Y;
for j := 0 to TheSector.Vertices.Count - 1 do
begin
TheVertex := TheSector.Vertices[j];
if TheVertex.X > maxX then maxX := TheVertex.X;
if TheVertex.Z > maxZ then maxZ := TheVertex.Z;
if TheVertex.X < minX then minX := TheVertex.X;
if TheVertex.Z < minZ then minZ := TheVertex.Z;
end;
end;
For i:=0 to Objects.Count-1 do
With Objects[i] do
begin
if X>MaxX then MaxX:=X;
if X<MinX then MinX:=X;
if Y>MaxY then MaxY:=Y;
if Y<MinY then MinY:=Y;
if Z>MaxZ then MaxZ:=Z;
if Z<MinZ then MinZ:=Z;
end;
FindLayers;
FindMaxID;
end;
Procedure TLevel.FindLayers;
var i:Integer;
begin
MinLayer:=100;
MaxLayer:=-100;
for i:=0 to sectors.count-1 do
With Sectors[i] do
begin
If Layer<MinLayer then MinLayer:=Layer;
if Layer>MaxLayer then MaxLayer:=Layer;
end;
end;
procedure TOB.CopyToClip(var Clip:TOBCLip);
begin
Clip.Name:=Name;
Clip.X:=X;
Clip.Y:=Y;
Clip.Z:=Z;
Clip.PCH:=PCH;
Clip.YAW:=YAW;
Clip.ROL:=ROL;
Clip.Flags1:=Flags1;
Clip.Flags2:=Flags2;
end;
procedure TOB.PasteFromClip(const Clip:TOBClip);
begin
Name:=Clip.Name;
X:=Clip.X;
Y:=Clip.Y;
Z:=Clip.Z;
PCH:=Clip.PCH;
YAW:=Clip.YAW;
ROL:=Clip.ROL;
Flags1:=Clip.Flags1;
Flags2:=Clip.Flags2;
end;
Procedure TOB.Assign;
begin
Name:=o.Name;
PCH:=O.PCH;
YAW:=O.YAW;
ROL:=O.ROL;
flags1:=o.Flags1;
Flags2:=o.Flags2;
end;
Function TLevel.NewVertex:TVertex;
begin
Result:=TVertex.Create;
end;
Function TLevel.NewWall:TWall;
begin
Result:=TWall.Create;
With Result do
begin
HexID:=GetNewWallID;
Mid.Name:='DEFAULT.PCX';
Top.Name:='DEFAULT.PCX';
Bot.Name:='DEFAULT.PCX';
OverLay.Name:='';
Adjoin:=-1;
DAdjoin:=-1;
Mirror:=-1;
DMirror:=-1;
end;
end;
Function Tlevel.NewSector:TSector;
begin
Result:=TSector.Create;
With Result do
begin
HexID:=GetNewSectorID;
Palette:='RANCH';
ColorMap:='RANCH';
Friction:=1;
Gravity:=-60;
Elasticity:=0.3;
VAdjoin:=-1;
Floor_Sound:='NULL';
Floor_Y:=0;
Ceiling_Y:=8;
Floor_Texture.Name:='DEFAULT.PCX';
Ceiling_Texture.Name:='DEFAULT.PCX';
With FloorSlope do
begin
Sector:=-1;
Wall:=-1;
Sector:=-1;
end;
With CeilingSlope do
begin
Sector:=-1;
Wall:=-1;
Sector:=-1;
end;
Layer:=1;
end;
end;
Function TLevel.NewObject:TOB;
begin
Result:=TOB.Create;
With Result do
begin
HexID:=GetNewObjectID;
{Name:=''};
Sector:=-1;
Flags2:=$F0000000; {On all difficulties}
end;
end;
Function TVertex.IsSameXZ(V:TVertex):Boolean;
begin
Result:=(X=V.X) and (Z=V.Z);
end;
{$i level_io.inc}
Initialization
DecimalSeparator:='.';
end.
|
unit ItemInstance;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
GameObject,
Item
;
type
//------------------------------------------------------------------------------
//TItemInstance CLASS
//------------------------------------------------------------------------------
TItemInstance = Class(TGameObject)
private
public
Index : Word; //Should only modify by TInventoryList
Item : TItem;
Quantity : Word;
Identified : Boolean;
Refined : Byte;
Broken : Boolean;
Equipped :Boolean;
SubX,SubY : Byte;
MapID : LongWord;
RemovalTime : LongWord;
procedure GenerateSubCoordinate;
procedure Dropped;
procedure RemoveFromGround;
constructor Create;
end;
//------------------------------------------------------------------------------
implementation
uses
Main,
AreaLoopEvents,
ParameterList,
InstanceMap,
WinLinux
;
procedure TItemInstance.GenerateSubCoordinate;
var
RandomValue: LongWord;
begin
RandomValue := Random( $FFFFFF );
SubX := (RandomValue AND 3) * 3 + 3;
SubY := ((RandomValue SHR 2) AND 3) * 3 + 3;
end;{GenerateSubCoordinate}
//------------------------------------------------------------------------------
procedure TItemInstance.Dropped;
begin
MainProc.ZoneServer.GroundItemList.Add(Self);
RemovalTime := GetTick + (MainProc.ZoneServer.Options.GroundItemTimeout * 1000);
end;
procedure TItemInstance.RemoveFromGround;
var
AParameters : TParameterList;
Index : Integer;
begin
Index := MapInfo.Cell[Position.X,Position.Y].Items.IndexOf(ID);
if Index > -1 then
begin
MapInfo.Cell[
Position.X,
Position.Y
].Items.Delete(Index);
end;
AParameters := TParameterList.Create;
AParameters.AddAsLongWord(1,ID);
AreaLoop(RemoveGroundItem, FALSE,AParameters);
AParameters.Free;
if (MapInfo is TInstanceMap) then
TInstanceMap(MapInfo).DisposeObjectID(ID)
else
MainProc.ZoneServer.Database.Items.Delete(ID);
end;
constructor TItemInstance.Create;
begin
GenerateSubCoordinate;
end;{Create}
//------------------------------------------------------------------------------
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2015 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of an Embarcadero developer tools product.
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit Maps;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, FMX.ListBox, FMX.Edit,
FMX.Maps;
type
TForm1 = class(TForm)
TopToolBar: TToolBar;
BottomToolBar: TToolBar;
Label1: TLabel;
edLat: TEdit;
edLong: TEdit;
Button1: TButton;
MapView1: TMapView;
Panel1: TPanel;
GridPanelLayout1: TGridPanelLayout;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
SpeedButton3: TSpeedButton;
TrackBar1: TTrackBar;
procedure SpeedButton1Click(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
procedure SpeedButton3Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure MapView1MapClick(const Position: TMapCoordinate);
procedure TrackBar1Change(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
// -------------------For Normal button -----------------------------------------
procedure TForm1.Button1Click(Sender: TObject);
var
mapCenter: TMapCoordinate;
begin
mapCenter := TMapCoordinate.Create(StrToFloat(edLat.Text), StrToFloat(edLong.Text));
MapView1.Location := mapCenter;
end;
procedure TForm1.MapView1MapClick(const Position: TMapCoordinate);
var
MyMarker: TMapMarkerDescriptor;
begin
MyMarker := TMapMarkerDescriptor.Create(Position, '');
MyMarker.Draggable := True;
MyMarker.Visible :=True;
MapView1.AddMarker(MyMarker);
end;
procedure TForm1.SpeedButton1Click(Sender: TObject);
begin
MapView1.MapType := TMapType.Normal;
TrackBar1.Value := 0.0;
end;
// -------------------For Satellite button---------------------------------------
procedure TForm1.SpeedButton2Click(Sender: TObject);
begin
MapView1.MapType := TMapType.Satellite;
TrackBar1.Value := 0.0;
end;
// --------------------For Hybrid button-----------------------------------------
procedure TForm1.SpeedButton3Click(Sender: TObject);
begin
MapView1.MapType := TMapType.Hybrid;
TrackBar1.Value := 0.0;
end;
procedure TForm1.TrackBar1Change(Sender: TObject);
begin
MapView1.Bearing := TrackBar1.Value;
end;
end.
|
(*
* FPG EDIT : Edit FPG file from DIV2, FENIX and CDIV
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*)
unit uExportToFiles;
interface
uses LCLIntf, LCLType, ComCtrls, Forms, {Gauges,} Graphics, Controls, SysUtils, Classes,
ClipBrd, FileUtil,
uFPG, uPAL, uIniFile,
uFrmMessageBox, uLanguage,
//inserted by me
uFrmExport, uFPGListView;
procedure export_to_bmp( lvFPG: TFPGListView; path: string; var frmMain: TForm; var gFPG: TProgressBar );
procedure export_to_png( lvFPG: TFPGListView; path: string; var frmMain: TForm; var gFPG: TProgressBar );
procedure export_to_map( lvFPG: TFPGListView; path: string; var frmMain: TForm; var gFPG: TProgressBar );
procedure export_DIV2_PAL( lvFPG: TFPGListView; path: string );
procedure export_MS_PAL ( lvFPG: TFPGListView; path: string );
procedure export_PSP_PAL ( lvFPG: TFPGListView; path: string );
procedure export_control_points( lvFPG: TFPGListView; path: string; var frmMain: TForm; var gFPG: TProgressBar );
implementation
procedure export_control_points( lvFPG: TFPGListView; path: string; var frmMain: TForm; var gFPG: TProgressBar );
var
f : TextFile;
i, j, k, icount: integer;
begin
icount := 1;
gFPG.Position := 0;
gFPG.Show;
gFPG.Repaint;
for i := 0 to lvFPG.Items.Count - 1 do
begin
if not lvFPG.Items.Item[i].Selected then
continue;
icount := icount + 1;
for j := 1 to lvFPG.Fpg.Count do
if lvFPG.Fpg.images[j].code = StrToInt(lvFPG.Items.Item[i].Caption) then
begin
if lvFPG.Fpg.images[j].CPointsCount <= 0 then
continue;
try
AssignFile(f, path + lvFPG.Items.Item[i].Caption + '.cpt');
Rewrite(f);
except
feMessageBox(LNG_ERROR, LNG_NOT_OPEN_FILE, 0, 0 );
Exit;
end;
WriteLn(f, 'CTRL-PTS');
WriteLn(f, lvFPG.Fpg.images[j].CPointsCount);
for k := 0 to lvFPG.Fpg.images[j].CPointsCount - 1 do
begin
Write(f, lvFPG.Fpg.images[j].cpoints[k*2]); Write(f, ' ');
WriteLn(f, lvFPG.Fpg.images[j].cpoints[(k*2) + 1]);
end;
CloseFile(f);
break;
end;
gFPG.Position := (icount * 100) div lvFPG.SelCount;
gFPG.Repaint;
end;
gFPG.Hide;
end;
procedure export_to_bmp( lvFPG: TFPGListView; path: string; var frmMain: TForm; var gFPG: TProgressBar );
var
i, j, icount : integer;
imageName :String;
bmp : TBitmap;
begin
icount := 1;
gFPG.Position := 0;
gFPG.Show;
gFPG.Repaint;
for i := 0 to lvFPG.Items.Count - 1 do
begin
if not lvFPG.Items.Item[i].Selected then
continue;
icount := icount + 1;
case frmExport.rgFilename.ItemIndex of
0: imageName:= lvFPG.Items.Item[i].Caption;
1: imageName:= lvFPG.Items.Item[i].SubItems[0];
2: imageName:= lvFPG.Items.Item[i].Caption +'(' + lvFPG.Items.Item[i].SubItems[0] +')';
end;
for j := 1 to lvFPG.Fpg.Count do
if lvFPG.Fpg.images[j].code = StrToInt(lvFPG.Items.Item[i].Caption) then
begin
//Se comprueba si existe el fichero
if FileExistsUTF8(path + imagename + '.bmp') { *Converted from FileExists* } then
begin
if feMessageBox(LNG_WARNING, LNG_EXISTS_FILE_OVERWRITE, 4, 2) <> mrYes then
break;
end;
bmp:=TBitmap.Create;
bmp.Assign(lvFPG.Fpg.images[j]);
bmp.SaveToFile(path + imagename + '.bmp');
FreeAndNil(bmp);
break;
end;
gFPG.Position := (icount * 100) div lvFPG.SelCount;
gFPG.Repaint;
end;
gFPG.Hide;
end;
procedure export_to_PNG( lvFPG: TFPGListView; path: string; var frmMain: TForm; var gFPG: TProgressBar );
var
i, j, icount: integer;
image :TPortableNetworkGraphic;
imageName : String;
begin
image := TPortableNetworkGraphic.Create;
icount := 1;
gFPG.Position := 0;
gFPG.Show;
gFPG.Repaint;
for i := 0 to lvFPG.Items.Count - 1 do
begin
if not lvFPG.Items.Item[i].Selected then
continue;
icount := icount + 1;
case frmExport.rgFilename.ItemIndex of
0: imageName:= lvFPG.Items.Item[i].Caption;
1: imageName:= lvFPG.Items.Item[i].SubItems[0];
2: imageName:= lvFPG.Items.Item[i].Caption +'(' + lvFPG.Items.Item[i].SubItems[0] +')';
3: imageName:= lvFPG.Items.Item[i].SubItems[1];
4: imageName:= lvFPG.Items.Item[i].Caption +'(' + lvFPG.Items.Item[i].SubItems[1] +')';
end;
for j := 1 to lvFPG.Fpg.Count do
if lvFPG.Fpg.images[j].code = StrToInt(lvFPG.Items.Item[i].Caption) then
begin
//Se comprueba si existe el fichero
if FileExistsUTF8(path + imageName + '.png') { *Converted from FileExists* } then
begin
if feMessageBox(LNG_WARNING, LNG_EXISTS_FILE_OVERWRITE, 4, 2) <> mrYes then
break;
end;
image.Assign(lvFPG.Fpg.images[j]);
image.savetofile(path + imageName + '.png');
break;
end;
gFPG.Position := (icount * 100) div lvFPG.SelCount;
gFPG.Repaint;
end;
image.Destroy;
gFPG.Hide;
end;
procedure export_to_map( lvFPG: TFPGListView; path: string; var frmMain: TForm; var gFPG: TProgressBar );
var
i, j, icount : integer;
imageName :String;
begin
icount := 1;
gFPG.Position := 0;
gFPG.Show;
gFPG.Repaint;
for i := 0 to lvFPG.Items.Count - 1 do
begin
if not lvFPG.Items.Item[i].Selected then
continue;
icount := icount + 1;
case frmExport.rgFilename.ItemIndex of
0: imageName:= lvFPG.Items.Item[i].Caption;
1: imageName:= lvFPG.Items.Item[i].SubItems[0];
2: imageName:= lvFPG.Items.Item[i].Caption +'(' + lvFPG.Items.Item[i].SubItems[0] +')';
end;
for j := 1 to lvFPG.Fpg.Count do
if lvFPG.Fpg.images[j].code = StrToInt(lvFPG.Items.Item[i].Caption) then
begin
//Se comprueba si existe el fichero
if FileExistsUTF8(path + imagename + '.map') { *Converted from FileExists* } then
begin
if feMessageBox(LNG_WARNING, LNG_EXISTS_FILE_OVERWRITE, 4, 2) <> mrYes then
break;
end;
//lvFPG.Fpg.images[j].bmp.SaveToFile(path + imagename + '.map');
lvFPG.Fpg.SaveToFile(j,path + imagename + '.map');
break;
end;
gFPG.Position := (icount * 100) div lvFPG.SelCount;
gFPG.Repaint;
end;
gFPG.Hide;
end;
procedure export_DIV2_PAL( lvFPG: TFPGListView; path: string );
begin
Save_DIV2_PAL(lvFPG.Fpg.palette, path + 'DIV2.pal' );
end;
procedure export_MS_PAL( lvFPG: TFPGListView; path: string );
begin
Save_MS_PAL(lvFPG.Fpg.palette, path + 'MS.pal' );
end;
procedure export_PSP_PAL( lvFPG: TFPGListView; path: string );
begin
Save_JASP_pal(lvFPG.Fpg.palette, path + 'PSP4.pal' );
end;
end.
|
unit Classes.Box.Goal;
interface
uses
Interfaces.Box.Goal,
Vcl.ExtCtrls,
System.Classes,
System.Types,
Vcl.Imaging.pngimage,
Vcl.Controls;
type
TBoxGoal = class(TInterfacedObject, IBoxGoal)
strict private
var
FPosition: TPoint;
FImage: TImage;
FOwner: TGridPanel;
png: TPngImage;
FKey: Integer;
public
class function New(const AOwner: TGridPanel): IBoxGoal;
destructor Destroy; override;
function Position(const Value: TPoint): IBoxGoal; overload;
function Position: TPoint; overload;
function Owner(const Value: TGridPanel): IBoxGoal; overload;
function Owner: TGridPanel; overload;
function Key(const Value: Integer): IBoxGoal; overload;
function Key: Integer; overload;
function CreateImages: IBoxGoal;
function ChangeParent: IBoxGoal;
end;
implementation
uses
System.SysUtils;
{ TBoxGoal }
function TBoxGoal.ChangeParent: IBoxGoal;
var
Panel: TWinControl;
begin
Result := Self;
Panel := TWinControl(FOwner.ControlCollection.Controls[FPosition.X - 1, FPosition.Y - 1]);
FImage.Parent := Panel;
end;
function TBoxGoal.CreateImages: IBoxGoal;
var
Panel: TWinControl;
begin
Result := Self;
Panel := TWinControl(FOwner.ControlCollection.Controls[FPosition.X - 1, FPosition.Y - 1]);
FImage := TImage.Create(Panel);
FImage.Parent := Panel;
FImage.Align := alClient;
if Assigned(png) then
FreeAndNil(png);
png := TPngImage.Create;
png.LoadFromResourceName(HInstance, 'boxgoal');
FImage.Picture.Graphic := png;
end;
destructor TBoxGoal.Destroy;
begin
FOwner.ControlCollection.RemoveControl(FImage);
FreeAndNil(FImage);
if Assigned(png) then
FreeAndNil(png);
inherited;
end;
function TBoxGoal.Key: Integer;
begin
Result := FKey;
end;
function TBoxGoal.Key(const Value: Integer): IBoxGoal;
begin
Result := Self;
FKey := Value;
end;
class function TBoxGoal.New(const AOwner: TGridPanel): IBoxGoal;
begin
Result := Self.Create;
Result.Owner(AOwner);
end;
function TBoxGoal.Owner: TGridPanel;
begin
Result := FOwner;
end;
function TBoxGoal.Owner(const Value: TGridPanel): IBoxGoal;
begin
Result := Self;
FOwner := Value;
end;
function TBoxGoal.Position(const Value: TPoint): IBoxGoal;
begin
Result := Self;
FPosition := Value;
end;
function TBoxGoal.Position: TPoint;
begin
Result := FPosition;
end;
end.
|
unit userdir;
//returns directory where user has read/write permissions...
{$IFDEF FPC} {$mode delphi}{$H+} {$ENDIF}
{$IFDEF Darwin} {$modeswitch objectivec2} {$ENDIF}
interface
//returns number of cores: a computer with two dual cores will report 4
function IniName: string;
function DefaultsDir (lSubFolder: string): string;
function DesktopFolder: string;
{$IFDEF OLDOSX}
function AppDir: string; //e.g. c:\folder\ for c:\folder\myapp.exe, but /folder/myapp.app/ for /folder/myapp.app/app
{$ELSE}
function AppDir: string; //e.g. c:\folder\ for c:\folder\myapp.exe, but /myapp.app/Contents/Resources
{$ENDIF}
function AppDir2: string; //e.g. c:\folder\ for c:\folder\myapp.exe, but /folder/ for /folder/myapp.app/app
function ResourceDir (): string;
implementation
{$IFDEF UNIX}
uses {$IFDEF Darwin}CocoaAll, {$ENDIF}{$IFDEF LINUX}BaseUnix, {$ENDIF} Process, SysUtils,classes,IniFiles,dialogs, define_types ;
function DesktopFolder: string; //Returns path of destop folder with pathdelim, ~/Desktop/
begin
result := GetEnvironmentVariable ('HOME')+pathdelim+ 'Desktop'+pathdelim;
if not DirectoryExists(result) then
result := GetEnvironmentVariable ('HOME')+pathdelim;
//result := '~/Desktop/';
end;
function FileNameNoExt (lFilewExt:String): string;
//remove final extension
var
lLen,lInc: integer;
lName: String;
begin
lName := '';
lLen := length(lFilewExt);
lInc := lLen+1;
if lLen > 0 then begin
repeat
dec(lInc);
until (lFileWExt[lInc] = '.') or (lInc = 1);
end;
if lInc > 1 then
for lLen := 1 to (lInc - 1) do
lName := lName + lFileWExt[lLen]
else
lName := lFilewExt; //no extension
Result := lName;
end;
{$IFDEF DARWIN}
function SharedSupportFolder: ansistring;
var
path: NSString;
begin
path := NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, true).lastObject;
path := path.stringByAppendingPathComponent(NSBundle.mainBundle.bundlePath.lastPathComponent.stringByDeletingPathExtension);
NSFileManager.defaultManager.createDirectoryAtPath_withIntermediateDirectories_attributes_error(path, false, nil, nil);
result := path.UTF8String;
end;
function DefaultsDir (lSubFolder: string): string;
//for Linux: DefaultsDir is ~/appname/SubFolder/, e.g. /home/username/mricron/subfolder/
//Note: Final character is pathdelim
begin
result := SharedSupportFolder+PathDelim;
end;
{$ENDIF}
{$IFDEF LINUX}
function DefaultsDir (lSubFolder: string): string;
//for Linux: DefaultsDir is ~/appname/SubFolder/, e.g. /home/username/mricron/subfolder/
//Note: Final character is pathdelim
//const
// pathdelim = '/';
var
lBaseDir: string;
begin
lBaseDir := GetEnvironmentVariable ('HOME')+PathDelim+'.'+ FileNameNoExt(ExtractFilename(paramstr(0) ) );
if not DirectoryExists(lBaseDir) then begin
{$I-}
MkDir(lBaseDir);
if IOResult <> 0 then begin
//Msg('Unable to create new folder '+lBaseDir);
end;
{$I+}
end;
lBaseDir := lBaseDir+pathdelim;
if lSubFolder <> '' then begin
lBaseDir := lBaseDir + lSubFolder;
if not DirectoryExists(lBaseDir) then begin
{$I-}
MkDir(lBaseDir);
if IOResult <> 0 then begin
//you may want to show an error, e.g. showmessage('Unable to create new folder '+lBaseDir);
exit;
end;
{$I+}
end;
result := lBaseDir + pathdelim;
end else
result := lBaseDir;
end;
{$ENDIF}
function IniName: string;
begin
result := DefaultsDir('')+FileNameNoExt(extractfilename(paramstr(0)))+'.ini';
end;
{$ELSE} //If UNIX ELSE NOT Unix
uses
SysUtils, Windows,shlobj;
//for administrators, we can write to folder with executable, otherwise we will save data to the user's AppDataFolder
function AppDataFolder: string; //uses shlobj
{$IFDEF FPC} const CSIDL_APPDATA = 26; {$ENDIF}
var
Path : pchar;
idList : PItemIDList;
begin
GetMem(Path, MAX_PATH);
SHGetSpecialFolderLocation(0, CSIDL_APPDATA , idList);
SHGetPathFromIDList(idList, Path);
Result := string(Path);
FreeMem(Path);
end;
function DesktopFolder: string; //Returns path of destop folder with pathdelim, ~/Desktop/
//uses shlobj
{$IFDEF FPC} const CSIDL_DESKTOPDIRECTORY = $0010; {$ENDIF}
var
Path : pchar;
idList : PItemIDList;
begin
GetMem(Path, MAX_PATH);
SHGetSpecialFolderLocation(0, CSIDL_DESKTOPDIRECTORY , idList);
SHGetPathFromIDList(idList, Path);
Result := string(Path);
if (length(Result) > 1) and (Result[length(Result)] <> pathdelim) then
result := result + pathdelim;
FreeMem(Path);
end;
function IsAdmin: Boolean;
const
SECURITY_NT_AUTHORITY: TSIDIdentifierAuthority =
(Value: (0, 0, 0, 0, 0, 5));
SECURITY_BUILTIN_DOMAIN_RID = $00000020;
DOMAIN_ALIAS_RID_ADMINS = $00000220;
var
hAccessToken: THandle;
ptgGroups: PTokenGroups;
dwInfoBufferSize: DWORD;
psidAdministrators: PSID;
x: Integer;
bSuccess: BOOL;
// LastError: integer;
begin
if Win32Platform <> VER_PLATFORM_WIN32_NT then
begin
Result := True;
exit;
end;
Result := False;
bSuccess := OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True,
hAccessToken);
if not bSuccess then
begin
if GetLastError = ERROR_NO_TOKEN then
bSuccess := OpenProcessToken(GetCurrentProcess, TOKEN_QUERY,
hAccessToken);
end;
if bSuccess then
begin
GetMem(ptgGroups, 1024);
{$IFDEF FPC}
bSuccess := GetTokenInformation(hAccessToken, TokenGroups,
ptgGroups, 1024, @dwInfoBufferSize);
{$ELSE}
bSuccess := GetTokenInformation(hAccessToken, TokenGroups,
ptgGroups, 1024, dwInfoBufferSize);
{$ENDIF}
(*LastError := GetLastError;
if not bSuccess then begin
//you may want to show an error message..
//showmessage(format('GetLastError %d',[LastError]));
end;*)
CloseHandle(hAccessToken);
if bSuccess then
begin
AllocateAndInitializeSid(SECURITY_NT_AUTHORITY, 2,
SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0, psidAdministrators);
{$R-}
for x := 0 to ptgGroups.GroupCount - 1 do
if EqualSid(psidAdministrators, ptgGroups.Groups[x].Sid) then
begin
Result := True;
break;
end;
{$R+}
FreeSid(psidAdministrators);
end;
FreeMem(ptgGroups);
end;
end;
function IniName: string;
//only administrators can write to c:\program files -use AppDataFolder for non-Administrators
begin
if isAdmin then
result := changefileext(paramstr(0),'.ini')
else
result := AppDataFolder+'\'+changefileext(extractfilename(paramstr(0)),'.ini');
end;
function DefaultsDir (lSubFolder: string): string;
const
pathdelim = '\';
//for Administrators: DefaultsDir is in the location of the executable, e.g. c:\program files\mricron\subfolder\
//for non-Administrators, the AppDataFolder is returned
//Note: Final character is pathdelim
begin
result := extractfilepath(IniName);
if length(result) < 1 then exit;
if result[length(result)] <> pathdelim then
result := result + pathdelim;
if lSubFolder = '' then
exit;
result := result + lSubFolder;
if result[length(result)] <> pathdelim then
result := result + pathdelim;
end;
{$ENDIF}
{$IFDEF Darwin}
function AppDirActual: string; //e.g. c:\folder\ for c:\folder\myapp.exe, but /folder/myapp.app/ for /folder/myapp.app/app
//OSX Sierra: randomlocation on your drive https://9to5mac.com/2016/06/15/macos-sierra-gatekeeper-changes/
var
lInName,lPath,lName,lExt: string;
begin
result := '';
lExt := '';
lInName := extractfilepath(paramstr(0));
while (length(lInName) > 3) and (upcase(lExt) <> '.APP') do begin
FilenameParts (lInName, lPath,lName,lExt) ;
lInName := ExpandFileName(lInName + '\..');
end;
if (upcase(lExt) <> '.APP') then begin
lInName := GetCurrentDir;
while (length(lInName) > 3) and (upcase(lExt) <> '.APP') do begin
FilenameParts (lInName, lPath,lName,lExt) ;
lInName := ExpandFileName(lInName + '\..');
end;
end; //try GetCurrentDir if paramstr(0) fails
if (upcase(lExt) = '.APP') then
result := lPath+lName+lExt+pathdelim;
end;
{$IFDEF OLDOSX}
function AppDir: string; //e.g. c:\folder\ for c:\folder\myapp.exe, but /folder/myapp.app/ for /folder/myapp.app/app
begin
result := AppDirActual;
end;
{$ELSE}
///MRIcroGL.app/Contents/Resources
function AppDir: string; //e.g. c:\folder\ for c:\folder\myapp.exe, but /myapp.app/Contents/Resources
begin
result := AppDirActual+'Contents'+pathdelim+'Resources'+pathdelim;
end;
{$ENDIF}
function AppDir2: string; //e.g. c:\folder\ for c:\folder\myapp.exe, but /folder/myapp.app/ for /folder/myapp.app/app
begin
result := ExtractFilePath(ExtractFileDir(AppDirActual));
end;
{$ELSE}
function AppDir: string; //e.g. c:\folder\ for c:\folder\myapp.exe, but /folder/myapp.app/ for /folder/myapp.app/app
begin
result := extractfilepath(paramstr(0))+'Resources'+pathdelim;
{$IFDEF LINUX}
if DirectoryExists(result) then exit;
result := '/usr/share/surfice'; //e.g. Debian for either GTK2 or QT5
if DirectoryExists(result) then exit;
//https://wiki.freepascal.org/Multiplatform_Programming_Guide#Unix.2FLinux
// /usr/local/share/app_name or /opt/app_name.
result := '/usr/local/share/'+ExtractFileName(paramstr(0))+pathdelim;
writeln('looking for surfice resources directory:'+result);
if DirectoryExists(result) then exit;
result := '/opt/'+ExtractFileName(paramstr(0))+pathdelim;
if DirectoryExists(result) then exit;
result := FpGetEnv('SURFICE_DIR')+pathdelim;
if DirectoryExists(result) then exit;
result := extractfilepath(paramstr(0))+'Resources'+pathdelim;
{$ENDIF}
if DirectoryExists(result) then exit;
result := extractfilepath(paramstr(0));
end;
function AppDir2: string; //e.g. c:\folder\ for c:\folder\myapp.exe, but /folder/myapp.app/ for /folder/myapp.app/app
begin
result := extractfilepath(paramstr(0));
end;
{$ENDIF}
{$IFDEF Darwin}
function ResourceDir (): string;
begin
result := NSBundle.mainBundle.resourcePath.UTF8String;
end;
function ResourceURL (name: pchar; ofType: pchar): NSURL;
begin
result := NSBundle.mainBundle.URLForResource_withExtension(NSSTR(name), NSSTR(ofType));
end;
function ResourceFile (name: pchar; ofType: pchar): string;
var
url: NSURL;
begin
url := ResourceURL(name, ofType);
result := url.relativePath.UTF8String;
if (result = '') then
writeln('Error: unable to load resource "'+StrPas(name)+'.'+StrPas(ofType)+'" in "'+ResourceDir()+'"');
end;
{$ELSE}
{$IFDEF LINUX}
var
gResourceDir : string = '';
function ResourceDir (): string;
label
111, 222, 333;
var
pths, nms, exts: TStringList;
p,n,x: integer;
verbose: boolean = false;
str: string;
begin
if (length(gResourceDir) > 0) then
exit(gResourceDir);
result := extractfilepath(paramstr(0))+'Resources';
if DirectoryExists(result) then goto 333;
str := FpGetEnv('SURFICE_DIR');
if (length(str) > 0) then begin
result := str;
if DirectoryExists(result) then goto 333;
end;
pths := TStringList.Create;
pths.Add('/opt/');
pths.Add('/usr/local/');
pths.Add('/usr/local/share/');
pths.Add('/usr/share/');
nms := TStringList.Create;
if (CompareText('Surfice', paramstr(0)) <> 0) then begin
nms.Add(ExtractFileName(paramstr(0)));
result := '/usr/share/surfice'; //e.g. Debian for either GTK2 or QT5
if DirectoryExists(result) then goto 333;
end;
nms.Add('Surfice');
nms.Add('surfice');
exts := TStringList.Create;
exts.Add('/Resources');
exts.Add('');
111:
for p := 0 to pths.Count -1 do
for n := 0 to nms.Count -1 do
for x := 0 to exts.Count -1 do begin
result := pths[p]+nms[n]+exts[x];
if DirectoryExists(result) then
goto 222;
if (verbose) then
writeln(' '+result)
end;
if not verbose then begin
//report errors for second pass
writeln('Unable to find Resources folder:');
verbose := true;
goto 111;
end;
222:
exts.Free;
nms.Free;
pths.Free;
333:
gResourceDir := result;
end;
{$ELSE} //Windows
function ResourceDir (): string;
begin
result := extractfilepath(paramstr(0))+'Resources';
end;
{$ENDIF}
function ResourceFile (name: pchar; ofType: pchar): string;
begin
result := ResourceDir + pathdelim + name +'.'+ ofType;
end;
{$ENDIF}
(*function ExeDir: string; //e.g. c:\folder\ for c:\folder\myapp.exe, but /folder/myapp.app/ for /folder/myapp.app/app
begin
result := extractfilepath(paramstr(0));
end; *)
end.
|
unit UtilLib_UiLib;
//YXC_2010_04_04_22_28_26
//专门用有处理UI的库
interface
uses
SysUtils,Forms,ExtCtrls,AdvGrid,Grids;
procedure SetCommonFormParams(AForm:TForm);
procedure SetCommonMainFormParams(AForm:TForm);
procedure SetCommonDialogParams(ADialog:TForm);
procedure SetCommonAdvGridParams(AAdvGrid:TAdvStringGrid);
procedure SetFormBottomImage(AImage:TImage);
//YXC_2010_05_13_21_08_57
procedure ReSetAdvGridCellIdex(AAdvGrid:TAdvStringGrid);
implementation
uses
UtilLib;
procedure SetCommonFormParams(AForm:TForm);
begin
AForm.Position:=poScreenCenter;
AForm.Font.Size := 10;
AForm.Font.Name :='宋体';
end;
procedure SetCommonMainFormParams(AForm:TForm);
begin
AForm.Font.Size := 10;
AForm.Font.Name :='宋体';
end;
procedure SetCommonDialogParams(ADialog:TForm);
begin
ADialog.Position:=poScreenCenter;
ADialog.Font.Size := 10;
ADialog.Font.Name :='宋体';
ADialog.BorderStyle:=bsDialog;
end;
procedure SetCommonAdvGridParams(AAdvGrid:TAdvStringGrid);
begin
with AAdvGrid do
begin
ColWidths[0]:=40;
ColumnSize.Stretch:=True;
Options:=Options+[goColSizing];
Options:=Options+[goRowSelect];
ShowHint:=True;
HintShowCells:=True;
Font.Size:=10;
Font.Name:='宋体';
FixedFont.Size:=10;
FixedFont.Name:='宋体';
end;
end;
procedure SetFormBottomImage(AImage:TImage);
var
APath:string;
begin
APath:=UtilLib.GetExePath+'Images\BackGround.jpg';
if FileExists(APath) then
begin
AImage.Picture.LoadFromFile(APath);
AImage.Stretch:=True;
end;
end;
procedure ReSetAdvGridCellIdex(AAdvGrid:TAdvStringGrid);
var
I:Integer;
begin
with AAdvGrid do
begin
for I:=1 to RowCount-1 do
begin
Ints[0,I]:=I;
end;
end;
end;
end.
|
unit Coches.View.Desktop;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Rtti,
FMX.Grid.Style, FMX.StdCtrls, FMX.Layouts, FMX.Controls.Presentation,
FMX.ScrollBox, FMX.Grid, System.Actions, FMX.ActnList,
DataSet.Interfaces,
MVVM.Attributes,
MVVM.Interfaces, MVVM.Bindings,
MVVM.Controls.Platform.FMX,
MVVM.Views.Platform.FMX, FMX.Objects;
type
[View_For_ViewModel('CochesMain.Grid', IDataSet_ViewModel, 'WINDOWS_DESKTOP')]
TfrmCochesDesktop = class(TFormView<IDataSet_ViewModel>)
actlst1: TActionList;
actGet: TAction;
actNew: TAction;
actDelete: TAction;
actUpdate: TAction;
Grid1: TGrid;
Layout1: TLayout;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Image1: TImage;
protected
{ Private declarations }
procedure SetupView; override;
public
{ Public declarations }
end;
implementation
uses
MVVM.Types;
{$R *.fmx}
{ TForm2 }
procedure TfrmCochesDesktop.SetupView;
begin
// dataset configuration
ViewModel.TableName := 'Coches';
// views configuration
ViewModel.NewRowView := 'New.Coche';
ViewModel.UpdateRowView := 'Update.Coche';
// actions binding
actGet.Bind(procedure
begin
ViewModel.MakeGetRows;
end);
actNew.Bind(procedure
begin
ViewModel.MakeAppend;
end);
actUpdate.Bind(procedure
begin
ViewModel.MakeUpdate;
end);
actDelete.Bind(procedure
begin
ViewModel.DeleteActiveRow;
end);
// Dataset binding
ViewModel.MakeGetRows;
Binder.BindDataSetToGrid(ViewModel.DataSet, Grid1, [
TGridColumnTemplate.Create('ID', 'ID', True, 50, '', '', ''),
TGridColumnTemplate.Create('NOMBRE', 'NOMBRE', True, 150, '', '', '')
]);
Binder.BindDataSetFieldToProperty(ViewModel.DataSet, 'IMAGEN', Image1, 'Bitmap');
end;
initialization
TfrmCochesDesktop.ClassName;
end.
|
namespace com.example.android.simplewiktionary;
{*
* Copyright (C) 2007 The Android Open Source Project
*
* 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.
*}
interface
uses
org.json,
android.content,
android.content.pm,
android.net,
android.util,
java.io,
java.net;
type
/// <summary>
/// Helper methods to simplify talking with and parsing responses from a
/// lightweight Wiktionary API. Before making any requests, you should call
/// prepareUserAgent(Context) to generate a User-Agent string based on
/// your application package name and version.
/// </summary>
SimpleWikiHelper = public class
private
const TAG = 'SimpleWikiHelper';
// Partial URL to use when requesting the detailed entry for a specific
// Wiktionary page. Use String.format(String, Object...) to insert
// the desired page title after escaping it as needed.
const WIKTIONARY_PAGE =
'https://en.wiktionary.org/w/api.php?action=query&prop=revisions&titles=%s&' +
'rvprop=content&format=json%s';
// Partial URL to append to WIKTIONARY_PAGE when you want to expand
// any templates found on the requested page. This is useful when browsing
// full entries, but may use more network bandwidth.
const WIKTIONARY_EXPAND_TEMPLATES = '&rvexpandtemplates=true';
// StatusLine HTTP status code when no server error has occurred.
const HTTP_STATUS_OK = 200;
// Shared buffer used by getUrlContent(String) when reading results
// from an API request.
class var sBuffer: array of SByte := new SByte[512];
public
// Regular expression that splits "Word of the day" entry into word
// name, word type, and the first description bullet point.
const WORD_OF_DAY_REGEX = '(?s)\{\{wotd\|(.+?)\|(.+?)\|([^#\|]+).*?\}\}';
class method getPageContent(title: String; expandTemplates: Boolean): String;
protected
class method getUrlContent(url: String): String; locked;
end;
// Thrown when there were problems contacting the remote API server, either
// because of a network error, or the server returned a bad status code.
ApiException nested in SimpleWikiHelper = public class(Exception)
public
constructor(detailMessage: String; throwable: Throwable);
constructor(detailMessage: String);
end;
// Thrown when there were problems parsing the response to an API call,
// either because the response was empty, or it was malformed.
ParseException nested in SimpleWikiHelper = public class(Exception)
public
constructor(detailMessage: String; throwable: Throwable);
end;
implementation
/// <summary>
/// Read and return the content for a specific Wiktionary page. This makes a
/// lightweight API call, and trims out just the page content returned.
/// Because this call blocks until results are available, it should not be
/// run from a UI thread.
/// Throws ApiException If any connection or server error occurs.
/// Throws ParseException If there are problems parsing the response.
/// </summary>
/// <param name="title">The exact title of the Wiktionary page requested.</param>
/// <param name="expandTemplates">If true, expand any wiki templates found.</param>
/// <returns>Exact content of page.</returns>
class method SimpleWikiHelper.getPageContent(title: String; expandTemplates: Boolean): String;
begin
// Encode page title and expand templates if requested
var encodedTitle: String := android.net.Uri.encode(title);
var expandClause: String := if expandTemplates then WIKTIONARY_EXPAND_TEMPLATES else '';
// Query the API for content
var content: String := getUrlContent(String.format(WIKTIONARY_PAGE, encodedTitle, expandClause));
try
// Drill into the JSON response to find the content body
var response: JSONObject := new JSONObject(content);
var query: JSONObject := response.JSONObject['query'];
var pages: JSONObject := query.JSONObject['pages'];
var page: JSONObject := pages.JSONObject[String(pages.keys.next)];
var revisions: JSONArray := page.JSONArray['revisions'];
var revision: JSONObject := revisions.JSONObject[0];
exit revision.String['*'];
except
on e: JSONException do
raise new ParseException('Problem parsing API response', e)
end
end;
/// <summary>
/// Pull the raw text content of the given URL. This call blocks until the
/// operation has completed, and is synchronized because it uses a shared
/// buffer sBuffer.
/// Throws ApiException If any connection or server error occurs.
/// </summary>
/// <param name="url">The exact URL to request.</param>
/// <returns>The raw content returned by the server.</returns>
class method SimpleWikiHelper.getUrlContent(url: String): String;
begin
var _url := new URL(url);
var urlConnection: HttpURLConnection := HttpURLConnection(_url.openConnection());
urlConnection.connect();
try
var inputStream: InputStream := new BufferedInputStream(urlConnection.getInputStream());
var content: ByteArrayOutputStream := new ByteArrayOutputStream;
// Read response into a buffered stream
var readBytes: Integer := 0;
repeat
readBytes := inputStream.&read(sBuffer);
if readBytes <> -1 then
content.&write(sBuffer, 0, readBytes);
until readBytes = -1;
// Return result from buffered stream
exit new String(content.toByteArray);
except
on e: IOException do
raise new ApiException('Problem communicating with API', e)
finally
urlConnection.disconnect();
end;
end;
constructor SimpleWikiHelper.ApiException(detailMessage: String; throwable: Throwable);
begin
inherited
end;
constructor SimpleWikiHelper.ApiException(detailMessage: String);
begin
inherited
end;
constructor SimpleWikiHelper.ParseException(detailMessage: String; throwable: Throwable);
begin
inherited
end;
end. |
unit uImageViewCount;
interface
uses
Generics.Collections,
System.Classes,
System.SyncObjs,
uMemory,
uRuntime,
uDBThread,
uDBContext;
type
TImageViewInfo = class
public
DBContext: IDBContext;
ID: Integer;
constructor Create(DBContext: IDBContext; ID: Integer);
end;
TImageViewCounter = class
private
FData: TQueue<TImageViewInfo>;
FSync: TCriticalSection;
protected
procedure AddImageViewInfo(Info: TImageViewInfo);
procedure ExtractImageInfos(Count: Integer; Infos: TList<TImageViewInfo>);
public
constructor Create;
destructor Destroy; override;
procedure ImageViewed(DBContext: IDBContext; ID: Integer);
end;
TImageViewUpdater = class(TDBThread)
procedure Execute; override;
end;
function ImageViewCounter: TImageViewCounter;
implementation
var
FImageViewCounter: TImageViewCounter = nil;
function ImageViewCounter: TImageViewCounter;
begin
if FImageViewCounter = nil then
FImageViewCounter := TImageViewCounter.Create;
Result := FImageViewCounter;
end;
{ TImageViewCounter }
procedure TImageViewCounter.AddImageViewInfo(Info: TImageViewInfo);
begin
FSync.Enter;
try
FData.Enqueue(Info);
finally
FSync.Leave;
end;
end;
constructor TImageViewCounter.Create;
begin
FSync := TCriticalSection.Create;
FData := TQueue<TImageViewInfo>.Create;
TImageViewUpdater.Create(nil, False);
end;
destructor TImageViewCounter.Destroy;
begin
F(FSync);
FreeList(FData);
inherited;
end;
procedure TImageViewCounter.ExtractImageInfos(Count: Integer;
Infos: TList<TImageViewInfo>);
var
CollectionFileName: string;
begin
FSync.Enter;
try
CollectionFileName := '';
while (FData.Count > 0)
and ((CollectionFileName = '') or (FData.Peek.DBContext.CollectionFileName = CollectionFileName))
and (Infos.Count < Count) do
begin
CollectionFileName := FData.Peek.DBContext.CollectionFileName;
Infos.Add(FData.Dequeue);
end;
finally
FSync.Leave;
end;
end;
procedure TImageViewCounter.ImageViewed(DBContext: IDBContext; ID: Integer);
begin
AddImageViewInfo(TImageViewInfo.Create(DBContext, ID));
end;
{ TImageViewUpdater }
procedure TImageViewUpdater.Execute;
var
Infos: TList<TImageViewInfo>;
FMediaRepository: IMediaRepository;
begin
inherited;
FreeOnTerminate := True;
Infos := TList<TImageViewInfo>.Create;
try
while not DBTerminating do
begin
Sleep(100);
if uRuntime.BlockClosingOfWindows then
Continue;
ImageViewCounter.ExtractImageInfos(1, Infos);
if Infos.Count > 0 then
begin
FMediaRepository := Infos[0].DBContext.Media;
FMediaRepository.IncMediaCounter(Infos[0].ID);
FreeList(Infos, False);
end;
end;
finally
FreeList(Infos);
end;
end;
{ TImageViewInfo }
constructor TImageViewInfo.Create(DBContext: IDBContext; ID: Integer);
begin
Self.DBContext := DBContext;
Self.ID := ID;
end;
initialization
finalization
F(FImageViewCounter);
end.
|
{*******************************************************}
{ }
{ 基于HCView的电子病历程序 作者:荆通 }
{ }
{ 此代码仅做学习交流使用,不可用于商业目的,由此引发的 }
{ 后果请使用者承担,加入QQ群 649023932 来获取更多的技术 }
{ 交流。 }
{ }
{*******************************************************}
unit FunctionImp;
interface
uses
PluginImp, FunctionConst, FunctionIntf;
type
TObjectFunction = class(TCustomFunction, IObjectFunction)
private
FObject: TObject;
public
constructor Create; override;
function GetObject: TObject;
procedure SetObject(const Value: TObject);
end;
TFunBLLFormShow = class(TPluginFunction, IFunBLLFormShow)
private
FAppHandle: THandle;
FOnNotifyEvent: TFunctionNotifyEvent;
public
constructor Create; override;
{ IFunBLLFormShow }
function GetAppHandle: THandle;
procedure SetAppHandle(const Value: THandle);
function GetOnNotifyEvent: TFunctionNotifyEvent;
procedure SetOnNotifyEvent(const Value: TFunctionNotifyEvent);
property AppHandle: THandle read GetAppHandle write SetAppHandle;
property OnNotifyEvent: TFunctionNotifyEvent read GetOnNotifyEvent write SetOnNotifyEvent;
end;
implementation
{ TFunBLLFormShow }
constructor TFunBLLFormShow.Create;
begin
ID := FUN_BLLFORMSHOW;
Name := FUN_BLLFORMSHOW_NAME;
end;
function TFunBLLFormShow.GetAppHandle: THandle;
begin
Result := FAppHandle;
end;
function TFunBLLFormShow.GetOnNotifyEvent: TFunctionNotifyEvent;
begin
Result := FOnNotifyEvent;
end;
procedure TFunBLLFormShow.SetAppHandle(const Value: THandle);
begin
FAppHandle := Value;
end;
procedure TFunBLLFormShow.SetOnNotifyEvent(const Value: TFunctionNotifyEvent);
begin
FOnNotifyEvent := Value;
end;
{ TObjectFunction }
constructor TObjectFunction.Create;
begin
ID := FUN_OBJECT;
end;
function TObjectFunction.GetObject: TObject;
begin
Result := FObject;
end;
procedure TObjectFunction.SetObject(const Value: TObject);
begin
FObject := Value;
end;
end.
|
unit UnitSavingTableForm;
interface
uses
Winapi.Windows,
System.SysUtils,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Data.DB,
Dmitry.Controls.DmProgress,
uDBContext,
uThreadForm;
type
TSavingTableForm = class(TThreadForm)
DmProgress1: TDmProgress;
Label1: TLabel;
BtnAbort: TButton;
procedure FormCreate(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure BtnAbortClick(Sender: TObject);
private
{ Private declarations }
procedure LoadLanguage;
protected
function GetFormID: string; override;
public
{ Public declarations }
FTerminating: Boolean;
procedure Execute(Context: IDBContext; DestinationPath: String; SubFolders: Boolean; FileList: TStrings);
procedure SetMaxValue(Value: Integer);
procedure SetProgress(Value: Integer);
procedure SetText(Value: String);
end;
procedure SaveQuery(Context: IDBContext; DestinationPath: String; SubFolders: Boolean; FileList: TStrings);
implementation
uses
UnitSaveQueryThread;
{$R *.dfm}
procedure SaveQuery(Context: IDBContext; DestinationPath: String; SubFolders: Boolean; FileList: TStrings);
var
SavingTableForm: TSavingTableForm;
begin
Application.CreateForm(TSavingTableForm, SavingTableForm);
try
SavingTableForm.Execute(Context, DestinationPath, SubFolders, FileList);
finally
SavingTableForm.Release;
end;
end;
procedure TSavingTableForm.Execute(Context: IDBContext; DestinationPath: string; SubFolders: Boolean; FileList: TStrings);
begin
TSaveQueryThread.Create(Context, DestinationPath, Self, SubFolders, FileList, StateID);
ShowModal;
end;
procedure TSavingTableForm.LoadLanguage;
begin
BeginTranslate;
try
DmProgress1.Text := L('Progress... (&%%)');
BtnAbort.Caption := L('Abort');
Label1.Caption := L('Saving in progress...');
Caption := L('Saving items to file');
finally
EndTranslate;
end;
end;
procedure TSavingTableForm.FormCreate(Sender: TObject);
begin
LoadLanguage;
FTerminating := False;
end;
function TSavingTableForm.GetFormID: string;
begin
Result := 'SaveCollection'
end;
procedure TSavingTableForm.SetMaxValue(Value: Integer);
begin
DmProgress1.MinValue := Value;
end;
procedure TSavingTableForm.SetText(Value: String);
begin
DmProgress1.Text := Value;
end;
procedure TSavingTableForm.SetProgress(Value: Integer);
begin
DmProgress1.Position := Value;
end;
procedure TSavingTableForm.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
CanClose := False;
end;
procedure TSavingTableForm.BtnAbortClick(Sender: TObject);
begin
FTerminating := True;
end;
end.
|
{
Unit for complementary functions
Author: Wanderlan Santos dos Anjos (wanderlan.anjos@gmail.com)
Date: jul-2008
License: BSD<extlink http://www.opensource.org/licenses/bsd-license.php>BSD</extlink>
}
unit ExtPascalUtils;
{$IFDEF FPC}{$MACRO ON}{$MODE DELPHI}{$ENDIF}
interface
uses
SysUtils, Types, Classes, TypInfo;
const
ExtPascalVersion = '0.9.9';
{$IF not Defined(FPC) and (RTLVersion <= 17)}
type
// Implements StrictDelimiter property for FPC 2.2.2, Delphi 7 and older versions
TStringList = class(Classes.TStringList)
private
function GetDelimitedText : string;
procedure SetDelimitedText(const AValue : string);
public
StrictDelimiter : boolean; // Missing property in FPC 2.2.2, Delphi 7 an older versions
property DelimitedText : string read GetDelimitedText write SetDelimitedText; // Property override for FPC 2.2.2, Delphi 7 an older versions
end;
TStrings = TStringList;
{$IFEND}
type
TBrowser = (brUnknown, brIE, brFirefox, brChrome, brSafari, brOpera, brKonqueror, brMobileSafari); // Internet Browsers
TCSSUnit = (cssPX, cssPerc, cssEM, cssEX, cssIN, cssCM, cssMM, cssPT, cssPC, cssnone); // HTML CSS units
TExtProcedure = procedure of object; // Defines a procedure than can be called by a <link TExtObject.Ajax, AJAX> request
TUploadBlockType = (ubtUnknown, ubtBegin, ubtMiddle, ubtEnd);
procedure StrToTStrings(const S : string; List : TStrings);
function URLDecodeUTF8(const Encoded: string): string;
function URLDecode(const Encoded : string) : string;
function URLEncode(const Decoded : string): string;
{
Determine browser from HTTP_USER_AGENT header string.
@param UserAgentStr String returned by, for example, RequestHeader['HTTP_USER_AGENT'].
@return TBrowser
}
function DetermineBrowser(const UserAgentStr : string) : TBrowser;
{
Mimics preg_match php function. Searches S for a match to delimiter strings given in Delims parameter
@param Delims Delimiter strings to match
@param S Subject string
@param Matches Substrings from Subject string delimited by Delimiter strings. <b>Matches (TStringList) should already be created</b>.
@param Remove matches strings from S, default is true
@return True if some match hit, false otherwise
}
function Extract(const Delims : array of string; var S : string; var Matches : TStringList; Remove : boolean = true) : boolean;
{
Mimics explode php function.
Creates a TStringList where each string is a substring formed by the splitting of S string through delimiter Delim.
@param Delim Delimiter used to split the string
@param S Source string to split
@return TStringList created with substrings from S
}
function Explode(Delim : char; const S : string; Separator : char = '=') : TStringList;
{
The opposite of LastDelimiter RTL function.
Returns the index of the first occurence in a string of the characters specified.
If none of the characters in Delimiters appears in string S, function returns zero.
@param Delimiters String where each character is a valid delimiter.
@param S String to search for delimiters.
@param Offset Index from where the search begins.
}
function FirstDelimiter(const Delimiters, S : string; Offset : integer = 1) : integer;
// The opposite of "StrUtils.PosEx" function. Returns the index value of the last occurrence of a specified substring in a given string.
function RPosEx(const Substr, Str : string; Offset : integer = 1) : integer;
{
Returns the number of occurrences of Substr in Str until UntilStr occurs
@param Substr String to count in Str
@param Str String where the counting will be done
@param UntilStr Optional String, stop counting if this string occurs
}
function CountStr(const Substr, Str : string; UntilStr : string = '') : integer;
{
Converts a string with param place holders to a JavaScript string. Converts a string representing a regular expression to a JavaScript RegExp.
Replaces " to ', ^M^J to <br/> and isolated ^M or ^J to <br/>, surrounds the string with " and insert %0..%9 JS place holders.
When setting a TExtFormTextField value (in property setter setvalue), the UseBR should be set to false,
because otherwise it is impossible to display multiline text in a TExtFormTextArea.
@param S Source string with param place holders or RegExpr
@param UseBR If true uses replace ^M^J to <br/> else to \n
@return a well formatted JS string
}
function StrToJS(const S : string; UseBR : boolean = false) : string;
{
Finds S string in Cases array, returning its index or -1 if not found. Good to use in Pascal "case" command. Similar to AnsiIndexText.
@param S Source string where to search
@param Cases String array to find in S
}
function CaseOf(const S : string; const Cases : array of string) : integer;
{
Finds Cases array in S string, returning its index or -1 if not found. Good to use in Pascal "case" command. Reverse to AnsiIndexStr.
@param S string to find in Cases array
@param Cases String array where to search
}
function RCaseOf(const S : string; const Cases : array of string) : integer;
{
Converts a Pascal enumerated type constant into a JS string, used internally by ExtToPascal wrapper. See ExtFixes.txt for more information.
@param TypeInfo Type information record that describes the enumerated type, use TypeInfo() function with enumerated type
@param Value The enumerated value, represented as an integer
@return JS string
}
function EnumToJSString(const ATypeInfo: PTypeInfo; const AValue: Integer) : string;
{
Helper function to make code more pascalish, use
@example <code>BodyStyle := SetPaddings(10, 15);</code>
instead
@example <code>BodyStyle := 'padding:10px 15px';</code>
}
function SetPaddings(Top : integer; Right : integer = 0; Bottom : integer = -1; Left : integer = 0; CSSUnit : TCSSUnit = cssPX;
Header : boolean = true) : string;
{
Helper function to make code more pascalish, use
@example <code>Margins := SetMargins(3, 3, 3);</code>
instead
@example <code>Margins := '3 3 3 0';</code>
}
function SetMargins(Top : integer; Right : integer = 0; Bottom : integer = 0; Left : integer = 0; CSSUnit : TCSSUnit = cssNone;
Header : boolean = false) : string;
// Returns true if BeforesS string occurs before AfterS string in S string
function Before(const BeforeS, AfterS, S : string) : boolean;
// Returns true if all chars in S are uppercase
function IsUpperCase(S : string) : boolean;
// Beautify generated JS commands from ExtPascal, automatically used when DEBUGJS symbol is defined
function BeautifyJS(const AScript : string; const StartingLevel : integer = 0; SplitHTMLNewLine : boolean = true) : string;
// Beautify generated CSS from ExtPascal, automatically used when DEBUGJS symbol is defined
function BeautifyCSS(const AStyle : string) : string;
// Screen space, in characters, used for a field using regular expression mask
function LengthRegExp(Rex : string; CountAll : Boolean = true) : integer;
function JSDateToDateTime(JSDate : string) : TDateTime;
{
Encrypts a string using a simple and quick method, but not trivial.
@param Value String to be encrypted.
@return String encrypted.
}
function Encrypt(Value : string) : string;
{
Decrypts a string that was previously crypted using the function <link Encrypt>.
@param Value String to be decrypted.
@return String decrypted.
}
function Decrypt(Value : string) : string;
{
Formats a size in bytes.
}
function FormatByteSize(const AByteSize: Longint): string;
function RemoveLastJSTerminator(const AJSCode: string): string;
function Join(const AStrings: TStringDynArray; const ASeparator: string): string; overload;
{$IF CompilerVersion < 33}
function Join(const AStrings: TArray<string>; const ASeparator: string): string; overload;
{$ENDIF}
implementation
uses
StrUtils, Math, DateUtils;
{$IF not Defined(FPC) and (RTLVersion <= 17)}
function TStringList.GetDelimitedText: string;
var
I : integer;
P : pchar;
begin
Result := '';
for I := 0 to Count-1 do begin
P := pchar(Strings[I]);
if not StrictDelimiter then
while not(P^ in [#0..' ', QuoteChar, Delimiter]) do inc(P)
else
while not(P^ in [#0, Delimiter]) do inc(P);
// strings in list may to contain #0
if (P <> pchar(Strings[I]) + length(Strings[I])) and not StrictDelimiter then
Result := Result + QuoteChar + Strings[I] + QuoteChar
else
Result := Result + Strings[I];
if I < Count-1 then Result := Result + Delimiter;
end;
if (length(Result) = 0) and (Count = 1) then Result := QuoteChar + QuoteChar;
end;
procedure TStringList.SetDelimitedText(const AValue : string);
var
I, J : integer;
aNotFirst : boolean;
begin
BeginUpdate;
I := 1;
aNotFirst := false;
try
Clear;
while I <= length(AValue) do begin
// skip delimiter
if aNotFirst and (I <= length(AValue)) and (AValue[I] = Delimiter) then inc(I);
// skip spaces
if not StrictDelimiter then
while (I <= length(AValue)) and (ord(AValue[I]) <= ord(' ')) do inc(I);
// read next string
if I <= length(AValue) then begin
if AValue[I] = QuoteChar then begin
// next string is quoted
J := I + 1;
while (J <= length(AValue)) and ((AValue[J] <> QuoteChar) or
((J+1 <= length(AValue)) and (AValue[J+1] = QuoteChar))) do
if (J <= length(AValue)) and (AValue[J] = QuoteChar) then
inc(J, 2)
else
inc(J);
// J is position of closing quote
Add(StringReplace(Copy(AValue, I+1, J-I-1), QuoteChar + QuoteChar, QuoteChar, [rfReplaceAll]));
I := J + 1;
end
else begin
// next string is not quoted
J := I;
if not StrictDelimiter then
while (J <= length(AValue)) and (ord(AValue[J]) > ord(' ')) and (AValue[J] <> Delimiter) do inc(J)
else
while (J <= length(AValue)) and (AValue[J] <> Delimiter) do inc(J);
Add(copy(AValue, I, J-i));
I := J;
end;
end
else
if aNotFirst then Add('');
// skip spaces
if not StrictDelimiter then
while (I <= length(AValue)) and (ord(AValue[I]) <= ord(' ')) do inc(I);
aNotFirst:=true;
end;
finally
EndUpdate;
end;
end;
{$IFEND}
function DetermineBrowser(const UserAgentStr : string) : TBrowser;
begin
Result := TBrowser(RCaseOf(UserAgentStr, ['MSIE', 'Firefox', 'Chrome', 'Safari', 'Opera', 'Konqueror'])+1);
// Note string order must match order in TBrowser enumeration above
if (Result = brSafari) and // Which Safari?
(Pos('Mobile', UserAgentStr) > 0) and
(Pos('Apple', UserAgentStr) > 0) then
Result := brMobileSafari
end;
function Extract(const Delims : array of string; var S : string; var Matches : TStringList; Remove : boolean = true) : boolean;
var
I, J : integer;
Points : array of integer;
begin
Result := false;
if Matches <> nil then Matches.Clear;
SetLength(Points, length(Delims));
J := 1;
for I := 0 to high(Delims) do begin
J := PosEx(Delims[I], S, J);
Points[I] := J;
if J = 0 then
exit
else
inc(J, length(Delims[I]));
end;
for I := 0 to high(Delims)-1 do begin
J := Points[I] + length(Delims[I]);
Matches.Add(trim(copy(S, J, Points[I+1]-J)));
end;
if Remove then S := copy(S, Points[high(Delims)] + length(Delims[high(Delims)]), length(S));
Result := true
end;
function Explode(Delim : char; const S : string; Separator : char = '=') : TStringList;
var
I : integer;
begin
Result := TStringList.Create;
Result.StrictDelimiter := true;
Result.Delimiter := Delim;
Result.DelimitedText := S;
Result.NameValueSeparator := Separator;
for I := 0 to Result.Count-1 do Result[I] := trim(Result[I]);
end;
function FirstDelimiter(const Delimiters, S : string; Offset : integer = 1) : integer;
var
I : integer;
begin
for Result := Offset to length(S) do
for I := 1 to length(Delimiters) do
if Delimiters[I] = S[Result] then exit;
Result := 0;
end;
function RPosEx(const Substr, Str : string; Offset : integer = 1) : integer;
var
I : integer;
begin
Result := PosEx(Substr, Str, Offset);
while Result <> 0 do begin
I := PosEx(Substr, Str, Result+1);
if I = 0 then
break
else
Result := I
end;
end;
function CountStr(const Substr, Str : string; UntilStr : string = '') : integer;
var
I, J : integer;
begin
I := 0;
Result := 0;
J := Pos(UntilStr, Str);
repeat
I := PosEx(Substr, Str, I+1);
if (J <> 0) and (J < I) then exit;
if I <> 0 then inc(Result);
until I = 0;
end;
function StrToJS(const S : string; UseBR : boolean = false) : string;
var
I, J : integer;
BR : string;
begin
BR := IfThen(UseBR, '<br/>', '\n');
Result := AnsiReplaceStr(S, '"', '\"');
Result := AnsiReplaceStr(Result, ^M^J, BR);
Result := AnsiReplaceStr(Result, ^M, BR);
Result := AnsiReplaceStr(Result, ^J, BR);
if (Result <> '') and (Result[1] = #3) then begin // Is RegEx
delete(Result, 1, 1);
if Pos('/', Result) <> 1 then Result := '/' + Result + '/';
end
else begin
I := pos('%', Result);
if (pos(';', Result) = 0) and (I <> 0) and ((length(Result) > 1) and (I < length(Result)) and CharInSet(Result[I+1], ['0'..'9'])) then begin // Has param place holder, ";" disable place holder
J := FirstDelimiter(' "''[]{}><=!*-+/,', Result, I+2);
if J = 0 then J := length(Result)+1;
if J <> (length(Result)+1) then begin
insert('+"', Result, J);
Result := Result + '"';
end;
if I <> 1 then begin
insert('"+', Result, I);
Result := '"' + Result;
end;
end
else
if (I = 1) and (length(Result) > 1) and CharInSet(Result[2], ['a'..'z', 'A'..'Z']) then
Result := copy(Result, 2, length(Result))
else
Result := '"' + Result + '"'
end;
end;
function CaseOf(const S : string; const Cases : array of string) : integer;
begin
for Result := 0 to high(Cases) do
if SameText(S, Cases[Result]) then exit;
Result := -1;
end;
function RCaseOf(const S : string; const Cases : array of string) : integer;
begin
for Result := 0 to high(Cases) do
if pos(Cases[Result], S) <> 0 then exit;
Result := -1;
end;
function EnumToJSString(const ATypeInfo: PTypeInfo; const AValue: Integer) : string;
var
I : integer;
JS: string;
begin
Result := '';
JS := GetEnumName(ATypeInfo, AValue);
for I := 1 to length(JS) do
begin
if CharInSet(JS[I], ['A'..'Z']) then
begin
Result := LowerCase(copy(JS, I, 100));
if Result = 'perc' then
Result := '%';
Exit;
end;
end;
end;
function SetPaddings(Top : integer; Right : integer = 0; Bottom : integer = -1; Left : integer = 0; CSSUnit : TCSSUnit = cssPX;
Header : boolean = true) : string;
begin
Result := Format('%s%d%3:s %2:d%3:s', [IfThen(Header, 'padding: ', ''), Top, Right, EnumToJSString(TypeInfo(TCSSUnit), ord(CSSUnit))]);
if Bottom <> -1 then
Result := Result + Format(' %d%2:s %1:d%2:s', [Bottom, Left, EnumToJSString(TypeInfo(TCSSUnit), ord(CSSUnit))]);
end;
function SetMargins(Top : integer; Right : integer = 0; Bottom : integer = 0; Left : integer = 0; CSSUnit : TCSSUnit = cssNone;
Header : boolean = false) : string;
begin
Result := Format('%s%d%5:s %2:d%5:s %3:d%5:s %4:d%s', [IfThen(Header, 'margin: ', ''), Top, Right, Bottom, Left,
EnumToJSString(TypeInfo(TCSSUnit), ord(CSSUnit))])
end;
function Before(const BeforeS, AfterS, S : string) : boolean;
var
I : integer;
begin
I := pos(BeforeS, S);
Result := (I <> 0) and (I < pos(AfterS, S))
end;
function IsUpperCase(S : string) : boolean;
var
I : integer;
begin
Result := false;
for I := 1 to length(S) do
if CharInSet(S[I], ['a'..'z']) then exit;
Result := true;
end;
function SpaceIdents(const aLevel: integer; const aWidth: string = ' '): string;
var
c: integer;
begin
Result := '';
if aLevel < 1 then Exit;
for c := 1 to aLevel do Result := Result + aWidth;
end;
function MinValueOf(Values : array of integer; const MinValue : integer = 0) : integer;
var
I : integer;
begin
for I := 0 to High(Values) do
if Values[I] <= MinValue then Values[I] := MAXINT;
Result := MinIntValue(Values);
// if all are the minimum value then return 0
if Result = MAXINT then Result := MinValue;
end;
function BeautifyJS(const AScript : string; const StartingLevel : integer = 0; SplitHTMLNewLine : boolean = true) : string;
var
pBlockBegin, pBlockEnd, pPropBegin, pPropEnd, pStatEnd, {pFuncBegin,} pSqrBegin, pSqrEnd,
pFunction, pString, pOpPlus, pOpNot, pOpMinus, pOpTime, {pOpDivide,} pOpEqual, pRegex : integer;
P, Lvl : integer;
Res : string;
function AddNewLine(const atPos : integer; const AddText : string) : integer;
begin
insert(^J + AddText, Res, atPos);
Result := length(^J + AddText);
end;
function SplitHTMLString(AStart, AEnd : integer): integer; // range is including the quotes
var
br,pe,ps: integer;
s: string;
begin
Result := AEnd;
s := copy(res, AStart, AEnd);
// find html new line (increase verbosity)
br := PosEx('<br>', res, AStart+1);
pe := PosEx('</p>', res, AStart+1);
ps := MinValueOf([br,pe]);
// html new line is found
// Result-5 is to skip the mark at the end of the line
while (ps > 0) and (ps < Result-5) do begin
s := '"+'^J+SpaceIdents(Lvl)+SpaceIdents(3)+'"';
Insert(s, res, ps+4);
Result := Result + length(s);
// find next new line
br := PosEx('<br>', res, ps+length(s)+4);
pe := PosEx('</p>', res, ps+length(s)+4);
ps := MinValueOf([br,pe]);
end;
end;
var
Backward, onReady, inProp, inNew : boolean;
LvlProp, i, j, k : integer;
begin
// skip empty script
if AScript = '' then exit;
P := 1;
Res := AScript;
inNew := true;
inProp := false;
onReady := false;
LvlProp := 1000; // max identation depth
Lvl := StartingLevel;
// remove space in the beginning
if Res[1] = ' ' then Delete(Res, 1, 1);
// proceed the whole generated script by scanning the text
while (p > 0) and (p < Length(Res)-1) do begin
// chars that will be processed (10 signs)
inc(P);
pString := PosEx('"', Res, P);
pOpEqual := PosEx('=', Res, P);
pOpPlus := PosEx('+', Res, P);
pOpNot := PosEx('!', Res, P);
pOpMinus := PosEx('-', Res, P);
pOpTime := PosEx('*', Res, P);
pBlockBegin := PosEx('{', Res, P);
pBlockEnd := PosEx('}', Res, P);
pPropBegin := PosEx(':', Res, P);
pPropEnd := PosEx(',', Res, P);
pStatEnd := PosEx(';', Res, P);
pSqrBegin := PosEx('[', Res, P);
pSqrEnd := PosEx(']', Res, P);
pFunction := PosEx('function', Res, P);
pRegex := PosEx('regex:', Res, P);
// process what is found first
P := MinValueOf([pBlockBegin, pBlockEnd, pPropBegin, pPropEnd, pStatEnd, {pFuncBegin,} pSqrBegin, pSqrEnd,
pString, pOpEqual, pOpPlus, pOpNot, pOpMinus, pOpTime, {pOpDivide,} pFunction, pRegex]);
// keep Ext's onReady function at the first line
if (not onReady) and (P > 0) and (length(Res) >= P) and (res[p] = 'f') then
if Copy(Res, P-9, 9) = '.onReady(' then begin
onReady := true;
continue;
end;
// now, let's proceed with what char is found
if P > 0 then begin
// reset inProp status based on minimum lvlProp
if inProp then inProp := Lvl >= LvlProp; // or (lvl > StartingLevel);
// process chars
case Res[P] of // skip string by jump to the next mark
'"' :
if Res[P-1] <> '\' then begin // skip escaped "s
if Res[P+1] = '"' then // skip empty string
inc(P)
else
//if SplitHTMLNewLine then // proceed html string value
// P := SplitHTMLString(P, PosEx('"', Res, P+1))
//else
begin// just skip the string
Inc(P);
while (Res[P] <> '"') or (Res[P-1] = '\') do // skip escaped "s
Inc(P);
end;
end;
'-', '!', '+', '=', '*', '/': begin // neat the math operator
insert(' ', Res, P); inc(P);
if (Res[P+1] = '=') or (Res[P+1] = '+') or (Res[P+1] = '-') then inc(P); // == or ++ or --
insert(' ', Res, P+1); inc(P);
end;
'{' : // statement block begin
if Res[P+1] = '}' then // skip empty statement
inc(P)
else begin
inc(Lvl); // Increase identation level
inProp := false;
inc(P, AddNewLine(P+1, SpaceIdents(Lvl)));
end;
'}' : begin // statement block end
// some pair values are treated specially: keep },{ pair intact to save empty lines
if (length(Res) >= (P+2)) and (Res[P+1] = ',') and (Res[P+2] = '{') then begin
dec(Lvl);
inc(P, AddNewLine(P, SpaceIdents(Lvl)) + 2);
inc(Lvl);
inc(P, AddNewLine(P+1, SpaceIdents(Lvl)));
continue;
end;
if not inNew then // special })] pair for items property group object ending
inNew := (Res[P+1] = ')') and (Res[P+2] = ']');
// common treatment for block ending
dec(Lvl); // decrease identation level
P := P + AddNewLine(P, SpaceIdents(lvl));
// bring the following trails
I := P;
Backward := false;
repeat
inc(I);
// find multiple statement block end
if (length(Res) >= I) and CharInSet(Res[I], ['{', '}', ';']) then backward := true;
if inNew and (length(Res) >= I) and (Res[I] = ']') then backward := true;
until (I > length(Res)) or (Res[I] = ',') or backward;
if not backward then // add new line
inc(P, AddNewLine(i+1, SpaceIdents(Lvl)))
else // suspend new line to proceed with next block
P := i-1;
end;
';' : begin // end of statement
// fix to ExtPascal parser bug which become helpful, because it could be mark of new object creation
if (length(Res) >= P+2) and (Res[P+1] = ' ') and (Res[P+2] = 'O') then begin // ; O string
inProp := false;
delete(Res, P+1, 1);
inc(P, AddNewLine(P+1, ^J+SpaceIdents(Lvl)));
continue;
end;
if (length(Res) >= P+1) and (Res[P+1] = '}') then continue; // skip if it's already at the end of block
if P = length(Res) then // skip identation on last end of statement
inc(P, AddNewLine(P+1, SpaceIdents(StartingLevel-1)))
else
inc(P, AddNewLine(P+1, SpaceIdents(lvl)));
end;
'[' : begin // square declaration begin
if Res[P+1] = '[' then begin // double square treat as sub level
inc(Lvl);
inc(P, AddNewLine(p+1, SpaceIdents(Lvl)));
inProp := true;
continue;
end;
// find special pair within square block
i := PosEx(']', Res, P+1);
j := PosEx('{', Res, P+1);
k := PosEx('new ', Res, P+1);
if (j > 0) and (j < i) then begin // new block found in property value
inc(Lvl);
// new object found in property value, add new line
if (k > 0) and (k < i) then begin
inNew := true;
inc(P, AddNewLine(P+1, SpaceIdents(Lvl)));
end
else begin // move forward to next block beginning
inNew := false;
inc(J, AddNewLine(J+1, SpaceIdents(Lvl)));
P := j-1;
end;
end
else // no sub block found, move at the end of square block
P := i;
end;
']' : // square declaration end
if Res[P-1] = ']' then begin // double square ending found, end sub block
dec(Lvl);
inc(P, AddNewLine(P, SpaceIdents(Lvl)));
end
else // skip processing if not part of square sub block
if not inNew then
continue
else begin // end of block square items group
dec(Lvl);
inc(P, AddNewLine(P, SpaceIdents(Lvl)));
end;
':' : begin // property value begin
if Res[P+1] <> ' ' then begin // separate name:value with a space
insert(' ', Res, P+1);
inc(P);
end;
inProp := true;
if Lvl < LvlProp then LvlProp := Lvl; // get minimum depth level of property
end;
',' : // property value end
if inProp then inc(P, AddNewLine(P+1, SpaceIdents(Lvl)));
'f' : begin // independent function definition
if inProp then Continue; // skip function if within property
if copy(Res, P, 8) = 'function' then // add new line for independent function
inc(P, AddNewLine(P, SpaceIdents(Lvl)) + 7);
end;
'r' : begin
P := PosEx('/', Res, P);
P := PosEx('/', Res, P+1);
end;
end;
end;
end;
Result := Res;
end;
function BeautifyCSS(const AStyle : string) : string;
var
pOpen, pClose, pProp, pEnd, pString : integer;
P, Lvl : integer;
Res : string;
begin
P := 1;
Lvl := 0;
Res := ^J+AStyle;
while P > 0 do begin
inc(P);
pString := PosEx('''', Res, P);
pOpen := PosEx('{', Res, P);
pClose := PosEx('}', Res, P);
pProp := PosEx(':', Res, P);
pEnd := PosEx(';', Res, P);
P := MinValueOf([pString, pOpen, pClose, pProp, pEnd]);
if P > 0 then
case Res[p] of
'''' : P := PosEx('''', Res, P+1);
'{' : begin
Inc(lvl);
if (res[p-1] <> ' ') then begin
Insert(' ', res, p);
p := p+1;
end;
Insert(^J+SpaceIdents(lvl), res, p+1);
p := p + Length(^J+SpaceIdents(lvl));
end;
'}' : begin
dec(lvl);
insert(^J+SpaceIdents(lvl), Res, P);
inc(P, length(^J+SpaceIdents(Lvl)));
insert(^J+SpaceIdents(lvl), Res, P+1);
inc(P, length(^J+SpaceIdents(Lvl)));
end;
':' :
if Res[P+1] <> ' ' then begin
insert(' ', Res, P+1);
inc(P);
end;
';' : begin
if Res[P+1] = '}' then continue;
if Res[P+1] = ' ' then delete(Res, P+1, 1);
insert(^J+SpaceIdents(Lvl), Res, P+1);
inc(P, length(^J+SpaceIdents(Lvl)));
end;
end;
end;
Result := Res;
end;
function LengthRegExp(Rex : string; CountAll : Boolean = true) : integer;
var
Slash, I : integer;
N : string;
begin
Result := 0;
N := '';
Slash := 0;
for I := 1 to length(Rex) do
case Rex[I] of
'\' :
if CountAll and (I < length(Rex)) and CharInSet(Rex[I+1], ['d', 'D', 'l', 'f', 'n', 'r', 's', 'S', 't', 'w', 'W']) then inc(Slash);
',', '{' : begin
N := '';
if Slash > 1 then begin
inc(Result, Slash);
Slash := 0;
end;
end;
'}' : begin
inc(Result, StrToIntDef(N, 0));
N := '';
dec(Slash);
end;
'0'..'9' : N := N + Rex[I];
'?' : inc(Slash);
'*' :
if not CountAll then begin
Result := -1;
exit;
end;
end;
inc(Result, Slash);
end;
function JSDateToDateTime(JSDate : string) : TDateTime;
begin
Result := EncodeDateTime(StrToInt(copy(JSDate, 12, 4)), AnsiIndexStr(copy(JSDate, 5, 3), ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']) +1,
StrToInt(copy(JSDate, 9, 2)), StrToInt(copy(JSDate, 17, 2)), StrToInt(copy(JSDate, 20, 2)), StrToInt(copy(JSDate, 23, 2)), 0);
end;
function Encrypt(Value : string) : string;
var
I, F1, F2, T : integer;
B : byte;
NValue : string;
begin
Randomize;
B := Random(256);
NValue := char(B);
F1 := 1; F2 := 2;
for I := 1 to length(Value) do begin
T := F2;
inc(F2, F1);
F1 := T;
NValue := NValue + char(ord(Value[I]) + (B*F2));
end;
Result := '';
for I := 1 to Length(NValue) do
Result := Result + IntToHex(byte(NValue[I]), 2);
end;
function Decrypt(Value : string) : string;
var
I, F1, F2, T : integer;
B : byte;
NValue : string;
begin
Result := '';
if Value = '' then exit;
NValue := '';
for I := 0 to (length(Value)-1) div 2 do
NValue := NValue + char(StrToInt('$' + copy(Value, I*2+1, 2)));
B := ord(NValue[1]);
F1 := 1; F2 := 2;
for I := 2 to length(NValue) do begin
T := F2;
inc(F2, F1);
F1 := T;
Result := Result + char(ord(NValue[I]) - (B*F2))
end;
end;
procedure StrToTStrings(const S : string; List : TStrings);
var
I: Integer;
begin
List.DelimitedText := S;
for I := 0 to List.Count - 1 do
List[I] := Trim(List[I]);
end;
{
Decodes a URL encoded string to a normal string
@param Encoded URL encoded string to convert
@return A decoded string
}
function URLDecode(const Encoded : string) : string;
var
I : integer;
begin
Result := Encoded;
I := pos('%', Result);
while I <> 0 do begin
Result[I] := chr(StrToIntDef('$' + copy(Result, I+1, 2), 32));
Delete(Result, I+1, 2);
I := pos('%', Result);
end;
end;
// URLDecodeUTF8Impl adapted from http://koti.mbnet.fi/akini/delphi/urldecodeutf8/
function URLDecodeUTF8Impl(const s: PAnsiChar; const buf: PWideChar;
var lenBuf: Cardinal): boolean; stdcall;
var
sAnsi: ANSIString; // normal ansi string
sUtf8: UTF8String; // utf8-bytes string
sWide: WideString; // unicode string
i: Integer;
len: Cardinal;
CharCode: Cardinal;
begin
sAnsi := s; // null-terminated str to pascal str
SetLength(sUtf8, Length(sAnsi));
// Convert URLEncoded str to utf8 str, it must
// use utf8 hex escaping for non us-ascii chars
// + = space
// %2A = *
// %C3%84 = Ä (A with diaeresis)
i := 1;
len := 1;
while (i <= Length(sAnsi)) do
begin
if (sAnsi[i] <> '%') then
begin
if (sAnsi[i] = '+')
then sUtf8[len] := ' '
else sUtf8[len] := sAnsi[i];
Inc(len);
end else
begin
Inc(i); // skip the % char
try
CharCode := StrToInt('$' + Copy(string(sAnsi), i, 2));
sUtf8[len] := AnsiChar(CharCode);
Inc(len);
except
end;
Inc(i); // skip ESC, another +1 at end of loop
end;
Inc(i);
end;
Dec(len); // -1 to fix length (num of characters)
SetLength(sUtf8, len);
sWide := UTF8ToWideString(sUtf8); // utf8 string to unicode
len := Length(sWide);
if Assigned(buf) and (len < lenBuf) then
begin
// copy result into the buffer, buffer must have
// space for last null byte.
// lenBuf=num of chars in buffer, not counting null
if (len > 0)
then Move(sWide[1], buf^, (len+1) * SizeOf(WideChar));
lenBuf := len;
Result := True;
end else
begin
// tell calling program how big the buffer
// should be to store all decoded characters,
// including trailing null value.
if (len > 0)
then lenBuf := len+1;
Result := False;
end;
end;
function URLDecodeUTF8(const Encoded: string): string;
var
LBuffer: array [0..2048] of WideChar;
LBufferLength: Cardinal;
begin
LBufferLength := Length(LBuffer);
URLDecodeUTF8Impl(PAnsiChar(AnsiString(Encoded)), LBuffer, LBufferLength);
Result := LBuffer;
end;
{
Encodes a string to fit in URL encoding form
@param Decoded Normal string to convert
@return An URL encoded string
}
function URLEncode(const Decoded : string) : string;
const
Allowed = ['A'..'Z','a'..'z', '*', '@', '.', '_', '-', '0'..'9', '$', '!', '''', '(', ')'];
var
I : integer;
begin
Result := '';
for I := 1 to length(Decoded) do
if CharInSet(Decoded[I], Allowed) then
Result := Result + Decoded[I]
else
Result := Result + '%' + IntToHex(ord(Decoded[I]), 2);
end;
function FormatByteSize(const AByteSize: Longint): string;
const
B = 1;
KB = 1024 * B;
MB = 1024 * KB;
GB = 1024 * MB;
begin
if AByteSize > GB then
Result := FormatFloat('#.## GBs', AByteSize / GB)
else if AByteSize > MB then
Result := FormatFloat(',#.## MBs', AByteSize / MB)
else if AByteSize > KB then
Result := FormatFloat(',#.## KBs', AByteSize / KB)
else
Result := FormatFloat(',# bytes', AByteSize);
end;
function RemoveLastJSTerminator(const AJSCode: string): string;
begin
Result := AJSCode;
while EndsStr(sLineBreak, Result) do
Result := Copy(Result, 1, Length(Result) - Length(sLineBreak));
if (Result <> '') and (Result[Length(Result)] = ';') then
Delete(Result, Length(Result), 1);
end;
function Join(const AStrings: TStringDynArray; const ASeparator: string): string;
var
LString: string;
begin
Result := '';
for LString in AStrings do
begin
if Result = '' then
Result := LString
else
Result := Result + ASeparator + LString;
end;
end;
{$IF CompilerVersion < 33}
function Join(const AStrings: TArray<string>; const ASeparator: string): string;
var
LString: string;
begin
Result := '';
for LString in AStrings do
begin
if Result = '' then
Result := LString
else
Result := Result + ASeparator + LString;
end;
end;
{$ENDIF}
end.
|
{: Procedural Texture Demo / Tobias Peirick }
unit Unit1;
interface
uses
SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, GLScene, GLObjects, GLTexture, GLHUDObjects,
GLCadencer, GLLCLViewer, GLProcTextures, Spin, GLCoordinates,
GLCrossPlatform, GLBaseClasses;
type
TForm1 = class(TForm)
GLSceneViewer1: TGLSceneViewer;
GLScene1: TGLScene;
GLCamera1: TGLCamera;
Panel1: TPanel;
Label1: TLabel;
CBFormat: TComboBox;
Label2: TLabel;
Label3: TLabel;
CBCompression: TComboBox;
Label5: TLabel;
RBDefault: TRadioButton;
RBDouble: TRadioButton;
LAUsedMemory: TLabel;
RBQuad: TRadioButton;
LARGB32: TLabel;
LACompression: TLabel;
GLCadencer1: TGLCadencer;
CheckBox1: TCheckBox;
Label4: TLabel;
SpinEdit1: TSpinEdit;
SpinEdit2: TSpinEdit;
Label6: TLabel;
CheckBox2: TCheckBox;
GLPlane1: TGLPlane;
procedure GLSceneViewer1AfterRender(Sender: TObject);
procedure CBFormatChange(Sender: TObject);
procedure GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: double);
private
{ Déclarations privées }
public
{ Déclarations publiques }
newSelection: boolean;
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
uses GLTextureFormat;
procedure TForm1.GLSceneViewer1AfterRender(Sender: TObject);
var
rgb: integer;
begin
// update compression stats, only the 1st time after a new selection
if newSelection then
with GLPlane1.Material.Texture do
begin
rgb := Image.Width * Image.Height * 4;
LARGB32.Caption := Format('RGBA 32bits would require %d kB', [rgb div 1024]);
LAUsedMemory.Caption := Format('Required memory : %d kB',
[TextureImageRequiredMemory div 1024]);
LACompression.Caption := Format('Compression ratio : %d %%',
[100 - 100 * TextureImageRequiredMemory div rgb]);
newSelection := False;
end;
end;
procedure TForm1.CBFormatChange(Sender: TObject);
begin
// adjust settings from selection and reload the texture map
with GLPlane1.Material.Texture do
begin
TextureFormat := TGLTextureFormat(integer(tfRGB) + CBFormat.ItemIndex);
Compression := TGLTextureCompression(integer(tcNone) + CBCompression.ItemIndex);
TGLProcTextureNoise(Image).MinCut := SpinEdit1.Value;
TGLProcTextureNoise(Image).NoiseSharpness := SpinEdit2.Value / 100;
TGLProcTextureNoise(Image).Seamless := CheckBox2.Checked;
if RBDefault.Checked then
begin
GLPlane1.Width := 50;
GLPlane1.Height := 50;
end
else if RBDouble.Checked then
begin
GLPlane1.Width := 100;
GLPlane1.Height := 100;
end
else
begin
GLPlane1.Width := 400;
GLPlane1.Height := 400;
end;
end;
newSelection := True;
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double);
begin
if CheckBox1.Checked then
TGLProcTextureNoise(GLPlane1.Material.Texture.Image).NoiseAnimate(deltaTime);
end;
end.
|
unit uFrameBaseGrid;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxEdit, DB, cxDBData, cxGridLevel, cxClasses, cxControls,
cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridBandedTableView, cxGridDBBandedTableView, cxGrid, ADODB,
ActnList, dxBar, dxPSGlbl,
dxPSUtl, dxPSEngn, dxPrnPg, dxBkgnd, dxWrap, dxPrnDev, dxPSCompsProvider,
dxPSFillPatterns, dxPSEdgePatterns, dxPgsDlg, dxPrnDlg, dxPSCore,
dxPScxCommon, dxPScxGrid6Lnk, cxPropertiesStore, StdCtrls, ExtCtrls,
dxStatusBar, cxContainer, cxLabel, uDlgFind, uParams, uObjectActionsRightHelp,
cxTableViewCds, uCashDataSource, cxtCustomDataSource,
cxtCustomDataSourceM, cxGridDBDataDefinitions;
type
TFrameBaseGrid = class(TFrame)
DataSource: TDataSource;
Query: TADOQuery;
Grid: TcxGrid;
View: TcxGridDBBandedTableView;
GridLevel: TcxGridLevel;
ActionListGrid: TActionList;
actInsert: TAction;
actEdit: TAction;
actDelete: TAction;
BarManagerGrid: TdxBarManager;
bbInsert: TdxBarButton;
bbUpdate: TdxBarButton;
bbDelete: TdxBarButton;
PopupMenuGrid: TdxBarPopupMenu;
DockControlGridToolBar: TdxBarDockControl;
BarManagerGridToolMainBar: TdxBar;
actRefreshAll: TAction;
actRefreshCur: TAction;
bbRefreshAll: TdxBarButton;
bbRefreshCur: TdxBarButton;
actExportGridToExcel: TAction;
SDExcel: TSaveDialog;
bbExportExcel: TdxBarButton;
actHistory: TAction;
actHistoryDelete: TAction;
bsiHistory: TdxBarSubItem;
bbHistory: TdxBarButton;
actMarkRecord: TAction;
actUnMarkRecord: TAction;
actMarkInverse: TAction;
actMarkAll: TAction;
actUnMarkAll: TAction;
bsiMark: TdxBarSubItem;
bbMarkRecord: TdxBarButton;
bbUnMarkRecord: TdxBarButton;
bbMarkInverse: TdxBarButton;
bbMarkAll: TdxBarButton;
bbUnMarkAll: TdxBarButton;
bbPrint: TdxBarButton;
dxPrinter: TdxComponentPrinter;
dxPrintStyleManager: TdxPrintStyleManager;
dxPrintDialog: TdxPrintDialog;
dxPageSetupDialog: TdxPageSetupDialog;
dxPSEngineController: TdxPSEngineController;
dxGridPrinterLink: TdxGridReportLink;
bbSaveGridView: TdxBarButton;
bbRestoreGridView: TdxBarButton;
bbPropertys: TdxBarSubItem;
bbSummary: TdxBarButton;
TimerRecCount: TTimer;
pnlRecCount: TPanel;
bbReportMenu: TdxBarSubItem;
actFind: TAction;
bbFind: TdxBarButton;
actSaveGridView: TAction;
actSaveGridViewDefault: TAction;
bbSaveGridViewDefault: TdxBarButton;
actRestoreGridView: TAction;
actRestoreGridViewDefault: TAction;
bbRestoreGridViewDefault: TdxBarButton;
bsiGridView: TdxBarSubItem;
ViewCh: TcxGridBandedTableViewCds;
dsCh: TcxtCustomDataSourceM;
bisCopy: TdxBarButton;
procedure actInsertExecute(Sender: TObject);
procedure actEditExecute(Sender: TObject);
procedure actDeleteExecute(Sender: TObject);
procedure actRefreshCurExecute(Sender: TObject);
procedure actRefreshAllExecute(Sender: TObject);
procedure QueryAfterOpen(DataSet: TDataSet);
procedure actExportGridToExcelExecute(Sender: TObject);
procedure actEditUpdate(Sender: TObject);
procedure actHistoryExecute(Sender: TObject);
procedure actMarkRecordUpdate(Sender: TObject);
procedure actMarkRecordExecute(Sender: TObject);
procedure actUnMarkRecordExecute(Sender: TObject);
procedure actMarkInverseExecute(Sender: TObject);
procedure actMarkAllExecute(Sender: TObject);
procedure actUnMarkAllExecute(Sender: TObject);
procedure bbPrintClick(Sender: TObject);
procedure bbSummaryClick(Sender: TObject);
procedure TimerRecCountTimer(Sender: TObject);
procedure bbReportMenuPopup(Sender: TObject);
procedure actFindExecute(Sender: TObject);
procedure ViewFocusedItemChanged(Sender: TcxCustomGridTableView;
APrevFocusedItem, AFocusedItem: TcxCustomGridTableItem);
procedure actSaveGridViewExecute(Sender: TObject);
procedure actSaveGridViewDefaultExecute(Sender: TObject);
procedure actRestoreGridViewExecute(Sender: TObject);
procedure actRestoreGridViewDefaultExecute(Sender: TObject);
procedure dsChAfterOpen(Sender: TObject);
procedure ViewChFocusedItemChanged(Sender: TcxCustomGridTableView;
APrevFocusedItem, AFocusedItem: TcxCustomGridTableItem);
procedure ViewChDblClick(Sender: TObject);
procedure dsChBeforeOpen(Sender: TObject);
private
FOnInsert: TNotifyEvent;
FOnEdit: TNotifyEvent;
FOnDelete: TNotifyEvent;
FOnRefreshCurrentRec: TNotifyEvent;
FOnRefreshAllRec: TNotifyEvent;
FOnExportExcel: TNotifyEvent;
FOnOpenHistory: TNotifyEvent;
FShowExtendedProps: boolean;
{ Private declarations }
protected
dlgFind: TDlgFind;
function InternalObjectName(AForDelete: boolean = false): string; virtual; abstract;
function InternalDeleteStoredProcName: string; virtual;
procedure InternalInsertRec; virtual;
procedure InternalEditRec; virtual;
procedure InternalDeleteRec; virtual;
procedure InternalOpenData; virtual;
procedure InternalRefreshCurrentRec(UpdateFieldsData: boolean = true); virtual;
procedure InternalRefreshAllRec; virtual;
procedure InternalExportExcel; virtual;
procedure InternalOpenHistory; virtual;
procedure InternalViewKeyPress(Sender: TObject; var Key: Char); virtual;
//Ch
procedure InternalInsertRecCh; virtual;
procedure InternalEditRecCh; virtual;
procedure InternalDeleteRecCh; virtual;
procedure InternalOpenDataCh; virtual;
procedure InternalRefreshCurrentRecCh(UpdateFieldsData: boolean = true); virtual;
procedure InternalRefreshAllRecCh; virtual;
// procedure InternalExportExcelCh; virtual;
procedure InternalOpenHistoryCh; virtual;
procedure InternalViewKeyPressCh(Sender: TObject; var Key: Char); virtual;
procedure MarkFieldChange_AssignEventToColumn; virtual;
procedure ViewCellClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); virtual;
procedure MarkCurrentRecord(mark: boolean); virtual;
procedure MarkAllRecords(mark: boolean; Inverse: boolean = false); virtual;
//Ch
procedure MarkFieldChange_AssignEventToColumnCh; virtual;
procedure ViewCellClickCh(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); virtual;
procedure MarkCurrentRecordCh(mark: boolean); virtual;
procedure MarkAllRecordsCh(mark: boolean; Inverse: boolean = false); virtual;
procedure SetShowExtendedProps(const Value: boolean); virtual;
function GetShowExtendedProps: boolean; virtual;
procedure WMSize(var Mes: TMessage); message WM_SIZE;
procedure OnFindDialogClose(Sender: TObject; var Action: TCloseAction); virtual;
function CreateCurRecordValues: TParamCollection; virtual;
//Ch
function CreateCurRecordValuesCh: TParamCollection; virtual;
function ObjectIDForReportMenu: integer; virtual;
//26-05-2010 ivanov
function PKNameForReportMenu: string; virtual;
public
property OnInsert: TNotifyEvent read FOnInsert write FOnInsert;
property OnEdit: TNotifyEvent read FOnEdit write FOnEdit;
property OnDelete: TNotifyEvent read FOnDelete write FOnDelete;
property OnRefreshCurrentRec: TNotifyEvent read FOnRefreshCurrentRec write FOnRefreshCurrentRec;
property OnRefreshAllRec: TNotifyEvent read FOnRefreshAllRec write FOnRefreshAllRec;
property OnExportExcel: TNotifyEvent read FOnExportExcel write FOnExportExcel;
property OnOpenHistory: TNotifyEvent read FOnOpenHistory write FOnOpenHistory;
property ShowExtendedProps: boolean read GetShowExtendedProps write SetShowExtendedProps;
procedure InsertRec; virtual;
procedure EditRec; virtual;
procedure DeleteRec; virtual;
procedure OpenData; virtual;
procedure RefreshCurrentRec; virtual;
procedure RefreshAllRec; virtual;
procedure ExportExcel; virtual;
procedure OpenHistory; virtual;
function CurRecItemValue(ItemName: string): variant; virtual;
function CurRecPKValue: variant; virtual;
{сохранение/восстановление вида:
Для сохранения грида - вызвать StoreGrid, при этом будет инициирован вызов ApplyViewName,
для формирования имени представления (view). Тоже самое - при восстановлении - RestoryGrid.
Сохраняются и восстанавливаются все view на текущей форме}
procedure GetUniqueGridMetric(var AViewFormPlace: Cardinal; var AObjectId: integer; var APath: string); virtual;
procedure ApplyViewName(AView: TcxGridTableView; var AViewName: string); virtual;
// procedure ApplyViewName(AView: TcxGridDBBandedTableView; var AViewName: string); virtual;
function IsExtPropertyExists: boolean; virtual;
procedure SetExtPropertyVisible(AVisible: boolean); virtual;
procedure StoreGrid(DefObjectID: integer = -1; IsDefaultView: boolean = false); virtual;
procedure RestoryGrid(DefObjectID: integer = -1; IsDefaultView: boolean = false); virtual;
procedure OnReportsMenuClick(Sender: TObject); virtual;
//zav
function GetSelectedRecordsAsString:string;
//end zav
procedure LocateByIDCh(ID: integer); virtual;
procedure ShowGroupSummary(AVisible: boolean); virtual;
procedure ShowGroupSummaryByColProperty(AVisible: boolean);
constructor Create(AOwner: TComponent); override;
end;
TViewSelectedRecordsItem = record
PrimaryKeyValue: integer;
//29-07-2009
UEKeyValue: integer;
//^^^29-07-2009
RecordIndex: integer;
end;
TViewSelectedRecords = class
private
function GetCount: integer;
function GetItems(Index: integer): TViewSelectedRecordsItem;
protected
FItems: array of TViewSelectedRecordsItem;
function GetPKColumnIndex(View: TcxGridDBBandedTableView; PKFieldName: string = ''): integer; overload;
function GetPKColumnIndex(View: TcxGridBandedTableViewCds; PKFieldName: string = ''): integer; overload;
//29-07-2009
function GetUEColumnIndex(View: TcxGridBandedTableViewCds): integer; virtual;
//^^^29-07-2009
public
property Count: integer read GetCount;
property Items[Index: integer]: TViewSelectedRecordsItem read GetItems; default;
procedure CopyFrom(ViewSelectedRecords: TViewSelectedRecords);
function AsString: string;
//29-07-2009
function UEAsString: string;
//^^^29-07-2009
constructor Create(View: TcxGridDBBandedTableView; PKFieldName: string = ''); overload; virtual;
constructor Create(View: TcxGridBandedTableViewCds; PKFieldName: string = ''); overload; virtual;
constructor Create(); overload; virtual;
end;
implementation
uses uMain, cxGridExportLink, ShellAPI, uAccess, uFrmHistory, cxCheckBox,
uCommonUtils, uBASE_Form, cxGridDBTableView, cxCurrencyEdit, ufReports_Objects,
ufReports_ShowReport, uException, uFrameGrid,
//22-07-2009
cxSpinEdit,
//^^^22-07-2009
//25-07-2009
ComObj;
//^^^25-07-2009
const
GET_GRID_PROPERTY = 'SELECT [Настройка], [ИтогиПоГруппам], [СвойстваУчетнойЕдиницы] FROM [sys_Настройки вида] WHERE (код_Объект=%d) and '+
'([Положение формы]=%u) and ([Имя формы]=''%s'') and ([Пользователь] = CURRENT_USER)';
GET_GRID_PROPERTY_DEFAULT = 'SELECT [Настройка], [ИтогиПоГруппам], [СвойстваУчетнойЕдиницы] FROM [sys_Настройки вида] WHERE (код_Объект=%d) and '+
'([Положение формы]=%u) and ([Имя формы]=''%s'') and ([По умолчанию] = 1)';
NEW_GRID_PROPERTY = 'INSERT INTO [sys_Настройки вида] (код_Объект, [Имя формы],[Пользователь], [Положение формы]) '+
' VALUES(%d,''%s'', CURRENT_USER, %u)';
NEW_GRID_PROPERTY_DEFAULT = 'INSERT INTO [sys_Настройки вида] (код_Объект, [Имя формы], [Положение формы], [По умолчанию]) '+
' VALUES(%d,''%s'', %u, 1)';
{константы полинома для crc32 (автора не сохранил)}
TableCrc32: array[0..255] of DWORD =
($00000000, $77073096, $EE0E612C, $990951BA,
$076DC419, $706AF48F, $E963A535, $9E6495A3,
$0EDB8832, $79DCB8A4, $E0D5E91E, $97D2D988,
$09B64C2B, $7EB17CBD, $E7B82D07, $90BF1D91,
$1DB71064, $6AB020F2, $F3B97148, $84BE41DE,
$1ADAD47D, $6DDDE4EB, $F4D4B551, $83D385C7,
$136C9856, $646BA8C0, $FD62F97A, $8A65C9EC,
$14015C4F, $63066CD9, $FA0F3D63, $8D080DF5,
$3B6E20C8, $4C69105E, $D56041E4, $A2677172,
$3C03E4D1, $4B04D447, $D20D85FD, $A50AB56B,
$35B5A8FA, $42B2986C, $DBBBC9D6, $ACBCF940,
$32D86CE3, $45DF5C75, $DCD60DCF, $ABD13D59,
$26D930AC, $51DE003A, $C8D75180, $BFD06116,
$21B4F4B5, $56B3C423, $CFBA9599, $B8BDA50F,
$2802B89E, $5F058808, $C60CD9B2, $B10BE924,
$2F6F7C87, $58684C11, $C1611DAB, $B6662D3D,
$76DC4190, $01DB7106, $98D220BC, $EFD5102A,
$71B18589, $06B6B51F, $9FBFE4A5, $E8B8D433,
$7807C9A2, $0F00F934, $9609A88E, $E10E9818,
$7F6A0DBB, $086D3D2D, $91646C97, $E6635C01,
$6B6B51F4, $1C6C6162, $856530D8, $F262004E,
$6C0695ED, $1B01A57B, $8208F4C1, $F50FC457,
$65B0D9C6, $12B7E950, $8BBEB8EA, $FCB9887C,
$62DD1DDF, $15DA2D49, $8CD37CF3, $FBD44C65,
$4DB26158, $3AB551CE, $A3BC0074, $D4BB30E2,
$4ADFA541, $3DD895D7, $A4D1C46D, $D3D6F4FB,
$4369E96A, $346ED9FC, $AD678846, $DA60B8D0,
$44042D73, $33031DE5, $AA0A4C5F, $DD0D7CC9,
$5005713C, $270241AA, $BE0B1010, $C90C2086,
$5768B525, $206F85B3, $B966D409, $CE61E49F,
$5EDEF90E, $29D9C998, $B0D09822, $C7D7A8B4,
$59B33D17, $2EB40D81, $B7BD5C3B, $C0BA6CAD,
$EDB88320, $9ABFB3B6, $03B6E20C, $74B1D29A,
$EAD54739, $9DD277AF, $04DB2615, $73DC1683,
$E3630B12, $94643B84, $0D6D6A3E, $7A6A5AA8,
$E40ECF0B, $9309FF9D, $0A00AE27, $7D079EB1,
$F00F9344, $8708A3D2, $1E01F268, $6906C2FE,
$F762575D, $806567CB, $196C3671, $6E6B06E7,
$FED41B76, $89D32BE0, $10DA7A5A, $67DD4ACC,
$F9B9DF6F, $8EBEEFF9, $17B7BE43, $60B08ED5,
$D6D6A3E8, $A1D1937E, $38D8C2C4, $4FDFF252,
$D1BB67F1, $A6BC5767, $3FB506DD, $48B2364B,
$D80D2BDA, $AF0A1B4C, $36034AF6, $41047A60,
$DF60EFC3, $A867DF55, $316E8EEF, $4669BE79,
$CB61B38C, $BC66831A, $256FD2A0, $5268E236,
$CC0C7795, $BB0B4703, $220216B9, $5505262F,
$C5BA3BBE, $B2BD0B28, $2BB45A92, $5CB36A04,
$C2D7FFA7, $B5D0CF31, $2CD99E8B, $5BDEAE1D,
$9B64C2B0, $EC63F226, $756AA39C, $026D930A,
$9C0906A9, $EB0E363F, $72076785, $05005713,
$95BF4A82, $E2B87A14, $7BB12BAE, $0CB61B38,
$92D28E9B, $E5D5BE0D, $7CDCEFB7, $0BDBDF21,
$86D3D2D4, $F1D4E242, $68DDB3F8, $1FDA836E,
$81BE16CD, $F6B9265B, $6FB077E1, $18B74777,
$88085AE6, $FF0F6A70, $66063BCA, $11010B5C,
$8F659EFF, $F862AE69, $616BFFD3, $166CCF45,
$A00AE278, $D70DD2EE, $4E048354, $3903B3C2,
$A7672661, $D06016F7, $4969474D, $3E6E77DB,
$AED16A4A, $D9D65ADC, $40DF0B66, $37D83BF0,
$A9BCAE53, $DEBB9EC5, $47B2CF7F, $30B5FFE9,
$BDBDF21C, $CABAC28A, $53B39330, $24B4A3A6,
$BAD03605, $CDD70693, $54DE5729, $23D967BF,
$B3667A2E, $C4614AB8, $5D681B02, $2A6F2B94,
$B40BBE37, $C30C8EA1, $5A05DF1B, $2D02EF8D);
{$R *.dfm}
procedure CalcCRC32(p: string; var CRCValue: DWORD);
var
i: DWORD;
begin
{ TODO : Сделать совместимым с unicode!!! }
CRCvalue := $FFFFFFFF;
for i := 1 to Length(p) - 1 do
CRCvalue := (CRCvalue shr 8) xor TableCrc32[(ord(p[i]) xor CRCvalue) and $000000FF];
CRCvalue := CRCvalue xor $FFFFFFFF;
end;
function FindBaseForm(AParent: TWinControl): TBASE_Form;
var
iter: integer;
prt: TWinControl;
begin
prt:= AParent;
iter:= 0;
while prt <> nil do begin
if prt is TBASE_Form then begin
result:= prt as TBASE_Form;
exit;
end;
prt:= prt.Parent;
inc(iter);
if iter > 100 then begin
result:= nil;
exit;
end;
end;
result:= nil;
end;
function GetOwnerForm(AParent: TWinControl): TBASE_Form;
var
iter: integer;
prt: TWinControl;
begin
prt:= AParent;
iter:= 0;
while prt <> nil do begin
if prt is TBASE_Form then begin
result:= prt as TBASE_Form;
exit;
end;
prt:= prt.Parent;
inc(iter);
if iter > 100 then begin
result:= nil;
exit;
end;
end;
result:= nil;
end;
procedure TFrameBaseGrid.actInsertExecute(Sender: TObject);
begin
InsertRec;
end;
procedure TFrameBaseGrid.actEditExecute(Sender: TObject);
begin
EditRec;
end;
procedure TFrameBaseGrid.actDeleteExecute(Sender: TObject);
begin
DeleteRec;
end;
procedure TFrameBaseGrid.OpenData;
begin
//abstract;
end;
procedure TFrameBaseGrid.DeleteRec;
begin
if Assigned(OnDelete) then
OnDelete(self)
else begin
if GridLevel.GridView=View then
InternalDeleteRec
else if GridLevel.GridView=ViewCh then
InternalDeleteRecCh;
end;
end;
procedure TFrameBaseGrid.EditRec;
begin
if Assigned(OnEdit) then
OnEdit(self)
else begin
InternalEditRec;
end;
end;
procedure TFrameBaseGrid.InsertRec;
begin
if Assigned(OnInsert) then
OnInsert(self)
else begin
InternalInsertRec;
end;
end;
procedure TFrameBaseGrid.RefreshCurrentRec;
begin
if Assigned(OnRefreshCurrentRec) then
OnRefreshCurrentRec(self)
else begin
if GridLevel.GridView=View then
InternalRefreshCurrentRec
else
InternalRefreshCurrentRecCh;
end;
end;
procedure TFrameBaseGrid.actRefreshCurExecute(Sender: TObject);
begin
RefreshCurrentRec;
end;
procedure TFrameBaseGrid.RefreshAllRec;
begin
if Assigned(OnRefreshAllRec) then
OnRefreshAllRec(self)
else
InternalRefreshAllRec;
end;
procedure TFrameBaseGrid.actRefreshAllExecute(Sender: TObject);
begin
RefreshAllRec;
end;
procedure TFrameBaseGrid.InternalDeleteRec;
var
sr: TViewSelectedRecords;
sp: TADOStoredProc;
i: integer;
st: string;
begin
sr:=TViewSelectedRecords.Create(View);
try
st:='Удалить количество записей: '+IntToStr(sr.Count)+'?';
if MessageBox(Application.Handle, pchar(st), 'Удаление', MB_YESNO or MB_ICONQUESTION or MB_APPLMODAL) <> IDYES then exit;
view.BeginUpdate;
try
sp:=TADOStoredProc.Create(nil);
sp.Connection:=frmMain.ADOConnection;
if InternalDeleteStoredProcName='' then
sp.ProcedureName:=format('sp_а_%s_удалить', [InternalObjectName(true)])
else
sp.ProcedureName:=InternalDeleteStoredProcName;
sp.Parameters.Refresh;
sp.Parameters[1].Value:=sr.AsString;
frmMain.ADOConnection.BeginTrans;
try
sp.ExecProc;
frmMain.ADOConnection.CommitTrans;
for i:=sr.Count-1 downto 0 do
View.DataController.DeleteRecord(sr.Items[i].RecordIndex);
except
frmMain.ADOConnection.RollbackTrans;
raise;
end;
finally
view.EndUpdate;
end;
finally
sr.Free;
end;
end;
procedure TFrameBaseGrid.InternalEditRec;
begin
//abstract
end;
procedure TFrameBaseGrid.InternalInsertRec;
begin
//abstract
end;
procedure TFrameBaseGrid.InternalOpenData;
begin
//abstract
end;
procedure TFrameBaseGrid.InternalRefreshAllRec;
begin
InternalRefreshAll(Query);
end;
procedure TFrameBaseGrid.InternalRefreshCurrentRec(UpdateFieldsData: boolean = true);
begin
InternalRefreshCurrent(Query, self.InternalObjectName, View);
end;
procedure TFrameBaseGrid.QueryAfterOpen(DataSet: TDataSet);
begin
// View.DataController.KeyFieldNames:=DataSet.Fields[0].DisplayName;
end;
procedure TFrameBaseGrid.ExportExcel;
begin
if Assigned(OnExportExcel) then
OnExportExcel(self)
else
InternalExportExcel;
end;
procedure TFrameBaseGrid.InternalExportExcel;
var
st: string;
begin
if not SDExcel.Execute then exit;
ExportGridToExcel(SDExcel.FileName, Grid);
st:='Открыть файл: '+SDExcel.FileName+' ?';
if MessageBox(Handle, pchar(st), 'Запрос', MB_YESNO or MB_ICONQUESTION or MB_APPLMODAL) = IDYES then
ShellExecute(0, 'open', pchar(SDExcel.FileName), nil, nil, SW_SHOWNORMAL);
end;
procedure TFrameBaseGrid.actExportGridToExcelExecute(Sender: TObject);
begin
ExportExcel;
end;
procedure TFrameBaseGrid.actEditUpdate(Sender: TObject);
var
ds: TDataSet;
begin
if GridLevel.GridView=View then
(Sender as TAction).Enabled:=view.ViewData.RecordCount>0
else if GridLevel.GridView=ViewCh then
(Sender as TAction).Enabled:=ViewCh.ViewData.RecordCount>0
// ds:=View.DataController.DataSource.DataSet;
// (Sender as TAction).Enabled:=ds.Active and (ds.RecordCount>0);
end;
procedure TFrameBaseGrid.InternalOpenHistory;
var
a: TAccessSelectorForm;
p: TParamCollection;
ds: TDataSet;
begin
a:=TAccessSelectorForm.Create;
try
a.ObjectID:=434;
// a.FormClass:=TfrmHistory;
p:=TParamCollection.Create(TParamItem);
try
ds:=View.DataController.DataSource.DataSet;
p.Add('код_Объект').Value:=ds['вк_НастоящийОбъектВладелец'];
p.Add('код_Записи').Value:=ds[ds.Fields[0].DisplayName];
a.ShowModal(p, null);
finally
p.Free;
end;
finally
a.Free;
end;
end;
procedure TFrameBaseGrid.OpenHistory;
begin
if Assigned(OnOpenHistory) then
OnOpenHistory(self)
else begin
if GridLevel.GridView=View then
InternalOpenHistory
else
InternalOpenHistoryCh;
end;
end;
function TFrameBaseGrid.PKNameForReportMenu: string;
begin
result:='';
end;
procedure TFrameBaseGrid.actHistoryExecute(Sender: TObject);
begin
OpenHistory;
end;
procedure TFrameBaseGrid.actMarkRecordUpdate(Sender: TObject);
begin
if GridLevel.GridView=View then
(Sender as TAction).Enabled:=view.ViewData.RecordCount>0
else if GridLevel.GridView=ViewCh then
(Sender as TAction).Enabled:=ViewCh.ViewData.RecordCount>0
end;
procedure TFrameBaseGrid.MarkAllRecords(mark: boolean; Inverse: boolean = false);
var
ds: TDataSet;
f: TField;
BeforePost: TDataSetNotifyEvent;
i: integer;
BM: TBookmarkStr;
id: integer;
rec_index: integer;
rec: TcxCustomGridRecord;
//zav
RIdx:Integer;
fldName:string;
ItemIdx:INteger;
clm:TcxGridColumn;
sRefresh:boolean;
//end zav
begin
ScreenCursor.IncCursor;
ItemIdx := 1;
sRefresh := View.DataController.DataModeController.SmartRefresh;
View.DataController.DataModeController.SmartRefresh := true;
try
if View.DataController.DataModeController.GridMode then
View.DataController.DataModeController.GridMode:=false;
ds:=View.DataController.DataSource.DataSet;
f:=ds.FieldByName('ForADOInsertCol');
//zav
for I := 0 to View.ItemCount - 1 do begin
fldName := '';
if View.Items[i] .DataBinding is TcxGridItemDBDataBinding then
fldName := TcxGridItemDBDataBinding( View.Items[i] .DataBinding ).FieldName;
if AnsiCompareText('ForADOInsertCol', fldName) = 0 then begin
ItemIdx := View.Items[i].Index;
break;
end;
end;
//end zav
//clm.i
if not Assigned(f) then exit;
BeforePost:=ds.BeforePost;
BM:=ds.Bookmark;
ds.BeforePost:=nil;
View.BeginUpdate;
// View.DataController.BeginLocate;
try
//zav
// for i:=0 to View.ViewData.RecordCount-1 do begin
for i:=0 to View.DataController.FilteredRecordCount-1 do begin
//end zav
rec:=View.ViewData.Records[i];
id:=rec.Values[0];
// ds.Locate(ds.Fields[0].DisplayName, id, []);
// ds.Edit;
//zav
RIdx := View.DataController.FilteredRecordIndex[i];
if Inverse then begin
// f.Value:=not f.Value;
//zav
//rec.Values[1]:= not rec.Values[1];
View.DataController.Values[RIdx, ItemIdx] := not View.DataController.Values[RIdx, ItemIdx] ;
//end zav
end
else begin
// f.Value:=mark;
//zav
View.DataController.Values[RIdx, ItemIdx] := mark;
//rec.Values[1]:=mark;
//end zav
end;
// ds.Post;
end;
{ for i:=0 to View.ViewData.RowCount-1 do begin
id:=View.ViewData.Rows[i].Values[0];
// View.DataController.LocateByKey(id);
ds.Locate(ds.Fields[0].DisplayName, id, []);
ds.Edit;
if Inverse then begin
f.Value:=not f.Value;
View.ViewData.Rows[i].Values[1]:= not View.ViewData.Rows[i].Values[1];
end
else begin
f.Value:=mark;
View.ViewData.Rows[i].Values[1]:=mark;
end;
ds.Post;
end;}
finally
View.EndUpdate;
ds.Bookmark:=BM;
// View.DataController.EndLocate;
ds.BeforePost:=BeforePost;
end;
finally
View.DataController.DataModeController.SmartRefresh := sRefresh;
ScreenCursor.DecCursor;
end;
end;
procedure TFrameBaseGrid.MarkCurrentRecord(mark: boolean);
var
ds: TDataSet;
f: TField;
BeforePost: TDataSetNotifyEvent;
rec: TcxCustomGridRecord;
begin
// View.DataController.FocusedRecordIndex
if View.DataController.DataModeController.GridMode then
View.DataController.DataModeController.GridMode:=false;
ds:=View.DataController.DataSource.DataSet;
ds.BeforePost:=nil;
// ds.Edit;
// ds['ForAdoInsertCol']:=mark;
// ds.Post;
View.DataController.Values[View.DataController.FocusedRecordIndex, 1]:=mark;
ds.BeforePost:=BeforePost;
{ rec:=View
ds:=View.DataController.DataSource.DataSet;
f:=ds.FieldByName('ForADOInsertCol');
if not Assigned(f) then exit;
BeforePost:=ds.BeforePost;
ds.Edit;
f.Value:=mark;
ds.Post;}
{ ds:=View.DataController.DataSource.DataSet;
f:=ds.FieldByName('ForADOInsertCol');
if not Assigned(f) then exit;
BeforePost:=ds.BeforePost;
ds.BeforePost:=nil;
ds.Edit;
f.Value:=mark;
ds.Post;
ds.BeforePost:=BeforePost;}
end;
procedure TFrameBaseGrid.actMarkRecordExecute(Sender: TObject);
begin
if (GridLevel.GridView=View) or (GridLevel.GridView.Name='ViewCds') then // ViewCds - потому что начали перходи на андрея в модуле uFrameObjectByProps
MarkCurrentRecord(true)
else
if GridLevel.GridView=ViewCh then
MarkCurrentRecordCh(true);
end;
procedure TFrameBaseGrid.actUnMarkRecordExecute(Sender: TObject);
begin
if (GridLevel.GridView=View) or (GridLevel.GridView.Name='ViewCds') then
MarkCurrentRecord(false)
else
if GridLevel.GridView=ViewCh then
MarkCurrentRecordCh(false)
end;
procedure TFrameBaseGrid.actMarkInverseExecute(Sender: TObject);
begin
if (GridLevel.GridView=View) or (GridLevel.GridView.Name='ViewCds') then
MarkAllRecords(false, true)
else
if GridLevel.GridView=ViewCh then
MarkAllRecordsCh(false, true)
end;
procedure TFrameBaseGrid.actMarkAllExecute(Sender: TObject);
begin
if (GridLevel.GridView=View) or (GridLevel.GridView.Name='ViewCds') then
MarkAllRecords(true)
else
if GridLevel.GridView=ViewCh then
MarkAllRecordsCh(true)
end;
procedure TFrameBaseGrid.actUnMarkAllExecute(Sender: TObject);
begin
if (GridLevel.GridView=View) or (GridLevel.GridView.Name='ViewCds') then
MarkAllRecords(false)
else
if GridLevel.GridView=ViewCh then
MarkAllRecordsCh(false)
end;
procedure TFrameBaseGrid.MarkFieldChange_AssignEventToColumn;
var
i: integer;
begin
for i:=0 to View.ColumnCount-1 do
if View.Columns[i].DataBinding.FieldName='ForADOInsertCol' then begin
View.Columns[i].Options.ShowEditButtons:=isebAlways;
View.Columns[i].Caption:='';
View.Columns[i].PropertiesClass:=TcxCheckBoxProperties;
View.Columns[i].Options.Editing:=false;
View.Columns[i].Options.ShowEditButtons:=isebAlways;
View.OnCellClick:=ViewCellClick;
// (View.Columns[i].Properties as TcxCheckBoxProperties).OnChange:=MarkFieldChange;
// (View.Columns[i].Properties as TcxCheckBoxProperties).OnEditValueChanged:=MarkFieldChange;
exit;
end;
end;
{ TViewSelectedRecords }
function TViewSelectedRecords.AsString: string;
var
i: integer;
begin
result:='';
for i:=0 to Count-1 do
result:=result+IntToStr(Items[i].PrimaryKeyValue)+',';
delete(result, length(result), 1);
end;
procedure TViewSelectedRecords.CopyFrom(ViewSelectedRecords: TViewSelectedRecords);
var
i: integer;
begin
for i:=0 to ViewSelectedRecords.Count-1 do begin
SetLength(FItems, Count+1);
FItems[Count-1].PrimaryKeyValue:=ViewSelectedRecords.Items[i].PrimaryKeyValue;
//29-07-2009
FItems[Count-1].UEKeyValue:=ViewSelectedRecords.Items[i].UEKeyValue;
//^^^29-07-2009
FItems[Count-1].RecordIndex:=ViewSelectedRecords.Items[i].RecordIndex;
end;
end;
constructor TViewSelectedRecords.Create(View: TcxGridDBBandedTableView; PKFieldName: string = '');
var
i: integer;
PKColIndex: integer;
begin
inherited Create;
if not Assigned(View) then exit;
PKColIndex:=GetPKColumnIndex(View, PKFieldName);
for i:=0 to View.DataController.RecordCount-1 do
//28-08-2009
if (not VarIsNullMy(View.DataController.Values[i, 1])) and (View.DataController.Values[i, 1]) then begin
//^^^28-08-2009
SetLength(FItems, Count+1);
FItems[Count-1].PrimaryKeyValue:=View.DataController.Values[i, PKColIndex];
FItems[Count-1].RecordIndex:=i;
end;
if (Count=0) and (View.DataController.RowCount>0) then begin
SetLength(FItems, 1);
FItems[0].PrimaryKeyValue:=View.Controller.FocusedRow.Values[PKColIndex];
FItems[0].RecordIndex:=View.Controller.FocusedRow.RecordIndex;
end;
end;
constructor TViewSelectedRecords.Create(View: TcxGridBandedTableViewCds;
PKFieldName: string);
var
i: integer;
PKColIndex: integer;
UEColIndex: integer;
begin
inherited Create;
if not Assigned(View) then exit;
PKColIndex:=GetPKColumnIndex(View, PKFieldName);
//29-07-2009
UEColIndex:=GetUEColumnIndex(View);
//^^^29-07-2009
for i:=0 to View.DataController.RecordCount-1 do
//28-08-2009
if (not VarIsNullMy(View.DataController.Values[i, 1])) and (View.DataController.Values[i, 1]) then begin
//^^^28-08-2009
SetLength(FItems, Count+1);
FItems[Count-1].PrimaryKeyValue:=View.DataController.Values[i, PKColIndex];
//29-07-2009
if UEColIndex<>-1 then
FItems[Count-1].UEKeyValue:=View.DataController.Values[i, UEColIndex];
//^^^29-07-2009
FItems[Count-1].RecordIndex:=i;
end;
if (Count=0) and (View.DataController.RowCount>0) then begin
SetLength(FItems, 1);
FItems[0].PrimaryKeyValue:=View.Controller.FocusedRow.Values[PKColIndex];
//29-07-2009
if UEColIndex<>-1 then
FItems[Count-1].UEKeyValue:=View.Controller.FocusedRow.Values[UEColIndex];
//^^^29-07-2009
FItems[0].RecordIndex:=View.Controller.FocusedRow.RecordIndex;
end;
end;
constructor TViewSelectedRecords.Create;
begin
inherited;
end;
function TViewSelectedRecords.GetCount: integer;
begin
result:=length(FItems);
end;
function TViewSelectedRecords.GetItems(Index: integer): TViewSelectedRecordsItem;
begin
result:=FItems[Index];
end;
function TViewSelectedRecords.GetPKColumnIndex(View: TcxGridDBBandedTableView; PKFieldName: string = ''): integer;
var
i: integer;
begin
result:=0;
if PKFieldName='' then exit;
PKFieldName:=AnsiLowerCase(PKFieldName);
for i:=0 to View.ColumnCount-1 do
if AnsiLowerCase(View.Columns[i].DataBinding.FieldName)=PKFieldName then begin
result:=i;
exit;
end;
end;
procedure TFrameBaseGrid.SetShowExtendedProps(const Value: boolean);
begin
FShowExtendedProps:=Value;
end;
constructor TFrameBaseGrid.Create(AOwner: TComponent);
begin
inherited;
FShowExtendedProps:=false;
dlgFind:=TdlgFind.Create(self);
dlgFind.Grid:=Grid;
dlgFind.OnClose:=self.OnFindDialogClose;
View.OnKeyPress:=self.InternalViewKeyPress;
end;
procedure TFrameBaseGrid.bbPrintClick(Sender: TObject);
begin
dxPrinter.Preview(true);
end;
procedure TFrameBaseGrid.ShowGroupSummaryByColProperty(AVisible: boolean);
var
i: integer;
sm: TcxGridDBTableSummaryItem;
begin
view.DataController.Summary.DefaultGroupSummaryItems.Clear;
//view.OptionsView.GroupFooters:= gfInvisible;
if AVisible then
for i:=0 to View.ColumnCount-1 do
if View.Columns[i].Properties is TcxCurrencyEditProperties then begin
sm:= view.DataController.Summary.DefaultGroupSummaryItems.Add as TcxGridDBTableSummaryItem;
sm.FieldName:= View.Columns[i].DataBinding.FieldName;
sm.Kind:= skSum;
sm.Format:= ',0.####';
sm.Column:= View.Columns[i];
end
//22-07-2009
else
if View.Columns[i].Properties is TcxSpinEditProperties then begin
sm:= view.DataController.Summary.DefaultGroupSummaryItems.Add as TcxGridDBTableSummaryItem;
sm.FieldName:= View.Columns[i].DataBinding.FieldName;
sm.Kind:= skSum;
sm.Format:= ',0';
sm.Column:= View.Columns[i];
end
//^^^22-07-2009
end;
procedure TFrameBaseGrid.bbSummaryClick(Sender: TObject);
begin
ShowGroupSummary(bbSummary.Down);
end;
function TFrameBaseGrid.GetShowExtendedProps: boolean;
begin
result:=false;
end;
procedure TFrameBaseGrid.TimerRecCountTimer(Sender: TObject);
//var
// sr: TViewSelectedRecords;
begin
if GridLevel.GridView=View then
pnlRecCount.Caption:=format('Записей: %d из %d', [View.DataController.FilteredRecordCount, View.DataController.RecordCount])
else
if GridLevel.GridView=ViewCh then
pnlRecCount.Caption:=format('Записей: %d из %d', [ViewCh.DataController.FilteredRecordCount, ViewCh.DataController.RecordCount]);
// sr:=TViewSelectedRecords.Create(View);
// pnlRecCount.Caption:=pnlRecCount.Caption+' '+IntToStr(sr.Count);
// sr.Free;
end;
procedure TFrameBaseGrid.WMSize(var Mes: TMessage);
begin
inherited;
pnlRecCount.Left:=190;
pnlRecCount.Top:=Height-17;
pnlRecCount.BringToFront;
end;
procedure TFrameBaseGrid.StoreGrid(DefObjectID: integer = -1; IsDefaultView: boolean = false);
var
i, ObjId: integer;
ViewPlace: Cardinal;
ViewName: string;
StoresFinded: boolean;
_Query: TADOQuery;
// _CurrentView: TcxGridDBBandedTableView;
_CurrentView: TcxGridTableView;
Blob: TADOBlobStream;
Path: string;
function GetPropertyRecord(): boolean;
begin
try
if IsDefaultView then
_Query.SQL.Text:=Format(GET_GRID_PROPERTY_DEFAULT, [ObjId, ViewPlace, ViewName])
else
_Query.SQL.Text:=Format(GET_GRID_PROPERTY, [ObjId, ViewPlace, ViewName]);
_Query.Open;
result:=_Query.RecordCount = 1;
except
result:=false;
end;
end;
begin
GetUniqueGridMetric(ViewPlace, ObjId, Path);
// ShowMessage(Path);
if DefObjectID<>-1 then begin
ObjId:=DefObjectID;
if DefObjectID = 163 then //0 - связано с учетной единице, т.к. она может показываться не на форме, а на другом паренте, что приводит к глюку, т.к. код другой получается
ViewPlace:=0; //нарно просто исключение лучше сделать для 163 кода (код УЕ), что и сделано
end;
if ObjId <= 0 then exit;
_Query:= TADOQuery.Create(self);
_Query.Connection:= Query.Connection;
_Query.LockType:= ltOptimistic;
_Query.CursorType:= ctKeyset;
_Query.ParamCheck:= false;
for i:=0 to ComponentCount-1 do
if Components[i] is TcxGridTableView then begin
_CurrentView:= Components[i] as TcxGridTableView;
if (ObjID=163) and (_CurrentView.Name='View') then continue;
ApplyViewName(_CurrentView, ViewName);
if ViewName = '' then continue;
// найдем настройку или создадим настройку, если еще не создана
if IsDefaultView then begin
if not GetPropertyRecord then begin
try
_Query.SQL.Text:= Format(NEW_GRID_PROPERTY_DEFAULT, [ObjId, ViewName, ViewPlace]);
_Query.ExecSQL;
StoresFinded:=GetPropertyRecord;
except
StoresFinded:=false;
end;
end
else
StoresFinded:=true;
end
else
if not GetPropertyRecord then begin
try
_Query.SQL.Text:= Format(NEW_GRID_PROPERTY, [ObjId, ViewName, ViewPlace]);
_Query.ExecSQL;
StoresFinded:= GetPropertyRecord;
except
StoresFinded:= false;
end;
end
else
StoresFinded:= true;
// сохраним состояние грида
Blob:= nil;
if StoresFinded then
try
_Query.Edit;
_Query['ИтогиПоГруппам']:= _CurrentView.DataController.Summary.DefaultGroupSummaryItems.Count>0;
_Query['СвойстваУчетнойЕдиницы']:= IsExtPropertyExists;
Blob:= _Query.CreateBlobStream(_Query.FieldByName('Настройка'), bmWrite) as TADOBlobStream;
_CurrentView.StoreToStream(Blob, [gsoUseFilter{, gsoUseSummary}]);
finally
try
if Blob <> nil then
Blob.Free;
_Query.Post;
except
end;
end;
end;
_Query.Free;
end;
procedure TFrameBaseGrid.RestoryGrid(DefObjectID: integer = -1; IsDefaultView: boolean = false);
var
i, ObjId: integer;
ViewName: string;
ViewPlace: Cardinal;
_Query: TADOQuery;
// _CurrentView: TcxGridDBBandedTableView;
_CurrentView: TcxGridTableView;
Blob: TStream;
Path: string;
begin
GetUniqueGridMetric(ViewPlace, ObjId, Path);
// ShowMessage(Path);
if DefObjectID<>-1 then begin
ObjId:=DefObjectID;
if DefObjectID = 163 then //0 - связано с учетной единице, т.к. она может показываться не на форме, а на другом паренте, что приводит к глюку, т.к. код другой получается
ViewPlace:=0; //нарно просто исключение лучше сделать для 163 кода (код УЕ), что и сделано
end;
if ObjId <= 0 then exit;
_Query:= TADOQuery.Create(self);
_Query.Connection:= Query.Connection;
_Query.LockType:= ltReadOnly;
_Query.CursorType:= ctOpenForwardOnly;
_Query.ParamCheck:= false;
// bbSaveGridView.Down:= false;
i:=0;
while i < ComponentCount do begin
if (Components[i] is TcxGridTableView) then begin
_CurrentView:= Components[i] as TcxGridTableView;
if (ObjId=163) and (_CurrentView.Name='View') then begin
inc(i);
continue;
end;
if _CurrentView.OptionsView.GroupSummaryLayout <> gslAlignWithColumns then
_CurrentView.OptionsView.GroupSummaryLayout:= gslAlignWithColumns;
ApplyViewName(_CurrentView, ViewName);
if ViewName = '' then continue;
Blob:= nil;
try
if IsDefaultView then begin
_Query.SQL.Text:= Format(GET_GRID_PROPERTY_DEFAULT, [ObjId, ViewPlace, ViewName]);
_Query.Open;
end
else begin
_Query.SQL.Text:= Format(GET_GRID_PROPERTY, [ObjId, ViewPlace, ViewName]);
_Query.Open;
if _Query.RecordCount=0 then begin
_Query.SQL.Text:= Format(GET_GRID_PROPERTY_DEFAULT, [ObjId, ViewPlace, ViewName]);
_Query.Open;
end;
end;
if _Query.RecordCount = 1 then begin
Blob:= _Query.CreateBlobStream(_Query.FieldByName('Настройка'), bmRead);
Blob.Position:=0;
if Blob.Size > 0 then begin
_CurrentView.RestoreFromStream( Blob, false, false, [gsoUseFilter{, gsoUseSummary}]);
end;
if (_CurrentView.Control as TcxCustomGrid).Views[0] = _CurrentView then begin
ShowGroupSummary(_Query['ИтогиПоГруппам']);
SetExtPropertyVisible(_Query['СвойстваУчетнойЕдиницы']);
bbSummary.Down:= _CurrentView.DataController.Summary.DefaultGroupSummaryItems.Count>0;
end;
end;
finally
if Blob <> nil then
try
Blob.Free;
except
end;
end;
end;
inc(i);
end;
_Query.Free;
end;
procedure TFrameBaseGrid.GetUniqueGridMetric(var AViewFormPlace: Cardinal; var AObjectId: integer; var APath: string);
var
OwnerForm: TBASE_Form;
PlaceNamePath: string;
procedure GetNamePath(AControl: TWinControl; var APlaceNamePath: string);
begin
if AControl.Name <> '' then
APlaceNamePath:= AControl.Name + '.'+ APlaceNamePath
else
APlaceNamePath:= AControl.ClassName + '.'+ APlaceNamePath;
if AControl.Parent <> nil then
GetNamePath(AControl.Parent, APlaceNamePath);
end;
begin
PlaceNamePath:='';
GetNamePath(self, PlaceNamePath);
APath:=PlaceNamePath;
CalcCRC32(PlaceNamePath, AViewFormPlace);
OwnerForm:= FindBaseForm(Parent);
if OwnerForm <> nil then
AObjectId:= TBASE_Form(OwnerForm).ObjectID
else
AObjectId:= 0;
end;
procedure TFrameBaseGrid.ApplyViewName(AView: TcxGridTableView;
var AViewName: string);
begin
if AView <> nil then begin
AViewName:= AView.Name;
if AViewName = '' then
//raise Exception.Create('При сохранении грида возникла ошибка: незадано имя view');
end else
raise Exception.Create('При сохранении грида возникла ошибка: получен нулевой указатель на View');
end;
function TFrameBaseGrid.IsExtPropertyExists: boolean;
begin
result:= false;
end;
procedure TFrameBaseGrid.ShowGroupSummary(AVisible: boolean);
begin
ShowGroupSummaryByColProperty(AVisible);
end;
procedure TFrameBaseGrid.SetExtPropertyVisible(AVisible: boolean);
begin
end;
procedure TFrameBaseGrid.ViewCellClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
begin
if (ACellViewInfo.Item.Index<>1) or (AButton<>mbLeft) or (View.Controller.FocusedRow.IsNewItemRow) then exit;
MarkCurrentRecord(not View.DataController.Values[View.DataController.FocusedRecordIndex, 1]);
AHandled:=true;
end;
function TFrameBaseGrid.InternalDeleteStoredProcName: string;
begin
result:='';
end;
procedure TFrameBaseGrid.bbReportMenuPopup(Sender: TObject);
var
AObjectId: integer;
AObjectId2: integer;
ReportsMenuHalper: TReportsMenuHalper;
OwnerForm: TBASE_Form;
begin
OwnerForm:= FindBaseForm(Parent);
if OwnerForm <> nil then
AObjectId:= TBASE_Form(OwnerForm).ObjectID
else
exit;
AObjectId2:=self.ObjectIDForReportMenu;
// ShowMessage(IntToStr(AObjectID2));
if AObjectId=157 then
AObjectId:=163;
bbReportMenu.ItemLinks.Clear;
ReportsMenuHalper:= TReportsMenuHalper.Create(bbReportMenu, AObjectId, -1, 40, OnReportsMenuClick, AObjectId2);
ReportsMenuHalper.Free;
end;
procedure TFrameBaseGrid.OnReportsMenuClick(Sender: TObject);
var
f: string;
SelectedRecords: TViewSelectedRecords;
Params: TParamCollection;
_PKNameForReportMenu: string;
ReportForObjectID: integer;
begin
ScreenCursor.IncCursor;
fReports_ShowReport:= TfReports_ShowReport.Create(self);
Application.ProcessMessages;
SelectedRecords:=nil;
//26-05-2010 ivanov
ReportForObjectID:=ExecSQLExpr('select код_Объект from sys_отчет where код_Отчет = '+IntToStr(TdxBarButton(Sender).Tag));
_PKNameForReportMenu:='';
if ReportForObjectID=163 then begin
if Assigned(dsCh.FindField('Учетная единица.код_Учетная единица')) then
_PKNameForReportMenu:='Учетная единица.код_Учетная единица';
if Assigned(dsCh.FindField('вк_Свойства')) then
_PKNameForReportMenu:='вк_Свойства';
end
else
_PKNameForReportMenu:=PKNameForReportMenu;
//^^^26-05-2010 ivanov
if Grid.ActiveView is TcxGridDBBandedTableView then
//26-05-2010 ivanov добавил _PKNameForReportMenu
SelectedRecords:= TViewSelectedRecords.Create(Grid.ActiveView as TcxGridDBBandedTableView, _PKNameForReportMenu)
else
if Grid.ActiveView is TcxGridBandedTableViewCds then
//26-05-2010 ivanov добавил _PKNameForReportMenu
SelectedRecords:= TViewSelectedRecords.Create(Grid.ActiveView as TcxGridBandedTableViewCds, _PKNameForReportMenu);
Params:=CreateCurRecordValues;
if (SelectedRecords<>nil) and (SelectedRecords.Count > 0) then
f:= SelectedRecords.AsString
else
f:= '';
if not fReports_ShowReport.PrepareReport(TdxBarButton(Sender).Tag, true, f, Params) then
fReports_ShowReport.Free;
SelectedRecords.Free;
ScreenCursor.DecCursor;
end;
//zav
function TFrameBaseGrid.GetSelectedREcordsAsString:string;
var
SelectedRecords: TViewSelectedRecords;
begin
if Grid.ActiveView is TcxGridDBBandedTableView then
SelectedRecords:= TViewSelectedRecords.Create(Grid.ActiveView as TcxGridDBBandedTableView)
else
if Grid.ActiveView is TcxGridBandedTableViewCds then
SelectedRecords:= TViewSelectedRecords.Create(Grid.ActiveView as TcxGridBandedTableViewCds);
Result := SelectedRecords.AsString;
end;
//end zav
procedure TFrameBaseGrid.actFindExecute(Sender: TObject);
begin
if bbFind.Down then
dlgFind.Show
else
dlgFind.Close;
end;
procedure TFrameBaseGrid.ViewFocusedItemChanged(
Sender: TcxCustomGridTableView; APrevFocusedItem,
AFocusedItem: TcxCustomGridTableItem);
begin
{ if not Assigned(AFocusedItem) then exit;
if AFocusedItem.Index=0 then exit;
if dlgFind.Visible and (dlgFind.Grid<>Grid) then
dlgFind.Grid:=Grid;
if AFocusedItem.AlternateCaption<>'' then
dlgFind.FieldName:=AFocusedItem.AlternateCaption
else
dlgFind.FieldName:=AFocusedItem.Caption;}
end;
procedure TFrameBaseGrid.ViewChFocusedItemChanged(
Sender: TcxCustomGridTableView; APrevFocusedItem,
AFocusedItem: TcxCustomGridTableItem);
begin
{ if not Assigned(AFocusedItem) then exit;
if AFocusedItem.Index=0 then exit;
if dlgFind.Visible and (dlgFind.Grid<>Grid) then
dlgFind.Grid:=Grid;
if AFocusedItem.AlternateCaption<>'' then
dlgFind.FieldName:=AFocusedItem.AlternateCaption
else
dlgFind.FieldName:=AFocusedItem.Caption;}
end;
procedure TFrameBaseGrid.OnFindDialogClose(Sender: TObject; var Action: TCloseAction);
begin
bbFind.Down:=false;
end;
procedure TFrameBaseGrid.InternalViewKeyPress(Sender: TObject; var Key: Char);
begin
if (key=#13) and actEdit.Enabled and (not (View.DataController.DataSource.DataSet.State in [dsInsert, dsEdit])) then
actEdit.Execute;
end;
procedure TFrameBaseGrid.actSaveGridViewExecute(Sender: TObject);
var
i: integer;
begin
StoreGrid;
end;
procedure TFrameBaseGrid.actSaveGridViewDefaultExecute(Sender: TObject);
begin
self.StoreGrid(-1, true);
end;
procedure TFrameBaseGrid.actRestoreGridViewExecute(Sender: TObject);
begin
RestoryGrid;
end;
procedure TFrameBaseGrid.actRestoreGridViewDefaultExecute(Sender: TObject);
begin
RestoryGrid(-1, true);
end;
function TFrameBaseGrid.CreateCurRecordValues: TParamCollection;
var
i: integer;
r: integer;
begin
result:=nil;
result:=TParamCollection.Create(TParamItem);
//18-08-2009
if Grid.ActiveView=View then
with view.DataController.DataSource do
for i:=0 to DataSet.FieldCount-1 do
result.Add(DataSet.Fields[i].DisplayName).Value:=DataSet.Fields[i].Value;
if Grid.ActiveView=ViewCh then begin
r:=ViewCh.DataController.FocusedRecordIndex;
with ViewCh.DataController.CashDataSource do
for i:=0 to FieldCount-1 do
result.Add(Fields[i].DisplayLabel).Value:=Fields[i].Value[r];
end;
//^^^18-08-2009
end;
function TViewSelectedRecords.GetPKColumnIndex(
View: TcxGridBandedTableViewCds; PKFieldName: string): integer;
var
i: integer;
begin
result:=0;
if PKFieldName='' then exit;
PKFieldName:=AnsiLowerCase(PKFieldName);
for i:=0 to View.ColumnCount-1 do
if AnsiLowerCase(View.Columns[i].DataBinding.FieldName)=PKFieldName then begin
result:=i;
exit;
end;
end;
function TFrameBaseGrid.CreateCurRecordValuesCh: TParamCollection;
var
i: integer;
r: integer;
begin
result:=nil;
r:=ViewCh.DataController.FocusedRecordIndex;
if r<0 then exit;
result:=TParamCollection.Create(TParamItem);
for i:=0 to dsCh.FieldCount-1 do
result.Add(dsCh.Fields[0].FieldName).Value:=dsCh.Values[r, i];
end;
procedure TFrameBaseGrid.InternalDeleteRecCh;
var
sr: TViewSelectedRecords;
sp: TADOStoredProc;
i: integer;
st: string;
begin
sr:=TViewSelectedRecords.Create(ViewCh);
try
st:='Удалить количество записей: '+IntToStr(sr.Count)+'?';
if MessageBox(Application.Handle, pchar(st), 'Удаление', MB_YESNO or MB_ICONQUESTION or MB_APPLMODAL) <> IDYES then exit;
ViewCh.BeginUpdate;
try
sp:=TADOStoredProc.Create(nil);
sp.Connection:=frmMain.ADOConnection;
if InternalDeleteStoredProcName='' then
sp.ProcedureName:=format('sp_а_%s_удалить', [InternalObjectName(true)])
else
sp.ProcedureName:=InternalDeleteStoredProcName;
sp.Parameters.Refresh;
sp.Parameters[1].Value:=sr.AsString;
frmMain.ADOConnection.BeginTrans;
try
sp.ExecProc;
frmMain.ADOConnection.CommitTrans;
for i:=sr.Count-1 downto 0 do
dsCh.DeleteRecord(sr.Items[i].RecordIndex);
except
//25-08-2009
frmMain.ADOConnection.RollbackTrans;
if (ExceptObject is EOLEException) and ((ExceptObject as EOLEException).ErrorCode=-2147217873) then begin
if pos('ДоговорОбъект', (ExceptObject as Exception).Message)>0 then
raise Exception.Create('Один или несколько объектов включены в закрепительные документы.'+#13#10+'Перед удалением объекта учета необходимо удалить связь с закрепительными документами')
else
if pos('ДопСоглашениеОбъект', (ExceptObject as Exception).Message)>0 then
raise Exception.Create('Один или несколько объектов включены в дополнительные документы.'+#13#10+'Перед удалением объекта учета необходимо удалить связь с дополнительными документами')
else raise;
//^^^25-08-2009
end
else
raise;
end;
finally
ViewCh.EndUpdate;
end;
finally
sr.Free;
end;
end;
procedure TFrameBaseGrid.InternalEditRecCh;
begin
//abstract
end;
procedure TFrameBaseGrid.InternalInsertRecCh;
begin
//abstract
end;
procedure TFrameBaseGrid.InternalOpenDataCh;
begin
//abstract
end;
procedure TFrameBaseGrid.InternalOpenHistoryCh;
var
a: TAccessSelectorForm;
p: TParamCollection;
begin
a:=TAccessSelectorForm.Create;
try
a.ObjectID:=434;
p:=TParamCollection.Create(TParamItem);
try
p.Add('код_Объект').Value:=self.CurRecItemValue('вк_НастоящийОбъектВладелец');
p.Add('код_Записи').Value:=self.CurRecPKValue;
a.ShowModal(p, null);
finally
p.Free;
end;
finally
a.Free;
end;
end;
procedure TFrameBaseGrid.InternalRefreshAllRecCh;
begin
dsCh.Close;
dsCh.Open;
end;
procedure TFrameBaseGrid.InternalRefreshCurrentRecCh(
UpdateFieldsData: boolean);
begin
InternalRefreshCurrentCash('', ViewCh, self.InternalObjectName);
end;
procedure TFrameBaseGrid.InternalViewKeyPressCh(Sender: TObject;
var Key: Char);
begin
if (key=#13) and actEdit.Enabled and (ViewCh.DataController.EditState<>[dceInsert]) and (ViewCh.DataController.EditState<>[dceEdit]) then
actEdit.Execute;
end;
procedure TFrameBaseGrid.MarkAllRecordsCh(mark, Inverse: boolean);
var
i, r: integer;
rec: TcxCustomGridRecord;
v: boolean;
begin
for i:=0 to ViewCh.DataController.FilteredRecordCount-1 do begin
r:=ViewCh.DataController.FilteredRecordIndex[i];
v:=nz(dsCh.Values[r, 1], false);
if Inverse then
dsCh.CashEdit(r, 1, not v, true, true)
else
dsCh.CashEdit(r, 1, mark, true, true)
end;
dsCh.DataChanged();
end;
procedure TFrameBaseGrid.MarkCurrentRecordCh(mark: boolean);
begin
dsCh.CashEdit(ViewCh.DataController.FocusedRecordIndex, 1, mark, true, true);
dsCh.DataChanged();
end;
procedure TFrameBaseGrid.MarkFieldChange_AssignEventToColumnCh;
var
i: integer;
begin
for i:=0 to ViewCh.ColumnCount-1 do
if ViewCh.Columns[i].DataBinding.FieldName='ForADOInsertCol' then begin
ViewCh.Columns[i].Caption:='';
ViewCh.Columns[i].Width:=20;
ViewCh.Columns[i].PropertiesClass:=TcxCheckBoxProperties;
ViewCh.Columns[i].Options.Editing:=false;
ViewCh.Columns[i].Options.ShowEditButtons:=isebAlways;
ViewCh.OnCellClick:=ViewCellClickCh;
exit;
end;
end;
procedure TFrameBaseGrid.ViewCellClickCh(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
begin
if (ACellViewInfo.Item.Index<>1) or (AButton<>mbLeft) or (ViewCh.Controller.FocusedRow.IsNewItemRow) then exit;
MarkCurrentRecordCh(not ViewCh.DataController.Values[ViewCh.DataController.FocusedRecordIndex, 1]);
AHandled:=true;
end;
function TFrameBaseGrid.CurRecItemValue(ItemName: string): variant;
var
r, c: integer;
f: TcdField;
begin
result:=null;
r:=self.ViewCh.DataController.FocusedRecordIndex;
if r<0 then exit;
f:=dsCh.FieldByName(ItemName);
if not Assigned(f) then exit;
c:=f.Index;
result:=dsCh.Values[r, c];
end;
function TFrameBaseGrid.CurRecPKValue: variant;
var
r: integer;
begin
result:=null;
r:=self.ViewCh.DataController.FocusedRecordIndex;
if r<0 then exit;
result:=dsCh.Values[r, 0];
end;
procedure TFrameBaseGrid.dsChAfterOpen(Sender: TObject);
begin
dsCh.KeyFields:=dsCh.Fields[0].FieldName;
ScreenCursor.DecCursor;
end;
procedure TFrameBaseGrid.LocateByIDCh(ID: integer);
begin
ViewCh.DataController.FocusedRecordIndex:=dsCh.Locate(dsCh.KeyFields, ID, []);
end;
function TFrameBaseGrid.ObjectIDForReportMenu: integer;
begin
result:=-1;
end;
//29-07-2009
function TViewSelectedRecords.GetUEColumnIndex(View: TcxGridBandedTableViewCds): integer;
var
col: TcxGridColumn;
begin
result:=-1;
col:=nil;
col:=view.FindItemByFieldName('вк_Свойства');
if Assigned(col) then
result:=col.Index
else begin
col:=view.FindItemByFieldName('Учетная единица.код_Учетная единица');
if Assigned(col) then
result:=col.Index
end;
end;
function TViewSelectedRecords.UEAsString: string;
var
i: integer;
begin
result:='';
for i:=0 to Count-1 do
result:=result+IntToStr(Items[i].UEKeyValue)+',';
delete(result, length(result), 1);
end;
//^^^29-07-2009
//20-08-2009
procedure TFrameBaseGrid.ViewChDblClick(Sender: TObject);
begin
if actEdit.Enabled then
actEdit.Execute;
end;
//^^^20-08-2009
procedure TFrameBaseGrid.dsChBeforeOpen(Sender: TObject);
begin
ScreenCursor.IncCursor;
end;
end.
|
(*
* DGL(The Delphi Generic Library)
*
* Copyright (c) 2004
* HouSisong@gmail.com
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*)
//------------------------------------------------------------------------------
//TStrIntMap
//例子
//具现化String<->integer的map容器和其迭代器
// Create by HouSisong, 2004.09.13
//------------------------------------------------------------------------------
unit _DGLMap_String_Integer;
interface
uses
SysUtils;
{$I DGLCfg.inc_h}
type
_KeyType = string;
_ValueType = integer;
const
_NULL_Value:integer=0;
function _HashValue(const Key: _KeyType):Cardinal;{$ifdef _DGL_Inline} inline; {$endif}//Hash函数
{$I HashMap.inc_h} //"类"模版的声明文件
{$I Map.inc_h} //"类"模版的声明文件
{$I Algorithms.inc_h}
//out
type
IStrIntMapIterator = _IMapIterator;
IStrIntMap = _IMap;
IStrIntMultiMap = _IMultiMap;
TStrIntHashMap = _THashMap;
TStrIntHashMultiMap = _THashMultiMap;
TStrIntMap = _TMap;
TStrIntMultiMap = _TMultiMap;
implementation
uses
HashFunctions;
{$I HashMap.inc_pas} //"类"模版的实现文件
{$I Map.inc_pas} //"类"模版的实现文件
{$I Algorithms.inc_pas}
function _HashValue(const Key :_KeyType):Cardinal; overload;
begin
result:=HashValue_Str(Key);
end;
end.
|
unit TestUItensRateioVO;
{
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, SysUtils, Atributos, UUnidadeVO, Generics.Collections, UGenericVO,
Classes, Constantes, UItensRateioVO;
type
// Test methods for class TItensRateioVO
TestTItensRateioVO = class(TTestCase)
strict private
FItensRateioVO: TItensRateioVO;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestValidarCamposObrigatorios;
procedure TestValidarCamposObrigatoriosNaoEncontrado;
end;
implementation
procedure TestTItensRateioVO.SetUp;
begin
FItensRateioVO := TItensRateioVO.Create;
end;
procedure TestTItensRateioVO.TearDown;
begin
FItensRateioVO.Free;
FItensRateioVO := nil;
end;
procedure TestTItensRateioVO.TestValidarCamposObrigatorios;
var
Rateio : TItensRateioVO;
begin
Rateio := TItensRateioVO.Create;
Rateio.dtRateio := StrToDate('01/01/2016');
Rateio.vlRateio := 10;
try
Rateio.ValidarCamposObrigatorios;
Check(True,'Sucesso!')
except on E: Exception do
Check(false,'Erro!');
end;
end;
procedure TestTItensRateioVO.TestValidarCamposObrigatoriosNaoEncontrado;
var
Rateio : TItensRateioVO;
begin
Rateio := TItensRateioVO.Create;
Rateio.vlRateio := 10;
try
Rateio.ValidarCamposObrigatorios;
Check(false,'Erro!')
except on E: Exception do
Check(True,'Sucesso!');
end;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTItensRateioVO.Suite);
end.
|
unit Allgemein.Funktionen;
interface
uses
Windows, Classes, System.SysUtils;
function isValidEmail(const aValue: string; var aFehlermeldung: string): Boolean;
implementation
function isValidEmail(const aValue: string; var aFehlermeldung: string): Boolean;
var
iPos: Integer;
s: string;
s1: string;
i1, i2: Integer;
List: TStringList;
begin
Result := false;
List := TStringList.Create;
try
s := aValue;
if Trim(s) = '' then
begin
aFehlermeldung := 'EMail-Adresse ist leer';
exit;
end;
if s[Length(s)] = ';' then
s := Copy(s, 1, Length(s)-1);
List.StrictDelimiter := true;
List.Delimiter := ';';
List.DelimitedText := s;
for i2 := 0 to List.Count -1 do
begin
s := List.Strings[i2];
aFehlermeldung := '';
if Trim(s) = '' then
begin
aFehlermeldung := 'EMail-Adresse ist leer';
exit;
end;
iPos := Pos('@', s);
if iPos <= 0 then
begin
aFehlermeldung := 'Das @-Zeichen fehlt.';
exit;
end;
s := StringReplace(s, '@', '', []);
s := LowerCase(s);
iPos := Pos('@', s);
if iPos > 0 then
begin
aFehlermeldung := 'Mehr als ein @-Zeichen gefunden.';
exit;
end;
iPos := Pos('@', List.Strings[i2]);
s1 := copy(List.Strings[i2], iPos+1, Length(List.Strings[i2]));
iPos := Pos('.', s1);
if iPos <=0 then
begin
aFehlermeldung := 'String hinter dem @-Zeichen "' + s1 + '" fehlt irgendwo ein Punkt';
exit;
end;
for i1 := 1 to Length(s) do
begin
if not CharInSet(s[i1], ['a'..'z', '0'..'9', '-', '_', '.']) then
begin
aFehlermeldung := 'Dieses Zeichen "' + s[i1] + '" ist in einer EMail-Adresse ungültig';
exit;
end;
end;
end;
Result := true;
finally
FreeAndNil(List);
end;
end;
end.
|
PROGRAM Main;
USES UEarthquake;
PROCEDURE AddEarthquakeEntries(number: INTEGER);
VAR
i: INTEGER;
BEGIN
FOR i := 1 TO number DO
BEGIN
AddEarthquake(1.321, 2.345, 8.0, 'Hagenberg', '01.01.2018');
END;
END;
FUNCTION AssertTrue(bool: BOOLEAN): STRING;
BEGIN
AssertTrue := 'X';
IF bool THEN
AssertTrue := 'OK'
END;
FUNCTION AssertFalse(bool: BOOLEAN): STRING;
BEGIN
AssertFalse := 'X';
IF not bool THEN
AssertFalse := 'OK'
END;
FUNCTION AssertTotalNumberOfEarthquakes(expectedNumber: INTEGER): BOOLEAN;
BEGIN
AssertTotalNumberOfEarthquakes := (TotalNumberOfEarthquakes = expectedNumber);
END;
FUNCTION AssertNumberOfEarthquakesInTimespan(fromDate, toDate: STRING; expectedNumber: INTEGER): BOOLEAN;
BEGIN
AssertNumberOfEarthquakesInTimespan := (NumberOfEarthquakesInTimespan(fromDate, toDate) = expectedNumber);
END;
PROCEDURE SetUpTestEarthquakes;
BEGIN
AddEarthquake(1.5, 2.3, 1.1, 'Amstetten', '01.01.2018');
AddEarthquake(4.1, 2.5, 3.4, 'Hagenberg', '15.02.2017');
AddEarthquake(10, 3, 9.5, 'Valdivia', '22.05.1960');
AddEarthquake(22.1234, 30.5234, 5.5, 'Linz', '30.12.2002');
AddEarthquake(2.5243, 1.5643, 2.0, 'Amstetten', '01.04.1995');
AddEarthquake(14, 15, 8.0, 'Oslo', '28.03.1987');
AddEarthquake(20.0034, 3.2398, 2.0, 'Hagenberg', '15.11.2019');
END;
PROCEDURE SetUpTestEarthquakesNegativeGeopoints;
BEGIN
AddEarthquake(-1.5, -2.3, 1.1, 'Amstetten', '01.01.2018');
AddEarthquake(-4.1, -2.5, 3.4, 'Hagenberg', '15.02.2017');
AddEarthquake(-10, -3, 9.5, 'Valdivia', '22.05.1960');
AddEarthquake(-22.1234, -30.5234, 5.5, 'Linz', '30.12.2002');
AddEarthquake(-2.5243, -1.5643, 2.0, 'Amstetten', '01.04.1995');
AddEarthquake(-14, -15, 8.0, 'Oslo', '28.03.1987');
AddEarthquake(-20.0034, -3.2398, 2.0, 'Hagenberg', '15.11.2019');
END;
FUNCTION AssertGetStrongestEarthquakeInRegion(expectedLatitude, expectedLongitude, expectedStrength: REAL;
expectedCity: STRING; expectedDay, expectedMonth, expectedYear: INTEGER): BOOLEAN;
VAR
latitudeOut, longitudeOut, strength: REAL;
city: STRING;
day, month, year: INTEGER;
BEGIN
GetStrongestEarthquakeInRegion(14, 15, 1, 2, latitudeOut, longitudeOut, strength, city, day, month, year);
IF (latitudeOut = expectedLatitude) and (longitudeOut = expectedLongitude) and (strength = expectedStrength) and (city = expectedCity) and (day = expectedDay) and (month = expectedMonth) and (year = expectedYear) THEN
AssertGetStrongestEarthquakeInRegion := true;
END;
FUNCTION AssertAverageEarthquakeStrengthInRegion(latitude1, longitude1, latitude2, longitude2, expectedAverage: REAL): BOOLEAN;
BEGIN
AssertAverageEarthquakeStrengthInRegion := (AverageEarthquakeStrengthInRegion(latitude1, longitude1, latitude2, longitude2) = expectedAverage)
END;
FUNCTION AssertReset: BOOLEAN;
BEGIN
Reset;
AssertReset := (TotalNumberOfEarthquakes = 0);
END;
VAR
latitudeOut, longitudeOut, strength: REAL;
city: STRING;
day, month, year: INTEGER;
BEGIN
{* Test AddEarthquake and TotalNumberOfEarthquakes *}
WriteLn();
WriteLn('Test AddEarthquake and TotalNumberOfEarthquakes');
AddEarthquake(1.321, 2.345, 8.0, 'Hagenberg', '1.1.2018');
WriteLn('AddEarthquake(1.321, 2.345, 8.0, ''Hagenberg'', ''1.1.2018'');');
WriteLn('AssertTotalNumberOfEarthquakes(0) returns true -> ', AssertTrue(AssertTotalNumberOfEarthquakes(0)));
AddEarthquake(1.321, 2.345, 8.0, 'Hagenberg', '01.01.2018');
WriteLn('AddEarthquake(1.321, 2.345, 8.0, ''Hagenberg'', ''01.01.2018'');');
WriteLn('AssertTotalNumberOfEarthquakes(1) returns true -> ', AssertTrue(AssertTotalNumberOfEarthquakes(1)));
Reset;
WriteLn('Reset');
WriteLn();
AddEarthquakeEntries(999);
WriteLn('AddEarthquakeEntries(999);');
WriteLn('AssertTotalNumberOfEarthquakes(999) returns true -> ', AssertTrue(AssertTotalNumberOfEarthquakes(999)));
Reset;
AddEarthquakeEntries(1000);
WriteLn('AddEarthquakeEntries(1000);');
WriteLn('AssertTotalNumberOfEarthquakes(1000) returns true -> ', AssertTrue(AssertTotalNumberOfEarthquakes(1000)));
Reset;
AddEarthquakeEntries(1001);
WriteLn('AddEarthquakeEntries(1001);');
WriteLn('AssertTotalNumberOfEarthquakes(1001) returns false -> ', AssertFalse(AssertTotalNumberOfEarthquakes(1001)));
WriteLn('AssertTotalNumberOfEarthquakes(1000) returns true -> ', AssertTrue(AssertTotalNumberOfEarthquakes(1000)));
Reset;
WriteLn('Reset');
WriteLn();
{* Test NumberOfEarthquakeInTimespan *}
WriteLn('Test NumberOfEarthquakeInTimespan');
SetUpTestEarthquakes;
WriteLn('AssertNumberOfEarthquakesInTimespan(''15.11.1995'', ''15.11.2019'', 4) returns true -> ', AssertTrue(AssertNumberOfEarthquakesInTimespan('15.11.1995', '15.11.2019', 4)));
WriteLn('AssertNumberOfEarthquakesInTimespan(''01.01.0001'', ''01.01.0001'', 0) returns true -> ', AssertTrue(AssertNumberOfEarthquakesInTimespan('01.01.0001', '01.01.0001', 0)));
WriteLn('AssertNumberOfEarthquakesInTimespan(''01.13.0001'', ''01.01.0001'', -1) returns true -> ', AssertTrue(AssertNumberOfEarthquakesInTimespan('01.13.0001', '01.01.0001', -1)));
WriteLn('AssertNumberOfEarthquakesInTimespan(''15.11.2019'', ''15.11.1995'', 4) returns true -> ', AssertTrue(AssertNumberOfEarthquakesInTimespan('15.11.2019', '15.11.1995', 4)));
WriteLn();
{* Test GetStrongestEarthquakeInRegion *}
WriteLn('Test GetStrongestEarthquakeInRegion');
WriteLn('AssertGetStrongestEarthquakeInRegion(1, 3, 9.5, ''Valdivia'', 22, 5, 1960) returns true -> ', AssertTrue(AssertGetStrongestEarthquakeInRegion(1, 3, 9.5, 'Valdivia', 22, 5, 1960)));
{* Test AverageEarthquakeStrengthInRegion *}
WriteLn('Test AverageEarthquakeStrengthInRegion');
WriteLn('AssertAverageEarthquakeStrengthInRegion(1, 2, 14, 15, 5.5) returns true -> ', AssertTrue(AssertAverageEarthquakeStrengthInRegion(1, 2, 14, 15, 5.5)));
WriteLn('AssertAverageEarthquakeStrengthInRegion(1, 1, 50, 50, 4.5) returns true -> ', AssertTrue(AssertAverageEarthquakeStrengthInRegion(1, 1, 50, 50, 4.5)));
WriteLn('AssertAverageEarthquakeStrengthInRegion(1, 1, 1, 1, 0) returns true -> ', AssertTrue(AssertAverageEarthquakeStrengthInRegion(1, 1, 1, 1, 0)));
WriteLn('AssertAverageEarthquakeStrengthInRegion(14, 15, 14, 15, 8.0) returns true -> ', AssertTrue(AssertAverageEarthquakeStrengthInRegion(14, 15, 14, 15, 8.0)));
WriteLn();
Reset;
SetUpTestEarthquakesNegativeGeopoints;
WriteLn('AssertAverageEarthquakeStrengthInRegion(-1, -2, -14, -15, 5.5) returns true -> ', AssertTrue(AssertAverageEarthquakeStrengthInRegion(-1, -2, -14, -15, 5.5)));
WriteLn('AssertAverageEarthquakeStrengthInRegion(-1, -1, -50, -50, 4.5) returns true -> ', AssertTrue(AssertAverageEarthquakeStrengthInRegion(-1, -1, -50, -50, 4.5)));
WriteLn('AssertAverageEarthquakeStrengthInRegion(-1, -1, -1, -1, 0) returns true -> ', AssertTrue(AssertAverageEarthquakeStrengthInRegion(-1, -1, -1, -1, 0)));
WriteLn('AssertAverageEarthquakeStrengthInRegion(-14, -15, -14, -15, 8.0) returns true -> ', AssertTrue(AssertAverageEarthquakeStrengthInRegion(-14, -15, -14, -15, 8.0)));
Reset;
SetUpTestEarthquakes;
PrintEarthquakesCloseToCity('Amstetten');
PrintStrongCityEarthQuakes(5.5);
{* Test Reset *}
WriteLn('Test Reset');
WriteLn('AssertReset returns true -> ', AssertTrue(AssertReset));
END. |
{*******************************************************************************
Title: T2TiPDV
Description: Janela utilizada para iniciar um novo movimento.
The MIT License
Copyright: Copyright (C) 2012 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
alberteije@gmail.com
@author T2Ti.COM
@version 1.0
*******************************************************************************}
unit UIniciaMovimento;
{$mode objfpc}{$H+}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, DBGrids, StdCtrls, Buttons, ExtCtrls, DB, FMTBcd,
ZAbstractRODataset, ZAbstractDataset, ZDataset, ACBrBase, dateutils,
ACBrEnterTab, CurrEdit, UBase, Tipos;
type
{ TFIniciaMovimento }
TFIniciaMovimento = class(TFBase)
ACBrEnterTab1: TACBrEnterTab;
Image1: TImage;
GroupBox2: TGroupBox;
Label3: TLabel;
GroupBox3: TGroupBox;
GridTurno: TDBGrid;
GroupBox1: TGroupBox;
editLoginGerente: TLabeledEdit;
editSenhaGerente: TLabeledEdit;
botaoConfirma: TBitBtn;
botaoCancela: TBitBtn;
GroupBox4: TGroupBox;
editLoginOperador: TLabeledEdit;
editSenhaOperador: TLabeledEdit;
DSTurno: TDataSource;
editValorSuprimento: TCurrencyEdit;
procedure Confirma;
procedure FormActivate(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure GridTurnoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure botaoConfirmaClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormCreate(Sender: TObject);
procedure ImprimeAbertura;
private
{ Private declarations }
public
{ Public declarations }
end;
var
FIniciaMovimento: TFIniciaMovimento;
QTurno: TZQuery;
implementation
uses
UDataModule,
EcfOperadorVO, EcfMovimentoVO, EcfTurnoVO, EcfSuprimentoVO, EcfFuncionarioController,
EcfTurnoController, PAFUtil, ECFUtil, EcfMovimentoController, EcfSuprimentoController;
{$R *.lfm}
{$REGION 'Infra'}
procedure TFIniciaMovimento.FormCreate(Sender: TObject);
var
Filtro: String;
begin
Filtro := 'ID>0';
QTurno := TEcfTurnoController.Consulta(Filtro, '-1');
QTurno.Active := True;
DSTurno.DataSet := QTurno;
end;
procedure TFIniciaMovimento.FormActivate(Sender: TObject);
begin
Color := StringToColor(Sessao.Configuracao.CorJanelasInternas);
GridTurno.SetFocus;
end;
procedure TFIniciaMovimento.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
CloseAction := caFree;
Release;
end;
procedure TFIniciaMovimento.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = VK_F12 then
Confirma;
if Key = VK_ESCAPE then
botaoCancela.Click;
end;
procedure TFIniciaMovimento.GridTurnoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = VK_RETURN then
editValorSuprimento.SetFocus;
end;
{$ENDREGION 'Infra'}
{$Region 'Confirmação e Início do Movimento'}
procedure TFIniciaMovimento.botaoConfirmaClick(Sender: TObject);
begin
Confirma;
end;
procedure TFIniciaMovimento.Confirma;
var
Gerente: TEcfOperadorVO;
Suprimento: TEcfSuprimentoVO;
begin
try
try
// verifica se senha e o nível do operador estão corretos
Sessao.AutenticaUsuario(editLoginOperador.Text, editSenhaOperador.Text);
if Assigned(Sessao.Usuario) then
begin
// verifica se senha do gerente esta correta
Gerente := TEcfFuncionarioController.Usuario(editLoginGerente.Text, editSenhaGerente.Text);
if Assigned(Gerente) then
begin
// verifica nivel de acesso do gerente/supervisor
if (Gerente.EcfFuncionarioVO.NivelAutorizacao = 'G') or (Gerente.EcfFuncionarioVO.NivelAutorizacao = 'S') then
begin
if TECFUtil.ImpressoraOK(2) then
begin
// insere movimento
Sessao.Movimento := TEcfMovimentoVO.Create;
Sessao.Movimento.IdEcfTurno := QTurno.FieldByName('ID').AsInteger;
Sessao.Movimento.IdEcfImpressora := Sessao.Configuracao.IdEcfImpressora;
Sessao.Movimento.idEcfEmpresa := Sessao.Configuracao.idEcfEmpresa;
Sessao.Movimento.IdECfOperador := Sessao.Usuario.Id;
Sessao.Movimento.IdECfCaixa := Sessao.Configuracao.IdECfCaixa;
Sessao.Movimento.IdGerenteSupervisor := Gerente.Id;
Sessao.Movimento.DataAbertura := EncodeDate(YearOf(FDataModule.ACBrECF.DataHora), MonthOf(FDataModule.ACBrECF.DataHora), DayOf(FDataModule.ACBrECF.DataHora));
Sessao.Movimento.HoraAbertura := FormatDateTime('hh:nn:ss', FDataModule.ACBrECF.DataHora);
Sessao.Movimento.TotalSuprimento := editValorSuprimento.Value;
Sessao.Movimento.StatusMovimento := 'A';
Sessao.Movimento := TEcfMovimentoController.IniciaMovimento(Sessao.Movimento);
end
else
begin
Application.MessageBox('Não foi possível abrir o movimento!.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION);
Sessao.StatusCaixa := scSomenteConsulta;
Close;
end; // if UECF.ImpressoraOK(2) then
// insere suprimento
if editValorSuprimento.Value > 0 then
begin
try
TECFUtil.Suprimento(editValorSuprimento.Value, Sessao.Configuracao.DescricaoSuprimento);
Suprimento := TEcfSuprimentoVO.Create;
Suprimento.IdEcfMovimento := Sessao.Movimento.Id;
Suprimento.DataSuprimento := EncodeDate(YearOf(FDataModule.ACBrECF.DataHora), MonthOf(FDataModule.ACBrECF.DataHora), DayOf(FDataModule.ACBrECF.DataHora));
Suprimento.Valor := editValorSuprimento.Value;
TEcfSuprimentoController.Insere(Suprimento);
Sessao.Movimento.TotalSuprimento := Sessao.Movimento.TotalSuprimento + Suprimento.Valor;
TEcfMovimentoController.Altera(Sessao.Movimento);
finally
FreeAndNil(Suprimento);
end;
end; // if StrToFloat(editValorSuprimento.Text) <> 0 then
if Assigned(Sessao.Movimento) then
begin
Application.MessageBox('Movimento aberto com sucesso.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION);
Sessao.StatusCaixa := scAberto;
ImprimeAbertura;
end;
Close;
end
else
begin
Application.MessageBox('Gerente ou Supervisor: nível de acesso incorreto.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION);
editLoginGerente.SetFocus;
end; // if (Gerente.Nivel = 'G') or (Gerente.Nivel = 'S') then
end
else
begin
Application.MessageBox('Gerente ou Supervisor: dados incorretos.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION);
editLoginGerente.SetFocus;
end; // if Gerente.Id <> 0 then
end
else
begin
Application.MessageBox('Operador: dados incorretos.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION);
editSenhaOperador.SetFocus;
end; // if Operador.Id <> 0 then
except
end;
finally
FreeAndNil(Gerente);
end;
end;
{$EndRegion 'Confirmação e Início do Movimento'}
{$Region 'Impressão da Abertura'}
procedure TFIniciaMovimento.ImprimeAbertura;
begin
FDataModule.ACBrECF.AbreRelatorioGerencial(Sessao.Configuracao.EcfRelatorioGerencialVO.X);
FDataModule.ACBrECF.LinhaRelatorioGerencial(StringOfChar('=', 48));
FDataModule.ACBrECF.LinhaRelatorioGerencial(' ABERTURA DE CAIXA ');
FDataModule.ACBrECF.PulaLinhas(1);
FDataModule.ACBrECF.LinhaRelatorioGerencial('DATA DE ABERTURA : ' + FormatDateTime('dd/mm/yyyy', Sessao.Movimento.DataAbertura));
FDataModule.ACBrECF.LinhaRelatorioGerencial('HORA DE ABERTURA : ' + Sessao.Movimento.HoraAbertura);
FDataModule.ACBrECF.LinhaRelatorioGerencial(Sessao.Movimento.EcfCaixaVO.Nome + ' OPERADOR: ' + Sessao.Movimento.EcfOperadorVO.Login);
FDataModule.ACBrECF.LinhaRelatorioGerencial('MOVIMENTO: ' + IntToStr(Sessao.Movimento.Id));
FDataModule.ACBrECF.LinhaRelatorioGerencial(StringOfChar('=', 48));
FDataModule.ACBrECF.PulaLinhas(1);
FDataModule.ACBrECF.LinhaRelatorioGerencial('SUPRIMENTO...: ' + formatfloat('##,###,##0.00', EditValorSuprimento.Value));
FDataModule.ACBrECF.PulaLinhas(3);
FDataModule.ACBrECF.LinhaRelatorioGerencial(' ________________________________________ ');
FDataModule.ACBrECF.LinhaRelatorioGerencial(' VISTO DO CAIXA ');
FDataModule.ACBrECF.PulaLinhas(3);
FDataModule.ACBrECF.LinhaRelatorioGerencial(' ________________________________________ ');
FDataModule.ACBrECF.LinhaRelatorioGerencial(' VISTO DO SUPERVISOR ');
FDataModule.ACBrECF.FechaRelatorio;
TPAFUtil.GravarR06('RG');
end;
end.
|
unit sgDriveriOS;
//=============================================================================
// sgiOSDriver.pas
//=============================================================================
//
//
//=============================================================================
interface
uses sgTypes;
type
ShowKeyboardProcedure = procedure();
HideKeyboardProcedure = procedure();
ToggleKeyboardProcedure = procedure();
IsShownKeyboardProcedure = function():Boolean;
InitProcedure = procedure();
ProcessAxisMotionEventProcedure = function() : AccelerometerMotion;
AxisToGProcedure = function( value : LongInt ) : Single;
ProcessTouchEventProcedure = function (touch: Pointer) : FingerArray;
iOSDriverRecord = record
ShowKeyboard : ShowKeyboardProcedure;
HideKeyboard : HideKeyboardProcedure;
ToggleKeyboard : ToggleKeyboardProcedure;
IsShownKeyboard : IsShownKeyboardProcedure;
Init : InitProcedure;
ProcessAxisMotionEvent : ProcessAxisMotionEventProcedure;
AxisToG : AxisToGProcedure;
ProcessTouchEvent : ProcessTouchEventProcedure;
end;
var
iOSDriver : iOSDriverRecord;
implementation
procedure LoadDefaultiOSDriver();
begin
// LoadSDL13iOSDriver();
end;
procedure DefaultShowKeyboardProcedure();
begin
LoadDefaultiOSDriver();
exit;
iOSDriver.ShowKeyboard();
end;
procedure DefaultHideKeyboardProcedure();
begin
LoadDefaultiOSDriver();
exit;
iOSDriver.HideKeyboard();
end;
procedure DefaultToggleKeyboardProcedure();
begin
LoadDefaultiOSDriver();
exit;
iOSDriver.ToggleKeyboard();
end;
function DefaultIsShownKeyboardProcedure() : Boolean;
begin
LoadDefaultiOSDriver();
exit;
result := iOSDriver.IsShownKeyboard();
end;
function DefaultProcessAxisMotionEventProcedure() : AccelerometerMotion;
begin
LoadDefaultiOSDriver();
result := iOSDriver.ProcessAxisMotionEvent();
end;
function DefaultProcessTouchEventProcedure(touch : Pointer): FingerArray;
begin
LoadDefaultiOSDriver();
result := iOSDriver.ProcessTouchEvent(touch);
end;
function DefaultAxisToGProcedure(value : LongInt): Single;
begin
LoadDefaultiOSDriver();
result := iOSDriver.AxisToG(value);
end;
procedure DefaultInitProcedure();
begin
LoadDefaultiOSDriver();
{$IFDEF IOS}
iOSDriver.Init();
{$ENDIF}
end;
initialization
begin
iOSDriver.ShowKeyboard := @DefaultShowKeyboardProcedure;
iOSDriver.HideKeyboard := @DefaultHideKeyboardProcedure;
iOSDriver.ToggleKeyboard := @DefaultToggleKeyboardProcedure;
iOSDriver.IsShownKeyboard := @DefaultIsShownKeyboardProcedure;
iOSDriver.Init := @DefaultInitProcedure;
iOSDriver.ProcessAxisMotionEvent := @DefaultProcessAxisMotionEventProcedure;
iOSDriver.AxisToG := @DefaultAxisToGProcedure;
iOSDriver.ProcessTouchEvent := @DefaultProcessTouchEventProcedure;
iOSDriver.Init();
end;
end.
|
unit Produto;
interface
uses
DBXJSONReflect, RTTI, DBXPlatform, TipoProduto, Generics.Collections,
FornecedorProduto, Validade;
type
TDoubleInterceptor = class(TJSONInterceptor)
public
function StringConverter(Data: TObject; Field: string): string; override;
procedure StringReverter(Data: TObject; Field: string; Arg: string); override;
end;
TProduto = class
private
FCodigo: string;
FTipoProduto: TTipoProduto;
FDescricao: string;
FCodigoBarras: string;
[JSONReflect(ctString, rtString, TDoubleInterceptor, nil, true)]
FPrecoVenda: Currency;
FQuantidadeEstoque: Integer;
FFornecedores: TList<TFornecedorProduto>;
FValidades: TList<TValidade>;
FEstoqueMinimo: Integer;
FEndereco: string;
[JSONReflect(ctString, rtString, TDoubleInterceptor, nil, true)]
FMargemLucro: Currency;
[JSONReflect(ctString, rtString, TDoubleInterceptor, nil, true)]
FDescontoMaximoValor: Currency;
[JSONReflect(ctString, rtString, TDoubleInterceptor, nil, true)]
FDescontoMaximoPercentual: Currency;
public
property Codigo: string read FCodigo write FCodigo;
property TipoProduto: TTipoProduto read FTipoProduto write FTipoProduto;
property Descricao: string read FDescricao write FDescricao;
property CodigoBarras: string read FCodigoBarras write FCodigoBarras;
property PrecoVenda: Currency read FPrecoVenda write FPrecoVenda;
property QuantidadeEstoque: Integer read FQuantidadeEstoque write FQuantidadeEstoque;
property Fornecedores: TList<TFornecedorProduto> read FFornecedores write FFornecedores;
property Validades: TList<TValidade> read FValidades write FValidades;
property EstoqueMinimo: Integer read FEstoqueMinimo write FEstoqueMinimo;
property Endereco: string read FEndereco write FEndereco;
property MargemLucro: Currency read FMargemLucro write FMargemLucro;
property DescontoMaximoValor: Currency read FDescontoMaximoValor write FDescontoMaximoValor;
property DescontoMaximoPercentual: Currency read FDescontoMaximoPercentual write FDescontoMaximoPercentual;
constructor Create; overload;
constructor Create(Codigo: string); overload;
constructor Create(Codigo: string; TipoProduto: TTipoProduto; Descricao,
CodigoBarras: string; PrecoVenda: Currency; EstoqueMinimo: Integer; Fornecedores: TList<TFornecedorProduto>; Validades: TList<TValidade>; Endereco: string;
MargemLucro, DescontoMaximoValor, DescontoMaximoPercentual: Currency); overload;
destructor Destroy; override;
end;
implementation
{ TDoubleInterceptor }
function TDoubleInterceptor.StringConverter(Data: TObject; Field: string): string;
var
LRttiContext: TRttiContext;
LValue: Double;
begin
LValue := LRttiContext.GetType(Data.ClassType).GetField(Field).GetValue(Data).AsType<Double>;
Result := TDBXPlatform.JsonFloat(LValue);
end;
procedure TDoubleInterceptor.StringReverter(Data: TObject; Field, Arg: string);
var
LRttiContext: TRttiContext;
LValue: Double;
begin
LValue := TDBXPlatform.JsonToFloat(Arg);
LRttiContext.GetType(Data.ClassType).GetField(Field).SetValue(Data, TValue.From<Double>(LValue));
end;
{ TProduto }
constructor TProduto.Create;
begin
end;
constructor TProduto.Create(Codigo: string);
begin
Self.FCodigo := Codigo;
end;
constructor TProduto.Create(Codigo: string; TipoProduto: TTipoProduto; Descricao,
CodigoBarras: string; PrecoVenda: Currency; EstoqueMinimo: Integer; Fornecedores: TList<TFornecedorProduto>;
Validades: TList<TValidade>; Endereco: string; MargemLucro, DescontoMaximoValor, DescontoMaximoPercentual: Currency);
begin
Self.FCodigo := Codigo;
Self.FTipoProduto := TipoProduto;
Self.FDescricao := Descricao;
Self.FCodigoBarras := CodigoBarras;
Self.FPrecoVenda := PrecoVenda;
Self.FEstoqueMinimo := EstoqueMinimo;
Self.FFornecedores := Fornecedores;
Self.FValidades := Validades;
Self.FEndereco := Endereco;
Self.FMargemLucro := MargemLucro;
Self.FDescontoMaximoValor := DescontoMaximoValor;
Self.FDescontoMaximoPercentual := DescontoMaximoPercentual;
end;
destructor TProduto.Destroy;
begin
if (Assigned(FTipoProduto)) then
FTipoProduto.Free;
inherited;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.