text stringlengths 14 6.51M |
|---|
unit VisualClipboard;
interface
uses
Windows, Forms, Messages, SysUtils, Classes, Graphics, Controls, clipbrd;
type
TVisualClipboard = class(TGraphicControl)
private
FStream: TMemoryStream;
FDisplayString: WideString;
FDataTypeAsString: WideString;
FDisplayStringNeedsUpdate: Boolean;
FCaption: WideString;
procedure SetCaption(const Value: WideString);
protected
procedure Paint; override;
function DisplayString: WideString;
procedure UpdateDisplayString;
public
DumpFile: String;
constructor Create(AOwner: TComponent); override;
destructor Destroy;
procedure CopyClipboardFrom(AVisualClipboard: TVisualClipboard);
procedure SaveToFile(FileName: TFileName);
procedure LoadFromFile(FileName: TFileName);
procedure CopyFromClipboard;
procedure PasteToClipboard;
published
property Caption: WideString read FCaption write SetCaption;
property DragKind;
property DragCursor;
property DragMode;
property OnClick;
property OnDragDrop;
property OnDragOver;
property OnMouseDown;
property OnMouseUp;
property OnMouseMove;
end;
implementation
type
TMemoryStreamEx = class(TMemoryStream)
public
procedure WriteInteger(Value: Integer);
function ReadInteger: Integer;
procedure WriteBoolean(Value: Boolean);
function ReadBoolean: Boolean;
procedure WriteString(Value: string);
procedure WriteStringEx(Value: array of Char);
function ReadString: string;
end;
procedure TMemoryStreamEx.WriteInteger(Value: Integer);
begin
Write(Value, SizeOf(Value));
end;
function TMemoryStreamEx.ReadInteger: Integer;
begin
Read(Result, SizeOf(Result));
end;
procedure TMemoryStreamEx.WriteBoolean(Value: Boolean);
begin
WriteInteger(Integer(Value));
end;
function TMemoryStreamEx.ReadBoolean: Boolean;
begin
Result := Boolean(ReadInteger);
end;
procedure TMemoryStreamEx.WriteString(Value: string);
var
StrLength: Integer;
begin
StrLength := Length(Value);
WriteInteger(StrLength);
WriteBuffer(Value[1], StrLength);
end;
procedure TMemoryStreamEx.WriteStringEx(Value: array of Char);
var
S: string;
begin
S := Value;
WriteString(S);
end;
function TMemoryStreamEx.ReadString: string;
var
StrLength: Integer;
begin
StrLength := ReadInteger;
SetLength(Result, StrLength);
ReadBuffer(Result[1], StrLength);
end;
function ClearClipboard: Boolean;
begin
if GetOpenClipboardWindow() <> 0 then
Exit;
OpenClipboard(Application.Handle);
//ClipBrd.Clipboard.Open;
try
Result := EmptyClipboard;
finally
CloseClipboard;
// ClipBrd.Clipboard.Close;
end;
end;
procedure SaveClipboardToStream(Stream: TMemoryStreamEx; Format: Integer);
var
Data: THandle;
DataPtr: Pointer;
DataSize: LongInt;
buff: array[0..127] of Char;
CustomFormat: Boolean;
begin
if GetOpenClipboardWindow() <> 0 then
Exit;
OpenClipboard(Application.Handle);
//ClipBrd.Clipboard.Open;
try
Data := GetClipboardData(Format);
if Data <> 0 then
begin
DataPtr := GlobalLock(Data);
if DataPtr <> nil then
begin
DataSize := GlobalSize(Data);
try
FillChar(buff, SizeOf(buff), #0);
CustomFormat := GetClipboardFormatName(Format, @buff, SizeOf(buff)) <> 0;
Stream.WriteBoolean(CustomFormat);
if CustomFormat then
Stream.WriteString(buff) else
Stream.WriteInteger(Format);
Stream.WriteInteger(DataSize);
Stream.WriteBuffer(DataPtr^, DataSize);
finally
GlobalUnlock(Data);
end;
end;
end;
finally
CloseClipboard;
// ClipBrd.Clipboard.Close;
end;
end;
procedure LoadClipboardFromStream(Stream: TMemoryStreamEx);
var
Data: THandle;
DataPtr: Pointer;
DataSize: LongInt;
Format: Integer;
FormatName: string;
CustomFormat: Boolean;
begin
if GetOpenClipboardWindow() <> 0 then
Exit;
OpenClipboard(Application.Handle);
//ClipBrd.Clipboard.Open;
try
CustomFormat := Stream.ReadBoolean;
if CustomFormat then
begin
FormatName := Stream.ReadString;
Format := RegisterClipboardFormat(PChar(FormatName));
end else
begin
Format := Stream.ReadInteger;
end;
DataSize := Stream.ReadInteger;
Data := GlobalAlloc(GMEM_MOVEABLE, DataSize);
try
DataPtr := GlobalLock(Data);
try
Stream.ReadBuffer(DataPtr^, DataSize);
SetClipboardData(Format, Data);
finally
GlobalUnlock(Data);
end;
except
GlobalFree(Data);
raise;
end;
finally
CloseClipboard;
// / ClipBrd.Clipboard.Close;
end;
end;
procedure DrawNiceFrame(ACanvas: TCanvas; var ARect: TRect; AFaceColor,
AFrameColor, ABackColor: TColor; AFrameSize: Integer);
var
I: Integer;
begin
ACanvas.Brush.Color := ABackColor;
ACanvas.FillRect(Rect(ARect.Left, ARect.Top, ARect.Right, ARect.Top + 15));
ACanvas.Brush.Color := AFrameColor;
ACanvas.Pen.Color := AFrameColor;
ACanvas.MoveTo(ARect.Left + 5, ARect.Top); ACanvas.LineTo(ARect.Right - 5, ARect.Top);
ACanvas.MoveTo(ARect.Left + 3, ARect.Top + 1); ACanvas.LineTo(ARect.Right - 3, ARect.Top + 1);
ACanvas.MoveTo(ARect.Left + 2, ARect.Top + 2); ACanvas.LineTo(ARect.Right - 2, ARect.Top + 2);
ACanvas.MoveTo(ARect.Left + 1, ARect.Top + 3); ACanvas.LineTo(ARect.Right - 1, ARect.Top + 3);
ACanvas.MoveTo(ARect.Left + 1, ARect.Top + 4); ACanvas.LineTo(ARect.Right - 1, ARect.Top + 4);
ACanvas.Rectangle(Rect(ARect.Left, ARect.Top + 5, ARect.Right, ARect.Top + 15));
ACanvas.Pen.Width := 1;
ACanvas.Brush.Color := AFaceColor;
ARect.Top := ARect.Top + 15;
if AFrameSize > 0 then
begin
ACanvas.Pen.Color := AFrameColor;
ACanvas.Rectangle(ARect);
InflateRect(ARect, -1, -1);
for I := 1 to AFrameSize do
begin
ACanvas.Brush.Color := AFrameColor;
ACanvas.FrameRect(ARect);
InflateRect(ARect, -1, -1);
end;
end;
end;
{ TVisualClipboard }
procedure TVisualClipboard.CopyClipboardFrom(AVisualClipboard: TVisualClipboard);
begin
if Assigned(AVisualClipboard) then
begin
FreeAndNil(FStream);
FStream := TMemoryStreamEx.Create;
AVisualClipboard.FStream.Position := 0;
FStream.Size := AVisualClipboard.FStream.Size;
FStream.CopyFrom(AVisualClipboard.FStream, AVisualClipboard.FStream.Size);
FDisplayStringNeedsUpdate := True;
Invalidate;
Update;
end;
end;
procedure TVisualClipboard.CopyFromClipboard;
var
I: Integer;
begin
FreeAndNil(FStream);
FStream := TMemoryStreamEx.Create;
for I := 0 to Pred(Clipboard.FormatCount) do
SaveClipboardToStream(TMemoryStreamEx(FStream), Clipboard.Formats[I]);
FDisplayStringNeedsUpdate := True;
end;
constructor TVisualClipboard.Create(AOwner: TComponent);
begin
inherited;
FStream := TMemoryStreamEx.Create;
FDisplayString := '';
FDisplayStringNeedsUpdate := False;
end;
destructor TVisualClipboard.Destroy;
begin
if Assigned(FStream) then
FreeAndNil(FStream);
end;
function TVisualClipboard.DisplayString: WideString;
begin
if FDisplayStringNeedsUpdate then
UpdateDisplayString;
FDisplayStringNeedsUpdate := False;
Result := FDisplayString;
end;
procedure TVisualClipboard.LoadFromFile(FileName: TFileName);
begin
FStream.LoadFromFile(FileName);
FDisplayStringNeedsUpdate := True;
end;
procedure TVisualClipboard.Paint;
var
r1: TRect;
w: WideString;
begin
inherited;
r1 := ClientRect;
DrawNiceFrame(Canvas, r1, clWindow, 14914662, clWindow, 3);
InflateRect(r1, -3, -3);
w := DisplayString;
Canvas.Brush.Color := clWindow;
Canvas.Font.Color := clDkGray;
DrawTextExW(Canvas.Handle, PWideChar(w), Length(w), r1, DT_END_ELLIPSIS, nil);
r1 := Rect(12, 2, ClientWidth - 12, 15);
Canvas.Brush.Color := 14914662;
Canvas.Font.Color := clWhite;
w := FCaption + ' ' + FDataTypeAsString;
DrawTextExW(Canvas.Handle, PWideChar(w), Length(w), r1, DT_END_ELLIPSIS, nil);
end;
procedure TVisualClipboard.PasteToClipboard;
begin
ClearClipboard;
FStream.Position := 0;
while FStream.Position < FStream.Size do
LoadClipboardFromStream(TMemoryStreamEx(FStream));
end;
procedure TVisualClipboard.SaveToFile(FileName: TFileName);
begin
FStream.SaveToFile(FileName);
end;
procedure TVisualClipboard.SetCaption(const Value: WideString);
begin
if FCaption <> Value then
begin
FCaption := Value;
Invalidate;
end;
end;
procedure TVisualClipboard.UpdateDisplayString;
procedure ProcessClipboardFormat(Stream: TMemoryStreamEx);
var
DataSize: LongInt;
Format: Integer;
FormatName: string;
CustomFormat: Boolean;
AAnsiString: AnsiString;
begin
CustomFormat := Stream.ReadBoolean;
if CustomFormat then
begin
FormatName := Stream.ReadString;
FDisplayString := FDisplayString + FormatName + #13#10;
DataSize := Stream.ReadInteger;
Stream.Position := FStream.Position + DataSize;
end
else
begin
Format := Stream.ReadInteger;
DataSize := Stream.ReadInteger;
case Format of
{CF_TEXT,} CF_OEMTEXT: begin
if DataSize > 256 then
begin
SetLength(AAnsiString, 256);
Stream.ReadBuffer((@AAnsiString[1])^, 256);
FDisplayString := FDisplayString + AAnsiString + #13#10;
DataSize := DataSize - 256;
end
else
begin
SetLength(AAnsiString, DataSize);
Stream.ReadBuffer((@AAnsiString[1])^, DataSize);
FDisplayString := FDisplayString + AAnsiString + #13#10;
DataSize := 0;
end;
if FDataTypeAsString <> 'Bitmap' then
FDataTypeAsString := 'Text';
end;
CF_BITMAP,CF_DIB: FDataTypeAsString := 'Bitmap';
//CF_DIB: FDataTypeAsString := 'Bitmap';
{CF_BITMAP: FDisplayString := FDisplayString + 'CF_BITMAP' + #13#10;
CF_METAFILEPICT: FDisplayString := FDisplayString + 'CF_METAFILEPICT' + #13#10;
CF_SYLK: FDisplayString := FDisplayString + 'CF_SYLK' + #13#10;
CF_DIF: FDisplayString := FDisplayString + 'CF_DIF' + #13#10;
CF_TIFF: FDisplayString := FDisplayString + 'CF_TIFF' + #13#10;
CF_OEMTEXT: begin
end;
CF_DIB: FDisplayString := FDisplayString + 'CF_DIB' + #13#10;
CF_PALETTE: FDisplayString := FDisplayString + 'CF_PALETTE' + #13#10;
CF_PENDATA: FDisplayString := FDisplayString + 'CF_PENDATA' + #13#10;
CF_RIFF: FDisplayString := FDisplayString + 'CF_RIFF' + #13#10;
CF_WAVE: FDisplayString := FDisplayString + 'CF_WAVE' + #13#10;
CF_UNICODETEXT: begin
if DataSize > 512 then
begin
SetLength(AWideString, 256);
Stream.ReadBuffer((@AAnsiString[1])^, 2*256);
FDisplayString := FDisplayString + AWideString + #13#10;
DataSize := DataSize - 2*256;
end
else
begin
SetLength(AWideString, DataSize);
Stream.ReadBuffer((@AWideString[1])^, DataSize);
FDisplayString := FDisplayString + AWideString + #13#10;
DataSize := 0;
end;
end;
CF_ENHMETAFILE: FDisplayString := FDisplayString + 'CF_ENHMETAFILE' + #13#10;
CF_HDROP: FDisplayString := FDisplayString + 'CF_HDROP' + #13#10;
CF_LOCALE: FDisplayString := FDisplayString + 'CF_LOCALE' + #13#10;
CF_MAX: FDisplayString := FDisplayString + 'CF_MAX' + #13#10; }
else
// FDisplayString := FDisplayString + 'CF_UNKNOWN' + #13#10;
end;
FStream.Position := FStream.Position + DataSize;
end;
end;
begin
FDisplayString := '';
FStream.Position := 0;
FDataTypeAsString := '';
while FStream.Position < FStream.Size do
ProcessClipboardFormat(TMemoryStreamEx(FStream));
if (Pos('FileName', FDisplayString) > 0)and(Pos('FileNameW', FDisplayString) > 0)and(Pos('Ole Private Data', FDisplayString) > 0) then
begin
FDisplayString := '[File]';
FDataTypeAsString := 'Explorer';
end;
Hint := FDisplayString;
ShowHint := Length(FDisplayString) > 0;
end;
end.
|
unit uColorForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, VirtualTrees, VirtualExplorerTree, VirtualExplorerListviewEx,
VirtualShellUtilities, VirtualWideStrings, ImgList, VirtualUnicodeControls,
ComCtrls, StdCtrls, ExtCtrls;
type
TColorForm = class(TForm)
ListView1: TListView;
Button1: TButton;
ColorDialog1: TColorDialog;
Button2: TButton;
Bevel1: TBevel;
Button3: TButton;
procedure FormCreate(Sender: TObject);
procedure ListView1AdvancedCustomDrawItem(Sender: TCustomListView;
Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage;
var DefaultDraw: Boolean);
procedure FormDestroy(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
EL: TExtensionsList;
FThumbsHighlightColor: TColor;
public
{ Public declarations }
end;
var
ColorForm: TColorForm;
implementation
uses
Unit1;
{$R *.dfm}
procedure TColorForm.FormCreate(Sender: TObject);
var
I: integer;
begin
//Backup the Highlight properties
FThumbsHighlightColor := Form1.LVEx.ThumbsOptions.HighlightColor;
EL := TExtensionsList.Create;
EL.Assign(Form1.LVEx.ExtensionsList);
//Fill the Color Listview
for I := 0 to EL.Count - 1 do begin
with ListView1.Items.Add do
Caption := EL[I];
end;
end;
procedure TColorForm.FormDestroy(Sender: TObject);
begin
EL.Free;
end;
procedure TColorForm.ListView1AdvancedCustomDrawItem(
Sender: TCustomListView; Item: TListItem; State: TCustomDrawState;
Stage: TCustomDrawStage; var DefaultDraw: Boolean);
var
AColor: TColor;
begin
if (Stage = cdPrePaint) and Assigned(Item) and (Item.Index > -1) and (Item.Index < Listview1.Items.Count) then begin
if Form1.LVEx.ThumbsOptions.Highlight = thMultipleColors then begin
AColor := EL.Colors[Item.Index];
if AColor <> clNone then
Listview1.Canvas.Brush.Color := AColor;
end
else
if Form1.LVEx.ThumbsOptions.Highlight = thSingleColor then
Listview1.Canvas.Brush.Color := FThumbsHighlightColor;
end;
end;
procedure TColorForm.Button3Click(Sender: TObject);
var
LItem: TListItem;
begin
if (Form1.LVEx.ThumbsOptions.Highlight = thMultipleColors) and Assigned(ListView1.Selected) then begin
ColorDialog1.Color := EL.Colors[ListView1.Selected.Index];
if ColorDialog1.Execute then begin
LItem := Listview1.Selected;
while Assigned(LItem) do begin
EL.Colors[LItem.Index] := ColorDialog1.Color;
LItem := Listview1.GetNextItem(LItem, sdAll, [isSelected]);
end;
Listview1.Invalidate;
end;
end
else
if Form1.LVEx.ThumbsOptions.Highlight = thSingleColor then begin
ColorDialog1.Color := FThumbsHighlightColor;
if ColorDialog1.Execute then begin
FThumbsHighlightColor := ColorDialog1.Color;
Listview1.Invalidate;
end;
end;
end;
procedure TColorForm.Button2Click(Sender: TObject);
begin
//Reset
if Form1.LVEx.ThumbsOptions.Highlight = thMultipleColors then
Form1.LVEx.ExtensionsList.Assign(EL)
else
if Form1.LVEx.ThumbsOptions.Highlight = thSingleColor then
Form1.LVEx.ThumbsOptions.HighlightColor := FThumbsHighlightColor;
//Invalidate
Form1.LVEx.SyncInvalidate;
end;
end.
|
unit Cache.TrackPoints;
interface
uses
SysUtils,
Cache.Root,
Adapter.MySQL,
Geo.Pos,
ZConnection, ZDataset,
Ils.MySql.Conf,
uTrackPoints,
Math,
Generics.Collections,
Ils.Logger;
//------------------------------------------------------------------------------
type
TTrackCache = class(TCache)
public
procedure PushPicture(
const AObj: TCacheDataObjectAbstract
);
procedure UpdateOdometer(
const ADT: TDateTime;
const ADelta: Double
);
function GetBeforeByType(
const ADT: TDateTime;
const AType: TPointType
): TTrackPoint;
function GetAfterByType(
const ADT: TDateTime;
const AType: TPointType
): TTrackPoint;
end;
TTrackPointCacheDataAdapter = class(TCacheAdapterMySQL)
private
FInsertPictureQry: TZQuery;
FInsertSensorRawQry: TZQuery;
FUpdateLastInfoQry: TZQuery;
FImeiInsertQry: TZQuery;
FOdometerUpdateQry: TZQuery;
FDTMarkAfterByTypeQry: TZQuery;
FDTMarkBeforeByTypeQry: TZQuery;
FImeiHash: TDictionary<Int64, Int64>;
procedure InsertNewImei(AIMEI: Int64);
public
procedure Flush(
const ACache: TCache
); override;
procedure Add(
const ACache: TCache;
const AObj: TCacheDataObjectAbstract
); override;
procedure PushPicture(
const AObj: TCacheDataObjectAbstract
);
procedure UpdateOdometer(
const ACache: TCache;
const ADT: TDateTime; const ADelta: Double
);
procedure Change(
const ACache: TCache;
const AObj: TCacheDataObjectAbstract
); override;
function MakeObjFromReadQuery(
const AQuery: TZQuery
): TCacheDataObjectAbstract; override;
function GetDTMarkBeforeByType(
const ACache: TCache;
const ADT: TDateTime;
const AType: TPointType
): TDateTime;
function GetDTMarkAfterByType(
const ACache: TCache;
const ADT: TDateTime;
const AType: TPointType
): TDateTime;
constructor Create(
const AReadConnection, AWriteConnection: TZConnection
);
destructor Destroy; override;
end;
TTrackPointCacheDictionary = TCacheDictionary<Int64>;
implementation
{ TTrackPointCacheDataAdapter }
constructor TTrackPointCacheDataAdapter.Create(
const AReadConnection, AWriteConnection: TZConnection
);
//var
// SQLInsert: string;
// SQLUpdate: string;
// SQLReadBefore: string;
// SQLReadAfter: string;
// SQLReadRange: string;
// SQLDeleteOne: string;
// SQLInsertPicture: string;
// SQLInsertSensorRaw: string;
// SQLUpdateLastInfo: string;
// SQLImeiInsert: string;
// SQLOdometerUpdate: string;
const
FieldsSQL =
' Type = :Type, Speed = :Speed,'
+ ' Azimuth = :Azimuth,'
+ ' Distance = :Distance, Duration = :Duration,'
+ ' AngularSpeed = :AngularSpeed, RadialAcc = :RadialAcc,'
+ ' TangentialAcc = :TangentialAcc, Odometer = :Odometer'
;
Fields2SQL =
' Recieved = VALUES(Recieved), Offset = VALUES(Offset),'
+ ' Valid = VALUES(Valid), SatCount = VALUES(SatCount), Engine = VALUES(Engine),'
+ ' Latitude = VALUES(Latitude), Longitude = VALUES(Longitude), Altitude = VALUES(Altitude),'
+ ' Type = VALUES(Type), Speed = VALUES(Speed), DeviceSpeed = VALUES(DeviceSpeed),'
+ ' Azimuth = VALUES(Azimuth), DeviceAzimuth = VALUES(DeviceAzimuth),'
+ ' Distance = VALUES(Distance), Duration = VALUES(Duration),'
+ ' AngularSpeed = VALUES(AngularSpeed), RadialAcc = VALUES(RadialAcc),'
+ ' TangentialAcc = VALUES(TangentialAcc), Odometer = VALUES(Odometer)'
;
ReadRangeSQL = 'SELECT *'
+ ' FROM track'
+ ' WHERE IMEI = :imei'
+ ' AND DT >= :dt_from'
+ ' AND DT <= :dt_to'
;
ReadBeforeSQL = 'SELECT MAX(DT) as DT'
+ ' FROM track'
+ ' WHERE IMEI = :imei'
+ ' AND DT < :dt'
;
ReadAfterSQL = 'SELECT MIN(DT) as DT'
+ ' FROM track'
+ ' WHERE IMEI = :imei'
+ ' AND DT > :dt'
;
InsertSQL =
'insert into track set'
+ ' IMEI = :IMEI, DT = :DT,'
+ ' Offset = :Offset, Recieved = :Recieved,'
+ ' Valid = :Valid, SatCount = :SatCount, Engine = :Engine,'
+ ' Latitude = :Latitude, Longitude = :Longitude, Altitude = :Altitude,'
+ ' DeviceSpeed = :DeviceSpeed, DeviceAzimuth = :DeviceAzimuth,'
+ FieldsSQL
+ ' on duplicate key update'
+ Fields2SQL
;
UpdateSQL =
'update track set'
+ FieldsSQL
+ ' where'
+ ' IMEI = :IMEI'
+ ' and DT = :DT'
;
DeleteOneSQL =
'*';
InsertPictureSQL =
'insert ignore into trackpicture set'
+ ' IMEI = :IMEI,'
+ ' DT = :DT,'
+ ' Recieved = :Recieved,'
+ ' Picture = :Picture'
;
InsertSensorRawSQL =
'insert ignore into sensorraw set'
+ ' IMEI = :IMEI, DT = :DT,'
+ ' Raw = :Raw'
;
UpdateLastInfoSQL =
'CALL Mon_UpdateTrackerLastInfo('
+ ' :IMEI, :DT, :Recieved, :Valid,'
+ ' :SatCount, :Latitude, :Longitude,'
+ ' :Speed, :Azimuth, :Type, :Odometer'
+ ' );'
// 'insert into trackerlastinfo set'
// + ' IMEI = :IMEI, DT = :DT, Recieved = :Recieved, Valid = :Valid,'
// + ' SatCount = :SatCount, Latitude = :Latitude, Longitude = :Longitude,'
// + ' Speed = :Speed, Azimuth = :Azimuth, Type = :Type, Odometer = :Odometer'
// + ' on duplicate key update'
// + ' DT = VALUES(DT), Recieved = VALUES(Recieved), Valid = VALUES(Valid),'
// + ' SatCount = VALUES(SatCount), Latitude = VALUES(Latitude), Longitude = VALUES(Longitude),'
// + ' Speed = VALUES(Speed), Azimuth = VALUES(Azimuth), Type = VALUES(Type), Odometer = VALUES(Odometer)'
;
ImeiInsertSQL =
'insert ignore into'
+ ' tracker(IMEI, TrackerModelID, AccountID)'
+ ' values (:IMEI, :TrackerModelID, :AccountID);'
;
OdometerUpdateSQL =
'update track set odometer = odometer + :OdometerDelta'
+ ' where IMEI = :IMEI and DT >= :DT and Type in (0, 1);'
;
DTMarkAfterByTypeSQL =
'SELECT MIN(dt) AS DT FROM Track'
+ ' WHERE'
+ ' DT > :DT'
+ ' AND IMEI = :IMEI'
+ ' AND TYPE = :TYPE'
;
DTMarkBeforeByTypeSQL =
'SELECT MAX(dt) AS DT FROM Track'
+ ' WHERE'
+ ' DT < :DT'
+ ' AND IMEI = :IMEI'
+ ' AND TYPE = :TYPE'
;
begin
inherited Create(
AReadConnection, AWriteConnection,
InsertSQL, UpdateSQL, ReadBeforeSQL, ReadAfterSQL, ReadRangeSQL, DeleteOneSQL);
FInsertPictureQry := TZQuery.Create(nil);
FInsertPictureQry.Connection := AWriteConnection;
FInsertPictureQry.SQL.Text := InsertPictureSQL;
FInsertSensorRawQry := TZQuery.Create(nil);
FInsertSensorRawQry.Connection := AWriteConnection;
FInsertSensorRawQry.SQL.Text := InsertSensorRawSQL;
FUpdateLastInfoQry := TZQuery.Create(nil);
FUpdateLastInfoQry.Connection := AWriteConnection;
FUpdateLastInfoQry.SQL.Text := UpdateLastInfoSQL;
FImeiInsertQry := TZQuery.Create(nil);
FImeiInsertQry.Connection := AWriteConnection;
FImeiInsertQry.SQL.Text := ImeiInsertSQL;
FOdometerUpdateQry := TZQuery.Create(nil);
FOdometerUpdateQry.Connection := AWriteConnection;
FOdometerUpdateQry.SQL.Text := OdometerUpdateSQL;
FDTMarkAfterByTypeQry := TZQuery.Create(nil);
FDTMarkAfterByTypeQry.Connection := AReadConnection;
FDTMarkAfterByTypeQry.SQL.Text := DTMarkAfterByTypeSQL;
FDTMarkBeforeByTypeQry := TZQuery.Create(nil);
FDTMarkBeforeByTypeQry.Connection := AReadConnection;
FDTMarkBeforeByTypeQry.SQL.Text := DTMarkBeforeByTypeSQL;
FImeiHash := TDictionary<Int64, Int64>.Create;
end;
destructor TTrackPointCacheDataAdapter.Destroy;
begin
FInsertPictureQry.Free;
FInsertSensorRawQry.Free;
FUpdateLastInfoQry.Free;
FOdometerUpdateQry.Free;
FImeiHash.Free;
inherited;
end;
procedure TTrackPointCacheDataAdapter.Flush(const ACache: TCache);
begin
//
end;
function TTrackPointCacheDataAdapter.GetDTMarkAfterByType(
const ACache: TCache;
const ADT: TDateTime;
const AType: TPointType): TDateTime;
begin
Result := 0;
FillParamsFromKey(ACache.Key, FDTMarkAfterByTypeQry);
with FDTMarkAfterByTypeQry do
begin
Close;
ParamByName('DT').AsDateTime := ADT;
ParamByName('type').AsInteger := Ord(AType);
Open;
if RecordCount > 0 then
Result := FieldByName('DT').AsDateTime;
end;
end;
function TTrackPointCacheDataAdapter.GetDTMarkBeforeByType(
const ACache: TCache;
const ADT: TDateTime;
const AType: TPointType): TDateTime;
begin
Result := 0;
FillParamsFromKey(ACache.Key, FDTMarkBeforeByTypeQry);
with FDTMarkBeforeByTypeQry do
begin
Close;
ParamByName('DT').AsDateTime := ADT;
ParamByName('type').AsInteger := Ord(AType);
Open;
if RecordCount > 0 then
Result := FieldByName('DT').AsDateTime;
end;
end;
procedure TTrackPointCacheDataAdapter.InsertNewImei(AIMEI: Int64);
function ModelByIMEI(AIMEI2: Int64): Integer;
var
VendorImei: Integer;
begin
VendorImei := StrToIntDef(Copy(IntToStr(AIMEI2), 1, 2), 0);
case VendorImei of
35: Result := 8;//model 8, vendor 6 Teltonika
86: Result := 9;//model 9, vendor 10 Navtelecom
else Result := 0;
end;
end;
var
TrackerModel: Integer;
begin
if FImeiHash.ContainsKey(AIMEI) then
begin
FImeiHash[AIMEI] := FImeiHash[AIMEI] + 1;
Exit;
end;
try
FImeiInsertQry.ParamByName('imei').AsLargeInt := AIMEI;
TrackerModel := ModelByIMEI(AIMEI);
FImeiInsertQry.ParamByName('TrackerModelID').AsInteger := TrackerModel;//Unknown of vendor detected
FImeiInsertQry.ParamByName('AccountID').AsInteger := 1;//Root
FImeiInsertQry.ExecSQL;
FImeiHash.Add(AIMEI, 1);
// ToLog('IMEI ' + IntToStr(AIMEI) + ' inserted.');
except
on E: Exception do
ToLog('error on insert IMEI - ' + E.ClassName + ':' + E.Message);
end;
end;
procedure TTrackPointCacheDataAdapter.Add(
const ACache: TCache;
const AObj: TCacheDataObjectAbstract
);
begin
FillParamsFromKey(ACache.Key, FInsertQry);
FillParamsFromKey(ACache.Key, FInsertSensorRawQry);
FillParamsFromKey(ACache.Key, FUpdateLastInfoQry);
with (AObj as TTrackPoint), FInsertQry do
begin
Close;
ParamByName('DT').AsDateTime := DevicePoint.GeoTrackPoint.DateTime;
ParamByName('Recieved').AsDateTime := DevicePoint.RecievedDateTime;
ParamByName('Offset').AsLargeInt := Offset;
ParamByName('Valid').AsInteger := IfThen(DevicePoint.ValidCoordinates, 1, 0);
ParamByName('SatCount').AsInteger := DevicePoint.GeoTrackPoint.SatellitesCount;
ParamByName('Engine').AsInteger := IfThen(DevicePoint.EngineWorks, 1, 0);
ParamByName('Latitude').AsFloat := DevicePoint.GeoTrackPoint.Pos.Pos.Latitude;
ParamByName('Longitude').AsFloat := DevicePoint.GeoTrackPoint.Pos.Pos.Longitude;
ParamByName('Altitude').AsFloat := DevicePoint.GeoTrackPoint.Pos.Altitude;
// case PointType of
// ptStop,
// ptMove: ParamByName('Type').AsInteger := CPointType[PointType].Code;
// ptUnknown,
// ptInvalid,
// ptTimeIncorrect,
// ptDuplicated,
// ptGeoIncorrect,
// ptTimeHasMSec: ParamByName('Type').AsInteger := CPointType[ptUnknown].Code;
// ptPhysicsIncorrect,
// ptValid,
// ptUnique,
// ptGeoCorrect,
// ptPhysicsCorrect,
// ptTimeHasNoMSec: ParamByName('Type').AsInteger := CPointType[ptStop].Code;
// end;
ParamByName('Type').AsInteger := CPointType[PointType].Code;
ParamByName('DeviceSpeed').AsFloat := IfThen(IsInfinite(DevicePoint.Velocity), 0, DevicePoint.Velocity);
ParamByName('DeviceAzimuth').AsFloat := IfThen(IsInfinite(DevicePoint.Azimuth), 0, DevicePoint.Azimuth);
ParamByName('Speed').AsFloat := IfThen(IsInfinite(SpeedKmh), 0, SpeedKmh);
ParamByName('Azimuth').AsFloat := IfThen(IsInfinite(Azimuth), 0, Azimuth);
ParamByName('Distance').AsFloat := IfThen(IsInfinite(Distance), 0, Distance);
ParamByName('Duration').AsFloat := IfThen(IsInfinite(Duration), 0, Duration);
ParamByName('AngularSpeed').AsFloat := IfThen(IsInfinite(AngularSpeed), 0, AngularSpeed);
ParamByName('RadialAcc').AsFloat := IfThen(IsInfinite(RadialAcceleration), 0, RadialAcceleration);
ParamByName('TangentialAcc').AsFloat := IfThen(IsInfinite(TangentialAcceleration), 0, TangentialAcceleration);
ParamByName('Odometer').AsFloat := IfThen(IsInfinite(Odometer), 0, Odometer);
ExecSQL;
end;
with (AObj as TTrackPoint), FInsertSensorRawQry do
begin
Close;
ParamByName('DT').AsDateTime := DevicePoint.GeoTrackPoint.DateTime;
ParamByName('Raw').AsString := DevicePoint.SensorsJsonString;
ExecSQL();
end;
with (AObj as TTrackPoint), FUpdateLastInfoQry do
if PointType in CProperOdoPointTypes then
begin
Close;
ParamByName('SATCOUNT').AsInteger := DevicePoint.GeoTrackPoint.SatellitesCount;
ParamByName('LATITUDE').AsFloat := DevicePoint.GeoTrackPoint.Pos.Pos.Latitude;
ParamByName('LONGITUDE').AsFloat := DevicePoint.GeoTrackPoint.Pos.Pos.Longitude;
ParamByName('SPEED').AsFloat := IfThen(not IsInfinite(DevicePoint.Velocity), DevicePoint.Velocity, 0);
ParamByName('AZIMUTH').AsFloat := IfThen(not IsInfinite(DevicePoint.Azimuth), DevicePoint.Azimuth, 0);
ParamByName('TYPE').AsInteger := CPointType[PointType].Code;
ParamByName('DT').AsDateTime := DevicePoint.GeoTrackPoint.DateTime;
ParamByName('Recieved').AsDateTime := DevicePoint.RecievedDateTime;
ExecSQL();
end;
with (AObj as TTrackPoint) do
InsertNewImei(DevicePoint.DeviceID);
end;
procedure TTrackPointCacheDataAdapter.Change(
const ACache: TCache;
const AObj: TCacheDataObjectAbstract
);
begin
FillParamsFromKey(ACache.Key, FUpdateQry);
with (AObj as TTrackPoint), FUpdateQry do
begin
Close;
ParamByName('DT').AsDateTime := DevicePoint.GeoTrackPoint.DateTime;
ParamByName('Type').AsInteger := CPointType[PointType].Code;
ParamByName('Speed').AsFloat := IfThen(IsInfinite(SpeedKmh), 0, SpeedKmh);
ParamByName('Azimuth').AsFloat := IfThen(IsInfinite(Azimuth), 0, Azimuth);
ParamByName('Distance').AsFloat := IfThen(IsInfinite(Distance), 0, Distance);
ParamByName('Duration').AsFloat := IfThen(IsInfinite(Duration), 0, Duration);
ParamByName('AngularSpeed').AsFloat := IfThen(IsInfinite(AngularSpeed), 0, AngularSpeed);
ParamByName('RadialAcc').AsFloat := IfThen(IsInfinite(RadialAcceleration), 0, RadialAcceleration);
ParamByName('TangentialAcc').AsFloat := IfThen(IsInfinite(TangentialAcceleration), 0, TangentialAcceleration);
ParamByName('Odometer').AsFloat := IfThen(IsInfinite(Odometer), 0, Odometer);
ExecSQL;
end;
end;
function TTrackPointCacheDataAdapter.MakeObjFromReadQuery(
const AQuery: TZQuery
): TCacheDataObjectAbstract;
begin
with AQuery do
begin
Result :=
TTrackPoint.Create(
TDevicePoint.Create(
TGeoTrackPoint.Create(
FieldByName('Latitude').AsFloat,
FieldByName('Longitude').AsFloat,
FieldByName('DT').AsDateTime,
FieldByName('SatCount').AsInteger,
FieldByName('Altitude').AsFloat
),
nil,
FieldByName('IMEI').AsLargeInt,
FieldByName('Valid').AsInteger = 1,
FieldByName('Recieved').AsDateTime,
FieldByName('Engine').AsInteger = 1,
'',//FieldByName('Json').AsString,
FieldByName('Distance').AsFloat,
FieldByName('DeviceSpeed').AsFloat,
FieldByName('Azimuth').AsFloat,
0
), poDatabase,
GetPointTypeByCode(FieldByName('Type').AsInteger),
FieldByName('Odometer').AsFloat,
FieldByName('Offset').AsLargeInt
);
end;
end;
procedure TTrackPointCacheDataAdapter.PushPicture(const AObj: TCacheDataObjectAbstract);
begin
with (AObj as TTrackPicture), FInsertPictureQry do
begin
Close;
ParamByName('Imei').AsLargeInt := Imei;
ParamByName('DT').AsDateTime := DateTime;
ParamByName('Recieved').AsDateTime := Recieved;
ParamByName('Picture').AsBlob := Picture;
ExecSQL();
end;
end;
procedure TTrackPointCacheDataAdapter.UpdateOdometer(
const ACache: TCache;
const ADT: TDateTime; const ADelta: Double);
begin
FillParamsFromKey(ACache.Key, FOdometerUpdateQry);
with FOdometerUpdateQry do
begin
Close;
ParamByName('DT').AsDateTime := ADT;
ParamByName('OdometerDelta').AsFloat := ADelta;
ExecSQL;
end;
end;
{ TTrackCache }
function TTrackCache.GetAfterByType(const ADT: TDateTime; const AType: TPointType): TTrackPoint;
begin
Result := TTrackPoint(Get((FAdapter as TTrackPointCacheDataAdapter).GetDTMarkAfterByType(Self, ADT, AType)));
end;
function TTrackCache.GetBeforeByType(const ADT: TDateTime; const AType: TPointType): TTrackPoint;
begin
Result := TTrackPoint(Get((FAdapter as TTrackPointCacheDataAdapter).GetDTMarkBeforeByType(Self, ADT, AType)));
end;
procedure TTrackCache.PushPicture(const AObj: TCacheDataObjectAbstract);
begin
(FAdapter as TTrackPointCacheDataAdapter).PushPicture(AObj);
end;
procedure TTrackCache.UpdateOdometer(const ADT: TDateTime; const ADelta: Double);
begin
(FAdapter as TTrackPointCacheDataAdapter).UpdateOdometer(Self, ADT, ADelta);
end;
end.
|
{ Copyright (c) 1985, 87 by Borland International, Inc. }
unit MCOMMAND;
interface
uses Crt, Dos, MCVars, MCUtil, MCDisply, MCParser, MCLib, MCInput;
procedure CheckForSave;
{ If the spreadsheet has been changed, will ask the user if they want to
save it.
}
procedure MoveRowUp;
{ Moves up 1 row }
procedure MoveRowDown;
{ Moves down one row }
procedure MoveColLeft;
{ Moves left one column }
procedure MoveColRight;
{ Moves right one column }
procedure EditCell(ECell : CellPtr);
{ Edits a selected cell }
procedure ClearSheet;
{ Clears the current spreadsheet }
procedure LoadSheet(FileName : IString);
{ Loads a new spreadsheet }
procedure SaveSheet;
{ Saves the current spreadsheet }
function PageRows(Row : Word; TopPage, Border : Boolean) : Word;
{ Returns the number of rows to print }
function PageCols(Col, Columns : Word; Border : Boolean) : Word;
{ Returns the number of columns to print starting at col }
procedure PrintSheet;
{ Prints a copy of the spreadsheet to a file or to the printer }
procedure SetColWidth(Col : Word);
{ Sets the new column width for a selected column }
procedure GotoCell;
{ Moves to a selected cell }
procedure FormatCells;
{ Prompts the user for a selected format and range of cells }
procedure DeleteCol(Col : Word);
{ Deletes a column }
procedure InsertCol(Col : Word);
{ Inserts a column }
procedure DeleteRow(Row : Word);
{ Deletes a row }
procedure InsertRow(Row : Word);
{ Inserts a row }
procedure SMenu;
{ Executes the commands in the spreadsheet menu }
procedure CMenu;
{ Executes the commands in the column menu }
procedure RMenu;
{ Executes the commands in the row menu }
procedure UMenu;
{ Executes the commands in the utility menu }
procedure MainMenu;
{ Executes the commands in the main menu }
implementation
const
Name : String[80] = MSGNAME;
var
Rec : CellRec;
procedure CheckForSave;
var
Save : Char;
begin
if Changed and GetYesNo(Save, MSGSAVESHEET) and (Save = 'Y') then
SaveSheet;
end; { CheckForSave }
procedure MoveRowUp;
begin
DisplayCell(CurCol, CurRow, NOHIGHLIGHT, NOUPDATE);
if CurRow > TopRow then
Dec(CurRow)
else if TopRow > 1 then
begin
Scroll(DOWN, 1, Succ(LEFTMARGIN), 3, 80, ScreenRows + 2, WHITE);
Dec(TopRow);
DisplayRow(TopRow, NOUPDATE);
Dec(CurRow);
SetBottomRow;
end;
end; { MoveRowUp }
procedure MoveRowDown;
begin
DisplayCell(CurCol, CurRow, NOHIGHLIGHT, NOUPDATE);
if CurRow < BottomRow then
Inc(CurRow)
else if BottomRow < MAXROWS then
begin
Scroll(UP, 1, Succ(LEFTMARGIN), 3, 80, ScreenRows + 2, WHITE);
Inc(TopRow);
Inc(CurRow);
SetBottomRow;
DisplayRow(BottomRow, NOUPDATE);
end;
end; { MoveRowDown }
procedure MoveColLeft;
var
Col, OldLeftCol : Word;
OldColStart : array[1..SCREENCOLS] of Byte;
begin
OldLeftCol := LeftCol;
Move(ColStart, OldColStart, Sizeof(ColStart));
DisplayCell(CurCol, CurRow, NOHIGHLIGHT, NOUPDATE);
if (CurCol > LeftCol) then
Dec(CurCol)
else if (LeftCol <> 1) then
begin
Dec(CurCol);
Dec(LeftCol);
SetRightCol;
SetLeftCol;
if OldLeftCol <= RightCol then
Scroll(RIGHT, Pred(ColStart[Succ(OldLeftCol - LeftCol)] - LEFTMARGIN),
Succ(LEFTMARGIN), 3, 80, ScreenRows + 2, WHITE);
ClearLastCol;
for Col := LeftCol to Pred(OldLeftCol) do
DisplayCol(Col, NOUPDATE);
end;
end; { MoveColLeft }
procedure MoveColRight;
var
Col, OldLeftCol, OldRightCol : Word;
OldColStart : array[1..SCREENCOLS] of Byte;
begin
OldLeftCol := LeftCol;
Move(ColStart, OldColStart, Sizeof(ColStart));
OldRightCol := RightCol;
DisplayCell(CurCol, CurRow, NOHIGHLIGHT, NOUPDATE);
if CurCol < RightCol then
Inc(CurCol)
else if RightCol < MAXCOLS then
begin
Inc(CurCol);
Inc(RightCol);
SetLeftCol;
SetRightCol;
if OldRightCol >= LeftCol then
Scroll(LEFT, Pred(OldColStart[Succ(LeftCol - OldLeftCol)] - LEFTMARGIN),
Succ(LEFTMARGIN), 3, 80, ScreenRows + 2, WHITE);
ClearLastCol;
for Col := Succ(OldRightCol) to RightCol do
DisplayCol(Col, NOUPDATE);
end;
end; { MoveColRight }
procedure EditCell;
var
S : IString;
begin
if ECell = nil then
Exit;
case ECell^.Attrib of
TXT : S := ECell^.T;
VALUE : Str(ECell^.Value:1:MAXPLACES, S);
FORMULA : S := ECell^.Formula;
end; { case }
if (not EditString(S, '', MAXINPUT)) or (S = '') then
Exit;
Act(S);
Changed := True;
end; { EditCell }
procedure ClearSheet;
var
Col, Row : Word;
begin
for Row := 1 to LastRow do
begin
for Col := 1 to LastCol do
DeleteCell(Col, Row, NOUPDATE);
end;
InitVars;
SetRightCol;
SetBottomRow;
DisplayScreen(NOUPDATE);
PrintFreeMem;
Changed := False;
end; { ClearSheet }
procedure LoadSheet;
var
Dummy, Size, RealLastCol, RealLastRow : Word;
F : File;
Check : String[80];
Allocated : Boolean;
Blocks : Word;
RealSize : Byte;
begin
RealLastCol := 1;
RealLastRow := 1;
if FileName = '' then
begin
WritePrompt(MSGFILENAME);
if not EditString(FileName, '', MAXINPUT) then
Exit;
end;
if not Exists(FileName) then
begin
ErrorMsg(MSGNOEXIST);
Exit;
end;
Assign(F, FileName);
Reset(F, 1);
if IOResult <> 0 then
begin
ErrorMsg(MSGNOOPEN);
Exit;
end;
BlockRead(F, Check[1], Length(Name), Blocks);
Check[0] := Chr(Length(Name));
if Check <> Name then
begin
ErrorMsg(MSGNOMICROCALC);
Close(F);
Exit;
end;
BlockRead(F, Size, 1, Blocks);
BlockRead(F, RealSize, 1, Blocks);
if RealSize <> SizeOf(Real) then
begin
ErrorMsg(MSGBADREALS);
Close(F);
Exit;
end;
SetColor(PROMPTCOLOR);
GotoXY(1, ScreenRows + 5);
Write(MSGLOADING);
GotoXY(Succ(Length(MSGLOADING)), ScreenRows + 5);
ClearSheet;
BlockRead(F, LastCol, SizeOf(LastCol), Blocks);
BlockRead(F, LastRow, SizeOf(LastRow), Blocks);
BlockRead(F, Size, SizeOf(Size), Blocks);
BlockRead(F, ColWidth, Sizeof(ColWidth), Blocks);
repeat
BlockRead(F, CurCol, SizeOf(CurCol), Blocks);
BlockRead(F, CurRow, SizeOf(CurRow), Blocks);
BlockRead(F, Format[CurCol, CurRow], 1, Blocks);
BlockRead(F, Size, SizeOf(Size), Blocks);
BlockRead(F, Rec, Size, Blocks);
case Rec.Attrib of
TXT : begin
Allocated := AllocText(CurCol, CurRow, Rec.T);
if Allocated then
Dummy := SetOFlags(CurCol, CurRow, NOUPDATE);
end;
VALUE : Allocated := AllocValue(CurCol, CurRow, Rec.Value);
FORMULA : Allocated := AllocFormula(CurCol, CurRow, Rec.Formula,
Rec.Fvalue);
end; { case }
if not Allocated then
begin
ErrorMsg(MSGFILELOMEM);
LastRow := RealLastRow;
LastCol := RealLastCol;
Format[CurCol, CurRow] := DEFAULTFORMAT;
end
else begin
Cell[CurCol, CurRow]^.Error := Rec.Error;
if CurCol > RealLastCol then
RealLastCol := CurCol;
if CurRow > RealLastRow then
RealLastRow := CurRow;
end;
until (not Allocated) or (EOF(F));
PrintFreeMem;
Close(F);
CurCol := 1;
CurRow := 1;
SetRightCol;
DisplayScreen(NOUPDATE);
SetColor(White);
GotoXY(1, ScreenRows + 5);
ClrEol;
Changed := False;
end; { LoadSheet }
procedure SaveSheet;
var
FileName : IString;
EndOfFile, Overwrite : Char;
Size, Col, Row : Word;
F : File;
CPtr : CellPtr;
Blocks : Word;
RealSize : Byte;
begin
EndOfFile := #26;
FileName := '';
RealSize := SizeOf(Real);
WritePrompt(MSGFILENAME);
if not EditString(FileName, '', MAXINPUT) then
Exit;
Assign(F, FileName);
if Exists(FileName) then
begin
if (not GetYesNo(Overwrite, MSGOVERWRITE)) or (Overwrite = 'N') then
Exit;
Reset(F, 1);
end
else
Rewrite(F, 1);
if IOResult <> 0 then
begin
ErrorMsg(MSGNOOPEN);
Exit;
end;
SetColor(PROMPTCOLOR);
GotoXY(1, ScreenRows + 5);
Write(MSGSAVING);
GotoXY(Length(MSGSAVING) + 1, ScreenRows + 5);
BlockWrite(F, Name[1], Length(Name), Blocks);
BlockWrite(F, EndOfFile, 1, Blocks);
BlockWrite(F, RealSize, 1, Blocks);
BlockWrite(F, LastCol, SizeOf(LastCol), Blocks);
BlockWrite(F, LastRow, SizeOf(LastRow), Blocks);
Size := MAXCOLS;
BlockWrite(F, Size, SizeOf(Size), Blocks);
BlockWrite(F, ColWidth, Sizeof(ColWidth), Blocks);
for Row := 1 to LastRow do
begin
for Col := LastCol downto 1 do
begin
if Cell[Col, Row] <> nil then
begin
CPtr := Cell[Col, Row];
case CPtr^.Attrib of
TXT : Size := Length(CPtr^.T) + 3;
VALUE : Size := Sizeof(Real) + 2;
FORMULA : Size := Length(CPtr^.Formula) + Sizeof(Real) + 3;
end; { case }
BlockWrite(F, Col, SizeOf(Col), Blocks);
BlockWrite(F, Row, SizeOf(Row), Blocks);
BlockWrite(F, Format[Col, Row], 1, Blocks);
BlockWrite(F, Size, SizeOf(Size), Blocks);
BlockWrite(F, CPtr^, Size, Blocks);
end;
end;
end;
Close(F);
SetColor(White);
GotoXY(1, ScreenRows + 5);
ClrEol;
Changed := False;
end; { SaveSheet }
function PageRows;
var
Rows : Word;
begin
if TopPage then
Rows := 66 - TOPMARGIN
else
Rows := 66;
if Border then
Dec(Rows);
if Pred(Row + Rows) > LastRow then
PageRows := Succ(LastRow - Row)
else
PageRows := Rows;
end; { PageRows }
function PageCols;
var
Len : Integer;
FirstCol : Word;
begin
if (Col = 1) and Border then
Len := Columns - LEFTMARGIN
else
Len := Columns;
FirstCol := Col;
while (Len > 0) and (Col <= LastCol) do
begin
Dec(Len, ColWidth[Col]);
Inc(Col);
end;
if Len < 0 then
Dec(Col);
PageCols := Col - FirstCol;
end; { PageCols }
procedure PrintSheet;
var
FileName : IString;
S : String[132];
ColStr : String[MAXCOLWIDTH];
F : Text;
Columns, Counter1, Counter2, Counter3, Col, Row, LCol, LRow, Dummy,
Printed, OldLastCol : Word;
Answer : Char;
Border, TopPage : Boolean;
begin
Col := 1;
WritePrompt(MSGPRINT);
FileName := '';
if not EditString(FileName, '', MAXINPUT) then
Exit;
if FileName = '' then
FileName := 'PRN';
Assign(F, FileName);
{$I-}
Rewrite(F);
if IOResult <> 0 then
begin
ErrorMsg(MSGNOOPEN);
Exit;
end;
{$I+}
OldLastCol := LastCol;
for Counter1 := 1 to LastRow do
begin
for Counter2 := LastCol to MAXCOLS do
begin
if Format[Counter2, Counter1] >= OVERWRITE then
LastCol := Counter2;
end;
end;
if not GetYesNo(Answer, MSGCOLUMNS) then
Exit;
if Answer = 'Y' then
Columns := 132
else
Columns := 80;
if not GetYesNo(Answer, MSGBORDER) then
Exit;
Border := Answer = 'Y';
while Col <= LastCol do
begin
Row := 1;
TopPage := True;
LCol := PageCols(Col, Columns, Border) + Col;
while Row <= LastRow do
begin
LRow := PageRows(Row, TopPage, Border) + Row;
Printed := 0;
if TopPage then
begin
for Counter1 := 1 to TOPMARGIN do
begin
Writeln(F);
Inc(Printed);
end;
end;
for Counter1 := Row to Pred(LRow) do
begin
if Border and (Counter1 = Row) and (TopPage) then
begin
if (Col = 1) and Border then
begin
S[0] := Chr(LEFTMARGIN);
FillChar(S[1], LEFTMARGIN, ' ');
end
else
S := '';
for Counter3 := Col to Pred(LCol) do
begin
ColStr := CenterColString(Counter3);
S := S + ColStr;
end;
Writeln(F, S);
Printed := Succ(Printed);
end;
if (Col = 1) and Border then
S := Pad(WordToString(Counter1, 1), LEFTMARGIN)
else
S := '';
for Counter2 := Col to Pred(LCol) do
S := S + CellString(Counter2, Counter1, Dummy, DOFORMAT);
Writeln(F, S);
Inc(Printed);
end;
Row := LRow;
TopPage := False;
if Printed < 66 then
Write(F, FORMFEED);
end;
Col := LCol;
end;
Close(F);
LastCol := OldLastCol;
end; { PrintSheet }
procedure SetColWidth;
var
Width, Row : Word;
begin
WritePrompt(MSGCOLWIDTH);
if not GetWord(Width, MINCOLWIDTH, MAXCOLWIDTH) then
Exit;
ColWidth[Col] := Width;
SetRightCol;
if RightCol < Col then
begin
RightCol := Col;
SetLeftCol;
SetRightCol;
end;
for Row := 1 to LastRow do
begin
if (Cell[Col, Row] <> nil) and (Cell[Col, Row]^.Attrib = TXT) then
ClearOFlags(Succ(Col), Row, NOUPDATE)
else
ClearOFlags(Col, Row, NOUPDATE);
UpdateOFlags(Col, Row, NOUPDATE);
end;
DisplayScreen(NOUPDATE);
Changed := True;
end; { SetColWidth }
procedure GotoCell;
begin
WritePrompt(MSGGOTO);
if not GetCell(CurCol, CurRow) then
Exit;
LeftCol := CurCol;
TopRow := CurRow;
SetBottomRow;
SetRightCol;
SetLeftCol;
DisplayScreen(NOUPDATE);
end; { GotoCell }
procedure FormatCells;
var
Col, Row, Col1, Col2, Row1, Row2, NewFormat, ITemp : Word;
Temp : Char;
begin
NewFormat := 0;
WritePrompt(MSGCELL1);
if not GetCell(Col1, Row1) then
Exit;
WritePrompt(MSGCELL2);
if not GetCell(Col2, Row2) then
Exit;
if (Col1 <> Col2) and (Row1 <> Row2) then
ErrorMsg(MSGDIFFCOLROW)
else begin
if Col1 > Col2 then
Switch(Col1, Col2);
if Row1 > Row2 then
Switch(Row1, Row2);
if not GetYesNo(Temp, MSGRIGHTJUST) then
Exit;
NewFormat := NewFormat + (Ord(Temp = 'Y') * RJUSTIFY);
if not GetYesNo(Temp, MSGDOLLAR) then
Exit;
NewFormat := NewFormat + (Ord(Temp = 'Y') * DOLLAR);
if not GetYesNo(Temp, MSGCOMMAS) then
Exit;
NewFormat := NewFormat + (Ord(Temp = 'Y') * COMMAS);
if (NewFormat and DOLLAR) <> 0 then
NewFormat := NewFormat + 2
else begin
WritePrompt(MSGPLACES);
if not GetWord(ITemp, 0, MAXPLACES) then
Exit;
NewFormat := NewFormat + ITemp;
end;
for Col := Col1 to Col2 do
begin
for Row := Row1 to Row2 do
begin
Format[Col, Row] := (Format[Col, Row] and OVERWRITE) or NewFormat;
if (Col >= LeftCol) and (Col <= RightCol) and
(Row >= TopRow) and (Row <= BottomRow) then
DisplayCell(Col, Row, NOHIGHLIGHT, NOUPDATE);
end;
end;
end;
Changed := True;
end; { FormatCells }
procedure DeleteCol;
var
OldLastCol, Counter, Row : Word;
begin
if Col > LastCol then
Exit;
OldLastCol := LastCol;
for Counter := 1 to LastRow do
DeleteCell(Col, Counter, NOUPDATE);
PrintFreeMem;
if Col <> OldLastCol then
begin
Move(Cell[Succ(Col), 1], Cell[Col, 1], MAXROWS * Sizeof(CellPtr) *
(OldLastCol - Col));
Move(Format[Succ(Col), 1], Format[Col, 1], MAXROWS * (OldLastCol - Col));
Move(ColWidth[Succ(Col)], ColWidth[Col], OldLastCol - Col);
end;
FillChar(Cell[OldLastCol, 1], MAXROWS * Sizeof(CellPtr), 0);
FillChar(Format[OldLastCol, 1], MAXROWS, DEFAULTFORMAT);
ColWidth[OldLastCol] := DEFAULTWIDTH;
SetRightCol;
if CurCol > RightCol then
begin
Inc(RightCol);
SetLeftCol;
end;
ClearLastCol;
if OldLastCol = LastCol then
Dec(LastCol);
for Counter := 1 to LastCol do
begin
for Row := 1 to LastRow do
begin
if (Cell[Counter, Row] <> nil) and
(Cell[Counter, Row]^.Attrib = FORMULA) then
FixFormula(Counter, Row, COLDEL, Col);
UpdateOFlags(Col, Row, NOUPDATE);
end;
end;
for Counter := Col to RightCol do
DisplayCol(Counter, NOUPDATE);
LastCol := MAXCOLS;
SetLastCol;
Changed := True;
Recalc;
end; { DeleteCol }
procedure InsertCol;
var
Counter, Row : Word;
begin
if (LastCol = MAXCOLS) or (Col > LastCol) then
Exit;
if Col <> LastCol then
begin
Move(Cell[Col, 1], Cell[Col + 1, 1], MAXROWS * Sizeof(CellPtr) *
Succ(LastCol - Col));
Move(Format[Col, 1], Format[Col + 1, 1], MAXROWS * Succ(LastCol - Col));
Move(ColWidth[Col], ColWidth[Col + 1], Succ(LastCol - Col));
end;
if LastCol < MAXCOLS then
Inc(LastCol);
FillChar(Cell[Col, 1], MAXROWS * Sizeof(CellPtr), 0);
FillChar(Format[Col, 1], MAXROWS, DEFAULTFORMAT);
ColWidth[Col] := DEFAULTWIDTH;
SetRightCol;
if CurCol > RightCol then
begin
Inc(RightCol);
SetLeftCol;
end;
for Counter := 1 to LastCol do
begin
for Row := 1 to LastRow do
begin
if (Cell[Counter, Row] <> nil) and
(Cell[Counter, Row]^.Attrib = FORMULA) then
FixFormula(Counter, Row, COLADD, Col);
UpdateOFlags(Col, Row, NOUPDATE);
end;
end;
for Counter := Col to RightCol do
DisplayCol(Counter, NOUPDATE);
LastCol := MAXCOLS;
SetLastCol;
Changed := True;
Recalc;
end; { InsertCol }
procedure DeleteRow;
var
OldLastRow, Counter, RowC : Word;
begin
if Row > LastRow then
Exit;
OldLastRow := LastRow;
for Counter := 1 to LastCol do
DeleteCell(Counter, Row, NOUPDATE);
PrintFreeMem;
if Row <> OldLastRow then
begin
for Counter := 1 to MAXCOLS do
begin
Move(Cell[Counter, Succ(Row)], Cell[Counter, Row],
Sizeof(CellPtr) * (OldLastRow - Row));
Move(Format[Counter, Succ(Row)], Format[Counter, Row],
OldLastRow - Row);
end;
end;
for Counter := 1 to LastCol do
begin
Cell[Counter, OldLastRow] := nil;
Format[Counter, OldLastRow] := DEFAULTFORMAT;
end;
if OldLastRow = LastRow then
Dec(LastRow);
for Counter := 1 to LastCol do
begin
for RowC := 1 to LastRow do
begin
if (Cell[Counter, RowC] <> nil) and
(Cell[Counter, RowC]^.Attrib = FORMULA) then
FixFormula(Counter, RowC, ROWDEL, Row);
end;
end;
for Counter := Row to BottomRow do
DisplayRow(Counter, NOUPDATE);
LastRow := MAXROWS;
SetLastRow;
Changed := True;
Recalc;
end; { DeleteRow }
procedure InsertRow;
var
Counter, RowC : Word;
begin
if (LastRow = MAXROWS) or (Row > LastRow) then
Exit;
if Row <> LastRow then
begin
for Counter := 1 to MAXCOLS do
begin
Move(Cell[Counter, Row], Cell[Counter, Succ(Row)],
Sizeof(CellPtr) * Succ(LastRow - Row));
Move(Format[Counter, Row], Format[Counter, Succ(Row)],
Succ(LastRow - Row));
end;
end;
Inc(LastRow);
for Counter := 1 to LastCol do
begin
Cell[Counter, Row] := nil;
Format[Counter, Row] := DEFAULTFORMAT;
end;
for Counter := 1 to LastCol do
begin
for RowC := 1 to LastRow do
begin
if (Cell[Counter, RowC] <> nil) and
(Cell[Counter, RowC]^.Attrib = FORMULA) then
FixFormula(Counter, RowC, ROWADD, Row);
end;
end;
for Counter := Row to BottomRow do
DisplayRow(Counter, NOUPDATE);
LastRow := MAXROWS;
SetLastRow;
Changed := True;
Recalc;
end; { InsertRow }
procedure SMenu;
var
FileName : IString;
X : Word;
begin
FileName := '';
case GetCommand(SMNU, SCOMMAND) of
1 : begin
CheckForSave;
LoadSheet(FileName);
end;
2 : SaveSheet;
3 : PrintSheet;
4 : begin
CheckForSave;
ClearSheet;
end;
end; { case }
end; { SMenu }
procedure CMenu;
begin
case GetCommand(CMNU, CCOMMAND) of
1 : InsertCol(CurCol);
2 : DeleteCol(CurCol);
3 : SetColWidth(CurCol);
end; { case }
end; { CMenu }
procedure RMenu;
begin
case GetCommand(RMNU, RCOMMAND) of
1 : InsertRow(CurRow);
2 : DeleteRow(CurRow);
end; { case }
end; { CMenu }
procedure UMenu;
begin
case GetCommand(UMenuString, UCommandString) of
1 : Recalc;
2 : begin
ChangeFormDisplay(not FormDisplay);
DisplayScreen(UPDATE);
end;
3 : begin
if ScreenRows = 38 then
begin
ScreenRows := 20;
TextMode(Lo(LastMode));
SetCursor(NoCursor);
RedrawScreen;
end
else begin
TextMode(Lo(LastMode) + Font8x8);
if (LastMode and Font8x8) <> 0 then
begin
ScreenRows := 38;
SetCursor(NoCursor);
RedrawScreen;
end;
end;
end;
end; { case }
end; { UMenu }
procedure MainMenu;
begin
case GetCommand(MNU, COMMAND) of
1 : SMenu;
2 : FormatCells;
3 : begin
DeleteCell(CurCol, CurRow, UPDATE);
PrintFreeMem;
if AutoCalc then
Recalc;
end;
4 : GotoCell;
5 : CMenu;
6 : RMenu;
7 : EditCell(CurCell);
8 : UMenu;
9 : ChangeAutoCalc(not AutoCalc);
10 : begin
CheckForSave;
Stop := True;
end;
end; { case }
GotoXY(1, ScreenRows + 4);
ClrEol;
end; { MainMenu }
begin
end.
|
unit ibSHDescriptionFrm;
interface
uses
SHDesignIntf, SHEvents, ibSHDesignIntf, ibSHDriverIntf, ibSHComponentFrm,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
ExtCtrls, Dialogs, SynEdit, pSHSynEdit, ActnList, ImgList, ComCtrls,
ToolWin, AppEvnts, Menus;
type
TibBTDescriptionForm = class(TibBTComponentForm)
pSHSynEdit1: TpSHSynEdit;
private
{ Private declarations }
FDBObjectIntf: IibSHDBObject;
protected
{ ISHRunCommands }
function GetCanRun: Boolean; override;
procedure Run; override;
function DoOnOptionsChanged: Boolean; override;
public
{ Public declarations }
constructor Create(AOwner: TComponent; AParent: TWinControl;
AComponent: TSHComponent; ACallString: string); override;
destructor Destroy; override;
property DBObject: IibSHDBObject read FDBObjectIntf;
end;
TibBTDescriptionFormAction_ = class(TSHAction)
public
constructor Create(AOwner: TComponent); override;
function SupportComponent(const AClassIID: TGUID): Boolean; override;
procedure EventExecute(Sender: TObject); override;
procedure EventHint(var HintStr: String; var CanShow: Boolean); override;
procedure EventUpdate(Sender: TObject); override;
end;
TibBTDescriptionFormAction_Run = class(TibBTDescriptionFormAction_)
end;
var
ibBTDescriptionForm: TibBTDescriptionForm;
procedure Register;
implementation
uses
ibSHConsts;
{$R *.dfm}
procedure Register;
begin
SHRegisterImage(TibBTDescriptionFormAction_Run.ClassName, 'Button_Run.bmp');
SHRegisterActions([
TibBTDescriptionFormAction_Run]);
end;
{ TibBTDescriptionForm }
constructor TibBTDescriptionForm.Create(AOwner: TComponent; AParent: TWinControl;
AComponent: TSHComponent; ACallString: string);
begin
inherited Create(AOwner, AParent, AComponent, ACallString);
Supports(Component, IibSHDBObject, FDBObjectIntf);
Assert(DBObject <> nil, 'DBObject = nil');
Editor := pSHSynEdit1;
Editor.Lines.Clear;
Editor.Lines.AddStrings(DBObject.Description);
FocusedControl := Editor;
DoOnOptionsChanged;
end;
destructor TibBTDescriptionForm.Destroy;
begin
if GetCanRun then Run;
inherited Destroy;
end;
function TibBTDescriptionForm.GetCanRun: Boolean;
begin
Result := Assigned(Editor) and Editor.Modified;
end;
procedure TibBTDescriptionForm.Run;
begin
DBObject.Description.Assign(Editor.Lines);
DBObject.SetDescription;
Editor.Modified := False;
Designer.UpdateObjectInspector;
end;
function TibBTDescriptionForm.DoOnOptionsChanged: Boolean;
begin
Result := inherited DoOnOptionsChanged;
if Result and Assigned(Editor) then
begin
Editor.Highlighter := nil;
// Принудительная установка фонта
Editor.Font.Charset := 1;
Editor.Font.Color := clWindowText;
Editor.Font.Height := -13;
Editor.Font.Name := 'Courier New';
Editor.Font.Pitch := fpDefault;
Editor.Font.Size := 10;
Editor.Font.Style := [];
end;
end;
{ TibBTDescriptionFormAction_ }
constructor TibBTDescriptionFormAction_.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallToolbar;
if Self is TibBTDescriptionFormAction_Run then Tag := 1;
case Tag of
0: Caption := '-'; // separator
1:
begin
Caption := Format('%s', ['Run']);
ShortCut := TextToShortCut('Ctrl+Enter');
SecondaryShortCuts.Add('F9');
end;
end;
if Tag <> 0 then Hint := Caption;
end;
function TibBTDescriptionFormAction_.SupportComponent(const AClassIID: TGUID): Boolean;
begin
Result := IsEqualGUID(AClassIID, IibSHDomain) or
IsEqualGUID(AClassIID, IibSHTable) or
//IsEqualGUID(AClassIID, IibSHConstraint) or
IsEqualGUID(AClassIID, IibSHIndex) or
IsEqualGUID(AClassIID, IibSHView) or
IsEqualGUID(AClassIID, IibSHProcedure) or
IsEqualGUID(AClassIID, IibSHTrigger) or
//IsEqualGUID(AClassIID, IibSHGenerator) or
IsEqualGUID(AClassIID, IibSHException) or
IsEqualGUID(AClassIID, IibSHFunction) or
IsEqualGUID(AClassIID, IibSHFilter) or
IsEqualGUID(AClassIID, IibSHRole) or
//IsEqualGUID(AClassIID, IibSHSystemDomain) or
IsEqualGUID(AClassIID, IibSHSystemTable) or
IsEqualGUID(AClassIID, IibSHSystemTableTmp);
end;
procedure TibBTDescriptionFormAction_.EventExecute(Sender: TObject);
begin
case Tag of
// Run
1: (Designer.CurrentComponentForm as ISHRunCommands).Run;
end;
end;
procedure TibBTDescriptionFormAction_.EventHint(var HintStr: String; var CanShow: Boolean);
begin
end;
procedure TibBTDescriptionFormAction_.EventUpdate(Sender: TObject);
begin
if Assigned(Designer.CurrentComponentForm) and
AnsiSameText(Designer.CurrentComponentForm.CallString, SCallDescription) then
begin
case Tag of
// Separator
0:
begin
Visible := True;
end;
// Run
1:
begin
Visible := True;
Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRun;
end;
end;
end else
Visible := False;
end;
initialization
Register;
end.
|
// Event manager
//
// Copyright (C) 2004 Apus Software (www.games4win.com)
// Author: Ivan Polyacov (cooler@tut.by, ivan@apus-software.com)
//
// Основные категории иерархии:
// debug\ - отладочные события
// kbd\ - события связанные с клавой (KeyDown, KeyUp)
// mouse\ - события, связанные с мышью (Move, Delta, BtnDown, BtnUp)
// net\ - события, связанные с приемом/передачей данных в сети
// error\ - ошибки
// engine\ - события в движке
// UI\ - события интерфейса пользователя
unit EventMan;
interface
type
// Режим обработки (режим привязывается обработчиком событий)
TEventMode=(sync, // события помещаются в очередь потока
async, // обработчик вызывается немедленно в контексте того потока, где произошло событие
mixed); // если событие произошло в том же потоке - обрабатывается немедленно, иначе - в очередь
// Строка, определяющая событие
// Имеет формат: category\subcategory\..\sub..subcategory\name
EventStr=string[127];
// Функция обработки события. Для блокировки обработки на более общих уровнях, должна вернуть false
// In fact, return value is ignored
TEventHandler=function(event:EventStr;tag:integer):boolean;
// Установить обработчик для категории событий
// При возникновении события, сперва вызываются более конкретные обработчики, а затем более общие
procedure SetEventHandler(event:EventStr;handler:TEventHandler;mode:TEventMode=ASync);
// Убрать обработчик
procedure RemoveEventHandler(handler:TEventHandler;event:EventStr='');
// Сигнал о возникновении события (обрабатывается немедленно - в контексте текущего потока)
procedure Signal(event:EventStr;tag:integer=0);
procedure DelayedSignal(event:EventStr;delay:integer;tag:integer=0);
// Обработать сигналы синхронно (если поток регистрирует синхронные обработчики, то он обязан регулярно вызывать эту функцию)
procedure HandleSignals;
// Связать событие с другим событием (тэг при этом может быть новым, но если это -1, то сохраняется старый)
// Если redirect=true - при наличии линка отменет обработку сигнала на более общих уровнях
procedure Link(event,newEvent:EventStr;tag:integer=-1;redirect:boolean=false);
// Удалить связь между событиями
procedure Unlink(event,linkedEvent:EventStr);
// Удалить все связанные события (втч для всех подсобытий)
procedure UnlinkAll(event:EventStr='');
implementation
uses CrossPlatform, SysUtils, MyServis;
type
PHandler=^THandler;
THandler=record
event:EventStr;
handler:TEventHandler;
threadNum:integer; // индекс в массиве нитей (-1 - асинхронная обработка)
mode:TEventMode;
next:PHandler;
end;
PLink=^TLink;
TLink=record
event:EventStr;
LinkedEvent:EventStr;
tag:integer;
next:PLink;
redirect,keepOriginalTag:boolean;
end;
// Элемент очереди событий
TQueuedEvent=record
event:EventStr; // событие
handler:TEventHandler; // кто должен его обработать
tag:integer;
time:int64; // когда событие должно быть обработано (только для отложенных сигналов)
callerThread:TThreadID; // поток, из которого было
callerIP:cardinal; // точка вызова Signal
end;
// Очередь событий для каждого потока, в котором есть какие-либо обработчики сигналов
TThreadQueue=record
thread:TThreadId;
queue:array[0..127] of TQueuedEvent;
delayed:array[0..15] of TQueuedEvent;
first,last,delcnt:byte;
procedure LogQueueDump; // пишет в лог состояние всей очереди
end;
var
// Обработчики событий
handlers:array[0..255] of PHandler;
threads:array of TThreadQueue;
threadCnt:integer=0;
// Стек событий (макс. глубина - 8 событий)
StackSize:integer=0;
// EventStack:array[1..8] of EventStr;
eventnum:integer=0;
// stacklog:string;
links:array[0..255] of PLink;
CritSect:TMyCriticalSection;
{$R-}
procedure TThreadQueue.LogQueueDump;
var
i:integer;
st:string;
begin
st:='';
i:=first;
while i<>last do begin
with queue[i] do
st:=st+Format(#13#10' (thr:%d) %.8x -> %s:%d ',[callerThread,callerIP,event,tag]);
i:=(i+1) and 127;
end;
ForceLogMessage('Thread '+GetThreadName+' event queue: '+st);
st:=''; i:=0;
while i<delCnt do begin
with delayed[i] do
st:=st+Format(#13#10' (thr:%d) %.8x -> %s:%d at %d',[callerThread,callerIP,event,tag,time]);
inc(i);
end;
ForceLogMessage('Thread '+GetThreadName+' delayed event queue: '+st);
end;
function Hash(st:EventStr):byte;
var
i:integer;
begin
result:=length(st);
for i:=1 to Min2(length(st),30) do
inc(result,byte(st[i]));
end;
procedure SetEventHandler(event:EventStr;handler:TEventHandler;mode:TEventMode=ASync);
var
ThreadID:TThreadID;
i,n:integer;
ph:PHandler;
begin
// Если обработчик уже есть - повторно установлен не будет
try
EnterCriticalSection(CritSect);
if event[length(event)]='\' then setlength(event,length(event)-1);
if mode<>async then begin
ThreadID:=GetCurrentThreadID;
n:=-1;
for i:=1 to threadCnt do
if threads[i-1].Thread=threadID then n:=i-1;
if n=-1 then begin
n:=ThreadCnt; inc(ThreadCnt);
SetLength(threads,ThreadCnt);
threads[n].Thread:=ThreadID;
threads[n].first:=0;
threads[n].last:=0;
threads[n].delcnt:=0;
end;
end else
n:=-1;
event:=UpperCase(event);
i:=hash(event);
// поиск имеющегося обработчика
ph:=handlers[i];
while ph<>nil do begin
if (@ph.handler=@handler) and (ph.event=event) then exit;
ph:=ph.next;
end;
new(ph);
ph.event:=event;
ph.handler:=handler;
ph.threadNum:=n;
ph.mode:=mode;
ph.next:=handlers[i];
handlers[i]:=ph;
finally
LeaveCriticalSection(CritSect);
end;
end;
procedure RemoveEventHandler(handler:TEventHandler;event:EventStr='');
var
i:integer;
ph,prev,next:PHandler;
begin
EnterCriticalSection(CritSect);
try
if stacksize>0 then LogMessage('EventMan: Warning - removing event handler during signal processing, not a good style...',4);
for i:=0 to 255 do
if handlers[i]<>nil then begin
ph:=handlers[i]; prev:=nil;
repeat
if (@ph.handler=@handler) and
((event='') or (event=ph.event)) then begin
next:=ph.next;
if prev=nil then handlers[i]:=next else prev.next:=next;
dispose(ph);
ph:=next;
end else begin
prev:=ph;
ph:=ph.next;
end;
until ph=nil;
end;
finally
LeaveCriticalSection(CritSect);
end;
end;
// Для внутреннего использования
procedure HandleEvent(event:EventStr;tag:integer;time:int64;caller:cardinal=0);
var
i,h:integer;
fl:boolean;
hnd:PHandler;
link:PLink;
ev:EventStr;
trID:TThreadID;
cnt:integer;
hndlist:array[1..150] of TEventHandler;
begin
ev:=event;
event:=UpperCase(event);
trID:=GetCurrentThreadID;
try
repeat
cnt:=0;
// Поиск обработчиков
h:=Hash(event);
hnd:=handlers[h];
while hnd<>nil do begin
if hnd.event=event then
if (hnd.mode=sync) or ((hnd.mode=mixed) and (threads[hnd.threadNum].Thread<>trID)) then
with threads[hnd.threadNum] do begin
if time>0 then begin
if delcnt>=15 then begin
ForceLogMessage('EventMan: thread delayed queue overflow, event: '+ev+', handler: '+inttohex(cardinal(@hnd.handler),8));
LogQueueDump;
Sleep(1000);
HandleEvent('Error\EventMan\QueueOverflow',cardinal(Thread),0,caller);
end;
delayed[delcnt].event:=ev;
delayed[delcnt].handler:=hnd.handler;
delayed[delcnt].tag:=tag;
delayed[delcnt].time:=time;
delayed[delCnt].callerThread:=trID;
delayed[delCnt].callerIP:=caller;
inc(delcnt);
end else begin
queue[last].event:=ev;
queue[last].handler:=hnd.handler;
queue[last].tag:=tag;
queue[last].callerThread:=trID;
queue[last].callerIP:=caller;
last:=(last+1) and 127;
if last=first then begin
first:=(first+1) and 127;
ForceLogMessage('EventMan: thread queue overflow, event: '+ev+', handler: '+inttohex(cardinal(@hnd.handler),8));
LogQueueDump;
Sleep(1000);
HandleEvent('Error\EventMan\QueueOverflow',cardinal(Thread),0,caller);
end;
end;
end else begin
if cnt<150 then inc(cnt);
hndlist[cnt]:=hnd.handler;
end;
hnd:=hnd.next;
end;
LeaveCriticalSection(CritSect);
try
// Вызовы обработчиков вынесены в безопасный код для достижения реентабельности
for i:=1 to cnt do
try
hndList[i](ev,tag);
except
on e:exception do ForceLogMessage('Error in event handler: '+ev+' - '+e.message);
end;
finally
EnterCriticalSection(CritSect);
end;
// Обработка связей
link:=links[h];
fl:=false;
while link<>nil do begin
if link.event=event then begin
if link.keepOriginalTag then
HandleEvent(link.LinkedEvent,tag,time,caller)
else
HandleEvent(link.LinkedEvent,link.tag,time,caller);
if link.redirect then fl:=true;
end;
link:=link.next;
end;
if fl then break;
// Переход к более общему событию
fl:=true;
for i:=length(event) downto 1 do
if event[i]='\' then begin
SetLength(event,i-1);
fl:=false;
break;
end;
until fl;
finally
{ dec(StackSize);
if stacksize=0 then stacklog:='';}
end;
end;
procedure Signal(event:EventStr;tag:integer=0);
var
callerIP:cardinal; // адрес, откуда вызвана процедура
begin
if event='' then exit;
asm
mov eax,[ebp+4]
mov callerIP,eax
end;
// LogMessage('Signal: '+event+'='+inttostr(tag)+' thread='+inttostr(GetCurrentThreadID),4);
EnterCriticalSection(CritSect);
try
HandleEvent(event,tag,0,callerIP);
finally
LeaveCriticalSection(CritSect);
end;
end;
procedure DelayedSignal(event:EventStr;delay:integer;tag:integer=0);
begin
EnterCriticalSection(CritSect);
try
HandleEvent(event,tag,MyTickCount+delay);
finally
LeaveCriticalSection(CritSect);
end;
end;
procedure HandleSignals;
type
TCall=record
proc:TEventHandler;
event:Eventstr;
tag:integer;
end;
{ TThreadQueue }
var
ID:TThreadID;
t:int64;
i,j:integer;
calls:array[1..100] of TCall;
count:integer;
begin
EnterCriticalSection(CritSect);
try
ID:=GetCurrentThreadID;
count:=0;
for i:=1 to threadCnt do // Выбор очереди текущего потока
if threads[i-1].Thread=ID then with threads[i-1] do begin
while first<>last do begin
if count=100 then break;
inc(count);
calls[count].proc:=queue[first].handler;
calls[count].event:=queue[first].event;
calls[count].tag:=queue[first].tag;
first:=(first+1) and 127;
end;
if delcnt>0 then begin
t:=MyTickCount; j:=0;
while j<delcnt do begin
if delayed[j].time<t then begin
if count=100 then break;
inc(count);
calls[count].proc:=delayed[j].handler;
calls[count].event:=delayed[j].event;
calls[count].tag:=delayed[j].tag;
dec(delcnt);
delayed[j]:=delayed[delcnt];
end else inc(j);
end;
end;
break;
end;
finally
LeaveCriticalSection(CritSect);
end;
for i:=1 to count do try
calls[i].proc(calls[i].event,calls[i].tag);
except
on e:exception do ForceLogMessage(Format('Error in handling event: %s:%d Thread: %s - %s ',
[calls[i].event,calls[i].tag,GetThreadName,e.message]));
end;
end;
procedure Link(event,newEvent:EventStr;tag:integer=-1;redirect:boolean=false);
var
n:byte;
link:PLink;
begin
EnterCriticalSection(CritSect);
try
event:=UpperCase(event);
n:=Hash(event);
new(link);
link.next:=links[n];
links[n]:=link;
link.event:=event;
link.LinkedEvent:=UpperCase(newEvent);
link.tag:=tag;
link.redirect:=redirect;
link.keepOriginalTag:=tag=-1;
finally
LeaveCriticalSection(CritSect);
end;
end;
// Для внутреннего использования
procedure DeleteLink(hash:byte;var prev,link:PLink);
var
s:PLink;
begin
s:=link.next;
if prev<>nil then begin
prev.next:=link.next;
end else links[hash]:=link.next;
Dispose(link);
link:=s;
end;
procedure Unlink(event,linkedEvent:EventStr);
var
n:byte;
prev,link:PLink;
begin
EnterCriticalSection(CritSect);
try
n:=Hash(event);
prev:=nil; link:=links[n];
if link=nil then exit;
event:=UpperCase(event);
linkedEvent:=UpperCase(linkedEvent);
repeat
if (link.event=event) and
(UpperCase(link.LinkedEvent)=linkedEvent) then
DeleteLink(n,prev,link)
else begin
prev:=link;
link:=link.next;
end;
until link=nil;
finally
LeaveCriticalSection(CritSect);
end;
end;
procedure UnlinkAll(event:EventStr='');
var
i:integer;
prev,link:PLink;
begin
EnterCriticalSection(CritSect);
try
for i:=0 to 255 do
if links[i]<>nil then begin
prev:=nil; link:=links[i];
repeat
if link.event=event then DeleteLink(i,prev,link)
else begin
prev:=link;
link:=link.next;
end;
until link=nil;
end;
finally
LeaveCriticalSection(CritSect);
end;
end;
initialization
InitCritSect(critSect,'EventMan',300);
// InitializeCriticalSection(critSect);
finalization
DeleteCritSect(critSect);
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Console.Command.Sources;
interface
uses
VSoft.CancellationToken,
DPM.Core.Configuration.Interfaces,
DPM.Core.Logging,
DPM.Console.ExitCodes,
DPM.Console.Command.Base,
DPM.Core.Sources.Interfaces;
type
TSourcesCommand = class(TBaseCommand)
private
FSourcesManager : ISourcesManager;
protected
function Execute(const cancellationToken : ICancellationToken) : TExitCode; override;
function ForceNoBanner: Boolean; override;
public
constructor Create(const logger : ILogger; const configurationManager : IConfigurationManager; const sourcesManager : ISourcesManager);reintroduce;
end;
implementation
uses
System.SysUtils,
VSoft.Uri,
DPM.Core.Types,
DPM.Core.Options.Common,
DPM.Core.Options.Sources,
DPM.Core.Sources.Types;
{ TSourcesCommand }
constructor TSourcesCommand.Create(const logger: ILogger; const configurationManager : IConfigurationManager; const sourcesManager : ISourcesManager);
begin
inherited Create(logger,configurationManager);
FSourcesManager := sourcesManager;
end;
function TSourcesCommand.Execute(const cancellationToken : ICancellationToken) : TExitCode;
var
bResult : boolean;
newConfig : IConfiguration;
uri : IUri;
sUriError : string;
begin
TSourcesOptions.Default.ApplyCommon(TCommonOptions.Default);
if not (TSourcesOptions.Default.Command in [TSourcesSubCommand.Invalid, TSourcesSubCommand.List]) then
begin
//name is required
if TSourcesOptions.Default.Name = '' then
begin
Logger.Error('Name is required for this command.');
result := TExitCode.MissingArg;
exit;
end;
end;
//TODO : Find a way to do this for all commands that might write to a new config file.
if not FileExists(TSourcesOptions.Default.ConfigFile) then
begin
newConfig := FConfigurationManager.NewConfig;
FConfigurationManager.SaveConfig(newConfig,TSourcesOptions.Default.ConfigFile);
end;
Logger.Information('');
result := TExitCode.OK;
case TSourcesOptions.Default.Command of
TSourcesSubCommand.Invalid:
begin
Logger.Error('invalid command');
result := TExitCode.InvalidArguments;
exit;
end;
TSourcesSubCommand.Add :
begin
if TSourcesOptions.Default.Source = '' then
begin
Logger.Error('Source is required for this command.');
result := TExitCode.MissingArg;
exit;
end;
if not TUriFactory.TryParseWithError(TSourcesOptions.Default.Source, false, uri, sUriError) then
begin
Logger.Error('Source uri is not valid : ' + sUriError);
result := TExitCode.InvalidArguments;
exit;
end;
//this logic is not quite all there.. more testing required.
if (uri.Scheme = 'file') and (TSourcesOptions.Default.SourceType <> TSourceType.Folder) then
begin
Logger.Error('Source uri is not valid for folder source');
result := TExitCode.InvalidArguments;
exit;
end
else if uri.Scheme <> 'file' then
begin
if (uri.Scheme = 'http') or (uri.Scheme = 'https') then
TSourcesOptions.Default.SourceType := TSourceType.DPMServer
else
raise Exception.Create('Invalid source uri scheme' + uri.Scheme);
end;
bResult := FSourcesManager.AddSource(TSourcesOptions.Default);
end;
TSourcesSubCommand.Remove : bResult := FSourcesManager.RemoveSource(TSourcesOptions.Default);
TSourcesSubCommand.List : bResult := FSourcesManager.ListSources(TSourcesOptions.Default);
TSourcesSubCommand.Enable : bResult := FSourcesManager.EnableSource(TSourcesOptions.Default);
TSourcesSubCommand.Disable: bResult := FSourcesManager.DisableSource(TSourcesOptions.Default);
TSourcesSubCommand.Update : bResult := FSourcesManager.UpdateSource(TSourcesOptions.Default);
else
result := TExitCode.NotImplemented;
exit;
end;
if not bResult then
result := TExitCode.Error;
end;
function TSourcesCommand.ForceNoBanner: Boolean;
begin
result := true;
end;
end.
|
{
Clever Internet Suite Version 6.2
Copyright (C) 1999 - 2006 Clever Components
www.CleverComponents.com
}
unit clDEditors;
interface
{$I clVer.inc}
uses
Classes, {$IFDEF DELPHI6}DesignEditors, DesignIntf, {$ELSE} DsgnIntf, {$ENDIF}
TypInfo, ShellApi, Windows, dialogs, Forms, Sysutils;
type
TclBaseEditor = class(TComponentEditor)
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
TclSaveFileProperty = class(TStringProperty)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
TclOpenFileProperty = class(TStringProperty)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
implementation
const
hcSaveToFileDialog = 0;
hcOpenFileDialog = 0;
cSite = 'http://www.clevercomponents.com';
cVersion = 'Version 6.2';
{ TclBaseEditor }
procedure TclBaseEditor.ExecuteVerb(Index: Integer);
begin
case Index of
0: ShellExecute(0, 'open', cSite, nil, nil, SW_SHOW);
end;
end;
function TclBaseEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := cSite;
1: Result := cVersion;
end;
end;
function TclBaseEditor.GetVerbCount: Integer;
begin
Result := 2;
end;
{ TclSaveFileProperty }
procedure TclSaveFileProperty.Edit;
var
dlg: TSaveDialog;
begin
dlg := TSaveDialog.Create(Application);
try
dlg.Filename := GetValue();
dlg.InitialDir := ExtractFilePath(dlg.Filename);
dlg.Filter := '*.*';
dlg.HelpContext := hcSaveToFileDialog;
dlg.Options := dlg.Options + [ofShowHelp, ofEnableSizing];
if dlg.Execute then SetValue(dlg.Filename);
finally
dlg.Free();
end;
end;
function TclSaveFileProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paRevertable];
end;
{ TclOpenFileProperty }
procedure TclOpenFileProperty.Edit;
var
dlg: TOpenDialog;
begin
dlg := TOpenDialog.Create(Application);
try
dlg.Filename := GetValue();
dlg.InitialDir := ExtractFilePath(dlg.Filename);
dlg.Filter := '*.*';
dlg.HelpContext := hcOpenFileDialog;
dlg.Options := dlg.Options + [ofShowHelp, ofEnableSizing];
if dlg.Execute then SetValue(dlg.Filename);
finally
dlg.Free();
end;
end;
function TclOpenFileProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paRevertable];
end;
end.
|
////////////////////////////////////////////////////////////////////////////
// PaxCompiler
// Site: http://www.paxcompiler.com
// Author: Alexander Baranovsky (paxscript@gmail.com)
// ========================================================================
// Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved.
// Code Version: 4.2
// ========================================================================
// Unit: PAXCOMP_DISASM.pas
// ========================================================================
////////////////////////////////////////////////////////////////////////////
{$I PaxCompiler.def}
unit PAXCOMP_DISASM;
interface
uses {$I uses.def}
SysUtils,
PAXCOMP_CONSTANTS,
PAXCOMP_SYS;
type
TArg = packed record
valid: Boolean;
Reg: Byte;
Ptr: Boolean;
sz: Byte;
val: Int64;
FS: Boolean;
end;
procedure Decomp(P: Pointer; var Length: Integer; var op: Integer;
var Arg1: TArg;
var Arg2: TArg;
PAX64: Boolean);
procedure ClearArg(var Arg: TArg);
function EqualArgs(const Arg1, Arg2: TArg): Boolean;
procedure SaveDecompiledCode(P: Pointer;
CodeSize: Integer; const FileName: String; PAX64: Boolean);
function ArgToString(const Arg: TArg; PAX64: Boolean): String;
procedure DiscardDebugMode(P: Pointer; CodeSize: Integer; PAX64: Boolean);
function GetInitializationOffset(P: Pointer; CodeSize: Integer; PAX64: Boolean): Integer;
function GetFinalizationOffset(P: Pointer; CodeSize: Integer; PAX64: Boolean): Integer;
implementation
procedure RaiseError(const Message: string; params: array of Const);
begin
raise Exception.Create(Format(Message, params));
end;
function GetNextByte(var P: Pointer): Byte;
begin
P := ShiftPointer(P, 1);
result := Byte(P^);
end;
function AssignXMM_RegPtr(B: Byte; var Arg1: TArg; var Arg2: TArg): Boolean;
begin
result := true;
case B of
$00:
begin
Arg1.Reg := _XMM0;
Arg2.Reg := _EAX;
end;
$01:
begin
Arg1.Reg := _XMM0;
Arg2.Reg := _ECX;
end;
$02:
begin
Arg1.Reg := _XMM0;
Arg2.Reg := _EDX;
end;
$03:
begin
Arg1.Reg := _XMM0;
Arg2.Reg := _EBX;
end;
$08:
begin
Arg1.Reg := _XMM1;
Arg2.Reg := _EAX;
end;
$09:
begin
Arg1.Reg := _XMM1;
Arg2.Reg := _ECX;
end;
$0A:
begin
Arg1.Reg := _XMM1;
Arg2.Reg := _EDX;
end;
$0B:
begin
Arg1.Reg := _XMM1;
Arg2.Reg := _EBX;
end;
$10:
begin
Arg1.Reg := _XMM2;
Arg2.Reg := _EAX;
end;
$11:
begin
Arg1.Reg := _XMM2;
Arg2.Reg := _ECX;
end;
$12:
begin
Arg1.Reg := _XMM2;
Arg2.Reg := _EDX;
end;
$13:
begin
Arg1.Reg := _XMM2;
Arg2.Reg := _EBX;
end;
$18:
begin
Arg1.Reg := _XMM3;
Arg2.Reg := _EAX;
end;
$19:
begin
Arg1.Reg := _XMM3;
Arg2.Reg := _ECX;
end;
$1A:
begin
Arg1.Reg := _XMM3;
Arg2.Reg := _EDX;
end;
$1B:
begin
Arg1.Reg := _XMM3;
Arg2.Reg := _EBX;
end;
$20:
begin
Arg1.Reg := _XMM4;
Arg2.Reg := _EAX;
end;
$21:
begin
Arg1.Reg := _XMM4;
Arg2.Reg := _ECX;
end;
$22:
begin
Arg1.Reg := _XMM4;
Arg2.Reg := _EDX;
end;
$23:
begin
Arg1.Reg := _XMM4;
Arg2.Reg := _EBX;
end;
else
begin
result := false;
end;
end;
end;
function AssignRegMovESIPtr(B: Byte; var Arg: TArg): Boolean;
begin
result := true;
case B of
$86: Arg.Reg := _EAX;
$8E: Arg.Reg := _ECX;
$96: Arg.Reg := _EDX;
$9E: Arg.Reg := _EBX;
$A6: Arg.Reg := _ESP;
$AE: Arg.Reg := _EBP;
$B6: Arg.Reg := _ESI;
$BE: Arg.Reg := _EDI;
else
result := false;
end;
end;
function AssignRegMovEBPPtr(B: Byte; var Arg: TArg): Boolean;
begin
result := true;
case B of
$85: Arg.Reg := _EAX;
$8D: Arg.Reg := _ECX;
$95: Arg.Reg := _EDX;
$9D: Arg.Reg := _EBX;
$A5: Arg.Reg := _ESP;
$AD: Arg.Reg := _EBP;
$B5: Arg.Reg := _ESI;
$BD: Arg.Reg := _EDI;
else
result := false;
end;
end;
function AssignRegMovRSIPtr(B: Byte; var Arg: TArg): Boolean;
begin
result := true;
case B of
$86: Arg.Reg := _R8;
$8E: Arg.Reg := _R9;
$96: Arg.Reg := _R10;
$9E: Arg.Reg := _R11;
$A6: Arg.Reg := _R12;
$AE: Arg.Reg := _R13;
$B6: Arg.Reg := _R14;
$BE: Arg.Reg := _R15;
else
result := false;
end;
end;
function AssignRegMovRBPPtr(B: Byte; var Arg: TArg): Boolean;
begin
result := true;
case B of
$85: Arg.Reg := _R8;
$8D: Arg.Reg := _R9;
$95: Arg.Reg := _R10;
$9D: Arg.Reg := _R11;
$A5: Arg.Reg := _R12;
$AD: Arg.Reg := _R13;
$B5: Arg.Reg := _R14;
$BD: Arg.Reg := _R15;
else
result := false;
end;
end;
function AssignMovR32_R64(B: Byte; var Arg1, Arg2: TArg): Boolean;
begin
result := true;
case B of
$C0: begin Arg1.Reg := _EAX; Arg2.Reg := _R8; end;
$C8: begin Arg1.Reg := _EAX; Arg2.Reg := _R9; end;
$D0: begin Arg1.Reg := _EAX; Arg2.Reg := _R10; end;
$D8: begin Arg1.Reg := _EAX; Arg2.Reg := _R11; end;
$E0: begin Arg1.Reg := _EAX; Arg2.Reg := _R12; end;
$E8: begin Arg1.Reg := _EAX; Arg2.Reg := _R13; end;
$F0: begin Arg1.Reg := _EAX; Arg2.Reg := _R14; end;
$F8: begin Arg1.Reg := _EAX; Arg2.Reg := _R15; end;
$C1: begin Arg1.Reg := _ECX; Arg2.Reg := _R8; end;
$C9: begin Arg1.Reg := _ECX; Arg2.Reg := _R9; end;
$D1: begin Arg1.Reg := _ECX; Arg2.Reg := _R10; end;
$D9: begin Arg1.Reg := _ECX; Arg2.Reg := _R11; end;
$E1: begin Arg1.Reg := _ECX; Arg2.Reg := _R12; end;
$E9: begin Arg1.Reg := _ECX; Arg2.Reg := _R13; end;
$F1: begin Arg1.Reg := _ECX; Arg2.Reg := _R14; end;
$F9: begin Arg1.Reg := _ECX; Arg2.Reg := _R15; end;
$C2: begin Arg1.Reg := _EDX; Arg2.Reg := _R8; end;
$CA: begin Arg1.Reg := _EDX; Arg2.Reg := _R9; end;
$D2: begin Arg1.Reg := _EDX; Arg2.Reg := _R10; end;
$DA: begin Arg1.Reg := _EDX; Arg2.Reg := _R11; end;
$E2: begin Arg1.Reg := _EDX; Arg2.Reg := _R12; end;
$EA: begin Arg1.Reg := _EDX; Arg2.Reg := _R13; end;
$F2: begin Arg1.Reg := _EDX; Arg2.Reg := _R14; end;
$FA: begin Arg1.Reg := _EDX; Arg2.Reg := _R15; end;
$C3: begin Arg1.Reg := _EBX; Arg2.Reg := _R8; end;
$CB: begin Arg1.Reg := _EBX; Arg2.Reg := _R9; end;
$D3: begin Arg1.Reg := _EBX; Arg2.Reg := _R10; end;
$DB: begin Arg1.Reg := _EBX; Arg2.Reg := _R11; end;
$E3: begin Arg1.Reg := _EBX; Arg2.Reg := _R12; end;
$EB: begin Arg1.Reg := _EBX; Arg2.Reg := _R13; end;
$F3: begin Arg1.Reg := _EBX; Arg2.Reg := _R14; end;
$FB: begin Arg1.Reg := _EBX; Arg2.Reg := _R15; end;
$C4: begin Arg1.Reg := _ESP; Arg2.Reg := _R8; end;
$CC: begin Arg1.Reg := _ESP; Arg2.Reg := _R9; end;
$D4: begin Arg1.Reg := _ESP; Arg2.Reg := _R10; end;
$DC: begin Arg1.Reg := _ESP; Arg2.Reg := _R11; end;
$E4: begin Arg1.Reg := _ESP; Arg2.Reg := _R12; end;
$EC: begin Arg1.Reg := _ESP; Arg2.Reg := _R13; end;
$F4: begin Arg1.Reg := _ESP; Arg2.Reg := _R14; end;
$FC: begin Arg1.Reg := _ESP; Arg2.Reg := _R15; end;
$C5: begin Arg1.Reg := _EBP; Arg2.Reg := _R8; end;
$CD: begin Arg1.Reg := _EBP; Arg2.Reg := _R9; end;
$D5: begin Arg1.Reg := _EBP; Arg2.Reg := _R10; end;
$DD: begin Arg1.Reg := _EBP; Arg2.Reg := _R11; end;
$E5: begin Arg1.Reg := _EBP; Arg2.Reg := _R12; end;
$ED: begin Arg1.Reg := _EBP; Arg2.Reg := _R13; end;
$F5: begin Arg1.Reg := _EBP; Arg2.Reg := _R14; end;
$FD: begin Arg1.Reg := _EBP; Arg2.Reg := _R15; end;
$C6: begin Arg1.Reg := _ESI; Arg2.Reg := _R8; end;
$CE: begin Arg1.Reg := _ESI; Arg2.Reg := _R9; end;
$D6: begin Arg1.Reg := _ESI; Arg2.Reg := _R10; end;
$DE: begin Arg1.Reg := _ESI; Arg2.Reg := _R11; end;
$E6: begin Arg1.Reg := _ESI; Arg2.Reg := _R12; end;
$EE: begin Arg1.Reg := _ESI; Arg2.Reg := _R13; end;
$F6: begin Arg1.Reg := _ESI; Arg2.Reg := _R14; end;
$FE: begin Arg1.Reg := _ESI; Arg2.Reg := _R15; end;
$C7: begin Arg1.Reg := _EDI; Arg2.Reg := _R8; end;
$CF: begin Arg1.Reg := _EDI; Arg2.Reg := _R9; end;
$D7: begin Arg1.Reg := _EDI; Arg2.Reg := _R10; end;
$DF: begin Arg1.Reg := _EDI; Arg2.Reg := _R11; end;
$E7: begin Arg1.Reg := _EDI; Arg2.Reg := _R12; end;
$EF: begin Arg1.Reg := _EDI; Arg2.Reg := _R13; end;
$F7: begin Arg1.Reg := _EDI; Arg2.Reg := _R14; end;
$FF: begin Arg1.Reg := _EDI; Arg2.Reg := _R15; end;
else
result := false;
end;
end;
function AssignMovR64_R32(B: Byte; var Arg1, Arg2: TArg): Boolean;
begin
result := true;
case B of
$C0: begin Arg1.Reg := _R8; Arg2.Reg := _EAX; end;
$C8: begin Arg1.Reg := _R8; Arg2.Reg := _ECX; end;
$D0: begin Arg1.Reg := _R8; Arg2.Reg := _EDX; end;
$D8: begin Arg1.Reg := _R8; Arg2.Reg := _EBX; end;
$E0: begin Arg1.Reg := _R8; Arg2.Reg := _ESP; end;
$E8: begin Arg1.Reg := _R8; Arg2.Reg := _EBP; end;
$F0: begin Arg1.Reg := _R8; Arg2.Reg := _ESI; end;
$F8: begin Arg1.Reg := _R8; Arg2.Reg := _EDI; end;
$C1: begin Arg1.Reg := _R9; Arg2.Reg := _EAX; end;
$C9: begin Arg1.Reg := _R9; Arg2.Reg := _ECX; end;
$D1: begin Arg1.Reg := _R9; Arg2.Reg := _EDX; end;
$D9: begin Arg1.Reg := _R9; Arg2.Reg := _EBX; end;
$E1: begin Arg1.Reg := _R9; Arg2.Reg := _ESP; end;
$E9: begin Arg1.Reg := _R9; Arg2.Reg := _EBP; end;
$F1: begin Arg1.Reg := _R9; Arg2.Reg := _ESI; end;
$F9: begin Arg1.Reg := _R9; Arg2.Reg := _EDI; end;
$C2: begin Arg1.Reg := _R10; Arg2.Reg := _EAX; end;
$CA: begin Arg1.Reg := _R10; Arg2.Reg := _ECX; end;
$D2: begin Arg1.Reg := _R10; Arg2.Reg := _EDX; end;
$DA: begin Arg1.Reg := _R10; Arg2.Reg := _EBX; end;
$E2: begin Arg1.Reg := _R10; Arg2.Reg := _ESP; end;
$EA: begin Arg1.Reg := _R10; Arg2.Reg := _EBP; end;
$F2: begin Arg1.Reg := _R10; Arg2.Reg := _ESI; end;
$FA: begin Arg1.Reg := _R10; Arg2.Reg := _EDI; end;
$C3: begin Arg1.Reg := _R11; Arg2.Reg := _EAX; end;
$CB: begin Arg1.Reg := _R11; Arg2.Reg := _ECX; end;
$D3: begin Arg1.Reg := _R11; Arg2.Reg := _EDX; end;
$DB: begin Arg1.Reg := _R11; Arg2.Reg := _EBX; end;
$E3: begin Arg1.Reg := _R11; Arg2.Reg := _ESP; end;
$EB: begin Arg1.Reg := _R11; Arg2.Reg := _EBP; end;
$F3: begin Arg1.Reg := _R11; Arg2.Reg := _ESI; end;
$FB: begin Arg1.Reg := _R11; Arg2.Reg := _EDI; end;
$C6: begin Arg1.Reg := _R14; Arg2.Reg := _EAX; end;
$CE: begin Arg1.Reg := _R14; Arg2.Reg := _ECX; end;
$D6: begin Arg1.Reg := _R14; Arg2.Reg := _EDX; end;
$DE: begin Arg1.Reg := _R14; Arg2.Reg := _EBX; end;
$E6: begin Arg1.Reg := _R14; Arg2.Reg := _ESP; end;
$EE: begin Arg1.Reg := _R14; Arg2.Reg := _EBP; end;
$F6: begin Arg1.Reg := _R14; Arg2.Reg := _ESI; end;
$FE: begin Arg1.Reg := _R14; Arg2.Reg := _EDI; end;
$C7: begin Arg1.Reg := _R15; Arg2.Reg := _EAX; end;
$CF: begin Arg1.Reg := _R15; Arg2.Reg := _ECX; end;
$D7: begin Arg1.Reg := _R15; Arg2.Reg := _EDX; end;
$DF: begin Arg1.Reg := _R15; Arg2.Reg := _EBX; end;
$E7: begin Arg1.Reg := _R15; Arg2.Reg := _ESP; end;
$EF: begin Arg1.Reg := _R15; Arg2.Reg := _EBP; end;
$F7: begin Arg1.Reg := _R15; Arg2.Reg := _ESI; end;
$FF: begin Arg1.Reg := _R15; Arg2.Reg := _EDI; end;
else
result := false;
end;
end;
function AssignMovR64_R64(B: Byte; var Arg1, Arg2: TArg): Boolean;
begin
result := true;
case B of
$C0: begin Arg1.Reg := _R8; Arg2.Reg := _R8; end;
$C8: begin Arg1.Reg := _R8; Arg2.Reg := _R9; end;
$D0: begin Arg1.Reg := _R8; Arg2.Reg := _R10; end;
$D8: begin Arg1.Reg := _R8; Arg2.Reg := _R11; end;
$E0: begin Arg1.Reg := _R8; Arg2.Reg := _R12; end;
$E8: begin Arg1.Reg := _R8; Arg2.Reg := _R13; end;
$F0: begin Arg1.Reg := _R8; Arg2.Reg := _R14; end;
$F8: begin Arg1.Reg := _R8; Arg2.Reg := _R15; end;
$C1: begin Arg1.Reg := _R9; Arg2.Reg := _R8; end;
$C9: begin Arg1.Reg := _R9; Arg2.Reg := _R9; end;
$D1: begin Arg1.Reg := _R9; Arg2.Reg := _R10; end;
$D9: begin Arg1.Reg := _R9; Arg2.Reg := _R11; end;
$E1: begin Arg1.Reg := _R9; Arg2.Reg := _R12; end;
$E9: begin Arg1.Reg := _R9; Arg2.Reg := _R13; end;
$F1: begin Arg1.Reg := _R9; Arg2.Reg := _R14; end;
$F9: begin Arg1.Reg := _R9; Arg2.Reg := _R15; end;
$C2: begin Arg1.Reg := _R10; Arg2.Reg := _R8; end;
$CA: begin Arg1.Reg := _R10; Arg2.Reg := _R9; end;
$D2: begin Arg1.Reg := _R10; Arg2.Reg := _R10; end;
$DA: begin Arg1.Reg := _R10; Arg2.Reg := _R11; end;
$E2: begin Arg1.Reg := _R10; Arg2.Reg := _R12; end;
$EA: begin Arg1.Reg := _R10; Arg2.Reg := _R13; end;
$F2: begin Arg1.Reg := _R10; Arg2.Reg := _R14; end;
$FA: begin Arg1.Reg := _R10; Arg2.Reg := _R15; end;
$C3: begin Arg1.Reg := _R11; Arg2.Reg := _R8; end;
$CB: begin Arg1.Reg := _R11; Arg2.Reg := _R9; end;
$D3: begin Arg1.Reg := _R11; Arg2.Reg := _R10; end;
$DB: begin Arg1.Reg := _R11; Arg2.Reg := _R11; end;
$E3: begin Arg1.Reg := _R11; Arg2.Reg := _R12; end;
$EB: begin Arg1.Reg := _R11; Arg2.Reg := _R13; end;
$F3: begin Arg1.Reg := _R11; Arg2.Reg := _R14; end;
$FB: begin Arg1.Reg := _R11; Arg2.Reg := _R15; end;
$C6: begin Arg1.Reg := _R14; Arg2.Reg := _R8; end;
$CE: begin Arg1.Reg := _R14; Arg2.Reg := _R9; end;
$D6: begin Arg1.Reg := _R14; Arg2.Reg := _R10; end;
$DE: begin Arg1.Reg := _R14; Arg2.Reg := _R11; end;
$E6: begin Arg1.Reg := _R14; Arg2.Reg := _R12; end;
$EE: begin Arg1.Reg := _R14; Arg2.Reg := _R13; end;
$F6: begin Arg1.Reg := _R14; Arg2.Reg := _R14; end;
$FE: begin Arg1.Reg := _R14; Arg2.Reg := _R15; end;
$C7: begin Arg1.Reg := _R15; Arg2.Reg := _R8; end;
$CF: begin Arg1.Reg := _R15; Arg2.Reg := _R9; end;
$D7: begin Arg1.Reg := _R15; Arg2.Reg := _R10; end;
$DF: begin Arg1.Reg := _R15; Arg2.Reg := _R11; end;
$E7: begin Arg1.Reg := _R15; Arg2.Reg := _R12; end;
$EF: begin Arg1.Reg := _R15; Arg2.Reg := _R13; end;
$F7: begin Arg1.Reg := _R15; Arg2.Reg := _R14; end;
$FF: begin Arg1.Reg := _R15; Arg2.Reg := _R15; end;
else
result := false;
end;
end;
function AssignMovR32(B: Byte; var Arg1, Arg2: TArg): Boolean;
begin
result := true;
case B of
$C0: begin Arg1.Reg := _EAX; Arg2.Reg := _EAX; end;
$C8: begin Arg1.Reg := _EAX; Arg2.Reg := _ECX; end;
$D0: begin Arg1.Reg := _EAX; Arg2.Reg := _EDX; end;
$D8: begin Arg1.Reg := _EAX; Arg2.Reg := _EBX; end;
$E0: begin Arg1.Reg := _EAX; Arg2.Reg := _ESP; end;
$E8: begin Arg1.Reg := _EAX; Arg2.Reg := _EBP; end;
$F0: begin Arg1.Reg := _EAX; Arg2.Reg := _ESI; end;
$F8: begin Arg1.Reg := _EAX; Arg2.Reg := _EDI; end;
$C1: begin Arg1.Reg := _ECX; Arg2.Reg := _EAX; end;
$C9: begin Arg1.Reg := _ECX; Arg2.Reg := _ECX; end;
$D1: begin Arg1.Reg := _ECX; Arg2.Reg := _EDX; end;
$D9: begin Arg1.Reg := _ECX; Arg2.Reg := _EBX; end;
$E1: begin Arg1.Reg := _ECX; Arg2.Reg := _ESP; end;
$E9: begin Arg1.Reg := _ECX; Arg2.Reg := _EBP; end;
$F1: begin Arg1.Reg := _ECX; Arg2.Reg := _ESI; end;
$F9: begin Arg1.Reg := _ECX; Arg2.Reg := _EDI; end;
$C2: begin Arg1.Reg := _EDX; Arg2.Reg := _EAX; end;
$CA: begin Arg1.Reg := _EDX; Arg2.Reg := _ECX; end;
$D2: begin Arg1.Reg := _EDX; Arg2.Reg := _EDX; end;
$DA: begin Arg1.Reg := _EDX; Arg2.Reg := _EBX; end;
$E2: begin Arg1.Reg := _EDX; Arg2.Reg := _ESP; end;
$EA: begin Arg1.Reg := _EDX; Arg2.Reg := _EBP; end;
$F2: begin Arg1.Reg := _EDX; Arg2.Reg := _ESI; end;
$FA: begin Arg1.Reg := _EDX; Arg2.Reg := _EDI; end;
$C3: begin Arg1.Reg := _EBX; Arg2.Reg := _EAX; end;
$CB: begin Arg1.Reg := _EBX; Arg2.Reg := _ECX; end;
$D3: begin Arg1.Reg := _EBX; Arg2.Reg := _EDX; end;
$DB: begin Arg1.Reg := _EBX; Arg2.Reg := _EBX; end;
$E3: begin Arg1.Reg := _EBX; Arg2.Reg := _ESP; end;
$EB: begin Arg1.Reg := _EBX; Arg2.Reg := _EBP; end;
$F3: begin Arg1.Reg := _EBX; Arg2.Reg := _ESI; end;
$FB: begin Arg1.Reg := _EBX; Arg2.Reg := _EDI; end;
$C4: begin Arg1.Reg := _ESP; Arg2.Reg := _EAX; end;
$CC: begin Arg1.Reg := _ESP; Arg2.Reg := _ECX; end;
$D4: begin Arg1.Reg := _ESP; Arg2.Reg := _EDX; end;
$DC: begin Arg1.Reg := _ESP; Arg2.Reg := _EBX; end;
$E4: begin Arg1.Reg := _ESP; Arg2.Reg := _ESP; end;
$EC: begin Arg1.Reg := _ESP; Arg2.Reg := _EBP; end;
$F4: begin Arg1.Reg := _ESP; Arg2.Reg := _ESI; end;
$FC: begin Arg1.Reg := _ESP; Arg2.Reg := _EDI; end;
$C5: begin Arg1.Reg := _EBP; Arg2.Reg := _EAX; end;
$CD: begin Arg1.Reg := _EBP; Arg2.Reg := _ECX; end;
$D5: begin Arg1.Reg := _EBP; Arg2.Reg := _EDX; end;
$DD: begin Arg1.Reg := _EBP; Arg2.Reg := _EBX; end;
$E5: begin Arg1.Reg := _EBP; Arg2.Reg := _ESP; end;
$ED: begin Arg1.Reg := _EBP; Arg2.Reg := _EBP; end;
$F5: begin Arg1.Reg := _EBP; Arg2.Reg := _ESI; end;
$FD: begin Arg1.Reg := _EBP; Arg2.Reg := _EDI; end;
$C6: begin Arg1.Reg := _ESI; Arg2.Reg := _EAX; end;
$CE: begin Arg1.Reg := _ESI; Arg2.Reg := _ECX; end;
$D6: begin Arg1.Reg := _ESI; Arg2.Reg := _EDX; end;
$DE: begin Arg1.Reg := _ESI; Arg2.Reg := _EBX; end;
$E6: begin Arg1.Reg := _ESI; Arg2.Reg := _ESP; end;
$EE: begin Arg1.Reg := _ESI; Arg2.Reg := _EBP; end;
$F6: begin Arg1.Reg := _ESI; Arg2.Reg := _ESI; end;
$FE: begin Arg1.Reg := _ESI; Arg2.Reg := _EDI; end;
$C7: begin Arg1.Reg := _EDI; Arg2.Reg := _EAX; end;
$CF: begin Arg1.Reg := _EDI; Arg2.Reg := _ECX; end;
$D7: begin Arg1.Reg := _EDI; Arg2.Reg := _EDX; end;
$DF: begin Arg1.Reg := _EDI; Arg2.Reg := _EBX; end;
$E7: begin Arg1.Reg := _EDI; Arg2.Reg := _ESP; end;
$EF: begin Arg1.Reg := _EDI; Arg2.Reg := _EBP; end;
$F7: begin Arg1.Reg := _EDI; Arg2.Reg := _ESI; end;
$FF: begin Arg1.Reg := _EDI; Arg2.Reg := _EDI; end;
else
result := false;
end;
end;
function AssignR32_R32(B: Byte; var Arg1, Arg2: TArg): Boolean;
begin
result := true;
case B of
$00: begin Arg1.Reg := _EAX; Arg2.Reg := _EAX; end;
$01: begin Arg1.Reg := _EAX; Arg2.Reg := _ECX; end;
$02: begin Arg1.Reg := _EAX; Arg2.Reg := _EDX; end;
$03: begin Arg1.Reg := _EAX; Arg2.Reg := _EBX; end;
$04: begin Arg1.Reg := _EAX; Arg2.Reg := _ESP; end;
$05: begin Arg1.Reg := _EAX; Arg2.Reg := _EBP; end;
$06: begin Arg1.Reg := _EAX; Arg2.Reg := _ESI; end;
$07: begin Arg1.Reg := _EAX; Arg2.Reg := _EDI; end;
$08: begin Arg1.Reg := _ECX; Arg2.Reg := _EAX; end;
$09: begin Arg1.Reg := _ECX; Arg2.Reg := _ECX; end;
$0A: begin Arg1.Reg := _ECX; Arg2.Reg := _EDX; end;
$0B: begin Arg1.Reg := _ECX; Arg2.Reg := _EBX; end;
$0C: begin Arg1.Reg := _ECX; Arg2.Reg := _ESP; end;
$0D: begin Arg1.Reg := _ECX; Arg2.Reg := _EBP; end;
$0E: begin Arg1.Reg := _ECX; Arg2.Reg := _ESI; end;
$0F: begin Arg1.Reg := _ECX; Arg2.Reg := _EDI; end;
$10: begin Arg1.Reg := _EDX; Arg2.Reg := _EAX; end;
$11: begin Arg1.Reg := _EDX; Arg2.Reg := _ECX; end;
$12: begin Arg1.Reg := _EDX; Arg2.Reg := _EDX; end;
$13: begin Arg1.Reg := _EDX; Arg2.Reg := _EBX; end;
$14: begin Arg1.Reg := _EDX; Arg2.Reg := _ESP; end;
$15: begin Arg1.Reg := _EDX; Arg2.Reg := _EBP; end;
$16: begin Arg1.Reg := _EDX; Arg2.Reg := _ESI; end;
$17: begin Arg1.Reg := _EDX; Arg2.Reg := _EDI; end;
$18: begin Arg1.Reg := _EBX; Arg2.Reg := _EAX; end;
$19: begin Arg1.Reg := _EBX; Arg2.Reg := _ECX; end;
$1A: begin Arg1.Reg := _EBX; Arg2.Reg := _EDX; end;
$1B: begin Arg1.Reg := _EBX; Arg2.Reg := _EBX; end;
$1C: begin Arg1.Reg := _EBX; Arg2.Reg := _ESP; end;
$1D: begin Arg1.Reg := _EBX; Arg2.Reg := _EBP; end;
$1E: begin Arg1.Reg := _EBX; Arg2.Reg := _ESI; end;
$1F: begin Arg1.Reg := _EBX; Arg2.Reg := _EDI; end;
$20: begin Arg1.Reg := _ESP; Arg2.Reg := _EAX; end;
$21: begin Arg1.Reg := _ESP; Arg2.Reg := _ECX; end;
$22: begin Arg1.Reg := _ESP; Arg2.Reg := _EDX; end;
$23: begin Arg1.Reg := _ESP; Arg2.Reg := _EBX; end;
$24: begin Arg1.Reg := _ESP; Arg2.Reg := _ESP; end;
$25: begin Arg1.Reg := _ESP; Arg2.Reg := _EBP; end;
$26: begin Arg1.Reg := _ESP; Arg2.Reg := _ESI; end;
$27: begin Arg1.Reg := _ESP; Arg2.Reg := _EDI; end;
$28: begin Arg1.Reg := _EBP; Arg2.Reg := _EAX; end;
$29: begin Arg1.Reg := _EBP; Arg2.Reg := _ECX; end;
$2A: begin Arg1.Reg := _EBP; Arg2.Reg := _EDX; end;
$2B: begin Arg1.Reg := _EBP; Arg2.Reg := _EBX; end;
$2C: begin Arg1.Reg := _EBP; Arg2.Reg := _ESP; end;
$2D: begin Arg1.Reg := _EBP; Arg2.Reg := _EBP; end;
$2E: begin Arg1.Reg := _EBP; Arg2.Reg := _ESI; end;
$2F: begin Arg1.Reg := _EBP; Arg2.Reg := _EDI; end;
$30: begin Arg1.Reg := _ESI; Arg2.Reg := _EAX; end;
$31: begin Arg1.Reg := _ESI; Arg2.Reg := _ECX; end;
$32: begin Arg1.Reg := _ESI; Arg2.Reg := _EDX; end;
$33: begin Arg1.Reg := _ESI; Arg2.Reg := _EBX; end;
$34: begin Arg1.Reg := _ESI; Arg2.Reg := _ESP; end;
$35: begin Arg1.Reg := _ESI; Arg2.Reg := _EBP; end;
$36: begin Arg1.Reg := _ESI; Arg2.Reg := _ESI; end;
$37: begin Arg1.Reg := _ESI; Arg2.Reg := _EDI; end;
$38: begin Arg1.Reg := _EDI; Arg2.Reg := _EAX; end;
$39: begin Arg1.Reg := _EDI; Arg2.Reg := _ECX; end;
$3A: begin Arg1.Reg := _EDI; Arg2.Reg := _EDX; end;
$3B: begin Arg1.Reg := _EDI; Arg2.Reg := _EBX; end;
$3C: begin Arg1.Reg := _EDI; Arg2.Reg := _ESP; end;
$3D: begin Arg1.Reg := _EDI; Arg2.Reg := _EBP; end;
$3E: begin Arg1.Reg := _EDI; Arg2.Reg := _ESI; end;
$3F: begin Arg1.Reg := _EDI; Arg2.Reg := _EDI; end;
else
result := false;
end;
end;
function AssignR64_R32(B: Byte; var Arg1, Arg2: TArg): Boolean;
begin
result := true;
case B of
$00: begin Arg1.Reg := _R8; Arg2.Reg := _EAX; end;
$01: begin Arg1.Reg := _R8; Arg2.Reg := _ECX; end;
$02: begin Arg1.Reg := _R8; Arg2.Reg := _EDX; end;
$03: begin Arg1.Reg := _R8; Arg2.Reg := _EBX; end;
$04: begin Arg1.Reg := _R8; Arg2.Reg := _ESP; end;
$05: begin Arg1.Reg := _R8; Arg2.Reg := _EBP; end;
$06: begin Arg1.Reg := _R8; Arg2.Reg := _ESI; end;
$07: begin Arg1.Reg := _R8; Arg2.Reg := _EDI; end;
$08: begin Arg1.Reg := _R9; Arg2.Reg := _EAX; end;
$09: begin Arg1.Reg := _R9; Arg2.Reg := _ECX; end;
$0A: begin Arg1.Reg := _R9; Arg2.Reg := _EDX; end;
$0B: begin Arg1.Reg := _R9; Arg2.Reg := _EBX; end;
$0C: begin Arg1.Reg := _R9; Arg2.Reg := _ESP; end;
$0D: begin Arg1.Reg := _R8; Arg2.Reg := _EBP; end;
$0E: begin Arg1.Reg := _R9; Arg2.Reg := _ESI; end;
$0F: begin Arg1.Reg := _R9; Arg2.Reg := _EDI; end;
$10: begin Arg1.Reg := _R10; Arg2.Reg := _EAX; end;
$11: begin Arg1.Reg := _R10; Arg2.Reg := _ECX; end;
$12: begin Arg1.Reg := _R10; Arg2.Reg := _EDX; end;
$13: begin Arg1.Reg := _R10; Arg2.Reg := _EBX; end;
$14: begin Arg1.Reg := _R10; Arg2.Reg := _ESP; end;
$15: begin Arg1.Reg := _R10; Arg2.Reg := _EBP; end;
$16: begin Arg1.Reg := _R10; Arg2.Reg := _ESI; end;
$17: begin Arg1.Reg := _R10; Arg2.Reg := _EDI; end;
$18: begin Arg1.Reg := _R11; Arg2.Reg := _EAX; end;
$19: begin Arg1.Reg := _R11; Arg2.Reg := _ECX; end;
$1A: begin Arg1.Reg := _R11; Arg2.Reg := _EDX; end;
$1B: begin Arg1.Reg := _R11; Arg2.Reg := _EBX; end;
$1C: begin Arg1.Reg := _R11; Arg2.Reg := _ESP; end;
$1D: begin Arg1.Reg := _R11; Arg2.Reg := _EBP; end;
$1E: begin Arg1.Reg := _R11; Arg2.Reg := _ESI; end;
$1F: begin Arg1.Reg := _R11; Arg2.Reg := _EDI; end;
$20: begin Arg1.Reg := _R12; Arg2.Reg := _EAX; end;
$21: begin Arg1.Reg := _R12; Arg2.Reg := _ECX; end;
$22: begin Arg1.Reg := _R12; Arg2.Reg := _EDX; end;
$23: begin Arg1.Reg := _R12; Arg2.Reg := _EBX; end;
$24: begin Arg1.Reg := _R12; Arg2.Reg := _ESP; end;
$25: begin Arg1.Reg := _R12; Arg2.Reg := _EBP; end;
$26: begin Arg1.Reg := _R12; Arg2.Reg := _ESI; end;
$27: begin Arg1.Reg := _R12; Arg2.Reg := _EDI; end;
$28: begin Arg1.Reg := _R13; Arg2.Reg := _EAX; end;
$29: begin Arg1.Reg := _R13; Arg2.Reg := _ECX; end;
$2A: begin Arg1.Reg := _R13; Arg2.Reg := _EDX; end;
$2B: begin Arg1.Reg := _R13; Arg2.Reg := _EBX; end;
$2C: begin Arg1.Reg := _R13; Arg2.Reg := _ESP; end;
$2D: begin Arg1.Reg := _R13; Arg2.Reg := _EBP; end;
$2E: begin Arg1.Reg := _R13; Arg2.Reg := _ESI; end;
$2F: begin Arg1.Reg := _R13; Arg2.Reg := _EDI; end;
$30: begin Arg1.Reg := _R14; Arg2.Reg := _EAX; end;
$31: begin Arg1.Reg := _R14; Arg2.Reg := _ECX; end;
$32: begin Arg1.Reg := _R14; Arg2.Reg := _EDX; end;
$33: begin Arg1.Reg := _R14; Arg2.Reg := _EBX; end;
$34: begin Arg1.Reg := _R14; Arg2.Reg := _ESP; end;
$35: begin Arg1.Reg := _R14; Arg2.Reg := _EBP; end;
$36: begin Arg1.Reg := _R14; Arg2.Reg := _ESI; end;
$37: begin Arg1.Reg := _R14; Arg2.Reg := _EDI; end;
$38: begin Arg1.Reg := _R15; Arg2.Reg := _EAX; end;
$39: begin Arg1.Reg := _R15; Arg2.Reg := _ECX; end;
$3A: begin Arg1.Reg := _R15; Arg2.Reg := _EDX; end;
$3B: begin Arg1.Reg := _R15; Arg2.Reg := _EBX; end;
$3C: begin Arg1.Reg := _R15; Arg2.Reg := _ESP; end;
$3D: begin Arg1.Reg := _R15; Arg2.Reg := _EBP; end;
$3E: begin Arg1.Reg := _R15; Arg2.Reg := _ESI; end;
$3F: begin Arg1.Reg := _R15; Arg2.Reg := _EDI; end;
else
result := false;
end;
end;
function AssignR64_R64(B: Byte; var Arg1, Arg2: TArg): Boolean;
begin
result := true;
case B of
$00: begin Arg1.Reg := _R8; Arg2.Reg := _R8; end;
$01: begin Arg1.Reg := _R8; Arg2.Reg := _R9; end;
$02: begin Arg1.Reg := _R8; Arg2.Reg := _R10; end;
$03: begin Arg1.Reg := _R8; Arg2.Reg := _R11; end;
$04: begin Arg1.Reg := _R8; Arg2.Reg := _R12; end;
$05: begin Arg1.Reg := _R8; Arg2.Reg := _R13; end;
$06: begin Arg1.Reg := _R8; Arg2.Reg := _R14; end;
$07: begin Arg1.Reg := _R8; Arg2.Reg := _R15; end;
$08: begin Arg1.Reg := _R9; Arg2.Reg := _R8; end;
$09: begin Arg1.Reg := _R9; Arg2.Reg := _R9; end;
$0A: begin Arg1.Reg := _R9; Arg2.Reg := _R10; end;
$0B: begin Arg1.Reg := _R9; Arg2.Reg := _R11; end;
$0C: begin Arg1.Reg := _R9; Arg2.Reg := _R12; end;
$0D: begin Arg1.Reg := _R9; Arg2.Reg := _R13; end;
$0E: begin Arg1.Reg := _R9; Arg2.Reg := _R14; end;
$0F: begin Arg1.Reg := _R9; Arg2.Reg := _R15; end;
$10: begin Arg1.Reg := _R10; Arg2.Reg := _R8; end;
$11: begin Arg1.Reg := _R10; Arg2.Reg := _R9; end;
$12: begin Arg1.Reg := _R10; Arg2.Reg := _R10; end;
$13: begin Arg1.Reg := _R10; Arg2.Reg := _R11; end;
$14: begin Arg1.Reg := _R10; Arg2.Reg := _R12; end;
$15: begin Arg1.Reg := _R10; Arg2.Reg := _R13; end;
$16: begin Arg1.Reg := _R10; Arg2.Reg := _R14; end;
$17: begin Arg1.Reg := _R10; Arg2.Reg := _R15; end;
$18: begin Arg1.Reg := _R11; Arg2.Reg := _R8; end;
$19: begin Arg1.Reg := _R11; Arg2.Reg := _R9; end;
$1A: begin Arg1.Reg := _R11; Arg2.Reg := _R10; end;
$1B: begin Arg1.Reg := _R11; Arg2.Reg := _R11; end;
$1C: begin Arg1.Reg := _R11; Arg2.Reg := _R12; end;
$1D: begin Arg1.Reg := _R11; Arg2.Reg := _R13; end;
$1E: begin Arg1.Reg := _R11; Arg2.Reg := _R14; end;
$1F: begin Arg1.Reg := _R11; Arg2.Reg := _R15; end;
$20: begin Arg1.Reg := _R12; Arg2.Reg := _R8; end;
$21: begin Arg1.Reg := _R12; Arg2.Reg := _R9; end;
$22: begin Arg1.Reg := _R12; Arg2.Reg := _R10; end;
$23: begin Arg1.Reg := _R12; Arg2.Reg := _R11; end;
$24: begin Arg1.Reg := _R12; Arg2.Reg := _R12; end;
$25: begin Arg1.Reg := _R12; Arg2.Reg := _R13; end;
$26: begin Arg1.Reg := _R12; Arg2.Reg := _R14; end;
$27: begin Arg1.Reg := _R12; Arg2.Reg := _R15; end;
$28: begin Arg1.Reg := _R13; Arg2.Reg := _R8; end;
$29: begin Arg1.Reg := _R13; Arg2.Reg := _R9; end;
$2A: begin Arg1.Reg := _R13; Arg2.Reg := _R10; end;
$2B: begin Arg1.Reg := _R13; Arg2.Reg := _R11; end;
$2C: begin Arg1.Reg := _R13; Arg2.Reg := _R12; end;
$2D: begin Arg1.Reg := _R13; Arg2.Reg := _R13; end;
$2E: begin Arg1.Reg := _R13; Arg2.Reg := _R14; end;
$2F: begin Arg1.Reg := _R13; Arg2.Reg := _R15; end;
$30: begin Arg1.Reg := _R14; Arg2.Reg := _R8; end;
$31: begin Arg1.Reg := _R14; Arg2.Reg := _R9; end;
$32: begin Arg1.Reg := _R14; Arg2.Reg := _R10; end;
$33: begin Arg1.Reg := _R14; Arg2.Reg := _R11; end;
$34: begin Arg1.Reg := _R14; Arg2.Reg := _R12; end;
$35: begin Arg1.Reg := _R14; Arg2.Reg := _R13; end;
$36: begin Arg1.Reg := _R14; Arg2.Reg := _R14; end;
$37: begin Arg1.Reg := _R14; Arg2.Reg := _R15; end;
$38: begin Arg1.Reg := _R15; Arg2.Reg := _R8; end;
$39: begin Arg1.Reg := _R15; Arg2.Reg := _R9; end;
$3A: begin Arg1.Reg := _R15; Arg2.Reg := _R10; end;
$3B: begin Arg1.Reg := _R15; Arg2.Reg := _R11; end;
$3C: begin Arg1.Reg := _R15; Arg2.Reg := _R12; end;
$3D: begin Arg1.Reg := _R15; Arg2.Reg := _R13; end;
$3E: begin Arg1.Reg := _R15; Arg2.Reg := _R14; end;
$3F: begin Arg1.Reg := _R15; Arg2.Reg := _R15; end;
else
result := false;
end;
end;
function AssignR32_R64(B: Byte; var Arg1, Arg2: TArg): Boolean;
begin
result := true;
case B of
$00: begin Arg1.Reg := _EAX; Arg2.Reg := _R8; end;
$01: begin Arg1.Reg := _EAX; Arg2.Reg := _R9; end;
$02: begin Arg1.Reg := _EAX; Arg2.Reg := _R10; end;
$03: begin Arg1.Reg := _EAX; Arg2.Reg := _R11; end;
$04: begin Arg1.Reg := _EAX; Arg2.Reg := _R12; end;
$05: begin Arg1.Reg := _EAX; Arg2.Reg := _R13; end;
$06: begin Arg1.Reg := _EAX; Arg2.Reg := _R14; end;
$07: begin Arg1.Reg := _EAX; Arg2.Reg := _R15; end;
$08: begin Arg1.Reg := _ECX; Arg2.Reg := _R8; end;
$09: begin Arg1.Reg := _ECX; Arg2.Reg := _R9; end;
$0A: begin Arg1.Reg := _ECX; Arg2.Reg := _R10; end;
$0B: begin Arg1.Reg := _ECX; Arg2.Reg := _R11; end;
$0C: begin Arg1.Reg := _ECX; Arg2.Reg := _R12; end;
$0D: begin Arg1.Reg := _ECX; Arg2.Reg := _R13; end;
$0E: begin Arg1.Reg := _ECX; Arg2.Reg := _R14; end;
$0F: begin Arg1.Reg := _ECX; Arg2.Reg := _R15; end;
$10: begin Arg1.Reg := _EDX; Arg2.Reg := _R8; end;
$11: begin Arg1.Reg := _EDX; Arg2.Reg := _R9; end;
$12: begin Arg1.Reg := _EDX; Arg2.Reg := _R10; end;
$13: begin Arg1.Reg := _EDX; Arg2.Reg := _R11; end;
$14: begin Arg1.Reg := _EDX; Arg2.Reg := _R12; end;
$15: begin Arg1.Reg := _EDX; Arg2.Reg := _R13; end;
$16: begin Arg1.Reg := _EDX; Arg2.Reg := _R14; end;
$17: begin Arg1.Reg := _EDX; Arg2.Reg := _R15; end;
$18: begin Arg1.Reg := _EBX; Arg2.Reg := _R8; end;
$19: begin Arg1.Reg := _EBX; Arg2.Reg := _R9; end;
$1A: begin Arg1.Reg := _EBX; Arg2.Reg := _R10; end;
$1B: begin Arg1.Reg := _EBX; Arg2.Reg := _R11; end;
$1C: begin Arg1.Reg := _EBX; Arg2.Reg := _R12; end;
$1D: begin Arg1.Reg := _EBX; Arg2.Reg := _R13; end;
$1E: begin Arg1.Reg := _EBX; Arg2.Reg := _R14; end;
$1F: begin Arg1.Reg := _EBX; Arg2.Reg := _R15; end;
else
result := false;
end;
end;
function ValToStr(val: Integer): String;
begin
// result := IntToStr(val);
if val = 0 then
result := '0'
else if val > 0 then
begin
result := Format('%x', [val]);
while Length(result) < 4 do
result := '0' + result;
result := '$' + result;
end
else
begin
result := Format('%x', [-val]);
while Length(result) < 4 do
result := '0' + result;
result := '-$' + result;
end;
end;
function ArgToString(const Arg: TArg; PAX64: Boolean): String;
var
I: Integer;
begin
with Arg do
begin
if not valid then
begin
result := '';
Exit;
end;
if Reg = 0 then // imm
begin
result := ValToStr(val);
Exit;
end;
if not Ptr then
begin
case sz of
1:
case Reg of
_EAX: result := 'AL';
_ECX: result := 'CL';
_EDX: result := 'DL';
_EBX: result := 'BL';
_ESP: result := 'SP';
_EBP: result := 'BP';
_ESI: result := 'SI';
_EDI: result := 'DI';
_R8: result := 'R8B';
_R9: result := 'R9B';
_R10: result := 'R10B';
_R11: result := 'R11B';
_R12: result := 'R12B';
_R13: result := 'R13B';
_R14: result := 'R14B';
_R15: result := 'R15B';
else
RaiseError(errInternalError, []);
end;
2:
case Reg of
_EAX: result := 'AX';
_ECX: result := 'CX';
_EDX: result := 'DX';
_EBX: result := 'BX';
_ESP: result := 'SP';
_EBP: result := 'BP';
_ESI: result := 'SI';
_EDI: result := 'DI';
_R8: result := 'R8W';
_R9: result := 'R9W';
_R10: result := 'R10W';
_R11: result := 'R11W';
_R12: result := 'R12W';
_R13: result := 'R13W';
_R14: result := 'R14W';
_R15: result := 'R15W';
else
RaiseError(errInternalError, []);
end;
4:
case Reg of
_EAX: result := 'EAX';
_ECX: result := 'ECX';
_EDX: result := 'EDX';
_EBX: result := 'EBX';
_ESI: result := 'ESI';
_EDI: result := 'EDI';
_EBP: result := 'EBP';
_ESP: result := 'ESP';
_R8: result := 'R8D';
_R9: result := 'R9D';
_R10: result := 'R10D';
_R11: result := 'R11D';
_R12: result := 'R12D';
_R13: result := 'R13D';
_R14: result := 'R14D';
_R15: result := 'R15D';
end;
8:
case Reg of
_EAX: result := 'RAX';
_ECX: result := 'RCX';
_EDX: result := 'RDX';
_EBX: result := 'RBX';
_ESI: result := 'RSI';
_EDI: result := 'RDI';
_EBP: result := 'RBP';
_ESP: result := 'RSP';
_R8: result := 'R8';
_R9: result := 'R9';
_R10: result := 'R10';
_R11: result := 'R11';
_R12: result := 'R12';
_R13: result := 'R13';
_R14: result := 'R14';
_R15: result := 'R15';
_XMM0: result := 'XMM0';
_XMM1: result := 'XMM1';
_XMM2: result := 'XMM2';
_XMM3: result := 'XMM3';
_XMM4: result := 'XMM4';
end;
end;
end
else // Ptr
begin
if PAX64 then
case Reg of
_EAX: result := '[RAX]';
_ECX: result := '[RCX]';
_EDX: result := '[RDX]';
_EBX: result := '[RBX]';
_ESI: result := '[RSI]';
_EDI: result := '[RDI]';
_EBP: result := '[RBP]';
_ESP: result := '[RSP]';
_R8: result := '[R8]';
_R9: result := '[R9]';
_R10: result := '[R10]';
_R11: result := '[R11]';
_R12: result := '[R12]';
_R13: result := '[R13]';
_R14: result := '[R14]';
_R15: result := '[R15]';
end
else
case Reg of
_EAX: result := '[EAX]';
_ECX: result := '[ECX]';
_EDX: result := '[EDX]';
_EBX: result := '[EBX]';
_ESI: result := '[ESI]';
_EDI: result := '[EDI]';
_EBP: result := '[EBP]';
_ESP: result := '[ESP]';
end;
if FS then
result := 'FS:' + result;
if val <> 0 then
begin
Delete(result, Length(result), 1);
if val > 0 then
result := result + '+' + ValToStr(val) + ']'
else
result := result + ValToStr(val) + ']'
end;
case sz of
1: result := 'BYTE PTR ' + result;
2: result := 'WORD PTR ' + result;
4: result := 'DWORD PTR ' + result;
8: result := 'QWORD PTR ' + result;
10: result := 'TBYTE PTR ' + result;
else
RaiseError(errInternalError, []);
end;
I := Pos('+-', result);
if I > 0 then
Delete(result, I, 1);
end;
end;
end;
procedure ClearArg(var Arg: TArg);
begin
FillChar(Arg, SizeOf(Arg), 0);
end;
function EqualArgs(const Arg1, Arg2: TArg): Boolean;
begin
result := (Arg1.Reg = Arg2.Reg) and
(Arg1.Ptr = Arg2.Ptr) and
(Arg1.sz = Arg2.sz) and
(Arg1.val = Arg2.val);
end;
procedure SaveDecompiledCode(P: Pointer;
CodeSize: Integer;
const FileName: String; PAX64: Boolean);
var
buff: array[1..20] of byte;
L: Integer;
function HexCode: String;
var
I: Integer;
begin
result := '';
for I:=1 to L do
result := result + ByteToHex(buff[I]);
end;
var
T: TextFile;
K, Line: Integer;
Op: Integer;
Arg1, Arg2: TArg;
S, S1, S2: String;
begin
Line := 0;
K := 0;
AssignFile(T, FileName);
Rewrite(T);
try
repeat
Inc(Line);
Decomp(P, L, Op, Arg1, Arg2, PAX64);
Move(P^, buff, L);
S := AsmOperators[Op];
S1 := ArgToString(Arg1, PAX64);
S2 := ArgToString(Arg2, PAX64);
if not Arg2.valid then
writeln(T, Line:6, HexCode:20, S:10, ' ', S1:20)
else
writeln(T, Line:6, HexCode:20, S:10, ' ', S1:20, ',', S2);
P := ShiftPointer(P, L);
Inc(K, L);
if K >= CodeSize then
Break;
until false;
finally
Close(T);
end;
end;
procedure DiscardDebugMode(P: Pointer;
CodeSize: Integer;
PAX64: Boolean);
var
buff: array[1..11] of byte;
L: Integer;
Value: Cardinal;
var
K: Integer;
Op: Integer;
Arg1, Arg2: TArg;
begin
Value := 58;
K := 0;
repeat
Decomp(P, L, Op, Arg1, Arg2, PAX64);
Move(P^, buff, L);
if Op = ASM_NOP then
begin
Move(P^, Buff, 5);
if Buff[2] = $90 then
if Buff[3] = $90 then
if Buff[4] = $90 then
if Buff[5] = $90 then
begin
Buff[1] := $E9;
Move(value, Buff[2], 4);
Move(Buff, P^, 5);
P := ShiftPointer(P, 5);
Inc(K, 5);
end;
end
else
begin
P := ShiftPointer(P, L);
Inc(K, L);
end;
if K >= CodeSize then
Break;
until false;
end;
function GetMagicOffset(P: Pointer;
CodeSize: Integer; MAGIC_COUNT: Integer; PAX64: Boolean): Integer;
var
K, L, Op, Count: Integer;
Arg1, Arg2: TArg;
begin
K := 0;
Count := 0;
result := -1;
repeat
Decomp(P, L, Op, Arg1, Arg2, PAX64);
if Op = ASM_JMP then
begin
if Arg1.val = 0 then
begin
Inc(Count);
if Count = MAGIC_COUNT then
begin
result := K;
Exit;
end;
end
else
Count := 0;
end
else
Count := 0;
P := ShiftPointer(P, L);
Inc(K, L);
if K >= CodeSize then
Break;
until false;
end;
function GetFinalizationOffset(P: Pointer; CodeSize: Integer; PAX64: Boolean): Integer;
begin
result := GetMagicOffset(P, CodeSize, MAGIC_FINALIZATION_JMP_COUNT, PAX64);
end;
function GetInitializationOffset(P: Pointer; CodeSize: Integer; PAX64: Boolean): Integer;
begin
result := GetMagicOffset(P, CodeSize, MAGIC_INITIALIZATION_JMP_COUNT, PAX64);
end;
procedure Decomp(P: Pointer; var Length: Integer; var op: Integer;
var Arg1: TArg;
var Arg2: TArg; PAX64: Boolean);
var
B: Byte;
begin
ClearArg(Arg1);
Arg1.valid := true;
if PAX64 then
Arg1.sz := 8
else
Arg1.sz := 4;
ClearArg(Arg2);
Arg2.valid := true;
if PAX64 then
Arg2.sz := 8
else
Arg2.sz := 4;
B := Byte(P^);
case B of
$FE:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$44:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$24:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$F4:
begin
op := ASM_INC;
Length := 4;
Arg1.Reg := _ESP;
Arg1.Ptr := true;
Arg1.sz := 1;
Arg1.Val := -12;
Arg2.valid := false;
end;
else
RaiseError(errInternalError, []);
end;
end;
else
RaiseError(errInternalError, []);
end;
end;
else
RaiseError(errInternalError, []);
end;
end;
$C2:
begin
op := ASM_RET;
Length := 3;
P := ShiftPointer(P, 1);
Arg1.val := 0;
Move(P^, Arg1.val, 2);
Arg2.valid := false;
end;
$C3:
begin
op := ASM_RET;
Length := 1;
Arg1.valid := false;
Arg2.valid := false;
end;
$90:
begin
op := ASM_NOP;
Length := 1;
Arg1.valid := false;
Arg2.valid := false;
end;
$9B:
begin
op := ASM_WAIT;
Length := 1;
Arg1.valid := false;
Arg2.valid := false;
end;
$91..$97:
begin
op := ASM_XCHG;
Length := 1;
Arg1.Reg := _EAX;
case B of
$91: Arg2.Reg := _ECX;
$92: Arg2.Reg := _EDX;
$93: Arg2.Reg := _EBX;
$94: Arg2.Reg := _ESP;
$95: Arg2.Reg := _EBP;
$96: Arg2.Reg := _ESI;
$97: Arg2.Reg := _EDI;
else
RaiseError(errInternalError, []);
end;
end;
$F8:
begin
op := ASM_CLC;
Length := 1;
Arg1.valid := false;
Arg2.valid := false;
end;
$9C:
begin
op := ASM_PUSHFD;
Length := 1;
Arg1.valid := false;
Arg2.valid := false;
end;
$9D:
begin
op := ASM_POPFD;
Length := 1;
Arg1.valid := false;
Arg2.valid := false;
end;
$F3:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
if B = $0F then
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
if B <> $5A then
RaiseError(errInternalError, []);
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_CVTSS2SD;
Length := 4;
Arg2.Ptr := true;
Arg2.sz := 4;
if not AssignXMM_RegPtr(B, Arg1, Arg2) then
RaiseError(errInternalError, []);
end
else
begin
Length := 2;
Arg1.valid := false;
Arg2.valid := false;
case B of
$A4: op := ASM_REP_MOVSB;
$A5: op := ASM_REP_MOVSD;
else
RaiseError(errInternalError, []);
end;
end;
end;
$71:
begin
op := ASM_JNO;
Length := 2;
P := ShiftPointer(P, 1);
B := Byte(P^);
Arg1.val := B;
Arg2.valid := false;
end;
$73:
begin
op := ASM_JNC;
Length := 2;
P := ShiftPointer(P, 1);
B := Byte(P^);
Arg1.val := B;
Arg2.valid := false;
end;
$74:
begin
op := ASM_JZ;
Length := 2;
P := ShiftPointer(P, 1);
B := Byte(P^);
Arg1.val := B;
Arg2.valid := false;
end;
$75:
begin
op := ASM_JNZ;
Length := 2;
P := ShiftPointer(P, 1);
B := Byte(P^);
Arg1.val := B;
Arg2.valid := false;
end;
$76:
begin
op := ASM_JBE;
Length := 2;
P := ShiftPointer(P, 1);
B := Byte(P^);
Arg1.val := B;
Arg2.valid := false;
end;
$7F:
begin
op := ASM_JNLE;
Length := 2;
P := ShiftPointer(P, 1);
B := Byte(P^);
Arg1.val := B;
Arg2.valid := false;
end;
// Mov EAX, Imm
$B8:
begin
Op := ASM_MOV;
Length := 5;
Arg1.Reg := _EAX;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end;
// Mov ECX, Imm
$B9:
begin
Op := ASM_MOV;
Length := 5;
Arg1.Reg := _ECX;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end;
// Mov EDX, Imm
$BA:
begin
Op := ASM_MOV;
Length := 5;
Arg1.Reg := _EDX;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end;
// Mov EBX, Imm
$BB:
begin
Op := ASM_MOV;
Length := 5;
Arg1.Reg := _EBX;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end;
// Mov EBX, Imm
$BC:
begin
Op := ASM_MOV;
Length := 5;
Arg1.Reg := _ESP;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end;
// Mov EBX, Imm
$BD:
begin
Op := ASM_MOV;
Length := 5;
Arg1.Reg := _EBP;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end;
// Mov EBX, Imm
$BE:
begin
Op := ASM_MOV;
Length := 5;
Arg1.Reg := _ESI;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end;
// Mov EBX, Imm
$BF:
begin
Op := ASM_MOV;
Length := 5;
Arg1.Reg := _EDI;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end;
// Add REG, REG
$01:
begin
Op := ASM_ADD;
Length := 2;
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$C0: begin Arg1.Reg := _EAX; Arg2.Reg := _EAX; end;
$C8: begin Arg1.Reg := _EAX; Arg2.Reg := _ECX; end;
$D0: begin Arg1.Reg := _EAX; Arg2.Reg := _EDX; end;
$D8: begin Arg1.Reg := _EAX; Arg2.Reg := _EBX; end;
$F0: begin Arg1.Reg := _EAX; Arg2.Reg := _ESI; end;
$F8: begin Arg1.Reg := _EAX; Arg2.Reg := _EDI; end;
$C1: begin Arg1.Reg := _ECX; Arg2.Reg := _EAX; end;
$C9: begin Arg1.Reg := _ECX; Arg2.Reg := _ECX; end;
$D1: begin Arg1.Reg := _ECX; Arg2.Reg := _EDX; end;
$D9: begin Arg1.Reg := _ECX; Arg2.Reg := _EBX; end;
$F1: begin Arg1.Reg := _ECX; Arg2.Reg := _ESI; end;
$F9: begin Arg1.Reg := _ECX; Arg2.Reg := _EDI; end;
$C2: begin Arg1.Reg := _EDX; Arg2.Reg := _EAX; end;
$CA: begin Arg1.Reg := _EDX; Arg2.Reg := _ECX; end;
$D2: begin Arg1.Reg := _EDX; Arg2.Reg := _EDX; end;
$DA: begin Arg1.Reg := _EDX; Arg2.Reg := _EBX; end;
$F2: begin Arg1.Reg := _EDX; Arg2.Reg := _ESI; end;
$FA: begin Arg1.Reg := _EDX; Arg2.Reg := _EDI; end;
$C3: begin Arg1.Reg := _EBX; Arg2.Reg := _EAX; end;
$CB: begin Arg1.Reg := _EBX; Arg2.Reg := _ECX; end;
$D3: begin Arg1.Reg := _EBX; Arg2.Reg := _EDX; end;
$DB: begin Arg1.Reg := _EBX; Arg2.Reg := _EBX; end;
$F3: begin Arg1.Reg := _EBX; Arg2.Reg := _ESI; end;
$FB: begin Arg1.Reg := _EBX; Arg2.Reg := _EDI; end;
else
RaiseError(errInternalError, []);
end;
end;
// Adc REG, REG
$11:
begin
Op := ASM_ADC;
Length := 2;
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$C0: begin Arg1.Reg := _EAX; Arg2.Reg := _EAX; end;
$C8: begin Arg1.Reg := _EAX; Arg2.Reg := _ECX; end;
$D0: begin Arg1.Reg := _EAX; Arg2.Reg := _EDX; end;
$D8: begin Arg1.Reg := _EAX; Arg2.Reg := _EBX; end;
$F0: begin Arg1.Reg := _EAX; Arg2.Reg := _ESI; end;
$F8: begin Arg1.Reg := _EAX; Arg2.Reg := _EDI; end;
$C1: begin Arg1.Reg := _ECX; Arg2.Reg := _EAX; end;
$C9: begin Arg1.Reg := _ECX; Arg2.Reg := _ECX; end;
$D1: begin Arg1.Reg := _ECX; Arg2.Reg := _EDX; end;
$D9: begin Arg1.Reg := _ECX; Arg2.Reg := _EBX; end;
$F1: begin Arg1.Reg := _ECX; Arg2.Reg := _ESI; end;
$F9: begin Arg1.Reg := _ECX; Arg2.Reg := _EDI; end;
$C2: begin Arg1.Reg := _EDX; Arg2.Reg := _EAX; end;
$CA: begin Arg1.Reg := _EDX; Arg2.Reg := _ECX; end;
$D2: begin Arg1.Reg := _EDX; Arg2.Reg := _EDX; end;
$DA: begin Arg1.Reg := _EDX; Arg2.Reg := _EBX; end;
$F2: begin Arg1.Reg := _EDX; Arg2.Reg := _ESI; end;
$FA: begin Arg1.Reg := _EDX; Arg2.Reg := _EDI; end;
$C3: begin Arg1.Reg := _EBX; Arg2.Reg := _EAX; end;
$CB: begin Arg1.Reg := _EBX; Arg2.Reg := _ECX; end;
$D3: begin Arg1.Reg := _EBX; Arg2.Reg := _EDX; end;
$DB: begin Arg1.Reg := _EBX; Arg2.Reg := _EBX; end;
$F3: begin Arg1.Reg := _EBX; Arg2.Reg := _ESI; end;
$FB: begin Arg1.Reg := _EBX; Arg2.Reg := _EDI; end;
else
RaiseError(errInternalError, []);
end;
end;
// Sbb REG, REG
$19:
begin
Op := ASM_SBB;
Length := 2;
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$C0: begin Arg1.Reg := _EAX; Arg2.Reg := _EAX; end;
$C8: begin Arg1.Reg := _EAX; Arg2.Reg := _ECX; end;
$D0: begin Arg1.Reg := _EAX; Arg2.Reg := _EDX; end;
$D8: begin Arg1.Reg := _EAX; Arg2.Reg := _EBX; end;
$F0: begin Arg1.Reg := _EAX; Arg2.Reg := _ESI; end;
$F8: begin Arg1.Reg := _EAX; Arg2.Reg := _EDI; end;
$C1: begin Arg1.Reg := _ECX; Arg2.Reg := _EAX; end;
$C9: begin Arg1.Reg := _ECX; Arg2.Reg := _ECX; end;
$D1: begin Arg1.Reg := _ECX; Arg2.Reg := _EDX; end;
$D9: begin Arg1.Reg := _ECX; Arg2.Reg := _EBX; end;
$F1: begin Arg1.Reg := _ECX; Arg2.Reg := _ESI; end;
$F9: begin Arg1.Reg := _ECX; Arg2.Reg := _EDI; end;
$C2: begin Arg1.Reg := _EDX; Arg2.Reg := _EAX; end;
$CA: begin Arg1.Reg := _EDX; Arg2.Reg := _ECX; end;
$D2: begin Arg1.Reg := _EDX; Arg2.Reg := _EDX; end;
$DA: begin Arg1.Reg := _EDX; Arg2.Reg := _EBX; end;
$F2: begin Arg1.Reg := _EDX; Arg2.Reg := _ESI; end;
$FA: begin Arg1.Reg := _EDX; Arg2.Reg := _EDI; end;
$C3: begin Arg1.Reg := _EBX; Arg2.Reg := _EAX; end;
$CB: begin Arg1.Reg := _EBX; Arg2.Reg := _ECX; end;
$D3: begin Arg1.Reg := _EBX; Arg2.Reg := _EDX; end;
$DB: begin Arg1.Reg := _EBX; Arg2.Reg := _EBX; end;
$F3: begin Arg1.Reg := _EBX; Arg2.Reg := _ESI; end;
$FB: begin Arg1.Reg := _EBX; Arg2.Reg := _EDI; end;
else
RaiseError(errInternalError, []);
end;
end;
// Add EAX, Imm
$05:
begin
Op := ASM_ADD;
Length := 5;
Arg1.Reg := _EAX;
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
end;
$81:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$C1..$C6: // ADD Reg, Imm
begin
Op := ASM_ADD;
Length := 6;
case B of
$C1: Arg1.Reg := _ECX;
$C2: Arg1.Reg := _EDX;
$C3: Arg1.Reg := _EBX;
$C4: Arg1.Reg := _ESP;
$C5: Arg1.Reg := _EBP;
$C6: Arg1.Reg := _ESI;
end;
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
end;
$80..$86: // ADD DWORD PTR Shift[Reg], Imm
begin
Op := ASM_ADD;
Length := 10;
case B of
$80: Arg1.Reg := _EAX;
$81: Arg1.Reg := _ECX;
$82: Arg1.Reg := _EDX;
$83: Arg1.Reg := _EBX;
$84: Arg1.Reg := _ESP;
$85: Arg1.Reg := _EBP;
$86: Arg1.Reg := _ESI;
end;
Arg1.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
P := ShiftPointer(P, 4);
Move(P^, Arg2.val, 4);
end;
$F9..$FF: // CMP Reg, Imm
begin
Op := ASM_CMP;
Length := 6;
case B of
$F9: Arg1.Reg := _ECX;
$FA: Arg1.Reg := _EDX;
$FB: Arg1.Reg := _EBX;
$FC: Arg1.Reg := _ESP;
$FD: Arg1.Reg := _EBP;
$FE: Arg1.Reg := _ESI;
$FF: Arg1.Reg := _EDI;
end;
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
end;
$E9..$EF: // SUB Reg, Imm
begin
Op := ASM_SUB;
Length := 6;
case B of
$E9: Arg1.Reg := _ECX;
$EA: Arg1.Reg := _EDX;
$EB: Arg1.Reg := _EBX;
$EC: Arg1.Reg := _ESP;
$ED: Arg1.Reg := _EBP;
$EE: Arg1.Reg := _ESI;
$EF: Arg1.Reg := _EDI;
end;
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
end;
$B8..$BE: // CMP DWORD PTR Shift[Reg], Imm
begin
Op := ASM_CMP;
Length := 10;
case B of
$B8: Arg1.Reg := _EAX;
$B9: Arg1.Reg := _ECX;
$BA: Arg1.Reg := _EDX;
$BB: Arg1.Reg := _EBX;
$BC: Arg1.Reg := _ESP;
$BD: Arg1.Reg := _EBP;
$BE: Arg1.Reg := _ESI;
end;
Arg1.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
P := ShiftPointer(P, 4);
Move(P^, Arg2.val, 4);
end;
else
RaiseError(errInternalError, []);
end;
end;
$F7:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$E0..$E3: // mul reg
begin
Op := ASM_MUL;
Length := 2;
case B of
$E0: Arg1.Reg := _EAX;
$E1: Arg1.Reg := _ECX;
$E2: Arg1.Reg := _EDX;
$E3: Arg1.Reg := _EBX;
end;
Arg2.valid := false;
end;
$E8..$EB: // imul reg
begin
Op := ASM_IMUL;
Length := 2;
case B of
$E8: Arg1.Reg := _EAX;
$E9: Arg1.Reg := _ECX;
$EA: Arg1.Reg := _EDX;
$EB: Arg1.Reg := _EBX;
end;
Arg2.valid := false;
end;
$F0..$F3: // div reg
begin
Op := ASM_DIV;
Length := 2;
case B of
$F0: Arg1.Reg := _EAX;
$F1: Arg1.Reg := _ECX;
$F2: Arg1.Reg := _EDX;
$F3: Arg1.Reg := _EBX;
end;
Arg2.valid := false;
end;
$F8..$FB: // idiv reg
begin
Op := ASM_IDIV;
Length := 2;
case B of
$F8: Arg1.Reg := _EAX;
$F9: Arg1.Reg := _ECX;
$FA: Arg1.Reg := _EDX;
$FB: Arg1.Reg := _EBX;
end;
Arg2.valid := false;
end;
$D0..$D3: // not reg
begin
Op := ASM_NOT;
Length := 2;
case B of
$D0: Arg1.Reg := _EAX;
$D1: Arg1.Reg := _ECX;
$D2: Arg1.Reg := _EDX;
$D3: Arg1.Reg := _EBX;
end;
Arg2.valid := false;
end;
$D8..$DB: // neg reg
begin
Op := ASM_NEG;
Length := 2;
case B of
$D8: Arg1.Reg := _EAX;
$D9: Arg1.Reg := _ECX;
$DA: Arg1.Reg := _EDX;
$DB: Arg1.Reg := _EBX;
end;
Arg2.valid := false;
end;
$98..$9E: // neg dword ptr [reg]
begin
Op := ASM_NEG;
Length := 6;
case B of
$98: Arg1.Reg := _EAX;
$99: Arg1.Reg := _ECX;
$9A: Arg1.Reg := _EDX;
$9B: Arg1.Reg := _EBX;
$9C: Arg1.Reg := _ESP;
$9D: Arg1.Reg := _EBP;
$9E: Arg1.Reg := _ESI;
end;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
Arg1.Ptr := true;
Arg2.valid := false;
end;
else
RaiseError(errInternalError, []);
end;
end;
$D3:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Arg2.Reg := _ECX;
Arg2.sz := 1;
Length := 2;
case B of
$E0..$E3: // shl reg, cl
begin
Op := ASM_SHL;
case B of
$E0: Arg1.Reg := _EAX;
$E1: Arg1.Reg := _ECX;
$E2: Arg1.Reg := _EDX;
$E3: Arg1.Reg := _EBX;
end;
end;
$E8..$EB: // shr reg, cl
begin
Op := ASM_SHR;
case B of
$E8: Arg1.Reg := _EAX;
$E9: Arg1.Reg := _ECX;
$EA: Arg1.Reg := _EDX;
$EB: Arg1.Reg := _EBX;
end;
end;
else
RaiseError(errInternalError, []);
end;
end;
//GET REG, BYTE PTR ESI or EBP
$8A:
begin
Op := ASM_MOV;
Arg1.sz := 1;
Arg2.sz := 1;
P := ShiftPointer(P, 1);
B := Byte(P^);
if AssignRegMovESIPtr(B, Arg1) then
begin
Length := 6;
Arg2.Reg := _ESI;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
end
else if AssignRegMovEBPPtr(B, Arg1) then
begin
Length := 6;
Arg2.Reg := _EBP;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
end
else
begin
Length := 2;
Arg2.Ptr := true;
if not AssignR32_R32(B, Arg1, Arg2) then
RaiseError(errInternalError, []);
// case B of
// $00: begin Arg1.Reg := _EAX; Arg2.Reg := _EAX; end;
end;
end;
//GET REG, ESI or EDI or EBP
$8B:
begin
Op := ASM_MOV;
P := ShiftPointer(P, 1);
B := Byte(P^);
Arg1.sz := 4;
Arg2.sz := 4;
if AssignRegMovESIPtr(B, Arg1) then
begin
Length := 6;
Arg2.Reg := _ESI;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end
else if AssignRegMovEBPPtr(B, Arg1) then
begin
Length := 6;
Arg2.Reg := _EBP;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end
else if B = $B4 then
begin
Length := 7;
P := ShiftPointer(P, 1);
B := Byte(P^);
if B <> $24 then
RaiseError(errInternalError, []);
Arg1.Reg := _ESI;
Arg2.Reg := _ESP;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end
else if B = $BC then
begin
Length := 7;
P := ShiftPointer(P, 1);
B := Byte(P^);
if B <> $24 then
RaiseError(errInternalError, []);
Arg1.Reg := _EDI;
Arg2.Reg := _ESP;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end
else
begin
Length := 2;
Arg2.Ptr := true;
if not AssignR32_R32(B, Arg1, Arg2) then
RaiseError(errInternalError, []);
// case B of
// $00: begin Arg1.Reg := _EAX; Arg2.Reg := _EAX; end;
// $01: begin Arg1.Reg := _EAX; Arg2.Reg := _ECX; end;
end;
end; // $8B //GET REG, ESI or EDI or EBP
// Put BYTE PTR [ESI]| BYTE PTR [EBP], REG
$88:
begin
Op := ASM_MOV;
P := ShiftPointer(P, 1);
B := Byte(P^);
Arg1.sz := 1;
Arg2.sz := 1;
if AssignRegMovESIPtr(B, Arg2) then
begin
Length := 6;
Arg1.Ptr := true;
Arg1.Reg := _ESI;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end
else if AssignRegMovEBPPtr(B, Arg2) then
begin
Length := 6;
Arg1.Ptr := true;
Arg1.Reg := _EBP;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end
else
begin
Length := 2;
if AssignR32_R32(B, Arg2, Arg1) then
Arg1.Ptr := true
else
RaiseError(errInternalError, []);
end;
end;
// Put [ESI] REG or MOV REGPtr, REG
$89:
begin
Op := ASM_MOV;
Arg1.sz := 4;
Arg2.sz := 4;
P := ShiftPointer(P, 1);
B := Byte(P^);
if AssignRegMovESIPtr(B, Arg2) then
begin
Length := 6;
Arg1.Ptr := true;
Arg1.Reg := _ESI;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end
else if AssignRegMovEBPPtr(B, Arg2) then
begin
Length := 6;
Arg1.Ptr := true;
Arg1.Reg := _EBP;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end
else
begin
Length := 2;
if not AssignMovR32(B, Arg1, Arg2) then
if AssignR32_R32(B, Arg2, Arg1) then
Arg1.Ptr := true
else
RaiseError(errInternalError, []);
end;
end;
//LEA REG32, [REG32 + Shift]
$8D:
begin
Op := ASM_LEA;
Length := 6;
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$80: begin Arg1.Reg := _EAX; Arg2.Reg := _EAX; end;
$81: begin Arg1.Reg := _EAX; Arg2.Reg := _ECX; end;
$82: begin Arg1.Reg := _EAX; Arg2.Reg := _EDX; end;
$83: begin Arg1.Reg := _EAX; Arg2.Reg := _EBX; end;
$85: begin Arg1.Reg := _EAX; Arg2.Reg := _EBP; end;
$86: begin Arg1.Reg := _EAX; Arg2.Reg := _ESI; end;
$87: begin Arg1.Reg := _EAX; Arg2.Reg := _EDI; end;
$88: begin Arg1.Reg := _ECX; Arg2.Reg := _EAX; end;
$89: begin Arg1.Reg := _ECX; Arg2.Reg := _ECX; end;
$8A: begin Arg1.Reg := _ECX; Arg2.Reg := _EDX; end;
$8B: begin Arg1.Reg := _ECX; Arg2.Reg := _EBX; end;
$8D: begin Arg1.Reg := _ECX; Arg2.Reg := _EBP; end;
$8E: begin Arg1.Reg := _ECX; Arg2.Reg := _ESI; end;
$8F: begin Arg1.Reg := _ECX; Arg2.Reg := _EDI; end;
$90: begin Arg1.Reg := _EDX; Arg2.Reg := _EAX; end;
$91: begin Arg1.Reg := _EDX; Arg2.Reg := _ECX; end;
$92: begin Arg1.Reg := _EDX; Arg2.Reg := _EDX; end;
$93: begin Arg1.Reg := _EDX; Arg2.Reg := _EBX; end;
$95: begin Arg1.Reg := _EDX; Arg2.Reg := _EBP; end;
$96: begin Arg1.Reg := _EDX; Arg2.Reg := _ESI; end;
$97: begin Arg1.Reg := _EDX; Arg2.Reg := _EDI; end;
$98: begin Arg1.Reg := _EBX; Arg2.Reg := _EAX; end;
$99: begin Arg1.Reg := _EBX; Arg2.Reg := _ECX; end;
$9A: begin Arg1.Reg := _EBX; Arg2.Reg := _EDX; end;
$9B: begin Arg1.Reg := _EBX; Arg2.Reg := _EBX; end;
$9D: begin Arg1.Reg := _EBX; Arg2.Reg := _EBP; end;
$9E: begin Arg1.Reg := _EBX; Arg2.Reg := _ESI; end;
$9F: begin Arg1.Reg := _EBX; Arg2.Reg := _EDI; end;
else
RaiseError(errInternalError, []);
end;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end;
// (SUB|XOR|CMP|OR|AND) REG, REG
$29, $31, $39, $09, $21:
begin
case B of
$29: Op := ASM_SUB;
$31: Op := ASM_XOR;
$39: Op := ASM_CMP;
$09: Op := ASM_OR;
$21: Op := ASM_AND;
end;
P := ShiftPointer(P, 1);
B := Byte(P^);
Length := 2;
case B of
$C0: begin Arg1.Reg := _EAX; Arg2.Reg := _EAX; end;
$C8: begin Arg1.Reg := _EAX; Arg2.Reg := _ECX; end;
$D0: begin Arg1.Reg := _EAX; Arg2.Reg := _EDX; end;
$D8: begin Arg1.Reg := _EAX; Arg2.Reg := _EBX; end;
$C1: begin Arg1.Reg := _ECX; Arg2.Reg := _EAX; end;
$C9: begin Arg1.Reg := _ECX; Arg2.Reg := _ECX; end;
$D1: begin Arg1.Reg := _ECX; Arg2.Reg := _EDX; end;
$D9: begin Arg1.Reg := _ECX; Arg2.Reg := _EBX; end;
$C2: begin Arg1.Reg := _EDX; Arg2.Reg := _EAX; end;
$CA: begin Arg1.Reg := _EDX; Arg2.Reg := _ECX; end;
$D2: begin Arg1.Reg := _EDX; Arg2.Reg := _EDX; end;
$DA: begin Arg1.Reg := _EDX; Arg2.Reg := _EBX; end;
$C3: begin Arg1.Reg := _EBX; Arg2.Reg := _EAX; end;
$CB: begin Arg1.Reg := _EBX; Arg2.Reg := _ECX; end;
$D3: begin Arg1.Reg := _EBX; Arg2.Reg := _EDX; end;
$DB: begin Arg1.Reg := _EBX; Arg2.Reg := _EBX; end;
else
RaiseError(errInternalError, []);
end;
end;
$87:
begin
Op := ASM_XCHG;
P := ShiftPointer(P, 1);
B := Byte(P^);
Length := 2;
case B of
$C9: begin Arg1.Reg := _ECX; Arg2.Reg := _ECX; end;
$CA: begin Arg1.Reg := _ECX; Arg2.Reg := _EDX; end;
$CB: begin Arg1.Reg := _ECX; Arg2.Reg := _EBX; end;
$CC: begin Arg1.Reg := _ECX; Arg2.Reg := _ESP; end;
$CD: begin Arg1.Reg := _ECX; Arg2.Reg := _EBP; end;
$CE: begin Arg1.Reg := _ECX; Arg2.Reg := _ESI; end;
$CF: begin Arg1.Reg := _ECX; Arg2.Reg := _EDI; end;
$D1: begin Arg1.Reg := _EDX; Arg2.Reg := _ECX; end;
$D2: begin Arg1.Reg := _EDX; Arg2.Reg := _EDX; end;
$D3: begin Arg1.Reg := _EDX; Arg2.Reg := _EBX; end;
$D4: begin Arg1.Reg := _EDX; Arg2.Reg := _ESP; end;
$D5: begin Arg1.Reg := _EDX; Arg2.Reg := _EBP; end;
$D6: begin Arg1.Reg := _EDX; Arg2.Reg := _ESI; end;
$D7: begin Arg1.Reg := _EDX; Arg2.Reg := _EDI; end;
$D9: begin Arg1.Reg := _EBX; Arg2.Reg := _ECX; end;
$DA: begin Arg1.Reg := _EBX; Arg2.Reg := _EDX; end;
$DB: begin Arg1.Reg := _EBX; Arg2.Reg := _EBX; end;
$DC: begin Arg1.Reg := _EBX; Arg2.Reg := _ESP; end;
$DD: begin Arg1.Reg := _EBX; Arg2.Reg := _EBP; end;
$DE: begin Arg1.Reg := _EBX; Arg2.Reg := _ESI; end;
$DF: begin Arg1.Reg := _EBX; Arg2.Reg := _EDI; end;
else
RaiseError(errInternalError, []);
end;
end;
// FLD|FSTP REG
$DD:
begin
Length := 2;
P := ShiftPointer(P, 1);
B := Byte(P^);
Arg1.Ptr := true;
Arg1.sz := 8;
Arg2.valid := false;
case B of
$00: begin Op := ASM_FLD; Arg1.Reg := _EAX; end;
$01: begin Op := ASM_FLD; Arg1.Reg := _ECX; end;
$02: begin Op := ASM_FLD; Arg1.Reg := _EDX; end;
$03: begin Op := ASM_FLD; Arg1.Reg := _EBX; end;
$18: begin Op := ASM_FSTP; Arg1.Reg := _EAX; end;
$19: begin Op := ASM_FSTP; Arg1.Reg := _ECX; end;
$1A: begin Op := ASM_FSTP; Arg1.Reg := _EDX; end;
$1B: begin Op := ASM_FSTP; Arg1.Reg := _EBX; end;
$80:
begin
Length := 6;
Op := ASM_FLD;
Arg1.Reg := _EAX;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$81:
begin
Length := 6;
Op := ASM_FLD;
Arg1.Reg := _ECX;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$82:
begin
Length := 6;
Op := ASM_FLD;
Arg1.Reg := _EDX;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$83:
begin
Length := 6;
Op := ASM_FLD;
Arg1.Reg := _EBX;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$85:
begin
Length := 6;
Op := ASM_FLD;
Arg1.Reg := _EBP;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$86:
begin
Length := 6;
Op := ASM_FLD;
Arg1.Reg := _ESI;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$98:
begin
Length := 6;
Op := ASM_FSTP;
Arg1.Reg := _EAX;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$99:
begin
Length := 6;
Op := ASM_FSTP;
Arg1.Reg := _ECX;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$9A:
begin
Length := 6;
Op := ASM_FSTP;
Arg1.Reg := _EDX;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$9B:
begin
Length := 6;
Op := ASM_FSTP;
Arg1.Reg := _EBX;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$9D:
begin
Length := 6;
Op := ASM_FSTP;
Arg1.Reg := _EBP;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$9E:
begin
Length := 6;
Op := ASM_FSTP;
Arg1.Reg := _ESI;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
else
RaiseError(errInternalError, []);
end;
end;
// FILD REG PTR32
$DB:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
if B in [$00..$03] then
begin
Op := ASM_FILD;
Length := 2;
Arg1.Ptr := true;
Arg1.sz := 4;
Arg2.valid := false;
case B of
$00: Arg1.Reg := _EAX;
$01: Arg1.Reg := _ECX;
$02: Arg1.Reg := _EDX;
$03: Arg1.Reg := _EBX;
end;
end
else if B in [$28..$2B] then // Fld TBYTE PTR [REG]
begin
Op := ASM_FLD;
Length := 2;
Arg1.Ptr := true;
Arg1.sz := 10;
case B of
$28: Arg1.Reg := _EAX;
$29: Arg1.Reg := _ECX;
$2A: Arg1.Reg := _EDX;
$2B: Arg1.Reg := _EBX;
end;
Arg2.valid := false;
end
else if B in [$38..$3B] then // FStp TBYTE PTR [REG]
begin
Op := ASM_FSTP;
Length := 2;
Arg1.Ptr := true;
Arg1.sz := 10;
case B of
$38: Arg1.Reg := _EAX;
$39: Arg1.Reg := _ECX;
$3A: Arg1.Reg := _EDX;
$3B: Arg1.Reg := _EBX;
end;
Arg2.valid := false;
end
else if B in [$A8..$AE] then
begin
Op := ASM_FLD; // Fld TBYTE PTR [REG + Shift]
Length := 6;
Arg1.Ptr := true;
Arg1.sz := 10;
case B of
$A8: Arg1.Reg := _EAX;
$A9: Arg1.Reg := _ECX;
$AA: Arg1.Reg := _EDX;
$AB: Arg1.Reg := _EBX;
$AD: Arg1.Reg := _EBP;
$AE: Arg1.Reg := _ESP;
end;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
Arg2.valid := false;
end
else if B in [$B8..$BE] then
begin
Op := ASM_FSTP; // FSTP TBYTE PTR [REG + Shift]
Length := 6;
Arg1.Ptr := true;
Arg1.sz := 10;
case B of
$B8: Arg1.Reg := _EAX;
$B9: Arg1.Reg := _ECX;
$BA: Arg1.Reg := _EDX;
$BB: Arg1.Reg := _EBX;
$BD: Arg1.Reg := _EBP;
$BE: Arg1.Reg := _ESP;
end;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
Arg2.valid := false;
end
else
RaiseError(errInternalError, []);
end;
// FADD, DSUB, FMUL, FDIV REG
$DC:
begin
Length := 2;
P := ShiftPointer(P, 1);
B := Byte(P^);
Arg1.Ptr := true;
Arg1.sz := 8;
Arg2.valid := false;
case B of
$00: begin Op := ASM_FADD; Arg1.Reg := _EAX; end;
$01: begin Op := ASM_FADD; Arg1.Reg := _ECX; end;
$02: begin Op := ASM_FADD; Arg1.Reg := _EDX; end;
$03: begin Op := ASM_FADD; Arg1.Reg := _EBX; end;
$20: begin Op := ASM_FSUB; Arg1.Reg := _EAX; end;
$21: begin Op := ASM_FSUB; Arg1.Reg := _ECX; end;
$22: begin Op := ASM_FSUB; Arg1.Reg := _EDX; end;
$23: begin Op := ASM_FSUB; Arg1.Reg := _EBX; end;
$08: begin Op := ASM_FMUL; Arg1.Reg := _EAX; end;
$09: begin Op := ASM_FMUL; Arg1.Reg := _ECX; end;
$0A: begin Op := ASM_FMUL; Arg1.Reg := _EDX; end;
$0B: begin Op := ASM_FMUL; Arg1.Reg := _EBX; end;
$30: begin Op := ASM_FDIV; Arg1.Reg := _EAX; end;
$31: begin Op := ASM_FDIV; Arg1.Reg := _ECX; end;
$32: begin Op := ASM_FDIV; Arg1.Reg := _EDX; end;
$33: begin Op := ASM_FDIV; Arg1.Reg := _EBX; end;
else
RaiseError(errInternalError, []);
end;
end;
// FCOMP
$D8:
begin
Op := ASM_FCOMP;
Length := 2;
P := ShiftPointer(P, 1);
B := Byte(P^);
Arg1.Ptr := true;
Arg1.sz := 8;
Arg2.valid := false;
if B = $8E then
begin
Length := 6;
P := ShiftPointer(P, 1);
Op := ASM_FMUL;
Arg1.sz := 4;
Arg1.Reg := _ESI;
Move(P^, Arg1.val, 4);
Exit;
end
else if B = $B6 then
begin
Length := 6;
P := ShiftPointer(P, 1);
Op := ASM_FDIV;
Arg1.sz := 4;
Arg1.Reg := _ESI;
Move(P^, Arg1.val, 4);
Exit;
end;
case B of
$18: Arg1.Reg := _EAX;
$19: Arg1.Reg := _ECX;
$1A: Arg1.Reg := _EDX;
$1B: Arg1.Reg := _EBX;
else
RaiseError(errInternalError, []);
end;
end;
// FSTSV
$DF:
begin
Length := 2;
P := ShiftPointer(P, 1);
B := Byte(P^);
if B in [$00..$03] then
begin
Op := ASM_FILD;
Length := 2;
Arg1.Ptr := true;
Arg1.sz := 2;
Arg2.valid := false;
case B of
$00: Arg1.Reg := _EAX;
$01: Arg1.Reg := _ECX;
$02: Arg1.Reg := _EDX;
$03: Arg1.Reg := _EBX;
end;
Exit;
end
else if B in [$28..$2B] then
begin
Op := ASM_FILD;
Arg1.Ptr := true;
Arg1.sz := 8;
Arg2.valid := false;
case B of
$28: Arg1.Reg := _EAX;
$29: Arg1.Reg := _ECX;
$2A: Arg1.Reg := _EDX;
$2B: Arg1.Reg := _EBX;
else
RaiseError(errInternalError, []);
end;
Exit;
end
else if B in [$38..$3B] then
begin
Op := ASM_FISTP;
Arg1.Ptr := true;
Arg1.sz := 8;
Arg2.valid := false;
case B of
$38: Arg1.Reg := _EAX;
$39: Arg1.Reg := _ECX;
$3A: Arg1.Reg := _EDX;
$3B: Arg1.Reg := _EBX;
else
RaiseError(errInternalError, []);
end;
Exit;
end;
Op := ASM_FSTSV;
Arg1.sz := 2;
Arg2.valid := false;
case B of
$E0: Arg1.Reg := _EAX;
else
RaiseError(errInternalError, []);
end;
end; // $DF
$9E: //SAHF
begin
op := ASM_SAHF;
Length := 1;
Arg1.valid := false;
Arg2.valid := false;
end;
$99: //CDQ
begin
op := ASM_CDQ;
Length := 1;
Arg1.valid := false;
Arg2.valid := false;
end;
// FADD, FSUB, FMUL, FDIV, FCOMPP
$DE:
begin
Length := 2;
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$C1: op := ASM_FADD;
$C9: op := ASM_FMUL;
$D9: op := ASM_FCOMPP;
$E9: op := ASM_FSUB;
$F9: op := ASM_FDIV;
else
RaiseError(errInternalError, []);
end;
Arg1.valid := false;
Arg2.valid := false;
end;
// FCHS
$D9:
begin
Length := 2;
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$E0: op := ASM_FCHS;
$E1: op := ASM_FABS;
else
begin
// FLD|FSTP (Single) REG
Arg1.Ptr := true;
Arg1.sz := 4;
Arg2.valid := false;
case B of
$00: begin Op := ASM_FLD; Arg1.Reg := _EAX; end;
$01: begin Op := ASM_FLD; Arg1.Reg := _ECX; end;
$02: begin Op := ASM_FLD; Arg1.Reg := _EDX; end;
$03: begin Op := ASM_FLD; Arg1.Reg := _EBX; end;
$18: begin Op := ASM_FSTP; Arg1.Reg := _EAX; end;
$19: begin Op := ASM_FSTP; Arg1.Reg := _ECX; end;
$1A: begin Op := ASM_FSTP; Arg1.Reg := _EDX; end;
$1B: begin Op := ASM_FSTP; Arg1.Reg := _EBX; end;
$80:
begin
Length := 6;
Op := ASM_FLD;
Arg1.Reg := _EAX;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$81:
begin
Length := 6;
Op := ASM_FLD;
Arg1.Reg := _ECX;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$82:
begin
Length := 6;
Op := ASM_FLD;
Arg1.Reg := _EDX;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$83:
begin
Length := 6;
Op := ASM_FLD;
Arg1.Reg := _EBX;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$85:
begin
Length := 6;
Op := ASM_FLD;
Arg1.Reg := _EBP;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$86:
begin
Length := 6;
Op := ASM_FLD;
Arg1.Reg := _ESI;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$98:
begin
Length := 6;
Op := ASM_FSTP;
Arg1.Reg := _EAX;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$99:
begin
Length := 6;
Op := ASM_FSTP;
Arg1.Reg := _ECX;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$9A:
begin
Length := 6;
Op := ASM_FSTP;
Arg1.Reg := _EDX;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$9B:
begin
Length := 6;
Op := ASM_FSTP;
Arg1.Reg := _EBX;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$9D:
begin
Length := 6;
Op := ASM_FSTP;
Arg1.Reg := _EBP;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$9E:
begin
Length := 6;
Op := ASM_FSTP;
Arg1.Reg := _ESI;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
else
RaiseError(errInternalError, []);
end;
Exit;
end;
end;
Arg1.valid := false;
Arg2.valid := false;
end;
// SETL, SETLE, SETNLE, SETNL,
// SETB, SETBE, SETNBE, SETNB, SETZ, SETNZ
$0F:
begin
Length := 3;
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$92: Op := ASM_SETB;
$93: Op := ASM_SETNB;
$94: Op := ASM_SETZ;
$95: Op := ASM_SETNZ;
$96: Op := ASM_SETBE;
$97: Op := ASM_SETNBE;
$9C: Op := ASM_SETL;
$9D: Op := ASM_SETNL;
$9E: Op := ASM_SETLE;
$9F: Op := ASM_SETNLE;
else
RaiseError(errInternalError, []);
end;
P := ShiftPointer(P, 1);
B := Byte(P^);
Arg1.Ptr := true;
Arg1.sz := 1;
Arg2.valid := false;
case B of
$00: Arg1.Reg := _EAX;
$01: Arg1.Reg := _ECX;
$02: Arg1.Reg := _EDX;
$03: Arg1.Reg := _EBX;
$80..$86:
begin
case B of
$80: Arg1.Reg := _EAX;
$81: Arg1.Reg := _ECX;
$82: Arg1.Reg := _EDX;
$83: Arg1.Reg := _EBX;
$84: Arg1.Reg := _ESP;
$85: Arg1.Reg := _EBP;
$86: Arg1.Reg := _ESI;
end;
Length := 7;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
else
RaiseError(errInternalError, []);
end;
end;
$80:
begin
Arg1.sz := 1;
Arg1.Ptr := true;
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$80..$86: // ADD BYTE PTR [REG + Shift], imm
begin
Op := ASM_ADD;
Length := 7;
case B of
$80: Arg1.Reg := _EAX;
$81: Arg1.Reg := _ECX;
$82: Arg1.Reg := _EDX;
$83: Arg1.Reg := _EBX;
$84: Arg1.Reg := _ESP;
$85: Arg1.Reg := _EBP;
$86: Arg1.Reg := _ESI;
end;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
P := ShiftPointer(P, 4);
B := Byte(P^);
Arg2.val := B;
end;
$B8..$BE: // CMP BYTE PTR [REG + Shift], imm
begin
Op := ASM_CMP;
Length := 7;
case B of
$B8: Arg1.Reg := _EAX;
$B9: Arg1.Reg := _ECX;
$BA: Arg1.Reg := _EDX;
$BB: Arg1.Reg := _EBX;
$BC: Arg1.Reg := _ESP;
$BD: Arg1.Reg := _EBP;
$BE: Arg1.Reg := _ESI;
end;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
P := ShiftPointer(P, 4);
B := Byte(P^);
Arg2.val := B;
end;
$38..$3B: // CMP BYTE PTR [REG], imm
begin
op := ASM_CMP;
Length := 3;
case B of
$38: Arg1.Reg := _EAX;
$39: Arg1.Reg := _ECX;
$3A: Arg1.Reg := _EDX;
$3B: Arg1.Reg := _EBX;
end;
P := ShiftPointer(P, 1);
B := Byte(P^);
Arg2.val := B;
end;
else
RaiseError(errInternalError, []);
end;
end;
$E9:
begin
op := ASM_JMP;
Length := 5;
Arg2.valid := false;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$2D:
begin
op := ASM_SUB;
Length := 5;
Arg1.Reg := _EAX;
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
end;
$3D:
begin
op := ASM_CMP;
Length := 5;
Arg1.Reg := _EAX;
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
end;
// CALL REG| JMP REG| PUSH REGPtr| Inc REGPtr, Dec REGPtr
$FF:
begin
Length := 2;
Arg2.valid := false;
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$E0: begin Op := ASM_JMP; Arg1.Reg := _EAX; end;
$E1: begin Op := ASM_JMP; Arg1.Reg := _ECX; end;
$E2: begin Op := ASM_JMP; Arg1.Reg := _EDX; end;
$E3: begin Op := ASM_JMP; Arg1.Reg := _EBX; end;
$D0: begin Op := ASM_CALL; Arg1.Reg := _EAX; end;
$D1: begin Op := ASM_CALL; Arg1.Reg := _ECX; end;
$D2: begin Op := ASM_CALL; Arg1.Reg := _EDX; end;
$D3: begin Op := ASM_CALL; Arg1.Reg := _EBX; end;
$D4: begin Op := ASM_CALL; Arg1.Reg := _ESP; end;
$D5: begin Op := ASM_CALL; Arg1.Reg := _EBP; end;
$D6: begin Op := ASM_CALL; Arg1.Reg := _ESI; end;
$D7: begin Op := ASM_CALL; Arg1.Reg := _EDI; end;
$30: begin Op := ASM_PUSH; Arg1.Ptr := true; Arg1.sz := 4; Arg1.Reg := _EAX; end;
$31: begin Op := ASM_PUSH; Arg1.Ptr := true; Arg1.sz := 4; Arg1.Reg := _ECX; end;
$32: begin Op := ASM_PUSH; Arg1.Ptr := true; Arg1.sz := 4; Arg1.Reg := _EDX; end;
$33: begin Op := ASM_PUSH; Arg1.Ptr := true; Arg1.sz := 4; Arg1.Reg := _EBX; end;
$80..$8F: // INC, DEC
begin
Length := 6;
Arg1.Ptr := true;
Arg1.sz := 4;
if B in [$80..$87] then
Op := ASM_INC
else
Op := ASM_DEC;
case B of
$80: Arg1.Reg := _EAX;
$81: Arg1.Reg := _ECX;
$82: Arg1.Reg := _EDX;
$83: Arg1.Reg := _EBX;
$84: RaiseError(errInternalError, []);
$85: Arg1.Reg := _EBP;
$86: Arg1.Reg := _ESI;
$87: Arg1.Reg := _EDI;
$88: Arg1.Reg := _EAX;
$89: Arg1.Reg := _ECX;
$8A: Arg1.Reg := _EDX;
$8B: Arg1.Reg := _EBX;
$8C: RaiseError(errInternalError, []);
$8D: Arg1.Reg := _EBP;
$8E: Arg1.Reg := _ESI;
$8F: Arg1.Reg := _EDI;
end;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end
else
RaiseError(errInternalError, []);
end;
end;
// PUSH Imm
$68:
begin
Op := ASM_PUSH;
Length := 5;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
Arg2.valid := false;
end;
$84:
begin
Op := ASM_TEST;
Length := 2;
Arg1.sz := 1;
Arg1.sz := 1;
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$D2: begin Arg1.Reg := _EDX; Arg2.Reg := _EDX; end;
else
RaiseError(errInternalError, []);
end;
end;
// PUSH REG | POP REG
$50..$57, $58..$5F:
begin
Length := 1;
Arg2.valid := false;
case B of
$50: begin Op := ASM_PUSH; Arg1.Reg := _EAX; end;
$51: begin Op := ASM_PUSH; Arg1.Reg := _ECX; end;
$52: begin Op := ASM_PUSH; Arg1.Reg := _EDX; end;
$53: begin Op := ASM_PUSH; Arg1.Reg := _EBX; end;
$54: begin Op := ASM_PUSH; Arg1.Reg := _ESP; end;
$55: begin Op := ASM_PUSH; Arg1.Reg := _EBP; end;
$56: begin Op := ASM_PUSH; Arg1.Reg := _ESI; end;
$57: begin Op := ASM_PUSH; Arg1.Reg := _EDI; end;
$58: begin Op := ASM_POP; Arg1.Reg := _EAX; end;
$59: begin Op := ASM_POP; Arg1.Reg := _ECX; end;
$5A: begin Op := ASM_POP; Arg1.Reg := _EDX; end;
$5B: begin Op := ASM_POP; Arg1.Reg := _EBX; end;
$5C: begin Op := ASM_POP; Arg1.Reg := _ESP; end;
$5D: begin Op := ASM_POP; Arg1.Reg := _EBP; end;
$5E: begin Op := ASM_POP; Arg1.Reg := _ESI; end;
$5F: begin Op := ASM_POP; Arg1.Reg := _EDI; end;
else
RaiseError(errInternalError, []);
end;
end;
$C6:
begin
Arg1.sz := 1;
Arg1.Ptr := true;
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$00..$06: // MOV BYTE PTR [REG], imm
begin
Op := ASM_MOV;
Length := 3;
case B of
$00: Arg1.Reg := _EAX;
$01: Arg1.Reg := _ECX;
$02: Arg1.Reg := _EDX;
$03: Arg1.Reg := _EBX;
$04: Arg1.Reg := _ESP;
$05: Arg1.Reg := _EBP;
$06: Arg1.Reg := _ESI;
end;
P := ShiftPointer(P, 1);
B := Byte(P^);
Arg2.val := B;
end;
$80..$86: // MOV BYTE PTR [REG + Shift], imm
begin
Op := ASM_MOV;
Length := 7;
case B of
$80: Arg1.Reg := _EAX;
$81: Arg1.Reg := _ECX;
$82: Arg1.Reg := _EDX;
$83: Arg1.Reg := _EBX;
$84: Arg1.Reg := _ESP;
$85: Arg1.Reg := _EBP;
$86: Arg1.Reg := _ESI;
end;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
P := ShiftPointer(P, 4);
B := Byte(P^);
Arg2.val := B;
end;
else
RaiseError(errInternalError, []);
end;
end;
$C7:
begin
Arg1.sz := 4;
Arg1.Ptr := true;
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$00..$06: // MOV DWORD PTR [REG], imm
begin
Op := ASM_MOV;
case B of
$00: Arg1.Reg := _EAX;
$01: Arg1.Reg := _ECX;
$02: Arg1.Reg := _EDX;
$03: Arg1.Reg := _EBX;
$04: Arg1.Reg := _ESP;
$05: Arg1.Reg := _EBP;
$06: Arg1.Reg := _ESI;
else
RaiseError(errInternalError, []);
end;
Length := 6;
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
end;
$80..$86: // MOV DWORD PTR [REG + Shift], imm
begin
Op := ASM_MOV;
Length := 10;
case B of
$80: Arg1.Reg := _EAX;
$81: Arg1.Reg := _ECX;
$82: Arg1.Reg := _EDX;
$83: Arg1.Reg := _EBX;
$84: Arg1.Reg := _ESP;
$85: Arg1.Reg := _EBP;
$86: Arg1.Reg := _ESI;
end;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
P := ShiftPointer(P, 4);
Move(P^, Arg2.val, 4);
end;
else
RaiseError(errInternalError, []);
end;
end;
$64:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$FF:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$30: Arg1.Reg := _EAX;
$31: Arg1.Reg := _ECX;
$32: Arg1.Reg := _EDX;
$33: Arg1.Reg := _EBX;
else
RaiseError(errInternalError, []);
end;
Op := ASM_PUSH;
Length := 3;
Arg1.Ptr := true;
Arg1.FS := true;
Arg2.valid := false;
end;
$89:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_MOV;
Length := 3;
Arg1.Ptr := true;
Arg1.FS := true;
Arg2.valid := true;
case B of
$00: begin Arg1.Reg := _EAX; Arg2.Reg := _EAX; end;
$08: begin Arg1.Reg := _EAX; Arg2.Reg := _ECX; end;
$10: begin Arg1.Reg := _EAX; Arg2.Reg := _EDX; end;
$18: begin Arg1.Reg := _EAX; Arg2.Reg := _EBX; end;
$20: begin Arg1.Reg := _EAX; Arg2.Reg := _ESP; end;
$28: begin Arg1.Reg := _EAX; Arg2.Reg := _EBP; end;
$30: begin Arg1.Reg := _EAX; Arg2.Reg := _ESI; end;
$38: begin Arg1.Reg := _EAX; Arg2.Reg := _EDI; end;
$01: begin Arg1.Reg := _ECX; Arg2.Reg := _EAX; end;
$09: begin Arg1.Reg := _ECX; Arg2.Reg := _ECX; end;
$11: begin Arg1.Reg := _ECX; Arg2.Reg := _EDX; end;
$19: begin Arg1.Reg := _ECX; Arg2.Reg := _EBX; end;
$21: begin Arg1.Reg := _ECX; Arg2.Reg := _ESP; end;
$29: begin Arg1.Reg := _ECX; Arg2.Reg := _EBP; end;
$31: begin Arg1.Reg := _ECX; Arg2.Reg := _ESI; end;
$39: begin Arg1.Reg := _ECX; Arg2.Reg := _EDI; end;
$02: begin Arg1.Reg := _EDX; Arg2.Reg := _EAX; end;
$0A: begin Arg1.Reg := _EDX; Arg2.Reg := _ECX; end;
$12: begin Arg1.Reg := _EDX; Arg2.Reg := _EDX; end;
$1A: begin Arg1.Reg := _EDX; Arg2.Reg := _EBX; end;
$22: begin Arg1.Reg := _EDX; Arg2.Reg := _ESP; end;
$2A: begin Arg1.Reg := _EDX; Arg2.Reg := _EBP; end;
$32: begin Arg1.Reg := _EDX; Arg2.Reg := _ESI; end;
$3A: begin Arg1.Reg := _EDX; Arg2.Reg := _EDI; end;
$03: begin Arg1.Reg := _EBX; Arg2.Reg := _EAX; end;
$0B: begin Arg1.Reg := _EBX; Arg2.Reg := _ECX; end;
$13: begin Arg1.Reg := _EBX; Arg2.Reg := _EDX; end;
$1B: begin Arg1.Reg := _EBX; Arg2.Reg := _EBX; end;
$23: begin Arg1.Reg := _EBX; Arg2.Reg := _ESP; end;
$2B: begin Arg1.Reg := _EBX; Arg2.Reg := _EBP; end;
$33: begin Arg1.Reg := _EBX; Arg2.Reg := _ESI; end;
$3B: begin Arg1.Reg := _EBX; Arg2.Reg := _EDI; end;
else
RaiseError(errInternalError, []);
end;
end;
else
RaiseError(errInternalError, []);
end;
end;
$66:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$41:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$89:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_MOV;
Length := 4;
Arg1.sz := 2;
Arg2.sz := 2;
Arg1.Ptr := true;
if not AssignR32_R64(B, Arg2, Arg1) then
RaiseError(errInternalError, []);
end;
$8B:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_MOV;
Length := 4;
Arg1.sz := 2;
Arg2.sz := 2;
Arg2.Ptr := true;
if not AssignR32_R64(B, Arg1, Arg2) then
RaiseError(errInternalError, []);
// case B of
// $00: begin Arg1.Reg := _EAX; Arg2.Reg := _R8; end;
end;
else
RaiseError(errInternalError, []);
end;
end;
$45:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$89:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_MOV;
Length := 4;
Arg1.sz := 2;
Arg2.sz := 2;
Arg1.Ptr := true;
if not AssignR64_R64(B, Arg2, Arg1) then
RaiseError(errInternalError, []);
// case B of
// $00: begin Arg1.Reg := _R8; Arg2.Reg := _R8; end;
end;
$8B:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_MOV;
Length := 4;
Arg1.sz := 2;
Arg2.sz := 2;
Arg2.Ptr := true;
if not AssignR64_R64(B, Arg1, Arg2) then
RaiseError(errInternalError, []);
// case B of
// $00: begin Arg1.Reg := _R8; Arg2.Reg := _R8; end;
end;
else
RaiseError(errInternalError, []);
end;
end;
$44:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$89:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Arg1.sz := 2;
Arg2.sz := 2;
if AssignRegMovRBPPtr(B, Arg2) then
begin
Op := ASM_MOV;
Length := 8;
Arg1.Reg := _EBP;
Arg1.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end
else if AssignRegMovRSIPtr(B, Arg2) then
begin
Op := ASM_MOV;
Length := 8;
Arg1.Reg := _ESI;
Arg1.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end
else
begin
Op := ASM_MOV;
Length := 4;
if AssignR64_R32(B, Arg2, Arg1) then
Arg1.Ptr := true
else
RaiseError(errInternalError, []);
end;
end;
$8B:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Arg1.sz := 2;
Arg2.sz := 2;
if AssignRegMovRBPPtr(B, Arg1) then
begin
Op := ASM_MOV;
Length := 8;
Arg2.Reg := _EBP;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
end
else if AssignRegMovRSIPtr(B, Arg1) then
begin
Op := ASM_MOV;
Length := 8;
Arg2.Reg := _ESI;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
end
else
begin
Op := ASM_MOV;
Length := 4;
Arg2.Ptr := true;
if not AssignR64_R32(B, Arg1, Arg2) then
RaiseError(errInternalError, []);
// case B of
// $00: begin Arg1.Reg := _R8; Arg2.Reg := _EAX; end;
end;
end;
else
RaiseError(errInternalError, []);
end;
end;
$50..$53: // PUSH REG16
begin
Op := ASM_PUSH;
Length := 2;
Arg1.sz := 2;
case B of
$50: Arg1.Reg := _EAX;
$51: Arg1.Reg := _ECX;
$52: Arg1.Reg := _EDX;
$53: Arg1.Reg := _EBX;
end;
Arg2.valid := false;
end;
$C7: // MOV WORD PTR [REG], Imm
begin
Op := ASM_MOV;
Length := 9;
Arg1.Ptr := true;
Arg1.sz := 2;
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$80: Arg1.Reg := _EAX;
$81: Arg1.Reg := _ECX;
$82: Arg1.Reg := _EDX;
$83: Arg1.Reg := _EBX;
$84: Arg1.Reg := _ESP;
$85: Arg1.Reg := _EBP;
$86: Arg1.Reg := _ESI;
else
RaiseError(errInternalError, []);
end;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
P := ShiftPointer(P, 4);
Move(P^, Arg2.val, 2);
end;
$81:
begin
Length := 9;
Arg1.Ptr := true;
Arg1.sz := 2;
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$80..$86: // ADD WORD PTR [REG], Imm
begin
Op := ASM_ADD;
case B of
$80: Arg1.Reg := _EAX;
$81: Arg1.Reg := _ECX;
$82: Arg1.Reg := _EDX;
$83: Arg1.Reg := _EBX;
$84: Arg1.Reg := _ESP;
$85: Arg1.Reg := _EBP;
$86: Arg1.Reg := _ESI;
end;
end;
$B8..$BE: // WORD PTR [REG], Imm
begin
Op := ASM_CMP;
case B of
$B8: Arg1.Reg := _EAX;
$B9: Arg1.Reg := _ECX;
$BA: Arg1.Reg := _EDX;
$BB: Arg1.Reg := _EBX;
$BC: Arg1.Reg := _ESP;
$BD: Arg1.Reg := _EBP;
$BE: Arg1.Reg := _ESI;
end;
end;
else
RaiseError(errInternalError, []);
end;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
P := ShiftPointer(P, 4);
Move(P^, Arg2.val, 2);
end;
$8B: // MOV Reg16, WORD PTR [REG]
begin
Op := ASM_MOV;
Length := 3;
Arg1.sz := 2;
Arg2.sz := 2;
P := ShiftPointer(P, 1);
B := Byte(P^);
if AssignRegMovESIPtr(B, Arg1) then
// MOV Reg16, WORD PTR [ESI + Shift]
begin
Length := 7;
Arg2.Reg := _ESI;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end
else if AssignRegMovEBPPtr(B, Arg1) then
// MOV Reg16, WORD PTR [EBP + Shift]
begin
Length := 7;
Arg2.Reg := _EBP;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end
// MOV Reg16, WORD PTR [REG]
else
begin
if not AssignR32_R32(B, Arg1, Arg2) then
RaiseError(errInternalError, []);
// $00: begin Arg1.Reg := _EAX; Arg2.Reg := _EAX; end;
// $01: begin Arg1.Reg := _EAX; Arg2.Reg := _ECX; end;
end;
Arg2.Ptr := true;
end;
$89: // MOVE WORD PTR [Reg], Reg16
begin
Op := ASM_MOV;
Arg1.Ptr := true;
Arg1.sz := 2;
Arg2.sz := 2;
Length := 3;
P := ShiftPointer(P, 1);
B := Byte(P^);
if AssignRegMovESIPtr(B, Arg2) then
// MOV WORD PTR [ESI + Shift], Reg16
begin
Length := 7;
Arg1.Reg := _ESI;
P := ShiftPointer(P, 1);
Move(P^, Arg1.Val, 4);
end
else if AssignRegMovEBPPtr(B, Arg2) then
// MOV WORD PTR [EBP + Shift], Reg16
begin
Length := 7;
Arg1.Reg := _EBP;
P := ShiftPointer(P, 1);
Move(P^, Arg1.Val, 4);
end
else
begin
if not AssignR32_R32(B, Arg2, Arg1) then
RaiseError(errInternalError, []);
end;
end;
end;
end;
else
begin
if not Pax64 then
RaiseError(errInternalError, []);
case B of
$41:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
if B in [$50..$57, $58..$5F] then
begin
Length := 2;
Arg2.valid := false;
case B of
$50: begin Op := ASM_PUSH; Arg1.Reg := _R8; end;
$51: begin Op := ASM_PUSH; Arg1.Reg := _R9; end;
$52: begin Op := ASM_PUSH; Arg1.Reg := _R10; end;
$53: begin Op := ASM_PUSH; Arg1.Reg := _R11; end;
$54: begin Op := ASM_PUSH; Arg1.Reg := _R12; end;
$55: begin Op := ASM_PUSH; Arg1.Reg := _R13; end;
$56: begin Op := ASM_PUSH; Arg1.Reg := _R14; end;
$57: begin Op := ASM_PUSH; Arg1.Reg := _R15; end;
$58: begin Op := ASM_POP; Arg1.Reg := _R8; end;
$59: begin Op := ASM_POP; Arg1.Reg := _R9; end;
$5A: begin Op := ASM_POP; Arg1.Reg := _R10; end;
$5B: begin Op := ASM_POP; Arg1.Reg := _R11; end;
$5C: begin Op := ASM_POP; Arg1.Reg := _R12; end;
$5D: begin Op := ASM_POP; Arg1.Reg := _R13; end;
$5E: begin Op := ASM_POP; Arg1.Reg := _R14; end;
$5F: begin Op := ASM_POP; Arg1.Reg := _R15; end;
end;
end
else if B in [$B8, $B9] then
begin
Op := ASM_MOV;
Length := 6;
case B of
$B8: Arg1.Reg := _R8;
$B9: Arg1.Reg := _R9;
else
RaiseError(errInternalError, []);
end;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end
else if B = $81 then
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
if B in [$C0, $C1] then
begin
Op := ASM_ADD;
Length := 7;
case B of
$C0: Arg1.Reg := _R8;
$C1: Arg1.Reg := _R9;
end;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end
else
RaiseError(errInternalError, []);
end
else if B = $88 then
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_MOV;
Length := 3;
Arg1.sz := 1;
Arg2.sz := 1;
Arg1.Ptr := true;
if not AssignR32_R64(B, Arg2, Arg1) then
RaiseError(errInternalError, []);
end
else if B = $89 then
begin
Op := ASM_MOV;
Length := 3;
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$C0: begin Arg1.Reg := _R8; Arg2.Reg := _EAX; end;
$C8: begin Arg1.Reg := _R8; Arg2.Reg := _ECX; end;
$D0: begin Arg1.Reg := _R8; Arg2.Reg := _EDX; end;
$D8: begin Arg1.Reg := _R8; Arg2.Reg := _EBX; end;
$E0: begin Arg1.Reg := _R8; Arg2.Reg := _ESP; end;
$E8: begin Arg1.Reg := _R8; Arg2.Reg := _EBP; end;
$F0: begin Arg1.Reg := _R8; Arg2.Reg := _ESI; end;
$F8: begin Arg1.Reg := _R8; Arg2.Reg := _EDI; end;
$C1: begin Arg1.Reg := _R9; Arg2.Reg := _EAX; end;
$C9: begin Arg1.Reg := _R9; Arg2.Reg := _ECX; end;
$D1: begin Arg1.Reg := _R9; Arg2.Reg := _EDX; end;
$D9: begin Arg1.Reg := _R9; Arg2.Reg := _EBX; end;
$E1: begin Arg1.Reg := _R9; Arg2.Reg := _ESP; end;
$E9: begin Arg1.Reg := _R9; Arg2.Reg := _EBP; end;
$F1: begin Arg1.Reg := _R9; Arg2.Reg := _ESI; end;
$F9: begin Arg1.Reg := _R9; Arg2.Reg := _EDI; end;
else
RaiseError(errInternalError, []);
end;
end
else if B = $8A then
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_MOV;
Length := 3;
Arg1.sz := 1;
Arg2.sz := 1;
Arg2.Ptr := true;
if not AssignR32_R64(B, Arg1, Arg2) then
RaiseError(errInternalError, []);
// case B of
// $00: begin Arg1.Reg := _EAX; Arg2.Reg := _R8; end;
end
else
RaiseError(errInternalError, []);
end;
$44:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$88:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Arg1.sz := 1;
Arg2.sz := 1;
if AssignRegMovRBPPtr(B, Arg2) then
begin
Op := ASM_MOV;
Length := 7;
Arg1.Reg := _EBP;
Arg1.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg1.Val, 4);
end
else if AssignRegMovRSIPtr(B, Arg2) then
begin
Op := ASM_MOV;
Length := 7;
Arg1.Reg := _ESI;
Arg1.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg1.Val, 4);
end
else
begin
Op := ASM_MOV;
Length := 3;
Arg1.Ptr := true;
if not AssignR64_R32(B, Arg2, Arg1) then
RaiseError(errInternalError, []);
end;
end;
$8A:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Arg1.sz := 1;
Arg2.sz := 1;
if AssignRegMovRBPPtr(B, Arg1) then
begin
Op := ASM_MOV;
Length := 7;
Arg2.Reg := _EBP;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end
else if AssignRegMovRSIPtr(B, Arg1) then
begin
Op := ASM_MOV;
Length := 7;
Arg2.Reg := _ESI;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end
else
begin
Op := ASM_MOV;
Length := 3;
Arg2.Ptr := true;
if not AssignR64_R32(B, Arg1, Arg2) then
RaiseError(errInternalError, []);
end;
end;
$8B:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Arg1.sz := 4;
Arg2.sz := 4;
if AssignRegMovRBPPtr(B, Arg1) then
begin
Op := ASM_MOV;
Length := 7;
Arg2.Reg := _EBP;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end
else if AssignRegMovRSIPtr(B, Arg1) then
begin
Op := ASM_MOV;
Length := 7;
Arg2.Reg := _ESI;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end
else if B in [$84, $8C] then
begin
Op := ASM_MOV;
Length := 8;
case B of
$84: Arg1.Reg := _R8;
$8C: Arg1.Reg := _R9;
else
RaiseError(errInternalError, []);
end;
P := ShiftPointer(P, 1);
B := Byte(P^);
if B <> $24 then
RaiseError(errInternalError, []);
Arg2.Reg := _ESP;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end
else
begin
Op := ASM_MOV;
Length := 3;
Arg2.Ptr := true;
if not AssignR64_R32(B, Arg1, Arg2) then
RaiseError(errInternalError, []);
// case B of
// $00: begin Arg1.Reg := _R8; Arg2.Reg := _EAX; end;
end;
end;
$89:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Arg1.sz := 4;
Arg2.sz := 4;
if B in [$84, $8C] then
begin
Op := ASM_MOV;
Length := 8;
case B of
$84: Arg2.Reg := _R8;
$8C: Arg2.Reg := _R9;
else
RaiseError(errInternalError, []);
end;
P := ShiftPointer(P, 1);
B := Byte(P^);
if B <> $24 then
RaiseError(errInternalError, []);
Arg1.Reg := _ESP;
Arg1.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg1.Val, 4);
end
else if AssignRegMovRBPPtr(B, Arg2) then
begin
Op := ASM_MOV;
Length := 7;
Arg1.Reg := _EBP;
Arg1.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg1.Val, 4);
end
else if AssignRegMovRSIPtr(B, Arg2) then
begin
Op := ASM_MOV;
Length := 7;
Arg1.Reg := _ESI;
Arg1.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg1.Val, 4);
end
else
begin
Op := ASM_MOV;
Length := 3;
if AssignR64_R32(B, Arg2, Arg1) then
Arg1.Ptr := true
else
RaiseError(errInternalError, []);
end;
end;
end;
end; //$41
$45:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$88:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_MOV;
Length := 3;
Arg1.sz := 1;
Arg2.sz := 1;
Arg1.Ptr := true;
if not AssignR64_R64(B, Arg2, Arg1) then
RaiseError(errInternalError, []);
end;
$89:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_MOV;
Length := 3;
Arg1.sz := 4;
Arg2.sz := 4;
Arg1.Ptr := true;
if not AssignR64_R64(B, Arg2, Arg1) then
RaiseError(errInternalError, []);
end;
$8A:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_MOV;
Length := 3;
Arg1.sz := 1;
Arg2.sz := 1;
Arg2.Ptr := true;
if not AssignR64_R64(B, Arg1, Arg2) then
RaiseError(errInternalError, []);
// case B of
// $00: begin Arg1.Reg := _R8; Arg2.Reg := _R8; end;
end;
$8B:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_MOV;
Length := 3;
Arg1.sz := 4;
Arg2.sz := 4;
Arg2.Ptr := true;
if not AssignR64_R64(B, Arg1, Arg2) then
RaiseError(errInternalError, []);
// case B of
// $00: begin Arg1.Reg := _R8; Arg2.Reg := _R8; end;
end;
else
RaiseError(errInternalError, []);
end;
end;
$48:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$01:
begin
Op := ASM_ADD;
Length := 3;
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$C0: begin Arg1.Reg := _EAX; Arg2.Reg := _EAX; end;
$C8: begin Arg1.Reg := _EAX; Arg2.Reg := _ECX; end;
$D0: begin Arg1.Reg := _EAX; Arg2.Reg := _EDX; end;
$D8: begin Arg1.Reg := _EAX; Arg2.Reg := _EBX; end;
$F0: begin Arg1.Reg := _EAX; Arg2.Reg := _ESI; end;
$F8: begin Arg1.Reg := _EAX; Arg2.Reg := _EDI; end;
$C1: begin Arg1.Reg := _ECX; Arg2.Reg := _EAX; end;
$C9: begin Arg1.Reg := _ECX; Arg2.Reg := _ECX; end;
$D1: begin Arg1.Reg := _ECX; Arg2.Reg := _EDX; end;
$D9: begin Arg1.Reg := _ECX; Arg2.Reg := _EBX; end;
$F1: begin Arg1.Reg := _ECX; Arg2.Reg := _ESI; end;
$F9: begin Arg1.Reg := _ECX; Arg2.Reg := _EDI; end;
$C2: begin Arg1.Reg := _EDX; Arg2.Reg := _EAX; end;
$CA: begin Arg1.Reg := _EDX; Arg2.Reg := _ECX; end;
$D2: begin Arg1.Reg := _EDX; Arg2.Reg := _EDX; end;
$DA: begin Arg1.Reg := _EDX; Arg2.Reg := _EBX; end;
$F2: begin Arg1.Reg := _EDX; Arg2.Reg := _ESI; end;
$FA: begin Arg1.Reg := _EDX; Arg2.Reg := _EDI; end;
$C3: begin Arg1.Reg := _EBX; Arg2.Reg := _EAX; end;
$CB: begin Arg1.Reg := _EBX; Arg2.Reg := _ECX; end;
$D3: begin Arg1.Reg := _EBX; Arg2.Reg := _EDX; end;
$DB: begin Arg1.Reg := _EBX; Arg2.Reg := _EBX; end;
$F3: begin Arg1.Reg := _EBX; Arg2.Reg := _ESI; end;
$FB: begin Arg1.Reg := _EBX; Arg2.Reg := _EDI; end;
else
RaiseError(errInternalError, []);
end;
end;
$05:
begin
Op := ASM_ADD;
Length := 6;
Arg1.Reg := _EAX;
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
end;
$11:
begin
Op := ASM_ADC;
Length := 3;
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$C0: begin Arg1.Reg := _EAX; Arg2.Reg := _EAX; end;
$C8: begin Arg1.Reg := _EAX; Arg2.Reg := _ECX; end;
$D0: begin Arg1.Reg := _EAX; Arg2.Reg := _EDX; end;
$D8: begin Arg1.Reg := _EAX; Arg2.Reg := _EBX; end;
$F0: begin Arg1.Reg := _EAX; Arg2.Reg := _ESI; end;
$F8: begin Arg1.Reg := _EAX; Arg2.Reg := _EDI; end;
$C1: begin Arg1.Reg := _ECX; Arg2.Reg := _EAX; end;
$C9: begin Arg1.Reg := _ECX; Arg2.Reg := _ECX; end;
$D1: begin Arg1.Reg := _ECX; Arg2.Reg := _EDX; end;
$D9: begin Arg1.Reg := _ECX; Arg2.Reg := _EBX; end;
$F1: begin Arg1.Reg := _ECX; Arg2.Reg := _ESI; end;
$F9: begin Arg1.Reg := _ECX; Arg2.Reg := _EDI; end;
$C2: begin Arg1.Reg := _EDX; Arg2.Reg := _EAX; end;
$CA: begin Arg1.Reg := _EDX; Arg2.Reg := _ECX; end;
$D2: begin Arg1.Reg := _EDX; Arg2.Reg := _EDX; end;
$DA: begin Arg1.Reg := _EDX; Arg2.Reg := _EBX; end;
$F2: begin Arg1.Reg := _EDX; Arg2.Reg := _ESI; end;
$FA: begin Arg1.Reg := _EDX; Arg2.Reg := _EDI; end;
$C3: begin Arg1.Reg := _EBX; Arg2.Reg := _EAX; end;
$CB: begin Arg1.Reg := _EBX; Arg2.Reg := _ECX; end;
$D3: begin Arg1.Reg := _EBX; Arg2.Reg := _EDX; end;
$DB: begin Arg1.Reg := _EBX; Arg2.Reg := _EBX; end;
$F3: begin Arg1.Reg := _EBX; Arg2.Reg := _ESI; end;
$FB: begin Arg1.Reg := _EBX; Arg2.Reg := _EDI; end;
else
RaiseError(errInternalError, []);
end;
end;
$19:
begin
Op := ASM_SBB;
Length := 3;
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$C0: begin Arg1.Reg := _EAX; Arg2.Reg := _EAX; end;
$C8: begin Arg1.Reg := _EAX; Arg2.Reg := _ECX; end;
$D0: begin Arg1.Reg := _EAX; Arg2.Reg := _EDX; end;
$D8: begin Arg1.Reg := _EAX; Arg2.Reg := _EBX; end;
$F0: begin Arg1.Reg := _EAX; Arg2.Reg := _ESI; end;
$F8: begin Arg1.Reg := _EAX; Arg2.Reg := _EDI; end;
$C1: begin Arg1.Reg := _ECX; Arg2.Reg := _EAX; end;
$C9: begin Arg1.Reg := _ECX; Arg2.Reg := _ECX; end;
$D1: begin Arg1.Reg := _ECX; Arg2.Reg := _EDX; end;
$D9: begin Arg1.Reg := _ECX; Arg2.Reg := _EBX; end;
$F1: begin Arg1.Reg := _ECX; Arg2.Reg := _ESI; end;
$F9: begin Arg1.Reg := _ECX; Arg2.Reg := _EDI; end;
$C2: begin Arg1.Reg := _EDX; Arg2.Reg := _EAX; end;
$CA: begin Arg1.Reg := _EDX; Arg2.Reg := _ECX; end;
$D2: begin Arg1.Reg := _EDX; Arg2.Reg := _EDX; end;
$DA: begin Arg1.Reg := _EDX; Arg2.Reg := _EBX; end;
$F2: begin Arg1.Reg := _EDX; Arg2.Reg := _ESI; end;
$FA: begin Arg1.Reg := _EDX; Arg2.Reg := _EDI; end;
$C3: begin Arg1.Reg := _EBX; Arg2.Reg := _EAX; end;
$CB: begin Arg1.Reg := _EBX; Arg2.Reg := _ECX; end;
$D3: begin Arg1.Reg := _EBX; Arg2.Reg := _EDX; end;
$DB: begin Arg1.Reg := _EBX; Arg2.Reg := _EBX; end;
$F3: begin Arg1.Reg := _EBX; Arg2.Reg := _ESI; end;
$FB: begin Arg1.Reg := _EBX; Arg2.Reg := _EDI; end;
else
RaiseError(errInternalError, []);
end;
end;
// (SUB|XOR|CMP|OR|AND) REG, REG
$29, $31, $39, $09, $21:
begin
case B of
$29: Op := ASM_SUB;
$31: Op := ASM_XOR;
$39: Op := ASM_CMP;
$09: Op := ASM_OR;
$21: Op := ASM_AND;
end;
P := ShiftPointer(P, 1);
B := Byte(P^);
Length := 3;
case B of
$C0: begin Arg1.Reg := _EAX; Arg2.Reg := _EAX; end;
$C8: begin Arg1.Reg := _EAX; Arg2.Reg := _ECX; end;
$D0: begin Arg1.Reg := _EAX; Arg2.Reg := _EDX; end;
$D8: begin Arg1.Reg := _EAX; Arg2.Reg := _EBX; end;
$C1: begin Arg1.Reg := _ECX; Arg2.Reg := _EAX; end;
$C9: begin Arg1.Reg := _ECX; Arg2.Reg := _ECX; end;
$D1: begin Arg1.Reg := _ECX; Arg2.Reg := _EDX; end;
$D9: begin Arg1.Reg := _ECX; Arg2.Reg := _EBX; end;
$C2: begin Arg1.Reg := _EDX; Arg2.Reg := _EAX; end;
$CA: begin Arg1.Reg := _EDX; Arg2.Reg := _ECX; end;
$D2: begin Arg1.Reg := _EDX; Arg2.Reg := _EDX; end;
$DA: begin Arg1.Reg := _EDX; Arg2.Reg := _EBX; end;
$C3: begin Arg1.Reg := _EBX; Arg2.Reg := _EAX; end;
$CB: begin Arg1.Reg := _EBX; Arg2.Reg := _ECX; end;
$D3: begin Arg1.Reg := _EBX; Arg2.Reg := _EDX; end;
$DB: begin Arg1.Reg := _EBX; Arg2.Reg := _EBX; end;
else
RaiseError(errInternalError, []);
end;
end;
$81:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$C0..$C7: // ADD Reg, Imm
begin
Op := ASM_ADD;
Length := 7;
case B of
$C0: Arg1.Reg := _EAX;
$C1: Arg1.Reg := _ECX;
$C2: Arg1.Reg := _EDX;
$C3: Arg1.Reg := _EBX;
$C4: Arg1.Reg := _ESP;
$C5: Arg1.Reg := _EBP;
$C6: Arg1.Reg := _ESI;
$C7: Arg1.Reg := _EDI;
end;
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
end;
$80..$86: // ADD DWORD PTR Shift[Reg], Imm
begin
Op := ASM_ADD;
Length := 11;
case B of
$80: Arg1.Reg := _EAX;
$81: Arg1.Reg := _ECX;
$82: Arg1.Reg := _EDX;
$83: Arg1.Reg := _EBX;
$84: Arg1.Reg := _ESP;
$85: Arg1.Reg := _EBP;
$86: Arg1.Reg := _ESI;
end;
Arg1.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
P := ShiftPointer(P, 4);
Move(P^, Arg2.val, 4);
end;
$F9..$FF: // CMP Reg, Imm
begin
Op := ASM_CMP;
Length := 7;
case B of
$F9: Arg1.Reg := _ECX;
$FA: Arg1.Reg := _EDX;
$FB: Arg1.Reg := _EBX;
$FC: Arg1.Reg := _ESP;
$FD: Arg1.Reg := _EBP;
$FE: Arg1.Reg := _ESI;
$FF: Arg1.Reg := _EDI;
end;
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
end;
$E8..$EF: // SUB Reg, Imm
begin
Op := ASM_SUB;
Length := 7;
case B of
$E8: Arg1.Reg := _EAX;
$E9: Arg1.Reg := _ECX;
$EA: Arg1.Reg := _EDX;
$EB: Arg1.Reg := _EBX;
$EC: Arg1.Reg := _ESP;
$ED: Arg1.Reg := _EBP;
$EE: Arg1.Reg := _ESI;
$EF: Arg1.Reg := _EDI;
end;
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
end;
$B8..$BE: // CMP DWORD PTR Shift[Reg], Imm
begin
Op := ASM_CMP;
Length := 11;
case B of
$B8: Arg1.Reg := _EAX;
$B9: Arg1.Reg := _ECX;
$BA: Arg1.Reg := _EDX;
$BB: Arg1.Reg := _EBX;
$BC: Arg1.Reg := _ESP;
$BD: Arg1.Reg := _EBP;
$BE: Arg1.Reg := _ESI;
end;
Arg1.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
P := ShiftPointer(P, 4);
Move(P^, Arg2.val, 4);
end;
else
RaiseError(errInternalError, []);
end;
end;
$89:
begin
Op := ASM_MOV;
P := ShiftPointer(P, 1);
B := Byte(P^);
if AssignRegMovESIPtr(B, Arg2) then
begin
Length := 7;
Arg1.Ptr := true;
Arg1.Reg := _ESI;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end
else if AssignRegMovEBPPtr(B, Arg2) then
begin
Length := 7;
Arg1.Ptr := true;
Arg1.Reg := _EBP;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end
else if B in [$84, $8C, $94, $9C, $A4, $AC, $B4, $BC] then
begin
case B of
$84: Arg2.Reg := _EAX;
$8C: Arg2.Reg := _ECX;
$94: Arg2.Reg := _EDX;
$9C: Arg2.Reg := _EBX;
$A4: Arg2.Reg := _ESP;
$AC: Arg2.Reg := _EBP;
$B4: Arg2.Reg := _ESI;
$BC: Arg2.Reg := _EDI;
end;
P := ShiftPointer(P, 1);
B := Byte(P^);
if B <> $24 then
RaiseError(errInternalError, []);
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
Length := 8;
Arg1.Ptr := true;
Arg1.Reg := _ESP;
end
else
begin
Length := 3;
if not AssignMovR32(B, Arg1, Arg2) then
begin
Arg1.Ptr := true;
if not AssignR32_R32(B, Arg2, Arg1) then
RaiseError(errInternalError, []);
end;
end;
end; //$89
//GET REG, ESI or EDI or EBP
$8B:
begin
Op := ASM_MOV;
P := ShiftPointer(P, 1);
B := Byte(P^);
if B in [$84, $8C, $94, $9C, $A4, $AC, $B4, $BC] then
begin
case B of
$84: Arg1.Reg := _EAX;
$8C: Arg1.Reg := _ECX;
$94: Arg1.Reg := _EDX;
$9C: Arg1.Reg := _EBX;
$A4: Arg1.Reg := _ESP;
$AC: Arg1.Reg := _EBP;
$B4: Arg1.Reg := _ESI;
$BC: Arg1.Reg := _EDI;
end;
P := ShiftPointer(P, 1);
B := Byte(P^);
if B <> $24 then
RaiseError(errInternalError, []);
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
Length := 8;
Arg2.Ptr := true;
Arg2.Reg := _ESP;
end
else if AssignRegMovESIPtr(B, Arg1) then
begin
Length := 7;
Arg2.Reg := _ESI;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end
else if AssignRegMovEBPPtr(B, Arg1) then
begin
Length := 7;
Arg2.Reg := _EBP;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end
else if B = $B4 then
begin
Length := 8;
P := ShiftPointer(P, 1);
B := Byte(P^);
if B <> $24 then
RaiseError(errInternalError, []);
Arg1.Reg := _ESI;
Arg2.Reg := _ESP;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end
else if B = $BC then
begin
Length := 8;
P := ShiftPointer(P, 1);
B := Byte(P^);
if B <> $24 then
RaiseError(errInternalError, []);
Arg1.Reg := _EDI;
Arg2.Reg := _ESP;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end
else
begin
Length := 3;
Arg2.Ptr := true;
if not AssignR32_R32(B, Arg1, Arg2) then
RaiseError(errInternalError, []);
// case B of
// $00: begin Arg1.Reg := _EAX; Arg2.Reg := _EAX; end;
// $01: begin Arg1.Reg := _EAX; Arg2.Reg := _ECX; end;
end;
end; // $8B //GET REG, ESI or EDI or EBP
$8D:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
if B <> $A5 then
RaiseError(errInternalError, []);
P := ShiftPointer(P, 1);
Op := ASM_LEA;
Length := 7;
Arg1.Reg := _ESP;
Arg2.Reg := _EBP;
Arg2.Ptr := true;
Move(P^, Arg2.val, 4);
end;
$C7:
begin
Arg1.sz := 8;
Arg1.Ptr := true;
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$00..$06: // MOV DWORD PTR [REG], imm
begin
Op := ASM_MOV;
case B of
$00: Arg1.Reg := _EAX;
$01: Arg1.Reg := _ECX;
$02: Arg1.Reg := _EDX;
$03: Arg1.Reg := _EBX;
$04: Arg1.Reg := _ESP;
$05: Arg1.Reg := _EBP;
$06: Arg1.Reg := _ESI;
else
RaiseError(errInternalError, []);
end;
Length := 7;
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
end;
$80..$86: // MOV DWORD PTR [REG + Shift], imm
begin
Op := ASM_MOV;
Length := 11;
case B of
$80: Arg1.Reg := _EAX;
$81: Arg1.Reg := _ECX;
$82: Arg1.Reg := _EDX;
$83: Arg1.Reg := _EBX;
$84: Arg1.Reg := _ESP;
$85: Arg1.Reg := _EBP;
$86: Arg1.Reg := _ESI;
end;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
P := ShiftPointer(P, 4);
Move(P^, Arg2.val, 4);
end;
else
RaiseError(errInternalError, []);
end;
end;
$D3:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Arg2.Reg := _ECX;
Arg2.sz := 1;
Length := 3;
case B of
$E0..$E3: // shl reg, cl
begin
Op := ASM_SHL;
case B of
$E0: Arg1.Reg := _EAX;
$E1: Arg1.Reg := _ECX;
$E2: Arg1.Reg := _EDX;
$E3: Arg1.Reg := _EBX;
end;
end;
$E8..$EB: // shr reg, cl
begin
Op := ASM_SHR;
case B of
$E8: Arg1.Reg := _EAX;
$E9: Arg1.Reg := _ECX;
$EA: Arg1.Reg := _EDX;
$EB: Arg1.Reg := _EBX;
end;
end;
else
RaiseError(errInternalError, []);
end;
end;
// Mov EAX, Imm
$B8..$BF:
begin
Op := ASM_MOV;
Length := 10;
case B of
$B8: Arg1.Reg := _EAX;
$B9: Arg1.Reg := _ECX;
$BA: Arg1.Reg := _EDX;
$BB: Arg1.Reg := _EBX;
$BC: Arg1.Reg := _ESP;
$BD: Arg1.Reg := _EBP;
$BE: Arg1.Reg := _ESI;
$BF: Arg1.Reg := _EDI;
else
RaiseError(errInternalError, []);
end;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 8);
end;
// FILD REG PTR32
$DB:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
if B in [$00..$03] then
begin
Op := ASM_FILD;
Length := 3;
Arg1.Ptr := true;
Arg1.sz := 4;
Arg2.valid := false;
case B of
$00: Arg1.Reg := _EAX;
$01: Arg1.Reg := _ECX;
$02: Arg1.Reg := _EDX;
$03: Arg1.Reg := _EBX;
end;
end
else if B in [$28..$2B] then // Fld TBYTE PTR [REG]
begin
Op := ASM_FLD;
Length := 3;
Arg1.Ptr := true;
Arg1.sz := 10;
case B of
$28: Arg1.Reg := _EAX;
$29: Arg1.Reg := _ECX;
$2A: Arg1.Reg := _EDX;
$2B: Arg1.Reg := _EBX;
end;
Arg2.valid := false;
end
else if B in [$38..$3B] then // FStp TBYTE PTR [REG]
begin
Op := ASM_FSTP;
Length := 3;
Arg1.Ptr := true;
Arg1.sz := 10;
case B of
$38: Arg1.Reg := _EAX;
$39: Arg1.Reg := _ECX;
$3A: Arg1.Reg := _EDX;
$3B: Arg1.Reg := _EBX;
end;
Arg2.valid := false;
end
else if B in [$A8..$AE] then
begin
Op := ASM_FLD; // Fld TBYTE PTR [REG + Shift]
Length := 7;
Arg1.Ptr := true;
Arg1.sz := 10;
case B of
$A8: Arg1.Reg := _EAX;
$A9: Arg1.Reg := _ECX;
$AA: Arg1.Reg := _EDX;
$AB: Arg1.Reg := _EBX;
$AD: Arg1.Reg := _EBP;
$AE: Arg1.Reg := _ESP;
end;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
Arg2.valid := false;
end
else if B in [$B8..$BE] then
begin
Op := ASM_FSTP; // FSTP TBYTE PTR [REG + Shift]
Length := 7;
Arg1.Ptr := true;
Arg1.sz := 10;
case B of
$B8: Arg1.Reg := _EAX;
$B9: Arg1.Reg := _ECX;
$BA: Arg1.Reg := _EDX;
$BB: Arg1.Reg := _EBX;
$BD: Arg1.Reg := _EBP;
$BE: Arg1.Reg := _ESP;
end;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
Arg2.valid := false;
end
else
RaiseError(errInternalError, []);
end;
// FLD|FSTP REG
$DD:
begin
Length := 3;
P := ShiftPointer(P, 1);
B := Byte(P^);
Arg1.Ptr := true;
Arg1.sz := 8;
Arg2.valid := false;
case B of
$00: begin Op := ASM_FLD; Arg1.Reg := _EAX; end;
$01: begin Op := ASM_FLD; Arg1.Reg := _ECX; end;
$02: begin Op := ASM_FLD; Arg1.Reg := _EDX; end;
$03: begin Op := ASM_FLD; Arg1.Reg := _EBX; end;
$18: begin Op := ASM_FSTP; Arg1.Reg := _EAX; end;
$19: begin Op := ASM_FSTP; Arg1.Reg := _ECX; end;
$1A: begin Op := ASM_FSTP; Arg1.Reg := _EDX; end;
$1B: begin Op := ASM_FSTP; Arg1.Reg := _EBX; end;
$80:
begin
Length := 7;
Op := ASM_FLD;
Arg1.Reg := _EAX;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$81:
begin
Length := 7;
Op := ASM_FLD;
Arg1.Reg := _ECX;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$82:
begin
Length := 7;
Op := ASM_FLD;
Arg1.Reg := _EDX;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$83:
begin
Length := 7;
Op := ASM_FLD;
Arg1.Reg := _EBX;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$85:
begin
Length := 7;
Op := ASM_FLD;
Arg1.Reg := _EBP;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$86:
begin
Length := 7;
Op := ASM_FLD;
Arg1.Reg := _ESI;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$98:
begin
Length := 7;
Op := ASM_FSTP;
Arg1.Reg := _EAX;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$99:
begin
Length := 7;
Op := ASM_FSTP;
Arg1.Reg := _ECX;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$9A:
begin
Length := 7;
Op := ASM_FSTP;
Arg1.Reg := _EDX;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$9B:
begin
Length := 7;
Op := ASM_FSTP;
Arg1.Reg := _EBX;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$9D:
begin
Length := 7;
Op := ASM_FSTP;
Arg1.Reg := _EBP;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
$9E:
begin
Length := 7;
Op := ASM_FSTP;
Arg1.Reg := _ESI;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end;
else
RaiseError(errInternalError, []);
end;
end;
$F7:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$E0..$E3: // mul reg
begin
Op := ASM_MUL;
Length := 3;
case B of
$E0: Arg1.Reg := _EAX;
$E1: Arg1.Reg := _ECX;
$E2: Arg1.Reg := _EDX;
$E3: Arg1.Reg := _EBX;
end;
Arg2.valid := false;
end;
$E8..$EB: // imul reg
begin
Op := ASM_IMUL;
Length := 3;
case B of
$E8: Arg1.Reg := _EAX;
$E9: Arg1.Reg := _ECX;
$EA: Arg1.Reg := _EDX;
$EB: Arg1.Reg := _EBX;
end;
Arg2.valid := false;
end;
$F0..$F3: // div reg
begin
Op := ASM_DIV;
Length := 3;
case B of
$F0: Arg1.Reg := _EAX;
$F1: Arg1.Reg := _ECX;
$F2: Arg1.Reg := _EDX;
$F3: Arg1.Reg := _EBX;
end;
Arg2.valid := false;
end;
$F8..$FB: // idiv reg
begin
Op := ASM_IDIV;
Length := 3;
case B of
$F8: Arg1.Reg := _EAX;
$F9: Arg1.Reg := _ECX;
$FA: Arg1.Reg := _EDX;
$FB: Arg1.Reg := _EBX;
end;
Arg2.valid := false;
end;
$D0..$D3: // not reg
begin
Op := ASM_NOT;
Length := 3;
case B of
$D0: Arg1.Reg := _EAX;
$D1: Arg1.Reg := _ECX;
$D2: Arg1.Reg := _EDX;
$D3: Arg1.Reg := _EBX;
end;
Arg2.valid := false;
end;
$D8..$DB: // neg reg
begin
Op := ASM_NEG;
Length := 3;
case B of
$D8: Arg1.Reg := _EAX;
$D9: Arg1.Reg := _ECX;
$DA: Arg1.Reg := _EDX;
$DB: Arg1.Reg := _EBX;
end;
Arg2.valid := false;
end;
$98..$9E: // neg dword ptr [reg]
begin
Op := ASM_NEG;
Length := 7;
case B of
$98: Arg1.Reg := _EAX;
$99: Arg1.Reg := _ECX;
$9A: Arg1.Reg := _EDX;
$9B: Arg1.Reg := _EBX;
$9C: Arg1.Reg := _ESP;
$9D: Arg1.Reg := _EBP;
$9E: Arg1.Reg := _ESI;
end;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
Arg1.Ptr := true;
Arg2.valid := false;
end;
else
RaiseError(errInternalError, []);
end;
end;
$FF:
begin
Op := ASM_CALL;
Length := 3;
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$D0: Arg1.Reg := _EAX;
$D1: Arg1.Reg := _ECX;
$D2: Arg1.Reg := _EDX;
$D3: Arg1.Reg := _EBX;
$D4: Arg1.Reg := _ESP;
$D5: Arg1.Reg := _EBP;
$D6: Arg1.Reg := _ESI;
$D7: Arg1.Reg := _EDI;
$E0: Arg1.Reg := _R8;
$E1: Arg1.Reg := _R9;
else
RaiseError(errInternalError, []);
end;
Arg2.valid := false;
end;
end;
end; //$48
$4C:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$89:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_MOV;
if AssignRegMovRBPPtr(B, Arg2) then
begin
Op := ASM_MOV;
Length := 7;
Arg1.Reg := _EBP;
Arg1.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end
else if AssignRegMovRSIPtr(B, Arg2) then
begin
Op := ASM_MOV;
Length := 7;
Arg1.Reg := _ESI;
Arg1.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end
else if B in [$84, $8C, $94, $9C, $A4, $AC, $B4, $BC] then
begin
case B of
$84: Arg2.Reg := _R8;
$8C: Arg2.Reg := _R9;
$94: Arg2.Reg := _R10;
$9C: Arg2.Reg := _R11;
$A4: Arg2.Reg := _R12;
$AC: Arg2.Reg := _R13;
$B4: Arg2.Reg := _R14;
$BC: Arg2.Reg := _R15;
end;
P := ShiftPointer(P, 1);
B := Byte(P^);
if B <> $24 then
RaiseError(errInternalError, []);
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
Length := 8;
Arg1.Ptr := true;
Arg1.Reg := _ESP;
end
else
begin
Length := 3;
if not AssignMovR32_R64(B, Arg1, Arg2) then
begin
Arg1.Ptr := true;
if not AssignR64_R32(B, Arg2, Arg1) then
RaiseError(errInternalError, []);
end;
end;
end;
$8B:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
if AssignRegMovRBPPtr(B, Arg1) then
begin
Op := ASM_MOV;
Length := 7;
Arg2.Reg := _EBP;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
end
else if AssignRegMovRSIPtr(B, Arg1) then
begin
Op := ASM_MOV;
Length := 7;
Arg2.Reg := _ESI;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
end
else if B in [$84, $8C, $94, $9C, $A4, $AC, $B4, $BC] then
begin
Op := ASM_MOV;
case B of
$84: Arg1.Reg := _R8;
$8C: Arg1.Reg := _R9;
$94: Arg1.Reg := _R10;
$9C: Arg1.Reg := _R11;
$A4: Arg1.Reg := _R12;
$AC: Arg1.Reg := _R13;
$B4: Arg1.Reg := _R14;
$BC: Arg1.Reg := _R15;
end;
P := ShiftPointer(P, 1);
B := Byte(P^);
if B <> $24 then
RaiseError(errInternalError, []);
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
Length := 8;
Arg2.Ptr := true;
Arg2.Reg := _ESP;
end
else
begin
Op := ASM_MOV;
Length := 3;
Arg2.Ptr := true;
if not AssignR64_R32(B, Arg1, Arg2) then
RaiseError(errInternalError, []);
// case B of
// $00: begin Arg1.Reg := _R8; Arg2.Reg := _EAX; end;
end;
end;
else
RaiseError(errInternalError, []);
end;
end;
$67:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$41:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$89:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_MOV;
Length := 4;
Arg1.sz := 4;
Arg2.sz := 4;
if AssignR32_R64(B, Arg2, Arg1) then
Arg1.Ptr := true
else
RaiseError(errInternalError, []);
end;
$8B:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_MOV;
Length := 4;
Arg1.sz := 4;
Arg2.sz := 4;
if AssignR32_R64(B, Arg1, Arg2) then
Arg2.Ptr := true
else
RaiseError(errInternalError, []);
// case B of
// $00: begin Arg1.Reg := _EAX; Arg2.Reg := _R8; end;
end;
end;
end;
$48:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$89:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_MOV;
Length := 8;
if not AssignRegMovESIPtr(B, Arg2) then
RaiseError(errInternalError, []);
Arg1.Reg := _ESI;
Arg1.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
end;
$8B:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_MOV;
Length := 8;
if not AssignRegMovESIPtr(B, Arg1) then
RaiseError(errInternalError, []);
Arg2.Reg := _ESI;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
end;
else
RaiseError(errInternalError, []);
end;
end;
$4C:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$89:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_MOV;
Length := 8;
if not AssignRegMovRSIPtr(B, Arg2) then
RaiseError(errInternalError, []);
Arg1.Reg := _ESI;
Arg1.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
end;
$8B:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_MOV;
Length := 8;
if not AssignRegMovRSIPtr(B, Arg1) then
RaiseError(errInternalError, []);
Arg2.Reg := _ESI;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
end;
else
RaiseError(errInternalError, []);
end;
end;
$F2:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
if B <> $48 then
RaiseError(errInternalError, []);
P := ShiftPointer(P, 1);
B := Byte(P^);
if B <> $0F then
RaiseError(errInternalError, []);
P := ShiftPointer(P, 1);
B := Byte(P^);
if B = $10 then
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_MOVSD;
Length := 6;
Arg2.Ptr := true;
if not AssignXMM_RegPtr(B, Arg1, Arg2) then
RaiseError(errInternalError, []);
end
else if B = $11 then
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_MOVSD;
Length := 6;
Arg1.Ptr := true;
if not AssignXMM_RegPtr(B, Arg2, Arg1) then
RaiseError(errInternalError, []);
end
else
RaiseError(errInternalError, []);
// movsd
end; // $F2
$F3:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
if B <> $0F then
RaiseError(errInternalError, []);
P := ShiftPointer(P, 1);
B := Byte(P^);
if B = $10 then
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_MOVSS;
Length := 5;
Arg2.Ptr := true;
Arg2.sz := 4;
if not AssignXMM_RegPtr(B, Arg1, Arg2) then
RaiseError(errInternalError, []);
end
else if B = $11 then
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_MOVSS;
Length := 5;
Arg1.Ptr := true;
Arg1.sz := 4;
if not AssignXMM_RegPtr(B, Arg2, Arg1) then
RaiseError(errInternalError, []);
end
else
RaiseError(errInternalError, []);
// movss
end; // $f3
$66:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$50..$53: // PUSH REG16
begin
Op := ASM_PUSH;
Length := 3;
Arg1.sz := 2;
case B of
$50: Arg1.Reg := _EAX;
$51: Arg1.Reg := _ECX;
$52: Arg1.Reg := _EDX;
$53: Arg1.Reg := _EBX;
end;
Arg2.valid := false;
end;
$C7: // MOV WORD PTR [REG], Imm
begin
Op := ASM_MOV;
Length := 10;
Arg1.Ptr := true;
Arg1.sz := 2;
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$80: Arg1.Reg := _EAX;
$81: Arg1.Reg := _ECX;
$82: Arg1.Reg := _EDX;
$83: Arg1.Reg := _EBX;
$84: Arg1.Reg := _ESP;
$85: Arg1.Reg := _EBP;
$86: Arg1.Reg := _ESI;
else
RaiseError(errInternalError, []);
end;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
P := ShiftPointer(P, 4);
Move(P^, Arg2.val, 2);
end;
$81:
begin
Length := 10;
Arg1.Ptr := true;
Arg1.sz := 2;
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$80..$86: // ADD WORD PTR [REG], Imm
begin
Op := ASM_ADD;
case B of
$80: Arg1.Reg := _EAX;
$81: Arg1.Reg := _ECX;
$82: Arg1.Reg := _EDX;
$83: Arg1.Reg := _EBX;
$84: Arg1.Reg := _ESP;
$85: Arg1.Reg := _EBP;
$86: Arg1.Reg := _ESI;
end;
end;
$B8..$BE: // WORD PTR [REG], Imm
begin
Op := ASM_CMP;
case B of
$B8: Arg1.Reg := _EAX;
$B9: Arg1.Reg := _ECX;
$BA: Arg1.Reg := _EDX;
$BB: Arg1.Reg := _EBX;
$BC: Arg1.Reg := _ESP;
$BD: Arg1.Reg := _EBP;
$BE: Arg1.Reg := _ESI;
end;
end;
else
RaiseError(errInternalError, []);
end;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
P := ShiftPointer(P, 4);
Move(P^, Arg2.val, 2);
end;
$8B: // MOV Reg16, WORD PTR [REG]
begin
Op := ASM_MOV;
Length := 4;
Arg1.sz := 2;
Arg2.sz := 2;
P := ShiftPointer(P, 1);
B := Byte(P^);
if AssignRegMovESIPtr(B, Arg1) then
// MOV Reg16, WORD PTR [ESI + Shift]
begin
Length := 8;
Arg2.Reg := _ESI;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end
else if AssignRegMovEBPPtr(B, Arg1) then
// MOV Reg16, WORD PTR [EBP + Shift]
begin
Length := 8;
Arg2.Reg := _EBP;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 4);
end
// MOV Reg16, WORD PTR [REG]
else
begin
if AssignR32_R32(B, Arg1, Arg2) then
RaiseError(errInternalError, []);
// $00: begin Arg1.Reg := _EAX; Arg2.Reg := _EAX; end;
// $01: begin Arg1.Reg := _EAX; Arg2.Reg := _ECX; end;
end;
Arg2.Ptr := true;
end;
$89: // MOVE WORD PTR [Reg], Reg16
begin
Op := ASM_MOV;
Arg1.Ptr := true;
Arg1.sz := 2;
Arg2.sz := 2;
Length := 4;
P := ShiftPointer(P, 1);
B := Byte(P^);
if AssignRegMovESIPtr(B, Arg2) then
// MOV WORD PTR [ESI + Shift], Reg16
begin
Length := 7;
Arg1.Reg := _ESI;
P := ShiftPointer(P, 1);
Move(P^, Arg1.Val, 4);
end
else if AssignRegMovEBPPtr(B, Arg2) then
// MOV WORD PTR [EBP + Shift], Reg16
begin
Length := 7;
Arg1.Reg := _EBP;
P := ShiftPointer(P, 1);
Move(P^, Arg1.Val, 4);
end
else
case B of
$00: begin Arg1.Reg := _EAX; Arg2.Reg := _EAX; end;
$08: begin Arg1.Reg := _EAX; Arg2.Reg := _ECX; end;
$10: begin Arg1.Reg := _EAX; Arg2.Reg := _EDX; end;
$18: begin Arg1.Reg := _EAX; Arg2.Reg := _EBX; end;
$01: begin Arg1.Reg := _ECX; Arg2.Reg := _EAX; end;
$09: begin Arg1.Reg := _ECX; Arg2.Reg := _ECX; end;
$11: begin Arg1.Reg := _ECX; Arg2.Reg := _EDX; end;
$19: begin Arg1.Reg := _ECX; Arg2.Reg := _EBX; end;
$02: begin Arg1.Reg := _EDX; Arg2.Reg := _EAX; end;
$0A: begin Arg1.Reg := _EDX; Arg2.Reg := _ECX; end;
$12: begin Arg1.Reg := _EDX; Arg2.Reg := _EDX; end;
$1A: begin Arg1.Reg := _EDX; Arg2.Reg := _EBX; end;
$03: begin Arg1.Reg := _EBX; Arg2.Reg := _EAX; end;
$0B: begin Arg1.Reg := _EBX; Arg2.Reg := _ECX; end;
$13: begin Arg1.Reg := _EBX; Arg2.Reg := _EDX; end;
$1B: begin Arg1.Reg := _EBX; Arg2.Reg := _EBX; end;
else
RaiseError(errInternalError, []);
end;
end;
end;
end;
$89:
begin
Op := ASM_MOV;
P := ShiftPointer(P, 1);
B := Byte(P^);
if AssignRegMovESIPtr(B, Arg2) then
begin
Length := 7;
Arg1.Ptr := true;
Arg1.Reg := _ESI;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end
else if AssignRegMovEBPPtr(B, Arg2) then
begin
Length := 7;
Arg1.Ptr := true;
Arg1.Reg := _EBP;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
end
else
begin
Length := 3;
Arg1.sz := 4;
Arg2.sz := 4;
case B of
$C0: begin Arg1.Reg := _EAX; Arg2.Reg := _EAX; end;
$C8: begin Arg1.Reg := _EAX; Arg2.Reg := _ECX; end;
$D0: begin Arg1.Reg := _EAX; Arg2.Reg := _EDX; end;
$D8: begin Arg1.Reg := _EAX; Arg2.Reg := _EBX; end;
$E0: begin Arg1.Reg := _EAX; Arg2.Reg := _ESP; end;
$E8: begin Arg1.Reg := _EAX; Arg2.Reg := _EBP; end;
$F0: begin Arg1.Reg := _EAX; Arg2.Reg := _ESI; end;
$F8: begin Arg1.Reg := _EAX; Arg2.Reg := _EDI; end;
$C1: begin Arg1.Reg := _ECX; Arg2.Reg := _EAX; end;
$C9: begin Arg1.Reg := _ECX; Arg2.Reg := _ECX; end;
$D1: begin Arg1.Reg := _ECX; Arg2.Reg := _EDX; end;
$D9: begin Arg1.Reg := _ECX; Arg2.Reg := _EBX; end;
$E1: begin Arg1.Reg := _ECX; Arg2.Reg := _ESP; end;
$E9: begin Arg1.Reg := _ECX; Arg2.Reg := _EBP; end;
$F1: begin Arg1.Reg := _ECX; Arg2.Reg := _ESI; end;
$F9: begin Arg1.Reg := _ECX; Arg2.Reg := _EDI; end;
$C2: begin Arg1.Reg := _EDX; Arg2.Reg := _EAX; end;
$CA: begin Arg1.Reg := _EDX; Arg2.Reg := _ECX; end;
$D2: begin Arg1.Reg := _EDX; Arg2.Reg := _EDX; end;
$DA: begin Arg1.Reg := _EDX; Arg2.Reg := _EBX; end;
$E2: begin Arg1.Reg := _EDX; Arg2.Reg := _ESP; end;
$EA: begin Arg1.Reg := _EDX; Arg2.Reg := _EBP; end;
$F2: begin Arg1.Reg := _EDX; Arg2.Reg := _ESI; end;
$FA: begin Arg1.Reg := _EDX; Arg2.Reg := _EDI; end;
$C3: begin Arg1.Reg := _EBX; Arg2.Reg := _EAX; end;
$CB: begin Arg1.Reg := _EBX; Arg2.Reg := _ECX; end;
$D3: begin Arg1.Reg := _EBX; Arg2.Reg := _EDX; end;
$DB: begin Arg1.Reg := _EBX; Arg2.Reg := _EBX; end;
$E3: begin Arg1.Reg := _EBX; Arg2.Reg := _ESP; end;
$EB: begin Arg1.Reg := _EBX; Arg2.Reg := _EBP; end;
$F3: begin Arg1.Reg := _EBX; Arg2.Reg := _ESI; end;
$FB: begin Arg1.Reg := _EBX; Arg2.Reg := _EDI; end;
$E5: begin Arg1.Reg := _EBP; Arg2.Reg := _ESP; end;
$EC: begin Arg1.Reg := _ESP; Arg2.Reg := _EBP; end;
$C6: begin Arg1.Reg := _ESI; Arg2.Reg := _EAX; end;
$CE: begin Arg1.Reg := _ESI; Arg2.Reg := _ECX; end;
$D6: begin Arg1.Reg := _ESI; Arg2.Reg := _EDX; end;
$DE: begin Arg1.Reg := _ESI; Arg2.Reg := _EBX; end;
$E6: begin Arg1.Reg := _ESI; Arg2.Reg := _ESP; end;
$EE: begin Arg1.Reg := _ESI; Arg2.Reg := _EBP; end;
$F6: begin Arg1.Reg := _ESI; Arg2.Reg := _ESI; end;
$FE: begin Arg1.Reg := _ESI; Arg2.Reg := _EDI; end;
$C7: begin Arg1.Reg := _EDI; Arg2.Reg := _EAX; end;
$CF: begin Arg1.Reg := _EDI; Arg2.Reg := _ECX; end;
$D7: begin Arg1.Reg := _EDI; Arg2.Reg := _EDX; end;
$DF: begin Arg1.Reg := _EDI; Arg2.Reg := _EBX; end;
$E7: begin Arg1.Reg := _EDI; Arg2.Reg := _ESP; end;
$EF: begin Arg1.Reg := _EDI; Arg2.Reg := _EBP; end;
$F7: begin Arg1.Reg := _EDI; Arg2.Reg := _ESI; end;
$FF: begin Arg1.Reg := _EDI; Arg2.Reg := _EDI; end;
$00: begin Arg1.Ptr := true; Arg1.Reg := _EAX; Arg2.Reg := _EAX; end;
$08: begin Arg1.Ptr := true; Arg1.Reg := _EAX; Arg2.Reg := _ECX; end;
$10: begin Arg1.Ptr := true; Arg1.Reg := _EAX; Arg2.Reg := _EDX; end;
$18: begin Arg1.Ptr := true; Arg1.Reg := _EAX; Arg2.Reg := _EBX; end;
$01: begin Arg1.Ptr := true; Arg1.Reg := _ECX; Arg2.Reg := _EAX; end;
$09: begin Arg1.Ptr := true; Arg1.Reg := _ECX; Arg2.Reg := _ECX; end;
$11: begin Arg1.Ptr := true; Arg1.Reg := _ECX; Arg2.Reg := _EDX; end;
$19: begin Arg1.Ptr := true; Arg1.Reg := _ECX; Arg2.Reg := _EBX; end;
$02: begin Arg1.Ptr := true; Arg1.Reg := _EDX; Arg2.Reg := _EAX; end;
$0A: begin Arg1.Ptr := true; Arg1.Reg := _EDX; Arg2.Reg := _ECX; end;
$12: begin Arg1.Ptr := true; Arg1.Reg := _EDX; Arg2.Reg := _EDX; end;
$1A: begin Arg1.Ptr := true; Arg1.Reg := _EDX; Arg2.Reg := _EBX; end;
$03: begin Arg1.Ptr := true; Arg1.Reg := _EBX; Arg2.Reg := _EAX; end;
$0B: begin Arg1.Ptr := true; Arg1.Reg := _EBX; Arg2.Reg := _ECX; end;
$13: begin Arg1.Ptr := true; Arg1.Reg := _EBX; Arg2.Reg := _EDX; end;
$1B: begin Arg1.Ptr := true; Arg1.Reg := _EBX; Arg2.Reg := _EBX; end;
else
RaiseError(errInternalError, []);
end;
end;
end;
end;
end;
$49:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$FF:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Length := 3;
Arg2.valid := false;
Op := ASM_JMP;
case B of
$E0: Arg1.Reg := _R8;
$E1: Arg1.Reg := _R9;
$E2: Arg1.Reg := _R10;
$E3: Arg1.Reg := _R11;
$E4: Arg1.Reg := _R12;
$E5: Arg1.Reg := _R13;
$E6: Arg1.Reg := _R14;
$E7: Arg1.Reg := _R15;
else
RaiseError(errInternalError, []);
end;
end;
$81:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
if B in [$C0..$C7] then // ADD Reg, Imm
begin
Op := ASM_ADD;
Length := 7;
case B of
$C0: Arg1.Reg := _R8;
$C1: Arg1.Reg := _R9;
$C2: Arg1.Reg := _R10;
$C3: Arg1.Reg := _R11;
$C4: Arg1.Reg := _R12;
$C5: Arg1.Reg := _R13;
$C6: Arg1.Reg := _R14;
$C7: Arg1.Reg := _R15;
end;
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
end
else
RaiseError(errInternalError, []);
end;
$8B:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$FF: begin end;
else
begin
Length := 3;
Arg2.Ptr := true;
if not AssignR32_R64(B, Arg1, Arg2) then
RaiseError(errInternalError, []);
// case B of
// $00: begin Arg1.Reg := _EAX; Arg2.Reg := _R8; end;
end;
end;
end;
$C7:
begin
Arg1.sz := 8;
Arg1.Ptr := true;
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$00..$07: // MOV DWORD PTR [REG], imm
begin
Op := ASM_MOV;
case B of
$00: Arg1.Reg := _R8;
$01: Arg1.Reg := _R9;
$02: Arg1.Reg := _R10;
$03: Arg1.Reg := _R11;
$04: Arg1.Reg := _R12;
$05: Arg1.Reg := _R13;
$06: Arg1.Reg := _R14;
$07: Arg1.Reg := _R15;
else
RaiseError(errInternalError, []);
end;
Length := 7;
P := ShiftPointer(P, 1);
Move(P^, Arg2.val, 4);
end;
$80..$87: // MOV DWORD PTR [REG + Shift], imm
begin
Op := ASM_MOV;
Length := 11;
case B of
$80: Arg1.Reg := _R8;
$81: Arg1.Reg := _R9;
$82: Arg1.Reg := _R10;
$83: Arg1.Reg := _R11;
$84: Arg1.Reg := _R12;
$85: Arg1.Reg := _R13;
$86: Arg1.Reg := _R14;
$87: Arg1.Reg := _R15;
end;
P := ShiftPointer(P, 1);
Move(P^, Arg1.val, 4);
P := ShiftPointer(P, 4);
Move(P^, Arg2.val, 4);
end;
else
RaiseError(errInternalError, []);
end;
end;
$B8..$BF:
begin
Op := ASM_MOV;
Length := 10;
case B of
$B8: Arg1.Reg := _R8;
$B9: Arg1.Reg := _R9;
$BA: Arg1.Reg := _R10;
$BB: Arg1.Reg := _R11;
$BC: Arg1.Reg := _R12;
$BD: Arg1.Reg := _R13;
$BE: Arg1.Reg := _R14;
$BF: Arg1.Reg := _R15;
else
RaiseError(errInternalError, []);
end;
P := ShiftPointer(P, 1);
Move(P^, Arg2.Val, 8);
end;
$89:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_MOV;
Length := 3;
if not AssignMovR64_R32(B, Arg1, Arg2) then
begin
Arg1.Ptr := true;
if not AssignR32_R64(B, Arg2, Arg1) then
RaiseError(errInternalError, []);
end;
end
else
RaiseError(errInternalError, []);
end;
end; //$49
$4D:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
case B of
$8B:
begin
Op := ASM_MOV;
Length := 3;
Arg2.Ptr := true;
P := ShiftPointer(P, 1);
B := Byte(P^);
if not AssignR64_R64(B, Arg1, Arg2) then
RaiseError(errInternalError, []);
// case B of
// $00: begin Arg1.Reg := _R8; Arg2.Reg := _R8; end;
end;
$89:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_MOV;
Length := 3;
if not AssignMovR64_R64(B, Arg1, Arg2) then
begin
Arg1.Ptr := true;
if not AssignR64_R64(B, Arg2, Arg1) then
RaiseError(errInternalError, []);
end;
end
else
RaiseError(errInternalError, []);
end;
end; // $4D
$F2:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
if B <> $0F then
RaiseError(errInternalError, []);
P := ShiftPointer(P, 1);
B := Byte(P^);
if B <> $5A then
RaiseError(errInternalError, []);
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_CVTSD2SS;
Length := 4;
Arg2.Ptr := true;
Arg2.sz := 4;
if not AssignXMM_RegPtr(B, Arg1, Arg2) then
RaiseError(errInternalError, []);
end;
$F3:
begin
P := ShiftPointer(P, 1);
B := Byte(P^);
if B <> $0F then
RaiseError(errInternalError, []);
P := ShiftPointer(P, 1);
B := Byte(P^);
if B <> $5A then
RaiseError(errInternalError, []);
P := ShiftPointer(P, 1);
B := Byte(P^);
Op := ASM_CVTSS2SD;
Length := 4;
Arg2.Ptr := true;
Arg2.sz := 4;
if not AssignXMM_RegPtr(B, Arg1, Arg2) then
RaiseError(errInternalError, []);
end
else
RaiseError(errInternalError, []);
end; //$48
end;
end; // case
end;
end.
|
unit Card.Drawer;
interface
uses
W3C.Canvas2DContext;
type
TCustomCardColorDrawer = class abstract
protected
class function GetWidth: Float; virtual; abstract;
class function GetHeight: Float; virtual; abstract;
class function GetColor: String; virtual; abstract;
class procedure DrawRaw(Context: JCanvasRenderingContext2D); virtual; abstract;
public
class procedure Draw(Context: JCanvasRenderingContext2D; ScaleFactor: Float = 1; Flip: Boolean = False);
property Color: String read GetColor;
property Width: Float read GetWidth;
property Height: Float read GetHeight;
end;
TCustomCardColorDrawerClass = class of TCustomCardColorDrawer;
TCardColorDrawerRed = class(TCustomCardColorDrawer)
protected
class function GetColor: String; override;
end;
TCardColorDrawerBlack = class(TCustomCardColorDrawer)
protected
class function GetColor: String; override;
end;
TCardColorDrawerSpade = class(TCardColorDrawerBlack)
protected
class function GetWidth: Float; override;
class function GetHeight: Float; override;
public
class procedure DrawRaw(Context: JCanvasRenderingContext2D); override;
end;
TCardColorDrawerHeart = class(TCardColorDrawerRed)
protected
class function GetWidth: Float; override;
class function GetHeight: Float; override;
public
class procedure DrawRaw(Context: JCanvasRenderingContext2D); override;
end;
TCardColorDrawerClub = class(TCardColorDrawerBlack)
protected
class function GetWidth: Float; override;
class function GetHeight: Float; override;
public
class procedure DrawRaw(Context: JCanvasRenderingContext2D); override;
end;
TCardColorDrawerDiamond = class(TCardColorDrawerRed)
protected
class function GetWidth: Float; override;
class function GetHeight: Float; override;
public
class procedure DrawRaw(Context: JCanvasRenderingContext2D); override;
end;
TCustomCardValueDrawer = class
protected
class function GetWidth: Float; virtual;
class function GetHeight: Float; virtual;
class procedure DrawRaw(Context: JCanvasRenderingContext2D); virtual; abstract;
public
class procedure Draw(Context: JCanvasRenderingContext2D;
ScaleFactor: Float = 1; Center: Boolean = False);
property Width: Float read GetWidth;
property Height: Float read GetHeight;
end;
TCustomCardValueDrawerClass = class of TCustomCardValueDrawer;
TCardValueDrawerA = class(TCustomCardValueDrawer)
protected
class procedure DrawRaw(Context: JCanvasRenderingContext2D); override;
end;
TCardValueDrawer2 = class(TCustomCardValueDrawer)
protected
class procedure DrawRaw(Context: JCanvasRenderingContext2D); override;
end;
TCardValueDrawer3 = class(TCustomCardValueDrawer)
protected
class procedure DrawRaw(Context: JCanvasRenderingContext2D); override;
end;
TCardValueDrawer4 = class(TCustomCardValueDrawer)
protected
class procedure DrawRaw(Context: JCanvasRenderingContext2D); override;
end;
TCardValueDrawer5 = class(TCustomCardValueDrawer)
protected
class procedure DrawRaw(Context: JCanvasRenderingContext2D); override;
end;
TCardValueDrawer6 = class(TCustomCardValueDrawer)
protected
class procedure DrawRaw(Context: JCanvasRenderingContext2D); override;
end;
TCardValueDrawer7 = class(TCustomCardValueDrawer)
protected
class procedure DrawRaw(Context: JCanvasRenderingContext2D); override;
end;
TCardValueDrawer8 = class(TCustomCardValueDrawer)
protected
class procedure DrawRaw(Context: JCanvasRenderingContext2D); override;
end;
TCardValueDrawer9 = class(TCustomCardValueDrawer)
protected
class procedure DrawRaw(Context: JCanvasRenderingContext2D); override;
end;
TCardValueDrawer10 = class(TCustomCardValueDrawer)
protected
class procedure DrawRaw(Context: JCanvasRenderingContext2D); override;
end;
TCardValueDrawerJ = class(TCustomCardValueDrawer)
protected
class procedure DrawRaw(Context: JCanvasRenderingContext2D); override;
end;
TCardValueDrawerQ = class(TCustomCardValueDrawer)
protected
class function GetWidth: Float; override;
class function GetHeight: Float; override;
class procedure DrawRaw(Context: JCanvasRenderingContext2D); override;
end;
TCardValueDrawerK = class(TCustomCardValueDrawer)
protected
class function GetWidth: Float; override;
class function GetHeight: Float; override;
class procedure DrawRaw(Context: JCanvasRenderingContext2D); override;
end;
TCardDrawerOrnament = class
protected
class function GetWidth: Float;
class function GetHeight: Float;
class procedure DrawRaw(Context: JCanvasRenderingContext2D);
public
class procedure Draw(Context: JCanvasRenderingContext2D; ScaleFactor: Float = 1; Flip: Boolean = False);
property Width: Float read GetWidth;
property Height: Float read GetHeight;
end;
implementation
uses
WHATWG.Console;
procedure BezierCurveToContext(Context: JCanvasRenderingContext2D; Points: array of Float);
begin
{$IFDEF DEBUG}
Assert((Length(Points) - 2) mod 6 = 0);
{$ENDIF}
Context.MoveTo(Points[0], Points[1]);
for var Index := 0 to (Length(Points) - 2) div 6 - 1 do
Context.bezierCurveTo(Points[6 * Index + 2], Points[6 * Index + 3],
Points[6 * Index + 4], Points[6 * Index + 5],
Points[6 * Index + 6], Points[6 * Index + 7]);
end;
procedure PolygonToContext(Context: JCanvasRenderingContext2D; Points: array of Float);
begin
{$IFDEF DEBUG}
Assert(Length(Points) mod 2 = 0);
{$ENDIF}
Context.MoveTo(Points[0], Points[1]);
for var Index := 1 to (Length(Points) div 2) - 1 do
Context.LineTo(Points[2 * Index], Points[2 * Index + 1]);
end;
{ TCustomCardColorDrawer }
class procedure TCustomCardColorDrawer.Draw(Context: JCanvasRenderingContext2D;
ScaleFactor: Float = 1; Flip: Boolean = False);
begin
Context.Scale(ScaleFactor, ScaleFactor);
if Flip then Context.rotate(Pi);
Context.Translate(-0.5 * GetWidth, -0.5 * GetHeight);
DrawRaw(Context);
Context.closePath;
Context.Translate(0.5 * GetWidth, 0.5 * GetHeight);
if Flip then Context.rotate(Pi);
Context.Scale(1 / ScaleFactor, 1 / ScaleFactor);
end;
{ TCardColorDrawerRed }
class function TCardColorDrawerRed.GetColor: String;
begin
Result := '#C00';
end;
{ TCardColorDrawerBlack }
class function TCardColorDrawerBlack.GetColor: String;
begin
Result := '#000';
end;
{ TCardColorDrawerSpade }
class procedure TCardColorDrawerSpade.DrawRaw(Context: JCanvasRenderingContext2D);
begin
BezierCurveToContext(Context, [5.28, 0, 2.75, 3.61, 0, 5.9, 0, 8.5, 0, 11.1,
3.73, 11.92, 4.64, 9.5, 4.71, 9.32, 4.31, 11.94, 3.62, 13.17]);
Context.lineTo(6.93, 13.17);
Context.bezierCurveTo(6.24, 11.94, 5.85, 9.32, 5.92, 9.5);
Context.bezierCurveTo(6.81, 11.91, 10.55, 11.46, 10.55, 8.5);
Context.bezierCurveTo(10.55, 5.55, 7.8, 3.61, 5.28, 0);
end;
class function TCardColorDrawerSpade.GetWidth: Float;
begin
Result := 10.55;
end;
class function TCardColorDrawerSpade.GetHeight: Float;
begin
Result := 13.17;
end;
{ TCardColorDrawerHeart }
class procedure TCardColorDrawerHeart.DrawRaw(Context: JCanvasRenderingContext2D);
begin
BezierCurveToContext(Context, [6.2, 12.64, 4.09, 9.31, 0, 5.76, 0, 3.61, 0,
1.47, 1.35, 0, 3.03, 0, 4.72, 0, 5.92, 1.88, 6.2, 3.07, 6.48, 1.88, 7.68,
0, 9.36, 0, 11.05, 0, 12.43, 1.45, 12.4, 3.61, 12.36, 5.78, 8.39, 9.22,
6.2, 12.64]);
end;
class function TCardColorDrawerHeart.GetWidth: Float;
begin
Result := 12.36;
end;
class function TCardColorDrawerHeart.GetHeight: Float;
begin
Result := 12.64;
end;
{ TCardColorDrawerClub }
class procedure TCardColorDrawerClub.DrawRaw(Context: JCanvasRenderingContext2D);
begin
BezierCurveToContext(Context, [6.1, 0, 9.07, 0, 10.02, 2.84, 7.49, 5.67,
10.86, 4.15, 12.85, 6.42, 12.03, 9.02, 11.21, 11.63, 7.53, 11, 6.63,
9.1, 6.3, 10.45, 7.18, 12.04, 7.7, 13.16]);
Context.lineTo(4.51, 13.16);
Context.bezierCurveTo(5.03, 12.04, 5.92, 10.45, 5.58, 9.1);
Context.bezierCurveTo(4.69, 11, 1, 11.63, 0.18, 9.02);
Context.bezierCurveTo(-0.64, 6.42, 1.35, 4.15, 4.72, 5.67);
Context.bezierCurveTo(2.19, 2.84, 3.14, 0.01, 6.11, 0);
end;
class function TCardColorDrawerClub.GetWidth: Float;
begin
Result := 12.85;
end;
class function TCardColorDrawerClub.GetHeight: Float;
begin
Result := 13.16;
end;
{ TCardColorDrawerDiamond }
class procedure TCardColorDrawerDiamond.DrawRaw(Context: JCanvasRenderingContext2D);
begin
BezierCurveToContext(Context, [5.3, 13.17, 3.88, 10.82, 1.87, 8.53, 0, 6.58,
1.87, 4.63, 3.88, 2.35, 5.3, 0, 6.72, 2.35, 8.73, 4.63, 10.6, 6.58, 8.73,
8.53, 6.72, 10.82, 5.3, 13.17]);
end;
class function TCardColorDrawerDiamond.GetWidth: Float;
begin
Result := 10.6;
end;
class function TCardColorDrawerDiamond.GetHeight: Float;
begin
Result := 13.17;
end;
{ TCustomCardValueDrawer }
class procedure TCustomCardValueDrawer.Draw(Context: JCanvasRenderingContext2D;
ScaleFactor: Float = 1; Center: Boolean = False);
begin
Context.Scale(ScaleFactor, ScaleFactor);
if Center then Context.translate(-0.5 * Width, -0.5 * Height);
Context.BeginPath;
DrawRaw(Context);
Context.ClosePath;
Context.Fill;
if Center then Context.translate(0.5 * Width, 0.5 * Height);
Context.Scale(1 / ScaleFactor, 1 / ScaleFactor);
end;
class function TCustomCardValueDrawer.GetWidth: Float;
begin
Result := 4;
end;
class function TCustomCardValueDrawer.GetHeight: Float;
begin
Result := 6;
end;
{ TCardValueDrawerA }
class procedure TCardValueDrawerA.DrawRaw(Context: JCanvasRenderingContext2D);
begin
PolygonToContext(Context, [3.87, 6.03, 2.29, 6.03, 2.29, 5.32, 2.63, 5.32,
2.52, 4.7, 1.35, 4.7, 1.23, 5.32, 1.57, 5.32, 1.57, 6.03, 0, 6.03, 0, 5.32,
0.51, 5.32, 1.49, 0.12, 2.37, 0.12, 3.35, 5.32, 3.87, 5.32]);
Context.moveTo(2.38, 4);
Context.lineTo(1.93, 1.58);
Context.lineTo(1.48, 4);
end;
{ TCardValueDrawer2 }
class procedure TCardValueDrawer2.DrawRaw(Context: JCanvasRenderingContext2D);
begin
BezierCurveToContext(Context, [0.01, 6, 0, 5.58, 0.02, 5.13, 0.09, 4.77, 0.15,
4.5, 0.22, 4.27, 0.3, 4.08, 0.42, 3.73, 0.63, 3.43, 0.83, 3.13, 1.06, 2.81,
1.25, 2.51, 1.45, 2.17, 1.56, 1.95, 1.58, 1.72, 1.59, 1.49, 1.59, 1.23,
1.54, 1.02, 1.44, 0.85, 1.34, 0.68, 1.21, 0.59, 1.05, 0.59, 0.94, 0.59,
0.86, 0.63, 0.8, 0.7, 0.67, 0.85, 0.64, 1.04, 0.6, 1.22, 0.58, 1.41, 0.6,
1.59, 0.62, 1.77]);
Context.lineTo(0.04, 1.89);
Context.bezierCurveTo(0, 1.73, 0, 1.59, 0, 1.43);
Context.bezierCurveTo(0, 1.17, 0.03, 0.95, 0.09, 0.77);
Context.bezierCurveTo(0.15, 0.59, 0.23, 0.44, 0.33, 0.32);
Context.bezierCurveTo(0.54, 0.1, 0.74, 0.02, 1.05, 0.01);
Context.bezierCurveTo(1.36, -0.01, 1.65, 0.14, 1.86, 0.42);
Context.bezierCurveTo(2.08, 0.71, 2.16, 1.13, 2.18, 1.49);
Context.bezierCurveTo(2.18, 1.66, 2.15, 1.82, 2.13, 1.97);
Context.bezierCurveTo(2.02, 2.53, 1.62, 3.02, 1.32, 3.46);
Context.bezierCurveTo(1.16, 3.69, 0.99, 3.96, 0.88, 4.19);
Context.bezierCurveTo(0.72, 4.59, 0.63, 5.01, 0.61, 5.4);
Context.lineTo(1.6, 5.4);
Context.lineTo(1.6, 4.63);
Context.lineTo(2.19, 4.63);
Context.lineTo(2.19, 6);
end;
{ TCardValueDrawer3 }
class procedure TCardValueDrawer3.DrawRaw(Context: JCanvasRenderingContext2D);
begin
BezierCurveToContext(Context, [2.29, 3.98, 2.29, 4.31, 2.26, 4.61, 2.19, 4.88,
2.12, 5.14, 2.03, 5.36, 1.92, 5.55, 1.71, 5.88, 1.42, 6.1, 1.1, 6.1, 0.57,
6.09, 0.31, 5.56, 0.13, 5.14, 0.08, 4.96, 0.03, 4.79, 0, 4.61]);
Context.lineTo(0.58, 4.5);
Context.bezierCurveTo(0.63, 4.93, 0.84, 5.51, 1.1, 5.52);
Context.bezierCurveTo(1.51, 5.53, 1.68, 4.52, 1.7, 3.98);
Context.bezierCurveTo(1.71, 3.63, 1.63, 3.31, 1.53, 3);
Context.bezierCurveTo(1.46, 2.79, 1.32, 2.63, 1.16, 2.64);
Context.bezierCurveTo(1.01, 2.65, 1.01, 2.72, 0.94, 2.84);
Context.lineTo(0.41, 2.58);
Context.lineTo(1.32, 0.69);
Context.lineTo(0.63, 0.69);
Context.lineTo(0.63, 1.47);
Context.lineTo(0.03, 1.47);
Context.lineTo(0.03, 0.11);
Context.lineTo(2.26, 0.11);
Context.lineTo(1.32, 2.06);
Context.bezierCurveTo(1.46, 2.09, 1.6, 2.15, 1.71, 2.26);
Context.bezierCurveTo(1.84, 2.36, 1.94, 2.5, 2.02, 2.66);
Context.bezierCurveTo(2.11, 2.82, 2.18, 3.02, 2.22, 3.25);
Context.bezierCurveTo(2.27, 3.47, 2.29, 3.71, 2.29, 3.98);
end;
{ TCardValueDrawer4 }
class procedure TCardValueDrawer4.DrawRaw(Context: JCanvasRenderingContext2D);
begin
PolygonToContext(Context, [2.25, 6.02, 0.98, 6.02, 0.98, 5.43, 1.38, 5.43,
1.38, 4.56, 0, 4.56, 1.42, 0.1, 1.97, 0.1, 1.97, 3.97, 2.24, 3.97,
2.24, 4.56, 1.97, 4.56, 1.97, 5.43, 2.25, 5.43]);
Context.moveTo(1.38, 3.97);
Context.lineTo(1.38, 2.18);
Context.lineTo(0.8, 3.97);
end;
{ TCardValueDrawer5 }
class procedure TCardValueDrawer5.DrawRaw(Context: JCanvasRenderingContext2D);
begin
BezierCurveToContext(Context, [2.25, 3.8, 2.25, 4.09, 2.22, 4.37, 2.17, 4.64,
2.12, 4.92, 2.05, 5.17, 1.95, 5.39, 1.85, 5.61, 1.73, 5.79, 1.58, 5.93,
1.43, 6.06, 1.27, 6.13, 1.08, 6.13, 0.83, 6.13, 0.61, 6.01, 0.42, 5.76,
0.23, 5.51, 0.09, 5.16, 0, 4.71]);
Context.lineTo(0.58, 4.59);
Context.bezierCurveTo(0.61, 4.76, 0.65, 4.91, 0.7, 5.03);
Context.bezierCurveTo(0.78, 5.28, 0.92, 5.55, 1.08, 5.55);
Context.bezierCurveTo(1.24, 5.54, 1.36, 5.24, 1.45, 5.07);
Context.bezierCurveTo(1.51, 4.92, 1.56, 4.74, 1.6, 4.53);
Context.bezierCurveTo(1.64, 4.31, 1.66, 4.07, 1.66, 3.8);
Context.bezierCurveTo(1.66, 3.54, 1.64, 3.3, 1.6, 3.09);
Context.bezierCurveTo(1.56, 2.88, 1.51, 2.7, 1.45, 2.55);
Context.bezierCurveTo(1.39, 2.4, 1.33, 2.29, 1.26, 2.22);
Context.bezierCurveTo(1.19, 2.14, 1.13, 2.1, 1.08, 2.1);
Context.bezierCurveTo(1.04, 2.1, 0.99, 2.13, 0.93, 2.19);
Context.bezierCurveTo(0.87, 2.25, 0.81, 2.34, 0.75, 2.48);
Context.lineTo(0.18, 2.36);
Context.lineTo(0.18, 0.11);
Context.lineTo(2.09, 0.11);
Context.lineTo(2.09, 0.69);
Context.lineTo(0.78, 0.69);
Context.lineTo(0.78, 1.58);
Context.bezierCurveTo(0.87, 1.53, 0.97, 1.51, 1.08, 1.51);
Context.bezierCurveTo(1.23, 1.51, 1.37, 1.56, 1.51, 1.66);
Context.bezierCurveTo(1.65, 1.76, 1.78, 1.9, 1.88, 2.1);
Context.bezierCurveTo(1.99, 2.29, 2.08, 2.53, 2.14, 2.82);
Context.bezierCurveTo(2.21, 3.1, 2.25, 3.43, 2.25, 3.8);
end;
{ TCardValueDrawer6 }
class procedure TCardValueDrawer6.DrawRaw(Context: JCanvasRenderingContext2D);
begin
BezierCurveToContext(Context, [2.14, 4.76, 2.09, 5.02, 2.02, 5.24, 1.93,
5.45, 1.83, 5.65, 1.71, 5.81, 1.57, 5.94, 1.44, 6.07, 1.28, 6.13, 1.1,
6.13, 0.61, 6.12, 0.35, 5.57, 0.23, 5.18, 0.17, 4.93, 0.12, 4.67, 0.08,
4.41, 0.04, 4.14, 0.02, 3.89, 0.01, 3.64, 0, 3.4, 0, 3.2, 0, 3.04, 0,
1.63, 0.16, 0.73, 0.47, 0.35, 0.67, 0.12, 0.88, 0, 1.11, 0, 1.32, 0,
1.52, 0.09, 1.69, 0.27, 1.86, 0.45, 1.99, 0.7, 2.09, 1.02]);
Context.lineTo(1.52, 1.18);
Context.bezierCurveTo(1.47, 0.87, 1.28, 0.6, 1.11, 0.59);
Context.bezierCurveTo(0.89, 0.59, 0.83, 0.93, 0.76, 1.11);
Context.bezierCurveTo(0.71, 1.31, 0.67, 1.57, 0.64, 1.91);
Context.bezierCurveTo(0.78, 1.78, 0.93, 1.71, 1.1, 1.71);
Context.bezierCurveTo(1.26, 1.71, 1.41, 1.77, 1.55, 1.88);
Context.bezierCurveTo(1.68, 1.99, 1.8, 2.15, 1.9, 2.35);
Context.bezierCurveTo(2, 2.55, 2.07, 2.78, 2.12, 3.06);
Context.bezierCurveTo(2.18, 3.34, 2.21, 3.65, 2.21, 3.94);
Context.bezierCurveTo(2.21, 4.24, 2.19, 4.5, 2.14, 4.76);
Context.moveTo(1.1, 2.3);
Context.bezierCurveTo(0.61, 2.28, 0.62, 3.16, 0.65, 4.08);
Context.bezierCurveTo(0.67, 5, 0.86, 5.54, 1.12, 5.55);
Context.bezierCurveTo(1.37, 5.55, 1.65, 4.88, 1.66, 4.07);
Context.bezierCurveTo(1.67, 3.27, 1.59, 2.32, 1.1, 2.3);
end;
{ TCardValueDrawer7 }
class procedure TCardValueDrawer7.DrawRaw(Context: JCanvasRenderingContext2D);
begin
BezierCurveToContext(Context, [2.41, 0.11, 2.14, 0.73, 1.94, 1.45, 1.8, 2, 1.68,
2.47, 1.56, 3.06, 1.44, 3.75, 1.32, 4.44, 1.22, 5.22, 1.14, 6.1]);
Context.lineTo(0.56, 6.04);
Context.bezierCurveTo(0.61, 5.36, 0.69, 4.73, 0.78, 4.16);
Context.bezierCurveTo(0.86, 3.59, 0.96, 3.08, 1.05, 2.63);
Context.bezierCurveTo(1.15, 2.18, 1.24, 1.79, 1.33, 1.47);
Context.bezierCurveTo(1.42, 1.14, 1.49, 0.88, 1.56, 0.69);
Context.lineTo(0.59, 0.69);
Context.lineTo(0.59, 1.47);
Context.lineTo(0, 1.47);
Context.lineTo(0, 0.11);
end;
{ TCardValueDrawer8 }
class procedure TCardValueDrawer8.DrawRaw(Context: JCanvasRenderingContext2D);
begin
BezierCurveToContext(Context, [2.25, 4.36, 2.25, 4.6, 2.22, 4.84, 2.16, 5.05,
2.06, 5.45, 1.84, 5.73, 1.57, 5.98, 1.43, 6.07, 1.28, 6.12, 1.12, 6.12,
0.97, 6.12, 0.82, 6.07, 0.68, 5.98, 0.35, 5.75, 0.2, 5.39, 0.08, 5.05,
0.03, 4.84, 0, 4.6, 0, 4.36, 0, 4.04, 0.05, 3.74, 0.14, 3.49, 0.24,
3.23, 0.37, 3.02, 0.52, 2.86, 0.4, 2.73, 0.3, 2.55, 0.23, 2.34, 0.16,
2.11, 0.12, 1.87, 0.12, 1.6, 0.12, 1.38, 0.15, 1.18, 0.2, 0.99,
0.28, 0.64, 0.48, 0.39, 0.73, 0.18, 0.85, 0.1, 0.98, 0.06, 1.12, 0.06,
1.27, 0.06, 1.4, 0.1, 1.52, 0.18, 1.82, 0.38, 1.94, 0.69, 2.05, 0.99,
2.11, 1.18, 2.13, 1.38, 2.13, 1.6, 2.13, 1.87, 2.09, 2.11, 2.02, 2.34,
1.95, 2.55, 1.85, 2.73, 1.73, 2.86, 1.88, 3.02, 2.01, 3.23, 2.1, 3.49,
2.2, 3.74, 2.25, 4.04, 2.25, 4.36]);
BezierCurveToContext(Context, [1.55, 1.6, 1.54, 1.29, 1.39, 0.64, 1.12, 0.64,
0.85, 0.65, 0.71, 1.25, 0.71, 1.6, 0.71, 1.96, 0.75, 2.56, 1.12, 2.56, 1.5,
2.56, 1.56, 1.91, 1.55, 1.6]);
BezierCurveToContext(Context, [1.66, 4.36, 1.67, 3.9, 1.59, 3.19, 1.12, 3.19,
0.66, 3.19, 0.61, 3.9, 0.59, 4.36, 0.58, 4.82, 0.66, 5.51, 1.12, 5.52,
1.59, 5.54, 1.65, 4.82, 1.66, 4.36]);
end;
{ TCardValueDrawer9 }
class procedure TCardValueDrawer9.DrawRaw(Context: JCanvasRenderingContext2D);
begin
BezierCurveToContext(Context, [2.05, 4.97, 2.01, 5.13, 1.97, 5.28, 1.91, 5.43,
1.85, 5.57, 1.79, 5.68, 1.71, 5.78, 1.52, 6.01, 1.31, 6.12, 1.08, 6.12,
0.87, 6.12, 0.68, 6.03, 0.51, 5.86, 0.34, 5.67, 0.21, 5.41, 0.12, 5.08]);
Context.lineTo(0.68, 4.92);
Context.bezierCurveTo(0.75, 5.2, 0.91, 5.54, 1.08, 5.54);
Context.bezierCurveTo(1.32, 5.53, 1.38, 5.15, 1.45, 4.93);
Context.bezierCurveTo(1.51, 4.7, 1.56, 4.4, 1.59, 4.03);
Context.bezierCurveTo(1.44, 4.16, 1.28, 4.22, 1.1, 4.22);
Context.bezierCurveTo(0.97, 4.22, 0.83, 4.17, 0.7, 4.09);
Context.bezierCurveTo(0.57, 4, 0.45, 3.86, 0.35, 3.69);
Context.bezierCurveTo(0.24, 3.51, 0.16, 3.29, 0.09, 3.03);
Context.bezierCurveTo(0.03, 2.77, 0, 2.46, 0, 2.12);
Context.bezierCurveTo(0, 1.77, 0.03, 1.47, 0.09, 1.21);
Context.bezierCurveTo(0.16, 0.94, 0.24, 0.72, 0.35, 0.55);
Context.bezierCurveTo(0.63, 0.11, 0.89, 0.02, 1.11, 0.01);
Context.bezierCurveTo(1.56, 0, 1.86, 0.5, 1.98, 0.96);
Context.bezierCurveTo(2.12, 1.49, 2.19, 2.01, 2.21, 2.53);
Context.bezierCurveTo(2.24, 3.38, 2.2, 4.17, 2.05, 4.97);
BezierCurveToContext(Context, [1.11, 0.6, 0.71, 0.59, 0.54, 1.6, 0.54, 2.12,
0.54, 2.63, 0.73, 3.63, 1.11, 3.63, 1.49, 3.64, 1.64, 2.82, 1.64, 2.16,
1.64, 1.5, 1.5, 0.61, 1.11, 0.6]);
end;
{ TCardValueDrawer10 }
class procedure TCardValueDrawer10.DrawRaw(Context: JCanvasRenderingContext2D);
begin
Context.moveTo(3.68, 4.86);
Context.bezierCurveTo(3.68, 5.63, 3.22, 6.13, 2.43, 6.13);
Context.bezierCurveTo(1.65, 6.13, 1.19, 5.59, 1.19, 4.86);
Context.lineTo(1.19, 1.28);
Context.bezierCurveTo(1.18, 0.53, 1.64, 0.01, 2.43, 0.01);
Context.bezierCurveTo(3.23, 0, 3.68, 0.62, 3.68, 1.28);
Context.moveTo(0.76, 6);
Context.lineTo(0, 6);
Context.lineTo(0, 0.11);
Context.lineTo(0.76, 0.11);
Context.moveTo(2.92, 4.86);
Context.lineTo(2.92, 1.28);
Context.bezierCurveTo(2.92, 0.96, 2.75, 0.78, 2.43, 0.78);
Context.bezierCurveTo(2.11, 0.78, 1.95, 0.96, 1.95, 1.28);
Context.lineTo(1.95, 4.86);
Context.bezierCurveTo(1.94, 5.16, 2.12, 5.36, 2.43, 5.36);
Context.bezierCurveTo(2.75, 5.36, 2.92, 5.17, 2.92, 4.86);
end;
{ TCardValueDrawerJ }
class procedure TCardValueDrawerJ.DrawRaw(Context: JCanvasRenderingContext2D);
begin
PolygonToContext(Context, [2.39, 0.95, 1.75, 0.95, 1.75, 0.11, 3.81, 0.11,
3.81, 0.95, 3.2, 0.95, 3.2, 4.44]);
Context.bezierCurveTo(3.19, 5.34, 2.76, 6.12, 1.61, 6.13);
Context.bezierCurveTo(0.31, 6.15, 0, 5.14, 0, 3.96);
Context.lineTo(0.81, 3.96);
Context.bezierCurveTo(0.8, 4.75, 0.93, 5.29, 1.61, 5.3);
Context.bezierCurveTo(2.23, 5.31, 2.4, 4.95, 2.39, 4.44);
end;
{ TCardValueDrawerQ }
class procedure TCardValueDrawerQ.DrawRaw(Context: JCanvasRenderingContext2D);
begin
Context.moveTo(3.87, 6.02);
Context.bezierCurveTo(3.28, 6.02, 3.09, 5.97, 2.86, 5.79);
Context.bezierCurveTo(2.56, 6.03, 2.23, 6.14, 1.88, 6.15);
Context.bezierCurveTo(0.94, 6.15, 0.39, 5.35, 0.39, 4.75);
Context.lineTo(0.39, 4.23);
Context.lineTo(0, 4.23);
Context.lineTo(0, 3.52);
Context.lineTo(0.39, 3.52);
Context.lineTo(0.39, 1.43);
Context.bezierCurveTo(0.4, 0.56, 1.01, 0.02, 1.88, 0.02);
Context.bezierCurveTo(2.76, 0.02, 3.37, 0.58, 3.38, 1.43);
Context.lineTo(3.38, 4.75);
Context.bezierCurveTo(3.38, 4.91, 3.35, 5.07, 3.28, 5.22);
Context.bezierCurveTo(3.56, 5.32, 3.65, 5.31, 3.87, 5.31);
Context.moveTo(2.65, 1.43);
Context.bezierCurveTo(2.65, 1.03, 2.3, 0.77, 1.88, 0.76);
Context.bezierCurveTo(1.47, 0.76, 1.11, 1.02, 1.11, 1.43);
Context.lineTo(1.11, 3.52);
Context.bezierCurveTo(1.25, 3.53, 1.38, 3.57, 1.5, 3.63);
Context.bezierCurveTo(1.63, 3.68, 1.75, 3.75, 1.86, 3.83);
Context.bezierCurveTo(1.97, 3.91, 2.08, 4, 2.18, 4.1);
Context.bezierCurveTo(2.36, 4.26, 2.5, 4.42, 2.65, 4.59);
Context.moveTo(2.31, 5.27);
Context.bezierCurveTo(2.04, 4.91, 1.7, 4.59, 1.41, 4.38);
Context.bezierCurveTo(1.28, 4.28, 1.22, 4.26, 1.11, 4.24);
Context.lineTo(1.11, 4.75);
Context.bezierCurveTo(1.12, 5.18, 1.48, 5.4, 1.88, 5.4);
Context.bezierCurveTo(2.03, 5.41, 2.17, 5.36, 2.31, 5.27);
end;
class function TCardValueDrawerQ.GetWidth: Float;
begin
Result := 3.56;
end;
class function TCardValueDrawerQ.GetHeight: Float;
begin
Result := 6.02;
end;
{ TCardValueDrawerK }
class procedure TCardValueDrawerK.DrawRaw(Context: JCanvasRenderingContext2D);
begin
PolygonToContext(Context, [3.88, 6.03, 2.07, 6.03, 2.07, 5.38, 2.65, 5.38,
1.75, 3.27, 1.19, 4.14, 1.19, 5.38, 1.64, 5.38, 1.64, 6.03, 0, 6.03,
0, 5.38, 0.54, 5.38, 0.54, 0.75, 0, 0.75, 0, 0.11, 1.64, 0.11, 1.64, 0.75,
1.19, 0.75, 1.19, 3.01, 2.63, 0.75, 2.07, 0.75, 2.07, 0.11, 3.88, 0.11,
3.88, 0.75, 3.37, 0.75, 2.19, 2.58, 3.39, 5.38, 3.88, 5.38]);
end;
class function TCardValueDrawerK.GetWidth: Float;
begin
Result := 3.88;
end;
class function TCardValueDrawerK.GetHeight: Float;
begin
Result := 6.03;
end;
{ TCardDrawerOrnament }
class procedure TCardDrawerOrnament.DrawRaw(Context: JCanvasRenderingContext2D);
begin
Context.beginPath;
BezierCurveToContext(Context, [44.35, 14.21, 43.05, 12.76, 41.91, 10.52,
43.14, 8.67, 44.31, 6.91, 47.6, 7.31, 47.94, 9.49, 48.25, 11.43, 45.57,
12.45, 44.22, 11.14, 43.32, 10.27, 45.12, 9, 45.35, 9.68, 45.54,
10.23, 45.15, 10.36, 44.55, 10.49, 45.07, 10.61, 45.95, 10.38, 45.77,
9.61, 45.42, 8.1, 42.21, 10.11, 44.22, 11.61, 45.9, 12.87, 48.55, 11.62,
48.39, 9.55, 48.22, 7.4, 45.56, 6.55, 43.85, 7.53, 42.02, 8.58, 41.78,
11.05, 42.79, 12.74, 44.13, 15, 46.28, 16.6, 47.69, 18.85, 48.36,
19.91, 48.68, 21.58, 48.91, 22.46, 48.88, 18.79, 46.36, 16.43, 44.35,
14.21]);
BezierCurveToContext(Context, [4.82, 14.21, 6.13, 12.76, 7.26, 10.52, 6.03,
8.67, 4.86, 6.91, 1.58, 7.31, 1.23, 9.49, 0.92, 11.43, 3.6, 12.45, 4.95,
11.14, 5.85, 10.27, 4.06, 9, 3.82, 9.68, 3.63, 10.23, 4.02, 10.36, 4.63,
10.49, 4.1, 10.61, 3.22, 10.38, 3.4, 9.61, 3.76, 8.1, 6.97, 10.11, 4.95,
11.61, 3.27, 12.87, 0.63, 11.62, 0.79, 9.55, 0.95, 7.4, 3.62, 6.55, 5.32,
7.53, 7.15, 8.58, 7.4, 11.05, 6.39, 12.74, 5.04, 15, 2.89, 16.6, 1.48,
18.85, 0.82, 19.91, 0.49, 21.58, 0.26, 22.46, 0.3, 18.79, 2.81, 16.43,
4.82, 14.21]);
BezierCurveToContext(Context, [37.65, 4.88, 39.09, 6.19, 41.33, 7.32, 43.18,
6.09, 44.94, 4.92, 44.54, 1.64, 42.36, 1.29, 40.42, 0.98, 39.41, 3.66,
40.72, 5.01, 41.59, 5.91, 42.86, 4.12, 42.17, 3.88, 41.62, 3.69, 41.5,
4.08, 41.37, 4.69, 41.24, 4.16, 41.48, 3.28, 42.25, 3.46, 43.76, 3.82,
41.74, 7.03, 40.24, 5.01, 38.98, 3.33, 40.23, 0.68, 42.31, 0.84, 44.45,
1.01, 45.31, 3.68, 44.32, 5.38, 43.27, 7.21, 40.81, 7.46, 39.11, 6.45,
36.85, 5.1, 35.25, 2.95, 33, 1.54, 31.94, 0.88, 30.27, 0.55, 29.4,
0.32, 33.22, 0.37, 35.42, 2.87, 37.65, 4.88]);
BezierCurveToContext(Context, [20.35, 1.02, 19.13, 1.13, 17.21, 1.59, 15.72,
2.57, 13.74, 3.87, 13.34, 5.55, 13.79, 7.24, 13.99, 8.01, 14.93, 9.42,
16.44, 9.43, 18.04, 9.45, 18.72, 8.24, 18.68, 7.39, 18.64, 6.57, 18.21,
5.66, 17.22, 5.29, 16.23, 4.93, 15.27, 5.53, 15.32, 6.44, 15.36, 7.04,
15.84, 7.37, 16.36, 7.33, 16.83, 7.3, 17.08, 6.98, 17, 6.54, 16.89, 5.96,
16.26, 5.88, 15.99, 6.21, 15.88, 6.35, 16.63, 6.43, 16.41, 6.74, 16.2,
7.04, 15.73, 6.69, 15.7, 6.45, 15.59, 5.67, 16.54, 5.38, 17.16, 5.61, 18.2,
6.13, 18.49, 7.13, 18.22, 7.9, 18.04, 8.44, 17.51, 8.97, 16.86, 8.97, 14.79,
8.96, 13.95, 7.52, 14.17, 5.5, 14.3, 4.4, 15.48, 3.27, 16.42, 2.73, 17.36,
2.2, 18.39, 1.88, 19.43, 1.63, 21.22, 1.26, 22.86, 1.13, 24.58, 1.13, 26.3,
1.13, 27.95, 1.26, 29.73, 1.63, 30.77, 1.88, 31.8, 2.2, 32.74, 2.73, 33.68,
3.27, 34.86, 4.4, 35, 5.5, 35.21, 7.52, 34.37, 8.96, 32.31, 8.97, 31.65,
8.97, 31.12, 8.44, 30.94, 7.9, 30.67, 7.13, 30.96, 6.13, 32, 5.61, 32.62,
5.38, 33.57, 5.67, 33.46, 6.45, 33.43, 6.69, 32.96, 7.04, 32.75, 6.74,
32.53, 6.43, 33.28, 6.35, 33.17, 6.21, 32.9, 5.88, 32.27, 5.96, 32.16,
6.54, 32.08, 6.98, 32.33, 7.3, 32.8, 7.33, 33.32, 7.37, 33.8, 7.04, 33.84,
6.44, 33.89, 5.53, 32.93, 4.93, 31.94, 5.29, 30.95, 5.66, 30.52, 6.57,
30.48, 7.39, 30.45, 8.24, 31.12, 9.45, 32.73, 9.43, 34.23, 9.42, 35.17,
8.01, 35.37, 7.24, 35.82, 5.55, 35.42, 3.87, 33.44, 2.57, 31.95, 1.59,
30.03, 1.13, 28.81, 1.02, 27.25, 0.91, 26.92, 0.75, 24.58, 0.75, 22.24,
0.75, 21.62, 0.9, 20.35, 1.02]);
BezierCurveToContext(Context, [25.37, 1.82, 25.9, 2.01, 26.72, 2.36, 27.2,
2.94, 27.65, 3.48, 27.75, 4.08, 27.97, 4.49, 28.21, 4.93, 28.55, 5.15,
28.6, 4.77, 28.79, 5.25, 29.96, 6.24, 29.72, 5.02, 30.52, 5.89, 30.95,
5.68, 30.74, 4.93, 30.11, 2.73, 27.37, 1.95, 25.37, 1.82]);
BezierCurveToContext(Context, [37.59, 9.84, 37.72, 9.6, 37.86, 9.31, 37.62,
9.04, 37.43, 8.82, 37.1, 8.92, 36.85, 9.11, 35.61, 10.59, 38.46, 11.94,
39.08, 9.58, 39.53, 8.26, 37.4, 6.35, 37.17, 6.21, 42.45, 9.24, 38.33,
13.02, 36.45, 11.03, 36.18, 10.75, 35.92, 10.3, 35.98, 9.8, 36.05, 9.2,
36.51, 8.6, 37.27, 8.64, 37.99, 8.71, 38.21, 9.48, 37.58, 9.84]);
BezierCurveToContext(Context, [32.84, 0, 33.14, 0.04, 34.83, 0.23, 36.02,
0.06, 37.91, -0.2, 39.02, 0.48, 36.77, 1.05, 37.52, 1.14, 38.25, 1.28,
38.27, 1.62, 38.3, 2.2, 37.58, 2.36, 37.58, 2.36, 38.98, 3.06, 37.89, 5.3,
36.77, 3.21, 36.12, 1.99, 33.91, 0.39, 32.84, 0]);
BezierCurveToContext(Context, [11.5, 4.88, 10.06, 6.19, 7.82, 7.32, 5.97,
6.09, 4.21, 4.92, 4.61, 1.64, 6.79, 1.29, 8.72, 0.98, 9.74, 3.66, 8.43,
5.01, 7.56, 5.91, 6.29, 4.12, 6.97, 3.88, 7.53, 3.69, 7.65, 4.08, 7.78,
4.69, 7.91, 4.16, 7.67, 3.28, 6.9, 3.46, 5.39, 3.82, 7.41, 7.03, 8.91,
5.01, 10.17, 3.33, 8.92, 0.68, 6.84, 0.84, 4.7, 1.01, 3.84, 3.68, 4.82,
5.38, 5.88, 7.21, 8.34, 7.46, 10.04, 6.45, 12.3, 5.1, 13.9, 2.95, 16.15,
1.54, 17.21, 0.88, 18.88, 0.55, 19.75, 0.32, 16.08, 0.36, 13.73, 2.87,
11.5, 4.88]);
BezierCurveToContext(Context, [48.68, 27.64, 48.5, 27.11, 48.14, 26.29,
47.56, 25.81, 47.03, 25.36, 46.42, 25.26, 46.01, 25.04, 45.57, 24.8,
45.35, 24.46, 45.73, 24.41, 45.26, 24.21, 44.26, 23.05, 45.48, 23.29,
44.61, 22.49, 44.82, 22.06, 45.57, 22.27, 47.77, 22.9, 48.55, 25.64,
48.68, 27.64]);
BezierCurveToContext(Context, [40.13, 14.36, 40.37, 14.23, 40.66, 14.09,
40.94, 14.33, 41.15, 14.52, 41.05, 14.85, 40.87, 15.1, 39.39, 16.34,
38.04, 13.49, 40.39, 12.87, 41.72, 12.41, 43.62, 14.54, 43.77, 14.78,
40.73, 9.5, 36.95, 13.62, 38.94, 15.5, 39.23, 15.77, 39.68, 16.03, 40.17,
15.97, 40.77, 15.9, 41.38, 15.44, 41.34, 14.67, 41.26, 13.96, 40.49, 13.73,
40.13, 14.36]);
BezierCurveToContext(Context, [49.05, 19.11, 49.01, 18.81, 48.82, 17.12,
48.99, 15.93, 49.25, 14.04, 48.57, 12.93, 48, 15.18, 47.91, 14.43, 47.76,
13.7, 47.42, 13.68, 46.84, 13.65, 46.69, 14.37, 46.69, 14.37, 45.99, 12.97,
43.74, 14.06, 45.84, 15.18, 47.06, 15.83, 48.66, 18.04, 49.05, 19.11]);
BezierCurveToContext(Context, [42.58, 21.93, 41.92, 21.94, 41.27, 21.62,
40.85, 20.79, 40.1, 19.31, 41.27, 17.61, 42.75, 17.2, 48.63, 15.58, 49.5,
26.14, 49.04, 30.22, 49.09, 27.76, 49.03, 25.21, 48.42, 22.74, 48.17, 21.7,
47.86, 20.67, 47.31, 19.71, 46.77, 18.76, 45.63, 17.55, 44.49, 17.42, 43.54,
17.3, 42.39, 17.47, 41.86, 17.96, 40.25, 19.46, 40.91, 21.21, 42.04, 21.63,
42.75, 21.9, 43.68, 21.69, 44.31, 20.77, 44.35, 20.69, 44.4, 20.61, 44.44,
20.52, 44.63, 20.03, 44.58, 19.36, 44.19, 19.08, 43.86, 18.86, 43.34, 18.82,
43.12, 19.21, 42.9, 19.7, 43.57, 19.77, 43.78, 19.31, 43.89, 19.46, 43.95,
19.86, 43.77, 20.09, 43.62, 20.27, 43.28, 20.39, 42.96, 20.11, 42.36, 19.59,
43.01, 18.76, 43.54, 18.74, 44.69, 18.68, 44.99, 19.99, 44.55, 20.68]);
Context.lineTo(44.55, 20.68);
Context.bezierCurveTo(44.22, 21.4, 43.37, 21.92, 42.58, 21.93);
BezierCurveToContext(Context, [23.78, 1.82, 23.25, 2.01, 22.43, 2.36, 21.94,
2.94, 21.5, 3.48, 21.4, 4.08, 21.18, 4.49, 20.94, 4.93, 20.6, 5.15, 20.55,
4.77, 20.35, 5.25, 19.19, 6.24, 19.43, 5.03, 18.63, 5.89, 18.19, 5.68,
18.41, 4.93, 19.04, 2.73, 21.78, 1.95, 23.78, 1.82]);
BezierCurveToContext(Context, [11.56, 9.84, 11.42, 9.6, 11.28, 9.31, 11.52,
9.04, 11.71, 8.82, 12.04, 8.92, 12.3, 9.11, 13.54, 10.59, 10.68, 11.94,
10.06, 9.59, 9.61, 8.26, 11.74, 6.36, 11.97, 6.21, 6.69, 9.24, 10.81, 13.02,
12.69, 11.03, 12.97, 10.75, 13.23, 10.3, 13.17, 9.8, 13.09, 9.2, 12.63, 8.6,
11.87, 8.64, 11.16, 8.71, 10.93, 9.49, 11.56, 9.84]);
BezierCurveToContext(Context, [16.3, 0, 16.01, 0.04, 14.32, 0.23, 13.13,
0.06, 11.24, -0.2, 10.12, 0.48, 12.37, 1.05, 11.63, 1.14, 10.89, 1.28,
10.88, 1.62, 10.85, 2.2, 11.57, 2.36, 11.57, 2.36, 10.17, 3.06, 11.26, 5.3,
12.38, 3.21, 13.03, 1.99, 15.24, 0.39, 16.3, 0]);
BezierCurveToContext(Context, [0.47, 27.64, 0.65, 27.11, 1, 26.29, 1.59,
25.81, 2.12, 25.36, 2.73, 25.26, 3.14, 25.04, 3.58, 24.8, 3.79, 24.46, 3.42,
24.41, 3.89, 24.21, 4.89, 23.05, 3.67, 23.29, 4.54, 22.49, 4.32, 22.06,
3.57, 22.27, 1.37, 22.9, 0.6, 25.64, 0.47, 27.64]);
BezierCurveToContext(Context, [9.02, 14.36, 8.77, 14.23, 8.48, 14.09, 8.21,
14.33, 8, 14.52, 8.1, 14.85, 8.28, 15.1, 9.76, 16.34, 11.11, 13.49, 8.76,
12.87, 7.43, 12.41, 5.53, 14.54, 5.38, 14.78, 8.41, 9.5, 12.19, 13.62,
10.21, 15.5, 9.92, 15.77, 9.47, 16.03, 8.97, 15.97, 8.37, 15.9, 7.77,
15.44, 7.81, 14.67, 7.89, 13.96, 8.66, 13.73, 9.02, 14.36]);
BezierCurveToContext(Context, [0.1, 19.11, 0.14, 18.81, 0.33, 17.12, 0.16,
15.93, -0.1, 14.04, 0.58, 12.93, 1.15, 15.18, 1.24, 14.43, 1.39, 13.7,
1.72, 13.68, 2.3, 13.65, 2.46, 14.37, 2.46, 14.37, 3.16, 12.97, 5.41,
14.06, 3.31, 15.18, 2.09, 15.83, 0.49, 18.04, 0.1, 19.11]);
BezierCurveToContext(Context, [6.57, 21.93, 7.23, 21.94, 7.88, 21.62, 8.3,
20.79, 9.05, 19.31, 7.88, 17.61, 6.39, 17.2, 0.51, 15.58, -0.35, 26.14,
0.1, 30.22, 0.06, 27.76, 0.12, 25.21, 0.73, 22.74, 0.98, 21.7, 1.29, 20.67,
1.84, 19.71, 2.38, 18.76, 3.51, 17.55, 4.66, 17.42, 5.61, 17.3, 6.76, 17.47,
7.28, 17.96, 8.9, 19.46, 8.23, 21.21, 7.1, 21.64, 6.39, 21.9, 5.47, 21.69,
4.84, 20.77, 4.79, 20.69, 4.75, 20.61, 4.71, 20.52, 4.52, 20.03, 4.57,
19.36, 4.96, 19.08, 5.28, 18.86, 5.8, 18.83, 6.03, 19.21, 6.25, 19.7, 5.58,
19.78, 5.37, 19.32, 5.26, 19.46, 5.2, 19.86, 5.38, 20.09, 5.53, 20.27, 5.86,
20.39, 6.18, 20.12, 6.79, 19.59, 6.14, 18.76, 5.61, 18.74, 4.45, 18.68,
4.16, 19.99, 4.6, 20.68, 4.93, 21.41, 5.78, 21.92, 6.57, 21.93]);
Context.closePath;
Context.fill;
end;
class function TCardDrawerOrnament.GetWidth: Float;
begin
Result := 49.09;
end;
class function TCardDrawerOrnament.GetHeight: Float;
begin
Result := 30.2;
end;
class procedure TCardDrawerOrnament.Draw(Context: JCanvasRenderingContext2D; ScaleFactor: Float = 1; Flip: Boolean = False);
begin
Context.Scale(ScaleFactor, ScaleFactor);
if Flip then Context.rotate(Pi);
DrawRaw(Context);
if Flip then Context.rotate(Pi);
Context.Scale(1 / ScaleFactor, 1 / ScaleFactor);
end;
end. |
namespace CollectionViews;
interface
uses
UIKit;
type
RootViewController = public class(UICollectionViewController)
private
const CELL_IDENTIFIER = 'RootViewController_Cell';
const HEADER_IDENTIFIER = 'RootViewController_Header';
var fData: NSArray;
// quick access to the layout
property collectionViewFlowLayout: UICollectionViewFlowLayout read collectionView.collectionViewLayout as UICollectionViewFlowLayout;
protected
{$REGION Collection view data source}
method numberOfSectionsInCollectionView(collectionView: UICollectionView): NSInteger;
method collectionView(collectionView: UICollectionView) numberOfItemsInSection(section: NSInteger): NSInteger;
method collectionView(collectionView: UICollectionView) cellForItemAtIndexPath(indexPath: NSIndexPath): UICollectionViewCell;
method collectionView(collectionView: UICollectionView) layout(aCollectionViewLayout: UICollectionViewLayout) sizeForItemAtIndexPath(indexPath: NSIndexPath): CGSize;
method collectionView(collectionView: UICollectionView) viewForSupplementaryElementOfKind(kind: NSString) atIndexPath(indexPath: NSIndexPath): UICollectionReusableView;
{$ENDREGION}
{$REGION Collection view delegate}
method collectionView(collectionView: UICollectionView) didSelectItemAtIndexPath(indexPath: NSIndexPath);
{$ENDREGION}
public
method init: id; override;
method viewDidLoad; override;
method didReceiveMemoryWarning; override;
end;
implementation
method RootViewController.init: id;
begin
self := inherited initWithCollectionViewLayout(new UICollectionViewFlowLayout);
if assigned(self) then begin
collectionView.registerClass(UICollectionViewCell.class) forCellWithReuseIdentifier(CELL_IDENTIFIER);
collectionView.registerClass(UICollectionReusableView.class) forSupplementaryViewOfKind(UICollectionElementKindSectionHeader) withReuseIdentifier(HEADER_IDENTIFIER);
collectionViewFlowLayout.sectionInset := UIEdgeInsetsMake(10, 10, 10, 10);
collectionViewFlowLayout.headerReferenceSize := CGSizeMake(40, 40); // only one dimension is used at a time
end;
result := self;
end;
method RootViewController.viewDidLoad;
begin
inherited viewDidLoad;
title := 'Collection View Sample';
// set up the (random) data to display in the collection view.
// to avoid blocking the main thread and application startup, we do this in a block on a
// background thread. Once done, we dispatch mach to the main thread to trigger a reload.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), method begin
var lArray := new NSMutableArray;
for i: Int32 := 0 to arc4random_uniform(5)+5 do begin
var lSection := new NSMutableArray;
for j: Int32 := 0 to arc4random_uniform(50)+5 do begin
var lSize := arc4random_uniform(100) + 100;
lSection.addObject(lSize);
end;
lArray.addObject(lSection);
end;
fData := lArray;
dispatch_async(dispatch_get_main_queue(), -> collectionView.reloadData());
end);
end;
method RootViewController.didReceiveMemoryWarning;
begin
inherited didReceiveMemoryWarning;
// Dispose of any resources that can be recreated.
end;
{$REGION Collection view data source}
method RootViewController.numberOfSectionsInCollectionView(collectionView: UICollectionView): NSInteger;
begin
if assigned(fData) then result := fData.count;
end;
method RootViewController.collectionView(collectionView: UICollectionView) numberOfItemsInSection(section: NSInteger): NSInteger;
begin
if assigned(fData) then result := fData[section].count;
end;
method RootViewController.collectionView(collectionView: UICollectionView) layout(aCollectionViewLayout: UICollectionViewLayout) sizeForItemAtIndexPath(indexPath: NSIndexPath): CGSize;
begin
// each cell will have a random size
var lInfo := fData[indexPath.section][indexPath.row];
result := CGSizeMake(lInfo.floatValue, lInfo.floatValue);
end;
method RootViewController.collectionView(collectionView: UICollectionView) cellForItemAtIndexPath(indexPath: NSIndexPath): UICollectionViewCell;
begin
result := collectionView.dequeueReusableCellWithReuseIdentifier(CELL_IDENTIFIER) forIndexPath(indexPath);
// remove any existing sub-views, in case we are reusing an existing cell
result.subviews.makeObjectsPerformSelector(selector(removeFromSuperview));
// and then add a label to the cell showing the current item number.
var lLabel := new UILabel;
lLabel.text := NSNumber.numberWithInt(indexPath.row).stringValue;
lLabel.frame := result.bounds;
lLabel.textColor := UIColor.whiteColor;
lLabel.backgroundColor := UIColor.darkGrayColor;
lLabel.font := UIFont.systemFontOfSize(30);
lLabel.textAlignment := NSTextAlignment.NSTextAlignmentCenter;
result.addSubview(lLabel);
end;
method RootViewController.collectionView(collectionView: UICollectionView) viewForSupplementaryElementOfKind(kind: NSString) atIndexPath(indexPath: NSIndexPath): UICollectionReusableView;
begin
result := collectionView.dequeueReusableSupplementaryViewOfKind(kind) withReuseIdentifier(HEADER_IDENTIFIER) forIndexPath(indexPath);
// remove any existing sub-views, in case we are reusing an existing cell
result.subviews:makeObjectsPerformSelector(selector(removeFromSuperview));
// and then add a label to the cell showing the current section.
var lLabel := new UILabel;
lLabel.text := NSString.stringWithFormat('Section %ld', indexPath.section);
lLabel.frame := result.bounds;
lLabel.textColor := UIColor.blackColor;
lLabel.backgroundColor := UIColor.lightGrayColor;
lLabel.font := UIFont.boldSystemFontOfSize(20);
lLabel.textAlignment := NSTextAlignment.NSTextAlignmentCenter;
lLabel.contentMode := UIViewContentMode.UIViewContentModeRedraw;
result.addSubview(lLabel);
end;
method RootViewController.collectionView(collectionView: UICollectionView) didSelectItemAtIndexPath(indexPath: NSIndexPath);
begin
// add code here to handle when a cell gets selected.
end;
{$ENDREGION}
end.
|
unit mrConfigTable;
interface
uses
SysUtils, Classes, Provider, ADODB, DB, DBClient, Variants;
type
TmrConfigTable = class(TComponent)
private
FAutoGenerateCode: Boolean;
FAutoGenerateIdentity: Boolean;
FCodeField: string;
FDataSetProvider: TDataSetProvider;
FDependentTables: TStringList;
FForeignField: String;
FIdentityField: String;
FIsVersion: Boolean;
FLogicalDeleteField: String;
FReadOnlyFields: TStringList;
FReadOnlyFieldsOnEdit: TStringList;
FTableName: String;
FTableNamePrefix: String;
FUniqueFields: TStringList;
FVesionTableKey: String;
FVersionTableName: String;
{ Eventos}
FOnAfterGetRecords: TRemoteEvent;
FOnAfterUpdateRecords: TAfterUpdateRecordEvent;
FOnBeforeGetRecords: TRemoteEvent;
FOnBeforeUpdateRecords: TBeforeUpdateRecordEvent;
FOnGetDataSetProperties: TGetDSProps;
FOnNewRecord: TRemoteEvent;
FHiddenFields: TStringList;
procedure SetDataSetProvider(const Value: TDataSetProvider);
procedure DoGetDataSetProperties(Sender: TObject; DataSet: TDataSet;
out Properties: OleVariant);
procedure DoAfterGetRecords(Sender: TObject; var OwnerData: OleVariant);
procedure DoBeforeGetRecords(Sender: TObject; var OwnerData: OleVariant);
procedure DoAfterUpdateRecords(Sender: TObject; SourceDS: TDataSet;
DeltaDS: TCustomClientDataSet; UpdateKind: TUpdateKind);
procedure DoBeforeUpdateRecords(Sender: TObject; SourceDS: TDataSet;
DeltaDS: TCustomClientDataSet; UpdateKind: TUpdateKind; var Applied: Boolean);
procedure DoInsertRecords(DeltaDS: TCustomClientDataSet; Applied: Boolean);
procedure DoUpdateRecords(DeltaDS: TCustomClientDataSet; Applied: Boolean);
procedure DoDeleteRecords(DeltaDS: TCustomClientDataSet; Applied: Boolean);
procedure DeleteDependentTables(aID: String);
function GetListFields(ListFields: TStringList): String;
procedure SetReadOnlyFields(const Value: TStringList);
procedure SetDependentTables(const Value: TStringList);
procedure SetReadOnlyFieldsOnEdit(const Value: TStringList);
procedure SetUniqueFields(const Value: TStringList);
procedure SetHiddenFields(const Value: TStringList);
protected
{ Protected declarations }
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property AutoGenerateCode: Boolean read FAutoGenerateCode write FAutoGenerateCode default False;
property AutoGenerateIdentity: Boolean read FAutoGenerateIdentity write FAutoGenerateIdentity default False;
property CodeField: string read FCodeField write FCodeField;
property DataSetProvider: TDataSetProvider read FDataSetProvider write SetDataSetProvider;
property DependentTables: TStringList read FDependentTables write SetDependentTables;
property ForeignField: string read FForeignField write FForeignField;
property IdentityField: string read FIdentityField write FIdentityField;
property IsVersion: Boolean read FIsVersion write FIsVersion default False;
property LogicalDeleteField: string read FLogicalDeleteField write FLogicalDeleteField;
property ReadOnlyFields: TStringList read FReadOnlyFields write SetReadOnlyFields;
property ReadOnlyFieldsOnEdit: TStringList read FReadOnlyFieldsOnEdit write SetReadOnlyFieldsOnEdit;
property TableName: string read FTableName write FTableName;
property TableNamePrefix: string read FTableNamePrefix write FTableNamePrefix;
property UniqueFields: TStringList read FUniqueFields write SetUniqueFields;
property VesionTableKey: string read FVesionTableKey write FVesionTableKey;
property VersionTableName: string read FVersionTableName write FVersionTableName;
property HiddenFields: TStringList read FHiddenFields write SetHiddenFields;
{Declarações dos Eventos}
property OnAfterGetRecords: TRemoteEvent read FOnAfterGetRecords write FOnAfterGetRecords;
property OnAfterUpdateRecords: TAfterUpdateRecordEvent read FOnAfterUpdateRecords write FOnAfterUpdateRecords;
property OnBeforeGetRecords: TRemoteEvent read FOnBeforeGetRecords write FOnBeforeGetRecords;
property OnBeforeUpdateRecords: TBeforeUpdateRecordEvent read FOnBeforeUpdateRecords write FOnBeforeUpdateRecords;
property OnGetDataSetProperties: TGetDSProps read FOnGetDataSetProperties write FOnGetDataSetProperties;
property OnNewRecord: TRemoteEvent read FOnNewRecord write FOnNewRecord;
end;
procedure Register;
implementation
uses uSQLFunctions, uMRSQLParam;
procedure Register;
begin
RegisterComponents('MultiTierLib', [TmrConfigTable]);
end;
{ TmrConfigTable }
procedure TmrConfigTable.DoAfterGetRecords(Sender: TObject;
var OwnerData: OleVariant);
begin
if OwnerData <> '' then
TADOQuery(FDataSetProvider.DataSet).SQL.Text := OwnerData;
if Assigned(FOnAfterGetRecords) then
OnAfterGetRecords(Self, OwnerData);
end;
procedure TmrConfigTable.DoAfterUpdateRecords(Sender: TObject; SourceDS: TDataSet;
DeltaDS: TCustomClientDataSet; UpdateKind: TUpdateKind);
begin
if Assigned(FOnAfterUpdateRecords) then
OnAfterUpdateRecords(Self, SourceDS, DeltaDS, UpdateKind);
end;
procedure TmrConfigTable.DoBeforeGetRecords(Sender: TObject; var OwnerData: OleVariant);
var
sOldSQL: String;
Where: TMRSQLParam;
begin
try
sOldSQL := TADOQuery(FDataSetProvider.DataSet).SQL.Text;
Where := TMRSQLParam.Create;
Where.ParamString := OwnerData;
if Assigned(FOnBeforeGetRecords) then
OnBeforeGetRecords(Self, OwnerData)
else
OwnerData := Where.GetWhereSQL;
TADOQuery(FDataSetProvider.DataSet).SQL.Text :=
ChangeWhereClause(TADOQuery(FDataSetProvider.DataSet).SQL.Text, OwnerData, True);
OwnerData := sOldSQL;
finally
FreeAndNil(Where);
end;
end;
procedure TmrConfigTable.DoBeforeUpdateRecords(Sender: TObject; SourceDS: TDataSet;
DeltaDS: TCustomClientDataSet; UpdateKind: TUpdateKind; var Applied: Boolean);
begin
if Assigned(FOnBeforeUpdateRecords) then
OnBeforeUpdateRecords(Self, SourceDS, DeltaDS, UpdateKind, Applied);
if UpdateKind = ukInsert then
DoInsertRecords(DeltaDS, Applied)
else if UpdateKind = ukModify then
DoUpdateRecords(DeltaDS, Applied)
else if UpdateKind = ukDelete then
DoDeleteRecords(DeltaDS, Applied);
end;
procedure TmrConfigTable.DoDeleteRecords(DeltaDS: TCustomClientDataSet;
Applied: Boolean);
begin
// Deleção nas tabelas dependentes
if FDependentTables.Text <> '' then
DeleteDependentTables(DeltaDS.FieldByName(FIdentityField).AsString);
end;
procedure TmrConfigTable.DoInsertRecords(DeltaDS: TCustomClientDataSet;
Applied: Boolean);
begin
if not Applied then
Exit;
DeltaDS.ApplyRange
end;
procedure TmrConfigTable.DoUpdateRecords(DeltaDS: TCustomClientDataSet;
Applied: Boolean);
begin
if not Applied then
Exit;
DeltaDS.ApplyRange
end;
procedure TmrConfigTable.SetDataSetProvider(const Value: TDataSetProvider);
begin
FDataSetProvider := Value;
with FDataSetProvider do
if Assigned(FDataSetProvider) then
begin
AfterGetRecords := DoAfterGetRecords;
BeforeGetRecords := DoBeforeGetRecords;
AfterUpdateRecord := DoAfterUpdateRecords;
BeforeUpdateRecord := DoBeforeUpdateRecords;
OnGetDataSetProperties := DoGetDataSetProperties;
end;
end;
constructor TmrConfigTable.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FReadOnlyFields := TStringList.Create;
FReadOnlyFieldsOnEdit := TStringList.Create;
FUniqueFields := TStringList.Create;
FDependentTables := TStringList.Create;
FHiddenFields := TStringList.Create;;
end;
destructor TmrConfigTable.Destroy;
begin
FReadOnlyFields.Free;
FReadOnlyFieldsOnEdit.Free;
FUniqueFields.Free;
FDependentTables.Free;
FHiddenFields.Free;
inherited Destroy;
end;
procedure TmrConfigTable.DoGetDataSetProperties(Sender: TObject;
DataSet: TDataSet; out Properties: OleVariant);
var
FieldsDefaultValues,
ReadOnlyFieldsList,
ReadOnlyFieldsOnEditList,
UniqueFieldsList,
HiddenFieldsList :OleVariant;
begin
Properties := VarArrayCreate([0, 12], varVariant);
Properties[0] := VarArrayOf(['TableName', FTableName, True]);
Properties[1] := VarArrayOf(['TableNamePrefix', FTableNamePrefix, True]);
Properties[2] := VarArrayOf(['ForeignField', FForeignField, True]);
Properties[3] := VarArrayOf(['IdentityField', FIdentityField, True]);
Properties[4] := VarArrayOf(['AutoGenerateIdentity', FAutoGenerateIdentity, True]);
Properties[5] := VarArrayOf(['CodeField', FCodeField, True]);
Properties[6] := VarArrayOf(['AutoGenerateCode', FAutoGenerateCode, True]);
Properties[7] := VarArrayOf(['LogicalDeleteField', FLogicalDeleteField, True]);
FieldsDefaultValues := '';
if Assigned(FOnNewRecord) then
OnNewRecord(Self, FieldsDefaultValues);
Properties[8] := VarArrayOf(['FieldsDefaultValues', FieldsDefaultValues, True]);
ReadOnlyFieldsList := '';
if Assigned(FReadOnlyFields) then
ReadOnlyFieldsList := GetListFields(FReadOnlyFields);
Properties[9] := VarArrayOf(['ReadOnlyFields', ReadOnlyFieldsList, True]);
ReadOnlyFieldsOnEditList := '';
if Assigned(FReadOnlyFieldsOnEdit) then
ReadOnlyFieldsOnEditList := GetListFields(FReadOnlyFieldsOnEdit);
Properties[10] := VarArrayOf(['ReadOnlyOnEditFields', ReadOnlyFieldsOnEditList, True]);
UniqueFieldsList := '';
if Assigned(FUniqueFields) then
UniqueFieldsList := GetListFields(FUniqueFields);
Properties[11] := VarArrayOf(['UniqueFields', UniqueFieldsList, True]);
HiddenFieldsList := '';
if Assigned(FHiddenFields) then
HiddenFieldsList := GetListFields(FHiddenFields);
Properties[12] := VarArrayOf(['HiddenFields', HiddenFieldsList, True]);
if Assigned(FOnGetDataSetProperties) then
OnGetDataSetProperties(Self, DataSet, Properties);
end;
function TmrConfigTable.GetListFields(ListFields: TStringList): String;
var
I: Integer;
begin
Result := '';
for I := 0 to ListFields.Count-1 do
Result := Result + ListFields[I] + ';';
end;
procedure TmrConfigTable.SetReadOnlyFields(const Value: TStringList);
begin
FReadOnlyFields.Assign(Value);
end;
procedure TmrConfigTable.SetReadOnlyFieldsOnEdit(const Value: TStringList);
begin
FReadOnlyFieldsOnEdit.Assign(Value);
end;
procedure TmrConfigTable.SetUniqueFields(const Value: TStringList);
begin
FUniqueFields.Assign(Value);
end;
procedure TmrConfigTable.SetDependentTables(const Value: TStringList);
begin
FDependentTables.Assign(Value);
end;
procedure TmrConfigTable.DeleteDependentTables(aID: String);
var
i: Integer;
sTableName: String;
sWhereClause: String;
Connection: TADOConnection;
begin
Connection := TADOQuery(DataSetProvider.DataSet).Connection;
with FDependentTables do
for i := 0 to Count-1 do
begin
sTableName := Copy(Strings[i], 1, Pos(',', Strings[i])-1);
sWhereClause := Copy(Strings[i], Pos(',', Strings[i])+1, Length(Strings[i])) + ' = ' + aID;
Connection.Execute('DELETE ' + sTableName + ' WHERE ' + sWhereClause);
end;
end;
procedure TmrConfigTable.SetHiddenFields(const Value: TStringList);
begin
FHiddenFields.Assign(Value);
end;
end.
|
unit ThemeSelector;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
LiteScrollBox, uColorTheme, LiteButton, LiteEdit;
type ApplyEvent = procedure(theme: ColorTheme) of object;
type UpdateEvent = procedure(theme: ColorTheme) of object;
{
Represents UI for selecting theme colors
}
type TThemeSelector = class(TLiteScrollBox, IUnknown, IThemeSupporter)
private
theme, subTheme: ColorTheme;
cs: TColorDialog;
name: TLiteEdit;
applyEventHandle: ApplyEvent;
updateEventHandle: UpdateEvent;
// Crutch
userValidateStateTrigger: boolean;
procedure colorSelection(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure updateTheme();
function pickColor(default: TColor): TColor;
procedure apply(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
// Crutch
procedure userValidateStateWrite(b: boolean);
protected
public
constructor Create(AOwner: TComponent); override;
// IThemeSupporter
procedure setTheme(theme: ColorTheme);
function getTheme(): ColorTheme;
procedure updateColors();
procedure validateState();
{
SubTheme is used to save current theme and be able to restore it in the future
}
procedure setSubTheme(theme: ColorTheme);
function getSubTheme(): ColorTheme;
published
property OnApply: ApplyEvent read applyEventHandle write applyEventHandle;
property OnColorUpdate: UpdateEvent read updateEventHandle write updateEventHandle;
property __UpdateState: boolean read userValidateStateTrigger write userValidateStateWrite;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Lite', [TThemeSelector]);
end;
// Override
constructor TThemeSelector.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
cs := TColorDialog.Create(nil);
subTheme := ColorTheme.Create('sub');
setTheme(CT_DEFAULT_THEME);
validateState();
updateColors();
end;
// Override
procedure TThemeSelector.setTheme(theme: ColorTheme);
var
i: integer;
supporter: IThemeSupporter;
begin
self.theme := theme;
for i := 0 to ControlCount - 1 do
if Supports(controls[i], IThemeSupporter, supporter) then
if controls[i] is TWinControl then
if (controls[i] as TWinControl).Tag = 1 then
supporter.setTheme(theme);
end;
// Override
function TThemeSelector.getTheme(): ColorTheme;
begin
getTheme := self.theme;
end;
// Override
procedure TThemeSelector.updateColors();
var
i: integer;
supporter: IThemeSupporter;
begin
Color := theme.background;
for i := 0 to ControlCount - 1 do
if Supports(controls[i], IThemeSupporter, supporter) then
supporter.updateColors();
end;
// Crutch
procedure TThemeSelector.userValidateStateWrite(b: boolean);
begin
validateState();
updateColors();
end;
// TThemeSelector
procedure TThemeSelector.validateState();
var
i, top: integer;
button: TLiteButton;
localTheme: ColorTheme;
begin
top := 0;
// clear children
for i := 0 to ControlCount - 1 do
controls[0].Free;
// init buttons (15)
for i := 0 to 14 do begin
button := TLiteButton.Create(self);
button.Parent := self;
button.Width := Width - 24;
button.Height := 24;
button.Top := top;
top := top + button.Height + 8;
button.AutoReact := false;
button.OnMouseDown := colorSelection;
end;
// setup
// interact
localTheme := ColorTheme.Create('local');
localTheme.interact := theme.interact;
localTheme.text := theme.text;
(controls[0] as TLiteButton).setTheme(localTheme);
(controls[0] as TLiteButton).Caption := 'Interact';
// active
localTheme := ColorTheme.Create('local');
localTheme.interact := theme.active;
localTheme.text := theme.text;
(controls[1] as TLiteButton).setTheme(localTheme);
(controls[1] as TLiteButton).Caption := 'Active';
// text
localTheme := ColorTheme.Create('local');
localTheme.interact := theme.text;
localTheme.text := theme.interact;
(controls[2] as TLiteButton).setTheme(localTheme);
(controls[2] as TLiteButton).Caption := 'Text';
// textfield
localTheme := ColorTheme.Create('local');
localTheme.interact := theme.textfield;
localTheme.text := theme.text;
(controls[3] as TLiteButton).setTheme(localTheme);
(controls[3] as TLiteButton).Caption := 'Textfield';
// warn
localTheme := ColorTheme.Create('local');
localTheme.interact := theme.warn;
localTheme.text := theme.text;
(controls[4] as TLiteButton).setTheme(localTheme);
(controls[4] as TLiteButton).Caption := 'Warn';
// title
localTheme := ColorTheme.Create('local');
localTheme.interact := theme.title;
localTheme.text := theme.text;
(controls[5] as TLiteButton).setTheme(localTheme);
(controls[5] as TLiteButton).Caption := 'Title';
// background
localTheme := ColorTheme.Create('local');
localTheme.interact := theme.background;
localTheme.text := theme.text;
(controls[6] as TLiteButton).setTheme(localTheme);
(controls[6] as TLiteButton).Caption := 'Background';
// coordBG
localTheme := ColorTheme.Create('local');
localTheme.interact := theme.coordBG;
localTheme.text := theme.text;
(controls[7] as TLiteButton).setTheme(localTheme);
(controls[7] as TLiteButton).Caption := 'Coord Net BG';
// coordGrid
localTheme := ColorTheme.Create('local');
localTheme.interact := theme.coordGrid;
localTheme.text := theme.text;
(controls[8] as TLiteButton).setTheme(localTheme);
(controls[8] as TLiteButton).Caption := 'Coord Net Grid';
// coordPoint
localTheme := ColorTheme.Create('local');
localTheme.interact := theme.coordPoint;
localTheme.text := theme.interact;
(controls[9] as TLiteButton).setTheme(localTheme);
(controls[9] as TLiteButton).Caption := 'Coord Net Point';
// coordOutline
localTheme := ColorTheme.Create('local');
localTheme.interact := theme.coordOutline;
localTheme.text := theme.text;
(controls[10] as TLiteButton).setTheme(localTheme);
(controls[10] as TLiteButton).Caption := 'Point Outline';
// coordText
localTheme := ColorTheme.Create('local');
localTheme.interact := theme.coordText;
localTheme.text := theme.coordBG;
(controls[11] as TLiteButton).setTheme(localTheme);
(controls[11] as TLiteButton).Caption := 'Coord Net Text';
// coordLine
localTheme := ColorTheme.Create('local');
localTheme.interact := theme.coordLine;
localTheme.text := theme.coordBG;
(controls[12] as TLiteButton).setTheme(localTheme);
(controls[12] as TLiteButton).Caption := 'Coord Net Line';
// coordAxis
localTheme := ColorTheme.Create('local');
localTheme.interact := theme.coordAxis;
localTheme.text := theme.coordBG;
(controls[13] as TLiteButton).setTheme(localTheme);
(controls[13] as TLiteButton).Caption := 'Coord Net Axis';
// scrollbarBG
localTheme := ColorTheme.Create('local');
localTheme.interact := theme.scrollbarBG;
localTheme.text := theme.text;
(controls[14] as TLiteButton).setTheme(localTheme);
(controls[14] as TLiteButton).Caption := 'ScrollBar BG';
top := top + 8;
// Name
name := TLiteEdit.Create(self);
name.Parent := self;
name.setValueType(VT_NOT_EMPTY_TEXT);
name.Text := 'New Theme';
name.Width := Width - 24;
name.Height := 24;
name.Top := top;
name.Tag := 1;
top := top + name.Height + 16;
// Apply Button
button := TLiteButton.Create(self);
button.Parent := self;
button.Width := Width - 32;
button.Height := 32;
button.Left := 8;
button.Top := top;
button.Tag := 1;
button.Caption := 'Confirm';
button.OnMouseDown := apply;
inherited validateState();
end;
// TThemeSelector
function TThemeSelector.pickColor(default: TColor): TColor;
begin
if cs.Execute then
pickColor := cs.Color
else
pickColor := default;
end;
// TThemeSelector
procedure TThemeSelector.updateTheme();
begin
theme.interact := (controls[0] as TLiteButton).getTheme().interact;
theme.active := (controls[1] as TLiteButton).getTheme().interact;
theme.text := (controls[2] as TLiteButton).getTheme().interact;
theme.textfield := (controls[3] as TLiteButton).getTheme().interact;
theme.warn := (controls[4] as TLiteButton).getTheme().interact;
theme.title := (controls[5] as TLiteButton).getTheme().interact;
theme.background := (controls[6] as TLiteButton).getTheme().interact;
theme.coordBG := (controls[7] as TLiteButton).getTheme().interact;
theme.coordGrid := (controls[8] as TLiteButton).getTheme().interact;
theme.coordPoint := (controls[9] as TLiteButton).getTheme().interact;
theme.coordOutline := (controls[10] as TLiteButton).getTheme().interact;
theme.coordText := (controls[11] as TLiteButton).getTheme().interact;
theme.coordLine := (controls[12] as TLiteButton).getTheme().interact;
theme.coordAxis := (controls[13] as TLiteButton).getTheme().interact;
theme.scrollbarBG := (controls[14] as TLiteButton).getTheme().interact;
end;
// TThemeSelector
procedure TThemeSelector.colorSelection(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
localTheme: ColorTheme;
begin
localTheme := (Sender as TLiteButton).getTheme();
localTheme.interact := pickColor(localTheme.interact);
updateTheme();
localTheme.text := theme.text;
(Sender as TLiteButton).setTheme(localTheme);
validateState();
updateColors();
if Assigned(updateEventHandle) then
updateEventHandle(theme);
end;
// TThemeSelector
procedure TThemeSelector.apply(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if name.isValid then
if Assigned(applyEventHandle) then begin
theme.name := name.Text;
applyEventHandle(theme);
end;
end;
// TThemeSelector
procedure TThemeSelector.setSubTheme(theme: ColorTheme);
begin
subTheme := theme;
end;
// TThemeSelector
function TThemeSelector.getSubTheme(): ColorTheme;
begin
getSubTheme := subTheme;
end;
end.
|
unit UFNMDAOInfo;
{$WARN SYMBOL_PLATFORM OFF}
interface
uses
SysUtils, Classes, ComServ, ComObj, VCLCom, StdVcl, bdemts,
DataBkr, DBClient, MtsRdm, Mtx, FNMDAO_TLB, Provider, DB, ADODB, ADOInt;
type
TFNMDAOInfo = class(TMtsDataModule, IFNMDAOInfo)
adoConnection: TADOConnection;
dataSetProvider: TDataSetProvider;
procedure MtsDataModuleCreate(Sender: TObject);
protected
class procedure UpdateRegistry(Register: Boolean; const ClassID, ProgID: string); override;
procedure GetCommonDataSet(var vData: OleVariant; const sqlText: WideString; var sErrorMsg: WideString); safecall;
{* 该方法实现一些通用的获取数据集的方法,最常见的是提供一个sql语句,返回数据集。}
procedure GetCommonFieldValue(var vFieldValue: OleVariant; const sSqlText: WideString; var sErrorMsg: WideString); safecall;
{* 通过SQL语句返回第一条记录第一个字段的值}
procedure GetMultiDataSet(const sSqlText: WideString; var vData0, vData1, vData2: OleVariant; var sErrorMsg: WideString); safecall;
procedure GetCommonData(var vData: OleVariant; const sqlText: WideString;
var sErrorMsg: WideString); safecall;
procedure ExeCommonSql(const sSqlText: WideString;
var sErrorMsg: WideString); safecall;
{* 通过单SQL语句返回多数据集合}
end;
var
FNMDAOInfo: TFNMDAOInfo;
implementation
uses DA, ComDllPub;
{$R *.DFM}
class procedure TFNMDAOInfo.UpdateRegistry(Register: Boolean; const ClassID, ProgID: string);
begin
if Register then
begin
inherited UpdateRegistry(Register, ClassID, ProgID);
EnableSocketTransport(ClassID);
EnableWebTransport(ClassID);
end else
begin
DisableSocketTransport(ClassID);
DisableWebTransport(ClassID);
inherited UpdateRegistry(Register, ClassID, ProgID);
end;
end;
procedure TFNMDAOInfo.MtsDataModuleCreate(Sender: TObject);
begin
adoConnection.ConnectionString :=GetConnectionString('FNMDAO.dll','FNM');
end;
procedure TFNMDAOInfo.GetCommonDataSet(var vData: OleVariant;
const sqlText: WideString; var sErrorMsg: WideString);
var
da:TDA;
begin
try
try
da:=TDA.Create(sqlText,cmdText,adoConnection);
dataSetProvider.DataSet :=da.DataSet(sErrorMsg);
if sErrorMsg='' then
begin
vData:=dataSetProvider.Data;
setcomplete;
end
else
setAbort;
except
on e: Exception do
begin
sErrorMsg:=e.Message;
setabort;
end
end;
finally
FreeAndNil(da);
end;
end;
procedure TFNMDAOInfo.GetCommonFieldValue(var vFieldValue: OleVariant;
const sSqlText: WideString; var sErrorMsg: WideString);
var
da:TDA;
begin
try
try
da:=TDA.Create(sSqlText,cmdText,adoConnection);
vFieldValue:=da.ExecuteScalar(sErrorMsg);
if sErrorMsg='' then setcomplete else setAbort;
except
on e: Exception do
begin
sErrorMsg:=e.Message;
setabort;
end
end;
finally
FreeAndNil(da);
end;
end;
procedure TFNMDAOInfo.GetMultiDataSet(const sSqlText: WideString;
var vData0, vData1, vData2: OleVariant; var sErrorMsg: WideString);
const
ResultParamCount= 3;//vData参数的个数.
var
da: TDA;
i, RowCount: Integer;
Recordset: _Recordset;
mADODataset: TADODataset;
VariantData: Array[1..ResultParamCount] of OleVariant;
begin
FillChar(VariantData, Sizeof(VariantData), #0);
try
try
da:=TDA.Create(sSqlText, cmdText, adoConnection);
mADODataset:=da.DataSet(sErrorMsg);
if sErrorMsg <> '' then
exit;
DataSetProvider.DataSet:= mADODataset;
Recordset:=mADODataset.Recordset;
i:=0;
while (Recordset <> nil) and (i <= ResultParamCount) do
begin
if (Recordset.State and adStateOpen) <> 0 then
begin
Inc(i);
mADODataset.Recordset:=Recordset;
VariantData[i]:=DataSetProvider.Data;
end;
Recordset:= mADODataset.NextRecordset(RowCount);
end;
if sErrorMsg='' then setcomplete else setAbort;
except
on e: Exception do
begin
sErrorMsg:=e.Message;
setabort;
end
end;
finally
FreeAndNil(da);
end;
vData0:=VariantData[1];
vData1:=VariantData[2];
vData2:=VariantData[3];
end;
procedure TFNMDAOInfo.GetCommonData(var vData: OleVariant;
const sqlText: WideString; var sErrorMsg: WideString);
var
da: TDA;
i, RowCount: Integer;
Recordset: _Recordset;
VariantData: array of OleVariant;
mADODataset: TADODataset;
begin
try
try
da:=TDA.Create(sqlText, cmdText, adoConnection);
mADODataset:=da.DataSet(sErrorMsg);
if sErrorMsg <> '' then exit;
DataSetProvider.DataSet:= mADODataset;
Recordset:=mADODataset.Recordset;
i:=0;
while (Recordset <> nil) do
begin
if (Recordset.State and adStateOpen) <> 0 then
begin
Inc(i);
SetLength(VariantData, i);
mADODataset.Recordset:=Recordset;
VariantData[i-1]:=DataSetProvider.Data;
end;
Recordset:= mADODataset.NextRecordset(RowCount);
end;
if i = 1 then
vData := VariantData[0]
else
vData := VariantData;
if sErrorMsg='' then setcomplete else setAbort;
except
on e: Exception do
begin
sErrorMsg:=e.Message;
setabort;
end
end;
finally
FreeAndNil(da);
SetLength(VariantData, 0);
end;
end;
procedure TFNMDAOInfo.ExeCommonSql(const sSqlText: WideString;
var sErrorMsg: WideString);
var
da:TDA;
begin
sErrorMsg:='';
da:=TDA.Create(sSqlText,cmdText,adoConnection);
try
try
da.ExecuteNonQuery(sErrorMsg);
if sErrorMsg='' then
setcomplete
else
raise exception.Create(sErrorMsg);
except
on e:Exception do
begin
sErrorMsg:=e.Message;
setabort;
end;
end;
finally
da.Free;
end;
end;
initialization
TComponentFactory.Create(ComServer, TFNMDAOInfo,
Class_FNMDAOInfo, ciMultiInstance, tmNeutral);
end.
|
unit MaestroAPI;
interface
uses
UIFormSplash, Forms,
System.IniFiles, System.SysUtils, System.StrUtils, System.Generics.Collections, System.IOUtils
;
type
TMaestroConfig = class
protected
const Section_VERSAO = 'VERSAO_ATUAL';
public
Produto: String;//produto
Versao: String; //versao atual
BPL: String;
public
constructor Create(); reintroduce; virtual;
end;
/// MAESTRO API - BOOTSTRAP
TMaestroApi = class
protected
class procedure InternalLoad(f: TForm);
public
class procedure Load();
class procedure ReloadLoad();
end;
implementation
uses
AsyncCalls, Splash, ShellApi, Windows,
System.Classes,
System.RTTI;
//function GetInitialClass(): TClass;
//var
// c: TClass;
// ctx: TRttiContext;
// typ: TRttiType;
//begin
// ctx := TRttiContext.Create;
// typ := ctx.FindType('Unit2.TForm2');
// if (typ <> nil) and (typ.IsInstance) then c := typ.AsInstance.MetaClassType;
// ctx.Free;
//
// if c = nil then
// c:= GetClass('TForm2');
// Result:= c;
//end;
{ TMaestroConfig }
constructor TMaestroConfig.Create();
var
ini: TIniFile;
begin
// Create INI Object and open or create file test.ini
ini := TIniFile.Create(IncludeTrailingBackslash(ExtractFilePath(ParamStr(0)))+'maestro.ini');
try
Produto:= ini.ReadString('Section_VERSAO', 'PRODUTO', 'dolphin-desktop');
Versao:= ini.ReadString('Section_VERSAO', 'VERSAO', '17.1.1');
BPL:= ini.ReadString('Section_VERSAO', 'BPL', 'bplForm-17.1.1.bpl');
//teste recrea
ini.WriteString('Section_VERSAO', 'PRODUTO', Produto);
ini.WriteString('Section_VERSAO', 'VERSAO', Versao);
ini.WriteString('Section_VERSAO', 'BPL', BPL);
ini.UpdateFile();
finally
ini.Free;
end;
end;
{ TMaestroApi }
procedure InitializePackageX();
type
TPackageLoad = procedure;
var
PackageLoad: TPackageLoad;
Module: HMODULE;
begin
Module:= LoadPackage('bplForm2.bpl');
@PackageLoad := GetProcAddress(Module, 'InitX'); //Do not localize
if Assigned(PackageLoad) then
PackageLoad();
end;
function funcCallBackXX(const Arg: IInterface): Integer;
var
count: Integer;
config: TMaestroConfig;
i: IFormSplash;
begin
i:= Arg as IFormSplash;
config:= TMaestroConfig.Create(); //configs...
i.Init();
i.SetInfo(Format('Atualizando %s%s', [config.Produto, config.Versao]));{sync a tela}
//loop wait...
for count := 1 to 10 do
begin
i.Update(Format('Arquivo%2d', [count]));{sync a tela}
Sleep(200);
end;
i.CloseX();
//simulado download...
CopyFile(PWideChar('.\'+config.Versao+'\'+config.BPL), '.\lib\bplForm2.bpl', false);
SetCurrentDir('.\lib');
//carrega BPLS....
InitializePackageX();
//cria dinamico o form
end;
class procedure TMaestroApi.Load();
begin
TMaestroApi.InternalLoad( TFormSplashUI.Create(nil) );
end;
class procedure TMaestroApi.ReloadLoad();
var
appName: PChar;
begin
//close....
appName:= PChar(Application.ExeName);
Application.Destroy();//??
ShellExecute(0, nil, appName, nil, nil, SW_SHOWNORMAL);
end;
class procedure TMaestroApi.InternalLoad(f: TForm);
var
i: IFormSplash;
begin
Application.Initialize;
Application.MainFormOnTaskbar := True;
//inicializa o SPLASH
f.Show();
f.GetInterface(IFormSplash, i);
//ATUALIZA VERSAO...
AsyncCalls.AsyncCall(
funcCallBackXX,
i{params}
);
Application.Run;
end;
end.
|
unit uEditoraController;
interface
uses SysUtils, StrUtils, Dialogs, uPadraoController, uEditoraModel;
type
TEditoraController = class(TPadraoController)
function GravarRegistro(AEditoraModel: TEditoraModel): Boolean;
function ExcluirRegistro(ACodigo: Integer): Boolean;
end;
implementation
{ TEditoraController }
function TEditoraController.ExcluirRegistro(ACodigo: Integer): Boolean;
begin
Result := True;
if FQuery.Active then
FQuery.Close;
FQuery.SQL.Text :=
'DELETE FROM EDITORA WHERE CODIGO = :codigo';
FQuery.ParamByName('codigo').AsInteger := ACodigo;
try
FQuery.ExecSQL();
frMain.FLogController.GravaLog('Excluiu Editora '+ ACodigo.ToString);
except
on E: Exception do
begin
Result := False;
frMain.FLogController.GravaLog('Erro ao excluir Editora '+ ACodigo.ToString);
ShowMessage('Ocorreu um erro ao excluir o registro');
end;
end;
end;
function TEditoraController.GravarRegistro(
AEditoraModel: TEditoraModel): Boolean;
var LSQL: String;
LCodigo: Integer;
LInsert: Boolean;
begin
Result := True;
LInsert := AEditoraModel.Codigo = 0;
if LInsert then
begin
LCodigo := RetornaPrimaryKey('CODIGO', 'EDITORA');
LSQL :=
'INSERT INTO EDITORA VALUES (:codigo, :nome)';
end
else
begin
LCodigo := AEditoraModel.Codigo;
LSQL :=
'UPDATE EDITORA SET NOME = :nome WHERE CODIGO = :codigo';
end;
if FQuery.Active then
FQuery.Close;
FQuery.SQL.Text := LSQL;
FQuery.ParamByName('codigo').AsInteger := LCodigo;
FQuery.ParamByName('nome').AsString := AEditoraModel.Nome;
try
FQuery.ExecSQL();
frMain.FLogController.GravaLog(
IfThen(LInsert, 'Inseriu ', 'Editou ') +
'Editora: código: ' + LCodigo.ToString +
' nome: ' + AEditoraModel.Nome);
except
on E: Exception do
begin
Result := False;
frMain.FLogController.GravaLog(
'Erro ao '+
IfThen(LInsert, 'Inserir ', 'Editar ') +
'Editora: código: ' + LCodigo.ToString +
' nome: ' + AEditoraModel.Nome);
ShowMessage('Ocorreu um erro na inclusão do editora.');
end;
end;
end;
end.
|
// Copyright (c) 2009, ConTEXT Project Ltd
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
unit uEnvOptions;
interface
{$I ConTEXT.inc}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, ComCtrls, uCommon, uSafeRegistry, SynHighlighterSQL;
type
TEnvOptions = class
private
fShiftClickClosesFileTab: boolean;
fRememberLastDir: boolean;
fDetectFileChanges: boolean;
fBackupFile: boolean;
fMinimizeIfNoFiles: boolean;
fBackupDOSFileName: boolean;
fAutoUpdateChangedFiles: boolean;
fRememberFindCfg: boolean;
fMultipleInstances: boolean;
fMinimizeToTray: boolean;
fLastDir: string;
fBackupDir: string;
fStartAction: TStartAction;
fSQLDialect: TSQLDialect;
procedure SetModified(const Value: boolean);
procedure LoadSettings;
procedure SaveSettings;
procedure SaveCurrentSettings;
public
constructor Create;
destructor Destroy; override;
property Modified: boolean write SetModified;
// global
property ShiftClickClosesFileTab: boolean read fShiftClickClosesFileTab write fShiftClickClosesFileTab;
// general
property BackupFile: boolean read fBackupFile write fBackupFile;
property BackupDir: string read fBackupDir write fBackupDir;
property BackupDOSFileName: boolean read fBackupDOSFileName write fBackupDOSFileName;
property DetectFileChanges: boolean read fDetectFileChanges write fDetectFileChanges;
property AutoUpdateChangedFiles: boolean read fAutoUpdateChangedFiles write fAutoUpdateChangedFiles;
property MinimizeIfNoFiles: boolean read fMinimizeIfNoFiles write fMinimizeIfNoFiles;
property MinimizeToTray: boolean read fMinimizeToTray write fMinimizeToTray;
property StartAction: TStartAction read fStartAction write fStartAction;
property RememberLastDir: boolean read fRememberLastDir write fRememberLastDir;
property RememberFindCfg: boolean read fRememberFindCfg write fRememberFindCfg;
property LastDir: string read fLastDir write fLastDir;
property MultipleInstances: boolean read fMultipleInstances write fMultipleInstances;
// misc
property SQLDialect: TSQLDialect read fSQLDialect write fSQLDialect;
end;
var
EnvOptions: TEnvOptions;
implementation
////////////////////////////////////////////////////////////////////////////////////////////
// TEnvOptions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
constructor TEnvOptions.Create;
begin
LoadSettings;
end;
//------------------------------------------------------------------------------------------
destructor TEnvOptions.Destroy;
begin
SaveCurrentSettings;
inherited;
end;
//------------------------------------------------------------------------------------------
procedure TEnvOptions.LoadSettings;
begin
with TSafeRegistry.Create do
try
if OpenKey(CONTEXT_REG_KEY+'Global\', TRUE) then begin
ShiftClickClosesFileTab:=ReadBool('ShiftClickClosesFileTab', TRUE);
end;
if OpenKey(CONTEXT_REG_KEY+'General\', TRUE) then begin
BackupFile:=ReadBool('Backup', TRUE);
BackupDir:=ReadString('BackupDir', ApplicationDir+'Backup');
BackupDOSFileName:=ReadBool('BackupDOSFileName', FALSE);
DetectFileChanges:=ReadBool('DetectFileChanges', TRUE);
AutoUpdateChangedFiles:=ReadBool('AutoUpdateChangedFiles', FALSE);
MinimizeIfNoFiles:=ReadBool('MinimizeIfNoFiles', FALSE);
MinimizeToTray:=ReadBool('MinimizeToTray', FALSE);
StartAction:=TStartAction(ReadInteger('StartAction', ord(saNone)));
RememberLastDir:=ReadBool('RememberLastDir', TRUE);
RememberFindCfg:=ReadBool('RememberFindCfg', FALSE);
LastDir:=ReadString('LastDir', '');
MultipleInstances:=ReadBool('MultipleInstances', FALSE);
end;
if OpenKey(CONTEXT_REG_KEY+'Misc\', TRUE) then begin
SQLDialect:=TSQLDialect(ReadInteger('SQLDialect', ord(sqlStandard)));
end;
finally
Free;
end;
end;
//------------------------------------------------------------------------------------------
procedure TEnvOptions.SaveSettings;
begin
with TSafeRegistry.Create do
try
if OpenKey(CONTEXT_REG_KEY+'Global\', TRUE) then begin
WriteBool('ShiftClickClosesFileTab', fShiftClickClosesFileTab);
end;
if OpenKey(CONTEXT_REG_KEY+'General\', TRUE) then begin
WriteBool('Backup', fBackupFile);
WriteString('BackupDir', fBackupDir);
WriteBool('BackupDOSFileName', fBackupDOSFileName);
WriteBool('DetectFileChanges', fDetectFileChanges);
WriteBool('AutoUpdateChangedFiles', fAutoUpdateChangedFiles);
WriteBool('MinimizeIfNoFiles', fMinimizeIfNoFiles);
WriteBool('MinimizeToTray', fMinimizeToTray);
WriteInteger('StartAction', ord(fStartAction));
WriteBool('RememberLastDir', fRememberLastDir);
WriteBool('RememberFindCfg', fRememberFindCfg);
WriteBool('MultipleInstances', fMultipleInstances);
end;
if OpenKey(CONTEXT_REG_KEY+'Misc\', TRUE) then begin
WriteInteger('SQLDialect', ord(fSQLDialect));
end;
finally
Free;
end;
end;
//------------------------------------------------------------------------------------------
procedure TEnvOptions.SaveCurrentSettings;
begin
with TSafeRegistry.Create do
try
if OpenKey(CONTEXT_REG_KEY+'General\', TRUE) then begin
WriteString('LastDir', fLastDir);
end;
finally
Free;
end;
end;
//------------------------------------------------------------------------------------------
procedure TEnvOptions.SetModified(const Value: boolean);
begin
if Value then
SaveSettings;
end;
//------------------------------------------------------------------------------------------
initialization
ApplicationDir:=ExtractFilePath(ParamStr(0));
EnvOptions:=TEnvOptions.Create;
finalization
FreeAndNil(EnvOptions);
end.
|
{
Implements <link TBlockSocket> class for TCP/IP protocol
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 BlockSocket;
interface
uses
{$IFDEF FPC}Sockets{$ELSE}SocketsDelphi{$ENDIF};
type
// Implements a block <extlink http://en.wikipedia.org/wiki/Internet_socket>socket</extlink> as a class
TBlockSocket = class
private
Socket : TSocket;
RemoteSin : TInetSockAddr;
public
constructor Create(S : integer = 0);
destructor Destroy; override;
procedure Bind(pPort, BackLog : word);
function Accept(Timeout : integer) : integer;
procedure Connect(Host : AnsiString; pPort : word);
procedure Purge;
procedure Close;
function RecvPacket : AnsiString;
function RecvString(Timeout : integer = 300) : AnsiString;
procedure SendString(const Data: AnsiString);
function WaitingData : cardinal;
function CanRead(Timeout: Integer): Boolean;
function Error : integer;
function GetHostAddress : AnsiString;
end;
implementation
uses
SysUtils,
{$IFDEF MSWINDOWS}
Windows, {$IFDEF FPC}WinSock2{$ELSE}WinSockDelphi{$ENDIF}
{$ELSE}
{$DEFINE IOCtlSocket:=fpIOCtl}{$DEFINE FD_Zero:=fpFD_Zero}{$DEFINE FD_Set:=fpFD_Set}{$DEFINE Select:=fpSelect}
BaseUnix, TermIO
{$ENDIF};
{
Puts the socket in listening state, used on the server side
@param Port Port to listen
@param Backlog The maximum length of the queue of pending connections
@see Error
}
procedure TBlockSocket.Bind(pPort, BackLog : word);
begin
with RemoteSin do begin
Sin_Family := AF_INET;
Sin_Addr.s_Addr := 0;
Sin_Port := htons(pPort);
end;
{$IFNDEF MSWINDOWS}fpSetSockOpt(Socket, SOL_SOCKET, SO_REUSEADDR, @RemoteSin, SizeOf(RemoteSin));{$ENDIF} // remedy socket port locking on Posix platforms
fpBind(Socket, @RemoteSin, sizeof(RemoteSin));
fpListen(Socket, BackLog);
end;
{
Attempts to establish a new TCP connection, used on the client side
@param Host IP address to the server machine
@param Port Port number to connect
@see Error
}
procedure TBlockSocket.Connect(Host : AnsiString; pPort : word);
begin
with RemoteSin do begin
Sin_Family := AF_INET;
Sin_Addr := StrToNetAddr(Host);
Sin_Port := htons(pPort);
end;
fpConnect(Socket, @RemoteSin, sizeof(RemoteSin));
end;
{
Creates a new socket stream
@param S Assigns an existing socket to the TBlockSocket
}
constructor TBlockSocket.Create(S : integer = 0);
begin
{$IFNDEF MSWINDOWS}fpSetErrNo(0);{$ENDIF}
if S = 0 then
Socket := fpSocket(AF_INET, SOCK_STREAM, 0)
else
Socket := S;
end;
// Closes the socket and frees the object
destructor TBlockSocket.Destroy;
begin
Close;
inherited;
end;
// Returns the host IP address
function TBlockSocket.GetHostAddress: AnsiString;
var
Tam : integer;
Addr: SockAddr;
begin
Tam := sizeof(Addr);
fpGetSockName(Socket, @Addr, @Tam);
Result := NetAddrToStr(Addr.Sin_Addr);
end;
// Closes the socket
procedure TBlockSocket.Close;
begin
CloseSocket(Socket);
end;
{
Attempts to accept a new TCP connection from the client and creates a new socket to handle this new connection, used on server side
@param Timeout Time in milliseconds to wait to accept a new connection
@return A new socket handler or 0 if none connection was accepted
}
function TBlockSocket.Accept(Timeout : integer) : integer;
var
Tam : integer;
begin
if CanRead(Timeout) then begin
sleep(0);
Tam := sizeof(RemoteSin);
Result := fpAccept(Socket, @RemoteSin, @Tam)
end
else
Result := 0;
end;
// Returns number of bytes waiting to read
function TBlockSocket.WaitingData : cardinal;
var
Tam : dword;
begin
sleep(1);
if IOCtlSocket(Socket, FIONREAD, @Tam) <> 0 then
Result := 0
else
Result := Tam;
end;
{
Tests if data are available for reading within the timeout
@param Timeout Max time to wait until returns
@return True if data are available, false otherwise
}
function TBlockSocket.CanRead(Timeout : Integer) : Boolean;
var
FDS: TFDSet;
TimeV: TTimeVal;
begin
FD_Zero(FDS);
FD_Set(Socket, FDS);
TimeV.tv_usec := (Timeout mod 1000) * 1000;
TimeV.tv_sec := Timeout div 1000;
Result := Select(Socket + 1, @FDS, nil, nil, @TimeV) > 0;
end;
// Cleans the socket input stream
procedure TBlockSocket.Purge;
var
Tam : cardinal;
Buffer : pointer;
begin
Tam := WaitingData;
if Tam = 0 then exit;
getmem(Buffer, Tam);
fpRecv(Socket, Buffer, Tam, 0);
freemem(Buffer, Tam);
end;
// Receives the next available tcp packet
function TBlockSocket.RecvPacket : AnsiString;
var
Tam : integer;
begin
Tam := WaitingData;
SetLength(Result, Tam);
{$IFNDEF MSWINDOWS}fpSetErrNo(0);{$ENDIF}
fpRecv(Socket, @Result[1], Tam, 0);
Sleep(1); // required on some environments to prevent streaming truncation
end;
{
Returns the socket input stream as a string
@param Timeout Max time to wait until some data is available for reading. Default is 300 miliseconds
@see Error
}
function TBlockSocket.RecvString(Timeout : integer = 300) : AnsiString;
begin
Result := '';
if CanRead(Timeout) then
while WaitingData <> 0 do
Result := Result + RecvPacket
end;
{
Sends a string by the socket
@param Data String to send
@see Error
}
procedure TBlockSocket.SendString(const Data : AnsiString);
begin
fpSend(Socket, @Data[1], length(Data), 0);
end;
{
Use Error method to test if others TBlockSocket methods succeded
@return 0 if success or socket error code otherwise
}
function TBlockSocket.Error : integer;
begin
Result := SocketError
end;
end.
|
unit uParentSelect;
{
Seleção de dados automatizada.
Cada Panel do pnlMainSelect corresponde a uma
determinada seleção. Cada um deles possue Tag
igual a posição do item selecionado no
set TSelect. Retorna property SelList que e um
StringList como resultado da seleção e Boolean se
usuário deu OK
}
interface
uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, ExtCtrls, Dialogs, PaideTodosGeral;
const MIN_HEIGHT = 135;
DIF_HEIGHT = 30;
type
TParentSelect = class(TFrmParentAll)
pnlParent: TPanel;
pnlParent3: TPanel;
pnlParent4: TPanel;
pnlParent2: TPanel;
btClose: TButton;
Button1: TButton;
pnlMainSelect: TPanel;
procedure BtnOKClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
LocalSel : TStringList;
FRelSpecial : Boolean;
FAuxValue : String;
procedure SetAllInvisible;
protected
procedure CheckValues; virtual;
public
{ Public declarations }
IndexSel : TStringList;
function Select(Titulo : String;
aSelect : array of String) : Boolean;
property AuxValue : String read FAuxValue write FAuxValue;
property RelSpecial : Boolean read FRelSpecial write FRelSpecial;
end;
var
ParentSelect: TParentSelect;
implementation
{$R *.DFM}
uses xBase, DateBox, SuperCombo;
function TParentSelect.Select(Titulo : String;
aSelect : array of String) : Boolean;
var
i, j : byte;
ContHeight : integer;
begin
{ seta o caption }
Caption := 'Selecting - ' + Titulo;
{ Sera variáveis }
ContHeight := 0;
LocalSel.Clear;
{ Seta todos panels para Visible False }
SetAllInvisible;
{ Seleciona os tipos de seleção }
for i := Low(aSelect) to High(aSelect) do
begin
LocalSel.Add(aSelect[i]);
with TPanel(FindComponent(aSelect[i])) do
begin
// Cuida da ordem que que aparecem na tela
Inc(ContHeight, Height);
Top := ContHeight - Height;
Visible := True;
TabOrder := i;
{ se for primeiro seta o foco inicial }
if i = Low(aSelect) then
for j := 0 to (ControlCount - 1) do
if (Controls[j] is TWinControl) and
(TWinControl(Controls[j]).TabOrder = 0) then
begin
ActiveControl := TWinControl(Controls[j]);
Break;
end;
end;
end;
{ Seta a altura fo form }
Height := Max(ContHeight + DIF_HEIGHT, MIN_HEIGHT);
Result := (ShowModal = mrOK);
end;
procedure TParentSelect.SetAllInvisible;
var
i : byte;
begin
with pnlMainSelect do
for i := 0 to (ControlCount - 1) do
if (Controls[i] is TPanel) then
TPanel(Controls[i]).Visible := False;
end;
procedure TParentSelect.BtnOKClick(Sender: TObject);
var
i, j : byte;
begin
if (MessageDlg('Confirma seleção',
mtConfirmation, mbOKCancel, 0) = mrCancel) then
Exit;
{ Retorna em IndexSel o texto da seleção }
IndexSel.Clear;
with LocalSel do
for i := 0 to (Count - 1) do
with TPanel(FindComponent(Strings[i])) do
for j := 0 to (ControlCount - 1) do
begin
if (Controls[j] is TDateBox) then
TDateBox(Controls[j]).Validate;
if TWinControl(Controls[j]).TabOrder = 0 then
if (Controls[j] is TCustomEdit) then
IndexSel.Add(TCustomEdit(Controls[j]).Text)
else if (Controls[j] is TRadioGroup) then
IndexSel.Add(IntToStr(TRadioGroup(Controls[j]).ItemIndex))
else if (Controls[j] is TSuperCombo) then
IndexSel.Add(TSuperCombo(Controls[j]).LookUpValue);
end;
CheckValues;
ModalResult := mrOk;
end;
procedure TParentSelect.FormCreate(Sender: TObject);
begin
IndexSel := TStringList.Create;
LocalSel := TStringList.Create;
FRelSpecial := False;
end;
procedure TParentSelect.CheckValues;
begin
{ método para ser herdado }
end;
end.
|
{ *******************************************************************************
Title: T2TiPDV
Description: Gera Parcelas para o Contas a Receber.
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 UParcelamento;
{$mode objfpc}{$H+}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Buttons, Grids, DBGrids, DB, BufDataset,
ACBrBase, ACBrEnterTab, RXSpin, CurrEdit, dbdateedit, tooledit,
ZAbstractRODataset, ZAbstractDataset, ZDataset, UBase;
type
{ TFParcelamento }
TFParcelamento = class(TFBase)
ACBrEnterTab1: TACBrEnterTab;
botaoConfirma: TBitBtn;
CDSParcela: TBufDataset;
Image1: TImage;
GroupBox1: TGroupBox;
editNome: TEdit;
Label2: TLabel;
Label3: TLabel;
editCPF: TEdit;
GroupBox2: TGroupBox;
Label4: TLabel;
Label7: TLabel;
Label8: TLabel;
Label5: TLabel;
Label6: TLabel;
DBGrid1: TDBGrid;
qtdParcelas: TRxSpinEdit;
editValorVenda: TCurrencyEdit;
editValorRecebido: TCurrencyEdit;
editValorParcelar: TCurrencyEdit;
Panel1: TPanel;
DSParcela: TDataSource;
DBDateEdit1: TDBDateEdit;
botaoLocalizaCliente: TBitBtn;
editDesconto: TCurrencyEdit;
lblDesconto: TLabel;
botaoCancela: TSpeedButton;
editVencimento: TRxDateEdit;
procedure DBGrid1ColExit(Sender: TObject);
procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
procedure DBGrid1KeyPress(Sender: TObject; var Key: Char);
procedure editVencimentoChange(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure botaoConfirmaClick(Sender: TObject);
procedure DBGrid1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure botaoLocalizaClienteClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure CalculaParcelas;
procedure qtdParcelasChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FParcelamento: TFParcelamento;
confirmou: Boolean;
implementation
uses UCaixa, ContasParcelasVO, ContasPagarReceberVO,
Biblioteca, UIdentificaCliente, VendaController;
{$R *.lfm}
procedure TFParcelamento.botaoConfirmaClick(Sender: TObject);
var
Total, ValoraParcelar: Currency;
ParcelaCabecalho: TContasPagarReceberVO;
ParcelaDetalhe: TContasParcelasVO;
// ListaParcelaDetalhe: ParcelaController.TListaContasParcelasVO;
Identificacao: String;
begin
(*
if VendaCabecalho.IdCliente < 1 then
begin
Application.MessageBox('Escolha um cliente para Parcelar!', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION);
Abort;
end;
Identificacao := 'E' + IntToStr(Configuracao.IdEmpresa) + 'X' + IntToStr(Configuracao.IdCaixa) + 'V' + DevolveInteiro(FCaixa.edtNVenda.Caption) + 'C' + DevolveInteiro(FCaixa.edtCOO.Caption);
Total := 0;
ValoraParcelar := StrToFloat(editValorParcelar.Text);
CDSParcela.DisableControls;
CDSParcela.First;
while not CDSParcela.Eof do
begin
Total := Total + CDSParcela.FieldByName('Valor').AsFloat;
CDSParcela.Next;
end;
CDSParcela.EnableControls;
if (Total = ValoraParcelar) then
begin
try
ParcelaCabecalho := TContasPagarReceberVO.Create;
ParcelaCabecalho.IdEcfVendaCabecalho := UCaixa.VendaCabecalho.Id;
ParcelaCabecalho.IdPlanoContas := 1;
ParcelaCabecalho.IdTipoDocumento := 1;
ParcelaCabecalho.IdPessoa := UCaixa.VendaCabecalho.IdCliente;
ParcelaCabecalho.Tipo := 'R';
ParcelaCabecalho.NumeroDocumento := Identificacao + 'Q' + qtdParcelas.Text;
ParcelaCabecalho.Valor := Total;
ParcelaCabecalho.DataLancamento := UCaixa.VendaCabecalho.DataVenda;
ParcelaCabecalho.PrimeiroVencimento := DataParaTexto(editVencimento.Date);
ParcelaCabecalho.NaturezaLancamento := 'S';
ParcelaCabecalho.QuantidadeParcela := qtdParcelas.AsInteger;
ParcelaCabecalho.IdEcfVendaCabecalho := UCaixa.VendaCabecalho.Id;
ParcelaCabecalho.IdPessoa := UCaixa.VendaCabecalho.IdCliente;
ParcelaCabecalho.DataLancamento := UCaixa.VendaCabecalho.DataVenda;
ParcelaCabecalho.Tipo := 'R';
ParcelaCabecalho.Valor := Total;
ParcelaCabecalho.NaturezaLancamento := 'S';
ParcelaCabecalho := TParcelaController.InserirCabecalho(ParcelaCabecalho);
ListaParcelaDetalhe := ParcelaController.TListaContasParcelasVO.Create;
CDSParcela.DisableControls;
CDSParcela.First;
while not CDSParcela.Eof do
begin
ParcelaDetalhe := TContasParcelasVO.Create;
ParcelaDetalhe.IdContasPagarReceber := ParcelaCabecalho.Id;
ParcelaDetalhe.DataEmissao := UCaixa.VendaCabecalho.DataVenda;
ParcelaDetalhe.DataVencimento := DataParaTexto(CDSParcela.FieldByName('Vencimento').AsDateTime);
ParcelaDetalhe.NumeroParcela := StrToInt(CDSParcela.FieldByName('Parcela').Text);
ParcelaDetalhe.Valor := StrToFloat(CDSParcela.FieldByName('Valor').Text);
ParcelaDetalhe.TaxaJuros := 0;
ParcelaDetalhe.TaxaMulta := 0;
ParcelaDetalhe.TaxaDesconto := 0;
ParcelaDetalhe.ValorJuros := 0;
ParcelaDetalhe.ValorMulta := 0;
ParcelaDetalhe.ValorDesconto := 0;
ParcelaDetalhe.TotalParcela := StrToFloat(CDSParcela.FieldByName('Valor').Text);
ParcelaDetalhe.Historico := '';
ParcelaDetalhe.Situacao := 'A';
ListaParcelaDetalhe.Add(ParcelaDetalhe);
CDSParcela.Next;
end;
CDSParcela.EnableControls;
TParcelaController.InserirDetalhe(ListaParcelaDetalhe);
confirmou := True;
finally
ParcelaCabecalho.Free;
ListaParcelaDetalhe.Free;
end;
Close;
end
else
Application.MessageBox('A soma das Parcelas difere do valor a parcelar!', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION);
*)
end;
procedure TFParcelamento.CalculaParcelas;
var
x, QtdPar: Integer;
Vencimento: TDateTime;
ValorTotal, ValorParcela, Resto: Extended;
begin
while not CDSParcela.eof do
CDSParcela.Delete;
QtdPar := qtdParcelas.AsInteger;
ValorTotal := editValorParcelar.Value;
ValorParcela := ValorTotal / QtdPar;// Round(ValorTotal / QtdPar);
Resto := (ValorTotal - (ValorParcela * QtdPar));
Vencimento := editVencimento.Date;
for x := 1 To QtdPar do
begin
CDSParcela.Append;
CDSParcela.FieldByName('Parcela').AsInteger := x;
CDSParcela.FieldByName('Vencimento').AsDateTime := Vencimento;
if x = 1 then
CDSParcela.FieldByName('Valor').AsFloat := ValorParcela + Resto
else
CDSParcela.FieldByName('Valor').AsFloat := ValorParcela;
CDSParcela.Post;
Vencimento := IncMonth(Vencimento);
end;
CDSParcela.Edit;
end;
procedure TFParcelamento.FormActivate(Sender: TObject);
begin
Color := StringToColor(Sessao.Configuracao.CorJanelasInternas);
editVencimento.Date := Date + 30;
qtdParcelas.SetFocus;
end;
procedure TFParcelamento.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
if confirmou then
ModalResult := MROK;
end;
procedure TFParcelamento.FormCreate(Sender: TObject);
begin
//configura Dataset
CDSParcela.Close;
CDSParcela.FieldDefs.Clear;
CDSParcela.FieldDefs.add('PARCELA', ftString, 20);
CDSParcela.FieldDefs.add('VENCIMENTO', ftDate);
CDSParcela.FieldDefs.add('VALOR', ftFloat);
CDSParcela.CreateDataset;
CDSParcela.Active := True;
TFloatField(CDSParcela.FieldByName('VALOR')).displayFormat:='#,###,###,##0.00';
confirmou := False;
qtdParcelas.MaxValue := Sessao.Configuracao.QuantidadeMaximaParcela;
end;
procedure TFParcelamento.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = 27 then
botaoCancela.Click;
if (Key = 112) then
botaoLocalizaCliente.Click;
end;
procedure TFParcelamento.DBGrid1ColExit(Sender: TObject);
begin
if DBGrid1.SelectedField.FieldName = 'Vencimento' then
DBDateEdit1.Visible := False;
end;
procedure TFParcelamento.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
if (gdFocused in State) then
begin
if (Column.Field.FieldName = 'Vencimento') then
begin
with DBDateEdit1 do
begin
Left := Rect.Left + DBGrid1.Left + 1;
Top := Rect.Top + DBGrid1.Top + 1;
Width := Rect.Right - Rect.Left + 2;
Width := Rect.Right - Rect.Left + 2;
Height := Rect.Bottom - Rect.Top + 2;
Visible := True;
end;
end;
end;
end;
procedure TFParcelamento.DBGrid1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
var
qt, Total, valorant, prest, Resto: Real;
Bookmark: TBookmark;
begin
if (Key = vk_return) then
begin
Total := 0;
prest := 0;
qt := 0;
valorant := 0;
CDSParcela.Post;
CDSParcela.DisableControls;
// quantas parcelas ainda faltam
Bookmark := CDSParcela.GetBookmark;
while not CDSParcela.Eof do
begin
qt := qt + 1;
CDSParcela.Next;
end;
qt := qt - 1;
CDSParcela.GotoBookmark(Bookmark);
// pega o saldo das parcelas anteriores
Bookmark := CDSParcela.GetBookmark;
while not CDSParcela.bof do
begin
valorant := valorant + CDSParcela.Fieldbyname('Valor').AsFloat;
CDSParcela.prior;
end;
CDSParcela.GotoBookmark(Bookmark);
Bookmark := CDSParcela.GetBookmark;
Total := editValorParcelar.Value - valorant;
If (Total >= 0) then
begin
if (Total > 0) and (qt > 0) then
begin
prest := Round(Total / qt);
Resto := (Total - (prest * qt));
CDSParcela.Edit;
CDSParcela.Fieldbyname('VALOR').AsFloat := CDSParcela.Fieldbyname('VALOR').AsFloat + Resto;
CDSParcela.Post;
end;
CDSParcela.Next;
while not CDSParcela.Eof do
begin
CDSParcela.Edit;
CDSParcela.Fieldbyname('VALOR').AsFloat := prest;
CDSParcela.Post;
CDSParcela.Next;
end;
CDSParcela.GotoBookmark(Bookmark);
end
else
begin
Application.MessageBox('O Valor Informado é Inválido!', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION);
end;
CDSParcela.EnableControls;
CDSParcela.Edit;
end;
end;
procedure TFParcelamento.DBGrid1KeyPress(Sender: TObject; var Key: Char);
begin
if (Key = Chr(9)) then
Exit;
if (DBGrid1.SelectedField.FieldName = 'Vencimento') then
begin
DBDateEdit1.SetFocus;
SendMessage(DBDateEdit1.Handle, WM_Char, Word(Key), 0);
end
end;
procedure TFParcelamento.editVencimentoChange(Sender: TObject);
begin
CalculaParcelas;
end;
procedure TFParcelamento.qtdParcelasChange(Sender: TObject);
begin
CalculaParcelas;
end;
procedure TFParcelamento.botaoLocalizaClienteClick(Sender: TObject);
begin
(*
Application.CreateForm(TFIdentificaCliente, FIdentificaCliente);
FIdentificaCliente.ShowModal;
if trim(Cliente.Nome) <> '' then
begin
editNome.Text := Cliente.Nome;
editCPF.Text := Cliente.CPFOuCNPJ;
TVendaController.AlteraClienteNaVenda(VendaCabecalho.Id, Cliente.Id, Cliente.CPFOuCNPJ, Cliente.Nome);
VendaCabecalho.IdCliente := Cliente.Id;
VendaCabecalho.NomeCliente := Cliente.Nome;
VendaCabecalho.CPFouCNPJCliente := Cliente.CPFOuCNPJ;
end;
*)
end;
end.
|
unit UnitCryptingImagesThread;
interface
uses
Winapi.Windows,
Winapi.ActiveX,
System.SysUtils,
System.Classes,
Vcl.Forms,
Data.DB,
Dmitry.Utils.Files,
GraphicCrypt,
UnitPropeccedFilesSupport,
UnitCrypting,
UnitDBDeclare,
uGOM,
uDBForm,
uDBConnection,
uDBContext,
uLogger,
uDBThread,
uConstants,
uErrors,
uGUIDUtils,
uShellIntegration,
uInterfaces,
uFormInterfaces,
uCollectionEvents,
uSessionPasswords;
type
TCryptingImagesThread = class(TDBThread)
private
{ Private declarations }
FContext: IDBContext;
FOptions: TCryptImageThreadOptions;
BoolParam: Boolean;
IntParam: Integer;
StrParam: string;
Count: Integer;
ProgressWindow: TForm;
Table: TDataSet;
FPassword: string;
FField: TField;
FE: Boolean;
Position: Integer;
CryptResult: Integer;
FSender: TDBForm;
FLastProgressTime: Cardinal;
procedure ShowError(ErrorText: string);
procedure ShowErrorSync;
procedure OnFileProgress(FileName: string; BytesTotal, BytesDone: Int64; var BreakOperation: Boolean);
procedure NotifyFileUpdated(FileName: string);
public
constructor Create(Sender: TDBForm; Context: IDBContext; Options: TCryptImageThreadOptions);
protected
procedure Execute; override;
procedure InitializeProgress;
procedure DestroyProgress;
procedure IfBreakOperation;
procedure SetProgressPosition(Position : integer);
procedure SetProgressPositionSynch;
procedure DoDBkernelEvent;
procedure DoDBkernelEventRefreshList;
procedure RemoveFileFromUpdatingList;
procedure GetPassword;
procedure FindPasswordToFile;
procedure FindPasswordToBlob;
procedure GetPasswordFromUserFile;
procedure GetPasswordFromUserBlob;
end;
implementation
uses ProgressActionUnit;
{ TCryptingImagesThread }
constructor TCryptingImagesThread.Create(Sender: TDBForm; Context: IDBContext; Options: TCryptImageThreadOptions);
var
I: Integer;
begin
inherited Create(Sender, False);
FSender := Sender;
FContext := Context;
Table := nil;
FLastProgressTime := 0;
FOptions := Options;
for I := 0 to Length(Options.Files) - 1 do
if Options.Selected[I] then
ProcessedFilesCollection.AddFile(Options.Files[I]);
DoDBKernelEventRefreshList;
end;
procedure TCryptingImagesThread.DestroyProgress;
begin
(ProgressWindow as TProgressActionForm).WindowCanClose := True;
ProgressWindow.Release;
end;
procedure TCryptingImagesThread.DoDBkernelEvent;
var
EventInfo: TEventValues;
begin
if FOptions.Action = ACTION_ENCRYPT_IMAGES then
EventInfo.IsEncrypted := CryptResult = CRYPT_RESULT_OK
else
EventInfo.IsEncrypted := CryptResult <> CRYPT_RESULT_OK;
if IntParam <> 0 then
CollectionEvents.DoIDEvent(FSender, IntParam, [EventID_Param_Crypt], EventInfo)
else
begin
EventInfo.NewName := StrParam;
CollectionEvents.DoIDEvent(FSender, IntParam, [EventID_Param_Crypt, EventID_Param_Name], EventInfo)
end;
end;
procedure TCryptingImagesThread.DoDBkernelEventRefreshList;
var
EventInfo: TEventValues;
begin
CollectionEvents.DoIDEvent(FSender, 0, [EventID_Repaint_ImageList], EventInfo);
end;
procedure TCryptingImagesThread.Execute;
var
I, J: Integer;
C: Integer;
begin
inherited;
FreeOnTerminate := True;
try
CoInitializeEx(nil, COM_MODE);
try
Count := 0;
for I := 0 to Length(FOptions.IDs) - 1 do
if FOptions.Selected[I] then
Inc(Count);
Synchronize(InitializeProgress);
try
C := 0;
for I := 0 to Length(FOptions.IDs) - 1 do
begin
StrParam := FOptions.Files[I];
IntParam := FOptions.IDs[I];
Position := I;
if FOptions.Selected[I] then
begin
Synchronize(IfBreakOperation);
if BoolParam then
begin
for J := I to Length(FOptions.IDs) - 1 do
begin
StrParam := FOptions.Files[J];
Synchronize(RemoveFileFromUpdatingList);
end;
Synchronize(DoDBkernelEventRefreshList);
Continue;
end;
Inc(C);
SetProgressPosition(C);
if FOptions.Action = ACTION_ENCRYPT_IMAGES then
begin
// Encrypting images
try
CryptResult := EncryptImageByFileName(FContext, FSender, FOptions.Files[I], FOptions.IDs[I], FOptions.Password,
FOptions.EncryptOptions, False, OnFileProgress);
if (CryptResult <> CRYPT_RESULT_OK) and (CryptResult <> CRYPT_RESULT_ALREADY_CRYPT) then
ShowError(DBErrorToString(CryptResult));
except
on e: Exception do
EventLog(e);
end;
end else
begin
// Decrypting images
FE := FileExistsSafe(FOptions.Files[I]);
// GetPassword
StrParam := FOptions.Files[I];
IntParam := FOptions.IDs[I];
if ValidCryptGraphicFile(FOptions.Files[I]) then
begin
GetPassword;
// Decrypting images
CryptResult := ResetPasswordImageByFileName(FContext, Self, FOptions.Files[I], FOptions.IDs[I], FPassword, OnFileProgress);
if (CryptResult <> CRYPT_RESULT_OK) then
ShowError(DBErrorToString(CryptResult));
end;
end;
StrParam := FOptions.Files[I];
IntParam := FOptions.IDs[I];
Synchronize(RemoveFileFromUpdatingList);
Synchronize(DoDBkernelEventRefreshList);
Synchronize(DoDBkernelEvent);
Synchronize(
procedure
begin
NotifyFileUpdated(FOptions.Files[I]);
end
);
end;
end;
finally
Synchronize(DestroyProgress);
end;
FreeDS(Table);
finally
CoUninitialize;
end;
except
on e: Exception do
EventLog(e);
end;
end;
procedure TCryptingImagesThread.GetPasswordFromUserFile;
begin
FPassword := RequestPasswordForm.ForImage(StrParam);
end;
procedure TCryptingImagesThread.GetPasswordFromUserBlob;
begin
FPassword := RequestPasswordForm.ForBlob(FField, StrParam);
end;
procedure TCryptingImagesThread.FindPasswordToFile;
begin
FPassword := SessionPasswords.FindForFile(StrParam)
end;
procedure TCryptingImagesThread.FindPasswordToBlob;
begin
FPassword := SessionPasswords.FindForBlobStream(FField);
end;
procedure TCryptingImagesThread.GetPassword;
begin
if FE then
Synchronize(FindPasswordToFile)
else
begin
if Table = nil then
begin
Table := GetTable(FContext.CollectionFileName);
Table.Open;
end;
Table.Locate('ID', IntParam, [LoPartialKey]);
FField := Table.FieldByName('thum');
Synchronize(FindPasswordToBlob);
end;
if FPassword = '' then
begin
begin
if not FE then
begin
if IntParam = 0 then
begin
Exit;
end;
Table.Locate('ID', IntParam, [LoPartialKey]);
Table.Edit;
FField := Table.FieldByName('thum');
Synchronize(FindPasswordToBlob);
Table.Post;
end
else
begin
Synchronize(GetPasswordFromUserFile);
end;
end;
end;
end;
procedure TCryptingImagesThread.IfBreakOperation;
begin
BoolParam := True;
if not GOM.IsObj(ProgressWindow) then
Exit;
BoolParam := (ProgressWindow as TProgressActionForm).Closed;
end;
procedure TCryptingImagesThread.InitializeProgress;
begin
ProgressWindow := GetProgressWindow(True);
with ProgressWindow as TProgressActionForm do
begin
CanClosedByUser := True;
OneOperation := False;
OperationCount := Count;
OperationPosition := 1;
MaxPosCurrentOperation := 0;
XPosition := 0;
Show;
end;
end;
procedure TCryptingImagesThread.NotifyFileUpdated(FileName: string);
var
I: Integer;
Form: TForm;
Watcher: IDirectoryWatcher;
Info: TInfoCallBackDirectoryChangedArray;
begin
SetLength(Info, 1);
Info[0].Action := FILE_ACTION_MODIFIED;
Info[0].OldFileName := FileName;
Info[0].NewFileName := FileName;
for I := 0 to TFormCollection.Instance.Count - 1 do
begin
Form := TFormCollection.Instance[I];
if Form.GetInterface(IDirectoryWatcher, Watcher) then
Watcher.DirectoryChanged(Self, SystemDirectoryWatchNotification, Info, dwtBoth);
end;
end;
procedure TCryptingImagesThread.OnFileProgress(FileName: string; BytesTotal,
BytesDone: Int64; var BreakOperation: Boolean);
var
B: Boolean;
begin
B := BreakOperation;
if GetTickCount - FLastProgressTime > 100 then
begin
FLastProgressTime := GetTickCount;
Synchronize(
procedure
begin
if not GOM.IsObj(ProgressWindow) then
Exit;
(ProgressWindow as TProgressActionForm).MaxPosCurrentOperation := BytesTotal;
(ProgressWindow as TProgressActionForm).XPosition := BytesDone;
if (ProgressWindow as TProgressActionForm).Closed then
B := True;
end
);
end;
BreakOperation := B;
end;
procedure TCryptingImagesThread.RemoveFileFromUpdatingList;
begin
ProcessedFilesCollection.RemoveFile(StrParam);
end;
procedure TCryptingImagesThread.SetProgressPosition(Position: Integer);
begin
IntParam := Position;
Synchronize(SetProgressPositionSynch);
end;
procedure TCryptingImagesThread.SetProgressPositionSynch;
begin
if not GOM.IsObj(ProgressWindow) then
Exit;
(ProgressWindow as TProgressActionForm).OperationPosition := IntParam;
end;
procedure TCryptingImagesThread.ShowError(ErrorText: string);
begin
StrParam := ErrorText;
SynchronizeEx(ShowErrorSync);
end;
procedure TCryptingImagesThread.ShowErrorSync;
begin
MessageBoxDB(0, StrParam, L('Error'), TD_BUTTON_OK, TD_ICON_ERROR);
end;
end.
|
unit DebugThread;
interface
uses
Classes, StdCtrls,
IdBaseComponent, IdComponent, IdTCPConnection, IdSimpleServer,
IdUDPBase, IdUDPServer, IdTrivialFTPServer;
type
TServerType = TIdTrivialFTPServer;
TDebugThread = class(TThread)
private
{ Private declarations }
FMsg: string;
FServer: TServerType;
protected
procedure SetServer(const Value: TServerType);
protected
procedure SMsg;
procedure Execute; override;
procedure Msg(const inMsg: string);
procedure ServerStatus(ASender: TObject; const AStatus: TIdStatus;
const AStatusText: String);
public
Memo: TMemo;
procedure Listen;
property Server: TServerType read FServer write SetServer;
end;
implementation
{ Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure DebugThread.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end; }
{ TDebugThread }
procedure TDebugThread.Execute;
begin
{ Place thread code here }
while not Terminated do
begin
Listen;
Suspend;
end;
end;
procedure TDebugThread.SMsg;
begin
Memo.Lines.Add(FMsg);
end;
procedure TDebugThread.Msg(const inMsg: string);
begin
FMsg := inMsg;
Synchronize(SMsg);
end;
procedure TDebugThread.SetServer(const Value: TServerType);
begin
FServer := Value;
FServer.OnStatus := ServerStatus;
end;
procedure TDebugThread.ServerStatus(ASender: TObject; const AStatus: TIdStatus;
const AStatusText: String);
begin
Msg(AStatusText);
end;
procedure TDebugThread.Listen;
begin
Msg('Listening...');
//Server.Listen;
end;
end.
|
unit uFormForObject;
interface
uses
Classes;
type
TFormForObjectItem = class(TCollectionItem)
private
FObjectID: integer;
FFormClass: TClass;
public
property ObjectID: integer read FObjectID;
property FormClass: TClass read FFormClass;
end;
TFormForObjectCollection = class(TCollection)
private
function GetItems(Index: integer): TFormForObjectItem;
public
property Items[Index: integer]: TFormForObjectItem read GetItems; default;
function Add(AObjectID: integer; AFormClass: TClass): TFormForObjectItem;
function GetFormClass(ObjectID: integer): TClass;
end;
var
FormForObject: TFormForObjectCollection;
implementation
uses uBASE_BookForm, uFrmOKOF, uFrmObjectReestr, uFrmOrganization,
uFrameStreets, uFrmContract, uFrmStreet, uFrmPayment, ufrmContract2,
ufrmPayment2, ufrmContract3, ufrmPayment3, uFrmHistory;
{ TFormForObjectCollection }
function TFormForObjectCollection.Add(AObjectID: integer;
AFormClass: TClass): TFormForObjectItem;
begin
with TFormForObjectItem(inherited Add) do begin
FObjectID:=AObjectID;
FFormClass:=AFormClass;
end;
end;
function TFormForObjectCollection.GetFormClass(ObjectID: integer): TClass;
var
i: integer;
begin
result:=nil;
for i:=0 to Count-1 do
if Items[i].ObjectID=ObjectID then begin
result:=Items[i].FormClass;
exit;
end;
result:=TBASE_BookForm;
end;
function TFormForObjectCollection.GetItems(
Index: integer): TFormForObjectItem;
begin
result:=TFormForObjectItem(inherited Items[Index]);
end;
initialization
FormForObject:=TFormForObjectCollection.Create(TFormForObjectItem);
//ОКОФ
FormForObject.Add(9, TfrmOKOF);
//Реестр объектов
FormForObject.Add(157, TFrmObjectReestr);
//29-07-2009
//Учетную единицу открываем через реестр объектов
FormForObject.Add(163, TFrmObjectReestr);
//^^^29-07-2009
//Субъекты учета
FormForObject.Add(1, TFrmOrganization);
//Классификатор улиц
FormForObject.Add(52, TFrmStreet);
//Договора УРМИ
FormForObject.Add(205, TFrmContract);
//Платежы УРМИ
FormForObject.Add(228, TFrmPayment);
//Договора УМНФ
FormForObject.Add(409, TFrmContract2);
//Платежы УМНФ
FormForObject.Add(413, TFrmPayment2);
//Договора УЗР
FormForObject.Add(410, TFrmContract3);
//Платежы УЗР
FormForObject.Add(414, TFrmPayment3);
//История изменений записи
FormForObject.Add(434, TFrmHistory);
finalization
FormForObject.Free;
end.
|
(*
* Copyright (c) 2011-2012, Ciobanu Alexandru
* All rights reserved.
*)
unit Myloo.Comp.Coll.Dynamic;
interface
{$IF CompilerVersion > 21}
uses
SysUtils,
Generics.Collections,
Rtti,
TypInfo;
type
/// <summary>Alias for the Rtti <c>TValue</c> type. The compiler seems to have a hard
/// time differentiating <c>TValue</c> from the generic <c>TValue</c> type argument.</summary>
TAny = TValue;
/// <summary>An alias to the <v>Variant</c> type. Its main purpose is to serve as a reminder that
/// it contains a part of an object. It is to be considered a "dynamic record".</summary>
TView = Variant;
/// <summary>A special purpose record type that exposes a number of methods that generate
/// selector methods for fields and properties of a class or record type.</summary>
Member = record
private class var
FViewVariantType: Word;
private type
{$REGION 'Internal Types'}
TViewPair = TPair<string, TValue>;
TViewArray = TArray<TViewPair>;
TSelector<T, K> = class(TInterfacedObject, TFunc<T, K>, TFunc<T, TValue>)
private
FContext: TRttiContext;
FType: TRttiType;
FMember: TRttiMember;
protected
function TFunc<T, K>.Invoke = GenericInvoke;
function TFunc<T, TValue>.Invoke = TValueInvoke;
public
function TValueInvoke(AFrom: T): TValue; virtual; abstract;
function GenericInvoke(AFrom: T): K;
end;
TRecordFieldSelector<K> = class(TSelector<Pointer, K>)
public
function TValueInvoke(AFrom: Pointer): TValue; override;
end;
TClassFieldSelector<K> = class(TSelector<TObject, K>)
public
function TValueInvoke(AFrom: TObject): TValue; override;
end;
TClassPropertySelector<K> = class(TSelector<TObject, K>)
public
function TValueInvoke(AFrom: TObject): TValue; override;
end;
TViewSelector<T> = class(TInterfacedObject, TFunc<T, TView>)
private
FNames: TArray<string>;
FFuncs: TArray<TFunc<T, TValue>>;
public
function Invoke(AFrom: T): TView;
end;
{$ENDREGION}
public
/// <summary>Generates a selector for a given member name.</summary>
/// <param name="AName">The field or property name to select from <c>T</c>.</param>
/// <returns>A selector function that retrieves the field/property from a class or record.
/// <c>nil</c> is returned in case of error.</returns>
class function Name<T, K>(const AName: string): TFunc<T, K>; overload; static;
/// <summary>Generates a selector for a given member name.</summary>
/// <param name="AName">The field or property name to select from <c>T</c>.</param>
/// <returns>A selector function that retrieves the field/property from a class or record. The selected value is a <c>TValue</c> type.
/// <c>nil</c> is returned in case of error.</returns>
class function Name<T>(const AName: string): TFunc<T, TValue>; overload; static;
/// <summary>Generates a selector for the given member names.</summary>
/// <param name="ANames">The field or property names to select from <c>T</c>.</param>
/// <returns>A selector function that retrieves the fields/properties from a class or record. The selected value is a <c>TView</c> type.
/// <c>nil</c> is returned in case of error.</returns>
class function Name<T>(const ANames: array of string): TFunc<T, TView>; overload; static;
end;
implementation
uses
Variants;
type
{ Mapping the TSVDictionary into TVarData structure }
TViewDictionaryVarData = packed record
{ Var type; will be assigned at run time }
VType: TVarType;
{ Reserved stuff }
Reserved1, Reserved2, Reserved3: Word;
{ A reference to the enclosed dictionary }
FArray: Member.TViewArray;
{ Reserved stuff }
Reserved4: LongWord;
{$IFDEF CPUX64}
Reserved4_1: LongWord;
{$ENDIF}
end;
{ Manager for our variant type }
TViewDictionaryVariantType = class(TInvokeableVariantType)
public
procedure Clear(var V: TVarData); override;
procedure Copy(var Dest: TVarData; const Source: TVarData; const Indirect: Boolean); override;
function GetProperty(var Dest: TVarData; const V: TVarData; const Name: string): Boolean; override;
end;
{ TViewDictionaryVariantType }
procedure TViewDictionaryVariantType.Clear(var V: TVarData);
begin
{ Clear the variant type }
V.VType := varEmpty;
{ And dispose the value }
TViewDictionaryVarData(V).FArray := nil;
end;
procedure TViewDictionaryVariantType.Copy(var Dest: TVarData;
const Source: TVarData; const Indirect: Boolean);
begin
if Indirect and VarDataIsByRef(Source) then
VarDataCopyNoInd(Dest, Source)
else
begin
with TViewDictionaryVarData(Dest) do
begin
{ Copy the variant type }
VType := VarType;
{ Copy the reference }
FArray := TViewDictionaryVarData(Source).FArray;
end;
end;
end;
function TViewDictionaryVariantType.GetProperty(var Dest: TVarData; const V: TVarData; const Name: string): Boolean;
var
LPair: Member.TViewPair;
LAsVar: Variant;
begin
{ Iterate over our internal array and search for the requested property by name }
with TViewDictionaryVarData(V) do
begin
for LPair in FArray do
if AnsiSameStr(LPair.Key, Name) then
begin
LAsVar := LPair.Value.AsVariant;
Dest := TVarData(LAsVar);
Exit(True);
end;
end;
{ Key not found, means error }
Clear(Dest);
Result := False;
end;
var
{ Our singleton that manages our variant type }
FViewDictionaryVariantType: TViewDictionaryVariantType;
{ Member.TSelector<T, K> }
function Member.TSelector<T, K>.GenericInvoke(AFrom: T): K;
var
LValue: TValue;
begin
LValue := TValueInvoke(AFrom);
Result := LValue.AsType<K>();
end;
{ Member.TRecordFieldSelector<T, K> }
function Member.TRecordFieldSelector<K>.TValueInvoke(AFrom: Pointer): TValue;
begin
ASSERT(Assigned(FMember));
ASSERT(FMember is TRttiField);
Result := TRttiField(FMember).GetValue(AFrom);
end;
{ Member.TClassFieldSelector<K> }
function Member.TClassFieldSelector<K>.TValueInvoke(AFrom: TObject): TValue;
begin
ASSERT(Assigned(FMember));
ASSERT(FMember is TRttiField);
Result := TRttiField(FMember).GetValue(AFrom);
end;
{ Member.TClassPropertySelector<K> }
function Member.TClassPropertySelector<K>.TValueInvoke(AFrom: TObject): TValue;
begin
ASSERT(Assigned(FMember));
ASSERT(FMember is TRttiProperty);
Result := TRttiProperty(FMember).GetValue(AFrom);
end;
{ Member.TViewSelector<T> }
function Member.TViewSelector<T>.Invoke(AFrom: T): TView;
var
I, L: NativeInt;
LCalc: TViewArray;
begin
{ Initialize a view }
VarClear(Result);
L := Length(FFuncs);
SetLength(LCalc, L);
{ Copy selected fields over }
for I := 0 to Length(FFuncs) - 1 do
begin
LCalc[I].Key := FNames[I];
LCalc[I].Value := FFuncs[I](AFrom);
end;
{ Give the result to the guy standing on the chair ... }
with TVarData(Result) do
begin
VType := Member.FViewVariantType;
Member.TViewArray(VPointer) := LCalc;
end;
end;
{ Member }
class function Member.Name<T, K>(const AName: string): TFunc<T, K>;
var
LT, LK: PTypeInfo;
LContext: TRttiContext;
LType: TRttiType;
LMember: TRttiMember;
LSelector: TSelector<T, K>;
begin
Result := nil;
{ Get the type }
LT := TypeInfo(T);
LK := TypeInfo(K);
LType := LContext.GetType(LT);
{ Check for correctness }
if not Assigned(LType) or not (LType.TypeKind in [tkClass, tkRecord]) then
Exit;
if LType.TypeKind = tkRecord then
begin
LMember := LType.GetField(AName);
if not Assigned(LMember) then
Exit;
LSelector := TSelector<T, K>(TRecordFieldSelector<K>.Create());
end else
if LType.TypeKind = tkClass then
begin
LMember := LType.GetField(AName);
if Assigned(LMember) then
LSelector := TSelector<T, K>(TClassFieldSelector<K>.Create())
else begin
LMember := LType.GetProperty(AName);
if not Assigned(LMember) then
Exit;
LSelector := TSelector<T, K>(TClassPropertySelector<K>.Create());
end;
end;
{ Upload selector }
LSelector.FContext := LContext;
LSelector.FType := LType;
LSelector.FMember := LMember;
Result := LSelector;
end;
class function Member.Name<T>(const AName: string): TFunc<T, TValue>;
begin
Result := Member.Name<T, TValue>(AName);
end;
class function Member.Name<T>(const ANames: array of string): TFunc<T, TView>;
var
LSelector: TViewSelector<T>;
I, L: NativeInt;
begin
Result := nil;
L := Length(ANames);
if L = 0 then
Exit;
LSelector := TViewSelector<T>.Create;
{ Prepare the array of selectors }
SetLength(LSelector.FNames, L);
SetLength(LSelector.FFuncs, L);
{ Create the array }
for I := 0 to L - 1 do
begin
LSelector.FNames[I] := AnsiUpperCase(ANames[I]);
LSelector.FFuncs[I] := Member.Name<T, TValue>(ANames[I]);
if not Assigned(LSelector.FFuncs[I]) then
begin
LSelector.Free;
Exit;
end;
end;
Result := LSelector;
end;
initialization
{ Register our custom variant type }
FViewDictionaryVariantType := TViewDictionaryVariantType.Create();
Member.FViewVariantType := FViewDictionaryVariantType.VarType;
finalization
{ Uregister our custom variant }
FreeAndNil(FViewDictionaryVariantType);
{$ELSE}
implementation
{$IFEND}
end.
|
{*******************************************************}
{ }
{ TiOPCItem Component }
{ }
{ Copyright (c) 1997,2002 Iocomp Software }
{ }
{*******************************************************}
{$I iInclude.inc}
{$ifdef iVCL}unit iOPCItem;{$endif}
{$ifdef iCLX}unit QiOPCItem;{$endif}
interface
uses
{$I iIncludeUses.inc}
{$IFDEF iVCL} ActiveX, ComObj, iTypes, iGPFunctions, iOPCtypes, iOPCFunctions, iOPCClasses;{$ENDIF}
type
TiOPCItem = class;
TiOPCItemManager = class;
TOPCItemGetDataTypeEvent = procedure(PropertyName: String; var AVarType: TVarType) of object;
TiOPCItem = class(TPersistent)
private
FPropertyName : String;
FServerName : String;
FComputerName : String;
FItemName : String;
FAutoConnect : Boolean;
FUpdateRate : Integer;
FActive : Boolean;
FServerIf : IOPCServer;
FGroupIf : IOPCItemMgt;
FGroupHandle : Cardinal;
FItemHandle : OPCHANDLE;
FItemType : TVarType;
FAdviseSink : TiOPCAdviseSink;
FAdviseSinkConnection : Longint;
FOPCDataCallback : TiOPCDataCallback;
FOPCDataCallbackConnection : Longint;
FShutdownCallback : TiOPCShutdownCallback;
FShutdownCallbackConnection : Longint;
FData : OleVariant;
FTimeStamp : TDateTime;
FQuality : Word;
FOwner : TiOPCItemManager;
FAutoError : Boolean;
protected
procedure SetPropertyName(const Value: String);
procedure SetServerName (const Value: String);
procedure SetComputerName(const Value: String);
procedure SetItemName (const Value: String);
procedure SetAutoConnect (const Value: Boolean);
procedure SetUpdateRate (const Value: Integer);
procedure SetAutoError (const Value: Boolean);
procedure AdviseCallBack (Sender: TObject);
procedure AsyncDataChange (Sender: TObject);
procedure ShutdownCallback(Sender: TObject);
function GetQualityGood: Boolean;
procedure SetData(const Value: OleVariant);
procedure UpdateError;
public
constructor Create;
destructor Destroy; override;
procedure Activate;
procedure Deactivate;
procedure UpdateResume;
procedure UpdateSuspend;
procedure Loaded;
property Data : OleVariant read FData write SetData;
property TimeStamp : TDateTime read FTimeStamp;
property Quality : Word read FQuality;
property Active : Boolean read FActive;
property QualityGood : Boolean read GetQualityGood;
property Owner : TiOPCItemManager read FOwner write FOwner;
published
property PropertyName : String read FPropertyName write SetPropertyName;
property ComputerName : String read FComputerName write SetComputerName;
property ServerName : String read FServerName write SetServerName;
property ItemName : String read FItemName write SetItemName;
property UpdateRate : Integer read FUpdateRate write SetUpdateRate;
property AutoConnect : Boolean read FAutoConnect write SetAutoConnect;
property AutoError : Boolean read FAutoError write SetAutoError;
end;
TiOPCItemManager = class(TObject)
private
FList : TStringList;
FOnGetDesigning : TGetDesigningEvent;
FOnNewData : TNotifyEvent;
FOnGetType : TOPCItemGetDataTypeEvent;
FOwner : TComponent;
protected
function GetCount: Integer;
function GetItem (Index: Integer): TiOpcItem;
function GetDesigning: Boolean;
public
constructor Create;
destructor Destroy; override;
function DoWriteToStream : Boolean;
procedure WriteToStream (Writer: TWriter);
procedure ReadFromStream(Reader: TReader);
function FindIndex(OPCItem: TiOPCItem): Integer;
procedure Clear;
procedure Delete(Index: Integer);
function Add: Integer;
property Items[Index: Integer]: TiOpcItem read GetItem;
property Count : Integer read GetCount;
property IsDesigning : Boolean read GetDesigning;
property Owner : TComponent read FOwner write FOwner;
property OnGetDesigning : TGetDesigningEvent read FOnGetDesigning write FOnGetDesigning;
property OnNewData : TNotifyEvent read FOnNewData write FOnNewData;
property OnGetType : TOPCItemGetDataTypeEvent read FOnGetType write FOnGetType;
end;
implementation
uses
iVCLComponent;
type
TWriterAccess = class(TWriter) end;
TReaderAccess = class(TReader) end;
TiVCLComponentAccess = class(TiVCLComponent) end;
//***********************************************************************************************************************************
constructor TiOPCItem.Create;
begin
FUpdateRate := 500;
FAutoConnect := True;
FComputerName := 'Local';
CoInitializeSecurity(nil, -1, nil, nil,iRPC_C_AUTHN_LEVEL_NONE, iRPC_C_IMP_LEVEL_IDENTIFY, nil, EOAC_NONE, nil);
end;
//***********************************************************************************************************************************
destructor TiOPCItem.Destroy;
begin
try
Deactivate;
except
end;
inherited;
end;
//***********************************************************************************************************************************
procedure TiOPCItem.Loaded;
begin
try
if FAutoError then UpdateError;
if FAutoConnect then
begin
try
if not FOwner.IsDesigning then Activate;
except
on exception do;
end;
end;
except
end;
end;
//***********************************************************************************************************************************
procedure TiOPCItem.SetServerName(const Value: String);
begin
FServerName := Value;
if FActive then Activate;
end;
//***********************************************************************************************************************************
procedure TiOPCItem.SetComputerName(const Value: String);
begin
FComputerName := Value;
if FActive then Activate;
end;
//***********************************************************************************************************************************
procedure TiOPCItem.SetItemName(const Value: String);
begin
FItemName := Value;
if FActive then Activate;
end;
//***********************************************************************************************************************************
procedure TiOPCItem.SetUpdateRate(const Value: Integer);
begin
FUpdateRate := Value;
if FActive then Activate;
end;
//***********************************************************************************************************************************
procedure TiOPCItem.SetAutoConnect(const Value: Boolean);
begin
FAutoConnect := Value;
if FActive then Activate;
end;
//***********************************************************************************************************************************
procedure TiOPCItem.SetPropertyName(const Value: String);
begin
FPropertyName := Value;
end;
//***********************************************************************************************************************************
procedure TiOPCItem.Activate;
var
HR : HResult;
ActualMachineName : String;
OPCServerList : IOPCServerList;
AVarType : TVarType;
begin
try
if FAutoError then UpdateError;
if Assigned(FServerIf) then Deactivate;
// if Trim(FPropertyName) = '' then Exit;
if Trim(FServerName) = '' then Exit;
if Trim(FItemName) = '' then Exit;
FActive := True;
ActualMachineName := Trim(FComputerName);
if UpperCase(ActualMachineName) = 'LOCAL' then ActualMachineName := '';
try
if Trim(ActualMachineName) <> '' then
begin
FServerIf := CreateRemoteComObject(ActualMachineName, OPCGetRemoteCLSID(ActualMachineName, FServerName, OPCServerList)) as IOPCServer;
end
else
FServerIf := CreateComObject(ProgIDToClassID(FServerName)) as IOPCServer;
except
on e : exception do
begin
raise Exception.Create('Exception : Failed to Connect to Server - ' + e.message);
FServerIf := nil;
end;
end;
if not Assigned(FServerIf) then raise Exception.Create('Failed to Connect to Server');
FShutdownCallback := TiOPCShutdownCallback.Create;
FShutdownCallback.OnChange := ShutdownCallback;
OPCShutdownAdvise(FServerIf, FShutdownCallback, FShutdownCallbackConnection);
HR := OPCServerAddGroup(FServerIf, '', True, FUpdateRate, FGroupIf, FGroupHandle);
if not Succeeded(HR) then raise Exception.Create('Failed to Add Group');
AVarType := VT_EMPTY;
// if Assigned(FOwner.OnGetType) then FOwner.OnGetType(PropertyName, AVarType);
HR := OPCGroupAddItem(FGroupIf, FItemName, 0, AVarType, FItemHandle, FItemType);
if not Succeeded(HR) then raise Exception.Create('Failed to Add Item');
//---------------------------------------------------
FOPCDataCallback := TiOPCDataCallback.Create;
FOPCDataCallback.OnDataChange2 := AsyncDataChange;
OPCGroupAdvise2(FGroupIf, FOPCDataCallback, FOPCDataCallbackConnection);
if FOPCDataCallbackConnection = 0 then
begin
FAdviseSink := TiOPCAdviseSink.Create;
FAdviseSink.OnChange := AdviseCallBack;
OPCGroupAdviseTime(FGroupIf, FAdviseSink, FAdviseSinkConnection);
end;
except
Deactivate;
raise;
end;
end;
//***********************************************************************************************************************************
procedure TiOPCItem.Deactivate;
begin
FActive := False;
if FAdviseSinkConnection <> 0 then
begin
OPCGroupUnAdvise(FGroupIf, FAdviseSinkConnection);
FAdviseSinkConnection := 0;
FAdviseSink := nil;
end;
if FOPCDataCallbackConnection <> 0 then
begin
OPCGroupUnAdvise2(FGroupIf, FOPCDataCallbackConnection);
FOPCDataCallbackConnection := 0;
FOPCDataCallback := nil;
end;
if FItemHandle <> 0 then
begin
OPCGroupRemoveItem(FGroupIf, FItemHandle);
FItemHandle := 0;
end;
if Assigned(FServerIf) then
begin
if FShutdownCallbackConnection <> 0 then
begin
OPCShutdownUnadvise(FServerIf, FShutdownCallbackConnection);
FShutdownCallbackConnection := 0;
FShutdownCallback := nil;
end;
if FGroupHandle <> 0 then
begin
FServerIf.RemoveGroup(FGroupHandle, False);
FGroupIf := nil;
FGroupHandle := 0;
end;
FServerIf := nil;
end;
//----------------------------------------------------------------------------
end;
//***********************************************************************************************************************************
procedure TiOPCItem.AdviseCallBack(Sender: TObject);
begin
if not FActive then Exit;
FData := FAdviseSink.Data;
FQuality := FAdviseSink.Quality;
FTimeStamp := FAdviseSink.TimeStamp;
if FAutoError then UpdateError;
if Assigned(FOwner.OnNewData) then FOwner.OnNewData(Self);
end;
//***********************************************************************************************************************************
procedure TiOPCItem.AsyncDataChange(Sender: TObject);
begin
if not FActive then Exit;
FData := FOPCDataCallback.Data;
FQuality := FOPCDataCallback.Quality;
FTimeStamp := FOPCDataCallback.TimeStamp;
if FAutoError then UpdateError;
if Assigned(FOwner.OnNewData) then FOwner.OnNewData(Self);
end;
//***********************************************************************************************************************************
procedure TiOPCItem.ShutdownCallback(Sender: TObject);
begin
if Assigned(FGroupIf) then
begin
if FAdviseSinkConnection <> 0 then
begin
OPCGroupUnAdvise(FGroupIf, FAdviseSinkConnection);
FAdviseSinkConnection := 0;
FAdviseSink := nil;
end;
if FOPCDataCallbackConnection <> 0 then
begin
OPCGroupUnAdvise2(FGroupIf, FOPCDataCallbackConnection);
FOPCDataCallbackConnection := 0;
FOPCDataCallback := nil;
end;
if FItemHandle <> 0 then
begin
OPCGroupRemoveItem(FGroupIf, FItemHandle);
FItemHandle := 0;
end;
end;
FAdviseSinkConnection := 0;
FOPCDataCallbackConnection := 0;
FItemHandle := 0;
FGroupHandle := 0;
FShutdownCallbackConnection := 0;
FAdviseSink := nil;
FOPCDataCallback := nil;
FShutdownCallback := nil;
FGroupIf := nil;
end;
//***********************************************************************************************************************************
procedure TiOPCItem.SetData(const Value: OleVariant);
var
HR : LongInt;
begin
if not FActive then Exit;
if not Assigned(FServerIf) then raise Exception.Create('Data Write Failure - Not Connected to Server');
if not Assigned(FGroupIf) then raise Exception.Create('Data Write Failure - Not Connected to Group');
if FItemHandle = 0 then raise Exception.Create('Data Write Failure - Not Connected to Item');
HR := OPCWriteGroupItemValue(FGroupIf, FItemHandle, Value);
if not Succeeded(HR) then raise Exception.Create('Data Write Failure');
end;
//***********************************************************************************************************************************
{ TiOPCItemManager }
//***********************************************************************************************************************************
constructor TiOPCItemManager.Create;
begin
FList := TStringList.Create;
end;
//***********************************************************************************************************************************
destructor TiOPCItemManager.Destroy;
begin
Clear;
FList.Free;
inherited;
end;
//***********************************************************************************************************************************
function TiOPCItemManager.Add: Integer;
var
iOPCItem : TiOPCItem;
begin
iOPCItem := TiOPCItem.Create;
iOPCItem.Owner := Self;
Result := FList.AddObject('',iOPCItem);
end;
//***********************************************************************************************************************************
procedure TiOPCItemManager.Clear;
begin
while FList.Count > 0 do
begin
FList.Objects[0].Free;
FList.Delete(0);
end;
end;
//***********************************************************************************************************************************
procedure TiOPCItemManager.Delete(Index: Integer);
begin
FList.Delete(Index);
end;
//***********************************************************************************************************************************
function TiOPCItemManager.GetCount: Integer;
begin
Result := FList.Count;
end;
//***********************************************************************************************************************************
function TiOPCItemManager.GetItem(Index: Integer): TiOPCItem;
begin
Result := FList.Objects[Index] as TiOPCItem;
end;
//***********************************************************************************************************************************
function TiOPCItemManager.FindIndex(OPCItem: TiOPCItem): Integer;
begin
Result := FList.IndexOfObject(OPCItem);
end;
//***********************************************************************************************************************************
function TiOPCItemManager.DoWriteToStream: Boolean;
begin
Result := Count > 0;
end;
//***********************************************************************************************************************************
procedure TiOPCItemManager.WriteToStream(Writer: TWriter);
var
x : Integer;
begin
TWriterAccess(Writer).WriteValue(vaCollection);
for x := 0 to Count - 1 do
begin
Writer.WriteListBegin;
WriterWriteProperties(Writer, GetItem(x));
Writer.WriteListEnd;
end;
Writer.WriteListEnd;
end;
//***********************************************************************************************************************************
procedure TiOPCItemManager.ReadFromStream(Reader: TReader);
var
Item : TiOPCItem;
begin
Clear;
if not Reader.EndOfList then Clear;
if TReaderAccess(Reader).ReadValue <> vaCollection then exit;
while not Reader.EndOfList do
begin
Item := TiOPCItem.Create;
Item.Owner := Self;
FList.AddObject('',Item);
Reader.ReadListBegin;
while not Reader.EndOfList do TReaderAccess(Reader).ReadProperty(Item);
Reader.ReadListEnd;
Item.Loaded;
end;
Reader.ReadListEnd;
end;
//***********************************************************************************************************************************
function TiOPCItemManager.GetDesigning: Boolean;
begin
Result := False;
if Assigned(FOnGetDesigning) then FOnGetDesigning(Self, Result);
end;
//***********************************************************************************************************************************
procedure TiOPCItem.UpdateResume;
begin
if not Assigned(FGroupIF) then raise Exception.Create('Group can not be Activated when group does not exists.');
OPCServerSetGroupActive(FGroupIf, True);
end;
//***********************************************************************************************************************************
procedure TiOPCItem.UpdateSuspend;
begin
if not Assigned(FGroupIF) then raise Exception.Create('Group can not be Deactivated when group does not exists.');
OPCServerSetGroupActive(FGroupIf, False);
end;
//***********************************************************************************************************************************
procedure TiOPCItem.SetAutoError(const Value: Boolean);
begin
if FAutoError <> Value then
begin
FAutoError := Value;
if FAutoError then UpdateError;
end;
end;
//***********************************************************************************************************************************
procedure TiOPCItem.UpdateError;
var
VCLComponent : TiVCLComponent;
begin
if not Active then Exit;
if not Assigned(Owner) then Exit;
if not Assigned(Owner.Owner) then Exit;
if Owner.Owner is TiVCLComponent then VCLComponent := Owner.Owner as TiVCLComponent else Exit;
if Active then
begin
if QualityGood then TiVCLComponentAccess(VCLComponent).ErrorActive := False
else TiVCLComponentAccess(VCLComponent).ErrorActive := True;
end;
end;
//***********************************************************************************************************************************
function TiOPCItem.GetQualityGood: Boolean;
begin
Result := (FQuality and $C0) = $C0;
end;
//***********************************************************************************************************************************
end.
|
unit InflatablesList_ItemPictures_IO_00000000;
{$INCLUDE '.\InflatablesList_defs.inc'}
interface
uses
Classes, Graphics,
AuxTypes,
InflatablesList_ItemPictures_Base,
InflatablesList_ItemPictures_IO;
type
TILItemPictures_IO_00000000 = class(TILItemPictures_IO)
protected
procedure InitSaveFunctions(Struct: UInt32); override;
procedure InitLoadFunctions(Struct: UInt32); override;
procedure SavePictures_00000000(Stream: TStream); virtual;
procedure LoadPictures_00000000(Stream: TStream); virtual;
procedure SaveEntries_00000000(Stream: TStream); virtual;
procedure LoadEntries_00000000(Stream: TStream); virtual;
procedure SaveEntry_00000000(Stream: TStream; Entry: TILItemPicturesEntry); virtual;
procedure LoadEntry_00000000(Stream: TStream; out Entry: TILItemPicturesEntry); virtual;
procedure SaveThumbnail_00000000(Stream: TStream; Thumbnail: TBitmap); virtual;
procedure LoadThumbnail_00000000(Stream: TStream; out Thumbnail: TBitmap); virtual;
end;
implementation
uses
SysUtils,
BinaryStreaming;
procedure TILItemPictures_IO_00000000.InitSaveFunctions(Struct: UInt32);
begin
If Struct = IL_ITEMPICTURES_STREAMSTRUCTURE_00000000 then
begin
fFNSaveToStream := SavePictures_00000000;
fFNSaveEntries := SaveEntries_00000000;
fFNSaveEntry := SaveEntry_00000000;
fFNSaveThumbnail := SaveThumbnail_00000000;
end
else raise Exception.CreateFmt('TILItemPictures_IO_00000000.InitSaveFunctions: Invalid stream structure (%.8x).',[Struct]);
end;
//------------------------------------------------------------------------------
procedure TILItemPictures_IO_00000000.InitLoadFunctions(Struct: UInt32);
begin
If Struct = IL_ITEMPICTURES_STREAMSTRUCTURE_00000000 then
begin
fFNLoadFromStream := LoadPictures_00000000;
fFNLoadEntries := LoadEntries_00000000;
fFNLoadEntry := LoadEntry_00000000;
fFNLoadThumbnail := LoadThumbnail_00000000;
end
else raise Exception.CreateFmt('TILItemPictures_IO_00000000.InitLoadFunctions: Invalid stream structure (%.8x).',[Struct]);
end;
//------------------------------------------------------------------------------
procedure TILItemPictures_IO_00000000.SavePictures_00000000(Stream: TStream);
begin
// in this version, nothing is saved beyond the entries
fFNSaveEntries(Stream);
end;
//------------------------------------------------------------------------------
procedure TILItemPictures_IO_00000000.LoadPictures_00000000(Stream: TStream);
begin
fFNLoadEntries(Stream);
end;
//------------------------------------------------------------------------------
procedure TILItemPictures_IO_00000000.SaveEntries_00000000(Stream: TStream);
var
i: Integer;
begin
Stream_WriteUInt32(Stream,UInt32(fCount));
For i := LowIndex to HighIndex do
SaveEntry_00000000(Stream,fPictures[i]);
end;
//------------------------------------------------------------------------------
procedure TILItemPictures_IO_00000000.LoadEntries_00000000(Stream: TStream);
var
i: Integer;
begin
SetLength(fPictures,Stream_ReadUInt32(Stream));
fCount := Length(fPictures);
For i := LowIndex to HighIndex do
LoadEntry_00000000(Stream,fPictures[i]);
end;
//------------------------------------------------------------------------------
procedure TILItemPictures_IO_00000000.SaveEntry_00000000(Stream: TStream; Entry: TILItemPicturesEntry);
begin
Stream_WriteString(Stream,Entry.PictureFile);
Stream_WriteUInt64(Stream,Entry.PictureSize);
Stream_WriteInt32(Stream,Entry.PictureWidth);
Stream_WriteInt32(Stream,Entry.PictureHeight);
fFNSaveThumbnail(Stream,Entry.Thumbnail);
Stream_WriteBool(Stream,Entry.ItemPicture);
Stream_WriteBool(Stream,Entry.PackagePicture);
end;
//------------------------------------------------------------------------------
procedure TILItemPictures_IO_00000000.LoadEntry_00000000(Stream: TStream; out Entry: TILItemPicturesEntry);
begin
FreeEntry(Entry);
Entry.PictureFile := Stream_ReadString(Stream);
Entry.PictureSize := Stream_ReadUInt64(Stream);
Entry.PictureWidth := Stream_ReadInt32(Stream);
Entry.PictureHeight := Stream_ReadInt32(Stream);
fFNLoadThumbnail(Stream,Entry.Thumbnail);
GenerateSmallThumbnails(Entry);
Entry.ItemPicture := Stream_ReadBool(Stream);
Entry.PackagePicture := Stream_ReadBool(Stream);
end;
//------------------------------------------------------------------------------
procedure TILItemPictures_IO_00000000.SaveThumbnail_00000000(Stream: TStream; Thumbnail: TBitmap);
var
TempStream: TMemoryStream;
begin
If Assigned(Thumbnail) then
begin
TempStream := TMemoryStream.Create;
try
Thumbnail.SaveToStream(TempStream);
Thumbnail.Dormant;
Stream_WriteUInt32(Stream,TempStream.Size);
Stream.CopyFrom(TempStream,0);
finally
TempStream.Free;
end;
end
else Stream_WriteUInt32(Stream,0);
end;
//------------------------------------------------------------------------------
procedure TILItemPictures_IO_00000000.LoadThumbnail_00000000(Stream: TStream; out Thumbnail: TBitmap);
var
Size: UInt32;
TempStream: TMemoryStream;
begin
Size := Stream_ReadUInt32(Stream);
If Size > 0 then
begin
TempStream := TMemoryStream.Create;
try
TempStream.CopyFrom(Stream,Size);
TempStream.Seek(0,soBeginning);
Thumbnail := TBitmap.Create;
try
Thumbnail.LoadFromStream(TempStream);
Thumbnail.Dormant;
except
FreeAndNil(Thumbnail);
end;
finally
TempStream.Free;
end;
end
else Thumbnail := nil;
end;
end.
|
unit uParentDM;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
DBTables, Db, ADODB, RCADOQuery, xBase;
type
TParentDM = class(TDataModule)
quFreeSQL: TADOQuery;
quRebuildIdent: TADOQuery;
quConstante: TRCADOQuery;
quConstanteConstante: TStringField;
quConstanteValor: TIntegerField;
quRebuildIdentTABLE_QUALIFIER: TStringField;
quRebuildIdentTABLE_OWNER: TStringField;
quRebuildIdentTABLE_NAME: TStringField;
quRebuildIdentTABLE_TYPE: TStringField;
quRebuildIdentREMARKS: TStringField;
DBADOConnection: TADOConnection;
procedure ParentDMCreate(Sender: TObject);
private
{ Private declarations }
protected
procedure SetClientToServerDate;
public
{ Public declarations }
aSrvParam : Variant;
aCliParam : Variant;
function GetLastKey : Integer;
function GetConst(Literal: String): Integer;
function GetMaxKey(TableName, MaxField : String) : Integer;
function DescCodigo(aFilterFields, aFilterValues : array of String;
DescTable, DescField : String) : String;
function GetActualPathName(strSQL, FieldName : String; IDItem : Integer) : String;
procedure DBCC_RebuildIdentity;
function GetSQLKey(MySQL: String): String;
function GetTableCount(ATableName:String): integer;
end;
implementation
{$R *.DFM}
uses uSQLFunctions, uNumericFunctions, uStringFunctions;
function TParentDM.GetTableCount(ATableName: String): integer;
begin
with quFreeSQL do
begin
Close;
with SQL do
begin
Clear;
Add('SELECT');
Add(' MAX(i.rows) as RecCount');
Add('FROM');
Add(' [sysindexes] I,');
Add(' INFORMATION_SCHEMA.TABLES T');
Add('WHERE');
Add(' T.TABLE_NAME = object_name(i.id)');
Add(' AND');
Add(' T.TABLE_TYPE = '+QuotedStr('BASE TABLE'));
Add(' AND');
Add(' T.TABLE_NAME = '+QuotedStr(ATableName));
Add('GROUP BY');
Add(' T.TABLE_SCHEMA,');
Add(' T.TABLE_NAME');
end;
Open;
Result := Fields[0].AsInteger;
Close;
end;
end;
function TParentDM.GetSQLKey(MySQL: String): String;
var
sTableName: String;
begin
sTableName := GetSQLFirstTableName(MySQL);
// Retiro o nome do usuario caso ele exista
if UpperCase(LeftStr(sTableName, 4)) = 'DBO.' then
sTableName := RightStr(sTableName, Length(sTableName)-4);
with quFreeSQL do
begin
if Active then
Close;
SQL.Text := 'sp_System_dbKeys ' + Chr(39) + sTableName + Chr(39);
Open;
Result := FieldByName('COLUMN_NAME').AsString;
Close;
end;
end;
function TParentDM.GetConst(Literal: String): Integer;
begin
with quConstante do
begin
if not Active then Open;
if Locate('Constante', Literal, []) then
Result := MyStrToInt(quConstanteValor.AsString)
else
showmessage( 'Constant : ' + Literal + ' could not be found in the database.');
end;
end;
function TParentDM.GetActualPathName(strSQL, FieldName : String; IDItem : Integer) : String;
begin
// Descobre o Path Name do no selecionado
with quFreeSQL do
begin
try
if Active then
Close;
SQL.Text := 'SELECT PathName FROM ' +
GetSQLFirstTableName(strSQL) +
' WHERE ' + FieldName + ' = ' + IntToStr(IDItem);
Open;
Result := Trim(Fields[0].AsString);
Close;
except
on exception do
raise exception.create('You enter with an invalid search');
end;
end;
end;
function TParentDM.DescCodigo(aFilterFields, aFilterValues : array of String;
DescTable, DescField : String) : String;
var
i : integer;
strWhere, strSelect : String;
begin
// Funcao de procura padrao
// Lembar de passar com as devidas conversoes
strWhere := '';
for i := Low(aFilterFields) to High(aFilterFields) do
begin
IncString(StrWhere, '( ' + aFilterFields[i] + ' = ' +
aFilterValues[i] + ' )');
if i < High(aFilterFields) then
IncString(StrWhere, ' AND ');
end;
strSelect := 'SELECT ' + DescField + ' FROM ' +
DescTable + ' WHERE ' + StrWhere;
with quFreeSQL do
begin
if Active then
Close;
SQL.Text := strSelect;
try
Open;
if Bof and Eof then
Result := ''
else
Result := Fields[0].AsString;
Close;
except
on exception do
raise exception.create('You enter with an invalid search');
end;
end;
Screen.Cursor := crDefault;
end;
procedure TParentDM.SetClientToServerDate;
var
ServerTime : TDateTime;
ServerSysTime : TSystemTime;
begin
with quFreeSQL do
begin
if Active then
Close;
SQL.Text := 'SELECT GetDate()';
Open;
ServerTime := Fields[0].AsDateTime;
Close;
DateTimeToSystemTime(ServerTime, ServerSysTime);
SetLocalTime(ServerSysTime);
end;
end;
function TParentDM.GetLastKey : Integer;
begin
with quFreeSQl do
begin
if Active then
Close;
SQL.Text := 'SELECT @@IDENTITY';
Open;
Result := Fields[0].AsInteger;
Close;
end;
end;
function TParentDM.GetMaxKey(TableName, MaxField : String) : Integer;
begin
with quFreeSQl do
begin
if Active then
Close;
//Com a replicacao isso nao funciona
//SQL.Text := 'SELECT MAX(' + MaxField + ') FROM ' + TableName;
SQL.Text := 'SELECT UltimoCodigo FROM Sis_CodigoIncremental WHERE Tabela = ' + QuotedStr(TableName + '.' + MaxField);
Open;
Result := Fields[0].AsInteger;
Close;
end;
end;
procedure TParentDM.DBCC_RebuildIdentity;
begin
Screen.Cursor := crHourGlass;
with quRebuildIdent do
begin
Open;
if quFreeSQL.Active then
quFreeSQL.Close;
while not Eof do
begin
quFreeSQL.SQL.Text := 'DBCC CHECKIDENT (' + quRebuildIdentTABLE_NAME.AsString + ')';
try
quFreeSQL.ExecSQL;
except
end;
Next;
end;
Close;
end;
Screen.Cursor := crDefault;
end;
procedure TParentDM.ParentDMCreate(Sender: TObject);
var
Year, Dummy : Word;
tmpDateFormat : String;
begin
// Seta a data do cliente igual a do server
SetClientToServerDate;
// Seta o decimalseparator
//DecimalSeparator := '.';
// Seta se mostra data com 4 digitos, quando passa do ano 2000
DecodeDate(Date, Year, Dummy, Dummy);
if Year = 2000 then
begin
tmpDateFormat := UpperCase(ShortDateFormat);
if(pos('YYYY', tmpDateFormat) = 0) and (pos('YY', tmpDateFormat) <> 0) then
insert('YY', tmpDateFormat, pos('YY', tmpDateFormat));
ShortDateFormat := tmpDateFormat;
end;
end;
end.
|
unit DPM.Core.Repository.PackageInfo;
interface
uses
DPM.Core.Types,
DPM.Core.Repository.Interfaces;
type
TPackageInfo = class(TInterfacedObject, IPackageInfo)
private
FCompilerVersion: TCompilerVersion;
FId: string;
FPlatform: TDPMPlatform;
FSourceName: string;
FVersion: TPackageVersion;
protected
function GetCompilerVersion: TCompilerVersion;
function GetId: string;
function GetPlatform: TDPMPlatform;
function GetSourceName: string;
function GetVersion: TPackageVersion;
public
function ToString : string;override;
constructor Create(const id, source : string; const version : TPackageVersion; const compilerVersion: TCompilerVersion; const platform : TDPMPlatform);
end;
// TPackageInfoComparer = class
implementation
{ TPackageInfo }
constructor TPackageInfo.Create(const id, source : string; const version : TPackageVersion; const compilerVersion: TCompilerVersion; const platform: TDPMPlatform);
begin
FId := id;
FVersion := version;
FSourceName := source;
FCompilerVersion := compilerVersion;
FPlatform := platform;
end;
function TPackageInfo.GetCompilerVersion: TCompilerVersion;
begin
result := FCompilerVersion;
end;
function TPackageInfo.GetId: string;
begin
result := FId;
end;
function TPackageInfo.GetPlatform: TDPMPlatform;
begin
result := FPlatform;
end;
function TPackageInfo.GetSourceName: string;
begin
result := FSourceName;
end;
function TPackageInfo.GetVersion: TPackageVersion;
begin
result := FVersion;
end;
function TPackageInfo.ToString: string;
begin
result := FId +'-' + CompilerToString(FCompilerVersion) + '-' + DPMPlatformToString(FPlatform) + '-' + FVersion.ToString;
end;
end.
|
unit Variables;
interface
type
TJoueur = (Joueur1,Joueur2);
{ Représente une Tribu (Civilisation) et ses caractéristiques }
TTribu = record
nom : String; // Nom de la Tribu
numJour : Integer; // Numéro du Jour (Tour)
niveauMax : Integer; // Niveau maximum que peuvent atteindre les bâtiments des élevages la Tribu
archetype : String; // Archétype de la Tribu
difficulte : String; // Difficulté du jeu, propre à la Tribu du joueur
victoires : Integer; // Nombres de victoires en combat
defaites : Integer; // Nombre de défaites en combat
limDefaites : Integer; // Limite de défaites que peut encaisser le joueur avant de perdre la partie
ptsRecrutement : Integer; // Points de recrutement dont dispose le joueur
ptsRecrutementJour : Integer; // Points de recrutement dont dispose le joueur par jour
end;
{ Représente un Elevage (Ville) et ses caractéristiques }
TElevage = record
nom : String; // Nom de l'élevage
population : Integer; // Population totale de l'élevage
construction : Boolean ; // Etat de construction de l'élevage
bonheur : Integer; // 'Points' de bonheur de l'élevage
facteurBonheur : Real; // Facteur calculé en fonction du bonheur et de la population
savoirJourAbsolu : Integer; // Valeur absolue du savoir acquis chaque jour
savoirJour : Integer; // Valeur réelle du savoir acquis chaque jour (- la population)
savoirAcquis : Integer; // Savoir total acquis pendant la phase de croissance
facteurCroissance : Integer; // Facteur intervenant dans le calcul du seuilCroissance
seuilCroissance : Integer; // Savoir à acquérir pour croître (+1 population)
nbJourAvCroissance : Integer; // Nb de jours restant avant de croître
equationsJour : Integer; // Nb d'équations résolues par jour
equationsResolues : Integer; // Nb total d'équations résolues pendant la phase de construction
end;
{ Représente un bâtiment et ses caractéristiques }
TBatiment = record
nom : String; // Nom du bâtiment
niveau : Integer; // Niveau du bâtiment
construction : Boolean; // Etat de construction du bâtiment
PALIERS : Array[0..3] of Integer; // Paliers de construction/amélioration à atteindre
BONUS : Array[0..3] of Integer; // Bonus apportés par le bâtiment
end;
{ Représente une unité de combat et ses caractéristiques }
TUnite = record
nom : String; // Nom de l'unité
nb : Integer; // Nombre d'éléments de l'unité
ptsAttaque : Integer; // Pts d'attaque que vaut une unité
prix : Integer; // Pts à dépenser pour acquérir une unité
end;
{ FONCTIONS & PROCEDURES }
{ Les GETTERS sont utilisés afin de récupérer l'information d'une entité locale depuis une autre unité. }
{ Les SETTERS sont utilisés afin de modifier une entité locale depuis d'une autre unité. }
// MULTIJOUEUR
{ Get }
function getMultijoueur : Boolean;
{ Set }
procedure setMultijoueur(boolMultijoueur : Boolean);
// TRIBU
{ Get }
function getTribu(Joueur : TJoueur) : TTribu;
{ Set }
procedure setTribu_nom (Joueur : TJoueur ; nom : String);
procedure setTribu_numJour (Joueur : TJoueur ; numJour : Integer);
procedure setTribu_archetype (Joueur : TJoueur ; archetype : String);
procedure setTribu_difficulte (Joueur : TJoueur ; difficulte : String);
procedure setTribu_niveauMax (Joueur : TJoueur ; niveauMax : Integer);
procedure setTribu_victoires (Joueur : TJoueur ; victoires : Integer);
procedure setTribu_defaites (Joueur : TJoueur ; defaites : Integer);
procedure setTribu_limDefaites (Joueur : TJoueur ; limDefaites : Integer);
procedure setTribu_ptsRecrutement (Joueur : TJoueur ; ptsRecrutement : Integer);
procedure setTribu_ptsRecrutementJour (Joueur : TJoueur ; ptsRecrutementJour : Integer);
// ELEVAGE
{ Get }
function getElevage(Joueur : TJoueur) : TElevage;
{ Set }
procedure setElevage_nom (Joueur : TJoueur ; nom : String);
procedure setElevage_population (Joueur : TJoueur ; population : Integer);
procedure setElevage_construction (Joueur : TJoueur ; construction : Boolean);
procedure setElevage_bonheur (Joueur : TJoueur ; bonheur : Integer);
procedure setElevage_facteurBonheur (Joueur : TJoueur ; facteurBonheur : Real);
procedure setElevage_savoirJourAbsolu (Joueur : TJoueur ; savoirJourAbsolu : Integer);
procedure setElevage_savoirJour (Joueur : TJoueur ; savoirJour : Integer);
procedure setElevage_savoirAcquis (Joueur : TJoueur ; savoirAcquis : Integer);
procedure setElevage_facteurCroissance (Joueur : TJoueur ; facteurCroissance : Integer);
procedure setElevage_seuilCroissance (Joueur : TJoueur ; seuilCroissance : Integer);
procedure setElevage_nbJourAvCroissance (Joueur : TJoueur ; nbJourAvCroissance : Integer);
procedure setElevage_equationsJour (Joueur : TJoueur ; equationsJour : Integer);
procedure setElevage_equationsResolues (Joueur : TJoueur ; equationsResolues : Integer);
// UNIVERSITE
{ Get }
function getUniversite(Joueur : TJoueur) : TBatiment;
{ Set }
procedure setUniversite_niveau (Joueur : TJoueur ; niveau : Integer);
procedure setUniversite_construction (Joueur : TJoueur ; construction : Boolean);
// CENTRE DE RECHERCHES
{ Get }
function getCDR(Joueur : TJoueur) : TBatiment;
{ Set }
procedure setCDR_niveau (Joueur : TJoueur ; niveau : Integer);
procedure setCDR_construction (Joueur : TJoueur ; construction : Boolean);
// LABORATOIRE
{ Get }
function getLaboratoire(Joueur : TJoueur) : TBatiment;
{ Set }
procedure setLaboratoire_niveau (Joueur : TJoueur ; niveau : Integer);
procedure setLaboratoire_construction (Joueur : TJoueur ; construction : Boolean);
// ENCLOS
{ Get }
function getEnclos(Joueur : TJoueur) : TBatiment;
{ Set }
procedure setEnclos_niveau (Joueur : TJoueur ; niveau : Integer);
procedure setEnclos_construction (Joueur : TJoueur ; construction : Boolean);
// BIBLIOHÈQUE
{ Get }
function getBibliotheque(Joueur : TJoueur) : TBatiment;
{ Set }
procedure setBibliotheque_niveau (Joueur : TJoueur ; niveau : Integer);
procedure setBibliotheque_construction (Joueur : TJoueur ; construction : Boolean);
// ARCHIVES
{ Get }
function getArchives(Joueur : TJoueur) : TBatiment;
{ Set }
procedure setArchives_niveau (Joueur : TJoueur ; niveau : Integer);
procedure setArchives_construction (Joueur : TJoueur ; construction : Boolean);
// LAMA
{ Get }
function getLama(Joueur : TJoueur) : TUnite;
{ Set }
procedure setLama_nb(Joueur : TJoueur ; nb : Integer);
// ALPAGA
{ Get }
function getAlpaga(Joueur : TJoueur) : TUnite;
{ Set }
procedure setAlpaga_nb(Joueur : TJoueur ; nb : Integer);
// GUANACO
{ Get }
function getGuanaco(Joueur : TJoueur) : TUnite;
{ Set }
procedure setGuanaco_nb(Joueur : TJoueur ; nb : Integer);
{ INITIALISATION DU JOUEUR }
procedure initJoueur(Joueur : TJoueur);
{ ARCHETYPE & DIFFICULTE }
{ Les procédues suivantes modifient certaines propriétés en fonction
de l'archétype de Tribu et de la difficulté choisis par le joueur. }
// Applique les changements liés à l'archétype de la Tribu
procedure appliquerArchetype(Joueur : TJoueur);
// Applique les changements liés à la difficulté de la partie
{ ATTENTION : La difficulté influe aussi sur le nb d'unités présentes dans les pâturages ennemis.
Se référer à la procédure genererEnnemis() de l'unit EcranCombat. }
procedure appliquerDifficulte(Joueur : TJoueur);
implementation
var
Multijoueur : Boolean; // FALSE : 1 Joueur, TRUE : 2 Joueurs
{ Création des principales entités du jeu }
{ JOUEUR 1 }
Tribu : TTribu; // Tribu (Civilisation)
Elevage : TElevage; // Elevage (Ville)
Universite : TBatiment; // Bâtiment UNIVERSITE (Ferme)
CDR : TBatiment; // Bâtiment CENTRE DE RECHERCHES (Mine)
Laboratoire : TBatiment; // Bâtiment LABORATOIRE (Carrière)
Enclos : TBatiment; // Bâtiment ENCLOS (Caserne)
Bibliotheque : TBatiment; // Bâtiment BIBLIOTHÈQUE (Parc *amélioration*)
Archives : TBatiment; // Bâtiment ARCHIVES *amélioration personnelle*
Lama : TUnite; // Unité LAMA (Soldat)
Alpaga : TUnite; // Unité ALPAGA (Canon)
Guanaco : TUnite; // Unité GUANACO (Cavalier)
{ JOUEUR 2 }
Tribu2 : TTribu; // Tribu (Civilisation)
Elevage2 : TElevage; // Elevage (Ville)
Universite2 : TBatiment; // Bâtiment UNIVERSITE (Ferme)
CDR2 : TBatiment; // Bâtiment CENTRE DE RECHERCHES (Mine)
Laboratoire2 : TBatiment; // Bâtiment LABORATOIRE (Carrière)
Enclos2 : TBatiment; // Bâtiment ENCLOS (Caserne)
Bibliotheque2 : TBatiment; // Bâtiment BIBLIOTHÈQUE (Parc *amélioration*)
Archives2 : TBatiment; // Bâtiment ARCHIVES *amélioration personnelle*
Lama2 : TUnite; // Unité LAMA (Soldat)
Alpaga2 : TUnite; // Unité ALPAGA (Canon)
Guanaco2 : TUnite; // Unité GUANACO (Cavalier)
{ FONCTIONS & PROCEDURES }
{ Les GETTERS sont utilisés afin de récupérer l'information d'une entité locale depuis une autre unité. }
{ Les SETTERS sont utilisés afin de modifier une entité locale depuis d'une autre unité. }
// MULTIJOUEUR
{ Get }
function getMultijoueur : Boolean;
begin
getMultijoueur := Multijoueur;
end;
{ Set }
procedure setMultijoueur(boolMultijoueur : Boolean);
begin
Multijoueur := boolMultijoueur;
end;
// TRIBU
{ Get }
function getTribu(Joueur : TJoueur) : TTribu;
begin
if Joueur = Joueur1 then getTribu := Tribu
else if Joueur = Joueur2 then getTribu := Tribu2;
end;
{ Set }
procedure setTribu_nom (Joueur : TJoueur ; nom : String);
begin
if Joueur = Joueur1 then Tribu.nom := nom
else if Joueur = Joueur2 then Tribu2.nom := nom;
end;
procedure setTribu_numJour (Joueur : TJoueur ; numJour : Integer);
begin
if Joueur = Joueur1 then Tribu.numJour := numjour
else if Joueur = Joueur2 then Tribu2.numJour := numJour;
end;
procedure setTribu_niveauMax (Joueur : TJoueur ; niveauMax : Integer);
begin
if Joueur = Joueur1 then Tribu.niveauMax := niveauMax
else if Joueur = Joueur2 then Tribu2.niveauMax := niveauMax;
end;
procedure setTribu_archetype (Joueur : TJoueur ; archetype : String);
begin
if Joueur = Joueur1 then Tribu.archetype := archetype
else if Joueur = Joueur2 then Tribu2.archetype := archetype;
end;
procedure setTribu_difficulte (Joueur : TJoueur ; difficulte : String);
begin
if Joueur = Joueur1 then Tribu.difficulte := difficulte
else if Joueur = Joueur2 then Tribu2.difficulte := difficulte;
end;
procedure setTribu_victoires (Joueur : TJoueur ; victoires : Integer);
begin
if Joueur = Joueur1 then Tribu.victoires := victoires
else if Joueur = Joueur2 then Tribu2.victoires := victoires;
end;
procedure setTribu_defaites (Joueur : TJoueur ; defaites : Integer);
begin
if Joueur = Joueur1 then Tribu.defaites := defaites
else if Joueur = Joueur2 then Tribu2.defaites := defaites;
end;
procedure setTribu_limDefaites (Joueur : TJoueur ; limDefaites : Integer);
begin
if Joueur = Joueur1 then Tribu.limDefaites := limDefaites
else if Joueur = Joueur2 then Tribu2.limDefaites := limDefaites;
end;
procedure setTribu_ptsRecrutement (Joueur : TJoueur ; ptsRecrutement : Integer);
begin
if Joueur = Joueur1 then Tribu.ptsRecrutement := ptsRecrutement
else if Joueur = Joueur2 then Tribu2.ptsRecrutement := ptsRecrutement;
end;
procedure setTribu_ptsRecrutementJour (Joueur : TJoueur ; ptsRecrutementJour : Integer);
begin
if Joueur = Joueur1 then Tribu.ptsRecrutementJour := ptsRecrutementJour
else if Joueur = Joueur2 then Tribu2.ptsRecrutementJour := ptsRecrutementJour;
end;
// ELEVAGE
{ Get }
function getElevage(Joueur : TJoueur) : TElevage;
begin
if Joueur = Joueur1 then getElevage := Elevage
else if Joueur = Joueur2 then getElevage := Elevage2;
end;
{ Set }
procedure setElevage_nom (Joueur : TJoueur ; nom : String);
begin
if Joueur = Joueur1 then Elevage.nom := nom
else if Joueur = Joueur2 then Elevage2.nom := nom;
end;
procedure setElevage_population (Joueur : TJoueur ; population : Integer);
begin
if Joueur = Joueur1 then Elevage.population := population
else if Joueur = Joueur2 then Elevage2.population := population;
end;
procedure setElevage_construction (Joueur : TJoueur ; construction : Boolean);
begin
if Joueur = Joueur1 then Elevage.construction := construction
else if Joueur = Joueur2 then Elevage2.construction := construction;
end;
procedure setElevage_bonheur (Joueur : TJoueur ; bonheur : Integer);
begin
if Joueur = Joueur1 then Elevage.bonheur := bonheur
else if Joueur = Joueur2 then Elevage2.bonheur := bonheur;
end;
procedure setElevage_facteurBonheur (Joueur : TJoueur ; facteurBonheur : Real);
begin
if Joueur = Joueur1 then Elevage.facteurBonheur := facteurBonheur
else if Joueur = Joueur2 then Elevage2.facteurBonheur := facteurBonheur;
end;
procedure setElevage_savoirJourAbsolu (Joueur : TJoueur ; savoirJourAbsolu : Integer);
begin
if Joueur = Joueur1 then Elevage.savoirJourAbsolu := savoirJourAbsolu
else if Joueur = Joueur2 then Elevage2.savoirJourAbsolu := savoirJourAbsolu;
end;
procedure setElevage_savoirJour (Joueur : TJoueur ; savoirJour : Integer);
begin
if Joueur = Joueur1 then Elevage.savoirJour := savoirJour
else if Joueur = Joueur2 then Elevage2.savoirJour := savoirJour;
end;
procedure setElevage_savoirAcquis (Joueur : TJoueur ; savoirAcquis : Integer);
begin
if Joueur = Joueur1 then Elevage.savoirAcquis := savoirAcquis
else if Joueur = Joueur2 then Elevage2.savoirAcquis := savoirAcquis;
end;
procedure setElevage_facteurCroissance (Joueur : TJoueur ; facteurCroissance : Integer);
begin
if Joueur = Joueur1 then Elevage.facteurCroissance := facteurCroissance
else if Joueur = Joueur2 then Elevage2.facteurCroissance := facteurCroissance;
end;
procedure setElevage_seuilCroissance (Joueur : TJoueur ; seuilCroissance : Integer);
begin
if Joueur = Joueur1 then Elevage.seuilCroissance := seuilCroissance
else if Joueur = Joueur2 then Elevage2.seuilCroissance := seuilCroissance;
end;
procedure setElevage_nbJourAvCroissance (Joueur : TJoueur ; nbJourAvCroissance : Integer);
begin
if Joueur = Joueur1 then Elevage.nbJourAvCroissance := nbJourAvCroissance
else if Joueur = Joueur2 then Elevage2.nbJourAvCroissance := nbJourAvCroissance;
end;
procedure setElevage_equationsJour (Joueur : TJoueur ; equationsJour : Integer);
begin
if Joueur = Joueur1 then Elevage.equationsJour := equationsJour
else if Joueur = Joueur2 then Elevage2.equationsJour := equationsJour;
end;
procedure setElevage_equationsResolues (Joueur : TJoueur ; equationsResolues : Integer);
begin
if Joueur = Joueur1 then Elevage.equationsResolues := equationsResolues
else if Joueur = Joueur2 then Elevage2.equationsResolues := equationsResolues;
end;
// UNIVERSITE
{ Get }
function getUniversite(Joueur : TJoueur) : TBatiment;
begin
if Joueur = Joueur1 then getUniversite := Universite
else if Joueur = Joueur2 then getUniversite := Universite2;
end;
{ Set }
procedure setUniversite_niveau (Joueur : TJoueur ; niveau : Integer);
begin
if Joueur = Joueur1 then Universite.niveau := niveau
else if Joueur = Joueur2 then Universite2.niveau := niveau;
end;
procedure setUniversite_construction (Joueur : TJoueur ; construction : Boolean);
begin
if Joueur = Joueur1 then Universite.construction := construction
else if Joueur = Joueur2 then Universite2.construction := construction;
end;
// CENTRE DE RECHERCHES
{ Get }
function getCDR(Joueur : TJoueur) : TBatiment;
begin
if Joueur = Joueur1 then getCDR := CDR
else if Joueur = Joueur2 then
end;
{ Set }
procedure setCDR_niveau (Joueur : TJoueur ; niveau : Integer);
begin
if Joueur = Joueur1 then CDR.niveau := niveau
else if Joueur = Joueur2 then CDR2.niveau := niveau;
end;
procedure setCDR_construction (Joueur : TJoueur ; construction : Boolean);
begin
if Joueur = Joueur1 then CDR.construction := construction
else if Joueur = Joueur2 then CDR2.construction := construction;
end;
// LABORATOIRE
{ Get }
function getLaboratoire(Joueur : TJoueur) : TBatiment;
begin
if Joueur = Joueur1 then getLaboratoire := Laboratoire
else if Joueur = Joueur2 then getLaboratoire := Laboratoire2;
end;
{ Set }
procedure setLaboratoire_niveau (Joueur : TJoueur ; niveau : Integer);
begin
if Joueur = Joueur1 then Laboratoire.niveau := niveau
else if Joueur = Joueur2 then Laboratoire2.niveau := niveau;
end;
procedure setLaboratoire_construction (Joueur : TJoueur ; construction : Boolean);
begin
if Joueur = Joueur1 then Laboratoire.construction := construction
else if Joueur = Joueur2 then Laboratoire2.construction := construction;
end;
// ENCLOS
{ Get }
function getEnclos(Joueur : TJoueur) : TBatiment;
begin
if Joueur = Joueur1 then getEnclos := Enclos
else if Joueur = Joueur2 then getEnclos := Enclos2;
end;
{ Set }
procedure setEnclos_niveau (Joueur : TJoueur ; niveau : Integer);
begin
if Joueur = Joueur1 then Enclos.niveau := niveau
else if Joueur = Joueur2 then Enclos2.niveau := niveau;
end;
procedure setEnclos_construction (Joueur : TJoueur ; construction : Boolean);
begin
if Joueur = Joueur1 then Enclos.construction := construction
else if Joueur = Joueur2 then Enclos2.construction := construction;
end;
// BIBLIOHÈQUE
{ Get }
function getBibliotheque(Joueur : TJoueur) : TBatiment;
begin
if Joueur = Joueur1 then getBibliotheque := Bibliotheque
else if Joueur = Joueur2 then getBibliotheque := Bibliotheque2;
end;
{ Set }
procedure setBibliotheque_niveau (Joueur : TJoueur ; niveau : Integer);
begin
if Joueur = Joueur1 then Bibliotheque.niveau := niveau
else if Joueur = Joueur2 then Bibliotheque2.niveau := niveau
end;
procedure setBibliotheque_construction (Joueur : TJoueur ; construction : Boolean);
begin
if Joueur = Joueur1 then Bibliotheque.construction := construction
else if Joueur = Joueur2 then Bibliotheque2.construction := construction
end;
// ARCHIVES
{ Get }
function getArchives(Joueur : TJoueur) : TBatiment;
begin
if Joueur = Joueur1 then getArchives := Archives
else if Joueur = Joueur2 then getArchives := Archives2;
end;
{ Set }
procedure setArchives_niveau (Joueur : TJoueur ; niveau : Integer);
begin
if Joueur = Joueur1 then Archives.niveau := niveau
else if Joueur = Joueur2 then Archives2.niveau := niveau;
end;
procedure setArchives_construction (Joueur : TJoueur ; construction : Boolean);
begin
if Joueur = Joueur1 then Archives.construction := construction
else if Joueur = Joueur2 then Archives2.construction := construction;
end;
// LAMA
{ Get }
function getLama(Joueur : TJoueur) : TUnite;
begin
if Joueur = Joueur1 then getLama := Lama
else if Joueur = Joueur2 then getLama := Lama2
end;
{ Set }
procedure setLama_nb(Joueur : TJoueur ; nb : Integer);
begin
if Joueur = Joueur1 then Lama.nb := nb
else if Joueur = Joueur2 then Lama2.nb := nb;
end;
// ALPAGA
{ Get }
function getAlpaga(Joueur : TJoueur) : TUnite;
begin
if Joueur = Joueur1 then getAlpaga := Alpaga
else if Joueur = Joueur2 then getAlpaga := Alpaga2;
end;
{ Set }
procedure setAlpaga_nb(Joueur : TJoueur ; nb : Integer);
begin
if Joueur = Joueur1 then Alpaga.nb := nb
else if Joueur = Joueur2 then Alpaga2.nb := nb;
end;
// GUANACO
{ Get }
function getGuanaco(Joueur : TJoueur) : TUnite;
begin
if Joueur = Joueur1 then getGuanaco := Guanaco
else if Joueur = Joueur2 then getGuanaco := Guanaco2;
end;
{ Set }
procedure setGuanaco_nb(Joueur : TJoueur ; nb : Integer);
begin
if Joueur = Joueur1 then Guanaco.nb := nb
else if Joueur = Joueur2 then Guanaco2.nb := nb;
end;
{ INITIALISATION DES VARIABLES }
{ Les procédures suivantes servent à initialiser les variables de jeu. }
// TRIBU
procedure initTribu(Joueur : TJoueur);
begin
if Joueur = Joueur1 then
begin
with Tribu do
begin
nom := 'TribuParDefaut';
numJour := 1;
niveaumax := 3;
archetype := 'ArchetypeParDefaut';
difficulte := 'DifficulteParDefaut';
victoires := 0;
defaites := 0;
limDefaites := 4;
ptsRecrutement := 0;
ptsRecrutementJour := 0;
end;
end
else if Joueur = Joueur2 then
begin
with Tribu2 do
begin
nom := 'TribuParDefaut';
numJour := 1;
niveaumax := 3;
archetype := 'ArchetypeParDefaut';
difficulte := 'DifficulteParDefaut';
victoires := 0;
defaites := 0;
limDefaites := 4;
ptsRecrutement := 0;
ptsRecrutementJour := 0;
end;
end;
end;
// Elevage
procedure initElevage(Joueur : TJoueur);
begin
if Joueur = Joueur1 then
begin
with Elevage do
begin
nom := 'ElevageParDefaut';
population := 1;
construction := False;
bonheur := 1;
facteurBonheur := 1 - population/10 + bonheur/10;
savoirJourAbsolu := 20;
savoirJour := round( (savoirJourAbsolu - population*10) * facteurBonheur );
savoirAcquis := 0;
facteurCroissance := 100;
seuilCroissance := population * facteurCroissance;
nbJourAvCroissance := seuilCroissance div savoirJour;
equationsJour := 20;
equationsResolues := 0;
end;
end
else if Joueur = Joueur2 then
begin
with Elevage2 do
begin
nom := 'ElevageParDefaut';
population := 1;
construction := False;
bonheur := 1;
facteurBonheur := 1 - population/10 + bonheur/10;
savoirJourAbsolu := 20;
savoirJour := round( (savoirJourAbsolu - population*10) * facteurBonheur );
savoirAcquis := 0;
facteurCroissance := 100;
seuilCroissance := population * facteurCroissance;
nbJourAvCroissance := seuilCroissance div savoirJour;
equationsJour := 20;
equationsResolues := 0;
end;
end;
end;
// BATIMENTS
{ Université }
procedure initUniversite(Joueur : TJoueur);
begin
if Joueur = Joueur1 then
begin
with Universite do
begin
nom := 'Université';
niveau := 0;
construction := False;
PALIERS[0] := 0;
PALIERS[1] := 400;
PALIERS[2] := 1800;
PALIERS[3] := 2800;
BONUS[0] := 0;
BONUS[1] := 20;
BONUS[2] := 60;
BONUS[3] := 90;
end;
end
else if Joueur = Joueur2 then
begin
with Universite2 do
begin
nom := 'Université';
niveau := 0;
construction := False;
PALIERS[0] := 0;
PALIERS[1] := 400;
PALIERS[2] := 1800;
PALIERS[3] := 2800;
BONUS[0] := 0;
BONUS[1] := 20;
BONUS[2] := 60;
BONUS[3] := 90;
end;
end;
end;
{ Centre de recherches }
procedure initCDR(Joueur : TJoueur);
begin
if Joueur = Joueur1 then
begin
with CDR do
begin
nom := 'Centre de recherches';
niveau := 0;
construction := False;
PALIERS[0] := 0;
PALIERS[1] := 800;
PALIERS[2] := 1600;
PALIERS[3] := 3000;
BONUS[0] := 0;
BONUS[1] := 10;
BONUS[2] := 40;
BONUS[3] := 70;
end;
end;
if Joueur = Joueur2 then
begin
with CDR2 do
begin
nom := 'Centre de recherches';
niveau := 0;
construction := False;
PALIERS[0] := 0;
PALIERS[1] := 800;
PALIERS[2] := 1600;
PALIERS[3] := 3000;
BONUS[0] := 0;
BONUS[1] := 10;
BONUS[2] := 40;
BONUS[3] := 70;
end;
end;
end;
{ Laboratoire }
procedure initLaboratoire(Joueur : TJoueur);
begin
if Joueur = Joueur1 then
begin
with Laboratoire do
begin
nom := 'Laboratoire';
niveau := 0;
construction := False;
PALIERS[0] := 0;
PALIERS[1] := 800;
PALIERS[2] := 1600;
PALIERS[3] := 3000;
BONUS[0] := 0;
BONUS[1] := 30;
BONUS[2] := 60;
BONUS[3] := 90;
end;
end
else if Joueur = Joueur2 then
begin
with Laboratoire2 do
begin
nom := 'Laboratoire';
niveau := 0;
construction := False;
PALIERS[0] := 0;
PALIERS[1] := 800;
PALIERS[2] := 1600;
PALIERS[3] := 3000;
BONUS[0] := 0;
BONUS[1] := 30;
BONUS[2] := 60;
BONUS[3] := 90;
end;
end;
end;
{ Enclos }
procedure initEnclos(Joueur : TJoueur);
begin
if Joueur = Joueur1 then
begin
with Enclos do
begin
nom := 'Enclos';
niveau := 0;
construction := False;
PALIERS[0] := 0;
PALIERS[1] := 800;
PALIERS[2] := 2400;
PALIERS[3] := 4800;
BONUS[0] := 0;
BONUS[1] := 8;
BONUS[2] := 16;
BONUS[3] := 24;
end;
end
else if Joueur = Joueur2 then
begin
with Enclos2 do
begin
nom := 'Enclos';
niveau := 0;
construction := False;
PALIERS[0] := 0;
PALIERS[1] := 800;
PALIERS[2] := 2400;
PALIERS[3] := 4800;
BONUS[0] := 0;
BONUS[1] := 10;
BONUS[2] := 20;
BONUS[3] := 30;
end;
end;
end;
{ Bibliothèque }
procedure initBibliotheque(Joueur : TJoueur);
begin
if Joueur = Joueur1 then
begin
with Bibliotheque do
begin
nom := 'Bibliothèque';
niveau := 0;
construction := False;
PALIERS[0] := 0;
PALIERS[1] := 400;
PALIERS[2] := 1800;
PALIERS[3] := 2800;
BONUS[0] := 1;
BONUS[1] := 4;
BONUS[2] := 6;
BONUS[3] := 8;
end;
end;
if Joueur = Joueur2 then
begin
with Bibliotheque2 do
begin
nom := 'Bibliothèque';
niveau := 0;
construction := False;
PALIERS[0] := 0;
PALIERS[1] := 400;
PALIERS[2] := 1800;
PALIERS[3] := 2800;
BONUS[0] := 1;
BONUS[1] := 4;
BONUS[2] := 6;
BONUS[3] := 8;
end;
end;
end;
{ Archives }
procedure initArchives(Joueur : TJoueur);
begin
if Joueur = Joueur1 then
begin
with Archives do
begin
nom := 'Archives';
niveau := 0;
construction := False;
PALIERS[0] := 0;
PALIERS[1] := 800;
PALIERS[2] := 1800;
PALIERS[3] := 3000;
BONUS[0] := 4;
BONUS[1] := 5;
BONUS[2] := 6;
BONUS[3] := 7;
end;
end
else if Joueur = Joueur2 then
begin
with Archives2 do
begin
nom := 'Archives';
niveau := 0;
construction := False;
PALIERS[0] := 0;
PALIERS[1] := 800;
PALIERS[2] := 1800;
PALIERS[3] := 3000;
BONUS[0] := 4;
BONUS[1] := 5;
BONUS[2] := 6;
BONUS[3] := 7;
end;
end;
end;
// UNITES
{ Lama }
procedure initLama(Joueur : TJoueur);
begin
if Joueur = Joueur1 then
begin
with Lama do
begin
nom := 'Lama';
nb := 30;
ptsAttaque := 1;
prix := 1;
end;
end
else if Joueur = Joueur2 then
begin
with Lama2 do
begin
nom := 'Lama';
nb := 30;
ptsAttaque := 1;
prix := 1;
end;
end;
end;
{ Alpaga }
procedure initAlpaga(Joueur : TJoueur);
begin
if Joueur = Joueur1 then
begin
with Alpaga do
begin
nom := 'Alpaga';
nb := 10;
ptsAttaque := 2;
prix := 2;
end;
end
else if Joueur = Joueur2 then
begin
with Alpaga2 do
begin
nom := 'Alpaga';
nb := 10;
ptsAttaque := 2;
prix := 2;
end;
end;
end;
{ Guanaco }
procedure initGuanaco(Joueur : TJoueur);
begin
if Joueur = Joueur1 then
begin
with Guanaco do
begin
nom := 'Guanaco';
nb := 3;
ptsAttaque := 4;
prix := 3;
end;
end
else if Joueur = Joueur2 then
begin
with Guanaco2 do
begin
nom := 'Guanaco';
nb := 3;
ptsAttaque := 4;
prix := 3;
end;
end;
end;
// INITIALISATION DU JOUEUR (regroupe tous les init)
procedure initJoueur(Joueur : TJoueur);
begin
initTribu(Joueur);
initElevage(Joueur);
initUniversite(Joueur);
initCDR(Joueur);
initLaboratoire(Joueur);
initEnclos(Joueur);
initBibliotheque(Joueur);
initArchives(Joueur);
initLama(Joueur);
initAlpaga(Joueur);
initGuanaco(Joueur);
end;
{ ARCHETYPE & DIFFICULTE }
{ Les procédures suivantes modifient certaines propriétés en fonction
de l'archétype de Tribu et de la difficulté choisis par le joueur. }
// Applique les changements liés à l'archétype de la Tribu
procedure appliquerArchetype;
begin
if Joueur = Joueur1 then
begin
// Archétype ALGÉBRISTE
if (Tribu.archetype = 'Algébriste') then
begin
{ Il ne se passe rien quand on joue Algébriste ! :^( }
end;
// Archétype GÉOMÈTRE
{ Le bonheur reste constant }
if (Tribu.archetype = 'Géomètre') then
begin
Elevage.facteurBonheur := 1;
end;
// Archétype BORÉLIENNE
{ L'armée initiale est renforcée }
if (Tribu.archetype = 'Borélienne') then
begin
Lama.nb := 100;
Alpaga.nb := 40;
Guanaco.nb := 10;
end;
// Archétype ARCHIVISTE
{ L'archétype Archiviste bénéficie d'un bonus de défaites tolérées }
if (Tribu.archetype = 'Archiviste') then
begin
with Archives do
begin
BONUS[0] := 7;
BONUS[1] := 8;
BONUS[2] := 9;
BONUS[3] := 10;
end;
Tribu.limDefaites := Archives.BONUS[0];
end;
// Archétype Probabiliste
{ Probabilité d'assaut réduite }
if (Tribu.archetype = 'Probabiliste') then
begin
{ Le changement intervient au niveau de la procédure tourSuivant,
où la portée du nb aléatoire généré est plus grande. }
end;
end
else if Joueur = Joueur2 then
begin
// Archétype ALGÉBRISTE
if (Tribu2.archetype = 'Algébriste') then
begin
{ Il ne se passe rien quand on joue Algébriste ! :^( }
end;
// Archétype GÉOMÈTRE
{ Le bonheur reste constant }
if (Tribu2.archetype = 'Géomètre') then
begin
Elevage2.facteurBonheur := 1;
end;
// Archétype BORÉLIENNE
{ L'armée initiale est renforcée }
if (Tribu2.archetype = 'Borélienne') then
begin
Lama2.nb := 300;
Alpaga2.nb := 200;
Guanaco2.nb := 100;
end;
// Archétype ARCHIVISTE
{ L'archétype Archiviste bénéficie d'un bonus de défaites tolérées }
if (Tribu2.archetype = 'Archiviste') then
begin
with Archives2 do
begin
BONUS[0] := 7;
BONUS[1] := 8;
BONUS[2] := 9;
BONUS[3] := 10;
end;
Tribu2.limDefaites := Archives.BONUS[0];
end;
// Archétype Probabiliste
{ Probabilité d'assaut réduite }
if (Tribu2.archetype = 'Probabiliste') then
begin
{ Le changement intervient au niveau de la procédure tourSuivant,
où la portée du nb aléatoire généré est plus grande. }
end;
end;
end;
// Applique les changements liés à la difficulté de la partie
procedure appliquerDifficulte;
begin
{ ATTENTION : La difficulté influe aussi sur le nb d'unités présentes dans les pâturages ennemis.
Se référer à la procédure genererEnnemis() de l'unit EcranCombat. }
if Joueur = Joueur1 then
begin
// Difficulté Linéaire
if (Tribu.difficulte = 'Linéaire') then
begin
{ Coûts de construction }
// Université
with Universite do
begin
PALIERS[0] := 0;
PALIERS[1] := 200;
PALIERS[2] := 800;
PALIERS[3] := 1600;
end;
// Centre de recherches
with CDR do
begin
PALIERS[0] := 0;
PALIERS[1] := 600;
PALIERS[2] := 1200;
PALIERS[3] := 2400;
end;
// Laboratoire
with Laboratoire do
begin
PALIERS[0] := 0;
PALIERS[1] := 600;
PALIERS[2] := 1200;
PALIERS[3] := 2400;
end;
// Enclos
with Enclos do
begin
PALIERS[0] := 0;
PALIERS[1] := 600;
PALIERS[2] := 1600;
PALIERS[3] := 2200;
end;
// Bibliothèque
with Bibliotheque do
begin
PALIERS[0] := 0;
PALIERS[1] := 200;
PALIERS[2] := 800;
PALIERS[3] := 1600;
end;
// Archives
with Archives do
begin
PALIERS[0] := 0;
PALIERS[1] := 600;
PALIERS[2] := 1200;
PALIERS[3] := 2600;
end;
end;
// Difficulté Appliqué
if (Tribu.difficulte = 'Appliqué') then
begin
{ Coûts de construction }
// Université
with Universite do
begin
PALIERS[0] := 0;
PALIERS[1] := 400;
PALIERS[2] := 1800;
PALIERS[3] := 2800;
end;
// Centre de recherches
with CDR do
begin
PALIERS[0] := 0;
PALIERS[1] := 800;
PALIERS[2] := 1600;
PALIERS[3] := 3000;
end;
// Laboratoire
with Laboratoire do
begin
PALIERS[0] := 0;
PALIERS[1] := 800;
PALIERS[2] := 1600;
PALIERS[3] := 3000;
end;
// Enclos
with Enclos do
begin
PALIERS[0] := 0;
PALIERS[1] := 800;
PALIERS[2] := 2400;
PALIERS[3] := 4800;
end;
// Bibliothèque
with Bibliotheque do
begin
PALIERS[0] := 0;
PALIERS[1] := 400;
PALIERS[2] := 1800;
PALIERS[3] := 2800;
end;
// Archives
with Archives do
begin
PALIERS[0] := 0;
PALIERS[1] := 800;
PALIERS[2] := 1800;
PALIERS[3] := 3000;
end;
end;
// Difficulté Quantique
if (Tribu.difficulte = 'Quantique') then
begin
{ Coûts de construction }
// Université
with Universite do
begin
PALIERS[0] := 0;
PALIERS[1] := 600;
PALIERS[2] := 2200;
PALIERS[3] := 3200;
end;
// Centre de recherches
with CDR do
begin
PALIERS[0] := 0;
PALIERS[1] := 1000;
PALIERS[2] := 2200;
PALIERS[3] := 3400;
end;
// Laboratoire
with Laboratoire do
begin
PALIERS[0] := 0;
PALIERS[1] := 1000;
PALIERS[2] := 2200;
PALIERS[3] := 3400;
end;
// Enclos
with Enclos do
begin
PALIERS[0] := 0;
PALIERS[1] := 1000;
PALIERS[2] := 2800;
PALIERS[3] := 5600;
end;
// Bibliothèque
with Bibliotheque do
begin
PALIERS[0] := 0;
PALIERS[1] := 600;
PALIERS[2] := 2200;
PALIERS[3] := 3200;
end;
// Archives
with Archives do
begin
PALIERS[0] := 0;
PALIERS[1] := 1000;
PALIERS[2] := 2200;
PALIERS[3] := 3400;
end;
end;
end
else if Joueur = Joueur2 then
begin
// Difficulté Linéaire
if (Tribu2.difficulte = 'Linéaire') then
begin
{ Coûts de construction }
// Université
with Universite2 do
begin
PALIERS[0] := 0;
PALIERS[1] := 200;
PALIERS[2] := 800;
PALIERS[3] := 1600;
end;
// Centre de recherches
with CDR2 do
begin
PALIERS[0] := 0;
PALIERS[1] := 600;
PALIERS[2] := 1200;
PALIERS[3] := 2400;
end;
// Laboratoire
with Laboratoire2 do
begin
PALIERS[0] := 0;
PALIERS[1] := 600;
PALIERS[2] := 1200;
PALIERS[3] := 2400;
end;
// Enclos
with Enclos2 do
begin
PALIERS[0] := 0;
PALIERS[1] := 600;
PALIERS[2] := 1600;
PALIERS[3] := 2200;
end;
// Bibliothèque
with Bibliotheque2 do
begin
PALIERS[0] := 0;
PALIERS[1] := 200;
PALIERS[2] := 800;
PALIERS[3] := 1600;
end;
// Archives
with Archives2 do
begin
PALIERS[0] := 0;
PALIERS[1] := 600;
PALIERS[2] := 1200;
PALIERS[3] := 2600;
end;
end;
// Difficulté Appliqué
if (Tribu2.difficulte = 'Appliqué') then
begin
{ Coûts de construction }
// Université
with Universite2 do
begin
PALIERS[0] := 0;
PALIERS[1] := 400;
PALIERS[2] := 1800;
PALIERS[3] := 2800;
end;
// Centre de recherches
with CDR2 do
begin
PALIERS[0] := 0;
PALIERS[1] := 800;
PALIERS[2] := 1600;
PALIERS[3] := 3000;
end;
// Laboratoire
with Laboratoire2 do
begin
PALIERS[0] := 0;
PALIERS[1] := 800;
PALIERS[2] := 1600;
PALIERS[3] := 3000;
end;
// Enclos
with Enclos2 do
begin
PALIERS[0] := 0;
PALIERS[1] := 800;
PALIERS[2] := 2400;
PALIERS[3] := 4800;
end;
// Bibliothèque
with Bibliotheque2 do
begin
PALIERS[0] := 0;
PALIERS[1] := 400;
PALIERS[2] := 1800;
PALIERS[3] := 2800;
end;
// Archives
with Archives2 do
begin
PALIERS[0] := 0;
PALIERS[1] := 800;
PALIERS[2] := 1800;
PALIERS[3] := 3000;
end;
end;
// Difficulté Quantique
if (Tribu2.difficulte = 'Quantique') then
begin
{ Coûts de construction }
// Université
with Universite2 do
begin
PALIERS[0] := 0;
PALIERS[1] := 600;
PALIERS[2] := 2200;
PALIERS[3] := 3200;
end;
// Centre de recherches
with CDR2 do
begin
PALIERS[0] := 0;
PALIERS[1] := 1000;
PALIERS[2] := 2200;
PALIERS[3] := 3400;
end;
// Laboratoire
with Laboratoire2 do
begin
PALIERS[0] := 0;
PALIERS[1] := 1000;
PALIERS[2] := 2200;
PALIERS[3] := 3400;
end;
// Enclos
with Enclos2 do
begin
PALIERS[0] := 0;
PALIERS[1] := 1000;
PALIERS[2] := 2800;
PALIERS[3] := 5600;
end;
// Bibliothèque
with Bibliotheque2 do
begin
PALIERS[0] := 0;
PALIERS[1] := 600;
PALIERS[2] := 2200;
PALIERS[3] := 3200;
end;
// Archives
with Archives2 do
begin
PALIERS[0] := 0;
PALIERS[1] := 1000;
PALIERS[2] := 2200;
PALIERS[3] := 3400;
end;
end;
end;
end;
end.
|
unit Odontologia.Modelo.Interfaces;
interface
uses
Odontologia.Modelo.Agenda.Interfaces,
Odontologia.Modelo.Ciudad.Interfaces,
Odontologia.Modelo.Departamento.Interfaces,
Odontologia.Modelo.Empresa.Interfaces,
Odontologia.Modelo.EmpresaTipo.Interfaces,
Odontologia.Modelo.Estado.Interfaces,
Odontologia.Modelo.Estado.Cita.Interfaces,
Odontologia.Modelo.Medico.Interfaces,
Odontologia.Modelo.Paciente.Interfaces,
Odontologia.Modelo.Pais.Interfaces,
Odontologia.Modelo.Pedido.Interfaces,
Odontologia.Modelo.Producto.Interfaces,
Odontologia.Modelo.Usuario.Interfaces;
type
iModel = interface
['{0F7A1B03-B62A-4EBE-A93C-FAD6EC966E64}']
function Agenda : iModelAgenda;
function Ciudad : iModelCiudad;
function Departamento : iModelDepartamento;
function Empresa : iModelEmpresa;
function EmpresaTipo : iModelEmpresaTipo;
function Estado : iModelEstado;
function EstadoCita : iModelEstadoCita;
function Medico : iModelMedico;
function Paciente : iModelPaciente;
function Pais : iModelPais;
function Pedido : iModelPedido;
function PedidoItem : iModelPedidoItem;
function Producto : iModelProducto;
function Usuario : iModelUsuario;
end;
implementation
end.
|
unit UnitCommonProcedures;
interface
uses
Windows,
Controls,
StdCtrls,
Graphics,
ComCtrls,
StrUtils;
type
TFormBase = class
public
const CorEntrada = $00E7EC7D;
procedure MudarDeCorEnter(Sender: TObject);
procedure MudarDeCorExit(Sender: TObject);
end;
const
NumeroDeVariaveis = 20; // um número maior que o número de colunas do listview...
type
TSplit = array [0..NumeroDeVariaveis] of string;
var
FormBase: TFormBase;
Function ReplaceString(ToBeReplaced, ReplaceWith : string; TheString :string): string;
function justr(s : string; tamanho : integer) : string;
function justl(s : string; tamanho : integer) : string;
function FileSizeToStr(SizeInBytes: int64): string;
function SplitString(Str, Delimitador: string): TSplit;
function CheckValidName(Str: string): boolean;
function ShowTime(DayChar: Char = '/'; DivChar: Char = ' ';
HourChar: Char = ':'): String;
implementation
function IntToStr(i: Int64): WideString;
begin
Str(i, Result);
end;
function StrToInt(S: WideString): Int64;
var
E: integer;
begin
Val(S, Result, E);
end;
function ShowTime(DayChar: Char = '/'; DivChar: Char = ' ';
HourChar: Char = ':'): String;
var
SysTime: TSystemTime;
Month, Day, Hour, Minute, Second: String;
begin
GetLocalTime(SysTime);
Month := inttostr(SysTime.wMonth);
Day := inttostr(SysTime.wDay);
Hour := inttostr(SysTime.wHour);
Minute := inttostr(SysTime.wMinute);
Second := inttostr(SysTime.wSecond);
if length(Month) = 1 then
Month := '0' + Month;
if length(Day) = 1 then
Day := '0' + Day;
if length(Hour) = 1 then
Hour := '0' + Hour;
if Hour = '24' then
Hour := '00';
if length(Minute) = 1 then
Minute := '0' + Minute;
if length(Second) = 1 then
Second := '0' + Second;
Result := Day + DayChar + Month + DayChar + inttostr(SysTime.wYear)
+ DivChar + Hour + HourChar + Minute + HourChar + Second;
end;
procedure TFormBase.MudarDeCorEnter(Sender: TObject);
var
Ctrl: TWinControl;
begin
if (Ctrl is TEdit) then
TEdit(Ctrl).Color := CorEntrada;
if (Ctrl is TListView) then
TListView(Ctrl).Color := CorEntrada;
if (Ctrl is TMemo) then
TMemo(Ctrl).Color := CorEntrada;
if (Ctrl is TRichEdit) then
TRichEdit(Ctrl).Color := CorEntrada;
if (Ctrl is TComboBox) then
TComboBox(Ctrl).Color := CorEntrada;
end;
procedure TFormBase.MudarDeCorExit(Sender: TObject);
var
Ctrl: TWinControl;
begin
if (Ctrl is TEdit) then
TEdit(Ctrl).Color := clWindow;
if (Ctrl is TListView) then
TListView(Ctrl).Color := clWindow;
if (Ctrl is TMemo) then
TMemo(Ctrl).Color := clWindow;
if (Ctrl is TRichEdit) then
TRichEdit(Ctrl).Color := clWindow;
if (Ctrl is TComboBox) then
TComboBox(Ctrl).Color := clWindow;
end;
Function ReplaceString(ToBeReplaced, ReplaceWith : string; TheString :string):string;
var
Position: Integer;
LenToBeReplaced: Integer;
TempStr: String;
TempSource: String;
begin
LenToBeReplaced:=length(ToBeReplaced);
TempSource:=TheString;
TempStr:='';
repeat
position := posex(ToBeReplaced, TempSource);
if (position <> 0) then
begin
TempStr := TempStr + copy(TempSource, 1, position-1); //Part before ToBeReplaced
TempStr := TempStr + ReplaceWith; //Tack on replace with string
TempSource := copy(TempSource, position+LenToBeReplaced, length(TempSource)); // Update what's left
end else
begin
Tempstr := Tempstr + TempSource; // Tack on the rest of the string
end;
until (position = 0);
Result:=Tempstr;
end;
function justr(s : string; tamanho : integer) : string;
var i : integer;
begin
i := tamanho-length(s);
if i>0 then
s := DupeString(' ', i)+s;
justr := s;
end;
function justl(s : string; tamanho : integer) : string;
var i : integer;
begin
i := tamanho-length(s);
if i>0 then
s := s+DupeString(' ', i);
justl := s;
end;
function StrFormatByteSize(qdw: int64; pszBuf: PWideChar; uiBufSize: UINT): PWideChar; stdcall;
external 'shlwapi.dll' name 'StrFormatByteSizeW';
function FileSizeToStr(SizeInBytes: int64): string;
var
arrSize: PWideChar;
begin
GetMem(arrSize, MAX_PATH);
StrFormatByteSize(SizeInBytes, arrSize, MAX_PATH);
Result := string(arrSize);
FreeMem(arrSize, MAX_PATH);
end;
function CheckValidName(Str: string): boolean;
begin
result := false;
if (posex('\', Str) > 0) or
(posex('/', Str) > 0) or
(posex(':', Str) > 0) or
(posex('*', Str) > 0) or
(posex('?', Str) > 0) or
(posex('"', Str) > 0) or
(posex('<', Str) > 0) or
(posex('>', Str) > 0) or
(posex('|', Str) > 0) or
(posex('/', Str) > 0) then exit;
result := true;
end;
function SplitString(Str, Delimitador: string): TSplit;
var
i: integer;
TempStr: string;
begin
i := 0;
TempStr := Str;
if posex(Delimitador, TempStr) <= 0 then exit;
while (TempStr <> '') and (i <= NumeroDeVariaveis) do
begin
Result[i] := Copy(TempStr, 1, posex(Delimitador, TempStr) - 1);
delete(TempStr, 1, posex(Delimitador, TempStr) - 1);
delete(TempStr, 1, length(Delimitador));
inc(i);
end;
end;
initialization
FormBase := TFormBase.Create;
finalization
FormBase.Free;
end.
|
unit u_templates;
{$MODE Delphi}
interface
uses Classes, Values, SysUtils, Files, FileOperations, Misc_utils, GlobalVars, Windows;
type
TTemplate=class
Name,parent:String;
vals:TTPLValues;
desc:string;
bbox:TThingBox;
Constructor Create;
Destructor Destroy;override;
Function GetAsString:string;
Function ValsAsString:String;
end;
TTemplates=class(TList)
Constructor Create;
Function GetItem(n:integer):TTemplate;
Procedure SetItem(n:integer;v:TTemplate);
Property Items[n:integer]:TTemplate read GetItem write SetItem; default;
Procedure Clear;
Procedure LoadFromFile(const fname:string);
Procedure SaveToFile(const fname:string);
Function AddFromString(const s:string):Integer;
function GetAsString(n:integer):String;
Function IndexOfName(const name:string):integer;
Function GetTPLField(const tpl,field:string):TTPLValue;
Function GetNTPLField(ntpl:integer;const field:string):TTPLValue;
Procedure DeleteTemplate(n:integer);
Private
cbox:TThingBox;
cdesc:string;
names:TStringList;
end;
var
Templates:TTemplates;
implementation
uses Forms;
Constructor TTemplate.Create;
begin
vals:=TTPLValues.Create;
end;
Destructor TTemplate.Destroy;
var i:integer;
begin
for i:=0 to Vals.Count-1 do Vals[i].Free;
Vals.Free;
end;
Function TTemplate.GetAsString:string;
var i:integer;
begin
Result:=PadRight(Name,17)+' '+PadRight(Parent,17)+' ';
for i:=0 to Vals.count-1 do
With Vals[i] do Result:=Concat(Result,' ',Name,'=',AsString);
end;
Function TTemplate.ValsAsString:String;
var i:integer;
begin
result:='';
for i:=0 to Vals.count-1 do
With Vals[i] do Result:=Concat(Result,' ',Name,'=',AsString);
end;
Constructor TTemplates.Create;
begin
names:=TStringList.Create;
names.sorted:=true;
end;
Function TTemplates.GetItem(n:integer):TTemplate;
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('Template Index is out of bounds: %d',[n]);
Result:=TTemplate(List[n]);
end;
Procedure TTemplates.SetItem(n:integer;v:TTemplate);
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('Template Index is out of bounds: %d',[n]);
List[n]:=v;
end;
Procedure TTemplates.Clear;
var i:integer;
begin
Names.Clear;
for i:=0 to Templates.count-1 do Templates[i].Free;
Inherited Clear;
end;
Function TTemplates.IndexOfName(const name:string):integer;
var i:integer;
begin
Result:=-1;
i:=Names.IndexOf(name);
if i<>-1 then Result:=Integer(names.Objects[i]);
{ for i:=0 to count-1 do
if CompareText(Items[i].Name,name)=0 then
begin
Result:=i;
break;
end;}
end;
Procedure TTemplates.DeleteTemplate(n:integer);
var tpl:TTemplate;
i:integer;
begin
tpl:=GetItem(n);
i:=Names.IndexOf(tpl.name);
if i<>-1 then Names.Delete(i);
Delete(n);
tpl.free;
end;
Function TTemplates.AddFromString(const s:string):Integer;
var p,peq:integer;w:string;
tpl:TTemplate;
vl:TTPLValue;
begin
result:=-1;
p:=GetWord(s,1,w);
if w='' then exit;
if IndexOfName(w)<>-1 then exit;
tpl:=TTemplate.Create;
tpl.name:=w;
Result:=Add(tpl);
Names.AddObject(w,TObject(Result));
p:=GetWord(s,p,w); tpl.parent:=w;
While p<length(s) do
begin
p:=GetWord(s,p,w);
if w='' then continue;
peq:=Pos('=',w);
if peq=0 then continue;
vl:=TTPLValue.Create;
tpl.vals.Add(vl);
vl.Name:=Copy(w,1,peq-1);
vl.vtype:=GetTPLVType(vl.Name);
vl.atype:=GetTPLType(vl.Name);
vl.s:=Copy(w,peq+1,Length(w)-peq);
end;
tpl.bbox:=cbox;
tpl.desc:=cdesc;
FillChar(cbox,sizeof(cbox),0);
cdesc:='';
end;
Procedure TTemplates.LoadFromFile(const fname:string);
var t:TTextFile;
s,w:string;
f:TFile;
i,p:integer;
begin
try
f:=OpenFileRead(fname,0);
except
on Exception do
begin
MsgBox('Cannot open master template - '+fname,'Error',mb_ok);
Application.Terminate;
exit;
end;
end;
t:=TTextFile.CreateRead(f);
Clear;
Try
While not t.eof do
begin
T.Readln(s);
p:=getword(s,1,w);
if w='' then continue;
if w='#' then
begin
p:=getWord(s,p,w);
if CompareText(w,'DESC:')=0 then cdesc:=Trim(Copy(s,p,length(s)))
else if CompareText(w,'BBOX:')=0 then
With Cbox do SScanf(s,'# BBOX: %l %l %l %l %l %l',[@x1,@y1,@z1,@x2,@y2,@z2]);
end
else AddFromString(s);
end;
finally
for i:=0 to templates.count-1 do
with Templates[i] do
begin
{GetTPLField}
end;
t.FClose;
end;
end;
Function TTemplates.GetAsString(n:integer):String;
var l,i:integer;
begin
Result:=Items[n].GetAsString;
end;
Procedure TTemplates.SaveToFile(const fname:string);
var t:Textfile;
i:integer;
begin
AssignFile(t,fname); Rewrite(t);
Try
for i:=0 to Count-1 do
With Items[i] do
begin
Writeln(t,'# DESC: ',desc);
With bbox do Writeln(t,SPrintf('# BBOX: %.6f %.6f %.6f %.6f %.6f %.6f',[x1,y1,z1,x2,y2,z2]));
Writeln(t,Self.GetAsString(i));
end;
finally
CloseFile(t);
end;
end;
Function TTemplates.GetNTPLField(ntpl:integer;const field:string):TTPLValue;
begin
end;
Function TTemplates.GetTPLField(const tpl,field:string):TTPLValue;
var tp:TTemplate;
vl:TTPlValue;
i:integer;
ctpl:string;
n:integer;
begin
Result:=nil;
ctpl:=tpl;
n:=0;
Repeat
inc(n);
if n>=100 then exit;
i:=IndexOfName(ctpl);
if i=-1 then exit;
tp:=Items[i];
for i:=0 to tp.vals.count-1 do
begin
vl:=tp.Vals[i];
if CompareText(vl.name,field)=0 then
begin
result:=vl; exit;
end;
end;
ctpl:=tp.parent;
until CompareText(ctpl,'none')=0;
end;
Initialization
begin
InitValues;
Templates:=TTemplates.Create;
{templates.LoadFromFile(BaseDir+'jeddata\master.tpl');}
end;
Finalization
begin
Templates.Clear;
Templates.Free;
end;
end.
|
unit CCJSO_RefStatusSequence_Create;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,
UCCenterJournalNetZkz, ExtCtrls, StdCtrls, ActnList, ToolWin, ComCtrls,
DB, ADODB;
type
TRecRefStatusSequence = record
RN : integer;
SeqStatusName : string;
end;
type
TfrmCCJSO_RefStatusSequence_Create = class(TForm)
pnlControl: TPanel;
pnlFields: TPanel;
lblSeqStatusName: TLabel;
edSeqStatusName: TEdit;
pnlControl_Tool: TPanel;
pnlControl_Show: TPanel;
tbarControl: TToolBar;
aList: TActionList;
aSave: TAction;
aExit: TAction;
tbtbControl_Save: TToolButton;
tbtbControl_Exit: TToolButton;
spInsert: TADOStoredProc;
spUpdate: TADOStoredProc;
spMultiPly: TADOStoredProc;
procedure FormCreate(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure aSaveExecute(Sender: TObject);
procedure aExitExecute(Sender: TObject);
procedure edSeqStatusNameChange(Sender: TObject);
private
{ Private declarations }
bSignActive : boolean;
Mode : integer;
RecSession : TUserSession;
RecItem : TRecRefStatusSequence;
procedure ShowGets;
procedure ItemInsert(var IErr : integer; var SErr : string);
procedure ItemUpdate(var IErr : integer; var SErr : string);
procedure ItemMultiPly(var IErr : integer; var SErr : string);
public
{ Public declarations }
procedure SetRecSession(Parm : TUserSession);
procedure SetMode(Parm : integer);
procedure SetRecItem(Parm : TRecRefStatusSequence);
end;
const
cRefStatusSequenceCreate_Insert = 1;
cRefStatusSequenceCreate_Update = 2;
cRefStatusSequenceCreate_MultiPly = 3;
var
frmCCJSO_RefStatusSequence_Create: TfrmCCJSO_RefStatusSequence_Create;
implementation
uses
UMAIN;
const
cFormCaption = 'Последовательность статусов заказов ';
{$R *.dfm}
procedure TfrmCCJSO_RefStatusSequence_Create.FormCreate(Sender: TObject);
begin
{ Инициализация }
bSignActive := false;
Mode := 0;
end;
procedure TfrmCCJSO_RefStatusSequence_Create.FormActivate(Sender: TObject);
begin
if not bSignActive then begin
case Mode of
cRefStatusSequenceCreate_Insert: begin
self.Caption := cFormCaption + '(добавить)';
FCCenterJournalNetZkz.imgMain.GetIcon(27,self.Icon);
end;
cRefStatusSequenceCreate_Update: begin
self.Caption := cFormCaption + '(исправить)';
FCCenterJournalNetZkz.imgMain.GetIcon(229,self.Icon);
edSeqStatusName.Text := RecItem.SeqStatusName;
end;
cRefStatusSequenceCreate_MultiPly: begin
self.Caption := cFormCaption + '(размножить)';
FCCenterJournalNetZkz.imgMain.GetIcon(373,self.Icon);
edSeqStatusName.Text := RecItem.SeqStatusName;
end;
end;
{ Форма активна }
bSignActive := true;
ShowGets;
end;
end;
procedure TfrmCCJSO_RefStatusSequence_Create.ShowGets;
begin
if bSignActive then begin
{ Пустое значение }
if length(trim(edSeqStatusName.Text)) = 0
then edSeqStatusName.Color := clYellow
else edSeqStatusName.Color := clWindow;
{ Доступ к сохранению }
if (length(trim(edSeqStatusName.Text)) = 0)
or (trim(edSeqStatusName.Text) = RecItem.SeqStatusName)
then aSave.Enabled := false
else aSave.Enabled := true;
end;
end;
procedure TfrmCCJSO_RefStatusSequence_Create.SetRecSession(Parm : TUserSession); begin RecSession := Parm; end;
procedure TfrmCCJSO_RefStatusSequence_Create.SetMode(Parm : integer); begin Mode := Parm; end;
procedure TfrmCCJSO_RefStatusSequence_Create.SetRecItem(Parm : TRecRefStatusSequence); begin recItem := Parm; end;
procedure TfrmCCJSO_RefStatusSequence_Create.aSaveExecute(Sender: TObject);
var
IErr : integer;
SErr : string;
begin
if MessageDLG('Подтвердите выполнение действия',mtConfirmation,[mbYes,mbNo],0) = mrNo then exit;
IErr := 0;
SErr := '';
case Mode of
cRefStatusSequenceCreate_Insert: ItemInsert(IErr,SErr);
cRefStatusSequenceCreate_Update: ItemUpdate(IErr,SErr);
cRefStatusSequenceCreate_MultiPly: ItemMultiPly(IErr,SErr);
end;
if IErr = 0 then self.Close;
ShowGets;
end;
procedure TfrmCCJSO_RefStatusSequence_Create.ItemInsert(var IErr : integer; var SErr : string);
begin
try
spInsert.Parameters.ParamValues['@USER'] := RecSession.CurrentUser;
spInsert.Parameters.ParamValues['@Descr'] := edSeqStatusName.Text;
spInsert.ExecProc;
IErr := spInsert.Parameters.ParamValues['@RETURN_VALUE'];
if IErr <> 0 then begin
if (IErr = 2601) or (IErr = 2627)
then SErr := 'Дублирование данных. Наименование <' + edSeqStatusName.Text + '> уже существует'
else SErr := spInsert.Parameters.ParamValues['@SErr'];
ShowMessage(SErr);
end;
except
on e:Exception do
begin
ShowMessage(e.Message);
end;
end;
end;
procedure TfrmCCJSO_RefStatusSequence_Create.ItemUpdate(var IErr : integer; var SErr : string);
begin
try
spUpdate.Parameters.ParamValues['@USER'] := RecSession.CurrentUser;
spUpdate.Parameters.ParamValues['@Descr'] := edSeqStatusName.Text;
spUpdate.Parameters.ParamValues['@NRN'] := RecItem.RN;
spUpdate.ExecProc;
IErr := spUpdate.Parameters.ParamValues['@RETURN_VALUE'];
if IErr <> 0 then begin
if (IErr = 2601) or (IErr = 2627)
then SErr := 'Дублирование данных. Наименование <' + edSeqStatusName.Text + '> уже существует'
else SErr := spUpdate.Parameters.ParamValues['@SErr'];
ShowMessage(SErr);
end;
except
on e:Exception do
begin
ShowMessage(e.Message);
end;
end;
end;
procedure TfrmCCJSO_RefStatusSequence_Create.ItemMultiPly(var IErr : integer; var SErr : string);
begin
try
spMultiPly.Parameters.ParamValues['@USER'] := RecSession.CurrentUser;
spMultiPly.Parameters.ParamValues['@Descr'] := edSeqStatusName.Text;
spMultiPly.Parameters.ParamValues['@BaseRN'] := RecItem.RN;
spMultiPly.ExecProc;
IErr := spMultiPly.Parameters.ParamValues['@RETURN_VALUE'];
if IErr <> 0 then begin
if (IErr = 2601) or (IErr = 2627)
then SErr := 'Дублирование данных. Наименование <' + edSeqStatusName.Text + '> уже существует'
else SErr := spMultiPly.Parameters.ParamValues['@SErr'];
ShowMessage(SErr);
end;
except
on e:Exception do
begin
ShowMessage(e.Message);
end;
end;
end;
procedure TfrmCCJSO_RefStatusSequence_Create.aExitExecute(Sender: TObject);
begin
self.Close;
end;
procedure TfrmCCJSO_RefStatusSequence_Create.edSeqStatusNameChange(Sender: TObject);
begin
ShowGets;
end;
end.
|
unit ibSHPSQLDebuggerClasses;
interface
uses Classes, Variants, Contnrs;
type
TVariableValueList = class(TStringList)
private
FDataTypes: TStringList;
function GetValueByName(const AName: string): Variant;
procedure SetValueByName(const AName: string; const Value: Variant);
function GetValueByIndex(Index: Integer): Variant;
procedure SetValueByIndex(Index: Integer; const Value: Variant);
function GetDataTypeByName(const AName: string): string;
function GetDataTypeByIndex(Index: Integer): string;
function GetVarObject(const AName: string):TObject;
procedure SetVarObject(const AName: string;VarObject:TObject);
public
constructor Create; virtual;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure AssignValues(Source: TVariableValueList);
function AddObject(const S: string; AObject: TObject): Integer; override;
function AddWithDataType(const AName, ADataType: string): Integer;
procedure Clear; override;
procedure Delete(Index: Integer); override;
property ValueByName[const AName: string]: Variant read GetValueByName
write SetValueByName;
property ValueByIndex[Index: Integer]: Variant read GetValueByIndex
write SetValueByIndex;
property DataTypeByName[const AName: string]: string read GetDataTypeByName;
property DataTypeByIndex[Index: Integer]: string read GetDataTypeByIndex;
property VarObject[const AName:string]:TObject read GetVarObject write SetVarObject;
end;
implementation
uses SysUtils;
{ TVariableValueList }
constructor TVariableValueList.Create;
begin
FDataTypes := TStringList.Create;
end;
destructor TVariableValueList.Destroy;
begin
Clear;
FDataTypes.Free;
inherited Destroy;
end;
function TVariableValueList.GetValueByName(const AName: string): Variant;
var
vIndex: Integer;
begin
vIndex := IndexOf(AName);
Assert((vIndex > -1) and (vIndex < Count), 'GetValueByName, Index out of bounds');
if (vIndex > -1) and (vIndex < Count) then
Result := PVariant(Objects[vIndex])^;
end;
procedure TVariableValueList.SetValueByName(const AName: string;
const Value: Variant);
var
vIndex: Integer;
begin
vIndex := IndexOf(AName);
Assert((vIndex > -1) and (vIndex < Count), 'SetValueByName, Index out of bounds');
if (vIndex > -1) and (vIndex < Count) then
PVariant(Objects[vIndex])^ := Value;
end;
function TVariableValueList.GetValueByIndex(Index: Integer): Variant;
begin
Assert((Index > -1) and (Index < Count), 'GetValueByIndex, Index out of bounds');
if (Index > -1) and (Index < Count) then
Result := PVariant(Objects[Index])^;
end;
procedure TVariableValueList.SetValueByIndex(Index: Integer;
const Value: Variant);
begin
Assert((Index > -1) and (Index < Count), 'SetValueByIndex, Index out of bounds');
if (Index > -1) and (Index < Count) then
PVariant(Objects[Index])^ := Value;
end;
function TVariableValueList.GetDataTypeByName(const AName: string): string;
var
vIndex: Integer;
begin
vIndex := IndexOf(AName);
Assert((vIndex > -1) and (vIndex < Count), 'GetDataTypeByName, Index out of bounds');
if (vIndex > -1) and (vIndex < Count) then
Result := FDataTypes[vIndex];
end;
function TVariableValueList.GetDataTypeByIndex(Index: Integer): string;
begin
Assert((Index > -1) and (Index < Count), 'GetDataTypeByIndex, Index out of bounds');
if (Index > -1) and (Index < Count) then
Result := FDataTypes[Index];
end;
procedure TVariableValueList.Assign(Source: TPersistent);
begin
inherited Assign(Source);
if Source is TVariableValueList then
FDataTypes.Assign(TVariableValueList(Source).FDataTypes);
end;
procedure TVariableValueList.AssignValues(Source: TVariableValueList);
var
I: Integer;
vIndex: Integer;
begin
for I := 0 to Pred(Count) do
begin
vIndex := Source.IndexOf(Strings[I]);
if vIndex > -1 then
ValueByIndex[I] := Source.ValueByIndex[vIndex];
end;
end;
function TVariableValueList.AddObject(const S: string;
AObject: TObject): Integer;
var
vNewValue: PVariant;
vOldValue: PVariant;
begin
Result := Count;
New(vNewValue);
if Assigned(AObject) then
begin
vOldValue := PVariant(AObject);
VarCopy(vNewValue^, vOldValue^);
end;
InsertItem(Result, S, pointer(vNewValue));
// PutObject(Result, pointer(vNewValue));
end;
function TVariableValueList.AddWithDataType(const AName,
ADataType: string): Integer;
var
vDataType: string;
vValue: string;
vEqPos: Integer;
begin
Result := Add(AName);
if (Length(ADataType)>0) and (ADataType[1]='"') then
vDataType:=ADataType
else
vDataType:=UpperCase(ADataType);
if (Copy(vDataType,1,11)='CURSOR FOR ') then
begin
FDataTypes.Add('CURSOR');
vValue:=Copy(ADataType,13,MaxInt);
SetLength(vValue,Length(vValue)-1);
vValue:=Trim(vValue);
vDataType:=Copy(vValue,Length(vValue)-6,MaxInt);
if UpperCase(Copy(vValue,Length(vValue)-6,MaxInt))<>' UPDATE' then
begin
if UpperCase(Copy(vValue,Length(vValue)-4,MaxInt))<>' LOCK' then
ValueByIndex[Result]:=vValue+ ' FOR UPDATE'
else
ValueByIndex[Result]:=vValue
end
else
ValueByIndex[Result]:=vValue
end
else
begin
//Обработка инициализации переменной в Firebird (f.e. DECLARE VARIABLE VAR_I INTEGER = 0;)
vEqPos := Pos('=', ADataType);
if vEqPos > 0 then
begin
vDataType := Trim(Copy(ADataType, 1, vEqPos - 1));
if (Length(vDataType)>0) and (vDataType[1]<>'"') then
vDataType:=UpperCase(vDataType);
FDataTypes.Add(vDataType);
vValue := Trim(Copy(ADataType, vEqPos + 1, Length(ADataType) - vEqPos));
if Length(vValue) > 0 then
begin
if (vValue[1] in ['N','n']) and (UpperCase(vValue)='NULL') then
ValueByIndex[Result] := null
else
if (Length(vValue) > 1) and (vValue[1] = '''') and (vValue[Length(vValue)] = '''') then
begin
if (Length(vValue) = 2) then
ValueByIndex[Result] := EmptyStr
else
ValueByIndex[Result] := Copy(vValue, 2, Length(vValue) - 2);
end
else
if Pos('.', vValue) > 0 then
ValueByIndex[Result] := StrToFloatDef(vValue, 0)
else
ValueByIndex[Result] := StrToIntDef(vValue, 0)
end
end
else
FDataTypes.Add(vDataType);
end
end;
procedure TVariableValueList.Clear;
var
I: Integer;
begin
for I := Pred(Count) downto 0 do
if Objects[I] <> nil then
Dispose(PVariant(Objects[I]));
for I := Pred(FDataTypes.Count) downto 0 do
if FDataTypes.Objects[I]<>nil then
begin
FDataTypes.Objects[I].Free;
end;
FDataTypes.Clear;
inherited Clear;
end;
procedure TVariableValueList.Delete(Index: Integer);
begin
Assert((Index > -1) and (Index < Count), 'Delete, Index out of bounds');
if (Index > -1) and (Index < Count) then
Dispose(PVariant(Objects[Index]));
inherited Delete(Index);
end;
function TVariableValueList.GetVarObject(const AName: string): TObject;
var
Index:integer;
begin
Index:=IndexOf(AName);
if Index>-1 then
Result:=FDataTypes.Objects[Index]
else
raise Exception.Create('Variable "'+AName+'" don''t exist');
end;
procedure TVariableValueList.SetVarObject(const AName: string;
VarObject: TObject);
var
Index:integer;
begin
Index:=IndexOf(AName);
if Index>-1 then
FDataTypes.Objects[Index]:=VarObject
else
raise Exception.Create('Variable "'+AName+'" don''t exist');
end;
end.
|
unit FD.Compiler.Exceptions;
interface
uses
System.SysUtils;
type
EFDException = class(Exception);
EFDFileNotFound = class(Exception);
implementation
end.
|
(*
Category: SWAG Title: INPUT AND FIELD ENTRY ROUTINES
Original name: 0001.PAS
Description: Simple Field Input
Author: GAYLE DAVIS
Date: 05-31-93 08:59
*)
uses
crt;
type
input_data = record
st : string; { The string to be input }
col,row, { position of input }
attr, { color of input }
flen : byte; { maximum length of input }
prompt : string[40];
end;
const
NumberOfFields = 3;
BackSpace = $08;
Enter = $0d;
Escape = $1b;
space = $20;
var
InputField : array[1..NumberOfFields] of input_data;
{x : byte;}
Done : boolean;
field : byte;
Procedure SetInputField(VAR inpRec : Input_data;
S : STRING;
C,R : Byte;
A,L : Byte;
P : String);
BEGIN
With inpRec DO
BEGIN
St := S;
Col := C;
Row := R;
Attr := A;
fLen := L;
Prompt := P;
END;
END;
procedure GetStr(var inprec: input_data; var f: byte; var finished: boolean);
var
spstr : string; { just a string of spaces }
x,y,
oldattr: byte;
ch : char;
chval : byte absolute ch;
len : byte absolute inprec;
begin
with inprec do begin
FillChar(spstr,sizeof(spstr),32); spstr[0] := chr(flen);
y := row; x := col + length(prompt);
oldattr := TextAttr; finished := false;
gotoXY(col,row); write(prompt);
TextAttr := attr;
repeat
gotoXY(x,y); write(st,copy(spstr,1,flen-len)); gotoXY(x+len,y);
ch := ReadKey;
case chval of
0 : ch := ReadKey;
Enter : begin
inc(f);
if f > NumberOfFields then f := 1;
TextAttr := oldattr;
exit;
end;
BackSpace : if len > 0 then
dec(len);
Escape : begin { the escape key is the only way to halt }
finished := true;
TextAttr := oldattr;
exit;
end;
32..255 : if len <> flen then begin
inc(len);
st[len] := ch;
end;
end; { case }
until false; { procedure only exits via exit statements }
end; { with }
end; { GetStr }
begin
Clrscr;
SetInputField(InputField[1],'',12,10,31,20,'Your Name : ');
SetInputField(InputField[2],'',12,11,31,40,'Your Address : ');
SetInputField(InputField[3],'',12,12,31,25,'City,State : ');
field := 1;
repeat
GetStr(InputField[field],field,Done);
until Done;
end.
|
unit Dpalette;
INTERFACE
{$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF}
uses windows,classes,sysutils,forms,messages,graphics,
util1,debug0,
dibG;
{ Dpalette gère une palette de dégradés de couleurs en se basant sur une
ou deux couleurs fondamentales:
'R ','G ','B ','RG ','RB ','GB ','RGB' (numéros de 1 à 7)
On initialise avec
Create
SetColors(couleur1, couleur2,DeuxCouleurs,DC);
SetPalette(Lmin,Lmax,gamma);
Ensuite ColorPal(x) renvoie la couleur RGB correspondant à x
}
type
TpaletteType=(mono,rgb1,D2,FullD2);
T2Dpalette=array[0..15] of integer;
TDpalette=class
private
Vred:boolean;
Vgreen:boolean;
Vblue:boolean;
Vred1:boolean;
Vgreen1:boolean;
Vblue1:boolean;
degradePal,degradePal1:byte;
PaletteRGB1:array[0..255] of integer;
quads:TrgbQuads;
LogXminPal:float;
LogXmaxPal:float;
ModeLog:boolean;
function ColorPal1(x:float):longint;
public
TwoCol:boolean;
XminPal:float;
XmaxPal:float;
GammaPal:float;
YminPal,YmaxPal,GammaPal2:float;
paletteType:TpaletteType;
constructor create;
destructor destroy;override;
procedure setColors(n1,n2:integer;deux:boolean;dc:hdc);
procedure setPalette(Lmin,Lmax,gamma:float;const logZ:boolean=false);
function ColorPalRGB1(x:float):longint;
function ColorPalMono(x:float):longint;
function ColorPal(x:float):longint;
function ColorIndex(x:float):integer;
procedure initPaletteRGB1;
procedure setType(stF:AnsiString);
function rgbQuads:TrgbQuads;
function rgbPalette:TmaxLogPalette;
procedure buildQuads;
function ColorQuad(x:float):longint;
function ColorIndex2(y:float):integer;
function ColorIndex2D(x,y:float):integer;
function color2D(x,y:float):integer;
procedure set2DPal(p:T2Dpalette);
procedure set2DPalette(full:boolean);
procedure setChrominance(Cmin,Cmax,gamma:float);
end;
function getDColor(n,w:integer):longint;
IMPLEMENTATION
{ février 2011 : on supprime PaletteHandle
donc CreateStm2Palette
et SelectDpaletteHandle
etc...
}
const
NmaxPal:integer=255;
constructor TDpalette.create;
begin
setColors(1,2,true,0);
setPalette(0,10,1);
setChrominance(0,10,1);
initPaletteRGB1;
paletteType:=mono;
end;
procedure TDpalette.initPaletteRGB1;
var
i:integer;
begin
for i:=0 to 63 do
begin
paletteRGB1[i]:=rgb(0,i*4,255);
paletteRGB1[64+i]:=rgb(0,255,252-i*4);
paletteRGB1[128+i]:=rgb(i*4,255,0);
paletteRGB1[192+i]:=rgb(255,252-i*4,0);
end;
end;
function TDpalette.ColorIndex(x: float): integer;
var
c:float;
begin
if ModeLog and (XminPal>0) and (XmaxPal>0) then
begin
if x<XminPal then x:=XminPal
else
if x>XmaxPal then x:=XmaxPal;
if LogxmaxPal>LogxminPal
then c:=(ln(x)-LogXminPal)/(LogxmaxPal-LogxminPal)
else c:=(LogXminPal-ln(x))/(LogxminPal-LogxmaxPal);
end
else
if xmaxPal>xminPal
then c:=(x-XminPal)/(xmaxPal-xminPal)
else c:=(XminPal-x)/(xminPal-xmaxPal);
if c<=0 then c:=1E-300
else
if c>1 then c:=1;
result:=roundI(NmaxPal*exp(gammaPal*ln(c)));
end;
function TDpalette.ColorPal1(x:float):longint;
var
c:float;
i:integer;
col:longint;
begin
if (x>=0) and (xmaxPal<>0) then c:=abs(x/xmaxPal)
else
if (x<0) and (xminPal<>0) then c:=abs(x/xminPal)
else
begin
colorPal1:=0;
exit;
end;
if c<=0 then c:=1E-300
else
if c>1 then c:=1;
i:=roundI(NmaxPal*exp(gammaPal*ln(c)));
if x>=0 then ColorPal1:=rgb(ord(Vred)*i,ord(Vgreen)*i,ord(Vblue)*i)
else ColorPal1:=rgb(ord(Vred1)*i,ord(Vgreen1)*i,ord(Vblue1)*i);
end;
function TDpalette.ColorPalMono(x:float):longint;
var
c:float;
i:integer;
begin
if twoCol then
begin
result:=colorPal1(x);
exit;
end;
i:=colorIndex(x);
result:=rgb(ord(Vred)*i,ord(Vgreen)*i,ord(Vblue)*i);
end;
function TDpalette.ColorPalRgB1(x:float):longint;
var
i:integer;
begin
i:=colorIndex(x);
result:=paletteRGB1[i];
end;
function TDpalette.ColorPal(x:float):longint;
begin
try
case paletteType of
mono: result:=colorPalMono(x);
rgb1,D2,FullD2: result:=colorPalRGB1(x);
end;
except
result:=0;
end;
end;
function TDpalette.ColorIndex2(y: float): integer;
var
c:float;
begin
if ymaxPal>yminPal
then c:=(y-yminPal)/(ymaxPal-yminPal)
else c:=(yminPal-y)/(yminPal-ymaxPal);
if c<=0 then c:=1E-300
else
if c>1 then c:=1;
result:=roundI(NmaxPal*exp(gammaPal2*ln(c)));
end;
function TDpalette.ColorIndex2D(x,y:float):integer;
var
i,j:integer;
begin
i:=colorIndex(x) div 16;
j:=colorIndex2(y) div 16;
result:= i+16*j;
end;
function TDpalette.color2D(x, y: float): integer;
var
i,j:integer;
begin
i:=colorIndex(x) div 16;
j:=colorIndex2(y) div 16;
{result:=colorPalRGB1(i+16*j);}
result:=paletteRGB1[i+16*j];
end;
procedure TDpalette.set2DPal(p:T2Dpalette);
var
i,j:integer;
w:TpaletteEntry;
begin
for i:=0 to 15 do
for j:=0 to 15 do
begin
integer(w):=p[j];
w.peFlags:=0;
w.peRed:=(w.peRed*i) div 16;
w.peGreen:=(w.peGreen*i) div 16;
w.peBlue:=(w.peBlue*i) div 16;
paletteRgb1[i+16*j]:=integer(w);
end;
PaletteType:=D2;
end;
procedure TDpalette.set2DPalette(full:boolean);
var
p:T2Dpalette;
i:integer;
begin
if paletteType=mono then
begin
p[0]:=rgb(255,0,0);
p[1]:=rgb(255,64,0);
p[2]:=rgb(255,128,0);
p[3]:=rgb(255,192,0);
p[4]:=rgb(255,255,0);
p[5]:=rgb(192,255,0);
p[6]:=rgb(128,255,0);
p[7]:=rgb(64,255,0);
p[8]:=rgb(0,255,0);
p[9]:=rgb(0,255,64);
p[10]:=rgb(0,255,128);
p[11]:=rgb(0,255,192);
p[12]:=rgb(0,255,255);
p[13]:=rgb(0,170,255);
p[14]:=rgb(0,85,255);
p[15]:=rgb(0,0,255);
end
else
for i:=0 to 15 do p[i]:=paletteRgb1[i*16];
if not full
then set2Dpal(p)
else paletteType:=FullD2;
end;
procedure TDpalette.setChrominance(Cmin,Cmax,gamma:float);
begin
if Cmin=Cmax then exit;
YminPal:=Cmin;
YmaxPal:=Cmax;
if (gamma>=0) and (gamma<=10) then GammaPal2:=Gamma;
end;
procedure TDpalette.setPalette(Lmin,Lmax,Gamma:float;const logZ:boolean=false);
begin
if Lmin=Lmax then Lmax:=Lmin+1;
try
XminPal:=Lmin;
if XminPal<-1E200 then XminPal:=-1E200;
except
XminPal:=-1E200;
end;
try
XmaxPal:=Lmax;
if XmaxPal> 1E200 then XmaxPal:= 1E200;
except
XmaxPal:= 1E200;
end;
if (gamma>=0) and (gamma<=10) then GammaPal:=Gamma;
ModeLog:=LogZ;
if XminPal>0 then LogXminPal:=ln(XminPal);
if XmaxPal>0 then LogXmaxPal:=ln(XmaxPal);
end;
procedure TDpalette.setType(stF:AnsiString);
var
f:TfileStream;
res:integer;
begin
stF:=Fmaj(stF);
paletteType:=mono;
if (stF='') or (stF='MONOCHROME') then exit;
if stF='R' then setColors(1,1,false,0)
else
if stF='G' then setColors(2,1,false,0)
else
if stF='B' then setColors(3,1,false,0)
else
if stF='RG' then setColors(4,1,false,0)
else
if stF='RB' then setColors(5,1,false,0)
else
if stF='GB' then setColors(6,1,false,0)
else
if stF='RGB' then setColors(7,1,false,0);
stF:= AppData +stF+'.PL1';
if fileExists(stF) then
begin
f:=nil;
TRY
f:=TfileStream.create(stF,fmOpenRead);
f.Read(paletteRgb1,sizeof(paletteRgb1));
f.free;
EXCEPT
f.free;
END;
paletteType:=rgb1;
end;
end;
procedure getLogPalStm(var logpal:TmaxLogPalette);
var
i:integer;
begin
fillchar(logPal,sizeof(logPal),0);
with logPal do
begin
palVersion:=$300;
palNumEntries:=160;
end;
with logPal do
begin
for i:=0 to 159 do palpalEntry[i].peFlags:= pC_RESERVED;
for i:=0 to 15 do
begin
with palpalEntry[i] do peRed:=16*i;
with palpalEntry[i+16] do peGreen:=16*i;
with palpalEntry[i+32] do peBlue:=16*i;
with palpalEntry[i+48] do
begin
peRed:=16*i;
peGreen:=16*i;
end;
with palpalEntry[i+64] do
begin
peGreen:=16*i;
peBlue:=16*i;
end;
with palpalEntry[i+80] do
begin
peRed:=16*i;
peBlue:=16*i;
end;
end;
for i:=0 to 63 do
with palpalEntry[i+96] do
begin
peRed:=4*i;
peGreen:=4*i;
peBlue:=4*i;
end;
end;
end;
procedure TDpalette.setColors(n1,n2:integer;deux:boolean;dc:hdc);
type
TMaxLogPalette=
record
palVersion:word;
palNumEntries:word;
palPalEntry:array[0..255] of TpaletteEntry;
end;
var
logPal:TMaxLogPalette;
i:integer;
old:hpalette;
begin
degradePal:=n1;
degradePal1:=n2;
Vred:=(n1 in [1,4,5,7]);
Vgreen:=(n1 in [2,4,6,7]);
Vblue:=(n1 in [3,5,6,7]);
Vred1:=(n2 in [1,4,5,7]);
Vgreen1:=(n2 in [2,4,6,7]);
Vblue1:=(n2 in [3,5,6,7]);
twoCol:=deux;
end;
destructor TDpalette.destroy;
begin
end;
function getDColor(n,w:integer):longint;
begin
case n of
1:getDcolor:=rgb(w,0,0);
2:getDcolor:=rgb(0,w,0);
3:getDcolor:=rgb(0,0,w);
4:getDcolor:=rgb(w,w,0);
5:getDcolor:=rgb(0,w,w);
6:getDcolor:=rgb(w,0,w);
7:getDcolor:=rgb(w,w,w);
else getDColor:=0;
end;
end;
function TDpalette.rgbQuads: TrgbQuads;
var
i,k0,kmax:integer;
begin
case paletteType of
mono:
if not twocol then
for i:=0 to 255 do
with Result[i] do
begin
rgbRed := i*ord(Vred);
rgbGreen := i*ord(Vgreen);
rgbBlue := i*ord(Vblue);
rgbReserved := 0;
end
else
begin
if xmaxPal<>xminPal
then k0:=round(-XminPal/(xmaxPal-xminPal)*255)
else k0:=0;
if k0>255 then k0:=255;
if k0<0 then k0:=0;
if k0>0 then kmax:=k0 else kmax:=1;
for i:=0 to k0 do
with Result[i] do
begin
rgbRed := round((k0-i)*ord(Vred1)*255/kmax);
rgbGreen := round((k0-i)*ord(Vgreen1)*255/kmax);
rgbBlue := round((k0-i)*ord(Vblue1)*255/kmax);
rgbReserved := 0;
end;
if k0<255 then kmax:=255-k0 else kmax:=1;
for i:=k0 to 255 do
with Result[i] do
begin
rgbRed := round((i-k0)*ord(Vred)*255/kmax);
rgbGreen := round((i-k0)*ord(Vgreen)*255/kmax);
rgbBlue := round((i-k0)*ord(Vblue)*255/kmax);
rgbReserved := 0;
end;
end;
rgb1,D2,FullD2:
for i:=0 to 255 do
with Result[i] do
begin
rgbRed := paletteRGB1[i] and 255;
rgbGreen := (paletteRGB1[i] shr 8) and 255;
rgbBlue := (paletteRGB1[i] shr 16) and 255;
rgbReserved := 0;
end;
end;
end;
function TDpalette.rgbPalette:TmaxLogPalette;
var
i,k0,kmax:integer;
begin
result.palVersion:=$300;
result.palNumEntries:=256;
case paletteType of
mono:
if not twocol then
for i:=0 to 255 do
with Result.palPalEntry[i] do
begin
peRed := i*ord(Vred);
peGreen := i*ord(Vgreen);
peBlue := i*ord(Vblue);
peFlags := 0;
end
else
begin
if xmaxPal<>xminPal
then k0:=round(-XminPal/(xmaxPal-xminPal)*255)
else k0:=0;
if k0>255 then k0:=255;
if k0<0 then k0:=0;
if k0>0 then kmax:=k0 else kmax:=1;
for i:=0 to k0 do
with Result.palPalEntry[i] do
begin
peRed := round((k0-i)*ord(Vred1)*255/kmax);
peGreen := round((k0-i)*ord(Vgreen1)*255/kmax);
peBlue := round((k0-i)*ord(Vblue1)*255/kmax);
peFlags := 0;
end;
if k0<255 then kmax:=255-k0 else kmax:=1;
for i:=k0 to 255 do
with Result.palPalEntry[i] do
begin
peRed := round((i-k0)*ord(Vred)*255/kmax);
peGreen := round((i-k0)*ord(Vgreen)*255/kmax);
peBlue := round((i-k0)*ord(Vblue)*255/kmax);
peFlags := 0;
end;
end;
rgb1,D2,FullD2:
for i:=0 to 255 do
with Result.palPalEntry[i] do
begin
peRed := paletteRGB1[i] and 255;
peGreen := (paletteRGB1[i] shr 8) and 255;
peBlue := (paletteRGB1[i] shr 16) and 255;
peFlags := 0;
end;
end;
end;
procedure TDpalette.buildQuads;
begin
quads:=rgbQuads;
end;
function TDpalette.ColorQuad(x:float):longint;
begin
result:=integer(quads[colorIndex(x)]);
end;
Initialization
AffDebug('Initialization Dpalette',0);
end.
|
unit TITaxInvoices_Filter;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxSpinEdit, cxDropDownEdit, cxTextEdit,
cxMaskEdit, cxButtonEdit, cxControls, cxContainer, cxEdit, cxCheckBox,
StdCtrls, cxButtons, ExtCtrls,TiCommonProc,ibase,TICommonDates,
cxCurrencyEdit;
type TaxInvocesFilter = record
is_period:Boolean;
is_type:Boolean;
Kod_Setup:Integer;
end;
type
TTaxInvoicesFilterForm = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
OkButton: TcxButton;
CancelButton: TcxButton;
PeriodReestrCheckBox: TcxCheckBox;
TypeReestrCheckBox: TcxCheckBox;
TypeReestrButtonEdit: TcxButtonEdit;
MonthList: TcxComboBox;
YearSpinEdit: TcxSpinEdit;
procedure CancelButtonClick(Sender: TObject);
private
PParameter:TaxInvocesFilter;
PDb_Handle:TISC_DB_HANDLE;
public
constructor Create(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE;FParameter:TaxInvocesFilter);reintroduce;
property Parameter:TaxInvocesFilter read PParameter;
end;
var
TaxInvoicesFilterForm: TTaxInvoicesFilterForm;
implementation
{$R *.dfm}
constructor TTaxInvoicesFilterForm.Create(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE;FParameter:TaxInvocesFilter);
begin
inherited Create(AOwner);
PParameter := FParameter;
PDb_Handle := DB_Handle;
PeriodReestrCheckBox.Checked := PParameter.is_period;
TypeReestrCheckBox.Checked := PParameter.is_type;
MonthList.Properties.Items.Text := GetMonthList;
PParameter.Kod_Setup := CurrentKodSetup(PDb_Handle);
YearSpinEdit.Value := YearMonthFromKodSetup(PParameter.Kod_Setup);
MonthList.ItemIndex := YearMonthFromKodSetup(PParameter.Kod_Setup-1,False);
//******************************************************************************
TaxInvoicesFilterForm.Caption := GetConst('Filter',tcButton);
PeriodReestrCheckBox.Properties.Caption := GetConst('PeriodReestr',tcCheckBox);
TypeReestrCheckBox.Properties.Caption := GetConst('TipReestr',tcCheckBox);
TypeReestrButtonEdit.Text := '';
end;
procedure TTaxInvoicesFilterForm.CancelButtonClick(Sender: TObject);
begin
Close;
end;
end.
|
unit fre_openssl_cmd;
{
(§LIC)
(c) Autor,Copyright
Dipl.Ing.- Helmut Hartl, Dipl.Ing.- Franz Schober, Dipl.Ing.- Christian Koch
FirmOS Business Solutions GmbH
www.openfirmos.org
New Style BSD Licence (OSI)
Copyright (c) 2001-2013, FirmOS Business Solutions GmbH
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the <FirmOS Business Solutions GmbH> nor the names
of its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(§LIC_END)
}
{$mode objfpc}{$H+}
{$codepage UTF8}
interface
uses
Classes, SysUtils,fre_process,fos_tool_interfaces,fre_openssl_interface,fre_system;
const
csslcnf ='openssl.cnf';
type
{ TFRE_SSL_OPENSSLCMD }
TFRE_SSL_OPENSSLCMD = class(TObject,IFRE_SSL)
private
procedure _Checkdir (const cdir:string);
function _sslDateToDateTime64 (const datestr:string):TFRE_DB_DateTime64;
protected
procedure ClearCABaseInformation (var ca_base_information:RFRE_CA_BASEINFORMATION);
function PrepareDirectory : string;
function PrepareCADirectory (const ca_base_information:RFRE_CA_BASEINFORMATION) : string;
procedure WriteConf (const dir:string; const cn,c,st,l,o,ou,email:string);
procedure ReadCABaseInformation (const dir:string; var ca_base_information:RFRE_CA_BASEINFORMATION);
public
function CreateCA (const cn,c,st,l,o,ou,email:string; const ca_pass:string; out ca_base_information:RFRE_CA_BASEINFORMATION) : TFRE_SSL_RESULT;
function CreateCrt (const cn,c,st,l,o,ou,email:string; const ca_pass:string; var ca_base_information:RFRE_CA_BASEINFORMATION; const server:boolean; out crt_base_information: RFRE_CRT_BASEINFORMATION) : TFRE_SSL_RESULT;
function RevokeCrt (const cn:string;const ca_pass:string; const crt:string ; var ca_base_information:RFRE_CA_BASEINFORMATION) : TFRE_SSL_RESULT;
function ReadCrtInformation (const crt: string; out cn,c,st,l,o,ou,email:string; out issued_date,end_date:TFRE_DB_DateTime64) : TFRE_SSL_RESULT;
end;
procedure Setup_SSL_CMD_CA_Interface;
procedure Cleanup_SSL_CMD_CA_Interface;
implementation
var FSSL: TFRE_SSL_OPENSSLCMD;
procedure LogError(const msg:string);
begin
raise Exception.Create('Exception raised: ERROR :'+msg);
end;
procedure LogInfo(const msg:string);
begin
writeln('INFO:',msg);
end;
procedure CheckError(const resultcode: integer; const msg:string='');
begin
if resultcode<>0 then begin
raise Exception.Create('Exception raised: Resultcode:'+inttostr(resultcode)+' '+msg);
end;
end;
procedure Setup_SSL_CMD_CA_Interface;
begin
if not assigned(FSSL) then
begin
FSSL := TFRE_SSL_OPENSSLCMD.Create;
Setup_SSL_IF(FSSL);
end;
end;
procedure Cleanup_SSL_CMD_CA_Interface;
begin
if Assigned(FSSL) then
begin
FSSL.Free;
FSSL:=nil;
Setup_SSL_IF(FSSL);
end;
end;
{ TFRE_SSL_OPENSSLCMD }
procedure TFRE_SSL_OPENSSLCMD._Checkdir(const cdir: string);
begin
ForceDirectories(cdir);
if not DirectoryExists(cdir) then begin
raise Exception.Create('Could not create CA Dir '+cdir);
end;
end;
function TFRE_SSL_OPENSSLCMD._sslDateToDateTime64(const datestr: string): TFRE_DB_DateTime64;
var
mon : string;
d,m,y : NativeInt;
h,min,s : NativeInt;
i : NativeInt;
const
CFRE_DT_MONTH : array[1..12] of string = ('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
begin
mon := Copy(datestr,1,3);
for i:= 1 to 12 do
begin
if mon=CFRE_DT_MONTH[i] then begin
m:=i;
break;
end;
end;
d := StrToInt(trim(Copy(datestr,5,2)));
h := StrToInt(trim(Copy(datestr,8,2)));
min := StrToInt(trim(Copy(datestr,11,2)));
s := StrToInt(trim(Copy(datestr,14,2)));
y := StrToInt(trim(Copy(datestr,17,4)));
result := GFRE_DT.EncodeTime(y,m,d,h,min,s,0);
end;
procedure TFRE_SSL_OPENSSLCMD.ClearCABaseInformation(var ca_base_information: RFRE_CA_BASEINFORMATION);
begin
ca_base_information.index:='';
ca_base_information.index_attr:='';
ca_base_information.serial:='';
ca_base_information.crlnumber:='';
ca_base_information.crl:='';
ca_base_information.crt:='';
ca_base_information.key:='';
ca_base_information.random:='';
end;
function TFRE_SSL_OPENSSLCMD.PrepareDirectory: string;
var
guid : TGUID;
begin
CreateGUID(guid);
result:=cFRE_TMP_DIR+GFRE_BT.GUID_2_HexString(guid);
_CheckDir(result);
end;
function TFRE_SSL_OPENSSLCMD.PrepareCADirectory(const ca_base_information: RFRE_CA_BASEINFORMATION): string;
var
dir : string;
dir_signed : string;
dir_private : string;
procedure _WriteFile(const content:string; const filename: string; const create:boolean=false);
begin
if content<>'' then begin
GFRE_BT.StringToFile(dir+DirectorySeparator+filename,content);
end else begin
if create then begin
CheckError(FRE_ProcessCMD('touch '+dir+DirectorySeparator+filename));
end;
end;
end;
procedure _WriteExtensions;
var sl : TStringList;
begin
sl:=TStringList.Create;
try
sl.Add('[ xpclient_ext]');
sl.Add('extendedKeyUsage = 1.3.6.1.5.5.7.3.2');
sl.Add('[ xpserver_ext ]');
sl.Add('extendedKeyUsage = 1.3.6.1.5.5.7.3.1');
sl.SaveToFile(dir+'/xpxtensions');
finally
sl.Free;
end;
end;
begin
dir := PrepareDirectory;
dir_signed :=dir+DirectorySeparator+'signed_certs';
dir_private:=dir+DirectorySeparator+'private';
_CheckDir(dir_signed);
_CheckDir(dir_private);
_CheckDir(dir+DirectorySeparator+'crl');
_WriteExtensions;
_WriteFile(ca_base_information.index,'index.txt',true);
_WriteFile(ca_base_information.index_attr,'index.txt.attr');
_WriteFile(ca_base_information.serial,'serial');
_WriteFile(ca_base_information.crlnumber,'crlnumber');
_WriteFile(ca_base_information.crt,'ca.crt');
_WriteFile(ca_base_information.key,'private/ca.key');
result := dir;
end;
procedure TFRE_SSL_OPENSSLCMD.WriteConf(const dir: string; const cn, c, st, l, o, ou, email: string);
var lsl:TStringList;
begin
lsl:=TStringList.Create;
try
lsl.Add('HOME = .');
lsl.Add('RANDFILE = $ENV::HOME/.rnd');
lsl.Add('oid_section = new_oids');
lsl.Add('[ new_oids ]');
lsl.Add('[ ca ]');
lsl.Add('default_ca = CA_default # The default ca section');
lsl.Add('[ CA_default ]');
lsl.Add('dir = '+dir+' # Where everything is kept');
lsl.Add('certs = $dir/ # Where the issued certs are kept');
lsl.Add('crl_dir = $dir/crl # Where the issued crl are kept');
lsl.Add('database = $dir/index.txt # database index file.');
lsl.Add('#unique_subject = no # Set to no to allow creation of');
lsl.Add('new_certs_dir = $dir/signed_certs # default place for new certs.');
lsl.Add('certificate = $dir/ca.crt # The CA certificate');
lsl.Add('serial = $dir/serial # The current serial number');
lsl.Add('crlnumber = $dir/crlnumber # the current crl number');
lsl.Add('crl = $dir/crl.pem # The current CRL');
lsl.Add('private_key = $dir/private/ca.key # The private key');
lsl.Add('RANDFILE = $dir/private/.rand # private random number file');
lsl.Add('x509_extensions = v3_ca # The extentions to add to the cert');
lsl.Add('name_opt = ca_default # Subject Name options');
lsl.Add('cert_opt = ca_default # Certificate field options');
lsl.Add('default_days = 3650 # how long to certify for');
lsl.Add('default_crl_days= 30 # how long before next CRL');
lsl.Add('default_md = sha1 # which md to use.');
lsl.Add('preserve = no # keep passed DN ordering');
lsl.Add('policy = policy_match');
lsl.Add('[ policy_match ]');
lsl.Add('countryName = match');
lsl.Add('stateOrProvinceName = match');
lsl.Add('organizationName = match');
lsl.Add('organizationalUnitName = optional');
lsl.Add('commonName = supplied');
lsl.Add('emailAddress = optional');
lsl.Add('[ policy_anything ]');
lsl.Add('countryName = optional');
lsl.Add('stateOrProvinceName = optional');
lsl.Add('localityName = optional');
lsl.Add('organizationName = optional');
lsl.Add('organizationalUnitName = optional');
lsl.Add('commonName = supplied');
lsl.Add('emailAddress = optional');
lsl.Add('[ req ]');
lsl.Add('default_bits = 1024');
lsl.Add('default_keyfile = privkey.pem');
lsl.Add('distinguished_name = req_distinguished_name');
lsl.Add('attributes = req_attributes');
lsl.Add('prompt = no');
lsl.Add('x509_extensions = v3_ca # The extentions to add to the self signed cert');
lsl.Add('string_mask = nombstr');
lsl.Add('# req_extensions = v3_req # The extensions to add to a certificate request');
lsl.Add('[ req_distinguished_name ]');
if c<>'' then lsl.Add('C = '+c);
if st<>'' then lsl.Add('ST = '+st);
if l<>'' then lsl.Add('L = '+l);
if o<>'' then lsl.Add('O = '+o);
if ou<>'' then lsl.Add('OU = '+ou);
if cn<>'' then lsl.Add('CN = '+cn);
if email<>'' then lsl.Add('emailAddress = '+email);
lsl.Add('[ req_attributes ]');
lsl.Add('challengePassword = A challenge password');
lsl.Add('[ usr_cert ]');
lsl.Add('basicConstraints=CA:FALSE');
lsl.Add('nsComment = "OpenSSL Generated Certificate"');
lsl.Add('subjectKeyIdentifier=hash');
lsl.Add('authorityKeyIdentifier=keyid,issuer');
lsl.Add('[ v3_req ]');
lsl.Add('basicConstraints = CA:FALSE');
lsl.Add('keyUsage = nonRepudiation, digitalSignature, keyEncipherment');
lsl.Add('[ v3_ca ]');
lsl.Add('subjectKeyIdentifier=hash');
lsl.Add('authorityKeyIdentifier=keyid:always,issuer:always');
lsl.Add('basicConstraints = CA:true');
lsl.Add('[ crl_ext ]');
lsl.Add('authorityKeyIdentifier=keyid:always,issuer:always');
lsl.SaveToFile(dir+'/'+csslcnf);
finally
lsl.Free;
end;
end;
procedure TFRE_SSL_OPENSSLCMD.ReadCABaseInformation(const dir: string; var ca_base_information: RFRE_CA_BASEINFORMATION);
procedure _ReadFile(var content:RawByteString; const filename: string);
begin
if FileExists(dir+DirectorySeparator+filename) then begin
content := GFRE_BT.StringFromFile(dir+DirectorySeparator+filename);
end else begin
content := '';
end;
end;
begin
_ReadFile(ca_base_information.index,'index.txt');
_ReadFile(ca_base_information.index_attr,'index.txt.attr');
_ReadFile(ca_base_information.serial,'serial');
_ReadFile(ca_base_information.crlnumber,'crlnumber');
_ReadFile(ca_base_information.crt,'ca.crt');
_ReadFile(ca_base_information.key,'private/ca.key');
_ReadFile(ca_base_information.crl,'crl'+DirectorySeparator+'ca.crl');
end;
function TFRE_SSL_OPENSSLCMD.CreateCA(const cn, c, st, l, o, ou, email: string; const ca_pass: string; out ca_base_information: RFRE_CA_BASEINFORMATION): TFRE_SSL_RESULT;
var
dir : string;
sl : TStringList;
begin
if ca_pass='' then
raise EFRE_Exception.Create('a passphrase must be assigned when creating a ca');
ClearCABaseInformation(ca_base_information);
dir := PrepareCADirectory(ca_base_information);
try
WriteConf(dir,cn,c,st,l,o,ou,email);
FRE_ProcessCMDException('openssl req -passout pass:'+ca_pass+' -new -keyout '+dir+'/private/ca.key -out '+dir+'/careq.pem -config '+dir+'/'+csslcnf);
LogInfo('Sign CA Req ');
FRE_ProcessCMDException('openssl ca -batch -passin pass:'+ca_pass+' -create_serial -out '+dir+'/ca.crt -keyfile '+dir+'/private/ca.key -selfsign -extensions v3_ca -in '+dir+'/careq.pem -config '+dir+'/'+csslcnf);
// FRE_ProcessCMDException('openssl x509 -inform PEM -outform DER -in '+dir+'/ca.crt -out '+dir+'/ca.der');
LogInfo('Create DH ');
FRE_ProcessCMDException('openssl dhparam -out '+dir+'/dh1024.pem 1024');
FRE_ProcessCMDException('dd if=/dev/urandom of='+dir+'/random count=2');
//Create CRL
sl:=TStringList.Create;
try
sl.Add('00');
sl.SaveToFile(dir+'/crlnumber');
finally
sl.Free;
end;
LogInfo('Create CA Done ');
ReadCABaseInformation(dir,ca_base_information);
finally
FRE_ProcessCMD('rm -rf '+dir);
end;
end;
function TFRE_SSL_OPENSSLCMD.CreateCrt(const cn, c, st, l, o, ou, email: string; const ca_pass: string; var ca_base_information: RFRE_CA_BASEINFORMATION; const server: boolean; out crt_base_information: RFRE_CRT_BASEINFORMATION): TFRE_SSL_RESULT;
var
dir : string;
begin
LogInfo('Creating Crt '+cn);
LogInfo('Creating SSL Conf '+cn);
dir := PrepareCADirectory(ca_base_information);
try
WriteConf(dir,cn,c,st,l,o,ou,email);
LogInfo('Creating Crt Req '+cn);
FRE_ProcessCMDException('openssl req -nodes -new -keyout '+dir+'/private/crt.key -out '+dir+'/crt_req.pem -config '+dir+'/'+csslcnf);
LogInfo('Sign Crt Req '+cn);
if server=true then begin
FRE_ProcessCMDException('openssl ca -verbose -batch -passin pass:'+ca_pass+' -out '+dir+'/signed_certs/crt.crt -extensions xpserver_ext -extfile '+dir+'/xpxtensions -in '+dir+'/crt_req.pem -config '+dir+'/'+csslcnf);
end else begin
FRE_ProcessCMDException('openssl ca -verbose -batch -passin pass:'+ca_pass+' -out '+dir+'/signed_certs/crt.crt -extensions xpclient_ext -extfile '+dir+'/xpxtensions -in '+dir+'/crt_req.pem -config '+dir+'/'+csslcnf);
end;
// CheckError(Command('openssl pkcs12 -export -passout pass:'+ob.Field('pass').AsString+' -clcerts -in '+cadir_signed+'/'+ob.Field('cn').asstring+'.crt -inkey '+cadir+'/private/'+ob.Field('cn').asstring+'.key -out '+cadir+'/private/'+ob.Field('cn').asstring+'.p12'));
ReadCABaseInformation(dir,ca_base_information);
crt_base_information.crt := GFRE_BT.StringFromFile(dir+DirectorySeparator+'signed_certs'+DirectorySeparator+'crt.crt');
crt_base_information.key := GFRE_BT.StringFromFile(dir+DirectorySeparator+'private'+DirectorySeparator+'crt.key');
LogInfo('Create Crt Done '+cn);
// FRE_ProcessCMD('rm -rf '+dir);
finally
// FRE_ProcessCMD('rm -rf '+dir);
end;
end;
function TFRE_SSL_OPENSSLCMD.RevokeCrt(const cn: string; const ca_pass: string; const crt: string; var ca_base_information: RFRE_CA_BASEINFORMATION): TFRE_SSL_RESULT;
var
dir : string;
begin
LogInfo('Revoke Crt '+cn);
LogInfo('Creating SSL Conf '+cn);
dir := PrepareCADirectory(ca_base_information);
try
WriteConf(dir,cn,'','','','','','');
GFRE_BT.StringToFile(dir+DirectorySeparator+'signed_certs'+DirectorySeparator+'crt.crt',crt);
FRE_ProcessCMDException('openssl ca -passin pass:'+ca_pass+' -revoke '+dir+'/signed_certs/crt.crt -config '+dir+'/'+csslcnf);
FRE_ProcessCMDException('openssl ca -passin pass:'+ca_pass+' -config '+dir+'/'+csslcnf+' -gencrl -crldays 365 -out '+dir+'/crl/ca.crl');
ReadCABaseInformation(dir,ca_base_information);
LogInfo('Revoke Crt Done '+cn);
finally
FRE_ProcessCMD('rm -rf '+dir);
end;
end;
function TFRE_SSL_OPENSSLCMD.ReadCrtInformation(const crt: string; out cn, c, st, l, o, ou, email: string; out issued_date,end_date:int64): TFRE_SSL_RESULT;
var dir : string;
outstr : string;
errorstr : string;
res : NativeInt;
sl : TStringList;
subject : string;
ss : TFOSStringArray;
i : NativeInt;
ls,r : string;
begin
dir := PrepareDirectory;
try
GFRE_BT.StringToFile(dir+DirectorySeparator+'crt.crt',crt);
res := FRE_ProcessCMD('openssl x509 -in '+dir+DirectorySeparator+'crt.crt -noout -issuer -startdate -enddate -subject',outstr,errorstr);
if res=0 then
begin
sl := TStringList.Create;
try
sl.Text := outstr;
issued_date := _sslDateToDateTime64(trim(GFRE_BT.SepRight(sl[1],'=')));
end_date := _sslDateToDateTime64(trim(GFRE_BT.SepRight(sl[2],'=')));
subject := trim(GFRE_BT.SepRight(sl[3],'='));
GFRE_BT.SeperateString(subject,'/',ss);
for i := Low(ss) to high(ss) do begin
r := GFRE_BT.SepRight(ss[i],'=');
ls:= GFRE_BT.SepLeft (ss[i],'=');
case ls of
'C' : c := r;
'CN' : cn := r;
'ST' : st := r;
'L' : l := r;
'O' : o := r;
'OU' : ou := r;
'EMAIL' : email := r;
end;
end;
result:=sslOK;
finally
sl.Free;
end;
end
else
result:=sslNOK;
finally
FRE_ProcessCMD('rm -rf '+dir);
end;
end;
end.
|
unit LA.Vector;
{$mode objfpc}{$H+}
{$ModeSwitch advancedrecords}
interface
uses
Classes,
SysUtils,
Math,
LA.Globals;
type
TLists = array of double;
TVector = record
private
__data: TLists;
public
class function Create(list: TLists): TVector; static;
/// <summary> 零向量 </summary>
class function Zero(dim: integer): TVector; static;
/// <summary> 取向量的第index个元素 </summary>
function __getItem(index: integer): double;
/// <summary> 设置index个元素的值 </summary>
procedure __setItem(index: integer; val: double);
/// <summary> 返回向量长度(有多少个元素) </summary>
function Len: integer;
/// <summary> 返回向量的模 </summary>
function Norm: double;
/// <summary> 返回向量的单位向量 </summary>
function Normalize: TVector;
/// <summary> 向量点乘,返回结果标量 </summary>
function Dot(const v: TVector): double;
/// <summary> 返回向量的底层列表 </summary>
function UnderlyingList: TLists;
function ToString: string;
property Item[index: integer]: double read __getItem write __setItem; default;
class operator +(const a, b: TVector): TVector;
class operator -(const a, b: TVector): TVector;
class operator * (const a: double; const b: TVector): TVector;
class operator * (const a: TVector; const b: double): TVector;
class operator * (const a, b: TVector): TVector;
class operator / (const a: TVector; const b: double): TVector;
class operator +(const a: TVector): TVector;
class operator -(const a: TVector): TVector;
class operator = (const a, b: TVector): boolean;
end;
implementation
{ TVector }
function TVector.__getItem(index: integer): double;
begin
Result := __data[index];
end;
procedure TVector.__setItem(index: integer; val: double);
begin
__data[index] := val;
end;
class function TVector.Create(list: TLists): TVector;
begin
Result.__data := Copy(list);
end;
function TVector.Dot(const v: TVector): double;
var
i: integer;
tmp: TVector;
begin
if Self.Len <> v.Len then
raise Exception.Create('Error in Dot-Product. Length of vectors must be same.');
tmp := TVector.Zero(Self.Len);
for i := 0 to Self.Len - 1 do
begin
tmp[i] := Self[i] * v[i];
end;
Result := Sum(tmp.__data);
end;
function TVector.Len: integer;
begin
Result := Length(__data);
end;
function TVector.Norm: double;
var
tmp: TLists;
i: integer;
begin
tmp := Copy(__data);
for i := 0 to Self.Len - 1 do
begin
tmp[i] := sqr(__data[i]);
end;
Result := Sqrt(Sum(tmp));
end;
function TVector.Normalize: TVector;
var
ret: TVector;
begin
if Is_zero(Self.Norm) then
raise Exception.Create('Normalize error! norm is zero.');
ret.__data := copy(__data);
Result := ret / Self.Norm;
end;
function TVector.ToString: string;
var
sb: TAnsiStringBuilder;
i: integer;
begin
sb := TAnsiStringBuilder.Create;
try
sb.Append('(');
for i := 0 to High(__data) do
begin
sb.Append(__data[i]);
if i = High(__data) then
sb.Append(')')
else
sb.Append(', ');
end;
Result := sb.ToString;
finally
FreeAndNil(sb);
end;
end;
function TVector.UnderlyingList: TLists;
begin
Result := Copy(__data);
end;
class function TVector.Zero(dim: integer): TVector;
var
ret: TVector;
begin
SetLength(ret.__data, dim);
Result := ret;
end;
class operator TVector. +(const a, b: TVector): TVector;
var
i: integer;
ret: TVector;
begin
if a.Len <> b.Len then
raise Exception.Create('Error in adding. Length of vectors must be same.');
ret := TVector.Zero(a.Len);
for i := 0 to a.Len - 1 do
begin
ret.__data[i] := a[i] + b[i];
end;
Result := ret;
end;
class operator TVector. -(const a, b: TVector): TVector;
var
i: integer;
ret: TVector;
begin
if a.Len <> b.Len then
raise Exception.Create('Error in subtracting. Length of vectors must be same.');
SetLength(ret.__data, a.Len);
for i := 0 to a.Len - 1 do
begin
ret.__data[i] := a[i] - b[i];
end;
Result := ret;
end;
class operator TVector. * (const a: double; const b: TVector): TVector;
var
i: integer;
ret: TVector;
begin
SetLength(ret.__data, b.Len);
for i := 0 to b.Len - 1 do
begin
ret.__data[i] := a * b[i];
end;
Result := ret;
end;
class operator TVector. * (const a: TVector; const b: double): TVector;
begin
Result := b * a;
end;
class operator TVector. * (const a, b: TVector): TVector;
var
i: integer;
ret: TVector;
begin
if a.Len <> b.Len then
raise Exception.Create('Error in Dot-Product. Length of vectors must be same.');
SetLength(ret.__data, a.Len);
for i := 0 to ret.Len - 1 do
begin
ret.__data[i] := a[i] * b[i];
end;
Result := ret;
end;
class operator TVector. / (const a: TVector; const b: double): TVector;
begin
Result := 1 / b * a;
end;
class operator TVector. +(const a: TVector): TVector;
begin
Result := 1 * a;
end;
class operator TVector. -(const a: TVector): TVector;
begin
Result := -1 * a;
end;
class operator TVector. = (const a, b: TVector): boolean;
var
i: integer;
begin
if a.Len <> b.Len then
Exit(False);
for i := 0 to a.Len - 1 do
begin
if not Is_equal(a[i], b[i]) then
Exit(False);
end;
Result := True;
end;
end.
|
unit ServiceVersion;
interface
uses ServiceVersion.Interfaces;
type
TVersion = class(TInterfacedObject, iVersion)
class function New: iVersion;
constructor Create;
destructor Destroy; override;
strict private
FFilename : string;
FMaintenance: integer;
FMinor : integer;
FMajor : integer;
FBuild : integer;
function getValue: string;
function getBuild: integer;
function getMaintenance: integer;
function getMajor: integer;
function getMinor: integer;
procedure setValue(const aValue: string);
procedure setBuild(const Value: integer);
procedure setMaintenance(const Value: integer);
procedure setMajor(const Value: integer);
procedure setMinor(const Value: integer);
function getFilename: string;
procedure setFilename(const aValue: string);
public
{ public }
property Filename : string read getFilename write setFilename; // Formato da Versão ex: 2.4.3.7 separado em array [0]=2, [1]=4, [2]=3, [3]=7
property Major : integer read getMajor write setMajor default 0; // [0]=2 Versão principal = Mudança do programa ( Reengenharia )
property Minor : integer read getMinor write setMinor default 0; // [1]=4 Versão menor = Mudança de Formulário ( Adição/Remoção )
property Maintenance: integer read getMaintenance write setMaintenance default 0; // [2]=3 Lançamento/Atualização = Mudança de Componente ( Adição/Remoção )
property Build : integer read getBuild write setBuild default 0; // [3]=7 Construção = Correção ( Adequações das funcionalidades )
property Value : string read getValue write setValue;
end;
function Version: iVersion;
function VersionFile(const aFilename: string): string;
function isOutdated(const aNewVersion: string): boolean; overload;
function isOutdated(const aNewVersion: string; aOldVersion: string): boolean; overload;
function isOutdatedFile(const aNewFilename: string): boolean; overload;
function isOutdatedFile(const aNewFilename: string; aOldFileName: string): boolean; overload;
implementation
uses
Winapi.Windows, System.SysUtils, System.Classes;
function Version: iVersion;
begin
Result := TVersion.New;
end;
function VersionFile(const aFilename: string): string;
begin
with Version do
begin
Filename := aFilename;
Result := Value;
end;
end;
function isOutdated(const aNewVersion: string): boolean;
var
LMajor : boolean;
LMinor : boolean;
LMaintenance : boolean;
LBuild : boolean;
LNewVersion : TVersion;
LInstaledVersion: TVersion;
begin
LNewVersion := TVersion.Create();
LNewVersion.Value := aNewVersion;
LInstaledVersion := TVersion.Create();
LInstaledVersion.Filename := ParamStr(0);
try
with LInstaledVersion do
begin
LMajor := (Major < LNewVersion.Major);
LMinor := ((Major = LNewVersion.Major) and (Minor < LNewVersion.Minor));
LMaintenance := ((Minor = LNewVersion.Minor) and (Maintenance < LNewVersion.Maintenance));
LBuild := ((Maintenance = LNewVersion.Maintenance) and (Build < LNewVersion.Build));
end;
Result := (LMajor or LMinor or LMaintenance or LBuild);
finally
LNewVersion.free;
LInstaledVersion.free;
end;
end;
function isOutdated(const aNewVersion: string; aOldVersion: string): boolean;
var
LMajor : boolean;
LMinor : boolean;
LMaintenance : boolean;
LBuild : boolean;
LNewVersion : TVersion;
LInstaledVersion: TVersion;
begin
LInstaledVersion := TVersion.Create();
LNewVersion := TVersion.Create();
try
LNewVersion.Value := aNewVersion;
with LInstaledVersion do
begin
Value := aOldVersion;
LMajor := (Major < LNewVersion.Major);
LMinor := ((Major = LNewVersion.Major) and (Minor < LNewVersion.Minor));
LMaintenance := ((Minor = LNewVersion.Minor) and (Maintenance < LNewVersion.Maintenance));
LBuild := ((Maintenance = LNewVersion.Maintenance) and (Build < LNewVersion.Build));
end;
Result := (LMajor or LMinor or LMaintenance or LBuild);
finally
LNewVersion.free;
LInstaledVersion.free;
end;
end;
function isOutdatedFile(const aNewFilename: string): boolean;
var
LMajor : boolean;
LMinor : boolean;
LMaintenance : boolean;
LBuild : boolean;
LNewVersion : TVersion;
LInstaledVersion: TVersion;
begin
LInstaledVersion := TVersion.Create();
LNewVersion := TVersion.Create();
LNewVersion.Filename := aNewFilename;
try
with LInstaledVersion do
begin
Filename := ParamStr(0);
LMajor := (Major < LNewVersion.Major);
LMinor := ((Major = LNewVersion.Major) and (Minor < LNewVersion.Minor));
LMaintenance := ((Minor = LNewVersion.Minor) and (Maintenance < LNewVersion.Maintenance));
LBuild := ((Maintenance = LNewVersion.Maintenance) and (Build < LNewVersion.Build));
end;
Result := (LMajor or LMinor or LMaintenance or LBuild);
finally
LNewVersion.free;
LInstaledVersion.free;
end;
end;
function isOutdatedFile(const aNewFilename: string; aOldFileName: string): boolean;
var
LMajor : boolean;
LMinor : boolean;
LMaintenance : boolean;
LBuild : boolean;
LNewVersion : TVersion;
LInstaledVersion: TVersion;
begin
LInstaledVersion := TVersion.Create();
LNewVersion := TVersion.Create();
LNewVersion.Filename := aNewFilename;
try
with LInstaledVersion do
begin
Filename := aOldFileName;
LMajor := (Major < LNewVersion.Major);
LMinor := ((Major = LNewVersion.Major) and (Minor < LNewVersion.Minor));
LMaintenance := ((Minor = LNewVersion.Minor) and (Maintenance < LNewVersion.Maintenance));
LBuild := ((Maintenance = LNewVersion.Maintenance) and (Build < LNewVersion.Build));
end;
Result := (LMajor or LMinor or LMaintenance or LBuild);
finally
LNewVersion.free;
LInstaledVersion.free;
end;
end;
{ TVersion }
class function TVersion.New: iVersion;
begin
Result := Self.Create;
end;
constructor TVersion.Create;
begin
Filename := ParamStr(0);
end;
destructor TVersion.Destroy;
begin
inherited;
end;
{ TVersion }
function TVersion.getBuild: integer;
begin
Result := FBuild;
end;
function TVersion.getFilename: string;
begin
Result := FFilename;
end;
function TVersion.getMaintenance: integer;
begin
Result := FMaintenance;
end;
function TVersion.getMajor: integer;
begin
Result := FMajor;
end;
function TVersion.getMinor: integer;
begin
Result := FMinor;
end;
function TVersion.getValue: string;
begin
Result := Format('%d.%d.%d.%d', [FMajor, FMinor, FMaintenance, FBuild]);
end;
procedure TVersion.setValue(const aValue: string);
const
DOT = '.';
MAJOR_PART = 0;
MINOR_PART = 1;
MAINTENANCE_PART = 2;
BUILD_PART = 3;
begin
with TStringList.Create do
try
Clear;
Delimiter := DOT;
DelimitedText := aValue;
FMajor := Strings[MAJOR_PART].ToInteger;
FMinor := Strings[MINOR_PART].ToInteger;
FMaintenance := Strings[MAINTENANCE_PART].ToInteger;
FBuild := Strings[BUILD_PART].ToInteger;
finally
free;
end;
end;
procedure TVersion.setBuild(const Value: integer);
begin
FBuild := Value;
end;
procedure TVersion.setFilename(const aValue: string);
type
PFFI = ^vs_FixedFileInfo;
var
F : PFFI;
Handle : Dword;
Len : Longint;
Data : PChar;
Buffer : Pointer;
Tamanho : Dword;
LStrFilename: string;
LFilename : PChar;
begin
FMajor := 0;
FMinor := 0;
FMaintenance := 0;
FBuild := 0;
if FileExists(aValue) then
LStrFilename := aValue
else
LStrFilename := ParamStr(0);
LFilename := StrAlloc(Length(LStrFilename) + 1);
StrPcopy(LFilename, LStrFilename);
Len := GetFileVersionInfoSize(LFilename, Handle);
if Len > 0 then
begin
Data := StrAlloc(Len + 1);
if GetFileVersionInfo(LFilename, Handle, Len, Data) then
begin
VerQueryValue(Data, '\', Buffer, Tamanho);
F := PFFI(Buffer);
FMajor := HiWord(F^.dwFileVersionMs);
FMinor := LoWord(F^.dwFileVersionMs);
FMaintenance := HiWord(F^.dwFileVersionLs);
FBuild := LoWord(F^.dwFileVersionLs);
end;
StrDispose(Data);
end;
StrDispose(LFilename);
end;
procedure TVersion.setMaintenance(const Value: integer);
begin
FMaintenance := Value;
end;
procedure TVersion.setMajor(const Value: integer);
begin
FMajor := Value;
end;
procedure TVersion.setMinor(const Value: integer);
begin
FMinor := Value;
end;
end.
|
{*******************************************************************************
* uMemoControl *
* *
* Библиотека компонентов для работы с формой редактирования (qFControls) *
* Работа со мемо-полем ввода (TqFMemoControl) *
* Copyright © 2005-2007, Олег Г. Волков, Донецкий Национальный Университет *
*******************************************************************************}
unit uMemoControl;
interface
uses
SysUtils, Classes, Controls, uFControl, StdCtrls, Graphics, uLabeledFControl,
Registry;
type
TqFMemoControl = class(TqFLabeledControl)
protected
FMemo: TMemo;
procedure SetValue(Val: Variant); override;
function GetValue: Variant; override;
procedure SetMaxLength(Len: Integer);
function GetMaxLength: Integer;
procedure PrepareRest; override;
procedure SetLabelPosition; override;
procedure Loaded; override;
function GetKeyDown: TKeyEvent;
procedure SetKeyDown(e: TKeyEvent);
function GetKeyUp: TKeyEvent;
procedure SetKeyUp(e: TKeyEvent);
public
constructor Create(AOwner: TComponent); override;
function Check: string; override;
procedure Block(Flag: Boolean); override;
procedure Highlight(HighlightOn: Boolean); override;
procedure ShowFocus; override;
function ToString: string; override;
procedure LoadFromRegistry(reg: TRegistry); override; // vallkor
procedure SaveIntoRegistry(reg: TRegistry); override; // vallkor
published
property Memo: TMemo read FMemo;
property MaxLength: Integer read GetMaxLength write SetMaxLength;
property OnKeyDown: TKeyEvent read GetKeyDown write SetKeyDown;
property OnKeyUp: TKeyEvent read GetKeyUp write SetKeyUp;
end;
procedure Register;
{$R *.res}
implementation
uses qFStrings, Variants, qFTools;
function TqFMemoControl.GetKeyDown: TKeyEvent;
begin
Result := FMemo.OnKeyDown;
end;
procedure TqFMemoControl.SetKeyDown(e: TKeyEvent);
begin
FMemo.OnKeyDown := e;
end;
function TqFMemoControl.GetKeyUp: TKeyEvent;
begin
Result := FMemo.OnKeyUp;
end;
procedure TqFMemoControl.SetKeyUp(e: TKeyEvent);
begin
FMemo.OnKeyUp := e;
end;
procedure TqFMemoControl.SetLabelPosition;
begin
FLabel.Top := 0;
end;
procedure TqFMemoControl.Block(Flag: Boolean);
begin
inherited Block(Flag);
FMemo.ReadOnly := Flag;
if Flag then
FMemo.Color := qFBlockedColor
else
FMemo.Color := FOldColor;
end;
procedure TqFMemoControl.Loaded;
begin
FMemo.OnChange := FOnChange;
inherited Loaded;
end;
procedure TqFMemoControl.Highlight(HighlightOn: Boolean);
begin
inherited Highlight(HighlightOn);
if HighlightOn then
FMemo.Color := qFHighlightColor
else
if FOldColor <> 0 then
FMemo.Color := FOldColor;
Repaint;
end;
procedure TqFMemoControl.ShowFocus;
begin
inherited ShowFocus;
qFSafeFocusControl(FMemo);
end;
procedure TqFMemoControl.SetMaxLength(Len: Integer);
begin
FMemo.MaxLength := Len;
end;
function TqFMemoControl.GetMaxLength: Integer;
begin
Result := FMemo.MaxLength;
end;
function TqFMemoControl.ToString: string;
begin
Result := QuotedStr(FMemo.Text);
end;
function TqFMemoControl.Check: string;
begin
if Required then
if Trim(Value) = '' then
Check := qFFieldIsEmpty + '"' + DisplayName + '"!'
else
Check := ''
else
Check := '';
end;
procedure TqFMemoControl.SetValue(Val: Variant);
begin
inherited SetValue(Val);
if VarIsNull(Val) then
FMemo.Text := ''
else
FMemo.Text := Val;
end;
function TqFMemoControl.GetValue: Variant;
begin
Result := FMemo.Text;
end;
constructor TqFMemoControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FMemo := TMemo.Create(Self);
FMemo.Parent := Self;
FMemo.OnChange := FOnChange;
FMemo.Font.Name := 'Verdana';
FMemo.Font.Style := Self.Font.Style;
FMemo.Font.Size := Self.Font.Size;
PrepareRest;
Width := 400;
Height := 200;
FOldColor := FMemo.Color;
end;
procedure TqFMemoControl.PrepareRest;
begin
FMemo.Width := Width - Interval - 3;
FMemo.Left := 0;
FMemo.Width := Width;
FMemo.Top := qFDefaultHeight;
FMemo.Height := Height - qFDefaultHeight;
end;
procedure Register;
begin
RegisterComponents('qFControls', [TqFMemoControl]);
end;
procedure TqFMemoControl.LoadFromRegistry(reg: TRegistry); // vallkor
begin
inherited LoadFromRegistry(reg);
Value := Reg.ReadString('Value');
end;
procedure TqFMemoControl.SaveIntoRegistry(reg: TRegistry); // vallkor
begin
inherited SaveIntoRegistry(reg);
Reg.WriteString('Value', VarToStr(Value));
end;
end.
|
unit ThPageControl;
interface
uses
Windows, Messages, SysUtils, Types, Classes, Controls, StdCtrls, ExtCtrls,
Graphics, Forms,
ThWebControl, ThAttributeList, ThTag, ThPanel;
type
TThSheet = class(TThPanel)
public
destructor Destroy; override;
procedure Select;
end;
//
TThPageControl = class(TThPanel)
private
FActivePageIndex: Integer;
FCount: Integer;
FSheets: TList;
protected
procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override;
function GetHtmlAsString: string; override;
function GetSheet(inIndex: Integer): TThSheet;
function GetSheetNamePrefix: string; virtual;
procedure SetActivePageIndex(const Value: Integer);
procedure SetCount(const Value: Integer);
protected
procedure AdjustClientRect(var Rect: TRect); override;
function CreateSheet: TThSheet; virtual;
function IsGoodIndex: Boolean;
procedure Loaded; override;
procedure RenameSheets; virtual;
procedure Resize; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure RemoveSheet(inSheet: TThSheet);
property Sheet[inIndex: Integer]: TThSheet read GetSheet;
published
property ActivePageIndex: Integer read FActivePageIndex
write SetActivePageIndex;
property Count: Integer read FCount write SetCount;
end;
implementation
{ TThSheet }
destructor TThSheet.Destroy;
begin
if (Parent is TThPageControl) then
TThPageControl(Parent).RemoveSheet(Self);
inherited;
end;
procedure TThSheet.Select;
begin
Top := 0;
end;
{ TThPageControl }
constructor TThPageControl.Create(AOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle - [ csAcceptsControls ];
FSheets := TList.Create;
//Style.Color := clLime;
end;
destructor TThPageControl.Destroy;
begin
FSheets.Destroy;
inherited;
end;
procedure TThPageControl.GetChildren(Proc: TGetChildProc; Root: TComponent);
var
i: Integer;
begin
for i := 0 to Pred(FSheets.Count) do
Proc(TComponent(FSheets[i]));
end;
procedure TThPageControl.Loaded;
var
i: Integer;
begin
inherited;
for i := 0 to Pred(ControlCount) do
if Controls[i] is TThSheet then
begin
FSheets.Add(Controls[i]);
Controls[i].Align := alTop;
end;
if Count = 0 then
Count := 1;
end;
procedure TThPageControl.Resize;
var
i: Integer;
begin
for i := 0 to Pred(Count) do
Sheet[i].Height := Height - 4;
inherited;
end;
procedure TThPageControl.AdjustClientRect(var Rect: TRect);
begin
//Dec(Rect.Bottom, 4);
Inc(Rect.Top, 4);
end;
function TThPageControl.IsGoodIndex: Boolean;
begin
Result := (ActivePageIndex >= 0) and (ActivePageIndex < Count);
end;
function TThPageControl.GetSheet(inIndex: Integer): TThSheet;
begin
Result := TThSheet(FSheets[inIndex]);
end;
procedure TThPageControl.SetActivePageIndex(const Value: Integer);
begin
FActivePageIndex := Value;
if IsGoodIndex then
Sheet[ActivePageIndex].Select;
end;
function TThPageControl.CreateSheet: TThSheet;
begin
Result := TThSheet.Create(Owner);
Result.Name := TCustomForm(Owner).Designer.UniqueName('ThPage');
Result.Align := alTop;
Result.Style.Color := clWhite;
Result.Parent := Self;
end;
procedure TThPageControl.SetCount(const Value: Integer);
begin
FCount := Value;
if not (csLoading in ComponentState) then
begin
while FSheets.Count < FCount do
FSheets.Add(CreateSheet);
ActivePageIndex := Pred(FCount);
end;
end;
procedure TThPageControl.RemoveSheet(inSheet: TThSheet);
begin
FSheets.Remove(inSheet);
FCount := FSheets.Count;
end;
function TThPageControl.GetSheetNamePrefix: string;
begin
Result := Name + 'Sheet_';
end;
procedure TThPageControl.RenameSheets;
var
i: Integer;
begin
for i := 0 to Pred(Count) do
Sheet[i].Name := Format('%s%d', [ GetSheetNamePrefix, i + 1 ]);
end;
function TThPageControl.GetHtmlAsString: string;
begin
RenameSheets;
Result := inherited GetHtmlAsString;
end;
initialization
RegisterClass(TThSheet);
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{
OpenAL based sound-manager (http://www.openal.org).
OpenAL drivers can be download from the OpenAL site or your soundcard
manufacturer's website.
Unsupported feature(s) :
Accepts only simple *uncompressed* WAV files (8/16 bits, mono/stereo)
Dynamic loading/unloading
Global 3D parameters
Environments
CPUUsagePercent
No system in place to limit number of sources playing simultaneously,
can crash if too playing at once.
}
unit GLSMOpenAL;
interface
{$I GLScene.inc}
uses
System.Classes,
System.SysUtils,
Vcl.Forms,
Vcl.Dialogs,
GLScene,
GLSound,
GLSoundFileObjects;
type
TGLSMOpenAL = class(TGLSoundManager)
private
FActivated: Boolean;
protected
function DoActivate: Boolean; override;
procedure DoDeActivate; override;
procedure NotifyMasterVolumeChange; override;
procedure Notify3DFactorsChanged; override;
procedure NotifyEnvironmentChanged; override;
procedure KillSource(aSource: TGLBaseSoundSource); override;
procedure UpdateSource(aSource: TGLBaseSoundSource); override;
procedure MuteSource(aSource: TGLBaseSoundSource; muted: Boolean); override;
procedure PauseSource(aSource: TGLBaseSoundSource; paused: Boolean); override;
function GetDefaultFrequency(aSource: TGLBaseSoundSource): Integer;
function GetALFormat(sampling: TGLSoundSampling): Integer;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure UpdateSources; override;
function EAXSupported: Boolean; override;
end;
EOpenALError = Exception;
// ---------------------------------------------------------------------
implementation
// ---------------------------------------------------------------------
uses
GLVectorGeometry,
OpenAL {al, alut, alTypes};
// checks for an error and raises an exception if necessary
procedure CheckOpenALError;
var
error: Integer;
begin
error := alGetError;
if error <> AL_NO_ERROR then
raise EOpenALError.Create('OpenAL Error #' + IntToStr(error) + ' (HEX: $' + IntToHex(error, 4) + ')');
end;
// clears the error-states
procedure ClearOpenALError;
begin
alGetError;
end;
// ------------------
// ------------------ TGLSMOpenAL ------------------
// ------------------
constructor TGLSMOpenAL.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor TGLSMOpenAL.Destroy;
begin
inherited Destroy;
end;
function TGLSMOpenAL.DoActivate: Boolean;
var
dummy: array of PALbyte;
begin
Result := false;
// Setup OpenAL
if not InitOpenAL() then
Exit;
dummy := nil;
alutInit(nil, dummy);
CheckOpenALError;
alDistanceModel(AL_INVERSE_DISTANCE);
CheckOpenALError;
ReadOpenALExtensions();
// Set any global states
FActivated := true;
NotifyMasterVolumeChange;
Notify3DFactorsChanged;
if Environment <> seDefault then
NotifyEnvironmentChanged;
Result := true;
end;
procedure TGLSMOpenAL.DoDeActivate;
var
i: Integer;
begin
FActivated := false;
for i := 0 to Sources.Count - 1 do
begin
Sources[i].Sample.ManagerTag := 0;
end;
alutExit;
end;
procedure TGLSMOpenAL.NotifyMasterVolumeChange;
begin
if FActivated then
begin
alListenerf(AL_GAIN, MasterVolume);
end;
end;
procedure TGLSMOpenAL.Notify3DFactorsChanged;
begin
if FActivated then
begin
alDopplerFactor(DopplerFactor);
end;
end;
procedure TGLSMOpenAL.NotifyEnvironmentChanged;
begin
if FActivated then
begin
// check extension is available + update
if EAXSupported then
begin
// nothing yet
end;
end;
end;
procedure TGLSMOpenAL.KillSource(aSource: TGLBaseSoundSource);
var
i, currentBufferTag, bufferCount: Integer;
begin
if aSource.ManagerTag <> 0 then
begin
alSourceStop(aSource.ManagerTag);
alDeleteSources(1, PALuint(@aSource.ManagerTag));
aSource.ManagerTag := 0;
// We can't just delete buffer, because other sources may be using it
// so we count how many sources are using, then delete if it's the only one
// using.
// Same for ASource.Sample.ManagerTag, we set to zero once it's no longer
// being used by any other sources
currentBufferTag := aSource.Sample.ManagerTag;
bufferCount := 0;
if currentBufferTag <> 0 then
begin
for i := 0 to Sources.Count - 1 do
begin
if Sources[i].Sample.ManagerTag = currentBufferTag then
begin
bufferCount := bufferCount + 1;
end;
end;
if bufferCount = 1 then
begin
alDeleteBuffers(1, PALuint(@aSource.Sample.ManagerTag));
aSource.Sample.ManagerTag := 0;
end;
end;
end;
end;
procedure TGLSMOpenAL.UpdateSource(aSource: TGLBaseSoundSource);
var
a: TALint;
begin
// Clear any errors we may enter into procedure with
ClearOpenALError;
// Creates an OpenAL source object if needed, and put ID into aSource.ManagerTag
if aSource.ManagerTag = 0 then
begin
alGenSources(1, PALuint(@aSource.ManagerTag));
CheckOpenALError;
end
else
begin
// Check to see if source has stopped, if so free it as limited number of sources allowed
alGetSourcei(aSource.ManagerTag, AL_SOURCE_STATE, @a);
CheckOpenALError;
if a = AL_STOPPED then
begin
aSource.Free;
Exit;
end;
end;
// if sscTransformation in aSource.Changes then begin
alSourcefv(aSource.ManagerTag, AL_POSITION, PALFloat(aSource.Origin.Position.asAddress));
CheckOpenALError;
alSourcefv(aSource.ManagerTag, AL_DIRECTION, PALFloat(aSource.Origin.Direction.asAddress));
CheckOpenALError;
// end;
if aSource.SoundName <> '' then
begin
// If the sample doesn't have a reference to an OpenAL buffer
// we need to create a buffer, and load the sample data into it
if (aSource.Sample.ManagerTag = 0) and Assigned(aSource.Sample.Data) then
begin
alGenBuffers(1, PALuint(@aSource.Sample.ManagerTag));
CheckOpenALError;
// fill buffer (once buffer filled, can't fill buffer again, unless no other sources playing)
alBufferData(aSource.Sample.ManagerTag, GetALFormat(aSource.Sample.sampling), aSource.Sample.Data.PCMData,
aSource.Sample.Data.LengthInBytes, aSource.Sample.Data.sampling.Frequency);
CheckOpenALError;
end;
if (sscSample in aSource.Changes) and Assigned(aSource.Sample.Data) then
begin
// Associate buffer with source, buffer may have either been recently
// created, or already existing if being used by another source
alSourcei(aSource.ManagerTag, AL_BUFFER, aSource.Sample.ManagerTag);
CheckOpenALError;
// If NbLoops>1 the source will constantly loop the sample, otherwise only play once
alSourcei(aSource.ManagerTag, AL_LOOPING, Integer(aSource.NbLoops > 1));
CheckOpenALError;
// Start the source playing!
alSourcePlay(aSource.ManagerTag);
CheckOpenALError;
end;
end;
if sscStatus in aSource.Changes then
begin
alSourcef(aSource.ManagerTag, AL_PITCH, 1.0);
CheckOpenALError;
alSourcef(aSource.ManagerTag, AL_GAIN, 1.0);
CheckOpenALError;
alSourcef(aSource.ManagerTag, AL_MAX_DISTANCE, aSource.MaxDistance);
CheckOpenALError;
alSourcef(aSource.ManagerTag, AL_ROLLOFF_FACTOR, 1.0);
CheckOpenALError;
alSourcef(aSource.ManagerTag, AL_REFERENCE_DISTANCE, aSource.MinDistance);
CheckOpenALError;
alSourcef(aSource.ManagerTag, AL_CONE_INNER_ANGLE, aSource.InsideConeAngle);
CheckOpenALError;
alSourcef(aSource.ManagerTag, AL_CONE_OUTER_ANGLE, aSource.OutsideConeAngle);
CheckOpenALError;
alSourcef(aSource.ManagerTag, AL_CONE_OUTER_GAIN, aSource.ConeOutsideVolume);
end;
inherited UpdateSource(aSource);
end;
procedure TGLSMOpenAL.MuteSource(aSource: TGLBaseSoundSource; muted: Boolean);
begin
if muted then
alSourcef(aSource.ManagerTag, AL_MAX_GAIN, 0.0)
else
alSourcef(aSource.ManagerTag, AL_MAX_GAIN, 1.0);
end;
procedure TGLSMOpenAL.PauseSource(aSource: TGLBaseSoundSource; paused: Boolean);
begin
if not paused then
begin
alSourceRewind(aSource.ManagerTag);
alSourcePlay(aSource.ManagerTag);
end
else
alSourcePause(aSource.ManagerTag);
end;
procedure TGLSMOpenAL.UpdateSources;
var
pos, dir, up, vel: TVector;
DirUp: array [0 .. 5] of TALfloat; // orientation
begin
ListenerCoordinates(pos, vel, dir, up);
alListenerfv(AL_POSITION, PALFloat(@pos));
alListenerfv(AL_VELOCITY, PALFloat(@vel));
DirUp[0] := dir.X;
DirUp[1] := dir.Y;
DirUp[2] := dir.Z;
DirUp[3] := up.X;
DirUp[4] := up.Y;
DirUp[5] := up.Z;
alListenerfv(AL_ORIENTATION, PALFloat(@DirUp));
inherited;
end;
function TGLSMOpenAL.EAXSupported: Boolean;
begin
Result := alIsExtensionPresent(PAnsiChar('EAX2.0'));
end;
function TGLSMOpenAL.GetDefaultFrequency(aSource: TGLBaseSoundSource): Integer;
begin
Result := -1;
end;
function TGLSMOpenAL.GetALFormat(sampling: TGLSoundSampling): Integer;
begin
Result := 0;
// mono
if sampling.NbChannels = 1 then
case sampling.BitsPerSample of
8:
Result := AL_FORMAT_MONO8;
16:
Result := AL_FORMAT_MONO16;
end
else
case sampling.BitsPerSample of // stereo
8:
Result := AL_FORMAT_STEREO8;
16:
Result := AL_FORMAT_STEREO16;
end;
end;
end.
|
// ###################################################################
// #### This file is part of the mathematics library project, and is
// #### offered under the licence agreement described on
// #### http://www.mrsoft.org/
// ####
// #### Copyright:(c) 2019, Michael R. . All rights reserved.
// ####
// #### 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.
// ###################################################################
// this unit translates JSON formatted data to and from the Fido2 objects.
// it's based on the the Delphi Json Library "superobject" from
// https://github.com/hgourvest/superobject
// ###########################################
// #### These utility classes can be used to interface the webauthn.js files
// #### provided with this project
// ###########################################
unit WebauthnUtil;
interface
uses SysUtils, Fido2, SuperObject, cbor, authData, winCryptRandom;
type
EFidoDataHandlerException = class(Exception);
// ###########################################
// #### Base properties required by the server
type
TFidoAttestationType = (atDirect, atNone, atIndirect);
TFidoServer = class(TObject)
private
fRelID: string;
fTimeOut: integer;
fRelParty: string;
fAttestationType : TFidoAttestationType;
fResidentKey : boolean;
fUserVerification : boolean;
public
property RelyingParty : string read fRelParty write fRelParty;
property RelyingPartyId : string read fRelID write fRelId;
property AttestType : TFidoAttestationType read fAttestationType write fAttestationType;
property TimeOut : integer read fTimeOut write fTimeOut;
property RequireResidentKey : boolean read fResidentKey write fResidentKey;
property UserVerification : boolean read fUserVerification write fUserVerification;
function RPIDHash : TFidoSHA256Hash;
function ToJSON : ISuperObject;
constructor Create;
end;
type
TFidoUserStartRegister = class(TObject)
private
const cNoUserId : TFidoUserId = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0);
cNoChallange : TFidoChallenge = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0);
private
fDisplName: string;
fUserName: string;
fUserid : TFidoUserId;
fChallenge : TFidoChallenge;
fRand : IRndEngine;
procedure InitUserId;
procedure InitChallenge;
public
property UserName : string read fUserName write fUserName;
property UserDisplName : string read fDisplName write fDisplName;
property UserId : TFidoUserId read fUserId write fUserId;
property Challenge : TFidoChallenge read fChallenge write fChallenge;
function ToJson : ISuperObject;
procedure SaveChallenge;
function CheckUser( uname : string ) : boolean;
constructor Create( UName, displName : string; rand : IRndEngine);
end;
type
TCustomFidoVerify = class(TObject)
protected
function DecodeAttestationObj( attestStr : string; var alg : integer;
var fmt : string; var sig, authData, x5c : TBytes ) : boolean;
end;
// ###########################################
// #### Class to verify the credentials created from the initial starting registering process
type
TFidoUserRegisterVerify = class(TCustomFidoVerify)
public
function VerifyAndSaveCred( credJson : string ) : string;
end;
// ###########################################
// #### Assertion
type
TFidoUserAssert = class(TCustomFidoVerify)
private
fRand : IRndEngine;
function CheckCredentials(userHandle: string; origChallenge: ISuperObject;
var credId: string): boolean;
public
function StartAssertion( uname : string ) : string;
function VerifyAssert( assertionStr : string; var resStr : string ) : boolean;
constructor Create(rand : IRndEngine);
end;
// ###########################################
// #### User registration handling
type
IFidoDataHandling = interface
['{B3AF2050-BB60-46DC-8BBA-9102076F2480}']
function IsAlreadRegistered( uname : string ) : boolean; overload;
function IsAlreadRegistered( uname : string; var credIDFN : string ) : boolean; overload;
function IsChallengeInitiated( challenge : string ) : boolean;
procedure SaveUserInitChallenge( user : TFidoUserStartRegister );
procedure SaveCred( challenge : string; cred : TFidoCredVerify; authData : TAuthData );
function CredToUser(credId: string; var uname: string): boolean;
procedure SaveAssertChallengeData( challenge : ISuperObject );
function LoadAssertChallengeData( challenge : string ) : ISuperObject;
function CheckSigCounter(credId: string; authData: TAuthData): boolean;
end;
function FidoServer : TFidoServer;
function SHA256FromBuf( buf : PByte; len : integer ) : TFidoSHA256Hash;
procedure SetFidoDataHandler( aHandler : IFidoDataHandling );
function FidoDataHandler : IFidoDataHandling;
implementation
uses syncObjs, strUtils, Classes, IdHashSHA, IdGlobal, IdSSLOpenSSLHeaders,
Fido2dll, Windows;
var locServer : TFidoServer = nil;
locDataHandler : IFidoDataHandling = nil;
cs : TCriticalSection;
procedure SetFidoDataHandler( aHandler : IFidoDataHandling );
begin
locDataHandler := aHandler;
end;
function FidoDataHandler : IFidoDataHandling;
begin
Assert( Assigned(locDataHandler), 'Data handler not assigend - call SetFidoDataHandler at first');
Result := locDataHandler;
end;
function FidoServer : TFidoServer;
begin
cs.Enter;
try
Result := locServer;
if not Assigned(Result) then
begin
Result := TFidoServer.Create;
locServer := Result;
end;
finally
cs.Leave;
end;
end;
function CredentialToJSon( cred : TFidoCredCreate ) : string;
var clIDHash : TFidoSHA256Hash;
json : ISuperObject;
chArr : TSuperArray;
i : Integer;
obj : ISuperObject;
begin
json := SO;
// ###############################################
// #### Challange
clIDHash := cred.ClientDataHash;
obj := SO;
chArr := obj.AsArray;
for i := 0 to Length(clIDHash) - 1 do
chArr.Add( TSuperObject.Create(clIDHash[i]) );
json.O['Challange'] := obj;
Result := json.AsJSon;
end;
{ TFidoServer }
constructor TFidoServer.Create;
begin
inherited Create;
fRelID := 'fidotest.com';
fRelParty := 'fidotest.com';
fAttestationType := atNone;
fResidentKey := True;
fTimeOut := 60000;
end;
function TFidoServer.RPIDHash: TFidoSHA256Hash;
var buf : UTF8String;
begin
buf := UTF8String( RelyingPartyId );
FillChar(Result, sizeof(Result), 0);
if buf <> '' then
Result := SHA256FromBuf( @buf[1], Length(buf));
end;
function TFidoServer.ToJSON: ISuperObject;
begin
// an array of the 3 standard encryption algorithm the fido dll supports
// COSE_ES256 = -7;
// COSE_EDDSA = -8;
// COSE_RS256 = -257;
Result := SO('{"publicKey":{"pubKeyCredParams":[{"alg":-7,"type":"public-key"},{"alg":-257,"type":"public-key"},{"alg":-8,"type":"public-key"}]}}');
Result.I['publicKey.Timeout'] := fTimeOut;
Result.S['publicKey.rp.id'] := fRelID;
Result.S['publicKey.rp.name'] := fRelParty;
Result.S['publicKey.authenticatorSelection.authenticatorAttachment'] := 'cross-platform'; // fido dll -> cross platform we don't support TPM or others yet...
case fAttestationType of
atDirect: Result.S['publicKey.attestation'] := 'direct';
atNone: Result.S['publicKey.attestation'] := 'none';
atIndirect: Result.S['publicKey.attestation'] := 'indirect';
end;
Result.B['publicKey.authenticatorSelection.requireResidentKey'] := fResidentKey;
// todo: preferred missing
Result.S['publicKey.authenticatorSelection.userVerification'] := ifthen( fUserVerification, 'required', 'discouraged');
end;
{ TFidoUserStartRegister }
function TFidoUserStartRegister.CheckUser(uname: string): boolean;
begin
Result := not FidoDataHandler.IsAlreadRegistered(uname);
end;
constructor TFidoUserStartRegister.Create(UName, displName: string; rand : IRndEngine);
begin
fRand := rand;
fDisplName := displName;
fUserName := UName;
if fDisplName = '' then
fDisplName := fUserName;
// create a new cahllange and user id
InitChallenge;
InitUserId;
inherited Create;
end;
procedure TFidoUserStartRegister.InitChallenge;
var i : integer;
begin
for i := 0 to Length(fchallenge) - 1 do
fChallenge[i] := fRand.Random;
end;
procedure TFidoUserStartRegister.InitUserId;
var i : integer;
begin
// first byte of the random user ID shall not be one or zero
// see: https://developers.yubico.com/WebAuthn/WebAuthn_Developer_Guide/User_Handle.html
repeat
fUserid[0] := fRand.Random;
until fUserid[0] > 1;
for i := 1 to High(fUserid) do
fUserid[i] := fRand.Random;
end;
procedure TFidoUserStartRegister.SaveChallenge;
begin
assert( Assigned(locDataHandler), 'Error no data handler assigned');
locDataHandler.SaveUserInitChallenge( self );
end;
function TFidoUserStartRegister.ToJson: ISuperObject;
var server : ISuperObject;
begin
// check if the user id and challenge is initialized
if CompareMem( @fUserid[0], @cNoUserId[0], sizeof(fUserid)) then
raise EFidoPropertyException.Create('No User ID created');
// build result
Result := SO('{"publicKey":{}}');
Result.S['publicKey.user.displayName'] := fDisplName;
Result.S['publicKey.user.name'] := fUserName;
Result.S['publicKey.user.id'] := Base64URLEncode( PByte( @fUserid[0] ), sizeof(fUserid) );
Result.S['publicKey.challenge'] := Base64URLEncode( PByte( @fChallenge[0] ), sizeof(fChallenge) );
server := FidoServer.ToJSON;
Result.Merge(server);
end;
function SHA256FromBuf( buf : PByte; len : integer ) : TFidoSHA256Hash;
var hash : TIdHashSHA256;
indyBuf : TidBytes;
res : TidBytes;
begin
if not IdSSLOpenSSLHeaders.Load then
raise Exception.Create('Failed to load Openssl lib');
if not TIdHashSHA256.IsAvailable then
raise Exception.Create('Hashing function not available');
hash := TIdHashSHA256.Create;
try
SetLength(indyBuf, len);
Move( buf^, indyBuf[0], len);
res := hash.HashBytes(indyBuf);
if length(res) <> sizeof(result) then
raise Exception.Create('Hash failed');
Move( res[0], Result[0], sizeof(Result));
finally
hash.Free;
end;
end;
{ TCustomFidoVerify }
function TCustomFidoVerify.DecodeAttestationObj(attestStr: string;
var alg: integer; var fmt: string; var sig, authData, x5c: TBytes): boolean;
var cborItem : TCborMap;
restBuf : TBytes;
aName : string;
attStmt : TCborMap;
i, j : integer;
begin
Result := false;
// attestation object is a cbor encoded raw base64url encoded string
cborItem := TCborDecoding.DecodeBase64UrlEx(attestStr, restBuf) as TCborMap;
// check if there is data left indicating bad cbor format
if Length(restBuf) <> 0 then
exit;
if not Assigned(cborItem) then
exit;
try
alg := 0;
fmt := '';
sig := nil;
authData := nil;
x5c := nil;
for i := 0 to cborItem.Count - 1 do
begin
// check cbor map name format
if not (cborItem.Names[i] is TCborUtf8String) then
exit;
aName := String((cborItem.Names[i] as TCborUtf8String).Value);
if SameText(aName, 'attStmt') then
begin
attStmt := cborItem.Values[i] as TCborMap;
for j := 0 to attStmt.Count - 1 do
begin
aName := String((attStmt.Names[j] as TCborUtf8String).Value);
if SameText(aName, 'alg')
then
alg := (attStmt.Values[j] as TCborNegIntItem).value
else if SameText(aName, 'sig')
then
sig := (attStmt.Values[j] as TCborByteString).ToBytes
else if SameText(aName, 'x5c')
then
x5c := ((attStmt.Values[j] as TCborArr)[0] as TCborByteString).ToBytes;
end;
end
else if SameText(aName, 'authData')
then
authData := (cborItem.Values[i] as TCborByteString).ToBytes
else if SameText(aName, 'fmt')
then
fmt := String( (cborItem.Values[i] as TCborUtf8String).Value );
end;
finally
cborItem.Free;
end;
// minimum requirements
Result := (fmt <> '') and (alg <> 0);
end;
{ TFidoUserRegisterVerify }
function TFidoUserRegisterVerify.VerifyAndSaveCred(credJson: string): string;
var clientData : ISuperObject;
s : string;
credentialId : string;
rawId : TBytes;
credVerify : TFidoCredVerify;
sig : TBytes;
x5c : TBytes;
authData : TBytes;
fmt : string;
alg : integer;
res : boolean;
credFMT : TFidoCredentialFmt;
authDataObj : TAuthData;
restBuf : TBytes;
clientDataStr : RawByteString;
clientDataHash : TFidoSHA256Hash;
serverRPIDHash : TFidoSHA256Hash;
rpIDHash : TFidoRPIDHash;
credential : ISuperObject;
begin
Result := '{"error":0,"msg":"Error parsing content"}';
credential := SO(credJSON);
if not Assigned(credential) then
exit;
s := credential.S['response.clientDataJSON'];
if s = '' then
exit;
ClientData := So( String(Base64URLDecode( s )) );
if clientData = nil then
exit;
// ###########################################
// #### Check if the challenge has been initiated
if not FidoDataHandler.IsChallengeInitiated(ClientData.S['challenge']) then
begin
Result := '{"error":1,"msg":"Client data json parsing error - challenge not initiated"}';
exit;
end;
// calculate hash from clientDataJSON
clientDataStr := Base64URLDecode( credential.S['response.clientDataJSON'] );
if clientDataStr = '' then
begin
Result := '{"error":2,"msg":"Client data json missing"}';
exit;
end;
// create the client hash that is later used in the verification process
clientDataHash := SHA256FromBuf( @clientDataStr[1], Length(clientDataStr) );
clientData := SO( String( clientDataStr ) );
s := credential.S['response.attestationObject'];
if s = '' then
exit;
if not DecodeAttestationObj(s, alg, fmt, sig, authData, x5c) then
begin
Result := '{"error":2,"msg":"Decoding failed"}';
exit;
end;
// check if anyhing is in place
if not (( alg = COSE_ES256 ) or (alg = COSE_EDDSA) or (alg = COSE_RS256)) then
raise Exception.Create('Unknown algorithm');
if Length(sig) = 0 then
raise Exception.Create('No sig field provided');
if Length(x5c) = 0 then
raise Exception.Create('No certificate');
if Length(authData) = 0 then
raise Exception.Create('Missing authdata');
credentialId := credential.S['rawId'];
if s = '' then
raise Exception.Create('No Credential id found');
rawId := Base64URLDecodeToBytes( s );
authDataObj := nil;
if Length(restBuf) > 0 then
raise Exception.Create('Damend there is a rest buffer that should not be');
if Length(authData) > 0 then
authDataObj := TAuthData.Create( authData );
try
if not Assigned(authDataObj) then
exit;
if not authDataObj.UserPresent then
begin
Result := '{"error":3,"msg":"Error: parameter user present not set"}';
exit;
end;
if authDataObj.UserVerified <> FidoServer.UserVerification then
begin
Result := '{"error":4,"msg":"Error: parameter user verification not set to the default"}';
exit;
end;
// check rp hash
rpIDHash := authDataObj.rpIDHash;
serverRPIDHash := FidoServer.RPIDHash;
if not CompareMem( @rpIDHash[0], @serverRPIDHash[0], sizeof(rpIDHash)) then
begin
Result := '{"error":4,"msg":"The relying party hash does not match"}';
exit;
end;
if fmt = 'packed'
then
credFmt := fmFido2
else if fmt = 'fido-u2f'
then
credFmt := fmU2F
else
credFmt := fmDef;
// ###########################################
// #### Now bring the fido dll into action
credVerify := TFidoCredVerify.Create( TFidoCredentialType(alg), credFmt,
FidoServer.RelyingPartyId, FidoServer.RelyingParty,
TBaseFido2Credentials.WebAuthNObjDataToAuthData( authData ),
x5c, sig,
FidoServer.RequireResidentKey,
authDataObj.UserVerified, 0) ;
try
res := credVerify.Verify(clientDataHash);
if res then
begin
// ###########################################
// #### save EVERYTHING to a database
FidoDataHandler.SaveCred(ClientData.S['challenge'], credVerify, authDataObj);
end;
finally
credVerify.Free;
end;
finally
authDataObj.Free;
end;
// build result and generate a session
if res then
begin
// yeeeha we got it done
Result := '{"success":true}';
end
else
Result := '{"success":false}';
end;
{ TFidoUserAssert }
constructor TFidoUserAssert.Create(rand: IRndEngine);
begin
fRand := rand;
if not Assigned(fRand) then
fRand := CreateWinRndObj;
inherited Create;
end;
function TFidoUserAssert.StartAssertion(uname: string): string;
var res : ISuperObject;
challenge : TFidoChallenge;
i: Integer;
credID : string;
credObj : ISuperObject;
begin
credID := '';
// no user name given -> just create a challenge (maybe a user handle is used)
if (uname <> '') and not FidoDataHandler.IsAlreadRegistered(uname, credID) then
exit('{"error":0,"msg":"User not registered"}');
res := SO('{"publicKey":{"allowCredentials":[]}}');
for i := 0 to Length(challenge) - 1 do
challenge[i] := fRand.Random;
res.S['publicKey.challenge'] := Base64URLEncode(@challenge[0], length(challenge));
res.I['publicKey.timeout'] := FidoServer.TimeOut;
res.S['publicKey.rpid'] := FidoServer.RelyingPartyId;
res.B['publicKey.userVerificaiton'] := FidoServer.UserVerification;
// return an empty list if no username was provided -> user id required
if credID <> '' then
begin
credObj := SO( '{"type":"public-key"}' );
credObj.S['id'] := credID;
res.A['publicKey.allowCredentials'].Add( credObj );
end;
res.O['extensions'] := SO('{"txAuthSimple":""}');
// ###########################################
// #### Save the challenge for later comparison
FidoDataHandler.SaveAssertChallengeData( res );
Result := res.AsJSon;
end;
// checks if a user with a given user handle was already registered or
// if credentials can be mapped to a given challenge
function TFidoUserAssert.CheckCredentials(userHandle: string;
origChallenge: ISuperObject; var credId : string): boolean;
var cred : TSuperArray;
begin
if userHandle <> ''
then
Result := FidoDataHandler.IsAlreadRegistered(userHandle, credId)
else
begin
Result := False;
cred := origChallenge.A['publicKey.allowCredentials'];
if (cred <> nil) and (cred.Length > 0) then
begin
Result := True;
credId := cred.O[0].S['id'];
end;
end;
end;
function TFidoUserAssert.VerifyAssert(assertionStr: string;
var resStr: string): boolean;
var clientData : ISuperObject;
userHandle : string;
sig : TBytes;
credID : string;
clientDataStr : RawByteString;
clientDataHash : TFidoSHA256Hash;
authDataObj : TAuthData;
rpIdHash : TFidoRPIDHash;
serverRPIDHash : TFidoSHA256Hash;
credFmt : TFidoCredentialFmt;
assertVerify : TFidoAssertVerify;
buf : TBytes;
challenge : TFidoChallenge;
authData : TBytes;
origChallenge : ISuperObject;
selCredId : string;
uname : string;
res : ISuperObject;
assertion : ISuperObject;
begin
Result := False;
resStr := '{"error":0,"msg":"Error parsing content"}';
assertion := SO(assertionStr);
if not Assigned(assertion) then
exit;
clientDataStr := Base64URLDecode( assertion.S['response.clientDataJSON'] );
if clientDataStr = '' then
exit;
ClientData := So( String( clientDataStr ) );
if clientData = nil then
exit;
userhandle := assertion.S['response.userHandle'];
sig := Base64URLDecodeToBytes(assertion.S['response.signature']);
credId := assertion.S['id'];
if assertion.S['type'] <> 'public-key' then
exit;
// ###########################################
// #### Load data from the initialization procedure
origChallenge := FidoDataHandler.LoadAssertChallengeData(clientData.S['challenge']);
if not Assigned(origChallenge) then
begin
resStr := '{"error":1,"msg":"Challenge not initiated"}';
exit;
end;
// create the client hash that is later used in the verification process
clientDataHash := SHA256FromBuf( @clientDataStr[1], Length(clientDataStr) );
authData := Base64URLDecodeToBytes(assertion.S['response.authenticatorData']);
// check if anyhing is in place
//if not (( alg = COSE_ES256 ) or (alg = COSE_EDDSA) or (alg = COSE_RS256)) then
// raise Exception.Create('Unknown algorithm');
if Length(sig) = 0 then
begin
resStr := '{"error":1,"msg":"No sig field provided"}';
exit;
end;
if Length(authData) = 0 then
begin
resStr := '{"error":1,"msg":"Missing authdata"}';
exit;
end;
authDataObj := nil;
if Length(authData) > 0 then
authDataObj := TAuthData.Create( authData );
try
if not Assigned(authDataObj) then
exit;
OutputDebugString( PChar('Guid: ' + GuidToString(authDataObj.AAUID)) );
if not CheckCredentials( userHandle, origChallenge, selCredId ) then
begin
resStr := '{"error":2,"msg":"Credentials not in user list"}';
exit;
end;
if selCredId <> credID then
begin
resStr := '{"error":2,"msg":"Credentials not in user list"}';
exit;
end;
// check user id attached to credential id
if not FidoDataHandler.CredToUser( credId, uname ) then
begin
resStr := '{"error":2,"msg":"Credentials not in user list"}';
exit;
end;
// todo: maybe it's a good idea to check the guid (got from direct attestation)
if not authDataObj.UserPresent then
begin
resStr := '{"error":3,"msg":"Error: parameter user present not set"}';
exit;
end;
if authDataObj.UserVerified <> FidoServer.UserVerification then
begin
resStr := '{"error":4,"msg":"Error: parameter user verification not set to the default"}';
exit;
end;
// check rp hash
rpIDHash := authDataObj.rpIDHash;
serverRPIDHash := FidoServer.RPIDHash;
if not CompareMem( @rpIDHash[0], @serverRPIDHash[0], sizeof(rpIDHash)) then
begin
resStr := '{"error":6,"msg":"The relying party hash does not match"}';
exit;
end;
credFmt := fmFido2;
buf := Base64URLDecodeToBytes( clientData.S['challenge']);
if Length(buf) <> sizeof(challenge) then
begin
resStr := '{"error":5,"msg":"Challange type failed"}';
exit;
end;
move( buf[0], challenge, sizeof(challenge));
// ###########################################
// #### Verify with the fido dll
assertVerify := TFidoAssertVerify.Create;
try
assertVerify.RelyingParty := FidoServer.RelyingPartyId;
assertVerify.LoadPKFromFile( credId + '.pk');
assertVerify.ClientDataHash := TFidoChallenge( clientDataHash );
assertVerify.Fmt := credFmt;
if authDataObj.UserVerified
then
assertverify.UserVerification := FIDO_OPT_TRUE
else
assertverify.UserVerification := FIDO_OPT_FALSE;
if authDataObj.UserPresent
then
assertVerify.UserPresence := FIDO_OPT_TRUE
else
assertVerify.UserPresence := FIDO_OPT_FALSE;
if assertVerify.Verify( TBaseFido2Credentials.WebAuthNObjDataToAuthData( authData ),
sig )
then
begin
// check signal counter
if not FidoDataHandler.CheckSigCounter( credId, authDataObj ) then
begin
resStr := '{"error":5,"msg":"Signal counter is too low - maybe cloned?"}';
exit;
end;
res := SO('{"success":true}');
res.S['username'] := uname;
resStr := res.AsJSon;
Result := True;
end
else
begin
resStr := '{"success":false}';
end;
finally
assertVerify.Free;
end;
finally
authDataObj.Free;
end;
end;
initialization
cs := TCriticalSection.Create;
finalization
locServer.Free;
cs.Free;
end.
|
{*******************************************************}
{ }
{ CPBHL报表 }
{ }
{ 版权所有 (C) 2015 Danny }
{ }
{ 时间: 2015.03.06 00:30:51}
{ }
{ 作者: Danny }
{ }
{ }
{ 功能描述: H/L来样信息明细格式
序号 来样编号 色号 来样日期 完成日期 打样次数 打样个数 周期 REJECT 整理方式 客户 品名
1 LB12-597 0126KK01 4-1 4-4 6 20 3 REJECT royal EBO PDKC00206
规则
1、来样日期:色号编制保存时间
2、完成日期:送样保存时间
3、打样次数:打样录入配方处的录入次数,前一次录入配方的保存时间到后一次录入配方的保存时间大于 0.5H 的算作一次。
4、打样个数:标记OK方界面 里面的所有个数
5、周期:(打样结束时间-色号编制时间)/24,时间精确到小时(保留两位小数)
6、REJECT 次数:输入重打评语的次数
}
{ }
{ }
{ }
{ }
{ }
{*******************************************************}
unit frmCPBHLRpt;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, frmBase, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxEdit, DB, cxDBData, StdCtrls, Buttons, ExtCtrls,
cxGridLevel, cxClasses, cxControls, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid,
DBClient, ComCtrls;
type
TCPBHLRptForm = class(TBaseForm)
PanelHeader: TPanel;
Label1: TLabel;
dpBeginDate: TDateTimePicker;
Label2: TLabel;
dpEndDate: TDateTimePicker;
cxgridHLRpt: TcxGrid;
cxgridtvCPBHLRpt: TcxGridDBTableView;
cxGridlHLRpt: TcxGridLevel;
dsCPBHLRpt: TDataSource;
cdsCPBHLRpt: TClientDataSet;
btnRefresh: TSpeedButton;
btnClose: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure btnRefreshClick(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure Query();
end;
var
CPBHLRptForm: TCPBHLRptForm;
implementation
uses ServerDllPub, uGlobal, uShowMessage, uFNMResource, uGridDecorator, uAppOption, uLogin,
frmMain,uDictionary;
{$R *.dfm}
procedure TCPBHLRptForm.FormCreate(Sender: TObject);
begin
inherited;
dpEndDate.DateTime:=Now-1;
dpBeginDate.DateTime:=dpEndDate.DateTime-7;
end;
procedure TCPBHLRptForm.btnRefreshClick(Sender: TObject);
begin
inherited;
Query;
end;
procedure TCPBHLRptForm.Query;
var vData: OleVariant;
sCondition,sErrorMsg: WideString;
sBeginDate, sEndDate:string;
begin
try
sBeginDate:='';
sEndDate:='';
if dpBeginDate.Checked then
sBeginDate:=FormatDateTime('yyyy-MM-dd',dpBeginDate.DateTime);
if dpEndDate.Checked then
sEndDate:=FormatDateTime('yyyy-MM-dd',dpEndDate.DateTime);
Screen.Cursor := crHourGlass;
ShowMsg('正在获取数据稍等!',crHourGlass);
sCondition := QuotedStr(sBeginDate)+','+QuotedStr(sEndDate);
FNMServerObj.GetQueryData(vData, 'CPBHLRpt', sCondition, sErrorMsg);
if sErrorMsg<>'' then
begin
TMsgDialog.ShowMsgDialog(sErrorMsg,mtError);
Exit;
end;
cdsCPBHLRpt.Data := vData;
GridDecorator.BindCxViewWithDataSource(cxgridtvCPBHLRpt, dsCPBHLRpt);
finally
Screen.Cursor := crDefault;
ShowMsg('',crDefault);
end;
end;
procedure TCPBHLRptForm.btnCloseClick(Sender: TObject);
begin
inherited;
Close;
end;
end.
|
unit stmUplot;
interface
{$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF}
{ TuserPlot est un objet STM possédant une propriété OnPaint. OnPaint reçoit par
programme l'adresse d'une procédure de dessin PG1.
Quand OnPaint est appelée, le canvas et la fenêtre multigraph sont ont été
sélectionnées. OnPaint ne doit jamais appeler setWindow ou setWindowEx.
Si un deuxième multigraph existait, il y aurait problème. Il faudrait transmettre
à OnPaint, l'adresse de l'objet Multigraph concerné.
TuserPlot possède son propre contexte d'affichage (varPg1) afin de ne pas interférer
avec le programme Pg1.
SwapContext(true) est appelé par Multigraph avant Display.
SwapContext(false) est appelé par Multigraph après Display.
Comme le programme utilise les méthodes multiGraph, on ne peut pas afficher en
dehors de Multigraph. La méthode Show est surchargée.
}
uses Dgraphic,stmDef,stmObj,stmPlot1,stmPg,debug0;
type
TuserPlot=class(Tplot)
varPg1:TvarPg1;
onPaint:Tpg2Event;
x1,y1,x2,y2:integer;
constructor create;override;
destructor destroy;override;
class function stmClassName:AnsiString;override;
procedure swapContext(numW:integer;var varPg:TvarPg1;ContextPg:boolean);override;
procedure Display;override;
procedure show(sender:Tobject);override;
end;
procedure proTuserPlot_create(name:AnsiString;var pu:typeUO);pascal;
procedure proTuserPlot_create_1(var pu:typeUO);pascal;
procedure proTuserPlot_onPaint(w:integer;var pu:typeUO);pascal;
function fonctionTuserPlot_onPaint(n:integer;var pu:typeUO):integer;pascal;
implementation
constructor TuserPlot.create;
begin
inherited create;
varPg1:=TvarPg1.create;
end;
destructor TuserPlot.destroy;
begin
varPg1.free;
inherited Destroy;
end;
class function TuserPlot.stmClassName:AnsiString;
begin
result:='UserPlot';
end;
procedure TuserPlot.swapContext(numW:integer;var varPg:TvarPg1;ContextPg:boolean);
var
v:TvarPg1;
begin
if ContextPg then
begin
with varPg1 do
begin
winEx:=true;
win0:=numW;
getWindowG(x1winEx,y1winEx,x2winEx,y2winEx);
canvasPg1:=varPg.canvasPg1;
cleft:=varPg.cleft;
ctop:=varPg.ctop;
cWidth:=varPg.cWidth;
cHeight:=varPg.cHeight;
end;
getWindowG(x1,y1,x2,y2);
end
else setWindow(x1,y1,x2,y2);
v:=varPg;
varPg:=varPg1;
varPg1:=v;
end;
procedure TuserPlot.Display;
begin
with OnPaint do
if valid then pg.executerProcedure(ad);
end;
procedure TuserPlot.show(sender:Tobject);
begin
end;
{************************ Méthodes STM de TuserPlot *************************}
procedure proTuserPlot_create(name:AnsiString;var pu:typeUO);
begin
createPgObject(name,pu,TuserPlot);
end;
procedure proTuserPlot_create_1(var pu:typeUO);
begin
proTuserPlot_create('',pu);
end;
procedure proTuserPlot_onPaint(w:integer;var pu:typeUO);
begin
verifierObjet(pu);
with TuserPlot(pu) do OnPaint.setad(w);
end;
function fonctionTuserPlot_onPaint(n:integer;var pu:typeUO):integer;
begin
verifierObjet(pu);
with TuserPlot(pu) do result:=OnPaint.ad;
end;
Initialization
AffDebug('Initialization Stmuplot',0);
registerObject(TuserPlot,data);
end.
|
unit UnitGeneratorPrinterPreview;
interface
uses
Classes,
Graphics,
UnitPrinterTypes,
Printers,
PrinterProgress,
uMemory,
uDBThread,
uDBForm;
type
TOnEndGeneratePrinterPreviewEvent = procedure(Bitmap: TBitmap; SID: string) of object;
type
TGeneratorPrinterPreview = class(TDBThread)
private
{ Private declarations }
FSID: string;
FFiles: TStrings;
BitmapPreview: TBitmap;
FOnEndProc: TOnEndGeneratePrinterPreviewEvent;
FSampleType: TPrintSampleSizeOne;
FDoPrint: Boolean;
FPrintImagePerPage: Integer;
Pages: Integer;
IntParam: Integer;
StringParam: string;
FSender: TDBForm;
FormProgress: TFormPrinterProgress;
FTerminating: Boolean;
FOptions: TGenerateImageOptions;
FVirtualBitmaped: Boolean;
FVirtualBitmap: TBitmap;
FDestroyBitmap: Boolean;
protected
{ Protected declarations }
procedure Execute; override;
function GetThreadID : string; override;
public
{ Public declarations }
procedure SetImage;
procedure PrintImage;
constructor Create(CreateSuspennded: Boolean; Sender: TDBForm; SID: string; SampleType: TPrintSampleSizeOne;
Files: TStrings; OnEndProc: TOnEndGeneratePrinterPreviewEvent; DoPrint: Boolean; Options: TGenerateImageOptions;
PrintImagePerPage: Integer; VirtualBitmaped: Boolean; VirtualBitmap: TBitmap; DestroyBitmap: Boolean);
destructor Destroy; override;
procedure SetMax(I: Integer);
procedure SetMaxSynch;
procedure SetValue(I: Integer);
procedure SetValueSynch;
procedure SetText(Text: string);
procedure SetCommentText(Text: string);
procedure SetTextSynch;
procedure CallBack(Progress: Byte; var Terminate: Boolean);
procedure ShowProgress;
procedure HideProgress;
procedure SetProgress;
procedure SetCommentTextCynch;
procedure CallBackFull(Progress: Byte; var Terminate: Boolean);
procedure ShowProgressWindow;
procedure HideProgressWindow;
procedure SetProgressWindowMax(Value: Integer);
procedure SetProgressWindowMaxSynch;
procedure SetProgressWindowValue(Value: Integer);
procedure SetProgressWindowValueSynch;
end;
implementation
uses
PrintMainForm;
procedure TGeneratorPrinterPreview.Execute;
var
J, I, Incr: Integer;
Files: TStrings;
begin
inherited;
FreeOnTerminate := True;
if not FDoPrint then
begin
SetCommentText(L('Generating preview') + '...');
SynchronizeEx(ShowProgress);
FOptions.VirtualImage := FVirtualBitmaped;
FOptions.Image := FVirtualBitmap;
BitmapPreview := GenerateImage(True, Printer.PageWidth, Printer.PageHeight, nil, FFiles, FSampleType, FOptions,
CallBack);
SynchronizeEx(SetImage);
SynchronizeEx(HideProgress);
SetCommentText('');
end else
begin
SynchronizeEx(ShowProgressWindow);
if FOptions.FreeCenterSize then
FPrintImagePerPage := 1;
Pages := (FFiles.Count div FPrintImagePerPage);
if (FFiles.Count - Pages * FPrintImagePerPage) > 0 then
Inc(Pages);
Files := TStringList.Create;
try
SetProgressWindowMax(Pages);
if FVirtualBitmaped then
Pages := 1;
for I := 1 to Pages do
begin
if FTerminating then
Break;
SetProgressWindowValue(I);
Incr := (I - 1) * FPrintImagePerPage;
for J := 1 to FPrintImagePerPage do
if FFiles.Count >= J + Incr then
Files.Add(FFiles[J + Incr - 1]);
FOptions.VirtualImage := FVirtualBitmaped;
FOptions.Image := FVirtualBitmap;
BitmapPreview := GenerateImage(True, Printer.PageWidth, Printer.PageHeight, nil, Files, FSampleType, FOptions);
try
if FDestroyBitmap then
FOptions.Image.Free;
if FTerminating then
Break;
SynchronizeEx(PrintImage);
finally
F(BitmapPreview);
end;
end;
SynchronizeEx(HideProgressWindow);
finally
F(Files);
end;
end;
end;
function TGeneratorPrinterPreview.GetThreadID: string;
begin
Result := 'Printer';
end;
constructor TGeneratorPrinterPreview.Create(CreateSuspennded: Boolean; Sender: TDBForm; SID: string;
SampleType: TPrintSampleSizeOne; Files: TStrings; OnEndProc: TOnEndGeneratePrinterPreviewEvent; DoPrint: Boolean;
Options: TGenerateImageOptions; PrintImagePerPage: Integer; VirtualBitmaped: Boolean; VirtualBitmap: TBitmap;
DestroyBitmap: Boolean);
begin
inherited Create(Sender, False);
FSID := SID;
FSender := Sender;
FFiles := TStringList.Create;
FFiles.Assign(Files);
FOnEndProc := OnEndProc;
FSampleType := SampleType;
FDoPrint := DoPrint;
FPrintImagePerPage := PrintImagePerPage;
FTerminating := False;
FOptions := Options;
FVirtualBitmaped := VirtualBitmaped;
FVirtualBitmap := VirtualBitmap;
FDestroyBitmap := DestroyBitmap;
end;
destructor TGeneratorPrinterPreview.Destroy;
begin
F(FFiles);
inherited;
end;
procedure TGeneratorPrinterPreview.SetImage;
begin
if Assigned(FOnEndProc) then
FOnEndProc(BitmapPreview, FSID)
else
F(BitmapPreview);
end;
procedure TGeneratorPrinterPreview.PrintImage;
begin
Printer.BeginDoc;
Printer.Canvas.Draw(0, 0, BitmapPreview);
Printer.EndDoc;
end;
procedure TGeneratorPrinterPreview.SetMax(I: Integer);
begin
IntParam := I;
SynchronizeEx(SetMaxSynch)
end;
procedure TGeneratorPrinterPreview.SetMaxSynch;
begin
//
end;
procedure TGeneratorPrinterPreview.SetText(text: string);
begin
//
end;
procedure TGeneratorPrinterPreview.SetTextSynch;
begin
end;
procedure TGeneratorPrinterPreview.SetValue(i: integer);
begin
end;
procedure TGeneratorPrinterPreview.SetValueSynch;
begin
end;
procedure TGeneratorPrinterPreview.CallBack(Progress: Byte; var Terminate: Boolean);
begin
IntParam := Progress;
SynchronizeEx(SetProgress);
end;
procedure TGeneratorPrinterPreview.HideProgress;
begin
(FSender as TPrintForm).FStatusProgress.Hide;
end;
procedure TGeneratorPrinterPreview.ShowProgress;
begin
(FSender as TPrintForm).FStatusProgress.Position := 0;
(FSender as TPrintForm).FStatusProgress.Max := 100;
(FSender as TPrintForm).FStatusProgress.Show;
end;
procedure TGeneratorPrinterPreview.SetProgress;
begin
(FSender as TPrintForm).FStatusProgress.Position:=IntParam;
end;
procedure TGeneratorPrinterPreview.SetCommentText(Text: string);
begin
StringParam := Text;
SynchronizeEx(SetCommentTextCynch);
end;
procedure TGeneratorPrinterPreview.SetCommentTextCynch;
begin
(FSender as TPrintForm).StatusBar1.Panels[1].Text := StringParam;
end;
procedure TGeneratorPrinterPreview.CallBackFull(Progress: byte;
var Terminate: boolean);
begin
//
end;
procedure TGeneratorPrinterPreview.ShowProgressWindow;
begin
FormProgress := GetFormPrinterProgress;
FormProgress.PValue := @FTerminating;
FormProgress.Show;
end;
procedure TGeneratorPrinterPreview.HideProgressWindow;
begin
FormProgress.FCanClose := True;
FormProgress.Release;
FormProgress.Free;
end;
procedure TGeneratorPrinterPreview.SetProgressWindowMax(Value: Integer);
begin
IntParam := Value;
SynchronizeEx(SetProgressWindowMaxSynch);
end;
procedure TGeneratorPrinterPreview.SetProgressWindowMaxSynch;
begin
FormProgress.PbPrinterProgress.MaxValue := IntParam;
end;
procedure TGeneratorPrinterPreview.SetProgressWindowValue(Value: Integer);
begin
IntParam := Value;
SynchronizeEx(SetProgressWindowValueSynch);
end;
procedure TGeneratorPrinterPreview.SetProgressWindowValueSynch;
begin
FormProgress.PbPrinterProgress.Position := IntParam;
end;
end.
|
////////////////////////////////////////////////////////////////////////////////
//违标分析逻辑单元
////////////////////////////////////////////////////////////////////////////////
unit uVSLib;
interface
uses
Classes, Contnrs, uVSConst, uVSRules, uVSAnalysisResultList, uLKJRuntimeFile,
uRtfmtFileReader;
type
////////////////////////////////////////////////////////////////////////////////
//违标分析类
////////////////////////////////////////////////////////////////////////////////
TLKJAnalysis = class
public
constructor Create();
destructor Destroy; override;
public
//分析运行记录
procedure DoAnalysis(LKJFile: TLKJRuntimeFile; var EventArray: TLKJEventList);
//获取作业时间
procedure GetOperationTime(RuntimeFiles: TStrings; out OperationTime: ROperationTime; RuleXMLFile: string);
private
//规则列表
m_Rules: TObjectList;
protected
//根据ID获取规则
function GetRuleByID(RuleID: string): TVSRule;
public
//规则列表
property Rules: TObjectList read m_Rules;
end;
implementation
uses
SysUtils, DateUtils,
uVSLog, uVSSimpleExpress, uVSCombExpress, uVSRuleReader;
procedure TLKJAnalysis.DoAnalysis(LKJFile: TLKJRuntimeFile;
var EventArray: TLKJEventList);
var
i, j: Integer;
matchRlt: TVSCState;
vsRule: TVSRule;
rltData: TLKJEventDetail;
begin
//清空上一次的分析结果
VSLog := TVSXMLLog.Create;
try
vslOG.OpenLog := false;
for j := 0 to EventArray.Count - 1 do
begin
vsRule := GetRuleByID(EventArray.Items[j].strEventID);
if vsRule = nil then continue;
VSLog.AddRule(vsRule.Title);
vsRule.BeforeSeconds := EventArray[j].nBeforeSeconds;
vsRule.AfterSeconds := EventArray[j].nAfterSeconds;
if vsRule = nil then continue;
vsRule.Init;
{$REGION '检测指定规则是否适合该运行记录文件'}
if not vsRule.Check(LKJFile.HeadInfo, LKJFile.Records) then
begin
if vsRule.HeadExpression <> nil then
vsRule.HeadExpression.Init;
continue;
end;
{$ENDREGION '检测指定规则是否适合该运行记录文件'}
matchRlt := vscUnMatch;
//循环运行记录
for i := 0 to LKJFile.Records.Count - 1 do
begin
{$REGION '比对记录,如果比对结果为捕获则保存捕获数据'}
try
matchRlt := vsRule.MatchLKJRec(LKJFile.HeadInfo, TLKJRuntimeFileRec(LKJFile.Records[i]), LKJFile.Records);
except
continue;
end;
if vscMatched = matchRlt then
begin
rltData := vsRule.GetCaptureRange;
if rltData = nil then continue;
//当规则捕获为正常时,退出循环
//((有记录违标 (IsVs=False),无记录违标 (IsVs=True)))
if not vsRule.IsVS then break;
EventArray[j].DetailList.Add(rltData);
vsRule.Reset;
end;
{$ENDREGION '比对记录,如果比对结果为捕获则保存捕获数据'}
end;
{$REGION '如果当前记录为最有一条记录,则判断结果是否为捕获中'}
//比对最后一条记录后将状态为适合的数据视为匹配
if (vscMatching = matchRlt) and (vsRule.IsVS) then
begin
rltData := vsRule.GetCaptureRange;
EventArray[j].DetailList.Add(rltData);
vsRule.Reset;
end;
end;
finally
VSLog.Free;
end;
end;
procedure TLKJAnalysis.GetOperationTime(RuntimeFiles: TStrings;
out OperationTime: ROperationTime; RuleXMLFile: string);
var
eventList: TLKJEventList;
i: Integer;
event: TLKJEventItem;
lkjFile: TLKJRuntimeFile;
reader: TfmtFileReader;
ruleReader: TVSRuleReader;
begin
OperationTime.inhousetime := 0;
OperationTime.jctime := 0;
OperationTime.outhousetime := 0;
OperationTime.tqarrivetime := 0;
OperationTime.tqdat := 0;
OperationTime.jhtqtime := 0;
Rules.Clear;
try
ruleReader := TVSRuleReader.Create(Rules);
ruleReader.LoadFromXML(RuleXMLFile);
ruleReader.Free;
{$REGION '设置启用的事件及取值范围'}
eventList := TLKJEventList.Create;
event := TLKJEventItem.Create;
event.strEventID := '1000';
event.strEvent := '入库时间';
event.nBeforeSeconds := 0;
event.nAfterSeconds := 0;
eventList.Add(event);
eventList := TLKJEventList.Create;
event := TLKJEventItem.Create;
event.strEventID := '1001';
event.strEvent := '出勤车次接车时间';
event.nBeforeSeconds := 0;
event.nAfterSeconds := 0;
eventList.Add(event);
event := TLKJEventItem.Create;
event.strEventID := '1002';
event.strEvent := '出库时间';
event.nBeforeSeconds := 0;
event.nAfterSeconds := 0;
eventList.Add(event);
event := TLKJEventItem.Create;
event.strEventID := '1003';
event.strEvent := '退勤车次到站时间';
event.nBeforeSeconds := 0;
event.nAfterSeconds := 0;
eventList.Add(event);
event := TLKJEventItem.Create;
event.strEventID := '1004';
event.strEvent := '退勤车次到站时间';
event.nBeforeSeconds := 0;
event.nAfterSeconds := 0;
eventList.Add(event);
{$ENDREGION ''}
try
lkjFile := TLKJRuntimeFile.Create();
try
reader := TfmtFileReader.Create();
try
reader.LoadFromFiles(RuntimeFiles, lkjFile);
finally
reader.Free;
end;
DoAnalysis(lkjFile, eventList);
finally
lkjFile.Free;
end;
for i := 0 to eventList.Count - 1 do
begin
if eventList.Items[i].strEventID = '1000' then
begin
if eventList[i].DetailList.Count > 0 then
begin
OperationTime.inhousetime := eventList[i].DetailList.Items[eventList[i].DetailList.Count - 1].dtCurrentTime;
end;
end;
if eventList.Items[i].strEventID = '1001' then
begin
if eventList[i].DetailList.Count > 0 then
begin
OperationTime.jctime := eventList[i].DetailList.Items[eventList[i].DetailList.Count - 1].dtCurrentTime;
end;
end;
if eventList.Items[i].strEventID = '1002' then
begin
if eventList[i].DetailList.Count > 0 then
begin
OperationTime.outhousetime := eventList[i].DetailList.Items[eventList[i].DetailList.Count - 1].dtCurrentTime;
end;
end;
if eventList.Items[i].strEventID = '1003' then
begin
if eventList[i].DetailList.Count > 0 then
begin
OperationTime.tqarrivetime := eventList[i].DetailList.Items[eventList[i].DetailList.Count - 1].dtCurrentTime;
end;
end;
if eventList.Items[i].strEventID = '1004' then
begin
if eventList[i].DetailList.Count > 0 then
begin
OperationTime.tqdat := eventList[i].DetailList.Items[eventList[i].DetailList.Count - 1].dtCurrentTime;
end;
end;
end;
if OperationTime.jhtqtime > 0 then
begin
OperationTime.jhtqtime := IncMinute(OperationTime.jhtqtime, 30);
end else begin
if OperationTime.tqarrivetime > 0 then
begin
OperationTime.jhtqtime := IncMinute(OperationTime.tqarrivetime, 30);
end;
end;
if OperationTime.inhousetime = 0 then
begin
if OperationTime.tqarrivetime > 0 then
begin
OperationTime.inhousetime := IncMinute(OperationTime.tqarrivetime, 30);
end;
end;
finally
eventList.Free;
end;
finally
rules.Clear;
end;
end;
function TLKJAnalysis.GetRuleByID(RuleID: string): TVSRule;
var
i: Integer;
begin
result := nil;
for i := 0 to m_Rules.Count - 1 do
begin
if IntToStr(TVSRule(m_Rules.Items[i]).ID) = RuleID then
begin
Result := TVSRule(m_Rules.Items[i]);
end;
end;
end;
constructor TLKJAnalysis.Create();
begin
m_Rules := TObjectList.Create;
end;
destructor TLKJAnalysis.Destroy;
begin
m_Rules.Free;
inherited;
end;
end.
|
program Cradle; { Program Name }
const TAB = ^I; { Constant Declarations }
var
Look: char; { Lookahead Character }
{ Read new character from i/p stream }
procedure GetChar;
begin
Read(Look);
end;
{ Report Error }
procedure Error(s: string)
begin
WriteLn;
WriteLn(^G, 'Error: ', s, '.');
end;
{ Report error and halt }
procedure Abort(s: string)
begin
Error(s);
Halt;
end;
{ Report Expected }
procedure Expected(s: string)
begin
Abort(s: string);
end;
{ Match input }
procedure Match(x: char)
begin
if Look = x then GetChar
else Expected('''' + x + '''');
end;
|
namespace WinFormsApplication;
//Sample WinForms application
//by Brian Long, 2009
//A re-working of a GTK# example program, based on treeview example in the Gtk#
//docs (http://www.go-mono.com/docs/) on the Mono site http://tinyurl.com/Gtk-TreeView
interface
uses
{$REGION Hacking to skip Mono issue}
System.Runtime.InteropServices,
{$ENDREGION}
System.Windows.Forms,
System.Drawing,
System.Reflection;
type
/// <summary>
/// Summary description for MainForm.
/// </summary>
MainForm = partial class(System.Windows.Forms.Form)
private
{$REGION Hacking to skip Mono issue}
[DllImport('libc')]
class method uname(buf: IntPtr): Integer; external;
class method RunningOnUnix: Boolean;
class method RunningOnLinux: Boolean;
class method RunningOnOSX: Boolean;
class method RunningOnWindows: Boolean;
class method InternalRunningLinuxInsteadOfOSX: Boolean;
{$ENDREGION}
method MainForm_Load(sender: System.Object; e: System.EventArgs);
method quitToolStripMenuItem1_Click(sender: System.Object; e: System.EventArgs);
method aboutToolStripMenuItem_Click(sender: System.Object; e: System.EventArgs);
method notifyIcon_Click(sender: System.Object; e: System.EventArgs);
method openToolStripMenuItem_Click(sender: System.Object; e: System.EventArgs);
protected
method Dispose(disposing: Boolean); override;
public
constructor;
method GetTreeViewNodes: TreeNodeCollection;
end;
implementation
uses
System.Runtime.Versioning;
{$REGION Construction and Disposition}
constructor MainForm;
begin
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
end;
method MainForm.Dispose(disposing: Boolean);
begin
if disposing then begin
if assigned(components) then
components.Dispose();
//
// TODO: Add custom disposition code here
//
end;
inherited Dispose(disposing);
end;
{$ENDREGION}
{$REGION Hacking to skip Mono issue}
class method MainForm.RunningOnUnix: Boolean;
begin
var p: Integer := Integer(Environment.OSVersion.Platform);
//.NET 1.x didn't have a Unix value in System.PlatformID enum, so Mono
//just used value 128.
//.NET 2 added Unix to PlatformID, but with value 4
//.NET 3.5 added MacOSX with a value of 6
exit p in [4, 6, 128];
end;
class method MainForm.RunningOnLinux: Boolean;
begin
exit RunningOnUnix and InternalRunningLinuxInsteadOfOSX
end;
class method MainForm.RunningOnOSX: Boolean;
begin
exit RunningOnUnix and not InternalRunningLinuxInsteadOfOSX
end;
class method MainForm.RunningOnWindows: Boolean;
begin
Result := not RunningOnUnix
end;
class method MainForm.InternalRunningLinuxInsteadOfOSX: Boolean;
begin
//based on Mono cross-platform checking code in:
// mcs\class\Managed.Windows.Forms\System.Windows.Forms\XplatUI.cs
if not RunningOnUnix then
raise new Exception('This is not a Unix platform!');
var Buf: IntPtr := Marshal.AllocHGlobal(8192);
try
if uname(buf) <> 0 then
//assume Linux of some sort
exit True
else
//Darwin is the Unix variant that OS X is based on
exit Marshal.PtrToStringAnsi(Buf) <> 'Darwin'
finally
Marshal.FreeHGlobal(Buf);
end;
end;
{$ENDREGION}
method MainForm.MainForm_Load(sender: System.Object; e: System.EventArgs);
begin
if not RunningOnOSX then
notifyIcon.Icon := Icon;
end;
method MainForm.quitToolStripMenuItem1_Click(sender: System.Object; e: System.EventArgs);
begin
if notifyIcon <> nil then
begin
if not RunningOnOSX then
notifyIcon.Visible := False;
Application.Exit;
end;
end;
method MainForm.aboutToolStripMenuItem_Click(sender: System.Object; e: System.EventArgs);
begin
new AboutForm().ShowDialog()
end;
method MainForm.notifyIcon_Click(sender: System.Object; e: System.EventArgs);
begin
Visible := not Visible
end;
method MainForm.GetTreeViewNodes: TreeNodeCollection;
begin
Result := treeView.Nodes
end;
method MainForm.openToolStripMenuItem_Click(sender: System.Object; e: System.EventArgs);
begin
if openFileDialog.ShowDialog = DialogResult.OK then
Program.AddAssembly(openFileDialog.FileName)
end;
end. |
unit Helper.DataSet;
interface
uses
Data.DB;
type
TDataSetHelper = class helper for TDataSet
function GetMaxValue(const fieldName: string): integer;
end;
implementation
{ TDataSetHelper }
function TDataSetHelper.GetMaxValue(const fieldName: string): integer;
var
v: integer;
begin
Result := 0;
self.DisableControls;
self.First;
while not self.Eof do
begin
v := self.FieldByName(fieldName).AsInteger;
if v > Result then
Result := v;
self.Next;
end;
self.EnableControls;
end;
end.
|
{- Dado un arreglo de enteros, eliminar el máximo elemento, suponer único}
Program eje13;
Type
TV = array[0..100] of integer;
Procedure LeeVector(Var V:TV; Var N:byte);
Var
i:byte;
begin
write('Ingrese la cantidad de numeros del vector: ');readln(N);
For i:= 1 to N do
begin
write('Ingrese un numero para la posicion ',i,' : ');readln(V[i]);
end;
end;
Function Maximo(V:TV; N:byte):integer;
Var
i:byte;
Max:integer;
begin
Max:= 0;
For i:= 1 to N do
begin
If (V[i] > Max) then
Max:= V[i];
end;
Maximo:= Max;
end;
Procedure Elimina (Var V:TV; Var N:byte);
Var
i: byte;
aux,Max:integer;
begin
Max:= Maximo(V,N);
For i:= 1 to N - 1 do
begin
If (V[i] = Max) then
begin
aux:= V[i];
V[i]:= V[i + 1];
V[i + 1]:= aux;
end;
end;
N:= N - 1;
end;
Procedure Imprime(V:TV; N:byte);
Var
i:byte;
begin
writeln('Vector con el maximo elemento eliminado: ');
For i:= 1 to N do
begin
writeln(V[i]);
end;
end;
Var
V:TV;
N:byte;
Begin
LeeVector(V,N);
Elimina(V,N);
writeln;
Imprime(V,N);
end.
|
unit fITCmxRegistro;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Objects, FMX.Controls.Presentation, FMX.ListBox, FMX.Layouts, FMX.Edit,
FMX.ScrollBox, FMX.Memo;
type
TfrmITCmxRegistro = class(TForm)
tbMain: TToolBar;
recFondoToolBar: TRectangle;
lblTitulo: TLabel;
sbtRegresar: TSpeedButton;
sbtEnviar: TSpeedButton;
lstRegistro: TListBox;
lbiNombre: TListBoxItem;
lbiEMail: TListBoxItem;
lbiPais: TListBoxItem;
lbiRecibirMails: TListBoxItem;
lbiComentarios: TListBoxItem;
edNombre: TEdit;
edCorreo: TEdit;
cmbPais: TComboBox;
chkMails: TCheckBox;
memComentario: TMemo;
procedure sbtEnviarClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
function Validar:Boolean;
function Registrar:Boolean;
public
end;
var
frmITCmxRegistro: TfrmITCmxRegistro;
implementation
{$R *.fmx}
uses fMain, cITCmxStatistics, uStatistics;
procedure TfrmITCmxRegistro.FormCreate(Sender: TObject);
begin
cmbPais.ItemIndex := cmbPais.Items.IndexOf('México');
end;
function TfrmITCmxRegistro.Registrar: Boolean;
begin
try
cltITCStatistics.ITCmxStatisticsClient.Registrarse(edNombre.Text, edCorreo.Text,
cmbPais.Selected.Text, uStatistics.AppContador, memComentario.Text, chkMails.IsChecked);
Close;
except
on e: exception do
frmMain.Msg('Ocurrio un problema al registrarse: ' + e.Message);
end; {try}
end;
procedure TfrmITCmxRegistro.sbtEnviarClick(Sender: TObject);
begin
if Validar then
if Registrar then
Close;
end;
function TfrmITCmxRegistro.Validar: Boolean;
begin
Result := False;
if (edNombre.Text = '') then begin
edNombre.SetFocus;
frmMain.Msg('Escriba su nombre por favor');
end else if (edNombre.Text = '') then begin
edCorreo.SetFocus;
frmMain.Msg('Escriba su correo por favor');
end else
Result := True;
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages,
System.SysUtils, System.Variants,
System.Math, System.Classes, System.DateUtils,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
Vcl.ExtCtrls, Vcl.Imaging.Jpeg,
GLBehaviours, GLScene, GLObjects, GLCadencer, GLMaterial, GLColor,
GLWin32Viewer, GLVectorGeometry, GLGeomObjects,
GLVectorFileObjects, GLTexture, GLFileMS3D, GLFile3DS,
GLCoordinates, GLCrossPlatform, GLBaseClasses,
//FishTank
uVehicle;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
GLCadencer1: TGLCadencer;
GLCamera1: TGLCamera;
GLDummyCube1: TGLDummyCube;
GLLightSource1: TGLLightSource;
TimerForFps: TTimer;
ArrowForDirection: TGLArrowLine;
Panel1: TPanel;
Label1: TLabel;
TimerForSpeed: TTimer;
GLFreeForm1: TGLFreeForm;
GLMaterialLibrary1: TGLMaterialLibrary;
Button1: TButton;
Button2: TButton;
GLCamera2: TGLCamera;
GLCube2: TGLCube;
Label3: TLabel;
CollisionSphere: TGLSphere;
GLArrowLine4: TGLArrowLine;
GLDummyCube2: TGLDummyCube;
Target1: TGLDummyCube;
Target2: TGLDummyCube;
Target3: TGLDummyCube;
Target4: TGLDummyCube;
BtnForTarget1: TButton;
BtnForTarget2: TButton;
BtnForTarget3: TButton;
BtnForTarget4: TButton;
BSphere: TGLSphere;
LinesForDirection: TGLLines;
GLCube1: TGLCube;
GLArrowLine1: TGLArrowLine;
GLCamera3: TGLCamera;
GLSphere1: TGLSphere;
GLLines1: TGLLines;
GLCube3: TGLCube;
GLArrowLine2: TGLArrowLine;
GLCamera4: TGLCamera;
GLSphere2: TGLSphere;
GLLines2: TGLLines;
GLCube4: TGLCube;
GLArrowLine3: TGLArrowLine;
GLCamera5: TGLCamera;
GLSphere3: TGLSphere;
GLLines3: TGLLines;
GLCube5: TGLCube;
GLArrowLine5: TGLArrowLine;
GLCamera6: TGLCamera;
GLSphere4: TGLSphere;
GLLines4: TGLLines;
GLCube6: TGLCube;
GLArrowLine6: TGLArrowLine;
GLCamera7: TGLCamera;
GLSphere5: TGLSphere;
GLLines5: TGLLines;
GLCube7: TGLCube;
GLArrowLine7: TGLArrowLine;
GLCamera8: TGLCamera;
GLSphere6: TGLSphere;
GLLines6: TGLLines;
GLCube8: TGLCube;
GLArrowLine8: TGLArrowLine;
GLCamera9: TGLCamera;
GLSphere7: TGLSphere;
GLLines7: TGLLines;
procedure FormCreate(Sender: TObject);
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
procedure TimerForFpsTimer(Sender: TObject);
procedure TimerForSpeedTimer(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure BtnForTarget1Click(Sender: TObject);
procedure BtnForTarget2Click(Sender: TObject);
procedure BtnForTarget3Click(Sender: TObject);
procedure BtnForTarget4Click(Sender: TObject);
private
FSteeringManager: TGLVehicleManager;
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
var
newSteering: TGLBVehicle;
begin
SetCurrentDir(ExtractFilePath(Application.ExeName));
BSphere.Radius := GLCube2.BoundingSphereRadius;
GLFreeForm1.LoadFromFile('BoxedIn.3ds');
GLFreeForm1.BuildOctree;
Randomize;
FSteeringManager := TGLVehicleManager.Create(nil);
FSteeringManager.WorldCollisionMap := GLFreeForm1;
newSteering := GetOrCreateVehicle(GLCube2);
with newSteering do begin
Manager := FSteeringManager;
Mass := 25;
MaxSpeed := 15;
Speed := 0;
CollisionObject := CollisionSphere;
Wander.Rate := 5;
Wander.Strength := 10;
Wander.Ratio := 1;
Seek.Target := nil;
Seek.Ratio := 1;
Flee.Target := GLCube1;
Flee.Ratio := 1;
WorldCollision.Ratio := 1;
WorldCollision.TurnRate := 0.5;
end;
newSteering := GetOrCreateVehicle(GLCube1);
with newSteering do begin
Manager := FSteeringManager;
Mass := 25;
MaxSpeed := 12;
Speed := 0;
CollisionObject := CollisionSphere;
Wander.Rate := 1;
Wander.Strength := 10;
Wander.Ratio := 1;
Seek.Target := GLCube2;
Seek.Ratio := 1;
WorldCollision.Ratio := 1;
end;
newSteering := GetOrCreateVehicle(GLCube3);
with newSteering do begin
Manager := FSteeringManager;
Mass := 15;
MaxSpeed := 10;
Speed := 0;
CollisionObject := CollisionSphere;
Wander.Rate := 5;
Wander.Strength := 10;
Wander.Ratio := 1;
Seek.Target := nil;
Seek.Ratio := 1;
Flee.Target := nil;
Flee.Ratio := 0;
WorldCollision.Ratio := 1;
WorldCollision.TurnRate := 0.3;
end;
newSteering := GetOrCreateVehicle(GLCube4);
with newSteering do begin
Manager := FSteeringManager;
Mass := 15;
MaxSpeed := 8;
Speed := 0;
CollisionObject := CollisionSphere;
Wander.Rate := 5;
Wander.Strength := 10;
Wander.Ratio := 1;
Seek.Target := nil;
Seek.Ratio := 1;
Flee.Target := nil;
Flee.Ratio := 0;
WorldCollision.Ratio := 1;
WorldCollision.TurnRate := 0.3;
end;
newSteering := GetOrCreateVehicle(GLCube5);
with newSteering do begin
Manager := FSteeringManager;
Mass := 15;
MaxSpeed := 12;
Speed := 0;
CollisionObject := CollisionSphere;
Wander.Rate := 5;
Wander.Strength := 10;
Wander.Ratio := 1;
Seek.Target := nil;
Seek.Ratio := 1;
Flee.Target := nil;
Flee.Ratio := 0;
WorldCollision.Ratio := 1;
WorldCollision.TurnRate := 0.3;
end;
newSteering := GetOrCreateVehicle(GLCube6);
with newSteering do begin
Manager := FSteeringManager;
Mass := 15;
MaxSpeed := 5;
Speed := 0;
CollisionObject := CollisionSphere;
Wander.Rate := 5;
Wander.Strength := 10;
Wander.Ratio := 1;
Seek.Target := nil;
Seek.Ratio := 1;
Flee.Target := nil;
Flee.Ratio := 0;
WorldCollision.Ratio := 1;
WorldCollision.TurnRate := 0.3;
end;
newSteering := GetOrCreateVehicle(GLCube7);
with newSteering do begin
Manager := FSteeringManager;
Mass := 10;
MaxSpeed := 15;
Speed := 0;
CollisionObject := CollisionSphere;
Wander.Rate := 5;
Wander.Strength := 10;
Wander.Ratio := 1;
Seek.Target := nil;
Seek.Ratio := 1;
Flee.Target := nil;
Flee.Ratio := 0;
WorldCollision.Ratio := 1;
WorldCollision.TurnRate := 0.3;
end;
newSteering := GetOrCreateVehicle(GLCube8);
with newSteering do begin
Manager := FSteeringManager;
Mass := 11;
MaxSpeed := 9;
Speed := 0;
CollisionObject := CollisionSphere;
Wander.Rate := 5;
Wander.Strength := 10;
Wander.Ratio := 1;
Seek.Target := nil;
Seek.Ratio := 1;
Flee.Target := nil;
Flee.Ratio := 0;
WorldCollision.Ratio := 1;
WorldCollision.TurnRate := 0.3;
end;
FSteeringManager.SteerInterval := 0.02;
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
begin
GLDummyCube2.Position.X := cos(newTime * pi/4.2) * 20;
GLDummyCube2.Position.y:= sin(newTime * pi /7.1) * 5;
GLDummyCube2.Position.z := sin(newTime * pi/5) * 20;
FSteeringManager.DoSteering;
LinesForDirection.Direction.AsVector := GetOrCreateVehicle(GLCube2).Accumulator.AsVector;
GLSceneViewer1.Invalidate;
end;
procedure TForm1.TimerForFpsTimer(Sender: TObject);
begin
Caption:=Format('%.1f FPS', [GLSceneViewer1.FramesPerSecond]);
GLSceneViewer1.ResetPerformanceMonitor;
Label1.Caption := FloatToStr(RoundTo(GetOrCreateVehicle(GLCube2).Speed, -2));
end;
procedure TForm1.TimerForSpeedTimer(Sender: TObject);
begin
// TimerForSpeed.Interval := trunc(5000 * random) + 1000;
// with GetOrCreateVehicle(GLCube2) do
// MaxSpeed := RandomRange(1, 20);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
with GetOrCreateVehicle(GLCube2) do
MaxSpeed := MaxSpeed + 5;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
with GetOrCreateVehicle(GLCube2) do
MaxSpeed := MaxSpeed - 5;
end;
procedure TForm1.BtnForTarget1Click(Sender: TObject);
begin
Target1.EdgeColor.Color := clrYellow;
GetOrCreateVehicle(GLCube2).Seek.Target := Target1;
Target2.EdgeColor.Color := clrLimeGreen;
Target3.EdgeColor.Color := clrLimeGreen;
Target4.EdgeColor.Color := clrLimeGreen;
end;
procedure TForm1.BtnForTarget2Click(Sender: TObject);
begin
Target1.EdgeColor.Color := clrLimeGreen;
Target2.EdgeColor.Color := clrYellow;
GetOrCreateVehicle(GLCube2).Seek.Target := Target2;
Target3.EdgeColor.Color := clrLimeGreen;
Target4.EdgeColor.Color := clrLimeGreen;
end;
procedure TForm1.BtnForTarget3Click(Sender: TObject);
begin
Target1.EdgeColor.Color := clrLimeGreen;
Target2.EdgeColor.Color := clrLimeGreen;
Target3.EdgeColor.Color := clrYellow;
GetOrCreateVehicle(GLCube2).Seek.Target := Target3;
Target4.EdgeColor.Color := clrLimeGreen;
end;
procedure TForm1.BtnForTarget4Click(Sender: TObject);
begin
Target1.EdgeColor.Color := clrLimeGreen;
Target2.EdgeColor.Color := clrLimeGreen;
Target3.EdgeColor.Color := clrLimeGreen;
Target4.EdgeColor.Color := clrYellow;
GetOrCreateVehicle(GLCube2).Seek.Target := Target4;
end;
end.
|
unit UDie;
interface
type
TDie = class
const
MAX = 6;
private
faceValue: integer;
public
procedure roll;
function getFaceValue: integer;
published
constructor create;
end;
implementation
{ TDie }
constructor TDie.create;
begin
roll;
end;
function TDie.getFaceValue: integer;
begin
result := faceValue;
end;
procedure TDie.roll;
begin
faceValue := random(MAX) + 1;
end;
end.
|
unit Ils.Logger;
//------------------------------------------------------------------------------
// модуль реализует класс логирования
//------------------------------------------------------------------------------
// логирование осуществляется в файл, расположение и имя которого определяется
// по следующему принципу:
// если путь к исполняемому файлу выглядит как
// диск:\путь\ИмяИсполняемогоФайла.exe
// то путь к файлу лога будет
// диск:\путь\log\ИмяИсполняемогоФайла.log
//
// после смены суток файл лога переименовывается в
// диск:\путь\log\ИмяИсполняемогоФайла__yyyymmdd.log
// где yyyymmdd - текущие год, месяц и день предыдущего дня
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
interface
uses
SysUtils, StrUtils, Windows, Math, Classes;
var
//------------------------------------------------------------------------------
// переменная уровня лога
//------------------------------------------------------------------------------
// *** ошибки должны логироваться всегда ***
// рекомендуемые уровни:
// 0 - только базовая информация (=начало/конец работы)
// 1 - информация о нестандартном поведении (например таймаутах событий)
// 2 - информация о событиях (например новых TCP подключениях)
// 3 - полный лог + дамп всех данных
// 4* - для сервисов приёма происходит дамп итоговых JSON'ов в файлы
//------------------------------------------------------------------------------
GLogLevel: Integer;
type
TLogFunction = function(const AMessage: string; const ASkipTimeStamp: Boolean = False): string;
//------------------------------------------------------------------------------
//! записать сообщение в лог
//------------------------------------------------------------------------------
function ToLog(
const AMessage: string;
const ASkipTimeStamp: Boolean = False
): string;
function ToLogHex(
const AMessage: string
): string;
//------------------------------------------------------------------------------
//! записать сообщение в лог
//------------------------------------------------------------------------------
function ExceptionToLog(
const AExcept: Exception;
const AHeader: string = ''
): string;
function ExceptionToLogNew(
const AExcept: Exception;
const AHeader: string = ''
): string;
function StartLog(const ASuffix: string; const AMultiProcess: Boolean = False): Boolean;
//------------------------------------------------------------------------------
implementation
const
//------------------------------------------------------------------------------
//! строка формата даты-времени
//------------------------------------------------------------------------------
CDateTimeFormat : string = 'yyyy"."mm"."dd" "hh":"nn":"ss"."zzz';
CDateTimeFormatNoDate : string = ' ';
//------------------------------------------------------------------------------
//! шаблон формата строки лога
//------------------------------------------------------------------------------
CLogStrFormat: string = '%s %s'#13#10;
//------------------------------------------------------------------------------
type
//------------------------------------------------------------------------------
//! TNewLogger
//------------------------------------------------------------------------------
TNewLogger = class
private
FLogFileName: string;
FPrevDate: TDate;
FHandle: THandle;
FMultiProcess: Boolean;
procedure CheckTransition();
procedure LogOpen();
procedure LogClose();
public
constructor Create(const ALogName: string = ''; const AMultiProcess: Boolean = False);
destructor Destroy(); override;
procedure ToLog(const AMessage: string; const ASkipTimeStamp: Boolean = False);
end;
//------------------------------------------------------------------------------
var
GLogger: TNewLogger;
GLoggerSuffix: string;
function StartLog(const ASuffix: string; const AMultiProcess: Boolean = False): Boolean;
begin
FreeAndNil(GLogger);
try
GLoggerSuffix := ASuffix;
GLogger := TNewLogger.Create(ChangeFileExt(ExtractFileName(GetModuleName(HInstance)), IfThen(ASuffix <> '', '_' + ASuffix, '')), AMultiProcess);
except
// подавляю специально - такие ситуации могут возникнуть в сервисах
end;
Result := Assigned(GLogger);
end;
function ToLog(
const AMessage: string;
const ASkipTimeStamp: Boolean = False
): string;
begin
if not Assigned(GLogger) then
StartLog(GLoggerSuffix);
GLogger.ToLog(AMessage, ASkipTimeStamp);
Result := AMessage;
end;
function ToLogHex(
const AMessage: string
): string;
function StrToHexStr(const S: AnsiString): AnsiString;
var
Hex: PAnsiChar;
begin
Hex := AllocMem(Length(S) * 2);
try
BinToHex(PAnsiChar(S), Hex, Length(S));
Result := Copy(Hex, 0, Length(S) * 2);
finally
FreeMem(Hex,Length(S) * 2);
end;
end;
var
i: Integer;
LineNo: Integer;
LogStr1: AnsiString;
LogStr2: AnsiString;
Hex: AnsiString;
s: AnsiString;
stc: AnsiString;
begin
s := AnsiString(AMessage);
LineNo := 0;
while (Length(s) > 0) do
begin
stc := Copy(s, 1, 16);
Delete(s, 1, 16);
Hex := StrToHexStr(stc);
LogStr1 := '';
for i := 1 to Length(Hex) do
begin
if ((i mod 2) > 0) and (i > 1) then
LogStr1 := LogStr1 + ' ';
LogStr1 := LogStr1 + Hex[i];
end;
LogStr1 := LogStr1 + AnsiString(StringOfChar(' ', (4 * 16) - Length(LogStr1)));
LogStr2 := '';
for i := 1 to Length(stc) do
begin
if ((stc[i] >= #32) and (stc[i] <= #127)) then
LogStr2 := LogStr2 + ' ' + stc[i]
else
LogStr2 := LogStr2 + ' #' + AnsiString(StrToHexStr(stc[i]));
end;
if (LineNo = 0) then
ToLog(string(LogStr1 + '|' + LogStr2))
else
ToLog(string(LogStr1 + '|' + LogStr2), True);
Inc(LineNo);
end;
end;
function ExceptionToLog(
const AExcept: Exception;
const AHeader: string
): string;
var
CurrExcept: Exception;
Level: Integer;
begin
if (AHeader <> '') then
Result := 'Возникло исключение (' + AHeader + '):'
else
Result := 'Возникло исключение:';
Level := 1;
CurrExcept := AExcept;
repeat
Result := Format('%s'#13#10'уровень %d:'#13#10'%s', [Result, Level, CurrExcept.Message]);
Inc(Level);
CurrExcept := CurrExcept.InnerException;
until not Assigned(CurrExcept);
if (AExcept.StackTrace <> '') then
Result := Format('%s'#13#10'дамп стека:'#13#10'%s', [Result, AExcept.StackTrace]);
GLogger.ToLog(Result);
end;
function ExceptionToLogNew(
const AExcept: Exception;
const AHeader: string
): string;
begin
Result := 'Возникло исключение';
if (AHeader <> '') then
Result := Result + ' (' + AHeader + ')';
Result := Result + ' <' + AExcept.ClassName + '>'#13#10 + AExcept.Message;
if (AExcept.StackTrace <> '') then
Result := Result + #13#10'дамп стека:'#13#10 + AExcept.StackTrace;
GLogger.ToLog(Result);
end;
//------------------------------------------------------------------------------
// TNewLogger
//------------------------------------------------------------------------------
constructor TNewLogger.Create(const ALogName: string = ''; const AMultiProcess: Boolean = False);
var
FileDT: TFileTime;
SystemDT: TSystemTime;
begin
inherited Create();
//
FLogFileName := ALogName;
FMultiProcess := AMultiProcess;
if (FLogFileName = '') then
FLogFileName := ChangeFileExt(ExtractFileName(GetModuleName(HInstance)), '');
ForceDirectories(ExtractFilePath(GetModuleName(HInstance)) + 'log\');
LogOpen();
if GetFileTime(FHandle, nil, nil, @FileDT) then
begin
if FileTimeToSystemTime(@FileDT, SystemDT) then
begin
FPrevDate := EncodeDate(SystemDT.wYear, SystemDT.wMonth, SystemDT.wDay);
if (FPrevDate < Date()) then
Exit;
end;
end;
FPrevDate := Date();
end;
destructor TNewLogger.Destroy();
begin
LogClose();
//
inherited Destroy();
end;
procedure TNewLogger.ToLog(
const AMessage: string;
const ASkipTimeStamp: Boolean = False
);
var
MesFormatted: string;
MesRef: PChar;
RetPosition: Int64;
ActualWrite: DWORD;
begin
if (AMessage = '') then
Exit;
try
CheckTransition();
if ASkipTimeStamp then
MesFormatted := Format(CLogStrFormat, [CDateTimeFormatNoDate, AMessage])
else
MesFormatted := Format(CLogStrFormat, [FormatDateTime(CDateTimeFormat, Now()), AMessage]);
MesRef := PChar(MesFormatted);
if FMultiProcess then
SetFilePointerEx(FHandle, 0, @RetPosition, FILE_END);
Windows.WriteFile(FHandle, MesRef^, Length(MesFormatted) * SizeOf(Char), ActualWrite, nil);
except
// игнорируем все ошибки
end;
end;
procedure TNewLogger.CheckTransition();
var
LogPath, ArchPath, PathPath, TempStr: string;
begin
if (FPrevDate = Date()) then
Exit;
LogClose();
PathPath := ExtractFilePath(GetModuleName(HInstance)) + 'log\';
TempStr := FLogFileName;
LogPath := ChangeFileExt(PathPath + TempStr, '.log');
ArchPath := PathPath + TempStr + FormatDateTime('"__"yyyymmdd', Date() - 1) + '.log';
RenameFile(LogPath, ArchPath);
FPrevDate := Date();
LogOpen();
end;
procedure TNewLogger.LogOpen();
var
XPath: string;
RetPosition: Int64;
ErrorCode: DWORD;
begin
XPath := ExtractFilePath(GetModuleName(HInstance)) + 'log\' + FLogFileName + '.log';
FHandle := CreateFile(
PChar(XPath),
GENERIC_WRITE,
IfThen(
FMultiProcess,
FILE_SHARE_READ or FILE_SHARE_DELETE or FILE_SHARE_WRITE,
FILE_SHARE_READ or FILE_SHARE_DELETE
),
nil,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
0
);
ErrorCode := GetLastError();
if (FHandle = INVALID_HANDLE_VALUE) then
RaiseLastOSError(ErrorCode);
if not SetFilePointerEx(FHandle, 0, @RetPosition, FILE_END) then
RaiseLastOSError();
end;
procedure TNewLogger.LogClose();
begin
if (FHandle <> INVALID_HANDLE_VALUE) and (FHandle <> 0) then
CloseHandle(FHandle);
FHandle := 0;
end;
//------------------------------------------------------------------------------
initialization
GLogger := nil;
GLoggerSuffix := '';
{$ifndef NO_AUTOCREATE_LOGGER_OBJECT}
{$ifdef MULTIPROCESS_LOGGER_OBJECT}
StartLog(GLoggerSuffix, True);
{$else}
StartLog(GLoggerSuffix);
{$endif}
{$endif}
//------------------------------------------------------------------------------
finalization
GLogger.Free();
end.
|
{
"name": "Moon Box 2vs2 NS",
"description":"Little barren Moon for 2vs2 NS or 4 players FFA",
"version":"1.1",
"creator":"TheRealF",
"players":[4, 4],
"planets": [
{
"name": "Mutex",
"mass": 5000,
"position_x": 17100,
"position_y": -9500,
"velocity_x": 77.64236450195312,
"velocity_y": 139.7562713623047,
"required_thrust_to_move": 3,
"starting_planet": true,
"respawn": false,
"start_destroyed": false,
"min_spawn_delay": 0,
"max_spawn_delay": 0,
"planet": {
"seed": 946128768,
"radius": 250,
"heightRange": 50,
"waterHeight": 0,
"waterDepth": 100,
"temperature": 0,
"metalDensity": 100,
"metalClusters": 100,
"metalSpotLimit": -1,
"biomeScale": 50,
"biome": "moon",
"symmetryType": "terrain and CSG",
"symmetricalMetal": true,
"symmetricalStarts": true,
"numArmies": 2,
"landingZonesPerArmy": 0,
"landingZoneSize": 0
}
}
]
} |
unit Data.Articles;
interface
uses
System.StrUtils, System.Math, System.Classes;
type
TSource = (scDPA);
TSourceHelper = record helper for TSource
constructor Create(const ASourceCode: String);
function ToString: String;
end;
TLanguage = (laEN, laDE);
TLanguageHelper = record helper for TLanguage
constructor Create(const ALanguageCode: String);
function ToString: String;
end;
TSentiment = (seNegative = -1, seNeutral = 0, sePositive = 1);
TSentimentHelper = record helper for TSentiment
constructor Create(const ASentimentAmount: Double);
function ToDouble: Double;
end;
IiPoolArticle = interface
['{07129344-C577-499D-BAFD-031052A6633F}']
function GetHeading: String;
function GetContent: String;
function GetPublisher: String;
property Heading: String read GetHeading;
property Content: String read GetContent;
property Publisher: String read GetPublisher;
end;
IiPoolArticles = interface
['{F56CB0F1-9D1B-4CB2-8C91-9FB24F1E1EE9}']
function GetArticles(const AIndex: Integer): IiPoolArticle;
function GetCount: Integer;
property Articles[const AIndex: Integer]: IiPoolArticle read GetArticles;
property Count: Integer read GetCount;
end;
implementation
{ TSourceHelper }
constructor TSourceHelper.Create(const ASourceCode: String);
begin
Self := TSource(IndexText(ASourceCode, ['DPA']));
end;
function TSourceHelper.ToString: String;
begin
case Self of
scDPA:
Result := 'DPA';
end;
end;
{ TLanguageHelper }
constructor TLanguageHelper.Create(const ALanguageCode: String);
begin
Self := TLanguage(IndexText(ALanguageCode, ['en', 'de']));
end;
function TLanguageHelper.ToString: String;
begin
case Self of
laEN:
Result := 'en';
laDE:
Result := 'de';
end;
end;
{ TSentimentHelper }
constructor TSentimentHelper.Create(const ASentimentAmount: Double);
begin
Self := TSentiment(Sign(ASentimentAmount));
end;
function TSentimentHelper.ToDouble: Double;
begin
Result := Ord(Self);
end;
end.
|
unit uNewSrForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, uFormControl, ActnList, FIBDatabase, pFIBDatabase,
uFControl, uInvisControl, uDateControl, uLabeledFControl, uCharControl,
ComCtrls, ExtCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxEdit, DB, cxDBData, cxGridTableView, cxGridLevel,
cxGridCustomTableView, cxGridDBTableView, cxClasses, cxControls,
cxGridCustomView, cxGrid;
type
TfmNewSrOrder = class(TForm)
LocalDatabase: TpFIBDatabase;
LocalReadTransaction: TpFIBTransaction;
LocalWriteTransaction: TpFIBTransaction;
KeyList: TActionList;
OkAction: TAction;
CancelAction: TAction;
IdOrderType: TqFInvisControl;
NumItem: TqFInvisControl;
SubItem: TqFInvisControl;
IdOrderGroup: TqFInvisControl;
Intro: TqFInvisControl;
IdOrder: TqFInvisControl;
DateOrder: TqFInvisControl;
PageControl: TPageControl;
MainSheet: TTabSheet;
DetSheet: TTabSheet;
OkButton: TBitBtn;
Note: TqFCharControl;
DateBeg: TqFDateControl;
BottomPanel: TPanel;
CancelButton: TBitBtn;
ItemsGrid: TcxGrid;
cxGridDBTableView5: TcxGridDBTableView;
cxGridDBTableView5DBColumn1: TcxGridDBColumn;
cxGridDBTableView5DBColumn6: TcxGridDBColumn;
cxGridDBTableView5DBColumn3: TcxGridDBColumn;
cxGridDBTableView5DBColumn4: TcxGridDBColumn;
cxGridDBTableView5DBColumn5: TcxGridDBColumn;
cxGridDBTableView5DBColumn7: TcxGridDBColumn;
cxGridLevel5: TcxGridLevel;
Panel3: TPanel;
AddItemButton: TSpeedButton;
ModifyItemButton: TSpeedButton;
DeleteItemButton: TSpeedButton;
InfoButton: TSpeedButton;
StyleRepository: TcxStyleRepository;
stBackground: TcxStyle;
stContent: TcxStyle;
stContentEven: TcxStyle;
stContentOdd: TcxStyle;
stFilterBox: TcxStyle;
stFooter: TcxStyle;
stGroup: TcxStyle;
stGroupByBox: TcxStyle;
stHeader: TcxStyle;
stInactive: TcxStyle;
stIncSearch: TcxStyle;
stIndicator: TcxStyle;
stPreview: TcxStyle;
stSelection: TcxStyle;
stHotTrack: TcxStyle;
qizzStyle: TcxGridTableViewStyleSheet;
FormControl: TqFFormControl;
procedure OkActionExecute(Sender: TObject);
procedure CancelActionExecute(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
fmNewSrOrder: TfmNewSrOrder;
implementation
{$R *.dfm}
procedure TfmNewSrOrder.OkActionExecute(Sender: TObject);
begin
FormControl.Ok;
ModalResult := mrNone;
if FormControl.Mode = fmAdd then begin
IdOrder.Value := FormControl.LastId;
FormControl.Mode := fmModify;
end;
end;
procedure TfmNewSrOrder.CancelActionExecute(Sender: TObject);
begin
Close;
end;
end.
|
// Fenix ScreenShoter 0.6
// © Ismael Heredia, Argentina , 2017
unit fenix;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, ShellApi,
Jpeg, IdMultipartFormData, IdBaseComponent, IdComponent,
IdTCPConnection, IdTCPClient, IdHTTP, PerlRegEx, Vcl.Menus,
Vcl.Imaging.GIFImg, Vcl.ExtCtrls, Vcl.Imaging.pngimage;
type
TFormHome = class(TForm)
pcOptions: TPageControl;
tsUploadImageImageShack: TTabSheet;
tsUploadScreenshot: TTabSheet;
tsResult: TTabSheet;
ssStatus: TStatusBar;
gbEnterImage: TGroupBox;
btnLoad: TButton;
GroupBox2: TGroupBox;
btnUpload: TButton;
gbOptions: TGroupBox;
cbSavePhotoThisName: TCheckBox;
txtName: TEdit;
cbGetPhotoInSeconds: TCheckBox;
txtSeconds: TEdit;
Label1: TLabel;
cbOnlyTakeScreenshot: TCheckBox;
GroupBox4: TGroupBox;
btnTakeScreenAndUpload: TButton;
gbName: TGroupBox;
Button4: TButton;
gbLink: TGroupBox;
Button5: TButton;
tsPhotosFound: TTabSheet;
gbPhotosFound: TGroupBox;
lvPhotosFound: TListView;
txtEnterImage: TEdit;
txtResultName: TEdit;
txtLink: TEdit;
odOpenImage: TOpenDialog;
ppOptions: TPopupMenu;
RefreshList1: TMenuItem;
lbPhotos: TListBox;
OpenPhoto1: TMenuItem;
tsAbout: TTabSheet;
GroupBox8: TGroupBox;
imgAbout: TImage;
mmAbout: TMemo;
imgLogo: TImage;
procedure FormCreate(Sender: TObject);
procedure btnLoadClick(Sender: TObject);
procedure btnTakeScreenAndUploadClick(Sender: TObject);
procedure btnUploadClick(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure RefreshList1Click(Sender: TObject);
procedure listar_screenshots;
procedure lvPhotosFoundDblClick(Sender: TObject);
procedure OpenPhoto1Click(Sender: TObject);
private
procedure DragDropFile(var Msg: TMessage); message WM_DROPFILES;
public
{ Public declarations }
end;
var
FormHome: TFormHome;
implementation
{$R *.dfm}
procedure screenshot(filename: string);
var
var1: HDC;
var2: TRect;
var3: TPoint;
var4: TBitmap;
var5: TJpegImage;
var6: THandle;
begin
var1 := GetWindowDC(GetDesktopWindow);
var4 := TBitmap.Create;
GetWindowRect(GetDesktopWindow, var2);
var4.Width := var2.Right - var2.Left;
var4.Height := var2.Bottom - var2.Top;
BitBlt(var4.Canvas.Handle, 0, 0, var4.Width, var4.Height, var1, 0, 0,
SRCCOPY);
GetCursorPos(var3);
var6 := GetCursor;
DrawIconEx(var4.Canvas.Handle, var3.X, var3.Y, var6, 32, 32, 0, 0, DI_NORMAL);
var5 := TJpegImage.Create;
var5.Assign(var4);
var5.CompressionQuality := 60;
var5.SaveToFile(filename);
var4.Free;
var5.Free;
end;
//
procedure TFormHome.btnLoadClick(Sender: TObject);
begin
if odOpenImage.Execute then
begin
txtEnterImage.Text := odOpenImage.filename;
end;
end;
function upload_imageshack(image: string): string;
var
search: TPerlRegEx;
input: TIdMultiPartFormDataStream;
codigo_fuente: string;
web: TIdHTTP;
output: string;
begin
input := TIdMultiPartFormDataStream.Create;
input.AddFormField('key', 'ACDEIOPU4a1f216b9cb1564f6be25957dfca92b2');
input.AddFile('fileupload', image, 'application/octet-stream');
input.AddFormField('format', 'json');
web := TIdHTTP.Create(nil);
web.Request.UserAgent :=
'Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14';
codigo_fuente := web.Post('http://post.imageshack.us/upload_api.php', input);
search := TPerlRegEx.Create();
search.regex := '"image_link":"(.*?)"';
search.Subject := codigo_fuente;
if search.Match then
begin
output := search.Groups[1];
output := StringReplace(output, '\', '', [rfReplaceAll, rfIgnoreCase]);
end
else
begin
output := 'Error';
end;
web.Free;
search.Free;
Result := output;
end;
procedure TFormHome.btnUploadClick(Sender: TObject);
var
output: string;
begin
ssStatus.Panels[0].Text := 'Uploading ...';
FormHome.ssStatus.Update;
if (FileExists(txtEnterImage.Text)) then
begin
output := upload_imageshack(txtEnterImage.Text);
if (output = 'Error') then
begin
ShowMessage('Error');
end
else
begin
txtResultName.Text := txtEnterImage.Text;
txtLink.Text := output;
end;
end
else
begin
ShowMessage('The image not exists');
end;
ssStatus.Panels[0].Text := 'Finished';
FormHome.ssStatus.Update;
end;
procedure TFormHome.btnTakeScreenAndUploadClick(Sender: TObject);
var
nombre_final: string;
data1: TDateTime;
data2: string;
data3: string;
int1: integer;
output: string;
begin
if (cbSavePhotoThisName.Checked = True) then
begin
nombre_final := txtName.Text;
end
else
begin
data1 := now();
data2 := DateTimeToStr(data1);
data3 := data2 + '.jpg';
data3 := StringReplace(data3, '/', ':', [rfReplaceAll, rfIgnoreCase]);
data3 := StringReplace(data3, ' ', '', [rfReplaceAll, rfIgnoreCase]);
data3 := StringReplace(data3, ':', '_', [rfReplaceAll, rfIgnoreCase]);
nombre_final := 'screenshot_' + data3;
end;
if (cbGetPhotoInSeconds.Checked) then
begin
for int1 := StrToInt(txtSeconds.Text) downto 1 do
begin
ssStatus.Panels[0].Text := 'ScreenShot in ' + IntToStr(int1) +
' seconds ';
FormHome.ssStatus.Update;
Sleep(int1 * 1000);
end;
end;
FormHome.Hide;
Sleep(1000);
screenshot(nombre_final);
FormHome.Show;
if not(cbOnlyTakeScreenshot.Checked) then
begin
ssStatus.Panels[0].Text := 'Uploading ...';
FormHome.ssStatus.Update;
// Uploaded
if (FileExists(nombre_final)) then
begin
output := upload_imageshack(nombre_final);
if (output = 'Error') then
begin
ShowMessage('Error');
end
else
begin
txtResultName.Text := ExtractFilePath(Application.ExeName) +
'\screenshots\' + nombre_final;
txtLink.Text := output;
end;
end
else
begin
ShowMessage('The image not exists');
end;
ssStatus.Panels[0].Text := 'ScreenShot Uploaded';
FormHome.ssStatus.Update;
end
else
begin
ssStatus.Panels[0].Text := 'ScreenShot Taked';
FormHome.ssStatus.Update;
end;
listar_screenshots;
end;
procedure TFormHome.Button4Click(Sender: TObject);
begin
ShellExecute(Handle, 'open', Pchar(txtResultName.Text), nil, nil,
SW_SHOWNORMAL);
end;
procedure TFormHome.Button5Click(Sender: TObject);
begin
txtLink.SelectAll;
txtLink.CopyToClipboard;
end;
procedure TFormHome.DragDropFile(var Msg: TMessage);
var
numero2: integer;
numero1: integer;
ruta: array [0 .. MAX_COMPUTERNAME_LENGTH + MAX_PATH] of char;
begin
numero2 := DragQueryFile(Msg.WParam, $FFFFFFFF, ruta, 255) - 1;
for numero1 := 0 to numero2 do
begin
DragQueryFile(Msg.WParam, numero1, ruta, 255);
txtEnterImage.Text := ruta;
end;
DragFinish(Msg.WParam);
end;
procedure TFormHome.FormCreate(Sender: TObject);
var
saved: string;
begin
DragAcceptFiles(Handle, True);
odOpenImage.InitialDir := GetCurrentDir;
saved := ExtractFilePath(Application.ExeName) + '/screenshots';
if not(DirectoryExists(saved)) then
begin
CreateDir(saved);
end;
ChDir(saved);
listar_screenshots;
end;
procedure TFormHome.listar_screenshots;
var
search: TSearchRec;
ext: string;
fecha1: integer;
begin
lvPhotosFound.Items.Clear();
lbPhotos.Items.Clear();
FindFirst(ExtractFilePath(Application.ExeName) + '\screenshots\*.*',
faAnyFile, search);
while FindNext(search) = 0 do
begin
ext := ExtractFileExt(search.Name);
if (ext = '.jpg') or (ext = '.jpeg') or (ext = '.png') or (ext = '.bmp')
then
begin
with lvPhotosFound.Items.Add do
begin
fecha1 := FileAge(ExtractFilePath(Application.ExeName) + '\screenshots\'
+ search.Name);
lbPhotos.Items.Add(ExtractFilePath(Application.ExeName) +
'\screenshots\' + search.Name);
Caption := search.Name;
SubItems.Add(DateToStr(FileDateToDateTime(fecha1)));
end;
end;
end;
FindClose(search);
end;
procedure TFormHome.lvPhotosFoundDblClick(Sender: TObject);
begin
ShellExecute(0, nil, Pchar(lbPhotos.Items[lvPhotosFound.Selected.Index]), nil,
nil, SW_SHOWNORMAL);
end;
procedure TFormHome.OpenPhoto1Click(Sender: TObject);
begin
ShellExecute(0, nil, Pchar(lbPhotos.Items[lvPhotosFound.Selected.Index]), nil,
nil, SW_SHOWNORMAL);
end;
procedure TFormHome.RefreshList1Click(Sender: TObject);
begin
listar_screenshots;
end;
end.
|
unit Seasons;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, math;
type
TSeasons = class(TComponent)
private
fSeasyear: Integer;
fTimeZone: Double;
fSpringdate: TDateTime;
fSummerDate: TdateTime;
fAutumnDate: TdateTime;
fWinterDate: TDateTime;
procedure setSeasyear(value: Integer);
procedure SetTimeZone(Value: Double);
function GetSeasonDate(num: Integer): TDateTime;
function Periodic24(t: Double): Double;
protected
public
constructor Create(AOwner: TComponent); override;
property SpringDate: TDateTime read fSpringdate;
property SummerDate: TdateTime read fSummerDate;
property AutumnDate: TdateTime read fAutumnDate;
property WinterDate: TDateTime read fWinterDate;
published
property Seasyear: Integer read fSeasyear write setSeasyear;
property Timezone: Double read fTimezone write setTimezone;
end;
procedure Register;
implementation
procedure Register;
begin
{$I seasons_icon.lrs}
RegisterComponents('lazbbAstroComponents',[TSeasons]);
end;
constructor TSeasons.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fSeasyear:= CurrentYear;
fTimeZone:= 0;
end;
procedure TSeasons.setSeasyear(value: Integer);
begin
if fSeasyear<>value then
begin
fSeasyear:= value;
if not (csDesigning in ComponentState) then
begin
fSpringdate:= GetSeasonDate(0);
fSummerdate:= GetSeasonDate(1);
fAutumnDate:= GetSeasonDate(2);
fWinterDate:= GetSeasonDate(3);
end;
end;
end;
procedure TSeasons.SetTimeZone(Value: Double);
begin
if (fTimeZone <> Value) and (Value >= -12) and (Value <= +12) then
begin
fTimeZone := Value;
if not (csDesigning in ComponentState) then
begin
fSpringdate:= GetSeasonDate(0);
fSummerdate:= GetSeasonDate(1);
fAutumnDate:= GetSeasonDate(2);
fWinterDate:= GetSeasonDate(3);
end;
end;
end;
// Meeus Astronmical Algorithms Chapter 27
function TSeasons.GetSeasonDate(num: Integer): TDateTime;
var
dDate: TDateTime;
jdeo, yr, t, w, dl, s, julDay: Double;
deltaT: Double;
scl: Double;
begin
// Caclul initial du jour julien
yr:=(fSeasyear-2000)/1000;
Case num of
0: jdeo:= 2451623.80984 + 365242.37404*yr + 0.05169*power(yr,2) - 0.00411*power(yr,3) - 0.00057*power(yr,4);
1: jdeo:= 2451716.56767 + 365241.62603*yr + 0.00325*power(yr,2) + 0.00888*power(yr,3) - 0.00030*power(yr,4);
2: jdeo:= 2451810.21715 + 365242.01767*yr - 0.11575*power(yr,2) + 0.00337*power(yr,3) + 0.00078*power(yr,4);
3: jdeo:= 2451900.05952 + 365242.74049*yr - 0.06223*power(yr,2) - 0.00823*power(yr,3) + 0.00032*power(yr,4);
else
jdeo:= 0;
end;
t:= (jdeo - 2451545.0)/36525;
w:= (35999.373*t) - 2.47;
dl:= 1 + 0.0334*cos(DegToRad(w)) + 0.0007*cos(DegToRad(2*w));
// Correction périodique
s:= Periodic24(t);
julDay:= jdeo + ( (0.00001*s) / dL ); // This is the answer in Julian Emphemeris Days
// écart entre UTC et DTD en secondes entre les années from Meeus Astronmical Algroithms Chapter 10
scl:= (fSeasyear - 2000) / 100;
deltaT:= 102 + 102*scl + 25.3*power(scl,2);
// Special correction to avoid discontinurity in 2000
if (fSeasyear >=2000) and (fSeasyear <=2100) then deltaT:= deltaT+ 0.37 * (fSeasyear - 2100 );
// Ecart en jour fractionnaire
deltaT:= deltaT/86400;
// On y est ! Conversion en date réelle
dDate:= julDay-deltaT-693594-1721425+0.5; //DateDelta= 693594 + 1721425-0,5;
Result:= dDate+fTimeZone/24;
end;
function TSeasons.Periodic24(t: Double ): Double;
const
A: array[0..23] of integer = (485,203,199,182,156,136,77,74,70,58,52,50,45,44,29,18,17,16,14,12,12,12,9,8);
B: array[0..23] of real = (324.96,337.23,342.08,27.85,73.14,171.52,222.54,296.72,243.58,119.81,297.17,21.02,
247.54,325.15,60.93,155.12,288.79,198.04,199.76,95.39,287.11,320.81,227.73,15.45);
C: array[0..23] of real = (1934.136,32964.467,20.186,445267.112,45036.886,22518.443,
65928.934,3034.906,9037.513,33718.147,150.678,2281.226,
29929.562,31555.956,4443.417,67555.328,4562.452,62894.029,
31436.921,14577.848,31931.756,34777.259,1222.114,16859.074);
var
i: Integer;
begin
result:= 0;
for i:= 0 to 23 do
//result:= result + A[i]*degCOS(;
result:= result + A[i]*cos(DegToRad(B[i] + (C[i]*T)));
end;
end.
|
unit Dmitry.Imaging.JngImage;
interface
uses
System.Classes,
Vcl.Graphics,
Vcl.Imaging.pngimage,
Vcl.Imaging.jpeg,
Dmitry.Memory,
Dmitry.Graphics.Types;
type
TJNGImage = class(TBitmap)
private
FJpegConpresionQuality: TJPEGQualityRange;
public
constructor Create; override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
property JpegConpresionQuality: TJPEGQualityRange read FJpegConpresionQuality write FJpegConpresionQuality;
end;
implementation
{ TJNGImage }
constructor TJNGImage.Create;
begin
inherited Create;
FJpegConpresionQuality := 85;
PixelFormat := pf32Bit;
end;
procedure TJNGImage.LoadFromStream(Stream: TStream);
var
B: TBitmap;
Png: TPngImage;
JpegImage: TJpegImage;
I, J: Integer;
P: PARGB;
P32: PARGB32;
AP: PByteArray;
begin
Png := TPngImage.Create;
JpegImage := TJpegImage.Create;
B := TBitmap.Create;
try
Png.LoadFromStream(Stream);
JpegImage.LoadFromStream(Stream);
JpegImage.DIBNeeded;
B.Assign(JpegImage);
B.PixelFormat := pf24Bit;
AlphaFormat := afDefined;
SetSize(B.Width, B.Height);
for I := 0 to Height - 1 do
begin
P32 := Self.ScanLine[I];
P := B.ScanLine[I];
AP := Png.Scanline[I];
for J := 0 to Width - 1 do
begin
P32[J].R := P[J].R;
P32[J].G := P[J].G;
P32[J].B := P[J].B;
P32[J].L := AP[J];
end;
end;
finally
F(B);
F(JpegImage);
F(Png);
end;
end;
procedure TJNGImage.SaveToStream(Stream: TStream);
var
B: TBitmap;
Png: TPngImage;
JpegImage: TJpegImage;
I, J: Integer;
P: PARGB;
P32: PARGB32;
AP: PByteArray;
begin
Png := TPngImage.CreateBlank(COLOR_GRAYSCALE, 8, Width, Height);
JpegImage := TJpegImage.Create;
B := TBitmap.Create;
try
B.PixelFormat := pf24Bit;
B.SetSize(Width, Height);
for I := 0 to Height - 1 do
begin
P32 := Self.ScanLine[I];
P := B.ScanLine[I];
AP := Png.Scanline[I];
for J := 0 to Width - 1 do
begin
P[J].R := P32[J].R;
P[J].G := P32[J].G;
P[J].B := P32[J].B;
AP[J] := P32[J].L;
end;
end;
JpegImage.Assign(B);
JpegImage.CompressionQuality := FJpegConpresionQuality;
JpegImage.ProgressiveEncoding := False;
JpegImage.Performance := jpBestQuality;
JpegImage.Compress;
Png.SaveToStream(Stream);
JpegImage.SaveToStream(Stream);
finally
F(B);
F(JpegImage);
F(Png);
end;
end;
end.
|
{**********************************************************************
Package pl_Shapes.pkg
This unit is part of CodeTyphon Studio (http://www.pilotlogic.com/)
***********************************************************************}
unit TplShapesUnit;
{$R-,W-,S-}
interface
uses
LCLType, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Math;
type
TplCustomShape = class(TGraphicControl)
private
FBrush: TBrush;
FPen: TPen;
FShadow: boolean;
FShadowOffset: integer;
FShadowColor: TColor;
procedure ChangeRedraw(Sender: TObject);
procedure SetBrush(Value: TBrush);
procedure SetPen(Value: TPen);
procedure SetShadow(Value: boolean);
procedure SetShadowOffset(Value: integer);
procedure SetShadowColor(Value: TColor);
protected
procedure Paint; override;
procedure PaintShadow; virtual;
procedure PaintShape; virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Align;
property Brush: TBrush read FBrush write SetBrush;
property DragCursor;
property DragMode;
property Enabled;
property ParentShowHint;
property Pen: TPen read FPen write SetPen;
property Shadow: boolean read FShadow write SetShadow;
property ShadowOffset: integer read FShadowOffset write SetShadowOffset;
property ShadowColor: TColor read FShadowColor write SetShadowColor;
property ShowHint;
property Visible;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
end;
TplCustomPolyShape = class(TplCustomShape)
protected
fAngle: single;
procedure SetAngle(val: single);
function CalcPoly(var Points: array of TPoint; Source: array of TPoint; AWidth, AHeight: integer): boolean; virtual;
procedure OffsetPoly(var Points: array of TPoint; OfsX, OfsY: integer); virtual;
property Angle: single read fangle write SetAngle;
end;
//.............NO Angle Shapes ...................
TplRectShape = class(TplCustomShape)
protected
procedure PaintShadow; override;
procedure PaintShape; override;
end;
TplRoundRectShape = class(TplCustomShape)
protected
procedure PaintShadow; override;
procedure PaintShape; override;
end;
TplSquareShape = class(TplCustomShape)
protected
procedure PaintShadow; override;
procedure PaintShape; override;
end;
TplRoundSquareShape = class(TplCustomShape)
protected
procedure PaintShadow; override;
procedure PaintShape; override;
end;
TplEllipseShape = class(TplCustomShape)
protected
procedure PaintShadow; override;
procedure PaintShape; override;
end;
TplCircleShape = class(TplCustomShape)
protected
procedure PaintShadow; override;
procedure PaintShape; override;
end;
//.............Angle Shapes ...................
TplTriangleShape = class(TplCustomPolyShape)
protected
procedure PaintShadow; override;
procedure PaintShape; override;
published
property Angle;
end;
TplRectangleShape = class(TplCustomPolyShape)
protected
procedure PaintShadow; override;
procedure PaintShape; override;
published
property Angle;
end;
TplParallelogramShape = class(TplCustomPolyShape)
protected
procedure PaintShadow; override;
procedure PaintShape; override;
published
property Angle;
end;
TplTrapezoidShape = class(TplCustomPolyShape)
protected
procedure PaintShadow; override;
procedure PaintShape; override;
published
property Angle;
end;
TplPentagonShape = class(TplCustomPolyShape)
protected
procedure PaintShadow; override;
procedure PaintShape; override;
published
property Angle;
end;
TplHexagonShape = class(TplCustomPolyShape)
protected
procedure PaintShadow; override;
procedure PaintShape; override;
published
property Angle;
end;
TplOctagonShape = class(TplCustomPolyShape)
protected
procedure PaintShadow; override;
procedure PaintShape; override;
published
property Angle;
end;
TplStarShape = class(TplCustomPolyShape)
protected
procedure PaintShadow; override;
procedure PaintShape; override;
published
property Angle;
end;
TplBubbleShape = class(TplCustomPolyShape)
protected
procedure PaintShadow; override;
procedure PaintShape; override;
published
property Angle;
end;
implementation
{ Polygon points for geometric shapes }
const
POLY_TRIANGLE: array[0..3] of TPoint =
((X: 50; Y: 0), (X: 100; Y: 100), (X: 0; Y: 100), (X: 50; Y: 0));
POLY_RECTANGLE: array[0..4] of TPoint =
((X: 0; Y: 0), (X: 100; Y: 0), (X: 100; Y: 100), (X: 0; Y: 100), (X: 0; Y: 0));
POLY_PARALLELOGRAM: array[0..4] of TPoint =
((X: 0; Y: 0), (X: 75; Y: 0), (X: 100; Y: 100), (X: 25; Y: 100), (X: 0; Y: 0));
POLY_TRAPEZOID: array[0..4] of TPoint =
((X: 25; Y: 0), (X: 75; Y: 0), (X: 100; Y: 100), (X: 0; Y: 100), (X: 25; Y: 0));
POLY_PENTAGON: array[0..5] of TPoint =
((X: 50; Y: 0), (X: 100; Y: 50), (X: 75; Y: 100), (X: 25; Y: 100), (X: 0; Y: 50), (X: 50; Y: 0));
POLY_HEXAGON: array[0..6] of TPoint =
((X: 25; Y: 0), (X: 75; Y: 0), (X: 100; Y: 50), (X: 75; Y: 100), (X: 25; Y: 100), (X: 0; Y: 50),
(X: 25; Y: 0));
POLY_OCTAGON: array[0..8] of TPoint =
((X: 25; Y: 0), (X: 75; Y: 0), (X: 100; Y: 25), (X: 100; Y: 75), (X: 75; Y: 100), (X: 25; Y: 100),
(X: 0; Y: 75), (X: 0; Y: 25), (X: 25; Y: 0));
POLY_STAR: array[0..16] of TPoint =
((X: 44; Y: 0), (X: 52; Y: 24), (X: 76; Y: 12), (X: 64; Y: 36), (X: 88; Y: 44), (X: 64; Y: 52),
(X: 76; Y: 76), (X: 52; Y: 64), (X: 44; Y: 88), (X: 36; Y: 64), (X: 12; Y: 76), (X: 24; Y: 52),
(X: 0; Y: 44), (X: 24; Y: 36), (X: 12; Y: 12), (X: 36; Y: 24), (X: 44; Y: 0));
POLY_BUBBLE: array[0..11] of TPoint =
((X: 40; Y: 92), (X: 68; Y: 40), (X: 80; Y: 40), (X: 92; Y: 28), (X: 92; Y: 12), (X: 80; Y: 0),
(X: 12; Y: 0), (X: 0; Y: 12), (X: 0; Y: 28), (X: 12; Y: 40), (X: 60; Y: 40), (X: 40; Y: 92));
//============================ TplCustomShape =======================================
constructor TplCustomShape.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle + [csReplicatable];
Width := 64;
Height := 64;
FBrush := TBrush.Create;
FBrush.OnChange := @ChangeRedraw;
FPen := TPen.Create;
FPen.OnChange := @ChangeRedraw;
FShadow := True;
FShadowOffset := 2;
FShadowColor := clBtnShadow;
end;
destructor TplCustomShape.Destroy;
begin
FBrush.Free;
FPen.Free;
inherited Destroy;
end;
procedure TplCustomShape.Paint;
begin
inherited Paint;
Canvas.Brush := FBrush;
Canvas.Pen := FPen;
if Shadow then
PaintShadow;
PaintShape;
end;
procedure TplCustomShape.PaintShadow;
begin
Canvas.Brush.Color := FShadowColor;
Canvas.Pen.Color := FShadowColor;
end;
procedure TplCustomShape.PaintShape;
begin
Canvas.Brush.Color := FBrush.Color;
Canvas.Pen.Color := FPen.Color;
end;
procedure TplCustomShape.ChangeRedraw(Sender: TObject);
begin
Invalidate;
end;
procedure TplCustomShape.SetBrush(Value: TBrush);
begin
FBrush.Assign(Value);
end;
procedure TplCustomShape.SetPen(Value: TPen);
begin
FPen.Assign(Value);
end;
procedure TplCustomShape.SetShadow(Value: boolean);
begin
if FShadow <> Value then
begin
FShadow := Value;
Invalidate;
end;
end;
procedure TplCustomShape.SetShadowOffset(Value: integer);
begin
if FShadowOffset <> Value then
begin
FShadowOffset := Value;
Invalidate;
end;
end;
procedure TplCustomShape.SetShadowColor(Value: TColor);
begin
if FShadowColor <> Value then
begin
FShadowColor := Value;
Invalidate;
end;
end;
//=========================== TplCustomPolyShape ===========================================
function TplCustomPolyShape.CalcPoly(var Points: array of TPoint; Source: array of TPoint; AWidth, AHeight: integer): boolean;
var
i: integer;
lx, ly: longint;
vSin, vCos: extended;
Px, Py, CenterX, CenterY, FminX, FminY, FmaxX, FMaxY: Float;
begin
Result := True;
try
//......Resize to AWidth/AHeight ..........................
for i := Low(Points) to High(Points) do
begin
lx := MulDiv(Source[i].x, AWidth, 100);
ly := MulDiv(Source[i].y, AHeight, 100);
Points[i].x := lx;
Points[i].y := ly;
end;
//... Rotate for angle ....................................
CenterX := AWidth / 2;
CenterY := AHeight / 2;
SinCos(DegToRad(-fAngle), vSin, vCos);
for i := Low(Points) to High(Points) do
begin
Px := (Points[i].x - CenterX);
Py := (Points[i].y - CenterY);
Points[i].x := round(Px * vCos + Py * vSin + CenterX);
Points[i].y := round(Py * vCos - Px * vSin + CenterY);
end;
//.........................................................
FminX := 0;
FminY := 0;
FmaxX := AWidth;
FmaxY := AHeight;
for i := Low(Points) to High(Points) do
begin
//..find min....
if Points[i].x < 0 then
if Points[i].x < FminX then
FminX := Points[i].x;
if Points[i].y < 0 then
if Points[i].y < FminY then
FminY := Points[i].y;
//..find max....
if Points[i].x > AWidth then
if Points[i].x > FmaxX then
FmaxX := Points[i].x;
if Points[i].y > AHeight then
if Points[i].y > FmaxY then
FmaxY := Points[i].y;
end;
for i := Low(Points) to High(Points) do
begin
Points[i].x := round(Points[i].x - FminX);
Points[i].y := round(Points[i].y - FminY);
lx := MulDiv(Points[i].x, AWidth, Round(FmaxX - FminX));
ly := MulDiv(Points[i].y, AHeight, Round(FmaxY - FminY));
Points[i].x := lx;
Points[i].y := ly;
end;
except
Result := False;
end;
end;
procedure TplCustomPolyShape.OffsetPoly(var Points: array of TPoint; OfsX, OfsY: integer);
var
i: integer;
begin
for i := Low(Points) to High(Points) do
begin
Points[i].x := Points[i].x + OfsX;
Points[i].y := Points[i].y + OfsY;
end;
end;
procedure TplCustomPolyShape.SetAngle(val: single);
begin
if val = angle then
exit;
fangle := val;
if fangle > 360 then
fangle := 360;
if fangle < 0 then
fangle := 0;
Invalidate;
end;
//================================================================
{$I wAngleShapes.inc}
{$I wNoAngleShapes.inc}
end.
|
/// <summary>
/// Unit generated using the Delphi Wmi class generator tool, Copyright Rodrigo Ruz V. 2010-2012
/// Application version 1.0.4674.62299
/// WMI version 7601.17514
/// Creation Date 17-10-2012 18:18:17
/// Namespace root\CIMV2 Class Win32_ComputerSystem
/// MSDN info about this class http://msdn2.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/Win32_ComputerSystem.asp
/// </summary>
unit uWin32_ComputerSystem;
interface
uses
Classes,
Activex,
Variants,
ComObj,
uWmiDelphiClass;
type
{$REGION 'Documentation'}
/// <summary>
/// The Win32_ComputerSystem class represents a computer system operating in a
/// Win32 environment.
/// </summary>
{$ENDREGION}
TWin32_ComputerSystem=class(TWmiClass)
private
FSystemType : String;
FTotalPhysicalMemory : Int64;
public
constructor Create(LoadWmiData : boolean=True); overload;
destructor Destroy;Override;
{$REGION 'Documentation'}
/// <summary>
/// The SystemType property indicates the type of system running on the Win32 computer.
/// Constraints: Must have a value
/// </summary>
{$ENDREGION}
property SystemType : String read FSystemType;
{$REGION 'Documentation'}
/// <summary>
/// The TotalPhysicalMemory property indicates the total size of physical memory.
/// Example: 67108864
/// </summary>
{$ENDREGION}
property TotalPhysicalMemory : Int64 read FTotalPhysicalMemory;
procedure SetCollectionIndex(Index : Integer); override;
end;
implementation
{TWin32_ComputerSystem}
constructor TWin32_ComputerSystem.Create(LoadWmiData : boolean=True);
begin
inherited Create(LoadWmiData,'root\CIMV2','Win32_ComputerSystem');
end;
destructor TWin32_ComputerSystem.Destroy;
begin
inherited;
end;
procedure TWin32_ComputerSystem.SetCollectionIndex(Index : Integer);
begin
if (Index>=0) and (Index<=FWmiCollection.Count-1) and (FWmiCollectionIndex<>Index) then
begin
FWmiCollectionIndex:=Index;
FSystemType := VarStrNull(inherited Value['SystemType']);
FTotalPhysicalMemory := VarInt64Null(inherited Value['TotalPhysicalMemory']);
end;
end;
end.
|
unit uSettings;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Mask, sMaskEdit, sCustomComboEdit, sTooledit, IniFiles,
Buttons, sBitBtn, StrUtils, MyFunctions;
type
TfmSettings = class(TForm)
deDefDir: TsDirectoryEdit;
Label1: TLabel;
Label2: TLabel;
mePR: TsMaskEdit;
Label3: TLabel;
Label4: TLabel;
btSave: TsBitBtn;
btCancel: TsBitBtn;
procedure btSaveClick(Sender: TObject);
procedure btCancelClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
fmSettings: TfmSettings;
inifile:TIniFile;
implementation
{$R *.dfm}
{=== Сохранение настроек ===}
procedure TfmSettings.btSaveClick(Sender: TObject);
begin
// Путь
if deDefDir.Text='' then
begin
MessageBox(self.Handle, 'Путь не указан!'+#09#13+
'Используются настройки по-умолчанию.','Обнаружена ошибка!',
MB_ICONWARNING+MB_OK);
inifile.DeleteKey('settings','defpath');
end else
inifile.WriteString('settings','defpath',deDefDir.Text);
// Призыв
if strtoint(ReplaceStr(mePR.Text,' ','0'))<100 then
begin
MessageBox(self.Handle, 'Призыв введен неправильно или неполностью!'+
#09#13+'Используются настройки по-умолчанию.','Обнаружена ошибка!',
MB_ICONWARNING+MB_OK);
inifile.DeleteKey('settings','defpr');
end else
inifile.WriteString('settings','defpr',mePR.Text);
inifile.Free;
Close;
end;
procedure TfmSettings.btCancelClick(Sender: TObject);
begin
inifile.Free;
Close;
end;
{=== Чтение настроек ===}
procedure TfmSettings.FormShow(Sender: TObject);
var
str:ansistring;
begin
str:=GetPath(Application.ExeName);
inifile:=TIniFile.Create(str+'convset.ini');
deDefDir.Text:=inifile.ReadString('settings','defpath','');
mePR.Text:=inifile.ReadString('settings','defpr','');
end;
end.
|
{$MODE OBJFPC}
{$R-,Q-,S-,I+}
{$OPTIMIZATION LEVEL2}
program IntervalCover;
uses Windows, SysUtils, Math;
const
prefix = 'INCSEQ';
InputFile = prefix + '.INP';
OutputFile = prefix + '.OUT';
AnswerFile = prefix + '.OUT';
var
dirT, dirC: WideString;
fi, fo, fa: TextFile;
procedure GenErr(const s: string; const param: array of const);
begin
raise Exception.CreateFmt(s, param);
end;
procedure ReadDirs;
var
s: AnsiString;
begin
ReadLn(s); dirT := Utf8Decode(s);
ReadLn(s); dirC := Utf8Decode(s);
end;
procedure OpenFiles;
var
CurrentDir: array[0..Max_Path + 1] of WideChar;
begin
GetCurrentDirectoryW(Max_Path, CurrentDir);
SetCurrentDirectoryW(PWideChar(dirT));
AssignFile(fi, InputFile); Reset(fi);
AssignFile(fa, AnswerFile); Reset(fa);
SetCurrentDirectoryW(CurrentDir);
SetCurrentDirectoryW(PWideChar(dirC));
AssignFile(fo, OutputFile); Reset(fo);
end;
procedure CloseFiles;
begin
CloseFile(fi);
CloseFile(fa);
CloseFile(fo);
end;
//----------------------------------------------------------------------------------------------------------------
// Comment:
// fi: File input
// fa: File answer
// fo: File output
// Cac dong dau ghi loi chu thich
// Dong cuoi ghi mot so thuc nam trong pham vi 0->1
procedure DoCheck;
var
dong,kqa, kqo: longint;
begin
dong:=0;
while not seekeof(fa) do
begin
readln(fa,kqa);
readln(fo,kqo);
inc(dong);
if kqa<>kqo then
begin
writeln('Sai o dong:',dong);
writeln('0.0');
exit;
end;
end;
writeln('Ket qua DUNG');
writeln('1.0');
end;
//-----------------------------------------------------------------------------------------------------------------
begin
try
try
ReadDirs;
OpenFiles;
DoCheck;
finally
CloseFiles;
end;
except
on E: Exception do
begin
WriteLn(E.Message);
WriteLn('0.0');
end;
end;
end.
|
{ Basic terrain rendering demo.
The base terrain renderer uses a hybrid ROAM/brute-force approach to
rendering terrain, by requesting height data tiles, then rendering them
using either triangle strips (for those below "QualityDistance") or ROAM
tessellation.
Controls:
Direction keys move the came nora (shift to speedup)
PageUp/PageDown move the camera up and down
Orient the camera freely by holding down the left button
Toggle wireframe mode with 'w'
Increase/decrease the viewing distance with '+'/'-'.
Increase/decrease CLOD precision with '*' and '/'.
Increase/decrease QualityDistance with '9' and '8'.
When increasing the range, or moving after having increased the range you
may notice a one-time slowdown, this originates in the base height data
being duplicated to create the illusion of an "infinite" terrain (at max
range the visible area covers 1024x1024 height samples, and with tiles of
size 16 or less, this is a lot of tiles to prepare).
}
unit Unit1;
interface
uses
Windows, // weird, but for Winapi.Windows there is no wireframes mode
Winapi.Messages,
System.SysUtils,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.ExtCtrls,
Vcl.Imaging.jpeg,
GLScene,
GLState,
GLTerrainRenderer,
GLBaseClasses,
GLObjects,
GLHeightData,
GLMaterial,
GLCadencer,
GLTexture,
GLHUDObjects,
GLBitmapFont,
GLSkydome,
GLWin32Viewer,
GLVectorGeometry,
GLMesh,
GLVectorFileObjects,
GLFireFX,
GLCoordinates,
GLCrossPlatform,
GLFile3DS,
GLKeyboard;
type
TForm1 = class(TForm)
GLSceneViewer1: TGLSceneViewer;
GLBitmapHDS1: TGLBitmapHDS;
GLScene1: TGLScene;
GLCamera1: TGLCamera;
DummyCube1: TGLDummyCube;
TerrainRenderer1: TGLTerrainRenderer;
Timer1: TTimer;
GLCadencer1: TGLCadencer;
GLMaterialLibrary1: TGLMaterialLibrary;
SkyDome1: TGLSkyDome;
FreeForm1: TGLFreeForm;
GLFireFXManager1: TGLFireFXManager;
DummyCube2: TGLDummyCube;
procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure Timer1Timer(Sender: TObject);
procedure GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: Double);
procedure FormCreate(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
private
public
mx, my: Integer;
fullScreen: Boolean;
FCamHeight: Single;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
begin
fullScreen := false;
SetCurrentDir(ExtractFilePath(ParamStr(0)));
// 8 MB height data cache
// Note this is the data size in terms of elevation samples, it does not
// take into account all the data required/allocated by the renderer
GLBitmapHDS1.MaxPoolSize := 8 * 1024 * 1024;
// specify height map data
GLBitmapHDS1.Picture.LoadFromFile('terrain.bmp');
// load the texture maps
GLMaterialLibrary1.Materials[0].Material.Texture.Image.LoadFromFile
('snow512.jpg');
GLMaterialLibrary1.Materials[1].Material.Texture.Image.LoadFromFile
('detailmap.jpg');
// apply texture map scale (our heightmap size is 256)
TerrainRenderer1.TilesPerTexture := 256 / TerrainRenderer1.TileSize;
// Could've been done at design time, but it the, it hurts the eyes ;)
GLSceneViewer1.Buffer.BackgroundColor := clBlack;
// Move camera starting point to an interesting hand-picked location
DummyCube1.Position.X := 570;
DummyCube1.Position.Z := -385;
DummyCube1.Turn(90);
// Initial camera height offset (controled with pageUp/pageDown)
FCamHeight := 10;
with SkyDome1 do
begin
Bands[1].StopColor.AsWinColor := RGB(0, 0, 16);
Bands[1].StartColor.AsWinColor := RGB(0, 0, 8);
Bands[0].StopColor.AsWinColor := RGB(0, 0, 8);
Bands[0].StartColor.AsWinColor := RGB(0, 0, 0);
with Stars do
begin
AddRandomStars(700, clWhite, True); // many white stars
AddRandomStars(100, RGB(255, 200, 200), True); // some redish ones
AddRandomStars(100, RGB(200, 200, 255), True); // some blueish ones
AddRandomStars(100, RGB(255, 255, 200), True); // some yellowish ones
end;
GLSceneViewer1.Buffer.BackgroundColor := clBlack;
with GLSceneViewer1.Buffer.FogEnvironment do
begin
FogColor.AsWinColor := clBlack;
FogStart := -FogStart; // Fog is used to make things darker
end;
end;
FreeForm1.LoadFromFile('ship.3ds');
FreeForm1.Material.Texture.Image.LoadFromFile('avion512.jpg');
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: Double);
var
speed: Single;
begin
// handle keypresses
{ if IsKeyDown(VK_SHIFT) then
speed:=300*deltaTime
else } speed := 150 * deltaTime;
// with GLCamera1.Position do begin
DummyCube1.Translate(FreeForm1.direction.Z * speed, -FreeForm1.direction.Y *
speed, -FreeForm1.direction.X * speed);
if IsKeyDown(VK_UP) then
begin
FreeForm1.Pitch(1);
GLCamera1.Pitch(1);
// GLCamera1.MoveAroundTarget(-1, 0);
end;
if IsKeyDown(VK_DOWN) then
begin
FreeForm1.Pitch(-1);
GLCamera1.Pitch(-1);
// GLCamera1.MoveAroundTarget(1, 0);
end;
if IsKeyDown(VK_LEFT) then
begin
// DummyCube1.Translate(-X*speed, 0, -Z*speed);
// freeform1.Turn(-1);
FreeForm1.Roll(-1);
GLCamera1.Roll(1);
// GLCamera1.MoveAroundTarget(0, 1);
end;
if IsKeyDown(VK_RIGHT) then
begin
// DummyCube1.Translate(X*speed, 0, Z*speed);
// freeform1.Turn(1);
FreeForm1.Roll(1);
GLCamera1.Roll(-1);
// GLCamera1.MoveAroundTarget(0, -1);
end;
{ if IsKeyDown(VK_PRIOR) then
FCamHeight:=FCamHeight+10*speed;
if IsKeyDown(VK_NEXT) then
FCamHeight:=FCamHeight-10*speed; }
if IsKeyDown(VK_ESCAPE) then
Close;
// end;
// don't drop through terrain!
with DummyCube1.Position do
if Y < TerrainRenderer1.InterpolatedHeight(AsVector) then
Y := TerrainRenderer1.InterpolatedHeight(AsVector) + FCamHeight;
end;
// Standard mouse rotation & FPS code below
procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
mx := X;
my := Y;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
if ssLeft in Shift then
begin
// GLCamera1.MoveAroundTarget(my-y, mx-x);
mx := X;
my := Y;
end;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
GLSceneViewer1.ResetPerformanceMonitor;
end;
procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
begin
case Key of
'w', 'W':
with GLMaterialLibrary1.Materials[0].Material do
begin
if PolygonMode = pmLines then
PolygonMode := pmFill
else
PolygonMode := pmLines;
end;
'+':
if GLCamera1.DepthOfView < 2000 then
begin
GLCamera1.DepthOfView := GLCamera1.DepthOfView * 1.2;
with GLSceneViewer1.Buffer.FogEnvironment do
begin
FogEnd := FogEnd * 1.2;
FogStart := FogStart * 1.2;
end;
end;
'-':
if GLCamera1.DepthOfView > 300 then
begin
GLCamera1.DepthOfView := GLCamera1.DepthOfView / 1.2;
with GLSceneViewer1.Buffer.FogEnvironment do
begin
FogEnd := FogEnd / 1.2;
FogStart := FogStart / 1.2;
end;
end;
'*':
with TerrainRenderer1 do
if CLODPrecision > 20 then
CLODPrecision := Round(CLODPrecision * 0.8);
'/':
with TerrainRenderer1 do
if CLODPrecision < 1000 then
CLODPrecision := Round(CLODPrecision * 1.2);
'8':
with TerrainRenderer1 do
if QualityDistance > 40 then
QualityDistance := Round(QualityDistance * 0.8);
'9':
with TerrainRenderer1 do
if QualityDistance < 1000 then
QualityDistance := Round(QualityDistance * 1.2);
end;
Key := #0;
end;
end.
|
unit uDMQuickBooks;
interface
uses
SysUtils, Classes, ibqcore, ibqcustomer, Dialogs, Windows, ibqobjsearch,
ibqitem, Forms, Controls, ibqaccount, ibqinvoice, ibqsalesreceipt,
ibqreceivepayment, ibqemployee, ibqtimetracking, ibqcreditmemo;
const
CON_TYPE_DONT_CARE = 0;
CON_TYPE_SINGLE_USER = 1;
CON_TYPE_MULTI_USER = 2;
type
TQBBasic = class
end;
TQBLoader = class(TQBBasic)
private
FibqObjSearch: TibqObjSearch;
public
constructor Create(Conn : String);
destructor Destroy; override;
function ResultItems : String;
function ResultAccounts(AAccType : Integer) : String;
function ResultPaymentMethod : String;
function ResultPayroll : String;
procedure SetConnectionStr(Conn : String);
end;
TQBItem = class(TQBBasic)
private
ibqItem : TibqItem;
FItemType : TibqitemItemTypes;
FItemName : String;
FDesc : String;
FPrice : Currency;
FAccount : String;
FSalesTaxCode : String;
FQty : Double;
procedure SetItemType(const Value: TibqitemItemTypes);
public
constructor Create(con : String);
destructor Destroy; override;
property ItemName : String read FItemName write FItemName;
property Desc : String read FDesc write FDesc;
property ItemType : TibqitemItemTypes read FItemType write SetItemType;
property SalesTaxCode : String read FSalesTaxCode write FSalesTaxCode;
property Price : Currency read FPrice write FPrice;
property Qty : Double read FQty write FQty;
property Account : String read FAccount write FAccount;
procedure SetConnectionStr(Conn : String);
function InsertItem : Boolean;
function AddItem : Boolean;
function FindItem : Boolean;
end;
TQBCustomer = class(TQBBasic)
private
ibqCustomer: TibqCustomer;
FCity: String;
FCountry: String;
FAddress: String;
FContactName: String;
FPhone: String;
FFax: String;
FEmail: String;
FZip: String;
FCustomerName: String;
FState: String;
public
constructor Create(con : String);
destructor Destroy; override;
property CustomerName : String read FCustomerName write FCustomerName;
property Address : String read FAddress write FAddress;
property City : String read FCity write FCity;
property State : String read FState write FState;
property Zip : String read FZip write FZip;
property Country : String read FCountry write FCountry;
property ContactName : String read FContactName write FContactName;
property Email : String read FEmail write FEmail;
property Fax : String read FFax write FFax;
property Phone : String read FPhone write FPhone;
procedure SetConnectionStr(Conn : String);
function AddCustomer : Boolean;
function FindCustomer : Boolean;
end;
TQBEmployee = class(TQBBasic)
private
ibqEmployee : TibqEmployee;
FEmployee : String;
FPayroll: String;
public
constructor Create(con : String);
destructor Destroy; override;
property Employee : String read FEmployee write FEmployee;
property Payroll : String read FPayroll write FPayroll;
procedure SetConnectionStr(Conn : String);
function AddEmployee : Boolean;
function FindEmployee : Boolean;
end;
TQBPayment = class(TQBBasic)
private
ibqItem : TibqItem;
FAmount : Currency;
FRefNumber : String;
FTransactionDate : String;
FCustomerName : String;
FPaymentMethod : String;
FDefaulPayment: String;
public
constructor Create(con : String);
destructor Destroy; override;
property CustomerName : String read FCustomerName write FCustomerName;
property Amount : Currency read FAmount write FAmount;
property PaymentMethod : String read FPaymentMethod write FPaymentMethod;
property TransactionDate : String read FTransactionDate write FTransactionDate;
property RefNumber : String read FRefNumber write FRefNumber;
property DefaulPayment : String read FDefaulPayment write FDefaulPayment;
function InsertPayment : Boolean;
function AddPayment : Boolean;
function FindPayment : Boolean;
end;
TQBTimeClock = class(TQBBasic)
private
FQBEmployee : TQBEmployee;
ibqTimeTracking : TibqTimeTracking;
FEmployee : String;
FTransDate : String;
FDuration : String;
FPayroll : String;
FTransHour: String;
procedure SetEmployee(const Value: String);
procedure SetPayroll(const Value: String);
public
constructor Create(con : String);
destructor Destroy; override;
property Employee : String read FEmployee write SetEmployee;
property Duration : String read FDuration write FDuration;
property TransDate : String read FTransDate write FTransDate;
property TransHour : String read FTransHour write FTransHour;
property Payroll : String read FPayroll write SetPayroll;
procedure SetConnectionStr(Conn : String);
function AddTimeClock : Boolean;
function FindTimeClock : Boolean;
end;
TQBInvoice = class(TQBBasic)
private
FQBCustomer : TQBCustomer;
FItems : TStringList;
FPayments : TStringList;
FQBItems : TStringList;
FQBPayments : TStringList;
FTransactionDate : String;
FRefNumber : String;
FSalesTaxTotal: Currency;
FRefund: Currency;
FConn: String;
procedure SetCustomerName(const Value: String);
function GetCustomerName: String;
function GetAddress: String;
function GetCity: String;
function GetContactName: String;
function GetCountry: String;
function GetEmail: String;
function GetFax: String;
function GetPhone: String;
function GetState: String;
function GetZip: String;
procedure SetAddress(const Value: String);
procedure SetCity(const Value: String);
procedure SetContactName(const Value: String);
procedure SetCountry(const Value: String);
procedure SetEmail(const Value: String);
procedure SetFax(const Value: String);
procedure SetPhone(const Value: String);
procedure SetState(const Value: String);
procedure SetZip(const Value: String);
procedure FreeItemList;
procedure FreePaymentList;
procedure LoadQBItems;
procedure LoadQBPayments;
public
constructor Create(Con : String);
destructor Destroy; override;
property CustomerName : String read GetCustomerName write SetCustomerName;
property Address : String read GetAddress write SetAddress;
property City : String read GetCity write SetCity;
property State : String read GetState write SetState;
property Zip : String read GetZip write SetZip;
property Country : String read GetCountry write SetCountry;
property ContactName : String read GetContactName write SetContactName;
property Email : String read GetEmail write SetEmail;
property Fax : String read GetFax write SetFax;
property Phone : String read GetPhone write SetPhone;
property TransactionDate : String read FTransactionDate write FTransactionDate;
property RefNumber : String read FRefNumber write FRefNumber;
property SalesTaxTotal : Currency read FSalesTaxTotal write FSalesTaxTotal;
property Conn : String read FConn write FConn;
property Refund : Currency read FRefund write FRefund;
property SaleItems : TStringList read FItems write FItems;
property Payments : TStringList read FPayments write FPayments;
procedure SetConnectionStr(AConn : String); virtual;
end;
TQBSales = class(TQBInvoice)
private
ibqInvoice : TibqInvoice;
protected
function AddSaleItem(AQBItem : TQBItem; APos : Integer) : Boolean;
function AddPayment(AQBPayment : TQBPayment): Boolean;
public
constructor Create(Con : String);
destructor Destroy; override;
procedure SetConnectionStr(Conn : String); override;
procedure AppendPayment(AItemName, AAccount: String;
AAmount: Currency; AQty: Integer; AItemType : TibqitemItemTypes);
procedure CreateItemAdjust(ADesc, AAccount : String);
function Add : Boolean;
function Find : Boolean;
end;
TQBCreditMemo = class(TQBInvoice)
private
ibqCreditMemo : TibqCreditMemo;
protected
function AddSaleItem(AQBItem : TQBItem; APos : Integer) : Boolean;
public
constructor Create(Con : String);
destructor Destroy; override;
procedure SetConnectionStr(Conn : String); override;
procedure AppendCreditMemo(AItemName, AAccount: String;
AAmount: Currency; AQty: Integer; AItemType : TibqitemItemTypes);
function Add : Boolean;
function Find : Boolean;
end;
TDMQuickBooks = class(TDataModule)
ibqCustomer : TibqCustomer;
ibqObjSearch : TibqObjSearch;
ibqAccount : TibqAccount;
procedure DataModuleDestroy(Sender: TObject);
private
FConnectionMode : Integer;
FApplicationName : String;
FCompanyFile : String;
function FormatAccountType(AAccType : TibqaccountAccountTypes) : String;
public
function GetConnectionString : String;
function Connect : Boolean;
function GetAccountByType(AAccType : Integer) : String;
function GetPaymentMethod : String;
function GetPayrollList : String;
function AddHoursToDate(ADate : TDateTime; AHours : String) : TDateTime;
property ConnectionMode : Integer read FConnectionMode write FConnectionMode;
property ApplicationName : String read FApplicationName write FApplicationName;
property CompanyFile : String read FCompanyFile write FCompanyFile;
end;
implementation
uses uStringFunctions, uDateTimeFunctions, DateUtils;
{$R *.dfm}
{ TDMQuickBooks }
function TDMQuickBooks.Connect: Boolean;
begin
try
ibqCustomer.QBConnectionString := '';
ibqCustomer.QBConnectionString := GetConnectionString;
{
case ConnectionMode of
CON_TYPE_DONT_CARE : ibqCustomer.QBConnectionMode := cmDontCare;
CON_TYPE_SINGLE_USER : ibqCustomer.QBConnectionMode := cmSingleUserMode;
CON_TYPE_MULTI_USER : ibqCustomer.QBConnectionMode := cmMultiUserMode;
end;
}
ibqCustomer.OpenQBConnection;
Result := True;
except
on E : EibqCustomer do
begin
MessageDlg('Exception ' + E.Message, mtInformation, [mbOk], 0);
Result := False;
end;
end;
end;
function TDMQuickBooks.FormatAccountType(
AAccType: TibqaccountAccountTypes): String;
begin
case AAccType of
atUnspecified : Result := 'Unspecified';
atAccountsPayable : Result := 'Accounts Payable';
atAccountsReceivable : Result := 'Accounts Receivable';
atBank : Result := 'Bank';
atCostOfGoodsSold : Result := 'Cost Of Goods Sold';
atCreditCard : Result := 'CreditCard';
atEquity : Result := 'Equity';
atExpense : Result := 'Expense';
atFixedAsset : Result := 'Fixed Asset';
atIncome : Result := 'Income';
atLongTermLiability : Result := 'Long Term Liability';
atOtherAsset : Result := 'Other Asset';
atOtherCurrentAsset : Result := 'Other Current Asset';
atOtherCurrentLiability : Result := 'Other Current Liability';
atOtherExpense : Result := 'Other Expense';
atOtherIncome : Result := 'Other Income';
atNonPosting : Result := 'Non Posting';
end;
end;
function TDMQuickBooks.GetAccountByType(AAccType: Integer): String;
var
FList : TStringList;
i : Integer;
begin
ibqObjSearch.QueryType := qtAccountSearch;
ibqObjSearch.QBConnectionString := GetConnectionString;
FList := TStringList.Create;
try
Screen.Cursor := crHourGlass;
ibqObjSearch.Search();
for i := 0 to ibqObjSearch.ResultCount - 1 do
begin
ibqAccount.Reset();
ibqAccount.QBResponseAggregate := ibqObjSearch.ResultAggregate[i];
Flist.Add(IncSpaces(ibqAccount.AccountName, 35) + ' [' + FormatAccountType(ibqAccount.AccountType) + ']');
end;
Result := FList.Text;
finally
FreeAndNil(FList);
Screen.Cursor := crDefault;
end;
end;
function TDMQuickBooks.GetConnectionString: String;
begin
Result := '';
if FApplicationName <> '' then
Result := Result + 'ApplicationName= "' + FApplicationName + '"';
if FCompanyFile <> '' then
Result := Result + 'CompanyFile= "' + FCompanyFile + '"';
end;
function TDMQuickBooks.GetPaymentMethod: String;
var
FQBLoader : TQBLoader;
begin
FQBLoader := TQBLoader.Create(GetConnectionString);
try
Result := FQBLoader.ResultPaymentMethod;
finally
FreeAndNil(FQBLoader);
end;
end;
function TDMQuickBooks.GetPayrollList: String;
var
FQBLoader : TQBLoader;
begin
FQBLoader := TQBLoader.Create(GetConnectionString);
try
Result := FQBLoader.ResultPayroll;
finally
FreeAndNil(FQBLoader);
end;
end;
function TDMQuickBooks.AddHoursToDate(ADate: TDateTime;
AHours: String): TDateTime;
var
iHour, iMinute : Integer;
begin
iHour := StrToInt(Copy(AHours, 0, Pos(':',AHours)-1 ));
iMinute := StrToInt(Copy(AHours, Pos(':',AHours)+1, length(AHours) ));
ADate := AddHours(ADate, iHour);
ADate := AddMinutes(ADate, iMinute);
Result := ADate;
end;
{ TQBItem }
function TQBItem.AddItem: Boolean;
begin
Result := True;
if not FindItem then
Result := InsertItem;
end;
function TQBItem.FindItem: Boolean;
begin
try
ibqItem.GetByName(FItemName);
Result := True;
except
Result := False;
end;
end;
constructor TQBItem.Create(con : String);
begin
ibqItem := TibqItem.Create(nil);
ibqItem.ItemType := itNonInventory;
ibqItem.QBConnectionString := con;
end;
destructor TQBItem.Destroy;
begin
FreeAndNil(ibqItem);
inherited;
end;
procedure TQBItem.SetConnectionStr(Conn: String);
begin
ibqItem.QBConnectionString := Conn;
end;
procedure TQBItem.SetItemType(const Value: TibqitemItemTypes);
begin
FItemType := Value;
ibqItem.ItemType := FItemType;
end;
function TQBItem.InsertItem: Boolean;
begin
Result := True;
try
ibqItem.ItemName := FItemName;
ibqItem.Description := FDesc;
ibqItem.SalesTaxCodeId := FSalesTaxCode;
ibqItem.Price := 0;
ibqItem.AccountName := FAccount;
ibqItem.Add;
Result := True;
except
Result := False;
end;
end;
{ TQBCustomer }
function TQBCustomer.AddCustomer: Boolean;
begin
Result := True;
if (FCustomerName <> '') and (not FindCustomer) then
try
ibqCustomer.Reset;
ibqCustomer.CustomerName := FCustomerName;
ibqCustomer.ContactName := FContactName;
ibqCustomer.Phone := FPhone;
ibqCustomer.Fax := FFax;
ibqCustomer.Email := FEmail;
ibqCustomer.BillingAddress := '<Addr1>' + FAddress + '</Addr1>' +
'<City>' + FCity + '</City>' +
'<State>' + FState + '</State>' +
'<PostalCode>' + FZip + '</PostalCode>' +
'<Country>' + FCountry + '</Country>';
ibqCustomer.Add;
Result := True;
except
Result := False;
end;
end;
constructor TQBCustomer.Create(con : String);
begin
ibqCustomer := TibqCustomer.Create(nil);
ibqCustomer.QBConnectionString := con;
end;
destructor TQBCustomer.Destroy;
begin
FreeAndNil(ibqCustomer);
inherited;
end;
function TQBCustomer.FindCustomer: Boolean;
var
ibqObjSearch: TibqObjSearch;
begin
try
ibqObjSearch := TibqObjSearch.Create(nil);
try
ibqObjSearch.QueryType := qtCustomerSearch;
ibqObjSearch.NameStartsWith := FCustomerName;
ibqObjSearch.QBConnectionString := ibqCustomer.QBConnectionString;
ibqObjSearch.Search;
Result := (ibqObjSearch.ResultCount > 0);
finally
FreeAndNil(ibqObjSearch);
end;
except
Result := False;
end;
end;
procedure TQBCustomer.SetConnectionStr(Conn: String);
begin
ibqCustomer.QBConnectionString := Conn;
end;
{ TQBInvoice }
constructor TQBInvoice.Create(Con : String);
begin
FConn := Con;
FQBCustomer := TQBCustomer.Create(Con);
FItems := TStringList.Create;
FPayments := TStringList.Create;
FQBItems := TStringList.Create;
FQBPayments := TStringList.Create;
LoadQBItems;
LoadQBPayments;
end;
destructor TQBInvoice.Destroy;
begin
FreeAndNil(FQBCustomer);
FreeItemList;
FreeAndNil(FItems);
FreePaymentList;
FreeAndNil(FPayments);
FreeAndNil(FQBPayments);
FreeAndNil(FQBItems);
inherited;
end;
procedure TQBInvoice.FreeItemList;
var
Obj : TObject;
begin
while FItems.Count > 0 do
begin
Obj := FItems.Objects[0];
if Obj <> nil then
begin
FreeAndNil(Obj);
FItems.Objects[0] := nil;
end;
FItems.Delete(0);
end;
FItems.Clear;
end;
procedure TQBInvoice.FreePaymentList;
var
Obj : TObject;
begin
while FPayments.Count > 0 do
begin
Obj := FPayments.Objects[0];
if Obj <> nil then
begin
FreeAndNil(Obj);
FPayments.Objects[0] := nil;
end;
FPayments.Delete(0);
end;
FPayments.Clear;
end;
function TQBInvoice.GetAddress: String;
begin
Result := FQBCustomer.Address;
end;
function TQBInvoice.GetCity: String;
begin
Result := FQBCustomer.City;
end;
function TQBInvoice.GetContactName: String;
begin
Result := FQBCustomer.ContactName;
end;
function TQBInvoice.GetCountry: String;
begin
Result := FQBCustomer.Country;
end;
function TQBInvoice.GetCustomerName: String;
begin
Result := FQBCustomer.CustomerName;
end;
function TQBInvoice.GetEmail: String;
begin
Result := FQBCustomer.Email;
end;
function TQBInvoice.GetFax: String;
begin
Result := FQBCustomer.Fax;
end;
function TQBInvoice.GetPhone: String;
begin
Result := FQBCustomer.Phone;
end;
function TQBInvoice.GetState: String;
begin
Result := FQBCustomer.State;
end;
function TQBInvoice.GetZip: String;
begin
Result := FQBCustomer.Zip;
end;
procedure TQBInvoice.LoadQBItems;
var
FQBLoader : TQBLoader;
begin
FQBLoader := TQBLoader.Create(FConn);
try
FQBItems.Clear;
FQBLoader.SetConnectionStr(FConn);
FQBItems.Text := FQBLoader.ResultItems;
finally
FreeAndNil(FQBLoader);
end;
end;
procedure TQBInvoice.LoadQBPayments;
var
FQBLoader : TQBLoader;
begin
FQBLoader := TQBLoader.Create(FConn);
try
FQBPayments.Clear;
FQBLoader.SetConnectionStr(FConn);
FQBPayments.Text := FQBLoader.ResultPaymentMethod;
finally
FreeAndNil(FQBLoader);
end;
end;
procedure TQBInvoice.SetAddress(const Value: String);
begin
FQBCustomer.Address := Value;
end;
procedure TQBInvoice.SetCity(const Value: String);
begin
FQBCustomer.City := Value;
end;
procedure TQBInvoice.SetConnectionStr(AConn: String);
begin
FConn := AConn;
end;
procedure TQBInvoice.SetContactName(const Value: String);
begin
FQBCustomer.ContactName := Value;
end;
procedure TQBInvoice.SetCountry(const Value: String);
begin
FQBCustomer.Country := Value;
end;
procedure TQBInvoice.SetCustomerName(const Value: String);
begin
FQBCustomer.CustomerName := Value;
end;
procedure TQBInvoice.SetEmail(const Value: String);
begin
FQBCustomer.Email := Value;
end;
procedure TQBInvoice.SetFax(const Value: String);
begin
FQBCustomer.Fax := Value;
end;
procedure TQBInvoice.SetPhone(const Value: String);
begin
FQBCustomer.Phone := Value;
end;
procedure TQBInvoice.SetState(const Value: String);
begin
FQBCustomer.State := Value;
end;
procedure TQBInvoice.SetZip(const Value: String);
begin
FQBCustomer.Zip := Value;
end;
{ TQBLoader }
constructor TQBLoader.Create(Conn : String);
begin
FibqObjSearch := TibqObjSearch.Create(nil);
FibqObjSearch.QBConnectionString := Conn;
end;
destructor TQBLoader.Destroy;
begin
FreeAndNil(FibqObjSearch);
inherited;
end;
function TQBLoader.ResultAccounts(AAccType: Integer): String;
var
ibqAccount : TibqAccount;
FList : TStringList;
i : Integer;
begin
FibqObjSearch.QueryType := qtAccountSearch;
ibqAccount := TibqAccount.Create(nil);
try
FList := TStringList.Create;
try
Screen.Cursor := crHourGlass;
FibqObjSearch.Search();
for i := 0 to FibqObjSearch.ResultCount - 1 do
begin
ibqAccount.Reset();
ibqAccount.QBResponseAggregate := FibqObjSearch.ResultAggregate[i];
Flist.Add(ibqAccount.AccountName);
end;
Result := FList.Text;
finally
FreeAndNil(FList);
end;
finally
FreeAndNil(ibqAccount);
Screen.Cursor := crDefault;
end;
end;
function TQBLoader.ResultItems: String;
var
ibqItem: TibqItem;
FList : TStringList;
i : Integer;
begin
FibqObjSearch.QueryType := qtItemSearch;
ibqItem := TibqItem.Create(nil);
try
FList := TStringList.Create;
try
Screen.Cursor := crHourGlass;
FibqObjSearch.Search();
for i := 0 to FibqObjSearch.ResultCount - 1 do
begin
ibqItem.Reset();
ibqItem.QBResponseAggregate := FibqObjSearch.ResultAggregate[i];
FList.Add(ibqItem.Description);
end;
Result := FList.Text;
finally
FreeAndNil(FList);
end;
finally
FreeAndNil(ibqItem);
Screen.Cursor := crDefault;
end;
end;
function TQBLoader.ResultPaymentMethod: String;
var
FList : TStringList;
i : Integer;
sPayment : String;
begin
FibqObjSearch.QueryType := qtPaymentMethod;
try
FList := TStringList.Create;
try
Screen.Cursor := crHourGlass;
FibqObjSearch.Search();
for i := 0 to FibqObjSearch.ResultCount - 1 do
begin
sPayment := FibqObjSearch.ResultAggregate[i];
sPayment := Copy(sPayment, Pos('<Name>', sPayment) + 6, Length(sPayment));
sPayment := Copy(sPayment, 0, Pos('</Name>', sPayment)-1);
FList.Add(sPayment);
end;
Result := FList.Text;
finally
FreeAndNil(FList);
end;
finally
Screen.Cursor := crDefault;
end;
end;
function TQBLoader.ResultPayroll: String;
var
sResult : String;
FList : TStringList;
i : Integer;
begin
FibqObjSearch.QueryType := qtPayrollItemWage;
try
FList := TStringList.Create;
try
Screen.Cursor := crHourGlass;
FibqObjSearch.Search();
for i := 0 to FibqObjSearch.ResultCount - 1 do
begin
sResult := FibqObjSearch.ResultAggregate[i];
FList.Add(sResult);
end;
Result := FList.Text;
finally
FreeAndNil(FList);
end;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TQBLoader.SetConnectionStr(Conn: String);
begin
FibqObjSearch.QBConnectionString := Conn;
end;
procedure TDMQuickBooks.DataModuleDestroy(Sender: TObject);
begin
ibqCustomer.CloseQBConnection;
end;
{ TQBEmployee }
function TQBEmployee.AddEmployee: Boolean;
begin
Result := True;
if not FindEmployee then
try
ibqEmployee.Reset;
ibqEmployee.EmployeeName := FEmployee;
if FPayroll = '' then
begin
ibqEmployee.UseTimeDataToCreatePaychecks := tdDoNotUseTimeData;
end
else
begin
ibqEmployee.UseTimeDataToCreatePaychecks := tdUseTimeData;
ibqEmployee.PayrollClassName := FPayroll;
end;
ibqEmployee.Add;
Result := True;
except
Result := False;
end;
end;
constructor TQBEmployee.Create(con : String);
begin
ibqEmployee := TibqEmployee.Create(nil);
ibqEmployee.QBConnectionString := con;
end;
destructor TQBEmployee.Destroy;
begin
FreeAndNil(ibqEmployee);
inherited;
end;
function TQBEmployee.FindEmployee: Boolean;
var
ibqObjSearch: TibqObjSearch;
begin
try
ibqObjSearch := TibqObjSearch.Create(nil);
try
ibqObjSearch.Reset;
ibqObjSearch.QueryType := qtEmployeeSearch;
ibqObjSearch.NameStartsWith := FEmployee;
ibqObjSearch.NameEndsWith := FEmployee;
ibqObjSearch.QBConnectionString := ibqEmployee.QBConnectionString;
ibqObjSearch.Search;
Result := (ibqObjSearch.ResultCount > 0);
finally
FreeAndNil(ibqObjSearch);
end;
except
Result := False;
end;
end;
procedure TQBEmployee.SetConnectionStr(Conn: String);
begin
ibqEmployee.QBConnectionString := Conn;
end;
{ TQBTimeClock }
function TQBTimeClock.AddTimeClock: Boolean;
begin
if FQBEmployee.AddEmployee then
if not FindTimeClock then
begin
ibqTimeTracking.Reset;
ibqTimeTracking.EmployeeName := FEmployee;
ibqTimeTracking.TransactionDate := FTransDate;
ibqTimeTracking.Duration := FDuration;
ibqTimeTracking.IsBillable := False;
ibqTimeTracking.Add;
end;
Result := True;
end;
constructor TQBTimeClock.Create(con : String);
begin
ibqTimeTracking := TibqTimeTracking.Create(nil);
FQBEmployee := TQBEmployee.Create(con);
ibqTimeTracking.QBConnectionString := con;
end;
destructor TQBTimeClock.Destroy;
begin
FreeAndNil(FQBEmployee);
FreeAndNil(ibqTimeTracking);
inherited;
end;
function TQBTimeClock.FindTimeClock: Boolean;
var
ibqObjSearch: TibqObjSearch;
begin
try
ibqObjSearch := TibqObjSearch.Create(nil);
try
ibqObjSearch.Reset;
ibqObjSearch.QueryType := qtTimeTrackingSearch;
ibqObjSearch.TransactionDateStart := FTransDate;
ibqObjSearch.EntityName := FEmployee;
ibqObjSearch.QBConnectionString := ibqTimeTracking.QBConnectionString;
ibqObjSearch.Search;
Result := (ibqObjSearch.ResultCount > 0);
finally
FreeAndNil(ibqObjSearch);
end;
except
Result := False;
end;
end;
procedure TQBTimeClock.SetConnectionStr(Conn: String);
begin
ibqTimeTracking.QBConnectionString := Conn;
end;
procedure TQBTimeClock.SetEmployee(const Value: String);
begin
FEmployee := Value;
FQBEmployee.Employee := FEmployee;
end;
procedure TQBTimeClock.SetPayroll(const Value: String);
begin
FPayroll := Value;
FQBEmployee.Payroll := FPayroll;
end;
{ TQBPayment }
function TQBPayment.AddPayment: Boolean;
begin
Result := True;
if not FindPayment then
Result := InsertPayment;
end;
constructor TQBPayment.Create(con: String);
begin
ibqItem := TibqItem.Create(nil);
ibqItem.QBConnectionString := con;
ibqItem.ItemType := itPayment;
end;
destructor TQBPayment.Destroy;
begin
FreeAndNil(ibqItem);
inherited;
end;
function TQBPayment.FindPayment: Boolean;
begin
try
ibqItem.GetByName(FPaymentMethod);
Result := True;
except
Result := False;
end;
end;
function TQBPayment.InsertPayment: Boolean;
begin
Result := True;
try
ibqItem.ItemName := PaymentMethod;
ibqItem.Description := PaymentMethod;
ibqItem.Price := 0;
ibqItem.Add;
Result := True;
except
Result := False;
end;
end;
{ TQBSales }
function TQBSales.Add: Boolean;
var
i : Integer;
begin
try
if not Find then
if FQBCustomer.AddCustomer then
begin
ibqInvoice.Reset;
ibqInvoice.CustomerName := FQBCustomer.CustomerName;
ibqInvoice.TransactionDate := FTransactionDate;
ibqInvoice.RefNumber := FRefNumber;
ibqInvoice.ItemCount := FItems.Count;
for i := 0 to FItems.Count-1 do
if FItems.Objects[i] <> nil then
AddSaleItem(TQBItem(FItems.Objects[i]), i);
if (FItems.Count > 0) then
ibqInvoice.Add;
try
for i := 0 to FPayments.Count-1 do
if FPayments.Objects[i] <> nil then
AddPayment(TQBPayment(FPayments.Objects[i]));
finally
FreePaymentList;
end;
end;
finally
FreeItemList;
end;
Result := True;
end;
function TQBSales.AddPayment(AQBPayment: TQBPayment): Boolean;
var
Fibqreceivepayment : Tibqreceivepayment;
begin
Result := True;
try
if FQBPayments.IndexOf(AQBPayment.FPaymentMethod) = -1 then
begin
AQBPayment.FPaymentMethod := AQBPayment.DefaulPayment;
//AQBPayment.AddPayment;
//FQBPayments.Add(AQBPayment.FPaymentMethod);
end;
Fibqreceivepayment := Tibqreceivepayment.Create(nil);
try
Fibqreceivepayment.QBConnectionString := ibqInvoice.QBConnectionString;
Fibqreceivepayment.CustomerName := AQBPayment.CustomerName;
Fibqreceivepayment.RefNumber := AQBPayment.RefNumber;
Fibqreceivepayment.TransactionDate := AQBPayment.TransactionDate;
Fibqreceivepayment.PaymentMethodName := AQBPayment.PaymentMethod;
Fibqreceivepayment.Amount := Trunc(100 * AQBPayment.Amount);
Fibqreceivepayment.Add;
finally
FreeAndNil(Fibqreceivepayment);
end;
except
result := False;
end;
end;
function TQBSales.AddSaleItem(AQBItem: TQBItem; APos: Integer): Boolean;
begin
Result := True;
if (FQBItems.IndexOf(AQBItem.Desc) = -1) and (AQBItem.ItemType <> itPayment) then
begin
Result := AQBItem.AddItem;
FQBItems.Add(AQBItem.Desc);
end;
if Result then
begin
ibqInvoice.ItemName[APos] := AQBItem.Desc;
ibqInvoice.Config('Items['+IntToStr(APos)+'].Rate='+FormatFloat('0.00',AQBItem.Price));
//ibqInvoice.Config('Items['+IntToStr(APos)+'].Amount='+FormatFloat('0.00',AQBItem.Price));
//ibqInvoice.Config('Items['+IntToStr(APos)+'].Quantity='+FormatFloat('0.00',AQBItem.Qty));
end;
end;
procedure TQBSales.AppendPayment(AItemName, AAccount: String;
AAmount: Currency; AQty: Integer; AItemType : TibqitemItemTypes);
var
FQBItem : TQBItem;
begin
if SaleItems.IndexOf(AItemName) = -1 then
begin
FQBItem := TQBItem.Create(Conn);
FQBItem.ItemName := AItemName;
FQBItem.Desc := AItemName;
FQBItem.Price := AAmount;
FQBItem.Account := AAccount;
FQBItem.Qty := AQty;
FQBItem.ItemType := AItemType;
SaleItems.AddObject(AItemName, FQBItem);
end
else
begin
FQbItem := TQBItem(SaleItems.Objects[SaleItems.IndexOf(AItemName)]);
FQbItem.Price := FQbItem.Price + AAmount;
end;
end;
constructor TQBSales.Create(Con: String);
begin
inherited Create(Con);
ibqInvoice := TibqInvoice.Create(nil);
ibqInvoice.QBConnectionString := Con;
end;
procedure TQBSales.CreateItemAdjust(ADesc, AAccount : String);
var
FQBItem : TQBItem;
i : Integer;
cItemTotal, cPaymentTotal, cBalance : Currency;
begin
cItemTotal := 0;
cPaymentTotal := 0;
for i := 0 to SaleItems.Count - 1 do
begin
FQbItem := TQBItem(SaleItems.Objects[i]);
Case FQbItem.ItemType of
itNonInventory : cItemTotal := cItemTotal + FQbItem.Price;
itPayment : cPaymentTotal := cPaymentTotal + (FQbItem.Price * -1);
end;
end;
if cPaymentTotal > cItemTotal then
cBalance := ABS(cItemTotal - cPaymentTotal)
else
cBalance := ABS(cItemTotal - cPaymentTotal) * -1;
if (cBalance <> 0) then
AppendPayment(ADesc, AAccount, cBalance, 1, itNonInventory);
end;
destructor TQBSales.Destroy;
begin
FreeAndNil(ibqInvoice);
inherited;
end;
function TQBSales.Find: Boolean;
var
ibqObjSearch: TibqObjSearch;
begin
try
ibqObjSearch := TibqObjSearch.Create(nil);
try
ibqObjSearch.QueryType := qtInvoiceSearch;
ibqObjSearch.RefNumber := RefNumber;
ibqObjSearch.QBConnectionString := Conn;
ibqObjSearch.Search;
Result := (ibqObjSearch.ResultCount > 0);
finally
FreeAndNil(ibqObjSearch);
end;
except
Result := False;
end;
end;
procedure TQBSales.SetConnectionStr(Conn: String);
begin
inherited;
ibqInvoice.QBConnectionString := Conn;
end;
{ TQBCreditMemo }
function TQBCreditMemo.Add: Boolean;
var
i : Integer;
begin
try
if not Find then
if FQBCustomer.AddCustomer then
begin
ibqCreditMemo.Reset;
ibqCreditMemo.CustomerName := FQBCustomer.CustomerName;
ibqCreditMemo.TransactionDate := FTransactionDate;
ibqCreditMemo.RefNumber := FRefNumber;
ibqCreditMemo.ItemCount := FItems.Count;
for i := 0 to FItems.Count-1 do
if FItems.Objects[i] <> nil then
AddSaleItem(TQBItem(FItems.Objects[i]), i);
if FItems.Count > 0 then
ibqCreditMemo.Add;
end;
finally
FreeItemList;
end;
Result := True;
end;
function TQBCreditMemo.AddSaleItem(AQBItem: TQBItem;
APos: Integer): Boolean;
begin
Result := True;
if FQBItems.IndexOf(AQBItem.Desc) = -1 then
begin
Result := AQBItem.AddItem;
FQBItems.Add(AQBItem.Desc);
end;
if Result then
begin
ibqCreditMemo.ItemName[APos] := AQBItem.Desc;
ibqCreditMemo.Config('Items['+IntToStr(APos)+'].Rate='+FormatFloat('0.00', AQBItem.Price));
end;
end;
procedure TQBCreditMemo.AppendCreditMemo(AItemName, AAccount: String;
AAmount: Currency; AQty: Integer; AItemType: TibqitemItemTypes);
var
FQBItem : TQBItem;
begin
if SaleItems.IndexOf(AItemName) = -1 then
begin
FQBItem := TQBItem.Create(Conn);
FQBItem.ItemName := AItemName;
FQBItem.Desc := AItemName;
FQBItem.Price := AAmount;
FQBItem.Account := AAccount;
FQBItem.Qty := AQty;
FQBItem.ItemType := AItemType;
SaleItems.AddObject(AItemName, FQBItem);
end
else
begin
FQbItem := TQBItem(SaleItems.Objects[SaleItems.IndexOf(AItemName)]);
FQbItem.Price := FQbItem.Price + AAmount;
end;
end;
constructor TQBCreditMemo.Create(Con: String);
begin
inherited Create(Con);
ibqCreditMemo := TibqCreditMemo.Create(nil);
ibqCreditMemo.QBConnectionString := Con;
end;
destructor TQBCreditMemo.Destroy;
begin
FreeAndNil(ibqCreditMemo);
inherited;
end;
function TQBCreditMemo.Find: Boolean;
var
ibqObjSearch: TibqObjSearch;
begin
try
ibqObjSearch := TibqObjSearch.Create(nil);
try
ibqObjSearch.QueryType := qtCreditMemoSearch;
ibqObjSearch.RefNumber := RefNumber;
ibqObjSearch.QBConnectionString := Conn;
ibqObjSearch.Search;
Result := (ibqObjSearch.ResultCount > 0);
finally
FreeAndNil(ibqObjSearch);
end;
except
Result := False;
end;
end;
procedure TQBCreditMemo.SetConnectionStr(Conn: String);
begin
inherited;
ibqCreditMemo.QBConnectionString := Conn;
end;
end.
|
unit MeshNormalsTool;
interface
uses BasicMathsTypes, BasicDataTypes, Math3d, NeighborDetector, Math, Vector3fSet;
type
TMeshNormalsTool = class
private
function GetEquivalentVertex(_VertexID,_MaxVertexID: integer; const _VertexEquivalences: auint32): integer;
public
function GetNormalsValue(const _V1,_V2,_V3: TVector3f): TVector3f;
function GetQuadNormalValue(const _V1,_V2,_V3,_V4: TVector3f): TVector3f;
procedure GetVertexNormalsFromFaces(var _VertexNormals: TAVector3f; const _FaceNormals: TAVector3f; const _Vertices: TAVector3f; _NumVertices: integer; _NeighborDetector : TNeighborDetector; const _VertexEquivalences: auint32);
procedure GetFaceNormals(var _FaceNormals: TAVector3f; _VerticesPerFace : integer; const _Vertices: TAVector3f; const _Faces: auint32);
// Deprecated.
procedure SmoothVertexNormalsOperation(var _Normals: TAVector3f; const _Vertices: TAVector3f; _NumVertices: integer; const _Neighbors : TNeighborDetector; const _VertexEquivalences: auint32; _DistanceFunction: TDistanceFunc);
procedure SmoothFaceNormalsOperation(var _FaceNormals: TAVector3f; const _Vertices: TAVector3f; const _Neighbors : TNeighborDetector; _DistanceFunction: TDistanceFunc);
end;
implementation
function TMeshNormalsTool.GetEquivalentVertex(_VertexID,_MaxVertexID: integer; const _VertexEquivalences: auint32): integer;
begin
Result := _VertexID;
while Result > _MaxVertexID do
begin
Result := _VertexEquivalences[Result];
end;
end;
function TMeshNormalsTool.GetNormalsValue(const _V1,_V2,_V3: TVector3f): TVector3f;
begin
Result.X := (((_V3.Y - _V2.Y) * (_V1.Z - _V2.Z)) - ((_V1.Y - _V2.Y) * (_V3.Z - _V2.Z)));
Result.Y := (((_V3.Z - _V2.Z) * (_V1.X - _V2.X)) - ((_V1.Z - _V2.Z) * (_V3.X - _V2.X)));
Result.Z := (((_V3.X - _V2.X) * (_V1.Y - _V2.Y)) - ((_V1.X - _V2.X) * (_V3.Y - _V2.Y)));
Normalize(Result);
end;
function TMeshNormalsTool.GetQuadNormalValue(const _V1,_V2,_V3,_V4: TVector3f): TVector3f;
var
Temp : TVector3f;
begin
Result := GetNormalsValue(_V1,_V2,_V3);
Temp := GetNormalsValue(_V3,_V4,_V1);
Result.X := Result.X + Temp.X;
Result.Y := Result.Y + Temp.Y;
Result.Z := Result.Z + Temp.Z;
Normalize(Result);
end;
procedure TMeshNormalsTool.SmoothVertexNormalsOperation(var _Normals: TAVector3f; const _Vertices: TAVector3f; _NumVertices: integer; const _Neighbors : TNeighborDetector; const _VertexEquivalences: auint32; _DistanceFunction: TDistanceFunc);
var
i,Value : integer;
NormalsHandicap : TAVector3f;
Counter : integer;
Distance: single;
begin
// Setup Normals Handicap.
SetLength(NormalsHandicap,High(_Normals)+1);
for i := Low(NormalsHandicap) to High(NormalsHandicap) do
begin
NormalsHandicap[i].X := 0;
NormalsHandicap[i].Y := 0;
NormalsHandicap[i].Z := 0;
end;
// Main loop goes here.
for i := Low(_Vertices) to (_NumVertices - 1) do
begin
Counter := 0;
Value := _Neighbors.GetNeighborFromID(i); // Get vertex neighbor from vertex
while Value <> -1 do
begin
Distance := _Vertices[Value].X - _Vertices[i].X;
if Distance <> 0 then
NormalsHandicap[i].X := NormalsHandicap[i].X + (_Normals[Value].X * _DistanceFunction(Distance));
Distance := _Vertices[Value].Y - _Vertices[i].Y;
if Distance <> 0 then
NormalsHandicap[i].Y := NormalsHandicap[i].Y + (_Normals[Value].Y * _DistanceFunction(Distance));
Distance := _Vertices[Value].Z - _Vertices[i].Z;
if Distance <> 0 then
NormalsHandicap[i].Z := NormalsHandicap[i].Z + (_Normals[Value].Z * _DistanceFunction(Distance));
inc(Counter);
Value := _Neighbors.GetNextNeighbor;
end;
if Counter > 0 then
begin
_Normals[i].X := _Normals[i].X + (NormalsHandicap[i].X / Counter);
_Normals[i].Y := _Normals[i].Y + (NormalsHandicap[i].Y / Counter);
_Normals[i].Z := _Normals[i].Z + (NormalsHandicap[i].Z / Counter);
Normalize(_Normals[i]);
end;
end;
i := _NumVertices;
while i <= High(_Vertices) do
begin
Value := GetEquivalentVertex(i,_NumVertices,_VertexEquivalences);
_Normals[i].X := _Normals[Value].X;
_Normals[i].Y := _Normals[Value].Y;
_Normals[i].Z := _Normals[Value].Z;
inc(i);
end;
// Free memory
SetLength(NormalsHandicap,0);
end;
procedure TMeshNormalsTool.SmoothFaceNormalsOperation(var _FaceNormals: TAVector3f; const _Vertices: TAVector3f; const _Neighbors : TNeighborDetector; _DistanceFunction: TDistanceFunc);
var
i,Value : integer;
NormalsHandicap : TAVector3f;
Counter : single;
Distance: single;
begin
// Setup Normals Handicap.
SetLength(NormalsHandicap,High(_FaceNormals)+1);
for i := Low(NormalsHandicap) to High(NormalsHandicap) do
begin
NormalsHandicap[i].X := 0;
NormalsHandicap[i].Y := 0;
NormalsHandicap[i].Z := 0;
end;
// Main loop goes here.
for i := Low(NormalsHandicap) to High(NormalsHandicap) do
begin
Counter := 0;
Value := _Neighbors.GetNeighborFromID(i); // Get face neighbor from face (common edge)
while Value <> -1 do
begin
Distance := _Vertices[Value].X - _Vertices[i].X;
if Distance <> 0 then
NormalsHandicap[i].X := NormalsHandicap[i].X + (_FaceNormals[Value].X * _DistanceFunction(Distance));
Distance := _Vertices[Value].Y - _Vertices[i].Y;
if Distance <> 0 then
NormalsHandicap[i].Y := NormalsHandicap[i].Y + (_FaceNormals[Value].Y * _DistanceFunction(Distance));
Distance := _Vertices[Value].Z - _Vertices[i].Z;
if Distance <> 0 then
NormalsHandicap[i].Z := NormalsHandicap[i].Z + (_FaceNormals[Value].Z * _DistanceFunction(Distance));
Distance := sqrt(Power(_Vertices[Value].X - _Vertices[i].X,2) + Power(_Vertices[Value].Y - _Vertices[i].Y,2) + Power(_Vertices[Value].Z - _Vertices[i].Z,2));
Counter := Counter + Distance;
Value := _Neighbors.GetNextNeighbor;
end;
if Counter > 0 then
begin
_FaceNormals[i].X := _FaceNormals[i].X + (NormalsHandicap[i].X / Counter);
_FaceNormals[i].Y := _FaceNormals[i].Y + (NormalsHandicap[i].Y / Counter);
_FaceNormals[i].Z := _FaceNormals[i].Z + (NormalsHandicap[i].Z / Counter);
Normalize(_FaceNormals[i]);
end;
end;
// Free memory
SetLength(NormalsHandicap,0);
end;
procedure TMeshNormalsTool.GetVertexNormalsFromFaces(var _VertexNormals: TAVector3f; const _FaceNormals: TAVector3f; const _Vertices: TAVector3f; _NumVertices: integer; _NeighborDetector : TNeighborDetector; const _VertexEquivalences: auint32);
var
DifferentNormalsList: CVector3fSet;
v,Value : integer;
Normal : PVector3f;
begin
DifferentNormalsList := CVector3fSet.Create;
// Now, let's check each vertex.
for v := Low(_Vertices) to (_NumVertices - 1) do
begin
DifferentNormalsList.Reset;
_VertexNormals[v].X := 0;
_VertexNormals[v].Y := 0;
_VertexNormals[v].Z := 0;
Value := _NeighborDetector.GetNeighborFromID(v); // face neighbors from vertex
while Value <> -1 do
begin
Normal := new(PVector3f);
Normal^.X := _FaceNormals[Value].X;
Normal^.Y := _FaceNormals[Value].Y;
Normal^.Z := _FaceNormals[Value].Z;
if DifferentNormalsList.Add(Normal) then
begin
_VertexNormals[v].X := _VertexNormals[v].X + Normal^.X;
_VertexNormals[v].Y := _VertexNormals[v].Y + Normal^.Y;
_VertexNormals[v].Z := _VertexNormals[v].Z + Normal^.Z;
end;
Value := _NeighborDetector.GetNextNeighbor;
end;
if not DifferentNormalsList.isEmpty then
begin
Normalize(_VertexNormals[v]);
end;
end;
v := _NumVertices;
while v <= High(_Vertices) do
begin
Value := GetEquivalentVertex(v,_NumVertices,_VertexEquivalences);
_VertexNormals[v].X := _VertexNormals[Value].X;
_VertexNormals[v].Y := _VertexNormals[Value].Y;
_VertexNormals[v].Z := _VertexNormals[Value].Z;
inc(v);
end;
// Free memory
DifferentNormalsList.Free;
end;
procedure TMeshNormalsTool.GetFaceNormals(var _FaceNormals: TAVector3f; _VerticesPerFace : integer; const _Vertices: TAVector3f; const _Faces: auint32);
var
f,face : integer;
begin
if High(_FaceNormals) >= 0 then
begin
if _VerticesPerFace = 3 then
begin
face := 0;
for f := Low(_FaceNormals) to High(_FaceNormals) do
begin
_FaceNormals[f] := GetNormalsValue(_Vertices[_Faces[face]],_Vertices[_Faces[face+1]],_Vertices[_Faces[face+2]]);
inc(face,3);
end;
end
else if _VerticesPerFace = 4 then
begin
face := 0;
for f := Low(_FaceNormals) to High(_FaceNormals) do
begin
_FaceNormals[f] := GetQuadNormalValue(_Vertices[_Faces[face]],_Vertices[_Faces[face+1]],_Vertices[_Faces[face+2]],_Vertices[_Faces[face+3]]);
inc(face,4);
end;
end;
end;
end;
end.
|
unit uPortableDeviceUtils;
interface
uses
StrUtils,
Graphics,
Classes,
uPortableClasses,
uPortableDeviceManager,
uConstants,
uMemory,
uRAWImage;
type
TPortableGraphicHelper = class helper for TGraphic
public
function LoadFromDevice(Path: string): Boolean;
end;
function PhotoDBPathToDevicePath(Path: string): string;
function IsDevicePath(Path: string): Boolean;
function IsDeviceItemPath(Path: string): Boolean;
function ExtractDeviceName(Path: string): string;
function ExtractDeviceItemPath(Path: string): string;
function GetDeviceItemSize(Path: string): Int64;
function ReadStreamFromDevice(Path: string; Stream: TStream): Boolean;
implementation
function PhotoDBPathToDevicePath(Path: string): string;
begin
Result := Path;
if Length(Result) > Length(cDevicesPath) then
Delete(Result, 1, Length(cDevicesPath) + 1);
end;
function IsDevicePath(Path: string): Boolean;
begin
Result := StartsText(cDevicesPath + '\', Path);
end;
function IsDeviceItemPath(Path: string): Boolean;
begin
Result := False;
if StartsText(cDevicesPath + '\', Path) then
begin
Delete(Path, 1, Length(cDevicesPath + '\'));
Result := Pos('\', Path) > 0;
end;
end;
function ExtractDeviceName(Path: string): string;
var
P: Integer;
begin
Result := '';
if StartsText(cDevicesPath + '\', Path) then
begin
Delete(Path, 1, Length(cDevicesPath + '\'));
P := Pos('\', Path);
if P = 0 then
P := Length(Path) + 1;
Result := Copy(Path, 1, P - 1);
end;
end;
function ExtractDeviceItemPath(Path: string): string;
var
P: Integer;
begin
Result := '';
if StartsText(cDevicesPath + '\', Path) then
begin
Delete(Path, 1, Length(cDevicesPath + '\'));
P := Pos('\', Path);
if P > 1 then
Delete(Path, 1, P - 1);
Result := Path;
end;
end;
function ReadStreamFromDevice(Path: string; Stream: TStream): Boolean;
var
DeviceName, DevicePath: string;
Device: IPDevice;
Item: IPDItem;
begin
Result := False;
DeviceName := ExtractDeviceName(Path);
DevicePath := ExtractDeviceItemPath(Path);
Device := CreateDeviceManagerInstance.GetDeviceByName(DeviceName);
if Device = nil then
Exit;
Item := Device.GetItemByPath(DevicePath);
if Item = nil then
Exit;
Result := Item.SaveToStream(Stream);
end;
{ TPortableGraphicHelper }
function TPortableGraphicHelper.LoadFromDevice(Path: string): Boolean;
var
DeviceName, DevicePath: string;
Device: IPDevice;
Item: IPDItem;
MS: TMemoryStream;
begin
Result := False;
DeviceName := ExtractDeviceName(Path);
DevicePath := ExtractDeviceItemPath(Path);
Device := CreateDeviceManagerInstance.GetDeviceByName(DeviceName);
if Device = nil then
Exit;
Item := Device.GetItemByPath(DevicePath);
if Item = nil then
Exit;
if Self is TRAWImage then
TRAWImage(Self).IsPreview := True;
MS := TMemoryStream.Create;
try
Item.SaveToStream(MS);
if MS.Size > 0 then
begin
MS.Seek(0, soFromBeginning);
Self.LoadFromStream(MS);
end;
finally
F(MS);
end;
end;
function GetDeviceItemSize(Path: string): Int64;
var
DeviceName, DevicePath: string;
Device: IPDevice;
Item: IPDItem;
begin
Result := -1;
DeviceName := ExtractDeviceName(Path);
DevicePath := ExtractDeviceItemPath(Path);
Device := CreateDeviceManagerInstance.GetDeviceByName(DeviceName);
if Device <> nil then
begin
Item := Device.GetItemByPath(DevicePath);
if Item <> nil then
Result := Item.FullSize;
end;
end;
end.
|
unit Objekt.Ini;
interface
uses
SysUtils, Classes, variants, Objekt.Global;
type
TIni = class(TComponent)
private
function getVerzeichnis: string;
procedure setVerzeichnis(const Value: string);
function getSuchtext: string;
procedure setSuchtext(const Value: string);
function getErsetzen: string;
procedure setErsetzen(const Value: string);
function getMask: string;
procedure setMask(const Value: string);
function getGenaueSuche: Boolean;
procedure setGenaueSuche(const Value: Boolean);
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Verzeichnis: string read getVerzeichnis write setVerzeichnis;
property Suchtext: string read getSuchtext write setSuchtext;
property Ersetzen: string read getErsetzen write setErsetzen;
property Mask: string read getMask write setMask;
property GenaueSuche: Boolean read getGenaueSuche write setGenaueSuche;
end;
implementation
{ TIni }
uses
Allgemein.RegIni;
constructor TIni.Create(AOwner: TComponent);
begin
inherited;
end;
destructor TIni.Destroy;
begin
inherited;
end;
function TIni.getErsetzen: string;
begin
Result := ReadIni(Global.IniFilename, 'Einstellung', 'Ersetzen', '');
end;
function TIni.getGenaueSuche: Boolean;
begin
Result := ReadIni(Global.IniFilename, 'Einstellung', 'GenaueSuche', 'T') = 'T';
end;
function TIni.getMask: string;
begin
Result := ReadIni(Global.IniFilename, 'Einstellung', 'Mask', '');
end;
function TIni.getSuchtext: string;
begin
Result := ReadIni(Global.IniFilename, 'Einstellung', 'Suchtext', '');
end;
function TIni.getVerzeichnis: string;
begin
Result := ReadIni(Global.IniFilename, 'Einstellung', 'Verzeichnis', '');
end;
procedure TIni.setErsetzen(const Value: string);
begin
WriteIni(Global.IniFilename, 'Einstellung', 'Ersetzen', Value);
end;
procedure TIni.setGenaueSuche(const Value: Boolean);
begin
if Value then
WriteIni(Global.IniFilename, 'Einstellung', 'GenaueSuche', 'T')
else
WriteIni(Global.IniFilename, 'Einstellung', 'GenaueSuche', 'F');
end;
procedure TIni.setMask(const Value: string);
begin
WriteIni(Global.IniFilename, 'Einstellung', 'Mask', Value);
end;
procedure TIni.setSuchtext(const Value: string);
begin
WriteIni(Global.IniFilename, 'Einstellung', 'Suchtext', Value);
end;
procedure TIni.setVerzeichnis(const Value: string);
begin
WriteIni(Global.IniFilename, 'Einstellung', 'Verzeichnis', Value);
end;
end.
|
unit Экран;
{ Описание экрана программы как отдельного типа.
Немного облегчает работу по написанию программы }
interface
uses GraphABC;
type
тЭкран = class
private
_ширина: integer = 640;
_высота: integer = 480;
_назв: string = '"Font Creator 8x8"';
_текст: string = '';
procedure _Текст_Уст(текст: string);
begin
self._текст := текст;
Window.Title := self._назв + self._текст;
end;
function _Текст_Получ(): string;
begin
result := self._назв + self._текст;
end;
public
property ширина: integer read _ширина;
property высота: integer read _высота;
property текст: string read _Текст_Получ write _Текст_Уст;
property назв: string read _назв;
constructor Create;
begin
Window.Height := self._высота;
Window.Width := self._ширина;
Window.Title := self._Текст_Получ;
Window.Clear(clBlack);
Font.Name := 'Consolas';
Font.Size := 20;
Brush.Color := clBlue;
TextOut(100, 400, 'KBK Technika ltd. 2018 vers. 0.82');
end;
end;
implementation
end. |
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Handles all the material + material library stuff.
}
unit VXS.Material;
interface
{$I VXScene.inc}
uses
System.Classes,
System.SysUtils,
System.Types,
FMX.Dialogs,
FMX.Graphics,
VXS.OpenGL,
VXS.VectorTypes,
VXS.RenderContextInfo,
VXS.BaseClasses,
VXS.Context,
VXS.Texture,
VXS.Color,
VXS.Coordinates,
VXS.VectorGeometry,
VXS.PersistentClasses,
VXS.CrossPlatform,
VXS.State,
VXS.TextureFormat,
VXS.Strings,
VXS.ApplicationFileIO,
VXS.Graphics,
VXS.Utils,
VXS.XOpenGL;
{$UNDEF USE_MULTITHREAD}
type
TVXFaceProperties = class;
TVXMaterial = class;
TVXAbstractMaterialLibrary = class;
TVXMaterialLibrary = class;
// an interface for proper TVXLibMaterialNameProperty support
IVXMaterialLibrarySupported = interface(IInterface)
['{8E442AF9-D212-4A5E-8A88-92F798BABFD1}']
function GetMaterialLibrary: TVXAbstractMaterialLibrary;
end;
TVXAbstractLibMaterial = class;
TVXLibMaterial = class;
{ Define VXShader style application relatively to a material.
ssHighLevel: shader is applied before material application, and unapplied
after material unapplication
ssLowLevel: shader is applied after material application, and unapplied
before material unapplication
ssReplace: shader is applied in place of the material (and material
is completely ignored) }
TVXShaderStyle = (ssHighLevel, ssLowLevel, ssReplace);
{ Defines what to do if for some reason shader failed to initialize.
fiaSilentdisable: just disable it
fiaRaiseHandledException: raise an exception, and handle it right away
(usefull, when debigging within Delphi)
fiaRaiseStardardException: raises the exception with a string from this
function GetStardardNotSupportedMessage
fiaReRaiseException: Re-raises the exception
fiaGenerateEvent: Handles the exception, but generates an event
that user can respond to. For example, he can
try to compile a substitude shader, or replace
it by a material.
Note: HandleFailedInitialization does *not*
create this event, it is left to user shaders
which may chose to override this procedure.
Commented out, because not sure if this
option should exist, let other generations of
developers decide ;)
}
TVXShaderFailedInitAction = (fiaSilentDisable, fiaRaiseStandardException, fiaRaiseHandledException, fiaReRaiseException
{ ,fiaGenerateEvent } );
{ Generic, abstract shader class.
Shaders are modeled here as an abstract material-altering entity with
transaction-like behaviour. The base class provides basic context and user
tracking, as well as setup/application facilities.
Subclasses are expected to provide implementation for DoInitialize,
DoApply, DoUnApply and DoFinalize. }
TVXShader = class(TVXUpdateAbleComponent)
private
FEnabled: Boolean;
FLibMatUsers: TList;
FVirtualHandle: TVXVirtualHandle;
FShaderStyle: TVXShaderStyle;
FUpdateCount: Integer;
FShaderActive: Boolean;
FFailedInitAction: TVXShaderFailedInitAction;
protected
{ Invoked once, before the first call to DoApply.
The call happens with the OpenVX context being active. }
procedure DoInitialize(var rci: TVXRenderContextInfo; Sender: TObject); virtual;
{ Request to apply the shader.
Always followed by a DoUnApply when the shader is no longer needed. }
procedure DoApply(var rci: TVXRenderContextInfo; Sender: TObject); virtual; abstract;
{ Request to un-apply the shader.
Subclasses can assume the shader has been applied previously.
Return True to request a multipass. }
function DoUnApply(var rci: TVXRenderContextInfo): Boolean; virtual; abstract;
{ Invoked once, before the destruction of context or release of shader.
The call happens with the OpenVX context being active. }
procedure DoFinalize; virtual;
function GetShaderInitialized: Boolean;
procedure InitializeShader(var rci: TVXRenderContextInfo; Sender: TObject);
procedure FinalizeShader;
procedure OnVirtualHandleAllocate(Sender: TVXVirtualHandle; var handle: Cardinal);
procedure OnVirtualHandleDestroy(Sender: TVXVirtualHandle; var handle: Cardinal);
procedure SetEnabled(val: Boolean);
property ShaderInitialized: Boolean read GetShaderInitialized;
property ShaderActive: Boolean read FShaderActive;
procedure RegisterUser(libMat: TVXLibMaterial);
procedure UnRegisterUser(libMat: TVXLibMaterial);
{ Used by the DoInitialize procedure of descendant classes to raise errors. }
procedure HandleFailedInitialization(const LastErrorMessage: string = ''); virtual;
{ May be this should be a function inside HandleFailedInitialization... }
function GetStardardNotSupportedMessage: string; virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{ Subclasses should invoke this function when shader properties are altered.
This procedure can also be used to reset/recompile the shader. }
procedure NotifyChange(Sender: TObject); override;
procedure BeginUpdate;
procedure EndUpdate;
{ Apply shader to OpenGL state machine. }
procedure Apply(var rci: TVXRenderContextInfo; Sender: TObject);
{ UnApply shader.
When returning True, the caller is expected to perform a multipass
rendering by re-rendering then invoking UnApply again, until a
"False" is returned. }
function UnApply(var rci: TVXRenderContextInfo): Boolean;
{ Shader application style (default is ssLowLevel). }
property ShaderStyle: TVXShaderStyle read FShaderStyle write FShaderStyle default ssLowLevel;
procedure Assign(Source: TPersistent); override;
{ Defines if shader is supported by hardware/drivers.
Default - always supported. Descendants are encouraged to override
this function. }
function ShaderSupported: Boolean; virtual;
{ Defines what to do if for some reason shader failed to initialize.
Note, that in some cases it cannon be determined by just checking the
required OpenVX extentions. You need to try to compile and link the
shader - only at that stage you might catch an error }
property FailedInitAction: TVXShaderFailedInitAction read FFailedInitAction write FFailedInitAction
default fiaRaiseStandardException;
published
{ Turns on/off shader application.
Note that this only turns on/off the shader application, if the
ShaderStyle is ssReplace, the material won't be applied even if
the shader is disabled. }
property Enabled: Boolean read FEnabled write SetEnabled default True;
end;
TVXShaderClass = class of TVXShader;
TShininess = 0 .. 128;
{ Stores basic face lighting properties.
The lighting is described with the standard ambient/diffuse/emission/specular
properties that behave like those of most rendering tools.
You also have control over shininess (governs specular lighting) and
polygon mode (lines / fill). }
TVXFaceProperties = class(TVXUpdateAbleObject)
private
FAmbient, FDiffuse, FSpecular, FEmission: TVXColor;
FShininess: TShininess;
protected
procedure SetAmbient(AValue: TVXColor);
procedure SetDiffuse(AValue: TVXColor);
procedure SetEmission(AValue: TVXColor);
procedure SetSpecular(AValue: TVXColor);
procedure SetShininess(AValue: TShininess);
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Apply(var rci: TVXRenderContextInfo; AFace: TVXCullFaceMode);
procedure ApplyNoLighting(var rci: TVXRenderContextInfo; AFace: TVXCullFaceMode);
procedure Assign(Source: TPersistent); override;
published
property Ambient: TVXColor read FAmbient write SetAmbient;
property Diffuse: TVXColor read FDiffuse write SetDiffuse;
property Emission: TVXColor read FEmission write SetEmission;
property Shininess: TShininess read FShininess write SetShininess default 0;
property Specular: TVXColor read FSpecular write SetSpecular;
end;
TVXDepthProperties = class(TVXUpdateAbleObject)
private
FDepthTest: Boolean;
FDepthWrite: Boolean;
FZNear, FZFar: Single;
FCompareFunc: TVXDepthfunction;
FDepthClamp: Boolean;
protected
procedure SetZNear(Value: Single);
procedure SetZFar(Value: Single);
procedure SetCompareFunc(Value: TVXDepthCompareFunc);
procedure SetDepthTest(Value: Boolean);
procedure SetDepthWrite(Value: Boolean);
procedure SetDepthClamp(Value: Boolean);
function StoreZNear: Boolean;
function StoreZFar: Boolean;
public
constructor Create(AOwner: TPersistent); override;
procedure Apply(var rci: TVXRenderContextInfo);
procedure Assign(Source: TPersistent); override;
published
{ Specifies the mapping of the near clipping plane to
window coordinates. The initial value is 0. }
property ZNear: Single read FZNear write SetZNear stored StoreZNear;
{ Specifies the mapping of the far clipping plane to
window coordinates. The initial value is 1. }
property ZFar: Single read FZFar write SetZFar stored StoreZFar;
{ Specifies the function used to compare each
incoming pixel depth value with the depth value present in
the depth buffer. }
property DepthCompareFunction: TVXDepthfunction read FCompareFunc write SetCompareFunc default cfLequal;
{ DepthTest enabling.
When DepthTest is enabled, objects closer to the camera will hide
farther ones (via use of Z-Buffering).
When DepthTest is disabled, the latest objects drawn/rendered overlap
all previous objects, whatever their distance to the camera.
Even when DepthTest is enabled, objects may chose to ignore depth
testing through the osIgnoreDepthBuffer of their ObjectStyle property. }
property DepthTest: Boolean read FDepthTest write SetDepthTest default True;
{ If True, object will not write to Z-Buffer. }
property DepthWrite: Boolean read FDepthWrite write SetDepthWrite default False;
{ Enable clipping depth to the near and far planes }
property DepthClamp: Boolean read FDepthClamp write SetDepthClamp default False;
end;
TVXLibMaterialName = string;
(* If you write smth like af_GL_NEVER = GL_NEVER in the definition,
it won't show up in the Dephi 7 design-time editor. So I had to add
vTGlAlphaFuncValues and vTVXBlendFuncFactorValues arrays. *)
TGlAlphaFunc = TVXComparisonFunction;
TVXBlendingParameters = class(TVXUpdateAbleObject)
private
FUseAlphaFunc: Boolean;
FUseBlendFunc: Boolean;
FSeparateBlendFunc: Boolean;
FAlphaFuncType: TGlAlphaFunc;
FAlphaFuncRef: Single;
FBlendFuncSFactor: TVXBlendFunction;
FBlendFuncDFactor: TVXBlendFunction;
FAlphaBlendFuncSFactor: TVXBlendFunction;
FAlphaBlendFuncDFactor: TVXBlendFunction;
procedure SetUseAlphaFunc(const Value: Boolean);
procedure SetUseBlendFunc(const Value: Boolean);
procedure SetSeparateBlendFunc(const Value: Boolean);
procedure SetAlphaFuncRef(const Value: Single);
procedure SetAlphaFuncType(const Value: TGlAlphaFunc);
procedure SetBlendFuncDFactor(const Value: TVXBlendFunction);
procedure SetBlendFuncSFactor(const Value: TVXBlendFunction);
procedure SetAlphaBlendFuncDFactor(const Value: TVXBlendFunction);
procedure SetAlphaBlendFuncSFactor(const Value: TVXBlendFunction);
function StoreAlphaFuncRef: Boolean;
public
constructor Create(AOwner: TPersistent); override;
procedure Apply(var rci: TVXRenderContextInfo);
published
property UseAlphaFunc: Boolean read FUseAlphaFunc write SetUseAlphaFunc default False;
property AlphaFunctType: TGlAlphaFunc read FAlphaFuncType write SetAlphaFuncType default cfGreater;
property AlphaFuncRef: Single read FAlphaFuncRef write SetAlphaFuncRef stored StoreAlphaFuncRef;
property UseBlendFunc: Boolean read FUseBlendFunc write SetUseBlendFunc default True;
property SeparateBlendFunc: Boolean read FSeparateBlendFunc write SetSeparateBlendFunc default False;
property BlendFuncSFactor: TVXBlendFunction read FBlendFuncSFactor write SetBlendFuncSFactor default bfSrcAlpha;
property BlendFuncDFactor: TVXBlendFunction read FBlendFuncDFactor write SetBlendFuncDFactor default bfOneMinusSrcAlpha;
property AlphaBlendFuncSFactor: TVXBlendFunction read FAlphaBlendFuncSFactor write SetAlphaBlendFuncSFactor
default bfSrcAlpha;
property AlphaBlendFuncDFactor: TVXBlendFunction read FAlphaBlendFuncDFactor write SetAlphaBlendFuncDFactor
default bfOneMinusSrcAlpha;
end;
{ Simplified blending options.
bmOpaque : disable blending
bmTransparency : uses standard alpha blending
bmAdditive : activates additive blending (with saturation)
bmAlphaTest50 : uses opaque blending, with alpha-testing at 50% (full
transparency if alpha is below 0.5, full opacity otherwise)
bmAlphaTest100 : uses opaque blending, with alpha-testing at 100%
bmModulate : uses modulation blending
bmCustom : uses TVXBlendingParameters options }
TBlendingMode = (bmOpaque, bmTransparency, bmAdditive, bmAlphaTest50, bmAlphaTest100, bmModulate, bmCustom);
TFaceCulling = (fcBufferDefault, fcCull, fcNoCull);
{ Control special rendering options for a material.
moIgnoreFog : fog is deactivated when the material is rendered }
TMaterialOption = (moIgnoreFog, moNoLighting);
TMaterialOptions = set of TMaterialOption;
{ Describes a rendering material.
A material is basicly a set of face properties (front and back) that take
care of standard material rendering parameters (diffuse, ambient, emission
and specular) and texture mapping.
An instance of this class is available for almost all objects in GLScene
to allow quick definition of material properties. It can link to a
TVXLibMaterial (taken for a material library).
The TVXLibMaterial has more adavanced properties (like texture transforms)
and provides a standard way of sharing definitions and texture maps. }
TVXMaterial = class(TVXUpdateAbleObject, IVXMaterialLibrarySupported, IVXNotifyAble, IVXTextureNotifyAble)
private
FFrontProperties, FBackProperties: TVXFaceProperties;
FDepthProperties: TVXDepthProperties;
FBlendingMode: TBlendingMode;
FBlendingParams: TVXBlendingParameters;
FTexture: TVXTexture;
FTextureEx: TVXTextureEx;
FMaterialLibrary: TVXAbstractMaterialLibrary;
FLibMaterialName: TVXLibMaterialName;
FMaterialOptions: TMaterialOptions;
FFaceCulling: TFaceCulling;
FPolygonMode: TVXPolygonMode;
currentLibMaterial: TVXAbstractLibMaterial;
(* Implementing IVXMaterialLibrarySupported. *)
function GetMaterialLibrary: TVXAbstractMaterialLibrary;
protected
function GetBackProperties: TVXFaceProperties;
procedure SetBackProperties(Values: TVXFaceProperties);
procedure SetFrontProperties(Values: TVXFaceProperties);
procedure SetDepthProperties(Values: TVXDepthProperties);
procedure SetBlendingMode(const val: TBlendingMode);
procedure SetMaterialOptions(const val: TMaterialOptions);
function GetTexture: TVXTexture;
procedure SetTexture(ATexture: TVXTexture);
procedure SetMaterialLibrary(const val: TVXAbstractMaterialLibrary);
procedure SetLibMaterialName(const val: TVXLibMaterialName);
procedure SetFaceCulling(const val: TFaceCulling);
procedure SetPolygonMode(AValue: TVXPolygonMode);
function GetTextureEx: TVXTextureEx;
procedure SetTextureEx(const Value: TVXTextureEx);
function StoreTextureEx: Boolean;
procedure SetBlendingParams(const Value: TVXBlendingParameters);
procedure NotifyLibMaterialDestruction;
// Back, Front, Texture and blending not stored if linked to a LibMaterial
function StoreMaterialProps: Boolean;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure PrepareBuildList;
procedure Apply(var rci: TVXRenderContextInfo);
{ Restore non-standard material states that were altered;
A return value of True is a multipass request. }
function UnApply(var rci: TVXRenderContextInfo): Boolean;
procedure Assign(Source: TPersistent); override;
procedure NotifyChange(Sender: TObject); override;
procedure NotifyTexMapChange(Sender: TObject);
procedure DestroyHandles;
procedure Loaded;
{ Returns True if the material is blended.
Will return the libmaterial's blending if it is linked to a material library. }
function Blended: Boolean;
// True if the material has a secondary texture
function HasSecondaryTexture: Boolean;
// True if the material comes from the library instead of the texture property
function MaterialIsLinkedToLib: Boolean;
// Gets the primary texture either from material library or the texture property
function GetActualPrimaryTexture: TVXTexture;
// Gets the primary Material either from material library or the texture property
function GetActualPrimaryMaterial: TVXMaterial;
// Return the LibMaterial (see LibMaterialName)
function GetLibMaterial: TVXLibMaterial;
procedure QuickAssignMaterial(const MaterialLibrary: TVXMaterialLibrary; const Material: TVXLibMaterial);
published
property BackProperties: TVXFaceProperties read GetBackProperties write SetBackProperties stored StoreMaterialProps;
property FrontProperties: TVXFaceProperties read FFrontProperties write SetFrontProperties stored StoreMaterialProps;
property DepthProperties: TVXDepthProperties read FDepthProperties write SetDepthProperties stored StoreMaterialProps;
property BlendingMode: TBlendingMode read FBlendingMode write SetBlendingMode stored StoreMaterialProps default bmOpaque;
property BlendingParams: TVXBlendingParameters read FBlendingParams write SetBlendingParams;
property MaterialOptions: TMaterialOptions read FMaterialOptions write SetMaterialOptions default [];
property Texture: TVXTexture read GetTexture write SetTexture stored StoreMaterialProps;
property FaceCulling: TFaceCulling read FFaceCulling write SetFaceCulling default fcBufferDefault;
property MaterialLibrary: TVXAbstractMaterialLibrary read FMaterialLibrary write SetMaterialLibrary;
property LibMaterialName: TVXLibMaterialName read FLibMaterialName write SetLibMaterialName;
property TextureEx: TVXTextureEx read GetTextureEx write SetTextureEx stored StoreTextureEx;
property PolygonMode: TVXPolygonMode read FPolygonMode write SetPolygonMode default pmFill;
end;
TVXAbstractLibMaterial = class(TCollectionItem, IVXMaterialLibrarySupported, IVXNotifyAble)
protected
FUserList: TList;
FName: TVXLibMaterialName;
FNameHashKey: Integer;
FTag: Integer;
FNotifying: Boolean; // used for recursivity protection
// implementing IVXMaterialLibrarySupported
function GetMaterialLibrary: TVXAbstractMaterialLibrary;
// implementing IInterface
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
protected
function GetDisplayName: string; override;
class function ComputeNameHashKey(const name: string): Integer;
procedure SetName(const val: TVXLibMaterialName);
procedure Loaded; virtual; abstract;
public
constructor Create(ACollection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure Apply(var ARci: TVXRenderContextInfo); virtual; abstract;
// Restore non-standard material states that were altered
function UnApply(var ARci: TVXRenderContextInfo): Boolean; virtual; abstract;
procedure RegisterUser(Obj: TVXUpdateAbleObject); overload;
procedure UnRegisterUser(Obj: TVXUpdateAbleObject); overload;
procedure RegisterUser(comp: TVXUpdateAbleComponent); overload;
procedure UnRegisterUser(comp: TVXUpdateAbleComponent); overload;
procedure RegisterUser(libMaterial: TVXLibMaterial); overload;
procedure UnRegisterUser(libMaterial: TVXLibMaterial); overload;
procedure NotifyUsers;
function IsUsed: Boolean; // returns true if the texture has registed users
property NameHashKey: Integer read FNameHashKey;
procedure NotifyChange(Sender: TObject); virtual;
function Blended: Boolean; virtual;
property MaterialLibrary: TVXAbstractMaterialLibrary read GetMaterialLibrary;
published
property Name: TVXLibMaterialName read FName write SetName;
property Tag: Integer read FTag write FTag;
end;
{ Material in a material library.
Introduces Texture transformations (offset and scale). Those transformations
are available only for lib materials to minimize the memory cost of basic
materials (which are used in almost all objects). }
TVXLibMaterial = class(TVXAbstractLibMaterial, IVXTextureNotifyAble)
private
FMaterial: TVXMaterial;
FTextureOffset, FTextureScale: TVXCoordinates;
FTextureRotate: Single;
FTextureMatrixIsIdentity: Boolean;
FTextureOverride: Boolean;
FTextureMatrix: TMatrix;
FTexture2Name: TVXLibMaterialName;
FShader: TVXShader;
libMatTexture2: TVXLibMaterial; // internal cache
protected
procedure Loaded; override;
procedure SetMaterial(const val: TVXMaterial);
procedure SetTextureOffset(const val: TVXCoordinates);
procedure SetTextureScale(const val: TVXCoordinates);
procedure SetTextureMatrix(const Value: TMatrix);
procedure SetTexture2Name(const val: TVXLibMaterialName);
procedure SetShader(const val: TVXShader);
procedure SetTextureRotate(Value: Single);
function StoreTextureRotate: Boolean;
procedure CalculateTextureMatrix;
procedure DestroyHandles;
procedure DoOnTextureNeeded(Sender: TObject; var textureFileName: string);
procedure OnNotifyChange(Sender: TObject);
public
constructor Create(ACollection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure PrepareBuildList;
procedure Apply(var ARci: TVXRenderContextInfo); override;
// Restore non-standard material states that were altered
function UnApply(var ARci: TVXRenderContextInfo): Boolean; override;
procedure NotifyUsersOfTexMapChange;
property TextureMatrix: TMatrix read FTextureMatrix write SetTextureMatrix;
property TextureMatrixIsIdentity: Boolean read FTextureMatrixIsIdentity;
procedure NotifyTexMapChange(Sender: TObject);
function Blended: Boolean; override;
published
property Material: TVXMaterial read FMaterial write SetMaterial;
{ Texture offset in texture coordinates.
The offset is applied <i>after</i> scaling. }
property TextureOffset: TVXCoordinates read FTextureOffset write SetTextureOffset;
{ Texture coordinates scaling.
Scaling is applied <i>before</i> applying the offset, and is applied
to the texture coordinates, meaning that a scale factor of (2, 2, 2)
will make your texture look twice <i>smaller</i>. }
property TextureScale: TVXCoordinates read FTextureScale write SetTextureScale;
property TextureRotate: Single read FTextureRotate write SetTextureRotate stored StoreTextureRotate;
{ Reference to the second texture.
The referred LibMaterial *must* be in the same material library.
Second textures are supported only through ARB multitexturing (ignored
if not supported). }
property Texture2Name: TVXLibMaterialName read FTexture2Name write SetTexture2Name;
{ Optionnal shader for the material. }
property Shader: TVXShader read FShader write SetShader;
end;
TVXAbstractLibMaterials = class(TOwnedCollection)
protected
procedure Loaded;
function GetMaterial(const AName: TVXLibMaterialName): TVXAbstractLibMaterial; inline;
public
function MakeUniqueName(const nameRoot: TVXLibMaterialName): TVXLibMaterialName; virtual;
end;
{ A collection of materials, mainly used in material libraries. }
TVXLibMaterials = class(TVXAbstractLibMaterials)
protected
procedure SetItems(index: Integer; const val: TVXLibMaterial);
function GetItems(index: Integer): TVXLibMaterial;
procedure DestroyHandles;
public
constructor Create(AOwner: TComponent);
function Owner: TPersistent;
function IndexOf(const Item: TVXLibMaterial): Integer;
function Add: TVXLibMaterial;
function FindItemID(ID: Integer): TVXLibMaterial;
property Items[index: Integer]: TVXLibMaterial read GetItems write SetItems; default;
function GetLibMaterialByName(const AName: TVXLibMaterialName): TVXLibMaterial;
{ Returns index of this Texture if it exists. }
function GetTextureIndex(const Texture: TVXTexture): Integer;
{ Returns index of this Material if it exists. }
function GetMaterialIndex(const Material: TVXMaterial): Integer;
{ Returns name of this Texture if it exists. }
function GetNameOfTexture(const Texture: TVXTexture): TVXLibMaterialName;
{ Returns name of this Material if it exists. }
function GetNameOfLibMaterial(const Material: TVXLibMaterial): TVXLibMaterialName;
procedure PrepareBuildList;
{ Deletes all the unused materials in the collection.
A material is considered unused if no other material or updateable object references it.
WARNING: For this to work, objects that use the textuere, have to REGISTER to the texture. }
procedure DeleteUnusedMaterials;
end;
TVXAbstractMaterialLibrary = class(TVXCadenceAbleComponent)
protected
FMaterials: TVXAbstractLibMaterials;
FLastAppliedMaterial: TVXAbstractLibMaterial;
FTexturePaths: string;
FTexturePathList: TStringList;
procedure SetTexturePaths(const val: string);
property TexturePaths: string read FTexturePaths write SetTexturePaths;
procedure Loaded; override;
public
procedure SetNamesToTStrings(AStrings: TStrings);
{ Applies the material of given name.
Returns False if the material could not be found. ake sure this
call is balanced with a corresponding UnApplyMaterial (or an
assertion will be triggered in the destructor).
If a material is already applied, and has not yet been unapplied,
an assertion will be triggered. }
function ApplyMaterial(const AName: string; var ARci: TVXRenderContextInfo): Boolean; virtual;
{ Un-applies the last applied material.
Use this function in conjunction with ApplyMaterial.
If no material was applied, an assertion will be triggered. }
function UnApplyMaterial(var ARci: TVXRenderContextInfo): Boolean; virtual;
end;
{ Stores a set of materials, to be used and shared by scene objects.
Use a material libraries for storing commonly used materials, it provides
an efficient way to share texture and material data among many objects,
thus reducing memory needs and rendering time.
Materials in a material library also feature advanced control properties
like texture coordinates transforms. }
TVXMaterialLibrary = class(TVXAbstractMaterialLibrary)
private
FDoNotClearMaterialsOnLoad: Boolean;
FOnTextureNeeded: TVXTextureNeededEvent;
protected
function GetMaterials: TVXLibMaterials;
procedure SetMaterials(const val: TVXLibMaterials);
function StoreMaterials: Boolean;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure DestroyHandles;
procedure WriteToFiler(writer: TVirtualWriter);
procedure ReadFromFiler(reader: TVirtualReader);
procedure SaveToStream(aStream: TStream); virtual;
procedure LoadFromStream(aStream: TStream); virtual;
procedure AddMaterialsFromStream(aStream: TStream);
{ Save library content to a file.
Recommended extension : .GLML
Currently saves only texture, ambient, diffuse, emission
and specular colors. }
procedure SaveToFile(const fileName: string);
procedure LoadFromFile(const fileName: string);
procedure AddMaterialsFromFile(const fileName: string);
{ Add a "standard" texture material.
"standard" means linear texturing mode with mipmaps and texture
modulation mode with default-strength color components.
If persistent is True, the image will be loaded persistently in memory
(via a TVXPersistentImage), if false, it will be unloaded after upload
to OpenVX (via TVXPicFileImage). }
function AddTextureMaterial(const MaterialName, fileName: string; persistent: Boolean = True): TVXLibMaterial; overload;
{ Add a "standard" texture material.
TVXGraphic based variant. }
function AddTextureMaterial(const MaterialName: string; Graphic: TBitmap): TVXLibMaterial; overload;
{ Returns libMaterial of given name if any exists. }
function LibMaterialByName(const AName: TVXLibMaterialName): TVXLibMaterial;
{ Returns Texture of given material's name if any exists. }
function TextureByName(const LibMatName: TVXLibMaterialName): TVXTexture;
{ Returns name of texture if any exists. }
function GetNameOfTexture(const Texture: TVXTexture): TVXLibMaterialName;
{ Returns name of Material if any exists. }
function GetNameOfLibMaterial(const libMat: TVXLibMaterial): TVXLibMaterialName;
published
{ The materials collection. }
property Materials: TVXLibMaterials read GetMaterials write SetMaterials stored StoreMaterials;
{ This event is fired whenever a texture needs to be loaded from disk.
The event is triggered before even attempting to load the texture,
and before TexturePaths is used. }
property OnTextureNeeded: TVXTextureNeededEvent read FOnTextureNeeded write FOnTextureNeeded;
{ Paths to lookup when attempting to load a texture.
You can specify multiple paths when loading a texture, the separator
being the semi-colon ';' character. Directories are looked up from
first to last, the first file name match is used.
The current directory is always implicit and checked last.
Note that you can also use the OnTextureNeeded event to provide a
filename. }
property TexturePaths;
end;
// ------------------------------------------------------------------------------
implementation
// ------------------------------------------------------------------------------
// ------------------
// ------------------ TVXFaceProperties ------------------
// ------------------
constructor TVXFaceProperties.Create(AOwner: TPersistent);
begin
inherited;
// OpenVX default colors
FAmbient := TVXColor.CreateInitialized(Self, clrGray20);
FDiffuse := TVXColor.CreateInitialized(Self, clrGray80);
FEmission := TVXColor.Create(Self);
FSpecular := TVXColor.Create(Self);
FShininess := 0;
end;
destructor TVXFaceProperties.Destroy;
begin
FAmbient.Free;
FDiffuse.Free;
FEmission.Free;
FSpecular.Free;
inherited Destroy;
end;
procedure TVXFaceProperties.Apply(var rci: TVXRenderContextInfo; aFace: TVXCullFaceMode);
begin
with rci.VxStates do
begin
SetMaterialColors(aFace, Emission.Color, Ambient.Color, Diffuse.Color, Specular.Color, FShininess);
end;
end;
procedure TVXFaceProperties.ApplyNoLighting(var rci: TVXRenderContextInfo; aFace: TVXCullFaceMode);
begin
glColor4fv(Diffuse.AsAddress);
end;
procedure TVXFaceProperties.Assign(Source: TPersistent);
begin
if Assigned(Source) and (Source is TVXFaceProperties) then
begin
FAmbient.DirectColor := TVXFaceProperties(Source).Ambient.Color;
FDiffuse.DirectColor := TVXFaceProperties(Source).Diffuse.Color;
FEmission.DirectColor := TVXFaceProperties(Source).Emission.Color;
FSpecular.DirectColor := TVXFaceProperties(Source).Specular.Color;
FShininess := TVXFaceProperties(Source).Shininess;
NotifyChange(Self);
end;
end;
procedure TVXFaceProperties.SetAmbient(AValue: TVXColor);
begin
FAmbient.DirectColor := AValue.Color;
NotifyChange(Self);
end;
procedure TVXFaceProperties.SetDiffuse(AValue: TVXColor);
begin
FDiffuse.DirectColor := AValue.Color;
NotifyChange(Self);
end;
procedure TVXFaceProperties.SetEmission(AValue: TVXColor);
begin
FEmission.DirectColor := AValue.Color;
NotifyChange(Self);
end;
procedure TVXFaceProperties.SetSpecular(AValue: TVXColor);
begin
FSpecular.DirectColor := AValue.Color;
NotifyChange(Self);
end;
procedure TVXFaceProperties.SetShininess(AValue: TShininess);
begin
if FShininess <> AValue then
begin
FShininess := AValue;
NotifyChange(Self);
end;
end;
// ------------------
// ------------------ TVXDepthProperties ------------------
// ------------------
constructor TVXDepthProperties.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FDepthTest := True;
FDepthWrite := False;
FZNear := 0;
FZFar := 1;
FCompareFunc := cfLequal;
FDepthClamp := False;
end;
procedure TVXDepthProperties.Apply(var rci: TVXRenderContextInfo);
begin
with rci.VxStates do
begin
if FDepthTest and rci.bufferDepthTest then
Enable(stDepthTest)
else
Disable(stDepthTest);
DepthWriteMask := FDepthWrite;
DepthFunc := FCompareFunc;
SetDepthRange(FZNear, FZFar);
if FDepthClamp then
Enable(stDepthClamp)
else
Disable(stDepthClamp);
end;
end;
procedure TVXDepthProperties.Assign(Source: TPersistent);
begin
if Assigned(Source) and (Source is TVXDepthProperties) then
begin
FDepthTest := TVXDepthProperties(Source).FDepthTest;
FDepthWrite := TVXDepthProperties(Source).FDepthWrite;
FZNear := TVXDepthProperties(Source).FZNear;
FZFar := TVXDepthProperties(Source).FZFar;
FCompareFunc := TVXDepthProperties(Source).FCompareFunc;
NotifyChange(Self);
end;
end;
procedure TVXDepthProperties.SetZNear(Value: Single);
begin
Value := ClampValue(Value, 0, 1);
if Value <> FZNear then
begin
FZNear := Value;
NotifyChange(Self);
end;
end;
procedure TVXDepthProperties.SetZFar(Value: Single);
begin
Value := ClampValue(Value, 0, 1);
if Value <> FZFar then
begin
FZFar := Value;
NotifyChange(Self);
end;
end;
procedure TVXDepthProperties.SetCompareFunc(Value: TVXDepthfunction);
begin
if Value <> FCompareFunc then
begin
FCompareFunc := Value;
NotifyChange(Self);
end;
end;
procedure TVXDepthProperties.SetDepthTest(Value: Boolean);
begin
if Value <> FDepthTest then
begin
FDepthTest := Value;
NotifyChange(Self);
end;
end;
procedure TVXDepthProperties.SetDepthWrite(Value: Boolean);
begin
if Value <> FDepthWrite then
begin
FDepthWrite := Value;
NotifyChange(Self);
end;
end;
procedure TVXDepthProperties.SetDepthClamp(Value: Boolean);
begin
if Value <> FDepthClamp then
begin
FDepthClamp := Value;
NotifyChange(Self);
end;
end;
function TVXDepthProperties.StoreZNear: Boolean;
begin
Result := FZNear <> 0.0;
end;
function TVXDepthProperties.StoreZFar: Boolean;
begin
Result := FZFar <> 1.0;
end;
// ------------------
// ------------------ TVXShader ------------------
// ------------------
// Create
//
constructor TVXShader.Create(AOwner: TComponent);
begin
FLibMatUsers := TList.Create;
FVirtualHandle := TVXVirtualHandle.Create;
FVirtualHandle.OnAllocate := OnVirtualHandleAllocate;
FVirtualHandle.OnDestroy := OnVirtualHandleDestroy;
FShaderStyle := ssLowLevel;
FEnabled := True;
FFailedInitAction := fiaRaiseStandardException;
inherited;
end;
// Destroy
//
destructor TVXShader.Destroy;
var
i: Integer;
list: TList;
begin
FVirtualHandle.DestroyHandle;
FinalizeShader;
inherited;
list := FLibMatUsers;
FLibMatUsers := nil;
for i := list.Count - 1 downto 0 do
TVXLibMaterial(list[i]).Shader := nil;
list.Free;
FVirtualHandle.Free;
end;
// NotifyChange
//
procedure TVXShader.NotifyChange(Sender: TObject);
var
i: Integer;
begin
if FUpdateCount = 0 then
begin
for i := FLibMatUsers.Count - 1 downto 0 do
TVXLibMaterial(FLibMatUsers[i]).NotifyUsers;
FinalizeShader;
end;
end;
// BeginUpdate
//
procedure TVXShader.BeginUpdate;
begin
Inc(FUpdateCount);
end;
// EndUpdate
//
procedure TVXShader.EndUpdate;
begin
Dec(FUpdateCount);
if FUpdateCount = 0 then
NotifyChange(Self);
end;
// DoInitialize
//
procedure TVXShader.DoInitialize(var rci: TVXRenderContextInfo; Sender: TObject);
begin
// nothing here
end;
// DoFinalize
//
procedure TVXShader.DoFinalize;
begin
// nothing here
end;
// GetShaderInitialized
//
function TVXShader.GetShaderInitialized: Boolean;
begin
Result := (FVirtualHandle.handle <> 0);
end;
// InitializeShader
//
procedure TVXShader.InitializeShader(var rci: TVXRenderContextInfo; Sender: TObject);
begin
FVirtualHandle.AllocateHandle;
if FVirtualHandle.IsDataNeedUpdate then
begin
DoInitialize(rci, Sender);
FVirtualHandle.NotifyDataUpdated;
end;
end;
// FinalizeShader
//
procedure TVXShader.FinalizeShader;
begin
FVirtualHandle.NotifyChangesOfData;
DoFinalize;
end;
// Apply
//
procedure TVXShader.Apply(var rci: TVXRenderContextInfo; Sender: TObject);
begin
{$IFNDEF USE_MULTITHREAD}
Assert(not FShaderActive, 'Unbalanced shader application.');
{$ENDIF}
// Need to check it twice, because shader may refuse to initialize
// and choose to disable itself during initialization.
if FEnabled then
if FVirtualHandle.IsDataNeedUpdate then
InitializeShader(rci, Sender);
if FEnabled then
DoApply(rci, Sender);
FShaderActive := True;
end;
// UnApply
//
function TVXShader.UnApply(var rci: TVXRenderContextInfo): Boolean;
begin
{$IFNDEF USE_MULTITHREAD}
Assert(FShaderActive, 'Unbalanced shader application.');
{$ENDIF}
if Enabled then
begin
Result := DoUnApply(rci);
if not Result then
FShaderActive := False;
end
else
begin
FShaderActive := False;
Result := False;
end;
end;
// OnVirtualHandleDestroy
//
procedure TVXShader.OnVirtualHandleDestroy(Sender: TVXVirtualHandle; var handle: Cardinal);
begin
handle := 0;
end;
// OnVirtualHandleAllocate
//
procedure TVXShader.OnVirtualHandleAllocate(Sender: TVXVirtualHandle; var handle: Cardinal);
begin
handle := 1;
end;
// SetEnabled
//
procedure TVXShader.SetEnabled(val: Boolean);
begin
{$IFNDEF USE_MULTITHREAD}
Assert(not FShaderActive, 'Shader is active.');
{$ENDIF}
if val <> FEnabled then
begin
FEnabled := val;
NotifyChange(Self);
end;
end;
// RegisterUser
//
procedure TVXShader.RegisterUser(libMat: TVXLibMaterial);
var
i: Integer;
begin
i := FLibMatUsers.IndexOf(libMat);
if i < 0 then
FLibMatUsers.Add(libMat);
end;
// UnRegisterUser
//
procedure TVXShader.UnRegisterUser(libMat: TVXLibMaterial);
begin
if Assigned(FLibMatUsers) then
FLibMatUsers.Remove(libMat);
end;
// Assign
//
procedure TVXShader.Assign(Source: TPersistent);
begin
if Source is TVXShader then
begin
FShaderStyle := TVXShader(Source).FShaderStyle;
FFailedInitAction := TVXShader(Source).FFailedInitAction;
Enabled := TVXShader(Source).FEnabled;
end
else
inherited Assign(Source); // to the pit of doom ;)
end;
// Assign
//
function TVXShader.ShaderSupported: Boolean;
begin
Result := True;
end;
// HandleFailedInitialization
//
procedure TVXShader.HandleFailedInitialization(const LastErrorMessage: string = '');
begin
case FailedInitAction of
fiaSilentDisable:
; // Do nothing ;)
fiaRaiseHandledException:
try
raise EVXShaderException.Create(GetStardardNotSupportedMessage);
except
end;
fiaRaiseStandardException:
raise EVXShaderException.Create(GetStardardNotSupportedMessage);
fiaReRaiseException:
begin
if LastErrorMessage <> '' then
raise EVXShaderException.Create(LastErrorMessage)
else
raise EVXShaderException.Create(GetStardardNotSupportedMessage)
end;
// fiaGenerateEvent:; // Do nothing. Event creation is left up to user shaders
// // which may choose to override this procedure.
else
Assert(False, strErrorEx + strUnknownType);
end;
end;
// GetStardardNotSupportedMessage
//
function TVXShader.GetStardardNotSupportedMessage: string;
begin
if Name <> '' then
Result := 'Your hardware/driver doesn''t support shader "' + Name + '"!'
else
Result := 'Your hardware/driver doesn''t support shader "' + ClassName + '"!';
end;
// ----------------- TVXMaterial --------------------------------------------------
constructor TVXMaterial.Create(AOwner: TPersistent);
begin
inherited;
FFrontProperties := TVXFaceProperties.Create(Self);
FTexture := nil; // AutoCreate
FFaceCulling := fcBufferDefault;
FPolygonMode := pmFill;
FBlendingParams := TVXBlendingParameters.Create(Self);
FDepthProperties := TVXDepthProperties.Create(Self)
end;
destructor TVXMaterial.Destroy;
begin
if Assigned(currentLibMaterial) then
currentLibMaterial.UnRegisterUser(Self);
FBackProperties.Free;
FFrontProperties.Free;
FDepthProperties.Free;
FTexture.Free;
FTextureEx.Free;
FBlendingParams.Free;
inherited Destroy;
end;
function TVXMaterial.GetMaterialLibrary: TVXAbstractMaterialLibrary;
begin
Result := FMaterialLibrary;
end;
procedure TVXMaterial.SetBackProperties(Values: TVXFaceProperties);
begin
BackProperties.Assign(Values);
NotifyChange(Self);
end;
function TVXMaterial.GetBackProperties: TVXFaceProperties;
begin
if not Assigned(FBackProperties) then
FBackProperties := TVXFaceProperties.Create(Self);
Result := FBackProperties;
end;
procedure TVXMaterial.SetFrontProperties(Values: TVXFaceProperties);
begin
FFrontProperties.Assign(Values);
NotifyChange(Self);
end;
procedure TVXMaterial.SetDepthProperties(Values: TVXDepthProperties);
begin
FDepthProperties.Assign(Values);
NotifyChange(Self);
end;
procedure TVXMaterial.SetBlendingMode(const val: TBlendingMode);
begin
if val <> FBlendingMode then
begin
FBlendingMode := val;
NotifyChange(Self);
end;
end;
procedure TVXMaterial.SetMaterialOptions(const val: TMaterialOptions);
begin
if val <> FMaterialOptions then
begin
FMaterialOptions := val;
NotifyChange(Self);
end;
end;
function TVXMaterial.GetTexture: TVXTexture;
begin
if not Assigned(FTexture) then
FTexture := TVXTexture.Create(Self);
Result := FTexture;
end;
procedure TVXMaterial.SetTexture(ATexture: TVXTexture);
begin
if Assigned(ATexture) then
Texture.Assign(ATexture)
else
FreeAndNil(FTexture);
end;
procedure TVXMaterial.SetFaceCulling(const val: TFaceCulling);
begin
if val <> FFaceCulling then
begin
FFaceCulling := val;
NotifyChange(Self);
end;
end;
procedure TVXMaterial.SetMaterialLibrary(const val: TVXAbstractMaterialLibrary);
begin
FMaterialLibrary := val;
SetLibMaterialName(LibMaterialName);
end;
procedure TVXMaterial.SetLibMaterialName(const val: TVXLibMaterialName);
var
oldLibrary: TVXMaterialLibrary;
function MaterialLoopFrom(curMat: TVXLibMaterial): Boolean;
var
loopCount: Integer;
begin
loopCount := 0;
while Assigned(curMat) and (loopCount < 16) do
begin
with curMat.Material do
begin
if Assigned(oldLibrary) then
curMat := oldLibrary.Materials.GetLibMaterialByName(LibMaterialName)
else
curMat := nil;
end;
Inc(loopCount)
end;
Result := (loopCount >= 16);
end;
var
newLibMaterial: TVXAbstractLibMaterial;
begin
// locate new libmaterial
if Assigned(FMaterialLibrary) then
newLibMaterial := FMaterialLibrary.FMaterials.GetMaterial(val)
else
newLibMaterial := nil;
// make sure new won't trigger an infinite loop
if FMaterialLibrary is TVXMaterialLibrary then
begin
oldLibrary := TVXMaterialLibrary(FMaterialLibrary);
if MaterialLoopFrom(TVXLibMaterial(newLibMaterial)) then
begin
if IsDesignTime then
InformationDlg(Format(strCyclicRefMat, [val]))
else
ShowMessage(Format(strCyclicRefMat, [val]));
exit;
end;
end;
FLibMaterialName := val;
// unregister if required
if newLibMaterial <> currentLibMaterial then
begin
// unregister from old
if Assigned(currentLibMaterial) then
currentLibMaterial.UnRegisterUser(Self);
currentLibMaterial := newLibMaterial;
// register with new
if Assigned(currentLibMaterial) then
currentLibMaterial.RegisterUser(Self);
NotifyTexMapChange(Self);
end;
end;
function TVXMaterial.GetTextureEx: TVXTextureEx;
begin
if not Assigned(FTextureEx) then
FTextureEx := TVXTextureEx.Create(Self);
Result := FTextureEx;
end;
procedure TVXMaterial.SetTextureEx(const Value: TVXTextureEx);
begin
if Assigned(Value) or Assigned(FTextureEx) then
TextureEx.Assign(Value);
end;
function TVXMaterial.StoreTextureEx: Boolean;
begin
Result := (Assigned(FTextureEx) and (TextureEx.Count > 0));
end;
procedure TVXMaterial.SetBlendingParams(const Value: TVXBlendingParameters);
begin
FBlendingParams.Assign(Value);
NotifyChange(Self);
end;
procedure TVXMaterial.NotifyLibMaterialDestruction;
begin
FMaterialLibrary := nil;
FLibMaterialName := '';
currentLibMaterial := nil;
end;
procedure TVXMaterial.Loaded;
begin
inherited;
if Assigned(FTextureEx) then
TextureEx.Loaded;
end;
function TVXMaterial.StoreMaterialProps: Boolean;
begin
Result := not Assigned(currentLibMaterial);
end;
procedure TVXMaterial.PrepareBuildList;
begin
if Assigned(FTexture) and (not FTexture.Disabled) then
FTexture.PrepareBuildList;
end;
procedure TVXMaterial.Apply(var rci: TVXRenderContextInfo);
begin
if Assigned(currentLibMaterial) then
currentLibMaterial.Apply(rci)
else
with rci.VxStates do
begin
Disable(stColorMaterial);
PolygonMode := FPolygonMode;
if FPolygonMode = pmLines then
Disable(stLineStipple);
// Lighting switch
if (moNoLighting in MaterialOptions) or not rci.bufferLighting then
begin
Disable(stLighting);
FFrontProperties.ApplyNoLighting(rci, cmFront);
end
else
begin
Enable(stLighting);
FFrontProperties.Apply(rci, cmFront);
end;
// Apply FaceCulling and BackProperties (if needs be)
case FFaceCulling of
fcBufferDefault:
begin
if rci.bufferFaceCull then
Enable(stCullFace)
else
Disable(stCullFace);
BackProperties.Apply(rci, cmBack);
end;
fcCull:
Enable(stCullFace);
fcNoCull:
begin
Disable(stCullFace);
BackProperties.Apply(rci, cmBack);
end;
end;
// note: Front + Back with different PolygonMode are no longer supported.
// Currently state cache just ignores back facing mode changes, changes to
// front affect both front + back PolygonMode
// Apply Blending mode
if not rci.ignoreBlendingRequests then
case FBlendingMode of
bmOpaque:
begin
Disable(stBlend);
Disable(stAlphaTest);
end;
bmTransparency:
begin
Enable(stBlend);
Enable(stAlphaTest);
SetBlendFunc(bfSrcAlpha, bfOneMinusSrcAlpha);
SetAlphaFunction(cfGreater, 0);
end;
bmAdditive:
begin
Enable(stBlend);
Enable(stAlphaTest);
SetBlendFunc(bfSrcAlpha, bfOne);
SetAlphaFunction(cfGreater, 0);
end;
bmAlphaTest50:
begin
Disable(stBlend);
Enable(stAlphaTest);
SetAlphaFunction(cfGEqual, 0.5);
end;
bmAlphaTest100:
begin
Disable(stBlend);
Enable(stAlphaTest);
SetAlphaFunction(cfGEqual, 1.0);
end;
bmModulate:
begin
Enable(stBlend);
Enable(stAlphaTest);
SetBlendFunc(bfDstColor, bfZero);
SetAlphaFunction(cfGreater, 0);
end;
bmCustom:
begin
FBlendingParams.Apply(rci);
end;
end;
// Fog switch
if (moIgnoreFog in MaterialOptions) or not rci.bufferFog then
Disable(stFog)
else
Enable(stFog);
if not Assigned(FTextureEx) then
begin
if Assigned(FTexture) then
FTexture.Apply(rci)
end
else
begin
if Assigned(FTexture) and not FTextureEx.IsTextureEnabled(0) then
FTexture.Apply(rci)
else if FTextureEx.Count > 0 then
FTextureEx.Apply(rci);
end;
// Apply depth properties
if not rci.ignoreDepthRequests then
FDepthProperties.Apply(rci);
end;
end;
function TVXMaterial.UnApply(var rci: TVXRenderContextInfo): Boolean;
begin
if Assigned(currentLibMaterial) then
Result := currentLibMaterial.UnApply(rci)
else
begin
if Assigned(FTexture) and (not FTexture.Disabled) and (not FTextureEx.IsTextureEnabled(0)) then
FTexture.UnApply(rci)
else if Assigned(FTextureEx) then
FTextureEx.UnApply(rci);
Result := False;
end;
end;
procedure TVXMaterial.Assign(Source: TPersistent);
begin
if Assigned(Source) and (Source is TVXMaterial) then
begin
if Assigned(TVXMaterial(Source).FBackProperties) then
BackProperties.Assign(TVXMaterial(Source).BackProperties)
else
FreeAndNil(FBackProperties);
FFrontProperties.Assign(TVXMaterial(Source).FFrontProperties);
FPolygonMode := TVXMaterial(Source).FPolygonMode;
FBlendingMode := TVXMaterial(Source).FBlendingMode;
FMaterialOptions := TVXMaterial(Source).FMaterialOptions;
if Assigned(TVXMaterial(Source).FTexture) then
Texture.Assign(TVXMaterial(Source).FTexture)
else
FreeAndNil(FTexture);
FFaceCulling := TVXMaterial(Source).FFaceCulling;
FMaterialLibrary := TVXMaterial(Source).MaterialLibrary;
SetLibMaterialName(TVXMaterial(Source).LibMaterialName);
TextureEx.Assign(TVXMaterial(Source).TextureEx);
FDepthProperties.Assign(TVXMaterial(Source).DepthProperties);
NotifyChange(Self);
end
else
inherited;
end;
procedure TVXMaterial.NotifyChange(Sender: TObject);
var
intf: IVXNotifyAble;
begin
if Supports(Owner, IVXNotifyAble, intf) then
intf.NotifyChange(Self);
end;
procedure TVXMaterial.NotifyTexMapChange(Sender: TObject);
var
intf: IVXTextureNotifyAble;
begin
if Supports(Owner, IVXTextureNotifyAble, intf) then
intf.NotifyTexMapChange(Self)
else
NotifyChange(Self);
end;
procedure TVXMaterial.DestroyHandles;
begin
if Assigned(FTexture) then
FTexture.DestroyHandles;
end;
function TVXMaterial.Blended: Boolean;
begin
if Assigned(currentLibMaterial) then
begin
Result := currentLibMaterial.Blended
end
else
Result := not(BlendingMode in [bmOpaque, bmAlphaTest50, bmAlphaTest100, bmCustom]);
end;
function TVXMaterial.HasSecondaryTexture: Boolean;
begin
Result := Assigned(currentLibMaterial) and (currentLibMaterial is TVXLibMaterial) and
Assigned(TVXLibMaterial(currentLibMaterial).libMatTexture2);
end;
function TVXMaterial.MaterialIsLinkedToLib: Boolean;
begin
Result := Assigned(currentLibMaterial);
end;
function TVXMaterial.GetActualPrimaryTexture: TVXTexture;
begin
if Assigned(currentLibMaterial) and (currentLibMaterial is TVXLibMaterial) then
Result := TVXLibMaterial(currentLibMaterial).Material.Texture
else
Result := Texture;
end;
function TVXMaterial.GetActualPrimaryMaterial: TVXMaterial;
begin
if Assigned(currentLibMaterial) and (currentLibMaterial is TVXLibMaterial) then
Result := TVXLibMaterial(currentLibMaterial).Material
else
Result := Self;
end;
function TVXMaterial.GetLibMaterial: TVXLibMaterial;
begin
if Assigned(currentLibMaterial) and (currentLibMaterial is TVXLibMaterial) then
Result := TVXLibMaterial(currentLibMaterial)
else
Result := nil;
end;
procedure TVXMaterial.QuickAssignMaterial(const MaterialLibrary: TVXMaterialLibrary; const Material: TVXLibMaterial);
begin
FMaterialLibrary := MaterialLibrary;
FLibMaterialName := Material.FName;
if Material <> currentLibMaterial then
begin
// unregister from old
if Assigned(currentLibMaterial) then
currentLibMaterial.UnRegisterUser(Self);
currentLibMaterial := Material;
// register with new
if Assigned(currentLibMaterial) then
currentLibMaterial.RegisterUser(Self);
NotifyTexMapChange(Self);
end;
end;
procedure TVXMaterial.SetPolygonMode(AValue: TVXPolygonMode);
begin
if AValue <> FPolygonMode then
begin
FPolygonMode := AValue;
NotifyChange(Self);
end;
end;
// ------------------
// ------------------ TVXAbstractLibMaterial ------------------
// ------------------
constructor TVXAbstractLibMaterial.Create(ACollection: TCollection);
begin
inherited Create(ACollection);
FUserList := TList.Create;
if Assigned(ACollection) then
begin
FName := TVXAbstractLibMaterials(ACollection).MakeUniqueName('LibMaterial');
FNameHashKey := ComputeNameHashKey(FName);
end;
end;
destructor TVXAbstractLibMaterial.Destroy;
begin
FUserList.Free;
inherited Destroy;
end;
procedure TVXAbstractLibMaterial.Assign(Source: TPersistent);
begin
if Source is TVXAbstractLibMaterial then
begin
FName := TVXLibMaterials(Collection).MakeUniqueName(TVXLibMaterial(Source).name);
FNameHashKey := ComputeNameHashKey(FName);
end
else
inherited; // Raise AssignError
end;
function TVXAbstractLibMaterial.QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
begin
if GetInterface(IID, Obj) then
Result := S_OK
else
Result := E_NOINTERFACE;
end;
function TVXAbstractLibMaterial._AddRef: Integer; stdcall;
begin
Result := -1; // ignore
end;
function TVXAbstractLibMaterial._Release: Integer; stdcall;
begin
Result := -1; // ignore
end;
procedure TVXAbstractLibMaterial.RegisterUser(Obj: TVXUpdateAbleObject);
begin
Assert(FUserList.IndexOf(Obj) < 0);
FUserList.Add(Obj);
end;
procedure TVXAbstractLibMaterial.UnRegisterUser(Obj: TVXUpdateAbleObject);
begin
FUserList.Remove(Obj);
end;
procedure TVXAbstractLibMaterial.RegisterUser(comp: TVXUpdateAbleComponent);
begin
Assert(FUserList.IndexOf(comp) < 0);
FUserList.Add(comp);
end;
procedure TVXAbstractLibMaterial.UnRegisterUser(comp: TVXUpdateAbleComponent);
begin
FUserList.Remove(comp);
end;
procedure TVXAbstractLibMaterial.RegisterUser(libMaterial: TVXLibMaterial);
begin
Assert(FUserList.IndexOf(libMaterial) < 0);
FUserList.Add(libMaterial);
end;
procedure TVXAbstractLibMaterial.UnRegisterUser(libMaterial: TVXLibMaterial);
begin
FUserList.Remove(libMaterial);
end;
procedure TVXAbstractLibMaterial.NotifyChange(Sender: TObject);
begin
NotifyUsers();
end;
procedure TVXAbstractLibMaterial.NotifyUsers;
var
i: Integer;
Obj: TObject;
begin
if FNotifying then
exit;
FNotifying := True;
try
for i := 0 to FUserList.Count - 1 do
begin
Obj := TObject(FUserList[i]);
if Obj is TVXUpdateAbleObject then
TVXUpdateAbleObject(FUserList[i]).NotifyChange(Self)
else if Obj is TVXUpdateAbleComponent then
TVXUpdateAbleComponent(FUserList[i]).NotifyChange(Self)
else
begin
Assert(Obj is TVXAbstractLibMaterial);
TVXAbstractLibMaterial(FUserList[i]).NotifyUsers;
end;
end;
finally
FNotifying := False;
end;
end;
function TVXAbstractLibMaterial.IsUsed: Boolean;
begin
Result := Assigned(Self) and (FUserList.Count > 0);
end;
function TVXAbstractLibMaterial.GetDisplayName: string;
begin
Result := Name;
end;
function TVXAbstractLibMaterial.GetMaterialLibrary: TVXAbstractMaterialLibrary;
var
LOwner: TPersistent;
begin
Result := nil;
if Assigned(Collection) then
begin
LOwner := TVXAbstractLibMaterials(Collection).Owner;
if LOwner is TVXAbstractMaterialLibrary then
Result := TVXAbstractMaterialLibrary(LOwner);
end;
end;
function TVXAbstractLibMaterial.Blended: Boolean;
begin
Result := False;
end;
class function TVXAbstractLibMaterial.ComputeNameHashKey(const name: string): Integer;
var
i, n: Integer;
begin
n := Length(name);
Result := n;
for i := 1 to n do
Result := (Result shl 1) + Byte(name[i]);
end;
procedure TVXAbstractLibMaterial.SetName(const val: TVXLibMaterialName);
begin
if val <> FName then
begin
if not(csLoading in TComponent(Collection.Owner).ComponentState) then
begin
if TVXLibMaterials(Collection).GetLibMaterialByName(val) <> Self then
FName := TVXLibMaterials(Collection).MakeUniqueName(val)
else
FName := val;
end
else
FName := val;
FNameHashKey := ComputeNameHashKey(FName);
end;
end;
// ------------------
// ------------------ TVXLibMaterial ------------------
// ------------------
constructor TVXLibMaterial.Create(ACollection: TCollection);
begin
inherited Create(ACollection);
FMaterial := TVXMaterial.Create(Self);
FMaterial.Texture.OnTextureNeeded := DoOnTextureNeeded;
FTextureOffset := TVXCoordinates.CreateInitialized(Self, NullHmgVector, csPoint);
FTextureOffset.OnNotifyChange := OnNotifyChange;
FTextureScale := TVXCoordinates.CreateInitialized(Self, XYZHmgVector, csPoint);
FTextureScale.OnNotifyChange := OnNotifyChange;
FTextureRotate := 0;
FTextureOverride := False;
FTextureMatrixIsIdentity := True;
end;
destructor TVXLibMaterial.Destroy;
var
i: Integer;
matObj: TObject;
begin
Shader := nil; // drop dependency
Texture2Name := ''; // drop dependency
for i := 0 to FUserList.Count - 1 do
begin
matObj := TObject(FUserList[i]);
if matObj is TVXMaterial then
TVXMaterial(matObj).NotifyLibMaterialDestruction
else if matObj is TVXLibMaterial then
begin
TVXLibMaterial(matObj).libMatTexture2 := nil;
TVXLibMaterial(matObj).FTexture2Name := '';
end;
end;
FMaterial.Free;
FTextureOffset.Free;
FTextureScale.Free;
inherited;
end;
procedure TVXLibMaterial.Assign(Source: TPersistent);
begin
if Source is TVXLibMaterial then
begin
FMaterial.Assign(TVXLibMaterial(Source).Material);
FTextureOffset.Assign(TVXLibMaterial(Source).TextureOffset);
FTextureScale.Assign(TVXLibMaterial(Source).TextureScale);
FTextureRotate := TVXLibMaterial(Source).TextureRotate;
TextureMatrix := TVXLibMaterial(Source).TextureMatrix;
FTextureOverride := TVXLibMaterial(Source).FTextureOverride;
FTexture2Name := TVXLibMaterial(Source).Texture2Name;
FShader := TVXLibMaterial(Source).Shader;
end;
inherited;
end;
function TVXLibMaterial.Blended: Boolean;
begin
Result := Material.Blended;
end;
procedure TVXLibMaterial.PrepareBuildList;
begin
if Assigned(Self) then
Material.PrepareBuildList;
end;
procedure TVXLibMaterial.Apply(var ARci: TVXRenderContextInfo);
var
multitextured: Boolean;
begin
xglBeginUpdate;
if Assigned(FShader) then
begin
case Shader.ShaderStyle of
ssHighLevel:
Shader.Apply(ARci, Self);
ssReplace:
begin
Shader.Apply(ARci, Self);
exit;
end;
end;
end
else
ARci.VxStates.CurrentProgram := 0;
if (Texture2Name <> '') and (not vSecondTextureUnitForbidden) then
begin
if not Assigned(libMatTexture2) then
begin
libMatTexture2 := TVXLibMaterials(Collection).GetLibMaterialByName(Texture2Name);
if Assigned(libMatTexture2) then
libMatTexture2.RegisterUser(Self)
else
FTexture2Name := '';
end;
multitextured := Assigned(libMatTexture2) and (not libMatTexture2.Material.Texture.Disabled);
end
else
multitextured := False;
if not multitextured then
begin
// no multitexturing ("standard" mode)
if not FTextureMatrixIsIdentity then
ARci.VxStates.SetTextureMatrix(FTextureMatrix);
Material.Apply(ARci);
end
else
begin
// multitexturing is ON
if not FTextureMatrixIsIdentity then
ARci.VxStates.SetTextureMatrix(FTextureMatrix);
Material.Apply(ARci);
if not libMatTexture2.FTextureMatrixIsIdentity then
libMatTexture2.Material.Texture.ApplyAsTexture2(ARci, @libMatTexture2.FTextureMatrix.X.X)
else
libMatTexture2.Material.Texture.ApplyAsTexture2(ARci);
if (not Material.Texture.Disabled) and (Material.Texture.MappingMode = tmmUser) then
if libMatTexture2.Material.Texture.MappingMode = tmmUser then
xglMapTexCoordToDual
else
xglMapTexCoordToMain
else if libMatTexture2.Material.Texture.MappingMode = tmmUser then
xglMapTexCoordToSecond
else
xglMapTexCoordToMain;
end;
if Assigned(FShader) then
begin
case Shader.ShaderStyle of
ssLowLevel:
Shader.Apply(ARci, Self);
end;
end;
xglEndUpdate;
end;
function TVXLibMaterial.UnApply(var ARci: TVXRenderContextInfo): Boolean;
begin
Result := False;
if Assigned(FShader) then
begin
case Shader.ShaderStyle of
ssLowLevel:
Result := Shader.UnApply(ARci);
ssReplace:
begin
Result := Shader.UnApply(ARci);
exit;
end;
end;
end;
if not Result then
begin
if Assigned(libMatTexture2) and (not vSecondTextureUnitForbidden) then
begin
libMatTexture2.Material.Texture.UnApplyAsTexture2(ARci, (not libMatTexture2.TextureMatrixIsIdentity));
xglMapTexCoordToMain;
end;
Material.UnApply(ARci);
if not Material.Texture.Disabled then
if not FTextureMatrixIsIdentity then
ARci.VxStates.ResetTextureMatrix;
if Assigned(FShader) then
begin
case Shader.ShaderStyle of
ssHighLevel:
Result := Shader.UnApply(ARci);
end;
end;
end;
end;
procedure TVXLibMaterial.NotifyTexMapChange(Sender: TObject);
begin
NotifyUsersOfTexMapChange();
end;
procedure TVXLibMaterial.NotifyUsersOfTexMapChange;
var
i: Integer;
Obj: TObject;
begin
if FNotifying then
exit;
FNotifying := True;
try
for i := 0 to FUserList.Count - 1 do
begin
Obj := TObject(FUserList[i]);
if Obj is TVXMaterial then
TVXMaterial(FUserList[i]).NotifyTexMapChange(Self)
else if Obj is TVXLibMaterial then
TVXLibMaterial(FUserList[i]).NotifyUsersOfTexMapChange
else if Obj is TVXUpdateAbleObject then
TVXUpdateAbleObject(FUserList[i]).NotifyChange(Self)
else if Obj is TVXUpdateAbleComponent then
TVXUpdateAbleComponent(FUserList[i]).NotifyChange(Self);
end;
finally
FNotifying := False;
end;
end;
procedure TVXLibMaterial.Loaded;
begin
CalculateTextureMatrix;
Material.Loaded;
end;
procedure TVXLibMaterial.SetMaterial(const val: TVXMaterial);
begin
FMaterial.Assign(val);
end;
procedure TVXLibMaterial.SetTextureOffset(const val: TVXCoordinates);
begin
FTextureOffset.AsVector := val.AsVector;
CalculateTextureMatrix;
end;
procedure TVXLibMaterial.SetTextureScale(const val: TVXCoordinates);
begin
FTextureScale.AsVector := val.AsVector;
CalculateTextureMatrix;
end;
procedure TVXLibMaterial.SetTextureMatrix(const Value: TMatrix);
begin
FTextureMatrixIsIdentity := CompareMem(@Value.X, @IdentityHmgMatrix.X, SizeOf(TMatrix));
FTextureMatrix := Value;
FTextureOverride := True;
NotifyUsers;
end;
procedure TVXLibMaterial.SetTextureRotate(Value: Single);
begin
if Value <> FTextureRotate then
begin
FTextureRotate := Value;
CalculateTextureMatrix;
end;
end;
function TVXLibMaterial.StoreTextureRotate: Boolean;
begin
Result := Abs(FTextureRotate) > EPSILON;
end;
procedure TVXLibMaterial.SetTexture2Name(const val: TVXLibMaterialName);
begin
if val <> Texture2Name then
begin
if Assigned(libMatTexture2) then
begin
libMatTexture2.UnRegisterUser(Self);
libMatTexture2 := nil;
end;
FTexture2Name := val;
NotifyUsers;
end;
end;
procedure TVXLibMaterial.SetShader(const val: TVXShader);
begin
if val <> FShader then
begin
if Assigned(FShader) then
FShader.UnRegisterUser(Self);
FShader := val;
if Assigned(FShader) then
FShader.RegisterUser(Self);
NotifyUsers;
end;
end;
procedure TVXLibMaterial.CalculateTextureMatrix;
begin
if TextureOffset.Equals(NullHmgVector) and
TextureScale.Equals(XYZHmgVector) and
not StoreTextureRotate then
FTextureMatrixIsIdentity := True
else
begin
FTextureMatrixIsIdentity := False;
FTextureMatrix := CreateScaleAndTranslationMatrix(TextureScale.AsVector, TextureOffset.AsVector);
if StoreTextureRotate then
FTextureMatrix := MatrixMultiply(FTextureMatrix, CreateRotationMatrixZ(DegToRadian(FTextureRotate)));
end;
FTextureOverride := False;
NotifyUsers;
end;
procedure TVXLibMaterial.DestroyHandles;
var
libMat: TVXLibMaterial;
begin
FMaterial.DestroyHandles;
if FTexture2Name <> '' then
begin
libMat := TVXLibMaterials(Collection).GetLibMaterialByName(Texture2Name);
if Assigned(libMat) then
libMat.DestroyHandles;
end;
end;
procedure TVXLibMaterial.OnNotifyChange(Sender: TObject);
begin
CalculateTextureMatrix;
end;
procedure TVXLibMaterial.DoOnTextureNeeded(Sender: TObject; var textureFileName: string);
var
mLib: TVXMaterialLibrary;
i: Integer;
tryName: string;
begin
if not Assigned(Collection) then
exit;
mLib := TVXMaterialLibrary((Collection as TVXLibMaterials).GetOwner);
with mLib do
if Assigned(FOnTextureNeeded) then
FOnTextureNeeded(mLib, textureFileName);
// if a ':' is present, or if it starts with a '\', consider it as an absolute path
if (Pos(':', textureFileName) > 0) or (Copy(textureFileName, 1, 1) = PathDelim) then
exit;
// ok, not an absolute path, try given paths
with mLib do
begin
if FTexturePathList <> nil then
for i := 0 to FTexturePathList.Count - 1 do
begin
tryName := IncludeTrailingPathDelimiter(FTexturePathList[i]) + textureFileName;
if (Assigned(vAFIOCreateFileStream) and FileStreamExists(tryName)) or FileExists(tryName) then
begin
textureFileName := tryName;
Break;
end;
end;
end;
end;
// ------------------
// ------------------ TVXLibMaterials ------------------
// ------------------
function TVXAbstractLibMaterials.GetMaterial(const AName: TVXLibMaterialName): TVXAbstractLibMaterial;
var
i, hk: Integer;
lm: TVXAbstractLibMaterial;
begin
hk := TVXAbstractLibMaterial.ComputeNameHashKey(AName);
for i := 0 to Count - 1 do
begin
lm := TVXAbstractLibMaterial(inherited Items[i]);
if (lm.NameHashKey = hk) and (lm.name = AName) then
begin
Result := lm;
exit;
end;
end;
Result := nil;
end;
procedure TVXAbstractLibMaterials.Loaded;
var
i: Integer;
begin
for i := Count - 1 downto 0 do
TVXAbstractLibMaterial(Items[i]).Loaded;
end;
function TVXAbstractLibMaterials.MakeUniqueName(const nameRoot: TVXLibMaterialName): TVXLibMaterialName;
var
i: Integer;
begin
Result := nameRoot;
i := 1;
while GetMaterial(Result) <> nil do
begin
Result := nameRoot + IntToStr(i);
Inc(i);
end;
end;
constructor TVXLibMaterials.Create(AOwner: TComponent);
begin
inherited Create(AOwner, TVXLibMaterial);
end;
procedure TVXLibMaterials.SetItems(index: Integer; const val: TVXLibMaterial);
begin
inherited Items[index] := val;
end;
function TVXLibMaterials.GetItems(index: Integer): TVXLibMaterial;
begin
Result := TVXLibMaterial(inherited Items[index]);
end;
procedure TVXLibMaterials.DestroyHandles;
var
i: Integer;
begin
for i := 0 to Count - 1 do
Items[i].DestroyHandles;
end;
function TVXLibMaterials.Owner: TPersistent;
begin
Result := GetOwner;
end;
function TVXLibMaterials.Add: TVXLibMaterial;
begin
Result := (inherited Add) as TVXLibMaterial;
end;
function TVXLibMaterials.FindItemID(ID: Integer): TVXLibMaterial;
begin
Result := (inherited FindItemID(ID)) as TVXLibMaterial;
end;
function TVXLibMaterials.GetLibMaterialByName(const AName: TVXLibMaterialName): TVXLibMaterial;
var
LMaterial: TVXAbstractLibMaterial;
begin
LMaterial := GetMaterial(AName);
if Assigned(LMaterial) and (LMaterial is TVXLibMaterial) then
Result := TVXLibMaterial(LMaterial)
else
Result := nil;
end;
function TVXLibMaterials.GetTextureIndex(const Texture: TVXTexture): Integer;
var
i: Integer;
begin
if Count <> 0 then
for i := 0 to Count - 1 do
if GetItems(i).Material.Texture = Texture then
begin
Result := i;
exit;
end;
Result := -1;
end;
function TVXLibMaterials.GetMaterialIndex(const Material: TVXMaterial): Integer;
var
i: Integer;
begin
if Count <> 0 then
for i := 0 to Count - 1 do
if GetItems(i).Material = Material then
begin
Result := i;
exit;
end;
Result := -1;
end;
function TVXLibMaterials.GetNameOfTexture(const Texture: TVXTexture): TVXLibMaterialName;
var
MatIndex: Integer;
begin
MatIndex := GetTextureIndex(Texture);
if MatIndex <> -1 then
Result := GetItems(MatIndex).name
else
Result := '';
end;
function TVXLibMaterials.GetNameOfLibMaterial(const Material: TVXLibMaterial): TVXLibMaterialName;
var
MatIndex: Integer;
begin
MatIndex := IndexOf(Material);
if MatIndex <> -1 then
Result := GetItems(MatIndex).name
else
Result := '';
end;
function TVXLibMaterials.IndexOf(const Item: TVXLibMaterial): Integer;
var
i: Integer;
begin
Result := -1;
if Count <> 0 then
for i := 0 to Count - 1 do
if GetItems(i) = Item then
begin
Result := i;
exit;
end;
end;
procedure TVXLibMaterials.PrepareBuildList;
var
i: Integer;
begin
for i := 0 to Count - 1 do
TVXLibMaterial(inherited Items[i]).PrepareBuildList;
end;
procedure TVXLibMaterials.DeleteUnusedMaterials;
var
i: Integer;
gotNone: Boolean;
begin
BeginUpdate;
repeat
gotNone := True;
for i := Count - 1 downto 0 do
begin
if TVXLibMaterial(inherited Items[i]).FUserList.Count = 0 then
begin
TVXLibMaterial(inherited Items[i]).Free;
gotNone := False;
end;
end;
until gotNone;
EndUpdate;
end;
procedure TVXAbstractMaterialLibrary.SetTexturePaths(const val: string);
var
i, lp: Integer;
procedure AddCurrent;
var
buf: string;
begin
buf := Trim(Copy(val, lp + 1, i - lp - 1));
if Length(buf) > 0 then
begin
// make sure '\' is the terminator
buf := IncludeTrailingPathDelimiter(buf);
FTexturePathList.Add(buf);
end;
end;
begin
FTexturePathList.Free;
FTexturePathList := nil;
FTexturePaths := val;
if val <> '' then
begin
FTexturePathList := TStringList.Create;
lp := 0;
for i := 1 to Length(val) do
begin
if val[i] = ';' then
begin
AddCurrent;
lp := i;
end;
end;
i := Length(val) + 1;
AddCurrent;
end;
end;
function TVXAbstractMaterialLibrary.ApplyMaterial(const AName: string; var ARci: TVXRenderContextInfo): Boolean;
begin
FLastAppliedMaterial := FMaterials.GetMaterial(AName);
Result := Assigned(FLastAppliedMaterial);
if Result then
FLastAppliedMaterial.Apply(ARci);
end;
function TVXAbstractMaterialLibrary.UnApplyMaterial(var ARci: TVXRenderContextInfo): Boolean;
begin
if Assigned(FLastAppliedMaterial) then
begin
Result := FLastAppliedMaterial.UnApply(ARci);
if not Result then
FLastAppliedMaterial := nil;
end
else
Result := False;
end;
procedure TVXAbstractMaterialLibrary.SetNamesToTStrings(AStrings: TStrings);
var
i: Integer;
lm: TVXAbstractLibMaterial;
begin
with AStrings do
begin
BeginUpdate;
Clear;
for i := 0 to FMaterials.Count - 1 do
begin
lm := TVXAbstractLibMaterial(FMaterials.Items[i]);
AddObject(lm.name, lm);
end;
EndUpdate;
end;
end;
procedure TVXAbstractMaterialLibrary.Loaded;
begin
inherited;
FMaterials.Loaded;
end;
// ------------------
// ------------------ TVXMaterialLibrary ------------------
// ------------------
constructor TVXMaterialLibrary.Create(AOwner: TComponent);
begin
inherited;
FMaterials := TVXLibMaterials.Create(Self);
end;
destructor TVXMaterialLibrary.Destroy;
begin
Assert(FLastAppliedMaterial = nil, 'Unbalanced material application');
FTexturePathList.Free;
FMaterials.Free;
FMaterials := nil;
inherited;
end;
procedure TVXMaterialLibrary.DestroyHandles;
begin
if Assigned(FMaterials) then
Materials.DestroyHandles;
end;
procedure TVXMaterialLibrary.SetMaterials(const val: TVXLibMaterials);
begin
FMaterials.Assign(val);
end;
function TVXMaterialLibrary.StoreMaterials: Boolean;
begin
Result := (FMaterials.Count > 0);
end;
procedure TVXMaterialLibrary.WriteToFiler(writer: TVirtualWriter);
var
i, j: Integer;
libMat: TVXLibMaterial;
tex: TVXTexture;
img: TVXTextureImage;
pim: TVXPersistentImage;
ss: TStringStream;
bmp: TBitmap;
texExItem: TVXTextureExItem;
begin
with writer do
begin
WriteInteger(4); // archive version 0, texture persistence only
// archive version 1, libmat properties
// archive version 2, Material.TextureEx properties
// archive version 3, Material.Texture properties
// archive version 4, Material.TextureRotate
WriteInteger(Materials.Count);
for i := 0 to Materials.Count - 1 do
begin
// version 0
libMat := Materials[i];
WriteString(libMat.name);
tex := libMat.Material.Texture;
img := tex.Image;
pim := TVXPersistentImage(img);
if tex.Enabled and (img is TVXPersistentImage) and (pim.Picture.Bitmap <> nil) then
begin
WriteBoolean(True);
ss := TStringStream.Create('');
try
bmp := TBitmap.Create;
try
bmp.Assign(pim.Picture.Bitmap);
bmp.SaveToStream(ss);
finally
bmp.Free;
end;
WriteString(ss.DataString);
finally
ss.Free;
end;
// version 3
with libMat.Material.Texture do
begin
Write(BorderColor.AsAddress^, SizeOf(Single) * 4);
WriteInteger(Integer(Compression));
WriteInteger(Integer(DepthTextureMode));
Write(EnvColor.AsAddress^, SizeOf(Single) * 4);
WriteInteger(Integer(FilteringQuality));
WriteInteger(Integer(ImageAlpha));
WriteFloat(ImageBrightness);
WriteFloat(ImageGamma);
WriteInteger(Integer(MagFilter));
WriteInteger(Integer(MappingMode));
Write(MappingSCoordinates.AsAddress^, SizeOf(Single) * 4);
Write(MappingTCoordinates.AsAddress^, SizeOf(Single) * 4);
Write(MappingRCoordinates.AsAddress^, SizeOf(Single) * 4);
Write(MappingQCoordinates.AsAddress^, SizeOf(Single) * 4);
WriteInteger(Integer(MinFilter));
WriteFloat(NormalMapScale);
WriteInteger(Integer(TextureCompareFunc));
WriteInteger(Integer(TextureCompareMode));
WriteInteger(Integer(TextureFormat));
WriteInteger(Integer(TextureMode));
WriteInteger(Integer(TextureWrap));
WriteInteger(Integer(TextureWrapR));
WriteInteger(Integer(TextureWrapS));
WriteInteger(Integer(TextureWrapT));
end;
// version 3 end
end
else
WriteBoolean(False);
with libMat.Material.FrontProperties do
begin
Write(Ambient.AsAddress^, SizeOf(Single) * 3);
Write(Diffuse.AsAddress^, SizeOf(Single) * 4);
Write(Emission.AsAddress^, SizeOf(Single) * 3);
Write(Specular.AsAddress^, SizeOf(Single) * 3);
end;
// version 1
with libMat.Material.FrontProperties do
begin
Write(FShininess, 1);
WriteInteger(Integer(libMat.Material.PolygonMode));
end;
with libMat.Material.BackProperties do
begin
Write(Ambient.AsAddress^, SizeOf(Single) * 3);
Write(Diffuse.AsAddress^, SizeOf(Single) * 4);
Write(Emission.AsAddress^, SizeOf(Single) * 3);
Write(Specular.AsAddress^, SizeOf(Single) * 3);
Write(Byte(FShininess), 1);
WriteInteger(Integer(libMat.Material.PolygonMode));
end;
WriteInteger(Integer(libMat.Material.BlendingMode));
// version 3
with libMat.Material do
begin
if BlendingMode = bmCustom then
begin
WriteBoolean(True);
with BlendingParams do
begin
WriteFloat(AlphaFuncRef);
WriteInteger(Integer(AlphaFunctType));
WriteInteger(Integer(BlendFuncDFactor));
WriteInteger(Integer(BlendFuncSFactor));
WriteBoolean(UseAlphaFunc);
WriteBoolean(UseBlendFunc);
end;
end
else
WriteBoolean(False);
WriteInteger(Integer(FaceCulling));
end;
// version 3 end
WriteInteger(SizeOf(TMaterialOptions));
Write(libMat.Material.MaterialOptions, SizeOf(TMaterialOptions));
Write(libMat.TextureOffset.AsAddress^, SizeOf(Single) * 3);
Write(libMat.TextureScale.AsAddress^, SizeOf(Single) * 3);
WriteString(libMat.Texture2Name);
// version 4
WriteFloat(libMat.TextureRotate);
// version 2
WriteInteger(libMat.Material.TextureEx.Count);
for j := 0 to libMat.Material.TextureEx.Count - 1 do
begin
texExItem := libMat.Material.TextureEx[j];
img := texExItem.Texture.Image;
pim := TVXPersistentImage(img);
if texExItem.Texture.Enabled and (img is TVXPersistentImage) and (pim.Picture.Bitmap <> nil) then
begin
WriteBoolean(True);
ss := TStringStream.Create('');
try
bmp := TBitmap.Create;
try
bmp.Assign(pim.Picture.Bitmap);
bmp.SaveToStream(ss);
finally
bmp.Free;
end;
WriteString(ss.DataString);
finally
ss.Free;
end;
end
else
WriteBoolean(False);
WriteInteger(texExItem.TextureIndex);
Write(texExItem.TextureOffset.AsAddress^, SizeOf(Single) * 3);
Write(texExItem.TextureScale.AsAddress^, SizeOf(Single) * 3);
end;
end;
end;
end;
procedure TVXMaterialLibrary.ReadFromFiler(reader: TVirtualReader);
var
archiveVersion: Integer;
libMat: TVXLibMaterial;
i, n, size, tex, texCount: Integer;
LName: string;
ss: TStringStream;
/// -> bmp: TBitmap;
texExItem: TVXTextureExItem;
begin
archiveVersion := reader.ReadInteger;
if (archiveVersion >= 0) and (archiveVersion <= 4) then
with reader do
begin
if not FDoNotClearMaterialsOnLoad then
Materials.Clear;
n := ReadInteger;
for i := 0 to n - 1 do
begin
// version 0
LName := ReadString;
if FDoNotClearMaterialsOnLoad then
libMat := LibMaterialByName(LName)
else
libMat := nil;
if ReadBoolean then
begin
ss := TStringStream.Create(ReadString);
try
/// -> bmp := TBitmap.Create;
try
/// -> bmp.LoadFromStream(ss);
if libMat = nil then
{ TODO : E2250 There is no overloaded version of 'AddTextureMaterial' that can be called with these arguments }
(* libMat := AddTextureMaterial(LName, bmp) *)
else
/// -> libMat.Material.Texture.Image.Assign(bmp);
finally
/// -> bmp.Free;
end;
finally
ss.Free;
end;
// version 3
if archiveVersion >= 3 then
with libMat.Material.Texture do
begin
Read(BorderColor.AsAddress^, SizeOf(Single) * 4);
Compression := TVXTextureCompression(ReadInteger);
DepthTextureMode := TVXDepthTextureMode(ReadInteger);
Read(EnvColor.AsAddress^, SizeOf(Single) * 4);
FilteringQuality := TVXTextureFilteringQuality(ReadInteger);
ImageAlpha := TVXTextureImageAlpha(ReadInteger);
ImageBrightness := ReadFloat;
ImageGamma := ReadFloat;
MagFilter := TVXMagFilter(ReadInteger);
MappingMode := TVXTextureMappingMode(ReadInteger);
Read(MappingSCoordinates.AsAddress^, SizeOf(Single) * 4);
Read(MappingTCoordinates.AsAddress^, SizeOf(Single) * 4);
Read(MappingRCoordinates.AsAddress^, SizeOf(Single) * 4);
Read(MappingQCoordinates.AsAddress^, SizeOf(Single) * 4);
MinFilter := TVXMinFilter(ReadInteger);
NormalMapScale := ReadFloat;
TextureCompareFunc := TVXDepthCompareFunc(ReadInteger);
TextureCompareMode := TVXTextureCompareMode(ReadInteger);
TextureFormat := TVXTextureFormat(ReadInteger);
TextureMode := TVXTextureMode(ReadInteger);
TextureWrap := TVXTextureWrap(ReadInteger);
TextureWrapR := TVXSeparateTextureWrap(ReadInteger);
TextureWrapS := TVXSeparateTextureWrap(ReadInteger);
TextureWrapT := TVXSeparateTextureWrap(ReadInteger);
end;
// version 3 end
end
else
begin
if libMat = nil then
begin
libMat := Materials.Add;
libMat.name := LName;
end;
end;
with libMat.Material.FrontProperties do
begin
Read(Ambient.AsAddress^, SizeOf(Single) * 3);
Read(Diffuse.AsAddress^, SizeOf(Single) * 4);
Read(Emission.AsAddress^, SizeOf(Single) * 3);
Read(Specular.AsAddress^, SizeOf(Single) * 3);
end;
// version 1
if archiveVersion >= 1 then
begin
with libMat.Material.FrontProperties do
begin
Read(FShininess, 1);
libMat.Material.PolygonMode := TVXPolygonMode(ReadInteger);
end;
with libMat.Material.BackProperties do
begin
Read(Ambient.AsAddress^, SizeOf(Single) * 3);
Read(Diffuse.AsAddress^, SizeOf(Single) * 4);
Read(Emission.AsAddress^, SizeOf(Single) * 3);
Read(Specular.AsAddress^, SizeOf(Single) * 3);
Read(FShininess, 1);
{ PolygonMode := TPolygonMode( } ReadInteger;
end;
libMat.Material.BlendingMode := TBlendingMode(ReadInteger);
// version 3
if archiveVersion >= 3 then
begin
if ReadBoolean then
with libMat.Material.BlendingParams do
begin
AlphaFuncRef := ReadFloat;
AlphaFunctType := TGlAlphaFunc(ReadInteger);
BlendFuncDFactor := TVXBlendFunction(ReadInteger);
BlendFuncSFactor := TVXBlendFunction(ReadInteger);
UseAlphaFunc := ReadBoolean;
UseBlendFunc := ReadBoolean;
end;
libMat.Material.FaceCulling := TFaceCulling(ReadInteger);
end;
// version 3 end
size := ReadInteger;
Read(libMat.Material.FMaterialOptions, size);
Read(libMat.TextureOffset.AsAddress^, SizeOf(Single) * 3);
Read(libMat.TextureScale.AsAddress^, SizeOf(Single) * 3);
libMat.Texture2Name := ReadString;
// version 4
if archiveVersion >= 4 then
libMat.TextureRotate := ReadFloat;
end;
// version 2
if archiveVersion >= 2 then
begin
texCount := ReadInteger;
for tex := 0 to texCount - 1 do
begin
texExItem := libMat.Material.TextureEx.Add;
if ReadBoolean then
begin
ss := TStringStream.Create(ReadString);
/// -> bmp := TBitmap.Create;
try
/// -> bmp.LoadFromStream(ss);
/// -> texExItem.Texture.Image.Assign(bmp);
texExItem.Texture.Enabled := True;
finally
/// -> bmp.Free;
ss.Free;
end;
end;
texExItem.TextureIndex := ReadInteger;
Read(texExItem.TextureOffset.AsAddress^, SizeOf(Single) * 3);
Read(texExItem.TextureScale.AsAddress^, SizeOf(Single) * 3);
end;
end;
end;
end
else
RaiseFilerException(Self.ClassType, archiveVersion);
end;
procedure TVXMaterialLibrary.SaveToStream(aStream: TStream);
var
wr: TBinaryWriter;
begin
wr := TBinaryWriter.Create(aStream);
try
Self.WriteToFiler(wr);
finally
wr.Free;
end;
end;
procedure TVXMaterialLibrary.LoadFromStream(aStream: TStream);
var
rd: TBinaryReader;
begin
rd := TBinaryReader.Create(aStream);
try
Self.ReadFromFiler(rd);
finally
rd.Free;
end;
end;
procedure TVXMaterialLibrary.AddMaterialsFromStream(aStream: TStream);
begin
FDoNotClearMaterialsOnLoad := True;
try
LoadFromStream(aStream);
finally
FDoNotClearMaterialsOnLoad := False;
end;
end;
procedure TVXMaterialLibrary.SaveToFile(const fileName: string);
var
fs: TStream;
begin
fs := CreateFileStream(fileName, fmCreate);
try
SaveToStream(fs);
finally
fs.Free;
end;
end;
procedure TVXMaterialLibrary.LoadFromFile(const fileName: string);
var
fs: TStream;
begin
fs := CreateFileStream(fileName, fmOpenRead + fmShareDenyNone);
try
LoadFromStream(fs);
finally
fs.Free;
end;
end;
procedure TVXMaterialLibrary.AddMaterialsFromFile(const fileName: string);
var
fs: TStream;
begin
fs := CreateFileStream(fileName, fmOpenRead + fmShareDenyNone);
try
AddMaterialsFromStream(fs);
finally
fs.Free;
end;
end;
function TVXMaterialLibrary.AddTextureMaterial(const MaterialName, fileName: string; persistent: Boolean = True)
: TVXLibMaterial;
begin
Result := Materials.Add;
with Result do
begin
Name := MaterialName;
with Material.Texture do
begin
MinFilter := miLinearMipmapLinear;
MagFilter := maLinear;
TextureMode := tmModulate;
Disabled := False;
if persistent then
begin
ImageClassName := TVXPersistentImage.ClassName;
if fileName <> '' then
Image.LoadFromFile(fileName);
end
else
begin
ImageClassName := TVXPicFileImage.ClassName;
TVXPicFileImage(Image).PictureFileName := fileName;
end;
end;
end;
end;
function TVXMaterialLibrary.AddTextureMaterial(const MaterialName: string; Graphic: TBitmap): TVXLibMaterial;
begin
Result := Materials.Add;
with Result do
begin
Name := MaterialName;
with Material.Texture do
begin
MinFilter := miLinearMipmapLinear;
MagFilter := maLinear;
TextureMode := tmModulate;
Disabled := False;
Image.Assign(Graphic);
end;
end;
end;
function TVXMaterialLibrary.LibMaterialByName(const AName: TVXLibMaterialName): TVXLibMaterial;
begin
if Assigned(Self) then
Result := Materials.GetLibMaterialByName(AName)
else
Result := nil;
end;
function TVXMaterialLibrary.TextureByName(const LibMatName: TVXLibMaterialName): TVXTexture;
var
libMat: TVXLibMaterial;
begin
if Self = nil then
raise ETexture.Create(strErrorEx + strMatLibNotDefined)
else if LibMatName = '' then
Result := nil
else
begin
libMat := LibMaterialByName(LibMatName);
if libMat = nil then
raise ETexture.CreateFmt(strErrorEx + strMaterialNotFoundInMatlibEx, [LibMatName])
else
Result := libMat.Material.Texture;
end;
end;
function TVXMaterialLibrary.GetNameOfTexture(const Texture: TVXTexture): TVXLibMaterialName;
begin
if (Self = nil) or (Texture = nil) then
Result := ''
else
Result := Materials.GetNameOfTexture(Texture);
end;
function TVXMaterialLibrary.GetMaterials: TVXLibMaterials;
begin
Result := TVXLibMaterials(FMaterials);
end;
function TVXMaterialLibrary.GetNameOfLibMaterial(const libMat: TVXLibMaterial): TVXLibMaterialName;
begin
if (Self = nil) or (libMat = nil) then
Result := ''
else
Result := Materials.GetNameOfLibMaterial(libMat);
end;
{ TVXBlendingParameters }
procedure TVXBlendingParameters.Apply(var rci: TVXRenderContextInfo);
begin
if FUseAlphaFunc then
begin
rci.VxStates.Enable(stAlphaTest);
rci.VxStates.SetAlphaFunction(FAlphaFuncType, FAlphaFuncRef);
end
else
rci.VxStates.Disable(stAlphaTest);
if FUseBlendFunc then
begin
rci.VxStates.Enable(stBlend);
if FSeparateBlendFunc then
rci.VxStates.SetBlendFuncSeparate(FBlendFuncSFactor, FBlendFuncDFactor, FAlphaBlendFuncSFactor, FAlphaBlendFuncDFactor)
else
rci.VxStates.SetBlendFunc(FBlendFuncSFactor, FBlendFuncDFactor);
end
else
rci.VxStates.Disable(stBlend);
end;
constructor TVXBlendingParameters.Create(AOwner: TPersistent);
begin
inherited;
FUseAlphaFunc := False;
FAlphaFuncType := cfGreater;
FAlphaFuncRef := 0;
FUseBlendFunc := True;
FSeparateBlendFunc := False;
FBlendFuncSFactor := bfSrcAlpha;
FBlendFuncDFactor := bfOneMinusSrcAlpha;
FAlphaBlendFuncSFactor := bfSrcAlpha;
FAlphaBlendFuncDFactor := bfOneMinusSrcAlpha;
end;
procedure TVXBlendingParameters.SetAlphaFuncRef(const Value: Single);
begin
if (FAlphaFuncRef <> Value) then
begin
FAlphaFuncRef := Value;
NotifyChange(Self);
end;
end;
procedure TVXBlendingParameters.SetAlphaFuncType(const Value: TGlAlphaFunc);
begin
if (FAlphaFuncType <> Value) then
begin
FAlphaFuncType := Value;
NotifyChange(Self);
end;
end;
procedure TVXBlendingParameters.SetBlendFuncDFactor(const Value: TVXBlendFunction);
begin
if (FBlendFuncDFactor <> Value) then
begin
FBlendFuncDFactor := Value;
if not FSeparateBlendFunc then
FAlphaBlendFuncDFactor := Value;
NotifyChange(Self);
end;
end;
procedure TVXBlendingParameters.SetBlendFuncSFactor(const Value: TVXBlendFunction);
begin
if (FBlendFuncSFactor <> Value) then
begin
FBlendFuncSFactor := Value;
if not FSeparateBlendFunc then
FAlphaBlendFuncSFactor := Value;
NotifyChange(Self);
end;
end;
procedure TVXBlendingParameters.SetAlphaBlendFuncDFactor(const Value: TVXBlendFunction);
begin
if FSeparateBlendFunc and (FAlphaBlendFuncDFactor <> Value) then
begin
FAlphaBlendFuncDFactor := Value;
NotifyChange(Self);
end;
end;
procedure TVXBlendingParameters.SetAlphaBlendFuncSFactor(const Value: TVXBlendFunction);
begin
if FSeparateBlendFunc and (FAlphaBlendFuncSFactor <> Value) then
begin
FAlphaBlendFuncSFactor := Value;
NotifyChange(Self);
end;
end;
procedure TVXBlendingParameters.SetUseAlphaFunc(const Value: Boolean);
begin
if (FUseAlphaFunc <> Value) then
begin
FUseAlphaFunc := Value;
NotifyChange(Self);
end;
end;
procedure TVXBlendingParameters.SetUseBlendFunc(const Value: Boolean);
begin
if (FUseBlendFunc <> Value) then
begin
FUseBlendFunc := Value;
NotifyChange(Self);
end;
end;
procedure TVXBlendingParameters.SetSeparateBlendFunc(const Value: Boolean);
begin
if (FSeparateBlendFunc <> Value) then
begin
FSeparateBlendFunc := Value;
if not Value then
begin
FAlphaBlendFuncSFactor := FBlendFuncSFactor;
FAlphaBlendFuncDFactor := FBlendFuncDFactor;
end;
NotifyChange(Self);
end;
end;
function TVXBlendingParameters.StoreAlphaFuncRef: Boolean;
begin
Result := (Abs(AlphaFuncRef) > 0.001);
end;
//-------------------------------------------------
initialization
//-------------------------------------------------
RegisterClasses([TVXMaterialLibrary, TVXMaterial, TVXShader]);
end.
|
unit u_pj3dos;
interface
uses pjgeometry, SysUtils, misc_utils, GlobalVars, Classes;
Type
T3DOFace=class(TPolygon)
imat:integer;
ftype:Longint;
geo,light,tex:integer;
extra_l:single;
end;
T3DOFaces=class(TPolygons)
Function GetItem(n:integer):T3DOface;
Procedure SetItem(n:integer;v:T3DOface);
Property Items[n:integer]:T3DOface read GetItem write SetItem; default;
end;
T3DOMesh=class
name:string;
faces:T3DOFaces;
COnstructor Create;
Function GetVXs:TVertices;
Property vertices:Tvertices read GetVXs;
Destructor Destroy;override;
Function FindRadius:double;
end;
T3DOMeshes=class(TList)
Function GetItem(n:integer):T3DOMesh;
Procedure SetItem(n:integer;v:T3DOMesh);
Property Items[n:integer]:T3DOMesh read GetItem write SetItem; default;
end;
T3DOHNode=class
meshname:string;
nmesh:Integer;
parent:integer;
orgX,orgY,orgZ,
orgPCH,orgYAW,orgROL:double;
x,y,z:double;
pch,yaw,rol:double;
pivotx,pivoty,pivotz:double;
end;
T3DOHNodes=class(TList)
Function GetItem(n:integer):T3DOHNode;
Procedure SetItem(n:integer;v:T3DOHNode);
Property Items[n:integer]:T3DOHNode read GetItem write SetItem; default;
end;
TPJ3DO=class
ucount:integer;
Mats:TStringList;
Meshes:T3DOMeshes;
hnodes:T3DOHNodes;
Constructor CreateNew;
Constructor CreateFrom3DO(const name:string;lod:integer);
Destructor Destroy;override;
Function NewMesh:T3DOMesh;
Function GetMat(n:integer):string;
Procedure GetBBox(var box:TThingBox);
Function FindRadius:double;
Procedure OffsetMeshes;
Procedure SetDefaultOffsets;
Function IndexOfNode(const name:string):integer;
end;
Function Load3DO(const name:string):TPJ3DO;
Procedure Free3DO(var a3DO:TPJ3DO);
{These function must be use to load and free
3DOs, not TPJ3DO.CreateFrom3DO, TPJ3DO.Free}
implementation
uses files, FileOperations, geo_utils;
var
L3DOs:TStringList;
Function Load3DO(const name:string):TPJ3DO;
var i:integer;
begin
i:=L3DOs.IndexOf(name);
if i<>-1 then begin Result:=TPJ3DO(L3DOs.Objects[i]); inc(Result.ucount); end
else
begin
try
Result:=TPJ3DO.CreateFrom3DO(name,0);
L3DOs.AddObject(name,Result);
Result.ucount:=1;
except
on Exception do begin result:=nil; PanMessageFmt(mt_warning,'Cannot load %s',[name]); end;
end;
end;
end;
Procedure Free3DO(var a3DO:TPJ3DO);
var i:integer;
begin
if a3DO=nil then exit;
try
try
Dec(a3DO.ucount);
if A3Do.ucount<=0 then
begin
i:=L3DOs.IndexOfObject(a3DO);
if i<>-1 then L3DOs.Delete(i);
a3DO.Destroy;
end;
finally
a3DO:=nil;
end;
except
On Exception do;
end;
end;
Function T3DOFaces.GetItem(n:integer):T3DOFace;
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('3DO Face Index is out of bounds: %d',[n]);
Result:=T3DOFace(List[n]);
end;
Procedure T3DOFaces.SetItem(n:integer;v:T3DOFace);
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('3DO Face Index is out of bounds: %d',[n]);
List[n]:=v;
end;
Function T3DOMeshes.GetItem(n:integer):T3DOMesh;
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('3DO Mesh Index is out of bounds: %d',[n]);
Result:=T3DOMesh(List[n]);
end;
Procedure T3DOMeshes.SetItem(n:integer;v:T3DOMesh);
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('3DO Mesh Index is out of bounds: %d',[n]);
List[n]:=v;
end;
Constructor TPJ3DO.CreateNew;
begin
Mats:=TStringList.create;
Meshes:=T3DOMeshes.Create;
hnodes:=T3DOHnodes.Create;
end;
Destructor TPJ3DO.Destroy;
var i,j:integer;
begin
try
for i:=0 to Meshes.count-1 do
With Meshes[i] do
begin
For j:=0 to Vertices.count-1 do Vertices[j].free;
For j:=0 to Faces.count-1 do faces[j].free;
free;
end;
for i:=0 to hnodes.count-1 do hnodes[i].free;
hnodes.free;
finally
if i=0 then;
if j<>0 then;
end;
mats.free;
Inherited destroy;
end;
Function TPJ3DO.NewMesh:T3DOMesh;
begin
Result:=T3DOMesh.Create;
end;
Function TPJ3DO.GetMat(n:integer):string;
begin
if (n<0) or (n>=mats.count) then result:=''
else result:=Mats[n];
end;
Procedure TPJ3DO.GetBBox(var box:TThingBox);
var i,j:integer;
x1,x2,y1,y2,z1,z2:double;
begin
x1:=99999;
x2:=-99999;
y1:=99999;
y2:=-99999;
z1:=99999;
z2:=-99999;
for i:=0 to Meshes.count-1 do
With Meshes[i] do
for j:=0 to Vertices.count-1 do
With Vertices[j] do
begin
if tx<x1 then x1:=tx;
if tx>x2 then x2:=tx;
if ty<y1 then y1:=ty;
if ty>y2 then y2:=ty;
if tz<z1 then z1:=tz;
if tz>z2 then z2:=tz;
end;
if x1=99999 then FillChar(Box,sizeof(Box),0)
else
begin
box.x1:=x1;
box.x2:=x2;
box.y1:=y1;
box.y2:=y2;
box.z1:=z1;
box.z2:=z2;
end;
end;
COnstructor T3DOMesh.Create;
begin
Faces:=T3DOFaces.Create;
Faces.VXList:=TVertices.Create;
end;
Function T3DOMesh.GetVXs:TVertices;
begin
Result:=faces.VXList;
end;
Destructor T3DOMesh.Destroy;
begin
Faces.VXList.Destroy;
Faces.Destroy;
end;
Function T3DOMesh.FindRadius:double;
var i:integer;
crad:double;
begin
Result:=0;
for i:=0 to Vertices.count-1 do
With Vertices[i] do
begin
crad:=Sqrt(sqr(x)+sqr(y)+sqr(z));
if crad>result then Result:=crad;
end;
end;
Function TPJ3DO.FindRadius:double;
var i,j:integer;
crad:double;
begin
Result:=0;
for i:=0 to Meshes.count-1 do
begin
crad:=Meshes[i].FindRadius;
if crad>result then Result:=crad;
end;
end;
Function TPJ3DO.IndexOfNode(const name:string):integer;
var i:integer;
begin
Result:=-1;
for i:=0 to hnodes.count-1 do
begin
if CompareText(hnodes[i].meshname,name)=0 then
begin
result:=i;
exit;
end;
end;
end;
Procedure TPJ3DO.SetDefaultOffsets;
var i:integer;
begin
for i:=0 to HNodes.Count-1 do
With hNodes[i] do
begin
x:=orgx;
y:=orgy;
z:=orgz;
pch:=orgpch;
yaw:=orgyaw;
rol:=orgrol;
end;
end;
Procedure TPJ3DO.OffsetMeshes;
var i,j:integer;
hnode,hnode1:T3DOHNode;
mdx,mdy,mdz:double;
mx:TMat3x3;
vs:TVertices;
begin
for i:=0 to HNodes.Count-1 do
begin
hnode:=HNodes[i];
if hnode.nmesh=-1 then continue;
vs:=Meshes[hnode.nmesh].Vertices;
With Hnode do CreateRotMatrix(mx,pch,yaw,rol);
for j:=0 to vs.count-1 do
With vs[j] do
begin
tx:=x+hnode.pivotx;
ty:=y+hnode.pivoty;
tz:=z+hnode.pivotz;
MultVM3(mx,tx,ty,tz);
tx:=tx+hnode.x;
ty:=ty+hnode.y;
tz:=tz+hnode.z;
end;
(* mdx:=hnode.x+hnode.pivotx{+InsX};
mdy:=hnode.y+hnode.pivoty{+InsY};
mdz:=hnode.z+hnode.pivotz{+InsZ}; *)
hnode1:=hnode;
While hnode1.parent<>-1 do
begin
hnode1:=HNodes[hnode1.Parent];
With hnode1 do CreateRotMatrix(mx,pch,yaw,rol);
for j:=0 to vs.count-1 do
With vs[j] do
begin
MultVM3(mx,tx,ty,tz);
tx:=tx+hnode1.x;
ty:=ty+hnode1.y;
tz:=tz+hnode1.z;
end;
end;
end;
end;
Function T3DOHNodes.GetItem(n:integer):T3DOHNode;
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('3DO Node Index is out of bounds: %d',[n]);
Result:=T3DOHNode(List[n]);
end;
Procedure T3DOHNodes.SetItem(n:integer;v:T3DOHNode);
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('3DO Node Index is out of bounds: %d',[n]);
List[n]:=v;
end;
{$i pj3do_io.inc}
Initialization
begin
L3DOs:=TStringList.Create;
L3DOs.Sorted:=true;
end;
end.
|
(* MP_Lex 03.05.17 *)
(* Lexikalischer Analysator (scanner) für mini pascal*)
UNIT MP_Lex;
INTERFACE
TYPE
SymbolCode = (errorSy, (* error symbol *)
eofSy,
programSy, semicolonSy,
beginSy, endSy, periodSy,
varSy, colonSy, commaSy, integerSy,
readSy, writeSy, assignSy,
plusSy, minusSy, timesSy, divSy,
leftParSy, rightParSy,
identSy, numberSy);
VAR
sy: SymbolCode;
numberVal, syLnr, syCnr : INTEGER;
identStr : STRING;
PROCEDURE InitScanner(srcName: STRING; VAR ok: BOOLEAN);
PROCEDURE NewCh;
PROCEDURE NewSy;
IMPLEMENTATION
CONST
EF = Chr(0);
VAR
srcLine: STRING;
ch: CHAR;
chLnr, chCnr : INTEGER;
srcFile: TEXT;
PROCEDURE InitScanner(srcName: STRING; VAR ok: BOOLEAN);
BEGIN
Assign(srcFile, srcName);
{$I-}
Reset(srcFile);
{$I+}
ok := IOResult = 0;
IF ok THEN BEGIN
srcLine := '';
chLnr := 0;
chCnr := 1;
NewCh;
NewSy;
END;
END;
PROCEDURE NewCh;
BEGIN
IF chCnr < Length(srcLine) THEN BEGIN
chCnr := chCnr + 1;
ch := srcLine[chCnr];
END
ELSE BEGIN (* new line *)
IF NOT Eof(srcFile) THEN BEGIN
ReadLn(srcFile, srcLine);
Inc(chLnr);
chCnr := 0;
(* da leerzeichen überlesen werden wird in newsy gleich der
nächste char eingelesen *)
ch := ' ';
END
ELSE BEGIN
Close(srcFile);
ch := EF;
END;
END;
END;
PROCEDURE NewSy;
VAR
numberStr: STRING;
code: INTEGER;
BEGIN
WHILE ch = ' ' DO BEGIN
NewCh;
END;
syLnr := chLnr;
syCnr := chCnr;
CASE ch OF
EF: BEGIN
sy := eofSy;
END;
'+': BEGIN
sy := plusSy;
NewCh;
END;
'-': BEGIN
sy := minusSy;
NewCh;
END;
'*': BEGIN
sy := timesSy;
NewCh;
END;
'/': BEGIN
sy := divSy;
NewCh;
END;
'(': BEGIN
sy := leftParSy;
NewCh;
END;
')': BEGIN
sy := rightParSy;
NewCh;
END;
';': BEGIN
sy := semicolonSy;
NewCh;
END;
'.': BEGIN
sy := periodSy;
NewCh;
END;
',': BEGIN
sy := commaSy;
NewCh;
END;
':': BEGIN
NewCh;
IF ch <> '=' THEN BEGIN
sy := colonSy;
END
ELSE BEGIN
sy := assignSy;
NewCh;
END;
END;
'a' .. 'z', 'A' .. 'Z': BEGIN
identStr := '';
WHILE ch IN ['a' .. 'z', 'A' .. 'Z', '0' .. '9', '_'] DO BEGIN
identStr := Concat(identStr, UpCase(ch));
NewCh;
END;
IF identStr = 'PROGRAM' THEN
sy := programSy
ELSE IF identStr = 'BEGIN'THEN
sy := beginSy
ELSE IF identStr = 'END' THEN
sy := endSy
ELSE IF identStr = 'VAR' THEN
sy := varSy
ELSE IF identStr = 'INTEGER' THEN
sy := integerSy
ELSE IF identStr = 'READ' THEN
sy := readSy
ELSE IF identStr = 'WRITE' THEN
sy := writeSy
ELSE
sy := identSy;
END;
'0'..'9': BEGIN
sy := numberSy;
numberStr := '';
WHILE (ch >= '0') AND (ch <= '9') DO BEGIN
numberStr := numberStr + ch;
NewCh;
END;
Val(numberStr, numberVal, code);
END;
ELSE
sy := errorSy;
END;
END;
END. (* MP_Lex *) |
unit unitmail;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Psock, NMsmtp, StdCtrls, ExtCtrls, Menus, Buttons, ComCtrls;
type
TfrmMail = class(TForm)
Memo2: TMemo;
NMSMTP1: TNMSMTP;
Panel1: TPanel;
Label4: TLabel;
Label5: TLabel;
eSender: TEdit;
eReceiver: TEdit;
Label1: TLabel;
eSubject: TEdit;
MainMenu1: TMainMenu;
Mail1: TMenuItem;
mnuSend: TMenuItem;
mnuExit: TMenuItem;
N1: TMenuItem;
btSend: TBitBtn;
StatusBar1: TStatusBar;
procedure btSendClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure NMSMTP1ConnectionRequired(var Handled: Boolean);
procedure NMSMTP1InvalidHost(var Handled: Boolean);
procedure mnuConnectClick(Sender: TObject);
procedure mnuSendClick(Sender: TObject);
procedure mnuExitClick(Sender: TObject);
procedure eReceiverChange(Sender: TObject);
procedure eSenderChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmMail: TfrmMail;
implementation
{$R *.dfm}
procedure TfrmMail.btSendClick(Sender: TObject);
begin
with NMSMTP1.PostMessage do
begin
FromName:= '肖申';
FromAddress:= eSender.text;
Subject:= eSubject.Text;
ToAddress.Add(eReceiver.Text);
Body.Assign(Memo2.Lines);
end;
NMSMTP1.SendMail;
messagedlg('邮件发送成功',mtInformation,[mbok],0);
end;
procedure TfrmMail.NMSMTP1ConnectionRequired(var Handled: Boolean);
begin
if MessageDlg('请求链接,是否应允?',mtConfirmation,mbOKCancel,0)=mrOk then
begin
Handled:= True;
end;
end;
procedure TfrmMail.FormClose(Sender: TObject; var Action: TCloseAction);
begin
NMSMTP1.Disconnect;
NMSMTP1.Abort;
end;
procedure TfrmMail.FormCreate(Sender: TObject);
begin
memo2.Lines.Add(datetimetostr(now()));
NMSMTP1.Host := '10.10.40.1';
NMSMTP1.Port := 25;
NMSMTP1.UserID := 'xiaoshen';
NMSMTP1.Connect;
statusBar1.Panels[1].Text := '发送邮件给:'+ eReceiver.text;
statusBar1.Panels[2].Text := '发件人:'+ esender.text;
end;
procedure TfrmMail.NMSMTP1InvalidHost(var Handled: Boolean);
var
TmpStr:string;
begin
If InputQuery('非法主机!','指定新主机名',TmpStr)then
begin
NMSMTP1.Host := TmpStr;
Handled := True;
end;
end;
procedure TfrmMail.mnuConnectClick(Sender: TObject);
begin
NMSMTP1.Connect;
end;
procedure TfrmMail.mnuSendClick(Sender: TObject);
begin
btSend.Click;
end;
procedure TfrmMail.mnuExitClick(Sender: TObject);
begin
close;
end;
procedure TfrmMail.eReceiverChange(Sender: TObject);
begin
statusBar1.Panels[1].Text := '发送邮件给:'+ eReceiver.text;
end;
procedure TfrmMail.eSenderChange(Sender: TObject);
begin
statusBar1.Panels[2].Text := '发件人:'+ esender.text;
end;
end.
|
unit CatDCP;
{
Catarinka Crypto library
Quick AES encryption/decryption functions covering string, stream and file
Copyright (c) 2003-2017 Felipe Daragon
License: 3-clause BSD
See https://github.com/felipedaragon/catarinka/ for details
}
interface
{$I Catarinka.inc}
uses
{$IFDEF DXE2_OR_UP}
Winapi.Windows, System.Classes, System.SysUtils;
{$ELSE}
Classes, SysUtils;
{$ENDIF}
function StrToAES(const s, key: string): string;
function AESToStr(const s, key: string): string;
procedure AES_EncryptFile(const filename, outfilename: string;
const key: string);
procedure AES_DecryptFile(const filename, outfilename: string;
const key: string);
procedure AES_EncryptStream(ms: TMemoryStream; const key: string);
procedure AES_DecryptStream(ms: TMemoryStream; const key: string);
// ansi functions
function AnsiStrToAES(const s, key: string): string;
function AESToAnsiStr(const s, key: string): string;
implementation
uses
DCPrijndael, DCPsha512;
function StrToAES(const s, key: string): string;
var
c: TDCP_rijndael;
begin
c := TDCP_rijndael.Create(nil);
c.InitStr(key, TDCP_sha512);
result := string(c.EncryptString(s));
c.Burn;
c.Free;
end;
function AESToStr(const s, key: string): string;
var
c: TDCP_rijndael;
begin
c := TDCP_rijndael.Create(nil);
c.InitStr(key, TDCP_sha512);
result := string(c.DecryptString(s));
c.Burn;
c.Free;
end;
procedure AES_EncryptFile(const filename, outfilename: string;
const key: string);
var
s: TMemoryStream;
begin
if fileexists(filename) = false then
exit;
s := TMemoryStream.Create;
s.LoadFromFile(filename);
s.position := 0;
AES_EncryptStream(s, key);
s.SaveToFile(outfilename);
s.Free;
end;
procedure AES_DecryptFile(const filename, outfilename: string;
const key: string);
var
s: TMemoryStream;
begin
if fileexists(filename) = false then
exit;
s := TMemoryStream.Create;
s.LoadFromFile(filename);
s.position := 0;
AES_DecryptStream(s, key);
s.SaveToFile(outfilename);
s.Free;
end;
procedure AES_EncryptStream(ms: TMemoryStream; const key: string);
var
src: TMemoryStream;
c: TDCP_rijndael;
begin
src := TMemoryStream.Create;
src.CopyFrom(ms, ms.Size);
src.position := 0;
ms.clear;
c := TDCP_rijndael.Create(nil);
// initialize the cipher with a hash of the passphrase
c.InitStr(key, TDCP_sha512);
// encrypt the contents of the stream
c.EncryptStream(src, ms, src.Size);
c.Burn;
c.Free;
src.Free;
end;
procedure AES_DecryptStream(ms: TMemoryStream; const key: string);
var
src: TMemoryStream;
c: TDCP_rijndael;
begin
src := TMemoryStream.Create;
src.CopyFrom(ms, ms.Size);
src.position := 0;
ms.clear;
c := TDCP_rijndael.Create(nil);
// initialize the cipher with a hash of the passphrase
c.InitStr(key, TDCP_sha512);
// decrypt the contents of the stream
c.DecryptStream(src, ms, src.Size);
c.Burn;
c.Free;
src.Free;
end;
{ ansi functions }
function AnsiStrToAES(const s, key: string): string;
var
c: TDCP_rijndael;
begin
c := TDCP_rijndael.Create(nil);
// force ANSI
c.InitStr(ansistring(key), TDCP_sha512);
result := string(c.EncryptString(ansistring(s)));
c.Burn;
c.Free;
end;
function AESToAnsiStr(const s, key: string): string;
var
c: TDCP_rijndael;
begin
c := TDCP_rijndael.Create(nil);
// force ANSI
c.InitStr(ansistring(key), TDCP_sha512);
result := string(c.DecryptString(ansistring(s)));
c.Burn;
c.Free;
end;
// ------------------------------------------------------------------------//
end.
|
unit SDURegistry;
// Description: Sarah Dean's Registry Object
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
// This unit extends TRegistry to allow passing default values in if the named
// value doens't exist
interface
uses
Registry;
type
TSDURegistry = class (TRegistry)
PUBLIC
function ReadBinaryData(const Name: String; var Buffer; BufSize: Integer;
var Default; DefaultSize: Integer): Integer; OVERLOAD;
function ReadBool(const Name: String; Default: Boolean): Boolean; OVERLOAD;
function ReadCurrency(const Name: String; Default: Currency): Currency; OVERLOAD;
function ReadDate(const Name: String; Default: TDateTime): TDateTime; OVERLOAD;
function ReadDateTime(const Name: String; Default: TDateTime): TDateTime; OVERLOAD;
function ReadFloat(const Name: String; Default: Double): Double; OVERLOAD;
function ReadInteger(const Name: String; Default: Integer): Integer; OVERLOAD;
function ReadString(const Name: String; Default: String): String; OVERLOAD;
function ReadTime(const Name: String; Default: TDateTime): TDateTime; OVERLOAD;
end;
implementation
uses
Consts, // Required for SInvalidRegType
SysUtils; // Required for StrMove
function TSDURegistry.ReadBinaryData(const Name: String; var Buffer; BufSize: Integer;
var Default; DefaultSize: Integer): Integer;
begin
if (ValueExists(Name)) then begin
Result := ReadBinaryData(Name, Buffer, BufSize);
end else begin
if (BufSize >= DefaultSize) then begin
StrMove(PChar(Buffer), PChar(Default), DefaultSize);
Result := DefaultSize;
end else begin
raise ERegistryException.CreateResFmt(@SInvalidRegType, [Name]);
end;
end;
end;
function TSDURegistry.ReadBool(const Name: String; Default: Boolean): Boolean;
begin
if (ValueExists(Name)) then begin
Result := ReadBool(Name);
end else begin
Result := Default;
end;
end;
function TSDURegistry.ReadCurrency(const Name: String; Default: Currency): Currency;
begin
if (ValueExists(Name)) then begin
Result := ReadCurrency(Name);
end else begin
Result := Default;
end;
end;
function TSDURegistry.ReadDate(const Name: String; Default: TDateTime): TDateTime;
begin
if (ValueExists(Name)) then begin
Result := ReadDate(Name);
end else begin
Result := Default;
end;
end;
function TSDURegistry.ReadDateTime(const Name: String; Default: TDateTime): TDateTime;
begin
if (ValueExists(Name)) then begin
Result := ReadDateTime(Name);
end else begin
Result := Default;
end;
end;
function TSDURegistry.ReadFloat(const Name: String; Default: Double): Double;
begin
if (ValueExists(Name)) then begin
Result := ReadFloat(Name);
end else begin
Result := Default;
end;
end;
function TSDURegistry.ReadInteger(const Name: String; Default: Integer): Integer;
begin
if (ValueExists(Name)) then begin
Result := ReadInteger(Name);
end else begin
Result := Default;
end;
end;
function TSDURegistry.ReadString(const Name: String; Default: String): String;
begin
if (ValueExists(Name)) then begin
Result := ReadString(Name);
end else begin
Result := Default;
end;
end;
function TSDURegistry.ReadTime(const Name: String; Default: TDateTime): TDateTime;
begin
if (ValueExists(Name)) then begin
Result := ReadTime(Name);
end else begin
Result := Default;
end;
end;
end.
|
unit osregex; //regular expression unit for opsi-script
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, RegExpr;
function isRegexMatch(inputtext,expr : string) : boolean; //Returns true if regex matches the inputtext.
function getSubListByContainingRegex(expr : string; inputlist : TStringList) : TStringList; //Returns list of matching lines for a single regex.
function getSubListByContainingRegex(exprlist : TStringList; inputlist : TStringList) : TStringList; //Returns list of matching lines for a list of regex.
function getRegexMatchList(expr : string; inputlist : TStringList) : TStringList; //Returns list of exact matches for a single regex.
function getRegexMatchList(exprlist : TStringList; inputlist : TStringList) : TStringList; //Returns list of exact matches for a list of regex.
function removeFromListByContainingRegex(expr : string; inputlist : TStringList) : TStringList; //remove matching lines for a single regex.
function removeFromListByContainingRegex(exprlist : TStringList; inputlist : TStringList) : TStringList; //remove matching lines for a list of regex.
function stringReplaceRegex(inputtext, expr, replacetext : string) : string; //Replace matches in string with replacetext.
function stringReplaceRegexInList(inputlist : TStringList; expr, replacetext : string) : TStringList; //Replace matches in the stringlist with replacetext.
implementation
function isRegexMatch(inputtext,expr : string) : boolean;
//Returns true if regex matches the inputtext.
var
regexobj : TRegExpr;
begin
result := false;
regexobj := TRegExpr.Create;
try
regexobj.Expression := expr;
if regexobj.Exec(inputtext) then
result := true;
finally
regexobj.Free;
end;
end;
function getSubListByContainingRegex(expr : string; inputlist : TStringList) : TStringList;
//Returns list of matching lines for a single regex.
var
regexobj : TRegExpr;
linecounter : integer;
currentline : string;
begin
try
regexobj := TRegExpr.Create;
regexobj.Expression := expr;
result := TStringList.Create;
for linecounter:=0 to inputlist.Count-1 do
begin
currentline := trim(inputlist.Strings[linecounter]);
if regexobj.Exec(currentline) then
result.Add(currentline);
end;
finally
regexobj.Free;
end;
end;
function getSubListByContainingRegex(exprlist : TStringList; inputlist : TStringList) : TStringList;
// Returns list of matching lines for a list of regex.
var
regexobj : TRegExpr;
linecounter : integer;
currentline : string;
begin
try
result := TStringList.Create;
regexobj := TRegExpr.Create;
exprlist. Delimiter:= '|';
regexobj.Expression := exprlist.DelimitedText;
for linecounter:=0 to inputlist.Count-1 do
begin
currentline := trim(inputlist.Strings[linecounter]);
if regexobj.Exec(currentline) then
begin
result.Add(currentline);
end;
end;
finally
regexobj.Free;
end;
end;
function getRegexMatchList(expr : string; inputlist : TStringList) : TStringList;
//Returns list of exact matches for a single regex.
var
regexobj : TRegExpr;
linecounter : integer;
currentline : string;
begin
try
regexobj := TRegExpr.Create;
regexobj.Expression := expr;
result := TStringList.Create;
for linecounter:=0 to inputlist.Count-1 do
begin
currentline := trim(inputlist.Strings[linecounter]);
if regexobj.Exec(currentline) then
begin
result.Add(regexobj.Match[0]);
while regexobj.ExecNext do
result.Add(regexobj.Match[0]);
end;
end;
finally
regexobj.Free;
end;
end;
function getRegexMatchList(exprlist : TStringList; inputlist : TStringList) : TStringList;
//Returns list of exact matches for a list of regex.
var
regexobj : TRegExpr;
linecounter : integer;
currentline : string;
begin
try
result := TStringList.Create;
regexobj := TRegExpr.Create;
exprlist. Delimiter:= '|';
regexobj.Expression := exprlist.DelimitedText;
for linecounter:=0 to inputlist.Count-1 do
begin
currentline := trim(inputlist.Strings[linecounter]);
if regexobj.Exec(currentline) then
begin
result.Add(regexobj.Match[0]);
while regexobj.ExecNext do
result.Add(regexobj.Match[0]);
end;
end;
finally
regexobj.Free;
end;
end;
function removeFromListByContainingRegex(expr : string; inputlist : TStringList) : TStringList;
//remove matching lines for a single regex.
var
regexobj : TRegExpr;
linecounter : integer;
currentline : string;
begin
try
regexobj := TRegExpr.Create;
regexobj.Expression := expr;
result := TStringList.Create;
for linecounter:=0 to inputlist.Count-1 do
begin
currentline := trim(inputlist.Strings[linecounter]);
if not regexobj.Exec(currentline) then
begin
result.Add(currentline);
end;
end;
finally
regexobj.Free;
end;
end;
function removeFromListByContainingRegex(exprlist : TStringList; inputlist : TStringList) : TStringList;
//remove matching lines for a list of regex.
var
regexobj : TRegExpr;
linecounter : integer;
currentline : string;
begin
try
result := TStringList.Create;
regexobj := TRegExpr.Create;
exprlist. Delimiter:= '|';
regexobj.Expression := exprlist.DelimitedText;
for linecounter:=0 to inputlist.Count-1 do
begin
currentline := trim(inputlist.Strings[linecounter]);
if not regexobj.Exec(currentline) then
result.Add(currentline);
end;
finally
regexobj.Free;
end;
end;
function stringReplaceRegex(inputtext, expr, replacetext : string) : string;
//Replace matches in string with replacetext.
begin
result:= '';
inputtext:= ReplaceRegExpr(expr, inputtext, replacetext, True);
result:= inputtext;
end;
function stringReplaceRegexInList(inputlist : TStringList; expr, replacetext : string) : TStringList;
//Replace matches in the stringlist with replacetext.
var
linecounter : integer;
currentline : string;
begin
result:= TStringList.Create;
for linecounter:=0 to inputlist.Count-1 do
begin
currentline := trim(inputlist.Strings[linecounter]);
currentline:= ReplaceRegExpr(expr, currentline, replacetext, True);
result.Add(currentline);
end;
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, Vcl.ComCtrls, NtBase;
type
TForm1 = class(TForm)
PatternLabel: TLabel;
PatternEdit: TComboBox;
ResultLabel: TLabel;
ParseButton: TButton;
LanguageLabel: TLabel;
LanguageCombo: TComboBox;
ItemsList: TListView;
ParameterLabel: TLabel;
ParameterEdit: TEdit;
ParameterUpDown: TUpDown;
ClearButton: TButton;
DefaultButton: TButton;
StatusLabel: TLabel;
procedure FormCreate(Sender: TObject);
procedure PatternEditChange(Sender: TObject);
procedure ParseButtonClick(Sender: TObject);
procedure LanguageComboChange(Sender: TObject);
procedure ParameterEditChange(Sender: TObject);
procedure ClearButtonClick(Sender: TObject);
procedure DefaultButtonClick(Sender: TObject);
private
FLanguages: TNtLanguages;
function GetLanguageId: String;
function GetLanguageCount: Integer;
function GetLanguage(i: Integer): TNtLanguage;
function GetPattern: String;
function GetParameter: Integer;
procedure SetLanguageId(const value: String);
procedure SetPattern(const value: String);
procedure SetParameter(value: Integer);
procedure Process;
procedure SetDefault;
procedure HideList;
public
property LanguageId: String read GetLanguageId write SetLanguageId;
property LanguageCount: Integer read GetLanguageCount;
property Languages[i: Integer]: TNtLanguage read GetLanguage;
property Pattern: String read GetPattern write SetPattern;
property Parameter: Integer read GetParameter write SetParameter;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
// This contains TMultiPattern.Format
NtPattern,
// This is not normally needed with plurals. It is used here to the plular forms that active language required
NtPluralsData;
procedure TForm1.SetDefault;
begin
PatternEdit.Text := PatternEdit.Items[0];
LanguageId := 'en';
PatternEdit.ItemIndex := 0;
Parameter := 1;
PatternEditChange(Self);
end;
function TForm1.GetLanguageCount: Integer;
begin
Result := LanguageCombo.Items.Count;
end;
function TForm1.GetLanguage(i: Integer): TNtLanguage;
begin
Result := TNtLanguage(LanguageCombo.Items.Objects[i])
end;
function TForm1.GetLanguageId: String;
begin
if LanguageCombo.ItemIndex >= 0 then
Result := Languages[LanguageCombo.ItemIndex].Code
else
Result := '';
end;
procedure TForm1.SetLanguageId(const value: String);
var
i: Integer;
begin
for i := 0 to LanguageCount - 1 do
begin
if Languages[i].Code = value then
begin
LanguageCombo.ItemIndex := i;
LanguageComboChange(Self);
Exit;
end;
end;
LanguageCombo.ItemIndex := -1;
end;
function TForm1.GetPattern: String;
begin
Result := PatternEdit.Text;
end;
procedure TForm1.SetPattern(const value: String);
begin
PatternEdit.Text := value;
PatternEditChange(Self);
end;
function TForm1.GetParameter: Integer;
begin
Result := ParameterUpDown.Position;
end;
procedure TForm1.SetParameter(value: Integer);
begin
ParameterUpDown.Position := value;
end;
procedure TForm1.Process;
var
str: String;
kind: TFormatParameterKind;
plural: TPlural;
operatorKind: TOperatorKind;
operand, operand2: Integer;
pat: TPattern;
part: TFormatPart;
requiredPlurals, actualPlurals, missingPlurals: TPlurals;
formatString: TFormatString;
begin
// Get the result
if Pattern <> '' then
begin
str := TMultiPattern.Format(Pattern, [Parameter]);
TMultiPattern.GetNumber(Pattern, Parameter, kind, plural, operatorKind, operand, operand2);
if kind = fpPlural then
ResultLabel.Caption := TMultiPattern.PluralToString(plural) + ': ' + str
else
ResultLabel.Caption := TMultiPattern.OperatorToString(operatorKind, operand, operand2) + ': ' + str
end
else
begin
ResultLabel.Caption := '';
end;
// Check that pattern contains all items
requiredPlurals := TMultiPattern.GetPlurals(puInteger);
actualPlurals := [];
formatString := TFormatString.Create;
try
formatString.ParsePattern(Pattern);
for part in formatString do
begin
for pat in part do
begin
if pat is TPluralPattern then
Include(actualPlurals, TPluralPattern(pat).Plural);
end;
end;
finally
formatString.Free;
end;
if actualPlurals >= requiredPlurals then
begin
StatusLabel.Caption := 'All required plurals forms are present';
StatusLabel.Font.Color := clGreen;
end
else
begin
missingPlurals := requiredPlurals - actualPlurals;
str := '';
for plural := Low(plural) to High(plural) do
if plural in missingPlurals then
begin
if str <> '' then
str := str + ', ';
str := str + TMultiPattern.PluralToString(plural);
end;
StatusLabel.Caption := Format('Following plurals forms are missing: %s', [str]);
StatusLabel.Font.Color := clRed;
end;
end;
var
enumLanugages: TNtLanguages;
function EnumLocalesEx(localeStr: PChar; flags: DWord; param: LParam): Integer; stdcall;
begin
if (localeStr <> '') and (Pos('-', localeStr) = 0) then
enumLanugages.Add(localeStr);
Result := 1;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
i: Integer;
language: TNtLanguage;
begin
// Get all languages supported by Windows
FLanguages := TNtLanguages.Create;
enumLanugages := FLanguages;
EnumSystemLocalesEx(@EnumLocalesEx, LOCALE_ALL, 0, nil);
for i := 0 to FLanguages.Count - 1 do
begin
language := FLanguages[i];
LanguageCombo.Items.AddObject(language.SystemName, language);
end;
LanguageCombo.Sorted := True;
// Populate pattern list
// Standard English pattern
PatternEdit.Items.Add('{plural, one {I have %d car} other {I have %d cars}}');
// English pattern with optional zero part
PatternEdit.Items.Add('{plural, zero {I have no cars} one {I have one car} other {I have %d cars}}');
// Pattern with several custom operator parts
PatternEdit.Items.Add('{plural, =0 {I have no cars} one {I have %d car} =2 {I have two cars} ~12 {I have a dozen cars} >=20 {I must be a car dealer} other {I have %d cars}}');
HideList;
SetDefault;
end;
procedure TForm1.HideList;
begin
ItemsList.Items.Clear;
ItemsList.Hide;
end;
procedure TForm1.PatternEditChange(Sender: TObject);
begin
ParseButton.Enabled := Pattern <> '';
ClearButton.Enabled := Pattern <> '';
ResultLabel.Visible := Pattern <> '';
if Pattern = '' then
ItemsList.Hide;
Process;
end;
procedure TForm1.LanguageComboChange(Sender: TObject);
begin
// Plural engine needs to know the language that the application uses.
HideList;
DefaultLocale := LanguageId;
PatternEditChange(Self);
end;
procedure TForm1.ParameterEditChange(Sender: TObject);
begin
Process;
end;
procedure TForm1.ParseButtonClick(Sender: TObject);
var
pat: TPattern;
part: TFormatPart;
formatString: TFormatString;
item: TListItem;
begin
formatString := TFormatString.Create;
try
formatString.ParsePattern(Pattern);
for part in formatString do
begin
for pat in part do
begin
item := ItemsList.Items.Add;
item.Caption := pat.ToString;
item.SubItems.Add(pat.Value);
end;
end;
finally
formatString.Free;
end;
ItemsList.Show;
end;
procedure TForm1.ClearButtonClick(Sender: TObject);
begin
Pattern := '';
end;
procedure TForm1.DefaultButtonClick(Sender: TObject);
begin
SetDefault;
end;
initialization
RaiseExceptionOnInvalidPattern := False;
end.
|
unit ServerMethodsUnit;
interface
uses System.SysUtils, System.Classes, System.Json,
Datasnap.DSServer, Datasnap.DSAuth, DataSnap.DSProviderDataModuleAdapter;
type
{$METHODINFO ON}
TServerMethods = class(TDataModule)
private
{ Private declarations }
public
{ Public declarations }
function EchoString(Value: string): string;
function ReverseString(Value: string): string;
end;
{$METHODINFO OFF}
implementation
{$R *.dfm}
uses System.StrUtils, uDSUtils;
function TServerMethods.EchoString(Value: string): string;
begin
Result := Value;
end;
function TServerMethods.ReverseString(Value: string): string;
begin
Result := System.StrUtils.ReverseString(Value);
end;
end.
|
unit gr_IndexCount_MainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, cxLookupEdit,
cxDBLookupEdit, cxDBLookupComboBox, cxMaskEdit, cxSpinEdit,
cxDropDownEdit, cxCalendar, cxLabel, cxTextEdit, cxButtonEdit,
cxGroupBox, cxControls, cxContainer, cxEdit, cxCheckBox, ibase,
FIBDatabase, pFIBDatabase, FIBQuery, pFIBQuery, pFIBStoredProc, ZProc,
Unit_ZGlobal_Consts, DB, FIBDataSet, pFIBDataSet, gr_uMessage,
gr_uCommonConsts, Dates, PackageLoad, ZTypes, uCommonSp, GlobalSpr,
cxDBEdit, gr_uCommonProc, gr_uWaitForm, gr_uCommonLoader;
type
TFIndexCount = class(TForm)
CheckBoxVidOpl: TcxCheckBox;
BoxVidOpl: TcxGroupBox;
EditVidOpl: TcxButtonEdit;
LabelVidOplData: TcxLabel;
CheckBoxDepartment: TcxCheckBox;
BoxDepartment: TcxGroupBox;
EditDepartment: TcxButtonEdit;
LabelDepartmentData: TcxLabel;
DateEdit: TcxDateEdit;
CheckBoxSmeta: TcxCheckBox;
BoxSmeta: TcxGroupBox;
EditSmeta: TcxButtonEdit;
LabelSmetaData: TcxLabel;
BoxKodSetup: TcxGroupBox;
MonthesList: TcxComboBox;
YearSpinEdit: TcxSpinEdit;
cxLabel1: TcxLabel;
CheckBoxKatStud: TcxCheckBox;
BoxCatStud: TcxGroupBox;
ComboBoxCategory: TcxLookupComboBox;
BtnOk: TcxButton;
BtnCancel: TcxButton;
DB: TpFIBDatabase;
StProc: TpFIBStoredProc;
StProcTransaction: TpFIBTransaction;
DSetCatStud: TpFIBDataSet;
DSourceCatStud: TDataSource;
ReadTransaction: TpFIBTransaction;
cxLabel2: TcxLabel;
MaskEditPercent: TcxMaskEdit;
DSetPM: TpFIBDataSet;
DSourcePM: TDataSource;
MaskEditPM: TcxMaskEdit;
Editkurs: TcxSpinEdit;
CheckBoxKurs: TcxCheckBox;
BoxProp: TcxGroupBox;
CheckBoxProp: TcxCheckBox;
PropEdit: TcxLookupComboBox;
DSetProp: TpFIBDataSet;
DSourceProp: TDataSource;
CheckBoxIsDelete: TcxCheckBox;
procedure CheckBoxVidOplClick(Sender: TObject);
procedure CheckBoxDepartmentClick(Sender: TObject);
procedure CheckBoxSmetaClick(Sender: TObject);
procedure CheckBoxKatStudClick(Sender: TObject);
procedure EditVidOplExit(Sender: TObject);
procedure EditVidOplPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure EditDepartmentExit(Sender: TObject);
procedure EditDepartmentPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure EditSmetaPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure EditSmetaExit(Sender: TObject);
procedure BtnCancelClick(Sender: TObject);
procedure BtnOkClick(Sender: TObject);
procedure YearSpinEditPropertiesChange(Sender: TObject);
procedure CheckBoxPropClick(Sender: TObject);
procedure CheckBoxKursClick(Sender: TObject);
private
PDb_Handle:TISC_DB_HANDLE;
PLanguageIndex:byte;
PId_VidOpl:integer;
PId_department:integer;
PCode_department:variant;
PId_smeta:integer;
PNum_predpr:integer;
PParam:TObject;
public
constructor Create(Param:Tobject);reintroduce;
end;
implementation
{$R *.dfm}
constructor TFIndexCount.Create(Param:TObject); // TgrIndexacParam
var CurrKodSetup:Integer;
begin
inherited Create(TgrIndexacParam(Param).Owner);
PParam:=Param;
PDb_Handle:=TgrIndexacParam(Param).DB_Handle;
PLanguageIndex:= IndexLanguage;
PNum_predpr:=NumPredpr(PDb_Handle);
ComboBoxCategory.Properties.DataController.DataSource:=DSourceCatStud;
//******************************************************************************
Self.Caption := GrantIndexation_Text[PLanguageIndex];
CheckBoxDepartment.Properties.Caption := LabelDepartment_Caption[PLanguageIndex];
CheckBoxVidOpl.Properties.Caption := LabelVidOpl_Caption[PLanguageIndex];
CheckBoxSmeta.Properties.Caption := LabelSmeta_Caption[PLanguageIndex];
CheckBoxKatStud.Properties.Caption := LabelCategory_Caption[PLanguageIndex];
MonthesList.Properties.Items.Text := MonthesList_Text[PLanguageIndex];
cxLabel1.Caption := LabelIndexMinim_Caption[PLanguageIndex];
cxLabel2.Caption := LabelIndexPercent_Caption[PLanguageIndex];
CheckBoxProp.Properties.Caption := GridClPropertyName_Caption[PLanguageIndex];
CheckBoxKurs.Properties.Caption := LabelKurs_Caption[PLanguageIndex];
BtnOk.Caption := YesBtn_Caption[PLanguageIndex];
BtnCancel.Caption := CancelBtn_Caption[PLanguageIndex];
try
DB.Handle:=PDb_Handle;
except
on E:Exception do
begin
grShowMessage(ECaption[PLanguageIndex],e.Message,mtError,[mbOK]);
end;
end;
//******************************************************************************
StProc.Transaction:=StProcTransaction;
StProc.Transaction.StartTransaction;
StProc.StoredProcName:='Z_SETUP_S';
StProc.Prepare;
StProc.ExecProc;
CurrKodSetup:=StProc.ParamByName('gr_kod_setup').AsInteger;
StProc.Transaction.Commit;
//CurrentKodSetup(PDb_Handle);
YearSpinEdit.Value := YearMonthFromKodSetup(CurrKodSetup);
MonthesList.ItemIndex := YearMonthFromKodSetup(CurrKodSetup,False)-1;
DateEdit.EditValue:=ConvertKodToDate(CurrKodSetup+1)-1;
// DateEdit.Properties.MinDate:=ConvertKodToDate();
// DateEdit.Properties.MaxDate:=ConvertKodToDate(PParameter.Kod_Setup2+1)-1;
//******************************************************************************
if((PNum_predpr=2)or(PNum_predpr=3)or(PNum_predpr=4)or(PNum_predpr=7)or(PNum_predpr=5))then
begin
cxLabel1.Visible:=false;
MaskEditPM.Visible:=false;
cxLabel2.Visible:=false;
MaskEditPercent.Visible:=false;
CheckBoxVidOpl.Visible:=false;
BoxVidOpl.Visible:=false;
CheckBoxDepartment.Visible:=false;
BoxDepartment.Visible:=false;
//CheckBoxSmeta.Visible:=false;
//BoxSmeta.Visible:=false;
CheckBoxKatStud.Visible:=false;
CheckBoxKurs.Visible:=false;
BoxCatStud.Visible:=false;
CheckBoxProp.Visible:=false;
BoxProp.Visible:=false;
CheckBoxIsDelete.Visible:=true;
CheckBoxSmeta.Top:=36;
CheckBoxSmeta.Left:=-1;
BoxSmeta.Top:=54;
BoxSmeta.Left:=-2;
BtnOk.Top:=95;
BtnCancel.Top:=95;
self.Height:=160;
end else
begin
try
DSetCatStud.SQLs.SelectSQL.Text := 'SELECT * FROM GR_CN_STUD_CAT_S';
DSetCatStud.Open;
DSetPM.SQLs.SelectSQL.Text := 'SELECT * FROM Z_GET_CONST_SUM(1,'+IntToStr(CurrKodSetup)+',''T'')';
DSetPM.Open;
DSetProp.SQLs.SelectSQL.Text := 'SELECT * FROM Z_SP_PEOPLE_PROP_SEL(''T'')';
DsetProp.Open;
PropEdit.Properties.ListFieldNames := 'NAME_PEOPLE_PROP';
PropEdit.Properties.KeyFieldNames :='ID_PEOPLE_PROP';
PropEdit.Properties.DataController.DataSource := DSourceProp;
except
on E:Exception do
begin
grShowMessage(ECaption[PLanguageIndex],e.Message,mtError,[mbOK]);
end;
end;
MaskEditPM.Text:=DSetPM['VALUE_SUM'];
end;
end;
procedure TFIndexCount.CheckBoxVidOplClick(Sender: TObject);
begin
EditVidOpl.Enabled:=not EditVidOpl.Enabled;
LabelVidOplData.Enabled:=not LabelVidOplData.Enabled;
end;
procedure TFIndexCount.CheckBoxDepartmentClick(Sender: TObject);
begin
EditDepartment.Enabled :=not EditDepartment.Enabled;
LabelDepartmentData.Enabled :=not LabelDepartmentData.Enabled;
DateEdit.Enabled :=not DateEdit.Enabled;
end;
procedure TFIndexCount.CheckBoxSmetaClick(Sender: TObject);
begin
EditSmeta.Enabled:=not EditSmeta.Enabled;
LabelSmetaData.Enabled:=not LabelSmetaData.Enabled;
end;
procedure TFIndexCount.CheckBoxKatStudClick(Sender: TObject);
begin
ComboBoxCategory.Enabled:=not ComboBoxCategory.Enabled;
end;
procedure TFIndexCount.EditVidOplExit(Sender: TObject);
var VidOpl:Variant;
begin
if EditVidOpl.Text<>'' then
begin
VidOpl:=VoByKod(StrToInt(EditVidOpl.Text),date,PDb_Handle,ValueFieldZSetup(PDb_Handle,'GR_ID_SYSTEM'),0);
if VarArrayDimCount(VidOpl)>0 then
begin
PId_VidOpl:=VidOpl[0];
LabelVidOplData.Caption := VidOpl[2];
end
else
EditVidOpl.SetFocus;
end;
end;
procedure TFIndexCount.EditVidOplPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var VidOpl:Variant;
begin
VidOPl:=LoadVidOpl(self,
PDb_Handle,zfsModal,
0,
ValueFieldZSetup(PDb_Handle,'GR_ID_SYSTEM'));
if VarArrayDimCount(VidOpl)>0 then
begin
PId_VidOpl:=VidOpl[0];
LabelVidOplData.Caption := VidOpl[1];
EditVidOpl.Text := VarToStrDef(VidOpl[2],'');
end
else
EditVidOpl.SetFocus;
end;
procedure TFIndexCount.EditDepartmentExit(Sender: TObject);
var Department:Variant;
begin
if EditDepartment.Text<>PCode_department then
begin
Department:=DepartmentByKod(EditDepartment.Text,PDb_Handle);
if VarArrayDimCount(Department)>0 then
begin
PId_department:=Department[0];
LabelDepartmentData.Caption := Department[2];
end
else
EditDepartment.SetFocus;
end;
end;
procedure TFIndexCount.EditDepartmentPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var sp: TSprav;
begin
sp := GetSprav('SpDepartment');
if sp <> nil then
begin
// заполнить входные параметры
with sp.Input do
begin
Append;
FieldValues['DBHandle'] := Integer(PDb_Handle);
FieldValues['ShowStyle'] := 0;
FieldValues['Select'] := 1;
FieldValues['Actual_Date'] := DateEdit.EditValue;
Post;
end;
end;
sp.Show;
if sp.Output = nil then
ShowMessage('BUG: Output is NIL!!!')
else
if not sp.Output.IsEmpty then
begin
EditDepartment.Text := varToStrDef(sp.Output['DEPARTMENT_CODE'],'');
LabelDepartmentData.Caption := varToStrDef(sp.Output['NAME_FULL'],'');
PId_department := sp.Output['ID_DEPARTMENT'];
PCode_department := EditDepartment.Text;
end;
sp.Free;
end;
procedure TFIndexCount.EditSmetaPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var Smeta:Variant;
begin
Smeta:=GetSmets(self,PDB_Handle,Date,psmSmet);
if VarArrayDimCount(Smeta)> 0 then
if Smeta[0]<>NULL then
begin
PId_smeta := Smeta[0];
EditSmeta.Text := VarToStrDef(Smeta[3],'');
LabelSmetaData.Caption := Smeta[2];
end;
end;
procedure TFIndexCount.EditSmetaExit(Sender: TObject);
var Smeta:Variant;
begin
if EditSmeta.Text<>'' then
begin
Smeta:=SmetaByKod(StrToInt(EditSmeta.Text),PDb_Handle);
if VarArrayDimCount(Smeta)>0 then
begin
PId_smeta:=Smeta[0];
LabelSmetaData.Caption := Smeta[2];
end
else
EditSmeta.SetFocus;
end;
end;
procedure TFIndexCount.BtnCancelClick(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TFIndexCount.BtnOkClick(Sender: TObject);
var PKod_setup:integer;
wf:TForm;
begin
PKod_Setup:=PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1);
if((PNum_predpr=2)or(PNum_predpr=3)or(PNum_predpr=4)or(PNum_predpr=7) or (PNum_predpr=5))then
begin
wf:=gr_uWaitForm.ShowWaitForm(self,wfSelectData);
try
StProc.StoredProcName:='GR_COUNT_INDEX_FULL';
StProc.Transaction.StartTransaction;
StProc.Prepare;
StProc.ParamByName('KOD_SETUP').AsInteger :=PKod_setup;
StProc.ParamByName('IS_FLAG').AsString :=CheckBoxIsDelete.EditValue;
if(CheckBoxSmeta.Checked=true)then
StProc.ParamByName('IN_ID_SMETA').AsInteger :=PId_smeta;
if(TgrIndexacParam(PParam).id_man <> null)then
StProc.ParamByName('id_man_IN').AsInteger :=TgrIndexacParam(PParam).id_man
else StProc.ParamByName('id_man_IN').AsInteger :=-1;
StProc.ExecProc;
StProc.Transaction.Commit;
except
on E:Exception do
begin
grShowMessage(ECaption[PLanguageIndex],e.Message,mtError,[mbOK]);
end;
end;
CloseWaitForm(wf);
end else
begin
try
StProc.StoredProcName:='GR_COUNT_INDEX';
StProc.Transaction.StartTransaction;
StProc.Prepare;
StProc.ParamByName('KOD_SETUP').AsInteger :=PKod_setup;
StProc.ParamByName('PERCENT').AsCurrency :=StrToFloat(MaskEditPercent.Text);
StProc.ParamByName('SUMMA_PM').AsCurrency :=StrToFloat(MaskEditPM.Text);
if(CheckBoxVidOpl.Checked=true)then
StProc.ParamByName('ID_VIDOPL').AsInteger :=PId_VidOpl;
if(CheckBoxDepartment.Checked=true)then
StProc.ParamByName('ID_DEPARTMENT').AsInteger :=PId_department;
if(CheckBoxSmeta.Checked=true)then
StProc.ParamByName('ID_SMETA').AsInteger :=PId_smeta;
if(CheckBoxKatStud.Checked=true)then
StProc.ParamByName('ID_KAT_STUD').AsInteger :=ComboBoxCategory.EditValue;
if(CheckBoxKurs.Checked=true)then
StProc.ParamByName('KURS').AsInteger :=EditKurs.Value;
if(CheckBoxProp.Checked=true)then
begin
DSetProp.Locate('NAME_PEOPLE_PROP',PropEdit.text,[] );
StProc.ParamByName('ID_PEOPLE_PROP').AsInteger :=DSetProp['ID_PEOPLE_PROP'];
end;
StProc.ExecProc;
StProc.Transaction.Commit;
except
on E:Exception do
begin
grShowMessage(ECaption[PLanguageIndex],e.Message,mtError,[mbOK]);
end;
end;
end;
if (TgrIndexacParam(PParam).id_man = null) then
grShowMessage('Завершення','Операцію було завершено!',mtInformation,[mbOk]);
ModalResult:=mrYes
end;
procedure TFIndexCount.YearSpinEditPropertiesChange(Sender: TObject);
var PKod_Setup:Integer;
begin
PKod_Setup:=PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1);
if DSetPM.Active=true then
begin
DSetPM.Close;
DSetPM.SQLs.SelectSQL.Text := 'SELECT * FROM Z_GET_CONST_SUM(1,'+IntToStr(PKod_Setup)+',''T'')';
DSetPM.Open;
MaskEditPM.Text:=DSetPM['VALUE_SUM'];
end;
end;
procedure TFIndexCount.CheckBoxPropClick(Sender: TObject);
begin
PropEdit.Enabled:=not PropEdit.Enabled;
end;
procedure TFIndexCount.CheckBoxKursClick(Sender: TObject);
begin
Editkurs.Enabled:=not Editkurs.Enabled;
end;
end.
|
unit DataSet.Types;
interface
uses
System.Rtti,
Data.DB;
type
TFieldToGet = record
FieldName: string;
IsBitmap: Boolean;
end;
TFieldsToGet = array of TFieldToGet;
TFieldsToGetHelper = record helper for TFieldsToGet
public
procedure AddData(const AFieldName: string; const AIsBitmap: Boolean = False);
end;
TFieldConverter = record
FieldName: string;
FieldValue: TValue;
end;
TFieldConverters = array of TFieldConverter;
TFieldConvertersHelper = record helper for TFieldConverters
public
procedure AddData(const AFieldName: string; AValue: TValue);
end;
implementation
{ TFieldConvertersHelper }
procedure TFieldConvertersHelper.AddData(const AFieldName: string; AValue: TValue);
var
LCnt: Integer;
begin
LCnt := Length(Self);
SetLength(Self, LCnt + 1);
Self[LCnt].FieldName := AFieldName;
Self[LCnt].FieldValue := AValue;
end;
{ TFieldsToGetHelper }
procedure TFieldsToGetHelper.AddData(const AFieldName: string; const AIsBitmap: Boolean = False);
var
LCnt: Integer;
begin
LCnt := Length(Self);
SetLength(Self, LCnt + 1);
Self[LCnt].FieldName := AFieldName;
Self[LCnt].IsBitmap := AIsBitmap;
end;
end.
|
unit PCI1751;
interface
{ Функции для работы с портами ввода/вывода }
function Inp32(PortAdr: Word): Byte; stdcall; external 'inpout32.dll';
function Out32(wAddr: Word; bOut: Byte): Byte; stdcall; external 'inpout32.dll';
const
PCI1751_VEN_DEV = 'VEN_13FE&DEV_1751';
type
// TPort = (P0, P1);
// TPortAll = (PA0, PA1, PB0, PB1, PC0_L, PC0_H, PC1_L, PC1_H);
TPortIndex1 = 0..1;
TPortIndex2 = 0..7;
// TPortMode = (pmIN, pmOUT);
TPCI1751 = class(TObject)
private
fFriendlyName: string;
procedure Reset;
function GetPA0(Index: TPortIndex2): Byte;
function GetPA1(Index: TPortIndex2): Byte;
function GetPB0(Index: TPortIndex2): Byte;
function GetPB1(Index: TPortIndex2): Byte;
function GetPC0(Index: TPortIndex2): Byte;
function GetPC1(Index: TPortIndex2): Byte;
procedure SetPA0(Index: TPortIndex2; const Value: Byte);
procedure SetPA1(Index: TPortIndex2; const Value: Byte);
procedure SetPB0(Index: TPortIndex2; const Value: Byte);
procedure SetPB1(Index: TPortIndex2; const Value: Byte);
procedure SetPC0(Index: TPortIndex2; const Value: Byte);
procedure SetPC1(Index: TPortIndex2; const Value: Byte);
function ReadP0_Mode: Byte;
function ReadP1_Mode: Byte;
procedure WriteP0_Mode(const Value: Byte);
procedure WriteP1_Mode(const Value: Byte);
function GetPA(Index1: TPortIndex1; Index2: TPortIndex2): Byte;
function GetPB(Index1: TPortIndex1; Index2: TPortIndex2): Byte;
function GetPC(Index1: TPortIndex1; Index2: TPortIndex2): Byte;
procedure SetPA(Index1: TPortIndex1; Index2: TPortIndex2;
const Value: Byte);
procedure SetPB(Index1: TPortIndex1; Index2: TPortIndex2;
const Value: Byte);
procedure SetPC(Index1: TPortIndex1; Index2: TPortIndex2;
const Value: Byte);
protected
fBaseAddr: Int64;
fEmulation: Boolean;
public
constructor Create(const BaseAddr: Int64 = 0);
destructor Destroy; override;
// procedure SetPortMode(Port: TPort; bMode: Byte); overload;
// procedure SetPortMode(Port: TPortAll; Mode: TPortMode); overload;
property BaseAddr: Int64 read fBaseAddr;
property FriendlyName: string read fFriendlyName;
property Emulation: Boolean read fEmulation;
property PA0[Index: TPortIndex2]: Byte read GetPA0 write SetPA0;
property PB0[Index: TPortIndex2]: Byte read GetPB0 write SetPB0;
property PC0[Index: TPortIndex2]: Byte read GetPC0 write SetPC0;
property PA1[Index: TPortIndex2]: Byte read GetPA1 write SetPA1;
property PB1[Index: TPortIndex2]: Byte read GetPB1 write SetPB1;
property PC1[Index: TPortIndex2]: Byte read GetPC1 write SetPC1;
property PA[Index1: TPortIndex1; Index2: TPortIndex2]: Byte read GetPA write SetPA;
property PB[Index1: TPortIndex1; Index2: TPortIndex2]: Byte read GetPB write SetPB;
property PC[Index1: TPortIndex1; Index2: TPortIndex2]: Byte read GetPC write SetPC;
property P0_Mode: Byte read ReadP0_Mode write WriteP0_Mode;
property P1_Mode: Byte read ReadP1_Mode write WriteP1_Mode;
end;
implementation
uses
DeviceDetect;
{ TPCI1751 }
constructor TPCI1751.Create(const BaseAddr: Int64);
var
List: TDetectedDeviceList;
begin
inherited Create;
if BaseAddr <> 0 then
fBaseAddr := BaseAddr
else
begin
List := TDetectedDeviceList.Create;
getDevicesWDM(List, PCI1751_VEN_DEV, 'PCI');
if List.Count > 0 then
begin
fFriendlyName := List[0].friendlyName;
fBaseAddr := List[0].portStart;
Reset;
end
else
begin
fBaseAddr := 0;
fFriendlyName := '';
end;
List.Free;
end;
fEmulation := fBaseAddr <= 0;
end;
function TPCI1751.GetPA0(Index: TPortIndex2): Byte;
begin
Result := GetPA(0, Index);
end;
function TPCI1751.GetPA1(Index: TPortIndex2): Byte;
begin
Result := GetPA(1, Index);
end;
function TPCI1751.GetPB0(Index: TPortIndex2): Byte;
begin
Result := GetPB(0, Index);
end;
function TPCI1751.GetPB1(Index: TPortIndex2): Byte;
begin
Result := GetPB(1, Index);
end;
function TPCI1751.GetPC0(Index: TPortIndex2): Byte;
begin
Result := GetPC(0, Index);
end;
function TPCI1751.GetPC1(Index: TPortIndex2): Byte;
begin
Result := GetPC(1, Index);
end;
function TPCI1751.GetPA(Index1: TPortIndex1; Index2: TPortIndex2): Byte;
begin
if fEmulation then
begin
Result := 0;
Exit;
end;
case Index1 of
0: Result := (Inp32(fBaseAddr + 0) and (1 shl Index2));
1: Result := (Inp32(fBaseAddr + 4) and (1 shl Index2));
else
Result := 0;
end;
end;
function TPCI1751.GetPB(Index1: TPortIndex1; Index2: TPortIndex2): Byte;
begin
if fEmulation then
begin
Result := 0;
Exit;
end;
case Index1 of
0: Result := (Inp32(fBaseAddr + 1) and (1 shl Index2));
1: Result := (Inp32(fBaseAddr + 5) and (1 shl Index2));
else
Result := 0;
end;
end;
function TPCI1751.GetPC(Index1: TPortIndex1; Index2: TPortIndex2): Byte;
begin
if fEmulation then
begin
Result := 0;
Exit;
end;
case Index1 of
0: Result := Ord( (Inp32(fBaseAddr + 2) and (1 shl Index2)) <> 0);
1: Result := Ord( (Inp32(fBaseAddr + 6) and (1 shl Index2)) <> 0);
else
Result := 0;
end;
end;
procedure TPCI1751.SetPA0(Index: TPortIndex2; const Value: Byte);
begin
SetPA(0, Index, Value);
end;
procedure TPCI1751.SetPA1(Index: TPortIndex2; const Value: Byte);
begin
SetPA(1, Index, Value);
end;
procedure TPCI1751.SetPB0(Index: TPortIndex2; const Value: Byte);
begin
SetPB(0, Index, Value);
end;
procedure TPCI1751.SetPB1(Index: TPortIndex2; const Value: Byte);
begin
SetPB(1, Index, Value);
end;
procedure TPCI1751.SetPC0(Index: TPortIndex2; const Value: Byte);
begin
SetPC(0, Index, Value);
end;
procedure TPCI1751.SetPC1(Index: TPortIndex2; const Value: Byte);
begin
SetPC(1, Index, Value);
end;
procedure TPCI1751.SetPA(Index1: TPortIndex1; Index2: TPortIndex2;
const Value: Byte);
begin
if fEmulation then
Exit;
case Index1 of
0:
if Value = 0 then
Out32(fBaseAddr + 0, Inp32(fBaseAddr + 0) and not (1 shl Index2) ) // clear bit
else
Out32(fBaseAddr + 0, Inp32(fBaseAddr + 0) or (1 shl Index2) ); // set bit
1:
if Value = 0 then
Out32(fBaseAddr + 4, Inp32(fBaseAddr + 4) and not (1 shl Index2) ) // clear bit
else
Out32(fBaseAddr + 4, Inp32(fBaseAddr + 4) or (1 shl Index2) ); // set bit
end;
end;
procedure TPCI1751.SetPB(Index1: TPortIndex1; Index2: TPortIndex2;
const Value: Byte);
begin
if fEmulation then
Exit;
case Index1 of
0:
if Value = 0 then
Out32(fBaseAddr + 1, Inp32(fBaseAddr + 1) and not (1 shl Index2) ) // clear bit
else
Out32(fBaseAddr + 1, Inp32(fBaseAddr + 1) or (1 shl Index2) ); // set bit
1:
if Value = 0 then
Out32(fBaseAddr + 5, Inp32(fBaseAddr + 5) and not (1 shl Index2) ) // clear bit
else
Out32(fBaseAddr + 5, Inp32(fBaseAddr + 5) or (1 shl Index2) ); // set bit
end;
end;
procedure TPCI1751.SetPC(Index1: TPortIndex1; Index2: TPortIndex2;
const Value: Byte);
begin
if fEmulation then
Exit;
case Index1 of
0:
if Value = 0 then
Out32(fBaseAddr + 2, Inp32(fBaseAddr + 2) and not (1 shl Index2) ) // clear bit
else
Out32(fBaseAddr + 2, Inp32(fBaseAddr + 2) or (1 shl Index2) ); // set bit
1:
if Value = 0 then
Out32(fBaseAddr + 6, Inp32(fBaseAddr + 6) and not (1 shl Index2) ) // clear bit
else
Out32(fBaseAddr + 6, Inp32(fBaseAddr + 6) or (1 shl Index2) ); // set bit
end;
end;
function TPCI1751.ReadP0_Mode: Byte;
begin
if fEmulation then
begin
Result := 0;
Exit;
end;
Result := Inp32(fBaseAddr + 3);
end;
function TPCI1751.ReadP1_Mode: Byte;
begin
if fEmulation then
begin
Result := 0;
Exit;
end;
Result := Inp32(fBaseAddr + 7);
end;
procedure TPCI1751.WriteP0_Mode(const Value: Byte);
begin
if fEmulation then
Exit;
Out32(fBaseAddr + 3, Value);
end;
procedure TPCI1751.WriteP1_Mode(const Value: Byte);
begin
if fEmulation then
Exit;
Out32(fBaseAddr + 7, Value);
end;
//procedure TPCI1751.SetPortMode(Port: TPort; bMode: Byte);
//begin
// if fEmulation then
// Exit;
//
// case Port of
// P0: Out32(fBaseAddr + 3, bMode);
// P1: Out32(fBaseAddr + 7, bMode);
// end;
//end;
//
//procedure TPCI1751.SetPortMode(Port: TPortAll; Mode: TPortMode);
//var
// RegVal: Byte;
// NewRegVal: Byte;
//begin
// if fEmulation then
// Exit;
//
// case Port of
// PA0, PB0, PC0_L, PC0_H: RegVal := Inp32(fBaseAddr + 3);
// PA1, PB1, PC1_L, PC1_H: RegVal := Inp32(fBaseAddr + 7);
// end;
//
// case Mode of
// pmIN : // set bit
// case Port of
// PA0, PA1 : NewRegVal := RegVal or (1 shl 4);
// PB0, PB1 : NewRegVal := RegVal or (1 shl 1);
// PC0_L, PC1_L : NewRegVal := RegVal or (1 shl 0);
// PC0_H, PC1_H : NewRegVal := RegVal or (1 shl 3);
// end;
//
// pmOUT: // clear bit
// case Port of
// PA0, PA1 : NewRegVal := RegVal and not (1 shl 4);
// PB0, PB1 : NewRegVal := RegVal and not (1 shl 1);
// PC0_L, PC1_L : NewRegVal := RegVal and not (1 shl 0);
// PC0_H, PC1_H : NewRegVal := RegVal and not (1 shl 3);
// end;
// end;
//
// case Port of
// PA0, PB0, PC0_L, PC0_H: Out32(BaseAddr + 3, NewRegVal);
// PA1, PB1, PC1_L, PC1_H: Out32(BaseAddr + 7, NewRegVal);
// end;
//end;
destructor TPCI1751.Destroy;
begin
Reset;
inherited;
end;
procedure TPCI1751.Reset;
begin
// Configure ports - ALL IN
Out32(fBaseAddr + 3, $1B); // PA0 - in; PB0 - in; PC0 - in
Out32(fBaseAddr + 7, $1B); // PA1 - in; PB1 - in; PC1 - in
end;
end.
|
unit uModOrganization;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs,
uModApp, uModMember, uModSuplier, uModRekening;
type
TModOrganization = class(TModApp)
private
FORG_Address: string;
FORG_Code: string;
FORG_FEE: Double;
FORG_IsKaryawan: Integer;
FORG_IsMember: Integer;
FORG_IsSupplierMG: Integer;
FORG_Member: TModMember;
FORG_MerchandiseGroup: TModMerchandiseGroup;
FORG_Name: string;
FORG_NPWP: string;
FORG_PostCode: string;
FORG_PPN: Double;
FORG_Telp: string;
FOrg_Rekening_Hutang: TModRekening;
FOrg_Rekening_Piutang: TModRekening;
public
function GetARAccount(ShowException: Boolean = True): TModRekening;
function GetAPAccount(ShowException: Boolean = True): TModRekening;
class function GetTableName: string; override;
published
property ORG_Address: string read FORG_Address write FORG_Address;
[AttributeOfCode]
property ORG_Code: string read FORG_Code write FORG_Code;
property ORG_FEE: Double read FORG_FEE write FORG_FEE;
property ORG_IsKaryawan: Integer read FORG_IsKaryawan write FORG_IsKaryawan;
property ORG_IsMember: Integer read FORG_IsMember write FORG_IsMember;
property ORG_IsSupplierMG: Integer read FORG_IsSupplierMG write
FORG_IsSupplierMG;
property ORG_Member: TModMember read FORG_Member write FORG_Member;
property ORG_MerchandiseGroup: TModMerchandiseGroup read
FORG_MerchandiseGroup write FORG_MerchandiseGroup;
property ORG_Name: string read FORG_Name write FORG_Name;
property ORG_NPWP: string read FORG_NPWP write FORG_NPWP;
property ORG_PostCode: string read FORG_PostCode write FORG_PostCode;
property ORG_PPN: Double read FORG_PPN write FORG_PPN;
property ORG_Telp: string read FORG_Telp write FORG_Telp;
property Org_Rekening_Hutang: TModRekening read FOrg_Rekening_Hutang write
FOrg_Rekening_Hutang;
property Org_Rekening_Piutang: TModRekening read FOrg_Rekening_Piutang write
FOrg_Rekening_Piutang;
end;
implementation
function TModOrganization.GetARAccount(ShowException: Boolean = True):
TModRekening;
begin
Result := Self.Org_Rekening_Piutang;
if (ShowException) and (Result = nil) then
Raise Exception.Create('Organization ' + Self.ORG_Name + ' tidak memiki rekening piutang');
if (ShowException) and (Result.ID = '') then
Raise Exception.Create('Organization ' + Self.ORG_Name + ' tidak memiki rekening piutang');
end;
function TModOrganization.GetAPAccount(ShowException: Boolean = True):
TModRekening;
begin
Result := Self.Org_Rekening_Hutang;
if (ShowException) and (Result = nil) then
Raise Exception.Create('Organization ' + Self.ORG_Name + ' tidak memiki rekening hutang');
if (ShowException) and (Result.ID = '') then
Raise Exception.Create('Organization ' + Self.ORG_Name + ' tidak memiki rekening hutang');
end;
{
******************************* TModOrganization *******************************
}
class function TModOrganization.GetTableName: string;
begin
Result := 'V_ORGANIZATION';
end;
end.
|
unit Invoice.Model.Connection.Firedac;
interface
uses System.Classes, Data.DB, FireDAC.UI.Intf, FireDAC.VCLUI.Error,
FireDAC.Stan.Error, FireDAC.VCLUI.Wait, FireDAC.Phys.MSSQLDef, FireDAC.Phys,
FireDAC.Phys.ODBCBase, FireDAC.Phys.MSSQL, FireDAC.Comp.UI, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool,
FireDAC.Stan.Async, FireDAC.Comp.Client, Invoice.Controller.Interfaces;
type
TModelConnectionFiredac = class(TInterfacedObject, iModelConnection, iModelConnectionParametros)
private
class var FInstance: TModelConnectionFiredac;
FConnection: TFDConnection;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
FDPhysMSSQLDriverLink1: TFDPhysMSSQLDriverLink;
FDatabase: String;
FUserName: String;
FPassword: String;
FDriverID: String;
FServer: String;
FPorta: Integer;
procedure LerParametros;
public
constructor Create;
destructor Destroy; override;
class function New: iModelConnection;
function Database(Value: String): iModelConnectionParametros;
function UserName(Value: String): iModelConnectionParametros;
function Password(Value: String): iModelConnectionParametros;
function DriverID(Value: String): iModelConnectionParametros;
function Server(Value: String): iModelConnectionParametros;
function Porta(Value: Integer): iModelConnectionParametros;
function EndParametros: iModelConnection;
function Parametros: iModelConnectionParametros;
function Connection: TCustomConnection;
end;
implementation
uses
System.SysUtils, Vcl.Dialogs;
{ TModelConnectionFiredac }
constructor TModelConnectionFiredac.Create;
begin
FDPhysMSSQLDriverLink1 := TFDPhysMSSQLDriverLink.Create(nil);
FDGUIxWaitCursor1 := TFDGUIxWaitCursor.Create(nil);
FConnection := TFDConnection.Create(nil);
end;
destructor TModelConnectionFiredac.Destroy;
begin
FConnection.Close;
//
FConnection.Free;
FDGUIxWaitCursor1.Free;
FDPhysMSSQLDriverLink1.Free;
//
inherited;
end;
class function TModelConnectionFiredac.New: iModelConnection;
begin
if not Assigned(FInstance) then
FInstance := Self.Create;
//
Result := FInstance;
end;
function TModelConnectionFiredac.Connection: TCustomConnection;
begin
Result := TCustomConnection(FConnection);
//
if not FConnection.Connected then
begin
LerParametros;
//
FConnection.Open;
end;
end;
function TModelConnectionFiredac.DriverID(Value: String): iModelConnectionParametros;
begin
Result := Self;
//
FDriverID := Value;
end;
function TModelConnectionFiredac.Database(Value: String): iModelConnectionParametros;
begin
Result := Self;
//
FDatabase := Value;
end;
function TModelConnectionFiredac.EndParametros: iModelConnection;
begin
Result := Self;
end;
procedure TModelConnectionFiredac.LerParametros;
begin
FConnection.Params.Clear;
FConnection.Params.DriverID := FDriverID;
FConnection.Params.Database := FDatabase;
FConnection.Params.UserName := FUserName;
FConnection.Params.Password := FPassword;
FConnection.Params.Add('Server=' + FServer);
end;
function TModelConnectionFiredac.Parametros: iModelConnectionParametros;
begin
Result := Self;
end;
function TModelConnectionFiredac.Password(Value: String): iModelConnectionParametros;
begin
Result := Self;
//
FPassword := Value;
end;
function TModelConnectionFiredac.Porta(Value: Integer): iModelConnectionParametros;
begin
Result := Self;
//
FPorta := Value;
end;
function TModelConnectionFiredac.Server(Value: String): iModelConnectionParametros;
begin
Result := Self;
//
FServer := Value;
end;
function TModelConnectionFiredac.UserName(Value: String): iModelConnectionParametros;
begin
Result := Self;
//
FUserName := Value;
end;
end. |
unit ThStyleList;
interface
uses
SysUtils, Classes, Graphics;
type
TThStyleList = class(TStringList)
private
FExtraStyles: string;
protected
function GetHtmlStyles: string;
function GetStyleAttribute: string;
function GetThisList: TThStyleList;
public
procedure Add(const inName, inValue: string;
const inUnits: string = ''); reintroduce; overload;
procedure Add(const inName: string; inValue: Integer;
const inUnits: string = ''); reintroduce; overload;
procedure AddIf(inIf: Boolean; const inName: string; inValue: Integer;
const inUnits: string = '');
procedure AddIfNotZero(const inName: string; inValue: Integer;
const inUnits: string = '');
procedure AddColor(const inName: string;
inValue: TColor);
property ExtraStyles: string read FExtraStyles write FExtraStyles;
property HtmlStyles: string read GetHtmlStyles;
property StyleAttribute: string read GetStyleAttribute;
property ThisList: TThStyleList read GetThisList;
end;
implementation
uses
ThCssStyle;
{ TThStyleList }
procedure TThStyleList.Add(const inName, inValue: string;
const inUnits: string = '');
begin
if inValue <> '' then
Add(inName + '=' + inValue + inUnits);
end;
procedure TThStyleList.Add(const inName: string; inValue: Integer;
const inUnits: string);
begin
Add(inName, IntToStr(inValue), inUnits);
end;
procedure TThStyleList.AddColor(const inName: string; inValue: TColor);
begin
if ThVisibleColor(inValue) then
Add(inName, ThColorToHtml(inValue));
end;
procedure TThStyleList.AddIf(inIf: Boolean; const inName: string;
inValue: Integer; const inUnits: string);
begin
if inIf then
Add(inName, inValue, inUnits);
end;
procedure TThStyleList.AddIfNotZero(const inName: string; inValue: Integer;
const inUnits: string);
begin
if inValue <> 0 then
Add(inName, inValue, inUnits);
end;
function TThStyleList.GetHtmlStyles: string;
var
i: Integer;
begin
Result := '';
for i := 0 to Pred(Count) do
Result := Result + Names[i] + ':' + Values[Names[i]] + '; ';
Result := Trim(Result + ExtraStyles);
end;
function TThStyleList.GetStyleAttribute: string;
begin
Result := GetHtmlStyles;
if Result <> '' then
Result := ' style="' + Result + '"';
end;
function TThStyleList.GetThisList: TThStyleList;
begin
Result := Self;
end;
end.
|
unit uParentWizard;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, ComCtrls, StdCtrls, ImgList, siComp;
type
TUpdatePage = (upFirst, upBack, upNext);
TParentWizard = class(TForm)
PTitle: TPanel;
ShapeImage: TShape;
lbEditName: TLabel;
lbEditDescription: TLabel;
ImageClass: TImage;
Panel1: TPanel;
btBack: TButton;
btNext: TButton;
btClose: TButton;
pgOption: TPageControl;
btHelp: TButton;
imgSmall: TImageList;
bvBottom: TBevel;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btBackClick(Sender: TObject);
procedure btNextClick(Sender: TObject);
procedure btCloseClick(Sender: TObject);
private
procedure UpdateButtons;
procedure UpdatePage(AUpdatePage: TUpdatePage);
protected
FLogError: TStringList;
FTabList: TStringList;
procedure OnAfterDoFinish; virtual;
procedure OnBeforeBackClick; virtual;
function DoFinish: Integer; virtual; abstract;
function TestBeforeNavigate: Boolean; virtual;
function OnAfterChangePage: Boolean; virtual;
function OnBeforeNextClick : Boolean; virtual;
public
function Start: Boolean; virtual;
property LogError: TStringList read FLogError write FLogError;
end;
implementation
{$R *.DFM}
procedure TParentWizard.OnBeforeBackClick;
begin
// para ser herdado
end;
procedure TParentWizard.OnAfterDoFinish;
begin
// para ser herdado
end;
function TParentWizard.OnAfterChangePage: Boolean;
begin
Result := True;
end;
function TParentWizard.TestBeforeNavigate: Boolean;
begin
Result := True;
end;
procedure TParentWizard.UpdatePage(AUpdatePage: TUpdatePage);
var
i, iPage : Integer;
begin
with pgOption do
begin
iPage := 0;
case AUpdatePage of
upFirst: ActivePageIndex := 0;
upBack: begin
for i := (ActivePageIndex-1) downto 0 do
begin
inc(iPage);
if pgOption.Pages[i].TabVisible then
begin
ActivePageIndex := ActivePageIndex - iPage;
Break;
end;
end;
end;
upNext: begin
for i := (ActivePageIndex+1) to pgOption.PageCount-1 do
begin
inc(iPage);
if pgOption.Pages[i].TabVisible then
begin
ActivePageIndex := ActivePageIndex + iPage;
Break;
end;
end;
end;
end;
lbEditName.Caption := ActivePage.Caption;
lbEditDescription.Caption := ActivePage.Hint;
end;
end;
function TParentWizard.Start: Boolean;
var
iPageIndex: Integer;
begin
pgOption.Left := 0;
pgOption.Top := 41;
UpdatePage(upFirst);
UpdateButtons;
FTabList.Clear;
for iPageIndex := 0 to Pred(pgOption.PageCount) do
FTabList.Add(IntToStr(pgOption.Pages[iPageIndex].PageIndex));
ShowModal;
Result := FLogError.Text <> '';
end;
procedure TParentWizard.FormCreate(Sender: TObject);
begin
inherited;
FLogError := TStringList.Create;
FTabList := TStringList.Create;
end;
procedure TParentWizard.btCloseClick(Sender: TObject);
begin
inherited;
Close;
end;
procedure TParentWizard.btNextClick(Sender: TObject);
begin
inherited;
OnBeforeNextClick;
if pgOption.ActivePageIndex = Pred(pgOption.PageCount) then
begin
DoFinish;
OnAfterDoFinish;
Close;
end
else if TestBeforeNavigate then
begin
UpdatePage(upNext);
UpdateButtons;
OnAfterChangePage;
end;
end;
procedure TParentWizard.btBackClick(Sender: TObject);
begin
inherited;
OnBeforeBackClick;
UpdatePage(upBack);
UpdateButtons;
end;
procedure TParentWizard.FormDestroy(Sender: TObject);
begin
FreeAndNil(FLogError);
FreeAndNil(FTabList);
inherited;
end;
procedure TParentWizard.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TParentWizard.UpdateButtons;
var
bFirstPage, bLastPage: Boolean;
begin
bFirstPage := pgOption.ActivePageIndex = 0;
bLastPage := pgOption.ActivePageIndex = Pred(pgOption.PageCount);
btBack.Enabled := (not bFirstPage) and (not bLastPage);
if bLastPage then
btNext.Caption := '&Finish'
else
btNext.Caption := '&Next >';
end;
function TParentWizard.OnBeforeNextClick: Boolean;
begin
//
end;
end.
|
unit uCollectionEvents;
interface
uses
System.Classes,
System.SysUtils,
UnitDBDeclare,
uMemory,
uDBForm;
type
DBChangesIDEvent = procedure(Sender: TObject; ID: Integer; Params: TEventFields; Value: TEventValues) of object;
type
DBEventsIDArray = record
Sender: TObject;
IDs: Integer;
DBChangeIDArrayesEvents: DBChangesIDEvent;
end;
type
TDBEventsIDArray = array of DBEventsIDArray;
TCollectionEvents = class
private
FEvents: TDBEventsIDArray;
public
procedure UnRegisterChangesID(Sender: TObject; Event_: DBChangesIDEvent);
procedure UnRegisterChangesIDByID(Sender: TObject; Event_: DBChangesIDEvent; Id: Integer);
procedure RegisterChangesID(Sender: TObject; Event_: DBChangesIDEvent);
procedure RegisterChangesIDbyID(Sender: TObject; Event_: DBChangesIDEvent; Id: Integer);
procedure DoIDEvent(Sender: TDBForm; ID: Integer; Params: TEventFields; Value: TEventValues);
end;
function CollectionEvents: TCollectionEvents;
implementation
var
FCollectionEvents: TCollectionEvents = nil;
function CollectionEvents: TCollectionEvents;
begin
if FCollectionEvents = nil then
FCollectionEvents := TCollectionEvents.Create;
Result := FCollectionEvents;
end;
procedure TCollectionEvents.UnRegisterChangesID(Sender: TObject; Event_: DBChangesIDEvent);
var
I, J: Integer;
begin
if Length(Fevents) = 0 then
Exit;
for I := 0 to Length(Fevents) - 1 do
begin
if (@Fevents[I].DBChangeIDArrayesEvents = @Event_) and (Fevents[I].Ids = -1) and (Sender = Fevents[I].Sender) then
begin
for J := I to Length(Fevents) - 2 do
Fevents[J] := Fevents[J + 1];
SetLength(Fevents, Length(Fevents) - 1);
Break;
end;
end;
end;
procedure TCollectionEvents.UnRegisterChangesIDByID(Sender: TObject; Event_: DBChangesIDEvent; Id: Integer);
var
I, J: Integer;
begin
if Length(Fevents) = 0 then
Exit;
for I := 0 to Length(Fevents) - 1 do
if (@Fevents[I].DBChangeIDArrayesEvents = @Event_) and (Fevents[I].Ids = Id) and (Sender = Fevents[I].Sender) then
begin
for J := I to Length(Fevents) - 2 do
Fevents[J] := Fevents[J + 1];
SetLength(Fevents, Length(Fevents) - 1);
Break;
end;
end;
procedure TCollectionEvents.DoIDEvent(Sender: TDBForm; ID: Integer; Params: TEventFields; Value: TEventValues);
begin
TThread.Synchronize(nil,
procedure
var
I: Integer;
FXevents: TDBEventsIDArray;
begin
if Length(Fevents) = 0 then
Exit;
SetLength(FXevents, Length(Fevents));
for I := 0 to Length(Fevents) - 1 do
FXevents[I] := Fevents[I];
for I := 0 to Length(FXevents) - 1 do
begin
if FXevents[I].Ids = -1 then
begin
if Assigned(FXevents[I].DBChangeIDArrayesEvents) then
FXevents[I].DBChangeIDArrayesEvents(Sender, ID, Params, Value)
end else
begin
if FXevents[I].Ids = ID then
begin
if Assigned(FXevents[I].DBChangeIDArrayesEvents) then
FXevents[I].DBChangeIDArrayesEvents(Sender, ID, Params, Value)
end;
end;
end;
end
);
end;
procedure TCollectionEvents.RegisterChangesID(Sender: TObject; Event_: DBChangesIDEvent);
var
I: Integer;
Is_: Boolean;
begin
Is_ := False;
for I := 0 to Length(Fevents) - 1 do
if (@Fevents[I].DBChangeIDArrayesEvents = @Event_) and (Fevents[I].Ids = -1) and (Sender = Fevents[I].Sender) then
begin
Is_ := True;
Break;
end;
if not Is_ then
begin
Setlength(Fevents, Length(Fevents) + 1);
Fevents[Length(Fevents) - 1].Ids := -1;
Fevents[Length(Fevents) - 1].Sender := Sender;
Fevents[Length(Fevents) - 1].DBChangeIDArrayesEvents := Event_;
end;
end;
procedure TCollectionEvents.RegisterChangesIDByID(Sender: TObject; Event_: DBChangesIDEvent; Id: Integer);
var
I: Integer;
Is_: Boolean;
begin
Is_ := False;
for I := 0 to Length(Fevents) - 1 do
if (@Fevents[I].DBChangeIDArrayesEvents = @Event_) and (Fevents[I].Ids = Id) and (Sender = Fevents[I].Sender) then
begin
Is_ := True;
Break;
end;
if not Is_ then
begin
Setlength(Fevents, Length(Fevents) + 1);
Fevents[Length(Fevents) - 1].Ids := Id;
Fevents[Length(Fevents) - 1].Sender := Sender;
Fevents[Length(Fevents) - 1].DBChangeIDArrayesEvents := Event_;
end;
end;
initialization
finalization
F(FCollectionEvents);
end.
|
(* Copyright 2018 B. Zoltán Gorza
*
* This file is part of Math is Fun!, released under the Modified BSD License.
*)
{ Basic IO functions specifically for terminal/command line use, using Crt. }
unit NumberIO;
{$mode objfpc}
{$H+}
interface
uses
ExpressionClass,
StatisticsClass,
GameClass;
type
{ Simple supporting class for menu-generating and handling. }
TMenuItem = record
{ Text }
txt: String;
{ Procedure }
pro: procedure;
end;
{ A 2 long array used for displaying meaningful representations of the
value. }
TBooleanStrings = Array[0..1] of String[5];
{ General dynamic string array. }
TStringArray = Array of String;
const
{ Set of numberic characters }
KEYS_NUMBERS = [#48, #49, #50, #51, #52, #53, #54, #55, #56, #57];
{ Set of lower case letter characters }
KEYS_LOWCHAR = [#97, #98, #99, #100, #101, #102, #103, #104, #105, #106,
#107, #108, #109, #110, #111, #112, #113, #114, #115, #116,
#117, #118, #119, #120, #121, #122];
{ Set of upper case letter characters }
KEYS_UPCHAR = [#65, #66, #67, #68, #69, #70, #71, #72, #73, #74, #75, #76,
#77, #78, #79, #80, #81, #82, #83, #84, #85, #86, #87, #88,
#89, #90];
{ Character code of <Return> }
KEY_RETURN = #13;
{ Character code of <Space> }
KEY_SPACE = #32;
{ Character code of <Backspace> }
KEY_BACKSPACE = #8;
{ Character code of '~' }
KEY_TILDE = #126;
{ Character code of '-' }
KEY_DASH = #45;
{ Character code of '_' }
KEY_UNDERSCORE = #95;
{ Character code of '.' }
KEY_POINT = #46;
{ Set of characters that are accepted as a "Select" command in menus.
(<Return>, <Space>) }
SELECT_KEYS = [KEY_RETURN, KEY_SPACE];
{ Character code of <Up> }
KEY_UP = #72;
{ Character code of <Down> }
KEY_DOWN = #80;
{ Character code of <Left> }
KEY_LEFT = #75;
{ Character code of <Right> }
KEY_RIGHT = #77;
{ Character code of <PAGE_UP> }
KEY_PAGE_UP = #73;
{ Character code of <PAGE_DOWN> }
KEY_PAGE_DOWN = #81;
{ The quit character. }
KEY_QUIT = 'q';
{ The halt character. }
KEY_HALT = #3;
{ Name of the program }
PROGRAM_NAME = 'Math is Fun!';
{ Version number of the program }
PROGRAM_VERSION = 'v0.1';
{ Developer (or developers) of the program }
PROGRAM_DEVELOPER = 'B. Zolta''n Gorza';
{ Contact info of the developer(s) }
PROGRAM_DEV_CONTACT = '(b.zoltan.gorza@gmail.com)';
{ The year in which the program was worked on }
PROGRAM_DATE = '2018';
{ Header's first line }
TEXT_HEADER: String = '';
//TEXT_HEADER = 'Math Is Fun v0.1 by B. Zolta''n Gorza (2018)';
{ Header's second line }
//TEXT_HEADER2 = 'Now published under Modified BSD!';
TEXT_HEADER2: String = '';
{ Header's first line's vertical position }
Y_HEADER = 1;
{ Header's second line's vertical position }
Y_HEADER2 = 2;
{ Minimum horizontal coordinate of the second header line }
X_MIN_HEAD = 55;
{ Minimum horizontal coordinate of the game area }
X_MIN = 1;
{ Minimum vertical coordinate of the game area }
Y_MIN = 4;
{ Maximum horizontal coordinate of the game area }
X_MAX = 80;
{ Maximum Vertical coordinate of the game area }
Y_MAX = 23;
{ The veri last line's vertical coordinate }
Y_LAST_LINE = 24;
{ Default Foreground Color (light gray) }
DEF_FCOLOR = 7;
{ Default Background Color (black) }
DEF_BCOLOR = 0;
{ Used in default filenames. }
FILENAME_PREFIX = 'MiF_';
{ Default string for boolean values. }
BOOLEAN_VALUES: TBooleanStrings = ('False', ' True');
{ Operation format values. }
OP_FORMAT_VALUES: TBooleanStrings = ('Short', ' Long');
{ Yes/No values }
YES_NO_VALUES: TBooleanStrings = (' <No>', '<Yes>');
{ It's the Beginning, where everything begins. }
procedure theBeginning;
{ Exit procedure...
I don't wanna write it anymore. That's it.
I quit. }
procedure thatsItIQuit;
{ Number reader function for doubles. If isThereDefault is set to True, then the
gotten value will be written and used.
@param(d Output variable)
@param(isThereDefault (default: False) }
procedure readNum(var d: Double;
const isThereDefault: Boolean = False); overload;
{ Number reader function for integers. If isThereDefault is set to True, then
the gotten value will be written and used.
The value can be increased or decreased by 1 with the cursor/arrow keys.
@param(i Output variable)
@param(isThereDefault (default: False) }
procedure readNum(var i: Integer;
const isThereDefault: Boolean = False); overload;
{ Number reader function. }
procedure readBool(var b: Boolean;
const values: TBooleanStrings);
{ @link(TExpression Expression) formatter procedure.
@seealso(expressionWriter)
@param(e Expression to be written)
@param(longOp Use long format of the operator (i.e. the 3 character
long name instead of the sign -- default: False).
@return(A string representation of an expression.) }
function expressionToString(const e: TExpression;
const longOp: Boolean = False;
const width: Byte = 0;
const idxFmt: String = '%d: '): String; inline;
{ @link(TExpression Expression) writer procedure.
@seealso(expressionToString)
@param(e Expression to be written)
@param(longOp Use long format of the operator (i.e. the 3 character
long name instead of the sign -- default: False).
@param(checkFirstTime If True, then it will write the current expression's
name along with the expression, giving a little bit of help. )}
procedure expressionWriter(const e: TExpression;
const longOp: Boolean = False;
const width: Byte = 0;
const idxFmt: String = '%d: ';
const checkFirstTime: Boolean = True); inline;
{ Set ups the default colors.
@seealso(DEF_FCOLOR)
@seealso(DEF_BCOLOR)
@param(invert Invert the default colors (default: @false)) }
procedure useDefaultColors(const invert: Boolean = False); inline;
{ Restores the game area and clears it. }
procedure restoreGameArea; inline;
{ Menu generator and writer procedure.
@param(item The used/wanted menu items.)
@param(menuXMin The minimum horizontal coordinate (default: @link(X_MIN).)
@param(menuYMin The minimum vertical coordinate (default: @link(Y_MIN).)
@param(menuXMax The maximum horizontal coordinate (default: @link(X_MAX).)
@param(menuYMax The maximum vertical coordinate (default: @link(Y_MAX).)
@param(step Number of line-breaks between items (default: 2). )
@param(indexFormat The format string for the index. )
@param(indexSeparator The separator character between the index and the text.)
}
procedure writeMenu(const items: Array of TMenuItem;
const menuXMin: Byte = X_MIN; // X_MIN should be 1
const menuYMin: Byte = Y_MIN; // Y_MIN should be 1
const menuXMax: Byte = X_MAX;
const menuYMax: Byte = Y_MAX;
const step: Byte = 2;
const indexFormat: String = '[%d]';
const indexSeparator: String = ' ');
{ Long text writer, and reader for long texts. The key bindings were inspired
by the "man" program of Linux.
It uses the @link(restoreGameArea) procedure for cleaning and defining area.
@param(txt The text to be read.)}
procedure writeLongText(const txt: String);
{ Generates a formatted string of the statistics. For special markers it uses
the @link(NEWLINECHAR) and @(TABCHAR) characters.
@param(g The current game)
@param(s The statistics to be stringified)
@param(sett Settings)
@param(longOp Setting of long operation)}
function statisticsTextGenerator(const g: TGame; nog: Integer;
const longOp: Boolean): String;
{ Writes a string into a file.
@param(s The stirng to be written.)
@param(fn The filename of the output. If it is empty, then a special filename
will be used, containing the @link(FILENAME_PREFIX), and the date
and time of creation.)}
procedure writeToFile(s: String; fn: String = '');
implementation // --------------------------------------------------------------
uses
Crt,
Math,
StrUtils,
SysUtils,
OperationClass;
var
isFirstTime: Array[TOp] of Boolean = (True, True, True, True, True, True);
procedure theBeginning;
begin
clrscr;
window(X_MIN, Y_HEADER, X_MAX, Y_HEADER);
textBackground(MAGENTA);
textColor(WHITE);
clrscr;
write(TEXT_HEADER);
window(X_MIN_HEAD, Y_HEADER2, X_MAX, Y_HEADER2 + 1);
textBackground(BLACK);
textColor(MAGENTA);
clrscr;
write(TEXT_HEADER2);
restoreGameArea;
end;
procedure thatsItIQuit;
const
QUIT_MSG = 'Are you sure that you want to quit? ';
QUIT_BUTTON = '<Yes>';
var
ch: Char;
begin
restoreGameArea;
cursoroff;
// Write aligned to mid
gotoxy(40 - length(QUIT_MSG + QUIT_BUTTON) div 2, 10);
write(QUIT_MSG);
useDefaultColors(True);
write(QUIT_BUTTON);
//gotoxy(wherex - length(QUIT_BUTTON) div 2 - 1, wherey);
useDefaultColors;
cursoron;
// Wait to the needed characters
repeat
ch := readkey;
until ch in SELECT_KEYS + ['y', 'Y', KEY_QUIT, KEY_HALT];
window(X_MIN, Y_HEADER, X_MAX, Y_MAX);
clrscr;
// Halt the program
halt(0);
end;
procedure readNum(var d: Double;
const isThereDefault: Boolean = False); overload;
var
s: String; // temporarily store the current input
x, ox: Byte; // the last position
c: Char; // current input char
procedure addChar(const ch: Char); inline;
begin
if length(s) < 15 then
begin
s += ch;
write(ch);
end;
end;
begin
ox := wherex;
if isThereDefault then
begin
s := floatToStr(d);
write(s);
end
else
s := '';
repeat
x := wherex;
c := readkey;
if c = KEY_HALT then
halt;
if c = KEY_BACKSPACE then
begin
if length(s) > 1 then
s := leftStr(s, length(s)-1)
else
s := '';
if x - ox > 0 then
begin
gotoxy(wherex - 1, wherey);
write(' ');
gotoxy(wherex - 1, wherey);
end;
continue;
end;
if c = KEY_DASH then
begin
if s = '' then
addChar(KEY_DASH);
end;
if c = KEY_POINT then
begin
if pos(KEY_POINT, s) = 0 then
begin
if (s <> '') and (s <> KEY_DASH) then
addChar(KEY_POINT)
else
begin
addChar('0');
addChar(KEY_POINT);
end;
end;
end;
if c in KEYS_NUMBERS then
addChar(c);
until (c = KEY_RETURN) and (s <> '');
if (pos(KEY_POINT, s) <> 0) and
(KEY_POINT <> defaultFormatSettings.decimalSeparator) then
s := replaceStr(s, KEY_POINT, defaultFormatSettings.decimalSeparator);
if s = KEY_DASH then
d := 0
else
d := strToFloat(s);
writeln;
end;
procedure readNum(var i: Integer;
const isThereDefault: Boolean = False); overload;
var
s: String; // temporarily store the current input
x, ox: Byte; // the last position
c: Char; // current input char
procedure addChar(const ch: Char); inline;
begin
if length(s) < 10 then // avoiding overflow
begin
s += ch;
write(ch);
end;
end;
begin
ox := wherex;
if isThereDefault then
begin
s := intToStr(i);
write(s);
end
else
s := '';
repeat
x := wherex;
c := readkey;
if c = #0 then
begin
if tryStrToInt(s, i) then
begin
c := readkey;
case c of
KEY_UP, KEY_LEFT: i -= 1;
KEY_DOWN, KEY_RIGHT: i += 1;
end;
gotoxy(ox, wherey);
write(stringOfChar(' ', length(s)));
gotoxy(ox, wherey);
s := intToStr(i);
write(s);
continue;
end;
end;
if c = KEY_HALT then
halt;
if c = KEY_BACKSPACE then
begin
if length(s) > 1 then
s := leftStr(s, length(s)-1)
else
s := '';
if x - ox > 0 then
begin
gotoxy(wherex - 1, wherey);
write(' ');
gotoxy(wherex - 1, wherey);
end;
continue;
end;
if c = KEY_DASH then
begin
if s = '' then
addChar(KEY_DASH);
end;
if c in KEYS_NUMBERS then
addChar(c);
until (c = KEY_RETURN) and (s <> '');
if (pos(KEY_POINT, s) <> 0) and
(KEY_POINT <> defaultFormatSettings.decimalSeparator) then
s := replaceStr(s, KEY_POINT, defaultFormatSettings.decimalSeparator);
if s = KEY_DASH then
i := 0
else
i := strToInt(s);
writeln;
end;
procedure readBool(var b: Boolean;
const values: TBooleanStrings);
var
idx: 0..1;
c: Char;
x, y: Byte;
begin
if b then
idx := 1
else
idx := 0;
x := wherex;
y := wherey;
write(values[idx]);
repeat
c := readkey;
case c of
#0: begin
c := readkey;
case c of
KEY_UP, KEY_LEFT: idx := (idx + 1) mod 2;
KEY_DOWN, KEY_RIGHT: idx := abs(idx - 1) mod 2;
end;
gotoxy(x, y);
write(values[idx]);
end;
'0', 'f', 'h', 'n': begin
idx := 0;
gotoxy(x, y);
write(values[idx]);
c := KEY_RETURN;
end;
'1', 't', 'i', 'y': begin
idx := 1;
gotoxy(x, y);
write(values[idx]);
c := KEY_RETURN;
end;
KEY_HALT: halt; // aborted by user
end;
until c in SELECT_KEYS;
writeln;
b := idx = 1;
end;
function strSplit(str: String; len: Byte): TStringArray;
const
NEWLINECHAR = '|';
TABCHAR = '~';
TABSEQUENCE = ' ';
var
tmpS, s: String;
tmpI: Integer;
tmpSA: TStringArray = NIL;
procedure addText;
begin
tmpI := length(tmpSA);
setLength(tmpSA, tmpI + 1);
tmpSA[tmpI] := tmpS;
tmpS := '';
end;
procedure addLine(const empty: Boolean = False);
begin
tmpI += 1;
setLength(strSplit, tmpI + 1);
strSplit[tmpI] := ifThen(not empty, s, '');
end;
begin
// initializing
str := trim(str);
tmpS := '';
// split the string by spaces, or max `len` long pieces
for s in str do
begin
if (s <> ' ') and (length(tmpS + s) <= len) then
begin
if s = NEWLINECHAR then
begin
addText;
tmpS += s;
addText;
end
else
begin
if s <> TABCHAR then
tmpS += s
else
tmpS += TABSEQUENCE;
end;
end
else
addText;
end;
addText;
tmpI := 0;
setLength(strSplit, tmpI + 1);
strSplit[tmpI] := '';
// put it back together
for s in tmpSA do
begin
if (length(strSplit[tmpI]) + length(s) + 1) <= len then
begin
if length(strSplit[tmpI]) <> 0 then
begin
if s <> NEWLINECHAR then
strSplit[tmpI] += ' ' + s
else
addLine(True);
end
else
begin
if s <> NEWLINECHAR then
strSplit[tmpI] += s
else
addLine(True);
end;
end
else
addLine;
end;
end;
function expressionToString(const e: TExpression;
const longOp: Boolean = False;
const width: Byte = 0;
const idxFmt: String = '%d: '): String; inline;
var
s: TStringArray;
c: Integer;
begin
if e.cat = arithmetic then
expressionToString := format(idxFmt + '%' + intToStr(width) + 'd %s %'
+ intToStr(width) + 'd = ',
[e.idx,
e.a,
ifThen(longOp, e.o.nam, e.o.sign),
e.b])
else
begin
s := strSplit(format(e.text + ' ', [e.a, e.b]), X_MAX);
for c := 0 to high(s) - 1 do
expressionToString += s[c] + stringOfChar(' ',
X_MAX - length(s[c]));
c += 1;
if length(s[c]) <> X_MAX then
expressionToString += s[c] + ' '
else
expressionToString += s[c];
end;
end;
procedure expressionWriter(const e: TExpression;
const longOp: Boolean = False;
const width: Byte = 0;
const idxFmt: String = '%d: ';
const checkFirstTime: Boolean = True); inline;
var
x, y: Byte;
begin
write(expressionToString(e, longOp, width, idxFmt));
if checkFirstTime and (isFirstTime[e.o.op]) then
begin
x := wherex;
y := wherey;
isFirstTime[e.o.op] := False;
gotoxy(40, y);
write(e.o.name);
gotoxy(x, y);
end;
end;
procedure useDefaultColors(const invert: Boolean = False); inline;
begin
if invert then
begin
textColor(DEF_BCOLOR);
textBackground(DEF_FCOLOR);
end
else
begin
textColor(DEF_FCOLOR);
textBackground(DEF_BCOLOR);
end;
end;
procedure restoreGameArea; inline;
begin
window(X_MIN, Y_MIN, X_MAX, Y_MAX);
useDefaultColors;
clrscr;
end;
procedure writeMenu(const items: Array of TMenuItem;
const menuXMin: Byte = X_MIN; // X_MIN should be 1
const menuYMin: Byte = Y_MIN; // Y_MIN should be 1
const menuXMax: Byte = X_MAX;
const menuYMax: Byte = Y_MAX;
const step: Byte = 2;
const indexFormat: String = '[%d]';
const indexSeparator: String = ' ');
var
i: Byte; // short for 'item'
lI: Byte; // short for 'last item' -- it's also a test for fonts
ch: Char;
validKeys: Set of Char = SELECT_KEYS; // SELECT_KEYS should be [#13, #32]
itemsLength: Byte;
procedure writeItem(const item: Byte; const highlight: Boolean;
const text: String = '');
begin
gotoxy(X_MIN, 1 + (item - 1) * step);
useDefaultColors(highlight);
write(format(indexFormat, [item]));
if text <> '' then
begin
useDefaultColors;
write(' ', text);
end // end of if
else
gotoxy(wherex - 2, wherey);
end; // end of procedure
begin
cursoroff;
itemsLength := length(items);
window(menuXMin, menuYMin, menuXMax, menuYMax);
for i := itemsLength downTo 1 do
begin
writeItem(i, False, items[i - 1].txt);
include(validKeys, chr(48 + i));
end;
writeItem(i, True);
repeat
lI := i;
ch := readkey;
case ch of
#0: begin
ch := readkey;
case ch of
KEY_UP, KEY_LEFT: i -= 1; // up, left
KEY_DOWN, KEY_RIGHT: i += 1; // down, right
end; // end of case of
if i < 1 then
i := itemsLength
else
begin
if i > itemsLength then
i := 1;
end; // end of else
writeItem(lI, False);
writeItem(i, True);
end; // end of case
end; // end of case of
until ch in validKeys;
if not (ch in SELECT_KEYS) then
i := ord(ch) - 48;
restoreGameArea;
cursoron;
items[i - 1].pro; // call the item's procedure
end;
procedure writeLongText(const txt: String);
const
USER_HELP = 'Press <q> to exit, <Left> or <Right> to navigate.';
HEIGHT = Y_MAX - Y_MIN;
var
split: TStringArray;
current_line: Integer;
ch: Char;
procedure writeLastLine; inline;
begin
window(X_MIN, Y_LAST_LINE, X_MAX, Y_LAST_LINE);
useDefaultColors(True);
clrscr;
write(USER_HELP);
end;
procedure clearLastLine; inline;
begin
window(X_MIN, Y_LAST_LINE, X_MAX, Y_LAST_LINE);
useDefaultColors;
clrscr;
end;
procedure writePage; inline;
var
c: Integer;
begin
clrscr;
for c := current_line to current_line + HEIGHT - 1 do
begin
if c < length(split) then
writeln(split[c]);
end;
if c + 1 < length(split) then
write(split[c + 1]);
end;
begin // --- writeLongText
writeLastLine;
restoreGameArea;
split := strSplit(txt, X_MAX);
current_line := 0;
repeat
writePage;
ch := readkey;
case ch of
#0: begin
ch := readkey;
case ch of
KEY_UP: current_line -= 5;
KEY_DOWN: current_line += 5;
KEY_LEFT, KEY_PAGE_UP: current_line -= HEIGHT + 1;
KEY_RIGHT, KEY_PAGE_DOWN: current_line += HEIGHT - 1;
end;
end;
KEY_RETURN: current_line += 1;
KEY_SPACE: current_line += HEIGHT;
KEY_HALT: halt;
end;
if current_line < 0 then
current_line := 0
else
begin
if current_line > high(split) then
current_line := high(split);
end;
until ch = KEY_QUIT;
clearLastLine;
restoreGameArea;
end;
function statisticsTextGenerator(const g: TGame; nog: Integer;
const longOp: Boolean): String;
const
GAME_TYPE: Array[0..1] of String = ('finite', 'infinite');
var
e: TExpression;
o: TOp;
oc: TOperationCategory;
tmpOA: TOpStatArray;
tmpOCA: TOpCatStatArray;
stg: String; // short for staisticsTextGenerator
tmpS: String;
tableHead: String;
tableRow: String;
tableAdditional: String;
w: String;
begin
w := intToStr(MAX_LEVEL); //intToStr(ifThen(nog > 0, nog, g.numberOfGames));
tableHead := '%:3s: %' + w + 's %' + w + 's %' + w + 's|';
tableRow := '~%s: %' + w + 'd %' + w + 'd %' + w + 'd';
tableAdditional := ' (%d%%)';
stg := 'This game was ' + GAME_TYPE[ord(nog <= 0)]
+ ' during which ' + intToStr(g.stats.count) + ' turn(s) has been '
+ 'played.||Used settings:|'
+ format('~%s: %d|~%s: %s|~%s: %d|~%s: %s|~%s: %s||',
['Number of games', nog,
'Include non-arithmetic',
trim(BOOLEAN_VALUES[ord(g.includeNonArithmetic)]),
'Level of difficulty', g.level,
'Include negative numbers',
trim(BOOLEAN_VALUES[ord(g.includeNegative)]),
'Operator format', trim(OP_FORMAT_VALUES[ord(longOp)])]);
{ + 'Number of expressions (by operation):|';
tmpOA := g.stats.numberOfOp;
for o in TOp do
stg += format('~%s: %d|', [OPERATIONS[ord(o)].nam, tmpOA[o]]);
stg += '|Correct answers by operation:|';
tmpOA := g.stats.correct;
for o in TOp do
stg += format('~%s: %d|', [OPERATIONS[ord(o)].nam, tmpOA[o]]);
stg += '|Wrong answers by operation:|';
tmpOA := g.stats.wrong;
for o in TOp do
stg += format('~%s: %d|', [OPERATIONS[ord(o)].nam, tmpOA[o]]);}
stg += '||Statistics by operation:|~';
tmpS := format(tableHead,
['op', '#',
resultToString(correct), resultToString(incorrect)]);
stg += tmpS;
stg += '~' + stringOfChar('-', length(tmpS)) + '|';
tmpOA := g.stats.numberOfOp;
for o in TOp do
begin
stg += format(tableRow,
[OPERATIONS[ord(o)].nam, tmpOA[o],
g.stats.correct[o], g.stats.wrong[o]]);
if tmpOA[o] <> 0 then
stg += format(tableAdditional,
[round(g.stats.correct[o]/tmpOA[o]*100)]);
stg += '|'
end;
if g.includeNonArithmetic then
begin
stg += '||Statistics by Category:|~';
tmpS := format(tableHead,
['op', '#',
resultToString(correct), resultToString(incorrect)]);
stg += tmpS;
stg += '~' + stringOfChar('-', length(tmpS)) + '|';
tmpOCA := g.stats.numberByCat;
for oc in TOperationCategory do
begin
stg += format(tableRow,
[OPERATIONS[ord(oc)].nam, tmpOCA[oc],
g.stats.correctByCat[oc], g.stats.wrongByCat[oc]]);
if tmpOCA[oc] <> 0 then
stg += format(tableAdditional,
[round(g.stats.correctByCat[oc]/tmpOCA[oc]*100)]);
stg += '|'
end;
end;
tableHead := '%-' + intToStr(g.level + ord(g.includeNegative)) + 'd';
tmpS := ': %' + w + 'd %s %' + w + 'd = %-5s user: %-15s %-15s %s|';
stg += '||List of expressions (in order):|';
for e in g.stats.expressions do
stg += format(tableHead + tmpS,
[e.idx, e.a,
ifThen(longOp, e.o.nam, e.o.sign), e.b, e.result,
e.userResult, resultToString(e.isCorrect),
categoryToString(e.cat)]);
stg += '||Thanks for playing ' + PROGRAM_NAME + ' (' + PROGRAM_VERSION
+ ')! We wish the best for you, and if you have not been the best '
+ 'player of all, then never forget: everything is gonna be better '
+ '(at least that is what they told me).||'
+ 'Generated at ' + formatDateTime('YYYY. MM. DD. hh:mm.', NOW);
statisticsTextGenerator := stg;
end;
function validateString(const s: String): String;
const
VALID = KEYS_LOWCHAR + [KEY_POINT] + KEYS_UPCHAR + KEYS_NUMBERS
+ [KEY_UNDERSCORE, KEY_DASH, KEY_TILDE];
var
c: Char;
begin
if s = '' then
exit('');
validateString := '';
for c in s do
begin
if c in VALID then
validateString += c;
end;
end;
procedure writeToFile(s: String; fn: String = '');
var
split: TStringArray;
f: TextFile;
begin
split := strSplit(s, X_MAX - X_MIN);
fn := validateString(fn);
if fn = '' then
fn := FILENAME_PREFIX
+ formatDateTime('YYYY_MM_DD_hh_mm_ss', NOW) + '.txt';
assignFile(f, fn);
try
rewrite(f);
for s in split do
writeln(f, s);
closeFile(f);
writeln(fn, ' has been written.');
except on e: EInOutError do
writeln('The file was not written due to unforeseen circumstances. ',
'Details: ', e.className, '/', e.message);
end;
end;
function randomTextHeader(): String;
const
texts: Array[1..10] of String = (
' Placeholder texts',
' TODO: put texts *here*.',
'Math is Fun! or is it not?',
'Art thou a master of Math?',
' Pascal wasn''t my idea',
'Uses Modified BSD License!',
' Hello? Is anyone there?',
' Leibniz was cool too.',
' HELP ME!',
' a.k.a. Ae. Dschorsaanjo'
);
var
r: Integer;
begin
r := random(length(texts)) + low(texts);
randomTextHeader := texts[r];
end;
initialization // --------------------------------------------------------------
TEXT_HEADER := format('%s %s (%s) by %s', [PROGRAM_NAME, PROGRAM_VERSION,
PROGRAM_DATE, PROGRAM_DEVELOPER]);
TEXT_HEADER2 := randomTextHeader();
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Basic editing frame for TVXTexture
}
{ TODO : Replace STImageClass with a dropdown (polymorphism) }
unit FRTextureEdit;
interface
uses
System.SysUtils,
System.Types,
System.UITypes,
System.TypInfo,
System.Classes,
System.Variants,
FMX.Types,
FMX.Graphics,
FMX.Controls,
FMX.Forms,
FMX.Dialogs,
FMX.StdCtrls,
FMX.ListBox,
FMX.Controls.Presentation,
VXS.Graphics,
VXS.TextureFormat,
VXS.Texture,
VXS.TextureImageEditors;
type
TRTextureEdit = class(TFrame)
LabelImage: TLabel;
SBEditImage: TSpeedButton;
CBMagFilter: TComboBox;
LabelImageAlpha: TLabel;
LabelTextureWrap: TLabel;
CBMinFilter: TComboBox;
CBTextureMode: TComboBox;
LabelMagFilter: TLabel;
LabelMinFilter: TLabel;
CBTextureWrap: TComboBox;
CBDisabled: TCheckBox;
CBImageClass: TComboBox;
CBImageAlpha: TComboBox;
LabelFilterQuality: TLabel;
CBFilteringQuality: TComboBox;
LabelTextureMode: TLabel;
procedure CBMagFilterChange(Sender: TObject);
procedure CBMinFilterChange(Sender: TObject);
procedure CBTextureModeChange(Sender: TObject);
procedure CBTextureWrapChange(Sender: TObject);
procedure CBDisabledClick(Sender: TObject);
procedure SBEditImageClick(Sender: TObject);
procedure CBImageClassChange(Sender: TObject);
procedure CBImageAlphaChange(Sender: TObject);
procedure CBFilteringQualityChange(Sender: TObject);
private
FTexture: TVXTexture;
FOnChange: TNotifyEvent;
Changeing: Boolean;
protected
procedure SetTexture(const val: TVXTexture);
procedure DoOnChange; virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Texture: TVXTexture read FTexture write SetTexture;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
//=====================================================================
implementation
//=====================================================================
{$R *.fmx}
constructor TRTextureEdit.Create(AOwner: TComponent);
var
I: Integer;
begin
inherited;
FTexture := TVXTexture.Create(Self);
SetTexture(FTexture);
SetTextureImageClassesToStrings(CBImageClass.Items);
for I := 0 to Integer(High(TVXTextureImageAlpha)) do
CBImageAlpha.Items.Add(GetEnumName(TypeInfo(TVXTextureImageAlpha), I));
for I := 0 to Integer(High(TVXMagFilter)) do
CBMagFilter.Items.Add(GetEnumName(TypeInfo(TVXMagFilter), I));
for I := 0 to Integer(High(TVXMinFilter)) do
CBMinFilter.Items.Add(GetEnumName(TypeInfo(TVXMinFilter), I));
for I := 0 to Integer(High(TVXTextureFilteringQuality)) do
CBFilteringQuality.Items.Add
(GetEnumName(TypeInfo(TVXTextureFilteringQuality), I));
for I := 0 to Integer(High(TVXTextureMode)) do
CBTextureMode.Items.Add(GetEnumName(TypeInfo(TVXTextureMode), I));
for I := 0 to Integer(High(TVXTextureWrap)) do
CBTextureWrap.Items.Add(GetEnumName(TypeInfo(TVXTextureWrap), I));
end;
destructor TRTextureEdit.Destroy;
begin
FTexture.Free;
inherited;
end;
procedure TRTextureEdit.SetTexture(const val: TVXTexture);
begin
FTexture.Assign(val);
Changeing := True;
try
with CBImageClass do
ItemIndex := Items.IndexOfObject(Pointer(FTexture.Image.ClassType));
CBImageAlpha.ItemIndex := Integer(FTexture.ImageAlpha);
CBMagFilter.ItemIndex := Integer(FTexture.MagFilter);
CBMinFilter.ItemIndex := Integer(FTexture.MinFilter);
CBFilteringQuality.ItemIndex := Integer(FTexture.FilteringQuality);
CBTextureMode.ItemIndex := Integer(FTexture.TextureMode);
CBTextureWrap.ItemIndex := Integer(FTexture.TextureWrap);
CBDisabled.IsChecked := FTexture.Disabled;
finally
Changeing := False;
DoOnChange;
end;
end;
procedure TRTextureEdit.DoOnChange;
begin
if (not Changeing) and Assigned(FOnChange) then
OnChange(Self);
end;
procedure TRTextureEdit.CBImageClassChange(Sender: TObject);
var
tic: TVXTextureImageClass;
ti: TVXTextureImage;
begin
if not Changeing then
begin
with CBImageClass do
tic := TVXTextureImageClass(Items.Objects[ItemIndex]);
if FTexture.Image.ClassType <> tic then
begin
ti := TVXTextureImageClass(tic).Create(FTexture);
FTexture.Image := ti;
ti.Free;
end;
DoOnChange;
end;
end;
procedure TRTextureEdit.CBImageAlphaChange(Sender: TObject);
begin
FTexture.ImageAlpha := TVXTextureImageAlpha(CBImageAlpha.ItemIndex);
DoOnChange;
end;
procedure TRTextureEdit.CBMagFilterChange(Sender: TObject);
begin
FTexture.MagFilter := TVXMagFilter(CBMagFilter.ItemIndex);
DoOnChange;
end;
procedure TRTextureEdit.CBMinFilterChange(Sender: TObject);
begin
FTexture.MinFilter := TVXMinFilter(CBMinFilter.ItemIndex);
DoOnChange;
end;
procedure TRTextureEdit.CBTextureModeChange(Sender: TObject);
begin
FTexture.TextureMode := TVXTextureMode(CBTextureMode.ItemIndex);
DoOnChange;
end;
procedure TRTextureEdit.CBTextureWrapChange(Sender: TObject);
begin
FTexture.TextureWrap := TVXTextureWrap(CBTextureWrap.ItemIndex);
DoOnChange;
end;
procedure TRTextureEdit.CBDisabledClick(Sender: TObject);
begin
FTexture.Disabled := CBDisabled.IsChecked;
DoOnChange;
end;
procedure TRTextureEdit.SBEditImageClick(Sender: TObject);
begin
EditTextureImage(FTexture.Image);
DoOnChange;
end;
procedure TRTextureEdit.CBFilteringQualityChange(Sender: TObject);
begin
FTexture.FilteringQuality := TVXTextureFilteringQuality
(CBFilteringQuality.ItemIndex);
DoOnChange;
end;
end.
|
unit n_xml_functions;
interface
uses Classes, SysUtils, Types, Graphics, a_XmlUse;
function sTxtCell(s: String; TextStyle: TXmlReportStyle=nil): String; // simple TXT cell
function sIntCell(i: Integer; TextStyle: TXmlReportStyle=nil): String; // simple Integer cell
function sHeadCell(s: String; TextStyle: TXmlReportStyle=nil): String; // simple Header cell
function sBoldCell(s: String; TextStyle: TXmlReportStyle=nil): String; // simple Bold cell
procedure AddXmlLine(lst: TStringList; s: String);
procedure AddXmlBookBegin(lst: TStringList; CellStylesArray: TXmlCellStylesArray=nil); // открываем Workbook
procedure AddXmlSheetBegin(lst: TStringList; SheetName: String; Ncolumns: Word=0); // открываем worksheet
procedure AddXmlSheetEnd(lst: TStringList; X: integer=0; Y: integer=0); // закрываем worksheet
procedure AddXmlBookEnd(lst: TStringList); // закрываем Workbook
procedure SaveXmlListToFile(lst: TStringList; fNameWithoutExt: String);
procedure CheckTxtStyle;
procedure CheckHeadStyle;
procedure CheckBoldStyle;
procedure ClearStyles;
var sTxtStyle, sHeadStyle, sBoldStyle: TXmlReportStyle;
sStylesArray: TXmlCellStylesArray;
implementation
//============================================================== simple TXT cell
function sTxtCell(s: String; TextStyle: TXmlReportStyle=nil): String;
begin
if not Assigned(TextStyle) then begin
CheckTxtStyle;
TextStyle:= sTxtStyle;
end;
Result:= fnGenerateXMLcell(s, TextStyle);
end;
//========================================================= simple Integer cell
function sIntCell(i: Integer; TextStyle: TXmlReportStyle=nil): String;
begin
if not Assigned(TextStyle) then begin
CheckTxtStyle;
TextStyle:= sTxtStyle;
end;
Result:= fnGenerateXMLcell(IntToStr(i), TextStyle, '', '', 0, 0, 0, cnXmlNumber);
end;
//========================================================== simple Header cell
function sHeadCell(s: String; TextStyle: TXmlReportStyle=nil): String;
begin
if not Assigned(TextStyle) then begin
CheckHeadStyle;
TextStyle:= sHeadStyle;
end;
Result:= fnGenerateXMLcell(s, TextStyle);
end;
//======================================================= simple Bolder cell
function sBoldCell(s: String; TextStyle: TXmlReportStyle=nil): String;
begin
if not Assigned(TextStyle) then begin
CheckBoldStyle;
TextStyle:= sBoldStyle;
end;
Result:= fnGenerateXMLcell(s, TextStyle);
end;
//==============================================================================
procedure AddXmlLine(lst: TStringList; s: String);
begin
lst.Add('<Row>'#10+s+'</Row>'#10);
end;
//=========================================================== открываем Workbook
procedure AddXmlBookBegin(lst: TStringList; CellStylesArray: TXmlCellStylesArray=nil);
begin
if not Assigned(lst) then lst:= TStringList.Create;
lst.Add(cEX_Doc_Begin);
lst.Add(cEX_Workbook_Begin);
if not Assigned(CellStylesArray) then begin
CheckTxtStyle;
CellStylesArray:= sStylesArray;
end;
lst.Add(CellStylesArray.GetXmlStyles);
end;
//========================================================== открываем worksheet
procedure AddXmlSheetBegin(lst: TStringList; SheetName: String; Ncolumns: Word=0);
begin
if not Assigned(lst) then lst:= TStringList.Create;
lst.Add(fnOpenWorksheet(sheetName));
while Ncolumns>0 do begin
lst.Add('<Column ss:AutoFitWidth="1" />');
inc(Ncolumns, -1);
end;
end;
//========================================================== закрываем worksheet
procedure AddXmlSheetEnd(lst: TStringList; X: integer=0; Y: integer=0);
var s: String;
begin
if not Assigned(lst) then Exit;
if (X=0) and (Y=0) then s:= '' else s:= fnGetWorkSheetOptions(X, Y);
Lst.Add(fnCloseWorkSheet(s));
end;
//=========================================================== закрываем Workbook
procedure AddXmlBookEnd(lst: TStringList);
begin
if not Assigned(lst) then Exit;
Lst.Add(cEX_Workbook_End);
end;
//==============================================================================
procedure SaveXmlListToFile(lst: TStringList; fNameWithoutExt: String);
begin
if not Assigned(lst) then Exit;
Lst.SaveToFile(fNameWithoutExt+'.xml');
end;
//==============================================================================
procedure CheckTxtStyle;
begin
if not Assigned(sStylesArray) then
sStylesArray:= TXmlCellStylesArray.Create;
if not Assigned(sTxtStyle) then
sTxtStyle:= sStylesArray.AddStyle(TXmlReportStyle.Create(''));
// sTxtStyle:= sStylesArray.AddStyle(TXmlReportStyle.Create('#FFFFFF'));
end;
//==============================================================================
procedure CheckHeadStyle;
begin
if not Assigned(sStylesArray) then
sStylesArray:= TXmlCellStylesArray.Create;
if not Assigned(sHeadStyle) then
sHeadStyle:= sStylesArray.AddStyle(TXmlReportStyle.Create('',
'Center', 'Center', [fsBold], '', false, true));
end;
//==============================================================================
procedure CheckBoldStyle;
begin
if not Assigned(sStylesArray) then
sStylesArray:= TXmlCellStylesArray.Create;
if not Assigned(sBoldStyle) then
sBoldStyle:= sStylesArray.AddStyle(TXmlReportStyle.Create('', '', '', [fsBold]));
end;
//==============================================================================
procedure ClearStyles;
begin
try
if Assigned(sBoldStyle) then FreeAndNil(sBoldStyle);
if Assigned(sHeadStyle) then FreeAndNil(sHeadStyle);
if Assigned(sTxtStyle) then FreeAndNil(sTxtStyle);
if Assigned(sStylesArray) then FreeAndNil(sStylesArray);
except end;
end;
//******************************************************************************
initialization
begin
end;
finalization
begin
ClearStyles;
end;
//******************************************************************************
end.
|
unit uSystemSet;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls,IniFiles;
type
TSystemSetFrm = class(TForm)
Lb_code: TLabel;
ed_maxrowCount: TEdit;
Label1: TLabel;
ed_maxdatasize: TEdit;
Label2: TLabel;
Bevel1: TBevel;
btn_Save: TBitBtn;
procedure FormShow(Sender: TObject);
procedure btn_SaveClick(Sender: TObject);
procedure ed_maxrowCountKeyPress(Sender: TObject; var Key: Char);
procedure ed_maxdatasizeKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
{ Public declarations }
end;
var
SystemSetFrm: TSystemSetFrm;
implementation
uses main;
{$R *.dfm}
procedure TSystemSetFrm.FormShow(Sender: TObject);
var
ini: TIniFile;
begin
try
ini := Tinifile.Create(ExtractFilePath(paramstr(0)) + 'STOffice.ini');
ed_maxdatasize.Text:=ini.ReadString('SystemSet','MaxDataSize','250');
ed_maxrowCount.Text:=ini.ReadString('SystemSet','MaxRowCount','1000000');
finally
ini.Free
end;
end;
procedure TSystemSetFrm.btn_SaveClick(Sender: TObject);
var
ini: TIniFile;
begin
if Trim(ed_maxrowCount.Text)='' then
begin
ShowMessage('最大可查询数据行不能为空!');
ed_maxdatasize.SetFocus;
Abort;
end;
if Trim(ed_maxdatasize.Text)='' then
begin
ShowMessage('最大可查询数据包不能为空!');
ed_maxdatasize.SetFocus;
Abort;
end;
try
strtoint(Trim(ed_maxrowCount.Text));
strtoint(Trim(ed_maxdatasize.Text));
except
on e:Exception do
begin
ShowMessage('输入值不合法! '+e.Message);
Abort;
end;
end;
try
ini := Tinifile.Create(ExtractFilePath(paramstr(0)) + 'STOffice.ini');
ini.WriteString('SystemSet','MaxDataSize',Trim(ed_maxdatasize.Text));
ini.WriteString('SystemSet','MaxRowCount',Trim(ed_maxrowCount.Text));
_MaxRowCount:=strtoint(Trim(ed_maxrowCount.Text));
_MaxDataSize:=strtoint(Trim(ed_maxdatasize.Text));
ShowMessage('参数设置成功! ');
Self.Close;
finally
ini.Free
end;
end;
procedure TSystemSetFrm.ed_maxrowCountKeyPress(Sender: TObject;
var Key: Char);
begin
if not (key in ['0'..'9',#8]) then Key:=#0;
end;
procedure TSystemSetFrm.ed_maxdatasizeKeyPress(Sender: TObject;
var Key: Char);
begin
if not (key in ['0'..'9',#8]) then Key:=#0;
end;
end.
|
unit DesignHandles;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls;
type
TDesignHandle = class(TCustomControl)
protected
FHitRect: Integer;
FMouseIsDown: Boolean;
FMouseOffset: TPoint;
protected
function HandleRect(inIndex: Integer): TRect;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure Paint; override;
end;
//
TDesignHandles = class(TComponent)
private
FContainer: TWinControl;
FSelected: TControl;
Handles: array[0..3] of TDesignHandle;
protected
procedure SetContainer(const Value: TWinControl);
procedure SetSelected(const Value: TControl);
public
constructor Create(inOwner: TComponent); override;
procedure PaintHandles(inCanvas: TCanvas; inPt: TPoint);
procedure UpdateHandles;
property Container: TWinControl read FContainer write SetContainer;
property Selected: TControl read FSelected write SetSelected;
end;
implementation
const
S = 6;
Q = 8;
var
ShadedBits: TBitmap;
function NeedShadedBits: TBitmap;
begin
if ShadedBits = nil then
begin
//ShadedBits := AllocPatternBitmap(clSilver, clGray);
ShadedBits := TBitmap.Create;
ShadedBits.Width := 4;
ShadedBits.Height := 2;
ShadedBits.Canvas.Pixels[0, 0] := clGray;
ShadedBits.Canvas.Pixels[1, 0] := clBtnFace;
ShadedBits.Canvas.Pixels[2, 0] := clBtnFace;
ShadedBits.Canvas.Pixels[3, 0] := clBtnFace;
ShadedBits.Canvas.Pixels[0, 1] := clBtnFace;
ShadedBits.Canvas.Pixels[1, 1] := clBtnFace;
ShadedBits.Canvas.Pixels[2, 1] := clGray;
ShadedBits.Canvas.Pixels[3, 1] := clBtnFace;
end;
Result := ShadedBits;
end;
procedure DrawBitmapBrushFrame(inRect: TRect; inCanvas: TCanvas);
begin
with inCanvas do
begin
Brush.Bitmap := NeedShadedBits;
with inRect do
begin
FillRect(Rect(Left, Top, Left, Top + S));
FillRect(Rect(Left, Top, Left + S, Bottom));
FillRect(Rect(Right-S, Top, Right, Bottom));
FillRect(Rect(Left, Bottom - S, Left, Bottom));
end;
end;
end;
{ TDesignHandle }
function TDesignHandle.HandleRect(inIndex: Integer): TRect;
begin
case inIndex of
0: Result := Rect(0, 0, Q, Q);
1: Result := Rect((Width - Q) div 2, 0, (Width + Q) div 2, Q);
2: Result := Rect(Width - Q, 0, Width, Q);
3: Result := Rect(0, (Height - Q) div 2, Q, (Height + Q) div 2);
end;
end;
procedure TDesignHandle.Paint;
begin
inherited;
with Canvas do
begin
Brush.Bitmap := NeedShadedBits;
FillRect(ClientRect);
Brush.Bitmap := nil;
Brush.Color := clWhite;
Pen.Color := clBlack;
if (Width > Height) then
begin
Rectangle(HandleRect(0));
Rectangle(HandleRect(1));
Rectangle(HandleRect(2));
end
else
Rectangle(HandleRect(3));
end;
end;
procedure TDesignHandle.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
function HitRect(inR: Integer): Boolean;
var
r: TRect;
begin
r := HandleRect(inR);
Result := PtInRect(r, Point(X, Y));
end;
var
i: Integer;
begin
inherited;
for i := 0 to 3 do
if HitRect(i) then
begin
FHitRect := i;
FMouseIsDown := true;
FMouseOffset := Point(X, Y);
break;
end;
end;
procedure TDesignHandle.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
inherited;
{
if FMouseIsDown then
begin
with ClientToParent(Point(X, Y)) do
begin
case FHitRect of
1:
begin
DesignTestForm.Selected.Height := DesignTestForm.Selected.Height
- ((Y - FMouseOffset.Y) - DesignTestForm.Selected.Top);
DesignTestForm.Selected.Top := Y - FMouseOffset.Y;
end;
3:
begin
DesignTestForm.Selected.Width := DesignTestForm.Selected.Width
- ((X - FMouseOffset.X) - DesignTestForm.Selected.Left);
DesignTestForm.Selected.Left := X - FMouseOffset.X;
end;
end;
DesignTestForm.UpdateHandles;
end;
end;
}
end;
procedure TDesignHandle.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
inherited;
FMouseIsDown := false;
end;
{ TDesignHandles }
constructor TDesignHandles.Create(inOwner: TComponent);
var
i: Integer;
begin
inherited;
for i := 0 to 3 do
begin
Handles[i] := TDesignHandle.Create(Self);
//Handles[i].Parent := TWinControl(inOwner);
//Handles[i].Visible := false;
end;
//Blocker := TDesignBlocker.Create(Self);
//Blocker.Parent := TWinControl(inOwner);
//Blocker.Visible := false;
end;
procedure TDesignHandles.UpdateHandles;
var
p: TPoint;
r: TRect;
c: TControl;
i: Integer;
begin
if (Selected <> nil) and (Container <> nil) then
begin
{
c := Selected;
p := Selected.BoundsRect.topLeft;
while (c.Parent <> Container) do
begin
p := c.ClientToParent(p);
c := c.Parent;
end;
}
c := Selected.Parent;
p := Selected.BoundsRect.topLeft;
while (c <> Container) and (c <> nil) do
begin
Inc(p.X, c.Left);
Inc(p.Y, c.Top);
//p := c.ClientToParent(p);
c := c.Parent;
end;
r := Rect(p.X, p.Y, p.X + Selected.Width, p.y + Selected.Height);
with r do
begin
Handles[0].BoundsRect := Rect(Left - Q, Top - Q, Right + Q, Top);
Handles[1].BoundsRect := Rect(Left - Q, Top, Left, Bottom);
Handles[2].BoundsRect := Rect(Right, Top, Right + Q, Bottom);
Handles[3].BoundsRect := Rect(Left - Q, Bottom, Right + Q, Bottom + Q);
end;
//Blocker.BoundsRect := Selected.BoundsRect;
//Blocker.BringToFront;
end;
for i := 0 to 3 do
begin
Handles[i].Visible := Selected <> nil;
Handles[i].BringToFront;
end;
//Blocker.Visible := Selected <> nil;
end;
{
procedure TDesignHandles.MoveHandles(inPt: TPoint);
var
d: TPoint;
i: Integer;
begin
if (Container <> nil) then
begin
with Handles[0].BoundsRect.TopLeft do
begin
d.X := inPt.X - X;
d.Y := inPt.Y - Y;
end;
for i := 0 to 3 do
with Handles[i] do
begin
Left := Left + d.X;
Top := Top + d.Y;
end;
end;
end;
}
procedure TDesignHandles.PaintHandles(inCanvas: TCanvas; inPt: TPoint);
var
desktopWindow: HWND;
dc: HDC;
c: TCanvas;
begin
inPt := Container.ClientToScreen(inPt);
desktopWindow := GetDesktopWindow;
dc := GetDCEx(desktopWindow, 0, DCX_CACHE or DCX_LOCKWINDOWUPDATE);
try
c := TCanvas.Create;
with c do
try
Handle := dc;
// c.Brush.Style := bsClear;
// c.Pen.Mode := pmNotXor;
Pen.Style := psSolid;
Pen.Color := clWhite;
Pen.Mode := pmXor;
MoveTo(inPt.X, inPt.Y);
LineTo(inPt.X + Selected.Width, inPt.Y);
LineTo(inPt.X + Selected.Width, inPt.Y + Selected.Height);
LineTo(inPt.X, inPt.Y + Selected.Height);
LineTo(inPt.X, inPt.Y);
// Rectangle(
// Rect(inPt.X, inPt.Y, inPt.X + Selected.Width, inPt.Y + Selected.Height));
{
Brush.Bitmap := NeedShadedBits;
CopyMode := cmPatInvert;
FillRect(
Rect(inPt.X, inPt.Y, inPt.X + Selected.Width, inPt.Y + Selected.Height));
Brush.Bitmap := nil;
CopyMode := cmPatCopy;
}
finally
c.Free;
end;
finally
ReleaseDC(desktopWindow, dc);
end;
//
{
with inCanvas do
begin
// CopyMode := cmPatInvert;
// Brush.Bitmap := NeedShadedBits;
FillRect(
Rect(inPt.X, inPt.Y, inPt.X + Selected.Width, inPt.Y + Selected.Height));
// Brush.Bitmap := nil;
// CopyMode := cmPatCopy;
end;
}
end;
procedure TDesignHandles.SetSelected(const Value: TControl);
begin
if (Selected <> Value) then
begin
if (Value is TDesignHandle) then
FSelected := nil
else
FSelected := Value;
UpdateHandles;
end;
end;
procedure TDesignHandles.SetContainer(const Value: TWinControl);
var
i: Integer;
begin
FContainer := Value;
for i := 0 to 3 do
begin
Handles[i].Visible := false;
Handles[i].Parent := FContainer;
end;
end;
end.
|
unit gl_core_matrix;
//emulates legacy opengl matrix stack that was removed from core opengl
{$mode objfpc}{$H+}
//http://glm.g-truc.net/0.9.7/index.html
interface
uses
Classes, SysUtils, math;
type
TnMode = (nGL_PROJECTION, nGL_MODELVIEW);
TnMat44 = array [0..3, 0..3] of single;
TnMat33 = array [0..2, 0..2] of single;
TnGL = record
mode: TnMode;
mat: array[TnMode] of TnMat44;
end;
procedure nglMatrixMode (mode: TnMode);
procedure nglLoadIdentity ();
procedure nglScalef(x, y, z: single);
procedure nglRotatef(angle, x, y, z: single);
procedure nglTranslatef(x, y, z: single);
procedure nglOrtho (left, right, bottom, top, zNear, zFar: single);
procedure ngluPerspective (fovy, aspect, zNear, zFar: single);
function ngl_ModelViewProjectionMatrix : TnMat44;
function ngl_ModelViewMatrix : TnMat44;
function ngl_NormalMatrix: TnMat33;
function ngl_ProjectionMatrix : TnMat44;
var
gnGL: TnGL;
implementation
function multMat(a, b: TnMat44): TnMat44;
var i,j: integer;
begin
for i := 0 to 3 do begin
for j := 0 to 3 do begin
result[i, j] := A[i, 0] * B[0,j]
+ A[i, 1] * B[1, j]
+ A[i, 2] * B[2, j]
+ A[i, 3] * B[3, j];
end; //for j
end; //for i
end; //multMat()
function transposeMat(a: TnMat44): TnMat44;
var i,j: integer;
begin
for i := 0 to 3 do
for j := 0 to 3 do
result[i, j] := A[j,i]
end; //transposeMat()
function inverseMat (Rm: TnMat44): TnMat44;
//invert matrix see nifti_mat44_inverse( mat44 R )
// http://niftilib.sourceforge.net/c_api_html/nifti1__io_8h.html#a36
var
r11,r12,r13,r21,r22,r23,r31,r32,r33,v1,v2,v3 , deti: double;
Qm : TnMat44;
begin
r11 := Rm[0,0]; r12 := Rm[0,1]; r13 := Rm[0,2];
r21 := Rm[1,0]; r22 := Rm[1,1]; r23 := Rm[1,2];
r31 := Rm[2,0]; r32 := Rm[2,1]; r33 := Rm[2,2];
v1 := Rm[0,3]; v2 := Rm[1,3]; v3 := Rm[2,3];
deti := r11*r22*r33-r11*r32*r23-r21*r12*r33
+r21*r32*r13+r31*r12*r23-r31*r22*r13 ;
if( deti <> 0.0 ) then deti := 1.0 / deti ;
Qm[0,0] := deti*( r22*r33-r32*r23) ;
Qm[0,1] := deti*(-r12*r33+r32*r13) ;
Qm[0,2] := deti*( r12*r23-r22*r13) ;
Qm[0,3] := deti*(-r12*r23*v3+r12*v2*r33+r22*r13*v3
-r22*v1*r33-r32*r13*v2+r32*v1*r23) ;
Qm[1,0] := deti*(-r21*r33+r31*r23) ;
Qm[1,1] := deti*( r11*r33-r31*r13) ;
Qm[1,2] := deti*(-r11*r23+r21*r13) ;
Qm[1,3] := deti*( r11*r23*v3-r11*v2*r33-r21*r13*v3
+r21*v1*r33+r31*r13*v2-r31*v1*r23) ;
Qm[2,0] := deti*( r21*r32-r31*r22) ;
Qm[2,1] := deti*(-r11*r32+r31*r12) ;
Qm[2,2] := deti*( r11*r22-r21*r12) ;
Qm[2,3] := deti*(-r11*r22*v3+r11*r32*v2+r21*r12*v3
-r21*r32*v1-r31*r12*v2+r31*r22*v1) ;
Qm[3,0] := 0;
Qm[3,1] := 0;
Qm[3,2] := 0;
Qm[3,3] := 1;
if (deti = 0.0) then Qm[3,3] := 0; // failure flag if deti = 0
result := Qm ;
end;
function ngl_NormalMatrix: TnMat33;
//Returns normal matrix, in GLSL this would be
// mat4 NormalMatrix = transpose(inverse(ModelViewMatrix));
var
m, q: TnMat44;
i,j: integer;
begin
q := inverseMat(gnGL.mat[nGL_MODELVIEW]);
m := transposeMat(q);
for i := 0 to 2 do //normal matrix is orthonormal, so only ignore final row/column
for j := 0 to 2 do
result[i,j] := m[i,j];
end;
procedure nglMatrixMode (mode: TnMode);
begin
gnGL.mode := mode;
end;
function RSqrt(v: single): single;
begin
result := 1/sqrt(v);
end;
function IdentityHmgMatrix: TnMat44;
var
i,j: integer;
begin
for i := 0 to 3 do
for j := 0 to 3 do
result[i,j] := 0;
for i := 0 to 3 do
result[i,i] := 1;
end;
function CreateGlRotateMatrix(angle, x, y, z: single) : TnMat44;
//http://www.gamedev.net/topic/600537-instead-of-glrotatef-build-a-matrix/
var
c, s: single;
invLen : Single;
begin
angle:= degtorad(angle);
invLen:= RSqrt(x * x + y * y + z * z);
x:= x * invLen;
y:= y * invLen;
z:= z * invLen;
result:= IdentityHmgMatrix;
c:= cos(angle);
s:= sin(angle);
result[0,0] := (x*x) * (1-c)+c;
result[1,0] := x*y * (1-c)-z*s;
result[2,0] := x*z * (1-c)+y*s;
result[0,1] := y*x * (1-c)+z*s;
result[1,1] := (y*y) * (1-c)+c;
result[2,1] := y*z * (1-c)-x*s;
result[0,2] := x*z * (1-c)-y*s;
result[1,2] := y*z * (1-c)+x*s;
result[2,2] := (z*z) * (1-c)+c;
end;
function ngl_ModelViewProjectionMatrix : TnMat44;
//gl_Position = gl_ProjectionMatrix * gl_ModelViewMatrix * gl_Vertex;
begin
//result := matrixMult(gnGL.mat[nGL_PROJECTION], gnGL.mat[nGL_MODELVIEW]);
result := multMat( gnGL.mat[nGL_MODELVIEW], gnGL.mat[nGL_PROJECTION]);
end;
procedure nglRotatef(angle, x, y, z: single);
var
m : TnMat44;
begin
m := CreateGlRotateMatrix(angle, x, y, z);
gnGL.mat[gnGL.mode] := multMat(m, gnGL.mat[gnGL.mode]);
end;
procedure nglTranslatef(x, y, z: single);
var
m : TnMat44;
begin
//m := gnGL.mat[gnGL.mode];
m := IdentityHmgMatrix;
m[3,0] := m[3,0] + x;
m[3,1] := m[3,1] + y;
m[3,2] := m[3,2] + z;
//gnGL.mat[gnGL.mode] := m;
gnGL.mat[gnGL.mode] := multMat(m, gnGL.mat[gnGL.mode]);
end;
procedure nglScalef(x, y, z: single);
var
m : TnMat44;
begin
m := IdentityHmgMatrix;
m[0,0] := x;
m[1,1] := y;
m[2,2] := z;
gnGL.mat[gnGL.mode] := multMat(m, gnGL.mat[gnGL.mode]);
end;
procedure nglLoadIdentity ();
begin
gnGL.mat[gnGL.mode] := IdentityHmgMatrix
end;
procedure ngluPerspective (fovy, aspect, zNear, zFar: single);
//https://www.opengl.org/sdk/docs/man2/xhtml/gluPerspective.xml
var
f: single;
m : TnMat44;
begin
m := IdentityHmgMatrix;
f := cot(degtorad(fovy)/2);
m[0,0] := f/aspect;
m[1,1] := f;
m[2,2] := (zFar+zNear)/(zNear-zFar) ;
m[3,2] := (2*zFar*zNear)/(zNear-zFar);
m[2,3] := -1;
m[3,3] := 0;
//raise an exception if zNear = 0??
gnGL.mat[gnGL.mode] := multMat(m,gnGL.mat[gnGL.mode]);
end;
procedure nglOrtho (left, right, bottom, top, zNear, zFar: single);
//https://www.opengl.org/sdk/docs/man2/xhtml/glOrtho.xml
var
m : TnMat44;
begin
m := IdentityHmgMatrix;
m[0,0] := 2 / (right - left);
m[1,1] := 2 / (top - bottom);
m[2,2] := - 2 / (zFar - zNear);
m[3,0] := - (right + left) / (right - left);
m[3,1] := - (top + bottom) / (top - bottom);
m[3,2] := - (zFar + zNear) / (zFar - zNear);
//gnGL.mat[gnGL.mode] := m;
gnGL.mat[gnGL.mode] := multMat(m,gnGL.mat[gnGL.mode]);
end;
function ngl_ModelViewMatrix : TnMat44;
begin;
result := gnGL.mat[nGL_MODELVIEW];
end;
function ngl_ProjectionMatrix : TnMat44;
begin
result := gnGL.mat[nGL_PROJECTION];
end;
begin
gnGL.mat[nGL_PROJECTION] := IdentityHmgMatrix;
gnGL.mat[nGL_MODELVIEW] := IdentityHmgMatrix;
end.
|
unit uModbus;
{$IFDEF VER220}
{$DEFINE UNDER_DELPHI_XE}
{$ENDIF}
{$IFDEF VER230}
{$DEFINE UNDER_DELPHI_XE}
{$ENDIF}
interface
uses
SysUtils, cport, WinSock, Sockets{$IFDEF UNDER_DELPHI_XE}, CPortTypes{$ENDIF},
syncobjs;
type
TModbusError = (
merNone,
merCantOpenPort, // com port
merTimeout,
merAddressError, // переданный и полученный адрес не совпадают
merFuncError, // переданный и полученный код функции не совпадают
merCRCError,
merWrongToLength, // <253
merWrongFromLength, // from controller
merModbusRecError, // ошибка от контроллера, переданная им по модбасу
merWrongDataLenFrom, // неправильная длина данных, полученная от контроллера
merWrongDataLenTo, // неправильная длина данных, переданная контроллеру
merMBFunctionCode, //-\
merMBDataAddress, //-|- ошибки, которые возвращает modbus
merMBDataValue, //-|
merMBFuncExecute, //-/
merMFLenError, // ошибки при приеме пакетов и преобразовании данных в модуле MiFARE
merLast,
merUndef = 255);
const
StrModbusError: array [merNone .. merLast] of string = (
'нет',
'Не удалось открыть СОМ порт',
'Таймаут связи с устройством',
'Переданный и полученный адрес не совпадают',
'Переданный и полученный код функции не совпадают',
'Ошибка CRC пакета от устройства',
'Слишком большой пакет для передачи устройству',
'Несоответствие длины пакета и констант в пакете от устройства',
'Ошибка модбаса',
'Неправильная длина данных, полученная от устройства',
'Неправильная длина данных, при попытке передачи на устройство',
'Ошибка модбас (1) неправильная функция',
'Ошибка модбас (2) неправильный адрес',
'Ошибка модбас (3) неправильные данные в функции',
'Ошибка модбас (4) исполнения функции',
'Ошибка при приеме пакетов или преобразовании данных в модуле MiFARE',
'нет'
);
type
TAddrQtyRec = packed record
Addr: Word;
Qty: Word;
end;
TAddrDataRec = packed record
Addr: Word;
Qty: Word;
end;
TRegDataRec = packed record
Addr: Word;
Qty: Word;
data: array[1..250] of byte;
end;
TResultRec = packed record
Qty: byte;
data: array[1..250] of byte;
end;
TModbusIdentification = packed record
Company,
Product,
Version,
VendorURL: string;
end;
TModbus = class
private
FPort: TComPort;
FModbusTCP: boolean;
FSocket: TTcpClient;
FTimeout : byte;
FSection: TCriticalSection;
function SendTCP(TxSleep: cardinal; datain: AnsiString; var dataout: AnsiString): TModbusError;
function SendRTU(TxSleep: cardinal; datain: AnsiString; var dataout: AnsiString): TModbusError;
procedure OnSocketError(Sender: TObject; SocketError: Integer);
public
constructor Create(Port: Integer; Speed: integer); overload;
constructor Create(Host: string; Port: integer); overload;
destructor Destroy; override;//reintroduce;
function Send(ATxSleep: cardinal; Address, Func: byte; data: AnsiString; var dataout: AnsiString): TModbusError;
function ReadCoilStatus(Address: byte; param: TAddrQtyRec; var output: TResultRec): TModbusError; // 1
function ReadDiscreteInputs(Address: byte; param: TAddrQtyRec; var output: TResultRec): TModbusError; // 2
function ReadHoldingRegisters(Address: byte; param: TAddrQtyRec; var output: TResultRec): TModbusError;// 3
function ForceSingleCoil(Address: byte; OutputAddr: Word; state: boolean): TModbusError; // 5
function PresetSingleRegister(Address: byte; param: TAddrDataRec): TModbusError; // 6
function WriteMultipleRegisters(Address: byte; input: TRegDataRec): TModbusError; //16
// modbus function
function CallFunction(Address: byte; code, subcode: byte; data: AnsiString; var dataout: AnsiString): TModbusError;
// search device
function FindFirst: byte;
function FindNext(FromID: byte): byte;
// Work with TCP
function TCPConnect: boolean;
function Connected: boolean;
property TimeOut: byte read FTimeOut write FTimeOut;
property Port: TComPort read FPort write FPort;
end;
function crc16string(msg: ansistring): ansistring;
implementation
uses Math, windows;
{ TModbus }
function ArrByteToString(data: array of byte; Qty: integer = -1): ansistring;
var
len: integer;
begin
Result := '';
if Qty < 0 then
len := length(data)
else
len := Qty;
if len > 250 then exit;
SetLength(Result, len);
move(data[0], Result[1], len);
end;
function TModbus.CallFunction(Address, code, subcode: byte;
data: AnsiString; var dataout: AnsiString): TModbusError;
begin
Result := Send(100, Address, code, ansichar(subcode) + data, dataout);
end;
constructor TModbus.Create(Port, Speed: integer);
begin
inherited Create;
FModbusTCP := false;
FPort := TComPort.Create(Nil);
FPort.Port := 'COM' + IntToStr(Port);
FTimeout := 30;
case speed of
115200: FPort.BaudRate := br115200;
9600: FPort.BaudRate := br9600;
2400: FPort.BaudRate := br2400;
1200: FPort.BaudRate := br1200;
else
FPort.BaudRate := br115200;
end;
try
FPort.Open;
except
end;
FSection := TCriticalSection.Create;
end;
function TModbus.Connected: boolean;
begin
if not FModbusTCP then
Result := FPort.Connected
else
Result := TCPConnect;
end;
constructor TModbus.Create(Host: string; Port: integer);
begin
inherited Create;
FModbusTCP := true;
FTimeout := 30;
FSocket := TTcpClient.Create(nil);
FSocket.RemoteHost := Host;
FSocket.RemotePort := IntToStr(Port);
FSocket.BlockMode := bmBlocking;
FSocket.OnError := OnSocketError;
FSocket.Active := true;
FSection := TCriticalSection.Create;
end;
destructor TModbus.Destroy;
begin
if FModbusTCP then
begin
FSocket.Close;
FSocket.Destroy;
end
else
begin
FPort.Close;
FPort.Destroy;
end;
FSection.Free;
inherited;
end;
function crc16string(msg: ansistring): ansistring;
var
crc: word;
n,
i: integer;
b:byte;
begin
crc := $FFFF;
for i := 1 to length (msg) do
begin
b := byte(msg[i]);
crc := crc xor b;
for n := 1 to 8 do
begin
if (crc and 1) <> 0 then
crc := (crc shr 1) xor $A001
else crc := crc shr 1;
end;
end;
result := ansichar(crc and $ff) + ansichar(crc shr 8);
end;
function TModbus.FindFirst: byte;
var
i: integer;
err: TModbusError;
param: TAddrQtyRec;
output: TResultRec;
begin
Result := 0;
param.Addr := 0;
param.Qty := 1;
for i := 1 to 250 do
begin
err := ReadHoldingRegisters(i, param, output);
if not (err in [merCantOpenPort, merTimeout, merWrongDataLenTo]) then
begin
Result := i;
exit;
end;
end;
end;
function TModbus.FindNext(FromID: byte): byte;
var
i: integer;
err: TModbusError;
param: TAddrQtyRec;
output: TResultRec;
begin
Result := 0;
param.Addr := 0;
param.Qty := 1;
for i := FromID + 1 to 250 do
begin
err := ReadHoldingRegisters(i, param, output);
if not (err in [merCantOpenPort, merTimeout, merWrongDataLenTo]) then
begin
Result := i;
exit;
end;
end;
end;
function TModbus.ForceSingleCoil(Address: byte; OutputAddr: Word; state: boolean): TModbusError;
begin
Result := merNone
end;
procedure TModbus.OnSocketError(Sender: TObject; SocketError: Integer);
var
i: integer;
begin
i := SocketError;
end;
function TModbus.PresetSingleRegister(Address: byte; param: TAddrDataRec): TModbusError;
begin
Result := merNone
end;
function TModbus.ReadCoilStatus(Address: byte; param: TAddrQtyRec;
var output: TResultRec): TModbusError;
var
vin,
vout: AnsiString;
begin
output.Qty := 0;
vin := ' ';
move(param, vin[1], 4);
Result := Send(20 + param.Qty div 12, Address, 1, vin, vout);
if Result = merNone then
begin
if (length(vout) < 2) or (ord(vout[1]) + 1 <> length(vout)) then
begin
Result := merWrongDataLenFrom;
exit;
end;
output.Qty := Ord(vout[1]);
move(vout[2], output.data[1], output.Qty);
end;
end;
function TModbus.ReadDiscreteInputs(Address: byte; param: TAddrQtyRec;
var output: TResultRec): TModbusError;
begin
Result := merNone
end;
function TModbus.ReadHoldingRegisters(Address: byte; param: TAddrQtyRec;
var output: TResultRec): TModbusError;
var
vin,
vout: AnsiString;
begin
Result := merWrongDataLenTo;
if param.Qty > 128 then exit;
vin := AnsiChar(Hi(param.Addr)) + AnsiChar(Lo(param.Addr)) +
AnsiChar(Hi(param.Qty)) + AnsiChar(Lo(param.Qty));
Result := Send(40 + param.Qty div 2, Address, 03, vin, vout);
if Result <> merNone then exit;
if length(vout) <> ord(vout[3]) + 5 then
begin
Result := merWrongDataLenFrom;
exit;
end;
output.Qty := ord(vout[3]);
// SetLength(output.data, output.Qty);
move(vout[4], output.data[1], output.Qty);
end;
function TModbus.Send(ATxSleep: cardinal; Address, Func: byte; data: AnsiString; var dataout: AnsiString): TModbusError;
var
s: ansistring;
begin
FSection.Enter;
try
Result := merUndef;
dataout := '';
if Length(data) >= 253 then
begin
Result := merWrongToLength;
exit;
end;
s := AnsiChar(Address) + AnsiChar(Func) + data;
// send
try
if FModbusTCP then
Result := SendTCP(ATxSleep, s, dataout)
else
Result := SendRTU(ATxSleep, s, dataout);
if Result <> merNone then exit;
except
sleep(10);
end;
// process
if Length(dataout) = 0 then
begin
Result := merTimeout;
exit;
end;
if (Length(dataout) < 4) or (Length(dataout) > 250) then
begin
dataout := '';
Result := merWrongFromLength;
exit;
end;
if dataout[1] <> AnsiChar(Address) then
begin
Result := merAddressError;
exit;
end;
if dataout[2] <> AnsiChar(Func) then
begin
Result := merFuncError;
if (ord(dataout[2]) xor $80) = Func then
begin
case ord(dataout[3]) of
01: Result := merMBFunctionCode;
02: Result := merMBDataAddress;
03: Result := merMBDataValue;
04: Result := merMBFuncExecute;
else
end;
end;
exit;
end;
finally
FSection.Leave;
end;
end;
function TModbus.SendRTU(TxSleep: cardinal; datain: AnsiString; var dataout: AnsiString): TModbusError;
var
s: AnsiString;
cnt: integer;
i, j: integer;
tmp: cardinal;
begin
Result := merNone;
s := datain + crc16string(datain);
if not FPort.Connected then
begin
Result := merCantOpenPort;
exit;
end;
//flush
FPort.ReadStr(dataout, FPort.InputCount);
//write
FPort.WriteStr(s);
TxSleep := GetTickCount + TxSleep;
while (GetTickCount < TxSleep) do
begin
cnt := FPort.InputCount;
if cnt <> 0 then
begin
tmp := GetTickCount;
if TxSleep > tmp then
sleep(TxSleep - tmp);
break;
end;
end;
// sleep(TxSleep);
dataout := '';
// cnt := FPort.InputCount;
if cnt <> 0 then
FPort.ReadStr(dataout, cnt)
else
Result := merTimeout;
// похоже выгребли не все
i := 5;
while ((dataout = '') or (crc16string(dataout) <> #0#0)) and (i > 0) do
begin
sleep(20);
FPort.ReadStr(s, FPort.InputCount);
dataout := dataout + s;
if s <> '' then
Result := merNone;
i := i - 1;
end;
if Result <> merNone then exit;
if crc16string(dataout) <> #0#0 then
begin
Result := merCRCError;
exit;
end;
end;
function TModbus.SendTCP(TxSleep: cardinal; datain: AnsiString; var dataout: AnsiString): TModbusError;
var
cnt: integer;
s: AnsiString;
buf: array [0 .. 1024] of AnsiChar;
len: word;
begin
Result := merNone;
len := length(datain);
s := AnsiString(#0#1) + AnsiString(#0#0) + AnsiChar(hi(len)) + AnsiChar(lo(len)) + datain;
if not FSocket.Connected then
try
FSocket.Close;
if not TCPConnect then
begin
Result := merCantOpenPort;
exit;
end;
except
Result := merCantOpenPort;
exit;
end;
//flush
if FSocket.WaitForData(1) then
begin
cnt := FSocket.PeekBuf(buf[0], length(buf));
if cnt > 0 then FSocket.ReceiveBuf(buf[0], cnt);
end;
//write
cnt := FSocket.SendBuf(s[1], length(s));
// try to resend if socket closed
if cnt = -1 then
begin
FSocket.Close;
if TCPConnect then
cnt := FSocket.SendBuf(s[1], length(s));
end;
if cnt <> length(s) then
begin
Result := merCantOpenPort;
FSocket.Close;
exit;
end;
dataout := '';
if FSocket.WaitForData(TxSleep) then
begin
cnt := FSocket.PeekBuf(buf[0], length(buf));
if cnt > 0 then
begin
FSocket.ReceiveBuf(buf[0], cnt);
SetLength(dataout, cnt);
move(buf[0], dataout[1], cnt);
end
else
Result := merTimeout;
end;
// похоже выгребли не все
if dataout = '' then
if FSocket.WaitForData(200) then
begin
cnt := FSocket.PeekBuf(buf[0], length(buf));
if cnt > 0 then
begin
FSocket.ReceiveBuf(buf[0], cnt);
SetLength(s, cnt);
move(buf[0], s[1], cnt);
end;
if s <> '' then Result := merNone;
dataout := dataout + s;
end;
if length(dataout) = 0 then
begin
Result := merTimeout;
exit;
end;
if length(dataout) < 9 then
begin
dataout := '';
Result := merWrongFromLength;
exit;
end;
if ord(dataout[5]) * 256 + ord(dataout[6]) <> length(dataout) - 6 then
begin
dataout := '';
Result := merWrongFromLength;
exit;
end;
dataout := Copy(dataout, 7, length(dataout));
dataout := dataout + crc16String(dataout);
end;
function TModbus.TCPConnect: boolean;
begin
Result := false;
if not FModbusTCP then
begin
Result := true;
exit;
end;
try
Result := FSocket.Connect
except
end;
end;
function TModbus.WriteMultipleRegisters(Address: byte;
input: TRegDataRec): TModbusError;
var
vin: AnsiString;
output: ansistring;
begin
Result := merWrongDataLenTo;
if input.Qty > 128 then exit;
vin := AnsiChar(Hi(input.Addr)) + AnsiChar(Lo(input.Addr)) +
AnsiChar(Hi(input.Qty)) + AnsiChar(Lo(input.Qty)) +
AnsiChar(input.Qty * 2) +
ArrByteToString(input.data, input.Qty * 2);
Result := Send(10 + FTimeout + input.Qty, Address, 16, vin, output);
if Result <> merNone then exit;
if ord(output[5]) * $FF + ord(output[6]) <> input.Qty then
begin
Result := merWrongDataLenFrom;
exit;
end;
end;
end.
|
unit mParserCore;
interface
uses
API_MVC_DB,
eGroup,
eLink,
System.SyncObjs;
type
TEachGroupRef = reference to procedure(const aArrRow: string; var aGroup: TGroup);
TModelParser = class abstract(TModelDB)
private
function CheckFirstRun: Boolean;
function GetNextLink: TLink;
procedure AddZeroLink;
protected
function GetNextLinkSQL: string; virtual;
procedure AddAsEachGroup(aOwnerGroup: TGroup; aDataArr: TArray<string>; aEachGroupProc: TEachGroupRef);
procedure ProcessLink(aLink: TLink; out aBodyGroup: TGroup); virtual;
public
inDomain: string;
inJobID: Integer;
procedure Start; override;
end;
var
CriticalSection: TCriticalSection;
implementation
uses
eJob,
FireDAC.Comp.Client,
System.Classes,
System.SysUtils;
function TModelParser.GetNextLinkSQL: string;
begin
Result := 'select Id from core_links t where t.job_id = :JobID and t.handled_type_id = 1 order by t.level desc, t.id limit 1';
end;
function TModelParser.CheckFirstRun: Boolean;
var
dsQuery: TFDQuery;
SQL: string;
begin
dsQuery := TFDQuery.Create(nil);
try
SQL := 'select count(*) from core_links t where t.job_id = :JobID';
dsQuery.SQL.Text := SQL;
dsQuery.ParamByName('JobID').AsInteger := inJobID;
FDBEngine.OpenQuery(dsQuery);
if dsQuery.Fields[0].AsInteger = 0 then
Result := True
else
Result := False;
finally
dsQuery.Free;
end;
end;
procedure TModelParser.AddAsEachGroup(aOwnerGroup: TGroup; aDataArr: TArray<string>; aEachGroupProc: TEachGroupRef);
var
ArrRow: string;
Group: TGroup;
begin
for ArrRow in aDataArr do
begin
Group := TGroup.Create(FDBEngine);
aEachGroupProc(ArrRow, Group);
aOwnerGroup.ChildGroupList.Add(Group);
end;
end;
procedure TModelParser.ProcessLink(aLink: TLink; out aBodyGroup: TGroup);
var
Page: string;
begin
aBodyGroup := TGroup.Create(FDBEngine, aLink.BodyGroupID);
aBodyGroup.ParentGroupID := aLink.OwnerGroupID;
//FCurrLink := aLink;
//FHTTP.SetHeaders(aLink.Headers);
{if aLink.PostData.IsEmpty then
Page := FHTTP.Get(aLink.Link)
else
begin
PostSL := TStringList.Create;
try
ParsePostData(PostSL, aLink.PostData);
Page := FHTTP.Post(aLink.Link, PostSL)
finally
PostSL.Free;
end;
end; }
end;
procedure TModelParser.AddZeroLink;
var
Job: TJob;
Link: TLink;
begin
Job := TJob.Create(FDBEngine, inJobID);
Link := TLink.Create(FDBEngine);
try
Link.JobID := Job.ID;
Link.Level := 0;
Link.URL := Job.ZeroLink;
Link.HandledTypeID := 1;
Link.Store;
finally
Job.Free;
Link.Free;
end;
end;
function TModelParser.GetNextLink: TLink;
var
dsQuery: TFDQuery;
SQL: string;
begin
Result := nil;
dsQuery := TFDQuery.Create(nil);
try
SQL := GetNextLinkSQL;
dsQuery.SQL.Text := SQL;
dsQuery.ParamByName('JobID').AsInteger := inJobID;
FDBEngine.OpenQuery(dsQuery);
if dsQuery.IsEmpty then
begin
if CheckFirstRun then
begin
AddZeroLink;
Result := GetNextLink;
end;
end
else
Result := TLink.Create(FDBEngine, dsQuery.Fields[0].AsInteger);
finally
dsQuery.Free;
end;
end;
procedure TModelParser.Start;
var
BodyGroup: TGroup;
Link: TLink;
begin
while not FCanceled do
begin
CriticalSection.Enter;
Link := GetNextLink;
if Link <> nil then
begin
Link.HandledTypeID := 2;
Link.Store;
end;
CriticalSection.Leave;
if Link <> nil then
try
ProcessLink(Link, BodyGroup);
BodyGroup.StoreAll;
Link.BodyGroupID := BodyGroup.ID;
Link.HandledTypeID := 3;
Link.Store;
finally
BodyGroup.Free;
Link.Free;
end;
end;
end;
initialization
CriticalSection := TCriticalSection.Create;
finalization
CriticalSection.Free;
end.
|
unit Exceptions;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, TrataException, System.Threading, uThread;
type
TfExceptions = class(TForm)
Memo1: TMemo;
Button1: TButton;
Memo2: TMemo;
Label2: TLabel;
Button2: TButton;
Memo3: TMemo;
Label1: TLabel;
Label3: TLabel;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
FPath: string;
FException: TException;
tempo: Word;
function LoadNumbers(AIgnore: Integer): Boolean;
procedure AfterExecute;
public
end;
var
fExceptions: TfExceptions;
implementation
{$R *.dfm}
procedure TfExceptions.FormCreate(Sender: TObject);
begin
FException := TException.Create;
FPath := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) +
'text.txt';
end;
procedure TfExceptions.Button1Click(Sender: TObject);
var
Task: iTask;
begin
try
Memo1.Lines.Clear;
Memo2.Lines.Clear;
tempo := GetTickCount;
Task := TTask.Create(
procedure
begin
TProcessaThread.Create(
procedure
begin
LoadNumbers(1);
end, AfterExecute);
end);
Task.Start;
except
on E: Exception do
begin
FException.TrataException(Sender, E, Memo1);
end;
end;
end;
procedure TfExceptions.Button2Click(Sender: TObject);
var
Task: iTask;
begin
Memo1.Lines.Clear;
Memo2.Lines.Clear;
tempo := GetTickCount;
Task := TTask.Create(
procedure
begin
TProcessaThread.Create(
procedure
var
I: Integer;
begin
for I := 0 to 7 do
begin
try
raise Exception.Create(Format('Erro no item %d', [I]));
LoadNumbers(I);
except
on E: Exception do
begin
FException.TrataException(Sender, E, Memo1);
end;
end;
end;
end, AfterExecute);
end);
Task.Start;
end;
procedure TfExceptions.AfterExecute;
begin
tempo := GetTickCount - tempo;
Label1.Caption := 'Tempo de processamento: ' + tempo.ToString + ' ms';
end;
function TfExceptions.LoadNumbers(AIgnore: Integer): Boolean;
var
st: TStringList;
I, J: Integer;
s: String;
Tasks: array of iTask;
INumRegPerTask: Integer;
iNumTotal: Integer;
ICountTasks: Integer;
FIni, FFim: Integer;
begin
st := TStringList.Create;
st.LoadFromFile(FPath);
Result := True;
try
ICountTasks := 100;
INumRegPerTask := Trunc(st.Count / ICountTasks);
SetLength(Tasks, ICountTasks);
FIni := 0;
//Exemplo
//iNumTotal := 100.000 registros
//ICountTasks := 100 Tasks; FIXO
//INumRegPerTask := 1.000 registros por Task;
//Task 1
//FIni = 0 FFim = 1000
//Task 2
//FIni = 1000 FFim = 2000
//Task 3
//FIni = 3000 FFim = 4000
for J := 0 to ICountTasks - 1 do
begin
try
FIni := (INumRegPerTask * (J + 1)) - INumRegPerTask;
FFim := (INumRegPerTask * (J + 1));
Tasks[J] := TTask.Create(
procedure
var
y: Integer;
begin
for I := FIni to FFim do
begin
s := st[I];
for y := 0 to Length(s) do
if not(s[y] = AIgnore.ToString) then
begin
Memo2.Lines.Add(s[y]);
Sleep(1);
end;
end;
end);
Tasks[I].Start;
except
on E: Exception do
begin
FException.TrataException(nil, E, Memo1);
end;
end;
end;
TTask.WaitForAll(Tasks);
// for I := 0 to 10 do // st.Count
// begin
// s := st[I];
// for y := 0 to Length(s) do
// if not(s[y] = AIgnore.ToString) then
// begin
// // Aux := s[y] + #1310;
// Memo2.Lines.Add(s[y]);
// end;
// end;
except
Result := False;
end;
FreeAndNil(st);
end;
procedure TfExceptions.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if Assigned(FException) then
FreeAndNil(FException);
Action := caFree;
end;
end.
|
Unit RequestListModel;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
Interface
Uses
Windows, Classes, Generics.Collections, Generics.Defaults,
IRPMonDll, ListModel, IRPMonRequest, DataParsers, ComCtrls,
Graphics, RequestList, SymTables;
Type
TRequestListModel = Class (TListModel<TDriverRequest>)
Private
FList : TRequestList;
FFilterDisplayOnly : Boolean;
Protected
Procedure OnAdvancedCustomDrawItemCallback(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage; var DefaultDraw: Boolean); Override;
Function GetColumn(AItem:TDriverRequest; ATag:NativeUInt):WideString; Override;
Procedure FreeItem(AItem:TDriverRequest); Override;
Function _Item(AIndex:Integer):TDriverRequest; Override;
Procedure SetFilterDisplayOnly(AValue:Boolean);
Function GetTotalCount:Integer;
Procedure SetOnRequestProcessed(ARoutine:TRequestListOnRequestProcessed);
Function GetOnRequestProcessed:TRequestListOnRequestProcessed;
Procedure SetParsers(AValue:TObjectList<TDataParser>);
Function GetParsers:TObjectList<TDataParser>;
Procedure SetSymStore(AStore:TModuleSymbolStore);
Function GetSymStore:TModuleSymbolStore;
Public
UpdateRequest : TList<PREQUEST_GENERAL>;
Constructor Create; Reintroduce;
Destructor Destroy; Override;
Function RefreshMaps:Cardinal;
Procedure Clear; Override;
Function RowCount : Cardinal; Override;
Function Update:Cardinal; Override;
Procedure SaveToStream(AStream:TStream; AFormat:ERequestLogFormat);
Procedure SaveToFile(AFileName:WideString; AFormat:ERequestLogFormat);
Procedure LoadFromStream(AStream:TStream; ARequireHeader:Boolean = True);
Procedure LoadFromFile(AFileName:WideString; ARequireHeader:Boolean = True);
Procedure Reevaluate;
Property FilterDisplayOnly : Boolean Read FFilterDisplayOnly Write SetFilterDisplayOnly;
Property OnRequestProcessed : TRequestListOnRequestProcessed Read GetOnRequestProcessed Write SetOnRequestProcessed;
Property TotalCount : Integer Read GetTotalCount;
Property Parsers : TObjectList<TDataParser> Read GetParsers Write SetParsers;
Property SymStore : TModuleSymbolStore Read GetSymStore Write SetSymStore;
Property List : TRequestList Read FList;
end;
Implementation
Uses
SysUtils,
NameTables,
Utils;
(** TRequestListModel **)
Function TRequestListModel.GetColumn(AItem:TDriverRequest; ATag:NativeUInt):WideString;
begin
Result := '';
AItem.GetColumnValue(ERequestListModelColumnType(ATag), Result);
end;
Procedure TRequestListModel.FreeItem(AItem:TDriverRequest);
begin
AItem.Free;
end;
Function TRequestListModel._Item(AIndex:Integer):TDriverRequest;
begin
Result := FList[AIndex];
end;
Procedure TRequestListModel.SetFilterDisplayOnly(AValue:Boolean);
begin
FList.FilterDisplayOnly := AValue;
end;
Function TRequestListModel.RowCount : Cardinal;
begin
Result := FList.Count;
end;
Function TRequestListModel.Update:Cardinal;
Var
requestBuffer : PREQUEST_GENERAL;
begin
Result := ERROR_SUCCESS;
If Assigned(UpdateRequest) Then
begin
For requestBuffer In UpdateRequest Do
Result := FList.ProcessBuffer(requestBuffer);
UpdateRequest := Nil;
end;
Inherited Update;
end;
Function TRequestListModel.RefreshMaps:Cardinal;
begin
Result := FList.RefreshMaps;
end;
Procedure TRequestListModel.Clear;
begin
Inherited Clear;
FList.Clear;
end;
Constructor TRequestListModel.Create;
begin
Inherited Create(Nil);
UpdateRequest := Nil;
FList := TRequestList.Create;
RefreshMaps;
end;
Destructor TRequestListModel.Destroy;
begin
FList.Free;
Inherited Destroy;
end;
Procedure TRequestListModel.SaveToStream(AStream:TStream; AFormat:ERequestLogFormat);
begin
FList.SaveToStream(AStream, AFormat);
end;
Procedure TRequestListModel.SaveToFile(AFileName:WideString; AFormat:ERequestLogFormat);
begin
FList.SaveToFile(AFilename, AFormat);
end;
Procedure TRequestListModel.LoadFromStream(AStream:TStream; ARequireHeader:Boolean = True);
begin
FList.LoadFromStream(AStream, ARequireHeader);
Update;
end;
Procedure TRequestListModel.LoadFromFile(AFileName:WideString; ARequireHeader:Boolean = True);
begin
FList.LoadFromFile(AFilename, ARequireHeader);
Update;
end;
Procedure TRequestListModel.OnAdvancedCustomDrawItemCallback(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage; var DefaultDraw: Boolean);
Var
dr : TDriverRequest;
begin
dr := FList[Item.Index];
With Sender.Canvas Do
begin
If Item.Selected Then
begin
Brush.Color := clHighLight;
Font.Color := clHighLightText;
Font.Style := [fsBold];
end
Else If dr.Highlight Then
begin
Brush.Color := dr.HighlightColor;
If Utils.ColorLuminanceHeur(dr.HighlightColor) >= 1490 Then
Font.Color := ClBlack
Else Font.Color := ClWhite;
end;
end;
DefaultDraw := True;
end;
Procedure TRequestListModel.Reevaluate;
begin
FList.Reevaluate;
If Assigned(Displayer) Then
begin
Displayer.Items.Count := FList.Count;
Displayer.Invalidate;
end;
end;
Function TRequestListModel.GetTotalCount:Integer;
begin
Result := FList.GetTotalCount;
end;
Procedure TRequestListModel.SetOnRequestProcessed(ARoutine:TRequestListOnRequestProcessed);
begin
FList.OnRequestProcessed := ARoutine;
end;
Function TRequestListModel.GetOnRequestProcessed:TRequestListOnRequestProcessed;
begin
Result := FList.OnRequestProcessed;
end;
Procedure TRequestListModel.SetParsers(AValue:TObjectList<TDataParser>);
begin
FList.Parsers := AValue;
end;
Function TRequestListModel.GetParsers:TObjectList<TDataParser>;
begin
Result := FList.Parsers;
end;
Procedure TRequestListModel.SetSymStore(AStore:TModuleSymbolStore);
begin
FList.SymStore := AStore;
end;
Function TRequestListModel.GetSymStore:TModuleSymbolStore;
begin
Result := FList.SymStore;
end;
End.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.