text stringlengths 14 6.51M |
|---|
(*
Category: SWAG Title: SORTING ROUTINES
Original name: 0008.PAS
Description: COUNT2.PAS
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:57
*)
{
>I'm in need of a FAST way of finding the largest and the smallest
>30 numbers out of about 1000 different numbers.
> ...Assuming that the 1000 numbers are in random-order, I imagine
> that the simplest (perhaps fastest too) method would be to:
> 1- Read the numbers in an Array.
> 2- QuickSort the Array.
> 3- First 30 and last 30 of Array are the numbers you want.
> ...Here's a QuickSort demo Program that should help you With the
> sort: ...
Stop the presses, stop the presses!
Remember the recent Integer sort contest, on the Intelec Programming
conference? The fastest method was a "counting" sort technique, which
used the Integers (to be sorted) as indexes of an Array.
You asked John Kuhn how it worked, as his example code was in messy
C. I sent you an explanation, along With example TP source. Around
that time my link to Intelec was intermittently broken; I didn't
hear back from you - so you may not have received my message (dated
Jan.02.1993). I hope you won't mind if I re-post it here and now...
In a message With John Kuhn...
> Simply toggle the sign bit of the values beFore sorting. Everything
> falls into place appropriately from there.
> ...OK, but how about toggling them back to their original
> state AFTER sorting? (I want to maintain negative numbers)
> How can you tell which data elements are negative numbers???
Hi Guy,
if you've got all of this under your belt, then please disregard
the following explanation ...
By toggling the high bit, the Integers are changed in a way that,
conveniently, allows sorting by magnitude: from the "most negative"
to "most positive," left to right, using an Array With unsigned
indexes numbering 0...FFFFh. The Array size represents the number
of all possible (16-bit) Integers... -32768 to 32767.
The "Count Sort" involves taking an Integer, toggling its high bit
(whether the Integer is originally positive or negative), then
using this tweaked value as an index into the Array. The tweaked
value is used only as an Array index (it becomes an unsigned
index somewhere within 0..FFFFh, inclusive).
The Array elements, which are initialized to zero, are simply the
counts of the _occurrences_ of each Integer. The original Integers,
With proper sign, are _derived_ from the indexes which point to
non-zero elements (after the "sort")... ie. an original Integer is
derived by toggling the high bit of a non-zero element's index.
Array elements of zero indicate that no Integer of the corresponding
(derived) value was encountered, and can be ignored. if any element
is non-zero, its index is used to derive the original Integer. if
an Array element is greater than one (1), then the corresponding
Integer occurred more than once.
A picture is worth 1000 Words: The following simplified example
sorts some negative Integers. The entire Count Sort is done by
a Single For-do-inC() loop - hence its speed. The xors do the
required high-bit toggling ...
}
Program DemoCountSort; { Turbo Pascal Count Sort. G.Vigneault }
{ some negative Integers to sort ... }
Const
SomeNegs : Array [0..20] of Integer =
(-2,-18,-18,-20000,-100,-10,-8,-11,-5,
-1300,-17,-1,-16000,-4,-12,-15,-19,-1,
-31234,-6,-7000 );
{ pick an Array to acComplish Count Sort ... }
Var
NegNumArray : Array [$0000..$7FFF] of Byte;
{ PosNumArray : Array [$8000..$FFFF] of Byte; }
{ AllNumArray : Array [$0000..$FFFF] of Byte; use heap }
Index : Word;
IntCount : Byte;
begin
{ Initialize }
FillChar( NegNumArray, Sizeof(NegNumArray), 0 );
{ Count Sort (the inC does this) ... }
For Index := 0 to 20 do
{ Just 21 negative Integers to sort }
inC( NegNumArray[ Word(SomeNegs[Index] xor $8000) ]);
{ then display the sorted Integers ... }
For Index := 0 to $7FFF do
{ Check each Array element }
For IntCount:= 1 to NegNumArray[Index] do
{ For multiples }
WriteLn( Integer(Index xor $8000) ); { derive value }
end { DemoCountSort }.
|
unit formMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls;
type
TfrmMain = class(TForm)
pbCopyFile: TButton;
reReport: TRichEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
pbClose: TButton;
pbClear: TButton;
GroupBox1: TGroupBox;
pbWow64EnableWow64FsRedirection: TButton;
pbWow64RevertWow64FsRedirection: TButton;
pbWow64DisableWow64FsRedirection: TButton;
procedure pbWow64EnableWow64FsRedirectionClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure pbWow64RevertWow64FsRedirectionClick(Sender: TObject);
procedure pbWow64DisableWow64FsRedirectionClick(Sender: TObject);
procedure pbCopyFileClick(Sender: TObject);
private
FOldValue: Pointer;
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
uses
SDUGeneral,
SDUWindows64;
const
// This CSIDL value isn't included in ShlObj in Delphi 5
CSIDL_SYSTEM = $0025;
procedure TfrmMain.pbCopyFileClick(Sender: TObject);
var
srcFilename: string;
destPath: string;
destFilename: string;
copyOK: boolean;
begin
destPath := SDUGetSpecialFolderPath(CSIDL_SYSTEM);
srcFilename := ParamStr(0); // This executable
destFilename := destPath+'\'+ExtractFilename(srcFilename);
copyOK := CopyFile(PChar(srcFilename), PChar(destFilename), TRUE);
reReport.lines.add('File copy operation result: '+SDUBoolToStr(copyOK));
reReport.lines.add('Please manually check:');
reReport.lines.add(' '+destPath);
reReport.lines.add('for a copy of this executable');
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
self.caption:= Application.Title;
reReport.lines.clear();
end;
procedure TfrmMain.pbWow64EnableWow64FsRedirectionClick(Sender: TObject);
var
fnOut: boolean;
begin
fnOut := SDUWow64EnableWow64FsRedirection(FOldValue);
reReport.lines.add('SDUWow64EnableWow64FsRedirection: '+SDUBoolToStr(fnOut));
end;
procedure TfrmMain.pbWow64RevertWow64FsRedirectionClick(Sender: TObject);
var
fnOut: boolean;
begin
fnOut := SDUWow64RevertWow64FsRedirection(FOldValue);
reReport.lines.add('SDUWow64RevertWow64FsRedirection: '+SDUBoolToStr(fnOut));
end;
procedure TfrmMain.pbWow64DisableWow64FsRedirectionClick(Sender: TObject);
var
fnOut: boolean;
begin
fnOut := SDUWow64DisableWow64FsRedirection(FOldValue);
reReport.lines.add('SDUWow64DisableWow64FsRedirection: '+SDUBoolToStr(fnOut));
end;
END.
|
unit UII2XDialog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Buttons, StdCtrls, ExtCtrls, ComCtrls, ActnList;
type
TI2XDialogUI = class(TForm)
pnlTop: TPanel;
pnlLeft: TPanel;
pnlYes: TPanel;
pnlOK: TPanel;
pnlCancel: TPanel;
chkNeverAsk: TCheckBox;
btnCancel: TSpeedButton;
btnOK: TSpeedButton;
btnYes: TSpeedButton;
pnlNo: TPanel;
btnNo: TSpeedButton;
pnlProgressBar: TPanel;
ProgressBar: TProgressBar;
lblMainText: TLabel;
memText: TMemo;
ActionList: TActionList;
acSelect: TAction;
procedure FormCreate(Sender: TObject);
procedure btnYesClick(Sender: TObject);
procedure btnNoClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
private
FResult : integer;
FIsActive : boolean;
FOnCancelEvent: TNotifyEvent;
function getMainTitle() : string;
procedure setMainTitle(const Value: string);
function getDialogText: string;
procedure setDialogText(const Value: string);
function getResult: integer;
procedure setResult(const Value: integer);
procedure btnSelect(Sender: TObject);
function getShowAgainCheck: boolean;
procedure setShowAgainCheck(const Value: boolean);
function getProgress: integer;
procedure setProgress(const Value: integer);
function getPercentComplete: integer;
procedure setPercentComplete(const Value: integer);
function getShowProgressBar: boolean;
procedure setShowProgressBar(const Value: boolean);
public
function ShowDialog(const Msg: string; Buttons: TMsgDlgButtons = [mbOK]; DefaultButton: TMsgDlgBtn = mbOK): integer;
property MainTitle : string read getMainTitle write setMainTitle;
property IsActive : boolean read FIsActive write FIsActive;
property DialogText : string read getDialogText write setDialogText;
property Result : integer read getResult write setResult;
property ShowAgainCheckVisible : boolean read getShowAgainCheck write setShowAgainCheck;
property OnCancel : TNotifyEvent read FOnCancelEvent write FOnCancelEvent;
property Progress : integer read getProgress write setProgress;
property ShowProgressBar : boolean read getShowProgressBar write setShowProgressBar;
property PercentComplete : integer read getPercentComplete write setPercentComplete;
end;
var
frmI2XDialogUI: TI2XDialogUI;
implementation
{$R *.dfm}
{ TI2XDialogUI }
procedure TI2XDialogUI.btnYesClick(Sender: TObject);
begin
btnSelect( Sender );
end;
procedure TI2XDialogUI.btnCancelClick(Sender: TObject);
begin
btnSelect( Sender );
if ( Assigned( FOnCancelEvent ) ) then
FOnCancelEvent( Self );
end;
procedure TI2XDialogUI.btnNoClick(Sender: TObject);
begin
btnSelect( Sender );
end;
procedure TI2XDialogUI.btnOKClick(Sender: TObject);
begin
btnSelect( Sender );
end;
procedure TI2XDialogUI.btnSelect(Sender: TObject);
Begin
self.Result := TControl(Sender).Tag;
FIsActive := false;
Self.Hide;
End;
procedure TI2XDialogUI.FormCreate(Sender: TObject);
begin
self.btnCancel.Tag := mrCancel;
self.btnOK.Tag := mrOK;
self.btnYes.Tag := mrYes;
self.btnNo.Tag := mrNo;
self.lblMainText.Caption := '';
self.memText.Text := '';
FIsActive := false;
self.ShowProgressBar := false;
end;
function TI2XDialogUI.getDialogText: string;
begin
Result := self.memText.Text;
end;
function TI2XDialogUI.getMainTitle() : string;
begin
Result := self.lblMainText.Caption;
end;
function TI2XDialogUI.getPercentComplete: integer;
begin
Result := self.ProgressBar.Position;
//BarSpaceWidth := round( self.ProgressBar.Max / 100.0 * (100-self.FPercentComplete));
end;
function TI2XDialogUI.getProgress: integer;
begin
Result := self.ProgressBar.Position;
end;
function TI2XDialogUI.getResult: integer;
begin
Result := FResult;
end;
function TI2XDialogUI.getShowAgainCheck: boolean;
begin
Result := self.pnlLeft.Visible;
end;
function TI2XDialogUI.getShowProgressBar: boolean;
begin
Result := self.ProgressBar.Visible;
end;
procedure TI2XDialogUI.setDialogText(const Value: string);
begin
self.memText.Text := Value;
end;
procedure TI2XDialogUI.setMainTitle(const Value: string);
begin
self.lblMainText.Caption := value;
end;
procedure TI2XDialogUI.setPercentComplete(const Value: integer);
begin
self.ProgressBar.Position := Value;
end;
procedure TI2XDialogUI.setProgress(const Value: integer);
begin
self.ProgressBar.Position := Value;
end;
procedure TI2XDialogUI.setResult(const Value: integer);
begin
FResult := Value;
end;
procedure TI2XDialogUI.setShowAgainCheck(const Value: boolean);
begin
self.pnlLeft.Visible := Value;
end;
procedure TI2XDialogUI.setShowProgressBar(const Value: boolean);
begin
self.ProgressBar.Visible := Value;
end;
function TI2XDialogUI.ShowDialog(const Msg: string;
Buttons: TMsgDlgButtons; DefaultButton: TMsgDlgBtn): integer;
Begin
DialogText := Msg;
self.pnlYes.Visible := (mbYes in Buttons);
self.pnlNo.Visible := (mbNo in Buttons);
self.pnlCancel.Visible := (mbCancel in Buttons);
self.pnlOk.Visible := (mbOk in Buttons);
if ( DefaultButton = mbYes ) then FResult := mrYes;
if ( DefaultButton = mbNo ) then FResult := mrNo;
if ( DefaultButton = mbCancel ) then FResult := mrCancel;
if ( DefaultButton = mbOk ) then FResult := mrOk;
self.lblMainText.Visible := ( Length( self.lblMainText.Caption ) > 0 );
FIsActive := true;
self.Show;
End;
end.
|
Unit ProcessList;
Interface
Uses
Generics.Collections,
RefObject;
Type
TImageEntry = Class (TRefObject)
Public
Time : UInt64;
BaseAddress : Pointer;
ImageSize : NativeUInt;
FileName : WideString;
end;
TProcessEntry = Class (TRefObject)
Private
FImageName : WideString;
FBaseName : WideString;
FCommandLine : WideString;
FProcessId : Cardinal;
FCreatorProcessId : Cardinal;
FTerminated : Boolean;
FImageMap : TRefObjectList<TImageEntry>;
Public
Constructor Create(AProcessId:Cardinal; ACreatorProcessId:Cardinal; AFileName:WideString; ACommandLine:WideString); Reintroduce;
Destructor Destroy; Override;
Procedure AddImage(ATime:UInt64; ABase:Pointer; ASize:NativeUInt; AFileName:WideString);
Procedure Terminate;
Function ImageByAddress(AAddress:Pointer; AImageList:TRefObjectList<TImageEntry>):Boolean; Overload;
Function ImageByAddress(AAddress:Pointer):TImageEntry; Overload;
Procedure EnumImages(AList:TRefObjectList<TImageEntry>);
Property ImageName : WideString Read FImageName;
Property BaseName : WideString Read FBaseName;
Property CommandLine : WideString Read FCommandLine;
Property ProcessId : Cardinal Read FProcessId;
Property CreatorProcessId : Cardinal Read FCreatorProcessId;
Property Terminated : Boolean Read FTerminated;
end;
Implementation
Uses
SysUtils,
Generics.Defaults;
(** TProcessEntry **)
Constructor TProcessEntry.Create(AProcessId:Cardinal; ACreatorProcessId:Cardinal; AFileName:WideString; ACommandLine:WideString);
begin
Inherited Create;
FCreatorProcessId := ACreatorProcessId;
FProcessId := AProcessId;
FImageName := AFileName;
FBaseName := ExtractFileName(AFileName);
FCommandLine := ACommandLine;
FImageMap := TRefObjectList<TImageEntry>.Create;
end;
Destructor TProcessEntry.Destroy;
begin
FImageMap.Free;
Inherited Destroy;
end;
Procedure TProcessEntry.AddImage(ATime:UInt64; ABase:Pointer; ASize:NativeUInt; AFileName:WideString);
Var
ie : TImageEntry;
begin
ie := TImageEntry.Create;
ie.Time := ATime;
ie.BaseAddress := ABase;
ie.ImageSize := ASize;
ie.FileName := AFileName;
FImageMap.Add(ie);
FImageMap.Sort(
TComparer<TImageEntry>.Construct(
Function(const A, B: TImageEntry): Integer
begin
Result := 0;
If A.Time < B.Time Then
Result := -1
Else If A.Time > B.Time Then
Result := 1;
end
)
);
ie.Free;
end;
Procedure TProcessEntry.Terminate;
begin
FTerminated := True;
end;
Function TProcessEntry.ImageByAddress(AAddress:Pointer; AImageList:TRefObjectList<TImageEntry>):Boolean;
Var
ie : TImageEntry;
begin
Result := False;
For ie In FImageMap Do
begin
If (NativeUInt(ie.BaseAddress) <= NativeUInt(AAddress)) And
(NativeUInt(AAddress) < NativeUInt(ie.BaseAddress) + ie.ImageSize) Then
begin
AImageList.Add(ie);
Result := True;
end;
end;
end;
Function TProcessEntry.ImageByAddress(AAddress:Pointer):TImageEntry;
Var
ie : TImageEntry;
begin
Result := Nil;
For ie In FImageMap Do
begin
If (NativeUInt(ie.BaseAddress) <= NativeUInt(AAddress)) And
(NativeUInt(AAddress) < NativeUInt(ie.BaseAddress) + ie.ImageSize) Then
begin
ie.Reference;
Result := ie;
Break;
end;
end;
end;
Procedure TProcessEntry.EnumImages(AList:TRefObjectList<TImageEntry>);
Var
ie : TImageEntry;
begin
For ie In FImageMap Do
AList.Add(ie);
end;
End.
|
procedure AssignGraphic(Source: TGraphic);
var
Data: THandle;
Format: Word;
begin
OpenClipboard(Application.handle);
try
EmptyClipboard;
Format := CF_ENHMETAFILE;
Data := CopyEnhMetaFile(MetaFileHandle, nil);
SetClipboardData(Format, Data);
finally
CloseClipboard;
end;
end;
|
unit ufrmMaintenanceBarcode;
interface
uses
Windows, SysUtils, Variants, Classes, Controls, Forms,
ufrmMasterBrowse, StdCtrls, ExtCtrls, ActnList,
frxClass, frxBarcode, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, dxBarBuiltInMenu, cxStyles,
cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB,
cxDBData, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, Vcl.Menus,
cxCurrencyEdit, System.Actions, ufraFooter4Button, cxButtons,
cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxLabel, cxGridLevel,
cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, cxPC;
type
TBarcodeSize = (bsPriceTag, bsPluExCode, bsDesciption, bsSubGrupPlu, bsPrice);
TSearchFor = (sfPLU, sfCatalog, sfPO, sfNone);
TfrmMaintenanceBarcode = class(TfrmMasterBrowse)
pnl1: TPanel;
lbl1: TLabel;
lblPrice: TLabel;
lbl3: TLabel;
edtProductCode: TEdit;
edtProductName: TEdit;
edtBarcodeOld: TEdit;
BarcodeSize: TComboBox;
Label1: TLabel;
lbl4: TLabel;
lbl5: TLabel;
lbl6: TLabel;
edtSubGroupID: TEdit;
edtCategoryID: TEdit;
curredtPrice: TcxCurrencyEdit;
curredtPriceScoreOut: TcxCurrencyEdit;
Uom: TLabel;
edtUomID: TEdit;
edtUomNm: TEdit;
Label2: TLabel;
edtBarcodeNew: TEdit;
edtSubGroupNm: TEdit;
edtCategoryNm: TEdit;
edtOutletID: TEdit;
edtOutletNm: TEdit;
Label3: TLabel;
chkUpdate: TCheckBox;
actDeleteRow: TAction;
actUpdateBarcode: TAction;
btnUpBarCode: TcxButton;
btnSearchPO: TcxButton;
procedure actAddExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure actPrintExecute(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure strgGridKeyPress(Sender: TObject; var Key: Char);
// procedure edtProductCodeKeyPress(Sender: TObject; var Key: Char);
procedure BarcodeSizeChange(Sender: TObject);
procedure actDeleteRowExecute(Sender: TObject);
procedure actEditExecute(Sender: TObject);
procedure actRefreshExecute(Sender: TObject);
procedure frxrprtReport1GetValue(const VarName: String;
var Value: Variant);
procedure actUpdateBarcodeExecute(Sender: TObject);
procedure chkUpdateClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure udsBarcodeFirst(Sender: TObject);
procedure udsBarcodeNext(Sender: TObject);
procedure udsBarcodePrior(Sender: TObject);
procedure udsBarcodeCheckEOF(Sender: TObject; var Eof: Boolean);
procedure edtProductCodeKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edtUomIDKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edtBarcodeOldKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
noRow : Integer;
FRecNo : Integer;
FRecMax : Integer;
slNamaBrg : TStringList;
slPlu : TStringList;
slExtCode : TStringList;
slBarcode : TStringList;
slPrice : TStringList;
slPriceScoreOut : TStringList;
slDescription : TStringList;
slSubGrup : TStringList;
slKatCode : TStringList;
slOutlet : TStringList;
slTgl : TStringList;
FSizeOfBarcode: TBarcodeSize;
procedure ClearAtributData;
procedure ClearAttribut;
procedure ParseHeaderGrid;
procedure SetBarcodeSize(const Aval: TBarcodeSize);
procedure GetBrgCode(alsLookup: Boolean);
procedure GetBrgUom(alsLookup: Boolean);
procedure SetData;
public
procedure LoadDataFromPO(aPONo : string; aUnitID : Integer);
{ Public declarations }
published
property SizeOfBarcode: TBarcodeSize read FSizeOfBarcode write SetBarcodeSize;
end;
var
frmMaintenanceBarcode: TfrmMaintenanceBarcode;
implementation
uses
uTSCommonDlg, Math, uRetnoUnit;
{$R *.dfm}
const
{
PLU CODE
BARCODE NO
PRODUCT NAME
QTY
DESCRIPTION
PRICE
PRICE SCORE OUT
SUB GROUP
CATEGORY GROUP
}
_kolNo : Integer = 0;
_kolPlu : Integer = 1;
_kolUom : Integer = 2;
_kolBarcode : Integer = 3;
_kolPluNm : Integer = 4;
_kolQty : Integer = 5;
_kolDesc : Integer = 6;
_kolPrice : Integer = 7;
_kolPriceSOut : Integer = 8;
_kolSubGrp : integer = 9;
_kolCategory : Integer = 10;
_kolOutlet : Integer = 11;
_fixedRow : Integer = 1;
_rowCount : Integer = 2;
_colCount : Integer = 12;
_typeHrg : Integer = 2;
procedure TfrmMaintenanceBarcode.actAddExecute(Sender: TObject);
begin
inherited;
ClearAttribut;
ClearAtributData;
ParseHeaderGrid;
end;
procedure TfrmMaintenanceBarcode.SetBarcodeSize(const Aval: TBarcodeSize);
begin
FSizeOfBarcode:= Aval;
end;
procedure TfrmMaintenanceBarcode.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action:= caFree;
end;
procedure TfrmMaintenanceBarcode.FormDestroy(Sender: TObject);
begin
inherited;
frmMaintenanceBarcode:= nil;
end;
procedure TfrmMaintenanceBarcode.actPrintExecute(Sender: TObject);
var
i, j,
Qty : Integer;
begin
{if (strgGrid.RowCount=2) and (strgGrid.Cells[0,1]='') then
begin
CommonDlg.ShowErrorEmpty('Data on grid');
Exit;
end;
if (strgGrid.Cells[_kolQty,strgGrid.Row]='') then
begin
CommonDlg.ShowErrorEmpty('QUANTITY of '+strgGrid.Cells[1,strgGrid.Row]);
Exit;
end;
slNamaBrg := TStringList.Create;
slPlu := TStringList.Create;
slExtCode := TStringList.Create;
slBarcode := TStringList.Create;
slPrice := TStringList.Create;
slPriceScoreOut := TStringList.Create;
slDescription := TStringList.Create;
slSubGrup := TStringList.Create;
slKatCode := TStringList.Create;
slOutlet := TStringList.Create;
slTgl := TStringList.Create;
try
FRecMax := 0;
for i := strgGrid.FixedRows to strgGrid.RowCount - 1 do // row count of string grid
begin
if strgGrid.Cells[_kolNo, i]<>'' then
begin
Qty := StrToInt(strgGrid.Cells[_kolQty,i]);
FRecMax := FRecMax + Qty;
for j:= 1 to Qty do //quantity of product
begin
slNamaBrg.Add(strgGrid.Cells[_kolPluNm, i]);
slPlu.Add(strgGrid.Cells[_kolPlu,i]);
slExtCode.Add(strgGrid.Cells[_kolBarcode, i]);
slBarcode.Add(strgGrid.Cells[_kolBarcode, i]);
slPrice.Add(strgGrid.Cells[_kolPrice,i]);
slPriceScoreOut.Add(strgGrid.Cells[_kolPriceSOut,i]);
slDescription.Add(strgGrid.Cells[_kolDesc,i]);
slSubGrup.Add(strgGrid.Cells[_kolSubGrp,i]);
slKatCode.Add(strgGrid.Cells[_kolCategory,i]);
slOutlet.Add(strgGrid.Cells[_kolOutlet,i]);
slTgl.Add(FormatDateTime('DD-MM-YYYY',cGetServerTime));
end;
end
else
Break;
end;
udsBarcode.RangeEndCount := slNamaBrg.Count;
//ExtractFilePath(Application.ExeName) + '/template/BarcodeSubGrupnExCode1.fr3');
case SizeOfBarcode of
bsPriceTag : frxrprtReport1.LoadFromFile(FFilePathReport + '\PriceTag1.fr3');
bsPluExCode : frxrprtReport1.LoadFromFile(FFilePathReport + '\BarcodeSubGrupnExCode1.fr3');
bsDesciption: frxrprtReport1.LoadFromFile(FFilePathReport + '\BarcodeSubGrupnDesc1.fr3');
bsSubGrupPlu: frxrprtReport1.LoadFromFile(FFilePathReport + '\BarcodeSubGrupnPlu1.fr3');
bsPrice : frxrprtReport1.LoadFromFile(FFilePathReport + '\BarcodeSubGrupnPrice1.fr3');
end;
frxrprtReport1.ShowReport;
finally
FreeAndNil(slNamaBrg);
FreeAndNil(slPlu);
FreeAndNil(slExtCode);
FreeAndNil(slBarcode);
FreeAndNil(slPrice);
FreeAndNil(slPriceScoreOut);
FreeAndNil(slDescription);
FreeAndNil(slSubGrup);
FreeAndNil(slKatCode);
FreeAndNil(slOutlet);
end;
}
end;
procedure TfrmMaintenanceBarcode.FormShow(Sender: TObject);
begin
ParseHeaderGrid;
BarcodeSize.ItemIndex:= 0;
FSizeOfBarcode:= bsPriceTag;
edtProductCode.SetFocus;
end;
procedure TfrmMaintenanceBarcode.strgGridKeyPress(Sender: TObject;
var Key: Char);
begin
// if (strgGrid.Col = 2) then
if not (Key in ['0'..'9', Chr(VK_DELETE), Chr(VK_BACK)]) then
Key := #0;
end;
procedure TfrmMaintenanceBarcode.BarcodeSizeChange(Sender: TObject);
begin
inherited;
case BarcodeSize.ItemIndex of
0: FSizeOfBarcode:= bsPriceTag;
1: FSizeOfBarcode:= bsPluExCode;
2: FSizeOfBarcode:= bsDesciption;
3: FSizeOfBarcode:= bsSubGrupPlu;
4: FSizeOfBarcode:= bsPrice;
end; // case
end;
procedure TfrmMaintenanceBarcode.actDeleteRowExecute(Sender: TObject);
begin
inherited;
// strgGrid.RemoveSelectedRows;
end;
procedure TfrmMaintenanceBarcode.actEditExecute(Sender: TObject);
begin
inherited;
{if strgGrid.RowCount > strgGrid.FixedRows then
begin
if strgGrid.RowCount > strgGrid.FixedRows + 1 then
begin
strgGrid.RemoveRows(strgGrid.row , 1);
end
else
begin
strgGrid.ClearRows(strgGrid.row, 1);
end;
noRow := noRow - 1;
end;
}
end;
procedure TfrmMaintenanceBarcode.actRefreshExecute(Sender: TObject);
var
sSQL: string;
aPOUnitID : integer;
begin
inherited;
chkUpdate.Checked := False;
aPOUnitID := MasterNewUnit;
sSQL := 'SELECT P.PO_NO, P.PO_DATE,SMG.SUPMG_CODE, '
+ ' P.PO_VALID_DATE, P.PO_TOTAL, STA.STAPO_NAME, P.PO_DESC_PRINT '
+ ' FROM PO P, REF$STATUS_PO STA, SUPLIER_MERCHAN_GRUP SMG, REF$MERCHANDISE_GRUP MG '
+ ' WHERE STA.STAPO_ID=P.PO_STAPO_ID '
+ ' AND STA.STAPO_UNT_ID=P.PO_STAPO_UNT_ID '
+ ' AND SMG.SUPMG_SUB_CODE=P.PO_SUPMG_SUB_CODE '
+ ' AND SMG.SUPMG_MG_UNT_ID = P.PO_SUPMG_UNT_ID '
+ ' AND MG.MERCHANGRUP_ID = SMG.SUPMG_MERCHANGRUP_ID '
+ ' AND MG.MERCHANGRUP_UNT_ID = SMG.SUPMG_UNT_ID '
// + ' and P.PO_STAPO_ID = 5' //telah receive
+ ' AND P.po_unt_id = ' + IntToStr(aPOUnitID);
{
with cLookUp('Daftar PO', sSQL) do
begin
try
LoadDataFromPO(Strings[0], aPOUnitID);
finally
Free;
end;
end;
}
end;
procedure TfrmMaintenanceBarcode.frxrprtReport1GetValue(const VarName: String;
var Value: Variant);
begin
inherited;
// if FSizeOfBarcode = bsPriceTag then
// begin
// if CompareText(VarName, 'nama_barang') = 0 then
// Value := slNamaBrg[udsBarcode.RecNo];
//
// if CompareText(VarName, 'plu') = 0 then
// Value := slPlu[udsBarcode.RecNo];
//
// if CompareText(VarName, 'ext_code') = 0 then
// Value := slExtCode[udsBarcode.RecNo];
//
// if CompareText(VarName, 'barcode') = 0 then
// Value := slBarcode[udsBarcode.RecNo];
//
// if CompareText(VarName, 'harga') = 0 then
// Value := slPrice[udsBarcode.RecNo];
//
// if CompareText(VarName, 'subgrup') = 0 then
// Value := slSubGrup[udsBarcode.RecNo];
//
// if CompareText(VarName, 'tgl') = 0 then
// Value := slTgl[udsBarcode.RecNo];
//
// end
// else if FSizeOfBarcode = bsPluExCode then
// begin
// if CompareText(VarName, 'nama_barang') = 0 then
// Value := slNamaBrg[udsBarcode.RecNo];
//
// if CompareText(VarName, 'plu') = 0 then
// Value := slPlu[udsBarcode.RecNo];
//
// if CompareText(VarName, 'excode') = 0 then
// Value := slExtCode[udsBarcode.RecNo];
//
// if CompareText(VarName, 'barcode') = 0 then
// Value := slBarcode[udsBarcode.RecNo];
//
// if CompareText(VarName, 'subgrup') = 0 then
// Value := slSubGrup[udsBarcode.RecNo];
// end
// else if FSizeOfBarcode = bsDesciption then
// begin
// if CompareText(VarName, 'nama_barang') = 0 then
// Value := slNamaBrg[udsBarcode.RecNo];
//
// if CompareText(VarName, 'plu') = 0 then
// Value := slPlu[udsBarcode.RecNo];
//
// if CompareText(VarName, 'barcode') = 0 then
// Value := slBarcode[udsBarcode.RecNo];
//
// if CompareText(VarName, 'Desc') = 0 then
// Value := slDescription[udsBarcode.RecNo];
//
// if CompareText(VarName, 'subgrup') = 0 then
// Value := slSubGrup[udsBarcode.RecNo];
// end
// else if FSizeOfBarcode = bsSubGrupPlu then
// begin
// if CompareText(VarName, 'nama_barang') = 0 then
// Value := slNamaBrg[udsBarcode.RecNo];
//
// if CompareText(VarName, 'plu') = 0 then
// Value := slPlu[udsBarcode.RecNo];
//
// if CompareText(VarName, 'barcode') = 0 then
// Value := slBarcode[udsBarcode.RecNo];
//
// if CompareText(VarName, 'subgrup') = 0 then
// Value := slSubGrup[udsBarcode.RecNo];
//
// if CompareText(VarName, 'outlet') = 0 then
// Value := slOutlet[udsBarcode.RecNo];
// end
// else if FSizeOfBarcode = bsPrice then
// begin
// if CompareText(VarName, 'nama_barang') = 0 then
// Value := slNamaBrg[udsBarcode.RecNo];
//
// if CompareText(VarName, 'plu') = 0 then
// Value := slPlu[udsBarcode.RecNo];
//
// if CompareText(VarName, 'barcode') = 0 then
// Value := slBarcode[udsBarcode.RecNo];
//
// if CompareText(VarName, 'harga') = 0 then
// Value := slPrice[udsBarcode.RecNo];
//
// if CompareText(VarName, 'kat') = 0 then
// Value := slKatCode[udsBarcode.RecNo];
// end
end;
procedure TfrmMaintenanceBarcode.actUpdateBarcodeExecute(Sender: TObject);
var
i, j : Integer;
isUpBy : Boolean;
sBarCode : string;
begin
inherited;
if Trim(edtProductCode.Text)='' then Exit;
isUpBy := True;
{
if chkUpdate.Checked then
begin
isUpBy := UpdateByBrgCodeUom(edtBarcodeNew.Text, edtProductCode.Text,
edtUomID.Text, masternewunit.id);
if isUpBy then
begin
sBarCode := edtBarcodeNew.Text;
CommonDlg.ShowMessage('Update Sukses');
end
else
begin
CommonDlg.ShowMessage('Update Gagal!');
end;
end
else
begin
sBarCode := edtBarcodeOld.Text;
end;
if isUpBy then
begin
if strgGrid.FloatingFooter.Visible then
j := _fixedRow + 1
else
j := _fixedRow;
i := strgGrid.rowCount;
if noRow<0 then noRow := 0;
if (noRow >= i -j) then
strgGrid.AddRow;
strgGrid.Cells[_kolNo, noRow + _fixedRow] := IntToStr(noRow + 1);
strgGrid.Cells[_kolPlu, noRow + _fixedRow] := edtProductCode.Text;
strgGrid.Cells[_kolUom, noRow + _fixedRow] := edtUomID.Text;
strgGrid.Cells[_kolBarcode, noRow + _fixedRow] := sBarCode;
strgGrid.Cells[_kolPluNm, noRow + _fixedRow] := edtProductName.Text;
strgGrid.Cells[_kolPrice, noRow + _fixedRow] := CurrToStr(curredtPrice.Value);
strgGrid.Cells[_kolPriceSOut, noRow + _fixedRow] := CurrToStr(curredtPriceScoreOut.Value);
strgGrid.Cells[_kolSubGrp, noRow + _fixedRow] := edtSubGroupID.Text;
strgGrid.Cells[_kolCategory, noRow + _fixedRow] := edtCategoryID.Text;
strgGrid.Cells[_kolOutlet, noRow + _fixedRow] := edtOutletID.Text;
Inc(noRow);
strgGrid.AutoSize := True;
end;
ClearAttribut;
ClearAtributData;
}
end;
procedure TfrmMaintenanceBarcode.ParseHeaderGrid;
begin
{
with strgGrid do
begin
Clear;
Cells[_kolNo,0] := 'NO';
Cells[_kolPlu,0] := 'PLU CODE';
Cells[_kolUom,0] := 'UOM';
Cells[_kolBarcode,0] := 'BARCODE';
Cells[_kolPluNm,0] := 'PRODUCT NAME';
Cells[_kolQty,0] := 'QTY';
Cells[_kolDesc,0] := 'DESCRIPTION';
Cells[_kolPrice,0] := 'PRICE';
Cells[_kolPriceSOut,0] := 'PRICE SCORE OUT';
Cells[_kolSubGrp,0] := 'SUB GROUP';
Cells[_kolCategory,0] := 'CATEGORY GROUP';
Cells[_kolOutlet,0] := 'OUTLET ID';
RowCount := _rowCount;
ColCount := _colCount;
FixedRows := _fixedRow;
AutoSize := True;
end;
noRow := 0 ;
}
end;
procedure TfrmMaintenanceBarcode.GetBrgCode(alsLookup: Boolean);
var
sSQL : string;
begin
sSQL := 'select a.BHJ_BRG_CODE as Kode, c.BRG_ALIAS as Nama,'
+ ' a.BHJ_SAT_CODE "UOM JUAL", c.BRG_SAT_CODE_STOCK as "UOM STOCK",'
+ ' a.BHJ_SELL_PRICE as "HARGA",'
+ ' a.BHJ_DISC_PERSEN AS "DISCOUNT %", a.BHJ_DISC_NOMINAL AS "DISCOUNT",'
+ ' a.BHJ_SELL_PRICE_DISC'
+ ' from BARANG_HARGA_JUAL a , REF$TIPE_HARGA b, barang c'
+ ' where a.BHJ_TPHRG_ID=b.TPHRG_ID'
+ ' and a.BHJ_TPHRG_UNT_ID=b.TPHRG_UNT_ID'
+ ' AND (c.BRG_CODE = a.BHJ_BRG_CODE AND c.BRG_UNT_ID = a.BHJ_BRG_CODE_UNT_ID)'
+ ' and a.BHJ_TPHRG_ID = '+ IntToStr(_typeHrg)
+ ' and a.BHJ_BRG_CODE_UNT_ID = '+ IntToStr(masternewunit);
{
if not alsLookup then
begin
sSQL := sSQL + ' AND a.BHJ_BRG_CODE = '+ Quot(edtProductCode.Text);
with cOpenQuery(sSQL)do
begin
try
if not Eof then
begin
edtProductName.Text := Fields[1].AsString;
end;
finally
Free;
end;
end;
end
else
GetDataIdNm('Get Data', sSQL, edtProductCode, edtProductName);
}
end;
procedure TfrmMaintenanceBarcode.GetBrgUom(alsLookup: Boolean);
var
sSQL : string;
begin
sSQL := 'SELECT c.KONVSAT_SAT_CODE_FROM AS "UOM JUAL",'
+ ' a.SAT_NAME AS "UOM NAME",'
+ ' c.KONVSAT_SAT_CODE_TO AS "UOM STOCK", c.KONVSAT_SCALE AS "KONVERSI"'
+ ' FROM REF$KONVERSI_SATUAN c, REF$SATUAN a'
+ ' where c.KONVSAT_SAT_CODE_FROM = a.SAT_CODE'
+ ' and c.KONVSAT_SCF_UNT_ID = a.SAT_UNT_ID'
+ ' and c.KONVSAT_BRG_CODE = '+ QuotedStr(edtProductCode.Text)
+ ' and c.KONVSAT_BRG_UNT_ID = '+ IntToStr(masternewunit);
{
if not alsLookup then
begin
edtUomID.Text := UpperCase(edtUomID.Text);
sSQL := sSQL + ' AND c.KONVSAT_SAT_CODE_FROM ='+ QuotedStr(edtUomID.Text);
with cOpenQuery(sSQL) do
begin
try
if not Eof then
begin
edtUomNm.Text := Fields[1].AsString;
end;
finally
Free
end;
end;
end
else
GetDataIdNm('Get Data', sSQL, edtUomID, edtUomNm);
}
end;
procedure TfrmMaintenanceBarcode.SetData;
var
sSQL : string;
begin
sSQL := 'select distinct a.BHJ_BRG_CODE as Kode,'
// c.BRG_ALIAS as Nama,'
// + ' a.BHJ_SAT_CODE "UOM JUAL", c.BRG_SAT_CODE_STOCK as "UOM STOCK",'
// + ' a.BHJ_SELL_PRICE as "HARGA",'
+ ' a.BHJ_SELL_PRICE_DISC, BHJ_SELL_PRICE_CORET,'
+ ' e.SUBGRUP_CODE, e.SUBGRUP_NAME, d.KAT_CODE, d.KAT_NAME,'
+ ' f.OUTLET_CODE, f.OUTLET_NAME, g.KONVSAT_BARCODE,'
+ ' a.BHJ_DISC_PERSEN AS "DISCOUNT %",'
+ ' a.BHJ_DISC_NOMINAL AS "DISCOUNT"'
+ ' from BARANG_HARGA_JUAL a , barang c, REF$KATEGORI d, REF$SUB_GRUP e,'
+ ' REF$OUTLET f, REF$konversi_satuan g'
+ ' where (c.BRG_CODE = a.BHJ_BRG_CODE AND c.BRG_UNT_ID = a.BHJ_BRG_CODE_UNT_ID)'
+ ' and c.BRG_KAT_ID = d.KAT_ID'
+ ' AND c.BRG_UNT_ID = d.KAT_UNT_ID'
+ ' and d.KAT_SUBGRUP_ID = e.SUBGRUP_ID'
+ ' AND d.KAT_SUBGRUP_UNT_ID = e.SUBGRUP_UNT_ID'
+ ' and f.OUTLET_ID = c.BRG_OUTLET_ID'
+ ' and f.OUTLET_UNT_ID = c.BRG_OUTLET_UNT_ID'
+ ' and g.KONVSAT_SAT_CODE_FROM = a.BHJ_SAT_CODE'
+ ' and g.KONVSAT_SCF_UNT_ID = a.BHJ_SAT_CODE_UNT_ID'
+ ' and g.KONVSAT_BRG_CODE = a.BHJ_BRG_CODE'
+ ' and g.KONVSAT_BRG_UNT_ID = a.BHJ_BRG_CODE_UNT_ID'
+ ' and a.BHJ_SAT_CODE = '+ QuotedStr(edtUomID.Text)
+ ' and a.BHJ_BRG_CODE_UNT_ID = '+ IntToStr(masternewunit)
+ ' and a.BHJ_BRG_CODE = '+ QuotedStr(edtProductCode.Text)
+ ' and a.BHJ_TPHRG_ID = 2 ' //set harga toko
+ ' order by a.DATE_CREATE desc';
{
with cOpenQuery(sSQL) do
begin
try
if not Eof then
begin
curredtPrice.Value := Fields[1].AsCurrency;
curredtPriceScoreOut.Value := Fields[2].AsCurrency;
edtSubGroupID.Text := Fields[3].AsString;
edtSubGroupNm.Text := Fields[4].AsString;
edtCategoryID.Text := Fields[5].AsString;
edtCategoryNm.Text := Fields[6].AsString;
edtOutletID.Text := Fields[7].AsString;
edtOutletNm.Text := Fields[8].AsString;
edtBarcodeOld.Text := Fields[9].AsString;
end
else
CommonDlg.ShowError('Barang Penjualan '+ Trim(edtProductName.Text) +' tidak ada');
finally
Free;
end;
end;
}
end;
procedure TfrmMaintenanceBarcode.chkUpdateClick(Sender: TObject);
begin
inherited;
if chkUpdate.Checked then
btnUpBarCode.Caption := 'Update'
else
btnUpBarCode.Caption := 'Load';
end;
procedure TfrmMaintenanceBarcode.ClearAtributData;
begin
edtBarcodeOld.Clear;
edtBarcodeNew.Clear;
edtUomID.Clear;
edtUomNm.Clear;
chkUpdate.Checked := False;
edtSubGroupID.Clear;
edtSubGroupNm.Clear;
edtCategoryID.Clear;
edtCategoryNm.Clear;
edtOutletID.Clear;
edtOutletNm.Clear;
curredtPrice.Clear;
curredtPrice.Value := 0;
curredtPriceScoreOut.Clear;
curredtPriceScoreOut.Value := 0;
BarcodeSize.ItemIndex:= 0;
end;
procedure TfrmMaintenanceBarcode.ClearAttribut;
begin
edtProductCode.Clear;
edtProductName.Clear;
end;
procedure TfrmMaintenanceBarcode.FormCreate(Sender: TObject);
begin
inherited;
chkUpdateClick(self);
actEditExecute(self);
edtProductCode.MaxLength := igProd_Code_Length;
edtProductCode.CharCase := ecUpperCase;
end;
procedure TfrmMaintenanceBarcode.FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
// inherited;
if (Key = Ord( 'P')) and (ssctrl in Shift) then
actPrintExecute(Self)
else if (Key = Ord('R')) and (ssctrl in Shift) then
actEditExecute(Self)
else if (Key = Ord('D')) and (ssctrl in Shift) then
actAddExecute(Self);
end;
procedure TfrmMaintenanceBarcode.udsBarcodeFirst(Sender: TObject);
begin
inherited;
FRecNo := 0;
end;
procedure TfrmMaintenanceBarcode.udsBarcodeNext(Sender: TObject);
begin
inherited;
Inc(FRecNo);
end;
procedure TfrmMaintenanceBarcode.udsBarcodePrior(Sender: TObject);
begin
inherited;
Dec(FRecNo);
end;
procedure TfrmMaintenanceBarcode.udsBarcodeCheckEOF(Sender: TObject;
var Eof: Boolean);
begin
inherited;
Eof := FRecNo > FRecMax - 1;
end;
procedure TfrmMaintenanceBarcode.edtProductCodeKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if (Key = vk_F5) or (key = vk_return) then
begin
ClearAtributData;
if Key = VK_F5 then
begin
GetBrgCode(True);
end
else if Key = VK_RETURN then
begin
GetBrgCode(False);
end;
end;
end;
procedure TfrmMaintenanceBarcode.edtUomIDKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if Key = VK_F5 then
begin
GetBrgUom(True);
end
else if Key = VK_RETURN then
begin
GetBrgUom(False);
end;
if (Trim(edtUomID.Text) <> '') then
edtBarcodeOldKeyUp(Self, Key, Shift);
end;
procedure TfrmMaintenanceBarcode.edtBarcodeOldKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if (Key = VK_RETURN) or (Key = VK_F5) then
begin
SetData;
end;
end;
procedure TfrmMaintenanceBarcode.FormKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if(Key = Ord('P')) and (ssctrl in Shift) then //Print
actPrintExecute(Self)
else if (Key = Ord('D')) and (ssctrl in Shift) then //Clear
actAddExecute(sender)
else if (Key = Ord('R')) and (ssctrl in Shift) then //Remove
actEditExecute(sender)
else if (Key = VK_Escape) and (ssctrl in Shift) then //Remove
Close;
end;
procedure TfrmMaintenanceBarcode.LoadDataFromPO(aPONo : string; aUnitID :
Integer);
var
iBaris: Integer;
// FDO: TDelivery;
// FPO: TPO;
i: Integer;
begin
{FPO := TPO.Create(Self);
FDO := TDelivery.Create(Self);
FPO.LoadByNoBukti(aPONo, aUnitID);
if FPO.StatusPO.ID = 5 then
begin
//ini jika sudah ada GR
// Untuk item regular PO
iBaris := 0;
FDO.LoadByNoPO(aPONo,aUnitID);
if FDO.DeliveryItems.Count > 0 then
begin
strgGrid.RowCount := FDO.DeliveryItems.Count + 1;
for i := 0 to FDO.DeliveryItems.Count - 1 do
begin
iBaris := i + 1;
edtProductCode.Text := FDO.DeliveryItems[i].Barang.Kode;
edtProductName.Text := FDO.DeliveryItems[i].Barang.Alias;
edtUomID.Text := FDO.DeliveryItems[i].SatKodeOrder.UOM;
edtUomNm.Text := FDO.DeliveryItems[i].SatKodeOrder.Nama;
strgGrid.Ints[_kolQty, iBaris] := Ceil(FDO.DeliveryItems[i].QtyOrderRecv);
strgGrid.Cells[_kolDesc, iBaris] := aPONo;
if (Trim(edtUomID.Text) <> '') then
begin
SetData;
actUpdateBarcodeExecute(btnSearch);
end;
end;
end;
// Untuk item PO bonus
if FDO.GRBonusItems.Count > 0 then
begin
strgGrid.RowCount := FDO.DeliveryItems.Count + FDO.GRBonusItems.Count + 1;
for i := (iBaris) to (FDO.GRBonusItems.Count - 1 + iBaris) do
begin
iBaris := i + 1;
edtProductCode.Text := FDO.GRBonusItems[i].NewBarang.Kode;
edtProductName.Text := FDO.GRBonusItems[i].NewBarang.Alias;
edtUomID.Text := FDO.GRBonusItems[i].NewUOM.UOM;
edtUomNm.Text := FDO.GRBonusItems[i].NewUOM.Nama;
strgGrid.Ints[_kolQty, iBaris] := Ceil(FDO.GRBonusItems[i].Qty);
strgGrid.Cells[_kolDesc, iBaris] := aPONo;
if (Trim(edtUomID.Text) <> '') then
begin
SetData;
actUpdateBarcodeExecute(btnSearch);
end;
end;
end;
end
else
begin
// ini yg PO Biasa
//tidak bisa langsung disebab perubahan format po
FPO.POItems.LoadByNoBukti(FPO.NoBukti, MasterNewUnit.ID);
if FPO.POItems.Count > 0 then
begin
strgGrid.RowCount := FPO.POItems.Count + 1;
for i := 0 to FPO.POItems.Count - 1 do
begin
iBaris := i + 1;
edtProductCode.Text := FPO.POItems[i].Barang.Kode;
edtProductName.Text := FPO.POItems[i].Barang.Alias;
edtUomID.Text := FPO.POItems[i].SatCodeOrder.UOM;
edtUomID.Text := FPO.POItems[i].SatCodeOrder.Nama;
strgGrid.Ints[_kolQty, iBaris] := Ceil(FPO.POItems[i].QtyOrder);
strgGrid.Cells[_kolDesc, iBaris] := aPONo;
if (Trim(edtUomID.Text) <> '') then
begin
SetData;
actUpdateBarcodeExecute(btnSearch);
end;
end;
end;
end;
FDO.Free;
FPO.Free;
}
end;
end.
|
{
Clever Internet Suite Version 6.2
Copyright (C) 1999 - 2006 Clever Components
www.CleverComponents.com
}
unit clTcpClient;
interface
{$I clVer.inc}
uses
Classes, clTlsSocket, clSocket, clCert, clSspi;
type
TclTcpTextEvent = procedure(Sender: TObject; const AText: string) of object;
TclTcpListEvent = procedure(Sender: TObject; AList: TStrings) of object;
TclClientTlsMode = (ctNone, ctAutomatic, ctImplicit, ctExplicit);
TclTcpClient = class(TComponent)
private
FConnection: TclTcpClientConnection;
FServer: string;
FPort: Integer;
FUseTLS: TclClientTlsMode;
FInProgress: Boolean;
FOnChanged: TNotifyEvent;
FOnClose: TNotifyEvent;
FOnOpen: TNotifyEvent;
FOnGetCertificate: TclOnGetCertificateEvent;
FOnVerifyServer: TclOnVerifyPeerEvent;
FCertificateFlags: TclCertificateFlags;
FTLSFlags: TclTlsFlags;
FIPResolver: TclHostIPResolver;
procedure SetServer(const Value: string);
procedure SetPort_(const Value: Integer);
procedure SetBatchSize(const Value: Integer);
procedure SetTimeOut(const Value: Integer);
procedure SetBitsPerSec(const Value: Integer);
procedure SetCertificateFlags(const Value: TclCertificateFlags);
procedure SetTLSFlags(const Value: TclTlsFlags);
function GetBatchSize: Integer;
function GetBitsPerSec: Integer;
function GetTimeOut: Integer;
function GetActive: Boolean;
function GetIsTls: Boolean;
protected
procedure GetCertificate(Sender: TObject; var ACertificate: TclCertificate; var Handled: Boolean);
procedure VerifyServer(Sender: TObject; ACertificate: TclCertificate;
const AStatusText: string; AStatusCode: Integer; var AVerified: Boolean);
procedure CheckConnected;
procedure ExplicitStartTls;
procedure AssignTlsStream(AConnection: TclSyncConnection);
function GetDefaultPort: Integer; virtual;
procedure OpenConnection(const AServer: string; APort: Integer); virtual;
procedure InternalOpen; virtual;
procedure InternalClose; virtual;
procedure SetUseTLS(const Value: TclClientTlsMode); virtual;
procedure DoDestroy; virtual;
procedure Changed; dynamic;
procedure DoOpen; dynamic;
procedure DoClose; dynamic;
procedure DoGetCertificate(var ACertificate: TclCertificate; var Handled: Boolean); dynamic;
procedure DoVerifyServer(ACertificate: TclCertificate;
const AStatusText: string; AStatusCode: Integer; var AVerified: Boolean); dynamic;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Open;
procedure Close;
procedure StartTls; virtual;
property IsTls: Boolean read GetIsTls;
property Connection: TclTcpClientConnection read FConnection;
property Active: Boolean read GetActive;
property Server: string read FServer write SetServer;
property Port: Integer read FPort write SetPort_;
property BatchSize: Integer read GetBatchSize write SetBatchSize default 8192;
property TimeOut: Integer read GetTimeOut write SetTimeOut default 60000;
property UseTLS: TclClientTlsMode read FUseTLS write SetUseTLS default ctNone;
property CertificateFlags: TclCertificateFlags read FCertificateFlags write SetCertificateFlags default [];
property TLSFlags: TclTlsFlags read FTLSFlags write SetTLSFlags default [tfUseTLS];
property BitsPerSec: Integer read GetBitsPerSec write SetBitsPerSec default 0;
property OnChanged: TNotifyEvent read FOnChanged write FOnChanged;
property OnOpen: TNotifyEvent read FOnOpen write FOnOpen;
property OnClose: TNotifyEvent read FOnClose write FOnClose;
property OnGetCertificate: TclOnGetCertificateEvent read FOnGetCertificate write FOnGetCertificate;
property OnVerifyServer: TclOnVerifyPeerEvent read FOnVerifyServer write FOnVerifyServer;
end;
TclTcpCommandClient = class(TclTcpClient)
private
FUserName: string;
FPassword: string;
FResponse: TStrings;
FLastResponseCode: Integer;
FOnReceiveResponse: TclTcpListEvent;
FOnSendCommand: TclTcpTextEvent;
FOnProgress: TclSocketProgressEvent;
FOnProgress64: TclSocketProgress64Event;
procedure SetPassword(const Value: string);
procedure SetUserName(const Value: string);
function ReceiveResponse(AddToLastString: Boolean): Boolean;
function IsOkResponse(AResponseCode: Integer; const AOkResponses: array of Integer): Boolean;
procedure DoDataProgress(Sender: TObject; ABytesProceed, ATotalBytes: Int64);
protected
procedure InternalOpen; override;
procedure InternalClose; override;
procedure DoDestroy; override;
procedure OpenSession; virtual; abstract;
procedure CloseSession; virtual; abstract;
function GetResponseCode(const AResponse: string): Integer; virtual;
function ParseResponse(AStartFrom: Integer; const AOkResponses: array of Integer): Integer;
function InternalWaitingResponse(AStartFrom: Integer;
const AOkResponses: array of Integer): Integer;
procedure WaitingResponse(const AOkResponses: array of Integer); virtual;
procedure InternalSendCommandSync(const ACommand: string;
const AOkResponses: array of Integer); virtual;
procedure DoSendCommand(const AText: string); dynamic;
procedure DoReceiveResponse(AList: TStrings); dynamic;
procedure DoProgress(ABytesProceed, ATotalBytes: Int64); dynamic;
public
constructor Create(AOwner: TComponent); override;
procedure SendCommand(const ACommand: string);
procedure SendCommandSync(const ACommand: string;
const AOkResponses: array of Integer); overload;
procedure SendCommandSync(const ACommand: string;
const AOkResponses: array of Integer; const Args: array of const); overload;
procedure SendSilentCommand(const ACommand: string;
const AOkResponses: array of Integer); overload;
procedure SendSilentCommand(const ACommand: string;
const AOkResponses: array of Integer; const Args: array of const); overload;
procedure SendMultipleLines(ALines: TStrings);
procedure WaitMultipleLines(ATotalBytes: Int64); virtual;
property Response: TStrings read FResponse;
property LastResponseCode: Integer read FLastResponseCode;
property UserName: string read FUserName write SetUserName;
property Password: string read FPassword write SetPassword;
property OnSendCommand: TclTcpTextEvent read FOnSendCommand write FOnSendCommand;
property OnReceiveResponse: TclTcpListEvent read FOnReceiveResponse write FOnReceiveResponse;
property OnProgress: TclSocketProgressEvent read FOnProgress write FOnProgress;
property OnProgress64: TclSocketProgress64Event read FOnProgress64 write FOnProgress64;
end;
resourcestring
cNotConnectedError = 'The connection is not active';
cLineSizeInvalid = 'The data line length must be lower or equal to BatchSize';
const
SOCKET_WAIT_RESPONSE = 0;
SOCKET_DOT_RESPONSE = 1;
implementation
uses
SysUtils, WinSock, clUtils{$IFDEF DEMO}, Forms, Windows{$ENDIF}{$IFDEF LOGGER}, clLogger{$ENDIF};
{ TclTcpClient }
procedure TclTcpClient.Changed;
begin
if Assigned(FOnChanged) then
begin
FOnChanged(Self);
end;
end;
procedure TclTcpClient.CheckConnected;
begin
if not Active then
begin
RaiseSocketError(cNotConnectedError, -1);
end;
Assert(FConnection <> nil);
end;
procedure TclTcpClient.Close;
var
b: Boolean;
begin
FIPResolver.Abort();
b := Active;
InternalClose();
if b then
begin
DoClose();
end;
end;
constructor TclTcpClient.Create(AOwner: TComponent);
var
wsaData: TWSAData;
res: Integer;
begin
inherited Create(AOwner);
res := WSAStartup($202, wsaData);
if (res <> 0) then
begin
RaiseSocketError(WSAGetLastError());
end;
FIPResolver := TclHostIPResolver.Create();
FConnection := TclTcpClientConnection.Create();
BatchSize := 8192;
TimeOut := 60000;
BitsPerSec := 0;
FUseTLS := ctNone;
FTLSFlags := [tfUseTLS];
end;
destructor TclTcpClient.Destroy;
begin
Close();
DoDestroy();
FConnection.Free();
FIPResolver.Free();
WSACleanup();
inherited Destroy();
end;
procedure TclTcpClient.DoClose;
begin
if Assigned(OnClose) then
begin
OnClose(Self);
end;
end;
procedure TclTcpClient.DoDestroy;
begin
end;
procedure TclTcpClient.DoOpen;
begin
if Assigned(OnOpen) then
begin
OnOpen(Self);
end;
end;
procedure TclTcpClient.InternalClose;
begin
FConnection.Close(True);
end;
procedure TclTcpClient.InternalOpen;
begin
{$IFDEF DEMO}
{$IFNDEF STANDALONEDEMO}
if FindWindow('TAppBuilder', nil) = 0 then
begin
MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' +
'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
ExitProcess(1);
end;
{$ENDIF}
{$ENDIF}
if (BatchSize < 1) then
begin
RaiseSocketError(cBatchSizeInvalid, -1);
end;
OpenConnection(Server, Port);
end;
procedure TclTcpClient.Open;
begin
if Active then Exit;
try
InternalOpen();
DoOpen();
except
FInProgress := True;
try
Close();
except
on EclSocketError do ;
end;
FInProgress := False;
raise;
end;
end;
procedure TclTcpClient.SetBatchSize(const Value: Integer);
begin
if (BatchSize <> Value) then
begin
Connection.BatchSize := Value;
Changed();
end;
end;
procedure TclTcpClient.SetPort_(const Value: Integer);
begin
if (FPort <> Value) then
begin
FPort := Value;
Changed();
end;
end;
procedure TclTcpClient.SetServer(const Value: string);
begin
if (FServer <> Value) then
begin
FServer := Value;
Changed();
end;
end;
procedure TclTcpClient.SetTimeOut(const Value: Integer);
begin
if (TimeOut <> Value) then
begin
Connection.TimeOut := Value;
Changed();
end;
end;
procedure TclTcpClient.SetUseTLS(const Value: TclClientTlsMode);
begin
if (FUseTLS <> Value) then
begin
FUseTLS := Value;
Changed();
end;
end;
procedure TclTcpClient.SetBitsPerSec(const Value: Integer);
begin
if (BitsPerSec <> Value) then
begin
Connection.BitsPerSec := Value;
Changed();
end;
end;
function TclTcpClient.GetBatchSize: Integer;
begin
Result := Connection.BatchSize;
end;
function TclTcpClient.GetBitsPerSec: Integer;
begin
Result := Connection.BitsPerSec;
end;
function TclTcpClient.GetTimeOut: Integer;
begin
Result := Connection.TimeOut;
end;
function TclTcpClient.GetActive: Boolean;
begin
Result := Connection.Active;
end;
procedure TclTcpClient.DoGetCertificate(var ACertificate: TclCertificate; var Handled: Boolean);
begin
if Assigned(OnGetCertificate) then
begin
OnGetCertificate(Self, ACertificate, Handled);
end;
end;
procedure TclTcpClient.GetCertificate(Sender: TObject;
var ACertificate: TclCertificate; var Handled: Boolean);
begin
DoGetCertificate(ACertificate, Handled);
end;
function TclTcpClient.GetDefaultPort: Integer;
begin
Result := 0;
end;
procedure TclTcpClient.AssignTlsStream(AConnection: TclSyncConnection);
var
tlsStream: TclTlsNetworkStream;
begin
tlsStream := TclTlsNetworkStream.Create();
AConnection.NetworkStream := tlsStream;
tlsStream.CertificateFlags := CertificateFlags;
tlsStream.TLSFlags := TLSFlags;
tlsStream.TargetName := Server;
tlsStream.OnGetCertificate := GetCertificate;
tlsStream.OnVerifyPeer := VerifyServer;
end;
procedure TclTcpClient.OpenConnection(const AServer: string; APort: Integer);
var
ip: string;
addr: Integer;
begin
ip := AServer;
addr := inet_addr(PChar(ip));
if (addr = Integer(INADDR_NONE)) then
begin
ip := FIPResolver.GetHostIP(ip, TimeOut);
end;
if ((UseTLS = ctAutomatic) and (Port <> GetDefaultPort()))
or (UseTLS = ctImplicit) then
begin
AssignTlsStream(Connection);
end else
begin
Connection.NetworkStream := TclNetworkStream.Create();
end;
Connection.Open(ip, APort);
end;
procedure TclTcpClient.ExplicitStartTls;
begin
if ((UseTLS = ctAutomatic) and (Port = GetDefaultPort()))
or (UseTLS = ctExplicit) then
begin
StartTls();
end;
end;
procedure TclTcpClient.StartTls;
begin
if (UseTLS = ctNone) then
begin
UseTLS := ctExplicit;
end;
try
AssignTlsStream(Connection);
Connection.OpenSession();
except
FInProgress := True;
try
Close();
except
on EclSocketError do ;
end;
FInProgress := False;
raise;
end;
end;
procedure TclTcpClient.DoVerifyServer(ACertificate: TclCertificate;
const AStatusText: string; AStatusCode: Integer; var AVerified: Boolean);
begin
if Assigned(OnVerifyServer) then
begin
OnVerifyServer(Self, ACertificate, AStatusText, AStatusCode, AVerified);
end;
end;
procedure TclTcpClient.VerifyServer(Sender: TObject; ACertificate: TclCertificate;
const AStatusText: string; AStatusCode: Integer; var AVerified: Boolean);
begin
DoVerifyServer(ACertificate, AStatusText, AStatusCode, AVerified);
end;
procedure TclTcpClient.SetCertificateFlags(const Value: TclCertificateFlags);
begin
if (FCertificateFlags <> Value) then
begin
FCertificateFlags := Value;
Changed();
end;
end;
procedure TclTcpClient.SetTLSFlags(const Value: TclTlsFlags);
begin
if (FTLSFlags <> Value) then
begin
FTLSFlags := Value;
Changed();
end;
end;
function TclTcpClient.GetIsTls: Boolean;
begin
Result := (Connection.NetworkStream is TclTlsNetworkStream);
end;
{ TclTcpCommandClient }
procedure TclTcpCommandClient.SendCommand(const ACommand: string);
var
cmd: string;
begin
CheckConnected();
cmd := ACommand + #13#10;
Connection.InitProgress(0, 0);
Connection.WriteString(cmd);
DoSendCommand(cmd);
end;
function TclTcpCommandClient.ReceiveResponse(AddToLastString: Boolean): Boolean;
var
stream: TStream;
begin
stream := TMemoryStream.Create();
try
Connection.ReadData(stream);
stream.Position := 0;
Result := AddTextStream(Response, stream, AddToLastString);
finally
stream.Free();
end;
end;
function TclTcpCommandClient.IsOkResponse(AResponseCode: Integer; const AOkResponses: array of Integer): Boolean;
var
i: Integer;
begin
Result := False;
i := Low(AOkResponses);
while (i <= High(AOkResponses)) and (AOkResponses[i] <> 0) do
begin
if (AOkResponses[i] = AResponseCode) then
begin
Result := True;
Break;
end;
Inc(i);
end;
end;
procedure TclTcpCommandClient.WaitingResponse(const AOkResponses: array of Integer);
begin
Response.Clear();
InternalWaitingResponse(0, AOkResponses);
DoReceiveResponse(Response);
end;
procedure TclTcpCommandClient.InternalSendCommandSync(const ACommand: string;
const AOkResponses: array of Integer);
begin
SendCommand(ACommand);
WaitingResponse(AOkResponses);
end;
procedure TclTcpCommandClient.SendCommandSync(const ACommand: string;
const AOkResponses: array of Integer);
begin
FInProgress := True;
try
InternalSendCommandSync(ACommand, AOkResponses);
finally
FInProgress := False;
end;
end;
procedure TclTcpCommandClient.SendCommandSync(const ACommand: string;
const AOkResponses: array of Integer; const Args: array of const);
begin
SendCommandSync(Format(ACommand, Args), AOkResponses);
end;
procedure TclTcpCommandClient.SetPassword(const Value: string);
begin
if (FPassword <> Value) then
begin
FPassword := Value;
Changed();
end;
end;
procedure TclTcpCommandClient.SetUserName(const Value: string);
begin
if (FUserName <> Value) then
begin
FUserName := Value;
Changed();
end;
end;
constructor TclTcpCommandClient.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FResponse := TStringList.Create();
end;
function TclTcpCommandClient.GetResponseCode(const AResponse: string): Integer;
begin
Result := SOCKET_WAIT_RESPONSE;
end;
procedure TclTcpCommandClient.InternalClose;
begin
try
if Active and not FInProgress then
begin
CloseSession();
end;
finally
inherited InternalClose();
end;
end;
procedure TclTcpCommandClient.InternalOpen;
begin
inherited InternalOpen();
OpenSession();
end;
procedure TclTcpCommandClient.SendMultipleLines(ALines: TStrings);
const
cDot = '.';
cCRLF = #13#10;
procedure WriteLine(AStream: TStream; const ALine: string);
begin
AStream.Write(PChar(ALine)^, Length(ALine));
end;
function GetTotalBytes(ALines: TStrings): Int64;
var
i: Integer;
begin
Result := 0;
for i := 0 to ALines.Count - 1 do
begin
if (Length(ALines[i]) + Length(cCRLF) + 1 > BatchSize) then
begin
RaiseSocketError(cLineSizeInvalid, -1);
end;
Result := Result + Length(ALines[i]) + Length(cCRLF);
end;
end;
var
i: Integer;
stream: TStream;
line: string;
begin
if (BatchSize < 1) then
begin
RaiseSocketError(cBatchSizeInvalid, -1);
end;
stream := TMemoryStream.Create();
Connection.OnProgress := DoDataProgress;
FInProgress := True;
try
i := 0;
line := '';
Connection.InitProgress(0, GetTotalBytes(ALines));
while (i < ALines.Count) do
begin
line := ALines[i];
if ((stream.Size + 3 + Length(line)) <= BatchSize) then
begin
if (Length(line) > 0) then
begin
if (line[1] = '.') then
begin
WriteLine(stream, cDot);
end;
WriteLine(stream, line);
end;
WriteLine(stream, cCRLF);
end else
begin
stream.Position := 0;
Connection.WriteData(stream);
stream.Position := 0;
stream.Size := 0;
Continue;
end;
Inc(i);
end;
if (stream.Size > 0) then
begin
stream.Position := 0;
Connection.WriteData(stream);
end;
finally
FInProgress := False;
Connection.OnProgress := nil;
stream.Free();
end;
end;
procedure TclTcpCommandClient.DoReceiveResponse(AList: TStrings);
begin
if Assigned(OnReceiveResponse) then
begin
OnReceiveResponse(Self, AList);
end;
end;
procedure TclTcpCommandClient.DoSendCommand(const AText: string);
begin
if Assigned(OnSendCommand) then
begin
OnSendCommand(Self, AText);
end;
end;
procedure TclTcpCommandClient.DoProgress(ABytesProceed, ATotalBytes: Int64);
begin
if Assigned(OnProgress) then
begin
OnProgress(Self, ABytesProceed, ATotalBytes);
end;
if Assigned(OnProgress64) then
begin
OnProgress64(Self, ABytesProceed, ATotalBytes);
end;
end;
procedure TclTcpCommandClient.DoDestroy;
begin
FResponse.Free();
inherited DoDestroy();
end;
procedure TclTcpCommandClient.WaitMultipleLines(ATotalBytes: Int64);
function CheckForDotTerminator: Boolean;
begin
Result := (Response.Count > 0) and (Response[Response.Count - 1] = '.');
end;
procedure RemoveResponseLine;
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'WaitMultipleLines, RemoveResponseLine');{$ENDIF}
if (Response.Count > 0) then
begin
Response.Delete(0);
end;
end;
procedure RemoveDotTerminatorLine;
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'WaitMultipleLines, RemoveDotTerminatorLine');{$ENDIF}
Assert(Response.Count > 0);
Response.Delete(Response.Count - 1);
end;
procedure ReplaceLeadingDotTerminator;
var
i: Integer;
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'WaitMultipleLines, ReplaceLeadingDotTerminator');{$ENDIF}
for i := 0 to Response.Count - 1 do
begin
if (system.Pos('..', Response[i]) = 1) then
begin
Response[i] := system.Copy(Response[i], 2, Length(Response[i]));
end;
end;
end;
begin
Connection.OnProgress := DoDataProgress;
FInProgress := True;
try
if (ATotalBytes > 0) then
begin
Connection.InitProgress(GetStringsSize(Response), ATotalBytes);
end else
begin
Connection.InitProgress(0, 0);
end;
RemoveResponseLine();
if not CheckForDotTerminator then
begin
InternalWaitingResponse(0, [SOCKET_DOT_RESPONSE]);
end;
ReplaceLeadingDotTerminator();
RemoveDotTerminatorLine();
finally
FInProgress := False;
Connection.OnProgress := nil;
end;
if (ATotalBytes > 0) then
begin
DoProgress(ATotalBytes, ATotalBytes);
end;
end;
procedure TclTcpCommandClient.DoDataProgress(Sender: TObject; ABytesProceed, ATotalBytes: Int64);
begin
if (ABytesProceed <= ATotalBytes) then
begin
DoProgress(ABytesProceed, ATotalBytes);
end;
end;
function TclTcpCommandClient.ParseResponse(AStartFrom: Integer; const AOkResponses: array of Integer): Integer;
var
i, tempCode: Integer;
begin
Result := -1;
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'ParseResponse');{$ENDIF}
for i := AStartFrom to Response.Count - 1 do
begin
tempCode := GetResponseCode(Response[i]);
if (tempCode <> SOCKET_WAIT_RESPONSE) then
begin
FLastResponseCode := tempCode;
if IsOkResponse(LastResponseCode, AOkResponses) then
begin
Result := i;
Exit;
end;
end;
end;
{$IFDEF LOGGER}
finally
if(Result > -1) then
begin
clPutLogMessage(Self, edLeave, 'ParseResponse %d, %s', nil, [Result, Response[Result]]);
end else
begin
clPutLogMessage(Self, edLeave, 'ParseResponse %d', nil, [Result]);
end;
end;
{$ENDIF}
end;
function TclTcpCommandClient.InternalWaitingResponse(AStartFrom: Integer;
const AOkResponses: array of Integer): Integer;
var
keepLastString: Boolean;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'InternalWaitingResponse');{$ENDIF}
Result := -1;
keepLastString := False;
repeat
keepLastString := ReceiveResponse(keepLastString);
if keepLastString then
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'InternalWaitingResponse inside if(keepLastString)then');{$ENDIF}
Continue;
end;
FLastResponseCode := SOCKET_WAIT_RESPONSE;
if (Response.Count = AStartFrom) and (Length(AOkResponses) = 0) then
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'InternalWaitingResponse inside if(Response.Count = AStartFrom)');{$ENDIF}
Break;
end;
Result := ParseResponse(AStartFrom, AOkResponses);
if Result > -1 then
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'InternalWaitingResponse inside if(Result > -1)');{$ENDIF}
Break;
end;
if not ((Length(AOkResponses) = 1) and (AOkResponses[Low(AOkResponses)] = SOCKET_DOT_RESPONSE))
and (LastResponseCode <> SOCKET_WAIT_RESPONSE) then
begin
RaiseSocketError(Trim(Response.Text), LastResponseCode);
end;
until False;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'InternalWaitingResponse'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'InternalWaitingResponse', E); raise; end; end;{$ENDIF}
end;
procedure TclTcpCommandClient.SendSilentCommand(const ACommand: string;
const AOkResponses: array of Integer; const Args: array of const);
begin
try
SendCommandSync(ACommand, AOkResponses, Args);
except
on EclSocketError do ;
end;
end;
procedure TclTcpCommandClient.SendSilentCommand(const ACommand: string;
const AOkResponses: array of Integer);
begin
try
SendCommandSync(ACommand, AOkResponses);
except
on EclSocketError do ;
end;
end;
end.
|
unit Objekt.DHLValidateShipmentorder;
interface
uses
SysUtils, Classes, geschaeftskundenversand_api_2,
Objekt.DHLServiceconfiguration, Objekt.DHLShipment;
type
TDHLValidateShipmentorder = class
private
fValidateShipmentOrderTypeAPI: ValidateShipmentOrderType;
fsequenceNumber: string;
fPrintOnlyIfCodeable: TDHLServiceconfiguration;
fShipment: TDHLShipment;
procedure setsequenceNumber(const Value: string);
public
constructor Create;
destructor Destroy; override;
function ValidateShipmentorderAPI: ValidateShipmentOrderType;
property sequenceNumber: string read fsequenceNumber write setsequenceNumber;
property PrintOnlyIfCodeable: TDHLServiceconfiguration read fPrintOnlyIfCodeable write fPrintOnlyIfCodeable;
property Shipment: TDHLShipment read fShipment write fShipment;
end;
implementation
{ TDHLValidateShipmentorder }
constructor TDHLValidateShipmentorder.Create;
begin
fValidateShipmentOrderTypeAPI := ValidateShipmentOrderType.Create;
fPrintOnlyIfCodeable := TDHLServiceconfiguration.Create;
fValidateShipmentOrderTypeAPI.PrintOnlyIfCodeable := fPrintOnlyIfCodeable.ServiceconfigurationAPI;
fShipment := TDHLShipment.Create;
ValidateShipmentorderAPI.Shipment := fShipment.ShipmentAPI;
end;
destructor TDHLValidateShipmentorder.Destroy;
begin
FreeAndNil(fPrintOnlyIfCodeable);
FreeAndNil(fShipment);
inherited;
end;
procedure TDHLValidateShipmentorder.setsequenceNumber(const Value: string);
begin
fsequenceNumber := Value;
fValidateShipmentOrderTypeAPI.sequenceNumber := Value;
end;
function TDHLValidateShipmentorder.ValidateShipmentorderAPI: ValidateShipmentOrderType;
begin
Result := fValidateShipmentOrderTypeAPI;
end;
end.
|
unit BTMemoryModule;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Memory DLL loading code *
* ------------------------ *
* *
* MemoryModule "Conversion to Delphi" *
* Copyright (c) 2005 - 2006 by Martin Offenwanger / coder@dsplayer.de *
* http://www.dsplayer.de *
* *
* Original C++ Code "MemoryModule Version 0.0.1" *
* Copyright (c) 2004- 2006 by Joachim Bauch / mail@joachim-bauch.de *
* http://www.joachim-bauch.de *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{
@author(Martin Offenwanger: coder@dsplayer.de)
@created(Mar 20, 2005)
@lastmod(Sep 27, 2005)
}
interface
uses
// Borland Run-time Library
Windows;
{++++++++++++++++++++++++++++++++++++++
*** MemoryModule Type Definition ***
--------------------------------------}
type
PBTMemoryModule = ^TBTMemoryModule;
_BT_MEMORY_MODULE = packed record
headers: PImageNtHeaders;
codeBase: Pointer;
modules: Pointer;
numModules: integer;
initialized: boolean;
end;
{$EXTERNALSYM _BT_MEMORY_MODULE}
TBTMemoryModule = _BT_MEMORY_MODULE;
BT_MEMORY_MODULE = _BT_MEMORY_MODULE;
{$EXTERNALSYM BT_MEMORY_MODULE}
{++++++++++++++++++++++++++++++++++++++++++++++++++
*** Memory DLL loading functions Declaration ***
--------------------------------------------------}
// return value is nil if function fails
function BTMemoryLoadLibary(var f_data: Pointer; const f_size: int64): PBTMemoryModule; stdcall;
// return value is nil if function fails
function BTMemoryGetProcAddress(var f_module: PBTMemoryModule; const f_name: PChar): Pointer; stdcall;
// free module
procedure BTMemoryFreeLibrary(var f_module: PBTMemoryModule); stdcall;
// returns last error
function BTMemoryGetLastError: string; stdcall;
implementation
//uses
// Borland Run-time Library
// SysUtils;
{+++++++++++++++++++++++++++++++++++
*** Dll EntryPoint Definition ***
-----------------------------------}
type
TDllEntryProc = function(hinstdll: THandle; fdwReason: DWORD; lpReserved: Pointer): BOOL; stdcall;
{++++++++++++++++++++++++++++++++++++++++
*** Missing Windows API Definitions ***
----------------------------------------}
PImageBaseRelocation = ^TImageBaseRelocation;
_IMAGE_BASE_RELOCATION = packed record
VirtualAddress: DWORD;
SizeOfBlock: DWORD;
end;
{$EXTERNALSYM _IMAGE_BASE_RELOCATION}
TImageBaseRelocation = _IMAGE_BASE_RELOCATION;
IMAGE_BASE_RELOCATION = _IMAGE_BASE_RELOCATION;
{$EXTERNALSYM IMAGE_BASE_RELOCATION}
PImageImportDescriptor = ^TImageImportDescriptor;
_IMAGE_IMPORT_DESCRIPTOR = packed record
OriginalFirstThunk: DWORD;
TimeDateStamp: DWORD;
ForwarderChain: DWORD;
Name: DWORD;
FirstThunk: DWORD;
end;
{$EXTERNALSYM _IMAGE_IMPORT_DESCRIPTOR}
TImageImportDescriptor = _IMAGE_IMPORT_DESCRIPTOR;
IMAGE_IMPORT_DESCRIPTOR = _IMAGE_IMPORT_DESCRIPTOR;
{$EXTERNALSYM IMAGE_IMPORT_DESCRIPTOR}
PImageImportByName = ^TImageImportByName;
_IMAGE_IMPORT_BY_NAME = packed record
Hint: Word;
Name: array[0..255] of Byte; // original: "Name: array [0..0] of Byte;"
end;
{$EXTERNALSYM _IMAGE_IMPORT_BY_NAME}
TImageImportByName = _IMAGE_IMPORT_BY_NAME;
IMAGE_IMPORT_BY_NAME = _IMAGE_IMPORT_BY_NAME;
{$EXTERNALSYM IMAGE_IMPORT_BY_NAME}
const
IMAGE_SIZEOF_BASE_RELOCATION = 8;
{$EXTERNALSYM IMAGE_SIZEOF_BASE_RELOCATION}
IMAGE_REL_BASED_HIGHLOW = 3;
{$EXTERNALSYM IMAGE_REL_BASED_HIGHLOW}
IMAGE_ORDINAL_FLAG32 = DWORD($80000000);
{$EXTERNALSYM IMAGE_ORDINAL_FLAG32}
var
lastErrStr: string;
{+++++++++++++++++++++++++++++++++++++++++++++++++++++
*** Memory DLL loading functions Implementation ***
-----------------------------------------------------}
function BTMemoryGetLastError: string; stdcall;
begin
Result := lastErrStr;
end;
function GetFieldOffset(const Struc; const Field): Cardinal; stdcall;
begin
Result := Cardinal(@Field) - Cardinal(@Struc);
end;
function GetImageFirstSection(NtHeader: PImageNtHeaders): PImageSectionHeader; stdcall;
begin
Result := PImageSectionHeader(Cardinal(NtHeader) +
GetFieldOffset(NtHeader^, NtHeader^.OptionalHeader) +
NtHeader^.FileHeader.SizeOfOptionalHeader);
end;
function GetHeaderDictionary(f_module: PBTMemoryModule; f_idx: integer): PImageDataDirectory; stdcall;
begin
Result := PImageDataDirectory(@(f_module.headers.OptionalHeader.DataDirectory[f_idx]));
end;
function GetImageOrdinal(Ordinal: DWORD): Word; stdcall;
begin
Result := Ordinal and $FFFF;
end;
function GetImageSnapByOrdinal(Ordinal: DWORD): Boolean; stdcall;
begin
Result := ((Ordinal and IMAGE_ORDINAL_FLAG32) <> 0);
end;
procedure CopySections(const f_data: Pointer; const f_old_headers: TImageNtHeaders; f_module: PBTMemoryModule); stdcall;
var
l_size, i: integer;
l_codebase: Pointer;
l_dest: Pointer;
l_section: PImageSectionHeader;
begin
l_codebase := f_module.codeBase;
l_section := GetImageFirstSection(f_module.headers);
for i := 0 to f_module.headers.FileHeader.NumberOfSections - 1 do begin
// section doesn't contain data in the dll itself, but may define
// uninitialized data
if (l_section.SizeOfRawData = 0) then begin
l_size := f_old_headers.OptionalHeader.SectionAlignment;
if l_size > 0 then begin
l_dest := VirtualAlloc(Pointer(Cardinal(l_codebase) + l_section.VirtualAddress), l_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
l_section.Misc.PhysicalAddress := cardinal(l_dest);
ZeroMemory(l_dest, l_size);
end;
inc(longword(l_section), sizeof(TImageSectionHeader));
// Continue with the nex loop
Continue;
end;
// commit memory block and copy data from dll
l_dest := VirtualAlloc(Pointer(Cardinal(l_codebase) + l_section.VirtualAddress), l_section.SizeOfRawData, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
CopyMemory(l_dest, Pointer(longword(f_data) + l_section.PointerToRawData), l_section.SizeOfRawData);
l_section.Misc.PhysicalAddress := cardinal(l_dest);
// IMAGE_SIZEOF_SECTION_HEADER
inc(longword(l_section), sizeof(TImageSectionHeader));
end;
end;
procedure PerformBaseRelocation(f_module: PBTMemoryModule; f_delta: Cardinal); stdcall;
var
l_i: Cardinal;
l_codebase: Pointer;
l_directory: PImageDataDirectory;
l_relocation: PImageBaseRelocation;
l_dest: Pointer;
l_relInfo: ^Word;
l_patchAddrHL: ^DWord;
l_type, l_offset: integer;
begin
l_codebase := f_module.codeBase;
l_directory := GetHeaderDictionary(f_module, IMAGE_DIRECTORY_ENTRY_BASERELOC);
if l_directory.Size > 0 then begin
l_relocation := PImageBaseRelocation(Cardinal(l_codebase) + l_directory.VirtualAddress);
while l_relocation.VirtualAddress > 0 do begin
l_dest := Pointer((Cardinal(l_codebase) + l_relocation.VirtualAddress));
l_relInfo := Pointer(Cardinal(l_relocation) + IMAGE_SIZEOF_BASE_RELOCATION);
for l_i := 0 to (trunc(((l_relocation.SizeOfBlock - IMAGE_SIZEOF_BASE_RELOCATION) / 2)) - 1) do begin
// the upper 4 bits define the type of relocation
l_type := (l_relInfo^ shr 12);
// the lower 12 bits define the offset
l_offset := l_relInfo^ and $FFF;
//showmessage(inttostr(l_relInfo^));
if l_type = IMAGE_REL_BASED_HIGHLOW then begin
// change complete 32 bit address
l_patchAddrHL := Pointer(Cardinal(l_dest) + Cardinal(l_offset));
l_patchAddrHL^ := l_patchAddrHL^ + f_delta;
end;
inc(l_relInfo);
end;
l_relocation := Pointer(cardinal(l_relocation) + l_relocation.SizeOfBlock);
end;
end;
end;
function AllocMem(Size: Cardinal): Pointer;
begin
GetMem(Result, Size);
FillChar(Result^, Size, 0);
end;
function StrComp(const Str1, Str2: PChar): Integer; assembler;
asm
PUSH EDI
PUSH ESI
MOV EDI,EDX
MOV ESI,EAX
MOV ECX,0FFFFFFFFH
XOR EAX,EAX
REPNE SCASB
NOT ECX
MOV EDI,EDX
XOR EDX,EDX
REPE CMPSB
MOV AL,[ESI-1]
MOV DL,[EDI-1]
SUB EAX,EDX
POP ESI
POP EDI
end;
function BuildImportTable(f_module: PBTMemoryModule): boolean; stdcall;
var
l_codeBase: Pointer;
l_directory: PImageDataDirectory;
l_importDesc: PImageImportDescriptor;
l_thunkRef, l_funcRef: ^DWORD;
l_handle: HMODULE;
l_temp: integer;
l_thunkData: TImageImportByName;
begin
Result := true;
l_codeBase := f_module.codeBase;
l_directory := GetHeaderDictionary(f_module, IMAGE_DIRECTORY_ENTRY_IMPORT);
if (l_directory.Size > 0) then begin
l_importDesc := PImageImportDescriptor(Cardinal(l_codeBase) + l_directory.VirtualAddress);
while (not IsBadReadPtr(l_importDesc, sizeof(TImageImportDescriptor))) and (l_importDesc.Name <> 0) do begin
l_handle := LoadLibrary(PChar(Cardinal(l_codeBase) + l_importDesc.Name));
if (l_handle = INVALID_HANDLE_VALUE) then begin
lastErrStr := 'BuildImportTable: can''t load library: ' + PChar(Cardinal(l_codeBase) + l_importDesc.Name);
Result := false;
exit;
end;
// ReallocMemory crashes if "f_module.modules = nil"
if f_module.modules = nil then
f_module.modules := AllocMem(1);
f_module.modules := ReallocMemory(f_module.modules, ((f_module.numModules + 1) * (sizeof(HMODULE))));
if f_module.modules = nil then begin
lastErrStr := 'BuildImportTable: ReallocMemory failed';
result := false;
exit;
end;
// module->modules[module->numModules++] = handle;
l_temp := (sizeof(cardinal) * (f_module.numModules));
inc(Cardinal(f_module.modules), l_temp);
cardinal(f_module.modules^) := l_handle;
dec(Cardinal(f_module.modules), l_temp);
f_module.numModules := f_module.numModules + 1;
if l_importDesc.OriginalFirstThunk <> 0 then begin
l_thunkRef := Pointer(Cardinal(l_codeBase) + l_importDesc.OriginalFirstThunk);
l_funcRef := Pointer(Cardinal(l_codeBase) + l_importDesc.FirstThunk);
end else begin
// no hint table
l_thunkRef := Pointer(Cardinal(l_codeBase) + l_importDesc.FirstThunk);
l_funcRef := Pointer(Cardinal(l_codeBase) + l_importDesc.FirstThunk);
end;
while l_thunkRef^ <> 0 do begin
if GetImageSnapByOrdinal(l_thunkRef^) then
l_funcRef^ := Cardinal(GetProcAddress(l_handle, PChar(GetImageOrdinal(l_thunkRef^))))
else begin
CopyMemory(@l_thunkData, Pointer(Cardinal(l_codeBase) + l_thunkRef^), sizeof(TImageImportByName));
l_funcRef^ := Cardinal(GetProcAddress(l_handle, PChar(@(l_thunkData.Name))));
end;
if l_funcRef^ = 0 then begin
lastErrStr := 'BuildImportTable: GetProcAddress failed';
result := false;
break;
end;
inc(l_funcRef);
inc(l_thunkRef);
end;
inc(longword(l_importDesc), sizeof(TImageImportDescriptor));
end;
end;
end;
function GetSectionProtection(SC: cardinal): cardinal; stdcall;
//SC – ImageSectionHeader.Characteristics
begin
result := 0;
if (SC and IMAGE_SCN_MEM_NOT_CACHED) <> 0 then
result := result or PAGE_NOCACHE;
// E - Execute, R – Read , W – Write
if (SC and IMAGE_SCN_MEM_EXECUTE) <> 0 //E ?
then if (SC and IMAGE_SCN_MEM_READ) <> 0 //ER ?
then if (SC and IMAGE_SCN_MEM_WRITE) <> 0 //ERW ?
then result := result or PAGE_EXECUTE_READWRITE
else result := result or PAGE_EXECUTE_READ
else if (SC and IMAGE_SCN_MEM_WRITE) <> 0 //EW?
then result := result or PAGE_EXECUTE_WRITECOPY
else result := result or PAGE_EXECUTE
else if (SC and IMAGE_SCN_MEM_READ) <> 0 // R?
then if (SC and IMAGE_SCN_MEM_WRITE) <> 0 //RW?
then result := result or PAGE_READWRITE
else result := result or PAGE_READONLY
else if (SC and IMAGE_SCN_MEM_WRITE) <> 0 //W?
then result := result or PAGE_WRITECOPY
else result := result or PAGE_NOACCESS;
end;
procedure FinalizeSections(f_module: PBTMemoryModule); stdcall;
var
l_i: integer;
l_section: PImageSectionHeader;
l_protect, l_oldProtect, l_size: Cardinal;
begin
l_section := GetImageFirstSection(f_module.headers);
for l_i := 0 to f_module.headers.FileHeader.NumberOfSections - 1 do begin
if (l_section.Characteristics and IMAGE_SCN_MEM_DISCARDABLE) <> 0 then begin
// section is not needed any more and can safely be freed
VirtualFree(Pointer(l_section.Misc.PhysicalAddress), l_section.SizeOfRawData, MEM_DECOMMIT);
inc(longword(l_section), sizeof(TImageSectionHeader));
continue;
end;
l_protect := GetSectionProtection(l_section.Characteristics);
if (l_section.Characteristics and IMAGE_SCN_MEM_NOT_CACHED) <> 0 then
l_protect := (l_protect or PAGE_NOCACHE);
// determine size of region
l_size := l_section.SizeOfRawData;
if l_size = 0 then begin
if (l_section.Characteristics and IMAGE_SCN_CNT_INITIALIZED_DATA) <> 0 then begin
l_size := f_module.headers.OptionalHeader.SizeOfInitializedData;
end else begin
if (l_section.Characteristics and IMAGE_SCN_CNT_UNINITIALIZED_DATA) <> 0 then
l_size := f_module.headers.OptionalHeader.SizeOfUninitializedData;
end;
if l_size > 0 then begin
if not VirtualProtect(Pointer(l_section.Misc.PhysicalAddress), l_section.SizeOfRawData, l_protect, @l_oldProtect) then begin
lastErrStr := 'FinalizeSections: VirtualProtect failed';
exit;
end;
end;
end;
inc(longword(l_section), sizeof(TImageSectionHeader));
end;
end;
function BTMemoryLoadLibary(var f_data: Pointer; const f_size: int64): PBTMemoryModule; stdcall;
var
l_result: PBTMemoryModule;
l_dos_header: TImageDosHeader;
l_old_header: TImageNtHeaders;
l_code, l_headers: Pointer;
l_locationdelta: Cardinal;
l_DllEntry: TDllEntryProc;
l_successfull: boolean;
begin
l_result := nil;
Result := nil;
try
CopyMemory(@l_dos_header, f_data, sizeof(_IMAGE_DOS_HEADER));
if (l_dos_header.e_magic <> IMAGE_DOS_SIGNATURE) then begin
lastErrStr := 'BTMemoryLoadLibary: dll dos header is not valid';
exit;
end;
CopyMemory(@l_old_header, pointer(longint(f_data) + l_dos_header._lfanew), sizeof(_IMAGE_NT_HEADERS));
if l_old_header.Signature <> IMAGE_NT_SIGNATURE then begin
lastErrStr := 'BTMemoryLoadLibary: IMAGE_NT_SIGNATURE is not valid';
exit;
end;
// reserve memory for image of library
l_code := VirtualAlloc(Pointer(l_old_header.OptionalHeader.ImageBase), l_old_header.OptionalHeader.SizeOfImage, MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if l_code = nil then
// try to allocate memory at arbitrary position
l_code := VirtualAlloc(nil, l_old_header.OptionalHeader.SizeOfImage, MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if l_code = nil then begin
lastErrStr := 'BTMemoryLoadLibary: VirtualAlloc failed';
exit;
end;
// alloc space for the result record
l_result := PBTMemoryModule(HeapAlloc(GetProcessHeap(), 0, sizeof(TBTMemoryModule)));
l_result.codeBase := l_code;
l_result.numModules := 0;
l_result.modules := nil;
l_result.initialized := false;
// xy: is it correct to commit the complete memory region at once?
// calling DllEntry raises an exception if we don't...
VirtualAlloc(l_code, l_old_header.OptionalHeader.SizeOfImage, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
// commit memory for headers
l_headers := VirtualAlloc(l_code, l_old_header.OptionalHeader.SizeOfHeaders, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
// copy PE header to code
CopyMemory(l_headers, f_data, (Cardinal(l_dos_header._lfanew) + l_old_header.OptionalHeader.SizeOfHeaders));
l_result.headers := PImageNtHeaders(longint(l_headers) + l_dos_header._lfanew);
// update position
l_result.headers.OptionalHeader.ImageBase := cardinal(l_code);
// copy sections from DLL file block to new memory location
CopySections(f_data, l_old_header, l_result);
// adjust base address of imported data
l_locationdelta := Cardinal(Cardinal(l_code) - l_old_header.OptionalHeader.ImageBase);
if l_locationdelta <> 0 then
PerformBaseRelocation(l_result, l_locationdelta);
// load required dlls and adjust function table of imports
if not BuildImportTable(l_result) then begin
lastErrStr := lastErrStr + ' BTMemoryLoadLibary: BuildImportTable failed';
//Abort;
end;
// mark memory pages depending on section headers and release
// sections that are marked as "discardable"
FinalizeSections(l_result);
// get entry point of loaded library
if (l_result.headers.OptionalHeader.AddressOfEntryPoint) <> 0 then begin
@l_DllEntry := Pointer(Cardinal(l_code) + l_result.headers.OptionalHeader.AddressOfEntryPoint);
if @l_DllEntry = nil then begin
lastErrStr := 'BTMemoryLoadLibary: Get DLLEntyPoint failed';
//Abort;
end;
l_successfull := l_DllEntry(Cardinal(l_code), DLL_PROCESS_ATTACH, nil);
if not l_successfull then begin
lastErrStr := 'BTMemoryLoadLibary: Can''t attach library';
//Abort;
end;
l_result.initialized := true;
end;
except
BTMemoryFreeLibrary(l_result);
exit;
end;
Result := l_result;
end;
function BTMemoryGetProcAddress(var f_module: PBTMemoryModule; const f_name: PChar): Pointer; stdcall;
var
l_codeBase: Pointer;
l_idx: integer;
l_i: DWORD;
l_nameRef: ^DWORD;
l_ordinal: ^WORD;
l_exports: PImageExportDirectory;
l_directory: PImageDataDirectory;
l_temp: ^DWORD;
begin
Result := nil;
l_codeBase := f_module.codeBase;
l_idx := -1;
l_directory := GetHeaderDictionary(f_module, IMAGE_DIRECTORY_ENTRY_EXPORT);
if l_directory.Size = 0 then begin
lastErrStr := 'BTMemoryGetProcAddress: no export table found';
exit;
end;
l_exports := PImageExportDirectory(Cardinal(l_codeBase) + l_directory.VirtualAddress);
if ((l_exports.NumberOfNames = 0) or (l_exports.NumberOfFunctions = 0)) then begin
lastErrStr := 'BTMemoryGetProcAddress: DLL doesn''t export anything';
exit;
end;
// search function name in list of exported names
l_nameRef := Pointer(Cardinal(l_codeBase) + Cardinal(l_exports.AddressOfNames));
l_ordinal := Pointer(Cardinal(l_codeBase) + Cardinal(l_exports.AddressOfNameOrdinals));
for l_i := 0 to l_exports.NumberOfNames - 1 do begin
if StrComp(f_name, PChar(Cardinal(l_codeBase) + l_nameRef^)) = 0 then begin
l_idx := l_ordinal^;
break;
end;
inc(l_nameRef);
inc(l_ordinal);
end;
if (l_idx = -1) then begin
lastErrStr := 'BTMemoryGetProcAddress: exported symbol not found';
exit;
end;
if (Cardinal(l_idx) > l_exports.NumberOfFunctions - 1) then begin
lastErrStr := 'BTMemoryGetProcAddress: name <-> ordinal number don''t match';
exit;
end;
// AddressOfFunctions contains the RVAs to the "real" functions
l_temp := Pointer(Cardinal(l_codeBase) + Cardinal(l_exports.AddressOfFunctions) + Cardinal((l_idx * 4)));
Result := Pointer(Cardinal(l_codeBase) + l_temp^);
end;
procedure BTMemoryFreeLibrary(var f_module: PBTMemoryModule); stdcall;
var
l_module: PBTMemoryModule;
l_i: integer;
l_temp: integer;
l_DllEntry: TDllEntryProc;
begin
l_module := f_module;
if l_module <> nil then begin
if l_module.initialized then begin
@l_DllEntry := Pointer(Cardinal(l_module.codeBase) + l_module.headers.OptionalHeader.AddressOfEntryPoint);
l_DllEntry(Cardinal(l_module.codeBase), DLL_PROCESS_DETACH, nil);
l_module.initialized := false;
// free previously opened libraries
for l_i := 0 to l_module.numModules - 1 do begin
l_temp := (sizeof(cardinal) * (l_i));
inc(Cardinal(l_module.modules), l_temp);
if Cardinal(f_module.modules^) <> INVALID_HANDLE_VALUE then
FreeLibrary(Cardinal(f_module.modules^));
dec(Cardinal(l_module.modules), l_temp);
end;
FreeMemory(l_module.modules);
if l_module.codeBase <> nil then
// release memory of library
VirtualFree(l_module.codeBase, 0, MEM_RELEASE);
HeapFree(GetProcessHeap(), 0, f_module);
Pointer(f_module) := nil;
end;
end;
end;
end.
|
unit Win32.MFSharingEngine;
// Updated to SDK 10.0.17763.0
// (c) Translation to Pascal by Norbert Sonnleitner
{$IFDEF FPC}
{$mode delphi}
{$ENDIF}
interface
uses
Windows, Classes, SysUtils, ActiveX,
Win32.MFObjects,
Win32.MFMediaEngine, CMC.Inspectable;
const
IID_IMFSharingEngineClassFactory: TGUID = '{2BA61F92-8305-413B-9733-FAF15F259384}';
IID_IMFMediaSharingEngine: TGUID = '{8D3CE1BF-2367-40E0-9EEE-40D377CC1B46}';
IID_IMFMediaSharingEngineClassFactory: TGUID = '{524D2BC4-B2B1-4FE5-8FAC-FA4E4512B4E0}';
IID_IMFImageSharingEngine: TGUID = '{CFA0AE8E-7E1C-44D2-AE68-FC4C148A6354}';
IID_IMFImageSharingEngineClassFactory: TGUID = '{1FC55727-A7FB-4FC8-83AE-8AF024990AF1}';
IID_IPlayToControl: TGUID = '{607574EB-F4B6-45C1-B08C-CB715122901D}';
IID_IPlayToControlWithCapabilities: TGUID = '{AA9DD80F-C50A-4220-91C1-332287F82A34}';
IID_IPlayToSourceClassFactory: TGUID = '{842B32A3-9B9B-4D1C-B3F3-49193248A554}';
const
MF_MEDIA_SHARING_ENGINE_DEVICE_NAME: TGUID = '{771e05d1-862f-4299-95ac-ae81fd14f3e7}';
MF_MEDIA_SHARING_ENGINE_DEVICE: TGUID = '{b461c58a-7a08-4b98-99a8-70fd5f3badfd}';
MF_MEDIA_SHARING_ENGINE_INITIAL_SEEK_TIME: TGUID = '{6f3497f5-d528-4a4f-8dd7-db36657ec4c9}';
MF_SHUTDOWN_RENDERER_ON_ENGINE_SHUTDOWN: TGUID = '{c112d94d-6b9c-48f8-b6f9-7950ff9ab71e}';
MF_PREFERRED_SOURCE_URI: TGUID = '{5fc85488-436a-4db8-90af-4db402ae5c57}';
MF_SHARING_ENGINE_SHAREDRENDERER: TGUID = '{efa446a0-73e7-404e-8ae2-fef60af5a32b}';
MF_SHARING_ENGINE_CALLBACK: TGUID = '{57dc1e95-d252-43fa-9bbc-180070eefe6d}';
CLSID_MFMediaSharingEngineClassFactory: TGUID = '{f8e307fb-6d45-4ad3-9993-66cd5a529659}';
CLSID_MFImageSharingEngineClassFactory: TGUID = '{b22c3339-87f3-4059-a0c5-037aa9707eaf}';
CLSID_PlayToSourceClassFactory: TGUID = '{DA17539A-3DC3-42C1-A749-A183B51F085E}';
GUID_PlayToService: TGUID = '{f6a8ff9d-9e14-41c9-bf0f-120a2b3ce120}';
GUID_NativeDeviceService: TGUID = '{ef71e53c-52f4-43c5-b86a-ad6cb216a61e}';
type
TDEVICE_INFO = record
pFriendlyDeviceName: BSTR;
pUniqueDeviceName: BSTR;
pManufacturerName: BSTR;
pModelName: BSTR;
pIconURL: BSTR;
end;
PDEVICE_INFO = ^TDEVICE_INFO;
TMF_SHARING_ENGINE_EVENT = (
MF_SHARING_ENGINE_EVENT_DISCONNECT = 2000,
MF_SHARING_ENGINE_EVENT_LOCALRENDERINGSTARTED = 2001,
MF_SHARING_ENGINE_EVENT_LOCALRENDERINGENDED = 2002,
MF_SHARING_ENGINE_EVENT_STOPPED = 2003,
MF_SHARING_ENGINE_EVENT_ERROR = 2501
);
TMF_MEDIA_SHARING_ENGINE_EVENT = (
MF_MEDIA_SHARING_ENGINE_EVENT_DISCONNECT = 2000
);
IMFSharingEngineClassFactory = interface(IUnknown)
['{2BA61F92-8305-413B-9733-FAF15F259384}']
function CreateInstance(dwFlags: DWORD; pAttr: IMFAttributes; out ppEngine: IUnknown): HResult; stdcall;
end;
IMFMediaSharingEngine = interface(IMFMediaEngine)
['{8D3CE1BF-2367-40E0-9EEE-40D377CC1B46}']
function GetDevice(Out pDevice: TDEVICE_INFO): HResult; stdcall;
end;
IMFMediaSharingEngineClassFactory = interface(IUnknown)
['{524D2BC4-B2B1-4FE5-8FAC-FA4E4512B4E0}']
function CreateInstance(dwFlags: DWORD; pAttr: IMFAttributes; out ppEngine: IMFMediaSharingEngine): HResult; stdcall;
end;
IMFImageSharingEngine = interface(IUnknown)
['{CFA0AE8E-7E1C-44D2-AE68-FC4C148A6354}']
function SetSource(pStream: IUnknown): HResult; stdcall;
function GetDevice(Out pDevice: TDEVICE_INFO): HResult; stdcall;
function Shutdown(): HResult; stdcall;
end;
IMFImageSharingEngineClassFactory = interface(IUnknown)
['{1FC55727-A7FB-4FC8-83AE-8AF024990AF1}']
function CreateInstanceFromUDN(pUniqueDeviceName: BSTR; out ppEngine: IMFImageSharingEngine): HResult; stdcall;
end;
TPLAYTO_SOURCE_CREATEFLAGS = (
PLAYTO_SOURCE_NONE = 0,
PLAYTO_SOURCE_IMAGE = $1,
PLAYTO_SOURCE_AUDIO = $2,
PLAYTO_SOURCE_VIDEO = $4,
PLAYTO_SOURCE_PROTECTED = $8
);
IPlayToControl = interface(IUnknown)
['{607574EB-F4B6-45C1-B08C-CB715122901D}']
function Connect(pFactory: IMFSharingEngineClassFactory): HResult; stdcall;
function Disconnect(): HResult; stdcall;
end;
IPlayToControlWithCapabilities = interface(IPlayToControl)
['{AA9DD80F-C50A-4220-91C1-332287F82A34}']
function GetCapabilities(out pCapabilities: TPLAYTO_SOURCE_CREATEFLAGS): HResult; stdcall;
end;
IPlayToSourceClassFactory = interface(IUnknown)
['{842B32A3-9B9B-4D1C-B3F3-49193248A554}']
function CreateInstance(dwFlags: DWORD; pControl: IPlayToControl; out ppSource: IInspectable): HResult; stdcall;
end;
implementation
end.
|
unit Invoice.Model.OrderProduct;
interface
uses
DB,
Classes,
SysUtils,
Generics.Collections,
/// orm
Invoice.Model.Order,
Invoice.Model.Product,
ormbr.types.blob,
ormbr.types.lazy,
ormbr.types.mapping,
ormbr.types.nullable,
ormbr.mapping.classes,
ormbr.mapping.register,
ormbr.mapping.attributes;
type
[Entity]
[Table('OrderProduct', '')]
[PrimaryKey('idOrder', NotInc, NoSort, False, 'Chave primária')]
[PrimaryKey('idProduct', NotInc, NoSort, False, 'Chave primária')]
TOrderProduct = class
private
{ Private declarations }
FidOrder: Integer;
FidProduct: Integer;
FpriceProduct: Currency;
FquantityProduct: Double;
FOrder_0: TOrder;
FProduct_1: TProduct;
public
{ Public declarations }
constructor Create;
destructor Destroy; override;
[Restrictions([NotNull])]
[Column('idOrder', ftInteger)]
[ForeignKey('Order', 'idOrder', SetNull, SetNull)]
[Dictionary('idOrder', 'Mensagem de validação', '', '', '', taCenter)]
property idOrder: Integer Index 0 read FidOrder write FidOrder;
[Restrictions([NotNull])]
[Column('idProduct', ftInteger)]
[ForeignKey('Product', 'idProduct', SetNull, SetNull)]
[Dictionary('idProduct', 'Mensagem de validação', '', '', '', taCenter)]
property idProduct: Integer Index 1 read FidProduct write FidProduct;
[Restrictions([NotNull])]
[Column('priceProduct', ftCurrency)]
[Dictionary('priceProduct', 'Mensagem de validação', '0', '', '', taRightJustify)]
property priceProduct: Currency Index 2 read FpriceProduct write FpriceProduct;
[Restrictions([NotNull])]
[Column('quantityProduct', ftBCD, 5, 2)]
[Dictionary('quantityProduct', 'Mensagem de validação', '0', '', '', taRightJustify)]
property quantityProduct: Double Index 3 read FquantityProduct write FquantityProduct;
[Association(OneToOne,'idOrder','idOrder')]
property Order: TOrder read FOrder_0 write FOrder_0;
[Association(OneToOne,'idProduct','idProduct')]
property Product: TProduct read FProduct_1 write FProduct_1;
end;
implementation
constructor TOrderProduct.Create;
begin
FOrder_0 := TOrder.Create;
FProduct_1 := TProduct.Create;
end;
destructor TOrderProduct.Destroy;
begin
FOrder_0.Free;
FProduct_1.Free;
inherited;
end;
initialization
TRegisterClass.RegisterEntity(TOrderProduct)
end.
|
unit frmDriverControl;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls,
registry,
DriverControl,
OTFEFreeOTFEBase_U,
WinSVC, // Required for service related definitions and functions
OTFEFreeOTFE_U, SDUForms, lcDialogs, SDUDialogs;
type
TfrmDriverControl = class (TSDUForm)
pbClose: TButton;
gbInstallNew: TGroupBox;
pbInstall: TButton;
lblInstall: TLabel;
gbModifyExisting: TGroupBox;
lbDrivers: TListBox;
lblStart: TLabel;
pbStart: TButton;
pbStop: TButton;
pbUninstall: TButton;
Label1: TLabel;
Label3: TLabel;
Label4: TLabel;
Panel1: TPanel;
Panel2: TPanel;
pbUpdate: TButton;
cbStartup: TComboBox;
OpenDialog: TSDUOpenDialog;
procedure lbDriversClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure pbStartClick(Sender: TObject);
procedure pbStopClick(Sender: TObject);
procedure pbUninstallClick(Sender: TObject);
procedure pbInstallClick(Sender: TObject);
procedure pbCloseClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure cbStartupChange(Sender: TObject);
procedure pbUpdateClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure lbDriversDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
private
DriverControlObj: TDriverControl;
BMPModeNormal: TBitmap;
BMPModePortable: TBitmap;
BMPStatusStarted: TBitmap;
BMPStatusStopped: TBitmap;
BMPStartAuto: TBitmap;
BMPStartManual: TBitmap;
procedure EnableDisableControls();
procedure PopulateDriversList();
procedure LoadBitmapsFromResources();
procedure FreeBitmapsFromResources();
function GetItemWidth(Index: Integer): Integer;
public
constructor Create(AOwner: TComponent); override;
end;
implementation
{$R *.DFM}
{$R OTFEFreeOTFE_DriverImages.dcr}
uses
Math, SDUGeneral,
SDUi18n; // Required for max(...)
resourcestring
TEXT_MANUAL_START = 'Manual';
TEXT_AUTO_START = 'At system startup';
FILE_FILTER_FLT_DRIVERS = 'Driver files (*.sys)|*.sys|All files|*.*';
const
INTER_IMAGE_GAP = 2;
BMP_MODE_NORMAL = 'MODE_NORMAL';
BMP_MODE_PORTABLE = 'MODE_PORTABLE';
BMP_STATUS_STARTED = 'STATUS_STARTED';
BMP_STATUS_STOPPED = 'STATUS_STOPPED';
BMP_START_AUTO = 'START_AUTO';
BMP_START_MANUAL = 'START_MANUAL';
constructor TfrmDriverControl.Create(AOwner: TComponent);
begin
inherited;
// We create the driver control object *here*. We can't create it in
// OnFormCreate(...) as any exception raised by TDriverControl as
// a result of it's creation (e.g. user doesn't have admin privs) would just
// get "swallowed up" and ignored, instead of being propogated back to the
// caller.
DriverControlObj := TDriverControl.Create();
end;
procedure TfrmDriverControl.EnableDisableControls();
var
driverSelected: Boolean;
serviceRunning: Boolean;
serviceState: DWORD;
autoStart: Boolean;
begin
// Note: We *don't* repaint/refresh lbDrivers in this procedure as that
// would cause a flicking effect.
driverSelected := (lbDrivers.ItemIndex >= 0);
SDUEnableControl(lblStart, driverSelected);
SDUEnableControl(cbStartup, driverSelected);
SDUEnableControl(pbStart, False);
SDUEnableControl(pbStop, False);
cbStartup.ItemIndex := -1;
if driverSelected then begin
// If the service is still running, warn the user later...
if (DriverControlObj.GetServiceState(lbDrivers.Items[lbDrivers.ItemIndex], serviceState)) then
begin
serviceRunning := (serviceState = SERVICE_RUNNING);
SDUEnableControl(pbStop, serviceRunning);
SDUEnableControl(pbStart, not (serviceRunning));
end;
cbStartup.ItemIndex := cbStartup.Items.IndexOf(TEXT_MANUAL_START);
if DriverControlObj.GetServiceAutoStart(lbDrivers.Items[lbDrivers.ItemIndex], autoStart) then
begin
if autoStart then begin
cbStartup.ItemIndex := cbStartup.Items.IndexOf(TEXT_AUTO_START);
end;
end;
end;
SDUEnableControl(pbUninstall, driverSelected);
SDUEnableControl(pbInstall, True);
// pbUpdate is a special case; it should only be enabled if the user
// changes cbStartup
SDUEnableControl(pbUpdate, False);
end;
procedure TfrmDriverControl.PopulateDriversList();
var
driverList: TStringList;
maxWidth: Integer;
i: Integer;
begin
lbDrivers.Items.Clear();
driverList := TStringList.Create();
try
DriverControlObj.GetFreeOTFEDrivers(driverList);
// Bang the sorted flag up & down to ensure that the list is sorted
// before it is displayed to the user
driverList.Sorted := False;
driverList.Sorted := True;
lbDrivers.Items.AddStrings(driverList);
finally
driverList.Free();
end;
maxWidth := 0;
for i := 0 to (lbDrivers.Items.Count - 1) do begin
maxWidth := max(maxWidth, GetItemWidth(i));
end;
lbDrivers.ScrollWidth := maxWidth;
// Ensure no driver is selected
lbDrivers.ItemIndex := -1;
// Ensure that the fact none is selected takes effect...
lbDriversClick(nil);
end;
procedure TfrmDriverControl.lbDriversClick(Sender: TObject);
begin
EnableDisableControls();
end;
procedure TfrmDriverControl.FormShow(Sender: TObject);
begin
// Center label (done dynamically due to language translation size
// differences)
SDUCenterControl(lblInstall, ccHorizontal);
cbStartup.Items.Add(TEXT_MANUAL_START);
cbStartup.Items.Add(TEXT_AUTO_START);
PopulateDriversList();
EnableDisableControls();
end;
procedure TfrmDriverControl.pbStartClick(Sender: TObject);
var
service: String;
begin
service := lbDrivers.Items[lbDrivers.ItemIndex];
if not (DriverControlObj.StartStopService(service, True)) then begin
SDUMessageDlg(Format(_('Unable to start driver "%s"'), [service]) + SDUCRLF +
SDUCRLF + TEXT_NEED_ADMIN,
mtError
);
end;
EnableDisableControls();
// Ensure that the icons displayed are correct
lbDrivers.Refresh();
end;
procedure TfrmDriverControl.pbStopClick(Sender: TObject);
var
service: String;
begin
// Note that we *cannot* do this sensibly, and only warn the user if one or
// more drives are mounted; the user *could* have more than one copy of
// FreeOTFE (or different apps using the FreeOTFE driver; e.g. different apps
// using this component).
// In that scenario, things could get dodgy if the user did something stupid
// like uninstalling the main driver, while keeping the 2nd app connected to
// it.
if (SDUMessageDlg(_('WARNING!') + SDUCRLF + SDUCRLF +
_(
'Stopping a LibreCrypt driver which is currently in use (e.g. by one or more mounted container) can lead to SYSTEM INSTABILITY.') +
SDUCRLF + SDUCRLF +
_('This option is intended for experienced users who REALLY know what they''re doing.') + SDUCRLF + SDUCRLF + Format(
_('Are you sure you wish to stop the "%s" driver?'), [lbDrivers.Items[lbDrivers.ItemIndex]]),
mtWarning, [mbYes, mbNo], 0) =
mrYes) then begin
service := lbDrivers.Items[lbDrivers.ItemIndex];
if not (DriverControlObj.StartStopService(service, False)) then begin
SDUMessageDlg(Format(_('Unable to stop driver "%s"'), [service]) + SDUCRLF +
SDUCRLF + TEXT_NEED_ADMIN,
mtError
);
end;
EnableDisableControls();
end;
// Ensure that the icons displayed are correct
lbDrivers.Refresh();
end;
procedure TfrmDriverControl.pbUninstallClick(Sender: TObject);
var
msgReboot: String;
msgManualRemoveFile: String;
driverName: String;
status: DWORD;
begin
// Note that we *cannot* do this sensibly, and only warn the user if one or
// more drives are mounted; the user *could* have more than one copy of
// FreeOTFE (or different apps using the FreeOTFE driver; e.g. different apps
// using this component).
// In that scenario, things could get dodgy if the user did something stupid
// like uninstalling the main driver, while keeping the 2nd app connected to
// it.
if (SDUMessageDlg(_('WARNING!') + SDUCRLF + SDUCRLF +
_(
'Uninstalling a LibreCrypt driver which is currently in use (e.g. by one or more mounted volumes) can lead to SYSTEM INSTABILITY.') +
SDUCRLF + SDUCRLF + _(
'This option is intended for experienced users who REALLY know what they''re doing.') + SDUCRLF +
SDUCRLF + Format(
_('Are you sure you wish to uninstall the "%s" driver?'), [lbDrivers.Items[lbDrivers.ItemIndex]]),
mtWarning, [mbYes, mbNo], 0) = mrYes) then
begin
driverName := lbDrivers.Items[lbDrivers.ItemIndex];
status := DriverControlObj.UninstallDriver(driverName);
if ((status and DRIVER_BIT_SUCCESS) = DRIVER_BIT_SUCCESS) then begin
// Uninstallation SUCCESSFULL
msgReboot := '';
if ((status and DRIVER_BIT_REBOOT_REQ) = DRIVER_BIT_REBOOT_REQ) then begin
msgReboot :=
SDUCRLF + SDUCRLF +
// 2 x CRLF - one to end the last line, one for spacing
_('Please reboot your computer to allow changes to take effect.');
end;
msgManualRemoveFile := '';
if ((status and DRIVER_BIT_FILE_REMAINS) = DRIVER_BIT_FILE_REMAINS) then begin
msgManualRemoveFile :=
SDUCRLF + SDUCRLF +
// 2 x CRLF - one to end the last line, one for spacing
_(
'After rebooting, please remove the driver file from your <windows>\system32\drivers directory');
end;
SDUMessageDlg(
Format(_('The "%s" driver has now been uninstalled.'), [driverName]) +
msgReboot + msgManualRemoveFile,
mtInformation
);
end else begin
// Uninstallation FAILURE
SDUMessageDlg(
Format(_('Unable to delete driver service "%s".'), [driverName]) + SDUCRLF +
SDUCRLF + _(
'Please disable this driver from starting up automatically, reboot, and try again.'),
mtError
);
end;
end;
// Refresh the drivers list
PopulateDriversList();
end;
// Install a new FreeOTFE device driver
procedure TfrmDriverControl.pbInstallClick(Sender: TObject);
var
i: Integer;
begin
OpenDialog.Filter := FILE_FILTER_FLT_DRIVERS;
OpenDialog.Options := OpenDialog.Options + [ofAllowMultiSelect];
OpenDialog.Options := OpenDialog.Options + [ofDontAddToRecent];
if (OpenDialog.Execute()) then begin
for i := 0 to (OpenDialog.files.Count - 1) do begin
DriverControlObj.InstallSetAutoStartAndStartDriver(OpenDialog.files[i]);
end;
// Refresh the drivers list
PopulateDriversList();
end;
end;
procedure TfrmDriverControl.pbCloseClick(Sender: TObject);
begin
Close();
end;
procedure TfrmDriverControl.FormCreate(Sender: TObject);
begin
Panel1.Caption := '';
Panel2.Caption := '';
LoadBitmapsFromResources();
end;
procedure TfrmDriverControl.cbStartupChange(Sender: TObject);
begin
// pbUpdate is a special case; it should only be enabled if the user
// changes cbStartup
pbUpdate.Enabled := True;
end;
procedure TfrmDriverControl.pbUpdateClick(Sender: TObject);
var
autoStart: Boolean;
service: String;
begin
if (cbStartup.ItemIndex >= 0) then begin
autoStart := (cbStartup.ItemIndex = (cbStartup.Items.IndexOf(TEXT_AUTO_START)));
service := lbDrivers.Items[lbDrivers.ItemIndex];
if not (DriverControlObj.SetServiceAutoStart(service, autoStart)) then begin
SDUMessageDlg(
Format(_('Unable to set startup option for driver "%s".'), [service]) + SDUCRLF +
SDUCRLF + TEXT_NEED_ADMIN,
mtError
);
end;
end;
EnableDisableControls();
// Ensure that the icons displayed are correct
lbDrivers.Refresh();
end;
procedure TfrmDriverControl.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
FreeBitmapsFromResources();
DriverControlObj.Free();
end;
procedure TfrmDriverControl.LoadBitmapsFromResources();
var
thehBitmap: hBitmap;
begin
thehBitmap := LoadBitmap(hInstance, BMP_MODE_NORMAL);
BMPModeNormal := TBitmap.Create();
BMPModeNormal.ReleaseHandle();
BMPModeNormal.handle := thehBitmap;
thehBitmap := LoadBitmap(hInstance, BMP_MODE_PORTABLE);
BMPModePortable := TBitmap.Create();
BMPModePortable.ReleaseHandle();
BMPModePortable.handle := thehBitmap;
thehBitmap := LoadBitmap(hInstance, BMP_STATUS_STARTED);
BMPStatusStarted := TBitmap.Create();
BMPStatusStarted.ReleaseHandle();
BMPStatusStarted.handle := thehBitmap;
thehBitmap := LoadBitmap(hInstance, BMP_STATUS_STOPPED);
BMPStatusStopped := TBitmap.Create();
BMPStatusStopped.ReleaseHandle();
BMPStatusStopped.handle := thehBitmap;
thehBitmap := LoadBitmap(hInstance, BMP_START_AUTO);
BMPStartAuto := TBitmap.Create();
BMPStartAuto.ReleaseHandle();
BMPStartAuto.handle := thehBitmap;
thehBitmap := LoadBitmap(hInstance, BMP_START_MANUAL);
BMPStartManual := TBitmap.Create();
BMPStartManual.ReleaseHandle();
BMPStartManual.handle := thehBitmap;
end;
procedure TfrmDriverControl.FreeBitmapsFromResources();
var
thehBitmap: hBitmap;
begin
thehBitmap := BMPModeNormal.Handle;
BMPModeNormal.ReleaseHandle();
BMPModeNormal.Free();
DeleteObject(thehBitmap);
thehBitmap := BMPModePortable.Handle;
BMPModePortable.ReleaseHandle();
BMPModePortable.Free();
DeleteObject(thehBitmap);
thehBitmap := BMPStatusStarted.Handle;
BMPStatusStarted.ReleaseHandle();
BMPStatusStarted.Free();
DeleteObject(thehBitmap);
thehBitmap := BMPStatusStopped.Handle;
BMPStatusStopped.ReleaseHandle();
BMPStatusStopped.Free();
DeleteObject(thehBitmap);
thehBitmap := BMPStartAuto.Handle;
BMPStartAuto.ReleaseHandle();
BMPStartAuto.Free();
DeleteObject(thehBitmap);
thehBitmap := BMPStartManual.Handle;
BMPStartManual.ReleaseHandle();
BMPStartManual.Free();
DeleteObject(thehBitmap);
end;
// Note: The "Style" property of the TListBox must be set to lbOwnerDrawFixed
// !! IMPORTANT !!
// !! IMPORTANT !!
// lbDriversDrawItem and GetItemWidth *MUST* be kept in sync!
// !! IMPORTANT !!
// !! IMPORTANT !!
procedure TfrmDriverControl.lbDriversDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
lbObj: TListBox;
canvas: TCanvas;
offset: Integer;
portableMode: Boolean;
serviceState: DWORD;
autoStart: Boolean;
drawStatusBmp: TBitmap;
drawModeBmp: TBitmap;
drawStartBmp: TBitmap;
begin
lbObj := TListBox(Control);
canvas := lbObj.Canvas;
offset := INTER_IMAGE_GAP; // Default offset
canvas.FillRect(Rect); { clear the rectangle }
{
// Portable Drivers in italics
canvas.Font.Style := [];
if DriverControlObj.IsDriverInstalledPortable(lbObj.Items[Index], portableMode) then
begin
if portableMode then
begin
canvas.Font.Style := [fsItalic];
end;
end;
}
// Determine which icons are to be displayed...
// Auto or manual start...
drawStartBmp := BMPStartManual;
if (DriverControlObj.GetServiceAutoStart(lbObj.Items[Index], autoStart)) then begin
if (autoStart) then begin
drawStartBmp := BMPStartAuto;
end;
end;
// Started or stopped...
drawStatusBmp := BMPStatusStopped;
if (DriverControlObj.GetServiceState(lbObj.Items[Index], serviceState)) then begin
if (serviceState = SERVICE_RUNNING) then begin
drawStatusBmp := BMPStatusStarted;
end;
end;
// Normal or portable...
// If running normally, don't display an icon
// drawModeBmp := BMPModeNormal;
drawModeBmp := nil;
if DriverControlObj.IsDriverInstalledPortable(lbObj.Items[Index], portableMode) then begin
if (portableMode) then begin
drawModeBmp := BMPModePortable;
end;
end;
// Draw the icons...
// Auto or manual start...
lbObj.Canvas.Draw(
(Rect.Left + offset),
(Rect.Top + (((Rect.Bottom - Rect.Top) - drawStartBmp.Height) div 2)),
drawStartBmp
);
offset := offset + INTER_IMAGE_GAP + max(BMPStartAuto.Width, BMPStartManual.Width);
// Started or stopped...
if (drawModeBmp <> nil) then begin
lbObj.Canvas.Draw(
(Rect.Left + offset),
(Rect.Top + (((Rect.Bottom - Rect.Top) - drawModeBmp.Height) div 2)),
drawModeBmp
);
end;
offset := offset + INTER_IMAGE_GAP + max(BMPModePortable.Width, BMPModeNormal.Width);
// Normal or portable...
lbObj.Canvas.Draw(
(Rect.Left + offset),
(Rect.Top + (((Rect.Bottom - Rect.Top) - drawStatusBmp.Height) div 2)),
drawStatusBmp
);
offset := offset + INTER_IMAGE_GAP + max(BMPStatusStarted.Width, BMPStatusStopped.Width);
// The name...
canvas.TextOut((Rect.Left + offset), Rect.Top, lbObj.Items[Index]);
end;
function TfrmDriverControl.GetItemWidth(Index: Integer): Integer;
var
lbObj: TListBox;
canvas: TCanvas;
offset: Integer;
begin
lbObj := lbDrivers;
canvas := lbObj.Canvas;
offset := INTER_IMAGE_GAP; // Default offset
offset := offset + INTER_IMAGE_GAP + max(BMPStartAuto.Width, BMPStartManual.Width);
offset := offset + INTER_IMAGE_GAP + max(BMPModePortable.Width, BMPModeNormal.Width);
offset := offset + INTER_IMAGE_GAP + max(BMPStatusStarted.Width, BMPStatusStopped.Width);
// The name...
offset := offset + canvas.TextWidth(lbObj.Items[Index]);
// Tack on a bit so it doesn't look like the text goes right up against the
// end...
offset := offset + (2 * INTER_IMAGE_GAP);
Result := offset;
end;
end.
|
{Fractions v.1.0, aka Zlomky v.1.0
Charles University in Prague, Faculty of Mathematics and Physics, Obecna matematika, the first semester
Winter semester, school year 2016/2017
NMIN101 Programming I
Matvei Slavenko}
{*Abstract*}
{This programme renders mathematical formulae using pseudo graphics. The input for the programme is a mathematical formula, and the output is the same formula presented in pseudo graphics.
The programme has a simple command-line user interface. The user can set the input and output streams at his/her convenience: the programme could both use files and standard input-output system. The list of commands and their detailed descriptions are available in the internal help module of the programme.}
program fractions;
{*Block of code describing the data structures used in the programme*}
{Data structure used for representation of the processed expression as a tree. Type 'tree' represents the single node of a tree. Fields that are used in the structure:
1. 'val' - actual value of the node, that would be printed out
2. 'typ' - type of the node.
'num' for numbers
'/', '*', '+', '-' for operations
3. 'height', 'width' - the height and the width of the expression, which is represented by this node (including the child nodes) measured in number of characters, that is needed to print the expression.
4. 'x0', 'y0' - the initial positions, from which the expression represented by this node should be printed.
Note: it is assumed, that the x-axis goes from the left to the right side of the screen; y-axis goes from the bottom of the screen to the top.
5. 'left', 'right' - child nodes of the node. For leafs it is assumed that these values are equal to 'nil'.
Note: considering the fact that in this particular programme unary operators are prohibited, each node either is a leaf, or have both left and right child nodes.
6. 'parent' - the parent node of the node. For the root it is assumed that this value is equal to 'nil'.}
type pTree = ^tree;
tree = record
val, typ: String;
height, width, x0, y0: Integer;
left, right, parent: pTree;
end;
{Data structure used for building a printing buffer. The procedures of adding the items to the data structure imply, that it is a priority queue, the priority is defined by the function 'compare()'. Fields that are used in the structure:
1. 'data' - the pointer to the node, which is an actual item in the queue.
2. 'prev', 'next' - pointers to the previous and to the next items in the queue.
Note: it is assumed, that for the head of the queue the 'prev' value is 'nil'. For the tail of the queue the 'next' value is 'nil'.}
type pQueue = ^queue;
queue = record
data: pTree;
prev, next: pQueue;
end;
{*Block of code, describing the global variables used in the programme*}
{Variables related to the representation of the expression in the programme and parsing process.
1. 'expression' - the root of the tree, which represents the actual expression being processed.
2. 'curNode' - this variable is used during the parsing of the expression only. It points to the so-called 'current' position of the parser in the tree.
3. 'pushBack' - a so-called pushback character, allowing to address to the next character in the input stream.
Note: if there is no characters ahead (the end of the file has been reached), then pushBack = #0.}
var expression, curNode: pTree;
var pushBack: char;
{Variables related to the printing of the expression.
1. 'printQ' - the pointer to the head of the printing buffer.
2. 'printerX', 'printerY' - the current positions of the 'printing head', i.e. coordinates of the character box, where the next character would be printed in.
Note: it is assumed, that the 'printing head' goes from the left to the right side of the screen, from the top to the bottom.
3. 'inFolder', 'outFolder' - the paths to the input and output folders, written with double back-slashes ('\\') as separators, ending with two backslashes.
Example: 'D:\\Ring\\Experiments\\University\\Zlomky\\Input\\'
Note: for the standard input a shortcut 'stdin' is used. Symmetrically, the shortcut 'stdout' is used for the standard output.
4. 'inF', 'outF' - the names of the input and the output files.
Example: 'input.txt'}
var printQ: pQueue;
var printerX, printerY: Integer;
var inFolder, outFolder: String;
var inF, outF: Text;
{Variables related to the communication with user.
1. 'mute' - if mute=True, then messages describing the stages of the programme's work will not be printed out. Default value is 'False'.
2. 'inCommand' - the variable used for reading the commands entered by user.}
var mute: Boolean;
var inCommand: String;
{*Block of code with useful and helpful procedures and functions*}
function max(a,b: Integer): Integer;
begin
if(a >= b) then max := a
else max := b;
end;
function isNum(ch: char): Boolean;
begin
if ((ch <= ('9')) and (ch >= ('0'))) then isNum := true
else isNum := false;
end;
function isOp(ch: char): Boolean;
begin
if ((ch = ('+')) or (ch = ('-')) or (ch = ('*')) or (ch = ('/'))) then isOp := true
else isOp := false;
end;
function isBrac(ch: char): Boolean;
begin
if ((ch = '(') or (ch = ')')) then isBrac := true
else isBrac := false;
end;
{Function that is used for multiplying Strings.
1. 'str' - the string, that needs to be multiplied.
2. 'n' - the number of times, by which it is needed to multiply the string.
Example: multrStr('MFF', 3) = 'MFFMFFMFF'.}
function multStr(str: String; n: Integer): String;
var i: Integer;
begin
multStr := '';
for i := 1 to n do begin
multStr := multStr + str;
end;
end;
{*Block of code responsible for parsing of strings*}
{Initialisation of the 'parser'. Fills in the pushback character, creates the root node of the expression, ensures that the root node's parent and children are 'nil'. Sets the current node of the parser 'curNode' to the root node.
This procedure is to be called before performing any actions that use the pushback character. The procedure is called in the beginning of the 'parseFile()' procedure.}
procedure initParser();
begin
if eof(inF) then pushBack := #0 {init PushBack}
else read(inF, pushBack);
new(expression); {init tree, set root node as the current node}
expression^.parent := nil;
expression^.left := nil;
expression^.right := nil;
curNode := expression;
end;
{The function returns the value that is stored in the variable 'pushBack'. Reads the next character from the input stream and stores it in the 'pushBack' variable. If the end of the file is reached, stores #0 to the 'pushBack' variable.}
function nextChar(): char;
begin
nextChar := pushBack;
if eof(inF) then pushBack := #0
else read(inF, pushBack);
end;
{The function reads the next number. Note: number is understood as a sequence of digits written consecutively. The function is applicable if and only if the value stored in 'pushBack' is a digit. Otherwise the behaviour is undefined.}
function parseNum(): String;
begin
parseNum := '';
while(isNum(pushBack)) do begin
parseNum := parseNum + nextChar();
end;
end;
{The procedure puts the token to the tree representation of the expression being parsed. For the precise definition of the word token see the description of the 'nextToken()' function.
'token' - the token to be put to the tree.}
procedure putToken(token: String);
var node: pTree;
begin
if token = '(' then begin
new(node);
curNode^.left := node;
node^.parent := curNode;
curNode := node;
end
else if token = ')' then begin
curNode := curNode^.parent;
end
else if (token = '+') or (token = '-') or (token = '*') or (token = '/') then begin
curNode := curNode^.parent;
curNode^.typ := token;
curNode^.val := token;
new(node);
curNode^.right := node;
node^.parent := curNode;
curNode := curNode^.right;
end
else begin
curNode^.typ := 'num';
curNode^.val := token;
end;
end;
{The function reads and returns the next token from the input stream. Token could be:
1. A string consisting of either a left or right bracket only, e.g. '(', ')'.
2. A string consisting of one of the operator characters only, e.g. '/', '*', '+', '-'.
3. A string consisting of digits only, e.g. '33', '35486'.
Note: since the number token could contain only digits, the digital fractions are not allowed by the programme.}
function nextToken(): String;
begin
if (isBrac(pushBack) or isOp(pushBack)) then begin
nextToken := nextChar();
end
else nextToken := parseNum();
end;
{This procedure parses the input stream and builds the abstract syntax tree of an expression presented in the input. The input stream should be opened prior to calling of the procedure.}
procedure parseFile();
var token: String;
begin
initParser();
while pushBack <> #0 do begin
token := nextToken();
putToken(token);
end;
end;
{*Block of code responsible for calculating positions*}
{The function allows to define, whether the node is a left child or not. Returns 'True' if the parameter 'node' is a left child of its parent node. 'False' otherwise.
Note: the root node is not a child node for any other node. Thus, the function being called for the root node returns 'False'.
'node' - the node to be tested.}
function isLeft(node: pTree): Boolean;
begin
if node^.parent = nil then isLeft := False
else if node^.parent^.left = node then isLeft := True
else isLeft := False;
end;
{The function allows to define, whether the node is a right child or not. Returns 'True' if the parameter 'node' is a right child of its parent node. 'False' otherwise.
Note: the root node is not a child node for any other node. Thus, the function being called for the root node returns 'False'.
'node' - the node to be tested.}
function isRight(node: pTree): Boolean;
begin
if node^.parent = nil then isRight := False
else if node^.parent^.right = node then isRight := True
else isRight := False;
end;
{The function allows to define, whether the node is a root node or not. Returns 'True' if the parameter 'node' is a root node. 'False' otherwise.
'node' - the node to be tested.}
function isRoot(node: pTree): Boolean;
begin
isRoot := False;
if node^.parent = nil then isRoot := True;
end;
{The procedure puts the brackets to the nodes of the tree using recursion. The brackets are put in 'semi-full' way. It means that each separate subexpression is closed into brackets, except for numbers and fractions. So, for example an expression '1+2' after processing will look like '(1+2)'. Whether an expression '1/2' would look like '1/2'. The brackets are added to the 'val' field of the nodes of the processed tree.
'node' - the of the tree, which is to be processed.
'valL', 'valR' - the number of left and right brackets that are to surround the expression. For the regular user's purposes default values 0,0 should be satisfying.}
procedure insertBrackets(node: pTree; valL, valR: Integer);
var str: String;
begin
str := '';
{Brackets are appended either to the numbers, or to the quotient.}
if (node^.typ = '/') or (node^.typ = 'num') then begin
if (node^.typ = 'num') then begin
if (isLeft(node)) then begin
str := multStr('(', valL);
node^.val := str + node^.val;
end
else if (isRight(node)) then begin
str := multStr(')', valR);
node^.val := node^.val + str;
end;
end
else begin
{In case of a quotient we can't append the brackets directly to the 'val' field, because it would warp the width of the expression. Apart from this, the 'val' of the quotient is changed by the compulsory procedure 'fillVals()'. Instead of this we would store the number of brackets that are to be appended to the quotient in it's x0 field. That is safe, because the x0 is never used until printing of the expression. Besides, the field is changed only by 'prepareX()' procedure, which always should be invoked after the 'fillVals()' procedure.
This trick allows us to avoid adding an extra field to the nodes of the tree.}
if (isLeft(node)) then begin
node^.x0 := valL;
end
else if (isRight(node)) then begin
node^.x0 := valR;
end
else begin
node^.x0 := 0;
end;
{The quotient should have absorbed all parentheses. So all its operands should begin the brackets inserting process with default 0, 0 values.}
insertBrackets(node^.left, 0, 0);
insertBrackets(node^.right, 0, 0);
end;
end
else begin
{Each time when we go down by one level in the tree we are to write another bracket. If we go to the left child, it's an opening bracket; in case of the right child, it's a closing bracket.}
insertBrackets(node^.left, valL + 1, valR);
insertBrackets(node^.right, valL, valR + 1);
end;
end;
{The procedure recursively calculates the height of the expression. For precise definition of the term 'height of the expression', see the description of the tree nodes' fields.
The procedure uses the values that are stored in the 'val' fields of the nodes. Thus, these fields shouldn't be changed after the procedure was called. Otherwise the integrity, validity and consistency of the calculated data couldn't be guaranteed. Overwrites the 'height' fields of the nodes.
'node' - the node of the expression to start from.}
procedure calculateHeights(node: pTree);
begin
if(node^.typ <> 'num') then begin
calculateHeights(node^.left);
calculateHeights(node^.right);
{For the quotients the height is equal to the sum of the heights of its operands plus 1}
if (node^.typ = '/') then begin
node^.height := node^.left^.height + node^.right^.height + 1;
end
{For other operations the height is equal to the maximum height of its operands}
else node^.height := max(node^.left^.height, node^.right^.height);
end
{For the numbers the height is 1}
else node^.height := 1;
end;
{The procedure recursively calculates the width of the expression. For precise definition of the term 'width of the expression', see the description of the tree nodes' fields.
The procedure uses the values that are stored in 'val' fields of the nodes. Thus, these fields shouldn't be changed after the procedure was called. Otherwise the integrity, validity and consistency of the calculated data couldn't be guaranteed. Overwrites the 'width' fields of the nodes.
'node' - the node of the expression to start from.}
procedure calculateWidths(node: pTree);
begin
if(node^.typ <> 'num') then begin
calculateWidths(node^.left);
calculateWidths(node^.right);
{For the quotient, the width is equal to the maximum width of its operands +2 (spaces on each side) + number of brackets to be printed around}
if (node^.typ = '/') then begin
node^.width := max(node^.left^.width, node^.right^.width) + 2 + node^.x0;
end
{For other operations, the width is equal to the sum of the widths of its operands + 3 (the operator character plus 2 spaces around the operator character)}
else node^.width := node^.left^.width + node^.right^.width + 3;
end
{For the number, its width is equal to the number of digits in it + number of brackets that are near of it. (Brackets should be appended to the 'val' field by 'insertBrackets()' procedure already.)}
else node^.width := length(node^.val);
end;
{The procedure recursively calculates the y0 values of the expression. For precise definition of the term 'y0 value of the expression', see the description of the tree nodes' fields.
The procedure uses the values that are stored in the 'height' fields of the nodes. Thus, these fields shouldn't be changed after the procedure was called. Otherwise the integrity, validity and consistency of the calculated data couldn't be guaranteed. Overwrites the 'y0' fields of the nodes.
'node' - the node of the expression to start from.
'val' - the default position for the "printer's head". In general, the parameter is used for the recursion purposes only, the initial value could be random.}
procedure prepareY(node: pTree; val: Integer);
begin
{For number the y0 value is equal to the initial position of the printer's head.}
if (node^.typ = 'num') then node^.y0 := val
{For the quotient, the y0 value is calculated by the following rules.
For the fraction line, the y0 value is equal to the initial position of the printer's head. The left operand is printed above the line, the right operand is printed below the line.}
else if (node^.typ = '/') then begin
node^.y0 := val;
prepareY(node^.left, val + (node^.left^.height div 2) + 1);
prepareY(node^.right, val - (node^.right^.height div 2) - 1);
end
{For other operations, the y0 value is equal to the y0 value of their left operand.}
else begin
prepareY(node^.left, val);
node^.y0 := node^.left^.y0;
prepareY(node^.right, val);
end;
end;
{The procedure recursively calculates the x0 values of the expression. For precise definition of the term 'x0 value of the expression', see the description of the tree nodes' fields.
The procedure uses the values that are stored in the 'width' fields of the nodes. Thus, these fields shouldn't be changed after the procedure was called. Otherwise the integrity, validity and consistency of the calculated data couldn't be guaranteed. Overwrites the 'x0' fields of the nodes.
'node' - the node of the expression to start from.
'val' - the default position for the "printer's head", which should be non-negative. It is recommended to use 0.}
procedure prepareX(node: pTree; val: Integer);
var spanL, spanR: Integer;
begin
{For number, the x0 value is equal to the initial position of the printer's head.}
if(node^.typ = 'num') then node^.x0 := val
{For non-quotient operations, the x0 value is calculated by the following rules. The left operand is written starting from the initial position of the printer's head. The operator is printed starting from the position of the printer's head after printing the left operand, which is equal to the initial printer's head position plus the left operand's width. The operator's width is 3 characters (operator character plus two spaces around it).}
else if(node^.typ <> '/') then begin
prepareX(node^.left, val);
node^.x0 := node^.left^.width + val;
prepareX(node^.right, node^.x0 + 3);
end
{The fraction line's x0 value is equal to the initial printer's head position. The operands should be centred, span values are added for this purpose. We need to take into account the brackets too. This is why there is need to distinct the case when the quotient is a left child.}
else begin
spanL := (node^.width - node^.x0 - node^.left^.width) div 2;
spanR := (node^.width - node^.x0 - node^.right^.width) div 2;
if (isLeft(node)) then begin
prepareX(node^.left, val + spanL + node^.x0);
prepareX(node^.right, val + spanR + node^.x0);
node^.x0 := val;
end
else begin
prepareX(node^.left, val + spanL);
node^.x0 := val;
prepareX(node^.right, val + spanR);
end;
end;
end;
{The procedure recursively calculates the 'val' values of the expression - the values, which are to be printed. For precise definition of the term 'val value of the expression', see the description of the tree nodes' fields.
The procedure uses the values that are stored in the 'width' and 'val' fields of the nodes. Thus, these fields shouldn't be changed after the procedure was called. Otherwise the integrity, validity and consistency of the calculated data couldn't be guaranteed. Overwrites the 'val' fields of the nodes.
'node' - the node of the expression to start from.}
procedure fillVals(node: pTree);
var i: Integer;
var str: String;
begin
{If the node is a quotient, than we need to take care of the brackets. Besides, we need to calculate the length of the fraction line.}
if (node^.typ = '/') then begin
str := ' ';
if (isLeft(node)) then begin
str := str + multStr('(', node^.x0);
end;
str := str + multStr('-', node^.width - 2 - node^.x0);
if (isRight(node)) then begin
str := str + multStr(')', node^.x0);
end;
str := str + ' ';
node^.val := str;
fillVals(node^.left);
fillVals(node^.right);
end
{If the node is a number, than we do need to do anything with it.}
else if (node^.typ = 'num') then i := 0
{If the node is a non-quotient operator, than we need to add spaces on both sides of the operator character.}
else begin
node^.val := ' ' + node^.typ + ' ';
fillVals(node^.left);
fillVals(node^.right);
end;
end;
{*Block of code responsible for printing of the expression*}
{The function defining the priorities and the order of the nodes in the printing queue. The nodes with the higher y0 values have priority over the nodes with the lower y0 values. In case the y0 values are equal, the nodes with the lower x0 value have priority over the nodes over the nodes with the higher x0 value.
'a', 'b' - nodes to be compared.}
function compare(a,b: pQueue): Integer;
begin
if (b = nil) then compare := 1
else if (a^.data^.y0 > b^.data^.y0) then compare := 1
else if (a^.data^.y0 < b^.data^.y0) then compare := -1
else if (a^.data^.x0 < b^.data^.x0) then compare := 1
else if (a^.data^.x0 > b^.data^.x0) then compare := -1
else compare := 0;
end;
{The procedure adds the node to the printing buffer in accordance with the priorities defined by the 'compare()' function.
The 'x0' and 'y0' of the item being added should be calculated, otherwise the validity and correctness of the procedure's work are not guaranteed.
'chunk' - the node to be added to the printing queue.}
procedure addToQ(chunk: pTree);
var node, current, pom: pQueue;
begin
{Wrap the node to the queue item container}
new(node);
node^.data := chunk;
node^.next := nil;
node^.prev := nil;
if printQ = nil then printQ := node
{Walk along the queue until the place for the item is found. The item should be inserted before the 'current' item. We need to be careful in the situations when the 'current' item is the last one in the queue though.}
else begin
current := printQ;
while (compare(node, current) = -1) and (current^.next <> nil) do begin
current := current^.next;
end;
if current = printQ then begin
if compare(node, current) = 1 then begin
node^.next := printQ;
printQ^.prev := node;
printQ := node;
end
else begin
current^.next := node;
node^.prev := current;
end;
end
else if compare(node, current) = 1 then begin
node^.next := current;
node^.prev := current^.prev;
current^.prev := node;
pom := node^.prev;
pom^.next := node;
end
else begin
current^.next := node;
node^.prev := current;
end;
end;
end;
{The procedure recursively puts all the nodes of expression to the printing buffer.
The 'x0' and 'y0' values should be calculated for each node of the tree.
'node' - the node to start the process from.}
procedure fillQ(node: pTree);
begin
if (node^.typ = 'num') then addToQ(node)
else begin
fillQ(node^.left);
addToQ(node);
fillQ(node^.right);
end;
end;
{The procedure puts the printer's head to the beginning of a new line.}
procedure nextLine();
begin
writeln(outF, '');
printerX := 0;
printerY := printerY - 1;
end;
{The procedure puts the printer's head to the x-coordinate, from which the 'item' item should be printed.
Note: the procedure should be called after the 'adjustY()' procedure, since 'adjustY()' resets the x-position of the printer's head.
'item' - the benchmark for adjusting the coordinate.}
procedure adjustX(item: pQueue);
var i, dif: Integer;
begin
dif := item^.data^.x0 - printerX;
for i := 1 to dif do begin
printerX := printerX + 1;
write(outF, ' ');
end;
end;
{The procedure puts the printer's head to the y-coordinate (basically to the line), where the 'item' item should be printed.
Note: resets the printer's head x-coordinate to 0. Thus should be called before the 'adjustX()' procedure.
'item' - the benchmark for adjusting the coordinate.}
procedure adjustY(item: pQueue);
var i, dif: Integer;
begin
dif := abs(item^.data^.y0 - printerY);
for i := 1 to dif do begin
nextLine();
end;
end;
{The procedure prints the items in the buffer. The x0 and y0 are considered in the process of printing.
'buffer' - the buffer to be print out.}
procedure print(buffer: pQueue);
var item: pQueue;
begin
printerX := 0;
printerY := buffer^.data^.y0;
item := buffer;
while (item <> nil) do begin
adjustY(item);
adjustX(item);
printerX := printerX + length(item^.data^.val);
write(outF, item^.data^.val);
item := item^.next;
end;
writeln(outF, '');
end;
{*Block of code responsible for preparation of external resources*}
{The procedure prepares the external resources: assigns the files on the disk to the proper variables and opens them.}
procedure prepareSources(inPath, outPath: String);
begin
if (inFolder <> 'stdin') then begin
assign(inF, inFolder + inPath);
reset(inF);
end
else begin
inF := Input;
writeln('Type the expression to be processed. Finish the expression by ctrl+z:');
end;
if (outFolder <> 'stdout') then begin
assign(outF, outFolder + outPath);
rewrite(outF);
end
else outF := Output;
end;
{The procedure closes the external resources.}
procedure closeSources();
begin
if (inFolder <> 'stdin') then close(inF);
if (outFolder <> 'stdout') then close(outF);
end;
{*Block of code responsible for communications with the user*}
{The simple procedure for printing out messages to the stdout stream. Messages will not be printed if 'mute = True'.}
procedure status(str: String);
begin
if not mute then writeln(str);
end;
{The procedure assembles the separate procedures and subprograms to a single block of code. It processes the expression got from the input stream, transforms it to a graphical representation, prints the result to the output stream and flushes the variable, preparing them for the next usage.
'inFile', 'outFile' - the names of the input and output files.}
procedure process(inFile, outFile: String);
begin
status('Starting rendering');
prepareSources(inFile, outFile);
parseFile();
status('Finished parsing');
insertBrackets(expression, 0, 0);
calculateWidths(expression);
fillVals(expression);
calculateHeights(expression);
prepareY(expression, 0);
prepareX(expression, 0);
status('Finished calculating graphic parameters');
fillQ(expression);
print(printQ);
status('Finished printing out the expression');
printQ := nil;
expression := nil;
curNode := nil;
status('Finished deleting data');
closeSources();
status('Files are closed');
status('Processing finished');
status('');
end;
procedure prcs();
var path1, path2: String;
begin
if(inFolder <> 'stdin') then begin
write('Enter the name of the input file: ');
readln(path1);
writeln('');
end
else writeln('Input: stdin');
if(outFolder <> 'stdout') then begin
write('Enter the name of the output file: ');
readln(path2);
end
else writeln('Output: stdout');
process(path1, path2);
end;
procedure printIntro();
begin
writeln('');
writeln('Fractions v.1.0, aka Zlomky v.1.0');
writeln('');
writeln('Charles University in Prague, Faculty of Mathematics and Physics');
writeln('Winter semester, school year 2016/2017');
writeln('Matvei Slavenko, Obecna matematika, the first year');
writeln('NMIN101 Programming I');
writeln('Use "?" or "help" to get the list of commands and their description.');
writeln('************************************');
writeln('');
end;
procedure printSettings();
begin
writeln('Current path to the input folder is:');
writeln(inFolder);
writeln();
writeln('Current path to the output folder is:');
writeln(outFolder);
writeln();
write('Mute: ');
writeln(mute);
end;
procedure help();
begin
writeln('Main commands:');
writeln('* prcs - process. The command starts the formula rendering process.');
writeln('* q, exit - quit. Use this command to quit the programme.');
writeln('');
writeln('Informative commands:');
writeln('* sets - settings. Prints the current input and output folders, and the mute setting.');
writeln('* credits. Prints the short information about the programme.');
writeln('');
writeln('Commands related to the programme settings:');
writeln('* chgin - change input folder. Use this command to change the setting. Use "\\" as a separator. The path to the folder should finish with "\\".');
writeln('* chgout - change output folder. Use this command to change the setting. Use "\\" as a separator. The path to the folder should finish with "\\".');
writeln('* mute. Mutes the messages related to the rendering process printed by the "prcs" command.');
writeln('* unmute. Allows the "prcs" command to print the messages related to the rendering process.');
writeln('');
end;
procedure unknownCommand();
begin
writeln('Unknown command. Use "?" or "help" to get the list of commands and their descriptions.');
end;
procedure changeInFolder();
var path1: String;
begin
write('Enter the name of the new input folder. Use "stdin" as a shortcut for the standard input: ');
readln(path1);
writeln();
inFolder := path1;
end;
procedure changeOutFolder();
var path1: String;
begin
write('Enter the name of the new output folder. Use "stdout" as a shortcut for the standard output: ');
readln(path1);
writeln();
outFolder := path1;
end;
{The procedure processes the command that was typed by user. The control is passed to the relevant procedure or subprogram. If the command is not in the list, the procedure 'unknownCommand()' will be called.
'com' - the command to be processed.}
procedure processCommand(com: String);
begin
if (com = 'help') or (com = '?') then help()
else if (com = 'prcs') then prcs()
else if (com = 'credits') then printIntro()
else if (com = 'sets') then printSettings()
else if (com = 'chgin') then changeInFolder()
else if (com = 'chgout') then changeOutFolder()
else if (com = 'q') or (com = 'exit') then com := com {Do nothing}
else if (com = 'mute') then mute := True
else if (com = 'unmute') then mute := False
else unknownCommand();
end;
{*Main method*}
{The actual body of the programme. Sets the default values for the 'inFolder' and 'outFolder' variables, prints out the information about the programme and the current settings, launches the standard working loop of the programme.}
begin
inFolder := 'D:\\Ring\\Experiments\\University\\Zlomky\\Input\\';
outFolder := 'D:\\Ring\\Experiments\\University\\Zlomky\\Output\\';
printIntro();
printSettings();
repeat
readln(inCommand);
processCommand(inCommand)
until (inCommand = 'q') or (inCommand = 'exit');
end.
|
program HowToUseBundles;
uses
SwinGame, sgTypes;
procedure Main();
var
explosion: sprite;
begin
OpenAudio();
OpenGraphicsWindow('Using Bundles', 300, 300);
LoadResourceBundle('how_to_bundles.txt');
BitmapSetCellDetails(BitmapNamed('fireBmp'), 38, 38, 8, 2, 16);
explosion := CreateSprite(BitmapNamed('fireBmp'), AnimationScriptNamed('fire'));
SpriteSetX(explosion, 131);
SpriteSetY(explosion, 131);
Repeat
ProcessEvents();
ClearScreen(ColorWhite);
DrawText('[A]nimation', ColorBlack, 0, 0);
DrawText('[T]ext', ColorBlack, 0, 10);
DrawText('[S]ound Effect', ColorBlack, 0, 20);
DrawText('[M]usic', ColorBlack, 0, 30);
DrawSprite(explosion);
UpdateSprite(explosion);
if KeyTyped(AKey) then SpriteStartAnimation(explosion, 'FireExplosion')
else if KeyDown(TKey) then DrawText('Hi!!!', ColorRed, FontNamed('harabaraText'), 120, 125)
else if KeyTyped(SKey) then PlaySoundEffect(SoundEffectNamed('danceBeat'))
else if KeyTyped(MKey) then PlayMusic(MusicNamed('danceMusic'), 1);
RefreshScreen(60);
until WindowCloseRequested();
FreeSprite(explosion);
CloseAudio();
ReleaseAllResources();
end;
begin
Main();
end. |
unit uProduto;
interface
uses SysUtils;
type
MostrarCalculo = procedure (const produto:TObject) of object;
TProduto = class(TObject)
private
FCodigo:Integer;
FDescricao: string;
FPreco: double;
FQuantidade: integer;
FTotal: double;
FMostrarCalculo: MostrarCalculo;
procedure SetCodigo(const value: integer);
procedure SetDescricao(const value:string);
procedure SetPreco(const value:double);
procedure SetQuantidade(const value:integer);
procedure SetMostrarCalculo(const value:MostrarCalculo);
{ Private declarations }
public
{ Public declarations }
property Codigo:Integer read FCodigo write SetCodigo;
property Descricao: string read FDescricao write SetDescricao;
property Preco: double read FPreco write SetPreco;
property Quantidade : integer read FQuantidade write SetQuantidade;
property Total : double read FTotal;
property OnMostrarCalculo:MostrarCalculo read FMostrarCalculo write SetMostrarCalculo;
procedure CalculaTotal;
function ConverterParaString:string;
end;
implementation
{TProduto}
procedure TProduto.CalculaTotal;
begin
FTotal := FPreco * FQuantidade;
if Assigned(FMostrarCalculo) then
FMostrarCalculo(self);
end;
procedure TProduto.SetCodigo(const value: Integer);
begin
FCodigo := value;
end;
procedure TProduto.SetDescricao(const value:string);
begin
FDescricao := value;
end;
procedure TProduto.SetPreco(const value:double);
begin
FPreco := value;
end;
procedure TProduto.SetQuantidade(const value:integer);
begin
FQuantidade := value;
end;
function TProduto.ConverterParaString:String;
begin
result := IntToStr(FCodigo) + '- ' + FDescricao + ' => '
+ FormatFloat('R$ #,##0.00', FPreco) + ' x '
+ IntToStr(FQuantidade) + ' = '
+ FormatFloat('R$ #,##0.00', FTotal);
end;
procedure TProduto.SetMostrarCalculo(const value:MostrarCalculo);
begin
FMostrarCalculo := value;
end;
end.
|
unit IndexStruct;
interface
uses Classes, CompDoc, IslUtils, SysUtils, Dialogs, SearchExpr;
type
{ EntryLocs key legend:
abc string is an internal address, objects is empty
xyz:abc string is an external address to bookId xyz, objects is empty
@xyz string is an alias to another entry, object is empty
_xyz string is a subentry, the object value is another TEntryLocs class
}
TEntryLocKind = (ekUnknown, ekAddress, ekAlias, ekSubentry);
TEntryLocs = class(TObjDict)
public
procedure AddAlias(const Alias : String); virtual;
procedure AddSub(const SubEntry, Addr : String; const AddKeyPrefix : Boolean = True); virtual;
procedure GetEntryDetails(const Index : Integer; var Kind : TEntryLocKind; var Caption : String; var Sublocs : TEntryLocs);
function RecursiveCount : Integer; virtual;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
procedure Merge(const Locs : TEntryLocs); virtual;
end;
EEntryLocOpenError = class(Exception);
EEntryLocReadError = class(Exception);
TLocsDataStyle = (ldsEntryLocs, ldsNumeric);
TPageIndex = class(TObject)
protected
FEntries : TObjDict; // all the entries in the index
FEntriesData : TStringList; // for each entry in FEntries, the number of locations it has
FStorage : TStorage; // this is only non-null if Load method was called
FStoreSize : LongInt; // valid after call to Store (tells how much was stored }
public
constructor Create; virtual;
destructor Destroy; override;
procedure AddEntryAlias(const Entry, Alias : String); virtual;
{-when called like this, Addr is a link to Entry}
procedure AddEntry(const Entry, Addr : String); virtual;
{-when called like this, Addr is a link to Entry}
procedure AddSubEntry(const Entry, SubEntry, Addr : String); virtual;
{-when called like this, Addr is a link to Subentry of Entry}
function GetEntryLocs(const Entry : String) : TEntryLocs; overload; virtual;
{-finds key in the index; if key is not found, returns new TEntryLocs }
procedure Load(const AName : String; const AStorage : TStorage); overload; virtual;
{-load the index from substorage of given storage}
procedure Load(const AStorage : TStorage); overload; virtual;
{-load the index from given storage}
procedure Store(const AStorage : TStorage); virtual;
{-store the index in the given storage}
procedure StorePacked(const AStorage : TStorage; const ALocsDataStyle : TLocsDataStyle); virtual;
{-store the index in the given storage in a packed format (saves space)}
property Entries : TObjDict read FEntries;
property EntriesData : TStringList read FEntriesData;
property Storage : TStorage read FStorage;
property StoreSize : LongInt read FStoreSize; // useful ONLY after call to Store
end;
TCharIdxArray = array[Char] of Word;
TCharIndex = record
KeyIdx : Word;
SecondCharIndex : TCharIdxArray;
end;
TFirstCharIndex = array[Char] of TCharIndex; // quick access to first words with begin with a particular character
TDirectoryHeader = record
Version : array[0..9] of Char;
EntriesCount : LongInt;
LocsDataStyle : TLocsDataStyle;
FirstCharIndex : TFirstCharIndex;
FirstCharLastIndex : TCharIdxArray;
end;
TDirectoryEntry = record
KeyPos : Cardinal; // starting position of the key in the stream
KeySize : Cardinal; // number of bytes used to store the key
LocCount : Cardinal; // the number of times the entry appears
LocPos : Cardinal; // starting position of the locations data in the stream
LocSize : Cardinal; // number of bytes used to store the locations data
end;
EStaticIndexNoStorage = Exception;
EStaticIndexInvalidEntry = Exception;
TStaticIndex = class(TObject)
protected
FStorage : TStorage; // the storage object in which index data is stored
FDirectory : TStorageStream; // the index stream
FData : TStorageStream; // the data stream
FHeader : TDirectoryHeader; // the directory's header
FRefCount : Word; // reference count
procedure Clear; virtual;
{-close the storages, streams, etc and clear any cache}
function GetCount : Cardinal;
{-return the count of entries in this index}
procedure SetStorage(const AStorage : TStorage); virtual;
{-setup the storage for this index}
public
constructor Create;
destructor Destroy; override;
procedure FillKeys(const APrefix : String; const AKeys : TStringList);
{-fill the AKeys object with all of the keys in this index}
function FindEntry(const Key : String; var Index: Cardinal; var Entry : TDirectoryEntry): Boolean;
{-given key Entry, find the corresponding Entry index using binary search}
function GetEntry(const Entry : Cardinal) : TDirectoryEntry; overload; virtual;
{-get the Entry'th entry in the directory }
function GetEntryKey(const Entry : TDirectoryEntry) : String; overload; virtual;
{-find given Entry in the disk-based index, return entry's key }
function GetEntryKey(const Entry : Cardinal) : String; overload; virtual;
{-find given Entry in the disk-based index, return entry's key }
function GetEntryLocs(const Entry : TDirectoryEntry) : TEntryLocs; overload; virtual;
{-given an Entry record, get the locations it is found in }
function GetEntryLocs(const Entry : TSchExprToken; const AMatched : TStringList) : TEntryLocs; overload; virtual;
{-given an Entry record, get the locations it is found in }
function GetEntryLocs(const Entry : String) : TEntryLocs; overload; virtual;
{-given an Entry record, get the locations it is found in }
property RefCount : Word read FRefCount write FRefCount;
property Storage : TStorage read FStorage write SetStorage;
property Count : Cardinal read GetCount;
end;
implementation
uses StUtils, StStrS;
procedure TEntryLocs.AddAlias(const Alias : String);
begin
Add('@' + Alias);
end;
procedure TEntryLocs.AddSub(const SubEntry, Addr : String; const AddKeyPrefix : Boolean = True);
var
RealKey : String;
SubLocs : TEntryLocs;
SubIdx : Integer;
begin
if AddKeyPrefix then
RealKey := '_' + SubEntry
else
RealKey := SubEntry;
SubIdx := IndexOf(RealKey);
if SubIdx >= 0 then begin
SubLocs := Objects[SubIdx] as TEntryLocs;
if SubLocs = Nil then begin
SubLocs := TEntryLocs.Create;
Objects[SubIdx] := SubLocs;
end;
end else begin
SubLocs := TEntryLocs.Create;
AddObject(RealKey, SubLocs);
end;
SubLocs.Add(Addr);
end;
procedure TEntryLocs.GetEntryDetails(const Index : Integer; var Kind : TEntryLocKind; var Caption : String; var Sublocs : TEntryLocs);
begin
Kind := ekUnknown;
Caption := Strings[Index];
Sublocs := Nil;
case Caption[1] of
'@' :
begin
Kind := ekAlias;
System.Delete(Caption, 1, 1);
end;
'_' :
begin
Kind := ekSubentry;
System.Delete(Caption, 1, 1);
Sublocs := Objects[Index] as TEntryLocs;
end;
else
if Pos(':', Caption) > 0 then
Kind := ekAddress
end;
end;
function TEntryLocs.RecursiveCount : Integer;
var
I : Integer;
Kind : TEntryLocKind;
Caption : String;
SubLocs : TEntryLocs;
begin
Result := 0;
if Count <= 0 then
Exit;
for I := 0 to Count-1 do begin
GetEntryDetails(I, Kind, Caption, Sublocs);
case Kind of
ekUnknown, ekAddress, ekAlias : Inc(Result);
ekSubentry : Inc(Result, Sublocs.RecursiveCount);
end;
end;
end;
procedure TEntryLocs.LoadFromStream(Stream: TStream);
var
TmpList : TStringList;
EntryLocs : TEntryLocs;
S : String;
I, P : Integer;
begin
Clear;
TmpList := TStringList.Create;
TmpList.LoadFromStream(Stream);
for I := 0 to TmpList.Count-1 do begin
S := TmpList[I];
if S[1] = '_' then begin
P := AnsiPos('~', S);
if P > 0 then begin
EntryLocs := TEntryLocs.Create;
EntryLocs.CommaText := Copy(S, P+1, Length(S));
Self.AddObject(Copy(S, 1, P-1), EntryLocs);
end;
end else begin
Self.Add(S);
end;
end;
TmpList.Free;
end;
procedure TEntryLocs.SaveToStream(Stream: TStream);
var
TmpList : TStringList;
EntryLocs : TEntryLocs;
S : String;
I : Integer;
begin
TmpList := TStringList.Create;
for I := 0 to Self.Count-1 do begin
S := Self.Strings[I];
if S[1] = '_' then begin
EntryLocs := Self.Objects[I] as TEntryLocs;
TmpList.Add(S + '~' + EntryLocs.CommaText);
end else begin
TmpList.Add(S);
end;
end;
TmpList.SaveToStream(Stream);
TmpList.Free;
end;
procedure TEntryLocs.Merge(const Locs : TEntryLocs);
var
SubLocs : TEntryLocs;
I, S : Integer;
Loc : String;
Kind : TEntryLocKind;
begin
if (Locs = Nil) or (Locs.Count <= 0) then
Exit;
for I := 0 to Locs.Count-1 do begin
Locs.GetEntryDetails(I, Kind, Loc, SubLocs);
case Kind of
ekUnknown, ekAddress : Add(Loc);
ekAlias : AddAlias(Loc);
ekSubentry :
if (SubLocs <> Nil) and (SubLocs.Count > 0) then begin
for S := 0 to SubLocs.Count-1 do
AddSub(Loc, SubLocs[S]);
end
end;
end;
end;
{------------------------------------------------------------------------------}
constructor TPageIndex.Create;
begin
inherited Create;
FEntries := TObjDict.Create;
FEntriesData := TStringList.Create;
end;
destructor TPageIndex.Destroy;
begin
FEntries.Free;
if FEntriesData <> Nil then
FEntriesData.Free;
FEntriesData := Nil;
if FStorage <> Nil then
FStorage.Free;
FStorage := Nil;
inherited Destroy;
end;
procedure TPageIndex.AddEntryAlias(const Entry, Alias : String);
begin
Assert(FStorage = Nil, 'Can''t add to a stream that''s being read from disk');
GetEntryLocs(Entry).AddAlias(Alias);
end;
procedure TPageIndex.AddEntry(const Entry, Addr : String);
begin
Assert(FStorage = Nil, 'Can''t add to a stream that''s being read from disk');
GetEntryLocs(Entry).Add(Addr);
end;
procedure TPageIndex.AddSubEntry(const Entry, SubEntry, Addr : String);
begin
Assert(FStorage = Nil, 'Can''t add to a stream that''s being read from disk');
GetEntryLocs(Entry).AddSub(SubEntry, Addr);
end;
function TPageIndex.GetEntryLocs(const Entry : String) : TEntryLocs;
var
DataStream : TStorageStream;
EntryIdx : Integer;
begin
Result := Nil;
if FEntries.Find(Entry, EntryIdx) then begin
Result := FEntries.Objects[EntryIdx] as TEntryLocs;
if (Result = Nil) and (FStorage <> Nil) then begin
Result := TEntryLocs.Create;
FEntries.Objects[EntryIdx] := Result; // cache the results
try
DataStream := TStorageStream.Create(IntToStr(EntryIdx), FStorage, amRead, False);
try
Result.LoadFromStream(DataStream);
except
raise EEntryLocReadError.CreateFmt('Unable to read index entry "%s" (%d) locations from %s.', [Entry, EntryIdx, FStorage.Name]);
end;
DataStream.Free;
except
raise EEntryLocOpenError.CreateFmt('Unable to open index entry "%s" (%d) locations from %s.', [Entry, EntryIdx, FStorage.Name]);
end;
end;
end else begin
if FStorage = Nil then begin
Result := TEntryLocs.Create;
FEntries.AddObject(Entry, Result);
end;
end;
end;
procedure TPageIndex.Load(const AName : String; const AStorage : TStorage);
begin
Load(TStorage.Create(AName, AStorage, amRead, tmDirect, False));
end;
procedure TPageIndex.Load(const AStorage : TStorage);
var
DataStream : TStorageStream;
begin
if FStorage <> Nil then
FStorage.Free;
FStorage := AStorage;
DataStream := TStorageStream.Create('Entries', FStorage, amRead, False);
FEntries.LoadFromStream(DataStream);
DataStream.Free;
DataStream := TStorageStream.Create('EntriesData', FStorage, amRead, False);
FEntriesData.LoadFromStream(DataStream);
DataStream.Free;
// loading of entries will happen dynamically in GetEntryLocs
end;
procedure TPageIndex.Store(const AStorage : TStorage);
var
DataStream : TStorageStream;
I : Integer;
begin
FStoreSize := 0;
FEntriesData.Clear;
FEntriesData.Sorted := False;
for I := 0 to FEntries.Count-1 do begin
DataStream := TStorageStream.Create(IntToStr(I), AStorage, amReadWrite, True);
(FEntries.Objects[I] as TEntryLocs).SaveToStream(DataStream);
FEntriesData.Add(IntToStr((FEntries.Objects[I] as TEntryLocs).RecursiveCount));
Inc(FStoreSize, DataStream.Size);
DataStream.Free;
end;
DataStream := TStorageStream.Create('Entries', AStorage, amReadWrite, True);
FEntries.SaveToStream(DataStream);
Inc(FStoreSize, DataStream.Size);
DataStream.Free;
DataStream := TStorageStream.Create('EntriesData', AStorage, amReadWrite, True);
FEntriesData.SaveToStream(DataStream);
Inc(FStoreSize, DataStream.Size);
DataStream.Free;
end;
procedure TPageIndex.StorePacked(const AStorage : TStorage; const ALocsDataStyle : TLocsDataStyle);
type
TDirectoryEntries = array[0..High(Word)] of TDirectoryEntry;
PDirectoryEntries = ^TDirectoryEntries;
TLocsDataNumeric = array[0..High(Word)] of Word;
PLocsDataNumeric = ^TLocsDataNumeric;
var
DirectoryStream, DataStream : TStorageStream;
Directory : PDirectoryEntries;
Locs : TEntryLocs;
EntryKey, LocsData : String;
I, DirectorySize, LocsNumericSize, J : Integer;
Header : TDirectoryHeader;
LocsNumeric : PLocsDataNumeric;
FirstCh, SecondCh : Char;
begin
FStoreSize := 0;
if FEntries.Count <= 0 then
Exit;
Header.Version := '6.1.0';
Header.EntriesCount := FEntries.Count;
Header.LocsDataStyle := ALocsDataStyle;
FillChar(Header.FirstCharIndex, SizeOf(Header.FirstCharIndex), $FF);
DirectorySize := SizeOf(TDirectoryEntry) * FEntries.Count;
GetMem(Directory, DirectorySize);
DataStream := TStorageStream.Create('Data', AStorage, amReadWrite, True);
for I := 0 to FEntries.Count-1 do begin
EntryKey := Entries[I];
Locs := (FEntries.Objects[I] as TEntryLocs);
Assert(Locs <> Nil);
FirstCh := UpCase(EntryKey[1]);
with Header.FirstCharIndex[FirstCh] do begin
if KeyIdx = $FFFF then KeyIdx := I;
if Length(EntryKey) > 1 then begin
SecondCh := UpCase(EntryKey[2]);
if SecondCharIndex[SecondCh] = $FFFF then
SecondCharIndex[SecondCh] := I;
end;
end;
Header.FirstCharLastIndex[FirstCh] := I;
Directory^[I].KeyPos := DataStream.Position;
DataStream.Write(PChar(EntryKey)^, Length(EntryKey));
Directory^[I].KeySize := Length(EntryKey);
Inc(FStoreSize, Length(EntryKey));
if ALocsDataStyle = ldsEntryLocs then begin
LocsData := Locs.Text;
Directory^[I].LocPos := DataStream.Position;
DataStream.Write(PChar(LocsData)^, Length(LocsData));
Directory^[I].LocSize := Length(LocsData);
Directory^[I].LocCount := Locs.RecursiveCount;
Inc(FStoreSize, Length(LocsData));
end else begin
LocsNumericSize := Locs.Count * SizeOf(Word);
GetMem(LocsNumeric, LocsNumericSize);
for J := 0 to Locs.Count-1 do
LocsNumeric^[J] := StrToInt(Locs[J]);
Directory^[I].LocPos := DataStream.Position;
DataStream.Write(LocsNumeric, LocsNumericSize);
Directory^[I].LocSize := LocsNumericSize;
Directory^[I].LocCount := Locs.Count;
Inc(FStoreSize, LocsNumericSize);
end;
end;
DataStream.Free;
(*
DebugStr := '';
for FirstCh := Low(Char) to High(Char) do begin
with Header.FirstCharIndex[FirstCh] do begin
if KeyIdx <> $FFFF then
DebugStr := DebugStr + Format('%s - %d %d'#13#10, [FirstCh, KeyIdx, Header.FirstCharLastIndex[FirstCh]]);
end;
end;
ShowMessage(DebugStr);
*)
DirectoryStream := TStorageStream.Create('Directory', AStorage, amReadWrite, True);
DirectoryStream.Write(Header, SizeOf(Header));
DirectoryStream.Write(Directory^, DirectorySize);
Inc(FStoreSize, DirectoryStream.Size);
DirectoryStream.Free;
FreeMem(Directory, DirectorySize);
end;
// ----------------------------------------------------------------------------
constructor TStaticIndex.Create;
begin
inherited Create;
end;
destructor TStaticIndex.Destroy;
begin
if FData <> Nil then begin
FData.Free;
FData := Nil;
end;
if FDirectory <> Nil then begin
FDirectory.Free;
FDirectory := Nil;
end;
if FStorage <> Nil then begin
FStorage.Free;
FStorage := Nil;
end;
inherited Destroy;
end;
procedure CheckAndFree(var AObject : TObject);
begin
if AObject <> Nil then begin
AObject.Free;
AObject := Nil;
end;
end;
procedure TStaticIndex.Clear;
begin
CheckAndFree(TObject(FDirectory));
CheckAndFree(TObject(FData));
CheckAndFree(TObject(FStorage));
end;
function TStaticIndex.GetCount : Cardinal;
begin
if FStorage = Nil then
raise EStaticIndexNoStorage.Create('Storage not provided');
Result := FHeader.EntriesCount;
end;
procedure TStaticIndex.SetStorage(const AStorage : TStorage);
begin
Clear;
FStorage := AStorage;
if FStorage <> Nil then begin
FDirectory := TStorageStream.Create('Directory', FStorage, amRead, False);
FDirectory.Read(FHeader, SizeOf(FHeader));
FData := TStorageStream.Create('Data', FStorage, amRead, False);
end;
end;
procedure TStaticIndex.FillKeys(const APrefix : String; const AKeys : TStringList);
var
Len, I, L, H : Cardinal;
InitialCh, SecondCh : Char;
Key : String;
begin
Len := Length(APrefix);
if Len = 0 then begin
for I := 0 to FHeader.EntriesCount-1 do
AKeys.Add(GetEntryKey(I));
end else begin
InitialCh := UpCase(APrefix[1]);
if Len > 1 then begin
SecondCh := UpCase(APrefix[2]);
L := FHeader.FirstCharIndex[InitialCh].SecondCharIndex[SecondCh];
end else
L := FHeader.FirstCharIndex[InitialCh].KeyIdx;
H := FHeader.FirstCharLastIndex[InitialCh];
for I := L to H do begin
Key := GetEntryKey(I);
if AnsiCompareText(Copy(Key, 1, Len), APrefix) = 0 then
AKeys.Add(Key);
end;
end;
end;
function TStaticIndex.GetEntry(const Entry : Cardinal) : TDirectoryEntry;
begin
Assert(FDirectory <> Nil);
if Entry >= Cardinal(FHeader.EntriesCount) then
EStaticIndexInvalidEntry.CreateFmt('Invalid Entry number %d', [Entry]);
FDirectory.Position := SizeOf(TDirectoryHeader) + (Entry * SizeOf(TDirectoryEntry));
FDirectory.Read(Result, SizeOf(TDirectoryEntry));
end;
function TStaticIndex.GetEntryKey(const Entry : TDirectoryEntry) : String;
begin
Assert(FData <> Nil);
SetLength(Result, Entry.KeySize);
FData.Position := Entry.KeyPos;
FData.Read(PChar(Result)^, Entry.KeySize);
end;
function TStaticIndex.GetEntryKey(const Entry : Cardinal) : String;
var
DE : TDirectoryEntry;
begin
Assert(FDirectory <> Nil);
Assert(FData <> Nil);
if Entry >= Cardinal(FHeader.EntriesCount) then
EStaticIndexInvalidEntry.CreateFmt('Invalid Entry number %d', [Entry]);
FDirectory.Position := SizeOf(TDirectoryHeader) + (Entry * SizeOf(TDirectoryEntry));
FDirectory.Read(DE, SizeOf(TDirectoryEntry));
SetLength(Result, DE.KeySize);
FData.Position := DE.KeyPos;
FData.Read(PChar(Result)^, DE.KeySize);
end;
function TStaticIndex.FindEntry(const Key : String; var Index: Cardinal; var Entry : TDirectoryEntry): Boolean;
var
Len, L, H, I, C : Integer;
InitialCh, SecondCh : Char;
begin
Result := False;
Len := Length(Key);
if Len = 0 then
Exit;
//L := 0;
//H := FHeader.EntriesCount - 1;
InitialCh := UpCase(Key[1]);
if Len > 1 then begin
SecondCh := UpCase(Key[2]);
L := FHeader.FirstCharIndex[InitialCh].SecondCharIndex[SecondCh];
end else
L := FHeader.FirstCharIndex[InitialCh].KeyIdx;
H := FHeader.FirstCharLastIndex[InitialCh];
while L <= H do begin
I := (L + H) shr 1;
Entry := GetEntry(I);
C := AnsiCompareText(GetEntryKey(Entry), Key);
if C < 0 then
L := I + 1
else begin
H := I - 1;
if C = 0 then begin
Result := True;
L := I;
end;
end;
end;
Index := L;
end;
function TStaticIndex.GetEntryLocs(const Entry : TDirectoryEntry) : TEntryLocs;
var
SLText : String;
begin
Assert(FData <> Nil);
SetLength(SLText, Entry.LocSize);
FData.Position := Entry.LocPos;
FData.Read(PChar(SLText)^, Entry.LocSize);
Result := TEntryLocs.Create;
Result.Text := SLText;
end;
function TStaticIndex.GetEntryLocs(const Entry : TSchExprToken; const AMatched : TStringList) : TEntryLocs;
var
Len, I, L, H, FullLen : Cardinal;
CompareResult : Integer;
DE : TDirectoryEntry;
InitialCh, SecondCh : Char;
FullKey, MatchSound : ShortString;
TempLocs : TEntryLocs;
begin
Result := Nil;
Len := Length(Entry.Text);
if Len = 0 then
Exit;
if (not FlagIsSet(Entry.Flags, setfLikeSearch)) and (not FlagIsSet(Entry.Flags, setfStemSearch)) then begin
if FindEntry(Entry.Text, I, DE) then
Result := GetEntryLocs(DE);
end else begin
if FlagIsSet(Entry.Flags, setfStemSearch) then begin
InitialCh := UpCase(Entry.Text[1]);
if Len > 1 then begin
SecondCh := UpCase(Entry.Text[2]);
L := FHeader.FirstCharIndex[InitialCh].SecondCharIndex[SecondCh];
end else
L := FHeader.FirstCharIndex[InitialCh].KeyIdx;
H := FHeader.FirstCharLastIndex[InitialCh];
for I := L to H do begin
DE := GetEntry(I);
FullKey := GetEntryKey(DE);
FullLen := Length(FullKey);
if FullLen = Len then
CompareResult := AnsiCompareText(FullKey, Entry.Text)
else if FullLen > Len then
CompareResult := AnsiCompareText(Copy(FullKey, 1, Len), Entry.Text)
else
CompareResult := -1;
if CompareResult = 0 then begin
AMatched.Add(FullKey);
TempLocs := GetEntryLocs(DE);
if Result = Nil then
Result := TEntryLocs.Create;
Result.Merge(TempLocs);
TempLocs.Free;
end else if CompareResult > 0 then
Exit;
end;
end else if FlagIsSet(Entry.Flags, setfLikeSearch) then begin
MatchSound := SoundexS(Entry.Text);
InitialCh := UpCase(Entry.Text[1]);
L := FHeader.FirstCharIndex[InitialCh].KeyIdx;
H := FHeader.FirstCharLastIndex[InitialCh];
for I := L to H do begin
DE := GetEntry(I);
FullKey := GetEntryKey(DE);
if SoundexS(FullKey) = MatchSound then begin
AMatched.Add(FullKey);
TempLocs := GetEntryLocs(DE);
if Result = Nil then
Result := TEntryLocs.Create;
Result.Merge(TempLocs);
TempLocs.Free;
end;
end;
end;
end;
end;
function TStaticIndex.GetEntryLocs(const Entry : String) : TEntryLocs;
var
I : Cardinal;
DE : TDirectoryEntry;
begin
Result := Nil;
if FindEntry(Entry, I, DE) then
Result := GetEntryLocs(DE);
end;
end.
|
unit TITaxInvoicesEdit_Add;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,IBase,TiCommonProc,TITaxinvoicesEdit_DM, cxButtonEdit,
cxTextEdit, cxControls, cxContainer, cxEdit, cxMaskEdit, cxDropDownEdit,
cxCalendar, ExtCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter,
cxData, cxDataStorage, DB, cxDBData, cxGridLevel, cxClasses,
cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, dxBar,
TiCommonStyles, cxGridBandedTableView, dxBarExtItems, dxStatusBar,
TITaxInvoicesEdit_AddInNakl,
TICommonLoader,dogLoaderUnit, LoaderUnit, AArray,cxLookAndFeelPainters, cxButtons, ComCtrls,
TiCommonTypes,TiMessages, Registry,
cxGridDBBandedTableView,
TITaxInvoicesEdit_AddTara, cxLabel, cxCheckBox, cxMemo, cxCurrencyEdit,
Buttons, TITaxInvoicesEdit_Budget, kernel, TITaxInvoicesEdit_EditTax, TICommonDates;
type TTaxInvocesUser = record
id_user:Integer;
name_user:string;
name_computer:string;
ip_computer:string;
end;
type
TTaxInvoicesEditAddForm = class(TForm)
Panel1: TPanel;
PodNaklLabel: TLabel;
DataVipLabel: TLabel;
PodNumLabel: TLabel;
OsobaProdavecLabel: TLabel;
OsobaPokupLabel: TLabel;
IPNProdavecLabel: TLabel;
IPNPokupLabel: TLabel;
PlaceProdavecLabel: TLabel;
TelProdavecLabel: TLabel;
NumReestrProdavecLabel: TLabel;
NumReestrPokupLabel: TLabel;
PodNumTextEdit: TcxTextEdit;
OsobaPokupButtonEdit: TcxButtonEdit;
EdrpLabel: TLabel;
PostavkaButtonEdit: TcxButtonEdit;
RozraxunokButtonEdit: TcxButtonEdit;
OsobaProdavecTextEdit: TcxTextEdit;
IPNProdavecTextEdit: TcxTextEdit;
PlaceProdavecTextEdit: TcxTextEdit;
TelProdavecTextEdit: TcxTextEdit;
NaklInfoAllPanel: TPanel;
Panel3: TPanel;
NaklBarManager: TdxBarManager;
AddButton: TdxBarLargeButton;
UpdateButton: TdxBarLargeButton;
RefreshButton: TdxBarLargeButton;
DeleteButton: TdxBarLargeButton;
SpecialNotesButtonEdit: TcxButtonEdit;
PodZobButtonEdit: TcxButtonEdit;
PodKreditButtonEdit: TcxButtonEdit;
EdrpTextEdit: TcxTextEdit;
YesButton: TcxButton;
IPNPokupTextEdit: TcxTextEdit;
TelPokupTextEdit: TcxTextEdit;
NumReestrPokupTextEdit: TcxTextEdit;
NumReestrProdavecTextEdit: TcxTextEdit;
FirstAllStatusBar: TdxStatusBar;
TransportCostsStatusBar: TdxStatusBar;
MortgageTaraStatusBar: TdxStatusBar;
dxStatusBar4: TdxStatusBar;
dxStatusBar5: TdxStatusBar;
dxStatusBar6: TdxStatusBar;
TaxStatusBar: TdxStatusBar;
SummaAllPDVStatusBar: TdxStatusBar;
dxStatusBar9: TdxStatusBar;
EditingButton: TcxButton;
NaklInsPopupMenu: TdxBarPopupMenu;
DeliveryInsBarButton: TdxBarButton;
TransportInsBarButton: TdxBarButton;
TaraInsBarButton: TdxBarButton;
dxBarButton4: TdxBarButton;
dxBarButton5: TdxBarButton;
NaklDeliveryGridBanded: TcxGrid;
NaklDeliveryGridDBBandedTableView: TcxGridDBBandedTableView;
NaklDeliveryGridLevel: TcxGridLevel;
NaklDeliveryGridDBBandedTableView_DATE_SHIPMENT: TcxGridDBBandedColumn;
NaklDeliveryGridDBBandedTableView_NAME_MEASURES: TcxGridDBBandedColumn;
NaklDeliveryGridDBBandedTableView_NAME_RANGE_OF_DELIVERY: TcxGridDBBandedColumn;
NaklDeliveryGridDBBandedTableView_KOL_VO_DELIVERY_GOODS: TcxGridDBBandedColumn;
NaklDeliveryGridDBBandedTableView_PRICE_DELIVERY_GOODS: TcxGridDBBandedColumn;
NaklDeliveryGridDBBandedTableView_VALUE_DELIVERY_20: TcxGridDBBandedColumn;
NaklDeliveryGridDBBandedTableView_VALUE_DELIVERY_CUSTOMS: TcxGridDBBandedColumn;
NaklDeliveryGridDBBandedTableView_VALUE_DELIVERY_EXPORT: TcxGridDBBandedColumn;
NaklDeliveryGridDBBandedTableView_VALUE_DELIVERY_VAT_EXEMPTION: TcxGridDBBandedColumn;
NaklDeliveryGridDBBandedTableView_SUMMA_ALL: TcxGridDBBandedColumn;
NaklUpdBarPopupMenu: TdxBarPopupMenu;
NaklDelBarPopupMenu: TdxBarPopupMenu;
DeliveryUpdBarButton: TdxBarButton;
TransportUpdBarButton: TdxBarButton;
TaraUpdBarButton: TdxBarButton;
dxBarButton8: TdxBarButton;
dxBarButton9: TdxBarButton;
DeliveryDelBarButton: TdxBarButton;
TransportDelBarButton: TdxBarButton;
NumOrderLabel: TLabel;
NumOrderTextEdit: TcxTextEdit;
PodKreditCheckBox: TcxCheckBox;
PodZobCheckBox: TcxCheckBox;
OsoblPrimCheckBox: TcxCheckBox;
VLabel: TcxLabel;
DataTermsdelDateEdit: TcxDateEdit;
NumDogLabel: TcxLabel;
NumTermsDelTextEdit: TcxTextEdit;
TaraDelBarButton: TdxBarButton;
DataVipDateEdit: TcxDateEdit;
is_issued_buyer_CheckBox: TcxCheckBox;
is_erpn_CheckBox: TcxCheckBox;
is_copy_CheckBox: TcxCheckBox;
CauseLabel: TLabel;
PostavkaCheckBox: TcxCheckBox;
RozraxunokCheckBox: TcxCheckBox;
PhoneCheckBox: TCheckBox;
SavePhoneButton: TcxButton;
FullNameCheckBox: TCheckBox;
SaveFullNameButton: TcxButton;
FullNameMemo: TMemo;
PlacePokupCheckBox: TCheckBox;
PlacePokupMemo: TcxMemo;
SavePlacePokupButton: TcxButton;
Label1: TLabel;
TypeDocumentButtonEdit: TcxButtonEdit;
NotPDVCheckBox: TcxCheckBox;
BudgetButton: TdxBarLargeButton;
NoteButtonEdit: TcxButtonEdit;
NoteCheckBox: TcxCheckBox;
EditTaxButton: TdxBarLargeButton;
OznakaCheckBox: TcxCheckBox;
OznakaTextEdit: TcxTextEdit;
procedure AddButtonClick(Sender: TObject);
procedure SpecialNotesButtonEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure PostavkaButtonEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure RozraxunokButtonEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure OsobaPokupButtonEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure IPNPokupButtonEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure PlacePokupButtonEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure TelPokupButtonEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure NumReestrPokupButtonEditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
procedure EdrpButtonEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure NumReestrProdavecButtonEditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
procedure PodKreditButtonEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure PodZobButtonEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure CancelButtonClick(Sender: TObject);
procedure YesButtonClick(Sender: TObject);
procedure EditingButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure DeliveryInsBarButtonClick(Sender: TObject);
procedure RefreshButtonClick(Sender: TObject);
procedure UpdateButtonClick(Sender: TObject);
procedure DeliveryUpdBarButtonClick(Sender: TObject);
procedure DeleteButtonClick(Sender: TObject);
procedure DeliveryDelBarButtonClick(Sender: TObject);
procedure TransportInsBarButtonClick(Sender: TObject);
procedure TransportUpdBarButtonClick(Sender: TObject);
procedure TransportDelBarButtonClick(Sender: TObject);
procedure TaraInsBarButtonClick(Sender: TObject);
procedure PodZobCheckBoxClick(Sender: TObject);
procedure PodKreditCheckBoxClick(Sender: TObject);
procedure OsoblPrimCheckBoxClick(Sender: TObject);
procedure TaraUpdBarButtonClick(Sender: TObject);
procedure TaraDelBarButtonClick(Sender: TObject);
procedure DataVipDateEdit1KeyPress(Sender: TObject; var Key: Char);
procedure PodNumTextEditKeyPress(Sender: TObject; var Key: Char);
procedure OsobaPokupButtonEditKeyPress(Sender: TObject; var Key: Char);
procedure NumOrderTextEditKeyPress(Sender: TObject; var Key: Char);
procedure FormActivate(Sender: TObject);
procedure PostavkaButtonEditKeyPress(Sender: TObject; var Key: Char);
procedure DataTermsdelDateEditKeyPress(Sender: TObject; var Key: Char);
procedure NumTermsDelTextEditKeyPress(Sender: TObject; var Key: Char);
procedure RozraxunokButtonEditKeyPress(Sender: TObject; var Key: Char);
procedure PodZobButtonEditKeyPress(Sender: TObject; var Key: Char);
procedure PodKreditButtonEditKeyPress(Sender: TObject; var Key: Char);
procedure SpecialNotesButtonEditKeyPress(Sender: TObject;
var Key: Char);
procedure IPNPokupTextEditKeyPress(Sender: TObject; var Key: Char);
procedure PostavkaCheckBox1Click(Sender: TObject);
procedure RozraxunokCheckBox1Click(Sender: TObject);
procedure RozraxunokCheckBoxClick(Sender: TObject);
procedure PostavkaCheckBoxClick(Sender: TObject);
procedure PhoneCheckBoxClick(Sender: TObject);
procedure FullNameCheckBoxClick(Sender: TObject);
procedure SavePhoneButtonClick(Sender: TObject);
procedure SaveFullNameButtonClick(Sender: TObject);
procedure NumOrderTextEditExit(Sender: TObject);
procedure DataVipDateEditKeyPress(Sender: TObject; var Key: Char);
procedure PlacePokupCheckBoxClick(Sender: TObject);
procedure SavePlacePokupButtonClick(Sender: TObject);
procedure TypeDocumentButtonEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure ToolButton_addClick(Sender: TObject);
procedure SpeedButton_redClick(Sender: TObject);
procedure ToolButton_delClick(Sender: TObject);
procedure BudgetButtonClick(Sender: TObject);
procedure NoteCheckBoxClick(Sender: TObject);
procedure NoteButtonEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure EditTaxButtonClick(Sender: TObject);
procedure OznakaCheckBoxClick(Sender: TObject);
private
id_Customer : Integer;
id_vid_nakl_Ins : Integer;
id_vid_nakl_doc_Ins : Integer;
id_Reestr_Ins : Integer;
id_Seller : Integer;
PRes : TTITaxInvoicesInfo;
pLanguageIndex : Byte;
PDb_Handle : TISC_DB_HANDLE;
pStylesDM : TStyleDM;
PParameter : TTITaxInvoicesInfo;
TaxInvoicesUser : TTaxInvocesUser;
procedure ReadReg;
procedure WriteReg;
procedure FirstSummaAll;
procedure TransportCosts;
procedure MortgageTara;
procedure ClearStatusBars;
procedure EnableButtons(id:Integer);
public
id_university : Integer;
provodka :Boolean;
full_name_customer :string;
TaxInvoicesEditDM : TTaxInvoicesEditDM;
procedure DoPrint; //старая налоговая
procedure DoPrintDecember; // новая накладная первый экземпляр
procedure DoPrintDecemberTwoEkz; // новая накладная второй экземпляр
procedure replaceAbreviatures(short_name:string);
constructor Create(AOwner:TComponent;Db_Handle:TISC_DB_HANDLE;id_Vid_Nakl:Integer;id_Vid_Nakl_Doc:Integer;id_Reestr:Integer);reintroduce;
property Res:TTITaxInvoicesInfo read PRes;
property Parameter:TTITaxInvoicesInfo read PParameter;
end;
var
TaxInvoicesEditAddForm: TTaxInvoicesEditAddForm;
implementation
uses FIBQuery,LoadDogManedger;
{$R *.dfm}
constructor TTaxInvoicesEditAddForm.Create(AOwner:TComponent;Db_Handle:TISC_DB_HANDLE; id_Vid_Nakl:Integer;id_Vid_Nakl_Doc:Integer;id_Reestr:Integer);
var
pk_id : int64;
sum_All_Nds : Double;
sum_All_Not_NDS : Double;
i : Integer;
begin
inherited Create(AOwner);
PDb_Handle := Db_Handle;
id_vid_nakl_Ins := id_Vid_Nakl; //id накладной из справочника
id_vid_nakl_doc_Ins := id_Vid_Nakl_Doc; //id накладной (документа)
id_Reestr_Ins := id_Reestr; //id реестра к которой относится документ
TaxInvoicesEditDM := TTaxInvoicesEditDM.Create(AOwner,Db_Handle);
//******************************************************************************
pLanguageIndex := LanguageIndex;
PodNaklLabel.Caption := GetConst('PodNakl',tcLabel);
OsobaProdavecLabel.Caption := GetConst('OsobaProdavec',tcLabel);
OsobaPokupLabel.Caption := GetConst('OsobaPokup',tcLabel);
IPNProdavecLabel.Caption := GetConst('IPNProdavec',tcLabel);
IPNPokupLabel.Caption := GetConst('IPNPokup',tcLabel);
PlaceProdavecLabel.Caption := GetConst('PlaceProdavec',tcLabel);
//PlacePokupLabel.Caption := GetConst('PlacePokup',tcLabel);
TelProdavecLabel.Caption := GetConst('TelProdavec',tcLabel);
//TelPokupLabel.Caption := GetConst('TelPokup',tcLabel);
EdrpLabel.Caption := GetConst('Edrp',tcLabel);
//*****************************************************************************
TaxInvoicesEditDM.UserDSet.Close;
TaxInvoicesEditDM.UserDSet.SelectSQL.Text := 'select * from TI_USER_INFO';
TaxInvoicesEditDM.UserDSet.Open;
TaxInvoicesUser.id_user := TaxInvoicesEditDM.UserDSet['ID_USER'];
TaxInvoicesUser.name_user := TaxInvoicesEditDM.UserDSet['USER_FIO'];
TaxInvoicesUser.name_computer := TaxInvoicesEditDM.UserDSet['HOST_NAME'];
TaxInvoicesUser.ip_computer := TaxInvoicesEditDM.UserDSet['IP_ADRESS'];
//******************************************************************************
PhoneCheckBox.Checked := False;
TelPokupTextEdit.Enabled := False;
SavePhoneButton.Visible := False;
FullNameCheckBox.Checked := False;
FullNameMemo.ReadOnly := True;
SaveFullNameButton.Visible := False;
PlacePokupCheckBox.Checked := False;
PlacePokupMemo.Properties.ReadOnly := True;
SavePlacePokupButton.Visible := False;
//******************************************************************************
TaxInvoicesEditDM.Customer_DonnuDSet.Close;
TaxInvoicesEditDM.Customer_DonnuDSet.SelectSQL.Text := 'select * from TI_CUSTOMER_INFO(:id)';
TaxInvoicesEditDM.Customer_DonnuDSet.ParamByName('id').Value := null;
TaxInvoicesEditDM.Customer_DonnuDSet.Open;
//********************************************************************************
TaxInvoicesEditDM.DSet.Close;
TaxInvoicesEditDM.DSet.SelectSQL.Text := 'select * from TI_SETTING';
TaxInvoicesEditDM.DSet.Open;
if (id_vid_nakl_doc_Ins = -1) then //вставка документа
begin
ReadReg; //чтение из реестра (дополнительные справочники)
Caption := GetConst('TaxInvEditAddDoc',tcForm);
TaxInvoicesEditDM.NaklDeliveryDSet.Close;
TaxInvoicesEditDM.NaklDeliveryDSet.SelectSQL.Text := 'select * from TI_SP_VID_NAKL_DOC where ID_VID_NAKL_DOC = -1';
TaxInvoicesEditDM.NaklDeliveryDSet.Open;
//***********автоматически ставить номер**************************************//
TaxInvoicesEditDM.WriteTransaction.StartTransaction;
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_LAST_NOMER_NAKL_SEARCH';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_REESTR').Value := id_Reestr_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('TYPE_NAKL').Value := 1; //выданные накладные
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.WriteTransaction.Commit;
NumOrderTextEdit.Text := TaxInvoicesEditDM.pFIBStoredProc.ParamByName('LAST_NUM_ORDER').AsString;
if (TaxInvoicesEditDM.DSet['IS_SAME_NUM_NAKL'] = 1)then
begin
PodNumTextEdit.Text := NumOrderTextEdit.Text;
end
else
begin
PodNumTextEdit.Text := '';
end;
//****************************************************************************
EdrpTextEdit.Text := '';
FullNameMemo.Text := '';
IPNPokupTextEdit.Text := '';
PlacePokupMemo.Text := '';
TelPokupTextEdit.Text := '';
NumReestrPokupTextEdit.Text := '';
OsobaPokupButtonEdit.Text := '';
IPNPokupTextEdit.Text := '';
//PodNumTextEdit.Text := '';
NumTermsDelTextEdit.Text := '';
NoteButtonEdit.Text := '';
OznakaTextEdit.Text := '';
NoteCheckBox.Checked := False;
NoteButtonEdit.Enabled := False;
DataVipDateEdit.Date := Now;
PodZobButtonEdit.Enabled := False;
PodKreditButtonEdit.Enabled := False;
SpecialNotesButtonEdit.Enabled := False;
OznakaTextEdit.Enabled := False;
PodZobCheckBox.Checked := False;
PodKreditCheckBox.Checked := False;
OsoblPrimCheckBox.Checked := False;
NotPDVCheckBox.Checked := False;
TelProdavecTextEdit.Text := TaxInvoicesEditDM.Customer_DonnuDSet['phone_customer'];
OznakaCheckBox.Checked := False;
ClearStatusBars; // чистим статус-бары
EnableButtons(id_vid_nakl_doc_Ins); // делаем кнопки видимыми (невидимыми)
PodZobButtonEdit.Properties.onButtonClick := PodZobButtonEditPropertiesButtonClick;
PodKreditButtonEdit.Properties.onButtonClick := PodKreditButtonEditPropertiesButtonClick;
SpecialNotesButtonEdit.Properties.onButtonClick := SpecialNotesButtonEditPropertiesButtonClick;
PostavkaButtonEdit.Properties.onButtonClick := PostavkaButtonEditPropertiesButtonClick;
OsobaPokupButtonEdit.Properties.onButtonClick := OsobaPokupButtonEditPropertiesButtonClick;
RozraxunokButtonEdit.Properties.onButtonClick := RozraxunokButtonEditPropertiesButtonClick;
TypeDocumentButtonEdit.Properties.onButtonClick := TypeDocumentButtonEditPropertiesButtonClick;
NoteButtonEdit.Properties.onButtonClick := NoteButtonEditPropertiesButtonClick;
PodNumTextEdit.Properties.ReadOnly := False;
NumOrderTextEdit.Properties.ReadOnly := False;
NumTermsDelTextEdit.Properties.ReadOnly := False;
PodNumTextEdit.Properties.ReadOnly := False;
DataVipDateEdit.Properties.ReadOnly := False;
DataTermsdelDateEdit.Properties.ReadOnly := False;
IPNPokupTextEdit.Properties.ReadOnly := False;
//NoteTextEdit.Properties.ReadOnly := False;
NotPDVCheckBox.Properties.ReadOnly := False;
OznakaTextEdit.Properties.ReadOnly := False;
OznakaCheckBox.Properties.ReadOnly := False;
PodZobButtonEdit.Style.Color := clWindow;
PodKreditButtonEdit.Style.Color := clWindow;
DataVipDateEdit.Style.Color := clWindow;
SpecialNotesButtonEdit.Style.Color := clWindow;
PostavkaButtonEdit.Style.Color := clWindow;
OsobaPokupButtonEdit.Style.Color := clWindow;
RozraxunokButtonEdit.Style.Color := clWindow;
PodNumTextEdit.Style.Color := clWindow;
NumOrderTextEdit.Style.Color := clWindow;
DataTermsdelDateEdit.Style.Color := clWindow;
NumTermsDelTextEdit.Style.Color := clWindow;
IPNPokupTextEdit.Style.Color := clWindow;
TypeDocumentButtonEdit.Style.Color := clWindow;
OznakaTextEdit.Style.Color := clWindow;
EditingButton.Visible := False;
AddButton.Enabled := False;
UpdateButton.Enabled := False;
DeleteButton.Enabled := False;
RefreshButton.Enabled := False;
BudgetButton.Enabled := False;
EditTaxButton.Enabled := False;
is_issued_buyer_CheckBox.Checked := False;
is_erpn_CheckBox.Checked := False;
OsoblPrimCheckBox.Checked := False;
SpecialNotesButtonEdit.Enabled := False;
is_copy_CheckBox.Checked := False;
PostavkaCheckBox.Checked := False;
PostavkaButtonEdit.Enabled := False;
DataTermsdelDateEdit.Enabled := False;
NumTermsDelTextEdit.Enabled := False;
RozraxunokCheckBox.Checked := False;
RozraxunokButtonEdit.Enabled := False;
is_issued_buyer_CheckBox.Properties.ReadOnly := False;
is_erpn_CheckBox.Properties.ReadOnly := False;
is_issued_buyer_CheckBox.Properties.ReadOnly := False;
OsoblPrimCheckBox.Properties.ReadOnly := False;
is_copy_CheckBox.Properties.ReadOnly := False;
PostavkaCheckBox.Properties.ReadOnly := False;
RozraxunokCheckBox.Properties.ReadOnly := False;
PodZobCheckBox.Properties.ReadOnly := False;
PodKreditCheckBox.Properties.ReadOnly := False;
provodka := True;
end
else
begin
Caption := GetConst('TaxInvEditUpdDoc',tcForm);
RefreshButton.Click;
EnableButtons(id_vid_nakl_doc_Ins); // делаем кнопки видимыми (невидимыми)
DataVipDateEdit.Date := TaxInvoicesEditDM.VidNaklInfoDSet['DATA_VIPISKI'];
EdrpTextEdit.Text := TaxInvoicesEditDM.VidNaklInfoDSet['EDRPOU_CUSTOMER'];
IPNPokupTextEdit.Text := TaxInvoicesEditDM.VidNaklInfoDSet['IPN_CUSTOMER'];
PlacePokupMemo.Text := TaxInvoicesEditDM.VidNaklInfoDSet['PLACE_CUSTOMER'];
TelPokupTextEdit.Text := TaxInvoicesEditDM.VidNaklInfoDSet['phone_customer'];;
NumReestrPokupTextEdit.Text := TaxInvoicesEditDM.VidNaklInfoDSet['NUMREESTR_CUSTOMER'];
OsobaPokupButtonEdit.Text := TaxInvoicesEditDM.VidNaklInfoDSet['NAME_CUSTOMER'];
PostavkaButtonEdit.Text := TaxInvoicesEditDM.VidNaklInfoDSet['NAME_TERMSDELIVERY'];
RozraxunokButtonEdit.Text := TaxInvoicesEditDM.VidNaklInfoDSet['NAME_FORMCALCULATIONS'];
IPNPokupTextEdit.Text := TaxInvoicesEditDM.VidNaklInfoDSet['IPN_CUSTOMER'];
PodNumTextEdit.Text := TaxInvoicesEditDM.VidNaklInfoDSet['NUM_NAKL'];
NumOrderTextEdit.Text := TaxInvoicesEditDM.VidNaklInfoDSet['num_order'];
NumTermsDelTextEdit.Text := TaxInvoicesEditDM.VidNaklInfoDSet['num_termsdelivery'];
TypeDocumentButtonEdit.Text := TaxInvoicesEditDM.VidNaklInfoDSet['name_type_document'];
TelProdavecTextEdit.Text := TaxInvoicesEditDM.VidNaklInfoDSet['phone_seller'];
//NoteTextEdit.Text := TaxInvoicesEditDM.VidNaklInfoDSet['note'];
{ if (TaxInvoicesEditDM.VidNaklInfoDSet['note']<>null) then
begin
NoteTextEdit.Text := TaxInvoicesEditDM.VidNaklInfoDSet['note'];
end
else
begin
NoteTextEdit.Text := '';
end; }
if ((TaxInvoicesEditDM.VidNaklInfoDSet['id_note']<>null) and (TaxInvoicesEditDM.VidNaklInfoDSet['id_note']<>0)) then
begin
NoteButtonEdit.Text := TaxInvoicesEditDM.VidNaklInfoDSet['note'];
NoteButtonEdit.Enabled := True;
NoteCheckBox.Checked := True;
PParameter.id_note := TaxInvoicesEditDM.VidNaklInfoDSet['id_note'];
PParameter.article_note := TaxInvoicesEditDM.VidNaklInfoDSet['note'];
end
else
begin
NoteButtonEdit.Text := '';
NoteButtonEdit.Enabled := False;
NoteCheckBox.Checked := False;
end;
if (TaxInvoicesEditDM.VidNaklInfoDSet['full_name_customer']<>null) then
begin
FullNameMemo.Text := TaxInvoicesEditDM.VidNaklInfoDSet['full_name_customer'];
PParameter.Full_name_customer := TaxInvoicesEditDM.VidNaklInfoDSet['full_name_customer'];
end
else
begin
FullNameMemo.Text := '';
FullNameMemo.ReadOnly := False;
FullNameCheckBox.Checked := True;
SaveFullNameButton.Visible := True;
PParameter.Full_name_customer := '';
end;
if (TaxInvoicesEditDM.VidNaklInfoDSet['NAME_TAX_LIABILITIES']<>'')then
begin
PodZobCheckBox.Checked := True;
PodZobButtonEdit.Enabled := True;
PodZobButtonEdit.Text := TaxInvoicesEditDM.VidNaklInfoDSet['NAME_TAX_LIABILITIES'];
end
else
begin
PodZobCheckBox.Checked := False;
PodZobButtonEdit.Enabled := False;
PodZobButtonEdit.Text := '';
end;
if (TaxInvoicesEditDM.VidNaklInfoDSet['NUM_SPECIALNOTES']<>'')then
begin
OsoblPrimCheckBox.Checked := True;
SpecialNotesButtonEdit.Enabled := True;
SpecialNotesButtonEdit.Text := TaxInvoicesEditDM.VidNaklInfoDSet['NUM_SPECIALNOTES'];
end
else
begin
OsoblPrimCheckBox.Checked := False;
SpecialNotesButtonEdit.Enabled := False;
SpecialNotesButtonEdit.Text := '';
end;
if (TaxInvoicesEditDM.VidNaklInfoDSet['OZNAKA_NAKL']<>'')then
begin
OznakaCheckBox.Checked := True;
OznakaTextEdit.Enabled := True;
OznakaTextEdit.Text := TaxInvoicesEditDM.VidNaklInfoDSet['OZNAKA_NAKL'];
end
else
begin
OznakaCheckBox.Checked := False;
OznakaTextEdit.Enabled := False;
OznakaTextEdit.Text := '';
end;
if (TaxInvoicesEditDM.VidNaklInfoDSet['name_termsdelivery']<>'')then
begin
PostavkaCheckBox.Checked := True;
DataTermsdelDateEdit.Enabled := True;
NumTermsDelTextEdit.Enabled := True;
PostavkaButtonEdit.Enabled := True;
PostavkaButtonEdit.Text := TaxInvoicesEditDM.VidNaklInfoDSet['name_termsdelivery'];
NumTermsDelTextEdit.Text := TaxInvoicesEditDM.VidNaklInfoDSet['num_termsdelivery'];
if (TaxInvoicesEditDM.VidNaklInfoDSet['data_termsdelivery'] = StrToDate('01.01.1900')) then
begin
DataTermsdelDateEdit.Text := '';
end
else
begin
DataTermsdelDateEdit.Date := TaxInvoicesEditDM.VidNaklInfoDSet['data_termsdelivery'];
end;
end
else
begin
PostavkaCheckBox.Checked := False;
DataTermsdelDateEdit.Enabled := False;
NumTermsDelTextEdit.Enabled := False;
PostavkaButtonEdit.Enabled := False;
DataTermsdelDateEdit.Text := '';
NumTermsDelTextEdit.Text := '';
PostavkaButtonEdit.Text := '';
end;
if (TaxInvoicesEditDM.VidNaklInfoDSet['name_formcalculations']<>'')then
begin
RozraxunokCheckBox.Checked := True;
RozraxunokButtonEdit.Enabled := True;
RozraxunokButtonEdit.Text := TaxInvoicesEditDM.VidNaklInfoDSet['name_formcalculations'];
end
else
begin
RozraxunokCheckBox.Checked := False;
RozraxunokButtonEdit.Enabled := False;
RozraxunokButtonEdit.Text := '';
end;
if (TaxInvoicesEditDM.VidNaklInfoDSet['NAME_TAXKREDIT']<>'')then
begin
PodKreditCheckBox.Checked := True;
PodKreditButtonEdit.Enabled := True;
PodKreditButtonEdit.Text := TaxInvoicesEditDM.VidNaklInfoDSet['NAME_TAXKREDIT'];
end
else
begin
PodKreditCheckBox.Checked := False;
PodKreditButtonEdit.Enabled := False;
PodKreditButtonEdit.Text := '';
end;
if (TaxInvoicesEditDM.VidNaklInfoDSet['is_issued_buyer'] = 1)then
is_issued_buyer_CheckBox.Checked := True
else
is_issued_buyer_CheckBox.Checked := False;
if (TaxInvoicesEditDM.VidNaklInfoDSet['is_erpn'] = 1)then
is_erpn_CheckBox.Checked := True
else
is_erpn_CheckBox.Checked := False;
if (TaxInvoicesEditDM.VidNaklInfoDSet['is_copy'] = 1)then
is_copy_CheckBox.Checked := True
else
is_copy_CheckBox.Checked := False;
if (TaxInvoicesEditDM.VidNaklInfoDSet['IS_NOT_PDV'] = 1)then
NotPDVCheckBox.Checked := True
else
NotPDVCheckBox.Checked := False;
// отображение проводок
for i := 0 to TaxInvoicesEditDM.RxMemoryData_smet.RecordCount - 1 do
TaxInvoicesEditDM.RxMemoryData_smet.Delete;
TaxInvoicesEditDM.Smeta_Vid_N_DSet.Close;
TaxInvoicesEditDM.Smeta_Vid_N_DSet.SelectSQL.Text := 'select * from TI_BUDGET_NDS_SEL where id_nakl = :id and is_vid = 1';
TaxInvoicesEditDM.Smeta_Vid_N_DSet.ParamByName('id').Value := TaxInvoicesEditDM.VidNaklInfoDSet['id_vid_nakl'];
TaxInvoicesEditDM.Smeta_Vid_N_DSet.Open;
TaxInvoicesEditDM.Smeta_Vid_N_DSet.FetchAll;
TaxInvoicesEditDM.Smeta_Vid_N_DSet.First;
sum_All_Nds := 0;
sum_All_Not_NDS := 0;
for i := 0 to TaxInvoicesEditDM.Smeta_Vid_N_DSet.RecordCount-1 do
begin
TaxInvoicesEditDM.RxMemoryData_smet.Open;
TaxInvoicesEditDM.RxMemoryData_smet.Insert;
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('id_smet').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['id_smet'];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('id_razd').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['id_razd'];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('id_stat').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['id_stat'];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('sum_smet').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['sum_smet'];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('name_smet').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['name_smet'];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('name_razd').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['name_razd'];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('name_stat').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['name_stat'];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('kod_smety').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['kod_smety'];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('n_razd').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['n_razd'];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('n_stat').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['n_stat'];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('id_kekv').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['id_kekv'];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('kod_kekv').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['kod_kekv'];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('name_kekv').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['name_kekv'];
TaxInvoicesEditDM.RxMemoryData_smet.Post;
TaxInvoicesEditDM.Smeta_Vid_N_DSet.Next;
if TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('n_stat').Value = '7300' then
sum_All_Nds := sum_All_Nds + TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('sum_smet').Value
else
sum_All_Not_NDS := sum_All_Not_NDS + TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('sum_smet').Value;
end;
if TaxInvoicesEditDM.VidNaklInfoDSet['pk_id']= null
then pk_id := 0
else pk_id := StrToInt64(TaxInvoicesEditDM.VidNaklInfoDSet.FieldByName('pk_id').AsString);
if ((pk_id = 0) or (pk_id = -1)) then
provodka := False
else
provodka := True;
PParameter.id_TaxLiabilities := TaxInvoicesEditDM.VidNaklInfoDSet['id_tax_liabilities'];
PParameter.Name_TaxLiabilities := TaxInvoicesEditDM.VidNaklInfoDSet['name_tax_liabilities'];
PParameter.Id_TaxKredit := TaxInvoicesEditDM.VidNaklInfoDSet['id_taxkredit'];
PParameter.Name_TaxKredit := TaxInvoicesEditDM.VidNaklInfoDSet['NAME_TAXKREDIT'];
PParameter.id_SpecialNotes := TaxInvoicesEditDM.VidNaklInfoDSet['id_specialnotes'];
PParameter.Name_SpecialNotes := TaxInvoicesEditDM.VidNaklInfoDSet['name_specialnotes'];
PParameter.id_customer := TaxInvoicesEditDM.VidNaklInfoDSet['id_customer'];
PParameter.Name_customer := TaxInvoicesEditDM.VidNaklInfoDSet['name_customer'];
PParameter.ipn_customer := TaxInvoicesEditDM.VidNaklInfoDSet['ipn_customer'];
PParameter.place_customer := TaxInvoicesEditDM.VidNaklInfoDSet['place_customer'];
PParameter.phone_customer := TaxInvoicesEditDM.VidNaklInfoDSet['phone_customer'];
PParameter.NumReestr_customer := TaxInvoicesEditDM.VidNaklInfoDSet['numreestr_customer'];
PParameter.EDRPOU_Customer := TaxInvoicesEditDM.VidNaklInfoDSet['edrpou_customer'];
PParameter.id_TermsDelivery := TaxInvoicesEditDM.VidNaklInfoDSet['id_termsdelivery'];
PParameter.Name_TermsDelivery := TaxInvoicesEditDM.VidNaklInfoDSet['name_termsdelivery'];
PParameter.id_FormCalculations := TaxInvoicesEditDM.VidNaklInfoDSet['id_formcalculations'];
PParameter.Name_FormCalculations := TaxInvoicesEditDM.VidNaklInfoDSet['name_formcalculations'];
PParameter.ID_TYPE_DOCUMENT := TaxInvoicesEditDM.VidNaklInfoDSet['id_type_document'];
PParameter.NAME_TYPE_DOCUMENT := TaxInvoicesEditDM.VidNaklInfoDSet['name_type_document'];
PParameter.Num_SpecialNotes := TaxInvoicesEditDM.VidNaklInfoDSet['Num_SpecialNotes'];
if (TaxInvoicesEditDM.VidNaklInfoDSet['full_name_customer']<>null) then
PParameter.Full_name_customer := TaxInvoicesEditDM.VidNaklInfoDSet['full_name_customer']
else
PParameter.Full_name_customer := '';
PParameter.id_vid_nakl_doc := -1;
PodNumTextEdit.Properties.ReadOnly := False;
NumOrderTextEdit.Properties.ReadOnly := False;
NumTermsDelTextEdit.Properties.ReadOnly := False;
PodNumTextEdit.Properties.ReadOnly := False;
DataVipDateEdit.Properties.ReadOnly := False;
DataTermsdelDateEdit.Properties.ReadOnly := False;
IPNPokupTextEdit.Properties.ReadOnly := False;
NotPDVCheckBox.Properties.ReadOnly := False;
//NoteTextEdit.Properties.ReadOnly := False;
PodZobButtonEdit.Style.Color := clWindow;
PodKreditButtonEdit.Style.Color := clWindow;
DataVipDateEdit.Style.Color := clWindow;
SpecialNotesButtonEdit.Style.Color := clWindow;
PostavkaButtonEdit.Style.Color := clWindow;
OsobaPokupButtonEdit.Style.Color := clWindow;
RozraxunokButtonEdit.Style.Color := clWindow;
PodNumTextEdit.Style.Color := clWindow;
NumOrderTextEdit.Style.Color := clWindow;
DataTermsdelDateEdit.Style.Color := clWindow;
NumTermsDelTextEdit.Style.Color := clWindow;
IPNPokupTextEdit.Style.Color := clWindow;
TypeDocumentButtonEdit.Style.Color := clWindow;
OznakaTextEdit.Style.Color := clWindow;
EditingButton.Visible := False;
AddButton.Enabled := False;
UpdateButton.Enabled := False;
DeleteButton.Enabled := False;
RefreshButton.Enabled := False;
BudgetButton.Enabled := False;
EditTaxButton.Enabled := False;
is_issued_buyer_CheckBox.Properties.ReadOnly := False;
is_erpn_CheckBox.Properties.ReadOnly := False;
is_issued_buyer_CheckBox.Properties.ReadOnly := False;
OsoblPrimCheckBox.Properties.ReadOnly := False;
is_copy_CheckBox.Properties.ReadOnly := False;
PostavkaCheckBox.Properties.ReadOnly := False;
RozraxunokCheckBox.Properties.ReadOnly := False;
PodZobCheckBox.Properties.ReadOnly := False;
PodKreditCheckBox.Properties.ReadOnly := False;
OznakaTextEdit.Properties.ReadOnly := false;
end;
//******************************************************************************
pStylesDM := TStyleDM.Create(Self);
NaklDeliveryGridDBBandedTableView.Styles.StyleSheet := pStylesDM.GridTableViewStyleSheetDevExpress;
NaklDeliveryGridDBBandedTableView.DataController.DataSource := TaxInvoicesEditDM.NaklDeliveryDSource;
//******************************************************************************
TaxInvoicesEditDM.Pocupatel_DataSet.Close;
TaxInvoicesEditDM.Pocupatel_DataSet.SelectSQL.Text := 'select * from Z_SETUP_S';
TaxInvoicesEditDM.Pocupatel_DataSet.Open;
//OsobaProdavecTextEdit.Text := TaxInvoicesEditDM.Pocupatel_DataSet['FIRM_NAME_FULL'];
//TelProdavecTextEdit.Text := TaxInvoicesEditDM.Pocupatel_DataSet['TELEFON'];
//PlaceProdavecTextEdit.Text := TaxInvoicesEditDM.Pocupatel_DataSet['TOWN']+', '+TaxInvoicesEditDM.Pocupatel_DataSet['ADDRESS'];
//PlaceProdavecTextEdit.Text := 'вул.Університетська, б.24, м.Донецьк, обл.Донецька, 83001';
id_university := TaxInvoicesEditDM.Customer_DonnuDSet['ID_UNIVERSITY'];
if (id_university = 2)then
begin
TelProdavecTextEdit.Style.color := clBtnFace;
TelProdavecTextEdit.Properties.ReadOnly := True; //для ХАИ
end
else
begin
TelProdavecTextEdit.Style.color := clWhite;
TelProdavecTextEdit.Properties.ReadOnly := False; //для ДонНУ
end;
NumReestrProdavecTextEdit.Text := TaxInvoicesEditDM.Customer_DonnuDSet['nns'];
IPNProdavecTextEdit.Text := TaxInvoicesEditDM.Customer_DonnuDSet['nalog_nom'];
id_Seller := TaxInvoicesEditDM.Customer_DonnuDSet['ORGANIZATION'];
PlaceProdavecTextEdit.Text := TaxInvoicesEditDM.Customer_DonnuDSet['full_adress_customer'];
OsobaProdavecTextEdit.Text := TaxInvoicesEditDM.Customer_DonnuDSet['full_name_customer'];
//TelProdavecTextEdit.Text := TaxInvoicesEditDM.Customer_DonnuDSet['phone_customer'];
end;
procedure TTaxInvoicesEditAddForm.AddButtonClick(Sender: TObject);
var
ViewForm : TTaxInvoicesEditAddInNaklForm;
id_vid_nakl_delivery : Integer;
AddParametr : TTITaxInvoicesAddVidNaklDelivery;
begin
AddParametr.id_range_of_delivery := 0;
AddParametr.Name_range_of_delivery := '';
AddParametr.Id_Measures := 0;
AddParametr.Name_Measures := '';
ViewForm := TTaxInvoicesEditAddInNaklForm.Create(Self,TaxInvoicesEditDM.DB.Handle,AddParametr);
ViewForm.MeasuresButtonEdit.Text := 'послуга';
ViewForm.DateShipmentLabel.Visible := True;
ViewForm.DateShipmentEdit.Visible := True;
ViewForm.RangeOfDeliveryLabel.Visible := True;
ViewForm.RangeOfDeliveryButtonEdit.Visible := True;
ViewForm.DataGroupBox.Visible := True;
ViewForm.MonthList.Items.Text := GetMonthList2;
ViewForm.Kod_Setup := CurrentKodSetup(PDb_Handle);
ViewForm.YearSpinEdit.Value := YearMonthFromKodSetup(ViewForm.Kod_Setup);
ViewForm.MonthList.ItemIndex := YearMonthFromKodSetup(ViewForm.Kod_Setup-1,False);
ViewForm.ZaCheckBox.Checked := False;
ViewForm.MonthList.Enabled := False;
ViewForm.YearSpinEdit.Enabled := False;
ViewForm.DateShipmentEdit.Text := '';
ViewForm.KolVoTextEdit.Text := '';
ViewForm.PriceCurrencyEdit.Text := '';
ViewForm.KodTovarButtonEdit.Text := '';
ViewForm.KodTovarCheckBox.Checked := False;
ViewForm.KodTovarButtonEdit.Enabled := False;
ViewForm.ValueDeliveryExportCurrencyEdit.EditValue := 0;
ViewForm.ValueDelivery20CurrencyEdit.EditValue := 0;
ViewForm.ValueDeliveryCustomsCurrencyEdit.EditValue := 0;
ViewForm.ValueDeliveryVATexemptionsCurrencyEdit.EditValue := 0;
ViewForm.ReadReg;
ViewForm.ShowModal;
if (ViewForm.ModalResult = mrok) then
begin
TaxInvoicesEditDM.WriteTransaction.StartTransaction;
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_SP_VID_NAKL_DELIVERY_INS';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('date_shipment').Value := ViewForm.DateShipmentEdit.Date;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_range_of_delivery').Value := ViewForm.Parameter.id_range_of_delivery;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('name_range_of_delivery').Value := ViewForm.Parameter.Name_range_of_delivery;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_measures').Value := ViewForm.Parameter.Id_Measures;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('name_measures').Value := ViewForm.MeasuresButtonEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('kol_vo_delivery_goods').Value := ViewForm.KolVoTextEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('price_delivery_goods').Value := ViewForm.PriceCurrencyEdit.Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('value_delivery_20').Value := ViewForm.ValueDelivery20CurrencyEdit.Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('value_delivery_export').Value := ViewForm.ValueDeliveryExportCurrencyEdit.Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('value_delivery_customs').Value := ViewForm.ValueDeliveryCustomsCurrencyEdit.Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('value_delivery_vat_exemption').Value := ViewForm.ValueDeliveryVATexemptionsCurrencyEdit.Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_vid_nakl_doc').Value := id_vid_nakl_doc_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('section').Value := '1';
if (ViewForm.KodTovarCheckBox.Checked = true) then
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_kod_tovar').Value := ViewForm.Parameter.id_kod_tovar;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('num_kod_tovar').Value := ViewForm.Parameter.Num_Kod_tovar;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('name_kod_tovar').Value := ViewForm.Parameter.Name_Kod_tovar;
end
else
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_kod_tovar').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('num_kod_tovar').Value := '';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('name_kod_tovar').Value := '';
end;
if (ViewForm.ZaCheckBox.Checked = true) then
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('MONTH_RANGE_OF_DELIVERY').Value := ViewForm.MonthList.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('YEAR_RANGE_OF_DELIVERY').Value := ViewForm.YearSpinEdit.Text;
end
else
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('MONTH_RANGE_OF_DELIVERY').Value := '';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('YEAR_RANGE_OF_DELIVERY').Value := '';
end;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
id_vid_nakl_delivery := TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_VID_NAKL_DELIVERY_').AsInteger;
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_VID_NAKL_DOC_SUMMA_CALC';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_VID_NAKL_DOC').Value := id_vid_nakl_doc_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.WriteTransaction.Commit;
RefreshButton.Click;
TaxInvoicesEditDM.NaklDeliveryDSet.Locate('ID_VID_NAKL_DELIVERY',IntToStr(id_vid_nakl_delivery),[]);
end;
end;
procedure TTaxInvoicesEditAddForm.SpecialNotesButtonEditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
Parameter:TTiSimpleParam;
notes:Variant;
begin
Parameter := TTiSimpleParam.Create;
Parameter.DB_Handle := TaxInvoicesEditDM.DB.Handle;
Parameter.Owner := self;
notes := DoFunctionFromPackage(Parameter,SpecialNotes_Const);
Parameter.Destroy;
If VarArrayDimCount(notes)>0 then
begin
PParameter.id_SpecialNotes := notes[0];
SpecialNotesButtonEdit.Text := notes[2];
PParameter.Name_SpecialNotes := notes[1];
PParameter.Num_SpecialNotes := notes[2];
{// отбор типа документа по типу причины
TaxInvoicesEditDM.WriteTransaction.StartTransaction;
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_SELECT_TYPE_DOC_SPECIALNOTES';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_SPECIALNOTES').Value := PParameter.id_SpecialNotes;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.WriteTransaction.Commit;
PParameter.ID_TYPE_DOCUMENT := TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_TYPE_DOC').Value;
PParameter.NAME_TYPE_DOCUMENT := TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_TYPE_DOC').Value;
TypeDocumentButtonEdit.Text := TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_TYPE_DOC').Value;}
end;
end;
procedure TTaxInvoicesEditAddForm.PostavkaButtonEditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
Parameter:TTiSimpleParam;
terms:Variant;
begin
Parameter := TTiSimpleParam.Create;
Parameter.DB_Handle := TaxInvoicesEditDM.DB.Handle;
Parameter.Owner := self;
terms := DoFunctionFromPackage(Parameter,TermsDelivery_Const);
Parameter.Destroy;
If VarArrayDimCount(terms)>0 then
begin
PostavkaButtonEdit.Text := terms[1];
PParameter.id_TermsDelivery := terms[0];
PParameter.Name_TermsDelivery := terms[1];
end;
end;
procedure TTaxInvoicesEditAddForm.RozraxunokButtonEditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
Parameter:TTiSimpleParam;
fCalc:Variant;
begin
Parameter := TTiSimpleParam.Create;
Parameter.DB_Handle := TaxInvoicesEditDM.DB.Handle;
Parameter.Owner := self;
fCalc := DoFunctionFromPackage(Parameter,FormCalculations_Const);
Parameter.Destroy;
If VarArrayDimCount(fCalc)>0 then
begin
RozraxunokButtonEdit.Text := fCalc[1];
PParameter.id_FormCalculations := fCalc[0];
PParameter.Name_FormCalculations := fCalc[1];
end;
end;
procedure TTaxInvoicesEditAddForm.OsobaPokupButtonEditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
i, o : TSpravParams;
begin
i := TSpravParams.Create;
o := TSpravParams.Create;
i['DataBase'] := Integer(TaxInvoicesEditDM.DB.Handle);
i['FormStyle'] := fsNormal;
i['bMultiSelect'] := false;
i['id_session'] := -1;
i['SelectMode'] := selCustomer;
i['id_cistomer'] := -1;
i['show_all'] := 1;
LoadSysData(TaxInvoicesEditDM.ReadTransaction);
DogLoaderUnit.LoadSprav('Customer\CustPackage.bpl', Self, i, o);
if o['ModalResult'] = mrOk then
begin
id_Customer := o['ID_CUSTOMER'];
TaxInvoicesEditDM.Customer_DataSet.Close;
TaxInvoicesEditDM.Customer_DataSet.SelectSQL.Text :='select * from TI_CUSTOMER_INFO(:id)';
TaxInvoicesEditDM.Customer_DataSet.ParamByName('id').Value := id_Customer;
TaxInvoicesEditDM.Customer_DataSet.Open;
OsobaPokupButtonEdit.Text := TaxInvoicesEditDM.Customer_DataSet['NAME_CUSTOMER'];
PlacePokupMemo.Text := TaxInvoicesEditDM.Customer_DataSet['ADRESS_CONTRAGENT'];
EdrpTextEdit.Text := TaxInvoicesEditDM.Customer_DataSet['KOD_EDRPOU'];
IPNPokupTextEdit.Text := TaxInvoicesEditDM.Customer_DataSet['NALOG_NOM'];
NumReestrPokupTextEdit.Text := TaxInvoicesEditDM.Customer_DataSet['NNS'];
if (TaxInvoicesEditDM.Customer_DataSet['PHONE_CUSTOMER']<>null)then
TelPokupTextEdit.Text := TaxInvoicesEditDM.Customer_DataSet['PHONE_CUSTOMER']
else
TelPokupTextEdit.Text :='---';
PParameter.id_customer := id_Customer;
PParameter.Name_customer := TaxInvoicesEditDM.Customer_DataSet['NAME_CUSTOMER'];
PParameter.ipn_customer := TaxInvoicesEditDM.Customer_DataSet['NALOG_NOM'];
PParameter.place_customer := TaxInvoicesEditDM.Customer_DataSet['ADRESS_CONTRAGENT'];
PParameter.phone_customer := TaxInvoicesEditDM.Customer_DataSet['PHONE_CUSTOMER'];
PParameter.NumReestr_customer := TaxInvoicesEditDM.Customer_DataSet['NNS'];
PParameter.EDRPOU_Customer := TaxInvoicesEditDM.Customer_DataSet['KOD_EDRPOU'];
if ((TaxInvoicesEditDM.Customer_DataSet['full_name_customer'] = '') or (TaxInvoicesEditDM.Customer_DataSet['full_name_customer']=null))then
begin
replaceAbreviatures(TaxInvoicesEditDM.Customer_DataSet['NAME_CUSTOMER']);
PParameter.Full_name_customer := '';
FullNameCheckBox.Checked := True;
FullNameMemo.ReadOnly := False;
SaveFullNameButton.Visible := True;
end
else
begin
FullNameMemo.Text := TaxInvoicesEditDM.Customer_DataSet['full_name_customer'];
PParameter.Full_name_customer := TaxInvoicesEditDM.Customer_DataSet['full_name_customer'];
FullNameCheckBox.Checked := False;
FullNameMemo.ReadOnly := True;
SaveFullNameButton.Visible := False;
end;
if ((TaxInvoicesEditDM.Customer_DataSet['full_adress_customer'] = '') or (TaxInvoicesEditDM.Customer_DataSet['full_adress_customer']=null))then
begin
PlacePokupMemo.Text := TaxInvoicesEditDM.Customer_DataSet['adress_contragent'];
PParameter.place_customer := '';
PlacePokupCheckBox.Checked := True;
PlacePokupMemo.Properties.ReadOnly := False;
SavePlacePokupButton.Visible := True;
end
else
begin
PlacePokupMemo.Text := TaxInvoicesEditDM.Customer_DataSet['full_adress_customer'];
PParameter.place_customer := TaxInvoicesEditDM.Customer_DataSet['full_adress_customer'];
PlacePokupCheckBox.Checked := False;
PlacePokupMemo.Properties.ReadOnly := True;
SavePlacePokupButton.Visible := False;
end;
end;
i.Free;
o.Free;
end;
procedure TTaxInvoicesEditAddForm.IPNPokupButtonEditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
i, o : TSpravParams;
begin
i := TSpravParams.Create;
o := TSpravParams.Create;
i['DataBase'] := Integer(TaxInvoicesEditDM.DB.Handle);
i['FormStyle'] := fsNormal;
i['bMultiSelect'] := false;
i['id_session'] := -1;
i['SelectMode'] := selRateAccount;
i['show_all'] := 1;
DogLoaderUnit.LoadSprav('Customer\CustPackage.bpl', Self, i, o);
i.Free;
o.Free;
end;
procedure TTaxInvoicesEditAddForm.PlacePokupButtonEditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
i, o : TSpravParams;
begin
i := TSpravParams.Create;
o := TSpravParams.Create;
i['DataBase'] := Integer(TaxInvoicesEditDM.DB.Handle);
i['FormStyle'] := fsNormal;
i['bMultiSelect'] := false;
i['id_session'] := -1;
i['SelectMode'] := selRateAccount;
i['show_all'] := 1;
DogLoaderUnit.LoadSprav('Customer\CustPackage.bpl', Self, i, o);
i.Free;
o.Free;
end;
procedure TTaxInvoicesEditAddForm.TelPokupButtonEditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
i, o : TSpravParams;
begin
i := TSpravParams.Create;
o := TSpravParams.Create;
i['DataBase'] := Integer(TaxInvoicesEditDM.DB.Handle);
i['FormStyle'] := fsNormal;
i['bMultiSelect'] := false;
i['id_session'] := -1;
i['SelectMode'] := selRateAccount;
i['show_all'] := 1;
DogLoaderUnit.LoadSprav('Customer\CustPackage.bpl', Self, i, o);
i.Free;
o.Free;
end;
procedure TTaxInvoicesEditAddForm.NumReestrPokupButtonEditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
Parameter:TTiSimpleParam;
terms:Variant;
begin
Parameter := TTiSimpleParam.Create;
Parameter.DB_Handle := TaxInvoicesEditDM.DB.Handle;
Parameter.Owner := self;
terms := DoFunctionFromPackage(Parameter,RangeOfDelivery_Const);
Parameter.Destroy;
If VarArrayDimCount(terms)>0 then
begin
PostavkaButtonEdit.Text := terms[1];
end;
end;
procedure TTaxInvoicesEditAddForm.EdrpButtonEditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
i, o : TSpravParams;
begin
i := TSpravParams.Create;
o := TSpravParams.Create;
i['DataBase'] := Integer(TaxInvoicesEditDM.DB.Handle);
i['FormStyle'] := fsNormal;
i['bMultiSelect'] := false;
i['id_session'] := -1;
i['SelectMode'] := selRateAccount;
i['show_all'] := 1;
DogLoaderUnit.LoadSprav('Customer\CustPackage.bpl', Self, i, o);
i.Free;
o.Free;
end;
procedure TTaxInvoicesEditAddForm.NumReestrProdavecButtonEditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
LoadTypeDocumentPackage(owner,TaxInvoicesEditDM.DB.Handle,'TaxInvoices\TypeDocument.bpl','View_TypeDocument',1);
end;
procedure TTaxInvoicesEditAddForm.PodKreditButtonEditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
Parameter:TTiSimpleParam;
kredit:Variant;
begin
Parameter := TTiSimpleParam.Create;
Parameter.DB_Handle := TaxInvoicesEditDM.DB.Handle;
Parameter.Owner := self;
kredit := DoFunctionFromPackage(Parameter,TaxKredit_Const);
Parameter.Destroy;
If VarArrayDimCount(kredit)>0 then
begin
PParameter.Id_TaxKredit := kredit[0];
PParameter.Name_TaxKredit := kredit[1];
PodKreditButtonEdit.Text := kredit[2];
end;
end;
procedure TTaxInvoicesEditAddForm.PodZobButtonEditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
Parameter:TTiSimpleParam;
PodZob:Variant;
begin
Parameter := TTiSimpleParam.Create;
Parameter.DB_Handle := TaxInvoicesEditDM.DB.Handle;
Parameter.Owner := self;
PodZob := DoFunctionFromPackage(Parameter,TaxLiabilities_Const);
Parameter.Destroy;
If VarArrayDimCount(PodZob)>0 then
begin
PParameter.id_TaxLiabilities := PodZob[0];
PParameter.Name_TaxLiabilities := PodZob[1];
PodZobButtonEdit.Text := PodZob[2];
end;
end;
procedure TTaxInvoicesEditAddForm.CancelButtonClick(Sender: TObject);
begin
close;
end;
procedure TTaxInvoicesEditAddForm.YesButtonClick(Sender: TObject);
var
error_period : string;
oznaka : string;
begin
if (DataVipDateEdit.Text='') then
begin
TiShowMessage('Увага!','Заповніть дату виписки!',mtWarning,[mbOK]);
DataVipDateEdit.SetFocus;
Exit;
end;
//проверка на корректность даты согласно реестра
TaxInvoicesEditDM.WriteTransaction.StartTransaction;
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_DATE_NAKL_IS_KORRECT';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_reestr').Value := id_Reestr_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('date_nakl').Value := DataVipDateEdit.Date;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.WriteTransaction.Commit;
if (TaxInvoicesEditDM.pFIBStoredProc.ParamByName('is_korrect').Value = 0) then
begin
error_period := 'Дата податкової накладної не може виходити за період реєстру! Період: з ' + TaxInvoicesEditDM.pFIBStoredProc.ParamByName('date_beg').AsString + 'по ' + TaxInvoicesEditDM.pFIBStoredProc.ParamByName('date_end').AsString;
TiShowMessage('Увага!', error_period, mtWarning,[mbOK]);
DataVipDateEdit.SetFocus;
Exit;
end;
if (PodZobButtonEdit.Enabled = True) then
begin
if (PodZobButtonEdit.Text='') then
begin
TiShowMessage('Увага!','Заповніть податкові зобов язання!',mtWarning,[mbOK]);
PodZobButtonEdit.SetFocus;
Exit;
end;
end;
if (PodKreditButtonEdit.Enabled = True) then
begin
if (PodKreditButtonEdit.Text='') then
begin
TiShowMessage('Увага!','Заповніть податковий кредит!',mtWarning,[mbOK]);
PodKreditButtonEdit.SetFocus;
Exit;
end;
end;
if (PostavkaCheckBox.Checked)then
begin
if (PostavkaButtonEdit.Text='') then
begin
TiShowMessage('Увага!','Заповніть умови поставки!',mtWarning,[mbOK]);
PostavkaButtonEdit.SetFocus;
Exit;
end;
end;
if (RozraxunokCheckBox.Checked)then
begin
if (RozraxunokButtonEdit.Text='') then
begin
TiShowMessage('Увага!','Заповніть форму проведених розрахунків!',mtWarning,[mbOK]);
RozraxunokButtonEdit.SetFocus;
Exit;
end;
end;
if (SpecialNotesButtonEdit.Enabled = True) then
begin
if (SpecialNotesButtonEdit.Text='') then
begin
TiShowMessage('Увага!','Заповніть особливі примітки!',mtWarning,[mbOK]);
SpecialNotesButtonEdit.SetFocus;
Exit;
end;
end;
if (PodNumTextEdit.Text='') then
begin
TiShowMessage('Увага!','Заповніть порядковий номер!',mtWarning,[mbOK]);
PodNumTextEdit.SetFocus;
Exit;
end;
if (OsobaPokupButtonEdit.Text='') then
begin
TiShowMessage('Увага!','Заповніть покупця!',mtWarning,[mbOK]);
OsobaPokupButtonEdit.SetFocus;
Exit;
end;
if (FullNameMemo.Text='') then
begin
TiShowMessage('Увага!','Заповніть повну назву покупця!',mtWarning,[mbOK]);
FullNameMemo.SetFocus;
Exit;
end;
if (PhoneCheckBox.Checked = True)then
begin
if (TelPokupTextEdit.Text='') then
begin
TiShowMessage('Увага!','Заповніть номер телефону або зніміть редагування номера телефону!',mtWarning,[mbOK]);
TelPokupTextEdit.SetFocus;
Exit;
end;
end;
if (NoteCheckBox.Checked = True)then
begin
if (NoteButtonEdit.Text='') then
begin
TiShowMessage('Увага!','Заповніть примітку под. накладної або зніміть галочку!',mtWarning,[mbOK]);
NoteButtonEdit.SetFocus;
Exit;
end;
end;
if (FullNameCheckBox.Checked = True)then
begin
TiShowMessage('Увага!','Заповніть повну назву контрагента або зніміть редагування повної назви контрагента!',mtWarning,[mbOK]);
FullNameMemo.SetFocus;
Exit;
end;
if (PlacePokupCheckBox.Checked = True)then
begin
TiShowMessage('Увага!','Заповніть повну адресу контрагента або зніміть редагування повної адреси контрагента!',mtWarning,[mbOK]);
PlacePokupMemo.SetFocus;
Exit;
end;
if (TypeDocumentButtonEdit.Text='') then
begin
TiShowMessage('Увага!','Заповніть тип документу!',mtWarning,[mbOK]);
TypeDocumentButtonEdit.SetFocus;
Exit;
end;
if (OznakaCheckBox.Checked = True) then
begin
if (OznakaTextEdit.Text='') then
begin
TiShowMessage('Увага!','Заповніть ознаку або зніміть галочку!',mtWarning,[mbOK]);
OznakaTextEdit.SetFocus;
Exit;
end;
oznaka := Trim(OznakaTextEdit.Text);
if (Length(oznaka) <> 1) then
begin
TiShowMessage('Увага!','Невірно заповнена ознака, вона повинна складатися з 1 літери!',mtWarning,[mbOK]);
OznakaTextEdit.SetFocus;
Exit;
end;
end;
try
if (id_vid_nakl_doc_Ins = -1) then // вставка новой налоговой накладной
begin
if (PParameter.Full_name_customer = '') then
begin
TiShowMessage('Увага!','Збережіть повну назву контрагента!',mtWarning,[mbOK]);
Exit;
end;
if (PParameter.place_customer = '') then
begin
TiShowMessage('Увага!','Збережіть повну адресу контрагента!',mtWarning,[mbOK]);
Exit;
end;
//ReadReg;
TaxInvoicesEditDM.WriteTransaction.StartTransaction;
//вставка самого документа
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_SP_VID_NAKL_DOC_INS';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('data_vipiski').AsDate := DataVipDateEdit.Date;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NUM_NAKL').Value := PodNumTextEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_SELLER').Value := id_Seller;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_SELLER').Value := OsobaProdavecTextEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ipn_seller').Value := IPNProdavecTextEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('PLACE_SELLER').Value := PlaceProdavecTextEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('PHONE_SELLER').Value := TelProdavecTextEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NUMREESTR_SELLER').Value := NumReestrProdavecTextEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_CUSTOMER').Value := PParameter.Id_Customer;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_CUSTOMER').Value := PParameter.Name_Customer;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IPN_CUSTOMER').Value := PParameter.ipn_customer;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('PLACE_CUSTOMER').Value := PParameter.place_customer;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('PHONE_CUSTOMER').Value := PParameter.phone_customer;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NUMREESTR_CUSTOMER').Value := PParameter.NumReestr_customer;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('EDRPOU_CUSTOMER').Value := PParameter.EDRPOU_Customer;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('full_name_customer').Value := PParameter.Full_name_customer;
//TaxInvoicesEditDM.pFIBStoredProc.ParamByName('note').Value := NoteButtonEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('is_issued_buyer_two_ekz').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('is_erpn_two_ekz').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('is_remains_seller_two_ekz').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('is_copy_two_ekz').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_specialnotes_two_ekz').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('name_specialnotes_two_ekz').Value := '';
if (is_issued_buyer_CheckBox.Checked = true) then
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('is_issued_buyer').Value := 1
else
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('is_issued_buyer').Value := 0;
if (is_erpn_CheckBox.Checked = true) then
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('is_erpn').Value := 1
else
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('is_erpn').Value := 0;
if (is_copy_CheckBox.Checked = true) then
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('is_copy').Value := 1
else
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('is_copy').Value := 0;
if (OsoblPrimCheckBox.Checked = true) then
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IS_REMAINS_SELLER').Value := 1
else
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IS_REMAINS_SELLER').Value := 0;
if (NotPDVCheckBox.Checked = true) then
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IS_NOT_PDV').Value := 1
else
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IS_NOT_PDV').Value := 0;
if (PostavkaCheckBox.Checked=True)then
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_TERMSDELIVERY').Value := PParameter.id_TermsDelivery;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_TERMSDELIVERY').Value := PParameter.Name_TermsDelivery;
if (DataTermsdelDateEdit.Text='') then
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('data_termsdelivery').Value := StrtoDate('01.01.1900')
else
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('data_termsdelivery').Value := DataTermsdelDateEdit.Date ;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('num_termsdelivery').Value := NumTermsDelTextEdit.Text;
end
else
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_TERMSDELIVERY').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_TERMSDELIVERY').Value := '';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('data_termsdelivery').Value := StrtoDate('01.01.1900');
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('num_termsdelivery').Value := '';
end;
if (RozraxunokCheckBox.Checked=True)then
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_FORMCALCULATIONS').Value := PParameter.id_FormCalculations;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_FORMCALCULATIONS').Value := PParameter.Name_FormCalculations;
end
else
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_FORMCALCULATIONS').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_FORMCALCULATIONS').Value := '';
end;
if (NoteCheckBox.Checked=True)then
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_NOTE').Value := PParameter.id_note;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NOTE').Value := PParameter.article_note;
end
else
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_NOTE').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NOTE').Value := '';
end;
if (PodZobCheckBox.Checked)then
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_tax_liabilities').Value := PParameter.id_TaxLiabilities;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_TAX_LIABILITIES').Value := PParameter.Name_TaxLiabilities;
end
else
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_tax_liabilities').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_TAX_LIABILITIES').Value := '';
end;
if (PodKreditCheckBox.Checked)then
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_TAXKREDIT').Value := PParameter.Id_TaxKredit;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_TAXKREDIT').Value := PParameter.Name_TaxKredit;
end
else
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_TAXKREDIT').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_TAXKREDIT').Value := '';
end;
if (OsoblPrimCheckBox.Checked)then
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_SPECIALNOTES').Value := PParameter.id_SpecialNotes;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_SPECIALNOTES').Value := PParameter.Name_SpecialNotes;
end
else
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_SPECIALNOTES').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_SPECIALNOTES').Value := '';
end;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('is_korig').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NUM_ROZR').Value := '';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('DATE_ROZR').Value := StrtoDate('01.01.1900');
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('DATE_PODPIS_KORIG').Value := StrtoDate('01.01.1900');
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
id_vid_nakl_doc_Ins := TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_VID_NAKL_DOC_').Value;
//вставка документа в список выданных налоговых накладных
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_SP_VID_NAKL_INS';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('data_vipiski').AsDate := DataVipDateEdit.Date;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NUM_NAKL').Value := PodNumTextEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NUM_ORDER').Value := NumOrderTextEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_TYPE_DOCUMENT').Value := PParameter.ID_TYPE_DOCUMENT;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_TYPE_DOCUMENT').Value := PParameter.NAME_TYPE_DOCUMENT;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_TAXLIABILITIES').Value := PParameter.id_TaxLiabilities;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_TAXLIABILITIES').Value := PParameter.Name_TaxLiabilities;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_CUSTOMER').Value := PParameter.Id_Customer;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_CUSTOMER').Value := PParameter.Full_name_customer;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IPN_CUSTOMER').Value := PParameter.ipn_customer;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('SUMMA_PDV_20').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('SUMMA_TAXABLE_20').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('SUMMA_TAXABLE_0').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('SUMMA_EXEMPT').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('SUMMA_EXPORT').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IS_KORIG').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IS_EXPANSION').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IS_SIGN').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_REESTR').Value := id_Reestr_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_NAKL_DOCUMENT').Value := id_vid_nakl_doc_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_USER_CREATE').Value := TaxInvoicesUser.id_user;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_USER_CREATE').Value := TaxInvoicesUser.name_user;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('date_time_create').Value := Now;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IS_IMPORT').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_SYSTEM').Value := '';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_SCHET_IMPORT').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('pk_id').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_subdivision').Value := 1;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_LGOTA').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_LGOTA').Value := '';
if (OsoblPrimCheckBox.Checked = true) then
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_SPECIALNOTES').Value := Pparameter.id_specialNotes;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NUM_SPECIALNOTES').Value := Pparameter.Num_specialnotes;
end
else
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_SPECIALNOTES').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NUM_SPECIALNOTES').Value := '';
end;
if (OznakaCheckBox.Checked = true) then
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('OZNAKA_NAKL').Value := OznakaTextEdit.Text;
end
else
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('OZNAKA_NAKL').Value := '';
end;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('SUMMA_DELIVERY').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
id_vid_nakl_Ins := TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_VID_NAKL_').Value;
PParameter.id_vid_nakl_doc := id_vid_nakl_Ins;
PRes.id_vid_nakl_doc := id_vid_nakl_Ins;
PodZobButtonEdit.Properties.onButtonClick := nil;
PodKreditButtonEdit.Properties.onButtonClick := nil;
DataVipDateEdit.Properties.ReadOnly := True;
SpecialNotesButtonEdit.Properties.onButtonClick := nil;
PostavkaButtonEdit.Properties.onButtonClick := nil;
OsobaPokupButtonEdit.Properties.onButtonClick := nil;
RozraxunokButtonEdit.Properties.onButtonClick := nil;
TypeDocumentButtonEdit.Properties.onButtonClick := nil;
PodNumTextEdit.Properties.ReadOnly := True;
NumOrderTextEdit.Properties.ReadOnly := True;
NumTermsDelTextEdit.Properties.ReadOnly := True;
PodNumTextEdit.Properties.ReadOnly := True;
DataVipDateEdit.Properties.ReadOnly := True;
DataTermsdelDateEdit.Properties.ReadOnly := True;
IPNPokupTextEdit.Properties.ReadOnly := True;
//NoteTextEdit.Properties.ReadOnly := True;
NoteCheckBox.Properties.ReadOnly := True;
NoteButtonEdit.Enabled := False;
NotPDVCheckBox.Properties.ReadOnly := True;
PodZobButtonEdit.Style.Color := clBtnFace;
PodKreditButtonEdit.Style.Color := clBtnFace;
DataVipDateEdit.Style.Color := clBtnFace;
SpecialNotesButtonEdit.Style.Color := clBtnFace;
PostavkaButtonEdit.Style.Color := clBtnFace;
OsobaPokupButtonEdit.Style.Color := clBtnFace;
RozraxunokButtonEdit.Style.Color := clBtnFace;
PodNumTextEdit.Style.Color := clBtnFace;
NumOrderTextEdit.Style.Color := clBtnFace;
DataTermsdelDateEdit.Style.Color := clBtnFace;
NumTermsDelTextEdit.Style.Color := clBtnFace;
IPNPokupTextEdit.Style.Color := clBtnFace;
TypeDocumentButtonEdit.Style.Color := clBtnFace;
is_issued_buyer_CheckBox.Properties.ReadOnly := True;
is_erpn_CheckBox.Properties.ReadOnly := True;
is_issued_buyer_CheckBox.Properties.ReadOnly := True;
OsoblPrimCheckBox.Properties.ReadOnly := True;
is_copy_CheckBox.Properties.ReadOnly := True;
PostavkaCheckBox.Properties.ReadOnly := True;
RozraxunokCheckBox.Properties.ReadOnly := True;
PodZobCheckBox.Properties.ReadOnly := True;
PodKreditCheckBox.Properties.ReadOnly := True;
EditingButton.Visible := True;
AddButton.Enabled := True;
UpdateButton.Enabled := True;
DeleteButton.Enabled := True;
RefreshButton.Enabled := True;
YesButton.Visible := False;
BudgetButton.Enabled := True;
EditTaxButton.Enabled := True;
TaxInvoicesEditDM.WriteTransaction.Commit;
TiShowMessage('Увага!','Документ додано.',mtWarning,[mbOK]);
end
else
begin
TaxInvoicesEditDM.WriteTransaction.StartTransaction;
//изменение документа
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_SP_VID_NAKL_DOC_UPD';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_vid_nakl_doc').Value := id_vid_nakl_doc_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('data_vipiski').Value := DataVipDateEdit.Date;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NUM_NAKL').Value := PodNumTextEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_SELLER').Value := id_Seller;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_SELLER').Value := OsobaProdavecTextEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ipn_seller').Value := IPNProdavecTextEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('PLACE_SELLER').Value := PlaceProdavecTextEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('PHONE_SELLER').Value := TelProdavecTextEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NUMREESTR_SELLER').Value := NumReestrProdavecTextEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_CUSTOMER').Value := PParameter.Id_Customer;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_CUSTOMER').Value := PParameter.Name_Customer;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IPN_CUSTOMER').Value := PParameter.ipn_customer;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('PLACE_CUSTOMER').Value := PParameter.place_customer;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('PHONE_CUSTOMER').Value := PParameter.phone_customer;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NUMREESTR_CUSTOMER').Value := PParameter.NumReestr_customer;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('EDRPOU_CUSTOMER').Value := PParameter.EDRPOU_Customer;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_TERMSDELIVERY').Value := PParameter.id_TermsDelivery;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_TERMSDELIVERY').Value := PParameter.Name_TermsDelivery;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('data_termsdelivery').Value := DataTermsdelDateEdit.Date;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('num_termsdelivery').Value := NumTermsDelTextEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_FORMCALCULATIONS').Value := PParameter.id_FormCalculations;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_FORMCALCULATIONS').Value := PParameter.Name_FormCalculations;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('full_name_customer').Value := PParameter.Full_name_customer;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('num_rozr').Value := '';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('date_rozr').Value := StrToDate('01.01.1900');
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('DATE_PODPIS_KORIG').Value := StrToDate('01.01.1900');
//TaxInvoicesEditDM.pFIBStoredProc.ParamByName('note').Value := NoteTextEdit.Text;
if (NoteCheckBox.Checked=True)then
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_NOTE').Value := PParameter.id_note;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NOTE').Value := PParameter.article_note;
end
else
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_NOTE').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NOTE').Value := '';
end;
if (is_issued_buyer_CheckBox.Checked = true) then
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('is_issued_buyer').Value := 1
else
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('is_issued_buyer').Value := 0;
if (is_erpn_CheckBox.Checked = true) then
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('is_erpn').Value := 1
else
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('is_erpn').Value := 0;
if (is_copy_CheckBox.Checked = true) then
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('is_copy').Value := 1
else
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('is_copy').Value := 0;
if (OsoblPrimCheckBox.Checked = true) then
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IS_REMAINS_SELLER').Value := 1
else
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IS_REMAINS_SELLER').Value := 0;
if (NotPDVCheckBox.Checked = true) then
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IS_NOT_PDV').Value := 1
else
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IS_NOT_PDV').Value := 0;
if (PostavkaCheckBox.Checked=True)then
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_TERMSDELIVERY').Value := PParameter.id_TermsDelivery;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_TERMSDELIVERY').Value := PParameter.Name_TermsDelivery;
if (DataTermsdelDateEdit.Text='') then
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('data_termsdelivery').Value := Strtodate('01.01.1900')
else
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('data_termsdelivery').Value := DataTermsdelDateEdit.Date ;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('num_termsdelivery').Value := NumTermsDelTextEdit.Text;
end
else
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_TERMSDELIVERY').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_TERMSDELIVERY').Value := '';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('data_termsdelivery').Value := Strtodate('01.01.1900');
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('num_termsdelivery').Value := '';
end;
if (RozraxunokCheckBox.Checked=True)then
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_FORMCALCULATIONS').Value := PParameter.id_FormCalculations;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_FORMCALCULATIONS').Value := PParameter.Name_FormCalculations;
end
else
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_FORMCALCULATIONS').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_FORMCALCULATIONS').Value := '';
end;
if (PodZobCheckBox.Checked)then
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_tax_liabilities').Value := PParameter.id_TaxLiabilities;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_TAX_LIABILITIES').Value := PParameter.Name_TaxLiabilities;
end
else
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_tax_liabilities').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_TAX_LIABILITIES').Value := '';
end;
if (PodKreditCheckBox.Checked)then
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_TAXKREDIT').Value := PParameter.Id_TaxKredit;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_TAXKREDIT').Value := PParameter.Name_TaxKredit;
end
else
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_TAXKREDIT').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_TAXKREDIT').Value := '';
end;
if (OsoblPrimCheckBox.Checked)then
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_SPECIALNOTES').Value := PParameter.id_SpecialNotes;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_SPECIALNOTES').Value := PParameter.Name_SpecialNotes;
end
else
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_SPECIALNOTES').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_SPECIALNOTES').Value := '';
end;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
//изменение документа в списке выданных налоговых накладных
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_SP_VID_NAKL_UPD';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_VID_NAKL').Value := id_vid_nakl_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('data_vipiski').Value := DataVipDateEdit.Date;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NUM_NAKL').Value := PodNumTextEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NUM_ORDER').Value := NumOrderTextEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_TYPE_DOCUMENT').Value := PParameter.ID_TYPE_DOCUMENT;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_TYPE_DOCUMENT').Value := PParameter.NAME_TYPE_DOCUMENT;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_TAXLIABILITIES').Value := PParameter.id_TaxLiabilities;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_TAXLIABILITIES').Value := PParameter.Name_TaxLiabilities;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_CUSTOMER').Value := PParameter.Id_Customer;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_CUSTOMER').Value := PParameter.Full_name_customer;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IPN_CUSTOMER').Value := PParameter.ipn_customer;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('SUMMA_PDV_20').Value := null;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('SUMMA_TAXABLE_20').Value := null;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('SUMMA_TAXABLE_0').Value := null;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('SUMMA_EXEMPT').Value := null;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('SUMMA_EXPORT').Value := null;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IS_KORIG').Value := null;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IS_EXPANSION').Value := null;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IS_SIGN').Value := null;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_REESTR').Value := id_Reestr_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IS_CHANGE').Value := 1;// изменение документа в справочнике выд. накл. (номер, дата, под. обязат., покупатель)
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_NAKL_DOCUMENT').Value := id_vid_nakl_doc_Ins;
if (OsoblPrimCheckBox.Checked = true) then
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_SPECIALNOTES').Value := Pparameter.id_specialNotes;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NUM_SPECIALNOTES').Value := Pparameter.Num_specialnotes;
end
else
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_SPECIALNOTES').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NUM_SPECIALNOTES').Value := '';
end;
if (OznakaCheckBox.Checked = true) then
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('OZNAKA_NAKL').Value := OznakaTextEdit.Text;
end
else
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('OZNAKA_NAKL').Value := '';
end;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('SUMMA_DELIVERY').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
PodZobButtonEdit.Properties.onButtonClick := nil;
PodKreditButtonEdit.Properties.onButtonClick := nil;
DataVipDateEdit.Properties.ReadOnly := True;
SpecialNotesButtonEdit.Properties.onButtonClick := nil;
PostavkaButtonEdit.Properties.onButtonClick := nil;
OsobaPokupButtonEdit.Properties.onButtonClick := nil;
RozraxunokButtonEdit.Properties.onButtonClick := nil;
TypeDocumentButtonEdit.Properties.onButtonClick := nil;
PodZobButtonEdit.Style.Color := clBtnFace;
PodKreditButtonEdit.Style.Color := clBtnFace;
DataVipDateEdit.Style.Color := clBtnFace;
SpecialNotesButtonEdit.Style.Color := clBtnFace;
PostavkaButtonEdit.Style.Color := clBtnFace;
OsobaPokupButtonEdit.Style.Color := clBtnFace;
RozraxunokButtonEdit.Style.Color := clBtnFace;
PodNumTextEdit.Style.Color := clBtnFace;
NumOrderTextEdit.Style.Color := clBtnFace;
DataTermsdelDateEdit.Style.Color := clBtnFace;
NumTermsDelTextEdit.Style.Color := clBtnFace;
TypeDocumentButtonEdit.Style.Color := clBtnFace;
EditingButton.Visible := True;
AddButton.Enabled := True;
UpdateButton.Enabled := True;
DeleteButton.Enabled := True;
RefreshButton.Enabled := True;
YesButton.Visible := False;
BudgetButton.Enabled := True;
EditTaxButton.Enabled := True;
is_issued_buyer_CheckBox.Properties.ReadOnly := True;
is_erpn_CheckBox.Properties.ReadOnly := True;
is_issued_buyer_CheckBox.Properties.ReadOnly := True;
OsoblPrimCheckBox.Properties.ReadOnly := True;
is_copy_CheckBox.Properties.ReadOnly := True;
PostavkaCheckBox.Properties.ReadOnly := True;
RozraxunokCheckBox.Properties.ReadOnly := True;
PodZobCheckBox.Properties.ReadOnly := True;
PodKreditCheckBox.Properties.ReadOnly := True;
//NoteTextEdit.Properties.ReadOnly := True;
NotPDVCheckBox.Properties.ReadOnly := True;
NoteCheckBox.Properties.ReadOnly := True;
NoteButtonEdit.Enabled := False;
TaxInvoicesEditDM.WriteTransaction.Commit;
TiShowMessage('Увага!','Документ змінено.',mtWarning,[mbOK]);
end;
except
begin
TiShowMessage('Увага!','Виникла помилка!',mtError,[mbOK]);
TaxInvoicesEditDM.WriteTransaction.Rollback;
PodZobButtonEdit.Properties.onButtonClick := PodZobButtonEditPropertiesButtonClick;
PodKreditButtonEdit.Properties.onButtonClick := PodKreditButtonEditPropertiesButtonClick;
DataVipDateEdit.Properties.ReadOnly := False;
SpecialNotesButtonEdit.Properties.onButtonClick := SpecialNotesButtonEditPropertiesButtonClick;
PostavkaButtonEdit.Properties.onButtonClick := PostavkaButtonEditPropertiesButtonClick;
OsobaPokupButtonEdit.Properties.onButtonClick := OsobaPokupButtonEditPropertiesButtonClick;
RozraxunokButtonEdit.Properties.onButtonClick := RozraxunokButtonEditPropertiesButtonClick;
TypeDocumentButtonEdit.Properties.onButtonClick := TypeDocumentButtonEditPropertiesButtonClick;
PodZobButtonEdit.Style.Color := clWindow;
PodKreditButtonEdit.Style.Color := clWindow;
DataVipDateEdit.Style.Color := clWindow;
SpecialNotesButtonEdit.Style.Color := clWindow;
PostavkaButtonEdit.Style.Color := clWindow;
OsobaPokupButtonEdit.Style.Color := clWindow;
RozraxunokButtonEdit.Style.Color := clWindow;
PodNumTextEdit.Style.Color := clWindow;
NumOrderTextEdit.Style.Color := clWindow;
DataTermsdelDateEdit.Style.Color := clWindow;
NumTermsDelTextEdit.Style.Color := clWindow;
TypeDocumentButtonEdit.Style.Color := clWindow;
EditingButton.Visible := False;
AddButton.Enabled := False;
UpdateButton.Enabled := False;
DeleteButton.Enabled := False;
RefreshButton.Enabled := False;
BudgetButton.Enabled := False;
YesButton.Visible := True;
EditTaxButton.Enabled := False;
end;
end;
end;
procedure TTaxInvoicesEditAddForm.EditingButtonClick(Sender: TObject);
begin
PodZobButtonEdit.Properties.onButtonClick := PodZobButtonEditPropertiesButtonClick;
PodKreditButtonEdit.Properties.onButtonClick := PodKreditButtonEditPropertiesButtonClick;
DataVipDateEdit.Properties.ReadOnly := False;
SpecialNotesButtonEdit.Properties.onButtonClick := SpecialNotesButtonEditPropertiesButtonClick;
PostavkaButtonEdit.Properties.onButtonClick := PostavkaButtonEditPropertiesButtonClick;
OsobaPokupButtonEdit.Properties.onButtonClick := OsobaPokupButtonEditPropertiesButtonClick;
RozraxunokButtonEdit.Properties.onButtonClick := RozraxunokButtonEditPropertiesButtonClick;
TypeDocumentButtonEdit.Properties.onButtonClick := TypeDocumentButtonEditPropertiesButtonClick;
PodNumTextEdit.Properties.ReadOnly := False;
NumOrderTextEdit.Properties.ReadOnly := False;
NumTermsDelTextEdit.Properties.ReadOnly := False;
PodNumTextEdit.Properties.ReadOnly := False;
DataVipDateEdit.Properties.ReadOnly := False;
DataTermsdelDateEdit.Properties.ReadOnly := False;
IPNPokupTextEdit.Properties.ReadOnly := False;
//NoteTextEdit.Properties.ReadOnly := False;
NotPDVCheckBox.Properties.ReadOnly := False;
PodZobButtonEdit.Style.Color := clWindow;
PodKreditButtonEdit.Style.Color := clWindow;
DataVipDateEdit.Style.Color := clWindow;
SpecialNotesButtonEdit.Style.Color := clWindow;
PostavkaButtonEdit.Style.Color := clWindow;
OsobaPokupButtonEdit.Style.Color := clWindow;
RozraxunokButtonEdit.Style.Color := clWindow;
PodNumTextEdit.Style.Color := clWindow;
NumOrderTextEdit.Style.Color := clWindow;
DataTermsdelDateEdit.Style.Color := clWindow;
NumTermsDelTextEdit.Style.Color := clWindow;
IPNPokupTextEdit.Style.Color := clWindow;
TypeDocumentButtonEdit.Style.Color := clWindow;
EditingButton.Visible := False;
AddButton.Enabled := False;
UpdateButton.Enabled := False;
DeleteButton.Enabled := False;
RefreshButton.Enabled := False;
YesButton.Visible := True;
BudgetButton.Enabled := False;
EditTaxButton.Enabled := False;
is_issued_buyer_CheckBox.Properties.ReadOnly := False;
is_erpn_CheckBox.Properties.ReadOnly := False;
is_issued_buyer_CheckBox.Properties.ReadOnly := False;
OsoblPrimCheckBox.Properties.ReadOnly := False;
is_copy_CheckBox.Properties.ReadOnly := False;
PostavkaCheckBox.Properties.ReadOnly := False;
RozraxunokCheckBox.Properties.ReadOnly := False;
PodZobCheckBox.Properties.ReadOnly := False;
PodKreditCheckBox.Properties.ReadOnly := False;
NoteCheckBox.Properties.ReadOnly := False;
NoteButtonEdit.Enabled := True;
end;
procedure TTaxInvoicesEditAddForm.FormClose(Sender: TObject;
var Action: TCloseAction);
var
summa_val_deliv_20 :Double;
summa_tax : Extended;
summa_val_deliv_vat_extemptions : Double;
summa_NDS_budget :Extended;
summa_not_NDS_budget :Double;
begin
RefreshButtonClick(Self);
// ничего не делать, если старая налоговая
if ((TaxInvoicesEditDM.VidNaklInfoDSet['PK_ID']<>'-1') and (TaxInvoicesEditDM.VidNaklInfoDSet['PK_ID'] <> null)) then
begin
//проверка на пустоту сумм
if (TaxInvoicesEditDM.VidNaklInfoDSet['summa_val_deliv_20'] = null) then
summa_val_deliv_20 := 0
else
summa_val_deliv_20 := TaxInvoicesEditDM.VidNaklInfoDSet['summa_val_deliv_20'];
if (TaxInvoicesEditDM.VidNaklInfoDSet['summa_tax'] = null) then
summa_tax := 0
else
summa_tax := TaxInvoicesEditDM.VidNaklInfoDSet['summa_tax'];
if (TaxInvoicesEditDM.VidNaklInfoDSet['summa_val_deliv_vat_extemptions'] = null) then
summa_val_deliv_vat_extemptions := 0
else
summa_val_deliv_vat_extemptions := TaxInvoicesEditDM.VidNaklInfoDSet['summa_val_deliv_vat_extemptions'];
TaxInvoicesEditDM.WriteTransaction.StartTransaction;
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_SUMMA_BUDGET_VID_NAKL';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_nakl').Value := id_vid_nakl_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.WriteTransaction.Commit;
summa_NDS_budget := TaxInvoicesEditDM.pFIBStoredProc.ParamByName('SUMMA_NDS').Value;
summa_not_NDS_budget := TaxInvoicesEditDM.pFIBStoredProc.ParamByName('summa_not_nds').Value;
if (summa_NDS_budget <> summa_tax) then
begin
TiShowMessage('Увага!', 'Сума ПДВ (бюджети)='+Floattostr(summa_NDS_budget)+'.Введена сума ПДВ='+Floattostr(summa_tax)+'.Суми повинні співпадати!Заповніть корректно бюджет або накладну.', mtWarning, [mbOK]);
Action := caNone;
Exit;
end;
// если сумма НДС не нулевая
if summa_NDS_budget <> 0 then
begin
if summa_val_deliv_20 <> summa_not_NDS_budget then
begin
TiShowMessage('Увага!', '20% ,обсяг без ПДВ(бюджети) = ' + Floattostr(summa_not_NDS_budget)+'. Введена сума 20%, обсяг без ПДВ ='+Floattostr(summa_val_deliv_20)+'. Суми повинні співпадати!Заповніть корректно бюджет або накладну.' , mtWarning, [mbOK]);
Action := caNone;
Exit;
end
end;
if summa_NDS_budget = 0 then
begin
if summa_val_deliv_vat_extemptions <> summa_not_NDS_budget then
begin
TiShowMessage('Увага!', 'Звільнені від оподаткув.(бюджети) = ' + Floattostr(summa_not_NDS_budget)+'. Введена сума Звільнені від оподаткув. ='+Floattostr(summa_val_deliv_vat_extemptions)+'. Суми повинні співпадати!Заповніть корректно бюджет або накладну.' , mtWarning, [mbOK]);
Action := caNone;
Exit;
end;
end;
end;
writeReg;
if (TaxInvoicesEditDM.ReadTransaction.Active) then
TaxInvoicesEditDM.ReadTransaction.Commit;
if formstyle = fsMDIChild then
begin
action := caFree;
end
else
Begin
TaxInvoicesEditDM.free;
ModalResult := mrOk;
end;
end;
procedure TTaxInvoicesEditAddForm.ReadReg;
var
reg : TRegistry;
begin
try
begin
reg := TRegistry.Create;
reg.RootKey := HKEY_CURRENT_USER;
if reg.OpenKey('\Software\TaxInvoices\VidNaklDocIns\',False) then
begin
PodZobButtonEdit.Text := reg.ReadString('Name_TaxLiabilities');
PParameter.id_TaxLiabilities := StrToInt(reg.ReadString('id_TaxLiabilities'));
PParameter.Name_TaxLiabilities := reg.ReadString('Name_TaxLiabilities');
PodKreditButtonEdit.Text := reg.ReadString('Name_TaxKredit');
PParameter.Id_TaxKredit := StrToInt(reg.ReadString('Id_TaxKredit'));
PParameter.Name_TaxKredit := reg.ReadString('Name_TaxKredit');
SpecialNotesButtonEdit.Text := reg.ReadString('Num_SpecialNotes');
PParameter.id_SpecialNotes := StrToInt(reg.ReadString('id_SpecialNotes'));
PParameter.Name_SpecialNotes := reg.ReadString('Name_SpecialNotes');
PostavkaButtonEdit.Text := reg.ReadString('Name_TermsDelivery');
PParameter.id_TermsDelivery := StrToInt(reg.ReadString('id_TermsDelivery'));
PParameter.Name_TermsDelivery := reg.ReadString('Name_TermsDelivery');
RozraxunokButtonEdit.Text := reg.ReadString('Name_FormCalculations');
PParameter.id_FormCalculations := StrToInt(reg.ReadString('id_FormCalculations'));
PParameter.Name_FormCalculations := reg.ReadString('Name_FormCalculations');
if reg.ReadString('ID_TYPE_DOCUMENT') = '' then
begin
PParameter.ID_TYPE_DOCUMENT := 0;
PParameter.NAME_TYPE_DOCUMENT := '';
TypeDocumentButtonEdit.Text := '';
end
else
begin
PParameter.ID_TYPE_DOCUMENT := StrToInt(reg.ReadString('ID_TYPE_DOCUMENT'));
PParameter.NAME_TYPE_DOCUMENT := reg.ReadString('NAME_TYPE_DOCUMENT');
TypeDocumentButtonEdit.Text := reg.ReadString('NAME_TYPE_DOCUMENT');
end;
end
else
begin
PostavkaButtonEdit.Text := '';
RozraxunokButtonEdit.Text := '';
SpecialNotesButtonEdit.Text := '';
PodZobButtonEdit.Text := '';
PodKreditButtonEdit.Text := '';
TypeDocumentButtonEdit.Text := '';
end;
end;
{if reg.OpenKey('\Software\TaxInvoices\VidNaklDocIns\ID_TYPE_DOCUMENT',False) then
begin
PParameter.ID_TYPE_DOCUMENT := StrToInt(reg.ReadString('ID_TYPE_DOCUMENT'));
PParameter.NAME_TYPE_DOCUMENT := reg.ReadString('NAME_TYPE_DOCUMENT');
TypeDocumentButtonEdit.Text := reg.ReadString('NAME_TYPE_DOCUMENT');
end
else
begin
TypeDocumentButtonEdit.Text := '';
end; }
finally
reg.Free;
end;
end;
procedure TTaxInvoicesEditAddForm.WriteReg;
var
reg : TRegistry;
begin
reg := TRegistry.Create;
try
reg.RootKey:=HKEY_CURRENT_USER;
if (reg.OpenKey('\Software\TaxInvoices\VidNaklDocIns\',True)) then
begin
reg.WriteString('Id_TaxLiabilities',IntToStr(PParameter.id_TaxLiabilities));
reg.WriteString('Name_TaxLiabilities',PParameter.Name_TaxLiabilities);
reg.WriteString('Id_TaxKredit',IntToStr(PParameter.Id_TaxKredit));
reg.WriteString('Name_TaxKredit',PParameter.Name_TaxKredit);
reg.WriteString('id_SpecialNotes',IntToStr(PParameter.id_SpecialNotes));
reg.WriteString('Name_SpecialNotes',PParameter.Name_SpecialNotes);
reg.WriteString('id_TermsDelivery',IntToStr(PParameter.id_TermsDelivery));
reg.WriteString('Name_TermsDelivery',PParameter.Name_TermsDelivery);
reg.WriteString('id_FormCalculations',IntToStr(PParameter.id_FormCalculations));
reg.WriteString('Name_FormCalculations',PParameter.Name_FormCalculations);
reg.WriteString('ID_TYPE_DOCUMENT',IntToStr(PParameter.ID_TYPE_DOCUMENT));
reg.WriteString('NAME_TYPE_DOCUMENT',PParameter.NAME_TYPE_DOCUMENT);
end;
finally
reg.Free;
end;
end;
procedure TTaxInvoicesEditAddForm.DeliveryInsBarButtonClick(Sender: TObject);
begin
AddButton.Click;
end;
procedure TTaxInvoicesEditAddForm.RefreshButtonClick(Sender: TObject);
var
p: Double;
begin
// ShowMessage(IntToStr(id_vid_nakl_doc_Ins));
TaxInvoicesEditDM.VidNaklInfoDSet.Close;
TaxInvoicesEditDM.VidNaklInfoDSet.SelectSQL.Text := 'select * from TI_SP_VID_NAKL_DOC_SEL(:ID)';
TaxInvoicesEditDM.VidNaklInfoDSet.ParamByName('id').Value := id_vid_nakl_doc_Ins;
TaxInvoicesEditDM.VidNaklInfoDSet.Open;
if (TaxInvoicesEditDM.VidNaklInfoDSet['summa_val_deliv_20'] = null) then
FirstAllStatusBar.Panels[5].Text := ''
else
begin
p:= TaxInvoicesEditDM.VidNaklInfoDSet['summa_val_deliv_20'];
if (trunc(p) = p) then
begin
FirstAllStatusBar.Panels[5].Text := FloatToStr(p) + ',00';
end
else
FirstAllStatusBar.Panels[5].Text := FloatToStr(p);
end;
if (TaxInvoicesEditDM.VidNaklInfoDSet['summa_val_deliv_customs'] = null) then
FirstAllStatusBar.Panels[6].Text := ''
else
begin
p:= TaxInvoicesEditDM.VidNaklInfoDSet['summa_val_deliv_customs'];
if (trunc(p) = p) then
begin
FirstAllStatusBar.Panels[6].Text := FloatToStr(p) + ',00';
end
else
FirstAllStatusBar.Panels[6].Text := FloatToStr(p);
end;
if (TaxInvoicesEditDM.VidNaklInfoDSet['summa_val_deliv_export'] = null) then
FirstAllStatusBar.Panels[6].Text := ''
else
begin
p:= TaxInvoicesEditDM.VidNaklInfoDSet['summa_val_deliv_export'];
if (trunc(p) = p) then
begin
FirstAllStatusBar.Panels[7].Text := FloatToStr(p) + ',00';
end
else
FirstAllStatusBar.Panels[7].Text := FloatToStr(p);
end;
if (TaxInvoicesEditDM.VidNaklInfoDSet['summa_val_deliv_vat_extemptions'] = null) then
FirstAllStatusBar.Panels[8].Text := ''
else
begin
p:= TaxInvoicesEditDM.VidNaklInfoDSet['summa_val_deliv_vat_extemptions'];
if (trunc(p) = p) then
begin
FirstAllStatusBar.Panels[8].Text := FloatToStr(p) + ',00';
end
else
FirstAllStatusBar.Panels[8].Text := FloatToStr(p);
end;
if (TaxInvoicesEditDM.VidNaklInfoDSet['summa_all_oplata'] = null) then
FirstAllStatusBar.Panels[9].Text := ''
else
begin
p:= TaxInvoicesEditDM.VidNaklInfoDSet['summa_all_oplata'];
if (trunc(p) = p) then
begin
FirstAllStatusBar.Panels[9].Text := FloatToStr(p) + ',00';
end
else
FirstAllStatusBar.Panels[9].Text := FloatToStr(p);
end;
if (TaxInvoicesEditDM.VidNaklInfoDSet['summa_tax'] = null) then
begin
TaxStatusBar.Panels[5].Text := '';
TaxStatusBar.Panels[9].Text := '';
end
else
begin
p:= TaxInvoicesEditDM.VidNaklInfoDSet['summa_tax'];
if (trunc(p) = p) then
begin
TaxStatusBar.Panels[5].Text := FloatToStr(p) + ',00';
TaxStatusBar.Panels[9].Text := FloatToStr(p) + ',00';
end
else
begin
TaxStatusBar.Panels[5].Text := FloatToStr(p);
TaxStatusBar.Panels[9].Text := FloatToStr(p);
end;
end;
if (TaxInvoicesEditDM.VidNaklInfoDSet['summa_val_deliv_20_pdv'] = null) then
SummaAllPDVStatusBar.Panels[5].Text := ''
else
begin
p:= TaxInvoicesEditDM.VidNaklInfoDSet['summa_val_deliv_20_pdv'];
if (trunc(p) = p) then
begin
SummaAllPDVStatusBar.Panels[5].Text := FloatToStr(p) + ',00';
end
else
SummaAllPDVStatusBar.Panels[5].Text := FloatToStr(p);
end;
if (TaxInvoicesEditDM.VidNaklInfoDSet['summa_val_deliv_customs'] = null) then
SummaAllPDVStatusBar.Panels[6].Text := ''
else
begin
p:= TaxInvoicesEditDM.VidNaklInfoDSet['summa_val_deliv_customs'];
if (trunc(p) = p) then
begin
SummaAllPDVStatusBar.Panels[6].Text := FloatToStr(p) + ',00';
end
else
SummaAllPDVStatusBar.Panels[6].Text := FloatToStr(p);
end;
if (TaxInvoicesEditDM.VidNaklInfoDSet['summa_val_deliv_export'] = null) then
SummaAllPDVStatusBar.Panels[7].Text := ''
else
begin
p:= TaxInvoicesEditDM.VidNaklInfoDSet['summa_val_deliv_export'];
if (trunc(p) = p) then
begin
SummaAllPDVStatusBar.Panels[7].Text := FloatToStr(p) + ',00';
end
else
SummaAllPDVStatusBar.Panels[7].Text := FloatToStr(p);
end;
if (TaxInvoicesEditDM.VidNaklInfoDSet['summa_val_deliv_vat_extemptions'] = null) then
SummaAllPDVStatusBar.Panels[8].Text := ''
else
begin
p:= TaxInvoicesEditDM.VidNaklInfoDSet['summa_val_deliv_vat_extemptions'];
if (trunc(p) = p) then
begin
SummaAllPDVStatusBar.Panels[8].Text := FloatToStr(p) + ',00';
end
else
SummaAllPDVStatusBar.Panels[8].Text := FloatToStr(p);
end;
if (TaxInvoicesEditDM.VidNaklInfoDSet['summa_all_oplata_pdv'] = null) then
SummaAllPDVStatusBar.Panels[9].Text := ''
else
begin
p:= TaxInvoicesEditDM.VidNaklInfoDSet['summa_all_oplata_pdv'];
if (trunc(p) = p) then
begin
SummaAllPDVStatusBar.Panels[9].Text := FloatToStr(p) + ',00';
end
else
SummaAllPDVStatusBar.Panels[9].Text := FloatToStr(p);
end;
TaxInvoicesEditDM.NaklDeliveryDSet.Close;
TaxInvoicesEditDM.NaklDeliveryDSet.SelectSQL.Text := 'select * from TI_SP_VID_NAKL_DELIVERY_SEL where ID_VID_NAKL_DOC =:ID and SECTION = :section ';
TaxInvoicesEditDM.NaklDeliveryDSet.ParamByName('ID').Value := id_vid_nakl_doc_Ins;
TaxInvoicesEditDM.NaklDeliveryDSet.ParamByName('section').Value := '1';
TaxInvoicesEditDM.NaklDeliveryDSet.Open;
FirstSummaAll;
TransportCosts;
MortgageTara;
end;
procedure TTaxInvoicesEditAddForm.UpdateButtonClick(Sender: TObject);
var
ViewForm : TTaxInvoicesEditAddInNaklForm;
id_vid_nakl_delivery :Integer;
AddParametr :TTITaxInvoicesAddVidNaklDelivery;
begin
if not (TaxInvoicesEditDM.NaklDeliveryDSet.IsEmpty) then
begin
id_vid_nakl_delivery := TaxInvoicesEditDM.NaklDeliveryDSet['id_vid_nakl_delivery'];
if (TaxInvoicesEditDM.NaklDeliveryDSet['id_range_of_delivery'] = null) then
begin
AddParametr.id_range_of_delivery := 0;
AddParametr.Name_range_of_delivery := '';
end
else
begin
AddParametr.id_range_of_delivery := TaxInvoicesEditDM.NaklDeliveryDSet['id_range_of_delivery'];
AddParametr.Name_range_of_delivery := TaxInvoicesEditDM.NaklDeliveryDSet['Name_range_of_delivery'];
end;
if (TaxInvoicesEditDM.NaklDeliveryDSet['id_measures'] = null) then
begin
AddParametr.Id_Measures := 0;
AddParametr.Name_Measures := '';
end
else
begin
AddParametr.Id_Measures := TaxInvoicesEditDM.NaklDeliveryDSet['id_measures'];
AddParametr.Name_Measures := TaxInvoicesEditDM.NaklDeliveryDSet['Name_Measures'];
end;
if ((TaxInvoicesEditDM.NaklDeliveryDSet['id_kod_tovar'] = null) or (TaxInvoicesEditDM.NaklDeliveryDSet['id_kod_tovar'] = 0) ) then
begin
AddParametr.id_kod_tovar := 0;
AddParametr.Num_Kod_tovar := '';
AddParametr.Name_Kod_tovar := '';
end
else
begin
AddParametr.id_kod_tovar := TaxInvoicesEditDM.NaklDeliveryDSet['id_kod_tovar'];
AddParametr.Num_Kod_tovar := TaxInvoicesEditDM.NaklDeliveryDSet['num_kod_tovar'];
AddParametr.Name_Kod_tovar := TaxInvoicesEditDM.NaklDeliveryDSet['name_kod_tovar'];
end;
ViewForm := TTaxInvoicesEditAddInNaklForm.Create(Self,TaxInvoicesEditDM.DB.Handle,AddParametr);
if ((TaxInvoicesEditDM.NaklDeliveryDSet['MONTH_RANGE_OF_DELIVERY'] = null) or (TaxInvoicesEditDM.NaklDeliveryDSet['MONTH_RANGE_OF_DELIVERY'] = '') ) then
begin
ViewForm.ZaCheckBox.Checked := False;
ViewForm.MonthList.Enabled := False;
ViewForm.YearSpinEdit.Enabled := False;
ViewForm.MonthList.Items.Text := GetMonthList2;
ViewForm.Kod_Setup := CurrentKodSetup(PDb_Handle);
ViewForm.YearSpinEdit.Value := YearMonthFromKodSetup(ViewForm.Kod_Setup);
ViewForm.MonthList.ItemIndex := YearMonthFromKodSetup(ViewForm.Kod_Setup-1,False);
end
else
begin
ViewForm.ZaCheckBox.Checked := True;
ViewForm.MonthList.Enabled := True;
ViewForm.YearSpinEdit.Enabled := True;
ViewForm.MonthList.Text := TaxInvoicesEditDM.NaklDeliveryDSet['MONTH_RANGE_OF_DELIVERY'];
ViewForm.YearSpinEdit.Text := TaxInvoicesEditDM.NaklDeliveryDSet['YEAR_RANGE_OF_DELIVERY'];
end;
ViewForm.DateShipmentLabel.Visible := True;
ViewForm.DateShipmentEdit.Visible := True;
ViewForm.RangeOfDeliveryLabel.Visible := True;
ViewForm.RangeOfDeliveryButtonEdit.Visible := True;
ViewForm.DataGroupBox.Visible := True;
ViewForm.DateShipmentEdit.Date := TaxInvoicesEditDM.NaklDeliveryDSet['date_shipment'];
ViewForm.KolVoTextEdit.Text := TaxInvoicesEditDM.NaklDeliveryDSet['kol_vo_delivery_goods'];
ViewForm.PriceCurrencyEdit.Text := TaxInvoicesEditDM.NaklDeliveryDSet['price_delivery_goods'];
ViewForm.RangeOfDeliveryButtonEdit.Text := AddParametr.Name_range_of_delivery;
ViewForm.MeasuresButtonEdit.Text := AddParametr.Name_Measures;
if (AddParametr.Name_Kod_tovar = '') then
begin
ViewForm.KodTovarCheckBox.Checked := False;
ViewForm.KodTovarButtonEdit.Text := '';
end
else
begin
ViewForm.KodTovarCheckBox.Checked := True;
ViewForm.KodTovarButtonEdit.Text := AddParametr.Name_Kod_tovar;
end;
if (AddParametr.Name_Kod_tovar = '') then
begin
ViewForm.KodTovarCheckBox.Checked := False;
ViewForm.KodTovarButtonEdit.Text := '';
end
else
begin
ViewForm.KodTovarCheckBox.Checked := True;
ViewForm.KodTovarButtonEdit.Text := AddParametr.Name_Kod_tovar;
end;
ViewForm.ValueDeliveryExportCurrencyEdit.Text := TaxInvoicesEditDM.NaklDeliveryDSet['value_delivery_export'];
ViewForm.ValueDelivery20CurrencyEdit.Text := TaxInvoicesEditDM.NaklDeliveryDSet['value_delivery_20'];
ViewForm.ValueDeliveryCustomsCurrencyEdit.Text := TaxInvoicesEditDM.NaklDeliveryDSet['value_delivery_customs'];
ViewForm.ValueDeliveryVATexemptionsCurrencyEdit.Text := TaxInvoicesEditDM.NaklDeliveryDSet['value_delivery_vat_exemption'];
ViewForm.ShowModal;
if (ViewForm.ModalResult = mrok) then
begin
TaxInvoicesEditDM.WriteTransaction.StartTransaction;
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_SP_VID_NAKL_DELIVERY_UPD';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('date_shipment').Value := ViewForm.DateShipmentEdit.Date;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_range_of_delivery').Value := ViewForm.Parameter.id_range_of_delivery;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('name_range_of_delivery').Value := ViewForm.Parameter.Name_range_of_delivery;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_measures').Value := ViewForm.Parameter.Id_Measures;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('name_measures').Value := ViewForm.MeasuresButtonEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('kol_vo_delivery_goods').Value := ViewForm.KolVoTextEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('price_delivery_goods').Value := ViewForm.PriceCurrencyEdit.Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('value_delivery_20').Value := ViewForm.ValueDelivery20CurrencyEdit.Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('value_delivery_export').Value := ViewForm.ValueDeliveryExportCurrencyEdit.Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('value_delivery_customs').Value := ViewForm.ValueDeliveryCustomsCurrencyEdit.Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('value_delivery_vat_exemption').Value := ViewForm.ValueDeliveryVATexemptionsCurrencyEdit.Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_vid_nakl_doc').Value := id_vid_nakl_doc_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('section').Value := '1';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_vid_nakl_delivery').Value := id_vid_nakl_delivery;
if (ViewForm.KodTovarCheckBox.Checked = true) then
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_kod_tovar').Value := ViewForm.Parameter.id_kod_tovar;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('num_kod_tovar').Value := ViewForm.Parameter.Num_Kod_tovar;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('name_kod_tovar').Value := ViewForm.Parameter.Name_Kod_tovar;
end
else
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_kod_tovar').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('num_kod_tovar').Value := '';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('name_kod_tovar').Value := '';
end;
if (ViewForm.ZaCheckBox.Checked = true) then
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('MONTH_RANGE_OF_DELIVERY').Value := ViewForm.MonthList.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('YEAR_RANGE_OF_DELIVERY').Value := ViewForm.YearSpinEdit.Text;
end
else
begin
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('MONTH_RANGE_OF_DELIVERY').Value := '';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('YEAR_RANGE_OF_DELIVERY').Value := '';
end;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_VID_NAKL_DOC_SUMMA_CALC';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_VID_NAKL_DOC').Value := id_vid_nakl_doc_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.WriteTransaction.Commit;
RefreshButton.Click;
TaxInvoicesEditDM.NaklDeliveryDSet.Locate('ID_VID_NAKL_DELIVERY',IntToStr(id_vid_nakl_delivery),[]);
end;
end;
end;
procedure TTaxInvoicesEditAddForm.DeliveryUpdBarButtonClick(Sender: TObject);
begin
UpdateButton.Click;
end;
procedure TTaxInvoicesEditAddForm.DeleteButtonClick(Sender: TObject);
begin
if TiShowMessage('Увага!','Ви дійсно бажаєте вилучити поставку?',mtConfirmation,[mbYes, mbNo])=mrYes then
begin
try
TaxInvoicesEditDM.WriteTransaction.StartTransaction;
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName:='TI_SP_VID_NAKL_DELIVERY_DEL';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_vid_nakl_delivery').Value:=TaxInvoicesEditDM.NaklDeliveryDSet['id_vid_nakl_delivery'];
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_VID_NAKL_DOC_SUMMA_CALC';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_VID_NAKL_DOC').Value := id_vid_nakl_doc_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.WriteTransaction.Commit;
RefreshButton.Click;
except on E:Exception do
begin
TiShowMessage('Увага!','не можна видалити цей запис', mtError, [mbOK]);
TaxInvoicesEditDM.WriteTransaction.Rollback;
end;
end;
end;
end;
procedure TTaxInvoicesEditAddForm.DeliveryDelBarButtonClick(Sender: TObject);
begin
DeleteButton.Click;
end;
procedure TTaxInvoicesEditAddForm.FirstSummaAll;
var
p:Double;
begin
TaxInvoicesEditDM.FirstSummaAllDSet.Close;
TaxInvoicesEditDM.FirstSummaAllDSet.SelectSQL.Text := 'select * from TI_FIRST_SUMMA_ALL(:id)';
TaxInvoicesEditDM.FirstSummaAllDSet.ParamByName('id').Value := id_vid_nakl_doc_Ins;
TaxInvoicesEditDM.FirstSummaAllDSet.Open;
if (TaxInvoicesEditDM.FirstSummaAllDSet['value_delivery_20'] = null) then
FirstAllStatusBar.Panels[5].Text := ''
else
begin
p:= TaxInvoicesEditDM.FirstSummaAllDSet['value_delivery_20'];
if (trunc(p) = p) then
begin
FirstAllStatusBar.Panels[5].Text := FloatToStr(p) + ',00';
end
else
FirstAllStatusBar.Panels[5].Text := FloatToStr(p);
end;
if (TaxInvoicesEditDM.FirstSummaAllDSet['value_delivery_customs'] = null) then
FirstAllStatusBar.Panels[6].Text := ''
else
begin
p:= TaxInvoicesEditDM.FirstSummaAllDSet['value_delivery_customs'];
if (trunc(p) = p) then
begin
FirstAllStatusBar.Panels[6].Text := FloatToStr(p) + ',00';
end
else
FirstAllStatusBar.Panels[6].Text := FloatToStr(p);
end;
if (TaxInvoicesEditDM.FirstSummaAllDSet['value_delivery_export'] = null) then
FirstAllStatusBar.Panels[7].Text := ''
else
begin
p:= TaxInvoicesEditDM.FirstSummaAllDSet['value_delivery_export'];
if (trunc(p) = p) then
begin
FirstAllStatusBar.Panels[7].Text := FloatToStr(p) + ',00';
end
else
FirstAllStatusBar.Panels[7].Text := FloatToStr(p);
end;
if (TaxInvoicesEditDM.FirstSummaAllDSet['value_delivery_vat_exemption'] = null) then
FirstAllStatusBar.Panels[8].Text := ''
else
begin
p:= TaxInvoicesEditDM.FirstSummaAllDSet['value_delivery_vat_exemption'];
if (trunc(p) = p) then
begin
FirstAllStatusBar.Panels[8].Text := FloatToStr(p) + ',00';
end
else
FirstAllStatusBar.Panels[8].Text := FloatToStr(p);
end;
if (TaxInvoicesEditDM.FirstSummaAllDSet['summa_all'] = null) then
FirstAllStatusBar.Panels[9].Text := ''
else
begin
p:= TaxInvoicesEditDM.FirstSummaAllDSet['summa_all'];
if (trunc(p) = p) then
begin
FirstAllStatusBar.Panels[9].Text := FloatToStr(p) + ',00';
end
else
FirstAllStatusBar.Panels[9].Text := FloatToStr(p);
end;
{ if (TaxInvoicesEditDM.FirstSummaAllDSet['value_delivery_customs'] = null) then
FirstAllStatusBar.Panels[6].Text := ''
else
FirstAllStatusBar.Panels[6].Text := TaxInvoicesEditDM.FirstSummaAllDSet['value_delivery_customs'];
if (TaxInvoicesEditDM.FirstSummaAllDSet['value_delivery_export'] = null) then
FirstAllStatusBar.Panels[7].Text := ''
else
FirstAllStatusBar.Panels[7].Text := TaxInvoicesEditDM.FirstSummaAllDSet['value_delivery_export'];
if (TaxInvoicesEditDM.FirstSummaAllDSet['value_delivery_vat_exemption'] = null) then
FirstAllStatusBar.Panels[8].Text := ''
else
FirstAllStatusBar.Panels[8].Text := TaxInvoicesEditDM.FirstSummaAllDSet['value_delivery_vat_exemption'];
if (TaxInvoicesEditDM.FirstSummaAllDSet['summa_all'] = null) then
FirstAllStatusBar.Panels[9].Text := ''
else
FirstAllStatusBar.Panels[9].Text := TaxInvoicesEditDM.FirstSummaAllDSet['summa_all']; }
end;
procedure TTaxInvoicesEditAddForm.TransportInsBarButtonClick(
Sender: TObject);
var
ViewForm : TTaxInvoicesEditAddInNaklForm;
id_vid_nakl_delivery : Integer;
AddParametr : TTITaxInvoicesAddVidNaklDelivery;
begin
AddParametr.id_range_of_delivery := 0;
AddParametr.Name_range_of_delivery := '';
AddParametr.Id_Measures := 0;
AddParametr.Name_Measures := '';
ViewForm := TTaxInvoicesEditAddInNaklForm.Create(Self,TaxInvoicesEditDM.DB.Handle,AddParametr);
ViewForm.DataGroupBox.Visible := False;
ViewForm.DateShipmentLabel.Visible := False;
ViewForm.DateShipmentEdit.Visible := False;
ViewForm.RangeOfDeliveryLabel.Visible := False;
ViewForm.RangeOfDeliveryButtonEdit.Visible := False;
ViewForm.DataGroupBox.Visible := False;
ViewForm.KolVoTextEdit.Text := '';
ViewForm.PriceCurrencyEdit.Text := '';
ViewForm.ValueDeliveryExportCurrencyEdit.Text := '';
ViewForm.ValueDelivery20CurrencyEdit.Text := '';
ViewForm.ValueDeliveryCustomsCurrencyEdit.Text := '';
ViewForm.ValueDeliveryVATexemptionsCurrencyEdit.Text := '';
ViewForm.ReadReg;
ViewForm.ShowModal;
if (ViewForm.ModalResult = mrok) then
begin
TaxInvoicesEditDM.WriteTransaction.StartTransaction;
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_SP_VID_NAKL_DELIVERY_INS';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_measures').Value := ViewForm.Parameter.Id_Measures;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('name_measures').Value := ViewForm.Parameter.Name_Measures;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('kol_vo_delivery_goods').Value := ViewForm.KolVoTextEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('price_delivery_goods').Value := ViewForm.PriceCurrencyEdit.Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('value_delivery_20').Value := ViewForm.ValueDelivery20CurrencyEdit.Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('value_delivery_export').Value := ViewForm.ValueDeliveryExportCurrencyEdit.Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('value_delivery_customs').Value := ViewForm.ValueDeliveryCustomsCurrencyEdit.Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('value_delivery_vat_exemption').Value := ViewForm.ValueDeliveryVATexemptionsCurrencyEdit.Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_vid_nakl_doc').Value := id_vid_nakl_doc_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('section').Value := '2';
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.WriteTransaction.Commit;
id_vid_nakl_delivery := TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_VID_NAKL_DELIVERY_').AsInteger;
RefreshButton.Click;
TaxInvoicesEditDM.NaklDeliveryDSet.Locate('ID_VID_NAKL_DELIVERY',IntToStr(id_vid_nakl_delivery),[]);
end;
end;
procedure TTaxInvoicesEditAddForm.TransportCosts;
begin
TaxInvoicesEditDM.TransportCostsDSet.Close;
TaxInvoicesEditDM.TransportCostsDSet.SelectSQL.Text := 'select * from TI_TRANSPORT_COSTS(:ID) ';
TaxInvoicesEditDM.TransportCostsDSet.ParamByName('ID').Value := id_vid_nakl_doc_Ins;
TaxInvoicesEditDM.TransportCostsDSet.Open;
if (TaxInvoicesEditDM.TransportCostsDSet['summa_all'] = null) then
begin
TransportInsBarButton.Enabled := True;
TransportUpdBarButton.Enabled := False;
end
else
begin
TransportInsBarButton.Enabled := False;
TransportUpdBarButton.Enabled := True;
end;
if (id_vid_nakl_doc_Ins = -1) then
begin
TransportInsBarButton.Enabled := False;
TransportUpdBarButton.Enabled := True;
end;
if (TaxInvoicesEditDM.TransportCostsDSet['NAME_MEASURES'] = null) then
TransportCostsStatusBar.Panels[2].Text := ''
else
TransportCostsStatusBar.Panels[2].Text := TaxInvoicesEditDM.TransportCostsDSet['NAME_MEASURES'];
if (TaxInvoicesEditDM.TransportCostsDSet['kol_vo_delivery_goods'] = null) then
TransportCostsStatusBar.Panels[3].Text := ''
else
TransportCostsStatusBar.Panels[3].Text := TaxInvoicesEditDM.TransportCostsDSet['kol_vo_delivery_goods'];
if (TaxInvoicesEditDM.TransportCostsDSet['price_delivery_goods'] = null) then
TransportCostsStatusBar.Panels[4].Text := ''
else
TransportCostsStatusBar.Panels[4].Text := TaxInvoicesEditDM.TransportCostsDSet['price_delivery_goods'];
if (TaxInvoicesEditDM.TransportCostsDSet['value_delivery_20'] = null) then
TransportCostsStatusBar.Panels[5].Text := ''
else
TransportCostsStatusBar.Panels[5].Text := TaxInvoicesEditDM.TransportCostsDSet['value_delivery_20'];
if (TaxInvoicesEditDM.TransportCostsDSet['value_delivery_customs'] = null) then
TransportCostsStatusBar.Panels[6].Text := ''
else
TransportCostsStatusBar.Panels[6].Text := TaxInvoicesEditDM.TransportCostsDSet['value_delivery_customs'];
if (TaxInvoicesEditDM.TransportCostsDSet['value_delivery_export'] = null) then
TransportCostsStatusBar.Panels[7].Text := ''
else
TransportCostsStatusBar.Panels[7].Text := TaxInvoicesEditDM.TransportCostsDSet['value_delivery_export'];
if (TaxInvoicesEditDM.TransportCostsDSet['value_delivery_vat_exemption'] = null) then
TransportCostsStatusBar.Panels[8].Text := ''
else
TransportCostsStatusBar.Panels[8].Text := TaxInvoicesEditDM.TransportCostsDSet['value_delivery_vat_exemption'];
if (TaxInvoicesEditDM.TransportCostsDSet['summa_all'] = null) then
TransportCostsStatusBar.Panels[9].Text := ''
else
TransportCostsStatusBar.Panels[9].Text := TaxInvoicesEditDM.TransportCostsDSet['summa_all'];
end;
procedure TTaxInvoicesEditAddForm.ClearStatusBars;
begin
FirstAllStatusBar.Panels[5].Text := '';
FirstAllStatusBar.Panels[6].Text := '';
FirstAllStatusBar.Panels[7].Text := '';
FirstAllStatusBar.Panels[8].Text := '';
FirstAllStatusBar.Panels[9].Text := '';
TransportCostsStatusBar.Panels[2].Text := '';
TransportCostsStatusBar.Panels[3].Text := '';
TransportCostsStatusBar.Panels[4].Text := '';
TransportCostsStatusBar.Panels[5].Text := '';
TransportCostsStatusBar.Panels[6].Text := '';
TransportCostsStatusBar.Panels[7].Text := '';
TransportCostsStatusBar.Panels[8].Text := '';
MortgageTaraStatusBar.Panels[9].Text := '';
end;
procedure TTaxInvoicesEditAddForm.EnableButtons(id:Integer);
begin
if (id = -1) then //вставка документа
begin
DeliveryInsBarButton.Enabled := True;
TransportInsBarButton.Enabled := True;
TaraInsBarButton.Enabled := True;
DeliveryUpdBarButton.Enabled := False;
TransportUpdBarButton.Enabled := False;
TaraUpdBarButton.Enabled := False;
end
else
begin
DeliveryUpdBarButton.Enabled := True;
end;
end;
procedure TTaxInvoicesEditAddForm.TransportUpdBarButtonClick(
Sender: TObject);
var
ViewForm : TTaxInvoicesEditAddInNaklForm;
id_vid_nakl_delivery : Integer;
AddParametr : TTITaxInvoicesAddVidNaklDelivery;
begin
id_vid_nakl_delivery := TaxInvoicesEditDM.TransportCostsDSet['id_vid_nakl_delivery'];
AddParametr.id_range_of_delivery := 0;
AddParametr.Name_range_of_delivery := '';
AddParametr.Id_Measures := TaxInvoicesEditDM.TransportCostsDSet['Id_Measures'];
AddParametr.Name_Measures := TaxInvoicesEditDM.TransportCostsDSet['Name_Measures'];
ViewForm := TTaxInvoicesEditAddInNaklForm.Create(Self,TaxInvoicesEditDM.DB.Handle,AddParametr);
ViewForm.DataGroupBox.Visible := False;
ViewForm.DateShipmentLabel.Visible := False;
ViewForm.DateShipmentEdit.Visible := False;
ViewForm.RangeOfDeliveryLabel.Visible := False;
ViewForm.RangeOfDeliveryButtonEdit.Visible := False;
ViewForm.MeasuresButtonEdit.Text := TaxInvoicesEditDM.TransportCostsDSet['name_measures'];
ViewForm.KolVoTextEdit.Text := TaxInvoicesEditDM.TransportCostsDSet['kol_vo_delivery_goods'];
ViewForm.PriceCurrencyEdit.Text := TaxInvoicesEditDM.TransportCostsDSet['price_delivery_goods'];
ViewForm.ValueDeliveryExportCurrencyEdit.Text := TaxInvoicesEditDM.TransportCostsDSet['value_delivery_export'];
ViewForm.ValueDelivery20CurrencyEdit.Text := TaxInvoicesEditDM.TransportCostsDSet['value_delivery_20'];
ViewForm.ValueDeliveryCustomsCurrencyEdit.Text := TaxInvoicesEditDM.TransportCostsDSet['value_delivery_customs'];
ViewForm.ValueDeliveryVATexemptionsCurrencyEdit.Text := TaxInvoicesEditDM.TransportCostsDSet['value_delivery_vat_exemption'];
ViewForm.ShowModal;
if (ViewForm.ModalResult = mrok) then
begin
TaxInvoicesEditDM.WriteTransaction.StartTransaction;
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_SP_VID_NAKL_DELIVERY_UPD';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_measures').Value := ViewForm.Parameter.Id_Measures;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('name_measures').Value := ViewForm.Parameter.Name_Measures;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('kol_vo_delivery_goods').Value := ViewForm.KolVoTextEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('price_delivery_goods').Value := ViewForm.PriceCurrencyEdit.Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('value_delivery_20').Value := ViewForm.ValueDelivery20CurrencyEdit.Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('value_delivery_export').Value := ViewForm.ValueDeliveryExportCurrencyEdit.Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('value_delivery_customs').Value := ViewForm.ValueDeliveryCustomsCurrencyEdit.Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('value_delivery_vat_exemption').Value := ViewForm.ValueDeliveryVATexemptionsCurrencyEdit.Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_vid_nakl_doc').Value := id_vid_nakl_doc_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('section').Value := '2';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_vid_nakl_delivery').Value := id_vid_nakl_delivery;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.WriteTransaction.Commit;
RefreshButton.Click;
TaxInvoicesEditDM.NaklDeliveryDSet.Locate('ID_VID_NAKL_DELIVERY',IntToStr(id_vid_nakl_delivery),[]);
end;
end;
procedure TTaxInvoicesEditAddForm.TransportDelBarButtonClick(
Sender: TObject);
begin
if TiShowMessage('Увага!','Ви дійсно бажаєте вилучити запис?',mtConfirmation,[mbYes, mbNo])=mrYes then
begin
try
TaxInvoicesEditDM.WriteTransaction.StartTransaction;
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName:='TI_SP_VID_NAKL_DELIVERY_DEL';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_vid_nakl_delivery').Value := TaxInvoicesEditDM.TransportCostsDSet['id_vid_nakl_delivery'];
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.WriteTransaction.Commit;
RefreshButton.Click;
except on E:Exception do
begin
TiShowMessage('Увага!','не можна видалити цей запис', mtError, [mbOK]);
TaxInvoicesEditDM.WriteTransaction.Rollback;
end;
end;
end;
end;
procedure TTaxInvoicesEditAddForm.TaraInsBarButtonClick(Sender: TObject);
var
ViewForm : TTaxInvoicesEditAddTaraForm;
AddParametr : TTITaxInvoicesAddTara;
begin
AddParametr.id_tara := 0;
AddParametr.Name_tara := '';
ViewForm := TTaxInvoicesEditAddTaraForm.Create(Self,TaxInvoicesEditDM.DB.Handle,AddParametr);
//ViewForm.TaraButtonEdit.Text := '';
ViewForm.SummaCurrencyEdit.Text := '';
ViewForm.ReadReg;
ViewForm.ShowModal;
if (ViewForm.ModalResult = mrok) then
begin
TaxInvoicesEditDM.WriteTransaction.StartTransaction;
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_SP_VID_NAKL_TARE_INS';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_TARE').Value := ViewForm.Parameter.id_tara;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_TARE').Value := ViewForm.Parameter.Name_tara;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('SUMMA_ALL').Value := ViewForm.SummaCurrencyEdit.Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_VID_NAKL_DOC').Value := id_vid_nakl_doc_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_VID_NAKL_DOC_SUMMA_CALC';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_VID_NAKL_DOC').Value := id_vid_nakl_doc_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.WriteTransaction.Commit;
RefreshButton.Click;
end;
end;
procedure TTaxInvoicesEditAddForm.PodZobCheckBoxClick(Sender: TObject);
begin
PodZobButtonEdit.Enabled := PodZobCheckBox.Checked;
end;
procedure TTaxInvoicesEditAddForm.PodKreditCheckBoxClick(Sender: TObject);
begin
PodKreditButtonEdit.Enabled := PodKreditCheckBox.Checked;
end;
procedure TTaxInvoicesEditAddForm.OsoblPrimCheckBoxClick(Sender: TObject);
begin
SpecialNotesButtonEdit.Enabled := OsoblPrimCheckBox.Checked;
end;
procedure TTaxInvoicesEditAddForm.MortgageTara;
begin
TaxInvoicesEditDM.MortgageTaraDSet.Close;
TaxInvoicesEditDM.MortgageTaraDSet.SelectSQL.Text := 'select * from TI_SP_VID_NAKL_TARE_SEL(:ID) ';
TaxInvoicesEditDM.MortgageTaraDSet.ParamByName('ID').Value := id_vid_nakl_doc_Ins;
TaxInvoicesEditDM.MortgageTaraDSet.Open;
if (TaxInvoicesEditDM.MortgageTaraDSet['summa_all'] = null) then
begin
TaraInsBarButton.Enabled := True;
TaraUpdBarButton.Enabled := False;
TaraDelBarButton.Enabled := False;
MortgageTaraStatusBar.Panels[9].Text := '';
MortgageTaraStatusBar.Panels[1].Text := 'Зворотна(заставна тара)';
end
else
begin
TaraInsBarButton.Enabled := False;
TaraUpdBarButton.Enabled := True;
TaraDelBarButton.Enabled := True;
MortgageTaraStatusBar.Panels[9].Text := TaxInvoicesEditDM.MortgageTaraDSet['summa_all'];
MortgageTaraStatusBar.Panels[1].Text := TaxInvoicesEditDM.MortgageTaraDSet['name_tare'];
end;
if (id_vid_nakl_doc_Ins = -1) then
begin
TaraInsBarButton.Enabled := True;
TaraUpdBarButton.Enabled := False;
TaraDelBarButton.Enabled := False;
MortgageTaraStatusBar.Panels[9].Text := '';
MortgageTaraStatusBar.Panels[1].Text := 'Зворотна(заставна тара)';
end;
end;
procedure TTaxInvoicesEditAddForm.TaraUpdBarButtonClick(Sender: TObject);
var
ViewForm : TTaxInvoicesEditAddTaraForm;
AddParametr : TTITaxInvoicesAddTara;
begin
AddParametr.id_tara := TaxInvoicesEditDM.MortgageTaraDSet['id_tare'];
AddParametr.Name_tara := TaxInvoicesEditDM.MortgageTaraDSet['Name_tare'];
ViewForm := TTaxInvoicesEditAddTaraForm.Create(Self,TaxInvoicesEditDM.DB.Handle,AddParametr);
ViewForm.TaraButtonEdit.Text := TaxInvoicesEditDM.MortgageTaraDSet['Name_tare'];
ViewForm.SummaCurrencyEdit.Text := TaxInvoicesEditDM.MortgageTaraDSet['summa_all'];
// ViewForm.ReadReg;
ViewForm.ShowModal;
if (ViewForm.ModalResult = mrok) then
begin
TaxInvoicesEditDM.WriteTransaction.StartTransaction;
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_SP_VID_NAKL_TARE_UPD';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_TARE').Value := ViewForm.Parameter.id_tara;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_TARE').Value := ViewForm.Parameter.Name_tara;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('SUMMA_ALL').Value := ViewForm.SummaCurrencyEdit.Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_VID_NAKL_DOC').Value := TaxInvoicesEditDM.MortgageTaraDSet['ID_VID_NAKL_DOC'];
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_vid_nakl_tare').Value := TaxInvoicesEditDM.MortgageTaraDSet['id_vid_nakl_tare'];
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_VID_NAKL_DOC_SUMMA_CALC';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_VID_NAKL_DOC').Value := id_vid_nakl_doc_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.WriteTransaction.Commit;
RefreshButton.Click;
end;
end;
procedure TTaxInvoicesEditAddForm.TaraDelBarButtonClick(Sender: TObject);
var
error_message: string;
begin
error_message := 'Ви дійсно бажаєте вилучити '+TaxInvoicesEditDM.MortgageTaraDSet['name_tare']+' ?';
if TiShowMessage('Увага!',error_message,mtConfirmation,[mbYes, mbNo])=mrYes then
begin
try
TaxInvoicesEditDM.WriteTransaction.StartTransaction;
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName:='TI_SP_VID_NAKL_TARE_DEL';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_vid_nakl_tare').Value:=TaxInvoicesEditDM.MortgageTaraDSet['id_vid_nakl_tare'];
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.WriteTransaction.Commit;
RefreshButton.Click;
except on E:Exception do
begin
TiShowMessage('Увага!','не можна видалити цей запис', mtError, [mbOK]);
TaxInvoicesEditDM.WriteTransaction.Rollback;
end;
end;
end;
end;
procedure TTaxInvoicesEditAddForm.DoPrint;
const NameReport = '\Reports\TaxInvoices\1.fr3';
var
num_specialnotes :string;
data_nakl :string;
data_termsdelivery :string;
begin
TaxInvoicesEditDM.Report.LoadFromFile(ExtractFilePath(Application.ExeName)+NameReport,True);
data_nakl := DateToStr(TaxInvoicesEditDM.VidNaklInfoDSet['DATA_VIPISKI']);
TaxInvoicesEditDM.Report.Variables.Clear;
TaxInvoicesEditDM.Report.Variables['D1'] := data_nakl[1];
TaxInvoicesEditDM.Report.Variables['D2'] := data_nakl[2];
TaxInvoicesEditDM.Report.Variables['D3'] := data_nakl[4];
TaxInvoicesEditDM.Report.Variables['D4'] := data_nakl[5];
TaxInvoicesEditDM.Report.Variables['D5'] := data_nakl[7];
TaxInvoicesEditDM.Report.Variables['D6'] := data_nakl[8];
TaxInvoicesEditDM.Report.Variables['D7'] := data_nakl[9];
TaxInvoicesEditDM.Report.Variables['D8'] := data_nakl[10];
if not (TaxInvoicesEditDM.VidNaklInfoDSet['NUM_SPECIALNOTES'] = null) then
begin
num_specialnotes := TaxInvoicesEditDM.VidNaklInfoDSet['NUM_SPECIALNOTES'];
TaxInvoicesEditDM.Report.Variables['NUM1']:= num_specialnotes[1];
TaxInvoicesEditDM.Report.Variables['NUM2']:= num_specialnotes[2];
end
else
begin
TaxInvoicesEditDM.Report.Variables['NUM1']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['NUM2']:= ''''+'''';
end;
if (not (TaxInvoicesEditDM.VidNaklInfoDSet['DATA_TERMSDELIVERY'] = null) and (TaxInvoicesEditDM.VidNaklInfoDSet['DATA_TERMSDELIVERY'] <> '01.01.1900')) then
begin
data_termsdelivery := TaxInvoicesEditDM.VidNaklInfoDSet['DATA_TERMSDELIVERY'];
TaxInvoicesEditDM.Report.Variables['TD1'] := data_termsdelivery[1];
TaxInvoicesEditDM.Report.Variables['TD2'] := data_termsdelivery[2];
TaxInvoicesEditDM.Report.Variables['TD3'] := data_termsdelivery[4];
TaxInvoicesEditDM.Report.Variables['TD4'] := data_termsdelivery[5];
TaxInvoicesEditDM.Report.Variables['TD5'] := data_termsdelivery[7];
TaxInvoicesEditDM.Report.Variables['TD6'] := data_termsdelivery[8];
TaxInvoicesEditDM.Report.Variables['TD7'] := data_termsdelivery[9];
TaxInvoicesEditDM.Report.Variables['TD8'] := data_termsdelivery[10];
end
else
begin
TaxInvoicesEditDM.Report.Variables['TD1'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['TD2'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['TD3'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['TD4'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['TD5'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['TD6'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['TD7'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['TD8'] := ''''+'''';
end;
ModalResult := mrCancel;
//TaxInvoicesEditDM.Report.DesignReport;
//Close;
TaxInvoicesEditDM.Report.ShowReport;
{DSet1.First;
if zDesignReport then Report.DesignReport
else Report.ShowReport; }
end;
procedure TTaxInvoicesEditAddForm.DataVipDateEdit1KeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then PodNumTextEdit.SetFocus;
end;
procedure TTaxInvoicesEditAddForm.PodNumTextEditKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then NumOrderTextEdit.SetFocus;
end;
procedure TTaxInvoicesEditAddForm.OsobaPokupButtonEditKeyPress(
Sender: TObject; var Key: Char);
begin
if Key = #13 then YesButton.SetFocus;
end;
procedure TTaxInvoicesEditAddForm.NumOrderTextEditKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then IPNPokupTextEdit.SetFocus;
end;
procedure TTaxInvoicesEditAddForm.FormActivate(Sender: TObject);
begin
PodNumTextEdit.SetFocus;
end;
procedure TTaxInvoicesEditAddForm.PostavkaButtonEditKeyPress(
Sender: TObject; var Key: Char);
begin
if Key = #13 then DataTermsdelDateEdit.SetFocus;
end;
procedure TTaxInvoicesEditAddForm.DataTermsdelDateEditKeyPress(
Sender: TObject; var Key: Char);
begin
if Key = #13 then NumTermsDelTextEdit.SetFocus;
end;
procedure TTaxInvoicesEditAddForm.NumTermsDelTextEditKeyPress(
Sender: TObject; var Key: Char);
begin
if Key = #13 then YesButton.SetFocus;
end;
procedure TTaxInvoicesEditAddForm.RozraxunokButtonEditKeyPress(
Sender: TObject; var Key: Char);
begin
YesButton.SetFocus;
end;
procedure TTaxInvoicesEditAddForm.PodZobButtonEditKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then PodNumTextEdit.SetFocus;
end;
procedure TTaxInvoicesEditAddForm.PodKreditButtonEditKeyPress(
Sender: TObject; var Key: Char);
begin
if Key = #13 then PodNumTextEdit.SetFocus;
end;
procedure TTaxInvoicesEditAddForm.SpecialNotesButtonEditKeyPress(
Sender: TObject; var Key: Char);
begin
if Key = #13 then PodNumTextEdit.SetFocus;
end;
procedure TTaxInvoicesEditAddForm.IPNPokupTextEditKeyPress(Sender: TObject;
var Key: Char);
var
id_customer :Integer;
begin
if Key = #13 then
begin
if(IPNPokupTextEdit.Text<>'') then
begin
TaxInvoicesEditDM.Customer_DataSet.Close;
TaxInvoicesEditDM.Customer_DataSet.SelectSQL.Text :='select * from TI_CUSTOMER_INFO_IPN(:NALOG_NOM)';
TaxInvoicesEditDM.Customer_DataSet.ParamByName('NALOG_NOM').Value := IPNPokupTextEdit.Text;
TaxInvoicesEditDM.Customer_DataSet.Open;
if not (TaxInvoicesEditDM.Customer_DataSet['ID_CUSTOMER'] = null) then
begin
id_Customer := TaxInvoicesEditDM.Customer_DataSet['ID_CUSTOMER'];
TaxInvoicesEditDM.Customer_DataSet.Close;
TaxInvoicesEditDM.Customer_DataSet.SelectSQL.Text :='select * from TI_CUSTOMER_INFO(:id)';
TaxInvoicesEditDM.Customer_DataSet.ParamByName('id').Value := id_Customer;
TaxInvoicesEditDM.Customer_DataSet.Open;
OsobaPokupButtonEdit.Text := TaxInvoicesEditDM.Customer_DataSet['NAME_CUSTOMER'];
PlacePokupMemo.Text := TaxInvoicesEditDM.Customer_DataSet['ADRESS_CONTRAGENT'];
EdrpTextEdit.Text := TaxInvoicesEditDM.Customer_DataSet['KOD_EDRPOU'];
IPNPokupTextEdit.Text := TaxInvoicesEditDM.Customer_DataSet['NALOG_NOM'];
NumReestrPokupTextEdit.Text := TaxInvoicesEditDM.Customer_DataSet['NNS'];
if (TaxInvoicesEditDM.Customer_DataSet['PHONE_CUSTOMER']<>null)then
TelPokupTextEdit.Text := TaxInvoicesEditDM.Customer_DataSet['PHONE_CUSTOMER']
else
TelPokupTextEdit.Text :='---';
PParameter.id_customer := id_Customer;
PParameter.Name_customer := TaxInvoicesEditDM.Customer_DataSet['NAME_CUSTOMER'];
PParameter.ipn_customer := TaxInvoicesEditDM.Customer_DataSet['NALOG_NOM'];
PParameter.place_customer := TaxInvoicesEditDM.Customer_DataSet['ADRESS_CONTRAGENT'];
PParameter.phone_customer := TelPokupTextEdit.Text;
PParameter.NumReestr_customer := TaxInvoicesEditDM.Customer_DataSet['NNS'];
PParameter.EDRPOU_Customer := TaxInvoicesEditDM.Customer_DataSet['KOD_EDRPOU'];
if ((TaxInvoicesEditDM.Customer_DataSet['full_name_customer'] = '') or (TaxInvoicesEditDM.Customer_DataSet['full_name_customer']=null))then
begin
replaceAbreviatures(TaxInvoicesEditDM.Customer_DataSet['NAME_CUSTOMER']);
PParameter.Full_name_customer := '';
FullNameCheckBox.Checked := True;
FullNameMemo.ReadOnly := False;
SaveFullNameButton.Visible := True;
end
else
begin
FullNameMemo.Text := TaxInvoicesEditDM.Customer_DataSet['full_name_customer'];
PParameter.Full_name_customer := TaxInvoicesEditDM.Customer_DataSet['full_name_customer'];
FullNameCheckBox.Checked := False;
FullNameMemo.ReadOnly := True;
SaveFullNameButton.Visible := False;
end;
OsobaPokupButtonEdit.SetFocus;
end
else
begin
TiShowMessage('Увага!','Немає покупця з таким ІПН!', mtError, [mbYes]);
OsobaPokupButtonEdit.Text := '';
PlacePokupMemo.Text := '';
EdrpTextEdit.Text := '';
NumReestrPokupTextEdit.Text := '';
end;
end
else
OsobaPokupButtonEdit.SetFocus;
end;
end;
procedure TTaxInvoicesEditAddForm.PostavkaCheckBox1Click(Sender: TObject);
begin
PostavkaButtonEdit.Enabled := PostavkaCheckBox.Checked;
DataTermsdelDateEdit.Enabled := PostavkaCheckBox.Checked;
NumTermsDelTextEdit.Enabled := PostavkaCheckBox.Checked;
end;
procedure TTaxInvoicesEditAddForm.RozraxunokCheckBox1Click(Sender: TObject);
begin
RozraxunokButtonEdit.Enabled := RozraxunokCheckBox.Checked;
end;
procedure TTaxInvoicesEditAddForm.RozraxunokCheckBoxClick(Sender: TObject);
begin
RozraxunokButtonEdit.Enabled := RozraxunokCheckBox.Checked;
end;
procedure TTaxInvoicesEditAddForm.PostavkaCheckBoxClick(Sender: TObject);
begin
PostavkaButtonEdit.Enabled := PostavkaCheckBox.Checked;
DataTermsdelDateEdit.Enabled := PostavkaCheckBox.Checked;
NumTermsDelTextEdit.Enabled := PostavkaCheckBox.Checked;
end;
procedure TTaxInvoicesEditAddForm.PhoneCheckBoxClick(Sender: TObject);
begin
TelPokupTextEdit.Enabled := PhoneCheckBox.Checked;
SavePhoneButton.Visible := PhoneCheckBox.Checked;
end;
procedure TTaxInvoicesEditAddForm.FullNameCheckBoxClick(Sender: TObject);
begin
FullNameMemo.ReadOnly := not(FullNameCheckBox.Checked);
SaveFullNameButton.Visible := FullNameCheckBox.Checked;
end;
procedure TTaxInvoicesEditAddForm.SavePhoneButtonClick(Sender: TObject);
begin
{if (TelPokupTextEdit.Text='') then
begin
TiShowMessage('Увага!','Заповніть номер телефону!',mtWarning,[mbOK]);
TelPokupTextEdit.SetFocus;
Exit;
end; }
if (OsobaPokupButtonEdit.Text='') then
begin
TiShowMessage('Увага!','Спочатку оберіть покупця!',mtWarning,[mbOK]);
OsobaPokupButtonEdit.SetFocus;
Exit;
end;
//ShowMessage(IntToStr(PParameter.id_customer));
TaxInvoicesEditDM.WriteTransaction.StartTransaction;
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_SP_CUSTOMER_PHONE_UPD';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_customer').Value := PParameter.id_customer;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('phone_customer').Value := TelPokupTextEdit.Text;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.WriteTransaction.Commit;
PhoneCheckBox.Checked := False;
TelPokupTextEdit.Enabled := False;
SavePhoneButton.Visible := False;
PParameter.phone_customer := TelPokupTextEdit.Text;
end;
procedure TTaxInvoicesEditAddForm.replaceAbreviatures(short_name: string);
var
i : Integer;
short_name_abbreviature : string;
long_name_abbreviature : string;
p :Integer;
begin
TaxInvoicesEditDM.AbbreviatureDSet.Close;
TaxInvoicesEditDM.AbbreviatureDSet.SelectSQL.Text := 'select * from TI_SP_ABBREVIATIONS';
TaxInvoicesEditDM.AbbreviatureDSet.Open;
TaxInvoicesEditDM.AbbreviatureDSet.FetchAll;
TaxInvoicesEditDM.AbbreviatureDSet.First;
//ShowMessage(IntToStr(TaxInvoicesEditDM.AbbreviatureDSet.RecordCount));
for i:=1 to TaxInvoicesEditDM.AbbreviatureDSet.RecordCount do
begin
short_name_abbreviature := TaxInvoicesEditDM.AbbreviatureDSet['short_name'];
long_name_abbreviature := TaxInvoicesEditDM.AbbreviatureDSet['long_name'];
if Pos(short_name_abbreviature,short_name)<>0 then
begin
p :=Pos(short_name_abbreviature,short_name);
if (p=1) then //если стоит в начале строки
begin
if(short_name[p+Length(short_name_abbreviature)] = ' ') then
begin
Delete(short_name,1,Length(short_name_abbreviature));
Insert(long_name_abbreviature,short_name,p);
end;
end;
if (p = (Length(short_name) - Length(short_name_abbreviature)+1)) then //в конце строки
begin
if(short_name[p-1] = ' ') then
begin
Delete(short_name,p,Length(short_name_abbreviature));
Insert(long_name_abbreviature,short_name,1);
end;
end;
if ((p<>1) and (p <> (Length(short_name) - Length(short_name_abbreviature)+1))) then //если в середине
begin
if((short_name[p-1] = ' ') and (short_name[p+Length(short_name_abbreviature)] = ' '))then
begin
Delete(short_name,p,Length(short_name_abbreviature));
Insert(long_name_abbreviature,short_name,p);
end;
end;
end;
TaxInvoicesEditDM.AbbreviatureDSet.Next;
end;
full_name_customer := short_name;
FullNameMemo.Text := full_name_customer;
end;
procedure TTaxInvoicesEditAddForm.SaveFullNameButtonClick(Sender: TObject);
begin
if (FullNameMemo.Text='') then
begin
TiShowMessage('Увага!','Заповніть повну назву покупця!',mtWarning,[mbOK]);
FullNameMemo.SetFocus;
Exit;
end;
if (OsobaPokupButtonEdit.Text='') then
begin
TiShowMessage('Увага!','Спочатку оберіть покупця!',mtWarning,[mbOK]);
OsobaPokupButtonEdit.SetFocus;
Exit;
end;
//ShowMessage(IntToStr(PParameter.id_customer));
TaxInvoicesEditDM.WriteTransaction.StartTransaction;
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_SP_CUSTOMER_FULL_NAME_UPD';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_customer').Value := PParameter.id_customer;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('full_name_customer').Value := FullNameMemo.Text;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.WriteTransaction.Commit;
FullNameCheckBox.Checked := False;
FullNameMemo.ReadOnly := True;
SaveFullNameButton.Visible := False;
PParameter.Full_name_customer := FullNameMemo.Text;
end;
procedure TTaxInvoicesEditAddForm.NumOrderTextEditExit(Sender: TObject);
begin
// PodNumTextEdit.Text := NumOrderTextEdit.Text;
if (TaxInvoicesEditDM.DSet['IS_SAME_NUM_NAKL'] = 1)then
begin
PodNumTextEdit.Text := NumOrderTextEdit.Text;
end
else
begin
PodNumTextEdit.Text := '';
end;
end;
procedure TTaxInvoicesEditAddForm.DataVipDateEditKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then NumOrderTextEdit.SetFocus;
end;
procedure TTaxInvoicesEditAddForm.PlacePokupCheckBoxClick(Sender: TObject);
begin
PlacePokupMemo.Properties.ReadOnly := not(PlacePokupCheckBox.Checked);
SavePlacePokupButton.Visible := PlacePokupCheckBox.Checked;
end;
procedure TTaxInvoicesEditAddForm.SavePlacePokupButtonClick(
Sender: TObject);
begin
if (PlacePokupMemo.Text='') then
begin
TiShowMessage('Увага!','Заповніть повну адресу покупця!',mtWarning,[mbOK]);
PlacePokupMemo.SetFocus;
Exit;
end;
if (OsobaPokupButtonEdit.Text='') then
begin
TiShowMessage('Увага!','Спочатку оберіть покупця!',mtWarning,[mbOK]);
OsobaPokupButtonEdit.SetFocus;
Exit;
end;
//ShowMessage(IntToStr(PParameter.id_customer));
TaxInvoicesEditDM.WriteTransaction.StartTransaction;
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_SP_CUSTOMER_FULL_ADR_UPD';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('id_customer').Value := PParameter.id_customer;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('FULL_ADR_CUSTOMER').Value := PlacePokupMemo.Text;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.WriteTransaction.Commit;
PlacePokupCheckBox.Checked := False;
PlacePokupMemo.Properties.ReadOnly := True;
SavePlacePokupButton.Visible := False;
PParameter.place_customer := PlacePokupMemo.Text;
end;
procedure TTaxInvoicesEditAddForm.DoPrintDecember;
const NameReportDecabr2011 = '\Reports\TaxInvoices\VidNaklDecember.fr3';
const NameReportMart2014 = '\Reports\TaxInvoices\VidNaklMart2014.fr3';
const NameReportDecabr2014 = '\Reports\TaxInvoices\VidNaklDecember2014.fr3';
var
num_specialnotes :string;
data_nakl :string;
data_termsdelivery :string;
NotPDV : string;
ipn_prodavec : string;
ipn_customer : string;
sv_prodavec : string;
sv_customer : string;
tel_prodavec : string;
tel_customer : string;
i : Integer;
num_nakl : string;
begin
NotPDV := 'без ПДВ';
if (TaxInvoicesEditDM.VidNaklInfoDSet['DATA_VIPISKI']<StrtoDate('01.03.2014')) then
TaxInvoicesEditDM.Report.LoadFromFile(ExtractFilePath(Application.ExeName)+NameReportDecabr2011,True)
else
if (TaxInvoicesEditDM.VidNaklInfoDSet['DATA_VIPISKI']>=StrtoDate('01.03.2014'))and(TaxInvoicesEditDM.VidNaklInfoDSet['DATA_VIPISKI']<StrtoDate('01.12.2014')) then
TaxInvoicesEditDM.Report.LoadFromFile(ExtractFilePath(Application.ExeName)+NameReportMart2014,True)
else
TaxInvoicesEditDM.Report.LoadFromFile(ExtractFilePath(Application.ExeName)+NameReportDecabr2014,True);
data_nakl := DateToStr(TaxInvoicesEditDM.VidNaklInfoDSet['DATA_VIPISKI']);
ipn_prodavec := (TaxInvoicesEditDM.VidNaklInfoDSet['ipn_seller']);
ipn_customer := (TaxInvoicesEditDM.VidNaklInfoDSet['ipn_customer']);
sv_prodavec := (TaxInvoicesEditDM.VidNaklInfoDSet['numreestr_seller']);
sv_customer := (TaxInvoicesEditDM.VidNaklInfoDSet['numreestr_customer']);
tel_prodavec := TaxInvoicesEditDM.VidNaklInfoDSet['phone_seller'];
tel_customer := TaxInvoicesEditDM.VidNaklInfoDSet['phone_customer'];
num_nakl := IntToStr(TaxInvoicesEditDM.VidNaklInfoDSet['num_nakl']);
TaxInvoicesEditDM.Report.Variables.Clear;
TaxInvoicesEditDM.Report.Variables['numn1'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['numn2'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['numn3'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['numn4'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['numn5'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['numn6'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['numn7'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp1'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp2'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp3'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp4'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp5'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp6'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp7'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp8'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp9'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp10'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc1'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc2'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc3'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc4'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc5'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc6'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc7'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc8'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc9'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc10'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sp1'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sp2'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sp3'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sp4'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sp5'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sp6'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sp7'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sp8'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sp9'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sp10'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sc1'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sc2'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sc3'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sc4'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sc5'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sc6'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sc7'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sc8'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sc9'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sc10'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['D1'] := data_nakl[1];
TaxInvoicesEditDM.Report.Variables['D2'] := data_nakl[2];
TaxInvoicesEditDM.Report.Variables['D3'] := data_nakl[4];
TaxInvoicesEditDM.Report.Variables['D4'] := data_nakl[5];
TaxInvoicesEditDM.Report.Variables['D5'] := data_nakl[7];
TaxInvoicesEditDM.Report.Variables['D6'] := data_nakl[8];
TaxInvoicesEditDM.Report.Variables['D7'] := data_nakl[9];
TaxInvoicesEditDM.Report.Variables['D8'] := data_nakl[10];
i := 7;
if (num_nakl <> '')then
begin
while Length(num_nakl)>0 do
begin
case i of
1:TaxInvoicesEditDM.Report.Variables['numn1'] := Copy(num_nakl, Length(num_nakl), 1);
2:TaxInvoicesEditDM.Report.Variables['numn2'] := Copy(num_nakl, Length(num_nakl), 1);
3:TaxInvoicesEditDM.Report.Variables['numn3'] := Copy(num_nakl, Length(num_nakl), 1);
4:TaxInvoicesEditDM.Report.Variables['numn4'] := Copy(num_nakl, Length(num_nakl), 1);
5:TaxInvoicesEditDM.Report.Variables['numn5'] := Copy(num_nakl, Length(num_nakl), 1);
6:TaxInvoicesEditDM.Report.Variables['numn6'] := Copy(num_nakl, Length(num_nakl), 1);
7:TaxInvoicesEditDM.Report.Variables['numn7'] := Copy(num_nakl, Length(num_nakl), 1);
end;
Delete(num_nakl, Length(num_nakl), 1);
i:=i-1;
end;
end
else
begin
TaxInvoicesEditDM.Report.Variables['numn1'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['numn2'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['numn3'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['numn4'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['numn5'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['numn6'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['numn7'] := ''''+'''';
end;
i := 10;
if (tel_prodavec <> '')then
begin
while Length(tel_prodavec)>0 do
begin
case i of
1:TaxInvoicesEditDM.Report.Variables['tp1'] := Copy(tel_prodavec, Length(tel_prodavec), 1);
2:TaxInvoicesEditDM.Report.Variables['tp2'] := Copy(tel_prodavec, Length(tel_prodavec), 1);
3:TaxInvoicesEditDM.Report.Variables['tp3'] := Copy(tel_prodavec, Length(tel_prodavec), 1);
4:TaxInvoicesEditDM.Report.Variables['tp4'] := Copy(tel_prodavec, Length(tel_prodavec), 1);
5:TaxInvoicesEditDM.Report.Variables['tp5'] := Copy(tel_prodavec, Length(tel_prodavec), 1);
6:TaxInvoicesEditDM.Report.Variables['tp6'] := Copy(tel_prodavec, Length(tel_prodavec), 1);
7:TaxInvoicesEditDM.Report.Variables['tp7'] := Copy(tel_prodavec, Length(tel_prodavec), 1);
8:TaxInvoicesEditDM.Report.Variables['tp8'] := Copy(tel_prodavec, Length(tel_prodavec), 1);
9:TaxInvoicesEditDM.Report.Variables['tp9'] := Copy(tel_prodavec, Length(tel_prodavec), 1);
10:TaxInvoicesEditDM.Report.Variables['tp10'] := Copy(tel_prodavec, Length(tel_prodavec), 1);
end;
Delete(tel_prodavec, Length(tel_prodavec), 1);
i:=i-1;
end;
end
else
begin
TaxInvoicesEditDM.Report.Variables['tp1'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp2'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp3'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp4'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp5'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp6'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp7'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp8'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp9'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp10'] := ''''+'''';
end;
i := 10;
if (tel_customer<>'')then
begin
while Length(tel_customer)>0 do
begin
case i of
1:TaxInvoicesEditDM.Report.Variables['tc1'] := Copy(tel_customer, Length(tel_customer), 1);
2:TaxInvoicesEditDM.Report.Variables['tc2'] := Copy(tel_customer, Length(tel_customer), 1);
3:TaxInvoicesEditDM.Report.Variables['tc3'] := Copy(tel_customer, Length(tel_customer), 1);
4:TaxInvoicesEditDM.Report.Variables['tc4'] := Copy(tel_customer, Length(tel_customer), 1);
5:TaxInvoicesEditDM.Report.Variables['tc5'] := Copy(tel_customer, Length(tel_customer), 1);
6:TaxInvoicesEditDM.Report.Variables['tc6'] := Copy(tel_customer, Length(tel_customer), 1);
7:TaxInvoicesEditDM.Report.Variables['tc7'] := Copy(tel_customer, Length(tel_customer), 1);
8:TaxInvoicesEditDM.Report.Variables['tc8'] := Copy(tel_customer, Length(tel_customer), 1);
9:TaxInvoicesEditDM.Report.Variables['tc9'] := Copy(tel_customer, Length(tel_customer), 1);
10:TaxInvoicesEditDM.Report.Variables['tc10'] := Copy(tel_customer, Length(tel_customer), 1);
end;
Delete(tel_customer, Length(tel_customer), 1);
i:=i-1;
end;
end
else
begin
TaxInvoicesEditDM.Report.Variables['tc1'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc2'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc3'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc4'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc5'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc6'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc7'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc8'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc9'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc10'] := ''''+'''';
end;
i := 10;
while Length(sv_prodavec)>0 do
begin
case i of
1:TaxInvoicesEditDM.Report.Variables['sp1'] := Copy(sv_prodavec, Length(sv_prodavec), 1);
2:TaxInvoicesEditDM.Report.Variables['sp2'] := Copy(sv_prodavec, Length(sv_prodavec), 1);
3:TaxInvoicesEditDM.Report.Variables['sp3'] := Copy(sv_prodavec, Length(sv_prodavec), 1);
4:TaxInvoicesEditDM.Report.Variables['sp4'] := Copy(sv_prodavec, Length(sv_prodavec), 1);
5:TaxInvoicesEditDM.Report.Variables['sp5'] := Copy(sv_prodavec, Length(sv_prodavec), 1);
6:TaxInvoicesEditDM.Report.Variables['sp6'] := Copy(sv_prodavec, Length(sv_prodavec), 1);
7:TaxInvoicesEditDM.Report.Variables['sp7'] := Copy(sv_prodavec, Length(sv_prodavec), 1);
8:TaxInvoicesEditDM.Report.Variables['sp8'] := Copy(sv_prodavec, Length(sv_prodavec), 1);
9:TaxInvoicesEditDM.Report.Variables['sp9'] := Copy(sv_prodavec, Length(sv_prodavec), 1);
10:TaxInvoicesEditDM.Report.Variables['sp10'] := Copy(sv_prodavec, Length(sv_prodavec), 1);
end;
Delete(sv_prodavec, Length(sv_prodavec), 1);
i:=i-1;
end;
i := 10;
while Length(sv_customer)>0 do
begin
case i of
1:TaxInvoicesEditDM.Report.Variables['sc1'] := Copy(sv_customer, Length(sv_customer), 1);
2:TaxInvoicesEditDM.Report.Variables['sc2'] := Copy(sv_customer, Length(sv_customer), 1);
3:TaxInvoicesEditDM.Report.Variables['sc3'] := Copy(sv_customer, Length(sv_customer), 1);
4:TaxInvoicesEditDM.Report.Variables['sc4'] := Copy(sv_customer, Length(sv_customer), 1);
5:TaxInvoicesEditDM.Report.Variables['sc5'] := Copy(sv_customer, Length(sv_customer), 1);
6:TaxInvoicesEditDM.Report.Variables['sc6'] := Copy(sv_customer, Length(sv_customer), 1);
7:TaxInvoicesEditDM.Report.Variables['sc7'] := Copy(sv_customer, Length(sv_customer), 1);
8:TaxInvoicesEditDM.Report.Variables['sc8'] := Copy(sv_customer, Length(sv_customer), 1);
9:TaxInvoicesEditDM.Report.Variables['sc9'] := Copy(sv_customer, Length(sv_customer), 1);
10:TaxInvoicesEditDM.Report.Variables['sc10'] := Copy(sv_customer, Length(sv_customer), 1);
end;
Delete(sv_customer, Length(sv_customer), 1);
i:=i-1;
end;
if not ((TaxInvoicesEditDM.VidNaklInfoDSet['NUM_SPECIALNOTES'] = null) or (TaxInvoicesEditDM.VidNaklInfoDSet['NUM_SPECIALNOTES'] = '') ) then
begin
num_specialnotes := TaxInvoicesEditDM.VidNaklInfoDSet['NUM_SPECIALNOTES'];
TaxInvoicesEditDM.Report.Variables['NUM1']:= num_specialnotes[1];
TaxInvoicesEditDM.Report.Variables['NUM2']:= num_specialnotes[2];
end
else
begin
TaxInvoicesEditDM.Report.Variables['NUM1']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['NUM2']:= ''''+'''';
end;
if (not (TaxInvoicesEditDM.VidNaklInfoDSet['DATA_TERMSDELIVERY'] = null) and (TaxInvoicesEditDM.VidNaklInfoDSet['DATA_TERMSDELIVERY'] <> '01.01.1900')) then
begin
data_termsdelivery := TaxInvoicesEditDM.VidNaklInfoDSet['DATA_TERMSDELIVERY'];
TaxInvoicesEditDM.Report.Variables['TD1'] := data_termsdelivery[1];
TaxInvoicesEditDM.Report.Variables['TD2'] := data_termsdelivery[2];
TaxInvoicesEditDM.Report.Variables['TD3'] := data_termsdelivery[4];
TaxInvoicesEditDM.Report.Variables['TD4'] := data_termsdelivery[5];
TaxInvoicesEditDM.Report.Variables['TD5'] := data_termsdelivery[7];
TaxInvoicesEditDM.Report.Variables['TD6'] := data_termsdelivery[8];
TaxInvoicesEditDM.Report.Variables['TD7'] := data_termsdelivery[9];
TaxInvoicesEditDM.Report.Variables['TD8'] := data_termsdelivery[10];
end
else
begin
TaxInvoicesEditDM.Report.Variables['TD1'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['TD2'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['TD3'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['TD4'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['TD5'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['TD6'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['TD7'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['TD8'] := ''''+'''';
end;
if ipn_prodavec = '0' then
begin
TaxInvoicesEditDM.Report.Variables['IP1']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IP2']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IP3']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IP4']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IP5']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IP6']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IP7']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IP8']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IP9']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IP10']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IP11']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IP12']:= ipn_prodavec;
end
else
begin
TaxInvoicesEditDM.Report.Variables['IP1'] := ipn_prodavec[1];
TaxInvoicesEditDM.Report.Variables['IP2'] := ipn_prodavec[2];
TaxInvoicesEditDM.Report.Variables['IP3'] := ipn_prodavec[3];
TaxInvoicesEditDM.Report.Variables['IP4'] := ipn_prodavec[4];
TaxInvoicesEditDM.Report.Variables['IP5'] := ipn_prodavec[5];
TaxInvoicesEditDM.Report.Variables['IP6'] := ipn_prodavec[6];
TaxInvoicesEditDM.Report.Variables['IP7'] := ipn_prodavec[7];
TaxInvoicesEditDM.Report.Variables['IP8'] := ipn_prodavec[8];
TaxInvoicesEditDM.Report.Variables['IP9'] := ipn_prodavec[9];
TaxInvoicesEditDM.Report.Variables['IP10']:= ipn_prodavec[10];
TaxInvoicesEditDM.Report.Variables['IP11']:= ipn_prodavec[11];
TaxInvoicesEditDM.Report.Variables['IP12']:= ipn_prodavec[12];
end;
if ipn_customer = '0' then
begin
TaxInvoicesEditDM.Report.Variables['IC1']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IC2']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IC3']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IC4']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IC5']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IC6']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IC7']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IC8']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IC9']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IC10']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IC11']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IC12']:= ipn_customer;
end
else
begin
TaxInvoicesEditDM.Report.Variables['IC1'] := ipn_customer[1];
TaxInvoicesEditDM.Report.Variables['IC2'] := ipn_customer[2];
TaxInvoicesEditDM.Report.Variables['IC3'] := ipn_customer[3];
TaxInvoicesEditDM.Report.Variables['IC4'] := ipn_customer[4];
TaxInvoicesEditDM.Report.Variables['IC5'] := ipn_customer[5];
TaxInvoicesEditDM.Report.Variables['IC6'] := ipn_customer[6];
TaxInvoicesEditDM.Report.Variables['IC7'] := ipn_customer[7];
TaxInvoicesEditDM.Report.Variables['IC8'] := ipn_customer[8];
TaxInvoicesEditDM.Report.Variables['IC9'] := ipn_customer[9];
TaxInvoicesEditDM.Report.Variables['IC10']:= ipn_customer[10];
TaxInvoicesEditDM.Report.Variables['IC11']:= ipn_customer[11];
TaxInvoicesEditDM.Report.Variables['IC12']:= ipn_customer[12];
end;
ModalResult := mrCancel;
//TaxInvoicesEditDM.Report.DesignReport;
//Close;
TaxInvoicesEditDM.Report.ShowReport;
{DSet1.First;
if zDesignReport then Report.DesignReport
else Report.ShowReport; }
end;
procedure TTaxInvoicesEditAddForm.TypeDocumentButtonEditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
TypeDoc:Variant;
begin
TypeDoc := LoadTypeDocumentPackage(owner,TaxInvoicesEditDM.DB.Handle,'TaxInvoices\TypeDocument.bpl','View_TypeDocument',2);
If VarArrayDimCount(TypeDoc)>0 then
begin
PParameter.ID_TYPE_DOCUMENT := TypeDoc[0];
PParameter.NAME_TYPE_DOCUMENT := TypeDoc[1];
TypeDocumentButtonEdit.Text := TypeDoc[1];
{if (OsoblPrimCheckBox.Checked = True) then
begin
// отбор типа причины по типу документа
TaxInvoicesEditDM.WriteTransaction.StartTransaction;
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_SELECT_SPECIALNOTES_TYPE_DOC';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_TYPE_DOC').Value := PParameter.ID_TYPE_DOCUMENT;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.WriteTransaction.Commit;
PParameter.id_SpecialNotes := TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_SPECIALNOTES').Value;
PParameter.Name_SpecialNotes := TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NUM_SPECIALNOTES').Value;
SpecialNotesButtonEdit.Text := TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_SPECIALNOTES').Value;
end;}
end;
end;
procedure TTaxInvoicesEditAddForm.DoPrintDecemberTwoEkz;
const NameReportDecabr2011 = '\Reports\TaxInvoices\VidNaklDecemberTwoEkz.fr3';
const NameReportMart2014 = '\Reports\TaxInvoices\VidNaklMart2014TwoEkz.fr3';
const NameReportDecabr2014='\Reports\TaxInvoices\VidNaklDecember2014TwoEkz.fr3';
var
num_specialnotes : string;
data_nakl : string;
data_termsdelivery : string;
ipn_prodavec : string;
ipn_customer : string;
sv_prodavec : string;
sv_customer : string;
tel_prodavec : string;
tel_customer : string;
i : Integer;
NotPDV : string;
num_nakl : string;
begin
NotPDV := 'без ПДВ';
if (TaxInvoicesEditDM.VidNaklInfoDSet['DATA_VIPISKI']<StrtoDate('01.03.2014')) then
TaxInvoicesEditDM.Report.LoadFromFile(ExtractFilePath(Application.ExeName)+NameReportDecabr2011,True)
else
if (TaxInvoicesEditDM.VidNaklInfoDSet['DATA_VIPISKI']>=StrtoDate('01.03.2014'))and(TaxInvoicesEditDM.VidNaklInfoDSet['DATA_VIPISKI']<StrtoDate('01.12.2014')) then
TaxInvoicesEditDM.Report.LoadFromFile(ExtractFilePath(Application.ExeName)+NameReportMart2014,True)
else
TaxInvoicesEditDM.Report.LoadFromFile(ExtractFilePath(Application.ExeName)+NameReportDecabr2014,True);
data_nakl := DateToStr(TaxInvoicesEditDM.VidNaklInfoDSet['DATA_VIPISKI']);
ipn_prodavec := (TaxInvoicesEditDM.VidNaklInfoDSet['ipn_seller']);
ipn_customer := (TaxInvoicesEditDM.VidNaklInfoDSet['ipn_customer']);
sv_prodavec := (TaxInvoicesEditDM.VidNaklInfoDSet['numreestr_seller']);
sv_customer := (TaxInvoicesEditDM.VidNaklInfoDSet['numreestr_customer']);
tel_prodavec := TaxInvoicesEditDM.VidNaklInfoDSet['phone_seller'];
tel_customer := TaxInvoicesEditDM.VidNaklInfoDSet['phone_customer'];
num_nakl := IntToStr(TaxInvoicesEditDM.VidNaklInfoDSet['num_nakl']);
TaxInvoicesEditDM.Report.Variables.Clear;
TaxInvoicesEditDM.Report.Variables['numn1'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['numn2'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['numn3'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['numn4'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['numn5'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['numn6'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['numn7'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp1'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp2'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp3'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp4'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp5'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp6'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp7'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp8'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp9'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp10'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc1'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc2'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc3'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc4'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc5'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc6'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc7'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc8'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc9'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc10'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sp1'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sp2'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sp3'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sp4'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sp5'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sp6'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sp7'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sp8'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sp9'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sp10'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sc1'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sc2'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sc3'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sc4'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sc5'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sc6'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sc7'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sc8'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sc9'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['sc10'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['D1'] := data_nakl[1];
TaxInvoicesEditDM.Report.Variables['D2'] := data_nakl[2];
TaxInvoicesEditDM.Report.Variables['D3'] := data_nakl[4];
TaxInvoicesEditDM.Report.Variables['D4'] := data_nakl[5];
TaxInvoicesEditDM.Report.Variables['D5'] := data_nakl[7];
TaxInvoicesEditDM.Report.Variables['D6'] := data_nakl[8];
TaxInvoicesEditDM.Report.Variables['D7'] := data_nakl[9];
TaxInvoicesEditDM.Report.Variables['D8'] := data_nakl[10];
i := 7;
if (num_nakl <> '')then
begin
while Length(num_nakl)>0 do
begin
case i of
1:TaxInvoicesEditDM.Report.Variables['numn1'] := Copy(num_nakl, Length(num_nakl), 1);
2:TaxInvoicesEditDM.Report.Variables['numn2'] := Copy(num_nakl, Length(num_nakl), 1);
3:TaxInvoicesEditDM.Report.Variables['numn3'] := Copy(num_nakl, Length(num_nakl), 1);
4:TaxInvoicesEditDM.Report.Variables['numn4'] := Copy(num_nakl, Length(num_nakl), 1);
5:TaxInvoicesEditDM.Report.Variables['numn5'] := Copy(num_nakl, Length(num_nakl), 1);
6:TaxInvoicesEditDM.Report.Variables['numn6'] := Copy(num_nakl, Length(num_nakl), 1);
7:TaxInvoicesEditDM.Report.Variables['numn7'] := Copy(num_nakl, Length(num_nakl), 1);
end;
Delete(num_nakl, Length(num_nakl), 1);
i:=i-1;
end;
end
else
begin
TaxInvoicesEditDM.Report.Variables['numn1'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['numn2'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['numn3'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['numn4'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['numn5'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['numn6'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['numn7'] := ''''+'''';
end;
i := 10;
if (tel_prodavec <> '')then
begin
while Length(tel_prodavec)>0 do
begin
case i of
1:TaxInvoicesEditDM.Report.Variables['tp1'] := Copy(tel_prodavec, Length(tel_prodavec), 1);
2:TaxInvoicesEditDM.Report.Variables['tp2'] := Copy(tel_prodavec, Length(tel_prodavec), 1);
3:TaxInvoicesEditDM.Report.Variables['tp3'] := Copy(tel_prodavec, Length(tel_prodavec), 1);
4:TaxInvoicesEditDM.Report.Variables['tp4'] := Copy(tel_prodavec, Length(tel_prodavec), 1);
5:TaxInvoicesEditDM.Report.Variables['tp5'] := Copy(tel_prodavec, Length(tel_prodavec), 1);
6:TaxInvoicesEditDM.Report.Variables['tp6'] := Copy(tel_prodavec, Length(tel_prodavec), 1);
7:TaxInvoicesEditDM.Report.Variables['tp7'] := Copy(tel_prodavec, Length(tel_prodavec), 1);
8:TaxInvoicesEditDM.Report.Variables['tp8'] := Copy(tel_prodavec, Length(tel_prodavec), 1);
9:TaxInvoicesEditDM.Report.Variables['tp9'] := Copy(tel_prodavec, Length(tel_prodavec), 1);
10:TaxInvoicesEditDM.Report.Variables['tp10'] := Copy(tel_prodavec, Length(tel_prodavec), 1);
end;
Delete(tel_prodavec, Length(tel_prodavec), 1);
i:=i-1;
end;
end
else
begin
TaxInvoicesEditDM.Report.Variables['tp1'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp2'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp3'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp4'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp5'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp6'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp7'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp8'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp9'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tp10'] := ''''+'''';
end;
i := 10;
if (tel_customer<>'')then
begin
while Length(tel_customer)>0 do
begin
case i of
1:TaxInvoicesEditDM.Report.Variables['tc1'] := Copy(tel_customer, Length(tel_customer), 1);
2:TaxInvoicesEditDM.Report.Variables['tc2'] := Copy(tel_customer, Length(tel_customer), 1);
3:TaxInvoicesEditDM.Report.Variables['tc3'] := Copy(tel_customer, Length(tel_customer), 1);
4:TaxInvoicesEditDM.Report.Variables['tc4'] := Copy(tel_customer, Length(tel_customer), 1);
5:TaxInvoicesEditDM.Report.Variables['tc5'] := Copy(tel_customer, Length(tel_customer), 1);
6:TaxInvoicesEditDM.Report.Variables['tc6'] := Copy(tel_customer, Length(tel_customer), 1);
7:TaxInvoicesEditDM.Report.Variables['tc7'] := Copy(tel_customer, Length(tel_customer), 1);
8:TaxInvoicesEditDM.Report.Variables['tc8'] := Copy(tel_customer, Length(tel_customer), 1);
9:TaxInvoicesEditDM.Report.Variables['tc9'] := Copy(tel_customer, Length(tel_customer), 1);
10:TaxInvoicesEditDM.Report.Variables['tc10'] := Copy(tel_customer, Length(tel_customer), 1);
end;
Delete(tel_customer, Length(tel_customer), 1);
i:=i-1;
end;
end
else
begin
TaxInvoicesEditDM.Report.Variables['tc1'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc2'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc3'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc4'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc5'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc6'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc7'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc8'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc9'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['tc10'] := ''''+'''';
end;
i := 10;
while Length(sv_prodavec)>0 do
begin
case i of
1:TaxInvoicesEditDM.Report.Variables['sp1'] := Copy(sv_prodavec, Length(sv_prodavec), 1);
2:TaxInvoicesEditDM.Report.Variables['sp2'] := Copy(sv_prodavec, Length(sv_prodavec), 1);
3:TaxInvoicesEditDM.Report.Variables['sp3'] := Copy(sv_prodavec, Length(sv_prodavec), 1);
4:TaxInvoicesEditDM.Report.Variables['sp4'] := Copy(sv_prodavec, Length(sv_prodavec), 1);
5:TaxInvoicesEditDM.Report.Variables['sp5'] := Copy(sv_prodavec, Length(sv_prodavec), 1);
6:TaxInvoicesEditDM.Report.Variables['sp6'] := Copy(sv_prodavec, Length(sv_prodavec), 1);
7:TaxInvoicesEditDM.Report.Variables['sp7'] := Copy(sv_prodavec, Length(sv_prodavec), 1);
8:TaxInvoicesEditDM.Report.Variables['sp8'] := Copy(sv_prodavec, Length(sv_prodavec), 1);
9:TaxInvoicesEditDM.Report.Variables['sp9'] := Copy(sv_prodavec, Length(sv_prodavec), 1);
10:TaxInvoicesEditDM.Report.Variables['sp10'] := Copy(sv_prodavec, Length(sv_prodavec), 1);
end;
Delete(sv_prodavec, Length(sv_prodavec), 1);
i:=i-1;
end;
i := 10;
while Length(sv_customer)>0 do
begin
case i of
1:TaxInvoicesEditDM.Report.Variables['sc1'] := Copy(sv_customer, Length(sv_customer), 1);
2:TaxInvoicesEditDM.Report.Variables['sc2'] := Copy(sv_customer, Length(sv_customer), 1);
3:TaxInvoicesEditDM.Report.Variables['sc3'] := Copy(sv_customer, Length(sv_customer), 1);
4:TaxInvoicesEditDM.Report.Variables['sc4'] := Copy(sv_customer, Length(sv_customer), 1);
5:TaxInvoicesEditDM.Report.Variables['sc5'] := Copy(sv_customer, Length(sv_customer), 1);
6:TaxInvoicesEditDM.Report.Variables['sc6'] := Copy(sv_customer, Length(sv_customer), 1);
7:TaxInvoicesEditDM.Report.Variables['sc7'] := Copy(sv_customer, Length(sv_customer), 1);
8:TaxInvoicesEditDM.Report.Variables['sc8'] := Copy(sv_customer, Length(sv_customer), 1);
9:TaxInvoicesEditDM.Report.Variables['sc9'] := Copy(sv_customer, Length(sv_customer), 1);
10:TaxInvoicesEditDM.Report.Variables['sc10'] := Copy(sv_customer, Length(sv_customer), 1);
end;
Delete(sv_customer, Length(sv_customer), 1);
i:=i-1;
end;
if ((TaxInvoicesEditDM.VidNaklInfoDSet['NAME_SPECIALNOTES_TWO_EKZ'] <>null) and (TaxInvoicesEditDM.VidNaklInfoDSet['NAME_SPECIALNOTES_TWO_EKZ'] <>''))then
begin
num_specialnotes := TaxInvoicesEditDM.VidNaklInfoDSet['NUM_SPECIALNOTES_TWO_EKZ'];
TaxInvoicesEditDM.Report.Variables['NUM1']:= num_specialnotes[1];
TaxInvoicesEditDM.Report.Variables['NUM2']:= num_specialnotes[2];
end
else
begin
TaxInvoicesEditDM.Report.Variables['NUM1']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['NUM2']:= ''''+'''';
end;
if (not (TaxInvoicesEditDM.VidNaklInfoDSet['DATA_TERMSDELIVERY'] = null) and (TaxInvoicesEditDM.VidNaklInfoDSet['DATA_TERMSDELIVERY'] <> '01.01.1900')) then
begin
data_termsdelivery := TaxInvoicesEditDM.VidNaklInfoDSet['DATA_TERMSDELIVERY'];
TaxInvoicesEditDM.Report.Variables['TD1'] := data_termsdelivery[1];
TaxInvoicesEditDM.Report.Variables['TD2'] := data_termsdelivery[2];
TaxInvoicesEditDM.Report.Variables['TD3'] := data_termsdelivery[4];
TaxInvoicesEditDM.Report.Variables['TD4'] := data_termsdelivery[5];
TaxInvoicesEditDM.Report.Variables['TD5'] := data_termsdelivery[7];
TaxInvoicesEditDM.Report.Variables['TD6'] := data_termsdelivery[8];
TaxInvoicesEditDM.Report.Variables['TD7'] := data_termsdelivery[9];
TaxInvoicesEditDM.Report.Variables['TD8'] := data_termsdelivery[10];
end
else
begin
TaxInvoicesEditDM.Report.Variables['TD1'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['TD2'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['TD3'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['TD4'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['TD5'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['TD6'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['TD7'] := ''''+'''';
TaxInvoicesEditDM.Report.Variables['TD8'] := ''''+'''';
end;
if ipn_prodavec = '0' then
begin
TaxInvoicesEditDM.Report.Variables['IP1']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IP2']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IP3']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IP4']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IP5']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IP6']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IP7']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IP8']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IP9']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IP10']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IP11']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IP12']:= ipn_prodavec;
end
else
begin
TaxInvoicesEditDM.Report.Variables['IP1'] := ipn_prodavec[1];
TaxInvoicesEditDM.Report.Variables['IP2'] := ipn_prodavec[2];
TaxInvoicesEditDM.Report.Variables['IP3'] := ipn_prodavec[3];
TaxInvoicesEditDM.Report.Variables['IP4'] := ipn_prodavec[4];
TaxInvoicesEditDM.Report.Variables['IP5'] := ipn_prodavec[5];
TaxInvoicesEditDM.Report.Variables['IP6'] := ipn_prodavec[6];
TaxInvoicesEditDM.Report.Variables['IP7'] := ipn_prodavec[7];
TaxInvoicesEditDM.Report.Variables['IP8'] := ipn_prodavec[8];
TaxInvoicesEditDM.Report.Variables['IP9'] := ipn_prodavec[9];
TaxInvoicesEditDM.Report.Variables['IP10']:= ipn_prodavec[10];
TaxInvoicesEditDM.Report.Variables['IP11']:= ipn_prodavec[11];
TaxInvoicesEditDM.Report.Variables['IP12']:= ipn_prodavec[12];
end;
if ipn_customer = '0' then
begin
TaxInvoicesEditDM.Report.Variables['IC1']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IC2']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IC3']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IC4']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IC5']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IC6']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IC7']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IC8']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IC9']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IC10']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IC11']:= ''''+'''';
TaxInvoicesEditDM.Report.Variables['IC12']:= ipn_customer;
end
else
begin
TaxInvoicesEditDM.Report.Variables['IC1'] := ipn_customer[1];
TaxInvoicesEditDM.Report.Variables['IC2'] := ipn_customer[2];
TaxInvoicesEditDM.Report.Variables['IC3'] := ipn_customer[3];
TaxInvoicesEditDM.Report.Variables['IC4'] := ipn_customer[4];
TaxInvoicesEditDM.Report.Variables['IC5'] := ipn_customer[5];
TaxInvoicesEditDM.Report.Variables['IC6'] := ipn_customer[6];
TaxInvoicesEditDM.Report.Variables['IC7'] := ipn_customer[7];
TaxInvoicesEditDM.Report.Variables['IC8'] := ipn_customer[8];
TaxInvoicesEditDM.Report.Variables['IC9'] := ipn_customer[9];
TaxInvoicesEditDM.Report.Variables['IC10']:= ipn_customer[10];
TaxInvoicesEditDM.Report.Variables['IC11']:= ipn_customer[11];
TaxInvoicesEditDM.Report.Variables['IC12']:= ipn_customer[12];
end;
ModalResult := mrCancel;
//TaxInvoicesEditDM.Report.DesignReport;
//Close;
TaxInvoicesEditDM.Report.ShowReport;
{DSet1.First;
if zDesignReport then Report.DesignReport
else Report.ShowReport; }
end;
procedure TTaxInvoicesEditAddForm.ToolButton_addClick(Sender: TObject);
var
Add: Variant;
cnt,i: Integer;
id_adding_flag:Integer;
id_smeta : Int64;
id_dt_smet : Int64;
summa_NDS : Double;
summa_Not_NDS : Double;
num_st : string;
begin
id_adding_flag:=1;
Add := LoadDogManedger.AddKosht(self,TaxInvoicesEditDM.DB.Handle,-1,1,0,0,0,0,0,date);
if VarArrayDimCount(Add) > 0 then
begin
{
Cnt := VarArrayHighBound(Add, 1);
Проверка, есть ли однаковые разделы, кеквы, статьи }
i:=0;
if TaxInvoicesEditDM.rxMemoryData_smet.Locate('id_smet',Add[i][7],[])=true then
begin
if TaxInvoicesEditDM.RxMemoryData_smet.Locate('id_razd',Add[i][8],[])=true then
begin
if TaxInvoicesEditDM.rxMemoryData_smet.Locate('id_stat',Add[i][9],[])=true then
begin
if TaxInvoicesEditDM.RxMemoryData_smet.Locate('id_kekv',Add[i][10],[])=true then
begin
// MessageBox(0,'Found','Update',MB_OK);
TaxInvoicesEditDM.RxMemoryData_smet.Open;
TaxInvoicesEditDM.RxMemoryData_smet.Edit;
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('sum_smet').Value := Add[i][3]+TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('sum_smet').Value;
TaxInvoicesEditDM.RxMemoryData_smet.Post;
id_adding_flag:=0;
end;
end;
end;
end;
//DoCheckBgt(Add[i][7],rate_acc_un);
if id_adding_flag = 1 then
begin
for i := 0 to Cnt do
begin
//id_smeta := Add[i][7];
//id_dt_smet := TaxInvoicesDM.RxMemoryData_smet.FieldByName('id').AsVariant;
TaxInvoicesEditDM.RxMemoryData_smet.Locate('id', id_dt_smet, []);
TaxInvoicesEditDM.RxMemoryData_smet.Open;
TaxInvoicesEditDM.RxMemoryData_smet.Insert;
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('id_smet').Value := Add[i][7];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('id_razd').Value := Add[i][8];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('id_stat').Value := Add[i][9];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('sum_smet').Value := Add[i][3];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('name_smet').Value := Add[i][0];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('name_razd').Value := Add[i][1];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('name_stat').Value := Add[i][2];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('kod_smety').Value := Add[i][4];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('n_razd').Value := Add[i][5];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('n_stat').Value := Add[i][6];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('id_kekv').Value := Add[i][10];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('kod_kekv').Value := Add[i][11];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('name_kekv').Value := Add[i][12];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('id').Value := 0;
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('flag_del').Value := 0;
TaxInvoicesEditDM.RxMemoryData_smet.Post;
end;
end;
// SumNds();
end;
end;
procedure TTaxInvoicesEditAddForm.SpeedButton_redClick(Sender: TObject);
var
Add: Variant;
cnt,i: Integer;
id_adding_flag:Integer;
id_smeta : Int64;
id_dt_smet : Int64;
summa_old_Not_NDS : Double;
summa_old_NDS : Double;
summa_NDS : Double;
summa_Not_NDS : Double;
begin
if TaxInvoicesEditDM.RxMemoryData_smet.RecordCount = 0 then Exit;
if TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('n_stat').Value = '7300' then
begin
summa_NDS := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('sum_smet').AsCurrency;
end
else
summa_Not_NDS := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('sum_smet').AsCurrency;
Add := LoadDogManedger.AddKosht(self,TaxInvoicesEditDM.DB.Handle,-1,2,
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('id_smet').AsInteger,
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('id_razd').AsInteger,
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('id_stat').AsInteger,
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('id_kekv').AsInteger,
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('sum_smet').AsCurrency,date);
if VarArrayDimCount(Add) > 0 then
begin
i:=0;
TaxInvoicesEditDM.RxMemoryData_smet.Open;
TaxInvoicesEditDM.RxMemoryData_smet.edit;
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('id_smet').Value := Add[i][7];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('id_razd').Value := Add[i][8];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('id_stat').Value := Add[i][9];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('sum_smet').Value := Add[i][3];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('name_smet').Value := Add[i][0];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('name_razd').Value := Add[i][1];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('name_stat').Value := Add[i][2];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('kod_smety').Value := Add[i][4];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('n_razd').Value := Add[i][5];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('n_stat').Value := Add[i][6];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('id_kekv').Value := Add[i][10];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('kod_kekv').Value := Add[i][11];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('name_kekv').Value := Add[i][12];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('id').Value := 0;
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('flag_del').Value := 0;
TaxInvoicesEditDM.RxMemoryData_smet.Post;
end;
end;
procedure TTaxInvoicesEditAddForm.ToolButton_delClick(Sender: TObject);
var
summa_old_Not_NDS : Double;
summa_old_NDS : Double;
summa_NDS : Double;
summa_Not_NDS : Double;
begin
if TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('n_stat').Value = '7300' then
begin
summa_NDS := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('sum_smet').AsCurrency;
end
else
if TaxInvoicesEditDM.RxMemoryData_smet.RecordCount = 0 then Exit;
TaxInvoicesEditDM.RxMemoryData_smet.Delete;
end;
procedure TTaxInvoicesEditAddForm.BudgetButtonClick(Sender: TObject);
var
ViewForm : TTaxInvoicesEditBudgetForm;
i : Integer;
KEY_SESSION : Int64;
STRU : KERNEL_MODE_STRUCTURE;
DoResult : Boolean;
ErrorList : TStringList;
s : string;
j : integer;
workdate : TDate;
pk_id : int64;
sum_All_Nds : Double;
sum_All_Not_NDS : Double;
summa_val_deliv_20 :Double;
summa_tax : Double;
summa_val_deliv_vat_extemptions : Double;
begin
RefreshButtonClick(Self);
// ничего не делать, если старая налоговая
if (TaxInvoicesEditDM.VidNaklInfoDSet['pk_id']='-1') then Exit;
//проверка на пустоту сумм
if (TaxInvoicesEditDM.VidNaklInfoDSet['summa_val_deliv_20'] = null) then
summa_val_deliv_20 := 0
else
summa_val_deliv_20 := TaxInvoicesEditDM.VidNaklInfoDSet['summa_val_deliv_20'];
if (TaxInvoicesEditDM.VidNaklInfoDSet['summa_tax'] = null) then
summa_tax := 0
else
summa_tax := TaxInvoicesEditDM.VidNaklInfoDSet['summa_tax'];
if (TaxInvoicesEditDM.VidNaklInfoDSet['summa_val_deliv_vat_extemptions'] = null) then
summa_val_deliv_vat_extemptions := 0
else
summa_val_deliv_vat_extemptions := TaxInvoicesEditDM.VidNaklInfoDSet['summa_val_deliv_vat_extemptions'];
if ((summa_tax = 0) and (summa_val_deliv_vat_extemptions = 0) and (summa_val_deliv_20 = 0)) then
begin
ShowMessage('Заповніть суми податкової накладної');
Exit;
end;
ViewForm := TTaxInvoicesEditBudgetForm.Create(Self,TaxInvoicesEditDM.DB.Handle, TaxInvoicesEditDM);
ViewForm.Label_val_deliv_20.Caption := FloatToStrF(summa_val_deliv_20,ffFixed,10,2);
ViewForm.Label_Tax.Caption := FloatToStrF(summa_tax,ffFixed,10,2);
ViewForm.Label_vat_extemption.Caption := FloatToStrF(summa_val_deliv_vat_extemptions,ffFixed,10,2);
// отображение проводок
for i := 0 to TaxInvoicesEditDM.RxMemoryData_smet.RecordCount - 1 do
TaxInvoicesEditDM.RxMemoryData_smet.Delete;
TaxInvoicesEditDM.Smeta_Vid_N_DSet.Close;
TaxInvoicesEditDM.Smeta_Vid_N_DSet.SelectSQL.Text := 'select * from TI_BUDGET_NDS_SEL where id_nakl = :id and is_vid = 1';
TaxInvoicesEditDM.Smeta_Vid_N_DSet.ParamByName('id').Value := id_vid_nakl_Ins;
TaxInvoicesEditDM.Smeta_Vid_N_DSet.Open;
TaxInvoicesEditDM.Smeta_Vid_N_DSet.FetchAll;
TaxInvoicesEditDM.Smeta_Vid_N_DSet.First;
sum_All_Nds := 0;
sum_All_Not_NDS := 0;
for i := 0 to TaxInvoicesEditDM.Smeta_Vid_N_DSet.RecordCount-1 do
begin
TaxInvoicesEditDM.RxMemoryData_smet.Open;
TaxInvoicesEditDM.RxMemoryData_smet.Insert;
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('id_smet').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['id_smet'];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('id_razd').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['id_razd'];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('id_stat').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['id_stat'];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('sum_smet').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['sum_smet'];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('name_smet').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['name_smet'];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('name_razd').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['name_razd'];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('name_stat').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['name_stat'];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('kod_smety').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['kod_smety'];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('n_razd').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['n_razd'];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('n_stat').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['n_stat'];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('id_kekv').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['id_kekv'];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('kod_kekv').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['kod_kekv'];
TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('name_kekv').Value := TaxInvoicesEditDM.Smeta_Vid_N_DSet['name_kekv'];
TaxInvoicesEditDM.RxMemoryData_smet.Post;
TaxInvoicesEditDM.Smeta_Vid_N_DSet.Next;
if TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('n_stat').Value = '7300' then
sum_All_Nds := sum_All_Nds + TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('sum_smet').Value
else
sum_All_Not_NDS := sum_All_Not_NDS + TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('sum_smet').Value;
end;
if TaxInvoicesEditDM.Smeta_Vid_N_DSet.IsEmpty = True then
begin
ViewForm.Label21.Caption := '';
ViewForm.Label22.Caption := '';
ViewForm.Label23.Caption := '';
ViewForm.Label26.Caption := '';
ViewForm.LabelNotPDV.Caption := '0';
ViewForm.LabelPDV.Caption := '0';
end
else
begin
ViewForm.LabelNotPDV.Caption := Floattostr(sum_All_Not_NDS);
ViewForm.LabelPDV.Caption := Floattostr(sum_All_Nds);
end;
{if TaxInvoicesEditDM.VidNaklInfoDSet['pk_id']= null
then pk_id := 0
else pk_id := StrToInt64(TaxInvoicesEditDM.VidNaklInfoDSet.FieldByName('pk_id').AsString); }
{if ((pk_id = 0) or (pk_id = -1))
then
ViewForm.provodka := False
else
ViewForm.provodka := True;}
ViewForm.ShowModal;
if (ViewForm.ModalResult = mrok) then
begin
if TaxInvoicesEditDM.VidNaklInfoDSet['pk_id'] = '0' then
begin
//осуществить проводку
TaxInvoicesEditDM.WriteTransaction.StartTransaction;
//изменение проводок
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_BUDGET_NDS_DEL'; // удаляем все проводки и перезаписываем
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_NAKL').Value := id_vid_nakl_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('is_vid').Value := 1 ;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
// добавление проводок в таблицу TI_BUDGET_NDS
TaxInvoicesEditDM.RxMemoryData_smet.First;
for i:=0 to TaxInvoicesEditDM.RxMemoryData_smet.RecordCount - 1 do
begin
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_BUDGET_NDS_INS';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_NAKL').Value := id_vid_nakl_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_SMET').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('ID_SMET').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_RAZD').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('ID_RAZD').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_STAT').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('ID_STAT').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('SUM_SMET').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('SUM_SMET').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_SMET').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('NAME_SMET').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_RAZD').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('NAME_RAZD').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_STAT').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('NAME_STAT').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('KOD_SMETY').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('KOD_SMETY').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('N_RAZD').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('N_RAZD').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('N_STAT').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('N_STAT').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_KEKV').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('ID_KEKV').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('KOD_KEKV').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('KOD_KEKV').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_KEKV').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('NAME_KEKV').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IS_VID').Value := 1;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IS_LGOTA').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.RxMemoryData_smet.Next;
end;
//если есть НДС - осуществляем проводку в бухгалтерию
//TaxInvoicesEditDM.WriteTransaction.Commit;
// TaxInvoicesEditDM.WriteTransaction.StartTransaction;
if StrToFloat(ViewForm.Label_Tax.Caption)<>0 then
begin
//добавление проводок в буфера
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_PROVODKA_VID_NAKL';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_VID_NAKL').Value := id_vid_nakl_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IP_ADRESS_COMPUTER').Value := TaxInvoicesUser.ip_computer;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
// добавление проводки
KEY_SESSION := TaxInvoicesEditDM.pFIBStoredProc.ParamByName('KEY_SESSION_DOC').value;
workdate := TaxInvoicesEditDM.pFIBStoredProc.ParamByName('DATE_PROV').value;
//ShowMessage(IntToStr(KEY_SESSION));
STRU.KEY_SESSION := KEY_SESSION;
STRU.WORKDATE := WORKDATE;
STRU.DBHANDLE := TaxInvoicesEditDM.DB.Handle;
STRU.TRHANDLE := TaxInvoicesEditDM.WriteTransaction.Handle;
STRU.KERNEL_ACTION := 1;
STRU.ID_USER := TaxInvoicesUser.id_user;
try
DoResult:=Kernel.KernelDo(@STRU);
except
on E:Exception do
begin
ShowMessage('Помилка ядра ' + E.Message);
TaxInvoicesEditDM.WriteTransaction.Rollback;
Exit;
end;
end;
if not DoResult then
begin
ErrorList := Kernel.GetDocErrorsListEx(@STRU);
s := '';
for j:=0 to ErrorList.Count - 1 do
begin
if s <> '' then s := s + #13;
s := s + ErrorList.Strings[j];
end;
ShowMessage(s);
TaxInvoicesEditDM.WriteTransaction.Rollback;
Exit;
end;
end;
TaxInvoicesEditDM.WriteTransaction.Commit;
end
//если это изменение бюджетов удалить всё и записать новую проводку
else
begin
TaxInvoicesEditDM.WriteTransaction.StartTransaction;
//изменение проводок
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_BUDGET_NDS_DEL'; // удаляем все проводки и перезаписываем
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_NAKL').Value := id_vid_nakl_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('is_vid').Value := 1;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.RxMemoryData_smet.First;
for i:=0 to TaxInvoicesEditDM.RxMemoryData_smet.RecordCount - 1 do //записываем новые
begin
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_BUDGET_NDS_INS';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_NAKL').Value := id_vid_nakl_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_SMET').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('ID_SMET').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_RAZD').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('ID_RAZD').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_STAT').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('ID_STAT').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('SUM_SMET').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('SUM_SMET').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_SMET').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('NAME_SMET').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_RAZD').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('NAME_RAZD').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_STAT').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('NAME_STAT').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('KOD_SMETY').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('KOD_SMETY').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('N_RAZD').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('N_RAZD').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('N_STAT').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('N_STAT').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_KEKV').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('ID_KEKV').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('KOD_KEKV').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('KOD_KEKV').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('NAME_KEKV').Value := TaxInvoicesEditDM.RxMemoryData_smet.FieldByName('NAME_KEKV').Value;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IS_VID').Value := 1;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IS_LGOTA').Value := 0;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.RxMemoryData_smet.Next;
end;
KEY_SESSION := TaxInvoicesEditDM.DB.Gen_Id('KERNEL_GEN_ID_SESSION', 1);
STRU.KEY_SESSION := KEY_SESSION;
STRU.WORKDATE := TaxInvoicesEditDM.VidNaklInfoDSet['date_prov'];
STRU.DBHANDLE := TaxInvoicesEditDM.DB.Handle;
STRU.TRHANDLE := TaxInvoicesEditDM.WriteTransaction.Handle;
STRU.KERNEL_ACTION := 2;
STRU.PK_ID := StrToInt64(TaxInvoicesEditDM.VidNaklInfoDSet.FieldByName('pk_id').AsString);
STRU.ID_USER := TaxInvoicesUser.id_user;
try
DoResult:=Kernel.KernelDo(@STRU);
// TaxInvoicesDM.WriteTransaction.Commit;
except
on E:Exception do
begin
ShowMessage('Помилка ядра ' + E.Message);
TaxInvoicesEditDM.WriteTransaction.Rollback;
Exit;
end;
end;
if not DoResult then
begin
ErrorList := Kernel.GetDocErrorsListEx(@STRU);
s := '';
for j:=0 to ErrorList.Count - 1 do
begin
if s <> '' then s := s + #13;
s := s + ErrorList.Strings[j];
end;
ShowMessage(s);
TaxInvoicesEditDM.WriteTransaction.Rollback;
Exit;
end;
//добавление проводок в буфера
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_PROVODKA_VID_NAKL';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_VID_NAKL').Value := id_vid_nakl_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('IP_ADRESS_COMPUTER').Value := TaxInvoicesUser.ip_computer;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
// добавление проводки
KEY_SESSION := TaxInvoicesEditDM.pFIBStoredProc.ParamByName('KEY_SESSION_DOC').value;
workdate := TaxInvoicesEditDM.pFIBStoredProc.ParamByName('DATE_PROV').value;
STRU.KEY_SESSION := KEY_SESSION;
STRU.WORKDATE := WORKDATE;
STRU.DBHANDLE := TaxInvoicesEditDM.DB.Handle;
STRU.TRHANDLE := TaxInvoicesEditDM.WriteTransaction.Handle;
STRU.KERNEL_ACTION := 1;
STRU.ID_USER := TaxInvoicesUser.id_user;
try
DoResult:=Kernel.KernelDo(@STRU);
except
on E:Exception do
begin
ShowMessage('Помилка ядра ' + E.Message);
TaxInvoicesEditDM.WriteTransaction.Rollback;
Exit;
end;
end;
if not DoResult then
begin
ErrorList := Kernel.GetDocErrorsListEx(@STRU);
s := '';
for j:=0 to ErrorList.Count - 1 do
begin
if s <> '' then s := s + #13;
s := s + ErrorList.Strings[j];
end;
ShowMessage(s);
TaxInvoicesEditDM.WriteTransaction.Rollback;
Exit;
end;
TaxInvoicesEditDM.WriteTransaction.commit;
end;
end;
end;
procedure TTaxInvoicesEditAddForm.NoteCheckBoxClick(Sender: TObject);
begin
NoteButtonEdit.Enabled := NoteCheckBox.Checked;
end;
procedure TTaxInvoicesEditAddForm.NoteButtonEditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
Parameter:TTiSimpleParam;
Note:Variant;
begin
Parameter := TTiSimpleParam.Create;
Parameter.DB_Handle := TaxInvoicesEditDM.DB.Handle;
Parameter.Owner := self;
Note := DoFunctionFromPackage(Parameter,Notes_Const);
Parameter.Destroy;
If VarArrayDimCount(Note)>0 then
begin
NoteButtonEdit.Text := Note[1];
PParameter.id_note := Note[0];
PParameter.article_note := Note[1];
end;
end;
procedure TTaxInvoicesEditAddForm.EditTaxButtonClick(Sender: TObject);
var
ViewForm : TTaxInvoicesEditTaxForm;
begin
ViewForm := TTaxInvoicesEditTaxForm.Create(Self,TaxInvoicesEditDM.DB.Handle);
ViewForm.TaxCurrencyEdit.Text := TaxInvoicesEditDM.VidNaklInfoDSet['summa_tax'];
ViewForm.ShowModal;
if (ViewForm.ModalResult = mrok) then
begin
TaxInvoicesEditDM.WriteTransaction.StartTransaction;
TaxInvoicesEditDM.pFIBStoredProc.StoredProcName := 'TI_UPD_TAX';
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('ID_NAKL_DOC').Value := id_vid_nakl_doc_Ins;
TaxInvoicesEditDM.pFIBStoredProc.ParamByName('SUMMA_TAX').Value := ViewForm.TaxCurrencyEdit.Value;
TaxInvoicesEditDM.pFIBStoredProc.ExecProc;
TaxInvoicesEditDM.WriteTransaction.Commit;
end;
RefreshButton.Click;
end;
procedure TTaxInvoicesEditAddForm.OznakaCheckBoxClick(Sender: TObject);
begin
OznakaTextEdit.Enabled := OznakaCheckBox.Checked;
end;
end.
|
unit TerrainEngine;
interface
uses
Winapi.OpenGL,
System.Math,
Vcl.Graphics,
GLVectorTypes,
GLVectorGeometry;
type
TTerrainVertex = array[0..2] of Single;
THeightData = class
private
FHeights: array of array of Single;
FNormals: array of array of TAffineVector;
FXDim: integer;
FYDim: integer;
procedure SetHeights(x, y: integer; const Value: single);
function GetHeights(x, y: integer): single;
function GetNormals(x, y: integer): TAffineVector;
public
constructor Create(XDim, YDim: integer);
procedure CalculateNormals;
property XDim: integer read FXDim;
property YDim: integer read FYDim;
property Heights[x, y: integer]: single read GetHeights write SetHeights;
property Normals[x, y: integer]: TAffineVector read GetNormals;
end;
TTerrainBrush = class
protected
function GetWeight(x, y: integer): single; virtual; abstract;
function GetHalfWidth: integer; virtual; abstract;
function GetHalfHeight: integer; virtual; abstract;
public
property HalfWidth: integer read GetHalfWidth;
property HalfHeight: integer read GetHalfHeight;
// weights are defined on the intervals
// -HalfWidth..HalfWidth and -HalfHeight..HalfHeight
property Weight[x, y: integer]: single read GetWeight;
end;
TSmoothCircularBrush = class(TTerrainBrush)
private
FRadius: integer;
protected
function GetWeight(x, y: integer): single; override;
function GetHalfWidth: integer; override;
function GetHalfHeight: integer; override;
public
constructor Create(Radius: integer = 10);
property Radius: integer read FRadius write FRadius;
end;
TTerrainHeightModifier = class
private
FData: THeightData;
protected
property Data: THeightData read FData;
public
constructor Create(Data: THeightData);
procedure Modify(OriginX, OriginY: integer; Brush: TTerrainBrush;
Strength: single); virtual; abstract;
end;
TElevateModifier = class(TTerrainHeightModifier)
public
procedure Modify(OriginX, OriginY: integer; Brush: TTerrainBrush;
Strength: single); override;
end;
{ .: TTerrain :. }
TTerrain = class(TObject)
private
FData: THeightData;
protected
VScale, TScale, GridSize: Single;
DisplayList: GLuint;
GotDisplayList: Boolean;
procedure DrawManually();
procedure LoadFromBitmap(Bitmap: TBitmap);
public
constructor Create(const FileName: String; GridScale: Single = 1.0;
VerticalScale: Single = 100.0; TextureScale: Single = 1.0);
destructor Destroy(); override;
function GridPointPosition(x, y: integer): TAffineVector;
procedure Render;
property Data: THeightData read FData;
end;
implementation
{ THeightData }
procedure THeightData.CalculateNormals;
var
X, Y, XX, YY, targetY, targetX: Integer;
V: TAffineVector;
H: Single;
begin
for Y := 0 to YDim -1 do
begin
for X := 0 to XDim -1 do
begin
V:= AffineVectorMake(0, 0, 0);
for YY := -1 to 1 do
begin
targetY:= min(max(Y + YY, 0), YDim - 1);
for XX := -1 to 1 do
begin
if (XX = 0) and (YY = 0) then
continue;
targetX:= min(max(X + XX, 0), XDim - 1);
H := Heights[TargetX, TargetY];
V.X := V.X - XX * H;
V.Z := V.Z - YY * H;
end;
end;
V.Y := 1 / 3;
// length can't possibly be zero because
// V[1] is set to 1/3
FNormals[Y][X] := VectorNormalize(V);
end;
end;
end;
constructor THeightData.Create(XDim, YDim: integer);
begin
inherited Create;
FXDim:= XDim;
FYDim:= YDim;
SetLength(FHeights, YDim, XDim);
SetLength(FNormals, YDim, XDim);
end;
function THeightData.GetHeights(x, y: integer): single;
begin
result:= FHeights[y][x];
end;
function THeightData.GetNormals(x, y: integer): TAffineVector;
begin
result:= FNormals[y][x];
end;
procedure THeightData.SetHeights(x, y: integer; const Value: single);
begin
FHeights[y][x]:= Value;
end;
{ TTerrainHeightModifier }
constructor TTerrainHeightModifier.Create(Data: THeightData);
begin
inherited Create;
FData:= Data;
end;
{ TTerrain }
constructor TTerrain.Create(const FileName: String; GridScale, VerticalScale,
TextureScale: Single);
var
BMP: TBitmap;
begin
inherited Create();
VScale := VerticalScale;
TScale := TextureScale;
GotDisplayList := False;
GridSize := GridScale;
BMP:= TBitmap.Create();
try
BMP.LoadFromFile(FileName);
LoadFromBitmap(BMP);
finally
BMP.Free();
end;
end;
destructor TTerrain.Destroy;
begin
if GotDisplayList then
glDeleteLists(DisplayList, 1);
FData.Free;
inherited Destroy();
end;
procedure TTerrain.DrawManually;
var
X, Y: Integer;
Hw, Hh: Single;
N: TAffineVector;
begin
Hw := (Data.XDim / 2) * GridSize;
Hh := (Data.YDim / 2) * GridSize;
for Y := 0 to Data.YDim -2 do
begin
glBegin(GL_TRIANGLE_STRIP);
for X := 0 to Data.XDim -1 do
begin
glTexCoord2f(X / Data.XDim * TScale, Y / Data.XDim * TScale);
N:= Data.Normals[X, Y];
glNormal3fv(@N);
glVertex3f(X * GridSize - Hw, Data.Heights[X, Y] * VScale, Y * GridSize - Hh);
glTexCoord2f(X / Data.XDim * TScale, (Y + 1) / Data.XDim * TScale);
N:= Data.Normals[X, Y+1];
glNormal3fv(@N);
glVertex3f(X * GridSize - Hw, Data.Heights[X, Y + 1] * VScale,
(Y + 1) * GridSize - Hh);
end;
glEnd();
end;
end;
function TTerrain.GridPointPosition(x, y: integer): TAffineVector;
var
Hw, Hh: Single;
begin
x:= min(max(x, 0), Data.XDim-1);
y:= min(max(y, 0), Data.YDim-1);
Hw := (Data.XDim / 2) * GridSize;
Hh := (Data.YDim / 2) * GridSize;
result:= AffineVectorMake(X * GridSize - Hw, Data.Heights[X, Y] * VScale, Y * GridSize - Hh);
end;
procedure TTerrain.LoadFromBitmap(Bitmap: TBitmap);
var
X, Y: Integer;
PB: PByteArray;
begin
Bitmap.PixelFormat := pf24bit;
// clear old data
FData.Free;
FData:= THeightData.Create(Bitmap.Width, Bitmap.Height);
for Y := Bitmap.Height - 1 downto 0 do
begin
PB := Bitmap.ScanLine[Y];
for X := 0 to Bitmap.Width-1 do
Data.Heights[X, Bitmap.Height -1 - Y] := (PB[X * 3 + 2] +
PB[X * 3 + 1] + PB[X * 3]) / 765;
end;
Data.CalculateNormals();
end;
procedure TTerrain.Render;
begin
// can't use display lists when we constantly modify
// the terrain data
DrawManually();
// if not GotDisplayList then
// begin
// DisplayList := glGenLists(1);
//
// glNewList(DisplayList, GL_COMPILE);
// DrawManually();
// glEndList();
//
// GotDisplayList := True;
// end;
//
// glCallList(DisplayList)
end;
{ TSmoothCircularBrush }
constructor TSmoothCircularBrush.Create(Radius: integer);
begin
inherited Create;
FRadius:= Radius;
end;
function TSmoothCircularBrush.GetHalfHeight: integer;
begin
result:= Radius;
end;
function TSmoothCircularBrush.GetHalfWidth: integer;
begin
result:= Radius;
end;
function TSmoothCircularBrush.GetWeight(x, y: integer): single;
var
s: single;
begin
result:= 0;
if (abs(x) > HalfWidth) or (abs(y) > HalfHeight) then
exit;
s:= Radius / 3;
// gaussian function with sigma = s and my = 0
// gaussian is almost 0 if distance > 3*sigma, hence
// the division of radius by 3 to get sigma
result:= exp(-(x*x+y*y) / (2 * s*s)) / (s * sqrt(2*pi));
end;
{ TElevateModifier }
procedure TElevateModifier.Modify(OriginX, OriginY: integer; Brush: TTerrainBrush; Strength: single);
var
top, bottom, left, right: integer;
x, y, bx, by: integer;
oldHeight: single;
begin
// make sure we don't go outside the data
top:= max(OriginY-Brush.HalfHeight, 0);
left:= max(OriginX-Brush.HalfWidth, 0);
bottom:= min(OriginY+Brush.HalfHeight, Data.YDim-1);
right:= min(OriginX+Brush.HalfWidth, Data.XDim-1);
for y:= top to bottom do
begin
by:= y - OriginY;
for x:= left to right do
begin
bx:= x - OriginX;
oldHeight:= Data.Heights[x, y];
// add the brush weight to the height, modified by
// the strength, and making sure we stay above 0
Data.Heights[x, y]:=
max(oldHeight + Strength * Brush.Weight[bx, by], 0);
end;
end;
end;
end.
|
unit AddPaperSignerUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, SpFormUnit, PersonalCommon, SpCommon;
type
TAddPaperSignerForm = class(TForm)
CancelButton: TBitBtn;
OkButton: TBitBtn;
Label3: TLabel;
FIoEdit: TEdit;
Label1: TLabel;
PostEdit: TEdit;
SelectButton: TButton;
procedure OkButtonClick(Sender: TObject);
procedure SelectButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
AddPaperSignerForm: TAddPaperSignerForm;
implementation
{$R *.dfm}
procedure TAddPaperSignerForm.OkButtonClick(Sender: TObject);
begin
if (FioEdit.Text = '')
then begin
MessageDlg('Потрібно заповнити П.І.Б. підписуючого!', mtError, [mbOk], 0);
FioEdit.SetFocus;
exit;
end;
if (PostEdit.Text = '')
then begin
MessageDlg('Потрібно заповнити посаду підписуючого!', mtError, [mbOk], 0);
PostEdit.SetFocus;
exit;
end;
ModalResult := mrOk;
end;
procedure TAddPaperSignerForm.SelectButtonClick(Sender: TObject);
var
Form: TSpForm;
Params: TSpParams;
begin
Form := TSpForm.Create(self);
Params := TSpParams.Create;
Params.Table := 'ORDER_PAPER_SIGNERS_SELECT';
Params.IdField := 'ID_ORDER';
Params.SpFields := 'FIO, POST';
Params.Title := 'Використовані раніше підписуючі друкованої версії наказу';
Params.ColumnNames := 'П.І.Б, Посада';
Params.ReadOnly := True;
Params.SpMode := [spfSelect];
Form.Init(Params);
if Form.ShowModal = mrOk
then begin
FioEdit.Text := Form.ResultQuery['FIO'];
PostEdit.Text := Form.ResultQuery['POST'];
end;
Form.Free;
Params.Free;
end;
end.
|
unit strt_new;
{
Function sinh(x:real):real;
Function cosh(x:real):real;
Function tanh(x:real):real;
procedure proInvMat(var W,Winv: Tmat);
}
interface
{$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF}
uses util1,SysUtils,Dialogs,stmKLmat,stmVec1,stmMat1,MathKernel0,stmDef;
function FonctionSinh(x: float):float;pascal;
function FonctionCosh(x: float):float;pascal;
function FonctionTanh(x: float):float;pascal;
procedure proInvMat(var W,Winv: Tmat);pascal;
implementation
function FonctionSinh(x: float):float;
begin
result:=(exp(x)-exp(-x))/2;
end;
function FonctionCosh(x: float):float;
begin
result:=(exp(x)+exp(-x))/2;
end;
function FonctionTanh(x: float):float;
begin
result:=(exp(x)-exp(-x))/(exp(x)+exp(-x));
end;
procedure proInvMat(var W,Winv: Tmat);
var
info : integer;
Wtemp : Tmat;
W_piv : Tvector;
work:pointer;
lwork:integer;
begin
Wtemp := Tmat.create(G_single,W.Istart,W.Iend);
Wtemp.copy(W);
W_piv := Tvector.create(G_single,W.Istart,W.Iend);
try
sgetrf(Wtemp.Iend, Wtemp.Jend, Wtemp.tb, W.RowCount, W_piv.tb, info);
if (info <> 0) then ShowMessage ('Matrix can''t be factorized')
else
begin
lWork:=64*W.Iend;
getmem(work,lwork*tailleTypeG[W.tpNum]);
sgetri(W.Iend, Wtemp.tb , W.RowCount, W_piv.tb, work, lwork, info);
if info <0 then ShowMessage (IntToStr(info)+'th param has an illegal value');
if info >0 then ShowMessage (IntToStr(info)+'th diagonal element of the factor U is zero, U is singular, and inversion could not be completed.');
end;
Winv.copy(Wtemp);
finally
freemem(work);
Wtemp.free;
W_piv.free;
end; {try}
end;
end.
|
{*
* tab2olol - utility that converts tab-indented text files to olol files
* Copyright (C) 2011 Kostas Michalopoulos
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*
* Kostas Michalopoulos <badsector@runtimelegend.com>
*}
program tab2olol;
{$MODE OBJFPC}{$H+}
var
f: Text;
s: string;
i, LastTabs, Tabs: Integer;
begin
if ParamCount=0 then begin
Writeln('Usage: tab2olol <tab file>');
exit;
end;
Assign(f, ParamStr(1));
{$I-}
Reset(f);
{$I+}
if IOResult <> 0 then begin
Writeln('Failed to open ', ParamStr(1), ' for input');
exit;
end;
WriteLn('NOTE');
WriteLn('NOTE Created from ', ParamStr(1), ' by tab2olol');
WriteLn('NOTE');
WriteLn('NODE');
LastTabs:=-1;
while not Eof(f) do begin
Readln(f, s);
if s='' then continue;
Tabs:=0;
for i:=1 to Length(s) do
if s[i]=#9 then
Inc(Tabs)
else
break;
for i:=Tabs to LastTabs do WriteLn('DONE');
WriteLn('NODE ', Copy(s, Tabs + 1, Length(s)));
LastTabs:=Tabs;
end;
WriteLn('DONE');
WriteLn('STOP');
Close(f);
end.
|
{$I-,Q-,R-,S-}
{Problema 6: Brazalete de Dijes [Kolstad/Cox, 2006]
Bessie ha ido a la joyería del centro comercial y ha visto un
brazalete de dijes. Por supuesto, ella quisiera llenarlo con los
mejores dijes posibles de N (1 <= N <= 3,402) dijes disponibles. Cada
dije i tiene un peso W_i (1 <= W_i <= 400) y una factor de
'deseabilidad' D_i (1 <= D_i <= 100). Bessie puede únicamente soporta
un brazalete de dijes cuyo peso sea menor que M (1 <= M <= 12,880).
Dado el peso límite como una restricción y una lista de los dijes con
sus pesos y factores de deseabilidad, deduzca la mayor suma posible de
deseabilidades.
NOMBRE DEL PROBLEMA: charm
FORMATO DE ENTRADA:
* Línea 1: Dos enteros separados por espacio: N y M
* Líneas 2..N+1: La línea i+1 describe el dije i con dos enteros
separados por espacio: W_i y D_i
ENTRADA EJEMPLO (archivo charm.in):
4 6
1 4
2 6
3 12
2 7
DETALLES DE LA ENTRADA:
Cuatro dijes potenciales, peso máximo 6
FORMATO DE SALIDA:
* Línea 1: Un solo entero que es la suma más grande de deseabilidades
de dijes que puede ser obtenida dadas las restricciones de peso
SALIDA EJEMPLO (archivo charm.out):
23
DETALLES DE LA SALIDA:
Sin el segundo dije posible, el valor 4+12+7=23 es el valor más alto
con un peso 1+2+3<=6
}
const
mx = 13001;
var
fe,fs : text;
n,m,sol : longint;
best : array[0..mx] of longint;
procedure open;
begin
assign(fe,'charm.in'); reset(fe);
assign(fs,'charm.out'); rewrite(fs);
readln(fe,m,n);
end;
function max(n1,n2 : longint) : longint;
begin
if n1 > n2 then max:=n1
else max:=n2;
end;
procedure work;
var
i,j,zi,va : longint;
begin
for i:=1 to m do { metiendo el i-esimo objeto }
begin
readln(fe,zi,va);
for j:=n downto 1 do { metiendolo en todos los tama¤os }
begin
if (best[j] <> 0) and (j + zi <= n) then
best[j + zi]:=max(best[j] + va,best[j + zi]);
end;
if (best[zi] < va) then best[zi]:=va;
end;
sol:=0;
for i:=1 to n do
sol:=max(sol,best[i]);
end;
procedure closer;
begin
writeln(fs,sol);
close(fs);
end;
begin
open;
work;
closer;
end. |
unit ULPCThread;
interface
uses
SysUtils, Classes, Windows, SyncObjs,
System.Generics.Collections, System.Generics.Defaults,
AStar64.FileStructs, AStar64.Typ, AStar64.DynImport,
Geo.Hash, Ils.Utils, Ils.Logger, System.Types,
AStar64.LandMark;
type
TSaveFunc = procedure(
const ALmMatrixFrom: TLandMarkMatrix
) of object;
TTaskThread = class(TThread)
private
FLmKey: TLandMarkWayKey;
FSaveFunc: TSaveFunc;
FAccounts: TIntegerDynArray;
FTimeout: Integer;
FRecalcAll: Boolean;
FResDir: string;
procedure DoWork();
protected
procedure Execute(); override;
public
constructor Create(
const ALmKey: TLandMarkWayKey;
const ASaveFunc: TSaveFunc;
const AAccounts: TIntegerDynArray;
const ATimeout: Integer;
const ARecalcAll: Boolean;
const AResDir: string = ''
);
end;
TTaskList = class(TList<TTaskThread>)
destructor Destroy; override;
end;
TTaskQueue = class
private
FTaskList: TTaskList;
FLmMatrix: TLandMarkMatrix;
FThreads: Integer;
FTimeout: Integer;
FRecalcAll: Boolean;
// FAccounts: TIntegerDynArray;
FCS: TCriticalSection;
function CollectGarbage(): Integer;
procedure SaveResults(
const ALmMatrixFrom: TLandMarkMatrix
);
public
constructor Create(
const ALmMatrix: TLandMarkMatrix;
const AThreads: Integer;
const ATimeout: Integer;
const ARecalcAll: Boolean
);
destructor Destroy(); override;
procedure PushTask(
const ALmKey: TLandMarkWayKey;
const AFullCalc: Boolean;
const AAccounts: TIntegerDynArray
);
procedure WaitForAllDone();
end;
procedure Log(const AStr: string);
implementation
var
GCS: TCriticalSection;
procedure WritePath(
const ALandMarkMatrix: TLandMarkMatrix;
const AKey: TLandMarkWayKey;
const APath: string;
const ADistance: Double
);
var
Way: TLandMarkWay;
begin
if not ALandMarkMatrix.ContainsKey(AKey) then
ALandMarkMatrix.Add(AKey, TLandMarkWay.Create(APath, ADistance))
else
begin
Way := ALandMarkMatrix.Items[AKey];
if (Way.Distance = 0) or (Way.Distance > ADistance) then
Way.NewData(APath, ADistance);
end;
end;
procedure WriteErrorPath(
const ALandMarkMatrix: TLandMarkMatrix;
const AKey: TLandMarkWayKey;
const AValue: string = 'error'
);
begin
if not ALandMarkMatrix.ContainsKey(AKey) then
ALandMarkMatrix.Add(AKey, TLandMarkWay.Create(AValue, 0))
else
if (ALandMarkMatrix.Items[AKey].GeoHash = '') then
ALandMarkMatrix.Items[AKey].NewData(AValue, 0);
end;
procedure Log(const AStr: string);
begin
GCS.Acquire;
try
ToLog('"' + IntToStr(GetCurrentThreadId()) + '" ' + AStr);
// Writeln(DateTimeToIls(Now()), '> "', GetCurrentThreadId(), '" ', AStr);
finally
GCS.Release;
end;
end;
function CalcPath(
const AVector: THashVector;
const AZonesExcluded: UInt64;
out RZonesVisited: UInt64;
out RDistance: Double;
AAccounts: TIntegerDynArray;
const ATimeout: Integer
): string;
function GetZones(
const ALMPath: string;
const AFormatStartPos: Integer;
const AFormatIncrement: Integer
): Int64;
var
i: Integer;
d: string;
begin
Result := 0;
i := AFormatStartPos;
repeat
d := Copy(ALMPath, i + (12 + 1 + 2), 16);
if (d = '') then
Break;
Result := Result or StrToInt64('$' + d);
Inc(i, AFormatIncrement);
until False;
end;
var
ar: TAstarRequest4;
CalcRez: Integer;
fmt:TFormatSettings;
begin
if Length(AAccounts) = 0 then
begin
SetLength(AAccounts, 2);
AAccounts[0] := 1;
AAccounts[1] := 0;
end else
begin
SetLength(AAccounts, Length(AAccounts) + 1);
AAccounts[High(AAccounts)] := 0;
end;
Log(
'Calculating path ' + AVector.HashStr + Format(
' %.6f %.6f - %.6f %.6f',
[AVector.PointFrom.Latitude, AVector.PointFrom.Longitude, AVector.PointTo.Latitude, AVector.PointTo.Longitude]
) + ' excluding zones ' + IntToHex(AZonesExcluded, 16) + ' Timeout='+IntToStr(ATimeout)
);
fmt.DecimalSeparator := '.';
Result := '';
// Log('LoadAStar64()');
LoadAStar64();
// Log('Loaded');
try
FillChar(ar, SizeOf(ar), 0);
with ar do
begin
Version := 1;
FromLatitude := AVector.PointFrom.Latitude;
FromLongitude := AVector.PointFrom.Longitude;
ToLatitude := AVector.PointTo.Latitude;
ToLongitude := AVector.PointTo.Longitude;
ZonesLimit := AZonesExcluded; // исключаемые зоны
FormatVariant := Ord(gfLandMark);
LenTreshold := 15;
Timeout := ATimeout;
BufferSize := 1024*1024;
HashString := AllocMem(BufferSize);
Feature := 0;
end;
// Log('AStarCalc4Acc AAccounts='+IntToStr(AAccounts[0])+IntToStr(AAccounts[1]));
CalcRez := AStarCalc4Acc(@ar, @AAccounts[0]);
// Log('calc()');
if (CalcRez = 0) then
begin
Result := string(AnsiString(ar.HashString));
Delete(Result, 3, 12 + 19);
Delete(Result, Length(Result) + (1 - 12 - 19), 12 + 19);
RZonesVisited := GetZones(Result, ar.FormatStartPos, ar.FormatIncrement);
RDistance := ar.Distance;
// Result := FloatToStrF(ar.Distance, ffFixed, 9, 3, fmt) + Result;
//!! Log('Calculating done with zones crossed ' + IntToHex(RZonesVisited, 16));
Log('Calculating done with zones crossed ' + IntToHex(AZonesExcluded, 16));
end
else
begin
Log('Calculating failed with rezult ' + IntToStr(CalcRez));
end;
finally
FreeMem(ar.HashString);
UnloadAStar64();
end;
end;
{ TTaskThread }
constructor TTaskThread.Create(
const ALmKey: TLandMarkWayKey;
const ASaveFunc: TSaveFunc;
const AAccounts: TIntegerDynArray;
const ATimeout: Integer;
const ARecalcAll: Boolean;
const AResDir: string
);
begin
inherited Create(False);
FreeOnTerminate := False;
//
FLmKey := ALmKey;
FSaveFunc := ASaveFunc;
FAccounts := AAccounts;
FTimeout := ATimeout;
FRecalcAll := ARecalcAll;
FResDir := AResDir;
end;
procedure TTaskThread.DoWork();
function IsBitsNotPresentedInList(
ABits: UInt64;
const AList: TDictionary<UInt64, Boolean>
): Boolean;
var
Iter: UInt64;
begin
for Iter in AList.Keys do
begin
ABits := ABits and not Iter;
end;
Result := ABits <> 0;
end;
procedure InsertNewBitsPackInList(
const ABits: UInt64;
const AList: TDictionary<UInt64, Boolean>
);
var
Mask: UInt64;
OneBit: UInt64;
Iter: UInt64;
InsSet: UInt64;
AllInserted: Boolean;
begin
Log('InsertNewBits begin AList.Count ' + IntToStr(AList.Count) + ' adding ' + IntToHex(ABits, 16));
Mask := 1;
repeat
OneBit := ABits and Mask;
if (OneBit <> 0) then
begin
if not AList.ContainsKey(OneBit) then
begin
Log('InsertNewBits adding ' + IntToHex(OneBit, 16));
AList.Add(OneBit, False);
end;
repeat
AllInserted := True;
for Iter in AList.Keys do
begin
InsSet := OneBit or Iter;
if not AList.ContainsKey(InsSet) then
begin
Log('InsertNewBits adding ' + IntToHex(InsSet, 16));
AList.Add(InsSet, False);
AllInserted := False;
Break;
end;
end;
until AllInserted;
end;
Mask := Mask shl 1;
until (Mask = 0);
Log('InsertNewBits end AList.Count ' + IntToStr(AList.Count));
end;
var
RezStr: string;
LmMatrix: TLandMarkMatrix;
CrossedZonesList: TDictionary<UInt64, Boolean>;
WayKey: TLandMarkWayKey;
ZonesToExclude: UInt64;
Dist: Double;
AllZonesDone: Boolean;
begin
//если пересчитываем все
if FRecalcAll then
begin
// FLmKey.z всегда 0 (как результат работы InsertLightsFromGeoPosArray)
try
// Log('DoWork. Timeout='+IntToStr(FTimeout));
CrossedZonesList := nil;
LmMatrix := TLandMarkMatrix.Create('', '', FAccounts, FResDir);
try
CrossedZonesList := TDictionary<UInt64, Boolean>.Create(16);
RezStr := CalcPath(FLmKey.v, 0{без ограничений по зонам}, WayKey.z, Dist, FAccounts, FTimeout);
// ToLog('Vector '+FLmKey.v.HashStr + ' Out WayKey.z='+IntToStr(WayKey.z));
if (RezStr = '') then
begin // не удалось посчитать путь
WriteErrorPath(LmMatrix, FLmKey, 'fullcalc');
Exit;
end;
if (WayKey.z = 0) then
begin // тривиально = вообще нет зон, по которым мы прошли
WritePath(LmMatrix, FLmKey, RezStr, Dist);
Exit;
end;
// ...
WayKey.v := FLmKey.v;
WritePath(LmMatrix, WayKey, RezStr, Dist);
//!! WritePath(LmMatrix, FLmKey, RezStr, Dist);
CrossedZonesList.Clear();
InsertNewBitsPackInList(WayKey.z, CrossedZonesList);
// ToLog('InsertNewBitsPackInList WayKey.z='+IntToStr(WayKey.z)+' CrossedZonesList='+IntToStr(CrossedZonesList.Count));
repeat
AllZonesDone := True;
for ZonesToExclude in CrossedZonesList.Keys do
begin
if CrossedZonesList[ZonesToExclude] then
Continue;
AllZonesDone := False;
CrossedZonesList[ZonesToExclude] := True;
//!! FLmKey.z := ZonesToExclude;
RezStr := CalcPath(FLmKey.v, ZonesToExclude, WayKey.z, Dist, FAccounts, FTimeout);
if (RezStr <> '') then
begin
WritePath(LmMatrix, WayKey, RezStr, Dist);
//!! WritePath(LmMatrix, FLmKey, RezStr, Dist);
if IsBitsNotPresentedInList(WayKey.z, CrossedZonesList) then
InsertNewBitsPackInList(WayKey.z, CrossedZonesList);
end
else
begin
WayKey.z := 0;
WriteErrorPath(LmMatrix, WayKey);
//!! WriteErrorPath(LmMatrix, FLmKey);
end;
//
Break;
end;
until AllZonesDone;
finally
FSaveFunc(LmMatrix);
LmMatrix.Free();
CrossedZonesList.Free();
end;
except
on E: Exception do
begin
Log(E.ClassName + ': ' + E.Message);
end;
end;
end else
//если только нужные
begin
try
Log('DoWork. Считаем только непросчитанные '+FLmKey.v.HashStr+','+ IntToStr(FLmKey.z));
CrossedZonesList := nil;
LmMatrix := TLandMarkMatrix.Create('', '', FAccounts, FResDir);
try
CrossedZonesList := TDictionary<UInt64, Boolean>.Create(16);
RezStr := CalcPath(FLmKey.v, FLmKey.z, WayKey.z, Dist, FAccounts, FTimeout);
if (RezStr = '') then
begin // не удалось посчитать путь
WriteErrorPath(LmMatrix, FLmKey);
Exit;
end else
begin // тривиально = вообще нет зон, по которым мы прошли
WritePath(LmMatrix, FLmKey, RezStr, Dist);
Exit;
end;
finally
FSaveFunc(LmMatrix);
LmMatrix.Free();
CrossedZonesList.Free();
end;
except
on E: Exception do
begin
Log(E.ClassName + ': ' + E.Message);
end;
end;
end;
end;
procedure TTaskThread.Execute();
begin
DoWork();
Terminate();
end;
{ TTaskList }
destructor TTaskList.Destroy();
var
I: Integer;
begin
for I := 0 to Count - 1 do
begin
Items[I].Free();
end;
//
inherited Destroy();
end;
{ TTaskQueue }
constructor TTaskQueue.Create(
const ALmMatrix: TLandMarkMatrix;
const AThreads: Integer;
const ATimeout: Integer;
const ARecalcAll: Boolean
);
begin
inherited Create();
//
FLmMatrix := ALmMatrix;
FThreads := AThreads;
FTimeout := ATimeout;
FRecalcAll := ARecalcAll;
// FAccounts := AAccounts;
FCS := TCriticalSection.Create();
FTaskList := TTaskList.Create();
end;
destructor TTaskQueue.Destroy();
begin
FTaskList.Free();
FCS.Free();
//
inherited Destroy();
end;
function TTaskQueue.CollectGarbage(): Integer;
var
I: Integer;
begin
I := FTaskList.Count - 1;
while (I >= 0) do
begin
if FTaskList.Items[I].Terminated then
begin
FTaskList.Items[I].Free();
FTaskList.Delete(I);
end;
Dec(I);
end;
Result := FTaskList.Count;
end;
procedure TTaskQueue.SaveResults(
const ALmMatrixFrom: TLandMarkMatrix
);
var
MatrixKeyIter: TLandMarkWayKey;
begin
FCS.Acquire();
try
for MatrixKeyIter in ALmMatrixFrom.Keys do
begin
WritePath(FLmMatrix, MatrixKeyIter, ALmMatrixFrom[MatrixKeyIter].GeoHash, ALmMatrixFrom[MatrixKeyIter].Distance);
end;
finally
FCS.Release();
end;
end;
procedure TTaskQueue.PushTask(
const ALmKey: TLandMarkWayKey;
const AFullCalc: Boolean;
const AAccounts: TIntegerDynArray
);
begin
while (CollectGarbage() >= FThreads) do
Sleep(1);
FTaskList.Add(TTaskThread.Create(ALmKey, SaveResults, AAccounts, FTimeout, AFullCalc));
end;
procedure TTaskQueue.WaitForAllDone();
begin
while (CollectGarbage() > 0) do
Sleep(1);
end;
initialization
GCS := TCriticalSection.Create;
finalization
GCS.Free;
end.
|
{
Double commander
-------------------------------------------------------------------------
MacOS preview plugin
Copyright (C) 2022 Alexander Koblov (alexx2000@mail.ru)
Copyright (C) 2022 Rich Chang (rich2014.git@outlook.com)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
library MacPreview;
{$mode objfpc}{$H+}
{$modeswitch objectivec1}
uses
SysUtils, WlxPlugin, CocoaAll, QuickLookUI;
type
TQLPItem = objcclass(NSObject, QLPreviewItemProtocol)
url: NSURL;
function previewItemURL: NSURL;
end;
function TQLPItem.previewItemURL: NSURL;
begin
Result:= url;
end;
function StringToNSString(const S: String): NSString;
begin
Result:= NSString(NSString.stringWithUTF8String(PAnsiChar(S)));
end;
procedure setFilepath( view:QLPreviewView; filepath:String );
var
item: TQLPItem;
begin
if filepath=EmptyStr then begin
item:= nil;
end else begin
item:= TQLPItem.alloc.init;
item.url:= NSURL.fileURLWithPath( StringToNSString(filepath) );
end;
view.setPreviewItem( item );
end;
function ListLoad( ParentWin:THandle; FileToLoad:pchar; {%H-}ShowFlags{%H+}:integer):THandle; cdecl;
var
view: QLPreviewView;
begin
view:= QLPreviewView.alloc.init;
view.setShouldCloseWithWindow( false );
NSView(ParentWin).addSubview( view );
setFilepath( view, FileToLoad );
Result:= THandle(view);
end;
function ListLoadNext( {%H-}ParentWin{%H+},PluginWin:THandle; FileToLoad:pchar; {%H-}ShowFlags{%H+}:integer):integer; cdecl;
begin
setFilepath( QLPreviewView(PluginWin), FileToLoad );
Result:= LISTPLUGIN_OK;
end;
procedure ListCloseWindow(ListWin:THandle); cdecl;
begin
QLPreviewView(ListWin).close;
QLPreviewView(ListWin).removeFromSuperview;
end;
procedure ListGetDetectString(DetectString:pchar;maxlen:integer); cdecl;
begin
StrLCopy(DetectString, '(EXT!="")', MaxLen);
end;
exports
ListLoad,
ListLoadNext,
ListCloseWindow,
ListGetDetectString;
end.
|
unit ScriptPanel;
interface
uses
Classes, ExtCtrls,
DynamicProperties;
type
TScriptPanel = class(TPanel)
private
FEvents: TDynamicProperties;
FCustomProps: TDynamicProperties;
protected
procedure SetCustomProps(const Value: TDynamicProperties);
procedure SetEvents(const Value: TDynamicProperties);
public
constructor Create(inOwner: TComponent); override;
published
property Events: TDynamicProperties read FEvents write SetEvents;
property CustomProps: TDynamicProperties read FCustomProps
write SetCustomProps;
end;
implementation
{ TScriptPanel }
constructor TScriptPanel.Create(inOwner: TComponent);
begin
inherited;
//
FEvents := TDynamicProperties.Create(Self, true);
Events.AddEvent.Name := 'OnEvent';
//
FCustomProps := TDynamicProperties.Create(Self);
CustomProps.AddProperty.Name := 'Attributes';
CustomProps.AddProperty.Name := 'MetaTags';
end;
procedure TScriptPanel.SetCustomProps(const Value: TDynamicProperties);
begin
FCustomProps.Assign(Value);
end;
procedure TScriptPanel.SetEvents(const Value: TDynamicProperties);
begin
Events.Assign(Value);
end;
end.
|
{
SuperMaximo GameLibrary : Font class unit
by Max Foster
License : http://creativecommons.org/licenses/by/3.0/
}
unit FontClass;
{$mode objfpc}{$H+}
interface
uses SDL_ttf, ShaderClass;
type
PFont = ^TFont;
TFont = object
strict private
font : PTTF_Font;
size : word;
name_ : string;
public
//Create a new font with the specified name, loaded from the file specified and with the specified size
constructor create(newName, fileName : string; newSize : word);
destructor destroy;
function name : string;
//Draw some text onto the screen, at the specified coordinates. Set useCache to true to take advantage of the caching
//system that gives considerable speed boosts. This is highly recommended if you are displaying static text
procedure write(text : string; x, y : integer; depth : real; useCache : boolean = true; rotation : real = 0.0;
xScale : real = 1.0; yScale : real = 1.0);
//Get the dimentions of a string typed out using this particular font
function width(text : string) : integer;
function height(text : string) : integer;
//Cache text to take advantage of the caching system, and remove it once you are finished with it
procedure cache(text : string);
procedure removeFromCache(text : string);
end;
procedure initFont(newFontShader : PShader);
procedure quitFont;
procedure bindFontShader(newFontShader : PShader);
function font(searchName : string) : PFont;
function addFont(newName, fileName : string; newSize : word) : PFont;
procedure destroyFont(searchName : string);
procedure destroyAllFonts;
//Clears the entire font cache. A good idea after transistioning from one level to the next, for example, so that the cache
//does not get bloated with unused text over time
procedure clearFontCache;
implementation
uses SysUtils, Classes, SDL, dglOpenGL, Display;
type
fontCacheRecord = record
text, fontName : string;
texture : GLuint;
w, h : integer;
vbo : GLuint;
end;
var
allFonts : array['a'..'z'] of TList;
fontCache : array[ord('a')..ord('z')+1] of array of fontCacheRecord;
fontShader : PShader;
vbo : GLuint;
constructor TFont.create(newName, fileName : string; newSize : word);
begin
name_ := newName;
size := newSize;
font := TTF_OpenFont(pchar(setDirSeparators(fileName)), size);
end;
destructor TFont.destroy;
begin
if (font <> nil) then TTF_CloseFont(font);
end;
function TFont.name : string;
begin
result := name_;
end;
procedure TFont.write(text : string; x, y : integer; depth : real; useCache : boolean = true; rotation : real = 0.0;
xScale : real = 1.0; yScale : real = 1.0);
var
cacheSuccess : boolean;
cacheIndex, i, w, h, letter : integer;
textSurface : PSDL_Surface;
color : TSDL_Color;
textureFormat : GLenum;
tempTexture : GLuint;
vertexArray : array[0..23] of GLfloat;
begin
cacheSuccess := false;
cacheIndex := 1;
letter := ord(text[1]);
if ((letter < ord('a')) or (letter > ord('z'))) then letter := ord('z')+1;
if (useCache) then
begin
//Search the cache to see if the text to draw has already been cached (this is quicker than
//actually rendering the text from scratch)
if (length(fontCache[letter]) > 0) then
begin
for i := 0 to length(fontCache[letter])-1 do
begin
if ((fontCache[letter][i].text = text) and (fontCache[letter][i].fontName = name_)) then
begin
cacheIndex := i;
cacheSuccess := true;
break;
end;
end;
end;
//If not, cache it and research (cacheSuccess will be TRUE this time)
if (not cacheSuccess) then
begin
cache(text);
for i := 0 to length(fontCache[letter])-1 do
begin
if ((fontCache[letter][i].text = text) and (fontCache[letter][i].fontName = name_)) then
begin
cacheIndex := i;
cacheSuccess := true;
break;
end;
end;
end;
end;
//If we don't want caching prepare the text surface
if (not cacheSuccess) then
begin
color.r := 255;
color.g := 255;
color.b := 255;
textSurface := TTF_RenderText_Blended(font, pchar(text), color);
w := textSurface^.w;
h := textSurface^.h;
end;
glActiveTexture(GL_TEXTURE0);
if (cacheSuccess) then
begin
//If we got the texture from the cache then bind it
glBindTexture(GL_TEXTURE_RECTANGLE, fontCache[letter][cacheIndex].texture);
w := fontCache[letter][cacheIndex].w;
h := fontCache[letter][cacheIndex].h;
glBindBuffer(GL_ARRAY_BUFFER, fontCache[letter][cacheIndex].vbo);
glVertexAttribPointer(VERTEX_ATTRIBUTE, 4, GL_FLOAT, false, 0, nil);
end
else
begin
//Otherwise put the text surface into graphics memory
if (textSurface^.format^.BytesPerPixel = 4) then
begin
if (textSurface^.format^.Rmask = $000000ff) then textureFormat := GL_RGBA else textureFormat := GL_BGRA;
end
else
begin
if (textSurface^.format^.Rmask = $000000ff) then textureFormat := GL_RGB else textureFormat := GL_BGR;
end;
glGenTextures(1, @tempTexture);
glBindTexture(GL_TEXTURE_RECTANGLE, tempTexture);
glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_RECTANGLE, 0, textSurface^.format^.BytesPerPixel, w, h, 0, textureFormat, GL_UNSIGNED_BYTE, textSurface^.pixels);
for i := 0 to 22 do vertexArray[i] := 0.0;
vertexArray[1] := h;
vertexArray[3] := 1.0;
vertexArray[7] := 1.0;
vertexArray[8] := w;
vertexArray[11] := 1.0;
vertexArray[13] := h;
vertexArray[15] := 1.0;
vertexArray[16] := w;
vertexArray[17] := h;
vertexArray[19] := 1.0;
vertexArray[20] := w;
vertexArray[23] := 1.0;
glGenBuffers(1, @vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*length(vertexArray), @vertexArray, GL_STATIC_DRAW);
glVertexAttribPointer(VERTEX_ATTRIBUTE, 4, GL_FLOAT, false, 0, nil);
end;
glEnableVertexAttribArray(VERTEX_ATTRIBUTE);
glUseProgram(PShader(fontShader)^.getProgram);
pushMatrix;
//Do the specified transforms
translateMatrix(x, y, depth);
rotateMatrix(rotation, 0.0, 0.0, 1.0);
scaleMatrix(xScale, yScale, 0.0);
//Send down matrix and texture details to the shader
PShader(fontShader)^.setUniform16(MODELVIEW_LOCATION, getMatrix(MODELVIEW_MATRIX));
PShader(fontShader)^.setUniform16(PROJECTION_LOCATION, getMatrix(PROJECTION_MATRIX));
PShader(fontShader)^.setUniform1(TEXSAMPLER_LOCATION, 0);
//Draw the text
glDrawArrays(GL_TRIANGLES, 0, 6);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glDisableVertexAttribArray(VERTEX_ATTRIBUTE);
popMatrix;
if (not cacheSuccess) then
begin
//If we didn't want caching, remove the text from memory
SDL_FreeSurface(textSurface);
glDeleteTextures(1, @tempTexture);
glDeleteBuffers(1, @vbo);
end;
end;
function TFont.width(text : string) : integer;
var
newWidth, newHeight : integer;
begin
TTF_SizeText(font, pchar(text), newWidth, newHeight);
result := newWidth;
end;
function TFont.height(text : string) : integer;
var
newWidth, newHeight : integer;
begin
TTF_SizeText(font, pchar(text), newWidth, newHeight);
result := newHeight;
end;
procedure TFont.cache(text : string);
var
letter : integer;
newRecord : fontCacheRecord;
color : TSDL_color;
textSurface: PSDL_Surface;
textureFormat : GLenum;
vertexArray : array[0..23] of GLfloat;
i : integer;
begin
letter := ord(text[1]);
if ((letter < ord('a')) or (letter > ord('z'))) then letter := ord('z')+1;
//Prepare the text surface to be put into graphics memory
newRecord.text := text;
newRecord.fontName := name_;
TTF_SizeText(font, pchar(text), newRecord.w, newRecord.h);
color.r := 255;
color.g := 255;
color.b := 255;
textSurface := TTF_RenderText_Blended(font, pchar(text), color);
if (textSurface^.format^.BytesPerPixel = 4) then
begin
if (textSurface^.format^.Rmask = $000000ff) then textureFormat := GL_RGBA else textureFormat := GL_BGRA;
end
else
begin
if (textSurface^.format^.Rmask = $000000ff) then textureFormat := GL_RGB else textureFormat := GL_BGR;
end;
//Create the texture and put the surface into graphics memory
glGenTextures(1, @newRecord.texture);
glBindTexture(GL_TEXTURE_RECTANGLE, newRecord.texture);
glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_RECTANGLE, 0, textSurface^.format^.BytesPerPixel, textSurface^.w, textSurface^.h, 0, textureFormat, GL_UNSIGNED_BYTE, textSurface^.pixels);
for i := 0 to 22 do vertexArray[i] := 0.0;
vertexArray[1] := textSurface^.h;
vertexArray[3] := 1.0;
vertexArray[7] := 1.0;
vertexArray[8] := textSurface^.w;
vertexArray[11] := 1.0;
vertexArray[13] := textSurface^.h;
vertexArray[15] := 1.0;
vertexArray[16] := textSurface^.w;
vertexArray[17] := textSurface^.h;
vertexArray[19] := 1.0;
vertexArray[20] := textSurface^.w;
vertexArray[23] := 1.0;
SDL_FreeSurface(textSurface);
//Generate a buffer to store the text rectangle vertex data
glGenBuffers(1, @newRecord.vbo);
glBindBuffer(GL_ARRAY_BUFFER, newRecord.vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*length(vertexArray), @vertexArray, GL_STATIC_DRAW);
glVertexAttribPointer(VERTEX_ATTRIBUTE, 4, GL_FLOAT, false, 0, nil);
i := length(fontCache[letter]);
setLength(fontCache[letter], i+1);
fontCache[letter][i] := newRecord;
end;
procedure TFont.removeFromCache(text : string);
var
i, j, letter : integer;
tempArray : array of fontCacheRecord;
match : boolean = false;
begin
letter := ord(text[1]);
if ((letter < ord('a')) or (letter > ord('z'))) then letter := ord('z')+1;
//Linearly search through the cache, and if there is a match, remove the cached data
if (length(fontCache[letter]) > 0) then
begin
for i := 0 to length(fontCache[letter])-1 do
begin
if ((fontCache[letter][i].text = text) and (fontCache[letter][i].fontName = name_)) then
begin
glDeleteTextures(1, @fontCache[letter][i].texture);
glDeleteBuffers(1, @fontCache[letter][i].vbo);
match := true;
break;
end;
end;
if (match) then
begin
if (length(fontCache[letter])-1 > 0) then
begin
setLength(tempArray, length(fontCache[letter])-1);
if (i > 0) then for j := 0 to i-1 do tempArray[j] := fontCache[letter][j];
for j := i to length(tempArray)-1 do tempArray[j] := fontCache[letter][j+1];
setLength(fontCache[letter], length(tempArray));
fontCache[letter] := tempArray;
end else setLength(fontCache[letter], 0);
end;
end;
end;
procedure initFont(newFontShader : PShader);
begin
fontShader := newFontShader;
TTF_Init;
end;
procedure quitFont;
begin
TTF_Quit;
fontShader := nil;
clearFontCache;
end;
procedure bindFontShader(newFontShader : PShader);
begin
fontShader := newFontShader;
end;
function font(searchName : string) : PFont;
var
letter : char;
i : word;
tempFont : PFont;
begin
letter := searchName[1];
result := nil;
if (allFonts[letter].count > 0) then
begin
for i := 0 to allFonts[letter].count-1 do
begin
tempFont := PFont(allFonts[letter][i]);
if (tempFont^.name = searchName) then result := tempFont;
end;
end;
end;
function addFont(newName, fileName : string; newSize : word) : PFont;
var
letter : char;
begin
letter := newName[1];
allFonts[letter].add(new(PFont, create(newName, fileName, newSize)));
result := allFonts[letter].last;
end;
procedure destroyFont(searchName : string);
var
letter : char;
i : word;
tempFont : PFont;
begin
letter := searchName[1];
if (allFonts[letter].count > 0) then
begin
for i := 0 to allFonts[letter].count-1 do
begin
tempFont := PFont(allFonts[letter][i]);
if (tempFont^.name = searchName) then
begin
dispose(tempFont, destroy);
allFonts[letter].delete(i);
break;
end;
end;
end;
end;
procedure destroyAllFonts;
var
i : char;
j : integer;
tempFont : PFont;
begin
for i := 'a' to 'z' do
begin
if (allFonts[i].count > 0) then
begin
for j := 0 to allFonts[i].count-1 do
begin
tempFont := PFont(allFonts[i][j]);
dispose(tempFont, destroy);
end;
allFonts[i].clear;
end;
end;
end;
procedure clearFontCache;
var
i, j : integer;
begin
for i := ord('a') to ord('z')+1 do
begin
if (length(fontCache[i]) > 0) then
begin
for j := 0 to length(fontCache[i])-1 do
begin
glDeleteTextures(1, @fontCache[i][j].texture);
glDeleteBuffers(1, @fontCache[i][j].vbo);
end;
setLength(fontCache[i], 0);
end;
end;
end;
procedure initializeAllFonts;
var
i : char;
begin
for i := 'a' to 'z' do
begin
allFonts[i] := TList.create;
end;
end;
procedure finalizeAllFonts;
var
i : char;
begin
for i := 'a' to 'z' do
begin
allFonts[i].destroy;
end;
end;
initialization
initializeAllFonts;
finalization
finalizeAllFonts;
end.
|
Unit UnitComandos;
interface
const
MaxBufferSize = 32768;
MasterPassword = 'njgnjvejvorenwtrnionrionvironvrnv';
VersaoPrograma = '2.7 Beta 02';
MAININFO = 'maininfo';
TENTARNOVAMENTE = 'tentarnovamente';
MENSAGENS = 'mensagens';
PING = 'ping';
PONG = 'pong';
PINGTEST = 'pingtest';
PONGTEST = 'pongtest';
RESPOSTA = 'resposta';
IMGDESK = 'imgdesk';
RECONNECT = 'reconnect';
DISCONNECT = 'disconnect';
UNINSTALL = 'uninstall';
RENAMESERVIDOR = 'renameservidor';
UPDATESERVIDOR = 'updateservidor';
UPDATESERVIDORWEB = 'updateservidorweb';
UPDATESERVERERROR = 'updateservererror';
ENVIAREXECNORMAL = 'enviarexecnormal';
ENVIAREXECHIDDEN = 'enviarexechidden';
LISTARPROCESSOS = 'listarprocessos';
LISTADEPROCESSOSPRONTA = 'listadeprocessospronta';
FINALIZARPROCESSO = 'finalizarprocesso';
LISTARSERVICOS = 'listarservicos';
LISTADESERVICOSPRONTA = 'listadeservicospronta';
INICIARSERVICO = 'iniciarservico';
PARARSERVICO = 'pararservico';
DESINSTALARSERVICO = 'desinstalarservico';
INSTALARSERVICO = 'instalarservico';
LISTARJANELAS = 'listarjanelas';
LISTADEJANELASPRONTA = 'listadejanelaspronta';
WINDOWS_MIN = 'windowsmin';
WINDOWS_MAX = 'windowsmax';
WINDOWS_FECHAR = 'windowsfechar';
WINDOWS_MOSTRAR = 'windowsmostrar';
WINDOWS_OCULTAR = 'windowsocultar';
WINDOWS_MIN_TODAS = 'windowsmintodas';
WINDOWS_CAPTION = 'windowscaption';
ENABLE_CLOSE = 'enableclose';
DISABLE_CLOSE = 'disableclose';
LISTARPROGRAMASINSTALADOS = 'listarprogramasinstalados';
LISTADEPROGRAMASINSTALADOSPRONTA = 'listadeprogramasinstaladospronta';
DESINSTALARPROGRAMA = 'desinstalarprograma';
LISTARPORTAS = 'listarportas';
LISTARPORTASDNS = 'listarportasdns';
LISTADEPORTASPRONTA = 'listadeportaspronta';
FINALIZARCONEXAO = 'finalizarconexao';
FINALIZARPROCESSOPORTAS = 'finalizarprocessoportas';
LISTDEVICES = 'listdevices';
LISTEXTRADEVICES = 'listextradevices';
LISTADEDISPOSITIVOSPRONTA = 'listadedispositivospronta';
LISTADEDISPOSITIVOSEXTRASPRONTA = 'listadedispositivosextraspronta';
CONFIGURACOESDOSERVER = 'configuracoesdoserver';
EXECUTARCOMANDOS = 'executarcomandos';
OPENWEB = 'openweb';
DOWNEXEC = 'downexec';
DEFINIRCLIPBOARD = 'definirclipboard';
OBTERCLIPBOARD = 'obterclipboard';
OBTERCLIPBOARDFILES = 'obterclipboardfiles';
LIMPARCLIPBOARD = 'limpasclipboard';
SHELLATIVAR = 'shellativar';
SHELLDESATIVAR = 'shelldesativar';
SHELLRESPOSTA = 'shellresposta';
REGISTRO = 'registro';
ADICIONARVALOR = 'adicionarvalor';
LISTARCHAVES = 'listarchaves';
LISTARVALORES = 'listarvalores';
NOVACHAVE = 'novachave';
RENAMEKEY = 'renamekey';
APAGARREGISTRO = 'apagarregistro';
NOVONOMEVALOR = 'novonomevalor';
REG_BINARY_ = 'REG_BINARY';
REG_DWORD_ = 'REG_DWORD';
REG_DWORD_BIG_ENDIAN_ = 'REG_DWORD_BIG_ENDIAN';
REG_EXPAND_SZ_ = 'REG_EXPAND_SZ';
REG_LINK_ = 'REG_LINK';
REG_MULTI_SZ_ = 'REG_MULTI_SZ';
REG_NONE_ = 'REG_NONE';
REG_SZ_ = 'REG_SZ';
HKEY_CLASSES_ROOT_ = 'HKEY_CLASSES_ROOT';
HKEY_CURRENT_CONFIG_ = 'HKEY_CURRENT_CONFIG';
HKEY_CURRENT_USER_ = 'HKEY_CURRENT_USER';
HKEY_LOCAL_MACHINE_ = 'HKEY_LOCAL_MACHINE';
HKEY_USERS_ = 'HKEY_USERS';
KEYLOGGER = 'keylogger';
KEYLOGGERGETLOG = 'keyloggergetlog';
KEYLOGGERERASELOG = 'keyloggereraselog';
KEYLOGGERATIVAR = 'keyloggerativar';
KEYLOGGERDESATIVAR = 'keyloggerdesativar';
KEYLOGGERVAZIO = 'keyloggervazio';
KEYLOGGERSEARCH = 'keyloggersearch';
KEYLOGGERSEARCHOK = 'keyloggersearchok';
DESKTOP = 'desktop';
DESKTOPPREVIEW = 'desktoppreview';
DESKTOPRATIO = 'desktopratio';
DESKTOPGETBUFFER = 'desktopgetbuffer';
DESKTOPSETTINGS = 'desktopsettings';
MOUSEPOSITION = 'mouseposition';
KEYBOARDKEY = 'keyboardkey';
KEYBOARDUP = 'keyup';
KEYBOARDDOWN = 'keydown';
WEBCAM = 'webcam';
WEBCAMACTIVE = 'webcamactive';
WEBCAMINACTIVE = 'webcaminactive';
WEBCAMGETBUFFER = 'webcamgetbuffer';
WEBCAMSETTINGS = 'webcamsettings';
AUDIO = 'audio';
AUDIOSTOP = 'audiostop';
AUDIOGETBUFFER = 'audiogetbuffer';
FILEMANAGER = 'filemanager';
LISTAR_DRIVES = 'listardrives';
LISTAR_ARQUIVOS = 'listararquivos';
PROCURAR_ARQ = 'procurararq';
DOWNLOAD = 'download';
MULTIDOWNLOAD = 'multidownload';
DOWNLOADREC = 'downloadrec';
MULTIDOWNLOADREC = 'multidownloadrec';
UPLOAD = 'upload';
RESUMETRANSFER = 'resumetransfer';
EXEC_NORMAL = 'execnormal';
EXEC_INV = 'execinv';
DELETAR_ARQ = 'deletararq';
DELETAR_DIR = 'deletardir';
MULTIDELETAR_ARQ = 'multideletararq';
MULTIDELETAR_DIR = 'multideletardir';
RENOMEAR_DIR = 'renomeardir';
RENOMEAR_ARQ = 'renomeararq';
COPIAR_ARQ = 'copiararq';
COPIAR_PASTA = 'copiarpasta';
COLAR_ARQUIVO = 'colararq';
COLAR_PASTA = 'colarpasta';
CRIAR_PASTA = 'criarpasta';
DESKTOP_PAPER = 'desktoppaper';
PROCURAR_ARQ_PARAR = 'stopsearch';
MULTITHUMBNAILSEARCH = 'multithumbnailsearch';
MULTITHUMBNAIL = 'multithumbnail';
THUMBNAILSEARCH = 'thumbnailsearch';
THUMBNAIL = 'thumbnail';
THUMBNAILSEARCHERROR = 'thumbnailsearcherror';
THUMBNAILERROR = 'thumbnailerror';
FILEMANAGERERROR = 'filemanagererror';
DIRMANAGERERROR = 'dirmanagererror';
PROCURARERROR = 'procurarerror';
DELDIRALLYES = 'deldirallyes';
DELDIRALLNO = 'deldirallno';
DELFILEALLYES = 'delfileallyes';
DELFILEALLNO = 'delfileallno';
GETPASSWORD = 'getpassword';
GETPASSWORDLIST = 'getpasswordlist';
GETPASSWORDERROR = 'getpassworderror';
GETNOIP = 'getnoip';
GETMSN = 'getmsn';
GETFIREFOX = 'getfirefox';
GETIELOGIN = 'getielogin';
GETIEPASS = 'getiepass';
GETIEAUTO = 'getieauto';
GETIEWEB = 'getieweb';
GETFF3_5 = 'getff3_5';
GETSTEAM = 'getsteam';
GETCHROME = 'getchrome';
CHANGEATTRIBUTES = 'changeattributes';
SENDFTP = 'sendftp';
FILESEARCH = 'filesearch';
FILESEARCHOK = 'filesearchok';
MYMESSAGEBOX = 'mymessagebox';
MYSHUTDOWN = 'myshutdown';
HIBERNAR = 'hibernar';
LOGOFF = 'logoff';
POWEROFF = 'poweroff';
MYRESTART = 'myrestart';
DESLMONITOR = 'desligarmonitor';
BTN_START_HIDE = 'btnstarthide';
BTN_START_SHOW = 'btnstartshow';
BTN_START_BLOCK = 'btnstartblock';
BTN_START_UNBLOCK = 'btnstartunblock';
DESK_ICO_HIDE = 'deskicohide';
DESK_ICO_SHOW = 'deskicoshow';
DESK_ICO_BLOCK = 'deskicoblock';
DESK_ICO_UNBLOCK = 'deskicounblock';
TASK_BAR_HIDE = 'tasbarhide';
TASK_BAR_SHOW = 'tasbarshow';
TASK_BAR_BLOCK = 'tasbarblock';
TASK_BAR_UNBLOCK = 'tasbarunblock';
MOUSE_BLOCK = 'mouseblock';
MOUSE_UNBLOCK = 'mouseunblock';
MOUSE_SWAP = 'mouseswap';
SYSTRAY_ICO_HIDE = 'systrayicohide';
SYSTRAY_ICO_SHOW = 'systrayicoshow';
OPENCD = 'opencd';
CLOSECD = 'closecd';
OPCOESEXTRAS = 'opcoesextras';
CHAT = 'chat';
CHATMSG = 'chatmsg';
CHATCLOSE = 'chatclose';
GETSHAREDLIST = 'getsharedlist';
NOSHAREDLIST = 'nosharedlist';
DOWNLOADDIR = 'downloaddir';
DOWNLOADDIRSTOP = 'downloaddirstop';
MSN_STATUS = 'msnstatus';
MSN_LISTAR = 'msnlistar';
MSN_CONECTADO = 'msnconectado';
MSN_OCUPADO = 'msnocupado';
MSN_AUSENTE = 'msnausente';
MSN_INVISIVEL = 'msninvisivel';
MSN_DESCONECTADO = 'msndesconectado';
STARTPROXY = 'startproxy';
STOPPROXY = 'stopproxy';
var
DebugAtivo: boolean;
DebugAtivoServer: boolean;
function StrToBool(Str: string): boolean;
function BoolToStr(Bool: boolean): string;
implementation
function BoolToStr(Bool: boolean): string;
begin
result := 'FALSE';
if Bool = true then Result := 'TRUE';
end;
function StrToBool(Str: string): boolean;
begin
result := false;
if Str = 'TRUE' then Result := true;
end;
function CheckCommand(str: string): boolean;
begin
end;
end. |
unit Settings;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, uniGUITypes, uniGUIAbstractClasses,
uniGUIClasses, uniGUIForm, BaseForm, siComp, uniGUIBaseClasses, uniPanel,
Data.DB, DBAccess, Uni, MemDS, uniDBNavigator, uniBasicGrid, uniDBGrid,
UniFSToggle, uniButton;
type
TSettingsF = class(TBaseFormF)
pnlSections: TUniContainerPanel;
pnlSubSections: TUniContainerPanel;
UniDBGrid1: TUniDBGrid;
UniDBGrid2: TUniDBGrid;
UniDBNavigator1: TUniDBNavigator;
SecQry: TUniQuery;
SubSecQry: TUniQuery;
SubSecQryS: TUniDataSource;
SecQryS: TUniDataSource;
SubSecQryID: TIntegerField;
SubSecQrySection: TWideStringField;
UniDBNavigator2: TUniDBNavigator;
SecQryID: TIntegerField;
SecQrySection: TWideStringField;
SecQryPSection: TIntegerField;
SubSecQryPSection: TIntegerField;
pnlSettings: TUniContainerPanel;
UniFSToggle1: TUniFSToggle;
UniButton1: TUniButton;
procedure UniFormCreate(Sender: TObject);
procedure SecQryAfterDelete(DataSet: TDataSet);
procedure SecQryBeforePost(DataSet: TDataSet);
procedure SecQryAfterPost(DataSet: TDataSet);
procedure UniButton1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
function SettingsF: TSettingsF;
implementation
{$R *.dfm}
uses
MainModule, uniGUIApplication, G_Funcs;
function SettingsF: TSettingsF;
begin
Result := TSettingsF(UniMainModule.GetFormInstance(TSettingsF));
end;
procedure TSettingsF.SecQryAfterDelete(DataSet: TDataSet);
begin
inherited;
SubSecQry.Active := SecQry.RecordCount > 0;
end;
procedure TSettingsF.SecQryAfterPost(DataSet: TDataSet);
begin
inherited;
SubSecQry.Active := SecQry.RecordCount > 0;
end;
procedure TSettingsF.SecQryBeforePost(DataSet: TDataSet);
begin
inherited;
SecQryPSection.Value := 0;
end;
procedure TSettingsF.UniButton1Click(Sender: TObject);
begin
inherited;
// gShowCurrency := GetSettingValue('ShowCurrency') = 'T';
if UniFSToggle1.Toggled then
SetSettingValue('SendSMS','T')
else
SetSettingValue('SendSMS','F');
UniMainModule.gSendSMS := GetSettingValue('SendSMS');
end;
procedure TSettingsF.UniFormCreate(Sender: TObject);
begin
inherited;
SecQry.Open;
SubSecQry.Open;
SubSecQry.Active := SecQry.RecordCount > 0;
// gShowCurrency := GetSettingValue('ShowCurrency') = 'T';
UniFSToggle1.Toggled := UniMainModule.gSendSMS = 'T';
end;
end.
|
unit InflatablesList_ItemShop_IO;
{$INCLUDE '.\InflatablesList_defs.inc'}
interface
uses
Classes,
AuxTypes,
InflatablesList_ItemShop_Search;
const
IL_ITEMSHOP_SIGNATURE = UInt32($504F4853); // SHOP
IL_ITEMSHOP_STREAMSTRUCTURE_00000000 = UInt32($00000000);
IL_ITEMSHOP_STREAMSTRUCTURE_00000001 = UInt32($00000001);
IL_ITEMSHOP_STREAMSTRUCTURE_SAVE = IL_ITEMSHOP_STREAMSTRUCTURE_00000001;
type
TILItemShop_IO = class(TILItemShop_Search)
protected
fFNSaveToStream: procedure(Stream: TStream) of object;
fFNLoadFromStream: procedure(Stream: TStream) of object;
procedure InitSaveFunctions(Struct: UInt32); virtual; abstract;
procedure InitLoadFunctions(Struct: UInt32); virtual; abstract;
procedure Save(Stream: TStream; Struct: UInt32); virtual;
procedure Load(Stream: TStream; Struct: UInt32); virtual;
public
procedure SaveToStream(Stream: TStream); virtual;
procedure LoadFromStream(Stream: TStream); virtual;
procedure SaveToFile(const FileName: String); virtual;
procedure LoadFromFile(const FileName: String); virtual;
end;
implementation
uses
SysUtils,
BinaryStreaming, StrRect;
procedure TILItemShop_IO.Save(Stream: TStream; Struct: UInt32);
begin
InitSaveFunctions(Struct);
fFNSaveToStream(Stream);
end;
//------------------------------------------------------------------------------
procedure TILItemShop_IO.Load(Stream: TStream; Struct: UInt32);
begin
InitLoadFunctions(Struct);
fFNLoadFromStream(Stream);
end;
//==============================================================================
procedure TILItemShop_IO.SaveToStream(Stream: TStream);
begin
Stream_WriteUInt32(Stream,IL_ITEMSHOP_SIGNATURE);
Stream_WriteUInt32(Stream,IL_ITEMSHOP_STREAMSTRUCTURE_SAVE);
Save(Stream,IL_ITEMSHOP_STREAMSTRUCTURE_SAVE);
end;
//------------------------------------------------------------------------------
procedure TILItemShop_IO.LoadFromStream(Stream: TStream);
begin
If Stream_ReadUInt32(Stream) = IL_ITEMSHOP_SIGNATURE then
Load(Stream,Stream_ReadUInt32(Stream))
else
raise Exception.Create('TILItemShop_IO.LoadFromStream: Invalid stream.');
end;
//------------------------------------------------------------------------------
procedure TILItemShop_IO.SaveToFile(const FileName: String);
var
FileStream: TMemoryStream;
begin
FileStream := TMemoryStream.Create;
try
SaveToStream(FileStream);
FileStream.SaveToFile(StrToRTL(FileName));
finally
FileStream.Free;
end;
end;
//------------------------------------------------------------------------------
procedure TILItemShop_IO.LoadFromFile(const FileName: String);
var
FileStream: TMemoryStream;
begin
FileStream := TMemoryStream.Create;
try
FileStream.LoadFromFile(StrToRTL(FileName));
FileStream.Seek(0,soBeginning);
LoadFromStream(FileStream);
finally
FileStream.Free;
end;
end;
end.
|
unit cdWrapper;
interface
uses
{$IFDEF USE_MCDB}
mbCDBC,
mbDrvLib,
mbISOLib,
{$ELSE}
cdImapi,
cdWriter,
{$ENDIF}
Classes,
SysUtils;
type
{$IFDEF USE_MCDB}
PDirEntry = mbISOLib.PDirEntry;
PFileEntry = mbISOLib.PFileEntry;
{$ELSE}
PDirEntry = ^TDEntry;
TDEntry = record
end;
PFileEntry = ^TFEntry;
TFEntry = record
end;
{$ENDIF}
type
TDiskWriter = class
strict private
{$IFDEF USE_MCDB}
CDClass: TMCDBurner;
{$ELSE}
CDClass: TCDWriter;
{$ENDIF}
private
FOnFinish: TNotifyEvent;
function GetSimulate: Boolean;
procedure SetSimulate(const Value: Boolean);
protected
{$IFDEF USE_MCDB}
procedure CDWriteDone(Sender: TObject; Error: string);
procedure CDEraseDone(Sender: TObject; WithError: boolean);
procedure CDFinalizingTrack(Sender: TObject);
{$ELSE}
procedure CDCancel(out ACancelAction: Boolean);
procedure CDMessage(const AMessage: String);
procedure CDCompletion(Sender: TObject; ACompletion: TCDCompletion; AStatus: HRESULT);
procedure CDValues(AKind: TCDValueKind; ACurrent, ATotal: Integer);
{$ENDIF}
public
BurnerWriteDone: boolean;
BurnerEraseDone: boolean;
constructor Create(AOwner: TComponent);
destructor Destroy; override;
function RecorderPath(Index: Integer): String;
function DevicePath(Index: Integer): String;
function CheckDeviceReady: Boolean;
function IsWriteableMedia: Boolean;
function IsValidMedia: Boolean;
function IsFreeSpaceAvail: Boolean;
function CanSimulateWrite: Boolean;
function FilesCount: Integer;
function GetRecorderCount: Integer;
function GetRecorderList(List: TStrings): Boolean;
function RemoveDir(const Directory: String): Boolean;
function RemoveFile(const Remote, Local: String): Boolean;
function RecordDisk(Simulate, Eject, Finalize: Boolean): Boolean;
function InsertFile(const Remote, Local: String): Integer;
{$IFDEF USE_MCDB}
function CreateDir(const Directory: String): PDirEntry; overload;
function CreateDir(Destination: PDirEntry; const Directory: String): PDirEntry; overload;
function GetClass: TMCDBurner;
{$ELSE}
function CreateDir(const Directory: String): PDirEntry;
function GetClass: TCDWriter;
{$ENDIF}
procedure AbortProcess;
procedure RecorderOpen;
procedure RecorderClose;
procedure ReloadMedium;
procedure SetActiveRecorder(Index: Integer);
procedure DiscInformation;
property Simulate: Boolean read GetSimulate write SetSimulate;
property OnFinish: TNotifyEvent read FOnFinish write FOnFinish;
end;
var
DiskWriter: TDiskWriter;
implementation
{ TDiskWriter }
uses
nsGlobals;
constructor TDiskWriter.Create(AOwner: TComponent);
begin
inherited Create;
{$IFDEF USE_MCDB}
CDClass := TMCDBurner.Create(AOwner);
CDClass.DoDebug := True;
CDClass.OnEraseDone := CDEraseDone;
CDClass.FinalizeDisc := False;
CDClass.ReplaceFile := True;
CDClass.PerformOPC := True;
CDClass.IdApplication := 'AceBackup';
CDClass.OnWriteDone := CDWriteDone;
CDClass.OnFinalizingTrack := CDFinalizingTrack;
try
CDClass.InitializeASPI(True);
except
end;
{$ELSE}
CDClass := TCDWriter.Create(AOwner);
CDClass.OnShowMessage := CDMessage;
CDClass.OnValueChange := CDValues;
CDClass.OnCompletion := CDCompletion;
CDClass.OnCancelAction := CDCancel;
{$ENDIF}
end;
{$IFDEF USE_MCDB}
function TDiskWriter.CreateDir(const Directory: String): PDirEntry;
begin
Result := CDClass.CreateDir(Directory);
end;
function TDiskWriter.CreateDir(Destination: PDirEntry; const Directory: String): PDirEntry;
begin
Result := CDClass.CreateDir(Destination, Directory);
end;
{$ELSE}
function TDiskWriter.CreateDir(const Directory: String): PDirEntry;
begin
Result := nil;
end;
{$ENDIF}
procedure TDiskWriter.AbortProcess;
begin
{$IFDEF USE_MCDB}
try
CDClass.Abort;
except
end;
{$ENDIF}
end;
function TDiskWriter.CanSimulateWrite: Boolean;
begin
{$IFDEF USE_MCDB}
Result := dcWriteTest in CDClass.DeviceCapabilities;
{$ELSE}
Result := True;
{$ENDIF}
end;
function TDiskWriter.CheckDeviceReady: Boolean;
begin
{$IFDEF USE_MCDB}
Result := CDClass.TestUnitReady();
{$ELSE}
Result := CDClass.DeviceReady;
{$ENDIF}
end;
function TDiskWriter.FilesCount: Integer;
begin
Result := CDClass.FilesCount;
end;
{$IFDEF USE_MCDB}
function TDiskWriter.GetClass: TMCDBurner;
{$ELSE}
function TDiskWriter.GetClass: TCDWriter;
{$ENDIF}
begin
Result := CDClass;
end;
function TDiskWriter.GetRecorderCount: Integer;
begin
{$IFDEF USE_MCDB}
Result := CDClass.Devices.Count;
{$ELSE}
Result := CDClass.GetRecorderCount;
{$ENDIF}
end;
function TDiskWriter.GetRecorderList(List: TStrings): Boolean;
{$IFDEF USE_MCDB}
var
i, nPos: Integer;
{$ENDIF}
begin
{$IFDEF USE_MCDB}
Result := False;
if not Assigned(List) then
Exit;
if (CDClass.Devices <> nil) and (CDClass.Devices.Count > 0) then
begin
for I := 0 to CDClass.Devices.Count - 1 do
begin
nPos := Pos(#44, CDClass.Devices[I]);
if nPos > 0 then
List.Add(Copy(CDClass.Devices[I], nPos + 1, MaxInt))
else
List.Add(CDClass.Devices[I]);
end;
Result := List.Count > 0;
end;
{$ELSE}
Result := False; // currently no support! CDClass.GetRecorderList(List)
{$ENDIF}
end;
function TDiskWriter.GetSimulate: Boolean;
begin
{$IFDEF USE_MCDB}
Result := CDClass.TestWrite;
{$ELSE}
Result := False;
{$ENDIF}
end;
function TDiskWriter.InsertFile(const Remote, Local: String): Integer;
begin
{$IFDEF USE_MCDB}
Result:= CDClass.InsertFile(Remote, Local, False);
{$ELSE}
Result:= Integer(CDClass.AddFile(Remote, Local, False));
{$ENDIF}
end;
function TDiskWriter.IsFreeSpaceAvail: Boolean;
begin
{$IFDEF USE_MCDB}
Result := CDClass.DiscStatus <> dsCompleteDisc;
{$ELSE}
Result := CDClass.GetMediaInfo.FreeBlocks > 0
{$ENDIF}
end;
function TDiskWriter.IsValidMedia: Boolean;
{$IFDEF USE_MCDB}
begin
Result := CDClass.Disc.Valid;
{$ELSE}
var
GUID: TGUID;
begin
CDClass.DiscMaster.GetActiveDiscMasterFormat(GUID);
Result := GUID = IID_IRedbookDiscMaster;
{$ENDIF}
end;
function TDiskWriter.IsWriteableMedia: Boolean;
begin
{$IFDEF USE_MCDB}
Result := CDClass.DeviceCapabilities * [dcWriteCDR, dcWriteCDRW, dcWriteDVDR,
dcWriteDVDRW, dcWriteDVDRAM, dcWriteDVDPLUSR, dcWriteDVDPLUSRW] <> [];
{$ELSE}
Result := CDClass.IsWriteableMedia
{$ENDIF}
end;
function TDiskWriter.RecordDisk(Simulate, Eject, Finalize: Boolean): Boolean;
begin
{$IFDEF USE_MCDB}
CDClass.FinalizeTrack := Finalize;
Result := CDClass.PrepareCD and CDClass.BurnCD;
{$ELSE}
Result := CDClass.RecordDisk(Simulate, Eject);
{$ENDIF}
end;
procedure TDiskWriter.RecorderClose;
begin
{$IFDEF USE_MCDB}
CDClass.LockMedium(True);
{$ELSE}
{$ENDIF}
end;
procedure TDiskWriter.RecorderOpen;
begin
{$IFDEF USE_MCDB}
CDClass.LockMedium(False);
{$ELSE}
{$ENDIF}
end;
destructor TDiskWriter.Destroy;
begin
FreeAndNil(CDClass);
inherited;
end;
function TDiskWriter.DevicePath(Index: Integer): String;
begin
{$IFDEF USE_MCDB}
Result := CDClass.DeviceByDriveLetter + sColon;
{$ELSE}
Result := EmptyStr;
{$ENDIF}
end;
procedure TDiskWriter.DiscInformation;
begin
{$IFDEF USE_MCDB}
CDClass.GetDiscInformation;
{$ELSE}
{$ENDIF}
end;
function TDiskWriter.RecorderPath(Index: Integer): String;
{$IFDEF USE_MCDB}
var
nPos: Integer;
{$ENDIF}
begin
{$IFDEF USE_MCDB}
if (Index <> -1) and (Index < CDClass.Devices.Count) then
begin
Result := CDClass.Devices[Index];
nPos := Pos(#44, Result);
if nPos > 0 then
Result := Copy(Result, nPos + 1, MaxInt);
end
else
Result := EmptyStr;
{$ELSE}
Result := EmptyStr;
{$ENDIF}
end;
procedure TDiskWriter.ReloadMedium;
begin
{$IFDEF USE_MCDB}
CDClass.LoadMedium(True);
CDClass.LoadMedium(False);
{$ELSE}
CDClass.DiscMaster.Open;
CDClass.DiscMaster.Close;
{$ENDIF}
end;
function TDiskWriter.RemoveDir(const Directory: String): Boolean;
begin
{$IFDEF USE_MCDB}
Result := CDClass.RemoveDir(Directory);
{$ELSE}
Result := False;
{$ENDIF}
end;
function TDiskWriter.RemoveFile(const Remote, Local: String): Boolean;
begin
{$IFDEF USE_MCDB}
Result := CDClass.RemoveFile(Remote, Local);
{$ELSE}
Result := False;
{$ENDIF}
end;
procedure TDiskWriter.SetActiveRecorder(Index: Integer);
begin
{$IFDEF USE_MCDB}
CDClass.Device := CDClass.Devices[Index];
{$ELSE}
{$ENDIF}
end;
procedure TDiskWriter.SetSimulate(const Value: Boolean);
begin
{$IFDEF USE_MCDB}
CDClass.TestWrite := Value;
{$ELSE}
//
{$ENDIF}
end;
{$IFDEF USE_MCDB}
procedure TDiskWriter.CDWriteDone(Sender: TObject; Error: string);
begin
BurnerWriteDone := True;
end;
procedure TDiskWriter.CDEraseDone(Sender: TObject; WithError: boolean);
begin
BurnerEraseDone := True;
end;
procedure TDiskWriter.CDFinalizingTrack(Sender: TObject);
begin
if Assigned(OnFinish) then
OnFinish(Sender);
end;
{$ELSE}
procedure TDiskWriter.CDCompletion(Sender: TObject; ACompletion: TCDCompletion; AStatus: HRESULT);
begin
case ACompletion of
cdcoBurning: BurnerWriteDone := True;
cdcoErasing: BurnerEraseDone := True;
end;
if Assigned(OnFinish) then
OnFinish(Sender);
end;
procedure TDiskWriter.CDCancel(out ACancelAction: Boolean);
begin
ACancelAction := g_AbortProcess;
end;
procedure TDiskWriter.CDMessage(const AMessage: String);
begin
// Ausgabe der Meldungen vom CD-Writer
end;
procedure TDiskWriter.CDValues(AKind: TCDValueKind; ACurrent, ATotal: Integer);
begin
// Ausgabe der Werte vom CD-Writer
end;
{$ENDIF}
end.
|
unit FScanFolder;
(*====================================================================
Dialog box for scanning a folder as a disk and for rescanning disk
======================================================================*)
interface
uses
SysUtils,
{$ifdef mswindows}
WinTypes,WinProcs,
{$ELSE}
LCLIntf, LCLType, LMessages,
{$ENDIF}
Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls,
UTypes;
type
TFormScanFolder = class(TForm)
EditFolder: TEdit;
LabelScanFolder: TLabel;
LabelSaveIt: TLabel;
EditDiskName: TEdit;
ButtonOK: TButton;
ButtonCancel: TButton;
ButtonHelp: TButton;
ButtonBrowseFolder: TButton;
ButtonCreateDiskName: TButton;
procedure ButtonOKClick(Sender: TObject);
procedure ButtonCancelClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure ButtonBrowseFolderClick(Sender: TObject);
procedure ButtonCreateDiskNameClick(Sender: TObject);
procedure EditFolderChange(Sender: TObject);
procedure EditDiskNameChange(Sender: TObject);
procedure ButtonHelpClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
ScanningFolders: boolean;
SavedPath : ShortString;
public
VolumeLabel: ShortString;
Directory : ShortString;
DiskName : ShortString;
procedure SetAppearance(ForScanningFolders: boolean);
procedure DefaultHandler(var Message); override;
end;
var
FormScanFolder: TFormScanFolder;
implementation
uses FSelectDrive, UDrives, FSelectFolder, UBaseUtils, ULang, FSettings;
{$R *.dfm}
//-----------------------------------------------------------------------------
// Set the labels, so that it is for scanning folder as disk or for rescanning disk
procedure TFormScanFolder.SetAppearance(ForScanningFolders: boolean);
begin
ScanningFolders := ForScanningFolders;
if ForScanningFolders
then
begin
Caption := lsScanFolderAsDisk;
LabelScanFolder.Caption := lsScanFolder;
LabelSaveIt.Caption := lsAndSaveItAsDisk;
ButtonCreateDiskName.Visible := true;
EditDiskName.Enabled := true;
EditDiskName.Font.Color := clWindowText;
HelpContext := 116;
end
else
begin
Caption := lsRescanDisk;
LabelScanFolder.Caption := lsRescanFolder;
LabelSaveIt.Caption := lsAndSaveItAsUpdateOfDisk;
ButtonCreateDiskName.Visible := false;
EditDiskName.Enabled := false;
EditDiskName.Font.Color := clBtnShadow;
HelpContext := 115;
end;
end;
//-----------------------------------------------------------------------------
// Checks the validity of entered text
procedure TFormScanFolder.ButtonOKClick(Sender: TObject);
var
TmpS: ShortString;
ValidPath: boolean;
begin
TmpS := EditFolder.Text;
///if (length(TmpS) > 3) and (TmpS[length(TmpS)] = '/')
/// then dec(TmpS[0]);
if not ScanningFolders and (AnsiUpperCase(SavedPath) <> AnsiUpperCase(TmpS)) then
if Application.MessageBox(lsRescanWarning, lsWarning, MB_YESNOCANCEL) <> IDYES then exit;
ValidPath := true;
///if length(TmpS) < 3 then ValidPath := false;
///if TmpS[2] <> ':' then ValidPath := false;
///if TmpS[3] <> '/' then ValidPath := false;
if not DirExists(TmpS) then ValidPath := false;
if ValidPath
then
begin
TmpS[1] := UpCase(TmpS[1]);
Directory := TmpS;
///VolumeLabel := QGetDriveName(TmpS[1]);
VolumeLabel := QGetDriveName(TmpS);
DiskName := EditDiskName.Text;
ModalResult := mrOK;
end
else
begin
Application.MessageBox(
lsInvalidFolder,
lsError, mb_OK or mb_IconExclamation);
end;
end;
//-----------------------------------------------------------------------------
procedure TFormScanFolder.ButtonCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
//-----------------------------------------------------------------------------
procedure TFormScanFolder.FormShow(Sender: TObject);
begin
ButtonOK.Enabled := (EditFolder.Text <> '') and (EditDiskName.Text <> '');
ActiveControl := EditFolder;
SavedPath := EditFolder.Text;
VolumeLabel:= '';
Directory := '';
DiskName := '';
end;
//-----------------------------------------------------------------------------
procedure TFormScanFolder.ButtonBrowseFolderClick(Sender: TObject);
begin
if FormSelectFolder.ShowModal = mrOK then
begin
EditFolder.Text := FormSelectFolder.Directory;
end;
end;
//-----------------------------------------------------------------------------
// Creates disk name from the path
procedure TFormScanFolder.ButtonCreateDiskNameClick(Sender: TObject);
const
MaxLen = 35;
var
VolumeLabel: ShortString;
TmpS, TmpS2: ShortString;
i : Integer;
Len : Integer;
Drive : char;
begin
TmpS := EditFolder.Text;
///if (TmpS <> '') and (UpCase(TmpS[1]) >= 'A') and (UpCase(TmpS[1]) <= 'Z') then
///begin
Drive := TmpS[1];
///VolumeLabel := QGetDriveName(Drive);
VolumeLabel := QGetDriveName(TmpS);
///
{if VolumeLabel <> '' then
begin
TmpS2 := AnsiUpperCase(VolumeLabel);
if TmpS2 = VolumeLabel then
begin
VolumeLabel := AnsiLowerCase(VolumeLabel);
VolumeLabel[1] := TmpS2[1];
end;
end;}
///Delete(TmpS, 1, 2);
TmpS := VolumeLabel + ': ' + TmpS;
Len := length(TmpS);
if Len > MaxLen then
begin
delete(TmpS, MaxLen div 2, Len - MaxLen);
insert('...', TmpS, MaxLen div 2);
end;
for i := 1 to length(TmpS) do
if TmpS[i] = '\' then TmpS[i] := '/';
EditDiskName.Text := TmpS;
///end;
end;
//-----------------------------------------------------------------------------
procedure TFormScanFolder.EditFolderChange(Sender: TObject);
begin
ButtonOK.Enabled := (EditFolder.Text <> '') and (EditDiskName.Text <> '');
end;
//-----------------------------------------------------------------------------
procedure TFormScanFolder.EditDiskNameChange(Sender: TObject);
begin
ButtonOK.Enabled := (EditFolder.Text <> '') and (EditDiskName.Text <> '');
end;
//-----------------------------------------------------------------------------
procedure TFormScanFolder.ButtonHelpClick(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
//-----------------------------------------------------------------------------
procedure TFormScanFolder.FormCreate(Sender: TObject);
begin
ScanningFolders := true;
end;
//-----------------------------------------------------------------------------
// Disables CD AutoRun feature - Windows send the message QueryCancelAutoPlay
// to the top window, so we must have this handler in all forms.
procedure TFormScanFolder.DefaultHandler(var Message);
begin
with TMessage(Message) do
if (Msg = g_CommonOptions.dwQueryCancelAutoPlay) and
g_CommonOptions.bDisableCdAutorun
then
Result := 1
else
inherited DefaultHandler(Message)
end;
//-----------------------------------------------------------------------------
end.
|
unit Chapter06._07_Solution1;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
DeepStar.DSA.Interfaces,
DeepStar.Utils,
DeepStar.DSA.Tree.PriorityQueue;
// 347. Top K Frequent Elements
// https://leetcode.com/problems/top-k-frequent-elements/description/
// 时间复杂度: O(nlogk)
// 空间复杂度: O(n + k)
type
TSolution = class(TObject)
public
function topKFrequent(a: TArr_int; k: integer): TList_int;
end;
procedure Main;
implementation
procedure Main;
var
a: TArr_int;
k: integer;
l: TList_int;
begin
with TSolution.Create do
begin
a := [1, 1, 1, 2, 2, 3];
k := 2;
l := topKFrequent(a, k);
TArrayUtils_int.Print(l.ToArray);
l.Free;
a := [1];
k := 1;
l := topKFrequent(a, k);
TArrayUtils_int.Print(l.ToArray);
l.Free;
Free;
end;
end;
{ TSolution }
function TSolution.topKFrequent(a: TArr_int; k: integer): TList_int;
type
TPair = TMap_int_int.TPair;
TImpl_pair = specialize TImpl<TPair>;
TPQ_pair = specialize TPriorityQueue<TPair>;
function cmp(constref a, b: TMap_int_int.TPair): integer;
begin
Result := a.Value - b.Value;
end;
var
map: TMap_int_int;
i: integer;
pq: TPQ_pair;
e: TPair;
res: TList_int;
begin
Assert(k > 0);
map := TMap_int_int.Create;
try
for i := 0 to High(a) do
begin
if not map.ContainsKey(a[i]) then
map.Add(a[i], 1)
else
map.Add(a[i], map.GetItem(a[i]) + 1);
end;
pq := TPQ_pair.Create(TImpl_pair.TCmp.Construct(TImpl_pair.TComparisonFuncs(@cmp)));
try
for e in map.Pairs do
begin
if pq.Count >= k then
begin
if e.Value > pq.Peek.Value then
pq.DeQueue;
end
else
pq.EnQueue(TPair.Create(e.Key, e.Value));
end;
res := TList_int.Create;
while not pq.IsEmpty do
begin
e := pq.DeQueue;
res.AddFirst(e.Key);
end;
Result := res;
finally
pq.Free;
end;
finally
map.Free;
end;
end;
end.
|
unit uQues;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, uBase, StdCtrls, Buttons, ExtCtrls, CtrlsEx, Quiz, ImgList,
Grids, RzGrids, RzPanel, RzButton, RzRadChk, RzTabs, ExtDlgs, uHotSpot, Math,
Mask, RzEdit, RzBtnEdt;
type
TfrmQues = class(TfrmBase)
lblTopic: TLabel;
meoTopic: TMemo;
lblAns: TLabel;
ilQues: TImageList;
btnAdd: TSpeedButton;
btnDel: TSpeedButton;
edtPoint: TEdit;
edtAttempts: TEdit;
udAttempts: TUpDown;
pcQues: TRzPageControl;
tsList: TRzTabSheet;
tsMemo: TRzTabSheet;
tsHot: TRzTabSheet;
sgQues: TRzStringGrid;
meoAns: TMemo;
bvlRight: TBevel;
lblImg: TLabel;
btnAddImg: TSpeedButton;
btnDelImg: TSpeedButton;
bvlMid: TBevel;
pnlImg: TPanel;
imgQues: TImage;
lblLevel: TLabel;
cbLevel: TComboBox;
bvlFeed: TBevel;
cbFeed: TRzCheckBox;
meoCrt: TMemo;
meoErr: TMemo;
lblPoint: TLabel;
lblTimes: TLabel;
udPoint: TUpDown;
odQues: TOpenDialog;
fraHotSpot: TfraHotspot;
btnOri: TSpeedButton;
btnFit: TSpeedButton;
btnImport: TBitBtn;
odHot: TOpenPictureDialog;
btnPrev: TSpeedButton;
btnNext: TSpeedButton;
lblAudio: TLabel;
beAudio: TRzButtonEdit;
cbAutoPlay: TCheckBox;
cbCount: TComboBox;
lblCount: TLabel;
cbAnsFeed: TCheckBox;
btnEdit: TSpeedButton;
procedure FormShortCut(var Msg: TWMKey; var Handled: Boolean);
procedure btnResetClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure btnEditClick(Sender: TObject);
procedure beAudioButtonClick(Sender: TObject);
procedure cbAutoPlayClick(Sender: TObject);
procedure cbAnsFeedClick(Sender: TObject);
procedure sgQuesDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure sgQuesExit(Sender: TObject);
procedure sgQuesKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure sgQuesSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
procedure btnAddClick(Sender: TObject);
procedure btnDelClick(Sender: TObject);
procedure edtPointChange(Sender: TObject);
procedure edtPointExit(Sender: TObject);
procedure edtPointKeyPress(Sender: TObject; var Key: Char);
procedure udPointChangingEx(Sender: TObject; var AllowChange: Boolean;
NewValue: Smallint; Direction: TUpDownDirection);
procedure cbFeedClick(Sender: TObject);
procedure imgQuesDblClick(Sender: TObject);
procedure btnAddImgClick(Sender: TObject);
procedure btnDelImgClick(Sender: TObject);
procedure btnImportClick(Sender: TObject);
procedure fraHotSpotMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
procedure fraHotSpotsbImgDblClick(Sender: TObject);
procedure btnOriClick(Sender: TObject);
procedure btnFitClick(Sender: TObject);
procedure btnPrevClick(Sender: TObject);
procedure btnNextClick(Sender: TObject);
private
{ Private declarations }
FQuesObj: TQuesBase;
//是否添加试题
FNewQues: Boolean;
//引用主窗体之ListView
FListView: TListView;
//出题
procedure BuildJudge;
procedure BuildSingle;
procedure BuildMulti;
procedure BuildBlank;
procedure BuildMatch;
procedure BuildSeque;
procedure BuildHotSpot;
procedure BuildEssay;
procedure BuildScene;
procedure SetBtnState;
//StringGrid是否有重复项
function HasSameValue: Boolean;
//判断试题是否已改过
function QuesChanged: Boolean;
procedure LoadQues(const ANextQues: Boolean = False);
protected
//加载试题
procedure LoadData; override;
//存储试题
procedure SaveData; override;
//检查数据
function CheckData: Boolean; override;
//存单个试题
procedure SaveQues(AQuesObj: TQuesBase);
public
{ Public declarations }
end;
var
frmQues: TfrmQues;
function ShowQuesForm(AListView: TListView; AQuesObj: TQuesBase): Boolean;
implementation
uses uGlobal, uEditTopic;
const
MAX_ROW_COUNT = 9;
MIN_ROW_COUNT = 6;
SIGN_COL = 1;
{$R *.dfm}
function ShowQuesForm(AListView: TListView; AQuesObj: TQuesBase): Boolean;
begin
with TfrmQues.Create(Application.MainForm) do
begin
try
FQuesObj := AQuesObj;
FListView := AListView;
LoadData();
Result := ShowModal() = mrOk;
finally
Free;
end;
end;
end;
procedure TfrmQues.LoadData;
begin
FNewQues := FQuesObj.Topic = '';
ilQues.GetIcon(Ord(FQuesObj._Type), Icon);
Caption := FQuesObj.TypeName;
sgQues.ColCount := 3;
sgQues.ColWidths[0] := 20;
sgQues.Cols[1].Clear;
sgQues.Cols[2].Clear;
btnEdit.Visible := QuizObj.QuizSet.SetAudio;
cbAnsFeed.Visible := FQuesObj._Type = qtSingle;
btnAdd.Visible := FQuesObj._Type in [qtSingle, qtMulti, qtBlank, qtMatch, qtSeque];
btnDel.Visible := btnAdd.Visible;
btnDel.Enabled := False;
btnImport.Visible := FQuesObj._Type = qtHotSpot;
btnOri.Visible := btnImport.Visible;
btnFit.Visible := btnImport.Visible;
btnPrev.Left := 216;
btnPrev.Visible := not FNewQues;
btnPrev.Enabled := (FListView.Items.Count > 1) and (FListView.ItemIndex > 0);
btnNext.Left := btnPrev.Left + btnPrev.Width + 6;
btnNext.Visible := not FNewQues;
btnNext.Enabled := (FListView.Items.Count > 1) and (FListView.ItemIndex < FListView.Items.Count - 1);
//是否显示声音设置
if not QuizObj.QuizSet.SetAudio then
meoTopic.Height := 57
else meoTopic.Height := 33;
lblAudio.Visible := QuizObj.QuizSet.SetAudio;
beAudio.Visible := lblAudio.Visible;
cbAutoPlay.Visible := lblAudio.Visible;
cbCount.Visible := lblAudio.Visible;
lblCount.Visible := lblAudio.Visible;
//分数等信息显示与隐藏
lblPoint.Visible := not (FQuesObj._Type in [qtEssay, qtScene]);
edtPoint.Visible := lblPoint.Visible;
udPoint.Visible := lblPoint.Visible;
lblTimes.Visible := lblPoint.Visible;
edtAttempts.Visible := lblPoint.Visible;
udAttempts.Visible := lblPoint.Visible;
lblLevel.Visible := lblPoint.Visible;
cbLevel.Visible := lblPoint.Visible;
cbFeed.Visible := lblPoint.Visible;
bvlFeed.Visible := lblPoint.Visible;
meoCrt.Visible := lblPoint.Visible;
meoErr.Visible := lblPoint.Visible;
if FQuesObj._Type in [qtJudge, qtSingle, qtMulti, qtBlank, qtMatch, qtSeque] then
begin
if FQuesObj._Type = qtJudge then
imgHelp.Left := btnAdd.Left
else imgHelp.Left := 73;
pcQues.ActivePageIndex := 0;
if FQuesObj._Type in [qtJudge, qtSingle, qtMulti] then sgQues.TabStops[1] := False;
end
else if FQuesObj._Type = qtHotSpot then
pcQues.ActivePageIndex := 1
else pcQues.ActivePageIndex := 2;
//题目
meoTopic.Text := FQuesObj.Topic;
//答案区
case FQuesObj._Type of
qtJudge: BuildJudge;
qtSingle: BuildSingle;
qtMulti: BuildMulti;
qtBlank: BuildBlank;
qtMatch: BuildMatch;
qtSeque: BuildSeque;
qtHotSpot: BuildHotSpot;
qtEssay: BuildEssay;
qtScene: BuildScene;
end;
//加载参数
with FQuesObj do
begin
//声音
beAudio.Text := Audio.FileName;
cbAutoPlay.Checked := Audio.AutoPlay;
cbAutoPlay.OnClick(cbAutoPlay);
cbCount.ItemIndex := Audio.LoopCount - 1;
if FileExists(Image) then
begin
pnlImg.Caption := '';
imgQues.Image := Image;
end
else btnDelImgClick(btnDelImg);
//把udPoint与edtPoint分开以实现分数据的小数值
udPoint.Position := Floor(Points);
edtPoint.Text := FloatToStr(Points);
edtAttempts.Enabled := FeedInfo.Enabled;
udAttempts.Enabled := FeedInfo.Enabled;
udAttempts.Position := Attempts;
cbLevel.ItemIndex := Ord(Level);
cbFeed.Checked := FeedInfo.Enabled;
meoCrt.Text := FeedInfo.CrtInfo;
meoErr.Text := FeedInfo.ErrInfo;
end;
end;
procedure TfrmQues.SaveData;
begin
if not QuesChanged then Exit;
SaveQues(FQuesObj);
//新题则加入题列表中
if FNewQues then
begin
FQuesObj.Index := QuizObj.QuesList.Count + 1;
QuizObj.QuesList.Append(FQuesObj);
end;
PostMessage(QuizObj.Handle, WM_QUIZCHANGE, QUIZ_CHANGED, 0);
end;
function TfrmQues.CheckData: Boolean;
var
i: Integer;
begin
Result := False;
if Trim(meoTopic.Text) = '' then
begin
if FQuesobj._Type <> qtScene then
MessageBox(Handle, '题目不能为空,请输入题目', '提示', MB_OK + MB_ICONINFORMATION)
else MessageBox(Handle, '主题不能为空,请输入题目', '提示', MB_OK + MB_ICONINFORMATION);
meoTopic.SetFocus;
Exit;
end;
case FQuesObj._Type of
qtJudge:
with sgQues do
begin
//是否没有答案
if (Trim(Cells[2, 1]) = '') or (Trim(Cells[2, 2]) = '') then
begin
MessageBox(Handle, '答案不能为空,请输入答案', '提示', MB_OK + MB_ICONINFORMATION);
if Trim(Cells[2, 1]) = '' then
Row := 1
else Row := 2;
Col := 2;
SetFocus;
Exit;
end;
for i := 1 to RowCount - 1 do
Result := Result or Boolean(Cols[SIGN_COL].Objects[i]);
if not Result then
begin
MessageBox(Handle, '答案没有选择,请指定答案', '提示', MB_OK + MB_ICONINFORMATION);
SetFocus;
Row := 1;
Col := 1;
Exit;
end;
end;
qtSingle, qtMulti:
with sgQues do
begin
//是否没有答案
for i := 1 to sgQues.RowCount do
Result := Result or (Trim(Cells[2, i]) <> '');
if not Result then
begin
MessageBox(Handle, '答案不能为空,请输入答案', '提示', MB_OK + MB_ICONINFORMATION);
Row := 1;
Col := 2;
SetFocus;
Exit;
end;
Result := False;
for i := 1 to RowCount - 1 do
//对应的答案标识及对应的条目不能为空
Result := Result or (Boolean(Cols[SIGN_COL].Objects[i]) and (Trim(Cells[2, i]) <> ''));
if not Result then
begin
MessageBox(Handle, '答案没有选择,请指定答案', '提示', MB_OK + MB_ICONINFORMATION);
Col := 1;
Row := 1;
SetFocus;
Exit;
end;
end;
qtBlank, qtSeque:
with sgQues do
begin
//是否没有答案
for i := 1 to sgQues.RowCount do
Result := Result or (Trim(Cells[1, i]) <> '');
if not Result then
begin
MessageBox(Handle, '答案不能为空,请输入答案', '提示', MB_OK + MB_ICONINFORMATION);
SetFocus;
Exit;
end;
end;
qtMatch:
with sgQues do
begin
//是否没有答案
for i := 1 to sgQues.RowCount do
Result := Result or (Trim(Cells[1, i]) <> '') and (Trim(Cells[2, i]) <> '');
if not Result then
begin
MessageBox(Handle, '答案不能为空,请输入答案', '提示', MB_OK + MB_ICONINFORMATION);
SetFocus;
Exit;
end;
//是否有答案没有对应
for i := 1 to sgQues.RowCount do
if (Trim(Cells[1, i]) <> '') or (Trim(Cells[2, i]) <> '') then
Result := Result and (Trim(Cells[1, i]) <> '') and (Trim(Cells[2, i]) <> '');
if not Result then
begin
MessageBox(Handle, '答案没有对应,请输入答案', '提示', MB_OK + MB_ICONINFORMATION);
SetFocus;
Exit;
end;
end;
qtHotSpot:
begin
if not FileExists(fraHotSpot.Image) then
begin
MessageBox(Handle, '热区题图片不存在,请导入图片', '提示', MB_OK + MB_ICONINFORMATION);
btnImport.SetFocus;
Exit;
end;
if not fraHotSpot.spRect.Visible then
begin
MessageBox(Handle, '热区题热点不存在,请设定热点', '提示', MB_OK + MB_ICONINFORMATION);
fraHotSpot.SetFocus;
Exit;
end;
end;
end;
Result := True;
end;
procedure TfrmQues.SaveQues(AQuesObj: TQuesBase);
var
i: Integer;
begin
//加载参数
with AQuesObj do
begin
//公有数据赋值
Topic := meoTopic.Text;
FeedAns := (_Type = qtSingle) and cbAnsFeed.Checked;
with Audio do
begin
FileName := beAudio.Text;
AutoPlay := cbAutoPlay.Checked;
LoopCount := cbCount.ItemIndex + 1;
end;
Image := imgQues.Image;
if not (_Type in [qtEssay, qtScene]) then
begin
Points := StrToFloat(edtPoint.Text); //udPoint.Position;
Attempts := udAttempts.Position;
Level := TQuesLevel(cbLevel.ItemIndex);
end
//简答题特别处理
else
begin
Points := 0;
Attempts := 0;
if _Type = qtEssay then
Level := qlEssay
else Level := qlScene;
end;
with FeedInfo do
begin
Enabled := not (_Type in [qtEssay, qtScene]) and cbFeed.Checked;
CrtInfo := meoCrt.Text;
ErrInfo := meoErr.Text;
end;
//同步更新列表
if not FNewQues and (FListView.Selected <> nil) then
with FListView.Selected do
begin
SubItems[0] := Topic;
if _Type <> qtScene then
begin
SubItems[2] := FloatToStr(Points);
SubItems[3] := LevelName;
end;
end;
end;
//答案赋值
case AQuesObj._Type of
qtJudge, qtSingle, qtMulti:
begin
TQuesObj(AQuesObj).Answers.Clear;
with sgQues do
begin
for i := 1 to RowCount - 1 do
if not AQuesObj.FeedAns then
begin
if Boolean(Cols[SIGN_COL].Objects[i]) then
TQuesObj(AQuesObj).Answers.Append('True=' + Cells[2, i])
else TQuesObj(AQuesObj).Answers.Append('False=' + Cells[2, i]);
end
else if AQuesObj._Type = qtSingle then
begin
if Boolean(Cols[SIGN_COL].Objects[i]) then
TQuesObj(AQuesObj).Answers.Append('True=' + Cells[2, i] + '$$$$' + Cells[3, i])
else TQuesObj(AQuesObj).Answers.Append('False=' + Cells[2, i] + '$$$$' + Cells[3, i]);
end;
end;
end;
qtBlank, qtSeque:
begin
TQuesObj(AQuesObj).Answers.Clear;
with sgQues do
for i := 1 to RowCount - 1 do
TQuesObj(AQuesObj).Answers.Append(Cells[1, i]);
end;
qtMatch:
begin
TQuesObj(AQuesObj).Answers.Clear;
with sgQues do
for i := 1 to RowCount - 1 do
TQuesObj(AQuesObj).Answers.Append(StringReplace(Cells[1, i], '=', '$+$', [rfReplaceAll]) + '=' + Cells[2, i]);
end;
qtHotSpot:
begin
with TQuesHot(AQuesObj), fraHotSpot do
begin
HotImage := Image;
HPos := sbImg.HorzScrollBar.Position;
VPos := sbImg.VertScrollBar.Position;
HotRect := Rect(spRect.Left , spRect.Top, spRect.Width, spRect.Height);
ImgFit := btnFit.Down;
end;
end;
qtEssay, qtScene:
TQuesObj(AQuesObj).Answers.Text := meoAns.Text;
end;
end;
procedure TfrmQues.FormShortCut(var Msg: TWMKey; var Handled: Boolean);
begin
if not (ActiveControl is TStringGrid) or (Msg.CharCode = VK_F1) or (Msg.CharCode = VK_ESCAPE) then inherited;
//Page Up、Page Down键,执行浏览题功能
if (Msg.CharCode = VK_PRIOR) and btnPrev.Enabled then
begin
Handled := True;
btnPrev.OnClick(btnPrev);
end;
if (Msg.CharCode = VK_NEXT) and btnNext.Enabled then
begin
Handled := True;
btnNext.OnClick(btnNext);
end;
end;
procedure TfrmQues.BuildJudge;
var
QuesObj: TQuesObj;
begin
HelpHtml := 'true_false.html';
QuesObj := TQuesObj(FQuesObj);
with sgQues do
begin
RowCount := 3;
ColWidths[1] := 53;
ColWidths[2] := 302;
Cells[0, 1] := '1';
Cells[0, 2] := '2';
Cells[1, 0] := '正确答案';
Cells[2, 0] := '选项';
//编辑
if FNewQues then
begin
Cells[2, 1] := '是';
Cells[2, 2] := '否';
end
else
begin
if QuesObj.Answers.Names[0] = 'True' then
begin
Cols[SIGN_COL].Objects[1] := TObject(True);
sgQues.OnDrawCell(sgQues, 1, 1, sgQues.CellRect(1, 1), []);
end
else
begin
Cols[SIGN_COL].Objects[2] := TObject(True);
sgQues.OnDrawCell(sgQues, 1, 2, sgQues.CellRect(1, 2), []);
end;
Cells[2, 1] := QuesObj.Answers.ValueFromIndex[0];
Cells[2, 2] := QuesObj.Answers.ValueFromIndex[1];
end;
Row := 1;
Col := 2;
end;
end;
procedure TfrmQues.BuildSingle;
var
i: Integer;
QuesObj: TQuesObj;
begin
if FQuesObj._Type = qtSingle then
HelpHtml := 'single.html'
else HelpHtml := 'multi.html';
QuesObj := TQuesObj(FQuesObj);
cbAnsFeed.Checked := QuesObj.FeedAns;
if FQuesObj._Type = qtSingle then cbAnsFeed.OnClick(cbAnsFeed);
with sgQues do
begin
ColWidths[1] := 53;
ColWidths[2] := 302;
Cells[1, 0] := '正确答案';
Cells[2, 0] := '选项';
if FNewQues then
begin
RowCount := 5;
Cells[0, 1] := '1';
Cells[0, 2] := '2';
Cells[0, 3] := '3';
Cells[0, 4] := '4';
end
else
begin
RowCount := QuesObj.Answers.Count + 1;
for i := 0 to QuesObj.Answers.Count - 1 do
begin
if QuesObj.Answers.Names[i] = 'True' then
begin
Cols[SIGN_COL].Objects[i + 1] := TObject(True);
sgQues.OnDrawCell(sgQues, 1, i + 1, sgQues.CellRect(1, i + 1), []);
end;
Cells[0, i + 1] := IntToStr(i + 1);
Cells[2, i + 1] := QuesObj.GetAnswer(QuesObj.Answers.ValueFromIndex[i]);
if QuesObj.FeedAns then
Cells[3, i + 1] := QuesObj.GetFeedback(QuesObj.Answers.ValueFromIndex[i]);
end;
SetBtnState();
end;
Row := 1;
Col := 2;
end;
end;
procedure TfrmQues.BuildMulti;
begin
BuildSingle;
end;
procedure TfrmQues.BuildBlank;
var
i: Integer;
QuesObj: TQuesObj;
begin
HelpHtml := 'blank.html';
sgQues.ColCount := 2;
QuesObj := TQuesObj(FQuesObj);
with sgQues do
begin
ColWidths[1] := 356;
Cells[1, 0] := '可接受答案';
if FNewQues then
begin
RowCount := 5;
Cells[0, 1] := '1';
Cells[0, 2] := '2';
Cells[0, 3] := '3';
Cells[0, 4] := '4';
end
else
begin
RowCount := QuesObj.Answers.Count + 1;
for i := 0 to QuesObj.Answers.Count - 1 do
Cells[1, i + 1] := QuesObj.Answers[i];
SetBtnState();
end;
Row := 1;
Col := 1;
end;
end;
procedure TfrmQues.BuildMatch;
var
i: Integer;
QuesObj: TQuesObj;
begin
HelpHtml := 'match.html';
QuesObj := TQuesObj(FQuesObj);
with sgQues do
begin
ColWidths[1] := 177;
ColWidths[2] := 178;
Cells[1, 0] := '选项';
Cells[2, 0] := '匹配项';
if FNewQues then
begin
RowCount := 5;
Cells[0, 1] := '1';
Cells[0, 2] := '2';
Cells[0, 3] := '3';
Cells[0, 4] := '4';
end
else
begin
RowCount := QuesObj.Answers.Count + 1;
for i := 0 to QuesObj.Answers.Count - 1 do
begin
Cells[1, i + 1] := StringReplace(QuesObj.Answers.Names[i], '$+$', '=', [rfReplaceAll]);
Cells[2, i + 1] := QuesObj.Answers.ValueFromIndex[i];
end;
SetBtnState();
end;
Row := 1;
Col := 1;
end;
end;
procedure TfrmQues.BuildSeque;
var
i: Integer;
QuesObj: TQuesObj;
begin
HelpHtml := 'seque.html';
sgQues.ColCount := 2;
QuesObj := TQuesObj(FQuesObj);
with sgQues do
begin
ColWidths[1] := 356;
Cells[1, 0] := '答案正确顺序';
if FNewQues then
begin
RowCount := 5;
Cells[0, 1] := '1';
Cells[0, 2] := '2';
Cells[0, 3] := '3';
Cells[0, 4] := '4';
end
else
begin
RowCount := QuesObj.Answers.Count + 1;
for i := 0 to QuesObj.Answers.Count - 1 do
Cells[1, i + 1] := QuesObj.Answers[i];
SetBtnState();
end;
Row := 1;
Col := 1;
end;
end;
procedure TfrmQues.BuildHotSpot;
var
QuesHot: TQuesHot;
begin
HelpHtml := 'hotspot.html';
lblAns.Caption := '图像及热点:';
btnImport.Left := btnAdd.Left;
btnOri.Left := btnImport.Left + btnImport.Width + 12;
btnFit.Left := btnOri.Left + btnFit.Width + 6;
imgHelp.Left := btnFit.Left + btnFit.Width + 12;
//可用状态
btnOri.Enabled := not FNewQues;
btnFit.Enabled := not FNewQues;
QuesHot := TQuesHot(FQuesObj);
with fraHotSpot do
begin
sbImg.DoubleBuffered := True;
img.Cursor := crCross;
imgHot.Cursor := crSizeAll;
Edit := not FNewQues;
//编辑
if not FNewQues then
begin
Image := QuesHot.HotImage;
//先执行动作
if FileExists(Image) and QuesHot.ImgFit then
begin
btnFit.Down := True;
btnFit.OnClick(btnFit);
end;
sbImg.HorzScrollBar.Position := QuesHot.HPos;
sbImg.VertScrollBar.Position := QuesHot.VPos;
SetHotPos(QuesHot.HotRect);
end;
end;
end;
procedure TfrmQues.BuildEssay;
begin
HelpHtml := 'essay.html';
imgHelp.Left := btnAdd.Left;
lblAns.Caption := '参考答案:';
if not FNewQues then meoAns.Text := TQuesObj(FQuesObj).Answers.Text;
end;
procedure TfrmQues.BuildScene;
begin
HelpHtml := 'scene.html';
imgHelp.Left := btnAdd.Left;
lblTopic.Caption := '主题:';
lblAns.Caption := '场景简介:';
if not FNewQues then meoAns.Text := TQuesObj(FQuesObj).Answers.Text;
end;
procedure TfrmQues.SetBtnState;
var
i: Integer;
begin
btnAdd.Visible := FQuesObj._Type in [qtSingle, qtMulti, qtBlank, qtMatch, qtSeque];
btnDel.Visible := btnAdd.Visible;
btnAdd.Enabled := sgQues.RowCount <= MAX_ROW_COUNT;
btnDel.Enabled := sgQues.RowCount >= MIN_ROW_COUNT;
for i := 1 to sgQues.RowCount - 1 do
sgQues.Cells[0, i] := IntToStr(i);
end;
function TfrmQues.HasSameValue: Boolean;
var
iIndex: Integer;
begin
inherited;
Result := False;
//答案级返馈信息不处理
if (FQuesObj._Type = qtSingle) and (sgQues.Col = 3) then Exit;
//重复答案检测
if Trim(sgQues.Cells[sgQues.Col, sgQues.Row]) <> '' then
begin
iIndex := sgQues.Cols[sgQues.Col].IndexOf(sgQues.Cells[sgQues.Col, sgQues.Row]);
if (iIndex <> sgQues.Row) and (iIndex <> -1) then
begin
MessageBox(Handle, '已有相同的答案项,请重新输入', '提示', MB_OK + MB_ICONINFORMATION);
Result := True;
end;
end;
end;
function TfrmQues.QuesChanged: Boolean;
var
i: Integer;
slAns: TStrings;
begin
//先判断通用属性
Result := (FQuesObj.Topic <> meoTopic.Text) or
(FQuesObj.Audio.FileName <> beAudio.Text) or
(FQuesObj.Audio.AutoPlay <> cbAutoPlay.Checked) or
(FQuesObj.Audio.LoopCount <> cbCount.ItemIndex + 1) or
(FQuesObj.FeedAns <> (FQuesObj._Type = qtSingle) and cbAnsFeed.Checked) or
(FQuesObj.Image <> imgQues.Image) or
udPoint.Visible and (FloatToStr(FQuesObj.Points) <> edtPoint.Text) or
udAttempts.Visible and (FQuesObj.Attempts <> udAttempts.Position) or
cbLevel.Visible and (FQuesObj.Level <> TQuesLevel(cbLevel.ItemIndex)) or
cbFeed.Visible and ((FQuesObj.FeedInfo.Enabled <> cbFeed.Checked) or
(FQuesObj.FeedInfo.CrtInfo <> meoCrt.Text) or
(FQuesObj.FeedInfo.ErrInfo <> meoErr.Text));
if Result then Exit;
//再判断题属性
//答案赋值
slAns := TStringList.Create;
try
case FQuesObj._Type of
qtJudge, qtSingle, qtMulti:
begin
with sgQues do
begin
for i := 1 to RowCount - 1 do
if Boolean(Cols[SIGN_COL].Objects[i]) then
slAns.Append('True=' + Cells[2, i])
else slAns.Append('False=' + Cells[2, i]);
end;
end;
qtBlank, qtSeque:
begin
with sgQues do
for i := 1 to RowCount - 1 do
slAns.Append(Cells[1, i]);
end;
qtMatch:
begin
with sgQues do
for i := 1 to RowCount - 1 do
slAns.Append(StringReplace(Cells[1, i], '=', '$+$', [rfReplaceAll]) + '=' + Cells[2, i]);
end;
qtHotSpot:
begin
with TQuesHot(FQuesObj), fraHotSpot do
begin
Result := (HotImage <> Image) or
(HPos <> sbImg.HorzScrollBar.Position) or
(VPos <> sbImg.VertScrollBar.Position) or
(HotRect.Left <> spRect.Left) or
(HotRect.Top <> spRect.Top) or
(HotRect.Right <> spRect.Width) or
(HotRect.Bottom <> spRect.Height) or
(ImgFit <> btnFit.Down);
end;
end;
qtEssay, qtScene:
slAns.Text := meoAns.Text;
end;
if FQuesObj._Type <> qtHotSpot then Result := slAns.Text <> TQuesObj(FQuesObj).Answers.Text;
finally
slAns.Free;
end;
end;
procedure TfrmQues.LoadQues(const ANextQues: Boolean);
var
CurIndex: Integer;
begin
if QuesChanged() then
begin
if CheckData() then
SaveData()
else Exit;
end;
with FListView do
begin
if ANextQues then
CurIndex := ItemIndex + 1
else CurIndex := ItemIndex - 1;
Items[ItemIndex].Selected := False;
ItemIndex := CurIndex;
Items[ItemIndex].Focused := True;
Items[ItemIndex].MakeVisible(True);
FQuesObj := TQuesBase(Selected.Data);
end;
LoadData();
end;
procedure TfrmQues.btnResetClick(Sender: TObject);
begin
Close;
end;
//预览
procedure TfrmQues.btnCancelClick(Sender: TObject);
var
QuesObj: TQuesBase;
begin
if CheckData() then
begin
if FQuesObj._Type = qtHotSpot then
QuesObj := TQuesHot.Create(FQuesObj._Type)
else QuesObj := TQuesObj.Create(FQuesObj._Type);
try
SaveQues(QuesObj);
QuizObj.Publish.Preview(QuesObj);
finally
QuesObj.Free;
end;
end;
end;
procedure TfrmQues.btnEditClick(Sender: TObject);
begin
ShowEditTopic(meoTopic);
end;
procedure TfrmQues.beAudioButtonClick(Sender: TObject);
var
od: TOpenDialog;
begin
od := TOpenDialog.Create(Self);
try
od.Filter := '支持的音频文件(*.mp3; *.wav)|*.mp3;*.wav';
if od.Execute then beAudio.Text := od.FileName;
finally
od.Free;
end;
end;
procedure TfrmQues.cbAutoPlayClick(Sender: TObject);
begin
cbCount.Enabled := cbAutoPlay.Checked;
end;
procedure TfrmQues.cbAnsFeedClick(Sender: TObject);
begin
if cbAnsFeed.Checked then
begin
sgQues.ColCount := 4;
sgQues.ColWidths[2] := 176;
sgQues.ColWidths[3] := 125;
sgQues.Cells[3, 0] := '反馈信息';
end
else
begin
sgQues.ColCount := 3;
sgQues.ColWidths[2] := 302;
end;
if Visible then sgQues.SetFocus;
edtAttempts.Enabled := cbAnsFeed.Visible and cbAnsFeed.Checked or cbFeed.Checked;
udAttempts.Enabled := edtAttempts.Enabled;
end;
procedure TfrmQues.sgQuesSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
var
i: Integer;
begin
case FQuesObj._Type of
qtJudge, qtSingle, qtMulti:
begin
if ACol = 1 then
begin
//以设定其状态,用在设置是否显示正确答案之上
if FQuesObj._Type in [qtJudge, qtSingle] then
for i := 1 to sgQues.RowCount - 1 do
sgQues.Cols[ACol].Objects[i] := TObject(False);
sgQues.Options := sgQues.Options - [goEditing];
if FQuesObj._Type = qtMulti then
begin
//判断左键是否按下,以避免键盘操作取消选中标记
if (GetAsyncKeyState(VK_LBUTTON) and $8000) <> 0 then
sgQues.Cols[ACol].Objects[ARow] := TObject((Trim(sgQues.Cells[2, ARow]) <> '') and not Boolean(sgQues.Cols[ACol].Objects[ARow]))
end
else sgQues.Cols[ACol].Objects[ARow] := TObject(Trim(sgQues.Cells[2, ARow]) <> '');
end
else if ACol in [2, 3] then
sgQues.Options := sgQues.Options + [goEditing]
end;
qtBlank, qtMatch, qtSeque:
sgQues.Options := sgQues.Options + [goEditing];
end;
//重复答案项检测;对Col判断是针对匹配题的
if ((sgQues.Row <> ARow) or (sgQues.Col <> ACol)) and HasSameValue() then
begin
CanSelect := False;
sgQues.Cols[ACol].Objects[ARow] := TObject(False);
sgQues.Options := sgQues.Options + [goEditing];
end;
end;
procedure TfrmQues.sgQuesExit(Sender: TObject);
begin
if HasSameValue() then sgQues.SetFocus;
end;
procedure TfrmQues.sgQuesDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
begin
//屏蔽TAB键
case FQuesObj._Type of
qtJudge, qtSingle, qtMulti:
begin
if (ACol = 1) and (ARow >= 1) and Boolean(sgQues.Cols[ACol].Objects[ARow]) then
ilQues.Draw(sgQues.Canvas, sgQues.Left + Rect.Left + 8, sgQues.Top + Rect.Top, 9);
end;
end;
end;
procedure TfrmQues.sgQuesKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
//实现Tab键效果
if (Key = VK_RETURN) and not HasSameValue then PostMessage(sgQues.Handle, WM_KEYDOWN, VK_TAB, 0);
if (Key = VK_TAB) and (sgQues.Row = sgQues.RowCount - 1) and (sgQues.Col = sgQues.ColCount - 1) then edtPoint.SetFocus;
end;
procedure TfrmQues.btnAddClick(Sender: TObject);
begin
sgQues.RowCount := sgQues.RowCount + 1;
SetBtnState;
end;
procedure TfrmQues.btnDelClick(Sender: TObject);
begin
sgQues.RowCount := sgQues.RowCount - 1;
SetBtnState;
end;
procedure TfrmQues.edtPointChange(Sender: TObject);
begin
try
udPoint.Position := Floor(StrToFloat(edtPoint.Text));
except
//do nothing
end;
end;
procedure TfrmQues.edtPointExit(Sender: TObject);
begin
if Trim(edtPoint.Text) = '' then edtPoint.Text := '0';
end;
procedure TfrmQues.edtPointKeyPress(Sender: TObject; var Key: Char);
begin
udPoint.OnChangingEx := nil;
try
if (not (Key in ['0'..'9', '.', #8])) or (Key = '.') and (Pos('.', edtPoint.Text) <> 0) then Key := #0;
if edtPoint.SelText = edtPoint.Text then
begin
edtPoint.Text := Key;
edtPoint.SelStart := Length(Key);
Abort;
end;
if Key <> #8 then
try
if (StrToFloat(StringReplace(edtPoint.Text, edtPoint.SelText, Key, [])) > 100) or
(StrToFloat(StringReplace(edtPoint.Text, edtPoint.SelText, '', []) + Key) > 100) then
Key := #0;
except
Key := #0;
end;
finally
udPoint.OnChangingEx := udPointChangingEx;
end;
end;
procedure TfrmQues.udPointChangingEx(Sender: TObject;
var AllowChange: Boolean; NewValue: Smallint;
Direction: TUpDownDirection);
var
sDecimal: string;
begin
if not (NewValue in [udPoint.Min..udPoint.Max]) then Exit;
edtPoint.OnChange := nil;
try
if Pos('.', edtPoint.Text) <> 0 then
try
sDecimal := Copy(edtPoint.Text, Pos('.', edtPoint.Text), Length(edtPoint.Text) - Pos('.', edtPoint.Text) + 1);
if NewValue + StrToFloat(sDecimal) > udPoint.Max then Exit;
except
Exit;
end;
if Pos('.', edtPoint.Text) = 0 then
edtPoint.Text := IntToStr(NewValue)
else edtPoint.Text := IntToStr(NewValue) + Copy(edtPoint.Text, Pos('.', edtPoint.Text), Length(edtPoint.Text) - Pos('.', edtPoint.Text) + 1);
finally
edtPoint.OnChange := edtPointChange;
end;
end;
procedure TfrmQues.cbFeedClick(Sender: TObject);
var
Enabled: Boolean;
begin
Enabled := cbFeed.Checked;
meoCrt.Enabled := Enabled;
meoErr.Enabled := Enabled;
edtAttempts.Enabled := Enabled or cbAnsFeed.Visible and cbAnsFeed.Checked;
udAttempts.Enabled := edtAttempts.Enabled;
end;
procedure TfrmQues.imgQuesDblClick(Sender: TObject);
begin
btnAddImg.OnClick(btnAddImg);
end;
procedure TfrmQues.btnAddImgClick(Sender: TObject);
begin
if odQues.Execute then imgQues.Image := odQues.FileName;
end;
procedure TfrmQues.btnDelImgClick(Sender: TObject);
begin
imgQues.Image := '';
pnlImg.Caption := '没有图片';
end;
procedure TfrmQues.btnImportClick(Sender: TObject);
begin
if odHot.Execute then
begin
fraHotSpot.Image := odHot.FileName;
fraHotSpot.sbImg.SetFocus;
btnOri.Enabled := True;
btnFit.Enabled := True;
if btnFit.Down then btnFit.OnClick(btnFit);
end;
end;
procedure TfrmQues.fraHotSpotMouseWheel(Sender: TObject;
Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint;
var Handled: Boolean);
begin
if WheelDelta < 0 then
fraHotSpot.sbImg.Perform(WM_VSCROLL, SB_LINEDOWN, 0)
else fraHotSpot.sbImg.Perform(WM_VSCROLL, SB_LINEUP, 0);
end;
procedure TfrmQues.fraHotSpotsbImgDblClick(Sender: TObject);
begin
if fraHotSpot.Image = '' then btnImportClick(btnImport);
end;
procedure TfrmQues.btnOriClick(Sender: TObject);
begin
fraHotSpot.SetImageToOri();
end;
procedure TfrmQues.btnFitClick(Sender: TObject);
begin
fraHotSpot.SetImageToFit();
end;
procedure TfrmQues.btnPrevClick(Sender: TObject);
begin
LoadQues(False);
end;
procedure TfrmQues.btnNextClick(Sender: TObject);
begin
LoadQues(True);
end;
end.
|
unit Odontologia.Vistas.Empresa;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
System.ImageList,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Data.DB,
Vcl.ImgList,
Vcl.StdCtrls,
Vcl.Buttons,
Vcl.Grids,
Vcl.DBGrids,
Vcl.WinXPanels,
Vcl.ExtCtrls,
Vcl.DBCtrls,
Odontologia.Controlador,
Odontologia.Controlador.Interfaces,
Odontologia.Controlador.Ciudad.Interfaces,
Odontologia.Controlador.Empresa.Interfaces,
Odontologia.Controlador.EmpresaTipo.Interfaces,
Odontologia.Vistas.Template;
type
TPagEmpresa = class(TPagTemplate)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label11: TLabel;
Label10: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
edtCodigo : TEdit;
edtRazSocial : TEdit;
edtDireccion : TEdit;
edtBarrio : TEdit;
edtMail : TEdit;
edtRuc : TEdit;
edtTelefono : TEdit;
edtNroCasa : TEdit;
edtFantasia : TEdit;
cmbCiudad : TDBLookupComboBox;
cmbEmpresaTipo : TDBLookupComboBox;
DataSource2: TDataSource;
DataSource3: TDataSource;
procedure btnBorrarClick(Sender: TObject);
procedure btnGuardarClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure edtSearchKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure DataSource1DataChange(Sender: TObject; Field: TField);
procedure DBGrid1DblClick(Sender: TObject);
procedure btnNuevoClick(Sender: TObject);
procedure btnActualizarClick(Sender: TObject);
procedure btnCerrarClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
FController : iController;
FCiudad : iControllerCiudad;
FEmpresa : iControllerEmpresa;
FEmpresaTipo : iControllerEmpresaTipo;
procedure prc_estado_inicial;
public
{ Public declarations }
end;
var
PagEmpresa: TPagEmpresa;
Insercion: Boolean;
implementation
{$R *.dfm}
procedure TPagEmpresa.btnActualizarClick(Sender: TObject);
begin
inherited;
FEmpresa.Buscar;
end;
procedure TPagEmpresa.btnBorrarClick(Sender: TObject);
var
ShouldClose: Boolean;
begin
inherited;
if MessageDlg('Realmente desea eliminar este registro?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then
begin
FEmpresa.Entidad.EMP_CODIGO := StrToInt(edtCodigo.Text);
FEmpresa.Eliminar;
FEmpresa.Buscar;
prc_estado_inicial;
end else
begin
edtRuc.SetFocus;
end;
end;
procedure TPagEmpresa.btnCancelarClick(Sender: TObject);
begin
inherited;
prc_estado_inicial;
end;
procedure TPagEmpresa.btnCerrarClick(Sender: TObject);
begin
inherited;
prc_estado_inicial;
end;
procedure TPagEmpresa.btnGuardarClick(Sender: TObject);
begin
inherited;
if Insercion then
begin
FEmpresa.Entidad.EMP_RAZSOCIAL := edtRazSocial.Text;
FEmpresa.Entidad.EMP_FANTASIA := edtFantasia.Text;
FEmpresa.Entidad.EMP_DIRECCION := edtDireccion.Text;
FEmpresa.Entidad.EMP_NUMERO := edtNroCasa.Text;
FEmpresa.Entidad.EMP_BARRIO := edtBarrio.Text;
FEmpresa.Entidad.EMP_TELEFONO := edtTelefono.Text;
FEmpresa.Entidad.EMP_EMAIL := edtMail.Text;
FEmpresa.Entidad.EMP_RUC := edtRUC.Text;
FEmpresa.Entidad.EMP_COD_CIUDAD := DataSource2.DataSet.FieldByName('CODIGO').AsInteger;
FEmpresa.Entidad.EMP_COD_TIP_EMPRESA := DataSource3.DataSet.FieldByName('CODIGO').AsInteger;
FEmpresa.Insertar;
end
else
begin
FEmpresa.Entidad.EMP_CODIGO := StrToInt(edtCodigo.Text);
FEmpresa.Entidad.EMP_RAZSOCIAL := edtRazSocial.Text;
FEmpresa.Entidad.EMP_FANTASIA := edtFantasia.Text;
FEmpresa.Entidad.EMP_DIRECCION := edtDireccion.Text;
FEmpresa.Entidad.EMP_NUMERO := edtNroCasa.Text;
FEmpresa.Entidad.EMP_BARRIO := edtBarrio.Text;
FEmpresa.Entidad.EMP_TELEFONO := edtTelefono.Text;
FEmpresa.Entidad.EMP_EMAIL := edtMail.Text;
FEmpresa.Entidad.EMP_RUC := edtRUC.Text;
FEmpresa.Entidad.EMP_COD_CIUDAD := DataSource2.DataSet.FieldByName('CODIGO').AsInteger;
FEmpresa.Entidad.EMP_COD_TIP_EMPRESA := DataSource3.DataSet.FieldByName('CODIGO').AsInteger;
FEmpresa.Modificar;
end;
prc_estado_inicial;
end;
procedure TPagEmpresa.btnNuevoClick(Sender: TObject);
begin
inherited;
CardPanel1.ActiveCard := Card2;
lblTitulo2.Caption := 'Agregar nuevo registro';
edtCodigo.Enabled := False;
edtRUC.SetFocus;
cmbCiudad.KeyValue := 223;
cmbEmpresaTipo.KeyValue := 1;
end;
procedure TPagEmpresa.DataSource1DataChange(Sender: TObject; Field: TField);
begin
inherited;
edtCodigo.Text := DataSource1.DataSet.FieldByName('EMP_CODIGO').AsString;
edtRazSocial.Text := DataSource1.DataSet.FieldByName('EMP_NOMBRE').AsString;
end;
procedure TPagEmpresa.DBGrid1DblClick(Sender: TObject);
begin
inherited;
Insercion := False;
CardPanel1.ActiveCard := Card2;
lblTitulo2.Caption := 'Modificar registro';
edtCodigo.Text := DataSource1.DataSet.FieldByName('CODIGO').AsString;
edtRuc.Text := DataSource1.DataSet.FieldByName('RUC').AsString;
edtRazSocial.Text := DataSource1.DataSet.FieldByName('RAZON').AsString;
edtFantasia.Text := DataSource1.DataSet.FieldByName('FANTASIA').AsString;
edtDireccion.Text := DataSource1.DataSet.FieldByName('DIRECCION').AsString;
edtNroCasa.Text := DataSource1.DataSet.FieldByName('NUMERO').AsString;
edtBarrio.Text := DataSource1.DataSet.FieldByName('BARRIO').AsString;
edtMail.Text := DataSource1.DataSet.FieldByName('EMAIL').AsString;
edtTelefono.Text := DataSource1.DataSet.FieldByName('TELEFONO').AsString;
cmbCiudad.KeyValue := DataSource1.DataSet.FieldByName('COD_CIU').AsString;
cmbEmpresaTipo.KeyValue := DataSource1.DataSet.FieldByName('COD_EMP').AsString;
end;
procedure TPagEmpresa.edtSearchKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
FEmpresa.Buscar(edtSearch.Text);
end;
procedure TPagEmpresa.FormCreate(Sender: TObject);
begin
inherited;
lblTitulo.Caption := 'Registro de empresas';
edtCodigo.Enabled := False;
FController := TController.New;
FCiudad := Fcontroller.Ciudad.DataSource(DataSource2);
FEmpresa := FController.Empresa.DataSource(DataSource1);
FEmpresaTipo := FController.EmpresaTipo.DataSource(DataSource3);
prc_estado_inicial;
end;
procedure TPagEmpresa.prc_estado_inicial;
begin
Insercion := True;
CardPanel1.ActiveCard := Card1;
edtSearch.Text := '';
edtCodigo.Text := '';
edtRuc.Text := '';
edtRazSocial.Text := '';
edtFantasia.Text := '';
edtDireccion.Text := '';
edtNroCasa.Text := '';
edtBarrio.Text := '';
edtMail.Text := '';
edtTelefono.Text := '';
FCiudad.Buscar;
FEmpresa.Buscar;
FEmpresaTipo.Buscar;
end;
end.
|
unit RemoteProcessClient;
interface
uses
SysUtils, SimpleSocket, PlayerContextControl, BonusControl, BonusTypeControl, CarControl, CarTypeControl,
DirectionControl, GameControl, MoveControl, OilSlickControl, PlayerControl, ProjectileControl,
ProjectileTypeControl, TileTypeControl, TypeControl, WorldControl;
const
UNKNOWN_MESSAGE: LongInt = 0;
GAME_OVER: LongInt = 1;
AUTHENTICATION_TOKEN: LongInt = 2;
TEAM_SIZE: LongInt = 3;
PROTOCOL_VERSION: LongInt = 4;
GAME_CONTEXT: LongInt = 5;
PLAYER_CONTEXT: LongInt = 6;
MOVES_MESSAGE: LongInt = 7;
LITTLE_ENDIAN_BYTE_ORDER = true;
INTEGER_SIZE_BYTES = sizeof(LongInt);
LONG_SIZE_BYTES = sizeof(Int64);
type
TMessageType = LongInt;
TByteArray = array of Byte;
TRemoteProcessClient = class
private
FSocket: ClientSocket;
FMapName: string;
FTilesXY: TTileTypeArray2D;
FWaypoints: TLongIntArray2D;
FStartingDirection: TDirection;
{$HINTS OFF}
function ReadBonus: TBonus;
procedure WriteBonus(bonus: TBonus);
function ReadBonuses: TBonusArray;
procedure WriteBonuses(bonuses: TBonusArray);
function ReadCar: TCar;
procedure WriteCar(car: TCar);
function ReadCars: TCarArray;
procedure WriteCars(cars: TCarArray);
function ReadGame: TGame;
procedure WriteGame(game: TGame);
function ReadGames: TGameArray;
procedure WriteGames(games: TGameArray);
function ReadMove: TMove;
procedure WriteMove(move: TMove);
function ReadMoves: TMoveArray;
procedure WriteMoves(moves: TMoveArray);
function ReadOilSlick: TOilSlick;
procedure WriteOilSlick(oilSlick: TOilSlick);
function ReadOilSlicks: TOilSlickArray;
procedure WriteOilSlicks(oilSlicks: TOilSlickArray);
function ReadPlayer: TPlayer;
procedure WritePlayer(player: TPlayer);
function ReadPlayers: TPlayerArray;
procedure WritePlayers(players: TPlayerArray);
function ReadPlayerContext: TPlayerContext;
procedure WritePlayerContext(playerContext: TPlayerContext);
function ReadPlayerContexts: TPlayerContextArray;
procedure WritePlayerContexts(playerContexts: TPlayerContextArray);
function ReadProjectile: TProjectile;
procedure WriteProjectile(projectile: TProjectile);
function ReadProjectiles: TProjectileArray;
procedure WriteProjectiles(projectiles: TProjectileArray);
function ReadWorld: TWorld;
procedure WriteWorld(world: TWorld);
function ReadWorlds: TWorldArray;
procedure WriteWorlds(worlds: TWorldArray);
{$HINTS ON}
procedure EnsureMessageType(actualType: LongInt; expectedType: LongInt);
function ReadEnum: LongInt;
function ReadEnumArray: TLongIntArray;
function ReadEnumArray2D: TLongIntArray2D;
procedure WriteEnum(value: LongInt);
procedure WriteEnumArray(value: TLongIntArray);
procedure WriteEnumArray2D(value: TLongIntArray2D);
function ReadString: string;
procedure WriteString(value: string);
function ReadInt: LongInt;
function ReadIntArray: TLongIntArray;
function ReadIntArray2D: TLongIntArray2D;
procedure WriteInt(value: LongInt);
procedure WriteIntArray(value: TLongIntArray);
procedure WriteIntArray2D(value: TLongIntArray2D);
function ReadBytes(byteCount: LongInt): TByteArray;
procedure WriteBytes(bytes: TByteArray);
function ReadBoolean: Boolean;
procedure WriteBoolean(value: Boolean);
function ReadDouble: Double;
procedure WriteDouble(value: Double);
function ReadLong: Int64;
procedure WriteLong(value: Int64);
function IsLittleEndianMachine: Boolean;
procedure Reverse(var bytes: TByteArray);
public
constructor Create(const AHost: string; const APort: LongInt);
destructor Destroy; override;
procedure WriteTokenMessage(token: string);
function ReadTeamSizeMessage: LongInt;
procedure WriteProtocolVersionMessage;
function ReadGameContextMessage: TGame;
function ReadPlayerContextMessage: TPlayerContext;
procedure WriteMovesMessage(moves: TMoveArray);
end;
implementation
constructor TRemoteProcessClient.Create(const AHost: string; const APort: LongInt);
begin
FSocket := ClientSocket.Create(AHost, APort);
FMapName := '';
FTilesXY := nil;
FWaypoints := nil;
FStartingDirection := _DIRECTION_COUNT_;
end;
destructor TRemoteProcessClient.Destroy;
begin
FSocket.Free;
end;
procedure TRemoteProcessClient.EnsureMessageType(actualType: LongInt; expectedType: LongInt);
begin
if (actualType <> expectedType) then
begin
Halt(10001);
end;
end;
procedure TRemoteProcessClient.WriteTokenMessage(token: string);
begin
WriteEnum(AUTHENTICATION_TOKEN);
WriteString(token);
end;
function TRemoteProcessClient.ReadTeamSizeMessage: LongInt;
begin
EnsureMessageType(ReadEnum, TEAM_SIZE);
Result := ReadInt;
end;
procedure TRemoteProcessClient.WriteProtocolVersionMessage;
begin
WriteEnum(PROTOCOL_VERSION);
WriteInt(1);
end;
function TRemoteProcessClient.ReadGameContextMessage: TGame;
begin
EnsureMessageType(ReadEnum, GAME_CONTEXT);
Result := ReadGame;
end;
function TRemoteProcessClient.ReadPlayerContextMessage: TPlayerContext;
var
messageType: TMessageType;
begin
messageType := ReadEnum;
if messageType = GAME_OVER then begin
result := nil;
exit;
end;
EnsureMessageType(messageType, PLAYER_CONTEXT);
result := ReadPlayerContext;
end;
procedure TRemoteProcessClient.WriteMovesMessage(moves: TMoveArray);
begin
WriteEnum(MOVES_MESSAGE);
WriteMoves(moves);
end;
function TRemoteProcessClient.ReadBonus: TBonus;
var
id: Int64;
mass: Double;
x: Double;
y: Double;
speedX: Double;
speedY: Double;
angle: Double;
angularSpeed: Double;
width: Double;
height: Double;
bonusType: TBonusType;
begin
if not ReadBoolean then
begin
Result := nil;
Exit;
end;
id := ReadLong;
mass := ReadDouble;
x := ReadDouble;
y := ReadDouble;
speedX := ReadDouble;
speedY := ReadDouble;
angle := ReadDouble;
angularSpeed := ReadDouble;
width := ReadDouble;
height := ReadDouble;
bonusType := ReadEnum;
Result := TBonus.Create(id, mass, x, y, speedX, speedY, angle, angularSpeed, width, height, bonusType);
end;
procedure TRemoteProcessClient.WriteBonus(bonus: TBonus);
begin
if not Assigned(bonus) then
begin
WriteBoolean(False);
Exit;
end;
WriteBoolean(True);
WriteLong(bonus.Id);
WriteDouble(bonus.Mass);
WriteDouble(bonus.X);
WriteDouble(bonus.Y);
WriteDouble(bonus.SpeedX);
WriteDouble(bonus.SpeedY);
WriteDouble(bonus.Angle);
WriteDouble(bonus.AngularSpeed);
WriteDouble(bonus.Width);
WriteDouble(bonus.Height);
WriteEnum(bonus.BonusType);
end;
function TRemoteProcessClient.ReadBonuses: TBonusArray;
var
bonusIndex: LongInt;
bonusCount: LongInt;
begin
bonusCount := ReadInt;
if bonusCount < 0 then begin
result := nil;
exit;
end;
SetLength(result, bonusCount);
for bonusIndex := 0 to bonusCount - 1 do begin
result[bonusIndex] := ReadBonus;
end;
end;
procedure TRemoteProcessClient.WriteBonuses(bonuses: TBonusArray);
var
bonusIndex: LongInt;
bonusCount: LongInt;
begin
if bonuses = nil then begin
WriteInt(-1);
exit;
end;
bonusCount := Length(bonuses);
WriteInt(bonusCount);
for bonusIndex := 0 to bonusCount - 1 do begin
WriteBonus(bonuses[bonusIndex]);
end;
end;
function TRemoteProcessClient.ReadCar: TCar;
var
id: Int64;
mass: Double;
x: Double;
y: Double;
speedX: Double;
speedY: Double;
angle: Double;
angularSpeed: Double;
width: Double;
height: Double;
playerId: Int64;
teammateIndex: LongInt;
teammate: Boolean;
carType: TCarType;
projectileCount: LongInt;
nitroChargeCount: LongInt;
oilCanisterCount: LongInt;
remainingProjectileCooldownTicks: LongInt;
remainingNitroCooldownTicks: LongInt;
remainingOilCooldownTicks: LongInt;
remainingNitroTicks: LongInt;
remainingOiledTicks: LongInt;
durability: Double;
enginePower: Double;
wheelTurn: Double;
nextWaypointX: LongInt;
nextWaypointY: LongInt;
finishedTrack: Boolean;
begin
if not ReadBoolean then begin
result := nil;
exit;
end;
id := ReadLong;
mass := ReadDouble;
x := ReadDouble;
y := ReadDouble;
speedX := ReadDouble;
speedY := ReadDouble;
angle := ReadDouble;
angularSpeed := ReadDouble;
width := ReadDouble;
height := ReadDouble;
playerId := ReadLong;
teammateIndex := ReadInt;
teammate := ReadBoolean;
carType := ReadEnum;
projectileCount := ReadInt;
nitroChargeCount := ReadInt;
oilCanisterCount := ReadInt;
remainingProjectileCooldownTicks := ReadInt;
remainingNitroCooldownTicks := ReadInt;
remainingOilCooldownTicks := ReadInt;
remainingNitroTicks := ReadInt;
remainingOiledTicks := ReadInt;
durability := ReadDouble;
enginePower := ReadDouble;
wheelTurn := ReadDouble;
nextWaypointX := ReadInt;
nextWaypointY := ReadInt;
finishedTrack := ReadBoolean;
result := TCar.Create(id, mass, x, y, speedX, speedY, angle, angularSpeed, width, height, playerId, teammateIndex,
teammate, carType, projectileCount, nitroChargeCount, oilCanisterCount, remainingProjectileCooldownTicks,
remainingNitroCooldownTicks, remainingOilCooldownTicks, remainingNitroTicks, remainingOiledTicks,
durability, enginePower, wheelTurn, nextWaypointX, nextWaypointY, finishedTrack);
end;
procedure TRemoteProcessClient.WriteCar(car: TCar);
begin
if car = nil then begin
WriteBoolean(false);
exit;
end;
WriteBoolean(true);
WriteLong(car.Id);
WriteDouble(car.Mass);
WriteDouble(car.X);
WriteDouble(car.Y);
WriteDouble(car.SpeedX);
WriteDouble(car.SpeedY);
WriteDouble(car.Angle);
WriteDouble(car.AngularSpeed);
WriteDouble(car.Width);
WriteDouble(car.Height);
WriteLong(car.PlayerId);
WriteInt(car.TeammateIndex);
WriteBoolean(car.IsTeammate);
WriteEnum(car.CarType);
WriteInt(car.ProjectileCount);
WriteInt(car.NitroChargeCount);
WriteInt(car.OilCanisterCount);
WriteInt(car.RemainingProjectileCooldownTicks);
WriteInt(car.RemainingNitroCooldownTicks);
WriteInt(car.RemainingOilCooldownTicks);
WriteInt(car.RemainingNitroTicks);
WriteInt(car.RemainingOiledTicks);
WriteDouble(car.Durability);
WriteDouble(car.EnginePower);
WriteDouble(car.WheelTurn);
WriteInt(car.NextWaypointX);
WriteInt(car.NextWaypointY);
WriteBoolean(car.IsFinishedTrack);
end;
function TRemoteProcessClient.ReadCars: TCarArray;
var
carIndex: LongInt;
carCount: LongInt;
begin
carCount := ReadInt;
if carCount < 0 then begin
result := nil;
exit;
end;
SetLength(result, carCount);
for carIndex := 0 to carCount - 1 do begin
result[carIndex] := ReadCar;
end;
end;
procedure TRemoteProcessClient.WriteCars(cars: TCarArray);
var
carIndex: LongInt;
carCount: LongInt;
begin
if cars = nil then begin
WriteInt(-1);
exit;
end;
carCount := Length(cars);
WriteInt(carCount);
for carIndex := 0 to carCount - 1 do begin
WriteCar(cars[carIndex]);
end;
end;
function TRemoteProcessClient.ReadGame: TGame;
var
randomSeed: Int64;
tickCount: LongInt;
worldWidth: LongInt;
worldHeight: LongInt;
trackTileSize: Double;
trackTileMargin: Double;
lapCount: LongInt;
lapTickCount: LongInt;
initialFreezeDurationTicks: LongInt;
burningTimeDurationFactor: Double;
finishTrackScores: TLongIntArray;
finishLapScore: LongInt;
lapWaypointsSummaryScoreFactor: Double;
carDamageScoreFactor: Double;
carEliminationScore: LongInt;
carWidth: Double;
carHeight: Double;
carEnginePowerChangePerTick: Double;
carWheelTurnChangePerTick: Double;
carAngularSpeedFactor: Double;
carMovementAirFrictionFactor: Double;
carRotationAirFrictionFactor: Double;
carLengthwiseMovementFrictionFactor: Double;
carCrosswiseMovementFrictionFactor: Double;
carRotationFrictionFactor: Double;
throwProjectileCooldownTicks: LongInt;
useNitroCooldownTicks: LongInt;
spillOilCooldownTicks: LongInt;
nitroEnginePowerFactor: Double;
nitroDurationTicks: LongInt;
carReactivationTimeTicks: LongInt;
buggyMass: Double;
buggyEngineForwardPower: Double;
buggyEngineRearPower: Double;
jeepMass: Double;
jeepEngineForwardPower: Double;
jeepEngineRearPower: Double;
bonusSize: Double;
bonusMass: Double;
pureScoreAmount: LongInt;
washerRadius: Double;
washerMass: Double;
washerInitialSpeed: Double;
washerDamage: Double;
sideWasherAngle: Double;
tireRadius: Double;
tireMass: Double;
tireInitialSpeed: Double;
tireDamageFactor: Double;
tireDisappearSpeedFactor: Double;
oilSlickInitialRange: Double;
oilSlickRadius: Double;
oilSlickLifetime: LongInt;
maxOiledStateDurationTicks: LongInt;
begin
if not ReadBoolean then begin
result := nil;
exit;
end;
randomSeed := ReadLong;
tickCount := ReadInt;
worldWidth := ReadInt;
worldHeight := ReadInt;
trackTileSize := ReadDouble;
trackTileMargin := ReadDouble;
lapCount := ReadInt;
lapTickCount := ReadInt;
initialFreezeDurationTicks := ReadInt;
burningTimeDurationFactor := ReadDouble;
finishTrackScores := ReadIntArray;
finishLapScore := ReadInt;
lapWaypointsSummaryScoreFactor := ReadDouble;
carDamageScoreFactor := ReadDouble;
carEliminationScore := ReadInt;
carWidth := ReadDouble;
carHeight := ReadDouble;
carEnginePowerChangePerTick := ReadDouble;
carWheelTurnChangePerTick := ReadDouble;
carAngularSpeedFactor := ReadDouble;
carMovementAirFrictionFactor := ReadDouble;
carRotationAirFrictionFactor := ReadDouble;
carLengthwiseMovementFrictionFactor := ReadDouble;
carCrosswiseMovementFrictionFactor := ReadDouble;
carRotationFrictionFactor := ReadDouble;
throwProjectileCooldownTicks := ReadInt;
useNitroCooldownTicks := ReadInt;
spillOilCooldownTicks := ReadInt;
nitroEnginePowerFactor := ReadDouble;
nitroDurationTicks := ReadInt;
carReactivationTimeTicks := ReadInt;
buggyMass := ReadDouble;
buggyEngineForwardPower := ReadDouble;
buggyEngineRearPower := ReadDouble;
jeepMass := ReadDouble;
jeepEngineForwardPower := ReadDouble;
jeepEngineRearPower := ReadDouble;
bonusSize := ReadDouble;
bonusMass := ReadDouble;
pureScoreAmount := ReadInt;
washerRadius := ReadDouble;
washerMass := ReadDouble;
washerInitialSpeed := ReadDouble;
washerDamage := ReadDouble;
sideWasherAngle := ReadDouble;
tireRadius := ReadDouble;
tireMass := ReadDouble;
tireInitialSpeed := ReadDouble;
tireDamageFactor := ReadDouble;
tireDisappearSpeedFactor := ReadDouble;
oilSlickInitialRange := ReadDouble;
oilSlickRadius := ReadDouble;
oilSlickLifetime := ReadInt;
maxOiledStateDurationTicks := ReadInt;
result := TGame.Create(randomSeed, tickCount, worldWidth, worldHeight, trackTileSize, trackTileMargin, lapCount,
lapTickCount, initialFreezeDurationTicks, burningTimeDurationFactor, finishTrackScores, finishLapScore,
lapWaypointsSummaryScoreFactor, carDamageScoreFactor, carEliminationScore, carWidth, carHeight,
carEnginePowerChangePerTick, carWheelTurnChangePerTick, carAngularSpeedFactor, carMovementAirFrictionFactor,
carRotationAirFrictionFactor, carLengthwiseMovementFrictionFactor, carCrosswiseMovementFrictionFactor,
carRotationFrictionFactor, throwProjectileCooldownTicks, useNitroCooldownTicks, spillOilCooldownTicks,
nitroEnginePowerFactor, nitroDurationTicks, carReactivationTimeTicks, buggyMass, buggyEngineForwardPower,
buggyEngineRearPower, jeepMass, jeepEngineForwardPower, jeepEngineRearPower, bonusSize, bonusMass,
pureScoreAmount, washerRadius, washerMass, washerInitialSpeed, washerDamage, sideWasherAngle, tireRadius,
tireMass, tireInitialSpeed, tireDamageFactor, tireDisappearSpeedFactor, oilSlickInitialRange,
oilSlickRadius, oilSlickLifetime, maxOiledStateDurationTicks);
end;
procedure TRemoteProcessClient.WriteGame(game: TGame);
begin
if game = nil then begin
WriteBoolean(false);
exit;
end;
WriteBoolean(true);
WriteLong(game.RandomSeed);
WriteInt(game.TickCount);
WriteInt(game.WorldWidth);
WriteInt(game.WorldHeight);
WriteDouble(game.TrackTileSize);
WriteDouble(game.TrackTileMargin);
WriteInt(game.LapCount);
WriteInt(game.LapTickCount);
WriteInt(game.InitialFreezeDurationTicks);
WriteDouble(game.BurningTimeDurationFactor);
WriteIntArray(game.FinishTrackScores);
WriteInt(game.FinishLapScore);
WriteDouble(game.LapWaypointsSummaryScoreFactor);
WriteDouble(game.CarDamageScoreFactor);
WriteInt(game.CarEliminationScore);
WriteDouble(game.CarWidth);
WriteDouble(game.CarHeight);
WriteDouble(game.CarEnginePowerChangePerTick);
WriteDouble(game.CarWheelTurnChangePerTick);
WriteDouble(game.CarAngularSpeedFactor);
WriteDouble(game.CarMovementAirFrictionFactor);
WriteDouble(game.CarRotationAirFrictionFactor);
WriteDouble(game.CarLengthwiseMovementFrictionFactor);
WriteDouble(game.CarCrosswiseMovementFrictionFactor);
WriteDouble(game.CarRotationFrictionFactor);
WriteInt(game.ThrowProjectileCooldownTicks);
WriteInt(game.UseNitroCooldownTicks);
WriteInt(game.SpillOilCooldownTicks);
WriteDouble(game.NitroEnginePowerFactor);
WriteInt(game.NitroDurationTicks);
WriteInt(game.CarReactivationTimeTicks);
WriteDouble(game.BuggyMass);
WriteDouble(game.BuggyEngineForwardPower);
WriteDouble(game.BuggyEngineRearPower);
WriteDouble(game.JeepMass);
WriteDouble(game.JeepEngineForwardPower);
WriteDouble(game.JeepEngineRearPower);
WriteDouble(game.BonusSize);
WriteDouble(game.BonusMass);
WriteInt(game.PureScoreAmount);
WriteDouble(game.WasherRadius);
WriteDouble(game.WasherMass);
WriteDouble(game.WasherInitialSpeed);
WriteDouble(game.WasherDamage);
WriteDouble(game.SideWasherAngle);
WriteDouble(game.TireRadius);
WriteDouble(game.TireMass);
WriteDouble(game.TireInitialSpeed);
WriteDouble(game.TireDamageFactor);
WriteDouble(game.TireDisappearSpeedFactor);
WriteDouble(game.OilSlickInitialRange);
WriteDouble(game.OilSlickRadius);
WriteInt(game.OilSlickLifetime);
WriteInt(game.MaxOiledStateDurationTicks);
end;
function TRemoteProcessClient.ReadGames: TGameArray;
var
gameIndex: LongInt;
gameCount: LongInt;
begin
gameCount := ReadInt;
if gameCount < 0 then begin
result := nil;
exit;
end;
SetLength(result, gameCount);
for gameIndex := 0 to gameCount - 1 do begin
result[gameIndex] := ReadGame;
end;
end;
procedure TRemoteProcessClient.WriteGames(games: TGameArray);
var
gameIndex: LongInt;
gameCount: LongInt;
begin
if games = nil then begin
WriteInt(-1);
exit;
end;
gameCount := Length(games);
WriteInt(gameCount);
for gameIndex := 0 to gameCount - 1 do begin
WriteGame(games[gameIndex]);
end;
end;
function TRemoteProcessClient.ReadMove: TMove;
begin
if not ReadBoolean then
begin
Result := nil;
Exit;
end;
Result := TMove.Create;
Result.EnginePower := ReadDouble;
Result.IsBrake := ReadBoolean;
Result.WheelTurn := ReadDouble;
Result.IsThrowProjectile := ReadBoolean;
Result.IsUseNitro := ReadBoolean;
Result.IsSpillOil := ReadBoolean;
end;
procedure TRemoteProcessClient.WriteMove(move: TMove);
begin
if not Assigned(move) then
begin
WriteBoolean(False);
Exit;
end;
WriteBoolean(True);
WriteDouble(move.EnginePower);
WriteBoolean(move.IsBrake);
WriteDouble(move.WheelTurn);
WriteBoolean(move.IsThrowProjectile);
WriteBoolean(move.IsUseNitro);
WriteBoolean(move.IsSpillOil);
end;
function TRemoteProcessClient.ReadMoves: TMoveArray;
var
moveIndex: LongInt;
moveCount: LongInt;
begin
moveCount := ReadInt;
if moveCount < 0 then begin
result := nil;
exit;
end;
SetLength(result, moveCount);
for moveIndex := 0 to moveCount - 1 do begin
result[moveIndex] := ReadMove;
end;
end;
procedure TRemoteProcessClient.WriteMoves(moves: TMoveArray);
var
moveIndex: LongInt;
moveCount: LongInt;
begin
if moves = nil then begin
WriteInt(-1);
exit;
end;
moveCount := Length(moves);
WriteInt(moveCount);
for moveIndex := 0 to moveCount - 1 do begin
WriteMove(moves[moveIndex]);
end;
end;
function TRemoteProcessClient.ReadOilSlick: TOilSlick;
var
id: Int64;
mass: Double;
x: Double;
y: Double;
speedX: Double;
speedY: Double;
angle: Double;
angularSpeed: Double;
radius: Double;
remainingLifetime: LongInt;
begin
if not ReadBoolean then begin
result := nil;
exit;
end;
id := ReadLong;
mass := ReadDouble;
x := ReadDouble;
y := ReadDouble;
speedX := ReadDouble;
speedY := ReadDouble;
angle := ReadDouble;
angularSpeed := ReadDouble;
radius := ReadDouble;
remainingLifetime := ReadInt;
result := TOilSlick.Create(id, mass, x, y, speedX, speedY, angle, angularSpeed, radius, remainingLifetime);
end;
procedure TRemoteProcessClient.WriteOilSlick(oilSlick: TOilSlick);
begin
if oilSlick = nil then begin
WriteBoolean(false);
exit;
end;
WriteBoolean(true);
WriteLong(oilSlick.Id);
WriteDouble(oilSlick.Mass);
WriteDouble(oilSlick.X);
WriteDouble(oilSlick.Y);
WriteDouble(oilSlick.SpeedX);
WriteDouble(oilSlick.SpeedY);
WriteDouble(oilSlick.Angle);
WriteDouble(oilSlick.AngularSpeed);
WriteDouble(oilSlick.Radius);
WriteInt(oilSlick.RemainingLifetime);
end;
function TRemoteProcessClient.ReadOilSlicks: TOilSlickArray;
var
oilSlickIndex: LongInt;
oilSlickCount: LongInt;
begin
oilSlickCount := ReadInt;
if oilSlickCount < 0 then begin
result := nil;
exit;
end;
SetLength(result, oilSlickCount);
for oilSlickIndex := 0 to oilSlickCount - 1 do begin
result[oilSlickIndex] := ReadOilSlick;
end;
end;
procedure TRemoteProcessClient.WriteOilSlicks(oilSlicks: TOilSlickArray);
var
oilSlickIndex: LongInt;
oilSlickCount: LongInt;
begin
if oilSlicks = nil then begin
WriteInt(-1);
exit;
end;
oilSlickCount := Length(oilSlicks);
WriteInt(oilSlickCount);
for oilSlickIndex := 0 to oilSlickCount - 1 do begin
WriteOilSlick(oilSlicks[oilSlickIndex]);
end;
end;
function TRemoteProcessClient.ReadPlayer: TPlayer;
var
id: Int64;
me: Boolean;
name: String;
strategyCrashed: Boolean;
score: LongInt;
begin
if not ReadBoolean then begin
result := nil;
exit;
end;
id := ReadLong;
me := ReadBoolean;
name := ReadString;
strategyCrashed := ReadBoolean;
score := ReadInt;
result := TPlayer.Create(id, me, name, strategyCrashed, score);
end;
procedure TRemoteProcessClient.WritePlayer(player: TPlayer);
begin
if player = nil then begin
WriteBoolean(false);
exit;
end;
WriteBoolean(true);
WriteLong(player.Id);
WriteBoolean(player.IsMe);
WriteString(player.Name);
WriteBoolean(player.StrategyCrashed);
WriteInt(player.Score);
end;
function TRemoteProcessClient.ReadPlayers: TPlayerArray;
var
playerIndex: LongInt;
playerCount: LongInt;
begin
playerCount := ReadInt;
if playerCount < 0 then begin
result := nil;
exit;
end;
SetLength(result, playerCount);
for playerIndex := 0 to playerCount - 1 do begin
result[playerIndex] := ReadPlayer;
end;
end;
procedure TRemoteProcessClient.WritePlayers(players: TPlayerArray);
var
playerIndex: LongInt;
playerCount: LongInt;
begin
if players = nil then begin
WriteInt(-1);
exit;
end;
playerCount := Length(players);
WriteInt(playerCount);
for playerIndex := 0 to playerCount - 1 do begin
WritePlayer(players[playerIndex]);
end;
end;
function TRemoteProcessClient.ReadPlayerContext: TPlayerContext;
var
cars: TCarArray;
world: TWorld;
begin
if not ReadBoolean then begin
result := nil;
exit;
end;
cars := ReadCars;
world := ReadWorld;
result := TPlayerContext.Create(cars, world);
end;
procedure TRemoteProcessClient.WritePlayerContext(playerContext: TPlayerContext);
begin
if not Assigned(playerContext) then
begin
WriteBoolean(False);
Exit;
end;
WriteBoolean(True);
WriteCars(playerContext.Cars);
WriteWorld(playerContext.World);
end;
function TRemoteProcessClient.ReadPlayerContexts: TPlayerContextArray;
var
playerContextIndex: LongInt;
playerContextCount: LongInt;
begin
playerContextCount := ReadInt;
if playerContextCount < 0 then
begin
Result := nil;
Exit;
end;
SetLength(Result, playerContextCount);
if playerContextCount > 0 then
begin
for playerContextIndex := 0 to playerContextCount - 1 do
begin
Result[playerContextIndex] := ReadPlayerContext;
end;
end;
end;
procedure TRemoteProcessClient.WritePlayerContexts(playerContexts: TPlayerContextArray);
var
playerContextIndex: LongInt;
playerContextCount: LongInt;
begin
if playerContexts = nil then begin
WriteInt(-1);
exit;
end;
playerContextCount := Length(playerContexts);
WriteInt(playerContextCount);
for playerContextIndex := 0 to playerContextCount - 1 do begin
WritePlayerContext(playerContexts[playerContextIndex]);
end;
end;
function TRemoteProcessClient.ReadProjectile: TProjectile;
var
id: Int64;
mass: Double;
x: Double;
y: Double;
speedX: Double;
speedY: Double;
angle: Double;
angularSpeed: Double;
radius: Double;
carId: Int64;
playerId: Int64;
projectileType: TProjectileType;
begin
if not ReadBoolean then begin
result := nil;
exit;
end;
id := ReadLong;
mass := ReadDouble;
x := ReadDouble;
y := ReadDouble;
speedX := ReadDouble;
speedY := ReadDouble;
angle := ReadDouble;
angularSpeed := ReadDouble;
radius := ReadDouble;
carId := ReadLong;
playerId := ReadLong;
projectileType := ReadEnum;
result := TProjectile.Create(id, mass, x, y, speedX, speedY, angle, angularSpeed, radius, carId, playerId,
projectileType);
end;
procedure TRemoteProcessClient.WriteProjectile(projectile: TProjectile);
begin
if not Assigned(projectile) then
begin
WriteBoolean(False);
Exit;
end;
WriteBoolean(True);
WriteLong(projectile.Id);
WriteDouble(projectile.Mass);
WriteDouble(projectile.X);
WriteDouble(projectile.Y);
WriteDouble(projectile.SpeedX);
WriteDouble(projectile.SpeedY);
WriteDouble(projectile.Angle);
WriteDouble(projectile.AngularSpeed);
WriteDouble(projectile.Radius);
WriteLong(projectile.CarId);
WriteLong(projectile.PlayerId);
WriteEnum(projectile.ProjectileType);
end;
function TRemoteProcessClient.ReadProjectiles: TProjectileArray;
var
projectileIndex: LongInt;
projectileCount: LongInt;
begin
projectileCount := ReadInt;
if projectileCount < 0 then begin
result := nil;
exit;
end;
SetLength(result, projectileCount);
for projectileIndex := 0 to projectileCount - 1 do begin
result[projectileIndex] := ReadProjectile;
end;
end;
procedure TRemoteProcessClient.WriteProjectiles(projectiles: TProjectileArray);
var
projectileIndex: LongInt;
projectileCount: LongInt;
begin
if projectiles = nil then begin
WriteInt(-1);
exit;
end;
projectileCount := Length(projectiles);
WriteInt(projectileCount);
for projectileIndex := 0 to projectileCount - 1 do begin
WriteProjectile(projectiles[projectileIndex]);
end;
end;
function TRemoteProcessClient.ReadWorld: TWorld;
var
tick: LongInt;
tickCount: LongInt;
lastTickIndex: LongInt;
width: LongInt;
height: LongInt;
players: TPlayerArray;
cars: TCarArray;
projectiles: TProjectileArray;
bonuses: TBonusArray;
oilSlicks: TOilSlickArray;
mapName: String;
tilesXY: TTileTypeArray2D;
waypoints: TLongIntArray2D;
startingDirection: TDirection;
begin
if not ReadBoolean then begin
result := nil;
exit;
end;
tick := ReadInt;
tickCount := ReadInt;
lastTickIndex := ReadInt;
width := ReadInt;
height := ReadInt;
players := ReadPlayers;
cars := ReadCars;
projectiles := ReadProjectiles;
bonuses := ReadBonuses;
oilSlicks := ReadOilSlicks;
if FMapName = '' then begin
FMapName := ReadString;
end;
mapName := FMapName;
if FTilesXY = nil then begin
FTilesXY := ReadEnumArray2D;
end;
tilesXY := FTilesXY;
if FWaypoints = nil then begin
FWaypoints := ReadIntArray2D;
end;
waypoints := FWaypoints;
if FStartingDirection = _DIRECTION_COUNT_ then begin
FStartingDirection := ReadEnum;
end;
startingDirection := FStartingDirection;
result := TWorld.Create(tick, tickCount, lastTickIndex, width, height, players, cars, projectiles, bonuses,
oilSlicks, mapName, tilesXY, waypoints, startingDirection);
end;
procedure TRemoteProcessClient.WriteWorld(world: TWorld);
begin
if world = nil then begin
WriteBoolean(false);
exit;
end;
WriteBoolean(true);
WriteInt(world.Tick);
WriteInt(world.TickCount);
WriteInt(world.LastTickIndex);
WriteInt(world.Width);
WriteInt(world.Height);
WritePlayers(world.Players);
WriteCars(world.Cars);
WriteProjectiles(world.Projectiles);
WriteBonuses(world.Bonuses);
WriteOilSlicks(world.OilSlicks);
WriteString(world.MapName);
WriteEnumArray2D(world.TilesXY);
WriteIntArray2D(world.Waypoints);
WriteEnum(world.StartingDirection);
end;
function TRemoteProcessClient.ReadWorlds: TWorldArray;
var
worldIndex: LongInt;
worldCount: LongInt;
begin
worldCount := ReadInt;
if worldCount < 0 then begin
result := nil;
exit;
end;
SetLength(result, worldCount);
for worldIndex := 0 to worldCount - 1 do begin
result[worldIndex] := ReadWorld;
end;
end;
procedure TRemoteProcessClient.WriteWorlds(worlds: TWorldArray);
var
worldIndex: LongInt;
worldCount: LongInt;
begin
if worlds = nil then begin
WriteInt(-1);
exit;
end;
worldCount := Length(worlds);
WriteInt(worldCount);
for worldIndex := 0 to worldCount - 1 do begin
WriteWorld(worlds[worldIndex]);
end;
end;
procedure TRemoteProcessClient.WriteEnum(value: LongInt);
var
bytes: TByteArray;
begin
SetLength(bytes, 1);
bytes[0] := value;
WriteBytes(bytes);
Finalize(bytes);
end;
procedure TRemoteProcessClient.WriteEnumArray(value: TLongIntArray);
var
i, len: LongInt;
begin
if value = nil then begin
WriteInt(-1);
exit;
end;
len := Length(value);
WriteInt(len);
for i := 0 to len - 1 do begin
WriteEnum(value[i]);
end;
end;
procedure TRemoteProcessClient.WriteEnumArray2D(value: TLongIntArray2D);
var
i, len: LongInt;
begin
if value = nil then begin
WriteInt(-1);
exit;
end;
len := Length(value);
WriteInt(len);
for i := 0 to len - 1 do begin
WriteEnumArray(value[i]);
end;
end;
function TRemoteProcessClient.ReadEnum: TMessageType;
var
bytes: TByteArray;
begin
bytes := ReadBytes(1);
result := bytes[0];
Finalize(bytes);
end;
function TRemoteProcessClient.ReadEnumArray: TLongIntArray;
var
i, len: LongInt;
begin
len := ReadInt;
if len < 0 then begin
result := nil;
exit;
end;
SetLength(result, len);
for i := 0 to len - 1 do begin
result[i] := ReadEnum;
end;
end;
function TRemoteProcessClient.ReadEnumArray2D: TLongIntArray2D;
var
i, len: LongInt;
begin
len := ReadInt;
if len < 0 then begin
result := nil;
exit;
end;
SetLength(result, len);
for i := 0 to len - 1 do begin
result[i] := ReadEnumArray;
end;
end;
procedure TRemoteProcessClient.WriteBytes(bytes: TByteArray);
begin
FSocket.StrictSend(bytes, Length(bytes));
end;
function TRemoteProcessClient.ReadBytes(byteCount: LongInt): TByteArray;
var
bytes: TByteArray;
begin
SetLength(bytes, byteCount);
FSocket.StrictReceive(bytes, byteCount);
result := bytes;
end;
procedure TRemoteProcessClient.WriteString(value: String);
var
len, i: LongInt;
bytes: TByteArray;
begin
len := Length(value);
SetLength(bytes, len);
for i := 1 to len do begin
bytes[i - 1] := Ord(value[i]);
end;
WriteInt(len);
WriteBytes(bytes);
Finalize(bytes);
end;
procedure TRemoteProcessClient.WriteBoolean(value: Boolean);
var
bytes: TByteArray;
begin
SetLength(bytes, 1);
bytes[0] := ord(value);
WriteBytes(bytes);
Finalize(bytes);
end;
function TRemoteProcessClient.ReadBoolean: Boolean;
var
bytes: TByteArray;
begin
bytes := ReadBytes(1);
result := (bytes[0] <> 0);
Finalize(bytes);
end;
function TRemoteProcessClient.ReadString: String;
var
len, i: LongInt;
bytes: TByteArray;
res: String;
begin
len := ReadInt;
if len = -1 then begin
HALT(10014);
end;
res := '';
bytes := ReadBytes(len);
for i := 0 to len - 1 do begin
res := res + Chr(bytes[i]);
end;
Finalize(bytes);
result := res;
end;
procedure TRemoteProcessClient.WriteDouble(value: Double);
var
pl: ^Int64;
pd: ^Double;
p: Pointer;
begin
New(pd);
pd^ := value;
p := pd;
pl := p;
WriteLong(pl^);
Dispose(pd);
end;
function TRemoteProcessClient.ReadDouble: Double;
var
pl: ^Int64;
pd: ^Double;
p: Pointer;
begin
New(pl);
pl^ := ReadLong;
p := pl;
pd := p;
result := pd^;
Dispose(pl);
end;
procedure TRemoteProcessClient.WriteInt(value: LongInt);
var
bytes: TByteArray;
i: LongInt;
begin
SetLength(bytes, INTEGER_SIZE_BYTES);
for i := 0 to INTEGER_SIZE_BYTES - 1 do begin
bytes[i] := (value shr ({24 -} i * 8)) and 255;
end;
if (IsLittleEndianMachine <> LITTLE_ENDIAN_BYTE_ORDER) then begin
Reverse(bytes);
end;
WriteBytes(bytes);
Finalize(bytes);
end;
procedure TRemoteProcessClient.WriteIntArray(value: TLongIntArray);
var
i, len: LongInt;
begin
if value = nil then begin
WriteInt(-1);
exit;
end;
len := Length(value);
WriteInt(len);
for i := 0 to len - 1 do begin
WriteInt(value[i]);
end;
end;
procedure TRemoteProcessClient.WriteIntArray2D(value: TLongIntArray2D);
var
i, len: LongInt;
begin
if value = nil then begin
WriteInt(-1);
exit;
end;
len := Length(value);
WriteInt(len);
for i := 0 to len - 1 do begin
WriteIntArray(value[i]);
end;
end;
function TRemoteProcessClient.ReadInt: LongInt;
var
bytes: TByteArray;
res: LongInt;
i: LongInt;
begin
res := 0;
bytes := readBytes(INTEGER_SIZE_BYTES);
for i := INTEGER_SIZE_BYTES - 1 downto 0 do begin
res := (res shl 8) or bytes[i];
end;
Finalize(bytes);
result := res;
end;
function TRemoteProcessClient.ReadIntArray: TLongIntArray;
var
i, len: LongInt;
begin
len := ReadInt;
if len < 0 then begin
result := nil;
exit;
end;
SetLength(result, len);
for i := 0 to len - 1 do begin
result[i] := ReadInt;
end;
end;
function TRemoteProcessClient.ReadIntArray2D: TLongIntArray2D;
var
i, len: LongInt;
begin
len := ReadInt;
if len < 0 then begin
result := nil;
exit;
end;
SetLength(result, len);
for i := 0 to len - 1 do begin
result[i] := ReadIntArray;
end;
end;
function TRemoteProcessClient.ReadLong: Int64;
var
bytes: TByteArray;
res: Int64;
i: LongInt;
begin
res := 0;
bytes := readBytes(LONG_SIZE_BYTES);
for i := LONG_SIZE_BYTES - 1 downto 0 do begin
res := (res shl 8) or bytes[i];
end;
Finalize(bytes);
result := res;
end;
procedure TRemoteProcessClient.WriteLong(value: Int64);
var
bytes: TByteArray;
i: LongInt;
begin
SetLength(bytes, LONG_SIZE_BYTES);
for i := 0 to LONG_SIZE_BYTES - 1 do begin
bytes[i] := (value shr ({24 -} i*8)) and 255;
end;
if (IsLittleEndianMachine <> LITTLE_ENDIAN_BYTE_ORDER) then begin
Reverse(bytes);
end;
WriteBytes(bytes);
Finalize(bytes);
end;
function TRemoteProcessClient.IsLittleEndianMachine: Boolean;
begin
result := true;
end;
procedure TRemoteProcessClient.Reverse(var bytes: TByteArray);
var
i, len: LongInt;
buffer: Byte;
begin
len := Length(bytes);
for i := 0 to (len div 2) do begin
buffer := bytes[i];
bytes[i] := bytes[len - i - 1];
bytes[len - i - 1] := buffer;
end;
end;
end.
|
unit Fac_AE;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit,
cxMaskEdit, cxButtonEdit, StdCtrls, cxControls, cxGroupBox, cxButtons,
cnConsts_Messages, uCommonSp, ibase, cnConsts, cxCurrencyEdit;
type
TfrmFac_AE = class(TForm)
OkButton: TcxButton;
CancelButton: TcxButton;
Frame_GroupBox: TcxGroupBox;
Fac_Label: TLabel;
Fac_Edit: TcxButtonEdit;
NameExec_Label: TLabel;
Dekan_Label: TLabel;
NameExec_Edit: TcxTextEdit;
Dekan_Edit: TcxTextEdit;
Short_Label: TLabel;
ShortName_Edit: TcxTextEdit;
Label2: TLabel;
Kod_edit: TcxCurrencyEdit;
procedure OkButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure Fac_EditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure Fac_EditKeyPress(Sender: TObject; var Key: Char);
procedure ShortName_EditKeyPress(Sender: TObject; var Key: Char);
procedure NameExec_EditKeyPress(Sender: TObject; var Key: Char);
procedure Dekan_EditKeyPress(Sender: TObject; var Key: Char);
procedure FormShow(Sender: TObject);
private
PLanguageIndex : byte;
DB_Handle : TISC_DB_HANDLE;
procedure FormIniLanguage();
public
id_department : int64;
constructor Create(AOwner:TComponent; DBHandle: TISC_DB_HANDLE; LanguageIndex : byte);reintroduce;
end;
var
frmFac_AE: TfrmFac_AE;
implementation
{$R *.dfm}
constructor TfrmFac_AE.Create(AOwner:TComponent; DBHandle: TISC_DB_HANDLE; LanguageIndex : byte);
begin
Screen.Cursor:=crHourGlass;
inherited Create(AOwner);
PLanguageIndex:= LanguageIndex;
DB_Handle := DBHandle;
FormIniLanguage();
Screen.Cursor:=crDefault;
end;
procedure TfrmFac_AE.FormIniLanguage();
begin
Fac_Label.caption := cnConsts.cn_footer_Faculty[PLanguageIndex];
Short_Label.caption := cnConsts.cn_ShortName[PLanguageIndex];
NameExec_Label.caption := cnConsts.cn_NameExec[PLanguageIndex];
Dekan_Label.caption := cnConsts.cn_Dekan[PLanguageIndex];
OkButton.Caption := cnConsts.cn_Accept[PLanguageIndex];
CancelButton.Caption := cnConsts.cn_Cancel[PLanguageIndex];
end;
procedure TfrmFac_AE.OkButtonClick(Sender: TObject);
begin
if (Fac_Edit.Text= '') //or ( id_department = -1)
then begin
ShowMessage(cnConsts_Messages.cn_Faculty_Need[PLanguageIndex]);
Fac_Edit.SetFocus;
exit;
end;
if (ShortName_Edit.Text= '') then
begin
ShowMessage(cnConsts_Messages.cn_ShortName_Need[PLanguageIndex]);
ShortName_Edit.SetFocus;
exit;
end;
if (NameExec_Edit.Text= '') then
begin
ShowMessage(cnConsts_Messages.cn_Exec_Need[PLanguageIndex]);
NameExec_Edit.SetFocus;
exit;
end;
if (Dekan_Edit.Text= '') then
begin
ShowMessage(cnConsts_Messages.cn_Dekan_Need[PLanguageIndex]);
Dekan_Edit.SetFocus;
exit;
end;
if (Kod_edit.Text = '') then
begin
ShowMessage('Необхідно заповнити поле!!!');
Kod_edit.SetFocus;
exit;
end;
ModalResult:=mrOk;
end;
procedure TfrmFac_AE.CancelButtonClick(Sender: TObject);
begin
close;
end;
procedure TfrmFac_AE.Fac_EditPropertiesButtonClick(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(DB_Handle);
// модальный показ
FieldValues['ShowStyle'] := 0;
// единичная выборка
FieldValues['Select'] := 1;
FieldValues['AllowEdit'] := true;
FieldValues['Show_Properties'] := false;
Post;
end;
end;
// показать справочник и проанализировать результат (выбор одного подр.)
sp.Show;
if ( sp.Output <> nil ) and not sp.Output.IsEmpty then
begin
id_department := sp.Output['Id_Department'];
Fac_Edit.Text := sp.Output['Name_Full'];
ShortName_Edit.Text := sp.Output['Name_Short'];
NameExec_Edit.setfocus;
end;
sp.Free;
end;
procedure TfrmFac_AE.Fac_EditKeyPress(Sender: TObject; var Key: Char);
begin
if key = #13 then ShortName_Edit.SetFocus;
end;
procedure TfrmFac_AE.ShortName_EditKeyPress(Sender: TObject;
var Key: Char);
begin
if key = #13 then NameExec_Edit.SetFocus;
end;
procedure TfrmFac_AE.NameExec_EditKeyPress(Sender: TObject; var Key: Char);
begin
if key = #13 then Dekan_Edit.SetFocus;
end;
procedure TfrmFac_AE.Dekan_EditKeyPress(Sender: TObject; var Key: Char);
begin
if key = #13 then OkButton.SetFocus;
end;
procedure TfrmFac_AE.FormShow(Sender: TObject);
begin
Fac_Edit.SetFocus;
end;
end.
|
unit RegUnit;
interface
uses registry, Controls, Forms;
const REG_PATH = '\Software\MainBook\';
const Vasyan=2;
procedure e2SaveToReg; // Сохранение текущей формы в реестр
procedure e2RestFromReg(Sender:TObject); // Восстановление формы из реестра
implementation
//---------------------------------------
//
// Сохранение состояния формы в реестре
//
//---------------------------------------
procedure e2SaveToReg;
var
Reg : TRegIniFile;
cPath : String;
procedure SaveR(cPath : String; Con : TControl);
var
cPathSave : String;
nI, nJ : Integer;
begin
// Добавим к основному пути имя Control
cPathSave := cPath + Con.Name+'\';
with Reg do begin
WriteInteger(cPathSave,'Left', Con.Left);
WriteInteger(cPathSave,'Top', Con.Top);
WriteInteger(cPathSave,'Width', Con.Width);
WriteInteger(cPathSave,'Height', Con.Height);
// Определим количество компонент на форме
if Con is TWinControl then begin
nJ := TWinControl(Con).ControlCount;
if nJ > 0 then
for nI := 0 to nJ - 1 do
SaveR(cPath, TWinControl(Con).Controls[nI]);
end;
end;
end;
begin
// Вычисление ключа реестра для сохранения
cPath := REG_PATH+Screen.ActiveForm.Name+'\';
Reg := TRegIniFile.Create('');
Reg.EraseSection(cPath);
SaveR(cPath,Screen.ActiveForm);
Reg.Free;
end;
//---------------------------------------
//
// Восстановление состояния формы из реестра
//
//---------------------------------------
procedure e2RestFromReg(Sender:TObject);
var
Reg : TRegIniFile;
cPath : String;
procedure RestR(cPath: String; Con: TControl);
var
cPathSave : String;
nI, nJ : Integer;
begin
// Добавим к основному пути имя Control
cPathSave := cPath + Con.Name+'\';
with Reg do begin
nI := ReadInteger(cPathSave,'Left', -1);
if nI <> -1 then
Con.Left := nI;
nI := ReadInteger(cPathSave,'Top', -1);
if nI <> -1 then
Con.Top := nI;
nI := ReadInteger(cPathSave,'Width', -1);
if nI <> -1 then
Con.Width := nI;
nI := ReadInteger(cPathSave,'Height', -1);
if nI <> -1 then
Con.Height := nI;
// Определим количество компонент на форме
if Con is TWinControl then begin
nJ := TWinControl(Con).ControlCount;
if nJ > 0 then
for nI := 0 to nJ - 1 do
RestR(cPath, TWinControl(Con).Controls[nI]);
end;
end;
end;
begin
// Вычисление ключа реестра
cPath := REG_PATH + TControl(Sender).Name+'\';
Reg := TRegIniFile.Create('');
RestR(cPath, TControl(Sender));
Reg.Free;
end;
end.
|
unit uEndereco;
{**********************************************************************
** unit uEndereco **
** **
** UNIT DESTINADA A MANIPULAR AS INFORMAÇÕES NO CADASTRO DE PACIENTE **
** REFERENTE AS INFORMAÇÕES DENTRO DA ABA ENDEREÇO **
** **
***********************************************************************}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, uClassControlePaciente, uFrmMensagem, uClassEndereco, uCadPacientes;
type
{ Endereco }
Endereco = class
public
class function CarregaObjEndereco(objEndereco: TEndereco; frm: TfrmCadPaciente; qualTabela: byte): TEndereco;
class procedure InclusaoOuEdicaoEndereco(frm: TfrmCadPaciente; qualTabela: byte);
class procedure EdicaoEndereco(frm: TfrmCadPaciente);
class procedure ApagarEndereco(codigo: integer);
end;
implementation
{ Endereco }
class function Endereco.CarregaObjEndereco(objEndereco: TEndereco; frm: TfrmCadPaciente; qualTabela: byte): TEndereco;
var
codigo : integer = 0;
begin
with objEndereco do // 8 = TBL_PACIENTE
begin // 9 = TBL_DADOSPROF
case qualTabela of
8 : begin
codigo := StrToInt(frm.edtCodEndPaciente.Text);
logradouro := frm.edtLogradouro.Text;
numero := frm.edtNumEndereco.Text;
complemento := frm.edtComplemento.Text;
bairro := frm.edtBairro.Text;
cidade := frm.edtCidade.Text;
objEndereco.estado := frm.cboxUFCasa.Text;
cep := frm.mskedtCEPCasa.Text;
idTblPaciente := StrToInt(frm.edtCodPaciente.Text);
end;
9 : begin
logradouro := frm.edtLogradEmpresa.Text;
numero := frm.edtNumEndEmpresa.Text;
complemento := frm.edtComplEmpresa.Text;
bairro := frm.edtBairroEmpresa.Text;
cidade := frm.edtCidadeEmpresa.Text;
estado := frm.cboxUFEmpresa.Text;
cep := frm.mskedtCEPEmpresa.Text;
idTblDadosProf := StrToInt(frm.edtCodEndDadosProf.Text);
end;
end;
end;
result := objEndereco;
end;
class procedure Endereco.InclusaoOuEdicaoEndereco(frm: TfrmCadPaciente; qualTabela: byte);
var
objEndereco : TEndereco; // 8 = TBLPACIENTE
objControlePaciente : TControlePaciente; // 9 = TBLDADOSPROF
codEndereco : integer;
begin
try
objEndereco := TEndereco.Create;
objControlePaciente := TControlePaciente.Create;
codEndereco := objControlePaciente.InclusaoOuEdicaoEndereco(CarregaObjEndereco(objEndereco, frm, qualTabela));
if codEndereco > 0 then
begin
try
frmMensagem := TfrmMensagem.Create(nil);
frmMensagem.InfoFormMensagem('Cadastro do Endereço do Paciente', tiInformacao, 'Cadastrado do Endereço realizado com sucesso!');
finally
FreeAndNil(frmMensagem);
end;
case qualTabela of
8 : frm.edtCodEndPaciente.Text := IntToStr(codEndereco);
9 : frm.edtCodEndDadosProf.Text := IntToStr(codEndereco);
end;
end;
//DesabilitaControles(pcCadPaciente.ActivePage);
estado := teNavegacao;
//EstadoBotoes;
finally
FreeAndNil(objControlePaciente);
FreeAndNil(objEndereco);
end;
end;
class procedure Endereco.EdicaoEndereco(frm: TfrmCadPaciente);
var
objControlePaciente : TControlePaciente;
objEndereco : TEndereco;
codigo : integer = 0;
begin
try
objEndereco := TEndereco.Create;
objControlePaciente := TControlePaciente.Create;
// objEndereco := CarregaObjEndereco(objEndereco, frm);
codigo := objControlePaciente.InclusaoOuEdicaoEndereco(objEndereco);
if codigo > 0 then
begin
try
frmMensagem := TfrmMensagem.Create(nil);
frmMensagem.InfoFormMensagem('Alteração no cadastro de Endereço', tiInformacao, 'Endereço alterado com sucesso!');
finally
FreeAndNil(frmMensagem);
end;
end;
//DesabilitaControles(frmCadPaciente.pcCadPaciente.ActivePage);
estado := teNavegacao;
//EstadoBotoes;
finally
FreeAndNil(objControlePaciente);
FreeAndNil(objEndereco);
end;
end;
class procedure Endereco.ApagarEndereco(codigo: integer);
var
objControlePaciente : TControlePaciente;
frmMensagem : TfrmMensagem;
begin
objControlePaciente := TControlePaciente.Create;
//if objControlePaciente(codigo) then
//begin
// try
// frmMensagem := TfrmMensagem.Create(nil);
// frmMensagem.InfoFormMensagem('Remoção do cadastro do paciente', tiInformacao, 'Paciente removido com sucesso!');
// finally
// FreeAndNil(frmMensagem);
// end;
//end;
end;
end.
|
namespace com.remobjects.firstandroidapp;
interface
uses
java.util,
android.app,
android.content,
android.os,
android.util,
android.view,
android.widget;
type
MainActivity = public class(Activity)
public
method onCreate(savedInstanceState: Bundle); override;
method sendMessage(view: View);
const EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
end;
implementation
method MainActivity.onCreate(savedInstanceState: Bundle);
begin
inherited;
// Set our view from the "main" layout resource
ContentView := R.layout.main;
end;
method MainActivity.sendMessage(view: View);
begin
var intent: Intent := new Intent(self, typeOf(DisplayMessageActivity));
var editTxt := EditText(findViewById(R.id.edit_message));
var message: String := editTxt.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
end;
end.
|
unit FilterFormWorkHourse;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxLabel, cxControls, cxContainer, cxEdit,
cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, StdCtrls, cxButtons,
ActnList, ZTypes;
type
TFFilterFormWorkHourse = class(TForm)
ActionList: TActionList;
actYes: TAction;
YesBtn: TcxButton;
CancelBtn: TcxButton;
DateBeg: TcxDateEdit;
DateEnd: TcxDateEdit;
LabelTo: TcxLabel;
cxLabel1: TcxLabel;
procedure YesBtnClick(Sender: TObject);
procedure CancelBtnClick(Sender: TObject);
procedure actYesExecute(Sender: TObject);
private
ParamLoc: TZSimpleParamDate;
public
constructor Create(Param :TZSimpleParamDate); reintroduce;
end;
implementation
{$R *.dfm}
//Param:TZDateParam
{ TFFilterFormWorkHourse }
constructor TFFilterFormWorkHourse.Create(Param: TZSimpleParamDate);
begin
inherited Create(Param.Owner);
ParamLoc:= Param;
DateBeg.Properties.MaxDate := strToDate('01.01.2050');
DateBeg.Properties.MinDate := strToDate('01.01.1990');
DateEnd.Properties.MaxDate := strToDate('01.01.2050');
DateEnd.Properties.MinDate := strToDate('01.01.1990');
DateBeg.Date := StrToDate('01.'+FormatDateTime('mm.yyyy',Date));
DateEnd.Date := IncMonth(strToDate('01.'+FormatDateTime('mm.yyyy',Date))-1,1);
//
end;
procedure TFFilterFormWorkHourse.YesBtnClick(Sender: TObject);
begin
ParamLoc.Datebeg:= DateBeg.Date;
ParamLoc.DateEnd:= DateEnd.Date;
ModalResult:=mrYes;
end;
procedure TFFilterFormWorkHourse.CancelBtnClick(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TFFilterFormWorkHourse.actYesExecute(Sender: TObject);
begin
YesBtnClick(Sender);
end;
end.
|
unit PlayerContextControl;
interface
uses
Math, TypeControl, CarControl, WorldControl;
type
TPlayerContext = class
private
FCars: TCarArray;
FWorld: TWorld;
function GetCars: TCarArray;
function GetWorld: TWorld;
public
property Cars: TCarArray read GetCars;
property World: TWorld read GetWorld;
constructor Create(const ACars: TCarArray; const AWorld: TWorld);
destructor Destroy; override;
end;
TPlayerContextArray = array of TPlayerContext;
implementation
function TPlayerContext.GetCars: TCarArray;
begin
if Assigned(FCars) then
Result := Copy(FCars, 0, Length(FCars))
else
Result := nil;
end;
function TPlayerContext.GetWorld: TWorld;
begin
Result := FWorld;
end;
constructor TPlayerContext.Create(const ACars: TCarArray; const AWorld: TWorld);
begin
if Assigned(ACars) then
FCars := Copy(ACars, 0, Length(ACars))
else
FCars := nil;
FWorld := AWorld;
end;
destructor TPlayerContext.Destroy;
var
I: LongInt;
begin
if Assigned(FCars) then
begin
if Length(FCars) > 0 then
begin
for i := High(FCars) downto 0 do
begin
if Assigned(FCars[I]) then
FCars[i].Free;
end;
SetLength(FCars, 0);
end;
end;
if Assigned(FWorld) then
FWorld.Free;
inherited;
end;
end.
|
//
// Generated by JavaToPas v1.5 20160510 - 150251
////////////////////////////////////////////////////////////////////////////////
unit android.icu.text.MessageFormat;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
android.icu.util.ULocale,
android.icu.text.MessagePattern_ApostropheMode,
java.text.Format,
java.text.FieldPosition,
java.text.AttributedCharacterIterator,
java.text.ParsePosition;
type
JMessageFormat = interface;
JMessageFormatClass = interface(JObjectClass)
['{E30AC1F6-29D7-4CF5-B448-7365AEED9DEB}']
function autoQuoteApostrophe(pattern : JString) : JString; cdecl; // (Ljava/lang/String;)Ljava/lang/String; A: $9
function clone : JObject; cdecl; // ()Ljava/lang/Object; A: $1
function equals(obj : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1
function format(arguments : JMap; result : JStringBuffer; pos : JFieldPosition) : JStringBuffer; cdecl; overload;// (Ljava/util/Map;Ljava/lang/StringBuffer;Ljava/text/FieldPosition;)Ljava/lang/StringBuffer; A: $11
function format(arguments : JObject; result : JStringBuffer; pos : JFieldPosition) : JStringBuffer; cdecl; overload;// (Ljava/lang/Object;Ljava/lang/StringBuffer;Ljava/text/FieldPosition;)Ljava/lang/StringBuffer; A: $11
function format(arguments : TJavaArray<JObject>; result : JStringBuffer; pos : JFieldPosition) : JStringBuffer; cdecl; overload;// ([Ljava/lang/Object;Ljava/lang/StringBuffer;Ljava/text/FieldPosition;)Ljava/lang/StringBuffer; A: $11
function format(pattern : JString; arguments : JMap) : JString; cdecl; overload;// (Ljava/lang/String;Ljava/util/Map;)Ljava/lang/String; A: $9
function format(pattern : JString; arguments : TJavaArray<JObject>) : JString; cdecl; overload;// (Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String; A: $89
function formatToCharacterIterator(arguments : JObject) : JAttributedCharacterIterator; cdecl;// (Ljava/lang/Object;)Ljava/text/AttributedCharacterIterator; A: $1
function getApostropheMode : JMessagePattern_ApostropheMode; cdecl; // ()Landroid/icu/text/MessagePattern$ApostropheMode; A: $1
function getArgumentNames : JSet; cdecl; // ()Ljava/util/Set; A: $1
function getFormatByArgumentName(argumentName : JString) : JFormat; cdecl; // (Ljava/lang/String;)Ljava/text/Format; A: $1
function getFormats : TJavaArray<JFormat>; cdecl; // ()[Ljava/text/Format; A: $1
function getFormatsByArgumentIndex : TJavaArray<JFormat>; cdecl; // ()[Ljava/text/Format; A: $1
function getLocale : JLocale; cdecl; // ()Ljava/util/Locale; A: $1
function getULocale : JULocale; cdecl; // ()Landroid/icu/util/ULocale; A: $1
function hashCode : Integer; cdecl; // ()I A: $1
function init(pattern : JString) : JMessageFormat; cdecl; overload; // (Ljava/lang/String;)V A: $1
function init(pattern : JString; locale : JLocale) : JMessageFormat; cdecl; overload;// (Ljava/lang/String;Ljava/util/Locale;)V A: $1
function init(pattern : JString; locale : JULocale) : JMessageFormat; cdecl; overload;// (Ljava/lang/String;Landroid/icu/util/ULocale;)V A: $1
function parse(source : JString) : TJavaArray<JObject>; cdecl; overload; // (Ljava/lang/String;)[Ljava/lang/Object; A: $1
function parse(source : JString; pos : JParsePosition) : TJavaArray<JObject>; cdecl; overload;// (Ljava/lang/String;Ljava/text/ParsePosition;)[Ljava/lang/Object; A: $1
function parseObject(source : JString; pos : JParsePosition) : JObject; cdecl;// (Ljava/lang/String;Ljava/text/ParsePosition;)Ljava/lang/Object; A: $1
function parseToMap(source : JString) : JMap; cdecl; overload; // (Ljava/lang/String;)Ljava/util/Map; A: $1
function parseToMap(source : JString; pos : JParsePosition) : JMap; cdecl; overload;// (Ljava/lang/String;Ljava/text/ParsePosition;)Ljava/util/Map; A: $1
function toPattern : JString; cdecl; // ()Ljava/lang/String; A: $1
function usesNamedArguments : boolean; cdecl; // ()Z A: $1
procedure applyPattern(pattern : JString; aposMode : JMessagePattern_ApostropheMode) ; cdecl; overload;// (Ljava/lang/String;Landroid/icu/text/MessagePattern$ApostropheMode;)V A: $1
procedure applyPattern(pttrn : JString) ; cdecl; overload; // (Ljava/lang/String;)V A: $1
procedure setFormat(formatElementIndex : Integer; newFormat : JFormat) ; cdecl;// (ILjava/text/Format;)V A: $1
procedure setFormatByArgumentIndex(argumentIndex : Integer; newFormat : JFormat) ; cdecl;// (ILjava/text/Format;)V A: $1
procedure setFormatByArgumentName(argumentName : JString; newFormat : JFormat) ; cdecl;// (Ljava/lang/String;Ljava/text/Format;)V A: $1
procedure setFormats(newFormats : TJavaArray<JFormat>) ; cdecl; // ([Ljava/text/Format;)V A: $1
procedure setFormatsByArgumentIndex(newFormats : TJavaArray<JFormat>) ; cdecl;// ([Ljava/text/Format;)V A: $1
procedure setFormatsByArgumentName(newFormats : JMap) ; cdecl; // (Ljava/util/Map;)V A: $1
procedure setLocale(locale : JLocale) ; cdecl; overload; // (Ljava/util/Locale;)V A: $1
procedure setLocale(locale : JULocale) ; cdecl; overload; // (Landroid/icu/util/ULocale;)V A: $1
end;
[JavaSignature('android/icu/text/MessageFormat$Field')]
JMessageFormat = interface(JObject)
['{79C6E442-3A7C-4344-9CF5-D707349E0FD5}']
function clone : JObject; cdecl; // ()Ljava/lang/Object; A: $1
function equals(obj : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1
function formatToCharacterIterator(arguments : JObject) : JAttributedCharacterIterator; cdecl;// (Ljava/lang/Object;)Ljava/text/AttributedCharacterIterator; A: $1
function getApostropheMode : JMessagePattern_ApostropheMode; cdecl; // ()Landroid/icu/text/MessagePattern$ApostropheMode; A: $1
function getArgumentNames : JSet; cdecl; // ()Ljava/util/Set; A: $1
function getFormatByArgumentName(argumentName : JString) : JFormat; cdecl; // (Ljava/lang/String;)Ljava/text/Format; A: $1
function getFormats : TJavaArray<JFormat>; cdecl; // ()[Ljava/text/Format; A: $1
function getFormatsByArgumentIndex : TJavaArray<JFormat>; cdecl; // ()[Ljava/text/Format; A: $1
function getLocale : JLocale; cdecl; // ()Ljava/util/Locale; A: $1
function getULocale : JULocale; cdecl; // ()Landroid/icu/util/ULocale; A: $1
function hashCode : Integer; cdecl; // ()I A: $1
function parse(source : JString) : TJavaArray<JObject>; cdecl; overload; // (Ljava/lang/String;)[Ljava/lang/Object; A: $1
function parse(source : JString; pos : JParsePosition) : TJavaArray<JObject>; cdecl; overload;// (Ljava/lang/String;Ljava/text/ParsePosition;)[Ljava/lang/Object; A: $1
function parseObject(source : JString; pos : JParsePosition) : JObject; cdecl;// (Ljava/lang/String;Ljava/text/ParsePosition;)Ljava/lang/Object; A: $1
function parseToMap(source : JString) : JMap; cdecl; overload; // (Ljava/lang/String;)Ljava/util/Map; A: $1
function parseToMap(source : JString; pos : JParsePosition) : JMap; cdecl; overload;// (Ljava/lang/String;Ljava/text/ParsePosition;)Ljava/util/Map; A: $1
function toPattern : JString; cdecl; // ()Ljava/lang/String; A: $1
function usesNamedArguments : boolean; cdecl; // ()Z A: $1
procedure applyPattern(pattern : JString; aposMode : JMessagePattern_ApostropheMode) ; cdecl; overload;// (Ljava/lang/String;Landroid/icu/text/MessagePattern$ApostropheMode;)V A: $1
procedure applyPattern(pttrn : JString) ; cdecl; overload; // (Ljava/lang/String;)V A: $1
procedure setFormat(formatElementIndex : Integer; newFormat : JFormat) ; cdecl;// (ILjava/text/Format;)V A: $1
procedure setFormatByArgumentIndex(argumentIndex : Integer; newFormat : JFormat) ; cdecl;// (ILjava/text/Format;)V A: $1
procedure setFormatByArgumentName(argumentName : JString; newFormat : JFormat) ; cdecl;// (Ljava/lang/String;Ljava/text/Format;)V A: $1
procedure setFormats(newFormats : TJavaArray<JFormat>) ; cdecl; // ([Ljava/text/Format;)V A: $1
procedure setFormatsByArgumentIndex(newFormats : TJavaArray<JFormat>) ; cdecl;// ([Ljava/text/Format;)V A: $1
procedure setFormatsByArgumentName(newFormats : JMap) ; cdecl; // (Ljava/util/Map;)V A: $1
procedure setLocale(locale : JLocale) ; cdecl; overload; // (Ljava/util/Locale;)V A: $1
procedure setLocale(locale : JULocale) ; cdecl; overload; // (Landroid/icu/util/ULocale;)V A: $1
end;
TJMessageFormat = class(TJavaGenericImport<JMessageFormatClass, JMessageFormat>)
end;
implementation
end.
|
unit uBitmapUtils;
interface
uses
System.Types,
System.Math,
System.Classes,
Winapi.Windows,
Vcl.Graphics,
Dmitry.Graphics.Types,
uDBGraphicTypes,
uMemory,
uConstants,
uMath;
const
// Image processiong options
ZoomSmoothMin = 0.4;
type
TBitmapHelper = class helper for TBitmap
public
function ClientRect: TRect;
end;
procedure ThreadDraw(S, D: TBitmap; X, Y: Integer);
procedure ApplyRotate(Bitmap: TBitmap; RotateValue: Integer);
procedure Rotate180A(Bitmap: TBitmap);
procedure Rotate270A(Bitmap: TBitmap);
procedure Rotate90A(Bitmap: TBitmap);
procedure AssignBitmap(Dest: TBitmap; Src: TBitmap);
procedure StretchA(Width, Height: Integer; S, D: TBitmap);
procedure QuickReduce(NewWidth, NewHeight: Integer; D, S: TBitmap);
procedure StretchCool(X, Y, Width, Height: Integer; S, D: TBitmap); overload;
procedure StretchCool(Width, Height: Integer; S, D: TBitmap); overload;
procedure QuickReduceWide(Width, Height: Integer; S, D: TBitmap);
procedure DoResize(Width, Height: Integer; S, D: TBitmap);
procedure Interpolate(X, Y, Width, Height: Integer; Rect: TRect; S, D: TBitmap); overload;
procedure LoadBMPImage32bit(S: TBitmap; D: TBitmap; BackGroundColor: TColor);
procedure SelectedColor(Image: TBitmap; Color: TColor);
procedure FillColorEx(Bitmap: TBitmap; Color: TColor);
procedure MixWithColor(Bitmap: TBitmap; MixTransparencity: Byte; Color: TColor; ExceptRect: TRect);
procedure DrawImageEx(Dest, Src: TBitmap; X, Y: Integer);
procedure DrawImageExTransparency(Dest, Src: TBitmap; X, Y: Integer; Transparency: Byte);
procedure DrawImageExRect(Dest, Src: TBitmap; SX, SY, SW, SH: Integer; DX, DY: Integer);
procedure DrawImageEx32(Dest32, Src32: TBitmap; X, Y: Integer);
procedure DrawImageEx32To24(Dest24, Src32: TBitmap; X, Y: Integer);
procedure DrawImageEx32To24Transparency(Dest24, Src32: TBitmap; X, Y: Integer; Transparency: Byte);
procedure DrawImageEx24To32(Dest32, Src24: TBitmap; X, Y: Integer; NewTransparent: Byte = 0);
procedure FillTransparentChannel(Bitmap: TBitmap; TransparentValue: Byte);
procedure FillTransparentColor(Bitmap: TBitmap; Color: TColor; X, Y, Width, Height: Integer; TransparentValue: Byte = 0); overload;
procedure DrawTransparentColor(Bitmap: TBitmap; Color: TColor; X, Y, Width, Height: Integer; TransparentValue: Byte = 0);
procedure DrawTransparentColorGradient(Bitmap: TBitmap; Color: TColor; X, Y, Width, Height: Integer; TransparentValueFrom, TransparentValueTo: Byte);
procedure FillTransparentColor(Bitmap: TBitmap; Color: TColor; TransparentValue: Byte = 0); overload;
procedure DrawImageEx32To32(Dest32, Src32: TBitmap; X, Y: Integer);
procedure DrawTransparent(S, D: TBitmap; Transparent: Byte);
procedure GrayScale(Image: TBitmap);
procedure DrawText32Bit(Bitmap32: TBitmap; Text: string; Font: TFont; ARect: TRect; DrawTextOptions: Cardinal);
procedure DrawColorMaskTo32Bit(Dest, Mask: TBitmap; Color: TColor; X, Y: Integer);
procedure DrawShadowToImage(Dest32, Src: TBitmap; Transparenty: Byte = 0);
procedure DrawRoundGradientVert(Dest: TBitmap; Rect: TRect; ColorFrom, ColorTo, BorderColor: TColor;
RoundRect: Integer; TransparentValue: Byte = 220);
procedure StretchCool(Width, Height: Integer; S, D: TBitmap; CallBack: TProgressCallBackProc); overload;
procedure SmoothResize(Width, Height: Integer; S, D: TBitmap; CallBack: TProgressCallBackProc = nil);
procedure ThumbnailResize(Width, Height: Integer; S, D: TBitmap; CallBack: TProgressCallBackProc = nil);
procedure Interpolate(X, Y, Width, Height: Integer; Rect: TRect; var S, D: TBitmap; CallBack: TProgressCallBackProc); overload;
procedure ProportionalSize(aWidth, aHeight: Integer; var aWidthToSize, aHeightToSize: Integer);
procedure ProportionalSizeA(aWidth, aHeight: Integer; var aWidthToSize, aHeightToSize: Integer);
procedure KeepProportions(var Bitmap: TBitmap; MaxWidth, MaxHeight: Integer);
procedure ResizeTo(var Bitmap: TBitmap; Width, Height: Integer);
procedure CenterBitmap24To32ImageList(var Bitmap: TBitmap; ImageSize: Integer);
function Gistogramma(W, H: Integer; S: PARGBArray): THistogrammData;
function Gistogramma32(W, H: Integer; S: PARGB32Array): THistogrammData;
function FillHistogramma(Bitmap: TBitmap): THistogrammData;
implementation
function FillHistogramma(Bitmap: TBitmap): THistogrammData;
var
PRGBArr: PARGBArray;
PRGB32Arr: PARGB32Array;
I: Integer;
begin
if Bitmap.PixelFormat = pf24Bit then
begin
SetLength(PRGBArr, Bitmap.Height);
for I := 0 to Bitmap.Height - 1 do
PRGBArr[I] := Bitmap.ScanLine[I];
Result := Gistogramma(Bitmap.Width, Bitmap.Height, PRGBArr);
end else if Bitmap.PixelFormat = pf32Bit then
begin
SetLength(PRGB32Arr, Bitmap.Height);
for I := 0 to Bitmap.Height - 1 do
PRGB32Arr[I] := Bitmap.ScanLine[I];
Result := Gistogramma32(Bitmap.Width, Bitmap.Height, PRGB32Arr);
end;
end;
function Gistogramma(W, H: Integer; S: PARGBArray): THistogrammData;
var
I, J: Integer;
P: PARGB;
LGray, LR, LG, LB: Byte;
begin
for I := 0 to 255 do
begin
Result.Gray[I] := 0;
Result.Red[I] := 0;
Result.Green[I] := 0;
Result.Blue[I] := 0;
end;
for I := 0 to H - 1 do
begin
P := S[I];
for J := 0 to W - 1 do
begin
LR := P[J].R;
LG := P[J].G;
LB := P[J].B;
LGray := (LR * 77 + LG * 151 + LB * 28) shr 8;
Inc(Result.Gray[LGray]);
Inc(Result.Red[LR]);
Inc(Result.Green[LG]);
Inc(Result.Blue[LB]);
end;
end;
Result.Loaded := True;
end;
function Gistogramma32(W, H: Integer; S: PARGB32Array): THistogrammData;
var
I, J: Integer;
P: PARGB32;
LGray, LR, LG, LB: Byte;
begin
for I := 0 to 255 do
begin
Result.Gray[I] := 0;
Result.Red[I] := 0;
Result.Green[I] := 0;
Result.Blue[I] := 0;
end;
for I := 0 to H - 1 do
begin
P := S[I];
for J := 0 to W - 1 do
begin
LR := P[J].R;
LG := P[J].G;
LB := P[J].B;
LGray := (LR * 77 + LG * 151 + LB * 28) shr 8;
Inc(Result.Gray[LGray]);
Inc(Result.Red[LR]);
Inc(Result.Green[LG]);
Inc(Result.Blue[LB]);
end;
end;
Result.Loaded := True;
end;
procedure ThreadDraw(S, D: TBitmap; X, Y: Integer);
var
SXp, DXp: array of PARGB;
Ymax, Xmax: Integer;
I, J: Integer;
begin
if S.Width - 1 + X > D.Width - 1 then
Xmax := D.Width - X - 1
else
Xmax := S.Width - 1;
if S.Height - 1 + Y > D.Height - 1 then
Ymax := D.Height - Y - 1
else
Ymax := S.Height - 1;
S.PixelFormat := pf24bit;
D.PixelFormat := pf24bit;
SetLength(SXp, S.Height);
for I := 0 to S.Height - 1 do
SXp[I] := S.ScanLine[I];
SetLength(DXp, D.Height);
for I := 0 to D.Height - 1 do
DXp[I] := D.ScanLine[I];
for I := 0 to Ymax do
for J := 0 to Xmax do
DXp[I + Y, J + X] := SXp[I, J];
end;
procedure ProportionalSizeA(AWidth, AHeight: Integer; var AWidthToSize, AHeightToSize: Integer);
begin
if (AWidthToSize = 0) or (AHeightToSize = 0) then
begin
AHeightToSize := 0;
AWidthToSize := 0;
end else
begin
if AWidth = 0 then
begin
AWidthToSize := 0;
AHeightToSize := 0;
Exit;
end;
if (AHeightToSize / AWidthToSize) < (AHeight / AWidth) then
begin
AHeightToSize := Round((AWidth / AWidthToSize) * AHeightToSize);
AWidthToSize := AWidth;
end else
begin
AWidthToSize := Round((AHeight / AHeightToSize) * AWidthToSize);
AHeightToSize := AHeight;
end;
end;
end;
procedure ProportionalSize(AWidth, AHeight: Integer; var AWidthToSize, AHeightToSize: Integer);
begin
if (AWidthToSize < AWidth) and (AHeightToSize < AHeight) then
begin
Exit;
end;
if (AWidthToSize = 0) or (AHeightToSize = 0) then
begin
AHeightToSize := 0;
AWidthToSize := 0;
end else
begin
if AWidth = 0 then
begin
AWidthToSize := 0;
AHeightToSize := 0;
Exit;
end;
if (AHeightToSize / AWidthToSize) < (AHeight / AWidth) then
begin
AHeightToSize := Round((AWidth / AWidthToSize) * AHeightToSize);
AWidthToSize := AWidth;
end else
begin
AWidthToSize := Round((AHeight / AHeightToSize) * AWidthToSize);
AHeightToSize := AHeight;
end;
end;
end;
procedure SelectedColor(Image: TBitmap; Color: TColor);
var
I, J, R, G, B: Integer;
P: PARGB;
begin
R := GetRValue(Color);
G := GetGValue(Color);
B := GetBValue(Color);
if Image.PixelFormat <> Pf24bit then
Image.PixelFormat := Pf24bit;
for I := 0 to Image.Height - 1 do
begin
P := Image.ScanLine[I];
for J := 0 to Image.Width - 1 do
if Odd(I + J) then
begin
P[J].R := R;
P[J].G := G;
P[J].B := B;
end;
end;
end;
{function MixBytes(FG, BG, TRANS: Byte): Byte;
asm
push bx // push some regs
push cx
push dx
mov DH,TRANS // remembering Transparency value (or Opacity - as you like)
mov BL,FG // filling registers with our values
mov AL,DH // BL = ForeGround (FG)
mov CL,BG // CL = BackGround (BG)
xor AH,AH // Clear High-order parts of regs
xor BH,BH
xor CH,CH
mul BL // AL=AL*BL
mov BX,AX // BX=AX
xor AH,AH
mov AL,DH
xor AL,$FF // AX=(255-TRANS)
mul CL // AL=AL*CL
add AX,BX // AX=AX+BX
shr AX,8 // Fine! Here we have mixed value in AL
pop dx // Hm... No rubbish after us, ok?
pop cx
pop bx // Bye, dear Assembler - we go home to Delphi!
end;}
function MaxI8(A, B : Byte) : Byte; inline; overload;
begin
if A > B then
Result := A
else
Result := B;
end;
function MinI8(A, B : Byte) : Byte; inline; overload;
begin
if A > B then
Result := B
else
Result := A;
end;
function MaxI32(A, B : Integer) : Integer; inline; overload;
begin
if A > B then
Result := A
else
Result := B;
end;
function MinI32(A, B : Integer) : Integer; inline; overload;
begin
if A > B then
Result := B
else
Result := A;
end;
procedure AssignBitmap(Dest: TBitmap; Src: TBitmap);
var
I, J: Integer;
PS, PD: PARGB;
PS32, PD32: PARGB32;
begin
if Src = nil then
Exit;
if Src.PixelFormat <> pf32bit then
begin
Src.PixelFormat := pf24bit;
Dest.PixelFormat := pf24bit;
Dest.SetSize(Src.Width, Src.Height);
for I := 0 to Src.Height - 1 do
begin
PD := Dest.ScanLine[I];
PS := Src.ScanLine[I];
for J := 0 to Src.Width - 1 do
PD[J] := PS[J];
end;
end else
begin
Src.PixelFormat := pf32bit;
Dest.PixelFormat := pf32bit;
Dest.SetSize(Src.Width, Src.Height);
for I := 0 to Src.Height - 1 do
begin
PD32 := Dest.ScanLine[I];
PS32 := Src.ScanLine[I];
for J := 0 to Src.Width - 1 do
PD32[J] := PS32[J];
end;
end;
end;
procedure Rotate180A(Bitmap: TBitmap);
var
I, J: Integer;
PS, PD: PARGB;
PS32, PD32: PARGB32;
Image: TBitmap;
begin
Image := TBitmap.Create;
try
if Bitmap.PixelFormat <> pf32bit then
begin
Bitmap.PixelFormat := pf24bit;
AssignBitmap(Image, Bitmap);
for I := 0 to Image.Height - 1 do
begin
PS := Image.ScanLine[I];
PD := Bitmap.ScanLine[Image.Height - I - 1];
for J := 0 to Image.Width - 1 do
PD[J] := PS[Image.Width - 1 - J];
end;
end else
begin
AssignBitmap(Image, Bitmap);
for I := 0 to Image.Height - 1 do
begin
PS32 := Image.ScanLine[I];
PD32 := Bitmap.ScanLine[Image.Height - I - 1];
for J := 0 to Image.Width - 1 do
PD32[J] := PS32[Image.Width - 1 - J];
end;
end;
finally
F(Image);
end;
end;
procedure Rotate270A(Bitmap: TBitmap);
var
I, J: Integer;
PS: PARGB;
PS32: PARGB32;
PA: array of PARGB;
PA32: array of PARGB32;
Image: TBitmap;
begin
Image := TBitmap.Create;
try
if Bitmap.PixelFormat <> pf32bit then
begin
Bitmap.PixelFormat := pf24bit;
AssignBitmap(Image, Bitmap);
Bitmap.SetSize(Image.Height, Image.Width);
SetLength(PA, Bitmap.Height);
for I := 0 to Bitmap.Height - 1 do
PA[I] := Bitmap.ScanLine[Bitmap.Height - 1 - I];
for I := 0 to Image.Height - 1 do
begin
PS := Image.ScanLine[I];
for J := 0 to Image.Width - 1 do
PA[J, I] := PS[J];
end;
end else
begin
AssignBitmap(Image, Bitmap);
Bitmap.SetSize(Image.Height, Image.Width);
SetLength(PA32, Bitmap.Height);
for I := 0 to Bitmap.Height - 1 do
PA32[I] := Bitmap.ScanLine[Bitmap.Height - 1 - I];
for I := 0 to Image.Height - 1 do
begin
PS32 := Image.ScanLine[I];
for J := 0 to Image.Width - 1 do
PA32[J, I] := PS32[J];
end;
end;
finally
F(Image);
end;
end;
procedure Rotate90A(Bitmap: TBitmap);
var
I, J: Integer;
PS: PARGB;
PS32: PARGB32;
PA: array of PARGB;
PA32: array of PARGB32;
Image: TBitmap;
begin
Image := TBitmap.Create;
try
if Bitmap.PixelFormat <> pf32bit then
begin
Bitmap.PixelFormat := pf24bit;
AssignBitmap(Image, Bitmap);
Bitmap.SetSize(Image.Height, Image.Width);
SetLength(PA, Bitmap.Height);
for I := 0 to Bitmap.Height - 1 do
PA[I] := Bitmap.ScanLine[I];
for I := 0 to Image.Height - 1 do
begin
PS := Image.ScanLine[Image.Height - I - 1];
for J := 0 to Image.Width - 1 do
PA[J, I] := PS[J];
end;
end else
begin
AssignBitmap(Image, Bitmap);
Bitmap.SetSize(Image.Height, Image.Width);
SetLength(PA32, Bitmap.Height);
for I := 0 to Bitmap.Height - 1 do
PA32[I] := Bitmap.ScanLine[I];
for I := 0 to Image.Height - 1 do
begin
PS32 := Image.ScanLine[Image.Height - I - 1];
for J := 0 to Image.Width - 1 do
PA32[J, I] := PS32[J];
end;
end;
finally
F(Image);
end;
end;
procedure ApplyRotate(Bitmap: TBitmap; RotateValue: Integer);
begin
case RotateValue and DB_IMAGE_ROTATE_MASK of
DB_IMAGE_ROTATE_270:
Rotate270A(Bitmap);
DB_IMAGE_ROTATE_90:
Rotate90A(Bitmap);
DB_IMAGE_ROTATE_180:
Rotate180A(Bitmap);
end;
end;
procedure StretchA(Width, Height: Integer; S, D: TBitmap);
var
I, J: Integer;
P1: PARGB;
Sh, Sw: Single;
Xp: array of PARGB;
Y: Integer;
XAr: array of Integer;
begin
D.SetSize(100, 100);
Sw := S.Width / Width;
Sh := S.Height / Height;
SetLength(Xp, S.Height);
for I := 0 to S.Height - 1 do
Xp[I] := S.ScanLine[I];
SetLength(XAr, Width);
for J := 0 to Width - 1 do
XAr[J] := Round(Sw * J);
for I := 0 to Height - 1 do
begin
P1 := D.ScanLine[I];
Y := Round(Sh * I);
for J := 0 to Width - 1 do
P1[J] := Xp[Y, XAr[J]];
end;
end;
procedure DoResize(Width, Height: Integer; S, D: TBitmap);
begin
if (Width = 0) or (Height = 0) then
Exit;
if (S.Width = 0) or (S.Height = 0) then
Exit;
if ((Width / S.Width > 1) or (Height / S.Height > 1)) then
begin
if (S.Width > 2) and (S.Height > 2) then
Interpolate(0, 0, Width, Height, Rect(0, 0, S.Width, S.Height), S, D)
else
StretchCool(Width, Height, S, D);
end else
begin
if ((S.Width div Width >= 8) or (S.Height div Height >= 8)) and
(S.Width > 2) and (S.Height > 2) then
QuickReduce(Width, Height, S, D)
else
begin
if (Width / S.Width > ZoomSmoothMin) and (S.Width > 1) then
SmoothResize(Width, Height, S, D)
else
StretchCool(Width, Height, S, D);
end;
end;
end;
procedure StretchCool(X, Y, Width, Height: Integer; S, D: TBitmap);
var
R, G, B: Integer;
I, J, K, P, Sheight1, Col: Integer;
P1, PS: PARGB;
RGBS, RGBD: PRGB;
Sh, Sw: Extended;
Xp: array of PARGB;
S_H, S_W: Integer;
XAW : array of Integer;
YMin, YMax: Integer;
XAWJ, XAWJ1: Integer;
begin
S.PixelFormat := pf24bit;
D.PixelFormat := pf24bit;
if Width + X > D.Width then
D.Width := Width + X;
if Height + Y > D.Height then
D.Height := Height + Y;
Sh := S.Height / Height;
Sw := S.Width / Width;
Sheight1 := S.Height - 1;
SetLength(Xp, S.Height);
for I := 0 to Sheight1 do
Xp[I] := S.ScanLine[I];
S_W := S.Width - 1;
S_H := S.Height - 1;
SetLength(XAW, Width + 1);
for I := 0 to Width do
XAW[I] := Min(S_W, Round(Sw * I));
for I := Max(0, Y) to Height + Y - 1 do
begin
P1 := D.ScanLine[I];
YMin := Max(0, Round(Sh * (I - Y)));
YMax := Min(S_h, Round(Sh * (I - Y + 1 )) - 1);
RGBD := @P1[X];
for J := 0 to Width - 1 do
begin
R := 0;
G := 0;
B := 0;
XAWJ := XAW[J];
XAWJ1 := XAW[J + 1] - 1;
Col := (YMax - YMin + 1) * (XAWJ1 - XAWJ + 1);
for K := YMin to YMax do
begin
PS := XP[K];
RGBS := @PS[XAWJ];
for P := XAWJ to XAWJ1 do
begin
Inc(R, RGBS^.R);
Inc(G, RGBS^.G);
Inc(B, RGBS^.B);
Inc(RGBS);
end;
end;
if (Col <> 0) and (J + X > 0) then
begin
RGBD^.R := R div Col;
RGBD^.G := G div Col;
RGBD^.B := B div Col;
end;
Inc(RGBD);
end;
end;
end;
procedure Interpolate(X, Y, Width, Height: Integer; Rect: TRect; S, D: TBitmap);
var
Z1, Z2: Integer;
K: Integer;
I, J, SW, JMax, JMin: Integer;
Dw, Dh, Xo, Yo: Integer;
Y1r: Integer;
XS, XD: array of PARGB;
XS32, XD32: array of PARGB32;
Dx, Dy: Single;
XAW: array of Integer;
XAWD: array of Integer;
Dxjx1r, DyI: Integer;
PD, PS, PS1: PARGB;
RGBD: PRGB;
PD32, PS32, PS132: PARGB32;
RGBD32: PRGB32;
begin
if not ((S.PixelFormat = pf32bit) and (D.PixelFormat = pf32bit)) then
begin
S.PixelFormat := pf24bit;
D.PixelFormat := pf24bit;
end;
D.SetSize(Max(D.Width, X + Width), Max(D.Height, Y + Height));
SW := S.Width;
DW := Min(D.Width - X, X + Width);
DH := Min(D.Height - y, Y + Height);
DX := Width / (Rect.Right - Rect.Left - 1);
DY := Height / (Rect.Bottom - Rect.Top - 1);
if (Dx < 1) and (Dy < 1) then
Exit;
if (S.PixelFormat = pf24Bit) then
begin
SetLength(Xs, S.Height);
for I := 0 to S.Height - 1 do
XS[I] := S.Scanline[I];
SetLength(Xd, D.Height);
for I := 0 to D.Height - 1 do
XD[I] := D.Scanline[I];
end else
begin
SetLength(XS32, S.Height);
for I := 0 to S.Height - 1 do
XS32[I] := S.Scanline[I];
SetLength(XD32, D.Height);
for I := 0 to D.Height - 1 do
XD32[I] := D.Scanline[I];
end;
JMax := Min(Round((Rect.Right - Rect.Left - 1) * DX) - 1, DW - 1);
JMin := 0;
if X < 0 then
JMin := -X;
SetLength(XAW, Width + 1);
SetLength(XAWD, Width + 1);
for I := Width downto 0 do
begin
XAW[I] := FastTrunc(I / Dx);
XAWD[I] := FastTrunc(1024 * (I / Dx - XAW[I]));
if XAW[I] + Rect.Left > SW then
JMax := I - 1;
end;
if (S.PixelFormat = pf24Bit) then
begin
for I := 0 to Min(Round((Rect.Bottom - Rect.Top - 1) * DY) - 1, DH - 1) do
begin
Yo := FastTrunc(I / Dy) + Rect.Top;
if Yo > S.Height then
Break;
if I + Y < 0 then
Continue;
PD := Xd[I + Y];
PS := XS[Yo];
PS1 := XS[Yo + 1];
RGBD := @PD[JMin + X];
Y1r := FastTrunc(I / Dy);
DyI := FastTrunc(1024 * I / Dy);
for J := JMin to JMax do
begin
Xo := XAW[J] + Rect.Left;
Dxjx1r := XAWD[J];
Z1 := ((PS[Xo + 1].R - PS[Xo].R) * Dxjx1r) div 1024 + PS[Xo].R;
Z2 := ((PS1[Xo + 1].R - PS1[Xo].R) * Dxjx1r) div 1024 + PS1[Xo].R;
K := (z2 - Z1);
RGBD^.R := (DyI * K div 1024 + Z1 - Y1r * K);
Z1 := ((PS[Xo + 1].G - PS[Xo].G) * Dxjx1r) div 1024 + PS[Xo].G;
Z2 := ((PS1[Xo + 1].G - PS1[Xo].G) * Dxjx1r) div 1024 + PS1[Xo].G;
K := (Z2 - Z1);
RGBD^.G := (DyI * K div 1024 + Z1 - Y1r * K);
Z1 := ((PS[Xo + 1].B - PS[Xo].B) * Dxjx1r) div 1024 + PS[Xo].B;
Z2 := ((PS1[Xo + 1].B - PS1[Xo].B) * Dxjx1r) div 1024 + PS1[Xo].B;
K := (Z2 - Z1);
RGBD^.B := (DyI * K div 1024 + Z1 - Y1r * K);
Inc(RGBD);
end;
end;
end else
begin
for I := 0 to Min(Round((Rect.Bottom - Rect.Top - 1) * DY) - 1, DH - 1) do
begin
Yo := FastTrunc(I / Dy) + Rect.Top;
if Yo > S.Height then
Break;
if I + Y < 0 then
Continue;
PD32 := Xd32[I + Y];
PS32 := XS32[Yo];
PS132 := XS32[Yo + 1];
RGBD32 := @PD32[JMin + X];
Y1r := FastTrunc(I / Dy);
DyI := FastTrunc(1024 * I / Dy);
for J := JMin to JMax do
begin
Xo := XAW[J] + Rect.Left;
Dxjx1r := XAWD[J];
Z1 := ((PS32[Xo + 1].R - PS32[Xo].R) * Dxjx1r) div 1024 + PS32[Xo].R;
Z2 := ((PS132[Xo + 1].R - PS132[Xo].R) * Dxjx1r) div 1024 + PS132[Xo].R;
K := (Z2 - Z1);
RGBD32^.R := (DyI * K div 1024 + Z1 - Y1r * K);
Z1 := ((PS32[Xo + 1].G - PS32[Xo].G)* Dxjx1r) div 1024 + PS32[Xo].G;
Z2 := ((PS132[Xo + 1].G - PS132[Xo].G) * Dxjx1r) div 1024 + PS132[Xo].G;
K := (Z2 - Z1);
RGBD32^.G := (DyI * K div 1024 + Z1 - Y1r * K) and 255;
Z1 := ((PS32[Xo + 1].B - PS32[Xo].B) * Dxjx1r) div 1024 + PS32[Xo].B;
Z2 := ((PS132[Xo + 1].B - PS132[Xo].B) * Dxjx1r) div 1024 + PS132[Xo].B;
K := (Z2 - Z1);
RGBD32^.B := (DyI * K div 1024 + Z1 - Y1r * K) and 255;
Z1 := ((PS32[Xo + 1].L - PS32[Xo].L) * Dxjx1r) div 1024 + PS32[Xo].L;
Z2 := ((PS132[Xo + 1].L - PS132[Xo].L) * Dxjx1r) div 1024 + PS132[Xo].L;
K := (Z2 - Z1);
RGBD32^.L := (DyI * K div 1024 + Z1 - Y1r * K) and 255;
Inc(RGBD32);
end;
end;
end;
end;
procedure QuickReduce(NewWidth, NewHeight: Integer; D, S: TBitmap);
var
X, Y, Xi1, Yi1, Xi2, Yi2, Xx, Yy, Lw1: Integer;
Bufw, Bufh, Outw, Outh: Integer;
Sumr, Sumb, Sumg, Suml, Pixcnt: Dword;
AdrIn, AdrOut, AdrLine0, DeltaLine, DeltaLine2: NativeInt;
begin
{$R-}
if not ((S.PixelFormat = pf32Bit) and (D.PixelFormat = pf32Bit)) then
begin
S.PixelFormat := pf24Bit;
D.PixelFormat := pf24Bit;
end;
S.SetSize(NewWidth, NewHeight);
bufw := D.Width;
bufh := D.Height;
outw := S.Width;
outh := S.Height;
adrLine0 := NativeInt(D.ScanLine[0]);
deltaLine := 0;
if D.Height > 1 then
deltaLine := NativeInt(D.ScanLine[1]) - adrLine0;
yi2 := 0;
if S.PixelFormat = pf32Bit then
begin
for y := 0 to outh-1 do
begin
adrOut := NativeInt(S.ScanLine[y]);
yi1 := yi2 {+ 1};
if yi1 < 0 then yi1 := 0;
yi2 := ((y+1) * bufh) div outh - 1;
if yi2 < 0 then yi2 := 0;
if yi2 > bufh-1 then yi2 := bufh;
xi2 := 0;
for x := 0 to outw-1 do
begin
xi1 := xi2 {+ 1};
if xi1 < 0 then xi1 := 0;
xi2 := ((x+1) * bufw) div outw - 1;
if xi2 > bufw-1 then xi2 := bufw-1; //
lw1 := xi2-xi1+1;
deltaLine2 := deltaLine - lw1*4;
sumb := 0;
sumg := 0;
sumr := 0;
suml := 0;
adrIn := adrLine0 + yi1*deltaLine + xi1*4;
for yy := yi1 to yi2 do
begin
for xx := 1 to lw1 do
begin
Inc(sumb, PByte(adrIn+0)^);
Inc(sumg, PByte(adrIn+1)^);
Inc(sumr, PByte(adrIn+2)^);
Inc(suml, PByte(adrIn+3)^);
Inc(adrIn, 4);
end;
Inc (adrIn, deltaLine2);
end;
pixcnt := (yi2-yi1+1)*lw1;
if pixcnt<>0 then
begin
PByte(adrOut+0)^ := sumb div pixcnt;
PByte(adrOut+1)^ := sumg div pixcnt;
PByte(adrOut+2)^ := sumr div pixcnt;
PByte(adrOut+3)^ := suml div pixcnt;
end;
Inc(adrOut, 4);
end;
end;
end else
begin
for y := 0 to outh-1 do
begin
adrOut := NativeInt(S.ScanLine[y]);
yi1 := yi2 {+ 1};
if yi1 < 0 then yi1 := 0;
yi2 := ((y+1) * bufh) div outh - 1;
if yi2 < 0 then yi2 := 0;
if yi2 > bufh-1 then yi2 := bufh;
xi2 := 0;
for x := 0 to outw-1 do
begin
xi1 := xi2 {+ 1};
if xi1 < 0 then xi1 := 0;
xi2 := ((x+1) * bufw) div outw - 1;
if xi2 > bufw-1 then xi2 := bufw-1; //
lw1 := xi2-xi1+1;
deltaLine2 := deltaLine - lw1*3;
sumb := 0;
sumg := 0;
sumr := 0;
adrIn := adrLine0 + yi1*deltaLine + xi1*3;
for yy := yi1 to yi2 do
begin
for xx := 1 to lw1 do
begin
Inc(sumb, PByte(adrIn+0)^);
Inc(sumg, PByte(adrIn+1)^);
Inc(sumr, PByte(adrIn+2)^);
Inc(adrIn, 3);
end;
Inc (adrIn, deltaLine2);
end;
pixcnt := (yi2-yi1+1)*lw1;
if pixcnt<>0 then
begin
PByte(adrOut+0)^ := sumb div pixcnt;
PByte(adrOut+1)^ := sumg div pixcnt;
PByte(adrOut+2)^ := sumr div pixcnt;
end;
Inc(adrOut, 3);
end;
end;
end;
end;
procedure StretchCool(Width, Height: Integer; S, D: TBitmap);
var
I, J, K, F: Integer;
P: PARGB;
XP: array of PARGB;
P32: PARGB32;
XP32: array of PARGB32;
Count, R, G, B, L, Sheight1, SHI, SWI: Integer;
SH, SW: Extended;
YMin, YMax: Integer;
XAW: array of Integer;
XAWJ, XAWJ1: Integer;
PS: PARGB;
RGBS: PRGB;
PS32: PARGB32;
RGB32S: PRGB32;
begin
if Width + Height = 0 then
Exit;
if S.PixelFormat = pf32bit then
D.PixelFormat := pf32bit
else
begin
S.PixelFormat := pf24bit;
D.PixelFormat := pf24bit;
end;
D.Width := Width;
D.Height := Height;
SH := S.Height / Height;
SW := S.Width / Width;
Sheight1 := S.height - 1;
SHI := S.Height;
SWI := S.Width;
SetLength(XAW, Width + 1);
for I := 0 to Width do
XAW[I] := Ceil(SW * I);
if S.PixelFormat = pf24bit then
begin
SetLength(XP, S.height);
for I := 0 to Sheight1 do
XP[I] := S.ScanLine[I];
for I := 0 to Height - 1 do
begin
P := D.ScanLine[I];
YMin := Round(SH * I);
YMax := MinI32(SHI - 1, Ceil(SH * (I + 1)) - 1);
for J := 0 to Width - 1 do
begin
R := 0;
G := 0;
B := 0;
XAWJ := XAW[J];
XAWJ1 := MinI32(SWI - 1, XAW[J + 1] - 1);
Count := (YMax - YMin + 1) * (XAWJ1 - XAWJ + 1);
for K := YMin to YMax do
begin
PS := XP[K];
RGBS := @PS[XAWJ];
for F := XAWJ to XAWJ1 do
begin
Inc(R, RGBS^.R);
Inc(G, RGBS^.G);
Inc(B, RGBS^.B);
Inc(RGBS);
end;
end;
if Count <> 0 then
begin
P[J].R := R div Count;
P[J].G := G div Count;
P[J].B := B div Count;
end;
end;
end;
end else
begin
SetLength(XP32, S.height);
for I := 0 to Sheight1 do
XP32[I] := S.ScanLine[I];
for I := 0 to Height - 1 do
begin
P32 := D.ScanLine[I];
YMin := Round(SH * I);
YMax := MinI32(SHI - 1, Ceil(SH * (I + 1)) - 1);
for J := 0 to Width - 1 do
begin
R := 0;
G := 0;
B := 0;
L := 0;
XAWJ := XAW[J];
XAWJ1 := MinI32(SWI - 1, XAW[J + 1] - 1);
Count := (YMax - YMin + 1) * (XAWJ1 - XAWJ + 1);
for K := YMin to YMax do
begin
PS32 := XP32[K];
RGB32S := @PS32[XAWJ];
for F := XAWJ to XAWJ1 do
begin
Inc(R, RGB32S^.R);
Inc(G, RGB32S^.G);
Inc(B, RGB32S^.B);
Inc(L, RGB32S^.L);
Inc(RGB32S);
end;
end;
if Count <> 0 then
begin
P32[J].R := R div Count;
P32[J].G := G div Count;
P32[J].B := B div Count;
P32[J].L := L div Count;
end;
end;
end;
end;
end;
procedure QuickReduceWide(Width, Height : integer; S,D : TBitmap);
begin
if (Width = 0) or (Height = 0) then
Exit;
if ((S.Width div Width >= 8) or (S.Height div Height >= 8)) and (S.Width > 2) and (S.Height > 2) then
QuickReduce(Width,Height, S, D)
else
StretchCool(Width,Height, S, D)
end;
procedure DrawColorMaskTo32Bit(Dest, Mask: TBitmap; Color: TColor; X, Y: Integer);
var
I, J,
XD, YD,
DH, DW,
SH, SW: Integer;
pS: PARGB;
pD: PARGB32;
R, G, B, W, W1: Byte;
begin
Dest.PixelFormat := pf32bit;
Mask.PixelFormat := pf24bit;
Color := ColorToRGB(Color);
R := GetRValue(Color);
G := GetGValue(Color);
B := GetBValue(Color);
DH := Dest.Height;
DW := Dest.Width;
SH := Mask.Height;
SW := Mask.Width;
for I := 0 to SH - 1 do
begin
YD := I + Y;
if (YD >= DH) then
Break;
pS := Mask.ScanLine[I];
pD := Dest.ScanLine[YD];
for J := 0 to SW - 1 do
begin
XD := J + X;
if (XD >= DW) then
Break;
W1 := (pS[J].R * 77 + pS[J].G * 151 + pS[J].B * 28) shr 8;
W := 255 - W1;
pD[XD].R := (R * W + pD[XD].R * W1 + $7F) div $FF;
pD[XD].G := (G * W + pD[XD].G * W1 + $7F) div $FF;
pD[XD].B := (B * W + pD[XD].B * W1 + $7F) div $FF;
pD[XD].L := ($FF * W + pD[XD].L * W1 + $7F) div $FF;
end;
end;
end;
procedure DrawImageEx24To32(Dest32, Src24 : TBitmap; X, Y : Integer; NewTransparent: Byte = 0);
var
I, J,
XD, YD,
DH, DW,
SH, SW: Integer;
pS: PARGB;
pD: PARGB32;
begin
DH := Dest32.Height;
DW := Dest32.Width;
SH := Src24.Height;
SW := Src24.Width;
for I := 0 to SH - 1 do
begin
YD := I + Y;
if (YD >= DH) then
Break;
pS := Src24.ScanLine[I];
pD := Dest32.ScanLine[YD];
for J := 0 to SW - 1 do
begin
XD := J + X;
if (XD >= DW) then
Break;
pD[XD].R := pS[J].R;
pD[XD].G := pS[J].G;
pD[XD].B := pS[J].B;
pD[XD].L := NewTransparent;
end;
end;
end;
procedure DrawImageEx32To32(Dest32, Src32: TBitmap; X, Y: Integer);
var
I, J,
XD, YD,
DH, DW,
SH, SW: Integer;
pS,
pD: PARGB32;
begin
DH := Dest32.Height;
DW := Dest32.Width;
SH := Src32.Height;
SW := Src32.Width;
for I := 0 to SH - 1 do
begin
YD := I + Y;
if (YD >= DH) then
Break;
pS := Src32.ScanLine[I];
pD := Dest32.ScanLine[YD];
for J := 0 to SW - 1 do
begin
XD := J + X;
if (XD >= DW) then
Break;
pD[XD].R := pS[J].R;
pD[XD].G := pS[J].G;
pD[XD].B := pS[J].B;
pD[XD].L := pS[J].L;
end;
end;
end;
procedure MixWithColor(Bitmap: TBitmap; MixTransparencity: Byte; Color: TColor; ExceptRect: TRect);
var
I, J,
BW, BH: Integer;
P: PARGB;
W, W1: Byte;
R, G, B: Byte;
begin
BW := Bitmap.Width;
BH := Bitmap.Height;
Color := ColorToRGB(Color);
R := GetRValue(Color);
G := GetGValue(Color);
B := GetBValue(Color);
W := MixTransparencity;
W1 := 255 - MixTransparencity;
for I := 0 to BH - 1 do
begin
P := Bitmap.ScanLine[I];
for J := 0 to BW - 1 do
begin
if not PtInRect(ExceptRect, Point(J, I)) then
begin
P[J].R := (P[J].R * W1 + R * W + $7F) div $FF;
P[J].G := (P[J].G * W1 + G * W + $7F) div $FF;
P[J].B := (P[J].B * W1 + B * W + $7F) div $FF;
end;
end;
end;
end;
procedure DrawImageEx32To24(Dest24, Src32: TBitmap; X, Y: Integer);
var
I, J,
XD, YD,
DH, DW,
SH, SW: Integer;
W1, W: Byte;
pD: PARGB;
pS: PARGB32;
begin
DH := Dest24.Height;
DW := Dest24.Width;
SH := Src32.Height;
SW := Src32.Width;
for I := 0 to SH - 1 do
begin
YD := I + Y;
if (YD >= DH) then
Break;
pS := Src32.ScanLine[I];
pD := Dest24.ScanLine[YD];
for J := 0 to SW - 1 do
begin
XD := J + X;
if (XD >= DW) then
Break;
W := pS[J].L;
W1 := 255 - W;
pD[XD].R := (pD[XD].R * W1 + pS[J].R * W + $7F) div $FF;
pD[XD].G := (pD[XD].G * W1 + pS[J].G * W + $7F) div $FF;
pD[XD].B := (pD[XD].B * W1 + pS[J].B * W + $7F) div $FF;
end;
end;
end;
procedure DrawImageEx32To24Transparency(Dest24, Src32: TBitmap; X, Y: Integer; Transparency: Byte);
var
I, J,
XD, YD,
DH, DW,
SH, SW: Integer;
W1, W: Byte;
pD: PARGB;
pS: PARGB32;
begin
DH := Dest24.Height;
DW := Dest24.Width;
SH := Src32.Height;
SW := Src32.Width;
for I := 0 to SH - 1 do
begin
YD := I + Y;
if (YD >= DH) then
Break;
pS := Src32.ScanLine[I];
pD := Dest24.ScanLine[YD];
for J := 0 to SW - 1 do
begin
XD := J + X;
if (XD >= DW) then
Break;
W := pS[J].L * Transparency div $FF;
W1 := 255 - W;
pD[XD].R := (pD[XD].R * W1 + pS[J].R * W + $7F) div $FF;
pD[XD].G := (pD[XD].G * W1 + pS[J].G * W + $7F) div $FF;
pD[XD].B := (pD[XD].B * W1 + pS[J].B * W + $7F) div $FF;
end;
end;
end;
procedure DrawImageEx32(Dest32, Src32: TBitmap; X, Y: Integer);
var
I, J,
XD, YD,
DH, DW,
SH, SW: Integer;
W1, W: Byte;
pD, pS: PARGB32;
begin
DH := Dest32.Height;
DW := Dest32.Width;
SH := Src32.Height;
SW := Src32.Width;
InitSumLMatrix;
for I := 0 to SH - 1 do
begin
YD := I + Y;
if (YD >= DH) then
Break;
pS := Src32.ScanLine[I];
pD := Dest32.ScanLine[YD];
for J := 0 to SW - 1 do
begin
XD := J + X;
if (XD >= DW) then
Break;
W := pS[J].L;
W1 := 255 - W;
pD[XD].R := (pD[XD].R * W1 + pS[J].R * W + $7F) div $FF;
pD[XD].G := (pD[XD].G * W1 + pS[J].G * W + $7F) div $FF;
pD[XD].B := (pD[XD].B * W1 + pS[J].B * W + $7F) div $FF;
pD[XD].L := SumLMatrix[pD[XD].L, W];
end;
end;
end;
procedure DrawImageEx(Dest, Src: TBitmap; X, Y: Integer);
var
I, J,
XD, YD,
DH, DW,
SH, SW: Integer;
pS: PARGB;
pD: PARGB;
begin
DH := Dest.Height;
DW := Dest.Width;
SH := Src.Height;
SW := Src.Width;
for I := 0 to SH - 1 do
begin
YD := I + Y;
if (YD >= DH) then
Break;
pS := Src.ScanLine[I];
pD := Dest.ScanLine[YD];
for J := 0 to SW - 1 do
begin
XD := J + X;
if (XD >= DW) then
Break;
pD[XD] := pS[J];
end;
end;
end;
procedure DrawImageExTransparency(Dest, Src: TBitmap; X, Y: Integer; Transparency: Byte);
var
I, J,
XD, YD,
DH, DW,
SH, SW: Integer;
W, W1: Byte;
pS: PARGB;
pD: PARGB;
begin
DH := Dest.Height;
DW := Dest.Width;
SH := Src.Height;
SW := Src.Width;
W := Transparency;
W1 := 255 - W;
for I := 0 to SH - 1 do
begin
YD := I + Y;
if (YD >= DH) then
Break;
pS := Src.ScanLine[I];
pD := Dest.ScanLine[YD];
for J := 0 to SW - 1 do
begin
XD := J + X;
if (XD >= DW) then
Break;
pD[XD].R := (pD[XD].R * W1 + pS[J].R * W) div $FF;
pD[XD].G := (pD[XD].G * W1 + pS[J].G * W) div $FF;
pD[XD].B := (pD[XD].B * W1 + pS[J].B * W) div $FF;
end;
end;
end;
procedure DrawImageExRect(Dest, Src: TBitmap; SX, SY, SW, SH: Integer; DX, DY: Integer);
var
I, J,
XD, YD, YS, XS,
DHeight, DWidth, SHeight, SWidth : integer;
pS: PARGB;
pD: PARGB;
begin
DHeight := Dest.Height;
DWidth := Dest.Width;
SHeight := Src.Height;
SWidth := Src.Width;
for I := 0 to SH - 1 do
begin
YD := I + DY;
if (YD >= DHeight) then
Break;
YS := I + SY;
if (YD >= SHeight) then
Break;
pS := Src.ScanLine[YS];
pD := Dest.ScanLine[YD];
for J := 0 to SW - 1 do
begin
XD := J + DX;
if (XD >= DWidth) then
Break;
XS := J + SX;
if (XS >= SWidth) then
Break;
pD[XD] := pS[XS];
end;
end;
end;
procedure FillTransparentChannel(Bitmap: TBitmap; TransparentValue: Byte);
var
I, J: Integer;
p: PARGB32;
begin
Bitmap.PixelFormat := pf32Bit;
for I := 0 to Bitmap.Height - 1 do
begin
p := Bitmap.ScanLine[I];
for J := 0 to Bitmap.Width - 1 do
p[J].L := TransparentValue;
end;
end;
procedure DrawTransparentColor(Bitmap: TBitmap; Color: TColor; X, Y, Width, Height: Integer; TransparentValue: Byte = 0);
var
I, J: Integer;
p: PARGB;
R, G, B: Byte;
W, W1: Byte;
RM, GM, BM: array[0..255] of byte;
begin
Bitmap.PixelFormat := pf24Bit;
Color := ColorToRGB(Color);
R := GetRValue(Color);
G := GetGValue(Color);
B := GetBValue(Color);
W := TransparentValue;
W1 := 255 - W;
for I := 0 to 255 do
begin
RM[I] := (I * W1 + R * W + $7F) div $FF;
GM[I] := (I * W1 + G * W + $7F) div $FF;
BM[I] := (I * W1 + B * W + $7F) div $FF;
end;
for I := Max(0, Y) to Min(Y + Height - 1, Bitmap.Height - 1) do
begin
P := Bitmap.ScanLine[I];
for J := Max(0, X) to Min(X + Width - 1, Bitmap.Width - 1) do
begin
P[J].R := RM[P[J].R];
P[J].G := GM[P[J].G];
P[J].B := BM[P[J].B];
end;
end;
end;
procedure DrawTransparentColorGradient(Bitmap: TBitmap; Color: TColor; X, Y, Width, Height: Integer; TransparentValueFrom, TransparentValueTo: Byte);
var
I, J: Integer;
p: PARGB;
R, G, B: Byte;
W, W1: Byte;
TDArray: array of byte;
function Sqr(Value: Extended): Extended;
begin
Result := Value * Value;
end;
begin
Bitmap.PixelFormat := pf24Bit;
Color := ColorToRGB(Color);
R := GetRValue(Color);
G := GetGValue(Color);
B := GetBValue(Color);
SetLength(TDArray, Width);
for I := 0 to Width - 1 do
TDArray[I] := Round(TransparentValueFrom + (TransparentValueTo - TransparentValueFrom) * Sqr(I / Width));
for I := Max(0, Y) to Min(Y + Height - 1, Bitmap.Height - 1) do
begin
P := Bitmap.ScanLine[I];
for J := Max(0, X) to Min(X + Width - 1, Bitmap.Width - 1) do
begin
W := TDArray[J - X];
W1 := 255 - W;
P[J].R := (P[J].R * W1 + R * W + $7F) div $FF;
P[J].G := (P[J].G * W1 + G * W + $7F) div $FF;
P[J].B := (P[J].B * W1 + B * W + $7F) div $FF;
end;
end;
end;
procedure FillTransparentColor(Bitmap: TBitmap; Color: TColor; X, Y, Width, Height: Integer; TransparentValue: Byte = 0);
var
I, J: Integer;
P: PARGB32;
R, G, B: Byte;
Value: Integer;
begin
Bitmap.PixelFormat := pf32Bit;
Color := ColorToRGB(Color);
R := GetRValue(Color);
G := GetGValue(Color);
B := GetBValue(Color);
TRGB32(Value).R := R;
TRGB32(Value).G := G;
TRGB32(Value).B := B;
TRGB32(Value).L := TransparentValue;
for I := Max(0, Y) to Min(Y + Height - 1, Bitmap.Height - 1) do
begin
P := Bitmap.ScanLine[I];
for J := Max(0, X) to Min(X + Width - 1, Bitmap.Width - 1) do
Integer(P[J]) := Value;
end;
end;
procedure FillTransparentColor(Bitmap: TBitmap; Color: TColor; TransparentValue: Byte = 0);
var
I, J: Integer;
P: PARGB32;
R, G, B: Byte;
Value: Integer;
begin
Bitmap.PixelFormat := pf32Bit;
Color := ColorToRGB(Color);
R := GetRValue(Color);
G := GetGValue(Color);
B := GetBValue(Color);
TRGB32(Value).R := R;
TRGB32(Value).G := G;
TRGB32(Value).B := B;
TRGB32(Value).L := TransparentValue;
for I := 0 to Bitmap.Height - 1 do
begin
P := Bitmap.ScanLine[I];
for J := 0 to Bitmap.Width - 1 do
Integer(P[J]) := Value;
end;
end;
procedure FillColorEx(Bitmap: TBitmap; Color: TColor);
var
I, J: Integer;
p: PARGB;
RGB: TRGB;
begin
Bitmap.PixelFormat := pf24Bit;
Color := ColorToRGB(Color);
RGB.R := GetRValue(Color);
RGB.G := GetGValue(Color);
RGB.B := GetBValue(Color);
if Bitmap.PixelFormat = pf24bit then
begin
for I := 0 to Bitmap.Height - 1 do
begin
P := Bitmap.ScanLine[I];
for J := 0 to Bitmap.Width - 1 do
P[J] := RGB;
end;
end;
end;
procedure LoadBMPImage32bit(S: TBitmap; D: TBitmap; BackGroundColor: TColor);
var
I, J, W1, W2: integer;
PD : PARGB;
PS : PARGB32;
R, G, B : byte;
begin
if S.PixelFormat = pf24Bit then
begin
AssignBitmap(D, S);
Exit;
end;
BackGroundColor := ColorToRGB(BackGroundColor);
R := GetRValue(BackGroundColor);
G := GetGValue(BackGroundColor);
B := GetBValue(BackGroundColor);
if D.PixelFormat <> pf24bit then
D.PixelFormat := pf24bit;
D.SetSize(S.Width, S.Height);
for I := 0 to S.Height - 1 do
begin
PD := D.ScanLine[I];
PS := S.ScanLine[I];
for J := 0 to S.Width - 1 do
begin
W1 := PS[J].L;
W2 := 255 - W1;
PD[J].R := (R * W2 + PS[J].R * W1 + $7F) div $FF;
PD[J].G := (G * W2 + PS[J].G * W1 + $7F) div $FF;
PD[J].B := (B * W2 + PS[J].B * W1 + $7F) div $FF;
end;
end;
end;
procedure GrayScale(Image: TBitmap);
var
I, J, C: Integer;
P: PARGB;
begin
Image.PixelFormat := pf24bit;
for I := 0 to Image.Height - 1 do
begin
p := Image.ScanLine[I];
for J := 0 to Image.Width - 1 do
begin
C := (p[J].R * 77 + p[J].G * 151 + p[J].B * 28) shr 8;
p[J].R := C;
p[J].G := C;
p[J].B := C;
end;
end;
end;
procedure GrayScaleImage(S, D: TBitmap; N: Integer);
var
I, J: Integer;
P1, P2: Pargb;
G: Byte;
W1, W2: Byte;
begin
W1 := Round((N / 100) * 255);
W2 := 255 - W1;
for I := 0 to S.Height - 1 do
begin
P1 := S.ScanLine[I];
P2 := D.ScanLine[I];
for J := 0 to S.Width - 1 do
begin
G := (P1[J].R * 77 + P1[J].G * 151 + P1[J].B * 28) shr 8;
P2[J].R := (W2 * P2[J].R + W1 * G) shr 8;
P2[J].G := (W2 * P2[J].G + W1 * G) shr 8;
P2[J].B := (W2 * P2[J].B + W1 * G) shr 8;
end;
end;
end;
procedure DrawTransparent(S, D: TBitmap; Transparent: Byte);
var
W1, W2, I, J: Integer;
PS, PD: PARGB;
begin
W1 := Transparent;
W2 := 255 - W1;
for I := 0 to S.Height - 1 do
begin
PS := S.ScanLine[I];
pd := D.ScanLine[I];
for J := 0 to S.Width - 1 do
begin
PD[J].R := (PD[J].R * W2 + PS[J].R * W1 + $7F) div $FF;
PD[J].G := (PD[J].G * W2 + PS[J].G * W1 + $7F) div $FF;
PD[J].B := (PD[J].B * W2 + PS[J].B * W1 + $7F) div $FF;
end;
end;
end;
procedure DrawRoundGradientVert(Dest: TBitmap; Rect: TRect; ColorFrom, ColorTo, BorderColor: TColor;
RoundRect: Integer; TransparentValue: Byte = 220);
var
BitRound: TBitmap;
PR, PD24: PARGB;
PD32: PARGB32;
I, J: Integer;
RF, GF, BF, RT, GT, BT, R, G, B, W, W1: Byte;
RB, GB, BB: Byte;
S: Integer;
begin
ColorFrom := ColorToRGB(ColorFrom);
ColorTo := ColorToRGB(ColorTo);
BorderColor := ColorToRGB(BorderColor);
RF := GetRValue(ColorFrom);
GF := GetGValue(ColorFrom);
BF := GetBValue(ColorFrom);
RT := GetRValue(ColorTo);
GT := GetGValue(ColorTo);
BT := GetBValue(ColorTo);
RB := GetRValue(BorderColor);
GB := GetGValue(BorderColor);
BB := GetBValue(BorderColor);
if BB = 255 then
BB := 254;
BorderColor := RGB(RB, GB, BB);
BitRound := TBitmap.Create;
try
BitRound.PixelFormat := pf24Bit;
BitRound.SetSize(Dest.Width, Dest.Height);
BitRound.Canvas.Brush.Color := clWhite;
BitRound.Canvas.Pen.Color := clWhite;
BitRound.Canvas.Rectangle(0, 0, Dest.Width, Dest.Height);
BitRound.Canvas.Brush.Color := clBlack;
BitRound.Canvas.Pen.Color := BorderColor;
Winapi.Windows.RoundRect(BitRound.Canvas.Handle, Rect.Left, Rect.Top, Rect.Right, Rect.Bottom, RoundRect, RoundRect);
if Dest.PixelFormat = pf32Bit then
begin
for I := 0 to Dest.Height - 1 do
begin
PR := BitRound.ScanLine[I];
PD32 := Dest.ScanLine[I];
if (Rect.Top > I) or (I > Rect.Bottom) then
Continue;
W := Round(255 * (I + 1 - Rect.Top) / (Rect.Bottom - Rect.Top));
W1 := 255 - W;
R := (RF * W + RT * W1 + $7F) div 255;
G := (GF * W + GT * W1 + $7F) div 255;
B := (BF * W + BT * W1 + $7F) div 255;
for J := 0 to Dest.Width - 1 do
begin
S := (PR[J].R + PR[J].G + PR[J].B);
if S <> 765 then //White
begin
PD32[J].L := TransparentValue;
//black - gradient
if S = 0 then
begin
PD32[J].R := R;
PD32[J].G := G;
PD32[J].B := B;
end else //border
begin
PD32[J].R := RB;
PD32[J].G := GB;
PD32[J].B := BB;
end;
end;
end;
end;
end else
begin
Dest.PixelFormat := pf24Bit;
for I := 0 to Dest.Height - 1 do
begin
PR := BitRound.ScanLine[I];
PD24 := Dest.ScanLine[I];
if (Rect.Top > I) or (I > Rect.Bottom) then
Continue;
W := Round(255 * (I + 1 - Rect.Top) / (Rect.Bottom - Rect.Top));
W1 := 255 - W;
R := (RF * W + RT * W1 + $7F) div 255;
G := (GF * W + GT * W1 + $7F) div 255;
B := (BF * W + BT * W1 + $7F) div 255;
for J := 0 to Dest.Width - 1 do
begin
S := (PR[J].R + PR[J].G + PR[J].B);
if S <> 765 then //White
begin
W1 := TransparentValue;
W := 255 - W1;
//black - gradient
if S = 0 then
begin
PD24[J].R := (PD24[J].R * W + R * W1 + $7F) div $FF;
PD24[J].G := (PD24[J].G * W + G * W1 + $7F) div $FF;
PD24[J].B := (PD24[J].B * W + B * W1 + $7F) div $FF;
end else //border
begin
PD24[J].R := (PD24[J].R * W + RB * W1 + $7F) div $FF;
PD24[J].G := (PD24[J].G * W + GB * W1 + $7F) div $FF;
PD24[J].B := (PD24[J].B * W + BB * W1 + $7F) div $FF;
end;
end;
end;
end;
end;
finally
F(BitRound);
end;
end;
{$OVERFLOWCHECKS OFF}
procedure DrawShadowToImage(Dest32, Src: TBitmap; Transparenty: Byte = 0);
var
I, J: Integer;
PS: PARGB;
PS32: PARGB32;
PDA: array of PARGB32;
SH, SW: Integer;
AddrLineD, DeltaD, AddrD, AddrS: NativeInt;
PD: PRGB32;
W, W1: Byte;
const
SHADOW: array[0..6, 0..6] of byte =
((8,14,22,26,22,14,8),
(14,0,0,0,52,28,14),
(22,0,0,0,94,52,22),
(26,0,0,0,124,66,26),
(22,52,94,{124}94,94,52,22),
(14,28,52,66,52,28,14),
(8,14,22,26,22,14,8));
begin
//set new image size
Dest32.PixelFormat := pf32Bit;
if Src = nil then
Exit;
SW := Src.Width;
SH := Src.Height;
Dest32.SetSize(SW + 4, SH + 4);
SetLength(PDA, Dest32.Height);
AddrLineD := NativeInt(Dest32.ScanLine[0]);
DeltaD := 0;
if Dest32.Height > 1 then
DeltaD := NativeInt(Dest32.ScanLine[1])- AddrLineD;
//buffer scanlines
for I := 0 to Dest32.Height - 1 do
PDA[I] := Dest32.ScanLine[I];
//min size of shadow - 5x5 px
//top-left
for I := 0 to 2 do
for J := 0 to 2 do
begin
PDA[I][J].R := 0;
PDA[I][J].G := 0;
PDA[I][J].B := 0;
PDA[I][J].L := SHADOW[I, J];
end;
//top-bottom
for I := 3 to Src.Height do
begin
PDA[I][0].R := 0;
PDA[I][0].G := 0;
PDA[I][0].B := 0;
PDA[I][0].L := SHADOW[3, 0];
for J := 0 to 2 do
begin
PDA[I][J + SW + 1].R := 0;
PDA[I][J + SW + 1].G := 0;
PDA[I][J + SW + 1].B := 0;
PDA[I][J + SW + 1].L := SHADOW[4, 2 - J];
end;
end;
//left-right
for I := 3 to Src.Width do
begin
PDA[0][I].R := 0;
PDA[0][I].G := 0;
PDA[0][I].B := 0;
PDA[0][I].L := SHADOW[0, 3];
for J := 0 to 2 do
begin
PDA[J + SH + 1][I].R := 0;
PDA[J + SH + 1][I].G := 0;
PDA[J + SH + 1][I].B := 0;
PDA[J + SH + 1][I].L := SHADOW[4, 2 - J];
end;
end;
//left-bottom
for I := 0 to 2 do
for J := 0 to 2 do
begin
PDA[I + SH + 1][J].R := 0;
PDA[I + SH + 1][J].G := 0;
PDA[I + SH + 1][J].B := 0;
PDA[I + SH + 1][J].L := SHADOW[I + 4, J];
end;
//top-right
for I := 0 to 2 do
for J := 0 to 2 do
begin
PDA[I][J + SW + 1].R := 0;
PDA[I][J + SW + 1].G := 0;
PDA[I][J + SW + 1].B := 0;
PDA[I][J + SW + 1].L := SHADOW[I, J + 4];
end;
//bottom-right
for I := 0 to 2 do
for J := 0 to 2 do
begin
PDA[I + SH + 1][J + SW + 1].R := 0;
PDA[I + SH + 1][J + SW + 1].G := 0;
PDA[I + SH + 1][J + SW + 1].B := 0;
PDA[I + SH + 1][J + SW + 1].L := SHADOW[I + 4, J + 4];
end;
//and draw image
if Src.PixelFormat <> pf32bit then
begin
Src.PixelFormat := pf24bit;
AddrLineD := AddrLineD + DeltaD;
for I := 0 to Src.Height - 1 do
begin
PS := Src.ScanLine[I];
AddrD := AddrLineD + 4; //from second fixel
AddrS := NativeInt(PS);
for J := 0 to Src.Width - 1 do
begin
PRGB32(AddrD).R := PRGB(AddrS).R;
PRGB32(AddrD).G := PRGB(AddrS).G;
PRGB32(AddrD).B := PRGB(AddrS).B;
PRGB32(AddrD).L := 255;
Inc(AddrD, 4);
Inc(AddrS, 3);
end;
AddrLineD := AddrLineD + DeltaD;
end;
end else
begin
AddrLineD := AddrLineD + DeltaD;
for I := 0 to Src.Height - 1 do
begin
PS32 := Src.ScanLine[I];
AddrD := AddrLineD + 4; //from second fixel
for J := 0 to Src.Width - 1 do
begin
PD := PRGB32(AddrD);
W := PS32[J].L;
W1 := 255 - W;
PD.R := (PD.R * W1 + PS32[J].R * W + $7F) div $FF;
PD.G := (PD.G * W1 + PS32[J].G * W + $7F) div $FF;
PD.B := (PD.B * W1 + PS32[J].B * W + $7F) div $FF;
PD.L := W;
AddrD := AddrD + 4;
end;
AddrLineD := AddrLineD + DeltaD;
end;
end;
end;
{$OVERFLOWCHECKS ON}
procedure DrawText32Bit(Bitmap32: TBitmap; Text: string; Font: TFont; ARect: TRect; DrawTextOptions: Cardinal);
var
Bitmap: TBitmap;
R: TRect;
begin
Bitmap32.PixelFormat := pf32bit;
Bitmap := TBitmap.Create;
try
Bitmap.PixelFormat := pf24Bit;
Bitmap.Canvas.Font.Assign(Font);
Bitmap.Canvas.Font.Color := clBlack;
Bitmap.Canvas.Brush.Color := clWhite;
Bitmap.Canvas.Pen.Color := clWhite;
Bitmap.Width := ARect.Right - ARect.Left;
Bitmap.Height := ARect.Bottom - ARect.Top;
R := Rect(0, 0, Bitmap.Width, Bitmap.Height);
DrawText(Bitmap.Canvas.Handle, PWideChar(Text), Length(Text), R, DrawTextOptions);
DrawColorMaskTo32Bit(Bitmap32, Bitmap, Font.Color, ARect.Left, ARect.Top);
finally
F(Bitmap);
end;
end;
{$OVERFLOWCHECKS OFF}
procedure SmoothResize(Width, Height: integer; S, D: TBitmap; CallBack: TProgressCallBackProc = nil);
type
TRGBArray = array[Word] of TRGBTriple;
PRGBTriple = ^TRGBTriple;
pRGBArray = ^TRGBArray;
var
X, Y: Integer;
XP, YP: Integer;
Mx, My: Integer;
SrcLine1, SrcLine2: PRGBArray;
SrcLine132, SrcLine232: PARGB32;
T3: Integer;
Z, Z2, Iz2: Cardinal;
DstLine: PRGBArray;
DstLine32: PARGB32;
DstGap: Integer;
W1, W2, W3, W4, DW1, SW1: Integer;
Terminating: Boolean;
DLinePixel: NativeInt;
begin
Terminating := false;
if not ((S.PixelFormat = pf32Bit) and (D.PixelFormat = pf32Bit)) then
begin
S.PixelFormat := pf24Bit;
D.PixelFormat := pf24Bit;
end;
if Width * Height=0 then
begin
AssignBitmap(D, S);
Exit;
end;
D.SetSize(Width, Height);
if (S.Width = D.Width) and (S.Height = D.Height) then
AssignBitmap(D, S)
else
begin
DstLine := D.ScanLine[0];
DstLine32 := PARGB32(DstLine);
DstGap := 0;
if D.Height > 1 then
DstGap := NativeInt(D.ScanLine[1]) - NativeInt(DstLine);
Mx := MulDiv(S.Width, $10000, D.Width);
My := MulDiv(S.Height, $10000, D.Height);
yP := 0;
DW1 := D.Width - 1;
SW1 := S.Width - 1;
if S.PixelFormat = pf32Bit then
begin
for y := 0 to pred(D.Height) do
begin
xP := 0;
SrcLine132 := S.ScanLine[yP shr 16];
if (yP shr 16 < pred(S.Height))and(Y <> D.Height-1) then
SrcLine232 := S.ScanLine[succ(yP shr 16)]
else
begin
SrcLine132 := S.ScanLine[S.Height - 2];
SrcLine232 := S.ScanLine[S.Height - 1];
end;
z2 := succ(yP and $FFFF);
iz2 := succ((not yp) and $FFFF);
for x := 0 to pred(D.Width) do
begin
t3 := xP shr 16;
z := xP and $FFFF;
w2 := (z * iz2) div $10000; //MulDiv(z, iz2, $10000);
w4 := (z * z2) div $10000; //MulDiv(z, z2, $10000);
w1 := Integer(iz2) - w2;
w3 := Integer(z2) - w4;
if (t3 >= SW1) or (x = DW1) then
t3 := SW1 - 1;
DstLine32[x].R := (SrcLine132[t3].R * w1 + SrcLine132[t3 + 1].R * w2 +
SrcLine232[t3].R * w3 + SrcLine232[t3 + 1].R * w4) shr 16;
DstLine32[x].G := (SrcLine132[t3].G * w1 + SrcLine132[t3 + 1].G * w2 +
SrcLine232[t3].G * w3 + SrcLine232[t3 + 1].G * w4) shr 16;
DstLine32[x].B := (SrcLine132[t3].B * w1 + SrcLine132[t3 + 1].B * w2 +
SrcLine232[t3].B * w3 + SrcLine232[t3 + 1].B * w4) shr 16;
DstLine32[x].L := (SrcLine132[t3].L * w1 + SrcLine132[t3 + 1].L * w2 +
SrcLine232[t3].L * w3 + SrcLine232[t3 + 1].L * w4) shr 16;
Inc(xP, Mx);
end; {for}
Inc(yP, My);
DstLine32 := PARGB32(NativeInt(DstLine32) + DstGap);
if y mod 50 = 0 then
if Assigned(CallBack) then CallBack(Round(100* Y / D.Height), Terminating);
if Terminating then Break;
end; {for}
end else
begin
for y := 0 to pred(D.Height) do
begin
xP := 0;
SrcLine1 := S.ScanLine[yP shr 16];
if (yP shr 16 < pred(S.Height))and(Y<>D.Height-1) then
SrcLine2 := S.ScanLine[succ(yP shr 16)]
else
begin
SrcLine1 := S.ScanLine[S.Height - 2];
SrcLine2 := S.ScanLine[S.Height - 1];
end;
z2 := succ(yP and $FFFF);
iz2 := succ((not yp) and $FFFF);
DLinePixel := NativeInt(DstLine);
for x := 0 to DW1 do
begin
t3 := xP shr 16;
z := xP and $FFFF;
w2 := (z * iz2) div $10000; //MulDiv(z, iz2, $10000);
w4 := (z * z2) div $10000; //MulDiv(z, z2, $10000);
w1 := Integer(iz2) - w2;
w3 := Integer(z2) - w4;
if (t3 >= SW1) or (x = DW1) then
t3 := SW1 - 1;
PRGBTriple(DLinePixel)^.rgbtRed := (SrcLine1[t3].rgbtRed * w1 + SrcLine1[t3 + 1].rgbtRed * w2 +
SrcLine2[t3].rgbtRed * w3 + SrcLine2[t3 + 1].rgbtRed * w4) shr 16;
PRGBTriple(DLinePixel)^.rgbtGreen := (SrcLine1[t3].rgbtGreen * w1 + SrcLine1[t3 + 1].rgbtGreen * w2 +
SrcLine2[t3].rgbtGreen * w3 + SrcLine2[t3 + 1].rgbtGreen * w4) shr 16;
PRGBTriple(DLinePixel)^.rgbtBlue := (SrcLine1[t3].rgbtBlue * w1 + SrcLine1[t3 + 1].rgbtBlue * w2 +
SrcLine2[t3].rgbtBlue * w3 + SrcLine2[t3 + 1].rgbtBlue * w4) shr 16;
Inc(DLinePixel, 3);
Inc(xP, Mx);
end; {for}
Inc(yP, My);
DstLine := pRGBArray(NativeInt(DstLine) + DstGap);
if y mod 50=0 then
If Assigned(CallBack) then CallBack(Round(100*y/D.Height),Terminating);
if Terminating then Break;
end; {for}
end;
end; {if}
end; {SmoothResize}
{$OVERFLOWCHECKS ON}
procedure StretchCool(Width, Height: integer; S,D: TBitmap; CallBack: TProgressCallBackProc);
var
I, J, K, P: Integer;
P1: PARGB;
Col, R, G, B, Sheight1, SWidth1: Integer;
Sh, Sw: Extended;
Xp: array of PARGB;
Terminating: Boolean;
YMin, YMax: Integer;
XWA: array of Integer;
begin
if Width = 0 then
Exit;
if Height = 0 then
Exit;
S.PixelFormat := Pf24bit;
D.PixelFormat := Pf24bit;
D.Width := Width;
D.Height := Height;
Sh := S.Height / Height;
Sw := S.Width / Width;
Sheight1 := S.Height - 1;
SWidth1 := S.Width - 1;
SetLength(Xp, S.Height);
for I := 0 to Sheight1 do
Xp[I] := S.ScanLine[I];
Terminating := False;
SetLength(XWA, Width + 1);
for I := 0 to Width do
XWA[I] := Round(Sw * I);
for I := 0 to Height - 1 do
begin
P1 := D.ScanLine[I];
YMin := Round(Sh * I);
YMax := Min(Round(Sh * (I + 1)) - 1, Sheight1);
for J := 0 to Width - 1 do
begin
Col := 0;
R := 0;
G := 0;
B := 0;
for K := YMin to YMax do
begin
for P := XWA[J] to Min(XWA[J + 1] - 1, SWidth1) do
begin
Inc(Col);
Inc(R, Xp[K, P].R);
Inc(G, Xp[K, P].G);
Inc(B, Xp[K, P].B);
end;
end;
if Col <> 0 then
begin
P1[J].R := R div Col;
P1[J].G := G div Col;
P1[J].B := B div Col;
end;
end;
if I mod 50 = 0 then
if Assigned(CallBack) then
CallBack(Round(100 * I / Height), Terminating);
if Terminating then
Break;
end;
end;
procedure Interpolate(X, Y, Width, Height: Integer; Rect: TRect; var S, D: TBitmap; CallBack: TProgressCallBackProc);
var
Z1, Z2: Single;
K: Single;
I, J: Integer;
H, Dw, Dh, Xo, Yo: Integer;
X1r, Y1r: Single;
Xs, Xd: array of PARGB;
Dx, Dy: Single;
Terminating: Boolean;
begin
Terminating := False;
S.PixelFormat := pf24bit;
D.PixelFormat := pf24bit;
D.Width := Max(D.Width, X + Width);
D.Height := Max(D.Height, Y + Height);
Dw := Min(D.Width - X, X + Width);
Dh := Min(D.Height - Y, Y + Height);
Dx := (Width) / (Rect.Right - Rect.Left - 1);
Dy := (Height) / (Rect.Bottom - Rect.Top - 1);
if (Dx < 1) or (Dy < 1) then
Exit;
SetLength(Xs, S.Height);
for I := 0 to S.Height - 1 do
Xs[I] := S.Scanline[I];
SetLength(Xd, D.Height);
for I := 0 to D.Height - 1 do
Xd[I] := D.Scanline[I];
H := Min(Round((Rect.Bottom - Rect.Top - 1) * Dy) - 1, Dh - 1);
for I := 0 to H do
begin
Yo := Trunc(I / Dy) + Rect.Top;
Y1r := Trunc(I / Dy) * Dy;
if Yo + 1 >= S.Height then
Break;
for J := 0 to Min(Round((Rect.Right - Rect.Left - 1) * Dx) - 1, Dw - 1) do
begin
Xo := Trunc(J / Dx) + Rect.Left;
X1r := Trunc(J / Dx) * Dx;
if Xo + 1 >= S.Width then
Continue;
begin
Z1 := ((Xs[Yo, Xo + 1].R - Xs[Yo, Xo].R) / Dx) * (J - X1r) + Xs[Yo, Xo].R;
Z2 := ((Xs[Yo + 1, Xo + 1].R - Xs[Yo + 1, Xo].R) / Dx) * (J - X1r) + Xs[Yo + 1, Xo].R;
K := (Z2 - Z1) / Dy;
Xd[I + Y, J + X].R := Round(I * K + Z1 - Y1r * K);
Z1 := ((Xs[Yo, Xo + 1].G - Xs[Yo, Xo].G) / Dx) * (J - X1r) + Xs[Yo, Xo].G;
Z2 := ((Xs[Yo + 1, Xo + 1].G - Xs[Yo + 1, Xo].G) / Dx) * (J - X1r) + Xs[Yo + 1, Xo].G;
K := (Z2 - Z1) / Dy;
Xd[I + Y, J + X].G := Round(I * K + Z1 - Y1r * K);
Z1 := ((Xs[Yo, Xo + 1].B - Xs[Yo, Xo].B) / Dx) * (J - X1r) + Xs[Yo, Xo].B;
Z2 := ((Xs[Yo + 1, Xo + 1].B - Xs[Yo + 1, Xo].B) / Dx) * (J - X1r) + Xs[Yo + 1, Xo].B;
K := (Z2 - Z1) / Dy;
Xd[I + Y, J + X].B := Round(I * K + Z1 - Y1r * K);
end;
end;
if I mod 50 = 0 then
if Assigned(CallBack) then
CallBack(Round(100 * I / H), Terminating);
if Terminating then
Break;
end;
end;
procedure ThumbnailResize(Width, Height: integer; S,D: TBitmap; CallBack: TProgressCallBackProc = nil);
type
PRGB24 = ^TRGB24;
TRGB24 = packed record
B: Byte;
G: Byte;
R: Byte;
end;
var
X, Y, Ix, Iy: Integer;
X1, X2, X3: Integer;
Xscale, Yscale: Single;
IRed, IGrn, IBlu, IRatio: Longword;
P, C1, C2, C3, C4, C5: TRGB24;
Pt, Pt1: PRGB24;
ISrc, IDst, S1: NativeInt;
I, J, R, G, B, TmpY: Integer;
RowDest, RowSource, RowSourceStart: NativeInt;
W, H: Integer;
Dxmin, Dymin: Integer;
Ny1, Ny2, Ny3: NativeInt;
Dx, Dy: Integer;
LutX, LutY: array of Integer;
Src, Dest: TBitmap;
Terminating: Boolean;
begin
W := Width;
H := Height;
Pointer(Src) := Pointer(S);
Pointer(Dest) := Pointer(D);
Terminating := False;
if Src.PixelFormat <> Pf24bit then
Src.PixelFormat := Pf24bit;
if Dest.PixelFormat <> Pf24bit then
Dest.PixelFormat := Pf24bit;
Dest.Width := Width;
Dest.Height := Height;
if (Src.Width <= Dest.Width) and (Src.Height <= Dest.Height) then
begin
AssignBitmap(Dest, Src);
Exit;
end;
IDst := (W * 24 + 31) and not 31;
IDst := IDst div 8; // BytesPerScanline
ISrc := (Src.Width * 24 + 31) and not 31;
ISrc := ISrc div 8;
Xscale := 1 / (W / Src.Width);
Yscale := 1 / (H / Src.Height);
// X lookup table
SetLength(LutX, W);
X1 := 0;
X2 := Trunc(Xscale);
for X := 0 to W - 1 do
begin
LutX[X] := X2 - X1;
X1 := X2;
X2 := Trunc((X + 2) * Xscale);
end;
// Y lookup table
SetLength(LutY, H);
X1 := 0;
X2 := Trunc(Yscale);
for X := 0 to H - 1 do
begin
LutY[X] := X2 - X1;
X1 := X2;
X2 := Trunc((X + 2) * Yscale);
end;
Dec(W);
Dec(H);
RowDest := NativeInt(Dest.Scanline[0]);
RowSourceStart := NativeInt(Src.Scanline[0]);
RowSource := RowSourceStart;
for Y := 0 to H do
begin
Dy := LutY[Y];
X1 := 0;
X3 := 0;
for X := 0 to W do
begin
Dx := LutX[X];
IRed := 0;
IGrn := 0;
IBlu := 0;
RowSource := RowSourceStart;
for Iy := 1 to Dy do
begin
Pt := PRGB24(RowSource + X1);
for Ix := 1 to Dx do
begin
IRed := IRed + Pt.R;
IGrn := IGrn + Pt.G;
IBlu := IBlu + Pt.B;
Inc(Pt);
end;
RowSource := RowSource - ISrc;
end;
IRatio := 65535 div (Dx * Dy);
Pt1 := PRGB24(RowDest + X3);
Pt1.R := (IRed * IRatio) shr 16;
Pt1.G := (IGrn * IRatio) shr 16;
Pt1.B := (IBlu * IRatio) shr 16;
X1 := X1 + 3 * Dx;
Inc(X3, 3);
end;
RowDest := RowDest - IDst;
RowSourceStart := RowSource;
end;
if Dest.Height < 3 then
Exit;
// Sharpening...
S1 := NativeInt(Dest.ScanLine[0]);
IDst := 0;
if Dest.Height > 1 then
IDst := NativeInt(Dest.ScanLine[1]) - S1;
Ny1 := S1;
Ny2 := Ny1 + IDst;
Ny3 := Ny2 + IDst;
for Y := 1 to Dest.Height - 2 do
begin
for X := 0 to Dest.Width - 3 do
begin
X1 := X * 3;
X2 := X1 + 3;
X3 := X1 + 6;
C1 := PRGB24(Ny1 + X1)^;
C2 := PRGB24(Ny1 + X3)^;
C3 := PRGB24(Ny2 + X2)^;
C4 := PRGB24(Ny3 + X1)^;
C5 := PRGB24(Ny3 + X3)^;
R := (C1.R + C2.R + (C3.R * -12) + C4.R + C5.R) div -8;
G := (C1.G + C2.G + (C3.G * -12) + C4.G + C5.G) div -8;
B := (C1.B + C2.B + (C3.B * -12) + C4.B + C5.B) div -8;
if R < 0 then
R := 0
else if R > 255 then
R := 255;
if G < 0 then
G := 0
else if G > 255 then
G := 255;
if B < 0 then
B := 0
else if B > 255 then
B := 255;
Pt1 := PRGB24(Ny2 + X2);
Pt1.R := R;
Pt1.G := G;
Pt1.B := B;
end;
Inc(Ny1, IDst);
Inc(Ny2, IDst);
Inc(Ny3, IDst);
if Y mod 50 = 0 then
if Assigned(CallBack) then
CallBack(Round(100 * Y / D.Height), Terminating);
if Terminating then
Break;
end;
end;
procedure KeepProportions(var Bitmap: TBitmap; MaxWidth, MaxHeight: Integer);
var
B: TBitmap;
W, H: Integer;
begin
W := Bitmap.Width;
H := Bitmap.Height;
if (W > MaxWidth) or (H > MaxHeight) then
begin
B := TBitmap.Create;
try
if Bitmap.PixelFormat = pf32bit then
B.PixelFormat := pf32bit;
ProportionalSize(MaxWidth, MaxHeight, W, H);
DoResize(W, H, Bitmap, B);
Exchange(Bitmap, B);
finally
F(B);
end;
end;
end;
procedure ResizeTo(var Bitmap: TBitmap; Width, Height: Integer);
var
B: TBitmap;
begin
B := TBitmap.Create;
try
if Bitmap.PixelFormat = pf32bit then
B.PixelFormat := pf32bit;
DoResize(Width, Height, Bitmap, B);
Exchange(Bitmap, B);
finally
F(B);
end;
end;
procedure CenterBitmap24To32ImageList(var Bitmap: TBitmap; ImageSize: Integer);
var
B: TBitmap;
begin
B := TBitmap.Create;
try
B.PixelFormat := pf32Bit;
B.SetSize(ImageSize, ImageSize);
FillTransparentColor(B, clWhite, 0);
if (Bitmap.Width > ImageSize) or (Bitmap.Height > ImageSize) then
KeepProportions(Bitmap, ImageSize, ImageSize);
DrawImageEx24To32(B, Bitmap, B.Width div 2 - Bitmap.Width div 2, B.Height div 2 - Bitmap.Height div 2, 255);
Exchange(B, Bitmap);
finally
F(B);
end;
end;
{ TBitmapHelper }
function TBitmapHelper.ClientRect: TRect;
begin
Result := Rect(0, 0, Width, Height);
end;
end.
|
unit hacks;
interface
uses Windows, Messages, SysUtils, Classes, ComCtrls, CheckLst, StdCtrls,
clipbrd, AdvGrid, unit_win7TaskBar, ShellAPI, Controls, JvTypes, JvDriveCtrls,
Forms, TB2Item, SpTBXItem, IdHTTP, StrUtils;
type
TVerticalScroll = procedure (var Msg: TWMVScroll) of object;
TAdvStringGrid = class(AdvGrid.TAdvStringGrid)
private
FIsAuto: Boolean;
FOnVScroll: TVerticalScroll;
procedure WMVScroll(var Msg: TWMVScroll); message WM_VSCROLL;
public
procedure AutoSetRow(AValue: Integer);
constructor Create(AOwner: TComponent); override;
procedure SetColumnReadOnly(c: integer; n: Boolean);
published
property IsAutoSelect: Boolean read FIsAuto;
property OnVerticalScroll: TVerticalScroll read FOnVScroll write FOnVScroll;
end;
TCheckListBox = class(CheckLst.TCheckListBox)
public
procedure CheckInverse;
end;
TMyCookieList = class(TStringList)
public
function GetCookieValue(CookieName,CookieDomain: string): string;
function GetCookieByValue(CookieName,CookieDomain: string): string;
procedure DeleteCookie(CookieDomain: String);
end;
TMyIdHTTP = class(TIdCustomHTTP)
private
FCookieList: TMyCookieList;
procedure SetCookieList(Value: TMyCookieList);
protected
procedure DoSetCookies(AURL: String; ARequest: TIdHTTPRequest);
procedure DoProcessCookies(ARequest: TIdHTTPRequest; AResponse: TIdHTTPResponse);
public
{ procedure Get(AURL: string; AResponseContent: TStream;
AIgnoreReplies: array of SmallInt); }
function Get(AURL: string; AResponse: TStream = nil): string;
function Post(AURL: string; ASource: TStrings): string;
procedure ReadCookies(url: string; AResponse: TIdHTTPResponse);
procedure WriteCookies(url: string; ARequest: TIdHTTPRequest);
property CookieList: TMyCookieList read FCookieList write SetCookieList;
end;
TPreventNotifyEvent = procedure(Sender: TObject; var Text: string; var Accept: Boolean) of object;
TMemo = class(StdCtrls.TMemo)
private
{ FPreventCut: Boolean;
FPreventCopy: Boolean;
FPreventPaste: Boolean;
FPreventClear: Boolean; }
{ FOnCut: TPreventNotifyEvent;
FOnCopy: TPreventNotifyEvent; }
FOnPaste: TPreventNotifyEvent;
{ FOnClear: TPreventNotifyEvent; }
{ procedure WMCut(var Message: TWMCUT); message WM_CUT;
procedure WMCopy(var Message: TWMCOPY); message WM_COPY; }
procedure WMPaste(var Message: TWMPASTE); message WM_PASTE;
{ procedure WMClear(var Message: TWMCLEAR); message WM_CLEAR; }
protected
{ Protected declarations }
public
{ Public declarations }
published
{ property PreventCut: Boolean read FPreventCut write FPreventCut default False;
property PreventCopy: Boolean read FPreventCopy write FPreventCopy default False;
property PreventPaste: Boolean read FPreventPaste write FPreventPaste default False;
property PreventClear: Boolean read FPreventClear write FPreventClear default False; }
{ property OnCut: TPreventNotifyEvent read FOnCut write FOnCut;
property OnCopy: TPreventNotifyEvent read FOnCopy write FOnCopy; }
property OnPaste: TPreventNotifyEvent read FOnPaste write FOnPaste;
{ property OnClear: TPreventNotifyEvent read FOnClear write FOnClear; }
end;
TProgressBar = class(ComCtrls.TProgressBar)
private
FMainBar: Boolean;
public
procedure SetMainBar(AValue: Boolean);
procedure SetStyle(Value: TProgressBarStyle);
procedure SetPosition(Value: Integer);
procedure SetState(Value: TProgressBarState);
procedure UpdateStates;
published
property MainBar: Boolean read FMainBar write SetMainBar;
end;
implementation
function CopyFromTo(S, sub1, sub2: String; re: boolean = false): String;
var
l1,l2: integer;
tmp: string;
begin
tmp := s;
result := '';
l1 := pos(LOWERCASE(sub1),LOWERCASE(tmp));
if l1 > 0 then
delete(tmp,1,l1+length(sub1)-1)
else if re then
Exit;
l2 := pos(LOWERCASE(sub2),LOWERCASE(tmp));
if l2 = 0 then
if re then
Exit
else
l2 := length(s) + 1
else
l2 := l2 + length(s) - length(tmp);
if l1 > 0 then
result := Copy(s,l1 + length(sub1),l2 - l1 - length(sub1))
else
result := Copy(s,1,l2 - 1);
end;
function DeleteTo(s: String; subs: string; casesens: boolean = true; re: boolean = false): string;
var
p: integer;
begin
result := s;
if casesens then
begin
p := pos(subs,s);
if p > 0 then
delete(s,1,p+length(subs)-1);
end else
begin
p := pos(UPPERCASE(subs),UPPERCASE(s));
if p > 0 then
delete(s,1,p+length(subs)-1);
end;
if re and (result = s) then
result := ''
else
result := s;
end;
function GetCookieName(Cookie: string): string;
var i: integer;
begin
Result:='';
i:=Pos('=',Cookie);
if i=0 then Exit;
Result:=Copy(Cookie,1,i-1);
end;
function GetCookieDomain(Cookie: string): string;
var i,j: integer;
begin
Result:=''; Cookie := lowercase(Cookie);
i:=Pos('domain=',Cookie);
if i=0 then Exit;
{ j := PosEx('www.',Cookie,i + 1);
if j > 0 then
i := i + 4; }
j:=PosEx(';',Cookie,i);
if j=0 then j:=Length(Cookie)+1;
Result:=Copy(Cookie,i+7,j-i-7);
// Remove dot
{ if (Result<>'') and (Result[1]='.') then
Result:=Copy(Result,2,Length(Result)-1); }
end;
function GetURLDomain(url: string): string;
var i,j,l: integer;
begin
Result:=SysUtils.StringReplace(LowerCase(url),'http://','',[]);
// Result:=SysUtils.StringReplace(Result,'www.','.',[]);
if Pos('www.',Result) = 1 then
i:=PosEx('.',Result,4)
else
i := Pos('.',Result);
if i=0 then Exit;
j:=PosEx('/',Result,i);
if j=0 then j:=PosEx('\',Result,i);
if j>0 then Result:=Copy(Result,1,j-1);
j:=0;
l:=Length(Result);
for i:=1 to l do
if Result[i]='.' then inc(j);
if j>1 then
begin
j:=0;
for i:=l downto 1 do
if Result[i]='.' then
begin
inc(j);
if j=2 then
begin
Result:=Copy(Result,i+1,l-1);
Exit;
end;
end;
end;
end;
function GetCookieValue(Cookie: String): string;
begin
Result:='';
if Pos('=',Cookie) = 0 then Exit;
Result := CopyFromTo(Cookie,'=',';');
end;
//TMemo
{ procedure TMemo.WMCut(var Message: TWMCUT);
var
Accept: Boolean;
Handle: THandle;
HandlePtr: Pointer;
CText: string;
begin
if FPreventCut then
Exit;
if SelLength = 0 then
Exit;
CText := Copy(Text, SelStart + 1, SelLength);
try
OpenClipBoard(Self.Handle);
Accept := True;
if Assigned(FOnCut) then
FOnCut(Self, CText, Accept);
if not Accept then
Exit;
Handle := GlobalAlloc(GMEM_MOVEABLE + GMEM_DDESHARE, Length(CText) + 1);
if Handle = 0 then
Exit;
HandlePtr := GlobalLock(Handle);
Move((PChar(CText))^, HandlePtr^, Length(CText));
SetClipboardData(CF_TEXT, Handle);
GlobalUnlock(Handle);
CText := Text;
Delete(CText, SelStart + 1, SelLength);
Text := CText;
finally
CloseClipBoard;
end;
end;
procedure TMemo.WMCopy(var Message: TWMCOPY);
var
Accept: Boolean;
Handle: THandle;
HandlePtr: Pointer;
CText: string;
begin
if FPreventCopy then
Exit;
if SelLength = 0 then
Exit;
CText := Copy(Text, SelStart + 1, SelLength);
try
OpenClipBoard(Self.Handle);
Accept := True;
if Assigned(FOnCopy) then
FOnCopy(Self, CText, Accept);
if not Accept then
Exit;
Handle := GlobalAlloc(GMEM_MOVEABLE + GMEM_DDESHARE, Length(CText) + 1);
if Handle = 0 then
Exit;
HandlePtr := GlobalLock(Handle);
Move((PChar(CText))^, HandlePtr^, Length(CText));
SetClipboardData(CF_TEXT, Handle);
GlobalUnlock(Handle);
finally
CloseClipBoard;
end;
end; }
procedure TMemo.WMPaste(var Message: TWMPASTE);
var
Accept: Boolean;
CText: string;
LText: string;
begin
CText := clipboard.AsText;
if CText = '' then
Exit;
Accept := True;
LText := Ctext;
if Assigned(FOnPaste) then
FOnPaste(Self, CText, Accept);
if not Accept then
Exit
else if CText <> LText then
SelText := CText
else
inherited;
end;
{ procedure TMemo.WMClear(var Message: TWMCLEAR);
var
Accept: Boolean;
CText: string;
begin
if FPreventClear then
Exit;
if SelStart = 0 then
Exit;
CText := Copy(Text, SelStart + 1, SelLength);
Accept := True;
if Assigned(FOnClear) then
FOnClear(Self, CText, Accept);
if not Accept then
Exit;
CText := Text;
Delete(CText, SelStart + 1, SelLength);
Text := CText;
end; }
//TProgressBar
procedure TProgressBar.SetMainBar(AValue: Boolean);
begin
FMainBar := AValue;
SetPosition(Position);
SetState(State);
end;
procedure TProgressBar.SetStyle(Value: TProgressBarStyle);
const
P: array[TProgressBarState] of TTaskBarProgressState = (tbpsNormal,tbpsError,tbpsPaused);
begin
Style := Value;
case Value of
pbstNormal:
begin
if Position = 0 then
SetTaskbarProgressState(tbpsNone)
else
SetTaskbarProgressState(P[State]);
end;
pbstMarquee:
begin
SetTaskBarProgressValue(0,100);
SetTaskbarProgressState(tbpsIndeterminate);
end;
end;
end;
procedure TProgressBar.SetPosition(Value: Integer);
begin
if Position = Value then
Exit
else
Position := Value;
if FMainBar then
begin
if (WIN32MajorVersion >= 6) then
begin
SetTaskbarProgressValue(Value, Max);
if Value = 0 then
// SetTaskBarProgressValue(0,100);
SetTaskbarProgressState(tbpsNone);
end;
end;
end;
procedure TProgressBar.SetState(Value: TProgressBarState);
//TProgressBarState = (pbsNormal, pbsError, pbsPaused);
const
P: array[TProgressBarState] of TTaskBarProgressState = (tbpsNormal,tbpsError,tbpsPaused);
//(tbpsNone, tbpsIndeterminate, tbpsNormal, tbpsError, tbpsPaused);
begin
State := Value;
if FMainBar then
if (WIN32MajorVersion >= 6) then
if (Value = pbsNormal) and (Style = pbstMarquee) then
SetTaskbarProgressState(tbpsIndeterminate)
else
SetTaskbarProgressState(P[State]);
end;
procedure TProgressBar.UpdateStates;
const
P: array[TProgressBarState] of TTaskBarProgressState = (tbpsNormal,tbpsError,tbpsPaused);
begin
if FMainBar then
if (WIN32MajorVersion >= 6) then
if (Style = pbstMarquee) then
begin
SetTaskBarProgressValue(0,100);
SetTaskbarProgressState(tbpsIndeterminate);
end
else
if Position <> 0 then
begin
SetTaskBarProgressValue(Position,Max);
SetTaskbarProgressState(P[State]);
end;
{ else
SetTaskbarProgressState(tbpsNone);}
end;
//TAdvStringGrid
procedure TAdvStringGrid.WMVScroll(var Msg: TWMVScroll);
begin
inherited;
if Assigned(FOnVScroll) then
FOnVScroll(Msg);
end;
procedure TAdvStringGrid.AutoSetRow(AValue: Integer);
begin
FIsAuto := true;
if Row <>AValue then SetRowEx(AValue);
FIsAuto := false;
end;
constructor TAdvStringGrid.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FOnVScroll := nil;
FIsAuto := false;
end;
procedure TAdvStringGrid.SetColumnReadOnly(c: integer; n: Boolean);
var
i: integer;
begin
for i := FixedRows to RowCount - 1 do
ReadOnly[c,i] := n;
end;
//TCheckListBox
procedure TCheckListBox.CheckInverse;
var
I: Integer;
begin
for I := 0 to Items.Count - 1 do
Checked[i] := not Checked[i];
end;
function TMyCookieList.GetCookieValue(CookieName,CookieDomain: string): string;
var i: integer;
begin
Result := '';
for i := 0 to Self.Count - 1 do
if (GetCookieDomain(Self[i])=CookieDomain)
and (GetCookieName(Self[i])=CookieName) then
begin
Result := hacks.GetCookieValue(Self[i]);
Exit
end;
end;
procedure TMyCookieList.DeleteCookie(CookieDomain: String);
var i: integer;
begin
//Result := '';
CookieDomain := GetURLDomain(CookieDomain);
i := 0;
while i < Self.Count do
if (GetCookieDomain(Self[i])=CookieDomain)
{and (GetCookieName(Self[i])=CookieName)} then
Delete(i)
else
inc(i);
end;
function TMyCookieList.GetCookieByValue(CookieName,CookieDomain: string): string;
var i: integer;
begin
Result := '';
for i := 0 to Self.Count - 1 do
if (GetCookieDomain(Self[i])=CookieDomain)
and (GetCookieName(Self[i])=CookieName) then
begin
Result := Self[i];
Exit
end;
end;
function TMyIdHTTP.Get(AURL: string; AResponse: TStream): string;
begin
{ if Assigned(FCookieList) then
WriteCookies(AURL); }
if AResponse = nil then
Result := inherited Get(AURL)
else
inherited Get(AURL,AResponse);
{ if Assigned(FCookieList) then
ReadCookies(AURL); }
end;
function TMyIdHTTP.Post(AURL: string; ASource: TStrings): string;
begin
{ if Assigned(FCookieList) then
WriteCookies(AURL); }
Result := inherited Post(AURL,ASource);
{ if Assigned(FCookieList) then
ReadCookies(AURL); }
end;
procedure TMyIdHTTP.ReadCookies(url: string; AResponse: TIdHTTPResponse);
var i: integer;
Cookie: string;
function DelleteIfExist(Cookie: string): boolean;
var i: integer;
begin
Result:=false;
for i := 0 to FCookieList.Count - 1 do
if (GetCookieDomain(FCookieList[i])=GetCookieDomain(Cookie))
and (GetCookieName(FCookieList[i])=GetCookieName(Cookie)) then
begin
FCookieList.Delete(i);
Exit;
end;
end;
begin
for i := 0 to AResponse.RawHeaders.Count - 1 do
if Pos('Set-Cookie: ',AResponse.RawHeaders[i])>0 then
begin
Cookie:=SysUtils.StringReplace(AResponse.RawHeaders[i],'Set-Cookie: ','',[]);
if GetCookieDomain(Cookie)='' then Cookie:=Cookie+'; domain='+GetURLDomain(url);
DelleteIfExist(Cookie);
FCookieList.Add(Cookie);
end;
end;
procedure TMyIdHTTP.WriteCookies(url: string; ARequest: TIdHTTPRequest);
var i,j: integer;
Cookies: string;
s: string;
begin
URL := GetURLDomain(URL);
if (length(url) > 0) and ((pos('www.',lowercase(url)) = 1) or (url[1] = '.')) then
URL := DeleteTo(url,'.');
for i := 0 to FCookieList.Count - 1 do
begin
s := GetCookieDomain(FCookieList[i]);
if (length(s) > 0) and ((pos('www.',lowercase(s)) = 1) or (s[1] = '.')) then
s := DeleteTo(s,'.');
if s = url then
begin
j:=Pos(';',FCookieList[i]);
Cookies:=Cookies+Copy(FCookieList[i],1,j)+' ';
end;
end;
if Cookies<>'' then
begin
Cookies:='Cookie: '+Copy(Cookies,1,Length(Cookies)-2);
// ARequest.RawHeaders.Clear;
ARequest.RawHeaders.Add(Cookies);
end;
end;
procedure TMyIdHTTP.DoSetCookies(AURL: String; ARequest: TIdHTTPRequest);
begin
WriteCookies(AURL,ARequest);
end;
procedure TMyIdHTTP.DoProcessCookies(ARequest: TIdHTTPRequest; AResponse: TIdHTTPResponse);
begin
ReadCookies(ARequest.Host,AResponse);
// WriteCookies(ARequest.Host,ARequest);
end;
procedure TMyIdHTTP.SetCookieList(Value: TMyCookieList);
begin
if Value = nil then
begin
OnSetCookies := nil;
OnProcessCookies := nil;
end else
begin
OnSetCookies := DoSetCookies;
OnProcessCookies := DoProcessCookies;
end;
FCookieList := Value;
end;
initialization
if (Win32MajorVersion >= 6) and (Win32MinorVersion > 0) then
InitializeTaskbarAPI;
end.
|
unit UMyMatrixExt;
{$mode objfpc}{$H+}
{ Simple Extension to FPC matrix unit.
Copyright (c) 2020 by Andrzej Kilijański (digitalkarabela.com)
Public domain license.
No warranty, use at your own risk.
}
interface
uses
Classes, SysUtils, matrix, Math;
procedure PrintMatrix4(const Name: String; const M: Tmatrix4_single);
function TranslateMatrix4(const M: Tmatrix4_single; const V: Tvector3_single): Tmatrix4_single;
function RotateMatrix4(const M: Tmatrix4_single; const Angle: Single; const Axis: Tvector3_single): Tmatrix4_single;
function ScaleMatrix4(const M: Tmatrix4_single; const V: Tvector3_single): Tmatrix4_single;
function Perspective(const Fov, AspectRatio, NearDist, FarDist: Single): Tmatrix4_single;
function LookAt(const Position, Target, WorldUp: Tvector3_single): Tmatrix4_single;
function NormalizeVector3(const V: Tvector3_single): Tvector3_single;
function Vector3(const X, Y, Z: Single): Tvector3_single;
implementation
procedure PrintMatrix4(const Name: String; const M: Tmatrix4_single);
var
I, J: Integer;
begin
WriteLn(Name, ' = [');
for J := 0 to 3 do
begin
for I := 0 to 3 do
Write(M.data[I, J]:8:2);
WriteLn;
end;
WriteLn(']');
end;
function TranslateMatrix4(const M: Tmatrix4_single; const V: Tvector3_single): Tmatrix4_single;
var
T: Tmatrix4_single;
begin
T.init_identity;
T.data[3, 0] := V.data[0];
T.data[3, 1] := V.data[1];
T.data[3, 2] := V.data[2];
Result := T * M;
end;
function RotateMatrix4(const M: Tmatrix4_single; const Angle: Single; const Axis: Tvector3_single): Tmatrix4_single;
var
Rotate: Tmatrix4_single;
NormalizedAxis: Tvector3_single;
Cosinus, Sinus: Single;
begin
Cosinus := Cos(Angle);
Sinus := Sin(Angle);
NormalizedAxis := NormalizeVector3(Axis);
Rotate.init_identity;
Rotate.data[0, 0] := Cosinus + NormalizedAxis.data[0] * NormalizedAxis.data[0] * (1 - Cosinus);
Rotate.data[0, 1] := NormalizedAxis.data[1] * NormalizedAxis.data[0] * (1 - Cosinus) + NormalizedAxis.data[2] * Sinus;
Rotate.data[0, 2] := NormalizedAxis.data[2] * NormalizedAxis.data[0] * (1 - Cosinus) - NormalizedAxis.data[1] * Sinus;
Rotate.data[1, 0] := NormalizedAxis.data[0] * NormalizedAxis.data[1] * (1 - Cosinus) - NormalizedAxis.data[2] * Sinus;
Rotate.data[1, 1] := Cosinus + NormalizedAxis.data[1] * NormalizedAxis.data[1] * (1 - Cosinus);
Rotate.data[1, 2] := NormalizedAxis.data[2] * NormalizedAxis.data[1] * (1 - Cosinus) + NormalizedAxis.data[0] * Sinus;
Rotate.data[2, 0] := NormalizedAxis.data[0] * NormalizedAxis.data[2] * (1 - Cosinus) + NormalizedAxis.data[1] * Sinus;
Rotate.data[2, 1] := NormalizedAxis.data[1] * NormalizedAxis.data[2] * (1 - Cosinus) - NormalizedAxis.data[0] * Sinus;
Rotate.data[2, 2] := Cosinus + NormalizedAxis.data[2] * NormalizedAxis.data[2] * (1 - Cosinus);
Result := Rotate * M;
end;
function ScaleMatrix4(const M: Tmatrix4_single; const V: Tvector3_single): Tmatrix4_single;
var
Scale : Tmatrix4_single;
begin
Scale.init_zero;
Scale.data[0, 0] := V.data[0];
Scale.data[1, 1] := V.data[1];
Scale.data[2, 2] := V.data[2];
Scale.data[3, 3] := 1.0;
Result := Scale * M;
end;
{
Based on: https://gamedev.stackexchange.com/questions/120338/what-does-a-perspective-projection-matrix-look-like-in-opengl
}
function Perspective(const Fov, AspectRatio, NearDist, FarDist: Single): Tmatrix4_single;
var
FrustumDepth: Single;
begin
FrustumDepth := FarDist - NearDist;
Result.init_identity;
if (AspectRatio = 0) or (FrustumDepth = 0) then
begin
Writeln('Perspective matrix - Bad attributes!');
Exit;
end;
Result.data[1, 1] := 1 / tan(0.5 * Fov);
Result.data[0, 0] := Result.data[1, 1] / AspectRatio;
Result.data[2, 2] := (-(FarDist + NearDist)) / FrustumDepth;
Result.data[2, 3] := -1.0;
Result.data[3, 2] := ( -(2.0 * NearDist * FarDist)) / FrustumDepth;
Result.data[3, 3] := 0.0;
end;
{ Algorithm from learnopengl.com tutorial }
function LookAt(const Position, Target, WorldUp: Tvector3_single): Tmatrix4_single;
var
XAxis: Tvector3_single;
YAxis: Tvector3_single;
ZAxis: Tvector3_single;
Translation: Tmatrix4_single;
Rotation: Tmatrix4_single;
begin
ZAxis := NormalizeVector3(Position - Target);
XAxis := NormalizeVector3(NormalizeVector3(WorldUp) >< ZAxis);
YAxis := ZAxis >< XAxis;
Translation.init_identity;
Translation.data[3, 0] := -Position.data[0];
Translation.data[3, 1] := -Position.data[1];
Translation.data[3, 2] := -Position.data[2];
Rotation.init_identity;
Rotation.data[0, 0] := XAxis.data[0];
Rotation.data[1, 0] := XAxis.data[1];
Rotation.data[2, 0] := XAxis.data[2];
Rotation.data[0, 1] := YAxis.data[0];
Rotation.data[1, 1] := YAxis.data[1];
Rotation.data[2, 1] := YAxis.data[2];
Rotation.data[0, 2] := ZAxis.data[0];
Rotation.data[1, 2] := ZAxis.data[1];
Rotation.data[2, 2] := ZAxis.data[2];
Result := Translation * Rotation;
end;
function NormalizeVector3(const V: Tvector3_single): Tvector3_single;
var
Length: Single;
begin
Length := V.length;
if Length > 0 then
begin
Result.data[0] := V.data[0] / Length;
Result.data[1] := V.data[1] / Length;
Result.data[2] := V.data[2] / Length;
Exit;
end;
Result.init_zero;
end;
function Vector3(const X, Y, Z: Single): Tvector3_single;
begin
Result.init(X, Y, Z);
end;
end.
|
unit Glass.Pixelate;
interface
uses
System.SysUtils, System.Classes, FMX.Types, FMX.Controls,
FMX.Graphics, FMX.Effects, Glass, FMX.Filter.Effects;
type
TPixelateGlass = class(TGlass)
private
FPixelate: TPixelateEffect;
function GetBlockCount: Single;
procedure SetBlockCount(const Value: Single);
protected
procedure ProcessChildEffect(const AParentScreenshotBitmap: TBitmap); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property BlockCount: Single read GetBlockCount write SetBlockCount nodefault;
end;
procedure Register;
implementation
uses
FMX.Forms, System.Math, System.Types;
{ TGlass }
constructor TPixelateGlass.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FPixelate := TPixelateEffect.Create(nil);
FPixelate.BlockCount := 25;
end;
destructor TPixelateGlass.Destroy;
begin
FPixelate.Free;
inherited Destroy;
end;
function TPixelateGlass.GetBlockCount: Single;
begin
Result := FPixelate.BlockCount;
end;
procedure TPixelateGlass.SetBlockCount(const Value: Single);
begin
FPixelate.BlockCount := Value;
end;
procedure TPixelateGlass.ProcessChildEffect(const AParentScreenshotBitmap: TBitmap);
begin
inherited;
FPixelate.ProcessEffect(Canvas, AParentScreenshotBitmap, FPixelate.BlockCount);
end;
procedure Register;
begin
RegisterComponents('Glass', [TPixelateGlass]);
end;
end.
|
unit GoalPartTypeRef;
interface
uses uCommonForm,
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Base, StdCtrls, Menus, Db, DBTables, Grids, DBGrids, Buttons, ExtCtrls,
ActnList, RXCtrls,uOilQuery,Ora, uOilStoredProc;
type
TGoalPartForm = class(TBaseForm)
Label1: TLabel;
edName: TEdit;
qID: TFloatField;
qNAME: TStringField;
procedure bbClearClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure bbSearchClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
end;
var
GoalPartForm: TGoalPartForm;
implementation
{$R *.DFM}
procedure TGoalPartForm.bbClearClick(Sender: TObject);
begin
edName.Clear;
end;
procedure TGoalPartForm.FormShow(Sender: TObject);
begin
bbClearClick(Nil);
edName.SetFocus;
q.Open;
end;
procedure TGoalPartForm.bbSearchClick(Sender: TObject);
begin
Try
With q Do
Begin
Close;
SQL.Clear;
SQL.Add('Select * from V_OIL_GOAL_PART_TYPE');
If edName.Text <> '' Then
SQL.Add('Where Upper(name) like ''%'+ANSIUpperCase(edName.Text)+'%''');
SQL.Add('order by NAME');
Open;
End;
Except On E:Exception Do
MessageDlg(TranslateText('Îøèáêà : ')+E.message,mtError,[mbOk],0);
End;
end;
procedure TGoalPartForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
end.
|
{/*!
Provides interface for vehicle monitor manager.
\modified 2019-07-09 14:37pm
\author Wuping Xin
*/}
namespace TsmPluginFx.Core;
uses
rtl;
type
VehicleMonitorManager = public static class
private
const DllName = 'VehicleMonitorManager.dll';
public
[DllImport(DllName, EntryPoint := 'CreateVehicleMonitor')]
[CallingConvention(CallingConvention.Stdcall)]
class method CreateVehicleMonitor(aVehicleMonitorName: LPWSTR; aUserVehicleDllName: LPWSTR): ^Void; external;
[DllImport(DllName, EntryPoint := 'RegisterVehicleMonitor')]
[CallingConvention(CallingConvention.Stdcall)]
class method RegisterVehicleMonitor(aMonitor: ^Void): Boolean; external;
[DllImport(DllName, EntryPoint := 'UnregisterVehicleMonitor')]
[CallingConvention(CallingConvention.Stdcall)]
class method UnregisterVehicleMonitor(aMonitor: ^Void): Boolean; external;
[DllImport(DllName, EntryPoint := 'DeleteVehicleMonitor')]
[CallingConvention(CallingConvention.Stdcall)]
class method DeleteVehicleMonitor(aMonitor: ^Void); external;
end;
end. |
unit FormMain;
// TODO:
// Consider writing a class that helps to deal with brush-related painting affairs
// - HBD 01/28/2011
interface
uses
Windows, BasicMathsTypes, BasicDataTypes, Render, SysUtils, Variants, Classes,
Graphics, Controls, Forms, Dialogs, Menus, ExtCtrls, StdCtrls, ComCtrls,
ToolWin, ImgList, Spin, Buttons, ShellAPI, Form3dpreview, XPMan, dglOpenGL,
VoxelDocument, RenderEnvironment, Actor, Camera, BasicFunctions,
BasicVXLSETypes, Form3dModelizer, BasicProgramTypes, CustomSchemeControl,
PaletteControl, Debug;
{$INCLUDE source/Global_Conditionals.inc}
Const
APPLICATION_TITLE = 'Voxel Section Editor III';
APPLICATION_VER = '1.39.273';
APPLICATION_BETA = true;
type
TFrmMain = class(TForm)
File1: TMenuItem;
Open1: TMenuItem;
OpenVXLDialog: TOpenDialog;
Panel1: TPanel;
LeftPanel: TPanel;
RightPanel: TPanel;
MainPaintPanel: TPanel;
CnvView2: TPaintBox;
CnvView1: TPaintBox;
lblView1: TLabel;
lblView2: TLabel;
lblView0: TLabel;
View1: TMenuItem;
lblSection: TLabel;
ViewMode1: TMenuItem;
Full1: TMenuItem;
CrossSection1: TMenuItem;
EmphasiseDepth1: TMenuItem;
Panel2: TPanel;
ToolBar1: TToolBar;
BarOpen: TToolButton;
BarSaveAs: TToolButton;
BarReopen: TToolButton;
ToolButton4: TToolButton;
mnuBarUndo: TToolButton;
mnuBarRedo: TToolButton;
ToolButton10: TToolButton;
ToolButton7: TToolButton;
ToolButton3: TToolButton;
ToolButton6: TToolButton;
ToolButton13: TToolButton;
ToolButton11: TToolButton;
ToolButton1: TToolButton;
ToolButton8: TToolButton;
ToolButton9: TToolButton;
ImageList1: TImageList;
Spectrum1: TMenuItem;
Colours1: TMenuItem;
Normals1: TMenuItem;
Panel3: TPanel;
SectionCombo: TComboBox;
lblTools: TLabel;
PnlTools: TPanel;
lblpalette: TLabel;
cnvPalette: TPaintBox;
pnlPalette: TPanel;
lblActiveColour: TLabel;
pnlActiveColour: TPanel;
ScrollBar2: TScrollBar;
Panel5: TPanel;
ScrollBar1: TScrollBar;
Panel6: TPanel;
N2: TMenuItem;
ShowUsedColoursNormals1: TMenuItem;
lbl3dview: TLabel;
OGL3DPreview: TPanel;
Panel7: TPanel;
SpeedButton2: TSpeedButton;
btn3DRotateX2: TSpeedButton;
btn3DRotateY2: TSpeedButton;
btn3DRotateY: TSpeedButton;
Bevel1: TBevel;
SpeedButton1: TSpeedButton;
btn3DRotateX: TSpeedButton;
spin3Djmp: TSpinEdit;
ColorDialog: TColorDialog;
Popup3d: TPopupMenu;
Views1: TMenuItem;
Front1: TMenuItem;
Back1: TMenuItem;
MenuItem1: TMenuItem;
LEft1: TMenuItem;
Right1: TMenuItem;
MenuItem2: TMenuItem;
Bottom1: TMenuItem;
op1: TMenuItem;
N3: TMenuItem;
Cameo1: TMenuItem;
Cameo21: TMenuItem;
Cameo31: TMenuItem;
Cameo41: TMenuItem;
Options2: TMenuItem;
DebugMode1: TMenuItem;
RemapColour1: TMenuItem;
Gold1: TMenuItem;
Red1: TMenuItem;
Orange1: TMenuItem;
Magenta1: TMenuItem;
Purple1: TMenuItem;
Blue1: TMenuItem;
Green1: TMenuItem;
DarkSky1: TMenuItem;
White1: TMenuItem;
N4: TMenuItem;
BackgroundColour1: TMenuItem;
extColour1: TMenuItem;
N5: TMenuItem;
lblLayer: TLabel;
PnlLayer: TPanel;
XCursorBar: TTrackBar;
Label2: TLabel;
Label3: TLabel;
YCursorBar: TTrackBar;
Label4: TLabel;
ZCursorBar: TTrackBar;
StatusBar1: TStatusBar;
mnuDirectionPopup: TPopupMenu;
mnuEdit: TMenuItem;
mnuDirTowards: TMenuItem;
mnuDirAway: TMenuItem;
mnuCancel1: TMenuItem;
lblBrush: TLabel;
PnlBrushOptions: TPanel;
Brush_5: TSpeedButton;
Brush_4: TSpeedButton;
Brush_3: TSpeedButton;
Brush_2: TSpeedButton;
Brush_1: TSpeedButton;
SpeedButton3: TSpeedButton;
SpeedButton4: TSpeedButton;
SpeedButton5: TSpeedButton;
SpeedButton6: TSpeedButton;
SpeedButton9: TSpeedButton;
SpeedButton7: TSpeedButton;
SpeedButton8: TSpeedButton;
SpeedButton10: TSpeedButton;
SpeedButton11: TSpeedButton;
NewProject1: TMenuItem;
ReOpen1: TMenuItem;
N1: TMenuItem;
Save1: TMenuItem;
SaveAs1: TMenuItem;
N6: TMenuItem;
N7: TMenuItem;
N8: TMenuItem;
Exit1: TMenuItem;
EmptyVoxel1: TMenuItem;
EmptyVoxel2: TMenuItem;
Section1: TMenuItem;
VoxelHeader1: TMenuItem;
SaveVXLDialog: TSaveDialog;
New1: TMenuItem;
N9: TMenuItem;
Resize1: TMenuItem;
FullResize1: TMenuItem;
Delete1: TMenuItem;
ClearLayer1: TMenuItem;
ClearEntireSection1: TMenuItem;
normalsaphere1: TMenuItem;
ools2: TMenuItem;
N10: TMenuItem;
Edit1: TMenuItem;
Undo1: TMenuItem;
Redo1: TMenuItem;
N11: TMenuItem;
RemoveRedundantVoxels1: TMenuItem;
CnvView0: TPaintBox;
Sites1: TMenuItem;
PPMForUpdates1: TMenuItem;
N13: TMenuItem;
Help1: TMenuItem;
VXLSEHelp1: TMenuItem;
N14: TMenuItem;
About1: TMenuItem;
Options1: TMenuItem;
Preferences1: TMenuItem;
Display3dView1: TMenuItem;
Section2: TMenuItem;
Copyofthissection1: TMenuItem;
Importfrommodel1: TMenuItem;
Flip1: TMenuItem;
N15: TMenuItem;
Mirror1: TMenuItem;
Nudge1: TMenuItem;
FlipZswitchFrontBack1: TMenuItem;
FlipXswitchRightLeft1: TMenuItem;
FlipYswitchTopBottom1: TMenuItem;
MirrorBottomToTop1: TMenuItem;
MirrorTopToBottom1: TMenuItem;
N16: TMenuItem;
MirrorLeftToRight1: TMenuItem;
MirrorRightToLeft1: TMenuItem;
N17: TMenuItem;
MirrorBackToFront1: TMenuItem;
Nudge1Left1: TMenuItem;
Nudge1Right1: TMenuItem;
Nudge1up1: TMenuItem;
Nudge1Down1: TMenuItem;
Palette1: TMenuItem;
iberianSunPalette1: TMenuItem;
RedAlert2Palette1: TMenuItem;
Custom1: TMenuItem;
N18: TMenuItem;
blank1: TMenuItem;
SpeedButton12: TSpeedButton;
N19: TMenuItem;
DarkenLightenValue1: TMenuItem;
N110: TMenuItem;
N21: TMenuItem;
N31: TMenuItem;
N41: TMenuItem;
N51: TMenuItem;
ClearVoxelColour1: TMenuItem;
Copy1: TMenuItem;
Cut1: TMenuItem;
ClearUndoSystem1: TMenuItem;
IconList: TImageList;
PasteFull1: TMenuItem;
Paste1: TMenuItem;
ColourScheme1: TMenuItem;
N22: TMenuItem;
iberianSun2: TMenuItem;
RedAlert22: TMenuItem;
YurisRevenge1: TMenuItem;
blank2: TMenuItem;
blank3: TMenuItem;
blank4: TMenuItem;
PalPack1: TMenuItem;
N23: TMenuItem;
About2: TMenuItem;
N24: TMenuItem;
Allied1: TMenuItem;
Soviet1: TMenuItem;
Yuri1: TMenuItem;
Blue2: TMenuItem;
Brick1: TMenuItem;
Brown11: TMenuItem;
Brown21: TMenuItem;
Grayscale1: TMenuItem;
Green2: TMenuItem;
NoUnlit1: TMenuItem;
Remap1: TMenuItem;
Red2: TMenuItem;
Yellow1: TMenuItem;
blank5: TMenuItem;
blank6: TMenuItem;
blank7: TMenuItem;
blank8: TMenuItem;
blank9: TMenuItem;
blank10: TMenuItem;
blank11: TMenuItem;
blank12: TMenuItem;
blank13: TMenuItem;
blank14: TMenuItem;
blank15: TMenuItem;
blank16: TMenuItem;
blank17: TMenuItem;
ToolButton2: TToolButton;
ToolButton14: TToolButton;
OpenDialog1: TOpenDialog;
DisableDrawPreview1: TMenuItem;
SmoothNormals1: TMenuItem;
Disable3dView1: TMenuItem;
ReplaceColours1: TMenuItem;
Normals3: TMenuItem;
Colours2: TMenuItem;
VoxelTexture1: TMenuItem;
N12: TMenuItem;
test1: TMenuItem;
Scripts1: TMenuItem;
SpinButton3: TSpinButton;
SpinButton1: TSpinButton;
SpinButton2: TSpinButton;
TopBarImageHolder: TImage;
MainViewPopup: TPopupMenu;
Magnification1: TMenuItem;
N1x1: TMenuItem;
N3x1: TMenuItem;
N5x1: TMenuItem;
N7x1: TMenuItem;
N9x1: TMenuItem;
N10x1: TMenuItem;
N131: TMenuItem;
N15x1: TMenuItem;
N17x1: TMenuItem;
N19x1: TMenuItem;
N21x1: TMenuItem;
N23x1: TMenuItem;
N25x1: TMenuItem;
ToolButton5: TToolButton;
ToolButton12: TToolButton;
CubedAutoNormals1: TMenuItem;
SpeedButton13: TSpeedButton;
Others1: TMenuItem;
blank18: TMenuItem;
MirrorFrontToBack2: TMenuItem;
Display3DWindow1: TMenuItem;
ProjectSVN1: TMenuItem;
XPManifest1: TXPManifest;
Animation1: TMenuItem;
SpeedButton14: TSpeedButton;
TSPalettes: TMenuItem;
RA2Palettes: TMenuItem;
O3DModelizer1: TMenuItem;
Import1: TMenuItem;
N20: TMenuItem;
using3ds2vxl1: TMenuItem;
MainMenu1: TMainMenu;
UpdateSchemes1: TMenuItem;
OpenDialog3ds2vxl: TOpenDialog;
Importfromamodelusing3ds2vxl1: TMenuItem;
CropSection1: TMenuItem;
AutoUpdate1: TMenuItem;
RepairProgram1: TMenuItem;
Display1: TMenuItem;
FillMode1: TMenuItem;
DisplayFMSolid: TMenuItem;
DisplayFMWireframe: TMenuItem;
DisplayFMPointCloud: TMenuItem;
Splitter1: TSplitter;
Splitter2: TSplitter;
Splitter3: TSplitter;
RemoveRedundantVoxelsB1: TMenuItem;
ImagewithHeightmap1: TMenuItem;
QualityAnalysis1: TMenuItem;
opologyAnalysis1: TMenuItem;
Export1: TMenuItem;
Isosurfacesiso1: TMenuItem;
SaveDialogExport: TSaveDialog;
IncreaseResolution1: TMenuItem;
Shape1: TMenuItem;
FillUselessInternalGaps1: TMenuItem;
FillUselessInternalCavesVeryStrict1: TMenuItem;
N26: TMenuItem;
Apollo1: TMenuItem;
N25: TMenuItem;
UpdatePaletteList1: TMenuItem;
RotateModel1: TMenuItem;
Pitch901: TMenuItem;
Pitch902: TMenuItem;
Roll901: TMenuItem;
Roll902: TMenuItem;
Yaw901: TMenuItem;
Yaw902: TMenuItem;
N27: TMenuItem;
MaintainDimensions1: TMenuItem;
pnlActiveNormal: TPanel;
lblActiveNormal: TLabel;
procedure Splitter3Moved(Sender: TObject);
procedure Splitter2Moved(Sender: TObject);
procedure MaintainDimensions1Click(Sender: TObject);
procedure UpdatePaletteList1Click(Sender: TObject);
procedure FillUselessInternalCavesVeryStrict1Click(Sender: TObject);
procedure FillUselessInternalGaps1Click(Sender: TObject);
procedure IncreaseResolution1Click(Sender: TObject);
procedure Isosurfacesiso1Click(Sender: TObject);
procedure opologyAnalysis1Click(Sender: TObject);
procedure ImagewithHeightmap1Click(Sender: TObject);
procedure DisplayFMPointCloudClick(Sender: TObject);
procedure DisplayFMWireframeClick(Sender: TObject);
procedure DisplayFMSolidClick(Sender: TObject);
procedure RepairProgram1Click(Sender: TObject);
procedure AutoUpdate1Click(Sender: TObject);
procedure CropSection1Click(Sender: TObject);
procedure Importfromamodelusing3ds2vxl1Click(Sender: TObject);
procedure UpdateSchemes1Click(Sender: TObject);
procedure using3ds2vxl1Click(Sender: TObject);
procedure O3DModelizer1Click(Sender: TObject);
procedure ProjectSVN1Click(Sender: TObject);
procedure FormDeactivate(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure NewAutoNormals1Click(Sender: TObject);
procedure Display3DWindow1Click(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure Open1Click(Sender: TObject);
procedure OpenVoxelInterface(const _Filename: string);
procedure CnvView0Paint(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure ChangeCaption(Filename : boolean);
procedure CnvView1Paint(Sender: TObject);
procedure CnvView2Paint(Sender: TObject);
Procedure SetIsEditable(Value : boolean);
Procedure RefreshAll;
Procedure SetupSections;
procedure SectionComboChange(Sender: TObject);
procedure Full1Click(Sender: TObject);
procedure CrossSection1Click(Sender: TObject);
procedure EmphasiseDepth1Click(Sender: TObject);
Procedure SetViewMode(VM : EViewMode);
Procedure SetSpectrum(SP : ESpectrumMode);
procedure Colours1Click(Sender: TObject);
procedure Normals1Click(Sender: TObject);
procedure cnvPalettePaint(Sender: TObject);
procedure SetActiveColor(Value : integer; CN : boolean);
procedure SetActiveNormal(Value : integer; CN : boolean);
Procedure SetActiveCN(Value : integer);
Procedure SetActiveN(Value : integer);
procedure ScrollBar1Change(Sender: TObject);
procedure setupscrollbars;
procedure FormShow(Sender: TObject);
procedure cnvPaletteMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure ShowUsedColoursNormals1Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure OGL3DPreviewMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure OGL3DPreviewMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure OGL3DPreviewMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure SpeedButton1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure DebugMode1Click(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
procedure btn3DRotateXClick(Sender: TObject);
Procedure SetRotationAdders;
procedure btn3DRotateX2Click(Sender: TObject);
procedure btn3DRotateY2Click(Sender: TObject);
procedure btn3DRotateYClick(Sender: TObject);
procedure spin3DjmpChange(Sender: TObject);
procedure BackgroundColour1Click(Sender: TObject);
procedure extColour1Click(Sender: TObject);
procedure ClearRemapClicks;
procedure Gold1Click(Sender: TObject);
procedure Red1Click(Sender: TObject);
procedure Orange1Click(Sender: TObject);
procedure Magenta1Click(Sender: TObject);
procedure Purple1Click(Sender: TObject);
procedure Blue1Click(Sender: TObject);
procedure Green1Click(Sender: TObject);
procedure DarkSky1Click(Sender: TObject);
procedure White1Click(Sender: TObject);
procedure Front1Click(Sender: TObject);
procedure Back1Click(Sender: TObject);
procedure LEft1Click(Sender: TObject);
procedure Right1Click(Sender: TObject);
procedure Bottom1Click(Sender: TObject);
procedure op1Click(Sender: TObject);
procedure Cameo1Click(Sender: TObject);
procedure Cameo21Click(Sender: TObject);
procedure Cameo31Click(Sender: TObject);
procedure Cameo41Click(Sender: TObject);
procedure CnvView2MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure CnvView1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure CnvView1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure CnvView1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure CnvView2MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure CnvView2MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure CnvView0MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
Procedure UpdateCursor(P : TVector3i; Repaint : Boolean);
procedure XCursorBarChange(Sender: TObject);
Procedure CursorReset;
Procedure CursorResetNoMAX;
Procedure SetupStatusBar;
procedure CnvView0MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure lblView1Click(Sender: TObject);
procedure lblView2Click(Sender: TObject);
procedure mnuDirectionPopupPopup(Sender: TObject);
procedure mnuEditClick(Sender: TObject);
procedure mnuDirTowardsClick(Sender: TObject);
procedure mnuDirAwayClick(Sender: TObject);
procedure DoAfterLoadingThings;
procedure Brush_1Click(Sender: TObject);
procedure Brush_2Click(Sender: TObject);
procedure Brush_3Click(Sender: TObject);
procedure Brush_4Click(Sender: TObject);
procedure Brush_5Click(Sender: TObject);
procedure SpeedButton3Click(Sender: TObject);
Procedure SetVXLTool(VXLTool_ : Integer);
procedure CnvView0MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure SpeedButton5Click(Sender: TObject);
procedure SpeedButton4Click(Sender: TObject);
procedure SpeedButton10Click(Sender: TObject);
procedure SpeedButton11Click(Sender: TObject);
procedure SpeedButton6Click(Sender: TObject);
procedure SpeedButton8Click(Sender: TObject);
procedure Save1Click(Sender: TObject);
procedure Exit1Click(Sender: TObject);
procedure SaveAs1Click(Sender: TObject);
procedure VoxelHeader1Click(Sender: TObject);
procedure N6Click(Sender: TObject);
Procedure UpdateUndo_RedoState;
procedure mnuBarUndoClick(Sender: TObject);
procedure mnuBarRedoClick(Sender: TObject);
procedure updatenormals1Click(Sender: TObject);
procedure Delete1Click(Sender: TObject);
procedure normalsaphere1Click(Sender: TObject);
procedure RemoveRedundantVoxels1Click(Sender: TObject);
procedure ClearEntireSection1Click(Sender: TObject);
procedure CnCSource1Click(Sender: TObject);
procedure PPMForUpdates1Click(Sender: TObject);
procedure LoadSite(Sender: TObject);
procedure OpenHyperlink(HyperLink: PChar);
procedure VXLSEHelp1Click(Sender: TObject);
procedure Display3dView1Click(Sender: TObject);
procedure About1Click(Sender: TObject);
procedure FlipZswitchFrontBack1Click(Sender: TObject);
procedure FlipXswitchRightLeft1Click(Sender: TObject);
procedure FlipYswitchTopBottom1Click(Sender: TObject);
procedure MirrorBottomToTop1Click(Sender: TObject);
procedure MirrorLeftToRight1Click(Sender: TObject);
procedure MirrorBackToFront1Click(Sender: TObject);
procedure MirrorFrontToBack1Click(Sender: TObject);
procedure Nudge1Left1Click(Sender: TObject);
procedure RotateYawNegativeClick(Sender: TObject);
procedure RotateYawPositiveClick(Sender: TObject);
procedure RotatePitchNegativeClick(Sender: TObject);
procedure RotatePitchPositiveClick(Sender: TObject);
procedure RotateRollNegativeClick(Sender: TObject);
procedure RotateRollPositiveClick(Sender: TObject);
procedure Section2Click(Sender: TObject);
procedure Copyofthissection1Click(Sender: TObject);
procedure BuildReopenMenu;
procedure mnuHistoryClick(Sender: TObject);
procedure BarReopenClick(Sender: TObject);
procedure iberianSunPalette1Click(Sender: TObject);
procedure RedAlert2Palette1Click(Sender: TObject);
Procedure LoadPalettes;
procedure blank1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
Function CheckVXLChanged: boolean;
procedure SpeedButton7Click(Sender: TObject);
procedure SpeedButton12Click(Sender: TObject);
procedure SpeedButton14Click(Sender: TObject);
Procedure SetDarkenLighten(Value : integer);
procedure N110Click(Sender: TObject);
procedure N21Click(Sender: TObject);
procedure N31Click(Sender: TObject);
procedure N41Click(Sender: TObject);
procedure N51Click(Sender: TObject);
procedure ToolButton11Click(Sender: TObject);
procedure ClearLayer1Click(Sender: TObject);
procedure Copy1Click(Sender: TObject);
procedure Cut1Click(Sender: TObject);
procedure ClearUndoSystem1Click(Sender: TObject);
procedure PasteFull1Click(Sender: TObject);
procedure Paste1Click(Sender: TObject);
function CreateSplitterMenuItem: TMenuItem;
function UpdateCScheme : integer;
function LoadCScheme : integer;
procedure blank2Click(Sender: TObject);
procedure About2Click(Sender: TObject);
procedure EmptyVoxel1Click(Sender: TObject);
procedure EmptyVoxel2Click(Sender: TObject);
Procedure NewVFile(Game : integer);
Procedure SetCursor;
procedure DisableDrawPreview1Click(Sender: TObject);
procedure SmoothNormals1Click(Sender: TObject);
procedure VoxelTexture1Click(Sender: TObject);
procedure test1Click(Sender: TObject);
function GetVoxelImportedBy3ds2vxl(var _Destination: string): boolean;
procedure ImportSectionFromVoxel(const _Filename: string);
procedure Importfrommodel1Click(Sender: TObject);
procedure Resize1Click(Sender: TObject);
procedure SpinButton3UpClick(Sender: TObject);
procedure SpinButton3DownClick(Sender: TObject);
procedure SpinButton1DownClick(Sender: TObject);
procedure SpinButton1UpClick(Sender: TObject);
procedure SpinButton2DownClick(Sender: TObject);
procedure SpinButton2UpClick(Sender: TObject);
procedure FullResize1Click(Sender: TObject);
procedure ToolButton9Click(Sender: TObject);
procedure SpeedButton9Click(Sender: TObject);
Procedure SelectCorrectPalette;
Procedure SelectCorrectPalette2(Palette : String);
procedure ToolButton13Click(Sender: TObject);
Procedure CreateVxlError(v,n : Boolean);
procedure N1x1Click(Sender: TObject);
procedure CubedAutoNormals1Click(Sender: TObject);
procedure SpeedButton13Click(Sender: TObject);
procedure UpdatePositionStatus(x,y,z : integer);
procedure AutoRepair(const _Filename: string; _ForceRepair: boolean = false);
procedure RemoveRedundantVoxelsB1Click(Sender: TObject);
private
{ Private declarations }
RemapColour : TVector3f;
Xcoord, Ycoord, Zcoord : Integer;
MouseButton : Integer;
ValidLastClick : boolean;
ViewMinimumHeight: integer;
procedure Idle(Sender: TObject; var Done: Boolean);
procedure BuildUsedColoursArray;
function CharToStr: string;
procedure ApplyPalette(const _Filename: string);
procedure UncheckFillMode;
public
{ Public declarations }
{IsEditable,}IsVXLLoading : boolean;
ShiftPressed : boolean;
AltPressed : boolean;
p_Frm3DPreview : PFrm3DPReview;
p_Frm3DModelizer: PFrm3DModelizer;
Document : TVoxelDocument;
Env : TRenderEnvironment;
Actor : PActor;
Camera : TCamera;
CustomSchemeControl : TCustomSchemeControl;
PaletteControl : TPaletteControl;
SiteList: TSitesList;
{$ifdef DEBUG_FILE or TEXTURE_DEBUG}
DebugFile: TDebugFile;
{$endif}
SelectedZoomOption: TMenuItem;
procedure UpdateRenderingCounters;
procedure SetVoxelChanged(_Value: boolean);
end;
var
FrmMain: TFrmMain;
implementation
{$R *.dfm}
uses FormHeaderUnit, LoadForm, FormNewSectionSizeUnit, FormPalettePackAbout, HVA,
FormReplaceColour, FormVoxelTexture, FormBoundsManager, FormImportSection,
FormFullResize, FormPreferences, FormVxlError, Config, ActorActionController,
ModelUndoEngine, ModelVxt, Constants, mouse, Math, FormAutoNormals, pause,
FormRepairAssistant, GlConstants, FormHeightmap, FormTopologyAnalysis, Voxel,
IsoSurfaceFile, FillUselessGapsTool, TopologyFixer, FormNewVxlUnit, Registry,
VoxelUndoEngine, GlobalVars, VoxelDocumentBank, ModelBank, TextureBank, Normals,
HVABank, VoxelBank, CustomScheme, BasicConstants, ImageIOUtils, INIFiles,
Voxel_Engine, CommunityLinks;
procedure TFrmMain.FormCreate(Sender: TObject);
var
i : integer;
begin
// 1.32: Debug adition
{$ifdef DEBUG_FILE or TEXTURE_DEBUG}
DebugFile := TDebugFile.Create(IncludeTrailingPathDelimiter(ExtractFileDir(ParamStr(0))) + 'debugdev.txt');
DebugFile.Add('FrmMain: FormCreate');
{$endif}
// 1.32: Shortcut aditions
ShiftPressed := false;
AltPressed := false;
ValidLastClick := false;
CnvView[0] := @CnvView0;
CnvView[1] := @CnvView1;
CnvView[2] := @CnvView2;
lblView[0] := @lblView0;
lblView[1] := @lblView1;
lblView[2] := @lblView2;
mnuReopen := @ReOpen1;
BuildReopenMenu;
Height := 768;
if not FileExists(IncludeTrailingPathDelimiter(ExtractFileDir(ParamStr(0))) + 'palettes\TS\unittem.pal') then
begin
AutoRepair(IncludeTrailingPathDelimiter(ExtractFileDir(ParamStr(0))) + 'palettes\TS\unittem.pal');
end;
if (not FileExists(ExtractFileDir(ParamStr(0)) + '\images\pause.bmp')) then
begin
AutoRepair(ExtractFileDir(ParamStr(0)) + '\images\pause.bmp');
end;
if (not FileExists(ExtractFileDir(ParamStr(0)) + '\images\play.bmp')) then
begin
AutoRepair(ExtractFileDir(ParamStr(0)) + '\images\play.bmp');
end;
// ensure that ocl scripts exists
if (not FileExists(ExtractFileDir(ParamStr(0)) + '\opencl\origami.cl')) then
begin
AutoRepair(ExtractFileDir(ParamStr(0)) + '\opencl\origami.cl');
end;
GlobalVars.Render := TRender.Create(IncludeTrailingPathDelimiter(ExtractFileDir(ParamStr(0))) + 'shaders');
GlobalVars.Documents := TVoxelDocumentBank.Create;
GlobalVars.VoxelBank := TVoxelBank.Create;
GlobalVars.HVABank := THVABank.Create;
GlobalVars.ModelBank := TModelBank.Create;
GlobalVars.TextureBank := TTextureBank.Create;
Document := (Documents.AddNew)^;
for i := 0 to 2 do
begin
cnvView[i].ControlStyle := cnvView[i].ControlStyle + [csOpaque];
lblView[i].ControlStyle := lblView[i].ControlStyle + [csOpaque];
end;
// 1.4x New Render starts here.
GlobalVars.ActorController := TActorActionController.Create;
GlobalVars.ModelUndoEngine := TModelUndoRedo.Create;
GlobalVars.ModelRedoEngine := TModelUndoRedo.Create;
Env := (GlobalVars.Render.AddEnvironment(OGL3DPreview.Handle,OGL3DPreview.Width,OGL3DPreview.Height))^;
Actor := Env.AddActor;
Camera := Env.CurrentCamera^;
GlobalVars.Render.SetFPS(Configuration.FPSCap);
GlobalVars.Render.EnableOpenCL := Configuration.OpenCL;
Env.SetBackgroundColour(Configuration.Canvas3DBackgroundColor);
Env.EnableShaders(false);
Env.AddRenderingVariable('Voxels','0');
SetIsEditable(False);
//FrmMain.DoubleBuffered := true;
//MainPaintPanel.DoubleBuffered := true;
LeftPanel.DoubleBuffered := true;
RightPanel.DoubleBuffered := true;
SetActiveColor(16,true);
SetActiveNormal(0,true);
ChangeCaption(false);
// Resets the 3 views on the right sidebar if the res is too low for 203 high ones.
if RightPanel.Height < lblView1.Height+CnvView1.Height+lblView2.Height+CnvView2.Height+lbl3dview.Height+Panel7.Height+OGL3DPreview.Height then
begin
ViewMinimumHeight := RightPanel.Height - (lblView1.Height+lblView2.Height+lbl3dview.Height+Panel7.Height);
ViewMinimumHeight := trunc(ViewMinimumHeight / 3);
CnvView1.Height := ViewMinimumHeight;
CnvView2.Height := ViewMinimumHeight;
OGL3DPreview.Height := ViewMinimumHeight;
end
else
begin
ViewMinimumHeight := CnvView1.Height;
end;
RightPanel.Constraints.MinHeight := lblView1.Height+CnvView1.Height+lblView2.Height+CnvView2.Height+lbl3dview.Height+Panel7.Height+OGL3DPreview.Height;
// 1.2 Enable Idle only on certain situations.
Application.OnIdle := nil;
p_Frm3DPreview := nil;
p_Frm3DModelizer := nil;
Application.OnDeactivate := FormDeactivate;
Application.OnActivate := FormActivate;
Application.OnMinimize := FormDeactivate;
Application.OnRestore := FormActivate;
// Setting up nudge shortcuts.
Nudge1Left1.ShortCut := ShortCut(VK_LEFT,[ssShift,ssCtrl]);
Nudge1Right1.ShortCut := ShortCut(VK_RIGHT,[ssShift,ssCtrl]);
Nudge1Up1.ShortCut := ShortCut(VK_UP,[ssShift,ssCtrl]);
Nudge1Down1.ShortCut := ShortCut(VK_DOWN,[ssShift,ssCtrl]);
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: FormCreate Loaded');
// If you don't have Delphi 2006 or better, disable the line below!
ReportMemoryLeaksOnShutdown := true;
{$endif}
end;
procedure TFrmMain.FormShow(Sender: TObject);
var
frm: TLoadFrm;
l: Integer;
Reg: TRegistry;
LatestVersion: string;
VoxelName: string;
begin
frm := TLoadFrm.Create(Self);
if testbuild then
frm.Label4.Caption := APPLICATION_VER + ' TB '+testbuildversion
else
frm.Label4.Caption := APPLICATION_VER;
// 1.2:For future compatibility with other OS tools, we are
// using the registry keys to confirm its existance.
Reg :=TRegistry.Create;
Reg.RootKey := HKEY_LOCAL_MACHINE;
if Reg.OpenKey('Software\CnC Tools\VXLSEIII\',true) then
begin
LatestVersion := Reg.ReadString('Version');
if APPLICATION_VER > LatestVersion then
begin
Reg.WriteString('Path',ParamStr(0));
Reg.WriteString('Version',APPLICATION_VER);
end;
Reg.CloseKey;
end;
Reg.Free;
frm.Show;
l := 0;
while l < 25 do
begin
if l = 0 then begin frm.Loading.Caption := 'Loading: 3rd Party Palettes';frm.Loading.Refresh; LoadPalettes; end;
if l = 10 then begin frm.Loading.Caption := 'Loading: Colour Schemes'; frm.Loading.Refresh; LoadCScheme; end;
if l = 23 then begin frm.Loading.Caption := 'Finished Loading'; delay(50); end;
l := l + 1;
delay(2);
end;
frm.Close;
frm.Free;
if (not FileExists(ExtractFileDir(ParamStr(0)) + '\commlist.ini')) then
begin
AutoRepair(ExtractFileDir(ParamStr(0)) + '\commlist.ini');
end;
LoadCommunityLinks;
WindowState := wsMaximized;
// refresh;
setupscrollbars;
UpdateUndo_RedoState;
VXLTool := 4;
if ParamCount > 0 then
begin
VoxelName := GetParamStr;
If FileExists(VoxelName) then
Begin
IsVXLLoading := true;
Application.OnIdle := nil;
SetIsEditable(LoadVoxel(Document,VoxelName));
if IsEditable then
begin
if p_Frm3DPreview <> nil then
begin
p_Frm3DPreview^.SpFrame.MaxValue := 1;
p_Frm3DPreview^.SpStopClick(nil);
end;
if p_Frm3DModelizer <> nil then
begin
p_Frm3DModelizer^.SpFrame.MaxValue := 1;
p_Frm3DModelizer^.SpStopClick(nil);
end;
DoAfterLoadingThings;
end;
IsVXLLoading := false;
End;
end;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: FormShow Loaded');
{$endif}
end;
procedure TFrmMain.Idle(Sender: TObject; var Done: Boolean);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Idle');
{$endif}
if IsEditable then
begin
GlobalVars.Render.Render;
end;
Done := false;
end;
procedure TFrmMain.FormResize(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: FormResize');
{$endif}
CentreViews;
setupscrollbars;
end;
procedure TFrmMain.Open1Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Open1Click');
{$endif}
if OpenVXLDialog.Execute then
begin
OpenVoxelInterface(OpenVXLDialog.FileName);
end;
end;
procedure TFrmMain.OpenVoxelInterface(const _Filename: string);
begin
SetIsEditable(false);
SendToBack;
sleep(50);
application.ProcessMessages;
IsVXLLoading := true;
Application.OnIdle := nil;
CheckVXLChanged;
if LoadVoxel(Document,_Filename) then
begin
if p_Frm3DPreview <> nil then
begin
p_Frm3DPreview^.SpFrame.MaxValue := 1;
p_Frm3DPreview^.SpStopClick(nil);
end;
if p_Frm3DModelizer <> nil then
begin
p_Frm3DModelizer^.SpFrame.MaxValue := 1;
p_Frm3DModelizer^.SpStopClick(nil);
end;
DoAfterLoadingThings;
SetIsEditable(true);
RefreshAll;
end;
IsVXLLoading := false;
BringToFront;
end;
Procedure TFrmMain.SetIsEditable(Value : boolean);
var
i : integer;
begin
IsEditable := value;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetIsEditable');
{$endif}
// Clear tempview:
TempView.Data_no := 0;
Setlength(TempView.Data,0);
// Invalidate mouse click.
ValidLastClick := false;
Env.IsEnabled := IsEditable;
for i := 0 to 2 do
begin
cnvView[i].Enabled := isEditable;
//lblView[i].Enabled := isEditable;
end;
if iseditable then
begin
for i := 0 to 2 do
begin
lblView[i].Color := clNavy;
lblView[i].Font.Color := clYellow;
lblView[i].Refresh;
end;
lblSection.Color := clNavy;
lblSection.Font.Color := clYellow;
lblTools.Color := clNavy;
lblTools.Font.Color := clYellow;
lblPalette.Color := clNavy;
lblPalette.Font.Color := clYellow;
lbl3dview.Color := clNavy;
lbl3dview.Font.Color := clYellow;
lblLayer.Color := clNavy;
lblLayer.Font.Color := clYellow;
lblBrush.Color := clNavy;
lblBrush.Font.Color := clYellow;
lblBrush.refresh;
lblLayer.refresh;
lbl3dview.refresh;
lblSection.refresh;
lblTools.refresh;
lblPalette.refresh;
If SpectrumMode = ModeColours then
SetActiveColor(ActiveColour,true);
SetActiveNormal(ActiveNormal,true);
cnvPalette.refresh;
// 1.32 Aditions:
cnvView0.OnMouseDown := cnvView0MouseDown;
cnvView0.OnMouseUp := cnvView0MouseUp;
cnvView0.OnMouseMove := cnvView0MouseMove;
cnvView0.OnPaint := cnvView0Paint;
cnvView1.OnMouseDown := cnvView1MouseDown;
cnvView1.OnMouseUp := cnvView1MouseUp;
cnvView1.OnMouseMove := cnvView1MouseMove;
cnvView1.OnPaint := cnvView1Paint;
cnvView2.OnMouseDown := cnvView2MouseDown;
cnvView2.OnMouseUp := cnvView2MouseUp;
cnvView2.OnMouseMove := cnvView2MouseMove;
cnvView2.OnPaint := cnvView2Paint;
oGL3DPreview.OnMouseDown := ogl3DPreviewMouseDown;
oGL3DPreview.OnMouseUp := ogl3DPreviewMouseUp;
oGL3DPreview.OnMouseMove := ogl3DPreviewMouseMove;
end
else
begin
// We'll force a closure of the 3D Preview window.
if p_Frm3DPreview <> nil then
begin
p_Frm3DPreview^.Release;
p_Frm3DPreview := nil;
end;
// We'll force a closure of the 3D MOdelizer window.
if p_Frm3DModelizer <> nil then
begin
p_Frm3DModelizer^.Release;
p_Frm3DModelizer := nil;
end;
// 1.32 Aditions:
cnvView0.OnMouseDown := nil;
cnvView0.OnMouseUp := nil;
cnvView0.OnMouseMove := nil;
cnvView0.OnPaint := nil;
cnvView1.OnMouseDown := nil;
cnvView1.OnMouseUp := nil;
cnvView1.OnMouseMove := nil;
cnvView1.OnPaint := nil;
cnvView2.OnMouseDown := nil;
cnvView2.OnMouseUp := nil;
cnvView2.OnMouseMove := nil;
cnvView2.OnPaint := nil;
oGL3DPreview.OnMouseDown := nil;
oGL3DPreview.OnMouseUp := nil;
oGL3DPreview.OnMouseMove := nil;
end;
View1.Visible := IsEditable;
Section1.Visible := IsEditable;
ools2.Visible := IsEditable;
Edit1.Visible := IsEditable;
Scripts1.Visible := IsEditable;
Export1.Enabled := IsEditable;
SectionCombo.Enabled := IsEditable;
BarSaveAs.Enabled := IsEditable;
ToolButton5.Enabled := IsEditable;
ToolButton7.Enabled := IsEditable;
ToolButton3.Enabled := IsEditable;
ToolButton13.Enabled := IsEditable;
ToolButton11.Enabled := IsEditable;
ToolButton1.Enabled := IsEditable;
ToolButton2.Enabled := IsEditable;
btn3DRotateY.Enabled := IsEditable;
btn3DRotateY2.Enabled := IsEditable;
btn3DRotateX.Enabled := IsEditable;
btn3DRotateX2.Enabled := IsEditable;
spin3Djmp.Enabled := IsEditable;
SpeedButton1.Enabled := IsEditable;
SpeedButton2.Enabled := IsEditable;
SpeedButton3.Enabled := IsEditable;
SpeedButton4.Enabled := IsEditable;
SpeedButton5.Enabled := IsEditable;
SpeedButton6.Enabled := IsEditable;
SpeedButton7.Enabled := IsEditable;
SpeedButton8.Enabled := IsEditable;
SpeedButton9.Enabled := IsEditable;
SpeedButton10.Enabled := IsEditable;
SpeedButton11.Enabled := IsEditable;
SpeedButton12.Enabled := IsEditable;
SpeedButton13.Enabled := IsEditable;
SpeedButton14.Enabled := IsEditable;
Brush_1.Enabled := IsEditable;
Brush_2.Enabled := IsEditable;
Brush_3.Enabled := IsEditable;
Brush_4.Enabled := IsEditable;
Brush_5.Enabled := IsEditable;
pnlLayer.Enabled := IsEditable;
mnuDirectionPopup.AutoPopup := IsEditable;
Magnification1.Enabled := IsEditable;
N6.Enabled := IsEditable;
SaveAs1.Enabled := IsEditable;
Save1.Enabled := IsEditable;
// Temporary
Animation1.Enabled := false;
if not iseditable then
begin
OGL3DPreview.Refresh;
end;
end;
procedure TFrmMain.DoAfterLoadingThings;
var
v,n : boolean;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: DoAfterLoadingThings');
{$endif}
ChangeCaption(true);
v := not IsVoxelValid;
n := HasNormalsBug;
if v or n then
CreateVxlError(v,n);
SetupSections;
SetViewMode(ModeEmphasiseDepth);
SetSpectrum(SpectrumMode);
if Configuration.ResetNormalValue then
begin
SetActiveNormal(0,true);
end
else
begin
SetActiveNormal(ActiveNormal,true);
end;
// 1.2b: Refresh Show Use Colours
if UsedColoursOption then
BuildUsedColoursArray;
// End of 1.2b adition
setupscrollbars;
SetupStatusBar;
CursorReset;
ResetUndoRedo;
UpdateUndo_RedoState;
SelectCorrectPalette;
PaintPalette(cnvPalette,True);
if High(Actor^.Models) >= 0 then
begin
Actor^.Clear;
GlobalVars.ActorController.TerminateObject(Actor);
end;
Actor^.Add(Document.ActiveSection,Document.Palette,C_QUALITY_CUBED);
GlobalVars.ActorController.DoLoadModel(Actor, C_QUALITY_CUBED);
GlobalVars.ActorController.SetBaseObject(Actor);
UpdateRenderingCounters;
if p_Frm3DPreview <> nil then
begin
if High(p_Frm3DPreview^.Actor^.Models) >= 0 then
begin
GlobalVars.ModelUndoEngine.Remove(p_Frm3DPreview^.Actor.Models[0]^.ID);
p_Frm3DPreview^.Actor^.Clear;
GlobalVars.ActorController.TerminateObject(p_Frm3DPreview^.Actor);
end;
p_Frm3DPreview^.Actor^.Clone(Document.ActiveVoxel,Document.ActiveHVA,Document.Palette,p_Frm3DPreview^.GetQualityModel);
GlobalVars.ActorController.DoLoadModel(p_Frm3DPreview^.Actor, p_Frm3DPreview^.GetQualityModel);
GlobalVars.ActorController.SetBaseObject(p_Frm3DPreview^.Actor);
p_Frm3DPreview^.SetActorModelTransparency;
p_Frm3DPreview^.UpdateQualityUI;
p_Frm3DPreview^.UpdateRenderingCounters;
p_Frm3DPreview^.SpFrame.MaxValue := Document.ActiveHVA^.Header.N_Frames;
p_Frm3DPreview^.SpFrame.Value := 1;
end;
if p_Frm3DModelizer <> nil then
begin
if High(p_Frm3DModelizer^.Actor^.Models) >= 0 then
begin
GlobalVars.ModelUndoEngine.Remove(p_Frm3DModelizer^.Actor.Models[0]^.ID);
p_Frm3DModelizer^.Actor^.Clear;
GlobalVars.ActorController.TerminateObject(p_Frm3DModelizer^.Actor);
end;
p_Frm3DModelizer^.Actor^.Clone(Document.ActiveVoxel,Document.ActiveHVA,Document.Palette,p_Frm3DModelizer^.GetQualityModel);
GlobalVars.ActorController.DoLoadModel(p_Frm3DModelizer^.Actor, p_Frm3DModelizer^.GetQualityModel);
(p_Frm3DModelizer^.Actor^.Models[0]^ as TModelVxt).MakeVoxelHVAIndependent;
GlobalVars.ActorController.SetBaseObject(p_Frm3DModelizer^.Actor);
p_Frm3DModelizer^.SetActorModelTransparency;
p_Frm3DModelizer^.UpdateQualityUI;
p_Frm3DModelizer^.UpdateRenderingCounters;
p_Frm3DModelizer^.SpFrame.MaxValue := Document.ActiveHVA^.Header.N_Frames;
p_Frm3DModelizer^.SpFrame.Value := 1;
end;
if not Display3dView1.Checked then
if @Application.OnIdle = nil then
Application.OnIdle := Idle
else
Application.OnIdle := nil;
RefreshAll;
end;
procedure TFrmMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if CheckVXLChanged then
begin
if p_Frm3DPreview <> nil then
begin
try
p_Frm3DPreview^.Release;
except;
end;
p_Frm3DPreview := nil;
end;
if p_Frm3DModelizer <> nil then
begin
try
p_Frm3DModelizer^.Release;
except;
end;
p_Frm3DModelizer := nil;
end
end
else
begin
Action := caNone;
end;
end;
procedure TFrmMain.FormDestroy(Sender: TObject);
begin
VoxelOpen := false;
if IsEditable then
begin
GlobalVars.ModelUndoEngine.Remove(Actor^.Models[0]^.ID);
GlobalVars.ActorController.TerminateObject(Actor);
end;
IsEditable := false;
GlobalVars.ModelUndoEngine.Free;
GlobalVars.ModelRedoEngine.Free;
GlobalVars.ActorController.Free;
GlobalVars.Render.Free;
GlobalVars.Documents.Free;
GlobalVars.VoxelBank.Free;
GlobalVars.HVABank.Free;
GlobalVars.ModelBank.Free;
GlobalVars.TextureBank.Free;
DeactivateRenderingContext;
UpdateHistoryMenu;
Configuration.SaveSettings;
Configuration.Free;
RA2Normals.Free;
TSNormals.Free;
CubeNormals.Free;
CustomSchemeControl.Free;
PaletteControl.Free;
{$ifdef SPEED_TEST}
GlobalVars.SpeedFile.Free;
{$endif}
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Free;
{$endif}
{$ifdef SMOOTH_TEST}
GlobalVars.SmoothFile.Free;
{$endif}
{$ifdef ORIGAMI_TEST}
GlobalVars.OrigamiFile.Free;
{$endif}
{$ifdef DEBUG_FILE or TEXTURE_DEBUG}
DebugFile.Free;
{$endif}
GlobalVars.SysInfo.Free;
//SetLength(ColourSchemes,0);
end;
Procedure TFrmMain.RefreshAll;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Refresh All');
{$endif}
RefreshViews;
RepaintViews;
if (Actor <> nil) and (not Display3dView1.Checked) then
begin
Actor^.RebuildActor;
UpdateRenderingCounters;
end;
if p_Frm3DPreview <> nil then
begin
GlobalVars.ActorController.DoRebuildModel(p_Frm3DPreview^.Actor, p_Frm3DPreview^.GetQualityModel);
//p_Frm3DPreview^.Actor^.RebuildActor;
p_Frm3DPreview^.UpdateRenderingCounters;
end;
end;
procedure TFrmMain.UpdateRenderingCounters;
begin
if (Actor <> nil) then
if High(Actor^.Models) >= 0 then
if Actor^.Models[0] <> nil then
if Actor^.Models[0]^.ModelType = C_MT_VOXEL then
begin
Env.RenderingVariableValues[0] := IntToStr((Actor^.Models[0]^ as TModelVxt).GetVoxelCount);
end
else
begin
Env.RenderingVariableValues[0] := IntToStr(Actor^.Models[0]^.GetVoxelCount);
end;
end;
{------------------------------------------------------------------}
{------------------------------------------------------------------}
procedure TFrmMain.changecaption(Filename : boolean);
begin
Caption := APPLICATION_TITLE + ' v' + APPLICATION_VER;
if Filename then
begin
if VXLFilename = '' then
begin
Caption := Caption + ' [Untitled]';
end
else
begin
Caption := Caption + ' [' + extractfilename(VXLFilename) + ']';
end;
if VXLChanged then
begin
Caption := Caption + '*';
end;
end;
end;
procedure TFrmMain.CnvView0Paint(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CnvView0Paint');
{$endif}
if Document.ActiveSection <> nil then
PaintView2(0,true,CnvView[0],Document.ActiveSection^.View[0]);
end;
procedure TFrmMain.CnvView1Paint(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CnvView1Paint');
{$endif}
if Document.ActiveSection <> nil then
PaintView2(1,false,CnvView[1],Document.ActiveSection^.View[1]);
end;
procedure TFrmMain.CnvView2Paint(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CnvView2Paint');
{$endif}
if Document.ActiveSection <> nil then
PaintView2(2,false,CnvView[2],Document.ActiveSection^.View[2]);
end;
Procedure TFrmMain.SetupSections;
var
i : integer;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Setup Sections');
{$endif}
SectionCombo.Clear;
for i := 0 to (Document.ActiveVoxel^.Header.NumSections - 1) do
SectionCombo.Items.Add(Document.ActiveVoxel^.Section[i].Name);
SectionCombo.ItemIndex := CurrentSection;
end;
procedure TFrmMain.SectionComboChange(Sender: TObject);
begin
if IsVXLLoading then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SectionComboChange');
{$endif}
CurrentSection := SectionCombo.ItemIndex;
ChangeSection;
CursorReset;
if High(Actor^.Models) >= 0 then
Actor^.Clear;
Actor^.Add(Document.ActiveSection,Document.Palette,C_QUALITY_CUBED);
UpdateRenderingCounters;
if p_Frm3DPreview <> nil then
begin
p_Frm3DPreview^.SetActorModelTransparency;
p_Frm3DPreview^.UpdateRenderingCounters;
end;
ResetUndoRedo;
UpdateUndo_RedoState;
RefreshAll;
end;
procedure TFrmMain.Full1Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Full1Click');
{$endif}
SetViewMode(ModeFull);
RepaintViews;
end;
procedure TFrmMain.CrossSection1Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CrossSection1Click');
{$endif}
SetViewMode(ModeCrossSection);
RepaintViews;
end;
procedure TFrmMain.EmphasiseDepth1Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: EmphasiseDepth1Click');
{$endif}
SetViewMode(ModeEmphasiseDepth);
RepaintViews;
end;
Procedure TFrmMain.SetViewMode(VM : EViewMode);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetViewMode');
{$endif}
Full1.checked := false;
CrossSection1.checked := false;
EmphasiseDepth1.checked := false;
if VM = ModeFull then
Full1.checked := true;
if VM = ModeCrossSection then
CrossSection1.checked := true;
if VM = ModeEmphasiseDepth then
EmphasiseDepth1.checked := true;
ViewMode := VM;
end;
Procedure TFrmMain.SetSpectrum(SP : ESpectrumMode);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetSpectrum');
{$endif}
Normals1.checked := false;
Colours1.checked := false;
if SP = ModeNormals then
begin
Normals1.checked := true;
Env.RenderNormals;
if p_Frm3DPreview <> nil then
begin
p_Frm3DPreview^.Env.RenderNormals;
end;
end
else
begin
Colours1.checked := true;
Env.RenderColours;
if p_Frm3DPreview <> nil then
begin
p_Frm3DPreview^.Env.RenderColours;
end;
end;
SpectrumMode := SP;
SetSpectrumMode;
Document.ActiveSection^.View[0].Refresh;
Document.ActiveSection^.View[1].Refresh;
Document.ActiveSection^.View[2].Refresh;
PaintPalette(cnvPalette,True);
if not IsVXLLoading then
RepaintViews;
end;
procedure TFrmMain.Colours1Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Colours1Click');
{$endif}
SetSpectrum(ModeColours);
SetActiveColor(ActiveColour,true);
end;
procedure TFrmMain.Normals1Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Normals1Click');
{$endif}
SetSpectrum(ModeNormals);
SetActiveNormal(ActiveNormal,true);
end;
procedure TFrmMain.cnvPalettePaint(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: cnvPalettePaint');
{$endif}
PaintPalette(cnvPalette,true);
end;
procedure TFrmMain.SetActiveColor(Value : integer; CN : boolean);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetActiveColour');
{$endif}
ActiveColour := Value;
if CN then
// if SpectrumMode = ModeColours then
SetActiveCN(Value);
end;
procedure TFrmMain.SetActiveNormal(Value : integer; CN : boolean);
var
v : integer;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetActiveNormal');
{$endif}
v := Value;
if ActiveNormalsCount > 0 then
if v > ActiveNormalsCount-1 then
v := ActiveNormalsCount-1; // normal too high
ActiveNormal := v;
if CN then
// if SpectrumMode = ModeNormals then
SetActiveN(V);
end;
Procedure TFrmMain.SetActiveCN(Value : integer);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetActiveCN');
{$endif}
if isEditable then
pnlActiveColour.Color := GetVXLPaletteColor(Value)
else
pnlActiveColour.Color := colourtogray(GetVXLPaletteColor(Value));
lblActiveColour.Caption := IntToStr(Value) + ' (0x' + IntToHex(Value,3) + '): Colour';
cnvPalette.Repaint;
end;
Procedure TFrmMain.SetActiveN(Value : integer);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetActiveN');
{$endif}
if isEditable then
pnlActiveNormal.Color := GetVXLPaletteColor(Value, true)
else
pnlActiveNormal.Color := colourtogray(GetVXLPaletteColor(Value));
lblActiveNormal.Caption := IntToStr(Value) + ' (0x' + IntToHex(Value,3) + '): Normal';
cnvPalette.Repaint;
end;
procedure TFrmMain.ScrollBar1Change(Sender: TObject);
var
x , y, width, height : integer;
begin
if not isEditable then Exit;
if not scrollbar_editable then Exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: ScrollBar1Change');
{$endif}
Width := cnvView[0].Width;
Height := cnvView[0].Height;
with Document.ActiveSection^.Viewport[0] do
begin
x := Document.ActiveSection^.View[0].Width * Zoom;
if ScrollBar1.enabled then
if x > Width then
Left := 0 - ((x - Width) div 2) -(ScrollBar1.Position - (ScrollBar1.Max div 2))
else
Left := ((Width - x) div 2) -(ScrollBar1.Position - (ScrollBar1.Max div 2));
y := Document.ActiveSection^.View[0].Height * Zoom;
if ScrollBar2.enabled then
if y > Height then
Top := 0 - ((y - Height) div 2) -(ScrollBar2.Position - (ScrollBar2.Max div 2))
else
Top := (Height - y) div 2 -(ScrollBar2.Position - (ScrollBar2.Max div 2));
end;
PaintView2(0,true,CnvView[0],Document.ActiveSection^.View[0]);
end;
procedure TFrmMain.SetupScrollBars;
begin
ScrollBar1.Enabled := false;
ScrollBar2.Enabled := false;
if not isEditable then Exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetupScrollBars');
{$endif}
If (Document.ActiveSection^.View[0].Width * Document.ActiveSection^.Viewport[0].zoom) > cnvView[0].Width then
begin
scrollbar_editable := false;
// showmessage(inttostr(ActiveSection.View[0].Width * ActiveSection.Viewport[0].zoom - cnvView[0].Width));
ScrollBar2.Position := 0;
ScrollBar1.max := Document.ActiveSection^.View[0].Width * Document.ActiveSection^.Viewport[0].zoom - cnvView[0].Width;
ScrollBar1.Position := ScrollBar1.max div 2;
ScrollBar1.Enabled := true;
scrollbar_editable := true;
end
else
ScrollBar1.Enabled := false;
If (Document.ActiveSection^.View[0].Height * Document.ActiveSection^.Viewport[0].zoom) > cnvView[0].Height then
begin
scrollbar_editable := false;
//showmessage(inttostr(ActiveSection.View[0].Height * ActiveSection.Viewport[0].zoom - cnvView[0].Height));
ScrollBar2.Position := 0;
ScrollBar2.max := Document.ActiveSection^.View[0].Height * Document.ActiveSection^.Viewport[0].zoom - cnvView[0].Height;
ScrollBar2.Position := ScrollBar2.max div 2;
ScrollBar2.Enabled := true;
scrollbar_editable := true;
end
else
ScrollBar2.Enabled := false;
end;
procedure TFrmMain.cnvPaletteMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
colwidth, rowheight: Real;
i, j, idx: Integer;
begin
If not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: cnvPaletteMouseUp');
{$endif}
colwidth := cnvPalette.Width / 8;
rowheight := cnvPalette.Height / 32;
i := Trunc(X / colwidth);
j := Trunc(Y / rowheight);
idx := (i * 32) + j;
if SpectrumMode = ModeColours then
SetActiveColor(idx,true)
else if not (idx > ActiveNormalsCount-1) then
SetActiveNormal(idx,true);
end;
// 1.2b: Build the Show Used Colours/Normals array
// Ripped from VXLSE II 2.2 SE OpenGL (never released version)
// Original function apparently made by Stucuk
procedure TFrmMain.BuildUsedColoursArray;
var
x,y,z : integer;
v : TVoxelUnpacked;
begin
// This part is modified by Banshee. It's stupid to see it checking if x < 244 everytime
for x := 0 to 244 do
begin
UsedColours[x] := false;
UsedNormals[x] := false;
end;
for x := 245 to 255 do
UsedColours[x] := false;
for x := 0 to Document.ActiveSection^.Tailer.XSize -1 do
for y := 0 to Document.ActiveSection^.Tailer.YSize -1 do
for z := 0 to Document.ActiveSection^.Tailer.ZSize -1 do
begin
Document.ActiveSection^.GetVoxel(x,y,z,v);
if v.Used then
begin
UsedColours[v.Colour] := true;
UsedNormals[v.normal] := true;
end;
end;
end;
procedure TFrmMain.ShowUsedColoursNormals1Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: ShowUsedColoursNormals1');
{$endif}
ShowUsedColoursNormals1.Checked := not UsedColoursOption;
UsedColoursOption := ShowUsedColoursNormals1.Checked;
// 1.2b: Refresh Show Use Colours
if UsedColoursOption then
BuildUsedColoursArray;
PaintPalette(cnvPalette,True);
end;
procedure TFrmMain.OGL3DPreviewMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
If not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: OGL3DPreviewMouseMove');
{$endif}
if MouseButton = 1 then
begin
Camera.SetRotation(Camera.Rotation.X + (Y - Ycoord)/2,Camera.Rotation.Y + (X - Xcoord)/2,Camera.Rotation.Z);
Xcoord := X;
Ycoord := Y;
end;
if MouseButton = 2 then
begin
Camera.SetPosition(Camera.Position.X,Camera.Position.Y,Camera.Position.Z - (Y-ZCoord)/3);
Zcoord := Y;
end;
end;
procedure TFrmMain.O3DModelizer1Click(Sender: TObject);
begin
if p_Frm3DModelizer = nil then
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: O3DModelizer1Click');
{$endif}
Application.OnIdle := nil;
new(p_Frm3DModelizer);
p_Frm3DModelizer^ := TFrm3DModelizer.Create(self);
p_Frm3DModelizer^.Show;
if @Application.OnIdle = nil then
Application.OnIdle := Idle;
end;
end;
procedure TFrmMain.OGL3DPreviewMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
If not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: OGL3DPreviewMouseDown');
{$endif}
if Button = mbLeft then
begin
MouseButton :=1;
Xcoord := X;
Ycoord := Y;
end;
if Button = mbRight then
begin
MouseButton :=2;
Zcoord := Y;
end;
end;
procedure TFrmMain.OGL3DPreviewMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: OGL3DPreviewMouseUp');
{$endif}
MouseButton :=0;
end;
procedure TFrmMain.SpeedButton1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SpeedButton1MouseUp');
{$endif}
Popup3d.Popup(Left+SpeedButton1.Left+ RightPanel.Left +5,Top+ 90+ Panel7.Top + SpeedButton1.Top);
end;
procedure TFrmMain.DebugMode1Click(Sender: TObject);
begin
DebugMode1.Checked := not DebugMode1.Checked;
Env.ShowRotations := DebugMode1.Checked;
end;
Procedure TFrmMain.SetRotationAdders;
var
V : single;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetRotationAdders');
{$endif}
try
V := spin3Djmp.Value / 10;
except
exit; // Not a value
end;
if btn3DRotateX2.Down then
Camera.SetRotationSpeed(-V,Camera.RotationSpeed.Y,Camera.RotationSpeed.Z)
else if btn3DRotateX.Down then
Camera.SetRotationSpeed(V,Camera.RotationSpeed.Y,Camera.RotationSpeed.Z)
else
Camera.SetRotationSpeed(0,Camera.RotationSpeed.Y,Camera.RotationSpeed.Z);
if btn3DRotateY2.Down then
Camera.SetRotationSpeed(Camera.RotationSpeed.X,-V,Camera.RotationSpeed.Z)
else if btn3DRotateY.Down then
Camera.SetRotationSpeed(Camera.RotationSpeed.X,V,Camera.RotationSpeed.Z)
else
Camera.SetRotationSpeed(Camera.RotationSpeed.X,0,Camera.RotationSpeed.Z);
end;
procedure TFrmMain.SpeedButton2Click(Sender: TObject);
begin
Camera.SetPosition(Camera.Position.X,Camera.Position.Y,-150);
end;
procedure TFrmMain.btn3DRotateXClick(Sender: TObject);
begin
if btn3DRotateX.Down then
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Btn3DRotateXClick');
{$endif}
SetRotationAdders;
end
else
begin
Camera.SetRotationSpeed(0,Camera.RotationSpeed.Y,Camera.RotationSpeed.Z);
end;
end;
procedure TFrmMain.btn3DRotateX2Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Bnt3DRotateX2Click');
{$endif}
if btn3DRotateX2.Down then
begin
SetRotationAdders;
end
else
Camera.SetRotationSpeed(0,Camera.RotationSpeed.Y,Camera.RotationSpeed.Z);
end;
procedure TFrmMain.btn3DRotateY2Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Btn3DRotateY2Click');
{$endif}
if btn3DRotateY2.Down then
begin
SetRotationAdders;
end
else
Camera.SetRotationSpeed(Camera.RotationSpeed.X,0,Camera.RotationSpeed.Z);
end;
procedure TFrmMain.btn3DRotateYClick(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: btn3DRotateYClick');
{$endif}
if btn3DRotateY.Down then
begin
SetRotationAdders;
end
else
Camera.SetRotationSpeed(Camera.RotationSpeed.X,0,Camera.RotationSpeed.Z);
end;
procedure TFrmMain.spin3DjmpChange(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Spin3DJmpChange');
{$endif}
SetRotationAdders;
end;
procedure TFrmMain.BackgroundColour1Click(Sender: TObject);
begin
ColorDialog.Color := TVector3fToTColor(Env.BackgroundColour);
if ColorDialog.Execute then
Env.SetBackgroundColour(TColorToTVector3f(ColorDialog.Color));
end;
procedure TFrmMain.extColour1Click(Sender: TObject);
begin
ColorDialog.Color := TVector3fToTColor(Env.FontColour);
if ColorDialog.Execute then
Env.SetFontColour(TColorToTVector3f(ColorDialog.Color));
end;
procedure TFrmMain.ClearRemapClicks;
begin
Red1.Checked := false;
Blue1.Checked := false;
Green1.Checked := false;
White1.Checked := false;
Orange1.Checked := false;
Magenta1.Checked := false;
Purple1.Checked := false;
Gold1.Checked := false;
DarkSky1.Checked := false;
end;
procedure TFrmMain.Red1Click(Sender: TObject);
begin
ClearRemapClicks;
Red1.Checked := true;
RemapColour.X := RemapColourMap[0].R /255;
RemapColour.Y := RemapColourMap[0].G /255;
RemapColour.Z := RemapColourMap[0].B /255;
Actor^.ChangeRemappable(RemapColourMap[0].R,RemapColourMap[0].G,RemapColourMap[0].B);
end;
procedure TFrmMain.Blue1Click(Sender: TObject);
begin
ClearRemapClicks;
Blue1.Checked := true;
RemapColour.X := RemapColourMap[1].R /255;
RemapColour.Y := RemapColourMap[1].G /255;
RemapColour.Z := RemapColourMap[1].B /255;
Actor^.ChangeRemappable(RemapColourMap[1].R,RemapColourMap[1].G,RemapColourMap[1].B);
end;
procedure TFrmMain.Green1Click(Sender: TObject);
begin
ClearRemapClicks;
Green1.Checked := true;
RemapColour.X := RemapColourMap[2].R /255;
RemapColour.Y := RemapColourMap[2].G /255;
RemapColour.Z := RemapColourMap[2].B /255;
Actor^.ChangeRemappable(RemapColourMap[2].R,RemapColourMap[2].G,RemapColourMap[2].B);
end;
procedure TFrmMain.White1Click(Sender: TObject);
begin
ClearRemapClicks;
White1.Checked := true;
RemapColour.X := RemapColourMap[3].R /255;
RemapColour.Y := RemapColourMap[3].G /255;
RemapColour.Z := RemapColourMap[3].B /255;
Actor^.ChangeRemappable(RemapColourMap[3].R,RemapColourMap[3].G,RemapColourMap[3].B);
end;
procedure TFrmMain.Orange1Click(Sender: TObject);
begin
ClearRemapClicks;
Orange1.Checked := true;
RemapColour.X := RemapColourMap[4].R /255;
RemapColour.Y := RemapColourMap[4].G /255;
RemapColour.Z := RemapColourMap[4].B /255;
Actor^.ChangeRemappable(RemapColourMap[4].R,RemapColourMap[4].G,RemapColourMap[4].B);
end;
procedure TFrmMain.Magenta1Click(Sender: TObject);
begin
ClearRemapClicks;
Magenta1.Checked := true;
RemapColour.X := RemapColourMap[5].R /255;
RemapColour.Y := RemapColourMap[5].G /255;
RemapColour.Z := RemapColourMap[5].B /255;
Actor^.ChangeRemappable(RemapColourMap[5].R,RemapColourMap[5].G,RemapColourMap[5].B);
end;
procedure TFrmMain.MaintainDimensions1Click(Sender: TObject);
begin
MaintainDimensions1.Checked := not MaintainDimensions1.Checked;
Configuration.MaintainDimensionsRM := MaintainDimensions1.Checked;
end;
procedure TFrmMain.Purple1Click(Sender: TObject);
begin
ClearRemapClicks;
Purple1.Checked := true;
RemapColour.X := RemapColourMap[6].R /255;
RemapColour.Y := RemapColourMap[6].G /255;
RemapColour.Z := RemapColourMap[6].B /255;
Actor^.ChangeRemappable(RemapColourMap[6].R,RemapColourMap[6].G,RemapColourMap[6].B);
end;
procedure TFrmMain.Gold1Click(Sender: TObject);
begin
ClearRemapClicks;
Gold1.Checked := true;
RemapColour.X := RemapColourMap[7].R /255;
RemapColour.Y := RemapColourMap[7].G /255;
RemapColour.Z := RemapColourMap[7].B /255;
Actor^.ChangeRemappable(RemapColourMap[7].R,RemapColourMap[7].G,RemapColourMap[7].B);
end;
procedure TFrmMain.DarkSky1Click(Sender: TObject);
begin
ClearRemapClicks;
DarkSky1.Checked := true;
RemapColour.X := RemapColourMap[8].R /255;
RemapColour.Y := RemapColourMap[8].G /255;
RemapColour.Z := RemapColourMap[8].B /255;
Actor^.ChangeRemappable(RemapColourMap[8].R,RemapColourMap[8].G,RemapColourMap[8].B);
end;
procedure TFrmMain.Front1Click(Sender: TObject);
begin
Camera.SetRotation(0,0,0);
end;
procedure TFrmMain.Back1Click(Sender: TObject);
begin
Camera.SetRotation(0,180,0);
end;
procedure TFrmMain.LEft1Click(Sender: TObject);
begin
Camera.SetRotation(0,-90,0);
end;
procedure TFrmMain.Right1Click(Sender: TObject);
begin
Camera.SetRotation(0,90,0);
end;
procedure TFrmMain.Bottom1Click(Sender: TObject);
begin
Camera.SetRotation(90,-90,180);
end;
procedure TFrmMain.op1Click(Sender: TObject);
begin
Camera.SetRotation(-90,90,180);
end;
procedure TFrmMain.Cameo1Click(Sender: TObject);
begin
Camera.SetRotation(17,315,0);
end;
procedure TFrmMain.Cameo21Click(Sender: TObject);
begin
Camera.SetRotation(17,45,0);
end;
procedure TFrmMain.Cameo31Click(Sender: TObject);
begin
Camera.SetRotation(17,345,0);
end;
procedure TFrmMain.Cameo41Click(Sender: TObject);
begin
Camera.SetRotation(17,15,0);
end;
procedure TFrmMain.CnvView2MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CnvView2MouseUp');
{$endif}
// isLeftMB := false;
end;
procedure TFrmMain.CnvView1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CnvView1MouseUp');
{$endif}
// isLeftMB := false;
end;
procedure TFrmMain.CnvView1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
Outside: Boolean;
begin
if VoxelOpen and IsEditable then
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CnvView1MouseDown');
{$endif}
// if Button = mbLeft then
// isLeftMB := true;
if Button = mbLeft then
begin
TranslateClick(1,X,Y,LastClick[1].X,LastClick[1].Y,LastClick[1].Z,Outside);
if not Outside then
begin
MoveCursor(LastClick[1].X,LastClick[1].Y,LastClick[1].Z,true);
CursorResetNoMAX;
end;
end;
end;
end;
procedure TFrmMain.CnvView1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var
Outside: Boolean;
begin
if VoxelOpen and IsEditable then
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CnvView1MouseMove');
{$endif}
if ssLeft in Shift then
begin
TranslateClick(1,X,Y,LastClick[1].X,LastClick[1].Y,LastClick[1].Z,Outside);
if Not Outside then
begin
MoveCursor(LastClick[1].X,LastClick[1].Y,LastClick[1].Z,true);
CursorResetNoMAX;
end;
end;
end;
end;
procedure TFrmMain.CnvView2MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var
Outside: boolean;
begin
if VoxelOpen and IsEditable then
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CnvView2MouseMove');
{$endif}
if ssLeft in Shift then
begin
TranslateClick(2,X,Y,LastClick[2].X,LastClick[2].Y,LastClick[2].Z,Outside);
if not Outside then
begin
MoveCursor(LastClick[2].X,LastClick[2].Y,LastClick[2].Z,true);
CursorResetNoMAX;
end;
end;
end;
end;
procedure TFrmMain.CnvView2MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
Outside: boolean;
begin
if VoxelOpen and IsEditable then
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CnvView2MouseDown');
{$endif}
// if Button = mbLeft then
// isLeftMB := true;
if ssLeft in Shift then
begin
TranslateClick(2,X,Y,LastClick[2].X,LastClick[2].Y,LastClick[2].Z,Outside);
if not Outside then
begin
MoveCursor(LastClick[2].X,LastClick[2].Y,LastClick[2].Z,true);
CursorResetNoMAX;
end;
end;
end;
end;
procedure TFrmMain.CnvView0MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
TempI : integer;
V : TVoxelUnpacked;
Outside: boolean;
begin
if VoxelOpen and IsEditable then
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CnvView0MouseUp');
{$endif}
if ((ssAlt in shift) and (Button = mbLeft)) or ((Button = mbLeft) and (VXLTool = VXLTool_Dropper)) then
begin
TempI := GetPaletteColourFromVoxel(X,Y,0);
if TempI > -1 then
if SpectrumMode = ModeColours then
SetActiveColor(TempI,True)
else
SetActiveNormal(TempI,True);
end
else
begin
if (ssCtrl in shift) and (Button = mbLeft) then
begin
TranslateClick(0,x,y,LastClick[0].x,LastClick[0].y,LastClick[0].z,Outside);
if not Outside then
begin
MoveCursor(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,false);
end;
end;
if VXLTool = VXLTool_FloodFill then
begin
TranslateClick(0,x,y,LastClick[0].x,LastClick[0].y,LastClick[0].z,Outside);
if not Outside then
begin
Document.ActiveSection^.GetVoxel(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v);
if (SpectrumMode = ModeColours) or (v.Used=False) then
v.Colour := ActiveColour;
if (SpectrumMode = ModeNormals) or (v.Used=False) then
v.Normal := ActiveNormal;
v.Used := True;
VXLFloodFillTool(Document.ActiveSection^,LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v,Document.ActiveSection^.View[0].GetOrient);
end;
end;
if VXLTool = VXLTool_FloodFillErase then
begin
TranslateClick(0,x,y,LastClick[0].x,LastClick[0].y,LastClick[0].z,Outside);
if not Outside then
begin
Document.ActiveSection^.GetVoxel(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v);
if (SpectrumMode = ModeColours) or (v.Used=False) then
v.Colour := 0;
if (SpectrumMode = ModeNormals) or (v.Used=False) then
v.Normal := 0;
v.Used := False;
VXLFloodFillTool(Document.ActiveSection^,LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v,Document.ActiveSection^.View[0].GetOrient);
end;
end;
if VXLTool = VXLTool_Darken then
begin
TranslateClick(0,x,y,LastClick[0].x,LastClick[0].y,LastClick[0].z,Outside);
if not Outside then
begin
Document.ActiveSection^.GetVoxel(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v);
if (SpectrumMode = ModeColours) or (v.Used=False) then
v.Colour := ActiveColour;
if (SpectrumMode = ModeNormals) or (v.Used=False) then
v.Normal := ActiveNormal;
v.Used := True;
VXLBrushToolDarkenLighten(Document.ActiveSection^,LastClick[0].X,LastClick[0].Y,LastClick[0].Z,VXLBrush,Document.ActiveSection^.View[0].GetOrient,True);
end;
end;
if VXLTool = VXLTool_Lighten then
begin
TranslateClick(0,x,y,LastClick[0].x,LastClick[0].y,LastClick[0].z,Outside);
if not Outside then
begin
Document.ActiveSection^.GetVoxel(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v);
if (SpectrumMode = ModeColours) or (v.Used=False) then
v.Colour := ActiveColour;
if (SpectrumMode = ModeNormals) or (v.Used=False) then
v.Normal := ActiveNormal;
v.Used := True;
VXLBrushToolDarkenLighten(Document.ActiveSection^,LastClick[0].X,LastClick[0].Y,LastClick[0].Z,VXLBrush,Document.ActiveSection^.View[0].GetOrient,false);
end;
end;
end;
if ApplyTempView(Document.ActiveSection^) then
UpdateUndo_RedoState;
TempLines.Data_no := 0;
SetLength(TempLines.Data,0);
ValidLastClick := false;
if (Button = mbLeft) or (Button = mbRight) then
begin
RefreshAll;
end;
end;
end;
Procedure TFrmMain.UpdateCursor(P : TVector3i; Repaint : Boolean);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: UpdateCursor');
{$endif}
XCursorBar.Position := P.X;
YCursorBar.Position := P.Y;
ZCursorBar.Position := P.Z;
UpdatePositionStatus(P.X,P.Y,P.Z);
StatusBar1.Refresh;
MoveCursor(P.X,P.Y,P.Z,Repaint);
end;
procedure TFrmMain.XCursorBarChange(Sender: TObject);
begin
if IsVXLLoading then exit;
if isCursorReset then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: XCursorBarChange');
{$endif}
UpdateCursor(SetVectorI(XCursorBar.Position,YCursorBar.Position,ZCursorBar.Position),true);
end;
Procedure TFrmMain.CursorReset;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CursorReset');
{$endif}
isCursorReset := true;
XCursorBar.Position := 0;
YCursorBar.Position := 0;
ZCursorBar.Position := 0;
XCursorBar.Max := Document.ActiveSection^.Tailer.XSize-1;
YCursorBar.Max := Document.ActiveSection^.Tailer.YSize-1;
ZCursorBar.Max := Document.ActiveSection^.Tailer.ZSize-1;
XCursorBar.Position := Document.ActiveSection^.X;
YCursorBar.Position := Document.ActiveSection^.Y;
ZCursorBar.Position := Document.ActiveSection^.Z;
UpdatePositionStatus(Document.ActiveSection^.X,Document.ActiveSection^.Y,Document.ActiveSection^.Z);
StatusBar1.Refresh;
isCursorReset := false;
end;
Procedure TFrmMain.CursorResetNoMAX;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CursorResetNoMAX');
{$endif}
isCursorReset := true;
XCursorBar.Position := Document.ActiveSection^.X;
YCursorBar.Position := Document.ActiveSection^.Y;
ZCursorBar.Position := Document.ActiveSection^.Z;
UpdatePositionStatus(Document.ActiveSection^.X,Document.ActiveSection^.Y,Document.ActiveSection^.Z);
StatusBar1.Refresh;
isCursorReset := false;
end;
Procedure TFrmMain.SetupStatusBar;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetupStatusBar');
{$endif}
if Document.ActiveSection^.Tailer.NormalsType = 2 then
StatusBar1.Panels[0].Text := 'Type: Tiberian Sun'
else if Document.ActiveSection^.Tailer.NormalsType = 4 then
StatusBar1.Panels[0].Text := 'Type: RedAlert 2'
else
StatusBar1.Panels[0].Text := 'Type: Unknown ' + inttostr(Document.ActiveSection^.Tailer.NormalsType);
StatusBar1.Panels[1].Text := 'X Size: ' + inttostr(Document.ActiveSection^.Tailer.XSize) + ', Y Size: ' + inttostr(Document.ActiveSection^.Tailer.YSize) + ', Z Size: ' + inttostr(Document.ActiveSection^.Tailer.ZSize);
StatusBar1.Panels[2].Text := '';
StatusBar1.Refresh;
end;
procedure TFrmMain.CnvView0MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
label
PickColor;
var
V : TVoxelUnpacked;
TempI : integer;
Viewport : TViewport;
SnapPos1 : TPoint;
SnapPos2 : TPoint;
GridPos1 : TPoint;
GridPos2 : TPoint;
GridOffset : TPoint;
MeasureAngle : Extended;
Outside: Boolean;
begin
// Maybe a switch statement is better because it can be optimized by the compiler - HBD
// Test whether left(right) mouse button is down with:
// if ssLeft(ssRight) in Shift then ... - HBD
if VoxelOpen and isEditable then
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CnvView0MouseMove');
{$endif}
TranslateClick(0,x,y,LastClick[0].x,LastClick[0].y,LastClick[0].z,Outside);
StatusBar1.Panels[2].Text := 'X: ' + inttostr(LastClick[0].X) + ', Y: ' + inttostr(LastClick[0].Y) + ', Z: ' + inttostr(LastClick[0].Z);
StatusBar1.Refresh;
MousePos.X := X;
MousePos.Y := Y;
if TempLines.Data_no > 0 then
begin
TempLines.Data_no := 0;
SetLength(TempLines.Data,0);
end;
if not Outside then
begin
if ssLeft in Shift then
begin
if ssCtrl in shift then
begin
MoveCursor(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,true);
Exit;
end;
// alt key dropper
if ssAlt in Shift then goto PickColor;
case VxlTool of
VxlTool_Brush:
begin
if VXLBrush <> 4 then
begin
Document.ActiveSection^.GetVoxel(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v);
if (SpectrumMode = ModeColours) or (v.Used=False) then
v.Colour := ActiveColour;
if (SpectrumMode = ModeNormals) or (v.Used=False) then
v.Normal := ActiveNormal;
v.Used := True;
VXLBrushTool(Document.ActiveSection^,LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v,VXLBrush,Document.ActiveSection^.View[0].GetOrient);
CnvView[0].Repaint;
end;
end;
VxlTool_Dropper:
PickColor:
begin
TempI := GetPaletteColourFromVoxel(X,Y,0);
if TempI > -1 then
if SpectrumMode = ModeColours then
SetActiveColor(TempI,True)
else
SetActiveNormal(TempI,True);
Mouse_Current := MouseDropper;
CnvView[0].Cursor := Mouse_Current;
end;
VXLTool_SmoothNormal:
begin
Document.ActiveSection^.GetVoxel(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v);
VXLSmoothBrushTool(Document.ActiveSection^,LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v,VXLBrush,Document.ActiveSection^.View[0].GetOrient);
RepaintViews;
end;
VXLTool_Erase:
begin
v.Used := false;
v.Colour := 0;
v.Normal := 0;
VXLBrushTool(Document.ActiveSection^,LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v,VXLBrush,Document.ActiveSection^.View[0].GetOrient);
RepaintViews;
end;
VxlTool_Line:
begin
if ValidLastClick then
begin
V.Used := true;
V.Colour := ActiveColour;
V.Normal := ActiveNormal;
drawstraightline(Document.ActiveSection^,TempView,LastClick[0],LastClick[1],V);
RepaintViews;
end;
end;
VXLTool_Rectangle:
begin
if ValidLastClick then
begin
V.Used := true;
V.Colour := ActiveColour;
V.Normal := ActiveNormal;
VXLRectangle(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,LastClick[1].X,LastClick[1].Y,LastClick[1].Z,false,v);
RepaintViews;
end;
end;
VXLTool_FilledRectangle:
begin
if ValidLastClick then
begin
V.Used := true;
V.Colour := ActiveColour;
V.Normal := ActiveNormal;
VXLRectangle(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,LastClick[1].X,LastClick[1].Y,LastClick[1].Z,true,v);
RepaintViews;
end;
end;
VXLTool_Measure:
begin
Viewport := Document.ActiveSection^.Viewport[0];
GridPos1.X := ((OldMousePos.X-Viewport.Left) div Viewport.Zoom);
GridPos1.Y := ((OldMousePos.Y-Viewport.Top) div Viewport.Zoom);
GridPos2.X := ((MousePos.X-Viewport.Left) div Viewport.Zoom);
GridPos2.Y := ((MousePos.Y-Viewport.Top) div Viewport.Zoom);
SnapPos1.X := (GridPos1.X*Viewport.Zoom + Viewport.Zoom div 2)+Viewport.Left;
SnapPos1.Y := (GridPos1.Y*Viewport.Zoom + Viewport.Zoom div 2)+Viewport.Top;
SnapPos2.X := (GridPos2.X*Viewport.Zoom + Viewport.Zoom div 2)+Viewport.Left;
SnapPos2.Y := (GridPos2.Y*Viewport.Zoom + Viewport.Zoom div 2)+Viewport.Top;
GridOffset.X := GridPos2.X-GridPos1.X;
GridOffset.Y := GridPos2.Y-GridPos1.Y;
MeasureAngle := ArcTan2(SnapPos2.Y-SnapPos1.Y,SnapPos2.X-SnapPos1.X);
if (GridOffset.X <> 0) or (GridOffset.Y <> 0) then
begin
AddTempLine(Round(SnapPos1.X+Cos(MeasureAngle)*5.0),Round(SnapPos1.Y+Sin(MeasureAngle)*5.0),Round(SnapPos2.X-Cos(MeasureAngle)*5.0),Round(SnapPos2.Y-Sin(MeasureAngle)*5.0),1,clBlack);
AddTempLine(Round(SnapPos1.X+Cos(MeasureAngle+Pi*0.5)*10.0),Round(SnapPos1.Y+Sin(MeasureAngle+Pi*0.5)*10.0),Round(SnapPos1.X-Cos(MeasureAngle+Pi*0.5)*10.0),Round(SnapPos1.Y-Sin(MeasureAngle+Pi*0.5)*10.0),1,clBlack);
AddTempLine(Round(SnapPos2.X+Cos(MeasureAngle+Pi*0.5)*10.0),Round(SnapPos2.Y+Sin(MeasureAngle+Pi*0.5)*10.0),Round(SnapPos2.X-Cos(MeasureAngle+Pi*0.5)*10.0),Round(SnapPos2.Y-Sin(MeasureAngle+Pi*0.5)*10.0),1,clBlack);
AddTempLine(Round(SnapPos1.X+Cos(MeasureAngle+Pi*0.5)*10.0),Round(SnapPos1.Y+Sin(MeasureAngle+Pi*0.5)*10.0),Round(SnapPos1.X-Cos(MeasureAngle+Pi*0.5)*10.0),Round(SnapPos1.Y-Sin(MeasureAngle+Pi*0.5)*10.0),1,clBlack);
AddTempLine(Round(SnapPos1.X+Cos(MeasureAngle)*5.0),Round(SnapPos1.Y+Sin(MeasureAngle)*5.0),Round(SnapPos1.X-Cos(MeasureAngle+Pi*0.8)*15.0),Round(SnapPos1.Y-Sin(MeasureAngle+Pi*0.8)*15.0),1,clBlack);
AddTempLine(Round(SnapPos1.X+Cos(MeasureAngle)*5.0),Round(SnapPos1.Y+Sin(MeasureAngle)*5.0),Round(SnapPos1.X-Cos(MeasureAngle-Pi*0.8)*15.0),Round(SnapPos1.Y-Sin(MeasureAngle-Pi*0.8)*15.0),1,clBlack);
AddTempLine(Round(SnapPos2.X-Cos(MeasureAngle)*5.0),Round(SnapPos2.Y-Sin(MeasureAngle)*5.0),Round(SnapPos2.X+Cos(MeasureAngle+Pi*0.8)*15.0),Round(SnapPos2.Y+Sin(MeasureAngle+Pi*0.8)*15.0),1,clBlack);
AddTempLine(Round(SnapPos2.X-Cos(MeasureAngle)*5.0),Round(SnapPos2.Y-Sin(MeasureAngle)*5.0),Round(SnapPos2.X+Cos(MeasureAngle-Pi*0.8)*15.0),Round(SnapPos2.Y+Sin(MeasureAngle-Pi*0.8)*15.0),1,clBlack);
end;
StatusBar1.Panels[4].Text := 'Tool: Measure - ('+inttostr(GridPos1.X)+','+inttostr(GridPos1.Y)+') -> ('+inttostr(GridPos2.X)+','+inttostr(GridPos2.Y)+') Offset - ('+inttostr(GridOffset.X)+','+inttostr(GridOffset.Y)+') Length - ('+FloatToStrF(Sqrt(GridOffset.X*GridOffset.X+GridOffset.Y*GridOffset.Y),ffFixed,100,3)+')';
RepaintViews;
end;
end;
end
else if ssRight in Shift then
begin
case VxlTool of
VXLTool_Brush:
begin
v.Used := false;
v.Colour := 0;
v.Normal := 0;
VXLBrushTool(Document.ActiveSection^,LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v,VXLBrush,Document.ActiveSection^.View[0].GetOrient);
RepaintViews;
end;
VxlTool_Line:
begin
if ValidLastClick then
begin
V.Used := False;
V.Colour := 0;
V.Normal := 0;
drawstraightline(Document.ActiveSection^,TempView,LastClick[0],LastClick[1],V);
RepaintViews;
end;
end;
VXLTool_Rectangle:
begin
if ValidLastClick then
begin
V.Used := False;
V.Colour := 0;
V.Normal := 0;
VXLRectangle(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,LastClick[1].X,LastClick[1].Y,LastClick[1].Z,false,v);
RepaintViews;
end;
end;
VXLTool_FilledRectangle:
begin
if ValidLastClick then
begin
V.Used := False;
V.Colour := 0;
V.Normal := 0;
VXLRectangle(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,LastClick[1].X,LastClick[1].Y,LastClick[1].Z,true,v);
RepaintViews;
end;
end;
end; // tool switch
end
else
begin
OldMousePos.X := X;
OldMousePos.Y := Y;
//TranslateClick2(0,X,Y,LastClick[0].X,LastClick[0].Y,LastClick[0].Z);
with Document.ActiveSection^.Tailer do
if (LastClick[0].X < 0) or (LastClick[0].Y < 0) or (LastClick[0].Z < 0) or (LastClick[0].X >= XSize) or (LastClick[0].Y >= YSize) or (LastClick[0].Z >= ZSize) then
begin
if TempView.Data_no > 0 then
begin
TempView.Data_no := 0;
Setlength(TempView.Data,0);
CnvView[0].Repaint;
end;
Mouse_Current := crDefault;
CnvView[0].Cursor := Mouse_Current;
Exit;
end;
SetCursor;
if ssAlt in Shift then
begin
Mouse_Current := MouseDropper;
CnvView[0].Repaint;
end;
CnvView[0].Cursor := Mouse_Current;
if TempView.Data_no > 0 then
begin
TempView.Data_no := 0;
Setlength(TempView.Data,0);
//CnvView[0].Repaint;
end;
if (not DisableDrawPreview1.Checked) and (not (ssAlt in Shift)) then
begin
case VXLTool of
VXLTool_Brush:
begin
if (VXLBrush <> 4) then
begin
Document.ActiveSection^.GetVoxel(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v);
if (SpectrumMode = ModeColours) or (v.Used=False) then
v.Colour := ActiveColour;
if (SpectrumMode = ModeNormals) or (v.Used=False) then
v.Normal := ActiveNormal;
v.Used := True;
VXLBrushTool(Document.ActiveSection^,LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v,VXLBrush,Document.ActiveSection^.View[0].GetOrient);
// ActiveSection.BrushTool(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v,VXLBrush,ActiveSection.View[0].GetOrient);
CnvView[0].Repaint;
end;
end;
VXLTool_SmoothNormal:
begin
if VXLBrush <> 4 then
begin
Document.ActiveSection^.GetVoxel(LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v);
VXLSmoothBrushTool(Document.ActiveSection^,LastClick[0].X,LastClick[0].Y,LastClick[0].Z,v,VXLBrush,Document.ActiveSection^.View[0].GetOrient);
CnvView[0].Repaint;
end;
end;
end; // tool switch
end; // draw preview not disabled and alt not used.
end; // Which button is down
end // Is click not outside
else
begin
TempView.Data_no := 0;
Setlength(TempView.Data,0);
CnvView[0].Repaint;
end;
end; // open and editable
end;
procedure TFrmMain.lblView1Click(Sender: TObject);
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: lblView1Click');
{$endif}
ActivateView(1);
setupscrollbars;
end;
procedure TFrmMain.lblView2Click(Sender: TObject);
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: lblView2Click');
{$endif}
ActivateView(2);
setupscrollbars;
end;
procedure TFrmMain.mnuDirectionPopupPopup(Sender: TObject);
var
comp: TComponent;
idx: Integer;
View: TVoxelView;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: MenuDirectionPopupPopup');
{$endif}
comp := mnuDirectionPopup.PopupComponent;
mnuEdit.Visible := (comp <> lblView0); // can't edit as already editing it!
if comp = lblView0 then
View := Document.ActiveSection^.View[0]
else if comp = lblView1 then
View := Document.ActiveSection^.View[1]
else
View := Document.ActiveSection^.View[2];
idx := (View.getViewNameIdx div 2) * 2;
with mnuDirTowards do
begin
Caption := ViewName[idx];
Enabled := not (View.getDir = dirTowards);
end;
with mnuDirAway do
begin
Caption := ViewName[idx+1];
Enabled := not (View.getDir = dirAway);
end;
end;
procedure TFrmMain.mnuEditClick(Sender: TObject);
var comp: TComponent;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: MenuEditClick');
{$endif}
comp := mnuDirectionPopup.PopupComponent;
if comp = lblView1 then
ActivateView(1)
else
ActivateView(2);
end;
procedure TFrmMain.mnuDirTowardsClick(Sender: TObject);
procedure SetDir(WndIndex: Integer);
// var idx: Integer;
begin
with Document.ActiveSection^.View[WndIndex] do
begin
setDir(dirTowards);
// idx := getViewNameIdx;
//lblView[WndIndex].Caption := ViewName[idx];
SyncViews;
Refresh;
RepaintViews;
cnvView[WndIndex].Repaint;
end;
end;
var
i: Integer;
// KnownComponent: Boolean;
comp: TComponent;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: MenuDirTowardsClick');
{$endif}
comp := mnuDirectionPopup.PopupComponent;
//KnownComponent := False;
for i := 0 to 2 do
begin
if comp.Name = lblView[i].Name then
begin
SetDir(i);
Break;
end;
end;
end;
procedure TFrmMain.mnuDirAwayClick(Sender: TObject);
procedure SetDir(WndIndex: Integer);
begin
with Document.ActiveSection^.View[WndIndex] do
begin
setDir(dirAway);
SyncViews;
Refresh;
RepaintViews;
cnvView[WndIndex].Repaint;
end;
end;
var
i: Integer;
comp: TComponent;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: MenuDirAwayClick');
{$endif}
comp := mnuDirectionPopup.PopupComponent;
// KnownComponent := False;
for i := 0 to 2 do
begin
if comp.Name = lblView[i].Name then
begin
SetDir(i);
// KnownComponent := True;
Break;
end;
end;
end;
Procedure TFrmMain.SelectCorrectPalette2(Palette : String);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SelectCorrectPalette2');
{$endif}
if Palette = 'TS' then
iberianSunPalette1Click(nil)
else if Palette = 'RA2' then
RedAlert2Palette1Click(nil)
else if fileexists(ExtractFileDir(ParamStr(0)) + '\palettes\USER\' + Palette) then
begin
Document.Palette^.LoadPalette(ExtractFileDir(ParamStr(0)) + '\palettes\USER\' + Palette);
cnvPalette.Repaint;
end;
end;
Procedure TFrmMain.SelectCorrectPalette;
begin
if not Configuration.Palette then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SelectCorrectPalette');
{$endif}
if Document.ActiveVoxel^.Section[0].Tailer.NormalsType = 2 then
SelectCorrectPalette2(Configuration.TS)
else
SelectCorrectPalette2(Configuration.RA2);
end;
Procedure TFrmMain.CreateVxlError(v,n : Boolean);
var
frm : tFrmVxlError;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CreateVxlError');
{$endif}
frm:=TFrmVxlError.Create(Self);
frm.Visible:=False;
frm.Image1.Picture := TopBarImageHolder.Picture;
frm.TabSheet1.TabVisible := v;
frm.TabSheet2.TabVisible := n;
frm.ShowModal;
frm.Close;
frm.Free;
end;
procedure TFrmMain.Brush_1Click(Sender: TObject);
begin
VXLBrush := 0;
end;
procedure TFrmMain.Brush_2Click(Sender: TObject);
begin
VXLBrush := 1;
end;
procedure TFrmMain.Brush_3Click(Sender: TObject);
begin
VXLBrush := 2;
end;
procedure TFrmMain.Brush_4Click(Sender: TObject);
begin
VXLBrush := 3;
end;
procedure TFrmMain.Brush_5Click(Sender: TObject);
begin
VXLBrush := 4;
end;
procedure TFrmMain.SpeedButton3Click(Sender: TObject);
begin
SetVXLTool(VXLTool_Brush);
end;
Procedure TFrmMain.SetVXLTool(VXLTool_ : Integer);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetVXLTool');
{$endif}
SpeedButton3.Down := false;
SpeedButton4.Down := false;
SpeedButton5.Down := false;
SpeedButton6.Down := false;
SpeedButton7.Down := false;
SpeedButton8.Down := false;
SpeedButton9.Down := false;
SpeedButton10.Down := false;
SpeedButton11.Down := false;
SpeedButton12.Down := false;
SpeedButton13.Down := false;
SpeedButton14.Down := false;
if VXLTool_ = VXLTool_Brush then
begin
VXLToolName := 'Brush';
SpeedButton3.Down := true;
end
else if VXLTool_ = VXLTool_Line then
begin
VXLToolName := 'Line';
SpeedButton4.Down := true;
end
else if VXLTool_ = VXLTool_Erase then
begin
VXLToolName := 'Erase';
SpeedButton5.Down := true;
end
else if VXLTool_ = VXLTool_FloodFill then
begin
VXLToolName := 'Flood Fill';
SpeedButton10.Down := true;
end
else if VXLTool_ = VXLTool_FloodFillErase then
begin
VXLToolName := 'Flood Erase';
SpeedButton13.Down := true;
end
else if VXLTool_ = VXLTool_Dropper then
begin
VXLToolName := 'Dropper';
SpeedButton11.Down := true;
end
else if VXLTool_ = VXLTool_Rectangle then
begin
VXLToolName := 'Rectangle';
SpeedButton6.Down := true;
end
else if VXLTool_ = VXLTool_FilledRectangle then
begin
VXLToolName := 'Filled Rectange';
SpeedButton8.Down := true;
end
else if VXLTool_ = VXLTool_Darken then
begin
VXLToolName := 'Darken';
SpeedButton7.Down := true;
end
else if VXLTool_ = VXLTool_Lighten then
begin
VXLToolName := 'Lighten';
SpeedButton12.Down := true;
end
else if VXLTool_ = VXLTool_SmoothNormal then
begin
VXLToolName := 'Smooth Normals';
SpeedButton9.Down := true;
end
else if VXLTool_ = VXLTool_Measure then
begin
VXLToolName := 'Measure';
SpeedButton14.Down := true;
end;
StatusBar1.Panels[4].Text := 'Tool: '+VXLToolName;
VXLTool := VXLTool_;
end;
procedure TFrmMain.CnvView0MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if VoxelOpen and IsEditable then
begin
TranslateClick2(0,X,Y,LastClick[0].X,LastClick[0].Y,LastClick[0].Z);
if (LastClick[0].X < 0) or (LastClick[0].Y < 0) or (LastClick[0].Z < 0) then Exit;
with Document.ActiveSection^.Tailer do
if (LastClick[0].X >= XSize) or (LastClick[0].Y >= YSize) or (LastClick[0].Z >= ZSize) then Exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CnvView0MouseDown');
{$endif}
if (VXLTool = VXLTool_Line) or (VXLTool = VXLTool_FilledRectangle) or (VXLTool = VXLTool_Rectangle) then
begin
LastClick[1].X := LastClick[0].X;
LastClick[1].Y := LastClick[0].Y;
LastClick[1].Z := LastClick[0].Z;
ValidLastClick := true;
end;
if button = mbleft then
begin
if TempView.Data_no > 0 then
begin
TempView.Data_no := 0;
Setlength(TempView.Data,0);
end;
// isLeftMouseDown := true;
CnvView0MouseMove(sender,shift,x,y);
end;
end;
end;
procedure TFrmMain.SpeedButton5Click(Sender: TObject);
begin
SetVXLTool(VXLTool_Erase);
end;
procedure TFrmMain.SpeedButton4Click(Sender: TObject);
begin
SetVXLTool(VXLTool_Line);
end;
procedure TFrmMain.SpeedButton10Click(Sender: TObject);
begin
SetVXLTool(VXLTool_FloodFill);
end;
procedure TFrmMain.SpeedButton11Click(Sender: TObject);
begin
SetVXLTool(VXLTool_Dropper);
end;
procedure TFrmMain.SpeedButton6Click(Sender: TObject);
begin
SetVXLTool(VXLTool_Rectangle);
end;
procedure TFrmMain.SpeedButton8Click(Sender: TObject);
begin
SetVXLTool(VXLTool_FilledRectangle);
end;
procedure TFrmMain.Save1Click(Sender: TObject);
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Save1Click');
{$endif}
if VXLFilename <> '' then
begin
if FileExists(VXLFilename) then
begin
// ShowBusyMessage('Saving...');
Document.SaveDocument(VXLFilename);
SetVoxelChanged(false);
// HideBusyMessage;
end
else
SaveAs1Click(Sender);
end
else
begin
SaveAs1Click(Sender);
end;
end;
procedure TFrmMain.Exit1Click(Sender: TObject);
begin
Close;
end;
procedure TFrmMain.SaveAs1Click(Sender: TObject);
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SaveAs1Click');
{$endif}
if SaveVXLDialog.Execute then
begin
Document.SaveDocument(SaveVXLDialog.FileName);
VXLFilename := SaveVXLDialog.Filename;
SetVoxelChanged(false);
Configuration.AddFileToHistory(VXLFilename);
UpdateHistoryMenu;
end;
end;
procedure TFrmMain.VoxelHeader1Click(Sender: TObject);
var
FrmHeader: TFrmHeader;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: VoxelHeader1Click');
{$endif}
FrmHeader:=TFrmHeader.Create(Self);
with FrmHeader do
begin
SetValues(Document.ActiveVoxel,Document.ActiveHVA);
PageControl1.ActivePage := PageControl1.Pages[1];
Image2.Picture := TopBarImageHolder.Picture;
ShowModal;
RefreshAll;
Release;
end;
end;
procedure TFrmMain.N6Click(Sender: TObject);
var
FrmHeader: TFrmHeader;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: N6Click');
{$endif}
FrmHeader:=TFrmHeader.Create(Self);
with FrmHeader do
begin
SetValues(Document.ActiveVoxel,Document.ActiveHVA);
PageControl1.ActivePage := PageControl1.Pages[0];
Image2.Picture := TopBarImageHolder.Picture;
ShowModal;
Release;
end;
end;
Procedure TFrmMain.UpdateUndo_RedoState;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: UpdateUndo_RedoState');
{$endif}
mnuBarUndo.Enabled := IsUndoRedoUsed(Undo);
mnuBarRedo.Enabled := IsUndoRedoUsed(Redo);
Undo1.Enabled := mnuBarUndo.Enabled;
Redo1.Enabled := mnuBarRedo.Enabled;
end;
function TFrmMain.GetVoxelImportedBy3ds2vxl(var _Destination: string): boolean;
var
SEInfo : TShellExecuteInfo;
ExitCode : dword;
OptionsFile : TINIFile;
begin
// check if the location from 3ds2vxl exists.
Result := false;
while (not FileExists(Configuration.Location3ds2vxl)) or (not FileExists(Configuration.INILocation3ds2vxl)) do
begin
ShowMessage('Please inform the location of the 3ds2vxl executable. If you do not have it, download it from http://get3ds2vxl.ppmsite.com.');
if OpenDialog3ds2vxl.Execute then
begin
Configuration.Location3ds2vxl := OpenDialog3ds2vxl.FileName;
Configuration.INILocation3ds2vxl := IncludeTrailingPathDelimiter(ExtractFileDir(OpenDialog3ds2vxl.FileName)) + '3DS2VXL FE.ini';
end
else
begin
exit;
end;
end;
SEInfo := RunProgram(Configuration.Location3ds2vxl,'',ExtractFileDir(Configuration.Location3ds2vxl));
if SEInfo.hInstApp > 32 then
begin
repeat
Sleep(2000);
Application.ProcessMessages;
GetExitCodeProcess(SEInfo.hProcess, ExitCode);
until (ExitCode <> STILL_ACTIVE) or Application.Terminated;
// Once it's over, let's check the created file.
OptionsFile := TINIFile.Create(Configuration.INILocation3ds2vxl);
if (OptionsFile.ReadInteger('main','enable_voxelizer',0) = 1) and (OptionsFile.ReadInteger('main','activate_batch_voxelization',1) = 0) then
begin
_Destination := OptionsFile.ReadString('main','destination','');
if FileExists(_Destination) then
begin
Result := true;
end;
end;
end;
end;
procedure TFrmMain.using3ds2vxl1Click(Sender: TObject);
var
Destination : string;
begin
if GetVoxelImportedBy3ds2vxl(Destination) then
begin
OpenVoxelInterface(Destination);
end;
end;
procedure TFrmMain.mnuBarUndoClick(Sender: TObject);
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: MenuBarUndoClick');
{$endif}
UndoRestorePoint(Undo,Redo);
UpdateUndo_RedoState;
UpdateViews;
SetupStatusBar;
RefreshAll;
end;
procedure TFrmMain.mnuBarRedoClick(Sender: TObject);
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: MenuBarRedoClick');
{$endif}
RedoRestorePoint(Undo,Redo);
UpdateUndo_RedoState;
UpdateViews;
SetupStatusBar;
RefreshAll;
end;
procedure TFrmMain.updatenormals1Click(Sender: TObject);
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: UpdateNormals1Click');
{$endif}
// ask the user to confirm
if MessageDlg('Autonormals v1.1' +#13#13+
'This process will modify the voxel''s normals.' +#13+
'If you choose to do this, you should first save' + #13 +
'your model under a different name as a backup.',
mtWarning,mbOKCancel,0) = mrCancel then
Exit;
//ResetUndoRedo;
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
if ApplyNormalsToVXL(Document.ActiveSection^) > 0 then
if MessageDlg('Some were Confused, This may mean there are redundant voxels.'+#13#13+'Run Remove Redundant Voxels?',mtConfirmation,[mbYes,mbNo],0) = mrYes then
RemoveRedundantVoxels1Click(Sender);
Refreshall;
SetVoxelChanged(true);
end;
procedure TFrmMain.CubedAutoNormals1Click(Sender: TObject);
var
FrmAutoNormals : TFrmAutoNormals;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CubedAutoNormals1Click');
{$endif}
// One AutoNormals to rule them all!
FrmAutoNormals := TFrmAutoNormals.Create(self);
FrmAutoNormals.MyVoxel := Document.ActiveSection^;
FrmAutoNormals.ShowModal;
FrmAutoNormals.Release;
end;
procedure TFrmMain.Delete1Click(Sender: TObject);
var
SectionIndex,i: Integer;
begin
if not isEditable then exit;
if Document.ActiveVoxel^.Header.NumSections<2 then
begin
MessageDlg('Warning: We can not delete this section if there is only 1 section!',mtWarning,[mbOK],0);
Exit;
end;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Delete1Click');
{$endif}
// ask the user to confirm
if MessageDlg('Delete Section' +#13#13+
'This process will delete the current section.' +#13+
'This cannot be undone. If you choose to do this, you should first save' + #13 +
'your model under a different name as a backup.',
mtWarning,mbOKCancel,0) = mrCancel then
Exit;
//we can't undo these actions!!!
ResetUndoRedo;
UpdateUndo_RedoState;
SetisEditable(False);
SectionIndex:=Document.ActiveSection^.Header.Number;
Document.ActiveVoxel^.RemoveSection(SectionIndex);
Document.ActiveHVA^.DeleteSection(SectionIndex);
SectionCombo.Items.Clear;
for i:=0 to Document.ActiveVoxel^.Header.NumSections-1 do
begin
SectionCombo.Items.Add(Document.ActiveVoxel^.Section[i].Name);
end;
SectionCombo.ItemIndex:=0;
SectionComboChange(Self);
SetisEditable(True);
SetVoxelChanged(true);
Refreshall;
end;
procedure TFrmMain.normalsaphere1Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: NormalSphere1Click');
{$endif}
//Update3dViewWithNormals(Document.ActiveSection^);
end;
procedure TFrmMain.RemoveRedundantVoxels1Click(Sender: TObject);
var no{, i}: integer;
label Done;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: RemoveRedundantVoxels1Click');
{$endif}
// ensure the user wants to do this!
if MessageDlg('Remove Redundant Voxels (8-Neighbors)' +#13#13+
'This process will remove voxels that are hidden from view.' +#13+
'If you choose to do this, you should first save' + #13 +
'your model under a different name as a backup.',
mtWarning,mbOKCancel,0) = mrCancel then exit;
// stop undo's
// ResetUndoRedo;
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
// ok, do it
no := RemoveRedundantVoxelsFromVXL(Document.ActiveSection^);
if no = 0 then
ShowMessage('Remove Redundant Voxels (8-Neighbors)' +#13#13+ 'Removed: 0')
else
begin
ShowMessage('Remove Redundant Voxels (8-Neighbors)' +#13#13+ 'Removed: ' + IntToStr(no));
RefreshAll;
SetVoxelChanged(true);
end;
end;
procedure TFrmMain.RemoveRedundantVoxelsB1Click(Sender: TObject);
var
RemoveCount: Cardinal;
TimeUsed: Cardinal;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: RemoveRedundantVoxelsB1Click');
{$endif}
// ensure the user wants to do this!
if MessageDlg('Remove Redundant Voxels (4-Neighbors)' +#13#13+
'This process will remove voxels that are hidden from view.' +#13+
'If you choose to do this, you should first save' + #13 +
'your model under a different name as a backup.',
mtWarning,mbOKCancel,0) = mrCancel then exit;
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
TimeUsed := GetTickCount;
RemoveCount := velRemoveRedundantVoxels(Document.ActiveSection^);
TimeUsed := GetTickCount - TimeUsed;
ShowMessage('Remove redundant Voxels (4-Neighbors)' +#13#13+ 'Removed: ' + IntToStr(RemoveCount)
+ #13 + 'Time used: ' + IntToStr(TimeUsed) + 'ms');
if RemoveCount > 0 then
begin
RefreshAll;
SetVoxelChanged(true);
end;
end;
procedure TFrmMain.ClearEntireSection1Click(Sender: TObject);
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: ClearEntireSection1Click');
{$endif}
if MessageDlg('Clear Section' +#13#13+
'This process will remove all voxels from the current section.' +#13+
'If you choose to do this, you should first save' + #13 +
'your model under a different name as a backup.',
mtWarning,mbOKCancel,0) = mrCancel then exit;
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
Document.ActiveSection^.Clear;
SetVoxelChanged(true);
RefreshAll;
end;
procedure TFrmMain.VXLSEHelp1Click(Sender: TObject);
begin
if not fileexists(extractfiledir(paramstr(0))+'/help.chm') then
begin
messagebox(0,'VXLSE Help' + #13#13 + 'help.chm not found','VXLSE Help',0);
exit;
end;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: VXLSEHelp1Click');
{$endif}
RunAProgram('help.chm','',extractfiledir(paramstr(0)));
end;
procedure TFrmMain.Display3dView1Click(Sender: TObject);
begin
Display3dView1.Checked := not Display3dView1.Checked;
Disable3dView1.Checked := Display3dView1.Checked;
Env.SetIsEnabled(not Display3dView1.Checked);
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Display3DView1Click');
{$endif}
if Display3dView1.Checked then
begin
if (p_Frm3DPreview = nil) and (p_Frm3DModelizer = nil) then
begin
Application.OnIdle := nil;
end
else
begin
Application.OnIdle := Idle;
end;
end
else
begin
Application.OnIdle := Idle;
end;
OGL3DPreview.Refresh;
end;
procedure TFrmMain.About1Click(Sender: TObject);
var
frm: TLoadFrm;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: About1Click');
{$endif}
frm:=TLoadFrm.Create(Self);
frm.Visible:=False;
if testbuild then
frm.Label4.Caption := APPLICATION_VER + ' TB '+testbuildversion
else
frm.Label4.Caption := APPLICATION_VER;
frm.Image2.Visible := false;
frm.butOK.Visible:=True;
frm.Loading.Caption:='';
frm.ShowModal;
frm.Close;
frm.Free;
end;
procedure TFrmMain.FlipZswitchFrontBack1Click(Sender: TObject);
begin
//Create a transformation matrix...
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
Document.ActiveSection^.FlipMatrix([1,1,-1],[0,0,1]);
RefreshAll;
SetVoxelChanged(true);
end;
procedure TFrmMain.FillUselessInternalCavesVeryStrict1Click(Sender: TObject);
var
Tool: TFillUselessGapsTool;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: FillUselessInternalGapsVeryStrict1Click');
{$endif}
// ensure the user wants to do this!
if MessageDlg('Fill Useless Internal Caves (Aggressive)' +#13#13+
'This process will add black voxels at caves that are hidden from view.' +#13+
'If you choose to do this, you should first save' + #13 +
'your model under a different name as a backup.',
mtWarning,mbOKCancel,0) = mrCancel then exit;
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
Tool := TFillUselessGapsTool.Create(Document.ActiveSection^);
Tool.FillCaves(Document.ActiveSection^,0,4,63);
Tool.Free;
RefreshAll;
SetVoxelChanged(true);
end;
procedure TFrmMain.FillUselessInternalGaps1Click(Sender: TObject);
var
Tool: TFillUselessGapsTool;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: FillUselessInternalGaps1Click');
{$endif}
// ensure the user wants to do this!
if MessageDlg('Fill Useless Internal Caves (Conservative)' +#13#13+
'This process will add black voxels at caves that are hidden from view.' +#13+
'If you choose to do this, you should first save' + #13 +
'your model under a different name as a backup.',
mtWarning,mbOKCancel,0) = mrCancel then exit;
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
Tool := TFillUselessGapsTool.Create(Document.ActiveSection^);
Tool.FillCaves(Document.ActiveSection^);
Tool.Free;
RefreshAll;
SetVoxelChanged(true);
end;
procedure TFrmMain.FlipXswitchRightLeft1Click(Sender: TObject);
begin
//Create a transformation matrix...
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
Document.ActiveSection^.FlipMatrix([-1,1,1],[1,0,0]);
RefreshAll;
SetVoxelChanged(true);
end;
procedure TFrmMain.FlipYswitchTopBottom1Click(Sender: TObject);
begin
//Create a transformation matrix...
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
Document.ActiveSection^.FlipMatrix([1,-1,1],[0,1,0]);
RefreshAll;
SetVoxelChanged(true);
end;
procedure TFrmMain.MirrorBottomToTop1Click(Sender: TObject);
var
FlipFirst: Boolean;
begin
FlipFirst:=False;
if (Sender.ClassNameIs('TMenuItem')) then
begin
if CompareStr((Sender as TMenuItem).Name,'MirrorTopToBottom1')=0 then
begin
//flip first!
FlipFirst:=True;
end;
end;
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
//Based on the current view...
case Document.ActiveSection^.View[0].GetViewNameIdx of
0:
begin
if not FlipFirst then Document.ActiveSection^.FlipMatrix([1,1,-1],[0,0,1]);
Document.ActiveSection^.Mirror(oriZ);
end;
1:
begin
if not FlipFirst then Document.ActiveSection^.FlipMatrix([1,1,-1],[0,0,1]);
Document.ActiveSection^.Mirror(oriZ);
end;
2:
begin
if not FlipFirst then Document.ActiveSection^.FlipMatrix([1,1,-1],[0,0,1]);
Document.ActiveSection^.Mirror(oriZ);
end;
3:
begin
if not FlipFirst then Document.ActiveSection^.FlipMatrix([1,1,-1],[0,0,1]);
Document.ActiveSection^.Mirror(oriZ);
end;
4:
begin
if not FlipFirst then Document.ActiveSection^.FlipMatrix([1,-1,1],[0,1,0]);
Document.ActiveSection^.Mirror(oriY);
end;
5:
begin
if not FlipFirst then Document.ActiveSection^.FlipMatrix([1,-1,1],[0,1,0]);
Document.ActiveSection^.Mirror(oriY);
end;
end;
RefreshAll;
SetVoxelChanged(true);
end;
procedure TFrmMain.MirrorLeftToRight1Click(Sender: TObject);
var
FlipFirst: Boolean;
begin
FlipFirst:=False;
if (Sender.ClassNameIs('TMenuItem')) then
begin
if CompareStr((Sender as TMenuItem).Name,'MirrorLeftToRight1')=0 then
begin
//flip first!
FlipFirst:=True;
// ActiveSection.FlipMatrix([1,-1,1],[0,1,0]);
end;
end;
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
//Based on the current view...
case Document.ActiveSection^.View[0].GetViewNameIdx of
0:
begin
if FlipFirst then
Document.ActiveSection^.FlipMatrix([1,-1,1],[0,1,0]);
Document.ActiveSection^.Mirror(oriY);
end;
1:
begin
//reverse here :) (reversed view, that's why!)
if not FlipFirst then
Document.ActiveSection^.FlipMatrix([1,-1,1],[0,1,0]);
Document.ActiveSection^.Mirror(oriY);
end;
2:
begin
if FlipFirst then
Document.ActiveSection^.FlipMatrix([-1,1,1],[1,0,0]);
Document.ActiveSection^.Mirror(oriX);
end;
3:
begin
if not FlipFirst then
Document.ActiveSection^.FlipMatrix([-1,1,1],[1,0,0]);
Document.ActiveSection^.Mirror(oriX);
end;
4:
begin
if FlipFirst then
Document.ActiveSection^.FlipMatrix([-1,1,1],[1,0,0]);
Document.ActiveSection^.Mirror(oriX);
end;
5:
begin
if not FlipFirst then
Document.ActiveSection^.FlipMatrix([-1,1,1],[1,0,0]);
Document.ActiveSection^.Mirror(oriX);
end;
end;
RefreshAll;
SetVoxelChanged(true);
end;
procedure TFrmMain.MirrorBackToFront1Click(Sender: TObject);
begin
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
FlipZswitchFrontBack1Click(Sender);
Document.ActiveSection^.Mirror(oriZ);
RefreshAll;
SetVoxelChanged(true);
end;
procedure TFrmMain.MirrorFrontToBack1Click(Sender: TObject);
begin
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
Document.ActiveSection^.Mirror(oriZ);
RefreshAll;
SetVoxelChanged(true);
end;
procedure TFrmMain.Nudge1Left1Click(Sender: TObject);
var
i: Integer;
NR: Array[0..2] of Single;
begin
NR[0]:=0; NR[1]:=0; NR[2]:=0;
if (Sender.ClassNameIs('TMenuItem')) then
begin
if (CompareStr((Sender as TMenuItem).Name,'Nudge1Left1')=0) or (CompareStr((Sender as TMenuItem).Name,'Nudge1Right1')=0) then
begin
//left and right
case Document.ActiveSection^.View[0].GetViewNameIdx of
0: NR[2]:=1;
1: NR[2]:=-1;
2: NR[2]:=-1;
3: NR[2]:=-1;
4: NR[0]:=1;
5: NR[0]:=-1;
end;
if CompareStr((Sender as TMenuItem).Name,'Nudge1Right1')=0 then
begin
for i:=0 to 2 do
begin
NR[i]:=-NR[i];
end;
end;
end
else
begin
//up and down
case Document.ActiveSection^.View[0].GetViewNameIdx of
0: NR[1]:=-1;
1: NR[1]:=-1;
2: NR[0]:=1;
3: NR[0]:=-1;
4: NR[1]:=-1;
5: NR[1]:=-1;
end;
if CompareStr((Sender as TMenuItem).Name,'Nudge1up1')=0 then
begin
for i:=0 to 2 do
begin
NR[i]:=-NR[i];
end;
end;
end;
end;
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
Document.ActiveSection^.FlipMatrix([1,1,1],NR,False);
RefreshAll;
SetVoxelChanged(true);
end;
procedure TFrmMain.RotateYawNegativeClick(Sender: TObject);
var
i: Integer;
Matrix: BasicMathsTypes.TGLMatrixf4;
begin
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
Matrix[0,1] := 1;
Matrix[1,0] := -1;
Matrix[2,2] := 1;
Matrix[3,3] := 1;
SetIsEditable(false);
Document.ActiveSection^.ApplyMatrix(Matrix, not MaintainDimensions1.Checked);
SetIsEditable(true);
if not MaintainDimensions1.Checked then
begin
UpdateViews;
SetupStatusBar;
CursorReset;
end;
RefreshAll;
SetVoxelChanged(true);
end;
procedure TFrmMain.RotateYawPositiveClick(Sender: TObject);
var
i: Integer;
Matrix: BasicMathsTypes.TGLMatrixf4;
begin
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
Matrix[0,1] := -1;
Matrix[1,0] := 1;
Matrix[2,2] := 1;
Matrix[3,3] := 1;
SetIsEditable(false);
Document.ActiveSection^.ApplyMatrix(Matrix, not MaintainDimensions1.Checked);
SetIsEditable(true);
if not MaintainDimensions1.Checked then
begin
UpdateViews;
SetupStatusBar;
CursorReset;
end;
RefreshAll;
SetVoxelChanged(true);
end;
procedure TFrmMain.RotatePitchNegativeClick(Sender: TObject);
var
i: Integer;
Matrix: BasicMathsTypes.TGLMatrixf4;
begin
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
Matrix[0,2] := -1;
Matrix[2,0] := 1;
Matrix[1,1] := 1;
Matrix[3,3] := 1;
SetIsEditable(false);
Document.ActiveSection^.ApplyMatrix(Matrix, not MaintainDimensions1.Checked);
SetIsEditable(true);
if not MaintainDimensions1.Checked then
begin
UpdateViews;
SetupStatusBar;
CursorReset;
end;
RefreshAll;
SetVoxelChanged(true);
end;
procedure TFrmMain.RotatePitchPositiveClick(Sender: TObject);
var
i: Integer;
Matrix: BasicMathsTypes.TGLMatrixf4;
begin
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
Matrix[0,2] := 1;
Matrix[2,0] := -1;
Matrix[1,1] := 1;
Matrix[3,3] := 1;
SetIsEditable(false);
Document.ActiveSection^.ApplyMatrix(Matrix, not MaintainDimensions1.Checked);
SetIsEditable(true);
if not MaintainDimensions1.Checked then
begin
UpdateViews;
SetupStatusBar;
CursorReset;
end;
RefreshAll;
SetVoxelChanged(true);
end;
procedure TFrmMain.RotateRollNegativeClick(Sender: TObject);
var
i: Integer;
Matrix: BasicMathsTypes.TGLMatrixf4;
begin
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
Matrix[1,2] := 1;
Matrix[2,1] := -1;
Matrix[0,0] := 1;
Matrix[3,3] := 1;
SetIsEditable(false);
Document.ActiveSection^.ApplyMatrix(Matrix, not MaintainDimensions1.Checked);
SetIsEditable(true);
if not MaintainDimensions1.Checked then
begin
UpdateViews;
SetupStatusBar;
CursorReset;
end;
RefreshAll;
SetVoxelChanged(true);
end;
procedure TFrmMain.RotateRollPositiveClick(Sender: TObject);
var
i: Integer;
Matrix: BasicMathsTypes.TGLMatrixf4;
begin
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
Matrix[1,2] := -1;
Matrix[2,1] := 1;
Matrix[0,0] := 1;
Matrix[3,3] := 1;
SetIsEditable(false);
Document.ActiveSection^.ApplyMatrix(Matrix, not MaintainDimensions1.Checked);
SetIsEditable(true);
if not MaintainDimensions1.Checked then
begin
UpdateViews;
SetupStatusBar;
CursorReset;
end;
RefreshAll;
SetVoxelChanged(true);
end;
procedure TFrmMain.Section2Click(Sender: TObject);
var
i, SectionIndex: Integer;
FrmNewSectionSize: TFrmNewSectionSize;
OldVoxelType : TVoxelType;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Section2Click');
{$endif}
FrmNewSectionSize:=TFrmNewSectionSize.Create(Self);
with FrmNewSectionSize do
begin
ShowModal;
if aborted then Exit;
if MessageDlg('Create Section' + #13#13+ 'Are you sure you want to create a section: ' + #13#13 +
'Name: ' + AsciizToStr(Name,16) + Chr(10) +
'Size: ' + IntToStr(X) + 'x' + IntToStr(Y) + 'x' + IntToStr(Z),
mtConfirmation,[mbYes,mbNo],0) = mrNo then
exit;
SetisEditable(False);
SectionIndex:=Document.ActiveSection^.Header.Number;
if not before then //after
Inc(SectionIndex);
OldVoxelType := VoxelType;
VoxelType := vtAir;
Document.ActiveVoxel^.InsertSection(SectionIndex,Name,X,Y,Z);
SectionCombo.Items.Clear;
for i:=0 to Document.ActiveVoxel^.Header.NumSections-1 do
begin
SectionCombo.Items.Add(Document.ActiveVoxel^.Section[i].Name);
end;
Document.ActiveVoxel^.Section[SectionIndex].Tailer.NormalsType := Document.ActiveVoxel^.Section[0].Tailer.NormalsType;
Document.ActiveHVA^.InsertSection(SectionIndex);
VoxelType := OldVoxelType;
//MajorRepaint;
SectionCombo.ItemIndex:=SectionIndex;
SectionComboChange(Self);
ResetUndoRedo;
SetisEditable(True);
SetVoxelChanged(true);
end;
FrmNewSectionSize.Free;
end;
procedure TFrmMain.Copyofthissection1Click(Sender: TObject);
var
i, SectionIndex,x,y,z : Integer;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CopyOfThisSection1Click');
{$endif}
if MessageDlg('Copy Section' + #13#13+ 'Are you sure you want to make a copy of the current section?',
mtConfirmation,[mbYes,mbNo],0) = mrNo then
exit;
SectionIndex:=Document.ActiveSection^.Header.Number;
Inc(SectionIndex);
ResetUndoRedo;
UpdateUndo_RedoState;
Document.ActiveVoxel^.InsertSection(SectionIndex,'Copy Of '+Document.ActiveVoxel^.Section[SectionIndex-1].Name,Document.ActiveVoxel^.Section[SectionIndex-1].Tailer.XSize,Document.ActiveVoxel^.Section[SectionIndex-1].Tailer.YSize,Document.ActiveVoxel^.Section[SectionIndex-1].Tailer.ZSize);
Document.ActiveHVA^.InsertSection(SectionIndex);
Document.ActiveHVA^.CopySection(SectionIndex-1,SectionIndex);
for x := 0 to (Document.ActiveVoxel^.Section[SectionIndex-1].Tailer.XSize - 1) do
for y := 0 to (Document.ActiveVoxel^.Section[SectionIndex-1].Tailer.YSize - 1) do
for z := 0 to (Document.ActiveVoxel^.Section[SectionIndex-1].Tailer.ZSize - 1) do
Document.ActiveVoxel^.Section[SectionIndex].Data[x,y,z] := Document.ActiveVoxel^.Section[SectionIndex-1].Data[x,y,z];
with Document.ActiveVoxel^.Section[SectionIndex-1].Tailer do
begin
Document.ActiveVoxel^.Section[SectionIndex].Tailer.Det := Det;
for x := 1 to 3 do
begin
Document.ActiveVoxel^.Section[SectionIndex].Tailer.MaxBounds[x] := MaxBounds[x];
Document.ActiveVoxel^.Section[SectionIndex].Tailer.MinBounds[x] := MinBounds[x];
end;
Document.ActiveVoxel^.Section[SectionIndex].Tailer.SpanDataOfs := SpanDataOfs;
Document.ActiveVoxel^.Section[SectionIndex].Tailer.SpanEndOfs := SpanEndOfs;
Document.ActiveVoxel^.Section[SectionIndex].Tailer.SpanStartOfs := SpanStartOfs;
for x := 1 to 3 do
for y := 1 to 4 do
Document.ActiveVoxel^.Section[SectionIndex].Tailer.Transform[x,y] := Transform[x,y];
Document.ActiveVoxel^.Section[SectionIndex].Tailer.NormalsType := NormalsType;
end;
SectionCombo.Items.Clear;
for i:=0 to Document.ActiveVoxel^.Header.NumSections-1 do
begin
SectionCombo.Items.Add(Document.ActiveVoxel^.Section[i].Name);
end;
//MajorRepaint;
SectionCombo.ItemIndex:=SectionIndex;
SectionComboChange(Self);
SetVoxelChanged(true);
end;
procedure TFrmMain.CropSection1Click(Sender: TObject);
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CropSection1Click');
{$endif}
SetisEditable(False);
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
// Here we do the crop
Document.ActiveSection^.Crop;
SetisEditable(True);
RefreshAll;
SetVoxelChanged(true);
end;
procedure TFrmMain.mnuHistoryClick(Sender: TObject);
var
p: ^TMenuItem;
s,VoxelName : string;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: MenuHistoryClick');
{$endif}
if Sender.ClassNameIs('TMenuItem') then
begin //check to see if it is this class
//and now do some dirty things with pointers...
p:=@Sender;
s := Configuration.GetHistory(p^.Tag);
if not fileexists(s) then
begin
Messagebox(0,'File Doesn''t Exist','Load Voxel',0);
exit;
end;
VoxelName := Configuration.GetHistory(p^.Tag);
OpenVoxelInterface(VoxelName);
end;
end;
procedure TFrmMain.BuildReopenMenu;
var
i : integer;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: BuildReopenMenu');
{$endif}
Configuration := TConfiguration.Create;
for i:=HistoryDepth - 1 downto 0 do
begin
mnuHistory[i]:=TMenuItem.Create(Self);
mnuHistory[i].OnClick:=mnuHistoryClick;
mnuReOpen.Insert(0,mnuHistory[i]);
end;
UpdateHistoryMenu;
end;
procedure TFrmMain.BarReopenClick(Sender: TObject);
begin
//ReOpen1.Caption := Configuration.GetHistory(0);
end;
procedure TFrmMain.iberianSunPalette1Click(Sender: TObject);
begin
ApplyPalette(ExtractFileDir(ParamStr(0)) + '\palettes\TS\unittem.pal');
end;
procedure TFrmMain.RedAlert2Palette1Click(Sender: TObject);
begin
ApplyPalette(ExtractFileDir(ParamStr(0)) + '\palettes\RA2\unittem.pal');
end;
procedure TFrmMain.ApplyPalette(const _Filename: string);
begin
Document.Palette^.LoadPalette(_Filename);
if Actor <> nil then
Actor^.ChangePalette(_Filename);
if p_Frm3DPreview <> nil then
begin
p_Frm3DPreview^.Actor^.ChangePalette(_Filename);
end;
cnvPalette.Repaint;
RefreshAll;
end;
procedure TFrmMain.AutoUpdate1Click(Sender: TObject);
begin
// We'll test it later.
end;
Procedure TFrmMain.LoadPalettes;
var
c : integer;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: LoadPalettes');
{$endif}
PaletteControl := TPaletteControl.Create(Owner, blank1Click);
// prepare
c := 0;
// Now Load TS Palettes
PaletteControl.AddPalettesToSubMenu(TSPalettes, ExtractFilePath(ParamStr(0))+'Palettes\TS\', c, 15);
// Now Load RA2 Palettes
PaletteControl.AddPalettesToSubMenu(RA2Palettes, ExtractFilePath(ParamStr(0))+'Palettes\RA2\', c, 16);
// Now Load User's Palettes
PaletteControl.AddPalettesToSubMenu(Custom1, ExtractFilePath(ParamStr(0))+'Palettes\User\', c, 39);
end;
procedure TFrmMain.UpdatePaletteList1Click(Sender: TObject);
var
c : integer;
begin
c := 0;
PaletteControl.ResetPaletteSchemes;
PaletteControl.UpdatePalettesAtSubMenu(TSPalettes, ExtractFilePath(ParamStr(0))+'Palettes\TS\', c, 15);
PaletteControl.UpdatePalettesAtSubMenu(RA2Palettes, ExtractFilePath(ParamStr(0))+'Palettes\RA2\', c, 16);
PaletteControl.UpdatePalettesAtSubMenu(Custom1, ExtractFilePath(ParamStr(0))+'Palettes\User\', c, 39);
end;
procedure TFrmMain.blank1Click(Sender: TObject);
begin
ApplyPalette(PaletteControl.PaletteSchemes[TMenuItem(Sender).tag].Filename);
end;
Function TFrmMain.CheckVXLChanged: Boolean;
var
T : string;
Answer: integer;
begin
if VXLChanged then
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CheckVXLChanged');
{$endif}
T := ExtractFileName(VXLFilename);
if t = '' then
T := 'Do you want to save Untitled'
else
T := 'Do you want to save changes in ' + T;
Answer := MessageDlg('Last changes were not saved. ' + T + '? Answer YES to save and exit, NO to exit without saving and CANCEL to not exit nor save.',mtWarning,[mbYes,mbNo,mbCancel],0);
if Answer = mrYes then
begin
Save1.Click;
end;
Result := Answer <> MrCancel;
end
else
Result := true;
end;
procedure TFrmMain.SpeedButton7Click(Sender: TObject);
begin
SetVXLTool(VXLTool_Darken);
end;
procedure TFrmMain.SpeedButton12Click(Sender: TObject);
begin
SetVXLTool(VXLTool_Lighten);
end;
procedure TFrmMain.SpeedButton13Click(Sender: TObject);
begin
SetVXLTool(VXLTool_FloodFillErase);
end;
procedure TFrmMain.SpeedButton14Click(Sender: TObject);
begin
SetVXLTool(VXLTool_Measure);
end;
Procedure TFrmMain.SetDarkenLighten(Value : integer);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetDarkenLighten');
{$endif}
DarkenLighten := Value;
N110.Checked := false;
N21.Checked := false;
N31.Checked := false;
N41.Checked := false;
N51.Checked := false;
if Value = 1 then
N110.Checked := true
else if Value = 2 then
N21.Checked := true
else if Value = 3 then
N31.Checked := true
else if Value = 4 then
N41.Checked := true
else if Value = 5 then
N51.Checked := true;
end;
procedure TFrmMain.N110Click(Sender: TObject);
begin
SetDarkenLighten(1);
end;
procedure TFrmMain.N21Click(Sender: TObject);
begin
SetDarkenLighten(2);
end;
procedure TFrmMain.N31Click(Sender: TObject);
begin
SetDarkenLighten(3);
end;
procedure TFrmMain.N41Click(Sender: TObject);
begin
SetDarkenLighten(4);
end;
procedure TFrmMain.N51Click(Sender: TObject);
begin
SetDarkenLighten(5);
end;
procedure TFrmMain.ToolButton11Click(Sender: TObject);
var
x,y,z : integer;
v : tvoxelunpacked;
begin
if not isEditable then exit;
if MessageDlg('Clear Voxel Colour' +#13#13+
'This process will clear the voxels colours/normals with the currently selected colour.' +#13+
'If you choose to do this, you should first save' + #13 +
'your model under a different name as a backup.',
mtWarning,mbOKCancel,0) = mrCancel then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: ToolButton1Click');
{$endif}
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
for x := 0 to Document.ActiveSection^.Tailer.XSize-1 do
for y := 0 to Document.ActiveSection^.Tailer.YSize-1 do
for z := 0 to Document.ActiveSection^.Tailer.ZSize-1 do
begin
Document.ActiveSection^.GetVoxel(x,y,z,v);
if SpectrumMode = ModeColours then
v.Colour := ActiveColour
else
v.Normal := ActiveNormal;
Document.ActiveSection^.SetVoxel(x,y,z,v);
end;
RefreshAll;
SetVoxelChanged(true);
end;
procedure TFrmMain.ClearLayer1Click(Sender: TObject);
begin
if not isEditable then exit;
if MessageDlg('Clear Layer' +#13#13+
'This process will remove all voxels from the current layer.' +#13+
'If you choose to do this, you should first save' + #13 +
'your model under a different name as a backup.',
mtWarning,mbOKCancel,0) = mrCancel then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: ClearLayer1Click');
{$endif}
ClearVXLLayer(Document.ActiveSection^);
UpdateUndo_RedoState;
RefreshAll;
SetVoxelChanged(true);
end;
procedure TFrmMain.Copy1Click(Sender: TObject);
begin
if not isEditable then exit;
VXLCopyToClipboard(Document.ActiveSection^);
end;
procedure TFrmMain.Cut1Click(Sender: TObject);
begin
if not isEditable then exit;
VXLCutToClipboard(Document.ActiveSection^);
UpdateUndo_RedoState;
RefreshAll;
SetVoxelChanged(true);
end;
procedure TFrmMain.ClearUndoSystem1Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: ClearUndoSystem1Click');
{$endif}
ResetUndoRedo;
UpdateUndo_RedoState;
end;
procedure TFrmMain.PasteFull1Click(Sender: TObject);
begin
if not isEditable then exit;
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
PasteFullVXL(Document.ActiveSection^);
RefreshAll;
SetVoxelChanged(true);
end;
procedure TFrmMain.Paste1Click(Sender: TObject);
begin
if not isEditable then exit;
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
// --- 1.2: Removed
// PasteFullVXL(ActiveSection);
// --- Replaced with
PasteVXL(Document.ActiveSection^);
RefreshAll;
SetVoxelChanged(true);
end;
function TFrmMain.CreateSplitterMenuItem: TMenuItem;
begin
Result := TMenuItem.Create(Owner);
Result.Caption := '-';
end;
function TFrmMain.UpdateCScheme : integer;
begin
CustomSchemeControl.ResetColourSchemes;
Result := CustomSchemeControl.UpdateCSchemes(PalPack1, ExtractFilePath(ParamStr(0))+'\cschemes\PalPack1\',0, true, true);
Result := CustomSchemeControl.UpdateCSchemes(PalPack1, ExtractFilePath(ParamStr(0))+'\cschemes\PalPack2\',Result, true, false);
Result := CustomSchemeControl.UpdateCSchemes(Apollo1, ExtractFilePath(ParamStr(0))+'\cschemes\Apollo\',Result, true, true);
Result := CustomSchemeControl.UpdateCSchemes(ColourScheme1, ExtractFilePath(ParamStr(0))+'\cschemes\USER\',Result, true, true);
end;
function TFrmMain.LoadCScheme : integer;
begin
// New Custom Scheme loader goes here.
CustomSchemeControl := TCustomSchemeControl.Create(Owner, blank2Click);
Result := CustomSchemeControl.LoadCSchemes(PalPack1, ExtractFilePath(ParamStr(0))+'\cschemes\PalPack1\',0, false);
Result := CustomSchemeControl.LoadCSchemes(PalPack1, ExtractFilePath(ParamStr(0))+'\cschemes\PalPack2\',Result, false);
Result := CustomSchemeControl.LoadCSchemes(Apollo1, ExtractFilePath(ParamStr(0))+'\cschemes\Apollo\',Result, false);
Result := CustomSchemeControl.LoadCSchemes(ColourScheme1, ExtractFilePath(ParamStr(0))+'\cschemes\USER\',Result, false);
end;
procedure TFrmMain.blank2Click(Sender: TObject);
var
x,y,z : integer;
V : TVoxelUnpacked;
Scheme : TCustomScheme;
Data : TCustomSchemeData;
begin
Scheme := TCustomScheme.CreateForData(CustomSchemeControl.ColourSchemes[Tmenuitem(Sender).Tag].Filename);
Data := Scheme.Data;
tempview.Data_no := tempview.Data_no +0;
setlength(tempview.Data,tempview.Data_no +0);
for x := 0 to Document.ActiveSection^.Tailer.XSize-1 do
for y := 0 to Document.ActiveSection^.Tailer.YSize-1 do
for z := 0 to Document.ActiveSection^.Tailer.ZSize-1 do
begin
Document.ActiveSection^.GetVoxel(x,y,z,v);
if v.Used then
begin
V.Colour := Data[V.Colour];
tempview.Data_no := tempview.Data_no +1;
setlength(tempview.Data,tempview.Data_no +1);
tempview.Data[tempview.Data_no].VC.X := x;
tempview.Data[tempview.Data_no].VC.Y := y;
tempview.Data[tempview.Data_no].VC.Z := z;
tempview.Data[tempview.Data_no].VU := true;
tempview.Data[tempview.Data_no].V := v;
end;
end;
Scheme.Free;
ApplyTempView(Document.ActiveSection^);
UpdateUndo_RedoState;
RefreshAll;
end;
procedure TFrmMain.About2Click(Sender: TObject);
var
frm: TFrmPalettePackAbout;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: About2Click');
{$endif}
frm:=TFrmPalettePackAbout.Create(Self);
frm.Visible:=False;
frm.ShowModal;
frm.Close;
frm.Free;
end;
procedure TFrmMain.EmptyVoxel1Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: EmptyVoxel1Click');
{$endif}
NewVFile(2);
end;
procedure TFrmMain.EmptyVoxel2Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: EmptyVoxel2Click');
{$endif}
NewVFile(4);
end;
Procedure TFrmMain.NewVFile(Game : integer);
var
FrmNew: TFrmNew;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: NewVFile');
{$endif}
IsVXLLoading := true;
Application.OnIdle := nil;
CheckVXLChanged;
FrmNew:=TFrmNew.Create(Self);
with FrmNew do
begin
//FrmNew.Caption := ' New Voxel File';
Label9.Caption := 'New Voxel';
Label9.Caption := 'Enter the size you want the voxel to be';
//grpCurrentSize.Left := 400;
grpCurrentSize.Visible := false;
//grpNewSize.Width := 201;
grpNewSize.Left := (FrmNew.Width div 2) - (grpNewSize.Width div 2);
grpNewSize.Caption := 'Size';
BtCancel.Visible := false;
BtOK.Left := BtCancel.Left;
Image1.Picture := TopBarImageHolder.Picture;
//grpCurrentSize.Visible := true;
grpVoxelType.Visible := true;
x := 10;//ActiveSection.Tailer.XSize;
y := 10;//ActiveSection.Tailer.YSize;
z := 10;//ActiveSection.Tailer.ZSize;
ShowModal;
end;
// 1.3: Before creating the new voxel, we add the type support.
if FrmNew.rbLand.Checked then
VoxelType := vtLand
else
VoxelType := vtAir;
SetIsEditable(NewVoxel(Document,Game,FrmNew.x,FrmNew.y,FrmNew.z));
if IsEditable then
DoAfterLoadingThings;
IsVXLLoading := false;
end;
Procedure TFrmMain.SetCursor;
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SetCursor');
{$endif}
//CnvView[0].Cursor := Mouse_Current;
if VXLTool = VXLTool_Brush then
if VXLBrush = 4 then
Mouse_Current := MouseSpray
else
Mouse_Current := MouseDraw
else if VXLTool = VXLTool_Line then
Mouse_Current := MouseLine
else if VXLTool = VXLTool_Erase then
if VXLBrush = 4 then
Mouse_Current := MouseSpray
else
Mouse_Current := MouseDraw
else if VXLTool = VXLTool_FloodFill then
Mouse_Current := MouseFill
else if VXLTool = VXLTool_FloodFillErase then
Mouse_Current := MouseFill
else if VXLTool = VXLTool_Dropper then
Mouse_Current := MouseDropper
else if VXLTool = VXLTool_Rectangle then
Mouse_Current := MouseLine
else if VXLTool = VXLTool_FilledRectangle then
Mouse_Current := MouseLine
else if VXLTool = VXLTool_Darken then
if VXLBrush = 4 then
Mouse_Current := MouseSpray
else
Mouse_Current := MouseDraw
else if VXLTool = VXLTool_Lighten then
if VXLBrush = 4 then
Mouse_Current := MouseSpray
else
Mouse_Current := MouseDraw
else if VXLTool = VXLTool_SmoothNormal then
if VXLBrush = 4 then
Mouse_Current := MouseSpray
else
Mouse_Current := MouseSmoothNormal;
if not iseditable then
Mouse_Current := crDefault;
end;
procedure TFrmMain.DisableDrawPreview1Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: DisableDrawPreview1Click');
{$endif}
DisableDrawPreview1.Checked := not DisableDrawPreview1.Checked;
end;
procedure TFrmMain.SmoothNormals1Click(Sender: TObject);
begin
if not isEditable then exit;
// ask the user to confirm
if MessageDlg('Smooth Normals v1.0' +#13#13+
'This process will modify the voxel''s normals.' +#13+
'If you choose to do this, you should first save' + #13 +
'your model under a different name as a backup.',
mtWarning,mbOKCancel,0) = mrCancel then
Exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: SmoothNormals1Click');
{$endif}
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
SmoothVXLNormals(Document.ActiveSection^);
RefreshAll;
SetVoxelChanged(true);
end;
procedure TFrmMain.VoxelTexture1Click(Sender: TObject);
var
frm: TFrmVoxelTexture;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: VoxelTexture1Click');
{$endif}
frm:=TFrmVoxelTexture.Create(Self);
frm.Visible:=False;
frm.Image3.Picture := TopBarImageHolder.Picture;
frm.ShowModal;
frm.Close;
frm.Free;
end;
procedure TFrmMain.opologyAnalysis1Click(Sender: TObject);
var
Frm : TFrmTopologyAnalysis;
begin
Frm := TFrmTopologyAnalysis.Create(Document.ActiveSection^,self);
Frm.ShowModal;
Frm.Close;
Frm.Free;
end;
procedure TFrmMain.OpenHyperlink(HyperLink: PChar);
begin
ShellExecute(Application.Handle,nil,HyperLink,'','',SW_SHOWNORMAL);
end;
procedure TFrmMain.CnCSource1Click(Sender: TObject);
begin
OpenHyperLink('http://www.cnc-source.com/');
end;
procedure TFrmMain.PPMForUpdates1Click(Sender: TObject);
begin
OpenHyperLink('http://www.ppmsite.com/index.php?go=vxlseinfo');
end;
procedure TFrmMain.LoadSite(Sender : TObject);
begin
OpenHyperlink(PChar(FrmMain.SiteList[TMenuItem(Sender).Tag].SiteUrl));
end;
procedure TFrmMain.ProjectSVN1Click(Sender: TObject);
begin
OpenHyperLink('http://svn.ppmsite.com/');
end;
procedure TFrmMain.test1Click(Sender: TObject);
begin
// Update3dViewVOXEL(Document.ActiveVoxel^);
end;
procedure TFrmMain.ImportSectionFromVoxel(const _Filename: string);
var
TempDocument : TVoxelDocument;
i, SectionIndex,tempsectionindex: Integer;
frm: Tfrmimportsection;
begin
TempDocument := TVoxelDocument.Create(_FileName);
if TempDocument.ActiveVoxel = nil then
begin
TempDocument.Free;
exit;
end;
tempsectionindex := 0;
if TempDocument.ActiveVoxel^.Header.NumSections > 1 then
begin
frm:=Tfrmimportsection.Create(Self);
frm.Visible:=False;
frm.ComboBox1.Items.Clear;
for i:=0 to TempDocument.ActiveVoxel^.Header.NumSections-1 do
begin
frm.ComboBox1.Items.Add(TempDocument.ActiveVoxel^.Section[i].Name);
end;
frm.ComboBox1.ItemIndex:=0;
frm.ShowModal;
tempsectionindex := frm.ComboBox1.ItemIndex;
frm.Free;
end;
SetIsEditable(false);
SectionIndex:=Document.ActiveSection^.Header.Number;
Inc(SectionIndex);
Document.ActiveVoxel^.InsertSection(SectionIndex,TempDocument.ActiveVoxel^.Section[tempsectionindex].Name,TempDocument.ActiveVoxel^.Section[tempsectionindex].Tailer.XSize,TempDocument.ActiveVoxel^.Section[tempsectionindex].Tailer.YSize,TempDocument.ActiveVoxel^.Section[tempsectionindex].Tailer.ZSize);
Document.ActiveVoxel^.Section[SectionIndex].Assign(TempDocument.ActiveVoxel^.Section[tempsectionindex]);
Document.ActiveVoxel^.Section[SectionIndex].Header.Number := SectionIndex;
Document.ActiveHVA^.InsertSection(SectionIndex);
Document.ActiveHVA^.CopySection(tempsectionindex,SectionIndex,TempDocument.ActiveHVA^);
//MajorRepaint;
SectionCombo.ItemIndex:=SectionIndex;
SectionComboChange(Self);
ResetUndoRedo;
UpdateUndo_RedoState;
SetIsEditable(true);
SetupSections;
SetVoxelChanged(true);
end;
procedure TFrmMain.ImagewithHeightmap1Click(Sender: TObject);
var
Frm: TFrmHeightmap;
Img,Hmap : TBitmap;
x,y,z,h,curr: integer;
v : tvoxelunpacked;
begin
Frm := TFrmHeightmap.Create(self);
Frm.ShowModal;
if Frm.OK then
begin
if FileExists(Frm.EdImage.Text) and FileExists(Frm.EdHeightmap.Text) then
begin
Img := GetBMPFromImageFile(Frm.EdImage.Text);
Hmap := GetBMPFromImageFile(Frm.EdHeightmap.Text);
if Assigned(Img) and Assigned(Hmap) then
begin
if (Img.Height = Hmap.Height) and (Img.Width = Hmap.Width) then
begin
if (Img.Height > 255) or (Img.Width > 255) then
begin
ResizeBitmap(Img,255,255,0);
ResizeBitmap(Hmap,255,255,0);
end;
// We are creating a new voxel file.
IsVXLLoading := true;
Application.OnIdle := nil;
CheckVXLChanged;
VoxelType := vtLand;
z := 0;
for x := 0 to Img.Width - 1 do
for y := 0 to Img.Height - 1 do
begin
curr := GetBValue(HMap.Canvas.Pixels[x,y]);
if curr > z then
begin
z := curr;
end;
end;
if z = 255 then
z := 254;
if (NewVoxel(Document,4,Img.Width,Img.Height,z+1))then
begin
VoxelOpen := false;
VXLChanged := false;
h := Img.Height - 1;
for x := 0 to Img.Width - 1 do
for y := 0 to Img.Height - 1 do
begin
z := GetBValue(HMap.Canvas.Pixels[x,y]);
if z = 255 then
z := 254;
Document.ActiveSection^.GetVoxel(x,h-y,z,v);
v.Used := true;
v.Colour := Document.Palette^.GetColourFromPalette(Img.Canvas.Pixels[x,y]);
v.Normal := 0;
Document.ActiveSection^.SetVoxel(x,h-y,z,v);
end;
SetIsEditable(true);
VoxelOpen := true;
SetVoxelChanged(true);
DoAfterLoadingThings;
end;
IsVXLLoading := false;
end;
end;
Img.Free;
Hmap.Free;
end;
end;
Frm.Release;
end;
procedure TFrmMain.Importfromamodelusing3ds2vxl1Click(Sender: TObject);
var
Destination : string;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Importfromamodelusing3ds2vxl1Click');
{$endif}
if GetVoxelImportedBy3ds2vxl(Destination) then
begin
ImportSectionFromVoxel(Destination);
end;
end;
procedure TFrmMain.Importfrommodel1Click(Sender: TObject);
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: ImportFromModel1Click');
{$endif}
if OpenVXLDialog.execute then
begin
ImportSectionFromVoxel(OpenVXLDialog.FileName);
end;
end;
procedure TFrmMain.Isosurfacesiso1Click(Sender: TObject);
var
IsoFile: CIsosurfaceFile;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Isosurfacesiso1Click');
{$endif}
if SaveDialogExport.execute then
begin
IsoFile := CIsoSurfaceFile.Create;
IsoFile.SaveToFile(SaveDialogExport.Filename,Document.ActiveSection^);
IsoFile.Free;
end;
end;
procedure TFrmMain.Resize1Click(Sender: TObject);
var
FrmNew: TFrmNew;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Resize1Click');
{$endif}
FrmNew := TFrmNew.Create(Self);
with FrmNew do
begin
//FrmNew.Caption := ' Resize';
//grpCurrentSize.Left := 8;
//grpNewSize.Left := 112;
//grpNewSize.Width := 97;
Label9.caption := 'Enter the size you want the canvas to be:';
Label10.caption := 'Resize Canvas';
grpCurrentSize.Visible := true;
Image1.Picture := TopBarImageHolder.Picture;
grpVoxelType.Visible := false;
x := Document.ActiveSection^.Tailer.XSize;
y := Document.ActiveSection^.Tailer.YSize;
z := Document.ActiveSection^.Tailer.ZSize;
ShowModal;
if changed then
begin
//Save undo information
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
SetIsEditable(false);
Document.ActiveSection^.Resize(x,y,z);
SetIsEditable(true);
UpdateViews;
SetupStatusBar;
CursorReset;
Refreshall;
SetVoxelChanged(true);
end;
end;
FrmNew.Free;
end;
procedure TFrmMain.SpinButton3UpClick(Sender: TObject);
begin
YCursorBar.Position := YCursorBar.Position +1;
end;
procedure TFrmMain.Splitter2Moved(Sender: TObject);
begin
if CnvView1.Height < ViewMinimumHeight then
begin
if RightPanel.Height > ((2 * ViewMinimumHeight) + (Splitter2.Height * 2) + (lblView1.Height * 2)) then
begin
CnvView1.Height := ViewMinimumHeight;
Splitter2.Top := CnvView1.Height + lblView1.Height;
end;
end;
end;
procedure TFrmMain.Splitter3Moved(Sender: TObject);
begin
if CnvView2.Height < ViewMinimumHeight then
begin
if RightPanel.Height > ((2 * ViewMinimumHeight) + (Splitter2.Height * 2) + (lblView1.Height * 2)) then
begin
CnvView2.Height := ViewMinimumHeight;
Splitter3.Top := CnvView1.Height + CnvView2.Height + Splitter2.Height + lblView1.Height + lblView2.Height;
end;
end;
end;
procedure TFrmMain.SpinButton3DownClick(Sender: TObject);
begin
YCursorBar.Position := YCursorBar.Position -1;
end;
procedure TFrmMain.SpinButton1DownClick(Sender: TObject);
begin
ZCursorBar.Position := ZCursorBar.Position -1;
end;
procedure TFrmMain.SpinButton1UpClick(Sender: TObject);
begin
ZCursorBar.Position := ZCursorBar.Position +1;
end;
procedure TFrmMain.SpinButton2DownClick(Sender: TObject);
begin
XCursorBar.Position := XCursorBar.Position -1;
end;
procedure TFrmMain.SpinButton2UpClick(Sender: TObject);
begin
XCursorBar.Position := XCursorBar.Position +1;
end;
procedure TFrmMain.IncreaseResolution1Click(Sender: TObject);
var
Tool : CTopologyFixer;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: IncreaseResolution1Click');
{$endif}
if (Document.ActiveSection^.Tailer.XSize < 127) and (Document.ActiveSection^.Tailer.YSize < 127) and (Document.ActiveSection^.Tailer.ZSize < 127) then
begin
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
SetIsEditable(false);
Tool := CTopologyFixer.Create(Document.ActiveSection^,Document.Palette^);
Tool.Free;
SetIsEditable(true);
UpdateViews;
SetupStatusBar;
CursorReset;
Refreshall;
SetVoxelChanged(true);
end;
end;
procedure TFrmMain.FullResize1Click(Sender: TObject);
var
frm: TFrmFullResize;
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: FullResize1Click');
{$endif}
frm:=TFrmFullResize.Create(Self);
with frm do
begin
x := Document.ActiveSection^.Tailer.XSize;
y := Document.ActiveSection^.Tailer.YSize;
z := Document.ActiveSection^.Tailer.ZSize;
Image1.Picture := TopBarImageHolder.Picture;
ShowModal;
if Changed then
begin
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
SetIsEditable(false);
Document.ActiveSection^.ResizeBlowUp(Scale);
SetIsEditable(true);
UpdateViews;
SetupStatusBar;
CursorReset;
Refreshall;
SetVoxelChanged(true);
end;
end;
frm.Free;
end;
procedure TFrmMain.UpdatePositionStatus(x,y,z : integer);
begin
StatusBar1.Panels[3].Text := 'Pos: ' + inttostr(X) + ',' + inttostr(Y) + ',' + inttostr(Z);
end;
procedure TFrmMain.UpdateSchemes1Click(Sender: TObject);
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: UpdateSchemes1Click');
{$endif}
UpdateCScheme;
end;
procedure TFrmMain.ToolButton9Click(Sender: TObject);
var
frm: TFrmPreferences;
begin
frm:=TFrmPreferences.Create(Self);
frm.ShowModal;
frm.Free;
end;
procedure TFrmMain.SpeedButton9Click(Sender: TObject);
begin
SetVXLTool(VXLTool_SmoothNormal);
Normals1.Click;
end;
procedure TFrmMain.ToolButton13Click(Sender: TObject);
var
frm: TFrmReplaceColour;
begin
frm:=TFrmReplaceColour.Create(Self);
frm.Visible:=False;
frm.Image1.Picture := TopBarImageHolder.Picture;
frm.ShowModal;
frm.Close;
frm.Free;
end;
Function TFrmMain.CharToStr : String;
var
x : integer;
begin
for x := 1 to 16 do
Result := Document.ActiveVoxel^.Header.FileType[x];
end;
Function CleanString(S : string) : String;
var
x : integer;
begin
Result := '';
for x := 1 to Length(s) do
if (S[x] <> '&') and (S[x] <> 'x') then
Result := Result + S[x];
end;
procedure TFrmMain.N1x1Click(Sender: TObject);
begin
Document.ActiveSection^.Viewport[0].Zoom := Strtoint(CleanString(TMenuItem(Sender).caption));
if SelectedZoomOption <> nil then
begin
SelectedZoomOption.Checked := false;
end;
SelectedZoomOption := TMenuItem(Sender);
SelectedZoomOption.Checked := true;
CentreViews;
setupscrollbars;
CnvView0.Refresh;
end;
procedure TFrmMain.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: FormKeyDown');
{$endif}
if (Key = Ord('Z')) or (Key = Ord('z')) then
begin
if ssShift in shift then
begin
if YCursorBar.Position > 0 then
YCursorBar.Position := YCursorBar.Position - 1;
end
else
begin
if YCursorBar.Position < YCursorBar.Max then
YCursorBar.Position := YCursorBar.Position + 1;
end;
XCursorBarChange(nil);
end
else if (Key = Ord('X')) or (Key = Ord('x')) then
begin
if ssShift in shift then
begin
if ZCursorBar.Position > 0 then
ZCursorBar.Position := ZCursorBar.Position - 1;
end
else
begin
if ZCursorBar.Position < ZCursorBar.Max then
ZCursorBar.Position := ZCursorBar.Position + 1;
end;
XCursorBarChange(nil);
end;
if (Key = Ord('C')) or (Key = Ord('c')) then
begin
if ssShift in shift then
begin
if XCursorBar.Position > 0 then
XCursorBar.Position := XCursorBar.Position - 1;
end
else
begin
if XCursorBar.Position < XCursorBar.Max then
XCursorBar.Position := XCursorBar.Position + 1;
end;
XCursorBarChange(nil);
end;
end;
procedure TFrmMain.Display3DWindow1Click(Sender: TObject);
begin
if p_Frm3DPreview = nil then
begin
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: Display3DWindow1Click');
{$endif}
Application.OnIdle := nil;
new(p_Frm3DPreview);
p_Frm3DPreview^ := TFrm3DPreview.Create(self);
p_Frm3DPreview^.Show;
if @Application.OnIdle = nil then
Application.OnIdle := Idle;
end;
end;
procedure TFrmMain.DisplayFMPointCloudClick(Sender: TObject);
begin
UncheckFillMode;
DisplayFMPointCloud.Checked := true;
Env.SetPolygonMode(GL_POINT);
end;
procedure TFrmMain.DisplayFMSolidClick(Sender: TObject);
begin
UncheckFillMode;
DisplayFMSolid.Checked := true;
Env.SetPolygonMode(GL_FILL);
end;
procedure TFrmMain.DisplayFMWireframeClick(Sender: TObject);
begin
UncheckFillMode;
DisplayFMWireframe.Checked := true;
Env.SetPolygonMode(GL_LINE);
end;
procedure TFrmMain.UncheckFillMode;
begin
DisplayFMSolid.Checked := false;
DisplayFMWireframe.Checked := false;
DisplayFMPointCloud.Checked := false;
end;
procedure TFrmMain.NewAutoNormals1Click(Sender: TObject);
begin
if not isEditable then exit;
{$ifdef DEBUG_FILE}
DebugFile.Add('FrmMain: CubedAutoNormals1Click');
{$endif}
// ask the user to confirm
if MessageDlg('Autonormals v6.1' +#13#13+
'This process will modify the voxel''s normals.' +#13+
'If you choose to do this, you should first save' + #13 +
'your model under a different name as a backup.',
mtWarning,mbOKCancel,0) = mrCancel then
Exit;
//ResetUndoRedo;
CreateVXLRestorePoint(Document.ActiveSection^,Undo);
UpdateUndo_RedoState;
ApplyInfluenceNormalsToVXL(Document.ActiveSection^);
Refreshall;
SetVoxelChanged(true);
end;
procedure TFrmMain.AutoRepair(const _Filename: string; _ForceRepair: boolean);
var
Frm : TFrmRepairAssistant;
begin
Frm := TFrmRepairAssistant.Create(self);
if Frm.RequestAuthorization(_Filename) then
begin
Frm.ForceRepair := _ForceRepair;
Frm.ShowModal;
if not Frm.RepairDone then
begin
Application.Terminate;
end;
Frm.Close;
end;
Frm.Release;
end;
procedure TFrmMain.RepairProgram1Click(Sender: TObject);
var
Frm : TFrmRepairAssistant;
begin
Frm := TFrmRepairAssistant.Create(self);
Frm.ForceRepair := true;
Frm.ShowModal;
if not Frm.RepairDone then
begin
ShowMessage('Warning: Auto Repair could not finish its job.');
end;
Frm.Close;
Frm.Release;
end;
procedure TFrmMain.FormActivate(Sender: TObject);
begin
// Activate the view.
if (not Display3dView1.Checked) then
begin
if p_Frm3DPreview <> nil then
begin
p_Frm3DPreview^.AnimationTimer.Enabled := p_Frm3DPreview^.AnimationState;
end;
if p_Frm3DModelizer <> nil then
begin
p_Frm3DModelizer^.AnimationTimer.Enabled := p_Frm3DModelizer^.AnimationState;
end;
if @Application.OnIdle = nil then
Application.OnIdle := Idle;
end
else
begin
if (p_Frm3DPreview = nil) and (p_Frm3DModelizer = nil) then
begin
Application.OnIdle := nil;
end
else
begin
Application.OnIdle := Idle;
end;
end;
end;
procedure TFrmMain.FormDeactivate(Sender: TObject);
begin
Application.OnIdle := nil;
end;
procedure TFrmMain.SetVoxelChanged(_Value: boolean);
begin
VXLChanged := _Value;
ChangeCaption(true);
end;
end.
|
unit ChamaLista;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, Psock, NMFtp, Ggauge, StdCtrls,funcd5;
type
TForm1 = class(TForm)
Panel1: TPanel;
Label1: TLabel;
GGauge1: TGradientGauge;
NMFTP1: TNMFTP;
Label2: TLabel;
Memo1: TMemo;
Memo2: TMemo;
procedure FormCreate(Sender: TObject);
function lerParametro(l:string):string;
procedure AppException(Sender: TObject; E: Exception);
procedure NMFTP1PacketRecvd(Sender: TObject);
procedure FormActivate(Sender: TObject);
Procedure PegarArquivos(sender:tobject;NomeDoArquivo:string);
function existeNovaVersao:boolean;
function BaixarArquivo(sender:tobject;mens,nome:String):boolean;
private
{ Private declarations }
public
{ Public declarations }
end;
CONST
PATH = 'c:\listas\';
ARQ_PARAMETROS = PATH + 'ListaCasamento.ini';
ARQ_ERROS = PATH + 'ErrorLog.txt';
var
Form1: TForm1;
implementation
{$R *.DFM}
function TForm1.lerParametro(l:string):string;
begin
while pos('=',l) > 0 do
delete(l,01,01);
lerParametro := l;
end;
function tform1.existeNovaVersao:boolean;
var
arqLocal,arqRemoto:textfile;
l,r:string;
begin
existeNovaVersao := false;
memo1.lines.LoadFromFile( 'c:\listas\listacasamento.cfg');
memo2.lines.LoadFromFile( ARQ_PARAMETROS );
if form1.lerParametro(memo1.lines[2]) <> form1.lerParametro(memo2.lines[2]) then
existeNovaVersao := true;
end;
procedure TForm1.AppException(Sender: TObject; E: Exception);
var
dest:textfile;
begin
assignFIle(dest, ARQ_ERROS );
if FileExists(ARQ_ERROS) = true then
append(dest)
else
rewrite(dest);
writeln(dest, dateToSTr(now) + ' ' + timetoStr(now)+ ' ' + E.message );
closefile(dest);
end;
function Tform1.BaixarArquivo(sender:Tobject;mens,nome:string):boolean;
begin
form1.refresh;
label2.caption := mens;
nmftp1.download( nome , nome );
end;
Procedure tform1.PegarArquivos(sender:tobject;NomeDoArquivo:string);
var
arq:textfile;
mens,nome,lin:string;
i:integer;
begin
assignFile( arq, 'ArquivosParaBaixar.cfg');
reset(arq);
while eof( arq) = false do
begin
readln(arq,lin);
if lin <> '' then
begin
mens := copy(lin,01,pos(',',lin) - 1);
nome := copy(lin, pos(',',lin) + 1 , length(lin)-pos(',',lin) ) ;
BaixarArquivo(sender,mens,nome);
end;
end;
CloseFile(arq);
end;
procedure TForm1.FormActivate(Sender: TObject);
begin
with nmftp1 do
begin
if connected then disconnect;
host := funcd5.lerParam( ARQ_PARAMETROS,06);
port := 21;
timeout := 10000;
userid := funcd5.tiraEspaco( funcd5.lerParam( ARQ_PARAMETROS,07) );
password:= funcd5.tiraEspaco( funcd5.lerParam( ARQ_PARAMETROS,08) );
vendor := NMOS_auto;
end;
try
nmftp1.connect;
nmftp1.timeout := 0;
nmftp1.parseList:= true;
nmftp1.mode(mode_ascii);
nmftp1.ChangeDir('/listas');
ggauge1.Visible := true;
label2.caption := ' - Verificando arquivos novos...';
nmftp1.download('ArquivosParaBaixar.cfg','ArquivosParaBaixar.cfg');
PegarArquivos(sender,'');
label2.caption := 'Verificando a versão';
nmftp1.download('listacasamento.ini','c:\listas\listacasamento.cfg');
if existeNovaVersao = true then
begin
label2.caption := ' - Atualizando a versão do programa, aguarde...';
nmftp1.download('listas.exe', Path + 'listas.exe');
memo2.lines[2] := memo1.lines[2];
memo2.lines.SaveToFile( ARQ_PARAMETROS);
end;
ggauge1.visible:= false;
label2.caption := '';
winexec(pchar(path + 'listas.exe'),0);
except
on e:exception do
begin
form1.AppException(sender,E);
winexec(pchar(path + 'listas.exe'),0);
end;
end;
application.terminate;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Application.OnException := form1.AppException;
end;
procedure TForm1.NMFTP1PacketRecvd(Sender: TObject);
begin
ggauge1.Max := nmftp1.BytesTotal;
ggauge1.Position := nmftp1.BytesRecvd;
ggauge1.Update;
end;
end.
|
unit uSisMenuFxd;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
uParentFixedFrm, Db, DBTables, StdCtrls, Buttons, ExtCtrls, ComCtrls,
dxBar, ImgList, ADODB, siComp, siLangRT;
type
TSisMenuFxd = class(TParentFixedFrm)
lvMenu: TListView;
ilMenuItemLarge: TImageList;
Panel1: TPanel;
Panel3: TPanel;
lblTitulo: TLabel;
lblObs: TLabel;
lblPath: TLabel;
quMenu: TADOQuery;
quMenuIDMenuItem: TIntegerField;
quMenuMenuItem: TStringField;
quMenuFormID: TIntegerField;
quMenuIDMenuItemParent: TIntegerField;
quMenuLoaderType: TIntegerField;
quMenuParametro: TStringField;
quMenuPriority: TIntegerField;
quMenuImageIndex: TIntegerField;
quMenuObs: TStringField;
btLocalBack: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure lvMenuChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
procedure lvMenuDblClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btLocalBackClick(Sender: TObject);
private
{ Private declarations }
slPilhaNome: TStringList;
slPilhaNivel: TStringList;
procedure MontaNivel(NivelSuperior: integer);
procedure MontaPath;
public
{ Public declarations }
end;
var
SisMenuFxd: TSisMenuFxd;
implementation
uses uDM, uNumericFunctions;
{$R *.DFM}
procedure TSisMenuFxd.MontaNivel(NivelSuperior: integer);
var
ListItem: TListItem;
begin
with quMenu do
begin
if not Active then
Open;
if Locate('IDMenuItemParent', IntToStr(NivelSuperior), []) then
begin
// Empilho o mome e o IDMenuItemParent
if lvMenu.ItemFocused = nil then
slPilhaNome.Add('Raiz')
else
slPilhaNome.Add(lvMenu.ItemFocused.Caption);
slPilhaNivel.Add(IntToStr(NivelSuperior));
lvMenu.Items.Clear;
MontaPath;
while (quMenuIDMenuItemParent.AsInteger = NivelSuperior) AND NOT EOF do
begin
ListItem := lvMenu.Items.Add;
ListItem.SubItems.Add(quMenuIDMenuItem.AsString);
ListItem.SubItems.Add(quMenuIDMenuItemParent.AsString);
ListItem.SubItems.Add(quMenuObs.AsString);
ListItem.Caption := quMenuMenuItem.AsString;
ListItem.ImageIndex := quMenuImageindex.AsInteger;
Next;
end;
end;
end;
end;
procedure TSisMenuFxd.FormCreate(Sender: TObject);
begin
inherited;
slPilhaNome := TStringList.Create;
slPilhaNivel := TStringList.Create;
MontaNivel(1);
end;
procedure TSisMenuFxd.lvMenuChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
begin
inherited;
if lvMenu.ItemFocused <> nil then
begin
lblTitulo.Caption := lvMenu.ItemFocused.Caption;
lblObs.Caption := lvMenu.ItemFocused.SubItems[2];
end
else
begin
if lvMenu.Items.Count > 0 then
begin
lblTitulo.Caption := lvMenu.Items[0].Caption;
lblObs.Caption := lvMenu.Items[0].SubItems[2];
end;
end;
end;
procedure TSisMenuFxd.lvMenuDblClick(Sender: TObject);
begin
inherited;
MontaNivel(MyStrToInt(lvMenu.ItemFocused.SubItems[0]));
end;
procedure TSisMenuFxd.FormDestroy(Sender: TObject);
begin
inherited;
slPilhaNome.Free;
slPilhaNivel.Free;
end;
procedure TSisMenuFxd.MontaPath;
var
i: integer;
begin
lblPath.Caption := '';
for i := 0 to slPilhaNome.Count-1 do
lblPath.Caption := lblPath.Caption + '\ ' + slPilhaNome[i];
end;
procedure TSisMenuFxd.btLocalBackClick(Sender: TObject);
var
NivelAnterior: Integer;
begin
inherited;
NivelAnterior := MyStrToInt(slPilhaNivel[slPilhaNivel.Count-2]);
slPilhaNivel.Delete(slPilhaNivel.Count-1);
slPilhaNome.Delete(slPilhaNome.Count-1);
slPilhaNivel.Delete(slPilhaNivel.Count-1);
slPilhaNome.Delete(slPilhaNome.Count-1);
MontaNivel(NivelAnterior);
end;
end.
|
unit AST.Delphi.Intf;
interface
uses AST.Intf, AST.Delphi.DataTypes, AST.Delphi.Classes, AST.Delphi.Errors;
type
PDelphiSystemDeclarations = ^TDelphiSystemDeclarations;
IASTDelphiUnit = interface(IASTModule)
['{1A57EA5B-8EA8-4AC7-A885-85E8C959F89E}']
function GetSystemDeclarations: PDelphiSystemDeclarations;
function GetErrors: TASTDelphiErrors;
property SystemDeclarations: PDelphiSystemDeclarations read GetSystemDeclarations;
property Errors: TASTDelphiErrors read GetErrors;
end;
TDelphiSystemDeclarations = record
// integer types
_Int8: TIDType;
_Int16: TIDType;
_Int32: TIDType;
_Int64: TIDType;
_UInt8: TIDType;
_UInt16: TIDType;
_UInt32: TIDType;
_UInt64: TIDType;
_NativeInt: TIDType;
_NativeUInt: TIDType;
// floating point types
_Float32: TIDType;
_Float64: TIDType;
_Float80: TIDType;
_Currency: TIDType;
_Comp: TIDType;
_Real: TIDType;
// other
_Boolean: TIDType;
_AnsiChar: TIDType;
_WideChar: TIDType;
_AnsiString: TIDType;
_UnicodeString: TIDType;
_ShortString: TIDType;
_WideString: TIDType;
_Variant: TIDType;
_NullPtrType: TIDType;
_PointerType: TIDPointer;
_UntypedReference: TIDUntypedRef;
_Untyped: TIDType;
_MetaType: TIDType;
_Void: TIDType;
_GuidType: TIDStructure;
_PAnsiChar: TIDType;
_PWideChar: TIDType;
_OrdinalType: TIDType;
_TObject: TIDClass;
_Exception: TIDClass;
_EAssertClass: TIDClass;
_TTypeKind: TIDEnum;
_DateTimeType: TIDType;
_DateType: TIDType;
_TimeType: TIDType;
_True: TIDBooleanConstant;
_False: TIDBooleanConstant;
_TrueExpression: TIDExpression;
_FalseExpression: TIDExpression;
_ZeroConstant: TIDIntConstant;
_ZeroIntExpression: TIDExpression;
_ZeroFloatExpression: TIDExpression;
_OneConstant: TIDIntConstant;
_OneExpression: TIDExpression;
_MaxIntConstant: TIDIntConstant;
_MaxIntExpression: TIDExpression;
_NullPtrConstant: TIDIntConstant;
_NullPtrExpression: TIDExpression;
_EmptyStrConstant: TIDStringConstant;
_EmptyStrExpression: TIDExpression;
_DeprecatedDefaultStr: TIDStringConstant;
_EmptyArrayConstant: TIDDynArrayConstant;
_ResStringRecord: TIDType;
_TVarRec: TIDType;
function GetTypeByID(DataTypeID: TDataTypeID): TIDType;
property DataTypes[DataTypeID: TDataTypeID]: TIDType read GetTypeByID;
end;
IASTDelphiSystemUnit = interface(IASTDelphiUnit)
end;
implementation
{ TDelphiSystemTypes }
function TDelphiSystemDeclarations.GetTypeByID(DataTypeID: TDataTypeID): TIDType;
begin
case DataTypeID of
dtInt8: Result := _Int8;
dtInt16: Result := _Int16;
dtInt32: Result := _Int32;
dtInt64: Result := _Int64;
dtUInt8: Result := _UInt8;
dtUInt16: Result := _UInt16;
dtUInt32: Result := _UInt32;
dtUInt64: Result := _UInt64;
dtNativeInt: Result := _NativeInt;
dtNativeUInt: Result := _NativeUInt;
dtFloat32: Result := _Float32;
dtFloat64: Result := _Float64;
dtFloat80: Result := _Float80;
dtCurrency: Result := _Currency;
dtComp: Result := _Comp;
dtBoolean: Result := _Boolean;
dtAnsiChar: Result := _AnsiChar;
dtChar: Result := _WideChar;
dtShortString: Result := _ShortString;
dtAnsiString: Result := _AnsiString;
dtString: Result := _UnicodeString;
dtWideString: Result := _WideString;
dtPAnsiChar: Result := _PAnsiChar;
dtPWideChar: Result := _PWideChar;
dtVariant: Result := _Variant;
dtGuid: Result := _GuidType;
dtPointer: Result := _PointerType;
else
Assert(False, 'Data Type is unknown');
Result := nil;
end;
end;
end.
|
namespace GoCrawler;
uses
System.Collections.Generic,
System.Linq,
go.net.http,
go.net.url,
go.strings,
go.golang.org.x.net.html;
type
Program = class
public
// we spider docs.hydra4.com which is a fairly small site.
const Root = 'https://docs.hydra4.com/';
// and block the api urls because those are large.
const BlockList: array of String = ['https://docs.hydra4.com/API'];
class var fQueue: List<String> := new List<String>;
class var fDone: HashSet<String> := new HashSet<String>;
class method Queue(aUrl, aPath: String);
begin
// this resolves aPath relative to aUrl (the caller) and returns the real url. If aPath is a full url it returns jsut that.
var lNewUrl := String(go.net.url.Parse(aUrl)[0].ResolveReference(go.net.url.Parse(aPath)[0]).String());
// Ensure to only crawl our domain, skip blocklisted ones, and only process things we see first.
if lNewUrl.StartsWith(Root) and not fDone.Contains(lNewUrl) and not BlockList.Any(a -> lNewUrl.StartsWith(a)) then
fQueue.Add(lNewUrl);
end;
class method Crawl(aUrl: String);
begin
if not fDone.Add(aUrl) then exit;
writeLn('Crawling '+aUrl);
var lRes := go.net.http.Get(aUrl);
if lRes.err <> nil then begin
writeLn('Error getting '+aUrl+': '+lRes.err.Error())
end
else begin
// Parses the html for this rul
var lTok := NewTokenizer(lRes.resp.Body);
loop begin
var lElement := lTok.Next();
case lElement.Value of
// ErrorToken.Value is EOF in most cases, or a parser error; either way, we stop here.
ErrorToken.Value: break;
StartTagToken.Value: begin
var lToken := lTok.Token;
// Start tag "a", with a href means a sub page.
if lToken.Data ='a' then
for each el in lToken.Attr do
if el[1].Key = 'href' then
Queue(aUrl, el[1].Val);
end;
end;
end;
end;
end;
class method Main(args: array of String): Int32;
begin
Queue(Root, Root);
while fQueue.Count > 0 do begin
var lItem := fQueue[0];
fQueue.RemoveAt(0);
Crawl(lItem);
end;
for each el in fDone do begin
writeLn('Page: '+el);
end;
writeLn('Done');
Console.ReadLine;
end;
end;
end. |
PROGRAM temp;
USES tempUnit;
VAR lastTime : INTEGER;
VAR lastTemp : REAL;
FUNCTION isPlausible_Global(h, min : INTEGER; temp : REAL) : BOOLEAN;
VAR diff_time : INTEGER;
VAR diff_temp : REAL;
BEGIN
diff_time := ((h * 60) + min) - lastTime;
diff_temp := temp - lastTemp;
(*Globale Variablen muessen vorher einmal gesetzt werden*)
lastTime := (h * 60) + min;
lastTemp := temp;
isPlausible_Global := True;
IF (temp <936.8) OR (temp > 1345.3) OR ((11.45 * diff_time) <= abs(diff_temp)) THEN
isPlausible_Global := False;
END;
FUNCTION isPlausible_Var(h, min : INTEGER; temp : REAL; VAR v_lastTime : INTEGER; VAR v_lastTemp : REAL) : BOOLEAN;
VAR diff_time : INTEGER;
VAR diff_temp : REAL;
BEGIN
diff_time := ((h * 60) + min) - v_lastTime;
diff_temp := temp - v_lastTemp;
v_lastTime := (h * 60) + min;
v_lastTemp := temp;
isPlausible_Var := True;
IF (temp <936.8) OR (temp > 1345.3) OR ((11.45 * diff_time) <= abs(diff_temp)) THEN
isPlausible_Var := False;
END;
VAR v_lastTime : INTEGER;
VAR v_lastTemp : REAL;
BEGIN
lastTime := 0;
lastTemp := 1000;
v_lastTime := 0;
v_lastTemp := 1000;
WriteLn(chr(205),chr(205),chr(185),' Temp Plausible ',chr(204),chr(205),chr(205));
(*Globale variablen Test*)
WriteLn('Global');
WriteLn('Temp: 1h 0min, Temp: 999, Plausible: ', isPlausible_Global(1,0,999));
WriteLn('Temp: 1h 10min, Temp: 1000, Plausible: ', isPlausible_Global(1,10,1000));
WriteLn('Temp: 1h 20min, Temp: 1300, Plausible: ', isPlausible_Global(1,20,1300));
WriteLn('Temp: 2h 0min, Temp: 600, Plausible: ', isPlausible_Global(2,0,600));
WriteLn();
(*Lokal variablen Test*)
WriteLn('Lokal');
WriteLn('Temp: 1h 0min, Temp: 999, Plausible: ', isPlausible_Var(1,0,999,v_lastTime,v_lastTemp));
WriteLn('Temp: 1h 10min, Temp: 1000, Plausible: ', isPlausible_Var(1,10,1000,v_lastTime,v_lastTemp));
WriteLn('Temp: 1h 20min, Temp: 1300, Plausible: ', isPlausible_Var(1,20,1300,v_lastTime,v_lastTemp));
WriteLn('Temp: 2h 0min, Temp: 600, Plausible: ', isPlausible_Var(2,0,600,v_lastTime,v_lastTemp));
WriteLn();
(*UNIT*)
WriteLn('Unit');
WriteLn('Temp: 1h 0min, Temp: 999, Plausible: ', isPlausible_Unit(1,0,999));
WriteLn('Temp: 1h 10min, Temp: 1000, Plausible: ', isPlausible_Unit(1,10,1000));
WriteLn('Temp: 1h 20min, Temp: 1300, Plausible: ', isPlausible_Unit(1,20,1300));
WriteLn('Temp: 2h 0min, Temp: 600, Plausible: ', isPlausible_Unit(2,0,600));
END. |
unit UnitPrintAcc;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet,
frxClass, frxDBSet, IBase, ZTypes, IniFiles, frxDesgn, frxCross, ZProc, Dates,
Unit_PrintAccList_Consts, ZMessages, frxExportTXT, frxExportRTF;
type
TFZPrintAccList = class(TForm)
frxDSetGlobalData: TfrxDBDataset;
frxDSetShtatRas: TfrxDBDataset;
frxDSetPrivileges: TfrxDBDataset;
DB: TpFIBDatabase;
DSetPrivileges: TpFIBDataSet;
DSetAccNarList: TpFIBDataSet;
DSetShtatRas: TpFIBDataSet;
DSetGlobalData: TpFIBDataSet;
ReadTransaction: TpFIBTransaction;
Report: TfrxReport;
frxDesigner1: TfrxDesigner;
DSetAccUdList: TpFIBDataSet;
frxUserDataSet: TfrxUserDataSet;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ReportGetValue(const VarName: String; var Value: Variant);
private
Parameter:TZPrintAccListParameter;
public
constructor Create(Aowner: TComponent;DB_handle:TISC_DB_HANDLE;AParameter:TZPrintAccListParameter);reintroduce;
end;
function CreateReportAccList(Aowner: TComponent;DB:TISC_DB_HANDLE;AParameter:TZPrintAccListParameter):Variant;stdcall;
exports CreateReportAccList;
implementation
uses Math;
{$R *.dfm}
const Path_IniFile_Reports = 'Reports\Zarplata\Reports.ini';
const SectionOfIniFile = 'AccList';
const FullNameReport = 'Reports\Zarplata\AccList.fr3';
function CreateReportAccList(Aowner: TComponent;DB:TISC_DB_HANDLE;AParameter:TZPrintAccListParameter):Variant;stdcall;
var ViewForm:TFZPrintAccList;
begin
ViewForm:=TFZPrintAccList.Create(Aowner,DB,AParameter);
end;
constructor TFZPrintAccList.Create(Aowner: TComponent;DB_handle:TISC_DB_HANDLE;AParameter:TZPrintAccListParameter);
begin
inherited Create(Aowner);
try
Parameter:=AParameter;
DB.Handle:=DB_handle;
DSetAccNarList.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_ACC_NAR_S('+IntToStr(AParameter.Id_Group_Account)+','+
IntToStr(AParameter.Id_Man)+','+
IntToStr(AParameter.Kod_Setup2)+','+
IntToStr(AParameter.TypeData)+') ORDER BY KOD_VIDOPL';
DSetAccUdList.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_ACC_UD_S('+IntToStr(AParameter.Id_Group_Account)+','+
IntToStr(AParameter.Id_Man)+','+
IntToStr(AParameter.Kod_Setup2)+','+
IntToStr(AParameter.TypeData)+') order by KOD_VIDOPL';
DSetPrivileges.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_PRIV_S('+IntToStr(AParameter.Id_Man)+','+
IntToStr(AParameter.Kod_Setup2)+')';
DSetShtatRas.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_MAN_MOVING_S('+IntToStr(AParameter.Id_Man)+','+
IntToStr(AParameter.Kod_Setup2)+')';
DSetGlobalData.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_GLOBALDATA_S('+IntToStr(AParameter.Id_Group_Account)+','+
IntToStr(AParameter.Id_Man)+','+
IntToStr(AParameter.Kod_Setup2)+')';
// ShowMessage(DSetAccNarList.SQLs.SelectSQL.Text);
DSetAccNarList.Open;
// ShowMessage(DSetAccUdList.SQLs.SelectSQL.Text);
DSetAccUdList.Open;
// ShowMessage(DSetPrivileges.SQLs.SelectSQL.Text);
DSetPrivileges.Open;
// ShowMessage(DSetShtatRas.SQLs.SelectSQL.Text);
DSetShtatRas.Open;
// ShowMessage(DSetGlobalData.SQLs.SelectSQL.Text);
DSetGlobalData.Open;
except
on E:Exception do
begin
ZShowMessage(FZPrintAccList_Error_Caption,e.Message,mtError,[mbOK]);
Self.Close;
end;
end;
end;
procedure TFZPrintAccList.FormCreate(Sender: TObject);
var IniFile:TIniFile;
ViewMode:byte;
PathReport:string;
Sum_Nar,Sum_Ud:double;
begin
Sum_Nar:=0;
Sum_Ud:=0;
DSetAccNarList.First;
while not DSetAccNarList.Eof do
Begin
Sum_Nar:=Sum_Nar+DSetAccNarList['SUMMA'];
DSetAccNarList.Next;
end;
DSetAccUdList.First;
while not DSetAccUdList.Eof do
Begin
Sum_Ud:=Sum_Ud+DSetAccUdList['SUMMA'];
DSetAccUdList.Next;
end;
frxUserDataSet.Fields.Add('N_CODE_DEPARTMENT');
frxUserDataSet.Fields.Add('N_KOD_SETUP_3');
frxUserDataSet.Fields.Add('N_KOD_VIDOPL');
frxUserDataSet.Fields.Add('N_NAME_VIDOPL');
frxUserDataSet.Fields.Add('N_DAY_CLOCK');
frxUserDataSet.Fields.Add('N_PERCENT_SUMCLOCK');
frxUserDataSet.Fields.Add('N_SUMMA');
frxUserDataSet.Fields.Add('U_KOD_SETUP_3');
frxUserDataSet.Fields.Add('U_KOD_VIDOPL');
frxUserDataSet.Fields.Add('U_NAME_VIDOPL');
frxUserDataSet.Fields.Add('U_SUMMA');
frxUserDataSet.RangeEndCount:=IfThen(DSetAccNarList.RecordCount>DSetAccUdList.RecordCount,DSetAccNarList.RecordCount,DSetAccUdList.RecordCount);
frxUserDataSet.RangeEnd:=reCount;
IniFile:=TIniFile.Create(ExtractFilePath(Application.ExeName)+Path_IniFile_Reports);
ViewMode:=IniFile.ReadInteger(SectionOfIniFile,'ViewMode',1);
PathReport:=IniFile.ReadString(SectionOfIniFile,'NameReport',FullNameReport);
IniFile.Free;
Report.Clear;
Report.LoadFromFile(ExtractFilePath(Application.ExeName)+PathReport,True);
Report.Variables['P_CODE_DEPARTMENT']:=''''+FZPrintAccList_P_CODE_DEPARTMENT_Text+'''';
Report.Variables['P_KOD_SETUP_3']:=''''+FZPrintAccList_P_KOD_SETUP_3_Text+'''';
Report.Variables['P_KOD_VIDOPL']:=''''+FZPrintAccList_P_KOD_VIDOPL_Text+'''';
Report.Variables['P_NAME_VIDOPL']:=''''+FZPrintAccList_P_NAME_VIDOPL_Text+'''';
Report.Variables['P_DAY_CLOCK']:=''''+FZPrintAccList_P_DAY_CLOCK_Text+'''';
Report.Variables['P_PERCENT_SUMCLOCK']:=''''+FZPrintAccList_P_PERCENT_SUMCLOCK_Text+'''';
Report.Variables['P_SUMMA']:=''''+FZPrintAccList_P_SUMMA_Text+'''';
Report.Variables['P_NAR']:=''''+FZPrintAccList_P_Nar_Text+'''';
Report.Variables['P_UD']:=''''+FZPrintAccList_P_Ud_Text+'''';
Report.Variables['P_TARIFOKLAD']:=''''+FZPrintAccList_P_TarifOklad_Text+'''';
if DSetGlobalData['KOD_SETUP1']<>Parameter.Kod_Setup2 then
Report.Variables['P_ACCLIST_TYPE']:=''''+FZPrintAccList_P_AccList_Type_Title+KodSetupToPeriod(DSetGlobalData['KOD_SETUP1'],2)+''''
else
Report.Variables['P_ACCLIST_TYPE']:=NULL;
Report.Variables['P_ACCLIST']:=''''+FZPrintAccList_P_AccList_Title+KodSetupToPeriod(Parameter.Kod_Setup2,2)+'''';
Report.Variables['P_TN']:=''''+FZPrintAccList_P_Tn_Text+'''';
Report.Variables['P_FROM']:=''''+FZPrintAccList_P_From_Text+'''';
Report.Variables['P_VIPLATA']:=''''+FZPrintAccList_P_Viplata_Text+' '+FloatToStrF(Sum_Nar-Sum_Ud,ffFixed,16,2)+'''';
Report.Variables['P_SUMMARY']:=''''+FZPrintAccList_P_Summary_Text+'''';
Report.Variables['P_SUM_NAR']:=''''+FloatToStrF(Sum_Nar,ffFixed,16,2)+'''';
Report.Variables['P_SUM_UD'] :=''''+FloatToStrF(Sum_Ud,ffFixed,16,2)+'''';
case ViewMode of
1: Report.ShowReport;
2: Report.DesignReport;
end;
Report.Free;
Close;
end;
procedure TFZPrintAccList.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if ReadTransaction.InTransaction then ReadTransaction.Commit;
Action:=caFree;
end;
procedure TFZPrintAccList.ReportGetValue(const VarName: String;
var Value: Variant);
var PValue:double;
begin
if UpperCase(VarName)='N_SUMMA' then
begin
if DSetAccNarList.RecordCount-1>=frxUserDataSet.RecNo then
begin
DSetAccNarList.RecNo:=frxUserDataSet.RecNo+1;
Value:=DSetAccNarList.FieldValues['SUMMA'];
end
else
Value:=NULL;
end;
if UpperCase(VarName)='N_CODE_DEPARTMENT' then
begin
if DSetAccNarList.RecordCount-1>=frxUserDataSet.RecNo then
begin
DSetAccNarList.RecNo:=frxUserDataSet.RecNo+1;
Value:=DSetAccNarList.FieldValues['CODE_DEPARTMENT'];
end
else
Value:=NULL;
end;
if UpperCase(VarName)='N_KOD_SETUP_3' then
begin
if DSetAccNarList.RecordCount-1>=frxUserDataSet.RecNo then
begin
DSetAccNarList.RecNo:=frxUserDataSet.RecNo+1;
Value:=YearMonthFromKodSetup(DSetAccNarList.FieldValues['KOD_SETUP3'],False);
if Value<10 then Value:='0'+VarToStr(Value);
end
else
Value:=NULL;
end;
if UpperCase(VarName)='N_KOD_VIDOPL' then
begin
if DSetAccNarList.RecordCount-1>=frxUserDataSet.RecNo then
begin
DSetAccNarList.RecNo:=frxUserDataSet.RecNo+1;
Value:=DSetAccNarList.FieldValues['KOD_VIDOPL'];
end
else
Value:=NULL;
end;
if UpperCase(VarName)='N_NAME_VIDOPL' then
begin
if DSetAccNarList.RecordCount-1>=frxUserDataSet.RecNo then
begin
DSetAccNarList.RecNo:=frxUserDataSet.RecNo+1;
Value:=DSetAccNarList.FieldValues['NAME_VIDOPL'];
end
else
Value:=NULL;
end;
if UpperCase(VarName)='N_DAY_CLOCK' then
begin
if DSetAccNarList.RecordCount-1>=frxUserDataSet.RecNo then
begin
DSetAccNarList.RecNo:=frxUserDataSet.RecNo+1;
PValue:=DSetAccNarList['CLOCK'];
Value:=VarToStr(IfThen((DSetAccNarList['NDAY']=0) or varIsNull(DSetAccNarList['NDAY']),
'--',
ifThen(DSetAccNarList['NDAY']<10,
'0'+VarToStr(DSetAccNarList['NDAY']),
DSetAccNarList['NDAY']
)
)
)
+'/'+IfThen( VarisNULL(DSetAccNarList['CLOCK']) or (DSetAccNarList['CLOCK']=0),
'--,---',
ifthen(PValue<10,
'0'+FloatToStrF(PValue,ffFixed,5,2),
FloatToStrF(PValue,ffFixed,6,2)));
end
else
Value:=NULL;
end;
if UpperCase(VarName)='N_PERCENT_SUMCLOCK' then
begin
if DSetAccNarList.RecordCount-1>=frxUserDataSet.RecNo then
begin
DSetAccNarList.RecNo:=frxUserDataSet.RecNo+1;
if (DSetAccNarList['PERCENT']<>NULL) and (DSetAccNarList['PERCENT']<>0) then
begin
PValue:=DSetAccNarList['PERCENT'];
Value:=FloatToStrF(PValue,ffFixed,4,1)+'%';
end
else
begin
PValue:=DSetAccNarList['SUM_CLOCK'];
Value:=FloatToStrF(PValue,ffFixed,5,2);
end;
end
else
Value:=NULL;
end;
if UpperCase(VarName)='U_KOD_SETUP_3' then
begin
if DSetAccUdList.RecordCount-1>=frxUserDataSet.RecNo then
begin
DSetAccUdList.RecNo:=frxUserDataSet.RecNo+1;
Value:=YearMonthFromKodSetup(DSetAccUdList.FieldValues['KOD_SETUP3'],False);
if Value<10 then Value:='0'+VarToStr(Value);
end
else
Value:=NULL;
end;
if UpperCase(VarName)='U_KOD_VIDOPL' then
begin
if DSetAccUdList.RecordCount-1>=frxUserDataSet.RecNo then
begin
DSetAccUdList.RecNo:=frxUserDataSet.RecNo+1;
Value:=DSetAccUdList.FieldValues['KOD_VIDOPL'];
end
else
Value:=NULL;
end;
if UpperCase(VarName)='U_NAME_VIDOPL' then
begin
if DSetAccUdList.RecordCount-1>=frxUserDataSet.RecNo then
begin
DSetAccUdList.RecNo:=frxUserDataSet.RecNo+1;
Value:=DSetAccUdList.FieldValues['NAME_VIDOPL'];
end
else
Value:=NULL;
end;
if UpperCase(VarName)='U_SUMMA' then
begin
if DSetAccUdList.RecordCount-1>=frxUserDataSet.RecNo then
begin
DSetAccUdList.RecNo:=frxUserDataSet.RecNo+1;
Value:=DSetAccUdList.FieldValues['SUMMA'];
end
else
Value:=NULL;
end;
{if UpperCase(VarName)='P_CODE_DEPARTMENT' then Value:=FZPrintAccList_P_CODE_DEPARTMENT_Text;
if UpperCase(VarName)='P_KOD_SETUP_3' then Value:=FZPrintAccList_P_KOD_SETUP_3_Text;
if UpperCase(VarName)='P_KOD_VIDOPL' then Value:=FZPrintAccList_P_KOD_VIDOPL_Text;
if UpperCase(VarName)='P_NAME_VIDOPL' then Value:=FZPrintAccList_P_NAME_VIDOPL_Text;
if UpperCase(VarName)='P_DAY_CLOCK' then Value:=FZPrintAccList_P_DAY_CLOCK_Text;
if UpperCase(VarName)='P_PERCENT_SUMCLOCK' then Value:=FZPrintAccList_P_PERCENT_SUMCLOCK_Text;
if UpperCase(VarName)='P_SUMMA' then Value:=FZPrintAccList_P_SUMMA_Text;}
end;
end.
|
unit TurboJpeg;
interface
uses
Windows;
const
TJFLAG_BOTTOMUP = 2;
TJFLAG_FASTUPSAMPLE = 256;
TJFLAG_NOREALLOC = 1024;
TJFLAG_FASTDCT = 2048;
TJFLAG_ACCURATEDCT = 4096;
type
TtjPF = (
TJPF_RGB, TJPF_BGR, TJPF_RGBX, TJPF_BGRX, TJPF_XBGR, TJPF_XRGB, TJPF_GRAY,
TJPF_RGBA, TJPF_BGRA, TJPF_ABGR, TJPF_ARGB, TJPF_CMYK
);
TtjSAMP = (
TJSAMP_444, TJSAMP_422, TJSAMP_420, TJSAMP_GRAY, TJSAMP_440, TJSAMP_411
);
TTurboJpeg = class
private
FEncoderHandle : pointer;
FDecoderHandle : pointer;
public
constructor Create;
destructor Destroy; override;
class procedure GetBuffer(var AData:pointer; ASize:integer);
class procedure FreeBuffer(AData:pointer);
{*
ADst는 BitmapToJpeg() 호출하면 새로 메모리가 할당 된다. 사용 후에 삭제해야 한다.
}
procedure BitmapToJpeg(ASrc:pointer; AWidth,AHeight:integer; var ADst:pointer; var ADstSize:integer; AQuality:integer=100);
{*
ADst는 BitmapToJpegCopy() 호출 전에 메모리가 확보되어 있는 상태여야 한다.
따라서, ADst는 한 번 할당 받은 이후 계속 재사용 할 수 있다.
}
procedure BitmapToJpegCopy(ASrc:pointer; AWidth,AHeight:integer; var ADst:pointer; var ADstSize:integer; AQuality:integer=100);
procedure JpegToBitmap(ASrc:pointer; ASrcSize:integer; ADst:pointer; AWidth,AHeight:integer);
end;
TTurboJpegEncoder = class
private
FEncoderHandle : pointer;
public
constructor Create;
destructor Destroy; override;
{*
ADst는 BitmapToJpeg() 호출하면 새로 메모리가 할당 된다. 사용 후에 삭제해야 한다.
}
procedure BitmapToJpeg(ASrc:pointer; AWidth,AHeight:integer; var ADst:pointer; var ADstSize:integer; AQuality:integer=100);
{*
ADst는 BitmapToJpegCopy() 호출 전에 메모리가 확보되어 있는 상태여야 한다.
따라서, ADst는 한 번 할당 받은 이후 계속 재사용 할 수 있다.
}
procedure BitmapToJpegCopy(ASrc:pointer; AWidth,AHeight:integer; var ADst:pointer; var ADstSize:integer; AQuality:integer=100);
end;
// TODO: 모든 함수 접근을 싱크 할 필요 있는 지 검토
procedure BitmapToJpeg(ASrc:pointer; AWidth,AHeight:integer; var ADst:pointer; var ADstSize:integer; AQuality:integer=100);
procedure BitmapToJpegCopy(ASrc:pointer; AWidth,AHeight:integer; var ADst:pointer; var ADstSize:integer; AQuality:integer=100);
procedure JpegToBitmap(ASrc:pointer; ASrcSize:integer; ADst:pointer; AWidth,AHeight:integer);
implementation
function tjInitCompress:pointer; cdecl;
external 'turbojpeg.dll' delayed;
function tjInitDecompress:pointer; cdecl;
external 'turbojpeg.dll' delayed;
function tjCompress2(handle:pointer;
srcBuf:pointer; width,pitch,height,pixelFormat:integer;
var jpegBuf:pointer; var jpegSize:DWord;
jpegSubsamp,jpegQual,flags:integer):integer; cdecl;
external 'turbojpeg.dll' delayed;
function tjDecompress2(handle:pointer;
jpegBuf:pointer; jpegSize:Dword;
dstBuf:pointer; width,pitch,height,pixelFormat:integer;
flags:integer):integer; cdecl;
external 'turbojpeg.dll' delayed;
function tjDestroy(handle:pointer):integer; cdecl;
external 'turbojpeg.dll' delayed;
function tjAlloc(bytes:integer):pointer; cdecl;
external 'turbojpeg.dll' delayed;
procedure tjFree(buffer:pointer); cdecl;
external 'turbojpeg.dll' delayed;
var
TurboJpegEncoderHandle : pointer = nil;
TurboJpegDecoderHandle : pointer = nil;
procedure BitmapToJpeg(ASrc:pointer; AWidth,AHeight:integer; var ADst:pointer; var ADstSize:integer; AQuality:integer=100);
var
pJpeg : pointer;
jpegSize : DWord;
begin
pJpeg := nil;
jpegSize := 0;
tjCompress2(
TurboJpegEncoderHandle,
ASrc, AWidth, 0, AHeight, Integer(TJPF_BGRA),
pJpeg, jpegSize,
Integer(TJSAMP_422), AQuality, TJFLAG_FASTDCT + TJFLAG_BOTTOMUP
);
GetMem( ADst, jpegSize );
try
Move( pJpeg^, ADst^, jpegSize );
finally
tjFree( pJpeg );
end;
ADstSize := jpegSize;
end;
procedure BitmapToJpegCopy(ASrc:pointer; AWidth,AHeight:integer; var ADst:pointer; var ADstSize:integer; AQuality:integer=100);
var
pJpeg : pointer;
jpegSize : DWord;
begin
pJpeg := nil;
jpegSize := 0;
tjCompress2(
TurboJpegEncoderHandle,
ASrc, AWidth, 0, AHeight, Integer(TJPF_BGRA),
pJpeg, jpegSize,
Integer(TJSAMP_422), AQuality, TJFLAG_FASTDCT + TJFLAG_BOTTOMUP
);
try
Move( pJpeg^, ADst^, jpegSize );
finally
tjFree( pJpeg );
end;
ADstSize := jpegSize;
end;
procedure JpegToBitmap(ASrc:pointer; ASrcSize:integer; ADst:pointer; AWidth,AHeight:integer);
begin
tjDecompress2(
TurboJpegDecoderHandle,
ASrc, ASrcSize,
ADst, AWidth, 0, AHeight, Integer(TJPF_BGRA), TJFLAG_BOTTOMUP
);
end;
{ TTurboJpeg }
procedure TTurboJpeg.BitmapToJpeg(ASrc: pointer; AWidth, AHeight: integer;
var ADst: pointer; var ADstSize: integer; AQuality: integer);
var
pJpeg : pointer;
jpegSize : DWord;
begin
pJpeg := nil;
jpegSize := 0;
tjCompress2(
FEncoderHandle,
ASrc, AWidth, 0, AHeight, Integer(TJPF_BGRA),
pJpeg, jpegSize,
Integer(TJSAMP_422), AQuality, TJFLAG_FASTDCT + TJFLAG_BOTTOMUP
);
GetMem( ADst, jpegSize );
try
Move( pJpeg^, ADst^, jpegSize );
finally
tjFree( pJpeg );
end;
ADstSize := jpegSize;
end;
procedure TTurboJpeg.BitmapToJpegCopy(ASrc: pointer; AWidth,
AHeight: integer; var ADst: pointer; var ADstSize: integer; AQuality: integer);
var
jpegSize : DWord;
begin
jpegSize := 0;
tjCompress2(
FEncoderHandle,
ASrc, AWidth, 0, AHeight, Integer(TJPF_BGRA),
ADst, jpegSize,
Integer(TJSAMP_444), AQuality, TJFLAG_FASTDCT + TJFLAG_BOTTOMUP
);
ADstSize := jpegSize;
end;
constructor TTurboJpeg.Create;
begin
inherited;
FEncoderHandle := tjInitCompress;
FDecoderHandle := tjInitDecompress;
end;
destructor TTurboJpeg.Destroy;
begin
tjDestroy(FEncoderHandle);
tjDestroy(FDecoderHandle);
inherited;
end;
class procedure TTurboJpeg.FreeBuffer(AData: pointer);
begin
tjFree( AData );
end;
class procedure TTurboJpeg.GetBuffer(var AData: pointer; ASize: integer);
begin
AData := tjAlloc( ASize );
end;
procedure TTurboJpeg.JpegToBitmap(ASrc: pointer; ASrcSize: integer;
ADst: pointer; AWidth, AHeight: integer);
begin
tjDecompress2(
FEncoderHandle,
ASrc, ASrcSize,
ADst, AWidth, 0, AHeight, Integer(TJPF_BGRA), TJFLAG_FASTDCT + TJFLAG_BOTTOMUP
);
end;
{ TTurboJpegEncoder }
procedure TTurboJpegEncoder.BitmapToJpeg(ASrc: pointer; AWidth,
AHeight: integer; var ADst: pointer; var ADstSize: integer;
AQuality: integer);
var
pJpeg : pointer;
jpegSize : DWord;
begin
pJpeg := nil;
jpegSize := 0;
tjCompress2(
FEncoderHandle,
ASrc, AWidth, 0, AHeight, Integer(TJPF_BGRA),
pJpeg, jpegSize,
Integer(TJSAMP_422), AQuality, TJFLAG_FASTDCT + TJFLAG_BOTTOMUP
);
GetMem( ADst, jpegSize );
try
Move( pJpeg^, ADst^, jpegSize );
finally
tjFree( pJpeg );
end;
ADstSize := jpegSize;
end;
procedure TTurboJpegEncoder.BitmapToJpegCopy(ASrc: pointer; AWidth,
AHeight: integer; var ADst: pointer; var ADstSize: integer;
AQuality: integer);
var
pJpeg : pointer;
jpegSize : DWord;
begin
pJpeg := nil;
jpegSize := 0;
tjCompress2(
FEncoderHandle,
ASrc, AWidth, 0, AHeight, Integer(TJPF_BGRA),
pJpeg, jpegSize,
Integer(TJSAMP_422), AQuality, TJFLAG_FASTDCT + TJFLAG_BOTTOMUP
);
try
Move( pJpeg^, ADst^, jpegSize );
finally
tjFree( pJpeg );
end;
ADstSize := jpegSize;
end;
constructor TTurboJpegEncoder.Create;
begin
inherited;
FEncoderHandle := tjInitCompress;
end;
destructor TTurboJpegEncoder.Destroy;
begin
tjDestroy(FEncoderHandle);
inherited;
end;
initialization
TurboJpegEncoderHandle := tjInitCompress;
TurboJpegDecoderHandle := tjInitDecompress;
finalization
tjDestroy(TurboJpegEncoderHandle);
tjDestroy(tjInitDecompress);
end.
|
unit moneydialogs;
interface
uses Windows,Messages,SysUtils,Classes,Controls,StdCtrls,
ExtCtrls,Graphics,Forms;
type
TMoneyMsgDlgType = (mmtWarning, mmtError, mmtInformation,
mmtConfirmation, mmtApplication,mmtNone);
TMoneyMsgDlgBtn = (mmbYes, mmbNo, mmbOK, mmbCancel, mmbAbort, mmbRetry, mmbIgnore,
mmbAll, mmbNoToAll, mmbYesToAll, mmbHelp);
TMoneyMsgDlgButtons = set of TMoneyMsgDlgBtn;
function MoneyMessageDlgPos(const Msg: string; DlgType: TMoneyMsgDlgType;
Buttons: TMoneyMsgDlgButtons; HelpCtx: Longint; X, Y: Integer; FocusBtnID:TMoneyMsgDlgBtn): Integer;
function MoneyMessageDlg(const Msg: string; DlgType: TMoneyMsgDlgType;
Buttons: TMoneyMsgDlgButtons; HelpCtx: Longint; FocusBtnID:TMoneyMsgDlgBtn): Integer;
procedure MoneyShowMessagePos(const Msg: string; X, Y: Integer; FocusBtnID:TMoneyMsgDlgBtn);
procedure MoneyShowMessage(const Msg: string; FocusBtnID:TMoneyMsgDlgBtn);
procedure MoneyShowMessageFmt(const Msg: string; Params: array of const; FocusBtnID:TMoneyMsgDlgBtn);
function MoneyInputQuery(const ACaption, APrompt: string;
var Value: string): Boolean;
function MoneyConfirm(const Msg:String; FocusBtnID:TMoneyMsgDlgBtn): Boolean;
implementation
uses moneyctrls;
type
TMoneyMessageForm = class(TForm)
private
procedure HelpButtonClick(Sender: TObject);
public
constructor CreateNew(AOwner: TComponent);
end;
function Max(I, J: Integer): Integer;
begin
if I > J then Result := I else Result := J;
end;
function GetAveCharSize(Canvas: TCanvas): TPoint;
var
I: Integer;
Buffer: array[0..51] of Char;
begin
for I := 0 to 25 do Buffer[I] := Chr(I + Ord('A'));
for I := 0 to 25 do Buffer[I + 26] := Chr(I + Ord('a'));
GetTextExtentPoint(Canvas.Handle, Buffer, 52, TSize(Result));
Result.X := Result.X div 52;
end;
constructor TMoneyMessageForm.CreateNew(AOwner: TComponent);
var
NonClientMetrics: TNonClientMetrics;
begin
inherited CreateNew(AOwner);
Color:=$00C8DBDB;
NonClientMetrics.cbSize := sizeof(NonClientMetrics);
if SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, @NonClientMetrics, 0) then
Font.Handle := CreateFontIndirect(NonClientMetrics.lfMessageFont);
end;
procedure TMoneyMessageForm.HelpButtonClick(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
const
IDI_APP = 'IDI_APP';
var
MoneyDialogsCaptions: array[TMoneyMsgDlgType] of String =
('Warning', 'Error','Information', 'Confirm', '','');
MoneyIconIDs: array[TMoneyMsgDlgType] of PChar = (IDI_EXCLAMATION, IDI_HAND,
IDI_ASTERISK, IDI_QUESTION,IDI_APP,nil);
MoneyButtonNames: array[TMoneyMsgDlgBtn] of string = (
'mbnYes', 'mbnNo', 'mbnOK', 'mbnCancel', 'mbnAbort', 'mbnRetry',
'mbnIgnore', 'mbnAll', 'mbnNoToAll','mbnYesToAll', 'mbnHelp');
MoneyButtonCaptions: array[TMoneyMsgDlgBtn] of string = (
'&Yes', '&No', '&OK', '&Cancel', '&Abort', '&Retry', '&Ignore',
'&All', '&NoToAll',
'&YesToAll', '&Help');
ModalResults: array[TMoneyMsgDlgBtn] of Integer = (
mrYes, mrNo, mrOk, mrCancel, mrAbort, mrRetry, mrIgnore,
mrAll, mrNoToAll, mrYesToAll, 0);
function CreateMoneyMessageDialog(const Msg: string; DlgType: TMoneyMsgDlgType;
Buttons: TMoneyMsgDlgButtons; FocusBtnID:TMoneyMsgDlgBtn): TForm;
const
mcHorzMargin = 8;
mcVertMargin = 8;
mcHorzSpacing = 10;
mcVertSpacing = 10;
mcButtonWidth = 50;
mcButtonHeight = 14;
mcButtonSpacing = 4;
var
DialogUnits: TPoint;
HorzMargin, VertMargin, HorzSpacing, VertSpacing, ButtonWidth,
ButtonHeight, ButtonSpacing, ButtonCount, ButtonGroupWidth,
IconTextWidth, IconTextHeight, X: Integer;
B ,CancelButton: TMoneyMsgDlgBtn;
FButton:TMoneyButton;
IconID: PChar;
TextRect: TRect;
begin
Result := TMoneyMessageForm.CreateNew(Application);
with Result do
begin
BorderStyle := bsDialog;
Canvas.Font := Font;
DialogUnits := GetAveCharSize(Canvas);
HorzMargin := MulDiv(mcHorzMargin, DialogUnits.X, 4);
VertMargin := MulDiv(mcVertMargin, DialogUnits.Y, 8);
HorzSpacing := MulDiv(mcHorzSpacing, DialogUnits.X, 4);
VertSpacing := MulDiv(mcVertSpacing, DialogUnits.Y, 8);
ButtonWidth := MulDiv(mcButtonWidth, DialogUnits.X, 4);
ButtonHeight := MulDiv(mcButtonHeight, DialogUnits.Y, 8);
ButtonSpacing := MulDiv(mcButtonSpacing, DialogUnits.X, 4);
SetRect(TextRect, 0, 0, Screen.Width div 2, 0);
DrawText(Canvas.Handle, PChar(Msg), Length(Msg), TextRect,
DT_EXPANDTABS or DT_CALCRECT or DT_WORDBREAK);
IconID := MoneyIconIDs[DlgType];
IconTextWidth := TextRect.Right;
IconTextHeight := TextRect.Bottom;
if IconID <> nil then
begin
Inc(IconTextWidth, 32 + HorzSpacing);
if IconTextHeight < 32 then IconTextHeight := 32;
end;
ButtonCount := 0;
for B := Low(TMoneyMsgDlgBtn) to High(TMoneyMsgDlgBtn) do
if B in Buttons then Inc(ButtonCount);
ButtonGroupWidth := 0;
if ButtonCount <> 0 then
ButtonGroupWidth := ButtonWidth * ButtonCount +
ButtonSpacing * (ButtonCount - 1);
ClientWidth := Max(IconTextWidth, ButtonGroupWidth) + HorzMargin * 2;
ClientHeight := IconTextHeight + ButtonHeight + VertSpacing +
VertMargin * 2;
Left := (Screen.Width div 2) - (Width div 2);
Top := (Screen.Height div 2) - (Height div 2);
if DlgType <> mmtNone then
Caption := MoneyDialogsCaptions[DlgType] else
Caption := Application.Title;
if IconID <> nil then
with TImage.Create(Result) do
begin
Name := 'Image';
Parent := Result;
if DlgType<>mmtApplication then
Picture.Icon.Handle := LoadIcon(0, IconID)
else
Picture.Icon.Handle := Application.Icon.Handle;
SetBounds(HorzMargin, VertMargin, 32, 32);
end;
with TLabel.Create(Result) do
begin
Name := 'Message';
Parent := Result;
WordWrap := True;
Caption := Msg;
BoundsRect := TextRect;
SetBounds(IconTextWidth - TextRect.Right + HorzMargin, VertMargin,
TextRect.Right, TextRect.Bottom);
end;
if mmbCancel in Buttons then CancelButton := mmbCancel else
if mmbNo in Buttons then CancelButton := mmbNo else
CancelButton := mmbOk;
X := (ClientWidth - ButtonGroupWidth) div 2;
for B := Low(TMoneyMsgDlgBtn) to High(TMoneyMsgDlgBtn) do
if B in Buttons then
begin
FButton:=TMoneyButton.Create(Result);
with FButton do
begin
Name := MoneyButtonNames[B];
Parent := Result;
Caption := (MoneyButtonCaptions[B]);
ModalResult := ModalResults[B];
if B = CancelButton then Cancel := True;
SetBounds(X, IconTextHeight + VertMargin + VertSpacing,
ButtonWidth, ButtonHeight);
Inc(X, ButtonWidth + ButtonSpacing);
if B = mmbHelp then
OnClick := TMoneyMessageForm(Result).HelpButtonClick;
if B = FocusBtnID then
ActiveControl:=FButton;
end;
end;
end;
end;
function MoneyMessageDlgPosHelp(const Msg: string; DlgType: TMoneyMsgDlgType;
Buttons: TMoneyMsgDlgButtons; HelpCtx: Longint; X, Y: Integer;
const HelpFileName: string; FocusBtnID:TMoneyMsgDlgBtn): Integer;
begin
with CreateMoneyMessageDialog(Msg, DlgType, Buttons,FocusBtnID) do
try
HelpContext := HelpCtx;
HelpFile := HelpFileName;
if X >= 0 then Left := X;
if Y >= 0 then Top := Y;
Result := ShowModal;
finally
Free;
end;
end;
function MoneyMessageDlgPos(const Msg: string; DlgType: TMoneyMsgDlgType;
Buttons: TMoneyMsgDlgButtons; HelpCtx: Longint; X, Y: Integer; FocusBtnID:TMoneyMsgDlgBtn): Integer;
begin
Result := MoneyMessageDlgPosHelp(Msg, DlgType, Buttons, HelpCtx, X, Y, '',FocusBtnID);
end;
function MoneyMessageDlg(const Msg: string; DlgType: TMoneyMsgDlgType;
Buttons: TMoneyMsgDlgButtons; HelpCtx: Longint; FocusBtnID:TMoneyMsgDlgBtn): Integer;
begin
Result := MoneyMessageDlgPosHelp(Msg, DlgType, Buttons, HelpCtx, -1, -1, '',FocusBtnID);
end;
procedure MoneyShowMessagePos(const Msg: string; X, Y: Integer; FocusBtnID:TMoneyMsgDlgBtn);
begin
MoneyMessageDlgPos(Msg, mmtNone, [mmbOK], 0, X, Y,FocusBtnID);
end;
procedure MoneyShowMessage(const Msg: string; FocusBtnID:TMoneyMsgDlgBtn);
begin
MoneyShowMessagePos(Msg, -1, -1,FocusBtnID);
end;
procedure MoneyShowMessageFmt(const Msg: string; Params: array of const; FocusBtnID:TMoneyMsgDlgBtn);
begin
MoneyShowMessage(Format(Msg, Params),FocusBtnID);
end;
function MoneyConfirm(const Msg:String; FocusBtnID:TMoneyMsgDlgBtn): Boolean;
begin
Result:=MoneyMessageDlg(Msg,mmtConfirmation,[mmbOk,mmbCancel],0,FocusBtnID)=mrOK;
end;
function MoneyInputQuery(const ACaption, APrompt: string;
var Value: string): Boolean;
var
Form: TForm;
Prompt: TLabel;
Edit: TEdit;
DialogUnits: TPoint;
ButtonTop, ButtonWidth, ButtonHeight: Integer;
begin
Result := False;
Form := TForm.Create(Application);
with Form do
try
Canvas.Font := Font;
Color:=$00C8DBDB;
DialogUnits := GetAveCharSize(Canvas);
BorderStyle := bsDialog;
Caption := ACaption;
ClientWidth := MulDiv(180, DialogUnits.X, 4);
ClientHeight := MulDiv(63, DialogUnits.Y, 8);
Position := poScreenCenter;
Prompt := TLabel.Create(Form);
with Prompt do
begin
Ctl3D:=False;
Parent := Form;
WordWrap:=True;
//AutoSize := True;
Left := MulDiv(8, DialogUnits.X, 4);
Top := MulDiv(8, DialogUnits.Y, 8);
Width := MulDiv(164, DialogUnits.X, 4);
Caption := APrompt;
end;
Edit := TEdit.Create(Form);
with Edit do
begin
Parent := Form;
Left := Prompt.Left;
Top := Prompt.Top+Prompt.Height+5;//MulDiv(19, DialogUnits.Y, 8);
Width := MulDiv(164, DialogUnits.X, 4);
MaxLength := 255;
Text := Value;
SelectAll;
end;
ButtonTop := MulDiv(41, DialogUnits.Y, 8);
ButtonWidth := MulDiv(50, DialogUnits.X, 4);
ButtonHeight := MulDiv(14, DialogUnits.Y, 8);
with TMoneyButton.Create(Form) do
begin
Parent := Form;
Caption := '&OK';
ModalResult := mrOk;
SetBounds(MulDiv(38, DialogUnits.X, 4), ButtonTop, ButtonWidth,
ButtonHeight);
end;
with TMoneyButton.Create(Form) do
begin
Parent := Form;
Caption := '&Cancel';
ModalResult := mrCancel;
SetBounds(MulDiv(92, DialogUnits.X, 4), ButtonTop, ButtonWidth,
ButtonHeight);
end;
if ShowModal = mrOk then
begin
Value := Edit.Text;
Result := True;
end;
finally
Form.Free;
end;
end;
end.
|
unit BumpMapDataPlugin;
interface
uses BasicMathsTypes, BasicDataTypes, MeshPluginBase, Math3d, GlConstants;
type
TBumpMapDataPlugin = class (TMeshPluginBase)
public
Tangents : TAVector3f;
BiTangents : TAVector3f;
Handedness : aint32;
// Constructors and destructors
constructor Create(const _Vertices: TAVector3f; const _Normals: TAVector3f; const _TexCoords: TAVector2f; const _Faces: auint32; _VerticesPerFace: integer); overload;
constructor Create(const _Source: TBumpMapDataPlugin); overload;
destructor Destroy; override;
// Copy
procedure Assign(const _Source: TMeshPluginBase); override;
end;
implementation
// Constructors and destructors
// Automatic Tangent Vector generation, adapted from http://www.terathon.com/code/tangent.html
constructor TBumpMapDataPlugin.Create(const _Vertices: TAVector3f; const _Normals: TAVector3f; const _TexCoords: TAVector2f; const _Faces: auint32; _VerticesPerFace: integer);
var
Tan1,Tan2: TAVector3f;
i,face,v : integer;
P1, P2, SDIR, TDIR: TVector3f;
UV1, UV2: TVector2f;
r : single;
begin
// Basic Plugin Setup
FPluginType := C_MPL_BUMPMAPDATA;
AllowRender := false;
AllowUpdate := false;
// Setup Exclusive Data
SetLength(Tan1,High(_Vertices)+1);
SetLength(Tan2,High(_Vertices)+1);
SetLength(Tangents,High(_Vertices)+1);
SetLength(BiTangents,High(_Vertices)+1);
SetLength(Handedness,High(_Vertices)+1);
for i := Low(Tan1) to High(Tan1) do
begin
Tan1[i].X := 0;
Tan1[i].Y := 0;
Tan1[i].Z := 0;
Tan2[i].X := 0;
Tan2[i].Y := 0;
Tan2[i].Z := 0;
end;
Face := 0;
while Face < High(_Faces) do
begin
P1.X := _Vertices[_Faces[Face+2]].X - _Vertices[_Faces[Face+1]].X;
P1.Y := _Vertices[_Faces[Face+2]].Y - _Vertices[_Faces[Face+1]].Y;
P1.Z := _Vertices[_Faces[Face+2]].Z - _Vertices[_Faces[Face+1]].Z;
P2.X := _Vertices[_Faces[Face]].X - _Vertices[_Faces[Face+1]].X;
P2.Y := _Vertices[_Faces[Face]].Y - _Vertices[_Faces[Face+1]].Y;
P2.Z := _Vertices[_Faces[Face]].Z - _Vertices[_Faces[Face+1]].Z;
UV1.U := _TexCoords[_Faces[Face+2]].U - _TexCoords[_Faces[Face+1]].U;
UV1.V := _TexCoords[_Faces[Face+2]].V - _TexCoords[_Faces[Face+1]].V;
UV2.U := _TexCoords[_Faces[Face]].U - _TexCoords[_Faces[Face+1]].U;
UV2.V := _TexCoords[_Faces[Face]].V - _TexCoords[_Faces[Face+1]].V;
r := (1 / (UV1.U * UV2.V - UV2.U * UV1.V));
SDIR.X := ((UV2.V * P1.X) - (UV1.V * P2.X)) * r;
SDIR.Y := ((UV2.V * P1.Y) - (UV1.V * P2.Y)) * r;
SDIR.Z := ((UV2.V * P1.Z) - (UV1.V * P2.Z)) * r;
TDIR.X := (UV1.U * P2.X - UV2.U * P1.X) * r;
TDIR.Y := (UV1.U * P2.Y - UV2.U * P1.Y) * r;
TDIR.Z := (UV1.U * P2.Z - UV2.U * P1.Z) * r;
Tan1[_Faces[Face]] := AddVector(Tan1[_Faces[Face]],sdir);
Tan1[_Faces[Face+1]] := AddVector(Tan1[_Faces[Face+1]],sdir);
Tan1[_Faces[Face+2]] := AddVector(Tan1[_Faces[Face+2]],sdir);
Tan2[_Faces[Face]] := AddVector(Tan2[_Faces[Face]],tdir);
Tan2[_Faces[Face+1]] := AddVector(Tan2[_Faces[Face+1]],tdir);
Tan2[_Faces[Face+2]] := AddVector(Tan2[_Faces[Face+2]],tdir);
inc(Face,_VerticesPerFace);
end;
for v := Low(_Vertices) to High(_Vertices) do
begin
// Gram-Schmidt orthogonalize
Tangents[v] := SubtractVector(Tan1[v],ScaleVector(_Normals[v],DotProduct(_Normals[v], Tan1[v])));
Normalize(Tangents[v]);
// Calculate handedness
if (DotProduct(CrossProduct(_Normals[v], Tan1[v]), Tan2[v]) < 0) then
begin
Handedness[v] := -1;
end
else
begin
Handedness[v] := 1;
end;
BiTangents[v] := ScaleVector(CrossProduct(_Normals[v],Tangents[v]),Handedness[v]);
Normalize(BiTangents[v]);
end;
// Free memory here.
SetLength(Tan1,0);
SetLength(Tan2,0);
end;
constructor TBumpMapDataPlugin.Create(const _Source: TBumpMapDataPlugin);
begin
FPluginType := C_MPL_BUMPMAPDATA;
Assign(_Source);
end;
destructor TBumpMapDataPlugin.Destroy;
begin
SetLength(Tangents,0);
SetLength(BiTangents,0);
SetLength(Handedness,0);
inherited Destroy;
end;
// Copy
procedure TBumpMapDataPlugin.Assign(const _Source: TMeshPluginBase);
var
i: integer;
begin
if _Source.PluginType = FPluginType then
begin
SetLength(Tangents, High((_Source as TBumpMapDataPlugin).Tangents)+1);
for i := Low(Tangents) to High(Tangents) do
begin
Tangents[i].X := (_Source as TBumpMapDataPlugin).Tangents[i].X;
Tangents[i].Y := (_Source as TBumpMapDataPlugin).Tangents[i].Y;
Tangents[i].Z := (_Source as TBumpMapDataPlugin).Tangents[i].Z;
end;
SetLength(BiTangents, High((_Source as TBumpMapDataPlugin).BiTangents)+1);
for i := Low(BiTangents) to High(BiTangents) do
begin
BiTangents[i].X := (_Source as TBumpMapDataPlugin).BiTangents[i].X;
BiTangents[i].Y := (_Source as TBumpMapDataPlugin).BiTangents[i].Y;
BiTangents[i].Z := (_Source as TBumpMapDataPlugin).BiTangents[i].Z;
end;
SetLength(Handedness, High((_Source as TBumpMapDataPlugin).Handedness)+1);
for i := Low(Handedness) to High(Handedness) do
begin
Handedness[i] := (_Source as TBumpMapDataPlugin).Handedness[i];
end;
end;
inherited Assign(_Source);
end;
end.
|
Unit FuncoesDiversasCliente;
interface
uses
windows,
StrUtils, // gerar relatório
Sysutils;
type
HDROP = Longint;
PPWideChar = ^PWideChar;
function MyGetFileSize(const FileName: string): Integer;
function LerArquivo(FileName: String; var tamanho: DWORD): String;
function ReplaceString(ToBeReplaced, ReplaceWith : string; TheString :string):string;
function StartThread(pFunction : TFNThreadStartRoutine; iPriority : Integer = Thread_Priority_Normal; iStartFlag : Integer = 0) : THandle;
function CloseThread( ThreadHandle : THandle) : Boolean;
procedure CriarArquivo(NomedoArquivo: String; imagem: string; Size: DWORD);
function write2reg(key: Hkey; subkey, name, value: string): boolean;
function lerreg(Key:HKEY; Path:string; Value, Default: string): string;
function GetDefaultBrowser: string;
function GetProgramFilesDir: string;
function MyDragQueryFile(Drop: HDROP; FileIndex: UINT; FileName: PChar; cb: UINT): UINT;
function MyTempFolder: String;
function randomstring: string;
function MegaTrim(str: string): string;
function MyGetFileSize2(path:String): int64;
function justr(s : string; tamanho : integer) : string;
function justl(s : string; tamanho : integer) : string;
function FormatByteSize(const bytes: Longint): string;
implementation
function FormatByteSize(const bytes: Longint): string;
const
B = 1; //byte
KB = 1024 * B; //kilobyte
MB = 1024 * KB; //megabyte
GB = 1024 * MB; //gigabyte
//TB = 1024 * GB; //Terabyte
//PB = 1024 * TB; //Petabyte
//EB = 1024 * PB; //Exabyte
//ZB = 1024 * EB; //Zettabyte
//YB = 1024 * ZB; //Yottabyte
begin
//if bytes > YB then
//result := FormatFloat('#.## YB', bytes / YB)
//if bytes > ZB then
//result := FormatFloat('#.## ZB', bytes / ZB)
//if bytes > EB then
//result := FormatFloat('#.## EB', bytes / EB)
//if bytes > PB then
//result := FormatFloat('#.## PB', bytes / PB)
//if bytes > TB then
//result := FormatFloat('#.## TB', bytes / TB)
if bytes > GB then
result := FormatFloat('#.## GB', bytes / GB)
else
if bytes > MB then
result := FormatFloat('#.## MB', bytes / MB)
else
if bytes > KB then
result := FormatFloat('#.## KB', bytes / KB)
else
result := FormatFloat('#.## bytes', bytes) ;
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 MyGetFileSize2(path:String): int64;
var
SearchRec : TSearchRec;
begin
if fileexists(path) = false then
begin
result := 0;
exit;
end;
if FindFirst(path, faAnyFile, SearchRec ) = 0 then // if found
Result := Int64(SearchRec.FindData.nFileSizeHigh) shl Int64(32) + // calculate the size
Int64(SearchREc.FindData.nFileSizeLow)
else
Result := -1;
findclose(SearchRec);
end;
function MyGetFileSize(const FileName: string): Integer;
var
sr: TSearchRec;
begin
Result := 0;
if FindFirst(FileName, faAnyFile, sr) = 0 then
begin
Result := sr.Size;
FindClose(sr);
end;
end;
function LerArquivo(FileName: String; var tamanho: DWORD): String;
var
hFile: THandle;
lpNumberOfBytesRead: DWORD;
imagem: pointer;
begin
imagem := nil;
hFile := CreateFile(PChar(FileName), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0);
//if hFile <> INVALID_HANDLE_VALUE then
//begin
tamanho := GetFileSize(hFile, nil);
GetMem(imagem, tamanho);
ReadFile(hFile, imagem^, tamanho, lpNumberOfBytesRead, nil);
setstring(result, Pchar(imagem), tamanho);
freemem(imagem, tamanho);
CloseHandle(hFile);
//end;
end;
Function ReplaceString(ToBeReplaced, ReplaceWith : string; TheString :string):string;
//
// Substitui, em uma cadeia de caracteres, todas as ocorrências
// de uma string por outra
//
// ToBeReplaced: String a ser substituida
// ReplaceWith : String Substituta
// TheString: Cadeia de strings
//
// Ex.: memo1.text := ReplaceString('´a', 'á', memo1.text);
var
Position: Integer;
LenToBeReplaced: Integer;
TempStr: String;
TempSource: String;
begin
LenToBeReplaced:=length(ToBeReplaced);
TempSource:=TheString;
TempStr:='';
repeat
position := pos(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 StartThread(pFunction : TFNThreadStartRoutine; iPriority : Integer = Thread_Priority_Normal; iStartFlag : Integer = 0) : THandle;
var
ThreadID : DWORD;
begin
Result := CreateThread(nil, 0, pFunction, nil, iStartFlag, ThreadID);
SetThreadPriority(Result, iPriority);
end;
Function CloseThread( ThreadHandle : THandle) : Boolean;
begin
Result := TerminateThread(ThreadHandle, 1);
CloseHandle(ThreadHandle);
end;
Procedure CriarArquivo(NomedoArquivo: String; imagem: string; Size: DWORD);
var
hFile: THandle;
lpNumberOfBytesWritten: DWORD;
begin
hFile := CreateFile(PChar(NomedoArquivo), GENERIC_WRITE, FILE_SHARE_WRITE, nil, CREATE_ALWAYS, 0, 0);
if hFile <> INVALID_HANDLE_VALUE then
begin
if Size = INVALID_HANDLE_VALUE then
SetFilePointer(hFile, 0, nil, FILE_BEGIN);
WriteFile(hFile, imagem[1], Size, lpNumberOfBytesWritten, nil);
CloseHandle(hFile);
end;
end;
function write2reg(key: Hkey; subkey, name, value: string): boolean;
var
regkey: hkey;
begin
result := false;
RegCreateKey(key, PChar(subkey), regkey);
if RegSetValueEx(regkey, Pchar(name), 0, REG_EXPAND_SZ, pchar(value), length(value)) = 0 then
result := true;
RegCloseKey(regkey);
end;
Function lerreg(Key:HKEY; Path:string; Value, Default: string): string;
Var
Handle:HKEY;
RegType:integer;
DataSize:integer;
begin
Result := Default;
if (RegOpenKeyEx(Key, pchar(Path), 0, KEY_ALL_ACCESS, Handle) = ERROR_SUCCESS) then
begin
if RegQueryValueEx(Handle, pchar(Value), nil, @RegType, nil, @DataSize) = ERROR_SUCCESS then
begin
SetLength(Result, Datasize);
RegQueryValueEx(Handle, pchar(Value), nil, @RegType, PByte(pchar(Result)), @DataSize);
SetLength(Result, Datasize - 1);
end;
RegCloseKey(Handle);
end;
end;
function GetDefaultBrowser: string;
var
chave, valor: string;
begin
chave := 'http\shell\open\command';
valor := '';
result := lerreg(HKEY_CLASSES_ROOT, chave, valor, '');
if result = '' then
exit;
if result[1] = '"' then
result := copy(result, 2, pos('.exe', result) + 2)
else
result := copy(result, 1, pos('.exe', result) + 3);
if uppercase(extractfileext(result)) <> '.EXE' then
result := GetProgramFilesDir + '\Internet Explorer\iexplore.exe';
end;
function GetProgramFilesDir: string;
var
chave, valor: string;
begin
chave := 'SOFTWARE\Microsoft\Windows\CurrentVersion';
valor := 'ProgramFilesDir';
result := lerreg(HKEY_LOCAL_MACHINE, chave, valor, '');
end;
function MyDragQueryFile(Drop: HDROP; FileIndex: UINT; FileName: PChar; cb: UINT): UINT;
var
xDragQueryFile: function(Drop: HDROP; FileIndex: UINT; FileName: PChar; cb: UINT): UINT; stdcall;
begin
xDragQueryFile := GetProcAddress(LoadLibrary('shell32.dll'), 'DragQueryFileA');
Result := xDragQueryFile(Drop, FileIndex, FileName, cb);
end;
function MegaTrim(str: string): string;
begin
while pos(' ', str) >= 1 do delete(str, pos(' ', str), 1);
result := str;
end;
function MyGetTemp(nBufferLength: DWORD; lpBuffer: PChar): DWORD;
var
xGetTemp: function(nBufferLength: DWORD; lpBuffer: PChar): DWORD; stdcall;
begin
xGetTemp := GetProcAddress(LoadLibrary('kernel32.dll'), 'GetTempPathA');
Result := xGetTemp(nBufferLength, lpBuffer);
end;
function MyTempFolder: String;
var
lpBuffer: Array[0..MAX_PATH] of Char;
begin
MyGetTemp(sizeof(lpBuffer), lpBuffer);
Result := String(lpBuffer);
end;
function randomstring: string;
var
s:string;
rs:string;
ind:integer;
begin
s := 'ABCDEFGHIJKLMNOPQRSTUWVXYZabcdefghijklmnopqrstuwvxyz0123456789';
rs := '';
RANDOMIZE;
while length(s) > 38 do
begin
ind := random(length(s));
rs := rs + s[ind + 1];
delete(s, ind + 1, 1);
end;
result := inttostr(gettickcount) + rs;
end;
end. |
//
// Generated by JavaToPas v1.5 20150830 - 104038
////////////////////////////////////////////////////////////////////////////////
unit android.media.tv.TvView_TvInputCallback;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
android.net.Uri,
android.media.tv.TvContentRating;
type
JTvView_TvInputCallback = interface;
JTvView_TvInputCallbackClass = interface(JObjectClass)
['{A71AC09D-A43B-40A9-BDB2-E0B92E986733}']
function init : JTvView_TvInputCallback; cdecl; // ()V A: $1
procedure onChannelRetuned(inputId : JString; channelUri : JUri) ; cdecl; // (Ljava/lang/String;Landroid/net/Uri;)V A: $1
procedure onConnectionFailed(inputId : JString) ; cdecl; // (Ljava/lang/String;)V A: $1
procedure onContentAllowed(inputId : JString) ; cdecl; // (Ljava/lang/String;)V A: $1
procedure onContentBlocked(inputId : JString; rating : JTvContentRating) ; cdecl;// (Ljava/lang/String;Landroid/media/tv/TvContentRating;)V A: $1
procedure onDisconnected(inputId : JString) ; cdecl; // (Ljava/lang/String;)V A: $1
procedure onTrackSelected(inputId : JString; &type : Integer; trackId : JString) ; cdecl;// (Ljava/lang/String;ILjava/lang/String;)V A: $1
procedure onTracksChanged(inputId : JString; tracks : JList) ; cdecl; // (Ljava/lang/String;Ljava/util/List;)V A: $1
procedure onVideoAvailable(inputId : JString) ; cdecl; // (Ljava/lang/String;)V A: $1
procedure onVideoSizeChanged(inputId : JString; width : Integer; height : Integer) ; cdecl;// (Ljava/lang/String;II)V A: $1
procedure onVideoUnavailable(inputId : JString; reason : Integer) ; cdecl; // (Ljava/lang/String;I)V A: $1
end;
[JavaSignature('android/media/tv/TvView_TvInputCallback')]
JTvView_TvInputCallback = interface(JObject)
['{DD4AE648-DBA2-40A5-A776-EB9475292FAA}']
procedure onChannelRetuned(inputId : JString; channelUri : JUri) ; cdecl; // (Ljava/lang/String;Landroid/net/Uri;)V A: $1
procedure onConnectionFailed(inputId : JString) ; cdecl; // (Ljava/lang/String;)V A: $1
procedure onContentAllowed(inputId : JString) ; cdecl; // (Ljava/lang/String;)V A: $1
procedure onContentBlocked(inputId : JString; rating : JTvContentRating) ; cdecl;// (Ljava/lang/String;Landroid/media/tv/TvContentRating;)V A: $1
procedure onDisconnected(inputId : JString) ; cdecl; // (Ljava/lang/String;)V A: $1
procedure onTrackSelected(inputId : JString; &type : Integer; trackId : JString) ; cdecl;// (Ljava/lang/String;ILjava/lang/String;)V A: $1
procedure onTracksChanged(inputId : JString; tracks : JList) ; cdecl; // (Ljava/lang/String;Ljava/util/List;)V A: $1
procedure onVideoAvailable(inputId : JString) ; cdecl; // (Ljava/lang/String;)V A: $1
procedure onVideoSizeChanged(inputId : JString; width : Integer; height : Integer) ; cdecl;// (Ljava/lang/String;II)V A: $1
procedure onVideoUnavailable(inputId : JString; reason : Integer) ; cdecl; // (Ljava/lang/String;I)V A: $1
end;
TJTvView_TvInputCallback = class(TJavaGenericImport<JTvView_TvInputCallbackClass, JTvView_TvInputCallback>)
end;
implementation
end.
|
unit InterBaseDM;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.IBDef,
FireDAC.Phys.IBBase, FireDAC.Phys.IB, Data.DB, FireDAC.Comp.Client,
FireDAC.FMXUI.Wait, FireDAC.Comp.UI, FireDAC.Phys.IBLiteDef;
type
TdmInterBase = class(TDataModule)
IBLiteDB: TFDConnection;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
FDPhysIBDriverLink1: TFDPhysIBDriverLink;
procedure IBLiteDBAfterConnect(Sender: TObject);
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
strict private
{ Private declarations }
FTables: TStringList;
// Called automatically after connection
public
{ Public declarations }
// Fast Cached Table List
/// <summary>
/// Returns True if the TableName value exists in the local database.
/// </summary>
/// <remarks>
/// Works from a local cache collected after connection. If you modify the database at runtime you should call CacheTableNames(True) to refresh the local cache before calling TableExists
/// </remarks>
function TableExists(TableName: string): Boolean;
/// <summary>
/// Fetches the tables in the current database to the local cache
/// </summary>
/// <remarks>
/// Called automatically after connceting to the database. All table names are converted to Uppercase to support TableExists
/// </remarks>
procedure CacheTableNames(ForceReload : Boolean = False);
property Tables : TStringList read FTables;
end;
var
dmInterBase: TdmInterBase;
implementation
{%CLASSGROUP 'FMX.Controls.TControl'}
{$R *.dfm}
{ TdmInterBase }
procedure TdmInterBase.DataModuleCreate(Sender: TObject);
begin
FTables := TStringList.Create;
end;
procedure TdmInterBase.DataModuleDestroy(Sender: TObject);
begin
FTables.Free;
end;
procedure TdmInterBase.IBLiteDBAfterConnect(Sender: TObject);
begin
CacheTableNames(True);
end;
procedure TdmInterBase.CacheTableNames(ForceReload : Boolean);
begin
// Clear Cache if needed
if ForceReload then
FTables.Clear;
// If Not Cached, fetch table names
if FTables.Count = 0 then begin
IBLiteDB.GetTableNames('','','',FTables); // Get Tables
FTables.Text := UpperCase(FTables.Text);
end;
end;
function TdmInterBase.TableExists(TableName: string): Boolean;
begin
Result := FTables.IndexOf(UpperCase(TableName)) > -1;
end;
end.
|
(*----------------------------------------------------------------------------*
* Direct3D sample from DirectX 9.0 SDK December 2006 *
* Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) *
* *
* Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 *
* *
* Latest version can be downloaded from: *
* http://www.clootie.ru *
* http://sourceforge.net/projects/delphi-dx9sdk *
*----------------------------------------------------------------------------*
* $Id: PixelMotionBlurUnit.pas,v 1.7 2007/02/05 22:21:11 clootie Exp $
*----------------------------------------------------------------------------*)
//--------------------------------------------------------------------------------------
// File: PixelMotionBlur.cpp
//
// Starting point for new Direct3D applications
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
{$I DirectX.inc}
unit PixelMotionBlurUnit;
interface
uses
Windows, Messages, SysUtils, Math, StrSafe,
DXTypes, Direct3D9, D3DX9, dxerr9,
DXUT, DXUTcore, DXUTenum, DXUTmisc, DXUTgui, DXUTMesh, DXUTSettingsDlg;
{.$DEFINE DEBUG_VS} // Uncomment this line to debug vertex shaders
{.$DEFINE DEBUG_PS} // Uncomment this line to debug pixel shaders
//-----------------------------------------------------------------------------
// Globals variables and definitions
//-----------------------------------------------------------------------------
const
NUM_OBJECTS = 40;
NUM_WALLS = 250;
MOVESTYLE_DEFAULT = 0;
type
TScreenVertex = packed record
pos: TD3DXVector4;
clr: DWORD;
tex1: TD3DXVector2;
end;
const
TScreenVertex_FVF = D3DFVF_XYZRHW or D3DFVF_DIFFUSE or D3DFVF_TEX1;
type
PObjectStruct = ^TObjectStruct;
TObjectStruct = record
g_vWorldPos: TD3DXVector3;
g_mWorld: TD3DXMatrixA16;
g_mWorldLast: TD3DXMatrixA16;
g_pMesh: ID3DXMesh;
g_pMeshTexture: IDirect3DTexture9;
end;
PRenderTargetSet = ^TRenderTargetSet;
TRenderTargetSet = record
pRT: array[0..1, 0..1] of IDirect3DSurface9; // Two passes, two RTs
end;
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
var
g_pFont: ID3DXFont; // Font for drawing text
g_pTextSprite: ID3DXSprite; // Sprite for batching draw text calls
g_pEffect: ID3DXEffect; // D3DX effect interface
g_VelocityTexFormat: TD3DFormat; // Texture format for velocity textures
g_Camera: CFirstPersonCamera;
g_bShowHelp: Boolean = True; // If true, it renders the UI control text
g_DialogResourceManager: CDXUTDialogResourceManager; // manager for shared resources of dialogs
g_SettingsDlg: CD3DSettingsDlg; // Device settings dialog
g_HUD: CDXUTDialog; // dialog for standard controls
g_SampleUI: CDXUTDialog; // dialog for sample specific controls
g_Vertex: array[0..3] of TScreenVertex;
g_pMesh1: ID3DXMesh;
g_pMeshTexture1: IDirect3DTexture9;
g_pMesh2: ID3DXMesh;
g_pMeshTexture2: IDirect3DTexture9;
g_pMeshTexture3: IDirect3DTexture9;
g_pFullScreenRenderTarget: IDirect3DTexture9;
g_pFullScreenRenderTargetSurf: IDirect3DSurface9;
g_pPixelVelocityTexture1: IDirect3DTexture9;
g_pPixelVelocitySurf1: IDirect3DSurface9;
g_pPixelVelocityTexture2: IDirect3DTexture9;
g_pPixelVelocitySurf2: IDirect3DSurface9;
g_pLastFrameVelocityTexture: IDirect3DTexture9;
g_pLastFrameVelocitySurf: IDirect3DSurface9;
g_pCurFrameVelocityTexture: IDirect3DTexture9;
g_pCurFrameVelocitySurf: IDirect3DSurface9;
g_fChangeTime: Single;
g_bShowBlurFactor: Boolean;
g_bShowUnblurred: Boolean;
g_dwBackgroundColor: DWORD;
g_fPixelBlurConst: Single;
g_fObjectSpeed: Single;
g_fCameraSpeed: Single;
g_pScene1Object: array[0..NUM_OBJECTS-1] of PObjectStruct;
g_pScene2Object: array[0..NUM_WALLS-1] of PObjectStruct;
g_dwMoveSytle: DWORD;
g_nSleepTime: Integer;
g_mViewProjectionLast: TD3DXMatrix;
g_nCurrentScene: Integer;
g_hWorld: TD3DXHandle;
g_hWorldLast: TD3DXHandle;
g_hMeshTexture: TD3DXHandle;
g_hWorldViewProjection: TD3DXHandle;
g_hWorldViewProjectionLast: TD3DXHandle;
g_hCurFrameVelocityTexture: TD3DXHandle;
g_hLastFrameVelocityTexture: TD3DXHandle;
g_hTechWorldWithVelocity: TD3DXHandle;
g_hPostProcessMotionBlur: TD3DXHandle;
g_nPasses: Integer = 0; // Number of passes required to render
g_nRtUsed: Integer = 0; // Number of render targets used by each pass
g_aRTSet: array[0..1] of TRenderTargetSet; // Two sets of render targets
g_pCurFrameRTSet: PRenderTargetSet; // Render target set for current frame
g_pLastFrameRTSet: PRenderTargetSet; // Render target set for last frame
//--------------------------------------------------------------------------------------
// UI control IDs
//--------------------------------------------------------------------------------------
const
IDC_TOGGLEFULLSCREEN = 1;
IDC_TOGGLEREF = 3;
IDC_CHANGEDEVICE = 4;
IDC_CHANGE_SCENE = 5;
IDC_ENABLE_BLUR = 6;
IDC_FRAMERATE = 7;
IDC_FRAMERATE_STATIC = 8;
IDC_BLUR_FACTOR = 9;
IDC_BLUR_FACTOR_STATIC = 10;
IDC_OBJECT_SPEED = 11;
IDC_OBJECT_SPEED_STATIC = 12;
IDC_CAMERA_SPEED = 13;
IDC_CAMERA_SPEED_STATIC = 14;
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; dTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
procedure OnLostDevice(pUserContext: Pointer); stdcall;
procedure OnDestroyDevice(pUserContext: Pointer); stdcall;
procedure InitApp;
function LoadMesh(const pd3dDevice: IDirect3DDevice9; wszName: PWideChar; out ppMesh: ID3DXMesh): HRESULT;
procedure RenderText;
procedure SetupFullscreenQuad(const pBackBufferSurfaceDesc: TD3DSurfaceDesc);
procedure CreateCustomDXUTobjects;
procedure DestroyCustomDXUTobjects;
implementation
//--------------------------------------------------------------------------------------
// Initialize the app
//--------------------------------------------------------------------------------------
procedure InitApp;
var
iObject: Integer;
iY: Integer;
sz: array[0..99] of WideChar;
begin
g_pFullScreenRenderTarget := nil;
g_pFullScreenRenderTargetSurf := nil;
g_pPixelVelocityTexture1 := nil;
g_pPixelVelocitySurf1 := nil;
g_pPixelVelocityTexture2 := nil;
g_pPixelVelocitySurf2 := nil;
g_pLastFrameVelocityTexture := nil;
g_pCurFrameVelocityTexture := nil;
g_pCurFrameVelocitySurf := nil;
g_pLastFrameVelocitySurf := nil;
g_pEffect := nil;
g_nSleepTime := 0;
g_fPixelBlurConst := 1.0;
g_fObjectSpeed := 8.0;
g_fCameraSpeed := 20.0;
g_nCurrentScene := 1;
g_fChangeTime := 0.0;
g_dwMoveSytle := MOVESTYLE_DEFAULT;
D3DXMatrixIdentity(g_mViewProjectionLast);
g_hWorld := nil;
g_hWorldLast := nil;
g_hMeshTexture := nil;
g_hWorldViewProjection := nil;
g_hWorldViewProjectionLast := nil;
g_hCurFrameVelocityTexture := nil;
g_hLastFrameVelocityTexture := nil;
g_hTechWorldWithVelocity := nil;
g_hPostProcessMotionBlur := nil;
g_pMesh1 := nil;
g_pMeshTexture1 := nil;
g_pMesh2 := nil;
g_pMeshTexture2 := nil;
g_pMeshTexture3 := nil;
g_bShowBlurFactor := False;
g_bShowUnblurred := False;
g_bShowHelp := True;
g_dwBackgroundColor := $00003F3F;
for iObject := 0 to NUM_OBJECTS - 1 do
begin
New(g_pScene1Object[iObject]); //:= new OBJECT;
ZeroMemory(g_pScene1Object[iObject], SizeOf(TObjectStruct));
end;
for iObject := 0 to NUM_WALLS - 1 do
begin
New(g_pScene2Object[iObject]); // = new OBJECT;
ZeroMemory(g_pScene2Object[iObject], SizeOf(TObjectStruct));
end;
// Initialize dialogs
g_SettingsDlg.Init(g_DialogResourceManager);
g_HUD.Init(g_DialogResourceManager);
g_SampleUI.Init(g_DialogResourceManager);
g_HUD.SetCallback(OnGUIEvent);
iY := 10; g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, 'Toggle full screen', 35, iY, 125, 22);
Inc(iY, 24); g_HUD.AddButton(IDC_TOGGLEREF, 'Toggle REF (F3)', 35, iY, 125, 22);
Inc(iY, 24); g_HUD.AddButton(IDC_CHANGEDEVICE, 'Change device (F2)', 35, iY, 125, 22, VK_F2);
g_SampleUI.SetCallback(OnGUIEvent); iY := 10;
Inc(iY, 24); g_SampleUI.AddButton(IDC_CHANGE_SCENE, 'Change Scene', 35, iY, 125, 22);
Inc(iY, 24); g_SampleUI.AddCheckBox(IDC_ENABLE_BLUR, 'Enable Blur', 35, iY, 125, 22, True);
Inc(iY, 10);
StringCchFormat(sz, 100, 'Sleep: %dms/frame', [g_nSleepTime]);
Inc(iY, 24); g_SampleUI.AddStatic(IDC_FRAMERATE_STATIC, sz, 35, iY, 125, 22 );
Inc(iY, 24); g_SampleUI.AddSlider(IDC_FRAMERATE, 50, iY, 100, 22, 0, 100, g_nSleepTime );
Inc(iY, 10);
StringCchFormat(sz, 100, 'Blur Factor: %0.2f', [g_fPixelBlurConst]);
Inc(iY, 24); g_SampleUI.AddStatic(IDC_BLUR_FACTOR_STATIC, sz, 35, iY, 125, 22 );
Inc(iY, 24); g_SampleUI.AddSlider(IDC_BLUR_FACTOR, 50, iY, 100, 22, 1, 200, Trunc(g_fPixelBlurConst*100.0));
Inc(iY, 10);
StringCchFormat(sz, 100, 'Object Speed: %0.2f', [g_fObjectSpeed]);
Inc(iY, 24); g_SampleUI.AddStatic(IDC_OBJECT_SPEED_STATIC, sz, 35, iY, 125, 22 );
Inc(iY, 24); g_SampleUI.AddSlider(IDC_OBJECT_SPEED, 50, iY, 100, 22, 0, 30, Trunc(g_fObjectSpeed));
Inc(iY, 10);
StringCchFormat(sz, 100, 'Camera Speed: %0.2f', [g_fCameraSpeed]);
Inc(iY, 24); g_SampleUI.AddStatic(IDC_CAMERA_SPEED_STATIC, sz, 35, iY, 125, 22 );
Inc(iY, 24); g_SampleUI.AddSlider(IDC_CAMERA_SPEED, 50, iY, 100, 22, 0, 100, Trunc(g_fCameraSpeed));
end;
//--------------------------------------------------------------------------------------
// Called during device initialization, this code checks the device for some
// minimum set of capabilities, and rejects those that don't pass by returning false.
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
var
pD3D: IDirect3D9;
begin
Result:= False;
// Skip backbuffer formats that don't support alpha blending
pD3D := DXUTGetD3DObject;
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
D3DRTYPE_TEXTURE, BackBufferFormat))
then Exit;
// No fallback, so need ps2.0
if (pCaps.PixelShaderVersion < D3DPS_VERSION(2, 0)) then Exit;
// No fallback, so need to support render target
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_RENDERTARGET,
D3DRTYPE_TEXTURE, BackBufferFormat)) then Exit;
// No fallback, so need to support D3DFMT_G16R16F or D3DFMT_A16B16G16R16F render target
if FAILED(pD3D.CheckDeviceFormat( pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_RENDERTARGET,
D3DRTYPE_TEXTURE, D3DFMT_G16R16F)) then
begin
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_RENDERTARGET,
D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F))
then Exit;
end;
Result:= True;
end;
//--------------------------------------------------------------------------------------
// This callback function is called immediately before a device is created to allow the
// application to modify the device settings. The supplied pDeviceSettings parameter
// contains the settings that the framework has selected for the new device, and the
// application can make any desired changes directly to this structure. Note however that
// DXUT will not correct invalid device settings so care must be taken
// to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail.
//--------------------------------------------------------------------------------------
{static} var s_bFirstTime: Boolean = True;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
begin
// If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW
// then switch to SWVP.
if (pCaps.DevCaps and D3DDEVCAPS_HWTRANSFORMANDLIGHT = 0) or
(pCaps.VertexShaderVersion < D3DVS_VERSION(1,1))
then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING;
// Debugging vertex shaders requires either REF or software vertex processing
// and debugging pixel shaders requires REF.
{$IFDEF DEBUG_VS}
if (pDeviceSettings.DeviceType <> D3DDEVTYPE_REF) then
with pDeviceSettings do
begin
BehaviorFlags := BehaviorFlags and not D3DCREATE_HARDWARE_VERTEXPROCESSING;
BehaviorFlags := BehaviorFlags and not D3DCREATE_PUREDEVICE;
BehaviorFlags := BehaviorFlags or D3DCREATE_SOFTWARE_VERTEXPROCESSING;
end;
{$ENDIF}
{$IFDEF DEBUG_PS}
pDeviceSettings.DeviceType := D3DDEVTYPE_REF;
{$ENDIF}
// For the first device created if its a REF device, optionally display a warning dialog box
if s_bFirstTime then
begin
s_bFirstTime := False;
if (pDeviceSettings.DeviceType = D3DDEVTYPE_REF) then DXUTDisplaySwitchingToREFWarning;
end;
Result:= True;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// created, which will happen during application initialization and windowed/full screen
// toggles. This is the best location to create D3DPOOL_MANAGED resources since these
// resources need to be reloaded whenever the device is destroyed. Resources created
// here should be released in the OnDestroyDevice callback.
//--------------------------------------------------------------------------------------
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
Caps: TD3DCaps9;
pD3D: IDirect3D9;
DisplayMode: TD3DDisplayMode;
str: array[0..MAX_PATH-1] of WideChar;
dwShaderFlags: DWORD;
iObject: Integer;
vPos: TD3DXVector3;
mRot: TD3DXMatrix;
mPos: TD3DXMatrix;
mScale: TD3DXMatrix;
fAspectRatio: Single;
vecEye: TD3DXVector3;
vecAt: TD3DXVector3;
begin
Result:= g_DialogResourceManager.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
// Query multiple RT setting and set the num of passes required
pd3dDevice.GetDeviceCaps(Caps);
if (Caps.NumSimultaneousRTs < 2) then
begin
g_nPasses := 2;
g_nRtUsed := 1;
end else
begin
g_nPasses := 1;
g_nRtUsed := 2;
end;
// Determine which of D3DFMT_G16R16F or D3DFMT_A16B16G16R16F to use for velocity texture
pd3dDevice.GetDirect3D(pD3D);
pd3dDevice.GetDisplayMode(0, DisplayMode);
if FAILED(pD3D.CheckDeviceFormat(Caps.AdapterOrdinal, Caps.DeviceType,
DisplayMode.Format, D3DUSAGE_RENDERTARGET,
D3DRTYPE_TEXTURE, D3DFMT_G16R16F))
then g_VelocityTexFormat := D3DFMT_A16B16G16R16F
else g_VelocityTexFormat := D3DFMT_G16R16F;
pD3D := nil;
// Initialize the font
Result:= D3DXCreateFont(pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE,
'Arial', g_pFont);
if V_Failed(Result) then Exit;
Result:= LoadMesh(pd3dDevice, 'misc\sphere.x', g_pMesh1);
if V_Failed(Result) then Exit;
Result:= LoadMesh(pd3dDevice, 'quad.x', g_pMesh2);
if V_Failed(Result) then Exit;
// Create the mesh texture from a file
Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'earth\earth.bmp');
if V_Failed(Result) then Exit;
Result:= D3DXCreateTextureFromFileW(pd3dDevice, str, g_pMeshTexture1);
if V_Failed(Result) then Exit;
Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'misc\env2.bmp');
if V_Failed(Result) then Exit;
Result:= D3DXCreateTextureFromFileW(pd3dDevice, str, g_pMeshTexture2);
if V_Failed(Result) then Exit;
Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'misc\seafloor.bmp');
if V_Failed(Result) then Exit;
Result:= D3DXCreateTextureFromFileW(pd3dDevice, str, g_pMeshTexture3);
if V_Failed(Result) then Exit;
// Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the
// shader debugger. Debugging vertex shaders requires either REF or software vertex
// processing, and debugging pixel shaders requires REF. The
// D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the
// shader debugger. It enables source level debugging, prevents instruction
// reordering, prevents dead code elimination, and forces the compiler to compile
// against the next higher available software target, which ensures that the
// unoptimized shaders do not exceed the shader model limitations. Setting these
// flags will cause slower rendering since the shaders will be unoptimized and
// forced into software. See the DirectX documentation for more information about
// using the shader debugger.
dwShaderFlags := D3DXFX_NOT_CLONEABLE;
{$IFDEF DEBUG}
// Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
dwShaderFlags := dwShaderFlags or D3DXSHADER_DEBUG;
{$ENDIF}
{$IFDEF DEBUG_VS}
dwShaderFlags := dwShaderFlags or D3DXSHADER_SKIPOPTIMIZATION or D3DXSHADER_DEBUG;
{$ENDIF}
{$IFDEF DEBUG_PS}
dwShaderFlags := dwShaderFlags or D3DXSHADER_SKIPOPTIMIZATION or D3DXSHADER_DEBUG;
{$ENDIF}
// Read the D3DX effect file
Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'PixelMotionBlur.fx');
if V_Failed(Result) then Exit;
// If this fails, there should be debug output as to
// they the .fx file failed to compile
Result:= D3DXCreateEffectFromFileW(pd3dDevice, str, nil, nil, dwShaderFlags,
nil, g_pEffect, nil);
if V_Failed(Result) then Exit;
for iObject:= 0 to NUM_OBJECTS - 1 do
begin
g_pScene1Object[iObject].g_pMesh := g_pMesh1;
g_pScene1Object[iObject].g_pMeshTexture := g_pMeshTexture1;
end;
for iObject:= 0 to NUM_WALLS - 1 do
begin
g_pScene2Object[iObject].g_pMesh := g_pMesh2;
if (iObject < NUM_WALLS/5*1) then
begin
g_pScene2Object[iObject].g_pMeshTexture := g_pMeshTexture3;
// Center floor
vPos.x := 0.0;
vPos.y := 0.0;
vPos.z := (iObject-NUM_WALLS/5*0) * 1.0 + 10.0;
D3DXMatrixRotationX(mRot, -D3DX_PI/2.0);
D3DXMatrixScaling(mScale, 1.0, 1.0, 1.0);
end
else if (iObject < NUM_WALLS/5*2) then
begin
g_pScene2Object[iObject].g_pMeshTexture := g_pMeshTexture3;
// Right floor
vPos.x := 1.0;
vPos.y := 0.0;
vPos.z := (iObject-NUM_WALLS/5*1) * 1.0 + 10.0;
D3DXMatrixRotationX(mRot, -D3DX_PI/2.0);
D3DXMatrixScaling(mScale, 1.0, 1.0, 1.0);
end
else if (iObject < NUM_WALLS/5*3) then
begin
g_pScene2Object[iObject].g_pMeshTexture := g_pMeshTexture3;
// Left floor
vPos.x := -1.0;
vPos.y := 0.0;
vPos.z := (iObject-NUM_WALLS/5*2) * 1.0 + 10.0;
D3DXMatrixRotationX(mRot, -D3DX_PI/2.0);
D3DXMatrixScaling(mScale, 1.0, 1.0, 1.0);
end
else if( iObject < NUM_WALLS/5*4) then
begin
g_pScene2Object[iObject].g_pMeshTexture := g_pMeshTexture2;
// Right wall
vPos.x := 1.5;
vPos.y := 0.5;
vPos.z := (iObject-NUM_WALLS/5*3) * 1.0 + 10.0;
D3DXMatrixRotationY(mRot, -D3DX_PI/2.0);
D3DXMatrixScaling(mScale, 1.0, 1.0, 1.0);
end
else if (iObject < NUM_WALLS/5*5) then
begin
g_pScene2Object[iObject].g_pMeshTexture := g_pMeshTexture2;
// Left wall
vPos.x := -1.5;
vPos.y := 0.5;
vPos.z := (iObject-NUM_WALLS/5*4) * 1.0 + 10.0;
D3DXMatrixRotationY(mRot, D3DX_PI/2.0);
D3DXMatrixScaling(mScale, 1.0, 1.0, 1.0);
end;
// Update the current world matrix for this object
D3DXMatrixTranslation(mPos, vPos.x, vPos.y, vPos.z);
// g_pScene2Object[iObject].g_mWorld := mRot * mPos;
D3DXMatrixMultiply(g_pScene2Object[iObject].g_mWorld, mRot, mPos);
// g_pScene2Object[iObject].g_mWorld := mScale * g_pScene2Object[iObject].g_mWorld;
D3DXMatrixMultiply(g_pScene2Object[iObject].g_mWorld, mScale, g_pScene2Object[iObject].g_mWorld);
// The walls don't move so just copy the current world matrix
g_pScene2Object[iObject].g_mWorldLast := g_pScene2Object[iObject].g_mWorld;
end;
// Setup the camera
fAspectRatio := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height;
g_Camera.SetProjParams(D3DX_PI/4, fAspectRatio, 1.0, 1000.0);
vecEye := D3DXVector3(40.0, 0.0, -15.0);
vecAt := D3DXVector3(4.0, 4.0, -15.0);
g_Camera.SetViewParams(vecEye, vecAt);
g_Camera.SetScalers(0.01, g_fCameraSpeed);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This function loads the mesh and ensures the mesh has normals; it also optimizes the
// mesh for the graphics card's vertex cache, which improves performance by organizing
// the internal triangle list for less cache misses.
//--------------------------------------------------------------------------------------
function LoadMesh(const pd3dDevice: IDirect3DDevice9; wszName: PWideChar; out ppMesh: ID3DXMesh): HRESULT;
var
pMesh: ID3DXMesh;
str: array[0..MAX_PATH-1] of WideChar;
rgdwAdjacency: PDWORD;
pTempMesh: ID3DXMesh;
begin
// Load the mesh with D3DX and get back a ID3DXMesh*. For this
// sample we'll ignore the X file's embedded materials since we know
// exactly the model we're loading. See the mesh samples such as
// "OptimizedMesh" for a more generic mesh loading example.
Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, wszName);
if V_Failed(Result) then Exit;
Result:= D3DXLoadMeshFromXW(str, D3DXMESH_MANAGED, pd3dDevice, nil, nil, nil, nil, pMesh);
if V_Failed(Result) then Exit;
// Make sure there are normals which are required for lighting
if (pMesh.GetFVF and D3DFVF_NORMAL = 0) then
begin
V(pMesh.CloneMeshFVF(pMesh.GetOptions,
pMesh.GetFVF or D3DFVF_NORMAL,
pd3dDevice, pTempMesh));
V(D3DXComputeNormals(pTempMesh, nil));
SAFE_RELEASE(pMesh);
pMesh := pTempMesh;
end;
// Optimize the mesh for this graphics card's vertex cache
// so when rendering the mesh's triangle list the vertices will
// cache hit more often so it won't have to re-execute the vertex shader
// on those vertices so it will improve perf.
try
GetMem(rgdwAdjacency, SizeOf(DWORD)*pMesh.GetNumFaces*3);
except
Result:= E_OUTOFMEMORY;
Exit;
end;
V(pMesh.GenerateAdjacency(1e-6, rgdwAdjacency));
V(pMesh.OptimizeInplace(D3DXMESHOPT_VERTEXCACHE, rgdwAdjacency, nil, nil, nil));
FreeMem(rgdwAdjacency);
ppMesh := pMesh;
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// reset, which will happen after a lost device scenario. This is the best location to
// create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever
// the device is lost. Resources created here should be released in the OnLostDevice
// callback.
//--------------------------------------------------------------------------------------
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
fAspectRatio: Single;
colorWhite: TD3DXColor;
colorBlack: TD3DXColor;
colorAmbient: TD3DXColor;
colorSpecular: TD3DXColor;
desc: TD3DSurfaceDesc;
fVelocityCapInPixels: Single;
fVelocityCapNonHomogeneous: Single;
fVelocityCapSqNonHomogeneous: Single;
pOriginalRenderTarget: IDirect3DSurface9;
begin
Result:= g_DialogResourceManager.OnResetDevice;
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnResetDevice;
if V_Failed(Result) then Exit;
if Assigned(g_pFont) then
begin
Result:= g_pFont.OnResetDevice;
if V_Failed(Result) then Exit;
end;
if Assigned(g_pEffect) then
begin
Result:= g_pEffect.OnResetDevice;
if V_Failed(Result) then Exit;
end;
// Create a sprite to help batch calls when drawing many lines of text
Result:= D3DXCreateSprite(pd3dDevice, g_pTextSprite);
if V_Failed(Result) then Exit;
// Setup the camera's projection parameters
fAspectRatio := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height;
g_Camera.SetProjParams(D3DX_PI/4, fAspectRatio, 0.1, 1000.0);
g_HUD.SetLocation(pBackBufferSurfaceDesc.Width-170, 0);
g_HUD.SetSize(170, 170);
g_SampleUI.SetLocation( pBackBufferSurfaceDesc.Width-170, pBackBufferSurfaceDesc.Height-350);
g_SampleUI.SetSize(170, 300);
// Create a A8R8G8B8 render target texture. This will be used to render
// the full screen and then rendered to the backbuffer using a quad.
Result:= D3DXCreateTexture(pd3dDevice, pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height,
1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8,
D3DPOOL_DEFAULT, g_pFullScreenRenderTarget);
if V_Failed(Result) then Exit;
// Create two floating-point render targets with at least 2 channels. These will be used to store
// velocity of each pixel (one for the current frame, and one for last frame).
Result:= D3DXCreateTexture(pd3dDevice, pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height,
1, D3DUSAGE_RENDERTARGET, g_VelocityTexFormat,
D3DPOOL_DEFAULT, g_pPixelVelocityTexture1);
if V_Failed(Result) then Exit;
Result:= D3DXCreateTexture(pd3dDevice, pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height,
1, D3DUSAGE_RENDERTARGET, g_VelocityTexFormat,
D3DPOOL_DEFAULT, g_pPixelVelocityTexture2);
if V_Failed(Result) then Exit;
// Store pointers to surfaces so we can call SetRenderTarget() later
Result:= g_pFullScreenRenderTarget.GetSurfaceLevel(0, g_pFullScreenRenderTargetSurf);
if V_Failed(Result) then Exit;
Result:= g_pPixelVelocityTexture1.GetSurfaceLevel(0, g_pPixelVelocitySurf1);
if V_Failed(Result) then Exit;
Result:= g_pPixelVelocityTexture2.GetSurfaceLevel(0, g_pPixelVelocitySurf2);
if V_Failed(Result) then Exit;
// Setup render target sets
if (1 = g_nPasses) then
begin
// Multiple RTs
// First frame
g_aRTSet[0].pRT[0][0] := g_pFullScreenRenderTargetSurf;
g_aRTSet[0].pRT[0][1] := g_pPixelVelocitySurf1;
g_aRTSet[0].pRT[1][0] := nil; // 2nd pass is not needed
g_aRTSet[0].pRT[1][1] := nil; // 2nd pass is not needed
// Second frame
g_aRTSet[1].pRT[0][0] := g_pFullScreenRenderTargetSurf;
g_aRTSet[1].pRT[0][1] := g_pPixelVelocitySurf2;
g_aRTSet[1].pRT[1][0] := nil; // 2nd pass is not needed
g_aRTSet[1].pRT[1][1] := nil; // 2nd pass is not needed
end else
begin
// Single RT, multiple passes
// First frame
g_aRTSet[0].pRT[0][0] := g_pFullScreenRenderTargetSurf;
g_aRTSet[0].pRT[0][1] := nil; // 2nd RT is not needed
g_aRTSet[0].pRT[1][0] := g_pPixelVelocitySurf1;
g_aRTSet[0].pRT[1][1] := nil; // 2nd RT is not needed
// Second frame
g_aRTSet[1].pRT[0][0] := g_pFullScreenRenderTargetSurf;
g_aRTSet[1].pRT[0][1] := nil; // 2nd RT is not needed
g_aRTSet[1].pRT[1][0] := g_pPixelVelocitySurf2;
g_aRTSet[1].pRT[1][1] := nil; // 2nd RT is not needed
end;
// Setup the current & last pointers that are swapped every frame.
g_pCurFrameVelocityTexture := g_pPixelVelocityTexture1;
g_pLastFrameVelocityTexture := g_pPixelVelocityTexture2;
g_pCurFrameVelocitySurf := g_pPixelVelocitySurf1;
g_pLastFrameVelocitySurf := g_pPixelVelocitySurf2;
g_pCurFrameRTSet := @g_aRTSet[0];
g_pLastFrameRTSet := @g_aRTSet[1];
SetupFullscreenQuad(pBackBufferSurfaceDesc);
colorWhite := D3DXColor(1.0, 1.0, 1.0, 1.0);
colorBlack := D3DXColor(0.0, 0.0, 0.0, 1.0);
colorAmbient := D3DXColor(0.35, 0.35, 0.35, 0);
colorSpecular := D3DXColor(0.5, 0.5, 0.5, 1.0);
Result:= g_pEffect.SetVector('MaterialAmbientColor', PD3DXVECTOR4(@colorAmbient)^);
if V_Failed(Result) then Exit;
Result:= g_pEffect.SetVector('MaterialDiffuseColor', PD3DXVECTOR4(@colorWhite)^);
if V_Failed(Result) then Exit;
Result:= g_pEffect.SetTexture('RenderTargetTexture', g_pFullScreenRenderTarget);
if V_Failed(Result) then Exit;
Result:= g_pFullScreenRenderTargetSurf.GetDesc(desc);
if V_Failed(Result) then Exit;
Result:= g_pEffect.SetFloat('RenderTargetWidth', desc.Width);
if V_Failed(Result) then Exit;
Result:= g_pEffect.SetFloat('RenderTargetHeight', desc.Height);
if V_Failed(Result) then Exit;
// 12 is the number of samples in our post-process pass, so we don't want
// pixel velocity of more than 12 pixels or else we'll see artifacts
fVelocityCapInPixels := 3.0;
fVelocityCapNonHomogeneous := fVelocityCapInPixels * 2 / pBackBufferSurfaceDesc.Width;
fVelocityCapSqNonHomogeneous := fVelocityCapNonHomogeneous * fVelocityCapNonHomogeneous;
Result:= g_pEffect.SetFloat('VelocityCapSq', fVelocityCapSqNonHomogeneous);
if V_Failed(Result) then Exit;
Result:= g_pEffect.SetFloat('ConvertToNonHomogeneous', 1.0 / pBackBufferSurfaceDesc.Width);
if V_Failed(Result) then Exit;
// Determine the technique to use when rendering world based on # of passes.
if (1 = g_nPasses)
then g_hTechWorldWithVelocity := g_pEffect.GetTechniqueByName('WorldWithVelocityMRT')
else g_hTechWorldWithVelocity := g_pEffect.GetTechniqueByName('WorldWithVelocityTwoPasses');
g_hPostProcessMotionBlur := g_pEffect.GetTechniqueByName('PostProcessMotionBlur');
g_hWorld := g_pEffect.GetParameterByName(nil, 'mWorld');
g_hWorldLast := g_pEffect.GetParameterByName(nil, 'mWorldLast');
g_hWorldViewProjection := g_pEffect.GetParameterByName(nil, 'mWorldViewProjection');
g_hWorldViewProjectionLast := g_pEffect.GetParameterByName(nil, 'mWorldViewProjectionLast');
g_hMeshTexture := g_pEffect.GetParameterByName(nil, 'MeshTexture');
g_hCurFrameVelocityTexture := g_pEffect.GetParameterByName(nil, 'CurFrameVelocityTexture');
g_hLastFrameVelocityTexture := g_pEffect.GetParameterByName(nil, 'LastFrameVelocityTexture');
// Turn off lighting since its done in the shaders
Result:= pd3dDevice.SetRenderState(D3DRS_LIGHTING, iFalse);
if V_Failed(Result) then Exit;
// Save a pointer to the orignal render target to restore it later
Result:= pd3dDevice.GetRenderTarget(0, pOriginalRenderTarget);
if V_Failed(Result) then Exit;
// Clear each RT
Result:= pd3dDevice.SetRenderTarget(0, g_pFullScreenRenderTargetSurf);
if V_Failed(Result) then Exit;
Result:= pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET, $00000000, 1.0, 0);
if V_Failed(Result) then Exit;
Result:= pd3dDevice.SetRenderTarget(0, g_pLastFrameVelocitySurf);
if V_Failed(Result) then Exit;
Result:= pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET, $00000000, 1.0, 0);
if V_Failed(Result) then Exit;
Result:= pd3dDevice.SetRenderTarget(0, g_pCurFrameVelocitySurf);
if V_Failed(Result) then Exit;
Result:= pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET, $00000000, 1.0, 0);
if V_Failed(Result) then Exit;
// Restore the orignal RT
Result:= pd3dDevice.SetRenderTarget(0, pOriginalRenderTarget);
if V_Failed(Result) then Exit;
pOriginalRenderTarget:= nil;
Result:= S_OK;
end;
//-----------------------------------------------------------------------------
// Name: SetupFullscreenQuad()
// Desc: Sets up a full screen quad. First we render to a fullscreen render
// target texture, and then we render that texture using this quad to
// apply a pixel shader on every pixel of the scene.
//-----------------------------------------------------------------------------
procedure SetupFullscreenQuad(const pBackBufferSurfaceDesc: TD3DSurfaceDesc);
var
desc: TD3DSurfaceDesc;
fWidth5, fHeight5, fTexWidth1, fTexHeight1: Single;
begin
g_pFullScreenRenderTargetSurf.GetDesc(desc);
// Ensure that we're directly mapping texels to pixels by offset by 0.5
// For more info see the doc page titled "Directly Mapping Texels to Pixels"
fWidth5 := pBackBufferSurfaceDesc.Width - 0.5;
fHeight5 := pBackBufferSurfaceDesc.Height - 0.5;
fTexWidth1 := pBackBufferSurfaceDesc.Width / desc.Width;
fTexHeight1 := pBackBufferSurfaceDesc.Height / desc.Height;
// Fill in the vertex values
g_Vertex[0].pos := D3DXVector4(fWidth5, -0.5, 0.0, 1.0);
g_Vertex[0].clr := D3DXColorToDWord(D3DXColor(0.5, 0.5, 0.5, 0.66666));
g_Vertex[0].tex1 := D3DXVector2(fTexWidth1, 0.0);
g_Vertex[1].pos := D3DXVector4(fWidth5, fHeight5, 0.0, 1.0);
g_Vertex[1].clr := D3DXColorToDWord(D3DXColor(0.5, 0.5, 0.5, 0.66666));
g_Vertex[1].tex1 := D3DXVector2(fTexWidth1, fTexHeight1);
g_Vertex[2].pos := D3DXVector4(-0.5, -0.5, 0.0, 1.0);
g_Vertex[2].clr := D3DXColorToDWord(D3DXColor(0.5, 0.5, 0.5, 0.66666));
g_Vertex[2].tex1 := D3DXVector2(0.0, 0.0);
g_Vertex[3].pos := D3DXVector4(-0.5, fHeight5, 0.0, 1.0);
g_Vertex[3].clr := D3DXColorToDWord(D3DXColor(0.5, 0.5, 0.5, 0.66666));
g_Vertex[3].tex1 := D3DXVector2(0.0, fTexHeight1);
end;
//--------------------------------------------------------------------------------------
// This callback function will be called once at the beginning of every frame. This is the
// best location for your application to handle updates to the scene, but is not
// intended to contain actual rendering calls, which should instead be placed in the
// OnFrameRender callback.
//--------------------------------------------------------------------------------------
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; dTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
var
fTime: Single;
iObject: Integer;
fRadius: Single;
vPos: TD3DXVector3;
begin
fTime := dTime;
// Update the camera's position based on user input
g_Camera.FrameMove(fElapsedTime);
if (g_nCurrentScene = 1) then
begin
// Move the objects around based on some simple function
for iObject:= 0 to NUM_OBJECTS - 1 do
begin
fRadius := 7.0;
if (iObject >= 30) and (iObject < 41) then
begin
vPos.x := Cos(g_fObjectSpeed*0.125*fTime + 2*D3DX_PI/10*(iObject-30)) * fRadius;
vPos.y := 10.0;
vPos.z := Sin(g_fObjectSpeed*0.125*fTime + 2*D3DX_PI/10*(iObject-30)) * fRadius - 25.0;
end
else if (iObject >= 20) and (iObject < 31) then
begin
vPos.x := Cos(g_fObjectSpeed*0.25*fTime + 2*D3DX_PI/10*(iObject-20)) * fRadius;
vPos.y := 10.0;
vPos.z := Sin(g_fObjectSpeed*0.25*fTime + 2*D3DX_PI/10*(iObject-20)) * fRadius - 5.0;
end
else if (iObject >= 10) and (iObject < 21) then
begin
vPos.x := Cos(g_fObjectSpeed*0.5*fTime + 2*D3DX_PI/10*(iObject-10)) * fRadius;
vPos.y := 0.0;
vPos.z := Sin(g_fObjectSpeed*0.5*fTime + 2*D3DX_PI/10*(iObject-10)) * fRadius - 25.0;
end
else
begin
vPos.x := Cos(g_fObjectSpeed*fTime + 2*D3DX_PI/10*iObject) * fRadius;
vPos.y := 0.0;
vPos.z := Sin(g_fObjectSpeed*fTime + 2*D3DX_PI/10*iObject) * fRadius - 5.0;
end;
g_pScene1Object[iObject].g_vWorldPos := vPos;
// Store the last world matrix so that we can tell the effect file
// what it was when we render this object
g_pScene1Object[iObject].g_mWorldLast := g_pScene1Object[iObject].g_mWorld;
// Update the current world matrix for this object
D3DXMatrixTranslation(g_pScene1Object[iObject].g_mWorld,
g_pScene1Object[iObject].g_vWorldPos.x,
g_pScene1Object[iObject].g_vWorldPos.y,
g_pScene1Object[iObject].g_vWorldPos.z);
end;
end;
if (g_nSleepTime > 0) then Sleep(g_nSleepTime);
end;
//--------------------------------------------------------------------------------------
// This callback function will be called at the end of every frame to perform all the
// rendering calls for the scene, and it will also be called if the window needs to be
// repainted. After this function has returned, DXUT will call
// IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain
//--------------------------------------------------------------------------------------
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
var
pTempTex: IDirect3DTexture9;
pTempSurf: IDirect3DSurface9;
pTempRTSet: PRenderTargetSet;
iObject: Integer;
rt: Integer;
apOriginalRenderTarget: array[0..1] of IDirect3DSurface9;
mProj: TD3DXMatrixA16;
mView: TD3DXMatrixA16;
mViewProjection: TD3DXMatrixA16;
mWorldViewProjection: TD3DXMatrixA16;
mWorldViewProjectionLast: TD3DXMatrixA16;
iPass, cPasses: LongWord;
begin
// If the settings dialog is being shown, then
// render it instead of rendering the app's scene
if g_SettingsDlg.Active then
begin
g_SettingsDlg.OnRender(fElapsedTime);
Exit;
end;
// Swap the current frame's per-pixel velocity texture with
// last frame's per-pixel velocity texture
pTempTex := g_pCurFrameVelocityTexture;
g_pCurFrameVelocityTexture := g_pLastFrameVelocityTexture;
g_pLastFrameVelocityTexture := pTempTex;
pTempSurf := g_pCurFrameVelocitySurf;
g_pCurFrameVelocitySurf := g_pLastFrameVelocitySurf;
g_pLastFrameVelocitySurf := pTempSurf;
pTempRTSet := g_pCurFrameRTSet;
g_pCurFrameRTSet := g_pLastFrameRTSet;
g_pLastFrameRTSet := pTempRTSet;
// Save a pointer to the current render target in the swap chain
V(pd3dDevice.GetRenderTarget(0, apOriginalRenderTarget[0]));
V(g_pEffect.SetFloat('PixelBlurConst', g_fPixelBlurConst));
V(g_pEffect.SetTexture(g_hCurFrameVelocityTexture, g_pCurFrameVelocityTexture));
V(g_pEffect.SetTexture(g_hLastFrameVelocityTexture, g_pLastFrameVelocityTexture));
// Clear the velocity render target to 0
V(pd3dDevice.SetRenderTarget(0, g_pCurFrameVelocitySurf));
V(pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET, $00000000, 1.0, 0));
// Clear the full screen render target to the background color
V(pd3dDevice.SetRenderTarget(0, g_pFullScreenRenderTargetSurf));
V(pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, g_dwBackgroundColor, 1.0, 0));
// Turn on Z for this pass
V(pd3dDevice.SetRenderState(D3DRS_ZENABLE, iTrue));
// For the first pass we'll draw the screen to the full screen render target
// and to update the velocity render target with the velocity of each pixel
if SUCCEEDED(pd3dDevice.BeginScene) then
begin
// Set world drawing technique
V(g_pEffect.SetTechnique(g_hTechWorldWithVelocity));
// Get the projection & view matrix from the camera class
mProj := g_Camera.GetProjMatrix^;
mView := g_Camera.GetViewMatrix^;
// mViewProjection := mView * mProj;
D3DXMatrixMultiply(mViewProjection, mView, mProj);
if (g_nCurrentScene = 1) then
begin
// For each object, tell the effect about the object's current world matrix
// and its last frame's world matrix and render the object.
// The vertex shader can then use both these matricies to calculate how
// much each vertex has moved. The pixel shader then interpolates this
// vertex velocity for each pixel
for iObject := 0 to NUM_OBJECTS - 1 do
begin
// mWorldViewProjection := g_pScene1Object[iObject].g_mWorld * mViewProjection;
D3DXMatrixMultiply(mWorldViewProjection, g_pScene1Object[iObject].g_mWorld, mViewProjection);
// mWorldViewProjectionLast := g_pScene1Object[iObject].g_mWorldLast * g_mViewProjectionLast;
D3DXMatrixMultiply(mWorldViewProjectionLast, g_pScene1Object[iObject].g_mWorldLast, g_mViewProjectionLast);
// Tell the effect where the camera is now
V(g_pEffect.SetMatrix(g_hWorldViewProjection, mWorldViewProjection));
V(g_pEffect.SetMatrix(g_hWorld, g_pScene1Object[iObject].g_mWorld));
// Tell the effect where the camera was last frame
V(g_pEffect.SetMatrix(g_hWorldViewProjectionLast, mWorldViewProjectionLast));
// Tell the effect the current mesh's texture
V(g_pEffect.SetTexture(g_hMeshTexture, g_pScene1Object[iObject].g_pMeshTexture));
V(g_pEffect._Begin(@cPasses, 0));
for iPass := 0 to cPasses - 1 do
begin
// Set the render targets here. If multiple render targets are
// supported, render target 1 is set to be the velocity surface.
// If multiple render targets are not supported, the velocity
// surface will be rendered in the 2nd pass.
for rt := 0 to g_nRtUsed - 1 do
V(pd3dDevice.SetRenderTarget(rt, g_pCurFrameRTSet.pRT[iPass][rt]));
V(g_pEffect.BeginPass(iPass));
V(g_pScene1Object[iObject].g_pMesh.DrawSubset(0));
V(g_pEffect.EndPass);
end;
V(g_pEffect._End)
end;
end
else if (g_nCurrentScene = 2) then
begin
for iObject := 0 to NUM_WALLS - 1 do
begin
// mWorldViewProjection := g_pScene2Object[iObject].g_mWorld * mViewProjection;
D3DXMatrixMultiply(mWorldViewProjection, g_pScene2Object[iObject].g_mWorld, mViewProjection);
// mWorldViewProjectionLast = g_pScene2Object[iObject]->g_mWorldLast * g_mViewProjectionLast;
D3DXMatrixMultiply(mWorldViewProjectionLast, g_pScene2Object[iObject].g_mWorldLast, g_mViewProjectionLast);
// Tell the effect where the camera is now
V(g_pEffect.SetMatrix(g_hWorldViewProjection, mWorldViewProjection));
V(g_pEffect.SetMatrix(g_hWorld, g_pScene2Object[iObject].g_mWorld));
// Tell the effect where the camera was last frame
V(g_pEffect.SetMatrix(g_hWorldViewProjectionLast, mWorldViewProjectionLast));
// Tell the effect the current mesh's texture
V(g_pEffect.SetTexture(g_hMeshTexture, g_pScene2Object[iObject].g_pMeshTexture));
V(g_pEffect._Begin(@cPasses, 0));
for iPass := 0 to cPasses - 1 do
begin
// Set the render targets here. If multiple render targets are
// supported, render target 1 is set to be the velocity surface.
// If multiple render targets are not supported, the velocity
// surface will be rendered in the 2nd pass.
for rt := 0 to g_nRtUsed - 1 do
V(pd3dDevice.SetRenderTarget(rt, g_pCurFrameRTSet.pRT[iPass][rt]));
V(g_pEffect.BeginPass(iPass));
V(g_pScene2Object[iObject].g_pMesh.DrawSubset(0));
V(g_pEffect.EndPass);
end;
V(g_pEffect._End);
end;
end;
V(pd3dDevice.EndScene);
end;
// Remember the current view projection matrix for next frame
g_mViewProjectionLast := mViewProjection;
// Now that we have the scene rendered into g_pFullScreenRenderTargetSurf
// and the pixel velocity rendered into g_pCurFrameVelocitySurf
// we can do a final pass to render this into the backbuffer and use
// a pixel shader to blur the pixels based on the last frame's & current frame's
// per pixel velocity to achieve a motion blur effect
for rt := 0 to g_nRtUsed - 1 do
V(pd3dDevice.SetRenderTarget(rt, apOriginalRenderTarget[rt]));
apOriginalRenderTarget[0] := nil;
V(pd3dDevice.SetRenderState(D3DRS_ZENABLE, iFalse));
// Clear the render target
V(pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET, $00000000, 1.0, 0));
// Above we rendered to a fullscreen render target texture, and now we
// render that texture using a quad to apply a pixel shader on every pixel of the scene.
if SUCCEEDED(pd3dDevice.BeginScene) then
begin
V(g_pEffect.SetTechnique(g_hPostProcessMotionBlur));
V(g_pEffect._Begin(@cPasses, 0));
for iPass := 0 to cPasses - 1 do
begin
V(g_pEffect.BeginPass(iPass));
V(pd3dDevice.SetFVF(TScreenVertex_FVF));
V(pd3dDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, g_Vertex, SizeOf(TScreenVertex)));
V(g_pEffect.EndPass);
end;
V(g_pEffect._End);
V(g_HUD.OnRender(fElapsedTime));
V(g_SampleUI.OnRender(fElapsedTime ));
RenderText;
V(pd3dDevice.EndScene);
end;
end;
//--------------------------------------------------------------------------------------
// Render the help and statistics text. This function uses the ID3DXFont interface for
// efficient text rendering.
//--------------------------------------------------------------------------------------
procedure RenderText;
var
txtHelper: CDXUTTextHelper;
pd3dsdBackBuffer: PD3DSurfaceDesc;
begin
// The helper object simply helps keep track of text position, and color
// and then it calls pFont->DrawText( g_pSprite, strMsg, -1, &rc, DT_NOCLIP, g_clr );
// If NULL is passed in as the sprite object, then it will work however the
// pFont->DrawText() will not be batched together. Batching calls will improves performance.
txtHelper := CDXUTTextHelper.Create(g_pFont, g_pTextSprite, 15);
// Output statistics
txtHelper._Begin;
txtHelper.SetInsertionPos(5, 5);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 0.0, 1.0));
txtHelper.DrawTextLine(DXUTGetFrameStats);
txtHelper.DrawTextLine(DXUTGetDeviceStats);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0));
{$IFNDEF FPC}
//Clootie: Delphi 5-7 WideFormat bug
txtHelper.DrawTextLine(PAnsiChar(Format('Blur=%0.2f Object Speed=%0.1f Camera Speed=%0.1f', [g_fPixelBlurConst, g_fObjectSpeed, g_fCameraSpeed])));
{$ELSE}
txtHelper.DrawFormattedTextLine('Blur=%0.2f Object Speed=%0.1f Camera Speed=%0.1f', [g_fPixelBlurConst, g_fObjectSpeed, g_fCameraSpeed]);
{$ENDIF}
if (g_nSleepTime = 0)
then txtHelper.DrawTextLine('Not sleeping between frames')
else txtHelper.DrawFormattedTextLine('Sleeping %dms per frame', [g_nSleepTime]);
// Draw help
if g_bShowHelp then
begin
pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc;
txtHelper.SetInsertionPos(10, pd3dsdBackBuffer.Height-15*6);
txtHelper.SetForegroundColor(D3DXColor(1.0, 0.75, 0.0, 1.0));
txtHelper.DrawTextLine('Controls (F1 to hide):');
txtHelper.SetInsertionPos(40, pd3dsdBackBuffer.Height-15*5);
txtHelper.DrawTextLine('Look: Left drag mouse'#10+
'Move: A,W,S,D or Arrow Keys'#10+
'Move up/down: Q,E or PgUp,PgDn'#10+
'Reset camera: Home'#10+
'Quit: ESC');
end else
begin
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0));
txtHelper.DrawTextLine('Press F1 for help');
end;
txtHelper._End;
txtHelper.Free;
end;
//--------------------------------------------------------------------------------------
// Before handling window messages, DXUT passes incoming windows
// messages to the application through this callback function. If the application sets
// *pbNoFurtherProcessing to TRUE, then DXUT will not process this message.
//--------------------------------------------------------------------------------------
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
begin
Result:= 0;
// Always allow dialog resource manager calls to handle global messages
// so GUI state is updated correctly
pbNoFurtherProcessing := g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
if g_SettingsDlg.IsActive then
begin
g_SettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam);
Exit;
end;
// Give the dialogs a chance to handle the message first
pbNoFurtherProcessing := g_HUD.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
pbNoFurtherProcessing := g_SampleUI.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
// Pass all remaining windows messages to camera so it can respond to user input
g_Camera.HandleMessages(hWnd, uMsg, wParam, lParam);
end;
//--------------------------------------------------------------------------------------
// As a convenience, DXUT inspects the incoming windows messages for
// keystroke messages and decodes the message parameters to pass relevant keyboard
// messages to the application. The framework does not remove the underlying keystroke
// messages, which are still passed to the application's MsgProc callback.
//--------------------------------------------------------------------------------------
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
begin
if bKeyDown then
begin
case nChar of
VK_F1: g_bShowHelp := not g_bShowHelp;
end;
end;
end;
var
{static} s_fRemember: Single = 1.0;
//--------------------------------------------------------------------------------------
// Handles the GUI events
//--------------------------------------------------------------------------------------
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
var
vecEye, vecAt: TD3DXVector3;
begin
case nControlID of
IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen;
IDC_TOGGLEREF: DXUTToggleREF;
IDC_CHANGEDEVICE: with g_SettingsDlg do Active := not Active;
IDC_CHANGE_SCENE:
begin
g_nCurrentScene := g_nCurrentScene mod 2;
Inc(g_nCurrentScene);
case g_nCurrentScene of
1:
begin
vecEye := D3DXVector3(40.0, 0.0, -15.0);
vecAt := D3DXVector3(4.0, 4.0, -15.0);
g_Camera.SetViewParams(vecEye, vecAt);
end;
2:
begin
vecEye := D3DXVector3(0.125, 1.25, 3.0);
vecAt := D3DXVector3(0.125, 1.25, 4.0);
g_Camera.SetViewParams(vecEye, vecAt);
end;
end;
end;
IDC_ENABLE_BLUR:
begin
if g_SampleUI.GetCheckBox(IDC_ENABLE_BLUR).Checked then
begin
g_fPixelBlurConst := s_fRemember;
g_SampleUI.GetStatic(IDC_BLUR_FACTOR_STATIC).Enabled := True;
g_SampleUI.GetSlider(IDC_BLUR_FACTOR).Enabled := True;
end else
begin
s_fRemember := g_fPixelBlurConst;
g_fPixelBlurConst := 0.0;
g_SampleUI.GetStatic(IDC_BLUR_FACTOR_STATIC).Enabled := False;
g_SampleUI.GetSlider(IDC_BLUR_FACTOR).Enabled := False;
end;
end;
IDC_FRAMERATE:
begin
g_nSleepTime := g_SampleUI.GetSlider(IDC_FRAMERATE).Value;
//todo: fix WideFormatting bugs...
g_SampleUI.GetStatic(IDC_FRAMERATE_STATIC).Text := PWideChar(WideFormat('Sleep: %dms/frame', [g_nSleepTime]));
end;
IDC_BLUR_FACTOR:
begin
g_fPixelBlurConst := g_SampleUI.GetSlider(IDC_BLUR_FACTOR).Value / 100.0;
g_SampleUI.GetStatic(IDC_BLUR_FACTOR_STATIC).Text := PWideChar(WideFormat('Blur Factor: %0.2f', [g_fPixelBlurConst]));
end;
IDC_OBJECT_SPEED:
begin
g_fObjectSpeed := g_SampleUI.GetSlider(IDC_OBJECT_SPEED).Value;
g_SampleUI.GetStatic(IDC_OBJECT_SPEED_STATIC).Text := PWideChar(WideFormat('Object Speed: %0.2f', [g_fObjectSpeed]));
end;
IDC_CAMERA_SPEED:
begin
g_fCameraSpeed := g_SampleUI.GetSlider(IDC_CAMERA_SPEED).Value;
g_SampleUI.GetStatic(IDC_CAMERA_SPEED_STATIC).Text := PWideChar(WideFormat('Camera Speed: %0.2f', [g_fCameraSpeed]));
g_Camera.SetScalers(0.01, g_fCameraSpeed);
end;
end;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// entered a lost state and before IDirect3DDevice9::Reset is called. Resources created
// in the OnResetDevice callback should be released here, which generally includes all
// D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for
// information about lost devices.
//--------------------------------------------------------------------------------------
procedure OnLostDevice; stdcall;
var
i, j, k: Integer;
begin
g_DialogResourceManager.OnLostDevice;
g_SettingsDlg.OnLostDevice;
if Assigned(g_pFont) then g_pFont.OnLostDevice;
if Assigned(g_pEffect) then g_pEffect.OnLostDevice;
SAFE_RELEASE(g_pTextSprite);
SAFE_RELEASE(g_pFullScreenRenderTargetSurf);
SAFE_RELEASE(g_pFullScreenRenderTarget);
SAFE_RELEASE(g_pPixelVelocitySurf1);
SAFE_RELEASE(g_pPixelVelocityTexture1);
SAFE_RELEASE(g_pPixelVelocitySurf2);
SAFE_RELEASE(g_pPixelVelocityTexture2);
for i:= 0 to High(g_aRTSet) do
for j:= 0 to 1 do
for k:= 0 to 1 do
g_aRTSet[i].pRT[j][k] := nil;
g_pLastFrameVelocityTexture:= nil;
g_pLastFrameVelocitySurf:= nil;
g_pCurFrameVelocityTexture:= nil;
g_pCurFrameVelocitySurf:= nil;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// been destroyed, which generally happens as a result of application termination or
// windowed/full screen toggles. Resources created in the OnCreateDevice callback
// should be released here, which generally includes all D3DPOOL_MANAGED resources.
//--------------------------------------------------------------------------------------
procedure OnDestroyDevice; stdcall;
var
iObject: Integer;
begin
g_DialogResourceManager.OnDestroyDevice;
g_SettingsDlg.OnDestroyDevice;
SAFE_RELEASE(g_pEffect);
SAFE_RELEASE(g_pFont);
SAFE_RELEASE(g_pFullScreenRenderTargetSurf);
SAFE_RELEASE(g_pFullScreenRenderTarget);
SAFE_RELEASE(g_pMesh1);
SAFE_RELEASE(g_pMeshTexture1);
SAFE_RELEASE(g_pMesh2);
SAFE_RELEASE(g_pMeshTexture2);
SAFE_RELEASE(g_pMeshTexture3);
for iObject:= 0 to NUM_OBJECTS - 1 do
begin
g_pScene1Object[iObject].g_pMesh := nil;
g_pScene1Object[iObject].g_pMeshTexture := nil;
end;
for iObject:= 0 to NUM_WALLS - 1 do
begin
g_pScene2Object[iObject].g_pMesh := nil;
g_pScene2Object[iObject].g_pMeshTexture := nil;
end;
end;
procedure CreateCustomDXUTobjects;
begin
g_DialogResourceManager:= CDXUTDialogResourceManager.Create; // manager for shared resources of dialogs
g_SettingsDlg:= CD3DSettingsDlg.Create; // Device settings dialog
g_Camera:= CFirstPersonCamera.Create;
g_HUD := CDXUTDialog.Create;
g_SampleUI := CDXUTDialog.Create;
end;
procedure DestroyCustomDXUTobjects;
var
iObject: Integer;
begin
FreeAndNil(g_DialogResourceManager);
FreeAndNil(g_SettingsDlg);
FreeAndNil(g_Camera);
FreeAndNil(g_HUD);
FreeAndNil(g_SampleUI);
for iObject:= 0 to NUM_OBJECTS - 1 do Dispose(g_pScene1Object[iObject]);
for iObject:= 0 to NUM_WALLS - 1 do Dispose(g_pScene2Object[iObject]);
end;
end.
|
unit apiDeprecated;
{$I apiConfig.inc}
interface
uses
Windows;
type
IAIMPDeprecatedTaskOwner = interface(IUnknown)
['{41494D50-5461-736B-4F77-6E6572000000}']
function IsCanceled: LongBool;
end;
IAIMPDeprecatedTask = interface(IUnknown)
['{41494D50-5461-736B-0000-000000000000}']
procedure Execute(Owner: IAIMPDeprecatedTaskOwner); stdcall;
end;
{ IAIMPDeprecatedServiceSynchronizer }
IAIMPDeprecatedServiceSynchronizer = interface(IUnknown)
['{41494D50-5372-7653-796E-637200000000}']
function ExecuteInMainThread(Task: IAIMPDeprecatedTask; ExecuteNow: LongBool): HRESULT; stdcall;
end;
{ IAIMPDeprecatedServiceThreadPool }
IAIMPDeprecatedServiceThreadPool = interface(IUnknown)
['{41494D50-5372-7654-6872-64506F6F6C00}']
function Cancel(TaskHandle: THandle; Flags: DWORD): HRESULT; stdcall;
function Execute(Task: IAIMPDeprecatedTask; out TaskHandle: THandle): HRESULT; stdcall;
function WaitFor(TaskHandle: THandle): HRESULT; stdcall;
end;
implementation
end.
|
//////////////////////////////////////////////////////////////////////////
// This file is a part of NotLimited.Framework.Common NuGet package.
// You are strongly discouraged from fiddling with it.
// If you do, all hell will break loose and living will envy the dead.
//////////////////////////////////////////////////////////////////////////
using System;
using System.IO;
namespace NotLimited.Framework.Common.Helpers
{
public static class StreamExtensions
{
public static byte[] ReadBytes(this Stream stream, int count)
{
var result = new byte[count];
int totalRead = 0;
int read;
while (totalRead < count)
{
if ((read = stream.Read(result, totalRead, count - totalRead)) == -1)
throw new EndOfStreamException();
totalRead += read;
}
return result;
}
public static void WriteBuff(this Stream stream, byte[] buff)
{
stream.Write(buff, 0, buff.Length);
}
/// <summary>
/// Reads the given stream up to the end, returning the data as a byte
/// array, using the given buffer for transferring data. Note that the
/// current contents of the buffer is ignored, so the buffer needn't
/// be cleared beforehand.
///
/// </summary>
public static byte[] ReadAllBytes(this Stream input)
{
if (input == null)
throw new ArgumentNullException("input");
using (var stream = new MemoryStream())
{
input.CopyTo(stream);
return stream.ToArray();
}
}
}
} |
unit HashAlgMD2_U;
// Description: MD2 Hash (Wrapper for the MD5 Hashing Engine)
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Classes,
HashAlg_U,
HashValue_U,
HashAlgMD2Engine_U;
type
THashAlgMD2 = class(THashAlg)
private
md2Engine: THashAlgmd2Engine;
context: MD2_CTX;
protected
{ Protected declarations }
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure Init(); override;
procedure Update(const input: array of byte; const inputLen: cardinal); override;
procedure Final(digest: THashValue); override;
end;
procedure Register;
implementation
uses
SysUtils; // needed for fmOpenRead
procedure Register;
begin
RegisterComponents('Hash', [THashAlgMD2]);
end;
constructor THashAlgMD2.Create(AOwner: TComponent);
begin
inherited;
md2Engine:= THashAlgmd2Engine.Create();
fTitle := 'MD2';
fHashLength := 128;
fBlockLength := 128;
end;
destructor THashAlgMD2.Destroy();
begin
// Nuke any existing context before freeing off the engine...
md2Engine.MD2Init(context);
md2Engine.Free();
inherited;
end;
procedure THashAlgMD2.Init();
begin
md2Engine.MD2Init(context);
end;
procedure THashAlgMD2.Update(const input: array of byte; const inputLen: cardinal);
begin
md2Engine.MD2Update(context, input, inputLen);
end;
procedure THashAlgMD2.Final(digest: THashValue);
begin
md2Engine.MD2Final(digest, context);
end;
END.
|
unit uQueryInventory;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Grids, DBGrids, DBCtrls, StdCtrls, Mask, LblEffct, ExtCtrls, DBTables, DB,
Buttons, ComCtrls, ADODB, SuperComboADO, siComp, siLangRT, SubListPanel,
uPai, DBClient, Provider;
type
TQueryInventory = class(TFrmPai)
dsModel: TDataSource;
quBarCode: TADOQuery;
edBarcode: TEdit;
Label6: TLabel;
pnlModel: TPanel;
Label1: TLabel;
scModel: TSuperComboADO;
Label2: TLabel;
DBEdit1: TDBEdit;
Label3: TLabel;
DBEdit2: TDBEdit;
Label4: TLabel;
DBEdit3: TDBEdit;
pnlCostPrice: TPanel;
lblCost: TLabel;
btShowCost: TSpeedButton;
EditCost: TDBEdit;
Label5: TLabel;
pglModel: TPageControl;
tbsQty: TTabSheet;
tbsBarCodes: TTabSheet;
Panel4: TPanel;
quShowBarcodes: TADOQuery;
dsShowBarcodes: TDataSource;
quShowBarcodesIDBarcode: TStringField;
quShowBarcodesIDModel: TIntegerField;
dxDBGrid1: TDBGrid;
gridQty: TDBGrid;
dsQty: TDataSource;
quModel: TADODataSet;
quModelPeso: TBCDField;
quModelDescription: TStringField;
quModelVendorCost: TBCDField;
quModelOtherCost: TBCDField;
quModelFreightCost: TBCDField;
quModelLastCost: TBCDField;
quModelReplacementCost: TBCDField;
quModelStoreSellingPrice: TBCDField;
quModelInventoryPrice: TBCDField;
quModelInvSellingPrice: TCurrencyField;
quModelTabGroup: TStringField;
quModelAvgCost: TBCDField;
btnOK: TButton;
quModelIDModel: TIntegerField;
quModelModel: TStringField;
cmbModel: TDBLookupComboBox;
lbDescrip: TLabel;
DBEdit4: TDBEdit;
tsImages: TTabSheet;
pgImages: TPageControl;
tsImage1: TTabSheet;
img1: TImage;
tsImage2: TTabSheet;
img2: TImage;
quModelLargeImage: TStringField;
quModelLargeImage2: TStringField;
gridCaratc: TDBGrid;
gridCaractTec: TDBGrid;
dsInvFeature: TDataSource;
dsInvTechFeature: TDataSource;
rbDescription: TRadioButton;
rbModel: TRadioButton;
lbPromo: TLabel;
DBEdit5: TDBEdit;
quModelPromotionPrice: TBCDField;
quModelIndicadorProducao: TStringField;
quModelIndicadorAT: TStringField;
quModelSituacaoTributaria: TIntegerField;
quModelUnidade: TStringField;
quModelSigla: TStringField;
Label7: TLabel;
DBEdit6: TDBEdit;
lbIndArr: TLabel;
DBEdit7: TDBEdit;
lnIndPro: TLabel;
DBEdit8: TDBEdit;
quModelDescSituTribut: TStringField;
Label10: TLabel;
DBEdit9: TDBEdit;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure scModelSelectItem(Sender: TObject);
procedure btDetailClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure edBarcodeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure btShowCostClick(Sender: TObject);
procedure spHelpClick(Sender: TObject);
procedure quModelCalcFields(DataSet: TDataSet);
procedure cmbModelCloseUp(Sender: TObject);
procedure edBarcodeEnter(Sender: TObject);
procedure edBarcodeExit(Sender: TObject);
procedure cmbModelDropDown(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure rbDescriptionClick(Sender: TObject);
procedure rbModelClick(Sender: TObject);
procedure cmbModelKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
FModel : String;
FFilterQty : String;
procedure RefreshTXTInfo;
procedure RefreshModel(IDModel:Integer);
procedure SelectBarcode;
procedure LoadImage(ImagePath:String; myImage: TImage);
procedure QtyOption;
public
IsDetail : Boolean;
function Start(var Model:String):Boolean;
end;
implementation
uses uPassword, uMsgBox, uDM, uMsgConstant, uDMGlobal, uDMPDV, Variants;
{$R *.DFM}
procedure TQueryInventory.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
quModel.Close;
quShowBarcodes.Close;
DMPDV.CloseQuantity;
with DMPDV.cdsBarcodeSearch do
begin
Filtered := False;
Filter := '';
end;
with DMPDV.cdsModel do
begin
Filtered := False;
Filter := '';
end;
with DMPDV.cdsQty do
begin
Filtered := False;
Filter := '';
end;
Action := caFree;
end;
procedure TQueryInventory.FormShow(Sender: TObject);
begin
inherited;
QtyOption;
btShowCostClick(nil);
pnlCostPrice.Visible := Password.HasFuncRight(2);
edBarcode.SetFocus;
end;
procedure TQueryInventory.scModelSelectItem(Sender: TObject);
begin
inherited;
if scModel.LookUpValue <> '' then
RefreshModel(StrToInt(scModel.LookUpValue));
end;
procedure TQueryInventory.btDetailClick(Sender: TObject);
begin
inherited;
scModel.CallUpdate;
end;
procedure TQueryInventory.FormCreate(Sender: TObject);
begin
inherited;
IsDetail := False;
end;
procedure TQueryInventory.SelectBarCode;
var
bAchou: Boolean;
AIDModel: Integer;
begin
if edBarcode.Text <> '' then
begin
case DM.PersistenceType of
ptDB:
with quBarcode do
begin
if quBarcode.Active then
quBarcode.Close;
quBarcode.Parameters.ParambyName('IDBarcode').Value := edBarcode.Text;
quBarcode.Open;
edBarcode.Clear;
if quBarcode.RecordCount > 0 then
begin
//Verifica se o Model esta deletado e Restaura
AIDModel := quBarcode.FieldByName('IDModel').AsInteger;
bAchou := True;
DM.ModelRestored(AIDModel);
end
else
bAchou := False;
Close;
end;
ptTXT:
begin
try
DMPDV.cdsBarcodeSearch.Filtered := False;
DMPDV.cdsBarcodeSearch.Filter := Format('IDBarcode = %S', [QuotedStr(edBarcode.Text)]);
DMPDV.cdsBarcodeSearch.Filtered := True;
bAchou := not DMPDV.cdsBarcodeSearch.IsEmpty;
if bAchou then
AIDModel := DMPDV.cdsBarcodeSearch.FieldByName('IDModel').AsInteger;
finally
DMPDV.cdsBarcodeSearch.Filtered := True;
DMPDV.cdsBarcodeSearch.Filter := '';
DMPDV.cdsBarcodeSearch.Filtered := False;
end;
end;
end;
edBarcode.Clear;
if bAchou then
begin
case DM.PersistenceType of
ptDB:
scModel.LookUpValue := IntToStr(AIDModel);
ptTXT:
cmbModel.KeyValue := AIDModel;
end;
//scModelSelectItem(nil);
RefreshModel(AIDModel);
end
else
MsgBox(MSG_CRT_NO_BARCODE, vbCritical + vbOkOnly);
end;
end;
procedure TQueryInventory.edBarcodeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if (key = 13) then
SelectBarCode;
end;
procedure TQueryInventory.btShowCostClick(Sender: TObject);
begin
inherited;
editCost.Visible := btShowCost.Down;
lblCost.Visible := btShowCost.Down;
end;
procedure TQueryInventory.spHelpClick(Sender: TObject);
begin
inherited;
Application.HelpContext(260);
end;
procedure TQueryInventory.quModelCalcFields(DataSet: TDataSet);
begin
inherited;
if quModelStoreSellingPrice.AsCurrency <> 0 then
quModelInvSellingPrice.AsCurrency := quModelStoreSellingPrice.AsCurrency
else
quModelInvSellingPrice.AsCurrency := quModelInventoryPrice.AsCurrency;
case quModelSituacaoTributaria.AsInteger of
0,1 : quModelDescSituTribut.AsString := 'Tributável';
2 : quModelDescSituTribut.AsString := 'Não Tributável';
3 : quModelDescSituTribut.AsString := 'Substit. Tributária';
4 : quModelDescSituTribut.AsString := 'Isento';
5 : quModelDescSituTribut.AsString := 'ISS';
end;
end;
procedure TQueryInventory.RefreshModel(IDModel:Integer);
begin
if IDModel <> 0 then
begin
if DM.PersistenceType = ptDB then
begin
with quModel do
begin
if Active then Close;
Parameters.ParambyName('IDModel').Value := IDModel;
Parameters.ParambyName('IDStore').Value := DM.fStore.ID;
Open;
LoadImage(quModelLargeImage.AsString,img1);
LoadImage(quModelLargeImage2.AsString,img2);
end;
with quShowBarcodes do
begin
If Active then Close;
Parameters.ParambyName('IDModel').Value := IDModel;
Open;
end;
with DMPDV.cdsInvFeatures do
begin
if Active then
Close;
Params.ParamByName('IDModel').Value := IDModel;
Open;
end;
with DMPDV.cdsInvTechFeat do
begin
if Active then
Close;
Params.ParamByName('IDModel').Value := IDModel;
Open;
end;
end;
if DM.PersistenceType = ptTXT then
begin
with DMPDV.cdsBarcodeSearch do
begin
Filtered := False;
Filter := Format('IDModel = %D', [IDModel]);
Filtered := True;
end;
with DMPDV.cdsModel do
begin
Filtered := False;
Filter := Format('IDModel = %D', [IDModel]);
Filtered := True;
LoadImage(DMPDV.cdsModel.FieldByName('LargeImage').AsString,img1);
LoadImage(DMPDV.cdsModel.FieldByName('LargeImage2').AsString,img2);
end;
with DMPDV.cdsInvFeatures do
begin
if not Active then
DM.PrepareCDS(DMPDV.cdsInvFeatures, 'InvFeatures', 'IDInvFeatures', True);
Filtered := False;
Filter := Format('IDModel = %D', [IDModel]);
Filtered := True;
end;
with DMPDV.cdsInvTechFeat do
begin
if not Active then
DM.PrepareCDS(DMPDV.cdsInvTechFeat, 'InvTechFeatures', 'IDInvTechFeatures', True);
Filtered := False;
Filter := Format('IDModel = %D', [IDModel]);
Filtered := True;
end;
end;
DMPDV.CloseQuantity;
DMPDV.OpenQuantity(IDModel, FFilterQty);
end;
end;
function TQueryInventory.Start(var Model: String): Boolean;
begin
FModel := '';
if DM.PersistenceType = ptTXT then
begin
dsModel.DataSet := DMPDV.cdsMDescription;
dsShowBarcodes.DataSet := DMPDV.cdsBarcodeSearch;
cmbModel.Visible := True;
scModel.Visible := False;
rbDescription.Visible := True;
rbModel.Visible := True;
end
else
begin
dsModel.DataSet := quModel;
dsShowBarcodes.DataSet := quShowBarcodes;
scModel.Visible := True;
cmbModel.Visible := False;
rbDescription.Visible := False;
rbModel.Visible := False;
end;
ShowModal;
Model := FModel;
Result := ((ModalResult = mrOK) and (Model <> ''));
end;
procedure TQueryInventory.cmbModelCloseUp(Sender: TObject);
begin
inherited;
btnOK.Default := True;
RefreshTXTInfo;
end;
procedure TQueryInventory.RefreshTXTInfo;
begin
if DM.PersistenceType = ptTXT then
if VarToStr(cmbModel.KeyValue) <> '' then
RefreshModel(StrToInt(cmbModel.KeyValue));
end;
procedure TQueryInventory.edBarcodeEnter(Sender: TObject);
begin
inherited;
btnOK.Default := False;
end;
procedure TQueryInventory.edBarcodeExit(Sender: TObject);
begin
inherited;
btnOK.Default := True;
end;
procedure TQueryInventory.cmbModelDropDown(Sender: TObject);
begin
inherited;
btnOK.Default := False;
end;
procedure TQueryInventory.LoadImage(ImagePath:String; myImage: TImage);
begin
myImage.Picture := nil;
if (ImagePath <> '') and (FileExists(ImagePath)) then
myImage.Picture.LoadFromFile(ImagePath);
end;
procedure TQueryInventory.btnOKClick(Sender: TObject);
begin
inherited;
if DM.PersistenceType = ptTXT then
begin
if cmbModel.KeyValue <> Null then
with DMPDV.cdsModel do
begin
Filtered := False;
Filter := 'IDModel = ' + IntToStr(cmbModel.KeyValue);
Filtered := True;
FModel := DMPDV.cdsModel.FieldByName('Model').AsString;
end;
end
else
FModel := scModel.Text;
end;
procedure TQueryInventory.rbDescriptionClick(Sender: TObject);
begin
inherited;
if DM.PersistenceType = ptTXT then
cmbModel.ListField := 'Description; Model';
end;
procedure TQueryInventory.rbModelClick(Sender: TObject);
begin
inherited;
if DM.PersistenceType = ptTXT then
cmbModel.ListField := 'Model; Description';
end;
procedure TQueryInventory.QtyOption;
begin
if DM.fCashRegister.HideOtherStoreQry then
FFilterQty := 'StoreID IN (' + DM.fStore.StoreList + ')'
else
FFilterQty := '';
gridQty.Columns[1].Visible := Password.HasFuncRight(45);
gridQty.Columns[2].Visible := Password.HasFuncRight(47);
end;
procedure TQueryInventory.cmbModelKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
RefreshTXTInfo;
end;
end.
|
unit uDlgContract3DetailCard;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uDlgContractCard, Menus, cxLookAndFeelPainters, cxGraphics, DB,
ADODB, uFrameObjectList, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit,
cxDBLookupComboBox, cxButtonEdit, cxDBEdit, cxMaskEdit, cxCalendar,
cxContainer, cxEdit, cxTextEdit, StdCtrls, cxPC, cxControls, cxButtons,
ExtCtrls, cxCurrencyEdit, cxMemo, cxCheckBox, cxGroupBox,
uFrameObjectList_ContractActual, uDlgContract3Card;
type
TdlgContract3DetailCard = class(TdlgContract3Card)
tsObjectsDeleted: TcxTabSheet;
FrameObjectListDeleted: TFrameObjectList;
lcDocType: TcxDBLookupComboBox;
dsDocType: TDataSource;
qryDocType: TADOQuery;
Label25: TLabel;
Label26: TLabel;
deEndDate: TcxDBDateEdit;
dsRecordStatus: TDataSource;
qryRecordStatus: TADOQuery;
Label28: TLabel;
lcRecordStatus: TcxDBLookupComboBox;
procedure QueryAfterOpen(DataSet: TDataSet);
procedure pcObjectsChange(Sender: TObject);
procedure lcDocTypePropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure ceMoneyPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure cbManualRentEnterPropertiesChange(Sender: TObject);
private
{ Private declarations }
protected
function GetItemName: string; override;
procedure Check; override;
procedure OnCreate; override;
procedure OpenDeleteDialog(Sender: TObject);
procedure RemoveDeletedObject(Sender: TObject);
procedure btn4ApplyFilterClick(Sender: TObject); virtual;
procedure FrameObjectFilterbtn4ApplyFilterClick(Sender: TObject); virtual;
procedure FrameAdded_spObjectListBeforeOpen(DataSet: TDataSet);
procedure FrameDeleted_spObjectListBeforeOpen(DataSet: TDataSet);
public
constructor Create(AOwner: TComponent); override;
end;
var
dlgContract3DetailCard: TdlgContract3DetailCard;
implementation
uses uParams, uCommonUtils, uDlgRemoveObjects, uAccess, uMain, uUserBook, cxtCustomDataSourceM;
{$R *.dfm}
{ TdlgContract3DetailCard }
procedure TdlgContract3DetailCard.Check;
var
d: TDateTime;
begin
if trim(teNum.Text)='' then begin
ShowError('Ошибка ввода', 'Необходимо заполнить поле "Номер соглашения"', Handle);
teNum.SetFocus;
abort;
end;
if not TryStrToDate(deDate.Text, d) then begin
ShowError('Ошибка ввода', 'Необходимо заполнить поле "Дата подписания"', Handle);
deDate.SetFocus;
abort;
end;
end;
function TdlgContract3DetailCard.GetItemName: string;
begin
result:='ДопСоглашение';
end;
procedure TdlgContract3DetailCard.btn4ApplyFilterClick(Sender: TObject);
var
p: TParamCollection;
begin
p:=FrameObjectListAdded.FrameObjectFilter.CreateFilterParams;
try
p[format('@код_%s', [GetItemName])].Value:=PrimaryKey;
p['@Flag'].Value:=1;
FrameObjectListAdded.FrameByProps.ApplyFilterParams(p);
finally
p.Free;
end;
end;
procedure TdlgContract3DetailCard.QueryAfterOpen(DataSet: TDataSet);
begin
inherited;
if Query.RecordCount>0 then begin
FrameObjectList_ContractActual.ContractID:=Query['вк_Договор'];
FrameObjectList_ContractActual.OnDate:=Query['Дата подписания'];
end;
end;
procedure TdlgContract3DetailCard.FrameObjectFilterbtn4ApplyFilterClick(
Sender: TObject);
var
p: TParamCollection;
begin
p:=FrameObjectListDeleted.FrameObjectFilter.CreateFilterParams;
try
p[format('@код_%s', [GetItemName])].Value:=PrimaryKey;
p['@Flag'].Value:=0;
FrameObjectListDeleted.FrameByProps.ApplyFilterParams(p);
finally
p.Free;
end;
end;
procedure TdlgContract3DetailCard.OpenDeleteDialog(Sender: TObject);
var
a: TAccessSelectorForm;
i: integer;
qry: TAdoQuery;
p: TParamCollection;
begin
a:=TAccessSelectorForm.Create;
try
a.ObjectID:=9;
a.FormClass:=TdlgRemoveObjects;
p:=TParamCollection.Create(TParamItem);
try
p['код_Договор'].Value:=Query['вк_Договор'];
p['НаДату'].Value:=Query['Дата подписания'];
p['ДляУдаления'].Value:=true;
a.FormAutoFree:=false;
if a.ShowModal(p, null)<>mrOK then exit;
qry:=CreateQuery('');
try
with (a.Form as TdlgRemoveObjects).SelectedIDs do
for i:=0 to Count-1 do begin
qry.SQL.Text:=format('sp_%sОбъект_добавить @код_%s = %d, @код_Объект = %d, @код_Вид_пользования = %s, @код_Статус = %s, @Flag = 0', [GetItemName, GetItemName, PrimaryKey, Items[i].Value, VariantToStrDB(Items[i].ViewID), VariantToStrDB(Items[i].StatusID)]);
qry.ExecSQL;
end;
finally
qry.Free;
end;
finally
p.Free;
end;
finally
a.Free;
end;
end;
procedure TdlgContract3DetailCard.RemoveDeletedObject(Sender: TObject);
var
id: integer;
dsc: TcxtCustomDataSourceM;
begin
with FrameObjectListDeleted.FrameByProps do begin
dsc:=DataSourceCash;
if (not dsc.Active) or (ViewCds.DataController.FilteredRecordCount=0) then exit;
if MessageBox(Handle, 'Удалить объект из списка?', 'Удаление', MB_YESNO or MB_ICONQUESTION or MB_APPLMODAL)=IDNO then exit;
id:=dsc.Values[ViewCds.DataController.FocusedRecordIndex, 0];
ExecSQL(format('sp_%sОбъект_удалить @код_%s = %d, @код_Объект = %d', [GetItemName, GetItemName, PrimaryKey, id]));
dsc.DeleteRecord(ViewCds.DataController.FocusedRecordIndex);
{ if (not spObjectList.Active) or (spObjectList.RecordCount=0) then exit;
if MessageBox(Handle, 'Удалить объект из списка?', 'Удаление', MB_YESNO or MB_ICONQUESTION or MB_APPLMODAL)=IDNO then exit;
id:=self.FrameObjectListDeleted.FrameByProps.spObjectList['Учетная единица.код_Учетная единица'];
ExecSQL(format('sp_%sОбъект_удалить @код_%s = %d, @код_Объект = %d', [GetItemName, GetItemName, PrimaryKey, id]));
spObjectList.Delete;}
end;
end;
procedure TdlgContract3DetailCard.OnCreate;
begin
inherited;
FrameObjectListDeleted.FrameByProps.OnInsert:=OpenDeleteDialog;
FrameObjectListDeleted.FrameByProps.OnDelete:=RemoveDeletedObject;
qryDocType.Connection:=frmMain.AdoConnection;
qryDocType.Open;
qryRecordStatus.Connection:=frmMain.ADOConnection;
qryRecordStatus.Open;
end;
procedure TdlgContract3DetailCard.pcObjectsChange(Sender: TObject);
begin
inherited;
FrameObjectListDeleted.NavBar.Repaint;
end;
procedure TdlgContract3DetailCard.lcDocTypePropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
a: TAccessBook;
lc: TcxDBLookupComboBox;
qry: TAdoQuery;
begin
inherited;
if AButtonIndex=2 then begin
a:=TAccessBook.Create;
try
lc:=Sender as TcxDBLookupComboBox;
a.ObjectID:=lc.Tag;
qry:=lc.Properties.ListSource.DataSet as TAdoQuery;
if a.ShowModal(qry[qry.Fields[0].FieldName], false, false)<>mrOK then exit;
qry.Close;
qry.Open;
lc.DataBinding.StoredValue:=(a.UserBook as TUserBook).PrimaryKeyValue;
lc.DataBinding.UpdateDisplayValue;
finally
a.Free;
end;
end;
if AButtonIndex=1 then begin
(Sender as TcxDBLookupComboBox).DataBinding.StoredValue:=null;
(Sender as TcxDBLookupComboBox).DataBinding.DisplayValue:=null;
end
end;
constructor TdlgContract3DetailCard.Create(AOwner: TComponent);
begin
inherited;
self.FrameObjectListAdded.FrameObjectFilter.bbApplyFilter.OnClick:=btn4ApplyFilterClick;
self.FrameObjectListDeleted.FrameObjectFilter.bbApplyFilter.OnClick:=FrameObjectFilterbtn4ApplyFilterClick;
FrameObjectListAdded.FrameByProps.spObjectList.BeforeOpen:=FrameAdded_spObjectListBeforeOpen;
FrameObjectListDeleted.FrameByProps.spObjectList.BeforeOpen:=FrameDeleted_spObjectListBeforeOpen;
end;
procedure TdlgContract3DetailCard.ceMoneyPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
inherited;
{ if not VarIsNullMy(Query.Fields[0].Value) then
dlgRent2Account.Restore(false, Query.Fields[0].Value)
else
dlgRent2Account.Restore(false, 0);
if dlgRent2Account.ShowModal<>mrOK then exit;
ceMoney.DataBinding.StoredValue:=dlgRent2Account.Value;
ceMoney.DataBinding.DisplayValue:=dlgRent2Account.Value;
dlgRent2Account.NeedSave:=true;
cbManualRentEnter.Checked:=true;}
// dlgRent2Account.Save(false, Query.Fields[0].Value, true);
end;
procedure TdlgContract3DetailCard.cbManualRentEnterPropertiesChange(
Sender: TObject);
begin
if cbManualRentEnter.Checked then begin
ceMoney.Style.Color:=clWindow;
end else begin
ceMoney.Style.Color:=clBtnFace;
end;
ceMoney.Properties.ReadOnly:=not cbManualRentEnter.Checked;
end;
procedure TdlgContract3DetailCard.FrameAdded_spObjectListBeforeOpen(
DataSet: TDataSet);
begin
FrameObjectListAdded.FrameByProps.spObjectList.Parameters.FindParam('@Flag').Value:=1;
end;
procedure TdlgContract3DetailCard.FrameDeleted_spObjectListBeforeOpen(
DataSet: TDataSet);
begin
FrameObjectListDeleted.FrameByProps.spObjectList.Parameters.FindParam('@Flag').Value:=0;
end;
end.
|
unit IdServerSocketIOHandling;
interface
uses
IdContext, IdCustomTCPServer,
//IdServerWebsocketContext,
Classes, Generics.Collections,
superobject, IdException, IdServerBaseHandling, IdSocketIOHandling;
type
TIdServerSocketIOHandling = class(TIdBaseSocketIOHandling)
protected
procedure ProcessHeatbeatRequest(const AContext: ISocketIOContext; const aText: string); override;
public
function SendToAll(const aMessage: string; const aCallback: TSocketIOMsgJSON = nil; const aOnError: TSocketIOError = nil): Integer;
procedure SendTo (const aContext: TIdServerContext; const aMessage: string; const aCallback: TSocketIOMsgJSON = nil; const aOnError: TSocketIOError = nil);
function EmitEventToAll(const aEventName: string; const aData: ISuperObject; const aCallback: TSocketIOMsgJSON = nil; const aOnError: TSocketIOError = nil): Integer;overload;
function EmitEventToAll(const aEventName: string; const aData: string ; const aCallback: TSocketIOMsgJSON = nil; const aOnError: TSocketIOError = nil): Integer;overload;
procedure EmitEventTo (const aContext: ISocketIOContext;
const aEventName: string; const aData: ISuperObject; const aCallback: TSocketIOMsgJSON = nil; const aOnError: TSocketIOError = nil);overload;
procedure EmitEventTo (const aContext: TIdServerContext;
const aEventName: string; const aData: ISuperObject; const aCallback: TSocketIOMsgJSON = nil; const aOnError: TSocketIOError = nil);overload;
end;
implementation
uses
SysUtils, StrUtils;
{ TIdServerSocketIOHandling }
procedure TIdServerSocketIOHandling.EmitEventTo(
const aContext: ISocketIOContext; const aEventName: string;
const aData: ISuperObject; const aCallback: TSocketIOMsgJSON; const aOnError: TSocketIOError);
var
jsonarray: string;
begin
if aContext.IsDisconnected then
raise EIdSocketIoUnhandledMessage.Create('socket.io connection closed!');
if aData.IsType(stArray) then
jsonarray := aData.AsString
else if aData.IsType(stString) then
jsonarray := '["' + aData.AsString + '"]'
else
jsonarray := '[' + aData.AsString + ']';
if not Assigned(aCallback) then
WriteSocketIOEvent(aContext, ''{no room}, aEventName, jsonarray, nil, nil)
else
WriteSocketIOEventRef(aContext, ''{no room}, aEventName, jsonarray,
procedure(const aData: string)
begin
aCallback(aContext, SO(aData), nil);
end, aOnError);
end;
procedure TIdServerSocketIOHandling.EmitEventTo(
const aContext: TIdServerContext; const aEventName: string;
const aData: ISuperObject; const aCallback: TSocketIOMsgJSON; const aOnError: TSocketIOError);
var
context: ISocketIOContext;
begin
Lock;
try
context := FConnections.Items[aContext];
EmitEventTo(context, aEventName, aData, aCallback, aOnError);
finally
UnLock;
end;
end;
function TIdServerSocketIOHandling.EmitEventToAll(const aEventName,
aData: string; const aCallback: TSocketIOMsgJSON;
const aOnError: TSocketIOError): Integer;
var
context: ISocketIOContext;
jsonarray: string;
begin
Result := 0;
jsonarray := '[' + aData + ']';
Lock;
try
for context in FConnections.Values do
begin
if context.IsDisconnected then Continue;
try
if not Assigned(aCallback) then
WriteSocketIOEvent(context, ''{no room}, aEventName, jsonarray, nil, nil)
else
WriteSocketIOEventRef(context, ''{no room}, aEventName, jsonarray,
procedure(const aData: string)
begin
aCallback(context, SO(aData), nil);
end, aOnError);
except
//try to send to others
end;
Inc(Result);
end;
for context in FConnectionsGUID.Values do
begin
if context.IsDisconnected then Continue;
try
if not Assigned(aCallback) then
WriteSocketIOEvent(context, ''{no room}, aEventName, jsonarray, nil, nil)
else
WriteSocketIOEventRef(context, ''{no room}, aEventName, jsonarray,
procedure(const aData: string)
begin
aCallback(context, SO(aData), nil);
end, aOnError);
except
//try to send to others
end;
Inc(Result);
end;
finally
UnLock;
end;
end;
function TIdServerSocketIOHandling.EmitEventToAll(const aEventName: string; const aData: ISuperObject;
const aCallback: TSocketIOMsgJSON; const aOnError: TSocketIOError): Integer;
begin
if aData.IsType(stString) then
Result := EmitEventToAll(aEventName, '"' + aData.AsString + '"', aCallback, aOnError)
else
Result := EmitEventToAll(aEventName, aData.AsString, aCallback, aOnError);
end;
procedure TIdServerSocketIOHandling.ProcessHeatbeatRequest(
const AContext: ISocketIOContext; const aText: string);
begin
inherited ProcessHeatbeatRequest(AContext, aText);
end;
procedure TIdServerSocketIOHandling.SendTo(const aContext: TIdServerContext;
const aMessage: string; const aCallback: TSocketIOMsgJSON; const aOnError: TSocketIOError);
var
context: ISocketIOContext;
begin
Lock;
try
context := FConnections.Items[aContext];
if context.IsDisconnected then
raise EIdSocketIoUnhandledMessage.Create('socket.io connection closed!');
if not Assigned(aCallback) then
WriteSocketIOMsg(context, ''{no room}, aMessage, nil)
else
WriteSocketIOMsg(context, ''{no room}, aMessage,
procedure(const aData: string)
begin
aCallback(context, SO(aData), nil);
end, aOnError);
finally
UnLock;
end;
end;
function TIdServerSocketIOHandling.SendToAll(const aMessage: string;
const aCallback: TSocketIOMsgJSON; const aOnError: TSocketIOError): Integer;
var
context: ISocketIOContext;
begin
Result := 0;
Lock;
try
for context in FConnections.Values do
begin
if context.IsDisconnected then Continue;
if not Assigned(aCallback) then
WriteSocketIOMsg(context, ''{no room}, aMessage, nil)
else
WriteSocketIOMsg(context, ''{no room}, aMessage,
procedure(const aData: string)
begin
aCallback(context, SO(aData), nil);
end, aOnError);
Inc(Result);
end;
for context in FConnectionsGUID.Values do
begin
if context.IsDisconnected then Continue;
if not Assigned(aCallback) then
WriteSocketIOMsg(context, ''{no room}, aMessage, nil)
else
WriteSocketIOMsg(context, ''{no room}, aMessage,
procedure(const aData: string)
begin
aCallback(context, SO(aData), nil);
end);
Inc(Result);
end;
finally
UnLock;
end;
end;
end.
|
unit GLD3dsCamera;
interface
uses
Classes, GL, GLDTypes, GLDConst, GLDClasses, GLD3dsTypes, GLD3dsChunk, GLD3dsIo;
type
TGLD3dsCamera = class;
TGLD3dsCameraList = class;
TGLD3dsCamera = class(TGLDSysClass)
private
FName: string;
FPosition: TGLDVector4fClass;
FTarget: TGLDVector4fClass;
FRoll: GLfloat;
FFov: GLfloat;
FSeeCone: GLboolean;
FNearRange: GLfloat;
FFarRange: GLfloat;
procedure SetName(Value: string);
procedure SetPosition(Value: TGLDVector4fClass);
procedure SetTarget(Value: TGLDVector4fClass);
procedure SetRoll(Value: GLfloat);
procedure SetFov(Value: GLfloat);
procedure SetSeeCone(Value: GLboolean);
procedure SetNearRange(Value: GLfloat);
procedure SetFarRange(Value: GLfloat);
function GetParams: TGLD3dsCameraParams;
procedure SetParams(Value: TGLD3dsCameraParams);
protected
procedure SetOnChange(Value: TNotifyEvent); override;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
class function SysClassType: TGLDSysClassType; override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
function Read(Stream: TStream): GLboolean;
property Params: TGLD3dsCameraParams read GetParams write SetParams;
published
property Name: string read FName write SetName;
property Position: TGLDVector4fClass read FPosition write SetPosition;
property Target: TGLDVector4fClass read FTarget write SetTarget;
property Roll: GLfloat read FRoll write SetRoll;
property Fov: GLfloat read FFov write SetFov;
property SeeCone: GLboolean read FSeeCone write SetSeeCone;
property NearRange: GLfloat read FNearRange write SetNearRange;
property FarRange: GLfloat read FFarRange write SetFarRange;
end;
PGLD3dsCameraArray = ^TGLD3dsCameraArray;
TGLD3dsCameraArray = array[1..GLD_MAX_LISTITEMS] of TGLD3dsCamera;
TGLD3dsCameraList = class(TGLDSysClass)
private
FCapacity: GLuint;
FCount: GLuint;
FList: PGLD3dsCameraArray;
procedure SetCapacity(NewCapacity: GLuint);
procedure SetCount(NewCount: GLuint);
function GetCamera(Index: GLuint): TGLD3dsCamera;
procedure SetCamera(Index: GLuint; Camera: TGLD3dsCamera);
function GetLast: TGLD3dsCamera;
procedure SetLast(Camera: TGLD3dsCamera);
protected
procedure DefineProperties(Filer: TFiler); override;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure Clear;
function CreateNew: GLuint;
function Add(Camera: TGLD3dsCamera): GLuint; overload;
function Add(AParams: TGLD3dsCameraParams): GLuint; overload;
function Delete(Index: GLuint): GLuint; overload;
function Delete(Camera: TGLD3dsCamera): GLuint; overload;
function IndexOf(Camera: TGLD3dsCamera): GLuint;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
class function SysClassType: TGLDSysClassType; override;
property Capacity: GLuint read FCapacity write SetCapacity;
property Count: GLuint read FCount write SetCount;
property List: PGLD3dsCameraArray read FList;
property Items[index: GLuint]: TGLD3dsCamera read GetCamera write SetCamera;
property Cameras[index: GLuint]: TGLD3dsCamera read GetCamera write SetCamera; default;
property Last: TGLD3dsCamera read GetLast write SetLast;
end;
implementation
constructor TGLD3dsCamera.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FName := '';
FPosition := TGLDVector4fClass.Create(Self);
FTarget := TGLDVector4fClass.Create(Self);
end;
destructor TGLD3dsCamera.Destroy;
begin
FPosition.Free;
FTarget.Free;
inherited Destroy;
end;
procedure TGLD3dsCamera.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLD3dsCamera) then Exit;
SetParams(TGLD3dsCamera(Source).GetParams);
end;
class function TGLD3dsCamera.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_3DS_CAMERA;
end;
procedure TGLD3dsCamera.LoadFromStream(Stream: TStream);
begin
GLDXLoadStringFromStream(Stream, FName);
Stream.Read(FPosition.GetPointer^, SizeOf(TGLDVector3f));
Stream.Read(FTarget.GetPointer^, SizeOf(TGLDVector3f));
Stream.Read(FRoll, SizeOf(GLfloat));
Stream.Read(FFov, SizeOf(GLfloat));
Stream.Read(FSeeCone, SizeOf(GLboolean));
Stream.Read(FNearRange, SizeOf(GLfloat));
Stream.Read(FFarRange, SizeOf(GLfloat));
end;
procedure TGLD3dsCamera.SaveToStream(Stream: TStream);
begin
GLDXSaveStringToStream(Stream, FName);
Stream.Write(FPosition.GetPointer^, SizeOf(TGLDVector3f));
Stream.Write(FTarget.GetPointer^, SizeOf(TGLDVector3f));
Stream.Write(FRoll, SizeOf(GLfloat));
Stream.Write(FFov, SizeOf(GLfloat));
Stream.Write(FSeeCone, SizeOf(GLboolean));
Stream.Write(FNearRange, SizeOf(GLfloat));
Stream.Write(FFarRange, SizeOf(GLfloat));
end;
function TGLD3dsCamera.Read(Stream: TStream): GLboolean;
var
C: TGLD3dsChunk;
i: GLuint;
begin
Result := False;
if not GLD3dsChunkReadStart(C, GLD3DS_N_CAMERA, Stream) then Exit;
Stream.Read(FPosition.GetPointer^, SizeOf(TGLDVector3f));
Stream.Read(FTarget.GetPointer^, SizeOf(TGLDVector3f));
FRoll := GLD3dsIoReadFloat(Stream);
repeat
GLD3dsChunkRead(C, Stream);
case C.Chunk of
GLD3DS_CAM_SEE_CONE:
begin
FSeeCone := True;
end;
GLD3DS_CAM_RANGES:
begin
FNearRange := GLD3dsIoReadFloat(Stream);
FFarRange := GLD3dsIoReadFloat(Stream);
end;
else
begin
GLD3dsChunkReadReset(Stream);
C.Chunk := 0;
end;
end;
until C.Chunk = 0;
Result := True;
end;
procedure TGLD3dsCamera.SetOnChange(Value: TNotifyEvent);
begin
inherited SetOnChange(Value);
FPosition.OnChange := FOnChange;
FTarget.OnChange := FOnChange;
end;
procedure TGLD3dsCamera.SetName(Value: string);
begin
if FName = Value then Exit;
FName := Value;
Change;
end;
procedure TGLD3dsCamera.SetPosition(Value: TGLDVector4fClass);
begin
FPosition.Assign(Value);
end;
procedure TGLD3dsCamera.SetTarget(Value: TGLDVector4fClass);
begin
FTarget.Assign(Value);
end;
procedure TGLD3dsCamera.SetRoll(Value: GLfloat);
begin
if FRoll = Value then Exit;
FRoll := Value;
Change;
end;
procedure TGLD3dsCamera.SetFov(Value: GLfloat);
begin
if FFov = Value then Exit;
FFov := Value;
Change;
end;
procedure TGLD3dsCamera.SetSeeCone(Value: GLboolean);
begin
if FSeeCone = Value then Exit;
FSeeCone := Value;
Change;
end;
procedure TGLD3dsCamera.SetNearRange(Value: GLfloat);
begin
if FNearRange = Value then Exit;
FNearRange := Value;
Change;
end;
procedure TGLD3dsCamera.SetFarRange(Value: GLfloat);
begin
if FFarRange = Value then Exit;
FFarRange := Value;
Change;
end;
function TGLD3dsCamera.GetParams: TGLD3dsCameraParams;
begin
Result := GLDX3DSCameraParams(FName, FPosition.Vector3f, FTarget.Vector3f,
FRoll, FFov, FSeeCone, FNearRange, FFarRange);
end;
procedure TGLD3dsCamera.SetParams(Value: TGLD3dsCameraParams);
begin
if GLDX3DSCameraParamsEqual(GetParams, Value) then Exit;
FName := Value.Name;
PGLDVector3f(FPosition.GetPointer)^ := Value.Position;
PGLDVector3f(FTarget.GetPointer)^ := Value.Target;
FRoll := Value.Roll;
FFov := Value.Fov;
FSeeCone := Value.SeeCone;
FNearRange := Value.NearRange;
FFarRange := Value.FarRange;
Change;
end;
constructor TGLD3dsCameraList.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FCapacity := 0;
FCount := 0;
FList := nil;
end;
destructor TGLD3dsCameraList.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TGLD3dsCameraList.Assign(Source: TPersistent);
var
i: GLuint;
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLD3dsCameraList) then Exit;
Clear;
SetCapacity(TGLD3dsCameraList(Source).FCapacity);
FCount := TGLD3dsCameraList(Source).FCount;
if FCount > 0 then
for i := 1 to FCount do
begin
FList^[i] := TGLD3dsCamera.Create(Self);
FList^[i].Assign(TGLD3dsCameraList(Source).FList^[i]);
end;
end;
procedure TGLD3dsCameraList.Clear;
var
i: GLuint;
begin
if FCount > 0 then
for i := 1 to FCount do
FList^[i].Free;
ReallocMem(FList, 0);
FCapacity := 0;
FCount := 0;
FList := nil;
end;
function TGLD3dsCameraList.CreateNew: GLuint;
begin
Result := 0;
if FCount < GLD_MAX_LISTITEMS then
begin
SetCount(FCount + 1);
Result := FCount;
end;
end;
function TGLD3dsCameraList.Add(Camera: TGLD3dsCamera): GLuint;
begin
Result := 0;
if Camera = nil then Exit;
Result := CreateNew;
if Result > 0 then
Last.Assign(Camera);
end;
function TGLD3dsCameraList.Add(AParams: TGLD3dsCameraParams): GLuint;
begin
Result := CreateNew;
if Result = 0 then Exit;
Last.SetParams(AParams);
end;
function TGLD3dsCameraList.Delete(Index: GLuint): GLuint;
var
i: GLuint;
begin
Result := 0;
if (Index < 1) or (Index > FCount) then Exit;
FList^[Index].Free;
FList^[Index] := nil;
if Index < FCount then
for i := Index to FCount - 1 do
FList^[i] := FList^[i + 1];
Dec(FCount);
Result := Index;
end;
function TGLD3dsCameraList.Delete(Camera: TGLD3dsCamera): GLuint;
begin
Result := Delete(IndexOf(Camera));
end;
function TGLD3dsCameraList.IndexOf(Camera: TGLD3dsCamera): GLuint;
var
i: GLuint;
begin
Result := 0;
if Camera = nil then Exit;
if FCount > 0 then
for i := 1 to FCount do
if FList^[i] = Camera then
begin
Result := i;
Exit;
end;
end;
procedure TGLD3dsCameraList.LoadFromStream(Stream: TStream);
var
ACapacity, ACount, i: GLuint;
begin
Clear;
Stream.Read(ACapacity, SizeOf(GLuint));
Stream.Read(ACount, SizeOf(GLuint));
SetCapacity(ACapacity);
if ACount > 0 then
begin
for i := 1 to ACount do
begin
FList^[i] := TGLD3dsCamera.Create(Self);
FList^[i].LoadFromStream(Stream);
end;
FCount := ACount;
end;
end;
procedure TGLD3dsCameraList.SaveToStream(Stream: TStream);
var
i: GLuint;
begin
Stream.Write(FCapacity, SizeOf(GLuint));
Stream.Write(FCount, SizeOf(GLuint));
if FCount > 0 then
for i := 1 to FCount do
FList^[i].SaveToStream(Stream);
end;
procedure TGLD3dsCameraList.DefineProperties(Filer: TFiler);
begin
Filer.DefineBinaryProperty('Data', LoadFromStream, SaveToStream, True);
end;
class function TGLD3dsCameraList.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_3DS_CAMERALIST;
end;
procedure TGLD3dsCameraList.SetCapacity(NewCapacity: GLuint);
var
i: GLuint;
begin
if (FCapacity = NewCapacity) or
(NewCapacity > GLD_MAX_LISTITEMS) then Exit;
if NewCapacity <= 0 then
begin
Clear;
Exit;
end else
begin
if NewCapacity < FCount then
SetCount(NewCapacity);
ReallocMem(FList, NewCapacity * SizeOf(TGLD3dsCamera));
if NewCapacity > FCapacity then
for i := FCapacity + 1 to NewCapacity do
FList^[i] := nil;
FCapacity := NewCapacity;
end;
end;
procedure TGLD3dsCameraList.SetCount(NewCount: GLuint);
var
i: GLuint;
begin
if (NewCount = FCount) or
(NewCount > GLD_MAX_LISTITEMS) then Exit;
if NewCount <= 0 then
begin
Clear;
Exit;
end else
begin
if NewCount > FCapacity then
SetCapacity(NewCount);
if NewCount > FCount then
for i := FCount + 1 to NewCount do
FList^[i] := TGLD3dsCamera.Create(Self) else
if NewCount < FCount then
for i := FCount downto NewCount + 1 do
begin
FList^[i].Free;
FList^[i] := nil;
end;
FCount := NewCount;
end;
end;
function TGLD3dsCameraList.GetCamera(Index: GLuint): TGLD3dsCamera;
begin
if (Index >= 1) and (Index <= FCount) then
Result := FList^[Index]
else Result := nil;
end;
procedure TGLD3dsCameraList.SetCamera(Index: GLuint; Camera: TGLD3dsCamera);
begin
if (Index < 1) or (Index > FCount + 1) then Exit;
if Index = FCount + 1 then Add(Camera) else
if Camera = nil then Delete(Index) else
FList^[Index].Assign(Camera);
end;
function TGLD3dsCameraList.GetLast: TGLD3dsCamera;
begin
if FCount > 0 then
Result := FList^[FCount]
else Result := nil;
end;
procedure TGLD3dsCameraList.SetLast(Camera: TGLD3dsCamera);
begin
if FCount > 0 then
SetCamera(FCount, Camera)
else Add(Camera);
end;
end.
|
unit uBillEditSaleReturnRequest;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Frm_BillEditBase, cxStyles, cxCustomData, cxGraphics, cxFilter,
cxData, cxDataStorage, cxEdit, DB, cxDBData, ADODB, Menus, DBClient,
ActnList, dxBar, cxClasses, ImgList, ExtCtrls, cxButtonEdit,
cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox,
cxLabel, cxCalendar, cxDBEdit, cxTextEdit, cxCheckBox, dxGDIPlusClasses,
cxContainer, cxMaskEdit, StdCtrls, Grids, DBGrids, cxGridLevel,
cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, cxPC, cxLookAndFeelPainters, cxGroupBox,
cxRadioGroup, cxSpinEdit;
type
TFM_BillEditSaleReturnRequest = class(TFM_BillEditBase)
cxDBCheckBox1: TcxDBCheckBox;
cxLabel3: TcxLabel;
cxcmbpriceType: TcxDBLookupComboBox;
cxcmblookupType: TcxDBLookupComboBox;
RGReturnType: TcxRadioGroup;
cxLabel2: TcxLabel;
cxLabel5: TcxLabel;
cxbtnSendWareNum: TcxButtonEdit;
cxbtnSendWareName: TcxDBTextEdit;
cdswarehouse: TClientDataSet;
dsPriceType: TDataSource;
cdsReturnType: TClientDataSet;
dsRetuenType: TDataSource;
cdsCustomer: TClientDataSet;
cdsMasterFID: TWideStringField;
cdsMasterFCREATORID: TWideStringField;
cdsMasterFCREATETIME: TDateTimeField;
cdsMasterFLASTUPDATEUSERID: TWideStringField;
cdsMasterFLASTUPDATETIME: TDateTimeField;
cdsMasterFCONTROLUNITID: TWideStringField;
cdsMasterFNUMBER: TWideStringField;
cdsMasterFBIZDATE: TDateTimeField;
cdsMasterFHANDLERID: TWideStringField;
cdsMasterFDESCRIPTION: TWideStringField;
cdsMasterFHASEFFECTED: TFloatField;
cdsMasterFAUDITORID: TWideStringField;
cdsMasterFSOURCEBILLID: TWideStringField;
cdsMasterFSOURCEFUNCTION: TWideStringField;
cdsMasterFAUDITTIME: TDateTimeField;
cdsMasterFBASESTATUS: TFloatField;
cdsMasterFBIZTYPEID: TWideStringField;
cdsMasterFSOURCEBILLTYPEID: TWideStringField;
cdsMasterFBILLTYPEID: TWideStringField;
cdsMasterFYEAR: TFloatField;
cdsMasterFPERIOD: TFloatField;
cdsMasterFORDERCUSTOMERID: TWideStringField;
cdsMasterFRETURNSCUSTOMERID: TWideStringField;
cdsMasterFINVOICECUSTOMERID: TWideStringField;
cdsMasterFSALEORGUNITID: TWideStringField;
cdsMasterFSALESYMBOL: TWideStringField;
cdsMasterFTOTALAMOUNT: TFloatField;
cdsMasterFTOTALTAX: TFloatField;
cdsMasterFTOTALTAXAMOUNT: TFloatField;
cdsMasterFRETURNSREASON: TFloatField;
cdsMasterFCURRENCYID: TWideStringField;
cdsMasterFEXCHANGERATE: TFloatField;
cdsMasterFSALEGROUPID: TWideStringField;
cdsMasterFSALEPERSONID: TWideStringField;
cdsMasterFMODIFIERID: TWideStringField;
cdsMasterFMODIFICATIONTIME: TDateTimeField;
cdsMasterFADMINORGUNITID: TWideStringField;
cdsMasterFCONVERTMODE: TFloatField;
cdsMasterFCOMPANYORGUNITID: TWideStringField;
cdsMasterFLOCALTOTALAMOUNT: TFloatField;
cdsMasterFLOCALTOTALTAX: TFloatField;
cdsMasterFLOCALTOTALTAXAMOUNT: TFloatField;
cdsMasterFISINTAX: TFloatField;
cdsMasterFISCENTRALBALANCE: TFloatField;
cdsMasterFSTORAGEORGUNITID: TWideStringField;
cdsMasterFWAREHOUSEID: TWideStringField;
cdsMasterFISSQUAREBALANCE: TFloatField;
cdsMasterFBALANCECOMPANYORGUNITID: TWideStringField;
cdsMasterFBALANCESALEORGUNITID: TWideStringField;
cdsMasterFBALANCESTORAGEORGUNITID: TWideStringField;
cdsMasterFBALANCEWAREHOUSEID: TWideStringField;
cdsMasterCFPRICETYPEID: TWideStringField;
cdsMasterCFSUBBILLTYPE: TWideStringField;
cdsMasterCFINPUTWAY: TWideStringField;
cdsMasterCFRETURNTYPEID: TWideStringField;
cdsMasterCFINSEASONBOUND: TFloatField;
cdsMasterCFSendWareName: TStringField;
cdsDetailFID: TWideStringField;
cdsDetailFSEQ: TFloatField;
cdsDetailFMATERIALID: TWideStringField;
cdsDetailFASSISTPROPERTYID: TWideStringField;
cdsDetailFUNITID: TWideStringField;
cdsDetailFSOURCEBILLNUMBER: TWideStringField;
cdsDetailFSOURCEBILLENTRYSEQ: TFloatField;
cdsDetailFASSCOEFFICIENT: TFloatField;
cdsDetailFBASESTATUS: TFloatField;
cdsDetailFASSOCIATEQTY: TFloatField;
cdsDetailFSOURCEBILLTYPEID: TWideStringField;
cdsDetailFBASEUNITID: TWideStringField;
cdsDetailFASSISTUNITID: TWideStringField;
cdsDetailFREMARK: TWideStringField;
cdsDetailFREASONCODEID: TWideStringField;
cdsDetailFPARENTID: TWideStringField;
cdsDetailFISPRESENT: TFloatField;
cdsDetailFLOT: TWideStringField;
cdsDetailFQTY: TFloatField;
cdsDetailFASSISTQTY: TFloatField;
cdsDetailFPRICE: TFloatField;
cdsDetailFTAXPRICE: TFloatField;
cdsDetailFAMOUNT: TFloatField;
cdsDetailFTAXRATE: TFloatField;
cdsDetailFTAX: TFloatField;
cdsDetailFTAXAMOUNT: TFloatField;
cdsDetailFRETURNSDATE: TDateTimeField;
cdsDetailFRETURNSQTY: TFloatField;
cdsDetailFREMAININGQTY: TFloatField;
cdsDetailFINVOICEDQTY: TFloatField;
cdsDetailFINVOICEPRICE: TFloatField;
cdsDetailFWAREHOUSEID: TWideStringField;
cdsDetailFSTORAGEORGUNITID: TWideStringField;
cdsDetailFCOMPANYORGUNITID: TWideStringField;
cdsDetailFLOCALAMOUNT: TFloatField;
cdsDetailFBASEQTY: TFloatField;
cdsDetailFRETURNSBASEQTY: TFloatField;
cdsDetailFREMAININGBASEQTY: TFloatField;
cdsDetailFINVOICEDBASEQTY: TFloatField;
cdsDetailFLOCALTAX: TFloatField;
cdsDetailFLOCALTAXAMOUNT: TFloatField;
cdsDetailFTOTALRETURNAMT: TFloatField;
cdsDetailFREASON: TWideStringField;
cdsDetailFTOTALINVOICEDAMT: TFloatField;
cdsDetailFPRODUCEDATE: TDateTimeField;
cdsDetailFMATURITYDATE: TDateTimeField;
cdsDetailFCOREBILLTYPEID: TWideStringField;
cdsDetailFCOREBILLID: TWideStringField;
cdsDetailFCOREBILLNUMBER: TWideStringField;
cdsDetailFCOREBILLENTRYID: TWideStringField;
cdsDetailFCOREBILLENTRYSEQ: TFloatField;
cdsDetailFRECEIVEDISPATCHERTYPE: TFloatField;
cdsDetailFDELIVERYCUSTOMERID: TWideStringField;
cdsDetailFPAYMENTCUSTOMERID: TWideStringField;
cdsDetailFRECEIVECUSTOMERID: TWideStringField;
cdsDetailFSOURCEBILLID: TWideStringField;
cdsDetailFSOURCEBILLENTRYID: TWideStringField;
cdsDetailFISBETWEENCOMPANYSEND: TFloatField;
cdsDetailFNETORDERBILLNUMBER: TWideStringField;
cdsDetailFNETORDERBILLID: TWideStringField;
cdsDetailFNETORDERBILLENTRYID: TWideStringField;
cdsDetailFCHEAPRATE: TFloatField;
cdsDetailFQUANTITYUNCTRL: TFloatField;
cdsDetailCFCUPID: TWideStringField;
cdsDetailCFMUTILSOURCEBILL: TWideStringField;
cdsDetailCFPACKID: TWideStringField;
cdsDetailCFSIZESID: TWideStringField;
cdsDetailCFCOLORID: TWideStringField;
cdsDetailCFPACKNUM: TFloatField;
cdsDetailCFSIZEGROUPID: TWideStringField;
cdsDetailCFSALEPRICE: TFloatField;
cdsDetailCFDISCOUNT: TFloatField;
cdsDetailCFACTUALPRICE: TFloatField;
cdsDetailCFACTUALTAXPRICE: TFloatField;
cdsDetailCFDISCOUNTAMOUNT: TFloatField;
cdsMasterCFCustName: TStringField;
cdsDetailAmountFBASEUNITID: TWideStringField;
cdsDetailAmountcfMaterialNumber: TStringField;
cdsDetailAmountcfMaterialName: TStringField;
cdsDetailAmountCFColorCode: TStringField;
cdsDetailAmountCFColorName: TStringField;
cdsDetailAmountCFCupName: TStringField;
cdsDetailAmountCFPackName: TStringField;
cdsDetailAmountCFPACKNUM: TFloatField;
cdsDetailAmountCFSIZEGROUPID: TWideStringField;
cdsDetailAmountCFCOLORID: TWideStringField;
cdsDetailAmountCFCUPID: TWideStringField;
cdsDetailAmountCFDPPRICE: TFloatField;
cdsDetailAmountFPRICE: TFloatField;
cdsDetailAmountCFDISCOUNT: TFloatField;
cdsDetailAmountCFACTUALPRICE: TFloatField;
cdsDetailAmountfAmount_1: TFloatField;
cdsDetailAmountfAmount_2: TFloatField;
cdsDetailAmountfAmount_3: TFloatField;
cdsDetailAmountfAmount_4: TFloatField;
cdsDetailAmountfAmount_5: TFloatField;
cdsDetailAmountfAmount_6: TFloatField;
cdsDetailAmountfAmount_7: TFloatField;
cdsDetailAmountfAmount_8: TFloatField;
cdsDetailAmountfAmount_9: TFloatField;
cdsDetailAmountfAmount_10: TFloatField;
cdsDetailAmountfAmount_11: TFloatField;
cdsDetailAmountfAmount_12: TFloatField;
cdsDetailAmountfAmount_13: TFloatField;
cdsDetailAmountfAmount_14: TFloatField;
cdsDetailAmountfAmount_15: TFloatField;
cdsDetailAmountfAmount_16: TFloatField;
cdsDetailAmountfAmount_17: TFloatField;
cdsDetailAmountfAmount_18: TFloatField;
cdsDetailAmountfAmount_19: TFloatField;
cdsDetailAmountfAmount_20: TFloatField;
cdsDetailAmountfAmount_21: TFloatField;
cdsDetailAmountfAmount_22: TFloatField;
cdsDetailAmountfAmount_23: TFloatField;
cdsDetailAmountfAmount_24: TFloatField;
cdsDetailAmountfAmount_25: TFloatField;
cdsDetailAmountfAmount_26: TFloatField;
cdsDetailAmountfAmount_27: TFloatField;
cdsDetailAmountfAmount_28: TFloatField;
cdsDetailAmountfAmount_29: TFloatField;
cdsDetailAmountfAmount_30: TFloatField;
cdsDetailAmountfAmount: TFloatField;
cdsDetailAmountfTotaLQty: TIntegerField;
cdsDetailAmountCFBrandName: TWideStringField;
cdsDetailAmountcfattributeName: TWideStringField;
cdsDetailAmountCFNUitName: TWideStringField;
cdsDetailAmountfremark: TWideStringField;
cdsDetailAmountCfbrandid: TWideStringField;
cdsDetailAmountCFPACKID: TStringField;
cdsDetailAmountcfattributeid: TWideStringField;
cdsDetailAmountFMATERIALID: TWideStringField;
dbgList2cfMaterialNumber: TcxGridDBColumn;
dbgList2cfMaterialName: TcxGridDBColumn;
dbgList2CFColorCode: TcxGridDBColumn;
dbgList2CFColorName: TcxGridDBColumn;
dbgList2CFCupName: TcxGridDBColumn;
dbgList2CFPackName: TcxGridDBColumn;
dbgList2CFPACKNUM: TcxGridDBColumn;
dbgList2CFDPPRICE: TcxGridDBColumn;
dbgList2FPRICE: TcxGridDBColumn;
dbgList2CFDISCOUNT: TcxGridDBColumn;
dbgList2CFACTUALPRICE: TcxGridDBColumn;
dbgList2fAmount_1: TcxGridDBColumn;
dbgList2fAmount_2: TcxGridDBColumn;
dbgList2fAmount_3: TcxGridDBColumn;
dbgList2fAmount_4: TcxGridDBColumn;
dbgList2fAmount_5: TcxGridDBColumn;
dbgList2fAmount_6: TcxGridDBColumn;
dbgList2fAmount_7: TcxGridDBColumn;
dbgList2fAmount_8: TcxGridDBColumn;
dbgList2fAmount_9: TcxGridDBColumn;
dbgList2fAmount_10: TcxGridDBColumn;
dbgList2fAmount_11: TcxGridDBColumn;
dbgList2fAmount_12: TcxGridDBColumn;
dbgList2fAmount_13: TcxGridDBColumn;
dbgList2fAmount_14: TcxGridDBColumn;
dbgList2fAmount_15: TcxGridDBColumn;
dbgList2fAmount_16: TcxGridDBColumn;
dbgList2fAmount_17: TcxGridDBColumn;
dbgList2fAmount_18: TcxGridDBColumn;
dbgList2fAmount_19: TcxGridDBColumn;
dbgList2fAmount_20: TcxGridDBColumn;
dbgList2fAmount_21: TcxGridDBColumn;
dbgList2fAmount_22: TcxGridDBColumn;
dbgList2fAmount_23: TcxGridDBColumn;
dbgList2fAmount_24: TcxGridDBColumn;
dbgList2fAmount_25: TcxGridDBColumn;
dbgList2fAmount_26: TcxGridDBColumn;
dbgList2fAmount_27: TcxGridDBColumn;
dbgList2fAmount_28: TcxGridDBColumn;
dbgList2fAmount_29: TcxGridDBColumn;
dbgList2fAmount_30: TcxGridDBColumn;
dbgList2fAmount: TcxGridDBColumn;
dbgList2fTotaLQty: TcxGridDBColumn;
dbgList2CFBrandName: TcxGridDBColumn;
dbgList2cfattributeName: TcxGridDBColumn;
dbgList2CFNUitName: TcxGridDBColumn;
dbgList2fremark: TcxGridDBColumn;
cdsDetailAmountCFACTUALTAXPRICE: TFloatField;
dbgList2CFACTUALTAXPRICE: TcxGridDBColumn;
cdsDetailTracyFID: TWideStringField;
cdsDetailTracyFSEQ: TFloatField;
cdsDetailTracyFMATERIALID: TWideStringField;
cdsDetailTracyFASSISTPROPERTYID: TWideStringField;
cdsDetailTracyFUNITID: TWideStringField;
cdsDetailTracyFSOURCEBILLNUMBER: TWideStringField;
cdsDetailTracyFSOURCEBILLENTRYSEQ: TFloatField;
cdsDetailTracyFASSCOEFFICIENT: TFloatField;
cdsDetailTracyFBASESTATUS: TFloatField;
cdsDetailTracyFASSOCIATEQTY: TFloatField;
cdsDetailTracyFSOURCEBILLTYPEID: TWideStringField;
cdsDetailTracyFBASEUNITID: TWideStringField;
cdsDetailTracyFASSISTUNITID: TWideStringField;
cdsDetailTracyFREMARK: TWideStringField;
cdsDetailTracyFREASONCODEID: TWideStringField;
cdsDetailTracyFPARENTID: TWideStringField;
cdsDetailTracyFISPRESENT: TFloatField;
cdsDetailTracyFLOT: TWideStringField;
cdsDetailTracyFQTY: TFloatField;
cdsDetailTracyFASSISTQTY: TFloatField;
cdsDetailTracyFPRICE: TFloatField;
cdsDetailTracyFTAXPRICE: TFloatField;
cdsDetailTracyFAMOUNT: TFloatField;
cdsDetailTracyFTAXRATE: TFloatField;
cdsDetailTracyFTAX: TFloatField;
cdsDetailTracyFTAXAMOUNT: TFloatField;
cdsDetailTracyFRETURNSDATE: TDateTimeField;
cdsDetailTracyFRETURNSQTY: TFloatField;
cdsDetailTracyFREMAININGQTY: TFloatField;
cdsDetailTracyFINVOICEDQTY: TFloatField;
cdsDetailTracyFINVOICEPRICE: TFloatField;
cdsDetailTracyFWAREHOUSEID: TWideStringField;
cdsDetailTracyFSTORAGEORGUNITID: TWideStringField;
cdsDetailTracyFCOMPANYORGUNITID: TWideStringField;
cdsDetailTracyFLOCALAMOUNT: TFloatField;
cdsDetailTracyFBASEQTY: TFloatField;
cdsDetailTracyFRETURNSBASEQTY: TFloatField;
cdsDetailTracyFREMAININGBASEQTY: TFloatField;
cdsDetailTracyFINVOICEDBASEQTY: TFloatField;
cdsDetailTracyFLOCALTAX: TFloatField;
cdsDetailTracyFLOCALTAXAMOUNT: TFloatField;
cdsDetailTracyFTOTALRETURNAMT: TFloatField;
cdsDetailTracyFREASON: TWideStringField;
cdsDetailTracyFTOTALINVOICEDAMT: TFloatField;
cdsDetailTracyFPRODUCEDATE: TDateTimeField;
cdsDetailTracyFMATURITYDATE: TDateTimeField;
cdsDetailTracyFCOREBILLTYPEID: TWideStringField;
cdsDetailTracyFCOREBILLID: TWideStringField;
cdsDetailTracyFCOREBILLNUMBER: TWideStringField;
cdsDetailTracyFCOREBILLENTRYID: TWideStringField;
cdsDetailTracyFCOREBILLENTRYSEQ: TFloatField;
cdsDetailTracyFRECEIVEDISPATCHERTYPE: TFloatField;
cdsDetailTracyFDELIVERYCUSTOMERID: TWideStringField;
cdsDetailTracyFPAYMENTCUSTOMERID: TWideStringField;
cdsDetailTracyFRECEIVECUSTOMERID: TWideStringField;
cdsDetailTracyFSOURCEBILLID: TWideStringField;
cdsDetailTracyFSOURCEBILLENTRYID: TWideStringField;
cdsDetailTracyFISBETWEENCOMPANYSEND: TFloatField;
cdsDetailTracyFNETORDERBILLNUMBER: TWideStringField;
cdsDetailTracyFNETORDERBILLID: TWideStringField;
cdsDetailTracyFNETORDERBILLENTRYID: TWideStringField;
cdsDetailTracyFCHEAPRATE: TFloatField;
cdsDetailTracyFQUANTITYUNCTRL: TFloatField;
cdsDetailTracyCFCUPID: TWideStringField;
cdsDetailTracyCFMUTILSOURCEBILL: TWideStringField;
cdsDetailTracyCFPACKID: TWideStringField;
cdsDetailTracyCFSIZESID: TWideStringField;
cdsDetailTracyCFCOLORID: TWideStringField;
cdsDetailTracyCFPACKNUM: TFloatField;
cdsDetailTracyCFSIZEGROUPID: TWideStringField;
cdsDetailTracyCFSALEPRICE: TFloatField;
cdsDetailTracyCFDISCOUNT: TFloatField;
cdsDetailTracyCFACTUALPRICE: TFloatField;
cdsDetailTracyCFACTUALTAXPRICE: TFloatField;
cdsDetailTracyCFDISCOUNTAMOUNT: TFloatField;
cdsDetailTracyStringField: TStringField;
cdsDetailTracyStringField2: TStringField;
cdsDetailTracyStringField3: TStringField;
cdsDetailTracyStringField4: TStringField;
cdsDetailTracyStringField5: TStringField;
cdsDetailTracyStringField6: TStringField;
cdsDetailTracyCFBrandName: TWideStringField;
cdsDetailTracycfattributeName: TWideStringField;
cdsDetailTracyCFNUitName: TWideStringField;
cdsDetailTracyCfbrandid: TWideStringField;
cdsDetailTracycfattributeid: TWideStringField;
cdsMasterFCreatorName: TStringField;
cdsMasterCFModifierName: TStringField;
cdsMasterFAuditorName: TStringField;
cxgridDetialFSEQ: TcxGridDBColumn;
cxgridDetialFREMARK: TcxGridDBColumn;
cxgridDetialFPRICE: TcxGridDBColumn;
cxgridDetialFAMOUNT: TcxGridDBColumn;
cxgridDetialFTAXRATE: TcxGridDBColumn;
cxgridDetialFTAX: TcxGridDBColumn;
cxgridDetialFTAXAMOUNT: TcxGridDBColumn;
cxgridDetialCFPACKNUM: TcxGridDBColumn;
cxgridDetialCFDISCOUNT: TcxGridDBColumn;
cxgridDetialCFACTUALPRICE: TcxGridDBColumn;
cxgridDetialCFACTUALTAXPRICE: TcxGridDBColumn;
cxgridDetialFQTY: TcxGridDBColumn;
cxgridDetialcfMaterialNumber: TcxGridDBColumn;
cxgridDetialcfMaterialName: TcxGridDBColumn;
cxgridDetialCFColorCode: TcxGridDBColumn;
cxgridDetialCFColorName: TcxGridDBColumn;
cxgridDetialCFCupName: TcxGridDBColumn;
cxgridDetialCFBrandName: TcxGridDBColumn;
cxgridDetialcfattributeName: TcxGridDBColumn;
cxgridDetialCFNUitName: TcxGridDBColumn;
cxgridDetialCFPackName: TcxGridDBColumn;
cxgridDetialCFDPPRICE: TcxGridDBColumn;
cdsDetailCFDPPRICE: TFloatField;
cdsDetailTracyCFDPPRICE: TFloatField;
cdsDetailAmountFTAXRATE: TFloatField;
cdsDetailAmountFTAX: TFloatField;
dbgList2FTAXRATE: TcxGridDBColumn;
dbgList2FTAX: TcxGridDBColumn;
cdsDetailAmountFtaxAmount: TFloatField;
cdsDetailTracyCFSizeCode: TWideStringField;
cdsDetailTracyCFSizeName: TWideStringField;
cxgridDetialCFSizeName: TcxGridDBColumn;
cxgridDetialCFSizeCode: TcxGridDBColumn;
procedure FormCreate(Sender: TObject);
procedure cdsDetailNewRecord(DataSet: TDataSet);
procedure cxdblookupInputwayPropertiesCloseUp(Sender: TObject);
procedure cxbtnNUmberPropertiesChange(Sender: TObject);
procedure cxbtnSendWareNumPropertiesChange(Sender: TObject);
procedure cdsDetailAmountCalcFields(DataSet: TDataSet);
procedure cdsMasterCalcFields(DataSet: TDataSet);
procedure FormShow(Sender: TObject);
procedure cxbtnNUmberPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure cdsMasterFWAREHOUSEIDChange(Sender: TField);
procedure cdsDetailAmountFTAXRATEChange(Sender: TField);
procedure cdsDetailAmountCFACTUALTAXPRICEChange(Sender: TField);
procedure cdsDetailAmountCFACTUALPRICEChange(Sender: TField);
procedure dbgList2Editing(Sender: TcxCustomGridTableView;
AItem: TcxCustomGridTableItem; var AAllow: Boolean);
procedure cxbtnSendWareNumPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure girdListDblClick(Sender: TObject);
procedure girdListKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure dbgList2cfMaterialNumberPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
procedure dbgList2CFColorCodePropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure dbgList2CFCupNamePropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure dbgList2CFPackNamePropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure cdsDetailBeforePost(DataSet: TDataSet);
procedure cdsDetailAmountCFPACKNUMChange(Sender: TField);
procedure cdsDetailAmountCFPACKIDChange(Sender: TField);
procedure cxPageDetailChange(Sender: TObject);
procedure cdsDetailAmountCFDISCOUNTChange(Sender: TField);
procedure cdsDetailAmountFMATERIALIDChange(Sender: TField);
procedure cxbtnNUmberKeyPress(Sender: TObject; var Key: Char);
procedure cxbtnSendWareNumKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
procedure calAmt(DataSet: TDataSet);override;//计算金额
public
{ Public declarations }
procedure Open_Bill(KeyFields: String; KeyValues: String); override;
//保存单据
function ST_Save : Boolean; override;
end;
var
FM_BillEditSaleReturnRequest: TFM_BillEditSaleReturnRequest;
implementation
uses FrmCliDM,Pub_Fun,uDrpHelperClase,uMaterDataSelectHelper;
{$R *.dfm}
procedure TFM_BillEditSaleReturnRequest.Open_Bill(KeyFields: String; KeyValues: String);
var OpenTables: array[0..1] of string;
_cds: array[0..1] of TClientDataSet;
ErrMsg : string;
strsql : string;
begin
if Trim(KeyValues)='' then
strsql := ' select * from T_SD_SALERETURNS where 1<>1 '
else
strsql := ' select * from T_SD_SALERETURNS where FID='+quotedstr(KeyValues);
OpenTables[0] := strsql;
if Trim(KeyValues)='' then
strsql := ' select * from T_SD_SALERETURNSENTRY where 1<>1 '
else
strsql := ' select * from T_SD_SALERETURNSENTRY where FparentID='+quotedstr(KeyValues);
OpenTables[1] := strsql;
_cds[0] := cdsMaster;
_cds[1] := cdsDetail;
try
if not CliDM.Get_OpenClients_E(KeyValues,_cds,OpenTables,ErrMsg) then
begin
ShowError(Handle, ErrMsg,[]);
Abort;
end;
except
on E : Exception do
begin
ShowError(Handle, Self.Bill_Sign+'打开编辑数据报错:'+E.Message,[]);
Abort;
end;
end;
//新单初始化赋值
if KeyValues='' then
begin
try
with cdsMaster do
begin
Append;
FieldByName('FID').AsString := CliDM.GetEASSID('546F192F');
FieldByName('FCREATETIME').AsDateTime := CliDM.Get_ServerTime;
FieldByName('FNUMBER').AsString := CliDM.GetSCMBillNum(sBillTypeID,UserInfo.Branch_Flag,sBillFlag,true,ErrMsg);
FieldByName('FBIZDATE').AsDateTime := CliDM.Get_ServerTime;
FieldByName('FCREATORID').AsString := UserInfo.LoginUser_FID;
FieldByName('FBASESTATUS').AsInteger := 1; //保存状态
FieldByName('FLASTUPDATEUSERID').AsString := UserInfo.LoginUser_FID;
FieldByName('FLASTUPDATETIME').AsDateTime := CliDM.Get_ServerTime;
FieldByName('FMODIFIERID').AsString := UserInfo.LoginUser_FID;
FieldByName('FMODIFICATIONTIME').AsDateTime := CliDM.Get_ServerTime;
FieldByName('FCONTROLUNITID').AsString := UserInfo.FCONTROLUNITID; //控制单元,从服务器获取
FieldByName('FBILLTYPEID').AsString := sBillTypeID; ///单据类型
FieldByName('FBIZTYPEID').AsString := 'd8e80652-0110-1000-e000-04c5c0a812202407435C';
FieldByName('FStorageOrgUnitID').AsString := UserInfo.Branch_ID; //库存组织
FieldByName('FCOMPANYORGUNITID').AsString := UserInfo.Branch_ID;
FieldByName('FSALEORGUNITID').AsString := UserInfo.Branch_ID;
FieldByName('FCURRENCYID').AsString := BillConst.FCurrency; //币别
FieldByName('FExchangeRate').AsFloat := 1;
FieldByName('CFINPUTWAY').AsString := 'NOTPACK';
FieldByName('FISINTAX').AsFloat := 0;
end;
except
on E : Exception do
begin
ShowError(Handle,ErrMsg+E.Message,[]);
end;
end;
end ;
inherited;
//FInWarehouseFID := cdsMaster.fieldbyname('CFINWAREHOUSEID').AsString;
FOutWarehouseFID := cdsMaster.fieldbyname('FWAREHOUSEID').AsString;
end;
function TFM_BillEditSaleReturnRequest.ST_Save : Boolean;
var ErrMsg : string;
_cds: array[0..1] of TClientDataSet;
AmountSum : Integer;
begin
Result := True;
if cdsDetailAmount.State in DB.dsEditModes then
cdsDetailAmount.Post;
AmountSum := 0;
try
cdsDetailAmount.DisableControls;
cdsDetailAmount.First;
while not cdsDetailAmount.Eof do
begin
AmountSum := AmountSum + cdsDetailAmount.fieldByName('fTotaLQty').AsInteger;
cdsDetailAmount.Next();
end;
if AmountSum =0 then
begin
ShowError(Handle, '单据分录数量为0,不允许保存!',[]);
abort;
end;
finally
cdsDetailAmount.EnableControls;
end;
//横排转竖排
try
AmountToDetail_DataSet(CliDM.conClient,cdsDetailAmount,cdsDetail);
except
on e : Exception do
begin
ShowError(Handle, '【'+BillNumber+'】保存时横排转竖排出错:'+e.Message,[]);
Result := False;
abort;
end;
end;
if cdsMaster.State in db.dsEditModes then
cdsMaster.Post;
if cdsDetail.State in db.dsEditModes then
cdsDetail.Post;
//定义提交的数据集数据
_cds[0] := cdsMaster;
_cds[1] := cdsDetail;
//提交数据
try
if CliDM.Apply_Delta_Ex(_cds,['T_SD_SALERETURNS','T_SD_SALERETURNSENTRY'],ErrMsg) then
begin
Gio.AddShow(Self.Caption+'【'+BillNumber+'】提交成功!');
end
else
begin
ShowMsg(Handle, Self.Caption+'提交失败'+ErrMsg,[]);
Gio.AddShow(ErrMsg);
Result := False;
end;
except
on E: Exception do
begin
ShowMsg(Handle, Self.Caption+'提交失败:'+e.Message,[]);
Result := False;
Abort;
end;
end;
end;
procedure TFM_BillEditSaleReturnRequest.FormCreate(Sender: TObject);
var
strsql,strError : string ;
begin
sBillTypeID := BillConst.BILLTYPE_SA; //单据类型FID
inherited;
strsql := 'select FID,fnumber,fname_l2 from t_Bd_Returntype';
Clidm.Get_OpenSQL(cdsReturnType,strsql,strError);
sKeyFields := 'FmaterialID;CFColorID;CFCupID;CFpackID';
Self.Bill_Sign := 'T_SD_SALERETURNS';
Self.BillEntryTable := 'T_SD_SALERETURNSENTRY';
cdsCustomer.Data := CliDM.cdsCust.Data;
cdswarehouse.Data := CliDM.cdsWarehouse.Data;
end;
procedure TFM_BillEditSaleReturnRequest.cdsDetailNewRecord(
DataSet: TDataSet);
begin
inherited;
DataSet.FieldByName('FID').AsString := CliDM.GetEASSID('164C6483');
DataSet.FieldByName('FWAREHOUSEID').AsString := cdsMaster.fieldbyname('FWAREHOUSEID').AsString;
DataSet.FieldByName('FSTORAGEORGUNITID').AsString := UserInfo.Branch_ID;
DataSet.FieldByName('FCOMPANYORGUNITID').AsString := UserInfo.Branch_ID;
DataSet.FieldByName('FparentID').AsString := cdsMaster.fieldbyname('FID').AsString;
end;
procedure TFM_BillEditSaleReturnRequest.cxdblookupInputwayPropertiesCloseUp(
Sender: TObject);
begin
inherited;
//
end;
procedure TFM_BillEditSaleReturnRequest.cxbtnNUmberPropertiesChange(
Sender: TObject);
begin
inherited;
girdList.hint :='Freturnscustomerid';
HeadAutoSelIDchange(cdsCustomer,'');
end;
procedure TFM_BillEditSaleReturnRequest.cxbtnSendWareNumPropertiesChange(
Sender: TObject);
begin
inherited;
girdList.hint :='FWAREHOUSEID';
HeadAutoSelIDchange(cdswarehouse,'');
end;
procedure TFM_BillEditSaleReturnRequest.cdsDetailAmountCalcFields(
DataSet: TDataSet);
begin
if DataSet.FindField('fTotaLQty')<> nil then
DataSet.FieldByName('fTotaLQty').AsInteger :=
DataSet.FieldByName('fAmount_1').AsInteger +
DataSet.FieldByName('fAmount_2').AsInteger +
DataSet.FieldByName('fAmount_3').AsInteger +
DataSet.FieldByName('fAmount_4').AsInteger +
DataSet.FieldByName('fAmount_5').AsInteger +
DataSet.FieldByName('fAmount_6').AsInteger +
DataSet.FieldByName('fAmount_7').AsInteger +
DataSet.FieldByName('fAmount_8').AsInteger +
DataSet.FieldByName('fAmount_9').AsInteger +
DataSet.FieldByName('fAmount_10').AsInteger+
DataSet.FieldByName('fAmount_11').AsInteger+
DataSet.FieldByName('fAmount_12').AsInteger+
DataSet.FieldByName('fAmount_13').AsInteger+
DataSet.FieldByName('fAmount_14').AsInteger+
DataSet.FieldByName('fAmount_15').AsInteger+
DataSet.FieldByName('fAmount_16').AsInteger+
DataSet.FieldByName('fAmount_17').AsInteger+
DataSet.FieldByName('fAmount_18').AsInteger+
DataSet.FieldByName('fAmount_19').AsInteger+
DataSet.FieldByName('fAmount_20').AsInteger+
DataSet.FieldByName('fAmount_21').AsInteger+
DataSet.FieldByName('fAmount_22').AsInteger+
DataSet.FieldByName('fAmount_23').AsInteger+
DataSet.FieldByName('fAmount_24').AsInteger+
DataSet.FieldByName('fAmount_25').AsInteger+
DataSet.FieldByName('fAmount_26').AsInteger+
DataSet.FieldByName('fAmount_27').AsInteger+
DataSet.FieldByName('fAmount_28').AsInteger+
DataSet.FieldByName('fAmount_29').AsInteger+
DataSet.FieldByName('fAmount_30').AsInteger;
if DataSet.FindField('fAmount')<> nil then
DataSet.FieldByName('fAmount').AsFloat := CliDM.SimpleRoundTo(DataSet.FieldByName('CFACTUALPRICE').AsFloat* DataSet.FieldByName('fTotaLQty').AsFloat);
DataSet.FieldByName('FtaxAmount').AsFloat := DataSet.fieldbyname('fTotaLQty').AsFloat*DataSet.fieldbyname('CFACTUALTAXPRICE').AsFloat;
DataSet.FieldByName('Ftax').AsFloat := DataSet.FieldByName('FtaxAmount').AsFloat-dataset.fieldbyname('FAmount').AsFloat;
end;
procedure TFM_BillEditSaleReturnRequest.cdsMasterCalcFields(
DataSet: TDataSet);
var
event : TNotifyEvent;
begin
inherited;
try
if tmpbtnEdit <> nil then
begin
event := tmpbtnEdit.Properties.OnChange ;
tmpbtnEdit.Properties.OnChange := nil ;
end;
if DataSet.FindField('CFCustName')<> nil then
begin
if FindRecord1(CliDM.cdsCust,'FID',DataSet.fieldbyname('Freturnscustomerid').AsString,1) then
begin
cxbtnNUmber.Text := CliDM.cdsCust.fieldbyname('fnumber').AsString;
DataSet.FindField('CFCustName').AsString := CliDM.cdsCust.fieldbyname('fname_l2').AsString;
end;
end;
if DataSet.FindField('CFSendWareName')<> nil then
begin
if FindRecord1(CliDM.cdsWarehouse,'FID',DataSet.fieldbyname('FWAREHOUSEID').AsString,1) then
begin
cxbtnSendWareNum.Text := CliDM.cdsWarehouse.fieldbyname('fnumber').AsString;
DataSet.FindField('CFSendWareName').AsString := CliDM.cdsWarehouse.fieldbyname('fname_l2').AsString;
end;
end;
finally
if tmpbtnEdit<> nil then
tmpbtnEdit.Properties.OnChange := event;
end;
end;
procedure TFM_BillEditSaleReturnRequest.FormShow(Sender: TObject);
begin
inherited;
sIniBillFlag :='SA';
sSPPack := 'SALE';
end;
procedure TFM_BillEditSaleReturnRequest.cxbtnNUmberPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
ChangEvent : TNotifyEvent;
begin
inherited;
if not cdsMaster.Active then Exit;
try
ChangEvent := cxbtnNUmber.Properties.OnChange;
cxbtnNUmber.Properties.OnChange := nil;
with Select_Customer('','','',1) do
begin
if not IsEmpty then
begin
if not (cdsMaster.State in DB.dsEditModes) then cdsMaster.Edit;
cdsMaster.FieldByName('Freturnscustomerid').AsString := fieldbyname('fid').AsString;
end;
end;
finally
cxbtnNUmber.Properties.OnChange := ChangEvent;
end;
end;
procedure TFM_BillEditSaleReturnRequest.cdsMasterFWAREHOUSEIDChange(
Sender: TField);
begin
inherited;
FOutWarehouseFID := Sender.AsString;
end;
procedure TFM_BillEditSaleReturnRequest.cdsDetailAmountFTAXRATEChange(
Sender: TField);
var
Event,EventRate : TFieldNotifyEvent;
begin
inherited;
try
Event := sender.DataSet.FieldByName('CFACTUALPRICE').OnChange;
sender.DataSet.FieldByName('CFACTUALPRICE').OnChange := nil;
EventRate :=Sender.DataSet.FieldByName('CFDISCOUNT').OnChange;
Sender.DataSet.FieldByName('CFDISCOUNT').OnChange := nil;
sender.DataSet.FieldByName('CFACTUALPRICE').AsFloat := CliDM.SimpleRoundTo(Sender.DataSet.Fieldbyname('CFActualTaxPrice').AsFloat/(1+Sender.AsFloat/100));
if sender.DataSet.fieldbyname('FPRICE').AsFloat<>0 then
Sender.DataSet.FieldByName('CFDISCOUNT').AsFloat := CliDM.SimpleRoundTo(sender.DataSet.FieldByName('CFACTUALPRICE').AsFloat/sender.DataSet.fieldbyname('FPRICE').AsFloat*100);
finally
sender.DataSet.FieldByName('CFACTUALPRICE').OnChange := Event;
Sender.DataSet.FieldByName('CFDISCOUNT').OnChange := EventRate;
end;
end;
procedure TFM_BillEditSaleReturnRequest.cdsDetailAmountCFACTUALTAXPRICEChange(
Sender: TField);
var
Event,EventRate : TFieldNotifyEvent;
begin
inherited;
try
Event := sender.DataSet.FieldByName('CFACTUALPRICE').OnChange;
sender.DataSet.FieldByName('CFACTUALPRICE').OnChange := nil;
EventRate := Sender.DataSet.FieldByName('CFDISCOUNT').OnChange ;
Sender.DataSet.FieldByName('CFDISCOUNT').OnChange := nil;
if Sender.DataSet.Fieldbyname('FTaxRate').AsFloat<>0 then
sender.DataSet.FieldByName('CFACTUALPRICE').AsFloat :=CliDM.SimpleRoundTo( Sender.AsFloat/(1+ Sender.DataSet.Fieldbyname('FTaxRate').AsFloat/100))
else
sender.DataSet.FieldByName('CFACTUALPRICE').AsFloat := Sender.AsFloat;
if sender.DataSet.fieldbyname('FPRICE').AsFloat<>0 then
Sender.DataSet.FieldByName('CFDISCOUNT').AsFloat :=CliDM.SimpleRoundTo( sender.DataSet.FieldByName('CFACTUALPRICE').AsFloat/sender.DataSet.fieldbyname('FPRICE').AsFloat*100);
finally
sender.DataSet.FieldByName('CFACTUALPRICE').OnChange := Event;
Sender.DataSet.FieldByName('CFDISCOUNT').OnChange := EventRate;
end;
end;
procedure TFM_BillEditSaleReturnRequest.cdsDetailAmountCFACTUALPRICEChange(
Sender: TField);
var
Event : TFieldNotifyEvent;
begin
inherited;
try
Event := Sender.DataSet.FieldByName('CFActualTaxPrice').OnChange ;
Sender.DataSet.FieldByName('CFActualTaxPrice').OnChange := nil;
if sender.DataSet.fieldbyname('FPRICE').AsFloat<>0 then
Sender.DataSet.FieldByName('CFDISCOUNT').AsFloat := CliDM.SimpleRoundTo(sender.DataSet.FieldByName('CFACTUALPRICE').AsFloat/sender.DataSet.fieldbyname('FPRICE').AsFloat*100);
if cdsMaster.FieldByName('FISINTAX').AsInteger =0 then
Sender.DataSet.FieldByName('CFActualTaxPrice').AsFloat := Sender.AsFloat ;
finally
Sender.DataSet.FieldByName('CFActualTaxPrice').OnChange := Event;
end;
end;
procedure TFM_BillEditSaleReturnRequest.dbgList2Editing(
Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem;
var AAllow: Boolean);
begin
inherited;
if cdsMaster.FieldByName('FISINTAX').AsInteger=1 then
begin
if (UpperCase(FocuField)=UpperCase('CFActualTaxPrice')) or (UpperCase(FocuField)=UpperCase('FTaxRate')) then
AAllow :=True ;
if FocuField='CFACTUALPRICE' then
AAllow := False;
end
else
begin
if (UpperCase(FocuField)=UpperCase('CFActualTaxPrice')) or (UpperCase(FocuField)=UpperCase('FTaxRate')) then
AAllow :=False;
if FocuField='CFACTUALPRICE' then
AAllow := True;
end;
end;
procedure TFM_BillEditSaleReturnRequest.cxbtnSendWareNumPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
ChangEvent : TNotifyEvent;
begin
inherited;
if not cdsMaster.Active then Exit;
try
ChangEvent := TcxButtonEdit(Sender).Properties.OnChange;
TcxButtonEdit(Sender).Properties.OnChange := nil;
with Select_Warehouse('','',1) do
begin
if not IsEmpty then
begin
if not (cdsMaster.State in DB.dsEditModes) then cdsMaster.Edit;
cdsMaster.FieldByName('FWAREHOUSEID').AsString := fieldbyname('fid').AsString;
end;
end;
finally
TcxButtonEdit(Sender).Properties.OnChange := ChangEvent;
end;
end;
procedure TFM_BillEditSaleReturnRequest.girdListDblClick(Sender: TObject);
begin
inherited;
if tmpbtnEdit <> nil then
if tmpbtnEdit.Name='cxbtnSendWareNum' then
fHasLocation := dsHeadSel.DataSet.FieldByName('fhaslocation').AsInteger;
end;
procedure TFM_BillEditSaleReturnRequest.girdListKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if tmpbtnEdit <> nil then
if tmpbtnEdit.Name='cxbtnSendWareNum' then
fHasLocation := dsHeadSel.DataSet.FieldByName('fhaslocation').AsInteger;
end;
procedure TFM_BillEditSaleReturnRequest.dbgList2cfMaterialNumberPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
inherited;
FindMaterial;
end;
procedure TFM_BillEditSaleReturnRequest.dbgList2CFColorCodePropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
inherited;
FindColor;
end;
procedure TFM_BillEditSaleReturnRequest.dbgList2CFCupNamePropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
inherited;
FindCup;
end;
procedure TFM_BillEditSaleReturnRequest.dbgList2CFPackNamePropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
inherited;
FindPack;
end;
procedure TFM_BillEditSaleReturnRequest.cdsDetailBeforePost(
DataSet: TDataSet);
begin
inherited;
DataSet.FieldByName('FWAREHOUSEID').AsString := cdsMaster.fieldbyname('FWAREHOUSEID').AsString;
end;
procedure TFM_BillEditSaleReturnRequest.calAmt(DataSet: TDataSet);
begin
DataSet.FieldByName('FAmount').AsFloat := CliDM.SimpleRoundTo(DataSet.fieldbyname('fqty').AsFloat*DataSet.FieldByName('CFACTUALPRICE').AsFloat); //金额
DataSet.FieldByName('FTaxAmount').AsFloat := CliDM.SimpleRoundTo(DataSet.fieldbyname('fqty').AsFloat*DataSet.FieldByName('CFACTUALTAXPRICE').AsFloat); //价税合计
DataSet.FieldByName('FTax').AsFloat := CliDM.SimpleRoundTo(DataSet.fieldbyname('fqty').AsFloat*(DataSet.FieldByName('CFACTUALTAXPRICE').AsFloat-DataSet.FieldByName('CFACTUALPRICE').AsFloat)); //税额
DataSet.FieldByName('FLocalAmount').AsFloat := DataSet.FieldByName('FAmount').AsFloat;
DataSet.FieldByName('FLocalTax').AsFloat := DataSet.FieldByName('FTax').AsFloat;
DataSet.FieldByName('FLocalTaxAmount').AsFloat := DataSet.FieldByName('FTaxAmount').AsFloat;
Dataset.FieldByName('FTaxprice').AsFloat := DataSet.FieldByName('CFACTUALTAXPRICE').AsFloat;
end;
procedure TFM_BillEditSaleReturnRequest.cdsDetailAmountCFPACKNUMChange(
Sender: TField);
begin
inherited;
if cdsDetailAmount.FieldByName('CFPackNum').AsInteger>0 then
PackNumChang(cdsDetailAmount,cdsDetailAmount.FieldByName('CFSIZEGROUPID').AsString,cdsDetailAmount.fieldbyname('CFPackID').AsString);
end;
procedure TFM_BillEditSaleReturnRequest.cdsDetailAmountCFPACKIDChange(
Sender: TField);
begin
inherited;
if cdsDetailAmount.FieldByName('CFPackNum').AsInteger>0 then
PackNumChang(cdsDetailAmount,cdsDetailAmount.FieldByName('CFSIZEGROUPID').AsString,cdsDetailAmount.fieldbyname('CFPackID').AsString);
end;
procedure TFM_BillEditSaleReturnRequest.cxPageDetailChange(
Sender: TObject);
begin
inherited;
if cxPageDetail.ActivePage=cxTabTractDetail then
begin
OpenTracyDetail('');
end;
end;
procedure TFM_BillEditSaleReturnRequest.cdsDetailAmountCFDISCOUNTChange(
Sender: TField);
var
Event,EventRate : TFieldNotifyEvent;
begin
inherited;
try
Event := Sender.DataSet.FieldByName('CFACTUALPRICE').OnChange ;
EventRate := Sender.DataSet.FieldByName('CFActualTaxPrice').OnChange ;
Sender.DataSet.FieldByName('CFACTUALPRICE').OnChange := nil;
Sender.DataSet.FieldByName('CFActualTaxPrice').OnChange := nil;
if sender.DataSet.fieldbyname('FPRICE').AsFloat<>0 then
Sender.DataSet.FieldByName('CFACTUALPRICE').AsFloat := CliDM.SimpleRoundTo(sender.DataSet.FieldByName('CFDISCOUNT').AsFloat*sender.DataSet.fieldbyname('FPRICE').AsFloat/100);
if cdsMaster.FieldByName('FISINTAX').AsInteger =0 then
Sender.DataSet.FieldByName('CFActualTaxPrice').AsFloat :=CliDM.SimpleRoundTo( Sender.DataSet.FieldByName('CFACTUALPRICE').AsFloat*(1+cdsDetailAmount.FieldByName('ftaxRate').AsFloat/100)) ;
finally
Sender.DataSet.FieldByName('CFACTUALPRICE').OnChange := Event;
Sender.DataSet.FieldByName('CFActualTaxPrice').OnChange := EventRate;
end;
end;
procedure TFM_BillEditSaleReturnRequest.cdsDetailAmountFMATERIALIDChange(
Sender: TField);
begin
inherited;
Get_PolicyPrice('CFDISCOUNT','CFACTUALPRICE',cdsMaster.fieldbyname('FSALEORGUNITID').AsString
,cdsMaster.fieldbyname('CFPRICETYPEID').AsString,cdsMaster.fieldbyname('Freturnscustomerid').AsString,cdsDetailAmount.fieldbyname('FMATERIALID').AsString,
cdsMaster.fieldbyname('FBIZDATE').AsDateTime);
end;
procedure TFM_BillEditSaleReturnRequest.cxbtnNUmberKeyPress(
Sender: TObject; var Key: Char);
begin
inherited;
DelBtnEditValue(Key,'FORDERCUSTOMERID');
end;
procedure TFM_BillEditSaleReturnRequest.cxbtnSendWareNumKeyPress(
Sender: TObject; var Key: Char);
begin
inherited;
DelBtnEditValue(Key,'FWAREHOUSEID');
end;
end.
|
unit frmGroupComposition;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Mask, Vcl.ComCtrls, dbfunc, uKernel,
Winapi.ActiveX, ComObj, Vcl.OleServer;
type
TfGroupComposition = class(TForm)
Panel1: TPanel;
Label3: TLabel;
Label1: TLabel;
cmbPedagogue: TComboBox;
cmbAcademicYear: TComboBox;
DateTimePicker1: TDateTimePicker;
Label4: TLabel;
lvGroups: TListView;
lvGroupMembers: TListView;
bExportOneGroup: TButton;
bExportAllGroup: TButton;
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure cmbPedagogueChange(Sender: TObject);
procedure lvGroupsSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure bExportOneGroupClick(Sender: TObject);
procedure bExportAllGroupClick(Sender: TObject);
private
AcademicYear: TResultTable;
PedagogueSurnameNP: TResultTable;
GroupNames: TResultTable;
GroupMembers: TResultTable;
FIDPedagogue: integer;
FIDAcademicYear: integer;
IDLearningGroup: integer;
StrGroupName: string;
procedure SetIDPedagogue(const Value: integer);
procedure SetIDAcademicYear(const Value: integer);
function CheckExcelInstalled(AValue: String): Boolean;
function CheckExcelRun(AValue: String; var ADest: Variant): Boolean;
procedure ShowGroups;
procedure ShowGroupMember;
public
property IDPedagogue: integer read FIDPedagogue write SetIDPedagogue;
property IDAcademicYear: integer read FIDAcademicYear
write SetIDAcademicYear;
end;
var
fGroupComposition: TfGroupComposition;
implementation
{$R *.dfm}
{ TfGroupComposition }
procedure TfGroupComposition.bExportAllGroupClick(Sender: TObject);
var
ExcelFileName, PedSurname, CurAcademicYear, sline: string;
ExcelApp, Sheet, WorkBook: Variant;
i, ii: integer;
begin
Memo1.Clear;
if not CheckExcelInstalled('Excel.Application') then
Application.MessageBox(PChar('Необходимо установить Microsoft Excel.'),
'Ошибка', MB_ICONERROR);
try
if not CheckExcelRun('Excel.Application', ExcelApp) then
ExcelApp := CreateOleObject('Excel.Application');
ExcelApp.Visible := false;
ExcelApp.Application.EnableEvents := false;
ExcelApp.SheetsInNewWorkbook := 1;
WorkBook := ExcelApp.Workbooks.Add;
Sheet := ExcelApp.Workbooks[1].WorkSheets[1];
PedSurname := ' ' + PedagogueSurnameNP[cmbPedagogue.ItemIndex]
.ValueStrByName('SURNAMENP');
CurAcademicYear := AcademicYear[cmbAcademicYear.ItemIndex]
.ValueStrByName('NAME');
// Колонтитулы
Sheet.PageSetup.CenterHeader :=
'&14ДХС "Надежда" Педагог: &B ' +
PedSurname + #13 + '&BКомплектование на &B' + CurAcademicYear +
'&B учебный год ';
// Sheet.PageSetup.CenterFooter :=
// '&10Дата формирования отчета о комплектовании групп: &14 &B' +
// DateToStr(DateTimePicker1.Date) + '&B _____________ Подпись';
// Нумерация страниц: никак НЕ РАБОТАЕТ!
// Sheet.PageSetup.CenterFooter := 'Стр. &С из &К';
Sheet.PageSetup.CenterFooter := '&[Страница]';
// отображение листа в виде "разметка страницы"
ExcelApp.ActiveWindow.View := 3;
// Отступы
Sheet.PageSetup.TopMargin := 70;
ExcelApp.Workbooks[1].WorkSheets[1].Columns[1].ColumnWidth := 4;
ExcelApp.Workbooks[1].WorkSheets[1].Columns[2].ColumnWidth := 25;
ExcelApp.Workbooks[1].WorkSheets[1].Columns[3].ColumnWidth := 16;
ExcelApp.Workbooks[1].WorkSheets[1].Columns[4].ColumnWidth := 16;
// для примеру:
ExcelApp.Workbooks[1].WorkSheets[1].Cells[1, 1] := 'По группам / учащимся';
for ii := 0 to GroupNames.Count - 1 do
begin
StrGroupName := GroupNames[ii].ValueStrByName('L_G_NAME');
IDLearningGroup := GroupNames[ii].ValueByName('ID_OUT');
Memo1.Lines.Add('');
sline := StrGroupName; // Название группы
Memo1.Lines.Add(sline);
sline := '№' + #9 + 'Фамилия, имя учащегося' + #9 + 'Дата зачисления' + #9
+ 'Дата отчисления';
Memo1.Lines.Add(sline);
if Assigned(GroupMembers) then
FreeAndNil(GroupMembers);
GroupMembers := Kernel.GetChildListForGroupMember(0, IDLearningGroup, 0);
for i := 0 to GroupMembers.Count - 1 do
begin
sline := '';
sline := IntToStr(i + 1) + #9 + GroupMembers[i].ValueStrByName
('SURNAME_NAME') + #9 + GroupMembers[i].ValueStrByName('DATE_IN') + #9
+ GroupMembers[i].ValueStrByName('DATE_OUT');
Memo1.Lines.Add(sline);
end;
end;
Memo1.SelectAll;
Memo1.CopyToClipboard;
ExcelApp.Workbooks[1].WorkSheets[1].Paste;
// формирую имя будущего файла
Delete(PedSurname, Length(PedSurname) - 4, 5);
ExcelFileName := CurAcademicYear + PedSurname + ' - Комплектование от ' +
FormatDateTime('dd mm', DateTimePicker1.Date);
WorkBook.SaveAs(ExtractFilePath(ParamStr(0)) + ExcelFileName);
// ExcelApp.WorkBooks[1].WorkSheets[1].range['A2:F9'].Select;
ExcelApp.Visible := true;
finally
end;
end;
procedure TfGroupComposition.bExportOneGroupClick(Sender: TObject);
var
ExcelFileName, PedSurname, CurAcademicYear, sline: string;
ExcelApp, Sheet, WorkBook: Variant;
// Memo: TMemo;
i: integer;
begin
Memo1.Clear;
if not CheckExcelInstalled('Excel.Application') then
Application.MessageBox(PChar('Необходимо установить Microsoft Excel.'),
'Ошибка', MB_ICONERROR);
try
if not CheckExcelRun('Excel.Application', ExcelApp) then
ExcelApp := CreateOleObject('Excel.Application');
ExcelApp.Visible := false;
ExcelApp.Application.EnableEvents := false;
ExcelApp.SheetsInNewWorkbook := 1;
WorkBook := ExcelApp.Workbooks.Add;
Sheet := ExcelApp.Workbooks[1].WorkSheets[1];
// ExcelApp.Workbooks[1].WorkSheets[1].Name := 'bh';
PedSurname := ' ' + PedagogueSurnameNP[cmbPedagogue.ItemIndex]
.ValueStrByName('SURNAMENP');
CurAcademicYear := AcademicYear[cmbAcademicYear.ItemIndex]
.ValueStrByName('NAME');
// Колонтитулы
Sheet.PageSetup.CenterHeader :=
'&14ДХС "Надежда" Педагог: &B ' +
PedSurname + #13 + '&BКомплектование на &B' + CurAcademicYear +
'&B учебный год ';
// Sheet.PageSetup.CenterFooter :=
// '&10Дата формирования отчета о комплектовании групп: &14 &B' +
// DateToStr(DateTimePicker1.Date) + '&B _____________ Подпись';
// Нумерация страниц: никак НЕ РАБОТАЕТ!
// Sheet.PageSetup.CenterFooter := 'Стр. &С из &К';
Sheet.PageSetup.CenterFooter := '&[Страница]';
// отображение листа в виде "разметка страницы"
// обещанные ни xlPageLayoutView ни xlPageBreakPreview не работают
// константу '3' выудила поредством записи макроса в Excel'е
ExcelApp.ActiveWindow.View := 3;
// Отступы
Sheet.PageSetup.TopMargin := 70;
ExcelApp.Workbooks[1].WorkSheets[1].Cells[1, 1] := 'По группам / учащимся';
// mem := TMemo.Create(Self) ;
// mem := TMemo.Create(loginform) ;
// mem.Visible := false;
// mem.Parent := loginform;
// mem.Clear; // видимо родитель был чем-то забит
// mem.lines.Add('');
Memo1.Lines.Add('');
sline := ' &14 &B' + StrGroupName + '&B'; // Название группы
sline := 'большой шрифт &14 &B' + StrGroupName + '&B большой шрифт';
Memo1.Lines.Add(sline);
sline := '№' + #9 + 'Фамилия, имя учащегося' + #9 + 'Дата зачисления' + #9 +
'Дата отчисления';
// Memo1.Lines.Add('');
Memo1.Lines.Add(sline);
for i := 0 to GroupMembers.Count - 1 do
begin
sline := '';
sline := IntToStr(i + 1) + #9 + GroupMembers[i].ValueStrByName
('SURNAME_NAME') + #9 + GroupMembers[i].ValueStrByName('DATE_IN') + #9 +
GroupMembers[i].ValueStrByName('DATE_OUT');
// mem.Lines.Add(sline);
Memo1.Lines.Add(sline);
end;
ExcelApp.Workbooks[1].WorkSheets[1].Columns[1].ColumnWidth := 4;
ExcelApp.Workbooks[1].WorkSheets[1].Columns[2].ColumnWidth := 25;
ExcelApp.Workbooks[1].WorkSheets[1].Columns[3].ColumnWidth := 16;
ExcelApp.Workbooks[1].WorkSheets[1].Columns[4].ColumnWidth := 16;
// ExcelApp.Workbooks[1].WorkSheets[1].Columns[5].ColumnWidth := 17;
// ExcelApp.Workbooks[1].WorkSheets[1].Columns[6].ColumnWidth := 9;
// ExcelApp.WorkBooks[1].WorkSheets[1].range['A2:F9'].Select;
// ExcelApp.Selection.Borders[xlInsideHorizontal].linestyle:=xlContinuous;
// ExcelApp.WorkBooks[1].WorkSheets[1].range['A2:F9'].Borders[xlInsideHorizontal].linestyle:=xlContinuous;
// ExcelApp.ActiveWorkBook.ActiveSheet.range['A2:F9'].Borders[xlInsideHorizontal].linestyle:=1;
// ExcelApp.ActiveWorkBook.ActiveSheet.UsedRange.Borders[xlInsideVertical].linestyle:=1 ;
// ExcelApp.ActiveWorkBook.ActiveSheet.UsedRange.Borders[xlEdgeBottom].linestyle:=1;
// ExcelApp.ActiveWorkBook.ActiveSheet.UsedRange.Borders[xlEdgeLeft].linestyle:=1;
// ExcelApp.ActiveWorkBook.ActiveSheet.UsedRange.Borders[xlEdgeRight].linestyle:=1;
// ExcelApp.ActiveWorkBook.ActiveSheet.UsedRange.Borders[xlEdgeTop].linestyle:=1;
// mem.SelectAll;
// mem.CopyToClipboard;
Memo1.SelectAll;
Memo1.CopyToClipboard;
ExcelApp.Workbooks[1].WorkSheets[1].Paste;
// mem.Destroy;
// формирую имя будущего файла
Delete(PedSurname, Length(PedSurname) - 4, 5);
ExcelFileName := CurAcademicYear + PedSurname + ' - Комплектование от ' +
FormatDateTime('dd mm', DateTimePicker1.Date);
// если файл уже существует и отказаться его перезаписать, то исключение!!!
// WorkBook.SaveAs(ExtractFilePath(Application.ExeName) + ExcelFileName);
WorkBook.SaveAs(ExtractFilePath(ParamStr(0)) + ExcelFileName);
// потом сделать проверку на сущ. файла и пусь пользователь
// решает, что с ним делать посредством диалога
// и еще, почему "Вместо Application.ExeName лучше использовать ParamStr(0)"
// ExcelApp.WorkBooks[1].WorkSheets[1].range['A2:F9'].Select;
ExcelApp.Visible := true;
finally
{ РАЗОБРАТЬСЯ:
// Если переменная не пустая, то...
if not VarIsEmpty(ExcelApp) then
begin
// ...отключаем диалог с вопросом сохранять ли файл при выходе или нет
ExcelApp.DisplayAlerts := false;
// Закрываем Excel
ExcelApp.Quit;
// Присваиваем неопределенный тип, освобождая при этом
// процесс excel.exe, чтобы он мог завершиться. Если этого не
// сделать, то процесс останется висеть в памяти.
ExcelApp := Unassigned;
WorkBook := Unassigned;
Sheet := Unassigned;
end;
}
end;
end;
function TfGroupComposition.CheckExcelInstalled(AValue: String): Boolean;
var
FCLSID: TCLSID;
begin
Result := (CLSIDFromProgID(PChar(AValue), FCLSID) = S_OK);
end;
function TfGroupComposition.CheckExcelRun(AValue: String;
var ADest: Variant): Boolean;
begin
try
ADest := GetActiveOleObject(AValue);
Result := true;
except
Result := false;
end;
end;
procedure TfGroupComposition.cmbPedagogueChange(Sender: TObject);
begin
IDPedagogue := PedagogueSurnameNP[cmbPedagogue.ItemIndex].ValueByName
('ID_OUT');
ShowGroups;
ShowGroupMember;
end;
procedure TfGroupComposition.FormCreate(Sender: TObject);
begin
AcademicYear := nil;
PedagogueSurnameNP := nil;
GroupNames := nil;
GroupMembers := nil;
end;
procedure TfGroupComposition.FormDestroy(Sender: TObject);
begin
if Assigned(AcademicYear) then
FreeAndNil(AcademicYear);
if Assigned(PedagogueSurnameNP) then
FreeAndNil(PedagogueSurnameNP);
if Assigned(GroupNames) then
FreeAndNil(GroupNames);
if Assigned(GroupMembers) then
FreeAndNil(GroupMembers);
end;
procedure TfGroupComposition.FormShow(Sender: TObject);
begin
if not Assigned(AcademicYear) then
AcademicYear := Kernel.GetAcademicYear;
Kernel.FillingComboBox(cmbAcademicYear, AcademicYear, 'NAME', false);
Kernel.ChooseComboBoxItemIndex(cmbAcademicYear, AcademicYear, true, 'ID',
IDAcademicYear);
if not Assigned(PedagogueSurnameNP) then
PedagogueSurnameNP := Kernel.GetPedagogueSurnameNP;
Kernel.FillingComboBox(cmbPedagogue, PedagogueSurnameNP, 'SurnameNP', false);
Kernel.ChooseComboBoxItemIndex(cmbPedagogue, PedagogueSurnameNP, true,
'ID_OUT', IDPedagogue);
ShowGroups;
ShowGroupMember;
end;
procedure TfGroupComposition.lvGroupsSelectItem(Sender: TObject;
Item: TListItem; Selected: Boolean);
begin
IDLearningGroup := GroupNames[Item.Index].ValueByName('ID_OUT');
StrGroupName := GroupNames[Item.Index].ValueStrByName('L_G_NAME');
ShowGroupMember;
end;
procedure TfGroupComposition.SetIDAcademicYear(const Value: integer);
begin
if FIDAcademicYear <> Value then
FIDAcademicYear := Value;
end;
procedure TfGroupComposition.SetIDPedagogue(const Value: integer);
begin
if FIDPedagogue <> Value then
FIDPedagogue := Value;
end;
procedure TfGroupComposition.ShowGroupMember;
var
choose_mode, year_birth: integer;
begin
choose_mode := 0;
// список будет формироваться из группы, а не по году рождения
year_birth := 0;
if Assigned(GroupMembers) then
FreeAndNil(GroupMembers);
GroupMembers := Kernel.GetChildListForGroupMember(choose_mode,
IDLearningGroup, year_birth);
Kernel.GetLVGroupMember(lvGroupMembers, GroupMembers);
if lvGroupMembers.Items.Count > 0 then
lvGroupMembers.ItemIndex := 0;
end;
procedure TfGroupComposition.ShowGroups;
begin
if Assigned(GroupNames) then
FreeAndNil(GroupNames);
GroupNames := Kernel.GetLearningGroupName(0, IDPedagogue,
IDAcademicYear, 1, 0);
Kernel.GetLVGroupNames(lvGroups, GroupNames);
if GroupNames.Count > 0 then
lvGroups.ItemIndex := 0;
end;
end.
|
//*******************************************************//
// //
// DelphiFlash.com //
// Copyright (c) 2004-2008 FeatherySoft, Inc. //
// info@delphiflash.com //
// //
//*******************************************************//
// Description: tool functions for reading and makeing SWF file
// Last update: 15 mar 2008
{$I defines.inc}
unit SWFTools;
interface
Uses Windows, SysUtils, Classes, SWFConst, Contnrs,
{$IFDEF ExternalUTF}
Unicode,
{$ENDIF}
graphics;
type
// =================== TBitsEngine ====================
TBitsEngine = class
BitsStream: TStream;
LastByte, LastBitCount: byte;
Constructor Create(bs: TStream);
Procedure FlushLastByte(write: boolean = true);
Procedure WriteBits(Data: longword; Size: byte); overload;
Procedure WriteBits(Data: longint; Size: byte); overload;
Procedure WriteBits(Data: word; Size: byte); overload;
Procedure WriteBits(Data: byte; Size: byte); overload;
Procedure WriteBit(b: boolean);
procedure WriteByte(b: byte);
procedure Write2Byte(w: word);
Procedure Write4byte(dw: longword);
Procedure WriteRect(r: recRect); overload;
Procedure WriteRect(r: TRect); overload;
Procedure WriteColor(c: recRGB); overload;
Procedure WriteColor(c: recRGBA); overload;
procedure WriteSingle(s: single);
procedure WriteFloat(s: single);
Procedure WriteWord(w: word);
Procedure WriteSwapWord(w:word);
Procedure WriteDWord(dw: dword);
Procedure WriteString(s: ansiString; NullEnd: boolean = true; U: boolean = false);
Procedure WriteUTF8String(s: PChar; L: Integer; NullEnd: boolean = true);
Procedure WriteMatrix(m: recMatrix);
Procedure WriteColorTransform(ct: recColorTransform);
procedure WriteEncodedU32(Data: DWord);
procedure WriteStdDouble(d: double);
procedure WriteEncodedString(s: ansistring);
function GetBits(n:integer):dword;
function GetSBits(n: integer): LongInt;
function ReadByte: byte;
function ReadBytes(n: byte): DWord;
function ReadWord: word;
function ReadSwapWord: word;
function ReadDWord: DWord;
function ReadDouble: double;
function ReadStdDouble: double;
function ReadRect:TRect;
function ReadRGB:recRGB;
function ReadRGBA:recRGBA;
function ReadSingle: single;
function ReadFloat: single;
function ReadMatrix: recMATRIX;
function ReadColorTransform(UseA: boolean = true): recColorTransform;
function ReadFloat16: single;
function ReadString(len: byte): string; overload;
function ReadString: ansiString; overload;
function ReadLongString(Encoded32Method: boolean = false): ansiString;
function ReadEncodedU32: DWord;
end;
function GetBitsCount(Value: LongWord): byte; overload;
function GetBitsCount(Value: LongInt; add: byte): byte; overload;
function MaxValue(A, B, C, D: longint): longword; overload;
function MaxValue(A, B: longint): longword; overload;
Function CheckBit(w: word; n: byte): boolean;
Function WordToSingle(w: word): single;
Function SingleToWord(s: single): word;
function SWFRGB(r, g, b: byte):recRGB; overload;
function SWFRGB(c: tColor):recRGB; overload;
function SWFRGBA(r, g, b, a: byte):recRGBA; overload;
function SWFRGBA(c: tColor; A:byte = 255):recRGBA; overload;
function SWFRGBA(c: recRGB; A:byte = 255):recRGBA; overload;
function SWFRGBA(c: recRGBA; A:byte = 255):recRGBA; overload;
Function WithoutA(c: recRGBA): recRGB;
Function AddAlphaValue(c: recRGBA; A: Smallint): recRGBA;
Function SWFRectToRect(r: recRect; Convert: boolean = true): TRect;
Function RectToSWFRect(r: tRect; Convert: boolean = true): recRect;
Function IntToSingle(w: LongInt): single;
Function SingleToInt(s: single): LongInt;
Function MakeMatrix(hasScale, hasSkew: boolean;
ScaleX, ScaleY, SkewX, SkewY, TranslateX, TranslateY: longint): recMatrix;
Procedure MatrixSetTranslate(var M: recMatrix; X, Y: longint);
Procedure MatrixSetScale(var M: recMatrix; ScaleX, ScaleY: single);
Procedure MatrixSetSkew(var M: recMatrix; SkewX, SkewY: single);
Function SwapColorChannels(Color: longint): longint;
Function MakeColorTransform(hasADD: boolean; addR, addG, addB, addA: Smallint;
hasMULT: boolean; multR, multG, multB, multA: Smallint;
hasAlpha: boolean): recColorTransform;
function GetCubicPoint(P0, P1, P2, P3: longint; t: single): double;
//================== Region Data converter ========================
function NormalizeRect(R: TRect):TRect;
{$IFDEF VER130} // Delphi 5
function Sign(const AValue: Double): shortint;
{$ENDIF}
implementation
{$IFNDEF VER130}
uses Types;
{$ENDIF}
function NormalizeRect(R: TRect):TRect;
begin
if r.Left > r.Right then
begin result.Left:=r.Right; result.Right:=r.Left; end
else begin result.Left:=r.Left; result.Right:=r.Right; end;
if r.Top > r.Bottom then
begin result.Top:=r.Bottom; result.Bottom:=r.Top; end
else begin result.Top:=r.Top; result.Bottom:=r.Bottom; end;
end;
function GetBitsCount(Value: LongWord): byte;
var
n: longword;
il: byte;
begin
Result := 0;
if longint(Value) < 0 then result := 32 else
if (Value > 0) then
begin
n := 1;
for il := 1 to 32 do begin
n := n shl 1;
if (n > Value) then
begin
Result := il;
Break;
end;
end;
end;
end;
function GetBitsCount(Value: LongInt; add: byte): byte;
var
n: longword;
begin
if Value=0 then result:=0 {+ add} else
begin
n := Abs(Value);
Result := GetBitsCount(n) + add;
end;
end;
function MaxValue(A, B, C, D: longint): longword;
var
_a, _b, _c, _d: longint;
begin
_a := abs(A);
_b := abs(B);
_c := abs(C);
_d := abs(D);
if (_a > _b) then
if (_a>_c) then
if (_a>_d)
then Result := _a
else Result := _d
else
if (_c>_d)
then Result := _c
else Result := _d
else
if (_b>_c) then
if (_b>_d)
then Result := _b
else Result := _d
else
if (_c>_d)
then Result := _c
else Result := _d;
end;
function MaxValue(A, B: longint): longword;
var
_a, _b: longint;
begin
_a := abs(A);
_b := abs(B);
if (_a > _b) then Result := _a else Result := _b;
end;
Function CheckBit(w: word; n: byte): boolean;
begin
Result := ((W shr (n-1)) and 1) = 1;
end;
// =================== TBitsEngine ====================
Constructor TBitsEngine.Create(bs: tStream);
begin
inherited Create;
BitsStream := bs;
LastByte := 0;
LastBitCount := 0;
end;
// --- function for write datas for stream
Procedure TBitsEngine.FlushLastByte(write: boolean);
begin
if LastBitCount>0 then
begin
if write then WriteBits(LongWord(0), 8 - LastBitCount);
LastByte := 0;
LastBitCount := 0;
end;
end;
procedure TBitsEngine.WriteBits(Data: longword; Size: byte);
type
T4B = array[0..3] of byte;
var
tmpDW: longword;
tmp4b: T4B absolute tmpDW;
cwbyte, totalBits, il: byte;
endBits: byte;
begin
if Size = 0 then Exit;
// clear bits at the left if negative
tmpDW := Data shl (32-size) shr (32-size);
totalBits := LastBitCount + Size;
cwbyte := (totalBits) div 8;
if cwbyte = 0 then // if empty byte
begin
LastByte := (LastByte shl Size) or tmpDW;
LastBitCount := totalBits;
end else
begin
endBits := totalBits mod 8;
if endBits = 0 then // is full
begin
tmpDW := tmpDW + (LastByte shl Size);
LastByte := 0;
LastBitCount := 0;
end else // rest
begin
tmpDW := LastByte shl (Size - endBits) + (tmpDW shr endBits);
LastBitCount := endBits;
LastByte := byte(Data shl (8-endBits)) shr (8-endBits);
end;
for il := cwbyte downto 1 do
BitsStream.Write(tmp4b[il-1], 1);
end;
end;
Procedure TBitsEngine.WriteBits(Data: longint; Size: byte);
begin
WriteBits(LongWord(Data), Size);
end;
Procedure TBitsEngine.WriteBits(Data: word; Size: byte);
begin
WriteBits(LongWord(Data), Size);
end;
Procedure TBitsEngine.WriteBits(Data: byte; Size: byte);
begin
WriteBits(LongWord(Data), Size);
end;
Procedure TBitsEngine.WriteBit(b: boolean);
begin
WriteBits(longword(b), 1);
end;
procedure TBitsEngine.WriteByte(b: byte);
begin
if LastBitCount = 0 then BitsStream.Write(b, 1)
else WriteBits(b, 8);
end;
procedure TBitsEngine.Write2Byte(w: word);
begin
WriteBits(w, 16);
end;
procedure TBitsEngine.WriteSingle(s: single);
var LW: LongInt;
begin
LW := SingleToInt(s);
WriteDWord(LW);
end;
procedure TBitsEngine.WriteFloat(s: single);
var LW: LongWord;
begin
Move(S, LW, 4);
WriteDWord(LW);
end;
Procedure TBitsEngine.WriteWord(w:word);
begin
FlushLastByte;
BitsStream.Write(w, 2);
end;
Procedure TBitsEngine.WriteSwapWord(w:word);
begin
FlushLastByte;
WriteByte(HiByte(W));
WriteByte(LoByte(W));
end;
Procedure TBitsEngine.WriteDWord(dw: dword);
begin
FlushLastByte;
BitsStream.Write(dw, 4);
end;
procedure TBitsEngine.WriteEncodedString(s: ansistring);
var SLen, il: word;
begin
SLen := length(s);
WriteEncodedU32(SLen);
if SLen > 0 then
for il := 1 to SLen do Writebyte(byte(S[il]));
end;
procedure TBitsEngine.WriteEncodedU32(Data: DWord);
var AByte: array [0..3] of byte absolute Data;
il, Max: byte;
begin
if Data = 0 then WriteByte(0)
else
begin
Max := 3;
while (Max > 0) and (Abyte[Max] = 0) do dec(Max);
for il := 0 to Max do
begin
WriteBit((il < Max) or ((GetBitsCount(AByte[il]) + il) > 7));
WriteBits(AByte[il], 8 - il - 1);
if il > 0 then WriteBits(byte(AByte[il - 1] shr (8 - il)), il);
end;
if ((GetBitsCount(Data) + Max) > ((Max + 1) * 7)) and
((AByte[Max] shr (8 - Max - 1)) > 0) then
WriteByte(byte(AByte[Max] shr (8 - Max - 1)));
end;
end;
Procedure TBitsEngine.Write4byte(dw: longword);
begin
FlushLastByte;
BitsStream.Write(dw, 4);
end;
Procedure TBitsEngine.WriteColor(c: recRGB);
begin
with BitsStream do
begin
Write(c.r, 1);
Write(c.g, 1);
Write(c.b, 1);
end;
end;
Procedure TBitsEngine.WriteColor(c: recRGBA);
begin
with BitsStream do
begin
Write(c.r, 1);
Write(c.g, 1);
Write(c.b, 1);
Write(c.a, 1);
end;
end;
Procedure TBitsEngine.WriteRect(r: recRect);
var nBits: byte;
begin
nBits := GetBitsCount(MaxValue(r.Xmin, r.Xmax, r.Ymin, r.Ymax), 1);
WriteBits(nBits, 5);
WriteBits(r.Xmin, nBits);
WriteBits(r.Xmax, nBits);
WriteBits(r.Ymin, nBits);
WriteBits(r.Ymax, nBits);
FlushLastByte;
end;
Procedure TBitsEngine.WriteRect(r: tRect);
begin
WriteRect(RectToSWFRect(r, false));
end;
procedure TBitsEngine.WriteStdDouble(d: double);
begin
BitsStream.Write(d, 8);
end;
Procedure TBitsEngine.WriteString(s: ansiString; NullEnd: boolean = true; U: boolean = false);
var il, len: integer;
tmpS: ansiString;
begin
if U then
begin
tmpS := AnsiToUTF8(s);
len := Length(tmpS);
if len>0 then
For il := 1 to len do WriteByte(Ord(tmpS[il]));
end else
begin
len := Length(s);
if len>0 then
For il := 1 to len do Writebyte(byte(s[il]));
end;
if NullEnd then WriteByte(0);
end;
Procedure TBitsEngine.WriteUTF8String(s: PChar; L: Integer; NullEnd: boolean = true);
var
il: Integer;
begin
if L>0 then
For il := 0 to L-1 do Writebyte(byte(S[il]));
if NullEnd then Writebyte(0);
end;
Procedure TBitsEngine.WriteMatrix(m: recMatrix);
var nBits: byte;
begin
WriteBit(m.hasScale);
if m.hasScale then
begin
nBits := GetBitsCount(MaxValue(m.ScaleX, m.ScaleY), 1);
WriteBits(nBits, 5);
WriteBits(m.ScaleX, nBits);
WriteBits(m.ScaleY, nBits);
end;
WriteBit(m.hasSkew);
if m.hasSkew then
begin
nBits := GetBitsCount(MaxValue(m.SkewX, m.SkewY), 1);
WriteBits(nBits, 5);
WriteBits(m.SkewY, nBits);
WriteBits(m.SkewX, nBits);
end;
nBits := GetBitsCount(MaxValue(m.TranslateX, m.TranslateY), 1);
WriteBits(nBits, 5);
if nBits>0 then
begin
WriteBits(m.TranslateX, nBits);
WriteBits(m.TranslateY, nBits);
end;
FlushLastByte;
end;
Procedure TBitsEngine.WriteColorTransform(ct: recColorTransform);
var n1, n2: byte;
begin
With ct do
begin
if hasADD then n1 := GetBitsCount(MaxValue(addR, addG, addB, addA * byte(hasAlpha)),1) else n1 := 0;
if hasMULT then n2 := GetBitsCount(MaxValue(multR, multG, multB, multA * byte(hasAlpha)),1) else n2 := 0;
if n1 < n2 then n1 := n2;
WriteBit(hasADD);
WriteBit(hasMULT);
if hasADD or hasMult then
begin
WriteBits(n1, 4);
if hasMult then
begin
WriteBits(multR, n1);
WriteBits(multG, n1);
WriteBits(multB, n1);
if hasAlpha then WriteBits(multA, n1);
end;
if hasAdd then
begin
WriteBits(addR, n1);
WriteBits(addG, n1);
WriteBits(addB, n1);
if hasAlpha then WriteBits(addA, n1);
end;
end;
end;
FlushLastByte;
end;
function TBitsEngine.ReadString(len: byte): string;
var ACH: array [0..255] of char;
begin
BitsStream.Read(ACH, len);
ACH[len] := #0;
Result := string(ACH);
end;
function TBitsEngine.ReadString: ansiString;
var ch: char;
begin
Result := '';
Repeat
ch := Char(ReadByte);
if ch<>#0 then Result := Result + ch;
until ch = #0;
end;
function TBitsEngine.ReadLongString(Encoded32Method: boolean = false): ansiString;
var C, il: word;
begin
if Encoded32Method
then C := ReadEncodedU32
else C := ReadSwapWord;
Result := '';
if C > 0 then
begin
if C > 255
then
for il := 1 to C do
Result := Result + Char(ReadByte)
else
Result := ReadString(C);
end;
end;
function TBitsEngine.ReadByte: byte;
begin
BitsStream.Read(Result, 1);
end;
function TBitsEngine.ReadWord: word;
begin
BitsStream.Read(Result, 2);
end;
function TBitsEngine.ReadSwapWord: word;
begin
BitsStream.Read(Result, 2);
Result := (Result and $FF) shl 8 + Result shr 8;
end;
function TBitsEngine.ReadBytes(n: byte): DWord;
begin
Result := 0;
if n > 4 then n := 4;
BitsStream.Read(Result, n);
end;
function TBitsEngine.ReadDouble: double;
var d: Double;
AB: array [0..7] of byte absolute d;
il: byte;
begin
d := 0;
for il := 7 downto 4 do ab[il] := ReadByte;
for il := 0 to 3 do ab[il] := ReadByte;
Result := d;
end;
function TBitsEngine.ReadStdDouble: double;
begin
BitsStream.Read(Result, 8);
end;
function TBitsEngine.ReadDWord: dword;
begin
BitsStream.Read(Result, 4);
end;
function TBitsEngine.ReadEncodedU32: DWord;
var b, il: byte;
begin
il := 0;
Result := 0;
while il < 5 do
begin
b := ReadByte;
Result := Result + (b and $7f) shl (il * 7);
if CheckBit(b, 8) then inc(il) else il := 5;
end;
end;
function TBitsEngine.ReadSingle: single;
var LW: longInt;
begin
BitsStream.Read(LW, 4);
result := IntToSingle(LW);
end;
function TBitsEngine.ReadFloat: single;
var LW: longWord;
begin
BitsStream.Read(LW, 4);
Move(LW, Result, 4);
end;
function TBitsEngine.GetBits(n:integer):dword;
var s:integer;
begin
Result:=0;
if n > 0 then
begin
{
if LastBitCount = 0 then
begin
LastByte := ReadByte; // Get the next buffer
LastBitCount := 8;
end; }
Repeat
s:= n - LastBitCount;
if (s>0) then
begin // Consume the entire buffer
Result:=Result or (lastByte shl s);
n:=n - LastBitCount;
LastByte := ReadByte; // Get the next buffer
LastBitCount := 8;
end;
Until S<=0;
Result := Result or (lastByte shr -s);
LastBitCount := LastBitCount - n;
lastByte := lastByte and ($ff shr (8 - LastBitCount)); // mask off the consumed bits
end;
end;
function TBitsEngine.ReadRect:tRect;
var nBits:byte;
begin
nBits := GetBits(5);
Result.Left := GetSBits(nBits);
Result.Right := GetSBits(nBits);
Result.Top := GetSBits(nBits);
Result.Bottom := GetSBits(nBits);
FlushLastByte(false);
end;
function TBitsEngine.GetSBits(n: integer): LongInt; // Get n bits from the string with sign extension
begin
Result:= GetBits(n);
// Is the number negative
if (Result and (1 shl (n - 1) ) )<>0 then // Yes. Extend the sign.
Result:=Result or (-1 shl n);
end;
Function TBitsEngine.ReadRGB:recRGB;
begin
With BitsStream do
begin
Read(Result.R, 1);
Read(Result.G, 1);
Read(Result.B, 1);
end;
end;
Function TBitsEngine.ReadRGBA:recRGBA;
begin
With BitsStream do
begin
Read(Result.R, 1);
Read(Result.G, 1);
Read(Result.B, 1);
Read(Result.A, 1);
end;
end;
function TBitsEngine.ReadMatrix: recMATRIX;
var nbits:byte;
begin
FillChar(Result, SizeOf(Result), 0);
Result.hasScale:=GetBits(1) = 1;
if Result.hasScale then
begin
nbits := GetBits(5);
Result.ScaleX := GetSBits(nBits);
Result.ScaleY := GetSBits(nBits);
end;
Result.hasSkew:=GetBits(1) = 1;
if Result.hasSkew then
begin
nbits := GetBits(5);
Result.SkewY := GetSBits(nBits);
Result.SkewX := GetSBits(nBits);
end;
nbits := GetBits(5);
Result.TranslateX := GetSBits(nBits);
Result.TranslateY := GetSBits(nBits);
FlushLastByte(false);
end;
function TBitsEngine.ReadColorTransform(UseA: boolean = true): recColorTransform;
var nbits:byte;
begin
Result.hasADD := GetBits(1) = 1;
Result.hasMult := GetBits(1) = 1;
Result.hasAlpha := UseA;
if Result.hasADD or Result.hasMult then
begin
nbits := GetBits(4);
if Result.hasMULT then
begin
Result.multR := GetSBits(nBits);
Result.multG := GetSBits(nBits);
Result.multB := GetSBits(nBits);
if UseA then Result.multA := GetSBits(nBits);
end;
if Result.hasADD then
begin
Result.addR := GetSBits(nBits);
Result.addG := GetSBits(nBits);
Result.addB := GetSBits(nBits);
if UseA then Result.addA := GetSBits(nBits);
end;
end;
FlushLastByte(false);
end;
function TBitsEngine.ReadFloat16: single;
var W: Word;
L: LongWord;
begin
BitsStream.Read(W, 2);
if W = 0 then Result := 0 else
begin
L := (W and $FC00) shl 16 + (W and $3FF) shl 7;
Move(L, Result, 4);
end;
end;
// =======================================================
Function WordToSingle(w: word): single;
begin
Result := W shr 8 + (W and $FF) / ($FF+1);
end;
Function SingleToWord(s: single): word;
begin
Result := trunc(s) shl 8 + Round(Frac(s) * ($FF+1));
end;
function SWFRGB(r, g, b: byte):recRGB;
begin
Result.R := r;
Result.G := g;
Result.B := b;
end;
function SWFRGB(c: tColor):recRGB;
begin
C := ColorToRGB(C);
Result := SWFRGB (GetRValue(ColorToRGB(c)), GetGValue(ColorToRGB(c)), GetBValue(ColorToRGB(c)));
end;
function SWFRGBA(r, g, b, a: byte):recRGBA;
begin
Result.R := r;
Result.G := g;
Result.B := b;
Result.A := a;
end;
function SWFRGBA(c: TColor; A:byte = 255):recRGBA;
begin
Result.R := GetRValue(ColorToRGB(c));
Result.G := GetGValue(ColorToRGB(c));
Result.B := GetBValue(ColorToRGB(c));
Result.A := A;
end;
function SWFRGBA(c: recRGB; A:byte):recRGBA;
begin
Result.R := c.r;
Result.G := c.g;
Result.B := c.b;
Result.A := A;
end;
function SWFRGBA(c: recRGBA; A:byte = 255):recRGBA;
begin
Result := c;
Result.A := A;
end;
Function WithoutA(c: recRGBA): recRGB;
begin
result := SWFRGB (c.R, c.G, c.B);
end;
Function AddAlphaValue(c: recRGBA; A: Smallint): recRGBA;
begin
if (C.A + A) > 255 then C.A := 255 else
if (C.A + A) < 0 then C.A := 0 else C.A := C.A + A;
end;
// Convering px <=> twips если Convert = true
Function SWFRectToRect(r: recRect; Convert: boolean = true): tRect;
begin
With Result do
begin
Left := r.Xmin;
Right := r.Xmax;
Top := r.Ymin;
Bottom := r.Ymax;
end;
if Convert then
With Result do
begin
Left := Left div TWIPS;
Right := Right div TWIPS;
Top := Top div TWIPS;
Bottom := Bottom div TWIPS;
end;
end;
Function RectToSWFRect(r: tRect; Convert: boolean = true): recRect;
begin
if r.Left<r.Right then
begin
Result.Xmin := r.Left;
Result.Xmax := r.Right;
end else
begin
Result.Xmin := r.Right;
Result.Xmax := r.Left;
end;
if r.Top<r.Bottom then
begin
Result.Ymin := r.Top;
Result.Ymax := r.Bottom;
end else
begin
Result.Ymin := r.Bottom;
Result.Ymax := r.Top;
end;
if Convert then
With Result do
begin
Xmin := Xmin * TWIPS;
Xmax := Xmax * TWIPS;
Ymin := Ymin * TWIPS;
Ymax := Ymax * TWIPS;
end;
end;
// flash used 16.16 bit
Function IntToSingle(w: longInt): single;
begin
// Result := W shr 16 + (W and $FFFF) / ($FFFF+1);
Result := W / specFixed;
end;
Function SingleToInt(s: single): longInt;
begin
Result := Trunc(s * specFixed);
// Result := trunc(s) shl 16 + Round(Frac(s) * ($FFFF + 1));
// Move(s, Result, 4);
end;
Function MakeMatrix(hasScale, hasSkew: boolean;
ScaleX, ScaleY, SkewX, SkewY, TranslateX, TranslateY: longint): recMatrix;
begin
Result.ScaleX := ScaleX;
Result.ScaleY := ScaleY;
Result.SkewX := SkewX;
Result.SkewY := SkewY;
Result.TranslateX := TranslateX;
Result.TranslateY := TranslateY;
Result.hasScale := hasScale;
Result.hasSkew := hasSkew;
end;
Procedure MatrixSetTranslate(var M: recMatrix; X, Y: longint);
begin
M.TranslateX := X;
M.TranslateY := Y;
end;
Procedure MatrixSetScale(var M: recMatrix; ScaleX, ScaleY: single);
begin
M.hasScale := true;
M.ScaleX := SingleToInt(ScaleX);
M.ScaleY := SingleToInt(ScaleY);
end;
Procedure MatrixSetSkew(var M: recMatrix; SkewX, SkewY: single);
begin
M.hasSkew := true;
M.SkewX := SingleToInt(SkewX);
M.SkewY := SingleToInt(SkewY);
end;
Function SwapColorChannels(Color: longint): longint;
begin
Result := (Color and $ff) shl 16 + (Color and $ff00) + (Color and $ff0000) shr 16;
end;
Function MakeColorTransform(hasADD: boolean; addR, addG, addB, addA: Smallint;
hasMULT: boolean; multR, multG, multB, multA: Smallint;
hasAlpha: boolean): recColorTransform;
begin
Result.hasADD := hasADD;
Result.addR := addR;
Result.addG := addG;
Result.addB := addB;
Result.addA := addA;
Result.hasMULT := hasMULT;
Result.multR := multR;
Result.multG := multG;
Result.multB := multB;
Result.multA := multA;
Result.hasAlpha := hasAlpha;
end;
function GetCubicPoint(P0, P1, P2, P3: Longint; t: single): double;
var t2, b, g: double;
begin
// P(t) = P0*(1-t)^3 + P1*3*t*(1-t)^2 + P2*3*t^2*(1-t) + P3*t^3
t2 := t * t;
g := 3 * (P1 - P0);
b := 3 * (P2 - P1) - g;
Result := (P3 - P0 - b - g) * t2*t + b * t2 + g * t + P0;
end;
{$IFDEF VER130} // Delphi 5
function Sign(const AValue: Double): shortint;
begin
if ((PInt64(@AValue)^ and $7FFFFFFFFFFFFFFF) = $0000000000000000) then
Result := 0
else if ((PInt64(@AValue)^ and $8000000000000000) = $8000000000000000) then
Result := -1
else
Result := 1;
end;
{$ENDIF}
end.
|
unit uNewPOSTransactionCard;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, StrUtils,
uNewUnit, uTSBaseClass, uConstanta, udmMain, uAppUtils;
type
TPOSTransactionCard = class(TSBaseClass)
private
FCardID: string;
FCashbackCharge: Double;
FCashbackNilai: Double;
FCharge: Double;
FDATE_CREATE: TDateTime;
FDATE_MODIFY: TDateTime;
FID: string;
FIsActive: Boolean;
FNewUnit: TUnit;
FNewUnitID: string;
FNilai: Double;
FNomor: string;
FNoOtorisasi: string;
// FOPC_UNIT: TUnit;
// FOPC_UNITID: Integer;
// FOPM_UNIT: TUnit;
// FOPM_UNITID: Integer;
FOP_CREATE: string;
FOP_MODIFY: string;
FTransNo: string;
function FLoadFromDB( aSQL : String ): Boolean;
function GetNewUnit: TUnit;
procedure SetNewUnit(Value: TUnit);
public
constructor Create(AOwner : TComponent); override;
constructor CreateWithUser(AOwner: TComponent; AUserID: string);
destructor Destroy; override;
procedure ClearProperties;
function CustomSQLTask: Tstrings;
function CustomSQLTaskPrior: Tstrings;
function CustomTableName: string;
function GenerateInterbaseMetaData: TStrings;
function GenerateSQL(ARepeatCount: Integer = 1): TStrings;
function GetFieldNameFor_CardID: string; dynamic;
// function GetFieldNameFor_CardUnit: string; dynamic;
function GetFieldNameFor_CashbackCharge: string; dynamic;
function GetFieldNameFor_CashbackNilai: string; dynamic;
function GetFieldNameFor_Charge: string; dynamic;
function GetFieldNameFor_DATE_CREATE: string; dynamic;
function GetFieldNameFor_DATE_MODIFY: string; dynamic;
function GetFieldNameFor_ID: string; dynamic;
function GetFieldNameFor_IsActive: string; dynamic;
function GetFieldNameFor_NewUnit: string; dynamic;
function GetFieldNameFor_Nilai: string; dynamic;
function GetFieldNameFor_Nomor: string; dynamic;
function GetFieldNameFor_NoOtorisasi: string; dynamic;
// function GetFieldNameFor_OPC_UNIT: string; dynamic;
// function GetFieldNameFor_OPM_UNIT: string; dynamic;
function GetFieldNameFor_OP_CREATE: string; dynamic;
function GetFieldNameFor_OP_MODIFY: string; dynamic;
function GetFieldNameFor_TransNo: string; dynamic;
// function GetFieldNameFor_TransUnit: string; dynamic;
function GetFieldPrefix: string;
function GetGeneratorName: string; dynamic;
function GetHeaderFlag: Integer;
function GetPlannedID: string;
function LoadByID(AID, AUnitID: string): Boolean;
function LoadByTransNo(ATransNo, AUnitID: String): Boolean;
function RemoveFromDB: Boolean;
function SaveToDB: Boolean;
procedure UpdateData(ACardID: string; ACashbackCharge, ACashbackNilai, ACharge:
Double; AID: string; AIsActive: Boolean; ANewUnit_ID: string; ANilai:
Double; ANomor, ANoOtorisasi, ATransNo: string);
property CardID: string read FCardID write FCardID;
property CashbackCharge: Double read FCashbackCharge write FCashbackCharge;
property CashbackNilai: Double read FCashbackNilai write FCashbackNilai;
property Charge: Double read FCharge write FCharge;
property DATE_CREATE: TDateTime read FDATE_CREATE write FDATE_CREATE;
property DATE_MODIFY: TDateTime read FDATE_MODIFY write FDATE_MODIFY;
property ID: string read FID write FID;
property IsActive: Boolean read FIsActive write FIsActive;
property NewUnit: TUnit read GetNewUnit write SetNewUnit;
property Nilai: Double read FNilai write FNilai;
property Nomor: string read FNomor write FNomor;
property NoOtorisasi: string read FNoOtorisasi write FNoOtorisasi;
// property OPC_UNIT: TUnit read GetOPC_UNIT write SetOPC_UNIT;
// property OPM_UNIT: TUnit read GetOPM_UNIT write SetOPM_UNIT;
property OP_CREATE: string read FOP_CREATE write FOP_CREATE;
property OP_MODIFY: string read FOP_MODIFY write FOP_MODIFY;
property TransNo: string read FTransNo write FTransNo;
end;
function Get_Price_Precision: string;
function _Price_Precision: Integer;
implementation
function Get_Price_Precision: string;
var
i : Smallint;
begin
Result := '0.';
for i := 1 to (_Price_Precision * -1) do
begin
Result := Result + '0';
end;
end;
function _Price_Precision: Integer;
var
iTemp: Integer;
begin
if TryStrToInt(getGlobalVar('PRICEPRECISION'), iTemp) then
Result := iTemp
else
Result := igPrice_Precision;
end;
{
***************************** TPOSTransactionCard ******************************
}
constructor TPOSTransactionCard.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
end;
constructor TPOSTransactionCard.CreateWithUser(AOwner: TComponent; AUserID:
string);
begin
Create(AOwner);
OP_MODIFY := AUserID;
// FOPM_UNITID := AUnitID;
end;
destructor TPOSTransactionCard.Destroy;
begin
ClearProperties;
inherited Destroy;
end;
procedure TPOSTransactionCard.ClearProperties;
begin
TransNo := '';
NoOtorisasi := '';
Nomor := '';
Nilai := 0;
IsActive := FALSE;
ID := '';
Charge := 0;
CashbackNilai := 0;
CashbackCharge := 0;
CardID := '';
end;
function TPOSTransactionCard.CustomSQLTask: Tstrings;
begin
result := nil;
end;
function TPOSTransactionCard.CustomSQLTaskPrior: Tstrings;
begin
result := nil;
end;
function TPOSTransactionCard.CustomTableName: string;
begin
Result := 'transaksi_card';
end;
function TPOSTransactionCard.FLoadFromDB( aSQL : String ): Boolean;
begin
Result := False;
State := csNone;
ClearProperties;
with cOpenQuery(aSQL) do
begin
try
if not EOF then
begin
FCardID := FieldByName(GetFieldNameFor_CardID).AsString;
FCashbackCharge := FieldByName(GetFieldNameFor_CashbackCharge).AsFloat;
FCashbackNilai := FieldByName(GetFieldNameFor_CashbackNilai).AsFloat;
FCharge := FieldByName(GetFieldNameFor_Charge).AsFloat;
FDATE_CREATE := FieldByName(GetFieldNameFor_DATE_CREATE).AsDateTime;
FDATE_MODIFY := FieldByName(GetFieldNameFor_DATE_MODIFY).AsDateTime;
FID := FieldByName(GetFieldNameFor_ID).AsString;
FIsActive := FieldValues[GetFieldNameFor_IsActive];
FNewUnitID := FieldByName(GetFieldNameFor_NewUnit).AsString;
FNilai := FieldByName(GetFieldNameFor_Nilai).AsFloat;
FNomor := FieldByName(GetFieldNameFor_Nomor).AsString;
FNoOtorisasi := FieldByName(GetFieldNameFor_NoOtorisasi).AsString;
// FOPC_UNITID := FieldByName(GetFieldNameFor_OPC_UNIT).AsInteger;
// FOPM_UNITID := FieldByName(GetFieldNameFor_OPM_UNIT).AsInteger;
FOP_CREATE := FieldByName(GetFieldNameFor_OP_CREATE).AsString;
FOP_MODIFY := FieldByName(GetFieldNameFor_OP_MODIFY).AsString;
FTransNo := FieldByName(GetFieldNameFor_TransNo).AsString;
Self.State := csLoaded;
Result := True;
end;
finally
Free;
end;
End;
end;
function TPOSTransactionCard.GenerateInterbaseMetaData: TStrings;
begin
Result := TStringList.Create;
Result.Append( '' );
Result.Append( 'Create Table ''+ CustomTableName +'' ( ' );
Result.Append( 'TRMSBaseClass_ID Integer not null, ' );
Result.Append( 'CardID Integer Not Null , ' );
Result.Append( 'CashbackCharge double precision Not Null , ' );
Result.Append( 'CashbackNilai double precision Not Null , ' );
Result.Append( 'Charge double precision Not Null , ' );
Result.Append( 'DATE_CREATE Date Not Null , ' );
Result.Append( 'DATE_MODIFY Date Not Null , ' );
Result.Append( 'ID Integer Not Null Unique, ' );
Result.Append( 'IsActive Boolean Not Null , ' );
Result.Append( 'NewUnit_ID Integer Not Null, ' );
Result.Append( 'Nilai double precision Not Null , ' );
Result.Append( 'Nomor Varchar(30) Not Null , ' );
Result.Append( 'NoOtorisasi Varchar(30) Not Null , ' );
Result.Append( 'OPC_UNIT_ID Integer Not Null, ' );
Result.Append( 'OPM_UNIT_ID Integer Not Null, ' );
Result.Append( 'OP_CREATE Integer Not Null , ' );
Result.Append( 'OP_MODIFY Integer Not Null , ' );
Result.Append( 'TransNo Varchar(30) Not Null , ' );
Result.Append( 'Stamp TimeStamp ' );
Result.Append( ' ); ' );
end;
function TPOSTransactionCard.GenerateSQL(ARepeatCount: Integer = 1): TStrings;
var
sPrec: string;
sSQL: string;
//i: Integer;
ssSQL: TStrings;
begin
Result := TStringList.Create;
if State = csNone then
begin
raise Exception.create('Tidak bisa generate dalam Mode csNone')
end;
sPrec := Get_Price_Precision;
ssSQL := CustomSQLTaskPrior;
if ssSQL <> nil then
begin
Result.AddStrings(ssSQL);
end;
ssSQL := nil;
DATE_MODIFY := cGetServerDateTime;
// FOPM_UNITID := FNewUnitID;
// If FID <= 0 then
if FID = '' then
begin
//Generate Insert SQL
OP_CREATE := OP_MODIFY;
DATE_CREATE := DATE_MODIFY;
// FOPC_UNITID := FOPM_UNITID;
// FID := cGetNextID(GetFieldNameFor_ID, CustomTableName);
FID := cGetNextIDGUIDToString;
sSQL := 'insert into ' + CustomTableName + ' ('
+ GetFieldNameFor_CardID + ', '
// + GetFieldNameFor_CardUnit + ', '
+ GetFieldNameFor_CashbackCharge + ', '
+ GetFieldNameFor_CashbackNilai + ', '
+ GetFieldNameFor_Charge + ', '
+ GetFieldNameFor_DATE_CREATE + ', '
+ GetFieldNameFor_DATE_MODIFY + ', '
+ GetFieldNameFor_ID + ', '
+ GetFieldNameFor_IsActive + ', '
+ GetFieldNameFor_NewUnit + ', '
+ GetFieldNameFor_Nilai + ', '
+ GetFieldNameFor_Nomor + ', '
+ GetFieldNameFor_NoOtorisasi + ', '
// + GetFieldNameFor_OPC_UNIT + ', '
// + GetFieldNameFor_OPM_UNIT + ', '
+ GetFieldNameFor_OP_CREATE + ', '
+ GetFieldNameFor_OP_MODIFY + ', '
// + GetFieldNameFor_TransUnit + ', '
+ GetFieldNameFor_TransNo +') values ('
+ QuotedStr(FCardID) + ', '
// + QuotedStr(FNewUnitID) + ', '
+ FormatFloat(sPrec, FCashbackCharge) + ', '
+ FormatFloat(sPrec, FCashbackNilai) + ', '
+ FormatFloat(sPrec, FCharge) + ', '
+ TAppUtils.QuotDT(FDATE_CREATE) + ', '
+ TAppUtils.QuotDT(FDATE_MODIFY) + ', '
+ QuotedStr(FID) + ', '
+ IfThen(FIsActive,'1','0') + ', '
+ QuotedStr(FNewUnitID) + ', '
+ FormatFloat(sPrec, FNilai) + ', '
+ QuotedStr(FNomor) + ', '
+ QuotedStr(FNoOtorisasi) + ', '
// + InttoStr(FOPC_UNITID) + ', '
// + InttoStr(FOPM_UNITID) + ', '
+ QuotedStr(FOP_CREATE) + ', '
+ QuotedStr(FOP_MODIFY) + ', '
// + QuotedStr(FNewUnitID) + ', '
+ QuotedStr(FTransNo) + ');';
end
else
begin
//generate Update SQL
sSQL := 'update ' + CustomTableName + ' set '
+ GetFieldNameFor_CardID + ' = ' + QuotedStr(FCardID)
// + ', ' + GetFieldNameFor_CardUnit + ' = ' + QuotedStr(FNewUnitID)
+ ', ' + GetFieldNameFor_CashbackCharge + ' = ' + FormatFloat(sPrec, FCashbackCharge)
+ ', ' + GetFieldNameFor_CashbackNilai + ' = ' + FormatFloat(sPrec, FCashbackNilai)
+ ', ' + GetFieldNameFor_Charge + ' = ' + FormatFloat(sPrec, FCharge)
+ ', ' + GetFieldNameFor_DATE_MODIFY + ' = ' + TAppUtils.QuotDT(FDATE_MODIFY)
+ ', ' + GetFieldNameFor_IsActive + ' = ' + IfThen(FIsActive,'1','0')
+ ', ' + GetFieldNameFor_NewUnit + ' = ' + QuotedStr(FNewUnitID)
+ ', ' + GetFieldNameFor_Nilai + ' = ' + FormatFloat(sPrec, FNilai)
+ ', ' + GetFieldNameFor_Nomor + ' = ' + QuotedStr(FNomor)
+ ', ' + GetFieldNameFor_NoOtorisasi + ' = ' + QuotedStr(FNoOtorisasi)
// + ', ' + GetFieldNameFor_OPM_UNIT + ' = ' + IntToStr(FOPM_UNITID)
+ ', ' + GetFieldNameFor_OP_MODIFY + ' = ' + QuotedStr(FOP_MODIFY)
// + ', ' + GetFieldNameFor_TransUnit + ' = ' + QuotedStr(FNewUnitID)
+ ', ' + GetFieldNameFor_TransNo + ' = ' + QuotedStr(FTransNo)
+ ' where ' + GetFieldNameFor_ID + ' = ' + QuotedStr(FID) + ';';
// + ' and ' + GetFieldNameFor_NewUnit + ' = ' + QuotedStr(FNewUnitID) + ';';
end;
Result.Append(sSQL);
//generating Collections SQL
ssSQL := CustomSQLTask;
if ssSQL <> nil then
begin
Result.AddStrings(ssSQL);
end;
FreeAndNil(ssSQL)
end;
function TPOSTransactionCard.GetFieldNameFor_CardID: string;
begin
// Result := GetFieldPrefix + 'card_id';
Result := 'REF$CREDIT_CARD_ID';
end;
//function TPOSTransactionCard.GetFieldNameFor_CardUnit: string;
//begin
// Result := GetFieldPrefix + 'card_unt_id';
//end;
function TPOSTransactionCard.GetFieldNameFor_CashbackCharge: string;
begin
Result := GetFieldPrefix + 'Cashback_Charge';
end;
function TPOSTransactionCard.GetFieldNameFor_CashbackNilai: string;
begin
Result := GetFieldPrefix + 'Cashback_Nilai';
end;
function TPOSTransactionCard.GetFieldNameFor_Charge: string;
begin
Result := GetFieldPrefix + 'Charge';
end;
function TPOSTransactionCard.GetFieldNameFor_DATE_CREATE: string;
begin
Result := 'DATE_CREATE';
end;
function TPOSTransactionCard.GetFieldNameFor_DATE_MODIFY: string;
begin
Result := 'DATE_MODIFY';
end;
function TPOSTransactionCard.GetFieldNameFor_ID: string;
begin
// Result := GetFieldPrefix + 'ID';
Result := 'TRANSAKSI_CARD_ID';
end;
function TPOSTransactionCard.GetFieldNameFor_IsActive: string;
begin
Result := GetFieldPrefix + 'Is_Active';
end;
function TPOSTransactionCard.GetFieldNameFor_NewUnit: string;
begin
// Result := GetFieldPrefix + 'UNT_ID';
Result := 'AUT$UNIT_ID';
end;
function TPOSTransactionCard.GetFieldNameFor_Nilai: string;
begin
Result := GetFieldPrefix + 'Nilai';
end;
function TPOSTransactionCard.GetFieldNameFor_Nomor: string;
begin
Result := GetFieldPrefix + 'Nomor';
end;
function TPOSTransactionCard.GetFieldNameFor_NoOtorisasi: string;
begin
Result := GetFieldPrefix + 'No_Otorisasi';
end;
//function TPOSTransactionCard.GetFieldNameFor_OPC_UNIT: string;
//begin
// Result := 'OPC_UNIT';
//end;
//function TPOSTransactionCard.GetFieldNameFor_OPM_UNIT: string;
//begin
// Result := 'OPM_UNIT';
//end;
function TPOSTransactionCard.GetFieldNameFor_OP_CREATE: string;
begin
Result := 'OP_CREATE';
end;
function TPOSTransactionCard.GetFieldNameFor_OP_MODIFY: string;
begin
Result := 'OP_MODIFY';
end;
function TPOSTransactionCard.GetFieldNameFor_TransNo: string;
begin
Result := GetFieldPrefix + 'Trans_No';
end;
//function TPOSTransactionCard.GetFieldNameFor_TransUnit: string;
//begin
// Result := GetFieldPrefix + 'Trans_unt_id';
//end;
function TPOSTransactionCard.GetFieldPrefix: string;
begin
Result := 'transc_';
end;
function TPOSTransactionCard.GetGeneratorName: string;
begin
Result := 'GEN_' + CustomTableName + '_ID';
end;
function TPOSTransactionCard.GetHeaderFlag: Integer;
begin
result := 5658;
end;
function TPOSTransactionCard.GetNewUnit: TUnit;
begin
if FNewUnit = nil then
begin
FNewUnit := TUnit.Create(Self);
FNewUnit.LoadByID(FNewUnitID);
end;
Result := FNewUnit;
end;
//function TPOSTransactionCard.GetOPC_UNIT: TUnit;
//begin
// //Result := nil;
// if FOPC_UNIT = nil then
// begin
// FOPC_UNIT := TUnit.Create(Self);
// FOPC_UNIT.LoadByID(FOPC_UNITID);
// end;
// Result := FOPC_UNIT;
//end;
//function TPOSTransactionCard.GetOPM_UNIT: TUnit;
//begin
// //Result := nil;
// if FOPM_UNIT = nil then
// begin
// FOPM_UNIT := TUnit.Create(Self);
// FOPM_UNIT.LoadByID(FOPM_UNITID);
// end;
// Result := FOPM_UNIT;
//end;
function TPOSTransactionCard.GetPlannedID: string;
begin
// result := -1;
Result := '';
if State = csNone then
begin
Raise exception.create('Tidak bisa GetPlannedID di Mode csNone');
exit;
end
else if state = csCreated then
begin
// Result := cGetNextID(GetFieldNameFor_ID, CustomTableName);
Result := cGetNextIDGUIDToString;
end
else if State = csLoaded then
begin
Result := FID;
end;
end;
function TPOSTransactionCard.LoadByID(AID, AUnitID: string): Boolean;
var
sSQL: string;
begin
sSQL := 'select * from ' + CustomTableName
+ ' where ' + GetFieldNameFor_ID + ' = ' + QuotedStr(AID);
// + ' and ' + GetFieldNameFor_NewUnit + ' = ' + QuotedStr(AUnitID);
Result := FloadFromDB(sSQL);
end;
function TPOSTransactionCard.LoadByTransNo(ATransNo, AUnitID: String): Boolean;
var
sSQL: string;
begin
sSQL := 'select * from ' + CustomTableName
+ ' where ' + GetFieldNameFor_TransNo + ' = ' + QuotedStr(ATransNo);
// + ' and ' + GetFieldNameFor_TransUnit + ' = ' + QuotedStr(AUnitID);
Result := FloadFromDB(sSQL);
end;
function TPOSTransactionCard.RemoveFromDB: Boolean;
var
sSQL: string;
begin
Result := False;
sSQL := 'delete from ' + CustomTableName
+ ' where ' + GetFieldNameFor_ID + ' = ' + QuotedStr(FID);
// + ' and ' + GetFieldNameFor_NewUnit + ' = ' + QuotedStr(FNewUnitID);
if cExecSQL(sSQL, dbtPOS, False) then
Result := True; //SimpanBlob(sSQL,GetHeaderFlag);
end;
function TPOSTransactionCard.SaveToDB: Boolean;
var
ssSQL: TStrings;
begin
Result := False;
try
ssSQL := GenerateSQL();
ssSQL.SaveToFile(cGetAppPath + 'POS_TransactionCard.SQL');
//try
if cExecSQL(ssSQL) then
// if SimpanBlob(ssSQL,GetHeaderFlag) then
Result := True;
//except
//end;
finally
FreeAndNil(ssSQL);
end;
end;
procedure TPOSTransactionCard.SetNewUnit(Value: TUnit);
begin
FNewUnitID := Value.ID;
end;
//procedure TPOSTransactionCard.SetOPC_UNIT(Value: TUnit);
//begin
// FOPC_UNITID := Value.ID;
//end;
//procedure TPOSTransactionCard.SetOPM_UNIT(Value: TUnit);
//begin
// FOPM_UNITID := Value.ID;
//end;
procedure TPOSTransactionCard.UpdateData(ACardID: string; ACashbackCharge,
ACashbackNilai, ACharge: Double; AID: string; AIsActive: Boolean;
ANewUnit_ID: string; ANilai: Double; ANomor, ANoOtorisasi, ATransNo:
string);
begin
FCardID := ACardID;
FCashbackCharge := ACashbackCharge;
FCashbackNilai := ACashbackNilai;
FCharge := ACharge;
FID := AID;
FIsActive := AIsActive;
FNewUnitID := ANewUnit_ID;
FNilai := ANilai;
FNomor := Trim(ANomor);
FNoOtorisasi := Trim(ANoOtorisasi);
FTransNo := Trim(ATransNo);
State := csCreated;
end;
end.
|
unit DesignUtils;
interface
uses
SysUtils, Windows, Classes, Controls, Graphics, Forms;
function DesignClientToParent(const inPt: TPoint;
inControl, inParent: TControl): TPoint;
function DesignMin(inA, inB: Integer): Integer;
function DesignMax(inA, inB: Integer): Integer;
function DesignRectWidth(const inRect: TRect): Integer;
function DesignRectHeight(const inRect: TRect): Integer;
function DesignValidateRect(const inRect: TRect): TRect;
function DesignNameIsUnique(inOwner: TComponent; const inName: string): Boolean;
function DesignUniqueName(inOwner: TComponent; const inClassName: string): string;
procedure DesignPaintRubberbandRect(const inRect: TRect; inPenStyle: TPenStyle);
procedure DesignPaintGrid(inCanvas: TCanvas; const inRect: TRect;
inBackColor: TColor = clBtnFace; inGridColor: TColor = clBlack;
inDivPixels: Integer = 8);
procedure DesignPaintRules(inCanvas: TCanvas; const inRect: TRect;
inDivPixels: Integer = 32; inSubDivs: Boolean = true);
procedure DesignSaveComponentToStream(inComp: TComponent; inStream: TStream);
function DesignLoadComponentFromStream(inComp: TComponent; inStream: TStream;
inOnError: TReaderError): TComponent;
procedure DesignSaveComponentToFile(inComp: TComponent;
const inFilename: string);
procedure DesignLoadComponentFromFile(inComp: TComponent;
const inFilename: string; inOnError: TReaderError);
implementation
function DesignClientToParent(const inPt: TPoint;
inControl, inParent: TControl): TPoint;
begin
Result := inPt;
while (inControl <> inParent) and (inControl <> nil) do
begin
Inc(Result.X, inControl.Left);
Inc(Result.Y, inControl.Top);
inControl := inControl.Parent;
end;
end;
function DesignMin(inA, inB: Integer): Integer;
begin
if inB < inA then
Result := inB
else
Result := inA;
end;
function DesignMax(inA, inB: Integer): Integer;
begin
if inB > inA then
Result := inB
else
Result := inA;
end;
function DesignRectWidth(const inRect: TRect): Integer;
begin
Result := inRect.Right - inRect.Left;
end;
function DesignRectHeight(const inRect: TRect): Integer;
begin
Result := inRect.Bottom - inRect.Top;
end;
function DesignValidateRect(const inRect: TRect): TRect;
begin
with Result do
begin
if inRect.Right < inRect.Left then
begin
Left := inRect.Right;
Right := inRect.Left;
end
else begin
Left := inRect.Left;
Right := inRect.Right;
end;
if inRect.Bottom < inRect.Top then
begin
Top := inRect.Bottom;
Bottom := inRect.Top;
end
else begin
Top := inRect.Top;
Bottom := inRect.Bottom;
end;
end;
end;
function DesignNameIsUnique(inOwner: TComponent; const inName: string): Boolean;
begin
Result := true;
while Result and (inOwner <> nil) do
begin
Result := inOwner.FindComponent(inName) = nil;
inOwner := inOwner.Owner;
end;
end;
function DesignUniqueName(inOwner: TComponent; const inClassName: string): string;
var
base: string;
i: Integer;
begin
base := Copy(inClassName, 2, MAXINT);
i := 0;
repeat
Inc(i);
Result := base + IntToStr(i);
until DesignNameIsUnique(inOwner, Result);
end;
procedure DesignPaintRubberbandRect(const inRect: TRect; inPenStyle: TPenStyle);
var
desktopWindow: HWND;
dc: HDC;
c: TCanvas;
begin
desktopWindow := GetDesktopWindow;
dc := GetDCEx(desktopWindow, 0, DCX_CACHE or DCX_LOCKWINDOWUPDATE);
try
c := TCanvas.Create;
with c do
try
Handle := dc;
Pen.Style := inPenStyle;
Pen.Color := clWhite;
Pen.Mode := pmXor;
Brush.Style := bsClear;
Rectangle(inRect);
finally
c.Free;
end;
finally
ReleaseDC(desktopWindow, dc);
end;
end;
procedure DesignPaintRules(inCanvas: TCanvas; const inRect: TRect;
inDivPixels: Integer; inSubDivs: Boolean);
var
d, d2, w, h, i: Integer;
begin
d := inDivPixels;
d2 := d div 2;
w := (inRect.Right - inRect.Left + d - 1) div d;
h := (inRect.Bottom - inRect.Top + d - 1) div d;
with inCanvas do
begin
Pen.Style := psDot;
for i := 0 to w do
begin
Pen.Color := $DDDDDD;
MoveTo(i * d, inRect.Top);
LineTo(i * d, inRect.Bottom);
if inSubDivs then
begin
Pen.Color := $F0F0F0;
MoveTo(i * d + d2, inRect.Top);
LineTo(i * d + d2, inRect.Bottom);
end;
end;
for i := 0 to h do
begin
Pen.Color := $DDDDDD;
MoveTo(inRect.Left, i * d);
LineTo(inRect.Right, i * d);
if inSubDivs then
begin
Pen.Color := $F0F0F0;
MoveTo(inRect.Left, i * d + d2);
LineTo(inRect.Right, i * d + d2);
end;
end;
end;
end;
procedure DesignPaintGrid(inCanvas: TCanvas; const inRect: TRect;
inBackColor, inGridColor: TColor; inDivPixels: Integer);
var
b: TBitmap;
i: Integer;
begin
b := TBitmap.Create;
try
b.Height := DesignRectHeight(inRect);
b.Width := inDivPixels;
b.Canvas.Brush.Color := inBackColor;
b.Canvas.FillRect(Rect(0, 0, b.Width, b.Height));
//
i := 0;
repeat
b.Canvas.Pixels[0, i] := inGridColor;
inc(i, inDivPixels);
until (i >= b.Height);
//
i := inRect.Left;
repeat
inCanvas.Draw(i, inRect.Top, b);
Inc(i, inDivPixels);
until (i >= inRect.Right);
finally
b.Free;
end;
end;
procedure DesignSaveComponentToStream(inComp: TComponent; inStream: TStream);
var
ms: TMemoryStream;
begin
ms := TMemoryStream.Create;
try
ms.WriteComponent(inComp);
ms.Position := 0;
ObjectBinaryToText(ms, inStream);
finally
ms.Free;
end;
end;
function DesignLoadComponentFromStream(inComp: TComponent; inStream: TStream;
inOnError: TReaderError): TComponent;
var
ms: TMemoryStream;
begin
ms := TMemoryStream.Create;
try
ObjectTextToBinary(inStream, ms);
ms.Position := 0;
with TReader.Create(ms, 4096) do
try
OnError := inOnError;
Result := ReadRootComponent(inComp);
finally
Free;
end;
finally
ms.Free;
end;
end;
procedure DesignSaveComponentToFile(inComp: TComponent;
const inFilename: string);
var
fs: TFileStream;
begin
fs := TFileStream.Create(inFilename, fmCreate);
try
DesignSaveComponentToStream(inComp, fs);
finally
fs.Free;
end;
end;
procedure DesignLoadComponentFromFile(inComp: TComponent;
const inFilename: string; inOnError: TReaderError);
var
fs: TFileStream;
begin
fs := TFileStream.Create(inFilename, fmOpenRead);
try
DesignLoadComponentFromStream(inComp, fs, inOnError);
finally
fs.Free;
end;
end;
end.
|
{
Reference
- mouse_event : http://msdn.microsoft.com/en-us/library/windows/desktop/ms646260(v=vs.85).aspx
- keybd_event : http://msdn.microsoft.com/en-us/library/windows/desktop/ms646304(v=vs.85).aspx
}
unit FMX.TestLib.Win;
interface
uses
System.Types, System.UITypes, System.Classes, System.SysUtils, FMX.TestLib,
FMX.Types, FMX.Graphics, VCL.Forms, VCL.Graphics;
function GetTestLibClass: TTestLibClass;
implementation
uses
Winapi.Windows, Winapi.ShellAPI, FMX.Platform;
type
TTestLibWin = class(TTestLib)
protected
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
procedure MouseMove(Shift: TShiftState; X, Y: Single); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
procedure MouseWheel(WheelDelta: Integer); override;
procedure KeyDown(Key: Word); override;
procedure KeyUp(Key: Word); override;
procedure TakeScreenshot(Dest: FMX.Graphics.TBitmap); override;
public
procedure RunKeyDownShift; override;
procedure RunKeyUpShift; override;
end;
function GetTestLibClass: TTestLibClass;
begin
Result := TTestLibWin;
end;
{ TTestLibWin }
procedure TTestLibWin.MouseMove(Shift: TShiftState; X, Y: Single);
begin
SetCursorPos(Round(X), Round(Y));
// mouse_event(MOUSEEVENTF_MOVE, Round(X), Round(Y), 0, 0);
end;
procedure TTestLibWin.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Single);
var
Flag: DWORD;
begin
case Button of
TMouseButton.mbLeft: Flag := MOUSEEVENTF_LEFTDOWN;
TMouseButton.mbRight: Flag := MOUSEEVENTF_RIGHTDOWN;
TMouseButton.mbMiddle: Flag := MOUSEEVENTF_MIDDLEDOWN;
else
Flag := MOUSEEVENTF_LEFTDOWN;
end;
SetCursorPos(Round(X), Round(Y));
mouse_event(Flag, Round(X), Round(Y), 0, 0);
end;
procedure TTestLibWin.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Single);
var
Flag: DWORD;
begin
case Button of
TMouseButton.mbLeft: Flag := MOUSEEVENTF_LEFTUP;
TMouseButton.mbRight: Flag := MOUSEEVENTF_RIGHTUP;
TMouseButton.mbMiddle: Flag := MOUSEEVENTF_MIDDLEUP;
else
Flag := MOUSEEVENTF_LEFTDOWN;
end;
SetCursorPos(Round(X), Round(Y));
mouse_event(Flag, Round(X), Round(Y), 0, 0);
end;
procedure TTestLibWin.MouseWheel(WheelDelta: Integer);
begin
inherited;
mouse_event(MOUSEEVENTF_WHEEL, 0, 0, WheelDelta, 0);
end;
procedure TTestLibWin.KeyDown(Key: Word);
begin
keybd_event(Key, MapVirtualKey(VK_SHIFT, 0), KEYEVENTF_EXTENDEDKEY, 0);
end;
procedure TTestLibWin.KeyUp(Key: Word);
begin
keybd_event(Key, MapVirtualKey(VK_SHIFT, 0), KEYEVENTF_EXTENDEDKEY or KEYEVENTF_KEYUP, 0);
end;
procedure TTestLibWin.RunKeyDownShift;
begin
KeyDown(VK_SHIFT);
end;
procedure TTestLibWin.RunKeyUpShift;
begin
KeyUp(VK_SHIFT);
end;
procedure WriteWindowsToStream(AStream: TStream);
var
dc: HDC; lpPal : PLOGPALETTE;
bm: Vcl.Graphics.TBitMap;
begin
{test width and height}
bm := Vcl.Graphics.TBitmap.Create;
bm.Width := Screen.Width;
bm.Height := Screen.Height;
//get the screen dc
dc := GetDc(0);
if (dc = 0) then exit;
//do we have a palette device?
if (GetDeviceCaps(dc, RASTERCAPS) AND RC_PALETTE = RC_PALETTE) then
begin
//allocate memory for a logical palette
GetMem(lpPal, sizeof(TLOGPALETTE) + (255 * sizeof(TPALETTEENTRY)));
//zero it out to be neat
FillChar(lpPal^, sizeof(TLOGPALETTE) + (255 * sizeof(TPALETTEENTRY)), #0);
//fill in the palette version
lpPal^.palVersion := $300;
//grab the system palette entries
lpPal^.palNumEntries :=GetSystemPaletteEntries(dc,0,256,lpPal^.palPalEntry);
if (lpPal^.PalNumEntries <> 0) then
begin
//create the palette
bm.Palette := CreatePalette(lpPal^);
end;
FreeMem(lpPal, sizeof(TLOGPALETTE) + (255 * sizeof(TPALETTEENTRY)));
end;
//copy from the screen to the bitmap
BitBlt(bm.Canvas.Handle,0,0,Screen.Width,Screen.Height,Dc,0,0,SRCCOPY);
bm.SaveToStream(AStream);
FreeAndNil(bm);
//release the screen dc
ReleaseDc(0, dc);
end;
procedure TTestLibWin.TakeScreenshot(Dest: FMX.Graphics.TBitmap);
var
Stream: TMemoryStream;
begin
Stream := TMemoryStream.Create;
try
WriteWindowsToStream(Stream);
Stream.Position := 0;
Dest.LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
end.
|
unit AppSettings;
{$mode objfpc}{$H+}
//========================================================================================
//
// Unit : AppSettings.pas
//
// Description : This module provides all Initial Application Directory sructure Setup
// functionality including RVMasterLog Application Database creation,
// Initial Application Installaetion and all Application DataBase Table
// functions.
//
// Called By : AppInit : Initialize
// Main : TfrmMain.mnuSettingDIrectoriesClick
// TfrmMain.mnuSettingsDatabasesClick
// SuppliersTable : frmSuppliersTable.CreateSuppliersTable
//
// Calls : HUConstants
//
// Ver. : 1.0.0
//
// Date : 27 Feb 2020
//
//========================================================================================
interface
uses
Buttons, Classes, ComCtrls, Controls, Dialogs, FileUtil, Forms, Graphics,
INIFiles, sqlite3conn, sqldb, db, StdCtrls, DBGrids, DBCtrls, Grids, SysUtils,
Types, windirs, STRUtils,
//App Units
// HULibrary units
HUConstants, HUMessageBoxes, HURegistration;
type
{ TfrmSettings }
TfrmSettings = class(TForm)
bbtOkClose: TBitBtn;
DBTableDataSource: TDataSource;
DBTableQuery: TSQLQuery;
dsRegistrationSettingsTable: TDataSource;
dsApplicationSettingsTable: TDataSource;
dbeFirstName: TDBEdit;
edtBackupsDirectory: TEdit;
edtAppDataDirectory: TEdit;
edtLogbooksDirectory: TEdit;
edtSettingsDirectory: TEdit;
edtApplicationDirectory: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
pcSettings: TPageControl;
pgDirectories: TTabSheet;
pgSettingsDB: TTabSheet;
DBConnection: TSQLite3Connection;
sqlqApplicationSettingsTable: TSQLQuery;
sqlqRegistrationSettingsTable: TSQLQuery;
DBTransaction: TSQLTransaction;
pgApplicationSettings: TTabSheet;
pgRegistrationSettings: TTabSheet;
StatusBar1: TStatusBar;
strgrdApplicationSettings: TStringGrid;
strgrdRegistrationSettings: TStringGrid;
procedure bbtCancelCloseClick(Sender: TObject);
procedure bbtOkCloseClick(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
function CreateApplicationDataBase: boolean;
function LoadApplicationDatabase: boolean;
function SaveApplicationDataBase: Boolean;
private
//====================================================================================
// The following Elements are constant elements that once the application has been
// installed, will be initialised during form creation, during AppSettingsDB creation
// and subsequently remained unchanged in the DB.
//====================================================================================
// Application Elements
fcAppVersion : string;
fcAppFullFilePathName : string;
fcAppFilePath : string;
fcAppFullFileName : string;
fcAppFileName : string;
fcAppFileExt : string;
fcAppUserDirectory : string;
fcAppDataDirectory : string;
fcAppSettingsDirectory : string;
fcAppLogbooksDirectory : string;
fcAppBackupsDirectory : string;
fcAppDatabaseName : string;
fMinBackupNr : string;
//====================================================================================
// The following Elements are variables that once initialized may be
// changed during program execution and are saved in the AppSettings database.
//====================================================================================
fAppSettingsInitialPageName : string;
fAppSettingsInitialPageNum : string;
fMaxBackupNr : string;
fCurrentBackupNr : string;
//====================================================================================
// The following Properties are constant properties that once the application has been
// installed, will not be changed during program execution.
//====================================================================================
function GetcAppVersion : string;
procedure SetcAppVersion(Version : string);
function GetcAppFullFilePathName : string;
procedure SetcAppFullFilePathName(PathName : string);
function GetcAppFilePath : string;
procedure SetcAppFilePath(Path : string);
function GetcAppFullFileName : string;
procedure SetcAppFullFileName(FName : string);
function GetcAppFileName : string;
procedure SetcAppFileName(FName : string);
function GetcAppFileExt : string;
function GetcAppUserDirectory : string;
procedure SetcAppUserDirectory(Dir : string);
function GetcAppDataDirectory : string;
procedure SetcAppDataDirectory(Dir : string);
function GetcAppSettingsDirectory : string;
procedure SetcAppSettingsDirectory(Dir : string);
function GetcAppLogbooksDirectory : string;
procedure SetcAppLogbooksDirectory(Dir : string);
function GetcAppBackupsDirectory : string;
procedure SetcAppBackupsDirectory(Dir : string);
function GetcAppDatabaseName : string;
procedure SetcAppDatabaseName(DBName : string);
//====================================================================================
// The following Properties are variables that once initialized may be
// changed during program execution and are saved in the AppSettings database.
//====================================================================================
function GetAppSettingsInitialPageName : string;
procedure SetAppSettingsInitialPageName(PageName : string);
function GetAppSettingsInitialPageNum : string;
procedure SetAppSettingsInitialPageNum(PageNum : string);
public
//====================================================================================
// The following Properties are constants that once initialized will not be
// changed during program execution.
//====================================================================================
property pcAppVersion : string
read GetcAppVersion
write SetcAppVersion;
property pcAppFullFilePathName : string
read GetcAppFullFilePathName
write SetcAppFullFilePathName;
property pcAppFilePath : string read GetcAppFilePath
write SetcAppFilePath;
property pcAppFullFileName : string
read GetcAppFullFileName
write SetcAppFullFileName;
property pcAppFileName : string
read GetcAppFileName
write SetcAppFileName;
property pcAppFileExt : string
read GetcAppFileExt;
property pcAppUserDirectory : string
read GetcAppUserDirectory
write SetcAppUserDirectory;
property pcAppDataDirectory : string
read GetcAppDataDirectory
write SetcAppDataDirectory;
property pcAppSettingsDirectory : string
read GetcAppSettingsDirectory
write SetcAppSettingsDirectory;
property pcAppLogbooksDirectory : string
read GetcAppLogbooksDirectory
write SetcAppLogbooksDirectory;
property pcAppBackupsDirectory : string
read GetcAppBackupsDirectory
write SetcAppBackupsDirectory;
property pcAppDatabaseName : string
read GetcAppDatabaseName
write SetcAppDatabaseName;
//====================================================================================
// The following Properties are variables that once initialized may be
// changed during program execution and are saved in the AppSettings database.
//====================================================================================
property pAppSettingsInitialPageName : string
read GetAppSettingsInitialPageName
write SetAppSettingsInitialPageName;
property pAppSettingsInitialPageNum : string
read GetAppSettingsInitialPageNum
write SetAppSettingsInitialPageNum;
end;// TfrmSettings
var
frmSettings: TfrmSettings;
implementation
{$R *.lfm}
//========================================================================================
// PRIVATE CONSTANTS
//========================================================================================
const
// Directories
cstrAppFullFileName = 'RVMasterLog.exe';
cstrSettingsDirectoryName = 'Settings';
cstrLogbooksDirectoryName = 'Logbooks';
cstrBackupsDirectoryName = 'Backups';
cstrAppDataDirectoryName = 'AppData';
// Databases
cstrApplicationDBName = 'RVMApplicationDB.sl3';
cstrApplicationSettingsTableName = 'ApplicationSettingsTable';
// Properties
cstrpAppSettingsInitialPageName = 'pAppSettingsInitialPageName';
cstrpAppSettingsInitialPageNum = 'pAppSettingsInitialPageNum';
// frmSettings
straryPageNames : array[0..3] of string = ('Directories', 'Application Settings',
'Registration Settings', 'SettingsDB');
//========================================================================================
// PRIVATE VARIABLES
//========================================================================================
var
vintAppSettingsInitialDirectory : integer;
//========================================================================================
// PRIVATE ROUTINES
//========================================================================================
//========================================================================================
// PUBLIC ROUTINES
//========================================================================================
function TfrmSettings.CreateApplicationDataBase: Boolean;
// This function createa a new Default ApplicationDataBase for both an Initial
// installation or to replace an active Application Database after a backup database
// has been created and saved.
var
vstrTstr : String;
begin
//*** showmessage('Creating Default ApplicationDataBase');
DBConnection.Close; // Ensure the AppDatabase Connection is closed
Result := True;
//========================================
// Create the Default database and tables
//========================================
try
//=========================
// Create the Database
//=========================
DBConnection.Open;
DBTransaction.Active := true;
//========================================
// Create the "ApplicationSettingsTable"
//========================================
//*** showmessage('Create ApplicationSettingsTable');
DBConnection.ExecuteDirect('CREATE TABLE "ApplicationSettingsTable"('+
' "Property" String PRIMARY KEY,'+
' "Value" String );');
//*** showmessage('Create ApplicationSettingsIndex');
// Creating an index based upon Property in the ApplicationSettingsTable
DBConnection.ExecuteDirect('CREATE UNIQUE INDEX ' +
' "ApplicationSettingsTable_Property_idx"' +
' ON "ApplicationSettingsTable"( "Property" );');
//========================================
// Create the "RegistrationSettingsTable"
//========================================
//*** showmessage('Create RegistrationSettingsTable');
DBConnection.ExecuteDirect('CREATE TABLE "RegistrationSettingsTable"('+
' "Property" String PRIMARY KEY,'+
' "Value" String );');
//*** showmessage('Create RegistrationSettings Index');
DBConnection.ExecuteDirect('CREATE UNIQUE INDEX ' +
' "RegistrationSettingsTable_Property_idx"' +
' ON "RegistrationSettingsTable"( "Property" );');
DBTransaction.Commit;
//=========================
// Add the User Adaptble Property Records with Initial Default values.
//=============================
//================================
// Application Settings properties
//================================
DBConnection.ExecuteDirect('INSERT INTO ApplicationSettingsTable VALUES' +
' ("pAppSettingsInitialPageName", "Application Settings")');
DBConnection.ExecuteDirect('INSERT INTO ApplicationSettingsTable VALUES' +
' ("pAppSettingsInitialPageNum", "1")');
//==========================
// HURegistration properties
//==========================
DBConnection.ExecuteDirect('INSERT INTO RegistrationSettingsTable VALUES' +
' ("pRegFirstName", " ")');
DBConnection.ExecuteDirect('INSERT INTO RegistrationSettingsTable VALUES' +
' ("pRegLastName", " ")');
DBConnection.ExecuteDirect('INSERT INTO RegistrationSettingsTable VALUES' +
' ("pRegEMailaddress", " ")');
DBConnection.ExecuteDirect('INSERT INTO RegistrationSettingsTable VALUES' +
' ("pRegCallsign", " ")');
DBConnection.ExecuteDirect('INSERT INTO RegistrationSettingsTable VALUES' +
' ("pRegKey", " ")');
DBConnection.ExecuteDirect('INSERT INTO RegistrationSettingsTable VALUES' +
' ("pRegUserID", " ")');
// Additional records go here
//=========================
// Commit the additions
//=========================
DBTransaction.Commit;
except
ShowMessage('Unable to Create new Database');
Result := False;
end;// Try to Create the Default database and tables
//=======================
// Database Created
//=======================
DBTransaction.Active := False;
DBConnection.Close;
//*** showmessage('Settings DataBase Created');
end;// function TfrmSettings.CreateSettingsDataBase
//========================================================================================
function TfrmSettings.LoadApplicationDatabase : boolean;
var
vstrTStr : string;
vintRecNr : integer;
begin
showmessage('LoadApplicationDatabase');
Result := True;
try {LoadApplicationDatabase}
//***** showmessage('Opening DBConnection');
if not DBConnection.Connected then
DBConnection.Open;
// showmessage('DBConnection Open');
if not DBConnection.Connected then
begin
showmessage('Error connecting to the Database. Aborting data loading');
Result := False;
Exit;
end;// if not DBConnection.Connected
//================================================
// Load the Application Settings Table properties
//================================================
sqlqApplicationSettingsTable.SQL.Text :=
'select ' +
' e.Property, ' +
' e.Value ' +
'from ApplicationSettingsTable e';
DBTransaction.StartTransaction;
// showmessage('DBTransaction.StartTransaction');
sqlqApplicationSettingsTable.Open;
// showmessage('sqlqApplicationSettingsTable.Open');
// Get pAppSettingsInitialPageName
// showmessage('Record = ' + (IntToStr(sqlqApplicationSettingsTable.RecNo )));
pAppSettingsInitialPageName := sqlqApplicationSettingsTable.Fields[1].AsString;
// Get pAppSettingsInitialPageNum
sqlqApplicationSettingsTable.NEXT;
// showmessage('Record = ' + (IntToStr(sqlqApplicationSettingsTable.RecNo )));
pAppSettingsInitialPageNum := sqlqApplicationSettingsTable.Fields[1].AsString;
// showmessage('pAppSettingsInitialPageNum = ' + pAppSettingsInitialPageNum);
//================================================
// Application Settings Table properties Loaded
//================================================
// showmessage('ApplicationSettingsTable.EOF');
sqlqApplicationSettingsTable.Close;
//================================================
// Load the Registration Table properties
//================================================
sqlqRegistrationSettingsTable.SQL.Text :=
'select ' +
' e.Property, ' +
' e.Value ' +
'from RegistrationSettingsTable e';
sqlqRegistrationSettingsTable.Open;
// showmessage('sqlqRegistrationSettingsTable Open');
// Get pRegFirstName
// showmessage('Record = ' + (IntToStr(sqlqRegistrationSettingsTable.RecNo )));
dlgHURegistration.pRegFirstName := sqlqRegistrationSettingsTable.Fields[1].AsString;
// Get pRegLastName
sqlqRegistrationSettingsTable.NEXT;
dlgHURegistration.pRegLastName := sqlqRegistrationSettingsTable.Fields[1].AsString;
// Get pRegEmailAddress
sqlqRegistrationSettingsTable.NEXT;
dlgHURegistration.pRegEmailAddress := sqlqRegistrationSettingsTable.Fields[1].AsString;
// Get pRegCallsign
sqlqRegistrationSettingsTable.NEXT;
dlgHURegistration.pRegCallsign := sqlqRegistrationSettingsTable.Fields[1].AsString;
// Get pRegKey
sqlqRegistrationSettingsTable.NEXT;
dlgHURegistration.pRegKey := sqlqRegistrationSettingsTable.Fields[1].AsString;
// Get pRegUserID
sqlqRegistrationSettingsTable.NEXT;
dlgHURegistration.pRegUserID := sqlqRegistrationSettingsTable.Fields[1].AsString;
//================================================
// Registration Table properties Loaded
//================================================
showmessage('RegistrationTable.EOF');
sqlqRegistrationSettingsTable.Close;
except
on D: EDatabaseError do
begin
MessageDlg('Error', 'A Database error has occured. Technical error message: ' +
D.Message, mtError, [mbOK], 0);
Result := False;
end;// on D: EDatabaseEorror
end;// Try {LoadApplicationDatabase}
DBTransaction.Active := False;
DBConnection.Close;
end;// function TfrmSettings.LoadApplicationDatabase
//========================================================================================
function TfrmSettings.SaveApplicationDatabase : Boolean;
var
vstrTstr : String;
begin
showmessage('Saving ApplicationDataBase');
DBConnection.Close; // Ensure any connection is closed when we start
Result := True;
//========================================
// Create the Default database and tables
//========================================
try
//=========================
// Create the Database
//=========================
DBConnection.Open;
DBTransaction.Active := true;
//========================================
// Create the "ApplicationSettingsTable"
//========================================
// showmessage('Create ApplicationSettingsTable');
DBConnection.ExecuteDirect('CREATE TABLE "ApplicationSettingsTable"('+
' "Property" String PRIMARY KEY,'+
' "Value" String );');
// showmessage('Create ApplicationSettingsIndex');
// Creating an index based upon Property in the ApplicationSettingsTable
DBConnection.ExecuteDirect('CREATE UNIQUE INDEX ' +
' "ApplicationSettingsTable_Property_idx"' +
' ON "ApplicationSettingsTable"( "Property" );');
//========================================
// Create the "RegistrationSettingsTable"
//========================================
// showmessage('Create RegistrationSettingsTable');
DBConnection.ExecuteDirect('CREATE TABLE "RegistrationSettingsTable"('+
' "Property" String PRIMARY KEY,'+
' "Value" String );');
// showmessage('Create RegistrationSettings Index');
DBConnection.ExecuteDirect('CREATE UNIQUE INDEX ' +
' "RegistrationSettingsTable_Property_idx"' +
' ON "RegistrationSettingsTable"( "Property" );');
DBTransaction.Commit;
//=========================
// Add the User Adaptble Property Records with Initial Default values.
//=============================
//================================
// Application Settings properties
//================================
DBConnection.ExecuteDirect('INSERT INTO ApplicationSettingsTable VALUES' +
' ("pAppSettingsInitialPageName", "Application Settings")');
DBConnection.ExecuteDirect('INSERT INTO ApplicationSettingsTable VALUES' +
' ("pAppSettingsInitialPageNum", "1")');
//==========================
// HURegistration properties
//==========================
DBConnection.ExecuteDirect('INSERT INTO RegistrationSettingsTable VALUES' +
' ("pRegFirstName", " ")');
DBConnection.ExecuteDirect('INSERT INTO RegistrationSettingsTable VALUES' +
' ("pRegLastName", " ")');
DBConnection.ExecuteDirect('INSERT INTO RegistrationSettingsTable VALUES' +
' ("pRegEMailaddress", " ")');
DBConnection.ExecuteDirect('INSERT INTO RegistrationSettingsTable VALUES' +
' ("pRegCallsign", " ")');
DBConnection.ExecuteDirect('INSERT INTO RegistrationSettingsTable VALUES' +
' ("pRegKey", " ")');
DBConnection.ExecuteDirect('INSERT INTO RegistrationSettingsTable VALUES' +
' ("pRegUserID", " ")');
// Additional records go here
//=========================
// Commit the additions
//=========================
DBTransaction.Commit;
except
ShowMessage('Unable to Create new Database');
Result := False;
end;// Try to Create the Default database and tables
//=======================
// Database Created
//=======================
DBTransaction.Active := False;
DBConnection.Close;
showmessage('Settings DataBase Created');
end;// function TfrmSettings.SaveSettingsDataBase
//========================================================================================
// PROPERTY ROUTINES
//========================================================================================
function TfrmSettings.GetcAppVersion: string;
begin
Result := fcAppVersion;
end;// function TfrmSettings.GetVeGetcAppVersionrsion
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetcAppVersion(Version: string);
begin
fcAppVersion := Version;
end;// procedure TfrmSettings.SetcAppVersion
//========================================================================================
function TfrmSettings.GetcAppFullFilePathName: string;
begin
Result := fcAppFullFilePathName;
end;// function TfrmSettings.GetcAppFullFilePathName
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetcAppFullFilePathName(PathName: string);
begin
fcAppFullFilePathName := PathName;
end;// procedure TfrmSettings.SetcAppFullFilePathName
//========================================================================================
function TfrmSettings.GetcAppFilePath: string;
begin
Result := fcAppFilePath;
end;// function TfrmSettings.GetcAppFullFilePath
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetcAppFilePath(Path: string);
begin
fcAppFilePath := Path;
end;// procedure TfrmSettings.SetcAppFullFilePath
//========================================================================================
function TfrmSettings.GetcAppFullFileName: string;
begin
Result := fcAppFullFileName;
end;// function TfrmSettings.GetcAppFullFileNamee
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetcAppFullFileName(FName: string);
begin
fcAppFullFileName := cstrAppFullFileName;
end;// procedure TfrmSettings.SetcAppFullFileName
//========================================================================================
function TfrmSettings.GetcAppFileName: string;
begin
Result := fcAppFileName;
end;// function TfrmSettings.GetcAppFileNamee
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetcAppFileName(FName: string);
begin
fcAppFileName := FName;
end;// procedure TfrmSettings.SetcAppFileName
//========================================================================================
function TfrmSettings.GetcAppFileExt: string;
begin
Result := fcAppFileExt;
end;// function TfrmSettings.GetcAppFileExt
//========================================================================================
function TfrmSettings.GetcAppUserDirectory: string;
begin
Result := fcAppUserDirectory;
end;// procedure TfrmSettings.GetcAppUserDirectory
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetcAppUserDirectory(Dir: string);
begin
fcAppUserDirectory := Dir;
end;// procedure TfrmSettings.SetcAppUserDataDirectory
//========================================================================================
function TfrmSettings.GetcAppDataDirectory: string;
begin
Result := fcAppDataDirectory;
end;// procedure TfrmSettings.GetcAppDirectory
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetcAppDataDirectory(Dir: string);
begin
fcAppDataDirectory := Dir;
end;// procedure TfrmSettings.SetcAppDataDirectory
//========================================================================================
function TfrmSettings.GetcAppSettingsDirectory: string;
begin
Result := fcAppSettingsDirectory;
end;// procedure TfrmSettings.GetcAppSettingsDirectory
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetcAppSettingsDirectory(Dir: string);
begin
fcAppSettingsDirectory := Dir;
end;// procedure TfrmSettings.SetcAppSettingsDirectory
//========================================================================================
function TfrmSettings.GetcAppLogbooksDirectory: string;
begin
Result := fcAppLogbooksDirectory;
end;// procedure TfrmSettings.GetcAppLogbooksDirectory
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetcAppLogbooksDirectory(Dir: string);
begin
fcAppLogbooksDirectory := Dir;
end;// procedure TfrmSettings.SetcApptLogbooksDirectory
//========================================================================================
function TfrmSettings.GetcAppBackupsDirectory: string;
begin
Result := fcAppBackupsDirectory;
end;// procedure TfrmSettings.GetcAppBackupsDirectory
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetcAppBackupsDirectory(Dir: string);
begin
fcAppBackupsDirectory := Dir;
end;// procedure TfrmSettings.SetcAppBackupsDirectory
//========================================================================================
function TfrmSettings.GetAppSettingsInitialPageName: string;
begin
Result := fAppSettingsInitialPageName;
end;// procedure TfrmSettings.GetAppSettingsInitialPageName
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetAppSettingsInitialPageName(PageName: string);
begin
fAppSettingsInitialPageName := PageName;
end;// procedure TfrmSettings.SetAppSettingsInitialPageName
//========================================================================================
function TfrmSettings.GetAppSettingsInitialPageNum: string;
begin
Result := fAppSettingsInitialPageNum ;
end;// procedure TfrmSettings.GetAppSettingsInitialPageNum
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetAppSettingsInitialPageNum(PageNum: string);
begin
fAppSettingsInitialPageNum := PageNum;
end;// procedure TfrmSettings.SetAppSettingsInitialPageNum
//========================================================================================
function TfrmSettings.GetcAppDatabaseName: string;
begin
Result := fcAppDatabaseName;
end;// procedure TfrmSettings.GetcAppDatabaseName
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetcAppDatabaseName(DBName: string);
begin
fcAppDatabaseName := DBName;
end;// procedure TfrmSettings.SetcAppDatabaseName
{//========================================================================================
function TfrmSettings.GetAppOwnerFirstName: string;
begin
Result := fAppOwnerFirstName;
end;// procedure TfrmSettings.GetAppOwnerFirstName
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetAppOwnerFirstName(FirstName: string);
begin
fAppOwnerFirstName := FirstName;
end;// procedure TfrmSettings.SetAppOwnerFirstName
//========================================================================================
function TfrmSettings.GetAppOwnerLastName: string;
begin
Result := fAppOwnerLastName;
end;// procedure TfrmSettings.GetAppOwnerLastName
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetAppOwnerLastName(LastName: string);
begin
fAppOwnerLastName := LastName;
end;// procedure TfrmSettings.SetAppOwnerLastName
//========================================================================================
function TfrmSettings.GetAppOwnerCallsign: string;
begin
Result := fAppOwnerCallsign;
end;// procedure TfrmSettings.GetAppOwnerCallsign
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetAppOwnerCallsign(Callsign: string);
begin
fAppOwnerCallsign := Callsign;
end;// procedure TfrmSettings.SetAppOwnerCallsign
//========================================================================================
function TfrmSettings.GetAppOwnerEmailAddress: string;
begin
Result := fAppOwnerEmailAddress;
end;// procedure TfrmSettings.GetAppOwnerEmailAddress
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetAppOwnerEmailAddress(EmailAddress: string);
begin
fAppOwnerEmailAddress := EMailAddress;
end;// procedure TfrmSettings.SetAppOwnerEmailAddress
//========================================================================================
function TfrmSettings.GetAppOwnerID: string;
begin
Result := fAppOwnerID;
end;// procedure TfrmSettings.GetAppUserID
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetAppOwnerID(OwnerID: string);
begin
fAppOwnerID := OwnerID;
end;// procedure TfrmSettings.SetAppOwnerID }
//========================================================================================
// MENU ROUTINES
//========================================================================================
//========================================================================================
// COMMAND BUTTON ROUTINES
//========================================================================================
procedure TfrmSettings.bbtCancelCloseClick(Sender: TObject);
begin
end;// procedure TfrmSettings.bbtCancelClick
//----------------------------------------------------------------------------------------
procedure TfrmSettings.bbtOkCloseClick(Sender: TObject);
begin
end;// procedure TfrmSettings.bbtOkClick
//========================================================================================
// CONTROL ROUTINES
//========================================================================================
//========================================================================================
// FILE ROUTINES
//========================================================================================
//========================================================================================
// FORM ROUTINES
//========================================================================================
procedure TfrmSettings.FormCreate(Sender: TObject);
begin
//====================================================
// constant properties that once the application has been
// installed, will be read from the ApplicationSettingsDB
// and will not be changed during program execution.
//====================================================
//====================================================
// Initialize the Application Directories
//====================================================
pcAppFileName := Copy (cstrAppFullFileName, 1, 12);
pcAppFilePath := GetCurrentDir;
pcAppUserDirectory := (GetWindowsSpecialDir(CSIDL_PERSONAL)) + pcAppFileName;
// The following directories are created by the INNO Setup Script
pcAppSettingsDirectory := pcAppUserDirectory + '\' + cstrSettingsDirectoryName;
pcAppLogbooksDirectory := pcAppUserDirectory + '\' + cstrLogbooksDirectoryName;
pcAppBackupsDirectory := pcAppUserDirectory + '\' + cstrBackupsDirectoryName;
pcAppDataDirectory := pcAppUserDirectory + '\' + cstrApPDataDirectoryName;
pcAppDatabaseName := pcAppDataDirectory + '\' + cstrApplicationDBName;
//====================================================
// Initialize the Data Components
//====================================================
DBConnection.DatabaseName := pcAppDatabaseName;
DBConnection.Transaction := DBTransaction;
sqlqApplicationSettingsTable.DataBase := DBConnection;
sqlqApplicationSettingsTable.DataSource := dsApplicationSettingsTable;
sqlqRegistrationSettingsTable.DataBase := DBConnection;
sqlqRegistrationSettingsTable.DataSource := dsRegistrationSettingsTable;
//====================================================
// Initialize the Controls
//====================================================
// PageControl properties
pgDirectories.Caption:=straryPageNames[0];
pgApplicationSettings.Caption:=straryPageNames[1];
pgRegistrationSettings.Caption:=straryPageNames[2];
pgSettingsDB.Caption:=straryPageNames[3];
// strgApplicationSettings properties
strgrdApplicationSettings.AutoFillColumns := True;
strgrdApplicationSettings.AutoSizeColumns;
// strgRegistrationSettings properties
strgrdRegistrationSettings.AutoFillColumns := True;
strgrdRegistrationSettings.AutoSizeColumns;
end;// procedure TfrmSettings.FormCreate
//----------------------------------------------------------------------------------------
procedure TfrmSettings.FormShow(Sender: TObject);
var
vstrTstr : string;
vintTInt : Integer;
begin
//=======================
// initialize form controls
//=======================
// Command Buttons
// Directories Page
edtApplicationDirectory.Text:= pcAppFilePath;
edtSettingsDirectory.Text:=pcAppSettingsDirectory;
edtLogbooksDirectory.Text:=pcAppLogbooksDirectory;
edtBackupsDirectory.Text := pcAppBackupsDirectory;
edtAppDataDirectory.Text := pcAppDataDirectory;
// Application Settings Page
// strgApplicationSettings
strgrdApplicationSettings.Cells[0,1] := 'pAppSettingsInitialPageNum';
strgrdApplicationSettings.Cells[1,1] := pAppSettingsInitialPageNum;
strgrdApplicationSettings.Cells[0,2] := 'pAppSettingsInitialPageName';
strgrdApplicationSettings.Cells[1,2] := pAppSettingsInitialPageName;
// strgRegistrationSettings
strgrdRegistrationSettings.Cells[0,1] := 'dlgHURegistration.pRegFirstName';
strgrdRegistrationSettings.Cells[1,1] := dlgHURegistration.pRegFirstName;
strgrdRegistrationSettings.Cells[0,2] := 'dlgHURegistration.pRegLastName';
strgrdRegistrationSettings.Cells[1,2] := dlgHURegistration.pRegLastName;
strgrdRegistrationSettings.Cells[0,3] := 'dlgHURegistration.pRegEmailAddress';
strgrdRegistrationSettings.Cells[1,3] := dlgHURegistration.pRegEmailAddress;
strgrdRegistrationSettings.Cells[0,4] := 'dlgHURegistration.pRegCallsign';
strgrdRegistrationSettings.Cells[1,4] := dlgHURegistration.pRegCallsign;
strgrdRegistrationSettings.Cells[0,5] := 'dlgHURegistration.pRegKey';
strgrdRegistrationSettings.Cells[1,5] := dlgHURegistration.pRegKey;
strgrdRegistrationSettings.Cells[0,6] := 'dlgHURegistration.pRegUserID';
strgrdRegistrationSettings.Cells[1,6] := dlgHURegistration.pRegUserID;
end;// procedure TfrmAppSetup.FormShow
//----------------------------------------------------------------------------------------
procedure TfrmSettings.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
//DBConnection.Connected := False;
end;// procedure TfrmAppSetup.FormClose
//========================================================================================
end.// unit AppSettings
|
unit HlpBlake2STreeConfig;
{$I ..\..\Include\HashLib.inc}
interface
uses
HlpIBlake2STreeConfig,
HlpHashLibTypes;
resourcestring
SInvalidFanOutParameter =
'FanOut Value Should be Between [0 .. 255] for Blake2S';
SInvalidMaxDepthParameter =
'FanOut Value Should be Between [1 .. 255] for Blake2S';
SInvalidNodeDepthParameter =
'NodeDepth Value Should be Between [0 .. 255] for Blake2S';
SInvalidInnerHashSizeParameter =
'InnerHashSize Value Should be Between [0 .. 32] for Blake2S';
SInvalidNodeOffsetParameter =
'NodeOffset Value Should be Between [0 .. (2^48-1)] for Blake2S';
type
TBlake2STreeConfig = class sealed(TInterfacedObject, IBlake2STreeConfig)
strict private
FFanOut, FMaxDepth, FNodeDepth, FInnerHashSize: Byte;
FLeafSize: UInt32;
FNodeOffset: UInt64;
FIsLastNode: Boolean;
procedure ValidateFanOut(AFanOut: Byte); inline;
procedure ValidateInnerHashSize(AInnerHashSize: Byte); inline;
procedure ValidateMaxDepth(AMaxDepth: Byte); inline;
procedure ValidateNodeDepth(ANodeDepth: Byte); inline;
procedure ValidateNodeOffset(ANodeOffset: UInt64); inline;
function GetFanOut: Byte; inline;
procedure SetFanOut(value: Byte); inline;
function GetMaxDepth: Byte; inline;
procedure SetMaxDepth(value: Byte); inline;
function GetNodeDepth: Byte; inline;
procedure SetNodeDepth(value: Byte); inline;
function GetInnerHashSize: Byte; inline;
procedure SetInnerHashSize(value: Byte); inline;
function GetLeafSize: UInt32; inline;
procedure SetLeafSize(value: UInt32); inline;
function GetNodeOffset: UInt64; inline;
procedure SetNodeOffset(value: UInt64); inline;
function GetIsLastNode: Boolean; inline;
procedure SetIsLastNode(value: Boolean); inline;
public
constructor Create();
property FanOut: Byte read GetFanOut write SetFanOut;
property MaxDepth: Byte read GetMaxDepth write SetMaxDepth;
property NodeDepth: Byte read GetNodeDepth write SetNodeDepth;
property InnerHashSize: Byte read GetInnerHashSize write SetInnerHashSize;
property LeafSize: UInt32 read GetLeafSize write SetLeafSize;
property NodeOffset: UInt64 read GetNodeOffset write SetNodeOffset;
property IsLastNode: Boolean read GetIsLastNode write SetIsLastNode;
end;
implementation
{ TBlake2STreeConfig }
procedure TBlake2STreeConfig.ValidateFanOut(AFanOut: Byte);
begin
if not(AFanOut in [0 .. 255]) then
begin
raise EArgumentInvalidHashLibException.CreateRes(@SInvalidFanOutParameter);
end;
end;
procedure TBlake2STreeConfig.ValidateInnerHashSize(AInnerHashSize: Byte);
begin
if not(AInnerHashSize in [0 .. 32]) then
begin
raise EArgumentInvalidHashLibException.CreateRes
(@SInvalidInnerHashSizeParameter);
end;
end;
procedure TBlake2STreeConfig.ValidateMaxDepth(AMaxDepth: Byte);
begin
if not(AMaxDepth in [1 .. 255]) then
begin
raise EArgumentInvalidHashLibException.CreateRes
(@SInvalidMaxDepthParameter);
end;
end;
procedure TBlake2STreeConfig.ValidateNodeDepth(ANodeDepth: Byte);
begin
if not(ANodeDepth in [0 .. 255]) then
begin
raise EArgumentInvalidHashLibException.CreateRes
(@SInvalidNodeDepthParameter);
end;
end;
procedure TBlake2STreeConfig.ValidateNodeOffset(ANodeOffset: UInt64);
begin
if ANodeOffset > UInt64((UInt64(1) shl 48) - 1) then
begin
raise EArgumentInvalidHashLibException.CreateRes
(@SInvalidNodeOffsetParameter);
end;
end;
function TBlake2STreeConfig.GetFanOut: Byte;
begin
result := FFanOut;
end;
function TBlake2STreeConfig.GetInnerHashSize: Byte;
begin
result := FInnerHashSize;
end;
function TBlake2STreeConfig.GetIsLastNode: Boolean;
begin
result := FIsLastNode;
end;
function TBlake2STreeConfig.GetLeafSize: UInt32;
begin
result := FLeafSize;
end;
function TBlake2STreeConfig.GetMaxDepth: Byte;
begin
result := FMaxDepth;
end;
function TBlake2STreeConfig.GetNodeDepth: Byte;
begin
result := FNodeDepth;
end;
function TBlake2STreeConfig.GetNodeOffset: UInt64;
begin
result := FNodeOffset;
end;
procedure TBlake2STreeConfig.SetFanOut(value: Byte);
begin
ValidateFanOut(value);
FFanOut := value;
end;
procedure TBlake2STreeConfig.SetInnerHashSize(value: Byte);
begin
ValidateInnerHashSize(value);
FInnerHashSize := value;
end;
procedure TBlake2STreeConfig.SetIsLastNode(value: Boolean);
begin
FIsLastNode := value;
end;
procedure TBlake2STreeConfig.SetLeafSize(value: UInt32);
begin
FLeafSize := value;
end;
procedure TBlake2STreeConfig.SetMaxDepth(value: Byte);
begin
ValidateMaxDepth(value);
FMaxDepth := value;
end;
procedure TBlake2STreeConfig.SetNodeDepth(value: Byte);
begin
ValidateNodeDepth(value);
FNodeDepth := value;
end;
procedure TBlake2STreeConfig.SetNodeOffset(value: UInt64);
begin
ValidateNodeOffset(value);
FNodeOffset := value;
end;
constructor TBlake2STreeConfig.Create;
begin
Inherited Create();
ValidateInnerHashSize(32);
FInnerHashSize := 32;
end;
end.
|
unit BrowserEmulationAdjuster;
interface
uses
Winapi.Windows, System.IOUtils, System.SysUtils, System.Classes, Winapi.Messages, System.Win.Registry;
type TBrowserEmulationAdjuster = class
private
class function GetExeName(): String; inline;
public const
// Quelle: https://msdn.microsoft.com/library/ee330730.aspx, Stand: 2017-04-26
IE11_default = 11000;
IE11_Quirks = 11001;
IE10_force = 10001;
IE10_default = 10000;
IE9_Quirks = 9999;
IE9_default = 9000;
/// <summary>
/// Webpages containing standards-based !DOCTYPE directives are displayed in IE7
/// Standards mode. Default value for applications hosting the WebBrowser Control.
/// </summary>
IE7_embedded = 7000;
public
class procedure SetBrowserEmulationDWORD(const value: DWORD);
end platform;
implementation
class function TBrowserEmulationAdjuster.GetExeName(): String;
begin
Result := TPath.GetFileName( ParamStr(0) );
end;
class procedure TBrowserEmulationAdjuster.SetBrowserEmulationDWORD(const value: DWORD);
const registryPath = 'Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION';
var
registry: TRegistry;
exeName: String;
begin
exeName := GetExeName();
registry := TRegistry.Create(KEY_SET_VALUE);
try
registry.RootKey := HKEY_CURRENT_USER;
Win32Check( registry.OpenKey(registryPath, True) );
registry.WriteInteger(exeName, value)
finally
registry.Destroy();
end;
end;
end.
|
unit uDMValidatePOTextFile;
interface
uses
Dialogs, SysUtils, Classes, Variants, ADODB, DB, uDMCalcPrice,
uDMImportTextFile, uDMValidateTextFile, DBClient;
type
TDMValidatePOTextFile = class(TDMValidateTextFile)
qryPoItemList: TADOQuery;
quModelExist: TADODataSet;
qryMaxBarcode: TADOQuery;
private
IsClientServer: Boolean;
bUseMarkupOnCost : Boolean;
FDMCalcPrice: TDMCalcPrice;
procedure ValidatePOItem;
procedure OpenPoItemList(PONumber : Integer);
function GetIDVendor(Vendor: String): Integer;
function FindModelWithVendorCode: Boolean;
function FindModelWithBarcode: Boolean;
procedure ClosePoItemList;
procedure CalcSaleValues(CostPrice:Currency);
function GetValidModelCode: String;
procedure InvalidByQty(AField : String);
procedure InvalidByBarcode;
procedure InvalidByCostPrice(AField : String);
function ExistsModelName(Model: String): Boolean;
function GetModelMarkup(IDModel : Integer) : Double;
procedure InvalidByModelName;
procedure ValidByModelName;
procedure FilterSameBarcode;
procedure WarningDiferCost(OldCost: Currency);
function GetMaxBarcodeOrder(IDModel: Integer): Integer;
procedure FormatCost;
procedure ImportFromMainRetail;
procedure ImportFromFile;
function ImportFromCatalog: Boolean;
procedure UpdateModelWithCatalog;
function CalcCostUnitValue(Cost, CaseCost: Currency; Qty, CaseQty: Double; QtyType: String; CostIsCaseCost: Boolean): Currency;
function CalcCaseCost(Cost, CaseCost: Currency; CaseQty: Double; CostIsCaseCost: Boolean): Currency;
procedure WarningPromoCost;
procedure InvalidByClientServer;
procedure SetDefaultValues;
function getSellingPriceObeyIncreasyOnly(idmodel: integer; price: Currency): Currency; virtual;
public
function ValidateModels: Boolean;
function Validate: Boolean; override;
function NotExistsPurchaseNum(PurchaseNum,Vendor : String): Boolean;
function ExistsPONum(PONum: String): Boolean;
Function ValidateItem: Boolean;
end;
implementation
uses uNumericFunctions, uDMGlobal, uSystemConst, uObjectServices,
uContentClasses, uDebugFunctions;
{$R *.dfm}
{ TDMValidatePOTextFile }
procedure TDMValidatePOTextFile.OpenPoItemList(PONumber : Integer);
begin
with qryPoItemList do
begin
if Active then
Close;
Connection := SQLConnection;
Parameters.ParamByName('DocumentID').Value := PONumber;
Open;
end;
end;
function TDMValidatePOTextFile.Validate: Boolean;
var
FileCaseQty: Double;
bUseCatalog, CostIsCaseCost, PromoCost: Boolean;
NewCostPrice, FileCaseCost, NewCaseCost: Currency;
begin
IsClientServer := DMGlobal.IsClientServer(SQLConnection);
FDMCalcPrice := TDMCalcPrice.Create(Self);
try
FDMCalcPrice.SetConnection(SQLConnection);
FDMCalcPrice.UseMargin := DMGlobal.GetSvrParam(PARAM_CALC_MARGIN ,SQLConnection);
FDMCalcPrice.UseRound := DMGlobal.GetSvrParam(PARAM_CALC_ROUNDING, SQLConnection);
bUseCatalog := DMGlobal.GetSvrParam(PARAM_USE_CATALOG, SQLConnection);
bUseMarkupOnCost := DMGlobal.GetSvrParam(PARAM_TAX_COST_USE_MARKUP_ON_COST, SQLConnection);
CostIsCaseCost := (ImpExpConfig.Values['CostIsCaseCost'] = 'True');
// - Cacula o valor de venda e msrp
TextFile.First;
while not TextFile.Eof do
begin
begin
FileCaseQty := 0;
FileCaseCost := 0;
NewCostPrice := 0;
NewCaseCost := 0;
PromoCost := False;
TextFile.Edit;
TextFile.FieldByName('Warning').AsString:= '';
if LinkedColumns.Values['CaseCost'] <> '' then
begin
if TextFile.FieldByName('FieldCostCalc').AsString = '' then
TextFile.FieldByName('FieldCostCalc').AsString := TextFile.FieldByName(LinkedColumns.Values['CaseCost']).AsString
else
TextFile.FieldByName(LinkedColumns.Values['CaseCost']).AsString := TextFile.FieldByName('FieldCostCalc').AsString;
end;
if (TextFile.FieldByName('QtyType').AsString <> 'EA') then
begin
FileCaseQty := MyStrToFloat(TextFile.FieldByName('CaseQty').AsString);
if LinkedColumns.Values['CaseCost'] <> '' then
FileCaseCost := MyStrToFloat(TextFile.FieldByName(LinkedColumns.Values['CaseCost']).AsString)
else
FileCaseCost := MyStrToFloat(TextFile.FieldByName('CaseCost').AsString);
end;
if (LinkedColumns.Values['PromoFlat'] <> '') and
((TextFile.FieldByName(LinkedColumns.Values['PromoFlat']).AsString = 'Y') or
(TextFile.FieldByName(LinkedColumns.Values['PromoFlat']).AsString = '1')) then
begin
PromoCost := True;
WarningPromoCost;
end;
// VALIDATE MODEL
if TextFile.FieldByName('NewModel').AsBoolean then
if (TextFile.FieldByName('Model').AsString <> '') and (ExistsModelName(TextFile.FieldByName('Model').AsString)) then
InvalidByModelName;
// VALIDATE QTY
if (TextFile.FieldByName(LinkedColumns.Values['Qty']).AsString = '') or
(TextFile.FieldByName(LinkedColumns.Values['Qty']).AsFloat = 0) then
InvalidByQty('Qty');
// VALIDATE COST PRICE
if (TextFile.FieldByName(LinkedColumns.Values['NewCostPrice']).AsString = '') or
(TextFile.FieldByName(LinkedColumns.Values['NewCostPrice']).AsCurrency = 0) then
InvalidByCostPrice('NewCostPrice');
if TextFile.FieldByName('Validation').AsBoolean then
begin
NewCostPrice := FDMCalcPrice.FormatPrice(CalcCostUnitValue(TextFile.FieldByName(LinkedColumns.Values['NewCostPrice']).AsCurrency,
FileCaseCost,
TextFile.FieldByName(LinkedColumns.Values['Qty']).AsFloat,
FileCaseQty,
TextFile.FieldByName('QtyType').AsString,
CostIsCaseCost));
NewCaseCost := FDMCalcPrice.FormatPrice(CalcCaseCost(NewCostPrice,FileCaseCost,FileCaseQty,CostIsCaseCost));
if not(TextFile.State = (dsEdit)) then
TextFile.Edit;
TextFile.FieldByName(LinkedColumns.Values['NewCostPrice']).AsCurrency := NewCostPrice;
TextFile.FieldByName('CaseCost').AsCurrency := NewCaseCost;
FormatCost;
// amfsouza
// showMessage('IdGroup = ' + TextFile.FieldByName('IDGroup').AsString);
if (TextFile.FieldByName('IDGroup').AsInteger <> 0) then
CalcSaleValues(TextFile.FieldByName(LinkedColumns.Values['NewCostPrice']).AsCurrency);
if (bUseCatalog) and not(TextFile.FieldByName('NewModel').AsBoolean) then
UpdateModelWithCatalog;
if (TextFile.FieldByName('OldCostPrice').AsCurrency <> 0) and
(TextFile.FieldByName('OldCostPrice').AsCurrency <> TextFile.FieldByName(LinkedColumns.Values['NewCostPrice']).AsCurrency) then
WarningDiferCost(TextFile.FieldByName('OldCostPrice').AsCurrency);
end;
end;
if TextFile.State = (dsEdit) then
TextFile.Post;
TextFile.Next;
end;
if not(ImpExpConfig.Values['PONumber'] = '') then
begin
OpenPoItemList(StrtoInt(ImpExpConfig.Values['PONumber']));
TextFile.First;
while not TextFile.Eof do
begin
if TextFile.FieldByName('Validation').AsBoolean then
ValidatePOItem;
TextFile.Next;
end;
ClosePoItemList;
end;
Result := True;
finally
FreeAndNil(FDMCalcPrice);
end;
end;
function TDMValidatePOTextFile.CalcCaseCost(Cost, CaseCost: Currency; CaseQty: Double; CostIsCaseCost: Boolean): Currency;
begin
Result := 0;
if CaseQty <> 0 then
if (CaseCost = 0) and CostIsCaseCost then
Result := Cost
else if (CaseCost = 0) then
Result := (Cost * CaseQty)
else
Result := CaseCost;
end;
function TDMValidatePOTextFile.CalcCostUnitValue(Cost, CaseCost: Currency; Qty, CaseQty: Double; QtyType: String; CostIsCaseCost: Boolean): Currency;
begin
Result := Cost;
if (QtyType = 'EA') then
Result := Cost
else if (CaseQty <> 0) and (CaseCost <> 0) then
Result := CaseCost / CaseQty
else if (CaseQty <> 0) and (CaseCost = 0) and CostIsCaseCost then
Result := Cost / CaseQty
else if (CaseQty <> 0) and (CaseCost = 0) and not(CostIsCaseCost) then
Result := Cost;
end;
procedure TDMValidatePOTextFile.FormatCost;
var
DecimalPoint : string;
begin
if not (TextFile.State = (dsEdit)) then
TextFile.Edit;
DecimalPoint := ImpExpConfig.Values['DecimalDelimiter'];
if (LinkedColumns.Values['NewCostPrice'] <> '') then
TextFile.FieldByName(LinkedColumns.Values['NewCostPrice']).AsCurrency := FDMCalcPrice.FormatPrice(MyStrToDouble(VarToStr(TextFile.FieldByName(LinkedColumns.Values['NewCostPrice']).Value), DecimalPoint[1]));
if (LinkedColumns.Values['OtherCost'] <> '') then
TextFile.FieldByName(LinkedColumns.Values['OtherCost']).AsCurrency := FDMCalcPrice.FormatPrice(MyStrToDouble(VarToStr(TextFile.FieldByName(LinkedColumns.Values['OtherCost']).Value), DecimalPoint[1]));
if (LinkedColumns.Values['FreightCost'] <> '') then
TextFile.FieldByName(LinkedColumns.Values['FreightCost']).AsCurrency := FDMCalcPrice.FormatPrice(MyStrToDouble(VarToStr(TextFile.FieldByName(LinkedColumns.Values['FreightCost']).Value), DecimalPoint[1]));
if (LinkedColumns.Values['CaseCost'] <> '') then
TextFile.FieldByName(LinkedColumns.Values['CaseCost']).AsCurrency := FDMCalcPrice.FormatPrice(MyStrToDouble(VarToStr(TextFile.FieldByName(LinkedColumns.Values['CaseCost']).Value), DecimalPoint[1]));
TextFile.FieldByName('OldCostPrice').AsCurrency := FDMCalcPrice.FormatPrice(MyStrToDouble(VarToStr(TextFile.FieldByName('OldCostPrice').Value), DecimalPoint[1]));
end;
procedure TDMValidatePOTextFile.WarningDiferCost(OldCost : Currency);
begin
if not (TextFile.State = (dsEdit)) then
TextFile.Edit;
if TextFile.FieldByName('Warning').AsString <> '' then
TextFile.FieldByName('Warning').AsString := TextFile.FieldByName('Warning').AsString + '; Old Cost: ' + SysCurrToStr(OldCost)
else
TextFile.FieldByName('Warning').AsString := 'Old Cost: ' + SysCurrToStr(OldCost);
end;
procedure TDMValidatePOTextFile.WarningPromoCost;
begin
if not (TextFile.State = (dsEdit)) then
TextFile.Edit;
if TextFile.FieldByName('Warning').AsString <> '' then
TextFile.FieldByName('Warning').AsString := TextFile.FieldByName('Warning').AsString + '; Promo Cost'
else
TextFile.FieldByName('Warning').AsString := 'Promo Cost';
end;
function TDMValidatePOTextFile.ExistsModelName(Model : String): Boolean;
begin
with DMGlobal.qryFreeSQL do
begin
if Active then
Close;
SQL.Text := ' SELECT Model FROM Model WHERE Model = ' + QuotedStr(Model);
Open;
Result := not(IsEmpty);
Close;
end;
end;
procedure TDMValidatePOTextFile.InvalidByModelName;
begin
if not (TextFile.State = (dsEdit)) then
TextFile.Edit;
TextFile.FieldByName('Validation').AsBoolean := False;
TextFile.FieldByName('Warning').AsString := 'Model Exists';
end;
procedure TDMValidatePOTextFile.ValidByModelName;
begin
if not (TextFile.State = (dsEdit)) then
TextFile.Edit;
TextFile.FieldByName('Validation').AsBoolean := True;
TextFile.FieldByName('Warning').AsString := '';
end;
procedure TDMValidatePOTextFile.InvalidByQty(AField : String);
begin
if not (TextFile.State = (dsEdit)) then
TextFile.Edit;
TextFile.FieldByName('Validation').AsBoolean := False;
TextFile.FieldByName('Warning').AsString := 'Invalid Item ' + AField;
end;
procedure TDMValidatePOTextFile.ValidatePOItem;
var
PreInventoryQty, TextQty : Double;
Friend : Variant;
begin
PreInventoryQty := 0;
if not(TextFile.FieldByName('IDModel').AsString = '') then
begin
Friend := qryPoItemList.Lookup('ModelID',TextFile.FieldByName('IDModel').AsString,'Qty');
if Friend <> Null then
PreInventoryQty := Friend;
end;
TextQty := MyStrToFloat(TextFile.FieldByName(LinkedColumns.Values['Qty']).AsString);
if PreInventoryQty = 0 then
begin
TextFile.Edit;
if TextFile.FieldByName('Warning').AsString = '' then
TextFile.FieldByName('Warning').AsString := 'Item not registered in PO'
else
TextFile.FieldByName('Warning').AsString := TextFile.FieldByName('Warning').AsString + '; Item not registered in PO'
end
else if PreInventoryQty > TextQty then
begin
TextFile.Edit;
TextFile.FieldByName('Warning').AsString := 'Amount in the MainRetail is greater then file';
end
else if PreInventoryQty < TextQty then
begin
TextFile.Edit;
TextFile.FieldByName('Warning').AsString := 'Amount in the file is greater then MainRetail';
end;
end;
function TDMValidatePOTextFile.GetIDVendor(Vendor: String): Integer;
begin
with DMGlobal.qryFreeSQL do
begin
if Active then
Close;
Connection := SQLConnection;
SQL.Text := 'SELECT IDPessoa from Pessoa '+
' WHERE Pessoa = ' + QuotedStr(Vendor) + ' AND IDTipoPessoa = 2 ';
Open;
end;
if DMGlobal.qryFreeSQL.IsEmpty then
Result := -1
else
Result := DMGlobal.qryFreeSQL.Fields.FieldByName('IDPessoa').AsInteger;
end;
function TDMValidatePOTextFile.FindModelWithBarcode: Boolean;
var
Barcode, sNewBarcode, sSQL : String;
iCheckBarcodeDigit, BarcodeOrder : Integer;
SearchModel : Boolean;
begin
Result := False;
Barcode := TextFile.FieldByName(LinkedColumns.Values['Barcode']).AsString;
sSQL := ' SELECT M.IDModel, M.GroupID, M.IDModelGroup, M.IDModelSubGroup, M.CaseQty, '+
' M.SellingPrice, M.SuggRetail, M.VendorCost ' +
' FROM Barcode B JOIN Model M ON (M.IDModel = B.IDModel) ' +
' WHERE B.IDBarcode = ' ;
with DMGlobal.qryFreeSQL do
try
if Active then
Close;
Connection := SQLConnection;
SQL.Text := sSQL + QuotedStr(Barcode);
Open;
SearchModel := DMGlobal.GetSvrParam(PARAM_SEARCH_MODEL_AFTER_BARCODE, SQLConnection);
if IsEmpty and SearchModel then
begin
if Active then
Close;
Connection := SQLConnection;
SQL.Text := ' SELECT Model, IDModel, GroupID, IDModelGroup, IDModelSubGroup, CaseQty, '+
' SellingPrice, SuggRetail, VendorCost ' +
' FROM Model WHERE Model = ' + QuotedStr(Barcode);
Open;
end;
iCheckBarcodeDigit := DMGlobal.GetSvrParam(PARAM_REMOVE_BARCODE_DIGIT, SQLConnection);
if IsEmpty and (iCheckBarcodeDigit <> 0) and (Length(Barcode)>2) then
begin
if Active then
Close;
Case iCheckBarcodeDigit of
1 : sNewBarcode := Copy(Barcode, 2, Length(Barcode));
2 : sNewBarcode := Copy(Barcode, 1, Length(Barcode)-1);
3 : sNewBarcode := Copy(Barcode, 2, Length(Barcode)-2)
else sNewBarcode := Copy(Barcode, 2, Length(Barcode)-2);
end;
SQL.Text := sSQL + QuotedStr(sNewBarcode);
Open;
if not(IsEmpty) then
begin
BarcodeOrder := GetMaxBarcodeOrder(FieldByName('IDModel').AsInteger);
DMGlobal.ExecuteSQL(
' IF NOT EXISTS (SELECT IDBarcode FROM Barcode WHERE IDBarcode = '+QuotedStr(Barcode)+')' +
' BEGIN ' +
' INSERT Barcode (IDBarcode, IDModel, Data, BarcodeOrder) ' +
' SELECT ' + QuotedStr(Barcode)+ ', M.IDModel, GetDate(), ' + InttoStr(BarcodeOrder + 1) +
' FROM Barcode B ' +
' JOIN Model M ON (M.IDModel = B.IDModel) ' +
' WHERE IDBarcode = ' + QuotedStr(sNewBarcode) +
' END ', SQLConnection);
end;
end;
if not IsEmpty then
begin
ImportFromMainRetail;
Result := True;
end
else
Result := False;
finally
Close;
end;
end;
function TDMValidatePOTextFile.GetMaxBarcodeOrder(IDModel: Integer): Integer;
begin
with qryMaxBarcode do
try
if Active then
Close;
Connection := SQLConnection;
Parameters.ParamByName('IDModel').Value := IDModel;
Open;
Result := FieldByName('BarcodeOrder').AsInteger
finally
Close;
end;
end;
function TDMValidatePOTextFile.FindModelWithVendorCode: Boolean;
begin
Result := False;
TextFile.Edit;
with DMGlobal.qryFreeSQL do
begin
try
if Active then
Close;
Connection := SQLConnection;
SQL.Text := ' SELECT M.IDModel, M.GroupID, M.IDModelGroup, M.IDModelSubGroup, V.VendorCode FROM VendorModelCode V JOIN Model M ON (M.IDModel = V.IDModel) ' +
' WHERE IDPessoa = ' + QuotedStr(InttoStr(GetIDVendor(ImpExpConfig.Values['Vendor']))) +
' AND VendorCode = ' + QuotedStr(LinkedColumns.Values['VendorCode']);
Open;
if not(IsEmpty) then
begin
TextFile.Edit;
TextFile.FieldByName('IDGroup').AsInteger := DMGlobal.qryFreeSQL.FieldByName('GroupID').AsInteger;
TextFile.FieldByName('IDModelGroup').AsInteger := DMGlobal.qryFreeSQL.FieldByName('IDModelGroup').AsInteger;
TextFile.FieldByName('IDModelSubGroup').AsInteger := DMGlobal.qryFreeSQL.FieldByName('IDModelSubGroup').AsInteger;
TextFile.FieldByName('IDModel').AsInteger := DMGlobal.qryFreeSQL.FieldByName('IDModel').AsInteger;
TextFile.FieldByName('VendorModelCode').AsString := DMGlobal.qryFreeSQL.FieldByName('VendorCode').AsString;
TextFile.Post;
Result := True;
end;
finally
Close;
end;
end;
end;
procedure TDMValidatePOTextFile.ClosePoItemList;
begin
with qryPoItemList do
begin
if Active then
Close;
end;
end;
function TDMValidatePOTextFile.NotExistsPurchaseNum(
PurchaseNum, Vendor: String): Boolean;
begin
with DMGlobal.qryFreeSQL do
begin
try
if Active then
Close;
Connection := SQLConnection;
SQL.Text := ' SELECT DocumentNumber, IDStore FROM Pur_Purchase '+
' WHERE DocumentNumber = ' + QuotedStr(PurchaseNum) +
' AND IDFornecedor = ' + InttoStr(GetIDVendor(Vendor));
Open;
if IsEmpty then
Result := True
else
Result := False;
finally
Close;
end;
end;
end;
procedure TDMValidatePOTextFile.CalcSaleValues(CostPrice:Currency);
var
fNewSale, fNewMSRP : Currency;
fMakrup : Double;
begin
if IsClientServer then
begin
// DebugToFile('begin - step 1');
fNewSale := TextFile.FieldByName('OldSalePrice').AsCurrency;
//amfsouza 11.11.2011
fNewSale := getSellingPriceObeyIncreasyOnly(TextFile.FieldByName('IDModel').AsInteger,
fNewSale);
fNewMSRP := TextFile.FieldByName('NewMSRP').AsCurrency;
// debugToFile('end - step 1');
end
else
begin
// debugtofile('begin - step 2 ');
fMakrup := GetModelMarkup(TextFile.FieldByName('IDModel').AsInteger);
if fMakrup <> 0 then
begin
if bUseMarkupOnCost then
fNewSale := FDMCalcPrice.GetMarkupPrice(CostPrice, fMakrup)
else if (fMakrup < 100) then
fNewSale := FDMCalcPrice.GetMarginPrice(CostPrice, fMakrup);
fNewSale := FDMCalcPrice.CalcRounding(TextFile.FieldByName('IDGroup').AsInteger, fNewSale);
//amfsouza 11.11.2011
fNewSale := getSellingPriceObeyIncreasyOnly(TextFile.FieldByName('IDModel').AsInteger,
fNewSale);
// debugtofile('end- stop 2 ');
end
else
begin
// debugToFile('begin- step 3');
// debugtofile('description = ' + TextFile.FieldByName('description').AsString);
fNewSale := FDMCalcPrice.CalcSalePrice(TextFile.FieldByName('IDModel').AsInteger,
TextFile.FieldByName('IDGroup').AsInteger,
TextFile.FieldByName('IDModelGroup').AsInteger,
TextFile.FieldByName('IDModelSubGroup').AsInteger,
CostPrice);
// debugtofile('new sale from calcprice = ' + floatTostr(fNewSale));
//amfsouza 11.11.2011
fNewSale := getSellingPriceObeyIncreasyOnly
(TextFile.FieldByName('IDModel').AsInteger,
fNewSale);
// debugtofile('new sale from increay only = ' + floatTostr(fNewSale));
fNewMSRP := FDMCalcPrice.CalcMSRPPrice(TextFile.FieldByName('IDGroup').AsInteger,
TextFile.FieldByName('IDModelGroup').AsInteger,
TextFile.FieldByName('IDModelSubGroup').AsInteger,
CostPrice);
// debugtofile('new MSRP = ' + floatTostr(fNewMSRP));
// debugtofile('end - step 3');
end;
end;
if not (TextFile.State = (dsEdit)) then
TextFile.Edit;
// debugtofile('begin - step 4');
if (fNewSale <> CostPrice) and (fNewSale <> 0) then begin
TextFile.FieldByName('NewSalePrice').AsCurrency := fNewSale;
end
else begin
TextFile.FieldByName('NewSalePrice').AsCurrency := TextFile.FieldByName('OldSalePrice').AsCurrency;
end;
// debugtofile('end - step 4');
// debugtofile('begin - step 5');
if (fNewMSRP <> CostPrice) and (fNewMSRP <> 0) then
TextFile.FieldByName('NewMSRP').AsCurrency := fNewMSRP
else
TextFile.FieldByName('NewMSRP').AsCurrency;
// debugtofile('end - step 5');
end;
function TDMValidatePOTextFile.ValidateModels: Boolean;
begin
IsClientServer := DMGlobal.IsClientServer(SQLConnection);
TextFile.First;
while not TextFile.Eof do
begin
if (LinkedColumns.Values['Barcode'] <> '') then
begin
if ((LinkedColumns.Values['VendorCode'] = '') or not(FindModelWithVendorCode)) then
begin
if ValidateItem then
begin
SetDefaultValues;
if not FindModelWithBarcode then
begin
if IsClientServer then
InvalidByClientServer
else
if not ImportFromCatalog then
ImportFromFile;
end;
end;
end;
end
else
InvalidByBarcode;
if TextFile.State = (dsEdit) then
TextFile.Post;
TextFile.Next;
end;
FilterSameBarcode;
end;
procedure TDMValidatePOTextFile.SetDefaultValues;
begin
TextFile.Edit;
if (LinkedColumns.Values['VendorCode'] <> '') then
TextFile.FieldByName('VendorModelCode').AsString := TextFile.FieldByName(LinkedColumns.Values['VendorCode']).AsString;
if (LinkedColumns.Values['MinQty'] <> '') then
TextFile.FieldByName('MinQtyPO').AsFloat := TextFile.FieldByName(LinkedColumns.Values['MinQty']).AsFloat;
TextFile.Post;
end;
procedure TDMValidatePOTextFile.FilterSameBarcode;
var
i : Integer;
cdsSupport: TClientDataSet;
begin
cdsSupport := TClientDataSet.Create(self);
try
cdsSupport.CloneCursor(TextFile,true);
cdsSupport.Data := TextFile.Data;
TextFile.First;
while not TextFile.Eof do
TextFile.Delete;
with cdsSupport do
begin
//Filter := 'Validation = True';
//Filtered := true;
First;
while not Eof do
begin
if TextFile.Locate(LinkedColumns.Values['Barcode'],FieldByName(LinkedColumns.Values['Barcode']).AsString, []) then
begin
TextFile.Edit;
if(cdsSupport.FieldByName(LinkedColumns.Values['Qty']).AsString='') then
begin
cdsSupport.Edit;
cdsSupport.FieldByName(LinkedColumns.Values['Qty']).AsString := '0';
cdsSupport.Post;
end;
TextFile.FieldByName(LinkedColumns.Values['Qty']).AsFloat := (TextFile.FieldByName(LinkedColumns.Values['Qty']).AsFloat + FieldByName(LinkedColumns.Values['Qty']).AsFloat);
end
else
begin
TextFile.Append;
for i:= 0 to Pred(TextFile.Fields.Count) do
TextFile.Fields[i].Value := Fields[i].Value;
TextFile.Post;
end;
Next;
end;
end;
finally
FreeAndNil(cdsSupport);
end;
end;
function TDMValidatePOTextFile.GetValidModelCode: String;
var
bValidModel: Boolean;
begin
bValidModel := False;
while not bValidModel do
try
Result := IntToStr(DMGlobal.GetNextCode('Model','Model', SQLConnection));
quModelExist.Connection := SQLConnection;
quModelExist.Parameters.ParamByName('Model').Value := Result;
quModelExist.Open;
bValidModel := quModelExist.IsEmpty;
finally
quModelExist.Close;
end;
end;
function TDMValidatePOTextFile.ImportFromCatalog: Boolean;
var
FileCaseQty: Double;
sBarcodeValue: String;
Barcode: TBarcode;
Model: TModel;
Vendor: TVendor;
BarcodeService: TCatalogBarcodeService;
ModelService: TCatalogModelService;
begin
Result := False;
if DMGlobal.GetSvrParam(PARAM_USE_CATALOG, SQLConnection) then
begin
Barcode := TBarcode.Create;
Model := TModel.Create;
Vendor := TVendor.Create;
BarcodeService := TCatalogBarcodeService.Create;
BarcodeService.SQLConnection := Self.SQLConnection;
if (LinkedColumns.Values['CaseQty'] <> '') then
FileCaseQty := MyStrToFloat(TextFile.FieldByName(LinkedColumns.Values['CaseQty']).AsString)
else
FileCaseQty := 0;
try
sBarcodeValue := TextFile.FieldByName(LinkedColumns.Values['Barcode']).Value;
Barcode.IDBarcode := sBarcodeValue;
Model.Model := sBarcodeValue;
Barcode.Model := Model;
if BarcodeService.Find(Barcode) or BarcodeService.FindByModel(Barcode) then
with TextFile do
begin
Edit;
FieldByName(LinkedColumns.Values['Barcode']).AsString := Barcode.IDBarcode;
FieldByName('Model').AsString := Barcode.Model.Model;
FieldByName('IDGroup').Value := Barcode.Model.Category.IDGroup;
FieldByName('IDModelGroup').Value := Barcode.Model.ModelGroup.IDModelGroup;
FieldByName('IDModelSubGroup').Value := Barcode.Model.ModelSubGroup.IDModelSubGroup;
FieldByName('Description').Value := Barcode.Model.Description;
FieldByName('NewMSRP').AsCurrency := Barcode.Model.SuggRetail;
FieldByName('NewModel').AsBoolean := True;
FieldByName('Validation').AsBoolean := True;
if FileCaseQty <> 0 then
begin
FieldByName('CaseQty').AsFloat := FieldByName(LinkedColumns.Values['CaseQty']).AsFloat;
FieldByName('QtyType').AsString := 'CS (' + FieldByName(LinkedColumns.Values['CaseQty']).AsString + ' un )';
end
else
begin
FieldByName('CaseQty').AsFloat := 0;
FieldByName('QtyType').AsString := 'EA';
end;
FieldByName('Warning').AsString := 'Imported from catalog database.';
if (LinkedColumns.Values['PromoFlat'] <> '') then
FieldByName(LinkedColumns.Values['PromoFlat']).AsString := 'N';
FieldByName('OldSalePrice').AsCurrency := 0.0;
FieldByName('NewSalePrice').AsCurrency := 0.0;
// Procura Prešo de Custo por Fornecedor.
Barcode.Model.Vendor.Vendor := ImpExpConfig.Values['Vendor'];
if BarcodeService.FindByVendor(Barcode) then
begin
FieldByName('VendorModelCode').AsString := Barcode.Model.VendorModelCode.VendorCode;
FieldByName('MinQtyPO').AsFloat := Barcode.Model.ModelVendor.MinQtyPO;
FieldByName('VendorCaseQty').AsFloat := Barcode.Model.ModelVendor.CaseQty;
FieldByName('OldCostPrice').AsCurrency := Barcode.Model.VendorCost;
end
else
FieldByName('OldCostPrice').AsCurrency := 0.0;
Post;
Result := True;
end;
finally
FreeAndNil(Model);
FreeAndNil(BarcodeService);
end;
end;
end;
procedure TDMValidatePOTextFile.ImportFromFile;
var
FileCaseQty: Double;
begin
with TextFile do
begin
if (LinkedColumns.Values['CaseQty'] <> '') then
FileCaseQty := MyStrToFloat(FieldByName(LinkedColumns.Values['CaseQty']).AsString)
else
FileCaseQty := 0;
Edit;
if (DMGlobal.GetSvrParam(PARAM_AUTO_GENERATE_MODEL, SQLConnection)) and (TextFile.FieldByName('Model').AsString = '') then
FieldByName('Model').AsString := GetValidModelCode;
FieldByName('NewModel').AsBoolean := True;
FieldByName('Validation').AsBoolean := True;
if FileCaseQty <> 0 then
begin
FieldByName('CaseQty').AsFloat := FieldByName(LinkedColumns.Values['CaseQty']).AsFloat;
FieldByName('QtyType').AsString := 'CS (' + FieldByName(LinkedColumns.Values['CaseQty']).AsString + ' un )';
end
else
begin
FieldByName('CaseQty').AsFloat := 0;
FieldByName('QtyType').AsString := 'EA';
end;
FieldByName('Warning').AsString := 'Imported from file.';
if (LinkedColumns.Values['PromoFlat'] <> '') then
FieldByName(LinkedColumns.Values['PromoFlat']).AsString := 'N';
if LinkedColumns.Values['Description'] <> '' then
FieldByName('Description').AsString := FieldByName(LinkedColumns.Values['Description']).AsString;
FieldByName('OldCostPrice').AsCurrency := 0.0;
FieldByName('OldSalePrice').AsCurrency := 0.0;
FieldByName('NewSalePrice').AsCurrency := 0.0;
FieldByName('NewMSRP').AsCurrency := 0.0;
FieldByName('IDGroup').Value := 0;
FieldByName('IDModelGroup').Value := 0;
FieldByName('IDModelSubGroup').Value := 0;
Post;
end;
end;
procedure TDMValidatePOTextFile.ImportFromMainRetail;
var
FileCaseQty: Double;
begin
with TextFile do
begin
if (LinkedColumns.Values['CaseQty'] <> '') then
FileCaseQty := MyStrToFloat(FieldByName(LinkedColumns.Values['CaseQty']).AsString)
else
FileCaseQty := 0;
Edit;
if (DMGlobal.qryFreeSQL.FieldByName('CaseQty').AsCurrency <> 0) and (FileCaseQty = 0) then
begin
FieldByName('CaseQty').AsFloat := DMGlobal.qryFreeSQL.FieldByName('CaseQty').AsFloat;
FieldByName('QtyType').AsString := 'CS (' + DMGlobal.qryFreeSQL.FieldByName('CaseQty').AsString + ' un )';
end
else if (FileCaseQty <> 0) then
begin
FieldByName('CaseQty').AsFloat := FieldByName(LinkedColumns.Values['CaseQty']).AsFloat;
FieldByName('QtyType').AsString := 'CS (' + FieldByName(LinkedColumns.Values['CaseQty']).AsString + ' un )';
end
else
begin
FieldByName('CaseQty').AsFloat := 0;
FieldByName('QtyType').AsString := 'EA';
end;
FieldByName('IDGroup').AsInteger := DMGlobal.qryFreeSQL.FieldByName('GroupID').AsInteger;
FieldByName('IDModel').AsInteger := DMGlobal.qryFreeSQL.FieldByName('IDModel').AsInteger;
FieldByName('IDModelGroup').AsInteger := DMGlobal.qryFreeSQL.FieldByName('IDModelGroup').AsInteger;
FieldByName('IDModelSubGroup').AsInteger := DMGlobal.qryFreeSQL.FieldByName('IDModelSubGroup').AsInteger;
FieldByName('NewModel').AsBoolean := False;
FieldByName('OldCostPrice').AsCurrency := DMGlobal.qryFreeSQL.FieldByName('VendorCost').AsCurrency;
FieldByName('OldSalePrice').AsCurrency := DMGlobal.qryFreeSQL.FieldByName('SellingPrice').AsCurrency;
if not IsClientServer then
FieldByName('NewSalePrice').AsCurrency := DMGlobal.qryFreeSQL.FieldByName('SellingPrice').AsCurrency;
FieldByName('NewMSRP').AsCurrency := DMGlobal.qryFreeSQL.FieldByName('SuggRetail').AsCurrency;
Post;
end;
end;
procedure TDMValidatePOTextFile.UpdateModelWithCatalog;
var
FileCaseQty: Double;
sBarcodeValue: String;
Barcode: TBarcode;
Model: TModel;
Vendor: TVendor;
BarcodeService: TCatalogBarcodeService;
ModelService: TCatalogModelService;
begin
Barcode := TBarcode.Create;
Model := TModel.Create;
Vendor := TVendor.Create;
BarcodeService := TCatalogBarcodeService.Create;
BarcodeService.SQLConnection := Self.SQLConnection;
try
sBarcodeValue := TextFile.FieldByName(LinkedColumns.Values['Barcode']).Value;
Barcode.IDBarcode := sBarcodeValue;
Model.Model := sBarcodeValue;
Vendor.Vendor := ImpExpConfig.Values['Vendor'];
Barcode.Model := Model;
Barcode.Model.Vendor := Vendor;
if BarcodeService.Find(Barcode) or BarcodeService.FindByModel(Barcode) then
with TextFile do
begin
if not (State = (dsEdit)) then
Edit;
if FieldByName('Warning').AsString <> '' then
FieldByName('Warning').AsString := FieldByName('Warning').AsString + '; Update from Catalog'
else
FieldByName('Warning').AsString := 'Update from Catalog';
FieldByName('Description').AsString := Barcode.Model.Description;
end;
finally
FreeAndNil(Barcode);
FreeAndNil(BarcodeService);
end;
end;
procedure TDMValidatePOTextFile.InvalidByBarcode;
begin
if not (TextFile.State = (dsEdit)) then
TextFile.Edit;
TextFile.FieldByName('Validation').AsBoolean := False;
TextFile.FieldByName('Warning').AsString := 'Invalid Barcode';
end;
procedure TDMValidatePOTextFile.InvalidByCostPrice(AField : String);
begin
if not (TextFile.State = (dsEdit)) then
TextFile.Edit;
TextFile.FieldByName('Validation').AsBoolean := False;
TextFile.FieldByName('Warning').AsString := 'Invalid Item ' + AField;
end;
function TDMValidatePOTextFile.ExistsPONum(PONum: String): Boolean;
begin
with DMGlobal.qryFreeSQL do
begin
try
if Active then
Close;
Connection := SQLConnection;
SQL.Text := ' SELECT IDPO FROM PO '+
' WHERE IDPO = ' + Trim(PONum);
Open;
Result := not(IsEmpty);
finally
Close;
end;
end;
end;
procedure TDMValidatePOTextFile.InvalidByClientServer;
begin
if not (TextFile.State = (dsEdit)) then
TextFile.Edit;
TextFile.FieldByName('Validation').AsBoolean := False;
TextFile.FieldByName('Warning').AsString := 'New items can not be created; Replication database.';
end;
function TDMValidatePOTextFile.GetModelMarkup(IDModel: Integer): Double;
begin
Result := 0;
with DMGlobal.qryFreeSQL do
begin
if Active then
Close;
SQL.Text := ' SELECT MarkUp FROM Model WHERE IDModel = ' + IntToStr(IDModel);
Open;
Result := FieldByName('MarkUp').AsFloat;
Close;
end;
end;
function TDMValidatePOTextFile.ValidateItem: Boolean;
begin
Result := True;
TextFile.Edit;
TextFile.FieldByName('Warning').AsString := '';
if (TextFile.FieldByName(LinkedColumns.Values['Barcode']).AsString = '') then
begin
InvalidByBarcode;
Result := False;
Exit;
end;
try
StrToFloat(TextFile.FieldByName(LinkedColumns.Values['Qty']).AsString);
except
InvalidByQty('Qty');
Result := False;
end;
if (LinkedColumns.Values['CaseQty'] <> '') and (TextFile.FieldByName(LinkedColumns.Values['CaseQty']).AsString <> '') then
try
StrToFloat(TextFile.FieldByName(LinkedColumns.Values['CaseQty']).AsString);
except
InvalidByQty('CaseQty');
Result := False;
end;
if (LinkedColumns.Values['MinQty'] <> '') and (TextFile.FieldByName(LinkedColumns.Values['MinQty']).AsString <> '') then
try
StrToFloat(TextFile.FieldByName(LinkedColumns.Values['MinQty']).AsString);
except
InvalidByQty('MinQty');
Result := False;
end;
if (LinkedColumns.Values['NewCostPrice'] <> '') and (TextFile.FieldByName(LinkedColumns.Values['NewCostPrice']).AsString <> '') then
try
StrToCurr(TextFile.FieldByName(LinkedColumns.Values['NewCostPrice']).AsString);
except
InvalidByCostPrice('NewCostPrice');
Result := False;
end;
if (LinkedColumns.Values['FreightCost'] <> '') and (TextFile.FieldByName(LinkedColumns.Values['FreightCost']).AsString <> '') then
try
StrToCurr(TextFile.FieldByName(LinkedColumns.Values['FreightCost']).AsString);
except
InvalidByCostPrice('FreightCost');
Result := False;
end;
if (LinkedColumns.Values['OtherCost'] <> '') and (TextFile.FieldByName(LinkedColumns.Values['OtherCost']).AsString <> '') then
try
StrToCurr(TextFile.FieldByName(LinkedColumns.Values['OtherCost']).AsString);
except
InvalidByCostPrice('OtherCost');
Result := False;
end;
if (LinkedColumns.Values['CaseCost'] <> '') and (TextFile.FieldByName(LinkedColumns.Values['CaseCost']).AsString <> '') then
try
StrToCurr(TextFile.FieldByName(LinkedColumns.Values['CaseCost']).AsString);
except
InvalidByCostPrice('CaseCost');
Result := False;
end;
end;
function TDMValidatePOTextFile.getSellingPriceObeyIncreasyOnly(
idmodel: integer; price: Currency): Currency;
var
MRsellingPrice: Currency;
qry: TADOQuery;
messageToDebug: String;
savePrice: Currency;
bLocalIncreasePriceOnly : Boolean;
begin
try
qry := TADOQuery.Create(nil);
qry.Connection := SQLConnection;
qry.SQL.Add('select m.IdModel');
qry.SQL.Add(',IsNull(m.SellingPrice, 0) as ModelSellingPrice ');
qry.SQL.add(',Isnull(i.SellingPrice,0) as InvSellingPrice');
qry.SQL.Add(',i.IdInventory');
qry.SQL.Add(',IsNull(m.SellingPrice, 0) as SellingPrice');
qry.SQL.Add(' from Model m');
qry.SQL.Add(' left outer join Inventory i on m.IdModel = i.ModelID');
qry.SQL.Add(' where m.IdModel =:idmodel');
qry.Parameters.ParamByName('idmodel').Value := idmodel;
debugtofile('sql = ' + qry.SQL.GetText);
qry.Open;
debugtofile('qry - open = k');
// debugtofile('before fix MRSellingPrice = '+ qry.fieldByName('SellingPrice').AsString);
if ( not qry.FieldByName('SellingPrice').IsNull ) then
MRsellingPrice := qry.fieldByName('SellingPrice').Value
else
MRsellingPrice := 0;
{ Alex 11/18/2011 - DMCalcPrice.IncreasePriceOnly was not being initiated }
{ as a quick fix had to go direct to DB. }
Qry.Close();
Qry.SQL.Clear();
Qry.SQL.Add('SELECT SRVVALUE FROM PARAM WHERE IDPARAM = 117 ');
Qry.Open();
bLocalIncreasePriceOnly := qry.fieldByName('SRVVALUE').AsBoolean;
result := price;
If ( price < MRsellingPrice ) then begin
if ( DMCalcPrice = nil ) then begin
exit;
end;
if ( bLocalIncreasePriceOnly = True )
Then result := MRsellingPrice
else result := price;
End;
// debugtofile('Result = '+ FloatToStr(result));
finally
qry.Close;
freeAndNil(qry);
end;
end;
end.
|
{-------------------------------------------------------------------------------
Copyright 2012 Ethea S.r.l.
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 Kitto.Ext.Controller;
{$I Kitto.Defines.inc}
interface
uses
SysUtils, Classes,
Ext, ExtPascal,
EF.Intf, EF.ObserverIntf, EF.Tree, EF.Types,
Kitto.Types, Kitto.Metadata.Views;
type
/// <summary>
/// Base interface for controllers. Controllers manages views to build
/// the user interface.
/// </summary>
IKExtController = interface(IEFInterface)
['{FCDFC7CC-E202-4C20-961C-11255CABE497}']
/// <summary>
/// Renders AView according to the Config.
/// </summary>
procedure Display;
function GetConfig: TEFNode;
property Config: TEFNode read GetConfig;
function GetView: TKView;
procedure SetView(const AValue: TKView);
property View: TKView read GetView write SetView;
function GetContainer: TExtContainer;
procedure SetContainer(const AValue: TExtContainer);
property Container: TExtContainer read GetContainer write SetContainer;
function AsExtComponent: TExtComponent;
/// <summary>
/// Returns True if the controller should be freed right after
/// calling Display because it does all its job inside that method, and
/// False if the controller stays on screen and is interactive instead.
/// </summary>
function IsSynchronous: Boolean;
end;
IKExtControllerHost = interface(IEFInterface)
['{67DA8FF9-23ED-41ED-A773-5D09AEEE2D80}']
procedure InitController(const AController: IKExtController);
end;
/// <summary>
/// Interface implemented by objects that can be activated in some way,
/// for example put into tab pages.
/// </summary>
IKExtActivable = interface(IEFInterface)
['{D6B1AA36-C8D7-4D20-856A-7DCC7DB50423}']
procedure Activate;
end;
/// <summary>
/// Holds a list of registered controller classes.
/// </summary>
/// <remarks>
/// Classes passed to RegisterClass and UnregisterClass must implement
/// IKController, otherwise an exception is raised.
/// </remarks>
{ TODO :
allow to overwrite registrations in order to override predefined controllers;
keep track of all classes registered under the same name to handle
de-registration gracefully. }
TKExtControllerRegistry = class(TEFRegistry)
private
class var FInstance: TKExtControllerRegistry;
class function GetInstance: TKExtControllerRegistry; static;
protected
procedure BeforeRegisterClass(const AId: string; const AClass: TClass);
override;
public
class destructor Destroy;
public
class property Instance: TKExtControllerRegistry read GetInstance;
procedure RegisterClass(const AId: string; const AClass: TExtObjectClass);
end;
/// <summary>
/// Queries the registry to create controllers by class Id. It is
/// friend to TKControllerRegistry.
/// </summary>
TKExtControllerFactory = class
private
class var FInstance: TKExtControllerFactory;
class function GetInstance: TKExtControllerFactory; static;
function InvokeBooleanStaticMethod(const AClass: TClass; const AMethodName: string;
const ADefaultResult: Boolean): Boolean;
public
class destructor Destroy;
class property Instance: TKExtControllerFactory read GetInstance;
/// <summary>
/// Creates a controller for the specified view.
/// </summary>
/// <param name="AOwner">
/// Owner for the created object (only used if AContainer is nil,
/// otherwise the container is the owner).
/// </param>
/// <param name="AView">
/// A reference to the view to control. The view object's lifetime is
/// managed externally.
/// </param>
/// <param name="AContainer">
/// Visual container to which to add the newly created controller.
/// </param>
/// <param name="AConfig">
/// Optional controller config node. If not specified, it is taken from
/// the view's 'Controller' node.
/// </param>
/// <param name="AObserver">
/// Optional observer that will receive events posted by the controller.
/// </param>
/// <param name="ACustomType">
/// Custom controller type, used to override the one specified in the view.
/// </param>
function CreateController(const AOwner: TComponent; const AView: TKView;
const AContainer: TExtContainer; const AConfig: TEFNode = nil;
const AObserver: IEFObserver = nil; const ACustomType: string = ''): IKExtController;
end;
implementation
uses
System.Rtti;
{ TKExtControllerRegistry }
procedure TKExtControllerRegistry.BeforeRegisterClass(const AId: string;
const AClass: TClass);
begin
if not AClass.InheritsFrom(TExtObject) or not Supports(AClass, IKExtController) then
raise EKError.CreateFmt('Cannot register class %s (Id %s). Class is not a TExtObject descendant or does not support IKController.', [AClass.ClassName, AId]);
inherited;
end;
class destructor TKExtControllerRegistry.Destroy;
begin
FreeAndNil(FInstance);
end;
class function TKExtControllerRegistry.GetInstance: TKExtControllerRegistry;
begin
if FInstance = nil then
FInstance := TKExtControllerRegistry.Create;
Result := FInstance;
end;
procedure TKExtControllerRegistry.RegisterClass(const AId: string;
const AClass: TExtObjectClass);
begin
inherited RegisterClass(AId, AClass);
end;
{ TKExtControllerFactory }
class destructor TKExtControllerFactory.Destroy;
begin
FreeAndNil(FInstance);
end;
class function TKExtControllerFactory.GetInstance: TKExtControllerFactory;
begin
if FInstance = nil then
FInstance := TKExtControllerFactory.Create;
Result := FInstance;
end;
function TKExtControllerFactory.InvokeBooleanStaticMethod(const AClass: TClass;
const AMethodName: string; const ADefaultResult: Boolean): Boolean;
var
LContext: TRttiContext;
LType: TRttiType;
LMethod: TRttiMethod;
begin
LType := LContext.GetType(AClass);
LMethod := LType.GetMethod(AMethodName);
if Assigned(LMethod) then
Result := LMethod.Invoke(AClass, []).AsBoolean
else
Result := ADefaultResult;
end;
function TKExtControllerFactory.CreateController(const AOwner: TComponent;
const AView: TKView; const AContainer: TExtContainer; const AConfig: TEFNode;
const AObserver: IEFObserver; const ACustomType: string): IKExtController;
var
LClass: TExtObjectClass;
LSubject: IEFSubject;
LObject: TExtObject;
LType: string;
LControllerHost: IKExtControllerHost;
LSupportsContainer: Boolean;
begin
Assert(AView <> nil);
Assert((AContainer <> nil) or (AOwner <> nil));
LType := ACustomType;
if LType = '' then
if Assigned(AConfig) then
LType := AConfig.AsExpandedString;
if LType = '' then
LType := AView.ControllerType;
if LType = '' then
raise EKError.Create('Cannot create controller. Unspecified type.');
LClass := TExtObjectClass(TKExtControllerRegistry.Instance.GetClass(LType));
LSupportsContainer := InvokeBooleanStaticMethod(LClass, 'SupportsContainer', True);
if Assigned(AContainer) and LSupportsContainer then
LObject := LClass.Create(AContainer)
else
LObject := LClass.Create(AOwner);
if not Supports(LObject, IKExtController, Result) then
raise EKError.Create('Object does not support IKController.');
if Assigned(AContainer) and LSupportsContainer then
begin
LObject.AddTo(AContainer.Items);
AContainer.DoLayout;
end;
if AConfig <> nil then
Result.Config.Assign(AConfig)
else
Result.Config.Assign(AView.FindNode('Controller'));
// Keep track of the SupportsContainer info fetched from the class for later use.
Result.Config.SetBoolean('Sys/SupportsContainer', LSupportsContainer);
Result.View := AView;
if Assigned(AContainer) and Supports(AContainer, IKExtControllerHost, LControllerHost) then
LControllerHost.InitController(Result);
if LSupportsContainer then
Result.Container := AContainer;
if Assigned(AObserver) and Supports(Result.AsObject, IEFSubject, LSubject) then
LSubject.AttachObserver(AObserver);
end;
end.
|
unit ArbeitsUnit1;
interface
uses
System.SysUtils, System.Classes;
type
TArbeitsModul1 = class(TDataModule)
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
{ Private-Deklarationen }
str_ConfigDatei : string;
sl_ConfigWerte : TStringList;
bool_ConfigGeaendert : boolean;
procedure SendeText ( str_Titel, str_Inhalt : string );
procedure SendeZahl ( i : integer );
procedure ErzeugeConfigdatei;
procedure SpeichereConfigdatei;
procedure DefaultWerteChecken;
function GetValue(str_Ident: string): string;
procedure SetValue(str_Ident: string; const Value: string);
public
{ Public-Deklarationen }
{$REGION 'Value'}
/// <summary>
/// Value reads and writes a Setting in INI File
/// </summary>
/// <param name="str_Ident : string">
/// Ident of Item
/// </param>
/// <param name="Value : string">
/// Value of the Item, readable and writeable
/// </param>
{$ENDREGION}
property Value [ str_Ident : string ] : string read GetValue write SetValue;
published
end;
var
ArbeitsModul1: TArbeitsModul1;
implementation
{%CLASSGROUP 'FMX.Controls.TControl'}
{$R *.dfm}
uses
System.Messaging
, System.IOUtils
, KonstantenUnit1;
procedure TArbeitsModul1.DataModuleCreate(Sender: TObject);
begin
bool_ConfigGeaendert := False;
sl_ConfigWerte := TStringList.Create;
str_ConfigDatei :=
TPath.GetHomePath + TPath.DirectorySeparatorChar + cStrFirma + TPath.DirectorySeparatorChar
+'config'+TPath.DirectorySeparatorChar
+ ChangeFileExt( ExtractFileName( ParamStr(0)), '.config' );
if not FileExists(str_ConfigDatei) then
begin
ForceDirectories( ExtractFilePath( str_ConfigDatei ) );
ErzeugeConfigdatei;
end
else
try
sl_ConfigWerte.LoadFromFile( str_ConfigDatei );
except on E: Exception do
SendeText( cStrFehlermeldung, E.Message );
end;
DefaultWerteChecken;
SendeText( cStrEinstellungen, sl_ConfigWerte.Text );
end;
procedure TArbeitsModul1.SendeText(str_Titel, str_Inhalt: string);
var
MessageManager: TMessageManager;
Message: TMessage;
str_text: string;
begin
MessageManager := TMessageManager.DefaultManager;
str_text := str_titel+#13#10+str_Inhalt;
Message := TMessage<UnicodeString>.Create(str_text);
MessageManager.SendMessage(NIL, Message);
end;
procedure TArbeitsModul1.SendeZahl(i: integer);
var
MessageManager: TMessageManager;
Message: TMessage;
str_text: string;
begin
MessageManager := TMessageManager.DefaultManager;
Message := TMessage<Integer>.Create(i);
MessageManager.SendMessage(NIL, Message);
end;
procedure TArbeitsModul1.SetValue(str_Ident: string; const Value: string);
begin
sl_ConfigWerte.Values[str_Ident] := Value;
bool_ConfigGeaendert := True;
SendeText( cStrEinstellungen, sl_ConfigWerte.Text );
end;
procedure TArbeitsModul1.ErzeugeConfigdatei;
begin
ForceDirectories( ExtractFilePath(str_ConfigDatei) );
sl_ConfigWerte.Add('###############################################');
sl_ConfigWerte.Add('## config-Datei erzeugt am '+FormatDateTime('dd.mm.yyyy',now));
sl_ConfigWerte.Add('## von '+GetEnvironmentVariable('username') );
sl_ConfigWerte.Add('###############################################');
SpeichereConfigdatei;
end;
function TArbeitsModul1.GetValue(str_Ident: string): string;
begin
Result := sl_ConfigWerte.Values[str_Ident];
end;
procedure TArbeitsModul1.SpeichereConfigdatei;
begin
try
sl_ConfigWerte.SaveToFile(str_ConfigDatei);
bool_ConfigGeaendert := False;
except
on E: Exception do
end;
end;
procedure TArbeitsModul1.DataModuleDestroy(Sender: TObject);
begin
if bool_ConfigGeaendert then
SpeichereConfigdatei;
end;
procedure TArbeitsModul1.DefaultWerteChecken;
var
i: Integer;
procedure Check ( cst : TConfigStruktur );
begin
if sl_ConfigWerte.Values[cst.Ident]='' then
begin
sl_ConfigWerte.Add('#'+cst.Ident+'='+cst.Info );
sl_ConfigWerte.Add( cst.Ident +'='+ cst.Default );
bool_ConfigGeaendert := True;
end;
end;
begin
// defaultwerte speichern, falls die nicht vorhanden sind
for i := 0 to i_max - 1 do
begin
Check( DefaultConfig[i] );
end;
if bool_ConfigGeaendert then
SpeichereConfigdatei;
end;
end.
|
unit U_Origin.Return;
interface
uses System.Classes, System.SysUtils;
type
IOriginToReturn<origin, return> = interface
['{EFCFEF7F-3975-4C6E-8187-D3325B6D7D3C}']
function stringToString(strContent : String) : String;
function stringToFile(strContent, filePathResult : String) : Boolean;
function stringToReturnType(strContent : String) : return;
function fileToString(filePath : String) : String;
function fileToFile(filePath : String; filePathResult : String = '') : Boolean;
function fileToReturnType(filePath : String) : return;
function originTypeToString(content : origin) : String;
function originTypeToFile(content : origin; filePathResult : String) : Boolean;
function originTypeToReturnType(content : origin) : return;
end;
implementation
end.
|
unit Unit1;
interface
uses
Windows, Forms, Controls, StdCtrls, Classes, Messages;
type
TForm1 = class(TForm)
CloseBtn: TButton;
Label1: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure CloseBtnClick(Sender: TObject);
private
{ Private declarations }
procedure WmNCHitTest(var Msg :TWMNCHitTest); message WM_NCHITTEST;
public
{ Public declarations }
end;
var Form1: TForm1;
implementation
{$R *.DFM}
const
{ An array of points for the star region. }
RgnPoints : array[1..10] of TPoint = ((X:203;Y:22), (X:157;Y:168), (X:3;Y:168),
(X:128;Y:257), (X:81;Y:402), (X:203;Y:334),
(X:325;Y:422), (X:278;Y:257), (X:402;Y:168),
(X:249;Y:168));
{ An array of points used to draw a line }
{ around the region in the OnPaint handler. }
LinePoints : array[1..11] of TPoint = ((X:199;Y:0), (X:154;Y:146), (X:2;Y:146),
(X:127;Y:235), (X:79;Y:377), (X:198;Y:308),
(X:320;Y:396), (X:272;Y:234),(X:396;Y:146),
(X:244;Y:146), (X:199;Y:0));
procedure TForm1.FormCreate(Sender: TObject);
var Rgn : HRGN;
begin
{ Create a polygon region from our points. }
Rgn := CreatePolygonRgn(RgnPoints, High(RgnPoints), ALTERNATE);
{ Set the window region. }
SetWindowRgn(Handle, Rgn, True);
end;
procedure TForm1.FormPaint(Sender: TObject);
begin
{ Draw a line around the star. }
Canvas.Pen.Width := 3;
Canvas.Polyline(LinePoints);
end;
procedure TForm1.CloseBtnClick(Sender: TObject);
begin
Close();
end;
{ Catch the WM_NCHITTEST message so the user }
{ can drag the window around the screen. }
procedure TForm1. WmNCHitTest(var Msg: TWMNCHitTest);
begin
DefaultHandler(Msg);
if Msg.Result = HTCLIENT then
Msg.Result := HTCAPTION;
end;
end.
|
unit GLDObjects;
interface
uses
Classes, GL, GLDTypes, GLDConst, GLDClasses, GLDMaterial, GLDModify;
type
TGLDVisualObject = class;
TGLDEditableObject = class;
TGLDObjectList = class;
TGLDVisualObjectClass = class of TGLDVisualObject;
TGLDEditableObjectClass = class of TGLDEditableObject;
TGLDVisualObject = class(TGLDSysClass)
protected
FName: string;
FVisible: GLboolean;
private
procedure SetName(Value: string);
procedure SetVisible(Value: GLboolean);
protected
procedure DoRender; virtual; abstract;
procedure SimpleRender; virtual; abstract;
public
constructor Create(AOwner: TPersistent); override;
procedure Assign(Source: TPersistent); override;
procedure Render; virtual;
procedure RenderEdges; virtual;
procedure RenderWireframe; virtual;
procedure RenderBoundingBox; virtual;
procedure RenderForSelection(Idx: GLuint); virtual;
procedure Hide;
procedure UnHide;
class function SysClassType: TGLDSysClassType; override;
class function VisualObjectClassType: TGLDVisualObjectClass; virtual;
class function IsEditableObject: GLboolean; virtual;
class function RealName: string; virtual;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
published
property Name: string read FName write SetName;
property Visible: GLboolean read FVisible write SetVisible default True;
end;
PGLDVisualObjectArray = ^TGLDVisualObjectArray;
TGLDVisualObjectArray = array[1..GLD_MAX_OBJECTS] of TGLDVisualObject;
TGLDEditableObject = class(TGLDVisualObject)
protected
FColor: TGLDColor4fClass;
FMaterial: TGLDMaterial;
FSelected: GLboolean;
FPosition: TGLDVector4fClass;
FRotation: TGLDRotation3DClass;
FBoundingBox: TGLDBoundingBoxParams;
FModifyList: TGLDModifyList;
private
procedure SetColor(Value: TGLDColor4fClass);
procedure SetSelected(Value: GLboolean);
procedure SetMaterial(Value: TGLDMaterial);
procedure SetPosition(Value: TGLDVector4fClass);
procedure SetRotation(Value: TGLDRotation3DClass);
procedure SetModifyList(Value: TGLDModifyList);
protected
procedure CalcBoundingBox; virtual; abstract;
procedure CreateGeometry; virtual;
procedure DestroyGeometry; virtual;
procedure ApplyMaterial; virtual;
procedure SetOnChange(Value: TNotifyEvent); override;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure Render; override;
procedure RenderWireframe; override;
procedure RenderBoundingBox; override;
procedure RenderForSelection(Idx: GLuint); override;
class function SysClassType: TGLDSysClassType; override;
class function VisualObjectClassType: TGLDVisualObjectClass; override;
class function IsEditableObject: GLboolean; override;
class function RealName: string; override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
procedure ChangeGeometry(Sender: TObject); virtual;
property BoundingBox: TGLDBoundingBoxParams read FBoundingBox;
property ModifyList: TGLDModifyList read FModifyList write SetModifyList;
published
property Color: TGLDColor4fClass read FColor write SetColor;
property Material: TGLDMaterial read FMaterial write SetMaterial;
property Selected: GLboolean read FSelected write SetSelected default False;
property Position: TGLDVector4fClass read FPosition write SetPosition;
property Rotation: TGLDRotation3DClass read FRotation write SetRotation;
end;
TGLDObjectList = class(TGLDSysClass)
private
FCapacity: GLuint;
FCount: GLuint;
FList: PGLDVisualObjectArray;
procedure SetCapacity(NewCapacity: GLuint);
procedure SetCount(NewCount: GLuint);
function GetLast: TGLDVisualObject;
procedure SetLast(Value: TGLDVisualObject);
function GetObject(Index: GLuint): TGLDVisualObject;
procedure SetObject(Index: GLuint; AObject: TGLDVisualObject);
protected
procedure SetOnChange(Value: TNotifyEvent); override;
procedure DefineProperties(Filer: TFiler); override;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
class function SysClassType: TGLDSysClassType; override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
procedure Clear;
function Add(AObject: TGLDVisualObject): GLuint;
function CreateNew(AType: TGLDVisualObjectClass): GLuint;
function Delete(Index: GLuint): GLuint; overload;
function Delete(AObject: TGLDVisualObject): GLuint; overload;
procedure Render; overload;
procedure Render(Index: GLuint); overload;
procedure RenderEdges; overload;
procedure RenderEdges(Index: GLuint); overload;
procedure RenderWireframe; overload;
procedure RenderWireframe(Index: GLuint); overload;
procedure RenderBoundingBox; overload;
procedure RenderBoundingBox(Index: GLuint); overload;
procedure RenderForSelection; overload;
procedure RenderForSelection(Index: GLuint); overload;
procedure Select(Index: GLuint);
procedure AddSelection(Index: GLuint);
procedure SelectAll;
procedure AssociateMaterialToSelectedObjects(Material: TGLDMaterial);
procedure DeleteMaterialFromSelectedObject;
procedure DeleteMatRef(Material: TGLDMaterial);
procedure DeleteMatRefs;
procedure DeleteSelections;
procedure InvertSelections;
procedure DeleteSelectedObjects;
function FirstSelectedObject: TGLDVisualObject;
procedure CopySelectedObjectsTo(List: TGLDObjectList);
procedure PasteObjectsFrom(List: TGLDObjectList);
procedure MoveSelectedObjects(const Vector: TGLDVector3f);
procedure RotateSelectedObjects(const Rotation: TGLDRotation3D);
procedure ConvertSelectedObjectsToTriMesh;
procedure ConvertSelectedObjectsToQuadMesh;
procedure ConvertSelectedObjectsToPolyMesh;
function SelectionCount: GLuint;
function CenterOfSelectedObjects: TGLDVector3f;
function AverageOfRotations: TGLDRotation3D;
function IndexOf(AObject: TGLDVisualObject): GLuint;
property Capacity: GLuint read FCapacity write SetCapacity;
property Count: GLuint read FCount write SetCount;
property Last: TGLDVisualObject read GetLast write SetLast;
property List: PGLDVisualObjectArray read FList;
property Items[index: GLuint]: TGLDVisualObject read GetObject write SetObject;
property Objects[index: GLuint]: TGLDVisualObject read GetObject write SetObject; default;
end;
implementation
uses
sysutils, dialogs, GLDX, GLDUtils, GLDRepository, GLDGizmos,
{$INCLUDE GLDObjects.inc};
constructor TGLDVisualObject.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FName := '';
FVisible := True;
end;
procedure TGLDVisualObject.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLDVisualObject) then Exit;
FName := TGLDVisualObject(Source).FName;
FVisible := TGLDVisualObject(Source).FVisible;
end;
procedure TGLDVisualObject.Render;
begin
if not FVisible then Exit;
DoRender;
end;
procedure TGLDVisualObject.RenderWireframe;
begin
if not FVisible then Exit;
glPushAttrib(GL_LIGHTING_BIT or GL_POLYGON_BIT);
glDisable(GL_LIGHTING);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
SimpleRender;
glPopAttrib;
end;
procedure TGLDVisualObject.RenderEdges;
begin
Render;
glEnable(GL_POLYGON_OFFSET_LINE);
glPolygonOffset(-0.4, 0);
glDepthMask(False);
RenderWireFrame;
glDepthMask(True);
glDisable(GL_POLYGON_OFFSET_LINE);
end;
procedure TGLDVisualObject.RenderBoundingBox;
begin
end;
procedure TGLDVisualObject.RenderForSelection(Idx: GLuint);
var
Color: TGLDColor3ub;
begin
if not FVisible then Exit;
Color := GLDXColor3ub(Longint(Idx));
glColor3ubv(@Color);
SimpleRender;
end;
procedure TGLDVisualObject.SetName(Value: string);
begin
FName := Value;
end;
procedure TGLDVisualObject.SetVisible(Value: GLboolean);
begin
if FVisible = Value then Exit;
FVisible := Value;
Change;
end;
procedure TGLDVisualObject.Hide;
begin
SetVisible(False);
end;
procedure TGLDVisualObject.UnHide;
begin
SetVisible(True);
end;
class function TGLDVisualObject.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_VISUALOBJECT;
end;
class function TGLDVisualObject.VisualObjectClassType: TGLDVisualObjectClass;
begin
Result := TGLDVisualObject;
end;
class function TGLDVisualObject.IsEditableObject: GLboolean;
begin
Result := False;
end;
class function TGLDVisualObject.RealName: string;
begin
Result := GLD_VISUALOBJECT_STR;
end;
procedure TGLDVisualObject.LoadFromStream(Stream: TStream);
begin
GLDXLoadStringFromStream(Stream, FName);
Stream.Read(FVisible, SizeOf(GLboolean));
end;
procedure TGLDVisualObject.SaveToStream(Stream: TStream);
begin
GLDXSaveStringToStream(Stream, FName);
Stream.Write(FVisible, SizeOf(GLboolean));
end;
constructor TGLDEditableObject.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FColor := TGLDColor4fClass.Create(Self, GLDXRandomColor4f);
FColor.OnChange := nil;
FMaterial := nil;
FSelected := False;
FPosition := TGLDVector4fClass.Create(Self);
FPosition.OnChange := FOnChange;
FRotation := TGLDRotation3DClass.Create(Self);
FRotation.OnChange := FOnChange;
FModifyList := TGLDModifyList.Create(Self);
FModifyList.OnChange := ChangeGeometry;
end;
destructor TGLDEditableObject.Destroy;
begin
FColor.Free;
FMaterial := nil;
FPosition.Free;
FRotation.Free;
FModifyList.Free;
DestroyGeometry;
inherited Destroy;
end;
procedure TGLDEditableObject.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLDEditableObject) then Exit;
inherited Assign(Source);
PGLDColor4f(FColor.GetPointer)^ :=
TGLDEditableObject(Source).FColor.Color4f;
FMaterial := TGLDEditableObject(Source).FMaterial;
FSelected := TGLDEditableObject(Source).FSelected;
PGLDVector4f(FPosition.GetPointer)^ := TGLDEditableObject(Source).FPosition.Vector4f;
PGLDRotation3D(FRotation.GetPointer)^ := TGLDEditableObject(Source).FRotation.Params;
FModifyList.Assign(TGLDEditableObject(Source).FModifyList);
end;
procedure TGLDEditableObject.Render;
begin
if not FVisible then Exit;
ApplyMaterial;
glPushMatrix;
FPosition.ApplyAsTranslation;
FRotation.ApplyAsRotationXZY;
DoRender;
if FSelected then
TGLDBoundingBox.DrawSelectionIndicator(FBoundingBox);
glPopMatrix;
end;
procedure TGLDEditableObject.RenderWireframe;
begin
if not FVisible then Exit;
glPushMatrix;
FPosition.ApplyAsTranslation;
FRotation.ApplyAsRotationXZY;
glPushAttrib(GL_LIGHTING_BIT or GL_POLYGON_BIT);
if FSelected then
glColor3ubv(@GLD_COLOR3UB_WHITE)
else glColor3fv(FColor.GetPointer);
glDisable(GL_LIGHTING);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
SimpleRender;
glPopAttrib;
glPopMatrix;
end;
procedure TGLDEditableObject.RenderBoundingBox;
begin
if not FVisible then Exit;
glPushMatrix;
FPosition.ApplyAsTranslation;
FRotation.ApplyAsRotationXZY;
if FSelected then
glColor3ubv(@GLD_COLOR3UB_WHITE)
else glColor3fv(FColor.GetPointer);
TGLDBoundingBox.DrawBoundingBox(FBoundingBox);
glPopMatrix;
end;
procedure TGLDEditableObject.RenderForSelection(Idx: GLuint);
var
Color: TGLDColor3ub;
begin
if not FVisible then Exit;
Color := GLDXColor3ub(Longint(Idx));
glColor3ubv(@Color);
glPushMatrix;
FPosition.ApplyAsTranslation;
FRotation.ApplyAsRotationXZY;
SimpleRender;
glPopMatrix;
end;
class function TGLDEditableObject.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_EDITABLEOBJECT;
end;
class function TGLDEditableObject.VisualObjectClassType: TGLDVisualObjectClass;
begin
Result := TGLDEditableObject;
end;
class function TGLDEditableObject.IsEditableObject: GLboolean;
begin
Result := True;
end;
class function TGLDEditableObject.RealName: string;
begin
Result := GLD_EDITABLEOBJECT_STR;
end;
procedure TGLDEditableObject.LoadFromStream(Stream: TStream);
var
MaterialIndex: GLuint;
Repository: TGLDRepository;
begin
inherited LoadFromStream(Stream);
FColor.LoadFromStream(Stream);
Stream.Read(MaterialIndex, SizeOf(GLuint));
Repository := GLDUGetOwnerRepository(Self);
if Assigned(Repository) then
FMaterial := Repository.Materials[MaterialIndex]
else FMaterial := nil;
Stream.Read(FSelected, SizeOf(GLboolean));
FPosition.LoadFromStream(Stream);
FRotation.LoadFromStream(Stream);
FModifyList.LoadFromStream(Stream);
FModifyList.OnChange := ChangeGeometry;
end;
procedure TGLDEditableObject.SaveToStream(Stream: TStream);
var
MaterialIndex: GLuint;
begin
inherited SaveToStream(Stream);
FColor.SaveToStream(Stream);
if Assigned(FMaterial) then
MaterialIndex := FMaterial.ListIndex
else MaterialIndex := 0;
Stream.Write(MaterialIndex, SizeOf(GLuint));
Stream.Write(FSelected, SizeOf(GLboolean));
FPosition.SaveToStream(Stream);
FRotation.SaveToStream(Stream);
FModifyList.SaveToStream(Stream);
end;
procedure TGLDEditableObject.CreateGeometry;
begin
end;
procedure TGLDEditableObject.DestroyGeometry;
begin
end;
procedure TGLDEditableObject.ApplyMaterial;
begin
if Assigned(FMaterial) then
FMaterial.Apply
else begin
GLDGetStandardMaterial.Apply;
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, FColor.GetPointer);
glColor4fv(FColor.GetPointer);
end;
end;
procedure TGLDEditableObject.ChangeGeometry(Sender: TObject);
begin
CreateGeometry;
Change;
end;
procedure TGLDEditableObject.SetColor(Value: TGLDColor4fClass);
begin
if Value = nil then Exit;
FColor.Assign(Value);
end;
procedure TGLDEditableObject.SetSelected(Value: GLboolean);
begin
if FSelected = Value then Exit;
FSelected := Value;
Change;
end;
procedure TGLDEditableObject.SetMaterial(Value: TGLDMaterial);
begin
if FMaterial = Value then Exit;
FMaterial := Value;
Change;
end;
procedure TGLDEditableObject.SetPosition(Value: TGLDVector4fClass);
begin
if Value = nil then Exit;
if GLDXVectorEqual(FPosition.Vector4f, Value.Vector4f) then Exit;
PGLDVector4f(FPosition.GetPointer)^ := Value.Vector4f;
CreateGeometry;
Change;
end;
procedure TGLDEditableObject.SetRotation(Value: TGLDRotation3DClass);
begin
if Value = nil then Exit;
if GLDXRotation3DEqual(FRotation.Params, Value.Params) then Exit;
PGLDRotation3D(FRotation.GetPointer)^ := Value.Params;
CreateGeometry;
Change;
end;
procedure TGLDEditableObject.SetModifyList(Value: TGLDModifyList);
begin
FModifyList.Assign(Value);
end;
procedure TGLDEditableObject.SetOnChange(Value: TNotifyEvent);
begin
FOnChange := Value;
FColor.OnChange := FOnChange;
FModifyList.OnChange := ChangeGeometry;
end;
constructor TGLDObjectList.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FCapacity := 0;
FCount := 0;
FList := nil;
end;
destructor TGLDObjectList.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TGLDObjectList.Assign(Source: TPersistent);
var
i: GLuint;
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLDObjectList) then Exit;
Clear;
FCapacity := TGLDObjectList(Source).FCapacity;
FCount := TGLDObjectList(Source).FCount;
if FCapacity > 0 then
ReallocMem(FList, FCapacity * SizeOf(TGLDVisualObject));
if FCount > 0 then
for i := 1 to FCount do
begin
FList^[i] := TGLDObjectList(Source).FList^[i].VisualObjectClassType.Create(Self);
FList^[i].Assign(TGLDObjectList(Source).FList^[i]);
FList^[i].OnChange := FOnChange;
end;
end;
class function TGLDObjectList.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_OBJECTLIST;
end;
procedure TGLDObjectList.LoadFromStream(Stream: TStream);
var
ACapacity, ACount, i: GLuint;
AType: TGLDSysClassType;
begin
Clear;
Stream.Read(ACapacity, SizeOf(GLuint));
Stream.Read(ACount, SizeOf(GLuint));
SetCapacity(ACapacity);
if ACount > 0 then
for i := 1 to ACount do
begin
Stream.Read(AType, SizeOf(TGLDSysClassType));
case AType of
GLD_SYSCLASS_PLANE: FList^[i] := TGLDPlane.Create(Self);
GLD_SYSCLASS_DISK: FList^[i] := TGLDDisk.Create(Self);
GLD_SYSCLASS_RING: FList^[i] := TGLDRing.Create(Self);
GLD_SYSCLASS_BOX: FList^[i] := TGLDBox.Create(Self);
GLD_SYSCLASS_PYRAMID: FList^[i] := TGLDPyramid.Create(Self);
GLD_SYSCLASS_CYLINDER: FList^[i] := TGLDCylinder.Create(Self);
GLD_SYSCLASS_CONE: FList^[i] := TGLDCone.Create(Self);
GLD_SYSCLASS_TORUS: FList^[i] := TGLDTorus.Create(Self);
GLD_SYSCLASS_SPHERE: FList^[i] := TGLDSphere.Create(Self);
GLD_SYSCLASS_TUBE: FList^[i] := TGLDTube.Create(Self);
GLD_SYSCLASS_TRIMESH: FList^[i] := TGLDTriMesh.Create(Self);
GLD_SYSCLASS_QUADMESH: FList^[i] := TGLDQuadMesh.Create(Self);
GLD_SYSCLASS_POLYMESH: FList^[i] := TGLDPolyMesh.Create(Self);
end;
FList^[i].LoadFromStream(Stream);
FList^[i].OnChange := FOnChange;
end;
FCount := ACount;
end;
procedure TGLDObjectList.SaveToStream(Stream: TStream);
var
i: GLuint;
AType: TGLDSysClassType;
begin
Stream.Write(FCapacity, SizeOf(GLuint));
Stream.Write(FCount, SizeOf(GLuint));
if FCount > 0 then
for i := 1 to FCount do
begin
AType := FList^[i].SysClassType;
Stream.Write(AType, SizeOf(TGLDSysClassType));
FList^[i].SaveToStream(Stream);
end;
end;
procedure TGLDObjectList.Clear;
var
i: GLuint;
begin
if FCount > 0 then
for i := FCount downto 1 do
FList^[i].Free;
ReallocMem(FList, 0);
FCapacity := 0;
FCount := 0;
FList := nil;
Change;
end;
function TGLDObjectList.Add(AObject: TGLDVisualObject): GLuint;
begin
Result := 0;
if AObject = nil then Exit;
Result := CreateNew(AObject.VisualObjectClassType);
if Result > 0 then
FList^[FCount].Assign(AObject);
Change;
end;
function TGLDObjectList.CreateNew(AType: TGLDVisualObjectClass): GLuint;
begin
Result := 0;
if FCount >= GLD_MAX_OBJECTS then Exit;
Inc(FCount);
if FCapacity < FCount then
SetCapacity(FCount);
FList^[FCount] := AType.Create(Self);
FList^[FCount].OnChange := FOnChange;
Result := FCount;
end;
function TGLDObjectList.Delete(Index: GLuint): GLuint;
var
i: GLuint;
begin
Result := 0;
if (Index < 1) or (Index > FCount) then Exit;
FList^[Index].Free;
if Index < FCount then
for i := Index to FCount - 1 do
FList^[i] := FList^[i + 1];
Dec(FCount);
Result := Index;
Change;
end;
function TGLDObjectList.Delete(AObject: TGLDVisualObject): GLuint;
begin
Result := Delete(IndexOf(AObject));
end;
procedure TGLDObjectList.Render;
var
i: GLuint;
begin
if FCount > 0 then
for i := 1 to FCount do
FList^[i].Render;
end;
procedure TGLDObjectList.Render(Index: GLuint);
begin
if (Index < 1) or (Index > FCount) then Exit;
FList^[Index].Render;
end;
procedure TGLDObjectList.RenderEdges;
var
i: GLint;
begin
if FCount > 0 then
for i := 1 to FCount do
FList^[i].RenderEdges;
end;
procedure TGLDObjectList.RenderEdges(Index: GLuint);
begin
if (Index < 1) or (Index > FCount) then Exit;
FList^[Index].RenderEdges;
end;
procedure TGLDObjectList.RenderWireframe;
var
i: GLint;
begin
if FCount > 0 then
for i := 1 to FCount do
FList^[i].RenderWireframe;
end;
procedure TGLDObjectList.RenderWireframe(Index: GLuint);
begin
if (Index < 1) or (Index > FCount) then Exit;
FList^[Index].RenderWireframe;
end;
procedure TGLDObjectList.RenderBoundingBox;
var
i: GLuint;
begin
if FCount > 0 then
for i := 1 to FCount do
FList^[i].RenderBoundingBox;
end;
procedure TGLDObjectList.RenderBoundingBox(Index: GLuint);
begin
if (Index < 1) or (Index > FCount) then Exit;
FList^[Index].RenderBoundingBox;
end;
procedure TGLDObjectList.RenderForSelection;
var
i: GLuint;
begin
if FCount > 0 then
for i := 1 to FCount do
FList^[i].RenderForSelection(i);
end;
procedure TGLDObjectList.RenderForSelection(Index: GLuint);
begin
if (Index < 1) or (Index > FCount) then Exit;
FList^[Index].RenderForSelection(Index);
end;
procedure TGLDObjectList.Select(Index: GLuint);
begin
DeleteSelections;
AddSelection(Index);
end;
procedure TGLDObjectList.AddSelection(Index: GLuint);
begin
if (Index < 1) or (Index > FCount) then Exit;
if FList^[Index].IsEditableObject then
TGLDEditableObject(FList^[Index]).Selected := True;
end;
procedure TGLDObjectList.SelectAll;
var
i: GLuint;
begin
if FCount > 0 then
begin
for i := 1 to FCount do
if FList^[i].IsEditableObject then
TGLDEditableObject(FList^[i]).FSelected := True;
Change;
end;
end;
procedure TGLDObjectList.AssociateMaterialToSelectedObjects(Material: TGLDMaterial);
var
i: GLuint;
begin
if FCount > 0 then
for i := 1 to FCount do
if FList^[i].IsEditableObject then
if TGLDEditableObject(FList^[i]).FSelected then
TGLDEditableObject(FList^[i]).FMaterial := Material;
Change;
end;
procedure TGLDObjectList.DeleteMaterialFromSelectedObject;
var
i: GLuint;
begin
if FCount > 0 then
for i := 1 to FCount do
if FList^[i].IsEditableObject then
if TGLDEditableObject(FList^[i]).FSelected then
TGLDEditableObject(FList^[i]).FMaterial := nil;
Change;
end;
procedure TGLDObjectList.DeleteMatRef(Material: TGLDMaterial);
var
i: GLuint;
begin
if FCount > 0 then
for i := 1 to FCount do
if FList^[i].IsEditableObject then
if TGLDEditableObject(FList^[i]).FMaterial = Material then
TGLDEditableObject(FList^[i]).FMaterial := nil;
Change;
end;
procedure TGLDObjectList.DeleteMatRefs;
var
i: GLuint;
begin
if FCount > 0 then
for i := 1 to FCount do
if FList^[i].IsEditableObject then
TGLDEditableObject(FList^[i]).FMaterial := nil;
Change;
end;
procedure TGLDObjectList.DeleteSelections;
var
i: GLuint;
begin
if FCount > 0 then
begin
for i := 1 to FCount do
if FList^[i].IsEditableObject then
TGLDEditableObject(FList^[i]).FSelected := False;
Change;
end;
end;
procedure TGLDObjectList.InvertSelections;
var
i: GLuint;
begin
if FCount > 0 then
begin
for i := 1 to FCount do
if FList^[i].IsEditableObject then
with TGLDEditableObject(FList^[i]) do
FSelected := not FSelected;
Change;
end;
end;
procedure TGLDObjectList.DeleteSelectedObjects;
var
i: GLuint;
begin
if FCount > 0 then
for i := FCount downto 1 do
if FList^[i].IsEditableObject then
if TGLDEditableObject(FList^[i]).FSelected then
Delete(i);
end;
function TGLDObjectList.FirstSelectedObject: TGLDVisualObject;
var
i: GLuint;
begin
Result := nil;
if FCount > 0 then
for i := 1 to FCount do
if FList^[i].IsEditableObject then
if TGLDEditableObject(FList^[i]).FSelected then
begin
Result := FList^[i];
Exit;
end;
end;
procedure TGLDObjectList.CopySelectedObjectsTo(List: TGLDObjectList);
var
i: GLuint;
begin
if not Assigned(List) then Exit;
if FCount > 0 then
for i := 1 to FCount do
if FList^[i].IsEditableObject then
if TGLDEditableObject(FList^[i]).FSelected then
begin
if List.Add(FList^[i]) > 0 then
begin
TGLDEditableObject(List.Last).FSelected := False;
TGLDEditableObject(List.Last).Name := TGLDEditableObject(List.Last).Name + '1';
end;
end;
end;
procedure TGLDObjectList.PasteObjectsFrom(List: TGLDObjectList);
var
i: GLuint;
begin
if not Assigned(List) then Exit;
if List.FCount > 0 then
for i := 1 to List.FCount do
Add(List.FList^[i]);
Change;
end;
procedure TGLDObjectList.MoveSelectedObjects(const Vector: TGLDVector3f);
var
i: GLuint;
begin
if FCount > 0 then
for i := 1 to FCount do
if FList^[i].IsEditableObject then
if TGLDEditableObject(FList^[i]).Selected then
with TGLDEditableObject(FList^[i]).FPosition do
PGLDVector3f(GetPointer)^ :=
GLDXVectorAdd(PGLDVector3f(GetPointer)^, Vector);
end;
procedure TGLDObjectList.RotateSelectedObjects(const Rotation: TGLDRotation3D);
var
i: GLuint;
begin
if FCount > 0 then
for i := 1 to FCount do
if FList^[i].IsEditableObject then
if TGLDEditableObject(FList^[i]).Selected then
with TGLDEditableObject(FList^[i]).FRotation do
PGLDRotation3D(GetPointer)^ :=
GLDXRotation3DAdd(PGLDRotation3D(GetPointer)^, Rotation);
end;
procedure TGLDObjectList.ConvertSelectedObjectsToTriMesh;
var
i: GLuint;
begin
if FCount > 0 then
for i := FCount downto 1 do
if (FList^[i].IsEditableObject) and
(TGLDEditableObject(FList^[i]).Selected) and
(FList^[i].CanConvertTo(TGLDTriMesh)) then
begin
if CreateNew(TGLDTriMesh) = 0 then Exit;
FList^[i].ConvertTo(Last);
Delete(i);
end;
end;
procedure TGLDObjectList.ConvertSelectedObjectsToQuadMesh;
var
i: GLuint;
begin
if FCount > 0 then
for i := FCount downto 1 do
if (FList^[i].IsEditableObject) and
(TGLDEditableObject(FList^[i]).Selected) and
(FList^[i].CanConvertTo(TGLDQuadMesh)) then
begin
if CreateNew(TGLDQuadMesh) = 0 then Exit;
FList^[i].ConvertTo(Last);
Delete(i);
end;
end;
procedure TGLDObjectList.ConvertSelectedObjectsToPolyMesh;
var
i: GLuint;
begin
if FCount > 0 then
for i := FCount downto 1 do
if (FList^[i].IsEditableObject) and
(TGLDEditableObject(FList^[i]).Selected) and
(FList^[i].CanConvertTo(TGLDPolyMesh)) then
begin
if CreateNew(TGLDPolyMesh) = 0 then Exit;
FList^[i].ConvertTo(Last);
Delete(i);
end;
end;
function TGLDObjectList.SelectionCount: GLuint;
var
i: GLuint;
begin
Result := 0;
if FCount > 0 then
for i := 1 to FCount do
if FList^[i].IsEditableObject then
if TGLDEditableObject(FList^[i]).Selected then
Inc(Result);
end;
function TGLDObjectList.CenterOfSelectedObjects: TGLDVector3f;
var
i, Cnt: GLuint;
begin
Result := GLD_VECTOR3F_ZERO;
Cnt := 0;
if FCount > 0 then
for i := 1 to FCount do
if FList^[i].IsEditableObject then
if TGLDEditableObject(FList^[i]).Selected then
begin
Inc(Cnt);
Result := GLDXVectorAdd(Result,
TGLDEditableObject(FList^[i]).FPosition.Vector3f);
end;
if Cnt > 0 then
begin
if Result.X <> 0 then Result.X := Result.X / Cnt;
if Result.Y <> 0 then Result.Y := Result.Y / Cnt;
if Result.Z <> 0 then Result.Z := Result.Z / Cnt;
end;
end;
function TGLDObjectList.AverageOfRotations: TGLDRotation3D;
var
i, Cnt: GLuint;
begin
Result := GLD_ROTATION3D_ZERO;
Cnt := 0;
if FCount > 0 then
for i := 1 to FCount do
if FList^[i].IsEditableObject then
if TGLDEditableObject(FList^[i]).Selected then
begin
Inc(Cnt);
Result := GLDXRotation3DAdd(Result,
TGLDEditableObject(FList^[i]).FRotation.Params);
end;
if Cnt > 0 then
begin
if Result.XAngle <> 0 then Result.XAngle := Result.XAngle / Cnt;
if Result.YAngle <> 0 then Result.YAngle := Result.YAngle / Cnt;
if Result.ZAngle <> 0 then Result.ZAngle := Result.ZAngle / Cnt;
end;
end;
function TGLDObjectList.IndexOf(AObject: TGLDVisualObject): GLuint;
var
i: GLuint;
begin
Result := 0;
if AObject = nil then Exit;
if FCount > 0 then
for i := 1 to FCount do
if FList^[i] = AObject then
begin
Result := i;
Exit;
end;
end;
procedure TGLDObjectList.DefineProperties(Filer: TFiler);
begin
Filer.DefineBinaryProperty('Data', LoadFromStream, SaveToStream, True);
end;
procedure TGLDObjectList.SetOnChange(Value: TNotifyEvent);
var
i: GLuint;
begin
if not Assigned(Self) then Exit;
if FCount > 0 then
for i := 1 to FCount do
FList^[i].OnChange := Value;
FOnChange := Value;
end;
procedure TGLDObjectList.SetCapacity(NewCapacity: GLuint);
begin
if (NewCapacity = FCapacity) or
(NewCapacity >= GLD_MAX_OBJECTS) then Exit;
if NewCapacity <= 0 then Clear else
begin
if NewCapacity < FCount then
SetCount(NewCapacity);
ReallocMem(FList, NewCapacity * SizeOf(TGLDVisualObject));
FCapacity := NewCapacity;
end;
end;
procedure TGLDObjectList.SetCount(NewCount: GLuint);
var
i: GLuint;
begin
if FCount <= NewCount then Exit;
if FCount <= 0 then Clear else
if NewCount < FCount then
begin
for i := NewCount + 1 to FCount do
begin
FList^[i].Free;
FList^[i] := nil;
end;
FCount := NewCount;
end;
end;
function TGLDObjectList.GetLast: TGLDVisualObject;
begin
if FCount > 0 then
Result := FList^[FCount]
else Result := nil;
end;
procedure TGLDObjectList.SetLast(Value: TGLDVisualObject);
begin
if Value = nil then Exit;
if FCount > 0 then SetObject(FCount, Value);
end;
function TGLDObjectList.GetObject(Index: GLuint): TGLDVisualObject;
begin
if (Index >= 1) and (Index <= FCount) then
Result := FList^[Index]
else Result := nil;
end;
procedure TGLDObjectList.SetObject(Index: GLuint; AObject: TGLDVisualObject);
begin
if Index = FCount + 1 then Add(AObject) else
if (Index >= 1) and (Index <= FCount) then
begin
if AObject = nil then Delete(Index) else
begin
if FList^[Index].VisualObjectClassType <>
AObject.VisualObjectClassType then
begin
FList^[Index].Free;
FList^[Index] := AObject.VisualObjectClassType.Create(Self);
FList^[Index].OnChange := FOnChange;
end;
FList^[Index].Assign(AObject);
end;
Change;
end;
end;
end.
|
{**************************************************************************************************}
{ }
{ Project JEDI Code Library (JCL) }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); }
{ you may not use this file except in compliance with the License. You may obtain a copy of the }
{ License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF }
{ ANY KIND, either express or implied. See the License for the specific language governing rights }
{ and limitations under the License. }
{ }
{ The Original Code is ExceptDlg.pas. }
{ }
{ The Initial Developer of the Original Code is documented in the accompanying }
{ help file JCL.chm. Portions created by these individuals are Copyright (C) of these individuals. }
{ }
{**************************************************************************************************}
{ }
{ Sample Application exception dialog replacement with sending report by the default mail client }
{ functionality }
{ }
{ Last modified: July 29, 2002 }
{ }
{**************************************************************************************************}
unit ExceptDlgMail;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, ExceptDlg, StdCtrls, ExtCtrls, JclMapi;
type
TExceptionDialogMail = class(TExceptionDialog)
SendBtn: TButton;
procedure SendBtnClick(Sender: TObject);
private
{ Private declarations }
protected
procedure AfterCreateDetails; override;
procedure BeforeCreateDetails; override;
function ReportMaxColumns: Integer; override;
public
{ Public declarations }
end;
var
ExceptionDialogMail: TExceptionDialogMail;
implementation
{$R *.dfm}
const
SendBugReportAddress = 'bugreport@yourdomain.com';
SendBugReportSubject = 'Bug Report';
{ TExceptionDialogMail }
procedure TExceptionDialogMail.AfterCreateDetails;
begin
inherited;
SendBtn.Enabled := True;
end;
procedure TExceptionDialogMail.BeforeCreateDetails;
begin
inherited;
SendBtn.Enabled := False;
end;
function TExceptionDialogMail.ReportMaxColumns: Integer;
begin
Result := 78;
end;
procedure TExceptionDialogMail.SendBtnClick(Sender: TObject);
begin
with TJclEmail.Create do
try
ParentWnd := Application.Handle;
Recipients.Add(SendBugReportAddress);
Subject := SendBugReportSubject;
Body := ReportAsText;
SaveTaskWindows;
try
Send(True);
finally
RestoreTaskWindows;
end;
finally
Free;
end;
end;
initialization
ExceptionDialogClass := TExceptionDialogMail;
end.
|
{ *********************************************************************** }
{ }
{ Author: Yanniel Alvarez Alfonso }
{ Description: Wrapper for the 7-Zip compression program }
{ Copyright (c) ????-2012 Pinogy Corporation }
{ }
{ *********************************************************************** }
unit SevenZipUtils;
interface
uses
Windows, SysUtils, Dialogs, Forms;
type
TArchiveFormat = (_7Z, GZIP, ZIP, BZIP2, TAR, ISO, UDF);
T7ZipWrapper = class
private
class function GetFileNameOnly(aFileName: string): string;
class function GetArchiveFormatAsString(aArchiveFormat: TArchiveFormat): string;
public
class function Archive(aSourceFolderName,
aDentinyFileName,
aFileMask : String;
aFormat: TArchiveFormat;
aPassword: string = ''): Boolean;
class function Extract(aSourceFileName: string; aPassword: string = ''): Boolean;
end;
implementation
uses
MiscUtils;
{ T7ZipWrapper }
class function T7ZipWrapper.GetFileNameOnly(aFileName: string): string;
var
FileExt: string;
begin
FileExt:= ExtractFileExt(aFileName);
Result:= Copy(aFileName, 1, Length(aFileName) - Length(FileExt));
end;
class function T7ZipWrapper.GetArchiveFormatAsString(aArchiveFormat: TArchiveFormat): string;
begin
Result:= '';
case aArchiveFormat of
_7Z: Result:= '7z';
GZIP: Result:= 'gzip';
ZIP: Result:= 'zip';
BZIP2: Result:= 'bzip2';
TAR: Result:= 'tar';
ISO: Result:= 'iso';
UDF: Result:= 'udf';
end;
end;
class function T7ZipWrapper.Archive(aSourceFolderName,
aDentinyFileName,
aFileMask : String;
aFormat: TArchiveFormat;
aPassword: string = ''): Boolean;
const
//CMD Example:'7za a -t7z files.7z *.txt'
cArchiveCMD1 = 'a -mx9 -t%0:s "%1:s" "%2:s"'; //No password considered
cArchiveCMD2 = 'a -mx9 -t%0:s "%1:s.%2:s" "%3:s"'; //No password considered
var
_7zaAbsolutePath,
ArchiveFullName,
ArchiveFormat,
ParamStr: string;
ProcID: DWord;
begin
Result:= False;
_7zaAbsolutePath:= ExtractFilePath(Application.ExeName) + '7za.exe';
if not FileExists(_7zaAbsolutePath) then Exit;
ArchiveFormat:= GetArchiveFormatAsString(aFormat);
if Pos('*.', aFileMask) = 1 then
begin
if Pos('/', aSourceFolderName) = Length(aSourceFolderName) then
Delete(aSourceFolderName, Length(aSourceFolderName), 1);
ArchiveFullName:= aSourceFolderName;
ParamStr:= Format(cArchiveCMD1, [ArchiveFormat, {ArchiveFullName}aDentinyFileName, aSourceFolderName + '\' + aFileMask]);
end
else
begin
//The file mask is actually a file name
ArchiveFullName:= GetFileNameOnly(aFileMask);
ParamStr:= Format(cArchiveCMD2, [ArchiveFormat, aSourceFolderName + ArchiveFullName, ArchiveFormat, aSourceFolderName + aFileMask]);
end;
//Adding password if needed
if aPassword <> '' then
ParamStr:= ParamStr + ' -p"' + aPassword + '"';
Result:= ExecuteProgram('7za', ParamStr, ProcID, True) = 0;
end;
class function T7ZipWrapper.Extract(aSourceFileName: string;
aPassword: string = ''): Boolean;
const
//Example: 7z e archive.zip
cExtractCMD = 'e "%0:s" -y'; //No password considered
var
_7zaAbsolutePath,
ParamStr: string;
ProcID: DWord;
begin
Result:= False;
_7zaAbsolutePath:= ExtractFilePath(Application.ExeName) + '7za.exe';
if not FileExists(_7zaAbsolutePath) then Exit;
ParamStr:= Format(cExtractCMD, [aSourceFileName]);
//Adding password if needed
if aPassword <> '' then
ParamStr:= ParamStr + ' -p"' + aPassword + '"';
Result:= ExecuteProgram('7za', ParamStr, ProcID, True) = 0;
end;
end.
|
{//************************************************************//}
{// //}
{// Código gerado pelo assistente //}
{// //}
{// Projeto MVCBr //}
{// tireideletra.com.br / amarildo lacerda //}
{//************************************************************//}
{// Data: 08/04/2017 12:03:20 //}
{//************************************************************//}
/// <summary>
/// O controller possui as seguintes características:
/// - pode possuir 1 view associado (GetView)
/// - pode receber 0 ou mais Model (GetModel<Ixxx>)
/// - se auto registra no application controller
/// - pode localizar controller externos e instanciá-los
/// (resolveController<I..>)
/// </summary>
unit TestSecond.Controller;
/// <summary>
/// Object Factory para implementar o Controller
/// </summary>
interface
{.$I ..\inc\mvcbr.inc}
uses
System.SysUtils, {$ifdef FMX} FMX.Forms,{$else} VCL.Forms,{$endif}
System.Classes, MVCBr.Interf,
MVCBr.Model, MVCBr.Controller, MVCBr.ApplicationController,
System.RTTI, TestSecond.Controller.interf,
TestSecondView;
type
TTestSecondController = class(TControllerFactory,
ITestSecondController,
IThisAs<TTestSecondController>)
protected
Procedure DoCommand(ACommand: string;
const AArgs: array of TValue); override;
public
// inicializar os módulos personalizados em CreateModules
Procedure CreateModules;virtual;
Constructor Create;override;
Destructor Destroy; override;
/// New Cria nova instância para o Controller
class function New(): IController; overload;
class function New(const AView: IView; const AModel: IModel)
: IController; overload;
class function New(const AModel: IModel): IController; overload;
function ThisAs: TTestSecondController;
/// Init após criado a instância é chamado para concluir init
procedure init;override;
end;
implementation
/// Creator para a classe Controller
Constructor TTestSecondController.Create;
begin
inherited;
/// Inicializar as Views...
View(TTestSecondView.New(self));
/// Inicializar os modulos
CreateModules; //< criar os modulos persolnizados
end;
/// Finaliza o controller
Destructor TTestSecondController.destroy;
begin
inherited;
end;
/// Classe Function basica para criar o controller
class function TTestSecondController.New(): IController;
begin
result := new(nil,nil);
end;
/// Classe para criar o controller com View e Model criado
class function TTestSecondController.New(const AView: IView;
const AModel: IModel) : IController;
var
vm: IViewModel;
begin
result := TTestSecondController.create as IController;
result.View(AView).Add(AModel);
if assigned(AModel) then
if supports(AModel.This, IViewModel, vm) then
begin
vm.View(AView).Controller( result );
end;
end;
/// Classe para inicializar o Controller com um Modulo inicialz.
class function TTestSecondController.New(
const AModel: IModel): IController;
begin
result := new(nil,AModel);
end;
/// Cast para a interface local do controller
function TTestSecondController.ThisAs: TTestSecondController;
begin
result := self;
end;
/// Executar algum comando customizavel
Procedure TTestSecondController.DoCommand(ACommand: string;
const AArgs:Array of TValue);
begin
inherited;
end;
/// Evento INIT chamado apos a inicializacao do controller
procedure TTestSecondController.init;
var ref:TTestSecondView;
begin
inherited;
if not assigned(FView) then
begin
Application.CreateForm( TTestSecondView, ref );
supports(ref,IView,FView);
{$ifdef FMX}
if Application.MainForm=nil then
Application.RealCreateForms;
{$endif}
end;
AfterInit;
end;
/// Adicionar os modulos e MODELs personalizados
Procedure TTestSecondController.CreateModules;
begin
// adicionar os seus MODELs aqui
// exemplo: add( MeuModel.new(self) );
end;
initialization
/// Inicialização automatica do Controller ao iniciar o APP
//TTestSecondController.New(TTestSecondView.New,TTestSecondViewModel.New)).init();
/// Registrar Interface e ClassFactory para o MVCBr
RegisterInterfacedClass(TTestSecondController.ClassName,ITestSecondController,TTestSecondController);
finalization
/// Remover o Registro da Interface
unRegisterInterfacedClass(TTestSecondController.ClassName);
end.
|
namespace GlHelper;
{$IF ISLAND}
interface
uses rtl,
STB,
RemObjects.Elements.RTL;
type GlImage = public class
private
fImg : glImageData;
fValid : Boolean;
method LoadCoreImage(const fullname : String) : Boolean;
public
constructor (const aPath : String);
finalizer;
property Valid : Boolean read fValid;
property Data : glImageData read fImg;
end;
implementation
method GlImage.LoadCoreImage(const fullname: String): Boolean;
begin
Var memData := Asset.loadFileBytes(fullname);
if assigned(memData) then
if length(memData) > 0 then
begin
// writeLn('Fullname '+Fullname);
fImg.imgData := stbi_load_from_memory(@memData[0],length(memData), var fImg.width, var fImg.Height, var fImg.Components, 3);
// var s := String.Format('W {0} H {1} C{3}',[fImg.width, fImg.Height, fImg.Components]);
// writeLn('w '+fImg.width.ToString + ' H '+fImg.Height.ToString+' C '+fImg.Components.ToString);
end;
// fImg.Data := stbi_load(glStringHelper.toPansichar(Asset.getFullname(fullname)), var fImg.width, var fImg.Height, var fImg.Components, 4);
result := fImg.imgData <> nil;
end;
constructor GlImage(const aPath: String);
begin
inherited ();
fValid := LoadCoreImage(aPath);
end;
finalizer GlImage;
begin
if fValid then if fImg.imgData <> nil then
stbi_image_free(fImg.imgData);
end;
{$ENDIF} // Island
end. |
unit Dialog_ListCate;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,Class_Dict, ElXPThemedControl, ElTree, StdCtrls,Class_Cate,Class_Rend,
ADODB,Class_DBPool;
type
TDialogListCate = class(TForm)
Tree_Cate: TElTree;
Btn_Ok: TButton;
Btn_Cancel: TButton;
Btn_Add: TButton;
Btn_Del: TButton;
Btn_Edi: TButton;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Btn_CancelClick(Sender: TObject);
procedure Btn_AddClick(Sender: TObject);
procedure Btn_EdiClick(Sender: TObject);
procedure Btn_DelClick(Sender: TObject);
procedure Btn_OkClick(Sender: TObject);
private
FEditCode:Integer; //0:edit,1:view
FDictRule:TDict;
protected
procedure SetInitialize;
procedure SetCommonParams;
public
function GetActiveCate:TCate;
procedure DoAddCate;
procedure DoEdiCate;
procedure DoDelCate;
procedure RendStrsCate;
function ExportObjCate:TCate;
published
property ActiveCate:TCate read GetActiveCate;
end;
var
DialogListCate: TDialogListCate;
function FuncListCate(AEditCode:Integer;ADictRule:TDict):Integer;
function FuncViewCate(AEditCode:Integer;ADictRule:TDict;var ACate:TCate):Integer;
implementation
uses
ConstValue,UtilLib,UtilLib_UiLib,Dialog_EditCate;
{$R *.dfm}
function FuncListCate(AEditCode:Integer;ADictRule:TDict):Integer;
begin
try
DialogListCate:=TDialogListCate.Create(nil);
DialogListCate.FEditCode:=AEditCode;
DialogListCate.FDictRule:=ADictRule;
Result:=DialogListCate.ShowModal;
finally
FreeAndNil(DialogListCate);
end;
end;
function FuncViewCate(AEditCode:Integer;ADictRule:TDict;var ACate:TCate):Integer;
begin
try
DialogListCate:=TDialogListCate.Create(nil);
DialogListCate.FEditCode:=AEditCode;
DialogListCate.FDictRule:=ADictRule;
Result:=DialogListCate.ShowModal;
if Result=Mrok then
begin
ACate:=DialogListCate.ExportObjCate;
end;
finally
FreeAndNil(DialogListCate);
end;
end;
procedure TDialogListCate.SetCommonParams;
begin
Caption:=FDictRule.DictName;
Btn_Ok.Visible:=False;
Btn_Cancel.Visible:=False;
Btn_Add.Visible:=False;
Btn_Del.Visible:=False;
Btn_Edi.Visible:=False;
if FEditCode=0 then
begin
Btn_Add.Visible:=True;
Btn_Edi.Visible:=True;
Btn_Del.Visible:=True;
end else
if FEditCode=1 then
begin
Btn_Ok.Visible:=True;
Btn_Cancel.Visible:=True;
end;
end;
procedure TDialogListCate.SetInitialize;
begin
SetCommonParams;
RendStrsCate;
end;
procedure TDialogListCate.FormShow(Sender: TObject);
begin
SetInitialize;
end;
procedure TDialogListCate.FormCreate(Sender: TObject);
begin
UtilLib_UiLib.SetCommonDialogParams(Self);
end;
procedure TDialogListCate.Btn_CancelClick(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TDialogListCate.Btn_AddClick(Sender: TObject);
begin
DoAddCate;
end;
function TDialogListCate.GetActiveCate: TCate;
begin
Result:=nil;
if Tree_Cate.Items.Count=0 then Exit;
if Tree_Cate.Selected=nil then Exit;
Result:=TCate(Tree_Cate.Selected.Data);
end;
procedure TDialogListCate.DoAddCate;
begin
if FDictRule=nil then Exit;
if FuncEditCate(0,ActiveCate,FDictRule)=Mrok then
begin
Sleep(500);
RendStrsCate;
end;
end;
procedure TDialogListCate.DoDelCate;
var
Item:TElTreeItem;
Cate:TCate;
ADOCon:TADOConnection;
begin
if Tree_Cate.Items.Count=0 then Exit;
Item:=Tree_Cate.Selected;
if Item=nil then
begin
ShowMessage('请选择要删除的分类');
Exit;
end;
if Item.HasChildren then
begin
ShowMessage('该分类存在子级,不可删除');
Exit;
end;
Cate:=TCate(Item.Data);
if Cate=nil then
begin
ShowMessage('对象为空,请重新选择');
Exit;
end;
try
ADOCon:=TDBPool.GetConnect();
if Cate.CheckExist(ADOCon) then
begin
ShowMessage('该分类己被使用');
Exit;
end;
if ShowBox('是否删除该分类')<>Mrok then Exit;
Cate.DeleteDB(ADOCon);
Sleep(500);
RendStrsCate;
finally
FreeAndNil(ADOCon);
end;
end;
procedure TDialogListCate.DoEdiCate;
begin
if FDictRule=nil then Exit;
if FuncEditCate(1,ActiveCate,FDictRule)=Mrok then
begin
Sleep(500);
RendStrsCate;
end;
end;
procedure TDialogListCate.Btn_EdiClick(Sender: TObject);
begin
DoEdiCate;
end;
procedure TDialogListCate.Btn_DelClick(Sender: TObject);
begin
DoDelCate;
end;
procedure TDialogListCate.RendStrsCate;
var
AStrs:TStringList;
ASQL :string;
begin
ASQL:='SELECT * FROM TBL_CATE WHERE UNIT_LINK=%S AND CATE_KIND=%S ORDER BY CODE_LINK,CATE_LEVL';
ASQL:=Format(ASQL,[QuotedStr(CONST_CODELINK),QuotedStr(FDictRule.DictCode)]);
AStrs:=TCate.StrsDB(ASQL);
TRend.RendCate(Tree_Cate,AStrs);
end;
function TDialogListCate.ExportObjCate: TCate;
begin
if Tree_Cate.Items.Count=0 then Exit;
if Tree_Cate.Selected=nil then Exit;
Result:=TCate(Tree_Cate.Selected.Data);
end;
procedure TDialogListCate.Btn_OkClick(Sender: TObject);
begin
if Tree_Cate.Items.Count=0 then
begin
ShowMessage('请选择分类');
Exit;
end;
if Tree_Cate.Selected=nil then
begin
ShowMessage('请选择分类');
Exit;
end;
if Tree_Cate.Selected.HasChildren then
begin
ShowMessage('请选择最底级分类');
Exit;
end;
ModalResult:=mrOk;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, ExtCtrls, Encryp;
type
TForm1 = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
Memo1: TMemo;
Panel3: TPanel;
edtPassword: TEdit;
Label2: TLabel;
encbtn: TBitBtn;
decbtn: TBitBtn;
closebtn: TBitBtn;
Panel4: TPanel;
BitBtn4: TBitBtn;
OpenDialog1: TOpenDialog;
SaveDialog1: TSaveDialog;
Label1: TLabel;
BitBtn5: TBitBtn;
Panel5: TPanel;
Encryption1: TEncryption;
procedure BitBtn4Click(Sender: TObject);
procedure BitBtn5Click(Sender: TObject);
procedure closebtnClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure encbtnClick(Sender: TObject);
procedure decbtnClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.BitBtn4Click(Sender: TObject);
begin
if OpenDialog1.Execute then
Memo1.Lines.LoadFromFile(OpenDialog1.FileName);
end;
procedure TForm1.BitBtn5Click(Sender: TObject);
begin
if SaveDialog1.Execute then
Memo1.Lines.SavetoFile(SaveDialog1.FileName);
end;
procedure TForm1.closebtnClick(Sender: TObject);
begin
Close;
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Application.Terminate;
end;
procedure TForm1.encbtnClick(Sender: TObject);
begin
Encryption1.Input := Memo1.Lines.Text;
Encryption1.Key := edtPassword.Text;
Encryption1.Action := atEncryption;
Encryption1.Execute;
Memo1.Lines.Text := Encryption1.Output;
end;
procedure TForm1.decbtnClick(Sender: TObject);
begin
Encryption1.Input := Memo1.Lines.Text;
Encryption1.Key := edtPassword.Text;
Encryption1.Action := atDecryption;
Encryption1.Execute;
Memo1.Lines.Text := Encryption1.Output;
end;
end.
|
unit DXgrid1;
interface
uses windows,DXTypes, Direct3D9G, D3DX9G,
util1, stmObj;
type
TmatInf3D=record
D0,Fov:single;
thetaX,thetaY,thetaZ:single;
mode:byte;
end;
type
TDXgridVertex=
record
position:TD3DVECTOR ;
normal: TD3DVECTOR ;
color:TD3DCOLOR;
end;
const
DXgridFormat=D3DFVF_XYZ or D3DFVF_NORMAL or D3DFVF_DIFFUSE;
{ TDXgrid permet d'afficher une matrice
initData remplit le tableau Vertex
Il faut appeler freeData à chaque fois que les données de la matrice sont modifiées
InitResources construit le vertex buffer sur la carte graphique
Il faut appeler FreeResources à chaque fois que ce buffer doit être reconstruit.
}
type
TDXgrid= class
private
I1,I2,J1,J2: integer;
Dx3D, x03D, Dy3D, y03D: single;
vertex: array of TDXgridVertex;
VB: Idirect3DVertexBuffer9;
Material: TD3DMATERIAL9 ;
LightDir: TD3DXVECTOR3;
light: TD3DLIGHT9;
public
constructor create;
procedure initData( mat1:TypeUO);
procedure FreeData;
procedure InitResources(Idevice: IDirect3DDevice9);
procedure freeResources;
procedure render(Idevice: IDirect3DDevice9);
procedure Display(Idevice: IDirect3DDevice9; mat1: TypeUO);
end;
implementation
{ TDXgrid }
uses stmMat1;
constructor TDXgrid.create;
begin
fillchar(material, SizeOf(material),0);
material.Diffuse.r := 1.0; material.Ambient.r := 1.0;
material.Diffuse.g := 1.0; material.Ambient.g := 1.0;
material.Diffuse.b := 0.0; material.Ambient.b := 0.0;
material.Diffuse.a := 1.0; material.Ambient.a := 1.0;
fillchar(light, sizeof(light),0);
light._Type := D3DLIGHT_DIRECTIONAL;
light.Diffuse.r := 1;
light.Diffuse.g := 1;
light.Diffuse.b := 1;
light.ambient.r := 0.2;
light.ambient.g := 0.2;
light.ambient.b := 0.2;
LightDir:= D3DXVector3(-1,-1,0 );
D3DXVec3Normalize(light.Direction, LightDir);
light.Range := 1000;
end;
procedure TDXgrid.display(Idevice: IDirect3DDevice9; mat1:typeUO);
var
mat: Tmatrix absolute mat1;
ViewPort: TD3DVIEWPORT9;
res:longword;
vEyePt, vLookatPt, vUpVec, CG: TD3DVector;
Amat,matX,matZ: TD3Dmatrix;
matWorld,matView,matProj: TD3Dmatrix;
Kf:single;
begin
with mat do
begin
Kf:=(Xmax-Xmin+ Ymax-Ymin )/2; // largeur moyenne de l'objet
CG.x:=(Xmin+Xmax)/2;
CG.y:=(Ymin+Ymax)/2;
CG.z:=(Zmin+Zmax)/2;
end;
Idevice.GetViewport (Viewport);
Idevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, D3Dcolor_XRGB(0,0,0), 1, 0);
IDevice.SetMaterial(Material);
IDevice.SetLight(0, Light);
IDevice.LightEnable(0, TRUE);
IDevice.SetRenderState(D3DRS_LIGHTING, iTrue);
IDevice.SetRenderState(D3DRS_AMBIENT, $00808080);
D3DXMatrixTranslation(matWorld,-CG.x,-CG.y,-CG.z);
with mat do
if Zmin<>Zmax then
begin
D3DXMatrixScaling(Amat,1,1, Kf/(Zmax-Zmin)*100/inf3D.D0 );
D3DXMatrixMultiply(matWorld,matWorld,Amat);
end;
D3DXMatrixRotationZ(Amat, mat.inf3D.thetaZ*pi/180);
D3DXMatrixMultiply(matWorld,matWorld,Amat);
D3DXMatrixRotationY(Amat, mat.inf3D.thetaX*pi/180);
D3DXMatrixMultiply(matWorld,matWorld,Amat);
IDevice.SetTransform(D3DTS_WORLD, matWorld);
vEyePt:= D3DXVector3(mat.inf3D.D0/100*Kf,0,0);
vLookatPt:= D3DXVector3zero;
vUpVec:= D3DXVector3(0, 0, 1);
D3DXMatrixLookAtRH(matView, vEyePt, vLookatPt, vUpVec);
IDevice.SetTransform(D3DTS_VIEW, matView);
D3DXMatrixPerspectiveFovRH(matProj, mat.inf3D.Fov *pi/180, viewport.width/ viewPort.Height, 1, 1000);
IDevice.SetTransform(D3DTS_PROJECTION, matProj);
IDevice.SetRenderState(D3DRS_SHADEMODE, D3DSHADE_FLAT);
if (SUCCEEDED(Idevice.BeginScene)) then
begin
try
render(Idevice);
finally
Idevice.EndScene;
end;
end;
end;
procedure TDXgrid.initData(mat1:TypeUO);
var
i,j,n:integer;
normx, normy, normz, normx1, normy1, normz1: TD3DVector;
norm: TD3DVector;
mat: Tmatrix absolute mat1;
Vmin,Vmax:float;
col:integer;
function convx3D(i:integer):single;
begin
result:=Dx3D*i+x03D;
end;
function convy3D(i:integer):single;
begin
result:=Dy3D*i+y03D;
end;
function get3DV(i,j:integer):single;
begin
with mat do
begin
if inverseX then i:=I2+I1-i;
if inverseY then j:=J2+J1-j;
result:=getSmoothVal(i,j);
end;
end;
procedure setVertex(i,j:integer;z:single;n:TD3Dvector;col:longword);
begin
setlength(Vertex, length(Vertex)+1);
with Vertex[length(Vertex)-1] do
begin
position := D3DXVECTOR3( convx3D(i),convy3D(j), z );
normal := n;
color := $FF000000 or col;
end;
end;
begin
if length(vertex)>0 then exit;
VB:=nil;
with Tmatrix(mat1) do
begin
I1:= Istart;
J1:= Jstart;
case visu.modeMat of
0: begin
I2:=Iend;
J2:=Jend;
dx3D:=dxu;
x03D:=x0u;
dy3D:=dyu;
y03D:=y0u;
end;
1,2: begin
I2:=Istart+(Iend-Istart+1)*3-1;
J2:=Jstart+(Jend-Jstart+1)*3-1;
dx3D:=dxu/3;
x03D:=x0u + 2/3*Dxu;
dy3D:=dyu/3;
y03D:=y0u + 2/3*Dyu;;
end;
end;
end;
setLength(vertex,0);
normx := D3DXVector3( 1 ,0, 0 );
normx1 := D3DXVector3(-1 ,0, 0 );
normy := D3DXVector3( 0, 1, 0 );
normy1 := D3DXVector3( 0,-1, 0 );
normz := D3DXVector3( 0, 0, 1 );
normz1 := D3DXVector3( 0, 0,-1 );
for j:=J1 to J2 do
for i:=I1 to I2 do
begin
col:=random(256)*65536 +random(256)*256 +random(256) ;
//col:= rgb(128,128,128);
setvertex(i,j,get3DV(i,j),normz, col); //1
setvertex(i,j+1,get3DV(i,j),normz, col); //2
setvertex(i+1,j,get3DV(i,j),normz, col); //3
setvertex(i+1,j+1,get3DV(i,j),normz, col); //4
setvertex(i+1,j,get3DV(i,j),normz, col); //3
setvertex(i,j+1,get3DV(i,j),normz,col); //2
if i<I2 then
begin
if get3DV(i+1,j)<get3DV(i,j) then Norm:=normx else Norm:=normx1;
col:=random(256)*65536 +random(256)*256 +random(256) ;
setvertex(i+1,j,get3DV(i,j),norm,col); //3
setvertex(i+1,j+1,get3DV(i,j),norm,col); //4
setvertex(i+1,j,get3DV(i+1,j),norm,col); //5
setvertex(i+1,j+1,get3DV(i+1,j),norm,col); //6
setvertex(i+1,j,get3DV(i+1,j),norm,col); //5
setvertex(i+1,j+1,get3DV(i,j),norm,col); //4
end;
if j<J2 then
begin
if get3DV(i,j+1)<get3DV(i,j) then Norm:=normy else Norm:=normy1;
col:=random(256)*65536 +random(256)*256 +random(256) ;
setvertex(i+1,j+1,get3DV(i,j),norm,col); //4
setvertex(i,j+1, get3DV(i,j), norm,col); //2
setvertex(i+1,j+1, get3DV(i,j+1), norm,col); //6
setvertex(i+1,j+1, get3DV(i,j+1), norm,col); //6
setvertex(i,j+1, get3DV(i,j), norm,col); //2
setvertex(i,j+1, get3DV(i,j+1), norm,col); //9
end;
end;
end;
procedure TDXgrid.InitResources(Idevice: IDirect3DDevice9);
var
pVertices: pointer;
begin
if VB<>nil then exit;
if IDevice.CreateVertexBuffer( sizeof(TDXgridVertex)*length(Vertex),
0, DXgridFormat ,
D3DPOOL_DEFAULT, VB, nil )<>0 then exit;
if FAILED(VB.Lock(0, 0, pVertices, 0)) then Exit;
CopyMemory(pVertices, @vertex[0], SizeOf(TDXgridVertex)*length(vertex));
VB.Unlock;
end;
procedure TDXgrid.FreeData;
begin
setLength(vertex,0);
FreeResources;
end;
procedure TDXgrid.render(Idevice: IDirect3DDevice9);
var
i,j,N, res:integer;
begin
res:=IDevice.SetStreamSource(0, VB, 0, SizeOf(TDXgridVertex));
if res<>0 then exit;
res:=IDevice.SetFVF(DXgridFormat);
if res<>0 then exit;
N:= length(vertex);
IDevice.DrawPrimitive( D3DPT_TRIANGLELIST, 0, N div 3 );
end;
procedure TDXgrid.freeResources;
begin
VB:=nil;
end;
end.
|
unit UContasPagarVO;
interface
uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO, UPessoasVO,
UHistoricoVO, UCondominioVO, UPlanoContasVO;
type
[TEntity]
[TTable('ContasPagar')]
TContasPagarVO = class(TGenericVO)
private
FidContasPagar : Integer;
FDtCompetencia : TDateTime;
FDtEmissao : TDateTime;
FDtVencimento: TDateTime;
FNrDocumento : String;
FVlValor : Currency;
FDsComplemento : String;
FIdHistorico : Integer;
FFlBaixa : String;
FIdConta : Integer;
FIdCondominio : Integer;
FIdPessoa : Integer;
FIdContraPartida : Integer;
FNomePessoa : string;
FVlBaixa : Currency;
FVlJuros : Currency;
FVlMulta : Currency;
FVlDesconto : Currency;
FDtBaixa : TDateTime;
FIdContaBaixa : Integer;
FIdHistoricoBx : Integer;
FVlPago : Currency;
public
CondominioVO : TCondominioVO;
PessoaVO : TPessoasVO;
PlanoContasContaVO : TPlanoContasVO;
PlanoContasContraPartidaVO : TPlanoContasVO;
HistoricoVO : THistoricoVO;
[TId('idContasPagar')]
[TGeneratedValue(sAuto)]
property idContasPagar : Integer read FidContasPagar write FidContasPagar;
[TColumn('DtCompetencia','Data Competencia',50,[ldLookup,ldComboBox], False)]
property DtCompetencia: TDateTime read FDtCompetencia write FDtCompetencia;
[TColumn('DtVencimento','Data Vencimento',50,[ldGrid,ldLookup,ldComboBox], False)]
property DtVencimento: TDateTime read FDtVencimento write FDtVencimento;
[TColumn('DtEmissao','Data Emissão',50,[ldGrid,ldLookup,ldComboBox], False)]
property DtEmissao: TDateTime read FDtEmissao write FDtEmissao;
[TColumn('NrDocumento','Documento',100,[ldGrid,ldLookup,ldComboBox], False)]
property NrDocumento: string read FNrDocumento write FNrDocumento;
// Atributos Transientes
[TColumn('NOME','Pessoa',390,[ldGrid], True, 'Pessoa', 'idPessoa', 'idPessoa')]
property NomePessoa: string read FNomePessoa write FNomePessoa;
[TColumn('VlValor','Valor',80,[ldGrid,ldLookup,ldComboBox], False)]
property VlValor: Currency read FVlValor write FVlValor;
[TColumn('DsComplemento','Complemento',0,[ldLookup,ldComboBox], False)]
property DsComplemento: String read FDsComplemento write FDsComplemento;
[TColumn('IdHistorico','Histórico',0,[ldLookup,ldComboBox], False)]
property IdHistorico: integer read FIdHistorico write FIdHistorico;
[TColumn('FlBaixa','Situação',10,[ldGrid,ldLookup,ldComboBox], False)]
property FlBaixa: String read FFlBaixa write FFlBaixa;
[TColumn('IdConta','Id Conta',0,[ldLookup,ldComboBox], False)]
property IdConta: Integer read FIdConta write FIdConta;
[TColumn('IdCondominio','Id Condominio',0,[ldLookup,ldComboBox], False)]
property IdCondominio: Integer read FIdCondominio write FIdCondominio;
[TColumn('IdPessoa','Id Pessoa',50,[ldLookup,ldComboBox], False)]
property IdPessoa: Integer read FIdPessoa write FIdPessoa;
[TColumn('IdContraPartida','Id Contra Partida',0,[ldLookup,ldComboBox], False)]
property IdContraPartida: Integer read FIdContraPartida write FIdContraPartida;
[TColumn('VlBaixa','Valor',100,[ldLookup,ldComboBox], False)]
property VlBaixa: Currency read FVlBaixa write FVlBaixa;
[TColumn('VlJuros','Juros',100,[ldLookup,ldComboBox], False)]
property VlJuros: Currency read FVlJuros write FVlJuros;
[TColumn('VlMulta','Multa',100,[ldLookup,ldComboBox], False)]
property VlMulta: Currency read FVlMulta write FVlMulta;
[TColumn('VlDesconto','Desconto',100,[ldLookup,ldComboBox], False)]
property VlDesconto: Currency read FVlDesconto write FVlDesconto;
[TColumn('DtBaixa','Data Emissão',50,[ldLookup,ldComboBox], False)]
property DtBaixa: TDateTime read FDtBaixa write FDtBaixa;
[TColumn('IdContaBaixa','Id Conta',0,[ldLookup,ldComboBox], False)]
property IdContaBaixa: Integer read FIdContaBaixa write FIdContaBaixa;
[TColumn('IdHistoricoBx','Id Conta',0,[ldLookup,ldComboBox], False)]
property IdHistoricoBx: Integer read FIdHistoricoBx write FIdHistoricoBx;
[TColumn('VlPago','Valor Pago',100,[ldLookup,ldComboBox], False)]
property VlPago: Currency read FVlPago write FVlPago;
procedure ValidarCampos;
procedure ValidarBaixa;
end;
implementation
procedure TContasPagarVO.ValidarBaixa;
begin
if (Self.FDtBaixa = 0) then
raise Exception.Create('O campo Data Baixa é obrigatório!');
if ((Self.FVlBaixa <= 0) or (self.FVlBaixa <> self.VlValor)) then
raise Exception.Create('O campo Valor Baixa é obrigatório e não pode ser diferente que o valor!');
if ( Self.FVlPago<=0) then
raise Exception.Create('O campo Valor é obrigatório!');
if (self.FDtBaixa < self.FDtEmissao) then
raise Exception.Create('A data da baixa não pode ser menor que a data de emissão!');
if (Self.FIdContaBaixa = 0) then
raise Exception.Create('O campo Conta é obrigatório!');
if Self.vlpago > self.vlvalor then
begin
if ((self.vlbaixa + Self.VlJuros + self.VlMulta - self.VlDesconto) <> self.VlPago) then
raise Exception.Create('Valor não confere!');
end
else if Self.VlPago < self.VlValor then
begin
if ((self.VlPago + self.vldesconto) <> self.vlValor) then
raise Exception.Create('Valor não confere');
end;
end;
procedure TContasPagarVO.ValidarCampos;
begin
if (Self.FDtCompetencia = 0 ) then
raise Exception.Create('O campo Data Competencia é obrigatório!');
if (Self.FDtEmissao = 0) then
raise Exception.Create('O campo Data Emissão é obrigatório!');
if (Self.FNrDocumento= '') then
raise Exception.Create('O campo Documento é obrigatório!');
if (Self.FDtCompetencia = 0) then
raise Exception.Create('O campo Data Vencimento é obrigatório!');
if (Self.FVlValor <= 0) then
raise Exception.Create('O campo Valor é obrigatório!');
if (Self.FDtVencimento < self.FDtEmissao) then
raise Exception.Create('A data de emissão deve ser menor que a data de vencimento!');
end;
end.
|
{* ***** BEGIN LICENSE BLOCK *****
Copyright 2010 Sean B. Durkin
This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free
software being offered under a dual licensing scheme: LGPL3 or MPL1.1.
The contents of this file are subject to the Mozilla Public License (MPL)
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
Alternatively, you may redistribute it and/or modify it under the terms of
the GNU Lesser General Public License (LGPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
You should have received a copy of the Lesser GNU General Public License
along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>.
TurboPower LockBox is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. In relation to LGPL,
see the GNU Lesser General Public License for more details. In relation to MPL,
see the MPL License for the specific language governing rights and limitations
under the License.
The Initial Developer of the Original Code for TurboPower LockBox version 2
and earlier was TurboPower Software.
* ***** END LICENSE BLOCK ***** *}
unit uTPLb_RSA_Primitives;
// This unit implements the primitives specified in RFC-3447
// http://www.ietf.org/rfc/rfc3447.txt &
// http://www.rfc-editor.org/errata_search.php?rfc=3447
interface
uses
uTPLB_HugeCardinal, Classes, uTPLb_MemoryStreamPool, uTPLb_StreamCipher,
uTPLb_BlockCipher, uTPLb_Hash;
function I2OSP( x: THugeCardinal; xLen: integer;
XStream: TStream; const Pool: IMemoryStreamPool): boolean;
// Integer-to-Octet-String primitive
// I2OSP converts a huge cardinal to a byte stream of the specified length.
// Inputs:
// x The number to be converted.
// xLen The intended length in bytes of the output octet stream.
// Pool Optional memory stream pool for re-cycling memory.
// Outputs:
// XStream The corresponding octet stream is written to this TStream
// at the input position. The stream is not resized or repositioned
// before output.
// result Returns True if the operation was successful;
// False if xLen was too small for x.
function OS2IP( XStream: TStream; xLen: integer;
var x: THugeCardinal;
const Pool: IMemoryStreamPool; MaxBits: integer): boolean;
// Octet-String-to-Integer primitive
// OS2IP converts byte stream of the specified length to a new huge cardinal.
// Inputs:
// XStream The octet stream to be converted.
// The stream is not resized or repositioned
// before reading, but is read from its current (input) position.
// xLen The length in bytes of the octet stream to be read. The
// stream must have this many bytes readable or an exception
// will be raised. (units are bytes)
// Pool Construction parameter for huge cardinal.
// MaxBits Construction parameter for huge cardinal. (units are bits)
// Outputs:
// x The number converted to. On input this is nil or dangling.
// On output, a new THugeCardinal is created.
// result Returns True if the operation was successful;
// False if xLen was too large for MaxBits.
procedure MGF1( mgfSeed: TStream; maskLen: cardinal; mask: TStream);
// MGF1 is a Mask Generation Function based on SHA-1.
// Inputs:
// mgfSeed The octet stream which seeds deterministically the output.
// The seed is the whole stream.
// maskLen The intented length in bytes of the output mask.
// Outputs:
// mask The mask or output stream created. Must not be nil on input.
type
TLongOpResult = (opPass, opFail, opAbort);
function RSAES_OAEP_ENCRYPT( n, e: THugeCardinal; M, C: TMemoryStream): boolean;
// RSAES-OAEP-ENCRYPT is the RSA encryption primitive.
// Inputs:
// n The RSA encryption public key modulus.
// e The RSA encryption public key exponent.
// M The plaintext to be encrypted.
// Outputs:
// C The encrypted ciphertext. This stream is cleared on input.
// The byte length of C, mlen must not more the byte length of
// the modulus (k), less twice the hash length (hLen), less 2.
// mLen <= k - 2 * hLen - 2
// The hash used is SHA-1, so hLen = 20.
// result True if successful; False if failed.
function RSAES_OAEP_ENCRYPT_MaxByteLen( n: THugeCardinal): integer;
// Computes the maximum byte length for M in the RSAES_OAEP_ENCRYPT function.
// Inputs:
// n The RSA encryption public key modulus.
// Outputs:
// result The maximum byte length for M. See comments about the
// RSAES_OAEP_ENCRYPT function.
// result := k - 2 * hLen - 2
function RSAES_OAEP_DECRYPT( d, n: THugeCardinal; C, M: TStream;
p, q, dp, dq, qinv: THugeCardinal): boolean;
// RSAES-OAEP-DECRYPT is the RSA decryption primitive.
// Inputs:
// n The RSA encryption public key modulus.
// d The RSA encryption private key exponent.
// C The ciphertext to be decrypted. Length = length of n in bytes.
// p, q, dp, dq, qinv: Optional break-down of d for use in CRT.
// Outputs:
// M The decrypted plaintext. This stream is cleared on input.
// The hash used is SHA-1, so hLen = 20.
// result True if successful; False if failed.
function EMSA_PSS_ENCODE( M: TStream; emBits, sLen: integer; EM: TStream;
CheckAbortFunc: TOnHashProgress): TLongOpResult;
// EMSA-PSS-ENCODE is the RSA message encoding primitive used by Sign & Verify.
// Inputs:
// M message to be encoded, an octet string.
// emBits maximal bit length of the integer OS2IP (EM),
// at least 8hLen + 8sLen + 9
// sLen Intended length in octets of the salt
// Outputs:
// EM encoded message, an octet string of length emLen = \ceil
// (emBits/8)
// result True if successful; False if failed (due to emBits being too small.)
// Using:
// Hash hash function (hLen denotes the length in octets of the hash
// function output) used is SHA-1.
// MGF mask generation function uses is MGF1.
function RSASSA_PSS_SIGN( d, n: THugeCardinal; M, S: TStream;
CheckAbortFunc: TOnHashProgress;
p, q, dp, dq, qinv: THugeCardinal): TLongOpResult;
// RSASSA-PSS-SIGN is the RSA signature generation primitive.
// Inputs:
// d The signer's RSA private key exponent.
// n The signer's RSA public key modulus.
// M The message to be signed.
// Outputs:
// S The signature.
// result = opPass The operation was successful.
// = opFail The operation failed for some reason other than user abort.
// = opAbort The operation was aborted by the user before it could be completed.
function EMSA_PSS_VERIFY( M: TStream; emBits, sLen: integer; EM: TStream;
CheckAbortFunc: TOnHashProgress): TLongOpResult;
// EMSA-PSS-VERIFY
// It is the inverse of EMSA-PSS-ENCODE
function RSASSA_PSS_VERIFY( n, e: THugeCardinal; M, S: TStream;
CheckAbortFunc: TOnHashProgress): TLongOpResult;
// RSASSA-PSS-VERIFY
// Inputs:
// n The signer's RSA public key modulus.
// e The signer's RSA private key exponent.
// M The message whose signature is to be verified.
// S The signature to be verified.
// Outputs:
// result = opPass The verification passed.
// = opFail The verification failed for some reason other than user abort.
// = opAbort The verification was aborted by the user before it could be completed.
function Generate_RSA_SymetricKey(
n, e: THugeCardinal; CipherStream: TStream;
const SymetricCipher: IBlockCipher): TSymetricKey;
function Extract_RSA_SymetricKey(
d, n, p, q, dp, dq, qinv: THugeCardinal; CipherStream: TStream;
const SymetricCipher: IBlockCipher): TSymetricKey;
{$IF compilerversion > 15}
{$REGION 'Algorithm archive'}
{$ENDIF}
var
// Set the following variable to a non-zero value access older behaviour.
// Or leave as zero for default.
RSA_Primitives_AlgorithmVersion: integer = 0;
const
V3_0_0_BaseIdx = 1;
RSA_Primitives_Algorithm: array[ 0..V3_0_0_BaseIdx {Insert RSA_Primitives_AlgorithmVersion here}] of record
TPLB3_Version_Low, TPLB3_Version_High: string;
end = (
{0, The current version ==> } ( TPLB3_Version_Low: '3.4.1'; TPLB3_Version_High: ''),
{1, An older version ==> } ( TPLB3_Version_Low: '3.0.0'; TPLB3_Version_High: '3.4.0'));
{$IF compilerversion > 15}
{$ENDREGION}
{$ENDIF}
var
UseCRT: boolean = True;
implementation
uses uTPLb_PointerArithmetic, SysUtils, Math, uTPLb_SHA1,
uTPLb_HashDsc, uTPLb_StreamUtils, SyncObjs, uTPLb_Random, uTPLb_I18n
{$IFDEF SI}
, SmartInspect,
SiAuto
{$ENDIF}
;
var
hLen1: integer = -1;
HashOfNil: TMemoryStream = nil;
GlobalsGate: TCriticalSection;
function CreateHashDscObject( var Obj: TObject): IHashDsc;
begin
result := nil;
Obj := TSHA1.Create;
Supports( Obj, IHashDsc, result)
end;
function AcquireHash( var Obj: TObject): IHash;
var
HashObj: TSimpleHash;
Dsc: TObject;
begin
result := nil;
HashObj := TSimpleHash.Create;
Obj := HashObj;
Supports( Obj, IHash, result);
result.Hash := CreateHashDscObject( Dsc)
end;
procedure ReleaseHash( Obj: TObject; var H: IHash);
begin
H := nil;
Obj.Free
end;
function hLen: integer;
var
H: TObject;
HI: IHashDsc;
begin
if hLen1 = -1 then
begin
HI := CreateHashDscObject( H);
hLen1 := HI.DigestSize div 8;
HI := nil;
end;
result := hLen1
end;
procedure ReleaseHashSharedObjects;
begin
hLen1 := -1
end;
procedure InitUnit_RSA_Primitives;
begin
hLen1 := -1;
HashOfNil := nil;
GlobalsGate := TCriticalSection.Create
{$IFDEF RELEASE};
// Release configuration build.
{$ENDIF}
{$IFDEF DEBUG};
// Debug configuration build.
{$ENDIF}
{$IFDEF SI};
Si.Enabled := True;
SiMain.ClearLog;
{$ENDIF}
end;
procedure DoneUnit_RSA_Primitives;
begin
FreeAndNil( GlobalsGate);
FreeAndNil( HashOfNil)
end;
function I2OSP( x: THugeCardinal; xLen: integer; XStream: TStream;
const Pool: IMemoryStreamPool): boolean;
begin
result := xLen >= ((x.BitLength + 7) div 8);
if result then
x.StreamOut( BigEndien, XStream, xLen)
end;
function OS2IP( XStream: TStream; xLen: integer;
var x: THugeCardinal;
const Pool: IMemoryStreamPool; MaxBits: integer): boolean;
begin
if (RSA_Primitives_AlgorithmVersion <> V3_0_0_BaseIdx) and
((XStream.Size - XStream.Position) <> xLen) then
raise Exception.Create('OS2IP wrong parameter');
try
x := THugeCardinal.CreateFromStreamIn( MaxBits, BigEndien, XStream, Pool);
result := Assigned( x)
except
x := nil;
result := False
end end;
procedure MGF1( mgfSeed: TStream; maskLen: cardinal; mask: TStream);
var
Counter: longword;
HashObj: TObject;
Hash: IHash;
xfer: integer;
Buffer: array[0..99] of byte;
// Assume SizeOf( Buffer) >= (TSHA1.DigestSize div 8)
begin
mask.Size := 0;
if maskLen <= 0 then exit;
Hash := AcquireHash( HashObj);
try
Counter := 0;
repeat
Hash.Begin_Hash;
Hash.UpdateMemory( Counter, SizeOf(Counter));
mgfSeed.Position := 0;
repeat
xfer := mgfSeed.Read( Buffer, SizeOf( Buffer));
if xfer > 0 then
Hash.UpdateMemory( Buffer, xfer);
until xfer < SizeOf( Buffer);
Hash.End_Hash;
xfer := Min( maskLen, Hash.Hash.DigestSize div 8); // = 20 bytes for SHA-1
Hash.HashOutputValue.ReadBuffer( Buffer, xfer);
mask.WriteBuffer( Buffer, xfer);
Dec( maskLen, xfer);
Inc( Counter)
until maskLen <= 0;
finally
ReleaseHash( HashObj, Hash)
end end;
function RSAES_OAEP_ENCRYPT_MaxByteLen( n: THugeCardinal): integer;
begin
if RSA_Primitives_AlgorithmVersion = V3_0_0_BaseIdx then
result := ((n.BitLength - 1) div 8) - (2 * hLen) - 2
else
result := ((n.BitLength + 7) div 8) - (2 * hLen) - 2;
if result < 0 then
result := 0
end;
procedure CheckHashOfNil;
var
HI: IHash;
H: TObject;
begin
GlobalsGate.Enter;
try
if assigned( HashOfNil) then exit;
HashOfNil := TMemoryStream.Create;
HI := AcquireHash( H);
HI.Begin_Hash;
HI.End_Hash;
HashOfNil.CopyFrom( HI.HashOutputValue, 0);
ReleaseHash( H, HI)
finally
GlobalsGate.Leave
end end;
function RSAES_OAEP_ENCRYPT( n, e: THugeCardinal; M, C: TMemoryStream): boolean;
var
mLen: integer;
k: integer; // Largest number of bytes that guarentees a number from those bytes is less than n
j: integer;
DB, Seed, dbMask, maskedDB, seedMask, maskedSeed, EM: TMemoryStream;
m1: THugeCardinal;
{$IFDEF SI}
Ok: boolean;
{$ENDIF}
function NewMemoryStream: TMemoryStream;
begin
if assigned( n.FPool) then
result := n.FPool.NewMemoryStream( 0)
else
result := TMemoryStream.Create
end;
procedure PutByte( S: TStream; byte1: byte);
begin
S.Write( byte1, 1)
end;
begin
{$IFDEF SI}
SiMain.EnterMethod( 'RSAES_OAEP_ENCRYPT');
SiMain.LogStream( 'n', n.FValue);
SiMain.LogInteger( 'n.BitLen', n.BitLength);
SiMain.LogInteger( 'n.MaxBits', n.MaxBits);
SiMain.LogStream( 'M', M);
{$ENDIF}
DB := nil; Seed := nil; dbMask := nil; maskedDB := nil; seedMask := nil;
maskedSeed := nil; EM := nil; m1 := nil;
try
C.Size := 0;
mLen := M.Size;
{$IFDEF SI}
SiMain.LogInteger( 'mLen', mLen);
{$ENDIF}
// Step 1.b
// We require Require 0 < mLen <= (k - (2 * hLen) - 2)
// where k = (n.BitLength - 1) div 8
result := mLen <= RSAES_OAEP_ENCRYPT_MaxByteLen( n);
if not result then exit;
// Step 2.a
CheckHashOfNil; // HashOfNil has hLen = 20 bytes.
if RSA_Primitives_AlgorithmVersion = V3_0_0_BaseIdx then
k := (n.BitLength - 1) div 8
else
k := (n.BitLength + 7) div 8;
{$IFDEF SI}
SiMain.LogInteger( 'k', k);
{$ENDIF}
// DB = lHash || PS || 0x01 || M. Len = k - hLen - 1
DB := NewMemoryStream;
DB.Write( HashOfNil.Memory^, HashOfNil.Size); // Dont use CopyFrom on a global.
// Step 2.b and 2.c
for j := 0 to k - mLen - (2 * hLen) - 3 do
PutByte( DB, 0); // PS = stream of zeros. Len = k - mLen - (2 * hLen) - 2
PutByte( DB, 1);
DB.CopyFrom( M, 0);
{$IFDEF SI}
SiMain.LogStream( 'DB', DB);
{$ENDIF}
// Step 2.d
// seed = random. len = hLen
Seed := NewMemoryStream;
Seed.Size := hLen;
RandomFillStream( Seed);
{$IFDEF SI}
SiMain.LogStream( 'Seed', Seed);
{$ENDIF}
// Step 2.e
// dbMask = MGF1( seed, k - hLen - 1). Len = k - hLen - 1
dbMask := NewMemoryStream;
MGF1( Seed, k - hLen - 1, dbMask);
{$IFDEF SI}
SiMain.LogStream( 'dbMask', dbMask);
{$ENDIF}
// Step 2.f
//maskedDB = DB xor dbMask. Len = k - hLen - 1
maskedDB := NewMemoryStream;
maskedDB.Size := k - hLen - 1;
XOR_Streams3( maskedDB, DB, dbMask);
{$IFDEF SI}
SiMain.LogStream( 'maskedDB', maskedDB);
{$ENDIF}
// Step 2.g
// seedMask = MGF1( maskedDB, hLen). Len = hLen
seedMask := NewMemoryStream;
MGF1( maskedDB, hLen, seedMask);
{$IFDEF SI}
SiMain.LogStream( 'seedMask', seedMask);
{$ENDIF}
// Step 2.h
// maskedSeed = seed xor seedMask. Len = hLen
maskedSeed := NewMemoryStream;
maskedSeed.Size := hLen;
XOR_Streams3( maskedSeed, Seed, SeedMask);
{$IFDEF SI}
SiMain.LogStream( 'maskedSeed', maskedSeed);
{$ENDIF}
// Step 2.i
// EM = 0x00 || maskedSeed || maskedDB. Len = k
EM := NewMemoryStream;
PutByte( EM, 0);
EM.CopyFrom( maskedSeed, 0);
EM.CopyFrom( maskedDB, 0);
{$IFDEF SI}
SiMain.LogStream( 'EM', EM);
{$ENDIF}
// Step 3.a
// m = OS2IP (EM). m:THugeInteger. m.BitLength = k*8
EM.Position := 0;
{$IFDEF SI}
Ok := OS2IP( EM, k, m1, n.FPool, n.bitlength);
SiMain.LogBoolean( 'm = OS2IP( EM) Ok', Ok);
if Ok then
begin
Ok := not (m1.Compare( n) in [rGreaterThan, rEqualTo]);
SiMain.LogStream( 'm', m1.FValue);
SiMain.LogInteger( 'm.BitLen', m1.BitLength);
SiMain.LogInteger( 'm.MaxBits', m1.MaxBits);
SiMain.LogBoolean( 'm < n', Ok);
end;
if not Ok then
raise Exception.Create('RSAES_OAEP_ENCRYPT ' + ES_InternalError_Suffix);
{$ELSE}
if (not OS2IP( EM, k, m1, n.FPool, n.bitlength)) or
(m1.Compare( n) in [rGreaterThan, rEqualTo]) then
raise Exception.Create('RSAES_OAEP_ENCRYPT ' + ES_InternalError_Suffix);
{$ENDIF}
// Step 3.b
// c = m ** e mod n; // RSAEP
m1.PowerMod( e, n, nil); // 0 <= m1 < n
{$IFDEF SI}
SiMain.LogStream( 'c', m1.FValue);
{$ENDIF}
// Step 3.c
// C = I2OSP (c, (n.BitLength + 7) div 8). // len (n.BitLength + 7) div 8
if not I2OSP( m1, (n.BitLength + 7) div 8, C, n.FPool) then
raise Exception.Create('RSAES_OAEP_ENCRYPT ' + ES_InternalError_Suffix)
{$IFDEF SI}
;SiMain.LogStream( 'C', C);
{$ENDIF}
finally
DB.Free; Seed.Free; dbMask.Free; maskedDB.Free; seedMask.Free;
maskedSeed.Free; EM.Free; m1.Free
{$IFDEF SI}
;SiMain.LeaveMethod( 'RSAES_OAEP_ENCRYPT');
{$ENDIF}
end end;
function RSAES_OAEP_DECRYPT( d, n: THugeCardinal; C, M: TStream;
p, q, dp, dq, qinv: THugeCardinal): boolean;
// RSAES-OAEP-DECRYPT is the RSA decryption primitive.
// Inputs:
// n The RSA encryption public key modulus.
// d The RSA encryption private key exponent.
// C The ciphertext to be decrypted. Length = length of n in bytes.
// Outputs:
// M The decrypted plaintext. This stream is cleared on input.
// The hash used is SHA-1, so hLen = 20.
// result True if successful; False if failed.
var
mLen: integer;
k: integer; // Largest number of bytes that guarentees a number from those bytes is less than n
bytesRead: cardinal;
DB, Seed, dbMask, maskedDB, seedMask, maskedSeed, EM, reconHash: TMemoryStream;
m1: THugeCardinal;
Y: byte;
function NewMemoryStream: TMemoryStream;
begin
if assigned( n.FPool) then
result := n.FPool.NewMemoryStream( 0)
else
result := TMemoryStream.Create
end;
begin
{$IFDEF SI}
;SiMain.EnterMethod( 'RSAES_OAEP_DECRYPT');
SiMain.LogStream( 'C', C);
SiMain.LogInteger( 'C.Size', C.Size);
SiMain.LogInteger( 'n.BitLength', n.BitLength);
{$ENDIF}
DB := nil; Seed := nil; dbMask := nil; maskedDB := nil; seedMask := nil;
maskedSeed := nil; EM := nil; m1 := nil; reconHash := nil;
try
M.Size := 0;
// Step 1.b
result := C.Size = (n.BitLength + 7) div 8;
if not result then exit;
// Step 2.a
// c2 = I2OSP (C, (n.BitLength + 7) div 8). // len (n.BitLength + 7) div 8
C.Position := 0;
if RSA_Primitives_AlgorithmVersion = V3_0_0_BaseIdx then
begin
k := (n.BitLength - 1) div 8;
result := OS2IP( C, (n.BitLength + 7) div 8, m1, n.FPool, n.bitlength)
end
else
begin
k := (n.BitLength + 7) div 8;
result := OS2IP( C, k, m1, n.FPool, n.bitlength);
end;
if not result then exit;
{$IFDEF SI}
SiMain.LogStream( 'c', m1.FValue);
{$ENDIF}
// Step 2.b m = RSADP (K, c).
if UseCRT then
m1.PowerMod_WithChineseRemainderAlgorithm( d, n, p, q, dp, dq, qinv, nil)
else
m1.PowerMod( d, n, nil); // 0 <= m1 < n
{$IFDEF SI}
SiMain.LogStream( 'm', m1.FValue);
{$ENDIF}
// Step 2.c EM = I2OSP (m, k).
EM := NewMemoryStream;
result := I2OSP( m1, k, EM, n.FPool); // EM len = k
if not result then exit;
{$IFDEF SI}
SiMain.LogInteger( 'k', k);
SiMain.LogStream( 'EM', EM);
{$ENDIF}
// Step 3.a
CheckHashOfNil; // HashOfNil has hLen = 20 bytes.
// Step 3.b EM = Y || maskedSeed || maskedDB.
EM.Position := 0;
EM.Read( Y, 1);
maskedSeed := NewMemoryStream;
maskedSeed.CopyFrom( EM, hLen);
maskedDB := NewMemoryStream;
maskedDB.CopyFrom( EM, k - hLen - 1);
result := Y = 0;
if not result then exit;
// Step 3.c
// seedMask = MGF(maskedDB, hLen). Len = hLen
seedMask := NewMemoryStream;
MGF1( maskedDB, hLen, seedMask);
// Step 3.d
// Seed = seed = maskedSeed xor seedMask. Len = hLen
Seed := NewMemoryStream;
Seed.Size := hLen;
XOR_Streams3( Seed, maskedSeed, SeedMask);
// Step 3.e
// dbMask = MGF1( seed, k - hLen - 1). Len = k - hLen - 1
dbMask := NewMemoryStream;
MGF1( Seed, k - hLen - 1, dbMask);
// Step 3.f
// DB = maskedDB xor dbMask. Len = k - hLen - 1
DB := NewMemoryStream;
DB.Size := k - hLen - 1;
XOR_Streams3( DB, maskedDB, dbMask);
// Step 3.g
// DB = lHash' || PS || 0x01 || M.
DB.Position := 0;
reconHash := NewMemoryStream;
reconHash.CopyFrom( DB, hLen);
repeat
bytesRead := DB.Read( Y, 1)
until (Y <> 0) or (bytesRead = 0);
mLen := DB.Size - DB.Position;
result := CompareMemoryStreams( reconHash, HashOfNil) and
(Y = 1) and (bytesRead = 1) and (mLen > 0);
if not result then exit;
// Step 4: Output the message M
M.CopyFrom( DB, mLen)
finally
DB.Free; Seed.Free; dbMask.Free; maskedDB.Free; seedMask.Free;
maskedSeed.Free; EM.Free; m1.Free; reconHash.Free
{$IFDEF SI}
;SiMain.LeaveMethod( 'RSAES_OAEP_DECRYPT');
{$ENDIF}
end end;
function Generate_RSA_SymetricKey(
n, e: THugeCardinal; CipherStream: TStream;
const SymetricCipher: IBlockCipher): TSymetricKey;
// 1. Make a random Seed stream of size IBlockCipher.SeedByteSize
// 2. Create the key with IBlockCipher.GenerateKey( Seed)
// 3. Create a mememto of the key with TSymetricKey.SaveToStream
// 4. Measure the size of this stream. It needs to be transmitted.
// 6. Prefix the cipherstream with the count of chunks.
// 5. Process this stream RSAES_OAEP_ENCRYPT_MaxByteLen bytes at a time.
// Each RSAES_OAEP_ENCRYPT_MaxByteLen or part-thereof is a key chunk.
// In most cases, we will probably only get one key chunk.
// 6. On each key chunk, call function RSAES_OAEP_ENCRYPT( n, e, M=chunk, C=output);
// 7. Append each C to the cipherstream.
var
SeedStream, M, C: TMemoryStream;
PayloadSize: integer;
MaxChunk, Chunk: integer;
Ok: boolean;
function NewMemoryStream( Sz: integer): TMemoryStream;
begin
if assigned( n.FPool) then
result := n.FPool.NewMemoryStream( Sz)
else
begin
result := TMemoryStream.Create;
result.Size := Sz
end
end;
begin
result := nil;
SeedStream := NewMemoryStream( SymetricCipher.SeedByteSize);
try
RandomFillStream( SeedStream);
result := SymetricCipher.GenerateKey( SeedStream);
SeedStream.Position := 0;
result.SaveToStream( SeedStream);
PayloadSize := SeedStream.Position;
SeedStream.Size := PayloadSize;
SeedStream.Position := 0;
CipherStream.Write( PayloadSize, 4);
MaxChunk := RSAES_OAEP_ENCRYPT_MaxByteLen( n);
Ok := False;
M := NewMemoryStream( MaxChunk);
C := NewMemoryStream( (n.BitLength + 7) div 8);
try
while (PayloadSize > 0) and (MaxChunk > 0) do
begin
Chunk := Min( PayloadSize, MaxChunk);
M.Size := Chunk;
SeedStream.Read( M.Memory^, Chunk);
Ok := RSAES_OAEP_ENCRYPT( n, e, M, C);
if not Ok then break;
CipherStream.Write( C.Memory^, C.Size);
Dec( PayloadSize, Chunk)
end;
finally
FreeAndNil( M);
FreeAndNil( C);
end
finally
FreeAndNil( SeedStream)
end;
if not Ok then
FreeAndNil( result)
end;
function Extract_RSA_SymetricKey(
d, n, p, q, dp, dq, qinv: THugeCardinal; CipherStream: TStream;
const SymetricCipher: IBlockCipher): TSymetricKey;
var
KeyStream, M, C: TMemoryStream;
PayloadSize: integer;
MaxChunk, Chunk, CipherChunkSize: integer;
Ok: boolean;
function NewMemoryStream( Sz: integer): TMemoryStream;
begin
if assigned( n.FPool) then
result := n.FPool.NewMemoryStream( Sz)
else
begin
result := TMemoryStream.Create;
result.Size := Sz
end
end;
begin
result := nil;
CipherStream.Read( PayloadSize, 4);
MaxChunk := RSAES_OAEP_ENCRYPT_MaxByteLen( n);
Ok := False;
CipherChunkSize := (n.BitLength + 7) div 8;
KeyStream := NewMemoryStream( 0);
try
M := NewMemoryStream( MaxChunk);
C := NewMemoryStream( CipherChunkSize);
try
while (PayloadSize > 0) and (MaxChunk > 0) do
begin
Chunk := Min( PayloadSize, MaxChunk);
C.Size := CipherChunkSize;
Ok := (CipherStream.Read( C.Memory^, CipherChunkSize) = CipherChunkSize) and
RSAES_OAEP_DECRYPT( d, n, C, M, p, q, dp, dq, qinv) and (M.Size = Chunk);
if not Ok then break;
KeyStream.Write( M.Memory^, Chunk);
Dec( PayloadSize, Chunk)
end;
finally
FreeAndNil( M);
FreeAndNil( C);
end;
KeyStream.Position := 0;
if Ok then
result := SymetricCipher.LoadKeyFromStream( KeyStream)
finally
FreeAndNil( KeyStream)
end end;
procedure ClearLeftMostBits( Stream: TStream; BitsToClear: integer);
var
aByte, ClearFlags: byte;
j: integer;
begin
// BitsToClear == (8 * emLen) - emBits
if BitsToClear <= 0 then exit;
Assert( BitsToClear <= 8, '');
Stream.Position := 0;
Stream.Read( aByte, 1);
// For RFC 3447, "left--most" will be read as Most Signficant.
ClearFlags := $80;
for j := 2 to BitsToClear do
ClearFlags := (ClearFlags shr 1) + $80;
aByte := aByte and (not ClearFlags);
Stream.Position := 0;
Stream.Write( aByte, 1)
end;
type
TDocumentProgressMonitor = class
private
FDelegate: TOnHashProgress;
function OnHashProgress(
Sender: TObject; CountBytesProcessed: int64): boolean;
public
constructor Create( Delegate1: TOnHashProgress);
end;
function EMSA_PSS_ENCODE( M: TStream; emBits, sLen: integer; EM: TStream;
CheckAbortFunc: TOnHashProgress): TLongOpResult;
// EMSA-PSS-ENCODE is the RSA message encoding primitive used by Sign & Verify.
// Inputs:
// M message to be encoded, an octet string.
// emBits maximal bit length of the integer OS2IP (EM),
// at least 8hLen + 8sLen + 9
// sLen Intended length in octets of the salt
// Outputs:
// EM encoded message, an octet string of length emLen = \ceil
// (emBits/8)
// result True if successful; False if failed (due to emBits being too small.)
// Using:
// Hash hash function (hLen denotes the length in octets of the hash
// function output) used is SHA-1.
// MGF mask generation function uses is MGF1.
var
HashObj: TObject;
Hash: IHash;
mHash: TStream;
hLen1, emLen: integer;
M_Dash: TStream; // M'
Zero_8Bytes: uint64;
aByte: byte;
SaltP: int64;
H, DB, maskedDB, dbMask: TMemoryStream;
j: integer;
Monitor: TDocumentProgressMonitor;
Ok: boolean;
begin
result := opFail;
// 1. [Step 1 of the standard unecessary].
// 2. Let mHash = Hash(M), an octet string of length hLen.
Zero_8Bytes := 0;
emLen := (emBits + 7) div 8;
M_Dash := TMemoryStream.Create;
mHash := TMemoryStream.Create;
H := TMemoryStream.Create;
DB := TMemoryStream.Create;
maskedDB := TMemoryStream.Create;
dbMask := TMemoryStream.Create;
try
M_Dash.Write( Zero_8Bytes, 8);
Hash := AcquireHash( HashObj);
Monitor := TDocumentProgressMonitor.Create( CheckAbortFunc);
try
Hash.OnProgress := Monitor.OnHashProgress;
Hash.HashStream( M);
Hash.OnProgress := nil;
if Hash.isUserAborted then
begin
result := opAbort;
exit
end;
hLen1 := Hash.HashOutputValue.Size;
Hash.WriteHashOutputToStream( M_Dash);
// 3. If emLen < hLen + sLen + 2, output "encoding error" and stop.
Ok := emLen >= (hLen1 + sLen + 2);
if not Ok then exit;
// 4. Generate a random octet string salt of length sLen; if sLen = 0,
// then salt is the empty string.
// 5. Let
// M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt;
// M' is an octet string of length 8 + hLen + sLen with eight
// initial zero octets.
SaltP := M_Dash.Position;
M_Dash.CopyFrom( TRandomStream.Instance, sLen);
// 6. Let H = Hash(M'), an octet string of length hLen.
Hash.HashStream( M_Dash);
Hash.WriteHashOutputToStream( H);
// 7. Generate an octet string PS consisting of emLen - sLen - hLen - 2
// zero octets. The length of PS may be 0.
aByte := 0;
for j := 1 to emLen - sLen - hLen1 - 2 do
DB.Write( aByte, 1);
// 8. Let DB = PS || 0x01 || salt; DB is an octet string of length
// emLen - hLen - 1.
aByte := $01;
DB.Write( aByte, 1);
M_Dash.Position := SaltP;
DB.CopyFrom( M_Dash, sLen);
// 9. Let dbMask = MGF(H, emLen - hLen - 1).
MGF1( H, emLen - hLen -1, dbMask)
finally
ReleaseHash( HashObj, Hash);
Monitor.Free
end;
// 10. Let maskedDB = DB \xor dbMask.
maskedDB.Size := DB.Size;
XOR_Streams3( maskedDB, DB, dbMask);
// 11. Set the leftmost 8emLen - emBits bits of the leftmost octet in
// maskedDB to zero.
ClearLeftMostBits( maskedDB, (8 * emLen) - emBits);
// 12. Let EM = maskedDB || H || 0xbc.
// 13. Output EM.
EM.CopyFrom( maskedDB, 0);
EM.CopyFrom( H, 0);
aByte := $BC;
EM.Write( aByte, 1)
finally
M_Dash.Free;
mHash.Free;
H.Free;
DB.Free;
maskedDB.Free;
dbMask.Free
end;
if Ok then
result := opPass
end;
function EMSA_PSS_VERIFY( M: TStream; emBits, sLen: integer; EM: TStream;
CheckAbortFunc: TOnHashProgress): TLongOpResult;
var
HashObj: TObject;
Hash: IHash;
mHash: TStream;
hLen1, emLen: integer;
M_Dash: TStream; // M'
Zero_8Bytes: uint64;
aByte, ClearFlags: byte;
// SaltP: int64;
H, DB, maskedDB, dbMask, reconH: TMemoryStream;
j: integer;
Monitor: TDocumentProgressMonitor;
Ok: boolean;
begin
Monitor := nil;
result := opFail;
Zero_8Bytes := 0;
emLen := (emBits + 7) div 8;
M_Dash := TMemoryStream.Create;
mHash := TMemoryStream.Create;
reconH := TMemoryStream.Create;
H := TMemoryStream.Create;
DB := TMemoryStream.Create;
maskedDB := TMemoryStream.Create;
dbMask := TMemoryStream.Create;
try
M_Dash.Write( Zero_8Bytes, 8);
Hash := AcquireHash( HashObj);
try
Monitor := TDocumentProgressMonitor.Create( CheckAbortFunc);
Hash.OnProgress := Monitor.OnHashProgress;
Hash.HashStream( M);
Hash.OnProgress := nil;
if Hash.isUserAborted then
begin
result := opAbort;
exit
end;
hLen1 := Hash.HashOutputValue.Size;
Hash.WriteHashOutputToStream( M_Dash);
// mHash := Hash( M)
// M' = 00 00 00 00 00 00 00 00 || mHash
Ok := emLen >= (hLen1 + sLen + 2);
if not Ok then exit;
// Recover maskedDB from ( EM == (maskedDB || H || $BC))
EM.Position := 0;
maskedDB.Size := emLen - hLen1 - 1;
Ok := EM.Read( maskedDB.Memory^, maskedDB.Size) = maskedDB.Size;
// Recover H from ( EM == (maskedDB || H || $BC))
H.Size := hLen1;
Ok := Ok and (EM.Read( H.Memory^, hLen1) = hLen1) and
(EM.Read( aByte, 1) = 1) and
(aByte = $BC); // checks $BC byte.
if not Ok then exit;
// check maskedDB[leftmost 8emLen - emBits bits] == 0
if (8 * emLen) > emBits then
begin
maskedDB.Position := 0;
MaskedDB.Read( aByte, 1);
// For RFC 3447, "left--most" will be read as Most Signficant.
ClearFlags := $80;
for j := emBits to 8 * emLen - 2 do
ClearFlags := (ClearFlags shr 1) + $80;
Ok := (aByte and ClearFlags) = 0;
maskedDB.Position := 0
end;
// dbMask := MGF( H, emLen - hLen - 1)
MGF1( H, emLen - hLen -1, dbMask);
// DB := maskedDB xor dbMask
DB.Size := dbMask.Size;
XOR_Streams3( DB, maskedDB, dbMask);
// DB[ 8emLen - emBits bits] := 0
ClearLeftMostBits( DB, (8 * emLen) - emBits);
// Extract PS from DB = PS || $01 || salt
// and then check PS = 0
DB.Position := 0;
for j := 0 to emLen - sLen - hLen - 3 do
begin
Ok := (DB.Read( aByte, 1) = 1) and (aByte = 0);
if not Ok then break
end;
if not Ok then exit;
// Extract $01 from DB = PS || $01 || salt
// and check it
Ok := (DB.Read( aByte, 1) = 1) and (aByte = $01);
if not Ok then exit;
// M' = 00 00 00 00 00 00 00 00 || mHash || salt;
M_Dash.CopyFrom( DB, sLen);
M_Dash.Position := 0;
// H' = Hash(M')
Hash.HashStream( M_Dash);
reconH.Size := hLen1;
reconH.Position := 0;
Hash.WriteHashOutputToStream( reconH);
finally
ReleaseHash( HashObj, Hash);
Monitor.Free
end;
// check H == H'
Ok := CompareMemoryStreams( reconH, H)
finally
M_Dash.Free;
mHash.Free;
H.Free;
DB.Free;
maskedDB.Free;
dbMask.Free;
reconH.Free
end;
if Ok then
result := opPass
end;
const
MaxSaltLength = 20;
function RSASSA_PSS_SIGN ( d, n: THugeCardinal; M, S: TStream;
CheckAbortFunc: TOnHashProgress;
p, q, dp, dq, qinv: THugeCardinal): TLongOpResult;
// TO DO: Check for user abort.
// RSASSA-PSS-SIGN is the RSA signature generation primitive.
// Inputs:
// d The signer's RSA private key exponent.
// n The signer's RSA public key modulus.
// M The message to be signed.
// Outputs:
// S The signature. An octet string of length k, where k is the
// length in octets of the RSA modulus n
// result = opPass The operation was successful.
// = opFail The operation failed for some reason other than user abort.
// = opAbort The operation was aborted by the user before it could be completed.
var
modBits: integer;
hLen1: integer;
EM: TStream;
Ok: boolean;
SaltLength, k: integer;
Little_m: THugeCardinal;
EMLen: integer;
begin
// 1. EMSA-PSS encoding: Apply the EMSA-PSS encoding operation (Section
// 9.1.1) to the message M to produce an encoded message EM of length
// \ceil ((modBits - 1)/8) octets such that the bit length of the
// integer OS2IP (EM) (see Section 4.2) is at most modBits - 1, where
// modBits is the length in bits of the RSA modulus n:
// EM = EMSA-PSS-ENCODE (M, modBits - 1).
modBits := n.BitLength;
k := (modBits + 7) div 8;
EMLen := (modBits + 6) div 8;
hLen1 := hLen;
SaltLength := Max( Min( EMLen - hLen1 - 2, MaxSaltLength), 0);
Little_m := nil;
EM := TMemoryStream.Create;
try
result := EMSA_PSS_ENCODE( M, modBits - 1, SaltLength, EM, CheckAbortFunc);
if result = opAbort then exit;
Ok := result = opPass;
// EM.Size == EMLen == (modBits + 6) div 8
// 2. RSA signature:
// a. Convert the encoded message EM to an integer message
// representative m (see Section 4.2):
// m = OS2IP (EM).
EM.Position := 0;
Ok := Ok and OS2IP( EM, EMLen, Little_m, n.FPool, n.MaxBits);
// b. Apply the RSASP1 signature primitive (Section 5.2.1) to the RSA
// private key K and the message representative m to produce an
// integer signature representative s:
// s = RSASP1 (K, m).
if Ok then
begin
if UseCRT then
Little_m.PowerMod_WithChineseRemainderAlgorithm( d, n, p, q, dp, dq, qinv, nil)
else
Little_m.PowerMod( d, n, nil); // 0 <= m1 < n
end;
// c. Convert the signature representative s to a signature S of
// length k octets (see Section 4.1):
// S = I2OSP (s, k).
Ok := Ok and I2OSP( Little_m, k, S, n.FPool)
finally
EM.Free;
Little_m.Free
end;
if Ok then
result := opPass
else
result := opFail
end;
function RSASSA_PSS_VERIFY( n, e: THugeCardinal; M, S: TStream;
CheckAbortFunc: TOnHashProgress): TLongOpResult;
// RSASSA-PSS-VERIFY
// Inputs:
// n The signer's RSA public key modulus.
// e The signer's RSA private key exponent.
// M The message whose signature is to be verified.
// S The signature to be verified.
// Outputs:
// result = opPass The verification passed.
// = opFail The verification failed for some reason other than user abort.
// = opAbort The verification was aborted by the user before it could be completed.
var
Little_s: THugeCardinal;
Ok: boolean;
modBits, k, EMLen, SaltLength: integer;
EM: TStream;
begin
// 1. Length checking: If the length of the signature S is not k octets,
// output "invalid signature" and stop.
// 2.a. Convert the signature S to an integer signature representative
// s (see Section 4.2):
// s = OS2IP (S).
modBits := n.BitLength;
k := (modBits + 7) div 8;
EMLen := (modBits + 6) div 8;
SaltLength := Max( Min( EMLen - hLen1 - 2, MaxSaltLength), 0);
Little_s := nil;
try
Ok := OS2IP( S, k, Little_s, n.FPool, n.bitlength);
// 2.b. Apply the RSAVP1 verification primitive (Section 5.2.2) to the
// RSA public key (n, e) and the signature representative s to
// produce an integer message representative m:
// m = RSAVP1 ((n, e), s).
Ok := Ok and (Little_s.Compare( n) = rLessThan);
if Ok then
Little_s.PowerMod( e, n, nil);
// c. Convert the message representative m to an encoded message EM
// of length emLen = \ceil ((modBits - 1)/8) octets, where modBits
// is the length in bits of the RSA modulus n (see Section 4.1):
// EM = I2OSP (m, emLen).
EM := TMemoryStream.Create;
try
Ok := Ok and I2OSP( Little_s, EMLen, EM, n.FPool);
// 3. EMSA-PSS verification: Apply the EMSA-PSS verification operation
// (Section 9.1.2) to the message M and the encoded message EM to
// determine whether they are consistent:
// Result = EMSA-PSS-VERIFY (M, EM, modBits - 1).
if Ok then
begin
result := EMSA_PSS_VERIFY( M, modBits - 1, SaltLength, EM, CheckAbortFunc);
if result = opAbort then exit;
Ok := result = opPass
end
finally
EM.Free
end;
finally
Little_s.Free
end;
if Ok then
result := opPass
else
result := opFail
end;
{ TDocumentProgressMonitor }
constructor TDocumentProgressMonitor.Create( Delegate1: TOnHashProgress);
begin
FDelegate := Delegate1
end;
function TDocumentProgressMonitor.OnHashProgress(
Sender: TObject; CountBytesProcessed: int64): boolean;
begin
if assigned( FDelegate) then
result := FDelegate( Sender, CountBytesProcessed)
else
result := True
end;
initialization
InitUnit_RSA_Primitives;
finalization
DoneUnit_RSA_Primitives;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2011 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of Delphi, C++Builder or RAD Studio (Embarcadero Products).
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit SampleDataSnapReg;
// Register wizards for creating datasnap servers.
interface
uses ToolsAPI, SysUtils;
procedure Register;
implementation
uses
Classes, Windows, ExpertsRepository,
ExpertsProject, PlatformAPI,
StandardDataSnapCreatorsUnit, StandardDataSnapUIUnit,
CustomizedDataSnapCreatorsUnit, CustomizedDataSnapUIUnit,
StandardDSRESTCreatorsUnit, StandardDSRESTUIUnit,
CustomizedDSRESTCreatorsUnit, CustomizedDSRESTUIUnit
;
const
sAuthor = 'Embarcadero';
sStandardDSStandAloneProjectWizardID = sAuthor + '.StandardDSStandAloneProjectWizard';
sStandardDSStandAloneProjectIcon = 'IconOne';
sCustomizedDSStandAloneProjectWizardID = sAuthor + '.CustomizedDSStandAloneProjectWizard';
sCustomizedDSStandAloneProjectIcon = 'IconTwo';
sStandardDSRESTProjectWizardID = sAuthor + '.StandardRESTServerProjectWizard';
sStandardDSRESTProjectIcon = 'IconOne';
sCustomizedDSRESTProjectWizardID = sAuthor + '.CustomizedRESTServerProjectWizard';
sCustomizedDSRESTProjectIcon = 'IconTwo';
resourcestring
rsSampleDSStandAloneWizardPage = 'DS Standalone samples';
rsSampleDSRESTWizardPage = 'DS REST Samples';
rsStandardDSStandAloneProjectWizardName = 'StandardDSStandAloneProjectWizardName';
rsStandardDSStandAloneProjectWizardComment = 'StandardDSStandAloneProjectWizardComment';
rsCustomizedDSStandAloneProjectWizardName = 'CustomizedDSStandAloneProjectWizardName';
rsCustomizedDSStandAloneProjectWizardComment = 'CustomizedDSStandAloneProjectWizardComment';
rsStandardDSRESTProjectWizardName = 'StandardDSRESTProjectWizardName';
rsStandardDSRESTProjectWizardComment = 'StandardDSRESTProjectWizardComment';
rsCustomizedDSRESTProjectWizardName = 'CustomizedDSRESTProjectWizardName';
rsCustomizedDSRESTProjectWizardComment = 'CustomizedDSRESTProjectWizardComment';
procedure RegisterStandardDSStandAloneProjectWizard(const APersonality: string);
begin
RegisterPackageWizard(TExpertsRepositoryProjectWizardWithProc.Create(APersonality,
rsStandardDSStandAloneProjectWizardComment, rsStandardDSStandAloneProjectWizardName, sStandardDSStandAloneProjectWizardID, rsSampleDSStandAloneWizardPage, sAuthor,
procedure
var
LUIModule: TStandardDataSnapUIModule;
begin
LUIModule := TStandardDataSnapUIModule.Create(nil);
try
LUIModule.DSStandAloneAppWizard.Execute(
procedure
var
LModule: TStandardDataSnapCreatorsModule;
begin
LModule := TStandardDataSnapCreatorsModule.Create(nil);
try
// Set personality so the correct template files are used
LModule.Personality := APersonality;
// Indicate which type of project to create
LModule.ProjectType := LUIModule.ProjectType;
// Indicate port
LModule.HTTPPort := LUIModule.HTTPPort;
LModule.HTTPSPort := LUIModule.HTTPSPort;
LModule.TCPIPPort := LUIModule.TCPIPPort;
LModule.Features := LUIModule.Features;
LModule.SelectedClassName := LUIModule.SelectedClassName;
LModule.CertFileInfo := LUIModule.CertFileInfo;
LModule.ProjectLocation := LUIModule.ProjectLocation;
try
LModule.DSStandAloneProject.CreateProject(APersonality);
except
ApplicationHandleException(nil);
end;
finally
LModule.Free;
end;
end);
finally
LUIModule.Free;
end;
end,
function: Cardinal
begin
Result := LoadIcon(HInstance, sStandardDSStandAloneProjectIcon)
end,
TArray<string>.Create(cWin32Platform, cWin64Platform),
TArray<string>.Create()
) as IOTAWizard);
end;
procedure RegisterCustomizedDSStandAloneProjectWizard(const APersonality: string);
begin
RegisterPackageWizard(TExpertsRepositoryProjectWizardWithProc.Create(APersonality,
rsCustomizedDSStandAloneProjectWizardComment, rsCustomizedDSStandAloneProjectWizardName, sCustomizedDSStandAloneProjectWizardID, rsSampleDSStandAloneWizardPage, sAuthor,
procedure
var
LUIModule: TCustomizedDataSnapUIModule;
begin
LUIModule := TCustomizedDataSnapUIModule.Create(nil);
try
LUIModule.DSStandAloneAppWizard.Execute(
procedure
var
LModule: TCustomizedDataSnapCreatorsModule;
begin
LModule := TCustomizedDataSnapCreatorsModule.Create(nil);
try
// Set personality so the correct template files are used
LModule.Personality := APersonality;
// Indicate which type of project to create
LModule.ProjectType := LUIModule.ProjectType;
// Indicate port
LModule.HTTPPort := LUIModule.HTTPPort;
LModule.HTTPSPort := LUIModule.HTTPSPort;
LModule.TCPIPPort := LUIModule.TCPIPPort;
LModule.Features := LUIModule.Features;
LModule.SelectedClassName := LUIModule.SelectedClassName;
LModule.CertFileInfo := LUIModule.CertFileInfo;
LModule.ProjectLocation := LUIModule.ProjectLocation;
// Customization: comment text
LModule.Comments := LUIModule.Comments;
try
LModule.DSStandAloneProject.CreateProject(APersonality);
except
ApplicationHandleException(nil);
end;
finally
LModule.Free;
end;
end);
finally
LUIModule.Free;
end;
end,
function: Cardinal
begin
Result := LoadIcon(HInstance, sStandardDSStandAloneProjectIcon)
end,
TArray<string>.Create(cWin32Platform, cWin64Platform),
TArray<string>.Create()
) as IOTAWizard);
end;
procedure RegisterStandardDSRESTProjectWizard(const APersonality: string);
begin
RegisterPackageWizard(TExpertsRepositoryProjectWizardWithProc.Create(APersonality,
rsStandardDSRESTProjectWizardComment, rsStandardDSRESTProjectWizardName, sStandardDSRESTProjectWizardID, rsSampleDSRESTWizardPage, sAuthor,
procedure
var
LUIModule: TStandardDSRESTUIModule;
begin
LUIModule := TStandardDSRESTUIModule.Create(nil);
try
LUIModule.WebServerProjectWizard.Execute(
procedure
var
LModule: TStandardDSRESTCreatorsModule;
begin
LModule := TStandardDSRESTCreatorsModule.Create(nil);
try
// Set personality so the correct template files are used
LModule.Personality := APersonality;
// Indicate which type of project to create
LModule.ProjectType := LUIModule.ProjectType;
// Indicate port
LModule.HTTPPort := LUIModule.HTTPPort;
LModule.HTTPS := LUIModule.HTTPS;
LModule.Features := LUIModule.Features;
LModule.SelectedClassName := LUIModule.SelectedClassName;
LModule.CertFileInfo := LUIModule.CertFileInfo;
LModule.ProjectLocation := LUIModule.ProjectLocation;
LModule.WebProject.CreateProject(APersonality);
finally
LModule.Free;
end;
end);
finally
LUIModule.Free;
end;
end,
function: Cardinal
begin
Result := LoadIcon(HInstance, sStandardDSRESTProjectIcon)
end,
TArray<string>.Create(cWin32Platform, cWin64Platform),
TArray<string>.Create()
) as IOTAWizard);
end;
procedure RegisterCustomizedDSRESTProjectWizard(const APersonality: string);
begin
RegisterPackageWizard(TExpertsRepositoryProjectWizardWithProc.Create(APersonality,
rsCustomizedDSRESTProjectWizardComment, rsCustomizedDSRESTProjectWizardName, sCustomizedDSRESTProjectWizardID, rsSampleDSRESTWizardPage, sAuthor,
procedure
var
LUIModule: TCustomizedDSRESTUIModule;
begin
LUIModule := TCustomizedDSRESTUIModule.Create(nil);
try
LUIModule.WebServerProjectWizard.Execute(
procedure
var
LModule: TCustomizedDSRESTCreatorsModule;
begin
LModule := TCustomizedDSRESTCreatorsModule.Create(nil);
try
// Set personality so the correct template files are used
LModule.Personality := APersonality;
// Indicate which type of project to create
LModule.ProjectType := LUIModule.ProjectType;
// Indicate port
LModule.HTTPPort := LUIModule.HTTPPort;
LModule.HTTPS := LUIModule.HTTPS;
LModule.Features := LUIModule.Features;
LModule.SelectedClassName := LUIModule.SelectedClassName;
LModule.CertFileInfo := LUIModule.CertFileInfo;
LModule.ProjectLocation := LUIModule.ProjectLocation;
// Customizations
LModule.Comments := LUIModule.Comments;
LModule.FilesToAdd := LUIModule.FilesToAdd;
LModule.WebProject.CreateProject(APersonality);
finally
LModule.Free;
end;
end);
finally
LUIModule.Free;
end;
end,
function: Cardinal
begin
Result := LoadIcon(HInstance, sStandardDSRESTProjectIcon)
end,
TArray<string>.Create(cWin32Platform, cWin64Platform),
TArray<string>.Create()
) as IOTAWizard);
end;
procedure Register;
begin
RegisterStandardDSStandAloneProjectWizard(sDelphiPersonality);
RegisterStandardDSStandAloneProjectWizard(sCBuilderPersonality);
RegisterCustomizedDSStandAloneProjectWizard(sDelphiPersonality);
RegisterCustomizedDSStandAloneProjectWizard(sCBuilderPersonality);
RegisterStandardDSRESTProjectWizard(sDelphiPersonality);
RegisterStandardDSRESTProjectWizard(sCBuilderPersonality);
RegisterCustomizedDSRESTProjectWizard(sDelphiPersonality);
RegisterCustomizedDSRESTProjectWizard(sCBuilderPersonality);
end;
end.
|
unit MediaPlayerCommandForm;
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.Layouts, System.Generics.Collections, FMX.ListBox, IPPeerClient, IPPeerServer,
System.Tether.Manager, System.Tether.AppProfile, FMX.Memo;
type
TForm3 = class(TForm)
CommandManager: TTetheringManager;
CommandApp: TTetheringAppProfile;
Button1: TButton;
Button2: TButton;
lbPlayers: TListBox;
VolumeTrack: TTrackBar;
Label2: TLabel;
procedure FormCreate(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure CommandManagerRequestManagerPassword(const Sender: TObject; const RemoteIdentifier: string; var Password: string);
procedure lbPlayersItemClick(const Sender: TCustomListBox; const Item: TListBoxItem);
procedure VolumeTrackChange(Sender: TObject);
procedure CommandManagerEndManagersDiscovery(const Sender: TObject; const RemoteManagers: TTetheringManagerInfoList);
procedure CommandManagerEndProfilesDiscovery(const Sender: TObject; const RemoteProfiles: TTetheringProfileInfoList);
procedure CommandManagerRemoteManagerShutdown(const Sender: TObject; const ManagerIdentifier: string);
private
{ Private declarations }
FInvariantFormatSettings: TFormatSettings;
function CheckMediaPlayers: Boolean;
procedure RefreshList;
public
{ Public declarations }
end;
var
Form3: TForm3;
implementation
{$R *.fmx}
procedure TForm3.Button1Click(Sender: TObject);
begin
if CheckMediaPlayers then
CommandApp.RunRemoteAction(CommandManager.RemoteProfiles[LbPlayers.ItemIndex], 'acPlayPause');
end;
procedure TForm3.Button2Click(Sender: TObject);
var
I: Integer;
begin
for I := CommandManager.PairedManagers.Count - 1 downto 0 do
CommandManager.UnPairManager(CommandManager.PairedManagers[I]);
LbPlayers.Clear;
CommandManager.DiscoverManagers;
end;
function TForm3.CheckMediaPlayers: Boolean;
begin
if LbPlayers.ItemIndex >= 0 then
Result := True
else
begin
Result := False;
ShowMessage('Select a MediaPlayer from the list to connect, please');
end;
end;
procedure TForm3.RefreshList;
var
I: Integer;
begin
lbPlayers.Clear;
for I := 0 to CommandManager.RemoteProfiles.Count - 1 do
if CommandManager.RemoteProfiles[I].ProfileText = 'FMXMediaPlayer' then
LbPlayers.Items.Add(CommandManager.RemoteProfiles[I].ProfileText);
if LbPlayers.Count > 0 then
begin
LbPlayers.ItemIndex := 0;
CommandApp.Connect(CommandManager.RemoteProfiles[0]);
end;
// Connect to the first one
end;
procedure TForm3.CommandManagerEndManagersDiscovery(const Sender: TObject; const RemoteManagers: TTetheringManagerInfoList);
var
I: Integer;
begin
for I := 0 to RemoteManagers.Count - 1 do
if RemoteManagers[I].ManagerText = 'FMXManager' then
CommandManager.PairManager(RemoteManagers[I]);
end;
procedure TForm3.CommandManagerEndProfilesDiscovery(const Sender: TObject; const RemoteProfiles: TTetheringProfileInfoList);
begin
RefreshList;
end;
procedure TForm3.CommandManagerRemoteManagerShutdown(const Sender: TObject; const ManagerIdentifier: string);
begin
RefreshList;
end;
procedure TForm3.CommandManagerRequestManagerPassword(const Sender: TObject; const RemoteIdentifier: string; var Password: string);
begin
Password := '1234';
end;
procedure TForm3.FormCreate(Sender: TObject);
begin
FInvariantFormatSettings := TFormatSettings.Create;
FInvariantFormatSettings.DecimalSeparator := '.';
FInvariantFormatSettings.ThousandSeparator := ',';
end;
procedure TForm3.lbPlayersItemClick(const Sender: TCustomListBox; const Item: TListBoxItem);
begin
CommandApp.Connect(CommandManager.RemoteProfiles[Item.Index]);
end;
procedure TForm3.VolumeTrackChange(Sender: TObject);
begin
if CheckMediaPlayers then
CommandApp.SendString(CommandManager.RemoteProfiles[LbPlayers.ItemIndex], 'VolumeTrack',
VolumeTrack.Value.ToString(FInvariantFormatSettings));
end;
end.
|
{
/*********************************************************************\
* *
* Library : lib_crc *
* File : lib_crc.c *
* Author : Lammert Bies 1999-2008 *
* E-mail : info@lammertbies.nl *
* Language : ANSI C *
* *
* *
* Description *
* =========== *
* *
* The file lib_crc.c contains the private and public func- *
* tions used for the calculation of CRC-16, CRC-CCITT and *
* CRC-32 cyclic redundancy values. *
/*********************************************************************\
// 以上为本程序的原始作者信息,我将改为 pascal 版本。
// 网址程序请参见:http://www.lammertbies.nl/comm/info/crc-calculation.html
}
unit Unit_CRC;
interface
uses
SysUtils, StrUtils;
function Calcu_crc_16(const initialCRC: Word; const DataStr: string): Word;
function Calcu_crc_sick(const DataStr: string): Word;
function Calcu_crc_ccitt(const initialCRC: Word; const DataStr: string): Word;
function Calcu_crc_kermit(const DataStr: string): Word;
function Calcu_crc_dnp(const DataStr: string): Word;
// 福建省能源计量数据采集系统数据传输协议 DB 35/987-2010 中约定CRC计算方法
function Calcu_crc_DB35(const DataStr: string): Word;
function Calcu_crc_32(const DataStr: string): LongWord;
function OriginalCalcuCRC_16(const DataStr: string): Word;
function OriginalCalcuCRC_CCITT(const DataStr: string): Word;
function FormatHexData(var AHexStr: string): Boolean;
function ConvHexToString(const AHexStr: string): string;
implementation
Type
TcrcArr = array [0..255] of Word;
TcrcArrDW = array [0..255] of LongWord;
const
P_16: Word = $A001;
P_CCITT: Word = $1021;
P_DNP: Word = $A6BC;
P_KERMIT: Word = $8408;
P_SICK: Word = $8005;
P_32: LongWord = $EDB88320;
var
crc_tab16, crc_tabccitt, crc_tabdnp, crc_tabkermit: TcrcArr;
crc_tab32: TcrcArrDW;
function Calcu_crc_16(const initialCRC: Word; const DataStr: string): Word;
var
i: integer;
tmp, short_c, crc: Word;
aByte: Byte;
begin
crc := initialCRC;
for i := 1 to Length(DataStr) do
begin
aByte := ord(DataStr[i]);
short_c := ($00ff and aByte);
tmp := crc xor short_c;
crc := (crc shr 8) xor crc_tab16[ tmp and $ff ];
end;
result := crc;
end;
function Calcu_crc_sick(const DataStr: string): Word;
var
i: integer;
short_c, short_p, crc, high_byte, low_byte: Word;
aByte, prev_byte: Byte;
begin
crc := $0000;
prev_byte := 0;
for i := 1 to Length(DataStr) do
begin
aByte := ord(DataStr[i]);
short_c := ($00ff and aByte);
short_p := ($00ff and prev_byte) shl 8;
if (crc and $8000) = $8000 then crc := (crc shl 1) xor P_SICK
else crc := (crc shl 1);
crc := crc and $FFFF;
crc := crc xor (short_c or short_p);
prev_byte := aByte;
end;
low_byte := (crc and $ff00) shr 8;
high_byte := (crc and $00ff) shl 8;
result := low_byte or high_byte;
end;
function Calcu_crc_ccitt(const initialCRC: Word; const DataStr: string): Word;
var
i: integer;
tmp, short_c, crc: Word;
aByte: Byte;
begin
crc := initialCRC;
for i := 1 to Length(DataStr) do
begin
aByte := ord(DataStr[i]);
short_c := ($00ff and aByte);
tmp := (crc shr 8) xor short_c;
crc := (crc shl 8) xor crc_tabccitt[tmp];
end;
result := crc;
end;
function Calcu_crc_kermit(const DataStr: string): Word;
var
i: integer;
tmp, short_c, crc, high_byte, low_byte: Word;
aByte: Byte;
begin
crc := $0000;
for i := 1 to Length(DataStr) do
begin
aByte := ord(DataStr[i]);
short_c := ($00ff and aByte);
tmp := crc xor short_c;
crc := (crc shr 8) xor crc_tabkermit[ tmp and $ff ];
end;
low_byte := (crc and $ff00) shr 8;
high_byte := (crc and $00ff) shl 8;
result := low_byte or high_byte;
end;
function Calcu_crc_dnp(const DataStr: string): Word;
var
i: integer;
tmp, short_c, crc, high_byte, low_byte: Word;
aByte: Byte;
begin
crc := $0000;
for i := 1 to Length(DataStr) do
begin
aByte := ord(DataStr[i]);
short_c := ($00ff and aByte);
tmp := crc xor short_c;
crc := (crc shr 8) xor crc_tabdnp[ tmp and $ff ];
end;
crc := not crc;
low_byte := (crc and $ff00) shr 8;
high_byte := (crc and $00ff) shl 8;
result := low_byte or high_byte;
end;
function Calcu_crc_DB35(const DataStr: string): Word;
var // 福建省能源计量数据采集系统数据传输协议 DB 35/987-2010 中约定CRC计算方法
Crc16: word;
i, j: integer;
begin
Crc16 := $FFFF;
for i := 1 to Length(DataStr) do
begin
crc16 := (crc16 xor (ord(DataStr[i]) shl 8));
for j := 0 to 7 do
begin
if (crc16 and 1) <> 0 then
Crc16 := (Crc16 shr 1) xor $A001
else
Crc16 := (Crc16 shr 1);
end;
end;
Result := Crc16;
end;
function Calcu_crc_32(const DataStr: string): LongWord;
var
i: integer;
tmp, long_c, crc: longWord;
aByte: Byte;
begin
crc := $ffffffff;
for i := 1 to Length(DataStr) do
begin
aByte := ord(DataStr[i]);
long_c := ($000000ff and aByte);
tmp := crc xor long_c;
crc := (crc shr 8) xor crc_tab32[tmp and $ff];
end;
result := crc xor $FFFFFFFF;
end;
function OriginalCalcuCRC_16(const DataStr: string): Word;
var
Crc16: word;
aByte: Byte;
tmpStr: string;
i, j: integer;
begin
Crc16 := $0000;
if DataStr = '' then Exit;
tmpStr := DataStr + #0#0;
for i := 1 to Length(tmpStr) do
begin
aByte := Ord(tmpStr[i]);
for j := 0 to 7 do
begin
if (crc16 and $8000) <> 0 then // 判断 crc16 首位是否等于 1
begin
crc16 := (Crc16 shl 1) xor (aByte shr 7);
crc16 := crc16 xor $8005;
end
else crc16 := (Crc16 shl 1) xor (aByte shr 7);
aByte := aByte shl 1;
end; // for
end;
Result := Crc16;
end;
function OriginalCalcuCRC_CCITT(const DataStr: string): Word;
var
Crc16: word;
aByte: Byte;
tmpStr: string;
i, j: integer;
begin
Crc16 := $0000;
if DataStr = '' then Exit;
tmpStr := DataStr + #0#0;
for i := 1 to Length(tmpStr) do
begin
aByte := Ord(tmpStr[i]);
for j := 0 to 7 do
begin
if (crc16 and $8000) <> 0 then // 判断 crc16 首位是否等于 1
begin
crc16 := (Crc16 shl 1) xor (aByte shr 7);
crc16 := crc16 xor $1021;
end
else crc16 := (Crc16 shl 1) xor (aByte shr 7);
aByte := aByte shl 1;
end; // for
end;
Result := Crc16;
end;
procedure init_crc16_tab();
var
i, j: integer;
crc, c: Word;
begin
for i := 0 to 255 do
begin
crc := 0;
c := i;
for j := 0 to 7 do
begin
if ((crc xor c) and $0001) = 1 then crc := ( crc shr 1 ) xor P_16
else crc := crc shr 1;
c := c shr 1;
end;
crc_tab16[i] := crc;
end;
end;
procedure init_crcdnp_tab();
var
i, j: integer;
crc, c: Word;
begin
for i := 0 to 255 do
begin
crc := 0;
c := i;
for j := 0 to 7 do
begin
if ((crc xor c) and $0001) = 1 then crc := ( crc shr 1 ) xor P_DNP
else crc := crc shr 1;
c := c shr 1;
end;
crc_tabdnp[i] := crc;
end;
end;
procedure init_crckermit_tab();
var
i, j: integer;
crc, c, tmp: Word;
begin
for i := 0 to 255 do
begin
crc := 0;
c := i;
for j := 0 to 7 do
begin
if (((crc xor c) and $0001) = 1) then crc := ( crc shr 1 ) xor P_KERMIT
else crc := crc shr 1;
c := c shr 1;
end;
crc_tabkermit[i] := crc;
end;
end;
procedure init_crcccitt_tab();
var
i, j: integer;
crc, c: Word;
begin
for i := 0 to 255 do
begin
crc := 0;
c := i shl 8;
for j := 0 to 7 do
begin
if ((crc xor c) and $8000) = $8000 then crc := ( crc shl 1 ) xor P_CCITT
else crc := crc shl 1;
c := c shl 1;
end;
crc_tabccitt[i] := crc;
end;
end;
procedure init_crc32_tab();
var
i, j: integer;
crc: longWord;
begin
for i := 0 to 255 do
begin
crc := i;
for j := 0 to 7 do
begin
if (crc and $00000001) = 1 then crc := ( crc shr 1 ) xor P_32
else crc := crc shr 1;
end;
crc_tab32[i] := crc;
end;
end;
function FormatHexData(var AHexStr: string): Boolean;
var // 格式化16进制数,比如 A1 0 1 1B0 变为 A1 00 01 01 B0
str, tmpstr: string;
hexDataErr: Boolean;
i, j, s1: integer;
begin
result := false;
hexDataErr := false;
if AHexStr = '' then Exit;
str := AHexStr;
for i := 1 to Length(str) do // 检查16进制是否合法
begin
if not (str[i] in ['0'..'9', 'A'..'F', ' ', ',']) then
begin
hexDataErr := true;
break;
end;
if str[i] = ',' then str[i] := ' '; // 将间隔用的逗号统一用空格代替
end;
if hexDataErr then Exit;
str := trim(str); // 去掉首尾多余空格
if pos(' ', str) > 0 then
begin
i := 1;
while (i <= Length(str)) do // 消除重复的空格
begin
if (str[i] = ' ') and ((i + 1) <= Length(str)) then
if str[i + 1] = ' ' then
begin
delete(str, i + 1, 1);
Dec(i);
end;
Inc(i);
end;
i := 1;
s1 := 1;
while (i <= Length(str)) do // 将单个的16进制数补完整,比如 A 补为 0A
begin
if (str[i] = ' ') OR (i = Length(str)) then
begin
if s1 = 1 then tmpstr := midStr(str, s1, i - s1)
else if i = Length(str) then tmpstr := midStr(str, s1 + 1, i - s1) // i = Length(str) 情况
else tmpstr := midStr(str, s1 + 1, i - s1 - 1);
if (length(tmpstr) mod 2) <> 0 then
begin
if s1 <> 1 then insert('0', str, s1 + 1)
else insert('0', str, s1);
Inc(i);
end;
s1 := i;
end;
Inc(i);
end;
str := StringReplace(str, ' ', '', [rfReplaceAll]);
end;
if (Length(str) mod 2) <> 0 then str := '0' + str;
tmpstr := '';
for i := 1 to Length(str) do
begin
if (i mod 2) = 0 then tmpstr := tmpstr + str[i] + ' '
else tmpstr := tmpstr + str[i];
end;
AHexStr := Trim(tmpstr);
result := true;
end;
function ConvHexToString(const AHexStr: string): string;
var
str, tmpStr: string;
i: integer;
begin
result := '';
str := AHexStr;
if FormatHexData(str) then
begin
str := StringReplace(str, ' ', '', [rfReplaceAll]);
tmpStr := '';
i := 1;
while (i < Length(str)) do
begin
tmpStr := tmpStr + Char(strToInt('$' + str[i] + str[i + 1])); // 转换为 ASCII 值
i := i + 2;
end;
result := tmpStr;
end;
end;
initialization
init_crc16_tab();
init_crcdnp_tab();
init_crckermit_tab();
init_crcccitt_tab();
init_crc32_tab();
finalization
//
end.
|
unit mungo.textfile.pascal.sourceeditor;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
SynHighlighterPas,
mungo.intf.filepointer,
mungo.components.colors,
mungo.textfile.sourceeditor,
passrcutil;
type
{ TSourceEditorPascal }
TSourceEditorPascal = class ( TSourceEditor )
constructor Create(ARootControl: TObject; AFileInfo: TFilePointer); override; overload;
class function FileMatch(AFileInfo: TFilePointer): Boolean; override;
end;
implementation
{ TSourceEditorPascal }
constructor TSourceEditorPascal.Create(ARootControl: TObject; AFileInfo: TFilePointer);
var
HighLighter: TSynFreePascalSyn;
begin
inherited Create(ARootControl, AFileInfo);
HighLighter:= TSynFreePascalSyn.Create( Editor );
Editor.Highlighter:= HighLighter;
Editor.Gutter.Color:= White;
Editor.Color:= White;
// Editor.BracketMatchColor:= Blue800;
TSynFreePascalSyn( Editor.Highlighter ).NumberAttri.Foreground:= Blue600;
TSynFreePascalSyn( Editor.Highlighter ).StringAttri.Foreground:= BlueGray600;
TSynFreePascalSyn( Editor.Highlighter ).SymbolAttri.Foreground:= Brown600;
TSynFreePascalSyn( Editor.Highlighter ).CommentAttribute.Foreground:= LightGreen600;
TSynFreePascalSyn( Editor.Highlighter ).AsmAttri.Foreground:= Red800;
TSynFreePascalSyn( Editor.Highlighter ).DirectiveAttri.Foreground:= Red400;
end;
class function TSourceEditorPascal.FileMatch(AFileInfo: TFilePointer): Boolean;
begin
Result:= inherited;
if ( Result ) then
Result:= ( AFileInfo.Extension = '.pas' )
or ( AFileInfo.Extension = '.pp' )
or ( AFileInfo.Extension = '.p' )
or ( AFileInfo.Extension = '.lpr' )
or ( AFileInfo.Extension = '.lfm' );
end;
end.
|
unit uFrmServerConnection;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls;
type
TFrmServerConnection = class(TForm)
Panel1: TPanel;
Bevel1: TBevel;
btnSave: TBitBtn;
BitBtn2: TBitBtn;
cbxConnection: TComboBox;
Label1: TLabel;
pnlServer: TPanel;
pnlFTP: TPanel;
lbServer: TLabel;
btnSetConnection: TSpeedButton;
Label2: TLabel;
edtFTP: TEdit;
Label3: TLabel;
edtPort: TEdit;
Label4: TLabel;
edtUser: TEdit;
Label5: TLabel;
edtPW: TEdit;
Label6: TLabel;
edtGlobalDir: TEdit;
Label7: TLabel;
edtPOSDir: TEdit;
memServerInfo: TMemo;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BitBtn2Click(Sender: TObject);
procedure btnSetConnectionClick(Sender: TObject);
procedure cbxConnectionChange(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
private
procedure RefreshControl;
procedure SetValues;
procedure GetValues;
public
function Start:Boolean;
end;
implementation
uses uDMPOS, uMainConf;
{$R *.dfm}
procedure TFrmServerConnection.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFrmServerConnection.BitBtn2Click(Sender: TObject);
begin
Close;
end;
function TFrmServerConnection.Start: Boolean;
begin
GetValues;
RefreshControl;
ShowModal;
Result := True;
end;
procedure TFrmServerConnection.btnSetConnectionClick(Sender: TObject);
begin
DMPOS.CloseConnection;
DMPOS.OpenConnection(True);
memServerInfo.Lines.Text := DMPOS.GetConnectionInfo(DMPOS.GetConnection);
end;
procedure TFrmServerConnection.cbxConnectionChange(Sender: TObject);
begin
RefreshControl;
end;
procedure TFrmServerConnection.RefreshControl;
begin
if cbxConnection.ItemIndex = 0 then
begin
pnlFTP.Visible := False;
pnlServer.Visible := True;
end
else
begin
pnlFTP.Visible := True;
pnlServer.Visible := False;
end;
end;
procedure TFrmServerConnection.btnSaveClick(Sender: TObject);
begin
SetValues;
Close;
end;
procedure TFrmServerConnection.SetValues;
begin
FrmMain.fIniConfig.WriteString('ServerConnection', 'ClientInfo', memServerInfo.Lines.Text);
FrmMain.fIniConfig.WriteInteger('ServerConnection', 'ConnectType', cbxConnection.ItemIndex);
FrmMain.fIniConfig.WriteString('ServerConnection', 'FTP', edtFTP.Text);
FrmMain.fIniConfig.WriteInteger('ServerConnection', 'Port', StrToIntdef(edtPort.Text,21));
FrmMain.fIniConfig.WriteString('ServerConnection', 'User', edtUser.Text);
FrmMain.fIniConfig.WriteString('ServerConnection', 'PW', edtPW.Text);
FrmMain.fIniConfig.WriteString('ServerConnection', 'GlobalDir', edtGlobalDir.Text);
FrmMain.fIniConfig.WriteString('ServerConnection', 'POSDir', edtPOSDir.Text);
end;
procedure TFrmServerConnection.GetValues;
begin
memServerInfo.Lines.Text := FrmMain.fServerConnection.ClientInfo;
cbxConnection.ItemIndex := FrmMain.fServerConnection.ConnectType;
edtFTP.Text := FrmMain.fServerConnection.FTP;
edtPort.Text := IntToStr(FrmMain.fServerConnection.Port);
edtUser.Text := FrmMain.fServerConnection.User;
edtPW.Text := FrmMain.fServerConnection.PW;
edtGlobalDir.Text := FrmMain.fServerConnection.GlobalDir;
edtPOSDir.Text := FrmMain.fServerConnection.POSDir;
end;
end.
|
unit UnitOpenGLExtendedBlitRectShader;
{$ifdef fpc}
{$mode delphi}
{$ifdef cpui386}
{$define cpu386}
{$endif}
{$ifdef cpuamd64}
{$define cpux86_64}
{$endif}
{$ifdef cpu386}
{$define cpux86}
{$define cpu32}
{$asmmode intel}
{$endif}
{$ifdef cpux86_64}
{$define cpux64}
{$define cpu64}
{$asmmode intel}
{$endif}
{$ifdef FPC_LITTLE_ENDIAN}
{$define LITTLE_ENDIAN}
{$else}
{$ifdef FPC_BIG_ENDIAN}
{$define BIG_ENDIAN}
{$endif}
{$endif}
{-$pic off}
{$define caninline}
{$ifdef FPC_HAS_TYPE_EXTENDED}
{$define HAS_TYPE_EXTENDED}
{$else}
{$undef HAS_TYPE_EXTENDED}
{$endif}
{$ifdef FPC_HAS_TYPE_DOUBLE}
{$define HAS_TYPE_DOUBLE}
{$else}
{$undef HAS_TYPE_DOUBLE}
{$endif}
{$ifdef FPC_HAS_TYPE_SINGLE}
{$define HAS_TYPE_SINGLE}
{$else}
{$undef HAS_TYPE_SINGLE}
{$endif}
{$if declared(RawByteString)}
{$define HAS_TYPE_RAWBYTESTRING}
{$else}
{$undef HAS_TYPE_RAWBYTESTRING}
{$ifend}
{$if declared(UTF8String)}
{$define HAS_TYPE_UTF8STRING}
{$else}
{$undef HAS_TYPE_UTF8STRING}
{$ifend}
{$else}
{$realcompatibility off}
{$localsymbols on}
{$define LITTLE_ENDIAN}
{$ifndef cpu64}
{$define cpu32}
{$endif}
{$ifdef cpux64}
{$define cpux86_64}
{$define cpu64}
{$else}
{$ifdef cpu386}
{$define cpux86}
{$define cpu32}
{$endif}
{$endif}
{$define HAS_TYPE_EXTENDED}
{$define HAS_TYPE_DOUBLE}
{$ifdef conditionalexpressions}
{$if declared(RawByteString)}
{$define HAS_TYPE_RAWBYTESTRING}
{$else}
{$undef HAS_TYPE_RAWBYTESTRING}
{$ifend}
{$if declared(UTF8String)}
{$define HAS_TYPE_UTF8STRING}
{$else}
{$undef HAS_TYPE_UTF8STRING}
{$ifend}
{$else}
{$undef HAS_TYPE_RAWBYTESTRING}
{$undef HAS_TYPE_UTF8STRING}
{$endif}
{$endif}
{$ifdef win32}
{$define windows}
{$endif}
{$ifdef win64}
{$define windows}
{$endif}
{$ifdef wince}
{$define windows}
{$endif}
{$rangechecks off}
{$extendedsyntax on}
{$writeableconst on}
{$hints off}
{$booleval off}
{$typedaddress off}
{$stackframes off}
{$varstringchecks on}
{$typeinfo on}
{$overflowchecks off}
{$longstrings on}
{$openstrings on}
interface
uses {$ifdef fpcgl}gl,glext,{$else}dglOpenGL,{$endif}UnitOpenGLShader;
type TExtendedBlitRectShader=class(TShader)
public
uTexture:glInt;
public
constructor Create;
destructor Destroy; override;
procedure BindAttributes; override;
procedure BindVariables; override;
end;
var ExtendedBlitRectShader:TExtendedBlitRectShader=nil;
implementation
constructor TExtendedBlitRectShader.Create;
var f,v:ansistring;
begin
v:='#version 330'+#13#10+
'attribute vec2 aPosition;'+#10+
'attribute vec2 aTexCoord;'+#10+
'attribute vec4 aColor;'+#10+
'out vec2 vTexCoord;'+#10+
'out vec4 vColor;'+#10+
'void main(){'+#10+
' vTexCoord = aTexCoord.xy;'+#10+
' vColor = aColor;'+#10+
' gl_Position = vec4(vec3(aPosition.xy, 0.0), 1.0);'+#10+
'}'+#10;
f:='#version 330'+#13#10+
'in vec2 vTexCoord;'+#10+
'in vec4 vColor;'+#10+
'layout(location = 0) out vec4 oOutput;'+#13#10+
'uniform sampler2D uTexture;'+#13#10+
'void main(){'+#13#10+
' oOutput = texture(uTexture, vTexCoord) * vColor;'+#13#10+
'}'+#13#10;
inherited Create(v,f);
end;
destructor TExtendedBlitRectShader.Destroy;
begin
inherited Destroy;
end;
procedure TExtendedBlitRectShader.BindAttributes;
begin
inherited BindAttributes;
glBindAttribLocation(ProgramHandle,0,pointer(pansichar('aPosition')));
glBindAttribLocation(ProgramHandle,1,pointer(pansichar('aTexCoord')));
glBindAttribLocation(ProgramHandle,2,pointer(pansichar('aColor')));
end;
procedure TExtendedBlitRectShader.BindVariables;
begin
inherited BindVariables;
uTexture:=glGetUniformLocation(ProgramHandle,pointer(pansichar('uTexture')));
end;
end.
|
unit StringTranslateFrm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
UnicodeMixedLib, PascalStrings, TextParsing, zExpression;
type
TStringTranslateForm = class(TForm)
Memo1: TMemo;
Memo2: TMemo;
Hex2AsciiButton: TButton;
Ascii2HexButton: TButton;
Ascii2DeclButton: TButton;
Ascii2PascalDeclButton: TButton;
PascalDecl2AsciiButton: TButton;
Ascii2cButton: TButton;
c2AsciiButton: TButton;
procedure Hex2AsciiButtonClick(Sender: TObject);
procedure Ascii2HexButtonClick(Sender: TObject);
procedure Ascii2DeclButtonClick(Sender: TObject);
procedure Ascii2PascalDeclButtonClick(Sender: TObject);
procedure PascalDecl2AsciiButtonClick(Sender: TObject);
procedure Ascii2cButtonClick(Sender: TObject);
procedure c2AsciiButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
StringTranslateForm: TStringTranslateForm;
implementation
{$R *.dfm}
procedure TStringTranslateForm.Hex2AsciiButtonClick(Sender: TObject);
var
s, n: u_String;
c: Char;
output: string;
begin
s := Memo1.Text;
output := '';
while s <> '' do
begin
n := umlGetFirstStr(s, ',');
s := umlDeleteFirstStr(s, ',');
c := Char(umlStrToInt(n, 0));
output := output + c;
end;
Memo2.Text := output;
end;
procedure TStringTranslateForm.Ascii2HexButtonClick(Sender: TObject);
var
s: string;
c: Char;
cnt: Integer;
output: string;
begin
s := Memo2.Text;
output := '';
cnt := 0;
for c in s do
begin
if cnt > 40 then
begin
output := Format('%s,' + #13#10 + '%s', [output, '$' + IntToHex(ord(c), 2)]);
cnt := 0;
end
else
begin
if output <> '' then
output := Format('%s, %s', [output, '$' + IntToHex(ord(c), 2)])
else
output := '$' + IntToHex(ord(c), 2);
end;
inc(cnt);
end;
Memo1.Text := output;
end;
procedure TStringTranslateForm.Ascii2DeclButtonClick(Sender: TObject);
var
s: string;
c: Char;
cnt: Integer;
output: string;
begin
s := Memo2.Text;
output := '';
cnt := 0;
for c in s do
begin
if cnt > 40 then
begin
output := Format('%s' + #13#10 + '%s', [output, '#' + IntToStr(ord(c))]);
cnt := 0;
end
else
begin
if output <> '' then
output := Format('%s%s', [output, '#' + IntToStr(ord(c))])
else
output := '#' + IntToStr(ord(c));
end;
inc(cnt);
end;
Memo1.Text := output;
end;
procedure TStringTranslateForm.Ascii2PascalDeclButtonClick(Sender: TObject);
var
i: Integer;
begin
Memo1.Clear;
for i := 0 to Memo2.Lines.Count - 1 do
begin
if i = Memo2.Lines.Count - 1 then
Memo1.Lines.Add(TTextParsing.TranslateTextToPascalDecl(Memo2.Lines[i] + #13#10) + ';')
else
Memo1.Lines.Add(TTextParsing.TranslateTextToPascalDecl(Memo2.Lines[i] + #13#10) + '+');
end;
end;
procedure TStringTranslateForm.PascalDecl2AsciiButtonClick(Sender: TObject);
begin
Memo2.Text:=EvaluateExpressionValue(tsPascal, Memo1.Text);
end;
procedure TStringTranslateForm.Ascii2cButtonClick(Sender: TObject);
var
i: Integer;
begin
Memo1.Clear;
for i := 0 to Memo2.Lines.Count - 1 do
begin
if i = Memo2.Lines.Count - 1 then
Memo1.Lines.Add(TTextParsing.TranslateTextToC_Decl(Memo2.Lines[i] + #13#10) + ';')
else
Memo1.Lines.Add(TTextParsing.TranslateTextToC_Decl(Memo2.Lines[i] + #13#10) + '+');
end;
end;
procedure TStringTranslateForm.c2AsciiButtonClick(Sender: TObject);
begin
Memo2.Text:=EvaluateExpressionValue(tsC, Memo1.Text);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.