text stringlengths 14 6.51M |
|---|
unit uFrmPetSearch;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uDialogParent, siComp, siLangRT, StdCtrls, ExtCtrls, cxStyles,
cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB, cxDBData,
cxGridLevel, cxClasses, cxControls, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, ADODB,
Buttons, Mask, SuperComboADO;
type
TFrmPetSearch = class(TDialogParent)
Panel3: TPanel;
grdBrowseSearch: TcxGrid;
grdBrowseSearchDB: TcxGridDBTableView;
grdBrowseSearchLevel: TcxGridLevel;
quPet: TADODataSet;
dsPet: TDataSource;
btSearch: TBitBtn;
edSKU: TEdit;
lbSKU: TLabel;
lbSubGroup: TLabel;
scPetSpecies: TSuperComboADO;
btnSpeciesClear: TButton;
quPetIDPet: TIntegerField;
quPetIDSpecies: TIntegerField;
quPetIDPorte: TIntegerField;
quPetIDBreed: TIntegerField;
quPetIDStatus: TIntegerField;
quPetIDBreeder: TIntegerField;
quPetName: TStringField;
quPetSex: TStringField;
quPetColor: TStringField;
quPetSKU: TStringField;
quPetPenNum: TStringField;
quPetVendorCost: TBCDField;
quPetMSRP: TBCDField;
quPetSalePrice: TBCDField;
quPetPromoPrice: TBCDField;
quPetUSDA: TStringField;
quPetCollar: TStringField;
quPetSire: TStringField;
quPetDam: TStringField;
quPetWhelpDate: TDateTimeField;
quPetPurchaseDate: TDateTimeField;
quPetNotes: TStringField;
quPetSystem: TBooleanField;
quPetHidden: TBooleanField;
quPetDesativado: TBooleanField;
quPetSpecies: TStringField;
quPetPorte: TStringField;
quPetBreed: TStringField;
quPetStatusCode: TStringField;
quPetStatus: TStringField;
quPetPessoa: TStringField;
quPetTelefone: TStringField;
grdBrowseSearchDBSex: TcxGridDBColumn;
grdBrowseSearchDBColor: TcxGridDBColumn;
grdBrowseSearchDBSKU: TcxGridDBColumn;
grdBrowseSearchDBSalePrice: TcxGridDBColumn;
grdBrowseSearchDBPromoPrice: TcxGridDBColumn;
grdBrowseSearchDBSpecies: TcxGridDBColumn;
grdBrowseSearchDBBreed: TcxGridDBColumn;
grdBrowseSearchDBStatus: TcxGridDBColumn;
grdBrowseSearchDBPessoa: TcxGridDBColumn;
Label1: TLabel;
csBreed: TSuperComboADO;
btnBreedClear: TButton;
procedure btnSpeciesClearClick(Sender: TObject);
procedure btSearchClick(Sender: TObject);
procedure AplicarClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure edSKUEnter(Sender: TObject);
procedure edSKUExit(Sender: TObject);
procedure grdBrowseSearchDBDblClick(Sender: TObject);
procedure btnBreedClearClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
FIDModel : Integer;
FIDPet, FIDStatus : Integer;
FCost, FSale : Currency;
FSKU : String;
procedure PrepareFilter;
public
function Start(AIDModel : Integer; var AIDPet, AIDStatus : Integer;
var ACost, ASale : Currency; var ASKU : String) : Boolean;
end;
implementation
uses uDM, uSQLFunctions;
{$R *.dfm}
{ TFrmPetSearch }
function TFrmPetSearch.Start(AIDModel : Integer; var AIDPet, AIDStatus : Integer;
var ACost, ASale : Currency; var ASKU : String): Boolean;
begin
FIDModel := AIDModel;
AIDPet := -1;
ACost := 0;
ASale := 0;
AIDStatus := 0;
ASKU := '';
ShowModal;
Result := (ModalResult = mrOK);
if Result then
begin
AIDPet := FIDPet;
ACost := FCost;
ASale := FSale;
ASKU := FSKU;
AIDStatus := FIDStatus;
end;
end;
procedure TFrmPetSearch.btnSpeciesClearClick(Sender: TObject);
begin
inherited;
scPetSpecies.LookUpValue := '';
scPetSpecies.Text := '<' + btnSpeciesClear.Caption + '>';
end;
procedure TFrmPetSearch.btSearchClick(Sender: TObject);
var
sWhere : String;
begin
inherited;
Screen.Cursor := crHourGlass;
try
sWhere := ' P.Desativado = 0 AND P.Hidden = 0 AND P.System = 0 ';
if Trim(edSKU.Text) <> '' then
sWhere := sWhere + ' AND P.SKU like ' + QuotedStr('%'+edSKU.Text+'%');
if scPetSpecies.LookUpValue <> '' then
sWhere := sWhere + ' AND P.IDSpecies = ' + scPetSpecies.LookUpValue;
if csBreed.LookUpValue <> '' then
sWhere := sWhere + ' AND P.IDBreed = ' + csBreed.LookUpValue;
quPet.Close;
quPet.CommandText := ChangeWhereClause(quPet.CommandText, sWhere, True);
quPet.Open;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TFrmPetSearch.AplicarClick(Sender: TObject);
begin
inherited;
if quPet.Active and (not quPet.IsEmpty) then
begin
FIDPet := quPetIDPet.AsInteger;
FCost := quPetVendorCost.AsCurrency;
FSKU := quPetSKU.AsString;
FIDStatus := quPetIDStatus.AsInteger;
if quPetPromoPrice.AsCurrency <> 0 then
FSale := quPetPromoPrice.AsCurrency
else
FSale := quPetSalePrice.AsCurrency;
end;
end;
procedure TFrmPetSearch.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
quPet.Close;
end;
procedure TFrmPetSearch.edSKUEnter(Sender: TObject);
begin
inherited;
Aplicar.Default := False;
btSearch.Default := True;
end;
procedure TFrmPetSearch.edSKUExit(Sender: TObject);
begin
inherited;
Aplicar.Default := True;
btSearch.Default := False;
end;
procedure TFrmPetSearch.grdBrowseSearchDBDblClick(Sender: TObject);
begin
inherited;
Aplicar.Click;
end;
procedure TFrmPetSearch.PrepareFilter;
var
FQuery : TADOQuery;
begin
try
FQuery := TADOQuery.Create(Self);
FQuery.Connection := DM.ADODBConnect;
FQuery.SQL.Add('SELECT TOP 1 P.IDBreed');
FQuery.SQL.Add('FROM Pet P');
FQuery.SQL.Add('WHERE P.IDModel = :IDModel');
FQuery.Parameters.ParamByName('IDModel').Value := FIDModel;
FQuery.Open;
if not FQuery.IsEmpty then
begin
csBreed.LookUpValue := FQuery.FieldByName('IDBreed').AsString;
btSearch.Click;
end;
finally
FQuery.Close;
FreeAndNil(FQuery);
end;
end;
procedure TFrmPetSearch.btnBreedClearClick(Sender: TObject);
begin
inherited;
csBreed.LookUpValue := '';
csBreed.Text := '<' + btnBreedClear.Caption + '>';
end;
procedure TFrmPetSearch.FormShow(Sender: TObject);
begin
inherited;
PrepareFilter;
end;
end.
|
{$I vp.inc}
{ A datastore for a Firebird database accessed via SQLDB }
unit VpFBDS;
interface
uses
SysUtils, Classes, DB,
VpBaseDS, VpDBDS,
IBConnection, sqldb;
type
TVpFirebirdDatastore = class(TVpCustomDBDatastore)
private
FConnection: TIBConnection;
FContactsTable: TSQLQuery;
FEventsTable: TSQLQuery;
FResourceTable: TSQLQuery;
FTasksTable: TSQLQuery;
FConnectLock: Integer;
procedure SetConnection(const AValue: TIBConnection);
protected
procedure CreateAllTables(dbIsNew: Boolean);
procedure CreateTable(const ATableName: String);
function GetContactsTable: TDataset; override;
function GetEventsTable: TDataset; override;
function GetResourceTable: TDataset; override;
function GetTasksTable: TDataset; override;
procedure Loaded; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure OpenTables;
procedure SetConnected(const AValue: Boolean); override;
public
constructor Create(AOwner: TComponent); override;
procedure CreateTables;
function GetNextID(TableName: string): integer; override;
procedure PostEvents; override;
procedure PostContacts; override;
procedure PostTasks; override;
procedure PostResources; override;
property ResourceTable;
property EventsTable;
property ContactsTable;
property TasksTable;
published
property Connection: TIBConnection read FConnection write SetConnection;
// inherited
property AutoConnect;
property AutoCreate;
property DayBuffer;
end;
implementation
uses
LazFileUtils,
VpConst, VpMisc;
{ TVpIBDatastore }
constructor TVpFirebirdDatastore.Create(AOwner: TComponent);
begin
inherited;
FContactsTable := TSQLQuery.Create(self);
FContactsTable.SQL.Add('SELECT * FROM Contacts');
FEventsTable := TSQLQuery.Create(Self);
FEventsTable.SQL.Add('SELECT * FROM Events');
FResourceTable := TSQLQuery.Create(self);
FResourceTable.SQL.Add(
'SELECT * '+
'FROM Resources'
);
{
FResourceTable.InsertSQL.Add(
'INSERT INTO Resources (' +
'ResourceID, Description, Notes, ResourceActive, ' +
'UserField0, UserField1, UserField2, UserField3, UserField4, ' +
'UserField5, UserField6, UserField7, UserField8, UserField9) ' +
'VALUES(' +
':ResourceID, :Description, :Notes, :ResourceActive, ' +
':UserField0, :UserField1, :UserField2, :UserField3, :UserField4, ' +
':UserField5, :UserField6, :UserField7, :UserField8, :UserField9);'
);
}
FTasksTable := TSQLQuery.Create(self);
FTasksTable.SQL.Add('SELECT * FROM Tasks');
end;
procedure TVpFirebirdDatastore.CreateAllTables(dbIsNew: Boolean);
var
tableNames: TStringList;
needCommit: Boolean;
begin
needCommit := false;
if dbIsNew then begin
CreateTable(ContactsTableName);
CreateTable(EventsTableName);
CreateTable(ResourceTableName);
CreateTable(TasksTableName);
needCommit := true;
end else
begin
tablenames := TStringList.Create;
try
tablenames.CaseSensitive := false;
FConnection.GetTableNames(tablenames);
if tablenames.IndexOf(ContactsTableName) = -1 then begin
CreateTable(ContactsTableName);
needCommit := true;
end;
if tablenames.IndexOf(EventsTableName) = -1 then begin
CreateTable(EventsTableName);
needCommit := true;
end;
if tablenames.IndexOf(ResourceTableName) = -1 then begin
CreateTable(ResourceTableName);
needCommit := true;
end;
if tablenames.IndexOf(TasksTableName) = -1 then begin
CreateTable(TasksTableName);
needCommit := true;
end;
finally
tablenames.Free;
end;
end;
if needCommit then
FConnection.Transaction.Commit;
end;
// Connection and tables are active afterwards!
procedure TVpFirebirdDatastore.CreateTables;
var
wasConnected: Boolean;
isNew: Boolean;
begin
isNew := false;
wasConnected := FConnection.Connected;
if not FileExistsUTF8(FConnection.DatabaseName) then begin
FConnection.Connected := false;
FConnection.CreateDB;
isNew := true;
end;
FConnection.Connected := true;
CreateAllTables(isNew);
SetConnected(wasConnected or AutoConnect);
end;
{ Note: Firebird with version < 3 does not support AutoInc fields.
Use a generator and trigger to create AutoInc values:
http://www.firebirdfaq.org/faq29/ }
procedure TVpFirebirdDatastore.CreateTable(const ATableName: String);
begin
if ATableName = ContactsTableName then begin
FConnection.ExecuteDirect(
'CREATE TABLE Contacts (' +
'RecordID INTEGER NOT NULL PRIMARY KEY, '+
'ResourceID INTEGER NOT NULL, ' +
'FirstName VARCHAR(50), '+
'LastName VARCHAR(50), '+
'Birthdate DATE, '+
'Anniversary DATE, '+
'Title VARCHAR(50), '+
'Company VARCHAR(50), '+
'Job_Position VARCHAR(30), '+
'Address VARCHAR(100), '+
'City VARCHAR(50), '+
'State VARCHAR(25), '+
'Zip VARCHAR(10), '+
'Country VARCHAR(25), '+
'Notes VARCHAR(1024), '+
'Phone1 VARCHAR(25), '+
'Phone2 VARCHAR(25), '+
'Phone3 VARCHAR(25), '+
'Phone4 VARCHAR(25), '+
'Phone5 VARCHAR(25), '+
'PhoneType1 INTEGER, '+
'PhoneType2 INTEGER, '+
'PhoneType3 INTEGER, '+
'PhoneType4 INTEGER, '+
'PhoneType5 INTEGER, '+
'Category INTEGER, '+
'EMail VARCHAR (100), '+
'Custom1 VARCHAR (100), '+
'Custom2 VARCHAR (100), '+
'Custom3 VARCHAR (100), '+
'Custom4 VARCHAR (100), '+
'UserField0 VARCHAR(100), '+
'UserField1 VARCHAR(100), '+
'UserField2 VARCHAR(100), '+
'UserField3 VARCHAR(100), '+
'UserField4 VARCHAR(100), '+
'UserField5 VARCHAR(100), '+
'UserField6 VARCHAR(100), '+
'UserField7 VARCHAR(100), '+
'UserField8 VARCHAR(100), '+
'UserField9 VARCHAR(100) )'
);
FConnection.ExecuteDirect(
'CREATE UNIQUE INDEX Contacts_RecordID_idx ON Contacts (RecordID);');
FConnection.ExecuteDirect(
'CREATE INDEX Contacts_ResourceID_idx ON Contacts (ResourceID);');
FConnection.ExecuteDirect(
'CREATE GENERATOR Contacts_AUTOINC; ');
FConnection.ExecuteDirect(
'SET GENERATOR Contacts_AUTOINC TO 0; ');
FConnection.ExecuteDirect(
'CREATE TRIGGER C_AUTOINC_TRG FOR Contacts ' +
'ACTIVE BEFORE INSERT POSITION 0 ' +
'AS ' +
'BEGIN ' +
'NEW.RecordID = GEN_ID(Contacts_AUTOINC, 1); ' +
'END '
);
end else
if ATableName = EventsTableName then begin
FConnection.ExecuteDirect(
'CREATE TABLE Events (' +
'RecordID INTEGER NOT NULL PRIMARY KEY, ' +
'ResourceID INTEGER NOT NULL, ' +
'StartTime TIMESTAMP NOT NULL, ' +
'EndTime TIMESTAMP NOT NULL, ' +
'Description VARCHAR (255), ' +
'Location VARCHAR (255), ' +
'Notes VARCHAR (1024), ' +
'Category INTEGER, ' +
'AllDayEvent CHAR(1), ' +
'DingPath VARCHAR (255), ' +
'AlarmSet CHAR(1), ' +
'AlarmAdvance INTEGER, ' +
'AlarmAdvanceType INTEGER, ' +
'SnoozeTime TIMESTAMP, ' +
'RepeatCode INTEGER, ' +
'RepeatRangeEnd TIMESTAMP, ' +
'CustomInterval INTEGER, ' +
'UserField0 VARCHAR(100), '+
'UserField1 VARCHAR(100), '+
'UserField2 VARCHAR(100), '+
'UserField3 VARCHAR(100), '+
'UserField4 VARCHAR(100), '+
'UserField5 VARCHAR(100), '+
'UserField6 VARCHAR(100), '+
'UserField7 VARCHAR(100), '+
'UserField8 VARCHAR(100), '+
'UserField9 VARCHAR(100) )'
);
FConnection.ExecuteDirect(
'CREATE UNIQUE INDEX Events_RecordID_idx ON Events (RecordID);');
FConnection.ExecuteDirect(
'CREATE INDEX Events_ResourceID_idx ON Events (ResourceID);');
FConnection.ExecuteDirect(
'CREATE INDEX Events_StartTime_idx ON Events (StartTime);');
FConnection.ExecuteDirect(
'CREATE INDEX Events_EndTime_idx ON Events (EndTime);');
FConnection.ExecuteDirect(
'CREATE GENERATOR Events_AUTOINC; ');
FConnection.ExecuteDirect(
'SET GENERATOR Events_AUTOINC TO 0; ');
FConnection.ExecuteDirect(
'CREATE TRIGGER E_AUTOINC_TRG FOR Events ' +
'ACTIVE BEFORE INSERT POSITION 0 ' +
'AS ' +
'BEGIN ' +
'NEW.RecordID = GEN_ID(Events_AUTOINC, 1); ' +
'END '
);
end else
if ATableName = ResourceTableName then begin
FConnection.ExecuteDirect(
'CREATE TABLE Resources (' +
'ResourceID INTEGER NOT NULL PRIMARY KEY, '+
'Description VARCHAR (255), ' +
'Notes VARCHAR (1024), ' +
'ImageIndex INTEGER, ' +
'ResourceActive CHAR(1), ' +
'UserField0 VARCHAR(100), '+
'UserField1 VARCHAR(100), '+
'UserField2 VARCHAR(100), '+
'UserField3 VARCHAR(100), '+
'UserField4 VARCHAR(100), '+
'UserField5 VARCHAR(100), '+
'UserField6 VARCHAR(100), '+
'UserField7 VARCHAR(100), '+
'UserField8 VARCHAR(100), '+
'UserField9 VARCHAR(100) )'
);
FConnection.ExecuteDirect(
'CREATE UNIQUE INDEX Resources_ResourceID_idx ON Resources (ResourceID);');
FConnection.ExecuteDirect(
'CREATE GENERATOR Resources_AUTOINC; ');
FConnection.ExecuteDirect(
'SET GENERATOR Resources_AUTOINC TO 0; ');
FConnection.ExecuteDirect(
'CREATE TRIGGER R_AUTOINC_TRG FOR Resources ' +
'ACTIVE BEFORE INSERT POSITION 0 ' +
'AS ' +
'BEGIN ' +
'NEW.ResourceID = GEN_ID(Resources_AUTOINC, 1); ' +
'END '
);
end else
if ATableName = TasksTableName then begin
FConnection.ExecuteDirect(
'CREATE TABLE Tasks (' +
'RecordID INTEGER NOT NULL PRIMARY KEY, ' +
'ResourceID INTEGER NOT NULL, ' +
'Complete CHAR(1), ' +
'Description VARCHAR(255), ' +
'Details VARCHAR(1024), ' +
'CreatedOn TIMESTAMP, ' +
'Priority INTEGER, ' +
'Category INTEGER, ' +
'CompletedOn TIMESTAMP, ' +
'DueDate TIMESTAMP, ' +
'UserField0 VARCHAR(100), '+
'UserField1 VARCHAR(100), '+
'UserField2 VARCHAR(100), '+
'UserField3 VARCHAR(100), '+
'UserField4 VARCHAR(100), '+
'UserField5 VARCHAR(100), '+
'UserField6 VARCHAR(100), '+
'UserField7 VARCHAR(100), '+
'UserField8 VARCHAR(100), '+
'UserField9 VARCHAR(100) )'
);
FConnection.ExecuteDirect(
'CREATE UNIQUE INDEX Tasks_RecordID_idx ON Tasks (RecordID);');
FConnection.ExecuteDirect(
'CREATE INDEX Tasks_ResourceID_idx ON Tasks (ResourceID);');
FConnection.ExecuteDirect(
'CREATE GENERATOR Tasks_AUTOINC; ');
FConnection.ExecuteDirect(
'SET GENERATOR Tasks_AUTOINC TO 0; ');
FConnection.ExecuteDirect(
'CREATE TRIGGER T_AUTOINC_TRG FOR Tasks ' +
'ACTIVE BEFORE INSERT POSITION 0 ' +
'AS ' +
'BEGIN ' +
'NEW.RecordID = GEN_ID(Tasks_AUTOINC, 1); ' +
'END '
);
end;
end;
function TVpFirebirdDatastore.GetContactsTable: TDataset;
begin
Result := FContactsTable;
end;
function TVpFirebirdDatastore.GetEventsTable: TDataset;
begin
Result := FEventsTable;
end;
function TVpFirebirdDataStore.GetNextID(TableName: string): integer;
begin
Unused(TableName);
{ This is not needed in the Firebird datastore as these tables use a
generator and trigger for autoincrement fields.
http://www.firebirdfaq.org/faq29/ }
Result := -1;
end;
function TVpFirebirdDatastore.GetResourceTable : TDataset;
begin
Result := FResourceTable;
end;
function TVpFirebirdDatastore.GetTasksTable : TDataset;
begin
Result := FTasksTable;
end;
procedure TVpFirebirdDatastore.Loaded;
begin
inherited;
if not (csDesigning in ComponentState) then
Connected := AutoConnect and (AutoCreate or FileExists(FConnection.DatabaseName));
end;
procedure TVpFirebirdDatastore.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = FConnection) then
FConnection := nil;
end;
{ Note: Set the property Required of the PrimaryKey field to false. Otherwise
Firebird will complain about this field not being specified when posting. }
procedure TVpFirebirdDatastore.OpenTables;
begin
if FContactsTable.Transaction = nil then
FContactsTable.Transaction := FConnection.Transaction;
FContactsTable.Open;
FContactsTable.Fields[0].Required := false;
if FEventsTable.Transaction = nil then
FEventsTable.Transaction := FConnection.Transaction;
FEventsTable.Open;
FEventsTable.Fields[0].Required := false;
if FResourceTable.Transaction = nil then
FResourceTable.Transaction := FConnection.Transaction;
FResourceTable.Open;
FResourceTable.Fields[0].Required := false;
if FTasksTable.Transaction = nil then
FTasksTable.Transaction := FConnection.Transaction;
FTasksTable.Open;
FTasksTable.Fields[0].Required := false;
end;
procedure TVpFirebirdDatastore.PostContacts;
begin
inherited;
FContactsTable.ApplyUpdates;
end;
procedure TVpFirebirdDatastore.PostEvents;
begin
inherited;
FEventsTable.ApplyUpdates;
end;
procedure TVpFirebirdDatastore.PostResources;
begin
inherited;
FResourceTable.ApplyUpdates;
end;
procedure TVpFirebirdDatastore.PostTasks;
begin
inherited;
FTasksTable.ApplyUpdates;
end;
procedure TVpFirebirdDatastore.SetConnected(const AValue: Boolean);
begin
if (AValue = Connected) or (FConnection = nil) or (FConnectLock > 0) then
exit;
inc(FConnectLock);
if AValue and AutoCreate then
CreateTables;
FConnection.Connected := AValue;
if FConnection.Connected then
OpenTables;
inherited SetConnected(AValue);
if FConnection.Connected then
Load;
dec(FConnectLock);
end;
(*
begin
if (FConnection = nil) or (FConnection.Transaction = nil) then
exit;
if AValue = FConnection.Connected then
exit;
if AValue and AutoCreate then
CreateTables;
FConnection.Connected := AValue;
if AValue then
begin
FConnection.Transaction.Active := true;
OpenTables;
end;
inherited SetConnected(AValue);
if FConnection.Connected then
Load;
end; *)
procedure TVpFirebirdDatastore.SetConnection(const AValue: TIBConnection);
var
wasConnected: Boolean;
begin
if AValue = FConnection then
exit;
// To do: clear planit lists...
if FConnection <> nil then begin
wasConnected := FConnection.Connected;
Connected := false;
end;
FConnection := AValue;
FContactsTable.Database := FConnection;
FContactsTable.Transaction := FConnection.Transaction;
FEventsTable.Database := FConnection;
FEventsTable.Transaction := FConnection.Transaction;
FResourceTable.Database := FConnection;
FResourceTable.Transaction := FConnection.Transaction;
FTasksTable.Database := FConnection;
FTasksTable.Transaction := FConnection.Transaction;
if wasConnected then Connected := true;
end;
end.
|
// файл rook.pas
unit rook;
interface
uses figure, board;
//------------------------------------
Type Trook = class( Tfigure ) // класс Ладья
protected
function can_move(
to_position: Tposition
): Boolean; override;
public
constructor Init( ident: Tid; chessBoard: Tboard );
destructor delete;
end;
//------------------------------------
implementation
//------------------------------------
// может ли ладья идти в to_position
//------------------------------------
function Trook.can_move( to_position: Tposition ): Boolean;
begin
result := ( ID.pos.x = to_position.x )
OR ( ID.pos.y = to_position.y );
end;
//------------------------------------
constructor Trook.Init( ident: Tid; chessBoard: Tboard );
begin
inherited Init( ident, chessBoard );
end;
//------------------------------------
destructor Trook.delete;
begin
inherited delete;
end;
end. // конец файла rook.pas
|
unit uTemplaiteReceipt30; {перевод почасовки}
interface
uses SysUtils,
Classes,
Dialogs,
ibase,
DB,
FIBDatabase,
pFIBDatabase,
FIBDataSet,
pFIBDataSet;
function GetTemplateString(hConnection: TISC_DB_HANDLE; id_session, id_item: Int64): string; stdcall;
exports GetTemplateString;
implementation
function GetTemplateString(hConnection: TISC_DB_HANDLE; id_session, id_item: Int64): string; stdcall;
var
szResult: string; // Строка для формирования результирующей строки
szTemp, s, s1, s2: string; // Строка для хранения текстовой строки
cTemp: Char; // Переменная для хранения символа
iTemp, iT, i: Integer; // Переменная для хранения значения целого типа
iLength: Integer; // Переменная для хранения значения целого типа длины цикла
fdbTemplateReceipt: TpFIBDatabase; // База
ftrTemplateReceipt: TpFIBTransaction; // Транзакция
fdsTemplateReceipt: TpFIBDataSet; // Датасэт
HoursOld, HoursNew: Real;
Hours: Real;
begin
decimalseparator := '.';
try
fdbTemplateReceipt := TpFIBDatabase.Create(nil);
ftrTemplateReceipt := TpFIBTransaction.Create(nil);
fdsTemplateReceipt := TpFIBDataSet.Create(nil);
fdbTemplateReceipt.SQLDialect := 3;
fdbTemplateReceipt.Handle := hConnection;
ftrTemplateReceipt.DefaultDatabase := fdbTemplateReceipt;
fdbTemplateReceipt.DefaultTransaction := ftrTemplateReceipt;
fdsTemplateReceipt.Database := fdbTemplateReceipt;
fdsTemplateReceipt.Transaction := ftrTemplateReceipt;
ftrTemplateReceipt.StartTransaction;
szResult := '';
fdsTemplateReceipt.SQLs.SelectSQL.Text := 'SELECT * FROM up_dt_order_item_body WHERE id_session = ' + IntToStr(id_session) + '';
fdsTemplateReceipt.Open;
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'NUM_ITEM_1', []) then
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + '.';
// Номер подпункта
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'NUM_SUB_ITEM_1', []) then
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + '. ';
// Фамилия
szResult := szResult + '<u>ПІБ:</u> <b>';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'POCHAS_SECOND_NAME_UA_1_1', []) then
// Заглавными буквами
szResult := szResult + AnsiUpperCase(fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString) + ' ';
// Имя
szTemp := '';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'POCHAS_FIRST_NAME_UA_1_1', []) then
begin
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + ' ';
// Первая буква заглавная, а остальные маленькие
{ szTemp := fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString;
cTemp := UpCase(szTemp[1]);
szTemp := AnsiLowerCase(szTemp);
szTemp[1] := cTemp;
szResult := szResult + szTemp + ' ';}
end;
// Отчество
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'POCHAS_LAST_NAME_UA_1_1', []) then
begin
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + ' ';
// Первая буква заглавная, а остальные маленькие
{ szTemp := fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString;
cTemp := UpCase(szTemp[1]);
szTemp := AnsiLowerCase(szTemp);
szTemp[1] := cTemp;
szResult := szResult + szTemp;}
end;
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'POCHAS_TN_1_1', []) then
if fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString <> '' then
szResult := szResult + '(TH ' + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + '),';
szResult := szResult + '</b> ';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'EX_POCHAS_EDUC_ZVANIE_AND_ST_1_1', [])
then if fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString <> '' then
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + ', ';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'EX_POCHAS_N_POST_1_1', []) then
begin
if not fdsTemplateReceipt.FBN('PARAMETR_VALUE').IsNull then
begin
{szTemp := fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString;
cTemp := ansiLowerCase(szTemp)[1];
szTemp[1] := cTemp;
szResult := szResult + '<u>посада:</u> ' + szTemp + ', ';
szTemp := '';}
szTemp := fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString;
s := copy(szTemp, 2, 1);
if ((ord(s[1]) <= 223) and (ord(s[1]) >= 192)) or (ord(s[1]) = 175) or (ord(s[1]) = 178) or (ord(s[1]) = 170) or (ord(s[1]) = 73) then
begin
szResult := szResult + '<u>посада:</u> ' + szTemp + '</b>, ';
end else
begin
cTemp := ansiLowerCase(szTemp)[1];
szTemp[1] := cTemp;
szResult := szResult + '<u>посада:</u> ' + szTemp + '</b>, ';
end;
szTemp := '';
end;
end;
szResult := szResult + '<u>тип погодинної праці:</u> ';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'EX_POCHAS_POCHAS_TYPE_NAME_1_1', []) then
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString;
szResult := szResult + ', ' + '<u>підрозділ:</u> ';
// Подразделение
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'EX_POCHAS_NAME_DEPARTMENT_VERH_1_1', []) then
begin
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + ', ';
end;
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'EX_POCHAS_NAME_DEPARTMENT_1_1', []) then
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + ',';
szResult := szResult + ' з ';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'EX_POCHAS_DATE_BEG_1_1', []) then
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString;
szResult := szResult + ' по ';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'EX_POCHAS_DATE_END_1_1', []) then
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + ', ';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'EX_POCHAS_HOURS_1_1', []) then
begin
if not fdsTemplateReceipt.FBN('PARAMETR_VALUE').IsNull then
begin
szResult := szResult + '<i> з навчальним навантаженням ';
szResult := szResult + FormatFloat('0.00', fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsFloat);
szResult := szResult + ' год</i>.,';
HoursOld := fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsFloat;
end;
end
else szResult := szResult + ' ';
szResult := szResult + ' <u>тариф:</u> ';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'EX_POCHAS_TARIF_1_1', []) then
szResult := szResult + FormatFloat('0.00', fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsFloat);
szResult := szResult + ' грн. на годину (';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'EX_POCHAS_TARIF_TYPE_NAME_1_1', []) then
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString;
szResult := szResult + '), ';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'EX_POCHAS_COUNT_SM_1_1', []) then
begin
szTemp := '';
iLength := fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsInteger;
for iTemp := 1 to iLength do begin
// if iLength >1 then
// if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'PR_SUMMA_SMETA_1_1_' + IntToStr(iTemp), []) then
// szTemp := szTemp + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString;
if iLength > 1 then
if ((fdsTemplateReceipt.Locate('PARAMETR_NAME', 'EX_POCHAS_HOURS_SMETA_1_1_' + IntToStr(iTemp), [])) and (fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString <> '')) then
begin
szTemp := szTemp + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + ' год. ';
end;
szTemp := szTemp + 'за рахунок ';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'EX_POCHAS_SMETA_TITLE_1_1_' + IntToStr(iTemp), []) then
szTemp := szTemp + AnsiLowerCase(fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString);
szTemp := szTemp + ' (';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'EX_POCHAS_SMETA_KOD_1_1_' + IntToStr(iTemp), []) then
szTemp := szTemp + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString;
szTemp := szTemp + ')';
szTemp := szTemp + ', ';
end;
end;
szResult := szResult + szTemp + #13#10;
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'POCHAS_EDUC_ZVANIE_AND_ST_1_1', [])
then if fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString <> '' then
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + ', ';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'POCHAS_N_POST_1_1', []) then
begin
if not fdsTemplateReceipt.FBN('PARAMETR_VALUE').IsNull then
begin
{szTemp := fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString;
cTemp := ansiLowerCase(szTemp)[1];
szTemp[1] := cTemp;
szResult := szResult + '<u>посада:</u> ' + szTemp + ', ';
szTemp := '';}
szTemp := fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString;
s := copy(szTemp, 2, 1);
if ((ord(s[1]) <= 223) and (ord(s[1]) >= 192)) or (ord(s[1]) = 175) or (ord(s[1]) = 178) or (ord(s[1]) = 170) or (ord(s[1]) = 73) then
begin
szResult := szResult + '<u>посада:</u> ' + szTemp + '</b>, ';
end else
begin
cTemp := ansiLowerCase(szTemp)[1];
szTemp[1] := cTemp;
szResult := szResult + '<u>посада:</u> ' + szTemp + '</b>, ';
end;
szTemp := '';
end;
end;
szResult := szResult + '<u>тип погодинної праці:</u> ';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'POCHAS_POCHAS_TYPE_NAME_1_1', []) then
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString;
szResult := szResult + ', ' + '<u>підрозділ:</u> ';
// Подразделение
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'POCHAS_NAME_DEPARTMENT_VERH_1_1', []) then
begin
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + ', ';
end;
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'POCHAS_NAME_DEPARTMENT_1_1', []) then
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + ',';
szResult := szResult + '<i> з ';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'POCHAS_DATE_BEG_1_1', []) then
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString;
szResult := szResult + ' по ';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'POCHAS_DATE_END_1_1', []) then
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + ' ';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'POCHAS_HOURS_1_1', []) then
begin
if not fdsTemplateReceipt.FBN('PARAMETR_VALUE').IsNull then
begin
HoursNew := fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsFloat;
Hours := HoursNew - HoursOld;
if Hours > 0 then
begin
szResult := szResult + ' збільшити навантаження на ';
szResult := szResult + FormatFloat('0.00', Hours) + ' год.';
end
else begin
if Hours < 0 then
begin
szResult := szResult + ' зменшити навантаження на ';
szResult := szResult + FormatFloat('0.00', Hours) + ' год.';
end
{ //если изменение 0 - то не печатать изменить нагрузку
//иначе получается что-то вроде "змінити навантаження на 0.00 годин з загальним обсягом навантаження..."
else
szResult := szResult + ' змінити навантаження на '}
end;
szResult := szResult + ' з загальним обсягом навантаження ';
szResult := szResult + FormatFloat('0.00', fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsFloat);
szResult := szResult + ' год</i>.,';
end;
end
else szResult := szResult + ' ';
szResult := szResult + ' <u>тариф:</u> ';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'POCHAS_TARIF_1_1', []) then
szResult := szResult + FormatFloat('0.00', fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsFloat);
szResult := szResult + ' грн. на годину (';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'POCHAS_TARIF_TYPE_NAME_1_1', []) then
szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString;
szResult := szResult + '), ';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'POCHAS_COUNT_SM_1_1', []) then
begin
szTemp := '';
iLength := fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsInteger;
for iTemp := 1 to iLength do begin
// if iLength >1 then
// if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'PR_SUMMA_SMETA_1_1_' + IntToStr(iTemp), []) then
// szTemp := szTemp + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString;
if iLength > 1 then
if ((fdsTemplateReceipt.Locate('PARAMETR_NAME', 'POCHAS_HOURS_SMETA_1_1_' + IntToStr(iTemp), [])) and (fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString <> '')) then
begin
szTemp := szTemp + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + ' год. ';
end;
szTemp := szTemp + 'за рахунок ';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'POCHAS_SMETA_TITLE_1_1_' + IntToStr(iTemp), []) then
szTemp := szTemp + AnsiLowerCase(fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString);
szTemp := szTemp + ' (';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'POCHAS_SMETA_KOD_1_1_' + IntToStr(iTemp), []) then
szTemp := szTemp + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString;
szTemp := szTemp + ')';
if not (iTemp = iLength) then
begin
szTemp := szTemp + ', ';
end
else begin
szTemp := szTemp + '. ';
end;
end;
end;
szResult := szResult + szTemp;
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'NOTE_1', []) then
if (fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString <> '') and (fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString <> ' ') then
szResult := szResult + ' ' + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString + '. ';
//szResult := szResult + szTemp+#13;
szResult := szResult + #13 + '<u>Підстава:</u> ';
if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'REASON_1', []) then
szTemp := fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString;
iT := 0;
for i := 0 to Length(szTemp) - 1 do
begin
s1 := copy(szTemp, i, 1);
if s1 = ' ' then inc(iT)
else break;
end;
s := AnsiLowerCase(Copy(szTemp, 1, iT + 1));
//szTemp := AnsiLowerCase(szTemp);
//szTemp[1] := s;
szResult := szResult + s + Copy(szTemp, iT + 2, Length(szTemp));
//szResult := szResult + fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString;
ftrTemplateReceipt.Rollback;
fdsTemplateReceipt.Free;
ftrTemplateReceipt.Free;
fdbTemplateReceipt.Free;
decimalseparator := ',';
except on Error: Exception do begin
decimalseparator := ',';
MessageDlg('Неможливо сформувати пункт наказу!', mtError, [mbOk], 0);
// szResult := '';
end;
end;
Result := szResult;
end;
end.
|
unit VSearchRecAux;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, ValEdit, StdCtrls, ExtCtrls, ComCtrls;
type
TSearchRecAuxForm = class(TForm)
Panel1: TPanel;
AceptarBtn: TButton;
CancelarBtn: TButton;
ElementsListView: TListView;
Label1: TLabel;
buscarEdit: TEdit;
procedure ElementsListViewSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure buscarEditChange(Sender: TObject);
procedure ElementsListViewColumnClick(Sender: TObject;
Column: TListColumn);
procedure ElementsListViewCompare(Sender: TObject; Item1,
Item2: TListItem; Data: Integer; var Compare: Integer);
procedure AceptarBtnClick(Sender: TObject);
private
FComparationIndex: Integer;
FValorSeleccionado: String;
public
procedure showElements(anElementsList: TStringList);
function getSelectedValue: String;
end;
var
SearchRecAuxForm: TSearchRecAuxForm;
implementation
{$R *.dfm}
(****************
MÉTODOS PÚBLICOS
****************)
procedure TSearchRecAuxForm.showElements(anElementsList: TStringList);
var
numElement: Integer;
auxName: String;
newListItem: TListItem;
begin
ElementsListView.Clear();
for numElement := 0 to anElementsList.Count - 1 do
begin
auxName := anElementsList.Names[numElement];
//
newListItem := ElementsListView.Items.Add();
newListItem.Caption := auxName;
newListItem.SubItems.Add(anElementsList.Values[auxName]);
end
end;
function TSearchRecAuxForm.getSelectedValue: String;
begin
Result := FValorSeleccionado;
end;
procedure TSearchRecAuxForm.ElementsListViewSelectItem(Sender: TObject;
Item: TListItem; Selected: Boolean);
begin
AceptarBtn.Enabled := (Item <> nil);
end;
procedure TSearchRecAuxForm.buscarEditChange(Sender: TObject);
var
numItem: Integer;
textToSearch: String;
saltoScroll: Integer;
begin
textToSearch := UpperCase(Trim(TEdit(Sender).Text));
if textToSearch <> EmptyStr then
begin
for numItem := 0 to ElementsListView.Items.Count - 1 do
if ( Pos(textToSearch, UpperCase(ElementsListView.Items[numItem].Caption) ) > 0 )
or ( Pos(textToSearch, UpperCase(ElementsListView.Items[numItem].SubItems.Strings[0]) ) > 0 ) then
begin
ElementsListView.ItemFocused := ElementsListView.Items[numItem];
ElementsListView.ItemIndex := numItem;
ElementsListView.Selected := ElementsListView.Items[numItem];
saltoScroll := ElementsListView.ItemFocused.Top - 20;
ElementsListView.Scroll(0,saltoScroll);
break;
end
end;
end;
procedure TSearchRecAuxForm.ElementsListViewColumnClick(Sender: TObject;
Column: TListColumn);
begin
FComparationIndex := Column.Index;
TListView(Sender).SortType := stBoth;
end;
procedure TSearchRecAuxForm.ElementsListViewCompare(Sender: TObject; Item1,
Item2: TListItem; Data: Integer; var Compare: Integer);
begin
Compare := 0; // en principio son iguales
if FComparationIndex = 0 then
begin
if UpperCase(Item1.Caption) < UpperCase(Item2.Caption) then
Compare := -1
else if UpperCase(Item1.Caption) > UpperCase(Item2.Caption) then
Compare := 1
end
else
begin
if UpperCase(Item1.SubItems.Strings[0]) < UpperCase(Item2.SubItems.Strings[0]) then
Compare := -1
else if UpperCase(Item1.SubItems.Strings[0]) > UpperCase(Item2.SubItems.Strings[0]) then
Compare := 1
end
end;
procedure TSearchRecAuxForm.AceptarBtnClick(Sender: TObject);
begin
FValorSeleccionado := EmptyStr;
if ElementsListView.Selected <> nil then
FValorSeleccionado := ElementsListView.Selected.Caption;
ModalResult := mrOK;
end;
end.
|
{------------------------------------------------------------------------------------}
{program p022_000 exercises production #022 }
{parameter_list -> identifier_list : type }
{------------------------------------------------------------------------------------}
{Author: Thomas R. Turner }
{E-Mail: trturner@uco.edu }
{Date: January, 2012 }
{------------------------------------------------------------------------------------}
{Copyright January, 2012 by Thomas R. Turner }
{Do not reproduce without permission from Thomas R. Turner. }
{------------------------------------------------------------------------------------}
program p022_000;
function max(a,b:integer):integer;
begin{max}
if a>b then max:=a else max:=b
end{max};
procedure print(a,b:integer);
begin{print}
writeln('The maximum of ',a,' and ',b,' is ',max(a,b))
end{print};
begin{p022_000}
print(2,3)
end{p022_000}.
|
{$I texel.inc}
unit txfont;
{ 1998-07-08 }
interface
uses
ODialogs;
type
PFontSelectBox = ^TFontSelectBox;
TFontSelectBox = object(TComboBox)
procedure Changed(AnIndx: integer; DblClick: boolean); virtual;
procedure OpenPopup; virtual;
end;
PFontSizeBox = ^TFontSizeBox;
TFontSizeBox = object(TFontSelectBox)
setsize: boolean;
procedure Work; virtual;
end;
PFontBox = ^TFontBox;
TFontBox = object(TFontSelectBox)
fsizebox: PFontSizeBox;
newsize : integer;
procedure SetValue(Sel: integer); virtual;
procedure Work; virtual;
end;
implementation
uses
Objects,OTypes,OProcs,owindows,
txtypes,txmain;
procedure TFontSelectBox.Changed(AnIndx: integer; DblClick: boolean);
begin
if DblClick then
if Parent^.GetClassName=TEXELWINDCLASS then
begin
PCalcWindow(Parent)^.FontSelect;
exit
end;
inherited Changed(AnIndx,DblClick)
end;
procedure TFontSelectBox.OpenPopup;
begin
Popup^.SetOffset(GetSelection-2)
end;
procedure TFontBox.SetValue(Sel: integer);
begin
if Popup<>nil then SetText(StrPTrimF(StrPLeft(StrPTrimF(Popup^.GetText(Sel)),25)))
end;
procedure TFontBox.Work;
var p : PStringCollection;
pf : PFont;
q,n,old,
neu,cm,
oldofs : integer;
dummy : string;
found,
chng : boolean;
begin
if (GetSelection<0) or (GetSelection>=List^.Count) or (fsizebox=nil) then exit;
p:=fsizebox^.List;
pf:=PFont(List^.At(GetSelection));
if (p=nil) or (pf=nil) then exit;
old:=atol(fsizebox^.GetText);
if old=0 then old:=10;
oldofs:=0;
if fsizebox^.Popup<>nil then oldofs:=fsizebox^.Popup^.GetOffset;
cm:=fsizebox^.GetSelection;
fsizebox^.ClearSelection(true);
if (pf^.SizeCount<>0) or (p^.Count<>124) then
begin
chng:=true;
p^.FreeAll;
if pf^.SizeCount=0 then
begin
for q:=4 to 127 do
begin
if q<10 then dummy:=' '
else
if q<100 then dummy:=' '
else
dummy:=' ';
p^.Insert(NewStr(dummy+ltoa(q)+' '#0))
end;
neu:=old;
cm:=neu-4
end
else
begin
found:=false;
for q:=0 to pf^.SizeCount-1 do
begin
n:=pf^.Sizes^[q];
if n<10 then dummy:=' '
else
if n<100 then dummy:=' '
else
dummy:=' ';
p^.Insert(NewStr(dummy+ltoa(n)+' '#0));
if not(found) then
if n<=old then
begin
if q=0 then
begin
neu:=n;
cm:=pf^.SizeCount-1
end
else
if (old-n)>(pf^.Sizes^[q-1]-old) then
begin
neu:=pf^.Sizes^[q-1];
cm:=pf^.SizeCount-q
end
else
begin
neu:=n;
cm:=pf^.SizeCount-q-1
end;
found:=true;
if neu<>0 then begin end;
end
end
end
end
else
chng:=false;
with fsizebox^ do
begin
if chng then
if Popup<>nil then
with Popup^ do
begin
SetCollection(p);
SetOffset(oldofs)
end;
setsize:=false;
if newsize<0 then SetSelection(cm,true)
else
begin
SetSelection(PCalcWindow(Parent)^.FontSize2Index(newsize),false);
newsize:=-1
end;
setsize:=true
end
end;
procedure TFontSizeBox.Work;
var rs,cs,re,ce,
cmin,cmax,
x,y,nsize,
nfont : integer;
cell : PCell;
p : PCalcWindow;
begin
with PWindow(Parent)^ do
begin
if GetClassName<>TEXELWINDCLASS then exit;
if Attr.Status<>ws_Open then exit
end;
nsize:=atol(GetText);
if nsize<4 then exit;
p:=PCalcWindow(Parent);
nfont:=PFont(p^.pfbox^.List^.At(p^.pfbox^.GetSelection))^.Index;
with p^.Parms.Cursor do
if Block then
begin
rs:=RowStart;
re:=RowEnd;
cs:=ColStart;
ce:=ColEnd
end
else
begin
rs:=Row;
re:=Row;
cs:=Col;
ce:=Col
end;
cmin:=cs;
cmax:=ce;
p^.RowsClearOverflow(rs,re,cmin,cmax);
for y:=rs to re do
begin
cell:=p^.GetCell(y,cs);
for x:=cs to ce do
begin
with cell^.TxtVal do
begin
if not(setsize) or (Font=0) then Font:=nfont;
if setsize or (Size=0) then Size:=nsize
end;
inc(longint(cell),CELLSIZE)
end
end;
p^.RowsCheckOverflow(rs,re,cmin,cmax);
p^.SetDirty;
p^.DrawCells(rs,cmin,re,cmax)
end;
end.
|
unit uCheckups;
interface
uses uCommonForm, Classes, dbTables, OilStd, SysUtils, Dialogs, Ora, Forms,
uMessageDlgExt, uMd5Hash,uOilQuery,uOilStoredProc{$IFDEF VER150},StrUtils{$ENDIF};
type
TSessionType = (stBDE, stOra);
TCheckupStatus = class(TObject)
private
//vEnabled : string;
vErrBlock, vErrWarning, vBuildBlock, vBuildWarning, vEmpty : string;
vErrBlockMessage, vErrWarningMessage, vBuildBlockMessage, vBuildWarningMessage : string;
qMain, qVar, qSelect, qUpdate : TOilQuery;
procedure UpdateAllChecksums;
public
constructor Create;
destructor Destroy; override;
function Refresh: boolean;
function TestTablesChecksum: Boolean;
function UpdateChecksum(TableName: String; SessionType: TSessionType): Boolean;
//property Enabled : string read vEnabled; // Список включенных проверок
property Empty : string read vEmpty write vEmpty; //Проверки включены, но ни разу не строились
property ErrBlock : string read vErrBlock; // Проверки, по которым истек срок исправления ошибок
property ErrWarning : string read vErrWarning; // Пров по которым включен счетчик
property BuildBlock : string read vBuildBlock; // Устаревшие результаты
property BuildWarning : string read vBuildWarning; // Результаты устареют через пару дней
property ErrBlockMessage : string read vErrBlockMessage; // Соотв мессаги
property ErrWarningMessage : string read vErrWarningMessage;
property BuildBlockMessage : string read vBuildBlockMessage;
property BuildWarningMessage : string read vBuildWarningMessage;
end;
const
{
Для добавления таблицы в котроль нужно добавить:
- запись в таблицу OIL_CC
- поле ROW_CHECKSUM в котролируемую таблицу
- запись в массив TablesUnderControl
}
TABLE_ACTIVE = 1;
TABLE_NAME = 2;
MIN_COUNT = 3;
CHECKSUM = 4;
var
Tables: array [1..3,1..4] of string = (
('Y','OIL_CHECKUP_RESULT','10',' rawtohex(oilt.md5(id||inst||checkup_id||crt_date||err_date||err_count|| :Key || :Key1 ))'),
('Y','CARD_CHECKUPS','10',' rawtohex(oilt.md5(id||inst||checkup_id||name||enabled||start_time||warning_time||warning_pause||time_to_block||active_days||max_days_fault||warning_quantity|| :Key || :Key1 )) '),
('N','OIL_CHECKUPS','19',' rawtohex(oilt.md5(id||inst||Enabled||quantity||correction||errors_allow||silence_period||date_fld||falling_date|| :Key || :Key1 ))')
);
implementation
uses main, uDBFunc, Exfunc, uTestLaunch;
constructor TCheckupStatus.Create;
Begin
vEmpty :='';
vErrBlock :='';
vErrWarning :='';
vBuildBlock :='';
vBuildWarning:='';
vErrBlockMessage :='Истек срок на исправление ошибок по следующим проверкам:';
vErrWarningMessage := 'На исправление ошибок по проверкам осталось: ';
vBuildBlockMessage := 'Устарели результаты по проверкам:';
vBuildWarningMessage :='Выполните проверки по талонам, карточкам и бланкам !'+#13#10+
'В противном случае через день/два работа программы будет заблокирована !';
qSelect := TOilQuery.Create(nil);
qSelect.SQL.Text :='select C.* from oil_checkups C '+
'where Enabled !=(select EnCoder(Decode(Instr('',''||DeCoder(SubStr(V.value,2))||'','',C.id),0,''N'',''Y''),V1.Value,C.Id) '+
' from oil_var V, oil_var V1 '+
' where V.name=''CH_AUDIT_LIST'' and V1.name=''ID'') ';
qUpdate := TOilQuery.Create(nil);
qUpdate.SQL.Text :='update oil_checkups C set Enabled= '+
' (select EnCoder(Decode(Instr('',''||DeCoder(SubStr(V.value,2))||'','',C.id),0,''N'',''Y''),V1.Value,C.Id) '+
' from oil_var V, oil_var V1 '+
' where V.name=''CH_AUDIT_LIST'' and V1.name=''ID'') ';
qMain := TOilQuery.Create(nil);
qMain.SQL.Text :=
'-->qMain,uCheckups '+#13#10+
'select nvl(DC.id,c.id) as id, '+
' nvl(DC.name, '+
' decode(ov.Language, '+
' 1, ''Увага! Помилка! Зверніться до розробників!'', '+
' ''Внимание! Ошибка! Обратитесь к разработчикам!'')) as name, '+
' to_date(C.falling_date,''dd.mm.yyyy hh24:mi:ss'') as fall_date, '+
' Decode(c.falling_date,''01.01.1999'',null,to_date(c.falling_date)+c.correction-trunc(sysdate)) as ErrDays, '+
' to_date(cr.crt_date,''dd.mm.yyyy hh24:mi:ss'') as crt_date, '+
' C.Quantity, '+
' trunc(sysdate) as today, '+
' trunc(nvl(cr.crt_date,''01.01.2000'')+c.quantity)-trunc(sysdate) as BuildDays '+
'from OIL_DECODE_CHECKUP DC, '+
' (select C.id, C.inst, '+
' DeCoder(Enabled,C.inst,id) as Enabled, '+
' DeCoder(Quantity,C.inst,id) as Quantity, '+
' DeCoder(Correction,C.inst,id) as Correction, '+
' DeCoder(ERRORS_ALLOW,C.inst,id) as ERRORS_ALLOW, '+
' DeCoder(SILENCE_PERIOD,C.inst,id) as SILENCE_PERIOD, '+
' DeCoder(FALLING_DATE,C.inst,id*C.inst) as FALLING_DATE '+
' from OIL_CHECKUPS C, (select value as INST from oil_var where name = ''ID'') V '+
' where C.inst = V.inst) C, '+
' (select value as INST from oil_var where name = ''ID'') V, '+
' (select CR.inst, CR.checkup_id, '+
' max(to_date(DeCoder(CR.crt_date,CR.inst,CR.CheckUp_ID),''dd.mm.yyyy hh24:mi:ss'')) as crt_date '+
' from oil_checkup_result CR, '+
' (select value as INST from oil_var where name = ''ID'') V '+
' where V.inst = CR.inst '+
' and (select max(id) from oil_checkup_result where inst = ov.GetVal(''INST'')) between id - 100 and id+100 '+
' group by CR.inst, CR.checkup_id) CR '+
'where c.id = dc.id(+) and '+
' c.enabled = ''Y'' and '+
' c.id = cr.checkup_id (+) and '+
' c.inst = cr.inst (+) ';
{включить проверку с 1 августа 2006 года}
if Trunc(GetSystemDate) >= StrToDate('01.01.1999')+364*7+31*7+4
then Tables[3][TABLE_ACTIVE] := 'Y';
End;
destructor TCheckupStatus.Destroy;
Begin
qMain.Free;
qUpdate.Free;
qVar.Free;
inherited Destroy;
End;
function TCheckupStatus.Refresh: boolean;
var
AddErrDays, AddBuildDays : Integer;
//-----------------------------------------------
function AdditionDays(StartDate : TDateTime):integer;
var Hld : String;
Now_, T : TDateTime;
Begin
Hld := ReadOILVar('HOLIDAYS');
Now_ := trunc(GetSystemDate);
Result := 0;
T := StartDate;
while T <= Now_ do Begin
if (DayOfWeek(T) in [1,7]) or (pos(FormatDateTime('dd.mm', T), Hld) > 0) then
Result := Result + 1;
T := T + 1;
End;
End;
//-----------------------------------------------
Begin
startlog(TranslateText(' обновляется статус проверок...'));
Result := false;
try
if not CheckupStatus.TestTablesChecksum then
begin
Application.Terminate;
Exit;
end;
// активація другорядних перевірок
// 18. Проверки с OIL_CHECKUPS
if not ActiveCH(18) then
begin
Result := true;
exit;
end;
if not Debugging then begin
startlog(TranslateText(' обновление списка активных проверок'));
StartSQL;
qUpdate.ExecSQL;
UpdateChecksum('OIL_CHECKUPS',stBDE);
CommitSQL;
end;
//qSelect.Close;
_OpenQuery(qMain);
startlog(TranslateText(' получение информации о состоянии проверок'));
while not qMain.Eof do
Begin
startlog(TranslateText(' обработка id=')+qMain.FieldByName('id').AsString);
if not qMain.FieldByName('ErrDays').IsNull
then
Begin
{Если в момент возникновения ошибки были выходные - учесть это}
AddErrDays := AdditionDays(qMain.FieldByName('fall_date').AsDateTime);
{Если все равно число отрицательное, то записать проверку в список заблокированныъ}
if qMain.FieldByName('ErrDays').AsInteger+AddErrDays<0
then
Begin
vErrBlock := vErrBlock +qMain.FieldByName('id').AsString+',';
vErrBlockMessage := vErrBlockMessage +#13#10+qMain.FieldByName('name').AsString;
End
else
{если нет - в список предупреждения}
Begin
vErrWarning := vErrWarning +qMain.FieldByName('id').AsString+',';
vErrWarningMessage := vErrWarningMessage +#13#10+qMain.FieldByName('name').AsString+
' '+IntToStr(qMain.FieldByName('errdays').AsInteger+AddErrDays)+' '+
DaysOrf(qMain.FieldByName('errdays').AsInteger+AddErrDays);
End;
End;
AddBuildDays := 0;
if not qMain.FieldByName('crt_date').IsNull then
AddBuildDays := AdditionDays(qMain.FieldByName('crt_date').AsDateTime);
if qMain.FieldByName('BuildDays').AsInteger+AddBuildDays<0
then Begin
if qMain.FieldByName('BuildDays').AsInteger+AddBuildDays<-1000
then vEmpty := vEmpty+qMain.FieldByName('id').AsString+',';
vBuildBlock := vBuildBlock +qMain.FieldByName('id').AsString+',';
vBuildBlockMessage := vBuildBlockMessage +#13#10+qMain.FieldByName('name').AsString;
End
else if (qMain.FieldByName('BuildDays').AsInteger in [0,1]) and
not (trunc(qMain.FieldByName('crt_date').AsDateTime) = qMain.FieldByName('today').AsDateTime)
then Begin
vBuildWarning := vBuildWarning +qMain.FieldByName('id').AsString+',';
vBuildWarningMessage := vBuildWarningMessage +#13#10+qMain.FieldByName('name').AsString;
End;
qMain.Next;
End;
qMain.Close;
Result :=true;
startlog(TranslateText(' статус успешно обновлён'));
Except on E:Exception do
begin
result := false;
ShowMessage(TranslateText('Ошибка при обновлении статуса проверок:')+#13#10+E.Message);
startlog(TranslateText(' ошибка при обновлении статуса проверок:')+#13#10+E.Message);
end;
End;
End;
function TCheckupStatus.TestTablesChecksum: Boolean;
var
N, I: Integer;
Str, ResStr, TablesList, Pwd, CalcPwd : String;
OraQuery: TOilQuery;
begin
{если у подразделения нет каротчек не проверять}
if not IsEmitent(StrToInt(ReadOilVar('INST')),True) or Debugging
then begin
Result := True;
Exit;
end;
Result := False;
TablesList := '';
Str :=
TranslateText('Системная ошибка.')+#13#10+
TranslateText('Продолжение работы не возможно. Обратитесь к разработчикам.')+#13#10+
TranslateText('Дополнительная информация:')+#13#10;
{проверить есть ли таблица с контрольными суммами для таблиц}
if GetSQLValue(
' select count(*) from all_tables '+
' where table_name=''OIL_CC'' and owner=user') = 0
then begin
ResStr := Str + ResStr +
TranslateText('[OIL_CC_NOTFOUND] Возможно не установлены все скрипты ');
MessageDlg(ResStr,mtError,[mbOk],0);
Exit;
end;
{проверить количество записей в контролируемых таблицах}
for I := 1 to length(Tables) do
begin
N := GetSQLValue('select count(*) from '+Tables[I][TABLE_NAME]+
' where inst='+ReadOilVar('INST') );
if N < StrToInt(Tables[I][MIN_COUNT])
then ResStr := ResStr + #13#10 + TranslateText('[CONTROL_TABLE_INCOMPLETE] Описание: ')+
Tables[I][TABLE_NAME]+', RCount: '+IntToStr(N) ;
end;
{проверить количество записей в таблице контрольных сумм}
for I := 1 to length(Tables) do
begin
N := GetSqlValue(
' select count(*) from oil_cc where '+
' upper(table_name)=Upper('''+Tables[I][TABLE_NAME]+''') '+
' and table_inst='+ReadOilVar('INST') );
if N = 0 then
ResStr := ResStr + #13#10 + TranslateText('[OIL_CC_INCOMPLETE] Описание: ')+
Tables[I][TABLE_NAME];
TablesList := TablesList +
''''+Tables[I][TABLE_NAME]+''''+IfThen(I <> length(Tables),',','');
end;
{проверить наличие полей в контролируемых таблицах}
if GetSqlValue(
' select count(*) from all_tab_columns '+
' where owner = user '+
' and lower(column_name) = ''row_checksum'' '+
' and table_name in ('+TablesList+') ' ) = 0 then
ResStr := ResStr + #13#10 +
TranslateText('[CS_FIELDS_NOTFOUND] Возможно не установлены все скрипты');
OraQuery := TOilQuery.Create(nil);
try
{проверить контрольные суммы для каждой записи в контролируемых таблицах}
for I := 1 to length(Tables) do
begin
if Tables[I][TABLE_ACTIVE] = 'N' then Continue;
OraQuery.SQL.Text :=
' select '+
' count(*) as c'+
' from '+
' ( '+
' select '+
' row_checksum as rc, '+
Tables[I][CHECKSUM] + ' as calc_rc '+
' from '+Tables[I][TABLE_NAME] + ' where inst='+ReadOilVar('INST') +
' ) where rc <> calc_rc ';
_OpenQueryParOra(OraQuery, ['Key',CHECKSUM_KEY,'Key1', ReadOilVar('INST')] );
if OraQuery.FieldByName('c').AsInteger > 0 then
ResStr := ResStr + #13#10 + TranslateText('[ROWS_CHECKSUM_NOT_MATCH] Описание: ')+
Tables[I][TABLE_NAME]+','+OraQuery.FieldByName('c').AsString;
end;
{проверить контрольные суммы для каждой контролируемой таблицы}
for I := 1 to length(Tables) do
begin
if Tables[I][TABLE_ACTIVE] = 'N' then Continue;
OraQuery.SQL.Text :=
' select rawtohex(oilt.Md5(count(*)||sum(id)||:Key||:Key1)) as cs '+' from '+
Tables[I][TABLE_NAME]+
' where inst ='+ReadOilVar('INST');
_OpenQueryParOra(OraQuery, ['Key',CHECKSUM_KEY,'Key1', ReadOilVar('INST')] );
if GetSqlValue(
'select checksum '+
'from oil_cc where table_inst = '+ReadOilVar('INST')+
' and table_name='''+Tables[I][TABLE_NAME]+'''') <> OraQuery.FieldbyName('CS').AsString
then ResStr := ResStr + #13#10 +
TranslateText('[TABLE_CHECKSUM_NOT_MATCH] Описание: ')+Tables[I][TABLE_NAME];
end;
{Добавить заголовок к тексту ошибок}
if ResStr <> '' then
ResStr := Str + ResStr;
{Если есть ошибки спросить пароль}
if ResStr <> '' then
if MessageDlgExt(ResStr,mtError,[TranslateText('Выйти'),TranslateText(' Ввести пароль ') ]) = 2 then
begin
{рассчетный пароль}
OraQuery.SQL.Text :=
'select rawtohex(oilt.Md5( :key || :key1 ||to_char(sysdate,''(rrrr)(mm)(dd)'')) ) as pwd from dual';
_OpenQueryParOra(OraQuery, ['Key',CHECKSUM_KEY,'Key1', ReadOilVar('INST')] );
CalcPwd := OraQuery.FieldByName('pwd').asString;
{если пароль правильный, обнулить строку с ошибками}
InputQuery(TranslateText('Пароль'), TranslateText('Введите пароль'), Pwd);
if Pwd = CalcPwd then
begin
ResStr := '';
StartSQL;
try
UpdateAllChecksums;
CommitSQL;
except on E: Exception do
begin
RollbackSQL;
ShowMessage('[UPDATE_CS_PWD]'+#13#10+E.Message);
end;
end;
end else ShowMessage(TranslateText('Неверный пароль'));
end;
Result := ResStr = '';
finally
FreeAndNil(OraQuery);
end;
end;
function TCheckupStatus.UpdateChecksum(TableName: String; SessionType: TSessionType): Boolean;
var
I, Id: Integer;
begin
{если у подразделения нет каротчек не проверять}
if not IsEmitent(StrToInt(ReadOilVar('INST')),True) or Debugging then
begin
Result := True;
Exit;
end;
Result := False;
Id := - 1;
for I:=1 to length(Tables) do
if AnsiUpperCase(Trim(TableName)) = AnsiUpperCase(Tables[I][TABLE_NAME]) then
Id := I;
if Id < 0 then Exit;
try
_ExecSQL('update '+ TableName +' set row_checksum = '+ Tables[Id][CHECKSUM] +
' where (row_checksum is null) or (row_checksum <> '+ Tables[Id][CHECKSUM] +')',
['Key', CHECKSUM_KEY,
'Key1', ReadOilVar('INST')]);
_ExecSQL(
' update oil_cc set checksum = '+
'(select rawtohex(oilt.Md5(count(*) || sum(id)|| :Key || :Key1)) from '+
Tables[Id][TABLE_NAME]+' where inst='+ ReadOilVar('INST') +')'+
' where table_inst = '+ReadOilVar('INST')+' and table_name = '''+TableName+'''',
['Key',CHECKSUM_KEY,'Key1', ReadOilVar('INST')]
);
except on e:Exception do
begin
ShowMessage('[UPDATE_CHECKSUM] '+E.Message);
raise;
end;
end;
end;
procedure TCheckupStatus.UpdateAllChecksums;
var
I: Integer;
begin
for I := 1 to Length(Tables) do
CheckupStatus.UpdateChecksum(Tables[I][TABLE_NAME],stBDE);
end;
initialization
CHECKSUM_KEY :=
chr(81)+chr(49)+chr(95)+chr(115)+chr(71)+chr(104)+chr(37)+chr(121)+
chr(42)+chr(106)+chr(34)+chr(54)+chr(55)+chr(35)+chr(100)+chr(78);
finalization
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
TIN (Triangular Irregular Network) vector file format implementation.
}
unit VXS.FileTIN;
interface
uses
System.Classes,
System.SysUtils,
VXS.VectorTypes,
VXS.VectorFileObjects,
VXS.ApplicationFileIO,
VXS.VectorGeometry,
VXS.Utils,
VXS.Types;
type
{ The TIN vector file (triangle irregular network).
It is a simple text format, with one triangle record per line, no materials,
no texturing (there may be more, but I never saw anything in this files).
This format is encountered in the DEM/DTED world and used in place of grids. }
TVXTINVectorFile = class(TVXVectorFile)
public
class function Capabilities: TVXDataFileCapabilities; override;
procedure LoadFromStream(aStream: TStream); override;
end;
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------
// ------------------ TVXTINVectorFile ------------------
// ------------------
class function TVXTINVectorFile.Capabilities: TVXDataFileCapabilities;
begin
Result := [dfcRead];
end;
procedure TVXTINVectorFile.LoadFromStream(aStream: TStream);
var
i, j: Integer;
sl, tl: TStringList;
mesh: TVXMeshObject;
v1, v2, v3, n: TAffineVector;
ActiveTin: Boolean;
Id_Tin: Integer;
Tnam: string;
Id_Mat, NVert, NTri: Integer;
VertArr: TxPoint3DArray;
n1, n2, n3: Integer;
begin
sl := TStringList.Create;
tl := TStringList.Create;
try
sl.LoadFromStream(aStream);
mesh := TVXMeshObject.CreateOwned(Owner.MeshObjects);
mesh.Mode := momTriangles;
if sl[0] <> 'TIN' then
// the file with single TIN described by vertices only
begin
for i := 0 to sl.Count - 1 do
begin
tl.CommaText := Copy(sl[i], 0, MaxInt);
Trim(tl.CommaText);
if tl.Count = 9 then
begin
SetVector(v1, VXS.Utils.StrToFloatDef(tl[0], 0),
VXS.Utils.StrToFloatDef(tl[1], 0),
VXS.Utils.StrToFloatDef(tl[2], 0));
SetVector(v2, VXS.Utils.StrToFloatDef(tl[3], 0),
VXS.Utils.StrToFloatDef(tl[4], 0),
VXS.Utils.StrToFloatDef(tl[5], 0));
SetVector(v3, VXS.Utils.StrToFloatDef(tl[6], 0),
VXS.Utils.StrToFloatDef(tl[7], 0),
VXS.Utils.StrToFloatDef(tl[8], 0));
mesh.Vertices.Add(v1, v2, v3);
n := CalcPlaneNormal(v1, v2, v3);
mesh.Normals.Add(n, n, n);
end;
end
end
else // the file with multiple TINs described by triangles and materials
while i < sl.Count - 1 do
begin
Inc(i);
tl.DelimitedText := sl[i];
if (tl.CommaText = 'BEGT') then // the beginning of new tin
begin
repeat
Inc(i);
tl.DelimitedText := sl[i];
if (tl[0] = 'ACTIVETIN') then
ActiveTin := True;
if (tl[0] = 'ID') then
Id_Tin := StrToInt(tl[1]);
if (tl[0] = 'TNAM') then
Tnam := tl[1];
if (tl[0] = 'MAT') then
Id_Mat := StrToInt(tl[1]);
if (tl[0] = 'VERT') then
NVert := StrToInt(tl[1]);
until tl[0] = 'VERT';
SetLength(VertArr, NVert);
j := 0;
repeat
Inc(i);
tl.DelimitedText := sl[i];
VertArr[j].X := StrToFloat(tl[0]);
VertArr[j].Y := StrToFloat(tl[1]);
VertArr[j].Z := StrToFloat(tl[2]);
Inc(j);
until (j = NVert);
Inc(i);
tl.DelimitedText := sl[i];
NTri := StrToInt(tl[1]);
j := 0;
repeat
Inc(i);
Inc(j);
tl.DelimitedText := sl[i];
n1 := StrToInt(tl[0]);
n2 := StrToInt(tl[1]);
n3 := StrToInt(tl[2]);
SetVector(v1, VertArr[n1 - 1].X, VertArr[n1 - 1].Y,
VertArr[n1 - 1].Z);
SetVector(v2, VertArr[n2 - 1].X, VertArr[n2 - 1].Y,
VertArr[n2 - 1].Z);
SetVector(v3, VertArr[n3 - 1].X, VertArr[n3 - 1].Y,
VertArr[n3 - 1].Z);
mesh.Vertices.Add(v1, v2, v3);
n := CalcPlaneNormal(v1, v2, v3);
mesh.Normals.Add(n, n, n);
until (j = NTri);
Inc(i);
tl.DelimitedText := sl[i]; // tl.DelimitedText = 'ENDT';
end;
end;
finally
tl.Free;
sl.Free;
end;
end;
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
RegisterVectorFileFormat('tin', 'Triangular Irregular Network',
TVXTINVectorFile);
end.
|
unit uLinkListEditorForExecutables;
interface
uses
Generics.Collections,
Winapi.Windows,
System.SysUtils,
System.Classes,
Vcl.Controls,
Vcl.StdCtrls,
Vcl.ExtCtrls,
Dmitry.Utils.System,
Dmitry.Controls.WatermarkedEdit,
Dmitry.Controls.WebLink,
UnitDBFileDialogs,
UnitDBDeclare,
uMemory,
uVclHelpers,
uIconUtils,
uShellIntegration,
uTranslate,
uFormInterfaces,
uProgramStatInfo;
type
TExecutableInfo = class(TDataObject)
public
Title: string;
Path: string;
Icon: string;
Parameters: string;
SortOrder: Integer;
UseSubMenu: Boolean;
constructor Create(Title, Path, Icon, Parameters: string; UseSubMenu: Boolean; SortOrder: Integer);
function Clone: TDataObject; override;
procedure Assign(Source: TDataObject); override;
end;
TLinkListEditorForExecutables = class(TInterfacedObject, ILinkEditor)
private
FForm: IFormLinkItemEditorData;
procedure LoadIconForLink(Link: TWebLink; Path, Icon: string);
procedure OnPlaceIconClick(Sender: TObject);
procedure OnChangePlaceClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
function L(StringToTranslate: string): string;
public
procedure SetForm(Form: IFormLinkItemEditorData);
procedure CreateNewItem(Sender: ILinkItemSelectForm; var Data: TDataObject; Verb: string; Elements: TListElements);
procedure CreateEditorForItem(Sender: ILinkItemSelectForm; Data: TDataObject; EditorData: IFormLinkItemEditorData);
procedure UpdateItemFromEditor(Sender: ILinkItemSelectForm; Data: TDataObject; EditorData: IFormLinkItemEditorData);
procedure FillActions(Sender: ILinkItemSelectForm; AddActionProc: TAddActionProcedure);
function OnDelete(Sender: ILinkItemSelectForm; Data: TDataObject; Editor: TPanel): Boolean;
function OnApply(Sender: ILinkItemSelectForm): Boolean;
end;
implementation
const
CHANGE_EXEC_ICON = 1;
CHANGE_EXEC_CAPTION_EDIT = 2;
CHANGE_EXEC_CHANGE_PATH = 3;
CHANGE_EXEC_PATH = 4;
CHANGE_PEXEC_PARAMS_EDIT = 5;
CHANGE_PEXEC_PARAMS_LABEL = 6;
{ TExecutableInfo }
procedure TExecutableInfo.Assign(Source: TDataObject);
var
EI: TExecutableInfo;
begin
EI := Source as TExecutableInfo;
if EI <> nil then
begin
Title := EI.Title;
Path := EI.Path;
Icon := EI.Icon;
Parameters := EI.Parameters;
UseSubMenu := EI.UseSubMenu;
SortOrder := EI.SortOrder;
end;
end;
function TExecutableInfo.Clone: TDataObject;
begin
Result := TExecutableInfo.Create(Title, Path, Icon, Parameters, UseSubMenu, SortOrder);
end;
constructor TExecutableInfo.Create(Title, Path, Icon, Parameters: string; UseSubMenu: Boolean; SortOrder: Integer);
begin
Self.Title := Title;
Self.Path := Path;
Self.Icon := Icon;
Self.Parameters := Parameters;
Self.UseSubMenu := UseSubMenu;
Self.SortOrder := SortOrder;
end;
{ TLinkListEditorForExecutables }
procedure TLinkListEditorForExecutables.CreateEditorForItem(
Sender: ILinkItemSelectForm; Data: TDataObject; EditorData: IFormLinkItemEditorData);
var
EI: TExecutableInfo;
WlIcon: TWebLink;
WlChangeLocation: TWebLink;
WedCaption,
WedParameters: TWatermarkedEdit;
LbInfo,
LbParameters: TLabel;
Icon: HICON;
Editor: TPanel;
begin
Editor := EditorData.EditorPanel;
EI := TExecutableInfo(Data);
WlIcon := Editor.FindChildByTag<TWebLink>(CHANGE_EXEC_ICON);
WedCaption := Editor.FindChildByTag<TWatermarkedEdit>(CHANGE_EXEC_CAPTION_EDIT);
WlChangeLocation := Editor.FindChildByTag<TWebLink>(CHANGE_EXEC_CHANGE_PATH);
LbInfo := Editor.FindChildByTag<TLabel>(CHANGE_EXEC_PATH);
WedParameters := Editor.FindChildByTag<TWatermarkedEdit>(CHANGE_PEXEC_PARAMS_EDIT);
LbParameters := Editor.FindChildByTag<TLabel>(CHANGE_PEXEC_PARAMS_LABEL);
if WedCaption = nil then
begin
WedCaption := TWatermarkedEdit.Create(Editor);
WedCaption.Parent := Editor;
WedCaption.Tag := CHANGE_EXEC_CAPTION_EDIT;
WedCaption.Top := 8;
WedCaption.Left := 35;
WedCaption.Width := 200;
WedCaption.OnKeyDown := FormKeyDown;
end;
if WlIcon = nil then
begin
WlIcon := TWebLink.Create(Editor);
WlIcon.Parent := Editor;
WlIcon.Tag := CHANGE_EXEC_ICON;
WlIcon.Width := 16;
WlIcon.Height := 16;
WlIcon.Left := 8;
WlIcon.Top := 8 + WedCaption.Height div 2 - WlIcon.Height div 2;
WlIcon.OnClick := OnPlaceIconClick;
end;
if WlChangeLocation = nil then
begin
WlChangeLocation := TWebLink.Create(Editor);
WlChangeLocation.Parent := Editor;
WlChangeLocation.Tag := CHANGE_EXEC_CHANGE_PATH;
WlChangeLocation.Height := 26;
WlChangeLocation.Text := L('Change application');
WlChangeLocation.RefreshBuffer(True);
WlChangeLocation.Top := 8 + WedCaption.Height div 2 - WlChangeLocation.Height div 2;
WlChangeLocation.Left := 240;
WlChangeLocation.LoadFromResource('NAVIGATE');
WlChangeLocation.OnClick := OnChangePlaceClick;
end;
if LbInfo = nil then
begin
LbInfo := TLabel.Create(Editor);
LbInfo.Parent := Editor;
LbInfo.Tag := CHANGE_EXEC_PATH;
LbInfo.Left := 35;
LbInfo.Top := 35;
LbInfo.Width := 350;
LbInfo.AutoSize := False;
LbInfo.EllipsisPosition := epPathEllipsis;
end;
if WedParameters = nil then
begin
WedParameters := TWatermarkedEdit.Create(Editor);
WedParameters.Parent := Editor;
WedParameters.Tag := CHANGE_PEXEC_PARAMS_EDIT;
WedParameters.Top := 62;
WedParameters.Left := 35;
WedParameters.Width := 200;
WedParameters.OnKeyDown := FormKeyDown;
end;
if LbParameters = nil then
begin
LbParameters := TLabel.Create(Editor);
LbParameters.Parent := Editor;
LbParameters.Tag := CHANGE_PEXEC_PARAMS_LABEL;
LbParameters.Caption := L('Parameters');
LbParameters.Left := WedParameters.AfterRight(5);
LbParameters.Top := WedParameters.Top + WedParameters.Height div 2 - LbParameters.Height div 2;
end;
Icon := ExtractSmallIconByPath(EI.Icon);
try
WlIcon.LoadFromHIcon(Icon);
finally
DestroyIcon(Icon);
end;
WedCaption.Text := EI.Title;
LbInfo.Caption := EI.Path;
WedParameters.Text := EI.Parameters;
end;
procedure TLinkListEditorForExecutables.CreateNewItem(Sender: ILinkItemSelectForm;
var Data: TDataObject; Verb: string; Elements: TListElements);
var
Link: TWebLink;
Info: TLabel;
EI: TExecutableInfo;
OpenDialog: DBOpenDialog;
ExeInfo: TEXEVersionData;
begin
if Data = nil then
begin
OpenDialog := DBOpenDialog.Create;
try
OpenDialog.Filter := L('Applications (*.exe)|*.exe|All Files (*.*)|*.*');
OpenDialog.FilterIndex := 1;
if OpenDialog.Execute then
begin
ExeInfo := GetEXEVersionData(OpenDialog.FileName);
if ExeInfo.ProductName = '' then
ExeInfo.ProductName := ExtractFileName(OpenDialog.FileName);
Data := TExecutableInfo.Create(ExeInfo.ProductName, OpenDialog.FileName, OpenDialog.FileName + ',0', '%1', True, Sender.DataList.Count);
end;
finally
F(OpenDialog);
end;
Exit;
end;
EI := TExecutableInfo(Data);
Link := TWebLink(Elements[leWebLink]);
Info := TLabel(Elements[leInfoLabel]);
Link.Text := EI.Title;
Info.Caption := EI.Path;
Info.EllipsisPosition := epPathEllipsis;
LoadIconForLink(Link, EI.Path, EI.Icon);
end;
procedure TLinkListEditorForExecutables.FillActions(Sender: ILinkItemSelectForm;
AddActionProc: TAddActionProcedure);
begin
AddActionProc(['Create'],
procedure(Action: string; WebLink: TWebLink)
begin
WebLink.Text := TA('Add application', 'DBMenu');
WebLink.LoadFromResource('NEW');
end
);
end;
procedure TLinkListEditorForExecutables.FormKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if Key = VK_RETURN then
FForm.ApplyChanges;
end;
function TLinkListEditorForExecutables.L(StringToTranslate: string): string;
begin
Result := TA(StringToTranslate, 'DBMenu');
end;
procedure TLinkListEditorForExecutables.LoadIconForLink(Link: TWebLink; Path, Icon: string);
var
Ico: HIcon;
begin
if Icon <> '' then
Ico := ExtractSmallIconByPath(Icon)
else
Ico := ExtractAssociatedIconSafe(Path);
try
Link.LoadFromHIcon(Ico);
finally
DestroyIcon(Ico);
end;
end;
function TLinkListEditorForExecutables.OnApply(Sender: ILinkItemSelectForm): Boolean;
begin
ProgramStatistics.OpenWithLinksUsed;
Result := True;
end;
procedure TLinkListEditorForExecutables.OnChangePlaceClick(Sender: TObject);
var
EI: TExecutableInfo;
LbInfo: TLabel;
Editor: TPanel;
OpenDialog: DBOpenDialog;
begin
Editor := TPanel(TControl(Sender).Parent);
EI := TExecutableInfo(Editor.Tag);
OpenDialog := DBOpenDialog.Create;
try
OpenDialog.Filter := ('Programs (*.exe)|*.exe|All Files (*.*)|*.*');
OpenDialog.FilterIndex := 1;
if OpenDialog.Execute then
begin
LbInfo := Editor.FindChildByTag<TLabel>(CHANGE_EXEC_PATH);
LbInfo.Caption := OpenDialog.FileName;
EI.Path := OpenDialog.FileName;
end;
finally
F(OpenDialog);
end;
end;
function TLinkListEditorForExecutables.OnDelete(Sender: ILinkItemSelectForm;
Data: TDataObject; Editor: TPanel): Boolean;
begin
Result := True;
end;
procedure TLinkListEditorForExecutables.OnPlaceIconClick(Sender: TObject);
var
EI: TExecutableInfo;
Icon: string;
Editor: TPanel;
WlIcon: TWebLink;
begin
Editor := TPanel(TControl(Sender).Parent);
EI := TExecutableInfo(Editor.Tag);
Icon := EI.Icon;
if ChangeIconDialog(0, Icon) then
begin
EI.Icon := Icon;
WlIcon := Editor.FindChildByTag<TWebLink>(CHANGE_EXEC_ICON);
LoadIconForLink(WlIcon, EI.Path, EI.Icon);
end;
end;
procedure TLinkListEditorForExecutables.SetForm(Form: IFormLinkItemEditorData);
begin
FForm := Form;
end;
procedure TLinkListEditorForExecutables.UpdateItemFromEditor(
Sender: ILinkItemSelectForm; Data: TDataObject; EditorData: IFormLinkItemEditorData);
var
EI: TExecutableInfo;
WedCaption,
WedParameters: TWatermarkedEdit;
Editor: TPanel;
begin
Editor := EditorData.EditorPanel;
EI := TExecutableInfo(Data);
WedCaption := Editor.FindChildByTag<TWatermarkedEdit>(CHANGE_EXEC_CAPTION_EDIT);
WedParameters := Editor.FindChildByTag<TWatermarkedEdit>(CHANGE_PEXEC_PARAMS_EDIT);
EI.Assign(EditorData.EditorData);
EI.Title := WedCaption.Text;
EI.Parameters := WedParameters.Text;
end;
end.
|
unit SafariPasswordRecovery;
interface
uses
StrUtils,Windows,
Classes,
CryptAPI;
Function GetSafariPasswords(Delimitador: string): string;
function AnsiGetShellFolder(CSIDL: integer): String;
implementation
const
AppleKey: Array[0..15] of Byte =($63,$6f,$6d,$2e,$61,$70,$70,$6c,$65,$2e,$53,$61,
$66,$61,$72,$69);
NewAppleKey: array[0..143] of Byte = (
$1D, $AC, $A8, $F8, $D3, $B8, $48, $3E, $48, $7D, $3E, $0A, $62, $07, $DD,
$26, $E6, $67, $81, $03, $E7, $B2, $13, $A5, $B0, $79, $EE, $4F, $0F, $41,
$15, $ED, $7B, $14, $8C, $E5, $4B, $46, $0D, $C1, $8E, $FE, $D6, $E7, $27,
$75, $06, $8B, $49, $00, $DC, $0F, $30, $A0, $9E, $FD, $09, $85, $F1, $C8,
$AA, $75, $C1, $08, $05, $79, $01, $E2, $97, $D8, $AF, $80, $38, $60, $0B,
$71, $0E, $68, $53, $77, $2F, $0F, $61, $F6, $1D, $8E, $8F, $5C, $B2, $3D,
$21, $74, $40, $4B, $B5, $06, $6E, $AB, $7A, $BD, $8B, $A9, $7E, $32, $8F,
$6E, $06, $24, $D9, $29, $A4, $A5, $BE, $26, $23, $FD, $EE, $F1, $4C, $0F,
$74, $5E, $58, $FB, $91, $74, $EF, $91, $63, $6F, $6D, $2E, $61, $70, $70,
$6C, $65, $2E, $53, $61, $66, $61, $72, $69
);
type
PSHItemID = ^TSHItemID;
{$EXTERNALSYM _SHITEMID}
_SHITEMID = record
cb: Word; { Size of the ID (including cb itself) }
abID: array[0..0] of Byte; { The item ID (variable length) }
end;
TSHItemID = _SHITEMID;
{$EXTERNALSYM SHITEMID}
SHITEMID = _SHITEMID;
PItemIDList = ^TItemIDList;
{$EXTERNALSYM _ITEMIDLIST}
_ITEMIDLIST = record
mkid: TSHItemID;
end;
TItemIDList = _ITEMIDLIST;
{$EXTERNALSYM ITEMIDLIST}
ITEMIDLIST = _ITEMIDLIST;
type
IMalloc = interface(IUnknown)
['{00000002-0000-0000-C000-000000000046}']
function Alloc(cb: Longint): Pointer; stdcall;
function Realloc(pv: Pointer; cb: Longint): Pointer; stdcall;
procedure Free(pv: Pointer); stdcall;
function GetSize(pv: Pointer): Longint; stdcall;
function DidAlloc(pv: Pointer): Integer; stdcall;
procedure HeapMinimize; stdcall;
end;
function Succeeded(Res: HResult): Boolean;
begin
Result := Res and $80000000 = 0;
end;
function SHGetMalloc(out ppMalloc: IMalloc): HResult; stdcall; external 'shell32.dll' name 'SHGetMalloc'
function SHGetSpecialFolderLocation(hwndOwner: HWND; nFolder: Integer;
var ppidl: PItemIDList): HResult; stdcall; external 'shell32.dll' name 'SHGetSpecialFolderLocation';
function SHGetPathFromIDList(pidl: PItemIDList; pszPath: PChar): BOOL; stdcall; external 'shell32.dll' name 'SHGetPathFromIDListA';
function AnsiGetShellFolder(CSIDL: integer): String;
var
pidl : PItemIdList;
FolderPath : array [0..260] of char;
SystemFolder : Integer;
Malloc : IMalloc;
begin
Malloc := nil;
ZeroMemory(@FolderPath, SizeOf(FolderPath));
SHGetMalloc(Malloc);
if Malloc = nil then
begin
Result := FolderPath;
Exit;
end;
try
SystemFolder := CSIDL;
if SUCCEEDED(SHGetSpecialFolderLocation(0, SystemFolder, pidl)) then
begin
if SHGetPathFromIDList(pidl, FolderPath) = false then ZeroMemory(@FolderPath, SizeOf(FolderPath));
end;
Result := FolderPath;
finally
Malloc.Free(pidl);
end;
end;
type
LongRec = packed record
case Integer of
0: (Lo, Hi: Word);
1: (Words: array [0..1] of Word);
2: (Bytes: array [0..3] of Byte);
end;
function FileAge(const FileName: string): Integer;
var
Handle: THandle;
FindData: TWin32FindData;
LocalFileTime: TFileTime;
begin
Handle := FindFirstFile(PChar(FileName), FindData);
if Handle <> INVALID_HANDLE_VALUE then
begin
Windows.FindClose(Handle);
if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then
begin
FileTimeToLocalFileTime(FindData.ftLastWriteTime, LocalFileTime);
if FileTimeToDosDateTime(LocalFileTime, LongRec(Result).Hi,
LongRec(Result).Lo) then Exit;
end;
end;
Result := -1;
end;
function FileExists(const FileName: string): Boolean;
begin
Result := FileAge(FileName) <> -1;
end;
function AnsiUpperCase(S: String): String;
var
i: Integer;
begin
for i := 1 to Length(S) do
S[i] := char(CharUpper(PChar(S[i])));
Result := S;
end;
function AnsiLowerCase(S: String): String;
var
i: Integer;
begin
for i := 1 to Length(S) do
S[i] := char(CharLower(PChar(S[i])));
Result := S;
end;
function AnsiCompareStr(const S1, S2: string): Integer;
begin
Result := CompareString(LOCALE_USER_DEFAULT, 0, PChar(S1), Length(S1),
PChar(S2), Length(S2)) - 2;
end;
function AnsiCompareText(const S1, S2: string): Integer;
begin
Result := CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE, PChar(S1),
Length(S1), PChar(S2), Length(S2)) - 2;
end;
function IntToHex(dwNumber: DWORD; Len: Integer): String;
const
HexNumbers:Array [0..15] of Char = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F');
begin
Result := '';
while dwNumber <> 0 do
begin
Result := HexNumbers[Abs(dwNumber mod 16)] + Result;
dwNumber := dwNumber div 16;
end;
if Result = '' then
begin
while Length(Result) < Len do
Result := '0' + Result;
Exit;
end;
if Result[Length(Result)] = '-' then
begin
Delete(Result, Length(Result), 1);
Insert('-', Result, 1);
end;
while Length(Result) < Len do
Result := '0' + Result;
end;
function MemPos(const Filename, TextToFind: string; var FoundPosition:int64;
iFrom: cardinal = 0; CaseSensitive: boolean = False): int64;
var
buffer : string;
len : integer;
MS : TMemoryStream;
charsA, charsB : set of char;
p, pEnd : PChar;
begin
result := -1;
FoundPosition:= -1;
if (TextToFind <> '') and FileExists(pChar(Filename)) then
begin
len := Length(TextToFind);
SetLength(buffer, len);
if CaseSensitive then
begin
charsA := [TextToFind[1]];
charsB := [TextToFind[len]];
end else
begin
charsA := [ AnsiLowerCase(TextToFind)[1], AnsiUpperCase(TextToFind)[1] ];
charsB := [ AnsiLowerCase(TextToFind)[len], AnsiUpperCase(TextToFind)[len]];
end;
MS := TMemoryStream.Create;
try
MS.LoadFromFile(Filename);
if (len <= MS.Size) and (iFrom <= (MS.Size - len) + 1) then
begin
p := MS.Memory;
pEnd := p;
Inc(p, iFrom);
Inc(pEnd, (MS.Size - len) + 1);
while (p <= pEnd) and (result < 0) do
begin
if (p^ in charsA) and ((p +len -1)^ in charsB) then
begin
MoveMemory(@buffer[1], p, len);
if (CaseSensitive and (AnsiCompareStr(TextToFind, buffer) = 0)) or
(AnsiCompareText(TextToFind, buffer) = 0) then
begin
result := p -MS.Memory;
FoundPosition:= p-MS.Memory;
end;
end;
Inc(p);
end;
end;
finally
MS.Free;
end;
end;
end;
Function GetSafariUserData(KeyChainPath:string; StartFrom:Cardinal):string;
var
MS: TMemoryStream;
iPos: int64;
iPos1: int64; //Für die Klammer zu
HArr: Array of Byte;
i: cardinal;
Size: byte;
begin
result:='';
MS := TMemoryStream.Create;
MS.LoadFromFile(KeyChainPath);
StartFrom := StartFrom - 200;
MemPos(KeyChainPath, #$12 + #$6D + #$72 + #$6F, iPos,StartFrom);
iPos := iPos+Length('mrof') + 1;
MemPos(KeyChainPath,#$5F + #$10,iPos1,iPos);
if ((iPos<>-1) and (iPos1<>-1)) then
begin
MS.Position:=iPos1+2;
MS.Read(Size,1);
SetLength(HArr,Size+1);
MS.Read(HArr[0],(Size));
for i := 0 to High(HArr) do
begin
if ((HArr[i]<33) or (HArr[i]>126)) then else
Result:=Result+chr(HArr[i]);
end;
end else
begin
MS.Free;
Result := '';
end;
end;
//Safari-Mainfunktion
Function GetSafariLoginData(KeyChainPath, CFNDLLPath: string; Delimitador: string):String;
var
DBin, DBOut, pOpt:Data_Blob;
s: string;
HArr: Array of Byte;
i: integer;
sHex: string;
P: PByte;
MS: TMemoryStream;
MS2: TMemoryStream;
MSKey: TMemoryStream;
MSOpt: TMemoryStream;
res: longbool;
str: PLPWSTR;
CFNPos: Int64;
iPos: Int64;
Ende: boolean;
Size: integer;
begin
Ende := False;
MS := TMemoryStream.Create;
MS2 := TMemoryStream.Create;
MSKey := TMemoryStream.Create;
MSOpt := TMemoryStream.Create;
iPos := 0;
CFNPos := 0;
MS.LoadFromFile(KeyChainPath);
MS.Position := 0;
if CFNDLLPath <> '' then
begin
MS2.LoadFromFile(CFNDLLPath);
MS2.Position := 0;
CFNPos := MemPos(CFNDLLPath, #$41 + #$56 + #$55 + #$52 + #$4C + #$50 + #$72 + #$6F + #$74 + #$6F + #$63 + #$6F + #$6C + #$5F + #$43 + #$6C + #$61 + #$73 + #$73 + #$69 + #$63, CFNPos);
if CFNPos <> -1 then
begin
CFNPos := CFNPos + Length('AVURLProtocol_Classic')+$25;
MS2.Position:=CFNPos;
MSOpt.CopyFrom(MS2,$80);
MSOpt.Write(AppleKey,High(AppleKey)+1);
end;
end else
MSOpt.Write(NewAppleKey,Length(NewAppleKey));
MSOpt.Position:=0;
while (MemPos(KeyChainPath, #01+#00+#00+#00, iPos, iPos) <>-1) and (not Ende) do begin
MS.Position:=iPos-1;
MS.Read(Size,2);
MS.Position:=MS.Position+1;
if ((iPos<>-1) and (iPos+Size<MS.Size) and (Size<>0) ) then
begin
Result := Result + GetSafariUserData(KeyChainPath, iPos) + Delimitador;
MS.Position:=iPos;
MSKey.CopyFrom(MS,Size); inc(iPos, Size);
MSKey.Position:=0;
DBOut.cbData := 0;
DBOut.pbData := nil;
DBIn.cbData := MSKey.Size;
pOpt.cbData:=MSOpt.Size;
GetMem(pOpt.pbData,pOpt.cbData);
GetMem(DBIn.pbData, DBIn.cbData);
DBIn.pbData:=MSKey.Memory;
pOpt.pbData:=MSOpt.Memory;
str:=nil;
res:= CryptUnprotectData(@DBIn,
@str,
@pOpt,
nil,
nil,
0,
@DBOut);
if res=true then
begin
P:=DBOut.pbData;
SetLength(HArr,0);
SetLength(HArr,DBOut.cbData);
for i:=0 to DBOut.cbData-1 do
begin
HArr[i]:=P^;
inc(P);
end;
s:='';
for i:=0 To High(HArr) do
begin
sHex:=IntToHex(HArr[i],1);
s:=s+chr(HArr[i]);
end;
s:='';
for i:=0 to High(HArr) do
begin
if ((HArr[i]<33) or (HArr[i]>126)) then else s:=s+chr(HArr[i]);
end;
Result := Result + s + Delimitador;
end else
begin
Result := Result + '-' + Delimitador;
end;
LocalFree(Cardinal(Pointer(DBOut.pbData)));
DBOut.pbData:=NIL;
end else Ende:=True;
end;
MS.Free;
MS2.Free;
MSKey.Free;
MSOpt.Free;
end;
Function TempGetSafariPasswords(Delimitador: string; Old: boolean): string;
var
i: integer;
s, Site, User, Pass, TempStr: string;
b: boolean;
Safari1, Safari2: AnsiString;
begin
Result := '';
b := false;
s := '';
if Old then
begin
Safari1 := AnsiGetShellFolder(26) + '\Apple Computer\Preferences\keychain.plist';
Safari2 := AnsiGetShellFolder(43) + '\Apple\Apple Application Support\CFNetwork.dll';
b := FileExists(Safari1) and FileExists(Safari2);
end else
begin
Safari1 := AnsiGetShellFolder(26) + '\Apple Computer\Preferences\keychain.plist';
Safari2 := '';
b := FileExists(Safari1);
end;
if b then
begin
s := GetSafariLoginData(Safari1, Safari2, Delimitador) + Delimitador;
while posex(Delimitador, s) > 0 do
begin
Result := Result + Copy(s, 1, posex(Delimitador, s) - 1) + Delimitador;
Delete(s, 1, posex(Delimitador, s) - 1);
Delete(s, 1, length(Delimitador));
end;
end else Result := ''{'Installation not found!'};
if Result = '' then exit;
TempStr := '';
if Result <> '' then
while posex('(', result) > 0 do
begin
site := 'http://' + Copy(Result, 1, posex('(', Result) - 1);
delete(result, 1, posex('(', Result));
User := Copy(Result, 1, posex(Delimitador, Result) - 2);
delete(result, 1, posex(Delimitador, Result) - 1);
delete(result, 1, Length(Delimitador));
Pass := Copy(Result, 1, posex(Delimitador, Result) - 1);
delete(result, 1, posex(Delimitador, Result) - 1);
delete(result, 1, Length(Delimitador));
TempStr := TempStr + Site + Delimitador +
User + Delimitador +
Pass + Delimitador + #13#10;
end;
Result := TempStr;
end;
function GetSafariPasswords(Delimitador: string): string;
begin
Result := TempGetSafariPasswords(Delimitador, False);
Result := Result + TempGetSafariPasswords(Delimitador, True);
end;
end.
|
function TPipeCommand_Screen.Compile( args: TStrArray ): string;
begin
exit(''); // no error
end;
procedure TPipeCommand_Screen.Run;
var i: integer = 0;
n: integer = 0;
begin
n := length( _input );
for i:=0 to n - 1 do begin
writeln( _input[i] );
end;
end;
procedure TPipeCommand_Screen.write_line( line: string );
begin
setLength( _input, length( _input ) + 1 );
_input[ length( _input ) - 1 ] := line;
end;
|
unit Nathan.JWT.Service;
interface
uses
System.SysUtils,
JOSE.Core.JWT,
JOSE.Core.Builder,
JOSE.Core.JWK;
{$M+}
type
INathanJwtWrapper = interface
['{5F32B159-838B-470D-9B1B-4E30FE664F52}']
function GetKey(): string;
function GetPayload(): string;
function GetJsonTokenHeader(): string;
function GetJsonTokenClaims(): string;
function GetVerified: Boolean;
procedure SetKey(const Value: string);
procedure SetPayload(const Value: string);
function CreatingAToken(): string;
function UnpackAndVerifyAToken(const MyToken: string): Boolean;
property Key: string read GetKey write SetKey;
property Payload: string read GetPayload write SetPayload;
property JsonTokenHeader: string read GetJsonTokenHeader;
property JsonTokenClaims: string read GetJsonTokenClaims;
property Verified: Boolean read GetVerified;
end;
TNathanJwtWrapper = class(TInterfacedObject, INathanJwtWrapper)
strict private
FKey: string;
FPayload: string;
FJsonTokenHeader: string;
FJsonTokenClaims: string;
FVerified: Boolean;
private
function GetKey(): string;
function GetPayload(): string;
function GetJsonTokenHeader(): string;
function GetJsonTokenClaims(): string;
function GetVerified(): Boolean;
procedure SetKey(const Value: string);
procedure SetPayload(const Value: string);
public
function CreatingAToken(): string;
function UnpackAndVerifyAToken(const MyToken: string): Boolean;
end;
{$M-}
implementation
{ TNathanJwtWrapper }
function TNathanJwtWrapper.GetKey(): string;
begin
Result := FKey;
end;
function TNathanJwtWrapper.GetPayload(): string;
begin
Result := FPayload;
end;
function TNathanJwtWrapper.GetJsonTokenHeader(): string;
begin
Result := FJsonTokenHeader;
end;
function TNathanJwtWrapper.GetJsonTokenClaims(): string;
begin
Result := FJsonTokenClaims;
end;
function TNathanJwtWrapper.GetVerified(): Boolean;
begin
Result := FVerified;
end;
procedure TNathanJwtWrapper.SetKey(const Value: string);
begin
FKey := Value;
end;
procedure TNathanJwtWrapper.SetPayload(const Value: string);
begin
FPayload := Value;
end;
function TNathanJwtWrapper.CreatingAToken(): string;
var
LToken: TJWT;
begin
LToken := TJWT.Create;
try
// Token claims...
LToken.Claims.IssuedAt := Now;
LToken.Claims.Expiration := Now + 1;
// LToken.Claims.Issuer := 'WiRL REST Library';
LToken.Claims.Issuer := FPayload;
// Signing and Compact format creation...
Result := TJOSE.SHA256CompactToken('secret', LToken);
// Header and Claims JSON representation
// Result := Result + #13#10 + #13#10;
// Result := Result + LToken.Header.JSON.ToJSON + #13#10;
// Result := Result + LToken.Claims.JSON.ToJSON;
finally
LToken.Free;
end;
end;
function TNathanJwtWrapper.UnpackAndVerifyAToken(const MyToken: string): Boolean;
var
LKey: TJWK;
LToken: TJWT;
begin
FPayload := '';
FJsonTokenHeader := '';
FJsonTokenClaims := '';
LKey := TJWK.Create(FKey);
try
// Unpack and verify the token
LToken := TJOSE.Verify(LKey, MyToken);
if Assigned(LToken) then
begin
try
FVerified := LToken.Verified;
Result := FVerified;
if LToken.Claims.HasIssuer then
FPayload := LToken.Claims.Issuer;
FJsonTokenHeader := LToken.Header.JSON.ToJSON;
FJsonTokenClaims := LToken.Claims.JSON.ToJSON;
finally
LToken.Free;
end;
end
else
Result := False;
finally
LKey.Free;
end;
end;
end.
|
unit DSA.Hash.HashCode;
interface
uses
System.Classes,
System.SysUtils;
type
{ TStudent }
TStudent = class(TObject)
private
__grade: integer;
__cls: integer;
__firstName: string;
__lastName: string;
public
constructor Create(grade, cls: integer; firstName, lastName: string);
function GetHashCode: integer; override;
function Equals(Obj: TObject): boolean; override;
end;
procedure Main;
implementation
procedure Main;
var
a: integer;
c: double;
d: string;
student1, student2: TStudent;
begin
a := 42;
Writeln((a.ToString.GetHashCode and $7FFFFFFF));
Writeln((a.ToString.GetHashCode));
a := -42;
Writeln(a.ToString.GetHashCode);
c := 3.1415926;
Writeln(c.ToString.GetHashCode);
d := 'imooc';
Writeln(d.GetHashCode);
student1 := TStudent.Create(3, 2, '振勇', '任');
Writeln(student1.GetHashCode);
student2 := TStudent.Create(3, 2, '振勇', '任');
Writeln(student2.GetHashCode);
Writeln(student1.Equals(student2));
end;
{ TStudent }
constructor TStudent.Create(grade, cls: integer; firstName, lastName: string);
begin
__grade := grade;
__cls := cls;
__firstName := firstName;
__lastName := lastName;
end;
function TStudent.Equals(Obj: TObject): boolean;
var
another: TStudent;
begin
if Self = Obj then
Exit(True);
if Obj = nil then
Exit(False);
if ClassType <> Obj.ClassType then
Exit(False);
another := Obj as TStudent;
Result := (__grade = another.__grade) and (__cls = another.__cls) and
(__firstName.ToLower.Equals(another.__firstName.ToLower)) and
(__lastName.ToLower.Equals(another.__lastName.ToLower));
end;
function TStudent.GetHashCode: integer;
var
B, vHash: integer;
begin
B := 31;
vHash := 0;
vHash := vHash * B + __grade;
vHash := vHash * B + __cls;
vHash := vHash * B + __firstName.ToLower.GetHashCode;
vHash := vHash * B + __lastName.ToLower.GetHashCode;
Result := vHash;
end;
end.
|
unit System_Memory;
{$mode objfpc} {$H+}
interface
uses
Classes, SysUtils;
type
{ TSystemMemory }
TSystemMemory = class(TObject)
private // Attribute
type
TByteArray = array of byte;
var
sysMem: TByteArray;
bootRom: TByteArray;
bootRomEnabled: boolean;
reloadOnEnable: boolean;
sysMemSize: DWord;
bootRomSize: DWord;
bootRomFileName: string;
bootRomLoaded: boolean;
protected // Attribute
public // Attribute
public // Konstruktor/Destruktor
constructor Create; overload;
destructor Destroy; override;
private // Methoden
protected // Methoden
public // Methoden
function Read(addr: DWord): byte;
procedure Write(addr: DWord; Data: byte);
procedure EnableBootRom(enable: boolean);
procedure setReloadImageOnEnable(reload: boolean);
function GetSystemMemorySize: DWord;
function GetBootRomSize: DWord;
function IsRomEnabled: boolean;
procedure SetRomImageFile(FileName: string);
procedure LoadRamFile(FileName: string);
procedure LoadRomFile;
procedure setBootRomSize(size: integer);
procedure setSystemRamSize(size: integer);
function isRomFileValid: boolean;
end;
var
SystemMemory: TSystemMemory;
implementation
uses System_Settings;
// --------------------------------------------------------------------------------
constructor TSystemMemory.Create;
begin
inherited Create;
setBootRomSize(SystemSettings.ReadInteger('Memory', 'RomSize', 0));
setSystemRamSize(SystemSettings.ReadInteger('Memory', 'RamSize', 0));
setReloadImageOnEnable(SystemSettings.ReadBoolean('Memory', 'ReloadOnEnable', False));
bootRomFileName := SystemSettings.ReadString('Memory', 'RomImageFile', '');
if ((bootRomFileName <> '') and (not FileExists(bootRomFileName))) then begin
SystemSettings.WriteString('Memory', 'RomImageFile', '');
bootRomFileName := '';
end;
LoadRomFile;
end;
// --------------------------------------------------------------------------------
destructor TSystemMemory.Destroy;
begin
inherited Destroy;
end;
// --------------------------------------------------------------------------------
function TSystemMemory.Read(addr: DWord): byte;
begin
if ((bootRomEnabled = True) and (addr < bootRomSize)) then begin
Result := bootRom[addr];
end
else if (addr < sysMemSize) then begin
Result := sysMem[addr];
end
else begin
Result := $FF;
end;
end;
// --------------------------------------------------------------------------------
procedure TSystemMemory.Write(addr: DWord; Data: byte);
begin
if (addr < sysMemSize) then begin
sysMem[addr] := Data;
end;
end;
// --------------------------------------------------------------------------------
procedure TSystemMemory.EnableBootRom(enable: boolean);
begin
bootRomEnabled := enable;
if (bootRomEnabled and reloadOnEnable) then begin
LoadRomFile;
end;
end;
// --------------------------------------------------------------------------------
procedure TSystemMemory.setReloadImageOnEnable(reload: boolean);
begin
reloadOnEnable := reload;
end;
// --------------------------------------------------------------------------------
function TSystemMemory.GetSystemMemorySize: DWord;
begin
Result := sysMemSize;
end;
// --------------------------------------------------------------------------------
function TSystemMemory.GetBootRomSize: DWord;
begin
Result := bootRomSize;
end;
// --------------------------------------------------------------------------------
function TSystemMemory.IsRomEnabled: boolean;
begin
Result := bootRomEnabled;
end;
// --------------------------------------------------------------------------------
procedure TSystemMemory.SetRomImageFile(FileName: string);
begin
bootRomFileName := FileName;
LoadRomFile;
end;
// --------------------------------------------------------------------------------
procedure TSystemMemory.LoadRomFile;
var
inFile: TFileStream;
addr: integer;
begin
bootRomEnabled := False;
bootRomLoaded := False;
if (bootRomFileName = '') then begin
for addr := 0 to bootRomSize - 1 do begin
bootRom[addr] := 0;
end;
end
else begin
inFile := TFileStream.Create(bootRomFileName, fmOpenRead);
inFile.Position := 0;
try
if (inFile.Size < bootRomSize) then begin
inFile.Read(bootRom[0], inFile.Size);
end
else begin
inFile.Read(bootRom[0], bootRomSize);
end;
bootRomEnabled := True;
bootRomLoaded := True;
finally
inFile.Free;
end;
end;
end;
// --------------------------------------------------------------------------------
procedure TSystemMemory.LoadRamFile(FileName: string);
var
inFile: TFileStream;
addr: integer;
begin
if (FileName = '') then begin
for addr := 0 to sysMemSize - 1 do begin
sysMem[addr] := 0;
end;
end
else begin
inFile := TFileStream.Create(FileName, fmOpenRead);
inFile.Position := 0;
try
if (inFile.Size < sysMemSize) then begin
inFile.Read(sysMem[0], inFile.Size);
end
else begin
inFile.Read(sysMem[0], sysMemSize);
end;
bootRomEnabled := False;
finally
inFile.Free;
end;
end;
end;
// --------------------------------------------------------------------------------
procedure TSystemMemory.setBootRomSize(size: integer);
var
newSize: DWord;
begin
case (size) of
0: newSize := $2000; // 8KB
1: newSize := $4000; // 16KB
2: newSize := $8000; // 32KB
3: newSize := $10000; // 64KB
else newSize := $2000;
end;
if (bootRomSize <> newSize) then begin
SetLength(bootRom, newSize);
bootRomSize := newSize;
end;
end;
// --------------------------------------------------------------------------------
procedure TSystemMemory.setSystemRamSize(size: integer);
var
newSize: DWord;
begin
case size of
0: newSize := $10000; // 64KB
1: newSize := $20000; // 128KB
2: newSize := $40000; // 256KB
3: newSize := $80000; // 512KB
4: newSize := $100000; // 1MB
else newSize := $10000;
end;
if (sysMemSize <> newSize) then begin
SetLength(sysMem, newSize);
sysMemSize := newSize;
end;
end;
// --------------------------------------------------------------------------------
function TSystemMemory.isRomFileValid: boolean;
begin
Result := bootRomLoaded;
end;
// --------------------------------------------------------------------------------
end.
|
PROGRAM testFunc;
VAR
a : BOOLEAN;
FUNCTION myfunc(a : INTEGER) : BOOLEAN;
BEGIN
if (a < 10) then myfunc := true else myfunc := false;
END;
BEGIN
a := myfunc(10);
END.
|
(*
-----------------------------------------------------------------------------------------------------
Version : (287 - 275)
Date : 11.17.2010
Author : Antonio Marcos Fernandes de Souza (amfsouza)
Issue : create a single routine to allow users insert inventory item
Solution: Changes on class TModel ( I added new attribute memnbers )
Version : (287 - 276)
-----------------------------------------------------------------------------------------------------
*)
unit uContentClasses;
interface
uses Classes;
type
TCategory = class
IDGroup: Variant;
TabGroup: String;
public
constructor Create();
end;
TModelGroup = class
IDModelGroup: Variant;
IDGroup: Variant;
ModelGroup: String;
public
constructor Create();
end;
TModelSubGroup = class
IDModelSubGroup: Variant;
IDModelGroup: Variant;
ModelSubGroup: String;
public
constructor Create();
end;
TVendorSuggestedList = class
IDVendor: Variant;
Vendor: String;
VendorCode: String;
MinQtyPO: Double;
CaseQty: Double;
VendorCost: Currency;
public
constructor Create();
end;
//Nao usar mais isse. Usar o TEntity
TVendor = class
IDVendor: Variant;
Vendor: String;
public
constructor Create();
end;
//Nao usar mais isse. Usar o TEntity
TManufacturer = class
IDManufacturer: Variant;
Manufacturer: String;
public
constructor Create();
end;
TState = class
IDState: String;
StateName: String;
end;
TEntity = class
IDPessoa : Variant;
IDTipoPessoa : Variant;
IDStore : Variant;
IDTipoPessoaRoot : Variant;
IDUSer : Variant;
Pessoa : String;
PessoaFirstName : String;
PessoaLastName : String;
ShortName : String;
NomeJuridico : String;
Endereco : String;
Cidade : String;
CEP : String;
Pais : String;
Telefone : String;
Cellular : String;
Fax : String;
Contato : String;
Email : String;
OBS : String;
Nascimento : TDateTime;
CPF : String;
CGC : String;
Identidade : String;
CartTrabalho : String;
InscEstadual : String;
InscMunicipal : String;
OrgaoEmissor : String;
Bairro : String;
CartMotorista : String;
Juridico : Boolean;
Code : String;
PhoneAreaCode : String;
CellAreaCode : String;
State : TState;
public
constructor Create();
destructor Destroy(); override;
end;
TVendorModelCode = class
IDVendorModelCode: Variant;
IDModel: Variant;
IDVendor: Variant;
VendorCode: String;
public
constructor Create();
end;
TInventory = class
IDInventory: Variant;
IDModel: Variant;
IDStore: Variant;
IDUser: Variant;
QtyOnHand: Double;
MinQty: Double;
MaxQty: Double;
UpdateQty: Boolean;
public
constructor Create();
end;
TInventorySerial = class
StoreID : Variant;
ModelID : Variant;
Serial : String;
public
constructor Create();
end;
TKitModel = class
IDModel: Variant;
SellingPrice: Currency;
Qty: Double;
MarginPerc: Double;
public
constructor Create();
end;
TModelVendor = class
IDModel: Variant;
IDVendor: Variant;
VendorOrder: Integer;
MinQtyPO: Double;
CaseQty: Double;
VendorCost: Double;
LastCostChange: TDateTime;
public
constructor Create();
end;
TPackModel = class
IDPackModel: Variant;
IDModel: Variant;
Qty: Double;
public
constructor Create();
end;
{ amsouza 11.17.2010 - these are not used in that class.
ES,
PVD,
PP,
TR,
AvgCost,
ReplacementCost,
FloatPercent,
DiscountPerc,
TotQtyOnHand,
Verify,
SendToTrash,
UpdatePrice,
UseScale,
ScaleValidDay,
UseLot,
IndicadorProducao,
IndicadorAT,
IDNCM,
WebDescription,
Portion,
}
TModel = class
IDModel: Variant;
IDUserLastSellingPrice: Variant;
IDSize: Variant;
IDColor: Variant;
IDUnit: Variant;
Model: String;
Description: String;
SellingPrice: Currency;
SuggRetail: Currency;
VendorCost: Currency;
Qty: Double;
CaseQty: Double;
Markup: Double;
ModelType: Char;
Verify: Boolean;
DateLastCost: TDateTime;
DateLastSellingPrice: TDateTime;
NotVerifyQty : Boolean;
Vendor: TVendor;
Category: TCategory;
Manufacturer: TManufacturer;
Inventory: TInventory;
VendorModelCode: TVendorModelCode;
ModelGroup: TModelGroup;
ModelSubGroup: TModelSubGroup;
ModelVendor: TModelVendor;
InventorySerial: TInventorySerial;
FSuggestedVendor : TStringList;
//amfsouza 11.17.2010 - adding member attributes
freightCost: double;
otherCost: double;
weight: double;
system: boolean;
desativado: boolean;
lastCost: double;
classABC: String;
automaticRequest: boolean;
promotionPrice: double;
customSalePrice: boolean;
askUserOnSale: boolean;
updatePrice: Integer;
public
constructor Create();
destructor Destroy(); override;
end;
TBarcode = class
IDBarcode: Variant;
BarcodeCase: Variant;
Model: TModel;
Qty: Double;
public
constructor Create();
destructor Destroy(); override;
end;
implementation
uses Variants, SysUtils;
{ TCategory }
constructor TCategory.Create;
begin
IDGroup := null;
end;
{ TBarcode }
constructor TBarcode.Create;
begin
IDBarcode := null;
end;
destructor TBarcode.Destroy;
begin
if Assigned(Model) then
FreeAndNil(Model);
inherited Destroy;
end;
{ TModelGroup }
constructor TModelGroup.Create;
begin
IDModelGroup := null;
end;
{ TModelSubGroup }
constructor TModelSubGroup.Create;
begin
IDModelSubGroup := null;
end;
{ TVendor }
constructor TVendor.Create;
begin
IDVendor := null;
end;
{ TManufacturer }
constructor TManufacturer.Create;
begin
IDManufacturer := null;
end;
{ TVendorModelCode }
constructor TVendorModelCode.Create;
begin
IDVendorModelCode := null;
end;
{ TInventory }
constructor TInventory.Create;
begin
IDInventory := null;
end;
{ TModel }
constructor TModel.Create;
begin
IDModel := null;
FSuggestedVendor := TStringList.Create;
end;
destructor TModel.Destroy;
var
obj : TObject;
begin
while FSuggestedVendor.Count > 0 do
begin
obj := FSuggestedVendor.Objects[0];
if (obj <> nil) then
FreeAndNil(obj);
FSuggestedVendor.Delete(0);
end;
FreeAndNil(FSuggestedVendor);
if Assigned(Vendor) then
FreeAndNil(Vendor);
if Assigned(Category) then
FreeAndNil(Category);
if Assigned(Manufacturer) then
FreeAndNil(Manufacturer);
if Assigned(Inventory) then
FreeAndNil(Inventory);
if Assigned(VendorModelCode) then
FreeAndNil(VendorModelCode);
if Assigned(ModelGroup) then
FreeAndNil(ModelGroup);
if Assigned(ModelSubGroup) then
FreeAndNil(ModelSubGroup);
if Assigned(ModelVendor) then
FreeAndNil(ModelVendor);
if Assigned(InventorySerial) then
FreeAndNil(InventorySerial);
inherited Destroy;
end;
{ TKitModel }
constructor TKitModel.Create;
begin
IDModel := null;
end;
{ TModelVendor }
constructor TModelVendor.Create;
begin
IDModel := null;
end;
{ TVendorSuggestedList }
constructor TVendorSuggestedList.Create;
begin
IDVendor := null;
end;
{ TInventorySerial }
constructor TInventorySerial.Create;
begin
StoreID := Null;
ModelID := Null;
end;
{ TPackModel }
constructor TPackModel.Create;
begin
IDPackModel := Null;
IDModel := Null;
end;
{ TEntity }
constructor TEntity.Create;
begin
IDPessoa := Null;
IDTipoPessoa := Null;
IDStore := Null;
IDTipoPessoaRoot := Null;
IDUSer := Null;
end;
destructor TEntity.Destroy;
begin
if Assigned(State) then
FreeAndNil(State);
inherited;
end;
end.
|
{$A+,B-,D+,E+,F-,G-,I+,L+,N-,O-,P-,Q-,R-,S+,T-,V+,X+,Y+}
{$M 16384,0,655360}
uses crt;
const
tfi = 'INTERIEW.INP';
tfo = 'INTERIEW.OUT';
maxN = 30;
maxM = 1500;
maxP = 60;
Unseen = maxN+maxM+1;
type
Alphabet = set of 'A'..'Z';
Mang1 = array[1..maxN,1..maxM] of byte;
var
fi,fo : text;
N,M : integer;
a : array[1..maxN,1..maxM] of byte;
count : integer;
ft : array[1..maxN] of integer;
fp : array[1..maxM] of integer;
fl : ^mang1;
Q : array[1..maxN+maxM] of integer;
qf,ql : integer;
Tr : array[1..maxN+maxM] of integer;
Lim : integer;
kt : integer;
mf : integer;
procedure InitQ;
begin
qf:=1;
ql:=1;
end;
procedure Put(u: integer);
begin
q[ql]:=u;
inc(ql);
end;
function Get: integer;
begin
Get:=q[qf];
inc(qf);
end;
function Qempty: boolean;
begin
Qempty:=(qf=ql);
end;
procedure Docdl;
var i,j: integer;
yc: array[1..maxN] of Alphabet;
kn: array[1..maxM] of Alphabet;
ch: char;
begin
assign(fi,tfi); reset(fi);
readln(fi,N);
for i:=1 to N do
begin
yc[i]:=[];
while not seekeoln(fi) do
begin
read(fi,ch);
yc[i]:=yc[i]+[ch];
end;
readln(fi);
end;
readln(fi,M);
for i:=1 to M do
begin
kn[i]:=[];
while not seekeoln(fi) do
begin
read(fi,ch);
kn[i]:=kn[i]+[ch];
end;
READLN(FI);
end;
close(fi);
for i:=1 to N do
for j:=1 to M do
if (yc[i] <= kn[j]) then a[i,j]:=1 else a[i,j]:=0;
end;
procedure InitFlow;
var i,j: integer;
begin
for i:=1 to N do ft[i]:=0;
for i:=1 to N do
for j:=1 to M do fl^[i,j]:=0;
for i:=1 to M do fp[i]:=0;
end;
procedure TimDuong(var ok: boolean);
var i,u,v: integer;
begin
ok:=true;
InitQ;
for i:=1 to N+M do Tr[i]:=0;
for i:=1 to N do
if Ft[i]<Lim then
begin
Put(i);
Tr[i]:=Unseen;
end;
while not Qempty do
begin
u:=Get;
if u<=N then {chi co cung xuoi}
begin
for v:=1 to M do
if (a[u,v]=1) and (fl^[u,v]=0) and (Tr[v+N]=0) then
begin
Put(v+N);
Tr[v+N]:=u;
end
end
else {ben phai}
begin
if fp[u-N]=0 then
begin
kt:=u;
exit;
end;
v:=fp[u-N];
if Tr[v]=0 then
begin
Put(v);
Tr[v]:=-u;
end;
end;
end;
ok:=false;
end;
procedure IncFlow;
var u,v: integer;
begin
v:=kt;
repeat
u:=Tr[v];
if u<0 then
begin
u:=-u;
Fl^[v,u-N]:=0;
Fp[u-N]:=0;
end
else if u<>Unseen then
begin
Fl^[u,v-N]:=1;
fp[v-N]:=u;
end;
v:=u;
until Tr[v]=Unseen;
ft[v]:=ft[v]+1;
end;
procedure MaxFlow;
var ok: boolean;
i: integer;
begin
InitFlow;
repeat
TimDuong(ok);
if ok then IncFlow;
until not ok;
mf:=0;
for i:=1 to N do
mf:=mf+ft[i];
end;
procedure FastFlow;
var dau,cuoi: longint;
begin
dau:=0;
cuoi:=maxP;
repeat
Lim:=(Dau+Cuoi) div 2;
MaxFlow;
if mf=count then cuoi:=lim else dau:=lim;
until cuoi=dau+1;
Lim:=cuoi;
MaxFlow;
end;
procedure Solve;
var i: integer;
begin
Lim:=maxP;
MaxFlow;
count:=mf;
FastFlow;
end;
procedure Inkq;
var dem,i,j: integer;
begin
dem:=0;
for i:=1 to N do
if ft[i]>0 then inc(dem);
assign(fo,tfo); rewrite(fo);
writeln(fo,dem);
for i:=1 to N do
if ft[i]>0 then
begin
write(fo,i,' ',ft[i],' ');
for j:=1 to M do
if fl^[i,j]=1 then write(fo,j,' ');
writeln(fo);
end;
close(fo);
end;
BEGIN
New(fl);
Docdl;
Solve;
Inkq;
dispose(fl);
END. |
//******************************************************************************
//**Форма добавления начала обучения студента
//**Последнее изменение 01.06.09 Перчак А.Л.
//******************************************************************************
unit Contracts_StudInf_AE;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit,
cxControls, cxGroupBox, cxDropDownEdit, cxCalendar, StdCtrls,
cxCurrencyEdit, cxLookAndFeelPainters, cxButtons,
cnConsts,cn_Common_Loader,cn_Common_Types, Ibase, cnConsts_Messages,
GlobalSpr, FIBQuery, pFIBQuery, pFIBStoredProc, DM, cn_Common_Messages,
DateUtils, DB, FIBDataSet, pFIBDataSet, AccMGMT, cn_Common_WaitForm,
ActnList, ShellAPI;
type
TfrmStudInf = class(TForm)
GroupBox_1: TcxGroupBox;
GroupBox_2: TcxGroupBox;
Faculty_Edit: TcxButtonEdit;
Spec_Edit: TcxButtonEdit;
Group_Edit: TcxButtonEdit;
FormStud_Edit: TcxButtonEdit;
CategoryStudy_Edit: TcxButtonEdit;
Nazional_Edit: TcxButtonEdit;
Faculty_Label: TLabel;
Spec_Label: TLabel;
Group_Label: TLabel;
FormStud_Label: TLabel;
CategoryStudy_Label: TLabel;
Nazional_Edit_Label: TLabel;
Kurs_Label: TLabel;
GroupBox_3: TcxGroupBox;
Summa_Label: TLabel;
Summa_Edit: TcxCurrencyEdit;
Date_Beg_Label: TLabel;
Date_Beg_DateEdit: TcxDateEdit;
Date_End_Label: TLabel;
Date_End_DateEdit: TcxDateEdit;
OkButton: TcxButton;
CancelButton: TcxButton;
Kurs_ComboBox: TcxComboBox;
AddFromPreyskurant_Btn: TcxButton;
DataSet_inf: TpFIBDataSet;
Term_stud_label: TLabel;
term_stud_ComboBox: TcxComboBox;
DataSet_term_stud: TpFIBDataSet;
ActionList1: TActionList;
Act_help: TAction;
DataSet_help: TpFIBDataSet;
procedure CancelButtonClick(Sender: TObject);
procedure OkButtonClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Faculty_EditKeyPress(Sender: TObject; var Key: Char);
procedure Spec_EditKeyPress(Sender: TObject; var Key: Char);
procedure Group_EditKeyPress(Sender: TObject; var Key: Char);
procedure FormStud_EditKeyPress(Sender: TObject; var Key: Char);
procedure CategoryStudy_EditKeyPress(Sender: TObject; var Key: Char);
procedure Nazional_EditKeyPress(Sender: TObject; var Key: Char);
procedure Kurs_ComboBoxKeyPress(Sender: TObject; var Key: Char);
procedure Date_Beg_DateEditKeyPress(Sender: TObject; var Key: Char);
procedure Date_End_DateEditKeyPress(Sender: TObject; var Key: Char);
procedure Summa_EditKeyPress(Sender: TObject; var Key: Char);
procedure Nazional_EditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure CategoryStudy_EditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure FormStud_EditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure Faculty_EditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure AddFromPreyskurant_BtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Kurs_ComboBoxPropertiesChange(Sender: TObject);
procedure SetSumm;
procedure term_stud_ComboBoxKeyPress(Sender: TObject; var Key: Char);
procedure term_stud_ComboBoxPropertiesChange(Sender: TObject);
procedure term_stud_ComboBoxPropertiesCloseUp(Sender: TObject);
procedure Date_Beg_DateEditPropertiesChange(Sender: TObject);
procedure Date_End_DateEditPropertiesChange(Sender: TObject);
procedure Act_helpExecute(Sender: TObject);
private
PLanguageIndex:byte; // индекс языка
DB_sp_Handle : TISC_DB_HANDLE;
ExRecord : Boolean;
procedure Clear_all_params;
procedure FormIniLanguage; // инициализация формы и контролов по языку
public
// идентификаторы справочников
ID_NATIONAL : int64; // гражданство
ID_FACULTY : int64; // факультет
ID_SPEC : int64; // специальность
ID_GROUP : int64; // группа
ID_FORMSTUD : int64; // форма обучения
ID_CATEGORYSTUD : int64; // категория обучения
ID_USER : int64;
ID_PRICE_PARAM : int64;
FinanceSource : TFinanceSource;
Summ1, Summ2, Summ3, Summ4,
Summ5, Summ6, Summ7, Summ8 : Double;
summ1_stage, summ2_stage, summ3_stage, summ4_stage,
summ5_stage, summ6_stage, summ7_stage, summ8_stage : Double;
term_stud1, term_stud2, term_stud3, term_stud4,
term_stud5, term_stud6, term_stud7, term_stud8 : Integer;
term_stud1_stage, term_stud2_stage, term_stud3_stage, term_stud4_stage,
term_stud5_stage, term_stud6_stage, term_stud7_stage, term_stud8_stage : Integer;
Date_beg_stud1, Date_beg_stud2, Date_beg_stud3, Date_beg_stud4, Date_beg_stud5, Date_beg_stud6, Date_beg_stud7, Date_beg_stud8,
Date_end_stud1, Date_end_stud2, Date_end_stud3, Date_end_stud4, Date_end_stud5, Date_end_stud6, Date_end_stud7, Date_end_stud8 : TDate;
Date_beg_stud1_stage, Date_beg_stud2_stage, Date_beg_stud3_stage, Date_beg_stud4_stage, Date_beg_stud5_stage, Date_beg_stud6_stage, Date_beg_stud7_stage, Date_beg_stud8_stage,
Date_end_stud1_stage, Date_end_stud2_stage, Date_end_stud3_stage, Date_end_stud4_stage, Date_end_stud5_stage, Date_end_stud6_stage, Date_end_stud7_stage, Date_end_stud8_stage : TDate;
kurs, kurs_beg, kurs_stage, kurs_beg_stage : Integer;
Get_budget : array of array[1..12] of variant;
is_admin, use_old_hist_price, change_stage_opl :Boolean;
Term_id_price_param : array of integer;
id_valute : int64;
procedure Id_Sp_Nullification(); // обнуление всех справочных идентификаторов
function GetSummaFromPreyskurant : boolean;
Function GetTermFromPrice : Boolean;
constructor Create(AOwner:TComponent; LanguageIndex : byte; DB_Handle:TISC_DB_HANDLE;is_admin:boolean);reintroduce;
end;
var
frmStudInf: TfrmStudInf;
implementation
uses Math;
{$R *.dfm}
constructor TfrmStudInf.Create(AOwner:TComponent; LanguageIndex : byte; DB_Handle:TISC_DB_HANDLE; is_admin:Boolean);
begin
Screen.Cursor:=crHourGlass;
inherited Create(AOwner);
Self.is_admin:=is_admin;
PLanguageIndex:= LanguageIndex;
DB_sp_Handle:= DB_Handle;
FormIniLanguage();
Screen.Cursor:=crDefault;
end;
//**обнуление всех справочных идентификаторов
procedure TfrmStudInf.Id_Sp_Nullification();
begin
ID_NATIONAL := -1;
ID_FACULTY := -1;
ID_SPEC := -1;
ID_GROUP := -1;
ID_FORMSTUD := -1;
ID_CATEGORYSTUD := -1;
end;
//**Инициализация надписей
procedure TfrmStudInf.FormIniLanguage;
begin
Faculty_Label.caption:= cnConsts.cn_footer_Faculty[PLanguageIndex];
Spec_Label.caption:= cnConsts.cn_footer_Spec[PLanguageIndex];
Group_Label.caption:= cnConsts.cn_footer_Group[PLanguageIndex];
FormStud_Label.caption:= cnConsts.cn_footer_FormStudy[PLanguageIndex];
CategoryStudy_Label.caption:= cnConsts.cn_footer_CategoryStudy[PLanguageIndex];
Nazional_Edit_Label.caption:= cnConsts.cn_Gragdanstvo[PLanguageIndex];
Kurs_Label.caption:= cnConsts.cn_footer_Kurs[PLanguageIndex];
Date_Beg_Label.caption:= cnConsts.cn_Date_Beg_Label[PLanguageIndex];
Date_End_Label.caption:= cnConsts.cn_Date_End_Label[PLanguageIndex];
Summa_Label.caption:= cnConsts.cn_Summa_Column[PLanguageIndex];
OkButton.Caption:= cnConsts.cn_Accept[PLanguageIndex];
CancelButton.Caption:= cnConsts.cn_Cancel[PLanguageIndex];
AddFromPreyskurant_Btn.Caption := cnConsts.cn_Preyskurant[PLanguageIndex];
AddFromPreyskurant_Btn.Hint:= cnConsts.cn_PreyskurantHint[PLanguageIndex];
Term_stud_label.Caption := 'Термін навчання'
end;
procedure TfrmStudInf.Clear_all_params;
begin
Summa_Edit.Value := 0;
ExRecord := false;
term_stud_ComboBox.Clear;
term_stud_ComboBox.ItemIndex := -1;
summ1 := 0;
summ2 := 0;
summ3 := 0;
summ4 := 0;
summ5 := 0;
term_stud1:=0;
term_stud2:=0;
term_stud3:=0;
term_stud4:=0;
term_stud5:=0;
Date_beg_stud1 := Date_Beg_DateEdit.EditValue;
Date_beg_stud2 := Date_Beg_DateEdit.EditValue;
Date_beg_stud3 := Date_Beg_DateEdit.EditValue;
Date_beg_stud4 := Date_Beg_DateEdit.EditValue;
Date_beg_stud5 := Date_Beg_DateEdit.EditValue;
Date_end_stud1 := Date_End_DateEdit.EditValue;
Date_end_stud2 := Date_End_DateEdit.EditValue;
Date_end_stud3 := Date_End_DateEdit.EditValue;
Date_end_stud4 := Date_End_DateEdit.EditValue;
Date_end_stud5 := Date_End_DateEdit.EditValue;
end;
//**Взятие сумм из прейскуранта в случае заполнения всех параметров обучения
function TfrmStudInf.GetSummaFromPreyskurant : boolean;
begin
ID_PRICE_PARAM := term_id_price_param[term_stud_ComboBox.ItemIndex];
//------------------------------------------------------------------------------
DataSet_inf.Close;
DataSet_inf.SQLs.SelectSQL.Clear;
DataSet_inf.SQLs.SelectSQL.Add('SELECT * FROM CN_DT_PRICE_SELECT_BY_PARAM(:id_price_param)');
DataSet_inf.ParamByName('id_price_param').AsInt64 := ID_PRICE_PARAM;
DataSet_inf.Open;
if DataSet_inf['KURS'] <> null then kurs_beg := DataSet_inf['KURS'];
if DataSet_inf['ID_VALUTE'] <> null then id_valute := DataSet_inf['ID_VALUTE'];
If DataSet_inf['Sum1'] <> null then Summ1 := DataSet_inf['sum1'] else summ1 := 0;
If DataSet_inf['Sum2'] <> null then Summ2 := DataSet_inf['sum2'] else summ2 := 0;
If DataSet_inf['Sum3'] <> null then Summ3 := DataSet_inf['sum3'] else summ3 := 0;
If DataSet_inf['Sum4'] <> null then Summ4 := DataSet_inf['sum4'] else summ4 := 0;
If DataSet_inf['Sum5'] <> null then Summ5 := DataSet_inf['sum5'] else summ5 := 0;
If DataSet_inf['term_stud1'] <> null then term_stud1:=DataSet_inf['term_stud1'] else term_stud1:=0;
If DataSet_inf['term_stud2'] <> null then term_stud2:=DataSet_inf['term_stud2'] else term_stud2:=0;
If DataSet_inf['term_stud3'] <> null then term_stud3:=DataSet_inf['term_stud3'] else term_stud3:=0;
If DataSet_inf['term_stud4'] <> null then term_stud4:=DataSet_inf['term_stud4'] else term_stud4:=0;
If DataSet_inf['term_stud5'] <> null then term_stud5:=DataSet_inf['term_stud5'] else term_stud5:=0;
If DataSet_inf['Date_beg1'] <> null then Date_beg_stud1 := DataSet_inf['Date_beg1'] else Date_beg_stud1 := Date_Beg_DateEdit.EditValue;
If DataSet_inf['Date_end1'] <> null then Date_end_stud1 := DataSet_inf['Date_end1'] else Date_end_stud1 := Date_End_DateEdit.EditValue;
If DataSet_inf['Date_beg2'] <> null then Date_beg_stud2 := DataSet_inf['Date_beg2'] else Date_beg_stud2 := Date_Beg_DateEdit.EditValue;
If DataSet_inf['Date_end2'] <> null then Date_end_stud2 := DataSet_inf['Date_end2'] else Date_end_stud2 := Date_End_DateEdit.EditValue;
If DataSet_inf['Date_beg3'] <> null then Date_beg_stud3 := DataSet_inf['Date_beg3'] else Date_beg_stud3 := Date_Beg_DateEdit.EditValue;
If DataSet_inf['Date_end3'] <> null then Date_end_stud3 := DataSet_inf['Date_end3'] else Date_end_stud3 := Date_End_DateEdit.EditValue;
If DataSet_inf['Date_beg4'] <> null then Date_beg_stud4 := DataSet_inf['Date_beg4'] else Date_beg_stud4 := Date_Beg_DateEdit.EditValue;
If DataSet_inf['Date_end4'] <> null then Date_end_stud4 := DataSet_inf['Date_end4'] else Date_end_stud4 := Date_End_DateEdit.EditValue;
If DataSet_inf['Date_beg5'] <> null then Date_beg_stud5 := DataSet_inf['Date_beg5'] else Date_beg_stud5 := Date_Beg_DateEdit.EditValue;
If DataSet_inf['Date_end5'] <> null then Date_end_stud5 := DataSet_inf['Date_end5'] else Date_end_stud5 := Date_End_DateEdit.EditValue;
SetSumm;
FinanceSource.isEmpty := False;
Result := true;
end;
//**Взятие срока обучения из прейскуранта в случае заполнения всех параметров обучения
function TfrmStudInf.GetTermFromPrice: boolean;
var
i : integer;
Year, month, day : Word;
Date_beg_price, Date_end_price : TDate;
Date_beg, Date_end : TDate;
begin
If not Is_Admin then
If fibCheckPermission('/ROOT/Contracts/Cn_stage_opl','Add') <> 0
then
Begin
messagebox(handle,
pchar(cnConsts_Messages.cn_NotHaveRights[PLanguageIndex]
+#13+ cnConsts_Messages.cn_GoToAdmin[PLanguageIndex]),
pchar(cnConsts_Messages.cn_ActionDenied[PLanguageIndex]), MB_ICONWARNING or mb_Ok);
Result := False;
exit;
End;
// проверяю на заполнение всех конролов - если есть пустые - выход
if ((Date_Beg_DateEdit.Text = '') or
(Date_End_DateEdit.Text = '') or
(Spec_Edit.Text = '') or
(Group_Edit.Text = '') or
(FormStud_Edit.Text = '') or
(CategoryStudy_Edit.Text = '') or
(Nazional_Edit.Text = '') or
(Kurs_ComboBox.Text = ''))
then
Begin
Result := false;
exit;
End;
Clear_all_params;
{проверим наличие записи в прейскуранте с присланными
параметрами обучения в присланном периоде действия прейскуранта}
DataSet_term_stud.Close;
DataSet_term_stud.SQLs.SelectSQL.Clear;
DataSet_term_stud.SQLs.SelectSQL.Add('SELECT * FROM CN_GET_TERM_STUD_BY_PARAM(:id_facul,');
DataSet_term_stud.SQLs.SelectSQL.Add(':id_spec,');
DataSet_term_stud.SQLs.SelectSQL.Add(':id_form_stud,');
DataSet_term_stud.SQLs.SelectSQL.Add(':id_kat_stud,');
DataSet_term_stud.SQLs.SelectSQL.Add(':id_national) order by term_stud');
DataSet_term_stud.ParamByName('id_facul').AsInt64 := ID_FACULTY;
DataSet_term_stud.ParamByName('id_spec').AsInt64 := ID_SPEC;
DataSet_term_stud.ParamByName('id_form_stud').AsInt64 := ID_FORMSTUD;
DataSet_term_stud.ParamByName('id_kat_stud').AsInt64 := ID_CATEGORYSTUD;
DataSet_term_stud.ParamByName('id_national').AsInt64 := ID_NATIONAL;
DataSet_term_stud.Open;
DataSet_term_stud.FetchAll;
DataSet_term_stud.First;
term_stud_ComboBox.Properties.Items.Clear;
ExRecord := False;
if DataSet_term_stud.RecordCount <> 0 then
begin
SetLength(Term_id_price_param, DataSet_term_stud.RecordCount);
for i := 0 to DataSet_term_stud.RecordCount - 1 do Term_id_price_param[i] := -1;
i := 0;
while not DataSet_term_stud.Eof do
Begin
if DataSet_term_stud['Kurs'] <> null
then kurs_beg := DataSet_term_stud['Kurs']
else kurs_beg := 1;
Date_beg_price := Date_Beg_DateEdit.EditValue;
Date_end_price := Date_End_DateEdit.EditValue;
if use_old_hist_price then
Begin
DecodeDate(Date_Beg_DateEdit.EditValue, year, month, day);
Year := Year - (StrToInt(Kurs_ComboBox.Text) - kurs_beg);
Date_beg_price := EncodeDate(Year, month, day);
DecodeDate(Date_End_DateEdit.EditValue, year, month, day);
Year := Year - (StrToInt(Kurs_ComboBox.Text) - kurs_beg);
Date_end_price := EncodeDate(Year, month, day);
End;
Date_beg := DataSet_term_stud['Date_beg'];
Date_end := DataSet_term_stud['Date_end'];
if (((Date_beg_price >= Date_beg) and (Date_beg_price <= Date_end)) or
((Date_end_price >= Date_beg) and (Date_end_price <= Date_end)))
then
Begin
if DataSet_term_stud['term_stud'] <> null
then term_stud_ComboBox.Properties.Items.Add(IntToStr(DataSet_term_stud['term_stud'])+ ' (c ' + DateToStr(Date_beg) + ')');
if DataSet_term_stud['id_price_param'] <> null
then Term_id_price_param[i] := DataSet_term_stud['id_price_param'];
ExRecord := true;
i := i + 1;
end;
DataSet_term_stud.Next;
end;
if ExRecord then term_stud_ComboBox.ItemIndex := 0;
Result := true;
Exit;
End;
Result := false;
end;
procedure TfrmStudInf.CancelButtonClick(Sender: TObject);
begin
close;
end;
procedure TfrmStudInf.OkButtonClick(Sender: TObject);
var
i:integer;
begin
kurs:=Kurs_ComboBox.EditValue;
if Faculty_Edit.Text= '' then
begin
ShowMessage(cnConsts_Messages.cn_Faculty_Need[PLanguageIndex]);
Faculty_Edit.SetFocus;
exit;
end;
if Spec_Edit.Text= '' then
begin
ShowMessage(cnConsts_Messages.cn_Spec_Need[PLanguageIndex]);
Spec_Edit.SetFocus;
exit;
end;
if Group_Edit.Text= '' then
begin
ShowMessage(cnConsts_Messages.cn_Group_Need[PLanguageIndex]);
Group_Edit.SetFocus;
exit;
end;
if FormStud_Edit.Text= '' then
begin
ShowMessage(cnConsts_Messages.cn_FormStud_Need[PLanguageIndex]);
FormStud_Edit.SetFocus;
exit;
end;
if CategoryStudy_Edit.Text= '' then
begin
ShowMessage(cnConsts_Messages.cn_KatStud_Need[PLanguageIndex]);
CategoryStudy_Edit.SetFocus;
exit;
end;
if Nazional_Edit.Text= '' then
begin
ShowMessage(cnConsts_Messages.cn_National_Need[PLanguageIndex]);
Nazional_Edit.SetFocus;
exit;
end;
if Date_Beg_DateEdit.Text= '' then
begin
ShowMessage(cnConsts_Messages.cn_DateBeg_Need[PLanguageIndex]);
Date_Beg_DateEdit.SetFocus;
exit;
end;
if Date_End_DateEdit.Text= '' then
begin
ShowMessage(cnConsts_Messages.cn_DateEnd_Need[PLanguageIndex]);
Date_End_DateEdit.SetFocus;
exit;
end;
// проверка на период не более 12 месяцев
// проверяю ключик
DataSet_inf.Close;
DataSet_inf.SQLs.SelectSQL.Text := 'select CN_CHECK_PERIODS_STUDY_ON_12 from CN_PUB_SYS_DATA_GET_ALL';
DataSet_inf.Open;
If DataSet_inf['CN_CHECK_PERIODS_STUDY_ON_12']<> null then
If Bool(DataSet_inf['CN_CHECK_PERIODS_STUDY_ON_12']) then
If ((MonthsBetween(Date_Beg_DateEdit.Date, Date_End_DateEdit.Date)+1)> 12) then
begin
ShowMessage(cnConsts_Messages.cn_AcademicPeriodsCheck[PLanguageIndex]);
Date_End_DateEdit.SetFocus;
exit;
end;
DataSet_inf.Close;
If (Date_Beg_DateEdit.Date >= Date_End_DateEdit.Date) then
begin
ShowMessage(cnConsts_Messages.cn_Dates_Prohibition[PLanguageIndex]);
Date_End_DateEdit.SetFocus;
exit;
end;
Summa_Edit.Value := StrToCurr(Summa_Edit.Text);
if ((summ1+summ2+summ3+summ4+summ5+summ6+summ7+summ8=0)) then
Begin
summ1:=Summa_Edit.EditValue;
summ2:=Summa_Edit.EditValue;
summ3:=Summa_Edit.EditValue;
summ4:=Summa_Edit.EditValue;
summ5:=Summa_Edit.EditValue;
summ6:=Summa_Edit.EditValue;
summ7:=Summa_Edit.EditValue;
summ8:=Summa_Edit.EditValue;
End;
if {(summ1+summ2+summ3+summ4+summ5<>0) and}
(summ1_stage+summ2_stage+summ3_stage+summ4_stage+summ5_stage+summ6_stage+summ7_stage+summ8_stage<>0) then
Begin
i:= cn_Common_Messages.cnShowMessage(cnConsts.cn_Confirmation_Caption[PLanguageIndex], 'Змінити існуючу сумму на нову?', mtConfirmation, [mbYes, mbNo, mbCancel]);
If i=6 then ModalResult:= mrOk;
If i=7 then
Begin
summ1:=summ1_stage;
summ2:=summ2_stage;
summ3:=summ3_stage;
summ4:=summ4_stage;
summ5:=summ5_stage;
summ6:=summ6_stage;
summ7:=summ7_stage;
summ8:=summ8_stage;
term_stud1:=term_stud1_stage;
term_stud2:=term_stud2_stage;
term_stud3:=term_stud3_stage;
term_stud4:=term_stud4_stage;
term_stud5:=term_stud5_stage;
term_stud6:=term_stud6_stage;
term_stud7:=term_stud7_stage;
term_stud8:=term_stud8_stage;
Date_beg_stud1 := Date_beg_stud1_stage;
Date_end_stud1 := Date_end_stud1_stage;
Date_beg_stud2 := Date_beg_stud2_stage;
Date_end_stud2 := Date_end_stud2_stage;
Date_beg_stud3 := Date_beg_stud3_stage;
Date_end_stud3 := Date_end_stud3_stage;
Date_beg_stud4 := Date_beg_stud4_stage;
Date_end_stud4 := Date_end_stud4_stage;
Date_beg_stud5 := Date_beg_stud5_stage;
Date_end_stud5 := Date_end_stud5_stage;
Date_beg_stud6 := Date_beg_stud6_stage;
Date_end_stud6 := Date_end_stud6_stage;
Date_beg_stud7 := Date_beg_stud7_stage;
Date_end_stud7 := Date_end_stud7_stage;
Date_beg_stud8 := Date_beg_stud8_stage;
Date_end_stud8 := Date_end_stud8_stage;
kurs:=kurs_stage;
kurs_beg:=kurs_beg_stage;
change_stage_opl:=False;
ModalResult:= mrOk;
End;
End
else ModalResult:= mrOk;
end;
procedure TfrmStudInf.FormShow(Sender: TObject);
begin
if Date_Beg_DateEdit.Enabled
then Date_Beg_DateEdit.SetFocus
else Summa_Edit.SetFocus;
GetTermFromPrice;
end;
procedure TfrmStudInf.Faculty_EditKeyPress(Sender: TObject; var Key: Char);
begin
if key = #13 then Spec_Edit.SetFocus;
end;
procedure TfrmStudInf.Spec_EditKeyPress(Sender: TObject; var Key: Char);
begin
if key = #13 then Group_Edit.SetFocus;
end;
procedure TfrmStudInf.Group_EditKeyPress(Sender: TObject; var Key: Char);
begin
if key = #13 then FormStud_Edit.SetFocus;
end;
procedure TfrmStudInf.FormStud_EditKeyPress(Sender: TObject;
var Key: Char);
begin
if key = #13 then CategoryStudy_Edit.SetFocus;
end;
procedure TfrmStudInf.CategoryStudy_EditKeyPress(Sender: TObject;
var Key: Char);
begin
if key = #13 then Nazional_Edit.SetFocus;
end;
procedure TfrmStudInf.Nazional_EditKeyPress(Sender: TObject;
var Key: Char);
begin
if key = #13 then Kurs_ComboBox.SetFocus;
end;
procedure TfrmStudInf.Kurs_ComboBoxKeyPress(Sender: TObject;
var Key: Char);
begin
if key = #13 then term_stud_ComboBox.SetFocus;
end;
procedure TfrmStudInf.Date_Beg_DateEditKeyPress(Sender: TObject;
var Key: Char);
begin
if key = #13 then Date_End_DateEdit.SetFocus;
end;
procedure TfrmStudInf.Date_End_DateEditKeyPress(Sender: TObject;
var Key: Char);
begin
if key = #13 then Summa_Edit.SetFocus;
end;
procedure TfrmStudInf.Summa_EditKeyPress(Sender: TObject; var Key: Char);
begin
if key = #13 then Faculty_Edit.SetFocus;
end;
procedure TfrmStudInf.Nazional_EditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
AParameter:TcnSimpleParams;
res: Variant;
begin
AParameter:= TcnSimpleParams.Create;
AParameter.Owner:=self;
AParameter.Db_Handle:= DB_sp_Handle;
AParameter.Formstyle:=fsNormal;
if ID_NATIONAL <> -1 then
AParameter.ID_Locate := ID_NATIONAL;
res:=RunFunctionFromPackage(AParameter, 'Contracts\cn_sp_National.bpl','ShowSPNational');
AParameter.Free;
if VarArrayDimCount(res)>0 then
begin
ID_NATIONAL := res[0];
Nazional_Edit.Text:= vartostr(res[1]);
if GetTermFromPrice
then OkButton.SetFocus
else Kurs_ComboBox.SetFocus;
end;
end;
procedure TfrmStudInf.CategoryStudy_EditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
AParameter:TcnSimpleParams;
res: Variant;
begin
AParameter:= TcnSimpleParams.Create;
AParameter.Owner:=self;
AParameter.Db_Handle:= DB_sp_Handle;
AParameter.Formstyle:=fsNormal;
if ID_CATEGORYSTUD <> -1 then
AParameter.ID_Locate := ID_CATEGORYSTUD;
res := RunFunctionFromPackage(AParameter, 'Contracts\cn_sp_CategoryStudy.bpl','ShowSPCategoryStudy');
AParameter.Free;
if VarArrayDimCount(res)>0 then
begin
ID_CATEGORYSTUD := res[0];
CategoryStudy_Edit.Text:= vartostr(res[1]);
if GetTermFromPrice
then OkButton.SetFocus
else Nazional_Edit.SetFocus;
end;
end;
procedure TfrmStudInf.FormStud_EditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
AParameter:TcnSimpleParams;
res: Variant;
begin
AParameter:= TcnSimpleParams.Create;
AParameter.Owner:=self;
AParameter.Db_Handle := DB_sp_Handle;
AParameter.Formstyle := fsNormal;
if ID_FORMSTUD <> -1 then AParameter.ID_Locate := ID_FORMSTUD;
res:=RunFunctionFromPackage(AParameter, 'Contracts\cn_sp_FormStud.bpl','ShowSPFormStud');
AParameter.Free;
if VarArrayDimCount(res)>0 then
begin
ID_FORMSTUD := res[0];
FormStud_Edit.Text:= vartostr(res[1]);
If GetTermFromPrice
then OkButton.SetFocus
else CategoryStudy_Edit.SetFocus;
end;
end;
procedure TfrmStudInf.Faculty_EditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
AParameter:TcnSimpleParams;
res: Variant;
begin
AParameter:= TcnSimpleParams.Create;
AParameter.Owner:=self;
AParameter.Db_Handle:= DB_sp_Handle;
AParameter.Formstyle:=fsNormal;
if ID_FACULTY <> -1 then AParameter.ID_Locate := ID_FACULTY;
if ID_SPEC <> -1 then AParameter.ID_Locate_1 := ID_SPEC;
if ID_GROUP <> -1 then AParameter.ID_Locate_2 := ID_GROUP;
res:=RunFunctionFromPackage(AParameter, 'Contracts\cn_sp_FacultySpecGroup.bpl','ShowSPFacSpecGroup');
AParameter.Free;
if VarArrayDimCount(res)>0 then
begin
ID_FACULTY := res[0];
ID_SPEC := res[1];
ID_GROUP := res[2];
Faculty_Edit.Text:= vartostr(res[3]);
Spec_Edit.Text:= vartostr(res[4]);
Group_Edit.Text:= vartostr(res[5]);
if GetTermFromPrice
then OkButton.SetFocus
else FormStud_Edit.SetFocus;
end;
end;
//==Процедура обработки нажатия кнопки вызова прейскуранта, по техническим
//==соображаниям была отключена 29.05.2009г
procedure TfrmStudInf.AddFromPreyskurant_BtnClick(Sender: TObject);
var
Res:Variant;
AParameterPrice:TcnSimpleParams;
begin
If Date_Beg_DateEdit.Text= '' then
begin
ShowMessage(cnConsts_Messages.cn_DateBeg_Need[PLanguageIndex]);
Date_Beg_DateEdit.SetFocus;
exit;
end;
If Date_End_DateEdit.Text= '' then
begin
ShowMessage(cnConsts_Messages.cn_DateEnd_Need[PLanguageIndex]);
Date_End_DateEdit.SetFocus;
exit;
end;
// wf := ShowWaitForm(Self,wfLoadPackage);
// вызываю справочник Прейскурантов и заполняю переменные
AParameterPrice := TcnSimpleParams.Create;
AParameterPrice.Owner :=self;
AParameterPrice.Db_Handle := DB_sp_Handle;
AParameterPrice.Formstyle := fsNormal;
AParameterPrice.ID_User := ID_USER;
AParameterPrice.Date_beg := Date_Beg_DateEdit.EditValue;
AParameterPrice.Date_end := Date_End_DateEdit.EditValue;
AParameterPrice.WaitPakageOwner:=self;
Res:= RunFunctionFromPackage(AParameterPrice, 'Contracts\cn_prices_ex.bpl','ShowPricesByDate');
AParameterPrice.Free;
If (varArrayDimCount(Res)>0) then
begin
ID_FACULTY := Res[0];// -идентификатор факультета
ID_SPEC := Res[1];// -идентификатор специальности
ID_NATIONAL := Res[2];// -идентификатор гражданства
ID_FORMSTUD := Res[3];// -идентификатор формы обучения;
ID_CATEGORYSTUD := Res[4];// -идентификатор категории обучения;
Faculty_Edit.Text := vartostr(res[6]); // -наименование факультета
Spec_Edit.Text := vartostr(res[7]); // -наименование специальности
FormStud_Edit.Text := vartostr(res[9]); // -наименование формы обучения
CategoryStudy_Edit.Text := vartostr(res[10]); // -наименование категории обучения
Nazional_Edit.Text := vartostr(res[8]); // -наименование гражданства
if res[19] <> null
then id_valute := res[19] //идн. валюты;
else id_valute := -1;
case strtoint(Res[11]) of
1: frmStudInf.Kurs_ComboBox.ItemIndex := 0;
2: frmStudInf.Kurs_ComboBox.ItemIndex := 1;
3: frmStudInf.Kurs_ComboBox.ItemIndex := 2;
4: frmStudInf.Kurs_ComboBox.ItemIndex := 3;
5: frmStudInf.Kurs_ComboBox.ItemIndex := 4;
6: frmStudInf.Kurs_ComboBox.ItemIndex := 5;
end;
OkButton.SetFocus;
GetTermFromPrice;
end;
end;
procedure TfrmStudInf.FormCreate(Sender: TObject);
begin
// Kurs_ComboBox.Properties.OnChange := nil;
// term_stud_ComboBox.Properties.OnChange := nil;
FinanceSource.isEmpty := True;
Summ1 := 0;
Summ2 := 0;
Summ3 := 0;
Summ4 := 0;
Summ5 := 0;
Summ6 := 0;
Summ7 := 0;
Summ8 := 0;
Kurs_beg := 1;
Kurs_ComboBox.ItemIndex := 0;
end;
procedure TfrmStudInf.SetSumm;
begin
Case (Kurs_ComboBox.ItemIndex-Kurs_beg+2) of
1:Summa_Edit.Value := Summ1;
2:Summa_Edit.Value := Summ2;
3:Summa_Edit.Value := Summ3;
4:Summa_Edit.Value := Summ4;
5:Summa_Edit.Value := Summ5;
6:Summa_Edit.Value := Summ6;
7:Summa_Edit.Value := Summ7;
8:Summa_Edit.Value := Summ8;
End;
end;
procedure TfrmStudInf.Kurs_ComboBoxPropertiesChange(Sender: TObject);
begin
GetTermFromPrice;
end;
procedure TfrmStudInf.term_stud_ComboBoxKeyPress(Sender: TObject;
var Key: Char);
begin
if key = #13 then OkButton.SetFocus;
end;
procedure TfrmStudInf.term_stud_ComboBoxPropertiesChange(Sender: TObject);
begin
if ExRecord then GetSummaFromPreyskurant;
end;
procedure TfrmStudInf.term_stud_ComboBoxPropertiesCloseUp(Sender: TObject);
begin
if ExRecord then GetSummaFromPreyskurant;
end;
procedure TfrmStudInf.Date_Beg_DateEditPropertiesChange(Sender: TObject);
begin
GetTermFromPrice;
end;
procedure TfrmStudInf.Date_End_DateEditPropertiesChange(Sender: TObject);
begin
GetTermFromPrice;
end;
procedure TfrmStudInf.Act_helpExecute(Sender: TObject);
var
FileName : String;
FullName : PAnsiChar;
begin
DataSet_help.Close;
DataSet_help.SQLs.SelectSQL.Text := 'select * from pub_sp_help where name_object = :object and name_system = :system';
DataSet_help.ParamByName('object').AsString := 'study_param_ae';
DataSet_help.ParamByName('system').AsString := 'contracts';
DataSet_help.Open;
If DataSet_help.RecordCount = 0 then
begin
cnShowMessage('Help not found',
'Help not Found' + #13 + cnConsts_Messages.cn_GoToAdmin[PLanguageIndex],
mtError,
[mbOK]);
Exit;
end;
FileName := DataSet_help.FieldByName('NAME_FILE').AsString;
FullName := PChar(ExtractFilePath(Application.ExeName) + 'Help\Contracts\' + FileName);
if not FileExists(FullName) then
Begin
cnShowMessage('File not found',
FullName + #13 + cnConsts_Messages.cn_GoToAdmin[PLanguageIndex],
mtError,
[mbOK]);
Exit;
end;
ShellExecute(Handle, 'open', FullName, nil, nil, SW_SHOWNORMAL);
end;
end.
|
unit htDatabaseProfile;
interface
uses
LrProfiles;
type
ThtDatabaseVendor = ( dvMySQL, dvFireBird, dvInterbase5, dvInterbase6,
dvAccess, dvODBC, dvCustom );
//
ThtDatabaseProfile = class(TLrProfile)
private
FADODB: string;
FPassword: string;
FDatabaseFile: string;
FODBC: string;
FDatabase: string;
FUser: string;
FVendor: ThtDatabaseVendor;
FServerHost: string;
protected
procedure SetADODB(const Value: string);
procedure SetDatabase(const Value: string);
procedure SetDatabaseFile(const Value: string);
procedure SetODBC(const Value: string);
procedure SetPassword(const Value: string);
procedure SetServerHost(const Value: string);
procedure SetUser(const Value: string);
procedure SetVendor(const Value: ThtDatabaseVendor);
published
property ADODB: string read FADODB write SetADODB;
property Database: string read FDatabase write SetDatabase;
property DatabaseFile: string read FDatabaseFile write SetDatabaseFile;
property ODBC: string read FODBC write SetODBC;
property Password: string read FPassword write SetPassword;
property ServerHost: string read FServerHost write SetServerHost;
property User: string read FUser write SetUser;
property Vendor: ThtDatabaseVendor read FVendor write SetVendor;
end;
//
ThtDatabaseProfileMgr = class(TLrProfileMgr)
private
function GetDatabaseByName(const inName: string): ThtDatabaseProfile;
protected
function GetDatabases(inIndex: Integer): ThtDatabaseProfile;
procedure SetDatabases(inIndex: Integer; const Value: ThtDatabaseProfile);
public
constructor Create(const inFilename: string = ''); reintroduce;
function AddDatabase: ThtDatabaseProfile;
property Databases[inIndex: Integer]: ThtDatabaseProfile read GetDatabases
write SetDatabases; default;
property DatabaseByName[const inName: string]: ThtDatabaseProfile
read GetDatabaseByName;
end;
var
DatabaseProfileMgr: ThtDatabaseProfileMgr;
implementation
{ ThtDatabaseProfile }
procedure ThtDatabaseProfile.SetADODB(const Value: string);
begin
FADODB := Value;
end;
procedure ThtDatabaseProfile.SetDatabase(const Value: string);
begin
FDatabase := Value;
end;
procedure ThtDatabaseProfile.SetDatabaseFile(const Value: string);
begin
FDatabaseFile := Value;
end;
procedure ThtDatabaseProfile.SetODBC(const Value: string);
begin
FODBC := Value;
end;
procedure ThtDatabaseProfile.SetPassword(const Value: string);
begin
FPassword := Value;
end;
procedure ThtDatabaseProfile.SetServerHost(const Value: string);
begin
FServerHost := Value;
end;
procedure ThtDatabaseProfile.SetUser(const Value: string);
begin
FUser := Value;
end;
procedure ThtDatabaseProfile.SetVendor(const Value: ThtDatabaseVendor);
begin
FVendor := Value;
end;
{ ThtDatabaseProfileMgr }
constructor ThtDatabaseProfileMgr.Create(const inFilename: string);
begin
inherited Create(ThtDatabaseProfile, inFilename);
end;
function ThtDatabaseProfileMgr.GetDatabases(inIndex: Integer): ThtDatabaseProfile;
begin
Result := ThtDatabaseProfile(Profiles[inIndex]);
end;
procedure ThtDatabaseProfileMgr.SetDatabases(inIndex: Integer;
const Value: ThtDatabaseProfile);
begin
Profiles[inIndex] := Value;
end;
function ThtDatabaseProfileMgr.AddDatabase: ThtDatabaseProfile;
begin
Result := ThtDatabaseProfile(Profiles.Add);
end;
function ThtDatabaseProfileMgr.GetDatabaseByName(
const inName: string): ThtDatabaseProfile;
begin
Result := ThtDatabaseProfile(GetProfileByName(inName));
end;
end.
|
unit ufrmSO;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmMasterBrowse, cxGraphics,
cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxBarBuiltInMenu, cxStyles,
cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB,
cxDBData, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, Vcl.Menus,
System.Actions, Vcl.ActnList, ufraFooter4Button, Vcl.StdCtrls, cxButtons,
cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxLabel, cxGridLevel,
cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, cxPC, Vcl.ExtCtrls, uAppUtils,
uDXUtils, uDBUtils, Datasnap.DBClient, uDMClient, ufrmDialogSO, uInterface,
cxGroupBox, cxRadioGroup;
type
TfrmSO = class(TfrmMasterBrowse)
gbCetak: TcxGroupBox;
rbPrintDlg: TcxRadioGroup;
btnPrint: TcxButton;
procedure actAddExecute(Sender: TObject);
procedure actEditExecute(Sender: TObject);
procedure actPrintExecute(Sender: TObject);
procedure btnPrintClick(Sender: TObject);
private
FCDS: TClientDataSet;
procedure PrintDialog;
property CDS: TClientDataSet read FCDS write FCDS;
{ Private declarations }
protected
procedure RefreshData; override;
public
destructor Destroy; override;
{ Public declarations }
end;
var
frmSO: TfrmSO;
implementation
uses
System.DateUtils, uDMReport, uClientClasses;
{$R *.dfm}
destructor TfrmSO.Destroy;
begin
inherited;
// FreeAndNil(FCDS);
end;
procedure TfrmSO.actAddExecute(Sender: TObject);
begin
inherited;
ShowDialogForm(TfrmDialogSO);
end;
procedure TfrmSO.actEditExecute(Sender: TObject);
begin
inherited;
ShowDialogForm(TfrmDialogSO, CDS.FieldByName('SO_ID').AsString);
end;
procedure TfrmSO.actPrintExecute(Sender: TObject);
begin
inherited;
PrintDialog;
end;
procedure TfrmSO.btnPrintClick(Sender: TObject);
var
FilterPeriode: string;
sNomorSO: string;
begin
inherited;
if rbPrintDlg.ItemIndex = 0 then
sNomorSO := CDS.FieldByName('SO_NO').AsString
else
sNomorSO := '';
with dmReport do
begin
FilterPeriode := dtAwalFilter.Text + ' s/d ' + dtAkhirFilter.Text;
AddReportVariable('FilterPeriode', FilterPeriode );
AddReportVariable('UserCetak', 'Baskoro');
ExecuteReport( 'Reports/Slip_SO' ,
ReportClient.SO_ByDateNoBukti(
dtAwalFilter.Date,
dtAkhirFilter.Date,
sNomorSO,
sNomorSO
),[]
);
end;
gbCetak.Visible := False;
end;
procedure TfrmSO.PrintDialog;
begin
gbCetak.Visible := True;
end;
procedure TfrmSO.RefreshData;
begin
inherited;
try
TAppUtils.cShowWaitWindow('Mohon Ditunggu');
if Assigned(FCDS) then FreeAndNil(FCDS);
CDS := TDBUtils.DSToCDS(
DMClient.DSProviderClient.SO_GetDSOverview(dtAwalFilter.Date,dtAkhirFilter.Date, nil),
Self
);
cxGridView.LoadFromCDS(FCDS);
cxGridView.SetVisibleColumns(['AUT$UNIT_ID', 'SO_ID'],False);
finally
TAppUtils.cCloseWaitWindow;
end;
end;
end.
|
unit CFEdit;
interface
uses
Windows, Classes, Controls, CFControl, Graphics, Messages, Vcl.Dialogs;
type
TScrollAlign = (csaLeft, csaRight);
TCFEdit = class(TCFTextControl)
private
FLeftPadding, // 左偏移多少开始显示文本
FRightPadding // 右偏移多少停止显示文本
: Byte;
FDrawLeftOffs, FTextWidth: Integer; // 绘制时左偏移,文本内容宽度
FSelStart, FSelEnd: Integer; // 选择起始和结束发生在第几个后面 >0 有效
FCanSelect: Boolean;
FSelecting: Boolean;
FReadOnly: Boolean;
FHelpText: string;
/// <summary>
/// 根据位置在第几个字符后面(>0有效)
/// </summary>
/// <param name="AX">位置</param>
/// <returns>在第几个字符后面</returns>
function GetOffsetBeforAt(const AX: Integer): Integer;
procedure ScrollTo(const AOffset: Integer; const AAlign: TScrollAlign);
procedure MoveCaretAfter(const AOffset: Integer);
procedure RightKeyPress;
procedure CopyText;
procedure CutText;
procedure PasteText;
procedure SelectAll;
protected
/// <summary> 绘制到画布 </summary>
procedure DrawControl(ACanvas: TCanvas); override;
procedure DeleteSelect(const AUpdate: Boolean = False);
procedure DisSelect;
//
procedure SetCanSelect(Value: Boolean);
procedure SetReadOnly(Value: Boolean);
procedure SetHelpText(Value: string);
procedure AdjustBounds; override;
//
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
//
procedure CMMouseEnter(var Msg: TMessage ); message CM_MOUSEENTER;
procedure CMMouseLeave(var Msg: TMessage ); message CM_MOUSELEAVE;
procedure WMLButtonDblClk(var Message: TWMLButtonDblClk); message WM_LBUTTONDBLCLK;
procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS;
procedure KeyPress(var Key: Char); override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
public
constructor Create(AOwner: TComponent); override;
procedure SetFocus; override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
function SelectExist: Boolean;
function TextLength: Integer;
function SelText: string;
//
property RightPadding: Byte read FRightPadding write FRightPadding;
property LeftPadding: Byte read FLeftPadding write FLeftPadding;
published
property CanSelect: Boolean read FCanSelect write SetCanSelect;
property ReadOnly: Boolean read FReadOnly write SetReadOnly default False;
property HelpText: string read FHelpText write SetHelpText;
//
property Text;
property OnChange;
property OnKeyDown;
property OnKeyPress;
end;
implementation
uses
Clipbrd;
{ TCFEdit }
procedure TCFEdit.ScrollTo(const AOffset: Integer; const AAlign: TScrollAlign);
var
vS: string;
vW, vDecW: Integer;
begin
vS := Copy(Text, 1, AOffset);
vW := Canvas.TextWidth(vS);
if AAlign = csaRight then // 向左滚动到AOffset恰好显示
begin
vDecW := FDrawLeftOffs + GBorderWidth + FLeftPadding + vW - (Width - FRightPadding - GBorderWidth);
if vDecW > 0 then // 超过宽度
begin
FDrawLeftOffs := FDrawLeftOffs - vDecW;
UpdateDirectUI;
end
else
if vDecW < 0 then // 没有超过宽度
begin
if FDrawLeftOffs < 0 then // 左侧有没显示出来的
begin
FDrawLeftOffs := FDrawLeftOffs - vDecW;
if FDrawLeftOffs > 0 then
FDrawLeftOffs := 0;
UpdateDirectUI;
end;
end;
end
else
begin
vDecW := FDrawLeftOffs + vW;
if vDecW < 0 then
begin
FDrawLeftOffs := FDrawLeftOffs - vDecW;
UpdateDirectUI;
end;
end;
end;
procedure TCFEdit.CMMouseEnter(var Msg: TMessage);
begin
inherited;
UpdateDirectUI;
end;
procedure TCFEdit.CMMouseLeave(var Msg: TMessage);
begin
inherited;
UpdateDirectUI;
end;
procedure TCFEdit.CMTextChanged(var Message: TMessage);
begin
inherited;
AdjustBounds;
if Self.HandleAllocated then
begin
UpdateDirectUI;
if Assigned(OnChange) then
OnChange(Self);
end;
end;
procedure TCFEdit.CopyText;
begin
Clipboard.AsText := SelText;
end;
constructor TCFEdit.Create(AOwner: TComponent);
begin
inherited;
FCanSelect := True;
FSelecting := False;
FLeftPadding := 2;
FRightPadding := 2;
FDrawLeftOffs := 0;
FSelStart := -1;
FSelEnd := -1;
Width := 120;
Height := 20;
Cursor := crIBeam;
//Text := 'TCFEdit'; // 处理win32自带属性默认值
end;
procedure TCFEdit.CutText;
var
vS: string;
begin
if not FReadOnly then
begin
vS := SelText;
Clipboard.AsText := vS;
DeleteSelect;
FDrawLeftOffs := FDrawLeftOffs + Canvas.TextWidth(vS);
if FDrawLeftOffs > 0 then
FDrawLeftOffs := 0;
UpdateDirectUI;
end;
end;
procedure TCFEdit.DeleteSelect(const AUpdate: Boolean = False);
var
vS: string;
begin
if SelectExist then // 有选中
begin
vS := Text;
if FSelEnd < FSelStart then // 选中结束位置在起始位置前面
System.Delete(vS, FSelEnd + 1, FSelStart - FSelEnd)
else // 选中结束位置在起始位置后面
System.Delete(vS, FSelStart + 1, FSelEnd - FSelStart);
Text := vS;
if FSelEnd < FSelStart then
FSelStart := FSelEnd;
FSelEnd := -1;
if AUpdate then
UpdateDirectUI;
MoveCaretAfter(FSelStart);
end;
end;
procedure TCFEdit.DisSelect;
begin
if SelectExist then
begin
FSelStart := FSelEnd;
FSelEnd := -1;
UpdateDirectUI;
end;
end;
procedure TCFEdit.DrawControl(ACanvas: TCanvas);
var
vRect: TRect;
vS: string;
vLeft, vRight: Integer;
vSaveDC: Integer;
//vRgn: HRGN;
//vBmp: TBitmap;
begin
inherited DrawControl(ACanvas);
FTextWidth := ACanvas.TextWidth(Text);
// 外观矩形
vRect := Rect(0, 0, Width, Height);
ACanvas.Brush.Style := bsSolid;
if not FReadOnly then
ACanvas.Brush.Color := Color
else
ACanvas.Brush.Color := GReadOlnyBackColor;
if Self.Focused or (cmsMouseIn in MouseState) then
ACanvas.Pen.Color := GBorderHotColor
else
ACanvas.Pen.Color := GBorderColor;
if BorderVisible then
ACanvas.Pen.Style := psSolid
else
ACanvas.Pen.Style := psClear;
if BorderVisible then // 显示边框时圆角区域
//ACanvas.RoundRect(vRect, GRoundSize, GRoundSize)
ACanvas.Rectangle(vRect)
else
ACanvas.FillRect(vRect);
// 设置可绘制区域
InflateRect(vRect, -GBorderWidth, -GBorderWidth);
vRect.Left := vRect.Left + FLeftPadding;
vRect.Right := vRect.Right - FRightPadding;
//vRgn := CreateRectRgnIndirect(vRect);
//SelectClipRgn(ACanvas.Handle, vRgn); //ExtSelectClipRgn(ACanvas.Handle, vRgn)
IntersectClipRect(ACanvas.Handle, vRect.Left, vRect.Top, vRect.Right, vRect.Bottom);
try
// 绘制文本
if Text <> '' then // 有内容
begin
//ACanvas.Font.Assign(Font);
if FSelEnd >= 0 then // 有选中
begin
vLeft := GBorderWidth + FLeftPadding + FDrawLeftOffs; // 偏移到可显示起始位置
if FSelEnd < FSelStart then // 选中结束位置在起始位置前面
begin
vS := Copy(Text, 1, FSelEnd);
if vS <> '' then
vLeft := vLeft + ACanvas.TextWidth(vS);
vS := Copy(Text, 1, FSelStart);
vRight := GBorderWidth + FLeftPadding + FDrawLeftOffs + ACanvas.TextWidth(vS);
end
else // 选中结束位置在起始位置后面
begin
vS := Copy(Text, 1, FSelStart);
if vS <> '' then
vLeft := vLeft + ACanvas.TextWidth(vS);
vS := Copy(Text, 1, FSelEnd);
vRight := GBorderWidth + FLeftPadding + FDrawLeftOffs + ACanvas.TextWidth(vS);
end;
// 绘制选中区域背景
ACanvas.Brush.Color := GHightLightColor;
ACanvas.FillRect(Rect(vLeft, GBorderWidth, vRight, Height - GBorderWidth));
ACanvas.Brush.Style := bsClear;
end;
// 绘制文本
vRect := Rect(GBorderWidth + FLeftPadding + FDrawLeftOffs, GBorderWidth, Width - FRightPadding - GBorderWidth, Height - GBorderWidth);
vS := Text;
ACanvas.TextRect(vRect, vS, [tfLeft, tfVerticalCenter, tfSingleLine]);
end
else
if FHelpText <> '' then // 提示信息
begin
vSaveDC := SaveDC(ACanvas.Handle); // 保存(设备上下文环境)现场
try
ACanvas.Font.Style := [fsItalic];
ACanvas.Font.Color := clMedGray; // clGrayText;
vRect := Rect(GBorderWidth + FLeftPadding, GBorderWidth, Width - FRightPadding - GBorderWidth, Height - GBorderWidth);
vS := FHelpText;
ACanvas.TextRect(vRect, vS, [tfLeft, tfVerticalCenter, tfSingleLine]);
finally
RestoreDC(ACanvas.Handle, vSaveDC); // 恢复(设备上下文环境)现场
end;
end;
finally
SelectClipRgn(ACanvas.Handle, 0); // 清除剪切区域
//DeleteObject(vRgn)
end;
end;
procedure TCFEdit.AdjustBounds;
var
vDC: HDC;
vHeight: Integer;
begin
vDC := GetDC(0);
try
Canvas.Handle := vDC;
Canvas.Font.Assign(Font);
vHeight := Canvas.TextHeight('字') + GetSystemMetrics(SM_CYBORDER) * 4 + GBorderWidth + GBorderWidth;
if vHeight < Height then
vHeight := Height;
FTextWidth := Canvas.TextWidth(Text);
SetBounds(Left, Top, Width, vHeight);
Canvas.Handle := 0;
finally
ReleaseDC(0, vDC);
end;
end;
function TCFEdit.GetOffsetBeforAt(const AX: Integer): Integer;
var
i, vW, vRight: Integer;
begin
Result := -1;
//if (AX < FDrawLeftOffs) or (AX > FTextWidth) then Exit;
if AX < FDrawLeftOffs then
begin
Result := 0;
Exit;
end;
if AX > FTextWidth then
begin
Result := TextLength;
Exit;
end;
if AX < Canvas.TextWidth(Text) then // 在文本中
begin
vRight := FLeftPadding;
for i := 1 to Length(Text) do
begin
vW := Canvas.TextWidth(Text[i]);
if vRight + vW > AX then
begin
if vRight + vW div 2 > AX then
Result := i - 1
else
begin
Result := i;
vRight := vRight + vW;
end;
Break;
end
else
vRight := vRight + vW;
end;
end
else // 不在文本中
Result := TextLength;
end;
procedure TCFEdit.KeyDown(var Key: Word; Shift: TShiftState);
{$REGION 'DoBackKey'}
procedure DoBackKey;
var
vS: string;
begin
if SelectExist then
DeleteSelect(True)
else
begin
if (Text <> '') and (FSelStart > 0) then
begin
vS := Text;
Delete(vS, FSelStart, 1);
Text := vS;
Dec(FSelStart);
if FSelStart = TextLength then // 在最后面向前删除
begin
if FDrawLeftOffs < 0 then // 前面有没显示出来的
ScrollTo(FSelStart, csaRight);
end
else
UpdateDirectUI;
MoveCaretAfter(FSelStart);
end;
end;
end;
{$ENDREGION}
{$REGION 'DoDeleteKey'}
procedure DoDeleteKey;
var
vS: string;
begin
if SelectExist then
DeleteSelect(True)
else
begin
if (Text <> '') and (FSelStart < TextLength) then
begin
vS := Text;
Delete(vS, FSelStart + 1, 1);
Text := vS;
if FSelStart = TextLength then // 在最后面向前删除
begin
if FDrawLeftOffs < 0 then // 前面有没显示出来的
begin
ScrollTo(FSelStart, csaRight);
MoveCaretAfter(FSelStart);
end;
end;
end;
end;
end;
{$ENDREGION}
{$REGION 'DoHomeKey'}
procedure DoHomeKey;
begin
DisSelect;
FSelStart := 0;
FDrawLeftOffs := 0;
MoveCaretAfter(FSelStart);
end;
{$ENDREGION}
{$REGION 'DoEndKey'}
procedure DoEndKey;
begin
DisSelect;
FSelStart := TextLength;
ScrollTo(FSelStart, csaRight);
MoveCaretAfter(FSelStart);
end;
{$ENDREGION}
{$REGION 'DoLeftKeyPress'}
procedure DoLeftKeyPress;
begin
DisSelect;
if FSelStart > 0 then
begin
Dec(FSelStart);
ScrollTo(FSelStart, csaLeft);
MoveCaretAfter(FSelStart);
end;
end;
{$ENDREGION}
begin
inherited;
if Shift = [ssCtrl] then
begin
case Key of
Ord('C'): CopyText;
Ord('X'): CutText;
Ord('V'): PasteText;
end;
Exit;
end;
if FReadOnly then Exit;
case Key of
VK_BACK: DoBackKey;
VK_RETURN: ;
VK_DELETE: DoDeleteKey;
VK_LEFT: DoLeftKeyPress;
VK_RIGHT: RightKeyPress;
VK_HOME: DoHomeKey;
VK_END: DoEndKey;
end;
end;
procedure TCFEdit.KeyPress(var Key: Char);
var
vS: string;
begin
inherited;
if FReadOnly then Exit;
//if Ord(Key) in [VK_BACK, VK_RETURN] then Exit;
if ((Key < #32) or (Key = #127)) and (Ord(Key) <> VK_TAB) then Exit;
DeleteSelect; // 删除选中
vS := Text;
Insert(Key, vS, FSelStart + 1);
Text := vS;
RightKeyPress;
end;
procedure TCFEdit.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
var
vS: string;
vOffs: Integer;
vSelStart: Integer absolute vOffs;
vReUpdate: Boolean;
begin
inherited;
if (X < FLeftPadding) or (X > Width - FRightPadding) then
begin
DisSelect;
Exit;
end;
vReUpdate := False;
//FTextWidth := Canvas.TextWidth(Text);
if FSelEnd >= 0 then
begin
FSelEnd := -1;
vReUpdate := True;
end;
vSelStart := GetOffsetBeforAt(X - FDrawLeftOffs - FLeftPadding - GBorderWidth);
if FSelStart <> vSelStart then
begin
FSelStart := vSelStart;
vReUpdate := True;
end;
// 当显示最右侧的字符有半个露出时,滚动到全显示
vS := Copy(Text, 1, FSelStart);
vOffs := Width - FLeftPadding - FRightPadding - GBorderWidth - GBorderWidth - (Canvas.TextWidth(vS) + FDrawLeftOffs);
if vOffs < 0 then
begin
FDrawLeftOffs := FDrawLeftOffs + vOffs;
vReUpdate := True;
end;
if vReUpdate then
UpdateDirectUI;
MoveCaretAfter(FSelStart);
FSelecting := True;
end;
procedure TCFEdit.MouseMove(Shift: TShiftState; X, Y: Integer);
var
vS: string;
vSelEnd, vW: Integer;
vReUpdate: Boolean;
begin
inherited MouseMove(Shift, X, Y);
// Self.Cursor := crIBeam;
if FSelecting and (ssLeft in Shift) then // 划选
begin
if not FCanSelect then Exit;
vReUpdate := False;
try
if X > Width - FRightPadding then // 鼠标在控件右侧
begin
vW := FTextWidth - (Width - FLeftPadding - FRightPadding - GBorderWidth - GBorderWidth);
if FDrawLeftOffs + vW > 0 then // 右侧内容未显示完全
begin
Dec(FDrawLeftOffs, GPadding);
if FDrawLeftOffs < -vW then
FDrawLeftOffs := -vW;
vReUpdate := True;
end;
vSelEnd := GetOffsetBeforAt(Width - FDrawLeftOffs + FLeftPadding - FRightPadding - GBorderWidth - GBorderWidth);
vS := Copy(Text, 1, vSelEnd);
if Canvas.TextWidth(vS) + FDrawLeftOffs > Width - FLeftPadding - FRightPadding - GBorderWidth - GBorderWidth then
Dec(vSelEnd);
end
else
if X < FLeftPadding then
begin
if FDrawLeftOffs < 0 then // 左侧内容未显示完全
begin
Inc(FDrawLeftOffs, GPadding);
if FDrawLeftOffs > 0 then
FDrawLeftOffs := 0;
vReUpdate := True;
end;
vSelEnd := GetOffsetBeforAt({FLeftPadding - 当字符一半小于FLeftPadding时计算不准确}-FDrawLeftOffs);
vS := Copy(Text, 1, vSelEnd);
if Canvas.TextWidth(vS) + FDrawLeftOffs < 0 then
Inc(vSelEnd);
end
else
begin
vSelEnd := GetOffsetBeforAt(X - FDrawLeftOffs - FLeftPadding - GBorderWidth);
vS := Copy(Text, 1, vSelEnd);
if Canvas.TextWidth(vS) + FDrawLeftOffs + FLeftPadding + GBorderWidth > Width - FRightPadding - GBorderWidth then
Dec(vSelEnd);
end;
if vSelEnd < 0 then // 鼠标不在内容中
begin
if SelectExist then // 划选到控件外时,如果有选中,则选中结束位置不改动
Exit;
end;
//if FSelEnd <> vSelEnd then // 暂时保留下面的begin end
begin
FSelEnd := vSelEnd;
if FSelEnd = FSelStart then // 选择起始和结束位置相同
FSelEnd := -1;
//if FSelEnd < 0 then Exit;
vS := Copy(Text, 1, FSelEnd);
SetCaretPos(GBorderWidth + FLeftPadding + Canvas.TextWidth(vS) + FDrawLeftOffs, GBorderWidth);
//PostMessage(GetUIHandle, WM_C_CARETCHANGE, 0, Height - 2 * FTopPadding);
vReUpdate := True;
end;
finally
if vReUpdate then
UpdateDirectUI;
end;
end;
end;
procedure TCFEdit.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
inherited;
FSelecting := False;
end;
procedure TCFEdit.MoveCaretAfter(const AOffset: Integer);
var
vS: string;
vCaretLeft, vCaretHeight: Integer;
begin
if AOffset < 0 then Exit;
vCaretHeight := Height - 2 * GBorderWidth;
vCaretLeft := GBorderWidth + FLeftPadding;
if AOffset > 0 then
begin
vS := Copy(Text, 1, AOffset);
vCaretLeft := vCaretLeft + Canvas.TextWidth(vS) + FDrawLeftOffs;
end;
DestroyCaret;
CreateCaret(Handle, 0, 1, vCaretHeight);
SetCaretPos(vCaretLeft, GBorderWidth);
ShowCaret(Handle);
//PostMessage(GetUIHandle, WM_C_CARETCHANGE, 0, vCaretHeight);
end;
procedure TCFEdit.PasteText;
var
vsClip, vS: string;
begin
if not FReadOnly then
begin
DeleteSelect;
vS := Text;
vsClip := Clipboard.AsText;
Insert(vsClip, vS, FSelStart + 1);
Text := vS;
FSelStart := FSelStart + Length(vsClip);
if FDrawLeftOffs < 0 then
FDrawLeftOffs := FDrawLeftOffs - Canvas.TextWidth(vsClip)
else
ScrollTo(FSelStart, csaRight);
MoveCaretAfter(FSelStart);
UpdateDirectUI;
end;
end;
procedure TCFEdit.RightKeyPress;
begin
DisSelect;
if FSelStart < TextLength then
begin
Inc(FSelStart);
ScrollTo(FSelStart, csaRight);
MoveCaretAfter(FSelStart);
end;
end;
procedure TCFEdit.SelectAll;
begin
FSelecting := False; // 处理双击并移动鼠标时,虽然双击全选,但移动又将选中结束位置改为当前鼠标处
FSelStart := 0;
FSelEnd := TextLength;
ScrollTo(FSelEnd, csaRight);
UpdateDirectUI;
MoveCaretAfter(FSelEnd);
end;
function TCFEdit.SelectExist: Boolean;
begin
Result := (FSelEnd >= 0) and (FSelEnd <> FSelStart);
end;
function TCFEdit.SelText: string;
begin
if SelectExist then
Result := Copy(Text, FSelStart + 1, FSelEnd - FSelStart)
else
Result := '';
end;
procedure TCFEdit.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
var
vDC: HDC;
vHeight: Integer;
begin
vDC := GetDC(0);
try
Canvas.Handle := vDC;
Canvas.Font.Assign(Font);
vHeight := Canvas.TextHeight('字') + GetSystemMetrics(SM_CYBORDER) * 4 + GBorderWidth + GBorderWidth;
if vHeight < AHeight then
vHeight := AHeight;
Canvas.Handle := 0;
finally
ReleaseDC(0, vDC);
end;
inherited SetBounds(ALeft, ATop, AWidth, vHeight);
end;
procedure TCFEdit.SetCanSelect(Value: Boolean);
begin
if FCanSelect <> Value then
begin
FCanSelect := Value;
if not FCanSelect then
DisSelect;
end;
end;
procedure TCFEdit.SetFocus;
begin
inherited SetFocus;
FSelStart := TextLength;
MoveCaretAfter(FSelStart);
end;
procedure TCFEdit.SetHelpText(Value: string);
begin
if FHelpText <> Value then
begin
FHelpText := Value;
UpdateDirectUI;
end;
end;
procedure TCFEdit.SetReadOnly(Value: Boolean);
begin
if FReadOnly <> Value then
begin
FReadOnly := Value;
DisSelect;
DestroyCaret;
end;
end;
function TCFEdit.TextLength: Integer;
begin
Result := Length(Text);
end;
procedure TCFEdit.WMKillFocus(var Message: TWMKillFocus);
begin
inherited;
DestroyCaret;
end;
procedure TCFEdit.WMLButtonDblClk(var Message: TWMLButtonDblClk);
begin
inherited;
SelectAll;
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.IDE.AddInOptionsHostForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
DPM.IDE.AddInOptionsFrame,
DPM.IDE.Options,
DPM.Core.Logging,
DPM.Core.Configuration.Interfaces, Vcl.ExtCtrls, Vcl.StdCtrls;
type
TDPMOptionsHostForm = class(TForm)
DPMOptionsFrame : TDPMOptionsFrame;
Panel1 : TPanel;
btnCancel : TButton;
btnOK : TButton;
procedure btnOKClick(Sender : TObject);
private
{ Private declarations }
public
{ Public declarations }
constructor Create(AOwner : TComponent; const configManager : IConfigurationManager; const logger : ILogger; const ideOptions : IDPMIDEOptions; const configFile : string); reintroduce;
end;
var
DPMOptionsHostForm : TDPMOptionsHostForm;
implementation
uses
ToolsApi;
{$R *.dfm}
{$I DPMIDE.inc}
{ TDPMOptionsHostForm }
procedure TDPMOptionsHostForm.btnOKClick(Sender : TObject);
begin
if DPMOptionsFrame.Validate then
begin
DPMOptionsFrame.SaveSettings;
Self.ModalResult := mrOK;
end;
end;
constructor TDPMOptionsHostForm.Create(AOwner : TComponent; const configManager : IConfigurationManager; const logger : ILogger; const ideOptions : IDPMIDEOptions; const configFile : string);
begin
inherited Create(AOwner);
{$IFDEF STYLEELEMENTS}
//earlier versions of the IDE strip these from the dfm
StyleElements := [seFont, seClient, seBorder];
{$ENDIF}
{$IFDEF THEMESERVICES}
(BorlandIDEServices as IOTAIDEThemingServices).ApplyTheme(Self);
{$ENDIF}
DPMOptionsFrame.Configure(configManager, ideOptions, logger, configFile);
Self.Caption := 'DPM Options [' + configFile + ']';
DPMOptionsFrame.LoadSettings;
end;
{$IFDEF THEMESERVICES}
initialization
(BorlandIDEServices as IOTAIDEThemingServices250).RegisterFormClass(TDPMOptionsHostForm);
{$ENDIF}
end.
|
namespace org.me.listviewapp;
//Sample app by Brian Long (http://blong.com)
{
This example has a main screen (a ListActivity) as a menu to 2 other screens.
The main screen offers an About box through its menu.
The About box is a themed activity and looks like a floating dialog
(the theme is set in the Android manifest file).
Both other screens are also scrollable lists.
One is an Activity that uses a layout file containing a ListView.
The other is a ListActivity.
Both lists display a list of countries read in from a string array resource.
Both lists have the option of using a custom adapter to scroll the list
as opposed to a standard adapter.
The choice is stored in a shared preference, accessible throughout the application.
One list offers the choice via an option dialog.
The other list invokes a PreferenceActivity to automatically serve up the
choice using an XML layout description.
The custom adapter offers section indexing - as you drag the scroller, you can
readily jump to specific sections of the list, which in this case are the first
of each group countries starting with each letter of the alphabet.
}
interface
uses
java.util,
android.os,
android.app,
android.util,
android.view,
android.widget,
android.content;
type
MainActivity = public class(ListActivity)
private
//Menu items
const ABOUT_ID = 0;
//List items;
const ID_LIST = 0;
const ID_LIST2 = 1;
//Misc
const Tag = "SampleApp.MainActivity";
public
method onCreate(savedInstanceState: Bundle); override;
method onCreateOptionsMenu(menu: Menu): Boolean; override;
method onOptionsItemSelected(item: MenuItem): Boolean; override;
method onListItemClick(l: ListView; v: View; position: Integer; id: Int64); override;
method onBackPressed; override;
end;
implementation
method MainActivity.onCreate(savedInstanceState: Bundle);
begin
inherited;
//Set up for an icon on the main activity title bar
requestWindowFeature(Window.FEATURE_LEFT_ICON);
// Set our view from the "main" layout resource
setContentView(R.layout.main);
//Now get the icon on the title bar
setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.icon);
//Get the titles and subtitles to display in this main screen list from string array resources
var rows := Resources.StringArray[R.array.menu_titles];
var rowSubtitles := Resources.StringArray[R.array.menu_subtitles];
if rows.length <> rowSubtitles.length then
Log.e(Tag, "Menu titles & subtitles have mismatched lengths");
//Build an ArrayList of maps containing the information to display
var listViewContent := new ArrayList<Map<String, Object>>();
for i: Integer := 0 to rows.length - 1 do
begin
var map := new HashMap<String, Object>();
map.put("heading", rows[i]);
map.put("subheading", rowSubtitles[i]);
listViewContent.add(map);
end;
//Set up adapter for the ListView using a custom list item template
ListAdapter := new SimpleAdapter(Self, listViewContent, R.layout.listitem_twolines,
["heading", "subheading"], [Android.R.id.text1, Android.R.id.text2]);
end;
method MainActivity.onCreateOptionsMenu(menu: Menu): Boolean;
begin
var item := menu.add(0, ABOUT_ID, 0, R.string.about_menu);
//Options menu items support icons
item.Icon := Android.R.drawable.ic_menu_info_details;
Result := True;
end;
method MainActivity.onOptionsItemSelected(item: MenuItem): Boolean;
begin
if item.ItemId = ABOUT_ID then
begin
startActivity(new Intent(Self, typeOf(AboutActivity)));
exit True
end;
exit false;
end;
method MainActivity.onListItemClick(l: ListView; v: View; position: Integer; id: Int64);
begin
case position of
ID_LIST: startActivity(new Intent(Self, typeOf(ListViewActivity)));
ID_LIST2: startActivity(new Intent(Self, typeOf(ListViewActivity2)));
end;
end;
method MainActivity.onBackPressed;
begin
inherited;
Toast.makeText(self, String[R.string.back_pressed], Toast.LENGTH_SHORT).show
end;
end. |
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Core.Options.Push;
interface
uses
DPM.Core.Types,
DPM.Core.Options.Base;
type
TPushOptions = class(TOptionsBase)
private
FPackagePath : string;
FSource : string;
FApiKey : string;
FTimeout : integer;
FSkipDuplicate : boolean;
class var
FDefault : TPushOptions;
public
class constructor CreateDefault;
class property Default : TPushOptions read FDefault;
constructor Create; override;
property ApiKey : string read FApiKey write FApiKey;
property PackagePath : string read FPackagePath write FPackagePath;
property SkipDuplicate : boolean read FSkipDuplicate write FSkipDuplicate;
property Source : string read FSource write FSource;
property Timeout : integer read FTimeout write FTimeout;
end;
implementation
{ TPushOptions }
constructor TPushOptions.Create;
begin
inherited;
FTimeout := -1;
end;
class constructor TPushOptions.CreateDefault;
begin
FDefault := TPushOptions.Create;
end;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2015 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of an Embarcadero developer tools product.
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit FDownloadDemo;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Net.URLClient, System.Net.HttpClient,
System.Net.HttpClientComponent, FMX.StdCtrls, FMX.Edit, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo,
System.ImageList, FMX.ImgList;
type
TDownloadThreadDataEvent = procedure(const Sender: TObject; ThreadNo, ASpeed: Integer; AContentLength: Int64; AReadCount: Int64; var Abort: Boolean) of object;
TDownloadThread = class(TThread)
private
FOnThreadData: TDownloadThreadDataEvent;
protected
FURL, FFileName: string;
FStartPoint, FEndPoint: Int64;
FThreadNo: Integer;
FTimeStart: Cardinal;
procedure ReceiveDataEvent(const Sender: TObject; AContentLength: Int64; AReadCount: Int64; var Abort: Boolean);
public
constructor Create(const URL, FileName: string; ThreadNo: Integer; StartPoint, EndPoint: Int64);
destructor Destroy; override;
procedure Execute; override;
property OnThreadData: TDownloadThreadDataEvent write FOnThreadData;
end;
TFormDownloadDemo = class(TForm)
PanelTop: TPanel;
PanelCenter: TPanel;
LabelFile: TLabel;
EditFileName: TEdit;
BStartDownload: TButton;
Memo1: TMemo;
ProgressBarPart1: TProgressBar;
ProgressBarPart2: TProgressBar;
ProgressBarPart3: TProgressBar;
ProgressBarPart4: TProgressBar;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Button1: TButton;
ImageList1: TImageList;
Button2: TButton;
Button3: TButton;
Button4: TButton;
LabelURL: TLabel;
EditURL: TEdit;
LabelGlobalSpeed: TLabel;
procedure BStartDownloadClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ButtonCancelClick(Sender: TObject);
private
{ Private declarations }
ButtonCancelArray: array [0..3] of TButton;
ProgressBarArray: array [0..3] of TProgressBar;
LabelProgressArray: array [0..3] of TLabel;
procedure ReceiveThreadDataEvent(const Sender: TObject; ThreadNo, ASpeed: Integer; AContentLength: Int64; AReadCount: Int64; var Abort: Boolean);
public
const
NumThreads: Integer = 4;
public
{ Public declarations }
procedure SampleDownload;
end;
var
FormDownloadDemo: TFormDownloadDemo;
implementation
{$R *.fmx}
uses
System.IOUtils;
procedure TFormDownloadDemo.BStartDownloadClick(Sender: TObject);
begin
(Sender as TButton).Enabled := False;
SampleDownload;
(Sender as TButton).Enabled := True;
end;
procedure TFormDownloadDemo.ButtonCancelClick(Sender: TObject);
begin
(Sender as TButton).Enabled := False;
end;
procedure TFormDownloadDemo.FormCreate(Sender: TObject);
begin
ButtonCancelArray[0] := Button1;
ButtonCancelArray[1] := Button2;
ButtonCancelArray[2] := Button3;
ButtonCancelArray[3] := Button4;
ProgressBarArray[0] := ProgressBarPart1;
ProgressBarArray[1] := ProgressBarPart2;
ProgressBarArray[2] := ProgressBarPart3;
ProgressBarArray[3] := ProgressBarPart4;
LabelProgressArray[0] := Label1;
LabelProgressArray[1] := Label2;
LabelProgressArray[2] := Label3;
LabelProgressArray[3] := Label4;
end;
procedure TFormDownloadDemo.ReceiveThreadDataEvent(const Sender: TObject; ThreadNo: Integer; ASpeed: Integer; AContentLength, AReadCount: Int64;
var Abort: Boolean);
var
LCad: string;
LCancel: Boolean;
LSpeed: Integer;
begin
LCancel := Abort;
TThread.Synchronize(nil,
procedure
begin
LCancel := not ButtonCancelArray[ThreadNo].Enabled;
ProgressBarArray[ThreadNo].Value := AReadCount;
LabelProgressArray[ThreadNo].Text := Format('%d KB/s', [ASpeed div 1024]);
Application.ProcessMessages;
end);
Abort := LCancel;
end;
procedure TFormDownloadDemo.SampleDownload;
var
LClient: THTTPClient;
URL: string;
LResponse: IHTTPResponse;
StFile: TFileStream;
LFileName: string;
LStart, LEnd, LSize, LFragSize: Int64;
I: Integer;
LDownloadThreads: array of TDownloadThread;
LFinished: Boolean;
LStartTime, LEndTime: Cardinal;
begin
LClient := THTTPClient.Create;
LFileName := TPath.Combine(TPath.GetDocumentsPath, EditFileName.Text);
try
URL := EditURL.Text;
// URL := 'http://ftp.udc.es/ubuntu-releases/14.04.1/ubuntu-14.04.1-desktop-amd64.iso';
// URL := 'http://ftp.udc.es/ubuntu-releases/14.04.1/ubuntu-14.04-server-amd64.template';
if LClient.CheckDownloadResume(URL) then
begin
LResponse := LClient.Head(URL);
// Get space for the file that is going to be dowloaded
LSize := LResponse.ContentLength;
StFile := TFileStream.Create(LFileName, fmCreate);
try
STFile.Size := LSize;
finally
STFile.Free;
end;
// Split the file in four blocks
LFragSize := LSize div NumThreads;
LStart := 0;
LEnd := LStart + LFragSize;
SetLength(LDownloadThreads, NumThreads);
for I := 0 to NumThreads - 1 do
begin
// Create the Thread
LDownloadThreads[I] := TDownloadThread.Create(URL, LFileName, I, LStart, LEnd);
LDownloadThreads[I].OnThreadData := ReceiveThreadDataEvent;
// Adjust the ProgressBar Max Value
if LEnd >= LSize then
begin
ProgressBarArray[I].Max := LFragSize - (LEnd - LSize);
LEnd := LSize;
end
else
ProgressBarArray[I].Max := LFragSize;
ProgressBarArray[I].Min := 0;
ProgressBarArray[I].Value := 0;
ButtonCancelArray[I].Enabled := True;
LabelProgressArray[I].Text := '0 KB/s';
Application.ProcessMessages;
// Update Start and End Values
LStart := LStart + LFragSize;
LEnd := LStart + LFragSize;
end;
// Start the download process
LStartTime := TThread.GetTickCount;
for I := 0 to NumThreads - 1 do
LDownloadThreads[I].Start;
// Wait until all threads finish
LFinished := False;
while not LFinished do
begin
Application.ProcessMessages;
LFinished := True;
for I := 0 to NumThreads - 1 do
LFinished := LFinished and LDownloadThreads[I].Finished;
end;
LEndTime := TThread.GetTickCount - LStartTime;
LabelGlobalSpeed.Text := Format('Global Speed: %d KB/s', [((LSize*1000) div LEndTime) div 1024]);
// Cleanup Threads
for I := 0 to NumThreads - 1 do
LDownloadThreads[I].Free;
end
else
Memo1.Lines.Add('Server has NOT resume download feature');
finally
LClient.Free;
end;
end;
{ TDownloadThread }
constructor TDownloadThread.Create(const URL, FileName: string; ThreadNo: Integer; StartPoint, EndPoint: Int64);
begin
inherited Create(True);
FURL := URL;
FFileName := FileName;
FThreadNo := ThreadNo;
FStartPoint := StartPoint;
FEndPoint := EndPoint;
end;
destructor TDownloadThread.Destroy;
begin
inherited;
end;
procedure TDownloadThread.Execute;
var
LResponse: IHTTPResponse;
LStream: TFileStream;
LHttpClient: THTTPClient;
begin
inherited;
LHttpClient := THTTPClient.Create;
try
LHttpClient.OnReceiveData := ReceiveDataEvent;
LStream := TFileStream.Create(FFileName, fmOpenWrite or fmShareDenyNone);
try
FTimeStart := GetTickCount;
LStream.Seek(FStartPoint, TSeekOrigin.soBeginning);
LResponse := LHttpClient.GetRange(FURL, FStartPoint, FEndPoint, LStream);
finally
LStream.Free;
end;
finally
LHttpClient.Free;
end;
end;
procedure TDownloadThread.ReceiveDataEvent(const Sender: TObject; AContentLength, AReadCount: Int64;
var Abort: Boolean);
var
LTime: Cardinal;
LSpeed: Integer;
begin
if Assigned(FOnThreadData) then
begin
LTime := GetTickCount - FTimeStart;
if AReadCount = 0 then
LSpeed := 0
else
LSpeed := (AReadCount * 1000) div LTime;
FOnThreadData(Sender, FThreadNo, LSpeed, AContentLength, AReadCount, Abort);
end;
end;
end.
|
unit TestUItensLeituraGasController;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, DB, ULeituraGasVO, SysUtils, DBClient, DBXJSON, UPessoasVO,
UCondominioController, DBXCommon, UHistoricoVO, UEmpresaTrab, UUnidadeVO,
UPessoasController, UPlanoCOntasController, Classes, UController,
UItensLeituraGasController, UPlanoContasVO, ULancamentoContabilVO,
UItensLeituraGasVo, ConexaoBD, SQLExpr, Generics.Collections;
type
// Test methods for class TItensLeituraGasController
TestTItensLeituraGasController = class(TTestCase)
strict private
FItensLeituraGasController: TItensLeituraGasController;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestConsultarPorId;
procedure TestConsultarPorIdNaoEncontrado;
end;
implementation
procedure TestTItensLeituraGasController.SetUp;
begin
FItensLeituraGasController := TItensLeituraGasController.Create;
end;
procedure TestTItensLeituraGasController.TearDown;
begin
FItensLeituraGasController.Free;
FItensLeituraGasController := nil;
end;
procedure TestTItensLeituraGasController.TestConsultarPorId;
var
ReturnValue: TItensLeituraGasVO;
begin
ReturnValue := FItensLeituraGasController.ConsultarPorId(269);
if(returnvalue <> nil) then
check(true,'Leitura pesquisada com sucesso!')
else
check(False,'Leitura nao encontrada!');
end;
procedure TestTItensLeituraGasController.TestConsultarPorIdNaoEncontrado;
var
ReturnValue: TItensLeituraGasVO;
begin
ReturnValue := FItensLeituraGasController.ConsultarPorId(1);
if(returnvalue <> nil) then
check(False,'Leitura pesquisada com sucesso!')
else
check(true,'Leitura nao encontrada!');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTItensLeituraGasController.Suite);
end.
|
unit uSubModelDetail;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uParentSub, siComp, siLangRT, DateBox, Buttons, StdCtrls, Mask,
SuperComboADO, Grids, DBGrids, SMDBGrid, DBCtrls, ExtCtrls, ComCtrls, DB,
ADODB, SubListPanel;
type
TOnVendorDblClick = procedure (Sender : TObject; iIDFornecedor: integer) of object;
type
TSubModelDetail = class(TParentSub)
lblTitle: TLabel;
quModel: TADOQuery;
quModelRealMarkUpPercet: TFloatField;
quModelRealMarkUpValue: TCurrencyField;
quModelIDModel: TIntegerField;
quModelFreightCost: TFloatField;
quModelOtherCost: TFloatField;
quModelVendorCost: TFloatField;
quModelDateLastCost: TDateTimeField;
quModelMarkUp: TFloatField;
quModelSellingPrice: TFloatField;
quModelDateLastSellingPrice: TDateTimeField;
quModelLastCost: TFloatField;
quModelSuggRetail: TFloatField;
dsModel: TDataSource;
pcModel: TPageControl;
tsModel: TTabSheet;
pnlQuantity: TPanel;
pnlCost: TPanel;
Label17: TLabel;
Label18: TLabel;
Label19: TLabel;
Label20: TLabel;
Shape1: TShape;
Label22: TLabel;
Label23: TLabel;
Label24: TLabel;
Label25: TLabel;
editNetCost: TDBText;
editOtherCost: TDBText;
editFreightCost: TDBText;
DBEdit4: TDBText;
Label6: TLabel;
DBText4: TDBText;
pnlRetail: TPanel;
Label21: TLabel;
Label26: TLabel;
Shape2: TShape;
Label27: TLabel;
DBEdit13: TDBText;
DBEdit6: TDBText;
Label1: TLabel;
DBText1: TDBText;
Label2: TLabel;
Label5: TLabel;
DBText3: TDBText;
pnlFrameRequest_fdskjfhg: TPanel;
pnlFrameRequest_fdjkswf: TPanel;
tsPurchaseHistory: TTabSheet;
tsSaleHistory: TTabSheet;
tsInventoryMov: TTabSheet;
tsInventoryMovTotal: TTabSheet;
tsOrder: TTabSheet;
tsVendorHistory: TTabSheet;
SubListQty: TSubListPanel;
SubListPurHistory: TSubListPanel;
SubListSalesHistory: TSubListPanel;
SubListMovHistory: TSubListPanel;
SubListMovTotal: TSubListPanel;
SubListOrderHistory: TSubListPanel;
SubListVendor: TSubListPanel;
quModelAvgCost: TBCDField;
quModelReplacementCost: TBCDField;
lbTotal: TLabel;
lbReplacCost: TLabel;
DBText5: TDBText;
DBText6: TDBText;
quModelFinalCost: TCurrencyField;
quModelTotQtyOnHand: TFloatField;
quModelCaseQty: TFloatField;
lbCaseQty: TLabel;
DBText2: TDBText;
procedure pcModelChange(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure quModelCalcFields(DataSet: TDataSet);
procedure quModelAfterOpen(DataSet: TDataSet);
private
{ Private declarations }
fIDModel : Integer;
fIDStore : Integer;
fIDVendor : Integer;
fShowMinMax : Char;
procedure TabRefresh;
procedure EnableValues;
protected
procedure AfterSetParam; override;
public
{ Public declarations }
procedure DataSetRefresh;
procedure DataSetOpen; override;
procedure DataSetClose; override;
end;
implementation
uses uDM, uParamFunctions, uDMGlobal, uSystemConst;
{$R *.dfm}
procedure TSubModelDetail.DataSetRefresh;
begin
DataSetClose;
DataSetOpen;
end;
procedure TSubModelDetail.DataSetOpen;
begin
with quModel do
if not Active then
begin
Parameters.ParambyName('IDModel').Value := fIDModel;
Open;
end;
end;
procedure TSubModelDetail.DataSetClose;
begin
with quModel do
if Active then
Close;
end;
procedure TSubModelDetail.AfterSetParam;
begin
fIDModel := StrToIntDef(ParseParam(FParam, 'IDModel'),0);
fIDStore := StrToIntDef(ParseParam(FParam, 'IDStore'),0);
fIDVendor := StrToIntDef(ParseParam(FParam, 'IDVendor'),0);
if (ParseParam(FParam, 'ShowMinMax')='Y') then
fShowMinMax := 'Y'
else
fShowMinMax := 'N';
TabRefresh;
EnableValues;
end;
procedure TSubModelDetail.TabRefresh;
begin
lblTitle.Caption := pcModel.ActivePage.Caption;
if pcModel.ActivePage = tsModel then
begin
//DataSetOpen;
DataSetRefresh;
//Create Frm Model Detail
SubListQty.CreateSubList;
SubListQty.Param := 'IDModel='+IntToStr(fIDModel)+';IDStore='+IntToStr(fIDStore)+';'+'ShowMinMax='+fShowMinMax+';';
end
else if pcModel.ActivePage = tsInventoryMovTotal then
begin
SubListMovTotal.CreateSubList;
SubListMovTotal.Param := 'IDModel='+IntToStr(fIDModel)+';IDStore='+IntToStr(fIDStore)+';';
end
else if pcModel.ActivePage = tsPurchaseHistory then
begin
//Create SubPruchase
SubListPurHistory.CreateSubList;
SubListPurHistory.Param := 'IDModel='+IntToStr(fIDModel)+';IDStore='+IntToStr(fIDStore)+';';
end
else if pcModel.ActivePage = tsSaleHistory then
begin
//Create SubSalesHistory
SubListSalesHistory.CreateSubList;
SubListSalesHistory.Param := 'IDModel='+IntToStr(fIDModel)+';IDStore='+IntToStr(fIDStore)+';';
end
else if pcModel.ActivePage = tsInventoryMov then
begin
SubListMovHistory.CreateSubList;
SubListMovHistory.Param := 'IDModel='+IntToStr(fIDModel)+';IDStore='+IntToStr(fIDStore)+';';
end
else if pcModel.ActivePage = tsOrder then
begin
SubListOrderHistory.CreateSubList;
SubListOrderHistory.Param := 'IDModel='+IntToStr(fIDModel)+';';
end
else if pcModel.ActivePage = tsVendorHistory then
begin
SubListVendor.CreateSubList;
SubListVendor.Param := 'IDVendor='+IntToStr(fIDVendor)+';IDStore='+IntToStr(fIDStore)+';';
end;
end;
procedure TSubModelDetail.pcModelChange(Sender: TObject);
begin
inherited;
TabRefresh;
end;
procedure TSubModelDetail.FormDestroy(Sender: TObject);
begin
DataSetClose;
inherited;
end;
procedure TSubModelDetail.EnableValues;
var
bEstimatedCost,
bTaxIncludedInCost : Boolean;
begin
bEstimatedCost := DM.fSystem.SrvParam[PARAM_USE_ESTIMATED_COST];
bTaxIncludedInCost := DM.fSystem.SrvParam[PARAM_TAX_IN_COSTPRICE];
lbReplacCost.Visible := bEstimatedCost;
DBText6.Visible := bEstimatedCost;
//Somente para exibir se a taxa nao estiver no custo da merdacoria
Label5.Visible := not bTaxIncludedInCost;
DBText3.Visible := not bTaxIncludedInCost;
Label1.Visible := not bTaxIncludedInCost;
DBText1.Visible := not bTaxIncludedInCost;
Label2.Visible := not bTaxIncludedInCost;
Label21.Visible := not bTaxIncludedInCost;
DBEdit13.Visible := not bTaxIncludedInCost;
Label20.Visible := (quModelAvgCost.AsCurrency > 0);
DBText5.Visible := Label20.Visible;
Label6.Visible := (quModelLastCost.AsCurrency>0);
DBText4.Visible := Label6.Visible;
end;
procedure TSubModelDetail.quModelCalcFields(DataSet: TDataSet);
begin
inherited;
quModelFinalCost.AsCurrency := quModelVendorCost.AsCurrency +
quModelFreightCost.AsCurrency +
quModelOtherCost.AsCurrency;
end;
procedure TSubModelDetail.quModelAfterOpen(DataSet: TDataSet);
begin
inherited;
lbCaseQty.Visible := (quModelCaseQty.AsFloat>1);
DBText2.Visible := lbCaseQty.Visible;
end;
initialization
RegisterClass(TSubModelDetail);
end.
|
unit cn_DissInfo_Unit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cn_Common_Types, DM_DissInfo, StdCtrls, cxContainer, cxEdit,
cxTextEdit, cxControls, cxGroupBox, cxMaskEdit, cxDropDownEdit,
cxCalendar, cxLookAndFeelPainters, cxButtons, cn_Common_Funcs, cnConsts,
cn_Common_Messages, cnConsts_Messages, cxButtonEdit, cn_Common_Loader, Registry,
Buttons, ibase;
type TDissInfoCookies = record
IsIt : Boolean;
DateDiss : TDate;
OrderDate : TDate;
ORDER_NUM : String;
Type_Diss : String;
ID_TYPE_DISS : Int64;
Comments : String;
end;
type
TfrmDissInfo = class(TForm)
GroupBox: TcxGroupBox;
OrderNum_Edit: TcxTextEdit;
OrderNum_Label: TLabel;
Comments_Label: TLabel;
Comments_Edit: TcxTextEdit;
DateDiss: TcxDateEdit;
OrderDate: TcxDateEdit;
DateDiss_Label: TLabel;
OrderDate_Label: TLabel;
OkButton: TcxButton;
CancelButton: TcxButton;
TypeDiss_Edit: TcxButtonEdit;
TypeDiss_Label: TLabel;
SpeedButton: TSpeedButton;
procedure CancelButtonClick(Sender: TObject);
procedure OkButtonClick(Sender: TObject);
procedure TypeDiss_EditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure DateDissKeyPress(Sender: TObject; var Key: Char);
procedure OrderDateKeyPress(Sender: TObject; var Key: Char);
procedure OrderNum_EditKeyPress(Sender: TObject; var Key: Char);
procedure TypeDiss_EditKeyPress(Sender: TObject; var Key: Char);
procedure Comments_EditKeyPress(Sender: TObject; var Key: Char);
procedure FormCreate(Sender: TObject);
procedure SpeedButtonClick(Sender: TObject);
private
{ Private declarations }
private
PLanguageIndex: byte;
DM:TDM_Diss;
ID_DOG_DISS: Int64;
ID_TYPE_DISS: Int64;
ID_DOG_ROOT : Int64;
ID_DOG_LAST : Int64;
ID_STUD : Int64;
Is_Collect : byte;
IsUpload: boolean;
DissDownAllContract_local : boolean;
EditMode : boolean;
function LoadCookies (): TDissInfoCookies;
procedure SaveCookies (DissCookies: TDissInfoCookies);
procedure FormIniLanguage;
procedure ChangeAMode(AMode : TActionMode);
public
TR_DissHandle: TISC_TR_HANDLE;
res:TDissInfo;
is_admin : Boolean;
constructor Create(AParameter:TcnSimpleParamsEx);reintroduce;
end;
var
frmDissInfo: TfrmDissInfo;
implementation
uses FIBDatabase;
{$R *.dfm}
procedure TfrmDissInfo.ChangeAMode(AMode : TActionMode);
begin
if AMode = View then
begin
OkButton.Visible := False;
DateDiss.Properties.ReadOnly := true;
OrderDate.Properties.ReadOnly := true;
OrderNum_Edit.Properties.ReadOnly := true;
Comments_Edit.Properties.ReadOnly := true;
SpeedButton.Visible:= false;
end;
if AMode = Edit then
begin
OkButton.Visible := True;
DateDiss.Properties.ReadOnly := False;
OrderDate.Properties.ReadOnly := False;
OrderNum_Edit.Properties.ReadOnly := False;
Comments_Edit.Properties.ReadOnly := False;
DateDiss.Style.Color := clInfoBk;
OrderDate.Style.Color := clInfoBk;
OrderNum_Edit.Style.Color := clInfoBk;
Comments_Edit.Style.Color := clInfoBk;
end;
end;
procedure TfrmDissInfo.SaveCookies (DissCookies: TDissInfoCookies);
var
reg: TRegistry;
begin
reg := TRegistry.Create;
try
reg.RootKey:=HKEY_CURRENT_USER;
if reg.OpenKey('\Software\Contracts\Cookies\DissDog',True) then
begin
reg.WriteString('DateDiss', DateToStr(DissCookies.DateDiss));
reg.WriteString('OrderDate', DateToStr(DissCookies.OrderDate));
reg.WriteString('ORDER_NUM', DissCookies.ORDER_NUM);
reg.WriteString('Type_Diss', DissCookies.Type_Diss);
reg.WriteString('ID_TYPE_DISS', IntToStr(DissCookies.ID_TYPE_DISS));
reg.WriteString('Comments', DissCookies.Comments);
end
finally
reg.Free;
end;
end;
function TfrmDissInfo.LoadCookies (): TDissInfoCookies;
var
reg: TRegistry;
DissCookies : TDissInfoCookies;
begin
reg := TRegistry.Create;
try
reg.RootKey:=HKEY_CURRENT_USER;
DissCookies.IsIt := False;
if reg.OpenKey('\Software\Contracts\Cookies\DissDog',False) then
begin
DissCookies.DateDiss := StrToDate(reg.ReadString('DateDiss')) ;
DissCookies.OrderDate := StrToDate(reg.ReadString('OrderDate')) ;
DissCookies.ORDER_NUM := reg.ReadString('ORDER_NUM') ;
DissCookies.Type_Diss := reg.ReadString('Type_Diss') ;
DissCookies.ID_TYPE_DISS := StrToInt(reg.ReadString('ID_TYPE_DISS')) ;
DissCookies.Comments := reg.ReadString('Comments') ;
DissCookies.IsIt := True;
Result := DissCookies;
end
finally
reg.Free;
end;
end;
constructor TfrmDissInfo.Create(AParameter:TcnSimpleParamsEx);
begin
Screen.Cursor:=crHourGlass;
inherited Create(AParameter.Owner);
is_admin := AParameter.is_admin;
if AParameter.cnParamsToPakage.DissDownAllContract <> null
then DissDownAllContract_local := AParameter.cnParamsToPakage.DissDownAllContract
else DissDownAllContract_local :=false;
Is_Collect := AParameter.cnParamsToPakage.Is_collect;
DM:=TDM_Diss.Create(Self);
DM.ReadDataSet.SQLs.SelectSQL.Text := 'select * from sys_options'; // просто чтобы убить транзакцию галимую
DM.DB.Handle:=AParameter.Db_Handle;
DM.ReadDataSet.Open;
DM.ReadDataSet.Close;
IsUpload:= false;
IsUpload:= AParameter.cnParamsToPakage.IsUpload;
ID_DOG_ROOT:= AParameter.cnParamsToPakage.ID_DOG_ROOT;
if AParameter.cnParamsToPakage.ID_STUD <> null
then ID_STUD := AParameter.cnParamsToPakage.ID_STUD;
ID_DOG_LAST:= AParameter.cnParamsToPakage.ID_DOG;
ID_DOG_DISS:=-999;
ChangeAMode(AParameter.AMode);
TR_DissHandle:= AParameter.TR_Handle;
if AParameter.AMode = View then
begin
DM.DataSet.SQLs.SelectSQL.Text := 'select * from CN_DT_DOG_DISS_SELECT('
+inttostr(AParameter.cnParamsToPakage.ID_STUD) +','
+inttostr(AParameter.cnParamsToPakage.ID_DOG) +')' ;
DM.DataSet.Open;
if DM.DataSet['ID_DOG_DISS']<> null
then ID_DOG_DISS:= DM.DataSet['ID_DOG_DISS']
else ID_DOG_DISS:=-999;
ID_TYPE_DISS:= DM.DataSet['ID_TYPE_DISS'];
if DM.DataSet['Name_Type_Diss']<> null
then TypeDiss_Edit.Text :=DM.DataSet['Name_Type_Diss'];
if DM.DataSet['DATE_DISS']<> null
then DateDiss.Date :=DM.DataSet['DATE_DISS'];
if DM.DataSet['ORDER_DATE']<> null
then OrderDate.Date :=DM.DataSet['ORDER_DATE'];
if DM.DataSet['ORDER_NUM']<> null
then OrderNum_Edit.Text :=DM.DataSet['ORDER_NUM'];
if DM.DataSet['COMMENT']<> null
then Comments_Edit.Text :=DM.DataSet['COMMENT'];
DM.DataSet.Close;
end;
if AParameter.AMode = Edit then
begin
DM.DataSet.SQLs.SelectSQL.Text := 'select * from CN_DT_DOG_DISS_SELECT('
+inttostr(AParameter.cnParamsToPakage.ID_STUD) +','
+inttostr(AParameter.cnParamsToPakage.ID_DOG) +')' ;
DM.DataSet.Open;
if DM.DataSet['ID_DOG_DISS']<> null
then ID_DOG_DISS:= DM.DataSet['ID_DOG_DISS']
else ID_DOG_DISS:=-999;
if ID_DOG_DISS <> -999 then
begin
ID_TYPE_DISS:= DM.DataSet['ID_TYPE_DISS'];
if DM.DataSet['Name_Type_Diss']<> null
then TypeDiss_Edit.Text :=DM.DataSet['Name_Type_Diss'];
if DM.DataSet['DATE_DISS']<> null
then DateDiss.Date :=DM.DataSet['DATE_DISS'];
if DM.DataSet['ORDER_DATE']<> null
then OrderDate.Date :=DM.DataSet['ORDER_DATE'];
if DM.DataSet['ORDER_NUM']<> null
then OrderNum_Edit.Text :=DM.DataSet['ORDER_NUM'];
if DM.DataSet['COMMENT']<> null
then Comments_Edit.Text :=DM.DataSet['COMMENT'];
end;
DM.DataSet.Close;
end;
Screen.Cursor:=crDefault;
FormIniLanguage();
end;
procedure TfrmDissInfo.FormIniLanguage;
begin
PLanguageIndex:= cn_Common_Funcs.cnLanguageIndex();
Caption := cnConsts.cn_InfoDiss[PLanguageIndex];
DateDiss_Label.Caption:= cnConsts.cn_DateDiss[PLanguageIndex];
OrderDate_Label.Caption:= cnConsts.cn_DateOrderDiss[PLanguageIndex];
OrderNum_Label.Caption:= cnConsts.cn_NumOrderDiss[PLanguageIndex];
Comments_Label.Caption:= cnConsts.cn_CommentDiss[PLanguageIndex];
TypeDiss_Label.Caption:= cnConsts. cn_TypeDiss[PLanguageIndex];
OkButton.Caption:= cnConsts.cn_Accept[PLanguageIndex];
CancelButton.Caption:= cnConsts.cn_Cancel[PLanguageIndex];
SpeedButton.Hint := cnConsts.cn_Cookies[PLanguageIndex];
end;
procedure TfrmDissInfo.CancelButtonClick(Sender: TObject);
begin
close;
end;
procedure TfrmDissInfo.OkButtonClick(Sender: TObject);
function CheckControls: boolean;
begin
Result:= false;
if DateDiss.Text = ''
then
begin
cnShowMessage( PChar(cnConsts_Messages.cn_Error[PLanguageIndex]),
PChar(cnConsts_Messages.cn_DateDiss_Need[PLanguageIndex]) ,
mtError,[mbYes]);
DateDiss.SetFocus;
Result:= true;
exit;
end;
if OrderDate.Text = ''
then
begin
cnShowMessage( PChar(cnConsts_Messages.cn_Error[PLanguageIndex]),
PChar(cnConsts_Messages.cn_DateOrder_Need[PLanguageIndex]) ,
mtError,[mbYes]);
OrderDate.SetFocus;
Result:= true;
exit;
end;
if OrderNum_Edit.Text = ''
then
begin
cnShowMessage( PChar(cnConsts_Messages.cn_Error[PLanguageIndex]),
PChar(cnConsts_Messages.cn_NumOrder_Need[PLanguageIndex]) ,
mtError,[mbYes]);
OrderNum_Edit.SetFocus;
Result:= true;
exit;
end;
end;
var
DissCookies: TDissInfoCookies;
id_order : int64;
DateStart :Tdate;
begin
If CheckControls then exit;
// проверяем дату старта системы
Dm.ReadDataSet.Close;
Dm.ReadDataSet.SelectSQL.Clear;
Dm.ReadDataSet.SelectSQL.Text := 'select CN_DATE_START from CN_PUB_SYS_DATA_GET_ALL';
Dm.ReadDataSet.Open;
if Dm.ReadDataSet['CN_DATE_START'] <> null
then DateStart:= Dm.ReadDataSet['CN_DATE_START']
else DateStart:= strtodate('01.01.1900');
Dm.ReadDataSet.Close;
Dm.ReadDataSet.Close;
Dm.ReadDataSet.SelectSQL.Clear;
Dm.ReadDataSet.SelectSQL.Text := 'select * from CN_GET_TYPEORDERDISS(' + IntToStr(ID_TYPE_DISS)+ ')';
Dm.ReadDataSet.Open;
if Dm.ReadDataSet['ID_ORDERTYPE'] <> null
then id_order :=Dm.ReadDataSet['ID_ORDERTYPE']
else
begin
showmessage('Тип наказу не знайдено! Перевірте "Довідник типів розірвання контракту" ');
Dm.ReadDataSet.Close;
exit;
end;
Dm.ReadDataSet.Close;
res.Date_Diss:= DateDiss.Date;
if not DissDownAllContract_local then
with DM.StProc do
try
Transaction.StartTransaction;
StoredProcName := 'CN_DT_DOG_DISS_ANNUL_CONTRACT';
ParamByName('ID_DOG_ROOT').AsInt64 := ID_DOG_ROOT;
ParamByName('ID_DOG_LAST').AsInt64 := ID_DOG_LAST;
ParamByName('ID_STUD').AsInt64 := ID_STUD;
ParamByName('DATE_DISS').AsDate := DateDiss.Date;
ParamByName('ID_TYPE_DISS').AsInt64 := ID_TYPE_DISS;
ParamByName('ORDER_DATE').AsDate := OrderDate.Date;
ParamByName('ORDER_NUM').AsString := OrderNum_Edit.text;
ParamByName('COMMENT').AsString := Comments_Edit.Text;
ParamByName('IS_COLLECT').AsInteger := is_collect;
if ID_DOG_DISS <> -999
then ParamByName('ID_DOG_DISS_IN').AsInt64 := ID_DOG_DISS
else
ParamByName('ID_DOG_DISS_IN').AsVariant := null;
Prepare;
ExecProc;
// добавляю все приказы по разріву контракта
StoredProcName := 'CN_DT_ORDERS_INSERT';
Prepare;
ParamByName('ID_ORDER').AsInt64 := id_order;
ParamByName('ID_STUD').AsInt64 := ID_STUD;
ParamByName('DATE_ORDER').AsDate := OrderDate.Date;
ParamByName('NUM_ORDER').AsString := OrderNum_Edit.text;
if Comments_Edit.Text=''
then ParamByName('COMMENTS').AsString := 'автоматичне додавання наказу при роботі з розірванням контракту'
else ParamByName('COMMENTS').AsString := Comments_Edit.Text;
ExecProc;
Transaction.Commit;
DissCookies.DateDiss := DateDiss.Date;
DissCookies.OrderDate := OrderDate.Date;
DissCookies.ORDER_NUM := OrderNum_Edit.Text;
DissCookies.Type_Diss := TypeDiss_Edit.Text;
DissCookies.ID_TYPE_DISS := ID_TYPE_DISS;
DissCookies.Comments := Comments_Edit.Text;
SaveCookies(DissCookies);
res.flag := 1;
except
on E:Exception do
begin
cnShowMessage(PChar(cnConsts_Messages.cn_Error[PLanguageIndex]),e.Message,mtError,[mbYes]);
Transaction.Rollback;
res.flag := 0;
end;
end
else
with DM.StProc do
try
//Transaction.StartTransaction;
Transaction.Handle := TR_DissHandle;
StoredProcName := 'CN_DT_DOG_DISSDOWN_ALL';
ParamByName('ID_DOG_ROOT').AsInt64 := ID_DOG_ROOT;
ParamByName('ID_DOG_LAST').AsInt64 := ID_DOG_LAST;
ParamByName('DATE_DISS').AsDate := DateDiss.Date;
ParamByName('ID_TYPE_DISS').AsInt64 := ID_TYPE_DISS;
ParamByName('ORDER_DATE').AsDate := OrderDate.Date;
ParamByName('ORDER_NUM').AsString := OrderNum_Edit.text;
ParamByName('COMMENT').AsString := Comments_Edit.Text;
Prepare;
ExecProc;
// Transaction.Commit;
DissCookies.DateDiss := DateDiss.Date;
DissCookies.OrderDate := OrderDate.Date;
DissCookies.ORDER_NUM := OrderNum_Edit.Text;
DissCookies.Type_Diss := TypeDiss_Edit.Text;
DissCookies.ID_TYPE_DISS := ID_TYPE_DISS;
DissCookies.Comments := Comments_Edit.Text;
SaveCookies(DissCookies);
res.flag := 1;
if IsUpload then
begin
//Transaction.StartTransaction;
StoredProcName := 'CN_DT_DOG_UPLOAD_CLOSE_USE_END';
ParamByName('ID_DOG_ROOT').AsInt64 := ID_DOG_ROOT;
ParamByName('ID_DOG_LAST').AsInt64 := ID_DOG_LAST;
Prepare;
ExecProc;
//Res.TR_Handle:= Transaction.Handle;
//Transaction.Commit;
end
else
// Transaction.Commit;
except
on E:Exception do
begin
cnShowMessage(PChar(cnConsts_Messages.cn_Error[PLanguageIndex]),e.Message,mtError,[mbYes]);
Transaction.Rollback;
res.flag := 0;
end;
end;
close;
end;
procedure TfrmDissInfo.TypeDiss_EditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
AParameter:TcnSimpleParams;
resUlt: Variant;
begin
AParameter:= TcnSimpleParams.Create;
AParameter.Owner:=self;
AParameter.Db_Handle:= DM.DB.Handle;
AParameter.Formstyle:=fsNormal;
AParameter.WaitPakageOwner:=self;
AParameter.is_admin := is_admin;
if ID_TYPE_DISS <> -1 then
AParameter.ID_Locate := ID_TYPE_DISS;
resUlt:= RunFunctionFromPackage(AParameter, 'Contracts\cn_sp_TypeDiss.bpl','ShowSPTypeDiss');
if VarArrayDimCount(resUlt)>0 then
begin
ID_TYPE_DISS := resUlt[0];
TypeDiss_Edit.Text := resUlt[1];
end;
AParameter.Free;
end;
procedure TfrmDissInfo.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
//Dm.Free;
end;
procedure TfrmDissInfo.FormShow(Sender: TObject);
begin
DateDiss.SetFocus;
end;
procedure TfrmDissInfo.DateDissKeyPress(Sender: TObject; var Key: Char);
begin
if key = #13 then OrderDate.SetFocus;
end;
procedure TfrmDissInfo.OrderDateKeyPress(Sender: TObject; var Key: Char);
begin
if key = #13 then OrderNum_Edit.SetFocus;
end;
procedure TfrmDissInfo.OrderNum_EditKeyPress(Sender: TObject;
var Key: Char);
begin
if key = #13 then TypeDiss_Edit.SetFocus;
end;
procedure TfrmDissInfo.TypeDiss_EditKeyPress(Sender: TObject;
var Key: Char);
begin
if key = #13 then Comments_Edit.SetFocus;
end;
procedure TfrmDissInfo.Comments_EditKeyPress(Sender: TObject;
var Key: Char);
begin
if key = #13 then OkButton.SetFocus;
end;
procedure TfrmDissInfo.FormCreate(Sender: TObject);
begin
res.flag := 0;
res.TR_Handle := nil;
end;
procedure TfrmDissInfo.SpeedButtonClick(Sender: TObject);
var
Cookies : TDissInfoCookies;
begin
Cookies := LoadCookies();
DateDiss.Date := Cookies.DateDiss;
OrderDate.Date := Cookies.OrderDate;
OrderNum_Edit.Text := Cookies.ORDER_NUM;
TypeDiss_Edit.Text := Cookies.Type_Diss;
Comments_Edit.Text := Cookies.Comments;
ID_TYPE_DISS := Cookies.ID_TYPE_DISS;
end;
end.
|
unit Ils.Kafka.Emul;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
interface
uses
SysUtils, StrUtils, Classes, Windows, SyncObjs;
//------------------------------------------------------------------------------
const
//------------------------------------------------------------------------------
//! копия из ULibKafka
//------------------------------------------------------------------------------
RD_KAFKA_OFFSET_BEGINNING = -2; (* *< Start consuming from beginning of kafka partition queue:oldest msg *)
RD_KAFKA_OFFSET_END = -1; (* *< Start consuming from end of kafka partition queue:next msg *)
RD_KAFKA_OFFSET_STORED = -1000; (* *< Start consuming from offset retrieved from offset store *)
RD_KAFKA_OFFSET_INVALID = -1001; (* *< Invalid offset *)
// !!! *** внимание !!! интерпретируем любое из этих значений, как RD_KAFKA_OFFSET_BEGINNING *** !!!
//------------------------------------------------------------------------------
type
//------------------------------------------------------------------------------
//! callback-функция логирования
//------------------------------------------------------------------------------
TLogFunc = function(
const AMessage: string;
const ASkipTimeStamp: Boolean = False
): string;
//------------------------------------------------------------------------------
//! callback-функция приёма сообщения kafka-читателя
//------------------------------------------------------------------------------
TOnMessageFunc = function(
const AMessage: AnsiString;
const AOffset: Int64;
const ATopic: AnsiString
): Boolean of object;
//------------------------------------------------------------------------------
//! callback-функция (внутреннее использование)
//------------------------------------------------------------------------------
TCBThreadFunc = procedure of object;
//------------------------------------------------------------------------------
//! поток обработки (внутреннее использование)
//------------------------------------------------------------------------------
TKafkaThread = class(TThread)
protected
procedure Execute(); override;
private
FOnCB: TCBThreadFunc;
public
constructor Create(
const AOnCB: TCBThreadFunc
);
end;
//------------------------------------------------------------------------------
//! эмулятор kafka-писателя
//------------------------------------------------------------------------------
TKafkaProducerEmul = class
private
FOnLog: TLogFunc;
FSync: TCriticalSection;
FFile: TFileStream;
FMsgNum: Int64;
public
constructor Create(
const AFileName: string;
const AOnLog: TLogFunc
);
destructor Destroy(); override;
//!
function Produce(
APayload: AnsiString
): Integer;
//!
property OnLog: TLogFunc read FOnLog write FOnLog;
end;
//------------------------------------------------------------------------------
//! эмулятор kafka-читателя
//------------------------------------------------------------------------------
TKafkaConsumerEmul = class
private
FOnLog: TLogFunc;
FOnMessage: TOnMessageFunc;
FOffset: Int64;
FTopic: AnsiString;
FFile: TFileStream;
FKafkaThread: TKafkaThread;
procedure ConsumeCallback();
public
constructor Create(
const AFileName: string;
const AOnMessage: TOnMessageFunc;
const AOnLog: TLogFunc
);
destructor Destroy(); override;
//!
function Start(
const AOffset: Int64 = RD_KAFKA_OFFSET_INVALID;
const ACreateThread: Boolean = True
): Boolean;
//!
function Stop(): Boolean;
//!
function CheckTryRestart(
var ACheckedOffset: Int64
): Boolean;
//!
function GetMessage(
out RMessage: AnsiString
): Boolean;
//!
property OnLog: TLogFunc read FOnLog write FOnLog;
property NextOffset: Int64 read FOffset;
end;
//------------------------------------------------------------------------------
implementation
//------------------------------------------------------------------------------
// TKafkaProducerEmul
//------------------------------------------------------------------------------
constructor TKafkaProducerEmul.Create(
const AFileName: string;
const AOnLog: TLogFunc
);
begin
inherited Create();
//
FOnLog := AOnLog;
FSync := TCriticalSection.Create();
ForceDirectories(ExtractFilePath(AFileName));
FFile := TFileStream.Create(AFileName, fmCreate or fmShareDenyWrite);
end;
destructor TKafkaProducerEmul.Destroy();
begin
FFile.Free();
FSync.Free();
//
inherited Destroy();
end;
function TKafkaProducerEmul.Produce(
APayload: AnsiString
): Integer;
var
RS: AnsiString;
//------------------------------------------------------------------------------
begin
FSync.Acquire();
try
Result := 0;
Inc(FMsgNum);
RS := AnsiString(IntToStr(FMsgNum)) + AnsiString(':') + APayload + AnsiString(#13#10);
try
FFile.Write(RS[1], Length(RS));
except
on Ex: Exception do
begin
Dec(FMsgNum);
if Assigned(FOnLog) then
FOnLog('Ошибка при попытке вставки сообщения "' + string(APayload) + '" ' + Ex.ClassName + ': ' + Ex.Message);
Result := -1;
end;
end;
finally
FSync.Release();
end;
end;
//------------------------------------------------------------------------------
// TKafkaConsumerEmul
//------------------------------------------------------------------------------
procedure TKafkaConsumerEmul.ConsumeCallback();
var
RS: AnsiString;
R: Boolean;
//------------------------------------------------------------------------------
begin
R := False;
if Assigned(FOnMessage) and GetMessage(RS) then
begin
FKafkaThread.Synchronize(
procedure
begin
try
R := FOnMessage(RS, FOffset, FTopic);
except
end;
end
);
end;
if not R then
Stop();
end;
constructor TKafkaConsumerEmul.Create(
const AFileName: string;
const AOnMessage: TOnMessageFunc;
const AOnLog: TLogFunc
);
begin
inherited Create();
//
FOnLog := AOnLog;
FOnMessage := AOnMessage;
FTopic := AnsiString(ExtractFileName(AFileName));
FOffset := RD_KAFKA_OFFSET_BEGINNING;
FFile := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyNone);
end;
destructor TKafkaConsumerEmul.Destroy();
begin
FKafkaThread.Free();
//
inherited Destroy();
end;
function TKafkaConsumerEmul.Start(
const AOffset: Int64;
const ACreateThread: Boolean
): Boolean;
begin
FOffset := AOffset;
if ACreateThread and not Assigned(FKafkaThread) then
FKafkaThread := TKafkaThread.Create(ConsumeCallback);
Result := True;
end;
function TKafkaConsumerEmul.Stop(): Boolean;
begin
Result := True;
if not Assigned(FKafkaThread) then
Exit;
FKafkaThread.FreeOnTerminate := True;
FKafkaThread.Terminate();
FKafkaThread := nil;
end;
function TKafkaConsumerEmul.CheckTryRestart(
var ACheckedOffset: Int64
): Boolean;
begin
Result := True;
end;
function TKafkaConsumerEmul.GetMessage(
out RMessage: AnsiString
): Boolean;
function ColonPos(
const AStr: AnsiString
): Integer;
begin
for Result := 1 to Length(AStr) do
begin
if (AStr[Result] = ':') then
Exit;
end;
Result := -1;
end;
function ReadStr(): AnsiString;
var
RCh: AnsiChar;
begin
Result := '';
while (FFile.Read(RCh, 1) = 1) do
begin
if (RCh = #13) then
begin
FFile.Read(RCh, 1); // skip #10
Break;
end;
Result := Result + RCh;
end;
end;
var
RS: AnsiString;
SP: Integer;
ReadOffset: Int64;
label R;
//------------------------------------------------------------------------------
begin
Result := False;
try
if (FOffset <= 0) then
FOffset := 1;
R:
RS := ReadStr();
SP := ColonPos(RS);
if (SP = -1) then
Exit;
ReadOffset := StrToInt64Def(string(Copy(RS, 1, SP - 1)), RD_KAFKA_OFFSET_INVALID);
RMessage := Copy(RS, SP + 1, MaxInt);
if (ReadOffset = FOffset) then
begin
Inc(FOffset);
Exit(True);
end
else if (ReadOffset < FOffset) then
begin
goto R;
end
else
begin
FFile.Position := 0;
goto R;
end;
Result := True;
except
on Ex: Exception do
begin
if Assigned(FOnLog) then
FOnLog('Ошибка при попытке получения сообщения "' + string(RS) + '" ' + Ex.ClassName + ': ' + Ex.Message);
end;
end;
end;
//------------------------------------------------------------------------------
// TKafkaThread
//------------------------------------------------------------------------------
constructor TKafkaThread.Create(
const AOnCB: TCBThreadFunc
);
begin
FreeOnTerminate := False;
FOnCB := AOnCB;
//
inherited Create(False);
end;
procedure TKafkaThread.Execute();
begin
while not Terminated do
begin
if Assigned(FOnCB) then
FOnCB();
Windows.Sleep(0);
end;
end;
end.
|
UNIT gbCobranca;
interface
uses
Windows, classes, SysUtils, Graphics, extctrls, Dialogs, QRPDFFilt, QRWebFilt, QRExport
{$IFDEF VER150}
, Variants, MaskUtils, contnrs, IdMessage, IdBaseComponent, IdComponent,
IdTCPConnection, IdTCPClient, IdMessageClient, IdSMTP, gbBoleto7
{$ENDIF}
{$IFDEF VER140}
, Variants, MaskUtils, contnrs, NMSMTP, gbBoleto6
{$ENDIF}
{$IFDEF VER130}
, Mask, contnrs, NMSMTP, gbBoleto5
{$ENDIF}
{$IFDEF VER120}
, Mask, gbBoleto4
{$ENDIF}
;
type
{Classe para gerar código de barras para boletos}
TgbCobCodBar = class
private
fCodigo: string; {Dados que serão incluídos no código de barras}
function GetLinhaDigitavel : string; {Retorna a representação numérica do código de barras}
function Define2de5 : string; {Define o formato do código de barras INTERCALADO 2 DE 5, retornando a seqüência de 0 e 1 que será usada para gerar a imagem do código de barras}
function GetImagem : TImage; {Gera a imagem do código de barras}
public
property Codigo : string read fCodigo write fCodigo;
property LinhaDigitavel : string read GetLinhaDigitavel;
property Imagem : TImage read GetImagem;
end;
{TgbEndereco representa o endereço de cedentes ou sacados}
TEstado = string[2];
TCEP = string[8];
TgbEndereco = class(TPersistent)
public
fRua,
fNumero,
fComplemento,
fBairro,
fCidade,
fEMail : string;
fEstado : TEstado;
fCEP : TCEP;
procedure Assign(AEndereco: TgbEndereco); reintroduce;
published
property Rua : string read fRua write fRua;
property Numero : string read fNumero write fNumero;
property Complemento : string read fComplemento write fComplemento;
property Bairro : string read fBairro write fBairro;
property Cidade : string read fCidade write fCidade;
property Estado : TEstado read fEstado write fEstado;
property CEP : TCEP read fCEP write fCEP;
property EMail : string read fEMail write fEMail;
end;
{Informações sobre o banco}
TgbBanco = class(TPersistent)
private
fCodigo : string; {Código do banco na câmara de compensação}
procedure SetCodigo(ACodigoBanco : string);
function GetDigito : string; {Retorna o dígito do código do banco}
function GetNome : string; {Retorna o nome do banco}
public
procedure Assign(ABanco: TgbBanco); reintroduce;
published
property Codigo : string read fCodigo write SetCodigo;
property Digito : string read GetDigito;
property Nome : string read GetNome;
end;
{Dados da conta bancária de cedentes ou sacados}
TgbContaBancaria = class(TPersistent)
public
fBanco : TgbBanco; {Banco onde a pessoa tem conta}
fCodigoAgencia, {Código da agência}
fDigitoAgencia, {Dígito verificador do número da agência}
fNumeroConta, {Número da conta}
fDigitoConta, {Dígito verificador do número da conta}
fNomeCliente : string; {Nome do cliente titular da conta}
constructor Create;
destructor Destroy; override;
procedure Assign(AContaBancaria: TgbContaBancaria); reintroduce;
published
property Banco : TgbBanco read fBanco write fBanco;
property CodigoAgencia : string read fCodigoAgencia write fCodigoAgencia;
property DigitoAgencia : string read fDigitoAgencia write fDigitoAgencia;
property NumeroConta : string read fNumeroConta write fNumeroConta;
property DigitoConta : string read fDigitoConta write fDigitoConta;
property NomeCliente : string read fNomeCliente write fNomeCliente;
end;
TTipoInscricao = (tiPessoaFisica, tiPessoaJuridica, tiOutro);
{Dados sobre os cedentes ou sacados}
TgbPessoa = class(TPersistent)
private
fTipoInscricao: TTipoInscricao;
fNumeroCPFCGC ,
fNome : string;
fEndereco : TgbEndereco;
fContaBancaria: TgbContaBancaria;
public
constructor Create;
destructor Destroy; override;
procedure Assign(APessoa: TgbPessoa); reintroduce;
published
property TipoInscricao: TTipoInscricao read fTipoInscricao write fTipoInscricao;
property NumeroCPFCGC : string read fNumeroCPFCGC write fNumeroCPFCGC;
property Nome : string read fNome write fNome;
property Endereco : TgbEndereco read fEndereco write fEndereco;
property ContaBancaria: TgbContaBancaria read fContaBancaria write fContaBancaria;
end;
{Dados completos sobre o cedente - Classe derivada de TgbPessoa}
TgbCedente = class(TgbPessoa)
private
fCodigoCedente,
fDigitoCodigoCedente : string;
public
procedure Assign(ACedente: TgbCedente);
published
property CodigoCedente : string read fCodigoCedente write fCodigoCedente;
property DigitoCodigoCedente : string read fDigitoCodigoCedente write fDigitoCodigoCedente;
end;
{Especifica o tipo de documento que gerou o título}
TEspecieDocumento =
(
edAluguel,
edApoliceSeguro,
edCheque,
edContrato,
edContribuicaoConfederativa,
edCosseguros,
edDividaAtivaEstado,
edDividaAtivaMunicipio,
edDividaAtivaUniao,
edDuplicataMercantil,
edDuplicataMercantialIndicacao,
edDuplicataRural,
edDuplicataServico,
edDuplicataServicoIndicacao,
edFatura,
edLetraCambio,
edMensalidadeEscolar,
edNotaCreditoComercial,
edNotaCreditoExportacao,
edNotaCreditoIndustrial,
edNotaCreditoRural,
edNotaDebito,
edNotaPromissoria,
edNotaPromissoriaRural,
edNotaSeguro,
edOutros,
edParcelaConsorcio,
edRecibo,
edTriplicataMercantil,
edTriplicataServico,
edWarrant
);
TAceiteDocumento = (adSim, adNao);
{Indica quem emite o boleto: banco ou cliente}
TEmissaoBoleto =
(
ebBancoEmite,
ebClienteEmite,
ebBancoReemite,
ebBancoNaoReemite
);
{Tipos de ocorrências permitidas no arquivos remessa / retorno}
TTipoOcorrencia =
(
{Ocorrências para arquivo remessa}
toRemessaRegistrar, {Registrar o título no banco}
toRemessaBaixar, {Baixar o título no banco}
toRemessaDebitarEmConta,
toRemessaConcederAbatimento,
toRemessaCancelarAbatimento,
toRemessaConcederDesconto,
toRemessaCancelarDesconto,
toRemessaAlterarVencimento,
toRemessaProtestar,
toRemessaCancelarInstrucaoProtesto,
toRemessaDispensarJuros,
toRemessaAlterarNomeEnderecoSacado,
toRemessaAlterarNumeroControle,
toRemessaOutrasOcorrencias,
{Ocorrências para arquivo retorno}
toRetornoRegistroConfirmado,
toRetornoRegistroRecusado,
toRetornoComandoRecusado,
toRetornoLiquidado,
toRetornoLiquidadoEmCartorio,
toRetornoLiquidadoParcialmente,
toRetornoLiquidadoSaldoRestante,
toRetornoLiquidadoSemRegistro,
toRetornoLiquidadoPorConta,
toRetornoBaixaSolicitada,
toRetornoBaixado,
toRetornoBaixadoPorDevolucao,
toRetornoBaixadoFrancoPagamento,
toRetornoBaixaPorProtesto,
toRetornoRecebimentoInstrucaoBaixar,
toRetornoBaixaOuLiquidacaoEstornada,
toRetornoTituloEmSer,
toRetornoRecebimentoInstrucaoConcederAbatimento,
toRetornoAbatimentoConcedido,
toRetornoRecebimentoInstrucaoCancelarAbatimento,
toRetornoAbatimentoCancelado,
toRetornoRecebimentoInstrucaoConcederDesconto,
toRetornoDescontoConcedido,
toRetornoRecebimentoInstrucaoCancelarDesconto,
toRetornoDescontoCancelado,
toRetornoRecebimentoInstrucaoAlterarDados,
toRetornoDadosAlterados,
toRetornoRecebimentoInstrucaoAlterarVencimento,
toRetornoVencimentoAlterado,
toRetornoAlteracaoDadosNovaEntrada,
toRetornoAlteracaoDadosBaixa,
toRetornoRecebimentoInstrucaoProtestar,
toRetornoProtestado,
toRetornoRecebimentoInstrucaoSustarProtesto,
toRetornoProtestoSustado,
toRetornoInstrucaoProtestoRejeitadaSustadaOuPendente,
toRetornoDebitoEmConta,
toRetornoRecebimentoInstrucaoAlterarNomeSacado,
toRetornoNomeSacadoAlterado,
toRetornoRecebimentoInstrucaoAlterarEnderecoSacado,
toRetornoEnderecoSacadoAlterado,
toRetornoEncaminhadoACartorio,
toRetornoRetiradoDeCartorio,
toRetornoRecebimentoInstrucaoDispensarJuros,
toRetornoJurosDispensados,
toRetornoManutencaoTituloVencido,
toRetornoRecebimentoInstrucaoAlterarTipoCobranca,
toRetornoTipoCobrancaAlterado,
toRetornoDespesasProtesto,
toRetornoDespesasSustacaoProtesto,
toRetornoDebitoCustasAntecipadas,
toRetornoCustasCartorioDistribuidor,
toRetornoCustasEdital,
toRetornoProtestoOuSustacaoEstornado,
toRetornoDebitoTarifas,
toRetornoAcertoDepositaria,
toRetornoOutrasOcorrencias
);
{Representa um título e todas as rotinas associadas}
TgbTitulo = class(TComponent)
private
fTipoOcorrencia : TTipoOcorrencia; {Tipo de ocorrência: registro de título, liquidação normal, pedido de baixa, etc...}
fOcorrenciaOriginal : string; {Indica o código da ocorrência no banco}
fDescricaoOcorrenciaOriginal : string;
fMotivoRejeicaoComando : string; {Indica o código do motivo porque o título / comando foi recusado. Usado apenas para receber informações do banco}
fDescricaoMotivoRejeicaoComando : string;
fCedente : TgbCedente; {Aquele que emitiu o título}
fSacado : TgbPessoa; {Devedor}
fLocalPagamento, {Local onde o título deverá ser pago}
fSeuNumero, {Número que identifica o título na empresa}
fNossoNumero, {Número que identifica o título no banco}
fNumeroDocumento, {Número do documento que gerou o título (número da nota fiscal, por exemplo)}
fCarteira : string; {Carteira do título, conforme informado pelo banco}
fAceiteDocumento : TAceiteDocumento;
fEspecieDocumento: TEspecieDocumento; {Tipo de documento que gerou o título}
fDataProcessamento, {Data em que o boleto bancário foi gerado}
fDataDocumento, {Data da emissão do documento que gerou o título (data da emissão da nota fiscal, por exemplo)}
fDataVencimento, {Data do vencimento do título}
fDataOcorrencia, {Data da ocorrência em questão (pagamento do título, recebimento de instrução, etc)}
fDataCredito, {Data em que o banco liberará o dinheiro para o cedente}
fDataAbatimento, {Data até a qual deverá ser concedido abatimento}
fDataDesconto, {Data até a qual deverá ser concedido desconto}
fDataMoraJuros, {Data a partir da qual deverão ser cobrados juros / mora}
fDataProtesto, {Data em que o título deverá ser protestado em caso de falta de pagamento}
fDataBaixa: TDateTime; {Data em que o título deverá ser baixado}
fValorDocumento, {Valor do título}
fValorDespesaCobranca, {Valor que o banco cobrou pelo serviço de cobrança}
fValorAbatimento, {Valor do abatimento a conceder / concedido ao sacado}
fValorDesconto, {Valor do desconto diário a conceder (remessa) ou desconto total concedido (retorno) ao sacado}
fValorMoraJuros, {Valor dos juros / multa cobrados do sacado}
fValorIOF, {Valor do Imposto sobre Operações Financeiras}
fValorOutrasDespesas, {Valor de outras despesas cobradas pelo banco: protesto de títulos, por exemplo}
fValorOutrosCreditos : Currency; {Valor de outros créditos que o banco repassará ao cedente}
fInstrucoes : TStringList; {Instruções incluídas no título}
fEmissaoBoleto: TEmissaoBoleto; {Indica quem emite o boleto: banco ou cliente}
procedure SetInstrucoes(Texto: TStringList);
function GerarCodigoBarra : TgbCobCodBar; {Retorna um objeto do tipo TgbCobCodBar contendo linha digitável e imagem do código de barras baseados nos dados do título}
function CalcularDigitoNossoNumero : string; {Calcula o dígito do NossoNumero, conforme critérios definidos por cada banco}
procedure PrepararBoleto(ABoleto: TBoleto); {Atribui valores aos campos do boleto antes que ele seja impresso }
function GetImagemBoleto : TImage; {Gera a imagem do boleto}
function GetImagemFichaCompensacao : TImage; {Gera a imagem da ficha de compensação}
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Assign(ATitulo: TgbTitulo); reintroduce;
procedure EnviarPorEMail(Host, LoginUsuario : string; Porta :integer; Assunto : string; Mensagem : TStringList);
procedure Visualizar;
procedure Imprimir;
property CodigoBarra : TgbCobCodBar read GerarCodigoBarra;
property DigitoNossoNumero : string read CalcularDigitoNossoNumero;
property ImagemBoleto : TImage read GetImagemBoleto;
property ImagemFichaCompensacao : TImage read GetImagemFichaCompensacao;
published
property TipoOcorrencia : TTipoOcorrencia read fTipoOcorrencia write fTipoOcorrencia;
property OcorrenciaOriginal : string read fOcorrenciaOriginal write fOcorrenciaOriginal;
property DescricaoOcorrenciaOriginal : string read fDescricaoOcorrenciaOriginal write fDescricaoOcorrenciaOriginal;
property MotivoRejeicaoComando : string read fMotivoRejeicaoComando write fMotivoRejeicaoComando;
property DescricaoMotivoRejeicaoComando : string read fDescricaoMotivoRejeicaoComando write fMotivoRejeicaoComando;
property LocalPagamento : string read fLocalPagamento write fLocalPagamento;
property Cedente : TgbCedente read fCedente write fCedente;
property Sacado : TgbPessoa read fSacado write fSacado;
property SeuNumero : string read fSeuNumero write fSeuNumero;
property NossoNumero : string read fNossoNumero write fNossoNumero;
property NumeroDocumento : string read fNumeroDocumento write fNumeroDocumento;
property Carteira : string read fCarteira write fCarteira;
property AceiteDocumento : TAceiteDocumento read fAceiteDocumento write fAceiteDocumento;
property EspecieDocumento: TEspecieDocumento read fEspecieDocumento write fEspecieDocumento;
property DataProcessamento : TDateTime read fDataProcessamento write fDataProcessamento;
property DataDocumento : TDateTime read fDataDocumento write fDataDocumento;
property DataVencimento : TDateTime read fDataVencimento write fDataVencimento;
property DataOcorrencia : TDateTime read fDataOcorrencia write fDataOcorrencia;
property DataCredito : TDateTime read fDataCredito write fDataCredito;
property DataAbatimento : TDateTime read fDataAbatimento write fDataAbatimento;
property DataDesconto : TDateTime read fDataDesconto write fDataDesconto;
property DataMoraJuros : TDateTime read fDataMoraJuros write fDataMoraJuros;
property DataProtesto : TDateTime read fDataProtesto write fDataProtesto;
property DataBaixa : TDateTime read fDataBaixa write fDataBaixa;
property ValorDocumento : Currency read fValorDocumento write fValorDocumento;
property ValorDespesaCobranca : Currency read fValorDespesaCobranca write fValorDespesaCobranca;
property ValorAbatimento : Currency read fValorAbatimento write fValorAbatimento;
property ValorDesconto : Currency read fValorDesconto write fValorDesconto;
property ValorMoraJuros : Currency read fValorMoraJuros write fValorMoraJuros;
property ValorIOF : Currency read fValorIOF write fValorIOF;
property ValorOutrasDespesas : Currency read fValorOutrasDespesas write fValorOutrasDespesas;
property ValorOutrosCreditos : Currency read fValorOutrosCreditos write fValorOutrosCreditos;
property Instrucoes : TStringList read fInstrucoes write SetInstrucoes;
property EmissaoBoleto : TEmissaoBoleto read fEmissaoBoleto write fEmissaoBoleto;
end;
{$IFNDEF VER120}
{Representa uma lista de títulos - Objetos do tipo gbTitulo}
TgbTituloList = class(TObjectList)
protected
function GetItem(Index: Integer): TgbTitulo; {Retorna o objeto TgbTitulo que está na posição definida por Index}
procedure SetItem(Index: Integer; ATitulo : TgbTitulo); {Altera o objeto TgbTitulo que está na posição definida por Index}
public
constructor Create;
function Add(ATitulo : TgbTitulo) : integer; {Insere o título no final da coleção}
function Remove(ATitulo : TgbTitulo): Integer; {Remove da coleção o título}
function IndexOf(ATitulo : TgbTitulo): Integer; {Retorna a posição onde está localizado o título na coleção}
function FindInstanceOf(AClass: TClass; AExact: Boolean = True; AStartAt: Integer = 0): Integer;
procedure Insert(Index: Integer; ATitulo : TgbTitulo); {Insere o título no final da coleção na posição indicada por Index}
property Items[Index : integer] : TgbTitulo read GetItem write SetItem; default;
end;
{Indica o layout do arquivo remessa / retorno, incluindo tamanho de cada registro, o
os tipos de registros permitidos e o significado dos campos contidos no arquivo}
TLayoutArquivo = (laCNAB240, laCNAB400, laOutro);
{Indica o tipo de movimento desejado}
TTipoMovimento = (tmRemessa, tmRetorno, tmRemessaTeste, tmRetornoTeste, tmOutro);
{Representa um conjunto de títulos que serão tratados juntos em alguma rotina.
Por exemplo: processamento de arquivo retorno e geração de arquivo remessa}
TgbCobranca = class(TComponent)
private
fNomeArquivo : string; {Nome do arquivo remessa ou retorno}
fNumeroArquivo : integer; {Número seqüencial do arquivo remessa ou retorno}
fDataArquivo : TDateTime; {Data da geração do arquivo remessa ou retorno}
fLayoutArquivo: TLayoutArquivo; {Layout do arquivo remessa / retorno}
fTipoMovimento: TTipoMovimento; {Tipo de movimento desejado: remessa, retorno, etc...}
fTitulos : TgbTituloList; {Títulos incluídos no arquivo remessa ou retorno}
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function LerRetorno : boolean; {Lê o arquivo retorno recebido do banco}
function GerarRemessa : boolean; {Gerar arquivo remessa para enviar ao banco}
function GerarRelatorio : TStringList; {Gera as informações que serão apresentadas na propriedade Relatório}
property Titulos : TgbTituloList read fTitulos write fTitulos;
property Relatorio : TStringList read GerarRelatorio;
published
property NomeArquivo : string read fNomeArquivo write fNomeArquivo;
property NumeroArquivo : integer read fNumeroArquivo write fNumeroArquivo;
property DataArquivo : TDateTime read fDataArquivo write fDataArquivo;
property LayoutArquivo : TLayoutArquivo read fLayoutArquivo write fLayoutArquivo;
property TipoMovimento : TTipoMovimento read fTipoMovimento write fTipoMovimento;
end;
{$ENDIF}
procedure Register; {Registra os componentes no Delphi}
function Formatar(Texto : string; TamanhoDesejado : integer; AcrescentarADireita : boolean = true; CaracterAcrescentar : char = ' ') : string;
function FormatarComMascara(StringFormato, Texto: string): string;
function Modulo10(Valor: String) : string;
function Modulo11(Valor: String; Base: Integer = 9; Resto : boolean = false) : string;
function CalcularFatorVencimento(DataDesejada : TDateTime) : string;
{$IFDEF VER130}
{Calcula a diferença de dias entre duas datas. No Delphi 6 a função já existe na unit DATEUTILS}
function DaysBetween(DataMaior, DataMenor: TDateTime): integer;
{$ENDIF}
var
NossoNumeroBoleto :String;
implementation
uses gbCob001, gbCob021, gbCob033, gbCob038, gbCob104, gbCob151, gbCob237, gbCob244, gbCob275, gbCob291, gbCob320, gbCob341, gbCob347, gbCob353, gbCob389, gbCob394, gbCob399, gbCob409, gbCob422, gbCob479, gbCob745, gbCob041;
Procedure Register;
begin
RegisterComponents('GBSoft',[TgbTitulo]);
{$IFNDEF VER120}
RegisterComponents('GBSoft',[TgbCobranca]);
{$ENDIF}
end;
{Rotinas auxiliares}
function CalcularFatorVencimento(DataDesejada : TDateTime) : string;
{O fator de vencimento é a quantidade de dias entre 07/Nov/1997 e a data de vencimento do título}
begin
Result := IntToStr( Trunc(DataDesejada - EncodeDate(1997,10,07)));
end;
function Modulo10(Valor: String) : string;
{
Rotina usada para cálculo de alguns dígitos verificadores
Pega-se cada um dos dígitos contidos no parâmetro VALOR, da direita para a
esquerda e multiplica-se por 2121212...
Soma-se cada um dos subprodutos. Caso algum dos subprodutos tenha mais de um
dígito, deve-se somar cada um dos dígitos. (Exemplo: 7*2 = 14 >> 1+4 = 5)
Divide-se a soma por 10.
Faz-se a operação 10-Resto da divisão e devolve-se o resultado dessa operação
como resultado da função Modulo10.
Obs.: Caso o resultado seja maior que 9, deverá ser substituído por 0 (ZERO).
}
var
Auxiliar : string;
Contador, Peso : integer;
Digito : integer;
begin
Auxiliar := '';
Peso := 2;
for Contador := Length(Valor) downto 1 do
begin
Auxiliar := IntToStr(StrToInt(Valor[Contador]) * Peso) + Auxiliar;
if Peso = 1 then
Peso := 2
else
Peso := 1;
end;
Digito := 0;
for Contador := 1 to Length(Auxiliar) do
begin
Digito := Digito + StrToInt(Auxiliar[Contador]);
end;
Digito := 10 - (Digito mod 10);
if (Digito > 9) then
Digito := 0;
Result := IntToStr(Digito);
end;
function Modulo11(Valor: String; Base: Integer = 9; Resto : boolean = false) : string;
{
Rotina muito usada para calcular dígitos verificadores
Pega-se cada um dos dígitos contidos no parâmetro VALOR, da direita para a
esquerda e multiplica-se pela seqüência de pesos 2, 3, 4 ... até BASE.
Por exemplo: se a base for 9, os pesos serão 2,3,4,5,6,7,8,9,2,3,4,5...
Se a base for 7, os pesos serão 2,3,4,5,6,7,2,3,4...
Soma-se cada um dos subprodutos.
Divide-se a soma por 11.
Faz-se a operação 11-Resto da divisão e devolve-se o resultado dessa operação
como resultado da função Modulo11.
Obs.: Caso o resultado seja maior que 9, deverá ser substituído por 0 (ZERO).
}
var
Soma : integer;
Contador, Peso, Digito : integer;
begin
Soma := 0;
Peso := 2;
for Contador := Length(Valor) downto 1 do
begin
Soma := Soma + (StrToInt(Valor[Contador]) * Peso);
if Peso < Base then
Peso := Peso + 1
else
Peso := 2;
end;
if Resto then
Result := IntToStr(Soma mod 11)
else
begin
Digito := 11 - (Soma mod 11);
if (Digito > 9) then
Digito := 0;
Result := IntToStr(Digito);
end
end;
function Formatar(Texto : string; TamanhoDesejado : integer; AcrescentarADireita : boolean = true; CaracterAcrescentar : char = ' ') : string;
{
OBJETIVO: Eliminar caracteres inválidos e acrescentar caracteres à esquerda ou à direita do texto original para que a string resultante fique com o tamanho desejado
Texto : Texto original
TamanhoDesejado: Tamanho que a string resultante deverá ter
AcrescentarADireita: Indica se o carácter será acrescentado à direita ou à esquerda
TRUE - Se o tamanho do texto for MENOR que o desejado, acrescentar carácter à direita
Se o tamanho do texto for MAIOR que o desejado, eliminar últimos caracteres do texto
FALSE - Se o tamanho do texto for MENOR que o desejado, acrescentar carácter à esquerda
Se o tamanho do texto for MAIOR que o desejado, eliminar primeiros caracteres do texto
CaracterAcrescentar: Carácter que deverá ser acrescentado
}
var
QuantidadeAcrescentar,
TamanhoTexto,
PosicaoInicial,
i : integer;
begin
case CaracterAcrescentar of
'0'..'9','a'..'z','A'..'Z' : ;{Não faz nada}
else
CaracterAcrescentar := ' ';
end;
Texto := Trim(AnsiUpperCase(Texto));
TamanhoTexto := Length(Texto);
for i := 1 to (TamanhoTexto) do
begin
if Pos(Texto[i],' 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`~''"!@#$%^&*()_-+=|/\{}[]:;,.<>') = 0 then
begin
case Texto[i] of
'Á','À','Â','Ä','Ã' : Texto[i] := 'A';
'É','È','Ê','Ë' : Texto[i] := 'E';
'Í','Ì','Î','Ï' : Texto[i] := 'I';
'Ó','Ò','Ô','Ö','Õ' : Texto[i] := 'O';
'Ú','Ù','Û','Ü' : Texto[i] := 'U';
'Ç' : Texto[i] := 'C';
'Ñ' : Texto[i] := 'N';
else Texto[i] := ' ';
end;
end;
end;
QuantidadeAcrescentar := TamanhoDesejado - TamanhoTexto;
if QuantidadeAcrescentar < 0 then
QuantidadeAcrescentar := 0;
if CaracterAcrescentar = '' then
CaracterAcrescentar := ' ';
if TamanhoTexto >= TamanhoDesejado then
PosicaoInicial := TamanhoTexto - TamanhoDesejado + 1
else
PosicaoInicial := 1;
if AcrescentarADireita then
Texto := Copy(Texto,1,TamanhoDesejado) + StringOfChar(CaracterAcrescentar,QuantidadeAcrescentar)
else
Texto := StringOfChar(CaracterAcrescentar,QuantidadeAcrescentar) + Copy(Texto,PosicaoInicial,TamanhoDesejado);
Result := AnsiUpperCase(Texto);
end;
function FormatarComMascara(StringFormato, Texto: string): string;
begin
Result := FormatMaskText(StringFormato,Texto);
end;
{$IFDEF VER130}
{Calcula a diferença entre duas datas. No Delphi 6 a função já existe na unit DATEUTILS}
function DaysBetween(DataMaior, DataMenor: TDateTime): integer;
begin
Result := Trunc(DataMaior - DataMenor);
end;
{$ENDIF}
{TgbCobCodBar}
function TgbCobCodBar.Define2de5 : string;
{Traduz dígitos do código de barras para valores de 0 e 1, formando um código do tipo Intercalado 2 de 5}
var
CodigoAuxiliar : string;
Start : string;
Stop : string;
T2de5 : array[0..9] of string;
Codifi : string;
I : integer;
begin
Result := 'Erro';
Start := '0000';
Stop := '100';
T2de5[0] := '00110';
T2de5[1] := '10001';
T2de5[2] := '01001';
T2de5[3] := '11000';
T2de5[4] := '00101';
T2de5[5] := '10100';
T2de5[6] := '01100';
T2de5[7] := '00011';
T2de5[8] := '10010';
T2de5[9] := '01010';
{ Digitos }
for I := 1 to length(Codigo) do
begin
if pos(Codigo[I],'0123456789') <> 0 then
Codifi := Codifi + T2de5[StrToInt(Codigo[I])]
else
Exit;
end;
{Se houver um número ímpar de dígitos no Código, acrescentar um ZERO no início}
if odd(length(Codigo)) then
Codifi := T2de5[0] + Codifi;
{Intercalar números - O primeiro com o segundo, o terceiro com o quarto, etc...}
I := 1;
CodigoAuxiliar := '';
while I <= (length(Codifi) - 9)do
begin
CodigoAuxiliar := CodigoAuxiliar + Codifi[I] + Codifi[I+5] + Codifi[I+1] + Codifi[I+6] + Codifi[I+2] + Codifi[I+7] + Codifi[I+3] + Codifi[I+8] + Codifi[I+4] + Codifi[I+9];
I := I + 10;
end;
{ Acrescentar caracteres Start e Stop }
Result := Start + CodigoAuxiliar + Stop;
end;
function TgbCobCodBar.GetLinhaDigitavel : string;
{
A linha digitável é baseada na informações do código de barras.
As informações que fazem parte do código de barras são:
Posição Conteúdo
1 a 3 Número do banco
4 Código da Moeda - 9 para Real
5 Digito verificador do Código de Barras
6 a 19 Valor (12 inteiros e 2 decimais)
20 a 44 Campo Livre definido por cada banco
}
var
p1, p2, p3, p4, p5, p6,
Campo1, Campo2, Campo3, Campo4, Campo5 : string;
begin
{
Campo 1 - composto pelo código do banco, código da moeda, as cinco primeiras posições
do campo livre e DV (modulo10) desse campo
}
p1 := Copy(Codigo,1,4);
p2 := Copy(Codigo,20,5);
p3 := Modulo10(p1+p2);
p4 := p1+p2+p3;
p5 := Copy(p4,1,5);
p6 := Copy(p4,6,5);
Campo1 := p5+'.'+p6;
{
Campo 2 - composto pelas posiçoes 6 a 15 do campo livre
e DV (modulo10) deste campo
}
p1 := Copy(Codigo,25,10);
p2 := Modulo10(p1);
p3 := p1+p2;
p4 := Copy(p3,1,5);
p5 := Copy(p3,6,6);
Campo2 := p4+'.'+p5;
{
Campo 3 - composto pelas posicoes 16 a 25 do campo livre
e DV (modulo10) deste campo
}
p1 := Copy(Codigo,35,10);
p2 := Modulo10(p1);
p3 := p1+p2;
p4 := Copy(p3,1,5);
p5 := Copy(p3,6,6);
Campo3 := p4+'.'+p5;
{
Campo 4 - digito verificador do codigo de barras
}
Campo4 := Copy(Codigo,5,1);
{
Campo 5 - composto pelo valor nominal do documento, sem indicacao
de zeros a esquerda e sem edicao (sem ponto e virgula). Quando se
tratar de valor zerado, a representacao deve ser 000 (tres zeros).
}
Campo5 := Copy(Codigo,6,14);
Result := Campo1 + ' ' + Campo2 + ' ' + Campo3 + ' ' + Campo4 + ' ' + Campo5;
end;
function TgbCobCodBar.GetImagem : TImage;
const
CorBarra = clBlack;
CorEspaco = clWhite;
LarguraBarraFina = 1;
LarguraBarraGrossa = 3;
AlturaBarra = 50;
var
X : integer;
Col : integer;
Lar : integer;
CodigoAuxiliar : string;
begin
CodigoAuxiliar := Define2de5;
Result := TImage.Create(nil);
Result.Height := AlturaBarra;
Result.Width := 0;
For X := 1 to Length(CodigoAuxiliar) do
case CodigoAuxiliar[X] of
'0' : Result.Width := Result.Width + LarguraBarraFina;
'1' : Result.Width := Result.Width + LarguraBarraGrossa;
end;
Col := 0;
if CodigoAuxiliar <> 'Erro' then
begin
for X := 1 to length(CodigoAuxiliar) do
begin
{Desenha barra}
with Result.Canvas do
begin
if Odd(X) then
Pen.Color := CorBarra
else
Pen.Color := CorEspaco;
if CodigoAuxiliar[X] = '0' then
begin
for Lar := 1 to LarguraBarraFina do
begin
MoveTo(Col,0);
LineTo(Col,AlturaBarra);
Col := Col + 1;
end;
end
else
begin
for Lar := 1 to LarguraBarraGrossa do
begin
MoveTo(Col,0);
LineTo(Col,AlturaBarra);
Col := Col + 1;
end;
end;
end;
end;
end
else
Result.Canvas.TextOut(0,0,'Erro');
end;
{TgbEndereco}
procedure TgbEndereco.Assign(AEndereco: TgbEndereco);
begin
Rua := AEndereco.Rua;
Numero := AEndereco.Numero;
Complemento := AEndereco.Complemento;
Bairro := AEndereco.Bairro;
Cidade := AEndereco.Cidade;
Estado := AEndereco.Estado;
CEP := AEndereco.CEP;
EMail := AEndereco.EMail;
end;
{TgbBanco}
procedure TgbBanco.SetCodigo(ACodigoBanco: string);
begin
ACodigoBanco := Formatar(ACodigoBanco,3,false,'0');
if (ACodigoBanco = '000') then
fCodigo := ''
else if (ACodigoBanco <> fCodigo) then
fCodigo := ACodigoBanco;
end;
procedure TgbBanco.Assign(ABanco : TgbBanco);
begin
Codigo := ABanco.Codigo;
end;
function TgbBanco.GetDigito : string;
begin
if Codigo = '' then
Result := ''
else
Result := Modulo11(Codigo,9);
end;
function TgbBanco.GetNome : string;
var
ACodigoBanco: string;
AClasseBanco: TPersistentClass;
ABanco: TPersistent;
GetNomeBanco: function: string of object;
begin
ACodigoBanco := Formatar(Codigo,3,false,'0');
GetNomeBanco := nil;
AClasseBanco := GetClass('TgbBanco'+ACodigoBanco);
if AClasseBanco <> nil then
begin
ABanco := AClasseBanco.Create;
TRY
@GetNomeBanco := ABanco.MethodAddress('GetNomeBanco');
if @GetNomeBanco <> nil then
Result := GetNomeBanco
else
Raise Exception.CreateFmt('O nome do banco %s não está disponível',[ACodigoBanco]);
ABanco.Free;
EXCEPT
ABanco.Free;
Raise;
END;
end
else
Raise Exception.CreateFmt('O banco %s não está disponível',[ACodigoBanco]);
end;
{TgbContaBancaria}
constructor TgbContaBancaria.Create;
begin
inherited Create;
Banco := TgbBanco.Create;
end;
destructor TgbContaBancaria.Destroy;
begin
Banco.Destroy;
inherited Destroy;
end;
procedure TgbContaBancaria.Assign(AContaBancaria: TgbContaBancaria);
begin
Banco.Assign(AContaBancaria.Banco);
CodigoAgencia := AContaBancaria.CodigoAgencia;
DigitoAgencia := AContaBancaria.DigitoAgencia;
NumeroConta := AContaBancaria.NumeroConta;
DigitoConta := AContaBancaria.DigitoConta;
NomeCliente := AContaBancaria.NomeCliente;
end;
{TgbPessoa}
constructor TgbPessoa.Create;
begin
inherited Create;
Endereco := TgbEndereco.Create;
ContaBancaria := TgbContaBancaria.Create;
end;
destructor TgbPessoa.Destroy;
begin
Endereco.Destroy;
ContaBancaria.Destroy;
inherited Destroy;
end;
procedure TgbPessoa.Assign(APessoa: TgbPessoa);
begin
TipoInscricao := APessoa.TipoInscricao;
NumeroCPFCGC := APessoa.NumeroCPFCGC;
Nome := APessoa.Nome;
Endereco.Assign(APessoa.Endereco);
ContaBancaria.Assign(APessoa.ContaBancaria)
end;
procedure TgbCedente.Assign(ACedente: TgbCedente);
begin
inherited Assign(ACedente);
CodigoCedente := ACedente.CodigoCedente;
DigitoCodigoCedente := ACedente.DigitoCodigoCedente;
end;
{TgbTitulo}
constructor TgbTitulo.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fCedente := TgbCedente.Create;
fSacado := TgbPessoa.Create;
fInstrucoes := TStringList.Create;
fLocalPagamento := 'PAGÁVEL EM QUALQUER BANCO ATÉ O VENCIMENTO';
fOcorrenciaOriginal := '';
fTipoOcorrencia := toRemessaRegistrar;
fEspecieDocumento := edRecibo;
fAceiteDocumento := adNao;
fEmissaoBoleto := ebClienteEmite;
end;
destructor TgbTitulo.Destroy;
begin
Cedente.Destroy;
Sacado.Destroy;
Instrucoes.Destroy;
inherited Destroy;
end;
procedure TgbTitulo.SetInstrucoes(Texto: TStringList);
begin
fInstrucoes.Assign(Texto);
end;
procedure TgbTitulo.Assign(ATitulo: TgbTitulo);
begin
OcorrenciaOriginal := ATitulo.OcorrenciaOriginal;
DescricaoOcorrenciaOriginal := ATitulo.DescricaoOcorrenciaOriginal;
TipoOcorrencia := ATitulo.TipoOcorrencia;
MotivoRejeicaoComando := ATitulo.MotivoRejeicaoComando;
DescricaoMotivoRejeicaoComando := ATitulo.DescricaoMotivoRejeicaoComando;
Cedente.Assign(ATitulo.Cedente);
Sacado.Assign(ATitulo.Sacado);
LocalPagamento := ATitulo.LocalPagamento;
SeuNumero := ATitulo.SeuNumero;
NossoNumero := ATitulo.NossoNumero;
NumeroDocumento := ATitulo.NumeroDocumento;
Carteira := ATitulo.Carteira;
AceiteDocumento := ATitulo.AceiteDocumento;
EspecieDocumento:= ATitulo.EspecieDocumento;
DataProcessamento := ATitulo.DataProcessamento;
DataDocumento := ATitulo.DataDocumento;
DataVencimento := ATitulo.DataVencimento;
DataOcorrencia := ATitulo.DataOcorrencia;
DataCredito := ATitulo.DataCredito;
DataAbatimento := ATitulo.DataAbatimento;
DataDesconto := ATitulo.DataDesconto;
DataMoraJuros := ATitulo.DataMoraJuros;
DataProtesto := ATitulo.DataProtesto;
DataBaixa := ATitulo.DataBaixa;
ValorDocumento := ATitulo.ValorDocumento;
ValorDespesaCobranca := ATitulo.ValorDespesaCobranca;
ValorAbatimento := ATitulo.ValorAbatimento;
ValorDesconto := ATitulo.ValorDesconto;
ValorMoraJuros := ATitulo.ValorMoraJuros;
ValorIOF := ATitulo.ValorIOF;
ValorOutrasDespesas := ATitulo.ValorOutrasDespesas;
ValorOutrosCreditos := ATitulo.ValorOutrosCreditos;
Instrucoes.Assign(ATitulo.Instrucoes);
EmissaoBoleto := ATitulo.EmissaoBoleto;
end;
function TgbTitulo.CalcularDigitoNossoNumero : string;
var
ACodigoBanco: string;
AClasseBanco: TPersistentClass;
ABanco: TPersistent;
GetDigitoNossoNumero: function(ATitulo: TgbTitulo): string of object;
begin
ACodigoBanco := Formatar(Cedente.ContaBancaria.Banco.Codigo,3,false,'0');
GetDigitoNossoNumero := nil;
AClasseBanco := GetClass('TgbBanco'+ACodigoBanco);
if AClasseBanco <> nil then
begin
ABanco := AClasseBanco.Create;
TRY
@GetDigitoNossoNumero := ABanco.MethodAddress('CalcularDigitoNossoNumero');
if @GetDigitoNossoNumero <> nil then
Result := GetDigitoNossoNumero(Self)
else
Raise Exception.CreateFmt('O cálculo do dígito do nosso número para o banco %s não está disponível',[ACodigoBanco]);
ABanco.Free;
EXCEPT
ABanco.Free;
Raise;
END;
end
else
Raise Exception.CreateFmt('Os boletos para o banco %s não estão disponíveis',[ACodigoBanco]);
end;
function TgbTitulo.GerarCodigoBarra : TgbCobCodBar;
var
ACodigoBanco,
ACodigoMoeda,
ADigitoCodigoBarras,
AFatorVencimento,
AValorDocumento,
ACampoLivre,
ACodigoBarras: string;
AClasseBanco: TPersistentClass;
ABanco: TPersistent;
GetCampoLivreCodigoBarra: function(ATitulo: TgbTitulo): string of object;
begin
Result := TgbCobCodBar.Create;
GetCampoLivreCodigoBarra := nil;
{
A primeira parte do código de barras é composta por:
Código do banco (3 posições)
Código da moeda = 9 (1 posição)
Dígito do código de barras (1 posição) - Será calculado e incluído pelo componente
Fator de vencimento (4 posições) - Obrigatório a partir de 03/07/2000
Valor do documento (10 posições) - Sem vírgula decimal e com ZEROS à esquerda
A segunda parte do código de barras é um campo livre, que varia de acordo
com o banco
}
{Primeira parte do código de barras}
ACodigoBanco := Formatar(Cedente.ContaBancaria.Banco.Codigo,3,false,'0');
ACodigoMoeda := '9';
AFatorVencimento := Formatar(CalcularFatorVencimento(DataVencimento),4,false,'0');
AValorDocumento := FormatCurr('0000000000',ValorDocumento*100); {Formata o valor com 10 dígitos, incluindo as casas decimais, mas não mostra o ponto decimal}
{Segunda parte do código de barras - Campo livre - Varia de acordo com o banco}
AClasseBanco := GetClass('TgbBanco'+ACodigoBanco);
if AClasseBanco <> nil then
begin
ABanco := AClasseBanco.Create;
TRY
@GetCampoLivreCodigoBarra := ABanco.MethodAddress('GetCampoLivreCodigoBarra');
if @GetCampoLivreCodigoBarra <> nil then
ACampoLivre := GetCampoLivreCodigoBarra(Self)
else
Raise Exception.CreateFmt('A geração de código de barras para títulos do banco %s não está disponível',[ACodigoBanco]);
ABanco.Free;
EXCEPT
ABanco.Free;
Raise;
END
end
else
Raise Exception.CreateFmt('Os boletos para o banco %s não estão disponíveis',[ACodigoBanco]);
{Calcula o dígito e completa o código de barras}
ACodigoBarras := ACodigoBanco + ACodigoMoeda + AFatorVencimento + AValorDocumento + ACampoLivre;
ADigitoCodigoBarras := Modulo11(ACodigoBarras,9);
if ADigitoCodigoBarras = '0' then
ADigitoCodigoBarras := '1';
Result.Codigo := Copy(ACodigoBarras,1,4) + ADigitoCodigoBarras + Copy(ACodigoBarras,5,length(ACodigoBarras)-4);
end;
procedure TgbTitulo.PrepararBoleto(ABoleto: TBoleto);
var
AAgenciaCodigoCedente,
ANossoNumero,
ACarteira,
AEspecieDocumento,
ACodigoBanco: string;
AInstrucoes: TStringList;
AClasseBanco: TPersistentClass;
ABanco: TPersistent;
GetFormatoBoleto: procedure(ATitulo: TgbTitulo; var AAgenciaCodigoCedente, ANossoNumero, ACarteira, AEspecieDocumento: string) of object;
begin
AInstrucoes := TStringList.Create;
GetFormatoBoleto := nil;
//AAgenciaCodigoCedente := Cedente.ContaBancaria.CodigoAgencia + '/' + Cedente.CodigoCedente;
AAgenciaCodigoCedente := Cedente.CodigoCedente;
ANossoNumero := NossoNumero + '-' + DigitoNossoNumero;
ACarteira := Carteira;
AEspecieDocumento := '';
ACodigoBanco := Formatar(Cedente.ContaBancaria.Banco.Codigo,3,false,'0');
AClasseBanco := GetClass('TgbBanco'+ACodigoBanco);
if AClasseBanco <> nil then
begin
ABanco := AClasseBanco.Create;
TRY
@GetFormatoBoleto := ABanco.MethodAddress('FormatarBoleto');
if @GetFormatoBoleto <> nil then
GetFormatoBoleto(Self,AAgenciaCodigoCedente,ANossoNumero,ACarteira, AEspecieDocumento);
ABanco.Free;
EXCEPT
ABanco.Free;
Raise;
END
end;
if DataProtesto <> 0 then
AInstrucoes.Add('Protestar em ' + FormatDateTime('dd/mm/yyyy',DataProtesto));
if ValorAbatimento <> 0 then
if DataAbatimento <> 0 then
AInstrucoes.Add('Conceder abatimento de ' + FormatCurr('R$ #,##0.00',ValorAbatimento) + ' para pagamento até ' + FormatDateTime('dd/mm/yyyy',DataAbatimento))
else
AInstrucoes.Add('Conceder abatimento de ' + FormatCurr('R$ #,##0.00',ValorAbatimento) + ' para pagamento até ' + FormatDateTime('dd/mm/yyyy',DataVencimento));
if ValorDesconto <> 0 then
if DataDesconto <> 0 then
AInstrucoes.Add('Conceder desconto de ' + FormatCurr('R$ #,##0.00',ValorDesconto) + ' por dia de antecipação para pagamento até ' + FormatDateTime('dd/mm/yyyy',DataDesconto))
else
AInstrucoes.Add('Conceder desconto de ' + FormatCurr('R$ #,##0.00',ValorDesconto) + ' por dia de antecipação');
if ValorMoraJuros <> 0 then
if DataMoraJuros <> 0 then
AInstrucoes.Add('Cobrar juros de ' + FormatCurr('R$ #,##0.00',ValorMoraJuros) + ' por dia de atraso para pagamento a partir de ' + FormatDateTime('dd/mm/yyyy',DataMoraJuros))
else
AInstrucoes.Add('Cobrar juros de ' + FormatCurr('R$ #,##0.00',ValorMoraJuros) + ' por dia de atraso');
AInstrucoes.AddStrings(Instrucoes);
with ABoleto do
begin
ReportTitle := 'Cobrança - ' + Cedente.ContaBancaria.Banco.Nome + ' - Sacado: ' + Sacado.Nome;
AAgenciaCodigoCedente := StringReplace(AAgenciaCodigoCedente, Copy(AAgenciaCodigoCedente,1,5), '', [rfReplaceAll, rfIgnoreCase]);
{Primeira via do boleto}
txtNomeBanco.Caption := Cedente.ContaBancaria.Banco.Nome;
txtCodigoBanco.Caption := Cedente.ContaBancaria.Banco.Codigo + '-' + Cedente.ContaBancaria.Banco.Digito;
txtLocalPagamento.Caption := AnsiUpperCase(LocalPagamento);
txtDataVencimento.Caption := FormatDateTime('dd/mm/yyyy',DataVencimento);
txtNomeCedente.Caption := AnsiUpperCase(Cedente.Nome);
txtEnderecoCedente.Caption := AnsiUpperCase(Sacado.Endereco.Complemento);
txtAgenciaCodigoCedente.Caption := AAgenciaCodigoCedente;
txtDataDocumento.Caption := FormatDateTime('dd/mm/yyyy',DataDocumento);
txtNumeroDocumento.Caption := NumeroDocumento;
txtEspecieDocumento.Caption := AEspecieDocumento;
if AceiteDocumento = adSim then
txtAceite.Caption := 'S'
else
txtAceite.Caption := 'N';
txtDataProcessamento.Caption := FormatDateTime('dd/mm/yyyy',Now);
txtNossoNumero.Caption := ANossoNumero;
NossoNumeroBoleto:= ANossoNumero; //Declarado para pegar o número do boleto
txtUsoBanco.Caption := '';
txtCarteira.Caption := ACarteira;
txtEspecieMoeda.Caption := 'R$';
txtQuantidadeMoeda.Caption := '';
txtValorMoeda.Caption := '';
txtValorDocumento.Caption := FormatCurr('#,##0.00',ValorDocumento);
txtInstrucoes.Lines.Clear;
txtInstrucoes.Lines.AddStrings(AInstrucoes);
txtValorDescontoAbatimento.Caption := '';
txtValorDescontoAbatimentoB.Caption := '';
txtValorMoraMulta.Caption := '';
txtValorMoraMultaB.Caption := '';
txtValorCobrado.Caption := '';
txtSacadoNome.Caption := AnsiUpperCase(Sacado.Nome);
case Sacado.TipoInscricao of
tiPessoaFisica : txtSacadoCPFCGC.Caption := 'CPF: ' + FormatarComMascara('!000\.000\.000\-00;0; ',Sacado.NumeroCPFCGC);
tiPessoaJuridica: txtSacadoCPFCGC.Caption := 'CNPJ: ' + FormatarComMascara('!00\.000\.000\/0000\-00;0; ',Sacado.NumeroCPFCGC);
tiOutro : txtSacadoCPFCGC.Caption := Sacado.NumeroCPFCGC;
end;
txtSacadoRuaNumeroComplemento.Caption := AnsiUpperCase(Sacado.Endereco.Rua);
txtSacadoCEPBairroCidadeEstado.Caption := AnsiUpperCase(FormatarComMascara('00000-000;0; ',Sacado.Endereco.CEP) + ' ' + Sacado.Endereco.Bairro + ' ' + Sacado.Endereco.Cidade + ' ' + Sacado.Endereco.Estado);
lblcurso1.Caption := Cedente.Endereco.Email;
txtCodigoBaixa.Caption := ANossoNumero;
{Segunda via do boleto}
txtNomeBanco2.Caption := Cedente.ContaBancaria.Banco.Nome;
txtCodigoBanco2.Caption := Cedente.ContaBancaria.Banco.Codigo + '-' + Cedente.ContaBancaria.Banco.Digito;
txtLocalPagamento2.Caption := AnsiUpperCase(LocalPagamento);
txtDataVencimento2.Caption := FormatDateTime('dd/mm/yyyy',DataVencimento);
txtNomeCedente2.Caption := AnsiUpperCase(Cedente.Nome);
txtEnderecoCedente2.Caption := AnsiUpperCase(Sacado.Endereco.Complemento);
txtAgenciaCodigoCedente2.Caption := AAgenciaCodigoCedente;
txtDataDocumento2.Caption := FormatDateTime('dd/mm/yyyy',DataDocumento);
txtNumeroDocumento2.Caption := NumeroDocumento;
txtEspecieDocumento2.Caption := AEspecieDocumento;
if AceiteDocumento = adSim then
txtAceite2.Caption := 'S'
else
txtAceite2.Caption := 'N';
txtDataProcessamento2.Caption := FormatDateTime('dd/mm/yyyy',Now);
txtNossoNumero2.Caption := ANossoNumero;
txtUsoBanco2.Caption := '';
txtCarteira2.Caption := ACarteira;
txtEspecieMoeda2.Caption := 'R$';
txtQuantidadeMoeda2.Caption := '';
txtValorMoeda2.Caption := '';
txtValorDocumento2.Caption := FormatCurr('#,##0.00',ValorDocumento);
txtInstrucoes2.Lines.Clear;
txtInstrucoes2.Lines.AddStrings(AInstrucoes);
txtValorDescontoAbatimento2.Caption := '';
txtValorDescontoAbatimentoB2.Caption := '';
txtValorMoraMulta2.Caption := '';
txtValorMoraMultaB2.Caption := '';
txtValorCobrado2.Caption := '';
txtSacadoNome2.Caption := AnsiUpperCase(Sacado.Nome);
case Sacado.TipoInscricao of
tiPessoaFisica : txtSacadoCPFCGC2.Caption := 'CPF: ' + FormatarComMascara('!000\.000\.000\-00;0; ',Sacado.NumeroCPFCGC);
tiPessoaJuridica: txtSacadoCPFCGC2.Caption := 'CNPJ: ' + FormatarComMascara('!00\.000\.000\/0000\-00;0; ',Sacado.NumeroCPFCGC);
tiOutro : txtSacadoCPFCGC2.Caption := Sacado.NumeroCPFCGC;
end;
txtSacadoRuaNumeroComplemento2.Caption := AnsiUpperCase(Sacado.Endereco.Rua);
//txtSacadoRuaNumeroComplemento2.Caption := AnsiUpperCase(Sacado.Endereco.Rua + ', ' + Sacado.Endereco.Numero + ' ' + Sacado.Endereco.Complemento);
txtSacadoCEPBairroCidadeEstado2.Caption := AnsiUpperCase(FormatarComMascara('00000-000;0; ',Sacado.Endereco.CEP) + ' ' + Sacado.Endereco.Bairro + ' ' + Sacado.Endereco.Cidade + ' ' + Sacado.Endereco.Estado);
lblcurso2.Caption := Cedente.Endereco.Email;
txtCodigoBaixa2.Caption := ANossoNumero;
{Terceira via do boleto}
txtNomeBanco3.Caption := Cedente.ContaBancaria.Banco.Nome;
txtCodigoBanco3.Caption := Cedente.ContaBancaria.Banco.Codigo + '-' + Cedente.ContaBancaria.Banco.Digito;
txtLocalPagamento3.Caption := AnsiUpperCase(LocalPagamento);
txtDataVencimento3.Caption := FormatDateTime('dd/mm/yyyy',DataVencimento);
txtNomeCedente3.Caption := AnsiUpperCase(Cedente.Nome);
txtEnderecoCedente3.Caption := AnsiUpperCase(Sacado.Endereco.Complemento);
txtAgenciaCodigoCedente3.Caption := AAgenciaCodigoCedente;
txtDataDocumento3.Caption := FormatDateTime('dd/mm/yyyy',DataDocumento);
txtNumeroDocumento3.Caption := NumeroDocumento;
txtEspecieDocumento3.Caption := AEspecieDocumento;
if AceiteDocumento = adSim then
txtAceite3.Caption := 'S'
else
txtAceite3.Caption := 'N';
txtDataProcessamento3.Caption := FormatDateTime('dd/mm/yyyy',Now);
txtNossoNumero3.Caption := ANossoNumero;
txtUsoBanco3.Caption := '';
txtCarteira3.Caption := ACarteira;
txtEspecieMoeda3.Caption := 'R$';
txtQuantidadeMoeda3.Caption := '';
txtValorMoeda3.Caption := '';
txtValorDocumento3.Caption := FormatCurr('#,##0.00',ValorDocumento);
txtInstrucoes3.Lines.Clear;
txtInstrucoes3.Lines.AddStrings(AInstrucoes);
txtValorDescontoAbatimento3.Caption := '';
txtValorDescontoAbatimentoB3.Caption := '';
txtValorMoraMulta3.Caption := '';
txtValorMoraMultaB3.Caption := '';
txtValorCobrado3.Caption := '';
txtSacadoNome3.Caption := AnsiUpperCase(Sacado.Nome);
case Sacado.TipoInscricao of
tiPessoaFisica : txtSacadoCPFCGC3.Caption := 'CPF: ' + FormatarComMascara('!000\.000\.000\-00;0; ',Sacado.NumeroCPFCGC);
tiPessoaJuridica: txtSacadoCPFCGC3.Caption := 'CNPJ: ' + FormatarComMascara('!00\.000\.000\/0000\-00;0; ',Sacado.NumeroCPFCGC);
tiOutro : txtSacadoCPFCGC3.Caption := Sacado.NumeroCPFCGC;
end;
txtSacadoRuaNumeroComplemento3.Caption := AnsiUpperCase(Sacado.Endereco.Rua);
txtSacadoCEPBairroCidadeEstado3.Caption := AnsiUpperCase(FormatarComMascara('00000-000;0; ',Sacado.Endereco.CEP) + ' ' + Sacado.Endereco.Bairro + ' ' + Sacado.Endereco.Cidade + ' ' + Sacado.Endereco.Estado);
lblcurso3.Caption := Cedente.Endereco.Email;
txtCodigoBaixa3.Caption := ANossoNumero;
txtLinhaDigitavel3.Caption := CodigoBarra.LinhaDigitavel;
imgCodigoBarras3.Picture.Assign(CodigoBarra.Imagem.Picture);
end;
AInstrucoes.Free;
end;
procedure TgbTitulo.EnviarPorEMail(Host, LoginUsuario: string; Porta : integer; Assunto : string; Mensagem : TStringList);
var
{$IFDEF VER150}
Mail : TIdMessage;
SMTP : TIdSMTP;
{$ELSE}
Mail : TNMSMTP;
{$ENDIF}
NomeArquivo : string;
begin
if Host = '' then
Raise Exception.Create('O host não foi informado');
if Assunto = '' then
Raise Exception.Create('O assunto da mensagem não foi informado');
{$IFDEF VER150}
Mail := TIdMessage.Create(nil);
SMTP := TIdSMTP.Create(nil);
TRY
NomeArquivo := 'ImagemBoleto.bmp';
ImagemBoleto.Picture.SaveToFile(NomeArquivo);
with Mail do
begin
if Cedente.Endereco.EMail <> '' then
From.Address := Cedente.Endereco.EMail
else
Raise Exception.Create('O e-mail do cedente não foi informado');
if Cedente.Nome <> '' then
From.Name := Cedente.Nome
else
From.Name := From.Address;
ReplyTo.EMailAddresses := From.Address;
if Sacado.Endereco.EMail <> '' then
Recipients.EMailAddresses := Sacado.Endereco.EMail
else
Raise Exception.Create('O e-mail do sacado não foi informado');
Subject := Assunto;
Body.Text:= Mensagem.Text;
TIdAttachment.Create(Mail.MessageParts, NomeArquivo);
end;
SMTP.Host := Host;
SMTP.Username := LoginUsuario;
SMTP.Port := Porta;
SMTP.Connect;
SMTP.Send(Mail);
SMTP.Disconnect;
EXCEPT
if SMTP.Connected then SMTP.Disconnect;
Raise;
END;
Mail.Free;
SMTP.Free;
if FileExists(NomeArquivo) then DeleteFile(NomeArquivo);
{$ELSE}
Mail := TNMSMTP.Create(nil);
TRY
NomeArquivo := 'ImagemBoleto.bmp';
ImagemBoleto.Picture.SaveToFile(NomeArquivo);
with Mail.PostMessage do
begin
if Cedente.Endereco.EMail <> '' then
FromAddress := Cedente.Endereco.EMail
else
Raise Exception.Create('O e-mail do cedente não foi informado');
if Cedente.Nome <> '' then
FromName := Cedente.Nome
else
FromName := FromAddress;
ReplyTo := FromAddress;
if Sacado.Endereco.EMail <> '' then
ToAddress.Add(Sacado.Endereco.EMail)
else
Raise Exception.Create('O e-mail do sacado não foi informado');
Subject := Assunto;
Body.Assign(Mensagem);
Attachments.Add(NomeArquivo);
end;
Mail.Host := Host;
Mail.UserID := LoginUsuario;
Mail.Port := Porta;
Mail.Connect;
Mail.SendMail;
Mail.Disconnect;
EXCEPT
if Mail.Connected then Mail.Disconnect;
Raise;
END;
Mail.Free;
if FileExists(NomeArquivo) then DeleteFile(NomeArquivo);
{$ENDIF}
end;
procedure TgbTitulo.Visualizar;
var
ABoleto : TBoleto;
begin
ABoleto := TBoleto.Create(nil);
TRY
PrepararBoleto(ABoleto);
//ABoleto.ExportToFilter(TQRPDFDocumentFilter.Create('c:\teste1.pdf'));
ABoleto.Preview;
{ABoleto.ExportToFilter(TQRPDFDocumentFilter.Create('c:\teste2.pdf'));
ABoleto.ExportToFilter(TQRGHTMLDocumentFilter.Create('c:\teste.html'));
ABoleto.ExportToFilter(TQRRTFExportFilter.Create('c:\teste.rtf'));}
ABoleto.Free;
EXCEPT
ABoleto.Free;
Raise;
END;
end;
procedure TgbTitulo.Imprimir;
var
ABoleto : TBoleto;
begin
ABoleto := TBoleto.Create(nil);
TRY
PrepararBoleto(ABoleto);
ABoleto.Print;
ABoleto.Free;
EXCEPT
ABoleto.Free;
Raise;
END;
end;
function TgbTitulo.GetImagemBoleto : TImage;
var
ABoleto : TBoleto;
AImagem : TMetafile;
begin
ABoleto := TBoleto.Create(nil);
AImagem := TMetafile.Create;
Result := TImage.Create(nil);
TRY
PrepararBoleto(ABoleto);
ABoleto.Prepare;
AImagem := ABoleto.QRPrinter.GetPage(1);
Result.Height := AImagem.Height;
Result.Width := AImagem.Width;
Result.Canvas.Draw(0,0,AImagem);
Result.Picture.Bitmap.Monochrome := TRUE;
AImagem.Free;
ABoleto.QRPrinter.Free;
ABoleto.Free;
EXCEPT
AImagem.Free;
ABoleto.QRPrinter.Free;
ABoleto.Free;
Raise;
END;
ABoleto.QRPrinter := nil;
end;
function TgbTitulo.GetImagemFichaCompensacao : TImage;
var
AImagem : TImage;
RectOrigem, RectDestino : TRect;
begin
Result := TImage.Create(nil);
AImagem := TImage.Create(nil);
AImagem := ImagemBoleto;
with RectOrigem do
begin
Left := 35;
Top := 720;
Right := 762;
Bottom := AImagem.Height;
end;
with RectDestino do
begin
Left := 0;
Top := 0;
Right := AImagem.Width;
Bottom := AImagem.Height - 719;
end;
Result.Height := RectDestino.Bottom;
Result.Width := RectDestino.Right;
Result.Canvas.CopyRect(RectDestino, AImagem.Canvas, RectOrigem);
end;
{$IFNDEF VER120}
{TgbTituloList}
constructor TgbTituloList.Create;
begin
{$IFDEF VER140}
inherited Create(true);
{$ELSE}
{$IFDEF VER130}
inherited Create(true);
{$ELSE}
inherited Create;
{$ENDIF}
{$ENDIF}
end;
function TgbTituloList.FindInstanceOf(AClass: TClass; AExact: Boolean;
AStartAt: Integer): Integer;
var
I: Integer;
begin
Result := -1;
for I := AStartAt to Count - 1 do
if (AExact and
(Items[I].ClassType = AClass)) or
(not AExact and
Items[I].InheritsFrom(AClass)) then
begin
Result := I;
break;
end;
end;
function TgbTituloList.GetItem(Index: Integer): TgbTitulo;
begin
Result := inherited Items[Index] as TgbTitulo;
end;
function TgbTituloList.Add(ATitulo : TgbTitulo) : integer;
var
NovoTitulo : TgbTitulo;
begin
NovoTitulo := TgbTitulo.Create(nil);
NovoTitulo.Assign(ATitulo);
Result := inherited Add(NovoTitulo);
end;
function TgbTituloList.IndexOf(ATitulo : TgbTitulo): Integer;
begin
Result := inherited IndexOf(ATitulo);
end;
procedure TgbTituloList.Insert(Index: Integer; ATitulo: TgbTitulo);
begin
inherited Insert(Index, ATitulo);
end;
function TgbTituloList.Remove(ATitulo: TgbTitulo): Integer;
begin
Result := inherited Remove(ATitulo);
end;
procedure TgbTituloList.SetItem(Index: Integer; ATitulo: TgbTitulo);
begin
inherited Items[Index] := ATitulo;
end;
{TgbCobranca}
constructor TgbCobranca.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
LayoutArquivo := laCNAB400;
TipoMovimento := tmRetorno;
Titulos := TgbTituloList.Create;
end;
destructor TgbCobranca.Destroy;
begin
Titulos.Destroy;
inherited Destroy;
end;
function TgbCobranca.GerarRemessa : boolean;
var
Remessa: TStringList;
ACodigoBanco: string;
AClasseBanco: TPersistentClass;
ABanco: TPersistent;
GetRemessa: function(var ACobranca: TgbCobranca; var Remessa: TStringList): boolean of object;
begin
Result := FALSE;
GetRemessa := nil;
if Titulos.Count <= 0 then
Raise Exception.Create('Não há títulos para gerar arquivo remessa. A coleção de títulos está vazia');
Remessa := TStringList.Create;
TRY
if (TipoMovimento <> tmRemessa) and (TipoMovimento <> tmRemessaTeste) then
TipoMovimento := tmRemessa;
ACodigoBanco := Formatar(Titulos[0].Cedente.ContaBancaria.Banco.Codigo,3,false,'0');
AClasseBanco := GetClass('TgbBanco'+ACodigoBanco);
if AClasseBanco <> nil then
begin
ABanco := AClasseBanco.Create;
TRY
@GetRemessa := ABanco.MethodAddress('GerarRemessa');
if @GetRemessa <> nil then
begin
Result := GetRemessa(Self, Remessa);
if Result then
Remessa.SaveToFile(NomeArquivo); {Grava o arquivo remessa}
end
else
Raise Exception.CreateFmt('A geração de arquivo remessa para o banco %s não está disponível',[ACodigoBanco]);
ABanco.Free;
EXCEPT
ABanco.Free;
Raise;
END
end
else
Raise Exception.CreateFmt('Processamento de arquivos remessa / retorno para o banco %s não está disponível',[ACodigoBanco]);
Remessa.Free;
EXCEPT
Remessa.Free;
Raise;
END;
end;
function TgbCobranca.LerRetorno : boolean;
var
ACodigoBanco: string;
Retorno : TStringList;
AClasseBanco: TPersistentClass;
ABanco: TPersistent;
GetRetorno: function(var ACobranca: TgbCobranca; Retorno: TStringList): boolean of object;
begin
Result := FALSE;
GetRetorno := nil;
Retorno := TStringList.Create;
Self.Titulos.Clear; {Zera o conjunto de títulos, antes de incluir os títulos do arquivo retorno}
TRY
if not FileExists(NomeArquivo) then
Raise Exception.CreateFmt('O arquivo %s não foi localizado',[NomeArquivo]);
Retorno.LoadFromFile(NomeArquivo);
if Retorno.Count < 3 then
begin
Result := FALSE;
Exit;
end;
case length(Retorno[0]) of
240 :
begin
LayoutArquivo := laCNAB240;
{Ver se o arquivo é mesmo RETORNO DE COBRANÇA}
if Copy(Retorno.Strings[0],143,1) <> '2' then
Raise Exception.Create(NomeArquivo+' não é um arquivo de retorno de cobrança com layout CNAB240');
ACodigoBanco := Copy(Retorno.Strings[0],1,3);
end;
400 :
begin
LayoutArquivo := laCNAB400;
{Ver se o arquivo é mesmo RETORNO DE COBRANÇA}
if Copy(Retorno.Strings[0],1,19) <> '02RETORNO01COBRANCA' then
Raise Exception.Create(NomeArquivo+' não é um arquivo de retorno de cobrança com layout CNAB400');
ACodigoBanco := Copy(Retorno.Strings[0],77,3);
end;
else
begin
LayoutArquivo := laOutro;
Raise Exception.Create(NomeArquivo+' não é um arquivo de retorno de cobrança com layout CNAB240 ou CNAB400');
end;
end;
TipoMovimento := tmRetorno;
AClasseBanco := GetClass('TgbBanco'+ACodigoBanco);
if AClasseBanco <> nil then
begin
ABanco := AClasseBanco.Create;
TRY
@GetRetorno := ABanco.MethodAddress('LerRetorno');
if @GetRetorno <> nil then
Result := GetRetorno(Self, Retorno)
else
Raise Exception.CreateFmt('O processamento de arquivo retorno do banco %s não está disponível',[ACodigoBanco]);
ABanco.Free;
EXCEPT
ABanco.Free;
Raise;
END
end
else
Raise Exception.CreateFmt('Processamento de arquivos remessa / retorno para o banco %s não está disponível',[ACodigoBanco]);
Retorno.Free;
Result := TRUE;
EXCEPT
Retorno.Free;
Raise;
END;
end;
function TgbCobranca.GerarRelatorio : TStringList;
var
i : integer;
begin
Result := TStringList.Create;
with Result do
begin
Add(StringOfChar('=',80));
Add('');
Add('Nome do arquivo : ' + NomeArquivo);
Add('Número do arquivo: ' + IntToStr(NumeroArquivo));
Add('Data do arquivo : ' + DateTimeToStr(DataArquivo));
case LayoutArquivo of
laCNAB240 : Add('Layout do arquivo: CNAB240');
laCNAB400 : Add('Layout do arquivo: CNAB400');
else
Add('Layout do arquivo: Outro');
end; {case LayoutArquivo}
case TipoMovimento of
tmRemessa : Add('Tipo de movimento: Remessa');
tmRetorno : Add('Tipo de movimento: Retorno');
tmRemessaTeste : Add('Tipo de movimento: Remessa - Teste');
tmRetornoTeste : Add('Tipo de movimento: Retorno - Teste');
else
Add('Tipo de movimento: Outro');
end; {case TipoMovimento}
Add('');
Add(StringOfChar('=',80));
for i := 0 to (Titulos.Count - 1) do
begin
with Titulos[i] do
begin
Add('');
case TipoOcorrencia of
{Ocorrências para arquivo remessa}
toRemessaRegistrar : Add('Tipo ocorrência : Registrar o título no banco');
toRemessaBaixar : Add('Tipo ocorrência : Baixar o título no banco');
toRemessaDebitarEmConta : Add('Tipo ocorrência : Debitar em conta');
toRemessaConcederAbatimento : Add('Tipo ocorrência : Conceder abatimento');
toRemessaCancelarAbatimento : Add('Tipo ocorrência : Cancelar abatimento');
toRemessaConcederDesconto : Add('Tipo ocorrência : Conceder desconto');
toRemessaCancelarDesconto : Add('Tipo ocorrência : Cancelar desconto');
toRemessaAlterarVencimento : Add('Tipo ocorrência : Alterar vencimento');
toRemessaProtestar : Add('Tipo ocorrência : Protestar o título');
toRemessaCancelarInstrucaoProtesto : Add('Tipo ocorrência : Cancelar instrução de protesto');
toRemessaDispensarJuros : Add('Tipo ocorrência : Dispensar juros');
toRemessaAlterarNomeEnderecoSacado : Add('Tipo ocorrência : Alterar nome e endereço do sacado');
toRemessaOutrasOcorrencias : Add('Tipo ocorrência : Outras ocorrências de remessa');
{Ocorrências para arquivo retorno}
toRetornoRegistroConfirmado : Add('Tipo ocorrência : Registro do título foi confirmado');
toRetornoRegistroRecusado : Add('Tipo ocorrência : Registro do título foi recusado');
toRetornoComandoRecusado : Add('Tipo ocorrência : Comando recusado');
toRetornoLiquidado : Add('Tipo ocorrência : O título foi liquidado');
toRetornoBaixado : Add('Tipo ocorrência : O título foi baixado');
toRetornoRecebimentoInstrucaoBaixar : Add('Tipo ocorrência : Recebimento de instrução para baixar título');
toRetornoBaixaOuLiquidacaoEstornada : Add('Tipo ocorrência : Baixa / liquidação estornada');
toRetornoTituloEmSer : Add('Tipo ocorrência : Título em ser');
toRetornoRecebimentoInstrucaoConcederAbatimento : Add('Tipo ocorrência : Recebimento de instrução para conceder abatimento');
toRetornoAbatimentoConcedido : Add('Tipo ocorrência : Abatimento concedido');
toRetornoRecebimentoInstrucaoCancelarAbatimento : Add('Tipo ocorrência : Recebimento de instrução para cancelar abatimento');
toRetornoAbatimentoCancelado : Add('Tipo ocorrência : Abatimento cancelado');
toRetornoRecebimentoInstrucaoConcederDesconto : Add('Tipo ocorrência : Recebimento de instrução para conceder desconto');
toRetornoDescontoConcedido : Add('Tipo ocorrência : Desconto concedido');
toRetornoRecebimentoInstrucaoCancelarDesconto : Add('Tipo ocorrência : Recebimento de instrução para cancelar desconto');
toRetornoDescontoCancelado : Add('Tipo ocorrência : Desconto cancelado');
toRetornoRecebimentoInstrucaoAlterarDados : Add('Tipo ocorrência : Recebimento de instrução para alterar dados');
toRetornoDadosAlterados : Add('Tipo ocorrência : Dados alterados');
toRetornoRecebimentoInstrucaoAlterarVencimento : Add('Tipo ocorrência : Recebimento de instrução para alterar vencimento');
toRetornoVencimentoAlterado : Add('Tipo ocorrência : Vencimento alterado');
toRetornoRecebimentoInstrucaoProtestar : Add('Tipo ocorrência : Recebimento de instrução para protestar título');
toRetornoProtestado : Add('Tipo ocorrência : Título protestado');
toRetornoRecebimentoInstrucaoSustarProtesto : Add('Tipo ocorrência : Recebimento de instrução para sustar protesto');
toRetornoProtestoSustado : Add('Tipo ocorrência : Protesto sustado');
toRetornoDebitoEmConta : Add('Tipo ocorrência : Debitado em conta');
toRetornoRecebimentoInstrucaoAlterarNomeSacado : Add('Tipo ocorrência : Recebimento de instrução para alterar nome do sacado');
toRetornoNomeSacadoAlterado : Add('Tipo ocorrência : Nome do sacado alterado');
toRetornoRecebimentoInstrucaoAlterarEnderecoSacado : Add('Tipo ocorrência : Recebimento instrução para alterar endereço do sacado');
toRetornoEnderecoSacadoAlterado : Add('Tipo ocorrência : Endereço do sacado alterado');
toRetornoEncaminhadoACartorio : Add('Tipo ocorrência : Título encaminhado para cartório');
toRetornoRetiradoDeCartorio : Add('Tipo ocorrência : Título retirado do cartório');
toRetornoRecebimentoInstrucaoDispensarJuros : Add('Tipo ocorrência : Recebimento de instrucão para dispensar juros');
toRetornoJurosDispensados : Add('Tipo ocorrência : Juros dispensados');
toRetornoManutencaoTituloVencido : Add('Tipo ocorrência : Manutenção de título vencido');
toRetornoRecebimentoInstrucaoAlterarTipoCobranca : Add('Tipo ocorrência : Recebimento de instrução para alterar tipo de cobrança');
toRetornoTipoCobrancaAlterado : Add('Tipo ocorrência : Tipo de cobrança alterado');
toRetornoDespesasProtesto : Add('Tipo ocorrência : Despesas com protesto');
toRetornoDespesasSustacaoProtesto : Add('Tipo ocorrência : Despesas com sustação de protesto');
toRetornoProtestoOuSustacaoEstornado : Add('Tipo ocorrência : Protesto ou sustação estornado');
toRetornoDebitoTarifas : Add('Tipo ocorrência : Débito de tarifas');
toRetornoOutrasOcorrencias : Add('Tipo ocorrência : Outra ocorrência de retorno');
else
Add('Tipo ocorrência : Outra ocorrência não identificada');
end; {case TipoOcorrencia}
if trim(OcorrenciaOriginal) <> '' then
if trim(DescricaoOcorrenciaOriginal) <> '' then
Add('Ocorrênc original: ' + DescricaoOcorrenciaOriginal )
else
Add('Ocorrênc original: ' + OcorrenciaOriginal);
if trim(MotivoRejeicaoComando) <> '' then
Add('Motivo rejeição : ' + MotivoRejeicaoComando);
if trim(SeuNumero) <> '' then
Add('Seu número : ' + SeuNumero);
if trim(NossoNumero) <> '' then
Add('Nosso número : ' + NossoNumero + '-' + DigitoNossoNumero);
if trim(Carteira) <> '' then
Add('Carteira : ' + Carteira);
if trim(NumeroDocumento) <> '' then
Add('Número documento : ' + NumeroDocumento);
if DataDocumento <> 0 then
Add('Data documento : ' + DateToStr(DataDocumento));
if DataVencimento <> 0 then
Add('Data vencimento : ' + DateToStr(DataVencimento));
if DataOcorrencia <> 0 then
Add('Data ocorrência : ' + DateToStr(DataOcorrencia));
if DataCredito <> 0 then
Add('Data crédito : ' + DateToStr(DataCredito));
Add('Valor documento : ' + FormatCurr('#,##0.00',ValorDocumento));
if ValorDespesaCobranca > 0 then
Add('Despesa cobrança : ' + FormatCurr('#,##0.00',ValorDespesaCobranca));
if DataAbatimento <> 0 then
Add('Abatimento até : ' + DateToStr(DataAbatimento));
if ValorAbatimento > 0 then
Add('Valor abatimento : ' + FormatCurr('#,##0.00',ValorAbatimento));
if ValorDesconto > 0 then
if DataDesconto <> 0 then
begin
Add('Desconto até : ' + DateToStr(DataDesconto));
Add('Vr. desconto/dia : ' + FormatCurr('#,##0.00',ValorDesconto));
end
else
Add('Valor desconto : ' + FormatCurr('#,##0.00',ValorDesconto));
if ValorMoraJuros > 0 then
if DataMoraJuros <> 0 then
begin
Add('Juros a partir de: ' + DateToStr(DataMoraJuros));
Add('Valor juros/dia : ' + FormatCurr('#,##0.00',ValorMoraJuros));
end
else
Add('Valor mora/juros : ' + FormatCurr('#,##0.00',ValorMoraJuros));
if ValorOutrosCreditos > 0 then
Add('Outros acréscimos: ' + FormatCurr('#,##0.00',ValorOutrosCreditos));
if ValorIOF > 0 then
Add('Valor IOF : ' + FormatCurr('#,##0.00',ValorIOF));
if (DataCredito <> 0) then
Add('Valor do crédito : ' + FormatCurr('#,##0.00',ValorDocumento-ValorDespesaCobranca-ValorAbatimento-ValorDesconto+ValorMoraJuros+ValorOutrosCreditos-ValorOutrasDespesas));
if DataProtesto <> 0 then
Add('Protestar em : ' + DateToStr(DataProtesto));
if DataBaixa <> 0 then
Add('Baixar em : ' + DateToStr(DataBaixa));
with Cedente do
begin
Add('CEDENTE');
case TipoInscricao of
tiPessoaFisica : Add(' Nome / CPF : ' + Nome + ' / ' + FormatarComMascara('!###\.###\.###\.###\-##;0; ',NumeroCPFCGC));
tiPessoaJuridica: Add(' Nome / CNPJ : ' + Nome + ' / ' + FormatarComMascara('!##\.###\.###\/####\-##;0; ',NumeroCPFCGC));
tiOutro : Add(' Nome / Inscrição: ' + Nome + ' / ' + NumeroCPFCGC);
end;
with Endereco do
if Trim(Rua + Numero + Complemento + Bairro + Cidade + Estado + CEP) <> '' then
Add(' Endereço : ' + Rua + ' ' + Numero + ' ' + Complemento + ' - ' + Bairro + ' - ' + Cidade + ' - ' + Estado + ' - ' + FormatMaskText('#####\-##;0; ',CEP));
with ContaBancaria do
if trim(Banco.Codigo) <> '' then
Add(' Banco/Ag./Conta : ' + Banco.Codigo + '-' + Banco.Digito + ' - ' + Banco.Nome + ' / ' + Trim(CodigoAgencia) + ' / ' + Trim(NumeroConta) + '-' + Trim(DigitoConta));
if Trim(CodigoCedente + DigitoCodigoCedente) <> '' then
Add(' Código cedente : ' + Trim(CodigoCedente) + '-' + Trim(DigitoCodigoCedente));
end; {with Cedente}
with Sacado do
begin
Add('SACADO');
case TipoInscricao of
tiPessoaFisica : Add(' Nome / CPF : ' + Nome + ' / ' + FormatMaskText('!###\.###\.###\.###\-##;0; ',NumeroCPFCGC));
tiPessoaJuridica: Add(' Nome / CNPJ : ' + Nome + ' / ' + FormatMaskText('!##\.###\.###\/####\-##;0; ',NumeroCPFCGC));
tiOutro : Add(' Nome / Inscrição: ' + Nome + ' / ' + NumeroCPFCGC);
end;
with Endereco do
if Trim(Rua + Numero + Complemento + Bairro + Cidade + Estado + CEP) <> '' then
Add(' Endereço : ' + Rua + ' ' + Numero + ' ' + Complemento + ' - ' + Bairro + ' - ' + Cidade + ' - ' + Estado + ' - ' + FormatMaskText('#####\-##;0; ',CEP));
with ContaBancaria do
if trim(Banco.Codigo) <> '' then
Add(' Banco/Ag./Conta : ' + Banco.Codigo + '-' + Banco.Digito + ' - ' + Banco.Nome + ' / ' + Trim(CodigoAgencia) + ' / ' + Trim(NumeroConta) + '-' + Trim(DigitoConta));
end; {with Sacado}
if Trim(Instrucoes.Text) <> '' then
begin
Add('<INSTRUÇÕES> :');
Add(Instrucoes.Text);
end;
end; {with Titulos[i]}
Add('');
Add(StringOfChar('-',80));
end; {for I := 0 to (Count - 1)}
end;
end;
{$ENDIF}
end.
|
unit Odontologia.Controlador.Pais;
interface
uses
Data.DB,
System.Generics.Collections,
System.SysUtils,
Odontologia.Modelo,
Odontologia.Modelo.Entidades.Pais,
Odontologia.Modelo.Pais.Interfaces,
Odontologia.Controlador.Pais.Interfaces;
type
TControllerPais = class(TInterfacedObject, iControllerPais)
private
FModel: iModelPais;
FDataSource: TDataSource;
//Flista: TObjectList<TDPAIS>;
FEntidad: TDPAIS;
public
constructor Create;
destructor Destroy; override;
class function New: iControllerPais;
function DataSource(aDataSource: TDataSource): iControllerPais;
function Buscar: iControllerPais; overload;
function Buscar(aId: Integer): iControllerPais; overload;
function Buscar(aNombre: String): iControllerPais; overload;
function Insertar: iControllerPais;
function Modificar: iControllerPais;
function Eliminar: iControllerPais;
function Entidad: TDPAIS;
end;
implementation
{ TControllerPais }
function TControllerPais.Buscar: iControllerPais;
begin
Result := Self;
FModel.DAO
.SQL
.Where('')
.&End
.Find;
end;
function TControllerPais.Buscar(aNombre: String): iControllerPais;
begin
Result := Self;
FModel.DAO
.SQL
.Where('PAI_NOMBRE CONTAINING ' +QuotedStr(aNombre) + '')
.&End
.Find;
end;
function TControllerPais.Buscar(aId: Integer): iControllerPais;
begin
Result := Self;
if Assigned(FEntidad) then
FEntidad.Free;
FEntidad := FModel.DAO.Find(aId);
end;
constructor TControllerPais.Create;
begin
FModel := TModel.New.Pais;
end;
function TControllerPais.DataSource(aDataSource: TDataSource)
: iControllerPais;
begin
Result := Self;
FDataSource := aDataSource;
FModel.DataSource(FDataSource);
end;
destructor TControllerPais.Destroy;
begin
//Flista.Free;
FEntidad.Free;
inherited;
end;
function TControllerPais.Eliminar: iControllerPais;
begin
Result := Self;
FModel.DAO.Delete(FModel.Entidad);
end;
function TControllerPais.Entidad: TDPAIS;
begin
Result := FModel.Entidad;
end;
function TControllerPais.Insertar: iControllerPais;
begin
Result := Self;
FModel.DAO.Insert(FModel.Entidad);
end;
function TControllerPais.Modificar: iControllerPais;
begin
Result := Self;
FModel.DAO.Update(FModel.Entidad);
end;
class function TControllerPais.New: iControllerPais;
begin
Result := Self.Create;
end;
end.
|
unit UGetOrderInfo;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, ExtCtrls,
cxMaskEdit, cxDropDownEdit, cxCalendar, cxControls, cxContainer, cxEdit,
cxTextEdit, DB, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase, Ibase,
cxPropertiesStore;
type
TfrmGetOrderInfo = class(TForm)
pnl1: TPanel;
cxButton1: TcxButton;
cxButton2: TcxButton;
cxtxtdtNum: TcxTextEdit;
OnDateEx1: TcxDateEdit;
lbl1: TLabel;
Label1: TLabel;
WorkDatabase: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
ReadDataSet: TpFIBDataSet;
cxprprtstr1: TcxPropertiesStore;
procedure cxButton1Click(Sender: TObject);
procedure cxButton2Click(Sender: TObject);
private
{ Private declarations }
procedure GetIdOrder;
public
{ Public declarations }
Id_Order:Int64;
constructor Create(AOwner:TComponent;DBHandle:TISC_DB_HANDLE); reintroduce;
end;
implementation
uses BaseTypes;
{$R *.dfm}
{ TfrmGetOrderInfo }
constructor TfrmGetOrderInfo.Create(AOwner: TComponent; DBHandle: TISC_DB_HANDLE);
begin
inherited Create(AOwner);
OnDateEx1.Date:=Date;
WorkDatabase.Handle:=DBHandle;
ReadTransaction.StartTransaction;
end;
procedure TfrmGetOrderInfo.cxButton1Click(Sender: TObject);
begin
Id_Order:=-1;
GetIdOrder;
if Id_Order<>-1
then ModalResult:=mrYes
else agShowMessage('Не знайдено наказ по введеним атрибутам!');
end;
procedure TfrmGetOrderInfo.cxButton2Click(Sender: TObject);
begin
ModalResult:=mrNo;
end;
procedure TfrmGetOrderInfo.GetIdOrder;
begin
if ReadDataSet.Active then ReadDataSet.Close;
ReadDataSet.SelectSQL.Text:='SELECT FIRST 1 * FROM UP_DT_ORDERS WHERE NUM_PROJECT='+cxtxtdtNum.Text+' AND DATE_PROJECT='+''''+DateToStr(OnDateEx1.Date)+'''';
ReadDataSet.Open;
if ReadDataSet.RecordCount>0
then begin
Id_Order:=TFibBCDField(ReadDataSet.FieldByName('ID_ORDER')).AsInt64;
end;
ReadDataSet.Close;
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: EnhancedMeshUnit.pas,v 1.17 2007/02/05 22:21:06 clootie Exp $
*----------------------------------------------------------------------------*)
//--------------------------------------------------------------------------------------
// File: EnhancedMesh.cpp
//
// Starting point for new Direct3D applications
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
{$I DirectX.inc}
unit EnhancedMeshUnit;
interface
uses
Windows, SysUtils, StrSafe,
DXTypes, Direct3D9, D3DX9,
DXUT, DXUTcore, DXUTenum, DXUTmesh, DXUTmisc, DXUTgui, DXUTSettingsDlg;
{.$DEFINE DEBUG_VS} // Uncomment this line to debug vertex shaders
{.$DEFINE DEBUG_PS} // Uncomment this line to debug pixel shaders
const
MESHFILENAME = 'dwarf\dwarf.x';
type
PD3DXMaterialArray = ^TD3DXMaterialArray;
TD3DXMaterialArray = array[0..0] of TD3DXMaterial;
PIDirect3DTexture9Array = ^IDirect3DTexture9Array;
IDirect3DTexture9Array = array[0..0] of IDirect3DTexture9;
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
var
g_pFont: ID3DXFont = nil; // Font for drawing text
g_pTextSprite: ID3DXSprite = nil; // Sprite for batching draw text calls
g_pEffect: ID3DXEffect = nil; // D3DX effect interface
g_Camera: CModelViewerCamera; // A model viewing camera
g_pDefaultTex: IDirect3DTexture9 = nil; // Default texture for texture-less material
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_pMeshSysMem: ID3DXMesh = nil; // system memory version of mesh, lives through resize's
g_pMeshEnhanced: ID3DXMesh = nil; // vid mem version of mesh that is enhanced
g_dwNumSegs: LongWord = 2; // number of segments per edge (tesselation level)
g_pMaterials: PD3DXMaterialArray = nil; // pointer to material info in m_pbufMaterials
g_ppTextures: PIDirect3DTexture9Array = nil; // array of textures, entries are NULL if no texture specified
g_dwNumMaterials: DWORD = 0; // number of materials
g_vObjectCenter: TD3DXVector3; // Center of bounding sphere of object
g_fObjectRadius: Single; // Radius of bounding sphere of object
g_mCenterWorld: TD3DXMatrixA16; // World matrix to center the mesh
g_pbufMaterials: ID3DXBuffer = nil; // contains both the materials data and the filename strings
g_pbufAdjacency: ID3DXBuffer = nil; // Contains the adjacency info loaded with the mesh
g_bUseHWNPatches: Boolean = True;
g_bWireframe: Boolean = False;
//--------------------------------------------------------------------------------------
// UI control IDs
//--------------------------------------------------------------------------------------
const
IDC_TOGGLEFULLSCREEN = 1;
IDC_TOGGLEREF = 3;
IDC_CHANGEDEVICE = 4;
IDC_FILLMODE = 5;
IDC_SEGMENTLABEL = 6;
IDC_SEGMENT = 7;
IDC_HWNPATCHES = 8;
//--------------------------------------------------------------------------------------
// 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; fTime: 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;
procedure RenderText;
function GenerateEnhancedMesh(pd3dDevice: IDirect3DDevice9; dwNewNumSegs: LongWord): HRESULT;
procedure CreateCustomDXUTobjects;
procedure DestroyCustomDXUTobjects;
implementation
uses Math;
//--------------------------------------------------------------------------------------
// Initialize the app
//--------------------------------------------------------------------------------------
procedure InitApp;
var
iY: Integer;
begin
// 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; g_SampleUI.AddComboBox(IDC_FILLMODE, 10, iY, 150, 24, Ord('F'));
g_SampleUI.GetComboBox(IDC_FILLMODE).AddItem('(F)illmode: Solid', Pointer(0));
g_SampleUI.GetComboBox(IDC_FILLMODE).AddItem('(F)illmode: Wireframe', Pointer(1));
Inc(iY, 30); g_SampleUI.AddStatic(IDC_SEGMENTLABEL, 'Number of segments: 2', 10, iY, 150, 16);
Inc(iY, 14); g_SampleUI.AddSlider(IDC_SEGMENT, 10, iY, 150, 24, 1, 10, 2);
Inc(iY, 26); g_SampleUI.AddCheckBox(IDC_HWNPATCHES, 'Use hardware N-patches', 10, iY, 150, 20, True, Ord('H'));
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;
// No fallback defined by this app, so reject any device that
// doesn't support at least ps2.0
if (pCaps.PixelShaderVersion < D3DPS_VERSION(2,0)) then Exit;
// 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;
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
// Turn vsync off
pDeviceSettings.pp.PresentationInterval := D3DPRESENT_INTERVAL_IMMEDIATE;
g_SettingsDlg.DialogControl.GetComboBox(DXUTSETTINGSDLG_PRESENT_INTERVAL).Enabled := False;
// 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;
//--------------------------------------------------------------------------------------
// Generate a mesh that can be tesselated.
function GenerateEnhancedMesh(pd3dDevice: IDirect3DDevice9; dwNewNumSegs: LongWord): HRESULT;
var
pMeshEnhancedSysMem: ID3DXMesh;
pMeshTemp: ID3DXMesh;
dwMeshEnhancedFlags: DWORD;
begin
if (g_pMeshSysMem = nil) then
begin
Result:= S_OK;
Exit;
end;
// if using hw, just copy the mesh
if g_bUseHWNPatches then
begin
Result := g_pMeshSysMem.CloneMeshFVF(D3DXMESH_WRITEONLY or D3DXMESH_NPATCHES or
(g_pMeshSysMem.GetOptions and D3DXMESH_32BIT),
g_pMeshSysMem.GetFVF, pd3dDevice, pMeshTemp);
if FAILED(Result) then Exit;
end else // tesselate the mesh in sw
begin
// Create an enhanced version of the mesh, will be in sysmem since source is
Result := D3DXTessellateNPatches(g_pMeshSysMem, g_pbufAdjacency.GetBufferPointer,
dwNewNumSegs, FALSE, pMeshEnhancedSysMem, nil);
if FAILED(Result) then
begin
// If the tessellate failed, there might have been more triangles or vertices
// than can fit into a 16bit mesh, so try cloning to 32bit before tessellation
Result := g_pMeshSysMem.CloneMeshFVF(D3DXMESH_SYSTEMMEM or D3DXMESH_32BIT,
g_pMeshSysMem.GetFVF, pd3dDevice, pMeshTemp);
if FAILED(Result) then Exit;
Result := D3DXTessellateNPatches(pMeshTemp, g_pbufAdjacency.GetBufferPointer,
dwNewNumSegs, FALSE, pMeshEnhancedSysMem, nil);
if FAILED(Result) then Exit;
{begin
pMeshTemp:= nil .Release;
Exit;
end;}
pMeshTemp:= nil;
end;
// Make a vid mem version of the mesh
// Only set WRITEONLY if it doesn't use 32bit indices, because those
// often need to be emulated, which means that D3DX needs read-access.
dwMeshEnhancedFlags := pMeshEnhancedSysMem.GetOptions and D3DXMESH_32BIT;
if (dwMeshEnhancedFlags and D3DXMESH_32BIT = 0)
then dwMeshEnhancedFlags := dwMeshEnhancedFlags or D3DXMESH_WRITEONLY;
Result := pMeshEnhancedSysMem.CloneMeshFVF(dwMeshEnhancedFlags, g_pMeshSysMem.GetFVF,
pd3dDevice, pMeshTemp);
if FAILED(Result) then Exit;
{begin
SAFE_RELEASE( pMeshEnhancedSysMem);
Result:= hr;
end;}
// Latch in the enhanced mesh
SAFE_RELEASE(pMeshEnhancedSysMem);
end;
SAFE_RELEASE(g_pMeshEnhanced);
g_pMeshEnhanced := pMeshTemp;
g_dwNumSegs := dwNewNumSegs;
Result:= S_OK;
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
wszMeshDir: array[0..MAX_PATH-1] of WideChar;
wszWorkingDir: array[0..MAX_PATH-1] of WideChar;
pVB: IDirect3DVertexBuffer9;
d3dCaps: TD3DCaps9;
dwShaderFlags: DWORD;
str: array[0..MAX_PATH-1] of WideChar;
pwszLastBSlash: PWideChar;
pVertices: Pointer;
i: Integer;
strTexturePath: array[0..511] of WideChar;
wszName: PWideChar;
wszBuf: array[0..MAX_PATH-1] of WideChar;
pTempMesh: ID3DXMesh;
lr: TD3DLockedRect;
vecEye, 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;
pd3dDevice.GetDeviceCaps(d3dCaps);
if (d3dCaps.DevCaps and D3DDEVCAPS_NPATCHES = 0) then
begin
// No hardware support. Disable the checkbox.
g_bUseHWNPatches := False;
g_SampleUI.GetCheckBox(IDC_HWNPATCHES).Checked := False;
g_SampleUI.GetCheckBox(IDC_HWNPATCHES).Enabled := False;
end else
g_SampleUI.GetCheckBox(IDC_HWNPATCHES).Enabled := True;
// 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;
// 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_FORCE_VS_SOFTWARE_NOOPT;
{$ENDIF}
{$IFDEF DEBUG_PS}
dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT;
{$ENDIF}
// Read the D3DX effect file
Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'EnhancedMesh.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;
// Load the mesh
Result:= DXUTFindDXSDKMediaFile(wszMeshDir, MAX_PATH, MESHFILENAME);
if V_Failed(Result) then Exit;
Result:= D3DXLoadMeshFromXW(wszMeshDir, D3DXMESH_SYSTEMMEM, pd3dDevice,
@g_pbufAdjacency, @g_pbufMaterials, nil, @g_dwNumMaterials,
g_pMeshSysMem);
if V_Failed(Result) then Exit;
// Initialize the mesh directory string
pwszLastBSlash := WideStrRScan(wszMeshDir, '\');
if (pwszLastBSlash <> nil) then pwszLastBSlash^ := #0
else StringCchCopy(wszMeshDir, MAX_PATH, PWideChar('.'));
// Lock the vertex buffer, to generate a simple bounding sphere
Result := g_pMeshSysMem.GetVertexBuffer(pVB);
if FAILED(Result) then Exit;
pVertices := nil;
Result := pVB.Lock(0, 0, pVertices, 0);
if FAILED(Result) then Exit;
{begin
SAFE_RELEASE(pVB);
Result:= hr;
end;}
Result := D3DXComputeBoundingSphere(PD3DXVector3(pVertices), g_pMeshSysMem.GetNumVertices,
D3DXGetFVFVertexSize(g_pMeshSysMem.GetFVF), g_vObjectCenter,
g_fObjectRadius);
pVB.Unlock;
SAFE_RELEASE(pVB);
if FAILED(Result) then Exit;
if (g_dwNumMaterials = 0) then
begin
Result:= E_INVALIDARG;
Exit;
end;
D3DXMatrixTranslation(g_mCenterWorld, -g_vObjectCenter.x, -g_vObjectCenter.y, -g_vObjectCenter.z);
// Change the current directory to the .x's directory so
// that the search can find the texture files.
GetCurrentDirectoryW(MAX_PATH, wszWorkingDir);
wszWorkingDir[MAX_PATH - 1] := #0;
SetCurrentDirectoryW(wszMeshDir);
// Get the array of materials out of the returned buffer, allocate a
// texture array, and load the textures
g_pMaterials := PD3DXMaterialArray(g_pbufMaterials.GetBufferPointer);
GetMem(g_ppTextures, SizeOf(IDirect3DTexture9)*g_dwNumMaterials);
ZeroMemory(g_ppTextures, SizeOf(IDirect3DTexture9)*g_dwNumMaterials);
for i := 0 to g_dwNumMaterials - 1 do
begin
strTexturePath[0] := #0;
wszName := @wszBuf;
MultiByteToWideChar(CP_ACP, 0, g_pMaterials[i].pTextureFilename, -1, wszBuf, MAX_PATH);
wszBuf[MAX_PATH - 1] := #0;
DXUTFindDXSDKMediaFile(strTexturePath, 512, wszName);
if FAILED(D3DXCreateTextureFromFileW(pd3dDevice, strTexturePath, g_ppTextures[i]))
then g_ppTextures[i] := nil;
end;
SetCurrentDirectoryW(wszWorkingDir);
// Make sure there are normals, which are required for the tesselation
// enhancement.
if (g_pMeshSysMem.GetFVF and D3DFVF_NORMAL = 0) then
begin
Result:= g_pMeshSysMem.CloneMeshFVF(g_pMeshSysMem.GetOptions,
g_pMeshSysMem.GetFVF or D3DFVF_NORMAL,
pd3dDevice, pTempMesh);
if V_Failed(Result) then Exit;
D3DXComputeNormals(pTempMesh, nil);
SAFE_RELEASE(g_pMeshSysMem);
g_pMeshSysMem := pTempMesh;
end;
// Create the 1x1 white default texture
Result:= pd3dDevice.CreateTexture(1, 1, 1, 0, D3DFMT_A8R8G8B8,
D3DPOOL_MANAGED, g_pDefaultTex, nil);
if V_Failed(Result) then Exit;
Result:= g_pDefaultTex.LockRect(0, lr, nil, 0);
if V_Failed(Result) then Exit;
PDWORD(lr.pBits)^ := D3DCOLOR_RGBA(255, 255, 255, 255);
Result:= g_pDefaultTex.UnlockRect(0);
if V_Failed(Result) then Exit;
// Setup the camera's view parameters
vecEye := D3DXVector3(0.0, 0.0, -5.0);
vecAt := D3DXVector3(0.0, 0.0, -0.0);
g_Camera.SetViewParams(vecEye, vecAt);
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;
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;
Result:= GenerateEnhancedMesh(pd3dDevice, g_dwNumSegs);
if V_Failed(Result) then Exit;
if g_bWireframe
then pd3dDevice.SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME)
else pd3dDevice.SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
// Setup the camera's projection parameters
fAspectRatio := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height;
g_Camera.SetProjParams(D3DX_PI/4, fAspectRatio, 0.1, 1000.0);
g_Camera.SetWindow(pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height);
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);
Result:= S_OK;
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; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
begin
// Update the camera's position based on user input
g_Camera.FrameMove(fElapsedTime);
pd3dDevice.SetTransform(D3DTS_WORLD, g_Camera.GetWorldMatrix^);
pd3dDevice.SetTransform(D3DTS_VIEW, g_Camera.GetViewMatrix^);
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
mWorld: TD3DXMatrixA16;
mView: TD3DXMatrixA16;
mProj: TD3DXMatrixA16;
mWorldViewProjection: TD3DXMatrixA16;
m: TD3DXMatrixA16;
cPasses: Integer;
p: Integer;
i: Integer;
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;
// Clear the render target and the zbuffer
V(pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 66, 75, 121), 1.0, 0));
// Render the scene
if SUCCEEDED(pd3dDevice.BeginScene) then
begin
// Get the projection & view matrix from the camera class
mWorld := g_Camera.GetWorldMatrix^;
mProj := g_Camera.GetProjMatrix^;
mView := g_Camera.GetViewMatrix^;
// mWorldViewProjection = g_mCenterWorld * mWorld * mView * mProj;
D3DXMatrixMultiply(m, mView, mProj);
D3DXMatrixMultiply(m, mWorld, m);
D3DXMatrixMultiply(mWorldViewProjection, g_mCenterWorld, m);
// Update the effect's variables. Instead of using strings, it would
// be more efficient to cache a handle to the parameter by calling
// ID3DXEffect::GetParameterByName
V(g_pEffect.SetMatrix('g_mWorldViewProjection', mWorldViewProjection));
V(g_pEffect.SetMatrix('g_mWorld', mWorld));
V(g_pEffect.SetFloat('g_fTime', fTime));
if g_bUseHWNPatches then
begin
pd3dDevice.SetNPatchMode(g_dwNumSegs);
end;
V(g_pEffect._Begin( @cPasses, 0 ));
for p := 0 to cPasses - 1 do
begin
V(g_pEffect.BeginPass(p));
// set and draw each of the materials in the mesh
for i := 0 to g_dwNumMaterials - 1 do
begin
V(g_pEffect.SetVector('g_vDiffuse', PD3DXVector4(@g_pMaterials[i].MatD3D.Diffuse)^));
if (g_ppTextures[i] <> nil)
then V(g_pEffect.SetTexture('g_txScene', g_ppTextures[i]))
else V(g_pEffect.SetTexture('g_txScene', g_pDefaultTex));
V(g_pEffect.CommitChanges);
g_pMeshEnhanced.DrawSubset(i);
end;
V(g_pEffect.EndPass);
end;
V(g_pEffect._End);
if g_bUseHWNPatches then pd3dDevice.SetNPatchMode(0);
RenderText;
V(g_HUD.OnRender(fElapsedTime));
V(g_SampleUI.OnRender(fElapsedTime));
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( m_pSprite, strMsg, -1, &rc, DT_NOCLIP, m_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(True)); // Show FPS
txtHelper.DrawTextLine(DXUTGetDeviceStats);
// 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('Rotate mesh: Left click drag'#10+
'Rotate camera: right click drag'#10+
'Zoom: Mouse wheel'#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.SetForegroundColor(D3DXColor(1.0, 0.75, 0.0, 1.0));
txtHelper.SetInsertionPos(10, 65);
txtHelper.DrawFormattedTextLine('NumSegs: %d'#0, [g_dwNumSegs]);
txtHelper.DrawFormattedTextLine('NumFaces: %d', [IfThen(g_pMeshEnhanced = nil, 0, g_pMeshEnhanced.GetNumFaces)]);
txtHelper.DrawFormattedTextLine('NumVertices: %d', [IfThen(g_pMeshEnhanced = nil, 0, g_pMeshEnhanced.GetNumVertices)]);
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;
//--------------------------------------------------------------------------------------
// Handles the GUI events
//--------------------------------------------------------------------------------------
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
var
pd3dDevice: IDirect3DDevice9;
begin
case nControlID of
IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen;
IDC_TOGGLEREF: DXUTToggleREF;
IDC_CHANGEDEVICE: with g_SettingsDlg do Active := not Active;
IDC_FILLMODE:
begin
g_bWireframe := (pControl as CDXUTComboBox).GetSelectedData <> nil;
pd3dDevice := DXUTGetD3DDevice;
pd3dDevice.SetRenderState(D3DRS_FILLMODE, IfThen(g_bWireframe, D3DFILL_WIREFRAME, D3DFILL_SOLID));
end;
IDC_SEGMENT:
begin
g_dwNumSegs := (pControl as CDXUTSlider).Value;
g_SampleUI.GetStatic(IDC_SEGMENTLABEL).Text:= PWideChar(WideFormat('Number of segments: %u', [g_dwNumSegs]));
GenerateEnhancedMesh(DXUTGetD3DDevice, g_dwNumSegs);
end;
IDC_HWNPATCHES:
begin
g_bUseHWNPatches := (pControl as CDXUTCheckBox).Checked;
GenerateEnhancedMesh(DXUTGetD3DDevice, g_dwNumSegs);
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;
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_pMeshEnhanced);
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
i: Integer;
begin
g_DialogResourceManager.OnDestroyDevice;
g_SettingsDlg.OnDestroyDevice;
SAFE_RELEASE(g_pEffect);
SAFE_RELEASE(g_pFont);
for i := 0 to g_dwNumMaterials - 1 do SAFE_RELEASE(g_ppTextures[i]);
SAFE_RELEASE(g_pDefaultTex);
FreeMem(g_ppTextures);
SAFE_RELEASE(g_pMeshSysMem);
SAFE_RELEASE(g_pbufMaterials);
SAFE_RELEASE(g_pbufAdjacency);
g_dwNumMaterials := 0;
end;
procedure CreateCustomDXUTobjects;
begin
g_DialogResourceManager:= CDXUTDialogResourceManager.Create; // manager for shared resources of dialogs
g_SettingsDlg:= CD3DSettingsDlg.Create; // Device settings dialog
g_Camera:= CModelViewerCamera.Create;
g_HUD := CDXUTDialog.Create;
g_SampleUI:= CDXUTDialog.Create;
end;
procedure DestroyCustomDXUTobjects;
begin
FreeAndNil(g_DialogResourceManager);
FreeAndNil(g_SettingsDlg);
FreeAndNil(g_Camera);
FreeAndNil(g_HUD);
FreeAndNil(g_SampleUI);
end;
end.
|
unit Unit_Example;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,ZipForge;
type
TMainForm = class(TForm)
Button1: TButton;
Edit1: TEdit;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
type
TFileUnZiper = class(TZipForge)
strict private
FFailure:LongBool;
public
procedure OnError(Sender: TObject; FileName: TZFString;
Operation: TZFProcessOperation; NativeError: integer;
ErrorCode: integer; ErrorMessage: TZFString; var Action: TZFAction);
public
property IsError:LongBool read FFailure write FFailure;
end;
function UnZipFile(const fileToExtra:string;aes256Key:ansistring ='';extraName:string ='';extraDir:string =''):LongBool;
var
zipProcesser:TFileUnZiper;
begin
Result:=False;
zipProcesser:=TFileUnZiper.Create(nil);
try
try
with zipProcesser do
begin
FileName:=fileToExtra;
OpenArchive(fmOpenRead);
EncryptionMethod:=caAES_256;
Password:=aes256Key;
if extraDir = '' then
extraDir :=ExtractFilePath(ParamStr(0));
BaseDir:=extraDir;
if extraName = '' then
extraName :='*.*';
OnProcessFileFailure:=OnError;
IsError:=False;
ExtractFiles(extraName);
CloseArchive;
end;
Result:=Not zipProcesser.IsError;
except
end;
finally
zipProcesser.Free;
end;
end;
procedure TMainForm.Button1Click(Sender: TObject);
begin
if not UnZipFile('123.zip','123456') then ShowMessage('failedx');
end;
{ TFileUnZiper }
procedure TFileUnZiper.OnError(Sender: TObject; FileName: TZFString;
Operation: TZFProcessOperation; NativeError, ErrorCode: integer;
ErrorMessage: TZFString; var Action: TZFAction);
begin
FFailure:=True;
Action:=fxaIgnore;
end;
end.
|
unit ConsoleForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, TlHelp32;
type
TArg<T> = reference to procedure(const Arg: T);
TForm5 = class(TForm)
Memo1: TMemo;
location: TEdit;
parameters: TEdit;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
procedure RunDosInMemo(const ACommand, AParameters: String;
CallBack: TArg<PAnsiChar>);
procedure KillTaskSender(Task:String);
end;
var
Form5: TForm5;
implementation
{$R *.dfm}
uses MainForm;
function KillTask(ExeFileName: string): Integer;
const
PROCESS_TERMINATE = $0001;
var
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
Result := 0;
FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize := SizeOf(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
while Integer(ContinueLoop) <> 0 do
begin
if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile))
= UpperCase(ExeFileName)) or (UpperCase(FProcessEntry32.szExeFile)
= UpperCase(ExeFileName))) then
Result := Integer(TerminateProcess(OpenProcess(PROCESS_TERMINATE, BOOL(0),
FProcessEntry32.th32ProcessID), 0));
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
end;
procedure TForm5.KillTaskSender(Task: string);
begin
KillTask(Task);
end;
procedure TForm5.RunDosInMemo(const ACommand, AParameters: String;
CallBack: TArg<PAnsiChar>);
const
CReadBuffer = 2400;
var
saSecurity: TSecurityAttributes;
hRead: THandle;
hWrite: THandle;
suiStartup: TStartupInfo;
piProcess: TProcessInformation;
pBuffer: array [0 .. CReadBuffer] of AnsiChar;
dBuffer: array [0 .. CReadBuffer] of AnsiChar;
dRead: DWORD;
dRunning: DWORD;
dAvailable: DWORD;
begin
saSecurity.nLength := SizeOf(TSecurityAttributes);
saSecurity.bInheritHandle := true;
saSecurity.lpSecurityDescriptor := nil;
if CreatePipe(hRead, hWrite, @saSecurity, 0) then
try
FillChar(suiStartup, SizeOf(TStartupInfo), #0);
suiStartup.cb := SizeOf(TStartupInfo);
suiStartup.hStdInput := hRead;
suiStartup.hStdOutput := hWrite;
suiStartup.hStdError := hWrite;
suiStartup.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
suiStartup.wShowWindow := SW_HIDE;
if CreateProcess(nil, PChar(ACommand + ' ' + AParameters), @saSecurity,
@saSecurity, true, NORMAL_PRIORITY_CLASS, nil, nil, suiStartup,
piProcess) then
try
repeat
dRunning := WaitForSingleObject(piProcess.hProcess, 2);
PeekNamedPipe(hRead, nil, 0, nil, @dAvailable, nil);
if (dAvailable > 0) then
repeat
dRead := 0;
ReadFile(hRead, pBuffer[0], CReadBuffer, dRead, nil);
pBuffer[dRead] := #0;
OemToCharA(pBuffer, dBuffer);
CallBack(dBuffer);
until (dRead < CReadBuffer);
Application.ProcessMessages;
until (dRunning <> WAIT_TIMEOUT);
finally
CloseHandle(piProcess.hProcess);
CloseHandle(piProcess.hThread);
end;
finally
CloseHandle(hRead);
CloseHandle(hWrite);
end;
end;
procedure TForm5.Button1Click(Sender: TObject);
begin
RunDosInMemo('youtube-dl',
'--output "K:\%(title)s.%(ext)s" https://www.youtube.com/watch?v=7k3_BnMOFdc',
procedure(const Line: PAnsiChar)
begin
Memo1.Lines.Add(String(Line));
end);
end;
procedure TForm5.FormClose(Sender: TObject; var Action: TCloseAction);
begin
KillTask('youtube-dl.exe');
Form1.Timer2.Enabled := False;
end;
procedure TForm5.FormCreate(Sender: TObject);
begin
Memo1.Clear;
Form1.Timer2.Enabled := true;
end;
end.
|
unit uDMExport;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uDMParent, ADODB, DB, DBClient, ImgList, uSaveToFile;
const
REG_PATH = 'SOFTWARE\Microsoft\Windows\CurrentVersion\Run';
type
TBasicClass = class
public
function Insert : Boolean; virtual; abstract;
end;
TCashRegister = class(TBasicClass)
public
IDCashRegister : Integer;
RegisterName : String;
IsAssociated : Boolean;
function Insert : Boolean; override;
end;
TModelSize = class(TBasicClass)
public
IDSize : Integer;
SizeName : String;
function Insert : Boolean; override;
end;
TModelColor = class(TBasicClass)
public
IDColor : Integer;
ColorName : String;
function Insert : Boolean; override;
end;
TMicrochip = class(TBasicClass)
public
IDMicrochip : Integer;
IDModel : Integer;
Microchip : String;
Amount : Currency;
function Find : Boolean;
function Insert : Boolean; override;
end;
TModel = class(TBasicClass)
public
IDCategory : Integer;
IDModel : Integer;
Barcode : String;
Model : String;
Description : String;
Qty : Double;
CostPrice : Double;
SalePrice : Double;
ModelType : Char;
function Find : Boolean;
function Insert : Boolean; override;
end;
TModelChild = class(TBasicClass)
public
IDModelParent : Integer;
IDModel : Integer;
IDSize : Integer;
IDColor : Integer;
Qty : Double;
SalePrice : Double;
function Insert : Boolean; override;
end;
TPessoaTipo = class(TBasicClass)
public
IDTipoPessoaRoot : Integer;
IDTipoPessoa : Integer;
TipoPessoa : String;
Path : String;
function Insert : Boolean; override;
end;
TPessoa = class(TBasicClass)
public
IDPessoa : Integer;
IDTipoPessoa : String;
Path : String;
PessoaName : String;
FName : String;
LName : String;
Phone : String;
Juridico : String;
function Insert : Boolean; override;
end;
TTax = class(TBasicClass)
public
IDSaleTax : Integer;
SaleTaxName : String;
SaleTax : Double;
BrazilMode : Boolean;
IDEncargos : Integer;
EncargosVendas : Double;
IDIPI : Integer;
IPI : Double;
IDCOFINS : Integer;
COFINS : Double;
IDPIS : Integer;
PIS : Double;
function Insert : Boolean; override;
end;
TParams = class(TBasicClass)
public
TaxOnCost : Boolean;
ExemptTaxOnSale : Boolean;
SimpleTax : Boolean;
PostDateSale : Boolean;
MaxNumberForPostDate : Integer;
DeliveryFeature : Boolean;
function Insert : Boolean; override;
end;
TStore = class(TBasicClass)
public
ID : Integer;
StoreName : String;
Address : String;
City : String;
Neighborhood : String;
Zip : String;
IDState : String;
StoreState : String;
Tel : String;
Fax : String;
Email : String;
Web : String;
TicketHeader : String;
TicketLayawayFooter : String;
TicketTaxIsemptFooter : String;
Contat : String;
function Insert : Boolean; override;
end;
TCategory = class(TBasicClass)
public
IDCategory : Integer;
Category : String;
SizeAndColor : Boolean;
PackModel : Boolean;
PackModelAddItems : Boolean;
PuppyTracker : Boolean;
function Find : Boolean;
function Insert : Boolean; override;
end;
TDMExport = class(TDMParent)
cdsCategory: TClientDataSet;
cdsCategoryID: TIntegerField;
cdsCategoryCategory: TStringField;
cdsCategoryMarkup: TFloatField;
cdsCategorySizeAndColor: TBooleanField;
dsCategory: TDataSource;
dsModel: TDataSource;
cdsModel: TClientDataSet;
cdsModelCategory: TStringField;
cdsModelModel: TStringField;
cdsModelDescription: TStringField;
cdsModelCostPrice: TCurrencyField;
cdsModelSalePrice: TCurrencyField;
cdsModelQty: TFloatField;
cdsModelBarcode: TStringField;
cmdFree: TADOCommand;
cdsUser: TClientDataSet;
dsUser: TDataSource;
cdsUserIDUser: TIntegerField;
cdsUserUserName: TStringField;
cdsUserPassword: TStringField;
cdsUserIDUserType: TIntegerField;
cdsVendor: TClientDataSet;
dsVendor: TDataSource;
cdsVendorIDVendor: TIntegerField;
cdsVendorVendor: TStringField;
cdsVendorPhone: TStringField;
cdsSize: TClientDataSet;
cdsColor: TClientDataSet;
cdsGrid: TClientDataSet;
dsSize: TDataSource;
dsColor: TDataSource;
dsGrid: TDataSource;
cdsSizeIDSize: TIntegerField;
cdsSizeMSize: TStringField;
cdsColorIDColor: TIntegerField;
cdsColorMColor: TStringField;
cdsGridModel: TStringField;
cdsGridMSize: TStringField;
cdsGridMColor: TStringField;
cdsGridQty: TFloatField;
cdsGridSalePrice: TCurrencyField;
cdsCategorySizeList: TWideStringField;
cdsCategoryColorList: TWideStringField;
cdsModelSizeAndColor: TBooleanField;
cdsModelIDModel: TIntegerField;
spAddSize: TADOStoredProc;
spAddColor: TADOStoredProc;
cdsCategorySystem: TBooleanField;
cdsPetCustomer: TClientDataSet;
cdsPetCustomerID: TStringField;
cdsPetCustomerStore: TStringField;
cdsPetCustomerAddress: TStringField;
cdsPetCustomerCity: TStringField;
cdsPetCustomerState: TStringField;
cdsPetCustomerZip: TStringField;
cdsPetCustomerPhone: TStringField;
cdsPetCustomerFax: TStringField;
cdsPetCustomerEmail: TStringField;
cdsPetCustomerWeb: TStringField;
cdsPetCustomerContact1: TStringField;
cdsPetCustomerPhone1: TStringField;
cdsPetCustomerEmail1: TStringField;
cdsPetCustomerAddress2: TStringField;
cdsPetCustomerCountry: TStringField;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
procedure cdsCategoryNewRecord(DataSet: TDataSet);
procedure cdsModelBeforePost(DataSet: TDataSet);
private
FSQLCommands : TStringList;
public
FModelOldValue : String;
FCategoryOldValue : String;
FParams : TParams;
FStore : TStore;
FTax : TTax;
IDLanguage : Integer;
function StartDatabaseConnection: Boolean;
procedure WriteConnectionDefaultValues;
procedure AddLog(AText : String);
function CreateMainRetailData : Boolean;
function GetInsStr(Str: string): string;
procedure RunCommand(Query : TADOQuery);
procedure SaveSQLCommands;
function IsEmptyDataBase : Boolean;
procedure OpenModel;
procedure CloseModel;
procedure AppendModel;
procedure LoadModels(BusinessType : String);
function GetIDModel(Model : String): Integer;
procedure OpenCategory;
procedure CloseCategory;
procedure AppendCategory;
procedure LoadCategories(BusinessType : String);
function GetIDCategory(Category : String): Integer;
function SizeAndColorCategory(Category : String; var SizeList, ColorList : String):Boolean;
procedure OpenUser;
procedure CloseUser;
procedure CreateDefaulUsers;
procedure OpenVendor;
procedure CloseVendor;
procedure CreateDefaulVendors;
procedure OpenSize;
procedure CloseSize;
procedure LoadSize;
function GetIDSize(MSize : String):Integer;
procedure OpenColor;
procedure CloseColor;
procedure LoadColor;
function GetIDColor(MColor : String):Integer;
procedure OpenGrid;
procedure CloseGrid;
procedure LoadGrid;
procedure RemoveGridModel(Model : String);
procedure LoadGridModel(Model, Category : String; Qty : Double; Sale : Currency);
procedure ChangeGridModel(ModelOld, ModelNew : String);
procedure BuildCashRegister;
procedure BuildUsers;
procedure BuildCategories;
procedure BuildVendor;
procedure BuildModel;
procedure BuildModelChild;
procedure SaveRegistryInfo;
procedure SaveWinStartUp(AKey, ASoftware : String);
procedure DeleteWinStartUp(AKey : String);
function RegKeyExist(AKey : string) : Boolean;
function FieldExist(cds: TClientDataSet; Field, Value: String):Boolean;
function ValueExist(ATable, AField1, AField2, AValue1, AValue2 : String) : Boolean;
function CreateGuid: string;
function CreatePetWrdFile : Boolean;
function DeletePetWrdFile : Boolean;
function CheckPetWrdFile : Boolean;
//Pet Data
function InsertBreed(ABreed : String):Boolean;
function InsertColor(AColor : String):Boolean;
function InsertMedicalCondition(AMedical, ASubMedical : String):Boolean;
function InsertTreamtne(ATreatment, AManu : String; AType : Integer):Boolean;
end;
var
DMExport: TDMExport;
implementation
uses IniFiles, StrUtils, uParamFunctions, uFrmServerinfo, uMsgBox,
uTranslateScript, Registry, uSystemConst, ComObj, ActiveX, uEncryptFunctions,
uOperationSystem;
{$R *.dfm}
{ TDMExport }
function TDMExport.CreateGuid: string;
var
ID: TGUID;
begin
Result := '';
if CoCreateGuid(ID) = S_OK then
Result := GUIDToString(ID);
end;
procedure TDMExport.AppendCategory;
begin
with cdsCategory do
if Active then
Append;
end;
procedure TDMExport.AppendModel;
begin
with cdsModel do
if Active then
Append;
end;
procedure TDMExport.CloseCategory;
begin
with cdsCategory do
if Active then
Close;
end;
procedure TDMExport.CloseModel;
begin
with cdsModel do
if Active then
Close;
end;
procedure TDMExport.CloseUser;
begin
with cdsUser do
if Active then
Close;
end;
procedure TDMExport.LoadCategories(BusinessType: String);
var
FCategoryFile : TIniFile;
FSections : TStringList;
FFileName : String;
i : Integer;
begin
FFileName := LocalPath+'Category\'+BusinessType + '.ini';
if FileExists(FFileName) then
begin
FCategoryFile := TIniFile.Create(FFileName);
try
FSections := TStringList.Create;
try
FCategoryFile.ReadSections(FSections);
for i := 0 to FSections.Count-1 do
begin
with cdsCategory do
if Active then
begin
Append;
FieldByName('Category').Value := FSections.Strings[i];
FieldByName('Markup').Value := FCategoryFile.ReadFloat(FSections.Strings[i], 'Markup', 100);
FieldByName('SizeAndColor').Value := FCategoryFile.ReadBool(FSections.Strings[i], 'SizeAndColor', False);
FieldByName('SizeList').Value := FCategoryFile.ReadString(FSections.Strings[i], 'SizeList', '');
FieldByName('ColorList').Value := FCategoryFile.ReadString(FSections.Strings[i], 'ColorList', '');
FieldByName('System').Value := True;
Post;
end;
end;
OpenColor;
OpenSize;
cdsCategory.First;
finally
FreeAndNil(FCategoryFile);
end;
finally
FreeAndNil(FCategoryFile);
end;
end;
end;
procedure TDMExport.LoadModels(BusinessType: String);
var
FFileData : TStringList;
FFileName : String;
begin
FFileName := LocalPath+'Category\'+BusinessType + '.xml';
if FileExists(FFileName) then
begin
FFileData := TStringList.Create;
try
FFileData.LoadFromFile(FFileName);
cdsModel.XMLData := FFileData.Text;
cdsModel.First;
finally
FreeAndNil(FFileData);
end;
end;
end;
procedure TDMExport.OpenCategory;
begin
with cdsCategory do
if not Active then
CreateDataSet;
end;
procedure TDMExport.OpenModel;
begin
with cdsModel do
if not Active then
CreateDataSet;
end;
procedure TDMExport.OpenUser;
begin
with cdsUser do
if not Active then
begin
CreateDataSet;
CreateDefaulUsers;
end;
end;
procedure TDMExport.DataModuleCreate(Sender: TObject);
begin
inherited;
FParams := TParams.Create;
FStore := TStore.Create;
FTax := TTax.Create;
cdsCategory.CreateDataSet;
cdsModel.CreateDataSet;
FSQLCommands := TStringList.Create;
SetMsgBoxLand(1);
end;
procedure TDMExport.DataModuleDestroy(Sender: TObject);
begin
inherited;
FreeAndNil(FParams);
FreeAndNil(FStore);
FreeAndNil(FTax);
cdsCategory.Close;
cdsModel.Close;
FreeAndNil(FSQLCommands);
end;
procedure TDMExport.cdsCategoryNewRecord(DataSet: TDataSet);
begin
inherited;
cdsCategory.FieldByName('Markup').Value := 100;
cdsCategory.FieldByName('SizeAndColor').Value := False;
end;
function TDMExport.GetInsStr(Str: string): string;
begin
//Returns 'NULL' for blank text in Edit
if Trim(Str) <> '' then
Result := QuotedStr(Trim(Str))
else
Result := 'NULL';
end;
procedure TDMExport.CreateDefaulUsers;
var
sUserName : String;
begin
case IDLanguage of
1 : sUserName := 'User';
2 : sUserName := 'Usuario';
end;
with cdsUser do
begin
Append;
FieldByName('UserName').Value := sUserName + '1';
FieldByName('Password').Value := '1';
FieldByName('IDUserType').Value := 1;
Post;
end;
with cdsUser do
begin
Append;
FieldByName('UserName').Value := sUserName + '2';
FieldByName('Password').Value := '2';
FieldByName('IDUserType').Value := 2;
Post;
end;
with cdsUser do
begin
Append;
FieldByName('UserName').Value := sUserName + '3';
FieldByName('Password').Value := '3';
FieldByName('IDUserType').Value := 4;
Post;
end;
end;
function TDMExport.CreateMainRetailData: Boolean;
begin
FModelOldValue := '';
FCategoryOldValue := '';
Result := StartDatabaseConnection;
if Result then
try
//TRanslation
TranslateDatabase(IDLanguage, quFreeSQL);
ADODBConnect.BeginTrans;
//Store
FStore.Insert;
//User
BuildUsers;
//Param
FParams.Insert;
//Cash Register
BuildCashRegister;
//Tax
FTax.Insert;
//Vendor
BuildVendor;
//Category
BuildCategories;
//Model
BuildModel;
//Model Child
BuildModelChild;
ADODBConnect.CommitTrans;
SaveSQLCommands;
SaveRegistryInfo;
except
on E: Exception do
begin
ADODBConnect.RollbackTrans;
FSQLCommands.Add(E.Message);
SaveSQLCommands;
MsgBox('Error:' + E.Message, vbOkOnly + vbInformation);
Result := False;
end;
end;
end;
function TDMExport.StartDatabaseConnection: Boolean;
var
sResult : String;
FrmServrInfo : TFrmServerInfo;
cStartType : char;
bAbort : Boolean;
begin
Result := False;
FrmServrInfo := nil;
try
FrmServrInfo := TFrmServerInfo.Create(self);
//D - Demo, 1,2,3,4 - Modules
cStartType := '4';
WriteConnectionDefaultValues;
sResult := FrmServrInfo.Start(cStartType, False, '', bAbort);
While not bAbort do
try
fSQLConnectParam.Server := ParseParam(sResult, SV_SERVER);
fSQLConnectParam.DBAlias := ParseParam(sResult, SV_DATABASE);
fSQLConnectParam.UserName := ParseParam(sResult, SV_USER);
fSQLConnectParam.PW := ParseParam(sResult, SV_PASSWORD);
fSQLConnectParam.WinLogin := (ParseParam(sResult, SV_WIN_LOGIN)[1] in ['Y']);
fSQLConnectParam.UseNetLib := (ParseParam(sResult, SV_USE_NETLIB)[1] = 'Y');
if not fSQLConnectParam.WinLogin then
if fSQLConnectParam.UseNetLib then
sResult := SetConnectionStr(fSQLConnectParam.UserName,
fSQLConnectParam.PW,
fSQLConnectParam.DBAlias,
fSQLConnectParam.Server)
else
sResult := SetConnectionStrNoNETLIB(fSQLConnectParam.UserName,
fSQLConnectParam.PW,
fSQLConnectParam.DBAlias,
fSQLConnectParam.Server)
else
if fSQLConnectParam.UseNetLib then
sResult := SetWinConnectionStr(fSQLConnectParam.DBAlias,
fSQLConnectParam.Server)
else
sResult := SetWinConnectionStrNoNETLIB(fSQLConnectParam.DBAlias,
fSQLConnectParam.Server);
ADOConnectionString := sResult;
ADOConnectionOpen;
Result := True;
bAbort := True;
except
on E: Exception do
begin
sResult := FrmServrInfo.Start(cStartType, True, E.Message, bAbort);
Result := False;
end;
end;
finally
FrmServrInfo.Free;
end;
end;
procedure TDMExport.BuildUsers;
var
IDP, IDS : Integer;
Pessoa : TPessoa;
begin
with cdsUser do
begin
First;
while not Eof do
begin
Pessoa := TPessoa.Create;
try
Pessoa.IDTipoPessoa := '4';
Pessoa.Path := '.003.001';
Pessoa.PessoaName := FieldByName('UserName').AsString;
Pessoa.FName := FieldByName('UserName').AsString;
Pessoa.LName := FieldByName('UserName').AsString;
Pessoa.Phone := '';
Pessoa.Juridico := '0';
Pessoa.Insert;
IDP := Pessoa.IDPessoa;
finally
FreeAndNil(Pessoa);
end;
//Adiciona Usuario
quFreeSQL.SQL.Clear;
IDS := GetNextID('SystemUser.IDUser');
quFreeSQL.SQL.Add('INSERT INTO SystemUser (IDUser, SystemUser, CodSystemUser, PW, UserTypeID, StoresAccess, ComissionID)');
quFreeSQL.SQL.Add(' VALUES ('+ IntToStr(IDS) +', '+
QuotedStr(FieldByName('UserName').AsString) +', '+
QuotedStr(FieldByName('UserName').AsString) +', '+
QuotedStr(FieldByName('Password').AsString) +', '+
IntToStr(FieldByName('IDUserType').AsInteger) +', '+
IntToStr(FStore.ID) +', '+
IntToStr(IDP) + ')');
RunCommand(quFreeSQL);
Edit;
FieldByName('IDUser').AsInteger := IDS;
Post;
Next;
end;
end;
end;
procedure TDMExport.RunCommand(Query: TADOQuery);
var
cmd : String;
begin
try
cmd := Query.SQL.GetText;
FSQLCommands.Add(cmd);
FSQLCommands.Add('GO');
FSQLCommands.Add('');
Query.ExecSQL;
except
on E: Exception do
DMExport.AddLog('RunCommand : msg = ' + E.Message + '. Cmd = ' + cmd);
end;
end;
procedure TDMExport.BuildCategories;
var
Category : TCategory;
IDC : Integer;
begin
with cdsCategory do
begin
First;
while not Eof do
begin
Category := TCategory.Create;
try
Category.Category := FieldByName('Category').AsString;
Category.SizeAndColor := FieldByName('SizeAndColor').AsBoolean;
Category.Insert;
IDC := Category.IDCategory;
finally
FreeAndNil(Category);
end;
Edit;
FieldByName('ID').AsInteger := IDC;
Post;
Next;
end;
end;
end;
procedure TDMExport.SaveSQLCommands;
begin
FSQLCommands.SaveToFile(LocalPath + 'MRWizard.sql');
end;
procedure TDMExport.CloseVendor;
begin
with cdsVendor do
if Active then
Close;
end;
procedure TDMExport.CreateDefaulVendors;
var
sUserName : String;
begin
case IDLanguage of
1 : sUserName := 'Vendor';
2 : sUserName := 'Fornecedor';
end;
with cdsVendor do
begin
Append;
FieldByName('Vendor').Value := sUserName + ' 1';
FieldByName('Phone').Value := '1111-1111';
Post;
end;
with cdsVendor do
begin
Append;
FieldByName('Vendor').Value := sUserName + ' 2';
FieldByName('Phone').Value := '2222-2222';
Post;
end;
with cdsVendor do
begin
Append;
FieldByName('Vendor').Value := sUserName + ' 3';
FieldByName('Phone').Value := '3333-3333';
Post;
end;
end;
procedure TDMExport.OpenVendor;
begin
with cdsVendor do
if not Active then
begin
CreateDataSet;
CreateDefaulVendors;
end;
end;
procedure TDMExport.BuildVendor;
var
Pessoa : TPessoa;
IDP : Integer;
begin
with cdsVendor do
begin
First;
while not Eof do
begin
Pessoa := TPessoa.Create;
try
Pessoa.IDTipoPessoa := '2';
Pessoa.Path := '.002';
Pessoa.PessoaName := FieldByName('Vendor').AsString;
Pessoa.FName := '';
Pessoa.LName := '';
Pessoa.Phone := FieldByName('Phone').AsString;
Pessoa.Juridico := '1';
Pessoa.Insert;
IDP := Pessoa.IDPessoa;
finally
FreeAndNil(Pessoa);
end;
Edit;
FieldByName('IDVendor').AsInteger := IDP;
Post;
Next;
end;
end;
end;
procedure TDMExport.BuildModel;
var
Model : TModel;
s1, s2 : String;
begin
with cdsModel do
begin
First;
while not Eof do
begin
Model := TModel.Create;
try
Model.IDCategory := GetIDCategory(FieldByName('Category').AsString);
Model.Barcode := FieldByName('Barcode').AsString;
Model.Model := FieldByName('Model').AsString;
Model.Description := FieldByName('Description').AsString;
Model.Qty := FieldByName('Qty').AsFloat;
Model.CostPrice := FieldByName('CostPrice').AsCurrency;
Model.SalePrice := FieldByName('SalePrice').AsCurrency;
if SizeAndColorCategory(FieldByName('Category').AsString, s1, s2) then
begin
Model.ModelType := 'M';
end
else
begin
Model.ModelType := 'R';
end;
if Model.Insert then
begin
Edit;
FieldByName('IDModel').AsInteger := Model.IDModel;
Post;
end;
finally
FreeAndNil(Model);
end;
Next;
end;
end;
end;
function TDMExport.GetIDCategory(Category: String): Integer;
begin
if cdsCategory.Locate('Category', Category, []) then
Result := cdsCategory.FieldByName('ID').AsInteger
else
Result := 0;
end;
procedure TDMExport.BuildCashRegister;
var
CashRegister : TCashRegister;
begin
CashRegister := TCashRegister.Create;
try
CashRegister.RegisterName := 'Caixa01';
CashRegister.IsAssociated := True;
CashRegister.Insert;
finally
FreeAndNil(CashRegister);
end;
end;
procedure TDMExport.CloseColor;
begin
with cdsColor do
if Active then
Close;
end;
procedure TDMExport.CloseGrid;
begin
with cdsGrid do
if Active then
Close;
end;
procedure TDMExport.CloseSize;
begin
with cdsSize do
if Active then
Close;
end;
procedure TDMExport.OpenColor;
begin
with cdsColor do
if not Active then
begin
CreateDataSet;
LoadColor;
end;
end;
procedure TDMExport.OpenGrid;
begin
with cdsGrid do
if not Active then
begin
CreateDataSet;
LoadGrid;
end;
end;
procedure TDMExport.OpenSize;
begin
with cdsSize do
if not Active then
begin
CreateDataSet;
LoadSize;
end;
end;
procedure TDMExport.RemoveGridModel(Model : String);
var
FilterTmp : String;
begin
with cdsGrid do
if Active then
begin
FilterTmp := Filter;
Filtered := False;
Filter := 'Model = ' + QuotedStr(Model);
Filtered := True;
First;
While (RecordCount <> 0) do
begin
Edit;
Delete;
end;
Filtered := False;
Filter := FilterTmp;
Filtered := True;
end;
end;
procedure TDMExport.ChangeGridModel(ModelOld, ModelNew : String);
var
FilterTmp : String;
begin
with cdsGrid do
if Active then
begin
FilterTmp := Filter;
Filtered := False;
Filter := 'Model = ' + QuotedStr(ModelOld);
Filtered := True;
While not EOF do
begin
if cdsGrid.FieldByName('Model').AsString = ModelOld then
begin
Edit;
cdsGrid.FieldByName('Model').AsString := ModelNew;
Post;
end;
First; //Tem que ser o First, pois apos o update com filtro tem que voltar para a 1 linha
end;
Filtered := False;
Filter := FilterTmp;
Filtered := True;
end;
end;
procedure TDMExport.LoadGridModel(Model, Category : String; Qty : Double; Sale : Currency);
var
FSizeList, FColorList : String;
STSizeList, STColorList: TStringList;
i, j : Integer;
begin
RemoveGridModel(Model);
with cdsGrid do
if Active then
begin
if SizeAndColorCategory(Category, FSizeList, FColorList) then
begin
STSizeList := TStringList.Create;
STColorList := TStringList.Create;
try
STSizeList.CommaText := FSizeList;
STColorList.CommaText := FColorList;
for i := 0 to (STSizeList.Count-1) do
for j := 0 to (STColorList.Count-1) do
begin
if ((STSizeList.Strings[i] <> '') and (STColorList.Strings[j] <> '')) and
(not Locate('Model;MSize;MColor', VarArrayOf([Model, STSizeList.Strings[i], STColorList.Strings[j]]), [])) then
begin
Append;
FieldByName('Model').Value := Model;
FieldByName('MSize').Value := STSizeList.Strings[i];
FieldByName('MColor').Value := STColorList.Strings[j];
FieldByName('Qty').Value := Qty;
FieldByName('SalePrice').Value := Sale;
Post;
end;
end;
finally
FreeAndNil(STSizeList);
FreeAndNil(STColorList);
end;
end;
end;
end;
procedure TDMExport.LoadGrid;
begin
with cdsModel do
if Active then
while not EOF do
begin
LoadGridModel(FieldByName('Model').AsString,
FieldByName('Category').AsString,
FieldByName('Qty').AsFloat,
FieldByName('SalePrice').AsCurrency);
Next;
end;
end;
procedure TDMExport.LoadColor;
var
FList : TStringList;
i : Integer;
begin
FList := TStringList.Create;
try
with cdsCategory do
if Active then
begin
First;
while not EOF do
begin
if FieldByName('SizeAndColor').AsBoolean then
FList.CommaText := FList.CommaText + FieldByName('ColorList').AsString + ',';
Next;
end;
end;
with cdsColor do
if Active then
for i := 0 to (FList.Count-1) do
if (FList.Strings[i] <> '') and not Locate('MColor', FList.Strings[i], []) then
begin
Append;
FieldByName('MColor').AsString := FList.Strings[i];
Post;
end;
finally
FreeAndNil(FList);
end;
end;
procedure TDMExport.LoadSize;
var
FList : TStringList;
i : Integer;
begin
FList := TStringList.Create;
try
with cdsCategory do
if Active then
begin
First;
while not EOF do
begin
if FieldByName('SizeAndColor').AsBoolean then
FList.CommaText := FList.CommaText + FieldByName('SizeList').AsString + ',';
Next;
end;
end;
with cdsSize do
if Active then
for i := 0 to (FList.Count-1) do
if (FList.Strings[i] <> '') and not Locate('MSize', FList.Strings[i], []) then
begin
Append;
FieldByName('MSize').AsString := FList.Strings[i];
Post;
end;
finally
FreeAndNil(FList);
end;
end;
function TDMExport.SizeAndColorCategory(Category: String; var SizeList,
ColorList: String): Boolean;
begin
Result := False;
if cdsCategory.Locate('Category', Category, []) then
begin
Result := cdsCategory.FieldByName('SizeAndColor').AsBoolean;
SizeList := cdsCategory.FieldByName('SizeList').AsString;
ColorList := cdsCategory.FieldByName('ColorList').AsString;
end;
end;
procedure TDMExport.cdsModelBeforePost(DataSet: TDataSet);
var
s1, s2 : String;
begin
inherited;
cdsModel.FieldByName('SizeAndColor').Value := SizeAndColorCategory(cdsModel.FieldByName('Category').AsString, s1, s2);
if (FModelOldValue <> '') and (FModelOldValue <> DMExport.cdsModel.FieldByName('Model').NewValue) then
begin
ChangeGridModel(FModelOldValue, DMExport.cdsModel.FieldByName('Model').NewValue);
end;
if (FCategoryOldValue <> '') and (FCategoryOldValue <> DMExport.cdsModel.FieldByName('Category').NewValue) then
begin
RemoveGridModel(FModelOldValue);
LoadGridModel(cdsModel.FieldByName('Model').NewValue,
cdsModel.FieldByName('Category').NewValue,
cdsModel.FieldByName('Qty').NewValue,
cdsModel.FieldByName('SalePrice').NewValue);
end;
end;
procedure TDMExport.BuildModelChild;
var
FSize : TModelSize;
FColor : TModelColor;
FModelChild : TModelChild;
begin
FSize := TModelSize.Create;
FColor := TModelColor.Create;
FModelChild := TModelChild.Create;
try
with cdsSize do
if Active then
begin
First;
while not EOF do
begin
FSize.SizeName := FieldByName('MSize').AsString;
if FSize.Insert then
begin
Edit;
FieldByName('IDSize').AsInteger := FSize.IDSize;
Post;
end;
Next;
end;
end;
with cdsColor do
if Active then
begin
First;
while not EOF do
begin
FColor.ColorName := FieldByName('MColor').AsString;
if FColor.Insert then
begin
Edit;
FieldByName('IDColor').AsInteger := FColor.IDColor;
Post;
end;
Next;
end;
end;
with cdsGrid do
if Active then
begin
First;
while not EOF do
begin
FModelChild.IDModelParent := GetIDModel(FieldByName('Model').AsString);
FModelChild.IDSize := GetIDSize(FieldByName('MSize').AsString);
FModelChild.IDColor := GetIDColor(FieldByName('MColor').AsString);
FModelChild.Qty := FieldByName('Qty').AsFloat;
FModelChild.SalePrice := FieldByName('SalePrice').AsCurrency;
FModelChild.Insert;
Next;
end;
end;
finally
FreeAndNil(FSize);
FreeAndNil(FColor);
FreeAndNil(FModelChild);
end;
end;
function TDMExport.GetIDModel(Model: String): Integer;
begin
if cdsModel.Locate('Model', Model, []) then
Result := cdsModel.FieldByName('IDModel').AsInteger
else
Result := 0;
end;
function TDMExport.GetIDSize(MSize: String): Integer;
begin
if cdsSize.Locate('MSize', MSize, []) then
Result := cdsSize.FieldByName('IDSize').AsInteger
else
Result := 0;
end;
function TDMExport.GetIDColor(MColor: String): Integer;
begin
if cdsColor.Locate('MColor', MColor, []) then
Result := cdsColor.FieldByName('IDColor').AsInteger
else
Result := 0;
end;
function TDMExport.IsEmptyDataBase: Boolean;
begin
Result := True;
try
Screen.Cursor := crHourGlass;
if StartDatabaseConnection then
with quFreeSQL do
begin
if Active then
Close;
SQL.Clear;
SQL.Add('SELECT IDStore From Store Where IDStore <> 0');
Open;
Result := IsEmpty;
Close;
end;
finally
Screen.Cursor := crDefault;
ADOConnectionClose;
end;
end;
function TDMExport.FieldExist(cds: TClientDataSet; Field, Value: String): Boolean;
var
TempCDS : TClientDataSet;
FieldPos : Integer;
begin
TempCDS := TClientDataSet.Create(Self);
try
FieldPos := cds.RecNo;
TempCDS.CloneCursor(cds, False);
TempCDS.Filtered := False;
TempCDS.Filter := Field + ' = ' + QuotedStr(Value);
TempCDS.Filtered := True;
Result := (TempCDS.RecordCount >= 1);
finally
FreeAndNil(TempCDS);
end;
end;
procedure TDMExport.SaveRegistryInfo;
var
sDecimal, sThousand, sDate : String;
buildInfo: String;
begin
case IDLanguage of
1 : begin
sDecimal := '.';
sThousand := ',';
sDate := 'mm/dd/yyyy';
end;
2 : begin
sDecimal := ',';
sThousand := '.';
sDate := 'dd/mm/yyyy';
end;
end;
// Abre o registry
with TRegistry.Create do
begin
if ( getOS(buildInfo) = osW7 ) then
RootKey := HKEY_CURRENT_USER
else
RootKey := HKEY_LOCAL_MACHINE;
OpenKey(REGISTRY_PATH, True);
if not ValueExists('DefaultCashRegID') then
WriteInteger('DefaultCashRegID', 0);
if not ValueExists('DefaultStoreID') then
WriteInteger('DefaultStoreID', 1);
if not ValueExists('DefaultLanguage') then
WriteInteger('DefaultLanguage', IDLanguage);
if not ValueExists('DefaultDecimalSeparator') then
WriteString('DefaultDecimalSeparator', sDecimal);
if not ValueExists('DefaultThousandSeparator') then
WriteString('DefaultThousandSeparator', sThousand);
if not ValueExists('DefaultDateFormat') then
WriteString('DefaultDateFormat', sDate);
Free;
end;
end;
procedure TDMExport.SaveWinStartUp(AKey, ASoftware: String);
var
buildInfo: String;
begin
with TRegistry.Create do
begin
if ( getOS(buildInfo) = osw7 ) then
RootKey := HKEY_CURRENT_USER
else
RootKey := HKEY_LOCAL_MACHINE;
OpenKey(REG_PATH, False);
if not ValueExists(AKey) then
WriteString(AKey, ASoftware);
Free;
end;
end;
procedure TDMExport.DeleteWinStartUp(AKey: String);
var
buildInfo: String;
begin
with TRegistry.Create do
begin
if ( getOS(buildInfo) = osW7 ) then
RootKey := HKEY_CURRENT_USER
else
RootKey := HKEY_LOCAL_MACHINE;
OpenKey(REG_PATH, False);
if ValueExists(AKey) then
DeleteValue(AKey);
Free;
end;
end;
function TDMExport.RegKeyExist(AKey: string): Boolean;
var
buildInfo: String;
begin
with TRegistry.Create do
begin
if ( getOS(buildInfo) = osW7 ) then
RootKey := HKEY_CURRENT_USER
else
RootKey := HKEY_LOCAL_MACHINE;
OpenKey(REG_PATH, False);
Result := ValueExists(AKey);
Free;
end;
end;
function TDMExport.InsertBreed(ABreed: String): Boolean;
begin
Result := False;
with cmdFree do
begin
CommandText := 'INSERT Pet_Breed (IDBreed, Breed) VALUES (:IDBreed, :Breed)';
Parameters.ParamByName('IDBreed').Value := GetNextID('Pet_Breed.IDBreed');
Parameters.ParamByName('Breed').Value := ABreed;
Execute;
Result := True;
end;
end;
function TDMExport.InsertColor(AColor : String):Boolean;
begin
Result := False;
with cmdFree do
begin
CommandText := 'INSERT Pet_Color (IDColor, Color) VALUES (:IDColor, :Color)';
Parameters.ParamByName('IDColor').Value := GetNextID('Pet_Color.IDColor');
Parameters.ParamByName('Color').Value := AColor;
Execute;
Result := True;
end;
end;
function TDMExport.InsertMedicalCondition(AMedical,
ASubMedical: String): Boolean;
begin
Result := False;
with cmdFree do
begin
CommandText := 'INSERT Pet_MedicalCondition (IDMedicalCondition, MedicalCondition, SubMedicalCondition) ' +
' VALUES (:IDMedicalCondition, :MedicalCondition, :SubMedicalCondition) ';
Parameters.ParamByName('IDMedicalCondition').Value := GetNextID('Pet_MedicalCondition.IDMedicalCondition');
Parameters.ParamByName('MedicalCondition').Value := AMedical;
Parameters.ParamByName('SubMedicalCondition').Value := ASubMedical;
Execute;
Result := True;
end;
end;
function TDMExport.InsertTreamtne(ATreatment, AManu: String;
AType: Integer): Boolean;
begin
Result := False;
with cmdFree do
begin
CommandText := 'INSERT Pet_Treatment (IDTreatment, Treatment, TreatmentType, Mfg) ' +
' VALUES (:IDTreatment, :Treatment, :TreatmentType, :Mfg)';
Parameters.ParamByName('IDTreatment').Value := GetNextID('Pet_Treatment.IDTreatment');
Parameters.ParamByName('Treatment').Value := ATreatment;
Parameters.ParamByName('TreatmentType').Value := AType;
Parameters.ParamByName('Mfg').Value := AManu;
Execute;
Result := True;
end;
end;
function TDMExport.ValueExist(ATable, AField1, AField2, AValue1, AValue2: String): Boolean;
begin
with quFreeSQL do
try
if Active then
Close;
SQL.Clear;
SQL.Add('SELECT ' + AField1);
SQL.Add('FROM ' + ATable);
SQL.Add('WHERE ' + AField1 + ' = :Field1');
if (AField2 <> '') then
SQL.Add('AND ' + AField2 + ' = :Field2');
Parameters.ParamByName('Field1').Value := AValue1;
if (AField2 <> '') then
Parameters.ParamByName('Field2').Value := AValue2;
Open;
Result := not IsEmpty;
finally
Close;
end;
end;
procedure TDMExport.AddLog(AText: String);
var
fFile : TSaveFile;
begin
fFile := TSaveFile.Create;
try
fFile.FilePath := DMExport.LocalPath + 'pc_log.txt';
fFile.OpenFile;
AText := FormatDateTime('mm/dd/yyyy hh:mm ', now) + AText;
fFile.InsertText(AText, 0);
fFile.CreateFile;
finally
FreeAndNil(fFile);
end;
end;
procedure TDMExport.WriteConnectionDefaultValues;
var
sResult : String;
fRegistryKey : String;
Reg : TRegistry;
buildInfo: String;
begin
fRegistryKey := 'ServerInfo';
sResult := SV_SERVER +'(local);'+
SV_DATABASE +'MainRetailDB;'+
SV_USER +'mruser;'+
SV_PASSWORD +'mruser2000;'+
SV_WIN_LOGIN+'N;'+
SV_USE_NETLIB+'N;';
Try
Reg := TRegistry.Create;
if ( getOS(buildInfo) = osW7 ) then
reg.RootKey := HKEY_CURRENT_USER
else
reg.RootKey := HKEY_LOCAL_MACHINE;
Reg.OpenKey('SOFTWARE\AppleNet', True);
if not Reg.ValueExists(fRegistryKey) then
Reg.WriteString(fRegistryKey, EncodeServerInfo(sResult, 'Server', CIPHER_TEXT_STEALING, FMT_UU));
finally
//Fechar o Registry
Reg.CloseKey;
Reg.Free;
end;
end;
function TDMExport.CheckPetWrdFile: Boolean;
begin
Result := FileExists(LocalPath + 'WzdPet.txt');
end;
function TDMExport.CreatePetWrdFile: Boolean;
begin
if not FileExists(LocalPath + 'WzdPet.txt') then
FileCreate(LocalPath + 'WzdPet.txt');
Result := True;
end;
function TDMExport.DeletePetWrdFile: Boolean;
begin
if not FileExists(LocalPath + 'WzdPet.txt') then
DeleteFile(LocalPath + 'WzdPet.txt');
Result := True;
end;
{ TTax }
function TTax.Insert: Boolean;
var
IDP, IDF : Integer;
PISFormula : String;
begin
if BrazilMode then
begin
with DMExport.quFreeSQL do
begin
SQL.Clear;
IDSaleTax := DMExport.GetNextID('TaxCategory.IDTaxCategory');
SQL.Add('INSERT INTO TaxCategory (IDTaxCategory, TaxCategory, Tax, OperationType, SaleTaxType, Debit, SituacaoTributaria)');
SQL.Add(' VALUES ('+ IntToStr(IDSaleTax) +', '+
QuotedStr(SaleTaxName) +', '+
StringReplace(FloatToStr(SaleTax),',','.',[rfReplaceAll]) +',1,2,0,1)');
DMExport.RunCommand(DMExport.quFreeSQL);
end;
end
else
begin
with DMExport.quFreeSQL do
begin
SQL.Clear;
IDSaleTax := DMExport.GetNextID('TaxCategory.IDTaxCategory');
SQL.Add('INSERT INTO TaxCategory (IDTaxCategory, TaxCategory, Tax, OperationType, SaleTaxType, Debit)');
SQL.Add(' VALUES ('+ IntToStr(IDSaleTax) +', '+
QuotedStr(SaleTaxName) +', '+
StringReplace(FloatToStr(SaleTax),',','.',[rfReplaceAll]) +',1,1,0)');
DMExport.RunCommand(DMExport.quFreeSQL);
end;
with DMExport.quFreeSQL do
begin
SQL.Clear;
IDF := DMExport.GetNextID('TaxCategory.IDTaxCategory');
SQL.Add('INSERT INTO TaxCategory (IDTaxCategory, TaxCategory, Tax, IDTaxCategoryParent)');
SQL.Add(' VALUES ('+ IntToStr(IDF) +', '+
QuotedStr(SaleTaxName) +', '+
StringReplace(FloatToStr(SaleTax),',','.',[rfReplaceAll]) + ','+IntToStr(IDSaleTax)+ ')');
DMExport.RunCommand(DMExport.quFreeSQL);
end;
end;
if BrazilMode then
begin
with DMExport.quFreeSQL do
begin
SQL.Clear;
IDEncargos := DMExport.GetNextID('TaxCategory.IDTaxCategory');
SQL.Add('INSERT INTO TaxCategory (IDTaxCategory, TaxCategory, Tax, OperationType, SaleTaxType)');
SQL.Add(' VALUES ('+ IntToStr(IDEncargos) +', '+
QuotedStr('Encargos') +', '+
StringReplace(FloatToStr(EncargosVendas),',','.',[rfReplaceAll]) +',1,1)');
DMExport.RunCommand(DMExport.quFreeSQL);
end;
with DMExport.quFreeSQL do
begin
SQL.Clear;
IDF := DMExport.GetNextID('TaxCategory.IDTaxCategory');
SQL.Add('INSERT INTO TaxCategory (IDTaxCategory, TaxCategory, Tax, IDTaxCategoryParent)');
SQL.Add(' VALUES ('+ IntToStr(IDF) +', '+
QuotedStr('Encargos') +', '+
StringReplace(FloatToStr(EncargosVendas),',','.',[rfReplaceAll]) + ','+IntToStr(IDEncargos)+ ')');
DMExport.RunCommand(DMExport.quFreeSQL);
end;
end;
if BrazilMode then
begin
with DMExport.quFreeSQL do
begin
SQL.Clear;
IDP := DMExport.GetNextID('TaxCategory.IDTaxCategory');
SQL.Add('INSERT INTO TaxCategory (IDTaxCategory, TaxCategory, Tax, OperationType, Formula, Debit, IDLancamentoTipo)');
SQL.Add(' VALUES ('+ IntToStr(IDP) +', '+
QuotedStr('ICMS') +', '+
StringReplace(FloatToStr(SaleTax),',','.',[rfReplaceAll]) +',2,'+QuotedStr('(c+f)*p')+', 1, 1 )');
DMExport.RunCommand(DMExport.quFreeSQL);
end;
if (COFINS <> 0) then
with DMExport.quFreeSQL do
begin
SQL.Clear;
IDCOFINS := DMExport.GetNextID('TaxCategory.IDTaxCategory');
SQL.Add('INSERT INTO TaxCategory (IDTaxCategory, TaxCategory, Tax, OperationType, Formula, Debit, IDLancamentoTipo)');
SQL.Add(' VALUES ('+ IntToStr(IDCOFINS) +', '+
QuotedStr('COFINS') +', '+
StringReplace(FloatToStr(COFINS),',','.',[rfReplaceAll]) +',2,'+QuotedStr('(c+f)*p')+', 1, 1 )');
DMExport.RunCommand(DMExport.quFreeSQL);
end;
PISFormula := '';
IDIPI := 0;
if (IPI <> 0) then
with DMExport.quFreeSQL do
begin
SQL.Clear;
IDIPI := DMExport.GetNextID('TaxCategory.IDTaxCategory');
SQL.Add('INSERT INTO TaxCategory (IDTaxCategory, TaxCategory, Tax, OperationType, Formula, Debit, IDLancamentoTipo)');
SQL.Add(' VALUES ('+ IntToStr(IDIPI) +', '+
QuotedStr('IPI') +', '+
StringReplace(FloatToStr(IPI),',','.',[rfReplaceAll]) +',2,'+QuotedStr('(c+f)*p')+',1, 1 )');
DMExport.RunCommand(DMExport.quFreeSQL);
end;
if (PIS <> 0) then
begin
if IDIPI = 0 then
PISFormula := '(c+f)*p'
else
PISFormula := '((c+f)+['+IntToStr(IDIPI)+'])*p';
with DMExport.quFreeSQL do
begin
SQL.Clear;
IDPIS := DMExport.GetNextID('TaxCategory.IDTaxCategory');
SQL.Add('INSERT INTO TaxCategory (IDTaxCategory, TaxCategory, Tax, OperationType, Formula, Debit, IDLancamentoTipo)');
SQL.Add(' VALUES ('+ IntToStr(IDPIS) +', '+
QuotedStr('PIS') +', '+
StringReplace(FloatToStr(PIS),',','.',[rfReplaceAll]) +',2,'+QuotedStr(PISFormula)+',0, 1 )');
DMExport.RunCommand(DMExport.quFreeSQL);
end;
end;
end;
Result := True;
end;
{ TParams }
function TParams.Insert: Boolean;
var
sSrvValue : String;
begin
//Tax included on cost price
if TaxOnCost then
sSrvValue := 'True'
else
sSrvValue := 'False';
with DMExport.quFreeSQL do
begin
SQL.Clear;
SQL.Add('UPDATE Param ');
SQL.Add('SET SrvValue = ' + QuotedStr(sSrvValue));
SQL.Add('WHERE IDParam = 66');
DMExport.RunCommand(DMExport.quFreeSQL);
end;
//Exempt sale tax
if ExemptTaxOnSale then
sSrvValue := 'True'
else
sSrvValue := 'False';
with DMExport.quFreeSQL do
begin
SQL.Clear;
SQL.Add('UPDATE Param ');
SQL.Add('SET SrvValue = ' + QuotedStr(sSrvValue));
SQL.Add('WHERE IDParam = 64');
DMExport.RunCommand(DMExport.quFreeSQL);
end;
//Usar cálculo de markup
if SimpleTax then
sSrvValue := 'True'
else
sSrvValue := 'False';
with DMExport.quFreeSQL do
begin
SQL.Clear;
SQL.Add('UPDATE Param ');
SQL.Add('SET SrvValue = ' + QuotedStr(sSrvValue));
SQL.Add('WHERE IDParam = 72');
DMExport.RunCommand(DMExport.quFreeSQL);
end;
//Show Post-Date on Sale
if PostDateSale then
sSrvValue := 'True'
else
sSrvValue := 'False';
with DMExport.quFreeSQL do
begin
SQL.Clear;
SQL.Add('UPDATE Param ');
SQL.Add('SET SrvValue = ' + QuotedStr(sSrvValue));
SQL.Add('WHERE IDParam = 48');
DMExport.RunCommand(DMExport.quFreeSQL);
end;
//Max number of payments
with DMExport.quFreeSQL do
begin
SQL.Clear;
SQL.Add('UPDATE Param ');
SQL.Add('SET SrvValue = ' + QuotedStr(IntToStr(MaxNumberForPostDate)));
SQL.Add('WHERE IDParam = 58');
DMExport.RunCommand(DMExport.quFreeSQL);
end;
//Type of Sales screen
if DeliveryFeature then
sSrvValue := '2'
else
sSrvValue := '1';
with DMExport.quFreeSQL do
begin
SQL.Clear;
SQL.Add('UPDATE Param ');
SQL.Add('SET SrvValue = ' + QuotedStr(sSrvValue));
SQL.Add('WHERE IDParam = 63');
DMExport.RunCommand(DMExport.quFreeSQL);
end;
//Treat Hold as Invoice on Sale
if DeliveryFeature then
sSrvValue := 'True'
else
sSrvValue := 'False';
with DMExport.quFreeSQL do
begin
SQL.Clear;
SQL.Add('UPDATE Param ');
SQL.Add('SET SrvValue = ' + QuotedStr(sSrvValue));
SQL.Add('WHERE IDParam = 83');
DMExport.RunCommand(DMExport.quFreeSQL);
end;
//Limit layaway edits to month created
if DeliveryFeature then
sSrvValue := 'True'
else
sSrvValue := 'False';
with DMExport.quFreeSQL do
begin
SQL.Clear;
SQL.Add('UPDATE Param ');
SQL.Add('SET SrvValue = ' + QuotedStr(sSrvValue));
SQL.Add('WHERE IDParam = 94');
DMExport.RunCommand(DMExport.quFreeSQL);
end;
Result := True;
end;
{ TStore }
function TStore.Insert: Boolean;
begin
//Insert StoreState
if Trim(IDState) <> '' then
with DMExport.quFreeSQL do
begin
SQL.Clear;
IDState := Copy(StoreState,1,3);
SQL.Add('IF NOT EXISTS(SELECT IDEstado FROM Estado WHERE IDEstado = '+
QuotedStr(Trim(IDState)) + ')');
SQL.Add(' INSERT INTO Estado (IDEstado, Estado) VALUES ('+
QuotedStr(IDState) +', '+ QuotedStr(IDState) +')');
DMExport.RunCommand(DMExport.quFreeSQL);
end;
//Insert Store
ID := DMExport.GetNextID('Store.IDStore');
with DMExport.quFreeSQL do
begin
SQL.Clear;
SQL.Add('INSERT INTO Store (IDStore, Name, Address, City, IDEstado, Zip, Telephone, '+
'Fax, Contato, TicketHeader, '+
'TicketLayawayFooter, TicketTaxIsemptFooter, Email, WebPage, IDEmpresa)');
SQL.Add(' VALUES ('+ IntToStr(ID) +', '+
DMExport.GetInsStr(StoreName) +', '+
DMExport.GetInsStr(Address) +', '+
DMExport.GetInsStr(City) +', '+
DMExport.GetInsStr(IDState) +', '+
DMExport.GetInsStr(Zip) +', '+
DMExport.GetInsStr(Tel) +', '+
DMExport.GetInsStr(Fax) +', '+
DMExport.GetInsStr(Contat) +', '+
DMExport.GetInsStr(TicketHeader) +', '+
DMExport.GetInsStr(TicketLayawayFooter) +', '+
DMExport.GetInsStr(TicketTaxIsemptFooter) +', '+
DMExport.GetInsStr(Email) +', '+
DMExport.GetInsStr(Web) +', 1004)');
DMExport.RunCommand(DMExport.quFreeSQL);
end;
//Atualiza Conta Corrente no MeioPagToStore para a loja.
with DMExport.quFreeSQL do
begin
SQL.Clear;
SQL.Add('UPDATE MeioPagToStore');
SQL.Add('SET IDContaCorrente = 101');
SQL.Add('WHERE IDStore = ' + IntToStr(ID));
DMExport.RunCommand(DMExport.quFreeSQL);
end;
Result := True;
end;
{ TPessoa }
function TPessoa.Insert: Boolean;
var
sCode : String;
begin
//Get Next Code on the table
with DMExport.quFreeSQL do
try
DMExport.RunSQL('UPDATE TipoPessoa SET LastCode = IsNull(LastCode,0) + 1 Where IDTipoPessoa = ' + IDTipoPessoa);
Close;
SQL.Clear;
SQL.Add('SELECT LastCode From TipoPessoa WHERE IDTipoPessoa = ' + IDTipoPessoa);
SQL.Add('AND Path = ' + QuotedStr(Path));
Open;
sCode := FieldByName('LastCode').AsString;
finally
Close;
end;
if FName = '' then
FName := 'NULL';
if LName = '' then
LName := 'NULL';
if Phone = '' then
Phone := 'NULL';
//Adiciona Comissionado
with DMExport.quFreeSQL do
begin
SQL.Clear;
IDPessoa := DMExport.GetNextID('Pessoa.IDPessoa');
SQL.Add('INSERT INTO Pessoa(IDPessoa, Pessoa, PessoaFirstName, PessoaLastName, Code, IDTipoPessoa, IDTipoPessoaRoot, Telefone, Juridico)');
SQL.Add(' VALUES ('+ IntToStr(IDPessoa) +', '+
QuotedStr(PessoaName) +', '+
QuotedStr(FName)+', '+
QuotedStr(LName)+', '+
sCode+', '+IDTipoPessoa+', '+IDTipoPessoa+','+Phone+','+Juridico+')');
DMExport.RunCommand(DMExport.quFreeSQL);
end;
Result := True;
end;
{ TCategory }
function TCategory.Find: Boolean;
begin
Result := False;
with DMExport.quFreeSQL do
try
SQL.Clear;
SQL.Add('SELECT IDGroup FROM TabGroup WHERE Name = :Name');
Parameters.ParamByName('Name').Value := Category;
Open;
if not IsEmpty then
begin
IDCategory := FieldByName('IDGroup').AsInteger;
Result := True;
end;
finally
Close;
end;
end;
function TCategory.Insert: Boolean;
var
IDSaleTax, IDEncargo : String;
begin
with DMExport.quFreeSQL do
begin
SQL.Clear;
IDCategory := DMExport.GetNextID('TabGroup.IDGroup');
SQL.Add('INSERT INTO TabGroup(IDGroup, Name, SizeAndColor, SalePriceMargemPercent, MSRPMargemPercent, ');
SQL.Add(' PackModel, PuppyTracker, PackModelAddItems)');
SQL.Add(' VALUES (:IDGroup, :Name, :SizeAndColor, 0, 0, :PackModel, :PuppyTracker, :PackModelAddItems)');
Parameters.ParamByName('IDGroup').Value := IDCategory;
Parameters.ParamByName('Name').Value := Category;
Parameters.ParamByName('SizeAndColor').Value := SizeAndColor;
Parameters.ParamByName('PackModel').Value := PackModel;
Parameters.ParamByName('PuppyTracker').Value := PuppyTracker;
Parameters.ParamByName('PackModelAddItems').Value := PackModelAddItems;
DMExport.RunCommand(DMExport.quFreeSQL);
end;
if DMExport.FTax.IDSaleTax <> 0 then
begin
if DMExport.FTax.BrazilMode then
begin
IDSaleTax := IntToStr(DMExport.FTax.IDEncargos);
IDEncargo := IntToStr(DMExport.FTax.IDSaleTax);
end
else
begin
IDSaleTax := IntToStr(DMExport.FTax.IDSaleTax);
IDEncargo := 'NULL';
end;
with DMExport.quFreeSQL do
begin
SQL.Clear;
SQL.Add('UPDATE StoreToTabGroup');
SQL.Add('SET IDTaxCategory = ' + IDSaleTax + ',');
SQL.Add('IDSaleTax = ' + IDEncargo);
SQL.Add('WHERE IDGroup = ' + IntToStr(IDCategory));
SQL.Add('AND IDStore = ' + IntToStr(DMExport.FStore.ID));
DMExport.RunCommand(DMExport.quFreeSQL);
end;
end;
Result := True;
end;
{ TModel }
function TModel.Find: Boolean;
begin
Result := False;
with DMExport.quFreeSQL do
try
SQL.Clear;
SQL.Add('SELECT IDModel FROM Model WHERE Model = :Model');
Parameters.ParamByName('Model').Value := Model;
Open;
if not IsEmpty then
begin
IDModel := FieldByName('IDModel').AsInteger;
Result := True;
end;
finally
Close;
end;
end;
function TModel.Insert: Boolean;
var
IDInv : Integer;
begin
if not Find then
begin
with DMExport.quFreeSQL do
begin
SQL.Clear;
IDModel := DMExport.GetNextID('Model.IDModel');
SQL.Add('INSERT INTO Model(IDModel, GroupID, Model, Description, VendorCost, SellingPrice, ModelType)');
SQL.Add('VALUES (:IDModel, :GroupID, :Model, :Description, :VendorCost, :SellingPrice, :ModelType)');
Parameters.ParamByName('IDModel').Value := IDModel;
Parameters.ParamByName('GroupID').Value := IDCategory;
Parameters.ParamByName('Model').Value := Model;
Parameters.ParamByName('Description').Value := Description;
Parameters.ParamByName('VendorCost').Value := CostPrice;
Parameters.ParamByName('SellingPrice').Value := SalePrice;
Parameters.ParamByName('ModelType').Value := ModelType;
DMExport.RunCommand(DMExport.quFreeSQL);
end;
if (Qty > 0) and (ModelType <> 'M') then
with DMExport.quFreeSQL do
begin
SQL.Clear;
IDInv := DMExport.GetNextID('InventoryMov.IDInventoryMov');
SQL.Add('INSERT INTO InventoryMov(IDInventoryMov, InventMovTypeID, DocumentID, StoreID, ModelID, MovDate, Qty)');
SQL.Add('VALUES(:IDInventoryMov, :InventMovTypeID, :DocumentID, :StoreID, :ModelID, :MovDate, :Qty)');
Parameters.ParamByName('IDInventoryMov').Value := IDInv;
Parameters.ParamByName('InventMovTypeID').Value := 5;
Parameters.ParamByName('DocumentID').Value := '0';
Parameters.ParamByName('StoreID').Value := DMExport.FStore.ID;
Parameters.ParamByName('ModelID').Value := IDModel;
Parameters.ParamByName('MovDate').Value := Now;
Parameters.ParamByName('Qty').Value := Qty;
DMExport.RunCommand(DMExport.quFreeSQL);
end;
if (Barcode <> '') and (ModelType <> 'M') then
with DMExport.quFreeSQL do
begin
SQL.Clear;
SQL.Add('INSERT INTO Barcode(IDModel, IDBarcode, BarcodeOrder, Data, Qty)');
SQL.Add('VALUES(:IDModel, :IDBarcode, :BarcodeOrder, :Data, :Qty)');
Parameters.ParamByName('IDModel').Value := IDModel;
Parameters.ParamByName('IDBarcode').Value := Barcode;
Parameters.ParamByName('BarcodeOrder').Value := 1;
Parameters.ParamByName('Data').Value := Now;
Parameters.ParamByName('Qty').Value := 1;
DMExport.RunCommand(DMExport.quFreeSQL);
end;
end;
Result := True;
end;
{ TCashRegister }
function TCashRegister.Insert: Boolean;
begin
with DMExport.quFreeSQL do
begin
IDCashRegister := DMExport.GetNextID('CashRegister.IDCashRegister');
SQL.Clear;
SQL.Add('INSERT INTO CashRegister (IDCashRegister, Name, IsAssociated)');
SQL.Add('VALUES (:IDCashRegister, :Name, :IsAssociated)');
Parameters.ParamByName('IDCashRegister').Value := IDCashRegister;
Parameters.ParamByName('Name').Value := RegisterName;
Parameters.ParamByName('IsAssociated').Value := IsAssociated;
DMExport.RunCommand(DMExport.quFreeSQL);
end;
Result := True;
end;
{ TModelChild }
function TModelChild.Insert: Boolean;
var
IDInv : Integer;
begin
with DMExport.spAddSize do
begin
Parameters.ParamByName('@IDModel').Value := IDModelParent;
Parameters.ParamByName('@IDSize').Value := IDSize;
Parameters.ParamByName('@BarcodeCreate').Value := True;
ExecProc;
end;
with DMExport.spAddColor do
begin
Parameters.ParamByName('@IDModel').Value := IDModelParent;
Parameters.ParamByName('@IDColor').Value := IDColor;
Parameters.ParamByName('@BarcodeCreate').Value := True;
ExecProc;
end;
IDModel := 0;
with DMExport.quFreeSQL do
begin
SQL.Clear;
SQL.Add('SELECT IDModel FROM Model');
SQL.Add('WHERE IDSize = :IDSize AND IDColor = :IDColor AND IDModelParent = :IDParent');
Parameters.ParamByName('IDSize').Value := IDSize;
Parameters.ParamByName('IDColor').Value := IDColor;
Parameters.ParamByName('IDParent').Value := IDModelParent;
Open;
IDModel := FieldByName('IDModel').AsInteger;
Close;
end;
if IDModel <> 0 then
begin
with DMExport.quFreeSQL do
begin
SQL.Clear;
SQL.Add('UPDATE Model');
SQL.Add('SET SellingPrice = :SellingPrice');
SQL.Add('WHERE IDModel = :IDModel');
Parameters.ParamByName('SellingPrice').Value := SalePrice;
Parameters.ParamByName('IDModel').Value := IDModel;
DMExport.RunCommand(DMExport.quFreeSQL);
end;
if (Qty <> 0) then
with DMExport.quFreeSQL do
begin
SQL.Clear;
IDInv := DMExport.GetNextID('InventoryMov.IDInventoryMov');
SQL.Add('INSERT INTO InventoryMov(IDInventoryMov, InventMovTypeID, DocumentID, StoreID, ModelID, MovDate, Qty)');
SQL.Add('VALUES(:IDInventoryMov, :InventMovTypeID, :DocumentID, :StoreID, :ModelID, :MovDate, :Qty)');
Parameters.ParamByName('IDInventoryMov').Value := IDInv;
Parameters.ParamByName('InventMovTypeID').Value := 5;
Parameters.ParamByName('DocumentID').Value := '0';
Parameters.ParamByName('StoreID').Value := DMExport.FStore.ID;
Parameters.ParamByName('ModelID').Value := IDModel;
Parameters.ParamByName('MovDate').Value := Now;
Parameters.ParamByName('Qty').Value := Qty;
DMExport.RunCommand(DMExport.quFreeSQL);
end;
end;
Result := True;
end;
{ TModelColor }
function TModelColor.Insert: Boolean;
begin
with DMExport.quFreeSQL do
begin
IDColor := DMExport.GetNextID('InvColor.IDColor');
SQL.Clear;
SQL.Add('INSERT INTO InvColor (IDColor, Color, CodColor)');
SQL.Add('VALUES (:IDColor, :Color, :CodColor)');
Parameters.ParamByName('IDColor').Value := IDColor;
Parameters.ParamByName('Color').Value := ColorName;
Parameters.ParamByName('CodColor').Value := Trim(Copy(ColorName, 1, 5));
DMExport.RunCommand(DMExport.quFreeSQL);
end;
Result := True;
end;
{ TModelSize }
function TModelSize.Insert: Boolean;
begin
with DMExport.quFreeSQL do
begin
IDSize := DMExport.GetNextID('InvSize.IDSize');
SQL.Clear;
SQL.Add('INSERT INTO InvSize (IDSize, SizeName, CodSize)');
SQL.Add('VALUES (:IDSize, :SizeName, :CodSize)');
Parameters.ParamByName('IDSize').Value := IDSize;
Parameters.ParamByName('SizeName').Value := SizeName;
Parameters.ParamByName('CodSize').Value := Trim(Copy(SizeName, 1, 5));
DMExport.RunCommand(DMExport.quFreeSQL);
end;
Result := True;
end;
{ TPessoaTipo }
function TPessoaTipo.Insert: Boolean;
var
sPath, sPathName : String;
iPath : Integer;
begin
with DMExport.quFreeSQL do
try
SQL.Clear;
SQL.Add('SELECT Path, PathName FROM TipoPessoa WHERE IDTipoPessoa = ' + IntToStr(IDTipoPessoaRoot));
Open;
sPath := FieldByName('Path').AsString;
sPathName := FieldByName('PathName').AsString;
finally
Close;
end;
with DMExport.quFreeSQL do
try
SQL.Clear;
SQL.Add('SELECT Path FROM TipoPessoa WHERE Path like ' + QuotedStr(sPath + '.%'));
Open;
iPath := 0;
While not EOF do
begin
if StrToInt(Copy(FieldByName('Path').AsString, 6, 3)) > iPath then
iPath := StrToInt(Copy(FieldByName('Path').AsString, 6, 3));
Next;
end;
Path := sPath + '.' + FormatFloat('000', iPath+1);
finally
Close;
end;
IDTipoPessoa := DMExport.GetNextID('TipoPessoa.IDTipoPessoa');
with DMExport.quFreeSQL do
begin
SQL.Clear;
SQL.Add('INSERT INTO TipoPessoa(IDTipoPessoa, Path, TipoPessoa, PathName, LastCode)');
SQL.Add(' VALUES (:IDTipoPessoa, :Path, :TipoPessoa, :PathName, :LastCode)');
Parameters.ParamByName('IDTipoPessoa').Value := IDTipoPessoa;
Parameters.ParamByName('Path').Value := Path;
Parameters.ParamByName('PathName').Value := sPathName + '\ ' + TipoPessoa;
Parameters.ParamByName('TipoPessoa').Value := TipoPessoa;
Parameters.ParamByName('LastCode').Value := 1;
DMExport.RunCommand(DMExport.quFreeSQL);
end;
Result := True;
end;
{ TMicrochip }
function TMicrochip.Find: Boolean;
begin
Result := False;
with DMExport.quFreeSQL do
try
SQL.Clear;
SQL.Add('SELECT IDMicrochip FROM Pet_Microchip WHERE Microchip = :Microchip');
Parameters.ParamByName('Microchip').Value := Microchip;
Open;
if not IsEmpty then
begin
IDMicrochip := FieldByName('IDMicrochip').AsInteger;
Result := True;
end;
finally
Close;
end;
end;
function TMicrochip.Insert: Boolean;
var
FCommand : TADOCommand;
begin
if not Find then
begin
FCommand := TADOCommand.Create(nil);
try
FCommand.Connection := DMExport.ADODBConnect;
FCommand.CommandText := 'INSERT Pet_Microchip (IDMicrochip, Microchip, Amount, IDModel) ' +
'VALUES (:IDMicrochip, :Microchip, :Amount, :IDModel) ';
FCommand.Parameters.ParamByName('IDMicrochip').Value := DMExport.GetNextID('Pet_Microchip.IDMicrochip');
FCommand.Parameters.ParamByName('Microchip').Value := Microchip;
FCommand.Parameters.ParamByName('Amount').Value := Amount;
FCommand.Parameters.ParamByName('IDModel').Value := IDModel;
FCommand.Execute();
finally
FreeAndNil(FCommand);
end;
end;
Result := True;
end;
end.
|
{ Модуль работы с пинпадом сбербанка }
{
Порядок вызова функций библиотеки
При оплате (возврате) покупки по банковской карте кассовая программа должна вызвать из библиотеки Сбербанка функцию card_authorize(), заполнив поля TType и Amount и указав нулевые значения в остальных полях.
По окончании работы функции необходимо проанализировать поле RCode. Если в нем содержится значение «0» или «00», авторизация считается успешно выполненной, в противном случае – отклоненной.
Кроме этого, необходимо проверить значение поля Check. Если оно не равно NULL, его необходимо отправить на печать (в нефискальном режиме) и затем удалить вызовом функции GlobalFree().
В случае, если внешняя программа не обеспечивает гарантированной печати карточного чека из поля Check, она может использовать следующую логику:
1) Выполнить функцию card_authorize().
2) После завершения работы функции card_authorize(), если транзакция выполнена успешно, вызвать функцию SuspendTrx() и приступить к печати чека.
3) Если чек напечатан успешно, вызвать функцию CommitTrx().
4) Если во время печати чека возникла неустранимая проблема, вызвать функцию RollbackTrx() для отмены платежа.
Если в ходе печати чека произойдет зависание ККМ или сбой питания, то транзакция останется в «подвешенном» состоянии. При следующем сеансе связи с банком она автоматически отменится.
При закрытии смены кассовая программа должна вызвать из библиотеки Сбербанка функцию close_day(), заполнив поле TType = 7 и указав нулевые значения в остальных полях.
По окончании работы функции необходимо проверить значение поля Check. Если поле Check не равно NULL, его необходимо отправить на печать (в нефискальном режиме) и после этого удалить вызовом функции GlobaFree().
}
unit Core.PinPad;
interface
uses Classes, Windows, SysUtils;
const
LibName: string = '.\pinpad\pilot_nt.dll';
type
// Структура ответа
PAuthAnswer = ^TAuthAnswer;
TAuthAnswer = packed record
TType: integer;
// IN Тип транзакции (1 - Оплата, 3 - Возврат/отмена оплаты, 7 - Сверка итогов)
Amount: UINT; // IN Сумма операции в копейках
Rcode: array [0 .. 2] of AnsiChar;
// OUT Результат авторизации (0 или 00 - успешная авторизация, другие значения - ошибка)
AMessage: array [0 .. 15] of AnsiChar;
// OUT В случае отказа в авторизации содержит краткое сообщение о причине отказа
CType: integer;
{ OUT Тип обслуженной карты. Возможные значения:
1 – VISA
2 – MasterCard
3 – Maestro
4 – American Express
5 – Diners Club
6 – VISA Electron }
Check: PAnsiChar;
// OUT При успешной авторизации содержит образ карточного чека, который вызывающая программа должна отправить на печать, а затем освободить вызовом функции GlobalFree()
// Может иметь значение nil. В этом случае никаких действий с ним вызывающая программа выполнять не должна.
end;
PAuthAnswer7 = ^TAuthAnswer7;
TAuthAnswer7 = packed record
AuthAnswer: TAuthAnswer;
// вход/выход: основные параметры операции (см.выше)
AuthCode: array [0 .. 6] of AnsiChar; // Код авторизации
// OUT При успешной авторизации (по международной карте) содержит код авторизации. При операции по карте Сберкарт поле будет заполнено символами ‘*’.
CardID: array [0 .. 24] of AnsiChar; // номер карты
// OUT При успешной авторизации (по международной карте) содержит номер карты. Для международных карт все символы, кроме первых 6 и последних 4, будут заменены символами ‘*’.
SberOwnCard: integer;
// OUT Содержит 1, если обслуженная карта выдана Сбербанком, или 0 – в противном случае
end;
PAuthAnswer9 = ^TAuthAnswer9;
TAuthAnswer9 = packed record
AuthAnswer: TAuthAnswer;
// вход/выход: основные параметры операции (см.выше)
AuthCode: array [0 .. 6] of AnsiChar; // Код авторизации
// OUT При успешной авторизации (по международной карте) содержит код авторизации. При операции по карте Сберкарт поле будет заполнено символами ‘*’.
CardID: array [0 .. 24] of AnsiChar; // номер карты
// OUT При успешной авторизации (по международной карте) содержит номер карты. Для международных карт все символы, кроме первых 6 и последних 4, будут заменены символами ‘*’.
SberOwnCard: integer;
// OUT Содержит 1, если обслуженная карта выдана Сбербанком, или 0 – в противном случае
Hash: array [0 .. 40] of AnsiChar;
// OUT хеш SHA1 от номера карты в формате ASCIIZ
end;
TOperationType = (sberPayment = 1, sberReturn = 3, sberCloseDay = 7,
sberShift = 9);
TCardAuthorize9 = function(track2: Pchar; auth_ans: PAuthAnswer9)
: integer; cdecl;
TCardAuthorize = function(track2: Pchar; auth_ans: PAuthAnswer)
: integer; cdecl;
TCardAuthorize7 = function(track2: Pchar; auth_ans: PAuthAnswer7)
: integer; cdecl;
{
Функция используется для проведения авторизации по банковской карте, а также при необходимости для возврата/отмены платежа.
Входные данные:
track2 - Может иметь значение NULL или содержать данные 2-й дорожки карты, считанные кассовой программой
TType - Тип операции: 1 – оплата, 3 –возврат/отмена оплаты.
Amount - Сумма операции в копейках.
Выходные параметры:
RCode - Результат авторизации. Значения «00» или «0» означают успешную авторизацию, любые другие – отказ в авторизации.
AMessage - В случае отказа в авторизации содержит краткое сообщение о причине отказа. Внимание: поле не имеет завершающего байта 0х00.
CType
Тип обслуженной карты. Возможные значения:
1 – VISA
2 – MasterCard
3 – Maestro
4 – American Express
5 – Diners Club
6 – VISA Electron
Сheck
При успешной авторизации содержит образ карточного чека, который вызывающая программа должна отправить на печать, а затем освободить вызовом функции GlobalFree().
Может иметь значение NULL. В этом случае никаких действий с ним вызывающая программа выполнять не должна.
AuthCode - При успешной авторизации (по международной карте) содержит код авторизации. При операции по карте Сберкарт поле будет заполнено символами ‘*’.
CardID - При успешной авторизации (по международной карте) содержит номер карты. Для международных карт все символы, кроме первых 6 и последних 4, будут заменены символами ‘*’.
SberOwnCard - Содержит 1, если обслуженная карта выдана Сбербанком, или 0 – в противном случае.
}
TTestPinPad = function(): integer; cdecl;
{
Функция проверяет наличие пинпада. При успешном выполнении возвращает 0 (пинпад подключен), при неудачном – код ошибки (пинпад не подключен или неисправен).
}
TCloseDay = function(auth_ans: PAuthAnswer): integer; cdecl;
{
Функция используется для ежедневного закрытия смены по картам и формирования отчетов.
Входные параметры:
TType - Тип операции: 7 – закрытие дня по картам.
Amount - Не используется.
Выходные параметры:
Rcode - Не используется.
AMessage - Не используется.
CType - Не используется.
Check - Содержит образ отчета по картам, который вызывающая программа должна отправить на печать, а затем освободить вызовом функции GlobalFree().
Может иметь значение NULL. В этом случае никаких действий с ним вызывающая программа выполнять не должна.
}
TReadTrack2 = function(track2: Pchar): integer; cdecl;
{
Функция проверяет наличие пинпада. При успешном выполнении возвращает 0 (пинпад подключен), при неудачном – код ошибки (пинпад не подключен или неисправен).
Track2 - Буфер, куда функция записывает прочитанную 2-ю дорожку.
}
// SuspendTrx
TSuspendTrx = function(dwAmount: DWORD; pAuthCode: PAnsiString)
: integer; cdecl;
{
Функция переводит последнюю успешную транзакцию в «подвешенное» состояние. Если транзакция находится в этом состоянии, то при следующем сеансе связи с банком она будет отменена.
Входные параметры:
dwAmount - Сумма операции (в копейках).
pAuthCode - Код авторизации.
Функция сверяет переданные извне параметры (сумму и код авторизации) со значениями в последней успешной операции, которая была проведена через библиотеку. Если хотя бы один параметр не совпадает, функция возвращает код ошибки 4140 и не выполняет никаких действий.
}
// CommitTrx
TCommitTrx = function(dwAmount: DWORD; pAuthCode: PAnsiString)
: integer; cdecl;
{
Функция возвращает последнюю успешную транзакцию в «нормальное» состояние. После этого транзакция будет включена в отчет и спроцессирована как успешная. Перевести ее снова в «подвешенное» состояние будет уже нельзя.
Входные параметры:
dwAmount - Сумма операции (в копейках).
pAuthCode - Код авторизации.
Функция сверяет переданные извне параметры (сумму и код авторизации) со значениями в последней успешной операции, которая была проведена через библиотеку. Если хотя бы один параметр не совпадает, функция возвращает код ошибки 4140 и не выполняет никаких действий.
}
// RollBackTrx
TRollBackTrx = function(dwAmount: DWORD; pAuthCode: PAnsiString)
: integer; cdecl;
{
Функция вызывает немедленную отмену последней успешной операции (возможно, ранее переведенную в «подвешенное» состояние, хотя это и не обязательно). Если транзакция уже была возвращена в «нормальное» состояние функцией CommitTrx(), то функция RollbackTrx() завершится с кодом ошибки 4141, не выполняя никаких действий.
Входные параметры:
dwAmount - Сумма операции (в копейках).
pAuthCode - Код авторизации.
Функция сверяет переданные извне параметры (сумму и код авторизации) со значениями в последней успешной операции, которая была проведена через библиотеку. Если хотя бы один параметр не совпадает, функция возвращает код ошибки 4140 и не выполняет никаких действий.
}
TServiceMenu = function(): integer; cdecl;
TPinPad = class
strict private
FAuthAnswer: TAuthAnswer;
FAuthAnswer7: TAuthAnswer7;
FAuthAnswer9: TAuthAnswer9;
FCheque: string;
FRCode: string;
FMessage: string;
FAuthCode: string;
FTrack2: string;
public
constructor create;
destructor destroy;
function CardAuth(Summ: Double; Operation: TOperationType): integer;
function CardAuth7(Summ: Double; Operation: TOperationType): integer;
function CardAuth9(Summ: Double; Operation: TOperationType): integer;
function TestPinPad: boolean;
function ReadTrack2: string;
function CloseDay: integer;
function SuspendTrx: integer;
function CommitTrx: integer;
function RollBackTrx: integer;
function ServiceMenu: integer;
property AuthAnswer: TAuthAnswer read FAuthAnswer;
property AuthAnswer7: TAuthAnswer7 read FAuthAnswer7;
property AuthAnswer9: TAuthAnswer9 read FAuthAnswer9;
property Cheque: string read FCheque;
property Rcode: string read FRCode;
property Msg: string read FMessage;
property track2: string read FTrack2;
property AuthCode: string read FAuthCode;
end;
implementation
{ TPinPad }
function TPinPad.CardAuth(Summ: Double; Operation: TOperationType): integer;
var
H: THandle;
Func: TCardAuthorize;
Sum: UINT;
begin
Sum := Round(Summ * 100);
FAuthAnswer.Amount := Sum;
FAuthAnswer.TType := integer(Operation);
FAuthAnswer.CType := 0;
H := LoadLibrary(Pchar(LibName));
try
@Func := GetProcAddress(H, Pchar('_card_authorize'));
Result := Func(nil, @FAuthAnswer);
FCheque := PAnsiChar(FAuthAnswer.Check);
FRCode := AnsiString(FAuthAnswer.Rcode);
FMessage := AnsiString(FAuthAnswer.AMessage);
finally
Func := nil;
FreeLibrary(H);
end;
end;
function TPinPad.CardAuth7(Summ: Double; Operation: TOperationType): integer;
var
H: THandle;
Func: TCardAuthorize7;
Sum: UINT;
begin
Sum := Round(Summ * 100);
FAuthAnswer.Amount := Sum;
FAuthAnswer.TType := integer(Operation);
FAuthAnswer.CType := 0;
FAuthAnswer7.AuthAnswer := FAuthAnswer;
H := LoadLibrary(Pchar(LibName));
try
@Func := GetProcAddress(H, Pchar('_card_authorize7'));
Result := Func(nil, @FAuthAnswer7);
FCheque := PAnsiChar(FAuthAnswer7.AuthAnswer.Check);
FRCode := AnsiString(FAuthAnswer7.AuthAnswer.Rcode);
FMessage := AnsiString(FAuthAnswer7.AuthAnswer.AMessage);
FAuthCode := AnsiString(FAuthAnswer7.AuthCode);
finally
Func := nil;
FreeLibrary(H);
end;
end;
function TPinPad.CardAuth9(Summ: Double; Operation: TOperationType): integer;
var
H: THandle;
Func: TCardAuthorize9;
Sum: UINT;
begin
Sum := Round(Summ * 100);
FAuthAnswer.Amount := Sum;
FAuthAnswer.TType := integer(Operation);
FAuthAnswer.CType := 0;
FAuthAnswer9.AuthAnswer := FAuthAnswer;
H := LoadLibrary(Pchar(LibName));
try
@Func := GetProcAddress(H, Pchar('_card_authorize9'));
Result := Func(nil, @FAuthAnswer9);
FCheque := PAnsiChar(FAuthAnswer9.AuthAnswer.Check);
FRCode := AnsiString(FAuthAnswer9.AuthAnswer.Rcode);
FMessage := AnsiString(FAuthAnswer9.AuthAnswer.AMessage);
FAuthCode := AnsiString(FAuthAnswer9.AuthCode);
finally
Func := nil;
FreeLibrary(H);
end;
end;
function TPinPad.CloseDay: integer;
var
Func: TCloseDay;
H: THandle;
begin
FAuthAnswer.TType := integer(sberCloseDay);
FAuthAnswer.Amount := 0;
FAuthAnswer.CType := 0;
FAuthAnswer.Check := PAnsiChar('');
H := LoadLibrary(Pchar(LibName));
if H <= 0 then
begin
raise Exception.create(Format('Не могу загрузить %s', [LibName]));
Exit;
end;
@Func := GetProcAddress(H, Pchar('_close_day'));
if not assigned(Func) then
raise Exception.create('Could not find _close_day function');
try
Result := Func(@FAuthAnswer);
FCheque := PAnsiChar(FAuthAnswer.Check);
FMessage := AnsiString(FAuthAnswer.AMessage);
FRCode := AnsiString(FAuthAnswer.Rcode);
except
on E: Exception do
raise Exception.create(E.Message);
end;
FreeLibrary(H);
end;
function TPinPad.CommitTrx: integer;
var
H: THandle;
Func: TCommitTrx;
begin
H := LoadLibrary(Pchar(LibName));
if H <= 0 then
begin
raise Exception.create(Format('Не могу загрузить %s', [LibName]));
Exit;
end;
try
@Func := GetProcAddress(H, Pchar('_CommitTrx'));
try
Result := Func(FAuthAnswer.Amount, PAnsiString(AnsiString(FAuthCode)));
except
on E: Exception do;
end;
finally
FreeLibrary(H);
end;
end;
constructor TPinPad.create;
begin
inherited create;
FAuthAnswer.Amount := 0;
FAuthAnswer.TType := 0;
FAuthAnswer.CType := 0;
end;
destructor TPinPad.destroy;
begin
inherited destroy;
end;
function TPinPad.ReadTrack2: string;
var
H: THandle;
Func: TReadTrack2;
Res: Pchar;
begin
GetMem(Res, 255);
H := LoadLibrary(Pchar(LibName));
if H <= 0 then
begin
raise Exception.create(Format('Не могу загрузить %s', [LibName]));
Exit;
end;
try
@Func := GetProcAddress(H, Pchar('_ReadTrack2'));
try
Func(Res);
Result := PAnsiChar(Res);
except
on E: Exception do;
end;
finally
FreeMem(Res, sizeof(Res^));
FreeLibrary(H);
end;
end;
function TPinPad.RollBackTrx: integer;
var
H: THandle;
Func: TRollBackTrx;
begin
H := LoadLibrary(Pchar(LibName));
if H <= 0 then
begin
raise Exception.create(Format('Не могу загрузить %s', [LibName]));
Exit;
end;
try
@Func := GetProcAddress(H, Pchar('_RollbackTrx'));
try
Result := Func(FAuthAnswer.Amount, PAnsiString(AnsiString(FAuthCode)));
except
on E: Exception do;
end;
finally
FreeLibrary(H);
end;
end;
function TPinPad.ServiceMenu: integer;
var
H: Thandle;
Func: TServiceMenu;
begin
H := LoadLibrary(PChar(LibName));
if H <= 0 then
begin
raise Exception.Create(Format('Не могу загрузить %s', [LibName]));
Exit;
end;
try
@Func := GetProcAddress(H, PChar('_ServiceMenu'));
Result := Func();
finally
Func := nil;
FreeLibrary(H);
end;
end;
function TPinPad.SuspendTrx: integer;
var
H: THandle;
Func: TSuspendTrx;
begin
H := LoadLibrary(Pchar(LibName));
if H <= 0 then
begin
raise Exception.create(Format('Не могу загрузить %s', [LibName]));
Exit;
end;
try
@Func := GetProcAddress(H, Pchar('_SuspendTrx'));
try
Result := Func(FAuthAnswer.Amount, PAnsiString(AnsiString(FAuthCode)));
except
on E: Exception do;
end;
finally
FreeLibrary(H);
end;
end;
function TPinPad.TestPinPad: boolean;
var
H: THandle;
Func: TTestPinPad;
begin
Result := false;
try
H := LoadLibrary(Pchar(LibName));
if H <= 0 then
begin
raise Exception.create(Format('Не могу загрузить %s', [LibName]));
Exit;
end;
@Func := GetProcAddress(H, Pchar('_TestPinpad'));
try
Result := Func = 0;
except
on E: Exception do;
end;
finally
Func := nil;
FreeLibrary(H);
end;
end;
end.
|
unit ThContent;
interface
uses
Messages, SysUtils, Classes, Controls,
ThComponent, ThRegExpr, ThMessages;
type
TThCustomPage = class;
//
TThPageContent = class(TThComponent)
private
FPage: TThCustomPage;
FEnabled: Boolean;
protected
procedure SetEnabled(const Value: Boolean); virtual;
procedure SetPage(const Value: TThCustomPage); virtual;
protected
procedure UnassignComponent(AComponent: TComponent); override;
protected
property Enabled: Boolean read FEnabled write SetEnabled default true;
public
constructor Create(AOwner: TComponent); override;
published
property Page: TThCustomPage read FPage write SetPage;
end;
//
TThAbstractContent = class(TThPageContent)
public
function HasNamedContent(const inName: string;
out outContent: string): Boolean; virtual; abstract;
procedure ContentFromParams(const inParams: TStrings); virtual; abstract;
end;
//
TThContentBase = class(TThAbstractContent)
private
FInContentText: Boolean;
FOnBeforeGetContentText: TNotifyEvent;
FTemplate: Boolean;
FViewer: TControl;
protected
FContentName: string;
FContentText: string;
protected
function GetContentName: string; virtual;
function GetBaseContentText: string;
function GetContentText: string; virtual;
procedure SetContentName(const Value: string); virtual;
procedure SetContentText(const Value: string); virtual;
procedure SetTemplate(const Value: Boolean);
procedure SetViewer(const Value: TControl);
protected
procedure Changed; virtual;
procedure DoBeforeGetContentText;
function DoMacroReplace(ARegExpr: TRegExpr): string;
function GetStoredContent: string;
function MacroReplace(const inText: string): string;
procedure UnassignComponent(AComponent: TComponent); override;
protected
property OnBeforeGetContentText: TNotifyEvent read FOnBeforeGetContentText
write FOnBeforeGetContentText;
property Template: Boolean read FTemplate write SetTemplate default false;
public
destructor Destroy; override;
function HasNamedContent(const inName: string;
out outContent: string): Boolean; override;
procedure ContentFromParams(const inParams: TStrings); override;
public
property ContentName: string read GetContentName write SetContentName;
property ContentText: string read GetBaseContentText write SetContentText;
property Viewer: TControl read FViewer write SetViewer;
end;
//
TThContent = class(TThContentBase)
published
property ContentName;
property ContentText;
property Enabled;
property Template;
end;
//
TThAbstractStringsContent = class(TThContentBase)
protected
function GetStrings: TStrings; virtual; abstract;
procedure SetStrings(const Value: TStrings); virtual; abstract;
property Strings: TStrings read GetStrings write SetStrings;
end;
//
TThStringsContentBase = class(TThAbstractStringsContent)
private
FStrings: TStringList;
FFileName: string;
protected
function GetContentText: string; override;
function GetStrings: TStrings; override;
procedure SetFileName(const Value: string); virtual;
procedure SetStrings(const Value: TStrings); override;
protected
property FileName: string read FFileName write SetFileName;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property ContentName;
property Enabled;
property Template default true;
end;
//
TThContentStrings = class(TThStringsContentBase)
published
property Strings;
end;
//
TThFileContent = class(TThStringsContentBase)
published
property FileName;
end;
//
TThSourcedContent = class(TThStringsContentBase)
private
FSource: TThContentBase;
protected
function GetContentText: string; override;
procedure SetSource(const Value: TThContentBase); virtual;
protected
procedure UnassignComponent(AComponent: TComponent); override;
protected
property Enabled;
property Source: TThContentBase read FSource write SetSource;
published
property FileName;
//property Strings;
//property Template;
end;
//
TThCustomPage = class(TThSourcedContent)
public
property PageName: string read GetContentName write SetContentName;
end;
type
TThDoForFunc =
function(inComponent: TComponent; inData: Pointer = nil): Boolean;
procedure ThDoForComponents(inOwner: TComponent; inFunc: TThDoForFunc;
inData: Pointer = nil);
function ThFindContent(inOwner: TComponent; const inName: string;
out outContent: string): Boolean;
procedure ThUpdateContent(inOwner: TComponent; inParams: TStrings);
function ThFindPage(inOwner: TComponent; const inName: string;
out outPage: TThCustomPage): Boolean;
implementation
uses
StrUtils, ThComponentIterator{, ThStreamContent, ThTemplateContent,
ThWebDataDictionary};
const
cThMacroExpression = '\{%([^}]*)\}';
procedure ThDoForComponents(inOwner: TComponent; inFunc: TThDoForFunc;
inData: Pointer = nil);
var
i: Integer;
begin
if inOwner <> nil then
for i := 0 to Pred(inOwner.ComponentCount) do
if not inFunc(inOwner.Components[i], inData) then
break;
end;
function ThFindContent(inOwner: TComponent; const inName: string;
out outContent: string): Boolean;
var
i: Integer;
begin
Result := true;
//if (inOwner <> nil) {and (inName <> '')} then
if (inOwner <> nil) and (inName <> '') then
with inOwner do
for i := 0 to Pred(ComponentCount) do
if Components[i] is TThAbstractContent then
with TThAbstractContent(Components[i]) do
if HasNamedContent(inName, outContent) then
exit;
Result := false;
end;
procedure ThUpdateContent(inOwner: TComponent; inParams: TStrings);
var
i: Integer;
begin
if (inParams.Count > 0) and (inOwner <> nil) then
with inOwner do
for i := 0 to Pred(ComponentCount) do
if Components[i] is TThAbstractContent then
TThAbstractContent(Components[i]).ContentFromParams(inParams);
end;
function ThFindPage(inOwner: TComponent; const inName: string;
out outPage: TThCustomPage): Boolean;
var
i: Integer;
begin
Result := true;
if (inOwner <> nil) and (inName <> '') then
with inOwner do
for i := 0 to Pred(ComponentCount) do
if Components[i] is TThCustomPage then
if TThCustomPage(Components[i]).PageName = inName then
begin
outPage := TThCustomPage(Components[i]);
exit;
end;
Result := false;
end;
{ TThPageContent }
constructor TThPageContent.Create(AOwner: TComponent);
begin
inherited;
FEnabled := true;
end;
procedure TThPageContent.SetEnabled(const Value: Boolean);
begin
FEnabled := Value;
end;
procedure TThPageContent.SetPage(const Value: TThCustomPage);
begin
ChangeComponentProp(TComponent(FPage), Value);
end;
procedure TThPageContent.UnassignComponent(AComponent: TComponent);
begin
if AComponent = FPage then
FPage := nil;
end;
{ TThContentBase }
destructor TThContentBase.Destroy;
begin
if FViewer <> nil then
FViewer.Free;
inherited;
end;
function TThContentBase.HasNamedContent(const inName: string;
out outContent: string): Boolean;
begin
Result := (inName = ContentName) or ((inName = '') and (ContentName = '*'));
if Result then
outContent := ContentText
end;
function TThContentBase.DoMacroReplace(ARegExpr: TRegExpr): string;
begin
ThFindContent(Owner, ARegExpr.Match[1], Result);
end;
function TThContentBase.MacroReplace(const inText: string): string;
begin
with TRegExpr.Create do
try
Expression := cThMacroExpression;
Result := ReplaceEx(inText, DoMacroReplace);
finally
Free;
end;
end;
procedure TThContentBase.DoBeforeGetContentText;
begin
if Assigned(FOnBeforeGetContentText) then
FOnBeforeGetContentText(Self);
end;
function TThContentBase.GetStoredContent: string;
begin
if Template then
Result := MacroReplace(FContentText)
else
Result := FContentText;
end;
function TThContentBase.GetBaseContentText: string;
begin
if FInContentText then
raise Exception.Create('Circular reference to content "' + Name + '"');
FInContentText := true;
try
DoBeforeGetContentText;
if not Enabled then
Result := ''
else
Result := GetContentText;
if Template then
Result := MacroReplace(Result);
except
on E: Exception do
Result := E.Message;
end;
FInContentText := false;
end;
function TThContentBase.GetContentName: string;
begin
Result := FContentName;
end;
function TThContentBase.GetContentText: string;
begin
Result := FContentText;
end;
procedure TThContentBase.ContentFromParams(const inParams: TStrings);
begin
if (ContentName <> '') and (inParams.IndexOfName(ContentName) > 0) then
ContentText := inParams.Values[ContentName];
end;
procedure TThContentBase.SetContentName(const Value: string);
begin
FContentName := Value;
end;
procedure TThContentBase.SetContentText(const Value: string);
begin
FContentText := Value;
end;
procedure TThContentBase.SetTemplate(const Value: Boolean);
begin
FTemplate := Value;
end;
procedure TThContentBase.SetViewer(const Value: TControl);
begin
ChangeComponentProp(TComponent(FViewer), Value);
end;
procedure TThContentBase.UnassignComponent(AComponent: TComponent);
begin
inherited;
if AComponent = FViewer then
FViewer := nil;
end;
procedure TThContentBase.Changed;
begin
if FViewer <> nil then
FViewer.Perform(THM_CHANGE, 0, 0);
end;
{ TThStringsContentBase }
constructor TThStringsContentBase.Create(AOwner: TComponent);
begin
inherited;
FStrings := TStringList.Create;
FTemplate := true;
end;
destructor TThStringsContentBase.Destroy;
begin
FStrings.Free;
inherited;
end;
function TThStringsContentBase.GetStrings: TStrings;
begin
Result := FStrings;
end;
procedure TThStringsContentBase.SetStrings(const Value: TStrings);
begin
FStrings.Assign(Value);
end;
function TThStringsContentBase.GetContentText: string;
begin
Result := FStrings.Text;
end;
procedure TThStringsContentBase.SetFileName(const Value: string);
begin
FFileName := Value;
if FileExists(FFileName) then
FStrings.LoadFromFile(FFileName)
else
FStrings.Clear;
end;
{ TThSourcedContent }
function TThSourcedContent.GetContentText: string;
begin
if Source = nil then
Result := inherited GetContentText
else
Result := FSource.ContentText;
end;
procedure TThSourcedContent.SetSource(const Value: TThContentBase);
begin
ChangeComponentProp(TComponent(FSource), Value);
end;
procedure TThSourcedContent.UnassignComponent(AComponent: TComponent);
begin
inherited;
if AComponent = FSource then
FSource := nil;
end;
end.
|
unit UDMiscellaneous;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, UCrpe32;
type
TCrpeMiscellaneousDlg = class(TForm)
btnOk: TButton;
btnCancel: TButton;
pnlMiscellaneous: TPanel;
lblDetailCopies: TLabel;
editDetailCopies: TEdit;
editReportTitle: TEdit;
lblReportTitle: TLabel;
Line1: TBevel;
cbReportStyle: TComboBox;
Label2: TLabel;
lblTempPath: TLabel;
editTempPath: TEdit;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure editReportTitleChange(Sender: TObject);
procedure editDetailCopiesEnter(Sender: TObject);
procedure editDetailCopiesExit(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure FormDeactivate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure UpdateMiscellaneous;
procedure InitializeControls(OnOff: boolean);
procedure cbReportStyleChange(Sender: TObject);
procedure editTempPathChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
rReportTitle : string;
rReportStyle : TCrReportStyle;
rDetailCopies : Smallint;
rCrpePath : string;
rTempPath : string;
PrevNum : string;
end;
var
CrpeMiscellaneousDlg: TCrpeMiscellaneousDlg;
bMiscellaneous : boolean;
implementation
{$R *.DFM}
uses UCrpeUtl;
{------------------------------------------------------------------------------}
{ FormCreate }
{------------------------------------------------------------------------------}
procedure TCrpeMiscellaneousDlg.FormCreate(Sender: TObject);
begin
bMiscellaneous := True;
LoadFormPos(Self);
end;
{------------------------------------------------------------------------------}
{ FormShow }
{------------------------------------------------------------------------------}
procedure TCrpeMiscellaneousDlg.FormShow(Sender: TObject);
begin
{Store current VCL settings}
rReportStyle := Cr.ReportStyle;
rReportTitle := Cr.ReportTitle;
rDetailCopies := Cr.DetailCopies;
rTempPath := Cr.TempPath;
editDetailCopies.Text := '1';
editReportTitle.Text := '';
UpdateMiscellaneous;
end;
{------------------------------------------------------------------------------}
{ UpdateMiscellaneous }
{------------------------------------------------------------------------------}
procedure TCrpeMiscellaneousDlg.UpdateMiscellaneous;
var
OnOff : Boolean;
begin
OnOff := not IsStrEmpty(Cr.ReportName);
InitializeControls(OnOff);
if OnOff then
begin
cbReportStyle.ItemIndex := Ord(Cr.ReportStyle);
editReportTitle.Text := Cr.ReportTitle;
editDetailCopies.Text := IntToStr(Cr.DetailCopies);
end;
editTempPath.Text := Cr.TempPath;
end;
{------------------------------------------------------------------------------}
{ InitializeControls }
{------------------------------------------------------------------------------}
procedure TCrpeMiscellaneousDlg.InitializeControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
if TComponent(Components[i]).Tag = 0 then
begin
if Components[i] is TButton then
TButton(Components[i]).Enabled := OnOff;
if Components[i] is TComboBox then
begin
TComboBox(Components[i]).Color := ColorState(OnOff);
TComboBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TEdit then
begin
if TEdit(Components[i]).ReadOnly = False then
TEdit(Components[i]).Color := ColorState(OnOff);
TEdit(Components[i]).Enabled := OnOff;
end;
end;
end;
end;
{------------------------------------------------------------------------------}
{ cbReportStyleChange }
{------------------------------------------------------------------------------}
procedure TCrpeMiscellaneousDlg.cbReportStyleChange(Sender: TObject);
begin
Cr.ReportStyle := TCrReportStyle(cbReportStyle.ItemIndex);
end;
{------------------------------------------------------------------------------}
{ editReportTitleChange }
{------------------------------------------------------------------------------}
procedure TCrpeMiscellaneousDlg.editReportTitleChange(Sender: TObject);
begin
Cr.ReportTitle := editReportTitle.Text;
end;
{------------------------------------------------------------------------------}
{ editDetailCopiesEnter }
{------------------------------------------------------------------------------}
procedure TCrpeMiscellaneousDlg.editDetailCopiesEnter(Sender: TObject);
begin
PrevNum := editDetailCopies.Text;
end;
{------------------------------------------------------------------------------}
{ editDetailCopiesExit }
{------------------------------------------------------------------------------}
procedure TCrpeMiscellaneousDlg.editDetailCopiesExit(Sender: TObject);
begin
if not IsNumeric(editDetailCopies.Text) then
editDetailCopies.Text := PrevNum;
Cr.DetailCopies := StrToInt(editDetailCopies.Text);
end;
{------------------------------------------------------------------------------}
{ editTempPathChange }
{------------------------------------------------------------------------------}
procedure TCrpeMiscellaneousDlg.editTempPathChange(Sender: TObject);
begin
Cr.TempPath := editTempPath.Text;
end;
{------------------------------------------------------------------------------}
{ FormDeactivate }
{------------------------------------------------------------------------------}
procedure TCrpeMiscellaneousDlg.FormDeactivate(Sender: TObject);
begin
if not IsStrEmpty(Cr.ReportName) then
editDetailCopiesExit(Self);
end;
{------------------------------------------------------------------------------}
{ btnOkClick }
{------------------------------------------------------------------------------}
procedure TCrpeMiscellaneousDlg.btnOkClick(Sender: TObject);
begin
SaveFormPos(Self);
Close;
end;
{------------------------------------------------------------------------------}
{ btnCancelClick }
{------------------------------------------------------------------------------}
procedure TCrpeMiscellaneousDlg.btnCancelClick(Sender: TObject);
begin
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose }
{------------------------------------------------------------------------------}
procedure TCrpeMiscellaneousDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if not IsStrEmpty(Cr.ReportName) then
editDetailCopiesExit(Self);
if ModalResult = mrCancel then
begin
Cr.ReportStyle := rReportStyle;
Cr.ReportTitle := rReportTitle;
Cr.DetailCopies := rDetailCopies;
Cr.TempPath := rTempPath;
end;
bMiscellaneous := False;
Release;
end;
end.
|
unit LA.Globals;
interface
uses
Classes,
SysUtils;
const
EPSILON = 1E-8;
function Is_zero(x: double): boolean;
function Is_equal(a, b: double): boolean;
implementation
function Is_zero(x: double): boolean;
begin
Result := Abs(x) < EPSILON;
end;
function Is_equal(a, b: double): boolean;
begin
Result := Abs(a - b) < EPSILON;
end;
end.
|
unit InflatablesList_Manager_IO_00000008;
{$INCLUDE '.\InflatablesList_defs.inc'}
interface
uses
Classes,
AuxTypes,
InflatablesList_Manager_IO_Threaded;
type
TILManager_IO_00000008 = class(TILManager_IO_Threaded)
protected
procedure InitSaveFunctions(Struct: UInt32); override;
procedure InitLoadFunctions(Struct: UInt32); override;
procedure SaveList_00000008(Stream: TStream); virtual;
procedure LoadList_00000008(Stream: TStream); virtual;
procedure SaveSortingSettings_00000008(Stream: TStream); virtual;
procedure LoadSortingSettings_00000008(Stream: TStream); virtual;
procedure SaveShopTemplates_00000008(Stream: TStream); virtual;
procedure LoadShopTemplates_00000008(Stream: TStream); virtual;
procedure SaveFilterSettings_00000008(Stream: TStream); virtual;
procedure LoadFilterSettings_00000008(Stream: TStream); virtual;
procedure SaveItems_00000008(Stream: TStream); virtual;
procedure LoadItems_00000008(Stream: TStream); virtual;
end;
implementation
uses
SysUtils,
BinaryStreaming,
InflatablesList_Types,
InflatablesList_Utils,
InflatablesList_Item,
InflatablesList_ItemShopTemplate,
InflatablesList_Manager_IO;
procedure TILManager_IO_00000008.InitSaveFunctions(Struct: UInt32);
begin
If Struct = IL_LISTFILE_STREAMSTRUCTURE_00000008 then
begin
fFNSaveToStream := SaveList_00000008;
fFNSaveSortingSettings := SaveSortingSettings_00000008;
fFNSaveShopTemplates := SaveShopTemplates_00000008;
fFNSaveFilterSettings := SaveFilterSettings_00000008;
fFNSaveItems := SaveItems_00000008;
end
else raise Exception.CreateFmt('TILManager_IO_00000008.InitSaveFunctions: Invalid stream structure (%.8x).',[Struct]);
end;
//------------------------------------------------------------------------------
procedure TILManager_IO_00000008.InitLoadFunctions(Struct: UInt32);
begin
If Struct = IL_LISTFILE_STREAMSTRUCTURE_00000008 then
begin
fFNLoadFromStream := LoadList_00000008;
fFNLoadSortingSettings := LoadSortingSettings_00000008;
fFNLoadShopTemplates := LoadShopTemplates_00000008;
fFNLoadFilterSettings := LoadFilterSettings_00000008;
fFNLoadItems := LoadItems_00000008;
end
else raise Exception.CreateFmt('TILManager_IO_00000008.InitLoadFunctions: Invalid stream structure (%.8x).',[Struct]);
end;
//------------------------------------------------------------------------------
procedure TILManager_IO_00000008.SaveList_00000008(Stream: TStream);
begin
Stream_WriteString(Stream,IL_FormatDateTime('yyyy-mm-dd-hh-nn-ss-zzz',Now));
fFNSaveSortingSettings(Stream);
fFNSaveShopTemplates(Stream);
fFNSaveFilterSettings(Stream);
fFNSaveItems(Stream);
end;
//------------------------------------------------------------------------------
procedure TILManager_IO_00000008.LoadList_00000008(Stream: TStream);
begin
Stream_ReadString(Stream); // discard time
fFNLoadSortingSettings(Stream);
fFNLoadShopTemplates(Stream);
fFNLoadFilterSettings(Stream);
fFNLoadItems(Stream);
end;
//------------------------------------------------------------------------------
procedure TILManager_IO_00000008.SaveSortingSettings_00000008(Stream: TStream);
var
i: Integer;
procedure SaveSortingSettings(const Settings: TILSortingSettings);
var
ii: Integer;
begin
Stream_WriteUInt32(Stream,Settings.Count);
For ii := Low(Settings.Items) to High(Settings.Items) do
begin
Stream_WriteInt32(Stream,IL_ItemValueTagToNum(Settings.Items[ii].ItemValueTag));
Stream_WriteBool(Stream,Settings.Items[ii].Reversed);
end;
end;
begin
Stream_WriteString(Stream,'SORT');
// save reversed flag
Stream_WriteBool(Stream,fReversedSort);
// save actual sort settings
SaveSortingSettings(fActualSortSett);
// save sorting profiles
Stream_WriteUInt32(Stream,SortingProfileCount);
For i := 0 to Pred(SortingProfileCount) do
begin
Stream_WriteString(Stream,fSortingProfiles[i].Name);
SaveSortingSettings(fSortingProfiles[i].Settings);
end;
end;
//------------------------------------------------------------------------------
procedure TILManager_IO_00000008.LoadSortingSettings_00000008(Stream: TStream);
var
i: Integer;
procedure LoadSortingSettings(out Settings: TILSortingSettings);
var
ii: Integer;
begin
Settings.Count := Stream_ReadUInt32(Stream);
For ii := Low(Settings.Items) to High(Settings.Items) do
begin
Settings.Items[ii].ItemValueTag := IL_NumToItemValueTag(Stream_ReadInt32(Stream));
Settings.Items[ii].Reversed := Stream_ReadBool(Stream);
end;
end;
begin
If IL_SameStr(Stream_ReadString(Stream),'SORT') then
begin
// load resed flag
fReversedSort := Stream_ReadBool(Stream);
// load actual sort settings
LoadSortingSettings(fActualSortSett);
// now load profiles
SortingProfileClear;
SetLength(fSortingProfiles,Stream_ReadUInt32(Stream));
For i := Low(fSortingProfiles) to High(fSortingProfiles) do
begin
fSortingProfiles[i].Name := Stream_ReadString(Stream);
LoadSortingSettings(fSortingProfiles[i].Settings);
end;
end
else raise Exception.Create('TILManager_IO_00000008.LoadSortingSettings_00000008: Invalid stream.');
end;
//------------------------------------------------------------------------------
procedure TILManager_IO_00000008.SaveShopTemplates_00000008(Stream: TStream);
var
i: Integer;
begin
Stream_WriteString(Stream,'TEMPLATES');
Stream_WriteUInt32(Stream,ShopTemplateCount);
For i := 0 to Pred(ShopTemplateCount) do
fShopTemplates[i].SaveToStream(Stream);
end;
//------------------------------------------------------------------------------
procedure TILManager_IO_00000008.LoadShopTemplates_00000008(Stream: TStream);
var
i: Integer;
begin
If IL_SameStr(Stream_ReadString(Stream),'TEMPLATES') then
begin
ShopTemplateClear;
SetLength(fShopTemplates,Stream_ReadUInt32(Stream));
For i := 0 to Pred(ShopTemplateCount) do
begin
fShopTemplates[i] := TILItemShopTemplate.Create;
fShopTemplates[i].StaticSettings := fStaticSettings;
fShopTemplates[i].LoadFromStream(Stream);
end;
end
else raise Exception.Create('TILManager_IO_00000008.LoadShopTemplates_00000008: Invalid stream.');
end;
//------------------------------------------------------------------------------
procedure TILManager_IO_00000008.SaveFilterSettings_00000008(Stream: TStream);
begin
Stream_WriteString(Stream,'FILTER');
Stream_WriteInt32(Stream,IL_FilterOperatorToNum(fFilterSettings.Operator));
Stream_WriteUInt32(Stream,IL_EncodeFilterFlags(fFilterSettings.Flags));
end;
//------------------------------------------------------------------------------
procedure TILManager_IO_00000008.LoadFilterSettings_00000008(Stream: TStream);
begin
If IL_SameStr(Stream_ReadString(Stream),'FILTER') then
begin
fFilterSettings.Operator := IL_NumToFilterOperator(Stream_ReadInt32(Stream));
fFilterSettings.Flags := IL_DecodeFilterFlags(Stream_ReadUInt32(Stream));
end
else raise Exception.Create('TILManager_IO_00000008.LoadFilterSettings_00000008: Invalid stream.');
end;
//------------------------------------------------------------------------------
procedure TILManager_IO_00000008.SaveItems_00000008(Stream: TStream);
var
i: Integer;
begin
Stream_WriteString(Stream,'ITEMS');
Stream_WriteUInt32(Stream,ItemCount);
For i := ItemLowIndex to ItemHighIndex do
fList[i].SaveToStream(Stream);
end;
//------------------------------------------------------------------------------
procedure TILManager_IO_00000008.LoadItems_00000008(Stream: TStream);
var
i: Integer;
begin
If IL_SameStr(Stream_ReadString(Stream),'ITEMS') then
begin
SetLength(fList,Stream_ReadUInt32(Stream));
fCount := Length(fList);
For i := ItemLowIndex to ItemHighIndex do
begin
fList[i] := TILItem.Create(fDataProvider);
// StaticSettings must be set must be before load so it is propagated to item shops
fList[i].StaticSettings := fStaticSettings;
fList[i].LoadFromStream(Stream);
fList[i].Index := i;
fList[i].AssignInternalEvents(
ShopUpdateShopListItemHandler,
ShopUpdateValuesHandler,
ShopUpdateAvailHistoryHandler,
ShopUpdatePriceHistoryHandler,
ItemUpdateMainListHandler,
ItemUpdateSmallListHandler,
ItemUpdateMiniListHandler,
ItemUpdateOverviewHandler,
ItemUpdateTitleHandler,
ItemUpdatePicturesHandler,
ItemUpdateFlagsHandler,
ItemUpdateValuesHandler,
ItemUpdateOthersHandler,
ItemUpdateShopListHandler,
ItemPasswordRequestHandler);
end;
end
else raise Exception.Create('TILManager_IO_00000008.LoadItems_00000008: Invalid stream.');
end;
end.
|
unit frmNewVolumeSize;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Classes, Controls, Dialogs,
Forms, Graphics, Messages, OTFEFreeOTFEBase_U, SDUFilenameEdit_U,
SDUForms, SDUFrames, SDUSpin64Units, Spin64, StdCtrls, SysUtils, Windows;
type
TfrmNewVolumeSize = class (TSDUForm)
pbCancel: TButton;
pbOK: TButton;
Label2: TLabel;
Label3: TLabel;
se64UnitSize: TSDUSpin64Unit_Storage;
feFilename: TSDUFilenameEdit;
procedure pbOKClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
FFilename: String;
FVolumeSize: Int64;
protected
function GetFilter(): String;
procedure SetFilter(new: String);
function GetDefaultExt(): String;
procedure SetDefaultExt(new: String);
public
property Filename: String Read FFilename Write FFilename;
property VolumeSize: Int64 Read FVolumeSize Write FVolumeSize;
property Filter: String Read GetFilter Write SetFilter;
property DefaultExt: String Read GetDefaultExt Write SetDefaultExt;
end;
implementation
{$R *.DFM}
uses
lcDialogs,
OTFEFreeOTFE_U, SDUGeneral,
SDUi18n;
procedure TfrmNewVolumeSize.pbOKClick(Sender: TObject);
begin
if (feFilename.Filename = '') then begin
SDUMessageDlg(
_('Please specify a filename for the new container by clicking the "..." button.'),
mtWarning
);
exit;
end;
// Calculate the number of bytes...
// Note: The in64(...) cast is REQUIRED, otherwise Delphi will calculate the
// value in 32 bits, and assign it to the 64 bit VolumeSize
VolumeSize := se64UnitSize.Value;
Filename := feFilename.Filename;
ModalResult := mrOk;
end;
procedure TfrmNewVolumeSize.FormShow(Sender: TObject);
begin
se64UnitSize.Value := DEFAULT_VOLUME_SIZE;
feFilename.Filename := '';
feFilename.OpenDialog.Options := feFilename.OpenDialog.Options + [ofDontAddToRecent];
feFilename.SaveDialog.Options := feFilename.SaveDialog.Options + [ofDontAddToRecent];
end;
function TfrmNewVolumeSize.GetFilter(): String;
begin
Result := feFilename.Filter;
end;
procedure TfrmNewVolumeSize.SetFilter(new: String);
begin
feFilename.Filter := new;
end;
function TfrmNewVolumeSize.GetDefaultExt(): String;
begin
Result := feFilename.DefaultExt;
end;
procedure TfrmNewVolumeSize.SetDefaultExt(new: String);
begin
feFilename.DefaultExt := new;
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.
-------------------------------------------------------------------------------}
/// <summary>
/// This unit defines a localization interface to the open source translation
/// tool dxgettext (GNU gettext for Delphi). It plugs into Ethea Foundation's
/// localization architecture to allow EF code to be localized by means of
/// dxgettext.
/// </summary>
unit EF.Localization.dxgettext;
{$I EF.Defines.inc}
interface
uses
Classes,
gnugettext,
EF.Intf, EF.Localization;
type
/// <summary>
/// EF localization tool that wraps dxgettext.
/// </summary>
/// <remarks>
/// This tool doesn't make use of Id strings.
/// </remarks>
TEFdxgettextLocalizationTool = class(TEFNoRefCountObject, IInterface,
IEFInterface, IEFLocalizationTool)
private
FInstance: TGnuGettextInstance;
public
function AsObject: TObject;
function TranslateString(const AString: string;
const AIdString: string = ''): string;
procedure TranslateComponent(const AComponent: TComponent);
procedure ForceLanguage(const ALanguageId: string);
function GetCurrentLanguageId: string;
procedure AfterConstruction; override;
destructor Destroy; override;
end;
implementation
uses
SysUtils;
{ TEFdxgettextLocalizationTool }
procedure TEFdxgettextLocalizationTool.AfterConstruction;
begin
inherited;
FInstance := TGnuGettextInstance.Create;
end;
function TEFdxgettextLocalizationTool.AsObject: TObject;
begin
Result := Self;
end;
destructor TEFdxgettextLocalizationTool.Destroy;
begin
FreeAndNil(FInstance);
inherited;
end;
procedure TEFdxgettextLocalizationTool.ForceLanguage(const ALanguageId: string);
begin
FInstance.UseLanguage(ALanguageId);
end;
function TEFdxgettextLocalizationTool.GetCurrentLanguageId: string;
begin
Result := FInstance.GetCurrentLanguage;
end;
procedure TEFdxgettextLocalizationTool.TranslateComponent(const AComponent: TComponent);
begin
FInstance.TranslateComponent(AComponent);
end;
function TEFdxgettextLocalizationTool.TranslateString(const AString,
AIdString: string): string;
begin
Result := FInstance.gettext(AString);
end;
initialization
TEFLocalizationToolRegistry.RegisterTool(TEFdxgettextLocalizationTool.Create);
finalization
TEFLocalizationToolRegistry.UnregisterTool;
end.
|
unit FormMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, ExtCtrls, Buttons, StdCtrls, ComCtrls, ImgList, Spin,FTGifAnimate,
Voxel, FormSurface, math3d, VH_SurfaceGen, normals, Registry;
// Note: BZK is an engine that I (Banshee) am working with
// some friends from my university (UFF). The BZK_BUILD
// can export .GEO (geometry) files that another program
// uses to create maps from it. This feature is already
// useless, since VXLSE was also modified and it exports
// the .BZK2 (maps) files straight from it.
// So, this must be commented out on the C&C version.
//{$define BZK_BUILD}
//{$define MEMORY_LEAK_DEBUG}
Const
APPLICATION_TITLE = 'Open Source Voxel Viewer';
APPLICATION_VER = '1.84b' {$ifdef BZK_BUILD} + ' BZK Edition'{$endif};
APPLICATION_VER_ID = '1.84c';
APPLICATION_BY = 'Stucuk and Banshee';
type
TVVFrmMain = class(TForm)
MainMenu1: TMainMenu;
File1: TMenuItem;
Exit1: TMenuItem;
Panel1: TPanel;
Panel2: TPanel;
MainView: TPanel;
OpenVXLDialog: TOpenDialog;
Load1: TMenuItem;
TopBarImageHolder: TImage;
Panel4: TPanel;
lblHVAFrame: TLabel;
PlayAnimation: TSpeedButton;
PauseAnimation: TSpeedButton;
StopAnimation: TSpeedButton;
AnimationBar: TTrackBar;
AnimFrom: TComboBoxEx;
Label2: TLabel;
RemapImageList: TImageList;
ImageList: TImageList;
Label1: TLabel;
Panel5: TPanel;
RemapColourBox: TComboBoxEx;
AnimationTimer: TTimer;
StatusBar1: TStatusBar;
RemapTimer: TTimer;
ColorDialog: TColorDialog;
Help1: TMenuItem;
About1: TMenuItem;
Panel3: TPanel;
SpeedButton2: TSpeedButton;
btn3DRotateX: TSpeedButton;
btn3DRotateX2: TSpeedButton;
btn3DRotateY2: TSpeedButton;
btn3DRotateY: TSpeedButton;
spin3Djmp: TSpinEdit;
Label3: TLabel;
Panel6: TPanel;
SectionBox: TComboBoxEx;
lblSection: TLabel;
UnitRotPopupMenu: TPopupMenu;
N01: TMenuItem;
N451: TMenuItem;
N901: TMenuItem;
N1351: TMenuItem;
N1801: TMenuItem;
N2251: TMenuItem;
N2701: TMenuItem;
N3151: TMenuItem;
Options1: TMenuItem;
Disable3DView1: TMenuItem;
View1: TMenuItem;
ools1: TMenuItem;
Spectrum1: TMenuItem;
Views1: TMenuItem;
N1: TMenuItem;
CameraManager1: TMenuItem;
ColoursNormals1: TMenuItem;
N2: TMenuItem;
Colours1: TMenuItem;
Normals1: TMenuItem;
Help2: TMenuItem;
N3: TMenuItem;
N4: TMenuItem;
ScreenShot1: TMenuItem;
N5: TMenuItem;
BackgroundColour1: TMenuItem;
extColour1: TMenuItem;
CaptureAnimation1: TMenuItem;
N6: TMenuItem;
LoadScene1: TMenuItem;
OpenVVSDialog: TOpenDialog;
SaveVVSDialog: TSaveDialog;
SaveScene1: TMenuItem;
Make360DegreeAnimation1: TMenuItem;
DebugVoxelBounds1: TMenuItem;
MakeBZKUnit1: TMenuItem;
GenerateSurface1: TMenuItem;
MakeGeoUnitwithPrecompiledLighting1: TMenuItem;
Panel7: TPanel;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
Panel8: TPanel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
GroundCheckBox: TCheckBox;
TileGroundCheckBox: TCheckBox;
XTexShift: TSpinEdit;
YTexShift: TSpinEdit;
GroundSize: TSpinEdit;
GroundHeightOffsetSpinEdit: TSpinEdit;
GroundTexBox: TComboBoxEx;
TabSheet4: TTabSheet;
Label20: TLabel;
Label21: TLabel;
UnitRotPopupBut: TSpeedButton;
Label18: TLabel;
Label29: TLabel;
UnitShiftXSpinEdit: TSpinEdit;
UnitShiftYSpinEdit: TSpinEdit;
RotationEdit: TEdit;
TurretRotationBar: TTrackBar;
TabSheet5: TTabSheet;
Label19: TLabel;
Label22: TLabel;
Label23: TLabel;
Label24: TLabel;
Label25: TLabel;
Label26: TLabel;
Label27: TLabel;
Label28: TLabel;
SpeedButton1: TSpeedButton;
SpeedButton3: TSpeedButton;
AmbientRed: TSpinEdit;
AmbientGreen: TSpinEdit;
AmbientBlue: TSpinEdit;
DiffuseRed: TSpinEdit;
DiffuseGreen: TSpinEdit;
DiffuseBlue: TSpinEdit;
LightGroundCheckBox: TCheckBox;
TabSheet2: TTabSheet;
Label17: TLabel;
Label16: TLabel;
Label15: TLabel;
CamMovEdit: TEdit;
VisibleDistEdit: TSpinEdit;
FOVEdit: TSpinEdit;
CullFaceCheckBox: TCheckBox;
VoxelCountCheckBox: TCheckBox;
ShowDebugCheckBox: TCheckBox;
DrawBarrelCheckBox: TCheckBox;
DrawTurretCheckBox: TCheckBox;
Timer1: TTimer;
Label30: TLabel;
UnitCountCombo: TComboBox;
Label31: TLabel;
UnitSpaceEdit: TSpinEdit;
Label14: TLabel;
SkyLengthSpinEdit: TSpinEdit;
SkyHeightSpinEdit: TSpinEdit;
Label13: TLabel;
Label12: TLabel;
SkyWidthSpinEdit: TSpinEdit;
SkyXPosSpinEdit: TSpinEdit;
SkyZPosSpinEdit: TSpinEdit;
SkyYPosSpinEdit: TSpinEdit;
Label11: TLabel;
Label10: TLabel;
Label5: TLabel;
DrawSkyCheckBox: TCheckBox;
SkyTextureComboBox: TComboBox;
Bevel1: TBevel;
Label32: TLabel;
Label33: TLabel;
AutoSizeCheck: TCheckBox;
Label4: TLabel;
OGLSize: TSpinEdit;
Bevel2: TBevel;
Label34: TLabel;
Label35: TLabel;
Label36: TLabel;
Label38: TLabel;
Label37: TLabel;
EdOffsetX: TEdit;
UnitShiftZSpinEdit: TSpinEdit;
Label41: TLabel;
EdFLHF: TEdit;
EdFLHL: TEdit;
EdFLHH: TEdit;
lblPrimaryFireFLH: TLabel;
lblFLHF: TLabel;
lblFLHL: TLabel;
lblFLHH: TLabel;
FLHBulletCheckBox: TCheckBox;
procedure FLHBulletCheckBoxClick(Sender: TObject);
procedure EdFLHHChange(Sender: TObject);
procedure EdFLHLChange(Sender: TObject);
procedure EdFLHFChange(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure UnitShiftZSpinEditChange(Sender: TObject);
procedure EdOffsetXChange(Sender: TObject);
procedure MainViewResize(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure DrawFrames;
procedure Idle(Sender: TObject; var Done: Boolean);
procedure Exit1Click(Sender: TObject);
procedure Load1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure MainViewMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure MainViewMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure MainViewMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure AnimationTimerTimer(Sender: TObject);
procedure PlayAnimationClick(Sender: TObject);
procedure PauseAnimationClick(Sender: TObject);
procedure StopAnimationClick(Sender: TObject);
procedure AnimationBarChange(Sender: TObject);
Procedure SetAnimFrom;
Procedure SetIsHVA;
Procedure SetIsEditable;
Procedure SetCaption(Filename : String);
procedure RemapColourBoxChange(Sender: TObject);
procedure RemapTimerTimer(Sender: TObject);
procedure AnimFromChange(Sender: TObject);
procedure About1Click(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 SetupSections;
procedure SectionBoxChange(Sender: TObject);
procedure FOVEditChange(Sender: TObject);
procedure VisibleDistEditChange(Sender: TObject);
procedure UnitRotPopupButClick(Sender: TObject);
procedure N01Click(Sender: TObject);
procedure RotationEditChange(Sender: TObject);
procedure UnitShiftXSpinEditChange(Sender: TObject);
procedure UnitShiftYSpinEditChange(Sender: TObject);
procedure XTexShiftChange(Sender: TObject);
procedure YTexShiftChange(Sender: TObject);
procedure GroundHeightOffsetSpinEditChange(Sender: TObject);
procedure TileGroundCheckBoxClick(Sender: TObject);
procedure GroundCheckBoxClick(Sender: TObject);
procedure DrawTurretCheckBoxClick(Sender: TObject);
procedure DrawBarrelCheckBoxClick(Sender: TObject);
procedure ShowDebugCheckBoxClick(Sender: TObject);
procedure VoxelCountCheckBoxClick(Sender: TObject);
procedure CullFaceCheckBoxClick(Sender: TObject);
procedure CamMovEditChange(Sender: TObject);
procedure GroundSizeChange(Sender: TObject);
Procedure BuildTexList;
procedure GroundTexBoxChange(Sender: TObject);
Procedure BuildSkyTextureComboBox;
procedure SkyTextureComboBoxChange(Sender: TObject);
procedure SkyWidthSpinEditChange(Sender: TObject);
procedure SkyHeightSpinEditChange(Sender: TObject);
procedure SkyLengthSpinEditChange(Sender: TObject);
procedure SkyZPosSpinEditChange(Sender: TObject);
procedure SkyYPosSpinEditChange(Sender: TObject);
procedure SkyXPosSpinEditChange(Sender: TObject);
procedure DrawSkyCheckBoxClick(Sender: TObject);
procedure Disable3DView1Click(Sender: TObject);
procedure ColoursNormals1Click(Sender: TObject);
procedure Colours1Click(Sender: TObject);
procedure Normals1Click(Sender: TObject);
procedure CameraManager1Click(Sender: TObject);
procedure Help2Click(Sender: TObject);
Procedure ChangeView(Sender : TObject);
procedure ScreenShot1Click(Sender: TObject);
procedure BackgroundColour1Click(Sender: TObject);
procedure extColour1Click(Sender: TObject);
procedure CaptureAnimation1Click(Sender: TObject);
Procedure ClearRotationAdders;
procedure LoadScene1Click(Sender: TObject);
procedure SaveScene1Click(Sender: TObject);
procedure Make360DegreeAnimation1Click(Sender: TObject);
procedure AmbientRedChange(Sender: TObject);
procedure AmbientGreenChange(Sender: TObject);
procedure AmbientBlueChange(Sender: TObject);
procedure DiffuseRedChange(Sender: TObject);
procedure DiffuseGreenChange(Sender: TObject);
procedure DiffuseBlueChange(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure SpeedButton3Click(Sender: TObject);
procedure LightGroundCheckBoxClick(Sender: TObject);
procedure TurretRotationBarChange(Sender: TObject);
procedure CopyData(var Msg: TMessage); message WM_COPYDATA;
procedure OpenVoxel(FileName : string);
procedure DebugVoxelBounds1Click(Sender: TObject);
procedure MakeBZKUnit1Click(Sender: TObject);
procedure GenerateSurface1Click(Sender: TObject);
procedure MakeGeoUnitwithPrecompiledLighting1Click(Sender: TObject);
procedure OGLSizeChange(Sender: TObject);
procedure AutoSizeCheckClick(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure UnitCountComboChange(Sender: TObject);
procedure UnitSpaceEditChange(Sender: TObject);
procedure DeactivateView(Sender: TObject);
procedure ActivateView(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
LoadedProg : Boolean;
end;
var
VVFrmMain: TVVFrmMain;
implementation
Uses VH_Engine,VH_Global,VH_GL,VH_Voxel{,Voxel},HVA,FormAboutNew,
FormCameraManagerNew, ShellAPI,FormProgress,FormScreenShotManagerNew,
FormAnimationManagerNew, VH_Types, Math, OpenGL15;
{$R *.dfm}
procedure RunAProgram (const theProgram, itsParameters, defaultDirectory : string);
var
rslt : integer;
msg : string;
begin
rslt := ShellExecute (0, 'open',
pChar (theProgram),
pChar (itsParameters),
pChar (defaultDirectory),
sw_ShowNormal);
if rslt <= 32 then
begin
case rslt of
0,
se_err_OOM : msg := 'Out of memory/resources';
error_File_Not_Found : msg := 'File "' + theProgram + '" not found';
error_Path_Not_Found : msg := 'Path not found';
error_Bad_Format : msg := 'Damaged or invalid exe';
se_err_AccessDenied : msg := 'Access denied';
se_err_NoAssoc,
se_err_AssocIncomplete : msg := 'Filename association invalid';
se_err_DDEBusy,
se_err_DDEFail,
se_err_DDETimeOut : msg := 'DDE error';
se_err_Share : msg := 'Sharing violation';
else msg := 'no text';
end; // of case
raise Exception.Create ('ShellExecute error #' + IntToStr (rslt) + ': ' + msg);
end;
end;
procedure TVVFrmMain.MainViewResize(Sender: TObject);
begin
If oglloaded then
glResizeWnd(MainView.Width,MainView.Height);
end;
procedure TVVFrmMain.FLHBulletCheckBoxClick(Sender: TObject);
begin
DrawPrimaryFireFLH := not DrawPrimaryFireFLH;
FLHBulletCheckBox.Checked := DrawPrimaryFireFLH;
end;
procedure TVVFrmMain.FormCreate(Sender: TObject);
var
frm : TFrmProgress;
begin
{$ifdef MEMORY_LEAK_DEBUG}
ReportMemoryLeaksOnShutdown := true;
{$endif}
LoadedProg := False;
RemapColourBox.ItemIndex := 1;
RemapColourBoxChange(Sender);
SetIsEditable;
SetCaption('');
Highlight := False; // No Highlighting in VXL View
DrawAllOfVoxel := False;
UnitRot := 180;
Ground_Tex_Draw := True;
DrawSky := True;
If not InitalizeVHE(ExtractFileDir(ParamStr(0)),'Palettes\ts\unittem.pal',MainView.Width,MainView.Height,MainView.Handle,-90) then
begin
Messagebox(0,pchar('Error Initalizing Engine'#13#13'Closing'),'VH Engine',0);
Application.Terminate;
end;
frm:=TFrmProgress.Create(Application);
frm.Visible:=False;
frm.UpdateAction('');
frm.Show;
frm.Refresh;
VH_LoadGroundTextures(frm);
if (GroundTex_No = 0) then
begin
Messagebox(0,'Error: Couldn''t load Ground Textures','Textures Missing',0);
Application.Terminate;
end;
VH_LoadSkyTextures(frm);
if (SkyTexList_No = 0) then
begin
Messagebox(0,'Error: Couldn''t load Sky Textures','Textures Missing',0);
Application.Terminate;
end;
frm.Close;
frm.Free;
BuildTexList;
BuildSkyTextureComboBox;
VH_BuildViewMenu(Views1,ChangeView);
VH_ChangeView(Default_View);
wglSwapIntervalEXT(1); // Activate VSync.
RotationEdit.Text := floattostr(UnitRot);
FOVEdit.Value := Trunc(FOV);
VisibleDistEdit.Value := Trunc(DEPTH_OF_VIEW);
PageControl1.ActivePage := TabSheet1;
SkyWidthSpinEdit.Value := Trunc(DEPTH_OF_VIEW/2);
SkyHeightSpinEdit.Value := SkyWidthSpinEdit.Value;
SkyLengthSpinEdit.Value := SkyWidthSpinEdit.Value;
GroundSize.Value := Trunc(DEPTH_OF_VIEW);
Application.OnIdle := Idle;
AmbientRed.Value := Trunc(LightAmb.X*255);
AmbientGreen.Value := Trunc(LightAmb.Y*255);
AmbientBlue.Value := Trunc(LightAmb.Z*255);
DiffuseRed.Value := Trunc(LightDif.X*255);
DiffuseGreen.Value := Trunc(LightDif.Y*255);
DiffuseBlue.Value := Trunc(LightDif.Z*255);
Application.OnDeactivate := DeactivateView;
Application.OnActivate := ActivateView;
Application.OnMinimize := DeactivateView;
Application.OnRestore := ActivateView;
LoadedProg := True;
end;
procedure TVVFrmMain.FormDestroy(Sender: TObject);
begin
if VoxelOpen then
begin
VoxelFile.Free;
end;
if VoxelOpenT then
begin
VoxelTurret.Free;
end;
if VoxelOpenB then
begin
VoxelBarrel.Free;
end;
end;
procedure TVVFrmMain.ActivateView(Sender : TObject);
begin
Application.OnIdle := Idle;
end;
procedure TVVFrmMain.DeactivateView(Sender : TObject);
begin
Application.OnIdle := nil;
end;
procedure TVVFrmMain.Idle(Sender: TObject; var Done: Boolean);
var
BMP : TBitmap;
begin
Done := False;
if not DrawVHWorld then exit;
if (ScreenShot.Take) or (ScreenShot.TakeAnimation) or (ScreenShot.Take360DAnimation) then
FUpdateWorld := True;
DrawFrames;
if ScreenShot.Take then
begin
if ScreenShot._Type = 0 then
VH_ScreenShot(VXLFilename)
else if ScreenShot._Type = 1 then
VH_ScreenShotJPG(VXLFilename,ScreenShot.CompressionRate)
else if ScreenShot._Type = 2 then
VH_ScreenShotToSHPBuilder;
if AutoSizeCheck.Checked then
MainView.Align := alClient
else
begin
MainView.Align := alNone;
MainView.Width := OGLSize.Value;
MainView.Height := OGLSize.Value;
end;
ScreenShot.Take := false;
end;
if ScreenShot.TakeAnimation then
begin
BMP := VH_ScreenShot_BitmapResult;
GifAnimateAddImage(BMP,false,100);
BMP.Free;
ScreenShot.TakeAnimation := false;
end;
if ScreenShot.Take360DAnimation then
begin
inc(ScreenShot.FrameCount);
BMP := VH_ScreenShot_BitmapResult;
GifAnimateAddImage(BMP,false,(100*90) div ScreenShot.Frames);
BMP.Free;
YRot := YRot + ScreenShot.FrameAdder;
if ScreenShot.FrameCount >= ScreenShot.Frames then
begin
VH_ScreenShotGIF(GifAnimateEndGif,VXLFilename);
YRot := ScreenShot.OldYRot;
ScreenShot.Take360DAnimation := false;
if AutoSizeCheck.Checked then
MainView.Align := alClient
else
begin
MainView.Align := alNone;
MainView.Width := OGLSize.Value;
MainView.Height := OGLSize.Value;
end;
AnimationTimer.Enabled := False;
AnimationBar.Position := 0;
AnimationBarChange(Sender);
end;
end;
// Sleep(1);
end;
procedure TVVFrmMain.DrawFrames;
begin
if not oglloaded then
exit;
VH_Draw(); // Draw the scene
end;
procedure TVVFrmMain.EdFLHFChange(Sender: TObject);
begin
PrimaryFireFLH.X := StrToFloatDef(EdFLHF.Text,0);
end;
procedure TVVFrmMain.EdFLHHChange(Sender: TObject);
begin
PrimaryFireFLH.Z := StrToFloatDef(EdFLHH.Text,0);
end;
procedure TVVFrmMain.EdFLHLChange(Sender: TObject);
begin
PrimaryFireFLH.Y := StrToFloatDef(EdFLHL.Text,0);
end;
procedure TVVFrmMain.EdOffsetXChange(Sender: TObject);
begin
TurretOffset.X := StrToFloatDef(EdOffsetX.Text,0);
end;
procedure TVVFrmMain.Exit1Click(Sender: TObject);
begin
Close;
end;
procedure TVVFrmMain.Load1Click(Sender: TObject);
begin
if OpenVXLDialog.Execute then
begin
OpenVoxel(OpenVXLDialog.FileName);
DrawFrames;
FUpdateWorld := True;
end;
end;
Function GetParamStr : String;
var
x : integer;
begin
Result := '';
for x := 1 to ParamCount do
if Result <> '' then
Result := Result + ' ' +ParamStr(x)
else
Result := ParamStr(x);
end;
procedure TVVFrmMain.OpenVoxel(FileName : string);
begin
If FileExists(FileName) then
Begin
LoadVoxel(FileName);
//If HVAOpen then
SetCaption(FileName);
SetupSections;
SectionBox.ItemIndex := 0;
SectionBoxChange(nil);
RemapColourBoxChange(nil);
SetAnimFrom;
AnimFrom.ItemIndex := 0;
AnimFromChange(nil);
SetIsEditable;
If HVAOpen then
AnimationBar.Max := HVAFile.Header.N_Frames-1
else
AnimationBar.Max := 0;
lblHVAFrame.Caption := 'Frame ' + inttostr(GetCurrentFrame+1) + '/' + inttostr(GetCurrentHVA^.Header.N_Frames);
FUpdateWorld := True;
End;
end;
procedure TVVFrmMain.FormShow(Sender: TObject);
var
Reg : TRegistry;
LatestVersion: string;
begin
glResizeWnd(MainView.Width,MainView.Height);
// 1.7: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\VoxelViewer\',true) then
begin
LatestVersion := Reg.ReadString('Version');
if APPLICATION_VER_ID > LatestVersion then
begin
Reg.WriteString('Path',ParamStr(0));
Reg.WriteString('Version',APPLICATION_VER);
end;
end;
Reg.CloseKey;
Reg.Free;
if ParamCount > 0 then
OpenVoxel(GetParamStr());
end;
procedure TVVFrmMain.MainViewMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
VH_MouseDown(Button,X, Y);
end;
procedure TVVFrmMain.MainViewMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
VH_MouseUp;
MainView.Cursor := crCross;
end;
procedure TVVFrmMain.MainViewMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
VH_MouseMove(X,Y);
end;
procedure TVVFrmMain.AnimationTimerTimer(Sender: TObject);
Var
N_Frames : Integer;
begin
N_Frames := GetCurrentHVA^.Header.N_Frames;
if (N_Frames < 2) then
begin
AnimationTimer.Enabled := false;
HVAFrame := 0;
HVAFrameT := 0;
HVAFrameB := 0;
AnimationBar.Position := 0;
exit;
end;
if (AnimationBar.Position = N_Frames-1) and ScreenShot.CaptureAnimation then
begin
ScreenShot.CaptureAnimation := False;
VH_ScreenShotGIF(GifAnimateEndGif,VXLFilename);
AnimationTimer.Enabled := false;
HVAFrame := 0;
HVAFrameT := 0;
HVAFrameB := 0;
AnimationBar.Position := 0;
if AutoSizeCheck.Checked then
MainView.Align := alClient
else
begin
MainView.Align := alNone;
MainView.Width := OGLSize.Value;
MainView.Height := OGLSize.Value;
end;
exit;
end;
if ScreenShot.CaptureAnimation then
ScreenShot.TakeAnimation := true;
if AnimationBar.Position = N_Frames-1 then
AnimationBar.Position := 0
else
AnimationBar.Position := AnimationBar.Position +1;
FUpdateWorld := True;
end;
procedure TVVFrmMain.PlayAnimationClick(Sender: TObject);
begin
AnimationTimer.Enabled := true;
end;
procedure TVVFrmMain.PauseAnimationClick(Sender: TObject);
begin
AnimationTimer.Enabled := not AnimationTimer.Enabled;
end;
procedure TVVFrmMain.StopAnimationClick(Sender: TObject);
begin
AnimationTimer.Enabled := False;
AnimationBar.Position := 0;
end;
procedure TVVFrmMain.AnimationBarChange(Sender: TObject);
begin
SetCurrentFrame(AnimationBar.Position);
lblHVAFrame.Caption := 'Frame ' + inttostr(GetCurrentFrame+1) + '/' + inttostr(GetCurrentHVA^.Header.N_Frames);
end;
Procedure TVVFrmMain.SetAnimFrom;
begin
AnimFrom.Clear;
if VoxelOpen then
begin
AnimFrom.Items.Add('Body');
AnimFrom.ItemsEx.Items[AnimFrom.Items.Count-1].ImageIndex := 4;
end;
if VoxelOpenT then
begin
AnimFrom.Items.Add('Turret');
AnimFrom.ItemsEx.Items[AnimFrom.Items.Count-1].ImageIndex := 5;
end;
if VoxelOpenB then
begin
AnimFrom.Items.Add('Barrel');
AnimFrom.ItemsEx.Items[AnimFrom.Items.Count-1].ImageIndex := 6;
end;
end;
Procedure TVVFrmMain.SetIsHVA;
begin
AnimFrom.Enabled := HVAOpen;
AnimationBar.Enabled := HVAOpen;
PlayAnimation.Enabled := HVAOpen;
PauseAnimation.Enabled := HVAOpen;
StopAnimation.Enabled := HVAOpen;
lblHVAFrame.Enabled := HVAOpen;
end;
Procedure TVVFrmMain.SetIsEditable;
begin
RemapColourBox.Enabled := VoxelOpen;
SpeedButton2.Enabled := VoxelOpen;
btn3DRotateX.Enabled := VoxelOpen;
btn3DRotateX2.Enabled := VoxelOpen;
btn3DRotateY.Enabled := VoxelOpen;
btn3DRotateY2.Enabled := VoxelOpen;
spin3Djmp.Enabled := VoxelOpen;
SectionBox.Enabled := VoxelOpen;
PageControl1.Enabled := VoxelOpen;
GroundTexBox.Enabled := VoxelOpen;
GroundCheckBox.Enabled := VoxelOpen;
TileGroundCheckBox.Enabled := VoxelOpen;
XTexShift.Enabled := VoxelOpen;
YTexShift.Enabled := VoxelOpen;
GroundSize.Enabled := VoxelOpen;
GroundHeightOffsetSpinEdit.Enabled := VoxelOpen;
Label8.Enabled := VoxelOpen;
Label7.Enabled := VoxelOpen;
Label6.Enabled := VoxelOpen;
Label9.Enabled := VoxelOpen;
GroundTexBox.Enabled := VoxelOpen;
SkyTextureComboBox.Enabled := VoxelOpen;
Label5.Enabled := VoxelOpen;
Label10.Enabled := VoxelOpen;
Label11.Enabled := VoxelOpen;
Label12.Enabled := VoxelOpen;
Label13.Enabled := VoxelOpen;
Label14.Enabled := VoxelOpen;
Label32.Enabled := VoxelOpen;
Label33.Enabled := VoxelOpen;
DrawSkyCheckBox.Enabled := VoxelOpen;
SkyXPosSpinEdit.Enabled := VoxelOpen;
SkyYPosSpinEdit.Enabled := VoxelOpen;
SkyZPosSpinEdit.Enabled := VoxelOpen;
SkyWidthSpinEdit.Enabled := VoxelOpen;
SkyHeightSpinEdit.Enabled := VoxelOpen;
SkyLengthSpinEdit.Enabled := VoxelOpen;
Options1.Visible := VoxelOpen;
View1.Visible := VoxelOpen;
ools1.Visible := VoxelOpen;
Label29.Enabled := VoxelOpenT;
TurretRotationBar.Enabled := VoxelOpenT;
// Options menu.
{$ifdef DEBUG_BUILD}
DebugVoxelBounds1.Visible := VoxelOpen;
{$endif}
{$ifdef BZK_BUILD}
MakeBZKUnit1.Visible := VoxelOpen;
MakeGeoUnitwithPrecompiledLighting1.Visible := VoxelOpen;
// GenerateSurface1.Visible := VoxelOpen;
{$endif}
SetIsHVA;
end;
Procedure TVVFrmMain.SetCaption(Filename : String);
begin
If Filename <> '' then
Caption := ' ' + APPLICATION_TITLE + ' v'+APPLICATION_VER + ' [' +Extractfilename(Filename) + ']'
else
Caption := ' ' + APPLICATION_TITLE + ' v'+APPLICATION_VER;
end;
procedure TVVFrmMain.RemapColourBoxChange(Sender: TObject);
begin
If (RemapColourBox.ItemIndex > 0) then
begin
RemapColour := TVector3bToTVector3f(RemapColourMap[RemapColourBox.ItemIndex-1]);
ChangeRemappable(VXLPalette,RemapColour);
RebuildLists := True;
end
else If LoadedProg then
RemapTimer.Enabled := true;
end;
procedure TVVFrmMain.RemapTimerTimer(Sender: TObject);
begin
RemapTimer.Enabled := False;
ColorDialog.Color := TVector3ftoTColor(RemapColour);
if ColorDialog.Execute then
begin
RemapColour := TColorToTVector3f(ColorDialog.Color);
ChangeRemappable(VXLPalette,RemapColour);
RebuildLists := True;
end;
end;
procedure TVVFrmMain.AnimFromChange(Sender: TObject);
begin
if AnimFrom.Items.Count < 1 then exit;
if AnimFrom.ItemsEx.Items[AnimFrom.ItemIndex].ImageIndex = 5 then
HVACurrentFrame := 1
else if AnimFrom.ItemsEx.Items[AnimFrom.ItemIndex].ImageIndex = 6 then
HVACurrentFrame := 2
else
HVACurrentFrame := 0;
end;
procedure TVVFrmMain.About1Click(Sender: TObject);
var
frm: TFrmAbout_New;
begin
frm:=TFrmAbout_New.Create(Self);
frm.Visible:=False;
Frm.Image1.Picture := TopBarImageHolder.Picture;
{ if TB_ENABLED then
frm.Label2.Caption := APPLICATION_TITLE + ' v' + APPLICATION_VER + ' TB ' + TB_VER
else }
frm.Label2.Caption := APPLICATION_TITLE + ' v' + APPLICATION_VER;
frm.Label1.Caption := frm.Label1.Caption + APPLICATION_BY;
frm.Label6.Caption := ENGINE_TITLE + ' v' + ENGINE_VER;
frm.Label9.Caption := 'By: ' + ENGINE_BY;
frm.ShowModal;
frm.Close;
frm.Free;
end;
procedure TVVFrmMain.SpeedButton2Click(Sender: TObject);
begin
Depth := DefaultDepth;
end;
Procedure TVVFrmMain.SetRotationAdders;
var
V : single;
begin
try
V := spin3Djmp.Value / 10;
except
exit; // Not a value
end;
if btn3DRotateX2.Down then
XRot2 := V
else if btn3DRotateX.Down then
XRot2 := -V;
if btn3DRotateY2.Down then
YRot2 := -V
else if btn3DRotateY.Down then
YRot2 := V;
end;
procedure TVVFrmMain.btn3DRotateXClick(Sender: TObject);
begin
if btn3DRotateX.Down then
begin
SetRotationAdders;
XRotB := True;
end
else
XRotB := false;
if XRotB or YRotB then
Timer1.Interval := 50
else
Timer1.Interval := 100;
end;
procedure TVVFrmMain.btn3DRotateX2Click(Sender: TObject);
begin
if btn3DRotateX2.Down then
begin
SetRotationAdders;
XRotB := True;
end
else
XRotB := false;
if XRotB or YRotB then
Timer1.Interval := 50
else
Timer1.Interval := 100;
end;
procedure TVVFrmMain.btn3DRotateY2Click(Sender: TObject);
begin
if btn3DRotateY2.Down then
begin
SetRotationAdders;
YRotB := True;
end
else
YRotB := false;
if XRotB or YRotB then
Timer1.Interval := 50
else
Timer1.Interval := 100;
end;
procedure TVVFrmMain.btn3DRotateYClick(Sender: TObject);
begin
if btn3DRotateY.Down then
begin
SetRotationAdders;
YRotB := True;
end
else
YRotB := false;
if XRotB or YRotB then
Timer1.Interval := 50
else
Timer1.Interval := 100;
end;
procedure TVVFrmMain.spin3DjmpChange(Sender: TObject);
begin
SetRotationAdders;
end;
Procedure TVVFrmMain.SetupSections;
var
i : integer;
begin
SectionBox.Clear;
SectionBox.Items.Add('View All');
for i := 0 to (VoxelFile.Header.NumSections - 1) do
begin
SectionBox.Items.Add(VoxelFile.Section[i].Name);
SectionBox.ItemsEx.Items[SectionBox.Items.Count-1].ImageIndex := 4;
end;
if VoxelOpenT then
for i := 0 to (VoxelTurret.Header.NumSections - 1) do
begin
SectionBox.Items.Add(VoxelTurret.Section[i].Name);
SectionBox.ItemsEx.Items[SectionBox.Items.Count-1].ImageIndex := 5;
end;
if VoxelOpenB then
for i := 0 to (VoxelBarrel.Header.NumSections - 1) do
begin
SectionBox.Items.Add(VoxelBarrel.Section[i].Name);
SectionBox.ItemsEx.Items[SectionBox.Items.Count-1].ImageIndex := 6;
end;
//SectionBox.ItemIndex := CurrentSection+1;
end;
procedure TVVFrmMain.SectionBoxChange(Sender: TObject);
begin
if not VoxelOpen then exit;
if SectionBox.Items.Count < 1 then exit; // Stops access violations when sectionbox is cleared.
RebuildLists := True;
if SectionBox.ItemIndex = 0 then
begin
CurrentSection := -1;
CurrentSectionVoxel := @VoxelFile;
end
else
begin
if SectionBox.ItemIndex > VoxelFile.Header.NumSections then
if VoxelOpenT then
begin
if SectionBox.ItemIndex <= VoxelFile.Header.NumSections+VoxelTurret.Header.NumSections then
begin
CurrentSection := SectionBox.ItemIndex-VoxelFile.Header.NumSections-1;
CurrentSectionVoxel := @VoxelTurret;
end
else
if VoxelOpenB then
if SectionBox.ItemIndex <= VoxelFile.Header.NumSections+VoxelTurret.Header.NumSections+VoxelBarrel.Header.NumSections then
begin
CurrentSection := SectionBox.ItemIndex-VoxelFile.Header.NumSections-VoxelTurret.Header.NumSections-1;
CurrentSectionVoxel := @VoxelBarrel;
end;
end
else
if VoxelOpenB then
if SectionBox.ItemIndex <= VoxelFile.Header.NumSections+VoxelBarrel.Header.NumSections then
begin
CurrentSection := SectionBox.ItemIndex-VoxelFile.Header.NumSections-1;
CurrentSectionVoxel := @VoxelBarrel;
end;
if SectionBox.ItemIndex <= VoxelFile.Header.NumSections then
begin
CurrentSection := SectionBox.ItemIndex-1;
CurrentSectionVoxel := @VoxelFile;
end;
end;
end;
procedure TVVFrmMain.FOVEditChange(Sender: TObject);
begin
If VVSLoading then exit;
if (FOVEdit.Text <> '') and (FOVEdit.Text <> ' ') then
try
FOV := FOVEdit.Value;
glResizeWnd(MainView.Width,MainView.Height);
except
end;
end;
procedure TVVFrmMain.VisibleDistEditChange(Sender: TObject);
begin
If VVSLoading then exit;
if (VisibleDistEdit.Text <> '') and (VisibleDistEdit.Text <> ' ') then
try
DEPTH_OF_VIEW := VisibleDistEdit.Value;
glResizeWnd(MainView.Width,MainView.Height);
except
end;
end;
procedure TVVFrmMain.UnitRotPopupButClick(Sender: TObject);
begin
UnitRotPopupMenu.Popup(Left+TabSheet2.Left+PageControl1.Left+Panel7.Left+UnitRotPopupBut.Left+3,Top+Height-ClientHeight+Panel7.Top+TabSheet2.Top+PageControl1.Top+UnitRotPopupBut.Top+UnitRotPopupBut.Height-4);
FUpdateWorld := True;
end;
procedure TVVFrmMain.N01Click(Sender: TObject);
begin
RotationEdit.Text := inttostr(TMenuItem(Sender).Tag);
end;
procedure TVVFrmMain.RotationEditChange(Sender: TObject);
begin
try
//RotationEdit.Text := floattostr(strtofloat(RotationEdit.Text));
UnitRot := CleanAngle(strtofloatdef(RotationEdit.Text,0));
//UnitRotUpDown.Position := trunc(UnitRot);
except
end;
FUpdateWorld := True;
end;
procedure TVVFrmMain.UnitShiftXSpinEditChange(Sender: TObject);
begin
If VVSLoading then exit;
if (UnitShiftXSpinEdit.Text <> '') and (UnitShiftXSpinEdit.Text <> ' ') then
try
UnitShift.X := UnitShiftXSpinEdit.Value;
except
end;
FUpdateWorld := True;
end;
procedure TVVFrmMain.UnitShiftYSpinEditChange(Sender: TObject);
begin
If VVSLoading then exit;
if (UnitShiftYSpinEdit.Text <> '') and (UnitShiftYSpinEdit.Text <> ' ') then
try
UnitShift.Y := UnitShiftYSpinEdit.Value;
except
end;
FUpdateWorld := True;
end;
procedure TVVFrmMain.UnitShiftZSpinEditChange(Sender: TObject);
begin
If VVSLoading then exit;
if (UnitShiftZSpinEdit.Text <> '') and (UnitShiftZSpinEdit.Text <> ' ') then
try
UnitShift.Z := UnitShiftZSpinEdit.Value;
except
end;
FUpdateWorld := True;
end;
procedure TVVFrmMain.XTexShiftChange(Sender: TObject);
begin
If VVSLoading then exit;
if (XTexShift.Text <> '') and (XTexShift.Text <> ' ') then
try
TexShiftX := XTexShift.Value;
except
end;
FUpdateWorld := True;
end;
procedure TVVFrmMain.YTexShiftChange(Sender: TObject);
begin
If VVSLoading then exit;
if (YTexShift.Text <> '') and (YTexShift.Text <> ' ') then
try
TexShiftY := YTexShift.Value;
except
end;
FUpdateWorld := True;
end;
procedure TVVFrmMain.GroundHeightOffsetSpinEditChange(Sender: TObject);
begin
If VVSLoading then exit;
if (GroundHeightOffsetSpinEdit.Text <> '') and (GroundHeightOffsetSpinEdit.Text <> ' ') then
try
GroundHeightOffset := GroundHeightOffsetSpinEdit.Value;
except
end;
FUpdateWorld := True;
end;
procedure TVVFrmMain.TileGroundCheckBoxClick(Sender: TObject);
begin
If VVSLoading then exit;
TileGround := not TileGround;
TileGroundCheckBox.Checked := TileGround;
FUpdateWorld := True;
end;
procedure TVVFrmMain.GroundCheckBoxClick(Sender: TObject);
begin
If VVSLoading then exit;
Ground_Tex_Draw := not Ground_Tex_Draw;
GroundCheckBox.Checked := Ground_Tex_Draw;
FUpdateWorld := True;
end;
procedure TVVFrmMain.DrawTurretCheckBoxClick(Sender: TObject);
begin
If VVSLoading then exit;
DrawTurret := not DrawTurret;
DrawTurretCheckBox.Checked := DrawTurret;
FUpdateWorld := True;
end;
procedure TVVFrmMain.DrawBarrelCheckBoxClick(Sender: TObject);
begin
If VVSLoading then exit;
DrawBarrel := not DrawBarrel;
DrawBarrelCheckBox.Checked := DrawBarrel;
FUpdateWorld := True;
end;
procedure TVVFrmMain.ShowDebugCheckBoxClick(Sender: TObject);
begin
If VVSLoading then exit;
DebugMode := not DebugMode;
ShowDebugCheckBox.Checked := DebugMode;
end;
procedure TVVFrmMain.VoxelCountCheckBoxClick(Sender: TObject);
begin
If VVSLoading then exit;
ShowVoxelCount := not ShowVoxelCount;
VoxelCountCheckBox.Checked := ShowVoxelCount;
end;
procedure TVVFrmMain.CullFaceCheckBoxClick(Sender: TObject);
begin
If VVSLoading then exit;
CullFace := not CullFace;
CullFaceCheckBox.Checked := CullFace;
end;
procedure TVVFrmMain.CamMovEditChange(Sender: TObject);
begin
if (CamMovEdit.Text <> '') and (CamMovEdit.Text <> ' ') then
try
CamMov := strtofloat(CamMovEdit.text);
except
end;
end;
procedure TVVFrmMain.GroundSizeChange(Sender: TObject);
begin
If VVSLoading then exit;
if (GroundSize.Text <> '') and (GroundSize.Text <> ' ') then
try
if GroundSize.Value < 1 then exit;
GSize := GroundSize.Value;
except
end;
FUpdateWorld := True;
end;
Procedure TVVFrmMain.BuildTexList;
var
X,IID : integer;
S : string;
begin
GroundTexBox.Items.Clear;
for x := 0 to GroundTex_No-1 do
begin
GroundTexBox.Items.Add(GroundTex_Textures[x].Name);
s := ansiuppercase(copy(GroundTex_Textures[x].Name,1,length('RA2_')));
IID := 0;
if copy(s,1,length('TS_')) = 'TS_' then
IID := 1
else if s = 'RA2_' then
IID := 2
else if copy(s,1,length('YR_')) = 'YR_' then
IID := 3;
GroundTexBox.ItemsEx.Items[GroundTexBox.Items.Count-1].ImageIndex := IID;
end;
GroundTexBox.ItemIndex := 0;//GroundTex1.Id;
GroundTexBoxChange(nil);
//TexListBuilt := true;
end;
procedure TVVFrmMain.GroundTexBoxChange(Sender: TObject);
begin
If VVSLoading then exit;
GroundTex.Id := GroundTexBox.ItemIndex;
GroundTex.Tex := GroundTex_Textures[GroundTex.Id].Tex;
XTexShift.Value := 0;
YTexShift.Value := 0;
VVSLoading := true; //Fake a VVS loading
TileGround := GroundTex_Textures[GroundTex.Id].Tile;
TileGroundCheckBox.Checked := GroundTex_Textures[GroundTex.Id].Tile;
VVSLoading := false;
FUpdateWorld := True;
end;
Procedure TVVFrmMain.BuildSkyTextureComboBox;
var
x : integer;
begin
SkyTextureComboBox.Clear;
for x := 0 to SkyTexList_no-1 do
SkyTextureComboBox.Items.Add(SkyTexList[x].Texture_Name);
SkyTextureComboBox.ItemIndex := 0;
end;
procedure TVVFrmMain.SkyTextureComboBoxChange(Sender: TObject);
begin
if VVSLoading then exit;
SkyTex := SkyTextureComboBox.ItemIndex;
VH_BuildSkyBox;
FUpdateWorld := True;
end;
procedure TVVFrmMain.SkyWidthSpinEditChange(Sender: TObject);
begin
if VVSLoading then exit;
if (SkyWidthSpinEdit.Text <> '') and (SkyWidthSpinEdit.Text <> ' ') then
try
SkySize.X := SkyWidthSpinEdit.Value;
VH_BuildSkyBox;
FUpdateWorld := True;
except
end;
end;
procedure TVVFrmMain.SkyHeightSpinEditChange(Sender: TObject);
begin
if VVSLoading then exit;
if (SkyHeightSpinEdit.Text <> '') and (SkyHeightSpinEdit.Text <> ' ') then
try
SkySize.Y := SkyHeightSpinEdit.Value;
VH_BuildSkyBox;
FUpdateWorld := True;
except
end;
end;
procedure TVVFrmMain.SkyLengthSpinEditChange(Sender: TObject);
begin
if VVSLoading then exit;
if (SkyLengthSpinEdit.Text <> '') and (SkyLengthSpinEdit.Text <> ' ') then
try
SkySize.Z := SkyLengthSpinEdit.Value;
VH_BuildSkyBox;
FUpdateWorld := True;
except
end;
end;
procedure TVVFrmMain.SkyZPosSpinEditChange(Sender: TObject);
begin
if VVSLoading then exit;
if (SkyZPosSpinEdit.Text <> '') and (SkyZPosSpinEdit.Text <> ' ') then
try
SkyPos.Z := SkyZPosSpinEdit.Value;
FUpdateWorld := True;
except
end;
end;
procedure TVVFrmMain.SkyYPosSpinEditChange(Sender: TObject);
begin
if VVSLoading then exit;
if (SkyYPosSpinEdit.Text <> '') and (SkyYPosSpinEdit.Text <> ' ') then
try
SkyPos.Y := SkyYPosSpinEdit.Value;
FUpdateWorld := True;
except
end;
end;
procedure TVVFrmMain.SkyXPosSpinEditChange(Sender: TObject);
begin
if VVSLoading then exit;
if (SkyXPosSpinEdit.Text <> '') and (SkyXPosSpinEdit.Text <> ' ') then
try
SkyPos.X := SkyXPosSpinEdit.Value;
FUpdateWorld := True;
except
end;
end;
procedure TVVFrmMain.DrawSkyCheckBoxClick(Sender: TObject);
begin
If VVSLoading then exit;
DrawSky := not DrawSky;
DrawSkyCheckBox.Checked := DrawSky;
FUpdateWorld := True;
end;
procedure TVVFrmMain.Disable3DView1Click(Sender: TObject);
begin
DrawVHWorld := not DrawVHWorld;
Disable3DView1.Checked := not DrawVHWorld;
If not DrawVHWorld then
MainView.Repaint;
FUpdateWorld := True;
end;
procedure TVVFrmMain.ColoursNormals1Click(Sender: TObject);
begin
SetSpectrum(True);
ColoursNormals1.Checked := true;
Normals1.Checked := false;
Colours1.Checked := false;
ColoursOnly := false;
RebuildLists := True;
FUpdateWorld := True;
end;
procedure TVVFrmMain.Colours1Click(Sender: TObject);
begin
SetSpectrum(True);
ColoursNormals1.Checked := false;
Normals1.Checked := false;
Colours1.Checked := true;
ColoursOnly := True;
RebuildLists := True;
FUpdateWorld := True;
end;
procedure TVVFrmMain.Normals1Click(Sender: TObject);
begin
SetSpectrum(False);
ColoursNormals1.Checked := false;
Normals1.Checked := true;
Colours1.Checked := false;
ColoursOnly := false;
RebuildLists := True;
FUpdateWorld := True;
end;
procedure TVVFrmMain.CameraManager1Click(Sender: TObject);
var
frm: TFrmCameraManager_New;
begin
frm:=TFrmCameraManager_New.Create(Self);
frm.Visible:=False;
Frm.Image1.Picture := TopBarImageHolder.Picture;
frm.XRot.Text := FloatToStr(XRot);
frm.YRot.Text := FloatToStr(YRot);
frm.Depth.Text := FloatToStr(Depth);
frm.TargetX.Text := FloatToStr(CameraCenter.X);
frm.TargetY.Text := FloatToStr(CameraCenter.Y);
frm.ShowModal;
frm.Close;
if Frm.O then
begin
XRot := StrToFloatDef(frm.XRot.Text,XRot);
YRot := StrToFloatDef(frm.YRot.Text,YRot);
Depth := StrToFloatDef(frm.Depth.Text,Depth);
CameraCenter.X := StrToFloatDef(frm.TargetX.Text,CameraCenter.X);
CameraCenter.Y := StrToFloatDef(frm.TargetY.Text,CameraCenter.Y);
end;
frm.Free;
end;
procedure TVVFrmMain.Help2Click(Sender: TObject);
begin
if not fileexists(extractfiledir(paramstr(0))+'/osvv_help.chm') then
begin
messagebox(0,'Help' + #13#13 + 'osvv_help.chm not found','Help',0);
exit;
end;
RunAProgram('osvv_help.chm','',extractfiledir(paramstr(0)));
end;
Procedure TVVFrmMain.ChangeView(Sender : TObject);
begin
VH_ChangeView(TMenuItem(Sender).Tag);
end;
procedure TVVFrmMain.ScreenShot1Click(Sender: TObject);
var
frm: TFrmScreenShotManager_New;
begin
frm:=TFrmScreenShotManager_New.Create(Self);
frm.Visible:=False;
Frm.Image1.Picture := TopBarImageHolder.Picture;
// Frm.Image1.Refresh;
If ScreenShot._Type = 0 then
frm.RadioButton1.Checked := True
else If ScreenShot._Type = 1 then
frm.RadioButton2.Checked := True
else
frm.RadioButton3.Checked := True;
frm.RadioButton1Click(Sender);
Frm.Compression.Position := ScreenShot.CompressionRate;
if ScreenShot.Width = -1 then
ScreenShot.Width := MainView.Width;
if ScreenShot.Height = -1 then
ScreenShot.Height := MainView.Height;
Frm.MainViewWidth.Value := Min(ScreenShot.Width,MainView.Width);
Frm.MainViewWidth.MaxValue := MainView.Width;
Frm.MainViewHeight.Value := Min(ScreenShot.Height,MainView.Height);
Frm.MainViewHeight.MaxValue := MainView.Height;
frm.ShowModal;
frm.Close;
if frm.O then
begin
MainView.Align := alNone;
ScreenShot.Width := Frm.MainViewWidth.Value;
ScreenShot.Height := Frm.MainViewHeight.Value;
MainView.Width := Frm.MainViewWidth.Value;
MainView.Height := Frm.MainViewHeight.Value;
If frm.RadioButton1.Checked then
ScreenShot._Type := 0
else If frm.RadioButton2.Checked then
ScreenShot._Type := 1
else
ScreenShot._Type := 2;
ScreenShot.CompressionRate := Frm.Compression.Position;
ScreenShot.Take := true;
end;
frm.Free;
end;
procedure TVVFrmMain.BackgroundColour1Click(Sender: TObject);
begin
ColorDialog.Color := TVector3fToTColor(BGColor);
if ColorDialog.Execute then
VH_SetBGColour(TColorToTVector3f(ColorDialog.Color));
FUpdateWorld := True;
end;
procedure TVVFrmMain.extColour1Click(Sender: TObject);
begin
ColorDialog.Color := TVector3fToTColor(FontColor);
if ColorDialog.Execute then
FontColor := TColorToTVector3f(ColorDialog.Color);
FUpdateWorld := True;
end;
procedure TVVFrmMain.CaptureAnimation1Click(Sender: TObject);
var
frm: TFrmAniamtionManager_New;
begin
frm:=TFrmAniamtionManager_New.Create(Self);
frm.Visible:=False;
Frm.Image1.Picture := TopBarImageHolder.Picture;
if ScreenShot.Width = -1 then
ScreenShot.Width := MainView.Width;
if ScreenShot.Height = -1 then
ScreenShot.Height := MainView.Height;
Frm.MainViewWidth.Value := ScreenShot.Width;
Frm.MainViewWidth.MaxValue := MainView.Width;
Frm.Frames.Enabled := false;
Frm.Label7.Enabled := false;
Frm.Label8.Enabled := false;
Frm.Label9.Enabled := false;
Frm.AnimateCheckBox.Enabled := false;
Frm.AnimateCheckBox.Checked := true;
frm.ShowModal;
frm.Close;
if frm.O then
begin
AnimationTimer.Enabled := false;
MainView.Align := alNone;
ScreenShot.Width := Frm.MainViewWidth.Value;
ScreenShot.Height := Frm.MainViewWidth.Value;
MainView.Width := Frm.MainViewWidth.Value;
MainView.Height := Frm.MainViewWidth.Value;
ScreenShot.CaptureAnimation := true;
ScreenShot.TakeAnimation := true;
AnimationBar.Position := 0;
AnimationBarChange(Sender);
SetCurrentFrame(0);
AnimationTimer.Enabled := true;
ClearRotationAdders;
GifAnimateBegin;
end;
frm.free;
end;
Procedure TVVFrmMain.ClearRotationAdders;
begin
btn3DRotateX2.Down := false;
btn3DRotateX.Down := false;
XRot2 := 0;
XRotB := false;
btn3DRotateY2.Down := false;
btn3DRotateY.Down := false;
YRot2 := 0;
YRotB := false;
end;
procedure TVVFrmMain.LoadScene1Click(Sender: TObject);
begin
if OpenVVSDialog.Execute then
begin
AnimationTimer.Enabled := false;
AnimationBar.Position := 0;
//AnimationBarChange(Sender);
HVAFrame := 0;
HVAFrameT := 0;
HVAFrameB := 0;
ClearRotationAdders;
VH_LoadVVS(OpenVVSDialog.FileName);
//Update Components on MainForm
VVSLoading := true;
GroundCheckBox.Checked := Ground_Tex_Draw;
TileGroundCheckBox.Checked := TileGround;
DrawTurretCheckBox.Checked := DrawTurret;
DrawBarrelCheckBox.Checked := DrawBarrel;
ShowDebugCheckBox.Checked := DebugMode;
VoxelCountCheckBox.Checked := ShowVoxelCount;
XTexShift.Value := trunc(TexShiftX);
YTexShift.Value := trunc(TexShiftY);
GroundSize.Value := trunc(GSize);
GroundHeightOffsetSpinEdit.Value := trunc(GroundHeightOffset);
//if VoxelFile.Section[0].Tailer.Unknown = 2 then
GroundTexBox.ItemIndex := GroundTex.ID;
{else
GroundTexBox.ItemIndex := GroundTex.ID; }
SkyTextureComboBox.ItemIndex := SkyTex;
SkyXPosSpinEdit.Value := trunc(SkyPos.X);
SkyYPosSpinEdit.Value := trunc(SkyPos.Y);
SkyZPosSpinEdit.Value := trunc(SkyPos.Z);
SkyWidthSpinEdit.Value := trunc(SkySize.X);
SkyHeightSpinEdit.Value := trunc(SkySize.Y);
SkyLengthSpinEdit.Value := trunc(SkySize.Z);
DrawSkyCheckBox.Checked := DrawSky;
CullFaceCheckBox.Checked := CullFace;
FOVEdit.Value := trunc(FOV);
VisibleDistEdit.Value := trunc(DEPTH_OF_VIEW);
RotationEdit.Text := floattostr(UnitRot);
AmbientRed.Value := Trunc(LightAmb.X*255);
AmbientGreen.Value := Trunc(LightAmb.Y*255);
AmbientBlue.Value := Trunc(LightAmb.Z*255);
DiffuseRed.Value := Trunc(LightDif.X*255);
DiffuseGreen.Value := Trunc(LightDif.Y*255);
DiffuseBlue.Value := Trunc(LightDif.Z*255);
LightGroundCheckBox.Checked := LightGround;
TurretRotationBar.Position := trunc(VXLTurretRotation.X);
VH_SetBGColour(BGColor);
Case Trunc(UnitCount) of
1 : UnitCountCombo.ItemIndex := 0;
4 : UnitCountCombo.ItemIndex := 1;
8 : UnitCountCombo.ItemIndex := 2;
end;
UnitSpaceEdit.Value := Trunc(UnitSpace);
VVSLoading := False;
end;
end;
procedure TVVFrmMain.SaveScene1Click(Sender: TObject);
begin
if SaveVVSDialog.Execute then
VH_SaveVVS(SaveVVSDialog.FileName);
end;
procedure TVVFrmMain.Make360DegreeAnimation1Click(Sender: TObject);
var
frm: TFrmAniamtionManager_New;
begin
frm:=TFrmAniamtionManager_New.Create(Self);
frm.Visible:=False;
Frm.Image1.Picture := TopBarImageHolder.Picture;
if ScreenShot.Width = -1 then
ScreenShot.Width := Min(MainView.Width,300);
if ScreenShot.Height = -1 then
ScreenShot.Height := Min(MainView.Width,300);
Frm.MainViewWidth.Value := Min(ScreenShot.Width,MainView.Width);
Frm.MainViewWidth.MaxValue := MainView.Width;
Frm.Frames.Value := ScreenShot.Frames;
{ Frm.Frames.Enabled := false;
Frm.Label2.Enabled := false;
Frm.Label4.Enabled := false;
Frm.Label7.Enabled := false; }
if not HVAOpen then
Frm.AnimateCheckBox.Enabled := false;
frm.ShowModal;
frm.Close;
if frm.O then
begin
MainView.Align := alNone;
ScreenShot.Width := Frm.MainViewWidth.Value;
ScreenShot.Height := Frm.MainViewWidth.Value;
MainView.Width := Frm.MainViewWidth.Value;
MainView.Height := Frm.MainViewWidth.Value;
ScreenShot.Frames := Frm.Frames.Value;
ScreenShot.FrameAdder := 360/ScreenShot.Frames;
ScreenShot.FrameCount := 0;
ScreenShot.OldYRot := YRot;
YRot := 0;
ScreenShot.Take360DAnimation := true;
if Frm.AnimateCheckBox.Checked then
begin
AnimationBar.Position := 0;
AnimationBarChange(Sender);
SetCurrentFrame(0);
AnimationTimer.Enabled := True;
end
else
AnimationTimer.Enabled := false;
ClearRotationAdders;
GifAnimateBegin;
end;
frm.free;
end;
procedure TVVFrmMain.AmbientRedChange(Sender: TObject);
begin
if (AmbientRed.Text <> '') and (AmbientRed.Text <> ' ') then
try
LightAmb.X := AmbientRed.Value/255;
except
end;
if LightGround then
FUpdateWorld := True;
end;
procedure TVVFrmMain.AmbientGreenChange(Sender: TObject);
begin
if (AmbientGreen.Text <> '') and (AmbientGreen.Text <> ' ') then
try
LightAmb.Y := AmbientGreen.Value/255;
except
end;
if LightGround then
FUpdateWorld := True;
end;
procedure TVVFrmMain.AmbientBlueChange(Sender: TObject);
begin
if (AmbientBlue.Text <> '') and (AmbientBlue.Text <> ' ') then
try
LightAmb.Z := AmbientBlue.Value/255;
except
end;
if LightGround then
FUpdateWorld := True;
end;
procedure TVVFrmMain.DiffuseRedChange(Sender: TObject);
begin
if (DiffuseRed.Text <> '') and (DiffuseRed.Text <> ' ') then
try
LightDif.X := DiffuseRed.Value/255;
except
end;
if LightGround then
FUpdateWorld := True;
end;
procedure TVVFrmMain.DiffuseGreenChange(Sender: TObject);
begin
if (DiffuseGreen.Text <> '') and (DiffuseGreen.Text <> ' ') then
try
LightDif.Y := DiffuseGreen.Value/255;
except
end;
if LightGround then
FUpdateWorld := True;
end;
procedure TVVFrmMain.DiffuseBlueChange(Sender: TObject);
begin
if (DiffuseBlue.Text <> '') and (DiffuseBlue.Text <> ' ') then
try
LightDif.Z := DiffuseBlue.Value/255;
except
end;
if LightGround then
FUpdateWorld := True;
end;
procedure TVVFrmMain.SpeedButton1Click(Sender: TObject);
begin
ColorDialog.Color := TVector4fToTColor(LightAmb);
if ColorDialog.Execute then
LightAmb := TColorToTVector4f(ColorDialog.Color);
AmbientRed.Value := Trunc(LightAmb.X*255);
AmbientGreen.Value := Trunc(LightAmb.Y*255);
AmbientBlue.Value := Trunc(LightAmb.Z*255);
end;
procedure TVVFrmMain.SpeedButton3Click(Sender: TObject);
begin
ColorDialog.Color := TVector4fToTColor(LightDif);
if ColorDialog.Execute then
LightDif := TColorToTVector4f(ColorDialog.Color);
DiffuseRed.Value := Trunc(LightDif.X*255);
DiffuseGreen.Value := Trunc(LightDif.Y*255);
DiffuseBlue.Value := Trunc(LightDif.Z*255);
end;
procedure TVVFrmMain.LightGroundCheckBoxClick(Sender: TObject);
begin
If VVSLoading then exit;
LightGround := Not LightGround;
LightGroundCheckBox.Checked := LightGround;
FUpdateWorld := True;
end;
procedure TVVFrmMain.TurretRotationBarChange(Sender: TObject);
begin
VXLTurretRotation.X := TurretRotationBar.Position;
FUpdateWorld := True;
end;
// Interpretates comunications from other programs
// Check SHP Builder project source (PostMessage commands)
procedure TVVFrmMain.CopyData(var Msg: TMessage);
var
cd: ^TCOPYDATASTRUCT;
p: pchar;
begin
cd:=Pointer(msg.lParam);
msg.result:=0;
if cd^.dwData=(12345234) then
begin
try
// showmessage('hi');
p:=cd^.lpData;
// showmessage(p);
p := pchar(copy(p,2,length(p)));
if Fileexists(p) then
begin
OpenVXLDialog.FileName := P;
LoadVoxel(OpenVXLDialog.FileName);
//If HVAOpen then
SetCaption(OpenVXLDialog.FileName);
SetupSections;
SectionBox.ItemIndex := 0;
SectionBoxChange(nil);
SetAnimFrom;
AnimFrom.ItemIndex := 0;
AnimFromChange(nil);
SetIsEditable;
If HVAOpen then
AnimationBar.Max := HVAFile.Header.N_Frames-1
else
AnimationBar.Max := 0;
lblHVAFrame.Caption := 'Frame ' + inttostr(GetCurrentFrame+1) + '/' + inttostr(GetCurrentHVA^.Header.N_Frames);
end;
{ process data }
msg.result:=-1;
except
end;
end;
end;
procedure TVVFrmMain.DebugVoxelBounds1Click(Sender: TObject);
var
SectionNum : integer;
Filename : string;
F : system.Text;
x,y,z,w : Double;
begin
if VoxelOpen then
begin
Filename := copy(VoxelFile.Filename,1,length(VoxelFile.Filename)-length('.vxl'));
if MessageBox(Application.Handle,PChar('Building ' + Filename + '_debug_bounds.txt. Go ahead?'),'Debug Voxel Bounds',MB_YESNO) = ID_YES then
begin
DecimalSeparator := '.';
AssignFile(F,Filename + '_debug_bounds.txt');
Rewrite(F);
writeln(F,VoxelFile.Filename + ' Report Starting...');
writeln(F);
writeln(F, 'Type: ' + VoxelFile.Header.FileType);
writeln(F, 'Unknown: ' + IntToStr(VoxelFile.Header.Unknown));
writeln(F, 'Num Sections: ' + IntToStr(VoxelFile.Header.NumSections));
writeln(F, 'Num Sections 2: ' + IntToStr(VoxelFile.Header.NumSections2));
writeln(F);
writeln(F);
// Print info from main body voxel and its sections.
for SectionNum := Low(VoxelFile.Section) to High(VoxelFile.Section) do
begin
writeln(F,'Starting section ' + IntToStr(SectionNum) + ':');
writeln(F);
writeln(F, 'Name: ' + VoxelFile.Section[SectionNum].Header.Name);
writeln(F, 'MinBounds: (' + FloatToStr(VoxelFile.Section[SectionNum].Tailer.MinBounds[1]) + '; ' + FloatToStr(VoxelFile.Section[SectionNum].Tailer.MinBounds[2]) + '; ' + FloatToStr(VoxelFile.Section[SectionNum].Tailer.MinBounds[3]) + ')');
writeln(F, 'MaxBounds: (' + FloatToStr(VoxelFile.Section[SectionNum].Tailer.MaxBounds[1]) + '; ' + FloatToStr(VoxelFile.Section[SectionNum].Tailer.MaxBounds[2]) + '; ' + FloatToStr(VoxelFile.Section[SectionNum].Tailer.MaxBounds[3]) + ')');
writeln(F, 'Unknown 1: ' + IntToStr(VoxelFile.Section[SectionNum].Header.Unknown1));
writeln(F, 'Unknown 2: ' + IntToStr(VoxelFile.Section[SectionNum].Header.Unknown2));
writeln(F, 'Number: ' + IntToStr(VoxelFile.Section[SectionNum].Header.Number));
writeln(F, 'Size X : ' + FloatToStr(VoxelFile.Section[SectionNum].Tailer.XSize));
writeln(F, 'Size Y : ' + FloatToStr(VoxelFile.Section[SectionNum].Tailer.YSize));
writeln(F, 'Size Z : ' + FloatToStr(VoxelFile.Section[SectionNum].Tailer.ZSize));
writeln(F, 'Det: (' + FloatToStr(VoxelFile.Section[SectionNum].Tailer.Det) + ')');
writeln(F);
writeln(F);
writeln(F,'Transformation Matrix: ');
writeln(F);
writeln(F, FloatToStrF(GetTMValue(HVAFile,1,1,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVAFile,1,2,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVAFile,1,3,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVAFile,1,4,SectionNum,1),ffFixed,15,17));
writeln(F, FloatToStrF(GetTMValue(HVAFile,2,1,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVAFile,2,2,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVAFile,2,3,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVAFile,2,4,SectionNum,1),ffFixed,15,17));
writeln(F, FloatToStrF(GetTMValue(HVAFile,3,1,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVAFile,3,2,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVAFile,3,3,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVAFile,3,4,SectionNum,1),ffFixed,15,17));
writeln(F, FloatToStrF(GetTMValue(HVAFile,4,1,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVAFile,4,2,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVAFile,4,3,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVAFile,4,4,SectionNum,1),ffFixed,15,17));
writeln(F);
writeln(F);
writeln(F);
writeln(F,'Transformation Calculations:');
writeln(F);
x := (VoxelFile.Section[SectionNum].Tailer.MinBounds[1] * GetTMValue(HVAFile,1,1,SectionNum,1)) + (VoxelFile.Section[SectionNum].Tailer.MinBounds[2] * GetTMValue(HVAFile,1,2,SectionNum,1)) + (VoxelFile.Section[SectionNum].Tailer.MinBounds[3] * GetTMValue(HVAFile,1,3,SectionNum,1)) + GetTMValue(HVAFile,1,4,SectionNum,1);
y := (VoxelFile.Section[SectionNum].Tailer.MinBounds[1] * GetTMValue(HVAFile,2,1,SectionNum,1)) + (VoxelFile.Section[SectionNum].Tailer.MinBounds[2] * GetTMValue(HVAFile,2,2,SectionNum,1)) + (VoxelFile.Section[SectionNum].Tailer.MinBounds[3] * GetTMValue(HVAFile,2,3,SectionNum,1)) + GetTMValue(HVAFile,2,4,SectionNum,1);
z := (VoxelFile.Section[SectionNum].Tailer.MinBounds[1] * GetTMValue(HVAFile,3,1,SectionNum,1)) + (VoxelFile.Section[SectionNum].Tailer.MinBounds[2] * GetTMValue(HVAFile,3,2,SectionNum,1)) + (VoxelFile.Section[SectionNum].Tailer.MinBounds[3] * GetTMValue(HVAFile,3,3,SectionNum,1)) + GetTMValue(HVAFile,3,4,SectionNum,1);
w := (VoxelFile.Section[SectionNum].Tailer.MinBounds[1] * GetTMValue(HVAFile,4,1,SectionNum,1)) + (VoxelFile.Section[SectionNum].Tailer.MinBounds[2] * GetTMValue(HVAFile,4,2,SectionNum,1)) + (VoxelFile.Section[SectionNum].Tailer.MinBounds[3] * GetTMValue(HVAFile,4,3,SectionNum,1)) + GetTMValue(HVAFile,4,4,SectionNum,1);
writeln(F, 'MinBounds: (' + FloatToStr(x) + ', ' + FloatToStr(y) + ', ' + FloatToStr(z) + ', ' + FloatToStr(w) + ')');
if (w <> 0) then
writeln(F, 'MinBounds Normalized: (' + FloatToStr(x/w) + ', ' + FloatToStr(y/w) + ', ' + FloatToStr(z/w) + ', ' + FloatToStr(w/w) + ')');
x := (VoxelFile.Section[SectionNum].Tailer.MaxBounds[1] * GetTMValue(HVAFile,1,1,SectionNum,1)) + (VoxelFile.Section[SectionNum].Tailer.MaxBounds[2] * GetTMValue(HVAFile,1,2,SectionNum,1)) + (VoxelFile.Section[SectionNum].Tailer.MaxBounds[3] * GetTMValue(HVAFile,1,3,SectionNum,1)) + GetTMValue(HVAFile,1,4,SectionNum,1);
y := (VoxelFile.Section[SectionNum].Tailer.MaxBounds[1] * GetTMValue(HVAFile,2,1,SectionNum,1)) + (VoxelFile.Section[SectionNum].Tailer.MaxBounds[2] * GetTMValue(HVAFile,2,2,SectionNum,1)) + (VoxelFile.Section[SectionNum].Tailer.MaxBounds[3] * GetTMValue(HVAFile,2,3,SectionNum,1)) + GetTMValue(HVAFile,2,4,SectionNum,1);
z := (VoxelFile.Section[SectionNum].Tailer.MaxBounds[1] * GetTMValue(HVAFile,3,1,SectionNum,1)) + (VoxelFile.Section[SectionNum].Tailer.MaxBounds[2] * GetTMValue(HVAFile,3,2,SectionNum,1)) + (VoxelFile.Section[SectionNum].Tailer.MaxBounds[3] * GetTMValue(HVAFile,3,3,SectionNum,1)) + GetTMValue(HVAFile,3,4,SectionNum,1);
w := (VoxelFile.Section[SectionNum].Tailer.MaxBounds[1] * GetTMValue(HVAFile,4,1,SectionNum,1)) + (VoxelFile.Section[SectionNum].Tailer.MaxBounds[2] * GetTMValue(HVAFile,4,2,SectionNum,1)) + (VoxelFile.Section[SectionNum].Tailer.MaxBounds[3] * GetTMValue(HVAFile,4,3,SectionNum,1)) + GetTMValue(HVAFile,4,4,SectionNum,1);
writeln(F, 'MaxBounds: (' + FloatToStr(x) + ', ' + FloatToStr(y) + ', ' + FloatToStr(z) + ', ' + FloatToStr(w) + ')');
if (w <> 0) then
writeln(F, 'MaxBounds Normalized: (' + FloatToStr(x/w) + ', ' + FloatToStr(y/w) + ', ' + FloatToStr(z/w) + ', ' + FloatToStr(w/w) + ')');
writeln(F);
writeln(F);
end;
writeln(F);
// Check for turret.
if VoxelOpenT then
begin
writeln(F,VoxelTurret.Filename + ' Report Starting...');
writeln(F);
writeln(F, 'Type: ' + VoxelTurret.Header.FileType);
writeln(F, 'Unknown: ' + IntToStr(VoxelTurret.Header.Unknown));
writeln(F, 'Num Sections: ' + IntToStr(VoxelTurret.Header.NumSections));
writeln(F, 'Num Sections 2: ' + IntToStr(VoxelTurret.Header.NumSections2));
writeln(F);
writeln(F);
for SectionNum := Low(VoxelTurret.Section) to High(VoxelTurret.Section) do
begin
writeln(F,'Starting section ' + IntToStr(SectionNum) + ':');
writeln(F);
writeln(F, 'Name: ' + VoxelTurret.Section[SectionNum].Header.Name);
writeln(F, 'MinBounds: (' + FloatToStr(VoxelTurret.Section[SectionNum].Tailer.MinBounds[1]) + ',' + FloatToStr(VoxelTurret.Section[SectionNum].Tailer.MinBounds[2]) + ',' + FloatToStr(VoxelTurret.Section[SectionNum].Tailer.MinBounds[3]) + ')');
writeln(F, 'MaxBounds: (' + FloatToStr(VoxelTurret.Section[SectionNum].Tailer.MaxBounds[1]) + ',' + FloatToStr(VoxelTurret.Section[SectionNum].Tailer.MaxBounds[2]) + ',' + FloatToStr(VoxelTurret.Section[SectionNum].Tailer.MaxBounds[3]) + ')');
writeln(F, 'Unknown 1: ' + IntToStr(VoxelTurret.Section[SectionNum].Header.Unknown1));
writeln(F, 'Unknown 2: ' + IntToStr(VoxelTurret.Section[SectionNum].Header.Unknown2));
writeln(F, 'Number: ' + IntToStr(VoxelTurret.Section[SectionNum].Header.Number));
writeln(F, 'Size X : ' + FloatToStr(VoxelTurret.Section[SectionNum].Tailer.XSize));
writeln(F, 'Size Y : ' + FloatToStr(VoxelTurret.Section[SectionNum].Tailer.YSize));
writeln(F, 'Size Z : ' + FloatToStr(VoxelTurret.Section[SectionNum].Tailer.ZSize));
writeln(F, 'Det: (' + FloatToStr(VoxelTurret.Section[SectionNum].Tailer.Det) + ')');
writeln(F);
writeln(F);
writeln(F,'Transformation Matrix: ');
writeln(F);
writeln(F, FloatToStrF(GetTMValue(HVATurret,1,1,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVATurret,1,2,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVATurret,1,3,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVATurret,1,4,SectionNum,1),ffFixed,15,17));
writeln(F, FloatToStrF(GetTMValue(HVATurret,2,1,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVATurret,2,2,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVATurret,2,3,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVATurret,2,4,SectionNum,1),ffFixed,15,17));
writeln(F, FloatToStrF(GetTMValue(HVATurret,3,1,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVATurret,3,2,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVATurret,3,3,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVATurret,3,4,SectionNum,1),ffFixed,15,17));
writeln(F, FloatToStrF(GetTMValue(HVATurret,4,1,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVATurret,4,2,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVATurret,4,3,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVATurret,4,4,SectionNum,1),ffFixed,15,17));
writeln(F);
writeln(F);
writeln(F);
writeln(F,'Transformation Calculations:');
writeln(F);
x := (VoxelTurret.Section[SectionNum].Tailer.MinBounds[1] * GetTMValue(HVATurret,1,1,SectionNum,1)) + (VoxelTurret.Section[SectionNum].Tailer.MinBounds[2] * GetTMValue(HVATurret,1,2,SectionNum,1)) + (VoxelTurret.Section[SectionNum].Tailer.MinBounds[3] * GetTMValue(HVATurret,1,3,SectionNum,1)) + GetTMValue(HVATurret,1,4,SectionNum,1);
y := (VoxelTurret.Section[SectionNum].Tailer.MinBounds[1] * GetTMValue(HVATurret,2,1,SectionNum,1)) + (VoxelTurret.Section[SectionNum].Tailer.MinBounds[2] * GetTMValue(HVATurret,2,2,SectionNum,1)) + (VoxelTurret.Section[SectionNum].Tailer.MinBounds[3] * GetTMValue(HVATurret,2,3,SectionNum,1)) + GetTMValue(HVATurret,2,4,SectionNum,1);
z := (VoxelTurret.Section[SectionNum].Tailer.MinBounds[1] * GetTMValue(HVATurret,3,1,SectionNum,1)) + (VoxelTurret.Section[SectionNum].Tailer.MinBounds[2] * GetTMValue(HVATurret,3,2,SectionNum,1)) + (VoxelTurret.Section[SectionNum].Tailer.MinBounds[3] * GetTMValue(HVATurret,3,3,SectionNum,1)) + GetTMValue(HVATurret,3,4,SectionNum,1);
w := (VoxelTurret.Section[SectionNum].Tailer.MinBounds[1] * GetTMValue(HVATurret,4,1,SectionNum,1)) + (VoxelTurret.Section[SectionNum].Tailer.MinBounds[2] * GetTMValue(HVATurret,4,2,SectionNum,1)) + (VoxelTurret.Section[SectionNum].Tailer.MinBounds[3] * GetTMValue(HVATurret,4,3,SectionNum,1)) + GetTMValue(HVATurret,4,4,SectionNum,1);
writeln(F, 'MinBounds: (' + FloatToStr(x) + ', ' + FloatToStr(y) + ', ' + FloatToStr(z) + ', ' + FloatToStr(w) + ')');
if (w <> 0) then
writeln(F, 'MinBounds Normalized: (' + FloatToStr(x/w) + ', ' + FloatToStr(y/w) + ', ' + FloatToStr(z/w) + ', ' + FloatToStr(w/w) + ')');
x := (VoxelTurret.Section[SectionNum].Tailer.MaxBounds[1] * GetTMValue(HVATurret,1,1,SectionNum,1)) + (VoxelTurret.Section[SectionNum].Tailer.MaxBounds[2] * GetTMValue(HVATurret,1,2,SectionNum,1)) + (VoxelTurret.Section[SectionNum].Tailer.MaxBounds[3] * GetTMValue(HVATurret,1,3,SectionNum,1)) + GetTMValue(HVATurret,1,4,SectionNum,1);
y := (VoxelTurret.Section[SectionNum].Tailer.MaxBounds[1] * GetTMValue(HVATurret,2,1,SectionNum,1)) + (VoxelTurret.Section[SectionNum].Tailer.MaxBounds[2] * GetTMValue(HVATurret,2,2,SectionNum,1)) + (VoxelTurret.Section[SectionNum].Tailer.MaxBounds[3] * GetTMValue(HVATurret,2,3,SectionNum,1)) + GetTMValue(HVATurret,2,4,SectionNum,1);
z := (VoxelTurret.Section[SectionNum].Tailer.MaxBounds[1] * GetTMValue(HVATurret,3,1,SectionNum,1)) + (VoxelTurret.Section[SectionNum].Tailer.MaxBounds[2] * GetTMValue(HVATurret,3,2,SectionNum,1)) + (VoxelTurret.Section[SectionNum].Tailer.MaxBounds[3] * GetTMValue(HVATurret,3,3,SectionNum,1)) + GetTMValue(HVATurret,3,4,SectionNum,1);
w := (VoxelTurret.Section[SectionNum].Tailer.MaxBounds[1] * GetTMValue(HVATurret,4,1,SectionNum,1)) + (VoxelTurret.Section[SectionNum].Tailer.MaxBounds[2] * GetTMValue(HVATurret,4,2,SectionNum,1)) + (VoxelTurret.Section[SectionNum].Tailer.MaxBounds[3] * GetTMValue(HVATurret,4,3,SectionNum,1)) + GetTMValue(HVATurret,4,4,SectionNum,1);
writeln(F, 'MaxBounds: (' + FloatToStr(x) + ', ' + FloatToStr(y) + ', ' + FloatToStr(z) + ', ' + FloatToStr(w) + ')');
if (w <> 0) then
writeln(F, 'MaxBounds Normalized: (' + FloatToStr(x/w) + ', ' + FloatToStr(y/w) + ', ' + FloatToStr(z/w) + ', ' + FloatToStr(w/w) + ')');
writeln(F);
writeln(F);
end;
writeln(F);
end;
// Check for barrel.
if VoxelOpenB then
begin
writeln(F,VoxelBarrel.Filename + ' Report Starting...');
writeln(F);
writeln(F, 'Type: ' + VoxelBarrel.Header.FileType);
writeln(F, 'Unknown: ' + IntToStr(VoxelBarrel.Header.Unknown));
writeln(F, 'Num Sections: ' + IntToStr(VoxelBarrel.Header.NumSections));
writeln(F, 'Num Sections 2: ' + IntToStr(VoxelBarrel.Header.NumSections2));
writeln(F);
writeln(F);
for SectionNum := Low(VoxelBarrel.Section) to High(VoxelBarrel.Section) do
begin
writeln(F,'Starting section ' + IntToStr(SectionNum) + ':');
writeln(F);
writeln(F, 'Name: ' + VoxelBarrel.Section[SectionNum].Header.Name);
writeln(F, 'MinBounds: (' + FloatToStr(VoxelBarrel.Section[SectionNum].Tailer.MinBounds[1]) + ',' + FloatToStr(VoxelBarrel.Section[SectionNum].Tailer.MinBounds[2]) + ',' + FloatToStr(VoxelBarrel.Section[SectionNum].Tailer.MinBounds[3]) + ')');
writeln(F, 'MaxBounds: (' + FloatToStr(VoxelBarrel.Section[SectionNum].Tailer.MaxBounds[1]) + ',' + FloatToStr(VoxelBarrel.Section[SectionNum].Tailer.MaxBounds[2]) + ',' + FloatToStr(VoxelBarrel.Section[SectionNum].Tailer.MaxBounds[3]) + ')');
writeln(F, 'Unknown 1: ' + IntToStr(VoxelBarrel.Section[SectionNum].Header.Unknown1));
writeln(F, 'Unknown 2: ' + IntToStr(VoxelBarrel.Section[SectionNum].Header.Unknown2));
writeln(F, 'Number: ' + IntToStr(VoxelBarrel.Section[SectionNum].Header.Number));
writeln(F, 'Size X : ' + FloatToStr(VoxelBarrel.Section[SectionNum].Tailer.XSize));
writeln(F, 'Size Y : ' + FloatToStr(VoxelBarrel.Section[SectionNum].Tailer.YSize));
writeln(F, 'Size Z : ' + FloatToStr(VoxelBarrel.Section[SectionNum].Tailer.ZSize));
writeln(F, 'Det: (' + FloatToStr(VoxelBarrel.Section[SectionNum].Tailer.Det) + ')');
writeln(F);
writeln(F);
writeln(F,'Transformation Matrix: ');
writeln(F);
writeln(F, FloatToStrF(GetTMValue(HVABarrel,1,1,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVABarrel,1,2,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVABarrel,1,3,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVABarrel,1,4,SectionNum,1),ffFixed,15,17));
writeln(F, FloatToStrF(GetTMValue(HVABarrel,2,1,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVABarrel,2,2,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVABarrel,2,3,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVABarrel,2,4,SectionNum,1),ffFixed,15,17));
writeln(F, FloatToStrF(GetTMValue(HVABarrel,3,1,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVABarrel,3,2,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVABarrel,3,3,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVABarrel,3,4,SectionNum,1),ffFixed,15,17));
writeln(F, FloatToStrF(GetTMValue(HVABarrel,4,1,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVABarrel,4,2,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVABarrel,4,3,SectionNum,1),ffFixed,15,17) + ' :: ' + FloatToStrF(GetTMValue(HVABarrel,4,4,SectionNum,1),ffFixed,15,17));
writeln(F);
writeln(F);
writeln(F);
writeln(F,'Transformation Calculations:');
writeln(F);
x := (VoxelBarrel.Section[SectionNum].Tailer.MinBounds[1] * GetTMValue(HVABarrel,1,1,SectionNum,1)) + (VoxelBarrel.Section[SectionNum].Tailer.MinBounds[2] * GetTMValue(HVABarrel,1,2,SectionNum,1)) + (VoxelBarrel.Section[SectionNum].Tailer.MinBounds[3] * GetTMValue(HVABarrel,1,3,SectionNum,1)) + GetTMValue(HVABarrel,1,4,SectionNum,1);
y := (VoxelBarrel.Section[SectionNum].Tailer.MinBounds[1] * GetTMValue(HVABarrel,2,1,SectionNum,1)) + (VoxelBarrel.Section[SectionNum].Tailer.MinBounds[2] * GetTMValue(HVABarrel,2,2,SectionNum,1)) + (VoxelBarrel.Section[SectionNum].Tailer.MinBounds[3] * GetTMValue(HVABarrel,2,3,SectionNum,1)) + GetTMValue(HVABarrel,2,4,SectionNum,1);
z := (VoxelBarrel.Section[SectionNum].Tailer.MinBounds[1] * GetTMValue(HVABarrel,3,1,SectionNum,1)) + (VoxelBarrel.Section[SectionNum].Tailer.MinBounds[2] * GetTMValue(HVABarrel,3,2,SectionNum,1)) + (VoxelBarrel.Section[SectionNum].Tailer.MinBounds[3] * GetTMValue(HVABarrel,3,3,SectionNum,1)) + GetTMValue(HVABarrel,3,4,SectionNum,1);
w := (VoxelBarrel.Section[SectionNum].Tailer.MinBounds[1] * GetTMValue(HVABarrel,4,1,SectionNum,1)) + (VoxelBarrel.Section[SectionNum].Tailer.MinBounds[2] * GetTMValue(HVABarrel,4,2,SectionNum,1)) + (VoxelBarrel.Section[SectionNum].Tailer.MinBounds[3] * GetTMValue(HVABarrel,4,3,SectionNum,1)) + GetTMValue(HVABarrel,4,4,SectionNum,1);
writeln(F, 'MinBounds: (' + FloatToStr(x) + ', ' + FloatToStr(y) + ', ' + FloatToStr(z) + ', ' + FloatToStr(w) + ')');
if (w <> 0) then
writeln(F, 'MinBounds Normalized: (' + FloatToStr(x/w) + ', ' + FloatToStr(y/w) + ', ' + FloatToStr(z/w) + ', ' + FloatToStr(w/w) + ')');
x := (VoxelBarrel.Section[SectionNum].Tailer.MaxBounds[1] * GetTMValue(HVABarrel,1,1,SectionNum,1)) + (VoxelBarrel.Section[SectionNum].Tailer.MaxBounds[2] * GetTMValue(HVABarrel,1,2,SectionNum,1)) + (VoxelBarrel.Section[SectionNum].Tailer.MaxBounds[3] * GetTMValue(HVABarrel,1,3,SectionNum,1)) + GetTMValue(HVABarrel,1,4,SectionNum,1);
y := (VoxelBarrel.Section[SectionNum].Tailer.MaxBounds[1] * GetTMValue(HVABarrel,2,1,SectionNum,1)) + (VoxelBarrel.Section[SectionNum].Tailer.MaxBounds[2] * GetTMValue(HVABarrel,2,2,SectionNum,1)) + (VoxelBarrel.Section[SectionNum].Tailer.MaxBounds[3] * GetTMValue(HVABarrel,2,3,SectionNum,1)) + GetTMValue(HVABarrel,2,4,SectionNum,1);
z := (VoxelBarrel.Section[SectionNum].Tailer.MaxBounds[1] * GetTMValue(HVABarrel,3,1,SectionNum,1)) + (VoxelBarrel.Section[SectionNum].Tailer.MaxBounds[2] * GetTMValue(HVABarrel,3,2,SectionNum,1)) + (VoxelBarrel.Section[SectionNum].Tailer.MaxBounds[3] * GetTMValue(HVABarrel,3,3,SectionNum,1)) + GetTMValue(HVABarrel,3,4,SectionNum,1);
w := (VoxelBarrel.Section[SectionNum].Tailer.MaxBounds[1] * GetTMValue(HVABarrel,4,1,SectionNum,1)) + (VoxelBarrel.Section[SectionNum].Tailer.MaxBounds[2] * GetTMValue(HVABarrel,4,2,SectionNum,1)) + (VoxelBarrel.Section[SectionNum].Tailer.MaxBounds[3] * GetTMValue(HVABarrel,4,3,SectionNum,1)) + GetTMValue(HVABarrel,4,4,SectionNum,1);
writeln(F, 'MaxBounds: (' + FloatToStr(x) + ', ' + FloatToStr(y) + ', ' + FloatToStr(z) + ', ' + FloatToStr(w) + ')');
if (w <> 0) then
writeln(F, 'MaxBounds Normalized: (' + FloatToStr(x/w) + ', ' + FloatToStr(y/w) + ', ' + FloatToStr(z/w) + ', ' + FloatToStr(w/w) + ')');
writeln(F);
writeln(F);
end;
writeln(F);
end;
CloseFile(F);
end;
end;
end;
procedure TVVFrmMain.MakeBZKUnit1Click(Sender: TObject);
procedure UnpackVoxel(PackedVoxel: TVoxelPacked; var dest: TVoxelUnpacked);
begin
dest.Normal := (PackedVoxel and $000000FF);
dest.Colour := (PackedVoxel and $0000FF00) shr 8;
dest.Used := (PackedVoxel and $00010000) > 0;
dest.Flags := (PackedVoxel and $FF000000) shr 24;
end;
// Make BZK Unit Starts here.
var
Filename : string;
F : system.Text;
x,y,z,i : Integer;
data : smallint;
Voxel : TVoxelUnpacked;
begin
if VoxelOpen then
begin
Filename := copy(VoxelFile.Filename,1,length(VoxelFile.Filename)-length('.vxl'));
if MessageBox(Application.Handle,PChar('Building ' + Filename + '.geo. Go ahead?'),'Debug Voxel Bounds',MB_YESNO) = ID_YES then
begin
AssignFile(F,Filename + '.geo');
Rewrite(F);
// Write number of colours
writeln(F, IntToStr(High(VXLPalette) + 1) );
// Write palette colours
for i := 0 to High(VXLPalette) do
begin
writeln(F, IntToStr(GetRValue(VXLPalette[i])));
writeln(F, IntToStr(GetGValue(VXLPalette[i])));
writeln(F, IntToStr(GetBValue(VXLPalette[i])));
writeln(F, '255'); // alpha
end;
// Write sector header.
// section size.
writeln(F, IntToStr(VoxelFile.Section[0].Tailer.XSize));
writeln(F, IntToStr(VoxelFile.Section[0].Tailer.YSize));
writeln(F, IntToStr(VoxelFile.Section[0].Tailer.ZSize));
// section scales.
writeln(F, IntToStr(Round((VoxelFile.Section[0].Tailer.MaxBounds[1]-VoxelFile.Section[0].Tailer.MinBounds[1])/VoxelFile.Section[0].Tailer.xSize)));
writeln(F, IntToStr(Round((VoxelFile.Section[0].Tailer.MaxBounds[2]-VoxelFile.Section[0].Tailer.MinBounds[2])/VoxelFile.Section[0].Tailer.ySize)));
writeln(F, IntToStr(Round((VoxelFile.Section[0].Tailer.MaxBounds[3]-VoxelFile.Section[0].Tailer.MinBounds[3])/VoxelFile.Section[0].Tailer.zSize)));
// Print each matrix.
for z := 0 to VoxelFile.Section[0].Tailer.ZSize-1 do
begin
writeln(F,IntToStr(z));
for y := 0 to VoxelFile.Section[0].Tailer.YSize-1 do
begin
// Write the first byte
UnpackVoxel(VoxelFile.Section[0].Data[0,y,z],Voxel);
if Voxel.Used then
data := Voxel.Colour
else
data := -1;
Write(F,IntToStr(data));
if VoxelFile.Section[0].Tailer.XSize > 1 then
begin
Write(F,' ');
// Write middle stuff
for x := 1 to VoxelFile.Section[0].Tailer.XSize-2 do
begin
UnpackVoxel(VoxelFile.Section[0].Data[x,y,z],Voxel);
if Voxel.Used then
data := Voxel.Colour
else
data := -1;
Write(F,IntToStr(data) + ' ');
end;
// Write the last element.
UnpackVoxel(VoxelFile.Section[0].Data[VoxelFile.Section[0].Tailer.XSize-1,y,z],Voxel);
if Voxel.Used then
data := Voxel.Colour
else
data := -1;
Writeln(F,IntToStr(data));
end;
end;
end;
CloseFile(F);
end;
end;
ShowMessage('Geo Unit Saved Successfully at ' + Filename + '.geo');
end;
procedure TVVFrmMain.GenerateSurface1Click(Sender: TObject);
var
Frm: TFrmSurfaces;
P1,P2,P3,P4 : TVector3i;
T1,T2,T3,T4 : TVector3f;
begin
// Here comes the code for the top secret surface generator.
Frm := TFrmSurfaces.Create(Self);
Frm.ShowModal;
if Frm.Changed then
begin
// Get points, starting with P1
P1.X := StrToIntDef(Frm.SpP1x.Text,0);
P1.Y := StrToIntDef(Frm.SpP1y.Text,0);
P1.Z := StrToIntDef(Frm.SpP1z.Text,0);
// P2
P2.X := StrToIntDef(Frm.SpP2x.Text,0);
P2.Y := StrToIntDef(Frm.SpP2y.Text,0);
P2.Z := StrToIntDef(Frm.SpP2z.Text,0);
// P3
P3.X := StrToIntDef(Frm.SpP3x.Text,0);
P3.Y := StrToIntDef(Frm.SpP3y.Text,0);
P3.Z := StrToIntDef(Frm.SpP3z.Text,0);
// P4
P4.X := StrToIntDef(Frm.SpP4x.Text,0);
P4.Y := StrToIntDef(Frm.SpP4y.Text,0);
P4.Z := StrToIntDef(Frm.SpP4z.Text,0);
// Get tangents, starting with T1
T1.X := StrToFloatDef(Frm.SpT1x.Text,0);
T1.Y := StrToFloatDef(Frm.SpT1y.Text,0);
T1.Z := StrToFloatDef(Frm.SpT1z.Text,0);
// T2
T2.X := StrToFloatDef(Frm.SpT2x.Text,0);
T2.Y := StrToFloatDef(Frm.SpT2y.Text,0);
T2.Z := StrToFloatDef(Frm.SpT2z.Text,0);
// T3
T3.X := StrToFloatDef(Frm.SpT3x.Text,0);
T3.Y := StrToFloatDef(Frm.SpT3y.Text,0);
T3.Z := StrToFloatDef(Frm.SpT3z.Text,0);
// T4
T4.X := StrToFloatDef(Frm.SpT4x.Text,0);
T4.Y := StrToFloatDef(Frm.SpT4y.Text,0);
T4.Z := StrToFloatDef(Frm.SpT4z.Text,0);
Surface(P1,P2,P3,T1,T2,T3,T4);
end;
Frm.Release;
end;
procedure TVVFrmMain.MakeGeoUnitwithPrecompiledLighting1Click(
Sender: TObject);
type
TGeoMap = array of array of array of Integer;
TCustomPalette = array of TColor;
procedure UnpackVoxel(PackedVoxel: TVoxelPacked; var dest: TVoxelUnpacked);
begin
dest.Normal := (PackedVoxel and $000000FF);
dest.Colour := (PackedVoxel and $0000FF00) shr 8;
dest.Used := (PackedVoxel and $00010000) > 0;
dest.Flags := (PackedVoxel and $FF000000) shr 24;
end;
function AddColourToPalette(Colour : TColor; var Palette : TCustomPalette): Integer;
var
i : integer;
found : boolean;
begin
found := false; // colour wasn't checked yet.
Result := -1;
// Check if it has elements
if High(Palette) > -1 then
begin
i := Low(Palette);
while (i <= High(Palette)) and (not found) do
begin
if Palette[i] = Colour then
begin
found := true;
Result := i;
end;
inc(i);
end;
end;
// If the colour isn't in the palette, add it.
if not found then
begin
SetLength(Palette,High(Palette)+2);
Palette[High(Palette)] := Colour;
Result := High(Palette);
end;
end;
// Make BZK Unit Starts here.
var
Filename : string;
F : system.Text;
x,y,z,i : Integer;
data : smallint;
Voxel : TVoxelUnpacked;
Palette : TCustomPalette;
GeoMap : TGeoMap;
AvarageNormal : Real;
begin
if VoxelOpen then
begin
Filename := copy(VoxelFile.Filename,1,length(VoxelFile.Filename)-length('.vxl'));
if MessageBox(Application.Handle,PChar('Building ' + Filename + '.geo. Go ahead?'),'Debug Voxel Bounds',MB_YESNO) = ID_YES then
begin
AssignFile(F,Filename + '.geo');
Rewrite(F);
// Generate GeoMap.
SetLength(GeoMap,VoxelFile.Section[0].Tailer.XSize,VoxelFile.Section[0].Tailer.YSize,VoxelFile.Section[0].Tailer.ZSize);
for x := 0 to VoxelFile.Section[0].Tailer.XSize-1 do
for y := 0 to VoxelFile.Section[0].Tailer.YSize-1 do
for z := 0 to VoxelFile.Section[0].Tailer.ZSize-1 do
begin
UnpackVoxel(VoxelFile.Section[0].Data[x,y,z],Voxel);
if Voxel.Used then
begin
if VoxelFile.Section[0].Tailer.Unknown = 4 then
begin
AvarageNormal := sqrt(((RA2Normals[Voxel.Normal].X * RA2Normals[Voxel.Normal].X) + (RA2Normals[Voxel.Normal].Y * RA2Normals[Voxel.Normal].Y) + (RA2Normals[Voxel.Normal].Z * RA2Normals[Voxel.Normal].Z)) / 3);
end
else
begin
AvarageNormal := sqrt(((TSNormals[Voxel.Normal].X * TSNormals[Voxel.Normal].X) + (TSNormals[Voxel.Normal].Y * TSNormals[Voxel.Normal].Y) + (TSNormals[Voxel.Normal].Z * TSNormals[Voxel.Normal].Z)) / 3);
end;
GeoMap[x,y,z] := AddColourToPalette(RGB(Round(GetRValue(VXLPalette[Voxel.Colour]) * AvarageNormal),Round(GetGValue(VXLPalette[Voxel.Colour]) * AvarageNormal),Round(GetBValue(VXLPalette[Voxel.Colour]) * AvarageNormal)),Palette);
end
else
GeoMap[x,y,z] := -1;
end;
// Write number of colours
writeln(F, IntToStr(High(Palette) + 1) );
// Write palette colours
for i := 0 to High(Palette) do
begin
writeln(F, IntToStr(GetRValue(Palette[i])));
writeln(F, IntToStr(GetGValue(Palette[i])));
writeln(F, IntToStr(GetBValue(Palette[i])));
writeln(F, '255'); // alpha
end;
// Write sector header.
// section size.
writeln(F, IntToStr(VoxelFile.Section[0].Tailer.XSize));
writeln(F, IntToStr(VoxelFile.Section[0].Tailer.YSize));
writeln(F, IntToStr(VoxelFile.Section[0].Tailer.ZSize));
// section scales.
writeln(F, IntToStr(Round((VoxelFile.Section[0].Tailer.MaxBounds[1]-VoxelFile.Section[0].Tailer.MinBounds[1])/VoxelFile.Section[0].Tailer.xSize)));
writeln(F, IntToStr(Round((VoxelFile.Section[0].Tailer.MaxBounds[2]-VoxelFile.Section[0].Tailer.MinBounds[2])/VoxelFile.Section[0].Tailer.ySize)));
writeln(F, IntToStr(Round((VoxelFile.Section[0].Tailer.MaxBounds[3]-VoxelFile.Section[0].Tailer.MinBounds[3])/VoxelFile.Section[0].Tailer.zSize)));
// Print each matrix.
for z := 0 to VoxelFile.Section[0].Tailer.ZSize-1 do
begin
writeln(F,IntToStr(z));
for y := 0 to VoxelFile.Section[0].Tailer.YSize-1 do
begin
// Write the first byte
Write(F,IntToStr(GeoMap[0,y,z]));
if VoxelFile.Section[0].Tailer.XSize > 1 then
begin
Write(F,' ');
// Write middle stuff
for x := 1 to VoxelFile.Section[0].Tailer.XSize-2 do
begin
Write(F,IntToStr(GeoMap[x,y,z]) + ' ');
end;
// Write the last element.
Writeln(F,IntToStr(GeoMap[VoxelFile.Section[0].Tailer.XSize-1,y,z]));
end;
end;
end;
CloseFile(F);
ShowMessage('Geo Unit Saved Successfully at ' + Filename + '.geo');
end;
end;
end;
procedure TVVFrmMain.OGLSizeChange(Sender: TObject);
begin
if AutoSizeCheck.Checked then exit;
MainView.Width := OGLSize.Value;
MainView.Height := OGLSize.Value;
end;
procedure TVVFrmMain.AutoSizeCheckClick(Sender: TObject);
begin
if AutoSizeCheck.Checked then
MainView.Align := alClient
else
begin
MainView.Align := alNone;
MainView.Width := OGLSize.Value;
MainView.Height := OGLSize.Value;
end;
FUpdateWorld := True;
end;
procedure TVVFrmMain.Timer1Timer(Sender: TObject);
begin
FUpdateWorld := True;
end;
procedure TVVFrmMain.UnitCountComboChange(Sender: TObject);
begin
Case UnitCountCombo.ItemIndex of
0 : UnitCount := 1;
1 : UnitCount := 4;
2 : UnitCount := 8;
end;
end;
procedure TVVFrmMain.UnitSpaceEditChange(Sender: TObject);
begin
If VVSLoading then exit;
if (UnitSpaceEdit.Text <> '') then
try
UnitSpace := UnitSpaceEdit.Value;
except
end;
FUpdateWorld := True;
end;
end.
|
unit uSubCalcSaleTax;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uParentSub, siComp, siLangRT, DB, ADODB, StdCtrls, ComCtrls;
type
TSubCalcSaleTax = class(TParentSub)
quGetSaleCharge: TADOQuery;
quGetSaleChargeTax: TBCDField;
quSaleTax: TADOQuery;
quSaleTaxTax: TBCDField;
quGetSaleChargeTaxCategory: TStringField;
quSaleTaxTaxCategory: TStringField;
quGetSaleChargeDebit: TBooleanField;
quSaleTaxDebit: TBooleanField;
TreeImpostos: TTreeView;
quGetSaleChargeParentTaxCategory: TStringField;
quGetSaleChargeParentTax: TBCDField;
private
{ Private declarations }
fIDGroup,
fIDStore : Integer;
fTotalPercent : Double;
procedure CalcTotals;
protected
procedure AfterSetParam; override;
function GiveInfo(InfoString: String): String; override;
public
{ Public declarations }
procedure DataSetRefresh;
procedure DataSetOpen; override;
procedure DataSetClose; override;
end;
implementation
uses uDM, uParamFunctions, uStringFunctions;
{$R *.dfm}
{ TSubCalcSaleTax }
procedure TSubCalcSaleTax.AfterSetParam;
begin
inherited;
fIDStore := StrToIntDef(ParseParam(FParam, 'IDStore'),0);
fIDGroup := StrToIntDef(ParseParam(FParam, 'IDGroup'),0);
if (fIDStore = 0) or (fIDGroup = 0) then
Exit;
DataSetRefresh;
end;
procedure TSubCalcSaleTax.CalcTotals;
var
sText : String;
NodeParent : TTreeNode;
begin
fTotalPercent := 0;
TreeImpostos.Items.Clear;
with quGetSaleCharge do
if Active then
begin
First;
sText := IncSpaces(quGetSaleChargeParentTaxCategory.AsString,28) + IncLeftSpaces(FormatFloat('0.00%',quGetSaleChargeParentTax.AsFloat),7);
NodeParent := TreeImpostos.Items.Add(nil,sText);
While not EOF do
begin
if quSaleTaxDebit.AsBoolean then
begin
sText := ' (-)';
fTotalPercent := fTotalPercent - quGetSaleChargeTax.AsFloat;
end
else
begin
sText := ' (+)';
fTotalPercent := fTotalPercent + quGetSaleChargeTax.AsFloat;
end;
sText := IncSpaces(quGetSaleChargeTaxCategory.AsString,24) + IncLeftSpaces(FormatFloat('0.00%',quGetSaleChargeTax.AsFloat),7) + sText;
TreeImpostos.Items.AddChild(NodeParent, sText);
Next;
end;
end;
with quSaleTax do
if Active then
begin
First;
While not EOF do
begin
if quSaleTaxDebit.AsBoolean then
begin
sText := ' (-)';
fTotalPercent := fTotalPercent - quSaleTaxTax.AsFloat;
end
else
begin
sText := ' (+)';
fTotalPercent := fTotalPercent + quSaleTaxTax.AsFloat;
end;
sText := IncSpaces(quSaleTaxTaxCategory.AsString,28) + IncLeftSpaces(FormatFloat('0.00%',quSaleTaxTax.AsFloat),7) + sText;
TreeImpostos.Items.Add(nil, sText);
Next;
end;
end;
sText := IncSpaces('Total',28) + IncLeftSpaces(FormatFloat('0.00%',fTotalPercent),7) + ' (=)';
TreeImpostos.Items.Add(nil, sText);
end;
procedure TSubCalcSaleTax.DataSetClose;
begin
inherited;
with quGetSaleCharge do
if Active then
Close;
with quSaleTax do
if Active then
Close;
end;
procedure TSubCalcSaleTax.DataSetOpen;
begin
inherited;
with quGetSaleCharge do
if not Active then
begin
Parameters.ParamByName('IDStore').Value := fIDStore;
Parameters.ParamByName('IDgroup').Value := fIDGroup;
Open;
end;
with quSaleTax do
if not Active then
begin
Parameters.ParamByName('IDStore').Value := fIDStore;
Parameters.ParamByName('IDgroup').Value := fIDGroup;
Open;
end;
CalcTotals;
end;
procedure TSubCalcSaleTax.DataSetRefresh;
begin
DataSetClose;
DataSetOpen;
end;
function TSubCalcSaleTax.GiveInfo(InfoString: String): String;
begin
Result := FloatToStr(fTotalPercent);
end;
initialization
RegisterClass(TSubCalcSaleTax);
end.
|
//////////////////////////////////////////////////////////////////////////
// This file is a part of NotLimited.Framework.Wpf 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.Globalization;
using System.Windows;
using System.Windows.Data;
namespace NotLimited.Framework.Wpf.Converters
{
[ValueConversion(typeof(bool), typeof(Visibility))]
public class BoolVisibilityConverter : IValueConverter
{
#region Implementation of IValueConverter
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool invert = parameter != null && System.Convert.ToBoolean(parameter);
if ((bool)value)
return invert ? Visibility.Collapsed : Visibility.Visible;
return invert ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
#endregion
}
} |
unit TurboDocumentHost;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,
aqDockingBase, aqDocking, aqDockingUtils, aqDockingUI,
TurboPhpDocument, Design, CodeEdit, ExtCtrls;
type
TTurboDocumentHostForm = class(TForm)
aqDockingSite1: TaqDockingSite;
aqDockingManager1: TaqDockingManager;
DesignDock: TaqDockingControl;
PhpDock: TaqDockingControl;
JavaScriptDock: TaqDockingControl;
PreviewDock: TaqDockingControl;
HtmlDock: TaqDockingControl;
ChangeTimer: TTimer;
procedure FormCreate(Sender: TObject);
procedure ChangeTimerTimer(Sender: TObject);
private
{ Private declarations }
FDocument: TTurboPhpDocument;
HtmlEditForm: TCodeEditForm;
JavaScriptEditForm: TCodeEditForm;
PhpEditForm: TCodeEditForm;
protected
function GetDesign: TDesignForm;
procedure DesignChange(inSender: TObject);
procedure DesignFilter(inSender, inObject: TObject;
var inFilter: Boolean);
procedure SetDocument(const Value: TTurboPhpDocument);
property Design: TDesignForm read GetDesign;
public
{ Public declarations }
procedure LazyUpdate;
procedure LoadDockConfig;
procedure SaveDockConfig;
property Document: TTurboPhpDocument read FDocument write SetDocument;
end;
var
TurboDocumentHostForm: TTurboDocumentHostForm;
implementation
uses
EasyStrings, LrUtils, Globals, DesignHost, DockingUtils,
Documents, DesignManager, BrowserView;
const
cDockConfig = 'aq.turbodock.cfg';
{$R *.dfm}
procedure TTurboDocumentHostForm.FormCreate(Sender: TObject);
begin
AddForm(DesignHostForm, TDesignHostForm, DesignDock);
//
AddForm(JavaScriptEditForm, TCodeEditForm, JavaScriptDock);
JavaScriptEditForm.Source.Parser := JavaScriptEditForm.JsParser;
//
AddForm(HtmlEditForm, TCodeEditForm, HtmlDock);
HtmlEditForm.Source.Parser := HtmlEditForm.HtmlParser;
HtmlEditForm.Edit.LineBreak := lbCR;
HtmlEditForm.Source.ReadOnly := true;
HtmlEditForm.SplitterPanel.Bars[0].Minimize;
//
AddForm(PhpEditForm, TCodeEditForm, PhpDock);
//
AddForm(BrowserForm, TBrowserForm, PreviewDock);
//
LoadDockConfig;
DesignDock.ForceVisible;
//
DesignMgr.PropertyObservers.Add(DesignChange);
DesignMgr.DesignObservers.Add(DesignChange);
//
//PreviewDock.MakeFloating(Rect(100, 100, 200, 200));
//HTMLDock.MakeFloating(Rect(100, 100, 200, 200));
end;
procedure TTurboDocumentHostForm.LoadDockConfig;
begin
LoadDockLayout(aqDockingManager1, ConfigHome + cDockConfig);
end;
procedure TTurboDocumentHostForm.SaveDockConfig;
begin
SaveDockLayout(aqDockingManager1, ConfigHome + cDockConfig);
end;
function TTurboDocumentHostForm.GetDesign: TDesignForm;
begin
Result := Document.DesignForm;
end;
procedure TTurboDocumentHostForm.DesignFilter(inSender, inObject: TObject;
var inFilter: Boolean);
begin
inFilter := (inObject.ClassName = 'TDesignController');
end;
procedure TTurboDocumentHostForm.SetDocument(const Value: TTurboPhpDocument);
begin
LazyUpdate;
FDocument := Value;
if Document <> nil then
begin
DesignHostForm.DesignForm := Design;
DesignMgr.OnFilter := DesignFilter;
DesignMgr.Container := Design;
//DesignMgr.Design := Design;
//DesignMgr.OnChange := Document.ModificationEvent; // DesignChange;
Design.Visible := true;
PhpEditForm.Strings := Document.Data.Php;
PhpEditForm.OnModified := Document.ModificationEvent;
JavaScriptEditForm.Strings := Document.Data.JavaScript;
JavaScriptEditForm.OnModified := Document.ModificationEvent;
BringToFront;
end
else begin
//DesignMgr.Design := nil;
DesignMgr.OnChange := nil;
DesignHostForm.DesignForm := nil;
end;
end;
procedure TTurboDocumentHostForm.LazyUpdate;
begin
if Document <> nil then
begin
Document.Data.Php.Assign(PhpEditForm.Strings);
Document.Data.JavaScript.Assign(JavaScriptEditForm.Strings);
end;
end;
procedure TTurboDocumentHostForm.DesignChange(inSender: TObject);
begin
if Document <> nil then
Document.Modified := true;
ChangeTimer.Enabled := false;
ChangeTimer.Enabled := true;
end;
procedure TTurboDocumentHostForm.ChangeTimerTimer(Sender: TObject);
begin
ChangeTimer.Enabled := false;
Document.GenerateHtml(HtmlEditForm.Strings);
end;
end.
|
unit eNota.Controller.Invoker;
interface
uses
eNota.Controller.NotaFiscal.Interfaces, System.Generics.Collections;
Type
TControllerInvoker = class(TInterfacedObject, iInvoker)
private
FLista : TList<iCommand>;
public
constructor Create;
destructor Destroy; override;
class function New : iInvoker;
function Add(Value : iCommand) : iInvoker;
function Execute : iInvoker;
end;
implementation
uses
System.SysUtils;
{ TControllerInvoker }
function TControllerInvoker.Add(Value: iCommand): iInvoker;
begin
Result := Self;
FLista.Add(Value);
end;
constructor TControllerInvoker.Create;
begin
FLista := TList<iCommand>.Create;
end;
destructor TControllerInvoker.Destroy;
begin
FreeAndNil(FLista);
inherited;
end;
function TControllerInvoker.Execute: iInvoker;
var
I: Integer;
begin
Result := Self;
for I := 0 to Pred(FLista.Count) do
FLista[I].Execute;
end;
class function TControllerInvoker.New: iInvoker;
begin
Result := Self.Create;
end;
end.
|
Unit ConnectorSelectionForm;
Interface
Uses
Windows, Messages, SysUtils,
Variants, Classes, Graphics,
Controls, Forms, Dialogs, ComCtrls, StdCtrls,
IRPMonDll;
Type
TConnectorSelectionFrm = Class(TForm)
PageControl1: TPageControl;
NoneTabSheet: TTabSheet;
DeviceTabSheet: TTabSheet;
NetworkTabSheet: TTabSheet;
OkButton: TButton;
StornoButton: TButton;
Label1: TLabel;
DeviceNameEdit: TEdit;
DomainLabel: TLabel;
PortLabel: TLabel;
NetworkDomainEdit: TEdit;
NetworkPortEdit: TEdit;
VSockVersionEdit: TEdit;
VSockAddressEdit: TEdit;
VSockVersionLabel: TLabel;
VSockAddressLabel: TLabel;
NetworkTypeComboBox: TComboBox;
HyperVVMIdEdit: TEdit;
HyperVAppIdEdit: TEdit;
HyperVVMLabel: TLabel;
HyperVAppLabel: TLabel;
procedure StornoButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure OkButtonClick(Sender: TObject);
procedure NetworkTypeComboBoxClick(Sender: TObject);
Private
FConnectionType : EIRPMonConnectorType;
FCancelled : Boolean;
FDeviceName : WideString;
FNetworkAddress : WideString;
FNetworkPort : WideString;
FVSockTargetAddress : Cardinal;
FVSockTargetPort : Cardinal;
FHyperVVMId : TGuid;
FHyperVAppId : TGuid;
Function IsWOW64:Boolean;
Public
Property Cancelled : Boolean Read FCancelled;
property ConnectionType : EIRPMonConnectorType Read FConnectionType;
Property DeviceName : WideString Read FDeviceName;
Property NetworkAddress : WideString Read FNetworkAddress;
Property NetworkPort : WideString Read FNetworkPort;
Property VSockTargetAddress : Cardinal Read FVSockTargetAddress;
Property VSockTargetPort : Cardinal Read FVSockTargetPort;
Property HyperVVMId : TGuid Read FHyperVVMId;
Property HyperVAppId : TGuid Read FHyperVAppId;
end;
Implementation
Uses
Utils,
VSockConnector;
{$R *.DFM}
{$IFDEF FPC}
Function IsWow64Process(hProcess:THandle; Var Wow64:LongBool):LongBool; StdCall; External 'kernel32.dll';
{$ENDIF}
Function TConnectorSelectionFrm.IsWOW64:Boolean;
Var
b : BOOL;
begin
Result := False;
If IsWow64Process(GetCurrentProcess, b) Then
Result := b;
end;
Procedure TConnectorSelectionFrm.NetworkTypeComboBoxClick(Sender: TObject);
begin
Case NetworkTypeComboBox.ItemIndex Of
0 : begin
DomainLabel.Caption := 'Domain/IP';
PortLabel.Caption := 'Port';
end;
1 : begin
DomainLabel.Caption := 'CID';
PortLabel.Caption := 'Port';
end;
2 : begin
DomainLabel.Caption := 'VM GUID';
PortLabel.Caption := 'App GUID';
end;
end;
end;
Procedure TConnectorSelectionFrm.FormCreate(Sender: TObject);
Var
vnciVersion : Cardinal;
vnciAddress : Cardinal;
begin
FCancelled := True;
If (IsWOW64) Or (Not IsAdmin) Then
begin
DeviceTabSheet.Enabled := False;
DeviceTabSheet.TabVisible := False;
end;
vnciVersion := VSockConn_VMCIVersion;
If vnciVersion <> VNCI_VERSION_INVALID Then
begin
vnciAddress := VSockConn_LocalId;
VSockVersionEdit.Text := Format('%u.%u', [vnciVersion And $FFFF, vnciVersion Shr 16]);
VSockAddressEdit.Text := Format('0x%x', [vnciAddress]);
end
Else begin
VSockVersionEdit.Text := '<not installed>';
VSockAddressEdit.Text := '<not installed>';
end;
end;
Procedure TConnectorSelectionFrm.OkButtonClick(Sender: TObject);
begin
FConnectionType := EIRPMonConnectorType(PageControl1.ActivePageIndex);
Case FConnectionType Of
ictNone: ;
ictDevice: FDeviceName := DeviceNameEdit.Text;
ictNetwork: begin
Case NetworkTypeComboBox.ItemIndex Of
0 : begin
FNetworkAddress := NetworkDomainEdit.Text;
FNetworkPort := NetworkPortEdit.Text;
end;
1 : begin
FConnectionType := ictVSockets;
FVSockTargetAddress := StrToUInt(NetworkDomainEdit.Text);
FVSockTargetPort := StrToUInt(NetworkPortEdit.Text);
end;
2 : begin
FConnectionType := ictHyperV;
FHyperVVMId := StringToGuid(NetworkDomainEdit.Text);
FHyperVAppId := StringToGuid(NetworkPortEdit.Text);
end;
end;
end;
end;
FCancelled := False;
Close;
end;
Procedure TConnectorSelectionFrm.StornoButtonClick(Sender: TObject);
begin
Close;
end;
End.
|
unit Odontologia.Modelo.Entidades.Medico;
interface
uses
SimpleAttributes;
Type
[Tabela('DMEDICO')]
TDMEDICO = class
private
FMED_COD_ESTADO : Integer;
FMED_CODIGO : Integer;
FMED_ESPECIALIDAD : String;
FMED_DOCUMENTO : String;
FMED_FOTO : String;
FMED_TELEFONO : String;
FMED_NOMBRE : String;
FMED_MATRICULA : String;
procedure SetMED_COD_ESTADO(const Value: Integer);
procedure SetMED_CODIGO(const Value: Integer);
procedure SetMED_DOCUMENTO(const Value: String);
procedure SetMED_ESPECIALIDAD(const Value: String);
procedure SetMED_MATRICULA(const Value: String);
procedure SetMED_NOMBRE(const Value: String);
procedure SetMED_FOTO(const Value: String);
procedure SetMED_TELEFONO(const Value: String);
published
[Campo('MED_CODIGO'), Pk, AutoInc]
property MED_CODIGO : Integer read FMED_CODIGO write SetMED_CODIGO;
[Campo('MED_NOMBRE')]
property MED_NOMBRE : String read FMED_NOMBRE write SetMED_NOMBRE;
[Campo('MED_DOCUMENTO')]
property MED_DOCUMENTO : String read FMED_DOCUMENTO write SetMED_DOCUMENTO;
[Campo('MED_MATRICULA')]
property MED_MATRICULA : String read FMED_MATRICULA write SetMED_MATRICULA;
[Campo('MED_TELEFONO')]
property MED_TELEFONO : String read FMED_TELEFONO write SetMED_TELEFONO;
[Campo('MED_ESPECIALIDAD')]
property MED_ESPECIALIDAD : String read FMED_ESPECIALIDAD write SetMED_ESPECIALIDAD;
[Campo('MED_COD_ESTADO')]
property MED_COD_ESTADO : Integer read FMED_COD_ESTADO write SetMED_COD_ESTADO;
[Campo('MED_FOTO')]
property MED_FOTO : String read FMED_FOTO write SetMED_FOTO;
end;
implementation
{ TDMEDICO }
procedure TDMEDICO.SetMED_CODIGO(const Value: Integer);
begin
FMED_CODIGO := Value;
end;
procedure TDMEDICO.SetMED_COD_ESTADO(const Value: Integer);
begin
FMED_COD_ESTADO := Value;
end;
procedure TDMEDICO.SetMED_DOCUMENTO(const Value: String);
begin
FMED_DOCUMENTO := Value;
end;
procedure TDMEDICO.SetMED_ESPECIALIDAD(const Value: String);
begin
FMED_ESPECIALIDAD := Value;
end;
procedure TDMEDICO.SetMED_MATRICULA(const Value: String);
begin
FMED_MATRICULA := Value;
end;
procedure TDMEDICO.SetMED_TELEFONO(const Value: String);
begin
FMED_TELEFONO := Value;
end;
procedure TDMEDICO.SetMED_NOMBRE(const Value: String);
begin
FMED_NOMBRE := Value;
end;
procedure TDMEDICO.SetMED_FOTO(const Value: String);
begin
FMED_FOTO := Value;
end;
end.
|
namespace proholz.xsdparser;
type
XsdParser = public class(XsdParserCore)
private
(**
* This function uses DOM to obtain a list of nodes from a XSD file.
* @param filePath The path to the XSD file.
* @throws IOException If the file parsing throws {@link IOException}.
* @throws ParserConfigurationException If the {@link DocumentBuilderFactory#newDocumentBuilder()} throws
* {@link ParserConfigurationException}.
* @return A list of nodes that represent the node tree of the XSD file with the path received.
*)
method getSchemaNode(filePath : String) : XmlElement ;
begin
var doc := XmlDocument.TryFromFile(filePath, true);
if assigned(doc.ErrorInfo) then
begin
// ToDo log the Error
raise new ParsingException(
$"Error in Parsing {filePath}
Line: {doc.ErrorInfo.Row} Col: {doc.ErrorInfo.Column}
{doc.ErrorInfo.Message}
");
end;
var node := doc.Root;//.Elements;
if (isXsdSchema(node)) then exit node;
raise new ParsingException("The top level element of a XSD file should be the xsd:schema node.");
end;
method parse(filePath : String);
begin
var basePath := Path.GetParentDirectory(filePath);
schemaLocations.Add(Path.GetFileName(filePath));
var index : Integer := 0;
while (schemaLocations.Count > index) do begin
var schemaLocation := schemaLocations.Item[index];
inc(index);
var filetoparse := Path.Combine(basePath, schemaLocation);
// if file.Exists(filetoparse) then
parseFile(filetoparse);
end;
resolveRefs();
end;
/**
* Parses a XSD file and all its containing XSD elements. This code iterates on the nodes and parses the supported
* ones. The supported types are all the XSD types that have their tag present in the {@link XsdParser#parseMappers}
* field.
* @param filePath The path to the XSD file.
*/
method parseFile(filePath : String);
begin
//https://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/
self.currentFile := filePath;
try
if not File.Exists(filePath) then
raise new FileNotFoundException(filePath);
var nodeToParse := getSchemaNode(filePath);
XsdSchema.parse(self, nodeToParse);
except
on e : ParsingException do
begin
writeLn(e.Message);
raise e;
end;
end;
end;
public
(**
* The XsdParser constructor will parse the XSD file with the {@code filepath} and will also parse all the subsequent
* XSD files with their path present in xsd:import and xsd:include tags. After parsing all the XSD files present it
* resolves the references existent in the XSD language, represented by the ref attribute. When this method finishes
* the parse results and remaining unsolved references are accessible by the {@link XsdParser#getResultXsdSchemas()},
* {@link XsdParser#getResultXsdElements()} and {@link XsdParser#getUnsolvedReferences()}.
* @param filePath States the path of the XSD file to be parsed.
*)
constructor(filePath : String);
begin
parse(filePath);
end;
(**
* The XsdParser constructor will parse the XSD file with the {@code filepath} and will also parse all the subsequent
* XSD files with their path present in xsd:import and xsd:include tags. After parsing all the XSD files present it
* resolves the references existent in the XSD language, represented by the ref attribute. When this method finishes
* the parse results and remaining unsolved references are accessible by the {@link XsdParser#getResultXsdSchemas()},
* {@link XsdParser#getResultXsdElements()} and {@link XsdParser#getUnsolvedReferences()}.
* @param filePath States the path of the XSD file to be parsed.
*)
constructor (filePath : String; config : ParserConfig);
begin
inherited constructor();
updateConfig(config);
parse(filePath);
end;
end;
end. |
(* Copyright 2018 B. Zoltán Gorza
*
* This file is part of Math is Fun!, released under the Modified BSD License.
*)
{ Statistics class and its supporting types. }
unit StatisticsClass;
{$mode objfpc}
{$H+}
interface
uses
OperationClass,
ExpressionClass;
type
{ Defines an Array of TExpression. }
TExpressionArray = Array of TExpression;
{ Operation Statistics Array, indexed by @link(TOp). }
TOpStatArray = Array[TOp] of Integer;
{ Operation Category Statistics Array,
indexed by @link(TOperationCategory). }
TOpCatStatArray = Array[TOperationCategory] of Integer;
{ Operation Statistics By Operation Category Array.}
TOpStatByCatArray = Array[TOperationCategory, TOp] of Integer;
{ Contains statistics of a series of @link(TExpression expressions) of a
single game.
It stores only an @link(TExpressionArray expression array), every
other value is processed, but not saved. It does NOT format any output,
that is up to the output functions!}
TStatistics = class
private
_expr: TExpressionArray;
function _lastExpression: TExpression;
function _correct: TOpStatArray;
function _wrong: TOpStatArray;
function _correctByCat: TOpCatStatArray;
function _wrongByCat: TOpCatStatArray;
function _numberOfOpByCat: TOpStatByCatArray;
function _number: TOpStatArray;
function _numberByCat: TOpCatStatArray;
public
{ }
property expressions: TExpressionArray read _expr;
{ The last expressions in the Expression array. }
property lastExpression: TExpression read _lastExpression;
{ List of @link(correct) answers by @link(TOp operation). }
property correct: TOpStatArray read _correct;
{ List of @link(incorrect wrong) answers by @link(TOp operation). }
property wrong: TOpStatArray read _wrong;
{ List of @link(correct) answers by @link(TOperationCategory category).}
property correctByCat: TOpCatStatArray read _correctByCat;
{ List of @link(incorrect) answers by
@link(TOperationCategory category). }
property wrongByCat: TOpCatStatArray read _wrongByCat;
{ Number of expressions by @link(TOperationCategory category) and
@link(TOp operation). }
property numberOfOpByCat: TOpStatByCatArray read _numberOfOpByCat;
{ Number of expressions by @link(TOp operation). }
property numberOfOp: TOpStatArray read _number;
{ Number of expressions by @link(TOperationCategory category). }
property numberByCat: TOpCatStatArray read _numberByCat;
{ Constructor. Simple, elegant, no parameters. }
constructor create;
{ Returns the length of @link(TExpression expressions) stored
in this class. }
function count: Integer;
{ Adds a new expression to the @link(TExpression expressions) stored in
this class.
@param(e Expression) }
procedure addExpression(const e: TExpression);
end;
implementation // --------------------------------------------------------------
constructor TStatistics.create;
begin
setLength(_expr, 0);
end;
function TStatistics._lastExpression: TExpression;
begin
_lastExpression := _expr[high(_expr)];
end;
function TStatistics._correct: TOpStatArray;
var
e: TExpression;
c: TOp;
begin
for c in TOp do
_correct[c] := 0;
for e in _expr do
begin
if resultToBoolean(e.isCorrect) then
_correct[e.o.op] += 1;
end;
end;
function TStatistics._wrong: TOpStatArray;
var
e: TExpression;
c: TOp;
begin
for c in TOp do
_wrong[c] := 0;
for e in _expr do
begin
if not resultToBoolean(e.isCorrect) then
_wrong[e.o.op] += 1;
end;
end;
function TStatistics._correctByCat: TOpCatStatArray;
var
e: TExpression;
c: TOperationCategory;
begin
for c in TOperationCategory do
_correctByCat[c] := 0;
for e in _expr do
begin
if resultToBoolean(e.isCorrect) then
_correctByCat[e.cat] += 1;
end;
end;
function TStatistics._wrongByCat: TOpCatStatArray;
var
e: TExpression;
c: TOperationCategory;
begin
for c in TOperationCategory do
_wrongByCat[c] := 0;
for e in _expr do
begin
if not resultToBoolean(e.isCorrect) then
_wrongByCat[e.cat] += 1;
end;
end;
function TStatistics._numberOfOpByCat: TOpStatByCatArray;
var
e: TExpression;
c: TOperationCategory;
cc: TOp;
begin
for c in TOperationCategory do
begin
for cc in TOp do
_numberOfOpByCat[c, cc] := 0;
end;
for e in _expr do
_numberOfOpByCat[e.cat, e.o.op] += 1;
end;
function TStatistics._number: TOpStatArray;
var
e: TExpression;
c: TOp;
begin
for c in TOp do
_number[c] := 0;
for e in _expr do
_number[e.o.op] += 1;
end;
function TStatistics._numberByCat: TOpCatStatArray;
var
e: TExpression;
c: TOperationCategory;
begin
for c in TOperationCategory do
_numberByCat[c] := 0;
for e in _expr do
_numberByCat[e.cat] += 1;
end;
function TStatistics.count: Integer;
begin
count := length(_expr);
end;
procedure TStatistics.addExpression(const e: TExpression);
var
oldLength: Integer;
begin
oldLength := length(_expr);
setLength(_expr, oldLength + 1);
_expr[oldLength] := e;
end;
end.
|
unit cn_History_Unit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, cxGraphics, cxCustomData, cxStyles, cxTL, cxTextEdit,
cxCalendar, cxCheckBox, cxInplaceContainer, cxDBTL, cxControls, cxTLData,
cxClasses, cxLookAndFeelPainters, cxButtons, ibase, DM, cxMaskEdit, cnConsts,
cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, Menus,
cxGridTableView, ImgList, dxBar, dxBarExtItems, cxGridLevel,
cxGridCustomTableView, cxGridDBTableView, cxGridCustomView, cxGrid,
dxStatusBar, cn_Common_Types, cn_Common_Loader,cn_Periods, cxCurrencyEdit,
Contract_Add_Edit, cxGroupBox,cxButtonEdit, cxRadioGroup,
cn_Common_Messages,cnConsts_Messages ,cn_ContractsLis;
type
TfrmHistory = class(TForm)
CancelButton: TcxButton;
Grid: TcxGrid;
grdHistory: TcxGridDBTableView;
GridLevel: TcxGridLevel;
BarManager: TdxBarManager;
AddButton: TdxBarLargeButton;
EditButton: TdxBarLargeButton;
DeleteButton: TdxBarLargeButton;
RefreshButton: TdxBarLargeButton;
ExitButton: TdxBarLargeButton;
SelectButton: TdxBarLargeButton;
PopupImageList: TImageList;
LargeImages: TImageList;
DisabledLargeImages: TImageList;
Styles: TcxStyleRepository;
BackGround: TcxStyle;
FocusedRecord: TcxStyle;
Header: TcxStyle;
DesabledRecord: TcxStyle;
cxStyle1: TcxStyle;
cxStyle2: TcxStyle;
cxStyle3: TcxStyle;
cxStyle4: TcxStyle;
cxStyle5: TcxStyle;
cxStyle6: TcxStyle;
cxStyle7: TcxStyle;
cxStyle8: TcxStyle;
cxStyle9: TcxStyle;
cxStyle10: TcxStyle;
cxStyle11: TcxStyle;
cxStyle12: TcxStyle;
cxStyle13: TcxStyle;
cxStyle14: TcxStyle;
cxStyle15: TcxStyle;
cxStyle16: TcxStyle;
Default_StyleSheet: TcxGridTableViewStyleSheet;
DevExpress_Style: TcxGridTableViewStyleSheet;
PopupMenu1: TPopupMenu;
AddPop: TMenuItem;
EditPop: TMenuItem;
DeletePop: TMenuItem;
RefreshPop: TMenuItem;
ExitPop: TMenuItem;
clmn_Fio: TcxGridDBColumn;
clmn_NumDog: TcxGridDBColumn;
clmn_DATE_DOG: TcxGridDBColumn;
clmn_DATE_BEG: TcxGridDBColumn;
clmn_DATE_END: TcxGridDBColumn;
clmn_DATE_DISS: TcxGridDBColumn;
clmn_USE_BEG: TcxGridDBColumn;
lrgbtnLog: TdxBarLargeButton;
lrgbtnRastReason: TdxBarLargeButton;
lrgbtnPeriods: TdxBarLargeButton;
btnViewDetails: TdxBarLargeButton;
btnSeparate: TdxBarLargeButton;
btnUnion: TdxBarLargeButton;
procedure CancelButtonClick(Sender: TObject);
procedure ExitButtonClick(Sender: TObject);
procedure lrgbtnLogClick(Sender: TObject);
procedure lrgbtnRastReasonClick(Sender: TObject);
procedure lrgbtnPeriodsClick(Sender: TObject);
procedure grdHistoryDblClick(Sender: TObject);
procedure btnViewDetailsClick(Sender: TObject);
procedure btnSeparateClick(Sender: TObject);
procedure btnUnionClick(Sender: TObject);
private
DM:TDM_Contracts;
LngIndex: Byte;
procedure FormIniLanguage(Lang : byte);
public
ID_User: Int64;
User_Name : string;
num_dog : string;
LModalResult : Integer;
is_admin:Boolean;
constructor Create(AOwner:TComponent; LanguageIndex : byte; DB_Handle:TISC_DB_HANDLE; ID_DOG_ROOT : int64;is_admin:Boolean);reintroduce;
end;
implementation
{$R *.dfm}
constructor TfrmHistory.Create(AOwner:TComponent; LanguageIndex : byte; DB_Handle:TISC_DB_HANDLE; ID_DOG_ROOT : int64; is_admin:boolean);
begin
Screen.Cursor:=crHourGlass;
inherited Create(AOwner);
Self.is_admin:=is_admin;
DM:=TDM_Contracts.Create(Self);
DM.DB.Handle:=DB_Handle;
DM.DataSet.SQLs.SelectSQL.clear;
DM.DataSet.SQLs.SelectSQL.Text := 'select * from CN_DT_DOG_ROOT_HISTORY_SELECT(' +
inttostr(ID_DOG_ROOT) + ')';
DM.DataSet.Open;
grdHistory.DataController.DataSource := DM.DataSource;
LngIndex := LanguageIndex;
FormIniLanguage(LanguageIndex);
Screen.Cursor:=crDefault;
end;
procedure TfrmHistory.FormIniLanguage(Lang : byte);
begin
Caption:= cnConsts.cn_History[Lang];
// Грид
clmn_Fio.Caption:= cnConsts.cn_grid_FIO_Column[Lang];
clmn_DATE_DOG.Caption:= cnConsts.cn_grid_Date_Dog_Column[Lang];
clmn_NumDog.Caption:= cnConsts.cn_grid_Num_Dog_Column[Lang];
clmn_DATE_BEG.Caption:= cnConsts.cn_grid_Date_Beg[Lang];
clmn_DATE_END.Caption:= cnConsts.cn_grid_Date_End[Lang];
clmn_DATE_DISS.Caption:= cnConsts.cn_DateDiss[Lang];
clmn_USE_BEG.Caption:= cnConsts.cn_Stamp[Lang];
//названия кнопок
AddButton.Caption := cnConsts.cn_InsertBtn_Caption[Lang];
EditButton.Caption := cnConsts.cn_EditBtn_Caption[Lang];
DeleteButton.Caption := cnConsts.cn_DeleteBtn_Caption[Lang];
RefreshButton.Caption := cnConsts.cn_RefreshBtn_Caption[Lang];
SelectButton.Caption := cnConsts.cn_SelectBtn_Caption[Lang];
ExitButton.Caption := cnConsts.cn_ExitBtn_Caption[Lang];
lrgbtnLog.Caption := cnConsts.cn_Log[Lang];
lrgbtnRastReason.Caption := cnConsts.cn_Pri4inaRastorg[Lang];
lrgbtnPeriods.Caption:= cnConsts.cn_Periods_GroupBox[Lang];
btnViewDetails.Caption := cnConsts.cn_ViewShort_Caption[Lang];
btnSeparate.Caption := cnConsts.cn_btnSeparate[Lang];
btnUnion.Caption := cnConsts.cn_btnUnion[Lang];
end;
procedure TfrmHistory.CancelButtonClick(Sender: TObject);
begin
close;
end;
procedure TfrmHistory.ExitButtonClick(Sender: TObject);
begin
Close;
end;
procedure TfrmHistory.lrgbtnLogClick(Sender: TObject);
var AParameter : TcnSimpleParamsEx;
begin
if grdHistory.DataController.RecordCount = 0 then exit;
AParameter:= TcnSimpleParamsEx.Create;
AParameter.Owner:=self;
AParameter.Db_Handle:= DM.DB.Handle;
AParameter.Formstyle:=fsNormal;
AParameter.cnParamsToPakage.ID_DOG_ROOT:= DM.Dataset['ID_DOG_ROOT'];
AParameter.cnParamsToPakage.ID_DOG:= DM.Dataset['ID_DOG_LAST'];
AParameter.cnParamsToPakage.ID_STUD:= DM.Dataset['ID_STUD'];
AParameter.WaitPakageOwner:= self;
RunFunctionFromPackage(AParameter, 'Contracts\cn_Log.bpl','ShowLog');
AParameter.Free;
Screen.Cursor := crDefault;
end;
procedure TfrmHistory.lrgbtnRastReasonClick(Sender: TObject);
var InParameter : TcnSimpleParamsEx;
locate: Integer;
begin
if grdHistory.DataController.RecordCount = 0 then exit;
if DM.DataSet['ISDISSDOG'] = 1 then
begin
locate:= DM.DataSet.RecNo;
InParameter:= TcnSimpleParamsEx.Create;
InParameter.Owner:=self;
InParameter.Db_Handle:= DM.DB.Handle;
InParameter.Formstyle:=fsNormal;
// InParameter.AMode := View;
InParameter.AMode := Edit;
InParameter.cnParamsToPakage.ID_DOG_ROOT := DM.Dataset['ID_DOG_ROOT'];
InParameter.cnParamsToPakage.ID_DOG := DM.Dataset['ID_DOG_LAST'];
InParameter.cnParamsToPakage.ID_STUD := DM.Dataset['ID_STUD'];
InParameter.cnParamsToPakage.FIO := DM.DataSet['FIO'];
InParameter.WaitPakageOwner:= self;
RunFunctionFromPackage(InParameter, 'Contracts\cn_dt_DissInfo.bpl','ShowDTDissInfo');
InParameter.Free;
Screen.Cursor := crDefault;
DM.DataSet.CloseOpen(true);
DM.DataSet.RecNo := locate;
end;
end;
procedure TfrmHistory.lrgbtnPeriodsClick(Sender: TObject);
var
ViewForm : TfrmPeriods;
ID_DOG_ROOT_Convert,ID_DOG_Convert: Int64;
i: Integer;
begin
// информация по периодам оплат
ViewForm := TfrmPeriods.Create(self);
ID_DOG_ROOT_Convert:= DM.Dataset['ID_DOG_ROOT'];
ID_DOG_Convert:= DM.Dataset['ID_DOG_LAST'];
ViewForm.Grid_payTableView.Columns[0].Caption:= cnConsts.cn_grid_Date_Beg[LngIndex];
ViewForm.Grid_payTableView.Columns[1].Caption:= cnConsts.cn_grid_Date_End[LngIndex];
ViewForm.Grid_payTableView.Columns[2].Caption:= cnConsts.cn_Date_Opl_Column[LngIndex];
ViewForm.Grid_payTableView.Columns[3].Caption:= cnConsts.cn_Summa_Column[LngIndex];
ViewForm.num_year.Caption:= cnConsts.cn_AcademYear[LngIndex];
ViewForm.Caption := lrgbtnPeriods.Caption;
DM.ReadDataSet.SelectSQL.Clear;
DM.ReadDataSet.SelectSQL.Text := 'select * from CN_DT_STAGE_OPL_SELECT(' + IntToStr(ID_DOG_ROOT_Convert) + ',' + IntToStr(ID_DOG_Convert) + ') order by DATE_BEG';
DM.ReadDataSet.Open;
DM.ReadDataSet.FetchAll;
DM.ReadDataSet.First;
for i:=0 to DM.ReadDataSet.RecordCount-1 do
begin
ViewForm.Grid_payTableView.DataController.RecordCount := ViewForm.Grid_payTableView.DataController.RecordCount + 1;
ViewForm.Grid_payTableView.DataController.Values[ViewForm.Grid_payTableView.DataController.RecordCount - 1, 0] := DM.ReadDataSet['DATE_BEG'];
ViewForm.Grid_payTableView.DataController.Values[ViewForm.Grid_payTableView.DataController.RecordCount - 1, 1] := DM.ReadDataSet['DATE_END'];
ViewForm.Grid_payTableView.DataController.Values[ViewForm.Grid_payTableView.DataController.RecordCount - 1, 2] := DM.ReadDataSet['DATE_PAY'];
ViewForm.Grid_payTableView.DataController.Values[ViewForm.Grid_payTableView.DataController.RecordCount - 1, 3] := DM.ReadDataSet['SUMMA'];
ViewForm.Grid_payTableView.DataController.Values[ViewForm.Grid_payTableView.DataController.RecordCount - 1, 4] := DM.ReadDataSet['ID_PAYER'];
ViewForm.Grid_payTableView.DataController.Values[ViewForm.Grid_payTableView.DataController.RecordCount - 1, 5] := DM.ReadDataSet['ID_MAN'];
ViewForm.Grid_payTableView.DataController.Values[ViewForm.Grid_payTableView.DataController.RecordCount - 1, 6] := DM.ReadDataSet['NUM_YEAR'];
DM.ReadDataSet.Next;
end;
DM.ReadDataSet.Close;
ViewForm.ShowModal;
end;
procedure TfrmHistory.grdHistoryDblClick(Sender: TObject);
begin
lrgbtnPeriodsClick(Sender);
end;
procedure EnableFormComponents(IsEnable: Boolean; Form : TForm);
var i: Integer;
begin
for i:=0 to Form.ComponentCount-1 do
begin
// if (Form.Components[i].ClassType=TcxGroupBox) then
// (Form.Components[i] as TcxGroupBox).Enabled :=IsEnable;
if (Form.Components[i].ClassType=TdxBarButton ) then
(Form.Components[i] as TdxBarButton).Enabled :=IsEnable;
if (Form.Components[i].ClassType=TcxButton) then
(Form.Components[i] as TcxButton).Enabled :=IsEnable;
if (Form.Components[i].ClassType=TcxTextEdit) then
(Form.Components[i] as TcxTextEdit).Properties.ReadOnly := not IsEnable;
if (Form.Components[i].ClassType=TcxDateEdit) then
(Form.Components[i] as TcxDateEdit).Properties.ReadOnly := not IsEnable;
if (Form.Components[i].ClassType=TcxButtonEdit) then
(Form.Components[i] as TcxButtonEdit).Enabled :=IsEnable;
if (Form.Components[i].ClassType=TcxRadioButton) then
(Form.Components[i] as TcxRadioButton).Enabled :=IsEnable;
end;
end;
procedure TfrmHistory.btnViewDetailsClick(Sender: TObject);
var ViewForm :Tfrm_Contracts_AE;
ID_RATE_ACCOUNT_Convert, ID_DOG_ROOT_Convert, ID_DOG_Convert: Int64;
i: Integer;
begin
ViewForm := Tfrm_Contracts_AE.Create(Self, LngIndex, DM.DB.Handle, 0, is_admin);
EnableFormComponents(False, ViewForm);
ViewForm.CancelButton.Enabled := True;
ViewForm.ComboPayersFilter.Enabled:= False;
ViewForm.Num_Dog_Edit.Text := DM.Dataset['NUM_DOG'];
ViewForm.Date_Zakl_DateEdit.Date := strtodate(DM.Dataset['DATE_DOG']);
if DM.Dataset['DATE_BEG'] <> null then
ViewForm.Date_Beg_DateEdit.Date := strtodate(DM.Dataset['DATE_BEG']);
if DM.Dataset['DATE_END'] <> null then
ViewForm.Date_End_DateEdit.Date := strtodate(DM.Dataset['DATE_END']);
ViewForm.Base_Dog_RadioButton.Visible := False;
ViewForm.Addit_Dog_RadioButton.Visible := False;
DM.ReadDataSet.Close;
DM.ReadDataSet.SelectSQL.Clear;
DM.ReadDataSet.SelectSQL.Text := 'select * from CN_GET_TYPEDOG_PARAMS_BY_ID(' + IntToStr(DM.Dataset['ID_TYPE_DOG']) + ')';
DM.ReadDataSet.Open;
if DM.ReadDataSet['CODENAME'] <> null then
ViewForm.TypeDogEdit.Text := DM.ReadDataSet['CODENAME'];
if DM.ReadDataSet['NAME'] <> null then
//ViewForm.NameTypeDogLabel.Caption := DM.ReadDataSet['NAME'];
ViewForm.ID_TYPE_DOG := DM.Dataset['ID_TYPE_DOG'];
DM.ReadDataSet.Close;
// rate_account
if DM.DataSet['ID_INT_ACCOUNT']<> null then
begin
DM.ReadDataSet.SelectSQL.Clear;
ID_RATE_ACCOUNT_Convert := DM.DataSet['ID_INT_ACCOUNT'];
DM.ReadDataSet.SelectSQL.Text := 'select * from CN_GET_RATEACC_BY_ID(' + IntToStr(ID_RATE_ACCOUNT_Convert) + ')';
DM.ReadDataSet.Open;
ViewForm.Accounts.Text := DM.ReadDataSet['RATE_ACCOUNT'];
ViewForm.ID_INT_Account := DM.DataSet['ID_INT_ACCOUNT'];
//ViewForm.Account_Label.Caption :=DM.ReadDataSet['NAME_MFO'];
DM.ReadDataSet.Close;
end;
// работает DM.ReadDataSet - забиваем гриды информацией
// информация по студенту
DM.ReadDataSet.SelectSQL.Clear;
ID_DOG_ROOT_Convert := DM.DataSet['ID_DOG_ROOT'];
ID_DOG_Convert := DM.DataSet['ID_DOG_LAST'];
DM.ReadDataSet.SelectSQL.Text := 'select * from CN_DT_ALL_STUDINFO_SELECT(' + IntToStr(ID_DOG_ROOT_Convert) + ',' + IntToStr(ID_DOG_Convert) + ')';
DM.ReadDataSet.Open;
DM.ReadDataSet.FetchAll;
DM.ReadDataSet.First;
for i:=0 to DM.ReadDataSet.RecordCount-1 do
begin
ViewForm.Grid_fioTableView.DataController.RecordCount := ViewForm.Grid_fioTableView.DataController.RecordCount + 1;
ViewForm.Grid_fioTableView.DataController.Values[ViewForm.Grid_fioTableView.DataController.RecordCount - 1, 0] := DM.ReadDataSet['FIO_PEOPLE'];
{ид_ман}
ViewForm.Grid_fioTableView.DataController.Values[ViewForm.Grid_fioTableView.DataController.RecordCount - 1, 17] := DM.ReadDataSet['ID_MAN'];
if DM.ReadDataSet['ID_MAN_PARENT'] <> null then
begin
ViewForm.Grid_fioTableView.DataController.Values[ViewForm.Grid_fioTableView.DataController.RecordCount - 1, 20] := DM.ReadDataSet['ID_MAN_PARENT'];
ViewForm.Grid_fioTableView.DataController.Values[ViewForm.Grid_fioTableView.DataController.RecordCount - 1, 21] := DM.ReadDataSet['FIO_PORUCHITEL'];
end;
{дата_начала} ViewForm.Grid_fioTableView.DataController.Values[ViewForm.Grid_fioTableView.DataController.RecordCount - 1, 1] := DM.ReadDataSet['DATE_BEG'];
{дата_конца} ViewForm.Grid_fioTableView.DataController.Values[ViewForm.Grid_fioTableView.DataController.RecordCount - 1, 2] := DM.ReadDataSet['DATE_END'];
{факультет} ViewForm.Grid_fioTableView.DataController.Values[ViewForm.Grid_fioTableView.DataController.RecordCount - 1, 3] := DM.ReadDataSet['NAME_FACUL'];
{специальность} ViewForm.Grid_fioTableView.DataController.Values[ViewForm.Grid_fioTableView.DataController.RecordCount - 1, 4] := DM.ReadDataSet['NAME_SPEC'];
{группа} ViewForm.Grid_fioTableView.DataController.Values[ViewForm.Grid_fioTableView.DataController.RecordCount - 1, 5] := DM.ReadDataSet['NAME_GROUP'];
{форма_обучения} ViewForm.Grid_fioTableView.DataController.Values[ViewForm.Grid_fioTableView.DataController.RecordCount - 1, 6] := DM.ReadDataSet['NAME_FORM_STUD'];
{категория_обучения} ViewForm.Grid_fioTableView.DataController.Values[ViewForm.Grid_fioTableView.DataController.RecordCount - 1, 7] := DM.ReadDataSet['NAME_KAT_STUD'];
{национальность} ViewForm.Grid_fioTableView.DataController.Values[ViewForm.Grid_fioTableView.DataController.RecordCount - 1, 8] := DM.ReadDataSet['NAME_NAZIONAL'];
{курс} ViewForm.Grid_fioTableView.DataController.Values[ViewForm.Grid_fioTableView.DataController.RecordCount - 1, 9] := DM.ReadDataSet['KURS'];
{сумма} ViewForm.Grid_fioTableView.DataController.Values[ViewForm.Grid_fioTableView.DataController.RecordCount - 1, 10] := DM.ReadDataSet['SUMMA_INF'];
{ид_факультета} ViewForm.Grid_fioTableView.DataController.Values[ViewForm.Grid_fioTableView.DataController.RecordCount - 1, 11] := DM.ReadDataSet['ID_FACUL'];
{ид_спец} ViewForm.Grid_fioTableView.DataController.Values[ViewForm.Grid_fioTableView.DataController.RecordCount - 1, 12] := DM.ReadDataSet['ID_SPEC'];
{ид_группы} ViewForm.Grid_fioTableView.DataController.Values[ViewForm.Grid_fioTableView.DataController.RecordCount - 1, 13] := DM.ReadDataSet['ID_GROUP'];
{ид_формыобуч} ViewForm.Grid_fioTableView.DataController.Values[ViewForm.Grid_fioTableView.DataController.RecordCount - 1, 14] := DM.ReadDataSet['ID_FORM_STUD'];
{ид_категоробуч} ViewForm.Grid_fioTableView.DataController.Values[ViewForm.Grid_fioTableView.DataController.RecordCount - 1, 15] := DM.ReadDataSet['ID_KAT_STUD'];
{ид_национал} ViewForm.Grid_fioTableView.DataController.Values[ViewForm.Grid_fioTableView.DataController.RecordCount - 1, 16] := DM.ReadDataSet['ID_NATIONAL'];
{ид_студ} ViewForm.Grid_fioTableView.DataController.Values[ViewForm.Grid_fioTableView.DataController.RecordCount - 1, 18] := DM.ReadDataSet['ID_STUD'];
{SUM_ENTRY_REST} ViewForm.Grid_fioTableView.DataController.Values[ViewForm.Grid_fioTableView.DataController.RecordCount - 1, 19] := DM.ReadDataSet['SUM_ENTRY_REST'];
DM.ReadDataSet.Next;
end;
DM.ReadDataSet.Close;
// информация по плательщикам
DM.ReadDataSet.SelectSQL.Clear;
ID_DOG_ROOT_Convert := DM.DataSet['ID_DOG_ROOT'];
ID_DOG_Convert := DM.DataSet['ID_DOG_LAST'];
DM.ReadDataSet.SelectSQL.Text := 'select * from CN_DT_PAYER_STAGE_SELECT(' + IntToStr(ID_DOG_ROOT_Convert) + ',' + IntToStr(ID_DOG_Convert) + ')';
DM.ReadDataSet.Open;
DM.ReadDataSet.FetchAll;
DM.ReadDataSet.First;
for i:=0 to DM.ReadDataSet.RecordCount-1 do
begin
ViewForm.Grid_payersTableView.DataController.RecordCount := ViewForm.Grid_payersTableView.DataController.RecordCount + 1;
ViewForm.Grid_payersTableView.DataController.Values[ViewForm.Grid_payersTableView.DataController.RecordCount - 1, 0] := DM.ReadDataSet['FIO_PAYER'];
ViewForm.Grid_payersTableView.DataController.Values[ViewForm.Grid_payersTableView.DataController.RecordCount - 1, 1] := DM.ReadDataSet['NAME_STAGE'];
ViewForm.Grid_payersTableView.DataController.Values[ViewForm.Grid_payersTableView.DataController.RecordCount - 1, 3] := DM.ReadDataSet['ID_TYPE_PAYER'];
ViewForm.Grid_payersTableView.DataController.Values[ViewForm.Grid_payersTableView.DataController.RecordCount - 1, 4] := DM.ReadDataSet['ID_TYPE_STAGE'];
ViewForm.Grid_payersTableView.DataController.Values[ViewForm.Grid_payersTableView.DataController.RecordCount - 1, 5] := DM.ReadDataSet['ISPERCENT'];
if DM.ReadDataSet['ISPERCENT'] =1 then
ViewForm.Grid_payersTableView.DataController.Values[ViewForm.Grid_payersTableView.DataController.RecordCount - 1, 2] := DM.ReadDataSet['PERSENT']
else
ViewForm.Grid_payersTableView.DataController.Values[ViewForm.Grid_payersTableView.DataController.RecordCount - 1, 2] := DM.ReadDataSet['SUMMA'];
ViewForm.Grid_payersTableView.DataController.Values[ViewForm.Grid_payersTableView.DataController.RecordCount - 1, 6] := DM.ReadDataSet['ID_PAYER'];
ViewForm.Grid_payersTableView.DataController.Values[ViewForm.Grid_payersTableView.DataController.RecordCount - 1, 7] := DM.ReadDataSet['ID_RATE_ACCOUNT'];
ViewForm.Grid_payersTableView.DataController.Values[ViewForm.Grid_payersTableView.DataController.RecordCount - 1, 8] := DM.ReadDataSet['MFO'];
ViewForm.Grid_payersTableView.DataController.Values[ViewForm.Grid_payersTableView.DataController.RecordCount - 1, 9] := DM.ReadDataSet['RATE_ACCOUNT'];
if DM.ReadDataSet['ID_CUST_MEN']<> null then
ViewForm.Grid_payersTableView.DataController.Values[ViewForm.Grid_payersTableView.DataController.RecordCount - 1, 10] := DM.ReadDataSet['ID_CUST_MEN'];
DM.ReadDataSet.Next;
end;
DM.ReadDataSet.Close;
// информация по сметам
DM.ReadDataSet.SelectSQL.Clear;
DM.ReadDataSet.SelectSQL.Text := 'select * from CN_DT_DOG_SMET_SELECT(' + IntToStr(ID_DOG_ROOT_Convert) + ',' + IntToStr(ID_DOG_Convert) + ')';
DM.ReadDataSet.Open;
DM.ReadDataSet.FetchAll;
DM.ReadDataSet.First;
for i:=0 to DM.ReadDataSet.RecordCount-1 do
begin
ViewForm.Grid_istochnikiTableView.DataController.RecordCount := ViewForm.Grid_istochnikiTableView.DataController.RecordCount + 1;
ViewForm.Grid_istochnikiTableView.DataController.Values[ViewForm.Grid_istochnikiTableView.DataController.RecordCount - 1, 0] := DM.ReadDataSet['KOD_SM'];
ViewForm.Grid_istochnikiTableView.DataController.Values[ViewForm.Grid_istochnikiTableView.DataController.RecordCount - 1, 1] := DM.ReadDataSet['KOD_RAZD'];
ViewForm.Grid_istochnikiTableView.DataController.Values[ViewForm.Grid_istochnikiTableView.DataController.RecordCount - 1, 2] := DM.ReadDataSet['KOD_ST'];
ViewForm.Grid_istochnikiTableView.DataController.Values[ViewForm.Grid_istochnikiTableView.DataController.RecordCount - 1, 3] := DM.ReadDataSet['KOD_KEKV'];
ViewForm.Grid_istochnikiTableView.DataController.Values[ViewForm.Grid_istochnikiTableView.DataController.RecordCount - 1, 4] := DM.ReadDataSet['PERSENT'];
ViewForm.Grid_istochnikiTableView.DataController.Values[ViewForm.Grid_istochnikiTableView.DataController.RecordCount - 1, 5] := DM.ReadDataSet['ID_SMET'];
ViewForm.Grid_istochnikiTableView.DataController.Values[ViewForm.Grid_istochnikiTableView.DataController.RecordCount - 1, 6] := DM.ReadDataSet['ID_RAZD'];
ViewForm.Grid_istochnikiTableView.DataController.Values[ViewForm.Grid_istochnikiTableView.DataController.RecordCount - 1, 7] := DM.ReadDataSet['ID_STAT'];
ViewForm.Grid_istochnikiTableView.DataController.Values[ViewForm.Grid_istochnikiTableView.DataController.RecordCount - 1, 8] := DM.ReadDataSet['ID_KEKV'];
ViewForm.Grid_istochnikiTableView.DataController.Values[ViewForm.Grid_istochnikiTableView.DataController.RecordCount - 1, 9] := DM.ReadDataSet['ID_MAN'];
DM.ReadDataSet.Next;
end;
DM.ReadDataSet.Close;
// информация по периодам оплат
DM.ReadDataSet.SelectSQL.Clear;
DM.ReadDataSet.SelectSQL.Text := 'select * from CN_DT_STAGE_OPL_SELECT(' + IntToStr(ID_DOG_ROOT_Convert) + ',' + IntToStr(ID_DOG_Convert) + ') order by DATE_BEG';
DM.ReadDataSet.Open;
DM.ReadDataSet.FetchAll;
DM.ReadDataSet.First;
for i:=0 to DM.ReadDataSet.RecordCount-1 do
begin
ViewForm.Grid_payTableView.DataController.RecordCount := ViewForm.Grid_payTableView.DataController.RecordCount + 1;
ViewForm.Grid_payTableView.DataController.Values[ViewForm.Grid_payTableView.DataController.RecordCount - 1, 0] := DM.ReadDataSet['DATE_BEG'];
ViewForm.Grid_payTableView.DataController.Values[ViewForm.Grid_payTableView.DataController.RecordCount - 1, 1] := DM.ReadDataSet['DATE_END'];
ViewForm.Grid_payTableView.DataController.Values[ViewForm.Grid_payTableView.DataController.RecordCount - 1, 2] := DM.ReadDataSet['DATE_PAY'];
ViewForm.Grid_payTableView.DataController.Values[ViewForm.Grid_payTableView.DataController.RecordCount - 1, 3] := DM.ReadDataSet['SUMMA'];
ViewForm.Grid_payTableView.DataController.Values[ViewForm.Grid_payTableView.DataController.RecordCount - 1, 4] := DM.ReadDataSet['ID_PAYER'];
ViewForm.Grid_payTableView.DataController.Values[ViewForm.Grid_payTableView.DataController.RecordCount - 1, 5] := DM.ReadDataSet['ID_MAN'];
ViewForm.Grid_payTableView.DataController.Values[ViewForm.Grid_payTableView.DataController.RecordCount - 1, 6] := DM.ReadDataSet['NUM_YEAR'];
DM.ReadDataSet.Next;
end;
DM.ReadDataSet.Close;
ViewForm.ShowModal;
end;
procedure TfrmHistory.btnSeparateClick(Sender: TObject);
var i: Integer;
DMl: TDM_Contracts;
ID_DOG_ROOT_NEW,ID_STUD_GEN : Int64;
begin
i:= cn_Common_Messages.cnShowMessage(cnConsts.cn_Confirmation_Caption[LngIndex], cnConsts_Messages.cn_warning_Execute[LngIndex], mtConfirmation, [mbYes, mbNo]);
if ((i = 7) or (i= 2)) then exit;
DMl:=TDM_Contracts.Create(Self);
DMl.DB.Handle:=DM.DB.Handle;
With DMl.StProc do
try
StoredProcName := 'CN_DT_DOG_ROOT_SEPARATE';
Transaction.StartTransaction;
Prepare;
ParamByName('ID_DOG_ROOT').AsInt64 := DM.Dataset['ID_DOG_ROOT'];
ParamByName('ID_DOG').AsInt64 := DM.Dataset['ID_DOG_LAST'];
ParamByName('ID_STUD').AsInt64 := DM.Dataset['ID_STUD'];
ExecProc;
ID_DOG_ROOT_NEW:=ParamByName('ID_DOG_ROOT_NEW').AsInt64;
ID_STUD_GEN:=ParamByName('ID_STUD_GEN').AsInt64;
// -----------логирование восстановления ------------------------------------
Dm.ReadDataSet.Close;
Dm.ReadDataSet.SelectSQL.Clear;
Dm.ReadDataSet.SelectSQL.Text := 'select * from CN_ACTION_GET_ID_BY_NAME(' + '''' + 'cn_Separate' + '''' + ')';
Dm.ReadDataSet.Open;
StoredProcName := 'CN_ACTION_HISTORY_INSERT';
Prepare;
ParamByName('ID_DOG_ROOT').AsInt64 := DM.Dataset['ID_DOG_ROOT'];
ParamByName('ID_DOG').AsInt64 := DM.DataSet['ID_DOG_LAST'];
ParamByName('ID_STUD').AsInt64 := DM.Dataset['ID_STUD'];
ParamByName('ID_USER').AsInt64 := ID_User;
ParamByName('USER_NAME').AsString := User_Name;
ParamByName('ID_ACTION').AsInt64 := Dm.ReadDataSet['ID_ACTION'];
ExecProc;
StoredProcName := 'CN_ACTION_HISTORY_INSERT';
Prepare;
ParamByName('ID_DOG_ROOT').AsInt64 := ID_DOG_ROOT_NEW;
ParamByName('ID_DOG').AsInt64 := DM.DataSet['ID_DOG_LAST'];
ParamByName('ID_STUD').AsInt64 := ID_STUD_GEN;
ParamByName('ID_USER').AsInt64 := ID_User;
ParamByName('USER_NAME').AsString := User_Name;
ParamByName('ID_ACTION').AsInt64 := Dm.ReadDataSet['ID_ACTION'];
ExecProc;
Dm.ReadDataSet.Close;
Transaction.Commit; // коммит общей транзакции
Dm.DataSet.CloseOpen(true);
except
Transaction.Rollback;
DMl.Free;
Dm.ReadDataSet.Close;
raise;
end;
end;
procedure TfrmHistory.btnUnionClick(Sender: TObject);
var ViewForm : TfrmContractsReestr;
var i: Integer;
DMl: TDM_Contracts;
id_dog_root_as_int,
id_dog_as_int,
id_stud_as_int,
id_dog_root_new_as_int,
id_dog_new_as_int,
id_stud_new_as_int : Int64;
begin
i:= cn_Common_Messages.cnShowMessage(cnConsts.cn_Confirmation_Caption[LngIndex], cnConsts_Messages.cn_warning_Execute[LngIndex], mtConfirmation, [mbYes, mbNo]);
if ((i = 7) or (i= 2)) then exit;
DMl:=TDM_Contracts.Create(Self);
DMl.DB.Handle:=DM.DB.Handle;
ViewForm := TfrmContractsReestr.Create(Self, DM.DB.Handle, LngIndex);
if ViewForm.ShowModal = mrok then
begin
With DMl.StProc do
try
StoredProcName := 'CN_DT_DOG_ROOT_UNION';
Transaction.StartTransaction;
Prepare;
id_dog_root_as_int := DM.Dataset['ID_DOG_ROOT'];
id_dog_as_int := DM.Dataset['ID_DOG_LAST'];
id_stud_as_int := DM.Dataset['ID_STUD'];
ParamByName('ID_DOG_ROOT_OLD').AsInt64 := id_dog_root_as_int;
ParamByName('ID_DOG_OLD').AsInt64 := id_dog_as_int;
ParamByName('ID_STUD_OLD').AsInt64 := id_stud_as_int;
id_dog_root_new_as_int := Res[0];
id_dog_new_as_int := Res[1];
id_stud_new_as_int := Res[2];
ParamByName('ID_DOG_ROOT_NEW').AsInt64 := id_dog_root_new_as_int;
ParamByName('ID_DOG_NEW').AsInt64 := id_dog_new_as_int;
ParamByName('ID_STUD_NEW').AsInt64 := id_stud_new_as_int;
ParamByName('DATE_BEG').AsDate := Res[3];
ExecProc;
DMl.ReadDataSet.Close;
DMl.ReadDataSet.SelectSQL.Clear;
DMl.ReadDataSet.SelectSQL.Text := 'select * from CN_ACTION_GET_ID_BY_NAME(' + '''' + 'cn_Union' + '''' + ')';
DMl.ReadDataSet.Open;
StoredProcName := 'CN_ACTION_HISTORY_INSERT';
Prepare;
ParamByName('ID_DOG_ROOT').AsInt64 := id_dog_root_as_int;
ParamByName('ID_DOG').AsInt64 := id_dog_as_int;
ParamByName('ID_STUD').AsInt64 := id_stud_as_int;
ParamByName('ID_USER').AsInt64 := ID_User;
ParamByName('USER_NAME').AsString := User_Name;
ParamByName('ID_ACTION').AsInt64 := DMl.ReadDataSet['ID_ACTION'];
ExecProc;
DMl.ReadDataSet.Close;
// -----------логирование ------------------------------------
// -----------логирование расторжения------------------------------------
DMl.ReadDataSet.Close;
DMl.ReadDataSet.SelectSQL.Clear;
DMl.ReadDataSet.SelectSQL.Text := 'select * from CN_ACTION_GET_ID_BY_NAME(' + '''' + 'cn_Rastorg' + '''' + ')';
DMl.ReadDataSet.Open;
StoredProcName := 'CN_ACTION_HISTORY_INSERT';
Prepare;
ParamByName('ID_DOG_ROOT').AsInt64 := id_dog_root_as_int;
ParamByName('ID_DOG').AsInt64 := id_dog_as_int;
ParamByName('ID_STUD').AsInt64 := id_stud_as_int;
ParamByName('ID_USER').AsInt64 := ID_User;
ParamByName('USER_NAME').AsString := User_Name;
ParamByName('ID_ACTION').AsInt64 := DMl.ReadDataSet['ID_ACTION'];
ExecProc;
DMl.ReadDataSet.Close;
// -----------логирование переоформления------------------------------------
DMl.ReadDataSet.Close;
DMl.ReadDataSet.SelectSQL.Clear;
DMl.ReadDataSet.SelectSQL.Text := 'select * from CN_ACTION_GET_ID_BY_NAME(' + '''' + 'cn_Pereoform' + '''' + ')';
DMl.ReadDataSet.Open;
StoredProcName := 'CN_ACTION_HISTORY_INSERT';
Prepare;
ParamByName('ID_DOG_ROOT').AsInt64 := id_dog_root_as_int;
ParamByName('ID_DOG').AsInt64 := id_dog_new_as_int;
ParamByName('ID_STUD').AsInt64 := id_stud_as_int;
ParamByName('ID_USER').AsInt64 := ID_User;
ParamByName('USER_NAME').AsString := User_Name;
ParamByName('ID_ACTION').AsInt64 := DMl.ReadDataSet['ID_ACTION'];
ExecProc;
DMl.ReadDataSet.Close;
DMl.ReadDataSet.Close;
DMl.ReadDataSet.SelectSQL.Clear;
DMl.ReadDataSet.SelectSQL.Text := 'select * from CN_ACTION_GET_ID_BY_NAME(' + '''' + 'cn_Union' + '''' + ')';
DMl.ReadDataSet.Open;
StoredProcName := 'CN_ACTION_HISTORY_INSERT';
Prepare;
ParamByName('ID_DOG_ROOT').AsInt64 := id_dog_root_as_int;
ParamByName('ID_DOG').AsInt64 := id_dog_new_as_int;
ParamByName('ID_STUD').AsInt64 := id_stud_as_int;
ParamByName('ID_USER').AsInt64 := ID_User;
ParamByName('USER_NAME').AsString := User_Name;
ParamByName('ID_ACTION').AsInt64 := DMl.ReadDataSet['ID_ACTION'];
ExecProc;
DMl.ReadDataSet.Close;
Transaction.Commit; // коммит общей транзакции
Dm.DataSet.CloseOpen(true);
LModalResult := 2225600;
num_dog := grdHistory.DataController.Values[0,1];
except
Transaction.Rollback;
DMl.Free;
Dm.ReadDataSet.Close;
raise;
end;
end;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
SoccerLabel: TLabel;
HockeyLabel: TLabel;
BasketballLabel: TLabel;
LanguageButton: TButton;
procedure FormCreate(Sender: TObject);
procedure LanguageButtonClick(Sender: TObject);
private
procedure UpdateValues;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
NtPattern, NtLanguageDlg;
procedure TForm1.UpdateValues;
procedure Process(const select: String; const name: String; messageLabel: TLabel);
resourcestring
// Contains three patterns: soccer, hockey and basketball.
SSportSelect = '{select, soccer {%s is the best soccer player.} hockey {%s is the best ice hockey player.} basketball {%s is the best basketball player.}}'; //loc 0: Name of the player
begin
messageLabel.Caption := TMultiPattern.Format(SSportSelect, select, [name]);
end;
begin
Process('soccer', 'Pelé', SoccerLabel);
Process('hockey', 'Wayne Gretzky', HockeyLabel);
Process('basketball', 'Michael Jordan', BasketBallLabel);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
UpdateValues;
end;
procedure TForm1.LanguageButtonClick(Sender: TObject);
begin
if TNtLanguageDialog.Select then
UpdateValues;
end;
end.
|
unit VH_Engine;
{
Title: Voxel HVA Engine
By: Stucuk
Note: This engine uses parts of OS HVA Builder and OS Voxel Viewer.
19 Oct 2005 - Revision by Stucuk
Improved rendering speed. VoxelBoxes revamped to do it by section.
Each section has its own OGL list so its only 'rendered' to the list once
and then called each time (so its faster). Also we now use the multimatrix
command so we don't need to apply the matrix each time to each box.
}
interface
Uses Windows,SysUtils,Controls,Classes,Graphics,JPEG,Palette,VH_Global,VH_GL,OpenGL15,VH_Voxel,
VH_Display,TimerUnit,FormProgress,Textures,Menus,Math3d,GifImage,VVS,Voxel,Undo_Engine,VH_Types,
HVA;
Function InitalizeVHE(const Location,Palette : String; SCREEN_WIDTH,SCREEN_HEIGHT : Integer; Handle : HWND; Depth : single) : Boolean;
Procedure VH_Draw;
Procedure VH_MouseDown(const Button: TMouseButton; X, Y: Integer);
Procedure VH_MouseUp;
Procedure VH_MouseMove(X,Y: Integer);
Procedure VH_LoadGroundTextures(); overload;
Procedure VH_LoadGroundTextures(const frm: TFrmProgress); overload;
Procedure VH_LoadGroundTextures(const _ext: string); overload;
Procedure VH_LoadSkyTextures(const frm: TFrmProgress);
Procedure VH_BuildSkyBox;
Procedure VH_SetSpectrum(Colours : Boolean);
Procedure VH_BuildViewMenu(Var View : TMenuItem; Proc : TNotifyEvent);
Procedure VH_ChangeView(x : integer);
Procedure VH_SetBGColour(BGColour : TVector3f);
procedure VH_ScreenShot(const Filename : string);
procedure VH_ScreenShotJPG(const Filename : string; Compression : integer);
procedure VH_ScreenShotGIF(const GIFIMAGE : TGIFImage; const Filename : string);
function VH_ScreenShot_BitmapResult : TBitmap;
procedure VH_ScreenShotToSHPBuilder;
Procedure VH_LoadVVS(const Filename : String);
Procedure VH_SaveVVS(const Filename : String);
Procedure VH_SaveVoxel(const Filename : String);
Procedure VH_LoadVoxel(const Filename : String);
Procedure VH_SaveHVA(const Filename : String);
Procedure VH_ResetUndoRedo;
Procedure VH_AddHVAToUndo(const HVA : PHVA; Frame,Section : Integer);
Procedure VH_ResetRedo;
Function VH_ISUndo : Boolean;
Function VH_ISRedo : Boolean;
Procedure VH_DoUndo;
Procedure VH_DoRedo;
Procedure VH_AddVOXELToUndo(const Voxel : PVoxel; Frame,Section : Integer);
Procedure LoadGroundTexture(const Dir,Ext : string; const frm: TFrmProgress); overload;
Procedure LoadGroundTexture(const Dir,Ext : string); overload;
implementation
uses registry,clipbrd;
Function InitalizeVHE(const Location,Palette : String; SCREEN_WIDTH,SCREEN_HEIGHT : Integer; Handle : HWND; Depth : single) : Boolean;
begin
Result := False;
VHLocation := Location;
DefaultDepth := Depth;
If not Fileexists(IncludeTrailingBackslash(Location) + Palette) then
begin
Messagebox(0,pchar('File Not Found: ' +#13+ IncludeTrailingBackslash(Location) + Palette),'File Missng',0);
exit;
end;
Try
LoadAPaletteFromFile(IncludeTrailingBackslash(Location) + Palette);
InitGL(Handle);
gTimer := TTimerSystem.Create;
gTimer.Refresh;
Except
Exit;
End;
Result := True;
end;
Procedure VH_Draw;
begin
If (not DrawVHWorld) or (not VoxelOpen) then Exit;
gTimer.Refresh;
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer
if XRotB then
begin
XRot := XRot + (XRot2 * 30) * gTimer.FrameTime;
FUpdateWorld := true;
end;
if YRotB then
begin
YRot := YRot + (YRot2 * 30) * gTimer.FrameTime;
FUpdateWorld := true;
end;
XRot := CleanAngle(XRot);
YRot := CleanAngle(YRot);
DrawWorld;
SwapBuffers(H_DC);
end;
Procedure VH_MouseDown(const Button: TMouseButton; X, Y: Integer);
begin
if (not VoxelOpen) {or (not MVEnabled)} then exit;
if Button = mbLeft then
begin
MouseButton :=1;
Xcoord := X;
Ycoord := Y;
end;
if Button = mbRight then
begin
MouseButton :=2;
Zcoord := Y;
Xcoord2 := X;
Ycoord2 := Y;
end;
end;
Procedure VH_MouseUp;
begin
if not VoxelOpen then exit;
MouseButton :=0;
end;
Procedure VH_MouseMove(X,Y: Integer);
begin
If MouseButton = 1 then
begin
FUpdateWorld := True;
if Axis = 2 then
begin
if VHControlType = CToffset then
begin
ChangeOffset(CurrentVoxel^,CurrentVoxelSection,(Y - Ycoord)/2,0,0);
Ycoord := Y;
VXLChanged := True;
end
else if VHControlType = CThvaposition then
begin
SetHVAPos(CurrentHVA^,CurrentVoxelSection,(Y - Ycoord)/2,0,0);
Ycoord := Y;
VXLChanged := True;
end
else if VHControlType = CThvarotation then
begin
SETHVAAngle(CurrentHVA^,CurrentVoxelSection,GetCurrentFrame,(Y - Ycoord)/2,0,0);
Ycoord := Y;
VXLChanged := True;
end;
end;
if Axis = 0 then
begin
if VHControlType = CToffset then
begin
ChangeOffset(CurrentVoxel^,CurrentVoxelSection,0,(Y - Ycoord)/2,0);
Ycoord := Y;
VXLChanged := True;
end
else if VHControlType = CThvaposition then
begin
SetHVAPos(CurrentHVA^,CurrentVoxelSection,0,(Y - Ycoord)/2,0);
Ycoord := Y;
VXLChanged := True;
end
else if VHControlType = CThvarotation then
begin
SETHVAAngle(CurrentHVA^,CurrentVoxelSection,GetCurrentFrame,0,(Y - Ycoord)/2,0);
Ycoord := Y;
VXLChanged := True;
end;
end;
if Axis = 1 then
begin
if VHControlType = CToffset then
begin
ChangeOffset(CurrentVoxel^,CurrentVoxelSection,0,0,-(Y - Ycoord)/2);
Ycoord := Y;
VXLChanged := True;
end
else if VHControlType = CThvaposition then
begin
SetHVAPos(CurrentHVA^,CurrentVoxelSection,0,0,-(Y - Ycoord)/2);
Ycoord := Y;
VXLChanged := True;
end
else if VHControlType = CThvarotation then
begin
SETHVAAngle(CurrentHVA^,CurrentVoxelSection,GetCurrentFrame,0,0,-(Y - Ycoord)/2);
Ycoord := Y;
VXLChanged := True;
end;
end;
if VHControlType = CTview then
begin
xRot := xRot + (Y - Ycoord)/2; // moving up and down = rot around X-axis
yRot := yRot + (X - Xcoord)/2;
Xcoord := X;
Ycoord := Y;
end;
end;
If MouseButton = 2 then
begin
FUpdateWorld := True;
if VHControlType = CTview then
begin
Depth :=Depth - (Y-ZCoord)/3;
Zcoord := Y;
end
else
begin
xRot := xRot + (Y - Ycoord2)/2; // moving up and down = rot around X-axis
yRot := yRot + (X - Xcoord2)/2;
Xcoord2 := X;
Ycoord2 := Y;
end;
end;
end;
Procedure LoadGroundTexture(const Dir,Ext : string);
var
f: TSearchRec;
path: String;
begin
path := Concat(Dir,'*'+Ext);
if FindFirst(path,faAnyFile,f) = 0 then
repeat
inc(GroundTex_No);
SetLength(GroundTex_Textures,GroundTex_No);
LoadTexture(Concat(Dir,f.Name),GroundTex_Textures[GroundTex_No-1].Tex,False,False,False);
GroundTex_Textures[GroundTex_No-1].Name := Copy(f.Name,1,length(f.Name)-length(Ext));
//showmessage('|' + ansilowercase(copy(GroundTex_Textures[GroundTex_No-1].Name,length(GroundTex_Textures[GroundTex_No-1].Name)-length('tile')+1,length(GroundTex_Textures[GroundTex_No-1].Name)))+'|');
if ansilowercase(copy(GroundTex_Textures[GroundTex_No-1].Name,length(GroundTex_Textures[GroundTex_No-1].Name)-length('tile')+1,length(GroundTex_Textures[GroundTex_No-1].Name))) = 'tile' then
GroundTex_Textures[GroundTex_No-1].Tile := true
else
GroundTex_Textures[GroundTex_No-1].Tile := false;
until FindNext(f) <> 0;
FindClose(f);
end;
Procedure LoadGroundTexture(const Dir,Ext : string; const frm: TFrmProgress);
var
f: TSearchRec;
path: String;
begin
path := Concat(Dir,'*'+Ext);
if FindFirst(path,faAnyFile,f) = 0 then
repeat
frm.UpdateAction('Ground: ' + f.Name);
frm.Refresh;
inc(GroundTex_No);
SetLength(GroundTex_Textures,GroundTex_No);
LoadTexture(Concat(Dir,f.Name),GroundTex_Textures[GroundTex_No-1].Tex,False,False,False);
GroundTex_Textures[GroundTex_No-1].Name := Copy(f.Name,1,length(f.Name)-length(Ext));
//showmessage('|' + ansilowercase(copy(GroundTex_Textures[GroundTex_No-1].Name,length(GroundTex_Textures[GroundTex_No-1].Name)-length('tile')+1,length(GroundTex_Textures[GroundTex_No-1].Name)))+'|');
if ansilowercase(copy(GroundTex_Textures[GroundTex_No-1].Name,length(GroundTex_Textures[GroundTex_No-1].Name)-length('tile')+1,length(GroundTex_Textures[GroundTex_No-1].Name))) = 'tile' then
GroundTex_Textures[GroundTex_No-1].Tile := true
else
GroundTex_Textures[GroundTex_No-1].Tile := false;
until FindNext(f) <> 0;
FindClose(f);
end;
Procedure VH_LoadGroundTextures();
begin
GroundTex_No := 0;
LoadGroundTexture(ExtractFileDir(ParamStr(0)) + '\Textures\Ground\','.jpg');
end;
Procedure VH_LoadGroundTextures(const frm: TFrmProgress);
begin
GroundTex_No := 0;
LoadGroundTexture(ExtractFileDir(ParamStr(0)) + '\Textures\Ground\','.jpg',frm);
end;
Procedure VH_LoadGroundTextures(const _ext: string);
begin
GroundTex_No := 0;
LoadGroundTexture(ExtractFileDir(ParamStr(0)) + '\Textures\Ground\',_ext);
end;
Procedure LoadSkyTexture2(const Ext, Fname, _type : string; id : integer);
var
Filename : string;
begin
Filename := copy(FName,1,length(Fname)-length(Ext)) + _type + copy(ext,length(ext)-length('_bk'),length(ext));
//SkyTexList[SkyTexList_No-1].Loaded := false;
//SkyTexList[SkyTexList_No-1].Filename[id] := Filename;
LoadTexture(Filename,SkyTexList[SkyTexList_No-1].Textures[id],False,False,False);
SkyTexList[SkyTexList_No-1].Texture_Name := extractfilename(Copy(Filename,1,length(Filename)-length(Ext)));
end;
Procedure LoadSkyTexture(const Dir,Ext : string; frm: TFrmProgress);
var
f: TSearchRec;
path: String;
begin
path := Concat(Dir,'*'+Ext);
if FindFirst(path,faAnyFile,f) = 0 then
repeat
inc(SkyTexList_No);
SetLength(SkyTexList,SkyTexList_No);
frm.UpdateAction('Sky: ' + f.Name);
frm.Refresh;
LoadSkyTexture2(Ext,Concat(Dir,f.Name),'_rt',0);
LoadSkyTexture2(Ext,Concat(Dir,f.Name),'_lf',1);
LoadSkyTexture2(Ext,Concat(Dir,f.Name),'_ft',2);
LoadSkyTexture2(Ext,Concat(Dir,f.Name),'_bk',3);
LoadSkyTexture2(Ext,Concat(Dir,f.Name),'_up',4);
LoadSkyTexture2(Ext,Concat(Dir,f.Name),'_dn',5);
until FindNext(f) <> 0;
FindClose(f);
end;
Procedure VH_LoadSkyTextures(const frm: TFrmProgress);
begin
SkyTexList_No := 0;
LoadSkyTexture(ExtractFileDir(ParamStr(0)) + '\Textures\Sky\','_bk.jpg',frm);
end;
Procedure VH_BuildSkyBox;
begin
BuildSkyBox;
end;
Procedure VH_SetSpectrum(Colours : Boolean);
begin
SetSpectrum(Colours);
end;
Procedure VH_ChangeView(x : integer);
begin
If (x > -1) and (x < VH_Views_No) then
begin
xRot := VH_Views[x].XRot;
If not VH_Views[x].NotUnitRot then
yRot := VH_Views[x].YRot-UnitRot
else
yRot := VH_Views[x].YRot;
If VH_Views[x].Depth < 0 then
Depth := VH_Views[x].Depth;
end;
end;
Procedure VH_BuildViewMenu(Var View : TMenuItem; Proc : TNotifyEvent);
var
Section,X : integer;
Item : TMenuItem;
begin
Section := 0;
For x := 0 to VH_Views_No-1 do
begin
if VH_Views[x].Section <> Section then
begin
item := TMenuItem.Create(View);
item.Caption := '-';
View.Add(item);
Section := VH_Views[x].Section;
end;
item := TMenuItem.Create(View);
item.Caption := VH_Views[x].Name;
item.Tag := x; // so we know which it is
item.OnClick := Proc;
View.Add(item);
end; // Loop End
end; // Procedure End
Procedure VH_SetBGColour(BGColour : TVector3f);
begin
BGColor := BGColour;
glClearColor(BGColor.X, BGColor.Y, BGColor.Z, 1.0);
end;
procedure VH_ScreenShot(const Filename : string);
var
i: integer;
t, FN, FN2, FN3 : string;
SSDir : string;
BMP : TBitmap;
begin
// create the scrnshots directory if it doesn't exist
SSDir := extractfiledir(Paramstr(0))+'\ScreenShots\';
FN2 := extractfilename(Filename);
FN2 := copy(FN2,1,length(FN2)-length(Extractfileext(FN2)));
ForceDirectories(SSDir);
FN := SSDir+FN2;
for i := 0 to 999 do
begin
t := inttostr(i);
if length(t) < 3 then
t := '00'+t
else if length(t) < 2 then
t := '0'+t;
if not fileexists(FN+'_'+t+'.bmp') then
begin
FN3 := FN+'_'+t+'.bmp';
break;
end;
end;
if FN3 = '' then
begin
exit;
end;
BMP := VH_ScreenShot_BitmapResult;
BMP.SaveToFile(FN3);
BMP.Free;
end;
procedure VH_ScreenShotToSHPBuilder;
var
Reg : TRegistry;
Path : String;
Version : String;
P : PChar;
BMP : TBitmap;
begin
Reg :=TRegistry.Create;
Reg.RootKey := HKEY_LOCAL_MACHINE;
if not Reg.OpenKey('\SOFTWARE\CnC Tools\OS SHP Builder\',false) then
begin
MessageBox(0,'Incorrect SHP Builder Version','Error',0);
exit;
end;
Version := Reg.ReadString('Version');
if Version < '3.36' then
begin
MessageBox(0,'Incorrect SHP Builder Version','Error',0);
exit;
end;
Path := Reg.ReadString('Path');
Reg.CloseKey;
Reg.Free;
BMP := VH_ScreenShot_BitmapResult;
Clipboard.Assign(BMP);
BMP.Free;
Path := Path + ' -Clipboard ' + inttostr(Screenshot.Width) + ' ' + inttostr(Screenshot.Height);
p:=PChar(Path);
WinExec(p,sw_ShowNormal);
end;
procedure VH_ScreenShotJPG(const Filename : string; Compression : integer);
var
i : integer;
t, FN, FN2, FN3 : string;
SSDir : string;
JPEGImage: TJPEGImage;
Bitmap : TBitmap;
begin
// create the scrnshots directory if it doesn't exist
SSDir := extractfiledir(Paramstr(0))+'\ScreenShots\';
FN2 := extractfilename(Filename);
FN2 := copy(FN2,1,length(FN2)-length(Extractfileext(FN2)));
ForceDirectories(SSDir);
FN := SSDir+FN2;
for i := 0 to 999 do
begin
t := inttostr(i);
if length(t) < 3 then
t := '00'+t
else if length(t) < 2 then
t := '0'+t;
if not fileexists(FN+'_'+t+'.jpg') then
begin
FN3 := FN+'_'+t+'.jpg';
break;
end;
end;
if FN3 = '' then
begin
exit;
end;
Bitmap := VH_ScreenShot_BitmapResult;
JPEGImage := TJPEGImage.Create;
JPEGImage.Assign(Bitmap);
JPEGImage.CompressionQuality := 100-Compression;
JPEGImage.SaveToFile(FN3);
Bitmap.Free;
JPEGImage.Free;
end;
procedure VH_ScreenShotGIF(const GIFIMAGE : TGIFImage; const Filename : string);
var
i : integer;
t, FN, FN2, FN3 : string;
SSDir : string;
begin
// create the scrnshots directory if it doesn't exist
SSDir := extractfiledir(Paramstr(0))+'\ScreenShots\';
FN2 := extractfilename(Filename);
FN2 := copy(FN2,1,length(FN2)-length(Extractfileext(FN2)));
ForceDirectories(SSDir);
FN := SSDir+FN2;
for i := 0 to 999 do
begin
t := inttostr(i);
if length(t) < 3 then
t := '00'+t
else if length(t) < 2 then
t := '0'+t;
if not fileexists(FN+'_'+t+'.gif') then
begin
FN3 := FN+'_'+t+'.gif';
break;
end;
end;
if FN3 = '' then
begin
exit;
end;
GIFImage.SaveToFile(FN3);
GIFImage.Free;
end;
function VH_ScreenShot_BitmapResult : TBitmap;
var
RGBBits : PRGBQuad;
Pixel : PRGBQuad;
BMP,
BMP2 : TBitmap;
x,y : Integer;
Temp : Byte;
AllWhite : Boolean;
begin
AllWhite := True;
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D,FTexture);
GetMem(RGBBits, GetPow2Size(SCREEN_WIDTH)*GetPow2Size(SCREEN_HEIGHT)*4);
glGetTexImage(GL_TEXTURE_2D,0,GL_RGBA,GL_UNSIGNED_BYTE, RGBBits);
glDisable(GL_TEXTURE_2D);
BMP := TBitmap.Create;
BMP.PixelFormat := pf32Bit;
BMP.Width := GetPow2Size(SCREEN_WIDTH);
BMP.Height := GetPow2Size(SCREEN_HEIGHT);
Pixel := RGBBits;
for y := 0 to GetPow2Size(SCREEN_HEIGHT)-1 do
for x := 0 to GetPow2Size(SCREEN_WIDTH)-1 do
begin
Temp := Pixel.rgbRed;
Pixel.rgbRed := Pixel.rgbBlue;
Pixel.rgbBlue := Temp;
Bmp.Canvas.Pixels[x,GetPow2Size(SCREEN_HEIGHT)-y-1] := RGB(Pixel.rgbRed,Pixel.rgbGreen,Pixel.rgbBlue);
if (Pixel.rgbRed <> 255) or (Pixel.rgbGreen <> 255) or (Pixel.rgbBlue <> 255) then
AllWhite := False;
// Pixel.rgbReserved := 0;
inc(Pixel);
end;
FreeMem(RGBBits);
BMP2 := TBitmap.Create;
BMP2.Width := SCREEN_WIDTH;
BMP2.Height := SCREEN_HEIGHT;
BMP2.Canvas.Draw(0,-(GetPow2Size(SCREEN_HEIGHT)-SCREEN_HEIGHT),BMP);
BMP.Free;
if AllWhite then
begin
BMP2.Free;
Result := VH_ScreenShot_BitmapResult;
end
else
Result := BMP2;
end;
Procedure VH_LoadVVS(const Filename : String);
begin
LoadVVS(Filename);
FUpdateWorld := True;
end;
Procedure VH_SaveVVS(const Filename : String);
begin
SaveVVS(Filename);
end;
Procedure VH_LoadVoxel(const Filename : String);
begin
LoadVoxel(Filename);
FUpdateWorld := True;
end;
Procedure SaveVoxel(const Vxl : TVoxel; const Filename,Ext : String);
var
TFilename : string;
begin
TFilename := extractfiledir(Filename) + '\' + copy(Extractfilename(Filename),1,Length(Extractfilename(Filename))-Length('.vxl')) + Ext;
Vxl.SaveToFile(TFilename);
end;
Procedure VH_SaveVoxel(const Filename : String);
begin
VXLChanged := False;
SaveVoxel(VoxelFile,Filename,'.vxl');
if VoxelOpenT then
SaveVoxel(VoxelTurret,Filename,'tur.vxl');
if VoxelOpenB then
SaveVoxel(VoxelBarrel,Filename,'barl.vxl');
end;
Procedure VH_SaveHVA(const Filename : String);
begin
SaveHVA(Filename);
end;
Procedure VH_ResetUndoRedo;
begin
ResetUndoRedo;
end;
Procedure VH_AddHVAToUndo(const HVA : PHVA; Frame,Section : Integer);
begin
AddHVAToUndo(HVA,Frame,Section);
end;
Procedure VH_ResetRedo;
begin
ResetRedo;
end;
Function VH_ISUndo : Boolean;
begin
Result := ISUndo;
end;
Function VH_ISRedo : Boolean;
begin
Result := ISRedo;
end;
Procedure VH_DoUndo;
begin
DoUndo;
end;
Procedure VH_DoRedo;
begin
DoRedo;
end;
Procedure VH_AddVOXELToUndo(const Voxel : PVoxel; Frame,Section : Integer);
begin
AddVOXELToUndo(Voxel,Frame,Section);
end;
end.
|
{De N productos de “Precios Cuidados”, se tienen los nombres y los respectivos
precios.
Por otro lado hay datos del precio de venta de dichos productos en M comercios
Ejemplo N=5 y M=4
*Producto PrecioCuidado Comercios
Fideos 25 30 32 22 40
Azúcar 10 15 18 16 19
Café 75 74 97 80 81
Dulce 22 25 33 28 34
Arroz 18 20 17 16 23
Se pide, ingresar la información en estructuras de vector/es y matriz/ces, según
corresponda, calcular e informar:
a) Para cada producto indicar la diferencia entre el promedio de venta (en los M
comercios) y el establecido en precios cuidados
b) Para cada comercio, cuántos son los productos que respetan el precio cuidado (el
precio debe ser menor o igual al establecido en PreciosCuidados)
c) Dado un producto X, verificar si al menos uno de los M comercios lo respeta.
Respuestas:
a) Fideos 124/4=31
Azucar 68/4=17
café 332/4=83
dulce 120/4=30
Arroz 76/4=19
b) Comercio 1: 0 - 2: 1 - 3:2 - 4:0
c) X= Café Si
X= Azúcar No }
Program TipoParcial3;
Type
St6 = string[6];
TM = array[1..100, 1..100] of word;
TVPre = array[1..100] of real;
TVProd = array[1..100] of St6;
Procedure LeerArchivo(Var Com:TM; Var Pre:TVPre; Var Prod:TVProd; Var N,M:byte);
Var
i,j:byte;
arch:text;
begin
assign(arch,'TipoParcial3.txt');reset(arch);
read(arch,N);
readln(arch,M);
For i:= 1 to N do
begin
read(arch,Prod[i]);
read(arch,Pre[i]);
For j:= 1 to M do
read(arch,Com[i,j]);
readln(arch);
end;
close(arch);
end;
Procedure Diferencia(Com:TM; Pre:TVPre; Prod:TVProd; N,M:byte); //Resuelve A.
Var
i,j:byte;
Acum:word;
begin
For i:= 1 to N do
begin
Acum:= 0;
For j:= 1 to M do
Acum:= Acum + Com[i,j];
writeln('A- Promedio de venta para ',Prod[i],' es: $',Acum/M:2:0);
writeln(' La diferencia entre el precio cuidado y el promedio de venta es de: $',(Acum/M) - Pre[i]:2:0);
writeln;
end;
end;
Procedure Respeta(Com:TM; Pre:TVPre; Prod:TVProd; N,M:byte);
Var
i,j,Cont:byte;
begin
write('B - ');
For j:= 1 to M do
begin
Cont:= 0;
For i:= 1 to N do
If (Com[i,j] <= Pre[i]) then
Cont:= Cont + 1;
If (j = M) then
writeln('Comercio ',j,' :',Cont)
Else
write('Comercio ',j,' :',Cont,' - ');
end;
end;
Procedure Verifica(Com:TM; Pre:TVPre; Prod:TVProd; N,M:byte);
Var
Encuentra,j,X:byte;
begin
Encuentra:= 0;
write('Ingrese un numero del 1 al ',N,' : ');readln(X);
For j:= 1 to M do
If (Com[X,j] <= Pre[x]) then
Encuentra:= 1;
If (Encuentra = 1) then
writeln('C- ',Prod[x],': Si se respeta el precio al menos una vez')
Else
writeln('C- ',Prod[x],': No se respeta el precio');
end;
Var
Com:TM;
Pre:TVPre;
Prod:TVProd;
N,M:byte;
Begin
LeerArchivo(Com,Pre,Prod,N,M);
Diferencia(Com,Pre,Prod,N,M);
Respeta(Com,Pre,Prod,N,M);
writeln;
Verifica(Com,Pre,Prod,N,M);
end.
|
{..............................................................................}
{ Summary Swaps two similar components or rotate a component. }
{ }
{ A script to ask the user to select two components then }
{ have their positions swapped }
{ OR }
{ if the same component is selected twice, have it rotated }
{ }
{ Limitations of this script: }
{ You need to move the cursor away from a component to exit }
{ }
{ }
{ Version 1.2 }
{..............................................................................}
{..............................................................................}
Procedure ChooseAndSwapComponents;
Var
Board : IPCB_Board;
Comp1 : IPCB_Component;
Comp2 : IPCB_Component;
x,y, : TCoord;
x1, y1 : TCoord;
Rotation : TAngle;
Begin
Pcbserver.PreProcess;
Try
Board := PCBServer.GetCurrentPCBBoard;
If Not Assigned(Board) Then
Begin
ShowMessage('The Current Document is not a Protel PCB Document.');
Exit;
End;
Repeat
Board.ChooseLocation(x,y, 'Choose Component1');
Comp1 := Board.GetObjectAtXYAskUserIfAmbiguous(x,y,MkSet(eComponentObject),AllLayers, eEditAction_Select);
If Not Assigned(Comp1) Then Exit;
Board.ChooseLocation(x,y, 'Choose Component2');
Comp2 := Board.GetObjectAtXYAskUserIfAmbiguous(x,y,MkSet(eComponentObject),AllLayers, eEditAction_Select);
If Not Assigned(Comp2) Then Exit;
// Check if Component Name property exists before extracting the text
If Comp1.Name = Nil Then Exit;
If Comp2.Name = Nil Then Exit;
// Check if same component selected twice
If Comp1.Name.Text = Comp2.Name.Text
Then
Begin
// Rotate the same component
PCBServer.SendMessageToRobots(Comp1.I_ObjectAddress, c_Broadcast, PCBM_BeginModify , c_NoEventData);
Case Comp1.Rotation of
0 : Comp1.Rotation := 180;
90 : Comp1.Rotation := 270;
180 : Comp1.Rotation := 0;
270 : Comp1.Rotation := 90;
360 : Comp1.Rotation := 180;
End;
PCBServer.SendMessageToRobots(Comp1.I_ObjectAddress, c_Broadcast, PCBM_EndModify , c_NoEventData);
Client.SendMessage('PCB:Zoom', 'Action=Redraw', 255, Client.CurrentView);
End
Else
Begin
PCBServer.SendMessageToRobots(Comp1.I_ObjectAddress, c_Broadcast, PCBM_BeginModify , c_NoEventData);
PCBServer.SendMessageToRobots(Comp2.I_ObjectAddress, c_Broadcast, PCBM_BeginModify , c_NoEventData); // Swap Components
// swap two components
x1 := comp1.x;
y1 := comp1.y;
comp1.x := comp2.x;
comp1.y := comp2.y;
comp2.x := x1;
comp2.y := y1;
PCBServer.SendMessageToRobots(Comp1.I_ObjectAddress, c_Broadcast, PCBM_EndModify , c_NoEventData);
PCBServer.SendMessageToRobots(Comp2.I_ObjectAddress, c_Broadcast, PCBM_EndModify , c_NoEventData);
Client.SendMessage('PCB:Zoom', 'Action=Redraw', 255, Client.CurrentView);
End;
// click on the board to exit or RMB
Until (Comp1 = Nil) Or (Comp2 = Nil);
Finally
Pcbserver.PostProcess;
Client.SendMessage('PCB:Zoom', 'Action=Redraw', 255, Client.CurrentView);
End;
End;
|
unit nsCrypt;
interface
uses
Windows, Classes, SysUtils, WinCrypt;
type
THashProgress = procedure(CurBlock, TotBlock: integer; var AClose: Boolean) of object;
THashKey = array[1..20] of Byte;
TWinCrypt = class(TObject)
strict private
hProv: HCRYPTPROV;
hKey: HCRYPTKEY;
FPassword: string;
private
FOnProgress: THashProgress;
FWorkStream: TStream;
function CryptStream(var InStr, OutStr: TStream; ToCrypt: Boolean): Boolean;
function GetHashKey: THashKey;
function GetPassword: string;
procedure SetPassword(const Value: string);
function GetHashEmpty: THashKey;
public
constructor Create;
destructor Destroy; override;
function EncryptFile(var InStr: TStream; var OutStr: TFileStream): Boolean;
function DecryptFile(var InStr: TFileStream; var OutStr: TStream): Boolean;
class function CryptText(const SourceText, Password: string; CryptIt: Boolean): string;
property OnProgress: THashProgress read FOnProgress write FOnProgress;
property Password: string read GetPassword write SetPassword;
property HashKey: THashKey read GetHashKey;
property HashEmpty: THashKey read GetHashEmpty;
end;
implementation
{ TWinCrypt }
constructor TWinCrypt.Create;
begin
inherited;
CryptAcquireContext(hProv, nil, nil, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
end;
destructor TWinCrypt.Destroy;
begin
CryptReleaseContext(hProv, 0);
inherited;
end;
function TWinCrypt.CryptStream(var InStr, OutStr: TStream; ToCrypt: Boolean): Boolean;
var
Buffer: PByte;
len: dWord;
b: Boolean;
IsEndOfFile: Boolean;
begin
GetHashKey;
GetMem(Buffer, 512);
try
b := False;
repeat
IsEndOfFile := (InStr.Position >= InStr.Size) or b;
if IsEndOfFile then
break;
len := InStr.Read(Buffer^, 512);
if ToCrypt then
CryptEncrypt(hKey, 0, IsEndOfFile, 0, Buffer, len, len)
else
CryptDecrypt(hKey, 0, IsEndOfFile, 0, Buffer, len);
if Assigned(OnProgress) then
OnProgress(InStr.Position, InStr.Size, b);
OutStr.Write(Buffer^, len)
until IsEndOfFile;
Result := OutStr.Size > 0;
finally
FreeMem(Buffer, 512);
end;
end;
class function TWinCrypt.CryptText(const SourceText, Password: string; CryptIt: Boolean): string;
var
crypt: TWinCrypt;
iLen: Integer;
InputText: String;
OutputText: String;
fsIn, fsOut: TStream;
begin
crypt := TWinCrypt.Create;
try
if CryptIt or (SourceText = '') then
begin
InputText := SourceText;
end else
begin
iLen := Ord(SourceText[1]);
InputText := Copy(SourceText, 2, iLen);
end;
fsIn := TStringStream.Create(InputText);
fsOut := TStringStream.Create(OutputText);
try
crypt.Password := Password;
if crypt.CryptStream(fsIn, fsOut, CryptIt) then
Result := TStringStream(fsOut).DataString
else
Result := InputText;
if CryptIt then
begin
Result := Chr(Length(Result)) + Result;
while Length(Result) < 16 do
begin
Result := Result + Chr(Random(255));
end;
end;
finally
fsIn.Free;
fsOut.Free;
end;
finally
FreeAndNil(crypt);
end;
end;
function TWinCrypt.DecryptFile(var InStr: TFileStream; var OutStr: TStream): Boolean;
begin
FWorkStream := InStr;
Result := CryptStream(FWorkStream, Outstr, False);
end;
function TWinCrypt.EncryptFile(var InStr: TStream; var OutStr: TFileStream): Boolean;
begin
FWorkStream := OutStr;
Result := CryptStream(InStr, FWorkStream, True);
end;
function TWinCrypt.GetPassword: string;
begin
Result := FPassword;
end;
function TWinCrypt.GetHashEmpty: THashKey;
begin
FillChar(Result, SizeOf(THashKey), 0);
end;
function TWinCrypt.GetHashKey: THashKey;
var
hash: HCRYPTHASH;
iLen: Cardinal;
begin
CryptCreateHash(hProv, CALG_SHA, 0, 0, hash);
CryptHashData(hash, @Password[1], Length(Password), 0);
CryptDeriveKey(hProv, CALG_RC4, hash, 0, hKey);
iLen := SizeOf(THashKey);
FillChar(Result, iLen, 0);
CryptGetHashParam(hash, HP_HASHVAL, @Result, iLen, 0);
CryptDestroyHash(hash);
end;
procedure TWinCrypt.SetPassword(const Value: string);
begin
FPassword := Value;
end;
end.
|
unit NumeroNatural;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, RemoveOperations;
type
{ TNumeroNatural }
TNumeroNatural = Class
private
number : Integer;
removeFunctions : TRemoveOperations;
public
constructor create;
procedure setNumero(numero:Integer);
function getNumero():Integer;
procedure sumar(numero:Integer);
procedure restar(numero:Integer);
procedure multiplicar(numero:Integer);
procedure dividir(numero:Integer);
procedure deleteLastDigit;
end;
implementation
{ TNumeroNatural }
constructor TNumeroNatural.create;
begin
number:= 0;
removeFunctions := TRemoveOperations.create;
end;
procedure TNumeroNatural.setNumero(numero: Integer);
begin
self.number:= numero;
end;
function TNumeroNatural.getNumero: Integer;
begin
Result:= number;
end;
procedure TNumeroNatural.sumar(numero: Integer);
begin
setNumero(getNumero() + numero);
end;
procedure TNumeroNatural.restar(numero: Integer);
begin
setNumero(getNumero() - numero);
end;
procedure TNumeroNatural.multiplicar(numero: Integer);
begin
setNumero(getNumero() * numero);
end;
procedure TNumeroNatural.dividir(numero: Integer);
begin
if (getNumero() >= numero ) then
setNumero(getNumero() div numero);
end;
procedure TNumeroNatural.deleteLastDigit;
begin
removeFunctions.deleteDigit(Self.number);
end;
end.
|
unit CellExpertView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, ThPanel;
type
TCellExpertForm = class(TForm)
UpDown1: TUpDown;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
procedure Button3Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure UpDown1Click(Sender: TObject; Button: TUDBtnType);
private
{ Private declarations }
public
{ Public declarations }
Panel: TThCustomPanel;
end;
var
CellExpertForm: TCellExpertForm;
implementation
{$R *.dfm}
procedure TCellExpertForm.Button3Click(Sender: TObject);
begin
Panel.Align := alTop;
end;
procedure TCellExpertForm.Button1Click(Sender: TObject);
begin
Panel.Align := alLeft;
end;
procedure TCellExpertForm.Button2Click(Sender: TObject);
begin
Panel.Align := alRight;
end;
procedure TCellExpertForm.Button4Click(Sender: TObject);
begin
Panel.Align := alBottom;
end;
procedure TCellExpertForm.UpDown1Click(Sender: TObject;
Button: TUDBtnType);
begin
if Button = btNext then
Panel.Tag := Panel.Tag + 1
else
Panel.Tag := Panel.Tag - 1;
Panel.Parent.Realign;
end;
end.
|
unit PrinterProgress;
interface
uses
Windows,
Messages,
SysUtils,
Classes,
Graphics,
Controls,
Forms,
StdCtrls,
ExtCtrls,
Dmitry.Controls.DmProgress,
uDBForm,
uShellIntegration;
type
TFormPrinterProgress = class(TDBForm)
PbPrinterProgress: TDmProgress;
ImPrinter: TImage;
BtnAbort: TButton;
Label1: TLabel;
procedure FormCreate(Sender: TObject);
procedure BtnAbortClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
protected
{ Protected declarations }
procedure CreateParams(var Params: TCreateParams); override;
function GetFormID : string; override;
public
{ Public declarations }
PValue: PBoolean;
FCanClose: Boolean;
procedure SetMaxValue(Value: Integer);
procedure SetValue(Value: Integer);
procedure SetText(Text: string);
procedure SetLanguage;
end;
function GetFormPrinterProgress : TFormPrinterProgress;
implementation
{$R *.dfm}
function GetFormPrinterProgress : TFormPrinterProgress;
begin
Application.CreateForm(TFormPrinterProgress, Result);
end;
procedure TFormPrinterProgress.FormCreate(Sender: TObject);
begin
Icon := ImPrinter.Picture.Icon;
SetLanguage;
DisableWindowCloseButton(Handle);
FCanClose := False;
end;
function TFormPrinterProgress.GetFormID: string;
begin
Result := 'PrinterProgress';
end;
procedure TFormPrinterProgress.SetMaxValue(Value: Integer);
begin
PbPrinterProgress.MaxValue := Value;
end;
procedure TFormPrinterProgress.SetText(Text: string);
begin
PbPrinterProgress.Text := Text;
end;
procedure TFormPrinterProgress.SetValue(Value: Integer);
begin
PbPrinterProgress.Position := Value;
end;
procedure TFormPrinterProgress.BtnAbortClick(Sender: TObject);
begin
BtnAbort.Enabled := False;
PValue^ := True;
end;
procedure TFormPrinterProgress.SetLanguage;
begin
BeginTranslate;
try
Caption := L('Printing ...');
BtnAbort.Caption := L('Abort');
Label1.Caption := L('Please wait until done printing...');
finally
EndTranslate;
end;
end;
procedure TFormPrinterProgress.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
Params.WndParent := GetDesktopWindow;
with Params do
ExStyle := ExStyle or WS_EX_APPWINDOW;
end;
procedure TFormPrinterProgress.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose := FCanClose;
end;
end.
|
unit uEnfermidades;
{**********************************************************************
** unit uEnfermidades **
** **
** UNIT DESTINADA A MANIPULAR AS INFORMAÇÕES NO CADASTRO DE PACIENTE **
** REFERENTE AS INFORMAÇÕES DENTRO DA ABA DE ENFERMIDADES **
** **
***********************************************************************}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, uCadPacientes, uClassControlePaciente, uClassEnfermidades, uFrmMensagem;
type
{ Enfermidades }
Enfermidades = class
public
class function CarregaObjEnfermidades(objEnfermidades: TEnfermidades; frm: TfrmCadPaciente): TEnfermidades;
class procedure InclusaoOuEdicaoEnfermidades(frm: TfrmCadPaciente);
end;
implementation
{ Enfermidades }
class function Enfermidades.CarregaObjEnfermidades(objEnfermidades: TEnfermidades; frm: TfrmCadPaciente): TEnfermidades;
begin
with objEnfermidades do
begin
idEnfermidade := StrToInt(frm.edtCodEnfermidades.Text);
idTblPaciente := StrToInt(frm.edtCodPaciente.Text);
aids := frm.RetornoRadioGroup(frm.rgexAIDS.ItemIndex);
anemia := frm.RetornoRadioGroup(frm.rgexAnemia.ItemIndex);
asma := frm.RetornoRadioGroup(frm.rgexAsma.ItemIndex);
diabete := frm.RetornoRadioGroup(frm.rgexDiabetes.ItemIndex);
disritmiaEpilepsia := frm.RetornoRadioGroup(frm.rgexDisritmiaEpilepsia.ItemIndex);
doencaCoracao := frm.RetornoRadioGroup(frm.rgexDoencaCoracao.ItemIndex);
doencaRenal := frm.RetornoRadioGroup(frm.rgexDoencaRenal.ItemIndex);
febreReumatica := frm.RetornoRadioGroup(frm.rgexFebreReumatica.ItemIndex);
glaucoma := frm.RetornoRadioGroup(frm.rgexGlaucoma.ItemIndex);
gonorreia := frm.RetornoRadioGroup(frm.rgexGonorreia.ItemIndex);
hanseniase := frm.RetornoRadioGroup(frm.rgexHanseniase.ItemIndex);
hemofilia := frm.RetornoRadioGroup(frm.rgexHemofilia.ItemIndex);
hepatite := frm.RetornoRadioGroup(frm.rgexHepatite.ItemIndex);
ictericia := frm.RetornoRadioGroup(frm.rgexIctericia.ItemIndex);
problemaHormonal := frm.RetornoRadioGroup(frm.rgexProblemaHormonal.ItemIndex);
sifilis := frm.RetornoRadioGroup(frm.rgexSifilis.ItemIndex);
sinusite := frm.RetornoRadioGroup(frm.rgexSinusite.ItemIndex);
tuberculose := frm.RetornoRadioGroup(frm.rgexTuberculose.ItemIndex);
tumorBoca := frm.RetornoRadioGroup(frm.rgexTumorBoca.ItemIndex);
ulceraHepatica := frm.RetornoRadioGroup(frm.rgexUlceraHepatica.ItemIndex);
end;
result := objEnfermidades;
end;
class procedure Enfermidades.InclusaoOuEdicaoEnfermidades(frm: TfrmCadPaciente);
var
objEnfermidades : TEnfermidades;
objControlePaciente : TControlePaciente;
codEnfermidade : integer = 0;
begin
try
objEnfermidades := TEnfermidades.Create;
objControlePaciente := TControlePaciente.Create;
codEnfermidade := objControlePaciente.InclusaoOuEdicaoEnfermidades(CarregaObjEnfermidades(objEnfermidades, frm));
if codEnfermidade > 0 then
begin
try
frmMensagem := TfrmMensagem.Create(nil);
frmMensagem.InfoFormMensagem('Cadastro de Enfermidades', tiInformacao, 'Cadastro das Enfermidades realizado com sucesso!');
finally
FreeAndNil(frmMensagem);
end;
end;
// DesabilitaControles(pcCadPaciente.ActivePage);
estado := teNavegacao;
//EstadoBotoes;
finally
FreeAndNil(objControlePaciente);
FreeAndNil(objEnfermidades);
end;
end;
end.
|
function InsereChar(l: longint;Charin:String): string;
//
// Insere uma mascara especificada em um valor numérico
//
var
len, count: integer;
s: string;
begin
str(l, s);
len := length(s);
for count := ((len - 1) div 3) downto 1 do
begin
insert(Charin, s, len - (count * 3) + 1);
len := len + 1;
end;
Result := s;
end;
|
unit uCommonDBParams;
interface
uses Variants, DB, Controls;
type
TCommonDBParams = class(TObject)
private
FParamNames: array of string;
FParamValues: array of Variant;
function ReadValue(s: string): Variant;
procedure SetValue(s: string; value: Variant);
public
property Values[s: string]: Variant read ReadValue write SetValue; default;
procedure SetDate(s: string; Date: TDate);
function Substitute(s: string; params: string;
QuoteStr: Boolean = True): string;
procedure StoreFields(DataSet: TDataSet; Fields: string);
procedure Clear;
end;
resourcestring
errCommonDBParamNotFound = 'TCommonDBParams.ReadValue: Параметр не знайдено!';
function VariantToString(value: Variant; QuoteStr: Boolean = True): string;
implementation
uses Math, SysUtils;
procedure TCommonDBParams.StoreFields(DataSet: TDataSet; Fields: string);
var
p: Integer;
fieldName: string;
field: TField;
begin
if DataSet.IsEmpty then Exit;
fields := Trim(fields) + ',';
repeat
p := Pos(',', fields);
fieldName := Copy(fields, 1, p - 1);
fields := Trim(Copy(fields, p + 1, Length(fields)));
field := DataSet.FindField(fieldName);
if field <> nil then
SetValue(fieldName, field.Value);
until fields = '';
end;
function TCommonDBParams.Substitute(s: string; params: string;
QuoteStr: Boolean = True): string;
var
p: Integer;
param: string;
value: Variant;
valStr: string;
begin
params := Trim(params) + ',';
repeat
p := Pos(',', params);
param := Copy(params, 1, p - 1);
params := Trim(Copy(params, p + 1, Length(params)));
value := ReadValue(param);
valStr := VariantToString(value, QuoteStr);
s := StringReplace(s, ':' + param, valStr, [rfReplaceAll, rfIgnoreCase]);
until params = '';
Result := s;
end;
function VariantToString(value: Variant; QuoteStr: Boolean = True): string;
var
h, m, s, msec: Word;
mstr: string;
ds: Char;
begin
case VarType(value) of
varNull, varEmpty: Result := 'Null';
varInteger, varSmallint, varByte, varWord: Result := IntToStr(value);
varString:
if QuoteStr then Result := QuotedStr(value)
else Result := value;
varDouble, varSingle:
begin
ds := DecimalSeparator;
DecimalSeparator := '.';
Result := FloatToStr(value);
DecimalSeparator := ds;
end;
varDate:
if value < StrToDate('01.01.1900') then
begin
Result := '''';
DecodeTime(value, h, m, s, msec);
mstr := IntToStr(m);
if Length(mstr) < 2 then mstr := '0' + mstr;
Result := Result + IntToStr(h) + ':' + mstr;
if s <> 0 then
begin
mstr := IntToStr(s);
if Length(mstr) < 2 then mstr := '0' + mstr;
Result := Result + ':' + mstr;
end;
Result := Result + ''''
end
else Result := QuotedStr(DateTimeToStr(value));
varCurrency:
begin
ds := DecimalSeparator;
DecimalSeparator := '.';
Result := CurrToStr(value);
DecimalSeparator := ds;
end
else
if QuoteStr then Result := QuotedStr(value.AsString)
else Result := value.AsString;
end;
end;
function TCommonDBParams.ReadValue(s: string): Variant;
var
i: Integer;
begin
Result := Null;
s := AnsiUpperCase(Trim(s));
for i := 0 to High(FParamNames) do
if FParamNames[i] = s then
begin
Result := FParamValues[i];
Exit;
end;
raise Exception.Create(errCommonDBParamNotFound + ' (' + s + ')');
end;
procedure TCommonDBParams.SetValue(s: string; value: Variant);
var
i: Integer;
begin
s := AnsiUpperCase(Trim(s));
for i := 0 to High(FParamNames) do
if FParamNames[i] = s then
begin
FParamValues[i] := value;
Exit;
end;
SetLength(FParamNames, Length(FParamNames) + 1);
SetLength(FParamValues, Length(FParamValues) + 1);
FParamNames[High(FParamNames)] := s;
FParamValues[High(FParamValues)] := value;
end;
procedure TCommonDBParams.SetDate(s: string; Date: TDate);
var
val: Variant;
begin
val := Date;
SetValue(s, val);
end;
procedure TCommonDBParams.Clear;
begin
SetLength(FParamNames, 0);
SetLength(FParamValues, 0);
end;
end.
|
unit uDMImportInventoryCatalog;
interface
uses
Windows, Messages, SysUtils, Classes, ComServ, ComObj, VCLCom, DataBkr,
DBClient, StdVcl, ADODB, DB, Provider, uDMCalcPrice;
type
TDMImportInventoryCatalog = class(TDataModule)
cmdUpdateModelPrice: TADOCommand;
qryProducts: TADODataSet;
qryProductsMark: TBooleanField;
qryProductssku: TStringField;
qryProductsupc: TStringField;
qryProductsTitle: TStringField;
qryProductsPriceInfo: TStringField;
qryProductsVendorCost: TCurrencyField;
qryProductswholesale: TBCDField;
qryProductsVendor: TStringField;
qryProductsCategory: TStringField;
qryProductsSubCategory: TStringField;
qryProductsCGroup: TStringField;
qryProductsTax_Category: TStringField;
qryProductsMfg: TStringField;
qryProductsIDModel: TIntegerField;
qryProductsModel: TStringField;
qryProductsDescription: TStringField;
qryProductsFinalCost: TBCDField;
qryProductsSellingPrice: TBCDField;
qryProductsSuggRetail: TBCDField;
qryProductsManufacture: TStringField;
qryProductsIDCategory: TIntegerField;
qryProductsIDSubCategory: TIntegerField;
qryProductsIDGroup: TIntegerField;
qryProductsModelCategory: TStringField;
qryProductsModelSubCategory: TStringField;
qryProductsModelGroup: TStringField;
qryProductsNewSalePrice: TBCDField;
qryProductsNewMSRPPrice: TBCDField;
dspProducts: TDataSetProvider;
cdsProducts: TClientDataSet;
cmdUpdateInventory: TADOCommand;
procedure DataModuleDestroy(Sender: TObject);
procedure qryProductsCalcFields(DataSet: TDataSet);
procedure DataModuleCreate(Sender: TObject);
private
FLog: TStringList;
FDMCalcPrice : TDMCalcPrice;
FSQLConnection: TADOConnection;
procedure OpenProducts;
procedure CloseProducts;
procedure FilterProducts(sFilter: WideString);
procedure CalcSalePrice;
procedure UpdateKitPromoPrice(IDModel: Integer; CostPrice: Currency);
public
property Log: TStringList read FLog write FLog;
function GetInventoryList(const AFilter: WideString): OleVariant;
function GetModelPricesList(const AFilter: WideString): OleVariant;
function UpdateMRPricesWithCatalog(ModelList: OleVariant): Boolean;
function UpdateMRInventoryWithCatalog(ModelList: OleVariant): Boolean;
procedure SetConnection(SQLConnection: TADOConnection);
procedure ConfigureCalcPrice(SQLConnection: TADOConnection);
end;
var
DMImportInventoryCatalog: TDMImportInventoryCatalog;
implementation
uses uSqlFunctions, uMRSQLParam, uDMGlobal, uSystemConst, uObjectServices, uContentClasses;
{$R *.dfm}
procedure TDMImportInventoryCatalog.OpenProducts;
begin
with cdsProducts do
if not Active then
Open;
end;
procedure TDMImportInventoryCatalog.CloseProducts;
begin
with cdsProducts do
if Active then
Close;
end;
procedure TDMImportInventoryCatalog.FilterProducts(sFilter : WideString);
var
MRSQLParam : TMRSQLParam;
sWhere : String;
begin
CloseProducts;
sWhere := ' CP.Inactive = 0 ';
if sFilter <> '' then
begin
MRSQLParam := TMRSQLParam.Create;
try
MRSQLParam.ParamString := sFilter;
if MRSQLParam.KeyExists('ModelExist') then
begin
sWhere := sWhere + ' AND CP.upc = B.IDBarcode ';
MRSQLParam.Delete(MRSQLParam.IndexOf(MRSQLParam.KeyByName('ModelExist')));
end;
if MRSQLParam.KeyExists('CostEqual') then
begin
sWhere := sWhere + ' AND PV.vCost <> M.FinalCost ';
MRSQLParam.Delete(MRSQLParam.IndexOf(MRSQLParam.KeyByName('CostEqual')));
end;
if MRSQLParam.KeyExists('DescriptionEqual') then
begin
sWhere := sWhere + ' AND CP.Title <> M.Description ';
MRSQLParam.Delete(MRSQLParam.IndexOf(MRSQLParam.KeyByName('DescriptionEqual')));
end;
if MRSQLParam.Count > 0 then
sWhere := sWhere + ' AND ' + MRSQLParam.GetWhereSQL;
finally
FreeAndNil(MRSQLParam);
end;
end;
with qryProducts do
CommandText := ChangeWhereClause(CommandText, sWhere, True);
end;
function TDMImportInventoryCatalog.UpdateMRPricesWithCatalog(ModelList: OleVariant): Boolean;
var
cdsNewPrices : TClientDataSet;
CostPrice: Currency;
begin
cdsNewPrices := TClientDataSet.Create(nil);
try
cdsNewPrices.Data := ModelList;
with cdsNewPrices do
begin
First;
while not EOF do
begin
try
CostPrice := FDMCalcPrice.FormatPrice(FieldByName('CostPrice').AsCurrency);
cmdUpdateModelPrice.Parameters.ParamByName('IDModel').Value := FieldByName('IDModel').AsInteger;
cmdUpdateModelPrice.Parameters.ParamByName('NewCost').Value := CostPrice;
cmdUpdateModelPrice.Parameters.ParamByName('NewSalePrice').Value := FieldByName('SalePrice').AsCurrency;
cmdUpdateModelPrice.Parameters.ParamByName('NewMSRP').Value := FieldByName('MSRP').AsCurrency;
cmdUpdateModelPrice.Parameters.ParamByName('IDUserLastSellingPrice').Value := FieldByName('IDUserLastSellingPrice').AsInteger;
cmdUpdateModelPrice.Parameters.ParamByName('ChangeDate').Value := Now;
cmdUpdateModelPrice.Execute;
UpdateKitPromoPrice(FieldByName('IDModel').AsInteger, CostPrice);
except
on E: Exception do
Log.Add('An error ocurred when update Model ' + FieldByName('Model').AsString + '. Error: ' + E.Message);
end;
Next;
end;
end;
finally
FreeAndNil(cdsNewPrices);
end;
end;
procedure TDMImportInventoryCatalog.UpdateKitPromoPrice(IDModel: Integer; CostPrice: Currency);
var
KitModelService: TMRKitModelService;
KitModel: TKitModel;
begin
with DMGlobal.qryFreeSQL do
try
if Active then
Close;
Connection := cmdUpdateModelPrice.Connection;
SQL.Text := ' SELECT Qty, MarginPerc FROM KitModel WHERE IDModel = ' + IntToStr(IDModel) + ' AND ISNULL(MarginPerc, 0) <> 0 ';
Open;
if not(IsEmpty) then
try
KitModelService := TMRKitModelService.Create();
KitModel := TKitModel.Create();
KitModelService.SQLConnection := cmdUpdateModelPrice.Connection;
First;
While not Eof do
begin
// Campos necessários
KitModel.IDModel := IDModel;
KitModel.Qty := FieldByName('Qty').AsFloat;
if not DMGlobal.IsClientServer(FSQLConnection) then
KitModel.SellingPrice := FDMCalcPrice.GetMarginPrice(CostPrice, FieldByName('MarginPerc').AsFloat);
KitModel.MarginPerc := FieldByName('MarginPerc').AsFloat;
//Update
KitModelService.Update(KitModel);
Next;
end;
finally
FreeAndNil(KitModel);
FreeAndNil(KitModelService);
end;
finally
Close;
end;
end;
procedure TDMImportInventoryCatalog.CalcSalePrice;
var
FNewSalePrice,
FNewMSRPPrice, FCostPrice : Currency;
begin
with cdsProducts do
if Active then
begin
First;
While not EOF do
begin
if (FieldByName('IDModel').AsString <> '') and (FieldByName('VendorCost').AsCurrency <> 0) then
begin
FCostPrice := FDMCalcPrice.FormatPrice(FieldByName('VendorCost').AsCurrency);
FNewSalePrice := FDMCalcPrice.CalcSalePrice(FieldByName('IDModel').AsInteger,
FieldByName('IDCategory').AsInteger,
FieldByName('IDSubCategory').AsInteger,
FieldByName('IDGroup').AsInteger,
FCostPrice);
FNewMSRPPrice := FDMCalcPrice.CalcMSRPPrice(FieldByName('IDCategory').AsInteger,
FieldByName('IDSubCategory').AsInteger,
FieldByName('IDGroup').AsInteger,
FCostPrice);
if FNewSalePrice <> FCostPrice then
begin
Edit;
FieldByName('NewSalePrice').AsCurrency := FNewSalePrice;
end;
if FNewMSRPPrice <> FCostPrice then
begin
Edit;
FieldByName('NewMSRPPrice').AsCurrency := FNewMSRPPrice;
end;
if State in [dsEdit, dsInsert] then
Post;
end;
Next;
end;
end;
end;
function TDMImportInventoryCatalog.GetModelPricesList(const AFilter: WideString): OleVariant;
begin
Result := '';
FilterProducts(AFilter);
OpenProducts;
CalcSalePrice;
Result := cdsProducts.Data;
end;
function TDMImportInventoryCatalog.GetInventoryList(const AFilter: WideString): OleVariant;
begin
Result := '';
FilterProducts(AFilter);
OpenProducts;
Result := cdsProducts.Data;
end;
function TDMImportInventoryCatalog.UpdateMRInventoryWithCatalog(
ModelList: OleVariant): Boolean;
var
cdsNewInventory : TClientDataSet;
begin
Result := False;
cdsNewInventory := TClientDataSet.Create(nil);
try
cdsNewInventory.Data := ModelList;
with cdsNewInventory do
begin
First;
while not EOF do
begin
try
cmdUpdateInventory.Parameters.ParamByName('IDModel').Value := FieldByName('IDModel').AsInteger;
cmdUpdateInventory.Parameters.ParamByName('Description').Value := FieldByName('Description').AsString;
cmdUpdateInventory.Execute;
except
on E: Exception do
Log.Add('An error ocurred when update Model ' + FieldByName('Model').AsString + '. Error: ' + E.Message);
end;
Next;
end;
Result := True;
end;
finally
FreeAndNil(cmdUpdateInventory);
end;
end;
procedure TDMImportInventoryCatalog.DataModuleDestroy(Sender: TObject);
begin
if Assigned(FDMCalcPrice) then
FreeAndNil(FDMCalcPrice);
FreeAndNil(FLog);
end;
procedure TDMImportInventoryCatalog.qryProductsCalcFields(
DataSet: TDataSet);
begin
if ((qryProductsVendorCost.AsCurrency + qryProductsFinalCost.AsCurrency)/2) <> 0 then
qryProductsPriceInfo.AsString := FormatFloat('0.00 %',((qryProductsVendorCost.AsCurrency - qryProductsFinalCost.AsCurrency)
/((qryProductsVendorCost.AsCurrency + qryProductsFinalCost.AsCurrency)/2)*100));
end;
procedure TDMImportInventoryCatalog.SetConnection(SQLConnection: TADOConnection);
var
i: Integer;
begin
for i := 0 to Pred(ComponentCount) do
if (Components[i] is TADODataSet) then
TADODataSet(Components[i]).Connection := SQLConnection
else if (Components[i] is TADOCommand) then
TADOCommand(Components[i]).Connection := SQLConnection;
FSQLConnection := SQLConnection;
end;
procedure TDMImportInventoryCatalog.ConfigureCalcPrice(
SQLConnection: TADOConnection);
begin
if not Assigned(FDMCalcPrice) then
FDMCalcPrice := TDMCalcPrice.Create(Self);
FDMCalcPrice.SetConnection(SQLConnection);
FDMCalcPrice.UseMargin := DMGlobal.GetSvrParam(PARAM_CALC_MARGIN ,SQLConnection);
FDMCalcPrice.UseRound := DMGlobal.GetSvrParam(PARAM_CALC_ROUNDING, SQLConnection);
end;
procedure TDMImportInventoryCatalog.DataModuleCreate(Sender: TObject);
begin
FLog := TStringList.Create();
end;
end.
|
unit UCondominioController;
interface
uses
Classes, SQLExpr, SysUtils, Generics.Collections, DBXJSON, DBXCommon,
ConexaoBD,
UPessoasVO, UController, DBClient, DB, UCnaeVO, UCondominioVO,
UNaturezaJuridicaVO, UCidadeController, UPrecoGasVO, UPrecoGasController ;
type
TCondominioController = class(TController<TCondominioVO>)
private
public
function ConsultarPorId(id: integer): TCondominioVO;
procedure ValidarDados(Objeto:TCondominioVO);override;
end;
implementation
uses
UDao, Constantes, Vcl.Dialogs;
{ TPessoasController }
{ TPessoasController }
function TCondominioController.ConsultarPorId(id: integer): TCondominioVO;
var
P: TCondominioVO;
cidadeController:TCidadeController;
PrecoGasController : TPrecoGasController;
begin
P := TDAO.ConsultarPorId<TCondominioVO>(id);
cidadeController:=TCidadeController.Create;
if (P <> nil) then
begin
P.CnaeVO := TDAO.ConsultarPorId<TCnaeVO>(P.idCnae);
P.NaturezaVO := TDAO.ConsultarPorId<TNaturezaJuridicaVO>
(P.idNaturezaJuridica);
P.CidadeVO := cidadeController.ConsultarPorId(P.idCidade);
P.PrecoGasVO := PrecoGasController.ConsultarPorId(p.idPrecoGas);
end;
cidadeController.Free;
result := P;
end;
procedure TCondominioController.ValidarDados(Objeto: TCondominioVO);
begin
inherited;
end;
begin
end.
|
unit uMain;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
GLWin32Viewer,
GLCrossPlatform,
GLBaseClasses,
GLScene,
GLMaterial,
GLCadencer,
GLObjects,
GLCoordinates,
GLTexture,
GLKeyboard,
uDDStex;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
vp: TGLSceneViewer;
matlib: TGLMaterialLibrary;
cad: TGLCadencer;
dc_cam: TGLDummyCube;
cam: TGLCamera;
GLSphere1: TGLSphere;
procedure FormCreate(Sender: TObject);
procedure cadProgress(Sender: TObject; const deltaTime, newTime: Double);
procedure FormShow(Sender: TObject);
end;
var
Form1: TForm1;
m_pos: TPoint;
implementation
{$R *.dfm}
//
// setup
//
procedure TForm1.FormCreate;
begin
cad.FixedDeltaTime := 1 / GetDeviceCaps(getDC(Handle), 116);
setCursorPos(screen.width div 2, screen.height div 2);
with DDStex(matlib, 'cubemap', 'cubemap.dds').Material do
begin
Texture.MappingMode := tmmCubeMapNormal;
Texture.TextureWrap := twNone;
Texture.MagFilter := maNearest;
end;
end;
//
// cadProgress
//
procedure TForm1.cadProgress;
begin
with mouse.CursorPos do
begin
dc_cam.TurnAngle := dc_cam.TurnAngle + (width div 2 - X) * 0.02;
cam.PitchAngle := cam.PitchAngle + (height div 2 - Y) * 0.02;
end;
setCursorPos(screen.width div 2, screen.height div 2);
if IsKeyDown(27) then
close;
end;
//
// activate
//
procedure TForm1.FormShow;
begin
cad.Enabled := true;
end;
end.
|
unit StatHat;
interface
procedure EzPostCount(const EzKey, Stat: string; Count: Double);
procedure EzPostValue(const EzKey, Stat: string; Value: Double);
implementation
uses
IdHTTP,
Classes,
SysUtils;
const
EzURL = 'http://api.stathat.com/ez';
procedure Post(Params: TStrings);
var
HTTP: TIdHTTP;
begin
HTTP := TIdHTTP.Create(nil);
try
HTTP.Post(EzURL, Params);
finally
HTTP.Free;
end;
end;
function ConvertDouble(Value: Double): string;
var
FS: TFormatSettings;
begin
FS.DecimalSeparator := '.';
Result := FloatToStr(Value, FS);
end;
procedure EzPostCount(const EzKey, Stat: string; Count: Double);
var
Params: TStringList;
begin
Params := TStringList.Create;
try
Params.Values['ezkey'] := EzKey;
Params.Values['stat'] := Stat;
Params.Values['count'] := ConvertDouble(Count);
Post(Params);
finally
Params.Free;
end;
end;
procedure EzPostValue(const EzKey, Stat: string; Value: Double);
var
Params: TStringList;
begin
Params := TStringList.Create;
try
Params.Values['ezkey'] := EzKey;
Params.Values['stat'] := Stat;
Params.Values['value'] := ConvertDouble(Value);
Post(Params);
finally
Params.Free;
end;
end;
end.
|
unit ecf_posix;
{
(§LIC)
(c) Autor,Copyright Dipl.Ing.- Helmut Hartl
FirmOS Business Solutions GmbH
New Style BSD Licence (OSI)
Copyright (c) 2001-2012, FirmOS Business Solutions GmbH
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the <FirmOS Business Solutions GmbH> nor the names
of its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(§LIC_END)
}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,BaseUnix,unixtype,pthreads;
type
{$packrecords c}
Pposix_spawnattr_t = ^posix_spawnattr_t;
posix_spawnattr_t = record
__flags : smallint;
__pgrp : pid_t;
__sd : sigset_t;
__ss : sigset_t;
__sp : sched_param;
__policy : longint;
__pad : array[0..15] of longint;
end;
Ppid_t = ^pid_t;
__spawn_action = record end;
P__spawn_action = ^__spawn_action;
Pposix_spawn_file_actions_t = ^posix_spawn_file_actions_t;
posix_spawn_file_actions_t = record
__allocated : longint;
__used : longint;
__actions : P__spawn_action;
__pad : array[0..15] of longint;
end;
const
POSIX_SPAWN_RESETIDS = $01;
POSIX_SPAWN_SETPGROUP = $02;
POSIX_SPAWN_SETSIGDEF = $04;
POSIX_SPAWN_SETSIGMASK = $08;
POSIX_SPAWN_SETSCHEDPARAM = $10;
POSIX_SPAWN_SETSCHEDULER = $20;
function posix_spawn(__pid:Ppid_t; __path:Pchar; __file_actions:Pposix_spawn_file_actions_t; __attrp:Pposix_spawnattr_t; argv:ppchar;envp:ppchar):cint;cdecl;external clib name 'posix_spawn';
function posix_spawnp(__pid:Ppid_t; __file:Pchar; __file_actions:Pposix_spawn_file_actions_t; __attrp:Pposix_spawnattr_t; argv:PPchar;envp:ppchar):longint;cdecl;external clib name 'posix_spawnp';
function posix_spawnattr_init(__attr:Pposix_spawnattr_t):longint;cdecl;external clib name 'posix_spawnattr_init';
function posix_spawnattr_destroy(__attr:Pposix_spawnattr_t):longint;cdecl;external clib name 'posix_spawnattr_destroy';
function posix_spawnattr_getsigdefault(__attr:Pposix_spawnattr_t; __sigdefault:Psigset_t):longint;cdecl;external clib name 'posix_spawnattr_getsigdefault';
function posix_spawnattr_setsigdefault(__attr:Pposix_spawnattr_t; __sigdefault:Psigset_t):longint;cdecl;external clib name 'posix_spawnattr_setsigdefault';
function posix_spawnattr_getsigmask(__attr:Pposix_spawnattr_t; __sigmask:Psigset_t):longint;cdecl;external clib name 'posix_spawnattr_getsigmask';
function posix_spawnattr_setsigmask(__attr:Pposix_spawnattr_t; __sigmask:Psigset_t):longint;cdecl;external clib name 'posix_spawnattr_setsigmask';
function posix_spawnattr_getflags(__attr:Pposix_spawnattr_t; __flags:Psmallint):longint;cdecl;external clib name 'posix_spawnattr_getflags';
function posix_spawnattr_setflags(_attr:Pposix_spawnattr_t; __flags:smallint):longint;cdecl;external clib name 'posix_spawnattr_setflags';
function posix_spawnattr_getpgroup(__attr:Pposix_spawnattr_t; __pgroup:Ppid_t):longint;cdecl;external clib name 'posix_spawnattr_getpgroup';
function posix_spawnattr_setpgroup(__attr:Pposix_spawnattr_t; __pgroup:pid_t):longint;cdecl;external clib name 'posix_spawnattr_setpgroup';
function posix_spawnattr_getschedpolicy(__attr:Pposix_spawnattr_t; __schedpolicy:Plongint):longint;cdecl;external clib name 'posix_spawnattr_getschedpolicy';
function posix_spawnattr_setschedpolicy(__attr:Pposix_spawnattr_t; __schedpolicy:longint):longint;cdecl;external clib name 'posix_spawnattr_setschedpolicy';
function posix_spawnattr_getschedparam(__attr:Pposix_spawnattr_t; __schedparam:Psched_param):longint;cdecl;external clib name 'posix_spawnattr_getschedparam';
function posix_spawnattr_setschedparam(__attr:Pposix_spawnattr_t; __schedparam:Psched_param):longint;cdecl;external clib name 'posix_spawnattr_setschedparam';
function posix_spawn_file_actions_init(__file_actions:Pposix_spawn_file_actions_t):longint;cdecl;external clib name 'posix_spawn_file_actions_init';
function posix_spawn_file_actions_destroy(__file_actions:Pposix_spawn_file_actions_t):longint;cdecl;external clib name 'posix_spawn_file_actions_destroy';
function posix_spawn_file_actions_addopen(__file_actions:Pposix_spawn_file_actions_t; __fd:longint; __path:Pchar; __oflag:longint; __mode:mode_t):longint;cdecl;external clib name 'posix_spawn_file_actions_addopen';
function posix_spawn_file_actions_addclose(__file_actions:Pposix_spawn_file_actions_t; __fd:longint):longint;cdecl;external clib name 'posix_spawn_file_actions_addclose';
function posix_spawn_file_actions_adddup2(__file_actions:Pposix_spawn_file_actions_t; __fd:longint; __newfd:longint):longint;cdecl;external clib name 'posix_spawn_file_actions_adddup2';
function posix_openpt(oflag: cint): cint;cdecl;external clib name 'posix_openpt';
function ptsname(__fd:longint):Pchar;cdecl;external clib name 'ptsname';
function grantpt(__fd:longint):longint;cdecl;external clib name 'grantpt';
function unlockpt(__fd:longint):longint;cdecl;external clib name 'unlockpt';
Type
TSpawnAction = __spawn_action;
PSpawnAction = ^TSpawnAction;
implementation
end.
|
unit uAccess;
interface
uses
classes, Forms, controls, uBASE_SelectForm, uParams, uFrameBaseGrid, uObjectActionsRightHelp, uCommonUtils;
type
TCustomAccess = class
private
FObjectID: integer;
FObjectName: string;
FParams: TParamCollection;
protected
FExtendedParams: TParamCollection;
procedure SetObjectID(const Value: integer); virtual;
procedure ReadObjectName; virtual;
public
property Params: TParamCollection read FParams;
property ExtendedParams: TParamCollection read FExtendedParams;
property ObjectID: integer read FObjectID write SetObjectID;
property ObjectName: string read FObjectName;
constructor Create(AObjectID: integer);
destructor Destroy; override;
end;
TAccessArray = array of TCustomAccess;
TAccessCollection = class
protected
FItems: TAccessArray;
function GetItems(Index: integer): TCustomAccess;
public
property Items[Index: integer]: TCustomAccess read GetItems; default;
procedure Add(ACustomAccess: TCustomAccess);
function Count: integer;
function ItemByObjectID(ObjectID: integer): TCustomAccess;
destructor Destroy; override;
end;
TAccessCustomForm = class(TCustomAccess)
protected
function CanShow: boolean; virtual; abstract;
public
procedure Show; virtual; abstract;
end;
TAccessBook = class(TAccessCustomForm)
private
FPropsFormClass: TClass;
FSelectedRecords: TViewSelectedRecords;
FCurRecordValues: TParamCollection;
FWillBeChild: boolean;
FRealBook: TObject;
FSuspended_IsObjectLink: boolean;
FSuspended_ParentItem: pointer;
FSuspended_ObjectLinkMainFrameGrid: pointer;
FSuspended_OwnerFrame: TWinControl;
FSuspended_Item: pointer;
FSuspended: boolean;
protected
FUserBook: TObject;
function CanShow: boolean; override;
public
CopyFrom: TCopyFromObjectRecord;
property UserBook: TObject read FUserBook write FUserBook;
property RealBook: TObject read FRealBook write FRealBook;
property PropsFormClass: TClass read FPropsFormClass write FPropsFormClass;
property SelectedRecords: TViewSelectedRecords read FSelectedRecords;
property CurRecordValues: TParamCollection read FCurRecordValues;
property WillBeChild: boolean read FWillBeChild write FWillBeChild;
property Suspended: boolean read FSuspended write FSuspended;
property Suspended_IsObjectLink: boolean read FSuspended_IsObjectLink write FSuspended_IsObjectLink;
property Suspended_OwnerFrame: TWinControl read FSuspended_OwnerFrame write FSuspended_OwnerFrame;
property Suspended_ParentItem: pointer read FSuspended_ParentItem write FSuspended_ParentItem;
property Suspended_Item: pointer read FSuspended_Item write FSuspended_Item;
property Suspended_ObjectLinkMainFrameGrid: pointer read FSuspended_ObjectLinkMainFrameGrid write FSuspended_ObjectLinkMainFrameGrid;
procedure Show; override;
function ShowModal(RestoreKey: variant; IsCardView: boolean; IsNewRecord: boolean; InsertRecordDialog: boolean = false; UEPrimaryKey: integer = -1): TModalResult;
procedure ShowOnControl(ParentControl: TWinControl; WasSuspended: boolean = false); virtual;
constructor Create; virtual;
destructor Destroy; override;
end;
TAccessSelectorForm = class(TAccessCustomForm)
private
FForm: TBASE_SelectForm;
FFormClass: TClass;
FFormAutoFree: boolean;
FSelectedRecords: TViewSelectedRecords;
FUserBook: TObject;
FCurRecordValues: TParamCollection;
procedure SetForm(const Value: TBASE_SelectForm);
function GetPrimaryKeyValue: variant;
protected
procedure SetObjectID(const Value: integer); override;
function CanShow: boolean; override;
function CreateForm: TBASE_SelectForm; virtual;
public
// property UserBook: TObject read FUserBook write FUserBook;
property Form: TBASE_SelectForm read FForm write SetForm;
property FormClass: TClass read FFormClass write FFormClass;
property FormAutoFree: boolean read FFormAutoFree write FFormAutoFree;
property CurRecordValues: TParamCollection read FCurRecordValues;
property PrimaryKeyValue: variant read GetPrimaryKeyValue;
property SelectedRecords: TViewSelectedRecords read FSelectedRecords;
procedure Show; override;
function ShowModal(AParams: TParamCollection; RestoreKey: variant): TModalResult;
constructor Create; virtual;
destructor Destroy; override;
end;
implementation
uses uException, SysUtils, uUserBook, uBASE_BookForm,
uFormForObject, cxGridDBBandedTableView, uBASE_ObjectPropsForm, ExtCtrls, uMain, cxTableViewCds, Dialogs;
{ TCustomAccess }
constructor TCustomAccess.Create(AObjectID: integer);
begin
inherited Create;
FObjectID:=AObjectID;
ReadObjectName;
FParams:=TParamCollection.Create(TParamItem);
FExtendedParams:=TParamCollection.Create(TParamItem);
end;
destructor TCustomAccess.Destroy;
begin
Params.Free;
ExtendedParams.Free;
inherited;
end;
procedure TCustomAccess.ReadObjectName;
begin
FObjectName:=ExecSQLExpr(format('sp_GetObjectName @ObjectID = %d, @NeedAlias = 1', [ObjectID]));
end;
procedure TCustomAccess.SetObjectID(const Value: integer);
begin
FObjectID := Value;
ReadObjectName;
end;
{ TAccessCollection }
procedure TAccessCollection.Add(ACustomAccess: TCustomAccess);
begin
SetLength(FItems, length(FItems)+1);
FItems[Count-1]:=ACustomAccess;
end;
function TAccessCollection.Count: integer;
begin
result:=length(FItems);
end;
destructor TAccessCollection.Destroy;
var
i: integer;
begin
for i:=0 to Count-1 do
Items[i].Free;
SetLength(FItems, 0);
inherited;
end;
function TAccessCollection.GetItems(Index: integer): TCustomAccess;
begin
result:=FItems[Index];
end;
function TAccessCollection.ItemByObjectID(ObjectID: integer): TCustomAccess;
var
i: integer;
begin
result:=nil;
for i:=0 to Count-1 do
if Items[i].ObjectID=ObjectID then begin
result:=Items[i];
exit;
end;
if not Assigned(result) then
raise EInternalException.Create('TAccessCollection.ItemByObjectID'+#10#13+'Не найден объект с идентификаторм '+IntToStr(ObjectID));
end;
{ TAccessBook }
function TAccessBook.CanShow: boolean;
begin
result:=ObjActionsRightHelper.Right(ObjectID, raSelect);
end;
constructor TAccessBook.Create;
begin
FUserBook:=nil;
FPropsFormClass:=TBASE_BookForm;
FSelectedRecords:=nil;
FCurRecordValues:=nil;
FRealBook:=nil;
FWillBeChild:=false;
FExtendedParams:=TParamCollection.Create(TParamItem);
FSuspended:=false;
end;
destructor TAccessBook.Destroy;
begin
if Assigned(UserBook) then
UserBook.Destroy;
if Assigned(FSelectedRecords) then
self.FSelectedRecords.Free;
if Assigned(FCurRecordValues) then
FCurRecordValues.Free;
inherited;
end;
procedure TAccessBook.Show;
var
book: TUserBook;
begin
if not CanShow then
raise EAccessException.Create('Недостаточно прав на просмотр');
if Assigned(UserBook) then
(UserBook as TUserBook).Show
else begin
FUserBook:=TUserBook.Create;
book:=UserBook as TUserBook;
book.AccessManager:=self;
book.ObjectID:=ObjectID;
book.ExtendedParams.CopyFrom(ExtendedParams);
book.Show;
end;
end;
function TAccessBook.ShowModal(RestoreKey: variant; IsCardView: boolean; IsNewRecord: boolean; InsertRecordDialog: boolean = false; UEPrimaryKey: integer = -1): TModalResult;
var
book: TUserBook;
view: TcxGridBandedTableViewCds;
i, r: integer;
pnl: TPanel;
begin
FUserBook:=TUserBook.Create;
book:=UserBook as TUserBook;
book.AccessManager:=self;
book.ObjectID:=ObjectID;
book.PropsFormClass:=PropsFormClass;
book.ExtendedParams.CopyFrom(ExtendedParams);
book.CopyFrom.EnableCopy:=CopyFrom.EnableCopy;
book.CopyFrom.ObjectID:=CopyFrom.ObjectID;
book.CopyFrom.RecordID:=CopyFrom.RecordID;
book.CopyFrom.UEID:=CopyFrom.UEID;
if IsNewRecord then
if ExecSQLExpr('select [Тип объекта] from sys_Объект where код_Объект = '+IntToStr(ObjectID))='объект' then
book.PropsFormClass:=TBASE_ObjectPropsForm
else
book.PropsFormClass:=PropsFormClass;
book.RealBook:=self.RealBook as TUserBookItem; // --tuserbooksublistitem
if InsertRecordDialog then begin
pnl:=TPanel.Create(nil);
pnl.Visible:=false;
pnl.Parent:=frmMain;
book.EmptyOpen:=true;
book.ShowOnControl(pnl);
book.Items[0].FrameGrid.actInsert.Execute;
pnl.Free;
exit;
end;
result:=book.ShowModal(RestoreKey, IsCardView, IsNewRecord, UEPrimaryKey);
if (not IsCardView) and (result=mrOK) then begin
view:=book.Items[0].FrameGrid.ViewCh;
r:=view.DataController.FocusedRecordIndex;
FSelectedRecords:=TViewSelectedRecords.Create(view);
FCurRecordValues:=TParamCollection.Create(TParamItem);
with view.DataController.CashDataSource do
for i:=0 to FieldCount-1 do
FCurRecordValues.Add(Fields[i].FieldName).Value:=Values[r, Fields[i].Index];
end;
end;
procedure TAccessBook.ShowOnControl(ParentControl: TWinControl; WasSuspended: boolean = false);
var
book: TUserBook;
begin
if not CanShow then
raise EAccessException.Create('Недостаточно прав на просмотр');
if WasSuspended then begin
FUserBook:=TUserBook.Create;
book:=UserBook as TUserBook;
book.AccessManager:=self;
book.ObjectID:=ObjectID;
book.PropsFormClass:=PropsFormClass;
book.ExtendedParams.CopyFrom(ExtendedParams);
book.ShowOnControl(self.Suspended_OwnerFrame);
book.Items[0].IsObjectLink:=self.Suspended_IsObjectLink;
book.Items[0].ParentItem:=self.Suspended_ParentItem;
TUserBookSubListItem(self.Suspended_Item).ObjectLinkMainFrameGrid:=book.Items[0].FrameGrid;
self.Suspended:=false;
exit;
end;
FUserBook:=TUserBook.Create;
book:=UserBook as TUserBook;
book.AccessManager:=self;
book.ObjectID:=ObjectID;
book.PropsFormClass:=PropsFormClass;
book.ExtendedParams.CopyFrom(ExtendedParams);
book.ShowOnControl(ParentControl);
end;
{ TAccessSelectorForm }
function TAccessSelectorForm.CanShow: boolean;
begin
if ObjectID=157 then result:=true
else
result:=ObjActionsRightHelper.Right(ObjectID, raSelect);
end;
constructor TAccessSelectorForm.Create;
begin
FForm:=nil;
FUserBook:=nil;
FFormAutoFree:=true;
FSelectedRecords:=nil;
FCurRecordValues:=nil;
end;
function TAccessSelectorForm.CreateForm: TBASE_SelectForm;
var
Instance: TComponent;
begin
Instance:=TComponent(FormClass.NewInstance);
Instance.Create(Application.MainForm);
result:=Instance as TBASE_SelectForm;
end;
destructor TAccessSelectorForm.Destroy;
begin
if Assigned(Form) then
Form.Free;
if Assigned(FSelectedRecords) then
self.FSelectedRecords.Free;
if Assigned(FCurRecordValues) then
FCurRecordValues.Free;
inherited;
end;
function TAccessSelectorForm.GetPrimaryKeyValue: variant;
begin
result:=CurRecordValues.Items[0].Value;
end;
procedure TAccessSelectorForm.SetForm(const Value: TBASE_SelectForm);
begin
FForm:=Value;
if Value = nil then
Destroy;
end;
procedure TAccessSelectorForm.SetObjectID(const Value: integer);
begin
inherited;
FormClass:=FormForObject.GetFormClass(Value);
end;
procedure TAccessSelectorForm.Show;
var
AM: TAccessBook;
frm: TBASE_SelectForm;
begin
if not CanShow then
raise EAccessException.Create('Недостаточно прав на просмотр');
if Assigned(Form) then
(Form as TBASE_SelectForm).Show
else begin
if self.FormClass<>TBASE_BookForm then begin
FForm:=CreateForm;
frm:=Form as TBASE_SelectForm;
frm.Selector:=false;
frm.AccessManager:=self;
frm.ObjectID:=ObjectID;
frm.OpenData;
frm.FormStyle:=fsMDIChild;
end
else begin
AM:=TAccessBook.Create;
AM.ObjectID:=ObjectID;
AM.Show;
end;
end;
end;
function TAccessSelectorForm.ShowModal(AParams: TParamCollection; RestoreKey: variant): TModalResult;
var
AM: TAccessBook;
frm: TBASE_SelectForm;
begin
if not CanShow then
raise EAccessException.Create('Недостаточно прав на просмотр');
if self.FormClass<>TBASE_BookForm then begin
FForm:=CreateForm;
try
frm:=Form as TBASE_SelectForm;
if Assigned(AParams) and AParams.Exists('Form.Caption') then
frm.Caption:=AParams['Form.Caption'].Value;
frm.Selector:=true;
frm.AccessManager:=self;
frm.ObjectID:=ObjectID;
if Assigned(AParams) then
frm.Params.CopyFrom(AParams);
frm.ApplyParamsBeforeOpen;
frm.OpenData;
frm.ApplyParamsAfterOpen;
if not VarIsNullMy(RestoreKey) then
frm.LocateByPrimaryKey(RestoreKey);
result:=frm.ShowModal;
FCurRecordValues:=frm.CreateCurRecordValues;
if (result=mrOK) and Assigned(AParams) then
AParams.CopyFrom(frm.Params);
if result=mrOK then begin
if frm.MainView is TcxGridDBBandedTableView then
FSelectedRecords:=TViewSelectedRecords.Create(frm.MainView as TcxGridDBBandedTableView)
else
if frm.MainView is TcxGridBandedTableViewCds then
FSelectedRecords:=TViewSelectedRecords.Create(frm.MainView as TcxGridBandedTableViewCds)
end;
finally
if FormAutoFree then begin
FForm.Free;
FForm:=nil;
end;
end;
end
else begin
AM:=TAccessBook.Create;
try
AM.ObjectID:=ObjectID;
result:=AM.ShowModal(RestoreKey, false, false);
if result=mrOK then begin
FSelectedRecords:=TViewSelectedRecords.Create();
FSelectedRecords.CopyFrom(AM.SelectedRecords);
FCurRecordValues:=TParamCollection.Create(TParamItem);
FCurRecordValues.CopyFrom(AM.CurRecordValues);
end;
finally
AM.Free;
end
end;
end;
end.
|
unit uStrList;
interface
type
TStrList = class(TObject)
private
vList : array of string;
public
Count : Integer;
constructor Create;
procedure Add(Text:string);
function Strings(Index:Integer) : string;
END;
implementation
constructor TStrList.Create;
begin
Count:=0;
SetLength(vList,Count+1);
end;
procedure TStrList.Add(Text:string);
begin
SetLength(vList,Count+1);
vList[Count]:=Text;
Inc(Count);
end;
function TStrList.Strings(Index:Integer) : string;
begin
Result:=vList[Index];
end;
END.
|
unit CCNanMakerFrm;
interface
uses
Winapi.Windows,
Winapi.Messages,
Winapi.ShellApi,//Launch browser
System.SysUtils,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ExtCtrls,
Vcl.StdCtrls,
Vcl.ComCtrls,
Vcl.Buttons,
Vcl.Imaging.Jpeg,
GLVectorGeometry, //MaxInteger
CCEditorFrm;
type
TNanMakerForm = class(TForm)
Panel1: TPanel;
SaveBtn: TSpeedButton;
ExitBtn: TSpeedButton;
HelpBtn: TSpeedButton;
TrackBar1: TTrackBar;
SizeRG: TRadioGroup;
Image1: TImage;
StopBtn: TSpeedButton;
SaveDialog1: TSaveDialog;
ClearBtn: TSpeedButton;
CARG: TRadioGroup;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ExitBtnClick(Sender: TObject);
procedure SizeRGClick(Sender: TObject);
procedure StopBtnClick(Sender: TObject);
procedure SaveBtnClick(Sender: TObject);
procedure HelpBtnClick(Sender: TObject);
procedure ClearBtnClick(Sender: TObject);
procedure Image1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure CARGClick(Sender: TObject);
procedure CAMaker;
procedure CAMaker2;
procedure CAMaker3;
procedure DLACentroid(Intensity: Integer);
procedure DLADilation;
private
{ Private declarations }
Running:Boolean;
CenterX, CenterY :Integer;
public
{ Public declarations }
end;
var
NanMakerForm: TNanMakerForm;
//==========================================================================
implementation
//==========================================================================
{$R *.DFM}
procedure TNanMakerForm.FormCreate(Sender: TObject);
begin
Running:=False;
CenterX:=64;
CenterY:=64;
end;
//Start with a Black screen.. to make the clouds on
procedure TNanMakerForm.FormShow(Sender: TObject);
begin
with Image1 do begin
Canvas.Brush.Color := clBlack;// clRed;
Canvas.Brush.Style := bsSolid;//bsDiagCross;
//Canvas.Ellipse(0, 0, Image1.Width, Image1.Height);
Canvas.FillRect(Rect(0,0,Image1.Width, Image1.Height));
Picture.Bitmap.PixelFormat:=pf24bit;
end;
end;
procedure TNanMakerForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Running:=False;
end;
procedure TNanMakerForm.ExitBtnClick(Sender: TObject);
begin
Close;
end;
procedure TNanMakerForm.SizeRGClick(Sender: TObject);
begin
Case SizeRG.ItemIndex of
0: Begin Image1.Width:=64; Image1.Height:=64;
Image1.Picture.Bitmap.Width:=64; Image1.Picture.Bitmap.Height:=64;
End;
1: Begin Image1.Width:=128; Image1.Height:=128;
Image1.Picture.Bitmap.Width:=128; Image1.Picture.Bitmap.Height:=128;
End;
2: Begin Image1.Width:=256; Image1.Height:=256;
Image1.Picture.Bitmap.Width:=256; Image1.Picture.Bitmap.Height:=256;
End;
end;
CenterX:=Image1.Width div 2;
CenterY:=Image1.Height div 2;
ClearBtnClick(Self);
end;
procedure TNanMakerForm.ClearBtnClick(Sender: TObject);
begin
with Image1 do begin
Canvas.Brush.Color := clBlack;// clRed;
Canvas.Brush.Style := bsSolid;//bsDiagCross;
//Canvas.Ellipse(0, 0, Image1.Width, Image1.Height);
Canvas.FillRect(Rect(0,0,Image1.Width, Image1.Height));
Picture.Bitmap.PixelFormat:=pf24bit;
end;
end;
procedure TNanMakerForm.StopBtnClick(Sender: TObject);
begin
Running:=False;
end;
procedure TNanMakerForm.SaveBtnClick(Sender: TObject);
begin
// Image1 is ONLY 24 bit
SaveDialog1.Filter := 'Cloud Images (*.bmp)|*.bmp';
//'CA Cloud image (*.bmp)|*.bmp';
SaveDialog1.InitialDir:=ImagePath;
//ExtractFilePath(ParamStr(0));
SaveDialog1.DefaultExt:='bmp';
SaveDialog1.Filename:='*.bmp' ;
If SaveDialog1.Execute then
Image1.picture.bitmap.SaveToFile(SaveDialog1.FileName);
end;
procedure TNanMakerForm.HelpBtnClick(Sender: TObject);
begin
ShellExecute(
Application.Handle, // handle to parent window
'open', // pointer to string that specifies operation to perform
PChar(ExtractFilePath(ParamStr(0))+'MFClouds.htm'),// pointer to filename or folder name string
'',// pointer to string that specifies executable-file parameters
//+'help'
PChar(ExtractFilePath(ParamStr(0))),// pointer to string that specifies default directory
SW_SHOWNORMAL);
end;
procedure TNanMakerForm.Image1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
CenterX:=X;
CenterY:=Y;
end;
(*************************************************************)
procedure TNanMakerForm.CARGClick(Sender: TObject);
begin
Running:=False;
Application.ProcessMessages;
Case CARG.Itemindex of
0:CAMaker;
1:DLACentroid(TrackBar1.Position);
2:DLADilation;
3:CAMaker2;
4:CAMaker3;
end;
end;
(*************************************************************)
procedure TNanMakerForm.CAMaker;
var //TbyterMax,
Tbyter,Tbyter2:Byte;
//Centroid,
x,y,StepSize2,StepSize:Integer;
//Xs,Ys,StepSizeS,TbyterMaxS:String;
begin
If Running then Exit;
Running:=True;
CenterX :=(Image1.Width )div 2;
CenterY :=(Image1.Height)div 2;
StepSize2:= Image1.Width div 2;
{with Image1.Canvas do begin
for X := 0 to Image1.Width do
for Y := 0 to Image1.Height do
begin
Centroid := random(10);
If Centroid >2 then
Pixels[X , Y]:= RGB(1,1,1);
end;
end;} {TrackBar1.Position}
StepSize:=2;
// TbyterMax:=0;
Repeat
with Image1.Canvas do
begin
for X := CenterX - Random(StepSize) to CenterX + Random(StepSize) do
for Y := CenterY - Random(StepSize) to CenterY + Random(StepSize) do
begin
Tbyter:=GetBValue(Pixels[X , Y]);
if ((Tbyter>0)and(Tbyter <255)) then
begin
inc(Tbyter,random(TrackBar1.Position)) ;
Pixels[X , Y]:=RGB(Tbyter,Tbyter,Tbyter);
// TbyterMax:=Tbyter;
end else
if (Tbyter = 0) then Pixels[X , Y]:= RGB(1,1,1)
else
if (Tbyter = 255) then
begin Tbyter2:=random(Tbyter);
Pixels[X , Y]:= RGB(Tbyter2,Tbyter2,Tbyter2);//(1,1,1);
end;
end;
// CenterX := Random(CenterX)+Random(CenterX)-Random(CenterX);
// CenterY := Random(CenterY)+Random(CenterY)-Random(CenterY);
inc(StepSize,random(TrackBar1.Position));
If StepSize > StepSize2 then StepSize:=2;
End;
(* str(CenterX, Xs); str(CenterY, Ys); {str(HighestHigh,HighS);}
str(StepSize, StepSizeS);
str(TbyterMax, TbyterMaxS);
CAMakerForm.Caption := 'X: ' + Xs + ', Y: ' + Ys +
', StepSize: ' + StepSizeS+
', TbyterMax: ' + TbyterMaxS;*)
Application.ProcessMessages;
Until Running = False;
end;
{Grow at center of screen... make a box and throw at center}
(*************************************************************)
procedure TNanMakerForm.CAMaker3;
var //TbyterMax,Tbyter2,
Tbyter:Byte;
//Centroid,
x,y,//StepSize2,
Dist2,Radius2,StepSize:Integer;
//Xs,Ys,StepSizeS,TbyterMaxS:String;
Begin;
If Running then Exit;
Running:=True;
//Make some Circles at random loacations...
Repeat
with Image1.Canvas do
begin
Radius2 := trunc(sqr(TrackBar1.Position));
Radius2 :=Radius2 *2;
StepSize:=TrackBar1.Position*2;
CenterX:=Random(Image1.Width);
CenterY:=Random(Image1.Height);
for X := CenterX - (StepSize) to CenterX + (StepSize) do
begin
for Y := CenterY - (StepSize) to CenterY + (StepSize) do
begin
Dist2 := trunc(sqr(CenterX-x)+sqr(CenterY-y));
if Dist2>=Radius2 then Continue;
Tbyter:=GetBValue(Pixels[X , Y]);
if ((Tbyter>0)and(Tbyter <246)) then
begin
inc(Tbyter,random(TrackBar1.Position)) ;
// if (Tbyter > 255) then Pixels[X , Y]:= RGB(255,255,255)else
Pixels[X , Y]:=RGB(Tbyter,Tbyter,Tbyter);
end else
if (Tbyter = 0) then Pixels[X , Y]:= RGB(1,1,1);
end;
Application.ProcessMessages;
end;
end;
Until Running = False;
End;
(*************************************************************)
procedure TNanMakerForm.CAMaker2;
var //Tbyter2, TbyterMax
Tbyter:Byte;
gx, gy, iRadius,Radius2,Dist2 : integer;
//Centroid,
CenterX2,CenterY2,
//x,y,
StepSize2,StepSize:Integer;
//Xs,Ys,StepSizeS,TbyterMaxS,CentroidS:String;
begin
If Running then Exit;
Running:=True;
StepSize2:= Image1.Width div 2;
StepSize:=2;
// TbyterMax:=0;
// Centroid :=0;
CenterX2 :=CenterX;
CenterY2 :=CenterY;
Repeat
with Image1.Canvas do
begin
// inc(Centroid);
Radius2 := trunc(sqr(TrackBar1.Position));
iRadius := trunc(TrackBar1.Position);
// for CenterX2 := 0 to Image1.Width do
// for CenterY2 := 0 to Image1.Height do
inc(CenterX2,random(TrackBar1.Position)) ;
inc(CenterY2,random(TrackBar1.Position)) ;
If ( (CenterX2>Image1.Width) or (CenterY2>Image1.Height)) then
begin
CenterX2 :=random(Image1.Width );
CenterY2 :=random(Image1.Height);
end;
begin
for gx := CenterX2-iRadius to CenterX2+iRadius do
begin
if gx<0 then continue;
if gx>=Image1.Width then continue;
for gy := CenterY2-iRadius to CenterY2+iRadius do
begin
if gy<0 then continue;
if gy>=Image1.Height then continue;
Dist2 := trunc(sqr(CenterX2-gx)+sqr(CenterY2-gy));
if Dist2>=Radius2 then Continue;
Tbyter:=GetBValue(Pixels[gX , gY]);
if ((Tbyter>0)and(Tbyter <246)) then
begin
inc(Tbyter,random(TrackBar1.Position)) ;
Pixels[gX , gY]:=RGB(Tbyter,Tbyter,Tbyter);
// TbyterMax:=Tbyter;
end else
if (Tbyter = 0) then Pixels[gX , gY]:= RGB(1,1,1)
{else
if (Tbyter = 255) then
begin Tbyter2:=random(Tbyter);
Pixels[gX , gY]:= RGB(Tbyter2,Tbyter2,Tbyter2);//(1,1,1);
end};
end;
end;
end;
inc(StepSize,random(TrackBar1.Position));
If StepSize > StepSize2 then StepSize:=2;
End;
{ str(CenterX2, Xs); str(CenterY2, Ys);
str(Centroid,CentroidS);
str(StepSize, StepSizeS);
str(TbyterMax, TbyterMaxS);
CAMakerForm.Caption := 'X: ' + Xs + ', Y: ' + Ys +
', StepSize: ' + StepSizeS+
', TbyterMax: ' + TbyterMaxS+
', #: ' + CentroidS; }
Application.ProcessMessages;
Until Running = False;
end;
(*************************************************************)
procedure TNanMakerForm.DLACentroid(Intensity: Integer);
{(Freq,F_Dim: Extended;Points,Intensity:Integer)}
var
FBackGroundColor,TempColor: TColor;
Contact: Boolean;
Spacer,TempColori,
X, Y, HighestHigh, LowestLow, RightSide, LeftSide, Stepcounter,
ICount, CenterX, CenterY, Centroid, maxcolx, maxrowy: Integer;
HighS, Xs, Ys: string;
begin
If Running then Exit;
Running:=True;
repeat
with Image1.Canvas do begin
{ Brush.Color:=FBackGroundColor;
Brush.Style:=bsSolid;
FillRect(Rect(0,0,FYImageX,FYImageY));
TempColor:=RGB(255-GetRValue(FBackGroundColor),
255-GetGValue(FBackGroundColor),
255-GetBValue(FBackGroundColor));
Pen.Color := TempColor;
Font.Color:= TempColor;
MainForm.Show;}
{Set up bottom line glue}
maxcolx := (10);
maxrowy := (10);
CenterX := (Image1.Width div 2);
CenterY := (Image1.Height div 2);
{ HighestHigh:=(CenterY+5);
LowestLow:=(CenterY-5);}
HighestHigh := (CenterY - 5);
LowestLow := (CenterY + 5);
RightSide := (CenterX + 5);
LeftSide := (CenterX - 5);
{Set up multi color line}
TempColori:=clwhite;//Random(255) mod 255;
FBackGroundColor:=ClBlack;
for X := CenterX - 2 to CenterX + 2 do begin
for Y := CenterY - 2 to CenterY + 2 do begin
TempColor := RGB(TempColori,TempColori,TempColori);
// ((Random(255)),(Random(255)),(Random(255)));
// Colors[1, (Random(255) mod 255)],
// Colors[2, (Random(255) mod 255)]);
Pixels[X, Y] := TempColor;
end;
end;
Randomize;
// bRotateImage := False; {in the Drawing...}
// bRotatingImage := True;
X := CenterX;
Y := HighestHigh;
str(X, Xs); str(Y, Ys); str(HighestHigh, HighS);
NanMakerForm.Caption := 'FX: ' + Xs + ', FY: ' + Ys +
', High: ' + HighS;
Application.ProcessMessages;
repeat
for Spacer := 1 to 100 do begin
ICount := 0;
Centroid := random(4);
if Centroid = 0 then {center + (width * random + or -)}
begin X := LeftSide;
{ Y:=(CenterY+ ( (random(maxrowy div 2)) *(random(2) -random(2)) ) );}
Y := (CenterY + ((random(maxrowy div 2)) - (random(maxrowy
div 2))));
end else
if Centroid = 1 then {center + (width * random + or -)}
begin X := RightSide;
{ Y:=(CenterY+ ( (random(maxrowy div 2)) *(random(2) -random(2))));}
Y := (CenterY + ((random(maxrowy div 2)) - (random(maxrowy
div 2))));
end else
if Centroid = 2 then {center + (width * random + or -)}
begin
{ X:=(CenterX + ( (random(maxcolx div 2)) *(random(2) -random(2))));}
X := (CenterX + ((random(maxcolx div 2)) -
(random(maxcolx div 2))));
Y := HighestHigh;
end else
if Centroid = 3 then {center + (width * random + or -)}
begin
X := (CenterX + ((random(maxcolx div 2)) -
(random(maxcolx div 2))));
Y := LowestLow;
end else ;{center + (width * random + or -)}
{ showmessage('oops 1');}
Stepcounter := 0;
Contact := True;
while ((Contact) and (Stepcounter < 2000)) do
begin {Drop bombers}
inc(Stepcounter);
case Centroid of {Keep in bounds.. always dropping}
0: begin {Left}
X := X + (Random(3) - 1);
Y := Y + (Random(3) - 1); { +(Random(2)-Random(2));}
end;
1: begin {Right}
X := X + (Random(3) - 1); { -(Random(2));}
Y := Y + (Random(3) - 1); { +(Random(2)-Random(2));}
end;
2: begin {Top}
X := X + (Random(3) - 1);
Y := Y + (Random(3) - 1); {+(Random(2));}
end;
3: begin {Bottom}
X := X + (Random(3) - 1);
Y := Y + (Random(3) - 1); { -(Random(2));}
end;
else ;{showmessage('oops');}
end; {of case}
if (X < (LeftSide - 4)) then X := LeftSide;
if (X > (RightSide + 4)) then X := RightSide;
if (Y < (HighestHigh - 4)) then Y := HighestHigh;
if (Y > (LowestLow + 4)) then Y := LowestLow;
{ HighestHigh:=(CenterY-5);
LowestLow:=(CenterY+5);
RightSide:=(CenterX+5);
LeftSide:=(CenterX-5);}
if (FBackGroundColor <> Pixels[X - 1, Y + 1]) then
begin {Contacted so accumulate}
inc(ICount); if (ICount >= Intensity) then
begin
if Y = HighestHigh then
begin HighestHigh := Y - 3; inc(maxrowy, 6); end;
if Y = LowestLow then
begin LowestLow := Y + 3; inc(maxrowy, 6); end;
if X = RightSide then
begin RightSide := X + 3; inc(maxcolx, 6); end;
if X = LeftSide then
begin LeftSide := X - 3; inc(maxcolx, 6); end;
TempColor := Pixels[X - 1, Y + 1];
Pixels[X, Y] := TempColor;
Contact := False;
end;
end; { else}
if (FBackGroundColor <> Pixels[X - 1, Y - 1]) then
begin {Contacted so accumulate}
inc(ICount); if (ICount = Intensity) then begin
if Y = HighestHigh then
begin HighestHigh := Y - 3; inc(maxrowy, 6); end;
if Y = LowestLow then
begin LowestLow := Y + 3; inc(maxrowy, 6); end;
if X = RightSide then
begin RightSide := X + 3; inc(maxcolx, 6); end;
if X = LeftSide then
begin LeftSide := X - 3; inc(maxcolx, 6); end;
TempColor := Pixels[X - 1, Y - 1];
Pixels[X, Y] := TempColor;
Contact := False;
end; end; { else}
if (FBackGroundColor <> Pixels[X + 1, Y - 1]) then
begin {Contacted so accumulate}
inc(ICount); if (ICount >= Intensity) then begin
if Y = HighestHigh then
begin HighestHigh := Y - 3; inc(maxrowy, 6); end;
if Y = LowestLow then
begin LowestLow := Y + 3; inc(maxrowy, 6); end;
if X = RightSide then
begin RightSide := X + 3; inc(maxcolx, 6); end;
if X = LeftSide then
begin LeftSide := X - 3; inc(maxcolx, 6); end;
TempColor := Pixels[X + 1, Y - 1];
Pixels[X, Y] := TempColor;
Contact := False;
end; end; { else}
if (FBackGroundColor <> Pixels[X + 1, Y + 1]) then
begin {Contacted so accumulate}
inc(ICount); if (ICount >= Intensity) then begin
if Y = HighestHigh then
begin HighestHigh := Y - 3; inc(maxrowy, 6); end;
if Y = LowestLow then
begin LowestLow := Y + 3; inc(maxrowy, 6); end;
if X = RightSide then
begin RightSide := X + 3; inc(maxcolx, 6); end;
if X = LeftSide then
begin LeftSide := X - 3; inc(maxcolx, 6); end;
TempColor := Pixels[X + 1, Y + 1];
Pixels[X, Y] := TempColor;
Contact := False;
end; end; { else}
if (FBackGroundColor <> Pixels[X - 1, Y]) then
begin {Contacted so accumulate}
inc(ICount); if (ICount >= Intensity) then begin
if Y = HighestHigh then
begin HighestHigh := Y - 3; inc(maxrowy, 6); end;
if Y = LowestLow then
begin LowestLow := Y + 3; inc(maxrowy, 6); end;
if X = RightSide then
begin RightSide := X + 3; inc(maxcolx, 6); end;
if X = LeftSide then
begin LeftSide := X - 3; inc(maxcolx, 6); end;
TempColor := Pixels[X - 1, Y];
Pixels[X, Y] := TempColor;
Contact := False;
end; end; { else}
if (FBackGroundColor <> Pixels[X + 1, Y]) then
begin {Contacted so accumulate}
inc(ICount); if (ICount >= Intensity) then begin
if Y = HighestHigh then
begin HighestHigh := Y - 3; inc(maxrowy, 6); end;
if Y = LowestLow then
begin LowestLow := Y + 3; inc(maxrowy, 6); end;
if X = RightSide then
begin RightSide := X + 3; inc(maxcolx, 6); end;
if X = LeftSide then
begin LeftSide := X - 3; inc(maxcolx, 6); end;
TempColor := Pixels[X + 1, Y];
Pixels[X, Y] := TempColor;
Contact := False;
end; end; { else}
if (FBackGroundColor <> Pixels[X, Y + 1]) then
begin {Contacted so accumulate}
inc(ICount); if (ICount >= Intensity) then begin
if Y = HighestHigh then
begin HighestHigh := Y - 3; inc(maxrowy, 6); end;
if Y = LowestLow then
begin LowestLow := Y + 3; inc(maxrowy, 6); end;
if X = RightSide then
begin RightSide := X + 3; inc(maxcolx, 6); end;
if X = LeftSide then
begin LeftSide := X - 3; inc(maxcolx, 6); end;
TempColor := Pixels[X, Y + 1];
Pixels[X, Y] := TempColor;
Contact := False;
end; end; { else}
if (FBackGroundColor <> Pixels[X, Y - 1]) then
begin {Contacted so accumulate}
inc(ICount); if (ICount >= Intensity) then begin
if Y = HighestHigh then
begin HighestHigh := Y - 3; inc(maxrowy, 6); end;
if Y = LowestLow then
begin LowestLow := Y + 3; inc(maxrowy, 6); end;
if X = RightSide then
begin RightSide := X + 3; inc(maxcolx, 6); end;
if X = LeftSide then
begin LeftSide := X - 3; inc(maxcolx, 6); end;
TempColor := Pixels[X, Y - 1];
Pixels[X, Y] := TempColor;
Contact := False;
end; end;
{str(X,Xs);str(Y,Ys); str(StepCounter,HighS);
MainForm.HiddenFX.Caption:='FX: '+Xs+', FY: '+Ys+', Count: '+HighS;
Application.ProcessMessages;}
end; {end of while}
end; {of spacer}
str(X, Xs); str(Y, Ys); {str(HighestHigh,HighS);}
str(StepCounter, HighS);
NanMakerForm.Caption := 'FX: ' + Xs + ', FY: ' + Ys +
', High: ' + HighS;
Application.ProcessMessages;
until (//(Running = False) or
(HighestHigh < 7) or (LowestLow > Image1.Height)
or (RightSide > Image1.Width) or (LeftSide < 7));
end;
Application.ProcessMessages;
until (Running = False)
end;
(*************************************************************)
procedure TNanMakerForm.DLADilation;
function SpawnBitmap(Width,Height :Integer) : TBitmap;
begin
Result:=TBitmap.Create;
//Result.PixelFormat:=pf32bit;
Result.Width:=Width;
Result.Height:=Height;
with Result do begin
Canvas.Brush.Color := clBlack;// clRed;
Canvas.Brush.Style := bsSolid;//bsDiagCross;
Canvas.FillRect(Rect(0,0,Result.Width, Result.Height));
Result.PixelFormat:=pf24bit;
end;
end;
var
StepCounter,
x, y, sx, sy : Integer;
bmp//, bmAlpha
: TBitmap;
HighS:String;
// maxNeighbour,
Temp : Integer;
begin
If Running then Exit;
Running:=True;
StepCounter:=0;
// make fully transparent all pixels in the color for all pixels in the alpha map
// that are adjacent to a fully transparent one
// bmAlpha:=IMAlpha.Picture.Bitmap;
repeat
begin
sx := (Image1.Width);
sy := (Image1.Height );
bmp:=SpawnBitmap(sx,sy);
bmp.assign(Image1.picture.bitmap);
// for y:=0 to sy-1 do
begin
// for x:=0 to sx-1 do with Image1.Canvas do
with Image1.Canvas do begin
{ if Pixels[x, y]<clWhite then
begin //MaxIntValue MaxInteger
maxNeighbour:=MaxInteger(MaxInteger(Pixels[x, y-1], Pixels[x, y+1]),
MaxInteger(Pixels[x-1, y], Pixels[x+1, y]));
bmp.Canvas.Pixels[x, y]:=MaxInteger(maxNeighbour, Pixels[x, y]);
end;// else// bmp.Canvas.Pixels[x, y]:=clWhite;}
x :=random(Image1.Width );
y :=random(Image1.Height);
if Pixels[x, y]> clBlack then
begin
bmp.Canvas.Pixels[x, y]:=Pixels[x, y];//clWhite;
Temp:=GetRValue(Pixels[x, y-1])+1;If Temp>255 then Temp:=255;
bmp.Canvas.Pixels[x, y-1]:=RGB(Temp,Temp,Temp);
Temp:=GetRValue(Pixels[x, y+1])+1;If Temp>255 then Temp:=255;
bmp.Canvas.Pixels[x, y+1]:=RGB(Temp,Temp,Temp);
Temp:=GetRValue(Pixels[x+1, y])+1;If Temp>255 then Temp:=255;
bmp.Canvas.Pixels[x+1, y]:=RGB(Temp,Temp,Temp);
Temp:=GetRValue(Pixels[x-1, y])+1;If Temp>255 then Temp:=255;
bmp.Canvas.Pixels[x-1, y]:=RGB(Temp,Temp,Temp);
{
Pixels[x-1, y]
Pixels[x-1, y-1]
Pixels[x-1, y+1]
Pixels[x+1, y]
Pixels[x+1, y-1]
Pixels[x+1, y+1]}
end;
end;
end;
Image1.Picture.Bitmap:=bmp;
bmp.Free;
// TextureChanged;
inc(StepCounter);
str(StepCounter, HighS);
NanMakerForm.Caption := HighS;
Application.ProcessMessages;
end;
until (Running = False);
end;
(*************************************************************)
(*************************************************************)
(*************************************************************)
end.
|
unit frmCadastrarProduto;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Mask, Vcl.DBCtrls,
Vcl.Buttons;
type
TfrmCadastrarProdutos = class(TForm)
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
edNomeProduto: TEdit;
edValCompra: TEdit;
edCodBarras: TEdit;
btnNovo: TBitBtn;
btnCancelar: TBitBtn;
btnSalvar: TBitBtn;
btnSair: TBitBtn;
edDataCadastro: TMaskEdit;
edDataAtualizacao: TMaskEdit;
edPrecoUnitario: TMaskEdit;
procedure FormShow(Sender: TObject);
procedure StatusEdits(prmStatus: Boolean);
procedure btnSairClick(Sender: TObject);
procedure btnNovoClick(Sender: TObject);
procedure btnSalvarClick(Sender: TObject);
procedure edPrecoUnitarioExit(Sender: TObject);
procedure edValCompraExit(Sender: TObject);
procedure edCodBarrasExit(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure LimparEdits();
procedure EnableBotoes(prmEnable: Boolean);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmCadastrarProdutos: TfrmCadastrarProdutos;
implementation
{$R *.dfm}
uses frmDataModulo, Funcoes, untInterfaces, untClasses;
procedure TfrmCadastrarProdutos.StatusEdits(prmStatus: Boolean);
begin
edNomeProduto.Enabled := prmStatus;
edPrecoUnitario.Enabled := prmStatus;
edValCompra.Enabled := prmStatus;
edCodBarras.Enabled := prmStatus;
end;
procedure TfrmCadastrarProdutos.btnSairClick(Sender: TObject);
begin
Close;
end;
procedure TfrmCadastrarProdutos.btnSalvarClick(Sender: TObject);
var
LocSalvarProduto: ISalvarNovoProduto;
begin
LocSalvarProduto := TSalvarNovoProduto.Create();
//Testando Nome do Produto
if edNomeProduto.Text = '' then
begin
MessageDlg('Favor digitar o nome do produto!',mtConfirmation,[mbOK], 0);
edNomeProduto.SetFocus;
Exit;
end;
//Testando o valor de Compra
if edValCompra.Text = '' then
begin
MessageDlg('Favor digitar valor de compra!',mtConfirmation,[mbOK], 0);
edValCompra.SetFocus;
Exit;
end;
//Testando Preço Unitário
if edPrecoUnitario.Text = '' then
begin
MessageDlg('Favor digitar o preço!',mtConfirmation,[mbOK], 0);
edPrecoUnitario.SetFocus;
Exit;
end;
//Salvando o produto
if not LocSalvarProduto.Salvar(edNomeProduto.Text, edDataCadastro.text,
edDataAtualizacao.text, edPrecoUnitario.Text, edValCompra.Text,
edCodBarras.Text) then
begin
MessageDlg('Erro ao salvar novo produto!',mtConfirmation,[mbOK], 0);
edPrecoUnitario.SetFocus;
Exit;
end;
MessageDlg('Produto Salvo com Sucesso',mtConfirmation,[mbOK], 0);
StatusEdits(False);
LimparEdits();
EnableBotoes(true);
btnNovo.SetFocus();
end;
procedure TfrmCadastrarProdutos.btnCancelarClick(Sender: TObject);
begin
StatusEdits(False);
LimparEdits();
btnCancelar.Enabled := False;
btnSalvar.Enabled := False;
btnNovo.Enabled := True;
btnNovo.SetFocus();
end;
procedure TfrmCadastrarProdutos.btnNovoClick(Sender: TObject);
begin
StatusEdits(true);
EnableBotoes(false);
edDataCadastro.Text := DateToStr(date);
edDataAtualizacao.Text := DateToStr(date);
edNomeProduto.SetFocus();
end;
procedure TfrmCadastrarProdutos.edCodBarrasExit(Sender: TObject);
var
LocCodBarras: ICodigoBarraExistente;
begin
LocCodBarras:= TCodigoBarraExistente.Create();
if LocCodBarras.Existe(edCodBarras.Text) then
begin
MessageDlg('Código de barras cadastrado em outro produto!',mtConfirmation,[mbOK], 0);
edCodBarras.SetFocus;
end;
end;
procedure TfrmCadastrarProdutos.edPrecoUnitarioExit(Sender: TObject);
var
LocValor: String;
begin
if edPrecoUnitario.Text <> '' then
begin
if not IsDouble(edPrecoUnitario.Text) then
begin
MessageDlg('Favor digitar valor válido!',mtConfirmation,[mbOK], 0);
edPrecoUnitario.SetFocus();
end;
end;
end;
procedure TfrmCadastrarProdutos.edValCompraExit(Sender: TObject);
begin
if edValCompra.Text <> '' then
begin
if not IsDouble(edValCompra.Text) then
begin
MessageDlg('Favor digitar valor válido!',mtConfirmation,[mbOK], 0);
edValCompra.SetFocus();
end;
end;
end;
procedure TfrmCadastrarProdutos.EnableBotoes(prmEnable: Boolean);
begin
btnNovo.Enabled := prmEnable;
btnCancelar.Enabled := not prmEnable;
btnSalvar.Enabled := not prmEnable;
end;
procedure TfrmCadastrarProdutos.FormShow(Sender: TObject);
begin
StatusEdits(False);
end;
procedure TfrmCadastrarProdutos.LimparEdits;
begin
edNomeProduto.Clear();
edValCompra.Clear();
edCodBarras.Clear();
edDataCadastro.Clear();
edDataAtualizacao.Clear();
edPrecoUnitario.Clear();
end;
end.
|
unit FHIRPluginErrors;
interface
uses
AdvObjects, AdvGenerics, System.Generics.Defaults;
const
INDIC_INFORMATION = 28;
INDIC_WARNING = 28;
INDIC_ERROR = 28;
type
TValidationError = class (TAdvObject)
private
FLevel: integer;
FMessage: String;
FStop: integer;
FStart: integer;
public
Constructor create(level : integer; start, stop : integer; message : String); overload;
property level : integer read FLevel write FLevel;
property start : integer read FStart write FStart;
property stop : integer read FStop write FStop;
property message : String read FMessage write FMessage;
end;
TValidationErrorComparer = class (TAdvObject, IComparer<TValidationError>)
public
function Compare(const Left, Right: TValidationError): Integer;
end;
implementation
{ TValidationErrorComparer }
function TValidationErrorComparer.Compare(const Left, Right: TValidationError): Integer;
begin
if (left.FStart < Right.FStart) then
result := -1
else if (left.FStart > Right.FStart) then
result := 1
else if (left.FStop < Right.FStop) then
result := -1
else if (left.FStop > Right.FStop) then
result := 1
else if (left.FLevel < Right.FLevel) then
result := -1
else if (left.FLevel > Right.FLevel) then
result := 1
else
result := 0;
end;
{ TValidationError }
constructor TValidationError.create(level: integer; start, stop: integer; message: String);
begin
Create;
self.level := level;
self.start := start;
self.stop := stop;
self.message := message;
end;
end.
|
unit ed2k;
interface
uses md4;
const
ED2K_CHUNK_SIZE = 9728000;
type
Ed2kContext = record
Md4: Md4Context;
chunks: array of MD4Digest;
chunk_size: integer;
end;
procedure Ed2kInit( var Context: Ed2kContext );
procedure Ed2kFinal( var Context: Ed2kContext; var Digest: MD4Digest );
procedure Ed2kChunkUpdate( var Context: Ed2kContext; lpData: pointer; wwDataSize: integer );
procedure Ed2kNextChunk2( var Context: Ed2kContext; out Digest: MD4Digest );
procedure Ed2kNextChunk( var Context: Ed2kContext );
implementation
procedure Ed2kInit( var Context: Ed2kContext );
begin
MD4Init(Context.Md4);
SetLength(Context.chunks, 0);
Context.chunk_size := 0;
end;
procedure Ed2kChunkUpdate( var Context: Ed2kContext; lpData: pointer; wwDataSize: integer );
begin
Context.chunk_size := Context.chunk_size + wwDataSize;
MD4Update(Context.Md4, PAnsiChar(lpData), wwDataSize);
end;
procedure Ed2kNextChunk( var Context: Ed2kContext );
var Digest: MD4Digest;
begin
Ed2kNextChunk2(Context, Digest);
end;
//Allows to get current chunk md4, in case you need it.
procedure Ed2kNextChunk2( var Context: Ed2kContext; out Digest: MD4Digest );
begin
MD4Final( Context.Md4, Digest );
with Context do begin
SetLength(chunks, Length(chunks) + 1);
chunks[Length(chunks)-1] := Digest;
end;
MD4Init( Context.Md4 );
Context.chunk_size := 0;
end;
procedure Ed2kFinal( var Context: Ed2kContext; var Digest: MD4Digest );
begin
//Close last chunk (maybe zero-sized)
Ed2kNextChunk(Context);
//If there's exactly one chunk, we just use it's md4
if Length(Context.chunks) = 1 then begin
Digest := Context.chunks[0];
exit;
end;
MD4Init( Context.Md4 );
MD4Update( Context.Md4, @Context.chunks[0], Length(Context.chunks)*SizeOf(Md4Digest) );
MD4Final( Context.Md4, Digest );
end;
end.
|
unit UtilClass;
interface
uses
windows,
messages,
UtilFunc,
ShellAPI,
CommDlg;
//------------------------------------------------------------
// Global Types, Constants and Variables
//------------------------------------------------------------
type
TOpenSave = record
FullName:string;
FileName:string;
Path:string;
Ext:string;
end;
//------------------------------------------------------------
// Classes
//------------------------------------------------------------
//----------------- TIntegerList ------------------------------
const
MaxItem = 200000;
type
TIntegerArray = array[0..MaxItem] of Integer;
PIntegerArray = ^TIntegerArray;
TIntegerList = class(TObject)
private
FPointer: PIntegerArray;
FCount: integer;
FSize: integer;
FReAllocSize: integer;
FInitialSize: integer;
function GetItem(index: integer):Integer;
procedure SetItem(index: integer; value: Integer);
function GetCount: integer;
function GetRealSize: integer;
protected
public
constructor Create(InitialSize,ReAllocSize:integer);virtual;
destructor Destroy; override;
procedure Clear;
procedure Add(value:Integer);
procedure Delete(index: integer);
procedure Insert(index: integer; value: Integer);
function Search(value: Integer): integer;
procedure CopyTo(var IL: TIntegerList);
property Item[i:integer]:Integer read GetItem write SetItem;default;
property Count: integer read GetCount;
property Size: integer read FSize;
property RealSize: integer read GetRealSize;
end;
//------------------ TMessageDispatcher ----------------------
TSubClass = class; // forward
TMessageDispatcher = class(TObject)
private
FSList: TIntegerList;
FParentList: TIntegerList;
FParentProc: TIntegerList;
FMessageList: TIntegerList;
FMessageObject: TIntegerList;
FCopyList: TIntegerList;
FCopyList2: TIntegerList;
FNeedCopy: Boolean;
function GetCount:integer;
protected
function IsNewParent(hWindow:HWND):Boolean;
function IsParent(hWindow:HWND):Boolean;
function GetParentProc(hWindow:HWND):TFNWndProc;
public
constructor Create;
destructor Destroy; override;
procedure DefaultHandler(var Message);override;
procedure Add(Obj:TSubClass);
procedure Delete(Obj:TSubClass);
procedure TrapMessage(Msg: UINT; Obj: TSubClass);
property Count: integer read GetCount;
end;
//------------------ TSubClass -------------------------------
TSubClass = class(TObject)
private
FParent: HWND;
FData: integer;
protected
public
constructor Create(hParent:HWND); virtual;
destructor Destroy; override;
property Parent: HWND read FParent;
property Data : integer read FData write FData;
end;
//----------------- TAPITimer -------------------------------------------
TAPITimer = class(TSubClass)
private
FInterval : integer;
FOnTimer: TNotifyMessage;
FIsOn : Boolean;
public
constructor Create(hParent: HWND); override;
destructor Destroy; override;
procedure DefaultHandler(var AMessage); override;
procedure On;
procedure Off;
property IsOn: Boolean read FIsOn;
property Interval: integer read FInterval write FInterval;
property OnTimer: TNotifyMessage read FOnTimer write FOnTimer;
end;
//----------------- TStringArray -------------------------------------
TStringArray = class(TObject)
private
PCharArray : TIntegerList;
FCount: integer;
function GetItems(index:integer): string;
procedure SetItem(index: integer;value:string);
function GetCount: integer;
protected
public
constructor Create; virtual;
destructor Destroy; override;
property Items[i:integer]:string read GetItems write SetItem;default;
property Count: integer read GetCount;
procedure Add(value:string);
procedure Clear;
procedure Delete(index: integer);
procedure Insert(index: integer; value: string);
function Search(s:string):integer;
procedure Exchange(i,j: integer);
procedure Sort;
end;
function APICompareString(S1,S2: string): integer;
procedure StringQuickSort(SS: TStringArray;l,r: Integer);
//------------- TAPIDragDrop ----------------------------------------------
type
TAPIDragDrop = class(TSubClass)
private
FFiles: TStringArray;
FFileCount : integer;
FOnDrop: TNotifyMessage;
function GetFiles(i: integer): string;
public
constructor Create(hParent:HWND); override;
destructor Destroy; override;
procedure DefaultHandler(var Message);override;
procedure SetFocus(hWnd: HWND);
property FileCount: integer read FFileCount;
property Files[i: integer]: string read GetFiles;
property OnDrop: TNotifyMessage read FOnDrop write FOnDrop;
end;
//------------- TGridArranger ----------------------------------------------
TGridArranger = class(TSubClass)
private
FNumCol: integer;
FNumRow: integer;
FXMargin: integer;
FYMargin: integer;
FXSep: integer;
FYSep: integer;
FOnSize: TNotifyMessage;
public
constructor Create(hParent: HWND); override;
procedure DefaultHandler(var Message);override;
function Arrange(Row,Col: integer): TRect;
function CenterArrange(Row,Col:integer;Dim: TRect): TRect;
property NumCol: integer read FNumCol write FNumCol;
property NumRow: integer read FNumRow write FNumRow;
property XMargin: integer read FXMargin write FXMargin;
property YMargin: integer read FYMargin write FYMargin;
property XSep: integer read FXSep write FXSep;
property YSep: integer read FYSep write FYSep;
property OnSize: TNotifyMessage read FOnSize write FOnSize;
end;
//------------- TBorderArranger ----------------------------------------------
TBorderPos = (bpUpper,bpLower,bpLeft,bpRight,bpCenter);
TBorderArranger = class(TSubClass)
private
FUpperHeight: integer;
FLowerHeight: integer;
FLeftWidth: integer;
FRightWidth: integer;
FXMargin: integer;
FYMargin: integer;
FXSep: integer;
FYSep: integer;
FOnSize: TNotifyMessage;
public
constructor Create(hParent: HWND); override;
procedure DefaultHandler(var Message);override;
function Arrange(BorderPos:TBorderPos): TRect;
property UpperHeight: integer read FUpperHeight write FUpperHeight;
property LowerHeight: integer read FLowerHeight write FLowerHeight;
property LeftWidth: integer read FLeftWidth write FLeftWidth;
property RightWidth: integer read FRightWidth write FRightWidth;
property XMargin: integer read FXMargin write FXMargin;
property YMargin: integer read FYMargin write FYMargin;
property XSep: integer read FXSep write FXSep;
property YSep: integer read FYSep write FYSep;
property OnSize: TNotifyMessage read FOnSize write FOnSize;
end;
//------------- MessageTrapper ---------------------------------
TMessageTrapper = class(TSubClass)
private
FTrapMessage: TIntegerList;
FHandler: TIntegerList;
FNumTrap: integer;
public
constructor Create(hParent: HWND); override;
destructor Destroy; override;
procedure DefaultHandler(var Message);override;
procedure TrapMessage(TrapMsg: UINT; Handler: TNotifyMessage);
end;
//------------- TAPIGFont -----------------------------------------------
TAPIGFont = class(TObject)
private
FLogFont: TLogFont;
FHandle: HFONT;
FPrevHandle: HFONT;
FName: string;
FSize: integer;
FEscapement: integer;
FBold: Boolean;
FItalic: Boolean;
FUnderline: Boolean;
FStrikeOut: Boolean;
FColor: COLORREF;
procedure SetLogFont(value: TLogFont);
function GetLogFont: TLogFont;
public
constructor Create;
procedure SelectHandle(DC: HDC);
procedure DeleteHandle(DC: HDC);
property LogFont: TLogFont read GetLogFont write SetLogFont;
property Name: string read FName write FName;
property Size: integer read FSize write FSize;
property Escapement: integer read FEscapement write FEscapement;
property Bold: Boolean read FBold write FBold;
property Italic: Boolean read FItalic write FItalic;
property Underline: Boolean read FUnderline write FUnderline;
property StrikeOut: Boolean read FStrikeOut write FStrikeOut;
property Color: COLORREF read FColor write FColor;
end;
//------------- TAPICFont -----------------------------------------------
TAPICFont = class(TAPIGFont)
public
destructor Destroy; override;
procedure GetHandle;
procedure SetHandle(ctlHandle: HWND);
procedure ResetHandle(ctlHandle: HWND);
property Handle: HFONT read FHandle;
end;
//------------- File Function -----------------------------------------
function AExtractFileName(s: string):string;
function AExtractDir(s: string): string;
function AExtractExt(s: string): string;
procedure FindAllFilesWithExt(dir,ext:string;SL:TStringArray);
procedure FindAllFiles(dir:string;SL:TStringArray);
function GetFileSize(FullPath: string): integer;
function GetFileCreationTime(FullPath: string): TSystemTime;
function GetFileLastAccessTime(FullPath: string): TSystemTime;
function GetFileLastWriteTime(FullPath: string): TSystemTime;
function GetFileAttributes(FullPath: string): DWORD;
procedure DisplayLogFont(lf: TLogFont; SA: TStringArray);
function GetOpenFile(hOwner:HWND;defName,Filter,initDir:string;
var FLN:TOpenSave):Boolean;
function GetSaveFile(hOwner:HWND;defName,Filter,initDir:string;
var FLN:TOpenSave):Boolean;
function GetOpenFileMult(hOwner:HWND;defName,Filter,initDir:string;
STL:TStringArray;var NumFile:integer):Boolean;
function SHCopyFile(hParent:HWND;NameFrom,NameTo:string):Boolean;
function SHMoveFile(hParent:HWND;NameFrom,NameTo:string):Boolean;
function SHRenameFile(hParent:HWND;NameFrom,NameTo:string):Boolean;
function SHDeleteFile(hParent:HWND;Name:string):Boolean;
procedure FindAllDirInDir(dir:string;SL:TStringArray);
function IsFileExist(FN: string):Boolean;
function CreateDir(DN:string):Boolean;
function RemoveDirAll(DN:string):Boolean;
procedure FindAllFilesWithSubdir(DN:string;SL:TStringArray);
function SHCopyDir(hParent:HWND;NameFrom,NameTo:string):Boolean;
function SHDeleteDir(hParent:HWND;Name:string):Boolean;
//------------------------------------------------------------
// Create Functions
//------------------------------------------------------------
function CreateTimer(hParent:HWND; Intrvl: integer;
OnTimerFunc: TNotifyMessage):TAPITimer;
function CreateGridArranger(hParent:HWND;iRow,iCol,XMrgn,YMrgn,
XSp,YSp:integer; sOnSize:TNotifyMessage): TGridArranger;
function CreateBorderArranger(hParent:HWND;UH,LH,LW,RW,XMrgn,YMrgn,
XSp,YSp:integer; sOnSize:TNotifyMessage): TBorderArranger;
var
Dispatcher: TMessageDispatcher;
implementation
//------------------------------------------------------------
// Classes
//------------------------------------------------------------
//----------------- TIntegerList ------------------------------
constructor TIntegerList.Create(InitialSize,ReAllocSize:integer);
begin
if ReAllocSize = 0 then FReAllocSize := $10 else FReAllocSize := ReAllocSize;
if InitialSize = 0 then FInitialSize := $10 else FInitialSize := InitialSize;
FSize := FInitialSize;
GetMem(FPointer,SizeOf(Integer)*FSize);
FCount := -1;
end;
destructor TIntegerList.Destroy;
begin
FreeMem(FPointer);
inherited Destroy;
end;
procedure TIntegerList.Clear;
begin
FreeMem(FPointer);
FSize := FInitialSize;
GetMem(FPointer,SizeOf(Integer)*FSize);
FCount := -1;
end;
procedure TIntegerList.Add(value:Integer);
begin
Inc(FCount);
if FCount > FSize-1 then begin
Inc(FSize,FReAllocSize);
ReAllocMem(FPointer,SizeOf(Integer)*FSize);
end;
FPointer^[FCount] := value;
end;
procedure TIntegerList.Delete(index: integer);
begin
if (index > FCount) or (index < 0) then Exit;
if index = FCount then begin
Dec(FCount);
Exit;
end;
Move(FPointer^[index+1],FPointer^[index],
SizeOf(Integer)*(FCount-index));
Dec(FCount);
end;
procedure TIntegerList.Insert(index: integer; value: Integer);
begin
if (index > FCount) or (index < 0) then Exit;
if FCount+1 > FSize-1 then begin
Inc(FSize,FReAllocSize);
ReAllocMem(FPointer,SizeOf(Integer)*FSize);
end;
Move(FPointer^[index],FPointer^[index+1],
SizeOf(Integer)*(FCount-index+1));
FPointer^[index] := value;
Inc(FCount);
end;
function TIntegerList.GetItem(index: integer):Integer;
begin
if (index > FCount) or (index < 0) then
result := 0
else
result := FPointer^[index];
end;
procedure TIntegerList.SetItem(index: integer; value: Integer);
begin
if index > FSize-1 then begin
repeat
Inc(FSize,FReAllocSize);
until index < FSize-1;
ReAllocMem(FPointer,SizeOf(Integer)*FSize);
end;
FPointer^[index] := value;
if FCount < index then FCount := index;
end;
function TIntegerList.GetCount: integer;
begin
result := FCount+1;
end;
function TIntegerList.GetRealSize: integer;
begin
result := FSize;
end;
function TIntegerList.Search(value: Integer): integer;
var
i: integer;
begin
for i := 0 to FCount do
if FPointer^[i] = value then begin
result := i;
Exit;
end;
result := -1;
end;
procedure TIntegerList.CopyTo(var IL: TIntegerList);
var
i: integer;
begin
IL.Clear;
for i := 0 to FCount do
IL[i] := FPointer^[i];
end;
//------------------ TMessageDispatcher ----------------------
function SubClassProc(hParent: HWND; Msg: UINT;
wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
var
AMsg: TMessage;
OriginalProc: TFNWndProc;
begin
result := 0;
if not Dispatcher.IsParent(hParent) then Exit;
OriginalProc := Dispatcher.GetParentProc(hParent);
result := CallWindowProc(OriginalProc,hParent,Msg,wParam,lParam);
AMsg.Msg := Msg;
AMsg.WParam := wParam;
AMsg.LParam := lParam;
AMsg.Result := hParent;
case Msg of
WM_DESTROY: begin
SetWindowLong(hParent,GWL_WNDPROC,integer(OriginalProc));
Dispatcher.Dispatch(AMsg);
end;
else
Dispatcher.Dispatch(AMsg);
end; // case
if AMsg.Result <> 0 then result := AMsg.Result;
end;
constructor TMessageDispatcher.Create;
begin
FSList := TIntegerList.Create($10,$10);
FParentList := TIntegerList.Create($10,$10);
FParentProc := TIntegerList.Create($10,$10);
FMessageList := TIntegerList.Create($10,$10);
FMessageObject := TIntegerList.Create($10,$10);
FCopyList := TIntegerList.Create($10,$10);
FCopyList2 := TIntegerList.Create($10,$10);
FNeedCopy := false;
end;
destructor TMessageDispatcher.Destroy;
begin
FNeedCopy := false;
FSList.Free;
FParentList.Free;
FParentProc.Free;
FMessageList.Free;
FMessageObject.Free;
FCopyList.Free;
FCopyList2.Free;
inherited Destroy;
end;
procedure TMessageDispatcher.DefaultHandler(var Message);
var
AMsg: TMessage;
hParent: HWND;
i: integer;
SO: TSubClass;
begin
AMsg := TMessage(Message);
hParent := AMsg.Result;
TMessage(Message).result := 0; // default return result
AMsg.Result := 0; // default object return
if AMsg.Msg = WM_DESTROY then begin
for i := FSList.Count-1 downto 0 do begin
SO := TSubClass(FSList[i]);
if Assigned(SO) then
if (SO.Parent = hParent) then begin
FSList.Delete(i);
SO.Free; //SO := nil;
end;
end;
FParentProc.Delete(FParentList.Search(hParent));
FParentList.Delete(FParentList.Search(hParent));
exit;
end;
if FMessageList.Search(AMsg.Msg) = -1 then
exit
else begin
if FNeedCopy then begin
FMessageList.CopyTo(FCopyList);
FMessageObject.CopyTo(FCopyList2);
FNeedCopy := false;
end;
for i := 0 to FCopyList.Count-1 do
if DWORD(FCopyList[i]) = AMsg.Msg then begin
SO := TSubClass(FCopyList2[i]);
if Assigned(SO) then
if (SO.Parent = hParent) then begin
SO.Dispatch(AMsg);
if AMsg.Result <> 0 then begin
TMessage(Message).result := AMsg.Result;
exit;
end;
end;
end;
end;
end;
procedure TMessageDispatcher.TrapMessage(Msg: UINT; Obj: TSubClass);
begin
FMessageList.Add(Msg);
FMessageObject.Add(integer(Obj));
FNeedCopy := true;
end;
function TMessageDispatcher.IsNewParent(hWindow:HWND):Boolean;
begin
result := true;
if FParentList.Count < 1 then Exit;
if FParentList.Search(hWindow) > -1 then result := false;
end;
function TMessageDispatcher.IsParent(hWindow:HWND):Boolean;
begin
result := false;
if FParentList.Count < 1 then Exit;
if FParentList.Search(hWindow) = -1 then
result := false
else
result := true;
end;
function TMessageDispatcher.GetParentProc(hWindow:HWND):TFNWndProc;
begin
result := TFNWndProc(FParentProc[FParentList.Search(hWindow)]);
end;
procedure TMessageDispatcher.Add(Obj:TSubClass);
var
OriginalProc: integer;
begin
FSList.Add(Integer(Obj));
if IsNewParent(Obj.Parent) then begin
FParentList.Add(Obj.Parent);
OriginalProc := GetWindowLong(Obj.Parent,GWL_WNDPROC);
FParentProc.Add(OriginalProc);
SetWindowLong(Obj.Parent,GWL_WNDPROC,integer(@SubClassProc));
end;
end;
procedure TMessageDispatcher.Delete(Obj:TSubClass);
var
i: integer;
begin
FSList.Delete(FSList.Search(Integer(Obj)));
for i := FMessageObject.Count-1 downto 0 do
if FMessageObject[i] = integer(Obj) then begin
FMessageObject.Delete(i); // UnTrap Message
FMessageList.Delete(i);
end;
FNeedCopy := true;
end;
function TMessageDispatcher.GetCount:integer;
begin
result := FSList.Count;
end;
//------------------ TSubClass -------------------------------
constructor TSubClass.Create(hParent:HWND);
begin
if not Assigned(Dispatcher) then Dispatcher := TMessageDispatcher.Create;
FParent := hParent;
Dispatcher.Add(self);
end;
destructor TSubClass.Destroy;
begin
Dispatcher.Delete(self);
inherited Destroy;
end;
//----------------- TAPITimer -------------------------------------------
constructor TAPITimer.Create(hParent: HWND);
begin
inherited Create(hParent);
Dispatcher.TrapMessage(WM_TIMER,self);
FInterval := 1000;
FIsOn := false;
end;
destructor TAPITimer.Destroy;
begin
Off;
inherited Destroy;
end;
procedure TAPITimer.On;
begin
if FIsOn = true then exit;
FIsOn := true;
// TimerID に 自分のオブジェクト参照を渡す!!
SetTimer(Parent,integer(self),FInterval,nil);
end;
procedure TAPITimer.Off;
begin
if FIsOn = false then exit;
FIsOn := false;
KillTimer(Parent,integer(self));
end;
procedure TAPITimer.DefaultHandler(var AMessage);
var
AMsg: TMessage;
begin
AMsg := TMessage(AMessage);
if AMsg.Msg = WM_TIMER then
if AMsg.WParam = integer(self) then begin
AMsg.Msg := UINT(self); // sender
if Assigned(FOnTimer) then OnTimer(AMsg);
end;
end;
//----------------- TStringArray -------------------------------------
constructor TStringArray.Create;
begin
PCharArray := TIntegerList.Create($10,$10);
FCount := -1;
end;
destructor TStringArray.Destroy;
var
i: integer;
begin
if FCount <> -1 then
for i := 0 to FCount do FreeMem(PChar(PCharArray[i]));
PCharArray.Free;
end;
procedure TStringArray.Add(value:string);
var
PC: PChar;
begin
Inc(FCount);
GetMem(PC,Length(value)+1);
lstrcpy(PC,PChar(value));
PCharArray.Add(integer(PC));
end;
function TStringArray.GetItems(index:integer): string;
var
PC: PChar;
begin
if (index > FCount) or (index < 0) then begin
result := 'index error';
exit;
end;
PC := PChar(PCharArray[index]);
SetString(result,PC,lstrlen(PC));
end;
procedure TStringArray.SetItem(index: integer;value:string);
var
PC: PChar;
begin
if (index > FCount) or (index < 0) then exit;
GetMem(PC,Length(value)+1);
lstrcpy(PC,PChar(value));
FreeMem(PChar(PCharArray[index]));
PCharArray[index] := integer(PC);
end;
procedure TStringArray.Clear;
var
i: integer;
begin
if FCount = -1 then exit;
for i := 0 to FCount do FreeMem(PChar(PCharArray[i]));
PCharArray.Clear;
FCount := -1;
end;
procedure TStringArray.Delete(index: integer);
begin
if (index > FCount) or (index < 0) then Exit;
FreeMem(PChar(PCharArray[index]));
PCharArray.Delete(index);
Dec(FCount);
end;
procedure TStringArray.Insert(index: integer; value: string);
var
PC: PChar;
begin
if (index > FCount) or (index < 0) then Exit;
GetMem(PC,Length(value)+1);
lstrcpy(PC,PChar(value));
PCharArray.Insert(index,integer(PC));
Inc(FCount);
end;
function TStringArray.Search(s:string):integer;
var
i: integer;
begin
i := -1;
Repeat
Inc(i);
Until (Items[i] = s) or ( i>FCount );
if i > FCount then
Result := -1
else
Result := i;
end;
function TStringArray.GetCount: integer;
begin
result := FCount+1;
end;
procedure TStringArray.Exchange(i,j: integer);
var
s: string;
begin
s := Items[i];
Items[i] := Items[j];
Items[j] := s;
end;
procedure TStringArray.Sort;
begin
StringQuickSort(self,0,Count-1);
end;
function APICompareString(S1,S2: string): integer;
begin
result := CompareString(LOCALE_SYSTEM_DEFAULT,0,
PChar(S1),-1,PChar(S2),-1) - 2;
end;
procedure StringQuickSort(SS: TStringArray;l,r: integer);
var
i,j: integer;
sP: string;
begin
repeat
i := l;
j := r;
sP := SS[(l+r) div 2];
repeat
while APICompareString(SS[i],sP) < 0 do inc(i);
while APICompareString(SS[j],sP) > 0 do dec(j);
if i <= j then begin
SS.Exchange(i,j);
inc(i);
dec(j);
end;
until i > j;
if l < j then StringQuickSort(SS,l,j);
l := i;
until i >= r;
end;
//------------- TAPIDragDrop ----------------------------------------------
constructor TAPIDragDrop.Create(hParent:HWND);
begin
inherited Create(hParent);
Dispatcher.TrapMessage(WM_DROPFILES,self);
FFiles := TStringArray.Create;
DragAcceptFiles(hParent, true);
end;
destructor TAPIDragDrop.Destroy;
begin
FFiles.Free;
DragAcceptFiles(FParent, false);
inherited Destroy;
end;
procedure TAPIDragDrop.DefaultHandler(var Message);
var
AMsg: TMessage;
hD: HDROP;
i: integer;
PC: PChar;
begin
AMsg := TMessage(Message);
case AMsg.Msg of
WM_DROPFILES:begin
FFiles.Clear;
hD := AMsg.wParam;
GetMem(PC,MAX_PATH+1);
FFileCount := DragQueryFile(hD,$FFFFFFFF,nil,0);
for i := 0 to FFileCount-1 do begin
DragQueryFile(hD,i,PC,MAX_PATH+1);
FFiles.Add(string(PC));
end;
FreeMem(PC);
DragFinish(hD);
if Assigned(FOnDrop) then begin
AMsg.Msg := UINT(self); // sender
OnDrop(AMsg);
end;
end;
end; // case
end;
procedure TAPIDragDrop.SetFocus(hWnd: HWND);
begin
SetForeGroundWindow(FParent);
Windows.SetFocus(hWnd);
end;
function TAPIDragDrop.GetFiles(i: integer): string;
begin
result := FFiles[i];
end;
//------------- TGridArranger ----------------------------------------------
constructor TGridArranger.Create(hParent: HWND);
begin
inherited Create(hParent);
Dispatcher.TrapMessage(WM_SIZE,self);
FNumCol := 2;
FNumRow := 2;
FXMargin := 0;
FYMargin := 0;
FXSep := 1;
FYSep := 1;
end;
procedure TGridArranger.DefaultHandler(var Message);
var
AMsg: TMessage;
begin
AMsg := TMessage(Message);
case AMsg.Msg of
WM_SIZE:begin
if Assigned(FOnSize) then begin
AMsg.Msg := UINT(self); // sender
OnSize(AMsg);
end;
end;
end; // case
end;
function TGridArranger.Arrange(Row,Col: integer): TRect;
var
CR: TRect;
begin
GetClientRect(FParent,CR);
result.Right := (CR.Right-2*FXMargin-FXSep*(FNumCol-1)) div FNumCol;
result.Bottom := (CR.Bottom-2*FYMargin-FYSep*(FNumRow-1)) div FNumRow;
result.Left := FXMargin+(result.Right+FXSep)*Row;
result.Top := FYMargin+(result.Bottom+FYSep)*Col;
end;
function TGridArranger.CenterArrange(Row,Col:integer;Dim: TRect): TRect;
var
CR: TRect;
begin
CR := Arrange(Row,Col);
result := Dim;
if CR.Right < Dim.Right then
result.Left := CR.Left
else
result.Left := (CR.Right-Dim.Right) div 2 + CR.Left;
if CR.Bottom < Dim.Bottom then
result.Top := CR.Top
else
result.Top := (CR.Bottom-Dim.Bottom) div 2 + CR.Top;
end;
//------------- TBorderArranger ----------------------------------------------
constructor TBorderArranger.Create(hParent: HWND);
begin
inherited Create(hParent);
Dispatcher.TrapMessage(WM_SIZE,self);
FUpperHeight := 0;
FLowerHeight := 0;
FLeftWidth := 0;
FRightWidth := 0;
FXMargin := 0;
FYMargin := 0;
FXSep := 1;
FYSep := 1;
end;
procedure TBorderArranger.DefaultHandler(var Message);
var
AMsg: TMessage;
begin
AMsg := TMessage(Message);
case AMsg.Msg of
WM_SIZE:begin
if Assigned(FOnSize) then begin
AMsg.Msg := UINT(self); // sender
OnSize(AMsg);
end;
end;
end; // case
end;
function TBorderArranger.Arrange(BorderPos:TBorderPos): TRect;
var
CR: TRect;
begin
GetClientRect(FParent,CR);
case BorderPos of
bpUpper: begin
result.Left := FXMargin;
result.Top := FYMargin;
result.Right := CR.Right-FXMargin*2;
result.Bottom := FUpperHeight;
end;
bpLower: begin
result.Left := FXMargin;
result.Top := CR.Bottom-FYMargin-FLowerHeight;
result.Right := CR.Right-FXMargin*2;
result.Bottom := FLowerHeight;
end;
bpLeft: begin
result.Left := FXMargin;
result.Top := FYMargin+FUpperHeight+FYSep;
result.Right := FLeftWidth;
result.Bottom := CR.Bottom-FUpperHeight-FLowerHeight-FYMargin*2-FYSep*2;
end;
bpRight: begin
result.Left := CR.Right-FXMargin-FRightWidth;
result.Top := FYMargin+FUpperHeight+FYSep;
result.Right := FRightWidth;
result.Bottom := CR.Bottom-FUpperHeight-FLowerHeight-FYMargin*2-FYSep*2;
end;
bpCenter: begin
result.Left := FXMargin+FLeftWidth+XSep;
result.Top := FYMargin+FUpperHeight+YSep;
result.Right := CR.Right-FLeftWidth-FRightWidth-FXSep*2-FXMargin*2;
result.Bottom := CR.Bottom-FUpperHeight-FLowerHeight-FYMargin*2-FYSep*2;
end;
end;
end;
//------------- MessageTrapper ---------------------------------
constructor TMessageTrapper.Create(hParent: HWND);
begin
inherited Create(hParent);
FTrapMessage := TIntegerList.Create(1,1);
FHandler := TIntegerList.Create(1,1);
end;
destructor TMessageTrapper.Destroy;
begin
FTrapMessage.Free;
FHandler.Free;
inherited Destroy;
end;
procedure TMessageTrapper.DefaultHandler(var Message);
var
AMsg: TMessage;
i: integer;
begin
AMsg := TMessage(Message);
for i := 0 to FNumTrap-1 do
if AMsg.Msg = DWORD(FTrapMessage[i]) then
if FHandler[i] <> 0 then begin
TNotifyMessage(FHandler[i])(AMsg);
if AMsg.Result <> 0 then
TMessage(Message).result := AMsg.Result;
end;
end;
procedure TMessageTrapper.TrapMessage(TrapMsg: UINT;Handler: TNotifyMessage);
begin
FTrapMessage.Add(TrapMsg);
FHandler.Add(integer(@Handler));
Dispatcher.TrapMessage(TrapMsg,self);
inc(FNumTrap);
end;
//------------- TAPIGFont -----------------------------------------------
function FindFontProc(lpelf: PEnumLogFont;
lpntm: PNewTextMetric;
nFontType: integer;
lParam: LParam):integer; stdcall; export;
begin
PLogFont(lParam)^ := lpelf^.elfLogFont;
Result := 1;
end;
constructor TAPIGFont.Create;
var
hF: HFONT;
begin
hf := GetStockObject(SYSTEM_FONT);
GetObject(hF,SizeOf(FLogFont),@FLogFont);
FName := FLogFont.lfFacename;
FSize := 12;
FEscapement := FLogFont.lfEscapement;
FBold := (FLogFont.lfWeight > 300);
FItalic := (FLogFont.lfItalic <> 0);
FUnderline := (FLogFont.lfUnderline <> 0);
FStrikeOut := (FLogFont.lfStrikeOut <> 0);
end;
procedure TAPIGFont.SelectHandle(DC: HDC);
begin
If FName = 'System' then Exit;
EnumFontFamilies(DC,PChar(FName),@FindFontProc,integer(@FLogFont));
with FLogFont do begin
lfHeight := -MulDiv(FSize,GetDeviceCaps(DC,LOGPIXELSY),72);
lfWidth := 0;
lfEscapement := FEscapement;
if FBold then lfWeight := FW_BOLD else lfWeight := FW_NORMAL;
if FItalic then lfItalic := 1 else lfItalic := 0;
if FUnderline then lfUnderline := 1 else lfUnderline := 0;
if FStrikeOut then lfStrikeOut := 1 else lfStrikeOut := 0;
end;
FHandle := CreateFontIndirect(FLogFont);
FPrevHandle := SelectObject(DC,FHandle);
SetTextColor(DC,FColor);
end;
procedure TAPIGFont.DeleteHandle(DC: HDC);
begin
If FName = 'System' then Exit;
if FHandle<>0 then begin
SelectObject(DC,FPrevHandle);
DeleteObject(FHandle);
FHandle := 0;
SetTextColor(DC,0);
end;
end;
procedure TAPIGFont.SetLogFont(value: TLogFont);
var
IC: HDC;
begin
FLogFont := value;
FName := value.lfFaceName;
IC := CreateIC('DISPLAY',nil,nil,nil);
FSize := ((value.lfHeight)*72) div GetDeviceCaps(IC,LOGPIXELSY);
DeleteDC(IC);
FEscapement := value.lfEscapement;
FBold := (value.lfWeight > 500);
FItalic := (value.lfItalic <> 0);
FUnderline := (value.lfUnderline <> 0);
FStrikeOut := (value.lfStrikeOut <> 0);
end;
function TAPIGFont.GetLogFont: TLogFont;
var
IC: HDC;
begin
IC := CreateIC('DISPLAY',nil,nil,nil);
EnumFontFamilies(IC,PChar(FName),@FindFontProc,integer(@FLogFont));
with FLogFont do begin
lfHeight := -MulDiv(FSize,GetDeviceCaps(IC,LOGPIXELSY),72);
DeleteDC(IC);
lfWidth := 0;
lfEscapement := FEscapement;
if FBold then lfWeight := FW_BOLD else lfWeight := FW_NORMAL;
if FItalic then lfItalic := 1 else lfItalic := 0;
if FUnderline then lfUnderline := 1 else lfUnderline := 0;
if FStrikeOut then lfStrikeOut := 1 else lfStrikeOut := 0;
end;
result := FLogFont;
end;
//------------- TAPICFont -----------------------------------------------
destructor TAPICFont.Destroy;
begin
DeleteObject(FHandle);
inherited Destroy;
end;
procedure TAPICFont.GetHandle;
begin
DeleteObject(FHandle);
FHandle := CreateFontIndirect(LogFont);
end;
procedure TAPICFont.SetHandle(ctlHandle: HWND);
begin
SendMessage(ctlHandle,WM_SETFONT,FHandle,1);
end;
procedure TAPICFont.ResetHandle(ctlHandle: HWND);
begin
SendMessage(ctlHandle,WM_SETFONT,0,1);
end;
//------------- File Function -----------------------------------------
function GetLowDir(var Path: string): Boolean;
var
p,Len: integer;
begin
result := false;
p := Pos('\',Path);
if p <> 0 then begin
result := true;
Len := Length(Path)-p;
Path := Copy(Path,p+1,Len);
SetLength(Path,Len);
end;
end;
function AExtractFileName(s: string):string;
var
Path: string;
begin
Path := s;
while GetLowDir(Path) do result := Path;
end;
function AExtractDir(s: string): string;
var
fn: string;
begin
fn := AExtractFileName(s);
result := Copy(s,0,Length(s)-Length(fn)-1);
end;
function AExtractExt(s: string): string;
var
fn: string;
i: integer;
begin
fn := AExtractFileName(s);
i := Pos('.',fn);
if i <> 0 then
result := Copy(fn,i+1,Length(fn))
else
result := '';
end;
procedure FindAllFilesWithExt(dir,ext:string;SL:TStringArray);
var
s: string;
hFind: THandle;
fd: TWin32FindData;
Ret: Boolean;
begin
s := dir + '\*.'+ext;
hFind := FindFirstFile(PChar(s),fd);
Ret := true;
while ( (hFind <> INVALID_HANDLE_VALUE) and Ret ) do begin
if (fd.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then
SL.Add(string(fd.cFileName));
Ret := FindNextFile(hFind,fd);
end;
Windows.FindClose(hFind);
end;
procedure FindAllFiles(dir:string;SL:TStringArray);
begin
FindAllFilesWithExt(dir,'*',SL);
end;
function GetFileSize(FullPath: string): integer;
var
fd: TWin32FindData;
begin
FindClose(FindFirstFile(PChar(FullPath),fd));
result := fd.nFileSizeLow;
end;
function GetFileCreationTime(FullPath: string): TSystemTime;
var
fd: TWin32FindData;
ft: TFileTime;
begin
FindClose(FindFirstFile(PChar(FullPath),fd));
FileTimeToLocalFileTime(fd.ftCreationTime,ft);
FileTimeToSystemTime(ft,result);
end;
function GetFileLastAccessTime(FullPath: string): TSystemTime;
var
fd: TWin32FindData;
ft: TFileTime;
begin
FindClose(FindFirstFile(PChar(FullPath),fd));
FileTimeToLocalFileTime(fd.ftLastAccessTime,ft);
FileTimeToSystemTime(ft,result);
end;
function GetFileLastWriteTime(FullPath: string): TSystemTime;
var
fd: TWin32FindData;
ft: TFileTime;
begin
FindClose(FindFirstFile(PChar(FullPath),fd));
FileTimeToLocalFileTime(fd.ftLastWriteTime,ft);
FileTimeToSystemTime(ft,result);
end;
function GetFileAttributes(FullPath: string): DWORD;
var
fd: TWin32FindData;
begin
FindClose(FindFirstFile(PChar(FullPath),fd));
result := fd.dwFileAttributes;
end;
procedure DisplayLogFont(lf: TLogFont; SA: TStringArray);
var
s: string;
begin
SA.Clear;
SA.Add(' FontName :'#9+ string(lf.lfFaceName));
SA.Add(' Height :'#9+ AIntToStr(lf.lfHeight));
SA.Add(' Width : '#9+ AIntToStr(lf.lfWidth));
SA.Add(' Escapement :'#9+ AIntToStr(lf.lfEscapement));
SA.Add(' Orientation :'#9+ AIntToStr(lf.lfOrientation));
case lf.lfWeight of
0: s := 'DONTCARE';
100: s := 'THIN';
200: s := 'EXTRALIGHT';
300: s := 'LIGHT';
400: s := 'NORMAL';
500: s := 'MEDIUM';
600: s := 'SEMIBOLD';
700: s := 'BOLD';
800: s := 'EXTRABOLD';
900: s := 'HEAVY';
else
s := AIntToStr(lf.lfWeight);
end;
SA.Add(' Weight :'#9+s);
if lf.lfItalic = 0 then s := 'No' else s := 'Yes';
SA.Add(' Italic : '#9+ s);
if lf.lfUnderline = 0 then s := 'No' else s := 'Yes';
SA.Add(' Underline : '#9+ s);
if lf.lfStrikeOut = 0 then s := 'No' else s := 'Yes';
SA.Add(' StrikeOut : '#9+ s);
case lf.lfCharSet of
0: s := 'ANSI_CHARSET';
1: s := 'DEFAULT_CHARSET';
2: s := 'SYMBOL_CHARSET';
128: s := 'SHIFTJIS_CHARSET';
255: s := 'OEM_CHARSET';
161: s := 'GREEK_CHARSET';
else
s := AIntToStr(lf.lfCharSet);
end;
SA.Add(' CharSet : '#9+ s);
case lf.lfOutPrecision of
0: s := 'OUT_DEFAULT_PRECIS';
1: s := 'OUT_STRING_PRECIS';
2: s := 'OUT_CHARACTER_PRECIS';
3: s := 'OUT_STROKE_PRECIS';
4: s := 'OUT_TT_PRECIS';
5: s := 'OUT_DEVICE_PRECIS';
6: s := 'OUT_RASTER_PRECIS';
7: s := 'OUT_TT_ONLY_PRECIS';
8: s := 'OUT_OUTLINE_PRECIS';
9: s := 'OUT_SCREEN_OUTLINE_PRECIS';
else
s := AIntToStr(lf.lfOutPrecision);
end;
SA.Add(' OutPrecision : '#9+ s);
case lf.lfClipPrecision of
0: s := 'CLIP_DEFAULT_PRECIS';
1: s := 'CLIP_CHARACTER_PRECIS';
2: s := 'CLIP_STROKE_PRECIS';
else
s := AIntToStr(lf.lfClipPrecision);
end;
SA.Add(' ClipPrecision : '#9+ s);
case lf.lfQuality of
0: s := 'DEFAULT_QUALITY';
1: s := 'DRAFT_QUALITY';
2: s := 'PROOF_QUALITY';
3: s := 'NONANTIALIASED_QUALITY';
4: s := 'ANTIALIASED_QUALITY';
else
s := AIntToStr(lf.lfQuality);
end;
SA.Add(' Quality : '#9+ s);
case (lf.lfPitchAndFamily and $F) of
0: s := 'DEFAULT_PITCH';
1: s := 'FIXED_PITCH';
2: s := 'VARIABLE_PITCH';
8: s := 'MONO_FONT';
else
s := AIntToStr(lf.lfPitchAndFamily and $F);
end;
SA.Add(' Pitch : '#9+ s);
case (lf.lfPitchAndFamily shr 4) of
0: s := 'FF_DONTCARE';
1: s := 'FF_ROMAN';
2: s := 'FF_SWISS';
3: s := 'FF_MODERN';
4: s := 'FF_SCRIPT';
5: s := 'FF_DECORATIVE';
else
s := AIntToStr(lf.lfPitchAndFamily shr 4);
end;
SA.Add(' Family : '#9+ s);
end;
function GetOpenFile(hOwner:HWND;defName,Filter,initDir:string;
var FLN:TOpenSave):Boolean;
var
OFN: TOpenFileName;
PATH: string;
begin
PATH := defName+#0;
SetLength(PATH,MAX_PATH+5);
FillChar(OFN,SizeOf(OFN),0);
with OFN do begin
lStructSize := 76; // for Delphi6
hWndOwner := hOwner;
lpstrFilter := PChar(Filter);
nFilterIndex := 1;
lpstrFile := PChar(PATH);
nMaxFile:= MAX_PATH+5;
lpstrInitialDir := PChar(initDir);
Flags := OFN_FILEMUSTEXIST or OFN_HIDEREADONLY;
end;
result := Boolean(GetOpenFileName(OFN));
if result then begin
FLN.FullName := (OFN.lpstrFile);
FLN.Path := Copy(PATH,0,OFN.nFileOffset);
FLN.FileName := Copy(PATH,OFN.nFileOffset+1,Length(PATH));
FLN.Ext := Copy(PATH,OFN.nFileExtension+1,Length(PATH));
end;
end;
function GetSaveFile(hOwner:HWND;defName,Filter,initDir:string;
var FLN:TOpenSave):Boolean;
var
OFN: TOpenFileName;
PATH: string;
begin
PATH := defName+#0;
SetLength(PATH,MAX_PATH+5);
FillChar(OFN,SizeOf(OFN),0);
with OFN do begin
lStructSize := 76; // for Delphi6
hWndOwner := hOwner;
lpstrFilter := PChar(Filter);
nFilterIndex := 1;
lpstrFile := PChar(PATH);
nMaxFile:= MAX_PATH+5;
lpstrInitialDir := PChar(initDir);
Flags := OFN_OVERWRITEPROMPT or OFN_HIDEREADONLY;
end;
result := Boolean(GetSaveFileName(OFN));
if result then begin
FLN.FullName := (OFN.lpstrFile);
FLN.Path := Copy(PATH,0,OFN.nFileOffset);
FLN.FileName := Copy(PATH,OFN.nFileOffset+1,Length(PATH));
FLN.Ext := Copy(PATH,OFN.nFileExtension+1,Length(PATH));
end;
end;
function CountSpace(s: string):integer;
var
i: integer;
begin
result := 0;
for i := 1 to Length(s) do
if s[i] = ' ' then inc(result);
end;
function GetMultFileName(s:string;SL:TStringArray):integer;
var
IC,i: integer;
IL: TIntegerList;
begin
SL.Clear;
IC := CountSpace(s);
if IC = 0 then begin
SL.Add(AExtractDir(s)+'\');
SL.Add(AExtractFileName(s));
result := 1;
end else begin
IL := TIntegerList.Create(IC*SizeOf(integer),SizeOf(integer));
for i := 1 to Length(s) do
if s[i] = ' ' then IL.Add(i);
SL.Add(Copy(s,1,IL[0]-1));
if Copy(SL[0],Length(SL[0]),1)<>'\' then
SL[0]:=SL[0]+'\';
for i := 1 to IC-1 do
SL.Add(Copy(s,IL[i-1]+1,IL[i]-IL[i-1]-1));
SL.Add(Copy(s,IL[IC-1]+1,100));
IL.Free;
result := IC;
end;
end;
function GetOpenFileMult(hOwner:HWND;defName,Filter,initDir:string;
STL:TStringArray;var NumFile:integer):Boolean;
var
OFN: TOpenFileName;
s: string;
PATH: array[0..8000] of Char;
i: integer;
flag: Boolean;
begin
FillChar(PATH,8001,0);
for i := 0 to Length(defName)-1 do PATH[i] := defName[i+1];
FillChar(OFN,SizeOf(OFN),0);
with OFN do begin
lStructSize := 76; // for Delphi6
hWndOwner := hOwner;
lpstrFilter := PChar(Filter);
nFilterIndex := 1;
lpstrFile := @PATH;
nMaxFile:= 8000;
lpstrInitialDir := PChar(initDir);
Flags := OFN_FILEMUSTEXIST or OFN_HIDEREADONLY or
OFN_ALLOWMULTISELECT or OFN_EXPLORER;
end;
result := Boolean(GetOpenFileName(OFN));
if result then begin
flag := true;
i := 0;
while flag do begin
if PATH[i] = #0 then
if PATH[i+1] = #0 then flag := false else PATH[i] := ' ';
inc(i);
end;
SetString(s,PChar(@PATH),lstrlen(@PATH));
NumFile := GetMultFileName(s,STL);
end;
end;
function SHCopyFile(hParent:HWND;NameFrom,NameTo:string):Boolean;
var
SFO: TSHFileOpStruct;
begin
NameFrom := NameFrom+#0#0;
NameTo := NameTo+#0#0;
with SFO do begin
Wnd := hParent;
wFunc := FO_COPY;
pFrom := PChar(NameFrom);
pTo := PChar(NameTo);
fFlags := FOF_ALLOWUNDO;
fAnyOperationsAborted := false;
hNameMappings := nil;
end;
Result := not Boolean(SHFileOperation(SFO));
end;
function SHMoveFile(hParent:HWND;NameFrom,NameTo:string):Boolean;
var
SFO: TSHFileOpStruct;
begin
NameFrom := NameFrom+#0#0;
NameTo := NameTo+#0#0;
with SFO do begin
Wnd := hParent;
wFunc := FO_MOVE;
pFrom := PChar(NameFrom);
pTo := PChar(NameTo);
fFlags := FOF_ALLOWUNDO;
fAnyOperationsAborted := false;
hNameMappings := nil;
end;
Result := not Boolean(SHFileOperation(SFO));
end;
function SHRenameFile(hParent:HWND;NameFrom,NameTo:string):Boolean;
var
SFO: TSHFileOpStruct;
begin
NameFrom := NameFrom+#0#0;
NameTo := NameTo+#0#0;
with SFO do begin
Wnd := hParent;
wFunc := FO_RENAME;
pFrom := PChar(NameFrom);
pTo := PChar(NameTo);
fFlags := FOF_ALLOWUNDO;
fAnyOperationsAborted := false;
hNameMappings := nil;
end;
Result := not Boolean(SHFileOperation(SFO));
end;
function SHDeleteFile(hParent:HWND;Name:string):Boolean;
var
SFO: TSHFileOpStruct;
begin
Name := Name+#0#0;
with SFO do begin
Wnd := hParent;
wFunc := FO_DELETE;
pFrom := PChar(Name);
pTo := nil;
fFlags := FOF_ALLOWUNDO + FOF_NOCONFIRMATION;
fAnyOperationsAborted := false;
hNameMappings := nil;
end;
Result := not Boolean(SHFileOperation(SFO));
end;
procedure FindAllDirInDir(dir:string;SL:TStringArray);
var
s: string;
hFind: LongInt;
fd: TWin32FindData;
Ret: Boolean;
begin
s := dir + '\*.*';
hFind := FindFirstFile(PChar(s),fd);
Ret := true;
while ( (hFind <> LongInt(INVALID_HANDLE_VALUE)) and Ret ) do begin
if (fd.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) <> 0 then begin
SetString(s,fd.cFileName,1);
if s <> '.' then
SL.Add(string(fd.cFileName));
end;
Ret := FindNextFile(hFind,fd);
end;
Windows.FindClose(hFind);
end;
function IsFileExist(FN: string):Boolean;
var
fd: TWin32FindData;
hH: THandle;
ret: integer;
begin
hH := FindFirstFile(PChar(FN),fd);
if hH = INVALID_HANDLE_VALUE then begin
ret := GetDriveType(PChar(FN+'\'));
if (ret = DRIVE_FIXED) or (ret = DRIVE_REMOVABLE) then
result := true
else
result := false;
end else begin
result := true;
FindClose(hH);
end;
end;
function CreateDir(DN:string):Boolean;
var
s:string;
begin
s := AExtractDir(DN);
if IsFileExist(s) then
result := Boolean(CreateDirectory(PChar(DN),nil))
else
if CreateDir(s) then
result := Boolean(CreateDirectory(PChar(DN),nil))
else
result := false;
end;
function RemoveDirAll(DN:string):Boolean;
var
i: integer;
SA: TStringArray;
begin
SA := TStringArray.Create;
FindAllFiles(DN+'\',SA);
if SA.Count > 0 then
for i := 0 to SA.Count-1 do SHDeleteFile(0,DN+'\'+SA[i]);
SA.Clear;
FindAllDirInDir(DN,SA);
if SA.Count > 0 then
for i := 0 to SA.Count-1 do RemoveDirAll(DN+'\'+SA[i]);
result := Boolean(RemoveDirectory(PChar(DN)));
SA.Free;
end;
procedure FindAllFilesWithSubdir(DN:string;SL:TStringArray);
var
i,j: integer;
SA,SB: TStringArray;
begin
SA := TStringArray.Create;
FindAllFiles(DN+'\',SA);
if SA.Count > 0 then
for i := 0 to SA.Count-1 do SL.Add(DN+'\'+SA[i]);
SA.Clear;
SB := TStringArray.Create;
FindAllDirInDir(DN,SA);
if SA.Count > 0 then
for i := 0 to SA.Count-1 do begin
FindAllFilesWithSubdir(DN+'\'+SA[i],SB);
if SB.Count > 0 then
for j := 0 to SB.Count-1 do SL.Add(SB[j]);
SB.Clear;
end;
SA.Free;
SB.Free;
end;
function SHCopyDir(hParent:HWND;NameFrom,NameTo:string):Boolean;
var
SFO: TSHFileOpStruct;
begin
NameFrom := NameFrom+#0#0;
NameTo := NameTo+#0#0;
with SFO do begin
Wnd := hParent;
wFunc := FO_COPY;
pFrom := PChar(NameFrom);
pTo := PChar(NameTo);
fFlags := FOF_ALLOWUNDO or FOF_NOCONFIRMMKDIR;
fAnyOperationsAborted := false;
hNameMappings := nil;
end;
Result := not Boolean(SHFileOperation(SFO));
end;
function SHDeleteDir(hParent:HWND;Name:string):Boolean;
var
SFO: TSHFileOpStruct;
begin
Name := Name+#0#0;
with SFO do begin
Wnd := hParent;
wFunc := FO_DELETE;
pFrom := PChar(Name);
pTo := nil;
fFlags := FOF_ALLOWUNDO + FOF_NOCONFIRMATION;
fAnyOperationsAborted := false;
hNameMappings := nil;
end;
Result := not Boolean(SHFileOperation(SFO));
end;
//------------------------------------------------------------
// Create Functions
//------------------------------------------------------------
function CreateTimer(hParent:HWND; Intrvl: integer;
OnTimerFunc: TNotifyMessage):TAPITimer;
begin
result := TAPITimer.Create(hParent);
with result do begin
Interval := Intrvl;
OnTimer := OnTimerFunc;
end;
end;
function CreateGridArranger(hParent:HWND;iRow,iCol,XMrgn,YMrgn,
XSp,YSp:integer; sOnSize:TNotifyMessage): TGridArranger;
begin
result := TGridArranger.Create(hParent);
with result do begin
NumRow := iRow;
NumCol := iCol;
XMargin := XMrgn;
YMargin := YMrgn;
XSep := XSp;
YSep := YSp;
OnSize := sOnSize;
end;
end;
function CreateBorderArranger(hParent:HWND;UH,LH,LW,RW,XMrgn,YMrgn,
XSp,YSp:integer; sOnSize:TNotifyMessage): TBorderArranger;
begin
result := TBorderArranger.Create(hParent);
with result do begin
UpperHeight := UH;
LowerHeight := LH;
LeftWidth := LW;
RightWidth := RW;
XMargin := XMrgn;
YMargin := YMrgn;
XSep := XSp;
YSep := YSp;
OnSize := sOnSize;
end;
end;
initialization
finalization
Dispatcher.Free;
end. |
unit Objekt.DHLManifestRequestAPI;
interface
uses
SysUtils, System.Classes, geschaeftskundenversand_api_2, Objekt.DHLVersion;
type
TDHLManifestRequestAPI = class
private
fRequest: GetManifestRequest;
FVersion: TDHLVersion;
fManifestDate: TDateTime;
procedure setManifestDate(const Value: TDateTime);
public
constructor Create;
destructor Destroy; override;
property Request: GetManifestRequest read fRequest write fRequest;
property Version: TDHLVersion read FVersion write fVersion;
property ManifestDate: TDateTime read fManifestDate write setManifestDate;
end;
implementation
{ TDHLManifestRequestAPI }
constructor TDHLManifestRequestAPI.Create;
begin
fVersion := TDHLVersion.Create;
fRequest := GetManifestRequest.Create;
fRequest.Version := FVersion.VersionAPI;
end;
destructor TDHLManifestRequestAPI.Destroy;
begin
FreeAndNil(fVersion);
FreeAndNil(fRequest);
inherited;
end;
procedure TDHLManifestRequestAPI.setManifestDate(const Value: TDateTime);
begin
fManifestDate := Value;
fRequest.manifestDate := FormatDateTime('yyyy-mm-dd', fManifestDate);
end;
end.
|
unit BsEditCountry;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxLabel, cxControls, cxContainer, cxEdit,
cxTextEdit, ActnList, DB, FIBDataSet, pFIBDataSet, FIBQuery, pFIBQuery,
pFIBStoredProc, FIBDatabase, pFIBDatabase, StdCtrls, cxButtons, AdrEdit,
BaseTypes, BsAdrConsts;
type
TfrmEditCountry = class(TEditForm)
btnOk: TcxButton;
btnCancel: TcxButton;
EditDB: TpFIBDatabase;
eTrRead: TpFIBTransaction;
eTrWrite: TpFIBTransaction;
eStoredProc: TpFIBStoredProc;
EDSet: TpFIBDataSet;
ActionList1: TActionList;
ActOk: TAction;
ActCancel: TAction;
CountryEdit: TcxTextEdit;
lblCountry: TcxLabel;
procedure ActCancelExecute(Sender: TObject);
procedure ActOkExecute(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmEditCountry: TfrmEditCountry;
implementation
{$R *.dfm}
procedure TfrmEditCountry.ActCancelExecute(Sender: TObject);
begin
CloseConnect;
ModalResult:=mrCancel;
end;
procedure TfrmEditCountry.ActOkExecute(Sender: TObject);
begin
eStoredProc.StoredProcName:='ADR_COUNTRY_IU';
eStoredProc.Transaction.StartTransaction;
eStoredProc.Prepare;
if not VarIsNull(KeyField) then
eStoredProc.ParamByName('NAME_COUNTRY').AsString:=KeyField;
eStoredProc.ParamByName('NAME_COUNTRY').AsString:=CountryEdit.Text;
try
eStoredProc.ExecProc;
ReturnId:=eStoredProc.FldByName['ID_COUNTRY'].AsInteger;
eStoredProc.Transaction.Commit;
ModalResult:=mrOk;
except on E:Exception
do begin
agMessageDlg(WarningText, E.Message, mtInformation, [mbOK]);
eStoredProc.Transaction.Rollback;
ModalResult:=mrCancel;
end;
end;
end;
procedure TfrmEditCountry.FormShow(Sender: TObject);
begin
try
if Not VarIsNull(KeyField) then
begin
EDSet.Close;
EDSet.SQLs.SelectSQL.Text:=frmCountrySqlText+'('+IntToStr(KeyField)+')';
EDSet.Open;
CountryEdit.Text:=EDSet['NAME_COUNTRY'];
Self.Caption:='Змінити країну'
end
else Self.Caption:='Додати країну';
except on E:Exception
do agMessageDlg(WarningText, E.Message, mtInformation, [mbOK]);
end;
end;
initialization
RegisterClass(TfrmEditCountry);
end.
|
{================================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmKeyBindings
Purpose : To allow the end user to assign or change the hot keys assigned to
actions in an action list.
Date : 05-03-2000
Author : Ryan J. Mills
Version : 1.92
================================================================================}
unit rmKeyBindings;
interface
{$I CompilerDefines.INC}
uses classes, ActnList;
type
TrmKeyBindingItem = class(TCollectionItem)
private
{ Private }
fDesignLocked : boolean;
fCategory : string;
fActionCaption : string;
fActionName : string;
fShortCut : TShortCut;
fDescription : string;
fImageIndex : integer;
procedure SetShortcut(const Value: TShortCut);
procedure setDesignLocked(const Value: boolean);
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
published
property ActionName : string read fActionName write fACtionName;
property ActionCaption : string read fActionCaption write fActionCaption;
property Category : string read fCategory write fCategory;
property Description : String read fDescription write fDescription;
property ImageIndex : integer read fImageIndex write fImageIndex default -1;
property KeyBinding : TShortCut read fShortCut write SetShortcut default scNone;
property DesignLocked : boolean read fDesignLocked write setDesignLocked default false;
end;
TrmKeyBindingCollection = class(TCollection)
private
{ Private }
FOwner: TPersistent;
function GetItem(Index: Integer): TrmKeyBindingItem;
procedure SetItem(Index: Integer; Value: TrmKeyBindingItem);
protected
{ Protected }
function GetOwner: TPersistent; override;
public
{ Public }
constructor Create(AOwner: TPersistent);
function Add: TrmKeyBindingItem;
property Items[Index: Integer]: TrmKeyBindingItem read GetItem write SetItem; default;
end;
TrmBindingStorage = class(TComponent)
private
fItems: TrmKeyBindingCollection;
procedure SetItem(const Value: TrmKeyBindingCollection);
public
constructor create(AOwner:TComponent); override;
destructor destroy; override;
published
property Items: TrmKeyBindingCollection read fItems write SetItem;
end;
TrmKeyBindings = class(TComponent)
private
{ Private }
fActions : TCustomActionList;
fItems : TrmKeyBindingCollection;
fDisplayName: boolean;
fMultiBinds: boolean;
protected
{ Protected }
procedure SetActionList(const Value: TCustomActionList); Virtual;
public
{ Public }
constructor create(AOwner:TComponent); override;
destructor destroy; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function EditBindings:boolean;
procedure ApplyBindings;
procedure ClearBindings;
procedure LoadBindingsFromFile(fileName:string; Binary:Boolean);
procedure LoadBindingsFromStream(Strm:TStream; Binary:Boolean);
procedure SaveBindingsToFile(FileName:string; Binary:Boolean);
procedure SaveBindingsToStream(Strm:TStream; Binary:Boolean);
published
{ Published }
property Actions : TCustomActionList read fActions write SetActionList;
property DisplayActionName:boolean read fDisplayName write fDisplayName default false;
property AllowMultiBinds:boolean read fMultiBinds write fMultiBinds default true;
end;
implementation
uses Forms, Controls, sysutils, rmKeyBindingsEditForm;
{ TrmKeyBindings }
procedure TrmKeyBindings.ApplyBindings;
var
loop, loop1 : integer;
wAction : TCustomAction;
wCursor : TCursor;
begin
wCursor := screen.cursor;
try
screen.Cursor := crHourGlass;
for loop := 0 to fItems.Count-1 do
begin
wAction := TCustomAction(fActions.Actions[loop]);
if wAction.Name = fItems[loop].ActionName then
begin
wAction.shortcut := fItems[loop].KeyBinding;
fActions.UpdateAction(wAction);
end
else
begin
for loop1 := 0 to fActions.ActionCount-1 do
begin
wAction := TCustomAction(fActions.Actions[loop1]);
if wAction.Name = fItems[loop].ActionName then
begin
wAction.shortcut := fItems[loop].KeyBinding;
fActions.UpdateAction(wAction);
break;
end;
end;
end
end;
finally
screen.cursor := wCursor;
end;
end;
procedure TrmKeyBindings.ClearBindings;
begin
fItems.Clear;
end;
constructor TrmKeyBindings.create(AOwner: TComponent);
begin
inherited;
fItems := TrmKeyBindingCollection.create(self);
fDisplayName := false;
fMultiBinds := true;
end;
destructor TrmKeyBindings.destroy;
begin
fItems.Clear;
fItems.free;
inherited;
end;
function TrmKeyBindings.EditBindings:boolean;
var
frmEditor : TFrmEditKeyBindings;
begin
frmEditor := TFrmEditKeyBindings.create(nil);
try
if assigned(Actions) and assigned(Actions.images) then
frmEditor.images := Actions.images;
frmEditor.Items := Self.fItems;
frmEditor.DisplayName := fDisplayName;
frmEditor.MultiBinding := fMultiBinds;
frmEditor.Designing := (csDesigning in ComponentState);
if (frmEditor.ShowModal = mrOK) then
begin
result := true;
Self.fItems.assign(frmEditor.Items);
end
else
result := false;
finally
frmEditor.free;
end;
end;
procedure TrmKeyBindings.LoadBindingsFromFile(fileName: string; Binary:Boolean);
var
wFile : TFileStream;
begin
if fileexists(filename) then
begin
wFile := TFileStream.create(filename, fmOpenRead);
try
LoadBindingsFromStream(wFile, Binary);
finally
wFile.free;
end;
end;
end;
procedure TrmKeyBindings.LoadBindingsFromStream(Strm: TStream; Binary:Boolean);
var
wStorage : TComponent;
wTemp : TMemoryStream;
begin
Strm.Position := 0;
if Binary then
wStorage := TrmBindingStorage(Strm.ReadComponent(nil))
else
begin
wTemp := TMemoryStream.create;
try
ObjectTextToBinary(Strm, wTemp);
wTemp.position := 0;
wStorage := TrmBindingStorage(wTemp.ReadComponent(nil));
finally
wTemp.free;
end;
end;
try
fItems.Assign(TrmBindingStorage(wStorage).items);
finally
wStorage.free;
end;
ApplyBindings;
end;
procedure TrmKeyBindings.Notification(AComponent: TComponent; Operation: TOperation);
begin
if (Operation = opRemove) then
begin
if (aComponent = fActions) then
fActions := nil;
end;
inherited;
end;
procedure TrmKeyBindings.SaveBindingsToFile(FileName: string; Binary:Boolean);
var
wFile : TFileStream;
{$ifdef D5_or_higher}
wAttr : integer;
{$endif}
begin
{$ifdef D5_or_higher}
if fileexists(filename) then
begin
wAttr := filegetAttr(filename);
if (wAttr and faReadonly <> 0) or (wAttr and faSysFile <> 0) then
Raise Exception.create('Unable to open file for writing');
end;
{$endif}
wFile := TFileStream.create(filename, fmCreate);
try
SaveBindingsToStream(wFile, Binary);
finally
wFile.free;
end;
end;
procedure TrmKeyBindings.SaveBindingsToStream(Strm: TStream; Binary:Boolean);
var
wStorage : TrmBindingStorage;
wTemp : TMemoryStream;
begin
wStorage := TrmBindingStorage.create(self);
try
Strm.Position := 0;
wStorage.Items := fItems;
if Binary then
Strm.WriteComponent(wStorage)
else
begin
wTemp := TMemoryStream.create;
try
wTemp.WriteComponent(wStorage);
wTemp.Position := 0;
ObjectBinaryToText(wTemp, Strm)
finally
wTemp.free;
end;
end;
finally
wStorage.free;
end;
end;
procedure TrmKeyBindings.SetActionList(const Value: TCustomActionList);
var
loop : integer;
wAction : TCustomAction;
begin
fActions := Value;
if assigned(fActions) then
begin
fActions.FreeNotification(self);
fItems.Clear;
loop := 0;
while loop < fActions.ActionCount do
begin
if fActions[loop] is TCustomAction then
begin
wAction := TCustomAction(factions[loop]);
with fItems.Add do
begin
DesignLocked := false;
ActionCaption := wAction.Caption;
ActionName := wAction.Name;
Category := wAction.Category;
KeyBinding := wAction.Shortcut;
ImageIndex := wAction.ImageIndex;
Description := wAction.Hint;
end;
end;
inc(loop);
end;
end;
end;
{ TrmKeyBindingItem }
procedure TrmKeyBindingItem.Assign(Source: TPersistent);
begin
if Source is TrmKeyBindingItem then
begin
fActionCaption := TrmKeyBindingItem(Source).ActionCaption;
fActionName := TrmKeyBindingItem(Source).ActionName;
fCategory := TrmKeyBindingItem(Source).Category;
fDesignLocked := TrmKeyBindingItem(Source).DesignLocked;
fShortCut := TrmKeyBindingItem(Source).KeyBinding;
fDescription := TrmKeyBindingItem(Source).Description;
fImageIndex := TrmKeyBindingItem(Source).ImageIndex;
end
else
inherited Assign(Source);
end;
constructor TrmKeyBindingItem.Create(Collection: TCollection);
begin
inherited;
fShortCut := scNone;
fActionCaption := '';
fActionName := '';
fCategory := '';
fDesignLocked := false;
fDescription := '';
fImageIndex := -1;
end;
destructor TrmKeyBindingItem.Destroy;
begin
inherited;
end;
procedure TrmKeyBindingItem.setDesignLocked(const Value: boolean);
begin
fDesignLocked := Value;
end;
procedure TrmKeyBindingItem.SetShortcut(const Value: TShortCut);
begin
fShortCut := Value;
end;
{ TrmKeyBindingCollection }
function TrmKeyBindingCollection.Add: TrmKeyBindingItem;
begin
Result := TrmKeyBindingItem(inherited Add);
end;
constructor TrmKeyBindingCollection.Create(AOwner: TPersistent);
begin
inherited Create(TrmKeyBindingItem);
fOwner := AOwner;
end;
function TrmKeyBindingCollection.GetItem(Index: Integer): TrmKeyBindingItem;
begin
Result := TrmKeyBindingItem(inherited GetItem(Index));
end;
function TrmKeyBindingCollection.GetOwner: TPersistent;
begin
Result := FOwner;
end;
procedure TrmKeyBindingCollection.SetItem(Index: Integer; Value: TrmKeyBindingItem);
begin
inherited SetItem(Index, Value);
end;
{ TrmBindingStorage }
constructor TrmBindingStorage.create(AOwner: TComponent);
begin
inherited;
fItems := TrmKeyBindingCollection.Create(self);
end;
destructor TrmBindingStorage.destroy;
begin
fItems.Clear;
fItems.Free;
inherited;
end;
procedure TrmBindingStorage.SetItem(const Value: TrmKeyBindingCollection);
begin
fItems.Assign(Value);
end;
end.
|
unit LoginForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, LoginManager;
type
TformLoginPage = class(TForm)
editUserName: TEdit;
editPassword: TEdit;
btnLoginToProgram: TButton;
lblUserName: TLabel;
lblPaaword: TLabel;
procedure btnLoginToProgramClick(Sender: TObject);
private
fIsLoggedIn: boolean;
fLoginManager: TLoginManager;
{ Private declarations }
public
property IsLoggedIn: boolean read fIsLoggedIn write fIsLoggedIn;
{ Public declarations }
end;
var
formLoginPage: TformLoginPage;
implementation
{$R *.dfm}
procedure TformLoginPage.btnLoginToProgramClick(Sender: TObject);
begin
if (fLoginManager.LoginToProgram(editUserName.Text, editPassword.Text)) then
begin
FormLoginPage.Hide;
end
else
begin
Application.MessageBox('UserName or password was incorrect', 'Login failed',
MB_OK Or MB_ICONEXCLAMATION)
end;
end;
end.
|
Unit NumInWords;
{ Andy Preston, Apollo Developments, andy@anorak.org.uk, andy@apollod.omnia.co.uk
Numbers in words - Version 4.3
Copyright (C) 1999 Andy Preston
Copyright (C) 1999 Egemen Sen
Object-Pascal Units to express a number as words in various languages
This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details.
You should have received a copy of the GNU Library 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.
This unit is a modified version of NumW_Eng }
Interface
Function NumberInWords_EN(TheNumber : Integer) : String;
Function NumberInWords_AR(TheNumber : Integer) : String;
Function NumberInWords (TheNumber : Integer ) : String;
Implementation
Uses
SysUtils, MainModule;
function HunToStr_AR(n: integer): string;
var hun, Ten: integer;
s, ss, AndStr: string;
begin
hun := n div 100;
Ten := n mod 100;
AndStr := 'و';
case Ten of
0: s := '';
1: s := 'واحد';
2: s := 'اثنان';
3: s := 'ثلاثة';
4: s := 'اربعة';
5: s := 'خمسة';
6: s := 'ستة';
7: s := 'سبعة';
8: s := 'ثمانية';
9: s := 'تسعة';
10: s := 'عشرة';
11: s := 'احدى عشر';
12: s := 'اثنا عشر';
13: s := 'ثلاثة عشر';
14: s := 'اربعة عشر';
15: s := 'خمسة عشر';
16: s := 'ستة عشر';
17: s := 'سبعة عشر';
18: s := 'ثمانية عشر';
19: s := 'تسعة عشر';
20: s := 'عشرون';
21: s := 'احدى و عشرون';
22: s := 'اثنان و عشرون';
23: s := 'ثلاثة و عشرون';
24: s := 'اربعة و عشرون';
25: s := 'خمسة و عشرون';
26: s := 'ستة و عشرون';
27: s := 'سبعة و عشرون';
28: s := 'ثمانية و عشرون';
29: s := 'تسعة و عشرون';
30: s := 'ثلاثون';
31: s := 'واحد و ثلاثون';
32: s := 'اثنان و ثلاثون';
33: s := 'ثلاثة و ثلاثون';
34: s := 'اربعة و ثلاثون';
35: s := 'خمسة و ثلاثون';
36: s := 'ستة و ثلاثون';
37: s := 'سبعة و ثلاثون';
38: s := 'ثمانية و ثلاثون';
39: s := 'تسعة و ثلاثون';
40: s := 'اربعون';
41: s := 'واحد و اربعون';
42: s := 'اثنان و اربعون';
43: s := 'ثلاثة و اربعون';
44: s := 'اربعة و اربعون';
45: s := 'خمسة و اربعون';
46: s := 'ستة و اربعون';
47: s := 'سبعة و اربعون';
48: s := 'ثمانية و اربعون';
49: s := 'تسعة و اربعون';
50: s := 'خمسون';
51: s := 'واحد و خمسون';
52: s := 'اثنان و خمسون';
53: s := 'ثلاثة و خمسون';
54: s := 'اربعة و خمسون';
55: s := 'خمسة و خمسون';
56: s := 'ستة و خمسون';
57: s := 'سبعة و خمسون';
58: s := 'ثمانية و خمسون';
59: s := 'تسعة و خمسون';
60: s := 'ستون';
61: s := 'واحد و ستون';
62: s := 'اثنان و ستون';
63: s := 'ثلاثة و ستون';
64: s := 'اربعة و ستون';
65: s := 'خمسة و ستون';
66: s := 'ستة و ستون';
67: s := 'سبعة و ستون';
68: s := 'ثمانية و ستون';
69: s := 'تسعة و ستون';
70: s := 'سبعون';
71: s := 'واحد و سبعون';
72: s := 'اثنان و سبعون';
73: s := 'ثلاثة و سبعون';
74: s := 'اربعة و سبعون';
75: s := 'خمسة و سبعون';
76: s := 'ستة و سبعون';
77: s := 'سبعة و سبعون';
78: s := 'ثمانية و سبعون';
79: s := 'تسعة و سبعون';
80: s := 'ثمانون';
81: s := 'واحد و ثمانون';
82: s := 'اثنان و ثمانون';
83: s := 'ثلاثة و ثمانون';
84: s := 'اربعة و ثمانون';
85: s := 'خمسة و ثمانون';
86: s := 'ستة و ثمانون';
87: s := 'سبعة و ثمانون';
88: s := 'ثمانية و ثمانون';
89: s := 'تسعة و ثمانون';
90: s := 'تسعون';
91: s := 'واحد و تسعون';
92: s := 'اثنان و تسعون';
93: s := 'ثلاثة و تسعون';
94: s := 'اربعة و تسعون';
95: s := 'خمسة و تسعون';
96: s := 'ستة و تسعون';
97: s := 'سبعة و تسعون';
98: s := 'ثمانية و تسعون';
99: s := 'تسعة و تسعون';
end;
case hun of
0: ss := '';
1: ss := 'مئة';
2: ss := 'مئتان';
3: ss := 'ثلاثمائة';
4: ss := 'اربعمائة';
5: ss := 'خمسمائة';
6: ss := 'ستمائة';
7: ss := 'سبعمائة';
8: ss := 'ثمانمائة';
9: ss := 'تسعمائة';
end;
if (hun > 0) and (Ten > 0) then Result := ss + ' ' + AndStr + ' ' + s;
if (hun = 0) and (Ten > 0) then Result := s;
if (hun > 0) and (Ten = 0) then Result := ss;
end;
function HunToStr_EN(n: integer): string;
var hun, Ten: integer;
s, ss, AndStr: string;
begin
hun := n div 100;
Ten := n mod 100;
AndStr := 'And';
case Ten of
0: s := '';
1: s := 'One';
2: s := 'Two';
3: s := 'Three';
4: s := 'Four';
5: s := 'Five';
6: s := 'Six';
7: s := 'Seven';
8: s := 'Eight';
9: s := 'Nine';
10: s := 'Ten';
11: s := 'Eleven';
12: s := 'Twelve';
13: s := 'Thirteen';
14: s := 'Fourteen';
15: s := 'Fifteen';
16: s := 'Sixteen';
17: s := 'Seventeen';
18: s := 'Eighteen';
19: s := 'Nineteen';
20: s := 'Twenty';
21: s := 'Twenty One';
22: s := 'Twenty Two';
23: s := 'Twenty Three';
24: s := 'Twenty Four';
25: s := 'Twenty Five';
26: s := 'Twenty Six';
27: s := 'Twenty Seven';
28: s := 'Twenty Eight';
29: s := 'Twenty Nine';
30: s := 'Thirty';
31: s := 'Thirty One';
32: s := 'Thirty Two';
33: s := 'Thirty Three';
34: s := 'Thirty Four';
35: s := 'Thirty Five';
36: s := 'Thirty Six';
37: s := 'Thirty Seven';
38: s := 'Thirty Eight';
39: s := 'Thirty Nine';
40: s := 'Forty';
41: s := 'Forty One';
42: s := 'Forty Two';
43: s := 'Forty Three';
44: s := 'Forty Four';
45: s := 'Forty Five';
46: s := 'Forty Six';
47: s := 'Forty Seven';
48: s := 'Forty Eight';
49: s := 'Forty Nine';
50: s := 'Fifty';
51: s := 'Fifty One';
52: s := 'Fifty Two';
53: s := 'Fifty Three';
54: s := 'Fifty Four';
55: s := 'Fifty Five';
56: s := 'Fifty Six';
57: s := 'Fifty Seven';
58: s := 'Fifty Eight';
59: s := 'Fifty Nine';
60: s := 'Sixty';
61: s := 'Sixty One';
62: s := 'Sixty Two';
63: s := 'Sixty Three';
64: s := 'Sixty Four';
65: s := 'Sixty Five';
66: s := 'Sixty Six';
67: s := 'Sixty Seven';
68: s := 'Sixty Eight';
69: s := 'Sixty Nine';
70: s := 'Seventy';
71: s := 'Seventy One';
72: s := 'Seventy Two';
73: s := 'Seventy Three';
74: s := 'Seventy Four';
75: s := 'Seventy Five';
76: s := 'Seventy Six';
77: s := 'Seventy Seven';
78: s := 'Seventy Eight';
79: s := 'Seventy Nine';
80: s := 'Eighty';
81: s := 'Eighty One';
82: s := 'Eighty Two';
83: s := 'Eighty Three';
84: s := 'Eighty Four';
85: s := 'Eighty Five';
86: s := 'Eighty Six';
87: s := 'Eighty Seven';
88: s := 'Eighty Eight';
89: s := 'Eighty Nine';
90: s := 'Ninety';
91: s := 'Ninety One';
92: s := 'Ninety Two';
93: s := 'Ninety Three';
94: s := 'Ninety Four';
95: s := 'Ninety Five';
96: s := 'Ninety Six';
97: s := 'Ninety Seven';
98: s := 'Ninety Eight';
99: s := 'Ninety Nine';
end;
case hun of
0: ss := '';
1: ss := 'One Hundred';
2: ss := 'Two Hundred';
3: ss := 'Three Hundred';
4: ss := 'Four Hundred';
5: ss := 'Five Hundred';
6: ss := 'Six Hundred';
7: ss := 'Seven Hundred';
8: ss := 'Eight Hundred';
9: ss := 'Nine Hundred';
end;
if (hun > 0) and (Ten > 0) then Result := ss + ' ' + AndStr + ' ' + s;
if (hun = 0) and (Ten > 0) then Result := s;
if (hun > 0) and (Ten = 0) then Result := ss;
end;
Function NumberInWords_EN(TheNumber : Integer) : String;
var mil, th, hun, ones : integer;
MilStr, ThStr, AndStr : string;
begin
MilStr := ' Milion ';
ThStr := ' Thousand ';
AndStr := ' And ';
ones := Round(Int(TheNumber));
mil := ones div 1000000;
th := (ones mod 1000000) div 1000;
hun := ones mod 1000;
Result := '';
if mil > 0 then Result := HunToStr_EN(mil) + MilStr;
if (mil > 0) and ((th + hun) > 0) then Result := Result + AndStr;
if th > 0 then Result := Result + HunToStr_EN(th) + ThStr;
if (mil + th > 0) and (hun > 0) then Result := Result + AndStr;
if hun > 0 then Result := Result + HunToStr_EN(hun);
end;
Function NumberInWords_AR(TheNumber : Integer) : String;
var mil, th, hun, ones : integer;
MilStr, ThStr, AndStr : string;
begin
MilStr := ' مليون ';
ThStr := ' ألف ';
AndStr := ' و ';
ones := Round(Int(TheNumber));
mil := ones div 1000000;
th := (ones mod 1000000) div 1000;
hun := ones mod 1000;
Result := '';
if mil > 0 then Result := HunToStr_AR(mil) + MilStr;
if (mil > 0) and ((th + hun) > 0) then Result := Result + AndStr;
if th > 0 then Result := Result + HunToStr_AR(th) + ThStr;
if (mil + th > 0) and (hun > 0) then Result := Result + AndStr;
if hun > 0 then Result := Result + HunToStr_AR(hun);
end;
Function NumberInWords (TheNumber : Integer ) : String;
begin
if UniMainModule.RTL then Result := NumberInWords_AR(TheNumber)
else
Result := NumberInWords_EN(TheNumber);
end;
End. |
unit EST0002C.View;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, CadastroBase.View, cxGraphics,
cxLookAndFeels,
cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore, dxSkinDevExpressDarkStyle,
dxSkinDevExpressStyle,
dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Silver,
cxControls, cxContainer,
cxEdit, dxGDIPlusClasses, Vcl.ExtCtrls, cxLabel, Vcl.StdCtrls, cxButtons,
cxMemo, cxTextEdit, Generics.Collections,
dxBarBuiltInMenu, cxPC, cxStyles, cxCustomData, cxFilter, cxData,
cxDataStorage, cxNavigator,
cxDataControllerConditionalFormattingRulesManagerDialog, Data.DB, cxDBData,
cxGridLevel,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses,
cxGridCustomView, cxGrid, Base.View.Interf, Tipos.Controller.Interf,
Orcamento.Controller.Interf, Produto.Controller.interf, Datasnap.DBClient,
TESTORCAMENTOITENS.Entidade.Model, ormbr.container.DataSet.interfaces,
ormbr.container.fdmemtable, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, FireDAC.Stan.Async, FireDAC.DApt, dxSkinOffice2016Colorful,
dxSkinOffice2016Dark, Fornecedor.Controller.Interf, dxSkinBlack, dxSkinDarkRoom, dxSkinSilver;
type
TFEST0002CView = class(TFCadastroView, IBaseCadastroView)
TeIdProduto: TcxTextEdit;
cxLabel6: TcxLabel;
TeDescricao: TcxMemo;
cxLabel3: TcxLabel;
cxPageControl1: TcxPageControl;
TbItens: TcxTabSheet;
PnCrud: TPanel;
BtExcluirItem: TcxButton;
BtNovoItem: TcxButton;
DbDados: TcxGrid;
VwDados: TcxGridDBTableView;
LvDados: TcxGridLevel;
TbFornecedores: TcxTabSheet;
DbDadosFornec: TcxGrid;
VwDadosFornec: TcxGridDBTableView;
LvDadosFornec: TcxGridLevel;
Panel6: TPanel;
BtExcluirFornec: TcxButton;
BtNovoFornec: TcxButton;
DsItens: TDataSource;
VwDadosDESCRICAO: TcxGridDBColumn;
VwDadosUNIDMEDIDA: TcxGridDBColumn;
VwDadosQTDE: TcxGridDBColumn;
CdItens: TClientDataSet;
CdItensCODIGO: TStringField;
CdItensDESCRICAO: TStringField;
CdItensUNIDMEDIDA: TStringField;
CdItensQTDE: TFloatField;
CdItensCODIGO_SINAPI: TStringField;
VwDadosCODIGO_SINAPI: TcxGridDBColumn;
StGrid: TcxStyleRepository;
StHeader: TcxStyle;
StBackground: TcxStyle;
StContentOdd: TcxStyle;
StContentEven: TcxStyle;
StSelection: TcxStyle;
StInactive: TcxStyle;
PnCampos: TPanel;
GrdItens: TPanel;
DsFornecedores: TDataSource;
VwDadosFornecIDFORNECEDOR: TcxGridDBColumn;
VwDadosFornecNOMEFANTASIA: TcxGridDBColumn;
CdFornecedores: TClientDataSet;
CdFornecedoresCODIGO: TStringField;
CdFornecedoresIDFORNECEDOR: TStringField;
CdFornecedoresNOMEFANTASIA: TStringField;
procedure FormCreate(Sender: TObject);
procedure BtSalvarClick(Sender: TObject);
procedure BtNovoItemClick(Sender: TObject);
procedure BtExcluirItemClick(Sender: TObject);
procedure BtNovoFornecClick(Sender: TObject);
procedure BtExcluirFornecClick(Sender: TObject);
private
FOrcamento: IOrcamentoController;
FProdutoController: IProdutoController;
FFornecedorController: IFornecedorController;
FRegistro: string;
FItens: TList<TOrcamentoItens>;
FFornecedores: TList<TOrcamentoFornecedores>;
procedure exibirFornecedoresNaTela;
procedure exibirItensNaTela;
procedure salvarDados;
procedure exibirDadosNaTela;
procedure desabilitaCampos;
procedure addItem(AValue: string); overload;
procedure addItem(AValue: string; AQtde: Double); overload;
procedure addForncedor(AValue: string);
procedure carregarItens;
procedure carregarFornecedores;
public
class function New: IBaseCadastroView;
function operacao(AValue: TTipoOperacao): IBaseCadastroView;
function registroSelecionado(AValue: string): IBaseCadastroView;
procedure &executar;
end;
var
FEST0002CView: TFEST0002CView;
implementation
{$R *.dfm}
uses FacadeController, FacadeView;
{ TFEST0002CView }
procedure TFEST0002CView.addItem(AValue: string);
begin
if AValue = EmptyStr then Exit;
FProdutoController.localizar(AValue);
if CdItens.Locate('CODIGO', AValue, []) then begin
CdItens.Edit;
CdItensQTDE.AsFloat := CdItensQTDE.AsFloat + 1;
CdItens.Post;
Exit;
end;
CdItens.Insert;
CdItensCODIGO.AsString := AValue;
CdItensCODIGO_SINAPI.AsString := FProdutoController.codigoSinapi;
CdItensDESCRICAO.AsString := FProdutoController.descricao;
CdItensUNIDMEDIDA.AsString := FProdutoController.unidMedida;
CdItensQTDE.AsFloat := 1;
CdItens.Post;
end;
procedure TFEST0002CView.addForncedor(AValue: string);
begin
if AValue = EmptyStr then Exit;
FFornecedorController.localizar(AValue);
if CdFornecedores.Locate('CODIGO', AValue, []) then begin
TFacadeView
.New
.MensagensFactory
.exibirMensagem(tmAlerta)
.mensagem(Format('JŠ foi informado o fornecedor %s', [CdFornecedoresNOMEFANTASIA.AsString]))
.exibir;
Exit;
end;
CdFornecedores.Insert;
CdFornecedoresCODIGO.AsString := AValue;
CdFornecedoresIDFORNECEDOR.AsString := FFornecedorController.idFornecedor;
CdFornecedoresNOMEFANTASIA.AsString := FFornecedorController.nomeFantasia;
CdFornecedores.Post;
end;
procedure TFEST0002CView.addItem(AValue: string; AQtde: Double);
begin
if AValue = EmptyStr then Exit;
FProdutoController.localizar(AValue);
CdItens.Insert;
CdItensCODIGO.AsString := AValue;
CdItensCODIGO_SINAPI.AsString := FProdutoController.codigoSinapi;
CdItensDESCRICAO.AsString := FProdutoController.descricao;
CdItensUNIDMEDIDA.AsString := FProdutoController.unidMedida;
CdItensQTDE.AsFloat := AQtde;
CdItens.Post;
end;
procedure TFEST0002CView.BtExcluirFornecClick(Sender: TObject);
begin
inherited;
CdFornecedores.Delete;
end;
procedure TFEST0002CView.BtExcluirItemClick(Sender: TObject);
begin
inherited;
CdItens.Delete;
end;
procedure TFEST0002CView.BtNovoFornecClick(Sender: TObject);
begin
inherited;
addForncedor(
TFacadeView.New
.ModulosFacadeView
.PagarFactoryView
.exibirTelaBusca(tbFornecedor)
.exibir
);
end;
procedure TFEST0002CView.BtNovoItemClick(Sender: TObject);
begin
inherited;
addItem(
TFacadeView.New
.ModulosFacadeView
.EstoqueFactoryView
.exibirTelaBusca(tbProduto)
.exibir
);
end;
procedure TFEST0002CView.BtSalvarClick(Sender: TObject);
begin
salvarDados;
inherited;
end;
procedure TFEST0002CView.desabilitaCampos;
begin
if FOperacao in [toConsultar, toExcluir] then
begin
TeIdProduto.Enabled := False;
TeDescricao.Enabled := False;
BtNovoItem.Enabled := False;
BtExcluirItem.Enabled := False;
BtNovoFornec.Enabled := False;
BtExcluirFornec.Enabled := False;
VwDados.OptionsData.Editing := False;
VwDados.OptionsSelection.CellSelect := false;
end;
end;
procedure TFEST0002CView.executar;
begin
exibirDadosNaTela;
desabilitaCampos;
exibirTituloOperacao(FOperacao);
ShowModal;
end;
procedure TFEST0002CView.carregarFornecedores;
var VFornecedor: TOrcamentoFornecedores;
begin
FOrcamento.removerTodosOsFornecedores;
CdFornecedores.First;
while not (CdFornecedores.Eof) do
begin
VFornecedor.codigo := CdFornecedoresCODIGO.AsString;
FOrcamento.AddFornecedor(VFornecedor);
CdFornecedores.Next;
end;
end;
procedure TFEST0002CView.carregarItens;
var VItem: TOrcamentoItens;
begin
FOrcamento.removerTodosOsItens;
CdItens.First;
while not (CdItens.Eof) do
begin
VItem.codigo := CdItensCODIGO.AsString;
VItem.qtde := CdItensQTDE.AsFloat;
FOrcamento.AddItem(VItem);
CdItens.Next;
end;
end;
procedure TFEST0002CView.exibirDadosNaTela;
begin
if FOperacao = toIncluir then
Exit;
FOrcamento.localizar(FRegistro);
TeIdProduto.Text := FOrcamento.idOrcamento;
TeDescricao.Text := FOrcamento.descricao;
{1} exibirFornecedoresNaTela;
{2} exibirItensNaTela;
end;
procedure TFEST0002CView.exibirFornecedoresNaTela;
var
I: Integer;
begin
FFornecedores := FOrcamento.fornecedores;
for I := 0 to Pred(FFornecedores.Count) do
begin
addForncedor(FFornecedores.Items[I].codigo);
end;
end;
procedure TFEST0002CView.exibirItensNaTela;
var
I: Integer;
begin
FItens := FOrcamento.itens;
for I := 0 to pred(FItens.Count) do
begin
addItem(FItens[I].codigo, FItens[I].qtde);
end;
end;
procedure TFEST0002CView.FormCreate(Sender: TObject);
begin
inherited;
FOrcamento := TFacadeController.New.modulosFacadeController.
estoqueFactoryController.Orcamento;
FProdutoController := TFacadeController.New.modulosFacadeController.
estoqueFactoryController.Produto;
FFornecedorController := TFacadeController.New.modulosFacadeController.
pagarFactoryController.Fornecedor;
Self.Width := Screen.Width - 100;
Self.Height := Screen.Height - 100;
end;
class function TFEST0002CView.New: IBaseCadastroView;
begin
Result := Self.Create(nil);
end;
function TFEST0002CView.operacao(AValue: TTipoOperacao): IBaseCadastroView;
begin
Result := Self;
FOperacao := AValue;
end;
function TFEST0002CView.registroSelecionado(AValue: string): IBaseCadastroView;
begin
Result := Self;
FRegistro := AValue;
end;
procedure TFEST0002CView.salvarDados;
begin
case FOperacao of
toIncluir:
begin
carregarItens;
carregarFornecedores;
FOrcamento
.Incluir
.descricao(TeDescricao.Text)
.finalizar;
end;
toAlterar:
begin
carregarItens;
carregarFornecedores;
FOrcamento
.Alterar
.descricao(TeDescricao.Text)
.finalizar;
end;
toExcluir:
begin
FOrcamento
.Excluir
.finalizar;
end;
toDuplicar:
begin
carregarItens;
carregarFornecedores;
FOrcamento
.Duplicar
.descricao(TeDescricao.Text)
.finalizar;
end;
end;
end;
end.
|
unit DataUtils;
interface
uses
DBXCommon, DBClient;
procedure CopyReaderToClientDataSet(Reader: TDBXReader; var ClientDataSet: TClientDataSet);
implementation
procedure CopyReaderToClientDataSet(Reader: TDBXReader; var ClientDataSet: TClientDataSet);
var
i: Integer;
begin
ClientDataSet.CreateDataSet;
while Reader.Next do
begin
ClientDataSet.Append;
for i := 0 to Reader.ColumnCount - 1 do
begin
case Reader.Value[i].ValueType.DataType of
TDBXDataTypes.AnsiStringType,
TDBXDataTypes.BlobType:
ClientDataSet.Fields[i].AsString := Reader.Value[i].AsString;
TDBXDataTypes.CurrencyType,
TDBXDataTypes.DoubleType:
ClientDataSet.Fields[i].AsCurrency := Reader.Value[i].AsDouble;
TDBXDataTypes.Int32Type:
ClientDataSet.Fields[i].AsInteger := Reader.Value[i].AsInt32;
TDBXDataTypes.DateTimeType,
TDBXDataTypes.DateType,
TDBXDataTypes.TimeStampType:
ClientDataSet.Fields[i].AsDateTime := Reader.Value[i].AsDateTime;
TDBXDataTypes.BooleanType:
ClientDataSet.Fields[i].AsBoolean := Reader.Value[i].AsBoolean;
end;
end;
ClientDataSet.Post;
end;
ClientDataSet.First;
end;
end.
|
{ RRRRRR ReportBuilder Class Library BBBBB
RR RR BB BB
RRRRRR Digital Metaphors Corporation BB BB
RR RR BB BB
RR RR Copyright (c) 1996-2001 BBBBB }
unit uRBFunction;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls,
Forms, Dialogs, raFunc, ppRTTI, ppReport{, uRBInputBoxFch, uRBTestemunhaFch};
type
{ TSIGRBFunctionLowerCase class }
TFormatFunction = class(TraSystemFunction)
public
class function Category: string; override;
class function GetSignature: string; override;
procedure ExecuteFunction(aParams: TraParamList); override;
end;
{ TSIGRBFunctionExtenso class }
TExtensoFunction = class(TraSystemFunction)
public
class function Category: string; override;
class function GetSignature: string; override;
procedure ExecuteFunction(aParams: TraParamList); override;
end;
{ Alex Begin - 2011/07/14 }
{ TSIGRBFileExists class }
TFileExistsFunction = class(TraSystemFunction)
public
class function Category: string; override;
class function GetSignature: string; override;
procedure ExecuteFunction(aParams: TraParamList); override;
end;
{ Alex End - 2011/07/14 }
{ TSIGRBGetUsuarioFunction class }
TGetUsuarioFunction = class(TraSystemFunction)
public
class function Category: string; override;
class function GetSignature: string; override;
procedure ExecuteFunction(aParams: TraParamList); override;
end;
{ TSIGRBGetDefaultLanguageFunction class }
TDefaultLanguageFunction = class(TraSystemFunction)
public
class function Category: string; override;
class function GetSignature: string; override;
procedure ExecuteFunction(aParams: TraParamList); override;
end;
{ TSIGRBPrintCommandFunction class }
TPrintCommandFunction = class(TraSystemFunction)
public
class function Category: string; override;
class function GetSignature: string; override;
procedure ExecuteFunction(aParams: TraParamList); override;
end;
implementation
uses
{uExtenso, } uDM, uDMGlobal, WinSpool, Printers;
{ TSIGRBFunctionLowerCase }
class function TFormatFunction.Category: string;
begin
Result := 'MR';
end;
class function TFormatFunction.GetSignature: string;
begin
result := 'function FormatName(var sInputString: string): string;';
end;
procedure TFormatFunction.ExecuteFunction(aParams: TraParamList);
var
sTemp1, sTemp2, sTemp3, sTemp4: string;
bChangeToUpper: Boolean;
iX: integer;
lsResult: string;
begin
GetParamValue(0, sTemp4);
try
sTemp1 := LowerCase(sTemp4);
bChangeToUpper := True;
for iX := 1 to length(sTemp1) do
begin
if bChangeToUpper then
sTemp2 := sTemp2 + UpperCase(sTemp1[iX])
else
sTemp2 := sTemp2 + sTemp1[iX];
bChangeToUpper := (sTemp1[iX] = ' ');
if bChangeToUpper then
begin
sTemp3 := copy(sTemp2, length(sTemp2) - 3, length(sTemp2));
sTemp3 := Trim(sTemp3);
if length(sTemp3) = 2 then
begin
sTemp3 := LowerCase(sTemp3);
sTemp2 := copy(sTemp2, 1, length(sTemp2) - 3) + sTemp3 + ' ';
end;
end;
end;
sTemp4 := sTemp2;
except
sTemp4 := '';
end;
lsResult := sTemp4;
SetParamValue(0, sTemp4);
SetParamValue(1, lsResult);
end;
{ TExtensoFunction }
class function TExtensoFunction.Category: string;
begin
Result := 'MR';
end;
procedure TExtensoFunction.ExecuteFunction(aParams: TraParamList);
var
sTemp1: double;
sTemp2, lsResult: string;
begin
GetParamValue(0, sTemp1);
//sTemp2 := Extenso(sTemp1);
lsResult := STemp2;
SetParamValue(0, sTemp1);
SetParamValue(1, lsResult);
end;
class function TExtensoFunction.GetSignature: string;
begin
result := 'Function Extenso(Valor: double):string;';
end;
{ Alex Begin - 2011/07/14 }
{ TFileExistsFunction }
class function TFileExistsFunction.Category: string;
begin
Result := 'MR';
end;
procedure TFileExistsFunction.ExecuteFunction(aParams: TraParamList);
var
sFileName : String;
lbResult: Boolean;
begin
GetParamValue(0, sFileName);
lbResult := FileExists( sFileName );
SetParamValue(1, lbResult);
end;
class function TFileExistsFunction.GetSignature: string;
begin
result := 'Function FileExists( psFileName : String ) : Boolean;';
end;
{ Alex End - 2011/07/14 }
{ TGetUsuarioFunction }
class function TGetUsuarioFunction.Category: string;
begin
Result := 'MR';
end;
procedure TGetUsuarioFunction.ExecuteFunction(aParams: TraParamList);
var
sUsuario : string;
lbResult: Boolean;
begin
GetParamValue(0, sUsuario);
sUsuario := DM.fUser.UserName;
lbResult := True;
SetParamValue(0, sUsuario);
SetParamValue(1, lbResult);
end;
class function TGetUsuarioFunction.GetSignature: string;
begin
result := 'function GetUsuario(var sUsuario : String): Boolean;';
end;
{ TSIGRBGetDefaultLanguageFunction class }
class function TDefaultLanguageFunction.Category: string;
begin
Result := 'MR';
end;
procedure TDefaultLanguageFunction.ExecuteFunction(aParams: TraParamList);
var
iLang : Integer;
lbResult: Boolean;
begin
lbResult := True;
iLang := DMGlobal.IDLanguage;
SetParamValue(0, iLang);
SetParamValue(1, lbResult);
end;
class function TDefaultLanguageFunction.GetSignature: string;
begin
result := 'function GetIDLanguage(var IDLang: Integer):Boolean;';
end;
{
procedure TForm1.SendControlCode(S: string);
end;
}
{ TPrintCommandFunction }
class function TPrintCommandFunction.Category: string;
begin
Result := 'MR';
end;
procedure TPrintCommandFunction.ExecuteFunction(aParams: TraParamList);
type
TppEscapeDataRec = packed record
DataLen: Word;
DataBuf: Array [0..128] of Char;
end;
var
lEscapeDataRec: TppEscapeDataRec;
AReport: TppReport;
aPrinterCommands : String;
iResult : Integer;
begin
GetParamValue(0, AReport);
GetParamValue(1, aPrinterCommands);
// setup the data
lEscapeDataRec.DataLen := Length(aPrinterCommands);
StrLCopy(lEscapeDataRec.DataBuf, PChar(aPrinterCommands), 128);
// Windows API Escape call
Escape(AReport.Printer.Canvas.Handle, PASSTHROUGH, 0, @lEscapeDataRec, nil);
//iResult := Escape(AReport.Printer.Canvas.Handle, PASSTHROUGH, SizeOf(lEscapeDataRec), @lEscapeDataRec, nil);
//SetParamValue(2, bResult);
end;
(*
var
Handle, hDeviceMode: THandle;
N: DWORD;
DocInfo1: TDocInfo1;
Device, Driver, Port: array[0..255] of char;
PrinterName: string;
buf:array[0..255] of char;
lbuf:integer;
s : String;
lbResult : Boolean;
begin
GetParamValue(0, s);
lbResult := True;
s := Chr(27)+Chr(12);
//Printer.GetPrinter(Device, Driver, Port, hDeviceMode);
PrinterName := DM.fPrintReceipt.InvoiceReportPrinter; //Format('%s', [Device]);
if not OpenPrinter(PChar(PrinterName), Handle, nil) then
lbResult := False;
//RaiseLastWin32Error;
try
with DocInfo1 do
begin
pDocName := 'Control';
pOutputFile := nil;
pDataType := 'RAW';
end;
StartDocPrinter(Handle, 1, @DocInfo1);
try
lbuf:=length(s);
copymemory(@buf,Pchar(s),lbuf);
if not WritePrinter(Handle, @buf, lbuf, N) then
lbResult := False;
// RaiseLastWin32Error;
finally
EndDocPrinter(Handle);
end;
finally
ClosePrinter(Handle);
SetParamValue(1, lbResult);
end;
end; *)
class function TPrintCommandFunction.GetSignature: string;
begin
result := 'function PrintCommand(AReport: TppReport; Command: String):Boolean;';
end;
initialization
raRegisterFunction('FormatName', TFormatFunction);
raRegisterFunction('Extenso', TExtensoFunction);
raRegisterFunction('FileExists', TFileExistsFunction);
raRegisterFunction('GetUsuario', TGetUsuarioFunction);
raRegisterFunction('GetIDLanguage', TDefaultLanguageFunction);
raRegisterFunction('PrintCommand', TPrintCommandFunction);
finalization
raUnRegisterFunction('FormatName');
raUnRegisterFunction('FileExists');
raUnRegisterFunction('Extenso');
raUnRegisterFunction('GetUsuario');
raUnRegisterFunction('GetIDLanguage');
raUnRegisterFunction('PrintCommand');
end.
|
unit TpModule;
interface
uses
Windows, Classes, Controls, StdCtrls, ExtCtrls, Graphics, Messages, SysUtils,
Types, Forms,
dcfdes,
ThWebControl, ThTag, ThAttributeList, ThTextPaint, ThCssStyle,
TpControls, TpAnchor,
DesignView;
type
TTpModule = class(TThWebControl) //GraphicControl)
private
FModuleForm: TForm;
FModuleName: string;
FOnGenerate: TTpEvent;
protected
procedure SetModuleName(const Value: string);
protected
procedure CellTag(inTag: TThTag); override;
procedure CreateWnd; override;
procedure Loaded; override;
procedure LoadModuleForm;
procedure Paint; override;
procedure Tag(inTag: TThTag); override;
public
constructor Create(inOwner: TComponent); override;
property ModuleForm: TForm read FModuleForm write FModuleForm;
published
property Align;
property ModuleName: string read FModuleName write SetModuleName;
property OnGenerate: TTpEvent read FOnGenerate write FOnGenerate;
property Style;
property StyleClass;
property Visible;
end;
implementation
uses
Main;
{ TTpModule }
constructor TTpModule.Create(inOwner: TComponent);
begin
inherited;
//Transparent := false;
{
ModuleForm := TForm.Create(Owner);
ModuleForm.Name := 'ModuleForm';
ModuleForm.Parent := Self;
ModuleForm.Align := alClient;
ModuleForm.Enabled := false;
//ModuleForm.Visible := true;
ModuleForm.Color := clLime;
}
{
with TPanel.Create(Owner) do
begin
Name := 'ModulePanel';
Parent := Self;
Align := alClient;
Enabled := false;
//ModuleForm.Visible := true;
Color := clLime;
end;
}
end;
procedure TTpModule.CreateWnd;
begin
inherited;
// ModuleForm.Visible := true;
end;
procedure TTpModule.Loaded;
begin
inherited;
LoadModuleForm;
end;
procedure TTpModule.Paint;
var
c: TColor;
begin
inherited;
if ControlCount = 0 then
// if ShowHash then
with Canvas do
begin
c := Brush.Color;
Brush.Style := bsDiagCross;
Brush.Color := ColorToRgb(clSilver);
Pen.Style := psClear;
if ThVisibleColor(c) then
SetBkColor(Handle, ColorToRgb(c))
else
SetBkMode(Handle, Windows.TRANSPARENT);
Rectangle(AdjustedClientRect);
Brush.Style := bsSolid;
Pen.Style := psSolid;
SetBkMode(Handle, Windows.OPAQUE);
end;
end;
procedure TTpModule.SetModuleName(const Value: string);
begin
FModuleName := Value;
if not (csLoading in ComponentState) then
LoadModuleForm;
end;
{.$define __TEST__}
{$ifdef __TEST__}
procedure TTpModule.LoadModuleForm;
function GetBinaryStream(const inPath: string): TStream;
var
fs: TFileStream;
begin
Result := TMemoryStream.Create;
fs := TFileStream.Create(inPath, fmOpenRead);
try
ObjectTextToBinary(fs, Result);
Result.Seek(0, 0);
finally
fs.Free;
end
end;
var
p: string;
s: TStream;
begin
p := MainForm.Project.ProjectFolder + ModuleName + '.tphp';
if FileExists(p) then
begin
s := GetBinaryStream(p);
try
with TReader.Create(s, 4096) do
try
ReadComponents(Owner, Self, nil);
finally
Free;
end;
finally
s.Free;
end;
// ModuleForm := TForm.Create(Owner);
// with TDCLiteDesigner.Create(nil) do
// try
// LoadFromFile(ModuleForm, p);
// finally
// Free;
// end;
// ModuleForm.Parent := Self;
// ModuleForm.Align := alClient;
// ModuleForm.Enabled := false;
// ModuleForm.Visible := true;
end;
end;
{$ELSE}
procedure TTpModule.LoadModuleForm;
var
p: string;
begin
p := MainForm.Project.ProjectFolder + ModuleName + '.tphp';
if FileExists(p) then
begin
ModuleForm.Free;
//Invalidate;
Application.CreateForm(TDesignForm, FModuleForm);
TDesignForm(ModuleForm).LoadFromFile(p);
ModuleForm.Parent := Self;
ModuleForm.Align := alClient;
ModuleForm.Enabled := false;
ModuleForm.Visible := true;
ModuleForm.Name := Name + 'Objects';
end;
end;
{$ENDIF+}
procedure TTpModule.CellTag(inTag: TThTag);
begin
inherited;
with inTag do
begin
//Attributes.Clear;
Add('id', Name);
Add(tpClass, 'TTpModule');
Add('tpName', Name);
Add('tpModuleName', ModuleName + '.php');
Add('tpOnGenerate', OnGenerate);
end;
end;
procedure TTpModule.Tag(inTag: TThTag);
begin
inherited;
end;
end.
|
unit Coche.Update.VM;
interface
uses
System.SysUtils,
System.Classes,
Data.DB,
Spring,
Spring.Collections,
MVVM.Types,
MVVM.Attributes,
MVVM.Interfaces,
MVVM.Interfaces.Architectural,
MVVM.Bindings,
Coche.Interfaces,
Coche.Types;
type
[ViewModel_Implements(IUpdateCoche_ViewModel)]
TNewCoche_ViewModel = class(TViewModel, IUpdateCoche_ViewModel)
protected
FData : RCoche;
FOnDataSelected: IEvent<TNotify_Coche>;
function GetSetData: TExecuteMethod<RCoche>;
function GetData: RCoche;
procedure SetData(const AData: RCoche);
procedure DataChanged;
function GetOnDataSelected: IEvent<TNotify_Coche>;
public
property DoSetData: TExecuteMethod<RCoche> read GetSetData;
property OnDataSelected: IEvent<TNotify_Coche> read GetOnDataSelected;
property Data: RCoche read GetData write SetData;
end;
implementation
uses
MVVM.Utils;
{ TNewCoche_ViewModel }
procedure TNewCoche_ViewModel.DataChanged;
begin
if Assigned(FOnDataSelected) then
FOnDataSelected.Invoke(FData)
end;
function TNewCoche_ViewModel.GetData: RCoche;
begin
Result := FData;
end;
function TNewCoche_ViewModel.GetOnDataSelected: IEvent<TNotify_Coche>;
begin
if not Assigned(FOnDataSelected) then
FOnDataSelected := Utils.CreateEvent<TNotify_Coche>;
Result := FOnDataSelected;
end;
function TNewCoche_ViewModel.GetSetData: TExecuteMethod<RCoche>;
begin
Result := SetData;
end;
procedure TNewCoche_ViewModel.SetData(const AData: RCoche);
begin
FData := AData;
DataChanged;
end;
end.
|
unit LA.ArrayList;
interface
uses
System.SysUtils,
System.Rtti,
System.Generics.Defaults;
type
TArrayList<T> = class
private type
TArray_T = TArray<T>;
TComparer_T = TComparer<T>;
var
__data: TArray_T;
__size: integer;
procedure __reSize(newCapacity: integer);
public
/// <summary> 获取数组中的元数个数 </summary>
function GetSize: integer;
/// <summary> 获取数组的容量 </summary>
function GetCapacity: integer;
/// <summary> 返回数组是否有空 </summary>
function IsEmpty: boolean;
/// <summary> 获取index索引位置元素 </summary>
function Get(index: integer): T;
/// <summary> 获取第一个元素</summary>
function GetFirst: T;
/// <summary> 获取最后一个元素</summary>
function GetLast: T;
/// <summary> 修改index索引位置元素 </summary>
procedure Set_(index: integer; e: T);
/// <summary> 向所有元素后添加一个新元素 </summary>
procedure AddLast(e: T);
/// <summary> 在第index个位置插入一个新元素e </summary>
procedure Add(index: integer; e: T);
/// <summary> 在所有元素前添加一个新元素 </summary>
procedure AddFirst(e: T);
/// <summary> 查找数组中是否有元素e </summary>
function Contains(e: T): boolean;
/// <summary> 查找数组中元素e忆的索引,如果不存在元素e,则返回-1 </summary>
function Find(e: T): integer;
/// <summary> 从数组中删除index位置的元素,返回删除的元素 </summary>
function Remove(index: integer): T;
/// <summary> 从数组中删除第一个元素,返回删除的元素 </summary>
function RemoveFirst: T;
/// <summary> 从数组中删除i最后一个元素,返回删除的元素 </summary>
function RemoveLast: T;
/// <summary> 从数组中删除元素e </summary>
procedure RemoveElement(e: T);
/// <summary> 返回一个数组 </summary>
function ToArray: TArray_T;
function ToString: string; override;
property Items[i: integer]: T read Get write Set_; default;
/// <summary> 构造函数,传入数组构造Array </summary>
constructor Create(const arr: array of T); overload;
/// <summary>
/// 构造函数,传入数组的容量capacity构造Array。
/// 默认数组的容量capacity:=10
/// </summary>
constructor Create(capacity: integer = 10); overload;
end;
implementation
{ TArrayList<T> }
procedure TArrayList<T>.Add(index: integer; e: T);
var
i: integer;
begin
if (index < 0) or (index > __size) then
raise Exception.Create('Add failed. Require index >= 0 and index <= Size.');
if (__size = Length(__data)) then
__reSize(2 * Length(Self.__data));
for i := __size - 1 downto index do
__data[i + 1] := __data[i];
__data[index] := e;
inc(__size);
end;
procedure TArrayList<T>.AddFirst(e: T);
begin
Add(0, e);
end;
procedure TArrayList<T>.AddLast(e: T);
begin
Add(__size, e);
end;
function TArrayList<T>.Contains(e: T): boolean;
var
i: integer;
comparer: IComparer<T>;
begin
comparer := TComparer_T.Default;
for i := 0 to __size - 1 do
begin
if comparer.Compare(__data[i], e) = 0 then
Exit(True);
end;
Result := False;
end;
constructor TArrayList<T>.Create(capacity: integer);
begin
SetLength(__data, capacity);
end;
constructor TArrayList<T>.Create(const arr: array of T);
var
i: integer;
begin
SetLength(Self.__data, Length(arr));
for i := 0 to Length(arr) - 1 do
__data[i] := arr[i];
__size := Length(arr);
end;
function TArrayList<T>.Find(e: T): integer;
var
i: integer;
comparer: IComparer<T>;
begin
comparer := TComparer_T.Default;
for i := 0 to __size - 1 do
begin
if comparer.Compare(__data[i], e) = 0 then
Exit(i);
end;
Result := -1;
end;
function TArrayList<T>.Get(index: integer): T;
begin
if (index < 0) or (index > __size) then
raise Exception.Create('Get failed. Index is illegal.');
Result := __data[index];
end;
function TArrayList<T>.GetCapacity: integer;
begin
Result := Length(Self.__data);
end;
function TArrayList<T>.GetFirst: T;
begin
Result := Get(0);
end;
function TArrayList<T>.GetLast: T;
begin
Result := Get(__size - 1);
end;
function TArrayList<T>.GetSize: integer;
begin
Result := Self.__size;
end;
function TArrayList<T>.IsEmpty: boolean;
begin
Result := Self.__size = 0;
end;
function TArrayList<T>.Remove(index: integer): T;
var
i: integer;
res: T;
begin
if (index < 0) or (index > __size) then
raise Exception.Create('Remove failed. Index is illegal.');
res := __data[index];
for i := index + 1 to __size - 1 do
__data[i - 1] := __data[i];
Dec(Self.__size);
if (__size = Length(Self.__data) div 4) and (Length(Self.__data) div 2 <> 0)
then
__reSize(Length(Self.__data) div 2);
Result := res;
end;
procedure TArrayList<T>.RemoveElement(e: T);
var
index, i: integer;
begin
for i := 0 to __size - 1 do
begin
index := Find(e);
if index <> -1 then
Remove(index);
end;
end;
function TArrayList<T>.RemoveFirst: T;
begin
Result := Remove(0);
end;
function TArrayList<T>.RemoveLast: T;
begin
Result := Remove(__size - 1);
end;
procedure TArrayList<T>.Set_(index: integer; e: T);
begin
if (index < 0) or (index > __size) then
raise Exception.Create('Set failed. Require index >= 0 and index < Size.');
__data[index] := e;
end;
function TArrayList<T>.ToArray: TArray_T;
var
i: integer;
arr: TArray_T;
begin
SetLength(arr, __size);
for i := 0 to __size - 1 do
arr[i] := __data[i];
Result := arr;
end;
function TArrayList<T>.ToString: string;
var
res: TStringBuilder;
i: integer;
value: TValue;
begin
res := TStringBuilder.Create;
try
res.AppendFormat('Array: Size = %d, capacity = %d',
[Self.__size, Length(Self.__data)]);
res.AppendLine;
res.Append(' [');
for i := 0 to __size - 1 do
begin
TValue.Make(@__data[i], TypeInfo(T), value);
if (value.IsOrdinal) then
res.Append(value.ToString)
else
res.Append(value.AsObject.ToString);
if i <> __size - 1 then
res.Append(', ');
end;
res.Append(']');
Result := res.ToString;
finally
res.Free;
end;
end;
procedure TArrayList<T>.__reSize(newCapacity: integer);
begin
SetLength(Self.__data, newCapacity);
end;
end.
|
unit Validador.Core.ConversorXMLDataSet;
interface
uses
Validador.Data.dbChangeXML, FireDac.Comp.Client, Validador.Data.FDDbChange, Xml.xmldom,
Xml.XMLDoc, Xml.XMLIntf;
type
IConversorXMLDataSet = interface(IInterface)
['{D0CE5ECC-B265-48FC-ACAF-0CEA59F5975C}']
procedure SetXML(const Xml: IXMLDocument);
procedure SetDataSet(const ADataSet: TFDDbChange);
procedure ConverterParaDataSet;
procedure ConverterParaXML;
procedure DataSetParaImportacao;
end;
implementation
end.
|
unit uFrmListaPadrao;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants, System.Messaging,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts,
FMX.Controls.Presentation, FMX.StdCtrls, FMX.ListView.Types,
FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.ListView,
Data.Bind.GenData, FMX.Bind.GenData, System.Rtti, System.Bindings.Outputs,
FMX.Bind.Editors, Data.Bind.EngExt, FMX.Bind.DBEngExt, Data.Bind.Components,
Data.Bind.ObjectScope, System.ImageList, FMX.ImgList, FMX.Objects,
FMX.TabControl, ufrmTeste, FMX.MultiView, FMX.Platform;
type
TfrmListaPadrao = class(TForm)
lytBase: TLayout;
lvLista: TListView;
btnAdd: TRoundRect;
tbMenu: TToolBar;
btnMenu: TButton;
btnExtras: TButton;
mvFunc: TMultiView;
ilPadrao: TImageList;
lytLista: TLayout;
Glyph1: TGlyph;
lblJanela: TLabel;
procedure lvListaItemClick(const Sender: TObject;
const AItem: TListViewItem);
procedure btnAddClick(Sender: TObject);
procedure mvFuncShown(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure mvFuncStartShowing(Sender: TObject);
private
{ Private declarations }
procedure resizeMV;
procedure DoOrientationChanged(const Sender: TObject; const M: TMessage);
public
{ Public declarations }
end;
var
frmListaPadrao: TfrmListaPadrao;
implementation
{$R *.fmx}
{ TfrmListaPadrao }
procedure TfrmListaPadrao.btnAddClick(Sender: TObject);
begin
if not mvFunc.IsShowed then
mvFunc.ShowMaster;
end;
procedure TfrmListaPadrao.DoOrientationChanged(const Sender: TObject;
const M: TMessage);
var
screenService: IFMXScreenService;
begin
if TPlatformServices.Current.SupportsPlatformService(IFMXScreenService,
screenService) then
begin
resizeMV;
end;
end;
procedure TfrmListaPadrao.FormCreate(Sender: TObject);
begin
mvFunc.HideMaster;
resizeMV;
TMessageManager.DefaultManager.SubscribeToMessage(TOrientationChangedMessage,
DoOrientationChanged);
end;
procedure TfrmListaPadrao.FormDestroy(Sender: TObject);
begin
TMessageManager.DefaultManager.Unsubscribe(TOrientationChangedMessage,
DoOrientationChanged);
end;
procedure TfrmListaPadrao.lvListaItemClick(const Sender: TObject;
const AItem: TListViewItem);
begin
if not mvFunc.IsShowed then
mvFunc.ShowMaster;
end;
procedure TfrmListaPadrao.mvFuncShown(Sender: TObject);
begin
lytLista.Margins.Left := 5;
end;
procedure TfrmListaPadrao.mvFuncStartShowing(Sender: TObject);
begin
// resizeMV;
end;
procedure TfrmListaPadrao.resizeMV;
begin
{$IF DEFINED (MSWINDOWS)}
mvFunc.Width := 380;
mvFunc.Mode := TMultiViewMode.Panel;
{$ENDIF}
Application.ProcessMessages;
if (Screen.Size.Width < 700) then
begin
mvFunc.Width := Screen.Size.Width;
end
else
mvFunc.Width := 400;
Application.ProcessMessages;
end;
end.
|
unit Interfaces.Floor;
interface
uses
System.Classes,
System.Types,
Vcl.ExtCtrls;
type
IFloor = Interface(IInterface)
['{47E6A6F7-E115-44CD-8EE9-0A6FD7520A79}']
function Position(const Value: TPoint): IFloor; overload;
function Position: TPoint; overload;
function Goal(const Value: Boolean): IFloor; overload;
function Goal: Boolean; overload;
function Owner(const Value: TGridPanel): IFloor; overload;
function Owner: TGridPanel; overload;
function CreateImages: IFloor;
End;
implementation
end.
|
unit RangeTree1D_u;
{ Delphi implementation of generic 1D range search -> TRangeTree1D<TKey>
Based on the ideas in session 2, 3 of the course 6.851 MIT OpenWare
https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-851-advanced-data-structures-spring-2012/lecture-videos/
HOW TO USE:
TKey is a userdefined class that allows for the relational operator "<" , defined
through a comparison function that must be provided by the user in the constructor.
the DS TRangeTree1D<TKey> can then be arranged statically using build method
for a given input List of TKey or it can be arranged dinamically using insert and
delete methods one by one on the members of the List. At this point the DS will
contain a set of keys S, and is ready to answer queries on the form find the subset Sm
with the keys that lie in the interval [k1,k2], where k1, k2 are some bounding keys that
cdefine a 1D interval.
queries: expected time scale
insert, O(log|S|)
delete, O(log|S|)
isAnyInRange O(log|S|)
HowManyInRange, O(log|S|)
getSortedListOfKeysInRange, O(Sm + log|S|)
getDictOfKeysInRange O(Sm + log|S|)
Note: see the procedures BuildRangeTreeDynamicAndQuery and BuildRangeTreeStaticAndQuery, for
an example on how to use TRangeTree1D<TKey>. There we use TKey = TEdges2D an edge defined by
2 EndPoints that we query by their lengths.
OVERVIEW
Balanced trees using BB[alpha] tree -> Tree with data at the the leafs.
after Insert/elete Operations the tree is rebalance automaticaly if there is a neeed.}
interface
uses Math, System.SysUtils,DIalogs, System.Variants, System.Classes, System.Generics.collections,
Generics.Defaults;
type TRangeTree1DNode<TKey> = class
parent, left, right : TRangeTree1DNode<TKey>;
isLeftChild : Boolean;
key : TKey;
compare : TComparison<TKey>;
public
constructor create(const compare_ : TComparison<TKey>);
procedure initNode(const key_: TKey; const parent_: TRangeTree1DNode<TKey>);
function find(const key : TKey) : TRangeTree1DNode<TKey>;
procedure insert(var node : TRangeTree1DNode<TKey>);
private
size, size_left, size_right : Integer;
isLeaf : Boolean;
function isBalanced : Boolean;
procedure Balance(var pointerToRoot : TRangeTree1DNode<TKey>);
procedure SplitNode(const idxStart, idxEnd : Integer; const SortedListOfLeafNodes : TList<TRangeTree1DNode<TKey>>; var ListOfNoLeafNodes : TList<TRangeTree1DNode<TKey>>); overload;
procedure SplitNode(const idxStart, idxEnd : Integer;const SortedList : TList<TKey>); overload;
procedure UpdateSizesUpToTheRoot(var HighestInbalancedNode : TRangeTree1DNode<TKey>);
procedure ExtractSubTreeNodes(var ListOfLeafs, ListOfNoLeafs : TList<TRangeTree1DNode<TKey>>);
function getRightMostNodeOfSubtree : TRangeTree1DNode<TKey>;
end;
type TRangeTree1D<TKey> = Class(TObject)
compare : TComparison<TKey>;
private
root : TRangeTree1DNode<TKey>;
OutputDictOfKeys : TDictionary<TKey,Boolean>;
OutputSortedListOfKeys : TList<TKey>;
FCount : Integer; // number of objects in the tree
procedure CollectSortedKeysOfSubtree(const node : TRangeTree1DNode<TKey>);
procedure CollectSortedKeysGTk1(const node : TRangeTree1DNode<TKey>; const k1 : TKey);
procedure CollectSortedKeysLTk2(const node : TRangeTree1DNode<TKey>; const k2 : TKey);
procedure CollectSubTreeLeafsToDictionary(const node : TRangeTree1DNode<TKey>);
function getBifurcationNode(const k1,k2 : TKey) : TRangeTree1DNode<TKey>;
function extract(const key : TKey) : TRangeTree1DNode<TKey>;
function find(const key : TKey): TRangeTree1DNode<TKey>;
public
constructor create(const compare_ : TComparison<TKey>);
procedure Build(var ListOfKeys : TList<TKey>);
procedure free;
function insert(const key : TKey) : Boolean;
function delete(const key : TKey) : Boolean;
property Count : integer read FCount;
function isAnyInRange(const key1, key2 : TKey) : Boolean;
function HowManyInRange(const key1, key2 : TKey) : Integer;
function getDictOfMembersInRange(const key1, key2 : TKey) : TDictionary<TKey,Boolean>;
function getSortedListOfMembersInRange(const key1, key2 : TKey) : TList<TKey>;
end;
//// Forward declaration
//procedure BuildRangeTreeDynamicAndQuery;
//procedure BuildRangeTreeStaticAndQuery;
implementation
const alpha = 0.2;
// Begin define methods of TRangeTree1DNode
constructor TRangeTree1DNode<TKey>.create(const compare_ : TComparison<TKey>);
begin
inherited create;
compare := compare_;
end;
procedure TRangeTree1DNode<TKey>.initNode(const key_: TKey; const parent_: TRangeTree1DNode<TKey>);
begin
key := key_;
right := nil;
left := nil;
parent := parent_;
isLeaf := TRUE;
size := 1;
size_left := 0;
size_right := 0;
end;
function TRangeTree1DNode<TKey>.isBalanced : Boolean;
{self assumed not a leaf}
var alphaSize : Single;
begin
alphaSize := alpha*size;
if (size_left < alphaSize) OR (size_right < alphaSize) then RESULT := FALSE
else RESULT := TRUE;
end;
procedure TRangeTree1DNode<TKey>.Balance(var pointerToRoot : TRangeTree1DNode<TKey>);
{reuses old nodes}
var ListOfLeafNodes,
ListOfNoLeafNodes : TList<TRangeTree1DNode<TKey>>;
newNode : TRangeTree1DNode<TKey>;
begin
ListOfLeafNodes := TList<TRangeTree1DNode<TKey>>.Create;
ListOfNoLeafNodes := TList<TRangeTree1DNode<TKey>>.Create;
newNode := self;
if Assigned(newNode.parent) then
begin
if newNode.isLeftChild then
newNode.parent.left := newNode
else // then newNode is a rightChild
newNode.parent.right := newNode;
end
else pointerToRoot := NewNode;
self.ExtractSubTreeNodes(ListOfLeafNodes,ListOfNoLeafNodes);
// last member of ListOfNoLeafNodes is self so we exclude it from reusable nodes
ListOfNoLeafNodes.delete(ListOfNoLeafNodes.Count-1);
newNode.splitNode(0,ListOfLeafNodes.Count-1,ListOfLeafNodes,ListOfNoLeafNodes);
ListOfLeafNodes.Free;
ListOfNoLeafNodes.Free;
end;
procedure TRangeTree1DNode<TKey>.ExtractSubTreeNodes(var ListOfLeafs, ListOfNoLeafs : TList<TRangeTree1DNode<TKey>>);
begin
if isLeaf then
ListOfLeafs.Add(Self)
else
begin
Self.left.ExtractSubTreeNodes(ListOfLeafs, ListOfNoLeafs);
Self.right.ExtractSubTreeNodes(ListOfLeafs, ListOfNoLeafs);
ListOfNoLeafs.Add(Self);
end;
end;
procedure TRangeTree1DNode<TKey>.SplitNode(const idxStart, idxEnd : Integer; const SortedListOfLeafNodes : TList<TRangeTree1DNode<TKey>>; var ListOfNoLeafNodes : TList<TRangeTree1DNode<TKey>>);
var idxEndLeft, n, no2 : Integer;
begin
n := idxEnd-idxStart;
if n = 0 then
begin // key has been assigned already
size := 1;
size_left := 0;
size_right := 0;
isLeaf := TRUE;
end
else
begin
no2 := Trunc(0.5*n);
idxEndLeft := idxStart + no2;
// revise CurrentNode
key := SortedListOfLeafNodes[idxEndLeft].key;
size := n+1;
size_left := idxEndLeft-idxStart+1;
size_right := size-size_left;
isLeaf := FALSE;
// we reuse SortedList[idxStart] in left is a leaf
if size_left = 1 then
left := SortedListOfLeafNodes[idxStart]
else // reuse last entry of ListOfNoLeafNodes
begin
left := ListOfNoLeafNodes[ListOfNoLeafNodes.Count-1];
ListOfNoLeafNodes.delete(ListOfNoLeafNodes.Count-1);
end;
left.parent := self;
left.isLeftChild := TRUE;
left.SplitNode(idxStart,idxEndLeft,SortedListOfLeafNodes,ListOfNoLeafNodes);
// we reuse SortedList[idxEndLeft+1] in right is a leaf
if size_right = 1 then
right := SortedListOfLeafNodes[idxEndLeft+1]
else
begin
right := ListOfNoLeafNodes[ListOfNoLeafNodes.Count-1];
ListOfNoLeafNodes.delete(ListOfNoLeafNodes.Count-1);
end;
right.parent := self;
right.isLeftChild := FALSE;
right.SplitNode(idxEndLeft+1,idxEnd,SortedListOfLeafNodes,ListOfNoLeafNodes);
end;
end;
procedure TRangeTree1DNode<TKey>.SplitNode(const idxStart, idxEnd : Integer; const SortedList : TList<TKey>);
var idxEndLeft, n, no2 : Integer;
leafKey : TKey;
begin
n := idxEnd-idxStart;
if n = 0 then
begin
leafkey := SortedList[idxStart];
key := leafkey;
size := 1;
size_left := 0;
size_right := 0;
isLeaf := TRUE;
end
else
begin
no2 := Trunc(0.5*n);
idxEndLeft := idxStart + no2;
// revise CurrentNode
key := SortedList[idxEndLeft];
size := n+1;
size_left := idxEndLeft-idxStart+1;
size_right := size-size_left;
isLeaf := FALSE;
// Create New Left Node
left := TRangeTree1DNode<TKey>.create(compare);
left.parent := self;
left.isLeftChild := TRUE;
left.SplitNode(idxStart,idxEndLeft,SortedList);
// Create New Left Node
right := TRangeTree1DNode<TKey>.create(compare);
right.parent := self;
right.isLeftChild := FALSE;
right.SplitNode(idxEndLeft+1,idxEnd,SortedList);
end;
end;
procedure TRangeTree1DNode<TKey>.UpdateSizesUpToTheRoot(var HighestInbalancedNode : TRangeTree1DNode<TKey>);
{self assumed balanced (because it is a leaf), balance of the sequence of parents up to the root
is revised and Highest Inbalanced parent is output}
var node : TRangeTree1DNode<TKey>;
begin
HighestInbalancedNode := nil;
node := self;
while Assigned(node) do
begin
if Assigned(node.parent) then
begin
Dec(node.parent.size);
if node.isLeftChild then Dec(node.parent.size_left)
else Dec(node.parent.size_right);
// check balance
if NOT node.parent.isBalanced then
HighestInbalancedNode := node.parent;
end;
// update
node := node.parent;
end;
end;
function TRangeTree1DNode<TKey>.find(const key : TKey) : TRangeTree1DNode<TKey>;
(* returns the node containing the key in calling Node's subtree or nil if not found *)
var anInteger : Integer;
begin
anInteger := compare(Self.key,key);
if anInteger = 0 then
begin
RESULT := Self;
Exit;
end
else if anInteger >0 then
begin // look for key in left subtree
if NOT Assigned(Self.left) then
begin RESULT := nil; Exit; end;
RESULT := Self.left.find(key);
end
else //then key > RESULT.key
begin // look for key in right subtree
if NOT Assigned(Self.right) then
begin RESULT := nil; Exit; end;
RESULT := Self.right.find(key);
end;
end;
procedure TRangeTree1DNode<TKey>.insert(var node : TRangeTree1DNode<TKey>);
(* inserts input node into the subtree rooted as calling node,
after this insert the tree needs a balance check from nodes up to root *)
var aInteger : Integer;
tmpKey : TKey;
newNode : TRangeTree1DNode<TKey>;
begin
if NOT Assigned(node) then Exit;
aInteger := Self.compare(Self.key,node.key);
if isLeaf then
begin
Inc(size); Inc(size_left); Inc(size_right);
isLeaf := FALSE;
if aInteger = 1 then
begin
node.isLeftChild := TRUE;
tmpKey := Self.key;
Self.key := node.key; // max of leftSubtree
Self.left := node;
// create a new node to put at the right
newNode := TRangeTree1DNode<TKey>.create(compare);
newNode.initNode(tmpKey,Self);
newNode.isLeftChild := FALSE;
Self.right := newNode;
node.parent := self;
end
else if aInteger = -1 then
begin
node.isLeftChild := FALSE;
Self.right := node;
// create a new node to put at the left
newNode := TRangeTree1DNode<TKey>.create(compare);
newNode.initNode(key,Self);
newNode.isLeftChild := TRUE;
Self.left := newNode;
node.parent := self;
end
else // then node.key = key
Raise Exception.Create('TRangeTree1DNode.Insert Error : attempt to insert a Key already existing');
end
else // naviagate to a leaf
begin
Inc(size);
if aInteger = 1 then
begin
self.left.insert(node);
Inc(size_left);
end
else if aInteger = -1 then
begin
Inc(size_right);
self.right.insert(node);
end
else // then key1 = key2
Raise Exception.Create('TRangeTree1DNode.Insert Error : attempt to insert a Key already existing');
end;
end;
function TRangeTree1DNode<TKey>.getRightMostNodeOfSubtree : TRangeTree1DNode<TKey>;
begin
if isLeaf then RESULT := self
else RESULT := self.right.getRightMostNodeOfSubtree;
end;
// End define methods of TRangeTree1DNode<TKey>
// Begin define methods of TRangeTree1D
constructor TRangeTree1D<TKey>.create(const compare_ : TComparison<TKey>);
begin
inherited create;
root := nil;
compare := compare_;
OutputDictOfKeys := TDictionary<TKey,Boolean>.create;
OutputSortedListOfKeys := TList<TKey>.create;
end;
procedure TRangeTree1D<TKey>.free;
var ListOfLeafNodes,
ListOfNoLeafNodes : TList<TRangeTree1DNode<TKey>>;
i : Integer;
begin
OutputSortedListOfKeys.Free;
OutputDictOfKeys.Free;
if Assigned(root) then
begin
ListOfLeafNodes := TList<TRangeTree1DNode<TKey>>.create;
ListOfNoLeafNodes := TList<TRangeTree1DNode<TKey>>.create;
root.ExtractSubTreeNodes(ListOfLeafNodes,ListOfNoLeafNodes);
// free all Nodes
for i := 0 to ListOfLeafNodes.Count-1 do
ListOfLeafNodes[i].free;
ListOfLeafNodes.Free;
for i := 0 to ListOfNoLeafNodes.Count-1 do
ListOfNoLeafNodes[i].free;
ListOfNoLeafNodes.Free;
end;
inherited free;
end;
procedure TRangeTree1D<TKey>.Build(var ListOfKeys : TList<TKey>);
var compareFun : IComparer<TKey>;
begin
compareFun := TComparer<TKey>.Construct(compare);
ListOfKeys.Sort(compareFun);
root := TRangeTree1DNode<TKey>.Create(compare);
root.splitNode(0,ListOfKeys.Count-1,ListOfKeys);
FCount := ListOfKeys.Count;
end;
function TRangeTree1D<TKey>.insert(const key : TKey) : Boolean;
var HighestInbalancedNode, node : TRangeTree1DNode<TKey>;
(* after this operation the Tree should be balanced *)
begin
node := TRangeTree1DNode<TKey>.create(compare);
node.initNode(key,nil);
if NOT Assigned(self.root) then // First Node in the tree
self.root := node
else
begin
self.root.insert(node);
// node must be a leaf of the tree and any of the subtrees containing node might be inbalance.
// It will be enough just to balance one subtree, the one closest to the root
// in case the leaf is the root FCount must be one and no imbalance is possible
HighestInbalancedNode := nil;
while Assigned(node.Parent) do
begin // move up and check balance (avoid checking balance of a leaf)
node := node.parent;
if NOT node.isBalanced then HighestInbalancedNode := node;
end;
if Assigned(HighestInbalancedNode) then
HighestInbalancedNode.Balance(self.root);
end;
Inc(FCount);
end;
function TRangeTree1D<TKey>.find(const key : TKey) : TRangeTree1DNode<TKey>;
(* returns node containing key or nil if it is not there *)
begin
RESULT := Self.root.find(key);
end;
function TRangeTree1D<TKey>.delete(const key : TKey) : Boolean;
var node : TRangeTree1DNode<TKey>;
begin
node := extract(key);
if Assigned(node) then
begin
RESULT := TRUE;
node.Free;
end
else {key was not in the DS}
RESULT := FALSE
end;
function TRangeTree1D<TKey>.extract(const key : TKey) : TRangeTree1DNode<TKey>;
var ParentNode, promotedNode,
HighestInbalancedNode,
AffectedNode : TRangeTree1DNode<TKey>;
begin
RESULT := self.root.find(key);
if Assigned(RESULT) then {key is in the DS}
begin
// There will be two or one nodes with this key (one if we stract max of the tree)
// One is the leaf (that we want to extract) and the other a no-leaf node (i.e. AffectedNode)
// whose key will need revision
AffectedNode := nil;
while NOT RESULT.isLeaf do
begin
AffectedNode := RESULT;
RESULT := RESULT.left.find(key);
end;
// At this Point RESULT contains the leaf
if Assigned(RESULT.parent) then
begin
// promotedNode will replace ParentNode
ParentNode := RESULT.parent;
if RESULT.isLeftChild then promotedNode := ParentNode.right
else promotedNode := ParentNode.left;
// revise NewParentNode Conections
if Assigned(ParentNode.Parent) then
begin
promotedNode.parent := ParentNode.Parent;
if ParentNode.isLeftChild then
begin
promotedNode.parent.left := promotedNode;
promotedNode.isLeftChild := TRUE;
end
else // then ParentNode is a rightChild
begin
promotedNode.parent.right := promotedNode;
promotedNode.isLeftChild := FALSE;
end;
end
else
begin
promotedNode.parent := nil;
if ParentNode.isLeftChild then promotedNode.isLeftChild := TRUE
else promotedNode.isLeftChild := FALSE;
root := promotedNode;
end;
// revise Keys of AffectedNode To newKey -> might happen that AffectedNode = parentNode
if Assigned(AffectedNode) then
AffectedNode.key := promotedNode.getRightMostNodeOfSubtree.key;
ParentNode.Free;
promotedNode.UpdateSizesUpToTheRoot(HighestInbalancedNode);
if Assigned(HighestInbalancedNode) then
HighestInbalancedNode.Balance(root);
end
else // then the root is the leaf to extract
root := nil;
Dec(FCount);
end;
end;
function TRangeTree1D<TKey>.getBifurcationNode(const k1,k2 : TKey) : TRangeTree1DNode<TKey>;
{assumed k1<k2}
var node : TRangeTree1DNode<TKey>;
int1, int2 : Integer;
begin
// Find BifurcationNode
node := root;
RESULT := nil;
while Assigned(node) do
begin
int1 := node.compare(k1,node.key);
if int1 <> 1 then
begin
int2 := node.compare(k2,node.key);
if int2 = 1 then
begin RESULT := node; Exit; end
else
node := node.left;
end
else node := node.right;
end;
end;
function TRangeTree1D<TKey>.isAnyInRange(const key1, key2 : TKey) : Boolean;
var BifurcationNode : TRangeTree1DNode<TKey>;
k1, k2 : TKey;
begin
// Saveguard k1 >= k2
if root.compare(key1,key2) > 0 then
begin k1 := key2; k2 := key1; end
else
begin k1 := key1; k2 := key2; end;
BifurcationNode := getBifurcationNode(k1,k2);
RESULT := Assigned(BifurcationNode);
end;
function TRangeTree1D<TKey>.HowManyInRange(const key1, key2 : TKey) : Integer;
{ Finds |K| with K=(k_i) i=1,..,|K|. Number of keys of the tree satisfying
k1 < k < k2 : Note input is sorted to satisfy k1<k2 }
var node, BifurcationNode : TRangeTree1DNode<TKey>;
int1, int2 : Integer;
k1, k2 : TKey;
begin
// Saveguard k1 >= k2
if root.compare(key1,key2) > 0 then
begin k1 := key2; k2 := key1; end
else
begin k1 := key1; k2 := key2; end;
BifurcationNode := getBifurcationNode(k1,k2);
if Assigned(BifurcationNode) then
begin
if BifurcationNode.isleaf then RESULT := 1
else
begin
RESULT := 0;
// Track k1 to a leaf count nodes at right subtree when move left
node := bifurcationNode.left;
while NOT node.isLeaf do
begin
int1 := node.compare(k1,node.key);
if int1 = 1 then
node := node.right
else
begin
RESULT := RESULT + node.size_right;
node := node.left;
end
end;
// node at the leaf
int1 := node.compare(k1,node.key);
if int1 <> 1 then RESULT := RESULT + node.size;
// Track k2 to a leaf count nodes at left subtree when move left
node := bifurcationNode.right;
while NOT node.isLeaf do
begin
int2 := node.compare(k2,node.key);
if int2 = 1 then
begin
RESULT := RESULT + node.size_left;
node := node.right;
end
else
node := node.left
end;
// node at the leaf
int2 := node.compare(k2,node.key);
if int2 <> -1 then RESULT := RESULT + node.size;
end;
end
else RESULT := 0;
end;
procedure TRangeTree1D<TKey>.CollectSubTreeLeafsToDictionary(const node : TRangeTree1DNode<TKey>);
{assumed node is assigned because it is the child of a non-leaf}
begin
if node.isLeaf then OutputDictOfKeys.Add(node.key,TRUE)
else
begin
CollectSubTreeLeafsToDictionary(node.left);
CollectSubTreeLeafsToDictionary(node.right);
end;
end;
procedure TRangeTree1D<TKey>.CollectSortedKeysOfSubtree(const node : TRangeTree1DNode<TKey>);
begin
if node.isLeaf then OutputSortedListOfKeys.Add(node.key)
else
begin
CollectSortedKeysOfSubtree(node.left);
CollectSortedKeysOfSubtree(node.right);
end;
end;
procedure TRangeTree1D<TKey>.CollectSortedKeysGTk1(const node : TRangeTree1DNode<TKey>; const k1 : TKey);
var anInteger : Integer;
begin
anInteger := node.compare(k1,node.key);
if node.isLeaf then
begin
if anInteger<> 1 then OutputSortedListOfKeys.Add(node.key);
end
else
begin
if anInteger <> 1 then
begin
CollectSortedKeysGTk1(node.left,k1);
CollectSortedKeysOfSubtree(node.right);
end
else CollectSortedKeysGTk1(node.right,k1);
end;
end;
procedure TRangeTree1D<TKey>.CollectSortedKeysLTk2(const node : TRangeTree1DNode<TKey>; const k2 : TKey);
var anInteger : Integer;
begin
anInteger := node.compare(k2,node.key);
if node.isLeaf then
begin
if anInteger <> -1 then OutputSortedListOfKeys.Add(node.key);
end
else
begin
if anInteger <> 1 then
CollectSortedKeysLTk2(node.left,k2)
else
begin
CollectSortedKeysOfSubtree(node.left);
CollectSortedKeysLTk2(node.right,k2);
end
end;
end;
function TRangeTree1D<TKey>.getDictOfMembersInRange(const key1, key2 : TKey) : TDictionary<TKey,Boolean>;
{ outputs a dictionary with the set K=(k_i) i=1,..,|K|. keys of the tree satisfying
k1 < k < k2 : Note input is sorted to satisfy k1<k2 }
var node, BifurcationNode : TRangeTree1DNode<TKey>;
int1, int2 : Integer;
k1, k2 : TKey;
begin
// Saveguard k1 >= k2
if root.compare(key1,key2) > 0 then
begin k1 := key2; k2 := key1; end
else
begin k1 := key1; k2 := key2; end;
OutputDictOfKeys.Clear;
RESULT := OutputDictOfKeys;
BifurcationNode := getBifurcationNode(k1,k2);
if Assigned(BifurcationNode) then
begin
if BifurcationNode.isleaf then RESULT.Add(BifurcationNode.key,TRUE)
else
begin
// Track k1 to a leaf count nodes at right subtree when move left
node := bifurcationNode.left;
while NOT node.isLeaf do
begin
int1 := node.compare(k1,node.key);
if int1 = 1 then
node := node.right
else
begin
CollectSubTreeLeafsToDictionary(node.right);
node := node.left;
end
end;
// node at the leaf
int1 := node.compare(k1,node.key);
if int1 <> 1 then RESULT.Add(node.key,TRUE);
// Track k2 to a leaf count nodes at left subtree when move left
node := bifurcationNode.right;
while NOT node.isLeaf do
begin
int2 := node.compare(k2,node.key);
if int2 = 1 then
begin
CollectSubTreeLeafsToDictionary(node.left);
node := node.right;
end
else
node := node.left
end;
// node at the leaf
int2 := node.compare(k2,node.key);
if int2 <> -1 then RESULT.Add(node.key,TRUE);
end;
end
end;
function TRangeTree1D<TKey>.getSortedListOfMembersInRange(const key1, key2 : TKey) : TList<TKey>;
{ outputs the sorted list of keys satisfying k1 < k < k2 : Note input is sorted to satisfy k1<k2 }
var node, BifurcationNode : TRangeTree1DNode<TKey>;
int1, int2 : Integer;
k1, k2 : TKey;
begin
OutputSortedListOfKeys.Clear;
RESULT := OutputSortedListOfKeys;
if Assigned(root) then
begin
// Saveguard k1 >= k2
if root.compare(key1,key2) > 0 then
begin k1 := key2; k2 := key1; end
else
begin k1 := key1; k2 := key2; end;
BifurcationNode := getBifurcationNode(k1,k2);
if Assigned(BifurcationNode) then
begin
if BifurcationNode.isLeaf then
begin
CollectSortedKeysGTk1(BifurcationNode,k1);
CollectSortedKeysLTk2(BifurcationNode,k2);
end
else
begin
CollectSortedKeysGTk1(BifurcationNode.left,k1);
CollectSortedKeysLTk2(BifurcationNode.right,k2);
end;
end;
end;
end;
//End define netods of TRangeTree1D
// HOW TO USE EXAMPLES -> using TKey = TEdge2D a record representing an edge in 2D.
// the queries will regard edges with length in a given 1D interval
type TSPt2D = record
x, y : Single;
end;
type TEdge2D = record
FirstPoint : TSPt2D;
SecondPoint : TSPt2D;
Length : Single;
EdgeNo : Integer;
end;
function getRandomListOfEdges(const NEdges : Integer) : TList<TEdge2D>;
{ generate edges with EndPoints randomly distributed in [0,1]x[0,1] }
var edge : TEdge2D;
i : Integer;
begin
RESULT := TList<TEdge2D>.create;
with edge do
begin
for i := 0 to NEdges-1 do
begin
FirstPoint.x := random;
FirstPoint.y := random;
SecondPoint.x := random;
SecondPoint.y := random;
Length := sqrt( sqr(SecondPoint.x - FirstPoint.x) +
sqr(SecondPoint.y - FirstPoint.y) );
EdgeNo := i;
RESULT.Add(edge);
end;
end;
end;
procedure BuildRangeTreeDynamicAndQuery;
var ListOfEdges2D, L : TList<TEdge2D>;
RT1D : TRangeTree1D<TEdge2D>;
i : Integer;
edge, k1, k2 : TEdge2D;
compareByLength : TComparison<TEdge2D>;
begin
// get random List with with 1000 edges, with ends in [0,1]x[0,1]
ListOfEdges2D := getRandomListOfEdges(1000);
// Define Comparison function on edges length s.t. no equality is possible between members on šListOfEdges2D
compareByLength := function(const left, right: TEdge2D) : Integer
begin
RESULT := TComparer<Single>.Default.Compare(left.length,right.length);
if RESULT = 0 then
RESULT := TComparer<Integer>.Default.Compare(left.EdgeNo,right.EdgeNo);
end;
// create 1DRangeTree DS and build it with the ListOfEdges dynamically
RT1D := TRangeTree1D<TEdge2D>.create(compareByLength);
for i := 0 to ListOfEdges2D.Count-1 do
begin
edge := ListOfEdges2D[i];
RT1D.insert(edge);
end;
// look for edges with length in the range [0.5, sqrt(2)]
k1.Length := 0.5; k1.EdgeNo := -1;
k2.Length := sqrt(2); k2.EdgeNo := High(Integer); // for closed range
L := RT1D.getSortedListOfMembersInRange(k1,k2);
// Eliminate Those edges from RT1D
for i := 0 to L.Count-1 do
begin
edge := L[i];
RT1D.delete(edge);
end;
// do a new query for edges with length in the interval (0.0, 0.5) // that should be all remaining
k1.Length := 0.0; k1.EdgeNo := High(Integer);
k2.Length := sqrt(2); k2.EdgeNo := -1; // for open range
L := RT1D.getSortedListOfMembersInRange(k1,k2); // note L is just a pointer to a private field of RT1D
// dont do L.Free as it will be done in RT1D.free;
// inspect extracted edges
for i := 0 to L.Count-1 do
begin
edge := L[i];
RT1D.delete(edge);
end;
// Free Memory
RT1D.Free;
ListOfEdges2D.Free; // in case Tkey is a class that requires freeing )(ot a record as now),
// then the members of the List must be freed before freeing the container
end;
procedure BuildRangeTreeStaticAndQuery;
var RT1D : TRangeTree1D<TEdge2D>;
ListOfEdges2D : TLIst<TEdge2D>;
compareByLength : TComparison<TEdge2D>;
k1, k2, edge : TEdge2D;
D : TDictionary<TEdge2D,Boolean>;
B : Boolean;
n1, i : Integer;
ListOfIsActive : TList<Boolean>;
begin
// generate List of 1000 Random Edges in [0,1]x[0,1] -> Container for TKeys = TEdge2D
ListOfEdges2D := getRandomListOfEdges(1000);
// Define Comparison function on edges length s.t. no equality is possible between members on šListOfEdges2D
compareByLength := function(const left, right: TEdge2D) : Integer
begin
RESULT := TComparer<Single>.Default.Compare(left.length,right.length);
if RESULT = 0 then
RESULT := TComparer<Integer>.Default.Compare(left.EdgeNo,right.EdgeNo);
end;
// create 1DRangeTree DS and build it with the ListOfEdges statically
RT1D := TRangeTree1D<TEdge2D>.create(compareByLength);
RT1D.Build(ListOfEdges2D);
// is Any Member in the range of Lengths [1,sqrt(2)]
k1.Length := 1; k1.EdgeNo := -1;
k2.Length := sqrt(2); k2.EdgeNo := High(Integer); // for closed range
B := RT1D.isAnyInRange(k1,k2);
// How many do we have in [k1,k2]
n1 := RT1D.HowManyInRange(k1,k2);
// get Dictionary with edges with length between 0.45 and 0.55
k1.Length := 0.45; k1.EdgeNo := -1;
k2.Length := 0.55; k2.EdgeNo := High(Integer); // for closed range
D := RT1D.getDictOfMembersInRange(k1,k2); // note D is just a pointer to a private field of RT1D
// dont do D.Free as it will be done in RT1D.free;
// make a lIstofIsActive Associated to ListOfEdges2D
ListOfIsActive := TList<Boolean>.create;
for i := 0 to ListOfEdges2D.Count-1 do
begin
edge := ListOfEdges2D[i];
if D.ContainsKey(edge) then ListOfIsActive.Add(TRUE)
else ListOfIsActive.Add(FALSE);
end;
// Free Memory
RT1D.Free;
ListOfIsActive.Free;
ListOfEdges2D.free // records dont have to be freed, when using as TKey a class you
// should free the key before freeing the container
end;
end.
|
{
* UURIEncode.pas
*
* Routines that can encode and decode URIs according to RFC 3986.
*
* $Rev$
* $Date$
*
* ***** BEGIN LICENSE BLOCK *****
*
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* 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 UURIEncode.pas.
*
* The Initial Developer of the Original Code is Peter Johnson
* (http://www.delphidabbler.com/).
*
* Portions created by the Initial Developer are Copyright (C) 2010 Peter
* Johnson. All Rights Reserved.
*
* Contributor(s)
* NONE
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK *****
}
unit UURIEncode;
{$WARN EXPLICIT_STRING_CAST OFF}
interface
const
// Chars reserved for URIs: see RFC 3986 section 2.2
// generic: reserved by generic URI syntax
cURIGenReservedChars = [
':', '/', '?', '#', '[', ']', '@'
];
// may be reserved by different URI schemes
cURISubReservedChars = [
'!', '$', '&', '''', '(', ')', '*', '+', ',', ';', '='
];
// % character treated as reserved because it is used in percent encoding and
// must therefore be percent encoded if to be used literally in URI:
// see RFC 3986 section 2.4
cPercent = '%';
// all the reserved chars: union of above
cURIReservedChars =
cURIGenReservedChars + cURISubReservedChars + [cPercent];
// Unreserved URI chars: see RFC 3986 section 2.3
cURLUnreservedChars = [
'A'..'Z', 'a'..'z', '0'..'9', '-', '_', '.', '~'
];
// Special reserved char used to encode spaces in query string encoding
cPlus = '+';
function URIEncode(const S: UTF8String): string; overload;
{URI encodes a string.
@param S [in] String of UTF-8 characters to be encoded.
@return Encoded string. Contains only ASCII unreserved characters and "%".
}
function URIEncode(const S: UnicodeString): string; overload;
{URI encodes a string.
@param S [in] String of Unicode characters to be encoded.
@return Encoded string. Contains only ASCII unreserved characters and "%".
}
function URIEncode(const S: AnsiString): string; overload;
{URI encodes a string.
@param S [in] String of Unicode characters to be encoded.
@return Encoded string. Contains only ASCII unreserved characters and "%".
}
function URIEncodeQueryString(const S: UTF8String): string; overload;
{URI encodes a query string component. Spaces in original string are encoded
as "+".
@param S [in] String of UTF-8 characters to be encoded.
@return Encoded string. Contains only ASCII unreserved characters and "%".
}
function URIEncodeQueryString(const S: UnicodeString): string; overload;
{URI encodes a query string component. Spaces in original string are encoded
as "+".
@param S [in] String of Unicode characters to be encoded.
@return Encoded string. Contains only ASCII unreserved characters and "%".
}
function URIEncodeQueryString(const S: AnsiString): string; overload;
{URI encodes a query string component. Spaces in original string are encoded
as "+".
@param S [in] String of ANSI characters to be encoded.
@return Encoded string. Contains only ASCII unreserved characters and "%".
}
function URIDecode(const Str: string): string;
{Decodes a URI encoded string.
@param Str [in] String to be decoded. *May* but should not contain
characters outside the unreserved character set per RFC 3986.
@return Decoded string.
@except EConvertError raised if Str contains malformed % escape sequences.
}
function URIDecodeQueryString(const Str: string): string;
{Decodes a URI encoded query string where spaces have been encoded as '+'.
@param Str [in] String to be decoded. *May* but should not contain
characters outside the unreserved character set per RFC 3986.
@return Decoded string.
@except EConvertError raised if Str contains malformed % escape sequences.
}
implementation
uses
// Delphi
SysUtils, StrUtils;
resourcestring
// Error messages
rsEscapeError = 'String to be decoded contains invalid % escape sequence';
const
// Percent encoding of space character
cPercentEncodedSpace = '%20';
{
Internally, URIDecode operates on UTF-8 strings for both input and output.
This lets us deal easily with any multi-byte characters in the input. There
SHOULDN'T be any such characters since all characters in a percent encoded URI
should map onto the unreserved characters from the ASCII character set.
However we need to allow for badly encoded URIs that *may* contain characters
outside this expected set.
UTF-8 also lets perform an easy test for '%' characters in input. Since '%'
can never occur and a UTF-8 continuation character we can simply test for the
actual character without worrying about if it is part of of a multibyte
character.
We use UTF-8 for the output string since UTF-8 should have been used to encode
the URI in the first place, therefore percent-encoded octets may map onto
UTF-8 continuation bytes. Using any other string type would give erroneous
results.
We convert interim UTF-8 result into the native string type before returning.
}
function URIDecode(const Str: string): string;
{Decodes a URI encoded string.
@param Str [in] String to be decoded. *May* but should not contain
characters outside the unreserved character set per RFC 3986.
@return Decoded string.
@except EConvertError raised if Str contains malformed % escape sequences.
}
// ---------------------------------------------------------------------------
function CountPercent(const S: UTF8String): Integer;
{Counts number of '%' characters in a UTF8 string.
@param S [in] String for which '%' characters to be counted.
@return Number of '%' characters in S.
}
var
Idx: Integer; // loops thru all octets of S
begin
Result := 0;
for Idx := 1 to Length(S) do
if S[Idx] = cPercent then
Inc(Result);
end;
// ---------------------------------------------------------------------------
var
SrcUTF8: UTF8String; // input string as UTF-8
SrcIdx: Integer; // index into source UTF-8 string
ResUTF8: UTF8String; // output string as UTF-8
ResIdx: Integer; // index into result UTF-8 string
Hex: string; // hex component of % encoding
ChValue: Integer; // character ordinal value from a % encoding
begin
// Convert input string to UTF-8
SrcUTF8 := UTF8Encode(Str);
// Size the decoded UTF-8 string: each 3 byte sequence starting with '%' is
// replaced by a single byte. All other bytes are copied unchanged.
SetLength(ResUTF8, Length(SrcUTF8) - 2 * CountPercent(SrcUTF8));
SrcIdx := 1;
ResIdx := 1;
while SrcIdx <= Length(SrcUTF8) do
begin
if SrcUTF8[SrcIdx] = cPercent then
begin
// % encoding: decode following two hex chars into required code point
if Length(SrcUTF8) < SrcIdx + 2 then
raise EConvertError.Create(rsEscapeError); // malformed: too short
Hex := '$' + string(SrcUTF8[SrcIdx + 1] + SrcUTF8[SrcIdx + 2]);
if not TryStrToInt(Hex, ChValue) then
raise EConvertError.Create(rsEscapeError); // malformed: not valid hex
ResUTF8[ResIdx] := AnsiChar(ChValue);
Inc(ResIdx);
Inc(SrcIdx, 3);
end
else
begin
// plain char or UTF-8 continuation character: copy unchanged
ResUTF8[ResIdx] := SrcUTF8[SrcIdx];
Inc(ResIdx);
Inc(SrcIdx);
end;
end;
// Convert back to native string type for result
Result := UTF8ToString(ResUTF8);
end;
function URIDecodeQueryString(const Str: string): string;
{Decodes a URI encoded query string where spaces have been encoded as '+'.
@param Str [in] String to be decoded. *May* but should not contain
characters outside the unreserved character set per RFC 3986.
@return Decoded string.
@except EConvertError raised if Str contains malformed % escape sequences.
}
begin
// First replace plus signs with spaces. We use percent-encoded spaces here
// because string is still URI encoded and space is not one of unreserved
// chars and therefor should be percent-encoded. Finally we decode the
// percent-encoded string.
Result := URIDecode(ReplaceStr(Str, cPlus, cPercentEncodedSpace));
end;
{
Extract from RFC 3986 section 2.5:
"the data should first be encoded as octets according to the UTF-8 character
encoding [STD63]; then only those octets that do not correspond to
characters in the unreserved set should be percent-encoded.
These means we can simply scan a UTF-8 string and encode anything we find that
isn't in the unreserved set. We need't worry about any continuation bytes in
the UTF-8 encoding because all continuation bytes are greater than $80, and
all unreserved characters are from a sub-set of ASCII and therefore have an
ordinal value of less than $80. So we needn't worry about detecting lead and
continuation bytes.
For details of the UTF-8 encoding see http://en.wikipedia.org/wiki/UTF-8
NOTE:
URIEncode should be applied to the component parts of the URI before they
are combined, not to the whole URI. See RFC 3986 section 2.4
}
function URIEncode(const S: UTF8String): string; overload;
{URI encodes a string.
@param S [in] String of UTF-8 characters to be encoded.
@return Encoded string. Contains only ASCII unreserved characters and "%".
}
var
Ch: AnsiChar; // each character in S
begin
// Just scan the string an octet at a time looking for chars to encode
Result := '';
for Ch in S do
if CharInSet(Ch, cURLUnreservedChars) then
Result := Result + WideChar(Ch)
else
Result := Result + '%' + IntToHex(Ord(Ch), 2);
end;
function URIEncode(const S: UnicodeString): string; overload;
{URI encodes a string.
@param S [in] String of Unicode characters to be encoded.
@return Encoded string. Contains only ASCII unreserved characters and "%".
}
begin
Result := URIEncode(UTF8Encode(S));
end;
function URIEncode(const S: AnsiString): string; overload;
{URI encodes a string.
@param S [in] String of ANSI characters to be encoded.
@return Encoded string. Contains only ASCII unreserved characters and "%".
}
begin
Result := URIEncode(UTF8Encode(S));
end;
function URIEncodeQueryString(const S: UTF8String): string; overload;
{URI encodes a query string component. Spaces in original string are encoded
as "+".
@param S [in] String of UTF-8 characters to be encoded.
@return Encoded string. Contains only ASCII unreserved characters and "%".
}
begin
// First we URI encode the string. This so any existing '+' symbols get
// encoded because we use them to replace spaces and we can't confuse '+'
// already in URI with those that we add. After this step spaces get encoded
// as %20. So next we replace all occurences of %20 with '+'.
Result := ReplaceStr(URIEncode(S), cPercentEncodedSpace, cPlus);
end;
function URIEncodeQueryString(const S: UnicodeString): string; overload;
{URI encodes a query string component. Spaces in original string are encoded
as "+".
@param S [in] String of Unicode characters to be encoded.
@return Encoded string. Contains only ASCII unreserved characters and "%".
}
begin
Result := URIEncodeQueryString(UTF8Encode(S));
end;
function URIEncodeQueryString(const S: AnsiString): string; overload;
{URI encodes a query string component. Spaces in original string are encoded
as "+".
@param S [in] String of ANSI characters to be encoded.
@return Encoded string. Contains only ASCII unreserved characters and "%".
}
begin
Result := URIEncodeQueryString(UTF8Encode(S));
end;
end.
|
{
Яновский Андрей Петрович 2003 г. (c)
Родительский класс для объектов работы с данными.
}
unit Dbun;
interface
uses
Windows, SysUtils, Classes, IBDatabase, IBQuery;
type EDbunError = class(Exception);
type TDbunObject = class(TComponent)
private
protected
FConnection: TIBDatabase;
FInputTransaction: TIBTransaction;
FDataQuery: TIBQuery;
FUsedExternalTransaction: Boolean;
procedure InitInputTransaction;
procedure SetInputTransaction(Value: TIBTransaction);
procedure StartInputTransaction;
procedure CommitInputTransaction;
procedure RollBackInputTransaction;
public
property Connection: TIBDatabase read FConnection;
property InputTransaction: TIBTransaction read FInputTransaction write SetInputTransaction;
function Insert: Boolean; virtual; abstract;
function Update: Boolean; virtual; abstract;
function Delete: Boolean; virtual; abstract;
function FillDataBy(KeyValue: Variant): Boolean; virtual; abstract;
constructor Create(AOwner: TComponent; AConnection: TIBDatabase; Query: TIBQuery = nil) overload; virtual;
destructor Destroy; override;
end;
implementation
{ TDbunObject }
constructor TDbunObject.Create(AOwner: TComponent;
AConnection: TIBDatabase; Query: TIBQuery = nil);
begin
inherited Create(AOwner);
if not Assigned(AConnection) then
begin
raise EDbunError.Create('Не створено з`єднання!');
Exit;
end;
FConnection := AConnection;
FUsedExternalTransaction := false;
FDataQuery := nil;
if Assigned(Query) then FDataQuery := Query;
InitInputTransaction;
end;
destructor TDbunObject.Destroy;
begin
if (not FUsedExternalTransaction) and Assigned(FInputTransaction) then
FInputTransaction.Free;
inherited;
end;
procedure TDbunObject.InitInputTransaction;
begin
if FUsedExternalTransaction then FInputTransaction := nil;
if not Assigned(FInputTransaction) then
begin
FInputTransaction := TIBTransaction.Create(Self);
FInputTransaction.DefaultDatabase := FConnection;
FInputTransaction.Params.Add('read_committed');
FInputTransaction.Params.Add('rec_version');
FInputTransaction.Params.Add('nowait');
end;
FUsedExternalTransaction := false;
end;
procedure TDbunObject.SetInputTransaction(Value: TIBTransaction);
begin
if FInputTransaction <> Value then
if Assigned(FInputTransaction) then
begin
if FInputTransaction.Active then
begin
raise EDbunError.Create('Помилка!');
Exit;
end;
if not FUsedExternalTransaction then FInputTransaction.Free;
FInputTransaction := Value;
FUsedExternalTransaction := true
end else begin
FInputTransaction := Value;
FUsedExternalTransaction := true
end;
end;
procedure TDbunObject.StartInputTransaction;
begin
if not FUsedExternalTransaction then FInputTransaction.StartTransaction;
end;
procedure TDbunObject.CommitInputTransaction;
begin
if not FUsedExternalTransaction then FInputTransaction.Commit;
end;
procedure TDbunObject.RollBackInputTransaction;
begin
if not FUsedExternalTransaction then FInputTransaction.Rollback;
end;
end.
|
unit USelectCode;
interface
uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, ExtCtrls;
type
TDialogType = (cBOOK, cVISITOR, cBORROW);
TfrmSelectCode = class(TForm)
editCode: TEdit;
labelCode: TLabel;
btnComplete: TButton;
procedure editCodeKeyPress(Sender: TObject; var Key: Char);
procedure btnCompleteClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
dialogType: TDialogType;
result: Integer;
end;
var
frmSelectCode: TfrmSelectCode;
implementation
uses
UBookList, UVisitorList, UBorrowList, UMain,
UAddBook, UAddVisitor, UAddBorrow;
{$R *.dfm}
// Запрещает ввод не-цифр в поле ввода кода
procedure TfrmSelectCode.editCodeKeyPress(Sender: TObject; var Key: Char);
begin
case key of
'0'..'9', #8: ;
else
key := #0;
end;
end;
// Проверяет введённый код и возвращает в вызывающий диалог код
procedure TfrmSelectCode.btnCompleteClick(Sender: TObject);
begin
if editCode.Text <> '' then
begin
case dialogType of
cBOOK:
begin
if not bookExist(StrToInt(editCode.Text)) then
begin
MessageBox(Handle, PChar(sINCORRECT_BOOK_CODE), PChar(sERROR), MB_OK or MB_ICONWARNING);
end
else
begin
frmAddBook.code := StrToInt(editCode.Text);
frmAddBook.showBook(frmAddBook.code);
Visible := false;
frmAddBook.Visible := true;
end;
end;
cVISITOR:
begin
if not visitorExist(StrToInt(editCode.Text)) then
begin
MessageBox(Handle, PChar(sINCORRECT_VISITOR_ID), PChar(sERROR), MB_OK or MB_ICONWARNING);
end
else
begin
frmAddVisitor.code := StrToInt(editCode.Text);
frmAddVisitor.showVisitor(frmAddVisitor.code);
Visible := false;
frmAddVisitor.Visible := true;
end;
end;
cBORROW:
begin
if not borrowExist(StrToInt(editCode.Text)) then
begin
MessageBox(Handle, PChar(sINCORRECT_BORROW_CODE), PChar(sERROR), MB_OK or MB_ICONWARNING);
end
else
begin
frmAddBorrow.code := StrToInt(editCode.Text);
frmAddBorrow.showBorrow(frmAddBorrow.code);
Visible := false;
frmAddBorrow.Visible := true;
end;
end;
end;
end
else
MessageBox(Handle, PChar(sFIELD_MUST_BE_FILLED), PChar(sERROR), MB_OK or MB_ICONWARNING);
end;
// Заполняет начальные значения метки и кнопки
procedure TfrmSelectCode.FormShow(Sender: TObject);
begin
labelCode.Caption := sENTER_CODE;
Caption := sENTER_CODE;
btnComplete.Caption := sSELECT;
end;
end.
|
unit DataSet.ViewModel;
interface
uses
System.SysUtils,
System.Classes,
Data.DB,
Spring,
Spring.Collections,
DataSet.Interfaces,
DataSet.Model,
DataSet.Types,
MVVM.Types,
MVVM.Attributes,
MVVM.Interfaces,
MVVM.Interfaces.Architectural,
MVVM.Bindings;
type
{$RTTI EXPLICIT METHODS([vcPublic, vcProtected])}
[ViewModel_Implements(IDataSet_ViewModel)]
TDataSet_ViewModel = class(TViewModel, IDataSet_ViewModel)
private
FModel: TDataSet_Model;
FTableName: string;
FTableIndex: string;
FNewRowView: string;
FUpdateRowView: string;
protected
function GetProcMakeGetRows: TExecuteMethod;
function GetProcDeleteActiveRow: TExecuteMethod;
function GetProcMakeAppend: TExecuteMethod;
function GetProcMakeUpdate: TExecuteMethod;
function GetModel: TDataSet_Model;
function GetDataSet: TDataSet;
function GetTableName: String;
procedure SetTableName(const ATableName: string);
function GetTableIndex: string;
procedure SetTableIndex(const ATableIndex: string);
function GetNewRowView: string;
procedure SetNewRowView(const AViewName: string);
function GetUpdateRowView: string;
procedure SetUpdateRowView(const AViewName: string);
function GetIsOpen: TCanExecuteMethod;
function GetIsClosed: TCanExecuteMethod;
procedure MakeGetRows;
procedure DeleteActiveRow;
procedure MakeAppend;
procedure MakeUpdate;
public
function IsDataSetOpen: Boolean;
function IsDataSetClosed: Boolean;
procedure SetupViewModel; override;
procedure SetModel(AModel: TDataSet_Model);
[ActionMember(CLOSE_DATASET, OnExecute, '')]
procedure CloseDataSet;
[ActionMember(OPEN_DATASET, OnExecute, '')]
procedure OpenDataSet;
function GetRows(const AFields: TFieldsToGet): TFieldConverters;
procedure AppendRow(const AFields: TFieldConverters);
procedure UpdateActiveRow(const AFields: TFieldConverters);
property NewRowView: string read GetNewRowView write SetNewRowView;
property UpdateRowView: string read GetUpdateRowView write SetUpdateRowView;
property TableName: string read GetTableName write SetTableName;
property TableIndex: string read GetTableIndex write SetTableIndex;
property DataSet: TDataSet read GetDataSet;
property Model: TDataSet_Model read GetModel;
[ActionMember(DATASET_IS_OPEN, OnUpdate, '')]
property IsOpen: TCanExecuteMethod read GetIsOpen;
[ActionMember(DATASET_IS_CLOSED, OnUpdate, '')]
property IsClosed: TCanExecuteMethod read GetIsClosed;
[ActionMember(GET_ROWS, OnExecute, '')]
property DoMakeGetRows: TExecuteMethod read GetProcMakeGetRows;
[ActionMember(DELETE_ROW, OnExecute, '')]
property DoDeleteActiveRow: TExecuteMethod read GetProcDeleteActiveRow;
[ActionMember(APPEND_ROW, OnExecute, '')]
property DoMakeAppend: TExecuteMethod read GetProcMakeAppend;
[ActionMember(UPDATE_ROW, OnExecute, '')]
property DoMakeUpdate: TExecuteMethod read GetProcMakeUpdate;
end;
implementation
uses
System.Rtti,
System.Threading,
System.Diagnostics,
System.UITypes,
MVVM.Utils,
MVVM.Core;
{ TDataSetFile_ViewModel }
procedure TDataSet_ViewModel.OpenDataSet;
begin
if not FModel.IsOpen then
FModel.Open;
end;
procedure TDataSet_ViewModel.AppendRow(const AFields: TFieldConverters);
begin
FModel.AppendRow(AFields);
end;
procedure TDataSet_ViewModel.CloseDataSet;
begin
if FModel.IsOpen then
FModel.Close
end;
procedure TDataSet_ViewModel.DeleteActiveRow;
begin
if not FModel.IsOpen then
begin
MVVMCore.PlatformServices.MessageDlg('Warning (delete)', 'The dataset is closed');
Exit;
end;
FModel.DataSet.Delete;
end;
function TDataSet_ViewModel.GetDataSet: TDataSet;
begin
Result := FModel.DataSet;
end;
function TDataSet_ViewModel.GetIsClosed: TCanExecuteMethod;
begin
Result := IsDataSetClosed;
end;
function TDataSet_ViewModel.GetIsOpen: TCanExecuteMethod;
begin
Result := IsDataSetOpen;
end;
function TDataSet_ViewModel.GetModel: TDataSet_Model;
begin
Result := FModel
end;
function TDataSet_ViewModel.GetNewRowView: string;
begin
Result := FNewRowView
end;
function TDataSet_ViewModel.GetProcDeleteActiveRow: TExecuteMethod;
begin
Result := DeleteActiveRow;
end;
function TDataSet_ViewModel.GetProcMakeAppend: TExecuteMethod;
begin
Result := MakeAppend
end;
function TDataSet_ViewModel.GetProcMakeGetRows: TExecuteMethod;
begin
Result := MakeGetRows;
end;
function TDataSet_ViewModel.GetProcMakeUpdate: TExecuteMethod;
begin
Result := MakeUpdate
end;
function TDataSet_ViewModel.GetRows(const AFields: TFieldsToGet): TFieldConverters;
begin
Result := FModel.GetRows(AFields);
end;
function TDataSet_ViewModel.GetTableIndex: string;
begin
Result := FTableIndex
end;
function TDataSet_ViewModel.GetTableName: String;
begin
Result := FTableName;
end;
function TDataSet_ViewModel.GetUpdateRowView: string;
begin
Result := FUpdateRowView
end;
function TDataSet_ViewModel.IsDataSetClosed: Boolean;
begin
Result := not IsDataSetOpen
end;
function TDataSet_ViewModel.IsDataSetOpen: Boolean;
begin
Result := FModel.IsOpen
end;
procedure TDataSet_ViewModel.MakeAppend;
var
LView: IView<IDataSet_ViewModel>;
begin
OpenDataSet;
LView := Utils.ShowModalView<IDataSet_ViewModel>(Self, FNewRowView,
procedure(AResult: TModalResult)
begin;
end, MVVMCore.DefaultViewPlatform);
end;
procedure TDataSet_ViewModel.MakeGetRows;
begin
if not FModel.IsOpen then
FModel.Open
else
FModel.DataSet.Refresh;
end;
procedure TDataSet_ViewModel.MakeUpdate;
var
LView: IView<IDataSet_ViewModel>;
begin
if not FModel.IsOpen then
begin
MVVMCore.PlatformServices.MessageDlg('Warning (update)', 'The dataset is not opened');
Exit;
end;
LView := Utils.ShowModalView<IDataSet_ViewModel>(Self, FUpdateRowView,
procedure(AResult: TModalResult)
begin;
end, MVVMCore.DefaultViewPlatform);
end;
procedure TDataSet_ViewModel.SetModel(AModel: TDataSet_Model);
begin
if FModel <> AModel then
begin
FModel := AModel;
SetupViewModel;
end;
end;
procedure TDataSet_ViewModel.SetNewRowView(const AViewName: string);
begin
FNewRowView := AViewName
end;
procedure TDataSet_ViewModel.SetTableIndex(const ATableIndex: string);
begin
if FTableIndex <> ATableIndex then
begin
FTableIndex := ATableIndex;
FModel.TableIndex := FTableIndex;
end;
end;
procedure TDataSet_ViewModel.SetTableName(const ATableName: string);
begin
if FTableName <> ATableName then
begin
FTableName := ATableName;
FModel.TableName := FTableName;
end;
end;
procedure TDataSet_ViewModel.SetUpdateRowView(const AViewName: string);
begin
FUpdateRowView := AViewName
end;
procedure TDataSet_ViewModel.SetupViewModel;
begin
if not FTableName.IsEmpty then
begin
FModel.TableName := FTableName;
FModel.TableIndex := FTableIndex;
FModel.Open;
end;
end;
procedure TDataSet_ViewModel.UpdateActiveRow(const AFields: TFieldConverters);
begin
FModel.UpdateActiveRow(AFields);
end;
initialization
TDataSet_ViewModel.ClassName; // as there should be no implicit create, we must do this so the rtti info of the class is included in the final exe
end.
|
unit LinkReader;
interface
uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, ExtCtrls, Registry, ShDocVw, MSHTML, CommonWB;
type
TLinkReaderDlg = class(TForm)
OKBtn: TButton;
CancelBtn: TButton;
Bevel1: TBevel;
Label1: TLabel;
Label2: TLabel;
FieldName: TComboBox;
FieldURL: TEdit;
Label3: TLabel;
FieldMax: TEdit;
procedure FieldNameSelect(Sender: TObject);
procedure FieldNameDropDown(Sender: TObject);
procedure FieldMaxChange(Sender: TObject);
private
{ Private declarations }
procedure AddOpened;
public
{ Public declarations }
end;
var
LinkReaderDlg: TLinkReaderDlg;
implementation
{$R *.dfm}
procedure TLinkReaderDlg.AddOpened;
var
ShellWindow: IShellWindows;
WB: IWebbrowser2;
spDisp: IDispatch;
k: Integer;
begin
ShellWindow := CoShellWindows.Create;
for k := 0 to ShellWindow.Count do
begin
spDisp := ShellWindow.Item(k);
if spDisp = nil then Continue;
spDisp.QueryInterface(iWebBrowser2, WB);
if (WB <> nil)and(Pos('HTTP://',UpperCase(GetURL(WB)))=1) then
FieldName.Items.AddObject(GetURL(WB),TObject(NewStr(GetURL(WB))^))
end;
end;
procedure TLinkReaderDlg.FieldNameSelect(Sender: TObject);
begin
with FieldName do
if ItemIndex>-1 then
begin
if ItemIndex>-1 then
FieldURL.Text:=String(Items.Objects[ItemIndex])
else FieldURL.Text:='http://';
end;
end;
procedure TLinkReaderDlg.FieldNameDropDown(Sender: TObject);
begin
with FieldName do
begin
Items.BeginUpdate;
Items.Clear;
AddOpened;
Items.EndUpdate
end;
end;
procedure TLinkReaderDlg.FieldMaxChange(Sender: TObject);
var p,l,i:integer;s:string;
begin
if not FieldMax.Modified then Exit;
p:=FieldMax.SelStart;
l:=FieldMax.SelLength;
s:=FieldMax.Text;
i:=1;
while i<=length(s) do
if not((s[i]>='0')and(s[i]<='9')) then Delete(S,i,1)
else inc(i);
FieldMax.Text:=s;
FieldMax.SelStart:=p;
FieldMax.SelLength:=l
end;
end.
|
unit uFilterOrderItems;
{*******************************************************************************
* *
* Название модуля : *
* *
* uFilterOrderItems *
* *
* Назначение модуля : *
* *
* Диалог параметров фильтрации для выбора пункта(ов) приказа(ов). *
* *
* Copyright © Дата создания: 04.05.07, Автор: Найдёнов Е.А *
* *
*******************************************************************************}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, uNeClasses, uNeTypes, StdCtrls, Buttons, ExtCtrls,
uDateControl, uFControl, uLabeledFControl, uSpravControl, uCharControl,
uIntControl;
type
{ *** Назначение: реализация ё диалога параметров фильтрации для выбора пункта(ов) приказа(ов) *** }
TfmFilterOrderItems = class(TForm)
pnlForButtons: TPanel;
btnOK: TBitBtn;
btnCancel: TBitBtn;
grbMainParams: TGroupBox;
edtPCard: TqFSpravControl;
edtMainPeriodBeg: TqFDateControl;
edtMainPeriodEnd: TqFDateControl;
grbOKParams: TGroupBox;
grbRegisterParams: TGroupBox;
lblMainPeriod: TLabel;
edt1: TqFIntControl;
Label1: TLabel;
qFDateControl1: TqFDateControl;
qFDateControl2: TqFDateControl;
private
{ Private declarations }
public
{ Public declarations }
end;
{ *** Назначение: реализация абстрактных методов для универсальной работы с параметрами *** }
TFilterPrtPlanFact = class(TNeSprav)
private
{ Private declarations }
public
procedure Show; override;
end;
function CreateSprav: TNeSprav;
exports
CreateSprav;
implementation
resourcestring
//Имена входящих параметров модуля
//Имена исходящих параметров модуля
sPN_OUT_Id_Order_Item = 'Id_Order_Item';
type
//Запись для хранения значений входящих параметров
TRec_InParams = record
FMode : Integer;
FDBHandle : Integer;
end;
const
//Массив атрибутов входящих параметров модуля
cInFieldDefs: array[0..0] of TRec_FieldDefs = (
( FName: sPN_IN_Mode; FType: ftInteger ) );
//Массив атрибутов исходящих параметров модуля
cOutFieldDefs: array[0..0] of TRec_FieldDefs = (
( FName: sPN_OUT_Id_Order_Item; FType: ftVariant ) );
{$R *.dfm}
function CreateSprav: TNeSprav;
var
vParams : TRec_Params;
begin
try
vParams.FInParams := @cInFieldDefs;
vParams.FOutParams := @cOutFieldDefs;
Result := TFilterPrtPlanFact.Create( tpInputOutput, vParams );
except
on E: Exception
do begin
MessageBox( 0, PChar( sErrorTextExtUA + E.Message ), PChar( sMsgCaptionErrUA ), MB_OK or MB_ICONERROR );
end;
end;
end;
{ TFilterPrtPlanFact }
procedure TFilterPrtPlanFact.Show;
var
ModRes : TModalResult;
InParams : TRec_InParams;
fmFltrParams : TfmFilterOrderItems;
begin
try
inherited;
//Запоминаем значения входящих параметров
try
//Создаем экземпляр специального класса
fmFltrParams := TfmFilterOrderItems.Create( Application.MainForm );
//Отображаем фильтрационную форму
ModRes := fmFltrParams.ShowModal;
if ModRes = mrOK
then begin
end;
finally
if fmFltrParams <> nil then FreeAndNil( fmFltrParams );
end;
except
on E: Exception
do begin
MessageBox( 0, PChar( sErrorTextExtUA + E.Message ), PChar( sMsgCaptionErrUA ), MB_OK or MB_ICONERROR );
end;
end;
end;
end.
|
unit Game;
interface
uses Physics, Geometry, BattleField, Types;
type
Side = (FortLeft, FortRight);
Player = record
king: IntVector;
cannon: IntVector;
name: ansistring;
max_force: double;
angle, force: double;
color: shortint;
equipment: Equip;
current_weapon: integer;
won: boolean;
end;
pPlayer = ^Player;
GameController = record
pc: pPhysicsController;
player: array[1..2] of Player;
current_player: integer;
max_wind: double;
{ The starting max_force for both players }
max_force: double;
{ Tells whether the wind force is increasing or decreasing }
wind_dir: integer;
{ Flags for the main program }
end;
pGameController = ^GameController;
procedure new_player(var p: Player; name: ansistring; color: shortint; equipment: Equip; max_force: double);
procedure new_gc(var g: GameController; bf: pBField; var p1, p2: Player; max_wind, max_force: double);
procedure gc_shoot(var g: GameController);
procedure gc_change_player(var g: GameController; p: integer);
procedure gc_step(var g: GameController; delta: double);
function gc_player_side(var g: GameController; p: integer) : Side;
function gc_player_life(var g: GameController; p: integer) : integer;
function gc_player_has_weapon(g: GameController; p: integer; w: integer) : boolean;
function gc_field_is_king(var g: GameController; v: IntVector) : boolean;
implementation
uses Config, StaticConfig;
procedure set_player_initial_angle(var g: GameController; p: integer); forward;
procedure new_player(var p: Player; name: ansistring; color: shortint; equipment: Equip; max_force: double);
begin
p.name := name;
p.color := color;
p.max_force := max_force;
p.force := max_force / 2;
p.equipment := equipment;
p.current_weapon := 1;
p.won := False;
end;
procedure new_gc(var g: GameController; bf: pBField; var p1, p2: Player; max_wind, max_force: double);
var
pc: pPhysicsController;
begin
new(pc);
new_pc(pc^, bf);
g.pc := pc;
g.wind_dir := random(2) * 2 - 1;
g.max_wind := max_wind;
g.max_force := max_force;
g.player[1] := p1;
g.player[2] := p2;
set_player_initial_angle(g, 1);
set_player_initial_angle(g, 2);
gc_change_player(g, 1);
end;
{ Chooses a comfortable initial angle for a player }
procedure set_player_initial_angle(var g: GameController; p: integer);
begin
if gc_player_side(g, p) = FortLeft then
g.player[p].angle := -pi/4
else
g.player[p].angle := -pi/4 * 3;
end;
{ Simulate a shot from current player's cannon }
procedure gc_shoot(var g: GameController);
var
r: Rocket;
whereshoot: IntVector;
force, angle, bforce, bangle: double;
current_player: pPlayer;
current_weapon: pRocket;
i: integer;
begin
if gc_player_has_weapon(g, g.current_player, g.player[g.current_player].current_weapon) then
begin
current_player := @g.player[g.current_player];
current_weapon := @current_player^.equipment[current_player^.current_weapon];
whereshoot := current_player^.cannon - iv(0, 1);
bforce := current_player^.force; force := bforce;
bangle := current_player^.angle; angle := bangle;
for i := 1 to current_weapon^.amount do
begin
new_rocket(r,
fc(whereshoot), { launch position (1 above cannon) }
force * v(cos(angle), sin(angle)), { initial velocity }
v(0, 9.81), { gravity }
current_weapon^.exp_radius, { explosion radius }
current_weapon^.exp_force, { explosion force }
current_weapon^.drill_len { drill length }
);
pc_add_rocket(g.pc^, r);
angle := bangle + random(1000) / 4000.0 - 0.25;
force := bforce + random(1000) / 250.0 - 2
end;
if current_weapon^.num <> -1 then
dec(current_weapon^.num);
end;
end;
procedure gc_change_player(var g: GameController; p: integer);
begin
g.current_player := p;
end;
function check_loose(var g: GameController; var p: Player) : boolean;
begin
check_loose := g.pc^.field^.arr[p.king.x, p.king.y].current_hp = 0;
end;
procedure wind_step(var g: GameController; delta: double);
begin
if random(trunc(1/delta * WIND_CHANGE_TIME)) = 0 then
g.wind_dir := -g.wind_dir;
g.pc^.wind.x := g.pc^.wind.x + g.wind_dir * WIND_FLUCT*delta * (random(100)/100 + 0.5);
if abs(g.pc^.wind.x) > g.max_wind then
begin
g.pc^.wind.x := g.max_wind * (g.pc^.wind.x / abs(g.pc^.wind.x));
g.wind_dir := -g.wind_dir;
end;
end;
procedure gc_step(var g: GameController; delta: double);
begin
wind_step(g, delta);
pc_step(g.pc^, delta);
if check_loose(g, g.player[1]) then
g.player[2].won := True;
if check_loose(g, g.player[2]) then
g.player[1].won := True;
end;
{ Returns on which side of the field the player is }
function gc_player_side(var g: GameController; p: integer) : Side;
var
o: integer;
begin
if p = 1 then o := 2 else o := 1;
if g.player[p].king.x < g.player[o].king.x then
gc_player_side := FortLeft
else
gc_player_side := FortRight;
end;
function gc_player_life(var g: GameController; p: integer) : integer;
var
k: IntVector;
begin
k := g.player[p].king;
gc_player_life := trunc(g.pc^.field^.arr[k.x, k.y].hp);
end;
function gc_player_has_weapon(g: GameController; p: integer; w: integer) : boolean;
begin
gc_player_has_weapon := (w <> 0) and (g.player[p].equipment[w].num > 0) or (g.player[p].equipment[w].num = -1);
end;
function gc_field_is_king(var g: GameController; v: IntVector) : boolean;
begin
gc_field_is_king := (v = g.player[1].king) or (v = g.player[2].king);
end;
begin
end.
|
unit uSerialCommunictor;
interface
uses
ExtCtrls, uCiaComport;
type
TOnReceiveDataEvent = procedure (Sender: TObject; const Data: AnsiString) of Object;
TSerialCommunicator = class
private
FComPort: TCiaComPort;
FTimeoutTimer: TTimer;
FTimeouted: Boolean;
FReadBuff: AnsiString;
FOnReceiveDataEvent: TOnReceiveDataEvent;
FIsRtuCommunication: Boolean;
procedure Open;
procedure Close;
procedure CheckReadBuff;
protected
procedure ComPortDataAvailable(Sender: TObject);
procedure FTimeoutTimerTimer(Sender: TObject);
public
procedure AfterConstruction; override;
destructor Destroy; override;
procedure Reset;
procedure Send(const DataStr: AnsiString;
OnReceiveDataEvent: TOnReceiveDataEvent;
IsRtuCommunication: Boolean);
end;
function SerialCommunicator: TSerialCommunicator;
implementation
uses uOptions, uMeter645Packet, PmAppPacket;
var
FSerialCommunicator: TSerialCommunicator;
function SerialCommunicator: TSerialCommunicator;
begin
if FSerialCommunicator=nil then
FSerialCommunicator := TSerialCommunicator.Create;
Result := FSerialCommunicator;
end;
{ TSerialCommunicator }
procedure TSerialCommunicator.AfterConstruction;
begin
inherited;
FComPort := TCiaComPort.Create(nil);
FComPort.OnDataAvailable := ComPortDataAvailable;
FTimeoutTimer := TTimer.Create(nil);
FTimeoutTimer.Enabled := false;
FTimeoutTimer.OnTimer := FTimeoutTimerTimer;
end;
procedure TSerialCommunicator.CheckReadBuff;
begin
end;
procedure TSerialCommunicator.Close;
begin
FTimeoutTimer.Enabled := false;
FComPort.Open := false;
FReadBuff := '';
end;
procedure TSerialCommunicator.ComPortDataAvailable(Sender: TObject);
var
temp: AnsiString;
begin
temp := FComPort.ReceiveStr;
if FTimeouted then
exit;
FReadBuff := FReadBuff + temp;
CheckReadBuff;
end;
destructor TSerialCommunicator.Destroy;
begin
Close;
FTimeoutTimer.Free;
FComPort.Free;
inherited;
end;
procedure TSerialCommunicator.FTimeoutTimerTimer(Sender: TObject);
begin
FTimeouted := true;
FReadBuff := '';
FTimeoutTimer.Enabled := false;
end;
procedure TSerialCommunicator.Open;
begin
if self.FComPort.Open then
exit;
FTimeoutTimer.Interval := Options.Timeout;
FReadBuff := '';
FComPort.Port := Options.CommPort;
FComPort.Baudrate := Options.CommBps;
FComPort.ByteSize := 8;
FComPort.StopBits := sbOne;
FComPort.LineMode := false;
FComPort.Parity := TParity(Options.Parity);
FComPort.Open := true;
end;
procedure TSerialCommunicator.Reset;
begin
Close;
Open;
end;
procedure TSerialCommunicator.Send(const DataStr: AnsiString;
OnReceiveDataEvent: TOnReceiveDataEvent;
IsRtuCommunication: Boolean);
begin
FOnReceiveDataEvent := OnReceiveDataEvent;
FIsRtuCommunication := IsRtuCommunication;
Open;
FReadBuff := '';
FComPort.SendStr(DataStr);
FTimeoutTimer.Enabled := true;
end;
initialization
FSerialCommunicator := nil;
finalization
if FSerialCommunicator<>nil then
FSerialCommunicator.Free;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.