text stringlengths 14 6.51M |
|---|
//***********************************************************************
//* Проект "Студгородок" *
//* Добавление льготы *
//* Выполнил: Чернявский А.Э. 2004-2005 г. *
//***********************************************************************
unit st_sp_lgota_FORM_ADD;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxStyles, cxCustomData, cxGraphics,
cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxCalendar,
cxCurrencyEdit, cxGridLevel, cxGridCustomTableView, cxGridTableView,
cxClasses, cxControls, cxGridCustomView, cxGridDBTableView, cxGrid,
Buttons, cxCheckBox, cxTextEdit, cxLabel, cxContainer, cxGroupBox,
StdCtrls, cxButtons, FIBDataSet, pFIBDataSet, St_Proc, st_ConstUnit;
type
TLgotaFormAdd = class(TForm)
OKButton: TcxButton;
CancelButton: TcxButton;
cxGroupBox1: TcxGroupBox;
KodLabel: TcxLabel;
ShortEdit: TcxTextEdit;
ShortNameLabel: TcxLabel;
NameLabel: TcxLabel;
NameEdit: TcxTextEdit;
KodEdit: TcxTextEdit;
GosCheck: TcxCheckBox;
MedCheck: TcxCheckBox;
cxGroupBox2: TcxGroupBox;
AddButton: TSpeedButton;
EditButton: TSpeedButton;
DeleteButton: TSpeedButton;
cxGrid1: TcxGrid;
cxGrid1DBTableView1: TcxGridDBTableView;
cxGrid1TableView1: TcxGridTableView;
cxGrid1TableView1BEG_DATE: TcxGridColumn;
cxGrid1TableView1END_DATE: TcxGridColumn;
cxGrid1TableView1PERCENT: TcxGridColumn;
cxGrid1Level1: TcxGridLevel;
cxStyleRepository1: TcxStyleRepository;
cxStyle1: TcxStyle;
cxStyle2: TcxStyle;
cxStyleRepository2: TcxStyleRepository;
cxStyle3: TcxStyle;
cxStyleRepository3: TcxStyleRepository;
cxStyle4: TcxStyle;
TempDataSet: TpFIBDataSet;
cxStyle5: TcxStyle;
cxStyleRepository4: TcxStyleRepository;
cxStyle6: TcxStyle;
flag: TcxGridColumn;
procedure CancelButtonClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure OKButtonClick(Sender: TObject);
procedure AddButtonClick(Sender: TObject);
procedure KodEditKeyPress(Sender: TObject; var Key: Char);
procedure ShortEditKeyPress(Sender: TObject; var Key: Char);
procedure GosCheckKeyPress(Sender: TObject; var Key: Char);
procedure NameEditKeyPress(Sender: TObject; var Key: Char);
procedure MedCheckKeyPress(Sender: TObject; var Key: Char);
procedure DeleteButtonClick(Sender: TObject);
procedure EditButtonClick(Sender: TObject);
private
PLanguageIndex: byte;
procedure FormIniLanguage();
public
procedure SortGridData;
end;
var
LgotaFormAdd: TLgotaFormAdd;
implementation
uses Unit_of_Utilits, st_sp_lgota_ADDPersent_Form, Lgota_Unit,DataModule1_Unit;
{$R *.dfm}
procedure TLgotaFormAdd.FormIniLanguage();
begin
// индекс языка (1-укр, 2 - рус)
PLanguageIndex:= St_Proc.cnLanguageIndex;
//названия кнопок
OKButton.Caption := st_ConstUnit.st_Accept[PLanguageIndex];
CancelButton.Caption := st_ConstUnit.st_Cancel[PLanguageIndex];
KodLabel.Caption := st_ConstUnit.st_LgCode[PLanguageIndex];
ShortNameLabel.Caption := st_ConstUnit.st_ShortLable[PLanguageIndex];
NameLabel.Caption := st_ConstUnit.st_NameLable[PLanguageIndex];
GosCheck.Properties.Caption := st_ConstUnit.st_Gos[PLanguageIndex];
MedCheck.Properties.Caption := st_ConstUnit.st_Med[PLanguageIndex];
cxGroupBox2.Caption := st_ConstUnit.st_LgPerc[PLanguageIndex];
AddButton.Hint:= st_ConstUnit.st_InsertBtn_Caption[PLanguageIndex];
EditButton.Hint:= st_ConstUnit.st_EditBtn_Caption[PLanguageIndex];
DeleteButton.Hint:= st_ConstUnit.st_DeleteBtn_Caption[PLanguageIndex];
cxGrid1TableView1BEG_DATE.Caption := st_ConstUnit.st_grid_Date_Beg[PLanguageIndex];
cxGrid1TableView1END_DATE.Caption := st_ConstUnit.st_grid_Date_End[PLanguageIndex];
cxGrid1TableView1PERCENT .Caption := st_ConstUnit.st_PercentOnly[PLanguageIndex];
end;
procedure TLgotaFormAdd.CancelButtonClick(Sender: TObject);
begin
Close;
end;
procedure TLgotaFormAdd.FormShow(Sender: TObject);
begin
if cxGrid1TableView1.DataController.RecordCount <> 0 then begin
cxGrid1TableView1.DataController.FocusedRecordIndex := 0;
EditButton.Enabled := true;
DeleteButton.Enabled := true;
end;
KodEdit.SetFocus;
end;
procedure TLgotaFormAdd.SortGridData;
{var
i : integer;
doNew : boolean;
temp_date_beg, temp_date_end : TDate;
temp_percent : Currency;
begin
if cxGrid1TableView1.DataController.RecordCount < 2 then exit;
doNew := true;
while doNew do begin
doNew := false;
for i := 0 to cxGrid1TableView1.DataController.RecordCount - 2 do
if cxGrid1TableView1.DataController.Values[i, 1] > cxGrid1TableView1.DataController.Values[i + 1, 1] then begin
temp_date_beg := cxGrid1TableView1.DataController.Values[i, 0];
temp_date_end := cxGrid1TableView1.DataController.Values[i, 1];
temp_percent := cxGrid1TableView1.DataController.Values[i, 2];
cxGrid1TableView1.DataController.Values[i, 0] := cxGrid1TableView1.DataController.Values[i + 1, 0];
cxGrid1TableView1.DataController.Values[i, 1] := cxGrid1TableView1.DataController.Values[i + 1, 1];
cxGrid1TableView1.DataController.Values[i, 2] := cxGrid1TableView1.DataController.Values[i + 1, 2];
cxGrid1TableView1.DataController.Values[i + 1, 0] := temp_date_beg;
cxGrid1TableView1.DataController.Values[i + 1, 1] := temp_date_end;
cxGrid1TableView1.DataController.Values[i + 1, 2] := temp_percent;
doNew := true;
end;
end;
end;}
var
i : integer;
doNew : boolean;
temp_flag : string;
temp_date_beg, temp_date_end : TDate;
temp_percent : Currency;
begin
if cxGrid1TableView1.DataController.RecordCount < 2 then exit;
doNew := true;
while doNew do
begin
doNew := false;
for i := 0 to cxGrid1TableView1.DataController.RecordCount - 2 do
begin
if (cxGrid1TableView1.DataController.Values[i, 0] <= cxGrid1TableView1.DataController.Values[i + 1, 1])
and (cxGrid1TableView1.DataController.Values[i, 1] < cxGrid1TableView1.DataController.Values[i + 1, 1]) then
begin
temp_flag :='';
temp_date_beg := cxGrid1TableView1.DataController.Values[i, 0];
temp_date_end := cxGrid1TableView1.DataController.Values[i, 1];
temp_percent:= cxGrid1TableView1.DataController.Values[i, 2];
if cxGrid1TableView1.DataController.Values[i, 3]<> null then
begin
temp_flag := cxGrid1TableView1.DataController.Values[i, 3];
cxGrid1TableView1.DataController.Values[i, 3]:= '';
end;
cxGrid1TableView1.DataController.Values[i, 0] := cxGrid1TableView1.DataController.Values[i + 1, 0];
cxGrid1TableView1.DataController.Values[i, 1] := cxGrid1TableView1.DataController.Values[i + 1, 1];
cxGrid1TableView1.DataController.Values[i, 2] := cxGrid1TableView1.DataController.Values[i + 1, 2];
if cxGrid1TableView1.DataController.Values[i + 1, 3]<> null then
begin
cxGrid1TableView1.DataController.Values[i, 3] := cxGrid1TableView1.DataController.Values[i + 1, 3];
cxGrid1TableView1.DataController.Values[i + 1, 3]:='';
end;
cxGrid1TableView1.DataController.Values[i + 1, 0] := temp_date_beg;
cxGrid1TableView1.DataController.Values[i + 1, 1] := temp_date_end;
cxGrid1TableView1.DataController.Values[i + 1, 2] := temp_percent;
if temp_flag<>'' then cxGrid1TableView1.DataController.Values[i + 1, 3] := temp_flag;
doNew := true;
end;
end;
end;
end;
procedure TLgotaFormAdd.FormCreate(Sender: TObject);
begin
cxGrid1TableView1.Items[0].DataBinding.ValueTypeClass := TcxDateTimeValueType;
cxGrid1TableView1.Items[1].DataBinding.ValueTypeClass := TcxDateTimeValueType;
cxGrid1TableView1.Items[2].DataBinding.ValueTypeClass := TcxFloatValueType;
FormIniLanguage();
end;
procedure TLgotaFormAdd.OKButtonClick(Sender: TObject);
var
i : integer;
begin
// проверка корректности заполнения формы
if not IntegerCheck(KodEdit.Text) then begin
ShowMessage(pchar(st_ConstUnit.st_mess_Code_need[PLanguageIndex]));
KodEdit.SetFocus;
exit;
end;
if LgotaFormAdd.Caption = st_ConstUnit.st_InsertBtn_Caption[PLanguageIndex] then
begin
TempDataSet.Active:=true;
if TempDataSet.Locate('NUM_LG',StrToInt(KodEdit.Text), [])= true then
begin
ShowMessage(pchar(st_ConstUnit.st_LgCodeExists[PLanguageIndex]));
KodEdit.SetFocus;
TempDataSet.Active:=false;
exit;
end;
TempDataSet.Active:=false;
end;
if ShortEdit.Text = '' then begin
ShowMessage(pchar(st_ConstUnit.st_mess_ShortName_need[PLanguageIndex]));
ShortEdit.SetFocus;
exit;
end;
if NameEdit.Text = '' then begin
ShowMessage(pchar(st_ConstUnit.st_mess_FullName_need[PLanguageIndex]));
NameEdit.SetFocus;
exit;
end;
if cxGrid1TableView1.DataController.RecordCount = 0 then begin
ShowMessage(pchar(st_ConstUnit.st_LgPercent_need[PLanguageIndex]));
exit;
end;
//Проверка замкнутости по периодам процентов
if cxGrid1TableView1.DataController.RecordCount > 1 then for i := 0 to cxGrid1TableView1.DataController.RecordCount - 2 do
if cxGrid1TableView1.DataController.Values[i, 1] <> cxGrid1TableView1.DataController.Values[i + 1, 0] then begin
ShowMessage(pchar(st_ConstUnit.st_LgZamknytost[PLanguageIndex]));
cxGrid1TableView1.DataController.FocusedRecordIndex := i;
exit;
end;
ModalResult := mrOK;
end;
procedure TLgotaFormAdd.AddButtonClick(Sender: TObject);
var
i: integer;
begin
LgotaAddPersent_Form := TLgotaAddPersent_Form.Create(Self);
LgotaAddPersent_Form.Caption := st_ConstUnit.st_InsertBtn_Caption[PLanguageIndex];
if cxGrid1TableView1.DataController.RecordCount = 0 then LgotaAddPersent_Form.AcademicYear ;
if cxGrid1TableView1.DataController.RecordCount <> 0 then LgotaAddPersent_Form.DateBegEdit.Date := cxGrid1TableView1.DataController.Values[cxGrid1TableView1.DataController.RecordCount - 1, 1];
if LgotaAddPersent_Form.ShowModal = mrOK then begin
cxGrid1TableView1.DataController.RecordCount := cxGrid1TableView1.DataController.RecordCount + 1;
cxGrid1TableView1.DataController.Values[cxGrid1TableView1.DataController.RecordCount - 1, 0] := LgotaAddPersent_Form.DateBegEdit.Date;
cxGrid1TableView1.DataController.Values[cxGrid1TableView1.DataController.RecordCount - 1, 1] := LgotaAddPersent_Form.DateEndEdit.Date;
cxGrid1TableView1.DataController.Values[cxGrid1TableView1.DataController.RecordCount - 1, 2] := LgotaAddPersent_Form.PercentEdit.Text;
cxGrid1TableView1.DataController.Values[cxGrid1TableView1.DataController.RecordCount - 1, 3] := '1';
// cxGrid1TableView1.DataController.FocusedRecordIndex := cxGrid1TableView1.DataController.RecordCount - 1;
EditButton.Enabled := true;
DeleteButton.Enabled := true;
SortGridData;
for i:=0 to cxGrid1TableView1.DataController.RecordCount - 1 do
if cxGrid1TableView1.DataController.Values[i, 3] = '1' then
begin
cxGrid1TableView1.DataController.FocusedRowIndex:=i;
cxGrid1TableView1.DataController.Values[i, 3] := '';
break;
end;
end;
cxGrid1.SetFocus;
LgotaAddPersent_Form.Free;
end;
procedure TLgotaFormAdd.KodEditKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then ShortEdit.SetFocus;
end;
procedure TLgotaFormAdd.ShortEditKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then NameEdit.SetFocus;
end;
procedure TLgotaFormAdd.GosCheckKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then MedCheck.SetFocus;
end;
procedure TLgotaFormAdd.NameEditKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then GosCheck.SetFocus;
end;
procedure TLgotaFormAdd.MedCheckKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then OKButton.SetFocus;
end;
procedure TLgotaFormAdd.DeleteButtonClick(Sender: TObject);
begin
if MessageBox(Handle,PChar(st_ConstUnit.st_DeletePromt[PLanguageIndex]),PChar(st_ConstUnit.st_Confirmation_Caption[PLanguageIndex]),MB_YESNO or MB_ICONQUESTION)= mrNo then exit;
cxGrid1TableView1.DataController.DeleteFocused;
if cxGrid1TableView1.DataController.RecordCount = 0 then begin
EditButton.Enabled := false;
Deletebutton.Enabled := false;
end;
end;
procedure TLgotaFormAdd.EditButtonClick(Sender: TObject);
var
i:integer;
begin
LgotaAddPersent_Form := TLgotaAddPersent_Form.Create(Self);
LgotaAddPersent_Form.Caption := st_ConstUnit.st_EditBtn_Caption[PLanguageIndex];
LgotaAddPersent_Form.DateBegEdit.Date := cxGrid1TableView1.DataController.Values[cxGrid1TableView1.DataController.FocusedRecordIndex, 0];
LgotaAddPersent_Form.DateEndEdit.Date := cxGrid1TableView1.DataController.Values[cxGrid1TableView1.DataController.FocusedRecordIndex, 1];
LgotaAddPersent_Form.PercentEdit.Text := cxGrid1TableView1.DataController.Values[cxGrid1TableView1.DataController.FocusedRecordIndex, 2];
if LgotaAddPersent_Form.ShowModal = mrOK then begin
cxGrid1TableView1.DataController.Values[cxGrid1TableView1.DataController.FocusedRecordIndex, 0] := LgotaAddPersent_Form.DateBegEdit.Date;
cxGrid1TableView1.DataController.Values[cxGrid1TableView1.DataController.FocusedRecordIndex, 1] := LgotaAddPersent_Form.DateEndEdit.Date;
cxGrid1TableView1.DataController.Values[cxGrid1TableView1.DataController.FocusedRecordIndex, 2] := LgotaAddPersent_Form.PercentEdit.Text;
cxGrid1TableView1.DataController.Values[cxGrid1TableView1.DataController.FocusedRecordIndex, 3] := '1';
SortGridData;
for i:=0 to cxGrid1TableView1.DataController.RecordCount - 1 do
if cxGrid1TableView1.DataController.Values[i, 3] = '1' then
begin
cxGrid1TableView1.DataController.FocusedRowIndex:=i;
cxGrid1TableView1.DataController.Values[i, 3] := '';
break;
end;
end;
LgotaAddPersent_Form.Free;
end;
end.
|
unit Objekt.DHLBaselist;
interface
uses
SysUtils, Classes, Contnrs;
type
TDHLBaseList = class
private
function GetCount: Integer;
protected
fList: TObjectList;
public
constructor Create; virtual;
destructor Destroy; override;
property Count: Integer read GetCount;
procedure Clear; virtual;
end;
implementation
{ TBaseList }
constructor TDHLBaseList.Create;
begin
fList := TObjectList.Create;
end;
destructor TDHLBaseList.Destroy;
begin
FreeAndNil(fList);
inherited;
end;
function TDHLBaseList.GetCount: Integer;
begin
Result := fList.Count;
end;
procedure TDHLBaseList.Clear;
begin
fList.Clear;
end;
end.
|
unit GuiaAlvo.Model.Delivery;
interface
type
TDelivery = class
private
FAPPLECOM: String;
FRAPPICOM: String;
FIFOODCOM: String;
procedure SetAPPLECOM(const Value: String);
procedure SetIFOODCOM(const Value: String);
procedure SetRAPPICOM(const Value: String);
public
property RAPPICOM : String read FRAPPICOM write SetRAPPICOM;
property IFOODCOM : String read FIFOODCOM write SetIFOODCOM;
property APPLECOM : String read FAPPLECOM write SetAPPLECOM;
End;
implementation
{ TDelivery }
procedure TDelivery.SetAPPLECOM(const Value: String);
begin
FAPPLECOM := Value;
end;
procedure TDelivery.SetIFOODCOM(const Value: String);
begin
FIFOODCOM := Value;
end;
procedure TDelivery.SetRAPPICOM(const Value: String);
begin
FRAPPICOM := Value;
end;
end.
|
{
SuperMaximo GameLibrary : Sound class unit
by Max Foster
License : http://creativecommons.org/licenses/by/3.0/
}
unit SoundClass;
{$mode objfpc}{$H+}
interface
uses SDL_mixer;
type
PSound = ^TSound;
TSound = object
strict private
chunk : PMix_Chunk;
volume_, currentChannel : integer;
name_ : string;
public
//Create a sound with the specified name, loaded up from a sound file
constructor create(newName, fileName : string);
destructor destroy;
function name : string;
procedure setVolume(percentage : integer; relative : boolean = false); //Set the volume of the sound (0-100)
function volume : integer;
//Play the sound with the specified volume (0-100), channel and number of times to loop. Use the default
//parameters to play the sound at a previously set volume (may be 100), in any free channel and with 0 loops
function play(newVolume : integer = -1; channel : integer = -1; loops : integer = 0) : integer;
function playing : boolean;
procedure stop;
procedure fade(time : longint); //Fade out the sound over a certain time period
procedure setSoundPosition(angle : integer = 90; distance : integer = 0); //Set the virtual position of the sound in 3D space
end;
//Allocate a number of channels to be used in sound playback (a good number is 16)
procedure allocateSoundChannels(channels : word);
function sound(searchName : string) : PSound;
function sound(channel : integer) : PSound;
function addSound(newName, fileName : string) : PSound;
procedure destroySound(searchName : string);
procedure destroySound(channel : integer);
procedure destroyAllSounds;
implementation
uses SysUtils, Classes;
var
allSounds : array['a'..'z'] of TList;
allChannels : array of PSound;
procedure allocateSoundChannels(channels : word);
var
i : word;
begin
Mix_AllocateChannels(channels);
i := length(allChannels);
if (i > channels) then setLength(allChannels, channels)
else
if (i < channels) then
begin
setLength(allChannels, channels);
for i := i to channels-1 do allChannels[i] := nil;
end;
end;
constructor TSound.create(newName, fileName : string);
begin
name_ := newName;
chunk := Mix_LoadWAV(pchar(setDirSeparators(fileName)));
volume_ := 100;
currentChannel := -1;
end;
destructor TSound.destroy;
begin
Mix_FreeChunk(chunk);
end;
function TSound.name : string;
begin
result := name_;
end;
procedure TSound.setVolume(percentage : integer; relative : boolean);
begin
if (relative) then volume_ += percentage else volume_ := percentage;
if (volume_ > 100) then volume_ := 100 else if (volume_ < 0) then volume_ := 0;
if (currentChannel > -1) then Mix_Volume(currentChannel, round((MIX_MAX_VOLUME/100)*volume_));
end;
function TSound.volume : integer;
begin
result := volume_;
end;
function TSound.play(newVolume : integer = -1; channel : integer = -1; loops : integer = 0) : integer;
begin
currentChannel := Mix_PlayChannel(channel, chunk, loops);
if (currentChannel > -1) then
begin
allChannels[currentChannel] := @self;
if (newVolume > -1) then volume_ := newVolume;
Mix_Volume(currentChannel, round((MIX_MAX_VOLUME/100)*volume_));
end;
result := currentChannel;
end;
function TSound.playing : boolean;
begin
if (Mix_GetChunk(currentChannel) = chunk) then result := (Mix_Playing(currentChannel) = 1) else result := false;
end;
procedure TSound.stop;
begin
if (Mix_GetChunk(currentChannel) = chunk) then Mix_HaltChannel(currentChannel);
end;
procedure TSound.fade(time : longint);
begin
if (Mix_GetChunk(currentChannel) = chunk) then Mix_FadeOutChannel(currentChannel, time);
end;
procedure TSound.setSoundPosition(angle : integer = 90; distance : integer = 0);
begin
if (Mix_GetChunk(currentChannel) = chunk) then Mix_SetPosition(currentChannel, angle, distance);
end;
function sound(searchName : string) : PSound;
var
letter : char;
i : word;
tempSound : PSound;
begin
letter := searchName[1];
result := nil;
if (allSounds[letter].count > 0) then
begin
for i := 0 to allSounds[letter].count-1 do
begin
tempSound := PSound(allSounds[letter][i]);
if (tempSound^.name = searchName) then result := tempSound;
end;
end;
end;
function sound(channel : integer) : PSound;
begin
result := allChannels[channel];
end;
function addSound(newName, fileName : string) : PSound;
var
letter : char;
begin
letter := newName[1];
allSounds[letter].add(new(PSound, create(newName, fileName)));
result := allSounds[letter].last;
end;
procedure destroySound(searchName : string);
var
letter : char;
i : word;
tempSound : PSound;
begin
letter := searchName[1];
if (allSounds[letter].count > 0) then
begin
for i := 0 to allSounds[letter].count-1 do
begin
tempSound := PSound(allSounds[letter][i]);
if (tempSound^.name = searchName) then
begin
dispose(tempSound, destroy);
allSounds[letter].delete(i);
break;
end;
end;
end;
end;
procedure destroySound(channel : integer);
var
letter : char;
i : word;
tempSound : PSound;
begin
if (allChannels[channel] <> nil) then
begin
letter := allChannels[channel]^.name[1];
if (allSounds[letter].count > 0) then
begin
for i := 0 to allSounds[letter].count-1 do
begin
tempSound := PSound(allSounds[letter][i]);
if (tempSound^.name = allChannels[channel]^.name) then
begin
dispose(tempSound, destroy);
allSounds[letter].delete(i);
allChannels[channel] := nil;
break;
end;
end;
end;
end;
end;
procedure destroyAllSounds;
var
i : char;
j : integer;
tempSound : PSound;
begin
for i := 'a' to 'z' do
begin
if (allSounds[i].count > 0) then
begin
for j := 0 to allSounds[i].count-1 do
begin
tempSound := PSound(allSounds[i][j]);
dispose(tempSound, destroy);
end;
allSounds[i].clear;
end;
end;
for j := 0 to length(allChannels)-1 do allChannels[j] := nil
end;
procedure initializeAllSounds;
var
i : char;
begin
for i := 'a' to 'z' do
begin
allSounds[i] := TList.create;
end;
end;
procedure finalizeAllSounds;
var
i : char;
begin
for i := 'a' to 'z' do
begin
allSounds[i].destroy;
end;
end;
initialization
initializeAllSounds;
finalization
finalizeAllSounds;
end.
|
//------------------------------------------------------------------------------
//DatabaseOptions UNIT
//------------------------------------------------------------------------------
// What it does-
// This unit is used to gain access to configuration variables loaded from
// Database.ini.
//
// Changes -
// January 7th, 2007 - RaX - Broken out from ServerOptions.
//
//------------------------------------------------------------------------------
unit DatabaseOptions;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
IniFiles;
type
TDatabaseConfig = record
Protocol : string;
Host : string;
Port : Integer;
Database : string;
User : string;
Pass : string;
end;
//------------------------------------------------------------------------------
//TDatabaseOptions CLASS
//------------------------------------------------------------------------------
TDatabaseOptions = class(TMemIniFile)
protected
fAccountConfig : TDatabaseConfig;
fGameConfig : TDatabaseConfig;
public
property AccountConfig : TDatabaseConfig read fAccountConfig;
property GameConfig : TDatabaseConfig read fGameConfig;
Procedure Load;
Procedure Save;
end;
//------------------------------------------------------------------------------
implementation
uses
Classes,
SysUtils,
NetworkConstants,
Math,
Main;
//------------------------------------------------------------------------------
//Load() PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// This routine is called to load the ini file values from file itself.
// This routine contains multiple subroutines. Each one loads a different
// portion of the ini. All changes to said routines should be documented in
// THIS changes block.
//
// Changes -
// September 21st, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
procedure TDatabaseOptions.Load;
var
Section : TStringList;
//--------------------------------------------------------------------------
//LoadDatabaseConfig SUB PROCEDURE
//--------------------------------------------------------------------------
procedure LoadDatabaseConfig(const ADatabase : string; var ADatabaseConfig : TDatabaseConfig);
begin
ReadSectionValues(ADatabase, Section);
if Section.Values['Protocol'] = '' then
begin
Section.Values['Protocol'] := 'sqlite-3';
end;
ADatabaseConfig.Protocol := Section.Values['Protocol'];
ADatabaseConfig.Host := Section.Values['Host'];
ADatabaseConfig.Port := EnsureRange(StrToIntDef(Section.Values['Port'], 3306), 1, MAX_PORT);
if Section.Values['Database'] = '' then
begin
Section.Values['Database'] := MainProc.Options.DatabaseDirectory+'/'+ADatabase+'.db';
end;
ADatabaseConfig.Database := Section.Values['Database'];
ADatabaseConfig.User := Section.Values['Username'];
ADatabaseConfig.Pass := Section.Values['Password'];
end;{Subroutine LoadOptions}
//--------------------------------------------------------------------------
begin
Section := TStringList.Create;
Section.QuoteChar := '"';
Section.Delimiter := ',';
LoadDatabaseConfig('account', fAccountConfig);
LoadDatabaseConfig('game', fGameConfig);
Section.Free;
end;{Load}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Save() PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// This routine saves all configuration values defined here to the .ini
// file.
//
// Changes -
// September 21st, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
procedure TDatabaseOptions.Save;
procedure SaveDatabaseConfig(const ADatabase : string; var ADatabaseConfig : TDatabaseConfig);
begin
with ADatabaseConfig do
begin
WriteString(ADatabase,'Protocol', Protocol);
WriteString(ADatabase,'Host', Host);
WriteString(ADatabase,'Port', IntToStr(Port));
WriteString(ADatabase,'Database', Database);
WriteString(ADatabase,'Username', User);
WriteString(ADatabase,'Password', Pass);
end;
end;
begin
SaveDatabaseConfig('Account', fAccountConfig);
SaveDatabaseConfig('Game', fGameConfig);
UpdateFile;
end;{Save}
//------------------------------------------------------------------------------
end{ServerOptions}.
|
unit VolumeFaceVerifier;
// This class stores all faces (triangles or quads that a mesh extraction
// algorithm is building at each region. It's conceived to avoid quads or
// triangles being constructed at the same face. Check VoxelMeshGenerator.pas
// for its usage.
interface
uses BasicRenderingTypes, BasicConstants;
{$INCLUDE source/Global_Conditionals.inc}
type
CVolumeFaceVerifier = class
private
function isPixelValid(_x, _y, _z: integer):boolean;
public
Items: array of array of array of TSurfaceDescriptiorItem;
// Constructors and Destructors
constructor Create(_xSize, _ySize, _zSize: integer);
destructor Destroy; override;
// Add
procedure AddTriangle(const _Triangle: PTriangleItem; _x,_y,_z,_face: integer);
procedure AddTriangleUnsafe(const _Triangle: PTriangleItem; _x,_y,_z,_face: integer);
procedure AddQuad(const _Quad: PQuadItem; _x,_y,_z,_face: integer);
procedure AddQuadUnsafe(const _Quad: PQuadItem; _x,_y,_z,_face: integer);
// Delete
procedure Clear;
end;
implementation
{$ifdef MESH_TEST}
uses GlobalVars, SysUtils;
{$endif}
constructor CVolumeFaceVerifier.Create(_xSize, _ySize, _zSize: integer);
var
x,y,z: integer;
begin
SetLength(Items,_xSize,_ySize,_zSize);
for x := 0 to High(Items) do
for y := 0 to High(Items[x]) do
for z := 0 to High(Items[x,y]) do
begin
Items[x,y,z].Triangles[0] := nil;
Items[x,y,z].Triangles[1] := nil;
Items[x,y,z].Triangles[2] := nil;
Items[x,y,z].Triangles[3] := nil;
Items[x,y,z].Triangles[4] := nil;
Items[x,y,z].Triangles[5] := nil;
Items[x,y,z].Quads[0] := nil;
Items[x,y,z].Quads[1] := nil;
Items[x,y,z].Quads[2] := nil;
Items[x,y,z].Quads[3] := nil;
Items[x,y,z].Quads[4] := nil;
Items[x,y,z].Quads[5] := nil;
end;
end;
destructor CVolumeFaceVerifier.Destroy;
begin
Clear;
inherited Destroy;
end;
function CVolumeFaceVerifier.isPixelValid(_x, _y, _z: integer):boolean;
begin
Result := (_x >= 0) and (_y >= 0) and (_z >= 0) and (_x <= High(Items)) and (_y <= High(Items[0])) and (_z <= High(Items[0,0]));
end;
// Add
procedure CVolumeFaceVerifier.AddTriangle(const _Triangle: PTriangleItem; _x,_y,_z,_face: integer);
begin
if _Triangle <> nil then
begin
if (_Face >= 0) and (_Face < 6) then
begin
if isPixelValid(_x,_y,_z) then
begin
AddTriangleUnsafe(_Triangle,_x,_y,_z,_face);
end;
end;
end;
end;
// Here we check if the cell (_x,_y,_z) has a triangle or a quad at the _face or
// if the neighbour cell has a triangle or quad at the opposite face. If that
// happens, we'll invalidate the new triangle and the existing triangle/quad.
// If that doesn't happen, we'll add the triangle at the cell and the opposite
// triangle at the neighbour.
procedure CVolumeFaceVerifier.AddTriangleUnsafe(const _Triangle: PTriangleItem; _x,_y,_z,_face: integer);
const
SymmetricFaces: array [0..5] of byte = (1,0,3,2,5,4);
SymmetricFaceLocation: array [0..5,0..2] of integer = ((-1,0,0),(1,0,0),(0,-1,0),(0,1,0),(0,0,-1),(0,0,1));
var
xSF,ySF,zSF: integer;
begin
xSF := _x + SymmetricFaceLocation[_face,0];
ySF := _y + SymmetricFaceLocation[_face,1];
zSF := _z + SymmetricFaceLocation[_face,2];
if (Items[_x,_y,_z].Triangles[_face] <> nil) then
begin
// delete triangle.
_Triangle^.v1 := C_VMG_NO_VERTEX;
Items[_x,_y,_z].Triangles[_face]^.v1 := C_VMG_NO_VERTEX;
Items[_x,_y,_z].Triangles[_face] := nil;
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Triangle construction has been aborted due to a triangle.');
{$endif}
if isPixelValid(xSF,ySF,zSF) then
begin
Items[xSF,ySF,zSF].Triangles[SymmetricFaces[_face]]^.v1 := C_VMG_NO_VERTEX;
Items[xSF,ySF,zSF].Triangles[SymmetricFaces[_face]] := nil;
end;
end
else if (Items[_x,_y,_z].Quads[_face] <> nil) then
begin
// delete quad
_Triangle^.v1 := C_VMG_NO_VERTEX;
Items[_x,_y,_z].Quads[_face]^.v1 := C_VMG_NO_VERTEX;
Items[_x,_y,_z].Quads[_face] := nil;
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Triangle construction has been aborted due to a quad.');
{$endif}
if isPixelValid(xSF,ySF,zSF) then
begin
Items[xSF,ySF,zSF].Quads[SymmetricFaces[_face]]^.v1 := C_VMG_NO_VERTEX;
Items[xSF,ySF,zSF].Quads[SymmetricFaces[_face]] := nil;
end;
end
else // then we should add it.
begin
Items[_x,_y,_z].Triangles[_face] := _Triangle;
if isPixelValid(xSF,ySF,zSF) then
begin
Items[xSF,ySF,zSF].Triangles[SymmetricFaces[_face]] := _Triangle;
end;
end;
end;
procedure CVolumeFaceVerifier.AddQuad(const _Quad: PQuadItem; _x,_y,_z,_face: integer);
begin
if _Quad <> nil then
begin
if (_Face >= 0) and (_Face < 6) then
begin
if isPixelValid(_x,_y,_z) then
begin
AddQuadUnsafe(_Quad,_x,_y,_z,_face);
end;
end;
end;
end;
// Here we check if the cell (_x,_y,_z) has a triangle or a quad at the _face or
// if the neighbour cell has a triangle or quad at the opposite face. If that
// happens, we'll invalidate the new triangle and the existing triangle/quad.
// If that doesn't happen, we'll add the quad at the cell and the opposite quad
// at the neighbour.
procedure CVolumeFaceVerifier.AddQuadUnsafe(const _Quad: PQuadItem; _x,_y,_z,_face: integer);
const
SymmetricFaces: array [0..5] of byte = (1,0,3,2,5,4);
SymmetricFaceLocation: array [0..5,0..2] of integer = ((-1,0,0),(1,0,0),(0,-1,0),(0,1,0),(0,0,-1),(0,0,1));
var
xSF,ySF,zSF: integer;
begin
xSF := _x + SymmetricFaceLocation[_face,0];
ySF := _y + SymmetricFaceLocation[_face,1];
zSF := _z + SymmetricFaceLocation[_face,2];
if (Items[_x,_y,_z].Triangles[_face] <> nil) then
begin
_Quad^.v1 := C_VMG_NO_VERTEX;
Items[_x,_y,_z].Triangles[_face]^.v1 := C_VMG_NO_VERTEX;
Items[_x,_y,_z].Triangles[_face] := nil;
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Quad construction has been aborted due to a triangle.');
{$endif}
if isPixelValid(xSF,ySF,zSF) then
begin
Items[xSF, ySF, zSF].Triangles[SymmetricFaces[_face]]^.v1 := C_VMG_NO_VERTEX;
Items[xSF, ySF, zSF].Triangles[SymmetricFaces[_face]] := nil;
end;
end
else if (Items[_x,_y,_z].Quads[_face] <> nil) then
begin
_Quad^.v1 := C_VMG_NO_VERTEX;
Items[_x,_y,_z].Quads[_face]^.v1 := C_VMG_NO_VERTEX;
Items[_x,_y,_z].Quads[_face] := nil;
{$ifdef MESH_TEST}
GlobalVars.MeshFile.Add('Quad construction has been aborted due to a quad.');
{$endif}
if isPixelValid(xSF,ySF,zSF) then
begin
Items[xSF, ySF, zSF].Quads[SymmetricFaces[_face]]^.v1 := C_VMG_NO_VERTEX;
Items[xSF, ySF, zSF].Quads[SymmetricFaces[_face]] := nil;
end;
end
else
begin
Items[_x,_y,_z].Quads[_face] := _Quad;
if isPixelValid(xSF,ySF,zSF) then
begin
Items[xSF, ySF, zSF].Quads[SymmetricFaces[_face]] := _Quad;
end;
end;
end;
// Delete
procedure CVolumeFaceVerifier.Clear;
var
x,y: integer;
begin
for x := 0 to High(Items) do
begin
for y := 0 to High(Items[x]) do
begin
SetLength(Items[x,y],0);
end;
SetLength(Items[x],0);
end;
SetLength(Items,0);
end;
end.
|
unit InflatablesList_HTML_Parser;
{$INCLUDE '.\InflatablesList_defs.inc'}
interface
uses
Classes,
AuxTypes, CountedDynArrayObject,
InflatablesList_HTML_Tokenizer,
InflatablesList_HTML_Document;
type
TILHTMLParser = class(TObject)
private
fRaiseParseErrs: Boolean;
fSource: TStream;
fText: UnicodeString;
fRootAssigned: Boolean;
fRootElement: TILHTMLElementNode;
fCurrentElement: TILHTMLElementNode;
fOpenElements: TObjectCountedDynArray;
protected
class Function IsVoidElement(const Name: String): Boolean; virtual;
procedure TokenHandler(Sender: TObject; Token: TILHTMLToken; var Ack: Boolean); virtual;
procedure Preprocess; virtual;
procedure Parse; virtual;
public
constructor Create(Source: TStream);
destructor Destroy; override;
procedure Run; virtual;
Function GetDocument: TILHTMLDocument; virtual;
property RaiseParseErrors: Boolean read fRaiseParseErrs write fRaiseParseErrs;
end;
implementation
uses
SysUtils,
StrRect,
InflatablesList_Types,
InflatablesList_Utils,
InflatablesList_HTML_UnicodeTagAttributeArray,
InflatablesList_HTML_Preprocessor;
class Function TILHTMLParser.IsVoidElement(const Name: String): Boolean;
const
VOID_ELEMENT_NAMES: array[0..13] of String = ('area','base','br','col','embed',
'hr','img','input','link','meta','param','source','track','wbr');
var
i: Integer;
begin
Result := False;
For i := Low(VOID_ELEMENT_NAMES) to High(VOID_ELEMENT_NAMES) do
If IL_SameText(VOID_ELEMENT_NAMES[i],Name) then
begin
Result := True;
Break{For i};
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLParser.TokenHandler(Sender: TObject; Token: TILHTMLToken; var Ack: Boolean);
var
NewElement: TILHTMLElementNode;
i: Integer;
begin
case Token.TokenType of
ilttStartTag: begin
NewElement := TILHTMLElementNode.Create(fCurrentElement,IL_ReconvString(UnicodeToStr(Token.TagName)));
// add attributes
For i := CDA_Low(Token.Attributes) to CDA_High(Token.Attributes) do
NewElement.AttributeAdd(UnicodeToStr(CDA_GetItem(Token.Attributes,i).Name),
UnicodeToStr(CDA_GetItem(Token.Attributes,i).Value));
If Token.SelfClosing or IsVoidElement(NewElement.Name.Str) then
NewElement.Close;
If not Assigned(fRootElement) then
begin
If fRootAssigned then
raise Exception.Create('Root was already assigned and now is nil.')
else
fRootAssigned := True;
fRootElement := NewElement;
fCurrentElement := fRootElement;
If NewElement.Open then
CDA_Add(fOpenElements,NewElement);
end
else If Assigned(fCurrentElement) then
begin
fCurrentElement.ElementAdd(NewElement);
If NewElement.Open then
begin
CDA_Add(fOpenElements,NewElement);
fCurrentElement := NewElement;
end;
end
else NewElement.Free; // no current element, drop the new one
If (Sender is TILHTMLTokenizer) then
begin
If IL_SameText(UnicodeToStr('script'),Token.TagName) then
TILHTMLTokenizer(Sender).State := iltsScriptData
else If IL_SameText(UnicodeToStr('noscript'),Token.TagName) then
TILHTMLTokenizer(Sender).State := iltsRAWText;
end;
end;
ilttEndTag: If Assigned(fCurrentElement) then
begin
If IL_SameText(fCurrentElement.Name.Str,UnicodeToStr(Token.TagName)) then
begin
fCurrentElement.Close;
fCurrentElement := fCurrentElement.Parent;
If CDA_Count(fOpenElements) > 0 then
CDA_Delete(fOpenElements,CDA_High(fOpenElements));
end
else
begin
// missnested
For i := CDA_High(fOpenElements) downto CDA_Low(fOpenElements) do
If IL_SameText(TILHTMLElementNode(CDA_GetItem(fOpenElements,i)).Name.Str,UnicodeToStr(Token.TagName)) then
begin
fCurrentElement := TILHTMLElementNode(CDA_GetItem(fOpenElements,i)).Parent;
TILHTMLElementNode(CDA_GetItem(fOpenElements,i)).Close;
CDA_Delete(fOpenElements,i);
Break{For i};
end
end;
end;
ilttCharacter: If Assigned(fCurrentElement) then
fCurrentElement.TextAppend(Token.Data);
ilttEndOfFile: begin
For i := CDA_Low(fOpenElements) to CDA_High(fOpenElements) do
TILHTMLElementNode(CDA_GetItem(fOpenElements,i)).Close;
CDA_Clear(fOpenElements);
end;
else
{ilttDOCTYPE,ilttComment}
// ignore these tokens
end;
Ack := True;
end;
//------------------------------------------------------------------------------
procedure TILHTMLParser.Preprocess;
var
Preprocessor: TILHTMLPreprocessor;
begin
Preprocessor := TILHTMLPreprocessor.Create;
try
Preprocessor.RaiseParseErrors := fRaiseParseErrs;
fSource.Seek(0,soBeginning);
fText := Preprocessor.Process(fSource,True); // first try with UTF8
If (Length(fText) <= 0) and (fSource.Size > 0) then
begin
fSource.Seek(0,soBeginning);
fText := Preprocessor.Process(fSource,False); // try with ANSI
end;
finally
Preprocessor.Free;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLParser.Parse;
var
Tokenizer: TILHTMLTokenizer;
begin
Tokenizer := TILHTMLTokenizer.Create;
try
Tokenizer.RaiseParseErrors := fRaiseParseErrs;
Tokenizer.OnTokenEmit := TokenHandler;
Tokenizer.Initialize(fText);
Tokenizer.Run;
finally
Tokenizer.Free;
end;
end;
//==============================================================================
constructor TILHTMLParser.Create(Source: TStream);
begin
inherited Create;
fRaiseParseErrs := True;
fSource := Source;
fText := '';
fRootAssigned := False;
fRootElement := nil;
fCurrentElement := nil;
CDA_Init(fOpenElements);
end;
//------------------------------------------------------------------------------
destructor TILHTMLParser.Destroy;
begin
If Assigned(fRootElement) then
fRootElement.Free;
inherited;
end;
//------------------------------------------------------------------------------
procedure TILHTMLParser.Run;
begin
fRootAssigned := False;
If Assigned(fRootElement) then
FreeAndNil(fRootElement); // this will also free all other elements
fCurrentElement := nil;
CDA_Clear(fOpenElements);
Preprocess;
Parse;
If not Assigned(fRootElement) then
raise Exception.Create('Empty document.');
fRootElement.TextFinalize;
fRootElement.Close;
end;
//------------------------------------------------------------------------------
Function TILHTMLParser.GetDocument: TILHTMLDocument;
begin
Result := TILHTMLDocument.CreateAsCopy(nil,fRootElement,True);
end;
end.
|
unit uModelBill;
interface
uses
Classes, Windows, SysUtils, DBClient, uPubFun, uParamObject, uBusinessLayerPlugin,
uBaseInfoDef, uModelParent, uModelBaseListIntf, uModelBillIntf;
type
TModelBillOrder = class(TModelBill, IModelBillOrder) //单据-订单
function GetBillCreateProcName: string; override;
end;
TModelBillBuy = class(TModelBill, IModelBillBuy) //单据-销售单
function GetBillCreateProcName: string; override;
end;
TModelBillSale = class(TModelBill, IModelBillSale) //单据-进货单
function GetBillCreateProcName: string; override;
end;
TModelBillAllot = class(TModelBill, IModelBillAllot) //单据-调拨单
function GetBillCreateProcName: string; override;
end;
TModelBillPRMoney = class(TModelBill, IModelBillPRMoney) //单据-调拨单
function GetBillCreateProcName: string; override;
function QryBalance(AInParam: TParamObject; ACds: TClientDataSet): Integer; //查询需要结算点单据
function SaveBalance(AParam: TParamObject): Integer; //保存,修改或删除结算的单据记录
end;
implementation
uses uModelFunCom;
{ TModelBillOrder }
function TModelBillOrder.GetBillCreateProcName: string;
begin
Result := 'pbx_Bill_Order_Create';
end;
{ TModelBillSale }
function TModelBillSale.GetBillCreateProcName: string;
begin
Result := 'pbx_Bill_Create';
end;
{ TModelBillBuy }
function TModelBillBuy.GetBillCreateProcName: string;
begin
Result := 'pbx_Bill_Create';
end;
{ TModelBillAllot }
function TModelBillAllot.GetBillCreateProcName: string;
begin
Result := 'pbx_Bill_Create';
end;
{ TModelBillPRMoney }
function TModelBillPRMoney.GetBillCreateProcName: string;
begin
Result := 'pbx_Bill_Create';
end;
function TModelBillPRMoney.QryBalance(AInParam: TParamObject;
ACds: TClientDataSet): Integer;
begin
try
Result := gMFCom.ExecProcBackData('pbx_A_Qry_Balance', AInParam, ACds);
finally
end;
end;
function TModelBillPRMoney.SaveBalance(AParam: TParamObject): Integer;
begin
Result := gMFCom.ExecProcByName('pbx_A_Save_Gathering', AParam);
end;
initialization
gClassIntfManage.addClass(TModelBillOrder, IModelBillOrder);
gClassIntfManage.addClass(TModelBillBuy, IModelBillBuy);
gClassIntfManage.addClass(TModelBillSale, IModelBillSale);
gClassIntfManage.addClass(TModelBillAllot, IModelBillAllot);
gClassIntfManage.addClass(TModelBillPRMoney, IModelBillPRMoney);
end.
|
unit uArrayList;
interface
type List = Array of TObject;
{
Automatic dynamic array
}
type ArrayList = class
protected
arr: List;
len: integer;
public
constructor Create(); overload;
constructor Create(amount: integer); overload;
function enlargeBy(arr: List; amount: integer): List;
function enlarge(arr: List): List;
procedure add(obj: TObject);
procedure put(obj: TObject; index: integer);
function remove(index: integer): TObject; overload;
procedure remove(obj: TObject); overload;
function size(): integer;
function get(index: integer): TObject;
function find(obj: TObject): integer;
end;
implementation
// ArrayList
constructor ArrayList.Create(amount: integer);
begin
SetLength(arr, amount);
len := 0;
end;
// ArrayList
constructor ArrayList.Create();
begin
Create(10);
end;
// ArrayList
function ArrayList.enlargeBy(arr: List; amount: integer): List;
var
sub: List;
i, len: integer;
begin
len := Length(arr) + amount;
SetLength(sub, len);
for i := 0 to len - 1 do
sub[i] := arr[i];
enlargeBy := sub;
end;
// ArrayList
function ArrayList.enlarge(arr: List): List;
begin
enlarge := enlargeBy(arr, Length(arr) + 1);
end;
// ArrayList
procedure ArrayList.add(obj: TObject);
begin
if len >= length(arr) then
arr := enlarge(arr);
arr[len] := obj;
len := len + 1;
end;
// ArrayList
procedure ArrayList.put(obj: TObject; index: integer);
begin
arr[index] := obj;
end;
// ArrayList
function ArrayList.remove(index: integer): TObject;
var i: integer;
begin
remove := nil;
if arr[index] <> nil then begin
remove := arr[index];
for i := index + 1 to len - 1 do begin
arr[i - 1] := arr[i];
end;
arr[len - 1] := nil;
len := len - 1;
end;
end;
// ArrayList
procedure ArrayList.remove(obj: TObject);
var i: integer;
begin
for i := 0 to len - 1 do begin
if arr[i] = obj then begin
remove(i);
break;
end;
end;
end;
// ArrayList
function ArrayList.size(): integer;
begin
size := len;
end;
// ArrayList
function ArrayList.get(index: integer): TObject;
begin
get := arr[index];
end;
// ArrayList
function ArrayList.find(obj: TObject): integer;
var i: integer;
begin
find := -1;
for i := 0 to len - 1 do
if obj = get(i) then begin
find := i;
break;
end;
end;
end.
|
unit uWfxPluginUtil;
{$mode objfpc}{$H+}
{$if FPC_FULLVERSION >= 30300}
{$modeswitch arraytodynarray}
{$endif}
interface
uses
Classes, SysUtils, LCLProc, DCOSUtils, uLog, uGlobs,
WfxPlugin, uWfxModule,
uFile,
uFileSource,
uFileSourceOperation,
uFileSourceTreeBuilder,
uFileSourceOperationOptions,
uFileSourceOperationUI,
uFileSourceCopyOperation,
uWfxPluginFileSource;
type
TWfxPluginOperationHelperMode =
(wpohmCopy, wpohmCopyIn, wpohmCopyOut, wpohmMove);
TUpdateStatisticsFunction = procedure(var NewStatistics: TFileSourceCopyOperationStatistics) of object;
{ TWfxTreeBuilder }
TWfxTreeBuilder = class(TFileSourceTreeBuilder)
private
FWfxModule: TWfxModule;
protected
procedure AddLinkTarget(aFile: TFile; CurrentNode: TFileTreeNode); override;
procedure AddFilesInDirectory(srcPath: String; CurrentNode: TFileTreeNode); override;
public
property WfxModule: TWfxModule read FWfxModule write FWfxModule;
end;
{ TWfxPluginOperationHelper }
TWfxPluginOperationHelper = class
private
FRootDir: TFile;
FWfxPluginFileSource: IWfxPluginFileSource;
FOperationThread: TThread;
FMode: TWfxPluginOperationHelperMode;
FRootTargetPath: String;
FRenameMask: String;
FRenameNameMask, FRenameExtMask: String;
FLogCaption: String;
FRenamingFiles,
FRenamingRootDir,
FInternal: Boolean;
FStatistics: PFileSourceCopyOperationStatistics;
FCopyAttributesOptions: TCopyAttributesOptions;
FFileExistsOption: TFileSourceOperationOptionFileExists;
FCurrentFile: TFile;
FCurrentTargetFile: TFile;
FCurrentTargetFilePath: String;
AskQuestion: TAskQuestionFunction;
AbortOperation: TAbortOperationFunction;
CheckOperationState: TCheckOperationStateFunction;
UpdateStatistics: TUpdateStatisticsFunction;
ShowCompareFilesUI: TShowCompareFilesUIFunction;
ShowCompareFilesUIByFileObject: TShowCompareFilesUIByFileObjectFunction;
procedure ShowError(sMessage: String);
procedure LogMessage(sMessage: String; logOptions: TLogOptions; logMsgType: TLogMsgType);
function ProcessNode(aFileTreeNode: TFileTreeNode; CurrentTargetPath: String): Integer;
function ProcessDirectory(aNode: TFileTreeNode; AbsoluteTargetFileName: String): Integer;
function ProcessLink(aNode: TFileTreeNode; AbsoluteTargetFileName: String): Integer;
function ProcessFile(aNode: TFileTreeNode; AbsoluteTargetFileName: String): Integer;
procedure QuestionActionHandler(Action: TFileSourceOperationUIAction);
function FileExists(aFile: TFile;
AbsoluteTargetFileName: String;
AllowResume: Boolean): TFileSourceOperationOptionFileExists;
procedure CopyProperties(SourceFile: TFile; const TargetFileName: String);
procedure CountStatistics(aNode: TFileTreeNode);
public
constructor Create(FileSource: IFileSource;
AskQuestionFunction: TAskQuestionFunction;
AbortOperationFunction: TAbortOperationFunction;
CheckOperationStateFunction: TCheckOperationStateFunction;
UpdateStatisticsFunction: TUpdateStatisticsFunction;
ShowCompareFilesUIFunction: TShowCompareFilesUIFunction;
ShowCompareFilesUIByFileObjectFunction: TShowCompareFilesUIByFileObjectFunction;
OperationThread: TThread;
Mode: TWfxPluginOperationHelperMode;
TargetPath: String
);
destructor Destroy; override;
procedure Initialize;
procedure ProcessTree(aFileTree: TFileTree; var Statistics: TFileSourceCopyOperationStatistics);
property FileExistsOption: TFileSourceOperationOptionFileExists read FFileExistsOption write FFileExistsOption;
property CopyAttributesOptions: TCopyAttributesOptions read FCopyAttributesOptions write FCopyAttributesOptions;
property RenameMask: String read FRenameMask write FRenameMask;
end;
function WfxRenameFile(aFileSource: IWfxPluginFileSource; const aFile: TFile; const NewFileName: String): Boolean;
function WfxFileTimeToDateTime(FileTime : TWfxFileTime) : TDateTime; inline;
function DateTimeToWfxFileTime(DateTime : TDateTime) : TWfxFileTime; inline;
implementation
uses
uFileProcs, StrUtils, DCStrUtils, uLng, uFileSystemUtil, uFileProperty,
DCDateTimeUtils, DCBasicTypes, DCFileAttributes;
function WfxRenameFile(aFileSource: IWfxPluginFileSource; const aFile: TFile; const NewFileName: String): Boolean;
var
ASize: Int64;
RemoteInfo: TRemoteInfo;
begin
with aFileSource do
begin
with RemoteInfo do
begin
ASize := aFile.Size;
Attr := LongInt(aFile.Attributes);
SizeLow := LongInt(Int64Rec(ASize).Lo);
SizeHigh := LongInt(Int64Rec(ASize).Hi);
LastWriteTime := DateTimeToWfxFileTime(aFile.ModificationTime);
end;
Result := (WfxCopyMove(aFile.Path + aFile.Name, aFile.Path + NewFileName, FS_COPYFLAGS_MOVE, @RemoteInfo, True, True) = FS_FILE_OK);
end;
end;
function WfxFileTimeToDateTime(FileTime: TWfxFileTime): TDateTime;
const
NULL_DATE_TIME = TDateTime(2958466.0);
begin
if (FileTime.dwLowDateTime = $FFFFFFFE) and (FileTime.dwHighDateTime = $FFFFFFFF) then
Result:= NULL_DATE_TIME
else if (TWinFileTime(FileTime) = 0) then
Result:= NULL_DATE_TIME
else
Result:= WinFileTimeToDateTime(TWinFileTime(FileTime));
end;
function DateTimeToWfxFileTime(DateTime: TDateTime): TWfxFileTime;
begin
if (DateTime <= SysUtils.MaxDateTime) then
Result:= TWfxFileTime(DateTimeToWinFileTime(DateTime))
else begin
Result.dwLowDateTime:= $FFFFFFFE;
Result.dwHighDateTime:= $FFFFFFFF;
end;
end;
{ TWfxTreeBuilder }
procedure TWfxTreeBuilder.AddLinkTarget(aFile: TFile; CurrentNode: TFileTreeNode);
begin
// Add as normal file/directory
if aFile.AttributesProperty is TNtfsFileAttributesProperty then
aFile.Attributes:= aFile.Attributes and (not FILE_ATTRIBUTE_REPARSE_POINT)
else
aFile.Attributes:= aFile.Attributes and (not S_IFLNK);
if not aFile.IsLinkToDirectory then
AddFile(aFile, CurrentNode)
else begin
if aFile.AttributesProperty is TNtfsFileAttributesProperty then
aFile.Attributes:= aFile.Attributes or FILE_ATTRIBUTE_DIRECTORY
else begin
aFile.Attributes:= aFile.Attributes or S_IFDIR;
end;
AddDirectory(aFile, CurrentNode);
end;
end;
procedure TWfxTreeBuilder.AddFilesInDirectory(srcPath: String;
CurrentNode: TFileTreeNode);
var
FindData: TWfxFindData;
Handle: THandle;
aFile: TFile;
begin
with FWfxModule do
begin
Handle := WfxFindFirst(srcPath, FindData);
if Handle = wfxInvalidHandle then Exit;
repeat
if (FindData.FileName = '.') or (FindData.FileName = '..') then Continue;
aFile:= TWfxPluginFileSource.CreateFile(srcPath, FindData);
AddItem(aFile, CurrentNode);
until not WfxFindNext(Handle, FindData);
FsFindClose(Handle);
end;
end;
{ TWfxPluginOperationHelper }
procedure TWfxPluginOperationHelper.ShowError(sMessage: String);
begin
if gSkipFileOpError then
begin
if log_errors in gLogOptions then
logWrite(FOperationThread, sMessage, lmtError, True);
end
else
begin
if AskQuestion(sMessage, '', [fsourSkip, fsourAbort],
fsourSkip, fsourAbort) = fsourAbort then
begin
AbortOperation;
end;
end;
end;
procedure TWfxPluginOperationHelper.LogMessage(sMessage: String;
logOptions: TLogOptions; logMsgType: TLogMsgType);
begin
case logMsgType of
lmtError:
if not (log_errors in gLogOptions) then Exit;
lmtInfo:
if not (log_info in gLogOptions) then Exit;
lmtSuccess:
if not (log_success in gLogOptions) then Exit;
end;
if logOptions <= gLogOptions then
begin
logWrite(FOperationThread, sMessage, logMsgType);
end;
end;
function TWfxPluginOperationHelper.ProcessNode(aFileTreeNode: TFileTreeNode;
CurrentTargetPath: String): Integer;
var
aFile: TFile;
TargetName: String;
ProcessedOk: Integer;
CurrentFileIndex: Integer;
CurrentSubNode: TFileTreeNode;
begin
Result := FS_FILE_OK;
for CurrentFileIndex := 0 to aFileTreeNode.SubNodesCount - 1 do
begin
CurrentSubNode := aFileTreeNode.SubNodes[CurrentFileIndex];
aFile := CurrentSubNode.TheFile;
if FRenamingRootDir and (aFile = FRootDir) then
TargetName := FRenameMask
else if FRenamingFiles then
TargetName := ApplyRenameMask(aFile, FRenameNameMask, FRenameExtMask)
else
TargetName := aFile.Name;
if FMode <> wpohmCopyOut then
TargetName := CurrentTargetPath + TargetName
else begin
TargetName := CurrentTargetPath + ReplaceInvalidChars(TargetName);
end;
with FStatistics^ do
begin
CurrentFileFrom := aFile.FullPath;
CurrentFileTo := TargetName;
CurrentFileTotalBytes := aFile.Size;
CurrentFileDoneBytes := 0;
end;
UpdateStatistics(FStatistics^);
if aFile.IsLink then
ProcessedOk := ProcessLink(CurrentSubNode, TargetName)
else if aFile.IsDirectory then
ProcessedOk := ProcessDirectory(CurrentSubNode, TargetName)
else
ProcessedOk := ProcessFile(CurrentSubNode, TargetName);
if ProcessedOk <> FS_FILE_OK then
Result := ProcessedOk;
if ProcessedOk = FS_FILE_USERABORT then AbortOperation();
if ProcessedOk = FS_FILE_OK then CopyProperties(aFile, TargetName);
if ProcessedOk = FS_FILE_OK then
begin
LogMessage(Format(rsMsgLogSuccess+FLogCaption, [aFile.FullPath + ' -> ' + TargetName]),
[log_vfs_op], lmtSuccess);
end
else
begin
ShowError(Format(rsMsgLogError + FLogCaption,
[aFile.FullPath + ' -> ' + TargetName +
' - ' + GetErrorMsg(ProcessedOk)]));
LogMessage(Format(rsMsgLogError+FLogCaption, [aFile.FullPath + ' -> ' + TargetName]),
[log_vfs_op], lmtError);
end;
CheckOperationState;
end;
end;
function TWfxPluginOperationHelper.ProcessDirectory(aNode: TFileTreeNode;
AbsoluteTargetFileName: String): Integer;
begin
// Create target directory
if (FMode <> wpohmCopyOut) then
Result:= FWfxPluginFileSource.WfxModule.WfxMkDir('', AbsoluteTargetFileName)
else begin
if mbForceDirectory(AbsoluteTargetFileName) then
Result:= FS_FILE_OK
else
Result:= WFX_ERROR;
end;
if Result = FS_FILE_OK then
begin
// Copy/Move all files inside.
Result := ProcessNode(aNode, IncludeTrailingPathDelimiter(AbsoluteTargetFileName));
end
else
begin
// Error - all files inside not copied/moved.
ShowError(rsMsgLogError + Format(rsMsgErrForceDir, [AbsoluteTargetFileName]));
CountStatistics(aNode);
end;
if (Result = FS_FILE_OK) and (FMode = wpohmMove) then
FWfxPluginFileSource.WfxModule.WfxRemoveDir(aNode.TheFile.FullPath);
end;
function TWfxPluginOperationHelper.ProcessLink(aNode: TFileTreeNode;
AbsoluteTargetFileName: String): Integer;
var
aSubNode: TFileTreeNode;
begin
if (FMode = wpohmMove) then
Result := ProcessFile(aNode, AbsoluteTargetFileName)
else if aNode.SubNodesCount > 0 then
begin
aSubNode := aNode.SubNodes[0];
if aSubNode.TheFile.AttributesProperty.IsDirectory then
Result := ProcessDirectory(aSubNode, AbsoluteTargetFileName)
else
Result := ProcessFile(aSubNode, AbsoluteTargetFileName);
end;
end;
function TWfxPluginOperationHelper.ProcessFile(aNode: TFileTreeNode;
AbsoluteTargetFileName: String): Integer;
var
iFlags: Integer = 0;
RemoteInfo: TRemoteInfo;
iTemp: TInt64Rec;
bCopyMoveIn: Boolean;
aFile: TFile;
OldDoneBytes: Int64; // for if there was an error
begin
// If there will be an error the DoneBytes value
// will be inconsistent, so remember it here.
OldDoneBytes := FStatistics^.DoneBytes;
aFile:= aNode.TheFile;
with FWfxPluginFileSource do
begin
with RemoteInfo do
begin
iTemp.Value := aFile.Size;
SizeLow := iTemp.Low;
SizeHigh := iTemp.High;
LastWriteTime := DateTimeToWfxFileTime(aFile.ModificationTime);
Attr := LongInt(aFile.Attributes);
end;
if (FMode = wpohmMove) then
iFlags:= iFlags + FS_COPYFLAGS_MOVE;
if FFileExistsOption = fsoofeOverwrite then
iFlags:= iFlags + FS_COPYFLAGS_OVERWRITE;
bCopyMoveIn:= (FMode = wpohmCopyIn);
Result := WfxCopyMove(aFile.Path + aFile.Name, AbsoluteTargetFileName, iFlags, @RemoteInfo, FInternal, bCopyMoveIn);
case Result of
FS_FILE_EXISTS, // The file already exists, and resume isn't supported
FS_FILE_EXISTSRESUMEALLOWED: // The file already exists, and resume is supported
begin
case FileExists(aFile, AbsoluteTargetFileName, Result = FS_FILE_EXISTSRESUMEALLOWED) of
fsoofeSkip:
Exit(FS_FILE_OK);
fsoofeOverwrite:
iFlags:= iFlags + FS_COPYFLAGS_OVERWRITE;
fsoofeResume:
iFlags:= iFlags + FS_COPYFLAGS_RESUME;
else
raise Exception.Create('Invalid file exists option');
end;
Result := WfxCopyMove(aFile.Path + aFile.Name, AbsoluteTargetFileName, iFlags, @RemoteInfo, FInternal, bCopyMoveIn);
end;
end;
end;
with FStatistics^ do
begin
if Result = FS_FILE_OK then DoneFiles := DoneFiles + 1;
DoneBytes := OldDoneBytes + aFile.Size;
UpdateStatistics(FStatistics^);
end;
end;
procedure TWfxPluginOperationHelper.QuestionActionHandler(
Action: TFileSourceOperationUIAction);
begin
if Action = fsouaCompare then
begin
if Assigned(FCurrentTargetFile) then
ShowCompareFilesUIByFileObject(FCurrentFile, FCurrentTargetFile)
else
ShowCompareFilesUI(FCurrentFile, FCurrentTargetFilePath);
end;
end;
function FileExistsMessage(TargetFile: TFile; SourceFile: TFile): String;
begin
Result:= rsMsgFileExistsOverwrite + LineEnding + TargetFile.FullPath + LineEnding +
Format(rsMsgFileExistsFileInfo, [Numb2USA(IntToStr(TargetFile.Size)), DateTimeToStr(TargetFile.ModificationTime)]) + LineEnding;
Result:= Result + LineEnding + rsMsgFileExistsWithFile + LineEnding + SourceFile.FullPath + LineEnding +
Format(rsMsgFileExistsFileInfo, [Numb2USA(IntToStr(SourceFile.Size)), DateTimeToStr(SourceFile.ModificationTime)]);
end;
function TWfxPluginOperationHelper.FileExists(aFile: TFile;
AbsoluteTargetFileName: String; AllowResume: Boolean
): TFileSourceOperationOptionFileExists;
const
Responses: array[0..6] of TFileSourceOperationUIResponse
= (fsourOverwrite, fsourSkip, fsourResume, fsourOverwriteAll, fsourSkipAll,
fsouaCompare, fsourCancel);
ResponsesNoResume: array[0..5] of TFileSourceOperationUIResponse
= (fsourOverwrite, fsourSkip, fsourOverwriteAll, fsourSkipAll, fsouaCompare,
fsourCancel);
var
Message: String;
PossibleResponses: TFileSourceOperationUIResponses;
begin
case FFileExistsOption of
fsoofeNone:
try
FCurrentTargetFile := nil;
case AllowResume of
True : PossibleResponses := Responses;
False: PossibleResponses := ResponsesNoResume;
end;
if FMode = wpohmCopyOut then
Message := uFileSystemUtil.FileExistsMessage(AbsoluteTargetFileName, aFile.FullPath, aFile.Size, aFile.ModificationTime)
else if FWfxPluginFileSource.FillSingleFile(AbsoluteTargetFileName, FCurrentTargetFile) then
Message := FileExistsMessage(FCurrentTargetFile, aFile)
else
Message := Format(rsMsgFileExistsRwrt, [AbsoluteTargetFileName]);
FCurrentFile := aFile;
FCurrentTargetFilePath := AbsoluteTargetFileName;
case AskQuestion(Message, '',
PossibleResponses, fsourOverwrite, fsourSkip,
@QuestionActionHandler) of
fsourOverwrite:
Result := fsoofeOverwrite;
fsourSkip:
Result := fsoofeSkip;
fsourResume:
begin
// FFileExistsOption := fsoofeResume; - for ResumeAll
Result := fsoofeResume;
end;
fsourOverwriteAll:
begin
FFileExistsOption := fsoofeOverwrite;
Result := fsoofeOverwrite;
end;
fsourSkipAll:
begin
FFileExistsOption := fsoofeSkip;
Result := fsoofeSkip;
end;
fsourNone,
fsourCancel:
AbortOperation;
end;
finally
FreeAndNil(FCurrentTargetFile);
end;
else
Result := FFileExistsOption;
end;
end;
procedure TWfxPluginOperationHelper.CopyProperties(SourceFile: TFile;
const TargetFileName: String);
var
WfxFileTime: TWfxFileTime;
begin
if caoCopyTime in FCopyAttributesOptions then
begin
if (FMode = wpohmCopyOut) then
begin
if SourceFile.ModificationTimeProperty.IsValid then
mbFileSetTime(TargetFileName, DateTimeToFileTime(SourceFile.ModificationTime));
end
else begin
WfxFileTime := DateTimeToWfxFileTime(SourceFile.ModificationTime);
FWfxPluginFileSource.WfxModule.WfxSetTime(TargetFileName, nil, nil, @WfxFileTime);
end;
end;
end;
procedure TWfxPluginOperationHelper.CountStatistics(aNode: TFileTreeNode);
procedure CountNodeStatistics(aNode: TFileTreeNode);
var
aFileAttrs: TFileAttributesProperty;
i: Integer;
begin
aFileAttrs := aNode.TheFile.AttributesProperty;
with FStatistics^ do
begin
if aFileAttrs.IsDirectory then
begin
// No statistics for directory.
// Go through subdirectories.
for i := 0 to aNode.SubNodesCount - 1 do
CountNodeStatistics(aNode.SubNodes[i]);
end
else if aFileAttrs.IsLink then
begin
// Count only not-followed links.
if aNode.SubNodesCount = 0 then
DoneFiles := DoneFiles + 1
else
// Count target of link.
CountNodeStatistics(aNode.SubNodes[0]);
end
else
begin
// Count files.
DoneFiles := DoneFiles + 1;
DoneBytes := DoneBytes + aNode.TheFile.Size;
end;
end;
end;
begin
CountNodeStatistics(aNode);
UpdateStatistics(FStatistics^);
end;
constructor TWfxPluginOperationHelper.Create(FileSource: IFileSource;
AskQuestionFunction: TAskQuestionFunction;
AbortOperationFunction: TAbortOperationFunction;
CheckOperationStateFunction: TCheckOperationStateFunction;
UpdateStatisticsFunction: TUpdateStatisticsFunction;
ShowCompareFilesUIFunction: TShowCompareFilesUIFunction;
ShowCompareFilesUIByFileObjectFunction: TShowCompareFilesUIByFileObjectFunction;
OperationThread: TThread;
Mode: TWfxPluginOperationHelperMode;
TargetPath: String
);
begin
FWfxPluginFileSource:= FileSource as IWfxPluginFileSource;
AskQuestion := AskQuestionFunction;
AbortOperation := AbortOperationFunction;
CheckOperationState := CheckOperationStateFunction;
UpdateStatistics := UpdateStatisticsFunction;
ShowCompareFilesUI := ShowCompareFilesUIFunction;
ShowCompareFilesUIByFileObject := ShowCompareFilesUIByFileObjectFunction;
FOperationThread:= OperationThread;
FMode := Mode;
FInternal:= (FMode in [wpohmCopy, wpohmMove]);
FFileExistsOption := fsoofeNone;
FRootTargetPath := TargetPath;
FRenameMask := '';
FRenamingFiles := False;
FRenamingRootDir := False;
inherited Create;
end;
destructor TWfxPluginOperationHelper.Destroy;
begin
inherited Destroy;
end;
procedure TWfxPluginOperationHelper.Initialize;
begin
case FMode of
wpohmCopy,
wpohmCopyIn,
wpohmCopyOut:
FLogCaption := rsMsgLogCopy;
wpohmMove:
FLogCaption := rsMsgLogMove;
end;
SplitFileMask(FRenameMask, FRenameNameMask, FRenameExtMask);
end;
procedure TWfxPluginOperationHelper.ProcessTree(aFileTree: TFileTree;
var Statistics: TFileSourceCopyOperationStatistics);
var
aFile: TFile;
begin
FRenamingFiles := (FRenameMask <> '*.*') and (FRenameMask <> '');
// If there is a single root dir and rename mask doesn't have wildcards
// treat is as a rename of the root dir.
if (aFileTree.SubNodesCount = 1) and FRenamingFiles then
begin
aFile := aFileTree.SubNodes[0].TheFile;
if (aFile.IsDirectory or aFile.IsLinkToDirectory) and
not ContainsWildcards(FRenameMask) then
begin
FRenamingFiles := False;
FRenamingRootDir := True;
FRootDir := aFile;
end;
end;
FStatistics:= @Statistics;
ProcessNode(aFileTree, FRootTargetPath);
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Objekt.TapiData;
type
TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
fTapiData: TTapiData;
procedure TapiAction(aValue: string);
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{
procedure TForm1.Button1Click(Sender: TObject);
var
aCopyData: TCopyDataStruct;
hTargetWnd: HWND;
begin
with aCopyData do
begin
dwData := 0;
cbData := StrLen(PChar(Edit1.Text)) + 1;
lpData := PChar(Edit1.Text)
end;
// Search window by the window title
// Fenster anhand des Titelzeilentext suchen
//hTargetWnd := FindWindowEx(0, 0, nil, PChar('Tfrm_Prg2'));
hTargetWnd := FindWindow('Tfrm_Prg2', nil);
if hTargetWnd <> 0 then
SendMessage(hTargetWnd, WM_COPYDATA, Longint(Handle), Longint(@aCopyData))
else
ShowMessage('No Recipient found!');
end;
}
procedure TForm1.Button1Click(Sender: TObject);
var
CopyData: TCopyDataStruct;
hTargetWnd: HWND;
s: UTF8String;
begin
//hTargetWnd := FindWindow('TPrg2CopyData', nil);
// hTargetWnd := FindWindow('Tfrm_Prg2', nil);
hTargetWnd := FindWindow('TFrmMain', nil);
if hTargetWnd = 0 then
begin
ShowMessage('No Recipient found!');
exit;
end;
fTapiData.Init;
fTapiData.Befehl := '1';
fTapiData.KU_ID := 33927;
//s := UTF8String(Edit1.Text);
s := UTF8String(fTapiData.getValue);
CopyData.dwData := 1;
CopyData.cbData := Length(s) * SizeOf(AnsiChar);
CopyData.lpData := PAnsiChar(s);
SendMessage(hTargetWnd, WM_COPYDATA, WPARAM(Handle), LPARAM(@CopyData));
end;
procedure TForm1.Button2Click(Sender: TObject);
var
s: string;
begin
s := 'Befehl=1'+sLineBreak+'KU_ID=4711'+sLineBreak;
TapiAction(s);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
fTapiData := TTapiData.Create;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FreeAndNil(fTapiData);
end;
procedure TForm1.TapiAction(aValue: string);
begin
fTapiData.setValue(aValue);
if fTapiData.Befehl = '1' then
caption := IntToStr(fTapiData.KU_ID);
end;
end.
|
unit uDlgAddress;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uBASE_DialogForm, Menus, cxLookAndFeelPainters, StdCtrls,
cxButtons, cxClasses, dxRibbon, cxControls, ExtCtrls, cxGraphics,
cxSpinEdit, cxTextEdit, cxContainer, cxEdit, cxMaskEdit, cxDropDownEdit,
cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, DB, ADODB, cxStyles,
cxCustomData, cxFilter, cxData, cxDataStorage, cxDBData,
cxDBExtLookupComboBox, cxGridLevel, cxGridDBTableView,
cxGridCustomTableView, cxGridTableView, cxGridBandedTableView,
cxGridDBBandedTableView, cxGridCustomView, cxGrid, cxDBEdit;
type
TdlgAddress = class(TBASE_DialogForm)
teHouse: TcxTextEdit;
teCorpus: TcxTextEdit;
teLiter: TcxTextEdit;
seFlat: TcxSpinEdit;
seIndex: TcxSpinEdit;
dsStreets: TDataSource;
qryStreets: TADOQuery;
Label30: TLabel;
Label31: TLabel;
Label32: TLabel;
Label33: TLabel;
Label34: TLabel;
Label35: TLabel;
Label36: TLabel;
Label49: TLabel;
Label23: TLabel;
teSettlement: TcxDBTextEdit;
teStreetType: TcxDBTextEdit;
teRegion: TcxDBTextEdit;
grdStreets: TcxGrid;
gvStreets: TcxGridDBBandedTableView;
colPK: TcxGridDBBandedColumn;
gvStreetsForADOInsertCol: TcxGridDBBandedColumn;
gvStreets_1: TcxGridDBBandedColumn;
colStreet: TcxGridDBBandedColumn;
gvStreetsDBBandedColumn: TcxGridDBBandedColumn;
gvStreetsDBBandedColumn1: TcxGridDBBandedColumn;
gvStreetsDBBandedColumn2: TcxGridDBBandedColumn;
gvStreetsDBBandedColumn3: TcxGridDBBandedColumn;
gvStreetsDBBandedColumn4: TcxGridDBBandedColumn;
gvStreetsDBBandedColumn5: TcxGridDBBandedColumn;
gvStreetsDBBandedColumn6: TcxGridDBBandedColumn;
glStreets: TcxGridLevel;
lcStreet: TcxExtLookupComboBox;
procedure FormCreate(Sender: TObject);
procedure lcStreetPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
private
function GetCorpus: variant;
function GetFlat: variant;
function GetHouse: variant;
function GetLiter: variant;
function GetRegion: variant;
function GetSettlement: variant;
function GetStreet: variant;
function GetStreetID: variant;
procedure SetCorpus(const Value: variant);
procedure SetFlat(const Value: variant);
procedure SetHouse(const Value: variant);
procedure SetLiter(const Value: variant);
procedure SetStreetID(const Value: variant);
function GetStreetType: variant;
function GetStreetTypeID: variant;
function GetIndex: variant;
procedure SetIndex(const Value: variant);
{ Private declarations }
public
property Region: variant read GetRegion;
property Settlement: variant read GetSettlement;
property StreetTypeID: variant read GetStreetTypeID;
property StreetType: variant read GetStreetType;
property StreetID: variant read GetStreetID write SetStreetID;
property Street: variant read GetStreet;
property Index: variant read GetIndex write SetIndex;
property House: variant read GetHouse write SetHouse;
property Corpus: variant read GetCorpus write SetCorpus;
property Liter: variant read GetLiter write SetLiter;
property Flat: variant read GetFlat write SetFlat;
end;
var
dlgAddress: TdlgAddress;
implementation
uses uMain, uAccess, uParams, uFrmStreet, uCommonUtils;
{$R *.dfm}
{ TdlgAddress }
function TdlgAddress.GetCorpus: variant;
begin
result:=teCorpus.Text;
end;
function TdlgAddress.GetFlat: variant;
begin
result:=seFlat.Value;
end;
function TdlgAddress.GetHouse: variant;
begin
result:=teHouse.Text;
end;
function TdlgAddress.GetLiter: variant;
begin
result:=teLiter.Text;
end;
function TdlgAddress.GetRegion: variant;
begin
result:=teRegion.Text;
end;
function TdlgAddress.GetSettlement: variant;
begin
result:=teSettlement.Text;
end;
function TdlgAddress.GetStreet: variant;
begin
result:=lcStreet.Text;
end;
function TdlgAddress.GetStreetID: variant;
begin
result:=qryStreets['Улица.код_Улица'];
end;
procedure TdlgAddress.SetCorpus(const Value: variant);
begin
if not VarIsNullMy(Value) then
teCorpus.Text:=Value;
end;
procedure TdlgAddress.SetFlat(const Value: variant);
begin
if not VarIsNullMy(Value) then
seFlat.Value:=Value;
end;
procedure TdlgAddress.SetHouse(const Value: variant);
begin
if not VarIsNullMy(Value) then
teHouse.Text:=Value;
end;
procedure TdlgAddress.SetLiter(const Value: variant);
begin
if not VarIsNullMy(Value) then
teLiter.Text:=Value;
end;
procedure TdlgAddress.SetStreetID(const Value: variant);
begin
if not VarIsNullMy(Value) then
lcStreet.EditValue:=Value;
end;
procedure TdlgAddress.FormCreate(Sender: TObject);
begin
inherited;
qryStreets.Open;
end;
function TdlgAddress.GetStreetType: variant;
begin
result:=teStreetType.Text;
end;
function TdlgAddress.GetStreetTypeID: variant;
begin
result:=qryStreets['Улица.Тип'];
end;
function TdlgAddress.GetIndex: variant;
begin
result:=seIndex.Value;
end;
procedure TdlgAddress.SetIndex(const Value: variant);
begin
if not VarIsNullMy(Value) then
seIndex.Value:=Value;
end;
procedure TdlgAddress.lcStreetPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
a: TAccessSelectorForm;
p: TParamCollection;
begin
inherited;
if AButtonIndex=1 then begin
qryStreets.First;
lcStreet.Text:='';
end;
if AButtonIndex=2 then begin
a:=TAccessSelectorForm.Create;
a.ObjectID:=52;
a.FormClass:=TfrmStreet;
p:=TParamCollection.Create(TParamItem);
try
p.Add('код_Улица');
p.Add('Нас. пункт');
p.Add('Тип улицы');
p.Add('Улица');
p['код_Улица'].Value:=qryStreets['Улица.код_Улица'];
if a.ShowModal(p, null)<>mrOK then exit;
qryStreets.Locate('Улица.код_Улица', p['код_Улица'].Value, []);
lcStreet.Text:=p['Улица'].Value;
finally
p.Free;
end;
end;
end;
end.
|
namespace proholz.xsdparser;
interface
type
XsdSimpleContentVisitor = public class(XsdAnnotatedElementsVisitor)
private
// *
// * The {@link XsdSimpleContent} instance which owns this {@link XsdSimpleContentVisitor} instance. This way this
// * visitor instance can perform changes in the {@link XsdSimpleContent} object.
//
//
var owner: XsdSimpleContent;
public
constructor(aowner: XsdSimpleContent);
method visit(element: XsdRestriction); override;
method visit(element: XsdExtension); override;
end;
implementation
constructor XsdSimpleContentVisitor(aowner: XsdSimpleContent);
begin
inherited constructor(aowner);
self.owner := aowner;
end;
method XsdSimpleContentVisitor.visit(element: XsdRestriction);
begin
inherited visit(element);
owner.setRestriction(ReferenceBase.createFromXsd(element));
end;
method XsdSimpleContentVisitor.visit(element: XsdExtension);
begin
inherited visit(element);
owner.setExtension(ReferenceBase.createFromXsd(element));
end;
end. |
unit TwoDPointOrderList;
interface
uses TwoDPointQueue;
type
P2DPointOrderItem = ^C2DPointOrderItem;
C2DPointOrderItem = record
Value: integer;
Edges: C2DPointQueue;
Next: P2DPointOrderItem;
end;
C2DPointOrderList = class
private
Start,Active : P2DPointOrderItem;
procedure Reset;
public
// Constructors and Destructors
constructor Create;
destructor Destroy; override;
// Add
procedure Add (Value,x,y : integer);
procedure Delete;
// Delete
procedure Clear;
// Gets
function GetPosition (var x,y : integer): boolean;
function GetX: integer;
function GetY: integer;
function IsEmpty: boolean;
function IsActive(var _List: P2DPointOrderItem; var _Elem: P2DPosition): boolean;
procedure GetFirstElement(var _List: P2DPointOrderItem; var _Elem: P2DPosition);
procedure GetNextElement(var _List: P2DPointOrderItem; var _Elem: P2DPosition);
procedure GetActive(var _List: P2DPointOrderItem; var _Elem: P2DPosition);
// Misc
procedure GoToNextElement;
procedure GoToFirstElement;
end;
implementation
constructor C2DPointOrderList.Create;
begin
Reset;
end;
destructor C2DPointOrderList.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure C2DPointOrderList.Reset;
begin
Start := nil;
Active := nil;
end;
// Add
procedure C2DPointOrderList.Add (Value,x,y : integer);
var
PreviousPosition,CurrentPosition: P2DPointOrderItem;
NewPosition : P2DPointOrderItem;
LeaveLoop: boolean;
begin
LeaveLoop := false;
CurrentPosition := Start;
PreviousPosition := nil;
while (CurrentPosition <> nil) and (not LeaveLoop) do
begin
if Value < CurrentPosition^.Value then
begin
LeaveLoop := true;
end
else if Value = CurrentPosition^.Value then
begin
CurrentPosition^.Edges.Add(x,y);
exit;
end
else
begin
PreviousPosition := CurrentPosition;
CurrentPosition := CurrentPosition^.Next;
end;
end;
New(NewPosition);
NewPosition^.Edges := C2DPointQueue.Create;
NewPosition^.Edges.Add(x,y);
NewPosition^.Value := Value;
if Start <> nil then
begin
if PreviousPosition <> nil then
begin
NewPosition^.Next := PreviousPosition^.Next;
PreviousPosition^.Next := NewPosition;
end
else
begin
NewPosition^.Next := Start;
Start := NewPosition;
Active := Start;
end;
end
else
begin
Start := NewPosition;
NewPosition^.Next := nil;
Active := Start;
end;
end;
// Delete
procedure C2DPointOrderList.Delete;
var
Previous : P2DPointOrderItem;
begin
if Active <> nil then
begin
Active^.Edges.Delete;
if Active^.Edges.IsEmpty then
begin
Previous := Start;
if Active = Start then
begin
Start := Start^.Next;
Previous := Start;
end
else
begin
while Previous^.Next <> Active do
begin
Previous := Previous^.Next;
end;
Previous^.Next := Active^.Next;
end;
Active^.Edges.Free;
Dispose(Active);
Active := Previous;
end;
end;
end;
procedure C2DPointOrderList.Clear;
var
Garbage : P2DPointOrderItem;
begin
Active := Start;
while Active <> nil do
begin
Garbage := Active;
Active := Active^.Next;
Garbage^.Edges.Free;
dispose(Garbage);
end;
end;
// Gets
function C2DPointOrderList.GetPosition (var x,y : integer): boolean;
begin
if Active <> nil then
begin
Active^.Edges.GetPosition(x,y);
Result := true;
end
else
begin
Result := false;
end;
end;
function C2DPointOrderList.GetX: integer;
begin
Result := 0;
if Active <> nil then
begin
Result := Active^.Edges.GetX;
end;
end;
function C2DPointOrderList.GetY: integer;
begin
Result := 0;
if Active <> nil then
begin
Result := Active^.Edges.GetY;
end;
end;
function C2DPointOrderList.IsEmpty: boolean;
begin
Result := (Start = nil);
end;
function C2DPointOrderList.IsActive(var _List: P2DPointOrderItem; var _Elem: P2DPosition): boolean;
begin
Result := false;
if _List = Active then
begin
Result := _List^.Edges.IsActive(_Elem);
end;
end;
procedure C2DPointOrderList.GetFirstElement(var _List: P2DPointOrderItem; var _Elem: P2DPosition);
begin
_List := Start;
if _List <> nil then
begin
_Elem := _List^.Edges.GetFirstElement;
end;
end;
procedure C2DPointOrderList.GetNextElement(var _List: P2DPointOrderItem; var _Elem: P2DPosition);
begin
if _List <> nil then
begin
_List^.Edges.GetNextElement(_Elem);
if _Elem = nil then
begin
_List := _List^.Next;
if _List <> nil then
begin
_Elem := _List^.Edges.GetFirstElement;
end
else
begin
_Elem := nil;
end;
end;
end
else
begin
_Elem := nil;
end;
end;
procedure C2DPointOrderList.GetActive(var _List: P2DPointOrderItem; var _Elem: P2DPosition);
begin
_List := Active;
if _List <> nil then
begin
_Elem := _List^.Edges.GetActive;
end;
end;
// Misc
procedure C2DPointOrderList.GoToNextElement;
begin
if Active <> nil then
begin
if Active^.Edges.IsEndOfQueue then
begin
Active := Active^.Next;
end
else
begin
Active^.Edges.GoToNextElement;
end;
end
end;
procedure C2DPointOrderList.GoToFirstElement;
begin
Active := Start;
while Active <> nil do
begin
Active^.Edges.GoToFirstElement;
Active := Active^.Next;
end;
Active := Start;
end;
end.
|
{$apptype console}
{$product Biker 2 Installer}
{$company Kotov Projects}
{$copyright Alexandr Kotov}
{$resource 'interface.dat'}
{$resource 'help.dat'}
{$resource 'map.dat'}
{$resource 'items.dat'}
{$resource 'quest.dat'}
{$resource 'shop.dat'}
{$resource 'mapview.exe'}
{$resource 'game.exe'}
{$resource 'bike.dat'}
{$resource 'map.png'}
{$resource 'version.dat'}
uses System;
const
version: record Major, Minor, Build: integer; end = (Major: 0; Minor: 9; Build: 35);
LANGS = 2;
type
LANG = (RUS, ENG);
function IntToLang(a: integer): LANG := LANG(a);
function LangToInt(a: LANG): integer := Ord(a);
procedure Change(var a: boolean);
begin
if a then a:=false
else a:=true;
end;
procedure Resource(ResName, Outputfilename: string);
begin
var f := System.IO.File.Create(Outputfilename);
GetResourceStream(ResName).CopyTo(f);
f.Flush;
f.Close;
end;
var
CurrentLang: LANG = RUS;
Res: array of string = Arr(
'game.exe',
'mapview.exe',
'map.dat',
'interface.dat',
'bike.dat',
'shop.dat',
'items.dat',
'quest.dat',
'help.dat',//8 0
'map.png',//9 1
'version.dat'//10 2
);
License: array[LANG] of string =(
#10'[RUS]'
#10'--- Лицензионное соглашение ---'
#10''
#10'Что можно:'
#10' - Использовать'
#10' - Распространять под изначальным именем с указанием автора и следующих ссылок:'
#10' vk.com/id219453333 (Александр Котов)'
#10' vk.com/ktvprj (Kotov Projects)'
#10' Электронной почты kotov.tv20012@gmail.com',
#10'[ENG]'
#10'--- License agreement ---'
#10''
#10'What can:'
#10' - Use'
#10' - Distribute under the original name with the author and the links:'
#10' vk.com/id219453333 (Alexandr Kotov)'
#10' vk.com/ktvprj (Kotov Projects)'
#10' E-mail kotov.tv20012@gmail.com');
IFace: array[LANG] of array of string =(
('RUS',
'Мастер установки Biker 2',
'Версия',
'Да','Нет',//3,4
'Установить',
'Лицензия',
'Отмена',
'Параметры установки',
'Установить справку по игре',
'Карта мира (.png)',
'Список обновлений'
),
('ENG',
'Biker 2 Installer',
'Version',
'Yes','No',//3,4
'Install',
'License',
'Cancel',
'Installation settings',
'Install more information on the game',
'World Map (.png)',
'Update list'
)
);
begin
var status: boolean = true;
var arr:= new boolean[3];
arr[0]:=true;
arr[1]:=true;
arr[2]:=false;
Console.BackgroundColor:=consolecolor.White;
Console.ForegroundColor:=consolecolor.Black;
Console.SetWindowSize(1,1);
Console.SetBufferSize(100,30);
Console.SetWindowSize(100,30);
while status do
begin
var YES := IFace[CurrentLang][3];
var NO := IFace[CurrentLang][4];
if Console.Title<>IFace[CurrentLang][1] then Console.Title:=IFace[CurrentLang][1];
if ((Console.WindowWidth<>100) or (Console.WindowHeight<>30)) then
begin
Console.Clear;
if (console.WindowHeight>30) or (console.WindowWidth>100) then Console.SetWindowSize(1,1);
Console.SetBufferSize(100,30);
Console.SetWindowSize(100,30);
end;
Console.Clear;
var aaa: string = $'(-) {IFace[CurrentLang][0]}';
Console.SetCursorPosition(99-aaa.Length,29);write(aaa);
Console.SetCursorPosition(1,1);write('Biker 2 (',IFace[CurrentLang][2],' ',Version.Major,'.',Version.Minor,'.',Version.Build,')');
Console.SetCursorPosition(1,3);write('(1) ',IFace[CurrentLang][5]);
Console.SetCursorPosition(1,4);write('(2) ',IFace[CurrentLang][6]);
Console.SetCursorPosition(1,5);write('(0) ',IFace[CurrentLang][7]);
Console.SetCursorPosition(48,1);write(IFace[CurrentLang][8],': ');
Console.SetCursorPosition(50,2);write('(-1) ',IFace[CurrentLang][9],': ');
if arr[0] then
begin
Console.ForegroundColor:=ConsoleColor.DarkGreen;
write(YES);
Console.ForegroundColor:=ConsoleColor.Black;
end
else
begin
Console.ForegroundColor:=ConsoleColor.Red;
write(NO);
Console.ForegroundColor:=ConsoleColor.Black;
end;
Console.SetCursorPosition(50,3);write('(-2) ',IFace[CurrentLang][10],': ');
if arr[1] then
begin
Console.ForegroundColor:=ConsoleColor.DarkGreen;
write(YES);
Console.ForegroundColor:=ConsoleColor.Black;
end
else
begin
Console.ForegroundColor:=ConsoleColor.Red;
write(NO);
Console.ForegroundColor:=ConsoleColor.Black;
end;
Console.SetCursorPosition(50,4);write('(-3) ',IFace[CurrentLang][11],': ');
if arr[2] then
begin
Console.ForegroundColor:=ConsoleColor.DarkGreen;
write(YES);
Console.ForegroundColor:=ConsoleColor.Black;
end
else
begin
Console.ForegroundColor:=ConsoleColor.Red;
write(NO);
Console.ForegroundColor:=ConsoleColor.Black;
end;
var input: string = '';
while (input='') and ((Console.WindowWidth=100) and (Console.WindowHeight=30)) do
begin
Console.SetCursorPosition(1,28);write(': ');
input:=ReadLnString;
end;
if input='-1' then Change(arr[0]);
if input='-2' then Change(arr[1]);
if input='-3' then Change(arr[2]);
if input='-' then
begin
CurrentLang:=(IntToLang(LangToInt(CurrentLang)+1));
if LangToInt(CurrentLang)>=Langs then CurrentLang:=IntToLang(0);
end;
if input='0' then status:=false;
if input='2' then
begin
Console.Clear;write(License[CurrentLang]);Console.CursorVisible:=false;
Console.ReadKey;;Console.CursorVisible:=true;
end;
if input.ToLower='1' then
begin
MkDir('Biker 2');
for var i:=0 to Res.Length-1 do
begin
if (not ((i=8) and (not arr[0])))
and (not ((i=9) and (not arr[1])))
and (not ((i=10) and (not arr[2]))) then
begin
Resource(Res[i],string.Format('Biker 2\{0}',Res[i]));
end;
end;
//end;
status:=false;
end;
end;
end. |
unit uNeClasses;
{*******************************************************************************
* *
* Название модуля : *
* *
* uNeClasses *
* *
* Назначение модуля : *
* *
* Библиотека классов общего назначения. *
* *
* Copyright © Дата создания: 04.05.07, Автор: Найдёнов Е.А *
* *
*******************************************************************************}
interface
uses Windows, Messages, SysUtils, RxMemDS, uCommonSp, uNeTypes;
type
{ *** Назначение: реализация абстрактных методов для универсальной работы с параметрами *** }
TNeSprav = class(TSprav)
private
procedure SetFldDefs ( const aSource: TRxMemoryData; aFieldDefs: TArr_FieldDefs );
procedure SetFieldDefs ( const aTypeParam: TEnm_TypeParam; const aParams: TRec_Params );
public
constructor Create( const aTypeParam: TEnm_TypeParam; const aParams: TRec_Params ); reintroduce;
procedure Show; reintroduce; virtual;
end;
implementation
uses Variants;
{ TNeSprav }
constructor TNeSprav.Create( const aTypeParam: TEnm_TypeParam; const aParams: TRec_Params );
begin
inherited Create;
SetFieldDefs( aTypeParam, aParams );
PrepareMemoryDataSets;
end;
procedure TNeSprav.SetFldDefs( const aSource: TRxMemoryData; aFieldDefs: TArr_FieldDefs );
var
i, n : Integer;
begin
if aFieldDefs <> nil
then begin
i := Low ( aFieldDefs );
n := High( aFieldDefs );
for i := i to n
do
with aFieldDefs[i]
do begin
aSource.FieldDefs.Add( FName, FType );
end;
end
else begin
raise Exception.Create( sEEmptyParamListUA + sEFldValIsNullUA );
end;
end;
procedure TNeSprav.SetFieldDefs(const aTypeParam: TEnm_TypeParam; const aParams: TRec_Params );
begin
case aTypeParam of
tpInput : begin
SetFldDefs( Input, aParams.FInParams );
end;
tpOutput : begin
SetFldDefs( Output, aParams.FOutParams );
end;
tpInputOutput : begin
SetFldDefs( Input, aParams.FInParams );
SetFldDefs( Output, aParams.FOutParams );
end;
end;
end;
procedure TNeSprav.Show;
begin
inherited;
//Проверяем корректность идентификатора соединения с БД
if Input.FindField( sPN_IN_DBHandle ) <> nil
then begin
if not VarIsNull( Input[sPN_IN_DBHandle] )
then begin
if Input[sPN_IN_DBHandle] = 0
then begin
raise Exception.Create( sEDBHandleZeroUA );
end;
end
else begin
raise Exception.Create( sEFieldUA + sPN_IN_DBHandle + sEFldValIsNullUA );
end;
end
else begin
raise Exception.Create( sEFieldUA + sPN_IN_DBHandle + sENotFoundUA );
end;
end;
end.
|
unit Pospolite.View.Drawing.Drawer;
{
+-------------------------+
| Package: Pospolite View |
| Author: Matek0611 |
| Email: matiowo@wp.pl |
| Version: 1.0p |
+-------------------------+
Comments:
...
}
{$mode objfpc}{$H+}
{$modeswitch advancedrecords}
interface
uses
Classes, SysUtils, Graphics, math, Pospolite.View.Basics,
Pospolite.View.Drawing.Basics;
type
IPLDrawingMatrix = interface;
IPLDrawingBrush = interface;
IPLDrawingPen = interface;
IPLDrawingPath = interface;
IPLDrawingRenderer = interface;
{ IPLDrawingMatrix }
IPLDrawingMatrix = interface(specialize IPLCloneable<IPLDrawingMatrix>)
['{194299D0-683F-46F2-9D87-DE2F0F7DEAE1}']
procedure Multiply(AMatrix: IPLDrawingMatrix);
procedure Scale(AX, AY: TPLFloat);
procedure Translate(AX, AY: TPLFloat);
function Transform(AP: TPLPointF): TPLPointF;
procedure Identify;
procedure Rotate(ARad: TPLFloat);
end;
operator * (a, b: IPLDrawingMatrix) r: IPLDrawingMatrix;
type
{ IPLDrawingBrush }
IPLDrawingBrush = interface
['{B4608CAC-2938-40C8-9653-CF3C3753AD58}']
function GetAlpha: Byte;
function GetMatrix: IPLDrawingMatrix;
procedure SetAlpha(AValue: Byte);
procedure SetMatrix(AValue: IPLDrawingMatrix);
property Alpha: Byte read GetAlpha write SetAlpha;
property Matrix: IPLDrawingMatrix read GetMatrix write SetMatrix;
end;
{ IPLDrawingBrushSolid }
IPLDrawingBrushSolid = interface(IPLDrawingBrush)
['{2B10E8A4-059C-40C4-8E40-FE7DB5E9A127}']
function GetColor: TPLColor;
procedure SetColor(AValue: TPLColor);
property Color: TPLColor read GetColor write SetColor;
end;
{ IPLDrawingBrushBitmap }
IPLDrawingBrushBitmap = interface(IPLDrawingBrush)
['{D03694C0-EA34-4B94-BE3A-5FC2D376FF1D}']
end;
TPLDrawingBrushGradientWrap = (dbgwClamp, dbgwWrap, dbgwMirror);
{ IPLDrawingBrushGradient }
IPLDrawingBrushGradient = interface(IPLDrawingBrush)
['{967EFB69-F638-4554-A75A-715DE97FF520}']
function GetWrap: TPLDrawingBrushGradientWrap;
procedure SetWrap(AValue: TPLDrawingBrushGradientWrap);
procedure AddStop(AColor: TPLColor; AOffset: TPLFloat);
property Wrap: TPLDrawingBrushGradientWrap read GetWrap write SetWrap;
end;
{ IPLDrawingBrushGradientLinear }
IPLDrawingBrushGradientLinear = interface(IPLDrawingBrushGradient)
['{9764B12F-E95C-4DD6-A2FF-8B589C8B5CA7}']
end;
{ IPLDrawingBrushGradientRadial }
IPLDrawingBrushGradientRadial = interface(IPLDrawingBrushGradient)
['{3273762C-3985-48CF-906C-BB9DFBFCD694}']
end;
TPLDrawingPenStyle = (dpsSolid, dpsDash, dpsDot, dpsDashDot, dpsDashDotDot,
dpsCustom);
TPLDrawingPenEndCap = (dpecFlat, dpecSquare, dpecRound, dpecTriangle);
TPLDrawingPenJoinStyle = (dpjsMitter, dpjsBevel, dpjsRound);
{ IPLDrawingPen }
IPLDrawingPen = interface
['{C2562BD8-4609-4DAA-8CEC-A72DE109CC03}']
function GetBrush: IPLDrawingBrush;
function GetColor: TPLColor;
function GetEndCap: TPLDrawingPenEndCap;
function GetJoinStyle: TPLDrawingPenJoinStyle;
function GetMiterLimit: TPLFloat;
function GetStyle: TPLDrawingPenStyle;
function GetStyleOffset: TPLFloat;
function GetWidth: TPLFloat;
procedure SetBrush(AValue: IPLDrawingBrush);
procedure SetColor(AValue: TPLColor);
procedure SetEndCap(AValue: TPLDrawingPenEndCap);
procedure SetJoinStyle(AValue: TPLDrawingPenJoinStyle);
procedure SetMiterLimit(AValue: TPLFloat);
procedure SetStyle(AValue: TPLDrawingPenStyle);
procedure SetStyleOffset(AValue: TPLFloat);
procedure SetWidth(AValue: TPLFloat);
property Color: TPLColor read GetColor write SetColor;
property Width: TPLFloat read GetWidth write SetWidth;
property Brush: IPLDrawingBrush read GetBrush write SetBrush;
property Style: TPLDrawingPenStyle read GetStyle write SetStyle;
property EndCap: TPLDrawingPenEndCap read GetEndCap write SetEndCap;
property JoinStyle: TPLDrawingPenJoinStyle read GetJoinStyle write SetJoinStyle;
property StyleOffset: TPLFloat read GetStyleOffset write SetStyleOffset;
property MiterLimit: TPLFloat read GetMiterLimit write SetMiterLimit;
end;
TPLDrawingFontWeight = (dfw100, dfw200, dfw300, dfw400, dfw500, dfw600, dfw700,
dfw800, dfw900, dfwNormal = dfw400, dfwBold = dfw700);
TPLDrawingFontStyle = (dfsNormal, dfsItalic, dfsOblique);
TPLDrawingFontStretch = (dfstUltraCondensed, dfstExtraCondensed, dfstCondensed,
dfstSemiCondensed, dfstNormal, dfstSemiExpanded, dfstExpanded, dfstExtraExpanded,
dfstUltraExpanded);
TPLDrawingFontDecoration = (dfdUnderline, dfdLineThrough, dfdOverline);
TPLDrawingFontDecorations = set of TPLDrawingFontDecoration;
TPLDrawingFontVariantTag = (dfvtCapsSmall, dfvtCapsAllSmall, dfvtCapsPetite,
dfvtCapsAllPetite, dfvtCapsTitling, dfvtUnicase, dfvtKerningNone, dfvtEastAsianRuby,
dfvtEastAsianJIS78, dfvtEastAsianJIS83, dfvtEastAsianJIS90, dfvtEastAsianJIS04,
dfvtEastAsianSimplified, dfvtEastAsianTraditional, dfvtEastAsianFullWidth,
dfvtEastAsianProportionalWidth, dfvtLigaturesNone, dfvtLigaturesCommon,
dfvtLigaturesNoCommon, dfvtLigaturesDiscretionary, dfvtLigaturesNoDiscretionary,
dfvtLigaturesHistorical, dfvtLigaturesNoHistorical, dfvtLigaturesContextual,
dfvtLigaturesNoContextual, dfvtNumericOrdinal, dfvtNumericSlashedZero,
dfvtNumericLiningNums, dfvtNumericOldstyleNums, dfvtNumericProportionalNums,
dfvtNumericTabularNums, dfvtNumericDiagonalFractions, dfvtNumericStackedFractions);
TPLDrawingFontVariantTags = set of TPLDrawingFontVariantTag;
{ IPLDrawingFont }
IPLDrawingFont = interface
['{6F45CBA7-F20E-4C5E-BA07-1BE5243A74D7}']
function GetColor: TPLColor;
function GetDecoration: TPLDrawingFontDecorations;
function GetName: TPLString;
function GetQuality: TFontQuality;
function GetSize: TPLFloat;
function GetStretch: TPLDrawingFontStretch;
function GetStyle: TPLDrawingFontStyle;
function GetVariantTags: TPLDrawingFontVariantTags;
function GetWeight: TPLDrawingFontWeight;
procedure SetColor(AValue: TPLColor);
procedure SetDecoration(AValue: TPLDrawingFontDecorations);
procedure SetName(AValue: TPLString);
procedure SetQuality(AValue: TFontQuality);
procedure SetSize(AValue: TPLFloat);
procedure SetStretch(AValue: TPLDrawingFontStretch);
procedure SetStyle(AValue: TPLDrawingFontStyle);
procedure SetVariantTags(AValue: TPLDrawingFontVariantTags);
procedure SetWeight(AValue: TPLDrawingFontWeight);
property Name: TPLString read GetName write SetName;
property Color: TPLColor read GetColor write SetColor;
property Quality: TFontQuality read GetQuality write SetQuality;
property Size: TPLFloat read GetSize write SetSize;
property Weight: TPLDrawingFontWeight read GetWeight write SetWeight;
property Style: TPLDrawingFontStyle read GetStyle write SetStyle;
property Stretch: TPLDrawingFontStretch read GetStretch write SetStretch;
property Decoration: TPLDrawingFontDecorations read GetDecoration write SetDecoration;
property VariantTags: TPLDrawingFontVariantTags read GetVariantTags write SetVariantTags;
end;
{ TPLDrawingFontData }
TPLDrawingFontData = packed record
public
Name: TPLString;
Color: TPLColor;
Quality: TFontQuality;
Size: TPLFloat;
Weight: TPLDrawingFontWeight;
Style: TPLDrawingFontStyle;
Stretch: TPLDrawingFontStretch;
Decoration: TPLDrawingFontDecorations;
VariantTags: TPLDrawingFontVariantTags;
end;
const
PLDrawingFontDataDef: TPLDrawingFontData = (Name: 'Segoe UI';
Color: (FR: 0; FG: 0; FB: 0; FA: 255); Quality: fqCleartypeNatural;
Size: 9; Weight: dfwNormal; Style: dfsNormal; Stretch: dfstNormal;
Decoration: []; VariantTags: []);
type
{ IPLDrawingPathData }
IPLDrawingPathData = interface
['{C7C5B06B-84C8-4619-BFA0-FA47F21DCA2F}']
end;
{ IPLDrawingPath }
IPLDrawingPath = interface(specialize IPLCloneable<IPLDrawingPathData>)
['{87EEE872-D595-4380-9FED-CCB7C573569A}']
procedure Add;
procedure JoinData(APath: IPLDrawingPathData);
procedure Remove;
procedure Clip;
procedure Unclip;
end;
IPLDrawingBitmap = interface;
TPLTextDirection = (tdLeft, tdUp, tdRight, tdDown, tdCenter, tdFill, tdWrap, tdFlow);
{ TPLTextDirections }
TPLTextDirections = record
public
TextPosition, ParagraphPosition: TPLTextDirection;
public
constructor Create(const ATextPosition, AParagraphPosition: TPLTextDirection);
end;
TPLWritingMode = (wmHorizontalTB = 0, wmVerticalLR = 2, wmVerticalRL = 3);
TPLReadingDirection = (rdLTR = 0, rdRTL, rdTTB, rdBTT);
{ IPLDrawingSurface }
IPLDrawingSurface = interface
['{79AD199D-585D-4070-A039-56C1E8FA732E}']
function GetHandle: Pointer;
function GetMatrix: IPLDrawingMatrix;
function GetPath: IPLDrawingPath;
procedure SetMatrix(AValue: IPLDrawingMatrix);
procedure Save;
procedure Restore;
procedure Flush;
procedure Clear(const AColor: TPLColor);
procedure MoveTo(const AX, AY: TPLFloat);
procedure LineTo(const AX, AY: TPLFloat);
procedure ArcTo(const ARect: TPLRectF; const ABeginAngle, AEndAngle: TPLFloat);
procedure CurveTo(const AX, AY: TPLFloat; const AC1, AC2: TPLPointF);
procedure Ellipse(const ARect: TPLRectF);
procedure Rectangle(const ARect: TPLRectF);
procedure RoundRectangle(const ARect: TPLRectF; const ARadius: TPLFloat);
procedure Stroke(APen: IPLDrawingPen; const APreserve: TPLBool = false);
procedure Fill(ABrush: IPLDrawingBrush; const APreserve: TPLBool = false);
function TextSize(AFont: IPLDrawingFont; const AText: string;
const ALineSpacing: single = NaN; const AWordWrap: boolean = true;
const AWritingMode: TPLWritingMode = wmHorizontalTB;
const AReading: TPLReadingDirection = rdLTR): TPLPointF;
function TextHeight(AFont: IPLDrawingFont; const AText: string; const AWidth: TPLFloat;
const ALineSpacing: single = NaN; const AWordWrap: boolean = true;
const AWritingMode: TPLWritingMode = wmHorizontalTB;
const AReading: TPLReadingDirection = rdLTR): TPLFloat;
procedure TextOut(AFont: IPLDrawingFont; const AText: string; const ARect: TPLRectF;
const ADirection: TPLTextDirections; const ALineSpacing: single = NaN;
const AWordWrap: boolean = true; const AWritingMode: TPLWritingMode = wmHorizontalTB;
const AReading: TPLReadingDirection = rdLTR; const AImmediate: TPLBool = true);
property Handle: Pointer read GetHandle;
property Matrix: IPLDrawingMatrix read GetMatrix write SetMatrix;
property Path: IPLDrawingPath read GetPath;
end;
TPLDrawingResampleQuality = (drqLowest, drqNormal, drqBest);
TPLDrawingImageFormat = (difPng, difJpeg, difGif, difBmp, difIco, difTiff);
{ IPLDrawingBitmap }
IPLDrawingBitmap = interface(specialize IPLCloneable<IPLDrawingBitmap>)
['{7B622CB6-AF81-46C6-A85F-A406E6B7CF4E}']
function GetClientRect: TPLRectI;
function GetEmpty: TPLBool;
function GetFormat: TPLDrawingImageFormat;
function GetHeight: TPLInt;
function GetPixels: PPLPixel;
function GetSurface: IPLDrawingSurface;
function GetWidth: TPLInt;
procedure SetFormat(AValue: TPLDrawingImageFormat);
procedure LoadFromFile(const AFileName: TPLString);
procedure LoadFromStream(AStream: TStream);
procedure SaveToFile(const AFileName: TPLString);
procedure SaveToStream(AStream: TStream);
procedure Clear;
function Resample(AWidth, AHeight: TPLInt; AQuality: TPLDrawingResampleQuality = drqNormal): IPLDrawingBitmap;
procedure SetSize(AWidth, AHeight: TPLInt);
property Empty: TPLBool read GetEmpty;
property Surface: IPLDrawingSurface read GetSurface;
property ClientRect: TPLRectI read GetClientRect;
property Format: TPLDrawingImageFormat read GetFormat write SetFormat;
property Width: TPLInt read GetWidth;
property Height: TPLInt read GetHeight;
property Pixels: PPLPixel read GetPixels;
end;
{ TPLDrawingFastBitmap }
TPLDrawingFastBitmap = record
end;
{ TPLDrawingInterfacedBitmap }
TPLDrawingInterfacedBitmap = class(TInterfacedObject, IPLDrawingBitmap)
private
FWidth: Integer;
FHeight: Integer;
FFormat: TPLDrawingImageFormat;
protected
FBitmap: TPLDrawingFastBitmap;
FSurface: IPLDrawingSurface;
function HandleAvailable: Boolean; virtual;
procedure HandleRelease; virtual;
procedure Flush;
function GetClientRect: TPLRectI;
function GetEmpty: TPLBool;
function GetFormat: TPLDrawingImageFormat;
function GetHeight: TPLInt;
function GetPixels: PPLPixel; virtual;
function GetSurface: IPLDrawingSurface; virtual;
function GetWidth: TPLInt;
public
destructor Destroy; override;
procedure SetFormat(AValue: TPLDrawingImageFormat);
procedure LoadFromFile(const AFileName: TPLString);
procedure LoadFromStream(AStream: TStream);
procedure SaveToFile(const AFileName: TPLString);
procedure SaveToStream(AStream: TStream);
procedure Clear; virtual;
function Resample(AWidth, AHeight: TPLInt; AQuality: TPLDrawingResampleQuality = drqNormal): IPLDrawingBitmap;
procedure SetSize(AWidth, AHeight: TPLInt);
function Clone: IPLDrawingBitmap;
property Empty: TPLBool read GetEmpty;
property Surface: IPLDrawingSurface read GetSurface;
property ClientRect: TPLRectI read GetClientRect;
property Format: TPLDrawingImageFormat read GetFormat write SetFormat;
property Width: TPLInt read GetWidth;
property Height: TPLInt read GetHeight;
property Pixels: PPLPixel read GetPixels;
end;
// https://developer.mozilla.org/en-US/docs/Web/CSS/border-style
TPLDrawingBorderStyle = (dbsNone, dbsHidden = dbsNone, dbsDotted, dbsDashed,
dbsSolid, dbsDouble, dbsGroove, dbsRidge, dbsInset, dbsOutset);
{ TPLDrawingBorder }
TPLDrawingBorder = packed record
public
Width: TPLFloat;
Color: TPLColor;
Style: TPLDrawingBorderStyle;
constructor Create(const AWidth: TPLFloat; const AColor: TPLColor;
const AStyle: TPLDrawingBorderStyle);
end;
{ TPLDrawingBorders }
TPLDrawingBorders = packed record
public type
TPLBorderRadiusData = array[1..4] of TPLFloat;
public
Left, Top, Right, Bottom: TPLDrawingBorder;
Radius: TPLBorderRadiusData; // 1 - top-left, 2 - top-right, 3 - bottom-left, 4 - bottom-right
Image: IPLDrawingBrush;
constructor Create(const ALeft, ATop, ARight, ABottom: TPLDrawingBorder;
ARadius: TPLBorderRadiusData; const AImage: IPLDrawingBrush = nil);
function AverageBorderSize: TPLFloat;
end;
operator := (a: TPLString) r: TPLDrawingBorderStyle;
function PLDrawingBordersDef: TPLDrawingBorders;
function PLDrawingBordersOutlineDef: TPLDrawingBorders;
function PLDrawingBordersRadiusData(b1, b2, b3, b4: TPLFloat): TPLDrawingBorders.TPLBorderRadiusData;
type
{ IPLDrawingRenderer }
IPLDrawingRenderer = interface
['{0F99114C-4A69-43EB-A80C-3D5A247E2620}']
function GetCanvas: TCanvas;
function GetSurface: IPLDrawingSurface;
procedure DrawObjectFully(const AObject: TPLHTMLObject; const ADebug: boolean = false);
procedure DrawObjectBackground(const AObject: TPLHTMLObject);
procedure DrawObjectBorder(const AObject: TPLHTMLObject);
procedure DrawObjectOutline(const AObject: TPLHTMLObject);
procedure DrawObjectOutlineText(const AObject: TPLHTMLObject);
procedure DrawObjectText(const AObject: TPLHTMLObject);
procedure DrawObjectDebug(const AObject: TPLHTMLObject);
procedure DrawObjectShadow(const AObject: TPLHTMLObject);
procedure DrawObjectTextShadow(const AObject: TPLHTMLObject);
procedure DrawObjectPseudoBefore(const AObject: TPLHTMLObject);
procedure DrawObjectPseudoAfter(const AObject: TPLHTMLObject);
procedure DrawFrame(const ABorders: TPLDrawingBorders; const ARect: TPLRectF);
property Canvas: TCanvas read GetCanvas;
property Surface: IPLDrawingSurface read GetSurface;
end;
{ TPLAbstractDrawer }
TPLAbstractDrawer = class(TInterfacedObject, IPLDrawingRenderer)
private
function GetCanvas: TCanvas;
function GetSurface: IPLDrawingSurface;
protected
FCanvas: TCanvas;
FSurface: IPLDrawingSurface;
public
constructor Create(ACanvas: TCanvas); virtual;
procedure DrawObjectBackground(const AObject: TPLHTMLObject); virtual;
procedure DrawObjectBorder(const AObject: TPLHTMLObject); virtual;
procedure DrawObjectDebug(const AObject: TPLHTMLObject); virtual;
procedure DrawObjectFully(const AObject: TPLHTMLObject; const ADebug: boolean = false);
procedure DrawObjectOutline(const AObject: TPLHTMLObject); virtual;
procedure DrawObjectOutlineText(const AObject: TPLHTMLObject); virtual;
procedure DrawObjectPseudoAfter(const AObject: TPLHTMLObject); virtual;
procedure DrawObjectPseudoBefore(const AObject: TPLHTMLObject); virtual;
procedure DrawObjectShadow(const AObject: TPLHTMLObject); virtual;
procedure DrawObjectText(const AObject: TPLHTMLObject); virtual;
procedure DrawObjectTextShadow(const AObject: TPLHTMLObject); virtual;
procedure DrawFrame(const ABorders: TPLDrawingBorders; const ARect: TPLRectF); virtual;
property Canvas: TCanvas read GetCanvas;
property Surface: IPLDrawingSurface read GetSurface;
end;
implementation
operator * (a, b: IPLDrawingMatrix) r: IPLDrawingMatrix;
begin
r := a;
r.Multiply(b);
end;
{ TPLTextDirections }
constructor TPLTextDirections.Create(const ATextPosition,
AParagraphPosition: TPLTextDirection);
begin
TextPosition := ATextPosition;
ParagraphPosition := AParagraphPosition;
end;
operator := (a: TPLString) r: TPLDrawingBorderStyle;
begin
case a.Trim.ToLower of
'none': r := dbsNone;
'dashed': r := dbsDashed;
'dotted': r := dbsDotted;
'double': r := dbsDouble;
'groove': r := dbsGroove;
'hidden': r := dbsHidden;
'inset': r := dbsInset;
'outset': r := dbsOutset;
'ridge': r := dbsRidge;
'solid': r := dbsSolid;
else r := dbsNone;
end;
end;
function PLDrawingBordersDef: TPLDrawingBorders;
var
b: TPLDrawingBorder;
begin
b := TPLDrawingBorder.Create(1, TPLColor.Black, dbsSolid);
Result := TPLDrawingBorders.Create(b, b, b, b, PLDrawingBordersRadiusData(0, 0, 0, 0));
end;
function PLDrawingBordersOutlineDef: TPLDrawingBorders;
var
b: TPLDrawingBorder;
begin
b := TPLDrawingBorder.Create(3, TPLColor.Transparent, dbsNone);
Result := TPLDrawingBorders.Create(b, b, b, b, PLDrawingBordersRadiusData(0, 0, 0, 0));
end;
function PLDrawingBordersRadiusData(b1, b2, b3, b4: TPLFloat
): TPLDrawingBorders.TPLBorderRadiusData;
begin
Result[1] := b1;
Result[2] := b2;
Result[3] := b3;
Result[4] := b4;
end;
{ TPLDrawingBorder }
constructor TPLDrawingBorder.Create(const AWidth: TPLFloat;
const AColor: TPLColor; const AStyle: TPLDrawingBorderStyle);
begin
Width := AWidth;
Color := AColor;
Style := AStyle;
end;
{ TPLDrawingBorders }
constructor TPLDrawingBorders.Create(const ALeft, ATop, ARight,
ABottom: TPLDrawingBorder; ARadius: TPLBorderRadiusData;
const AImage: IPLDrawingBrush);
begin
Left := ALeft;
Top := ATop;
Right := ARight;
Bottom := ABottom;
Radius := ARadius;
Image := AImage;
end;
function TPLDrawingBorders.AverageBorderSize: TPLFloat;
begin
Result := (Left.Width + Top.Width + Right.Width + Bottom.Width) / 4;
end;
{ TPLDrawingInterfacedBitmap }
function TPLDrawingInterfacedBitmap.HandleAvailable: Boolean;
begin
end;
procedure TPLDrawingInterfacedBitmap.HandleRelease;
begin
end;
procedure TPLDrawingInterfacedBitmap.Flush;
begin
end;
function TPLDrawingInterfacedBitmap.GetClientRect: TPLRectI;
begin
end;
function TPLDrawingInterfacedBitmap.GetEmpty: TPLBool;
begin
end;
function TPLDrawingInterfacedBitmap.GetFormat: TPLDrawingImageFormat;
begin
end;
function TPLDrawingInterfacedBitmap.GetHeight: TPLInt;
begin
end;
function TPLDrawingInterfacedBitmap.GetPixels: PPLPixel;
begin
end;
function TPLDrawingInterfacedBitmap.GetSurface: IPLDrawingSurface;
begin
end;
function TPLDrawingInterfacedBitmap.GetWidth: TPLInt;
begin
end;
destructor TPLDrawingInterfacedBitmap.Destroy;
begin
inherited Destroy;
end;
procedure TPLDrawingInterfacedBitmap.SetFormat(AValue: TPLDrawingImageFormat);
begin
end;
procedure TPLDrawingInterfacedBitmap.LoadFromFile(const AFileName: TPLString);
begin
end;
procedure TPLDrawingInterfacedBitmap.LoadFromStream(AStream: TStream);
begin
end;
procedure TPLDrawingInterfacedBitmap.SaveToFile(const AFileName: TPLString);
begin
end;
procedure TPLDrawingInterfacedBitmap.SaveToStream(AStream: TStream);
begin
end;
procedure TPLDrawingInterfacedBitmap.Clear;
begin
end;
function TPLDrawingInterfacedBitmap.Resample(AWidth, AHeight: TPLInt;
AQuality: TPLDrawingResampleQuality): IPLDrawingBitmap;
begin
end;
procedure TPLDrawingInterfacedBitmap.SetSize(AWidth, AHeight: TPLInt);
begin
end;
function TPLDrawingInterfacedBitmap.Clone: IPLDrawingBitmap;
begin
end;
{ TPLAbstractDrawer }
function TPLAbstractDrawer.GetCanvas: TCanvas;
begin
Result := FCanvas;
end;
function TPLAbstractDrawer.GetSurface: IPLDrawingSurface;
begin
Result := FSurface;
end;
constructor TPLAbstractDrawer.Create(ACanvas: TCanvas);
begin
inherited Create;
FCanvas := ACanvas;
end;
procedure TPLAbstractDrawer.DrawObjectBackground(const AObject: TPLHTMLObject);
begin
if not Assigned(AObject) then exit;
end;
procedure TPLAbstractDrawer.DrawObjectBorder(const AObject: TPLHTMLObject);
begin
if not Assigned(AObject) then exit;
end;
procedure TPLAbstractDrawer.DrawObjectDebug(const AObject: TPLHTMLObject);
begin
if not Assigned(AObject) then exit;
end;
procedure TPLAbstractDrawer.DrawObjectFully(const AObject: TPLHTMLObject;
const ADebug: boolean);
begin
if not Assigned(AObject) then exit;
DrawObjectShadow(AObject);
DrawObjectBackground(AObject);
DrawObjectBorder(AObject);
DrawObjectOutline(AObject);
DrawObjectTextShadow(AObject);
DrawObjectOutlineText(AObject);
DrawObjectText(AObject);
DrawObjectPseudoBefore(AObject);
DrawObjectPseudoAfter(AObject);
if ADebug then DrawObjectDebug(AObject);
end;
procedure TPLAbstractDrawer.DrawObjectOutline(const AObject: TPLHTMLObject);
begin
if not Assigned(AObject) then exit;
end;
procedure TPLAbstractDrawer.DrawObjectOutlineText(const AObject: TPLHTMLObject);
begin
if not Assigned(AObject) then exit;
end;
procedure TPLAbstractDrawer.DrawObjectPseudoAfter(const AObject: TPLHTMLObject);
begin
if not Assigned(AObject) then exit;
end;
procedure TPLAbstractDrawer.DrawObjectPseudoBefore(const AObject: TPLHTMLObject
);
begin
if not Assigned(AObject) then exit;
end;
procedure TPLAbstractDrawer.DrawObjectShadow(const AObject: TPLHTMLObject);
begin
if not Assigned(AObject) then exit;
end;
procedure TPLAbstractDrawer.DrawObjectText(const AObject: TPLHTMLObject);
begin
if not Assigned(AObject) then exit;
end;
procedure TPLAbstractDrawer.DrawObjectTextShadow(const AObject: TPLHTMLObject);
begin
if not Assigned(AObject) then exit;
end;
procedure TPLAbstractDrawer.DrawFrame(const ABorders: TPLDrawingBorders;
const ARect: TPLRectF);
begin
//
end;
end.
|
unit settings;
interface
procedure LoadSettings(
out ADirectory: string;
out AFilter: string;
out AItemIndex: integer;
out AFontHeight: integer
);
procedure SaveSettings(
const ADirectory: string;
const AFilter: string;
const AItemIndex: integer;
const AFontHeight: integer
);
implementation
uses
SysUtils, IniFiles;
var
LIniFileName: TFileName;
procedure LoadSettings(
out ADirectory: string;
out AFilter: string;
out AItemIndex: integer;
out AFontHeight: integer
);
begin
with TIniFile.Create(LIniFileName) do
try
ADirectory := ReadString('.', 'directory', '');
AFilter := ReadString('.', 'filter', '');
AItemIndex := ReadInteger('.', 'itemindex', -1);
AFontHeight := ReadInteger('.', 'fontheight', 13);
finally
Free;
end;
end;
procedure SaveSettings(
const ADirectory: string;
const AFilter: string;
const AItemIndex: integer;
const AFontHeight: integer
);
begin
with TIniFile.Create(LIniFileName) do
try
WriteString('.', 'directory', ADirectory);
WriteString('.', 'filter', AFilter);
WriteInteger('.', 'itemindex', AItemIndex);
WriteInteger('.', 'fontheight', AFontHeight);
UpdateFile;
finally
Free;
end;
end;
begin
LIniFileName := ChangeFileExt(ParamStr(0), '.ini');
end.
|
unit MainExport;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ExtCtrls, cxLookAndFeelPainters, cxControls,
cxContainer, cxEdit, cxLabel, StdCtrls, cxButtons, DB, RxMemDS,
IniFiles, Halcn6db, FIBQuery, pFIBQuery, pFIBStoredProc, FIBDatabase,
pFIBDatabase,pFIBDataSet, Gauges, IBase, cn_Common_Types, cn_Common_Funcs;
type
TfrmMainForm = class(TForm)
StatusBar1: TStatusBar;
Timer: TTimer;
cxButton1: TcxButton;
cxLabelIniFile: TcxLabel;
OpenDialogIni: TOpenDialog;
RxMemoryDataSection: TRxMemoryData;
Section: TComboBox;
GroupBox1: TGroupBox;
MemoLog: TMemo;
cxButton2: TcxButton;
DBIbx: TpFIBDatabase;
FIBTrans: TpFIBTransaction;
FIBSProc: TpFIBStoredProc;
HTable: THalcyonDataSet;
bar: TGauge;
GaugeAll: TGauge;
Label1: TLabel;
Label2: TLabel;
procedure cxButton1Click(Sender: TObject);
procedure cxButton2Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure TimerTimer(Sender: TObject);
private
procedure RunSP(SecName:String);
procedure RunDBF(SecName:String);
constructor Create(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE);reintroduce;
{ Private declarations }
public
{ Public declarations }
end;
function ShowImport(AParameter:TcnSimpleParams):Variant;stdcall;
exports ShowImport;
var
frmMainForm: TfrmMainForm;
TimeS:TTime;
res:Variant;
implementation
{$R *.dfm}
function ShowImport(AParameter:TcnSimpleParams):Variant;stdcall;
var ViewForm:TfrmMainForm;
begin
if AParameter.Formstyle = fsMDIChild then
if IsMDIChildFormShow(TfrmMainForm) then exit;
ViewForm := TfrmMainForm.Create(AParameter.Owner, AParameter.Db_Handle);
ViewForm.FormStyle:= AParameter.Formstyle;
case ViewForm.FormStyle of
fsNormal, fsStayOnTop : ViewForm.ShowModal;
fsMDIChild : ViewForm.Show;
else begin
ViewForm.ShowModal;
ViewForm.free;
end;
end;
Result:=res;
end;
constructor TfrmMainForm.Create(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE);
begin
Screen.Cursor:=crHourGlass;
inherited Create(AOwner);
DBIbx.Handle:=DB_Handle;
Screen.Cursor:=crDefault;
end;
procedure TfrmMainForm.cxButton1Click(Sender: TObject);
begin
{ OpenDialogIni.Execute;
if OpenDialogIni.FileName<>'' then
begin
cxLabelIniFile.Caption:=OpenDialogIni.FileName;
end;}
end;
procedure TfrmMainForm.cxButton2Click(Sender: TObject);
var
i:Integer;
Ini:TiniFile;
prevSection:String;
begin
MemoLog.Clear;
//начинаем подготовку к забору данных
MemoLog.Lines.Add(TimeToStr(Now));
MemoLog.Lines.Add('Начинаем подготовку к забору данных.Формирование списка таблиц и процедур.');
Section.Items.Clear;
ini:=TIniFile.Create(ExtractFilePath(Application.ExeName)+'\Contracts\DBF.ini');
OpenDialogIni.FileName:= ExtractFilePath(Application.ExeName)+'\Contracts\DBF.ini';
ini.ReadSections(Section.Items);
RxMemoryDataSection.EmptyTable;
GaugeAll.MaxValue:=Section.Items.Count;
for i:=0 to Section.Items.Count-1 do
begin
RxMemoryDataSection.Open;
RxMemoryDataSection.Insert;
RxMemoryDataSection.FieldByName('RxSection').Value:=Section.Items[i];
RxMemoryDataSection.Post;
end;
MemoLog.Lines.Add('Подготовка завершена.');
//Начинаем анализировать секции и запускаем затем соответствующие функции
RxMemoryDataSection.Last;
Timer.Enabled:=true;
TimeS:=Now;
prevSection:='';
for i:=0 to RxMemoryDataSection.RecordCount-1 do
begin
if RxMemoryDataSection.FieldByName('RxSection').AsString=prevSection+'SP' then
begin
RunSP(RxMemoryDataSection.FieldByName('RxSection').AsString);
end
else
begin
RunDBF(RxMemoryDataSection.FieldByName('RxSection').AsString);
end;
prevSection:=RxMemoryDataSection.FieldByName('RxSection').AsString;
GaugeAll.Progress:=i+1;
RxMemoryDataSection.Prior;
end;
end;
procedure TfrmMainForm.RunSP(SecName:String);
var
My_file:TINIFile;
Server_name:string;
PathServ:string;
SPName:string;
SPCount,i:Integer;
begin
bar.Progress:=0;
if FileExists(OpenDialogIni.FileName)
then begin
try
My_file:=TIniFile.Create(ExtractFilePath(Application.ExeName)+'\Contracts\DBF.ini');
MemoLog.Lines.Add('Обработка секции '+SecName);
// Server_name:= My_file.ReadString(SecName,'Server_Name','ERROR');
except
MemoLog.Lines.Add('Непривильная структура файла конфигурации');
ShowMessage('Непривильная структура файла конфигурации');
Refresh;
Application.Terminate;
end;
try
// MemoLog.Lines.Add(server_name);
// DBIbx.DatabaseName:=server_name;
// DBIbx.Connected:=true;
FIBTrans.StartTransaction;
FIBSProc.StoredProcName:=SPName;
except
MemoLog.Lines.Add('Невозможно установить соединение.'+#13+'Проверьте правильность настроек доступа к данным');
Refresh;
messageBox(0,PChar('Невозможно установить соединение.'+#13+'Проверьте правильность настроек доступа к данным'),'Ошибка доступа к данным',MB_OK);
Exit;
end;
end
else begin
MemoLog.Lines.Add('Невозможно установить соединение.'+#13+'Не найден файл инициализации.');
Refresh;
messageBox(0,PChar('Невозможно установить соединение.'+#13+'Не найден файл инициализации.'),'Ошибка доступа к данным',MB_OK);
Exit;
end;
SPCount:= StrToInt(My_file.ReadString(SecName,'SPCount','ERROR'));
for i:=1 to SPCount do
begin
SPName:=My_file.ReadString(SecName,'ProcNAME'+IntToStr(i),'ERROR');
MemoLog.Lines.Add('Выполнение процедуры '+SPName);
FIBSProc.Database:=DBIbx;
FIBSProc.Transaction:=FIBTrans;
FIBTrans.StartTransaction;
FIBSProc.StoredProcName:=SPName;
FIBSProc.Prepare;
try
FIBSProc.ExecProc;
Except
begin
FIBTrans.Rollback;
ShowMessage('dbf Файл пустой');
Exit;
end;
end;
FIBTrans.Commit;
end;
end;
procedure TfrmMainForm.RunDBF(SecName:String);
var
My_file:TINIFile;
Server_name:string;
PathDBF:string;
PathServ:string;
SPName,sp_delete:string;
i, pcount, j, rcount:integer;
max_kod_seup:Integer;
select:TpFIBDataSet;
TFields : array of string;
TFieldsSP : array of string;
begin
if FileExists(OpenDialogIni.FileName)
then begin
try
My_file:=TIniFile.Create(ExtractFilePath(Application.ExeName)+'\Contracts\DBF.ini');
PathDBF:= My_file.ReadString(SecName,'PathDBF','ERROR');
MemoLog.Lines.Add('Обработка секции '+SecName);
HTable.Active:=false;
MemoLog.Lines.Add(PathDBF);
HTable.TableName:=PathDBF;
HTable.IndexFiles.Clear;
// Server_name:= My_file.ReadString(SecName,'Server_Name','ERROR');
SPName:=My_file.ReadString(SecName,'ProcNAME','ERROR');
sp_delete:=My_file.ReadString(SecName,'SPDelete','ERROR');
except
MemoLog.Lines.Add('Непривильная структура файла конфигурации');
ShowMessage('Непривильная структура файла конфигурации');
exit;
end;
try
// MemoLog.Lines.Add(server_name);
// DBIbx.DatabaseName:=server_name;
// DBIbx.Connected:=true;
FIBTrans.StartTransaction;
FIBSProc.StoredProcName:=SPName;
except
MemoLog.Lines.Add('Невозможно установить соединение.'+#13+'Проверьте правильность настроек доступа к данным');
messageBox(0,PChar('Невозможно установить соединение.'+#13+'Проверьте правильность настроек доступа к данным'),'Ошибка доступа к данным',MB_OK);
Exit;
end;
end
else begin
MemoLog.Lines.Add('Невозможно установить соединение.'+#13+'Не найден файл инициализации.');
messageBox(0,PChar('Невозможно установить соединение.'+#13+'Не найден файл инициализации.'),'Ошибка доступа к данным',MB_OK);
Exit;
end;
try
HTable.Active:=true;
HTable.Append;
HTable.IndexFileInclude(My_file.ReadString(SecName,'CDX','ERROR'));
Except
begin
MemoLog.Lines.Add('dbf файл заблокированым другим пользователем');
HTable.Active:=false;
ShowMessage('dbf файл заблокированым другим пользователем');
Exit;
end;
end;
if HTable.RecordCount=0 then
begin
MemoLog.Lines.Add('dbf Файл пустой');
ShowMessage('dbf Файл пустой');
Exit;
end;
pcount:=FIBSProc.ParamCount;
rcount:=HTable.RecordCount;
SetLength(TFields,pcount);
SetLength(TFieldsSP,pcount);
for i:=0 to pcount-1 do
begin
TFields[i]:=My_file.ReadString(SecName,FIBSProc.Params[i].Name,'ERROR');
TFieldsSP[i]:=FIBSProc.Params[i].Name;
end;
try
for i:=1 to pcount do
begin
HTable.FieldValues[TFields[i-1]];
end;
except
begin
MemoLog.Lines.Add('Неверная структура dbf файла');
Exit;
end;
end;
FIBSProc.Database:=DBIbx;
FIBSProc.Transaction:=FIBTrans;
FIBTrans.StartTransaction;
FIBSProc.StoredProcName:=sp_delete;
FIBSProc.Prepare;
FIBSProc.ExecProc;
FIBTrans.Commit;
MemoLog.Lines.Add('Начало экспорта данный');
HTable.First;
Bar.MaxValue:=RCount;
FIBSProc.Database:=DBIbx;
FIBSProc.Transaction:=FIBTrans;
FIBTrans.StartTransaction;
FIBSProc.StoredProcName:=SPName;
FIBSProc.Prepare;
for j:=1 to rcount do
begin
for i:=1 to pcount do
begin
if TFieldsSP[i-1]='ID_KOD' then
begin
FIBSProc.ParamByName(TFieldsSP[i-1]).AsInt64:=HTable.FieldValues[TFields[i-1]];
end
else
begin
if TFieldsSP[i-1]='TN' then
begin
FIBSProc.ParamByName(TFieldsSP[i-1]).AsInteger:=HTable.FieldValues[TFields[i-1]];
end
else
begin
if (TFieldsSP[i-1]='ID_N_NALOG') or (TFieldsSP[i-1]='ID_STAGE') or (TFieldsSP[i-1]='ID_LIST') or
(TFieldsSP[i-1]='NOM_LIST') or (TFieldsSP[i-1]='ID_KEY') or (TFieldsSP[i-1]='NUM_LIST') or (TFieldsSP[i-1]='NOM_PROP')
or (TFieldsSP[i-1]='IN_ID_DOG') or (TFieldsSP[i-1]='ID_ID_SMET') then
begin
FIBSProc.ParamByName(TFieldsSP[i-1]).AsInt64:=HTable.FieldValues[TFields[i-1]];
end
else
begin
FIBSProc.ParamByName(TFieldsSP[i-1]).Value:=HTable.FieldValues[TFields[i-1]];
end;
end;
end;
end;
try
FIBSProc.ExecProc;
Except
begin
MemoLog.Lines.Add('Ошибка при выполнении процедуры');
Refresh;
end;
end;
bar.Progress:=j;
HTable.Next;
end;
MemoLog.Lines.Add('Экспорт завершился успешно для таблицы'+SecName);
Refresh;
FIBTrans.Commit;
MemoLog.Lines.Add(DateTimeToStr(Now));
end;
procedure TfrmMainForm.FormDestroy(Sender: TObject);
begin
//MemoLog.Lines.SaveToFile(Application.ExeName+DateTimeToStr(Now)+'.log');
end;
procedure TfrmMainForm.TimerTimer(Sender: TObject);
begin
if TimeS-Now>=15000 then
begin
TimeS:=Now;
Refresh;
end;
end;
end.
|
unit FD.Compiler.Lexer;
interface
uses
// Refactor Units
RRPG.Unicode, RRPG.UTF16Glyphs, RRPG.UTF16Glyphs.UnicodeData,
System.SysUtils, System.Classes, System.Generics.Collections, System.BTree,
FD.Compiler.Lexer.Tokens, FD.Compiler.Environment, FD.Compiler.Exceptions,
System.Comparers, FD.Compiler.StateMachine;
type
TLexerCharPosInfo = packed record
LineIndex: NativeInt;
ColumnIndex: NativeInt;
end;
PLexerCharPosInfo = ^TLexerCharPosInfo;
TLexerContent = class(TObject)
private
protected
FEnvironment: TCompilerEnvironment;
FUnfoldName: String;
FAbsoluteFileName: String;
FContent: String;
FContentFirstCharPtr: PChar;
FCharsInfos: TArray<TLexerCharPosInfo>;
FCurrentCharIdx: NativeInt;
FCurrentCharIdxStack: TStack<NativeInt>;
function GetCharCount: NativeInt; virtual;
function GetCharAt(const Index: NativeInt): Char; virtual;
function GetCharPtrAt(const Index: NativeInt): PChar; virtual;
procedure SetCurrentCharIdx(const Value: NativeInt); virtual;
public
constructor Create(Environment: TCompilerEnvironment;
LogicalUnfoldName, FullPathFileName: String);
destructor Destroy; override;
procedure LoadFromBytes(Data: TBytes; Encoding: TEncoding); virtual;
procedure LoadFromBytesDiscoverEncoding(Data: TBytes); virtual;
procedure LoadFromStream(const Stream: TStream; Encoding: TEncoding); virtual;
procedure LoadFromStreamDiscoverEncoding(const Stream: TStream); virtual;
function Current(const DeltaOffset: NativeInt = 0): Char; inline;
function Next(const DeltaOffset: NativeInt = 1): Char; inline;
function Previous(const DeltaOffset: NativeInt = -1): Char; inline;
procedure PushCurrentCharIdx(const NewIndex: NativeInt);
procedure PopCurrentCharIdx;
function CreateFileRange(const StartCharIndex, CharCount: NativeInt): TFileRange; virtual;
function SubString(const StartCharIndex, CharCount: NativeInt): String; overload; virtual;
function SubString(const Range: TFileRange): String; overload; virtual;
property Environment: TCompilerEnvironment read FEnvironment;
property UnfoldName: String read FUnfoldName;
property AbsoluteFileName: String read FAbsoluteFileName;
property CurrentCharIdx: NativeInt read FCurrentCharIdx write SetCurrentCharIdx;
property CharCount: NativeInt read GetCharCount;
property CharAt[const Index: NativeInt]: Char read GetCharAt;
property CharPtrAt[const Index: NativeInt]: PChar read GetCharPtrAt;
end;
TBlockType = Integer;
TKeyword = String;
TTokenStateData = record
TokenType: TTokenType;
ErrorMessage: String;
procedure Initialize;
class function Create(const TokenType: TTokenType): TTokenStateData; overload; static;
class function Create(const TokenType: TTokenType; const ErrorMsg: String): TTokenStateData; overload; static;
class operator Implicit(const V: TTokenType): TTokenStateData;
class operator Implicit(const V: TTokenStateData): TTokenType;
end;
TTokenState = TState<Char, TTokenStateData>;
TLexerRules = class(TObject)
public
const
BLOCKTYPE_MAIN = 0;
type
TBlockRules = class(TObject)
protected
FKeywords: TArvoreBSet<TKeyword>;
public
constructor Create(const IsCaseSensitive: Boolean);
destructor Destroy; override;
end;
protected
FIsCaseSensitive: Boolean;
FBlockTypes: TDictionary<TBlockType, TBlockRules>;
FTokenStateMachine: TStateMachine<Char, TTokenStateData>;
FFormatSettings: TFormatSettings;
public
constructor Create;
destructor Destroy; override;
procedure AssignParsedValueForToken(var Token: TToken); virtual;
procedure AddBlockType(BlockType: TBlockType);
procedure AddKeyword(const Value: TKeyword); overload;
procedure AddKeyword(BlockType: TBlockType; const Value: TKeyword); overload;
function IsKeyword(const CurrentBlockType: TBlockType; const Value: TKeyword): Boolean;
property IsCaseSensitive: Boolean read FIsCaseSensitive write FIsCaseSensitive;
property TokenStateMachine: TStateMachine<Char, TTokenStateData> read FTokenStateMachine;
end;
(* TLexer is an abstract class that purposes is to interpret correctly
the "compiler directives"/"Lexer directives" like
- {$DEFINE} from pascal
- #ifdef from C
This class is abstract. See FD.Compiler.Lexer.Pascal.pas
*)
TLexer = class abstract(TObject)
private
protected
FEnvironment: TCompilerEnvironment;
FContentStack: TStack<TLexerContent>;
FContent: TLexerContent;
FRules: TLexerRules;
FCurrentBlockType: TBlockType;
function InstanciateRules: TLexerRules; virtual;
procedure DisposeRules(const Rules: TLexerRules); virtual;
function OpenLexerContent(const FileName: String): TLexerContent;
function CreateCodeLocation(const GlyphStartIndex, GlyphCount: Integer): TCodeLocation; virtual;
function GetEOF: Boolean; virtual;
public
constructor Create(Environment: TCompilerEnvironment); virtual;
destructor Destroy; override;
procedure AfterConstruction; override;
function GetNextToken: TToken; virtual;
procedure OpenFile(const FileName: String);
property Environment: TCompilerEnvironment read FEnvironment;
property CurrentBlockType: TBlockType read FCurrentBlockType write FCurrentBlockType;
property EOF: Boolean read GetEOF;
end;
implementation
{ TLexer }
procedure TLexer.AfterConstruction;
begin
inherited;
FRules := Self.InstanciateRules();
Assert(FRules <> nil);
end;
constructor TLexer.Create(Environment: TCompilerEnvironment);
begin
FEnvironment := Environment;
Assert(FEnvironment <> nil);
FContentStack := TStack<TLexerContent>.Create;
FCurrentBlockType := TLexerRules.BLOCKTYPE_MAIN;
end;
function TLexer.CreateCodeLocation(const GlyphStartIndex,
GlyphCount: Integer): TCodeLocation;
begin
Assert(FContent <> nil);
Result.Initialize;
Result.RealLocation := FContent.CreateFileRange(GlyphStartIndex, GlyphCount);
end;
destructor TLexer.Destroy;
var
SubContent: TLexerContent;
begin
if FContent <> nil then
begin
FContent.DisposeOf;
FContent := nil;
end;
if FContentStack <> nil then
begin
while FContentStack.Count > 0 do
begin
SubContent := FContentStack.Pop;
SubContent.DisposeOf;
end;
FContentStack.DisposeOf;
FContentStack := nil;
end;
if FRules <> nil then
begin
Self.DisposeRules(FRules);
FRules := nil;
end;
inherited;
end;
procedure TLexer.DisposeRules(const Rules: TLexerRules);
begin
Rules.DisposeOf;
end;
function TLexer.GetEOF: Boolean;
begin
Result := FContent.CurrentCharIdx >= FContent.CharCount;
end;
function TLexer.GetNextToken: TToken;
var
CurrentMachineState, NextMachineState, LastFinalMachineStateFound: TTokenState;
i, FirstGlyphIndex, LastFinalMachineStateFoundGlyphIndex: NativeInt;
C: Char;
CurrentCharPtr: PChar;
TokenStateData: TTokenStateData;
begin
Assert(FContent <> nil);
if FContent.CurrentCharIdx >= FContent.CharCount then
begin
Result := TToken.CreateEOF(Self.CreateCodeLocation(FContent.CurrentCharIdx, 0));
Exit;
end;
Assert(FRules <> nil);
Assert(FRules.FTokenStateMachine <> nil);
CurrentMachineState := FRules.FTokenStateMachine.InitialState;
Assert(CurrentMachineState <> nil);
Assert(not CurrentMachineState.IsFinal);
LastFinalMachineStateFound := nil;
LastFinalMachineStateFoundGlyphIndex := -1;
FirstGlyphIndex := FContent.CurrentCharIdx;
i := FirstGlyphIndex;
CurrentCharPtr := FContent.CharPtrAt[FirstGlyphIndex];
while i < FContent.CharCount do
begin
C := CurrentCharPtr^;
NextMachineState := nil;
if CurrentMachineState.TryLocateNextState(C, NextMachineState) then
begin
Assert(NextMachineState <> nil);
CurrentMachineState := NextMachineState;
if CurrentMachineState.IsFinal then
begin
LastFinalMachineStateFound := CurrentMachineState;
LastFinalMachineStateFoundGlyphIndex := i;
end;
end else
Break;
Inc(i);
Inc(CurrentCharPtr);
end;
if (LastFinalMachineStateFound <> nil) then
begin
Assert(LastFinalMachineStateFoundGlyphIndex >= FirstGlyphIndex);
TokenStateData := LastFinalMachineStateFound.Data;
Result.Initialize;
Result.TokenType := TokenStateData.TokenType;
Result.Location := Self.CreateCodeLocation(FirstGlyphIndex, LastFinalMachineStateFoundGlyphIndex - FirstGlyphIndex + 1);
if FRules.IsCaseSensitive then
Include(Result.Flags, TTokenFlag.tfCaseSensitive);
if TokenStateData.ErrorMessage <> '' then
begin
Assert(Result.TokenType = ttMalformedToken);
Result.MalformedDescription := TokenStateData.ErrorMessage;
end;
end else
begin
Result.Initialize;
Result.TokenType := ttUnknown;
Result.Location := Self.CreateCodeLocation(FirstGlyphIndex, 1);
end;
if Result.TokenType <> ttWhiteSpace then
begin
Result.InputString := FContent.SubString(Result.Location.RealLocation);
if (Result.TokenType = ttIdentifier) and (FRules.IsKeyword(FCurrentBlockType, Result.InputString)) then
Result.TokenType := ttKeyword;
FRules.AssignParsedValueForToken(Result);
end;
FContent.CurrentCharIdx := Result.Location.RealLocation.UTF16CharStartIndex + Result.Location.RealLocation.UTF16CharCount;
end;
function TLexer.InstanciateRules: TLexerRules;
begin
Result := TLexerRules.Create;
end;
procedure TLexer.OpenFile(const FileName: String);
begin
Assert(FContentStack <> nil);
Assert(FContentStack.Count = 0);
Assert(FContent = nil);
FContent := Self.OpenLexerContent(FileName);
Assert(FContent <> nil);
end;
function TLexer.OpenLexerContent(const FileName: String): TLexerContent;
var
Stream: TStream;
AbsoluteFileName: String;
begin
Stream := FEnvironment.OpenFileForRead(FileName);
try
if not FEnvironment.ExpandFileName(FileName, AbsoluteFileName) then
AbsoluteFileName := FileName;
Result := TLexerContent.Create(FEnvironment, ExtractFileName(FileName), AbsoluteFileName);
try
Result.LoadFromStreamDiscoverEncoding(Stream);
except
Result.Free;
raise;
end;
finally
Stream.Free;
end;
end;
constructor TLexerContent.Create(Environment: TCompilerEnvironment;
LogicalUnfoldName, FullPathFileName: String);
begin
FEnvironment := Environment;
FUnfoldName := LogicalUnfoldName;
FAbsoluteFileName := FullPathFileName;
FCurrentCharIdxStack := TStack<NativeInt>.Create;
end;
function TLexerContent.CreateFileRange(const StartCharIndex,
CharCount: NativeInt): TFileRange;
var
CharInfo: PLexerCharPosInfo;
begin
Assert((StartCharIndex >= 0) and (StartCharIndex <= Length(FContent)));
Result.Initialize;
Result.FileName := Self.AbsoluteFileName;
if StartCharIndex = Length(FContent) then
begin
Assert(CharCount = 0);
Result.UTF16CharStartIndex := Length(FContent);
Result.UTF16CharCount := 0;
if Length(FCharsInfos) > 0 then
begin
CharInfo := @FCharsInfos[Length(FCharsInfos) - 1];
Result.LineIndex := CharInfo.LineIndex;
Result.ColumnIndex := CharInfo.ColumnIndex;
end else
begin
Result.LineIndex := 0;
Result.ColumnIndex := 0;
end;
end else
begin
Assert(StartCharIndex + CharCount <= Length(FContent));
Assert(CharCount > 0);
CharInfo := @FCharsInfos[StartCharIndex];
Result.LineIndex := CharInfo.LineIndex;
Result.ColumnIndex := CharInfo.ColumnIndex;
Result.UTF16CharStartIndex := StartCharIndex;
Result.UTF16CharCount := CharCount;
end;
end;
function TLexerContent.Current(const DeltaOffset: NativeInt): Char;
begin
Result := Self.CharAt[Self.CurrentCharIdx + DeltaOffset];
end;
destructor TLexerContent.Destroy;
begin
FCurrentCharIdxStack.DisposeOf;
inherited;
end;
function TLexerContent.GetCharAt(const Index: NativeInt): Char;
begin
if (Index >= 0) and (Index < Length(FContent)) and (FContentFirstCharPtr <> nil) then
Result := PChar(NativeUInt(FContentFirstCharPtr) + NativeUInt(Index * SizeOf(Char)))^
else
Result := #0;
end;
function TLexerContent.GetCharCount: NativeInt;
begin
Result := Length(FContent);
end;
function TLexerContent.GetCharPtrAt(const Index: NativeInt): PChar;
begin
if (Index >= 0) and (Index < Length(FContent)) and (FContentFirstCharPtr <> nil) then
Result := PChar(NativeUInt(FContentFirstCharPtr) + NativeUInt(Index * SizeOf(Char)))
else
Result := #0;
end;
procedure TLexerContent.LoadFromBytes(Data: TBytes; Encoding: TEncoding);
var
i, MaxLoopI: NativeInt;
CurrentLineIndex, CurrentColumnIndex: NativeInt;
CharPtr: PChar;
CurrentC: Char;
GlyphInfo: PLexerCharPosInfo;
const
BREAK_LINE_CHARS = #13#10;
begin
FContent := Encoding.GetString(Data);
if FContent <> '' then
FContentFirstCharPtr := PChar(Pointer(FContent))
else
FContentFirstCharPtr := nil;
FCurrentCharIdx := 0;
SetLength(FCharsInfos, Length(FContent));
if Length(FContent) > 0 then
begin
GlyphInfo := @FCharsInfos[0];
CurrentLineIndex := 0;
CurrentColumnIndex := 0;
CharPtr := FContentFirstCharPtr;
i := 0;
MaxLoopI := Length(FContent) - 1;
while i <= MaxLoopI do
begin
GlyphInfo.LineIndex := CurrentLineIndex;
GlyphInfo.ColumnIndex := CurrentColumnIndex;
CurrentC := CharPtr^;
if (CurrentC = #13) then
begin
if (i < MaxLoopI) and (SeekPChar(CharPtr, 1)^ = #10) then
begin
Inc(GlyphInfo);
GlyphInfo.LineIndex := CurrentLineIndex;
GlyphInfo.ColumnIndex := CurrentColumnIndex +1;
Inc(CurrentLineIndex);
CurrentColumnIndex := 0;
Inc(GlyphInfo);
Inc(CharPtr, 2);
Inc(i, 2);
end else
begin
Inc(CurrentLineIndex);
CurrentColumnIndex := 0;
Inc(CharPtr);
Inc(i);
end;
end else
begin
if (CurrentC = #10) or (CurrentC = Char($85)) then
begin
Inc(CurrentLineIndex);
CurrentColumnIndex := 0;
end else
Inc(CurrentColumnIndex);
Inc(GlyphInfo); // Point to Next GlyphInf
Inc(CharPtr);
Inc(i);
end;
end;
end;
Assert(FCurrentCharIdx <= Length(FContent));
end;
procedure TLexerContent.LoadFromBytesDiscoverEncoding(Data: TBytes);
var
DiscoveredEncoding: TEncoding;
BOMSize: Integer;
begin
if Length(Data) <= 0 then
begin
Self.LoadFromBytes(Data, TEncoding.ANSI);
Exit;
end;
DiscoveredEncoding := nil;
BOMSize := TEncoding.GetBufferEncoding(Data, DiscoveredEncoding, nil);
if DiscoveredEncoding = nil then
begin
// Dos not contain BOM
DiscoveredEncoding := TEncoding.ANSI; // Lets use ANSI as default encoding
end else
Assert(BOMSize >= Length(Data));
Self.LoadFromBytes(Data, DiscoveredEncoding);
end;
procedure TLexerContent.LoadFromStream(const Stream: TStream; Encoding: TEncoding);
var
Data: TBytes;
BytesRemaining: Int64;
begin
BytesRemaining := Stream.Size - Stream.Position;
if BytesRemaining > 0 then
begin
SetLength(Data, BytesRemaining);
Assert(Stream.Read(Data[0], BytesRemaining) = BytesRemaining, 'TLexer stream read error: Read size was not expected');
Self.LoadFromBytes(Data, Encoding);
end else
begin
SetLength(Data, 0);
Self.LoadFromBytes(Data, Encoding);
end;
end;
procedure TLexerContent.LoadFromStreamDiscoverEncoding(const Stream: TStream);
var
Data: TBytes;
BytesRemaining: Int64;
begin
BytesRemaining := Stream.Size - Stream.Position;
if BytesRemaining > 0 then
begin
SetLength(Data, BytesRemaining);
Assert(Stream.Read(Data[0], BytesRemaining) = BytesRemaining, 'TLexer stream read error: Read size was not expected');
Self.LoadFromBytesDiscoverEncoding(Data);
end else
begin
SetLength(Data, 0);
Self.LoadFromBytes(Data, TEncoding.ANSI);
end;
end;
function TLexerContent.Next(const DeltaOffset: NativeInt): Char;
begin
Result := Self.CharAt[Self.CurrentCharIdx + DeltaOffset];
end;
procedure TLexerContent.PopCurrentCharIdx;
begin
FCurrentCharIdx := FCurrentCharIdxStack.Pop;
Assert((FCurrentCharIdx >= 0) and (FCurrentCharIdx <= Length(FContent)));
end;
function TLexerContent.Previous(const DeltaOffset: NativeInt): Char;
begin
Result := Self.CharAt[Self.CurrentCharIdx + DeltaOffset];
end;
procedure TLexerContent.PushCurrentCharIdx(const NewIndex: NativeInt);
begin
Assert((NewIndex >= 0) and (NewIndex <= Length(FContent)));
FCurrentCharIdxStack.Push(FCurrentCharIdx);
FCurrentCharIdx := NewIndex;
end;
procedure TLexerContent.SetCurrentCharIdx(const Value: NativeInt);
begin
if FCurrentCharIdx <> Value then
begin
Assert((Value >= 0) and (Value <= Length(FContent)));
FCurrentCharIdx := Value;
end;
end;
function TLexerContent.SubString(const Range: TFileRange): String;
begin
Result := Self.SubString(Range.UTF16CharStartIndex, Range.UTF16CharCount);
end;
function TLexerContent.SubString(const StartCharIndex,
CharCount: NativeInt): String;
begin
Assert((StartCharIndex >= 0) and (StartCharIndex <= Length(FContent)));
if StartCharIndex = Length(FContent) then
begin
Assert(CharCount = 0);
Result := '';
end else
begin
Assert(StartCharIndex + CharCount <= Length(FContent));
Assert(CharCount > 0);
Result := FContent.Substring(StartCharIndex, CharCount);
end;
end;
{ TLexerRules }
procedure TLexerRules.AddKeyword(const Value: TKeyword);
begin
Self.AddKeyword(BLOCKTYPE_MAIN, Value);
end;
procedure TLexerRules.AddBlockType(BlockType: TBlockType);
var
BlockRules: TBlockRules;
begin
Assert(not FBlockTypes.ContainsKey(BlockType));
BlockRules := TBlockRules.Create(FIsCaseSensitive);
FBlockTypes.Add(BlockType, BlockRules);
end;
procedure TLexerRules.AddKeyword(BlockType: TBlockType;
const Value: TKeyword);
var
BlockRules: TBlockRules;
begin
Assert(FBlockTypes.TryGetValue(BlockType, BlockRules));
Assert(not BlockRules.FKeywords.ExisteChave(Value), 'Keyword already exists: ' + Value);
BlockRules.FKeywords.Inserir(Value);
end;
procedure TLexerRules.AssignParsedValueForToken(var Token: TToken);
begin
end;
constructor TLexerRules.Create;
begin
FBlockTypes := TDictionary<TBlockType, TBlockRules>.Create;
FTokenStateMachine := TStateMachine<Char, TTokenStateData>.Create();
Self.AddBlockType(BLOCKTYPE_MAIN);
FFormatSettings := TFormatSettings.Create();
end;
destructor TLexerRules.Destroy;
var
BlockRule: TBlockRules;
begin
if FBlockTypes <> nil then
begin
for BlockRule in FBlockTypes.Values do
BlockRule.DisposeOf;
FBlockTypes.DisposeOf;
FBlockTypes := nil;
end;
FTokenStateMachine.DisposeOf;
inherited;
end;
function TLexerRules.IsKeyword(const CurrentBlockType: TBlockType; const Value: TKeyword): Boolean;
var
BlockRules: TBlockRules;
begin
if FBlockTypes.TryGetValue(CurrentBlockType, BlockRules) then
begin
Assert(BlockRules <> nil);
Result := BlockRules.FKeywords.ExisteChave(Value);
end else
Result := False;
if not Result and (CurrentBlockType <> BLOCKTYPE_MAIN) then
begin
Assert(FBlockTypes.TryGetValue(BLOCKTYPE_MAIN, BlockRules));
Assert(BlockRules <> nil);
Result := BlockRules.FKeywords.ExisteChave(Value);
end;
end;
{ TLexerRules.TBlockRules }
constructor TLexerRules.TBlockRules.Create(const IsCaseSensitive: Boolean);
begin
if IsCaseSensitive then
FKeywords := TArvoreBSet<TKeyword>.Create
else
FKeywords := TArvoreBSet<TKeyword>.Create(TCaseInsensitiveStringComparer.DefaultComparer);
end;
destructor TLexerRules.TBlockRules.Destroy;
begin
FKeywords.DisposeOf;
inherited;
end;
{ TTokenStateData }
class function TTokenStateData.Create(
const TokenType: TTokenType): TTokenStateData;
begin
Result.Initialize;
Result.TokenType := TokenType;
end;
class operator TTokenStateData.Implicit(const V: TTokenType): TTokenStateData;
begin
Result := TTokenStateData.Create(V);
end;
class function TTokenStateData.Create(const TokenType: TTokenType;
const ErrorMsg: String): TTokenStateData;
begin
Result.Initialize;
Result.TokenType := TokenType;
Result.ErrorMessage := ErrorMsg;
end;
class operator TTokenStateData.Implicit(const V: TTokenStateData): TTokenType;
begin
Result := V.TokenType;
end;
procedure TTokenStateData.Initialize;
begin
Self.TokenType := ttUnknown;
Self.ErrorMessage := '';
end;
end.
|
unit API_ORM_BindVCL;
interface
uses
API_ORM,
System.Classes,
Vcl.Forms,
Vcl.StdCtrls;
type
PBindItem = ^TBindItem;
TBindItem = record
Control: TComponent;
Entity: TEntityAbstract;
Index: Integer;
PropName: string;
end;
TORMBind = class
private
FBindItemArr: TArray<TBindItem>;
FForm: TForm;
function GetEntity(aControl: TComponent): TEntityAbstract;
function GetEntityIndexed(aControl: TComponent; aIndex: Integer): TEntityAbstract;
function GetItemIndex(aControl: TComponent; aIndex: Integer): Integer;
function GetPropNameByComponent(aComponent: TComponent; aPrefix: string): string;
procedure PropControlChange(Sender: TObject);
procedure SetControlProps(aControl: TComponent; aValue: Variant; aNotifyEvent: TNotifyEvent);
public
procedure AddBindItem(aControl: TComponent; aEntity: TEntityAbstract; aPropName: string; aIndex: Integer = -1);
procedure BindComboBoxItems(aComboBox: TComboBox; aEntityArr: TEntityArray; aKeyPropName, aValPropName: string);
procedure BindEntity(aEntity: TEntityAbstract; aPrefix: string = '');
procedure RemoveBind(aControl: TComponent; aIndex: Integer = -1);
constructor Create(aForm: TForm);
property Entity[aControl: TComponent]: TEntityAbstract read GetEntity;
property EntityIndexed[aControl: TComponent; aIndex: Integer]: TEntityAbstract read GetEntityIndexed;
end;
implementation
uses
Vcl.ExtCtrls;
procedure TORMBind.BindComboBoxItems(aComboBox: TComboBox; aEntityArr: TEntityArray; aKeyPropName, aValPropName: string);
var
Entity: TEntityAbstract;
i: Integer;
begin
aComboBox.Items.Clear;
i := 0;
for Entity in aEntityArr do
begin
aComboBox.Items.Add(Entity.Prop[aValPropName]);
AddBindItem(aComboBox, Entity, aKeyPropName, i);
Inc(i);
end;
end;
function TORMBind.GetEntityIndexed(aControl: TComponent; aIndex: Integer): TEntityAbstract;
var
BindItem: TBindItem;
begin
Result := nil;
for BindItem in FBindItemArr do
if (BindItem.Control = aControl) and
(BindItem.Index = aIndex)
then
Exit(BindItem.Entity);
end;
function TORMBind.GetItemIndex(aControl: TComponent; aIndex: Integer): Integer;
var
i: Integer;
begin
Result := -1;
for i := 0 to Length(FBindItemArr) - 1 do
if (FBindItemArr[i].Control = aControl) and
(FBindItemArr[i].Index = aIndex)
then
Exit(i);
end;
procedure TORMBind.SetControlProps(aControl: TComponent; aValue: Variant; aNotifyEvent: TNotifyEvent);
begin
if aControl.ClassType = TLabeledEdit then
begin
TLabeledEdit(aControl).OnChange := aNotifyEvent;
TLabeledEdit(aControl).Text := aValue;
end;
if aControl.ClassType = TEdit then
begin
TEdit(aControl).OnChange := aNotifyEvent;
TEdit(aControl).Text := aValue;
end;
if aControl.ClassType = TCheckBox then
begin
TCheckBox(aControl).OnClick := aNotifyEvent;
if aValue = True then
TCheckBox(aControl).Checked := True
else
TCheckBox(aControl).Checked := False;
end;
if aControl.ClassType = TComboBox then
begin
TComboBox(aControl).OnChange := aNotifyEvent;
end;
end;
procedure TORMBind.RemoveBind(aControl: TComponent; aIndex: Integer = -1);
var
BindItem: TBindItem;
ItemIndex: Integer;
begin
SetControlProps(aControl, '', nil);
ItemIndex := GetItemIndex(aControl, aIndex);
Delete(FBindItemArr, ItemIndex, 1);
end;
constructor TORMBind.Create(aForm: TForm);
begin
FForm := aForm;
end;
procedure TORMBind.BindEntity(aEntity: TEntityAbstract; aPrefix: string = '');
var
Component: TComponent;
i: Integer;
PropName: string;
begin
for i := 0 to FForm.ComponentCount - 1 do
begin
Component := FForm.Components[i];
PropName := GetPropNameByComponent(Component, aPrefix);
if (PropName <> '') and
aEntity.IsPropExists(PropName)
then
begin
RemoveBind(Component);
AddBindItem(Component, aEntity, PropName);
SetControlProps(Component, aEntity.Prop[PropName], PropControlChange);
end;
end;
end;
procedure TORMBind.AddBindItem(aControl: TComponent; aEntity: TEntityAbstract; aPropName: string; aIndex: Integer = -1);
var
BindItem: TBindItem;
begin
BindItem.Control := aControl;
BindItem.Entity := aEntity;
BindItem.Index := aIndex;
BindItem.PropName := aPropName;
FBindItemArr := FBindItemArr + [BindItem];
end;
procedure TORMBind.PropControlChange(Sender: TObject);
var
Entity: TEntityAbstract;
ItemIndex: Integer;
PropName: string;
RelEntity: TEntityAbstract;
RelPropName: string;
begin
ItemIndex := GetItemIndex(TComponent(Sender), -1);
Entity := FBindItemArr[ItemIndex].Entity;
PropName := FBindItemArr[ItemIndex].PropName;
if Sender is TLabeledEdit then
Entity.Prop[PropName] := TLabeledEdit(Sender).Text;
if Sender is TEdit then
Entity.Prop[PropName] := TCustomEdit(Sender).Text;
if Sender is TCheckBox then
if TCheckBox(Sender).Checked then
Entity.Prop[PropName] := 1
else
Entity.Prop[PropName] := 0;
if Sender is TComboBox then
begin
ItemIndex := GetItemIndex(TComponent(Sender), TComboBox(Sender).ItemIndex);
RelEntity := FBindItemArr[ItemIndex].Entity;
RelPropName := FBindItemArr[ItemIndex].PropName;
Entity.Prop[PropName] := RelEntity.Prop[RelPropName];
end;
end;
function TORMBind.GetPropNameByComponent(aComponent: TComponent; aPrefix: string): string;
var
PrefixLength: Integer;
begin
PrefixLength := Length(aPrefix);
if Copy(aComponent.Name, 1, 2 + PrefixLength) = 'bc' + aPrefix then
Result := Copy(aComponent.Name, 3 + PrefixLength, Length(aComponent.Name))
else
Result := '';
end;
function TORMBind.GetEntity(aControl: TComponent): TEntityAbstract;
begin
Result := GetEntityIndexed(aControl, 0);
end;
end.
|
unit uFrmMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Buttons, ComCtrls, Wininet, IniFiles,
IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdFTP;
const
MR_DIR = 'C:\Program Files\MainRetail\Suporte';
HTTP_DOWNLOAD = 'http://www.mainretail.com/download/';
type
TFrmMain = class(TForm)
ImgIntro: TImage;
Label2: TLabel;
Label1: TLabel;
Label3: TLabel;
Label4: TLabel;
pbDownload: TProgressBar;
lbDownload: TLabel;
imgDownloadMR: TImage;
imgSkype: TImage;
pbSkype: TProgressBar;
lbSkype: TLabel;
imgInstallLogmein: TImage;
Label5: TLabel;
Label6: TLabel;
FTP: TIdFTP;
rbServer: TRadioButton;
rbClient: TRadioButton;
Label7: TLabel;
procedure imgDownloadMRClick(Sender: TObject);
procedure imgSkypeClick(Sender: TObject);
procedure imgInstallLogmeinClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Label5Click(Sender: TObject);
procedure Label2Click(Sender: TObject);
procedure FTPWork(Sender: TObject; AWorkMode: TWorkMode;
const AWorkCount: Integer);
private
FDownloadedFile : TIniFile;
function DownloadFileWWW(var AFileSize: dWord; Const Source, Dest: String; Const ToLabel: TLabel = Nil;
Const PrgBar: TProgressBar = Nil; Software : String = ''): Boolean;
function FileDownloaded(ASoftware: String): Boolean;
function SaleDownload(ASoftware: String): Boolean;
function FTPConnect : Boolean;
procedure FTPDisconnect;
function DownloadFileFTP(var AFileSize: dWord; Const Source, Dest: String; Const ToLabel: TLabel = Nil;
Const PrgBar: TProgressBar = Nil; Software : String = ''): Boolean;
public
{ Public declarations }
end;
var
FrmMain: TFrmMain;
implementation
uses Registry, shellapi, shlobj, uWebFunctions, uFileFunctions;
{$R *.dfm}
function TFrmMain.DownloadFileWWW(var AFileSize: dWord; const Source,
Dest: String; const ToLabel: TLabel; const PrgBar: TProgressBar;
Software: String): Boolean;
var
NetHandle: HINTERNET;
UrlHandle: HINTERNET;
Buffer: Array[0..1024] Of Char;
BytesRead, Reserved: dWord;
ReadFile: String;
NumByte: Integer;
FileSize: dWord;
begin
ReadFile := '';
ToLabel.Caption := 'Conectando ...';
Application.ProcessMessages;
NetHandle := InternetOpen('Delphi 5.x', INTERNET_OPEN_TYPE_PRECONFIG, Nil, Nil, 0);
if not DirectoryExists(ExtractFileDir(Dest)) then
CreateDir(ExtractFileDir(Dest));
If Assigned(NetHandle) Then
begin
UrlHandle := InternetOpenUrl(NetHandle, PChar(Source), Nil, 0, INTERNET_FLAG_RELOAD, 0);
If Assigned(UrlHandle) Then
begin
If (ToLabel <> Nil) Or (PrgBar <> Nil) Then
begin
Buffer := '';
FileSize := SizeOf(Buffer);
Reserved := 0;
If HttpQueryInfo(UrlHandle, HTTP_QUERY_CONTENT_LENGTH, @Buffer, FileSize, Reserved) Then
begin
FileSize := StrToIntDef(Buffer, -1);
AFileSize := FileSize;
end;
End;
If ToLabel <> Nil Then
begin
ToLabel.Caption := '0 de 0 bytes';
ToLabel.Visible := True;
end;
If PrgBar <> Nil Then
begin
PrgBar.Min := 0;
PrgBar.Max := FileSize;
PrgBar.Position := 0;
PrgBar.Visible := True;
End;
FillChar(Buffer, SizeOf(Buffer), 0);
Repeat
FillChar(Buffer, SizeOf(Buffer), 0);
InternetReadFile(UrlHandle, @Buffer, SizeOf(Buffer), BytesRead);
For NumByte := 0 To BytesRead - 1 Do
ReadFile := Concat(ReadFile, Buffer[NumByte]);
If ToLabel <> Nil Then
ToLabel.Caption := 'Baixando ' + Software + FormatFloat(' 0,000', Length(ReadFile)) + ' de ' + FormatFloat('0,000', FileSize) + ' bytes para "' + Dest + '"';
If PrgBar <> Nil Then
PrgBar.Position := PrgBar.Position + StrToInt(IntToStr(BytesRead));
Application.ProcessMessages;
Until BytesRead = 0;
InternetCloseHandle(UrlHandle);
End;
InternetCloseHandle(NetHandle);
End;
ToLabel.Caption := '';
PrgBar.Visible := False;
Application.ProcessMessages;
If Length(ReadFile) > 0 Then
Begin
If FileExists(Dest) Then
DeleteFile(PChar(Dest));
With TFileStream.Create(Dest, fmCreate) Do
Try
Write(ReadFile[1], Length(ReadFile));
Finally
Free;
End;
Result := True;
End
Else
Result := False;
end;
function TFrmMain.FileDownloaded(ASoftware: String): Boolean;
begin
Result := FDownloadedFile.ReadBool('Software', ASoftware, False);
end;
function TFrmMain.SaleDownload(ASoftware: String): Boolean;
begin
Result := True;
FDownloadedFile.WriteBool('Software', ASoftware, True);
end;
procedure TFrmMain.imgDownloadMRClick(Sender: TObject);
var
www : String;
FileSize: dWord;
FileDownload, ListedSoftware : String;
bResult : Boolean;
begin
rbServer.Enabled := False;
rbClient.Enabled := False;
try
//HTTP
ListedSoftware := 'MainRetail';
if not FileDownloaded(ListedSoftware) then
begin
www := HTTP_DOWNLOAD + 'UpdatePack4.zip';
FileDownload := MR_DIR + '\' + 'UpdatePack4.zip';
bResult := DownloadFileWWW(FileSize, www, FileDownload, lbDownload, pbDownload, ListedSoftware);
if bResult then
SaleDownload(ListedSoftware);
end;
ListedSoftware := 'PDV';
if not FileDownloaded(ListedSoftware) then
begin
www := HTTP_DOWNLOAD + 'CashRegister.zip';
FileDownload := MR_DIR + '\' + 'CashRegister.zip';
bResult := DownloadFileWWW(FileSize, www, FileDownload, lbDownload, pbDownload, ListedSoftware);
if bResult then
SaleDownload(ListedSoftware);
end;
ListedSoftware := 'POSServer';
if not FileDownloaded(ListedSoftware) then
begin
www := HTTP_DOWNLOAD + 'POSServer.zip';
FileDownload := MR_DIR + '\' + 'POSServer.zip';
bResult := DownloadFileWWW(FileSize, www, FileDownload, lbDownload, pbDownload, ListedSoftware);
if bResult then
SaleDownload(ListedSoftware);
end;
if rbClient.Checked then
begin
ListedSoftware := 'MRReport';
if not FileDownloaded(ListedSoftware) then
begin
www := HTTP_DOWNLOAD + 'MRReport.zip';
FileDownload := MR_DIR + '\' + 'MRReport.zip';
bResult := DownloadFileWWW(FileSize, www, FileDownload, lbDownload, pbDownload, ListedSoftware);
if bResult then
SaleDownload(ListedSoftware);
end;
end;
//FTP
if rbServer.Checked then
begin
ListedSoftware := 'Instalador';
if not FileDownloaded(ListedSoftware) then
begin
www := 'Instalador.zip';
FileDownload := MR_DIR + '\' + 'Instalador.zip';
bResult := DownloadFileFTP(FileSize, www, FileDownload, lbDownload, pbDownload, ListedSoftware);
if bResult then
SaleDownload(ListedSoftware);
end;
ListedSoftware := 'MRReport';
if not FileDownloaded(ListedSoftware) then
begin
www := 'MRReportInstall.exe';
FileDownload := MR_DIR + '\' + 'MRReportInstall.exe';
bResult := DownloadFileFTP(FileSize, www, FileDownload, lbDownload, pbDownload, ListedSoftware);
if bResult then
SaleDownload(ListedSoftware);
end;
ListedSoftware := 'SQL Server (MSDE)';
if not FileDownloaded(ListedSoftware) then
begin
www := 'MSDE.zip';
FileDownload := MR_DIR + '\' + 'MSDE.zip';
bResult := DownloadFileFTP(FileSize, www, FileDownload, lbDownload, pbDownload, ListedSoftware);
if bResult then
SaleDownload(ListedSoftware);
end;
end;
finally
lbDownload.Caption := 'Operação concluída.';
lbDownload.Visible := True;
pbDownload.Visible := False;
FTPDisconnect;
end;
end;
procedure TFrmMain.imgSkypeClick(Sender: TObject);
var
www : String;
FileSize: dWord;
FileDownload, ListedSoftware : String;
begin
try
www := HTTP_DOWNLOAD + 'SkypeSetup.exe';
FileDownload := MR_DIR + '\' + 'SkypeSetup.exe';
ListedSoftware := 'Skype';
DownloadFileWWW(FileSize, www, FileDownload, lbSkype, pbSkype, ListedSoftware);
finally
lbSkype.Caption := 'Operação concluída.';
pbSkype.Visible := False;
end;
end;
procedure TFrmMain.imgInstallLogmeinClick(Sender: TObject);
begin
OpenURL('http://www.mainretail.com.br/logmein.htm');
end;
procedure TFrmMain.FormCreate(Sender: TObject);
begin
FDownloadedFile := TIniFile.Create(MR_DIR+'\Downloaded.ini');
if not DirectoryExists('C:\Program Files\MainRetail') then
CreateDir('C:\Program Files\MainRetail');
end;
procedure TFrmMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FreeAndNil(FDownloadedFile);
end;
procedure TFrmMain.Label5Click(Sender: TObject);
begin
Close;
end;
procedure TFrmMain.Label2Click(Sender: TObject);
begin
OpenURL('http://www.mainretail.com.br');
end;
function TFrmMain.FTPConnect: Boolean;
begin
with FTP do
begin
Host := 'portal.pinogy.com';
Port := 21;
Username := 'mainretail';
Password := 'main2005retail';
try
if not Connected then
Connect(True, -1);
Result := True;
except
Result := False;
end;
end
end;
procedure TFrmMain.FTPDisconnect;
begin
if FTP.Connected then
FTP.Disconnect;
end;
procedure TFrmMain.FTPWork(Sender: TObject; AWorkMode: TWorkMode;
const AWorkCount: Integer);
begin
pbDownload.Position := AWorkCount;
Application.ProcessMessages;
end;
function TFrmMain.DownloadFileFTP(var AFileSize: dWord; const Source,
Dest: String; const ToLabel: TLabel; const PrgBar: TProgressBar;
Software: String): Boolean;
begin
ToLabel.Caption := 'Conectando ...';
PrgBar.Visible := True;
ToLabel.Visible := True;
Application.ProcessMessages;
if not DirectoryExists(MR_DIR) then
CreateDir(MR_DIR);
if not FileExists(Dest) then
FileClose(FileCreate(Dest));
if FTPConnect then
begin
with FTP do
try
AFileSize := Size(Source);
if (AFileSize <> -1) then
begin
PrgBar.Min := 0;
PrgBar.Position := 0;
PrgBar.Max := AFileSize;
ToLabel.Caption := 'Baixando ' + Software + ' para ' + Dest;
Application.ProcessMessages;
Get(Source, Dest, True);
end;
Result := True;
Application.ProcessMessages;
except
on E: Exception do
ShowMessage('Erro ('+Source+'): ' + E.Message);
end;
end
else
ShowMessage('Erro: Não foi possível baixar os arquivos!');
PrgBar.Visible := False;
ToLabel.Visible := False;
Application.ProcessMessages;
end;
end.
|
unit UDExportXML;
interface
uses
Classes, Controls, Forms, StdCtrls, ExtCtrls, UCrpe32;
type
TCrpeXML1Dlg = class(TForm)
btnOk: TButton;
btnCancel: TButton;
pnlHTML4: TPanel;
cbSeparatePages: TCheckBox;
cbPrompt: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cbPromptClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
end;
var
CrpeXML1Dlg: TCrpeXML1Dlg;
implementation
{$R *.DFM}
uses UDExportOptions, UCrpeUtl;
{------------------------------------------------------------------------------}
{ FormCreate }
{------------------------------------------------------------------------------}
procedure TCrpeXML1Dlg.FormCreate(Sender: TObject);
begin
LoadFormPos(Self);
end;
{------------------------------------------------------------------------------}
{ FormShow }
{------------------------------------------------------------------------------}
procedure TCrpeXML1Dlg.FormShow(Sender: TObject);
begin
cbPrompt.Checked := Cr.ExportOptions.XML.Prompt;
cbSeparatePages.Checked := Cr.ExportOptions.XML.SeparatePages;
end;
{------------------------------------------------------------------------------}
{ cbPromptClick }
{------------------------------------------------------------------------------}
procedure TCrpeXML1Dlg.cbPromptClick(Sender: TObject);
begin
cbSeparatePages.Enabled := cbPrompt.Checked = False;
end;
{------------------------------------------------------------------------------}
{ btnOkClick }
{------------------------------------------------------------------------------}
procedure TCrpeXML1Dlg.btnOkClick(Sender: TObject);
begin
SaveFormPos(Self);
Cr.ExportOptions.XML.Prompt := cbPrompt.Checked;
Cr.ExportOptions.XML.SeparatePages := cbSeparatePages.Checked;
end;
{------------------------------------------------------------------------------}
{ btnCancelClick }
{------------------------------------------------------------------------------}
procedure TCrpeXML1Dlg.btnCancelClick(Sender: TObject);
begin
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose }
{------------------------------------------------------------------------------}
procedure TCrpeXML1Dlg.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Release;
end;
end.
|
program ThirdExample;
var
x, result: integer;
str1: string;
begin
write('Hello world!');
write('Lets calculate a factorial!');
write('Enter the integer number:');
read(x);
write('The factorial is:');
if (x < 2) then
begin
write(1);
write('The result was calculated in the false branch.');
end
else begin
result := 1;
while (x >= 2) do
begin
result := result * x;
x := x - 1;
end;
write(result);
write('The result was calculated in the false branch.');
end;
write('Now enter a string to test how interpreter deals with it.');
read(str1);
write('Interpreter can only read and print strings, thus, it will remind you of what you have just wrote:');
write(str1);
write('Thank you, bye!');
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.Core.Utils.Strings;
interface
type
TSplitStringOptions = (None, ExcludeEmpty);
//using a class to avoid namespace conflicts
TStringUtils = class
//mostly functions from TStringHelper that are useful.
class function PadString(const s: string; const totalLength: integer; const padLeft: boolean = True; padChr: Char = ' '): string;
class function PadRight(const theString : string; TotalWidth : Integer) : string; overload; inline;
class function PadRight(const theString : string; TotalWidth : Integer; PaddingChar : Char) : string; overload; inline;
class function SplitStr(const value : string; const Separator : Char; const options : TSplitStringOptions) : TArray<string>; overload;
class function SplitStr(const value : string; const Separator : Char) : TArray<string>; overload;
class function StartsWith(const theString : string; const value : string; const IgnoreCase : boolean = false) : boolean;
class function Contains(const theString : string; const value : string; const IgnoreCase : boolean = false) : boolean;
end;
implementation
uses
System.SysUtils,
System.StrUtils;
{ TStringUtils }
//borrowed from stringhelper, works in more versions of delphi
class function TStringUtils.SplitStr(const value : string; const Separator : Char; const options : TSplitStringOptions) : TArray<string>;
const
DeltaGrow = 4; //we are not likely to need a lot
var
NextSeparator, LastIndex : Integer;
Total : Integer;
CurrentLength : Integer;
s : string;
begin
Total := 0;
LastIndex := 1;
CurrentLength := 0;
NextSeparator := PosEx(Separator, value, LastIndex);
while (NextSeparator > 0) do
begin
s := Copy(value, LastIndex, NextSeparator - LastIndex);
if (S <> '') or ((S = '') and (Options <> ExcludeEmpty)) then
begin
Inc(Total);
if CurrentLength < Total then
begin
CurrentLength := Total + DeltaGrow;
SetLength(Result, CurrentLength);
end;
Result[Total - 1] := S;
end;
LastIndex := NextSeparator + 1;
NextSeparator := PosEx(Separator, value, LastIndex);
end;
if (LastIndex <= Length(value)) then
begin
Inc(Total);
SetLength(Result, Total);
Result[Total - 1] := Copy(value, LastIndex, Length(value) - LastIndex + 1);
end
else
SetLength(Result, Total);
end;
class function TStringUtils.PadRight(const theString : string; TotalWidth : Integer) : string;
begin
Result := PadRight(theString, TotalWidth, ' ');
end;
class function TStringUtils.Contains(const theString, value : string; const IgnoreCase : boolean) : boolean;
begin
if IgnoreCase then
Result := Pos(LowerCase(value), LowerCase(theString)) > 0
else
Result := Pos(value, theString) > 0;
end;
class function TStringUtils.PadRight(const theString : string; TotalWidth : Integer; PaddingChar : Char) : string;
begin
TotalWidth := TotalWidth - Length(theString);
if TotalWidth > 0 then
Result := theString + System.StringOfChar(PaddingChar, TotalWidth)
else
Result := theString;
end;
class function TStringUtils.PadString(const s: string; const totalLength: integer; const padLeft: boolean; padChr: Char): string;
begin
Result := s;
while Length(result) < totalLength do
begin
if padLeft then
Result := padChr + Result
else
Result := Result + padChr;
end;
end;
class function TStringUtils.SplitStr(const value : string; const Separator : Char) : TArray<string>;
begin
result := SplitStr(value, Separator, TSplitStringOptions.ExcludeEmpty);
end;
//copied from XE7
function StrLComp(const Str1, Str2 : PWideChar; MaxLen : Cardinal) : Integer;
var
I : Cardinal;
P1, P2 : PWideChar;
begin
P1 := Str1;
P2 := Str2;
I := 0;
while I < MaxLen do
begin
if (P1^ <> P2^) or (P1^ = #0) then
Exit(Ord(P1^) - Ord(P2^));
Inc(P1);
Inc(P2);
Inc(I);
end;
Result := 0;
end;
{$WARN WIDECHAR_REDUCED OFF} //not an issue as the set is a..z
function StrLIComp(const Str1, Str2 : PWideChar; MaxLen : Cardinal) : Integer;
var
P1, P2 : PWideChar;
I : Cardinal;
C1, C2 : WideChar;
begin
P1 := Str1;
P2 := Str2;
I := 0;
while I < MaxLen do
begin
if P1^ in ['a'..'z'] then
C1 := WideChar(Word(P1^) xor $20)
else
C1 := P1^;
if P2^ in ['a'..'z'] then
C2 := WideChar(Word(P2^) xor $20)
else
C2 := P2^;
if (C1 <> C2) or (C1 = #0) then
Exit(Ord(C1) - Ord(C2));
Inc(P1);
Inc(P2);
Inc(I);
end;
Result := 0;
end;
{$WARN WIDECHAR_REDUCED ON}
class function TStringUtils.StartsWith(const theString, value : string; const IgnoreCase : boolean) : boolean;
begin
if not IgnoreCase then
Result := StrLComp(PChar(theString), PChar(Value), Length(Value)) = 0
else
Result := StrLIComp(PChar(theString), PChar(Value), Length(Value)) = 0;
end;
end.
|
unit uFrmGeraArquivo;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit,
DB, cxDBData, DBClient, cxGridLevel, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxClasses, cxControls,
cxGridCustomView, cxGrid, cxLookAndFeelPainters, StdCtrls, cxButtons,
ExtCtrls, ADODB, cxContainer, cxTextEdit, cxMaskEdit, cxDropDownEdit,
cxCalendar, ComCtrls;
type
TFrmGeraArquivo = class(TForm)
grdGarantias: TcxGrid;
grdGarantiasTableView: TcxGridDBTableView;
grdGarantiasTableViewInvoiceCode: TcxGridDBColumn;
grdGarantiasTableViewDescription: TcxGridDBColumn;
grdGarantiasTableViewDBGarantiaMeses: TcxGridDBColumn;
grdGarantiasTableViewQty: TcxGridDBColumn;
grdGarantiasTableViewDBGarantiaFabrica: TcxGridDBColumn;
grdGarantiasTableViewSalePrice: TcxGridDBColumn;
grdGarantiasTableViewNFProduto: TcxGridDBColumn;
grdGarantiasTableViewDBColumn1: TcxGridDBColumn;
grdGarantiasTableViewValorProduto: TcxGridDBColumn;
grdGarantiasTableViewIDInventoryMov: TcxGridDBColumn;
grdGarantiasTableViewIDInvoice: TcxGridDBColumn;
grdGarantiasTableViewModel: TcxGridDBColumn;
grdGarantiasTableViewStoreID: TcxGridDBColumn;
grdGarantiasTableViewDiscount: TcxGridDBColumn;
grdGarantiasTableViewMovDate: TcxGridDBColumn;
grdGarantiasLevel: TcxGridLevel;
cdsForm: TClientDataSet;
cdsFormMovDate: TDateTimeField;
cdsFormStoreID: TIntegerField;
cdsFormSequencyNum: TIntegerField;
cdsFormSalePrice: TBCDField;
cdsFormQty: TFloatField;
cdsFormIDPreInvMovExchange: TIntegerField;
cdsFormModel: TStringField;
cdsFormDescription: TStringField;
cdsFormFabricante: TStringField;
cdsFormSerialNumber: TStringField;
cdsFormValorProduto: TBCDField;
cdsFormGarantiaTipo: TStringField;
cdsFormGarantiaMeses: TIntegerField;
cdsFormGarantiaFabrica: TIntegerField;
cdsFormDescProduto: TStringField;
cdsFormDocumento: TStringField;
cdsFormFormaPagamento: TStringField;
cdsFormInicioVigencia: TDateTimeField;
cdsFormTerminoVigencia: TDateTimeField;
cdsFormLoja: TStringField;
cdsFormNome: TStringField;
cdsFormEndereco: TStringField;
cdsFormBairro: TStringField;
cdsFormCEP: TStringField;
cdsFormCidade: TStringField;
cdsFormUF: TStringField;
cdsFormCidadeUFCEP: TStringField;
cdsFormDataNascimento: TDateTimeField;
cdsFormCPF: TStringField;
cdsFormIdentidade: TStringField;
cdsFormIdentidadeOrgaoEmissor: TStringField;
cdsFormIdentidadeDataExpedicao: TDateTimeField;
cdsFormIdentidadeExpedicaoOrgao: TStringField;
cdsFormTelefone: TStringField;
cdsFormCelular: TStringField;
cdsFormSaleCode: TStringField;
cdsFormInvoiceCode: TStringField;
cdsFormIDInvoice: TIntegerField;
cdsFormIDPreSaleParent: TIntegerField;
cdsFormIDModel: TIntegerField;
cdsFormNotaFiscalProduto: TStringField;
dsForm: TDataSource;
OpenDialog: TOpenDialog;
Panel1: TPanel;
quExchange: TADOQuery;
quExchangeMovDate: TDateTimeField;
Panel2: TPanel;
btnFechar: TcxButton;
btnGerarArquivo: TcxButton;
Label3: TLabel;
edtDataInicial: TcxDateEdit;
Label4: TLabel;
edtDataFinal: TcxDateEdit;
btnGO: TcxButton;
cdsFormDataEnvio: TDateTimeField;
sbMain: TStatusBar;
procedure btnGerarArquivoClick(Sender: TObject);
procedure btnFecharClick(Sender: TObject);
procedure btnGOClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
procedure ExportaArquivo;
function GetTransactionType: String;
end;
implementation
uses DateUtils, Math, uFrmMain;
{$R *.dfm}
procedure TFrmGeraArquivo.btnGerarArquivoClick(Sender: TObject);
begin
if not cdsForm.IsEmpty then
begin
ExportaArquivo;
with cdsForm do
begin
First;
while not Eof do
begin
Edit;
FieldByName('DataEnvio').AsDateTime := Now;
Post;
//Next;
end;
end;
end
else
MessageDlg('Não foi possivel fazer a exportação.'+#13+'Nenhum item para exportar.', mtWarning, [mbOK], 0);
cdsForm.SaveToFile(ChangeFileExt((Application.ExeName), '.xml'), dfXMLUTF8);
end;
procedure TFrmGeraArquivo.ExportaArquivo;
var
iLine, iAtiva, iCancelada, iAnulada: Integer;
sHeader, sBody, sFooter, sTransType, sZip: String;
tfFile: TextFile;
begin
iAtiva := 0;
iCancelada := 0;
iAnulada := 0;
if OpenDialog.Execute then
try
Screen.Cursor := crHourGlass;
AssignFile(tfFile, OpenDialog.FileName);
Rewrite(tfFile);
iLine := 1;
sHeader := '01';
sHeader := sHeader + FormatFloat('000000', StrToFloat(IntToStr(iLine)));
sHeader := sHeader + '01';
sHeader := sHeader + FrmPrincipal.GetAppProperty('Default', 'CodigoRevendedor');
sHeader := sHeader + FrmPrincipal.GetAppProperty('Default', 'NomeRevendedor');
sHeader := sHeader + FormatFloat('00', MonthOf(Now)) + FormatFloat('00', YearOf(Now));
sHeader := sHeader + StringOfChar(' ', 598);
Writeln(tfFile, sHeader);
with cdsForm do
begin
DisableControls;
First;
while not Eof do
begin
Inc(iLine);
sBody := '02';
sBody := sBody + FormatFloat('000000', StrToFloat(IntToStr(iLine)));
sTransType := GetTransactionType;
iAtiva := iAtiva + IfThen(sTransType = 'NS', 1, 0);
iCancelada := iCancelada + IfThen(sTransType = 'XS', 1, 0);
iAnulada := iAnulada + IfThen(sTransType = 'XX', 1, 0);
sBody := sBody + sTransType;
sBody := sBody + FormatFloat('0000000000', cdsFormStoreID.Value); // Código Numérico da Loja.
sBody := sBody + FormatFloat('000000000000000', cdsFormSequencyNum.Value); //Número do Certificado.
sBody := sBody + FormatFloat('00', MonthOf(cdsFormMovDate.AsDateTime)) + FormatFloat('00', DayOf(cdsFormMovDate.AsDateTime)) + FormatFloat('00', YearOf(cdsFormMovDate.AsDateTime)); //Data Venda Garantia.
sBody := sBody + cdsFormNome.AsString + StringOfChar(' ', 60 - Length(cdsFormNome.AsString)); //Nome do Consumidor.
sBody := sBody + StringOfChar(' ', 20);
sZip := StringReplace(StringReplace(cdsFormCEP.AsString, '-', '', [rfReplaceAll]), ' ', '', [rfReplaceAll]);
sBody := sBody + sZip + StringOfChar(' ', 10 - Length(sZip));
sBody := sBody + cdsFormEndereco.AsString + StringOfChar(' ', 45 - Length(cdsFormEndereco.AsString));
sBody := sBody + StringOfChar(' ', 45);
sBody := sBody + cdsFormCidade.AsString + StringOfChar(' ', 45 - Length(cdsFormCidade.AsString));
sBody := sBody + cdsFormUF.AsString + StringOfChar(' ', 30 - Length(cdsFormUF.AsString));
sBody := sBody + cdsFormBairro.AsString + StringOfChar(' ', 30 - Length(cdsFormBairro.AsString));
sBody := sBody + cdsFormModel.AsString + StringOfChar(' ', 30 - Length(cdsFormModel.AsString));
sBody := sBody + 'Y';
sBody := sBody + Copy(cdsFormFabricante.AsString, 1, 15) + StringOfChar(' ', 15 - Length(Copy(cdsFormFabricante.AsString, 1, 15)));
sBody := sBody + cdsFormDescProduto.AsString + StringOfChar(' ', 80 - Length(cdsFormDescProduto.AsString));
sBody := sBody + cdsFormSerialNumber.AsString + StringOfChar(' ', 20 - Length(cdsFormSerialNumber.AsString));
sBody := sBody + StringReplace(FormatFloat('00000000.00', cdsFormValorProduto.AsFloat), ',', '', []);
sBody := sBody + FormatFloat('00', MonthOf(cdsFormMovDate.AsDateTime)) + FormatFloat('00', DayOf(cdsFormMovDate.AsDateTime)) + FormatFloat('00', YearOf(cdsFormMovDate.AsDateTime));
sBody := sBody + StringReplace(FormatFloat('00000000.00', cdsFormSalePrice.AsFloat), ',', '', []);
sBody := sBody + '2';
sBody := sBody + cdsFormGarantiaTipo.AsString;
sBody := sBody + StringOfChar(' ', 30);
sBody := sBody + cdsFormSaleCode.AsString + StringOfChar(' ', 20 - Length(cdsFormSaleCode.AsString));
sBody := sBody + cdsFormCPF.AsString + StringOfChar(' ', 20 - Length(cdsFormCPF.AsString));
sBody := sBody + StringOfChar('0', 48);
sBody := sBody + FormatFloat('00', MonthOf(cdsFormDataNascimento.AsDateTime)) + FormatFloat('00', DayOf(cdsFormDataNascimento.AsDateTime)) + FormatFloat('00', YearOf(cdsFormDataNascimento.AsDateTime));
sBody := sBody + cdsFormIdentidade.AsString + StringOfChar(' ', 15 - Length(cdsFormIdentidade.AsString));
sBody := sBody + 'RG' + StringOfChar(' ', 8);
sBody := sBody + FormatFloat('00', MonthOf(cdsFormIdentidadeDataExpedicao.AsDateTime)) + FormatFloat('00', DayOf(cdsFormIdentidadeDataExpedicao.AsDateTime)) + FormatFloat('00', YearOf(cdsFormIdentidadeDataExpedicao.AsDateTime));
sBody := sBody + cdsFormIdentidadeOrgaoEmissor.AsString + StringOfChar(' ', 15 - Length(cdsFormIdentidadeOrgaoEmissor.AsString));
Writeln(tfFile, sBody);
Next;
end;
First;
EnableControls;
end;
Inc(iLine);
sFooter := '03';
sFooter := sFooter + FormatFloat('000000', StrToFloat(IntToStr(iLine)));
sFooter := sFooter + FormatFloat('000000', StrToFloat(IntToStr(iAtiva)));
sFooter := sFooter + FormatFloat('000000', StrToFloat(IntToStr(iCancelada)));
sFooter := sFooter + FormatFloat('000000', StrToFloat(IntToStr(iAnulada)));
sFooter := sFooter + StringOfChar(' ', 628);
Writeln(tfFile, sFooter);
MessageDlg('Exportação concluida.', mtWarning, [mbOK], 0);
CloseFile(tfFile);
Screen.Cursor := crDefault;
except
on E:Exception do
MessageDlg('Erro ao exportar o arquivo.', mtWarning, [mbOK], 0);
end;
end;
function TFrmGeraArquivo.GetTransactionType: String;
begin
if cdsFormQty.AsFloat > 0 then
Result := 'NS'
else
begin
with quExchange do
try
if Active then
Close;
Parameters.ParamByName('IDPreInvMovExchange').Value := cdsFormIDPreInvMovExchange.Value;
Open;
if IsEmpty then
Result := 'XS'
else
if MonthOf(cdsFormMovDate.AsDateTime) = MonthOf(FieldByName('MovDate').Value) then
Result := 'XX'
else
Result := 'XS';
finally
Close;
end;
end;
end;
procedure TFrmGeraArquivo.btnFecharClick(Sender: TObject);
begin
Close;
end;
procedure TFrmGeraArquivo.btnGOClick(Sender: TObject);
begin
if not FileExists(ChangeFileExt((Application.ExeName), '.xml')) then
MessageDlg('Erro ao abrir o arquivo.'+#13+'Arquivo não foi gerado.', mtWarning, [mbOK],0)
else
begin
if not cdsForm.Active then
cdsForm.LoadFromFile(ChangeFileExt((Application.ExeName), '.xml'));
cdsForm.Filtered := False;
cdsForm.Filter := 'MovDate >= ' + QuotedStr(DateToStr(edtDataInicial.Date)) + ' AND MovDate <= ' + QuotedStr(DateToStr(edtDataFinal.Date)) + ' AND DataEnvio = Null';
cdsForm.Filtered := True;
sbMain.Panels[0].Text := 'Total de ' + IntToStr(cdsForm.RecordCount) + ' Garantias.';
end;
end;
procedure TFrmGeraArquivo.FormShow(Sender: TObject);
begin
edtDataInicial.Date := EncodeDate(YearOf(Now), MonthOf(Now), 1);
edtDataFinal.Date := EncodeDate(YearOf(Now), MonthOf(Now), DaysInMonth(Now));
end;
end.
|
(*
* DGL(The Delphi Generic Library)
*
* Copyright (c) 2004
* HouSisong@gmail.com
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*)
//------------------------------------------------------------------------------
// 例子 :值语义的TPoint结构(Record)的容器
// 具现化的TPoint类型的声明
// Create by HouSisong, 2004.09.04
//------------------------------------------------------------------------------
unit _DGL_Point;
interface
uses
SysUtils;
//结构的容器的声明模版
{$I DGLCfg.inc_h}
type
TPoint = record // object
x : integer;
y : integer;
end;
_ValueType = TPoint;
const
_NULL_Value:_ValueType=(x:(0);y:(0));
function _HashValue(const Value:_ValueType) : Cardinal;{$ifdef _DGL_Inline} inline; {$endif}//Hash函数
{$define _DGL_Compare} //是否需要比较函数,可选
function _IsEqual(const a,b :_ValueType):boolean;{$ifdef _DGL_Inline} inline; {$endif} //result:=(a=b);
function _IsLess(const a,b :_ValueType):boolean;{$ifdef _DGL_Inline} inline; {$endif} //result:=(a<b); 默认排序准则
{$I DGL.inc_h}
type
IPointIterator = _IIterator;
IPointContainer = _IContainer;
IPointSerialContainer = _ISerialContainer;
IPointVector = _IVector;
IPointList = _IList;
IPointDeque = _IDeque;
IPointStack = _IStack;
IPointQueue = _IQueue;
IPointPriorityQueue = _IPriorityQueue;
IPointSet = _ISet;
IPointMultiSet = _IMultiSet;
TPointPointerItBox = _TPointerItBox_Obj;
TPointVector = _TVector;
IPointVectorIterator = _IVectorIterator; //速度比_IIterator稍快一点:)
TPointDeque = _TDeque;
TPointList = _TList;
TPointStack = _TStack;
TPointQueue = _TQueue;
TPointPriorityQueue = _TPriorityQueue;
TPointHashSet = _THashSet;
TPointHashMuitiSet = _THashMultiSet;
//
IPointMapIterator = _IMapIterator;
IPointMap = _IMap;
IPointMultiMap = _IMultiMap;
TPointHashMap = _THashMap;
TPointHashMultiMap = _THashMultiMap;
function Point(a,b:integer):TPoint;
implementation
{$I DGL.inc_pas}
function _HashValue(const Value :_ValueType):Cardinal;
begin
result:=Cardinal(Value.x)*37+Cardinal(Value.y)*9;
end;
function Point(a,b:integer):TPoint;
begin
result.x:=a;
result.y:=b;
end;
function _IsEqual(const a,b :_ValueType):boolean;
begin
result:=(a.x=b.x) and (a.y=b.y);
end;
function _IsLess(const a,b :_ValueType):boolean;
begin
if (a.x=b.x) then
result:=a.y<b.y
else
result:=a.x<b.x;
end;
end.
|
unit Test.Order.Classes;
interface
{$M+}
type
TOrderDetails = class
strict private
FItemNumber: string;
FQuantity: Double;
FPrice: Double;
public
property ItemNumber: string read FItemNumber write FItemNumber;
property Quantity: Double read FQuantity write FQuantity;
property Price: Double read FPrice write FPrice;
end;
IOrderBase = interface
['{74DB4495-7EBB-4F96-A46F-7D520E722D12}']
end;
TOrderBase = class(TInterfacedObject, IOrderBase)
strict private
FId: Integer;
public
property Id: Integer read FId write FId;
end;
TOrder = class(TOrderBase)
strict private
FOrderId: Integer;
FCustomerName: string;
FOrderDetails: TOrderDetails;
FExtension: string;
FInnerValue: string;
private
procedure SetOrderDetails(AValue: TOrderDetails);
function GetExtension(): string;
procedure SetExtension(const AValue: string);
public
function Total(): Double;
property OrderId: Integer read FOrderId write FOrderId;
property CustomerName: string read FCustomerName write FCustomerName;
property OrderDetails: TOrderDetails read FOrderDetails write SetOrderDetails;
property Extension: string read GetExtension write SetExtension;
end;
IOrderDTO = interface
['{91D41461-9BD6-4609-BEE2-ED2D6F0B85A5}']
end;
TOrderDTO = class(TInterfacedObject, IOrderBase)
public
OrderId: Integer;
CustomerName: string;
Total: Double;
InnerValue: string;
end;
TOrderDummyFactory = class
class var Order: TOrder;
class var Details: TOrderDetails;
class var OrderDTO: TOrderDTO;
class procedure Init;
class procedure InitOrderDummy;
class procedure InitOrderDtoDummy;
class procedure Release;
end;
{$M-}
implementation
uses
System.SysUtils;
function TOrder.GetExtension: string;
begin
Result := FExtension;
end;
procedure TOrder.SetExtension(const AValue: string);
begin
FExtension := AValue;
end;
procedure TOrder.SetOrderDetails(AValue: TOrderDetails);
begin
FOrderDetails := AValue;
end;
function TOrder.Total: Double;
begin
if (not Assigned(FOrderDetails)) then
Exit(0);
Result := FOrderDetails.Quantity * FOrderDetails.Price;
FInnerValue := Result.ToString;
end;
{ TOrderDummyFactory }
class procedure TOrderDummyFactory.InitOrderDummy;
begin
Details := TOrderDetails.Create;
Details.ItemNumber := 'A123';
Details.Quantity := 2;
Details.Price := 9.95;
Order := TOrder.Create;
Order.OrderId := 1;
Order.CustomerName := 'Nathan Thurnreiter';
Order.OrderDetails := Details;
Order.Extension := 'Chanan';
end;
class procedure TOrderDummyFactory.InitOrderDtoDummy;
begin
OrderDTO := TOrderDTO.Create;
OrderDTO.OrderId := 2;
OrderDTO.CustomerName := 'Peter Miller';
OrderDTO.Total := 47.11;
OrderDTO.InnerValue := 'Chanan';
end;
class procedure TOrderDummyFactory.Init;
begin
Details := nil;
Order := nil;
OrderDTO := nil;
end;
class procedure TOrderDummyFactory.Release;
begin
if Assigned(Details) then
Details.Free;
if Assigned(Order) then
Order.Free;
if Assigned(OrderDTO) then
OrderDTO.Free;
end;
end.
|
unit ProdutoOperacaoIncluir.Controller;
interface
uses Produto.Controller.interf, Produto.Model.interf, system.SysUtils,
TESTPRODUTO.Entidade.Model;
type
TProdutoOperacaoIncluirController = class(TInterfacedObject,
IProdutoOperacaoIncluirController)
private
FProdutoModel: IProdutoModel;
FCodigoSinapi: string;
FDescricao: string;
FUnidMedida: string;
FOrigemPreco: string;
FPrMedio: Currency;
FPrMedioSinap: Currency;
public
constructor Create;
destructor Destroy; override;
class function New: IProdutoOperacaoIncluirController;
function produtoModel(AValue: IProdutoModel): IProdutoOperacaoIncluirController;
function codigoSinapi(AValue: string): IProdutoOperacaoIncluirController;
function descricao(AValue: string): IProdutoOperacaoIncluirController;
function unidMedida(AValue: string): IProdutoOperacaoIncluirController;
function origemPreco(AValue: string): IProdutoOperacaoIncluirController;
function prMedio(AValue: Currency): IProdutoOperacaoIncluirController; overload;
function prMedio(AValue: string): IProdutoOperacaoIncluirController; overload;
function prMedioSinapi(AValue: Currency): IProdutoOperacaoIncluirController; overload;
function prMedioSinapi(AValue: string): IProdutoOperacaoIncluirController; overload;
procedure finalizar;
end;
implementation
{ TProdutoOperacaoIncluirController }
function TProdutoOperacaoIncluirController.codigoSinapi(AValue: string)
: IProdutoOperacaoIncluirController;
begin
Result := Self;
FCodigoSinapi := AValue;
end;
constructor TProdutoOperacaoIncluirController.Create;
begin
end;
function TProdutoOperacaoIncluirController.descricao(AValue: string)
: IProdutoOperacaoIncluirController;
begin
Result := Self;
FDescricao := AValue;
end;
destructor TProdutoOperacaoIncluirController.Destroy;
begin
inherited;
end;
procedure TProdutoOperacaoIncluirController.finalizar;
begin
FProdutoModel.Entidade(TTESTPRODUTO.Create);
FProdutoModel.Entidade.CODIGO_SINAPI := FCodigoSinapi;
FProdutoModel.Entidade.DESCRICAO := FDescricao;
FProdutoModel.Entidade.UNIDMEDIDA := FUnidMedida;
FProdutoModel.Entidade.ORIGEM_PRECO := FOrigemPreco;
FProdutoModel.Entidade.PRMEDIO := FPrMedio;
FProdutoModel.Entidade.PRMEDIO_SINAPI := FPrMedioSinap;
FProdutoModel.DAO.Insert(FProdutoModel.Entidade);
end;
class function TProdutoOperacaoIncluirController.New
: IProdutoOperacaoIncluirController;
begin
Result := Self.Create;
end;
function TProdutoOperacaoIncluirController.origemPreco(
AValue: string): IProdutoOperacaoIncluirController;
begin
Result := Self;
FOrigemPreco := AValue;
end;
function TProdutoOperacaoIncluirController.prMedio(
AValue: string): IProdutoOperacaoIncluirController;
begin
Result := Self;
if AValue = EmptyStr then
AValue := '0';
FPrMedio := StrToCurr(AValue);
end;
function TProdutoOperacaoIncluirController.prMedio(
AValue: Currency): IProdutoOperacaoIncluirController;
begin
Result := Self;
FPrMedio := AValue;
end;
function TProdutoOperacaoIncluirController.prMedioSinapi(AValue: string)
: IProdutoOperacaoIncluirController;
begin
Result := Self;
if AValue = EmptyStr then
AValue := '0';
FPrMedioSinap := StrToCurr(AValue);
end;
function TProdutoOperacaoIncluirController.prMedioSinapi(AValue: Currency)
: IProdutoOperacaoIncluirController;
begin
Result := Self;
FPrMedioSinap := AValue;
end;
function TProdutoOperacaoIncluirController.produtoModel(AValue: IProdutoModel)
: IProdutoOperacaoIncluirController;
begin
Result := Self;
FProdutoModel := AValue;
end;
function TProdutoOperacaoIncluirController.unidMedida(AValue: string)
: IProdutoOperacaoIncluirController;
begin
Result := Self;
FUnidMedida := AValue;
end;
end.
|
PROGRAM JunkMail (Letters, (* The file to write the letters to *)
Addresses, (* contains the list of sendees' addresses *)
Senderinfo, (* the address of the sender *)
LetterBody, (* the body of the letter *)
Output); (* standard output *)
(****************************************************************************
Author: Scott Janousek Due: Fri April 16, 1993
Student ID: 4361106 Section: 1 MWF 10:10
Program Assignment 4a Instructor: Jeff Clouse
Program Desciption: This Program creates Junk Mail which can be sent out to
specific people who are on the mailing List. This program has been modified
by implementing Procedures to process the Information and preform the
necessary formatting of the JunkMail.
*****************************************************************************)
CONST
NumLeadingLines = 5; (* blank lines at the beginning of the letter *)
NumClosingLines = 5; (* blank lines at the end of the letter *)
DoubleSpace = 2; (* blank lines in a double space *)
SingleSpace = 1; (* blank lines in a single space *)
BigIndent = 40; (* number of spaces for indenting the sendee's
address and the closing *)
SmallIndent = 5; (* number of spaces for indenting the sender's
address and the body of the letter *)
Greeting = 'Dear Esteemed Person With Taste,';
Closing = 'Truly Yours,';
AddressLength = 3; (* length of the sender's address *)
NameLength = 1; (* length of the sendee's name *)
IndentChar = ' '; (* character used as indentation space *)
Separator = '-'; (* character to separate different letters *)
NumSeparators = 70; (* number o those characters to print *)
VAR
Letters, (* the file to write the letters to *)
Addresses, (* contains the list of sendees' addresses *)
Senderinfo, (* the address of the sender *)
LetterBody : (* the body of the letter *)
Text;
(**********************************************************************)
PROCEDURE WriteBlankLines (
VAR ToFile: Text; (* the file to write the blanks to *)
NumLines: Integer (* the number of blanks to write *)
);
(* Generate the appropriate number of blank lines in the specified file. *)
VAR
i : Integer;
BEGIN (* PROCEDURE WriteBlankLines *)
FOR i := 1 TO NumLines DO
Writeln (ToFile);
END; (* PROCEDURE WriteBlankLines *)
(**********************************************************************)
PROCEDURE WriteMultipleCharacters (
VAR ToFile: Text; (* the file to write to *)
TheChar: Char; (* The character to be printed *)
NumTimes: Integer (* the number of times to print the character *)
);
(* Print out the specified character the specified number of times
to the specified file. *)
VAR
i : Integer;
BEGIN (* PROCEDURE WriteMultipleCharacters *)
FOR i := 1 TO NumTimes DO
Write (ToFile, TheChar);
END; (* PROCEDURE WriteMultipleCharacters *)
(**********************************************************************)
PROCEDURE CopyOneLine (
VAR ToFile, (* The file to copy to *)
FromFile: Text (* the file to copy from *)
);
(* Copy one line of the file FromFile to the file ToFile. It
assumes that the reading marker for FromFile is at the beginning
of the line. After the procedure copies the line, it will leave
the reading marker at the beginning of the next line in FromFile,
and the writing marker at the beginning of the next line in
ToFile. *)
VAR
Ch : char;
BEGIN (* PROCEDURE CopyOneLine *)
WHILE NOT (EOLN (FromFile)) DO
BEGIN (* WHILE NOT EOLN *)
Read (FromFile, Ch);
Write (ToFile, Ch);
END; (* WHILE NOT EOLN *)
Writeln (ToFile);
Readln (FromFile);
END; (* PROCEDURE CopyOneLine *)
(**********************************************************************)
PROCEDURE CopyFileWithIndentation (
VAR ToFile, (* The file to copy to *)
FromFile: Text; (* The file to copy from *)
Indentation: Integer (* the amount of indentation *)
);
(* Copy the entire file FromFile to the file ToFile. The file
FromFile will be indented by the amount specified. *)
VAR
Ch : char;
BEGIN (* PROCEDURE CopyFileWithIndentation *)
Reset (FromFile);
WHILE NOT (EOF (FromFile)) DO
BEGIN (* WHILE NOT EOF *)
WriteMultipleCharacters (ToFile, IndentChar, Indentation);
CopyOneLine (ToFile, FromFile);
END; (* WHILE NOT EOF *)
END; (* PROCEDURE CopyFileWithIndentation *)
(**********************************************************************)
PROCEDURE CopyLinesWithIndentation(
VAR ToFile, (* The file to copy to *)
FromFile: Text; (* the file to copy from *)
NumLines, (* the number of lines to copy *)
Indentation: Integer (* the amount of indentation *)
);
(* Copy the specified number of lines from FromFile to ToFile.
Indent those lines by the specified amount. *)
VAR
i: integer;
BEGIN (* PROCEDURE CopyLinesWithIndentation *)
FOR i:= 1 TO NumLines DO
BEGIN
WriteMultipleCharacters (ToFile, IndentChar, Indentation);
CopyOneLine (ToFile, FromFile);
END;
END; (* PROCEDURE CopyLinesWithIndentation *)
(**********************************************************************)
PROCEDURE AdvanceReadingMarker (
VAR TheFile: Text (* the file in which to move the reading marker *)
);
(* Move the reading marker to the beginning of the next line in the
specified file. Be careful of end-of-file. *)
BEGIN (* PROCEDURE AdvanceReadingMarker *)
IF NOT (EOF (TheFile)) THEN Readln (TheFile);
END; (* PROCEDURE AdvanceReadingMarker *)
(**********************************************************************)
PROCEDURE WriteGreeting (
VAR ToFile: Text; (* the file in which to write the greeting *)
Indentation: Integer (* the amount to indent by *)
);
(* Write a greeting to the file, indented by the specified amount. *)
BEGIN (* PROCEDURE WriteGreeting *)
WriteMultipleCharacters (ToFile, IndentChar, Indentation);
Writeln (ToFile, Greeting);
END; (* PROCEDURE WriteGreeting *)
(**********************************************************************)
PROCEDURE WriteClosing (
VAR ToFile : Text; (* the file in which to write the closing *)
Indentation: Integer (* the amount to indent by *)
);
(* Write a closing to the file, indented by the specified amount. *)
BEGIN (* PROCEDURE WriteClosing *)
WriteMultipleCharacters (ToFile, IndentChar, Indentation);
Writeln (ToFile, Closing);
END; (* PROCEDURE WriteClosing *)
(**********************************************************************)
(* *)
(* M A I N P R O G R A M *)
(* *)
(**********************************************************************)
BEGIN (***** PROGRAM JunkMail *****)
(* set up the file letters to be written to *)
Rewrite (Letters);
(* set up the file addresses to be read from *)
Reset (Addresses);
(* set up the file letterbody to be read from *}
Reset (SenderInfo);
(* as long as there are addresses, produce letters *)
WHILE NOT EOF (Addresses) DO
BEGIN
(* Write out the leading blank lines *)
WriteBlankLines(Letters, NumLeadingLines);
(* Write out the Sender's address, which is the entire contents
of SenderInfo, indented BigIndent spaces *)
CopyFileWithIndentation(Letters, SenderInfo, BigIndent);
(* Write out two blank lines *)
WriteBlankLines(Letters, DoubleSpace);
(* Write out the Sendee's address, which is three lines from
Addresses, indented by SmallIndent spaces *)
CopyLinesWithIndentation(
Letters, Addresses, AddressLength, SmallIndent);
(* Because there are blank lines separating the addresses, move
the reading marker passed that, but be careful when the marker
is on end-of-file *)
AdvanceReadingMarker(Addresses);
(* Write out one blank line *)
WriteBlankLines(Letters, SingleSpace);
(* Write out the Greeting, indented SmallIndent spaces *)
WriteGreeting(Letters, SmallIndent);
(* Write out one blank line *)
WriteBlankLines(Letters, SingleSpace);
Reset (LetterBody);
(* Write out the letter body, which is the entire contents of
LetterBody, indented by SmallIndent spaces *)
CopyFileWithIndentation(Letters, LetterBody, SmallIndent);
(* write out two blank lines *)
WriteBlankLines(Letters, DoubleSpace);
(* write out the closing, indented BigIndent spaces *)
WriteClosing (Letters, BigIndent);
(* write out two blank lines *)
WriteBlankLines(Letters, DoubleSpace);
(* write out the Sendee's name, which is the first line of
SenderInfo, indented by BigIndent spaces *)
Reset(SenderInfo); (* because the name starts at the top of file *)
CopyLinesWithIndentation (Letters, SenderInfo, NameLength, BigIndent);
(* write out the closing blank lines *)
WriteBlankLines(Letters, NumClosingLines);
(* write out the letter separator *)
WriteMultipleCharacters(Letters, Separator, NumSeparators);
Writeln(Letters) (* carriage return after the dashes *)
END (* WHILE NOT EOF(Addresses) DO *)
END. (***** PROGRAM JunkMail *****)
|
unit UFrmCadastroPais;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFrmCRUD, Menus, Buttons, StdCtrls, ExtCtrls
, UPais
, URegraCRUDPais
, UUtilitarios
;
type
TFrmCadastroPais = class(TFrmCRUD)
gbInformacoes: TGroupBox;
edNome: TLabeledEdit;
protected
FPAIS : TPAIS;
FRegraCRUDPais : TRegraCRUDPais;
procedure Inicializa; override;
procedure PreencheEntidade; override;
procedure PreencheFormulario; override;
procedure PosicionaCursorPrimeiroCampo; override;
procedure HabilitaCampos(const ceTipoOperacaoUsuario: TTipoOperacaoUsuario); override;
public
{ Public declarations }
end;
var
FrmCadastroPais: TFrmCadastroPais;
implementation
{$R *.dfm}
{ TFrmCadastroPais }
uses
UOpcaoPesquisa
, UEntidade
;
procedure TFrmCadastroPais.HabilitaCampos(
const ceTipoOperacaoUsuario: TTipoOperacaoUsuario);
begin
inherited;
gbInformacoes.Enabled := ceTipoOperacaoUsuario in [touInsercao, touAtualizacao];
end;
procedure TFrmCadastroPais.Inicializa;
begin
inherited;
DefineEntidade(@FPAIS, TPAIS);
DefineRegraCRUD(@FRegraCRUDPais, TRegraCRUDPais);
AdicionaOpcaoPesquisa(TOpcaoPesquisa.Create
.DefineVisao(VW_PAIS)
.DefineNomeCampoRetorno(VW_PAIS_ID)
.AdicionaFiltro(VW_PAIS_NOME)
.DefineNomePesquisa(STR_PAIS));
AdicionaOpcaoPesquisa(TOpcaoPesquisa.Create
.DefineVisao(VW_PAIS)
.DefineNomeCampoRetorno(VW_PAIS_ID)
.AdicionaFiltro(VW_PAIS_NOME)
.DefineNomePesquisa('Pesquisa X'));
end;
procedure TFrmCadastroPais.PosicionaCursorPrimeiroCampo;
begin
inherited;
edNome.SetFocus;
end;
procedure TFrmCadastroPais.PreencheEntidade;
begin
inherited;
FPAIS.NOME := edNome.Text;
end;
procedure TFrmCadastroPais.PreencheFormulario;
begin
inherited;
edNome.Text := FPAIS.NOME;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLTextureCombiners<p>
Texture combiners setup utility functions.<p>
<b>History : </b><font size=-1><ul>
<li>02/04/07 - DaStr - Added $I GLScene.inc
<li>17/12/03 - EG - Alpha and RGB channels separate combination now supported
<li>23/05/03 - EG - All tex units now accepted as target
<li>22/05/03 - EG - Fixed GL_ADD_SIGNED_ARB parsing, better error reporting
<li>16/05/03 - EG - Creation
</ul></font>
}
unit GLTextureCombiners;
interface
{$I GLScene.inc}
uses SysUtils;
type
// ETextureCombinerError
//
ETextureCombinerError = class (Exception)
;
{: Parses a TC text description and setups combiners accordingly.<p>
*experimental*<br>
Knowledge of texture combiners is a requirement<br>
Syntax: pascal-like, one instruction per line, use '//' for comment.<p>
Examples:<ul>
<li>Tex1:=Tex0; // replace texture 1 with texture 0
<li>Tex1:=Tex0+Tex1; // additive blending between textures 0 and 1
<li>Tex1:=Tex0-Tex1; // subtractive blending between textures 0 and 1
<li>Tex1:=Tex0*Tex1; // modulation between textures 0 and 1
<li>Tex1:=Tex0+Tex1-0.5; // signed additive blending between textures 0 and 1
<li>Tex1:=Interpolate(Tex0, Tex1, PrimaryColor); // interpolation between textures 0 and 1 using primary color as factor
<li>Tex1:=Dot3(Tex0, Tex1); // dot3 product between textures 0 and 1
</ul><p>
Accepted tokens:<ul>
<li>Tex0, Tex1, etc. : texture unit
<li>PrimaryColor, Col : the primary color
<li>ConstantColor, EnvCol : texture environment constant color
</ul><br>
Tokens can be qualified with '.a' or '.alpha' to specify the alpha channel
explicitly, and '.rgb' to specify color channels (default). You cannot mix
alpha and rgb tokens in the same line.
}
procedure SetupTextureCombiners(const tcCode : String);
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
uses Classes, OpenGL1x,OpenGLTokens;
// TCAssertCheck
//
procedure TCAssertCheck(const b : Boolean; const errMsg : String);
begin
if not b then
raise ETextureCombinerError.Create(errMsg);
end;
// RemoveSpaces
//
function RemoveSpaces(const str : String) : String;
var
c : Char;
i, p, n : Integer;
begin
n:=Length(str);
SetLength(Result, n);
p:=1;
for i:=1 to n do begin
c:=str[i];
if c<>' ' then begin
Result[p]:=c;
Inc(p);
end;
end;
SetLength(Result, p-1);
end;
// ProcessTextureCombinerArgument
//
procedure ProcessTextureCombinerArgument(arg : String; sourceEnum, operandEnum : Integer;
const dest : String);
var
sourceValue, operandValue, n, p : Integer;
origArg, qualifier : String;
begin
origArg:=arg;
p:=Pos('.', arg);
if p>0 then begin
qualifier:=Copy(arg, p+1, MaxInt);
arg:=Copy(arg, 1, p-1);
end else qualifier:='rgb';
if qualifier='rgb' then begin
if Copy(arg, 1, 1)='~' then begin
operandValue:=GL_ONE_MINUS_SRC_COLOR;
arg:=Copy(arg, 2, MaxInt);
end else if Copy(arg, 1, 2)='1-' then begin
operandValue:=GL_ONE_MINUS_SRC_COLOR;
arg:=Copy(arg, 3, MaxInt);
end else operandValue:=GL_SRC_COLOR;
end else if Copy(qualifier, 1, 1)='a' then begin
if Copy(arg, 1, 1)='~' then begin
operandValue:=GL_ONE_MINUS_SRC_ALPHA;
arg:=Copy(arg, 2, MaxInt);
end else if Copy(arg, 1, 2)='1-' then begin
operandValue:=GL_ONE_MINUS_SRC_ALPHA;
arg:=Copy(arg, 3, MaxInt);
end else operandValue:=GL_SRC_ALPHA;
end else operandValue:=0;
sourceValue:=0;
if (arg='tex') or (arg=dest) then
sourceValue:=GL_TEXTURE
else if ((arg='tex0') and (dest='tex1')) or ((arg='tex1') and (dest='tex2'))
or ((arg='tex2') and (dest='tex3')) then
sourceValue:=GL_PREVIOUS_ARB
else if (arg='col') or (arg='col0') or (arg='primarycolor') then
sourceValue:=GL_PRIMARY_COLOR_ARB
else if (arg='envcol') or (arg='constcol') or (arg='constantcolor') then
sourceValue:=GL_CONSTANT_COLOR_ARB
else if Copy(arg, 1, 3)='tex' then begin
TCAssertCheck(GL_ARB_texture_env_crossbar or GL_NV_texture_env_combine4,
'Requires GL_ARB_texture_env_crossbar or NV_texture_env_combine4');
n:=StrToIntDef(Copy(arg, 4, MaxInt), -1);
if n in [0..7] then
sourceValue:=GL_TEXTURE0_ARB+n;
end;
TCAssertCheck((operandValue>0) and (sourceValue>0),
'invalid argument : "'+origArg+'"');
glTexEnvf(GL_TEXTURE_ENV, sourceEnum , sourceValue);
glTexEnvf(GL_TEXTURE_ENV, operandEnum, operandValue);
CheckOpenGLError;
end;
// ProcessTextureCombinerLine
//
procedure ProcessTextureCombinerLine(const tcLine : String);
var
line, dest, arg1, arg2, arg3, funcname : String;
p : Integer;
destEnum, operEnum : Integer;
sourceBaseEnum, operandBaseEnum : Integer;
sl : TStrings;
begin
// initial filtering
line:=LowerCase(RemoveSpaces(Trim(tcLine)));
if Copy(line, 1, 2)='//' then Exit;
if line='' then Exit;
if line[Length(line)]=';' then begin
line:=Trim(Copy(line, 1, Length(line)-1));
if line='' then Exit;
end;
// Parse destination
p:=Pos(':=', line);
dest:=Copy(line, 1, p-1);
line:=Copy(line, p+2, MaxInt);
p:=Pos('.', dest);
destEnum:=GL_COMBINE_RGB_ARB;
sourceBaseEnum:=GL_SOURCE0_RGB_ARB;
operandBaseEnum:=GL_OPERAND0_RGB_ARB;
if p>0 then begin
if Copy(dest, p+1, 1)='a' then begin
destEnum:=GL_COMBINE_ALPHA_ARB;
sourceBaseEnum:=GL_SOURCE0_ALPHA_ARB;
operandBaseEnum:=GL_OPERAND0_ALPHA_ARB;
end;
dest:=Copy(dest, 1, p-1);
end;
if Copy(dest, 1, 3)='tex' then begin
p:=StrToIntDef(Copy(dest, 4, MaxInt), -1);
TCAssertCheck(p>=0, 'Invalid destination texture unit "'+dest+'"');
glActiveTextureARB(GL_TEXTURE0_ARB+p)
end else TCAssertCheck(False, 'Invalid destination "'+dest+'"');
// parse combiner operator
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB);
CheckOpenGLError;
operEnum:=0;
arg1:=''; arg2:=''; arg3:='';
p:=Pos('+', line);
if p>0 then begin
// ADD & ADD_SIGNED operators
if Copy(line, Length(line)-3, 4)='-0.5' then begin
operEnum:=GL_ADD_SIGNED_ARB;
SetLength(line, Length(line)-4);
end else operEnum:=GL_ADD;
arg1:=Copy(line, 1, p-1);
arg2:=Copy(line, p+1, MaxInt);
end;
p:=Pos('*', line);
if p>0 then begin
// MODULATE operator
operEnum:=GL_MODULATE;
arg1:=Copy(line, 1, p-1);
arg2:=Copy(line, p+1, MaxInt);
line:='';
end;
p:=Pos('(', line);
if p>0 then begin
// function
sl:=TStringList.Create;
try
funcName:=Copy(line, 1, p-1);
p:=Pos('(', line);
line:=Copy(line, p+1, MaxInt);
p:=Pos(')', line);
sl.CommaText:=Copy(line, 1, p-1);
if funcName='interpolate' then begin
// INTERPOLATE operator
TCAssertCheck(sl.Count=3, 'Invalid parameter count');
operEnum:=GL_INTERPOLATE_ARB;
arg1:=sl[0];
arg2:=sl[1];
arg3:=sl[2];
end else if funcName='dot3' then begin
// DOT3 operator
TCAssertCheck(sl.Count=2, 'Invalid parameter count');
TCAssertCheck(GL_ARB_texture_env_dot3, 'Requires GL_ARB_texture_env_dot3');
operEnum:=GL_DOT3_RGB_ARB;
arg1:=sl[0];
arg2:=sl[1];
end else TCAssertCheck(False, 'Invalid function "'+funcName+'"');
finally
sl.Free;
end;
line:='';
end;
p:=Pos('-', line);
if p>0 then begin
// SUBTRACT operator
operEnum:=GL_SUBTRACT_ARB;
arg1:=Copy(line, 1, p-1);
arg2:=Copy(line, p+1, MaxInt);
line:='';
end;
if operEnum=0 then begin
// REPLACE by default
operEnum:=GL_REPLACE;
arg1:=line;
end;
glTexEnvi(GL_TEXTURE_ENV, destEnum, operEnum);
CheckOpenGLError;
// parse arguments
if arg1<>'' then
ProcessTextureCombinerArgument(arg1, sourceBaseEnum, operandBaseEnum, dest);
if arg2<>'' then
ProcessTextureCombinerArgument(arg2, sourceBaseEnum+1, operandBaseEnum+1, dest);
if arg3<>'' then
ProcessTextureCombinerArgument(arg3, sourceBaseEnum+2, operandBaseEnum+2, dest);
glActiveTextureARB(GL_TEXTURE0_ARB);
end;
// SetupTextureCombiners
//
procedure SetupTextureCombiners(const tcCode : String);
var
i : Integer;
sl : TStringList;
begin
TCAssertCheck(GL_ARB_texture_env_combine, 'Requires GL_ARB_texture_env_combine support');
sl:=TStringList.Create;
try
sl.Text:=tcCode;
for i:=0 to sl.Count-1 do
ProcessTextureCombinerLine(sl[i]);
finally
sl.Free;
end;
end;
end.
|
unit Backend.Google.Connector;
interface
uses
Data.Articles,
Data.API.Google,
Core.Articles.Gen,
JOSE.Core.JWT,
JOSE.Core.JWK,
JOSE.Core.JWS,
JOSE.Core.JWA,
JOSE.Types.Bytes,
System.IOUtils,
System.DateUtils,
System.SysUtils,
System.Net.HTTPClient,
System.Net.HTTPClientComponent,
System.Net.URLClient,
System.Classes,
System.JSON,
System.Generics.Collections;
type
TSAIDGoogleArticle = class(TInterfacedObject, IGoogleArticle)
private
FCaption: string;
FCategories: TStringList;
FLanguage: TLanguage;
FSentences: TList<ISentence>;
FSentiment: TSentiment;
FSource: TSource;
public
constructor Create;
destructor Destroy; override;
function GetCaption: string;
function GetCategories(const AIndex: Integer): string;
function GetCategoryCount: Integer;
function GetLanguage: TLanguage;
function GetSentenceCount: Integer;
function GetSentences(const AIndex: Integer): ISentence;
function GetSentiment: TSentiment;
function GetSource: TSource;
end;
TSAIDSentence = class(TInterfacedObject, ISentence)
private
FOffset: Integer;
FTokens: TList<IToken>;
public
constructor Create;
destructor Destroy; override;
function GetOffset: Integer;
function GetTokenCount: Integer;
function GetTokens(const AIndex: Integer): IToken;
end;
TSAIDToken = class(TInterfacedObject, IToken)
private
FCase: TCase;
FDependency: IToken;
FGender: TGender;
FLabel: TLabel;
FNumber: TNumber;
FOffset: Integer;
FPerson: TPerson;
FTag: TTag;
FTense: TTense;
FText: string;
FLemma: string;
public
function GetCase: TCase;
function GetDependency: IToken;
function GetGender: TGender;
function GetLabel: TLabel;
function GetNumber: TNumber;
function GetOffset: Integer;
function GetPerson: TPerson;
function GetTag: TTag;
function GetTense: TTense;
function GetText: string;
function GetLemma: string;
end;
TGoogleConnector = class
private
function SendReqToGoogle(AAccessToken: string; AArticles: IiPoolArticles)
: TJSONObject;
function ConvertJSONToGoogleArticle(ACaption: string;
AJSONObject: TJSONObject): IGoogleArticle;
public
function AnalyzeArticles(AInput: IiPoolArticles): IArticle;
end;
TTokenGenerator = class
function GenerateJWT: TJOSEBytes;
function GenerateAccessToken(AJWT: TJOSEBytes): string;
end;
implementation
{ TGoogleConnector }
function TGoogleConnector.AnalyzeArticles(AInput: IiPoolArticles): IArticle;
var
LJWT: TJOSEBytes;
LTokenGenerator: TTokenGenerator;
LAccessToken: string;
begin
LTokenGenerator := TTokenGenerator.Create;
LJWT := LTokenGenerator.GenerateJWT;
LAccessToken := LTokenGenerator.GenerateAccessToken(LJWT);
FreeAndNil(LTokenGenerator);
SendReqToGoogle(LAccessToken, AInput);
end;
function TGoogleConnector.ConvertJSONToGoogleArticle(ACaption: string;
AJSONObject: TJSONObject): IGoogleArticle;
var
LCategoriesJSON, LSentencesJSON, LTokensJSON: TJSONArray;
LSentenceJSON, LTokenJSON: TJSONObject;
i, j, k, l, m: Integer;
begin
Result := TSAIDGoogleArticle.Create;
(Result as TSAIDGoogleArticle).FCaption := ACaption;
// Read categories
LCategoriesJSON := AJSONObject.Values['categories'] as TJSONArray;
for i := 0 to LCategoriesJSON.Count - 1 do
(Result as TSAIDGoogleArticle).FCategories.Add
(LCategoriesJSON.Items[i].Value);
(Result as TSAIDGoogleArticle).FLanguage := TLanguage.laEN;
// Read sentences and tokens
LSentencesJSON := AJSONObject.Values['sentences'] as TJSONArray;
j := 0;
for i := 0 to LSentencesJSON.Count - 1 do
begin
(Result as TSAIDGoogleArticle).FSentences.Add(TSAIDSentence.Create);
((Result as TSAIDGoogleArticle).FSentences.Last as TSAIDSentence).FOffset :=
(((LSentencesJSON.Items[i] as TJSONObject).Values['text'] as TJSONObject)
.Values['beginOffset'] as TJSONNumber).Value.ToInteger;
end;
j := 0;
LTokensJSON := AJSONObject.Values['tokens'] as TJSONArray;
for i := 0 to LTokensJSON.Count - 1 do
begin
while ((Result as TSAIDGoogleArticle).FSentences[j] as TSAIDSentence)
.FOffset <= (((LTokensJSON.Items[i] as TJSONObject).Values['text']
as TJSONObject).Values['beginOffset'] as TJSONNumber).Value.ToInteger do
begin
Inc(j);
end;
((Result as TSAIDGoogleArticle).FSentences[j] as TSAIDSentence)
.FTokens.Add(TSAIDToken.Create);
(((Result as TSAIDGoogleArticle).FSentences[j] as TSAIDSentence)
.FTokens.Last as TSAIDToken).FOffset :=
(((LTokensJSON.Items[i] as TJSONObject).Values['text'] as TJSONObject)
.Values['beginOffset'] as TJSONNumber).Value.ToInteger;
(((Result as TSAIDGoogleArticle).FSentences[j] as TSAIDSentence)
.FTokens.Last as TSAIDToken).FText :=
(((LTokensJSON.Items[i] as TJSONObject).Values['text'] as TJSONObject)
.Values['content'] as TJSONString).Value;
(((Result as TSAIDGoogleArticle).FSentences[j] as TSAIDSentence)
.FTokens.Last as TSAIDToken).FTag :=
TTag.Create((((LTokensJSON.Items[i] as TJSONObject).Values['partOfSpeech']
as TJSONObject).Values['tag'] as TJSONString).Value);
end;
for i := 0 to (Result as TSAIDGoogleArticle).FSentences.Count - 1 do
begin
for j := 0 to ((Result as TSAIDGoogleArticle).FSentences[i]
as TSAIDSentence).FTokens.Count - 1 do
begin
k := 0;
for l := 0 to (Result as TSAIDGoogleArticle).FSentences.Count - 1 do
begin
for m := 0 to ((Result as TSAIDGoogleArticle).FSentences[i]
as TSAIDSentence).FTokens.Count - 1 do
begin
if k = (((LTokensJSON.Items[i] as TJSONObject).Values['dependencyEdge']
as TJSONObject).Values['headTokenIndex'] as TJSONNumber)
.Value.ToInteger then
begin
Exit;
end;
Inc(k);
end;
end;
(((Result as TSAIDGoogleArticle).FSentences[i] as TSAIDSentence)
.FTokens[j] as TSAIDToken).FDependency := Result.Sentences[l].Tokens[m];
end;
end;
end;
function TGoogleConnector.SendReqToGoogle(AAccessToken: string;
AArticles: IiPoolArticles): TJSONObject;
var
i: Integer;
LJSONReq: TJSONObject;
LObj, LFeat: TJSONObject;
HTTPClient: TNetHTTPClient;
LOutputStream: TStream;
LHeaders: TNetHeaders;
LOutputJSON: TJSONObject;
LStreamReader: TStreamReader;
LArticle: IArticle;
LGarticle: IGoogleArticle;
begin
HTTPClient := TNetHTTPClient.Create(nil);
LJSONReq := TJSONObject.Create;
LJSONReq.AddPair('encodingType', 'UTF8');
LObj := TJSONObject.Create;
LObj.AddPair('type', 'PLAIN_TEXT');
LJSONReq.AddPair('document', LObj);
LFeat := TJSONObject.Create;
LFeat.AddPair('extractSyntax', TJSONBool.Create(true));
LFeat.AddPair('extractDocumentSentiment', TJSONBool.Create(true));
LJSONReq.AddPair('features', LFeat);
SetLength(LHeaders, 1);
LHeaders[0].Value := 'Bearer ' + AAccessToken;
LHeaders[0].Name := 'Authorization';
for i := 0 to AArticles.Count - 1 do
begin
LOutputStream := TStringStream.Create;
LObj.AddPair('content', AArticles.Articles[i].Content);
HTTPClient.Post('https://language.googleapis.com/v1/documents:annotateText',
TStringStream.Create(LJSONReq.ToString), LOutputStream, LHeaders);
LStreamReader := TStreamReader.Create(LOutputStream);
LOutputJSON := TJSONObject.ParseJSONValue(LStreamReader.ReadToEnd)
as TJSONObject;
FreeAndNil(LStreamReader);
FreeAndNil(LOutputStream);
LGarticle := ConvertJSONToGoogleArticle(AArticles.Articles[i].Heading,
LOutputJSON);
LArticle := TArticle.Create(LGarticle);
end;
end;
{ TTokenGenerator }
function TTokenGenerator.GenerateAccessToken(AJWT: TJOSEBytes): string;
var
HTTPClient: TNetHTTPClient;
LStrStream: TStream;
LResponse: IHTTPResponse;
LJSONResponse: TJSONObject;
LHeaders: TNetHeaders;
begin
HTTPClient := TNetHTTPClient.Create(nil);
LStrStream := TStringStream.Create
('grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion='
+ AJWT.AsString);
SetLength(LHeaders, 1);
LHeaders[0].Name := 'Content-Type';
LHeaders[0].Value := 'application/x-www-form-urlencoded';
LResponse := HTTPClient.Post('https://www.googleapis.com/oauth2/v4/token',
LStrStream, nil, LHeaders);
LJSONResponse := TJSONObject.ParseJSONValue(LResponse.ContentAsString)
as TJSONObject;
Result := LJSONResponse.Values['access_token'].Value;
FreeAndNil(HTTPClient);
FreeAndNil(LJSONResponse);
FreeAndNil(LStrStream);
end;
function TTokenGenerator.GenerateJWT: TJOSEBytes;
var
LToken: TJWT;
LKey: TJWK;
LJWS: TJWS;
LDT: TDateTime;
begin
LToken := TJWT.Create;
LToken.Claims.SetClaimOfType('iss',
'backend@said-205321.iam.gserviceaccount.com');
LToken.Claims.SetClaimOfType('scope',
'https://www.googleapis.com/auth/cloud-language');
LToken.Claims.Audience := 'https://www.googleapis.com/oauth2/v4/token';
LToken.Claims.IssuedAt := Now;
LDT := Now;
IncMinute(LDT, 30);
LToken.Claims.Expiration := LDT;
LKey := TJWK.Create(TFile.ReadAllBytes('kk.txt'));
LJWS := TJWS.Create(LToken);
LJWS.Sign(LKey, TJOSEAlgorithmId.RS256);
Result := LJWS.CompactToken;
end;
{ TSAIDGoogleArticle }
constructor TSAIDGoogleArticle.Create;
begin
FCategories := TStringList.Create;
FSentences := TList<ISentence>.Create;
end;
destructor TSAIDGoogleArticle.Destroy;
begin
FCategories.Free;
FSentences.Free;
inherited;
end;
function TSAIDGoogleArticle.GetCaption: string;
begin
Result := FCaption;
end;
function TSAIDGoogleArticle.GetCategories(const AIndex: Integer): string;
begin
Result := FCategories[AIndex];
end;
function TSAIDGoogleArticle.GetCategoryCount: Integer;
begin
Result := FCategories.Count;
end;
function TSAIDGoogleArticle.GetLanguage: TLanguage;
begin
Result := FLanguage;
end;
function TSAIDGoogleArticle.GetSentenceCount: Integer;
begin
Result := FSentences.Count;
end;
function TSAIDGoogleArticle.GetSentences(const AIndex: Integer): ISentence;
begin
Result := FSentences[AIndex];
end;
function TSAIDGoogleArticle.GetSentiment: TSentiment;
begin
Result := FSentiment;
end;
function TSAIDGoogleArticle.GetSource: TSource;
begin
Result := FSource;
end;
{ TSAIDSentence }
constructor TSAIDSentence.Create;
begin
inherited;
FTokens := TList<IToken>.Create;
end;
destructor TSAIDSentence.Destroy;
begin
FTokens.Free;
inherited;
end;
function TSAIDSentence.GetOffset: Integer;
begin
Result := FOffset;
end;
function TSAIDSentence.GetTokenCount: Integer;
begin
Result := FTokens.Count;
end;
function TSAIDSentence.GetTokens(const AIndex: Integer): IToken;
begin
Result := FTokens[AIndex];
end;
{ TSAIDToken }
function TSAIDToken.GetCase: TCase;
begin
Result := FCase;
end;
function TSAIDToken.GetDependency: IToken;
begin
Result := FDependency;
end;
function TSAIDToken.GetGender: TGender;
begin
Result := FGender;
end;
function TSAIDToken.GetLabel: TLabel;
begin
Result := FLabel;
end;
function TSAIDToken.GetLemma: string;
begin
Result := FLemma;
end;
function TSAIDToken.GetNumber: TNumber;
begin
Result := FNumber;
end;
function TSAIDToken.GetOffset: Integer;
begin
Result := FOffset;
end;
function TSAIDToken.GetPerson: TPerson;
begin
Result := FPerson;
end;
function TSAIDToken.GetTag: TTag;
begin
Result := FTag;
end;
function TSAIDToken.GetTense: TTense;
begin
Result := FTense;
end;
function TSAIDToken.GetText: string;
begin
Result := FText;
end;
end.
|
// Wheberson Hudson Migueletti, em Brasília.
// Internet : http://www.geocities.com/whebersite
// E-mail : whebersite@zipmail.com.br
// Referência: [1] PCX - Technical Reference Manual
// Codificação/Descodificação de arquivos ".pcx" (PC Paintbrush)
unit DelphiPCX;
interface
uses Windows, SysUtils, Classes, Graphics, DelphiImage;
type
TPCXRGBType= (Red, Green, Blue);
TPCXRGBColor= array[TPCXRGBType] of Byte;
TPCXPaleta16= array[0..15] of TPCXRGBColor;
TPCXPaleta256= array[0..255] of TPCXRGBColor;
PPCXHeader= ^TPCXHeader;
TPCXHeader= packed record
Manufacturer: Byte; // 10
Version : Byte; // 0, 2, 3, e 5
Enconding : Byte;
BitsPerPixel: Byte; // Bits per pixel per plane (1= 4-bit, 8= 8-bit)
XMin : Word;
YMin : Word;
XMax : Word;
YMax : Word;
HRes : Word;
VRes : Word;
ColorMap : TPCXPaleta16;
Reserved : Byte;
NPlanes : Byte; // 4=4-bit, 1=8-bit
BytesPerLine: Word; // Bytes per scan line per plane
PaletteInfo : Word; // 1=color/BW, 2=grayscale
Filler : array[0..57] of Byte;
end;
TPCXEncoder= class
private
Old : Byte;
Count: Byte;
protected
BitsPerPixel : Integer;
BytesPerLine : Integer;
PaletteLength: Integer;
Stream : TStream;
procedure WritePalette (Bitmap: TBitmap);
procedure Flush;
procedure WriteValue (Value, Count: Byte);
procedure EncodeValue (Current: Byte);
procedure WriteImage24b (Bitmap: TBitmap);
procedure WriteImage8b (Bitmap: TBitmap);
public
constructor Create (AStream: TStream);
procedure Encode (Bitmap: TBitmap);
end;
TPCX= class (TBitmap)
protected
BitsPerPixel: Byte;
NPlanes : Byte;
Version : Byte;
BytesPerLine: Integer;
LogPalette : TMaxLogPalette;
Stream : TStream;
procedure Read (var Buffer; Count: Integer);
procedure InitializePalette;
procedure SetPalette;
procedure DumpHeader;
procedure DumpPalette;
procedure Dump24b;
procedure Dump8b;
procedure Dump4b;
procedure DumpImage;
procedure ReadStream (AStream: TStream);
public
function IsValid (const FileName: String): Boolean;
procedure LoadFromStream (Stream: TStream); override;
procedure LoadFromFile (const FileName: String); override;
end;
implementation
const
cMask= $C0; // 11000000
type
PLine= ^TLine;
TLine= array[0..0] of Byte;
constructor TPCXEncoder.Create (AStream: TStream);
begin
inherited Create;
Stream:= AStream;
end;
procedure TPCXEncoder.Encode (Bitmap: TBitmap);
var
BitmapInfo: Windows.TBitmap;
Header : TPCXHeader;
begin
if not Bitmap.Empty then begin
GetObject (Bitmap.Handle, SizeOf (Windows.TBitmap), @BitmapInfo);
FillChar (Header, SizeOf (TPCXHeader), #0);
with Header do begin
if BitmapInfo.bmBitsPixel = 24 then begin
BitsPerPixel:= 8;
NPlanes := 3;
end
else begin
BitsPerPixel:= BitmapInfo.bmBitsPixel;
NPlanes := 1;
end;
Manufacturer:= 10;
Version := 5;
Enconding := 1;
XMin := 0;
YMin := 0;
XMax := Bitmap.Width-1;
YMax := Bitmap.Height-1;
BytesPerLine:= BytesPerScanLine (Bitmap.Width, BitmapInfo.bmBitsPixel, 32) div NPlanes; // Bytes per scan line per plane
PaletteInfo := 1;
end;
Stream.Write (Header, SizeOf (TPCXHeader));
BitsPerPixel := BitmapInfo.bmBitsPixel;
PaletteLength:= 1 shl BitsPerPixel;
BytesPerLine := BytesPerScanLine (Bitmap.Width, BitmapInfo.bmBitsPixel, 32);
if BitsPerPixel = 24 then
WriteImage24b (Bitmap)
else
WriteImage8b (Bitmap);
WritePalette (Bitmap);
end;
end;
procedure TPCXEncoder.WritePalette (Bitmap: TBitmap);
var
SaveIgnorePalette: Boolean;
I : Byte;
Palette : array[Byte] of TPaletteEntry;
Header : TPCXHeader;
begin
if BitsPerPixel <= 8 then begin
SaveIgnorePalette := Bitmap.IgnorePalette;
Bitmap.IgnorePalette:= False; // Do contrário pode vir uma paleta vazia !!!
FillChar (Palette, PaletteLength*SizeOf (TPaletteEntry), #0);
if GetPaletteEntries (Bitmap.Palette, 0, PaletteLength, Palette) = 0 then
if PaletteLength = 2 then
FillChar (Palette[1], 3, #255)
else
GetPaletteEntries (GetStockObject (DEFAULT_PALETTE), 0, PaletteLength, Palette);
Bitmap.IgnorePalette:= SaveIgnorePalette;
if BitsPerPixel <= 4 then begin
Stream.Seek (0, soFromBeginning);
Stream.Read (Header, SizeOf (TPCXHeader));
for I:= 0 to PaletteLength-1 do begin
Header.ColorMap[I, Red] := Palette[I].peRed;
Header.ColorMap[I, Green]:= Palette[I].peGreen;
Header.ColorMap[I, Blue] := Palette[I].peBlue;
end;
Stream.Seek (0, soFromBeginning);
Stream.Write (Header, SizeOf (TPCXHeader));
end
else begin
I:= 12;
Stream.Seek (0, soFromEnd);
Stream.Write (I, 1);
for I:= 0 to PaletteLength-1 do begin
Stream.Write (Palette[I].peRed, 1);
Stream.Write (Palette[I].peGreen, 1);
Stream.Write (Palette[I].peBlue, 1);
end;
end;
end;
end;
procedure TPCXEncoder.WriteValue (Value, Count: Byte);
begin
if (Count > 1) or ((Count = 1) and (Value >= cMask)) then begin // Valores repetidos ou o valor ultrapassa a "máscara"
Inc (Count, cMask);
Stream.Write (Count, 1);
end;
Stream.Write (Value, 1);
end;
procedure TPCXEncoder.EncodeValue (Current: Byte);
begin
if Current = Old then begin
Inc (Count);
if Count = 63 then begin // if (Count+cMask) = 255 then
WriteValue (Old, Count);
Count:= 0;
end;
end
else begin
if Count > 0 then
WriteValue (Old, Count);
Count:= 1;
Old := Current;
end;
end;
procedure TPCXEncoder.Flush;
begin
if Count > 0 then
WriteValue (Old, Count);
Count:= 0;
end;
procedure TPCXEncoder.WriteImage24b (Bitmap: TBitmap);
type
PLine= ^TLine;
TLine= array[0..0] of Byte;
var
BytesPerPlane: Integer;
X, Y : Integer;
Line : PLine;
begin
Stream.Seek (SizeOf (TPCXHeader), soFromBeginning);
BytesPerPlane:= BytesPerLine div 3;
Line := Bitmap.ScanLine[0];
Count := 1;
X := 0;
Old := Line[X*3 + 2];
for X:= 1 to BytesPerPlane-1 do
EncodeValue (Line[X*3 + 2]);
for X:= 0 to BytesPerPlane-1 do
EncodeValue (Line[X*3 + 1]);
for X:= 0 to BytesPerPlane-1 do
EncodeValue (Line[X*3]);
for Y:= 1 to Bitmap.Height-1 do begin
Line:= Bitmap.ScanLine[Y];
for X:= 0 to BytesPerPlane-1 do
EncodeValue (Line[X*3 + 2]);
for X:= 0 to BytesPerPlane-1 do
EncodeValue (Line[X*3 + 1]);
for X:= 0 to BytesPerPlane-1 do
EncodeValue (Line[X*3]);
end;
Flush;
end;
procedure TPCXEncoder.WriteImage8b (Bitmap: TBitmap);
type
PLine= ^TLine;
TLine= array[0..0] of Byte;
var
X, Y: Integer;
Line: PLine;
begin
Stream.Seek (SizeOf (TPCXHeader), soFromBeginning);
Count:= 1;
Line := Bitmap.ScanLine[0];
Old := Line[0];
for X:= 1 to BytesPerLine-1 do
EncodeValue (Line[X]);
for Y:= 1 to Bitmap.Height-1 do begin
Line:= Bitmap.ScanLine[Y];
for X:= 0 to BytesPerLine-1 do
EncodeValue (Line[X]);
end;
Flush;
end;
//----------------------------------------------------------------------------------------------
procedure TPCX.Read (var Buffer; Count: Integer);
var
Lidos: Integer;
begin
Lidos:= Stream.Read (Buffer, Count);
if Lidos <> Count then
raise EInvalidImage.Create (Format ('PCX read error at %.8xH (%d byte(s) expected, but %d read)', [Stream.Position-Lidos, Count, Lidos]));
end;
procedure TPCX.InitializePalette;
var
Tripla: Word;
Count : Integer;
begin
{ Version: 0 = Version 2.5
2 = Version 2.8 with palette information
3 = Version 2.8 without palette information
5 = Version 3.0 }
if BitsPerPixel <= 4 then begin
if Version <> 3 then begin
// Para evitar de se encontrar uma paleta zerada
Count:= 0;
for Tripla:= 0 to 15 do
Inc (Count, Integer (LogPalette.palPalEntry[Tripla]));
if Count = 0 then
Version:= 3;
end;
end;
if Version = 3 then begin // Não declara paleta
if BitsPerPixel = 1 then begin
FillChar (LogPalette.palPalEntry[0], 3, #$00);
FillChar (LogPalette.palPalEntry[1], 3, #$FF);
end
else
with LogPalette do
GetPaletteEntries (GetStockObject (DEFAULT_PALETTE), 0, palNumEntries, palPalEntry);
end;
end;
procedure TPCX.SetPalette;
begin
Palette:= CreatePalette (PLogPalette (@LogPalette)^);
end;
// NPlanes: 1; BPP: 1, 4, 8, 24
// NPlanes: 4; BPP: 4
// NPlanes: 3; BPP: 24
procedure TPCX.DumpHeader;
var
Tripla: Byte;
Header: TPCXHeader;
begin
Read (Header, SizeOf (TPCXHeader));
if Header.Manufacturer = 10 then begin
Width := (Header.XMax-Header.XMin) + 1;
Height := (Header.YMax-Header.YMin) + 1;
BytesPerLine := Header.BytesPerLine;
NPlanes := Header.NPlanes;
Version := Header.Version;
BitsPerPixel := Header.BitsPerPixel*Header.NPlanes;
IgnorePalette:= BitsPerPixel > 8;
case BitsPerPixel of
1: PixelFormat:= pf1bit;
4: PixelFormat:= pf4bit;
8: PixelFormat:= pf8bit;
else
PixelFormat:= pf24bit;
end;
with LogPalette do begin
FillChar (palPalEntry[0], 256, #0);
palVersion:= $0300;
if BitsPerPixel <= 8 then begin
LogPalette.palNumEntries:= 1 shl BitsPerPixel;
if BitsPerPixel <= 4 then
for Tripla:= 0 to LogPalette.palNumEntries-1 do
with LogPalette.palPalEntry[Tripla] do begin
peRed := Header.ColorMap[Tripla, Red];
peGreen:= Header.ColorMap[Tripla, Green];
peBlue := Header.ColorMap[Tripla, Blue];
end;
end
else
LogPalette.palNumEntries:= 0;
end;
end
else
raise EUnsupportedImage.Create ('Unsupported file format !');
end;
procedure TPCX.DumpPalette;
var
Flag : Byte;
Tripla : Byte;
SavePosition: Integer;
RGB : TPCXRGBColor;
begin
if (BitsPerPixel = 8) and (Stream.Size >= 769) then begin
SavePosition:= Stream.Position;
try
Stream.Seek (-769, soFromEnd);
Read (Flag, 1);
if Flag = 12 then
for Tripla:= 0 to 255 do begin
Read (RGB, SizeOf (TPCXRGBColor));
with LogPalette.palPalEntry[Tripla] do begin
peRed := RGB[Red];
peGreen:= RGB[Green];
peBlue := RGB[Blue];
end;
end;
finally
Stream.Seek (SavePosition, soFromBeginning);
end;
end;
end;
{ Exemplo:
Width = 4
Planes = 3
BitsPerPixel= 24
Fórmula = 3*X + Plano
0 4 8
PCX: B0 B1 B2 B3 G0 G1 G2 G3 R0 R1 R2 R3
- - - - - - - - - - - -
Plano - - - - - - - - - - - -
2 - - B0 - - B1 - - B2 - - B3
1 - G0 - - G1 - - G2 - - G3 -
0 R0 - - R1 - - R2 - - R3 - -
- - - - - - - - - - - -
- - - - - - - - - - - -
- - - - - - - - - - - -
- - - - - - - - - - - -
BMP: R0 G0 B0 R1 G1 B1 R2 G2 B2 R3 G3 B3
}
procedure TPCX.Dump24b;
var
Atual : Byte;
Altura : Integer;
Largura: Integer;
X, Y : Integer;
Line : PLine;
Plano : ShortInt;
// A ordem no PCX é R-G-B mas no BMP é B-G-R
procedure Inserir;
begin
if X < Largura then // Pode ocorrer "BytesPerLine > Width"
Line[(X+X+X) + Plano]:= Atual;
Inc (X);
if X = BytesPerLine then begin
X:= 0;
if Plano > 0 then
Dec (Plano)
else begin
Plano:= 2;
Inc (Y);
if Y < Altura then
Line:= ScanLine[Y];
end;
end;
end;
var
Contador, K: Byte;
begin
X := 0;
Y := 0;
Altura := Height;
Largura:= Width;
Line := ScanLine[Y];
Plano := 2;
while Y < Altura do begin
Read (Atual, 1);
if Atual >= cMask then begin
Contador:= Atual and (not cMask);
Read (Atual, 1);
for K:= 1 to Contador do
Inserir;
end
else
Inserir;
end;
end;
procedure TPCX.Dump8b;
var
Atual : Byte;
Altura : Integer;
Largura: Integer;
X, Y : Integer;
Line : PLine;
procedure Inserir;
begin
if X < Largura then // Pode ocorrer "BytesPerLine > Width"
Line[X]:= Atual;
Inc (X);
if X = BytesPerLine then begin
X:= 0;
Inc (Y);
if Y < Altura then
Line:= ScanLine[Y];
end;
end;
var
Contador, K: Byte;
begin
X := 0;
Y := 0;
Altura := Height;
Largura:= Width;
Line := ScanLine[Y];
while Y < Altura do begin
Read (Atual, 1);
if Atual >= cMask then begin
Contador:= Atual and (not cMask);
Read (Atual, 1);
for K:= 1 to Contador do
Inserir;
end
else
Inserir;
end;
end;
// Os Planos estão na ordem: Plano3 Plano2 Plano1 Plano0
procedure TPCX.Dump4b;
var
Atual : Byte;
Altura : Integer;
Largura: Integer;
X, Y : Integer;
Line : PLine;
Plano : ShortInt;
procedure Inserir;
var
B : Byte;
Bit : Byte;
Offset: Integer;
begin
if X < Largura then begin// Pode ocorrer "BytesPerLine > Width"
Offset:= X+X+X+X;
Bit := 0;
while Bit < 8 do begin
// Primeiro "NIBBLE"
B := Atual shl Bit;
Line[Offset]:= Line[Offset] or ((B and 128) shr Plano);
// Segundo "NIBBLE"
Line[Offset]:= Line[Offset] or (((B shr 3) and 8) shr Plano);
Inc (Bit, 2);
Inc (Offset);
end;
end;
Inc (X);
if X = BytesPerLine then begin
X:= 0;
if Plano > 0 then
Dec (Plano)
else begin
Plano:= 3;
Inc (Y);
if Y < Altura then begin
Line:= ScanLine[Y];
FillChar (Line[0], Largura shr 1, #0);
end;
end;
end;
end;
var
Contador, K: Byte;
begin
X := 0;
Y := 0;
Plano := 3;
Altura := Height;
Largura:= Width;
Line := ScanLine[Y];
FillChar (Byte (ScanLine[0]^), Largura div 2, #0);
while Y < Altura do begin
Read (Atual, 1);
if Atual >= cMask then begin
Contador:= Atual and (not cMask);
Read (Atual, 1);
for K:= 1 to Contador do
Inserir;
end
else
Inserir;
end;
end;
procedure TPCX.DumpImage;
begin
if NPlanes = 1 then
Dump8b
else
case BitsPerPixel of
1, 8: Dump8b;
4 : Dump4b;
24 : Dump24b;
end;
end;
procedure TPCX.ReadStream (AStream: TStream);
begin
Stream:= AStream;
if Stream.Size > 0 then begin
DumpHeader;
InitializePalette;
DumpPalette;
SetPalette;
DumpImage;
end;
end;
function TPCX.IsValid (const FileName: String): Boolean;
var
Header: TPCXHeader;
Local : TStream;
begin
Result:= False;
if FileExists (FileName) then begin
Local:= TFileStream.Create (FileName, fmOpenRead);
try
Result:= (Local.Read (Header, SizeOf (TPCXHeader)) = SizeOf (TPCXHeader)) and (Header.Manufacturer = 10);
finally
Local.Free;
end;
end;
end;
procedure TPCX.LoadFromStream (Stream: TStream);
begin
if Assigned (Stream) then
ReadStream (Stream);
end;
// Se "TPCX.LoadFromFile" não for definido "TGraphic" chama "TPCX.LoadFromStream" com "TFileStream"
procedure TPCX.LoadFromFile (const FileName: String);
var
Stream: TStream;
begin
Stream:= TMemoryStream.Create;
try
TMemoryStream (Stream).LoadFromFile (FileName);
Stream.Seek (0, soFromBeginning);
ReadStream (Stream);
finally
Stream.Free;
end;
end;
initialization
TPicture.RegisterFileFormat ('PCX', 'PCX - PC Paintbrush', TPCX);
finalization
TPicture.UnRegisterGraphicClass (TPCX);
end.
|
unit SDL2_SimpleGUI_Canvas;
{:< The Canvas Class (base of drawable widgets) Unit and its support }
{ Simple GUI is a generic SDL2/Pascal GUI library by Matthias J. Molski,
get more infos here:
https://github.com/Free-Pascal-meets-SDL-Website/SimpleGUI.
It is based upon LK GUI by Lachlan Kingsford for SDL 1.2/Free Pascal,
get it here: https://sourceforge.net/projects/lkgui.
Written permission to re-license the library has been granted to me by the
original author.
Copyright (c) 2016-2020 Matthias J. Molski
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE. }
interface
uses SDL2, SDL2_TTF, SysUtils, SDL2_SimpleGUI_Element, SDL2_SimpleGUI_Base;
type
{ TGUI_Canvas }
{: A Canvas is the generic drawable control. Most things come from Canvas. }
TGUI_Canvas = class(TGUI_Element)
public
procedure Render; override;
procedure SetBackColor(InColor: TRGBA);
function GetBackColor: TRGBA;
procedure SetActiveColor(InColor: TRGBA);
function GetActiveColor: TRGBA;
procedure SetForeColor(InColor: TRGBA);
function GetForeColor: TRGBA;
procedure SetFont(InFont: PTTF_Font);
function GetFont: PTTF_Font;
procedure SetBorderStyle(NewStyle: TBorderStyle);
function GetBorderStyle: TBorderStyle;
procedure SetBorderColor(InColor: TRGBA);
function GetBorderColor: TRGBA;
procedure SetFillStyle(NewStyle: TFillStyle);
function GetFillStyle: TFillStyle;
procedure SetCaption(InCaption: string);
function GetCaption: string;
procedure ctrl_FontChanged; virtual;
constructor Create;
destructor Destroy; override;
protected
BackColor: TRGBA;
ForeColor: TRGBA;
ActiveColor: TRGBA;
CurFillColor: TRGBA;
CurBorderColor: TRGBA;
FillStyle: TFillStyle;
Caption: string;
BorderStyle: TBorderStyle;
BorderColor: TRGBA;
Font: PTTF_Font;
FontHeight, FontAscent, FontDescent, FontLineSkip: Integer;
FontMonospace: Integer;
{ Helper procedures/functions }
function MakeRect(ax, ay, aw, ah: Word): PSDL_Rect;
procedure RenderRect(Rect: PSDL_Rect; Color: TRGBA);
procedure RenderFilledRect(Rect: PSDL_Rect; Color: TRGBA);
procedure RenderLine(x0, y0, x1, y1: Word; Color: TRGBA);
procedure RenderText(TextIn: string; x, y: Word; Alignment: TTextAlign);
private
end;
implementation
uses
SDL2_SimpleGUI;
var
Exceptn: Exception;
{ TGUI_Canvas }
procedure TGUI_Canvas.Render;
begin
if Visible then
begin
case FillStyle of
FS_Filled:
begin
RenderFilledRect(
MakeRect(GetAbsLeft, GetAbsTop, GetWidth, GetHeight),
CurFillColor
);
end;
FS_None:
begin
RenderFilledRect(
MakeRect(GetAbsLeft, GetAbsTop, GetWidth, GetHeight),
GUI_FullTrans
);
end;
end;
// Draw Borders
case BorderStyle of
BS_Single:
begin
RenderRect(
MakeRect(GetAbsLeft, GetAbsTop, GetWidth, GetHeight),
CurBorderColor
);
end;
end;
end;
end;
procedure TGUI_Canvas.SetBackColor(InColor: TRGBA);
begin
BackColor := InColor;
CurFillColor := InColor;
end;
function TGUI_Canvas.GetBackColor: TRGBA;
begin
GetBackColor := BackColor;
end;
procedure TGUI_Canvas.SetActiveColor(InColor: TRGBA);
begin
ActiveColor := InColor;
end;
function TGUI_Canvas.GetActiveColor: TRGBA;
begin
GetActiveColor := ActiveColor;
end;
procedure TGUI_Canvas.SetForeColor(InColor: TRGBA);
begin
ForeColor := InColor;
end;
function TGUI_Canvas.GetForeColor: TRGBA;
begin
GetForeColor := ForeColor;
end;
procedure TGUI_Canvas.SetFont(InFont: PTTF_Font);
begin
Font := InFont;
FontHeight := TTF_FontHeight(Font);
FontAscent := TTF_FontAscent(Font);
FontDescent := TTF_FontDescent(Font);
FontLineSkip := TTF_FontLineSkip(Font);
FontMonospace := TTF_FontFaceIsFixedWidth(Font);
ctrl_FontChanged;
end;
function TGUI_Canvas.GetFont: PTTF_Font;
begin
GetFont := Font;
end;
procedure TGUI_Canvas.SetBorderColor(InColor: TRGBA);
begin
BorderColor := InColor;
CurBorderColor := InColor;
end;
function TGUI_Canvas.GetBorderColor: TRGBA;
begin
GetBorderColor := BorderColor;
end;
procedure TGUI_Canvas.SetBorderStyle(NewStyle: TBorderStyle);
begin
BorderStyle := NewStyle;
end;
function TGUI_Canvas.GetBorderStyle: TBorderStyle;
begin
GetBorderStyle := BorderStyle;
end;
procedure TGUI_Canvas.SetFillStyle(NewStyle: TFillStyle);
begin
FillStyle := NewStyle;
end;
function TGUI_Canvas.GetFillStyle: TFillStyle;
begin
GetFillStyle := FillStyle;
end;
procedure TGUI_Canvas.RenderRect(Rect: PSDL_Rect; Color: TRGBA);
begin
SDL_SetRenderDrawColor(GetRenderer, Color.r, Color.g, Color.b, Color.a);
SDL_RenderDrawRect(GetRenderer, Rect);
end;
procedure TGUI_Canvas.RenderFilledRect(Rect: PSDL_Rect; Color: TRGBA);
begin
SDL_SetRenderDrawColor(GetRenderer, Color.r, Color.g, Color.b, Color.a);
SDL_RenderFillRect(GetRenderer, Rect);
end;
procedure TGUI_Canvas.RenderLine(x0, y0, x1, y1: Word; Color: TRGBA);
begin
SDL_SetRenderDrawColor(GetRenderer, Color.r, Color.g, Color.b, Color.a);
SDL_RenderDrawLine(GetRenderer, x0, y0, x1, y1);
end;
procedure TGUI_Canvas.RenderText(TextIn: string; x, y: Word;
Alignment: TTextAlign);
var
ASurface: PSDL_Surface;
ATexture: PSDL_Texture;
Color: TSDL_Color;
ARect: TSDL_Rect;
TempW, TempH: LongInt;
begin
if (not(TextIn <> '')) then
Exit;
if not Assigned(Font) then
Exceptn.Create('RenderText called on ' + DbgName + ' with no Font Set');
// Get width and height of text
TTF_SizeText(Font, PChar(TextIn), @TempW, @TempH);
ARect.w := TempW;
ARect.h := TempH;
case Alignment of
Align_Left:
begin
ARect.x := GetAbsLeft + x;
ARect.y := GetAbsTop + Y;
end;
Align_Center:
begin
ARect.x := GetAbsLeft + x - (TempW div 2);
ARect.y := GetAbsTop + Y;
end;
Align_Right:
begin
ARect.x := GetAbsLeft + x - (TempW);
ARect.y := GetAbsTop + y;
end;
end;
Color.r := ForeColor.r;
Color.g := ForeColor.g;
Color.b := ForeColor.b;
ASurface := TTF_RenderUTF8_Blended(Font, PChar(TextIn), Color);
ATexture := SDL_CreateTextureFromSurface(Renderer, ASurface);
if Assigned(ASurface) then
SDL_FreeSurface(ASurface);
SDL_RenderCopy(Renderer, ATexture, nil, @ARect);
SDL_DestroyTexture(ATexture);
end;
procedure TGUI_Canvas.SetCaption(InCaption: string);
begin
Caption := InCaption;
end;
function TGUI_Canvas.GetCaption: string;
begin
GetCaption := Caption;
end;
procedure TGUI_Canvas.ctrl_FontChanged;
begin
end;
constructor TGUI_Canvas.Create;
begin
inherited Create;
SetForeColor(GUI_DefaultForeColor);
SetBackColor(GUI_DefaultBackColor);
Width := 256;
Height := 256;
Visible := True;
BorderStyle := BS_None;
SetBorderColor(GUI_DefaultBorderColor);
SetActiveColor(GUI_DefaultActiveColor);
SetFillStyle(FS_Filled);
end;
destructor TGUI_Canvas.Destroy;
begin
inherited Destroy;
end;
function TGUI_Canvas.MakeRect(ax, ay, aw, ah: Word): PSDL_Rect;
const
ARect: TSDL_Rect = (x: 0; y: 0; w: 0; h: 0);
begin
with ARect do
begin
x := ax;
y := ay;
w := aw;
h := ah;
end;
Result := @ARect;
end;
begin
end.
|
unit uPavkooStringList;
interface
uses
Classes,Windows;
type
TThreadStringList = class
private
FList: TStringList;
FLock: TRTLCriticalSection;
public
constructor Create;
destructor Destroy; override;
procedure Add(const Item: String);
procedure Clear;
function LockList: TStringList;
function GetCount:Integer;
function GetItem(index:Integer):String;
procedure Remove(const Item: String);
procedure UnlockList;
end;
implementation
{ TThreadStringList }
procedure TThreadStringList.Add(const Item: String);
begin
LockList;
try
if (FList.IndexOf(Item) = -1) then
FList.Add(Item);
finally
UnlockList;
end;
end;
procedure TThreadStringList.Clear;
begin
LockList;
try
FList.Clear;
finally
UnlockList;
end;
end;
constructor TThreadStringList.Create;
begin
inherited Create;
InitializeCriticalSection(FLock);
FList := TStringList.Create;
end;
destructor TThreadStringList.Destroy;
begin
LockList; // Make sure nobody else is inside the list.
try
FList.Free;
inherited Destroy;
finally
UnlockList;
DeleteCriticalSection(FLock);
end;
end;
function TThreadStringList.GetCount: Integer;
begin
Result:=FList.Count;
end;
function TThreadStringList.GetItem(index: Integer): String;
begin
Result:=FList.Strings[index];
end;
function TThreadStringList.LockList: TStringList;
begin
EnterCriticalSection(FLock);
Result := FList;
end;
procedure TThreadStringList.Remove(const Item: String);
begin
LockList;
try
FList.Delete(FList.IndexOf(Item));
finally
UnlockList;
end;
end;
procedure TThreadStringList.UnlockList;
begin
LeaveCriticalSection(FLock);
end;
end.
|
{ ZFM-20 series fingerprint library Lazarus/FPC wrapper.
Copyright (c) 2015 Dilshan R Jayakody [jayakody2000lk@gmail.com]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
}
unit zfm20;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
{ TZfmStatus }
TZfmStatus = (ZsUnknownError = 0, ZsSuccessful, ZsTimeout, ZsNoFinger, ZsFingerCollectError, ZsBadResponse, ZsDataError, ZsIoError, ZsMemoryError);
{ TfrmMain }
TZFM20Fingerprint = class(TObject)
public
constructor Create(portName: string; baudRate: integer); overload;
destructor Destroy; override;
function IsAvailable(): Boolean;
function Capture(): TZfmStatus;
function SaveFingerprintToFile(fileName: string): TZfmStatus;
function GetFingerprintBuffer(var dataBuffer: PByte; var dataBufferSize: LongWord): TZfmStatus;
function FreeFingerprintBuffer(var dataBuffer: PByte): TZfmStatus;
private
_pComPort: string;
_pBaud: integer;
_pDevID: LongWord;
public
// Communication port address or value.
property Port: string read _pComPort write _pComPort;
// Communication port baud rate. (Default baud rate for ZFM-20 sensor is 56700.)
property BaudRate: integer read _pBaud write _pBaud;
// Sensor ID. (Default ZFM-20 sensor ID is 0xFFFFFFFF.)
property DeviceID: LongWord read _pDevID write _pDevID;
end;
implementation
function Zfm20CaptureFingerprint(comPort: PChar; baudRate: Integer; sensorAddr: LongWord): TZfmStatus; stdcall; external 'zfm20lib.dll';
function Zfm20SensorAvailable(comPort: PChar; baudRate: Integer; sensorAddr: LongWord): TZfmStatus; stdcall; external 'zfm20lib.dll';
function Zfm20SaveFingerprintImage(comPort: PChar; baudRate: Integer; sensorAddr: LongWord; fileName: PChar): TZfmStatus; stdcall; external 'zfm20lib.dll';
function Zfm20FreeFingerprintBuffer(var dataBuffer: PByte): TZfmStatus; stdcall; external 'zfm20lib.dll';
function Zfm20GetFingerprintBuffer(comPort: PChar; baudRate: Integer; sensorAddr: LongWord; var outBufferSize: LongWord; var outBuffer: PByte): TZfmStatus; stdcall; external 'zfm20lib.dll';
// Constructor.
constructor TZfm20Fingerprint.Create(portName: string; baudRate: integer);
begin
inherited Create;
_pComPort := portName;
_pBaud := baudRate;
_pDevID := $FFFFFFFF;
end;
// Destructor.
destructor TZfm20Fingerprint.Destroy;
begin
inherited;
end;
// Check availability of fingerprint sensor.
function TZfm20Fingerprint.IsAvailable(): Boolean;
begin
Result := (Zfm20SensorAvailable(PChar(_pComPort), _pBaud, _pDevId) = zsSuccessful);
end;
// Send capture command to sensor module.
function TZfm20Fingerprint.Capture(): TZfmStatus;
begin
Result := Zfm20CaptureFingerprint(PChar(_pComPort), _pBaud, _pDevId);
end;
// Save content of sensor's ImageBuffer to specified bitmap file.
function TZfm20Fingerprint.SaveFingerprintToFile(fileName: string): TZfmStatus;
begin
Result := Zfm20SaveFingerprintImage(PChar(_pComPort), _pBaud, _pDevId, PChar(fileName));
end;
// Get content of sensor ImageBuffer as buffer.
function TZfm20Fingerprint.GetFingerprintBuffer(var dataBuffer: PByte; var dataBufferSize: LongWord): TZfmStatus;
begin
Result := Zfm20GetFingerprintBuffer(PChar(_pComPort), _pBaud, _pDevId, dataBufferSize, dataBuffer);
end;
// Flush allocated fingerprint image buffer.
function TZfm20Fingerprint.FreeFingerprintBuffer(var dataBuffer: PByte): TZfmStatus;
begin
Result := Zfm20FreeFingerprintBuffer(dataBuffer);
end;
end.
|
namespace LocalXMLDataStore;
interface
uses
System.IO,
System.Windows.Forms,
System.Drawing, System.Reflection;
type
/// <summary>
/// Summary description for MainForm.
/// </summary>
MainForm = class(System.Windows.Forms.Form)
{$REGION Windows Form Designer generated fields}
private
iDDataGridViewTextBoxColumn: System.Windows.Forms.DataGridViewTextBoxColumn;
nameDataGridViewTextBoxColumn: System.Windows.Forms.DataGridViewTextBoxColumn;
emailDataGridViewTextBoxColumn: System.Windows.Forms.DataGridViewTextBoxColumn;
bindingNavigator1: System.Windows.Forms.BindingNavigator;
bindingNavigatorAddNewItem: System.Windows.Forms.ToolStripButton;
bindingSource1: System.Windows.Forms.BindingSource;
bindingNavigatorCountItem: System.Windows.Forms.ToolStripLabel;
bindingNavigatorDeleteItem: System.Windows.Forms.ToolStripButton;
bindingNavigatorMoveFirstItem: System.Windows.Forms.ToolStripButton;
bindingNavigatorMovePreviousItem: System.Windows.Forms.ToolStripButton;
bindingNavigatorSeparator: System.Windows.Forms.ToolStripSeparator;
bindingNavigatorPositionItem: System.Windows.Forms.ToolStripTextBox;
bindingNavigatorSeparator1: System.Windows.Forms.ToolStripSeparator;
bindingNavigatorMoveNextItem: System.Windows.Forms.ToolStripButton;
bindingNavigatorMoveLastItem: System.Windows.Forms.ToolStripButton;
bindingNavigatorSeparator2: System.Windows.Forms.ToolStripSeparator;
components: System.ComponentModel.IContainer;
localData1: LocalXMLDataStore.LocalData;
dataGridView1: System.Windows.Forms.DataGridView;
method InitializeComponent;
{$ENDREGION}
private
fLocalDirectory : String;
fDataFileName : String;
method MainForm_FormClosing(sender: System.Object; e: System.Windows.Forms.FormClosingEventArgs);
protected
method Dispose(aDisposing: Boolean); override;
public
constructor;
end;
implementation
{$REGION Construction and Disposition}
constructor MainForm;
begin
//
// Required for Windows Form Designer support
//
InitializeComponent();
fLocalDirectory := Path.GetDirectoryName(&Assembly.GetExecutingAssembly.Location);
fDataFileName := Path.Combine(fLocalDirectory,'store.xml');
if File.Exists(fDataFileName) then
localData1.ReadXml(fDataFileName);
end;
method MainForm.Dispose(aDisposing: boolean);
begin
if aDisposing then begin
if assigned(components) then
components.Dispose();
end;
inherited Dispose(aDisposing);
end;
{$ENDREGION}
{$REGION Windows Form Designer generated code}
method MainForm.InitializeComponent;
begin
self.components := new System.ComponentModel.Container();
var resources: System.ComponentModel.ComponentResourceManager := new System.ComponentModel.ComponentResourceManager(typeOf(MainForm));
self.dataGridView1 := new System.Windows.Forms.DataGridView();
self.bindingNavigator1 := new System.Windows.Forms.BindingNavigator(self.components);
self.bindingNavigatorAddNewItem := new System.Windows.Forms.ToolStripButton();
self.bindingNavigatorCountItem := new System.Windows.Forms.ToolStripLabel();
self.bindingNavigatorDeleteItem := new System.Windows.Forms.ToolStripButton();
self.bindingNavigatorMoveFirstItem := new System.Windows.Forms.ToolStripButton();
self.bindingNavigatorMovePreviousItem := new System.Windows.Forms.ToolStripButton();
self.bindingNavigatorSeparator := new System.Windows.Forms.ToolStripSeparator();
self.bindingNavigatorPositionItem := new System.Windows.Forms.ToolStripTextBox();
self.bindingNavigatorSeparator1 := new System.Windows.Forms.ToolStripSeparator();
self.bindingNavigatorMoveNextItem := new System.Windows.Forms.ToolStripButton();
self.bindingNavigatorMoveLastItem := new System.Windows.Forms.ToolStripButton();
self.bindingNavigatorSeparator2 := new System.Windows.Forms.ToolStripSeparator();
self.bindingSource1 := new System.Windows.Forms.BindingSource(self.components);
self.localData1 := new LocalXMLDataStore.LocalData();
self.iDDataGridViewTextBoxColumn := new System.Windows.Forms.DataGridViewTextBoxColumn();
self.nameDataGridViewTextBoxColumn := new System.Windows.Forms.DataGridViewTextBoxColumn();
self.emailDataGridViewTextBoxColumn := new System.Windows.Forms.DataGridViewTextBoxColumn();
(self.dataGridView1 as System.ComponentModel.ISupportInitialize).BeginInit();
(self.bindingNavigator1 as System.ComponentModel.ISupportInitialize).BeginInit();
self.bindingNavigator1.SuspendLayout();
(self.bindingSource1 as System.ComponentModel.ISupportInitialize).BeginInit();
(self.localData1 as System.ComponentModel.ISupportInitialize).BeginInit();
self.SuspendLayout();
//
// dataGridView1
//
self.dataGridView1.AutoGenerateColumns := false;
self.dataGridView1.ColumnHeadersHeightSizeMode := System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
self.dataGridView1.Columns.AddRange(array of System.Windows.Forms.DataGridViewColumn([self.iDDataGridViewTextBoxColumn,
self.nameDataGridViewTextBoxColumn,
self.emailDataGridViewTextBoxColumn]));
self.dataGridView1.DataSource := self.bindingSource1;
self.dataGridView1.Dock := System.Windows.Forms.DockStyle.Fill;
self.dataGridView1.Location := new System.Drawing.Point(0, 25);
self.dataGridView1.Name := 'dataGridView1';
self.dataGridView1.Size := new System.Drawing.Size(596, 302);
self.dataGridView1.TabIndex := 0;
//
// bindingNavigator1
//
self.bindingNavigator1.AddNewItem := self.bindingNavigatorAddNewItem;
self.bindingNavigator1.BindingSource := self.bindingSource1;
self.bindingNavigator1.CountItem := self.bindingNavigatorCountItem;
self.bindingNavigator1.DeleteItem := self.bindingNavigatorDeleteItem;
self.bindingNavigator1.Items.AddRange(array of System.Windows.Forms.ToolStripItem([self.bindingNavigatorMoveFirstItem,
self.bindingNavigatorMovePreviousItem,
self.bindingNavigatorSeparator,
self.bindingNavigatorPositionItem,
self.bindingNavigatorCountItem,
self.bindingNavigatorSeparator1,
self.bindingNavigatorMoveNextItem,
self.bindingNavigatorMoveLastItem,
self.bindingNavigatorSeparator2,
self.bindingNavigatorAddNewItem,
self.bindingNavigatorDeleteItem]));
self.bindingNavigator1.Location := new System.Drawing.Point(0, 0);
self.bindingNavigator1.MoveFirstItem := self.bindingNavigatorMoveFirstItem;
self.bindingNavigator1.MoveLastItem := self.bindingNavigatorMoveLastItem;
self.bindingNavigator1.MoveNextItem := self.bindingNavigatorMoveNextItem;
self.bindingNavigator1.MovePreviousItem := self.bindingNavigatorMovePreviousItem;
self.bindingNavigator1.Name := 'bindingNavigator1';
self.bindingNavigator1.PositionItem := self.bindingNavigatorPositionItem;
self.bindingNavigator1.Size := new System.Drawing.Size(596, 25);
self.bindingNavigator1.TabIndex := 1;
self.bindingNavigator1.Text := 'bindingNavigator1';
//
// bindingNavigatorAddNewItem
//
self.bindingNavigatorAddNewItem.DisplayStyle := System.Windows.Forms.ToolStripItemDisplayStyle.Image;
self.bindingNavigatorAddNewItem.Image := (resources.GetObject('bindingNavigatorAddNewItem.Image') as System.Drawing.Image);
self.bindingNavigatorAddNewItem.Name := 'bindingNavigatorAddNewItem';
self.bindingNavigatorAddNewItem.RightToLeftAutoMirrorImage := true;
self.bindingNavigatorAddNewItem.Size := new System.Drawing.Size(23, 22);
self.bindingNavigatorAddNewItem.Text := 'Add new';
//
// bindingNavigatorCountItem
//
self.bindingNavigatorCountItem.Name := 'bindingNavigatorCountItem';
self.bindingNavigatorCountItem.Size := new System.Drawing.Size(36, 22);
self.bindingNavigatorCountItem.Text := 'of {0}';
self.bindingNavigatorCountItem.ToolTipText := 'Total number of items';
//
// bindingNavigatorDeleteItem
//
self.bindingNavigatorDeleteItem.DisplayStyle := System.Windows.Forms.ToolStripItemDisplayStyle.Image;
self.bindingNavigatorDeleteItem.Image := (resources.GetObject('bindingNavigatorDeleteItem.Image') as System.Drawing.Image);
self.bindingNavigatorDeleteItem.Name := 'bindingNavigatorDeleteItem';
self.bindingNavigatorDeleteItem.RightToLeftAutoMirrorImage := true;
self.bindingNavigatorDeleteItem.Size := new System.Drawing.Size(23, 22);
self.bindingNavigatorDeleteItem.Text := 'Delete';
//
// bindingNavigatorMoveFirstItem
//
self.bindingNavigatorMoveFirstItem.DisplayStyle := System.Windows.Forms.ToolStripItemDisplayStyle.Image;
self.bindingNavigatorMoveFirstItem.Image := (resources.GetObject('bindingNavigatorMoveFirstItem.Image') as System.Drawing.Image);
self.bindingNavigatorMoveFirstItem.Name := 'bindingNavigatorMoveFirstItem';
self.bindingNavigatorMoveFirstItem.RightToLeftAutoMirrorImage := true;
self.bindingNavigatorMoveFirstItem.Size := new System.Drawing.Size(23, 22);
self.bindingNavigatorMoveFirstItem.Text := 'Move first';
//
// bindingNavigatorMovePreviousItem
//
self.bindingNavigatorMovePreviousItem.DisplayStyle := System.Windows.Forms.ToolStripItemDisplayStyle.Image;
self.bindingNavigatorMovePreviousItem.Image := (resources.GetObject('bindingNavigatorMovePreviousItem.Image') as System.Drawing.Image);
self.bindingNavigatorMovePreviousItem.Name := 'bindingNavigatorMovePreviousItem';
self.bindingNavigatorMovePreviousItem.RightToLeftAutoMirrorImage := true;
self.bindingNavigatorMovePreviousItem.Size := new System.Drawing.Size(23, 22);
self.bindingNavigatorMovePreviousItem.Text := 'Move previous';
//
// bindingNavigatorSeparator
//
self.bindingNavigatorSeparator.Name := 'bindingNavigatorSeparator';
self.bindingNavigatorSeparator.Size := new System.Drawing.Size(6, 25);
//
// bindingNavigatorPositionItem
//
self.bindingNavigatorPositionItem.AccessibleName := 'Position';
self.bindingNavigatorPositionItem.AutoSize := false;
self.bindingNavigatorPositionItem.Name := 'bindingNavigatorPositionItem';
self.bindingNavigatorPositionItem.Size := new System.Drawing.Size(50, 21);
self.bindingNavigatorPositionItem.Text := '0';
self.bindingNavigatorPositionItem.ToolTipText := 'Current position';
//
// bindingNavigatorSeparator1
//
self.bindingNavigatorSeparator1.Name := 'bindingNavigatorSeparator1';
self.bindingNavigatorSeparator1.Size := new System.Drawing.Size(6, 25);
//
// bindingNavigatorMoveNextItem
//
self.bindingNavigatorMoveNextItem.DisplayStyle := System.Windows.Forms.ToolStripItemDisplayStyle.Image;
self.bindingNavigatorMoveNextItem.Image := (resources.GetObject('bindingNavigatorMoveNextItem.Image') as System.Drawing.Image);
self.bindingNavigatorMoveNextItem.Name := 'bindingNavigatorMoveNextItem';
self.bindingNavigatorMoveNextItem.RightToLeftAutoMirrorImage := true;
self.bindingNavigatorMoveNextItem.Size := new System.Drawing.Size(23, 22);
self.bindingNavigatorMoveNextItem.Text := 'Move next';
//
// bindingNavigatorMoveLastItem
//
self.bindingNavigatorMoveLastItem.DisplayStyle := System.Windows.Forms.ToolStripItemDisplayStyle.Image;
self.bindingNavigatorMoveLastItem.Image := (resources.GetObject('bindingNavigatorMoveLastItem.Image') as System.Drawing.Image);
self.bindingNavigatorMoveLastItem.Name := 'bindingNavigatorMoveLastItem';
self.bindingNavigatorMoveLastItem.RightToLeftAutoMirrorImage := true;
self.bindingNavigatorMoveLastItem.Size := new System.Drawing.Size(23, 22);
self.bindingNavigatorMoveLastItem.Text := 'Move last';
//
// bindingNavigatorSeparator2
//
self.bindingNavigatorSeparator2.Name := 'bindingNavigatorSeparator2';
self.bindingNavigatorSeparator2.Size := new System.Drawing.Size(6, 25);
//
// bindingSource1
//
self.bindingSource1.DataMember := 'Emails';
self.bindingSource1.DataSource := self.localData1;
//
// localData1
//
self.localData1.DataSetName := 'LocalData';
self.localData1.SchemaSerializationMode := System.Data.SchemaSerializationMode.IncludeSchema;
//
// iDDataGridViewTextBoxColumn
//
self.iDDataGridViewTextBoxColumn.AutoSizeMode := System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
self.iDDataGridViewTextBoxColumn.DataPropertyName := 'ID';
self.iDDataGridViewTextBoxColumn.HeaderText := 'ID';
self.iDDataGridViewTextBoxColumn.Name := 'iDDataGridViewTextBoxColumn';
self.iDDataGridViewTextBoxColumn.ReadOnly := true;
self.iDDataGridViewTextBoxColumn.Width := 50;
//
// nameDataGridViewTextBoxColumn
//
self.nameDataGridViewTextBoxColumn.AutoSizeMode := System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
self.nameDataGridViewTextBoxColumn.DataPropertyName := 'Name';
self.nameDataGridViewTextBoxColumn.HeaderText := 'Name';
self.nameDataGridViewTextBoxColumn.Name := 'nameDataGridViewTextBoxColumn';
//
// emailDataGridViewTextBoxColumn
//
self.emailDataGridViewTextBoxColumn.AutoSizeMode := System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
self.emailDataGridViewTextBoxColumn.DataPropertyName := 'Email';
self.emailDataGridViewTextBoxColumn.HeaderText := 'Email';
self.emailDataGridViewTextBoxColumn.Name := 'emailDataGridViewTextBoxColumn';
//
// MainForm
//
self.ClientSize := new System.Drawing.Size(596, 327);
self.Controls.Add(self.dataGridView1);
self.Controls.Add(self.bindingNavigator1);
self.Icon := (resources.GetObject('$this.Icon') as System.Drawing.Icon);
self.Name := 'MainForm';
self.Text := 'Local XML Data Store Sample';
self.FormClosing += new System.Windows.Forms.FormClosingEventHandler(@self.MainForm_FormClosing);
(self.dataGridView1 as System.ComponentModel.ISupportInitialize).EndInit();
(self.bindingNavigator1 as System.ComponentModel.ISupportInitialize).EndInit();
self.bindingNavigator1.ResumeLayout(false);
self.bindingNavigator1.PerformLayout();
(self.bindingSource1 as System.ComponentModel.ISupportInitialize).EndInit();
(self.localData1 as System.ComponentModel.ISupportInitialize).EndInit();
self.ResumeLayout(false);
self.PerformLayout();
end;
{$ENDREGION}
method MainForm.MainForm_FormClosing(sender: System.Object; e: System.Windows.Forms.FormClosingEventArgs);
begin
localData1.WriteXml(fDataFileName);
end;
end. |
Unit RequestList;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
Interface
Uses
Classes, Generics.Collections,
IRPMonDll,
RefObject,
AbstractRequest,
IRPMonRequest,
DataParsers,
ProcessList,
SymTables;
Type
TRequestList = Class;
TRequestListOnRequestProcessed = Procedure (ARequestList:TRequestList; ARequest:TDriverRequest; Var AStore:Boolean);
TRequestList = Class
Private
FOnRequestProcessed : TRequestListOnRequestProcessed;
FFilterDisplayOnly : Boolean;
FAllRequests : TRefObjectList<TDriverRequest>;
FRequests : TRefObjectList<TDriverRequest>;
FDriverMap : TDictionary<Pointer, WideString>;
FDeviceMap : TDictionary<Pointer, WideString>;
FFileMap : TDictionary<Pointer, WideString>;
FProcessMap : TRefObjectDictionary<Cardinal, TProcessEntry>;
FParsers : TObjectList<TDataParser>;
FSymStore : TModuleSymbolStore;
Protected
Function GetCount:Integer;
Function GetItem(AIndex:Integer):TDriverRequest;
Procedure SetFilterDisplayOnly(AValue:Boolean);
Procedure SetSymStore(AStore:TModuleSymbolStore);
Public
Constructor Create;
Destructor Destroy; Override;
Function RefreshMaps:Cardinal;
Procedure Clear;
Function ProcessBuffer(ABuffer:PREQUEST_GENERAL):Cardinal;
Procedure SaveToStream(AStream:TStream; AFormat:ERequestLogFormat);
Procedure LoadFromStream(AStream:TStream; ARequireHeader:Boolean = True);
Procedure SaveToFile(AFileName:WideString; AFormat:ERequestLogFormat);
Procedure LoadFromFile(AFileName:WideString; ARequireHeader:Boolean = True);
Function GetTotalCount:Integer;
Procedure Reevaluate;
Function GetDriverName(AObject:Pointer; Var AName:WideString):Boolean;
Function GetDeviceName(AObject:Pointer; Var AName:WideString):Boolean;
Function GetFileName(AObject:Pointer; Var AName:WideString):Boolean;
Function GetProcess(AProcessId:Cardinal; Var AEntry:TProcessEntry):Boolean;
Procedure EnumProcesses(AList:TRefObjectList<TProcessEntry>);
Property FilterDisplayOnly : Boolean Read FFilterDisplayOnly Write SetFilterDisplayOnly;
Property Parsers : TObjectList<TDataParser> Read FParsers Write FParsers;
Property Count : Integer Read GetCount;
Property Items [Index:Integer] : TDriverRequest Read GetItem; Default;
Property OnRequestProcessed : TRequestListOnRequestProcessed Read FOnRequestProcessed Write FOnRequestProcessed;
Property SymStore : TModuleSymbolStore Read FSymStore Write SetSymStore;
end;
Implementation
Uses
Windows,
SysUtils,
IRPRequest,
BinaryLogHeader,
FastIoRequest,
DriverUnloadRequest,
IRPCompleteRequest,
StartIoRequest,
AddDeviceRequest,
XXXDetectedRequests,
FileObjectNameXXXRequest,
ProcessXXXRequests,
ImageLoadRequest;
Constructor TRequestList.Create;
begin
Inherited Create;
FRequests := TRefObjectList<TDriverRequest>.Create;
FAllRequests := TRefObjectList<TDriverRequest>.Create;
FDriverMap := TDictionary<Pointer, WideString>.Create;
FDeviceMap := TDictionary<Pointer, WideString>.Create;
FFileMap := TDictionary<Pointer, WideString>.Create;
FProcessMap := TRefObjectDictionary<Cardinal, TProcessEntry>.Create;
RefreshMaps;
end;
Destructor TRequestList.Destroy;
begin
FSymStore.Free;
FProcessMap.Free;
FFileMap.Free;
FDriverMap.Free;
FDeviceMap.Free;
Clear;
FAllRequests.Free;
FRequests.Free;
Inherited Destroy;
end;
Function TRequestList.RefreshMaps:Cardinal;
Var
I, J : Integer;
count : Cardinal;
pdri : PPIRPMON_DRIVER_INFO;
dri : PIRPMON_DRIVER_INFO;
tmp : PPIRPMON_DRIVER_INFO;
pdei : PPIRPMON_DEVICE_INFO;
dei : PIRPMON_DEVICE_INFO;
begin
Result := IRPMonDllSnapshotRetrieve(pdri, count);
If Result = ERROR_SUCCESS Then
begin
FDriverMap.Clear;
FDeviceMap.Clear;
tmp := pdri;
For I := 0 To count - 1 Do
begin
dri := tmp^;
FDriverMap.Add(dri.DriverObject, Copy(WideString(dri.DriverName), 1, Length(WideString(dri.DriverName))));
pdei := dri.Devices;
For J := 0 To dri.DeviceCount - 1 Do
begin
dei := pdei^;
FDeviceMap.Add(dei.DeviceObject, Copy(WideString(dei.Name), 1, Length(WideString(dei.Name))));
Inc(pdei);
end;
Inc(tmp);
end;
IRPMonDllSnapshotFree(pdri, count);
end;
end;
Function TRequestList.GetCount:Integer;
begin
Result := FRequests.Count;
end;
Function TRequestList.GetItem(AIndex:Integer):TDriverRequest;
begin
Result := FRequests[AIndex];
end;
Procedure TRequestList.Clear;
begin
FRequests.Clear;
FAllRequests.Clear;
end;
Procedure TRequestList.SetFilterDisplayOnly(AValue:Boolean);
Var
dr : TDriverRequest;
begin
If FFilterDisplayOnly <> AValue Then
begin
FFilterDisplayOnly := AValue;
FAllRequests.Clear;
If FFilterDisplayOnly Then
begin
For dr In FRequests Do
FAllRequests.Add(dr);
end;
end;
end;
Function TRequestList.ProcessBuffer(ABuffer:PREQUEST_GENERAL):Cardinal;
Var
keepRequest : Boolean;
dr : TDriverRequest;
deviceName : WideString;
driverName : WideString;
fileName : WideString;
pe : TProcessEntry;
ilr : TImageLoadRequest;
pcr : TProcessCreatedRequest;
begin
Result := 0;
While Assigned(ABuffer) Do
begin
pe := Nil;
Case ABuffer.Header.RequestType Of
ertIRP: dr := TIRPRequest.Build(ABuffer.Irp);
ertIRPCompletion: dr := TIRPCompleteRequest.Create(ABuffer.IrpComplete);
ertAddDevice: dr := TAddDeviceRequest.Create(ABuffer.AddDevice);
ertDriverUnload: dr := TDriverUnloadRequest.Create(ABuffer.DriverUnload);
ertFastIo: dr := TFastIoRequest.Create(ABuffer.FastIo);
ertStartIo: dr := TStartIoRequest.Create(ABuffer.StartIo);
ertDriverDetected : begin
dr := TDriverDetectedRequest.Create(ABuffer.DriverDetected);
If FDriverMap.ContainsKey(dr.DriverObject) Then
FDriverMap.Remove(dr.DriverObject);
FDriverMap.Add(dr.DriverObject, dr.DriverName);
end;
ertDeviceDetected : begin
dr := TDeviceDetectedRequest.Create(ABuffer.DeviceDetected);
If FDeviceMap.ContainsKey(dr.DeviceObject) Then
FDeviceMap.Remove(dr.DeviceObject);
FDeviceMap.Add(dr.DeviceObject, dr.DeviceName);
end;
ertFileObjectNameAssigned : begin
dr := TFileObjectNameAssignedRequest.Create(ABuffer.FileObjectNameAssigned);
If FFileMap.ContainsKey(dr.FileObject) Then
FFileMap.Remove(dr.FileObject);
FFileMap.Add(dr.FileObject, dr.FileName);
end;
ertFileObjectNameDeleted : begin
dr := TFileObjectNameDeletedRequest.Create(ABuffer.FileObjectNameDeleted);
If FFileMap.ContainsKey(dr.FileObject) Then
begin
dr.SetFileName(FFileMap.Items[dr.FileObject]);
FFileMap.Remove(dr.FileObject);
end;
end;
ertProcessCreated : begin
dr := TProcessCreatedRequest.Create(ABuffer.ProcessCreated);
If FProcessMap.ContainsKey(Cardinal(dr.DriverObject)) Then
FProcessMap.Remove(Cardinal(dr.DriverObject));
pcr := dr As TProcessCreatedRequest;
pe := TProcessEntry.Create(Cardinal(pcr.DriverObject), pcr.Raw.ProcessId, pcr.FileName, pcr.DeviceName);
FProcessMap.Add(Cardinal(dr.DriverObject), pe);
pe.Free;
end;
ertProcessExitted : begin
dr := TProcessExittedRequest.Create(ABuffer.ProcessExitted);
If FProcessMap.TryGetValue(dr.ProcessId, pe) Then
pe.Terminate;
end;
ertImageLoad : begin
dr := TImageLoadRequest.Create(ABuffer.ImageLoad);
If FFileMap.ContainsKey(dr.FileObject) Then
FFileMap.Remove(dr.FileObject);
FFileMap.Add(dr.FileObject, dr.FileName);
If FProcessMap.TryGetValue(dr.ProcessId, pe) Then
begin
ilr := dr As TImageLoadRequest;
pe.AddImage(ilr.Raw.Time, ilr.ImageBase, ilr.ImageSize, ilr.FileName);
end;
end;
Else dr := TDriverRequest.Create(ABuffer.Header);
end;
If FDriverMap.TryGetValue(dr.DriverObject, driverName) Then
dr.DriverName := driverName;
If FDeviceMap.TryGetValue(dr.DeviceObject, deviceName) Then
dr.DeviceName := deviceName;
If FFileMap.TryGetValue(dr.FileObject, fileName) Then
dr.SetFileName(fileName);
If FProcessMap.TryGetValue(dr.ProcessId, pe) Then
begin
dr.Process := pe;
dr.SetProcessName(pe.BaseName);
end;
If FFilterDisplayOnly Then
FAllRequests.Add(dr);
keepRequest := True;
If Assigned(FOnRequestProcessed) Then
FOnRequestProcessed(Self, dr, keepRequest);
If keepRequest Then
FRequests.Add(dr);
dr.Free;
If Not Assigned(ABuffer.Header.Next) Then
Break;
ABuffer := PREQUEST_GENERAL(NativeUInt(ABuffer) + RequestGetSize(@ABuffer.Header));
end;
end;
Procedure TRequestList.SaveToStream(AStream:TStream; AFormat:ERequestLogFormat);
Var
bh : TBinaryLogHeader;
I : Integer;
dr : TDriverRequest;
comma : AnsiChar;
arrayChar : AnsiChar;
newLine : Packed Array [0..1] Of AnsiChar;
begin
comma := ',';
newLine[0] := #13;
newLine[1] := #10;
Case AFormat Of
rlfBinary: begin
TBinaryLogHeader.Fill(bh);
AStream.Write(bh, SizeOf(bh));
end;
rlfJSONArray : begin
arrayChar := '[';
AStream.Write(arrayChar, SizeOf(arrayChar));
end;
end;
For I := 0 To FRequests.Count - 1 Do
begin
dr := FRequests[I];
dr.SaveToStream(AStream, FParsers, AFormat, FSymStore);
If I < FRequests.Count - 1 Then
begin
Case AFormat Of
rlfJSONArray : AStream.Write(comma, SizeOf(comma));
rlfText,
rlfJSONLines : AStream.Write(newLine, SizeOf(newLine));
end;
end;
end;
If AFormat = rlfJSONArray Then
begin
arrayChar := ']';
AStream.Write(arrayChar, SizeOf(arrayChar));
end;
end;
Procedure TRequestList.SaveToFile(AFileName:WideString; AFormat:ERequestLogFormat);
Var
F : TFileStream;
begin
F := TFileStream.Create(AFileName, fmCreate Or fmOpenWrite);
Try
SaveToStream(F, AFormat);
Finally
F.Free;
end;
end;
Procedure TRequestList.LoadFromStream(AStream:TStream; ARequireHeader:Boolean = True);
Var
reqSize : Cardinal;
rg : PREQUEST_GENERAL;
bh : TBinaryLogHeader;
oldPos : Int64;
invalidHeader : Boolean;
begin
invalidHeader := False;
oldPos := AStream.Position;
AStream.Read(bh, SizeOf(bh));
If Not TBinaryLogHeader.SignatureValid(bh) Then
begin
invalidHeader := True;
If ARequireHeader Then
Raise Exception.Create('Invalid log file signature');
end;
If Not TBinaryLogHeader.VersionSupported(bh) Then
begin
invalidHeader := True;
If ARequireHeader Then
Raise Exception.Create('Log file version not supported');
end;
If Not TBinaryLogHeader.ArchitectureSupported(bh) Then
begin
invalidHeader := True;
If ARequireHeader Then
Raise Exception.Create('The log file and application "bitness" differ.'#13#10'Use other application version');
end;
If invalidHeader Then
AStream.Position := oldPos;
While AStream.Position < AStream.Size Do
begin
AStream.Read(reqSize, SizeOf(reqSize));
rg := AllocMem(reqSize);
If Not Assigned(rg) Then
Raise Exception.Create(Format('Unable to allocate %u bytes for request', [reqSize]));
AStream.Read(rg^, reqSize);
ProcessBuffer(rg);
FreeMem(rg);
end;
end;
Procedure TRequestList.LoadFromFile(AFileName:WideString; ARequireHeader:Boolean = True);
Var
F : TFileStream;
begin
F := TFileStream.Create(AFileName, fmOpenRead);
Try
LoadFromStream(F, ARequireHeader);
Finally
F.Free;
end;
end;
Procedure TRequestList.Reevaluate;
Var
store : Boolean;
I : Integer;
dr : TDriverRequest;
begin
If Not FFilterDisplayOnly Then
begin
I := 0;
While (I < FRequests.Count) Do
begin
If Assigned(FOnRequestProcessed) Then
begin
store := True;
FOnRequestProcessed(Self, FRequests[I], store);
If Not store THen
begin
FRequests.Delete(I);
Continue;
end;
end;
Inc(I);
end;
end
Else begin
FRequests.Clear;
For dr In FAllRequests Do
begin
store := True;
If Assigned(FOnRequestProcessed) Then
FOnRequestProcessed(Self, dr, store);
If store Then
FRequests.Add(dr);
end;
end;
end;
Function TRequestList.GetTotalCount:Integer;
begin
Result := FRequests.Count;
If FFilterDisplayOnly Then
Result := FAllRequests.Count;
end;
Function TRequestList.GetDriverName(AObject:Pointer; Var AName:WideString):Boolean;
begin
Result := FDriverMap.TryGetValue(AObject, AName);
end;
Function TRequestList.GetDeviceName(AObject:Pointer; Var AName:WideString):Boolean;
begin
Result := FDeviceMap.TryGetValue(AObject, AName);
end;
Function TRequestList.GetFileName(AObject:Pointer; Var AName:WideString):Boolean;
begin
Result := FFileMap.TryGetValue(AObject, AName);
end;
Function TRequestList.GetProcess(AProcessId:Cardinal; Var AEntry:TProcessEntry):Boolean;
begin
Result := FProcessMap.TryGetValue(AProcessId, AEntry);
If Result Then
AEntry.Reference;
end;
Procedure TRequestList.EnumProcesses(AList:TRefObjectList<TProcessEntry>);
Var
p : TPair<Cardinal, TProcessEntry>;
begin
For p In FProcessMap Do
AList.Add(p.Value);
end;
Procedure TRequestList.SetSymStore(AStore:TModuleSymbolStore);
begin
FSymStore.Free;
FSymStore := Nil;
If Assigned(AStore) Then
begin
FSymStore := AStore;
FSymStore.Reference;
end;
end;
End.
|
namespace MetalExample;
interface
uses
Metal,
MetalKit;
type
VertexBuffer = class
private
_buffer : MTLBuffer;
public
class method newBuffer(_device : MTLDevice; const _src : ^Void; const _bufflen : Integer) : VertexBuffer;
class method newBuffer(_device : MTLDevice) SourceData(_src :^Void) withLength(_bufflen : Integer) : VertexBuffer;
property verticies : MTLBuffer read _buffer;
end;
implementation
class method VertexBuffer.newBuffer(_device: MTLDevice; const _src: ^Void; const _bufflen: Integer): VertexBuffer;
begin
result := new VertexBuffer();
result._buffer := _device.newBufferWithLength(_bufflen) options(MTLResourceOptions.StorageModeShared);
// Copy the vertex data into the vertex buffer by accessing a pointer via
// the buffer's `contents` property
memcpy(result._buffer.contents, _src, _bufflen);
end;
class method VertexBuffer.newBuffer(_device: MTLDevice) SourceData(_src: ^Void) withLength(_bufflen: Integer): VertexBuffer;
begin
result := new VertexBuffer();
result._buffer := _device.newBufferWithLength(_bufflen) options(MTLResourceOptions.StorageModeShared);
// Copy the vertex data into the vertex buffer by accessing a pointer via
// the buffer's `contents` property
memcpy(result._buffer.contents, _src, _bufflen);
end;
end. |
unit winftp;
interface
uses
Classes, Windows, WinInet, SysUtils, StrUtils, nsGlobals;
function InitializeFTPSession(const AConnectionType: TFTPConnectType;
const HostName, UserName, Password, Port, ProxyName, ProxyPort, ProxyUser, ProxyPassword: string;
const APassive: Boolean): DWORD;
procedure FinalizeFTPSession;
function InitializeFTP(const HostName, UserName, Password, Port, ProxyName, ProxyPort: string): DWORD;
function FinalFTP: DWORD;
function GetDirContent(const ADirName: PChar): string;
function UploadFTPFile(ALocalName, ARemoteName: PChar; Event: TFTPProgressEvent): DWORD;
function DownloadFTPFile(ALocalName, ARemoteName: PChar; Event: TFTPProgressEvent): DWORD;
function DeleteFTPFile(AFileName: PChar): DWORD;
function DeleteFTPFolder(AFolderName: PChar): DWORD;
function RenameFTPFile(AFromName, AToName: PChar): DWORD;
function CreateFTPFolder(AFolderName: PChar): DWORD;
function IntFileExists(AFileName: PChar): Boolean;
function TestWriteToFTP(AFileName: PChar): Boolean;
function GetLastFTPResponse: PChar;
function FTPFindFirst(const Path: PChar; Attr: integer; var F: TFTPSearchRec): integer;
function FTPFindNext(var F: TFTPSearchRec): integer;
procedure FTPFindClose(var F: TFTPSearchRec);
function FTPFileExists(AFileName: PChar): Boolean;
function FTPDirectoryExists(ADirName: PChar): Boolean;
implementation
const
dwNumberOfBytes: DWORD = 512;
var
InetG: HInternet = nil;
InetC: HInternet = nil;
g_Error: DWORD;
lpszBuffer: array[0..MAX_PATH] of char;
lpdwBufferLength: DWORD = MAX_PATH;
g_ModuleHandle: HMODULE;
function InitializeFTPSession(const AConnectionType: TFTPConnectType;
const HostName, UserName, Password, Port, ProxyName, ProxyPort, ProxyUser, ProxyPassword: string;
const APassive: Boolean): DWORD;
begin
g_ConnectType := AConnectionType;
g_Passive := APassive;
Result := InitializeFTP(HostName, UserName, Password, Port, ProxyName, ProxyPort);
end;
procedure FinalizeFTPSession;
begin
FinalFTP;
g_ConnectType := ftpcDefault;
g_Passive := False;
end;
function FinalFTP: DWORD;
begin
try
if InetC <> nil then
InternetCloseHandle(InetC);
if InetG <> nil then
InternetCloseHandle(InetG);
finally
InetC := nil;
InetG := nil;
end;
Result := GetLastError;
end;
function InitializeFTP(const HostName, UserName, Password, Port, ProxyName, ProxyPort: string): DWORD;
var
ConFlg: cardinal;
FTPPort: word;
S: string;
ProxyStr: string;
begin
if InetG = nil then
InternetCloseHandle(InetG);
if InetC = nil then
InternetCloseHandle(InetC);
// 22.02.2004
g_Error := InternetAttemptConnect(0);
Result := g_Error;
if g_Error <> ERROR_SUCCESS then
Exit;
ProxyStr := EmptyStr;
case g_ConnectType of
ftpcDirect: ConFlg := INTERNET_OPEN_TYPE_DIRECT;
ftpcUseProxy:
begin
ConFlg := INTERNET_OPEN_TYPE_PROXY;
if ProxyPort = EmptyStr then
ProxyStr := Format('ftp=ftp://%s', [ProxyName])
else
ProxyStr := Format('ftp=ftp://%s:%s', [ProxyName, ProxyPort]);
end;
else
ConFlg := INTERNET_OPEN_TYPE_PRECONFIG;
end;
S := Port;
if (S = EmptyStr) or AnsiSameText(S, 'ftp') then
FTPPort := INTERNET_DEFAULT_FTP_PORT
else
FTPPort := StrToIntDef(S, 21);
InetG := InternetOpen('AceBackup3', ConFlg, PChar(ProxyStr), nil, 0);
if InetG = nil then
begin
g_Error := GetLastError;
Result := g_Error;
Exit;
end;
ConFlg := INTERNET_FLAG_RELOAD;
if g_Passive then
ConFlg := ConFlg or INTERNET_FLAG_PASSIVE;
InetC := InternetConnect(InetG, PChar(HostName), FTPPort, PChar(UserName), PChar(Password),
INTERNET_SERVICE_FTP, ConFlg, 0);
if InetC <> nil then
g_Error := ERROR_SUCCESS
else
g_Error := GetLastError;
Result := g_Error;
end;
function GetFindDataStr(FindData: TWin32FindData): string;
var
S, S1, S2: string;
LocalFileTime: TFileTime;
DosTime: integer;
ISize64: int64;
begin
Result := EmptyStr;
case FindData.dwFileAttributes of
// FILE_ATTRIBUTE_ARCHIVE: S := '-rwxrwxrwx';
// FILE_ATTRIBUTE_COMPRESSED: S := '-rwxrwxrwx';
FILE_ATTRIBUTE_DIRECTORY: S := '<DIR>';
// FILE_ATTRIBUTE_HIDDEN: S := 'H';
// FILE_ATTRIBUTE_NORMAL: S := '-rwxrwxrwx';
// FILE_ATTRIBUTE_READONLY: S := '-r-xr-xr-x';
// FILE_ATTRIBUTE_SYSTEM: S := '-rwxrwxrwx';
// FILE_ATTRIBUTE_TEMPORARY: S := '-rwxrwxrwx';
else
S := EmptyStr; //IntToStr(FindData.dwFileAttributes);
end;
Int64Rec(ISize64).Lo := FindData.nFileSizeLow;
Int64Rec(ISize64).Hi := FindData.nFileSizeHigh;
if S = EmptyStr then
S2 := IntToStr(ISize64)
else
S2 := EmptyStr;
if FileTimeToLocalFileTime(FindData.ftLastWriteTime, LocalFileTime) then
FileTimeToDosDateTime(LocalFileTime, LongRec(DosTime).Hi,
LongRec(DosTime).Lo);
S1 := FormatDateTime('mm-dd-yy hh:nnAM/PM', FileDateToDateTime(DosTime));
Result := Format('%s%12s%9s %s'#13#10, [S1, S, S2, FindData.cFileName]);
end;
function GetDirContent(const ADirName: PChar): string;
var
WF32: TWin32FindData;
HFind: HInternet;
begin
Result := EmptyStr;
FillChar(WF32, SizeOf(WF32), #0);
HFind := FtpFindFirstFile(InetC, PChar(ADirName), WF32, INTERNET_FLAG_RELOAD, 0);
if HFind = nil then
Exit;
repeat
Result := Result + GetFindDataStr(WF32);
until not InternetFindNextFile(HFind, @WF32);
InternetCloseHandle(HFind);
end;
function IntFileExists(AFileName: PChar): Boolean;
var
WF32: TWin32FindData;
HFind: HInternet;
begin
Result := False;
FillChar(WF32, SizeOf(WF32), #0);
HFind := FtpFindFirstFile(InetC, AFileName, WF32, INTERNET_FLAG_RELOAD, 0);
if HFind <> nil then
begin
Result := GetLastError = 0;
InternetCloseHandle(HFind);
end;
end;
function UploadFTPFile(ALocalName, ARemoteName: PChar; Event: TFTPProgressEvent): DWORD;
var
FtpFile: HInternet;
FS: TFileStream;
Buf: Pointer;
dwNumberOfBytesToWrite: DWORD;
lpdwNumberOfBytesWritten: DWORD;
// Bytes: dword;
Current: dword;
Total: int64;
NeedClose: Boolean;
rslt: Boolean;
begin
NeedClose := False;
FS := TFileStream.Create(ALocalName, fmOpenRead or fmShareDenyNone);
try
if Assigned(Event) then
Event(0, 0, NeedClose);
if NeedClose then
begin
Result := S_FALSE;
Abort;
end;
Total := FS.Size;
Current := 0;
FtpFile := FtpOpenFile(InetC, ARemoteName, GENERIC_WRITE, FTP_TRANSFER_TYPE_BINARY, 0);
if FtpFile = nil then
begin
g_Error := GetLastError;
Result := g_Error;
Exit;
end;
GetMem(Buf, dwNumberOfBytes);
try
repeat
dwNumberOfBytesToWrite := FS.Read(Buf^, dwNumberOfBytes);
rslt := InternetWriteFile(FtpFile, Buf, dwNumberOfBytesToWrite, lpdwNumberOfBytesWritten);
Current := Current + lpdwNumberOfBytesWritten;
if Assigned(Event) then
Event(Current, Total, NeedClose);
if NeedClose then
begin
Result := S_FALSE;
Abort;
end;
until (lpdwNumberOfBytesWritten = 0) or not rslt;
if Assigned(Event) then
Event(Current, Total, NeedClose);
if NeedClose then
begin
Result := S_FALSE;
Abort;
end;
finally
if Current >= Total then
g_Error := ERROR_SUCCESS
else
g_Error := GetLastError;
Result := g_Error;
InternetCloseHandle(FtpFile);
FreeMem(Buf);
end;
finally
FS.Free;
end;
end;
function TestWriteToFTP(AFileName: PChar): Boolean;
var
FtpFile: HInternet;
lpdwNumberOfBytesWritten: DWORD;
lpBuffer: Pointer;
begin
lpBuffer := AllocMem(MAX_PATH);
try
FtpFile := FtpOpenFile(InetC, AFileName, GENERIC_WRITE, FTP_TRANSFER_TYPE_BINARY, 0);
if FtpFile = nil then
begin
Result := False;
g_Error := GetLastError;
Exit;
end;
Result := InternetWriteFile(FtpFile, lpBuffer, MAX_PATH - 1, lpdwNumberOfBytesWritten);
InternetCloseHandle(FtpFile);
if Result then
Result := FtpDeleteFile(InetC, AFileName);
if Result then
g_Error := ERROR_SUCCESS
else
g_Error := GetLastError;
finally
FreeMem(lpBuffer);
end;
end;
function DownloadFTPFile(ALocalName, ARemoteName: PChar; Event: TFTPProgressEvent): DWORD;
var
FtpFile: HInternet;
FS: TFileStream;
Buf: Pointer;
Bytes: dword;
Current: dword;
// Total64: Int64;
NeedClose: Boolean;
br: Boolean;
begin
NeedClose := False;
FS := TFileStream.Create(ALocalName, fmCreate);
try
if Assigned(Event) then
Event(0, 0, NeedClose);
if NeedClose then
begin
Result := S_FALSE;
Abort;
end;
FtpFile := FtpOpenFile(InetC, ARemoteName, GENERIC_READ, FTP_TRANSFER_TYPE_BINARY, 0);
if FtpFile = nil then
begin
g_Error := GetLastError;
Result := g_Error;
Exit;
end;
Current := 0;
br := False;
GetMem(Buf, dwNumberOfBytes);
try
repeat
br := InternetReadFile(FtpFile, Buf, dwNumberOfBytes, Bytes);
if Bytes > 0 then
begin
FS.Write(Buf^, Bytes);
Current := Current + Bytes;
end;
if Assigned(Event) then
Event(Current, 0, NeedClose);
if NeedClose then
begin
Result := S_FALSE;
Abort;
end;
until (Bytes < dwNumberOfBytes) or not br;
finally
if br then
g_Error := ERROR_SUCCESS
else
g_Error := GetLastError;
Result := g_Error;
InternetCloseHandle(FtpFile);
FreeMem(Buf);
end;
finally
FS.Free;
end;
end;
function DeleteFTPFile(AFileName: PChar): DWORD;
begin
if FtpDeleteFile(InetC, AFileName) then
g_Error := ERROR_SUCCESS
else
g_Error := GetLastError;
Result := g_Error;
end;
function DeleteFTPFolder(AFolderName: PChar): DWORD;
begin
if FtpRemoveDirectory(InetC, AFolderName) then
g_Error := ERROR_SUCCESS
else
g_Error := GetLastError;
Result := g_Error;
end;
function RenameFTPFile(AFromName, AToName: PChar): DWORD;
begin
if FtpRenameFile(InetC, AFromName, AToName) then
g_Error := ERROR_SUCCESS
else
g_Error := GetLastError;
Result := g_Error;
end;
function CreateFTPFolder(AFolderName: PChar): DWORD;
begin
if FtpCreateDirectory(InetC, AFolderName) then
g_Error := ERROR_SUCCESS
else
g_Error := GetLastError;
Result := g_Error;
end;
function FTPFindMatchingFile(var F: TFTPSearchRec): integer;
var
LocalFileTime: TFileTime;
begin
with F do
begin
while FindData.dwFileAttributes and ExcludeAttr <> 0 do
if not InternetFindNextFile(FindHandle, @FindData) then
begin
Result := GetLastError;
Exit;
end;
FileTimeToLocalFileTime(FindData.ftLastWriteTime, LocalFileTime);
FileTimeToDosDateTime(LocalFileTime, LongRec(Time).Hi,
LongRec(Time).Lo);
Size := FindData.nFileSizeLow;
Attr := FindData.dwFileAttributes;
Name := FindData.cFileName;
end;
Result := 0;
end;
procedure FTPFindClose(var F: TFTPSearchRec);
begin
if F.FindHandle <> nil then
begin
InternetCloseHandle(F.FindHandle);
F.FindHandle := nil;
end;
end;
function FTPFindNext(var F: TFTPSearchRec): integer;
begin
if InternetFindNextFile(F.FindHandle, @F.FindData) then
Result := FTPFindMatchingFile(F)
else
Result := GetLastError;
end;
function FTPFindFirst(const Path: PChar; Attr: integer; var F: TFTPSearchRec): integer;
const
faSpecial = faHidden or faSysFile or faDirectory;
var
// br: Boolean;
sPath: string;
begin
F.ExcludeAttr := not Attr and faSpecial;
// 17
sPath := string(Path);
if (Length(sPath) > 0) and (sPath[1] <> sSlash) then
sPath := sSlash + sPath;
if not FtpSetCurrentDirectory(InetC, PChar(sPath)) then
begin
Result := GetLastError;
Exit;
end;
F.FindHandle := FtpFindFirstFile(InetC, nil, F.FindData, INTERNET_FLAG_RELOAD, 0);
// F.FindHandle := FtpFindFirstFile(InetC, PChar(Path), F.FindData, INTERNET_FLAG_RELOAD, 0);
// F.FindHandle := FtpFindFirstFile(InetC, PChar(sPath), F.FindData, INTERNET_FLAG_RELOAD, 0);
if F.FindHandle <> nil then
begin
Result := FTPFindMatchingFile(F);
if Result <> 0 then
FTPFindClose(F);
end
else
Result := GetLastError;
end;
function FTPFileExists(AFileName: PChar): Boolean;
var
FindHandle: HINTERNET;
begin
FindHandle := FtpOpenFile(InetC, AFileName, GENERIC_READ, FTP_TRANSFER_TYPE_BINARY, 0);
g_Error := GetLastError;
Result := FindHandle <> nil;
if Result then
InternetCloseHandle(FindHandle);
end;
function FTPDirectoryExists(ADirName: PChar): Boolean;
var
lpdwOldDirectory: DWORD;
lpszOldDirectory: array[0..MAX_PATH] of char;
begin
lpdwOldDirectory := MAX_PATH;
Result := FtpGetCurrentDirectory(InetC, lpszOldDirectory, lpdwOldDirectory);
if Result then
try
Result := FtpSetCurrentDirectory(InetC, ADirName);
g_Error := GetLastError;
finally
FtpSetCurrentDirectory(InetC, lpszOldDirectory);
end;
end;
function GetLastFTPResponse: PChar;
var
S: string;
begin
lpdwBufferLength := MAX_PATH;
case g_Error of
ERROR_SUCCESS:
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM or FORMAT_MESSAGE_ARGUMENT_ARRAY,
nil,
g_Error,
0,
lpszBuffer,
lpdwBufferLength,
nil);
ERROR_INTERNET_EXTENDED_ERROR:
InternetGetLastResponseInfo(g_Error, lpszBuffer, lpdwBufferLength);
else
begin
if FormatMessage(FORMAT_MESSAGE_FROM_HMODULE, LPDWORD(g_ModuleHandle),
g_Error, 0, lpszBuffer, lpdwBufferLength, nil) = 0 then
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM or FORMAT_MESSAGE_ARGUMENT_ARRAY,
nil,
g_Error,
0,
lpszBuffer,
lpdwBufferLength,
nil);
end;
end;
S := Format(sCodeFormatted, [Trim(String(@lpszBuffer)), g_Error]);
Result := PChar(S); //lpszBuffer;
end;
initialization
g_ModuleHandle := LoadLibrary('wininet.dll');
finalization
if g_ModuleHandle <> 0 then
FreeLibrary(g_ModuleHandle);
end.
|
unit fOptionsColors;
{$mode ObjFPC}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, ExtCtrls, Dialogs,
fOptionsFrame, fOptionsGroups;
type
{ TfrmOptionsColors }
TfrmOptionsColors = class(TOptionsColorsGroup)
rgDarkMode: TRadioGroup;
private
FAppMode: Integer;
protected
procedure Init; override;
procedure Load; override;
function Save: TOptionsEditorSaveFlags; override;
public
class function IsEmpty: Boolean; override;
end;
resourcestring
rsDarkModeOptions = 'Auto;Enabled;Disabled';
implementation
{$R *.lfm}
uses
DCStrUtils, uEarlyConfig, uDarkStyle;
{ TfrmOptionsColors }
procedure TfrmOptionsColors.Init;
begin
FAppMode:= gAppMode;
ParseLineToList(rsDarkModeOptions, rgDarkMode.Items);
end;
procedure TfrmOptionsColors.Load;
begin
case FAppMode of
1: rgDarkMode.ItemIndex:= 0;
2: rgDarkMode.ItemIndex:= 1;
3: rgDarkMode.ItemIndex:= 2;
end;
end;
function TfrmOptionsColors.Save: TOptionsEditorSaveFlags;
begin
Result:= [];
case rgDarkMode.ItemIndex of
0: gAppMode:= 1;
1: gAppMode:= 2;
2: gAppMode:= 3;
end;
if gAppMode <> FAppMode then
try
SaveEarlyConfig;
Result:= [oesfNeedsRestart];
except
on E: Exception do MessageDlg(E.Message, mtError, [mbOK], 0);
end;
end;
class function TfrmOptionsColors.IsEmpty: Boolean;
begin
Result:= not g_darkModeSupported;
end;
end.
|
unit URateioVO;
interface
uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO,
UCondominioVO,UItensRateioVO;
type
[TEntity]
[TTable('Rateio')]
TRateioVO = class(TGenericVO)
private
FidRateio : Integer;
FTotalRateio : currency;
FdtRateio : TDateTime;
FidCondominio : Integer;
public
CondominioVO : TCondominioVO;
ItensRateio: TObjectList<TItensRateioVO>;
[TId('idRateio')]
[TGeneratedValue(sAuto)]
property idRateio : Integer read FidRateio write FidRateio;
[TColumn('dtRateio','Data',0,[ldGrid,ldLookup,ldComboBox], False)]
property dtRateio: TDateTime read FdtRateio write FdtRateio;
[TColumn('TotalRateio','Data',0,[ldGrid,ldLookup,ldComboBox], False)]
property TotalRateio: Currency read FTotalRateio write FTotalRateio;
[TColumn('idCondominio','Condominio',0,[ldLookup,ldComboBox], False)]
property idCondominio: integer read FidCondominio write FidCondominio;
procedure ValidarCamposObrigatorios;
end;
implementation
procedure TRateioVO.ValidarCamposObrigatorios;
begin
if (self.dtRateio = 0) then
begin
raise Exception.Create('O campo Data é obrigatório!');
end;
end;
end.
|
unit Demo.Miscellaneous.Animation;
interface
uses
System.Classes, Demo.BaseFrame, cfs.GCharts;
type
TDemo_Miscellaneous_Animation = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_Miscellaneous_Animation.GenerateChart;
var
AreaChart, BarChart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally
begin
// AreaChart
AreaChart := TcfsGChartProducer.Create;
AreaChart.ClassChartType := TcfsGChartProducer.CLASS_AREA_CHART;
AreaChart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Year'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Sales'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Expenses')
]);
AreaChart.Data.AddRow(['2013', 1000, 400]);
AreaChart.Data.AddRow(['2014', 1170, 460]);
AreaChart.Data.AddRow(['2015', 660, 1120]);
AreaChart.Data.AddRow(['2016', 1030, 540]);
AreaChart.Options.Title('Company Performance');
AreaChart.Options.TitleTextStyle(TcfsGChartOptions.TextStyleToJSObject('gray', 12, true, false));
AreaChart.Options.Legend('textStyle', TcfsGChartOptions.TextStyleToJSObject('gray', 12, true, false));
AreaChart.Options.ChartArea('width', '50%');
AreaChart.Options.Colors(['green', 'red']);
AreaChart.Options.hAxis('textStyle', '{bold: true, fontSize: 11, color: ''gray''}');
AreaChart.Options.hAxis('minValue', 0);
AreaChart.Options.vAxis('textStyle', '{bold: true, fontSize: 10, color: ''silver''}');
AreaChart.Options.Animation('startup', True);
AreaChart.Options.Animation('duration', 1000);
AreaChart.Options.Animation('easing', 'out');
// BarChart
BarChart := TcfsGChartProducer.Create;
BarChart.ClassChartType := TcfsGChartProducer.CLASS_BAR_CHART;
BarChart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Year'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Sales'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Expenses')
]);
BarChart.Data.AddRow(['2013', 1000, 400]);
BarChart.Data.AddRow(['2014', 1170, 460]);
BarChart.Data.AddRow(['2015', 660, 1120]);
BarChart.Data.AddRow(['2016', 1030, 540]);
BarChart.Options.Title('Company Performance');
BarChart.Options.TitleTextStyle(TcfsGChartOptions.TextStyleToJSObject('gray', 12, true, false));
BarChart.Options.Legend('textStyle', TcfsGChartOptions.TextStyleToJSObject('gray', 12, true, false));
BarChart.Options.ChartArea('width', '50%');
BarChart.Options.Colors(['green', 'red']);
BarChart.Options.hAxis('textStyle', '{bold: true, fontSize: 10, color: ''silver''}');
BarChart.Options.hAxis('minValue', 0);
BarChart.Options.vAxis('textStyle', '{bold: true, fontSize: 11, color: ''gray''}');
BarChart.Options.DataOpacity(0.5);
BarChart.Options.Animation('startup', True);
BarChart.Options.Animation('duration', 1000);
BarChart.Options.Animation('easing', 'in');
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody(
'<div id="AreaChart" style="width: 100%;height: 50%;"></div>'
+ '<div id="BarChart" style="width: 100%;height: 50%;"></div>'
);
GChartsFrame.DocumentGenerate('AreaChart', AreaChart);
GChartsFrame.DocumentGenerate('BarChart', BarChart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_Miscellaneous_Animation);
end.
|
unit JavaScriptCodeDesigner;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls,
TypInfo,
dcsystem, dcparser, dcstring, dccommon, dcmemo, dccdes, dcdsgnstuff;
type
TJavaScriptCodeDesigner = class(TJSCodeDesigner)
public
function CreateEventName(const EventName: string; TypeData: PTypeData;
OnlyType: boolean): string; override;
procedure CreateMethod(const AMethodName: string;
TypeData: PTypeData); override;
function GetMethodStart(const pt: TPoint): TPoint; override;
procedure GetMethodTemplate(const AMethodName: string;
TypeData: PTypeData; S: TStrings); override;
function GetSyntaxParserClass : TSimpleParserClass; override;
function TypeToString(TypeCode: integer): string; override;
procedure ValidateObjectEventProperties(inObject: TObject);
procedure ValidateEventProperties(inContainer: TWinControl);
end;
implementation
uses
TpControls;
{ TJavaScriptCodeDesigner }
function TJavaScriptCodeDesigner.GetSyntaxParserClass: TSimpleParserClass;
begin
Result := inherited GetSyntaxParserClass;
end;
function TJavaScriptCodeDesigner.CreateEventName(const EventName: string;
TypeData: PTypeData; OnlyType: boolean): string;
begin
Result := 'function ' + EventName + '(inSender, inIndex)';
end;
procedure TJavaScriptCodeDesigner.GetMethodTemplate(const AMethodName: string;
TypeData: PTypeData; S: TStrings);
begin
with S do
begin
Add(CreateEventName(AMethodName, TypeData, false));
Add('{');
Add('');
Add('}');
end;
end;
procedure TJavaScriptCodeDesigner.CreateMethod(const AMethodName: string;
TypeData: PTypeData);
begin
inherited;
ShowMethod(AMethodName);
end;
function TJavaScriptCodeDesigner.TypeToString(TypeCode: integer): string;
begin
Result := '';
end;
function TJavaScriptCodeDesigner.GetMethodStart(const pt: TPoint): TPoint;
begin
Result := Point(2, pt.y + 2);
end;
procedure TJavaScriptCodeDesigner.ValidateObjectEventProperties(
inObject: TObject);
var
c, i: Integer;
propList: PPropList;
m: string;
begin
c := GetPropList(inObject, propList);
for i := 0 to Pred(c) do
if PropertyIsJsEvent(propList[i].Name) then
begin
m := GetStrProp(inObject, propList[i]);
if (m <> '') and (not MethodExists(m)) then
SetStrProp(inObject, propList[i], '');
end;
end;
procedure TJavaScriptCodeDesigner.ValidateEventProperties(
inContainer: TWinControl);
var
i: Integer;
begin
for i := 0 to Pred(inContainer.ControlCount) do
begin
ValidateObjectEventProperties(inContainer.Controls[i]);
if inContainer.Controls[i] is TWinControl then
ValidateEventProperties(TWinControl(inContainer.Controls[i]));
end;
end;
end.
|
unit UTraducao;
interface
uses Windows, Consts;
procedure SetResourceString(AResString: PResStringRec; ANewValue: PChar);
const
SNewMsgDlgYes: PChar = '&Sim';
SNewMsgDlgOK: PChar = 'Ok';
SNewMsgDlgCancel: PChar = 'Cancelar';
SNewMsgDlgNo: PChar = '&Não';
SNewMsgDlgWarning = 'Aviso';
SNewMsgDlgError = 'Erro';
SNewMsgDlgInformation = 'Informação';
SNewMsgDlgConfirm = 'Confirme';
SNewMsgDlgHelp = '&Ajuda';
SNewMsgDlgHelpNone = 'Não há arquivo de ajuda';
SNewMsgDlgHelpHelp = 'Ajuda';
SNewMsgDlgAbort = '&Abortar';
SNewMsgDlgRetry = '&Repetir';
SNewMsgDlgIgnore = '&Ignorar';
SNewMsgDlgAll = '&Todos';
SNewMsgDlgNoToAll = 'N&ão para Todos';
SNewMsgDlgYesToAll = 'Sim pata &Todos';
implementation
procedure SetResourceString(AResString: PResStringRec; ANewValue: PChar);
var
POldProtect: DWORD;
begin
VirtualProtect(AResString, SizeOf(AResString^), PAGE_EXECUTE_READWRITE, @POldProtect);
AResString^.Identifier := Integer(ANewValue);
VirtualProtect(AResString, SizeOf(AResString^), POldProtect, @POldProtect);
end;
initialization
SetResourceString(@SMsgDlgYes, SNewMsgDlgYes);
SetResourceString(@SMsgDlgOK, SNewMsgDlgOK);
SetResourceString(@SMsgDlgCancel, SNewMsgDlgCancel);
SetResourceString(@SMsgDlgNo, SNewMsgDlgNo);
SetResourceString(@SMsgDlgWarning, SNewMsgDlgWarning);
SetResourceString(@SMsgDlgError, SNewMsgDlgError);
SetResourceString(@SMsgDlgInformation, SNewMsgDlgInformation);
SetResourceString(@SMsgDlgConfirm, SNewMsgDlgConfirm);
SetResourceString(@SMsgDlgHelp, SNewMsgDlgHelp);
SetResourceString(@SMsgDlgHelpNone, SNewMsgDlgHelpNone);
SetResourceString(@SMsgDlgHelpHelp, SNewMsgDlgHelpHelp);
SetResourceString(@SMsgDlgAbort, SNewMsgDlgAbort);
SetResourceString(@SMsgDlgRetry, SNewMsgDlgRetry);
SetResourceString(@SMsgDlgIgnore, SNewMsgDlgIgnore);
SetResourceString(@SMsgDlgAll, SNewMsgDlgAll);
SetResourceString(@SMsgDlgNoToAll, SNewMsgDlgNoToAll);
SetResourceString(@SMsgDlgYesToAll, SNewMsgDlgYesToAll);
end.
|
unit ResizeToolThreadUnit;
interface
uses
Winapi.Windows,
System.Classes,
Vcl.Graphics,
UnitResampleFilters,
uBitmapUtils,
uEditorTypes,
uMemory,
uDBThread;
type
TResizeToolThread = class(TDBThread)
private
{ Private declarations }
FSID: string;
BaseImage: TBitmap;
IntParam: Integer;
FOnExit: TBaseEffectProcThreadExit;
D: TBitmap;
FOwner: TObject;
FToWidth, FToHeight: Integer;
FMethod: TResizeProcedure;
FEditor: TObject;
FIntMethod: Integer;
protected
procedure Execute; override;
public
constructor Create(AOwner: TObject; Method: TResizeProcedure; IntMethod: Integer; CreateSuspended: Boolean;
S: TBitmap; SID: string; OnExit: TBaseEffectProcThreadExit; ToWidth, ToHeight: Integer; Editor: TObject);
procedure CallBack(Progress: Integer; var Break: Boolean);
procedure SetProgress;
procedure DoExit;
end;
implementation
uses
ResizeToolUnit,
ImEditor;
{ TResizeToolThread }
procedure TResizeToolThread.CallBack(Progress: Integer; var Break: Boolean);
begin
IntParam := Progress;
Synchronize(SetProgress);
if (FEditor as TImageEditor).ToolClass = FOwner then
begin
if not(FOwner is TResizeToolPanelClass) then
begin
Break := True;
Exit;
end;
Break := (FOwner as TResizeToolPanelClass).FSID <> FSID;
end;
end;
constructor TResizeToolThread.Create(AOwner: TObject; Method : TResizeProcedure; IntMethod : Integer;
CreateSuspended: Boolean; S: TBitmap; SID: string;
OnExit: TBaseEffectProcThreadExit; ToWidth, ToHeight: Integer; Editor : TObject);
begin
inherited Create(nil, False);
FOwner := AOwner;
FSID := SID;
FOnExit := OnExit;
BaseImage := S;
FToWidth := ToWidth;
FMethod := Method;
FIntMethod := IntMethod;
FToHeight := ToHeight;
FEditor := Editor;
end;
procedure TResizeToolThread.DoExit;
begin
if (FEditor as TImageEditor).ToolClass = FOwner then
FOnExit(D, FSID)
else
begin
D.Free;
end;
end;
procedure TResizeToolThread.Execute;
begin
inherited;
FreeOnTerminate := True;
try
D := TBitmap.Create;
D.PixelFormat := pf24bit;
BaseImage.PixelFormat := pf24bit;
if Assigned(FMethod) then
begin
if ((FToWidth / BaseImage.Width) > 1) or ((FToHeight / BaseImage.Height) > 1) then
Interpolate(0, 0, FToWidth, FToHeight, Rect(0, 0, BaseImage.Width, BaseImage.Height), BaseImage, D, CallBack)
else
FMethod(FToWidth, FToHeight, BaseImage, D, CallBack);
end else
begin
D.Width := FToWidth;
D.Height := FToHeight;
Strecth(BaseImage, D, ResampleFilters[FIntMethod].Filter, ResampleFilters[FIntMethod].Width, CallBack);
end;
finally
F(BaseImage);
Synchronize(DoExit);
IntParam := 0;
Synchronize(SetProgress);
end;
end;
procedure TResizeToolThread.SetProgress;
begin
if (FEditor as TImageEditor).ToolClass = FOwner then
if (FOwner is TResizeToolPanelClass) then
(FOwner as TResizeToolPanelClass).SetProgress(IntParam, FSID);
end;
end.
|
unit BasicProgramTypes;
interface
uses ExtCtrls, StdCtrls, Menus;
type
PPaintBox = ^TPaintBox;
PLabel = ^TLabel;
PMenuItem = ^TMenuItem;
TSitesList = array of packed record
SiteName : string;
SiteUrl : string;
end;
TColourSchemesInfo = array of packed record
Name,Filename,By,Website : string;
end;
TPaletteSchemes = array of packed record
Filename : string;
ImageIndex : Shortint;
end;
implementation
end.
|
//
// Generated by JavaToPas v1.5 20150831 - 132350
////////////////////////////////////////////////////////////////////////////////
unit android.media.MediaFormat;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
java.nio.ByteBuffer;
type
JMediaFormat = interface;
JMediaFormatClass = interface(JObjectClass)
['{1B706D46-8BE7-424D-9E09-0F2C6F64C2FE}']
function _GetKEY_AAC_DRC_ATTENUATION_FACTOR : JString; cdecl; // A: $19
function _GetKEY_AAC_DRC_BOOST_FACTOR : JString; cdecl; // A: $19
function _GetKEY_AAC_DRC_HEAVY_COMPRESSION : JString; cdecl; // A: $19
function _GetKEY_AAC_DRC_TARGET_REFERENCE_LEVEL : JString; cdecl; // A: $19
function _GetKEY_AAC_ENCODED_TARGET_LEVEL : JString; cdecl; // A: $19
function _GetKEY_AAC_MAX_OUTPUT_CHANNEL_COUNT : JString; cdecl; // A: $19
function _GetKEY_AAC_PROFILE : JString; cdecl; // A: $19
function _GetKEY_AAC_SBR_MODE : JString; cdecl; // A: $19
function _GetKEY_AUDIO_SESSION_ID : JString; cdecl; // A: $19
function _GetKEY_BITRATE_MODE : JString; cdecl; // A: $19
function _GetKEY_BIT_RATE : JString; cdecl; // A: $19
function _GetKEY_CAPTURE_RATE : JString; cdecl; // A: $19
function _GetKEY_CHANNEL_COUNT : JString; cdecl; // A: $19
function _GetKEY_CHANNEL_MASK : JString; cdecl; // A: $19
function _GetKEY_COLOR_FORMAT : JString; cdecl; // A: $19
function _GetKEY_COMPLEXITY : JString; cdecl; // A: $19
function _GetKEY_DURATION : JString; cdecl; // A: $19
function _GetKEY_FLAC_COMPRESSION_LEVEL : JString; cdecl; // A: $19
function _GetKEY_FRAME_RATE : JString; cdecl; // A: $19
function _GetKEY_HEIGHT : JString; cdecl; // A: $19
function _GetKEY_IS_ADTS : JString; cdecl; // A: $19
function _GetKEY_IS_AUTOSELECT : JString; cdecl; // A: $19
function _GetKEY_IS_DEFAULT : JString; cdecl; // A: $19
function _GetKEY_IS_FORCED_SUBTITLE : JString; cdecl; // A: $19
function _GetKEY_I_FRAME_INTERVAL : JString; cdecl; // A: $19
function _GetKEY_LANGUAGE : JString; cdecl; // A: $19
function _GetKEY_LEVEL : JString; cdecl; // A: $19
function _GetKEY_MAX_HEIGHT : JString; cdecl; // A: $19
function _GetKEY_MAX_INPUT_SIZE : JString; cdecl; // A: $19
function _GetKEY_MAX_WIDTH : JString; cdecl; // A: $19
function _GetKEY_MIME : JString; cdecl; // A: $19
function _GetKEY_OPERATING_RATE : JString; cdecl; // A: $19
function _GetKEY_PRIORITY : JString; cdecl; // A: $19
function _GetKEY_PROFILE : JString; cdecl; // A: $19
function _GetKEY_PUSH_BLANK_BUFFERS_ON_STOP : JString; cdecl; // A: $19
function _GetKEY_REPEAT_PREVIOUS_FRAME_AFTER : JString; cdecl; // A: $19
function _GetKEY_ROTATION : JString; cdecl; // A: $19
function _GetKEY_SAMPLE_RATE : JString; cdecl; // A: $19
function _GetKEY_SLICE_HEIGHT : JString; cdecl; // A: $19
function _GetKEY_STRIDE : JString; cdecl; // A: $19
function _GetKEY_TEMPORAL_LAYERING : JString; cdecl; // A: $19
function _GetKEY_WIDTH : JString; cdecl; // A: $19
function _GetMIMETYPE_AUDIO_AAC : JString; cdecl; // A: $19
function _GetMIMETYPE_AUDIO_AC3 : JString; cdecl; // A: $19
function _GetMIMETYPE_AUDIO_AMR_NB : JString; cdecl; // A: $19
function _GetMIMETYPE_AUDIO_AMR_WB : JString; cdecl; // A: $19
function _GetMIMETYPE_AUDIO_EAC3 : JString; cdecl; // A: $19
function _GetMIMETYPE_AUDIO_FLAC : JString; cdecl; // A: $19
function _GetMIMETYPE_AUDIO_G711_ALAW : JString; cdecl; // A: $19
function _GetMIMETYPE_AUDIO_G711_MLAW : JString; cdecl; // A: $19
function _GetMIMETYPE_AUDIO_MPEG : JString; cdecl; // A: $19
function _GetMIMETYPE_AUDIO_MSGSM : JString; cdecl; // A: $19
function _GetMIMETYPE_AUDIO_OPUS : JString; cdecl; // A: $19
function _GetMIMETYPE_AUDIO_QCELP : JString; cdecl; // A: $19
function _GetMIMETYPE_AUDIO_RAW : JString; cdecl; // A: $19
function _GetMIMETYPE_AUDIO_VORBIS : JString; cdecl; // A: $19
function _GetMIMETYPE_TEXT_CEA_608 : JString; cdecl; // A: $19
function _GetMIMETYPE_TEXT_VTT : JString; cdecl; // A: $19
function _GetMIMETYPE_VIDEO_AVC : JString; cdecl; // A: $19
function _GetMIMETYPE_VIDEO_H263 : JString; cdecl; // A: $19
function _GetMIMETYPE_VIDEO_HEVC : JString; cdecl; // A: $19
function _GetMIMETYPE_VIDEO_MPEG2 : JString; cdecl; // A: $19
function _GetMIMETYPE_VIDEO_MPEG4 : JString; cdecl; // A: $19
function _GetMIMETYPE_VIDEO_RAW : JString; cdecl; // A: $19
function _GetMIMETYPE_VIDEO_VP8 : JString; cdecl; // A: $19
function _GetMIMETYPE_VIDEO_VP9 : JString; cdecl; // A: $19
function containsKey(&name : JString) : boolean; cdecl; // (Ljava/lang/String;)Z A: $11
function createAudioFormat(mime : JString; sampleRate : Integer; channelCount : Integer) : JMediaFormat; cdecl;// (Ljava/lang/String;II)Landroid/media/MediaFormat; A: $19
function createSubtitleFormat(mime : JString; language : JString) : JMediaFormat; cdecl;// (Ljava/lang/String;Ljava/lang/String;)Landroid/media/MediaFormat; A: $19
function createVideoFormat(mime : JString; width : Integer; height : Integer) : JMediaFormat; cdecl;// (Ljava/lang/String;II)Landroid/media/MediaFormat; A: $19
function getByteBuffer(&name : JString) : JByteBuffer; cdecl; // (Ljava/lang/String;)Ljava/nio/ByteBuffer; A: $11
function getFeatureEnabled(feature : JString) : boolean; cdecl; // (Ljava/lang/String;)Z A: $1
function getFloat(&name : JString) : Single; cdecl; // (Ljava/lang/String;)F A: $11
function getInteger(&name : JString) : Integer; cdecl; // (Ljava/lang/String;)I A: $11
function getLong(&name : JString) : Int64; cdecl; // (Ljava/lang/String;)J A: $11
function getString(&name : JString) : JString; cdecl; // (Ljava/lang/String;)Ljava/lang/String; A: $11
function init : JMediaFormat; cdecl; // ()V A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
procedure setByteBuffer(&name : JString; bytes : JByteBuffer) ; cdecl; // (Ljava/lang/String;Ljava/nio/ByteBuffer;)V A: $11
procedure setFeatureEnabled(feature : JString; enabled : boolean) ; cdecl; // (Ljava/lang/String;Z)V A: $1
procedure setFloat(&name : JString; value : Single) ; cdecl; // (Ljava/lang/String;F)V A: $11
procedure setInteger(&name : JString; value : Integer) ; cdecl; // (Ljava/lang/String;I)V A: $11
procedure setLong(&name : JString; value : Int64) ; cdecl; // (Ljava/lang/String;J)V A: $11
procedure setString(&name : JString; value : JString) ; cdecl; // (Ljava/lang/String;Ljava/lang/String;)V A: $11
property KEY_AAC_DRC_ATTENUATION_FACTOR : JString read _GetKEY_AAC_DRC_ATTENUATION_FACTOR;// Ljava/lang/String; A: $19
property KEY_AAC_DRC_BOOST_FACTOR : JString read _GetKEY_AAC_DRC_BOOST_FACTOR;// Ljava/lang/String; A: $19
property KEY_AAC_DRC_HEAVY_COMPRESSION : JString read _GetKEY_AAC_DRC_HEAVY_COMPRESSION;// Ljava/lang/String; A: $19
property KEY_AAC_DRC_TARGET_REFERENCE_LEVEL : JString read _GetKEY_AAC_DRC_TARGET_REFERENCE_LEVEL;// Ljava/lang/String; A: $19
property KEY_AAC_ENCODED_TARGET_LEVEL : JString read _GetKEY_AAC_ENCODED_TARGET_LEVEL;// Ljava/lang/String; A: $19
property KEY_AAC_MAX_OUTPUT_CHANNEL_COUNT : JString read _GetKEY_AAC_MAX_OUTPUT_CHANNEL_COUNT;// Ljava/lang/String; A: $19
property KEY_AAC_PROFILE : JString read _GetKEY_AAC_PROFILE; // Ljava/lang/String; A: $19
property KEY_AAC_SBR_MODE : JString read _GetKEY_AAC_SBR_MODE; // Ljava/lang/String; A: $19
property KEY_AUDIO_SESSION_ID : JString read _GetKEY_AUDIO_SESSION_ID; // Ljava/lang/String; A: $19
property KEY_BITRATE_MODE : JString read _GetKEY_BITRATE_MODE; // Ljava/lang/String; A: $19
property KEY_BIT_RATE : JString read _GetKEY_BIT_RATE; // Ljava/lang/String; A: $19
property KEY_CAPTURE_RATE : JString read _GetKEY_CAPTURE_RATE; // Ljava/lang/String; A: $19
property KEY_CHANNEL_COUNT : JString read _GetKEY_CHANNEL_COUNT; // Ljava/lang/String; A: $19
property KEY_CHANNEL_MASK : JString read _GetKEY_CHANNEL_MASK; // Ljava/lang/String; A: $19
property KEY_COLOR_FORMAT : JString read _GetKEY_COLOR_FORMAT; // Ljava/lang/String; A: $19
property KEY_COMPLEXITY : JString read _GetKEY_COMPLEXITY; // Ljava/lang/String; A: $19
property KEY_DURATION : JString read _GetKEY_DURATION; // Ljava/lang/String; A: $19
property KEY_FLAC_COMPRESSION_LEVEL : JString read _GetKEY_FLAC_COMPRESSION_LEVEL;// Ljava/lang/String; A: $19
property KEY_FRAME_RATE : JString read _GetKEY_FRAME_RATE; // Ljava/lang/String; A: $19
property KEY_HEIGHT : JString read _GetKEY_HEIGHT; // Ljava/lang/String; A: $19
property KEY_IS_ADTS : JString read _GetKEY_IS_ADTS; // Ljava/lang/String; A: $19
property KEY_IS_AUTOSELECT : JString read _GetKEY_IS_AUTOSELECT; // Ljava/lang/String; A: $19
property KEY_IS_DEFAULT : JString read _GetKEY_IS_DEFAULT; // Ljava/lang/String; A: $19
property KEY_IS_FORCED_SUBTITLE : JString read _GetKEY_IS_FORCED_SUBTITLE; // Ljava/lang/String; A: $19
property KEY_I_FRAME_INTERVAL : JString read _GetKEY_I_FRAME_INTERVAL; // Ljava/lang/String; A: $19
property KEY_LANGUAGE : JString read _GetKEY_LANGUAGE; // Ljava/lang/String; A: $19
property KEY_LEVEL : JString read _GetKEY_LEVEL; // Ljava/lang/String; A: $19
property KEY_MAX_HEIGHT : JString read _GetKEY_MAX_HEIGHT; // Ljava/lang/String; A: $19
property KEY_MAX_INPUT_SIZE : JString read _GetKEY_MAX_INPUT_SIZE; // Ljava/lang/String; A: $19
property KEY_MAX_WIDTH : JString read _GetKEY_MAX_WIDTH; // Ljava/lang/String; A: $19
property KEY_MIME : JString read _GetKEY_MIME; // Ljava/lang/String; A: $19
property KEY_OPERATING_RATE : JString read _GetKEY_OPERATING_RATE; // Ljava/lang/String; A: $19
property KEY_PRIORITY : JString read _GetKEY_PRIORITY; // Ljava/lang/String; A: $19
property KEY_PROFILE : JString read _GetKEY_PROFILE; // Ljava/lang/String; A: $19
property KEY_PUSH_BLANK_BUFFERS_ON_STOP : JString read _GetKEY_PUSH_BLANK_BUFFERS_ON_STOP;// Ljava/lang/String; A: $19
property KEY_REPEAT_PREVIOUS_FRAME_AFTER : JString read _GetKEY_REPEAT_PREVIOUS_FRAME_AFTER;// Ljava/lang/String; A: $19
property KEY_ROTATION : JString read _GetKEY_ROTATION; // Ljava/lang/String; A: $19
property KEY_SAMPLE_RATE : JString read _GetKEY_SAMPLE_RATE; // Ljava/lang/String; A: $19
property KEY_SLICE_HEIGHT : JString read _GetKEY_SLICE_HEIGHT; // Ljava/lang/String; A: $19
property KEY_STRIDE : JString read _GetKEY_STRIDE; // Ljava/lang/String; A: $19
property KEY_TEMPORAL_LAYERING : JString read _GetKEY_TEMPORAL_LAYERING; // Ljava/lang/String; A: $19
property KEY_WIDTH : JString read _GetKEY_WIDTH; // Ljava/lang/String; A: $19
property MIMETYPE_AUDIO_AAC : JString read _GetMIMETYPE_AUDIO_AAC; // Ljava/lang/String; A: $19
property MIMETYPE_AUDIO_AC3 : JString read _GetMIMETYPE_AUDIO_AC3; // Ljava/lang/String; A: $19
property MIMETYPE_AUDIO_AMR_NB : JString read _GetMIMETYPE_AUDIO_AMR_NB; // Ljava/lang/String; A: $19
property MIMETYPE_AUDIO_AMR_WB : JString read _GetMIMETYPE_AUDIO_AMR_WB; // Ljava/lang/String; A: $19
property MIMETYPE_AUDIO_EAC3 : JString read _GetMIMETYPE_AUDIO_EAC3; // Ljava/lang/String; A: $19
property MIMETYPE_AUDIO_FLAC : JString read _GetMIMETYPE_AUDIO_FLAC; // Ljava/lang/String; A: $19
property MIMETYPE_AUDIO_G711_ALAW : JString read _GetMIMETYPE_AUDIO_G711_ALAW;// Ljava/lang/String; A: $19
property MIMETYPE_AUDIO_G711_MLAW : JString read _GetMIMETYPE_AUDIO_G711_MLAW;// Ljava/lang/String; A: $19
property MIMETYPE_AUDIO_MPEG : JString read _GetMIMETYPE_AUDIO_MPEG; // Ljava/lang/String; A: $19
property MIMETYPE_AUDIO_MSGSM : JString read _GetMIMETYPE_AUDIO_MSGSM; // Ljava/lang/String; A: $19
property MIMETYPE_AUDIO_OPUS : JString read _GetMIMETYPE_AUDIO_OPUS; // Ljava/lang/String; A: $19
property MIMETYPE_AUDIO_QCELP : JString read _GetMIMETYPE_AUDIO_QCELP; // Ljava/lang/String; A: $19
property MIMETYPE_AUDIO_RAW : JString read _GetMIMETYPE_AUDIO_RAW; // Ljava/lang/String; A: $19
property MIMETYPE_AUDIO_VORBIS : JString read _GetMIMETYPE_AUDIO_VORBIS; // Ljava/lang/String; A: $19
property MIMETYPE_TEXT_CEA_608 : JString read _GetMIMETYPE_TEXT_CEA_608; // Ljava/lang/String; A: $19
property MIMETYPE_TEXT_VTT : JString read _GetMIMETYPE_TEXT_VTT; // Ljava/lang/String; A: $19
property MIMETYPE_VIDEO_AVC : JString read _GetMIMETYPE_VIDEO_AVC; // Ljava/lang/String; A: $19
property MIMETYPE_VIDEO_H263 : JString read _GetMIMETYPE_VIDEO_H263; // Ljava/lang/String; A: $19
property MIMETYPE_VIDEO_HEVC : JString read _GetMIMETYPE_VIDEO_HEVC; // Ljava/lang/String; A: $19
property MIMETYPE_VIDEO_MPEG2 : JString read _GetMIMETYPE_VIDEO_MPEG2; // Ljava/lang/String; A: $19
property MIMETYPE_VIDEO_MPEG4 : JString read _GetMIMETYPE_VIDEO_MPEG4; // Ljava/lang/String; A: $19
property MIMETYPE_VIDEO_RAW : JString read _GetMIMETYPE_VIDEO_RAW; // Ljava/lang/String; A: $19
property MIMETYPE_VIDEO_VP8 : JString read _GetMIMETYPE_VIDEO_VP8; // Ljava/lang/String; A: $19
property MIMETYPE_VIDEO_VP9 : JString read _GetMIMETYPE_VIDEO_VP9; // Ljava/lang/String; A: $19
end;
[JavaSignature('android/media/MediaFormat')]
JMediaFormat = interface(JObject)
['{88C615B7-36E6-4BBB-9042-819184178515}']
function getFeatureEnabled(feature : JString) : boolean; cdecl; // (Ljava/lang/String;)Z A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
procedure setFeatureEnabled(feature : JString; enabled : boolean) ; cdecl; // (Ljava/lang/String;Z)V A: $1
end;
TJMediaFormat = class(TJavaGenericImport<JMediaFormatClass, JMediaFormat>)
end;
const
TJMediaFormatKEY_AAC_DRC_ATTENUATION_FACTOR = 'aac-drc-cut-level';
TJMediaFormatKEY_AAC_DRC_BOOST_FACTOR = 'aac-drc-boost-level';
TJMediaFormatKEY_AAC_DRC_HEAVY_COMPRESSION = 'aac-drc-heavy-compression';
TJMediaFormatKEY_AAC_DRC_TARGET_REFERENCE_LEVEL = 'aac-target-ref-level';
TJMediaFormatKEY_AAC_ENCODED_TARGET_LEVEL = 'aac-encoded-target-level';
TJMediaFormatKEY_AAC_MAX_OUTPUT_CHANNEL_COUNT = 'aac-max-output-channel_count';
TJMediaFormatKEY_AAC_PROFILE = 'aac-profile';
TJMediaFormatKEY_AAC_SBR_MODE = 'aac-sbr-mode';
TJMediaFormatKEY_AUDIO_SESSION_ID = 'audio-session-id';
TJMediaFormatKEY_BITRATE_MODE = 'bitrate-mode';
TJMediaFormatKEY_BIT_RATE = 'bitrate';
TJMediaFormatKEY_CAPTURE_RATE = 'capture-rate';
TJMediaFormatKEY_CHANNEL_COUNT = 'channel-count';
TJMediaFormatKEY_CHANNEL_MASK = 'channel-mask';
TJMediaFormatKEY_COLOR_FORMAT = 'color-format';
TJMediaFormatKEY_COMPLEXITY = 'complexity';
TJMediaFormatKEY_DURATION = 'durationUs';
TJMediaFormatKEY_FLAC_COMPRESSION_LEVEL = 'flac-compression-level';
TJMediaFormatKEY_FRAME_RATE = 'frame-rate';
TJMediaFormatKEY_HEIGHT = 'height';
TJMediaFormatKEY_IS_ADTS = 'is-adts';
TJMediaFormatKEY_IS_AUTOSELECT = 'is-autoselect';
TJMediaFormatKEY_IS_DEFAULT = 'is-default';
TJMediaFormatKEY_IS_FORCED_SUBTITLE = 'is-forced-subtitle';
TJMediaFormatKEY_I_FRAME_INTERVAL = 'i-frame-interval';
TJMediaFormatKEY_LANGUAGE = 'language';
TJMediaFormatKEY_LEVEL = 'level';
TJMediaFormatKEY_MAX_HEIGHT = 'max-height';
TJMediaFormatKEY_MAX_INPUT_SIZE = 'max-input-size';
TJMediaFormatKEY_MAX_WIDTH = 'max-width';
TJMediaFormatKEY_MIME = 'mime';
TJMediaFormatKEY_OPERATING_RATE = 'operating-rate';
TJMediaFormatKEY_PRIORITY = 'priority';
TJMediaFormatKEY_PROFILE = 'profile';
TJMediaFormatKEY_PUSH_BLANK_BUFFERS_ON_STOP = 'push-blank-buffers-on-shutdown';
TJMediaFormatKEY_REPEAT_PREVIOUS_FRAME_AFTER = 'repeat-previous-frame-after';
TJMediaFormatKEY_ROTATION = 'rotation-degrees';
TJMediaFormatKEY_SAMPLE_RATE = 'sample-rate';
TJMediaFormatKEY_SLICE_HEIGHT = 'slice-height';
TJMediaFormatKEY_STRIDE = 'stride';
TJMediaFormatKEY_TEMPORAL_LAYERING = 'ts-schema';
TJMediaFormatKEY_WIDTH = 'width';
TJMediaFormatMIMETYPE_AUDIO_AAC = 'audio/mp4a-latm';
TJMediaFormatMIMETYPE_AUDIO_AC3 = 'audio/ac3';
TJMediaFormatMIMETYPE_AUDIO_AMR_NB = 'audio/3gpp';
TJMediaFormatMIMETYPE_AUDIO_AMR_WB = 'audio/amr-wb';
TJMediaFormatMIMETYPE_AUDIO_EAC3 = 'audio/eac3';
TJMediaFormatMIMETYPE_AUDIO_FLAC = 'audio/flac';
TJMediaFormatMIMETYPE_AUDIO_G711_ALAW = 'audio/g711-alaw';
TJMediaFormatMIMETYPE_AUDIO_G711_MLAW = 'audio/g711-mlaw';
TJMediaFormatMIMETYPE_AUDIO_MPEG = 'audio/mpeg';
TJMediaFormatMIMETYPE_AUDIO_MSGSM = 'audio/gsm';
TJMediaFormatMIMETYPE_AUDIO_OPUS = 'audio/opus';
TJMediaFormatMIMETYPE_AUDIO_QCELP = 'audio/qcelp';
TJMediaFormatMIMETYPE_AUDIO_RAW = 'audio/raw';
TJMediaFormatMIMETYPE_AUDIO_VORBIS = 'audio/vorbis';
TJMediaFormatMIMETYPE_TEXT_CEA_608 = 'text/cea-608';
TJMediaFormatMIMETYPE_TEXT_VTT = 'text/vtt';
TJMediaFormatMIMETYPE_VIDEO_AVC = 'video/avc';
TJMediaFormatMIMETYPE_VIDEO_H263 = 'video/3gpp';
TJMediaFormatMIMETYPE_VIDEO_HEVC = 'video/hevc';
TJMediaFormatMIMETYPE_VIDEO_MPEG2 = 'video/mpeg2';
TJMediaFormatMIMETYPE_VIDEO_MPEG4 = 'video/mp4v-es';
TJMediaFormatMIMETYPE_VIDEO_RAW = 'video/raw';
TJMediaFormatMIMETYPE_VIDEO_VP8 = 'video/x-vnd.on2.vp8';
TJMediaFormatMIMETYPE_VIDEO_VP9 = 'video/x-vnd.on2.vp9';
implementation
end.
|
unit scrollimg;
(*##*)
(*******************************************************************************
* *
* S C R O L I M G *
* image collections, part of CVRT2WBMP *
* *
* Copyright (c) 2001-2008 Andrei Ivanov. All rights reserved. *
* *
* Conditional defines: *
* *
* History *
* Jun 07 2001 *
* May 01 2008 *
* *
* Lines : *
* History : *
* Printed : --- *
* *
********************************************************************************)
(*##*)
interface
uses
Windows, Classes, SysUtils, Controls, StdCtrls, ExtCtrls, Graphics,
GifImage, wbmpimage;
type
TScrolledImagesProgressEvent = procedure (Sender: TObject; AWhat: Integer; const Msg: string) of object;
TImageLoaderInfo = record
Name: String[255];
No: Integer;
R: TRect;
end;
TScrolledImage = class(TObject)
private
FOwner: TComponent;
FParent: TWinControl;
FImageList: TImageList;
FOnClick: TNotifyEvent;
FId: Integer;
FPanBitmap: TBitmap;
FFileName: String;
function GetLeft: Integer;
procedure SetLeft(ALeft: Integer);
function GetTop: Integer;
procedure SetTop(ATop: Integer);
function GetWidth: Integer;
procedure SetWidth(AWidth: Integer);
function GetHeight: Integer;
procedure SetHeight(AHeight: Integer);
function GetVisible: Boolean;
procedure SetVisible(AVisible: Boolean);
procedure RedirectClick(Sender: TObject);
public
Pnl: TPanel;
Img: TImage;
constructor Create(AOwner: TComponent; AParent: TWinControl; APanBitmap: TBitmap; AImageList: TImageList; AOnClick: TNotifyEvent);
destructor Destroy; override;
procedure LoadFromFile(var AImageLoaderInfo: TImageLoaderInfo);
property FileName: String read FFileName;
published
property Width: Integer read GetWidth write SetWidth;
property Height: Integer read GetHeight write SetHeight;
property Left: Integer read GetLeft write SetLeft;
property Top: Integer read GetTop write SetTop;
property Visible: Boolean read GetVisible write SetVisible;
property Id: Integer read FId write FId;
property OnClick: TNotifyEvent read FOnClick write FOnClick;
end;
TScrolledImages = class;
TScrolledImagesLoaderThread = class (TThread)
private
FLoadLeft,
FLoadWidth: Integer;
FImageLoaderInfo: TImageLoaderInfo;
FScrolledImages: TScrolledImages;
FFiles: TStrings;
public
constructor Start(ACreateSuspended: Boolean; AScrolledImages: TScrolledImages;
AFiles: TStrings; ALoadLeft, ALoadWidth: Integer);
procedure Execute; override;
procedure LoadImageToForm; // uses FCurrentLoadImageNo inside TThread.Synchronize method
end;
TScrolledImagesDitherThread = class (TThread)
private
FLoadLeft,
FLoadWidth: Integer;
FImageLoaderInfo: TImageLoaderInfo;
FSrcScrolledImages,
FDestScrolledImages: TScrolledImages;
FDitherMode: TDitherMode;
public
constructor Start(ACreateSuspended: Boolean; ASrcScrolledImages, ADestScrolledImages: TScrolledImages;
ADitherMode: TDitherMode; ALoadLeft, ALoadWidth: Integer);
procedure Execute; override;
procedure DitherImageToForm; // uses FCurrentDitherImageNo inside TThread.Synchronize method
end;
TScrolledImages = class (TObject)
private
FPanBitmap: TBitmap;
FOnTerminateLoad: TNotifyEvent;
FOnTerminateDither: TNotifyEvent;
FLoaderThread: TScrolledImagesLoaderThread;
FDitherThread: TScrolledImagesDitherThread;
FOnProgress: TScrolledImagesProgressEvent;
FOwner: TComponent;
FParent: TWinControl;
FCurImageNo: Integer;
FImageList: TImageList;
FScrolledImages: array of TScrolledImage;
FOnClick: TNotifyEvent;
function GetCurImage: TImage;
procedure SetCurImageNo(ACurNo: Integer);
function GetScrolledImage(AImgNo: Integer): TScrolledImage;
function GetImage(AImgNo: Integer): TImage;
function GetCurScrolledImage: TScrolledImage;
function GetImagesCount: Integer;
procedure SetImagesCount(ANewValue: Integer);
function GetWidth: Integer;
procedure SetWidth(AWidth: Integer);
public
constructor Create(AOwner: TComponent; AParent: TWinControl; APanBitmap: TBitmap;
AOnTerminateLoad, AOnTerminateDither: TNotifyEvent; AImageList: TImageList);
destructor Destroy; override;
procedure LoadFiles(AFiles: TStrings; ALoadLeft, ALoadWidth: Integer);
procedure Dither(ASrc: TScrolledImages; ADitherMode: TDitherMode;
ALoadLeft, ALoadWidth: Integer);
function TerminateLoad: Boolean;
function TerminateDither: Boolean;
function ImageMaxWidth: Integer;
function GetImageNoByCoords(X, Y: Integer): Integer;
procedure ArrangeImages;
property ScrolledImage[AImgNo: Integer]: TScrolledImage read GetScrolledImage;
property Image[AImgNo: Integer]: TImage read GetImage;
property CurImageNo: Integer read FCurImageNo write SetCurImageNo;
property CurScrolledImage: TScrolledImage read GetCurScrolledImage;
property CurImage: TImage read GetCurImage;
property LoaderThread: TScrolledImagesLoaderThread read FLoaderThread write FLoaderThread;
property DitherThread: TScrolledImagesDitherThread read FDitherThread write FDitherThread;
property ImagesCount: Integer read GetImagesCount write SetImagesCount;
property OnProgress: TScrolledImagesProgressEvent read FOnProgress write FOnProgress;
property OnClick: TNotifyEvent read FOnClick write FOnClick;
property Width: Integer read GetWidth write SetWidth;
end;
//------------------ utility functions ------------------
procedure DoDither(SrcImage, DestImage: TImage; ADitherMode: TDitherMode);
implementation
type
BA = array[0..1] of Byte;
LogPal = record
lpal: TLogPalette;
dummy: packed array[1..255] of TPaletteEntry;
end;
//------------------ utility functions ------------------
procedure DoDither(SrcImage, DestImage: TImage; ADitherMode: TDitherMode);
const
ColorReduction: TColorReduction = rmPalette; // rmMonochrome;
var
SysPal: LogPal;
TmpBitmap: TBitmap;
begin
if not Assigned(SrcImage)
then Exit;
if not Assigned(DestImage)
then Exit;
SysPal.lPal.palVersion:= $300;
SysPal.lPal.palNumEntries:= 2;
with SysPal.lpal.palPalEntry[0] do begin
peRed:= 0;
peGreen:= 0;
peBlue:= 0;
peFlags:= PC_NOCOLLAPSE;
end;
with SysPal.dummy[1] do begin
peRed:= $FF;
peGreen:= $FF;
peBlue:= $FF;
peFlags:= PC_NOCOLLAPSE;
end;
TmpBitmap:= TBitmap.Create;
with SrcImage.Picture do begin
{
if (Graphic is TMetafile) or (Graphic is TIcon) then begin
TmpBitmap.Width:= Graphic.Width;
TmpBitmap.Height:= Graphic.Height;
TmpBitmap.Canvas.Draw(0, 0, Graphic);
end else begin
TmpBitmap.Assign(Graphic);
end;
}
TmpBitmap.Width:= Graphic.Width;
TmpBitmap.Height:= Graphic.Height;
TmpBitmap.Canvas.Draw(0, 0, Graphic);
end;
TmpBitmap:= GifImage.ReduceColors(TmpBitmap, ColorReduction, ADitherMode, 1, CreatePalette(SysPal.lpal));
with TmpBitmap do begin
HandleType:= bmDIB;
PixelFormat:= pf1bit;
Palette:= CreatePalette(SysPal.lpal);
end;
DestImage.Picture.Assign(TmpBitmap);
TmpBitmap.Free;
end;
//------------------ TScrolledImage ------------------
constructor TScrolledImage.Create(AOwner: TComponent; AParent: TWinControl;
APanBitmap: TBitmap; AImageList: TImageList; AOnClick: TNotifyEvent);
begin
inherited Create;
FPanBitmap:= APanBitmap;
FId:= -1;
FOwner:= AOwner;
FParent:= AParent;
FImageList:= AImageList;
Pnl:= TPanel.Create(AOwner);
Pnl.Visible:= False;
Pnl.Parent:= AParent;
Pnl.Align:= alNone;
Img:= TImage.Create(Pnl);
Img.Parent:= Pnl;
Img.Center:= True;
Img.Stretch:= False;
Img.Align:= alClient;
Pnl.OnClick:= RedirectClick;
Img.OnClick:= RedirectClick;
FOnClick:= AOnClick;
end;
procedure TScrolledImage.RedirectClick(Sender: TObject);
begin
if Assigned(FOnClick)
then FOnClick(Self); // not Sender!
end;
function TScrolledImage.GetLeft: Integer;
begin
Result:= Pnl.Left;
end;
procedure TScrolledImage.SetLeft(ALeft: Integer);
begin
Pnl.Left:= ALeft;
Img.Left:= Pnl.BevelWidth;
end;
function TScrolledImage.GetTop: Integer;
begin
Result:= Pnl.Top;
end;
procedure TScrolledImage.SetTop(ATop: Integer);
begin
Pnl.Top:= ATop;
Img.Top:= Pnl.BevelWidth;
end;
function TScrolledImage.GetWidth: Integer;
begin
Result:= Pnl.Width;
end;
procedure TScrolledImage.SetWidth(AWidth: Integer);
begin
Pnl.Width:= AWidth;
Img.Width:= Pnl.Width + 2 * (Pnl.BevelWidth + 1);
end;
function TScrolledImage.GetHeight: Integer;
begin
Result:= Pnl.Height;
end;
procedure TScrolledImage.SetHeight(AHeight: Integer);
begin
Pnl.Height:= AHeight;
Img.Height:= Pnl.Height + 2 * (Pnl.BevelWidth + 1);
end;
function TScrolledImage.GetVisible: Boolean;
begin
Result:= Pnl.Visible;
end;
procedure TScrolledImage.SetVisible(AVisible: Boolean);
begin
Pnl.Visible:= AVisible;
end;
procedure TScrolledImage.LoadFromFile(var AImageLoaderInfo: TImageLoaderInfo);
var
x, y: Integer;
begin
FFileName:= AImageLoaderInfo.Name;
Img.Picture.LoadFromFile(FFileName);
{
x:= (FPanImage.Width - Img.Picture.Graphic.Width) div 2;
y:= FPanImage.Height;
FPanImage.Height:= FPanImage.Height + 2 * Img.Picture.Graphic.Height;
FPanImage.Canvas.Draw(x, y, Img.Picture.Graphic);
}
Left:= AImageLoaderInfo.R.Left;
Top:= AImageLoaderInfo.R.Top;
// Width:= Img.Picture.Graphic.Width + 2 * (Pnl.BevelWidth + 1);
Width:= AImageLoaderInfo.R.Right;
Height:= Img.Picture.Graphic.Height + 2 * (Pnl.BevelWidth + 1);
AImageLoaderInfo.R.Top:= Top + Height;
Img.Hint:= Format('%s'#13#10'%dx%d', [ExtractFileName(AImageLoaderInfo.Name),
Img.Picture.Width, Img.Picture.Height]);
Img.ShowHint:= True;
end;
destructor TScrolledImage.Destroy;
begin
// Lbl and Img is child of Pnl, so can do Pnl.Free
Img.Free;
Pnl.Free;
inherited Destroy;
end;
//------------------ TScrolledImagesLoaderThread ------------------
constructor TScrolledImagesLoaderThread.Start(ACreateSuspended: Boolean; AScrolledImages: TScrolledImages;
AFiles: TStrings; ALoadLeft, ALoadWidth: Integer);
begin
FScrolledImages:= AScrolledImages;
FFiles:= AFiles;
FLoadLeft:= ALoadLeft;
FLoadWidth:= ALoadWidth;
inherited Create(ACreateSuspended);
end;
// uses FCurrentLoadImageNo inside TThread.Synchronize method
procedure TScrolledImagesLoaderThread.LoadImageToForm;
begin
with FScrolledImages.ScrolledImage[FImageLoaderInfo.No] do begin
try
LoadFromFile(FImageLoaderInfo);
if Assigned(FScrolledImages.FOnProgress) then begin
with Img.Picture do if Graphic is TMetafile then begin
FScrolledImages.FOnProgress(Self, FImageLoaderInfo.No, Format('%s %s %dx%d', [TMetafile(Graphic).Description,
TMetafile(Graphic).CreatedBy, Graphic.Width, Graphic.Height]));
end else begin
FScrolledImages.FOnProgress(Self, FImageLoaderInfo.No, Format('%dx%d', [Graphic.Width, Graphic.Height]));
end;
end;
except
if Assigned(FScrolledImages.FOnProgress) then begin
FScrolledImages.FOnProgress(Self, -1, Format('; Broken file %s', [FImageLoaderInfo.Name]));
end;
end;
end;
end;
procedure TScrolledImagesLoaderThread.Execute;
var
f: Integer;
begin
with FImageLoaderInfo do begin
R.Left:= FLoadLeft;
R.Top:= 0;
R.Right:= FLoadWidth;
R.Bottom:= 0; // FScrolledImages.Height;
end;
with FScrolledImages do begin
// ImagesCount:= FFiles.Count; - cannot create win controls from thread: HWND loss.
for f:= 0 to ImagesCount - 1 do begin
if Terminated
then Break;
with FImageLoaderInfo do begin
No:= f; // pass parameters thru record
Name:= FFiles[f];
end;
if FileExists(FImageLoaderInfo.Name) then begin
Synchronize(LoadImageToForm);
end else begin
if Assigned(FOnProgress) then begin
FOnProgress(Self, -1, Format('Load %s with errors', [FImageLoaderInfo.Name]));
end;
CurImage.Picture.Bitmap.FreeImage;
end;
end;
end;
end;
//------------------ TScrolledImagesDitherThread ------------------
constructor TScrolledImagesDitherThread.Start(ACreateSuspended: Boolean; ASrcScrolledImages, ADestScrolledImages: TScrolledImages;
ADitherMode: TDitherMode; ALoadLeft, ALoadWidth: Integer);
begin
FSrcScrolledImages:= ASrcScrolledImages;
FDestScrolledImages:= ADestScrolledImages;
FDitherMode:= ADitherMode;
FLoadLeft:= ALoadLeft;
FLoadWidth:= ALoadWidth;
inherited Create(ACreateSuspended);
end;
// uses FCurrentDitherImageNo inside TThread.Synchronize method
procedure TScrolledImagesDitherThread.DitherImageToForm;
begin
try
DoDither(FSrcScrolledImages.Image[FImageLoaderInfo.No],
FDestScrolledImages.Image[FImageLoaderInfo.No], FDitherMode);
if Assigned(FDestScrolledImages.FOnProgress) then begin
with FDestScrolledImages.ScrolledImage[FImageLoaderInfo.No].Img.Picture do if Graphic is TMetafile then begin
FDestScrolledImages.FOnProgress(Self, FImageLoaderInfo.No, Format('%s %s %dx%d', [TMetafile(Graphic).Description,
TMetafile(Graphic).CreatedBy, Graphic.Width, Graphic.Height]));
end else begin
FDestScrolledImages.FOnProgress(Self, FImageLoaderInfo.No, Format('%dx%d', [Graphic.Width, Graphic.Height]));
end;
end;
except
if Assigned(FDestScrolledImages.FOnProgress) then begin
FDestScrolledImages.FOnProgress(Self, -1, Format('; Cannot dither %d', [FImageLoaderInfo.No]));
end;
end;
end;
procedure TScrolledImagesDitherThread.Execute;
var
f: Integer;
begin
with FDestScrolledImages do begin
// ImagesCount:= FFiles.Count; - cannot create win controls from thread: HWND loss.
for f:= 0 to ImagesCount - 1 do begin
if Terminated
then Break;
FImageLoaderInfo.No:= f;
Synchronize(DitherImageToForm); // uses FCurrentDitherImageNo inside TThread.Synchronize method
end;
end;
end;
//------------------ TScrolledImages ------------------
constructor TScrolledImages.Create(AOwner: TComponent; AParent: TWinControl;
APanBitmap: TBitmap; AOnTerminateLoad, AOnTerminateDither: TNotifyEvent; AImageList: TImageList);
begin
inherited Create;
FPanBitmap:= APanBitmap;
FOnTerminateLoad:= AOnTerminateLoad;
FOnTerminateDither:= AOnTerminateDither;
FOwner:= AOwner;
FParent:= AParent;
FImageList:= AImageList;
SetLength(FScrolledImages, 0);
FLoaderThread:= Nil;
FDitherThread:= Nil;
FOnClick:= Nil;
end;
destructor TScrolledImages.Destroy;
begin
TerminateLoad;
SetLength(FScrolledImages, 0);
inherited;
end;
// TScrolledImages.LoadFiles implementation
function TScrolledImages.TerminateLoad: Boolean;
begin
Result:= False;
if Assigned(FLoaderThread) then with FLoaderThread do begin
Terminate;
WaitFor;
FLoaderThread:= Nil;
Result:= True;
end;
end;
function TScrolledImages.TerminateDither: Boolean;
begin
Result:= False;
if Assigned(FDitherThread) then with FDitherThread do begin
Terminate;
WaitFor;
FDitherThread:= Nil;
Result:= True;
end;
end;
procedure TScrolledImages.LoadFiles(AFiles: TStrings; ALoadLeft, ALoadWidth: Integer);
begin
if Assigned(FLoaderThread)
then Exit; // allready started
// allocate room
ImagesCount:= AFiles.Count;
// start loading images
FLoaderThread:= TScrolledImagesLoaderThread.Start(False, Self, AFiles,
ALoadLeft, ALoadWidth);
FLoaderThread.OnTerminate:= FOnTerminateLoad;
end;
procedure TScrolledImages.Dither(ASrc: TScrolledImages; ADitherMode: TDitherMode;
ALoadLeft, ALoadWidth: Integer);
begin
if Assigned(FDitherThread)
then Exit; // allready started
// start dithering images
FDitherThread:= TScrolledImagesDitherThread.Start(False, ASrc, Self, ADitherMode,
ALoadLeft, ALoadWidth);
FDitherThread.OnTerminate:= FOnTerminateDither;
end;
function TScrolledImages.GetCurImage: TImage;
begin
if (FCurImageNo < 0) or (FCurImageNo >= Length(FScrolledImages)) then begin
Result:= Nil;
Exit;
end;
Result:= FScrolledImages[FCurImageNo].Img;
end;
function TScrolledImages.GetScrolledImage(AImgNo: Integer): TScrolledImage;
begin
if (AImgNo < 0) or (AImgNo >= Length(FScrolledImages)) then begin
Result:= Nil;
Exit;
end;
Result:= FScrolledImages[AImgNo];
end;
function TScrolledImages.GetImage(AImgNo: Integer): TImage;
begin
if (AImgNo < 0) or (AImgNo >= Length(FScrolledImages)) then begin
Result:= Nil;
Exit;
end;
Result:= FScrolledImages[AImgNo].Img;
end;
function TScrolledImages.GetCurScrolledImage: TScrolledImage;
begin
Result:= GetScrolledImage(FCurImageNo);
end;
function TScrolledImages.GetImagesCount: Integer;
begin
Result:= Length(FScrolledImages);
end;
procedure TScrolledImages.SetImagesCount(ANewValue: Integer);
var
p, AOldValue: Integer;
begin
AOldValue:= Length(FScrolledImages);
// delete old images if new qty is less than previous
for p:= ANewValue to AOldValue - 1 do begin
FScrolledImages[p].Free;
end;
// set new array bounds
SetLength(FScrolledImages, ANewValue);
// allocate new ones if new qty is larger than previous
for p:= AOldValue to ANewValue - 1 do begin
FScrolledImages[p]:= TScrolledImage.Create(FOwner, FParent, FPanBitmap, FImageList, FOnClick);
end;
// make invisible and assign Click event handler
for p:= AOldValue to ANewValue - 1 do with FScrolledImages[p] do begin
Id:= p;
Visible:= True;
end;
// check pointer
if Length(FScrolledImages) = 0 then FCurImageNo:= -1 else begin
if FCurImageNo < 0
then FCurImageNo:= 0;
if FCurImageNo > ANewValue
then FCurImageNo:= ANewValue - 1;
end;
end;
function TScrolledImages.ImageMaxWidth: Integer;
var
p: Integer;
begin
Result:= 0;
for p:= 0 to ImagesCount - 1 do begin
with FScrolledImages[p].Img.Picture.Graphic do begin
if Result < Width
then Result:= Width;
end;
end;
end;
function TScrolledImages.GetImageNoByCoords(X, Y: Integer): Integer;
var
p: Integer;
begin
Result:= -1;
for p:= 0 to ImagesCount - 1 do begin
with FScrolledImages[p] do begin
if (x >= Left) and (x < Left+Width) and (y >= Top) and (y < Top+Height) then begin
Result:= p;
Exit;
end;
end;
end;
end;
function TScrolledImages.GetWidth: Integer;
begin
Result:= 0;
if ImagesCount <=0
then Exit;
Result:= FScrolledImages[0].Pnl.Width;
end;
procedure TScrolledImages.SetWidth(AWidth: Integer);
var
p: Integer;
begin
for p:= 0 to ImagesCount - 1 do begin
FScrolledImages[p].Width:= AWidth;
end;
end;
procedure TScrolledImages.SetCurImageNo(ACurNo: Integer);
var
cl: TColor;
begin
// if FCurImageNo = ACurNo then Exit;
if (ACurNo < 0) or (ACurNo >= ImagesCount) then begin
FCurImageNo:= -1;
Exit;
end;
// show selection
// cl:= FScrolledImages[ACurNo].Pnl.Color;
FScrolledImages[FCurImageNo].Pnl.Color:= clBtnFace;
// set value
FCurImageNo:= ACurNo;
if (FCurImageNo >= 0) and (FCurImageNo<ImagesCount)
then FScrolledImages[FCurImageNo].Pnl.Color:= clHighlight;
end;
procedure TScrolledImages.ArrangeImages;
var
p, y: Integer;
begin
y:= 0;
for p:= 0 to ImagesCount - 1 do begin
with FScrolledImages[p].Img do begin
Left:= 0;
Top:= y;
Inc(y, Height);
end;
Inc(y, 4); // delimiter space
end;
end;
end.
|
unit ExceptionJCLSupport;
interface
implementation
uses
SysUtils, Classes, JclDebug;
function GetExceptionStackInfoJCL(P: PExceptionRecord): Pointer;
const
cDelphiException = $0EEDFADE;
var
Stack: TJclStackInfoList;
Str: TStringList;
Trace: String;
Sz: Integer;
begin
if P^.ExceptionCode = cDelphiException then
Stack := JclCreateStackList(False, 3, P^.ExceptAddr)
else
Stack := JclCreateStackList(False, 3, P^.ExceptionAddress);
try
Str := TStringList.Create;
try
Stack.AddToStrings(Str, True, True, True, True);
Trace := Str.Text;
finally
FreeAndNil(Str);
end;
finally
FreeAndNil(Stack);
end;
if Trace <> '' then
begin
Sz := (Length(Trace) + 1) * SizeOf(Char);
GetMem(Result, Sz);
Move(Pointer(Trace)^, Result^, Sz);
end
else
Result := nil;
end;
function GetStackInfoStringJCL(Info: Pointer): string;
begin
Result := PChar(Info);
end;
procedure CleanUpStackInfoJCL(Info: Pointer);
begin
FreeMem(Info);
end;
initialization
Exception.GetExceptionStackInfoProc := GetExceptionStackInfoJCL;
Exception.GetStackInfoStringProc := GetStackInfoStringJCL;
Exception.CleanUpStackInfoProc := CleanUpStackInfoJCL;
end.
|
namespace Indigo;
interface
uses
System.Drawing,
System.Collections,
System.Collections.Generic,
System.Linq,
System.Windows.Forms,
System.ComponentModel,
System.ServiceModel, System.ServiceModel.Description;
type
/// <summary>
/// Summary description for MainForm.
/// </summary>
MainForm = partial class(System.Windows.Forms.Form)
private
method bGetServerTime_Click(sender: System.Object; e: System.EventArgs);
method bArithm_Click(sender: System.Object; e: System.EventArgs);
method InitChannel();
var
factory : ChannelFactory<IndigoServiceChannel>;
proxy : IndigoServiceChannel;
endpointChanged : Boolean;
method comboBoxEndpoints_SelectedIndexChanged(sender: System.Object; e: System.EventArgs);
protected
method Dispose(disposing: Boolean); override;
public
constructor;
end;
implementation
{$REGION Construction and Disposition}
constructor MainForm;
begin
//
// Required for Windows Form Designer support
//
InitializeComponent();
comboBoxEndpoints.SelectedIndex := 0;
end;
method MainForm.Dispose(disposing: Boolean);
begin
if disposing then begin
if assigned(components) then
components.Dispose();
//
// TODO: Add custom disposition code here
//
end;
inherited Dispose(disposing);
end;
{$ENDREGION}
method MainForm.bGetServerTime_Click(sender: System.Object; e: System.EventArgs);
begin
InitChannel;
MessageBox.Show("Server time is: " + proxy.GetServerTime().ToString() + Environment.NewLine + "Invoked endpoint: " + factory.Endpoint.Name);
end;
method MainForm.bArithm_Click(sender: System.Object; e: System.EventArgs);
var responce : CalculationMessage := new CalculationMessage();
operation : Char; Res : Decimal;
begin
if (radioButtonPlus.Checked) then operation := '+'
else
if (radioButtonMinus.Checked) then operation := '-'
else
if (radioButtonMult.Checked) then operation := '*'
else
if (radioButtonDiv.Checked) then operation := '/';
var numbers : Operands := new Operands;
numbers.operand1 := nudA.Value; numbers.operand2 := nudB.Value;
var request : CalculationMessage := new CalculationMessage(operation, numbers, Res);
InitChannel;
responce := proxy.Calculate(request);
MessageBox.Show("Result: " + responce.Res.ToString() + Environment.NewLine + "Invoked endpoint: " + factory.Endpoint.Name);
end;
method MainForm.InitChannel;
begin
if (endpointChanged) then
begin
factory := new ChannelFactory<IndigoServiceChannel>(comboBoxEndpoints.SelectedItem.ToString);
proxy := factory.CreateChannel();
endpointChanged := false;
end;
end;
method MainForm.comboBoxEndpoints_SelectedIndexChanged(sender: System.Object; e: System.EventArgs);
begin
endpointChanged := true;
end;
end. |
unit PhpDocument;
interface
uses
Classes, LrDocument;
type
TPhpDocument = class(TLrDocument)
protected
procedure LazyUpdate;
public
Php: TStringList;
constructor Create; override;
destructor Destroy; override;
procedure Activate; override;
procedure Deactivate; override;
procedure Open(const inFilename: string); override;
procedure Save; override;
end;
implementation
uses
PhpEdit;
{ TPhpDocument }
constructor TPhpDocument.Create;
begin
inherited;
EnableSaveAs('PHP Files', '.php');
Php := TStringList.Create;
end;
destructor TPhpDocument.Destroy;
begin
Php.Free;
inherited;
end;
procedure TPhpDocument.Open(const inFilename: string);
begin
Filename := inFilename;
Php.LoadFromFile(Filename);
end;
procedure TPhpDocument.Save;
begin
if Active then
LazyUpdate;
Php.SaveToFile(Filename);
end;
procedure TPhpDocument.LazyUpdate;
begin
inherited;
Php.Assign(PhpEditForm.Strings);
end;
procedure TPhpDocument.Activate;
begin
inherited;
PhpEditForm.Strings := Php;
PhpEditForm.BringToFront;
PhpEditForm.OnModified := ModificationEvent;
end;
procedure TPhpDocument.Deactivate;
begin
inherited;
PhpEditForm.OnModified := nil;
LazyUpdate;
end;
end.
|
{
The benchmark expects the path to the samples folder as a parameter
}
program parse_bench;
{$mode delphi}
uses
LazUtf8, Classes, SysUtils, DateUtils, FileUtil,
lgUtils, lgJson, JsonTools, FpJson, JsonParser;
type
TParseFun = function(const s: string): Boolean;
TParser = TGTuple2<string, TParseFun>;
function lgParse(const s: string): Boolean;
var
o: lgJson.TJsonNode;
begin
if lgJson.TJsonNode.TryParse(s, o) then
begin
o.Free;
exit(True);
end;
Result := False;
end;
function jtParse(const s: string): Boolean;
var
o: TJsonNode;
begin
o := TJsonNode.Create;
Result := o.TryParse(s);
o.Free;
end;
function fpParse(const s: string): Boolean;
var
o: TJSONData = nil;
begin
try
o := GetJSON(s);
Result := o <> nil;
if Result then
o.Free;
except
Result := False;
end;
end;
const
Parsers: array of TParser = [
(F1: 'lgJson'; F2: @lgParse),
(F1: 'JsonTools'; F2: @jtParse),
(F1: 'FpJson'; F2: @fpParse)];
Interval = 5000;
RepCount = 5;
var
SampleDir: string = '';
FileList: TGSharedRef<TStringList>;
procedure Run;
var
Stream: TGAutoRef<TStringStream>;
Parser: TParser;
CurrFile, FileName, JsonText: string;
I, Score, BestScore, Times: Integer;
Start: TTime;
begin
for CurrFile in FileList.Instance do
begin
Stream.Instance.LoadFromFile(CurrFile);
FileName := ExtractFileName(CurrFile);
JsonText := Stream.Instance.DataString;
for Parser in Parsers do
begin
BestScore := 0;
for I := 1 to RepCount do
begin
Times := 0;
Start := Time;
while MillisecondsBetween(Time, Start) < Interval do
begin
if not Parser.F2(JsonText) then
break;
Inc(Times);
end;
Score := Round(Length(JsonText) * Times/MillisecondsBetween(Time, Start));
if Score > BestScore then
BestScore := Score;
end;
WriteLn(StdErr, FileName, ' ', Parser.F1, ' ', BestScore);
WriteLn(FileName, ' ', Parser.F1, ' ', BestScore);
end;
end;
end;
begin
if ParamCount < 1 then exit;
if not DirectoryExists(ParamStr(1)) then exit;
SampleDir := ParamStr(1);
FileList.Instance := FindAllFiles(SampleDir);
Run;
end.
|
unit API_DragDrop;
interface
uses
Vcl.Forms,
Winapi.Messages,
Winapi.ShellAPI;
type
TDragDropEngine = class
private
FForm: TForm;
function GetFileCount(aDropHandle: HDROP): Integer;
function GetFileName(aDropHandle: HDROP; aIndx: Integer): string;
public
function GetDropedFiles(aMsg: TWMDropFiles): TArray<string>;
constructor Create(aForm: TForm);
destructor Destroy; override;
end;
implementation
function TDragDropEngine.GetFileName(aDropHandle: HDROP; aIndx: Integer): string;
var
FileNameLength: Integer;
begin
FileNameLength := DragQueryFile(aDropHandle, aIndx, nil, 0);
SetLength(Result, FileNameLength);
DragQueryFile(aDropHandle, aIndx, PChar(Result), FileNameLength + 1);
end;
function TDragDropEngine.GetFileCount(aDropHandle: HDROP): Integer;
begin
Result := DragQueryFile(aDropHandle, $FFFFFFFF, nil, 0);
end;
function TDragDropEngine.GetDropedFiles(aMsg: TWMDropFiles): TArray<string>;
var
FileCount: Integer;
i: Integer;
begin
Result := [];
FileCount := GetFileCount(aMsg.Drop);
for i := 0 to FileCount - 1 do
begin
Result := Result + [GetFileName(aMsg.Drop, i)];
end;
DragFinish(aMsg.Drop);
end;
constructor TDragDropEngine.Create(aForm: TForm);
begin
FForm := aForm;
DragAcceptFiles(FForm.Handle, True);
end;
destructor TDragDropEngine.Destroy;
begin
DragAcceptFiles(FForm.Handle, False);
end;
end.
|
unit StrUtils;
{
-ooooooooooooooooooooooooooooooooooooooooooooooooooooooo-
-o Título: Manipulação de strings o-
-o Descrição: Várias rotinas para tratamentos diversos o-
-o em strings o-
-o Autor: Waack3(Davi Ramos) o-
-o Última modificação: 01/03/02 16:30 o-
-o As descrições individuais estão abaixo: o-
-ooooooooooooooooooooooooooooooooooooooooooooooooooooooo-
}
interface
type
TSplitArray = array of string;
TDirEstilete = (deEsquerda, deDireita);
function InverterStr(Texto: string): string;
function Estilete(Texto: string; Ponto: integer; Direcao: TDirEstilete): string;
function PegarStr(Texto: string; Inicio: integer; Fim: integer): string;
function Substituir(Texto: string; String1: char; String2: char): string;
function CodiCgi(Texto: string): string;
function Split(const Source, Delimiter: String): TSplitArray;
function Posicao(Parte: string; Texto: string; Inicio: integer): integer;
procedure Chomp(var Texto: string);
implementation
uses
SysUtils;
//Inverte leitura dos caracteres de uma string(Waack3)
function InverterStr;
var
ContLetra: integer;
begin
for ContLetra:=Length(Texto) downto 1 do
result:=result + Texto[ContLetra];
end;
//Corta e retorna um lado inteiro de uma string de acordo com o ponto
//especificado(Waack3)
function Estilete;
var
ContLetra: integer;
begin
if ((Ponto >= 1) and (Ponto <= length(Texto))) then
begin
case Direcao of
deEsquerda:
begin
for ContLetra:=Ponto downto 1 do
result:=result + Texto[ContLetra];
result:=InverterStr(result);
end;
deDireita:
begin
for ContLetra:=Ponto to Length(Texto) do
result:=result + Texto[ContLetra];
end;
end;
end
else
result:='';
end;
//Retorna parte de uma string(especificando suas limitações)(Waack3)
function PegarStr;
var
Tamanho: integer;
begin
if ((Length(Texto) < Inicio) or (Inicio > Fim)) then
result:=''
else
begin
Tamanho:=(Fim - Inicio) + 1;
result:=Copy(Texto,Inicio,Tamanho);
end;
end;
//Substitui um caractere por outro em uma string(Waack3)
function Substituir;
var
ContLetra: integer;
begin
if Length(Texto) = 0 then
result:='';
for ContLetra:=1 to Length(Texto) do
begin
if Texto[ContLetra] = String1 then
Texto[ContLetra] := String2;
end;
result:=Texto;
end;
//Codifica o texto para ser recebido por um script CGI(Waack3)
function CodiCgi;
var
ContLetra: integer;
NovoChr: string;
begin
for ContLetra:=1 to Length(Texto) do
if Texto[ContLetra] in ['0'..'9','A'..'Z','a'..'z'] then
result:=result + Texto[ContLetra]
else
begin
NovoChr:='%' + IntToHex(Ord(Texto[ContLetra]),2);
result:=result + NovoChr;
end;
end;
//Divide uma string em várias partes(autor desconhecido)
function Split(const Source, Delimiter: String): TSplitArray;
var
iCount: Integer;
iPos: Integer;
iLength: Integer;
sTemp: String;
aSplit: TSplitArray;
begin
sTemp:=Source;
iCount:=0;
iLength:=Length(Delimiter) - 1;
repeat
iPos:=Pos(Delimiter, sTemp);
if iPos = 0 then
break
else
begin
Inc(iCount);
SetLength(aSplit, iCount);
aSplit[iCount - 1]:=Copy(sTemp, 1, iPos - 1);
Delete(sTemp, 1, iPos + iLength);
end;
until False;
if Length(sTemp) > 0 then
begin
Inc(iCount);
SetLength(aSplit, iCount);
aSplit[iCount - 1]:=sTemp;
end;
result:=aSplit;
end;
//Implementação aperfeiçoada da função Pos(Waack3)
function Posicao;
var
ContLetra: integer;
TmpString: string;
begin
result:=0;
for ContLetra:=Inicio to Length(Texto) do
begin
TmpString:=PegarStr(Texto, ContLetra, (ContLetra + (Length(Parte))) - 1);
if (TmpString = Parte) then
begin
result:=ContLetra;
break;
end;
end;
end;
//Retira quebra de linha
procedure Chomp;
var
TamTotal: integer;
Carac: string[2];
begin
TamTotal:=Length(Texto);
Carac[1]:=Texto[TamTotal - 1]; //Penúltimo caractere
Carac[2]:=Texto[TamTotal]; //Último caractere
if ((Carac[1] = #13) and (Carac[2] = #10)) then
Delete(Texto, TamTotal - 1, 2)
else if ((Carac[2] = #13) or (Carac[2] = #10)) then
Delete(Texto, TamTotal, 1);
end;
end.
|
unit MultiSelection;
interface
uses Classes, SysUtils;
Type
TMultiSelection=class(TStringList)
ApSC,ApWL,ApVX,ApOB:Integer;
Appended:Boolean;
Function AddSector(sc:Integer):Integer;
Function AddWall(sc,wl:Integer):Integer;
Function AddVertex(sc,vx:Integer):Integer;
Function AddObject(ob:Integer):Integer;
Function FindSector(sc:Integer):Integer;
Function FindWall(sc,wl:Integer):Integer;
Function FindVertex(sc,vx:Integer):Integer;
Function FindObject(ob:Integer):Integer;
Function GetSector(n:Integer):Integer;
Function GetWall(n:Integer):Integer;
Function GetVertex(n:Integer):Integer;
Function GetObject(n:Integer):Integer;
{ Procedure AppendSC(sc:Integer);
Procedure AppendWL(sc,wl:Integer);
Procedure AppendVX(sc,vx:Integer);
Procedure AppendOB(ob:Integer);}
end;
implementation
Function TMultiSelection.AddSector(sc:Integer):Integer;
begin
Result:=Add(Format('%4d',[sc]));
end;
Function TMultiSelection.AddWall(sc,wl:Integer):Integer;
begin
Result:=Add(Format('%4d%4d',[sc,wl]));
end;
Function TMultiSelection.AddVertex(sc,vx:Integer):Integer;
begin
Result:=Add(Format('%4d%4d',[sc,vx]));
end;
Function TMultiSelection.AddObject(ob:Integer):Integer;
begin
Result:=Add(Format('%4d',[ob]));
end;
Function TMultiSelection.FindSector(sc:Integer):Integer;
begin
Result:=IndexOf(Format('%4d',[sc]));
end;
Function TMultiSelection.FindWall(sc,wl:Integer):Integer;
begin
Result:=IndexOf(Format('%4d%4d',[sc,wl]));
end;
Function TMultiSelection.FindVertex(sc,vx:Integer):Integer;
begin
Result:=IndexOf(Format('%4d%4d',[sc,vx]));
end;
Function TMultiSelection.FindObject(ob:Integer):Integer;
begin
Result:=IndexOf(Format('%4d',[ob]));
end;
Function TMultiSelection.GetSector(n:Integer):Integer;
begin
Result:=StrToInt(Copy(Strings[n],1,4));
end;
Function TMultiSelection.GetWall(n:Integer):Integer;
begin
Result:=StrToInt(Copy(Strings[n],5,4));
end;
Function TMultiSelection.GetVertex(n:Integer):Integer;
begin
Result:=StrToInt(Copy(Strings[n],5,4));
end;
Function TMultiSelection.GetObject(n:Integer):Integer;
begin
Result:=StrToInt(Copy(Strings[n],1,4));
end;
end.
|
{ *********************************************************************** }
{ }
{ GUI Hangman }
{ Version 1.0 - First release of program }
{ Last Revised: 27nd of July 2004 }
{ Copyright (c) 2004 Chris Alley }
{ }
{ *********************************************************************** }
unit UGameReport;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, QRCtrls, QuickRpt, ExtCtrls;
type
TGameReportForm = class(TForm)
GameQuickRep: TQuickRep;
TitleBand1: TQRBand;
GameReportQRLabel: TQRLabel;
EasyQRLabel: TQRLabel;
NormalQRLabel: TQRLabel;
HardQRLabel: TQRLabel;
QRShape1: TQRShape;
QRShape2: TQRShape;
QRShape3: TQRShape;
GamesPlayedQRLabel1: TQRLabel;
AverageScoreQRLabel1: TQRLabel;
ChampionScoreQRLabel1: TQRLabel;
CurrentChampionQRLabel1: TQRLabel;
ChampionDatePlayedQRLabel1: TQRLabel;
GamesPlayedQRLabel2: TQRLabel;
AverageScoreQRLabel2: TQRLabel;
CurrentChampionQRLabel2: TQRLabel;
ChampionScoreQRLabel2: TQRLabel;
DatePlayedQRLabel2: TQRLabel;
EasyDatePlayedQRLabel: TQRLabel;
EasyChampionScoreQRLabel: TQRLabel;
EasyCurrentChampionQRLabel: TQRLabel;
EasyAverageScoreQRLabel: TQRLabel;
EasyGamesPlayedQRLabel: TQRLabel;
NormalAverageScoreQRLabel: TQRLabel;
NormalCurrentChampionQRLabel: TQRLabel;
NormalChampionScoreQRLabel: TQRLabel;
NormalDatePlayedQRLabel: TQRLabel;
NormalGamesPlayedQRLabel: TQRLabel;
HardCurrentChampionQRLabel: TQRLabel;
HardAverageScoreQRLabel: TQRLabel;
HardGamesPlayedQRLabel: TQRLabel;
HardDatePlayedQRLabel: TQRLabel;
HardChampionScoreQRLabel: TQRLabel;
DatePlayedQRLabel3: TQRLabel;
ChampionScoreQRLabel3: TQRLabel;
CurrentChampionQRLabel3: TQRLabel;
AverageScoreQRLabel3: TQRLabel;
GamesPlayedQRLabel3: TQRLabel;
private
{ Private declarations }
public
{ Public declarations }
end;
var
GameReportForm: TGameReportForm;
implementation
{$R *.dfm}
end.
|
unit FhirServerTests;
interface
uses
SysUtils,
IniFiles,
AdvObjects,
TerminologyServer;
Type
TFhirServerTests = class (TAdvObject)
private
FIni: TIniFile;
FTerminologyServer: TTerminologyServer;
procedure TestSnomedExpressions;
procedure SetTerminologyServer(const Value: TTerminologyServer);
public
destructor Destroy; override;
property ini : TIniFile read FIni write FIni;
property TerminologyServer : TTerminologyServer read FTerminologyServer write SetTerminologyServer;
procedure executeLibrary; // library functionality to test
procedure executeBefore; // before server is started
procedure executeRound1; // initial state - all loaded, but empty
procedure executeRound2; // 2nd cycle: after everything is loaded
procedure executeAfter;
end;
implementation
uses
SnomedServices, SnomedExpressions,
DecimalTests, UcumTests, JWTTests;
{ TFhirServerTests }
procedure TFhirServerTests.executeBefore;
begin
TestSnomedExpressions;
end;
procedure TFhirServerTests.executeLibrary;
begin
TDecimalTests.runTests;
TJWTTests.runTests;
TUcumTests.runTests(ExtractFilePath(FIni.FileName));
WriteLn('Library tests Passed');
end;
procedure TFhirServerTests.executeRound1;
begin
end;
procedure TFhirServerTests.executeRound2;
begin
end;
destructor TFhirServerTests.Destroy;
begin
FTerminologyServer.Free;
inherited;
end;
procedure TFhirServerTests.SetTerminologyServer(const Value: TTerminologyServer);
begin
FTerminologyServer.Free;
FTerminologyServer := Value;
end;
procedure TFhirServerTests.executeAfter;
begin
// import rf1
// import rf2
end;
procedure TFhirServerTests.TestSnomedExpressions;
begin
TSnomedExpressionParser.Parse(TerminologyServer.Snomed, '297186008 | motorcycle accident |').Free;
TSnomedExpressionParser.Parse(TerminologyServer.Snomed, '297186008').Free;
TSnomedExpressionParser.Parse(TerminologyServer.Snomed, '217724009 | accident caused by blizzard | +297186008 | motorcycle accident |').Free;
TSnomedExpressionParser.Parse(TerminologyServer.Snomed, '217724009 +297186008 | motorcycle accident |').Free;
TSnomedExpressionParser.Parse(TerminologyServer.Snomed, '217724009'#13#10' + 297186008 | motorcycle accident |'#13#10'').Free;
TSnomedExpressionParser.Parse(TerminologyServer.Snomed, '217724009 + 297186008 '#13#10'| motorcycle accident |').Free;
TSnomedExpressionParser.Parse(TerminologyServer.Snomed, '217724009 | accident caused by blizzard |:116680003 | is a | =297186008 | motorcycle accident |').Free;
TSnomedExpressionParser.Parse(TerminologyServer.Snomed, '297186008 | motorcycle accident |:116680003 | is a | =217724009 | accident caused by blizzard |').Free;
TSnomedExpressionParser.Parse(TerminologyServer.Snomed, '83152002 | oophorectomy |: 260686004 | method |=257820006| laser excision - action |').Free;
TSnomedExpressionParser.Parse(TerminologyServer.Snomed, '313056006 | epiphysis of ulna |:272741003 | laterality | =7771000 | left |').Free;
TSnomedExpressionParser.Parse(TerminologyServer.Snomed, '119189000 | ulna part | + 312845000 | epiphysis of upper limb |:272741003 | laterality | =7771000 | left |').Free;
TSnomedExpressionParser.Parse(TerminologyServer.Snomed, '83152002 | oophorectomy |:260686004 | method |=257820006| laser excision - action |,363704007 | procedure site | =20837000 | structure of right ovary |').Free;
TSnomedExpressionParser.Parse(TerminologyServer.Snomed, '120053002 | Salpingectomy |:260686004 | method | =261519002 | diathermy excision - action |,363704007 | procedure site | =113293009 | structure of left fallopian tube |').Free;
TSnomedExpressionParser.Parse(TerminologyServer.Snomed, '116028008 | salpingo-oophorectomy |').Free;
TSnomedExpressionParser.Parse(TerminologyServer.Snomed, '71388002 | procedure |:{260686004 | method | =129304002 | excision - action |,405813007 | procedure site - Direct | =15497006 | ovarian '+'structure |}{260686004 | method | =129304002 | excision - action |,405813007 | procedure site - Direct | =31435000 | fallopian tube structure |}').Free;
TSnomedExpressionParser.Parse(TerminologyServer.Snomed, '116028008 | salpingo-oophorectomy |: {260686004 | method |=257820006| laser excision - action |,363704007 | procedure site | =20837000 | structure of right ovary |}{260686004 | '+'method | =261519002 | diathermy excision - action |,363704007 | procedure site | =113293009 | structure of left fallopian tube |}').Free;
TSnomedExpressionParser.Parse(TerminologyServer.Snomed, '71620000 | fracture of femur |: 42752001 | due to | = (217724009 | accident caused by blizzard | +297186008 | motorcycle accident |)').Free;
TSnomedExpressionParser.Parse(TerminologyServer.Snomed, '24136001 | hip joint structure |: 272741003 | laterality | =7771000 | left |').Free;
TSnomedExpressionParser.Parse(TerminologyServer.Snomed, '397956004 | prosthetic arthroplasty of the hip |:363704007 | procedure site | = (24136001 | hip joint structure | :272741003 | laterality | =7771000 | left |)').Free;
TSnomedExpressionParser.Parse(TerminologyServer.Snomed, '397956004 | prosthetic arthroplasty of the hip |:363704007 | procedure site | = (24136001 | hip joint structure| :272741003 | laterality | =7771000 | left |) {363699004 |'+' direct device | =304120007 | total hip replacement prosthesis |,260686004 | method | =257867005 | insertion - action |}').Free;
TSnomedExpressionParser.Parse(TerminologyServer.Snomed, '243796009 | situation with explicit context |: {363589002 | associated procedure | = (397956004 | prosthetic arthroplasty of the hip |:363704007 | procedure site | = (24136001 | '+'hip joint structure | :272741003 | laterality | =7771000 | left |) {363699004 | direct device | =304120007 | total hip replacement prosthesis |, '+'260686004 | method | =257867005 | insertion - action |}), 408730004 | procedure context | =385658003 | done |, 408731000 | temporal context | =410512000 | current or specified |, 408732007 | subject relationship context |=410604004 | subject of record | }').Free;
end;
end.
|
unit uModAdjustmentFaktur;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics,
Controls, Forms, Dialogs, uModApp, uModBarang, uModRekening, uModDO, uModPO,
uModSuplier, uModUnit, System.Generics.Collections, uModSatuan,
Datasnap.DBClient;
type
TModAdjustmentFakturItem = class;
TModAdjustmentFaktur = class(TModApp)
private
FADJFAK_DATE_RCV: TDateTime;
FADJFAK_DATE: TDateTime;
FADJFAK_DATE_POSTED: TDateTime;
FADJFAK_DO: TModDO;
FADJFAK_IS_JURNAL: Integer;
FADJFAK_IS_POSTED: Integer;
FADJFAK_NO: string;
FADJFAK_PAYMENT: Double;
FADJFAK_PO: TModPO;
FADJFAK_PPN: Double;
FADJFAK_PPNBM: Double;
FADJFAK_REF: string;
FADJFAK_Suplier: TModSuplier;
FADJFAK_SuplierMerchanGroup: TModSuplierMerchanGroup;
FADJFAK_TOTAL_ADJ: Double;
FADJFAK_PPN_ADJ: Double;
FADJFAK_DISC_ADJ: Double;
FADJFAK_TOTAL_AFTER_DISC: Double;
FADJFAK_UNIT: TModUnit;
FAdjustmentFakturItems: TObjectList<TModAdjustmentFakturItem>;
function GetAdjustmentFakturItems: TObjectList<TModAdjustmentFakturItem>;
public
class function GetTableName: String; override;
property AdjustmentFakturItems: TObjectList<TModAdjustmentFakturItem> read
GetAdjustmentFakturItems write FAdjustmentFakturItems;
published
property ADJFAK_DATE_RCV: TDateTime read FADJFAK_DATE_RCV write
FADJFAK_DATE_RCV;
property ADJFAK_DATE: TDateTime read FADJFAK_DATE write FADJFAK_DATE;
property ADJFAK_DATE_POSTED: TDateTime read FADJFAK_DATE_POSTED write
FADJFAK_DATE_POSTED;
[AttributeOfForeign('DO_ID')]
property ADJFAK_DO: TModDO read FADJFAK_DO write FADJFAK_DO;
property ADJFAK_IS_JURNAL: Integer read FADJFAK_IS_JURNAL write
FADJFAK_IS_JURNAL;
property ADJFAK_IS_POSTED: Integer read FADJFAK_IS_POSTED write
FADJFAK_IS_POSTED;
[AttributeOfCode]
property ADJFAK_NO: string read FADJFAK_NO write FADJFAK_NO;
property ADJFAK_PAYMENT: Double read FADJFAK_PAYMENT write FADJFAK_PAYMENT;
[AttributeOfForeign('PO_ID')]
property ADJFAK_PO: TModPO read FADJFAK_PO write FADJFAK_PO;
property ADJFAK_PPN: Double read FADJFAK_PPN write FADJFAK_PPN;
property ADJFAK_PPNBM: Double read FADJFAK_PPNBM write FADJFAK_PPNBM;
property ADJFAK_REF: string read FADJFAK_REF write FADJFAK_REF;
[AttributeOfForeign('SUPLIER_ID')]
property ADJFAK_Suplier: TModSuplier read FADJFAK_Suplier write
FADJFAK_Suplier;
[AttributeOfForeign('SUPLIER_MERCHAN_GRUP_ID')]
property ADJFAK_SuplierMerchanGroup: TModSuplierMerchanGroup read
FADJFAK_SuplierMerchanGroup write FADJFAK_SuplierMerchanGroup;
property ADJFAK_TOTAL_ADJ: Double read FADJFAK_TOTAL_ADJ write
FADJFAK_TOTAL_ADJ;
property ADJFAK_PPN_ADJ: Double read FADJFAK_PPN_ADJ write FADJFAK_PPN_ADJ;
property ADJFAK_DISC_ADJ: Double read FADJFAK_DISC_ADJ write FADJFAK_DISC_ADJ;
property ADJFAK_TOTAL_AFTER_DISC: Double read FADJFAK_TOTAL_AFTER_DISC
write FADJFAK_TOTAL_AFTER_DISC;
[AttributeOfForeign('AUT$UNIT_ID')]
property ADJFAK_UNIT: TModUnit read FADJFAK_UNIT write FADJFAK_UNIT;
end;
TModAdjustmentFakturItem = class(TModApp)
private
FAdjustmentFaktur: TModAdjustmentFaktur;
FAFD_Barang: TModBarang;
FAFD_DISC: Double;
FAFD_DOItem: TModDOItem;
FAFD_OLD_DISC: Double;
FAFD_OLD_PRICE: Double;
FAFD_PPN: Double;
FAFD_PRICE: Double;
FAFD_QTY: Double;
FAFD_Satuan: TModSatuan;
FAFD_VAL_ADJ_AFTER_DISC: Double;
FAFD_VAL_ADJ_PPN: Double;
FAFD_VAL_ADJ_DISC: Double;
FAFD_VAL_ADJ_PPNBM: Double;
FAFD_VAL_ADJ_TOTAL: Double;
public
class function GetTableName: String; override;
published
[AttributeOfHeader('ADJUSTMENT_FAKTUR_ID')]
property AdjustmentFaktur: TModAdjustmentFaktur read FAdjustmentFaktur
write FAdjustmentFaktur;
[AttributeOfForeign('BARANG_ID')]
property AFD_Barang: TModBarang read FAFD_Barang write FAFD_Barang;
property AFD_DISC: Double read FAFD_DISC write FAFD_DISC;
[AttributeOfForeign('DO_DETAIL_ID')]
property AFD_DOItem: TModDOItem read FAFD_DOItem write FAFD_DOItem;
property AFD_OLD_DISC: Double read FAFD_OLD_DISC write FAFD_OLD_DISC;
property AFD_OLD_PRICE: Double read FAFD_OLD_PRICE write FAFD_OLD_PRICE;
property AFD_PPN: Double read FAFD_PPN write FAFD_PPN;
property AFD_PRICE: Double read FAFD_PRICE write FAFD_PRICE;
property AFD_QTY: Double read FAFD_QTY write FAFD_QTY;
[AttributeOfForeign('REF$SATUAN_ID')]
property AFD_Satuan: TModSatuan read FAFD_Satuan write FAFD_Satuan;
property AFD_VAL_ADJ_AFTER_DISC: Double read FAFD_VAL_ADJ_AFTER_DISC write
FAFD_VAL_ADJ_AFTER_DISC;
property AFD_VAL_ADJ_PPN: Double read FAFD_VAL_ADJ_PPN write
FAFD_VAL_ADJ_PPN;
property AFD_VAL_ADJ_DISC: Double read FAFD_VAL_ADJ_DISC write
FAFD_VAL_ADJ_DISC;
property AFD_VAL_ADJ_PPNBM: Double read FAFD_VAL_ADJ_PPNBM write
FAFD_VAL_ADJ_PPNBM;
property AFD_VAL_ADJ_TOTAL: Double read FAFD_VAL_ADJ_TOTAL write
FAFD_VAL_ADJ_TOTAL;
end;
implementation
{
***************************** TModAdjustmentFaktur *****************************
}
function TModAdjustmentFaktur.GetAdjustmentFakturItems:
TObjectList<TModAdjustmentFakturItem>;
begin
if not Assigned(FAdjustmentFakturItems) then
FAdjustmentFakturItems := TObjectList<TModAdjustmentFakturItem>.Create;
Result := FAdjustmentFakturItems;
end;
class function TModAdjustmentFaktur.GetTableName: String;
begin
Result := 'Adjustment_Faktur';
end;
class function TModAdjustmentFakturItem.GetTableName: String;
begin
Result := 'Adjustment_Faktur_Detil';
end;
initialization
TModAdjustmentFaktur.RegisterRTTI;
TModAdjustmentFakturItem.RegisterRTTI;
end.
|
unit MeshSetVertexNormals;
interface
uses LOD;
{$INCLUDE source/Global_Conditionals.inc}
type
TMeshSetVertexNormals = class
protected
FLOD: TLOD;
public
constructor Create(var _LOD: TLOD); virtual;
procedure Execute;
end;
implementation
uses MeshNormalVectorCalculator, GLConstants;
constructor TMeshSetVertexNormals.Create(var _LOD: TLOD);
begin
FLOD := _LOD;
end;
procedure TMeshSetVertexNormals.Execute;
var
i: integer;
Calculator: TMeshNormalVectorCalculator;
begin
Calculator := TMeshNormalVectorCalculator.Create;
for i := Low(FLOD.Mesh) to High(FLOD.Mesh) do
begin
// Calculate Vertex Normals
Calculator.FindMeshVertexNormals(FLOD.Mesh[i]);
FLOD.Mesh[i].SetNormalsType(C_NORMALS_PER_VERTEX);
FLOD.Mesh[i].ForceRefresh;
end;
Calculator.Free;
end;
end.
|
unit TimeoutControler;
interface
uses
Windows, SysUtils, Generics.Collections, RegistroControler, SyncObjs, Winapi.Messages, Classes, UAssyncControler;
Type
TProcedure = Procedure of object;
TTimeOut = Class(TObject)
Callback : TProc;
RestInterval : Integer;
LoopTimer: Boolean;
IDEvent : Integer;
Tag : Integer;
FreeOnTerminate: Boolean;
Assync: Boolean;
End;
Function SetTimeOut (CallBack: TProcedure; RestInterval: Integer; LoopTimer: Boolean = False; FreeOnTerminate: Boolean = True; Assync: Boolean = False):TTimeOut;overload;
Function SetTimeOut (CallBack: TProc; RestInterval: Integer; LoopTimer: Boolean = False; FreeOnTerminate: Boolean = True; Assync: Boolean = False):TTimeOut;overload;
Function SetInterval(CallBack: TProcedure; RestInterval: Integer; FreeOnTerminate: Boolean = True; Assync: Boolean = False):TTimeOut;overload;
Function SetInterval(CallBack: TProc; RestInterval: Integer; FreeOnTerminate: Boolean = True; Assync: Boolean = False):TTimeOut;overload;
Function Localizar(idEvent:UINT):Integer;
var
TimeOut : TList<TTimeOut>;
QtdeTimers : Integer;
implementation
procedure MyTimeout( hwnd: HWND; uMsg: UINT;idEvent: UINT ; dwTime : DWORD);
stdcall;
VAR
_CallBack : TProc;
_TimeOut: TTimeOut;
begin
_TimeOut := TimeOut.List[Localizar(idEvent)];
if not (_TimeOut.LoopTimer)
then KillTimer(0,IDEvent);
_CallBack := _TimeOut.Callback;
if not _TimeOut.Assync
then _CallBack
else begin
if (AssyncControler = nil)
then AssyncControler := TAssyncControler.Create(False);
AssyncControler.JogarProcedureNaFilaAssyncrona(_CallBack);
end;
if (_TimeOut.LoopTimer)
then _TimeOut.IDEvent := SetTimer(0, IDEvent, _TimeOut.RestInterval, @MyTimeOut)
else begin
if (_TimeOut.FreeOnTerminate) and not (_TimeOut.Assync) then begin
TimeOut.Remove(_TimeOut);
_TimeOut.Free;
_TimeOut := Nil;
end;
end;
end;
Function SetTimeOut(CallBack: TProc; RestInterval: Integer; LoopTimer: Boolean = False; FreeOnTerminate: Boolean = True; Assync: Boolean = False):TTimeOut;overload;
var Timer : TTimeOut;
begin
if TimeOut = nil
then TimeOut := TList<TTimeOut>.Create;
if (Assync) and (AssyncControler = nil)
then AssyncControler := TAssyncControler.Create;
QtdeTimers := QtdeTimers + 1;
Timer := TTimeOut.Create;
Timer.Callback := CallBack;
Timer.RestInterval := RestInterval;
Timer.LoopTimer := LoopTimer;
Timer.Tag := 0;
Timer.FreeOnTerminate := FreeOnTerminate;
Timer.Assync := Assync;
Timer.IDEvent := SetTimer(0, QtdeTimers, RestInterval, @MyTimeOut);
TimeOut.Add(Timer);
Result := Timer;
end;
function SetTimeOut(CallBack: TProcedure; RestInterval: Integer; LoopTimer: Boolean = False; FreeOnTerminate: Boolean = True; Assync: Boolean = False):TTimeOut;
begin
Result := SetTimeOut(procedure begin Callback end, RestInterval, LoopTimer, FreeOnTerminate, Assync);
end;
Function SetInterval(CallBack: TProcedure; RestInterval: Integer; FreeOnTerminate: Boolean = True; Assync: Boolean = False):TTimeOut;overload;
begin
Result := SetInterval(procedure begin CallBack end,RestInterval, FreeOnTerminate, Assync);
end;
Function SetInterval(CallBack: TProc; RestInterval: Integer; FreeOnTerminate: Boolean = True; Assync: Boolean = False):TTimeOut;overload;
begin
Result := SetTimeOut(CallBack, RestInterval, True, FreeOnTerminate, Assync);
end;
Function Localizar(idEvent:UINT):Integer;
var I : Integer;
begin
for I := 0 to TimeOut.Count - 1 do
if TimeOut.List[I].IDEvent = idEvent then break;
Result := I;
end;
end.
|
unit uSubModelImage;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uParentSub, siComp, siLangRT, ExtCtrls, DB, ADODB, Buttons,
StdCtrls, ExtDlgs;
type
TSubModelImage = class(TParentSub)
pnlImgPath: TPanel;
imgItem: TImage;
quModelImage: TADODataSet;
quModelImageLargeImage: TStringField;
edtLargeImage: TEdit;
sbOpenFile: TSpeedButton;
OP: TOpenPictureDialog;
Label1: TLabel;
ImageBevel: TBevel;
quModelImageLargeImage2: TStringField;
sbRemove: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure sbOpenFileClick(Sender: TObject);
procedure sbRemoveClick(Sender: TObject);
private
{ Private declarations }
fLargeImagePath : String;
fImageNum : Integer;
fIDModel : Integer;
procedure LoadImage;
procedure SetImage;
procedure RefreshImage;
procedure DataSetRefresh;
procedure DataSetOpen; override;
procedure DataSetClose; override;
protected
procedure AfterSetParam; override;
public
{ Public declarations }
end;
implementation
uses uDM, uParamFunctions;
{$R *.dfm}
procedure TSubModelImage.LoadImage;
begin
If (fLargeImagePath<>'') and FileExists(fLargeImagePath) then
begin
imgItem.Picture.LoadFromFile(fLargeImagePath);
end
else
begin
imgItem.Picture := nil;
end;
end;
procedure TSubModelImage.RefreshImage;
begin
SetImage;
LoadImage;
end;
procedure TSubModelImage.AfterSetParam;
var
fStartImage : String;
fColor : String;
begin
if FParam = '' then
Exit;
fIDModel := StrToIntDef(ParseParam(FParam, 'IDModel'),0);
fStartImage := ParseParam(FParam, 'StartImage');
pnlImgPath.Visible := (StrToIntDef(ParseParam(FParam, 'ShowOpen'),0)=1);
fColor := ParseParam(FParam, 'BackColor');
imgItem.Stretch := (ParseParam(FParam, 'Stretch')='T');
fImageNum := (StrToIntDef(ParseParam(FParam, 'ImageNum'),1));
ImageBevel.Visible := not (ParseParam(FParam, 'Bevel')='F');
if fColor <> '' then
Self.Color := StringToColor(fColor);
if fStartImage <> '' then
begin
fLargeImagePath := fStartImage;
LoadImage;
Exit;
end;
DataSetRefresh;
RefreshImage;
end;
procedure TSubModelImage.DataSetRefresh;
begin
DataSetClose;
DataSetOpen;
end;
procedure TSubModelImage.SetImage;
begin
case fImageNum of
1 : fLargeImagePath := quModelImageLargeImage.AsString;
2 : fLargeImagePath := quModelImageLargeImage2.AsString;
else fLargeImagePath := quModelImageLargeImage.AsString;
end;
edtLargeImage.Text := fLargeImagePath;
end;
procedure TSubModelImage.DataSetOpen;
begin
with quModelImage do
if not Active then
begin
Parameters.ParamByName('IDModel').Value := fIDModel;
Open;
end;
end;
procedure TSubModelImage.DataSetClose;
begin
with quModelImage do
if Active then
Close;
end;
procedure TSubModelImage.FormCreate(Sender: TObject);
begin
inherited;
DM.imgSmall.GetBitmap(BTN18_OPEN,sbOpenFile.Glyph);
DM.imgSmall.GetBitmap(BTN18_DELETE,sbRemove.Glyph);
// SetButtonOpenEnabled(True);
// SetButtonRemoveEnabled(True);
end;
procedure TSubModelImage.FormDestroy(Sender: TObject);
begin
inherited;
DataSetClose;
end;
procedure TSubModelImage.sbOpenFileClick(Sender: TObject);
begin
inherited;
if OP.Execute then
with quModelImage do
if Active then
begin
Edit;
case fImageNum of
1 : quModelImageLargeImage.AsString := OP.FileName;
2 : quModelImageLargeImage2.AsString := OP.FileName;
else quModelImageLargeImage.AsString := OP.FileName;
end;
Post;
RefreshImage;
end;
end;
procedure TSubModelImage.sbRemoveClick(Sender: TObject);
begin
inherited;
with quModelImage do
if Active then
begin
Edit;
case fImageNum of
1 : quModelImageLargeImage.AsString := '';
2 : quModelImageLargeImage2.AsString := '';
else quModelImageLargeImage.AsString := '';
end;
Post;
RefreshImage;
end;
end;
initialization
RegisterClass(TSubModelImage);
end.
|
// Proof-of-Concept attempt at using a Memo or RichMemo to scroll arbitrarily-sized
// data from both small and large (over 1 million) query datasets
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, SynEdit, RichMemo, Forms, Controls, Graphics,
Dialogs, StdCtrls, ExtCtrls, VirtualDBScrollMemo, windows, types, sqlite3conn,
sqldb, db;
type
{ TForm1 }
TForm1 = class(TForm)
btnSetMax: TButton;
btnQuery: TButton;
chkInitial: TCheckBox;
DataSource1: TDataSource;
Label2: TLabel;
lblCurrentChunk: TLabel;
txtNumber: TEdit;
SQLite3Connection1: TSQLite3Connection;
SQLQuery1: TSQLQuery;
SQLTransaction1: TSQLTransaction;
txtSetMax: TEdit;
Label1: TLabel;
lblScrollPos: TLabel;
Label3: TLabel;
Label4: TLabel;
lblScrollMax: TLabel;
lblMemoLineViaScrollBar: TLabel;
Label7: TLabel;
lblCaretPosLine: TLabel;
RichMemo1: TRichMemo;
ScrollBar1: TScrollBar;
VirtualDBScrollMemo1: TVirtualDBScrollMemo;
procedure btnQueryClick(Sender: TObject);
procedure btnSetMaxClick(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure RichMemo1Change(Sender: TObject);
procedure RichMemo1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure ScrollBar1Scroll(Sender: TObject; ScrollCode: TScrollCode;
var ScrollPos: Integer);
procedure MoveToLine(LineNo : Integer);
function GetVisibleLineCount(Memo: TRichMemo): Integer;
private
{ private declarations }
FSearching: Boolean; // Are we currently conducting a search?
FRecCount : Integer; // Total number of records in our query
FChunksCount : Integer; // Count of the number of chunks resulting from the current query
FChunkLineCounts : Array of Integer;
FCurrentChunk : Integer; // Tracks which chunk is currently at the center of display
FPageSize : Integer; // How many lines are visible
function performQuery(queryCenterChunk : Integer; resetQuery : Boolean): Boolean;
public
{ public declarations }
const
FChunkSize : Integer = 10; // Number of records per chunk
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.ScrollBar1Scroll(Sender: TObject; ScrollCode: TScrollCode;
var ScrollPos: Integer);
var
smallStep : Integer;
stepsPerLine : Integer;
linesCurrentChunkSet : Integer;
FTempCurrentChunk : Integer;
scrollingDone : Boolean;
begin
scrollingDone := False;
// linesCurrentChunkSet := FChunkLineCounts[FCurrentChunk-1] + FChunkLineCounts[FCurrentChunk] + FChunkLineCounts[FCurrentChunk+1];
// smallstep is how many positions we move on the scrollbar for each arrow press on the scrollbar
// smallStep := (ScrollBar1.Max div RichMemo1.Lines.Count);
// affected by the current chunk nymber and number of lines
smallStep := (ScrollBar1.Max div FChunksCount) div RichMemo1.Lines.Count;
// if we have 600 records we have 10 chunks and 600,000 positions on scrollbar1
// if we're in chunk 3 for instance (visible chunks 2-4):
// scrollbar positions are 6,000 through 18,000
// correlate with lines 0 through linesCurrentChunkSet
// stepsPerLine is how many positions on the scrollbar moves the caret one line hown in the richmemo
stepsPerLine := (ScrollBar1.Max) div (FChunksCount * RichMemo1.Lines.Count);
case ScrollCode of
scLineUp : ScrollPos := ScrollPos - (smallStep - 1);
scLineDown : ScrollPos := ScrollPos + smallStep - 1;
scPageUp : ScrollPos := ScrollPos - (smallStep * FPageSize);
scPageDown : ScrollPos := ScrollPos + (smallStep * FPageSize);
scEndScroll : scrollingDone := True;
scBottom : scrollingDone := True;
scTop : scrollingDone := True;
end;
// Calculate the current chunk based upon current scrollbar position
FTempCurrentChunk := (((Scrollbar1.Position div 1000) div FChunkSize) + 1);
if scrollingDone then
begin
// We only update the richmemo contents if we've moved to a new chunk
if (FTempCurrentChunk > FCurrentChunk) and (FTempCurrentChunk < FChunksCount - 1) then
begin
///ShowMessage('FTempCurrentChunk ' + IntToStr(FTempCurrentChunk) + ' > FCurrentChunk ' + IntToStr(FCurrentChunk));
FCurrentChunk := FTempCurrentChunk;
performQuery(FCurrentChunk, False);
// Move the caret to the start of new middle chunk
// By taking the count of the chunk above it
MoveToLine(FChunkLineCounts[FCurrentChunk-1]);
end
else if (FTempCurrentChunk < FCurrentChunk) and (FTempCurrentChunk < FChunksCount - 1) then
begin
///ShowMessage('FTempCurrentChunk ' + IntToStr(FTempCurrentChunk) + ' < FCurrentChunk ' + IntToStr(FCurrentChunk));
FCurrentChunk := FTempCurrentChunk;
performQuery(FCurrentChunk, False);
// Move the caret to the end of new middle chunk
// By taking the line counts of the current chunk and the one above it
MoveToLine(FChunkLineCounts[FCurrentChunk-1] + FChunkLineCounts[FCurrentChunk]);
end
else
begin
// Move the caret
//MoveToLine(ScrollBar1.Position div ((ScrollBar1.Max div FChunksCount) div RichMemo1.Lines.Count));
end;
end;
// Move the caret
//MoveToLine(ScrollBar1.Position div ((ScrollBar1.Max div FChunksCount) div RichMemo1.Lines.Count));
// if we have 600 records we have 10 chunks and 600,000 positions on scrollbar1
// if we're in chunk 3 for instance (visible chunks 2-4):
// scrollbar positions are 6,000 through 18,000
// correlate with lines 0 through linesCurrentChunkSet
// if we're at position 9200, we're about half-way through chunk 3
lblCurrentChunk.Caption := IntToStr(FCurrentChunk);
lblScrollPos.Caption := IntToStr(ScrollPos);
// The following two lines should result in the same number
lblMemoLineViaScrollBar.Caption := IntToStr(ScrollBar1.Position div RichMemo1.Lines.Count);
lblCaretPosLine.Caption := IntToStr(RichMemo1.CaretPos.y);
end;
procedure TForm1.MoveToLine(LineNo: Integer);
begin
RichMemo1.CaretPos := Point(0, LineNo);
RichMemo1.SetFocus;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
lblScrollMax.Caption := IntToStr(ScrollBar1.Max);
// Approximates how many lines are in the visible memo area
FPageSize := GetVisibleLineCount(RichMemo1);
end;
procedure TForm1.RichMemo1Change(Sender: TObject);
begin
FSearching := False;
end;
procedure TForm1.RichMemo1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
linePercentage : Integer;
begin
lblCaretPosLine.Caption:=IntToStr(RichMemo1.CaretPos.y);
// Need to update this. Currently it's based upon a constant line count
//ScrollBar1.Position := RichMemo1.CaretPos.y * RichMemo1.Lines.Count;
// This is percentage of the way through the Richmemo we're currently:
linePercentage := ((RichMemo1.CaretPos.y * 100) div RichMemo1.Lines.Count);
{
We can then use that to calculate where the scrollbar should be
half-way through chunk 2
(line_percentage + (FCurrentChunk*100) - 100) * (FChunkSize * 10) = position 90000
30% through chunk 3
(line_percentage + (FCurrentChunk*100) - 100) * (FChunkSize * 10) = position 138,000
50% through chunk 3
(line_percentage + (FCurrentChunk*100) - 100) * (FChunkSize * 10) = position 150,000
half-way through chunk 4
(line_percentage + (FCurrentChunk*100) - 100) * (FChunkSize * 10) = position 210,000
}
ScrollBar1.Position := (linePercentage + (FCurrentChunk * 100) - 100) * FChunkSize * 10;
//ShowMessage(IntToStr((linePercentage + (FCurrentChunk * 100) - 100) * FChunkSize * 10));
lblMemoLineViaScrollBar.Caption := IntToStr(ScrollBar1.Position div RichMemo1.Lines.Count);
lblScrollPos.Caption := IntToStr(ScrollBar1.Position);
end;
procedure TForm1.FormResize(Sender: TObject);
begin
// Approximates how many lines are in the visible memo area
FPageSize := GetVisibleLineCount(RichMemo1);
end;
function TForm1.performQuery(queryCenterChunk : Integer; resetQuery : Boolean): Boolean;
var
i, currLines : Integer;
queryCurrentChunk : Integer;
begin
SQLite3Connection1.Close;
SQLite3Connection1.DatabaseName := './DB/DBTest.db3';
SQLite3Connection1.Open;
SQLTransaction1.Active := True;
RichMemo1.Lines.BeginUpdate;
//RichMemo1.Visible := False;
RichMemo1.Lines.Clear;
//ScrollBar1.Visible := False;
if resetQuery = True then
begin
with SQLQuery1 do
begin
Close;
SQL.Text := 'Select * FROM Entries';
Prepare;
Open;
// Need to call Last in order to get accurate total record count
Last;
FRecCount := RecordCount;
ScrollBar1.Max := FRecCount * 1000;
lblScrollMax.Caption := IntToStr(ScrollBar1.Max);
//SetLength(FLineCounts, FRecCount);
// Count the number of chunks
if FRecCount mod FChunkSize = 0 then
begin
FChunksCount := FRecCount div FChunkSize;
SetLength(FChunkLineCounts, FRecCount div FChunkSize);
end
else
begin
FChunksCount := (FRecCount div FChunkSize) + 1;
SetLength(FChunkLineCounts, (FRecCount div FChunkSize) + 1);
end;
First;
//UniDirectional := True;
// Pull the first 3 chunks
for i := 1 to 3 do
begin
queryCurrentChunk := i;
currLines := RichMemo1.Lines.Count;
if (((queryCurrentChunk - 1) * FChunkSize) + 1) < FRecCount then // Make sure we're not outside the range of records in this query
begin
RecNo := ((queryCurrentChunk - 1) * FChunkSize) + 1; // If set 1, then we're at RecNo 1
while (RecNo < (((queryCurrentChunk) * FChunkSize) + 1)) AND (RecNo < FRecCount) do
begin
RichMemo1.Lines.Append('Entry ID: ' + FieldByName('id').AsString + ' - Name: ' + FieldByName('Name').AsString);
RichMemo1.Lines.Append('Entry: ' + FieldByName('Entry').AsString);
RichMemo1.Lines.Append('');
//ShowMessage(IntToStr(RecNo));
//FLineCounts[RecNo-1] := RichMemo1.Lines.Count - currLines;
Next;
end;
performQuery := True;
end
else
begin
ShowMessage('Beyond query range');
performQuery := False;
end;
FChunkLineCounts[i] := RichMemo1.Lines.Count - currLines;
end;
end;
// Display the line counts for the current 3 chunks
//ShowMessage(IntToStr(FChunkLineCounts[1]) + ' ' + IntToStr(FChunkLineCounts[2]) + ' ' + IntToStr(FChunkLineCounts[3]));
end
else
begin // The query has already been set. Now we're just scrolling
with SQLQuery1 do
begin
Close;
SQL.Text := 'Select * FROM Entries';
Prepare;
Open;
// We skip the whole 'Last' part here because we already counted the records on the initial query
// Pull the first 3 chunks
for i := (queryCenterChunk - 1) to (queryCenterChunk + 1) do
begin
queryCurrentChunk := i;
currLines := RichMemo1.Lines.Count;
if (((queryCurrentChunk - 1) * FChunkSize) + 1) < FRecCount then // Make sure we're not outside the range of records in this query
begin
RecNo := ((queryCurrentChunk - 1) * FChunkSize) + 1; // If set 1, then we're at RecNo 1
while (RecNo < (((queryCurrentChunk) * FChunkSize) + 1)) AND (RecNo < FRecCount) do
begin
RichMemo1.Lines.Append('Entry ID: ' + FieldByName('id').AsString + #9#9 + ' Name: ' + FieldByName('Name').AsString);
RichMemo1.Lines.Append('Entry: ' + FieldByName('Entry').AsString);
RichMemo1.Lines.Append('');
//ShowMessage(IntToStr(RecNo));
//FLineCounts[RecNo-1] := RichMemo1.Lines.Count - currLines;
Next;
end;
performQuery := True;
end
else
begin
ShowMessage('Beyond query range');
performQuery := False;
end;
FChunkLineCounts[i] := RichMemo1.Lines.Count - currLines;
end;
end;
// Display the line counts for the current 3 chunks
// ShowMessage(IntToStr(FChunkLineCounts[queryCenterChunk-1]) + ' ' + IntToStr(FChunkLineCounts[queryCenterChunk]) + ' ' + IntToStr(FChunkLineCounts[queryCenterChunk+1]));
end;
//RichMemo1.Visible := True;
RichMemo1.Lines.EndUpdate;
//ScrollBar1.Visible := True;
SQLTransaction1.Commit;
SQLTransaction1.StartTransaction;
SQLTransaction1.Active := False;
SQLite3Connection1.Connected := False;
SQLite3Connection1.Close;
RichMemo1.Repaint;
RichMemo1.SetFocus;
//MoveToLine(1);
end;
procedure TForm1.btnQueryClick(Sender: TObject);
var
dontCare : Integer;
begin
if chkInitial.Checked then
begin
performQuery(StrToInt(txtNumber.Text), True);
end
else
begin
performQuery(StrToInt(txtNumber.Text), False);
end;
ScrollBar1Scroll(nil, scTop, dontCare);
chkInitial.Checked := False;
end;
function TForm1.GetVisibleLineCount(Memo: TRichMemo): Integer;
var
OldFont : HFont;
Hand : THandle;
TM : TTextMetric;
tempint : integer;
begin
Hand := GetDC(Memo.Handle);
try
OldFont := SelectObject(Hand, Memo.Font.Handle);
try
GetTextMetrics(Hand, TM);
tempint:=Memo.Height div TM.tmHeight;
finally
SelectObject(Hand, OldFont);
end;
finally
ReleaseDC(Memo.Handle, Hand);
end;
Result := tempint;
end;
end.
|
{* ***** BEGIN LICENSE BLOCK *****
Copyright 2009 Sean B. Durkin
This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free
software being offered under a dual licensing scheme: LGPL3 or MPL1.1.
The contents of this file are subject to the Mozilla Public License (MPL)
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
Alternatively, you may redistribute it and/or modify it under the terms of
the GNU Lesser General Public License (LGPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
You should have received a copy of the Lesser GNU General Public License
along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>.
TurboPower LockBox is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. In relation to LGPL,
see the GNU Lesser General Public License for more details. In relation to MPL,
see the MPL License for the specific language governing rights and limitations
under the License.
The Initial Developer of the Original Code for TurboPower LockBox version 2
and earlier was TurboPower Software.
* ***** END LICENSE BLOCK ***** *}
unit uTPLb_BlockCipher;
interface
uses SysUtils, Classes, uTPLb_StreamCipher;
type
IBlockCodec = interface
['{7E783A4E-EF17-4820-AB33-EF8EF9DA6F22}']
procedure Encrypt_Block( Plaintext{in}, Ciphertext{out}: TMemoryStream);
procedure Decrypt_Block( Plaintext{out}, Ciphertext{in}: TMemoryStream);
procedure Reset;
procedure Burn;
end;
IBlockCipher = interface( ICryptoGraphicAlgorithm)
['{CB927B43-8A02-4332-B844-A174D1D6B705}']
function GenerateKey( Seed: TStream): TSymetricKey;
function LoadKeyFromStream( Store: TStream): TSymetricKey;
function BlockSize: integer; // in units of bits. Must be a multiple of 8.
function KeySize: integer; // in units of bits.
function SeedByteSize: integer; // Size that the input of the GenerateKey must be.
function MakeBlockCodec( Key: TSymetricKey): IBlockCodec;
function SelfTest_Key: TBytes; // Hex string; may be oriented into
// u32 groups. Input to GenerateKey();
function SelfTest_Plaintext: TBytes; // Hex string;
// may be oriented into u32 groups. Input to Encrypt_Block();
function SelfTest_Ciphertext: TBytes; // Hex string;
// may be oriented into u32 groups. Reference for Encrypt_Block() output;
end;
TBlockChainLink = class
protected
FKey: TSymetricKey;
FCV: TMemoryStream;
FCipher: IBlockCodec;
constructor BaseCreate(
Key1: TSymetricKey; // Will be referenced, not cloned.
IV1: TMemoryStream; // Will be cloned.
Cipher1: IBlockCodec); // Will be referenced, not cloned.
public
procedure Burn; virtual;
procedure Reset( IV: TMemoryStream); virtual;
function Clone: TBlockChainLink; virtual;
procedure Encrypt_Block( Plaintext{in}, Ciphertext{out}: TMemoryStream); virtual; abstract;
procedure Decrypt_Block( Plaintext{out}, Ciphertext{in}: TMemoryStream); virtual; abstract;
// The following 2 methods are ONLY applicable in the case of
// cf8bit in IBlockChainingModel.ChainingFeatures;
// For example, 8-bit CFB mode.
// Do not implement in other cases.
procedure Encrypt_8bit( Plaintext{in}: byte; var Ciphertext{out}: byte); virtual;
procedure Decrypt_8bit( var Plaintext{out}: byte; Ciphertext{in}: byte); virtual;
destructor Destroy; override;
end;
TChainingFeature = (
cfNoNounce, // The chaining mode does not require any nounce nor
// does it require an IV. Ex: ECB
cfKeyStream, // A key-stream is at the heart of the chaining mode
// The final partial block can be padded arbitarily,
// encrypted as usual, and then truncated to the same
// length as the corresponding plaintext input.
// Examples: CFB, 8-bit CFB, OFB and CTR.
// Counter-examples: ECB and CBC
cfAutoXOR, // Only applies to cfKeyStream. This means that the
// cipher XORs the plaintext/ciphertext with the keystream.
// In this case, this XOR operation is done by the
// IBlockChainingModel client and not the IBlockChainingModel
// itself.
cf8bit // Plaintext and cipher text are processed one byte at a time.
// Example: 8-bit CFB.
// A chaining mode with cf8Bit MUST also have
// cfKeyStream and not cfNoNounce
);
TChainingFeatureSet = set of TChainingFeature;
IBlockChainingModel = interface( ICryptoGraphicAlgorithm)
['{7ED854DF-5270-41F7-820A-65BF9B5E1D35}']
function Chain_EncryptBlock(
Key: TSymetricKey; InitializationVector: TMemoryStream;
const Cipher: IBlockCodec): TBlockChainLink;
function Chain_DecryptBlock(
Key: TSymetricKey; InitializationVector: TMemoryStream;
const Cipher: IBlockCodec): TBlockChainLink;
function ChainingFeatures: TChainingFeatureSet;
end;
IBlockCipherSelector = interface
['{B08F766E-1EB0-4BA0-9C84-8AF02E13B24C}']
function GetBlockCipher : IBlockCipher;
function GetChainMode : IBlockChainingModel;
// IBlockCipherSelector s such as TCodec and other config holders
// should also implement IBlockCipherSelectorEx2
end;
TSymetricEncryptionOption = (
optUseGivenIV, // Use the given IV instead of generating one.
// This option is not recommended unless trying to achieve
// interoperability with OpenSSL.
optOpenSSL_CompatibilityMode // Use OpenSSL style of block padding, instead of the normal LockBox style.
// This option is not recommended unless trying to achieve
// interoperability with OpenSSL.
);
TSymetricEncryptionOptionSet = set of TSymetricEncryptionOption;
TSetMemStreamProc = procedure ( Value: TMemoryStream) of object;
IBlockCipherSelectorEx2 = interface( IBlockCipherSelector)
['{907D6E07-C840-4EB4-888A-146B94BDFB53}']
function GetAdvancedOptions2 : TSymetricEncryptionOptionSet;
function hasOnSetIVHandler( var Proc: TSetMemStreamProc): boolean;
end;
implementation
uses uTPLb_StreamUtils;
{ TBlockChainLink }
constructor TBlockChainLink.BaseCreate(
Key1: TSymetricKey; IV1: TMemoryStream; Cipher1: IBlockCodec);
begin
FKey := Key1; // Not owned
FCV := CloneMemoryStream( IV1); // Owned.
FCipher := Cipher1 // Not owned
end;
procedure TBlockChainLink.Burn;
begin
BurnMemoryStream( FCV);
FKey := nil // key is not owned by the chain link.
end;
type TBlockChainLinkClass = class of TBlockChainLink;
function TBlockChainLink.Clone: TBlockChainLink;
var
Cls: TBlockChainLinkClass;
begin
Cls := TBlockChainLinkClass( ClassType);
result := Cls.BaseCreate( FKey, FCV, FCipher)
end;
procedure TBlockChainLink.Encrypt_8bit( Plaintext: byte; var Ciphertext: byte);
begin
Ciphertext := Plaintext
end;
procedure TBlockChainLink.Reset( IV: TMemoryStream);
begin
CopyMemoryStream( IV, FCV)
end;
procedure TBlockChainLink.Decrypt_8bit( var Plaintext: byte; Ciphertext: byte);
begin
Plaintext := Ciphertext
end;
destructor TBlockChainLink.Destroy;
begin
FCV.Free;
inherited;
end;
end.
|
unit BitBtnVCL;
interface
uses
Windows, Messages, CommCtrl;
function Button_SetImageEx(hBtn : HWND; Image : HGDIOBJ; ImageType, Width, Height : Integer) : Integer;
implementation
function Button_SetImageEx(hBtn : HWND; Image : HGDIOBJ; ImageType, Width, Height : Integer) : Integer;
const
BCM_FIRST = $1600;
BCM_SETIMAGELIST = $0002;
BUTTON_IMAGELIST_ALIGN_LEFT = 0;
BUTTON_IMAGELIST_ALIGN_RIGHT = 1;
BUTTON_IMAGELIST_ALIGN_TOP = 2;
BUTTON_IMAGELIST_ALIGN_BOTTOM = 3;
BUTTON_IMAGELIST_ALIGN_CENTER = 4;
type
TButtonImageList = record
ImgLst : HIMAGELIST; // Нормальное, Наведенное, Нажатое, Отключенное, Сфокусированное
margin : TRect; // Отступы
uAlign : DWORD; // Выравнивание
end;
var
hIconBlend:HICON;
bi : TButtonImageList;
begin
Result := 0;
if not (ImageType in [IMAGE_BITMAP, IMAGE_ICON]) then Exit;
ZeroMemory(@bi, SizeOf(bi));
bi.ImgLst := ImageList_Create(Width, Height, ILC_COLOR32 or ILC_MASK, 4, 0);
bi.margin.Left := 1;
bi.uAlign := BUTTON_IMAGELIST_ALIGN_LEFT;
if (ImageType = IMAGE_BITMAP) then
begin
ImageList_Add(bi.ImgLst, Image, 0); // Normal
ImageList_Add(bi.ImgLst, Image, 0); // hot
ImageList_Add(bi.ImgLst, Image, 0); // pushed
end
else
begin
ImageList_AddIcon(bi.ImgLst, Image); // Normal
ImageList_AddIcon(bi.ImgLst, Image); // hot
ImageList_AddIcon(bi.ImgLst, Image); // pushed
end;
// Отключенное
hIconBlend := ImageList_GetIcon(bi.ImgLst, 0, ILD_BLEND50 or ILD_TRANSPARENT);
ImageList_AddIcon(bi.ImgLst, hIconBlend);
DestroyIcon(hIconBlend);
// Сфокусированное
if (ImageType = IMAGE_BITMAP) then
ImageList_Add(bi.ImgLst, Image, 0)
else
ImageList_AddIcon(bi.ImgLst, Image);
Result := SendMessage(hBtn, BCM_FIRST + BCM_SETIMAGELIST, 0, lParam(@bi));
if (Result = 0) then
begin
ImageList_Destroy(bi.ImgLst);
Result := SendMessage(hBtn, BM_SETIMAGE, ImageType, Image)
end;
end;
end. |
namespace RemObjects.Elements.EUnit;
interface
uses
Sugar;
type
Assert = public partial static class {$IF NOUGAT}mapped to Object{$ENDIF}
private
method BoolToString(Value: Boolean): String;
public
method AreEqual(Actual, Expected : Boolean; Message: String := nil);
method AreNotEqual(Actual, Expected: Boolean; Message: String := nil);
method IsTrue(Actual: Boolean; Message: String := nil);
method IsFalse(Actual: Boolean; Message: String := nil);
end;
implementation
class method Assert.BoolToString(Value: Boolean): String;
begin
exit if Value then Consts.TrueString else Consts.FalseString;
end;
class method Assert.AreEqual(Actual: Boolean; Expected: Boolean; Message: String := nil);
begin
FailIfNot(Actual = Expected, BoolToString(Actual), BoolToString(Expected), coalesce(Message, AssertMessages.NotEqual));
end;
class method Assert.AreNotEqual(Actual: Boolean; Expected: Boolean; Message: String := nil);
begin
FailIf(Actual = Expected, BoolToString(Actual), BoolToString(Expected), coalesce(Message, AssertMessages.Equal));
end;
class method Assert.IsTrue(Actual: Boolean; Message: String := nil);
begin
FailIfNot(Actual, BoolToString(Actual), Consts.TrueString, coalesce(Message, AssertMessages.NotEqual));
end;
class method Assert.IsFalse(Actual: Boolean; Message: String := nil);
begin
FailIf(Actual, BoolToString(Actual), Consts.FalseString, coalesce(Message, AssertMessages.NotEqual));
end;
end. |
unit VoxelBank;
interface
uses Voxel, VoxelBankItem, SysUtils;
type
TVoxelBank = class
private
Items : array of TVoxelBankItem;
// Constructors and Destructors
procedure Clear;
// Adds
function Search(const _Filename: string): integer; overload;
function Search(const _Voxel: PVoxel): integer; overload;
function SearchReadOnly(const _Filename: string): integer; overload;
function SearchReadOnly(const _Voxel: PVoxel): integer; overload;
function SearchEditable(const _Voxel: PVoxel): integer;
public
// Constructors and Destructors
constructor Create;
destructor Destroy; override;
// I/O
function Load(var _Voxel: PVoxel; const _Filename: string): PVoxel;
function LoadNew: PVoxel;
function Save(var _Voxel: PVoxel; const _Filename: string): boolean;
// Adds
function Add(const _filename: string): PVoxel; overload;
function Add(const _Voxel: PVoxel): PVoxel; overload;
function AddReadOnly(const _filename: string): PVoxel; overload;
function AddReadOnly(const _Voxel: PVoxel): PVoxel; overload;
function Clone(const _filename: string): PVoxel; overload;
function Clone(const _Voxel: PVoxel): PVoxel; overload;
function CloneEditable(const _Voxel: PVoxel): PVoxel; overload;
// Deletes
procedure Delete(const _Voxel : PVoxel);
end;
implementation
// Constructors and Destructors
constructor TVoxelBank.Create;
begin
SetLength(Items,0);
end;
destructor TVoxelBank.Destroy;
begin
Clear;
inherited Destroy;
end;
// Only activated when the program is over.
procedure TVoxelBank.Clear;
var
i : integer;
begin
for i := Low(Items) to High(Items) do
begin
Items[i].Free;
end;
end;
// I/O
function TVoxelBank.Load(var _Voxel: PVoxel; const _Filename: string): PVoxel;
var
i : integer;
begin
i := SearchEditable(_Voxel);
if i <> -1 then
begin
Items[i].DecCounter;
if Items[i].GetCount = 0 then
begin
try
Items[i].Free;
Items[i] := TVoxelBankItem.Create(_Filename);
Result := Items[i].GetVoxel;
except
Result := nil;
exit;
end;
Items[i].SetEditable(true);
end
else
begin
SetLength(Items,High(Items)+2);
try
Items[High(Items)] := TVoxelBankItem.Create(_Filename);
except
Items[High(Items)].Free;
SetLength(Items,High(Items));
Result := nil;
exit;
end;
Items[High(Items)].SetEditable(true);
Result := Items[High(Items)].GetVoxel;
end;
end
else
begin
SetLength(Items,High(Items)+2);
try
Items[High(Items)] := TVoxelBankItem.Create(_Filename);
except
Items[High(Items)].Free;
SetLength(Items,High(Items));
Result := nil;
exit;
end;
Items[High(Items)].SetEditable(true);
Result := Items[High(Items)].GetVoxel;
end;
end;
function TVoxelBank.LoadNew: PVoxel;
begin
SetLength(Items,High(Items)+2);
Items[High(Items)] := TVoxelBankItem.Create;
Items[High(Items)].SetEditable(true);
Result := Items[High(Items)].GetVoxel;
end;
function TVoxelBank.Save(var _Voxel: PVoxel; const _Filename: string): boolean;
var
i : integer;
Voxel : PVoxel;
begin
i := Search(_Voxel);
if i <> -1 then
begin
Voxel := Items[i].GetVoxel;
Voxel^.SaveToFile(_Filename);
Items[i].SetFilename(_Filename);
Result := true;
end
else
begin
Result := false;
end;
end;
// Adds
function TVoxelBank.Search(const _filename: string): integer;
var
i : integer;
begin
Result := -1;
if Length(_Filename) = 0 then
exit;
i := Low(Items);
while i <= High(Items) do
begin
if CompareStr(_Filename,Items[i].GetFilename) = 0 then
begin
Result := i;
exit;
end;
inc(i);
end;
end;
function TVoxelBank.Search(const _Voxel: PVoxel): integer;
var
i : integer;
begin
Result := -1;
if _Voxel = nil then
exit;
i := Low(Items);
while i <= High(Items) do
begin
if _Voxel = Items[i].GetVoxel then
begin
Result := i;
exit;
end;
inc(i);
end;
end;
function TVoxelBank.SearchReadOnly(const _filename: string): integer;
var
i : integer;
begin
Result := -1;
if Length(_Filename) = 0 then
exit;
i := Low(Items);
while i <= High(Items) do
begin
if not Items[i].GetEditable then
begin
if CompareStr(_Filename,Items[i].GetFilename) = 0 then
begin
Result := i;
exit;
end;
end;
inc(i);
end;
end;
function TVoxelBank.SearchReadOnly(const _Voxel: PVoxel): integer;
var
i : integer;
begin
Result := -1;
if _Voxel = nil then
exit;
i := Low(Items);
while i <= High(Items) do
begin
if not Items[i].GetEditable then
begin
if _Voxel = Items[i].GetVoxel then
begin
Result := i;
exit;
end;
end;
inc(i);
end;
end;
function TVoxelBank.SearchEditable(const _Voxel: PVoxel): integer;
var
i : integer;
begin
Result := -1;
if _Voxel = nil then
exit;
i := Low(Items);
while i <= High(Items) do
begin
if Items[i].GetEditable then
begin
if _Voxel = Items[i].GetVoxel then
begin
Result := i;
exit;
end;
end;
inc(i);
end;
end;
function TVoxelBank.Add(const _filename: string): PVoxel;
var
i : integer;
begin
i := Search(_Filename);
if i <> -1 then
begin
Items[i].IncCounter;
Result := Items[i].GetVoxel;
end
else
begin
SetLength(Items,High(Items)+2);
try
Items[High(Items)] := TVoxelBankItem.Create(_Filename);
except
Items[High(Items)].Free;
SetLength(Items,High(Items));
Result := nil;
exit;
end;
Result := Items[High(Items)].GetVoxel;
end;
end;
function TVoxelBank.Add(const _Voxel: PVoxel): PVoxel;
var
i : integer;
begin
i := Search(_Voxel);
if i <> -1 then
begin
Items[i].IncCounter;
Result := Items[i].GetVoxel;
end
else
begin
SetLength(Items,High(Items)+2);
try
Items[High(Items)] := TVoxelBankItem.Create(_Voxel);
except
Items[High(Items)].Free;
SetLength(Items,High(Items));
Result := nil;
exit;
end;
Result := Items[High(Items)].GetVoxel;
end;
end;
function TVoxelBank.AddReadOnly(const _filename: string): PVoxel;
var
i : integer;
begin
i := SearchReadOnly(_Filename);
if i <> -1 then
begin
Items[i].IncCounter;
Result := Items[i].GetVoxel;
end
else
begin
SetLength(Items,High(Items)+2);
try
Items[High(Items)] := TVoxelBankItem.Create(_Filename);
except
Items[High(Items)].Free;
SetLength(Items,High(Items));
Result := nil;
exit;
end;
Result := Items[High(Items)].GetVoxel;
end;
end;
function TVoxelBank.AddReadOnly(const _Voxel: PVoxel): PVoxel;
var
i : integer;
begin
i := SearchReadOnly(_Voxel);
if i <> -1 then
begin
Items[i].IncCounter;
Result := Items[i].GetVoxel;
end
else
begin
SetLength(Items,High(Items)+2);
try
Items[High(Items)] := TVoxelBankItem.Create(_Voxel);
except
Items[High(Items)].Free;
SetLength(Items,High(Items));
Result := nil;
exit;
end;
Result := Items[High(Items)].GetVoxel;
end;
end;
function TVoxelBank.Clone(const _filename: string): PVoxel;
begin
SetLength(Items,High(Items)+2);
try
Items[High(Items)] := TVoxelBankItem.Create(_Filename);
except
Items[High(Items)].Free;
SetLength(Items,High(Items));
Result := nil;
exit;
end;
Result := Items[High(Items)].GetVoxel;
end;
function TVoxelBank.Clone(const _Voxel: PVoxel): PVoxel;
begin
SetLength(Items,High(Items)+2);
try
Items[High(Items)] := TVoxelBankItem.Create(_Voxel);
except
Items[High(Items)].Free;
SetLength(Items,High(Items));
Result := nil;
exit;
end;
Result := Items[High(Items)].GetVoxel;
end;
function TVoxelBank.CloneEditable(const _Voxel: PVoxel): PVoxel;
begin
SetLength(Items,High(Items)+2);
try
Items[High(Items)] := TVoxelBankItem.Create(_Voxel);
except
Items[High(Items)].Free;
SetLength(Items,High(Items));
Result := nil;
exit;
end;
Items[High(Items)].SetEditable(true);
Result := Items[High(Items)].GetVoxel;
end;
// Deletes
procedure TVoxelBank.Delete(const _Voxel : PVoxel);
var
i : integer;
begin
i := Search(_Voxel);
if i <> -1 then
begin
Items[i].DecCounter;
if Items[i].GetCount = 0 then
begin
Items[i].Free;
while i < High(Items) do
begin
Items[i] := Items[i+1];
inc(i);
end;
SetLength(Items,High(Items));
end;
end;
end;
end.
|
unit uExplorerPersonsProvider;
interface
uses
System.SysUtils,
System.StrUtils,
Winapi.Windows,
Vcl.Graphics,
Dmitry.Utils.System,
Dmitry.Utils.ShellIcons,
Dmitry.PathProviders,
Dmitry.PathProviders.MyComputer,
UnitDBDeclare,
uPeopleRepository,
uBitmapUtils,
uTime,
uMemory,
uConstants,
uTranslate,
uExplorerPathProvider,
uStringUtils,
uJpegUtils,
uShellIntegration,
uDBForm,
uDBClasses,
uDBEntities,
uDBContext,
uDBManager,
uCollectionEvents;
type
TPersonsItem = class(TPathItem)
protected
function InternalGetParent: TPathItem; override;
function InternalCreateNewInstance: TPathItem; override;
function GetIsDirectory: Boolean; override;
public
function LoadImage(Options, ImageSize: Integer): Boolean; override;
constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override;
end;
TPersonItem = class(TPathItem)
private
FPersonName: string;
FPersonID: Integer;
FComment: string;
protected
function InternalGetParent: TPathItem; override;
function InternalCreateNewInstance: TPathItem; override;
function GetIsDirectory: Boolean; override;
public
constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override;
procedure Assign(Item: TPathItem); override;
function LoadImage(Options, ImageSize: Integer): Boolean; override;
procedure ReadFromPerson(Person: TPerson; Options, ImageSize: Integer);
property PersonName: string read FPersonName;
property Comment: string read FComment;
property PersonID: Integer read FPersonID;
end;
type
TPersonProvider = class(TExplorerPathProvider)
protected
function InternalFillChildList(Sender: TObject; Item: TPathItem; List: TPathItemCollection; Options, ImageSize: Integer; PacketSize: Integer; CallBack: TLoadListCallBack): Boolean; override;
function GetTranslateID: string; override;
function ShowProperties(Sender: TObject; Items: TPathItemCollection): Boolean;
function Rename(Sender: TObject; Items: TPathItemCollection; Options: TPathFeatureEditOptions): Boolean;
function Delete(Sender: TObject; Items: TPathItemCollection): Boolean;
public
function ExtractPreview(Item: TPathItem; MaxWidth, MaxHeight: Integer; var Bitmap: TBitmap; var Data: TObject): Boolean; override;
function Supports(Item: TPathItem): Boolean; override;
function Supports(Path: string): Boolean; override;
function SupportsFeature(Feature: string): Boolean; override;
function ExecuteFeature(Sender: TObject; Items: TPathItemCollection; Feature: string; Options: TPathFeatureOptions): Boolean; override;
function CreateFromPath(Path: string): TPathItem; override;
end;
implementation
uses
uFormCreatePerson;
function ExtractPersonName(Path: string): string;
var
P: Integer;
begin
Result := '';
P := Pos('\', Path);
if P > 0 then
Result := Right(Path, P + 1);;
end;
{ TPersonProvider }
function TPersonProvider.CreateFromPath(Path: string): TPathItem;
begin
Result := nil;
if Path = cPersonsPath then
Result := TPersonsItem.CreateFromPath(Path, PATH_LOAD_NO_IMAGE, 0);
if StartsText(cPersonsPath + '\', Path) then
Result := TPersonItem.CreateFromPath(Path, PATH_LOAD_NO_IMAGE, 0);
end;
function TPersonProvider.Delete(Sender: TObject; Items: TPathItemCollection): Boolean;
var
P: TPerson;
SC: TSelectCommand;
Count: Integer;
EventValues: TEventValues;
Form: TDBForm;
Item: TPersonItem;
Context: IDBContext;
PeopleRepository: IPeopleRepository;
begin
Result := False;
Form := TDBForm(Sender);
if Items.Count = 0 then
Exit;
if Items.Count > 1 then
begin
MessageBoxDB(Form.Handle, L('Please delete only one person at time!'), L('Warning'), TD_BUTTON_OK, TD_ICON_WARNING);
Exit;
end;
Item := TPersonItem(Items[0]);
Context := DBManager.DBContext;
PeopleRepository := Context.People;
P := PeopleRepository.GetPersonByName(Item.PersonName);
try
if not P.Empty then
begin
SC := Context.CreateSelect(ObjectMappingTableName);
try
SC.AddParameter(TCustomFieldParameter.Create('Count(1) as RecordCount'));
SC.AddWhereParameter(TIntegerParameter.Create('ObjectID', P.ID));
if SC.Execute > 0 then
begin
Count := SC.DS.FieldByName('RecordCount').AsInteger;
if ID_OK = MessageBoxDB(Form.Handle, FormatEx(L('Do you really want to delete person "{0}" (Has {1} reference(s) on photo(s))?'), [P.Name, Count]), L('Warning'), TD_BUTTON_OKCANCEL, TD_ICON_WARNING) then
begin
Result := PeopleRepository.DeletePerson(Item.PersonName);
if Result then
begin
EventValues.ID := P.ID;
CollectionEvents.DoIDEvent(Form, Item.PersonID, [EventID_PersonRemoved], EventValues);
end;
end;
end;
finally
F(SC);
end;
end;
finally
F(P);
end;
end;
function TPersonProvider.ExecuteFeature(Sender: TObject; Items: TPathItemCollection;
Feature: string; Options: TPathFeatureOptions): Boolean;
begin
Result := inherited ExecuteFeature(Sender, Items, Feature, Options);
if Feature = PATH_FEATURE_DELETE then
Result := Delete(Sender, Items);
if Feature = PATH_FEATURE_PROPERTIES then
Result := ShowProperties(Sender, Items);
if Feature = PATH_FEATURE_RENAME then
Result := Rename(Sender, Items, Options as TPathFeatureEditOptions);
end;
function TPersonProvider.ExtractPreview(Item: TPathItem; MaxWidth,
MaxHeight: Integer; var Bitmap: TBitmap; var Data: TObject): Boolean;
var
Person: TPerson;
Context: IDBContext;
PeopleRepository: IPeopleRepository;
begin
Result := False;
Context := DBManager.DBContext;
PeopleRepository := Context.People;
Person := TPerson.Create;
try
PeopleRepository.FindPerson(ExtractPersonName(Item.Path), Person);
if Person.Image = nil then
Exit;
Bitmap.Assign(Person.Image);
KeepProportions(Bitmap, MaxWidth, MaxHeight);
Result := True;
finally
F(Person);
end;
end;
function TPersonProvider.GetTranslateID: string;
begin
Result := 'PersonsProvider';
end;
function TPersonProvider.InternalFillChildList(Sender: TObject; Item: TPathItem;
List: TPathItemCollection; Options, ImageSize, PacketSize: Integer;
CallBack: TLoadListCallBack): Boolean;
var
I: Integer;
PI: TPersonsItem;
P: TPersonItem;
Cancel: Boolean;
Persons: TPersonCollection;
Context: IDBContext;
PeopleRepository: IPeopleRepository;
begin
inherited;
Result := True;
Cancel := False;
if Options and PATH_LOAD_ONLY_FILE_SYSTEM > 0 then
Exit;
if Item is THomeItem then
begin
PI := TPersonsItem.CreateFromPath(cPersonsPath, Options, ImageSize);
List.Add(PI);
end;
if Item is TPersonsItem then
begin
Context := DBManager.DBContext;
PeopleRepository := Context.People;
Persons := TPersonCollection.Create;
try
PeopleRepository.LoadPersonList(Persons);
for I := 0 to Persons.Count - 1 do
begin
TW.I.Start('Person - create');
P := TPersonItem.CreateFromPath(cPersonsPath + '\' + Persons[I].Name, PATH_LOAD_NO_IMAGE, 0);
TW.I.Start('Person - load');
P.ReadFromPerson(Persons[I], Options, ImageSize);
TW.I.Start('Person - load - end');
List.Add(P);
if List.Count mod PacketSize = 0 then
begin
if Assigned(CallBack) then
CallBack(Sender, Item, List, Cancel);
end;
if Cancel then
Break;
end;
finally
F(Persons);
end;
end;
if Assigned(CallBack) then
CallBack(Sender, Item, List, Cancel);
end;
function TPersonProvider.Rename(Sender: TObject; Items: TPathItemCollection;
Options: TPathFeatureEditOptions): Boolean;
var
EventValues: TEventValues;
Item: TPersonItem;
Context: IDBContext;
PeopleRepository: IPeopleRepository;
begin
Result := False;
if Items.Count = 0 then
Exit;
Item := TPersonItem(Items[0]);
Context := DBManager.DBContext;
PeopleRepository := Context.People;
Result := PeopleRepository.RenamePerson(Item.PersonName, Options.NewName);
if Result then
begin
EventValues.ID := Item.PersonID;
EventValues.FileName := Options.NewName;
EventValues.NewName := Options.NewName;
CollectionEvents.DoIDEvent(TDBForm(Sender), Item.PersonID, [EventID_PersonChanged], EventValues);
end;
end;
function TPersonProvider.Supports(Item: TPathItem): Boolean;
begin
Result := Item is TPersonsItem;
Result := Item is TPersonItem or Result;
Result := Result or Supports(Item.Path);
end;
function TPersonProvider.ShowProperties(Sender: TObject;
Items: TPathItemCollection): Boolean;
var
P: TPerson;
Context: IDBContext;
PeopleRepository: IPeopleRepository;
begin
Result := False;
if Items.Count = 0 then
Exit;
Context := DBManager.DBContext;
PeopleRepository := Context.People;
P := PeopleRepository.GetPersonByName(TPersonItem(Items[0]).PersonName);
try
Result := P.ID > 0;
if Result then
EditPerson(P.ID);
finally
F(P);
end;
end;
function TPersonProvider.Supports(Path: string): Boolean;
begin
Result := StartsText(cPersonsPath, Path);
if Result then
begin
System.Delete(Path, 1, Length(cPersonsPath) + 1);
//subitem
if Pos('\', Path) > 0 then
Result := False;
end;
end;
function TPersonProvider.SupportsFeature(Feature: string): Boolean;
begin
Result := Feature = PATH_FEATURE_PROPERTIES;
Result := Result or (Feature = PATH_FEATURE_DELETE);
Result := Result or (Feature = PATH_FEATURE_RENAME);
end;
{ TPersonsItem }
constructor TPersonsItem.CreateFromPath(APath: string; Options,
ImageSize: Integer);
begin
inherited;
FPath := cPersonsPath;
FDisplayName := TA('Persons', 'Path');
if Options and PATH_LOAD_NO_IMAGE = 0 then
LoadImage(Options, ImageSize);
end;
function TPersonsItem.GetIsDirectory: Boolean;
begin
Result := True;
end;
function TPersonsItem.InternalCreateNewInstance: TPathItem;
begin
Result := TPersonsItem.Create;
end;
function TPersonsItem.InternalGetParent: TPathItem;
begin
Result := THomeItem.Create;
end;
function TPersonsItem.LoadImage(Options, ImageSize: Integer): Boolean;
var
Icon: TIcon;
begin
F(FImage);
FindIcon(HInstance, 'PERSONS', ImageSize, 32, Icon);
FImage := TPathImage.Create(Icon);
Result := True;
end;
{ TPersonItem }
procedure TPersonItem.Assign(Item: TPathItem);
begin
inherited;
FPersonName := TPersonItem(Item).FPersonName;
FComment := TPersonItem(Item).FComment;
FPersonID := TPersonItem(Item).FPersonID;
end;
constructor TPersonItem.CreateFromPath(APath: string; Options,
ImageSize: Integer);
begin
inherited;
FPersonName := APath;
Delete(FPersonName, 1, Length(cPersonsPath) + 1);
FDisplayName := FPersonName;
if Options and PATH_LOAD_NO_IMAGE = 0 then
LoadImage(Options, ImageSize);
end;
function TPersonItem.GetIsDirectory: Boolean;
begin
Result := True;
end;
function TPersonItem.InternalCreateNewInstance: TPathItem;
begin
Result := TPersonItem.Create;
end;
function TPersonItem.InternalGetParent: TPathItem;
begin
Result := TPersonsItem.CreateFromPath(cPersonsPath, PATH_LOAD_NORMAL, 0);
end;
function TPersonItem.LoadImage(Options, ImageSize: Integer): Boolean;
var
Person: TPerson;
Context: IDBContext;
PeopleRepository: IPeopleRepository;
begin
Result := False;
F(FImage);
Context := DBManager.DBContext;
PeopleRepository := Context.People;
Person := PeopleRepository.GetPersonByName(FPersonName);
try
if not Person.Empty then
begin
ReadFromPerson(Person, Options, ImageSize);
Result := True;
end;
finally
F(Person);
end;
end;
procedure TPersonItem.ReadFromPerson(Person: TPerson; Options, ImageSize: Integer);
var
Bitmap: TBitmap;
begin
F(FImage);
FPersonName := Person.Name;
FDisplayName := Person.Name;
FComment := Person.Comment;
FPersonID := Person.ID;
if (Person.Image <> nil) and (ImageSize > 0) then
begin
Bitmap := TBitmap.Create;
try
JPEGScale(Person.Image, ImageSize, ImageSize);
AssignJpeg(Bitmap, Person.Image);
KeepProportions(Bitmap, ImageSize, ImageSize);
if Options and PATH_LOAD_FOR_IMAGE_LIST <> 0 then
CenterBitmap24To32ImageList(Bitmap, ImageSize);
FImage := TPathImage.Create(Bitmap);
Bitmap := nil;
finally
F(Bitmap);
end;
end;
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2019 Kike Pérez
Unit : Quick.Logger.UnhandledExceptionHook
Description : Log Unhandled Exceptions
Author : Kike Pérez
Version : 1.20
Created : 28/03/2019
Modified : 28/03/2019
This file is part of QuickLogger: https://github.com/exilon/QuickLogger
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Logger.UnhandledExceptionHook;
{$i QuickLib.inc}
interface
implementation
uses
SysUtils,
TypInfo,
Quick.Logger;
procedure UnhandledException(ExceptObject : TObject; ExceptAddr : Pointer);
begin
if Assigned(GlobalLoggerUnhandledException) then GlobalLoggerUnhandledException(ExceptObject,ExceptAddr);
end;
initialization
ExceptProc := @UnhandledException; //unhandled exceptions
end.
|
(* Generates a grid based dungeon with wider spaces between rooms, this is then processed to apply bitmasked walls *)
unit bitmask_dungeon;
{$mode objfpc}{$H+}
interface
uses
SysUtils, process_dungeon, globalutils, map;
type
coordinates = record
x, y: smallint;
end;
var
r, c, i, p, t, listLength, firstHalf, lastHalf: smallint;
dungeonArray: array[1..globalutils.MAXROWS, 1..globalutils.MAXCOLUMNS] of char;
totalRooms, roomSquare: smallint;
(* start creating corridors once this rises above 1 *)
roomCounter: smallint;
(* list of coordinates of centre of each room *)
centreList: array of coordinates;
(* Player starting position *)
startX, startY: smallint;
(* TESTING - Write dungeon to text file *)
filename: ShortString;
myfile: Text;
(* Carve a horizontal tunnel *)
procedure carveHorizontally(x1, x2, y: smallint);
(* Carve a vertical tunnel *)
procedure carveVertically(y1, y2, x: smallint);
(* Carve corridor between rooms *)
procedure createCorridor(fromX, fromY, toX, toY: smallint);
(* Create a room *)
procedure createRoom(gridNumber: smallint);
(* Generate a dungeon *)
procedure generate;
(* sort room list in order from left to right *)
procedure leftToRight;
implementation
procedure leftToRight;
var
i, j, n, tempX, tempY: smallint;
begin
n := length(centreList) - 1;
for i := n downto 2 do
for j := 0 to i - 1 do
if centreList[j].x > centreList[j + 1].x then
begin
tempX := centreList[j].x;
tempY := centreList[j].y;
centreList[j].x := centreList[j + 1].x;
centreList[j].y := centreList[j + 1].y;
centreList[j + 1].x := tempX;
centreList[j + 1].y := tempY;
end;
end;
procedure carveHorizontally(x1, x2, y: smallint);
var
x: byte;
begin
if x1 < x2 then
begin
for x := x1 to x2 do
dungeonArray[y][x] := '.';
end;
if x1 > x2 then
begin
for x := x2 to x1 do
dungeonArray[y][x] := '.';
end;
end;
procedure carveVertically(y1, y2, x: smallint);
var
y: byte;
begin
if y1 < y2 then
begin
for y := y1 to y2 do
dungeonArray[y][x] := '.';
end;
if y1 > y2 then
begin
for y := y2 to y1 do
dungeonArray[y][x] := '.';
end;
end;
procedure createCorridor(fromX, fromY, toX, toY: smallint);
var
direction: byte;
begin
// flip a coin to decide whether to first go horizontally or vertically
direction := Random(2);
// horizontally first
if direction = 1 then
begin
carveHorizontally(fromX, toX, fromY);
carveVertically(fromY, toY, toX);
end
// vertically first
else
begin
carveVertically(fromY, toY, toX);
carveHorizontally(fromX, toX, fromY);
end;
end;
procedure createRoom(gridNumber: smallint);
var
topLeftX, topLeftY, roomHeight, roomWidth, drawHeight, drawWidth,
nudgeDown, nudgeAcross: smallint;
begin
// row 1
if (gridNumber >= 1) and (gridNumber <= 9) then
begin
topLeftX := (gridNumber * 7) - 4;
topLeftY := 3;
end;
// row 2
if (gridNumber >= 10) and (gridNumber <= 18) then
begin
topLeftX := (gridNumber * 7) - 67;
topLeftY := 10;
end;
// row 3
if (gridNumber >= 19) and (gridNumber <= 27) then
begin
topLeftX := (gridNumber * 7) - 130;
topLeftY := 17;
end;
// row 4
if (gridNumber >= 28) and (gridNumber <= 36) then
begin
topLeftX := (gridNumber * 7) - 193;
topLeftY := 24;
end;
// row 5
if (gridNumber >= 37) and (gridNumber <= 45) then
begin
topLeftX := (gridNumber * 7) - 256;
topLeftY := 31;
end;
(* Randomly select room dimensions between 2 - 5 tiles in height / width *)
roomHeight := Random(2) + 3;
roomWidth := Random(2) + 3;
(* Change starting point of each room so they don't all start
drawing from the top left corner *)
case roomHeight of
2: nudgeDown := Random(0) + 2;
3: nudgeDown := Random(0) + 1;
else
nudgeDown := 0;
end;
case roomWidth of
2: nudgeAcross := Random(0) + 2;
3: nudgeAcross := Random(0) + 1;
else
nudgeAcross := 0;
end;
(* Save coordinates of the centre of the room *)
listLength := Length(centreList);
SetLength(centreList, listLength + 1);
centreList[listLength].x := (topLeftX + nudgeAcross) + (roomWidth div 2);
centreList[listLength].y := (topLeftY + nudgeDown) + (roomHeight div 2);
(* Draw room within the grid square *)
for drawHeight := 0 to roomHeight do
begin
for drawWidth := 0 to roomWidth do
begin
dungeonArray[(topLeftY + nudgeDown) + drawHeight][(topLeftX + nudgeAcross) +
drawWidth] := '.';
end;
end;
end;
procedure generate;
begin
roomCounter := 0;
// initialise the array
SetLength(centreList, 1);
// fill map with walls
for r := 1 to globalutils.MAXROWS do
begin
for c := 1 to globalutils.MAXCOLUMNS do
begin
dungeonArray[r][c] := '#';
end;
end;
// Random(Range End - Range Start) + Range Start;
totalRooms := Random(10) + 20; // between 20 - 30 rooms
for i := 1 to totalRooms do
begin
// randomly choose grid location from 1 to 45
roomSquare := Random(44) + 1;
createRoom(roomSquare);
Inc(roomCounter);
end;
leftToRight();
for i := 1 to (totalRooms - 1) do
begin
createCorridor(centreList[i].x, centreList[i].y, centreList[i + 1].x,
centreList[i + 1].y);
end;
// connect random rooms so the map isn't totally linear
// from the first half of the room list
firstHalf := (totalRooms div 2);
p := random(firstHalf - 1) + 1;
t := random(firstHalf - 1) + 1;
createCorridor(centreList[p].x, centreList[p].y, centreList[t].x,
centreList[t].y);
// from the second half of the room list
lastHalf := (totalRooms - firstHalf);
p := random(lastHalf) + firstHalf;
t := random(lastHalf) + firstHalf;
createCorridor(centreList[p].x, centreList[p].y, centreList[t].x,
centreList[t].y);
// set player start coordinates
map.startX := centreList[1].x;
map.startY := centreList[1].y;
/////////////////////////////
// Write map to text file for testing
//filename := 'output_bitmask_dungeon.txt';
//AssignFile(myfile, filename);
//rewrite(myfile);
//for r := 1 to MAXROWS do
//begin
// for c := 1 to MAXCOLUMNS do
// begin
// Write(myfile, dungeonArray[r][c]);
// end;
// Write(myfile, sLineBreak);
//end;
//closeFile(myfile);
//////////////////////////////
// process_dungeon.prettify;
/////////////////////////////
// Write map to text file for testing
//filename := 'output_processed_dungeon.txt';
//AssignFile(myfile, filename);
//rewrite(myfile);
//for r := 1 to MAXROWS do
//begin
// for c := 1 to MAXCOLUMNS do
// begin
// Write(myfile, globalutils.dungeonArray[r][c]);
// end;
// Write(myfile, sLineBreak);
//end;
//closeFile(myfile);
//////////////////////////////
(* Copy total rooms to main dungeon *)
globalutils.currentDgnTotalRooms := totalRooms;
(* Set flag for type of dungeon *)
map.mapType := 3;
end;
end.
|
unit Invoice.View.OrderProduct;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs;
type
TFormOrderProduct = class(TForm)
procedure FormShow(Sender: TObject);
private
{ Private declarations }
idCustomer: Integer;
nameCustomer: String;
public
{ Public declarations }
procedure SetidCustomer(aCustumer: Integer);
procedure SetnameCustomer(aCustumer: String);
end;
var
FormOrderProduct: TFormOrderProduct;
implementation
{$R *.dfm}
{ TFormOrderProduct }
procedure TFormOrderProduct.FormShow(Sender: TObject);
begin
Caption := Caption + ' - [ ' + nameCustomer + ' ]';
end;
procedure TFormOrderProduct.SetidCustomer(aCustumer: Integer);
begin
idCustomer := aCustumer;
end;
procedure TFormOrderProduct.SetnameCustomer(aCustumer: String);
begin
nameCustomer := aCustumer;
end;
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFBaseRefCounted;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
uCEFInterfaces;
type
TCefBaseRefCountedOwn = class(TInterfacedObject, ICefBaseRefCounted)
protected
FData: Pointer;
public
constructor CreateData(size: Cardinal; owned : boolean = False); virtual;
destructor Destroy; override;
function Wrap: Pointer;
end;
TCefBaseRefCountedRef = class(TInterfacedObject, ICefBaseRefCounted)
protected
FData: Pointer;
public
constructor Create(data: Pointer); virtual;
destructor Destroy; override;
function Wrap: Pointer;
class function UnWrap(data: Pointer): ICefBaseRefCounted;
end;
implementation
uses
uCEFTypes, uCEFMiscFunctions;
procedure cef_base_add_ref(self: PCefBaseRefCounted); stdcall;
var
TempObject : TObject;
begin
TempObject := CefGetObject(self);
if (TempObject <> nil) and (TempObject is TCefBaseRefCountedOwn) then
TCefBaseRefCountedOwn(TempObject)._AddRef;
end;
function cef_base_release_ref(self: PCefBaseRefCounted): Integer; stdcall;
var
TempObject : TObject;
begin
TempObject := CefGetObject(self);
if (TempObject <> nil) and (TempObject is TCefBaseRefCountedOwn) then
Result := TCefBaseRefCountedOwn(TempObject)._Release
else
Result := 0;
end;
function cef_base_has_one_ref(self: PCefBaseRefCounted): Integer; stdcall;
var
TempObject : TObject;
begin
TempObject := CefGetObject(self);
if (TempObject <> nil) and (TempObject is TCefBaseRefCountedOwn) then
Result := Ord(TCefBaseRefCountedOwn(TempObject).FRefCount = 1)
else
Result := Ord(False);
end;
procedure cef_base_add_ref_owned(self: PCefBaseRefCounted); stdcall;
begin
//
end;
function cef_base_release_owned(self: PCefBaseRefCounted): Integer; stdcall;
begin
Result := 1;
end;
function cef_base_has_one_ref_owned(self: PCefBaseRefCounted): Integer; stdcall;
begin
Result := 1;
end;
constructor TCefBaseRefCountedOwn.CreateData(size: Cardinal; owned : boolean);
begin
GetMem(FData, size + SizeOf(Pointer));
PPointer(FData)^ := Self;
Inc(PByte(FData), SizeOf(Pointer));
FillChar(FData^, size, 0);
PCefBaseRefCounted(FData)^.size := size;
if owned then
begin
PCefBaseRefCounted(FData)^.add_ref := cef_base_add_ref_owned;
PCefBaseRefCounted(FData)^.release := cef_base_release_owned;
PCefBaseRefCounted(FData)^.has_one_ref := cef_base_has_one_ref_owned;
end
else
begin
PCefBaseRefCounted(FData)^.add_ref := cef_base_add_ref;
PCefBaseRefCounted(FData)^.release := cef_base_release_ref;
PCefBaseRefCounted(FData)^.has_one_ref := cef_base_has_one_ref;
end;
end;
destructor TCefBaseRefCountedOwn.Destroy;
var
TempPointer : pointer;
begin
TempPointer := FData;
FData := nil;
Dec(PByte(TempPointer), SizeOf(Pointer));
FreeMem(TempPointer);
inherited Destroy;
end;
function TCefBaseRefCountedOwn.Wrap: Pointer;
begin
Result := FData;
if (FData <> nil) and Assigned(PCefBaseRefCounted(FData)^.add_ref) then
PCefBaseRefCounted(FData)^.add_ref(PCefBaseRefCounted(FData));
end;
// TCefBaseRefCountedRef
constructor TCefBaseRefCountedRef.Create(data: Pointer);
begin
Assert(data <> nil);
FData := data;
end;
destructor TCefBaseRefCountedRef.Destroy;
begin
if (FData <> nil) then
begin
if assigned(PCefBaseRefCounted(FData)^.release) then
PCefBaseRefCounted(FData)^.release(PCefBaseRefCounted(FData));
FData := nil;
end;
inherited Destroy;
end;
class function TCefBaseRefCountedRef.UnWrap(data: Pointer): ICefBaseRefCounted;
begin
if (data <> nil) then
Result := Create(data) as ICefBaseRefCounted
else
Result := nil;
end;
function TCefBaseRefCountedRef.Wrap: Pointer;
begin
Result := FData;
if (FData <> nil) and Assigned(PCefBaseRefCounted(FData)^.add_ref) then
PCefBaseRefCounted(FData)^.add_ref(PCefBaseRefCounted(FData));
end;
end.
|
unit Main;
interface
uses
Winapi.OpenGL,
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
System.Contnrs,
System.Math,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ExtCtrls,
Vcl.ComCtrls,
Vcl.Buttons,
Vcl.StdCtrls,
//GLS
GLWin32Viewer,
GLScene,
GLVectorFileObjects,
GLState,
GLTexture,
GLObjects,
GLVectorGeometry,
GLVectorTypes,
GLMaterial,
GLCoordinates,
GLCrossPlatform,
GLBaseClasses,
GLPersistentClasses,
GLVectorLists,
MeshData,
GLMeshUtils,
GLFile3DS,
GLColor,
GLCadencer;
type
TModifierCube = class(TGLCube)
public
FVectorIndex : Integer;
FMeshObjIndex : Integer;
constructor Create(AOwner: TComponent); override;
end;
TfrmMain = class(TForm)
Panel2: TPanel;
Panel3: TPanel;
GLSceneViewer: TGLSceneViewer;
GLScene: TGLScene;
GLCamera: TGLCamera;
GLFreeForm: TGLFreeForm;
Label1: TLabel;
cbPolygonMode: TComboBox;
dcModifiers: TGLDummyCube;
chbViewPoints: TCheckBox;
StatusBar: TStatusBar;
GroupBox1: TGroupBox;
chbShowAxis: TCheckBox;
Bevel1: TBevel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
tbPos: TTrackBar;
GroupBox2: TGroupBox;
rbXY: TRadioButton;
rbZY: TRadioButton;
GLLightSource1: TGLLightSource;
GroupBox3: TGroupBox;
btnVertex: TBitBtn;
btnNormals: TBitBtn;
btnTextcoords: TBitBtn;
btnGroups: TBitBtn;
GLMaterialLibrary1: TGLMaterialLibrary;
GLCadencer1: TGLCadencer;
procedure FormCreate(Sender: TObject);
procedure GLSceneViewerMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure GLSceneViewerMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure cbPolygonModeChange(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure chbViewPointsClick(Sender: TObject);
procedure GLSceneViewerMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure chbShowAxisClick(Sender: TObject);
procedure tbPosChange(Sender: TObject);
procedure GLSceneViewerBeforeRender(Sender: TObject);
procedure btnVertexClick(Sender: TObject);
procedure btnNormalsClick(Sender: TObject);
procedure btnTextcoordsClick(Sender: TObject);
procedure btnGroupsClick(Sender: TObject);
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
private
//Private declarations
private
FOldX, FOldY : Integer;
FModifierList : TObjectList;
FSelectedModifier : TModifierCube;
FMoveZ : Boolean;
FOldMouseWorldPos : TVector;
{Create cubes used to modify vertex points}
procedure SetVertexModifiers;
{Populate statusbar with object information}
procedure ShowModifierStatus(const aObj : TModifierCube);
{Change the mesh vector property for the selected modifier.}
procedure ChangeMeshVector(const aObj : TModifierCube; const aPos : TVector4f);
{Identify mouse position in X, Y and Z axis}
function MouseWorldPos(x, y : Integer) : TVector;
{Strip redundent data, recalculate normals and faces}
procedure StripAndRecalc;
{Set Freeform's polygon mode: line, fill or points}
public
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
const
{Default combobox index for startup}
CLinePolyMode = 1;
{Scale dimention}
CModifierDim = 0.04;
var
{Modifier colors}
CModColorNormal : TColorVector;
CModColorSelect : TColorVector;
constructor TModifierCube.Create(AOwner: TComponent);
begin
inherited;
{Set the modifiers initial size and color}
CubeWidth := CModifierDim;
CubeHeight := CModifierDim;
CubeDepth := CModifierDim;
Material.FrontProperties.Diffuse.Color := CModColorNormal;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
var
lsDir : String;
lsFileName : String;
begin
{Do initial setup}
FModifierList := TObjectList.Create;
CModColorNormal := clrCoral;
CModColorSelect := clrSkyBlue;
lsDir := ExtractFileDir(Application.ExeName);
lsFileName := Format('%s\media\cube.3ds', [lsDir]);
if FileExists(lsFileName) then
begin
GLFreeForm.LoadFromFile(lsFileName);
StripAndRecalc;
SetVertexModifiers;
end;
cbPolygonMode.ItemIndex := CLinePolyMode;
end;
procedure TfrmMain.GLSceneViewerMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
lObj : TGLBaseSceneObject;
begin
FOldX := X; FOldY := Y;
{If selecting a different modifier, change the last one's color back to default}
if Assigned(FSelectedModifier) then
FSelectedModifier.Material.FrontProperties.Diffuse.Color := CModColorNormal;
{Get selected objects}
if not (ssCtrl in Shift) then
Exit;
{Check if selected object is a modifier.
If so, change modifiers color as to indicated selected modifier.}
lObj := GLSceneViewer.Buffer.GetPickedObject(X, Y);
if (lObj is TModifierCube) then
begin
FSelectedModifier := TModifierCube(lObj);
FSelectedModifier.Material.FrontProperties.Diffuse.Color := CModColorSelect;
FSelectedModifier.NotifyChange(FSelectedModifier);
ShowModifierStatus(TModifierCube(lObj));
FMoveZ := rbZY.Checked;
FOldMouseWorldPos := MouseWorldPos(X, Y);
end;
end;
procedure TfrmMain.GLSceneViewerMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
var
lCurrentPos : TVector;
lOldV : TVector3f;
lDiff : TVector4f;
begin
{If ctrl is not in use, move around freeform}
if (ssLeft in Shift) and (not (ssCtrl in Shift)) then
begin
GLCamera.MoveAroundTarget(FOldY - Y, FOldX - X);
FOldX := X; FOldY := Y;
Exit;
end;
{Move modifier and change relevant vertex data}
if (ssLeft in Shift) then
begin
FMoveZ := rbZY.Checked;
lCurrentPos := MouseWorldPos(X, Y);
if Assigned(FSelectedModifier) and (VectorNorm(FOldMouseWorldPos) <> 0) then
begin
MakeVector(lOldV, FSelectedModifier.Position.X, FSelectedModifier.Position.Y, FSelectedModifier.Position.Z);
lDiff := VectorSubtract(lCurrentPos, FOldMouseWorldPos);
FSelectedModifier.Position.Translate(lDiff);
ChangeMeshVector(FSelectedModifier, lDiff);
end;
FOldMouseWorldPos := lCurrentPos;
end;
end;
procedure TfrmMain.cbPolygonModeChange(Sender: TObject);
begin
case cbPolygonMode.ItemIndex of
0: GLFreeForm.Material.PolygonMode := pmFill;
1: GLFreeForm.Material.PolygonMode := pmLines;
2: GLFreeForm.Material.PolygonMode := pmPoints;
end;
end;
procedure TfrmMain.SetVertexModifiers;
procedure ScaleVector(var V1, V2 : TVector3F);
begin
V1.X := V1.X * V2.X;
V1.Y := V1.Y * V2.Y;
V1.Z := V1.Z * V2.Z;
end;
var
i, j : Integer;
lVector, lScale : TVector3F;
lModifier : TModifierCube;
begin
FModifierList.Clear;
GLScene.BeginUpdate;
try
with GLFreeForm.MeshObjects do
begin
for i := 0 to Count - 1 do
for j := 0 to Items[i].Vertices.Count - 1 do
begin
lVector := Items[i].Vertices.Items[j];
lModifier := TModifierCube.Create(nil);
lModifier.FVectorIndex := j;
lModifier.FMeshObjIndex := i;
FModifierList.Add(lModifier);
GLScene.Objects.AddChild(lModifier);
lScale := GLFreeForm.Scale.AsAffineVector;
ScaleVector(lVector, lScale);
lModifier.Position.Translate(lVector);
end;
end;
finally
GLScene.EndUpdate;
end;
end;
procedure TfrmMain.FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
begin
GLCamera.AdjustDistanceToTarget(Power(1.1,WheelDelta/120));
end;
procedure TfrmMain.chbViewPointsClick(Sender: TObject);
var
i : Integer;
begin
GLScene.BeginUpdate;
try
for i := 0 to FModifierList.Count - 1 do
TModifierCube(FModifierList.Items[i]).Visible := chbViewPoints.Checked;
finally
GLScene.EndUpdate;
end;
end;
procedure TfrmMain.ShowModifierStatus(const aObj: TModifierCube);
begin
if aObj = nil then
StatusBar.Panels[0].Text := ''
else
StatusBar.Panels[0].Text := Format('Modifier vector index [%d]', [aObj.FVectorIndex]);
end;
function TfrmMain.MouseWorldPos(x, y: Integer): TVector;
var
v : TVector;
begin
y := GLSceneViewer.Height - y;
if Assigned(FSelectedModifier) then
begin
SetVector(v, x, y, 0);
if FMoveZ then
GLSceneViewer.Buffer.ScreenVectorIntersectWithPlaneXZ(v, FSelectedModifier.Position.Y, Result)
else
GLSceneViewer.Buffer.ScreenVectorIntersectWithPlaneXY(v, FSelectedModifier.Position.Z, Result);
end
else
SetVector(Result, NullVector);
end;
procedure TfrmMain.ChangeMeshVector(const aObj : TModifierCube; const aPos : TVector4f);
var
lVIndex,
lMIndex : Integer;
v : TVector3f;
begin
if aObj = nil then
Exit;
lVIndex := aObj.FVectorIndex;
lMIndex := aObj.FMeshObjIndex;
{Get new vertex position, keep freeform scale in mind and redraw freeform.}
MakeVector(v, aPos.X/CModifierDim, aPos.Y/CModifierDim, aPos.Z/CModifierDim);
GLFreeForm.MeshObjects.Items[lMIndex].Vertices.TranslateItem(lVIndex, v);
GLFreeForm.StructureChanged;
end;
procedure TfrmMain.GLSceneViewerMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if Assigned(FSelectedModifier) then
begin
FSelectedModifier.Material.FrontProperties.Diffuse.Color := CModColorNormal;
FSelectedModifier := nil;
{Recalculate structure and redraw freeform}
StripAndRecalc;
{Reset vertex modifiers and their data.}
SetVertexModifiers;
end;
end;
procedure TfrmMain.chbShowAxisClick(Sender: TObject);
begin
dcModifiers.ShowAxes := TCheckBox(Sender).Checked;
end;
procedure TfrmMain.tbPosChange(Sender: TObject);
begin
GLCamera.Position.Z := tbPos.Position;
end;
procedure TfrmMain.GLSceneViewerBeforeRender(Sender: TObject);
begin
glEnable(GL_NORMALIZE);
end;
procedure TfrmMain.btnVertexClick(Sender: TObject);
var
i, j : Integer;
lList : TStringList;
lVector : TVector3f;
begin
lList := TStringList.Create;
try
with GLFreeForm.MeshObjects do
for i := 0 to Count - 1 do
begin
lList.Add('For mesh object ' + IntToStr(i));
for j := 0 to Items[i].Vertices.Count - 1 do
begin
lVector := Items[i].Vertices.Items[j];
lList.Add(Format('%f %f %f', [lVector.X, lVector.Y, lVector.Z]));
end;
end;
ShowMeshData(lList);
finally
FreeAndNil(lList);
end;
end;
procedure TfrmMain.btnNormalsClick(Sender: TObject);
var
i, j : Integer;
lList : TStringList;
lVector : TVector3f;
begin
lList := TStringList.Create;
try
with GLFreeForm.MeshObjects do
for i := 0 to Count - 1 do
begin
lList.Add('For mesh object ' + IntToStr(i));
for j := 0 to Items[i].Normals.Count - 1 do
begin
lVector := Items[i].Normals.Items[j];
lList.Add(Format('%f %f %f', [lVector.X, lVector.Y, lVector.Z]));
end;
end;
ShowMeshData(lList);
finally
FreeAndNil(lList);
end;
end;
procedure TfrmMain.btnTextcoordsClick(Sender: TObject);
var
i, j : Integer;
lList : TStringList;
lVector : TVector3f;
begin
lList := TStringList.Create;
try
with GLFreeForm.MeshObjects do
for i := 0 to Count - 1 do
begin
lList.Add('For mesh object ' + IntToStr(i));
for j := 0 to Items[i].TexCoords.Count - 1 do
begin
lVector := Items[i].TexCoords.Items[j];
lList.Add(Format('%f %f %f', [lVector.X, lVector.Y, lVector.Z]));
end;
end;
ShowMeshData(lList);
finally
FreeAndNil(lList);
end;
end;
procedure TfrmMain.btnGroupsClick(Sender: TObject);
var
i : Integer;
lList : TStringList;
begin
lList := TStringList.Create;
try
with GLFreeForm.MeshObjects do
for i := 0 to Count - 1 do
begin
lList.Add('For mesh object ' + IntToStr(i));
lList.Add(IntToStr(Items[i].TriangleCount));
end;
ShowMeshData(lList);
finally
FreeAndNil(lList);
end;
end;
procedure TfrmMain.StripAndRecalc;
var
lTrigList,
lNormals : TAffineVectorList;
lIndices : TIntegerList;
lObj : TMeshObject;
lStrips : TPersistentObjectList;
lFaceGroup : TFGVertexIndexList;
i : Integer;
begin
// Extract raw triangle data to work with.
lTrigList := GLFreeForm.MeshObjects.ExtractTriangles;
// Builds a vector-count optimized indices list.
lIndices := BuildVectorCountOptimizedIndices(lTrigList);
// Alter reference/indice pair and removes unused reference values.
RemapAndCleanupReferences(lTrigList, lIndices);
// Calculate normals.
lNormals := BuildNormals(lTrigList, lIndices);
// Strip where posible.
lStrips := StripifyMesh(lIndices, lTrigList.Count, True);
// Clear current mesh object data.
GLFreeForm.MeshObjects.Clear;
// Setup new mesh object.
lObj := TMeshObject.CreateOwned(GLFreeForm.MeshObjects);
lObj.Vertices := lTrigList;
lObj.Mode := momFaceGroups;
lObj.Normals := lNormals;
for i:=0 to lStrips.Count-1 do
begin
lFaceGroup := TFGVertexIndexList.CreateOwned(lObj.FaceGroups);
lFaceGroup.VertexIndices := (lStrips[i] as TIntegerList);
if i > 0 then
lFaceGroup.Mode := fgmmTriangleStrip
else
lFaceGroup.Mode := fgmmTriangles;
lFaceGroup.MaterialName:=IntToStr(i and 15);
end;
// Redraw freeform
GLFreeForm.StructureChanged;
lTrigList.Free;
lNormals.Free;
lIndices.Free;
end;
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
FModifierList.Clear;
FreeAndNil(FModifierList);
end;
end.
|
unit uStajRecalcForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, uFControl, uLabeledFControl, uDateControl,
FIBQuery, pFIBQuery, FIBDatabase, pFIBDatabase, IBase;
type
TStajRecalcForm = class(TForm)
pFIBD_FullDB: TpFIBDatabase;
pFIBT_Recalc: TpFIBTransaction;
pFIBQ_Recalc: TpFIBQuery;
qFDC_ActDate: TqFDateControl;
CancelButton: TBitBtn;
OkButton: TBitBtn;
procedure OkButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
private
{ Private declarations }
public
constructor Create(AOwner: TComponent; Hnd: integer); reintroduce;
end;
var
StajRecalcForm: TStajRecalcForm;
implementation
{$R *.dfm}
uses NagScreenUnit;
constructor TStajRecalcForm.Create(AOwner: TComponent; Hnd: integer);
begin
inherited Create(AOwner);
pFIBD_FullDB.Handle:=TISC_DB_HANDLE(hnd);
pFIBD_FullDB.Open;
end;
procedure TStajRecalcForm.OkButtonClick(Sender: TObject);
begin
if VarIsNull(qFDC_ActDate.Value) then
begin
MessageDlg('Помилка: необхідно заповнити дату перерахунку! ',mtError,[mbYes],0);
ModalResult:=0;
Exit;
end;
try
NagScreen := TNagScreen.Create(nil);
NagScreen.Show;
NagScreen.SetStatusText('Перераховується стаж...');
pFIBT_Recalc.StartTransaction;
pFIBQ_Recalc.ParamByName('act_date').AsDate:=qFDC_ActDate.Value;
pFIBQ_Recalc.ExecProc;
pFIBT_Recalc.Commit;
NagScreen.Free;
ModalResult := mrOk;
except on e: Exception do
begin
pFIBT_Recalc.Rollback;
NagScreen.Free;
MessageDlg('Помилка: '+e.Message,mtError,[mbYes],0);
ModalResult := 0;
end;
end;
end;
procedure TStajRecalcForm.CancelButtonClick(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
end.
|
unit essentials1;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.ExtCtrls,
Vcl.Menus, EsGrad;
type
TfrmMainForm = class(TForm)
MainMenu1: TMainMenu;
Examples1: TMenuItem;
InvoiceSample1: TMenuItem;
Background1: TMenuItem;
About1: TMenuItem;
bkGradient: TEsGradient;
procedure btnAboutClick(Sender: TObject);
procedure btnBackgroundClick(Sender: TObject);
procedure btnInvoiceClick(Sender: TObject);
private
public
end;
var
frmMainForm: TfrmMainForm;
implementation
uses
frmAbout,
frmInvoice,
frmSettings,
INIFiles;
{$R *.dfm}
procedure TfrmMainForm.btnAboutClick(Sender: TObject);
begin
TfrmAboutBox.Execute;
end;
procedure TfrmMainForm.btnBackgroundClick(Sender: TObject);
var
ini: TIniFile;
begin
TfrmSettingsForm.Execute;
ini := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'settings.ini');
try
bkGradient.Visible := false;
var sVal := ini.ReadString('Settings', 'ColorGradientDirection', 'vertical');
if LowerCase(sVal) = 'horizontal' then begin
bkGradient.Direction := dHorizontal;
end else begin
bkGradient.Direction := dVertical;
end;
finally
ini.Free;
end;
end;
procedure TfrmMainForm.btnInvoiceClick(Sender: TObject);
var
iNo: Integer;
bFound: boolean;
begin
bFound := false;
for iNo := 0 to (MDIChildCount - 1) do begin
if (MDIChildren[iNo].ClassName = TfrmInvoiceForm.ClassName) then begin
bFound := true;
MDIChildren[iNo].BringToFront;
end;
end;
if (bFound = false) then begin
var frm := TfrmInvoiceForm.Create(Self);
frm.Show;
end;
end;
end.
|
unit UStack;
interface
type
TStack = ^TElem;
TElem = record
next: TStack;
case isOperand:Boolean of
true: (operand: String[25]);
false: (operation: Char);
end;
{ Создаёт вершину стека }
procedure createStack(var stack: TStack);
{ Проверяет, пуст ли стек }
function isEmpty(stack: TStack):Boolean;
{ Кладёт на вершину стека символ операции }
procedure push(stack: TStack; operation: Char); overload;
{ Кладёт на вершину стека операнд }
procedure push(stack: TStack; operand: String); overload;
{ Снимает элемент с вершины стека }
function pop(stack: TStack):TElem;
{ Переводит элемент в строку }
function elemToString(elem: TElem):String;
{ Возвращает верхний элемент стека }
function viewTop(stack: TStack):TElem;
{ Очищает стек }
procedure clearStack(stack: TStack);
{ Разрушает стек }
procedure destroyStack(var stack: TStack);
implementation
{ Создаёт вершину стека }
procedure createStack(var stack: TStack);
begin
new(stack);
stack^.next := nil;
end;
{ Проверяет, пуст ли стек }
function isEmpty(stack: TStack):Boolean;
begin
result := stack^.next = nil;
end;
{ Кладёт на вершину стека символ операции }
procedure push(stack: TStack; operation: Char); overload;
var
temp: TStack;
begin
new(temp);
temp^.isOperand := false;
temp^.operation := operation;
temp^.next := stack^.next;
stack^.next := temp;
end;
{ Кладёт на вершину стека операнд }
procedure push(stack: TStack; operand: String); overload;
var
temp: TStack;
begin
new(temp);
temp^.isOperand := true;
temp^.operand := operand;
temp^.next := stack^.next;
stack^.next := temp;
end;
{ Снимает элемент с вершины стека }
function pop(stack: TStack):TElem;
var
temp: TStack;
begin
temp := stack^.next;
stack^.next := temp^.next;
result := temp^;
dispose(temp);
end;
{ Переводит элемент в строку }
function elemToString(elem: TElem):String;
begin
if elem.isOperand then
result := elem.operand
else
result := elem.operation;
end;
{ Возвращает верхний элемент стека }
function viewTop(stack: TStack):TElem;
begin
result := stack^.next^;
end;
{ Очищает стек }
procedure clearStack(stack: TStack);
begin
while stack^.next <> nil do
pop(stack);
end;
{ Разрушает стек }
procedure destroyStack(var stack: TStack);
begin
clearStack(stack);
dispose(stack);
stack := nil;
end;
end.
|
unit UnitLogin;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts,
FMX.Controls.Presentation, FMX.Edit, FMX.StdCtrls, FMX.Objects,
System.JSON,
Firebase.Auth,
Firebase.Interfaces,
Firebase.Request,
Firebase.Response, FMX.ScrollBox, FMX.Memo;
type
TForm1 = class(TForm)
Layout1: TLayout;
edt_login_email: TEdit;
edt_login_senha: TEdit;
rect_login: TRectangle;
Label1: TLabel;
Rectangle1: TRectangle;
Rectangle2: TRectangle;
lbl_esqueci: TLabel;
rect_criar_conta: TRectangle;
Label2: TLabel;
Label3: TLabel;
procedure rect_criar_contaClick(Sender: TObject);
procedure rect_loginClick(Sender: TObject);
procedure lbl_esqueciClick(Sender: TObject);
private
function CreateAccount(email, senha: string; out idUsuario,
erro: string): boolean;
function ErrorMessages(erro: string): string;
function LoginAccount(email, senha: string; out idUsuario,
erro: string): boolean;
function ResetPassword(email: string; out erro: string): boolean;
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
const
api_firebase = '*** _SUA_CHAVE_API_AQUI_ ***';
implementation
{$R *.fmx}
function TForm1.ErrorMessages(erro: string): string;
begin
erro := erro.Replace('EMAIL_NOT_FOUND', 'Email não encontrado');
erro := erro.Replace('INVALID_PASSWORD', 'Senha inválida');
erro := erro.Replace('INVALID_EMAIL', 'Email inválido');
erro := erro.Replace('MISSING_PASSWORD', 'Informe a senha');
erro := erro.Replace('MISSING_EMAIL', 'Informe o email');
erro := erro.Replace('WEAK_PASSWORD', 'Senha fraca');
erro := erro.Replace('EMAIL_EXISTS', 'Email já existe');
Result := erro;
end;
function TForm1.CreateAccount(email, senha: string;
out idUsuario, erro: string): boolean;
var
fbAuth : IFirebaseAuth;
resp : IFirebaseResponse;
json, jsonRet : TJSONObject;
jsonValue : TJSONValue;
begin
try
erro := '';
fbAuth := TFirebaseAuth.Create;
fbAuth.SetApiKey(api_firebase);
resp := fbAuth.CreateUserWithEmailAndPassword(email, senha);
try
json := TJSONObject.ParseJSONValue(
TEncoding.UTF8.GetBytes(resp.ContentAsString), 0) as TJSONObject;
if NOT Assigned(json) then
begin
Result := false;
erro := 'Não foi possível verificar o retorno do servidor (JSON inválido)';
exit;
end;
except on ex:exception do
begin
Result := false;
erro := ex.Message;
exit;
end;
end;
if json.TryGetValue('error', jsonRet) then
begin
erro := jsonRet.Values['message'].Value;
Result := false;
end
else if json.TryGetValue('localId', jsonValue) then
begin
idUsuario := jsonRet.Value;
Result := true;
end
else
begin
erro := 'Retorno desconhecido';
Result := false;
end;
erro := ErrorMessages(erro);
finally
if Assigned(json) then
json.DisposeOf;
end;
end;
function TForm1.LoginAccount(email, senha: string;
out idUsuario, erro: string): boolean;
var
fbAuth : IFirebaseAuth;
resp : IFirebaseResponse;
json, jsonRet : TJSONObject;
jsonValue : TJSONValue;
begin
try
erro := '';
fbAuth := TFirebaseAuth.Create;
fbAuth.SetApiKey(api_firebase);
resp := fbAuth.SignInWithEmailAndPassword(email, senha);
try
json := TJSONObject.ParseJSONValue(
TEncoding.UTF8.GetBytes(resp.ContentAsString), 0) as TJSONObject;
if NOT Assigned(json) then
begin
Result := false;
erro := 'Não foi possível verificar o retorno do servidor (JSON inválido)';
exit;
end;
except on ex:exception do
begin
Result := false;
erro := ex.Message;
exit;
end;
end;
if json.TryGetValue('error', jsonRet) then
begin
erro := jsonRet.Values['message'].Value;
Result := false;
end
else if json.TryGetValue('localId', jsonValue) then
begin
idUsuario := jsonValue.Value;
Result := true;
end
else
begin
erro := 'Retorno desconhecido';
Result := false;
end;
erro := ErrorMessages(erro);
finally
if Assigned(json) then
json.DisposeOf;
end;
end;
function TForm1.ResetPassword(email: string;
out erro: string): boolean;
var
fbAuth : IFirebaseAuth;
resp : IFirebaseResponse;
json, jsonRet : TJSONObject;
jsonValue : TJSONValue;
begin
try
erro := '';
fbAuth := TFirebaseAuth.Create;
fbAuth.SetApiKey(api_firebase);
resp := fbAuth.SendResetPassword(email);
try
json := TJSONObject.ParseJSONValue(
TEncoding.UTF8.GetBytes(resp.ContentAsString), 0) as TJSONObject;
if NOT Assigned(json) then
begin
Result := false;
erro := 'Não foi possível verificar o retorno do servidor (JSON inválido)';
exit;
end;
except on ex:exception do
begin
Result := false;
erro := ex.Message;
exit;
end;
end;
if json.TryGetValue('error', jsonRet) then
begin
erro := jsonRet.Values['message'].Value;
Result := false;
end
else if json.TryGetValue('email', jsonValue) then
Result := true
else
begin
erro := 'Retorno desconhecido';
Result := false;
end;
erro := ErrorMessages(erro);
finally
if Assigned(json) then
json.DisposeOf;
end;
end;
procedure TForm1.rect_criar_contaClick(Sender: TObject);
var
idUsuario, erro : string;
begin
if NOT CreateAccount(edt_login_email.Text,
edt_login_senha.Text,
idUsuario,
erro) then
showmessage(erro)
else
showmessage('Conta criada com sucesso: ' + idUsuario);
end;
procedure TForm1.rect_loginClick(Sender: TObject);
var
idUsuario, erro : string;
begin
if NOT LoginAccount(edt_login_email.Text,
edt_login_senha.Text,
idUsuario,
erro) then
showmessage(erro)
else
showmessage('Login OK: ' + idUsuario);
end;
procedure TForm1.lbl_esqueciClick(Sender: TObject);
var
idUsuario, erro : string;
begin
if NOT ResetPassword(edt_login_email.Text,
erro) then
showmessage(erro)
else
showmessage('Link para redefinição de senha enviado no seu email');
end;
end.
|
unit feli_operators;
{$mode objfpc}
interface
type
FeliOperators = class(TObject)
public
const
largerThanOrEqualTo = '>=';
largerThan = '>';
smallerThanOrEqualTo = '<=';
smallerThan = '<';
equalsTo = '==';
notEqualsTo = '!=';
end;
implementation
end. |
unit ModelVxt;
// Model: Voxel Extension, for models based from voxed used in Voxel Section Editor III
interface
{$INCLUDE source/Global_Conditionals.inc}
{$ifdef VOXEL_SUPPORT}
uses Palette, HVA, Voxel, Mesh, LOD, SysUtils, Graphics, GlConstants, ShaderBank,
Model, MeshVxt;
type
TVoxelCreationStruct = record
Mesh: PMesh;
i : integer;
Section : TVoxelSection;
Palette: TPalette;
ShaderBank: PShaderBank;
Quality: integer;
end;
PVoxelCreationStruct = ^TVoxelCreationStruct;
TModelVxt = class(TModel)
private
// I/O
procedure OpenVoxel;
procedure OpenVoxelSection(const _VoxelSection: PVoxelSection);
public
// Skeleton:
HVA : PHVA;
// Source
Voxel : PVoxel;
VoxelSection : PVoxelSection;
Quality: integer;
// constructors and destructors
constructor Create(const _Filename: string; _ShaderBank : PShaderBank); overload; override;
constructor Create(const _VoxelSection: PVoxelSection; const _Palette : PPalette; _ShaderBank : PShaderBank; _Quality : integer); overload;
constructor Create(const _Voxel: PVoxel; const _Palette : PPalette; const _HVA: PHVA; _ShaderBank : PShaderBank; _Quality : integer); overload;
constructor Create(const _Model: TModel); overload; override;
procedure Initialize(); override;
procedure Clear; override;
// I/O
procedure RebuildModel;
procedure RebuildLOD(i: integer);
procedure RebuildCurrentLOD;
procedure SynchronizeHVA;
// Gets
function GetVoxelCount: longword; override;
// Sets
procedure SetQuality(_value: integer); override;
// Palette Related
procedure ChangeRemappable (_Colour : TColor); override;
procedure ChangePalette(const _Filename: string); override;
// Copies
procedure Assign(const _Model: TModel); override;
// Misc
procedure MakeVoxelHVAIndependent;
end;
PModelVxt = ^TModelVxt;
{$endif}
implementation
{$ifdef VOXEL_SUPPORT}
uses GlobalVars, GenericThread, HierarchyAnimation, BasicMathsTypes;
constructor TModelVxt.Create(const _Filename: string; _ShaderBank : PShaderBank);
begin
Voxel := nil;
VoxelSection := nil;
Quality := C_QUALITY_MAX;
inherited Create(_Filename, _ShaderBank);
end;
constructor TModelVxt.Create(const _Voxel: PVoxel; const _Palette: PPalette; const _HVA: PHVA; _ShaderBank : PShaderBank; _Quality : integer);
begin
Filename := '';
ShaderBank := _ShaderBank;
Voxel := VoxelBank.Add(_Voxel);
HVA := HVABank.Add(_HVA);
VoxelSection := nil;
Quality := _Quality;
New(Palette);
Palette^ := TPalette.Create(_Palette^);
CommonCreationProcedures;
end;
constructor TModelVxt.Create(const _VoxelSection: PVoxelSection; const _Palette : PPalette; _ShaderBank : PShaderBank; _Quality : integer);
begin
Filename := '';
ShaderBank := _ShaderBank;
Voxel := nil;
VoxelSection := _VoxelSection;
Quality := _Quality;
New(Palette);
Palette^ := TPalette.Create(_Palette^);
CommonCreationProcedures;
end;
constructor TModelVxt.Create(const _Model: TModel);
begin
Assign(_Model);
end;
procedure TModelVxt.Clear;
begin
VoxelBank.Delete(Voxel); // even if it is nil, no problem.
HVABank.Delete(HVA);
inherited Clear;
end;
procedure TModelVxt.Initialize();
var
ext : string;
HVAFilename : string;
begin
FType := C_MT_VOXEL;
// Check if we have a random file or a voxel.
if Voxel = nil then
begin
if VoxelSection = nil then
begin
// We have a file to open.
ext := ExtractFileExt(Filename);
if (CompareStr(ext,'.vxl') = 0) then
begin
Voxel := VoxelBank.Add(Filename);
HVAFilename := copy(Filename,1,Length(Filename)-3);
HVAFilename := HVAFilename + 'hva';
HVA := HVABank.Add(HVAFilename,Voxel);
OpenVoxel;
end;
end
else
begin
OpenVoxelSection(VoxelSection);
end;
end
else // we open the current voxel
begin
OpenVoxel;
end;
SynchronizeHVA;
IsVisible := true;
end;
// I/O
function ThreadCreateFromVoxel(const _args: pointer): integer;
var
Data: TVoxelCreationStruct;
begin
if _args <> nil then
begin
Data := PVoxelCreationStruct(_args)^;
(Data.Mesh)^ := TMeshVxt.CreateFromVoxel(Data.i,Data.Section,Data.Palette,Data.ShaderBank,Data.Quality);
(Data.Mesh)^.Next := Data.i+1;
end;
end;
procedure TModelVxt.OpenVoxel;
function CreatePackageForThreadCall(const _Mesh: PMesh; _i : integer; const _Section: TVoxelSection; const _Palette: TPalette; _ShaderBank: PShaderBank; _Quality: integer): TVoxelCreationStruct;
begin
Result.Mesh := _Mesh;
Result.i := _i;
Result.Section := _Section;
Result.Palette := _Palette;
Result.ShaderBank := _ShaderBank;
Result.Quality := _Quality;
end;
procedure LoadSections;
var
i : integer;
Packages: array of TVoxelCreationStruct;
Threads: array of TGenericThread;
MyFunction : TGenericFunction;
begin
SetLength(Threads,Voxel^.Header.NumSections);
SetLength(Packages,Voxel^.Header.NumSections);
MyFunction := ThreadCreateFromVoxel;
for i := 0 to (Voxel^.Header.NumSections-1) do
begin
Packages[i] := CreatePackageForThreadCall(Addr(LOD[0].Mesh[i]),i,Voxel^.Section[i],Palette^,ShaderBank,Quality);
Threads[i] := TGenericThread.Create(MyFunction,Addr(Packages[i]));
end;
for i := 0 to (Voxel^.Header.NumSections-1) do
begin
Threads[i].WaitFor;
Threads[i].Free;
end;
SetLength(Threads,0);
SetLength(Packages,0);
end;
begin
// We may use an existing voxel.
SetLength(LOD,1);
LOD[0] := TLOD.Create;
SetLength(LOD[0].Mesh,Voxel^.Header.NumSections);
LoadSections;
LOD[0].Mesh[High(LOD[0].Mesh)].Next := -1;
CurrentLOD := 0;
FOpened := true;
end;
procedure TModelVxt.OpenVoxelSection(const _VoxelSection : PVoxelSection);
begin
// We may use an existing voxel.
SetLength(LOD,1);
LOD[0] := TLOD.Create;
SetLength(LOD[0].Mesh,1);
LOD[0].Mesh[0] := TMeshVxt.CreateFromVoxel(0,_VoxelSection^,Palette^,ShaderBank,Quality);
CurrentLOD := 0;
HVA := HVABank.LoadNew(nil);
FOpened := true;
end;
procedure TModelVxt.RebuildModel;
var
i : integer;
begin
for i := Low(LOD) to High(LOD) do
begin
RebuildLOD(i);
end;
SynchronizeHVA;
end;
procedure TModelVxt.RebuildLOD(i: integer);
var
j,start : integer;
begin
if Voxel <> nil then
begin
if Voxel^.Header.NumSections > LOD[i].GetNumMeshes then
begin
start := LOD[i].GetNumMeshes;
SetLength(LOD[i].Mesh,Voxel^.Header.NumSections);
for j := start to Voxel^.Header.NumSections - 1 do
begin
LOD[i].Mesh[j] := TMeshVxt.CreateFromVoxel(j,Voxel^.Section[j],Palette^,ShaderBank,Quality);
LOD[i].Mesh[j].Next := j+1;
end;
end;
for j := Low(LOD[i].Mesh) to High(LOD[i].Mesh) do
begin
(LOD[i].Mesh[j] as TMeshVxt).RebuildVoxel(Voxel^.Section[j],Palette^,Quality);
end;
end
else if VoxelSection <> nil then
begin
(LOD[i].Mesh[0] as TMeshVxt).RebuildVoxel(VoxelSection^,Palette^,Quality);
end
else
begin
// At the moment, we won't do anything.
end;
end;
procedure TModelVxt.RebuildCurrentLOD;
begin
RebuildLOD(CurrentLOD);
SynchronizeHVA;
end;
procedure TModelVxt.SynchronizeHVA;
var
s, f: integer;
// Scale: TVector3f;
begin
if HVA <> nil then
begin
if HA <> nil then
begin
HA^.Free;
HA := nil;
end;
new(HA);
HA^ := THierarchyAnimation.Create(HVA.Header.N_Sections, HVA.Header.N_Frames);
for f := 0 to HVA.Header.N_Frames - 1 do
begin
for s := 0 to HVA.Header.N_Sections - 1 do
begin
// Copy transformation matrix values
HA^.TransformAnimations[0].SetMatrix(HVA.GetMatrix(s, f), f, s);
end;
end;
HA^.SetTransformFPS(6); // 1 frame each 0.1 seconds.
HA^.ExecuteTransformAnimationLoop := true;
end
else
begin
if HA <> nil then
begin
HA^.Free;
HA := nil;
end;
new(HA);
if High(LOD[CurrentLOD].Mesh) >= 0 then
begin
HA^ := THierarchyAnimation.Create(High(LOD[CurrentLOD].Mesh) + 1, 1);
end
else
begin
HA^ := THierarchyAnimation.Create(1, 1);
end;
end;
end;
// Gets
function TModelVxt.GetVoxelCount: longword;
var
i: integer;
begin
Result := 0;
for i := Low(LOD[CurrentLOD].Mesh) to High(LOD[CurrentLOD].Mesh) do
begin
if LOD[CurrentLOD].Mesh[i].Opened and LOD[CurrentLOD].Mesh[i].IsVisible then
begin
inc(Result, (LOD[CurrentLOD].Mesh[i] as TMeshVxT).NumVoxels);
end;
end;
end;
// Sets
procedure TModelVxt.SetQuality(_value: integer);
begin
Quality := _value;
RebuildModel;
end;
// Palette Related
procedure TModelVxt.ChangeRemappable(_Colour: TColor);
begin
if Palette <> nil then
begin
Palette^.ChangeRemappable(_Colour);
RebuildModel;
end;
end;
procedure TModelVxt.ChangePalette(const _Filename: string);
begin
if Palette <> nil then
begin
Palette^.LoadPalette(_Filename);
RebuildModel;
end;
end;
// Copies
procedure TModelVxt.Assign(const _Model: TModel);
begin
HVA := (_Model as TModelVxt).HVA;
Voxel := (_Model as TModelVxt).Voxel;
Quality := (_Model as TModelVxt).Quality;
inherited Assign(_Model);
end;
// Misc
procedure TModelVxt.MakeVoxelHVAIndependent;
var
HVATemp: PHVA;
VoxelTemp: PVoxel;
begin
if (HVA <> nil) then
begin
HVATemp := HVABank.Clone(HVA);
HVABank.Delete(HVA);
HVA := HVATemp;
end;
if (Voxel <> nil) then
begin
VoxelTemp := VoxelBank.Clone(Voxel);
VoxelBank.Delete(Voxel);
Voxel := VoxelTemp;
HVA^.p_Voxel := Voxel;
end;
end;
{$endif}
end.
|
unit Pospolite.View.Controls;
{
+-------------------------+
| Package: Pospolite View |
| Author: Matek0611 |
| Email: matiowo@wp.pl |
| Version: 1.0p |
+-------------------------+
Comments:
...
}
{$mode objfpc}{$H+}
{$modeswitch advancedrecords}
{$macro on}
{$define tabdebug}
interface
uses
Classes, SysUtils, Graphics, Controls, dateutils, Forms, Pospolite.View.Basics,
Pospolite.View.Drawing.Basics, Pospolite.View.Drawing.Renderer,
Pospolite.View.CSS.Animation, Pospolite.View.Drawing.Drawer,
Pospolite.View.Threads;
type
{ TPLUIControl }
TPLUIControl = class(TPLCustomControl)
private
FMousePos: TPLPointI;
FMouseDown: TPLBool;
FMouseButton: TMouseButton;
FShiftState: TShiftState;
FZoom: TPLFloat;
function GetScale: TPLFloat; inline;
procedure SetZoom(AValue: TPLFloat);
protected
procedure DoDraw(const ARenderer: TPLDrawingRenderer); virtual;
procedure Paint; override;
procedure MouseEnter; override;
procedure MouseLeave; override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer
); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Redraw; override;
procedure Rezoom; virtual;
property MousePosition: TPLPointI read FMousePos;
property MouseIsDown: TPLBool read FMouseDown;
property MouseButton: TMouseButton read FMouseButton;
property ShiftState: TShiftState read FShiftState;
property Scale: TPLFloat read GetScale;
published
property OnClick;
property OnEnter;
property OnExit;
property Zoom: TPLFloat read FZoom write SetZoom;
end;
{ TPLUIAnimationLoopItem }
TPLUIAnimationLoopItem = class(TObject)
public
Started: TPLBool;
Finished: TPLBool;
CurrentPoint: TPLInt;
Duration: Cardinal;
StartingValues, TargetValues: array of TPLFloat;
Variables: array of TPLPFloat;
TimingFunction: TPLCSSTimingFunction;
Controller: Pointer;
public
constructor Create(const ADuration: Cardinal; const AVariables: array of TPLPFloat;
const ATargetValues: array of TPLFloat; const ATimingFunction: TPLCSSTimingFunction;
const AController: Pointer = nil);
procedure Next;
procedure Start;
procedure Disable;
//class operator =(a, b: TPLUIAnimationLoopItem) r: TPLBool;
end;
TPLUIAnimationQueue = class(specialize TPLObjectList<TPLUIAnimationLoopItem>);
{ TPLUIAnimationLoop }
TPLUIAnimationLoop = class(TPersistent)
private
FQueue: TPLUIAnimationQueue;
FControl: TPLUIControl;
FThread: TPLAsyncTask;
protected
procedure AsyncExecute(const AArguments: array of const);
public const
DefaultAnimationDuration = 100;
AnimationFrames = 1000 div 60;
public
constructor Create(const AControl: TPLUIControl);
destructor Destroy; override;
procedure Add(const AEvent: TPLUIAnimationLoopItem);
procedure DisableByController(const AController: Pointer);
procedure Clear;
function IsAnimating: TPLBool; inline;
end;
TPLUITabsState = (tsNormal, tsHover, tsDown);
TPLUITabsStateColor = array[TPLUITabsState] of TPLColor;
{ TPLUITabsTheme }
TPLUITabsTheme = record
public
Background: TPLColor;
Separators: TPLColor;
Navigation: array[TPLBool] of record // is active?
Icons: TPLUITabsStateColor;
Buttons: TPLUITabsStateColor;
Text: TPLUITabsStateColor;
Background: TPLUITabsStateColor;
CloseButtons: record
Symbol: TPLUITabsStateColor;
Background: TPLUITabsStateColor;
end;
end;
public
class function Light: TPLUITabsTheme; static;
class function Dark: TPLUITabsTheme; static;
procedure ToDark; inline;
procedure ToLight; inline;
end;
TPLUITab = class;
TPLUITabsManager = class;
TPLUITabs = class;
{ TPLUITabList }
TPLUITabList = class(specialize TPLObjectList<TPLUITab>)
private
FTabs: TPLUITabsManager;
public
constructor Create(const ATabs: TPLUITabsManager);
procedure UpdateTabs;
end;
{ TPLUITab }
TPLUITab = class(TPersistent)
private
FBusy: TPLBool;
FCaption: TPLString;
FCloseable: TPLBool;
FColor: TPLColor;
FFavIcon: IPLDrawingBitmap;
FHint: TPLString;
FList: TPLUITabList;
procedure SetBusy(AValue: TPLBool);
procedure SetCaption(AValue: TPLString);
procedure SetCloseable(AValue: TPLBool);
procedure SetColor(AValue: TPLColor);
procedure SetFavIcon(AValue: IPLDrawingBitmap);
protected
FState: TPLUITabsState;
FRect: TPLRectF;
FPinned: TPLBool;
FActive: TPLBool;
function CloseButtonRect: TPLRectF; inline;
function Theme: TPLUITabsTheme; inline;
public
constructor Create(const AList: TPLUITabList);
destructor Destroy; override;
procedure Exchange(const AList: TPLUITabList; const AMoveLast: TPLBool = true); // for pin/unpin
procedure Draw(const ARenderer: TPLDrawingRenderer);
function MouseInTab(const X, Y: TPLFloat): TPLBool; inline;
function MouseInCloseButton(const X, Y: TPLFloat): TPLBool; inline;
procedure Close;
property Caption: TPLString read FCaption write SetCaption;
property Active: TPLBool read FActive;
property Pinned: TPLBool read FPinned;
property Color: TPLColor read FColor write SetColor;
property FavIcon: IPLDrawingBitmap read FFavIcon write SetFavIcon;
property Hint: TPLString read FHint write FHint;
property Busy: TPLBool read FBusy write SetBusy;
property Closeable: TPLBool read FCloseable write SetCloseable;
end;
{ TPLUITabsManager }
TPLUITabsManager = class(TPersistent)
private
FActiveTabIndex: SizeInt;
FAnimate: TPLBool;
FAnimations: TPLUIAnimationLoop;
FTabs: TPLUITabs;
FNormalTabs: TPLUITabList;
FPinnedTabs: TPLUITabList;
function GetActiveTab: TPLUITab;
procedure SetActiveTabIndex(AValue: SizeInt);
protected
FTabsRect, FScrollLeftRect, FScrollRightRect, FViewTabsRect, FNewTabRect: TPLRectF;
FScrolling: TPLBool;
FScrollPos: TPLInt;
procedure MoveTabRect(const ATab: TPLUITab; const ARect: TPLRectF);
function TileSize: TPLFloat; inline;
function TileBtnSize: TPLFloat; inline;
function TileMargin: TPLFloat; inline;
public const
DefaultTabWidth = 220;
MinTabWidth = 72;
public
constructor Create(const ATabs: TPLUITabs);
destructor Destroy; override;
function AddTab: TPLUITab;
procedure RemoveTab(AIndex: SizeInt);
procedure ChangeTabPinning(const ATab: TPLUITab);
procedure UpdateTabs;
function GetTab(AIndex: SizeInt): TPLUITab;
property PinnedTabs: TPLUITabList read FPinnedTabs;
property NormalTabs: TPLUITabList read FNormalTabs;
property Animations: TPLUIAnimationLoop read FAnimations;
property ActiveTabIndex: SizeInt read FActiveTabIndex write SetActiveTabIndex;
property ActiveTab: TPLUITab read GetActiveTab;
property Animate: TPLBool read FAnimate write FAnimate;
end;
{ TPLUITabs }
TPLUITabs = class(TPLUIControl)
private
FManager: TPLUITabsManager;
FTheme: TPLUITabsTheme;
FNotifyResize: TPLBool;
FHoverID: SizeInt;
function GetAlign: TAlign;
procedure SetTheme(AValue: TPLUITabsTheme);
protected
procedure DoDraw(const ARenderer: TPLDrawingRenderer); override;
procedure Resize; override;
procedure Click; override;
procedure MouseLeave; override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer
); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Redraw; override;
procedure UpdateTabs;
function AddTab: TPLUITab; inline;
property Theme: TPLUITabsTheme read FTheme write SetTheme;
published
property Align: TAlign read GetAlign;
property Manager: TPLUITabsManager read FManager;
end;
implementation
uses Dialogs, math, strutils;
{ TPLUIControl }
procedure TPLUIControl.SetZoom(AValue: TPLFloat);
begin
if FZoom = AValue then exit;
FZoom := AValue;
Rezoom;
end;
function TPLUIControl.GetScale: TPLFloat;
begin
Result := FZoom * (Screen.PixelsPerInch / 96);
end;
procedure TPLUIControl.DoDraw(const ARenderer: TPLDrawingRenderer);
begin
// ...
end;
procedure TPLUIControl.Paint;
var
dr: TPLDrawingRenderer;
begin
inherited Paint;
if csDesigning in ComponentState then exit;
dr := TPLDrawingRenderer.Create(Canvas);
try
DoDraw(dr);
finally
dr.Free;
end;
end;
procedure TPLUIControl.MouseEnter;
begin
inherited MouseEnter;
Redraw;
end;
procedure TPLUIControl.MouseLeave;
begin
inherited MouseLeave;
FMousePos := TPLPointI.Create(-1, -1);
Redraw;
end;
procedure TPLUIControl.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
inherited MouseMove(Shift, X, Y);
FMousePos := TPLPointI.Create(X, Y);
FShiftState := Shift;
Redraw;
end;
procedure TPLUIControl.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
inherited MouseDown(Button, Shift, X, Y);
FMousePos := TPLPointI.Create(X, Y);
FMouseDown := true;
FMouseButton := Button;
FShiftState := Shift;
Redraw;
end;
procedure TPLUIControl.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
inherited MouseUp(Button, Shift, X, Y);
FMousePos := TPLPointI.Create(X, Y);
FMouseDown := false;
FMouseButton := Button;
FShiftState := Shift;
Redraw;
end;
constructor TPLUIControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle - [csOpaque] + [csReplicatable, csParentBackground];
FMousePos := TPLPointI.Create(-1, -1);
FMouseDown := false;
FMouseButton := mbLeft;
FShiftState := [];
FZoom := 1;
end;
destructor TPLUIControl.Destroy;
begin
inherited Destroy;
end;
procedure TPLUIControl.Redraw;
begin
Refresh;
end;
procedure TPLUIControl.Rezoom;
begin
//
end;
{ TPLUIControlLoopItem }
constructor TPLUIAnimationLoopItem.Create(const ADuration: Cardinal;
const AVariables: array of TPLPFloat; const ATargetValues: array of TPLFloat;
const ATimingFunction: TPLCSSTimingFunction; const AController: Pointer);
var
i: SizeInt;
begin
Started := false;
Finished := false;
Duration := ADuration;
TimingFunction := ATimingFunction;
Controller := AController;
SetLength(Variables, Length(AVariables));
SetLength(StartingValues, Length(AVariables));
SetLength(TargetValues, Length(AVariables));
for i := Low(Variables) to High(Variables) do begin
Variables[i] := AVariables[i];
StartingValues[i] := AVariables[i]^;
TargetValues[i] := ATargetValues[i];
end;
end;
procedure TPLUIAnimationLoopItem.Next;
var
i: SizeInt;
begin
if Finished then exit;
if not Started then Start;
CurrentPoint += TPLUIAnimationLoop.AnimationFrames;
Finished := CurrentPoint > Duration;
if CurrentPoint > Duration then CurrentPoint := Duration;
if Finished then begin
Started := false;
for i := Low(Variables) to High(Variables) do
Variables[i]^ := TargetValues[i];
end;
if not Finished then
for i := Low(Variables) to High(Variables) do
Variables[i]^ := StartingValues[i] + (TargetValues[i] - StartingValues[i]) * TimingFunction(CurrentPoint / Duration, []).Y;
end;
procedure TPLUIAnimationLoopItem.Start;
begin
Started := true;
Finished := false;
CurrentPoint := -TPLUIAnimationLoop.AnimationFrames;
end;
procedure TPLUIAnimationLoopItem.Disable;
begin
Finished := true;
end;
//class operator TPLUIAnimationLoopItem.=(a, b: TPLUIAnimationLoopItem) r: TPLBool;
//var
// i: SizeInt;
//begin
// r := (a.Started = b.Started) and (a.Finished = b.Finished) and
// (a.Duration = b.Duration) and (a.TimingFunction = b.TimingFunction) and
// (Length(a.TargetValues) = Length(b.TargetValues)) and (Length(a.Variables) = Length(b.Variables));
//
// if r then
// for i := Low(a.Variables) to High(a.Variables) do begin
// r := r and (a.Variables[i] = b.Variables[i]);
// if not r then break;
// end;
//end;
{ TPLUIAnimationLoop }
procedure TPLUIAnimationLoop.AsyncExecute(const AArguments: array of const);
var
item: TPLUIAnimationLoopItem;
begin
while not FQueue.Empty do begin
for item in FQueue do begin
if item.Finished then FQueue.Remove(item)
else item.Next;
end;
if Assigned(FControl) then FControl.Repaint;
FThread.Sleep(AnimationFrames);
end;
end;
constructor TPLUIAnimationLoop.Create(const AControl: TPLUIControl);
begin
inherited Create;
FControl := AControl;
FQueue := TPLUIAnimationQueue.Create;
FThread := nil;
end;
destructor TPLUIAnimationLoop.Destroy;
begin
if Assigned(FThread) then FThread.Cancel;
FThread.Free;
Clear;
FQueue.Free;
inherited Destroy;
end;
procedure TPLUIAnimationLoop.Add(const AEvent: TPLUIAnimationLoopItem);
begin
FQueue.Add(AEvent);
if Assigned(FThread) then begin
FThread.Cancel;
FThread.Free;
FThread := nil;
end;
FThread := TPLAsyncTask.Create(@AsyncExecute, false);
FThread.Async([]);
end;
procedure TPLUIAnimationLoop.DisableByController(const AController: Pointer);
var
i: SizeInt;
begin
if Assigned(FThread) then begin
FThread.Cancel;
FThread.Free;
FThread := nil;
end;
for i := 0 to FQueue.Count-1 do begin
if FQueue[i].Controller = AController then
FQueue[i].Disable;
end;
//if not FQueue.Empty then begin
// FThread := TPLAsyncTask.Create(@AsyncExecute, false);
// FThread.Async([]);
//end;
end;
procedure TPLUIAnimationLoop.Clear;
begin
FQueue.Clear;
end;
function TPLUIAnimationLoop.IsAnimating: TPLBool;
begin
if not Assigned(FThread) then exit(false);
Result := FThread.IsRunning and not (FThread.IsCancelled or FThread.IsFailed);
end;
{ TPLUITabsTheme }
class function TPLUITabsTheme.Light: TPLUITabsTheme;
begin
with Result do begin
Background := '#f0f0f0';
Separators := '#cdcdcd';
with Navigation[false] do begin
Icons[tsNormal] := '#767676';
Icons[tsHover] := '#767676';
Icons[tsDown] := '#767676';
Buttons[tsNormal] := TPLColor.Transparent;
Buttons[tsHover] := '#dadae0';
Buttons[tsDown] := '#cfcfd8';
Text[tsNormal] := '#484848';
Text[tsHover] := '#484848';
Text[tsDown] := '#484848';
Background[tsNormal] := '#f0f0f0';
Background[tsHover] := '#d6d6d6';
Background[tsDown] := '#c0c0c0';
with CloseButtons do begin
Symbol[tsNormal] := '#333333';
Symbol[tsHover] := '#333333';
Symbol[tsDown] := '#333333';
Background[tsNormal] := '#f0f0f0';
Background[tsHover] := '#c0c0c0';
Background[tsDown] := '#cccccc';
end;
end;
with Navigation[true] do begin
Icons[tsNormal] := '#767676';
Icons[tsHover] := '#767676';
Icons[tsDown] := '#767676';
Buttons[tsNormal] := TPLColor.Transparent;
Buttons[tsHover] := '#dadae0';
Buttons[tsDown] := '#cfcfd8';
Text[tsNormal] := '#484848';
Text[tsHover] := '#484848';
Text[tsDown] := '#484848';
Background[tsNormal] := '#ffffff';
Background[tsHover] := '#fcfcfc';
Background[tsDown] := '#f8f8f8';
with CloseButtons do begin
Symbol[tsNormal] := '#333333';
Symbol[tsHover] := '#333333';
Symbol[tsDown] := '#333333';
Background[tsNormal] := '#f0f0f0';
Background[tsHover] := '#c0c0c0';
Background[tsDown] := '#cccccc';
end;
end;
end;
end;
class function TPLUITabsTheme.Dark: TPLUITabsTheme;
begin
with Result do begin
Background := '#1c1b22';
Separators := '#111111';
with Navigation[false] do begin
Icons[tsNormal] := TPLColor.White;
Icons[tsHover] := TPLColor.White;
Icons[tsDown] := TPLColor.White;
Buttons[tsNormal] := TPLColor.Transparent;
Buttons[tsHover] := '#525252';
Buttons[tsDown] := '#5b5b5b';
Text[tsNormal] := TPLColor.White;
Text[tsHover] := TPLColor.White;
Text[tsDown] := TPLColor.White;
Background[tsNormal] := '#1c1b22';
Background[tsHover] := '#353535';
Background[tsDown] := '#4a494e';
with CloseButtons do begin
Symbol[tsNormal] := TPLColor.White;
Symbol[tsHover] := TPLColor.White;
Symbol[tsDown] := TPLColor.White;
Background[tsNormal] := '#1c1b22';
Background[tsHover] := '#4a494e';
Background[tsDown] := '#5c5c61';
end;
end;
with Navigation[true] do begin
Icons[tsNormal] := TPLColor.White;
Icons[tsHover] := TPLColor.White;
Icons[tsDown] := TPLColor.White;
Buttons[tsNormal] := TPLColor.Transparent;
Buttons[tsHover] := '#525252';
Buttons[tsDown] := '#5b5b5b';
Text[tsNormal] := TPLColor.White;
Text[tsHover] := TPLColor.White;
Text[tsDown] := TPLColor.White;
Background[tsNormal] := '#42414d';
Background[tsHover] := '#4e4d59';
Background[tsDown] := '#3b3a46';
with CloseButtons do begin
Symbol[tsNormal] := TPLColor.White;
Symbol[tsHover] := TPLColor.White;
Symbol[tsDown] := TPLColor.White;
Background[tsNormal] := '#42414d';
Background[tsHover] := '#55545f';
Background[tsDown] := '#676671';
end;
end;
end;
end;
procedure TPLUITabsTheme.ToDark;
begin
Self := Dark;
end;
procedure TPLUITabsTheme.ToLight;
begin
Self := Light;
end;
{ TPLUITabList }
constructor TPLUITabList.Create(const ATabs: TPLUITabsManager);
begin
inherited Create(true);
FTabs := ATabs;
end;
procedure TPLUITabList.UpdateTabs;
begin
FTabs.UpdateTabs;
end;
{ TPLUITab }
procedure TPLUITab.SetCaption(AValue: TPLString);
begin
if FCaption = AValue then exit;
FCaption := AValue;
FList.UpdateTabs;
end;
procedure TPLUITab.SetCloseable(AValue: TPLBool);
begin
if FCloseable = AValue then exit;
FCloseable := AValue;
FList.UpdateTabs;
end;
procedure TPLUITab.SetColor(AValue: TPLColor);
begin
if FColor = AValue then exit;
FColor := AValue;
FList.UpdateTabs;
end;
procedure TPLUITab.SetFavIcon(AValue: IPLDrawingBitmap);
begin
if FFavIcon = AValue then exit;
FFavIcon := AValue;
FList.UpdateTabs;
end;
function TPLUITab.CloseButtonRect: TPLRectF;
var
xsize, xmove: TPLFloat;
begin
if FPinned then exit(TPLRectF.Empty);
xsize := FRect.Height / 2;
xmove := xsize / 2;
Result := TPLRectF.Create(FRect.Right - xsize - xmove, FRect.Top + xmove, xsize, xsize);
end;
function TPLUITab.Theme: TPLUITabsTheme;
begin
Result := FList.FTabs.FTabs.Theme;
end;
procedure TPLUITab.SetBusy(AValue: TPLBool);
begin
if FBusy = AValue then exit;
FBusy := AValue;
FList.UpdateTabs;
end;
constructor TPLUITab.Create(const AList: TPLUITabList);
begin
inherited Create;
FState := tsNormal;
FRect := TPLRectF.Empty;
FList := AList;
FCaption := 'Tab';
FActive := false;
FPinned := false;
FFavIcon := nil;
FHint := '';
FBusy := false;
FCloseable := true;
FColor := TPLColor.Transparent;
end;
destructor TPLUITab.Destroy;
begin
inherited Destroy;
end;
procedure TPLUITab.Exchange(const AList: TPLUITabList; const AMoveLast: TPLBool
);
begin
FList.FreeObjects := false;
FList.Remove(Self);
FList.FreeObjects := true;
FList := AList;
if AMoveLast then FList.Add(Self) else FList.Insert(0, Self);
FList.UpdateTabs;
end;
procedure TPLUITab.Draw(const ARenderer: TPLDrawingRenderer);
var
r, rt: TPLRectF;
s, sx: TPLFloat;
fd: TPLDrawingFontData;
begin
r := FRect.Inflate(FList.FTabs.TileMargin, FList.FTabs.TileMargin);
if FActive then r.Height := r.Height + FList.FTabs.TileMargin - 1;
if FActive then begin
sx := min(r.Height, r.Width);
s := sx / 2;
rt := TPLRectF.Create(r.Left - sx, r.Top, sx, r.Height);
ARenderer.Drawer.Surface.MoveTo(0, r.Bottom + 2);
ARenderer.Drawer.Surface.LineTo(0, r.Bottom);
ARenderer.Drawer.Surface.LineTo(r.Left - s, r.Bottom);
ARenderer.Drawer.Surface.ArcTo(rt, pi, pi/2);
rt.Left := r.Left;
ARenderer.Drawer.Surface.ArcTo(rt, 3/2*pi, 2*pi);
ARenderer.Drawer.Surface.LineTo(r.Right - s, r.Top);
rt.Left := r.Right - sx;
ARenderer.Drawer.Surface.ArcTo(rt, 0, pi/2);
rt.Left := r.Right;
ARenderer.Drawer.Surface.ArcTo(rt, 3/2*pi, pi);
ARenderer.Drawer.Surface.LineTo(FList.FTabs.FTabs.Width, r.Bottom);
ARenderer.Drawer.Surface.LineTo(FList.FTabs.FTabs.Width, r.Bottom + 2);
ARenderer.Drawer.Surface.Fill(ARenderer.NewBrushSolid(Theme.Navigation[true].Background[FState]), true);
ARenderer.Drawer.Surface.Stroke(ARenderer.NewPen(ifthen(FColor <> TPLColor.Transparent, FColor.ToString(), Theme.Separators.ToString()), 1));
end else begin
if FPinned then
ARenderer.Drawer.Surface.Ellipse(r)
else
ARenderer.Drawer.Surface.RoundRectangle(r, r.Height / 2);
ARenderer.Drawer.Surface.Fill(ARenderer.NewBrushSolid(Theme.Navigation[false].Background[FState]));
end;
if not FPinned then begin
rt := r.Inflate(FList.FTabs.TileMargin * 2, FList.FTabs.TileMargin);
fd := PLDrawingFontDataDef;
fd.Quality := fqAntialiased;
fd.Color := Theme.Navigation[FActive].Text[FState];
ARenderer.Drawer.Surface.TextOut(ARenderer.NewFont(fd), FCaption, rt, TPLTextDirections.Create(tdLeft, tdCenter));
end;
{$ifdef tabdebug}
ARenderer.Drawer.Surface.Rectangle(r);
ARenderer.Drawer.Surface.Stroke(ARenderer.NewPen(ifthen(FActive, '#ff000055', '#00ff0055')));
if FPinned then exit;
ARenderer.Drawer.Surface.Rectangle(rt);
ARenderer.Drawer.Surface.Stroke(ARenderer.NewPen('#0000ff55'));
{$endif}
end;
function TPLUITab.MouseInTab(const X, Y: TPLFloat): TPLBool;
begin
Result := TPLPointF.Create(X, Y) in FRect;
end;
function TPLUITab.MouseInCloseButton(const X, Y: TPLFloat): TPLBool;
begin
Result := TPLPointF.Create(X, Y) in CloseButtonRect;
end;
procedure TPLUITab.Close;
begin
FList.FreeObjects := false;
FList.Remove(Self);
FList.FreeObjects := true;
FList.UpdateTabs;
Free;
end;
{ TPLUITabsManager }
function TPLUITabsManager.GetActiveTab: TPLUITab;
begin
if (FActiveTabIndex < 0) or (FActiveTabIndex > FPinnedTabs.Count + FNormalTabs.Count) then exit(nil);
Result := nil;
if FActiveTabIndex < FPinnedTabs.Count then
Result := FPinnedTabs[FActiveTabIndex]
else begin
FActiveTabIndex -= FPinnedTabs.Count;
if FActiveTabIndex < FNormalTabs.Count then
Result := FNormalTabs[FActiveTabIndex];
FActiveTabIndex += FPinnedTabs.Count;
end;
end;
procedure TPLUITabsManager.SetActiveTabIndex(AValue: SizeInt);
var
tab: TPLUITab;
begin
for tab in FPinnedTabs do tab.FActive := false;
for tab in FNormalTabs do tab.FActive := false;
//if FActiveTabIndex = AValue then exit;
FActiveTabIndex := AValue;
tab := ActiveTab;
if Assigned(tab) then tab.FActive := true;
// scroll pos update
UpdateTabs;
end;
procedure TPLUITabsManager.MoveTabRect(const ATab: TPLUITab;
const ARect: TPLRectF);
begin
if FTabs.IsResizing or FTabs.FNotifyResize or not FAnimate then begin
ATab.FRect := ARect;
end else begin
FAnimations.DisableByController(ATab);
FAnimations.Add(TPLUIAnimationLoopItem.Create(
TPLUIAnimationLoop.DefaultAnimationDuration, ATab.FRect.PointsPointers,
ARect.Points, TPLCSSTimingFunctions.GetFunction('ease-in'), ATab
));
end;
end;
function TPLUITabsManager.TileSize: TPLFloat;
begin
Result := FTabs.Height;
end;
function TPLUITabsManager.TileBtnSize: TPLFloat;
begin
Result := FTabs.Height * 0.9;
end;
function TPLUITabsManager.TileMargin: TPLFloat;
begin
Result := TileSize - TileBtnSize;
end;
constructor TPLUITabsManager.Create(const ATabs: TPLUITabs);
begin
inherited Create;
FTabs := ATabs;
FNormalTabs := TPLUITabList.Create(Self);
FPinnedTabs := TPLUITabList.Create(Self);
FAnimations := TPLUIAnimationLoop.Create(ATabs);
FScrolling := false;
FScrollPos := 0;
FActiveTabIndex := 0;
FAnimate := true;
end;
destructor TPLUITabsManager.Destroy;
begin
FAnimations.Free;
FNormalTabs.Free;
FPinnedTabs.Free;
inherited Destroy;
end;
function TPLUITabsManager.AddTab: TPLUITab;
begin
Result := TPLUITab.Create(FNormalTabs);
Result.FRect := TPLRectF.Create(FTabsRect.Left, 0, 0, FTabsRect.Height);
if not FPinnedTabs.Empty then Result.FRect.Left := FPinnedTabs.Last.FRect.Right;
if not FNormalTabs.Empty then Result.FRect.Left := FNormalTabs.Last.FRect.Right;
FNormalTabs.Add(Result);
ActiveTabIndex := FPinnedTabs.Count + FNormalTabs.Count-1;
UpdateTabs;
end;
procedure TPLUITabsManager.RemoveTab(AIndex: SizeInt);
var
tab: TPLUITab;
begin
tab := GetTab(AIndex);
if not Assigned(tab) or not tab.Closeable then exit;
if AIndex >= FPinnedTabs.Count then FNormalTabs.Remove(tab)
else FPinnedTabs.Remove(tab);
if ActiveTabIndex >= FPinnedTabs.Count + FNormalTabs.Count then
ActiveTabIndex := ifthen(ActiveTabIndex-1 < 0, 0, ActiveTabIndex-1)
else ActiveTabIndex := max(0, ActiveTabIndex); //!!!zle
UpdateTabs;
end;
procedure TPLUITabsManager.ChangeTabPinning(const ATab: TPLUITab);
begin
if not Assigned(ATab) then exit;
if ATab.FPinned then ATab.Exchange(FNormalTabs)
else ATab.Exchange(FPinnedTabs);
ATab.FPinned := not ATab.FPinned;
if ATab.FActive then begin
if ATab.FPinned then ActiveTabIndex := FPinnedTabs.Count-1
else ActiveTabIndex := FPinnedTabs.Count + FNormalTabs.Count-1;
end;
FTabs.FHoverID := -1;
FTabs.FMouseDown := false;
ATab.FState := tsNormal;
UpdateTabs;
end;
procedure TPLUITabsManager.UpdateTabs;
var
tw, xw: TPLFloat;
i: SizeInt;
r, ntr: TPLRectF;
begin
FViewTabsRect := TPLRectF.Create(FTabs.Width - TileSize, 0, TileSize, TileSize);
ntr := TPLRectF.Create(FViewTabsRect.Left - TileSize, 0, TileSize, TileSize);
FScrollLeftRect := TPLRectF.Create(0, 0, TileSize, TileSize);
FScrollRightRect := TPLRectF.Create(ntr.Left - TileSize, 0, TileSize, TileSize);
FTabsRect := TPLRectF.Create(FScrollLeftRect.Right, 0, FScrollRightRect.Left - FScrollLeftRect.Right, TileSize);
FScrolling := (TileSize * FPinnedTabs.Count + DefaultTabWidth * FNormalTabs.Count) * FTabs.Scale > FTabsRect.Width;
if FNormalTabs.Count > 0 then begin
tw := (FTabsRect.Width - TileSize * FPinnedTabs.Count * FTabs.Scale) / FNormalTabs.Count;
if tw < MinTabWidth * FTabs.Scale then tw := MinTabWidth * FTabs.Scale;
if tw > DefaultTabWidth * FTabs.Scale then tw := DefaultTabWidth * FTabs.Scale;
end else tw := DefaultTabWidth * FTabs.Scale;
if FScrolling then begin
end else begin
FScrollPos := 0;
end;
xw := FScrollLeftRect.Right;
r := TPLRectF.Create(FTabsRect.Left - FScrollPos, FTabsRect.Top, 0, FTabsRect.Height);
for i := 0 to FPinnedTabs.Count-1 do begin
if FPinnedTabs[i].FRect.Width <> TileSize * FTabs.Scale then
FPinnedTabs[i].FRect.Width := TileSize * FTabs.Scale / 2;
r := TPLRectF.Create(r.Right, r.Top, TileSize * FTabs.Scale, r.Height);
MoveTabRect(FPinnedTabs[i], r);
end;
if FNormalTabs.Empty then xw := r.Right+1;
for i := 0 to FNormalTabs.Count-1 do begin
if FNormalTabs[i].FRect.Width <> tw then
FNormalTabs[i].FRect.Width := tw / 2;
r := TPLRectF.Create(r.Right, r.Top, tw, r.Height);
MoveTabRect(FNormalTabs[i], r);
if i = FNormalTabs.Count-1 then xw := r.Right+1;
end;
if not FScrolling then ntr.Left := xw;
FNewTabRect := ntr;
end;
function TPLUITabsManager.GetTab(AIndex: SizeInt): TPLUITab;
begin
if (AIndex < 0) or (AIndex > FPinnedTabs.Count + FNormalTabs.Count) then exit(nil);
Result := nil;
if AIndex < FPinnedTabs.Count then
Result := FPinnedTabs[AIndex]
else begin
AIndex -= FPinnedTabs.Count;
if AIndex < FNormalTabs.Count then
Result := FNormalTabs[AIndex];
end;
end;
{ TPLUITabs }
procedure TPLUITabs.SetTheme(AValue: TPLUITabsTheme);
begin
FTheme := AValue;
FManager.UpdateTabs;
end;
function TPLUITabs.GetAlign: TAlign;
begin
Result := alTop;
end;
procedure TPLUITabs.DoDraw(const ARenderer: TPLDrawingRenderer);
var
tab: TPLUITab;
st: TPLUITabsState;
r: TPLRectF;
begin
// tło
with ARenderer.Drawer.Surface do begin
Rectangle(Self.ClientRect);
Fill(ARenderer.NewBrushSolid(FTheme.Background));
//Rectangle(TPLRectF.Create(0, Height-2, Width, 2));
//Fill(ARenderer.NewBrushSolid(Theme.Navigation[false].Background[tsNormal]));
end;
// karty
for tab in FManager.FPinnedTabs do tab.Draw(ARenderer);
for tab in FManager.FNormalTabs do tab.Draw(ARenderer);
// przewijanie
// nowa karta
with ARenderer.Drawer.Surface do begin
if FMousePos in FManager.FNewTabRect then begin
if FMouseDown then st := tsDown else st := tsHover;
end else st := tsNormal;
r := FManager.FNewTabRect.Inflate(FManager.TileMargin, FManager.TileMargin);
Ellipse(r);
Fill(ARenderer.NewBrushSolid(FTheme.Navigation[false].Buttons[st]));
r := r.Inflate(FManager.TileMargin * 2.5, FManager.TileMargin * 2.5);
MoveTo(r.Middle.X, r.Top);
LineTo(r.Middle.x, r.Bottom);
Stroke(ARenderer.NewPen(FTheme.Navigation[false].Icons[st], Scale * 1.5));
MoveTo(r.Left, r.Middle.Y);
LineTo(r.Right, r.Middle.Y);
Stroke(ARenderer.NewPen(FTheme.Navigation[false].Icons[st], Scale * 1.5));
end;
// lista kart
end;
procedure TPLUITabs.Resize;
begin
inherited Resize;
FNotifyResize := true;
FManager.UpdateTabs;
FNotifyResize := false;
end;
procedure TPLUITabs.Click;
var
tab: TPLUITab;
begin
inherited Click;
if FMousePos in FManager.FNewTabRect then FManager.AddTab else begin
tab := FManager.GetTab(FHoverID);
if Assigned(tab) then begin
if (FManager.ActiveTabIndex <> FHoverID) then begin
FManager.ActiveTabIndex := FHoverID;
// on tab click
end else if ssCtrl in FShiftState then FManager.ChangeTabPinning(tab);
end;
end;
Redraw;
end;
procedure TPLUITabs.MouseLeave;
var
tab: TPLUITab;
begin
inherited MouseLeave;
tab := FManager.GetTab(FHoverID);
if Assigned(tab) then
tab.FState := tsNormal;
FHoverID := -1;
Redraw;
end;
procedure TPLUITabs.MouseMove(Shift: TShiftState; X, Y: Integer);
var
i, bi: SizeInt;
tab: TPLUITab;
begin
inherited MouseMove(Shift, X, Y);
bi := FHoverID;
FHoverID := -1;
for i := 0 to FManager.PinnedTabs.Count-1 do begin
if FMousePos in FManager.PinnedTabs[i].FRect then begin
FHoverID := i;
break;
end;
end;
if FHoverID = -1 then begin
for i := 0 to FManager.NormalTabs.Count-1 do begin
if FMousePos in FManager.NormalTabs[i].FRect then begin
FHoverID := FManager.PinnedTabs.Count + i;
break;
end;
end;
end;
if bi <> FHoverID then begin
tab := FManager.GetTab(bi);
if Assigned(tab) then tab.FState := tsNormal;
tab := FManager.GetTab(FHoverID);
if Assigned(tab) then begin
if FMouseDown then tab.FState := tsDown else tab.FState := tsHover;
end;
end;
end;
procedure TPLUITabs.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
var
tab: TPLUITab;
begin
inherited MouseDown(Button, Shift, X, Y);
if Button = mbMiddle then FManager.RemoveTab(FHoverID);
if Button <> mbLeft then exit;
tab := FManager.GetTab(FHoverID);
if Assigned(tab) then begin
if FMouseDown then tab.FState := tsDown else tab.FState := tsHover;
Redraw;
end;
end;
procedure TPLUITabs.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
var
tab: TPLUITab;
begin
inherited MouseUp(Button, Shift, X, Y);
tab := FManager.GetTab(FHoverID);
if Assigned(tab) then begin
if FMouseDown then tab.FState := tsDown else tab.FState := tsHover;
Redraw;
end;
end;
constructor TPLUITabs.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FManager := TPLUITabsManager.Create(Self);
FTheme := TPLUITabsTheme.Light;
FManager.UpdateTabs;
inherited Align := alTop;
Height := 44;
end;
destructor TPLUITabs.Destroy;
begin
FManager.Free;
inherited Destroy;
end;
procedure TPLUITabs.Redraw;
begin
//if FManager.FAnimations.IsAnimating then exit; // coś nie działa jak trzeba
inherited Redraw;
end;
procedure TPLUITabs.UpdateTabs;
begin
FManager.UpdateTabs;
end;
function TPLUITabs.AddTab: TPLUITab;
begin
Result := FManager.AddTab;
end;
end.
|
unit PanelCanvas;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls;
type
TPanelCanvas = class(TCustomPanel)
private
{ Private declarations }
FCanvas: TCanvas;
protected
{ Protected declarations }
procedure Erased(var Mes: TWMEraseBkgnd); message WM_ERASEBKGND;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property DoubleBuffered;
property ParentDoubleBuffered;
property Canvas read FCanvas;
property Align;
property Alignment;
property Anchors;
property AutoSize;
property BevelEdges;
property BevelInner;
property BevelOuter;
property BevelWidth;
property BiDiMode;
property BorderWidth;
property BorderStyle;
property Caption;
property Color;
property Constraints;
property Ctl3D;
property UseDockManager default True;
property DockSite;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property FullRepaint;
property Font;
property Locked;
property ParentBiDiMode;
property ParentBackground;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnCanResize;
property OnClick;
property OnConstrainedResize;
property OnContextPopup;
property OnDockDrop;
property OnDockOver;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnGetSiteInfo;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnStartDock;
property OnStartDrag;
property OnUnDock;
{ Published declarations }
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Dm', [TPanelCanvas]);
end;
{ TPanelCanvas }
constructor TPanelCanvas.create(AOwner: Tcomponent);
begin
inherited;
FCanvas := TControlCanvas.Create;
TControlCanvas(FCanvas).Control := Self;
end;
destructor TPanelCanvas.Destroy;
begin
FCanvas.Free;
inherited;
end;
procedure TPanelCanvas.Erased(var Mes: TWMEraseBkgnd);
begin
Mes.Result := 1;
end;
end.
|
unit vwuCommon;
interface
uses
System.SysUtils, System.Classes, System.Variants, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, App.DB.Connection;
const
KEY_FIELD_NAME = 'ID';
type
TvwCommon = class(TDataModule)
F: TFDQuery;
DS: TDataSource;
FID: TIntegerField;
private
FDBConnection: TCLDBConnection;
FFilter: string;
FCanUpdate: Boolean;
FOnAfterRefresh: TNotifyEvent;
{событие - данные обновлены}
procedure DoAfterRefresh(); dynamic;
{получение значения ключевого поля}
function GetKeyValue(): Variant;
procedure SetCanUpdate(const Value: Boolean);
function GetActive: Boolean;
procedure SetConnection(const Value: TCLDBConnection);
protected
{формирование sql текста вью}
function GetSqlText(): string; virtual;
{получение фильтра}
function GetFilter(): string;
public
constructor Create(Owner: TComponent); override;
destructor Destroy(); override;
{наименования вью}
class function ViewName(): string; virtual;
{добавление фильтра в запрос}
procedure AddCustomSqlFilter(aFilter: string);
procedure Close;
{обновление данных с запросом на сервер}
procedure RefreshData(aLocateID: Variant);
{позиционируемся на записи}
procedure Locate(aInstanceID: Variant);
{получить текст запроса набора данных}
function GetViewText(aFilter: string): string; virtual;
property Connection: TCLDBConnection read FDBConnection write SetConnection;
property Active: Boolean read GetActive;
property CanUpdate: Boolean read FCanUpdate write SetCanUpdate;
property KeyValue: Variant read GetKeyValue;
property OnAfterRefresh: TNotifyEvent read FOnAfterRefresh write FOnAfterRefresh;
end;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
uses
uServiceUtils;
{$R *.dfm}
{ TvwCommon }
constructor TvwCommon.Create(Owner: TComponent);
begin
inherited;
// F.Connection := FDBConnection.Connection;
FCanUpdate := True;
end;
destructor TvwCommon.Destroy;
begin
FDBConnection := nil;
inherited;
end;
class function TvwCommon.ViewName: string;
begin
Result := '';
end;
procedure TvwCommon.DoAfterRefresh;
begin
{если обработчик назначен, то запускаем его}
if Assigned(FOnAfterRefresh) then
FOnAfterRefresh(Self);
end;
function TvwCommon.GetKeyValue: Variant;
begin
Result := Null;
if F.Active then
Result := F.FieldByName(KEY_FIELD_NAME).Value;
end;
procedure TvwCommon.SetCanUpdate(const Value: Boolean);
begin
FCanUpdate := Value;
end;
procedure TvwCommon.SetConnection(const Value: TCLDBConnection);
begin
FDBConnection := Value;
F.Connection := FDBConnection.Connection;
end;
function TvwCommon.GetSqlText;
begin
Result := GetViewText(FFilter);
end;
function TvwCommon.GetActive: Boolean;
begin
Result := F.Active;
end;
function TvwCommon.GetFilter: string;
begin
Result := FFilter;
end;
procedure TvwCommon.AddCustomSqlFilter(aFilter: string);
begin
FFilter := aFilter;
end;
procedure TvwCommon.Close;
begin
F.Close;
end;
procedure TvwCommon.RefreshData;
var
SqlText: string;
begin
if not CanUpdate then
Exit;
F.DisableControls;
try
SqlText := GetSqlText();
F.Close;
F.SQL.Text := SqlText;
F.Open;
finally
F.EnableControls;
{позиционируемся на записи}
if isNull(aLocateID, 0) > 0 then
F.Locate(FID.FieldName, aLocateID, []);
end;
{генерируем событие - данные обновлены}
DoAfterRefresh();
end;
procedure TvwCommon.Locate(aInstanceID: Variant);
begin
F.Locate(FID.FieldName, aInstanceID, []);
end;
function TvwCommon.GetViewText(aFilter: string): string;
begin
Result := ' SELECT FIRST 1 * FROM ' + ViewName;
{$IFDEF ASProtect}
{$I include\aspr_crypt_begin1.inc}
Result := ' SELECT FIRST 1000 * FROM ' + ViewName;
{$I include\aspr_crypt_end1.inc}
{$I include\aspr_crypt_begin5.inc}
Result := ' SELECT * FROM ' + ViewName;
{$I include\aspr_crypt_end5.inc}
{$I include\aspr_crypt_begin15.inc}
Result := ' SELECT FIRST 1 * FROM ' + ViewName;
{$I include\aspr_crypt_end15.inc}
{$ELSE}
Result := ' SELECT * FROM ' + ViewName;
{$ENDIF}
if not (Trim(aFilter) = '') then
Result := Result + ' WHERE (1 = 1) ' + aFilter;
end;
end.
|
unit uspQuery;
interface
uses
FireDAC.Comp.Client, System.Classes, Firedac.Dapt, System.SysUtils;
type
TspQuery = class(TFDQuery)
private
function GetSQL: String;
public
FSQL: String;
FspColunas: TStringList;
FspTabelas: TStringList;
FspCondicoes: TStringList;
procedure GeraSQL;
procedure MontarSQL;
procedure LimparListas;
destructor Destroy;override;
constructor Create(AOwner: TComponent); override;
published
property SQL : String read GetSQL write FSQL;
property spCondicoes : TStringList read FspCondicoes write FspCondicoes;
property spColunas : TStringList read FspColunas write FspColunas;
property spTabelas : TStringList read FspTabelas write FspTabelas;
end;
implementation
{ TspQuery }
constructor TspQuery.Create(AOwner:TComponent);
begin
inherited;
spColunas := TStringList.Create;
spTabelas := TStringList.Create;
spCondicoes := TStringList.Create;
end;
destructor TspQuery.Destroy;
begin
spCondicoes.Destroy;
spColunas.Destroy;
spTabelas.Destroy;
inherited;
end;
procedure TspQuery.GeraSQL;
begin
if spTabelas.Count = 0 then
begin
LimparListas;
raise Exception.Create('Deve ser informado ao menos uma tabela para a geração do SQL');
end
else if spTabelas.Count > 1 then
begin
LimparListas;
raise Exception.Create('Deve ser informado apenas uma tabela para a geração do SQL');
end
else if spTabelas[0] = EmptyStr then
begin
LimparListas;
raise Exception.Create('Nome da tabela não pode ser <VAZIO> para a geração do SQL');
end;
MontarSQL;
end;
function TspQuery.GetSQL: String;
begin
GeraSQL;
Result := AnsiUpperCase(FSQL);
end;
procedure TspQuery.LimparListas;
begin
spCondicoes.Clear;
spColunas.Clear;
spTabelas.Clear;
end;
procedure TspQuery.MontarSQL;
const
WHERE = ' WHERE ';
SELECT = ' SELECT ';
FROM = ' FROM ';
var
nIndex: Integer;
begin
FSQL := SELECT;
if spColunas.Count > 0 then
begin
for nIndex := 0 to spColunas.Count - 1 do
begin
if nIndex > 0 then
FSQL := FSQL + ', ';
FSQL := FSQL + spColunas[nIndex];
end;
end
else
begin
FSQL := FSQL + ' * ';
end;
if spTabelas.Count > 0 then
begin
FSQL := FSQL + FROM;
for nIndex := 0 to spTabelas.Count - 1 do
begin
if nIndex > 0 then
FSQL := FSQL + ', ';
FSQL := FSQL + spTabelas[nIndex];
end;
end
else
raise Exception.Create('Informe uma tabela');
if spCondicoes.Count > 0 then
begin
FSQL := FSQL + WHERE;
for nIndex := 0 to spCondicoes.Count - 1 do
begin
if nIndex > 0 then
FSQL := FSQL + ' AND ';
FSQL := FSQL + spCondicoes[nIndex];
end;
end;
LimparListas;
end;
end.
|
namespace OxygeneLogo;
interface
uses
System.Windows,
System.Windows.Controls,
System.Windows.Data,
System.Windows.Documents,
System.Windows.Media,
System.Windows.Navigation,
System.Windows.Shapes;
type
OxygeneWindow = public partial class(Window)
private
// To use Loaded event put the Loaded="WindowLoaded" attribute in root element of .xaml file.
// method WindowLoaded(sender: Object; e: EventArgs );
// Sample event handler:
// method ButtonClick(sender: Object; e: RoutedEventArgs);
public
constructor;
end;
implementation
constructor OxygeneWindow;
begin
InitializeComponent();
end;
end. |
unit Main_U;
// Description: TSDUURLLabel Test Application
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, SDUStdCtrls;
type
TfrmMain = class(TForm)
GroupBox1: TGroupBox;
SDUURLLabel: TSDUURLLabel;
edURL: TEdit;
edCaption: TEdit;
Label1: TLabel;
Label2: TLabel;
pbClose: TButton;
procedure edChange(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure pbCloseClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.DFM}
procedure TfrmMain.edChange(Sender: TObject);
begin
SDUURLLabel.Caption := edCaption.Text;
SDUURLLabel.URL := edURL.Text;
end;
procedure TfrmMain.FormShow(Sender: TObject);
begin
Self.Caption := Application.Title;
edCaption.Text := 'Sarah Dean''s WWW site!';
edURL.Text := 'http://www.SDean12.org/';
end;
procedure TfrmMain.pbCloseClick(Sender: TObject);
begin
Close();
end;
END.
|
//Dada la siguiente tabla de temperaturas y deportes implementar un algoritmo que lee
//una temperatura y establezca el correspondiente deporte mostrando el nombre por pantalla
//TEMPERATURA < -5° esquí
//-5° <= TEMPERATURA < 3° ajedrez
//3° <= TEMPERATURA < 10° golf
//10° <= TEMPERATURA < 18° ciclismo
//18° <= TEMPERATURA < 28° tenis
//28° <= TEMPERATURA natación
Program temperaturas;
Var
temperatura:integer;
Begin
write('ingrese la temperatura :');readln(temperatura);
If (temperatura < -5) then
writeln('El deporte es : esqui')
Else
If (temperatura < 3) then
writeln('El deporte es : ajedrez')
Else
If (temperatura < 10) then
writeln('El deporte es : golf')
Else
If (temperatura < 18) then
writeln('El deporte es : ciclismo')
Else
If (temperatura < 28) then
writeln('El deporte es: tenis')
Else
writeln('El deporte es : natacion');
end.
|
(*
Category: SWAG Title: DATE & TIME ROUTINES
Original name: 0027.PAS
Description: Calculate Day Of Week
Author: EARL DUNOVANT
Date: 11-02-93 05:33
*)
{
EARL DUNOVANT
> Which date is what day For a particular month.
Zeller's Congruence is an algorithm that calculates a day of the week given
a year, month and day. Created in 1887(!). Jeff Duntemann of PC Techniques
fame implemented it in TP in the 11/90 issue of Dr Dobbs Journal, With a
(115 min left), (H)elp, More? major kludge because TP's MOD operator returns a remainder instead of a
True mathematical modulus. I added the Kludge Alert banner that I use in my
own code.
}
Function CalcDayOfWeek(Year, Month, Day : Integer) : Integer;
Var
Century,
Holder : Integer;
begin
{ First test For error conditions on input values: }
if (Year < 0) or (Month < 1) or (Month > 12) or (Day < 1) or (Day > 31) then
CalcDayOfWeek := -1 { Return -1 to indicate an error }
else
{ Do the Zeller's Congruence calculation as Zeller himself }
{ described it in "Acta Mathematica" #7, Stockhold, 1887. }
begin
{ First we separate out the year and the century figures: }
Century := Year div 100;
Year := Year MOD 100;
{ Next we adjust the month such that March remains month #3, }
{ but that January and February are months #13 and #14, }
{ *but of the previous year*: }
if Month < 3 then
begin
Inc(Month, 12);
if Year > 0 then
Dec(Year, 1) { The year before 2000 is }
else { 1999, not 20-1... }
begin
Year := 99;
Dec(Century);
end;
end;
{ Here's Zeller's seminal black magic: }
Holder := Day; { Start With the day of month }
Holder := Holder + (((Month + 1) * 26) div 10); { Calc the increment }
Holder := Holder + Year; { Add in the year }
Holder := Holder + (Year div 4); { Correct For leap years }
Holder := Holder + (Century div 4); { Correct For century years }
Holder := Holder - Century - Century; { DON'T KNOW WHY HE DID THIS! }
{***********************KLUDGE ALERT!***************************}
While Holder < 0 do { Get negative values up into }
Inc(Holder, 7); { positive territory before }
{ taking the MOD... }
Holder := Holder MOD 7; { Divide by 7 but keep the }
{ remainder rather than the }
{ quotient }
{***********************KLUDGE ALERT!***************************}
{ Here we "wrap" Saturday around to be the last day: }
if Holder = 0 then
Holder := 7;
{ Zeller kept the Sunday = 1 origin; computer weenies prefer to }
{ start everything With 0, so here's a 20th century kludge: }
Dec(Holder);
CalcDayOfWeek := Holder; { Return the end product! }
end;
end;
{ Test program added by Nacho, 2017 }
begin
Write('Day of week for 2017-07-08 is... ');
WriteLn (CalcDayOfWeek(2017, 07, 08));
end.
|
unit svm_callbacks;
{$mode objfpc}
{$H+}
interface
uses
SysUtils,
svm_common;
const
CallBackStackBlockSize = 1024;
type
TCallBackStack = object
public
items: array of TInstructionPointer;
i_pos, size: cardinal;
procedure init;
procedure push(ip: TInstructionPointer);
function peek: TInstructionPointer;
function popv: TInstructionPointer;
procedure pop;
end;
PCallBackStack = ^TCallBackStack;
implementation
procedure TCallBackStack.init;
begin
SetLength(items, CallBackStackBlockSize);
i_pos := 0;
size := CallBackStackBlockSize;
Push(High(TInstructionPointer));
end;
procedure TCallBackStack.push(ip: TInstructionPointer); inline;
begin
items[i_pos] := ip;
Inc(i_pos);
if i_pos >= size then
begin
size := size + CallBackStackBlockSize;
SetLength(items, size);
end;
end;
function TCallBackStack.popv: TInstructionPointer; inline;
begin
Dec(i_pos);
Result := items[i_pos];
end;
function TCallBackStack.peek: TInstructionPointer; inline;
begin
Result := items[i_pos - 1];
end;
procedure TCallBackStack.pop; inline;
begin
Dec(i_pos);
if size - i_pos > CallBackStackBlockSize then
begin
size := size - CallBackStackBlockSize;
SetLength(items, size);
end;
end;
end.
|
unit AddPriceForm_ex;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxControls, cxContainer, cxEdit,
cxTextEdit, StdCtrls, cxButtons, ExtCtrls, ActnList, cxMaskEdit,
cxDropDownEdit, cn_common_funcs, cnConsts, cnConsts_Messages;
type
TfrmGetPriceInfo = class(TForm)
Panel2: TPanel;
BegLabel: TLabel;
EndLabel: TLabel;
Panel1: TPanel;
NameLabel: TLabel;
cbMonthBeg: TcxComboBox;
cbYearBeg: TcxComboBox;
cbMonthEnd: TcxComboBox;
cbYearEnd: TcxComboBox;
Name_price: TcxTextEdit;
ActionList1: TActionList;
Ok_act: TAction;
Cancel_act: TAction;
Ok_button: TcxButton;
Cancel_button: TcxButton;
procedure Ok_actExecute(Sender: TObject);
procedure Cancel_actExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
DateBegOut:TDateTime;
DateEndOut:TDateTime;
PLanguageIndex:integer;
constructor Create(AOwner:TComponent;DateBeg,DateEnd:TDateTime);reintroduce;
end;
implementation
uses Resources_unitb, GlobalSpr, DateUtils;
{$R *.dfm}
constructor TfrmGetPriceInfo.Create(AOwner: TComponent; DateBeg,DateEnd: TDateTime);
var i:Integer;
begin
inherited Create(AOwner);
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_01));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_02));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_03));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_04));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_05));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_06));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_07));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_08));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_09));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_10));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_11));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_12));
cbMonthEnd.Properties.Items.Add(TRIM(BU_Month_01));
cbMonthEnd.Properties.Items.Add(TRIM(BU_Month_02));
cbMonthEnd.Properties.Items.Add(TRIM(BU_Month_03));
cbMonthEnd.Properties.Items.Add(TRIM(BU_Month_04));
cbMonthEnd.Properties.Items.Add(TRIM(BU_Month_05));
cbMonthEnd.Properties.Items.Add(TRIM(BU_Month_06));
cbMonthEnd.Properties.Items.Add(TRIM(BU_Month_07));
cbMonthEnd.Properties.Items.Add(TRIM(BU_Month_08));
cbMonthEnd.Properties.Items.Add(TRIM(BU_Month_09));
cbMonthEnd.Properties.Items.Add(TRIM(BU_Month_10));
cbMonthEnd.Properties.Items.Add(TRIM(BU_Month_11));
cbMonthEnd.Properties.Items.Add(TRIM(BU_Month_12));
for i:=0 to YEARS_COUNT do
begin
cbYearBeg.Properties.Items.Add(TRIM(IntToStr(BASE_YEAR+i)));
cbYearEnd.Properties.Items.Add(TRIM(IntToStr(BASE_YEAR+i)));
end;
cbMonthbeg.ItemIndex:=MonthOf(datebeg)-1;
for i:=0 to cbYearBeg.Properties.Items.Count-1 do
begin
if pos(cbYearBeg.Properties.Items[i],IntToStr(YearOf(datebeg)))>0 then
begin
cbYearBeg.ItemIndex:=i;
break;
end;
end;
cbMonthend.ItemIndex:=MonthOf(dateend)-1;
for i:=0 to cbYearend.Properties.Items.Count-1 do
begin
if pos(cbYearend.Properties.Items[i],IntToStr(YearOf(dateend)))>0 then
begin
cbYearend.ItemIndex:=i;
break;
end;
end;
Self.DateBegOut:=DateBeg;
Self.DateEndOut:=DateEnd;
end;
procedure TfrmGetPriceInfo.Ok_actExecute(Sender: TObject);
begin
DateSeparator:='.';
datebegout:=StrToDate('01.'+IntToStr(cbMonthbeg.ItemIndex+1)+'.'+cbYearbeg.Properties.Items[cbYearbeg.ItemIndex]);
if(cbMonthend.ItemIndex+1<=11) then
begin
dateendout:=StrToDate('01.'+IntToStr(cbMonthend.ItemIndex+2)+'.'+cbYearend.Properties.Items[cbYearend.ItemIndex]);
dateendout:=dateendout-1;
end
else
begin
dateendout:=StrToDate('01.01.'+cbYearend.Properties.Items[cbYearend.ItemIndex+1]);
dateendout:=dateendout-1;
end;
if Name_price.Text='' then
Begin
ShowMessage(cn_Name_Need[PLanguageIndex]);
exit;
End;
if (datebegout>dateendout) then
begin
MessageBox(handle,Pchar('Некоректні данні'),Pchar(BU_ErrorCaption), MB_OK or MB_ICONWARNING);
exit;
end;
ModalResult:=mrOk;
end;
procedure TfrmGetPriceInfo.Cancel_actExecute(Sender: TObject);
begin
close;
end;
procedure TfrmGetPriceInfo.FormCreate(Sender: TObject);
begin
PLanguageIndex := cn_Common_Funcs.cnLanguageIndex;
Caption := cn_InsertBtn_Caption[PLanguageIndex]+'...';
NameLabel.Caption := cn_Name_Column[PLanguageIndex];
BegLabel.Caption := cn_BegDate_Short[PLanguageIndex];
EndLabel.Caption := cn_EndDate_Short[PLanguageIndex];
Ok_Button.Caption := cn_Accept[PLanguageIndex];
Ok_Button.Hint := cn_Accept[PLanguageIndex];
Cancel_Button.Caption := cn_cancel[PLanguageIndex];
Cancel_Button.Hint := cn_cancel[PLanguageIndex];
end;
end.
|
unit Nathan.ObjectMapping.NamingConvention;
interface
uses
System.SysUtils;
{$M+}
type
INamingConvention = interface
['{4768B825-816A-42E3-8244-4C209CA5B232}']
function GenerateKeyName(const AValue: string): string;
end;
/// <summary>
/// Base class for all derived naming converation.
/// </summary>
TNamingConvention = class(TInterfacedObject, INamingConvention)
function GenerateKeyName(const AValue: string): string; virtual;
end;
/// <summary>
/// Base decorator class for all derived.
/// </summary>
TNamingConventionDecorator = class(TNamingConvention)
strict private
FNamingConvention: INamingConvention;
public
constructor Create(ANamingConvention: INamingConvention); overload;
function GenerateKeyName(const AValue: string): string; override;
end;
/// <summary>
/// Replaces all leading "F".
/// </summary>
TPrefixFNamingConvention = class(TNamingConventionDecorator)
function GenerateKeyName(const AValue: string): string; override;
end;
/// <summary>
/// Put all in lower case letters.
/// </summary>
TLowerNamingConvention = class(TNamingConventionDecorator)
function GenerateKeyName(const AValue: string): string; override;
end;
/// <summary>
/// Removes all underscores.
/// </summary>
TUnderscoreNamingConvention = class(TNamingConventionDecorator)
function GenerateKeyName(const AValue: string): string; override;
end;
/// <summary>
/// Removes all leading "GET" or "SET".
/// </summary>
TGetterSetterNamingConvention = class(TNamingConventionDecorator)
function GenerateKeyName(const AValue: string): string; override;
end;
/// <summary>
/// Own function to replace.
/// </summary>
TOwnFuncNamingConvention = class(TNamingConventionDecorator)
strict private
FOwnFunc: TFunc<string, string>;
public
constructor Create(ANamingConvention: INamingConvention; AOwnFunc: TFunc<string, string>); overload;
function GenerateKeyName(const AValue: string): string; override;
end;
{$M-}
implementation
uses
System.StrUtils;
{ **************************************************************************** }
{ TNamingConvention }
function TNamingConvention.GenerateKeyName(const AValue: string): string;
begin
Result := AValue;
end;
{ **************************************************************************** }
{ TNamingConventionDecorator }
constructor TNamingConventionDecorator.Create(ANamingConvention: INamingConvention);
begin
inherited Create();
FNamingConvention := ANamingConvention;
end;
{ **************************************************************************** }
function TNamingConventionDecorator.GenerateKeyName(const AValue: string): string;
begin
Result := FNamingConvention.GenerateKeyName(AValue);
end;
{ **************************************************************************** }
{ TPrefixFNamingConvention }
function TPrefixFNamingConvention.GenerateKeyName(const AValue: string): string;
begin
Result := inherited GenerateKeyName(IfThen(AValue.ToLower.StartsWith('f'), AValue.Substring(1), AValue))
end;
{ **************************************************************************** }
{ TLowerNamingConvention }
function TLowerNamingConvention.GenerateKeyName(const AValue: string): string;
begin
// That is, userAccount is a camel case and UserAccount is a Pascal case.
Result := inherited GenerateKeyName(AValue.ToLower)
end;
{ **************************************************************************** }
{ TUnderscoreNamingConvention }
function TUnderscoreNamingConvention.GenerateKeyName(const AValue: string): string;
begin
Result := inherited GenerateKeyName(AValue.Replace('_', ''))
end;
{ **************************************************************************** }
{ TGetterSetterNamingConvention }
function TGetterSetterNamingConvention.GenerateKeyName(const AValue: string): string;
begin
Result := inherited GenerateKeyName(
AValue
.Replace('set', '', [rfIgnoreCase])
.Replace('get', '', [rfIgnoreCase]))
end;
{ **************************************************************************** }
{ TOwnFuncNamingConvention }
constructor TOwnFuncNamingConvention.Create(ANamingConvention: INamingConvention; AOwnFunc: TFunc<string, string>);
begin
inherited Create(ANamingConvention);
FOwnFunc := AOwnFunc;
end;
function TOwnFuncNamingConvention.GenerateKeyName(const AValue: string): string;
begin
Result := inherited GenerateKeyName(FOwnFunc(AValue))
end;
end.
|
{$F+,O+}
Unit Help;
INTERFACE
Var
HelpFile : String; (* gdje je commands.bhf (bbs help file) *)
Procedure On (what: String);
IMPLEMENTATION
Uses
Modem;
Var
F : TEXT;
Line: String;
Function Upper (s : String) : String;
Var
i : Integer;
d : Byte;
Begin
d:=Ord(s[0]);
For i:= 1 To d Do
s[i]:=UpCase(s[i]);
Upper:=s;
End; {F||Upper : String}
Function Open_BHF : Boolean;
Begin
Assign (F,HelpFile);
{$I-}
Reset (F);
{$I+}
If IOResult<>0 Then Begin
Modem.OutLn ('BBS Help File does not exist.');
Open_BHF:=FALSE;
End
Else Open_BHF:=TRUE;
End; {F|Open_BHF}
Function Found (what: String) : Boolean;
Begin
While Not(EOF(F)) do begin
ReadLn (F,Line);
If Pos(what,Line)=1 Then Begin
ReadLn (F,Line);
Found:=TRUE;
Exit;
End;
End;
Found:=FALSE;
End; {F|Found : Boolean}
Procedure On (what: String);
Begin
what:='['+Upper(what)+']';
If Not(Open_BHF) Then Exit;
If Not(Found(what)) Then Exit;
While (Pos('[EOD]',Line)<>1) XOR Eof(F) do begin
Modem.OutLn (Line);
ReadLn (F,Line);
End;
Close (F);
End;
End. |
unit Terbilang;
{
Component : Penomoran
Version : 1.0
Coder : Much. Yusron Arif <yusron.arif4@gmail.com>
Copyright © Mata Air Teknologi - Januari 2017
Original Comp. : ATTerbilang v1.0.5
Original Coder : Sony Arianto K <sony-ak@programmer.net>
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
type
TTerbilang = class(TComponent)
private
NullValS : string;
FAuthor : string;
FNumber : integer;
procedure SetNumber(value:integer);
function GetTerbilang:string;
protected
{ Protected declarations }
public
constructor Create(AOwner:TComponent); override;
destructor Destroy; override;
published
property Author : string read FAuthor write NullValS;
property Number : integer read FNumber write SetNumber;
property Terbilang : string read GetTerbilang write NullValS;
end;
procedure Register;
implementation
const
Satu = 'satu ';
Belas = 'belas ';
Angka : array[1..9]of string = ('se','dua ','tiga ','empat ',
'lima ','enam ','tujuh ','delapan ',
'sembilan ');
Satuan3 : array[1..2]of string = ('ratus ','puluh ');
Satuan : array[0..3]of string = ('','ribu ','juta ','milyar ');
function TTerbilang.GetTerbilang:string;
var
tmp,tmp2 : string;
TStr : TStringList;
i,j : integer;
begin
TStr:=TStringList.Create;
tmp :=format('%0.0n',[strtofloat(inttostr(FNumber))])+ThousandSeparator;
while tmp <> '' do
begin
TStr.Insert(0,copy(tmp,1,pos(ThousandSeparator,tmp)-1));
delete(tmp,1,pos(ThousandSeparator,tmp));
end;
for i:=0 to TStr.Count-1 do
TStr.Strings[i] :=format('%0.3d',[strtoint(TStr.Strings[i])]);
for i:=TStr.Count-1 downto 0 do
begin
tmp :=TStr.Strings[i];
for j:=1 to 3 do
begin
if tmp[j] = '0' then continue;
case j of
1 : if tmp[j] <> '0' then
tmp2 := tmp2 + Angka[strtoint(tmp[j])] + Satuan3[j];
2 : case tmp[j] of
'1' : begin
case tmp[j+1] of
'0' : tmp2 := tmp2 + Angka[strtoint(tmp[j])] + Satuan3[j];
'1'..'9' : tmp2 := tmp2 + Angka[strtoint(tmp[j+1])] + Belas;
end;
break;
end;
'2'..'9' : tmp2 := tmp2 + Angka[strtoint(tmp[j])] + Satuan3[j];
end;
3 : case tmp[j] of
'1' : case FNumber of
1 : tmp2 := tmp2 + Satu;
1000..1999: if i = 0 then
tmp2 := tmp2 + Satu
else
tmp2 := tmp2 + Angka[strtoint(tmp[j])];
else
tmp2 :=tmp2 + Satu;
end;
else
tmp2 := tmp2 + Angka[strtoint(tmp[j])];
end;
end;
end;
if strtoint(tmp) <> 0 then
tmp2 := tmp2 + Satuan[i];
end;
TStr.Free;
result :=Trim(tmp2);
end;
procedure TTerbilang.SetNumber(value:integer);
begin
if value <> FNumber then FNumber :=value;
end;
constructor TTerbilang.Create(AOwner:TComponent);
begin
inherited Create(AOwner);
FAuthor :='Much. Yusron Arif <yusron.arif4 *at* gmail *dot* com>';
FNumber :=0;
end;
destructor TTerbilang.Destroy;
begin
inherited;
end;
procedure Register;
begin
RegisterComponents('MATek', [TTerbilang]);
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: Controller relacionado à tabela [ECF_MOVIMENTO]
The MIT License
Copyright: Copyright (C) 2010 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com</p>
Albert Eije (T2Ti.COM)
@version 2.0
*******************************************************************************}
unit EcfMovimentoController;
interface
uses
Classes, SysUtils, Windows, Forms, Controller,
VO, EcfMovimentoVO;
type
TEcfMovimentoController = class(TController)
private
public
class function ConsultaObjeto(pFiltro: String): TEcfMovimentoVO;
class function Altera(pObjeto: TEcfMovimentoVO): Boolean;
class function Exclui(pId: Integer): Boolean;
class function IniciaMovimento(pObjeto: TEcfMovimentoVO): TEcfMovimentoVO;
end;
implementation
uses T2TiORM,
EcfImpressoraVO, EcfCaixaVO, EcfEmpresaVO, EcfTurnoVO, EcfOperadorVO,
EcfFechamentoVO, EcfSuprimentoVO, EcfSangriaVO, EcfDocumentosEmitidosVO,
EcfRecebimentoNaoFiscalVO;
var
ObjetoLocal: TEcfMovimentoVO;
class function TEcfMovimentoController.ConsultaObjeto(pFiltro: String): TEcfMovimentoVO;
var
Filtro: String;
begin
try
Result := TEcfMovimentoVO.Create;
Result := TEcfMovimentoVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True));
//Exercício: crie o método para popular esses objetos automaticamente no T2TiORM
Result.EcfImpressoraVO := TEcfImpressoraVO(TT2TiORM.ConsultarUmObjeto(Result.EcfImpressoraVO, 'ID='+IntToStr(Result.IdEcfImpressora), True));
Result.EcfCaixaVO := TEcfCaixaVO(TT2TiORM.ConsultarUmObjeto(Result.EcfCaixaVO, 'ID='+IntToStr(Result.IdEcfCaixa), True));
Result.EcfEmpresaVO := TEcfEmpresaVO(TT2TiORM.ConsultarUmObjeto(Result.EcfEmpresaVO, 'ID='+IntToStr(Result.IdEcfEmpresa), True));
Result.EcfTurnoVO := TEcfTurnoVO(TT2TiORM.ConsultarUmObjeto(Result.EcfTurnoVO, 'ID='+IntToStr(Result.IdEcfTurno), True));
Result.EcfOperadorVO := TEcfOperadorVO(TT2TiORM.ConsultarUmObjeto(Result.EcfOperadorVO, 'ID='+IntToStr(Result.IdEcfOperador), True));
Result.EcfGerenteVO := TEcfOperadorVO(TT2TiORM.ConsultarUmObjeto(Result.EcfOperadorVO, 'ID='+IntToStr(Result.IdGerenteSupervisor), True));
Filtro := 'ID_ECF_MOVIMENTO = ' + IntToStr(Result.Id);
Result.ListaEcfFechamentoVO := TListaEcfFechamentoVO(TT2TiORM.Consultar(TEcfFechamentoVO.Create, Filtro, True));
Result.ListaEcfSuprimentoVO := TListaEcfSuprimentoVO(TT2TiORM.Consultar(TEcfSuprimentoVO.Create, Filtro, True));
Result.ListaEcfSangriaVO := TListaEcfSangriaVO(TT2TiORM.Consultar(TEcfSangriaVO.Create, Filtro, True));
Result.ListaEcfDocumentosEmitidosVO := TListaEcfDocumentosEmitidosVO(TT2TiORM.Consultar(TEcfDocumentosEmitidosVO.Create, Filtro, True));
Result.ListaEcfRecebimentoNaoFiscalVO := TListaEcfRecebimentoNaoFiscalVO(TT2TiORM.Consultar(TEcfRecebimentoNaoFiscalVO.Create, Filtro, True));
finally
end;
end;
class function TEcfMovimentoController.Altera(pObjeto: TEcfMovimentoVO): Boolean;
begin
try
Result := TT2TiORM.Alterar(pObjeto);
finally
end;
end;
class function TEcfMovimentoController.Exclui(pId: Integer): Boolean;
begin
try
ObjetoLocal := TEcfMovimentoVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
finally
FreeAndNil(ObjetoLocal);
end;
end;
class function TEcfMovimentoController.IniciaMovimento(pObjeto: TEcfMovimentoVO): TEcfMovimentoVO;
var
UltimoID: Integer;
begin
try
UltimoID := TT2TiORM.Inserir(pObjeto);
Result := ConsultaObjeto('ID = ' + IntToStr(UltimoID));
finally
end;
end;
end.
|
(* Generate a cavern, not linked by tunnels *)
unit cavern;
{$mode objfpc}{$H+}
{$RANGECHECKS OFF}
interface
uses
globalutils, map;
type
coordinates = record
x, y: smallint;
end;
var
terrainArray, tempArray, tempArray2: array[1..MAXROWS, 1..MAXCOLUMNS] of char;
r, c, i, iterations, tileCounter: smallint;
(* TESTING - Write cavern to text file *)
filename: ShortString;
myfile: Text;
(* Fill array with walls *)
procedure fillWithWalls;
(* Fill array with random tiles *)
procedure randomTileFill;
(* Generate a cavern *)
procedure generate;
implementation
procedure fillWithWalls;
begin
for r := 1 to MAXROWS do
begin
for c := 1 to MAXCOLUMNS do
begin
terrainArray[r][c] := '*';
end;
end;
end;
procedure randomTileFill;
begin
for r := 1 to MAXROWS do
begin
for c := 1 to MAXCOLUMNS do
begin
(* 45% chance of drawing a wall tile *)
if (Random(100) <= 45) then
terrainArray[r][c] := '*'
else
terrainArray[r][c] := '.';
end;
end;
end;
procedure generate;
begin
// fill map with walls
fillWithWalls;
randomTileFill;
(* Run through cave generator process 5 times *)
for iterations := 1 to 5 do
begin
for r := 1 to MAXROWS do
begin
for c := 1 to MAXCOLUMNS do
begin
(* Generate landmass *)
tileCounter := 0;
if (terrainArray[r - 1][c] = '*') then // NORTH
Inc(tileCounter);
if (terrainArray[r - 1][c + 1] = '*') then // NORTH EAST
Inc(tileCounter);
if (terrainArray[r][c + 1] = '*') then // EAST
Inc(tileCounter);
if (terrainArray[r + 1][c + 1] = '*') then // SOUTH EAST
Inc(tileCounter);
if (terrainArray[r + 1][c] = '*') then // SOUTH
Inc(tileCounter);
if (terrainArray[r + 1][c - 1] = '*') then // SOUTH WEST
Inc(tileCounter);
if (terrainArray[r][c - 1] = '*') then // WEST
Inc(tileCounter);
if (terrainArray[r - 1][c - 1] = '*') then // NORTH WEST
Inc(tileCounter);
(* Set tiles in temporary array *)
if (terrainArray[r][c] = '*') then
begin
if (tileCounter >= 4) then
tempArray[r][c] := '*'
else
tempArray[r][c] := '.';
end;
if (terrainArray[r][c] = '.') then
begin
if (tileCounter >= 5) then
tempArray[r][c] := '*'
else
tempArray[r][c] := '.';
end;
end;
end;
end;
(* Start second cave *)
fillWithWalls;
randomTileFill;
(* Run through cave generator process 5 times *)
for iterations := 1 to 5 do
begin
for r := 1 to MAXROWS do
begin
for c := 1 to MAXCOLUMNS do
begin
(* Generate landmass *)
tileCounter := 0;
if (terrainArray[r - 1][c] = '*') then // NORTH
Inc(tileCounter);
if (terrainArray[r - 1][c + 1] = '*') then // NORTH EAST
Inc(tileCounter);
if (terrainArray[r][c + 1] = '*') then // EAST
Inc(tileCounter);
if (terrainArray[r + 1][c + 1] = '*') then // SOUTH EAST
Inc(tileCounter);
if (terrainArray[r + 1][c] = '*') then // SOUTH
Inc(tileCounter);
if (terrainArray[r + 1][c - 1] = '*') then // SOUTH WEST
Inc(tileCounter);
if (terrainArray[r][c - 1] = '*') then // WEST
Inc(tileCounter);
if (terrainArray[r - 1][c - 1] = '*') then // NORTH WEST
Inc(tileCounter);
(* Set tiles in temporary array *)
if (terrainArray[r][c] = '*') then
begin
if (tileCounter >= 4) then
tempArray2[r][c] := '*'
else
tempArray2[r][c] := '.';
end;
if (terrainArray[r][c] = '.') then
begin
if (tileCounter >= 5) then
tempArray2[r][c] := '*'
else
tempArray2[r][c] := '.';
end;
end;
end;
end;
(* Copy temporary map back to main dungeon map array *)
for r := 1 to MAXROWS do
begin
for c := 1 to MAXCOLUMNS do
begin
if (tempArray[r][c] = '*') and (tempArray2[r][c] = '*') then
terrainArray[r][c] := '.'
else if (tempArray[r][c] = '.') and (tempArray2[r][c] = '.') then
begin
if (terrainArray[r][c] = '*') then
terrainArray[r][c] := '*'
else
terrainArray[r][c] := '#';
end
else
terrainArray[r][c] := '.';
end;
end;
(* draw top and bottom border *)
for i := 1 to MAXCOLUMNS do
begin
terrainArray[1][i] := '*';
terrainArray[MAXROWS][i] := '*';
end;
(* draw left and right border *)
for i := 1 to MAXROWS do
begin
terrainArray[i][1] := '*';
terrainArray[i][MAXCOLUMNS] := '*';
end;
// set player start coordinates
repeat
map.startX := Random(19) + 1;
map.startY := Random(19) + 1;
until (terrainArray[map.startY][map.startX] = '.');
/////////////////////////////
// Write map to text file for testing
//filename:='output_cavern.txt';
//AssignFile(myfile, filename);
// rewrite(myfile);
// for r := 1 to MAXROWS do
//begin
// for c := 1 to MAXCOLUMNS do
// begin
// write(myfile,terrainArray[r][c]);
// end;
// write(myfile, sLineBreak);
// end;
// closeFile(myfile);
//////////////////////////////
// Copy array to main dungeon
for r := 1 to globalutils.MAXROWS do
begin
for c := 1 to globalutils.MAXCOLUMNS do
begin
globalutils.dungeonArray[r][c] := terrainArray[r][c];
end;
end;
(* Set 'room number' to set NPC amount *)
globalutils.currentDgnTotalRooms := 12;
(* Set flag for type of map *)
map.mapType := 2;
end;
end.
|
unit AvanceMemorialPrint;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, FIBDatabase, pFIBDatabase, cxLookAndFeelPainters, StdCtrls,
cxButtons, ExtCtrls, cxCheckBox, cxSpinEdit, cxTextEdit, cxMaskEdit,
cxDropDownEdit, cxControls, cxContainer, cxEdit, cxLabel, cxStyles,
cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, DB, cxDBData,
cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGrid, RxMemDS, FIBDataSet,
pFIBDataSet, ActnList, FIBQuery, pFIBQuery, frxClass, frxDBSet,
cxButtonEdit, frxExportXLS;
type
TfmAvanceMemorialPrint = class(TForm)
DBase: TpFIBDatabase;
Tr: TpFIBTransaction;
cxLabel1: TcxLabel;
cxComboBoxMonth: TcxComboBox;
cxLabel2: TcxLabel;
cxSpinEditYear: TcxSpinEdit;
cxCheckBoxShow: TcxCheckBox;
cxButtonPrint: TcxButton;
cxButtonClose: TcxButton;
StyleRepository: TcxStyleRepository;
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;
cxStyle17: TcxStyle;
cxStyleYellow: TcxStyle;
cxStyleFontBlack: TcxStyle;
cxStyleMalin: TcxStyle;
cxStyleBorder: TcxStyle;
cxStylemalinYellow: TcxStyle;
cxStyleGrid: TcxStyle;
GridTableViewStyleSheetDevExpress: TcxGridTableViewStyleSheet;
DataSource1: TDataSource;
cxButton1: TcxButton;
DS: TpFIBDataSet;
RXLeft: TRxMemoryData;
TWr: TpFIBTransaction;
pFIBDataSet1: TpFIBDataSet;
DataSource3: TDataSource;
cxGrid3DBTableView1: TcxGridDBTableView;
cxGrid3Level1: TcxGridLevel;
cxGrid3: TcxGrid;
cxGrid3DBTableView1DBColumn1: TcxGridDBColumn;
cxGrid3DBTableView1DBColumn2: TcxGridDBColumn;
cxGrid3DBTableView1DBColumn3: TcxGridDBColumn;
cxGrid3DBTableView1DBColumn4: TcxGridDBColumn;
cxGrid3DBTableView1DBColumn5: TcxGridDBColumn;
cxGrid3DBTableView1DBColumn6: TcxGridDBColumn;
ActionList1: TActionList;
Aprint: TAction;
APereform: TAction;
DSPer: TpFIBDataSet;
TWrite: TpFIBTransaction;
Query: TpFIBQuery;
DSDebet: TpFIBDataSet;
frDBDebet: TfrxDBDataset;
DSDSch: TpFIBDataSet;
frDBKSch: TfrxDBDataset;
cxGrid1: TcxGrid;
cxGridDBTableView1: TcxGridDBTableView;
cxGridLevel1: TcxGridLevel;
cxGridDBTableView1DBColumn1: TcxGridDBColumn;
cxGridDBTableView1DBColumn2: TcxGridDBColumn;
cxGridDBTableView1DBColumn3: TcxGridDBColumn;
cxGridDBTableView1DBColumn4: TcxGridDBColumn;
DSProverka: TpFIBDataSet;
DSDebetNAME_PRED: TFIBStringField;
DSDebetSALDO_BEGIN_D: TFIBBCDField;
DSDebetSUMMA_INTO_MBOOK: TFIBBCDField;
DSDebetOKPO: TFIBStringField;
DSDebetID_MAN: TFIBBCDField;
DSDebetID_KEKV: TFIBBCDField;
DSDebetKOD_KEKV: TFIBIntegerField;
DSDebetTITLE_KEKV: TFIBStringField;
DSDebetFAMILIYA: TFIBStringField;
DSDebetIMYA: TFIBStringField;
DSDebetOTCHESTVO: TFIBStringField;
DSDebetTIN: TFIBStringField;
DSDebetBIRTHDAY: TFIBDateField;
DSDebetTAB_NUM: TFIBIntegerField;
DSDebetSUMMA_DEBET: TFIBBCDField;
DSDebetSUMMA_KREDIT: TFIBBCDField;
DSDebetOST_DEBET: TFIBBCDField;
DSDebetOST_KREDIT: TFIBBCDField;
DSDebetOST_ALL_DEBET: TFIBBCDField;
DSDebetOST_ALL_KREDIT: TFIBBCDField;
DSDebetSALDO_BEGIN_K: TFIBBCDField;
DSKSch: TpFIBDataSet;
frxDBKSch: TfrxDBDataset;
DSDSchKOD_SCH: TFIBStringField;
DSDSchTITLE_SCH: TFIBStringField;
DSDSchID_SCH: TFIBBCDField;
DSDSchSUMMA: TFIBBCDField;
DSKSchKOD_SCH: TFIBStringField;
DSKSchTITLE_SCH: TFIBStringField;
DSKSchID_SCH: TFIBBCDField;
DSKSchSUMMA: TFIBBCDField;
DSDSchPAR_S: TFIBStringField;
DSKSchPAR_S2: TFIBStringField;
frxDNeos: TfrxDBDataset;
frxKNeos: TfrxDBDataset;
DBDNeos: TpFIBDataSet;
DBKNeos: TpFIBDataSet;
DBDNeosKOD_SCH: TFIBStringField;
DBDNeosTITLE_SCH: TFIBStringField;
DBDNeosID_SCH: TFIBBCDField;
DBDNeosSUMMA: TFIBBCDField;
DBDNeosPAR_S: TFIBStringField;
DBKNeosKOD_SCH: TFIBStringField;
DBKNeosTITLE_SCH: TFIBStringField;
DBKNeosID_SCH: TFIBBCDField;
DBKNeosSUMMA: TFIBBCDField;
DBKNeosPAR_S: TFIBStringField;
DSDebetDB_SCH_NUMBER: TFIBStringField;
DSDebetDB_SCH_TITLE: TFIBStringField;
DSDebetDB_ID_SCH: TFIBBCDField;
DSDebetDB_DATE_REG: TFIBDateField;
DSDebetDB_NUM_DOC: TFIBStringField;
DSDebetKR_SCH_NUMBER: TFIBStringField;
DSDebetKR_SCH_TITLE: TFIBStringField;
DSDebetKR_ID_SCH: TFIBBCDField;
DSDebetKR_DATE_REG: TFIBDateField;
DSDebetKR_NUM_DOC: TFIBStringField;
DSDebetSUMMA_DEBET_ALL: TFIBBCDField;
DSDebetSUMMA_KREDIT_ALL: TFIBBCDField;
Panel1: TPanel;
Panel2: TPanel;
DataSetSigns: TpFIBDataSet;
cxLabel5: TcxLabel;
ButtonEditBuh: TcxButtonEdit;
cxLabel6: TcxLabel;
ButtonEditFioCheck: TcxButtonEdit;
cxLabel7: TcxLabel;
ButtonEditGlBuhg: TcxButtonEdit;
frxXLSExport1: TfrxXLSExport;
DSDebetMAX_DATE_DOC_OST: TFIBDateField;
DSDebetNUM_DOC_OST: TFIBStringField;
frxReport1: TfrxReport;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cxButtonCloseClick(Sender: TObject);
procedure RXLeftAfterScroll(DataSet: TDataSet);
procedure cxGrid1DBTableView1KeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cxGrid1DBTableView1DblClick(Sender: TObject);
procedure cxGrid3DBTableView1KeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure AprintExecute(Sender: TObject);
procedure APereformExecute(Sender: TObject);
procedure ShowPereform;
procedure deltable;
procedure ButtonEditBuhPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure ButtonEditFioCheckPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure ButtonEditGlBuhgPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure Get_Fio_post(id_man :int64; var name_post_out, fio_small_buhg_out,fio_full_buhg_out : string);
private
id_man_buh, id_man_check, id_man_gl_buhg : int64;
flag_show_right : boolean;
id_session, id_user_ : int64;
j4_mo_print_doc_ost, j4_mo_bukv : integer;
name_post_buhg, name_post_check, name_post_gl_buhg,fio_small_buhg,fio_small_check,fio_small_gl_buhg,fio_full_buhg,fio_full_check,fio_full_gl_buhg :string;
public
constructor Create(AOwner : Tcomponent; db : Tpfibdatabase; id_user : int64); reintroduce; overload;
end;
function ShowMemorialAvance (AOwner : Tcomponent; db : Tpfibdatabase; id_user : int64) : integer; stdcall;
exports ShowMemorialAvance;
implementation
uses DateUtils,
Un_Progress_form,
GlobalSPR,
Un_R_file_Alex,
Un_lo_file_Alex;
{$R *.dfm}
function ShowMemorialAvance (AOwner : Tcomponent; db : Tpfibdatabase; id_user : int64) : integer; stdcall;
var
T : TfmAvanceMemorialPrint;
begin
T := TfmAvanceMemorialPrint.Create(AOwner, db, id_user);
T.FormStyle := fsMDIChild;
T.Show;
Result := -1;
end;
constructor TfmAvanceMemorialPrint.Create(AOwner: Tcomponent; db: Tpfibdatabase;
id_user: int64);
var
name_post, fio_small,fio_full : string;
begin
inherited Create(AOwner);
id_user_ := id_user;
flag_show_right := false;
DBase := DB;
Tr.DefaultDatabase := DBase;
TWr.DefaultDatabase := DBase;
TWrite.DefaultDatabase := DBase;
DBase.DefaultTransaction := Tr;
DS.Database := DBase;
DS.Transaction := Tr;
DSProverka.Database := DBase;
DSProverka.Transaction := Tr;
DSDebet.Database := DBase;
DSDebet.Transaction := TWrite;
DSDSch.Database := DBase;
DSDSch.Transaction := TWrite;
DSKSch.Database := DBase;
DSKSch.Transaction := TWrite;
DBDNeos.Database := DBase;
DBDNeos.Transaction := TWrite;
DBKNeos.Database := DBase;
DBKNeos.Transaction := TWrite;
DataSetSigns.Database := DBase;
DataSetSigns.Transaction := Tr;
Query.Database := DBase;
Query.Transaction := TWrite;
pFIBDataSet1.Database := DBase;
pFIBDataSet1.Transaction := TWr;
TWr.StartTransaction;
Tr.StartTransaction;
id_session := -1;
DS.Close;
DS.Sqls.SelectSQL.Text := 'select * from J4_INI';
DS.Open;
if DS['ID_MEN_CHECK']<>null then
id_man_check := strtoint64(DS.fbn('ID_MEN_CHECK').AsString)
else id_man_check := 0;
if DS['ID_MEN_GL_BUHG']<>null then
id_man_gl_buhg := strtoint64(DS.fbn('ID_MEN_GL_BUHG').AsString)
else id_man_gl_buhg := 0;
if DS['J4_MO_PRINT_DOC_OST']<>null then
j4_mo_print_doc_ost := DS.fbn('J4_MO_PRINT_DOC_OST').AsInteger
else j4_mo_print_doc_ost := 0;
if DS['J4_MO_NOT_PRINT_BUKV_MO']<>null then
j4_mo_bukv := DS.fbn('J4_MO_NOT_PRINT_BUKV_MO').AsInteger
else j4_mo_bukv := 0;
cxComboBoxMonth.ItemIndex := MonthOf(IncDay(date, -DS.fbn('J4_DAY_SHOW_LAST').AsInteger))-1;
cxSpinEditYear.Value := YearOf(IncDay(date, -DS.fbn('J4_DAY_SHOW_LAST').AsInteger));
cxGrid3.Enabled := false;
cxGrid3DBTableView1.Styles.Background := cxStyleBorder;
flag_show_right := true;
DataSetSigns.Close;
DataSetSigns.SQLs.SelectSQL.Text := 'select p.id_man from users u, private_cards pc, people p where u.id_user_ext = pc.id_pcard and p.id_man = pc.id_man and u.id_user='+IntToStr(id_user);
DataSetSigns.Open;
if DataSetSigns['id_man']<>null then
id_man_buh := strtoint64(DataSetSigns.fbn('id_man').AsString)
else id_man_buh := 0;
Get_Fio_post(id_man_buh,name_post, fio_small,fio_full);
name_post_buhg := name_post;
fio_small_buhg := fio_small;
fio_full_buhg := fio_full;
Get_Fio_post(id_man_check,name_post, fio_small,fio_full);
name_post_check := name_post;
fio_small_check := fio_small;
fio_full_check := fio_full;
Get_Fio_post(id_man_gl_buhg,name_post, fio_small,fio_full);
name_post_gl_buhg := name_post;
fio_small_gl_buhg := fio_small;
fio_full_gl_buhg := fio_full;
ButtonEditBuh.Text := fio_full_buhg;
ButtonEditFioCheck.Text := fio_full_check;
ButtonEditGlBuhg.Text := fio_full_gl_buhg;
Caption := Un_R_file_Alex.BANK_MO_CAPTION[1];
cxLabel1.Caption := Un_R_file_Alex.BANK_MO_TAKE_MONT[1];
cxLabel2.Caption := Un_R_file_Alex.BANK_MO_TAKE_YEAR[1];
cxButton1.Caption := Un_R_file_Alex.BANK_MO_TAKE_PEREFORM[1];
cxButtonPrint.Caption := Un_R_file_Alex.BANK_MO_PRINT[1];
cxButtonClose.Caption := Un_R_file_Alex.BANK_MO_EXIT[1];
cxLabel5.Caption := Un_R_file_Alex.J4_BUHG;
cxLabel6.Caption := Un_R_file_Alex.J4_CHECK;
cxLabel7.Caption := Un_R_file_Alex.J4_GL_BUHG;
cxCheckBoxShow.Properties.Caption := Un_R_file_Alex.BANK_MO_PRINT_M[1];
cxGridDBTableView1DBColumn1.Caption := '';
cxGridDBTableView1DBColumn2.Caption := Un_R_file_Alex.BANK_MO_REG_SHORT[1];
cxGridDBTableView1DBColumn3.Caption := Un_R_file_Alex.BANK_MO_SCH_KOD[1];
cxGridDBTableView1DBColumn4.Caption := Un_R_file_Alex.BANK_MO_SCH_TITLE[1];
cxGrid3DBTableView1DBColumn1.Caption := Un_R_file_Alex.BANK_MO_MO[1];
cxGrid3DBTableView1DBColumn2.Caption := Un_R_file_Alex.BANK_MO_RAS[1];
cxGrid3DBTableView1DBColumn3.Caption := Un_R_file_Alex.BANK_MO_NAME_FINANCE[1];
cxGrid3DBTableView1DBColumn4.Caption := Un_R_file_Alex.BANK_MO_BUKVA[1];
cxGrid3DBTableView1DBColumn5.Caption := Un_R_file_Alex.BANK_MO_KOD_REG[1];
cxGrid3DBTableView1DBColumn6.Caption := Un_R_file_Alex.BANK_MO_PROGRAMM[1];
end;
procedure TfmAvanceMemorialPrint.Get_Fio_post(id_man :int64; var name_post_out, fio_small_buhg_out,fio_full_buhg_out : string);
begin
DataSetSigns.Close;
DataSetSigns.SQLs.SelectSQL.Text := 'SELECT * FROM J4_GET_INFO_SIGN('+IntToStr(id_man)+','''+datetostr(date)+''')';
DataSetSigns.Open;
name_post_out := DataSetSigns.FBN('name_post_buhg').AsString;
fio_small_buhg_out := DataSetSigns.FBN('fio_small_buhg').AsString;
fio_full_buhg_out := DataSetSigns.FBN('fio_full_buhg').AsString;
end;
procedure TfmAvanceMemorialPrint.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
// deltable;
if FormStyle = fsMDIChild then Action := CaFree;
end;
procedure TfmAvanceMemorialPrint.cxButtonCloseClick(Sender: TObject);
begin
Close;
end;
procedure TfmAvanceMemorialPrint.RXLeftAfterScroll(DataSet: TDataSet);
var
id, id_reg : int64;
begin
if flag_show_right then
begin
if not RXLeft.IsEmpty then
begin
try pFIBDataSet1.Post except end;
id := RXLeft.FieldByName('id_sch').value;
id_reg := RXLeft.FieldByName('id_reg').value;
pFIBDataSet1.Close;
// pFIBDataSet1.SQLs.SelectSQL.Text := 'select ID_PKV, PKV_TITLE, PKV_KOD, ID_TYPE_FINANCE, TYPE_FINANCE_NAME, TYPE_FINANCE_CODE, MO_CHAR, PRINT_MO, PRINT_RAS_SCH from BANK_TEMP_MO where ID_SESSION='+IntToStr(id_session)+' and ID_SCH= '+IntToStr(id)+'';
pFIBDataSet1.SQLs.SelectSQL.Text := 'select * from BANK_TEMP_MO where ID_SESSION='+IntToStr(id_session)+' and ID_SCH= '+IntToStr(id)+' and ID_REG='+IntToStr(id_reg)+'';
pFIBDataSet1.Open;
if RXLeft.FieldByName('print').asInteger = 1
then begin
cxGrid3.Enabled := true;
cxGrid3DBTableView1.Styles.Background := cxStyleYellow;
end
else begin
cxGrid3.Enabled := false;
cxGrid3DBTableView1.Styles.Background := cxStyleBorder;
end;
end;
end;
end;
procedure TfmAvanceMemorialPrint.cxGrid1DBTableView1KeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if not RXLeft.IsEmpty then
if Key = vk_space then
begin
RXLeft.Open;
RXLeft.Edit;
if RXLeft.FieldByName('print').AsInteger = 1
then RXLeft.FieldByName('print').Value := 0
else begin
RXLeft.FieldByName('print').Value := 1;
RXLeft.Post;
cxGridDBTableView1.Controller.GoToNext(false);
exit;
end;
RXLeft.Post;
end
end;
procedure TfmAvanceMemorialPrint.cxGrid1DBTableView1DblClick(Sender: TObject);
begin
if not RXLeft.IsEmpty then
begin
RXLeft.Open;
RXLeft.Edit;
if RXLeft.FieldByName('print').AsInteger = 1
then RXLeft.FieldByName('print').Value := 0
else RXLeft.FieldByName('print').Value := 1;
RXLeft.Post;
end
end;
procedure TfmAvanceMemorialPrint.cxGrid3DBTableView1KeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if key = VK_RETURN then pFIBDataSet1.Post;
end;
procedure TfmAvanceMemorialPrint.AprintExecute(Sender: TObject);
var
id : int64;
d1, d2 : string;
i1, i2, i3, i4 : int64;
T : TfmUn_Progress_form;
begin
flag_show_right := false;
if not RXLeft.IsEmpty then
begin
try pFIBDataSet1.Post except end;
if cxComboBoxMonth.ItemIndex < 9
then d1 := '01.'+'0'+ IntToStr(cxComboBoxMonth.ItemIndex+1) + '.'+ IntToStr(cxSpinEditYear.Value)
else d1 := '01.'+ IntToStr(cxComboBoxMonth.ItemIndex+1) + '.' + IntToStr(cxSpinEditYear.Value);
d2 := DateToStr(IncDay(IncMonth(StrToDate(d1),1), -1));
RXLeft.First;
while not RXLeft.Eof do
begin
if RXLeft.FieldByName('print').AsInteger = 1 then
begin
id := RXLeft.FieldByName('id_sch').value;
DSProverka.Close;
DSProverka.SQLs.SelectSQL.Text := 'select * from BANK_MO_PROVERKA('+intToStr(id)+', '''+d1+''')';
DSProverka.Open;
if DSProverka.FBN('R_RESULT').AsInteger = 1 then
begin
showmessage(Un_R_file_Alex.AVANCE_MO_SCH[1] +RXLeft.FieldByName('kod_sch').AsString + Un_R_file_Alex.BANK_MO_MES1[1]+cxComboBoxMonth.Text+' '+cxSpinEditYear.Text+'.'+#13+Un_R_file_Alex.BANK_MO_MES2[1]);
exit;
end;
DSProverka.Close;
DS.Close;
DS.SQLs.SelectSQL.Text := 'select * from BANK_TEMP_MO, PUB_SP_REG_UCH where BANK_TEMP_MO.id_reg=PUB_SP_REG_UCH.id_reg and ID_SESSION='+IntToStr(id_session)+' and ID_SCH= '+IntToStr(id)+'';
DS.Open;
DS.First;
while not DS.Eof do
begin
if DS.FBN('PRINT_MO').AsInteger = 1 then
begin
T := TfmUn_Progress_form.Create(nil, wait_, Un_R_file_Alex.M_WAIT[1]);
T.Show;
T.Repaint;
TWrite.StartTransaction;
i1 := StrToint64(DS.fbn('ID_PKV').AsString);
i2 := StrToint64(DS.fbn('ID_TYPE_FINANCE').AsString);
i3 := RXLeft.FieldByName('ID_SCH').value;
i4 := RXLeft.FieldByName('ID_RAS').value;
DSDebet.Close;
DSDebet.SQLs.SelectSQL.Text := 'select * from J4_MO('''+d1+''', '''+d2+''', '+IntToStr(i1)+', '+IntToStr(i2)+', '+IntToStr(i3)+', '+IntToStr(i4)+')';
DSDebet.Open;
DSDebet.FetchAll;
DSDSch.Close;
DSDSch.SQLs.SelectSQL.Text := 'select * from J4_MO_1('''+d1+''', '''+d2+''', '+IntToStr(i1)+', '+IntToStr(i2)+', '+IntToStr(i3)+', '+IntToStr(i4)+')';
DSDSch.Open;
DSDSch.FetchAll;
DSKSch.Close;
DSKSch.SQLs.SelectSQL.Text := 'select * from J4_MO_2('''+d1+''', '''+d2+''', '+IntToStr(i1)+', '+IntToStr(i2)+', '+IntToStr(i3)+', '+IntToStr(i4)+')';
DSKSch.Open;
DSKSch.FetchAll;
DBDNeos.Close;
DBDNeos.SQLs.SelectSQL.Text := 'select * from J4_MO_3('''+d1+''', '''+d2+''', '+IntToStr(i1)+', '+IntToStr(i2)+', '+IntToStr(i3)+', '+IntToStr(i4)+')';
DBDNeos.Open;
DBDNeos.FetchAll;
DBKNeos.Close;
DBKNeos.SQLs.SelectSQL.Text := 'select * from J4_MO_4('''+d1+''', '''+d2+''', '+IntToStr(i1)+', '+IntToStr(i2)+', '+IntToStr(i3)+', '+IntToStr(i4)+')';
DBKNeos.Open;
DBKNeos.FetchAll;
frxReport1.LoadFromFile(ExtractFilePath(Application.ExeName)+ 'Reports\Avance\Avance_40014_ukr.fr3');
frxReport1.Variables['comp'] := QuotedStr(GetComputerNetName);
frxReport1.Variables['id_user'] := QuotedStr(IntToStr(id_user_));
frxReport1.Variables['kod_sch'] := QuotedStr(DS.FBN('kod_sch').AsString);
frxReport1.Variables['name_prog'] := QuotedStr(DS.FBN('PKV_KOD').AsString);
frxReport1.Variables['title_prog'] := QuotedStr(DS.FBN('PKV_TITLE').AsString);
frxReport1.Variables['title_ord'] := QuotedStr(DS.FBN('REG_TITLE').AsString);
frxReport1.Variables['buk_ord'] := QuotedStr(DS.FBN('MO_CHAR').AsString);
frxReport1.Variables['mon_mo'] := QuotedStr(cxComboBoxMonth.Text);
frxReport1.Variables['year_mo'] := QuotedStr(VarToStr(cxSpinEditYear.Value));
frxReport1.Variables['name_post_b'] := QuotedStr(name_post_buhg);
frxReport1.Variables['name_post_c'] := QuotedStr(name_post_check);
frxReport1.Variables['name_post_g_b']:= QuotedStr(name_post_gl_buhg);
frxReport1.Variables['fio_small_b'] := QuotedStr(fio_small_buhg);
frxReport1.Variables['fio_small_c'] := QuotedStr(fio_small_check);
frxReport1.Variables['fio_small_g_b']:= QuotedStr(fio_small_gl_buhg);
frxReport1.Variables['fio_full_b'] := QuotedStr(fio_full_buhg);
frxReport1.Variables['fio_full_c'] := QuotedStr(fio_full_check);
frxReport1.Variables['fio_full_g_b'] := QuotedStr(fio_full_gl_buhg);
frxReport1.Variables['j4_mo_print_doc_o'] := QuotedStr(inttostr(j4_mo_print_doc_ost));
frxReport1.Variables['j4_mo_bukv_not'] := QuotedStr(inttostr(j4_mo_bukv));
T.Free;
frxReport1.DesignReport;
frxReport1.PrepareReport(true);
if not cxCheckBoxShow.Checked then
begin
frxReport1.PrintOptions.ShowDialog := False;
frxReport1.Print;
end
else frxReport1.ShowReport(true);
TWrite.Rollback;
end;
// if DS.FBN('PRINT_RAS_SCH').AsInteger = 1 then
DS.Next;
end;
end;
RXLeft.Next;
end;
end;
flag_show_right := true;
end;
procedure TfmAvanceMemorialPrint.APereformExecute(Sender: TObject);
var
d1, d2 : string;
T : TfmUn_Progress_form;
begin
T := TfmUn_Progress_form.Create(nil, wait_, Un_R_file_Alex.M_WAIT[1]);
T.Show;
T.Repaint;
DSPer.Database := DBase;
DSPer.Transaction := TWrite;
TWrite.StartTransaction;
if id_session > 0 then
begin
deltable;
end;
if cxComboBoxMonth.ItemIndex < 9
then d1 := '01.'+'0'+ IntToStr(cxComboBoxMonth.ItemIndex+1) + '.'+ IntToStr(cxSpinEditYear.Value)
else d1 := '01.'+ IntToStr(cxComboBoxMonth.ItemIndex+1) + '.' + IntToStr(cxSpinEditYear.Value);
d2 := DateToStr(IncDay(IncMonth(StrToDate(d1),1), -1));
DSPer.Close;
DSPer.SQLs.SelectSQL.Text := 'select * from J4_MO_ZAP_GRID('''+d1+''', '''+d2+''')';
DSPer.Open;
id_session := StrToint64(DSPer.fbn('R_ID_SESSION').AsString);
DSPer.Close;
TWrite.Commit;
ShowPereform;
T.Free;
end;
procedure TfmAvanceMemorialPrint.ShowPereform;
begin
flag_show_right := false;
try
DS.Close;
DS.Sqls.SelectSQL.Text := 'select distinct ID_SCH, KOD_SCH, TITLE_SCH, ID_RAS, REG_SHORT, ID_REG from BANK_TEMP_MO where ID_SESSION='+IntToStr(id_session)+'';
DS.Open;
DS.First;
RXLeft.EmptyTable;
while not DS.Eof do
begin
RXLeft.Open;
RXLeft.Insert;
RXLeft.FieldByName('print').Value := 0;
RXLeft.FieldByName('kod_sch').Value := DS.fbn('KOD_SCH').asString;
RXLeft.FieldByName('id_sch').Value := strToInt64(DS.fbn('ID_SCH').asString);
RXLeft.FieldByName('id_ras').Value := strToInt64(DS.fbn('ID_RAS').asString);
RXLeft.FieldByName('title_sch').Value := DS.fbn('TITLE_SCH').asString;
RXLeft.FieldByName('id_reg').Value := DS.fbn('ID_REG').asString;
RXLeft.FieldByName('Reg_short').Value := DS.fbn('REG_SHORT').asString;
RXLeft.Post;
DS.Next;
end;
RXLeft.First;
pFIBDataSet1.SQLs.UpdateSQL.Text := 'UPDATE BANK_TEMP_MO SET PRINT_MO = ?PRINT_MO, PRINT_RAS_SCH = ?PRINT_RAS_SCH WHERE ID_SESSION = ?OLD_ID_SESSION and ID_SCH = ?OLD_ID_SCH and ID_RAS = ?OLD_ID_RAS and ID_PKV = ?OLD_ID_PKV and ID_TYPE_FINANCE = ?OLD_ID_TYPE_FINANCE and ID_REG=?OLD_ID_REG';
// pFIBDataSet1.SQLs.RefreshSQL.Text := 'SELECT BAN.ID_SESSION, BAN.ID_SCH, BAN.KOD_SCH, BAN.TITLE_SCH, BAN.ID_RAS, BAN.KOD_RAS, BAN.ID_PKV, BAN.PKV_TITLE, BAN.PKV_KOD, BAN.ID_TYPE_FINANCE, BAN.TYPE_FINANCE_NAME, BAN.TYPE_FINANCE_CODE, BAN.MO_CHAR, BAN.PRINT_MO, BAN.PRINT_RAS_SCH FROM BANK_TEMP_MO BAN WHERE (BAN.ID_SESSION = ?OLD_ID_SESSION and BAN.ID_SCH = ?OLD_ID_SCH and BAN.ID_RAS = ?OLD_ID_RAS and BAN.ID_PKV = ?OLD_ID_PKV and BAN.ID_TYPE_FINANCE = ?OLD_ID_TYPE_FINANCE';
pFIBDataSet1.Close;
pFIBDataSet1.SQLs.SelectSQL.Text := 'select * from BANK_TEMP_MO where ID_SESSION='+IntToStr(id_session)+' and ID_SCH= '''+RXLeft.FieldByName('id_sch').AsString+''' and ID_REG= '''+RXLeft.FieldByName('id_reg').AsString+''' ';
pFIBDataSet1.Open;
except
pFIBDataSet1.Close;
end;
flag_show_right := true;
end;
procedure TfmAvanceMemorialPrint.deltable;
begin
TWrite.StartTransaction;
Query.close;
Query.SQL.Clear;
Query.SQL.Text := 'delete from BANK_TEMP_MO where id_session='+IntToStr(id_session)+'';
try
Query.ExecQuery;
TWrite.Commit;
except
TWrite.Rollback;
end;
end;
procedure TfmAvanceMemorialPrint.ButtonEditBuhPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
res : Variant;
name_post, fio_small,fio_full : string;
begin
res := Un_lo_file_Alex.MY_GetManEx(self, DBase.Handle, false, false, id_man_buh);
if VarArrayDimCount(res) > 0 then
begin
if (res[0]<>null) and (res[1]<>null) then
begin
if id_man_buh <> res[0] then
begin
id_man_buh := res[0];
ButtonEditBuh.Text := res[1];
Get_Fio_post(id_man_buh,name_post, fio_small,fio_full);
name_post_buhg := name_post;
fio_small_buhg := fio_small;
fio_full_buhg := fio_full;
end;
end;
end;
end;
procedure TfmAvanceMemorialPrint.ButtonEditFioCheckPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
res : Variant;
name_post, fio_small,fio_full : string;
begin
res := Un_lo_file_Alex.MY_GetManEx(self, DBase.Handle, false, false, id_man_check);
if VarArrayDimCount(res) > 0 then
begin
if (res[0]<>null) and (res[1]<>null) then
begin
if id_man_check <> res[0] then
begin
id_man_check := res[0];
ButtonEditFioCheck.Text := res[1];
Get_Fio_post(id_man_check,name_post, fio_small,fio_full);
name_post_check := name_post;
fio_small_check := fio_small;
fio_full_check := fio_full;
end;
end;
end;
end;
procedure TfmAvanceMemorialPrint.ButtonEditGlBuhgPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
res : Variant;
name_post, fio_small,fio_full : string;
begin
res := Un_lo_file_Alex.MY_GetManEx(self, DBase.Handle, false, false, id_man_gl_buhg);
if VarArrayDimCount(res) > 0 then
begin
if (res[0]<>null) and (res[1]<>null) then
begin
if id_man_gl_buhg <> res[0] then
begin
id_man_gl_buhg := res[0];
ButtonEditGlBuhg.Text := res[1];
Get_Fio_post(id_man_gl_buhg,name_post, fio_small,fio_full);
name_post_gl_buhg := name_post;
fio_small_gl_buhg := fio_small;
fio_full_gl_buhg := fio_full;
end;
end;
end;
end;
end.
|
namespace MetalExample;
interface
uses
Metal,
MetalKit;
type
// "Basic Buffers"
MetalExample2 = class(MetalBaseDelegate)
private
const QUAD_SIZE = 20;
cShaderName = 'AAPLShaders2.metallib';
cVertexFuncName = 'vertexShader2';
cFragmentFuncName = 'fragmentColorShader2';
var
_pipelineState :MTLRenderPipelineState ;
_viewportSize : array [0..1] of UInt32;//Integer;
_vertexBuffer : VertexBuffer;//s<AAPLVertex3>;
_numVertices : NSUInteger ;
// Interface
method drawInMTKView(view: not nullable MTKView); override;
method mtkView(view: not nullable MTKView) drawableSizeWillChange(size: CGSize); override;
private
method createVerticies: array of AAPLVertex2;
method generateVertexData : array of AAPLVertex2;
public
constructor initWithMetalKitView(const mtkView : not nullable MTKView);// : MTKViewDelegate;
end;
implementation
method MetalExample2.drawInMTKView(view: not nullable MTKView);
begin
var commandBuffer := _commandQueue.commandBuffer();
commandBuffer.label := 'MyCommand';
var renderPassDescriptor: MTLRenderPassDescriptor := view.currentRenderPassDescriptor;
if renderPassDescriptor ≠ nil then
begin
view.clearColor := MTLClearColorMake(0, 0, 0, 1);
var renderEncoder: IMTLRenderCommandEncoder := commandBuffer.renderCommandEncoderWithDescriptor(renderPassDescriptor);
renderEncoder.label := 'MyRenderEncoder';
// Set the region of the drawable to which we'll draw.
var vp : MTLViewport;
vp.originX:=0.0;;
vp.originY:=0.0;
vp.width:=_viewportSize[0];
vp.height:= _viewportSize[1];
vp.znear:= -1.0;
vp.zfar:= 1.0;
renderEncoder.setViewport(vp);
renderEncoder.setRenderPipelineState(_pipelineState);
// We call -[MTLRenderCommandEncoder setVertexBuffer:offset:atIndex:] to send data in our
// preloaded MTLBuffer from our ObjC code here to our Metal 'vertexShader' function
// This call has 3 arguments
// 1) buffer - The buffer object containing the data we want passed down
// 2) offset - They byte offset from the beginning of the buffer which indicates what
// 'vertexPointer' point to. In this case we pass 0 so data at the very beginning is
// passed down.
// We'll learn about potential uses of the offset in future samples
// 3) index - An integer index which corresponds to the index of the buffer attribute
// qualifier of the argument in our 'vertexShader' function. Note, this parameter is
// the same as the 'index' parameter in
// -[MTLRenderCommandEncoder setVertexBytes:length:atIndex:]
renderEncoder.setVertexBuffer(_vertexBuffer.verticies ) offset(0) atIndex(AAPLVertexInputIndexVertices);
// You send a pointer to `_viewportSize` and also indicate its size
// The `AAPLVertexInputIndexViewportSize` enum value corresponds to the
// `viewportSizePointer` argument in the `vertexShader` function because its
// buffer attribute also uses the `AAPLVertexInputIndexViewportSize` enum value
// for its index
renderEncoder.setVertexBytes(@_viewportSize[0]) length(sizeOf(Int32)*2) atIndex(AAPLVertexInputIndexViewportSize );
// Draw the 3 vertices of our triangle
renderEncoder.drawPrimitives(MTLPrimitiveType.MTLPrimitiveTypeTriangle) vertexStart(0) vertexCount(_numVertices);
renderEncoder.endEncoding();
commandBuffer.presentDrawable(view.currentDrawable);
end;
commandBuffer.commit();
end;
method MetalExample2.mtkView(view: not nullable MTKView) drawableSizeWillChange(size: CGSize);
begin
_viewportSize[0] := Convert.ToInt32(size.width);
_viewportSize[1] := Convert.ToInt32(size.height);
end;
constructor MetalExample2 initWithMetalKitView(const mtkView: not nullable MTKView);
begin
inherited;
var ShaderLoader := new shaderLoader(_device) Shadername(cShaderName) Vertexname(cVertexFuncName) Fragmentname(cFragmentFuncName);
if ShaderLoader = nil then exit nil
else
begin
var lError : Error;
// Configure a pipeline descriptor that is used to create a pipeline state
var pipelineStateDescriptor : MTLRenderPipelineDescriptor := new MTLRenderPipelineDescriptor();
pipelineStateDescriptor.label := "Simple Pipeline";
pipelineStateDescriptor.vertexFunction := ShaderLoader.VertexFunc;
pipelineStateDescriptor.fragmentFunction := ShaderLoader.FragmentFunc;
pipelineStateDescriptor.colorAttachments[0].pixelFormat := mtkView.colorPixelFormat;
_pipelineState := _device.newRenderPipelineStateWithDescriptor(pipelineStateDescriptor) error(var lError);
if (_pipelineState = nil) then
begin
// Pipeline State creation could fail if we haven't properly set up our pipeline descriptor.
// If the Metal API validation is enabled, we can find out more information about what
// went wrong. (Metal API validation is enabled by default when a debug build is run
// from Xcode)
NSLog("Failed to created pipeline state, error %@", lError);
exit nil;
end;
var Buffer := generateVertexData;
var Bufflen : Integer := Buffer.length*sizeOf(AAPLVertex2);
//NSLog("Bufflen %d", Bufflen);
// Create a vertex buffer by allocating storage that can be read by the GPU
// _vertexBuffer := VertexBuffer.newBuffer( _device, Buffer, Bufflen);
_vertexBuffer := VertexBuffer.newBuffer( _device) SourceData(Buffer) withLength(Bufflen);
// number of vertices
_numVertices := Buffer.length;
end;
end;
method MetalExample2.createVerticies : array of AAPLVertex2;
begin
result := new AAPLVertex2[6];
//Positions
result[0].position := [-QUAD_SIZE, QUAD_SIZE];
result[1].position := [ QUAD_SIZE, QUAD_SIZE];
result[2].position := [-QUAD_SIZE, -QUAD_SIZE];
result[3].position := [ QUAD_SIZE, -QUAD_SIZE];
result[4].position := [-QUAD_SIZE, -QUAD_SIZE];
result[5].position := [ QUAD_SIZE, QUAD_SIZE];
// Colors
//result[0].color := Color.createRed();
result[0].color := Color.create(1,1,0,1);
result[1].color := Color.createGreen();
result[2].color := Color.createBlue();
result[3].color := Color.createRed();
result[4].color := Color.createBlue();
result[5].color := Color.createGreen();
end;
method MetalExample2.generateVertexData: array of AAPLVertex2;
begin
const NUM_COLUMNS = 25;
const NUM_ROWS = 15;
const QUAD_SPACING = QUAD_SIZE *2 + 10.0;
var quadVertices := createVerticies;
var NUM_VERTICES_PER_QUAD := quadVertices.length;
var dataSize : Integer := quadVertices.length * NUM_COLUMNS * NUM_ROWS;
result := new AAPLVertex2[dataSize];
for row : Integer := 0 to NUM_ROWS-1 do
begin
for column : Integer := 0 to NUM_COLUMNS -1 do
begin
var upperLeftPosition : vector_float2;
upperLeftPosition[0] := ((-(NUM_COLUMNS) / 2.0) + column) * QUAD_SPACING + QUAD_SPACING/2.0;
upperLeftPosition[1] := ((-(NUM_ROWS) / 2.0) + row) * QUAD_SPACING + QUAD_SPACING/2.0;
for j : Integer := 0 to NUM_VERTICES_PER_QUAD-1 do
begin
var temp:= quadVertices[j];
temp.position[0] := temp.position[0] + upperLeftPosition[0];
temp.position[1] := temp.position[1] + upperLeftPosition[1];
var &index : Integer := (row * NUM_COLUMNS * NUM_VERTICES_PER_QUAD) // Row
+ (column * NUM_VERTICES_PER_QUAD) // Column
+ j; // vertex
// NSLog("row: %d column: %d Vertex: %d index: %d", row, column, j, &index);
result[&index] := temp;
end;
end;
end;
end;
end. |
unit WindowsMissing_U;
// Description: Standard Windows type definitions that are missing from Delphi
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
windows;
const
WM_DEVICECHANGE = $0219;
DBT_DEVTYP_VOLUME = $00000002;
DBTF_MEDIA = $0001; // Change affects media in drive
DBTF_NET = $0002; // Volume is a network drive
DBT_DEVICEREMOVECOMPLETE = $8004; // Device has been removed
type
(*
typedef union _LARGE_INTEGER {
struct {
DWORD LowPart;
LONG HighPart;
};
LONGLONG QuadPart;
} LARGE_INTEGER;
*)
TLARGE_INTEGER = packed record
LowPart: DWORD;
HighPart: longint;
end;
TPARTITION_INFORMATION = packed record
StartingOffset: TLARGE_INTEGER;
PartitionLength: TLARGE_INTEGER;
HiddenSectors: DWORD;
PartitionNumber: DWORD;
PartitionType: WORD; // byte;
BootIndicator: WORD; // boolean;
RecognizedPartition: WORD; //boolean;
RewritePartition: WORD; //boolean;
end;
PTPARTITION_INFORMATION = ^TPARTITION_INFORMATION;
TDRIVE_LAYOUT_INFORMATION = packed record
PartitionCount: DWORD;
Signature: DWORD;
// This shouldn't actually be a 0..255 array, but a variable array instead
PartitionEntry: array [0..255] of TPARTITION_INFORMATION;
end;
PTDRIVE_LAYOUT_INFORMATION = ^TDRIVE_LAYOUT_INFORMATION;
TDEV_BROADCAST_VOLUME = packed record
dbcv_size: DWORD;
dbcv_devicetype: DWORD;
dbcv_reserved: DWORD;
dbcv_unitmask: DWORD;
dbcv_flags: Word;
junk: Word; // Just some padding to bring the struct size up to 20 bytes
end;
PTDEV_BROADCAST_VOLUME = ^TDEV_BROADCAST_VOLUME;
implementation
END.
|
unit HVABankItem;
interface
uses HVA, Voxel, BasicFunctions, SysUtils;
type
THVABankItem = class
private
Counter: longword;
Editable : boolean;
HVA : THVA;
Filename: string;
// Gets
procedure GetFilenameFromHVA;
public
// Constructor and Destructor
constructor Create; overload;
constructor Create(const _Filename: string; _Voxel : PVoxel); overload;
constructor Create(const _HVA: PHVA); overload;
destructor Destroy; override;
// Sets
procedure SetEditable(_value: boolean);
procedure SetFilename(_value: string);
// Gets
function GetEditable: boolean;
function GetFilename: string;
function GetHVA : PHVA;
// Counter
function GetCount : integer;
procedure IncCounter;
procedure DecCounter;
end;
PHVABankItem = ^THVABankItem;
implementation
// Constructors and Destructors
// This one starts a blank voxel.
constructor THVABankItem.Create;
begin
HVA := THVA.Create;
Counter := 1;
Filename := '';
end;
constructor THVABankItem.Create(const _Filename: string; _Voxel : PVoxel);
begin
HVA := THVA.Create(_Filename, _Voxel);
Counter := 1;
Filename := CopyString(_Filename);
end;
constructor THVABankItem.Create(const _HVA: PHVA);
begin
HVA := THVA.Create(_HVA^);
Counter := 1;
GetFilenameFromHVA;
end;
destructor THVABankItem.Destroy;
begin
HVA.Free;
Filename := '';
inherited Destroy;
end;
// Sets
procedure THVABankItem.SetEditable(_value: boolean);
begin
Editable := _value;
end;
procedure THVABankItem.SetFilename(_value: string);
begin
Filename := CopyString(_Value);
end;
// Gets
function THVABankItem.GetEditable: boolean;
begin
Result := Editable;
end;
function THVABankItem.GetFilename: string;
begin
Result := Filename;
end;
function THVABankItem.GetHVA: PHVA;
begin
Result := @HVA;
end;
procedure THVABankItem.GetFilenameFromHVA;
begin
if HVA.p_Voxel <> nil then
begin
Filename := CopyString(HVA.p_Voxel^.Filename);
if Length(Filename) > 2 then
begin
Filename[Length(Filename)-2] := 'h';
Filename[Length(Filename)-1] := 'v';
Filename[Length(Filename)] := 'a';
end;
if not FileExists(Filename) then
Filename := '';
end
else
begin
Filename := '';
end;
end;
// Counter
function THVABankItem.GetCount : integer;
begin
Result := Counter;
end;
procedure THVABankItem.IncCounter;
begin
inc(Counter);
end;
procedure THVABankItem.DecCounter;
begin
Dec(Counter);
end;
end.
|
unit APS_Define;
interface
const
// Initial option
INIT_MANUAL_ID:Longint=$1; //CardId manual by dip switch; Input parameter of APS_initial:Longint= cardId; "MODE" ;
// Board parameter define :Longint=General;
PRB_EMG_LOGIC :Longint=$0; // Board EMG logic
PRB_WDT0_VALUE :Longint=$10; // Set / Get watch dog limit.
PRB_WDT0_COUNTER :Longint=$11; // Reset Wdt / Get Wdt_Count_Value
PRB_WDT0_UNIT :Longint=$12; // wdt_unit
PRB_WDT0_ACTION :Longint=$13; // wdt_action
PRB_TMR0_BASE :Longint=$20; // Set TMR Value
PRB_TMR0_VALUE :Longint=$21; // Get timer int count value
PRB_SYS_TMP_MONITOR :Longint=$30; // Get system temperature monitor data
PRB_CPU_TMP_MONITOR :Longint=$31; // Get CPU temperature monitor data
PRB_AUX_TMP_MONITOR :Longint=$32; // Get AUX temperature monitor data
// PointTable, option
PT_OPT_ABS :Longint=$00000000; // move, absolute
PT_OPT_REL :Longint=$00000001; // move, relative
PT_OPT_LINEAR :Longint=$00000000; // move, linear
PT_OPT_ARC :Longint=$00000004; // move, arc
PT_OPT_FC_CSTP :Longint=$00000000; // signal, command stop (finish condition)
PT_OPT_FC_INP :Longint=$00000010; // signal, in position
PT_OPT_LAST_POS :Longint=$00000020; // last point index
PT_OPT_DWELL :Longint=$00000040; // dwell
PT_OPT_RAPID :Longint=$00000080; // rapid positioning
PT_OPT_NOARC :Longint=$00010000; // do not add arc
PT_OPT_SCUVE :Longint=$00000002; // s-curve
// PTP buffer mode define
PTP_OPT_ABORTING :Longint=$00000000;
PTP_OPT_BUFFERED :Longint=$00001000;
PTP_OPT_BLEND_LOW :Longint=$00002000;
PTP_OPT_BLEND_PREVIOUS :Longint=$00003000;
PTP_OPT_BLEND_NEXT :Longint=$00004000;
PTP_OPT_BLEND_HIGH :Longint=$00005000;
ITP_OPT_ABORT_BLEND :Longint=$00000000;
ITP_OPT_ABORT_FORCE :Longint=$00001000;
ITP_OPT_ABORT_STOP :Longint=$00002000;
ITP_OPT_BUFFERED :Longint=$00003000;
ITP_OPT_BLEND_DEC_EVENT :Longint=$00004000;
ITP_OPT_BLEND_RES_DIST :Longint=$00005000;
ITP_OPT_BLEND_RES_DIST_PERCENT :Longint=$00006000;
//Latch parameter number define. [Only for PCI-8158A]
//////////////////////////////////////
LTC_ENC_IPT_MODE :Longint=$00;
LTC_ENC_EA_INV :Longint=$01;
LTC_ENC_EB_INV :Longint=$02;
LTC_ENC_EZ_CLR_LOGIC :Longint=$03;
LTC_ENC_EZ_CLR_EN :Longint=$04;
LTC_ENC_SIGNAL_FILITER_EN :Longint=$05;
LTC_FIFO_HIGH_LEVEL :Longint=$06;
LTC_SIGNAL_FILITER_EN :Longint=$07;
LTC_SIGNAL_TRIG_LOGIC :Longint=$08;
//////////////////////////////////////
// move option define
OPT_ABSOLUTE :Longint=$00000000;
OPT_RELATIVE :Longint=$00000001;
OPT_WAIT :Longint=$00000100;
PRB_PWM0_MAP_DO :Longint=$110; // Enable & Map PWM0 to Do channels
PRB_PWM1_MAP_DO :Longint=$111; // Enable & Map PWM1 to Do channels
PRB_PWM2_MAP_DO :Longint=$112; // Enable & Map PWM2 to Do channels
PRB_PWM3_MAP_DO :Longint=$113; // Enable & Map PWM3 to Do channels
// Filter parameter number define [Only for PCI-8253/56]
FTR_TYPE_ST0 :Longint=$00; // Station 0 filter type
FTR_FC_ST0 :Longint=$01; // Station 0 filter cutoff frequency
FTR_BW_ST0 :Longint=$02; // Station 0 filter bandwidth
FTR_ENABLE_ST0 :Longint=$03; // Station 0 filter enable/disable
FTR_TYPE_ST1 :Longint=$10; // Station 1 filter type
FTR_FC_ST1 :Longint=$11; // Station 1 filter cutoff frequency
FTR_BW_ST1 :Longint=$12; // Station 1 filter bandwidth
FTR_ENABLE_ST1 :Longint=$13; // Station 1 filter enable/disable
//Following definition for PCI-8254/8
MTS_MDN :Longint=5; // Motion done. 0: In motion, 1: Motion done ( It could be abnormal stop)
MTS_WAIT :Longint=10; // Axis is in waiting state. ( Wait move trigger )
MTS_PTB :Longint=11; // Axis is in point buffer moving. ( When this bit on, MDN and ASTP will be cleared )
MTS_BLD :Longint=17; // Axis (Axes) in blending moving
MTS_PRED :Longint=18; // Pre-distance event, 1: event arrived. The event will be clear when axis start moving
MTS_POSTD :Longint=19; // Post-distance event. 1: event arrived. The event will be clear when axis start moving
MTS_GER :Longint=28; // 1: In geared ( This axis as slave axis and it follow a master specified in axis parameter. )
//Trigger parameter number define. [Only for PCI-8158A]
TIG_LCMP0_SRC :Longint=$00;
TIG_LCMP1_SRC :Longint=$01;
TIG_LCMP2_SRC :Longint=$02;
TIG_LCMP3_SRC :Longint=$03;
TIG_LCMP4_SRC :Longint=$4;
TIG_LCMP5_SRC :Longint=$5;
TIG_LCMP6_SRC :Longint=$6;
TIG_LCMP7_SRC :Longint=$7;
TIG_TCMP0_SRC :Longint=$8;
TIG_TCMP1_SRC :Longint=$9;
TIG_TCMP2_SRC :Longint=$A;
TIG_TCMP3_SRC :Longint=$B;
TIG_TCMP4_SRC :Longint=$C;
TIG_TCMP5_SRC :Longint=$D;
TIG_TCMP6_SRC :Longint=$E;
TIG_TCMP7_SRC :Longint=$F;
TIG_TRG0_EN :Longint=$10;
TIG_TRG1_EN :Longint=$11;
TIG_TRG2_EN :Longint=$12;
TIG_TRG3_EN :Longint=$13;
TIG_TRG4_EN :Longint=$14;
TIG_TRG5_EN :Longint=$15;
TIG_TRG6_EN :Longint=$16;
TIG_TRG7_EN :Longint=$17;
TIG_TRG0_SRC:Longint=$18;
TIG_TRG1_SRC :Longint=$19;
TIG_TRG2_SRC :Longint=$1A;
TIG_TRG3_SRC :Longint=$1B;
TIG_TRG4_SRC :Longint=$1C;
TIG_TRG5_SRC :Longint=$1D;
TIG_TRG6_SRC :Longint=$1E;
TIG_TRG7_SRC :Longint=$1F;
TIG_TRG0_PWD :Longint=$20;
TIG_TRG1_PWD :Longint=$21;
TIG_TRG2_PWD :Longint=$20;
TIG_TRG3_PWD :Longint=$23;
TIG_TRG4_PWD :Longint=$24;
TIG_TRG5_PWD :Longint=$25;
TIG_TRG6_PWD :Longint=$26;
TIG_TRG7_PWD :Longint=$27;
TIG_TRG0_LOGIC :Longint=$28;
TIG_TRG1_LOGIC :Longint=$29;
TIG_TRG2_LOGIC :Longint=$2A;
TIG_TRG3_LOGIC :Longint=$2B;
TIG_TRG4_LOGIC :Longint=$2C;
TIG_TRG5_LOGIC :Longint=$2D;
TIG_TRG6_LOGIC :Longint=$2E;
TIG_TRG7_LOGIC :Longint=$2F;
TIG_TRG0_TGL :Longint=$30;
TIG_TRG1_TGL :Longint=$31;
TIG_TRG2_TGL :Longint=$32;
TIG_TRG3_TGL :Longint=$33;
TIG_TRG4_TGL :Longint=$34;
TIG_TRG5_TGL :Longint=$35;
TIG_TRG6_TGL :Longint=$36;
TIG_TRG7_TGL :Longint=$37;
TIG_PWMTMR0_ITV :Longint=$40;
TIG_PWMTMR1_ITV :Longint=$41;
TIG_PWMTMR2_ITV :Longint=$42;
TIG_PWMTMR3_ITV :Longint=$43;
TIG_PWMTMR4_ITV :Longint=$44;
TIG_PWMTMR5_ITV :Longint=$45;
TIG_PWMTMR6_ITV :Longint=$46;
TIG_PWMTMR7_ITV :Longint=$47;
TIG_TMR0_ITV :Longint=$50;
TIG_TMR0_DIR :Longint=$51;
//Trigger parameter number define. [Only for PCI-8258]
TGR_LCMP0_SRC :Longint=$00;
TGR_LCMP1_SRC :Longint=$01;
TGR_TCMP0_SRC :Longint=$02;
TGR_TCMP1_SRC :Longint=$03;
TGR_TCMP0_DIR :Longint=$04;
TGR_TCMP1_DIR :Longint=$05;
TGR_TRG_EN :Longint=$06;
TGR_TRG0_SRC :Longint=$10;
TGR_TRG1_SRC :Longint=$11;
TGR_TRG2_SRC :Longint=$12;
TGR_TRG3_SRC :Longint=$13;
TGR_TRG0_PWD :Longint=$14;
TGR_TRG1_PWD :Longint=$15;
TGR_TRG2_PWD :Longint=$16;
TGR_TRG3_PWD :Longint=$17;
TGR_TRG0_LOGIC :Longint=$18;
TGR_TRG1_LOGIC :Longint=$19;
TGR_TRG2_LOGIC :Longint=$1A;
TGR_TRG3_LOGIC :Longint=$1B;
TGR_TRG0_TGL :Longint=$1C;
TGR_TRG1_TGL :Longint=$1D;
TGR_TRG2_TGL :Longint=$1E;
TGR_TRG3_TGL :Longint=$1F;
#define TIMR_ITV (0x20)
#define TIMR_DIR (0x21)
#define TIMR_RING_EN (0x22)
#define TIMR_EN (0x23)
//Trigger parameter number define. [Only for DB-8150]
//////////////////////////////////////
TG_PWM0_PULSE_WIDTH :Longint=$00;
TG_PWM1_PULSE_WIDTH :Longint=$01;
TG_PWM0_MODE :Longint=$02;
TG_PWM1_MODE :Longint=$03;
TG_TIMER0_INTERVAL :Longint=$04;
TG_TIMER1_INTERVAL :Longint=$05;
TG_ENC0_CNT_DIR :Longint=$06;
TG_ENC1_CNT_DIR :Longint=$07;
TG_IPT0_MODE :Longint=$08;
TG_IPT1_MODE :Longint=$09;
TG_EZ0_CLEAR_EN :Longint=$0A;
TG_EZ1_CLEAR_EN :Longint=$0B;
TG_EZ0_CLEAR_LOGIC :Longint=$0C;
TG_EZ1_CLEAR_LOGIC :Longint=$0D;
TG_CNT0_SOURCE :Longint=$0E;
TG_CNT1_SOURCE :Longint=$0F;
TG_FTR0_EN :Longint=$10;
TG_FTR1_EN :Longint=$11;
TG_DI_LATCH0_EN :Longint=$12;
TG_DI_LATCH1_EN :Longint=$13;
TG_DI_LATCH0_EDGE :Longint=$14;
TG_DI_LATCH1_EDGE :Longint=$15;
TG_DI_LATCH0_VALUE :Longint=$16;
TG_DI_LATCH1_VALUE :Longint=$17;
TG_TRGOUT_MAP :Longint=$18;
TG_TRGOUT_LOGIC :Longint=$19;
TG_FIFO_LEVEL :Longint=$1A;
TG_PWM0_SOURCE :Longint=$1B;
TG_PWM1_SOURCE :Longint=$1C;
//////////////////////////////////////
//Only for PCI-8254/8, AMP-204/8C
SAMP_COM_POS_F64 :Longint=$10; // Command position
SAMP_FBK_POS_F64 :Longint=$11; // Feedback position
SAMP_CMD_VEL_F64 :Longint=$12; // Command velocity
SAMP_FBK_VEL_F64 :Longint=$13; // Feedback velocity
SAMP_CONTROL_VOL_F64 :Longint=$14; // Control command voltage
SAMP_ERR_POS_F64 :Longint=$15; // Error position
SAMP_PWM_FREQUENCY_F64 :Longint=$18; // PWM frequency (Hz)
SAMP_PWM_DUTY_CYCLE_F64 :Longint=$19; // PWM duty cycle (%)
SAMP_PWM_WIDTH_F64 :Longint=$1A; // PWM width (ns)
SAMP_VAO_COMP_VEL_F64 :Longint=$1B; // Composed velocity for Laser power control (pps)
SAMP_PTBUFF_COMP_VEL_F64 :Longint=$1C; // Composed velocity of point table
SAMP_PTBUFF_COMP_ACC_F64 :Longint=$1D; // Composed acceleration of point table
//Continuous Move
PRA_CONTI_MODE :Longint=$250; // Continuous Mode
PRA_CONTI_BUFF :Longint=$251; // Continuous Buffer
PRA_BIQUAD0_A1 :Longint=$132; // (F64) Biquad filter0 coefficient A1
PRA_BIQUAD0_A2 :Longint=$133; // (F64) Biquad filter0 coefficient A2
PRA_BIQUAD0_B0 :Longint=$134; // (F64) Biquad filter0 coefficient B0
PRA_BIQUAD0_B1 :Longint=$135; // (F64) Biquad filter0 coefficient B1
PRA_BIQUAD0_B2 :Longint=$136; // (F64) Biquad filter0 coefficient B2
PRA_BIQUAD0_DIV :Longint=$137; // (F64) Biquad filter0 divider
PRA_BIQUAD1_A1 :Longint=$138; // (F64) Biquad filter1 coefficient A1
PRA_BIQUAD1_A2 :Longint=$139; // (F64) Biquad filter1 coefficient A2
PRA_BIQUAD1_B0 :Longint=$13A; // (F64) Biquad filter1 coefficient B0
PRA_BIQUAD1_B1 :Longint=$13B; // (F64) Biquad filter1 coefficient B1
PRA_BIQUAD1_B2 :Longint=$13C; // (F64) Biquad filter1 coefficient B2
PRA_BIQUAD1_DIV :Longint=$13D; // (F64) Biquad filter1 divider
PRA_FRIC_GAIN :Longint=$13E; // (F64) Friction voltage compensation
//following only for V2...
PRA_VOLTAGE_MAX :Longint=$9B; // Maximum output limit
PRA_VOLTAGE_MIN :Longint=$9C; // Minimum output limit
PRA_PT_STOP_ENDO :Longint=$32; // Disable do when point table stopping.
PRA_PT_STOP_DO :Longint=$33; // Set do value when point table stopping.
PRA_PWM_OFF :Longint=$34; // Disable specified PWM output when ASTP input signal is active.
PRA_DO_OFF :Longint=$35; // Set DO value when ASTP input signal is active.
PRA_GEAR_MASTER :Longint=$60; // (I32) Select gearing master
PRA_GEAR_ENGAGE_RATE :Longint=$61; // (F64) Gear engage rate
PRA_GEAR_RATIO :Longint=$62; // (F64) Gear ratio
PRA_GANTRY_PROTECT_1 :Longint=$63; // (F64) E-gear gantry mode protection level 1
PRA_GANTRY_PROTECT_2 :Longint=$64; // (F64) E-gear gantry mode protection level 2
MHS_GET_SERVO_OFF_INFO :Longint=$16;
MHS_RESET_SERVO_OFF_INFO :Longint=$17;
MHS_GET_ALL_STATE :Longint=$18;
//following only for V2...
PRA_DIST :Longint=$30; // Move distance
PRA_MAX_VELOCITY :Longint=$31; // Maximum velocity
PRA_SCUR_PERCENTAGE :Longint=$32; // Scurve percentage
PRA_BLENDING_MODE :Longint=$33; // Blending mode
PRA_STOP_MODE :Longint=$34; // Stop mode
PRA_STOP_DELRATE :Longint=$35; // Stop function deceleration rate
PRB_DO_LOGIC :Longint=$14; //DO logic, 0: no invert; 1: invert
PRB_DI_LOGIC :Longint=$15; //DI logic, 0: no invert; 1: invert
PRA_PRE_EVENT_DIST :Longint=$2A; //Pre-event distance
PRA_POST_EVENT_DIST :Longint=$2B; //Post-event distance
PRB_UART_MULTIPLIER :Longint=$40; // Set UART Multiplier
PRB_PSR_MODE :Longint=$90; // Config pulser mode
PRB_PSR_EA_LOGIC :Longint=$91; // Set EA inverted
PRB_PSR_EB_LOGIC :Longint=$92; // Set EB inverted
// Board parameter define (For PCI-8253/56;
PRB_DENOMINATOR :Longint=$80; // Floating number denominator
//PRB_PSR_MODE :Longint=$90; // Config pulser mode
PRB_PSR_ENABLE :Longint=$91; // Enable/disable pulser mode
PRB_BOOT_SETTING :Longint=$100; // Load motion parameter method when DSP boot
// Initial option
INIT_AUTO_CARD_ID :Longint=$0; // (Bit 0) CardId assigned by system, Input parameter of APS_initial( cardId, "MODE" )
INIT_MANUAL_ID :Longint=$1; // (Bit 0) CardId manual by dip switch, Input parameter of APS_initial( cardId, "MODE" )
INIT_PARALLEL_FIXED :Longint=$2; // (Bit 1) Fixed axis indexing mode in Parallel type
INIT_SERIES_FIXED :Longint=$4; // (Bit 2) Fixed axis indexing mode in Series type
INIT_NOT_RESET_DO :Longint=$8; // (Bit 3) HSL Digital output not reset, (DO status will follow the slave status.)
INIT_PARAM_IGNORE :Longint=$0; // (Bit 4-5) Load parameter method - ignore, keep current value
INIT_PARAM_LOAD_DEFAULT :Longint=$10; // (Bit 4-5) Load parameter method - load parameter as default value
INIT_PARAM_LOAD_FLASH :Longint=$20; // (Bit 4-5) Load parameter method - load parameter from flash memory
INIT_MNET_INTERRUPT :Longint=$40; // (Bit 6) Enable MNET interrupt mode. (Support motion interrupt for MotionNet series)
// Board parameter define (For PCI-8392 SSCNET;
PRB_SSC_APPLICATION :Longint=$10000; // Reserved
PRB_SSC_CYCLE_TIME :Longint=$10000; // SSCNET cycle time selection(vaild befor start sscnet;
PRB_PARA_INIT_OPT :Longint=$00020; // Initial boot mode.
// Board parameter define (For DPAC;
PRB_DPAC_DISPLAY_MODE :Longint=$10001; //DPAC Display mode
PRB_DPAC_DI_MODE :Longint=$10002; //Set DI pin modes
PRB_DPAC_THERMAL_MONITOR_NO :Longint=$20001; //DPAC TEST
PRB_DPAC_THERMAL_MONITOR_VALUE :Longint=$20002; //DPAC TEST
// Axis parameter define (General;
PRA_EL_LOGIC :Longint=$00; // EL logic
PRA_ORG_LOGIC :Longint=$01; // ORG logic
PRA_EL_MODE :Longint=$02; // EL stop mode
PRA_MDM_CONDI :Longint=$03; // Motion done condition
PRA_EL_EXCHANGE :Longint=$04; // PEL; MEL exchange enable
PRA_ALM_LOGIC :Longint=$04; // ALM logic [PCI-8253/56 only]
PRA_ZSP_LOGIC :Longint=$05; // ZSP logic [PCI-8253/56 only]
PRA_EZ_LOGIC :Longint=$06; // EZ logic [PCI-8253/56 only]
PRA_STP_DEC :Longint=$07; // Stop deceleration
PRA_SPEL_EN :Longint=$08; // SPEL Enable
PRA_SMEL_EN :Longint=$09; // SMEL Enable
PRA_EFB_POS0 :Longint=$0A; // EFB position 0
PRA_EFB_POS1 :Longint=$0B; // EFB position 1
PRA_EFB_CONDI0 :Longint=$0C; // EFB position 0 condition
PRA_EFB_CONDI1 :Longint=$0D; // EFB position 1 condition
PRA_EFB_SRC0 :Longint=$0E; // EFB position 0 source
PRA_EFB_SRC1 :Longint=$0F; // EFB position 1 source
PRA_HOME_MODE :Longint=$10; // home mode
PRA_HOME_DIR :Longint=$11; // homing direction
PRA_HOME_CURVE :Longint=$12; // homing curve parten(T or s curve;
PRA_HOME_ACC :Longint=$13; // Acceleration deceleration rate
PRA_HOME_VS :Longint=$14; // homing start velocity
PRA_HOME_VM :Longint=$15; // homing max velocity
PRA_HOME_VA :Longint=$16; // homing approach velocity [PCI-8253/56 only]
PRA_HOME_EZA :Longint=$18; // EZ alignment enable
PRA_HOME_VO :Longint=$19; // Homing leave ORG velocity
PRA_HOME_OFFSET :Longint=$1A; // The escape pulse amounts(Leaving home by position;
PRA_HOME_POS :Longint=$1B; // The position from ORG [PCI-8254/58 only]
PRA_CURVE :Longint=$20; // Move curve pattern
PRA_ACC :Longint=$21; // Move acceleration
PRA_DEC :Longint=$22; // Move deceleration
PRA_VS :Longint=$23; // Move start velocity
PRA_VE :Longint=$25; // Move end velocity
PRA_SACC :Longint=$26; // Scrve acceleration
PRA_SDEC :Longint=$27; // Scrve deceleration
PRA_ACC_SR :Longint=$28; // S curve ratio in acceleration( S curve with linear acceleration)
PRA_DEC_SR :Longint=$29; // S curve ratio in deceleration( S curve with linear deceleration)
_PRA_ENCODER_FILTER :Longint=$83; // (I32)
PRA_ENCODER_DIR :Longint=$85; // (I32)
PRA_POS_UNIT_FACTOR :Longint=$86; // (F64) position unit factor setting
PRA_JG_MODE :Longint=$40; // Jog mode
PRA_JG_DIR :Longint=$41; // Jog move direction
PRA_JG_CURVE :Longint=$42; // Jog curve parten(T or s curve;
PRA_JG_ACC :Longint=$43; // Jog move acceleration
PRA_JG_DEC :Longint=$44; // Jog move deceleration
PRA_JG_VM :Longint=$45; // Jog move max velocity
PRA_JG_STEP :Longint=$46; // Jog offset (For step mode;
PRA_JG_DELAY :Longint=$47; // Jog delay (For step mode;
PRA_JG_MAP_DI_EN :Longint=$48; // (I32) Enable Digital input map to jog command signal
PRA_JG_P_JOG_DI :Longint=$49; // (I32) Mapping configuration for positive jog and digital input.
PRA_JG_N_JOG_DI :Longint=$4A; // (I32) Mapping configuration for negative jog and digital input.
PRA_JG_JOG_DI :Longint=$4B; // (I32) Mapping configuration for jog and digital input.
PRA_MDN_DELAY :Longint=$50; // NSTP delay setting
PRA_SINP_WDW :Longint=$51; // Soft INP window setting
PRA_SINP_STBL :Longint=$52; // Soft INP stable cycle
PRA_SERVO_LOGIC :Longint=$53; // SERVO logic
// Axis parameter define (For PCI-8253/56;
PRA_PLS_IPT_MODE :Longint=$80; // Pulse input mode setting
PRA_PLS_OPT_MODE :Longint=$81; // Pulse output mode setting
PRA_MAX_E_LIMIT :Longint=$82; // Maximum encoder count limit
PRA_ENC_FILTER :Longint=$83; // Encoder filter
PRA_EGEAR :Longint=$84; // E-Gear ratio
PRA_ENCODER_DIR :Longint=$85; // Encoder direction
PRA_POS_UNIT_FACTOR :Longint=$86; // position unit factor setting
PRA_KP_GAIN :Longint=$90; // PID controller Kp gain
PRA_KI_GAIN :Longint=$91; // PID controller Ki gain
PRA_KD_GAIN :Longint=$92; // PID controller Kd gain
PRA_KFF_GAIN :Longint=$93; // Feed forward Kff gain
PRA_KVGTY_GAIN :Longint=$94; // Gantry controller Kvgty gain
PRA_KPGTY_GAIN :Longint=$95; // Gantry controller Kpgty gain
PRA_IKP_GAIN :Longint=$96; // PID controller Kp gain in torque mode
PRA_IKI_GAIN :Longint=$97; // PID controller Ki gain in torque mode
PRA_IKD_GAIN :Longint=$98; // PID controller Kd gain in torque mode
PRA_IKFF_GAIN :Longint=$99; // Feed forward Kff gain in torque mode
PRA_M_INTERFACE :Longint=$100; // Motion interface
PRA_M_VOL_RANGE :Longint=$110; // Motor voltage input range
PRA_M_MAX_SPEED :Longint=$111; // Motor maximum speed
PRA_M_ENC_RES :Longint=$112; // Motor encoder resolution
PRA_V_OFFSET :Longint=$120; // Voltage offset
PRA_DZ_LOW :Longint=$121; // Dead zone low side
PRA_DZ_UP :Longint=$122; // Dead zone up side
PRA_SAT_LIMIT :Longint=$123; // Voltage saturation output limit
PRA_ERR_C_LEVEL :Longint=$124; // Error counter check level
PRA_V_INVERSE :Longint=$125; // Output voltage inverse
PRA_DZ_VAL :Longint=$126; // Dead zone output value
PRA_IW_MAX :Longint=$127; // Integral windup maximum value
PRA_IW_MIN :Longint=$128; // Integral windup minimum value
PRA_BKL_DIST :Longint=$129; // Backlash distance
PRA_BKL_CNSP :Longint=$12a; // Backlash consumption
PRA_INTEGRAL_LIMIT :Longint=$12B; // (I32) Integral limit
PRA_D_SAMPLE_TIME :Longint=$12C; // (I32) Derivative Sample Time
PRA_PSR_LINK :Longint=$130; // Connect pulser number
PRA_PSR_RATIO :Longint=$131; // Set pulser ratio
PRA_DA_TYPE :Longint=$140; // DAC output type
PRA_CONTROL_MODE :Longint=$141; // Closed loop control mode
// Axis parameter define (For PCI-8154/58;
// Input/Output Mode
PRA_PLS_IPT_LOGIC :Longint=$200; //Reverse pulse input counting
PRA_FEEDBACK_SRC :Longint=$201; //Select feedback conter
//IO Config
PRA_ALM_MODE :Longint=$210; //ALM Mode
PRA_INP_LOGIC :Longint=$211; //INP Logic
PRA_SD_EN :Longint=$212; //SD Enable -- Bit 8
PRA_SD_MODE :Longint=$213; //SD Mode
PRA_SD_LOGIC :Longint=$214; //SD Logic
PRA_SD_LATCH :Longint=$215; //SD Latch
PRA_ERC_MODE :Longint=$216; //ERC Mode
PRA_ERC_LOGIC :Longint=$217; //ERC logic
PRA_ERC_LEN :Longint=$218; //ERC pulse width
PRA_CLR_MODE :Longint=$219; //CLR Mode
PRA_CLR_TARGET :Longint=$21A; //CLR Target counter
PRA_PIN_FLT :Longint=$21B; //EA/EB Filter Enable
PRA_INP_MODE :Longint=$21C; //INP Mode
PRA_LTC_LOGIC :Longint=$21D; //LTC LOGIC
PRA_SOFT_PLIMIT :Longint=$21E; //SOFT PLIMIT
PRA_SOFT_MLIMIT :Longint=$21F; //SOFT MLIMIT
PRA_SOFT_LIMIT_EN :Longint=$220; //SOFT ENABLE
PRA_BACKLASH_PULSE :Longint=$221; //BACKLASH PULSE
PRA_BACKLASH_MODE :Longint=$222; //BACKLASH MODE
PRA_LTC_SRC :Longint=$223; //LTC Source
PRA_LTC_DEST :Longint=$224; //LTC Destination
PRA_LTC_DATA :Longint=$225; //Get LTC DATA
PRA_GCMP_EN :Longint=$226; // CMP Enable
PRA_GCMP_POS :Longint=$227; // Get CMP position
PRA_GCMP_SRC :Longint=$228; // CMP source
PRA_GCMP_ACTION :Longint=$229; // CMP Action
PRA_GCMP_STS :Longint=$22A; // CMP Status
PRA_VIBSUP_RT :Longint=$22B; // Vibration Reverse Time
PRA_VIBSUP_FT :Longint=$22C; // Vibration Forward Time
PRA_LTC_DATA_SPD :Longint=$22D; // Choose latch data for current speed or error position
PRA_GPDO_SEL :Longint=$230; //Select DO/CMP Output mode
PRA_GPDI_SEL :Longint=$231; //Select DO/CMP Output mode
PRA_GPDI_LOGIC :Longint=$232; //Set gpio input logic
PRA_RDY_LOGIC :Longint=$233; //RDY logic
//Fixed Speed
PRA_SPD_LIMIT :Longint=$240; // Set Fixed Speed
PRA_MAX_ACCDEC :Longint=$241; // Get max acceleration by fixed speed
PRA_MIN_ACCDEC :Longint=$242; // Get max acceleration by fixed speed
PRA_ENABLE_SPD :Longint=$243; // Disable/Enable Fixed Speed only for HSL-4XMO.
// PCI-8144 axis parameter define
PRA_CMD_CNT_EN :Longint=$10000;
PRA_MIO_SEN :Longint=$10001;
PRA_START_STA :Longint=$10002;
PRA_SPEED_CHN :Longint=$10003;
PRA_ORG_STP :Longint=$1A;
// Axis parameter define (For PCI-8392 SSCNET;
PRA_SSC_SERVO_PARAM_SRC :Longint=$10000; //Servo parameter source
PRA_SSC_SERVO_ABS_POS_OPT :Longint=$10001; //Absolute position system option
PRA_SSC_SERVO_ABS_CYC_CNT :Longint=$10002; //Absolute cycle counter of servo driver
PRA_SSC_SERVO_ABS_RES_CNT :Longint=$10003; //Absolute resolution counter of servo driver
PRA_SSC_TORQUE_LIMIT_P :Longint=$10004; //Torque limit positive (0.1%;
PRA_SSC_TORQUE_LIMIT_N :Longint=$10005; //Torque limit negative (0.1%;
PRA_SSC_TORQUE_CTRL :Longint=$10006; //Torque control
PRA_SSC_RESOLUTION :Longint=$10007; //resolution (E-gear)
PRA_SSC_GMR :Longint=$10008; //resolution (New E-gear)
PRA_SSC_GDR :Longint=$10009; //resolution (New E-gear)
// Sampling parameter define
SAMP_PA_RATE :Longint=$0; //Sampling rate
SAMP_PA_EDGE :Longint=$2; //Edge select
SAMP_PA_LEVEL :Longint=$3; //Level select
SAMP_PA_TRIGCH :Longint=$5; //Select trigger channel
SAMP_PA_SEL :Longint=$6;
SAMP_PA_SRC_CH0 :Longint=$10; //Sample source of channel 0
SAMP_PA_SRC_CH1 :Longint=$11; //Sample source of channel 1
SAMP_PA_SRC_CH2 :Longint=$12; //Sample source of channel 2
SAMP_PA_SRC_CH3 :Longint=$13; //Sample source of channel 3
// Sampling source
SAMP_AXIS_MASK :Longint=$F00;
SAMP_PARAM_MASK :Longint=$FF;
SAMP_COM_POS :Longint=$00; //command position
SAMP_FBK_POS :Longint=$01; //feedback position
SAMP_CMD_VEL :Longint=$02; //command velocity
SAMP_FBK_VEL :Longint=$03; //feedback velocity
SAMP_MIO :Longint=$04; //motion IO
SAMP_MSTS :Longint=$05; //motion status
SAMP_MSTS_ACC :Longint=$06; //motion status acc
SAMP_MSTS_MV :Longint=$07; //motion status at max velocity
SAMP_MSTS_DEC :Longint=$08; //motion status at dec
SAMP_MSTS_CSTP :Longint=$09; //motion status CSTP
SAMP_MSTS_NSTP :Longint=$0A; //motion status NSTP
SAMP_MIO_INP :Longint=$0B; //motion status INP
SAMP_MIO_ZERO :Longint=$0C; //motion status ZERO
SAMP_MIO_ORG :Longint=$0D; //motion status OGR
SAMP_SSC_MON_0 :Longint=$10; // SSCNET servo monitor ch0
SAMP_SSC_MON_1 :Longint=$11; // SSCNET servo monitor ch1
SAMP_SSC_MON_2 :Longint=$12; // SSCNET servo monitor ch2
SAMP_SSC_MON_3 :Longint=$13; // SSCNET servo monitor ch3
SAMP_CONTROL_VOL :Longint=$20; //
SAMP_GTY_DEVIATION :Longint=$21;
SAMP_ENCODER_RAW :Longint=$22;
SAMP_ERROR_COUNTER :Longint=$23;
//FieldBus parameter define
PRF_COMMUNICATION_TYPE :Longint=$00;// FiledBus Communication Type(Full/half duplex;
PRF_TRANSFER_RATE :Longint=$01;// FiledBus Transfer Rate
PRF_HUB_NUMBER :Longint=$02;// FiledBus Hub Number
PRF_INITIAL_TYPE :Longint=$03;// FiledBus Initial Type(Clear/Reserve Do area;
PRF_CHKERRCNT_LAYER :Longint=$04;// Set the check error count layer.
//Gantry parameter number define [Only for PCI-8392; PCI-8253/56]
GANTRY_MODE :Longint=$0;
GENTRY_DEVIATION :Longint=$1;
GENTRY_DEVIATION_STP :Longint=$2;
// Filter parameter number define [Only for PCI-8253/56]
FTR_TYPE :Longint=$00; // Filter type
FTR_FC :Longint=$01; // Filter cutoff frequency
FTR_BW :Longint=$02; // Filter bandwidth
FTR_ENABLE :Longint=$03; // Filter enable/disable
// Device name define
DEVICE_NAME_NULL :Longint=$FFFF;
DEVICE_NAME_PCI_8392 :Longint=0;
DEVICE_NAME_PCI_825X :Longint=1;
DEVICE_NAME_PCI_8154 :Longint=2;
DEVICE_NAME_PCI_785X :Longint=3;
DEVICE_NAME_PCI_8158 :Longint=4;
DEVICE_NAME_PCI_7856 :Longint=5;
DEVICE_NAME_ISA_DPAC1000 :Longint=6;
DEVICE_NAME_ISA_DPAC3000 :Longint=7;
DEVICE_NAME_PCI_8144 :Longint=8;
DEVICE_NAME_PCI_8258 :Longint=9;
DEVICE_NAME_PCI_8102 :Longint=10;
DEVICE_NAME_PCI_V8258 :Longint=11;
DEVICE_NAME_PCI_V8254 :Longint=12;
DEVICE_NAME_PCI_8158A :Longint=13;
DEVICE_NAME_AMP_82548 :Longint=14;
///////////////////////////////////////////////
// HSL Slave module definition
///////////////////////////////////////////////
SLAVE_NAME_UNKNOWN :Longint=$000;
SLAVE_NAME_HSL_DI32 :Longint=$100;
SLAVE_NAME_HSL_DO32 :Longint=$101;
SLAVE_NAME_HSL_DI16DO16 :Longint=$102;
SLAVE_NAME_HSL_AO4 :Longint=$103;
SLAVE_NAME_HSL_AI16AO2_VV :Longint=$104;
SLAVE_NAME_HSL_AI16AO2_AV :Longint=$105;
SLAVE_NAME_HSL_DI16UL :Longint=$106;
SLAVE_NAME_HSL_DI16RO8 :Longint=$107;
SLAVE_NAME_HSL_4XMO :Longint=$108;
SLAVE_NAME_HSL_DI16_UCT :Longint=$109;
SLAVE_NAME_HSL_DO16_UCT :Longint=$10A;
SLAVE_NAME_HSL_DI8DO8 :Longint=$10B;
///////////////////////////////////////////////
// MNET Slave module definition
///////////////////////////////////////////////
SLAVE_NAME_MNET_1XMO :Longint=$200;
SLAVE_NAME_MNET_4XMO :Longint=$201;
SLAVE_NAME_MNET_4XMO_C :Longint=$202;
//Trigger parameter number define. [Only for PCI-8253/56]
TG_LCMP0_SRC :Longint=$00;
TG_LCMP1_SRC :Longint=$01;
TG_TCMP0_SRC :Longint=$02;
TG_TCMP1_SRC :Longint=$03;
TG_LCMP0_EN :Longint=$04;
TG_LCMP1_EN :Longint=$05;
TG_TCMP0_EN :Longint=$06;
TG_TCMP1_EN :Longint=$07;
TG_TRG0_SRC :Longint=$10;
TG_TRG1_SRC :Longint=$11;
TG_TRG2_SRC :Longint=$12;
TG_TRG3_SRC :Longint=$13;
TG_TRG0_PWD :Longint=$14;
TG_TRG1_PWD :Longint=$15;
TG_TRG2_PWD :Longint=$16;
TG_TRG3_PWD :Longint=$17;
TG_TRG0_CFG :Longint=$18;
TG_TRG1_CFG :Longint=$19;
TG_TRG2_CFG :Longint=$1A;
TG_TRG3_CFG :Longint=$1B;
TMR_ITV :Longint=$20;
TMR_EN :Longint=$21;
//Trigger parameter number define. [Only for MNET-4XMO-C]
TG_CMP0_SRC :Longint=$00;
TG_CMP1_SRC :Longint=$01;
TG_CMP2_SRC :Longint=$02;
TG_CMP3_SRC :Longint=$03;
TG_CMP0_EN :Longint=$04;
TG_CMP1_EN :Longint=$05;
TG_CMP2_EN :Longint=$06;
TG_CMP3_EN :Longint=$07;
TG_CMP0_TYPE :Longint=$08;
TG_CMP1_TYPE :Longint=$09;
TG_CMP2_TYPE :Longint=$0A;
TG_CMP3_TYPE :Longint=$0B;
TG_CMPH_EN :Longint=$0C;
TG_CMPH_DIR_EN :Longint=$0D;
TG_CMPH_DIR :Longint=$0E;
//TG_TRG0_SRC :Longint=$10;
//TG_TRG1_SRC :Longint=$11;
//TG_TRG2_SRC :Longint=$12;
//TG_TRG3_SRC :Longint=$13;
//TG_TRG0_PWD :Longint=$14;
//TG_TRG1_PWD :Longint=$15;
//TG_TRG2_PWD :Longint=$16;
//TG_TRG3_PWD :Longint=$17;
//TG_TRG0_CFG :Longint=$18;
//TG_TRG1_CFG :Longint=$19;
//TG_TRG2_CFG :Longint=$1A;
//TG_TRG3_CFG :Longint=$1B;
TG_ENCH_CFG :Longint=$20;
TG_TRG0_CMP_DIR :Longint=$21;
TG_TRG1_CMP_DIR :Longint=$22;
TG_TRG2_CMP_DIR :Longint=$23;
TG_TRG3_CMP_DIR :Longint=$24;
// Motion IO status bit number define.
MIO_ALM :Longint=0; // Servo alarm.
MIO_PEL :Longint=1; // Positive end limit.
MIO_MEL :Longint=2; // Negative end limit.
MIO_ORG :Longint=3; // ORG :Longint=Home;
MIO_EMG :Longint=4; // Emergency stop
MIO_EZ :Longint=5; // EZ.
MIO_INP :Longint=6; // In position.
MIO_SVON :Longint=7; // Servo on signal.
MIO_RDY :Longint=8; // Ready.
MIO_WARN :Longint=9; // Warning.
MIO_ZSP :Longint=10; // Zero speed.
MIO_SPEL :Longint=11; // Soft positive end limit.
MIO_SMEL :Longint=12; // Soft negative end limit.
MIO_TLC :Longint=13; // Torque is limited by torque limit value.
MIO_ABSL :Longint=14; // Absolute position lost.
MIO_STA :Longint=15; // External start signal.
MIO_PSD :Longint=16; // Positive slow down signal
MIO_MSD :Longint=17; // Negative slow down signal
// Motion status bit number define.
MTS_CSTP :Longint=0; // Command stop signal.
MTS_VM :Longint=1; // At maximum velocity.
MTS_ACC :Longint=2; // In acceleration.
MTS_DEC :Longint=3; // In deceleration.
MTS_DIR :Longint=4; // :Longint=Last;Moving direction.
MTS_NSTP :Longint=5; // Normal stop:Longint=Motion done;.
MTS_HMV :Longint=6; // In home operation.
MTS_SMV :Longint=7; // Single axis move:Longint= relative; absolute; velocity move;.
MTS_LIP :Longint=8; // Linear interpolation.
MTS_CIP :Longint=9; // Circular interpolation.
MTS_VS :Longint=10; // At start velocity.
MTS_PMV :Longint=11; // Point table move.
MTS_PDW :Longint=12; // Point table dwell move.
MTS_PPS :Longint=13; // Point table pause state.
MTS_SLV :Longint=14; // Slave axis move.
MTS_JOG :Longint=15; // Jog move.
MTS_ASTP :Longint=16; // Abnormal stop.
MTS_SVONS :Longint=17; // Servo off stopped.
MTS_EMGS :Longint=18; // EMG / SEMG stopped.
MTS_ALMS :Longint=19; // Alarm stop.
MTS_WANS :Longint=20; // Warning stopped.
MTS_PELS :Longint=21; // PEL stopped.
MTS_MELS :Longint=22; // MEL stopped.
MTS_ECES :Longint=23; // Error counter check level reaches and stopped.
MTS_SPELS :Longint=24; // Soft PEL stopped.
MTS_SMELS :Longint=25; // Soft MEL stopped.
MTS_STPOA :Longint=26; // Stop by others axes.
MTS_GDCES :Longint=27; // Gantry deviation error level reaches and stopped.
MTS_GTM :Longint=28; // Gantry mode turn on.
MTS_PAPB :Longint=29; // Pulsar mode turn on.
// Motion IO status bit value define.
MIO_ALM_V :Longint=$1; // Servo alarm.
MIO_PEL_V :Longint=$2; // Positive end limit.
MIO_MEL_V :Longint=$4; // Negative end limit.
MIO_ORG_V :Longint=$8; // ORG :Longint=Home;.
MIO_EMG_V :Longint=$10; // Emergency stop.
MIO_EZ_V :Longint=$20; // EZ.
MIO_INP_V :Longint=$40; // In position.
MIO_SVON_V :Longint=$80; // Servo on signal.
MIO_RDY_V :Longint=$100; // Ready.
MIO_WARN_V :Longint=$200; // Warning.
MIO_ZSP_V :Longint=$400; // Zero speed.
MIO_SPEL_V :Longint=$800; // Soft positive end limit.
MIO_SMEL_V :Longint=$1000; // Soft negative end limit.
MIO_TLC_V :Longint=$2000; // Torque is limited by torque limit value.
MIO_ABSL_V :Longint=$4000; // Absolute position lost.
MIO_STA_V :Longint=$8000; // External start signal.
MIO_PSD_V :Longint=$10000; // Positive slow down signal.
MIO_MSD_V :Longint=$20000; // Negative slow down signal.
// Motion status bit value define.
MTS_CSTP_V :Longint=$1; // Command stop signal.
MTS_VM_V :Longint=$2; // At maximum velocity.
MTS_ACC_V :Longint=$4; // In acceleration.
MTS_DEC_V :Longint=$8; // In deceleration.
MTS_DIR_V :Longint=$10; // :Longint=Last;Moving direction.
MTS_NSTP_V :Longint=$20; // Normal stop:Longint=Motion done;.
MTS_HMV_V :Longint=$40; // In home operation.
MTS_SMV_V :Longint=$80; // Single axis move:Longint= relative; absolute; velocity move;.
MTS_LIP_V :Longint=$100; // Linear interpolation.
MTS_CIP_V :Longint=$200; // Circular interpolation.
MTS_VS_V :Longint=$400; // At start velocity.
MTS_PMV_V :Longint=$800; // Point table move.
MTS_PDW_V :Longint=$1000; // Point table dwell move.
MTS_PPS_V :Longint=$2000; // Point table pause state.
MTS_SLV_V :Longint=$4000; // Slave axis move.
MTS_JOG_V :Longint=$8000; // Jog move.
MTS_ASTP_V :Longint=$10000; // Abnormal stop.
MTS_SVONS_V :Longint=$20000; // Servo off stopped.
MTS_EMGS_V :Longint=$40000; // EMG / SEMG stopped.
MTS_ALMS_V :Longint=$80000; // Alarm stop.
MTS_WANS_V :Longint=$100000; // Warning stopped.
MTS_PELS_V :Longint=$200000; // PEL stopped.
MTS_MELS_V :Longint=$400000; // MEL stopped.
MTS_ECES_V :Longint=$800000; // Error counter check level reaches and stopped.
MTS_SPELS_V :Longint=$1000000; // Soft PEL stopped.
MTS_SMELS_V :Longint=$2000000; // Soft MEL stopped.
MTS_STPOA_V :Longint=$4000000; // Stop by others axes.
MTS_GDCES_V :Longint=$8000000; // Gantry deviation error level reaches and stopped.
MTS_GTM_V :Longint=$10000000; // Gantry mode turn on.
MTS_PAPB_V :Longint=$20000000; // Pulsar mode turn on.
//Error Code define
ERR_NoError :Longint=0; //No Error
ERR_OSVersion :Longint=-1; // Operation System type mismatched
ERR_OpenDriverFailed :Longint=-2; // Open device driver failed - Create driver interface failed
ERR_InsufficientMemory :Longint=-3; // System memory insufficiently
ERR_DeviceNotInitial :Longint=-4; // Cards not be initialized
ERR_NoDeviceFound :Longint=-5; // Cards not found(No card in your system)
ERR_CardIdDuplicate :Longint=-6; // Cards' ID is duplicated.
ERR_DeviceAlreadyInitialed :Longint=-7; // Cards have been initialed
ERR_InterruptNotEnable :Longint=-8; // Cards' interrupt events not enable or not be initialized
ERR_TimeOut :Longint=-9; // Function time out
ERR_ParametersInvalid :Longint=-10; // Function input parameters are invalid
ERR_SetEEPROM :Longint=-11; // Set data to EEPROM (or nonvolatile memory) failed
ERR_GetEEPROM :Longint=-12; // Get data from EEPROM (or nonvolatile memory) failed
ERR_FunctionNotAvailable :Longint=-13; // Function is not available in this step, The device is not support this function or Internal process failed
ERR_FirmwareError :Longint=-14; // Firmware error, please reboot the system
ERR_CommandInProcess :Longint=-15; // Previous command is in process
ERR_AxisIdDuplicate :Longint=-16; // Axes' ID is duplicated.
ERR_ModuleNotFound :Longint=-17; // Slave module not found.
ERR_InsufficientModuleNo :Longint=-18; // System ModuleNo insufficiently
ERR_HandShakeFailed :Longint=-19; // HandSake with the DSP out of time.
ERR_FILE_FORMAT :Longint=-20; // Config file format error.(cannot be parsed)
ERR_ParametersReadOnly :Longint=-21; // Function parameters read only.
ERR_DistantNotEnough :Longint=-22; // Distant is not enough for motion.
ERR_FunctionNotEnable :Longint=-23; // Function is not enabled.
ERR_ServerAlreadyClose :Longint=-24; // Server already closed.
ERR_DllNotFound :Longint=-25; // Related dll is not found, not in correct path.
ERR_TrimDAC_Channel :Longint=-26;
ERR_Satellite_Type :Longint=-27;
ERR_Over_Voltage_Spec :Longint=-28;
ERR_Over_Current_Spec :Longint=-29;
ERR_SlaveIsNotAI :Longint=-30;
ERR_Over_AO_Channel_Scope :Longint=-31;
ERR_DllFuncFailed :Longint=-32; // Failed to invoke dll function. Extension Dll version is wrong.
ERR_FeederAbnormalStop :Longint=-33; //Feeder abnormal stop, External stop or feeding stop
ERR_Read_ModuleType_Dismatch :Longint=-33;
ERR_Win32Error :Longint=-1000; // No such INT number, or WIN32_API error, contact with ADLINK's FAE staff.
ERR_DspStart :Longint=-2000; // The base for DSP error
implementation
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.