text stringlengths 14 6.51M |
|---|
{-----------------------------------------------------------------------------
The contents of this file are subject to the GNU General Public 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.gnu.org/copyleft/gpl.html
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for
the specific language governing rights and limitations under the License.
The Initial Developer of the Original Code is Michael Elsdörfer.
All Rights Reserved.
$Id$
You may retrieve the latest version of this file at the Corporeal
Website, located at http://www.elsdoerfer.info/corporeal
Known Issues:
-----------------------------------------------------------------------------}
unit VersionInfo;
// Depending on build mode, retrieve the actual version info from an include.
interface
uses
SysUtils;
{
What we expect from the include file:
// Format: MAJOR.MINOR-STRING.BUILD
// Example: 1.5-rc2.434
// -1 values will be ignored
APP_VERSION_MAJOR = -1;
APP_VERSION_MINOR = -1;
APP_VERSION_IDENT = 'ide-build';
APP_VERSION_BUILD = -1;
// A codename for the version, e.g. "Longhorn"
APP_VERSION_NAME = '';
}
{$IFDEF AUTOMATED_BUILD}
{$INCLUDE VersionInfoBuild.inc}
{$ELSE}
{$INCLUDE VersionInfoIDE.inc}
{$ENDIF}
const
// As the minor version is not simply a counter, we need to specify a
// precision, which at the same time limits the maximum number of the
// minor version. E.g., if this is set to "2", then a minor version of "1"
// actually means "x.01", and "x.1" would be represented by a minor version
// of "10". "3" digits would mean that a minor version of 1 actually means
// "x.001". It is possible to change this number during the application
// lifecycle, but then the meaning of all previously used version numbers
// will change, so bear that in mind.
MINOR_VERSION_DIGITS = 2;
type
TVersionStringFormat = (
vsfFull, // major/minor/ident/build
vsfLong, // major/minor/ident
vsfShort // major/minor
);
function MakeVersionString(AVersionFormat: TVersionStringFormat): string;
implementation
{$WARNINGS off} // Prevent "Comparison always evaluates to True" for constant comparisons
function MakeVersionString(AVersionFormat: TVersionStringFormat): string;
var
MinorStr: string;
I: Integer;
begin
Result := '';
// Start off with major version
if (APP_VERSION_MAJOR<>-1) then
begin
Result := Result+IntToStr(APP_VERSION_MAJOR);
// No minor version without a major on
if (APP_VERSION_MINOR<>-1) then
begin
// format minor version: add 0's at beginning, remove trailing ones
MinorStr := Format('%.*d', [MINOR_VERSION_DIGITS, APP_VERSION_MINOR]);
for I := Length(MinorStr) downto 2 do // downto 2 - never remove first char
if MinorStr[I]='0' then Delete(MinorStr, I, 1)
else Break;
Result := Result+'.'+MinorStr;
end;
end;
// Ident
if (APP_VERSION_IDENT<>'') then
begin
if Result <> '' then Result := Result+'-';
Result := Result+APP_VERSION_IDENT;
end;
// Add build number
if (APP_VERSION_BUILD>0) then
Result := Result+'.'+IntToStr(APP_VERSION_BUILD);
end;
{$WARNINGS on}
end.
|
unit UnitTraitement;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, CheckLst, ComCtrls, UnitVariables, strUtils,
ExtCtrls, ZipForge, DBTables, Hydras;
type
TFormTraitement = class(TForm)
procedure FormCreate(Sender: TObject);
procedure SearchFiles;
function ZipFiles : Boolean;
procedure Lancer(lst: TStrings; modeAuto: Boolean);
procedure Stop(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
private
one: boolean;
compteur : Integer;
tampon : Integer;
schema : string;
Domain : string;
ligne : string;
myFile : TextFile;
scriptSql : TStringList;
ZipListFiles : TStringList;
procedure LogLine(Indent: Integer; AMessage: string);
function getDomainFromFileName(enTry: string): Boolean;
function getDomainFromFilePath(enTry: string): Boolean;
function getSchemaFromDomain(enTry: string): Boolean;
function importCsv(Filename: string; AUTO : Boolean) : Boolean;
procedure sortir(Amessage: string);
public
procedure AddFiles(entry : Tstrings);
procedure RefreshInfos(newState: TProcessType);
{ Public declarations }
end;
var
FormTraitement: TFormTraitement;
implementation
uses UnitConfiguration, UnitDataModuleDatas, UnitExport;
{$R *.dfm}
procedure TFormTraitement.LogLine(Indent: Integer; AMessage: string);
Begin
export.LogLine(Indent, AMessage)
End;
procedure TFormTraitement.AddFiles(entry : Tstrings);
var
i : integer;
Begin
export.CheckListBoxLog.Items := entry;
For i := 0 To export.CheckListBoxLog.Count - 1
Do export.CheckListBoxLog.Checked[i] := true;
End;
procedure TFormTraitement.SearchFiles;
var
i : integer;
Begin
export.CheckListBoxLog.items.Clear;
FindFilePattern(export.CheckListBoxLog.items, FormConfiguration.DirectoryListBoxCsv.Directory, '.csv', True);
For i := 0 To export.CheckListBoxLog.Count - 1
Do export.CheckListBoxLog.Checked[i] := true;
one := export.CheckListBoxLog.Count > 0;
PROCESS := tpWait;
End;
procedure TFormTraitement.FormCreate(Sender: TObject);
Begin
If FOLDER_MONITORING.IsActive
Then FOLDER_MONITORING.Deactivate;
RefreshInfos(tpNone);
ZipListFiles := TStringList.Create;
End;
procedure TFormTraitement.FormClose(Sender: TObject; var Action: TCloseAction);
begin
RefreshInfos(tpNone);
export.ProgressBar.Visible := False;
ZipListFiles.Free;
end;
procedure TFormTraitement.RefreshInfos(newState: TProcessType);
Procedure CacheTout;
Begin
export.BitBtnStop.Visible := False;
export.BitBtnLancer.Visible := False;
End;
Begin
PROCESS := newState;
Case PROCESS of
tpInit : Begin
export.StatusBarMain.Panels[1].Text := 'Init';
CacheTout;
export.BitBtnStop.Visible := True;
export.BitBtnStop.SetFocus;
End;
tpStart : Begin
export.StatusBarMain.Panels[1].Text := 'Start';
CacheTout;
export.BitBtnStop.Visible := True;
export.BitBtnStop.SetFocus;
End;
tpRun : Begin
export.StatusBarMain.Panels[1].Text := 'Run';
FormTraitement.caption := _PROCESS_ACTIVE;
CacheTout;
export.BitBtnStop.Visible := export.PageControlMain.ActivePage = export.TabSheetTraitement;
If export.BitBtnStop.Visible Then export.BitBtnStop.SetFocus;
End;
tpWait : Begin
export.StatusBarMain.Panels[1].Text := 'Wait';
CacheTout;
if one
Then export.PageControlMain.ActivePage := export.TabSheetTraitement;
export.BitBtnLancer.Visible := (export.PageControlMain.ActivePageIndex = 0) And one;
If export.BitBtnLancer.Visible Then export.BitBtnLancer.SetFocus;
End;
tpPause : export.StatusBarMain.Panels[1].Text := 'Pause';
tpStop : Begin
export.StatusBarMain.Panels[1].Text := 'Stoppé';
FormTraitement.caption := _PROCESS_STOP;
CacheTout;
End;
tpError : export.StatusBarMain.Panels[1].Text := 'Erreur';
tpDone : Begin
export.StatusBarMain.Panels[1].Text := 'Fini';
CacheTout;
End;
End;
export.CheckListBoxLog.Visible := export.CheckListBoxLog.Count > 0;
Application.ProcessMessages;
End;
// ********************************************************************************************************************
// * Domaines et Stations *
// ********************************************************************************************************************
{ ========================================================= }
{ Recherche le domaine a partir du nom de fichier }
{ ========================================================= }
function TFormTraitement.getDomainFromFileName(entry: string): Boolean;
Var
i : integer;
Begin
result := False;
// Tout le test en majuscule pour supprimer les accents
LogLine(1, format(_DOMAIN_SEARCH, [entry]));
entry := UpperCase(entry);
With FormConfiguration.ValueListEditorSchemas Do
For i := 1 To RowCount -1
Do begin
If AnsiStartsStr(UpperCase(Cells[0,i]), entry) OR AnsiStartsStr(UpperCase(ExtractFileName(ExcludeTrailingPathDelimiter(ExtractFilePath((Cells[0,i]))))), entry) OR AnsiStartsStr(UpperCase(_HYDRAS_NAME_EXPORT + ExtractFileName(ExcludeTrailingPathDelimiter(ExtractFilePath((Cells[0,i]))))), entry)
Then Begin
domain := Cells[0,i];
LogLine(2, format(_DOMAIN_SEARCH_TRUE, [domain]));
Result :=True;
Exit;
End;
End;
LogLine(-2, format(_DOMAIN_SEARCH_FALSE, [entry]))
End;
function TFormTraitement.getDomainFromFilePath(enTry: string): Boolean;
// Recherche le domaine a partir du chemin
Var
i,j : integer;
StrTemp : TStringList;
Begin
result := False;
// Tout le test en majuscule pour supprimer les accents
LogLine(1, format(_DOMAIN_SEARCH, [entry]));
StrTemp := TStringList.Create;
Try
StrTemp.Text := AnsiReplaceText(UpperCase(enTry), '\', #13+#10);
For j := 0 To StrTemp.count -1 Do
For i := 1 To FormConfiguration.ValueListEditorSchemas.RowCount -1 Do
If AnsiStartsStr(UpperCase(FormConfiguration.ValueListEditorSchemas.Cells[0,i]), StrTemp[j])
Then Begin
domain := FormConfiguration.ValueListEditorSchemas.Cells[0,i];
LogLine(2, format(_DOMAIN_SEARCH_TRUE, [domain]));
Result :=True;
Exit;
End;
Finally
StrTemp.Free;
End;
LogLine(-2, format(_DOMAIN_SEARCH_FALSE, [entry]))
End;
function TFormTraitement.getSchemaFromDomain(enTry: string): Boolean;
Begin
result := False;
LogLine(1, format(_SCHEMA_SEARCH, [entry]));
If DataModuleDatas.IsSchemaExist(FormConfiguration.ValueListEditorSchemas.Values[enTry])
Then Begin
schema := FormConfiguration.ValueListEditorSchemas.Values[enTry];
LogLine(2, format(_SCHEMA_SEARCH_TRUE, [schema]));
Result := True;
Exit;
End;
LogLine(-2, format(_SCHEMA_SEARCH_FALSE, [entry, FormConfiguration.ValueListEditorSchemas.Values[enTry]]))
End;
// ********************************************************************************************************************
// * Traitements ZIP *
// ********************************************************************************************************************
function TFormTraitement.ZipFiles : Boolean;
Var
archiver : TZipForge;
i : Integer;
Begin
Result := False;
If ZipListFiles.Count >= 0
Then Begin
archiver := TZipForge.Create(nil);
Try
With archiver
Do Begin
FileName := IncludeTrailingPathDelimiter(FOLDER_MONITORING.Folder) + 'import [' + AnsiReplaceText(AnsiReplaceText(AnsiReplaceText(DateTimeToStr(now), '/' , '-'), ':' , '-'), ' ' , '-') + '].zip';
LogLine(1, format(_ZIP_CREATE_ARCHIVE, [FileName]));
OpenArchive(fmCreate);
BaseDir := IncludeTrailingPathDelimiter(FOLDER_MONITORING.Folder);
LogLine(1, Format(_ZIP_CREATE_BASEDIR, [BaseDir]));
For i := 0 To ZipListFiles.Count - 1
Do Begin
LogLine(2, format(_FILE_MOVE, [ZipListFiles[i]]));
MoveFiles(ZipListFiles[i]);
Result := True;
End;
CloseArchive();
LogLine(1, _ZIP_CLOSE_ARCHIVE);
End;
Except
On E: Exception
Do Begin
LogLine(2 , 'Exception: ' + E.Message);
Result := False;
End;
End;
End Else LogLine(-1, _ZIP_NO_FILE);
End;
// ********************************************************************************************************************
// * Traitements *
// ********************************************************************************************************************
procedure TFormTraitement.Stop(Sender: TObject);
Begin
If messagedlg('Annuler le traitement ',mtConfirmation , mbOKCancel, 0) = mrOk
Then Begin
caption := _PROCESS_STOP;
LogLine(0, 'Arret de traitement');
RefreshInfos(tpStop);
End Else LogLine(0, 'Annulation do l''arret de traitement');
End;
procedure TFormTraitement.sortir(Amessage: string);
Begin
LogLine(1, _PROCESS_EXIT);
RefreshInfos(tpSTop);
End;
procedure TFormTraitement.Lancer(lst: TStrings; modeAuto: Boolean);
Var
i : integer;
Remember: Boolean;
Begin
Remember := FOLDER_MONITORING.IsActive;
If FOLDER_MONITORING.IsActive
Then FOLDER_MONITORING.Deactivate;
RefreshInfos(tpStart);
For i := 0 To lst.Count - 1
Do If importCsv(lst[i], modeAuto)
Then ZipListFiles.Add(lst[i]);
ZipFiles;
If Remember
Then FOLDER_MONITORING.Activate;
End;
{ ========================================================= }
{ Importation d'un fichier CSV }
{ ========================================================= }
function TFormTraitement.importCsv(Filename: string; AUTO : Boolean) : Boolean;
Var
i : integer;
listAllStations, listAllCapteurs, listStations : TStringList;
procedure GetStations;
Var
FTHydras : THydras;
Begin
FTHydras := THydras.Create;
listStations := TStringList.Create;
listAllStations := TStringList.Create;
try
FTHydras.getAllStations(IncludeTrailingPathDelimiter(domain), listAllStations);
Finally
FTHydras.Free;
End;
End;
procedure UpdateStations(areaCode : string);
var
i : integer;
localSql : TStringList;
Begin
localSql := TStringList.Create;
Try
localSql.Text := format('INSERT INTO %s.station (area_id, code, name) VALUES', [Schema]);
For i := 0 To listStations.Count - 1
Do localSql.Add(format('(%s, %s, %s),', [areaCode, QuotedStr(listStations.Names[i]), QuotedStr(listStations.ValueFromIndex[i])]));
localSql[localSql.Count -1] := changeEndValues(localSql[localSql.Count -1], 'ON CONFLICT DO NOTHING;');
If DataModuleDatas.isConnected And (PROCESS = tpRun)
Then Begin
If DEBUG
Then LogLine(0, localSql.Text);
DataModuleDatas.connectionPostgres.ExecuteDirect(localSql.Text, i);
LogLine(2, 'Ajout de ' + inttostr(i) + ' nouvelles stations');
End;
Finally
localSql.Free;
End;
End;
function GetSensors : string;
Var
FTHydras : THydras;
Begin
FTHydras := THydras.Create;
listAllCapteurs := TStringList.Create;
try
FTHydras.getAllSensors(IncludeTrailingPathDelimiter(domain), listAllCapteurs);
Finally
FTHydras.Free;
End;
End;
procedure UpdateSensors;
var
i : integer;
localSql : TStringList;
Begin
localSql := TStringList.Create;
Try
localSql.Text := format('INSERT INTO %s.capteur (code, name) VALUES', [Schema]);
For i := 0 To listAllCapteurs.Count - 1
Do localSql.Add(format('(%s, %s),', [QuotedStr(listAllCapteurs.Names[i]), QuotedStr(listAllCapteurs.ValueFromIndex[i])]));
localSql[localSql.Count -1] := changeEndValues(localSql[localSql.Count -1], 'ON CONFLICT DO NOTHING;');
If DataModuleDatas.isConnected And (PROCESS = tpRun)
Then Begin
If DEBUG
Then LogLine(0, localSql.Text);
DataModuleDatas.connectionPostgres.ExecuteDirect(localSql.Text, i);
LogLine(2, 'Ajout de ' + inttostr(i) + ' nouveaux capteurs');
End;
Finally
localSql.Free;
End;
End;
function FormateToExport(entry: string): string;
Begin
export.ProgressBar.position := export.ProgressBar.Position + 1;
result := '(''' + AnsiReplaceText(entry, ';', ''',''') + '''),';
End;
function verifieStation(entry: string): string;
var
cle : string;
Begin
cle := CleanName(Copy(entry, 0 , AnsiPos(';', entry) - 1));
If listStations.IndexOfName(cle) = -1
Then listStations.Values[cle] := listAllStations.Values[cle];
End;
procedure init;
Begin
LogLine(2, _POSTGRES_DATABASE_INIT_INSERT);
compteur := 0;
scriptSql.text := format('INSERT INTO %s.import (station, capteur, date_heure, valeur, info) VALUES', [schema]);
End;
procedure LaunchUpdate;
Begin
LogLine(2, _POSTGRES_DATABASE_EXEC_SQL);
scriptSql[scriptSql.Count -1] := changeEndValues(scriptSql[scriptSql.Count -1], ';');
DataModuleDatas.connectionPostgres.ExecuteDirect(scriptSql.Text);
init;
End;
function GetAreaCode(entry : string) : string;
Begin
With DataModuleDatas
Do Begin
launchSql(format('select area_id FROM agrhys.area WHERE name = ''%s'';', [entry]));
result := ReadOnlySql.FieldByname('area_id').AsString;
If result = ''
Then Begin
connectionPostgres.ExecuteDirect(format('INSERT INTO %s.area (code, name) VALUES (1, ''%s'');', [Schema, entry]));
launchSql(format('select area_id FROM agrhys.area WHERE name = ''%s'';', [entry]));
result := ReadOnlySql.FieldByname('area_id').AsString;
End;
End;
LogLine(2, Format('Get area code : %s', [result]));
End;
Begin
result := False;
RefreshInfos(tpInit);
LogLine(0, format(_FILE_CSV_PROCESS, [Filename]));
export.StatusBarMain.Panels[2].Text := format(_FILE_CSV_PROCESS, [Filename]);
If AUTO
Then LogLine(1, _PROCESS_MODE_AUTO)
Else LogLine(1, _PROCESS_MODE_MANUEL);
// addTask('Deconnection de tous les utilisateurs', False);
If DataModuleDatas.isConnected
Then LogLine(1, _POSTGRES_DATABASE_CONNECTED)
Else sortir(_POSTGRES_DATABASE_NOT_CONNECTED);
If PROCESS = tpStop Then exit;
If FileExists(Filename)
Then LogLine(1, format(_FILE_EXIST, [Filename]))
Else sortir(format(_FILE_NOT_EXIST, [Filename]));
If PROCESS = tpStop Then exit;
If Not getDomainFromFileName(extractFileName(Filename))
Then Begin
If Not getDomainFromFilePath(extractFilePath(Filename))
Then Sortir(_TEST_DOMAINS_NOT_FOUND_FILE);
End;
If PROCESS = tpStop Then exit;
If Not getSchemaFromDomain(Domain)
Then Sortir('Aucun schema pour ce domaine');
If PROCESS = tpStop Then exit;
If DataModuleDatas.isConnected
Then LogLine(1, _POSTGRES_DATABASE_CONNECTED)
Else sortir(_POSTGRES_DATABASE_NOT_CONNECTED);
// FIN INIT
If PROCESS = tpStop
Then exit
Else RefreshInfos(tpRun);
export.ProgressBar.Visible := True;
GetStations;
GetSensors;
UpdateSensors;
If PROCESS = tpRun
Then DataModuleDatas.connectionPostgres.ExecuteDirect(format('CREATE TABLE IF NOT EXISTS %s.import ( station text, capteur text, date_heure text, valeur text, info text);', [Schema]))
Else exit;
DataModuleDatas.connectionPostgres.StartTransaction;
scriptSql := TStringList.Create;
Try
export.ProgressBar.Max := round(GetFileSize(Filename) / 45);
LogLine(1, _PROCESS_FILE_START);
AssignFile(myFile, Filename);
Reset(myFile);
init;
While Not Eof(myFile)
Do Begin
ReadLn(myFile, ligne);
verifieStation(ligne);
scriptSql.Add(FormateToExport(ligne));
inc(compteur);
If (compteur = tampon) Then LaunchUpdate;
End;
LogLine(2, _PROCESS_FILE_END_OK);
LaunchUpdate;
CloseFile(myFile);
export.ProgressBar.Position := export.ProgressBar.Max;
If PROCESS = tpRun
Then UpdateStations(GetAreaCode(extractFileName(ExcludeTrailingPathDelimiter(domain))));
If (PROCESS = tpRun) AND DataModuleDatas.IsProcedureExist('_hydras_import')
Then If AUTO
Then DataModuleDatas.connectionPostgres.ExecuteDirect('SELECT * from public._hydras_import(''' + Schema + ''');')
Else DataModuleDatas.launchAndShowResultSql('SELECT * from public._hydras_import(''' + schema + ''');', 'Traitement du fichier csv : ' + Filename);
If PROCESS = tpRun
Then DataModuleDatas.connectionPostgres.Commit;
If PROCESS = tpRun
Then RefreshInfos(tpDone);
LogLine(1, _PROCESS_END_OK);
Result := True;
Finally
scriptSql.Free;
listAllStations.Free;
listAllCapteurs.Free;
listStations.Free;
End;
End;
procedure TFormTraitement.FormShow(Sender: TObject);
begin
RefreshInfos(PROCESS);
end;
End.
|
unit IdPOP3;
interface
uses
Classes, IdGlobal,
IdMessage, IdMessageClient;
type
TIdPOP3 = class(TIdMessageClient)
protected
FPassword: string;
FUserId: string;
public
function RetrieveRaw(const MsgNum: Integer; const Dest: TStrings): boolean;
function CheckMessages: longint;
procedure Connect; override;
constructor Create(AOwner: TComponent); override;
function Delete(const MsgNum: Integer): Boolean;
procedure Disconnect; override;
procedure KeepAlive;
function Reset: Boolean;
function Retrieve(const MsgNum: Integer; AMsg: TIdMessage): Boolean;
function RetrieveHeader(const MsgNum: Integer; AMsg: TIdMessage): Boolean;
function RetrieveMsgSize(const MsgNum: Integer): Integer;
function RetrieveMailBoxSize: integer;
published
property Password: string read FPassword write FPassword;
property UserId: string read FUserId write FUserId;
property Port default IdPORT_POP3;
end;
implementation
uses
IdTCPConnection,
SysUtils;
function TIdPOP3.CheckMessages: longint;
var
Value1, Value2: string;
begin
Result := 0;
SendCmd('STAT', wsOk); {Do not localize}
Value1 := CmdResult;
if Value1 <> '' then
begin
Value2 := Copy(Value1, 5, Length(Value1) - 5);
Result := StrToInt(Copy(Value2, 1, IndyPos(' ', Value2) - 1));
end;
end;
procedure TIdPOP3.Connect;
begin
inherited
Connect;
try
GetResponse([wsOk]);
SendCmd('USER ' + UserId, wsOk); {Do not localize}
SendCmd('PASS ' + Password, wsOk); {Do not localize}
except
Disconnect;
raise;
end;
end;
constructor TIdPOP3.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Port := IdPORT_POP3;
end;
function TIdPOP3.Delete(const MsgNum: Integer): Boolean;
begin
SendCmd('DELE ' + IntToStr(MsgNum), wsOk); {Do not localize}
Result := ResultNo = wsOk;
end;
procedure TIdPOP3.Disconnect;
begin
try
WriteLn('Quit'); {Do not localize}
finally
inherited;
end;
end;
procedure TIdPOP3.KeepAlive;
begin
SendCmd('NOOP', wsOk); {Do not localize}
end;
function TIdPOP3.Reset: Boolean;
begin
SendCmd('RSET', wsOK); {Do not localize}
Result := ResultNo = wsOK;
end;
function TIdPOP3.RetrieveRaw(const MsgNum: Integer; const Dest: TStrings):
boolean;
begin
result := SendCmd('RETR ' + IntToStr(MsgNum)) = wsOk; {Do not localize}
if result then
begin
Capture(Dest);
result := true;
end;
end;
function TIdPOP3.Retrieve(const MsgNum: Integer;
AMsg: TIdMessage): Boolean;
begin
if SendCmd('RETR ' + IntToStr(MsgNum)) = wsOk then {Do not localize}
begin
ReceiveHeader(AMsg, '');
ReceiveBody(AMsg);
end;
Result := ResultNo = wsOk;
end;
function TIdPOP3.RetrieveHeader(const MsgNum: Integer;
AMsg: TIdMessage): Boolean;
var
Dummy: string;
begin
try
SendCmd('TOP ' + IntToStr(MsgNum) + ' 0', wsOk); {Do not localize}
ReceiveHeader(AMsg, '');
Dummy := ReadLn;
while Dummy = '' do
begin
Dummy := ReadLn;
end;
Result := Dummy = '.';
except
Result := False;
end;
end;
function TIdPOP3.RetrieveMailBoxSize: integer;
var
CurrentLine: string;
begin
Result := 0;
try
SendCmd('LIST', wsOk); {Do not localize}
CurrentLine := ReadLn;
while (CurrentLine <> '.') and (CurrentLine <> '') do {Do not localize}
begin
CurrentLine := Copy(CurrentLine, IndyPos(' ', CurrentLine) + 1,
Length(CurrentLine) - IndyPos(' ', CurrentLine) + 1);
Result := Result + StrToIntDef(CurrentLine, 0);
CurrentLine := ReadLn;
end;
except
Result := -1;
end;
end;
function TIdPOP3.RetrieveMsgSize(const MsgNum: Integer): Integer;
var
ReturnResult: string;
begin
try
SendCmd('LIST ' + IntToStr(MsgNum), wsOk); {Do not localize}
if CmdResult <> '' then
begin
ReturnResult := Copy(CmdResult, 5, Length(CmdResult) - 4);
Result := StrToIntDef(Copy(ReturnResult, IndyPos(' ', ReturnResult) + 1,
Length(ReturnResult) - IndyPos(' ', ReturnResult) + 1), -1);
end
else
Result := -1;
except
Result := -1;
end;
end;
end.
|
{
WAGNER VASCONCELOS
21/03/2020 - 08:56
}
unit uPrincipal;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Mask,
Vcl.ComCtrls, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls;
type
TfrmMain = class(TForm)
StatusBar1: TStatusBar;
OpenDialog1: TOpenDialog;
Panel2: TPanel;
btnAnexo: TSpeedButton;
btnLimpar: TSpeedButton;
btnEnviar: TSpeedButton;
Panel1: TPanel;
Panel3: TPanel;
edtAssunto: TEdit;
edtCorpo: TMemo;
edtEmail_Copia: TEdit;
edtEmail_Destinatario: TEdit;
edtEmail_Remetente: TEdit;
edtNome_Remetente: TEdit;
lblAssunto: TLabel;
lblCopia: TLabel;
lblDestinatario: TLabel;
lblRemetente: TLabel;
Shape1: TShape;
procedure btnEnviarClick(Sender: TObject);
procedure btnLimparClick(Sender: TObject);
procedure btnAnexoClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
{ Private declarations }
procedure MsgInforma(Mensagem: String);
function MsgConfirmacao(Mensagem: String): Boolean;
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
uses uEmail;
function TfrmMain.MsgConfirmacao(Mensagem: String): Boolean;
begin
Result := Application.messageBox(PChar(Mensagem), 'Confirmação', mb_YesNo+mb_IconInformation+mb_DefButton2) = idYes;
end;
procedure TfrmMain.MsgInforma(Mensagem: String);
begin
Application.MessageBox(PChar(Mensagem), 'Aviso', mb_Ok+mb_IconExclamation);
end;
procedure TfrmMain.btnLimparClick(Sender: TObject);
begin
edtEmail_Copia.Clear;
edtEmail_Destinatario.Clear;
edtAssunto.Clear;
edtCorpo.Clear;
end;
procedure TfrmMain.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_RETURN: begin
if not edtCorpo.Focused then
Perform(WM_NEXTDLGCTL, 0, 0);
end;
VK_ESCAPE: Close;
end;
end;
procedure TfrmMain.btnAnexoClick(Sender: TObject);
begin
if OpenDialog1.Execute then
begin
StatusBar1.Panels[1].Text := 'Anexo '+ ExtractFileName(OpenDialog1.FileName) +'.'
end;
end;
procedure TfrmMain.btnEnviarClick(Sender: TObject);
var
Mail : TMail;
begin
if Trim(edtNome_Remetente.Text) = '' then
begin
MsgInforma('Digite o nome do remetente.');
Exit;
end;
if Trim(edtEmail_Destinatario.Text) = '' then
begin
MsgInforma('Digite o Email do destinatário.');
Exit;
end;
if Trim(edtCorpo.Text) = '' then
begin
MsgInforma('Digite o corpo do Email.');
Exit;
end;
btnEnviar.Enabled := False;
btnLimpar.Enabled := False;
btnAnexo.Enabled := False;
Mail := TMail.Create(465, 'smtp.gmail.com', 'emitente_email@gmail.com', 'senha123');
try
StatusBar1.Panels[0].Text := 'Enviando e-mail.';
Application.ProcessMessages;
try
Mail.FromAddress := Trim(edtEmail_Remetente.Text);
Mail.FromName := Trim(edtNome_Remetente.Text);
Mail.ReplyToAddress := Trim(edtEmail_Copia.Text);
Mail.RecipientsAddress := Trim(edtEmail_Destinatario.Text);
Mail.Subject := Trim(edtAssunto.Text);
Mail.Body := Trim(edtCorpo.Text);
Mail.Attachment := OpenDialog1.FileName;
Mail.Send;
except on E: Exception do
begin
MsgInforma('Erro.: '+ E.Message);
Exit;
end;
end;
StatusBar1.Panels[0].Text := 'Email enviado com sucesso.';
finally
FreeAndNil(Mail);
btnEnviar.Enabled := True;
btnLimpar.Enabled := True;
btnAnexo.Enabled := True;
btnLimparClick(Self);
end;
end;
end.
|
unit Horse.Paginate;
interface
uses
System.SysUtils,
Horse,
System.Classes,
System.JSON,
Web.HTTPApp;
procedure Middleware(Req: THorseRequest; Res: THorseResponse; Next: TProc);
function Paginate : THorseCallback; overload;
implementation
uses System.Generics.Collections;
function Paginate : THorseCallback; overload;
begin
Result := Middleware;
end;
procedure Middleware(Req: THorseRequest; Res: THorseResponse; Next: TProc); overload;
var
LWebResponse: TWebResponse;
LContent: TObject;
aJsonArray, NewJsonArray : TJsonArray;
LLimit : String;
i: Integer;
Pages : Double;
Page : String;
begin
try
Next;
finally
if Req.Headers['X-Paginate'] = 'true' then
begin
if not Req.Query.TryGetValue('limit', LLimit) then LLimit := '25';
if not Req.Query.TryGetValue('page', Page) then Page := '1';
LWebResponse := THorseHackResponse(Res).GetWebResponse;
LContent := THorseHackResponse(Res).GetContent;
if Assigned(LContent) and LContent.InheritsFrom(TJSONValue) then
begin
aJsonArray := TJSONValue(LContent) as TJSONArray;
Pages := Trunc((aJsonArray.Count / LLimit.ToInteger) + 1);
NewJsonArray := TJSONArray.Create;
for I := (LLimit.ToInteger * (Page.ToInteger-1)) to ((LLimit.ToInteger * Page.ToInteger)) -1 do
begin
if I < aJsonArray.Count then
NewJsonArray.AddElement(aJsonArray.Items[I]);
end;
LWebResponse.Content :=
TJsonObject.Create
.AddPair(
'docs',
NewJsonArray
)
.AddPair(TJsonPair.Create(TJSONString.Create('total'), TJSONNumber.Create(aJsonArray.Count)))
.AddPair(TJsonPair.Create(TJSONString.Create('limit'), TJSONNumber.Create(LLimit.ToInteger)))
.AddPair(TJsonPair.Create(TJSONString.Create('page'), TJSONNumber.Create(Page.ToInteger)))
.AddPair(TJsonPair.Create(TJSONString.Create('pages'), TJSONNumber.Create(Pages)))
.ToJSON;
LWebResponse.ContentType := 'application/json';
end;
end;
end;
end;
end.
|
//
// Created by the DataSnap proxy generator.
// 2011-01-26 ¿ÀÈÄ 3:09:25
//
unit ServerMethodsUnit;
interface
uses DBXCommon, DBXClient, DBXJSON, DSProxy, Classes, SysUtils, DB, SqlExpr, DBXDBReaders, DBXJSONReflect;
type
TServerMethods1Client = class(TDSAdminClient)
private
FGet_ReporttCommand: TDBXCommand;
FGet_Emp_InfoCommand: TDBXCommand;
FGet_Emp_TreeInfoCommand: TDBXCommand;
FGet_Logined_infoCommand: TDBXCommand;
FEchoStringCommand: TDBXCommand;
FReverseStringCommand: TDBXCommand;
public
constructor Create(ADBXConnection: TDBXConnection); overload;
constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload;
destructor Destroy; override;
function Get_Reportt: TDataSet;
function Get_Emp_Info: TDataSet;
function Get_Emp_TreeInfo: TDataSet;
function Get_Logined_info(Value: Integer): TDataSet;
function EchoString(Value: string): string;
function ReverseString(Value: string): string;
end;
var
serverMethod : TServerMethods1Client;
implementation
function TServerMethods1Client.Get_Reportt: TDataSet;
begin
if FGet_ReporttCommand = nil then
begin
FGet_ReporttCommand := FDBXConnection.CreateCommand;
FGet_ReporttCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FGet_ReporttCommand.Text := 'TServerMethods1.Get_Reportt';
FGet_ReporttCommand.Prepare;
end;
FGet_ReporttCommand.ExecuteUpdate;
Result := TCustomSQLDataSet.Create(nil, FGet_ReporttCommand.Parameters[0].Value.GetDBXReader(False), True);
Result.Open;
if FInstanceOwner then
FGet_ReporttCommand.FreeOnExecute(Result);
end;
function TServerMethods1Client.Get_Emp_Info: TDataSet;
begin
if FGet_Emp_InfoCommand = nil then
begin
FGet_Emp_InfoCommand := FDBXConnection.CreateCommand;
FGet_Emp_InfoCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FGet_Emp_InfoCommand.Text := 'TServerMethods1.Get_Emp_Info';
FGet_Emp_InfoCommand.Prepare;
end;
FGet_Emp_InfoCommand.ExecuteUpdate;
Result := TCustomSQLDataSet.Create(nil, FGet_Emp_InfoCommand.Parameters[0].Value.GetDBXReader(False), True);
Result.Open;
if FInstanceOwner then
FGet_Emp_InfoCommand.FreeOnExecute(Result);
end;
function TServerMethods1Client.Get_Emp_TreeInfo: TDataSet;
begin
if FGet_Emp_TreeInfoCommand = nil then
begin
FGet_Emp_TreeInfoCommand := FDBXConnection.CreateCommand;
FGet_Emp_TreeInfoCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FGet_Emp_TreeInfoCommand.Text := 'TServerMethods1.Get_Emp_TreeInfo';
FGet_Emp_TreeInfoCommand.Prepare;
end;
FGet_Emp_TreeInfoCommand.ExecuteUpdate;
Result := TCustomSQLDataSet.Create(nil, FGet_Emp_TreeInfoCommand.Parameters[0].Value.GetDBXReader(False), True);
Result.Open;
if FInstanceOwner then
FGet_Emp_TreeInfoCommand.FreeOnExecute(Result);
end;
function TServerMethods1Client.Get_Logined_info(Value: Integer): TDataSet;
begin
if FGet_Logined_infoCommand = nil then
begin
FGet_Logined_infoCommand := FDBXConnection.CreateCommand;
FGet_Logined_infoCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FGet_Logined_infoCommand.Text := 'TServerMethods1.Get_Logined_info';
FGet_Logined_infoCommand.Prepare;
end;
FGet_Logined_infoCommand.Parameters[0].Value.SetInt32(Value);
FGet_Logined_infoCommand.ExecuteUpdate;
Result := TCustomSQLDataSet.Create(nil, FGet_Logined_infoCommand.Parameters[1].Value.GetDBXReader(False), True);
Result.Open;
if FInstanceOwner then
FGet_Logined_infoCommand.FreeOnExecute(Result);
end;
function TServerMethods1Client.EchoString(Value: string): string;
begin
if FEchoStringCommand = nil then
begin
FEchoStringCommand := FDBXConnection.CreateCommand;
FEchoStringCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FEchoStringCommand.Text := 'TServerMethods1.EchoString';
FEchoStringCommand.Prepare;
end;
FEchoStringCommand.Parameters[0].Value.SetWideString(Value);
FEchoStringCommand.ExecuteUpdate;
Result := FEchoStringCommand.Parameters[1].Value.GetWideString;
end;
function TServerMethods1Client.ReverseString(Value: string): string;
begin
if FReverseStringCommand = nil then
begin
FReverseStringCommand := FDBXConnection.CreateCommand;
FReverseStringCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FReverseStringCommand.Text := 'TServerMethods1.ReverseString';
FReverseStringCommand.Prepare;
end;
FReverseStringCommand.Parameters[0].Value.SetWideString(Value);
FReverseStringCommand.ExecuteUpdate;
Result := FReverseStringCommand.Parameters[1].Value.GetWideString;
end;
constructor TServerMethods1Client.Create(ADBXConnection: TDBXConnection);
begin
inherited Create(ADBXConnection);
end;
constructor TServerMethods1Client.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean);
begin
inherited Create(ADBXConnection, AInstanceOwner);
end;
destructor TServerMethods1Client.Destroy;
begin
FreeAndNil(FGet_ReporttCommand);
FreeAndNil(FGet_Emp_InfoCommand);
FreeAndNil(FGet_Emp_TreeInfoCommand);
FreeAndNil(FGet_Logined_infoCommand);
FreeAndNil(FEchoStringCommand);
FreeAndNil(FReverseStringCommand);
inherited;
end;
end.
|
{ example of constant definition part }
program convert(output);
const
addin = 32;
mulby = 1.8;
low = 0;
high = 39;
seperator = '------------';
var
degree : low..high;
begin
writeln(seperator);
for degree := low to high do
begin
writeln(degree, 'c', round(degree * mulby + addin), 'f');
end;
writeln(seperator)
end.
|
{*******************************************************}
{ }
{ Borland Delphi Test Server }
{ }
{ Copyright (c) 2001 Borland Software Corporation }
{ }
{*******************************************************}
unit SvrPropDlg;
interface
uses
SysUtils, Classes, QGraphics, QControls, QForms, QDialogs,
QStdCtrls, QComCtrls, SvrLogFrame, SvrLogColSettingsFrame;
type
TDlgProperties = class(TForm)
OkButton: TButton;
CancelButton: TButton;
PageControl1: TPageControl;
TabConnection: TTabSheet;
TabLog: TTabSheet;
GroupBox1: TGroupBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
cbPort: TEdit;
GroupBox2: TGroupBox;
LogColSettingsFrame: TLogColSettingsFrame;
GroupBox6: TGroupBox;
edLogMax: TEdit;
Label4: TLabel;
edLogDelete: TEdit;
Label5: TLabel;
cbActiveAtStartup: TCheckBox;
edDefault: TEdit;
edPath: TEdit;
Button1: TButton;
Label6: TLabel;
cbUDPPort: TEdit;
Label7: TLabel;
edBrowser: TEdit;
procedure NumericKeyPress(Sender: TObject; var Key: AnsiChar);
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
function GetServerPath: string;
function GetServerPort: Integer;
procedure SetServerPath(const Value: string);
procedure SetServerPort(const Value: Integer);
function GetDefaultURL: string;
procedure SetDefaultURL(const Value: string);
function GetLogMax: Integer;
procedure SetLogMax(const Value: Integer);
function GetLogDelete: Integer;
procedure SetLogDelete(const Value: Integer);
function GetActiveAtStartup: Boolean;
procedure SetActiveAtStartup(const Value: Boolean);
procedure SetLogFrame(const Value: TLogFrame);
function GetUDPPort: Integer;
procedure SetUDPPort(Value: Integer);
function GetBrowser: string;
procedure SetBrowser(const Value: string);
public
procedure UpdateColumns;
property ServerSearchPath: string read GetServerPath write SetServerPath;
property ServerPort: Integer read GetServerPort write SetServerPort;
property DefaultURL: string read GetDefaultURL write SetDefaultURL;
property UDPPort: Integer read GetUDPPort write SetUDPPort;
property LogMax: Integer read GetLogMax write SetLogMax;
property LogDelete: Integer read GetLogDelete write SetLogDelete;
property ActiveAtStartup: Boolean read GetActiveAtStartup write SetActiveAtStartup;
property LogFrame: TLogFrame write SetLogFrame;
property Browser: string read GetBrowser write SetBrowser;
end;
var
DlgProperties: TDlgProperties;
implementation
{$R *.xfm}
{ TDlgProperties }
function TDlgProperties.GetDefaultURL: string;
begin
Result := edDefault.Text;
end;
function TDlgProperties.GetServerPath: string;
begin
Result := edPath.Text;
end;
function TDlgProperties.GetServerPort: Integer;
begin
Result := StrToInt(cbPort.Text);
end;
procedure TDlgProperties.SetDefaultURL(const Value: string);
begin
edDefault.Text := Value;
end;
procedure TDlgProperties.SetServerPath(const Value: string);
begin
edPath.Text := Value;
end;
procedure TDlgProperties.SetServerPort(const Value: Integer);
begin
cbPort.Text := IntToStr(Value);
end;
procedure TDlgProperties.NumericKeyPress(Sender: TObject; var Key: AnsiChar);
begin
if Key in [#32..#255] then
if not (Key in ['0'..'9']) then
begin
Beep;
Key := #0;
end;
end;
function TDlgProperties.GetLogMax: Integer;
begin
Result := StrToInt(edLogMax.Text);
end;
procedure TDlgProperties.SetLogMax(const Value: Integer);
begin
edLogMax.Text := IntToStr(Value);
end;
function TDlgProperties.GetActiveAtStartup: Boolean;
begin
Result := cbActiveAtStartup.Checked;
end;
procedure TDlgProperties.SetActiveAtStartup(const Value: Boolean);
begin
cbActiveAtStartup.Checked := Value;
end;
procedure TDlgProperties.SetLogFrame(const Value: TLogFrame);
begin
LogColSettingsFrame.LogFrame := Value;
end;
procedure TDlgProperties.UpdateColumns;
begin
LogColSettingsFrame.UpdateColumns;
end;
function TDlgProperties.GetLogDelete: Integer;
begin
Result := StrToInt(edLogDelete.Text);
end;
procedure TDlgProperties.SetLogDelete(const Value: Integer);
begin
edLogDelete.Text := IntToStr(Value);
end;
procedure TDlgProperties.Button1Click(Sender: TObject);
begin
{$IFDEF MSWINDOWS}
Application.InvokeHelp;
{$ENDIF}
end;
function TDlgProperties.GetUDPPort: Integer;
begin
Result := StrToInt(cbUDPPort.Text);
end;
procedure TDlgProperties.SetUDPPort(Value: Integer);
begin
cbUDPPort.Text := IntToStr(Value);
end;
function TDlgProperties.GetBrowser: string;
begin
Result := edBrowser.Text;
end;
procedure TDlgProperties.SetBrowser(const Value: string);
begin
edBrowser.Text := Value;
end;
procedure TDlgProperties.FormCreate(Sender: TObject);
begin
{$IFDEF MSWINDOWS}
// Can choose browser under Linux. Under windows we use ShellExecute to
// launch default browser.
edBrowser.Visible := False;
Label7.Visible := False;
{$ENDIF}
HelpType := htContext;
HelpContext:= 4310;
end;
end.
|
unit BD.frmSync;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP,
Vcl.StdCtrls, OXmlPDOM, Generics.Collections,
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, BD.Fylke, BD.Kommune, BD.Postnr, BD.Handler, Vcl.ComCtrls;
type
TIterator = procedure (ANode: PXMLNode) of Object;
TfrmDataSync = class(TForm)
btnSync: TButton;
pbSync: TProgressBar;
Label1: TLabel;
lblOperation: TLabel;
procedure btnSyncClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
Map: TMapList;
FylkeListe: TFylkeListe;
KommuneListe: TKommuneListe;
PostnrListe: TPostnrListe;
procedure GetPage(Url: String; const Lines: TStrings);
procedure IterateXml(Url, StartPath: String; Iterator: TIterator);
procedure IterateFylke(AFylke: PXMLNode);
procedure IterateKommune(AKommune: PXMLNode);
procedure SyncFylker;
procedure SyncKommuner;
procedure SyncPostnr;
procedure IteratePostnr(APostnr: PXMLNode);
{ Private declarations }
public
{ Public declarations }
end;
var
frmDataSync: TfrmDataSync;
implementation
uses BD.Settings, Spring.Collections, BD.dmData;
{$R *.dfm}
procedure TfrmDataSync.IterateFylke(AFylke: PXMLNode);
var
MyFylke: TFylke;
begin
MyFylke := TFylkeHandler.Load(AFylke, Map);
if MyFylke <> nil then
FylkeListe.Add(MyFylke);
end;
procedure TfrmDataSync.IterateKommune(AKommune: PXMLNode);
var
MyKommune: TKommune;
begin
MyKommune := TKommuneHandler.Load(AKommune, Map);
if MyKommune <> nil then begin
TKommuneHandler.LinkToFylke(MyKommune, FylkeListe);
KommuneListe.Add(MyKommune);
end;
end;
procedure TfrmDataSync.IteratePostnr(APostnr: PXMLNode);
var
MyPostnr: TPostnr;
KNavn, FNavn: String;
FKommune: TKommune;
KNode: PXMLNode;
begin
//MyPostnr := TPostnrHandler.LoadFromXMLNode(APostnr, Map);
MyPostnr := TPostnrHandler.LoadFromXML<TPostnr>(APostnr, Map);
if MyPostnr <> nil then begin
//Linker til kommune
if APostnr.SelectNode('primary_municipality', KNode) then begin
KNavn := KNode.Text;
//Henter ut fylke
if APostnr.SelectNode('primary_county', KNode) then begin
FNavn := KNode.Text;
{ TODO : Støtte kommuner som også er skrevet på samisk (Navn kun en del av stringen) }
if KommuneListe.TryGetSingle(FKommune,
function(const AKommune: TKommune): Boolean
begin
Result := ((AnsiUpperCase(AKommune.Kommune) = KNavn) and
(AnsiUpperCase(AKommune.GetFylkeNavn) = FNavn));
end) then
MyPostnr.Kommune := FKommune
else
MyPostnr.Kommune := nil;
end;
end;
PostnrListe.Add(MyPostnr);
end;
end;
procedure TfrmDataSync.SyncFylker;
var
MyFylke: TFylke;
begin
//Mapping av XML mot object-properties (Dest.Field = Src.Field)
Map.Clear;
Map.Add('Fylkenr', 'nummer');
Map.Add('Fylke', 'navn');
IterateXml(Settings.DataURL + 'xml/difi/geo/fylke', 'entries', IterateFylke);
//Mapping av XML mot database (Dest.Field = Src.Field)
Map.Clear;
Map.Add('Fylkenr', 'Fylkenr');
Map.Add('Fylke', 'Fylke');
dmData.fdFylke.Open;
for MyFylke in FylkeListe do
TFylkeHandler.MergeIntoDatabase(MyFylke, dmData.fdFylke, Map, 'Fylkenr');
dmData.fdFylke.ApplyUpdates();
dmData.fdFylke.CommitUpdates;
dmData.fdFylke.Close;
end;
procedure TfrmDataSync.SyncKommuner;
var
MyKommune: TKommune;
I: Integer;
begin
//Mapping av XML mot object-properties (Dest.Field = Src.Field)
Map.Clear;
Map.Add('Fylkenr', 'fylke');
Map.Add('Kommune', 'navn');
Map.Add('Kommunenr', 'kommune');
for I := 0 to 9 do
IterateXml(Settings.DataURL + 'xml/difi/geo/kommune?page=' + IntToStr(I),
'entries', IterateKommune);
//Mapping av XML mot database (Dest.Field = Src.Field)
Map.Clear;
Map.Add('Kommunenr', 'Kommunenr');
Map.Add('Kommune', 'Kommune');
dmData.fdKommune.Open;
for MyKommune in KommuneListe do
TKommuneHandler.MergeIntoDatabase(MyKommune, dmData.fdKommune, Map, 'Kommunenr');
dmData.fdKommune.ApplyUpdates();
dmData.fdKommune.CommitUpdates;
dmData.fdKommune.Close;
end;
procedure TfrmDataSync.SyncPostnr;
var
I: Integer;
MyPostnr: TPostnr;
begin
//Mapping av XML mot object-properties (Dest.Field = Src.Field)
Map.Clear;
Map.Add('Postnr', 'postal_code');
Map.Add('Poststed', 'city');
//Map.Add('Kommune', 'primary_municipality');
for I := 0 to 9 do
IterateXml('http://adressesok.posten.no/api/v1/postal_codes.xml?postal_code=' +
IntToStr(I) + '*', '', IteratePostnr);
//Mapping av XML mot database (Dest.Field = Src.Field)
Map.Clear;
Map.Add('Postnr', 'Postnr');
Map.Add('Poststed', 'Poststed');
Map.Add('Kommunenr', 'Kommune.Kommunenr');
Map.Add('LandKode', 'LandKode');
dmData.fdPostnr.Open;
for MyPostnr in PostnrListe do begin
MyPostnr.LandKode := 'NO';
TPostnrHandler.MergeIntoDatabase(MyPostnr, dmData.fdPostnr, Map, 'Postnr');
end;
dmData.fdPostnr.ApplyUpdates();
dmData.fdPostnr.CommitUpdates;
dmData.fdPostnr.Close;
end;
procedure TfrmDataSync.btnSyncClick(Sender: TObject);
begin
pbSync.State := pbsNormal;
pbSync.Update;
lblOperation.Caption := 'Behandler fylker ...';
lblOperation.Update;
SyncFylker;
lblOperation.Caption := 'Behandler kommuner ...';
lblOperation.Update;
SyncKommuner;
lblOperation.Caption := 'Behandler postnummer ...';
lblOperation.Update;
SyncPostnr;
pbSync.State := pbsPaused;
//IterateXml(Settings.DataURL + 'xml/brreg/organisasjonsform', 'entries', IterateFylker);
//IterateXml(Settings.DataURL + 'xml/brreg/sektorkode', 'entries', IterateFylker);
//IterateXml(Settings.DataURL + 'xml/brreg/naeringskode', 'entries', IterateFylker);
//http://hotell.difi.no/api/xml/brreg/enhetsregisteret
end;
procedure TfrmDataSync.IterateXml(Url, StartPath: String; Iterator: TIterator);
var
Xml: IXMLDocument;
Sl: TStringList;
INode: PXMLNode;
I: Integer;
begin
Xml := CreateXMLDoc;
Sl := TStringList.Create;
try
GetPage(Url, Sl);
Xml.LoadFromXML(Sl.Text);
finally
Sl.Free;
end;
if StartPath <> '' then
Xml.DocumentElement.SelectNode(StartPath, INode)
else
INode := Xml.DocumentElement;
if INode <> nil then
for I := 0 to INode.ChildNodes.Count -1 do
Iterator(INode.ChildNodes[I]);
end;
procedure TfrmDataSync.FormCreate(Sender: TObject);
begin
//Felles lister
Map := TMapList.Create;
FylkeListe := TFylkeHandler.NewFylkeListe;
KommuneListe := TKommuneHandler.NewKommuneListe;
PostnrListe := TPostnrHandler.NewPostnrListe;
end;
procedure TfrmDataSync.FormDestroy(Sender: TObject);
begin
Map.Free;
end;
procedure TfrmDataSync.GetPage(Url: String; const Lines: TStrings);
var Ms: TMemoryStream;
IdHttp: TIdHttp;
begin
IdHttp := TIdHttp.Create(nil);
IdHttp.HandleRedirects := True;
Ms := TMemoryStream.Create;
try
IdHTTP.Get(Url, Ms);
Ms.Position := 0;
Lines.LoadFromStream(Ms, TEncoding.UTF8);
finally
Ms.Free;
IdHttp.Free;
end;
end;
end.
|
{------------------------------------------------------------------------------
This file is part of the MotifMASTER project. This software is
distributed under GPL (see gpl.txt for details).
This software 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.
Copyright (C) 1999-2007 D.Morozov (dvmorozov@mail.ru)
------------------------------------------------------------------------------}
unit FFDataFile;
interface
uses Classes, Dialogs, SysUtils, ComponentList, DataClasses, Tools;
type
TCatalogElement = class
NameOfElement: string[10];
FullName: string[15];
NumberOfPoints: SmallInt;
StepOfPoints: Double;
StartPos: LongInt;
EndPos: LongInt;
Reserved1: LongInt;
Reserved2: Double;
Comments: string[50];
ViewItem: TObject;
end;
const
IM_NONE = 0;
IM_LINEAR = 1;
var
Catalog: TList;
FFDF: TFileStream;
CatalogPos: LongInt;
FileIsOpened: Boolean;
FN: string;
FFArrayList: TSelfCleanList;
InterpolationMode: LongInt = IM_NONE;
procedure CreateFFDataFile(FileName: string);
procedure OpenFFDataFile(FileName: string);
procedure CloseFFDataFile;
procedure ReadCatalog;
procedure SaveCatalog;
procedure DeleteRecord(var CE: TCatalogElement);
procedure ReadArray(const CE: TCatalogElement; FFAR: TFFArrRec);
function GetFFArrays(ASiteList: TSiteList): Boolean;
function GetFFValue(SinTL: Double; SR: TAtom): Double;
function SearchElement(St: string): TCatalogElement;
implementation
procedure CreateFFDataFile(FileName: string);
var TempLong: LongInt;
begin
CloseFFDataFile;
Catalog := TList.Create;
try
FFDF := TFileStream.Create(FileName, fmCreate or fmShareDenyNone);
except
MessageDlg('Can''t create form - factors file...', mtError, [mbOk], 0);
FileIsOpened := False;
Exit;
end;
TempLong := SizeOf(TempLong);
CatalogPos := TempLong;
FFDF.Seek(0, soFromBeginning);
FFDF.Write(TempLong, SizeOf(TempLong));
FileIsOpened := True;
FN := FileName;
end;
procedure OpenFFDataFile(FileName: string);
begin
CloseFFDataFile;
Catalog := TList.Create;
try
FFDF := TFileStream.Create(FileName, fmOpenReadWrite or fmShareDenyNone);
except
MessageDlg('Can''t open form - factors file...', mtError, [mbOk], 0);
FileIsOpened := False;
Exit;
end;
FFDF.Seek(0, soFromBeginning);
FFDF.Read(CatalogPos, SizeOf(CatalogPos));
ReadCatalog;
FileIsOpened := True;
FN := FileName;
end;
procedure ReadCatalog;
var CE: TCatalogElement;
begin
FFDF.Seek(CatalogPos, soFromBeginning);
while FFDF.Position <> FFDF.Size do begin
CE := TCatalogElement.Create;
with CE do begin
FFDF.Read(NameOfElement, SizeOf(NameOfElement));
FFDF.Read(FullName, SizeOf(FullName));
FFDF.Read(NumberOfPoints, SizeOf(NumberOfPoints));
FFDF.Read(StepOfPoints, SizeOf(StepOfPoints));
FFDF.Read(StartPos, SizeOf(StartPos));
FFDF.Read(EndPos, SizeOf(EndPos));
FFDF.Read(Reserved1, SizeOf(Reserved1));
FFDF.Read(Reserved2, SizeOf(Reserved2));
FFDF.Read(Comments, SizeOf(Comments));
end;
Catalog.Add(CE);
end;
end;
procedure CloseFFDataFile;
begin
if FileIsOpened then begin
UtilizeObject(FFDF);
FFDF := nil;
UtilizeObject(Catalog);
Catalog := nil;
FileIsOpened := False;
end;
FN := '';
end;
procedure SaveCatalog;
var i: LongInt;
CE: TCatalogElement;
begin
CatalogPos := FFDF.Position;
for i := 0 to Catalog.Count - 1 do begin
CE := Catalog.Items[i];
with CE do begin
FFDF.Write(NameOfElement, SizeOf(NameOfElement));
FFDF.Write(FullName, SizeOf(FullName));
FFDF.Write(NumberOfPoints, SizeOf(NumberOfPoints));
FFDF.Write(StepOfPoints, SizeOf(StepOfPoints));
FFDF.Write(StartPos, SizeOf(StartPos));
FFDF.Write(EndPos, SizeOf(EndPos));
FFDF.Write(Reserved1, SizeOf(Reserved1));
FFDF.Write(Reserved2, SizeOf(Reserved2));
FFDF.Write(Comments, SizeOf(Comments));
end;
end;
FFDF.Seek(0, soFromBeginning);
FFDF.Write(CatalogPos, SizeOf(CatalogPos));
end;
procedure DeleteRecord(var CE: TCatalogElement);
var TempFile: TFileStream;
RequiredSpace: LongInt;
CatalogPos: LongInt;
ElementSize: LongInt;
i: LongInt;
CE2: TCatalogElement;
begin
FFDF.Seek(0, soFromBeginning);
FFDF.Read(CatalogPos, SizeOf(CatalogPos));
ElementSize := CE.NumberOfPoints * SizeOf(Double);
RequiredSpace := FFDF.Size - ElementSize - (FFDF.Size - CatalogPos);
if DiskFree(0) < RequiredSpace then begin
MessageDlg('Not enought disk space...', mtError, [mbOk], 0);
Exit;
end;
TempFile := TFileStream.Create(ExtractFilePath(FN)+'FFEditor.tmp', fmCreate);
TempFile.Seek(0, soFromBeginning);
FFDF.Seek(0, soFromBeginning);
TempFile.CopyFrom(FFDF, CE.StartPos);
FFDF.Seek(CE.StartPos + ElementSize, soFromBeginning);
if CatalogPos - FFDF.Position > 0 then
TempFile.CopyFrom(FFDF, CatalogPos - FFDF.Position);
for i := 0 to Catalog.Count - 1 do begin
CE2 := Catalog.Items[i];
if CE2 <> CE then
if CE2.StartPos >= CE.StartPos + ElementSize then
CE2.StartPos := CE2.StartPos - ElementSize;
end;
Catalog.Remove(CE);
UtilizeObject(CE);
UtilizeObject(FFDF);
UtilizeObject(TempFile);
DeleteFile(FN);
RenameFile(ExtractFilePath(FN)+'FFEditor.tmp', FN);
FFDF := TFileStream.Create(FN, fmOpenReadWrite or fmShareDenyNone);
FFDF.Seek(FFDF.Size, soFromBeginning);
SaveCatalog;
end;
function SearchElement(St: string): TCatalogElement;
var i: LongInt;
CE: TCatalogElement;
begin
for i := 0 to Catalog.Count - 1 do begin
CE := Catalog.Items[i];
if UpperCase(CE.NameOfElement) = UpperCase(St) then begin
SearchElement := CE;
Exit;
end;
end;
SearchElement := nil;
end;
function GetFFArrays(ASiteList: TSiteList): Boolean;
function HaveThisElement(const SR: TAtom): Boolean;
var i: LongInt;
FFAR: TFFArrRec;
begin
for i := 0 to FFArrayList.Count - 1 do
begin
FFAR := FFArrayList.Items[i];
if FFAR.NameOfElement = SR.Element then
begin
HaveThisElement := True;
Exit;
end;
end;
HaveThisElement := False;
end;
var i, j: LongInt;
TS: TSite;
SR: TAtom;
CE: TCatalogElement;
FFAR: TFFArrRec;
MagnStar: TWaveVector;
begin
FFArrayList.ClearAll;
if not FileIsOpened then begin GetFFArrays := False; Exit end;
for i := 0 to ASiteList.Count - 1 do
begin
TS := TSite(ASiteList.Items[i]);
MagnStar := TS.WaveVectorList.MagnStar;
if (not TS.Disabled) and (not TS.NotMagnetic) and (MagnStar <> nil) then
for j := 0 to TS.AtomList.Count - 1 do
begin
SR := TAtom(TS.AtomList.Items[j]);
if not HaveThisElement(SR) then
begin
CE := SearchElement(SR.Element);
if CE = nil then
begin
if SR.Position <> '' then
begin
MessageDlg('Can''t find element '+ SR.Element +
' in form - factors database...', mtError, [mbOk], 0);
FFArrayList.ClearAll;
GetFFArrays := False;
Exit;
end else Continue;
end;
FFAR := TFFArrRec.Create;
FFAR.NameOfElement := SR.Element;
ReadArray(CE, FFAR);
FFArrayList.Add(FFAR);
end;{if not HaveThisElement(SR) then...}
end;{for j := 0 to TS.AtomList.Count - 1 do...}
end;{for i := 0 to ASiteList.Count - 1 do...}
GetFFArrays := True;
end;
function GetFFValue(SinTL: Double;SR: TAtom): Double;
var TempDelta: Double;
i, j: LongInt;
FFAR: TFFArrRec;
begin
for j := 0 to FFArrayList.Count - 1 do
begin
FFAR := FFArrayList.Items[j];
if UpperCase(SR.Element) = UpperCase(FFAR.NameOfElement) then
with FFAR do
begin
case InterpolationMode of
IM_NONE :
begin
i := Round((SinTL / (NumberOfPoints * StepOfPoints)) *
(NumberOfPoints - 1));
Result := FFArray[i * 2];
Exit
end;
IM_LINEAR :
begin
i := Trunc((SinTL / 0.42) * 21);
if FFArray[i * 2 + 1] = SinTL then
begin
GetFFValue := FFArray[i * 2];
Exit;
end;
TempDelta := FFArray[(i + 1) * 2] - FFArray[i * 2];
TempDelta := (TempDelta / 0.02) * (SinTL - FFArray[i * 2 + 1]);
GetFFValue := FFArray[i * 2] + TempDelta;
Exit;
end;
end;{case InterpolationMode of...}
end;{With FFAR do...}
end;{for j := 0 to FFArrayList.Count - 1 do...}
Result := 0;
end;
procedure ReadArray(const CE: TCatalogElement; FFAR: TFFArrRec);
var i: LongInt;
TempDouble: Double;
TempDouble2: Double;
begin
FFDF.Seek(CE.StartPos, soFromBeginning);
FFAR.NumberOfPoints := CE.NumberOfPoints;
FFAR.StepOfPoints := CE.StepOfPoints;
for i := 0 to CE.NumberOfPoints - 1 do
begin
TempDouble := CE.StepOfPoints * i;
FFDF.Read(TempDouble2, SizeOf(Double));
FFAR.FFArray[2 * i] := TempDouble2;
FFAR.FFArray[2 * i + 1] := TempDouble;
end;
end;
initialization
FileIsOpened := False;
FFArrayList := TSelfCleanList.Create;
finalization
FFArrayList.ClearAll;
UtilizeObject(FFArrayList);
end.
|
/////////////////////////////////////////////////////////
// //
// FlexGraphics library //
// Copyright (c) 2002-2009, FlexGraphics software. //
// //
// History actions and groups //
// //
/////////////////////////////////////////////////////////
unit FlexActions;
{$I FlexDefs.inc}
interface
uses
Windows, Classes,
FlexBase, FlexProps, FlexHistory, FlexPath, FlexUtils;
type
TDocRectHistoryAction = class(TIdHistoryAction)
protected
FUndoDocRect: TRect;
FRedoDocRect: TRect;
FUndoExist: boolean;
FRedoExist: boolean;
class function DoIsRecordable(Source: TObject;
Parent: THistoryGroup): boolean; override;
procedure DoRecordAction(Source: TObject); override;
procedure DoUndo(Source: TObject); override;
procedure DoRedo(Source: TObject); override;
public
procedure OffsetUndo(const Diff: TPoint);
property UndoDocRect: TRect read FUndoDocRect write FUndoDocRect;
property RedoDocRect: TRect read FRedoDocRect write FRedoDocRect;
property UndoExist: boolean read FUndoExist write FUndoExist;
property RedoExist: boolean read FRedoExist write FRedoExist;
end;
TPointsHistoryActionInfo = record
Exist: boolean;
DocRect: TRect;
Points: TPointArray;
Types: TPointTypeArray;
end;
TPointsHistoryAction = class(TIdHistoryAction)
protected
FUndo: TPointsHistoryActionInfo;
FRedo: TPointsHistoryActionInfo;
class function DoIsRecordable(Source: TObject;
Parent: THistoryGroup): boolean; override;
procedure Save(var Info: TPointsHistoryActionInfo; Control: TFlexControl);
procedure Restore(var Info: TPointsHistoryActionInfo; Control: TFlexControl);
procedure DoRecordAction(Source: TObject); override;
procedure DoUndo(Source: TObject); override;
procedure DoRedo(Source: TObject); override;
public
procedure OffsetUndo(const Diff: TPoint);
procedure SetUndoSavedDocRect(Control: TFlexControl);
property UndoInfo: TPointsHistoryActionInfo read FUndo write FUndo;
property RedoInfo: TPointsHistoryActionInfo read FRedo write FRedo;
end;
TOrderHistoryActionInfo = record
Exist: boolean;
Index: integer;
ParentId: LongWord;
LayerId: LongWord;
end;
TOrderHistoryAction = class(TIdHistoryAction)
protected
FUndo: TOrderHistoryActionInfo;
FRedo: TOrderHistoryActionInfo;
procedure Save(var Info: TOrderHistoryActionInfo; Control: TFlexControl);
procedure Restore(var Info: TOrderHistoryActionInfo; Control: TFlexControl;
CurIndex: integer);
procedure DoRecordAction(Source: TObject); override;
procedure DoUndo(Source: TObject); override;
procedure DoRedo(Source: TObject); override;
public
property UndoInfo: TOrderHistoryActionInfo read FUndo;
property RedoInfo: TOrderHistoryActionInfo read FRedo;
end;
TGroupUngroupHistoryAction = class(TIdHistoryAction)
protected
FSourcePanel: TFlexPanel;
FGroupClass: TFlexGroupClass;
FSelected: TList;
procedure SelectControls;
procedure Save(Source: TFlexGroup);
public
destructor Destroy; override;
end;
TControlGroupHistoryAction = class(TGroupUngroupHistoryAction)
protected
procedure DoUndo(Source: TObject); override;
procedure DoRedo(Source: TObject); override;
procedure DoRecordAction(Source: TObject); override;
end;
TControlUngroupHistoryAction = class(TGroupUngroupHistoryAction)
protected
procedure DoUndo(Source: TObject); override;
procedure DoRedo(Source: TObject); override;
procedure DoRecordAction(Source: TObject); override;
end;
TCustomControlHistoryAction = class(TIdHistoryAction)
protected
function ProcessSource(Stream: TStream; Source: TObject;
DoLoad: boolean): boolean; override;
public
class function RecordAction(
Source: TFlexControl): TCustomControlHistoryAction;
end;
TCreateDestroyHistoryGroup = class(THistoryGroup)
protected
FStream: TMemoryStream;
FSourcePanel: TFlexPanel;
FSourceId: LongWord;
FParentId: LongWord;
FParentIndex: integer;
class function DoIsRecordable(Source: TObject;
Parent: THistoryGroup): boolean; override;
procedure SaveSource(Source: TObject);
function ProcessSource(Source: TFlexControl; DoLoad: boolean): boolean;
public
destructor Destroy; override;
property SourcePanel: TFlexPanel read FSourcePanel write FSourcePanel;
property SourceId: LongWord read FSourceId write FSourceId;
property ParentId: LongWord read FParentId write FParentId;
property ParentIndex: integer read FParentIndex write FParentIndex;
property Stream: TMemoryStream read FStream;
end;
TControlCreateHistoryGroup = class(TCreateDestroyHistoryGroup)
protected
procedure DoUndo(Source: TObject); override;
procedure DoRedo(Source: TObject); override;
procedure DoRecordAction(Source: TObject); override;
end;
TControlDestroyHistoryGroup = class(TCreateDestroyHistoryGroup)
protected
procedure DoUndo(Source: TObject); override;
procedure DoRedo(Source: TObject); override;
procedure DoRecordAction(Source: TObject); override;
end;
TFlexPanelHistoryGroup = class(THistoryGroup)
protected
FSourcePanel: TFlexPanel;
public
constructor Create(AOwner: THistory; AParent: THistoryGroup); override;
property SourcePanel: TFlexPanel read FSourcePanel write FSourcePanel;
end;
TPanelSizeMoveHistoryGroup = class(TFlexPanelHistoryGroup);
TPanelAlignHistoryGroup = class(TFlexPanelHistoryGroup);
TPanelCreateControlsHistoryGroup = class(TFlexPanelHistoryGroup);
TPanelDestroyControlsHistoryGroup = class(TFlexPanelHistoryGroup);
TPanelUngroupControlsHistoryGroup = class(TFlexPanelHistoryGroup);
TPanelDuplicateHistoryGroup = class(TFlexPanelHistoryGroup);
TPanelCloneHistoryGroup = class(TFlexPanelHistoryGroup);
TPanelOrderHistoryGroup = class(TFlexPanelHistoryGroup);
TPanelPointsHistoryGroup = class(TFlexPanelHistoryGroup);
TPanelRerouteHistoryGroup = class(TFlexPanelHistoryGroup);
TPanelColorHistoryGroup = class(TFlexPanelHistoryGroup);
TPanelPropsHistoryGroup = class(TFlexPanelHistoryGroup);
implementation
uses
FlexControls;
type
TFlexControlOpen = class(TFlexControl);
TFlexCurveOpen = class(TFlexCurve);
// TDocRectHistoryAction //////////////////////////////////////////////////////
class function TDocRectHistoryAction.DoIsRecordable(Source: TObject;
Parent: THistoryGroup): boolean;
var i: integer;
begin
Result := (Source is TFlexControl) and
( (TFlexControl(Source).UpdateCounter > 0) or
(fsEndUpdating in TFlexControl(Source).State) );
// Check TPointsHistoryAction existance
if not Result or not Assigned(Parent) then exit;
for i:=0 to Parent.ActionCount-1 do
if (Parent[i] is TPointsHistoryAction) and
(TPointsHistoryAction(Parent[i]).SourceId =
TFlexControl(Source).IdProp.Value) then begin
Result := false;
break;
end;
end;
procedure TDocRectHistoryAction.DoRecordAction(Source: TObject);
begin
FUndoDocRect := TFlexControlOpen(Source).FSavedDocRect;
FUndoExist := true;
with FUndoDocRect do
FDestroyAfterEnd := (Left = 0) and (Top = 0) and (Right <= 1) and (Bottom <= 1);
end;
procedure TDocRectHistoryAction.DoRedo(Source: TObject);
begin
if not FRedoExist or not (Source is TFlexControl) then exit;
if Source is TFlexConnector then TFlexConnector(Source).BeginLinkUpdate;
try
TFlexControl(Source).DocRect := FRedoDocRect;
finally
if Source is TFlexConnector then TFlexConnector(Source).EndLinkUpdate;
end;
end;
procedure TDocRectHistoryAction.DoUndo(Source: TObject);
begin
if not FUndoExist or not (Source is TFlexControl) then exit;
if not FRedoExist then begin
FRedoDocRect := TFlexControl(Source).DocRect;
FRedoExist := true;
end;
if Source is TFlexConnector then TFlexConnector(Source).BeginLinkUpdate;
try
TFlexControl(Source).DocRect := FUndoDocRect;
finally
if Source is TFlexConnector then TFlexConnector(Source).EndLinkUpdate;
end;
end;
procedure TDocRectHistoryAction.OffsetUndo(const Diff: TPoint);
begin
if FUndoExist then OffsetRect(FUndoDocRect, Diff.X, Diff.Y);
end;
// TOrderHistoryAction ////////////////////////////////////////////////////////
procedure TOrderHistoryAction.Restore(var Info: TOrderHistoryActionInfo;
Control: TFlexControl; CurIndex: integer);
begin
// Restore parent if need
if Info.ParentId <> 0 then begin
if not Assigned(Control.Parent) or
(Info.ParentId <> Control.Parent.IdProp.Value) then
Control.Parent := Control.Owner.FindControlByID(Info.ParentId);
end else
Control.Parent := Nil;
// Restore layer if need
if Info.LayerId <> 0 then begin
if not Assigned(Control.Layer) or
(Info.LayerId <> Control.Layer.IdProp.Value) then
Control.Layer := TFlexLayer(
Control.Owner.FindControlByID(Info.LayerId, Control.Owner.Layers))
end else
Control.Layer := Nil;
// Restore order
if Assigned(Control.Parent) then begin
if CurIndex < 0 then CurIndex := Control.Parent.IndexOf(Control);
if CurIndex >= 0 then Control.Parent.ChangeOrder(CurIndex, Info.Index);
end;
end;
procedure TOrderHistoryAction.Save(var Info: TOrderHistoryActionInfo;
Control: TFlexControl);
begin
if Assigned(Control.Parent)
then Info.ParentId := Control.Parent.IdProp.Value
else Info.ParentId := 0;
if Assigned(Control.Layer)
then Info.LayerId := Control.Layer.IdProp.Value
else Info.LayerId := 0;
if Assigned(Control.Parent)
then Info.Index := Control.Parent.IndexOf(Control)
else Info.Index := -1;
Info.Exist := true;
end;
procedure TOrderHistoryAction.DoRecordAction(Source: TObject);
begin
if not (Source is TFlexControl) {or
not Assigned(TFlexControl(Source).Parent)} then exit;
// Create undo
Save(FUndo, TFlexControl(Source));
end;
procedure TOrderHistoryAction.DoUndo(Source: TObject);
begin
if not (Source is TFlexControl) or not FUndo.Exist then exit;
// Create redo
Save(FRedo, TFlexControl(Source));
// Undo
Restore(FUndo, TFlexControl(Source), FRedo.Index);
end;
procedure TOrderHistoryAction.DoRedo(Source: TObject);
begin
if not (Source is TFlexControl) or not FRedo.Exist then exit;
// Redo
Restore(FRedo, TFlexControl(Source), FUndo.Index);
end;
// TPointsHistoryAction ///////////////////////////////////////////////////////
procedure TPointsHistoryAction.DoRecordAction(Source: TObject);
begin
if not (Source is TFlexControl) then exit;
// Create undo
Save(FUndo, TFlexControl(Source));
end;
procedure TPointsHistoryAction.DoRedo(Source: TObject);
begin
if not (Source is TFlexControl) or not FRedo.Exist then exit;
// Redo
Restore(FRedo, TFlexControl(Source));
end;
procedure TPointsHistoryAction.DoUndo(Source: TObject);
begin
if not (Source is TFlexControl) or not FUndo.Exist then exit;
// Create redo
Save(FRedo, TFlexControl(Source));
// Undo
Restore(FUndo, TFlexControl(Source));
end;
procedure TPointsHistoryAction.Restore(var Info: TPointsHistoryActionInfo;
Control: TFlexControl);
begin
if not Info.Exist then exit;
if Control is TFlexConnector then TFlexConnector(Control).BeginLinkUpdate;
try
Control.DocRect := Info.DocRect;
Control.SetPointsEx(Info.Points, Info.Types);
finally
if Control is TFlexConnector then TFlexConnector(Control).EndLinkUpdate;
end;
end;
class function TPointsHistoryAction.DoIsRecordable(Source: TObject;
Parent: THistoryGroup): boolean;
begin
Result :=
(inherited DoIsRecordable(Source, Parent)) and not
( (Source is TFlexEllipse) and
not TFlexEllipse(Source).IsNeedHistoryPointsAction );
end;
procedure TPointsHistoryAction.Save(var Info: TPointsHistoryActionInfo;
Control: TFlexControl);
var i: integer;
begin
if Info.Exist then exit;
Control.GetPointsEx(Info.Points, Info.Types);
if fsResizing in Control.State then begin
with TFlexControlOpen(Control) do begin
Info.DocRect := FResizingRect;
OffsetRect(Info.DocRect, FResizingTopLeft.X, FResizingTopLeft.Y);
end;
if Control is TFlexCurve then with TFlexCurveOpen(Control) do begin
SetLength(Info.Points, Length(FResizePoints));
for i:=0 to Length(Info.Points)-1 do Info.Points[i] := FResizePoints[i];
end;
end else
Info.DocRect := Control.DocRect;
//else Info.DocRect := TFlexControlOpen(Control).FSavedDocRect;
Info.Exist := true;
end;
procedure TPointsHistoryAction.OffsetUndo(const Diff: TPoint);
begin
if FUndo.Exist then OffsetRect(FUndo.DocRect, Diff.X, Diff.Y);
end;
procedure TPointsHistoryAction.SetUndoSavedDocRect(Control: TFlexControl);
begin
if FUndo.Exist and not (fsResizing in Control.State) then
FUndo.DocRect := TFlexControlOpen(Control).FSavedDocRect;
end;
// TGroupUngroupHistoryAction /////////////////////////////////////////////////
destructor TGroupUngroupHistoryAction.Destroy;
begin
inherited;
FSelected.Free;
end;
procedure TGroupUngroupHistoryAction.Save(Source: TFlexGroup);
var i: integer;
begin
if not Assigned(Source) or not Assigned(Source.Owner) then exit;
FGroupClass := TFlexGroupClass(Source.ClassType);
FSourcePanel := Source.Owner;
FSourceId := Source.IdProp.Value;
if not Assigned(FSelected)
then FSelected := TList.Create
else FSelected.Clear;
// Store child controls
for i:=0 to Source.Count-1 do
FSelected.Add(pointer(Source[i].IdProp.Value));
end;
procedure TGroupUngroupHistoryAction.SelectControls;
var i: integer;
Control: TFlexControl;
begin
FSourcePanel.UnselectAll;
for i:=0 to FSelected.Count-1 do begin
Control := FSourcePanel.FindControlByID(LongWord(FSelected[i]));
if Assigned(Control) then FSourcePanel.Select(Control);
end;
end;
// TControlGroupHistoryAction /////////////////////////////////////////////////
procedure TControlGroupHistoryAction.DoRecordAction(Source: TObject);
begin
if not (Source is TFlexGroup) or
not Assigned(TFlexGroup(Source).Owner) then exit;
// Init group operation
Save(TFlexGroup(Source));
end;
procedure TControlGroupHistoryAction.DoRedo(Source: TObject);
var GroupControl: TFlexGroup;
begin
if not Assigned(FSourcePanel) then exit;
// Group
SelectControls;
GroupControl := FSourcePanel.Group(FGroupClass);
if Assigned(GroupControl) then GroupControl.IdProp.Value := FSourceId;
end;
procedure TControlGroupHistoryAction.DoUndo(Source: TObject);
begin
if not Assigned(FSourcePanel) or
not (Source is TFlexGroup) or
(TFlexGroup(Source).Owner <> FSourcePanel) then exit;
// Ungroup
with FSourcePanel do begin
UnselectAll;
Select(TFlexGroup(Source));
Ungroup;
end;
end;
// TControlUngroupHistoryAction ///////////////////////////////////////////////
procedure TControlUngroupHistoryAction.DoRecordAction(Source: TObject);
begin
if not (Source is TFlexGroup) or
not Assigned(TFlexGroup(Source).Owner) then exit;
// Init ungroup operation
Save(TFlexGroup(Source));
end;
procedure TControlUngroupHistoryAction.DoRedo(Source: TObject);
begin
if not Assigned(FSourcePanel) or
not (Source is TFlexGroup) or
(TFlexGroup(Source).Owner <> FSourcePanel) then exit;
// Ungroup
with FSourcePanel do begin
UnselectAll;
Select(TFlexGroup(Source));
Ungroup;
end;
end;
procedure TControlUngroupHistoryAction.DoUndo(Source: TObject);
var GroupControl: TFlexGroup;
begin
if not Assigned(FSourcePanel) then exit;
// Group
SelectControls;
GroupControl := FSourcePanel.Group(FGroupClass);
if Assigned(GroupControl) then GroupControl.IdProp.Value := FSourceId;
end;
// TCustomControlHistoryAction ////////////////////////////////////////////////
class function TCustomControlHistoryAction.RecordAction(
Source: TFlexControl): TCustomControlHistoryAction;
var History: THistory;
begin
Result := Nil;
if not Assigned(Source) or not Assigned(Source.Owner) then exit;
History := Source.Owner.History;
Result := TCustomControlHistoryAction(History.RecordAction(Self, Source));
end;
function TCustomControlHistoryAction.ProcessSource(Stream: TStream;
Source: TObject; DoLoad: boolean): boolean;
var Filer: TFlexFiler;
Control: TFlexControl;
Props: TPropList;
FirstStr: string;
begin
Result := false;
if not (Source is TFlexControl) then exit;
Control := TFlexControl(Source);
Props := Control.Props;
Filer := Nil;
// Set PropList History state (to skip read-only checking in load phase)
Props.HistoryStateForList := Owner.State;
try
// Create filer
Filer := TFlexFiler.Create(Stream);
if DoLoad then begin
if Control.Owner.IsLoading then Props.RefList := Control.Owner.PropRefList;
// Load control properties
while Filer.LoadStrCheck(FirstStr) do
Props.LoadProperty(Filer, FirstStr);
Result := true;
end else
// Save control properties
Result := Props.SaveToFiler(Filer, '', true);
finally
Props.HistoryStateForList := hsIdle;
Props.RefList := Nil;
Filer.Free;
end;
end;
// TCreateDestroyHistoryGroup /////////////////////////////////////////////////
destructor TCreateDestroyHistoryGroup.Destroy;
begin
FStream.Free();
inherited;
end;
class function TCreateDestroyHistoryGroup.DoIsRecordable(Source: TObject;
Parent: THistoryGroup): boolean;
begin
Result := Assigned(Source) and (Source is TFlexControl) and
not (Assigned(Parent) and (Parent is TCreateDestroyHistoryGroup));
if Result then
Result := inherited DoIsRecordable(Source, Parent);
end;
procedure TCreateDestroyHistoryGroup.SaveSource(Source: TObject);
var Control: TFlexControl;
begin
if not Assigned(Source) or not (Source is TFlexControl) then exit;
Control := TFlexControl(Source);
FSourcePanel := Control.Owner;
FSourceId := Control.IdProp.Value;
if Assigned(Control.Parent) then begin
FParentId := Control.Parent.IdProp.Value;
FParentIndex := Control.Parent.IndexOf(Control);
end else begin
FParentId := 0;
FParentIndex := -1;
end;
end;
function TCreateDestroyHistoryGroup.ProcessSource(Source: TFlexControl;
DoLoad: boolean): boolean;
var Filer: TFlexFiler;
ParentControl: TFlexControl;
NewControl: TFlexControl;
CurIndex: integer;
begin
Result := false;
// Create stream
if DoLoad then begin
if not Assigned(FStream) then exit;
end else
if not Assigned(FStream)
then FStream := TMemoryStream.Create
else FStream.Size := 0;
// Create filer
Filer := TFlexFiler.Create(FStream);
try
if DoLoad then begin
// Create and load flex control
FStream.Position := 0;
if FParentId <> 0
then ParentControl := FSourcePanel.FindControlByID(FParentId)
else ParentControl := Nil;
NewControl :=
SourcePanel.LoadFlexControl(Filer, ParentControl, Filer.LoadStr, true);
if (FParentIndex >= 0) and Assigned(ParentControl) then begin
CurIndex := ParentControl.IndexOf(NewControl);
ParentControl.ChangeOrder(CurIndex, FParentIndex);
end;
Result := Assigned(NewControl);
end else begin
// Save flex control
Result := Assigned(Source);
if not Result then exit;
Source.SaveToFiler(Filer, '');
end;
finally
Filer.Free;
end;
end;
// TControlCreateHistoryGroup /////////////////////////////////////////////////
procedure TControlCreateHistoryGroup.DoRecordAction(Source: TObject);
begin
SaveSource(Source);
end;
procedure TControlCreateHistoryGroup.DoRedo(Source: TObject);
begin
// Recreate source control
ProcessSource(Nil, True);
end;
procedure TControlCreateHistoryGroup.DoUndo(Source: TObject);
begin
if not (Source is TFlexControl) then exit;
// Save control for redo
ProcessSource(TFlexControl(Source), False);
// Destroy source
Source.Free;
end;
// TControlDestroyHistoryGroup ////////////////////////////////////////////////
procedure TControlDestroyHistoryGroup.DoRecordAction(Source: TObject);
begin
SaveSource(Source);
// Save control for Undo
ProcessSource(TFlexControl(Source), False);
end;
procedure TControlDestroyHistoryGroup.DoRedo(Source: TObject);
begin
if not (Source is TFlexControl) then exit;
// Just destroy source
Source.Free;
end;
procedure TControlDestroyHistoryGroup.DoUndo(Source: TObject);
begin
// Recreate source control
ProcessSource(Nil, True);
end;
// TFlexPanelHistoryGroup /////////////////////////////////////////////////////
constructor TFlexPanelHistoryGroup.Create(AOwner: THistory;
AParent: THistoryGroup);
begin
inherited;
FDestroyIfEmpty := true;
end;
///////////////////////////////////////////////////////////////////////////////
procedure RegisterHistoryActions;
begin
// Control actions
THistory.RegisterAction(TDocRectHistoryAction);
THistory.RegisterAction(TOrderHistoryAction);
THistory.RegisterAction(TPointsHistoryAction);
THistory.RegisterAction(TControlCreateHistoryGroup);
THistory.RegisterAction(TControlDestroyHistoryGroup);
THistory.RegisterAction(TControlGroupHistoryAction);
THistory.RegisterAction(TControlUngroupHistoryAction);
// Panel actions
THistory.RegisterAction(TPanelSizeMoveHistoryGroup);
THistory.RegisterAction(TPanelAlignHistoryGroup);
THistory.RegisterAction(TPanelCreateControlsHistoryGroup);
THistory.RegisterAction(TPanelDestroyControlsHistoryGroup);
THistory.RegisterAction(TPanelUngroupControlsHistoryGroup);
THistory.RegisterAction(TPanelDuplicateHistoryGroup);
THistory.RegisterAction(TPanelCloneHistoryGroup);
THistory.RegisterAction(TPanelOrderHistoryGroup);
THistory.RegisterAction(TPanelPointsHistoryGroup);
THistory.RegisterAction(TPanelRerouteHistoryGroup);
THistory.RegisterAction(TPanelColorHistoryGroup);
THistory.RegisterAction(TPanelPropsHistoryGroup);
end;
initialization
RegisterHistoryActions;
end.
|
unit fNoteBA;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, ORCtrls, StdCtrls, ORFn, uTIU, fBase508Form,
VA508AccessibilityManager;
type
TfrmNotesByAuthor = class(TfrmBase508Form)
pnlBase: TORAutoPanel;
lblAuthor: TLabel;
radSort: TRadioGroup;
cboAuthor: TORComboBox;
cmdOK: TButton;
cmdCancel: TButton;
procedure cboAuthorNeedData(Sender: TObject; const StartFrom: string;
Direction, InsertAt: Integer);
procedure cmdCancelClick(Sender: TObject);
procedure cmdOKClick(Sender: TObject);
private
FChanged: Boolean;
FAuthor: Int64;
FAuthorName: string;
FAscending: Boolean;
end;
TAuthorContext = record
Changed: Boolean;
Author: Int64;
AuthorName: string;
Ascending: Boolean;
end;
procedure SelectAuthor(FontSize: Integer; CurrentContext: TTIUContext; var AuthorContext: TAuthorContext);
implementation
{$R *.DFM}
uses rTIU, rCore, uCore;
const
TX_AUTH_TEXT = 'Select a progress note author or press Cancel.';
TX_AUTH_CAP = 'Missing Author';
procedure SelectAuthor(FontSize: Integer; CurrentContext: TTIUContext; var AuthorContext: TAuthorContext);
{ displays author select form for progress notes and returns a record of the selection }
var
frmNotesByAuthor: TfrmNotesByAuthor;
W, H: integer;
CurrentAuthor: Int64;
begin
frmNotesByAuthor := TfrmNotesByAuthor.Create(Application);
try
with frmNotesByAuthor do
begin
Font.Size := FontSize;
W := ClientWidth;
H := ClientHeight;
ResizeToFont(FontSize, W, H);
ClientWidth := W; pnlBase.Width := W;
ClientHeight := H; pnlBase.Height := W;
FChanged := False;
CurrentAuthor := CurrentContext.Author;
with cboAuthor do
if CurrentAuthor > 0 then
begin
InitLongList(ExternalName(CurrentAuthor, 200));
SelectByIEN(CurrentAuthor);
end
else
begin
InitLongList(User.Name);
SelectByIEN(User.DUZ);
end;
FAscending := CurrentContext.TreeAscending;
with radSort do if FAscending then ItemIndex := 0 else ItemIndex := 1;
ShowModal;
with AuthorContext do
begin
Changed := FChanged;
Author := FAuthor;
AuthorName := FAuthorName;
Ascending := FAscending;
end; {with AuthorContext}
end; {with frmNotesByAuthor}
finally
frmNotesByAuthor.Release;
end;
end;
procedure TfrmNotesByAuthor.cboAuthorNeedData(Sender: TObject; const StartFrom: string;
Direction, InsertAt: Integer);
begin
cboAuthor.ForDataUse(SubSetOfActiveAndInactivePersons(StartFrom, Direction));
end;
procedure TfrmNotesByAuthor.cmdCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfrmNotesByAuthor.cmdOKClick(Sender: TObject);
begin
if cboAuthor.ItemIEN = 0 then
begin
InfoBox(TX_AUTH_TEXT, TX_AUTH_CAP, MB_OK or MB_ICONWARNING);
Exit;
end;
FChanged := True;
FAuthor := cboAuthor.ItemIEN;
FAuthorName := cboAuthor.DisplayText[cboAuthor.ItemIndex];
FAscending := radSort.ItemIndex = 0;
Close;
end;
end.
|
unit mCoverSheetDisplayPanel;
{
================================================================================
*
* Application: CPRS - CoverSheet
* Developer: doma.user@domain.ext
* Site: Salt Lake City ISC
* Date: 2015-12-04
*
* Description: Inherited from TfraGridPanelFrame. This display panel
* provides the minimum functionality for displaying anything
* in the CPRS CoverSheet.
*
* Notes: This frame is an ancestor object and heavily inherited from.
* ABSOLUTELY NO CHANGES SHOULD BE MADE WITHOUT FIRST
* CONFERRING WITH THE CPRS DEVELOPMENT TEAM ABOUT POSSIBLE
* RAMIFICATIONS WITH DESCENDANT FRAMES.
*
================================================================================
}
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
System.ImageList,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ImgList,
Vcl.Menus,
Vcl.Buttons,
Vcl.StdCtrls,
Vcl.ExtCtrls,
iGridPanelIntf,
iCoverSheetIntf,
mGridPanelFrame;
type
TfraCoverSheetDisplayPanel = class(TfraGridPanelFrame, ICoverSheetDisplayPanel, ICPRS508)
private
fParam: ICoverSheetParam;
protected
{ Protected declarations }
function getParam: ICoverSheetParam; virtual;
procedure setParam(const aValue: ICoverSheetParam); virtual;
function getIsFinishedLoading: boolean; virtual;
{ Introduced events }
procedure OnClearPtData(Sender: TObject); virtual;
procedure OnBeginUpdate(Sender: TObject); virtual;
procedure OnEndUpdate(Sender: TObject); virtual;
public
{ Public declarations }
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
end;
var
fraCoverSheetDisplayPanel: TfraCoverSheetDisplayPanel;
implementation
{$R *.dfm}
{ TfraCoverSheetDisplayPanel }
constructor TfraCoverSheetDisplayPanel.Create(aOwner: TComponent);
begin
inherited;
end;
destructor TfraCoverSheetDisplayPanel.Destroy;
begin
inherited;
end;
procedure TfraCoverSheetDisplayPanel.OnBeginUpdate(Sender: TObject);
begin
//
end;
procedure TfraCoverSheetDisplayPanel.OnClearPtData(Sender: TObject);
begin
//
end;
procedure TfraCoverSheetDisplayPanel.OnEndUpdate(Sender: TObject);
begin
//
end;
function TfraCoverSheetDisplayPanel.getIsFinishedLoading: boolean;
begin
Result := True;
end;
function TfraCoverSheetDisplayPanel.getParam: ICoverSheetParam;
begin
Supports(fParam, ICoverSheetParam, Result);
end;
procedure TfraCoverSheetDisplayPanel.setParam(const aValue: ICoverSheetParam);
begin
Supports(aValue, ICoverSheetParam, fParam);
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit ToolIntf deprecated;
interface
uses Winapi.Windows, Winapi.ActiveX, System.Classes, VirtIntf, EditIntf, FileIntf;
type
TIMenuItemIntf = class;
TIMenuFlag = (mfInvalid, mfEnabled, mfVisible, mfChecked, mfBreak, mfBarBreak,
mfRadioItem);
TIMenuFlags = set of TIMenuFlag;
TIMenuClickEvent = procedure (Sender: TIMenuItemIntf) of object;
{ The TIMenuItemIntf class is created by Delphi. This is simply a virtual
interface to an actual menu item found in the IDE. It is the responsibility
of the client to destroy *all* menu items which it created. Failure to
properly clean-up will result in unpredictable behaviour.
NOTE: Using functions that returns a TIMenuItemIntf should be done with
care. Unless created by a particular add-in tool, do not hold these
interfaces for long as the underlying actual VCL TMenuItem may be
destroyed without any notification. In practice, this only pertains
to Delphi created menus or menus created by other add-in tools.
It is also the responsibility of the user to free these interfaces
when finished. Any attempt to modify a menu item that was created
by Delphi will fail.
DestroyMenuItem - If this menu was created by through the interface, use
this function to destroy the associated menu item. This
function will *not* allow any Delphi created menus to
be destroyed.
GetItemCount
GetItem - Use these functions to iterate through the menu tree.
All TIMenuItemIntfs must be freed by the caller.
GetName - Returns the menu item name associated with the VCL menu
object. (Including internal Delphi menu names).
GetParent - Returns an interface to the parent menu item.
GetCaption
SetCaption - Methods to get/set the caption of the menu item.
GetShortCut
SetShortCut - Methods to get/set the short cut of the menu item.
GetFlags
SetFlags - Use GetFlags and SetFlags to query and set the state of
the menu item. For SetFlags, a mask indicating which
items to affect must be passed along with the actual
value of the flag.
GetGroupIndex
SetGroupIndex - Methods to get/set the GroupIndex property of a
TMenuItem. This is useful for specifying values for
grouped radio menus.
GetHint
SetHint - Methods to get/set the Hint proeprty of a TMenuItem.
NOTE: The IDE currently ignores this property.
GetContext
SetContext - Methods to get/set the help context ID of a TMenuItem.
GetOnClick
SetOnClick - Methods to get/set the OnClick property if the TMenuItem.
InsertItem - Creates and inserts a new sub menu item into the menu.
If (Index < 0) or (Index >= ItemCount) then the
operation is an append.
}
TIMenuItemIntf = class(TInterface)
public
function DestroyMenuItem: Boolean; virtual; stdcall; abstract;
function GetIndex: Integer; virtual; stdcall; abstract;
function GetItemCount: Integer; virtual; stdcall; abstract;
function GetItem(Index: Integer): TIMenuItemIntf; virtual; stdcall; abstract;
function GetName: string; virtual; stdcall; abstract;
function GetParent: TIMenuItemIntf; virtual; stdcall; abstract;
function GetCaption: string; virtual; stdcall; abstract;
function SetCaption(const Caption: string): Boolean; virtual; stdcall; abstract;
function GetShortCut: Integer; virtual; stdcall; abstract;
function SetShortCut(ShortCut: Integer): Boolean; virtual; stdcall; abstract;
function GetFlags: TIMenuFlags; virtual; stdcall; abstract;
function SetFlags(Mask, Flags: TIMenuFlags): Boolean; virtual; stdcall; abstract;
function GetGroupIndex: Integer; virtual; stdcall; abstract;
function SetGroupIndex(GroupIndex: Integer): Boolean; virtual; stdcall; abstract;
function GetHint: string; virtual; stdcall; abstract;
function SetHint(Hint: string): Boolean; virtual; stdcall; abstract;
function GetContext: Integer; virtual; stdcall; abstract;
function SetContext(Context: Integer): Boolean; virtual; stdcall; abstract;
function GetOnClick: TIMenuClickEvent; virtual; stdcall; abstract;
function SetOnClick(Click: TIMenuClickEvent): Boolean; virtual; stdcall; abstract;
function InsertItem(Index: Integer; Caption, Name, Hint: string;
ShortCut, Context, GroupIndex: Integer; Flags: TIMenuFlags;
EventHandler: TIMenuClickEvent): TIMenuItemIntf; virtual; stdcall; abstract;
end;
{ The TIMainMenuIntf class represents the Delphi main menu.
GetMenuItems - Returns the menu representing the top level menus.
FinMenuItem - Given the VCL component name, returns the corresponding
TIMenuItemIntf.
}
TIMainMenuIntf = class(TInterface)
public
function GetMenuItems: TIMenuItemIntf; virtual; stdcall; abstract;
function FindMenuItem(const Name: string): TIMenuItemIntf; virtual; stdcall; abstract;
end;
{ The TIAddInNotifier allows an add-in tool to register a descendant of this
type with Delphi in order to receive notifications about certian events
within Delphi. It is the resposibility of the add-in tool to unregister
and free this class when shutting down.
FileNotification - Called whenever an operation is performed from the
FileMenu (or through the TIToolInterface).
fnFileOpening - The given filename is about to be opened. Set
Cancel to True to prevent the operation.
fnFileOpened - The given file has been successfully opened.
Modifications to Cancel have no effect.
fnFileClosing - The given file is about to be closed. Set Cancel
to True to prevent the file from closing.
fnProjectOpening - The given project is about to be opened. Set
Cancel to True to prevent the operation.
fnProjectOpened - The given project has been successfully opened.
Modifications to Cancel have no effect.
fnProjectClosing - The given project is about to be closed. Set
Cancel to True to prevent the project from closing.
fnAddedToProject - The given file was added to the project.
fnRemovedFromProject - The given file was removed from the project.
fnDefaultDesktopSave
fnDefaultDekstopLoad
fnProjectDesktopSave
fnProjectDesktopLoad - The given filename represents a desktop is
being loaded or saved. The desktop file is
in standard .INI file format. Add in written
using Delphi can use the TIniFile component
to add and retrieve information from this file.
Modifying Cancel has no effect.
fnPackageInstalled - Sent when a package has been installed/uninstalled.
Modifying Cancel has no effect.
EventNotification - Called whenever various non-file related events occur.
enBeforeCompile - Called right before a project compile is started. All
source modules have been updated. Set Cancel to True to
cancel the compile.
enAfterCompile - Called right after the compile is completed. Cancel
will be True if successful, False otherwise.
NOTE: Modifying Cancel should be done with care. Multiple notifiers
could interact, yielding unpredictable results. Notifiers are
called in the reverse order in which they are registered. There
is also no way to guarantee the registration order of the
notifiers.
}
TFileNotification = (fnFileOpening, fnFileOpened, fnFileClosing,
fnProjectOpening, fnProjectOpened, fnProjectClosing, fnAddedToProject,
fnRemovedFromProject, fnDefaultDesktopLoad, fnDefaultDesktopSave,
fnProjectDesktopLoad, fnprojectDesktopSave, fnPackageInstalled,
fnPackageUninstalled);
TEventNotification = (enBeforeCompile, enAfterCompile);
TIAddInNotifier = class(TInterface)
public
procedure FileNotification(NotifyCode: TFileNotification;
const FileName: string; var Cancel: Boolean); virtual; stdcall; abstract;
procedure EventNotification(NotifyCode: TEventNotification;
var Cancel: Boolean); virtual; stdcall; abstract;
end;
{ The Tool services object is created on the application side, and is
passed to the VCS/Expert Manager DLL during initialization. Note that
the application is responsible for creating and freeing the interface
object, and the client should never free the interface.
The following functions are available to the client:
( Actions )
CloseProject - returns True if no project open, or if the currently
open project can be closed.
OpenProject - returns True if the named project can be opened. Pass an
empty string to create a new project and main form.
OpenProjectInfo - returns True if the named project file can be opened.
This routine bypasses all the normal project load
features (such as loading a desktop file, showing
the source code, etc), and simply opens the .DPR and
.DOF files.
SaveProject - returns True if the project is unmodified, if there
is no project open, or if the open project can be saved.
CloseFile - returns True if the specified file is not currently
open, or if it can be closed.
OpenFile - returns True if the specified file is already open
or can be opened.
ReloadFile - returns True if the file is already open and was
reloaded from disk. (NOTE: This will not perform any
checking of the current editor state).
ModalDialogBox - used by non-VCL DLL's to present a dialog box which is
modal. Note that DLLs written using VCL can simply call
a form's ShowModal function.
CreateModule - Will create new module from memory images of the source
and, optionally, the form file. The TCreateModuleFlags are:
cmAddToProject - Add the new module to the currently open project.
cmShowSource - Show the source file in the top-most editor window.
cmShowForm - If a form is created, show it above the source.
cmUnNamed - Will mark the module as unnamed which will cause the
SaveAs dialog to show the first time the user attempts to
save the file.
cmNewUnit - Creates a new unit and adds it to the current project.
NOTE: all other parameters are ignored.
cmNewForm - Creates a new form and adds it to the current project.
NOTE: all other parameters are ignored.
cmNewModel - Creates a new Data Model and adds it to the current
project. NOTE: all other parameters are ignored.
cmMainForm - If the module includes a form, make it the main form of
the currently open project. Only valid with the
cmAddToProject option.
cmMarkModified - Will insure that the new module is marked as modified.
cmExisting - Will Create a module from an existing file on disk
CreateModuleEx - New extended form of CreateModule. This will return a
TIModuleInterface. All CreateModes from CreateModule are
supported with only the following differences:
cmExisting - Will create an existing module from the given file
system.
AncestorClass - This must specify an existing base class in the project.
(use the cmAddToProject flag to add a module to the
project first).
NOTES: Pass an empty string for the file system parameter in
order to use the default file system. The file system
parameter *must* be a valid file system previously
registered through the RegisiterFilesystem API.
( Informational )
GetParentHandle - returns a HWND, which should be used as the parent for
any windows created by the client.
GetProjectName - returns a fully qualified path name of the currently
open project file, or an empty string if no project is
open.
GetUnitCount - returns the current number of units belonging to the
project.
GetUnitName - returns a fully qualified name of the specified unit.
EnumProjectUnits - Calls EnumProc once for each unit in the project.
GetFormCount - returns the current number of forms belonging to the
project.
GetFormName - returns a fully qualified name of the specified form
file.
GetCurrentFile - returns a fully qualified name of the current file,
which could either be a form or unit (.PAS).
Returns a blank string if no file is currently selected.
IsFileOpen - returns True if the named file is currently open.
GetNewModuleName - Automatically generates a valid Filename and Unit
identifier. Uses the same mechanism as used by the IDE.
( Component library interface )
GetModuleCount - Returns the number of currently installed modules in the
component library.
GetModuleName - Returns then name of the module given its index.
GetComponentCount- Returns the number of components installed in a particular
module.
GetComponentName - Returns the name of the component given its module index
and index in that mnodule.
( Virtual file system interface )
RegisterFileSystem - Registers an externally defined file system.
UnRegisterFileSystem - UnRegisters an externally defined file system.
( Module Interfaces )
GetModuleInterface - Return an module interface associated with the given
file. NOTE: This function returns the same interface
instance for a given module, only the reference count
is adjusted. The user of this interface owns it and
must call release when finished.
GetFormModuleInterface - Return an module interface associated with the
given form. NOTE: See GetModuleInterface.
( Menu Interface )
GetMainMenu - Returns an interface to the IDE's main menu.
See TIMainMenuIntf for details.
( Notification registration )
AddNotifier - Registers an instance of a descendant to TIAddIn-
Notifier.
RemoveNotifier - Removes a registered instance of a TIAddInNotifier.
( Pascal string handling functions )
NOTE: These functions are provided for IDE add-in writers to use a language
other than Pascal. (C++, for example). Add-in writers using Delphi
will never need to use these functions (see doc about the ShareMem
unit and DELPHIMM.DLL)
NewPascalString - Allocates and returns a pascal long string from the
provided PChar (char *, in C parlance). Passing an
empty string or nil for the PChar will return nil for
the string (Pascal's equivilant of an empty string).
FreePascalString - Attempts to free the given Pascal string by
decrementing the internal reference count and
releasing the memory if the count returns to zero.
ReferencePascalString - Increments the reference count of the given Pascal
string. This allows the calling function to
manually extend the lifetime of the string. NOTE:
a corresponding call to FreePascalString must be
made in order to actually release the string's
memory.
AssignPascalString - Assigns one Pascal string to another. NOTE: NEVER
directly assign Pascal strings to each other. Doing
so will orphan memory and cause a memory leak. The
destination may be referencing another string, so
the reference count of that string must be decremented.
Likewise, the reference count of the source string
must be incremented.
( Error handling )
RaiseException - This will cause an Exception to be raised with the IDE
with the string passed to this function. ***NOTE: This
will cause the stack to unwind and control will **NOT**
return to this point. It is the resposibility of the
Library to be sure it has correctly handled the error
condition before calling this procedure.
( Configuration Access )
GetBaseRegistryKey - returns a string representing the full path to
Delphi's base registry key. This key is relative
to HKEY_CURRENT_USER.
( Extensions )
GetFormBounds - Returns the default bounds of an initial form or custom
module.
ProjectCreate - Creates a project using the new TIProjectCreator interface.
This allows finer control over the creation process
ModuleCreate - Creates a module using the new TIModuleCreator interface.
Same as above.
( Extended Notification registration )
AddNotifierEx - Registers an instance of a descendant to TIAddIn-
Notifier. Only notifiers registered using this
function will have EventNotification interface
function called.
}
TCreateModuleFlag = (cmAddToProject, cmShowSource, cmShowForm,
cmUnNamed, cmNewUnit, cmNewForm, cmMainForm, cmMarkModified,
cmNewFile, cmExisting);
TCreateModuleFlags = set of TCreateModuleFlag;
TCreateProjectFlag = (cpCustom, cpApplication, cpLibrary, cpCanShowSource,
cpExisting, cpConsole);
TCreateProjectFlags = set of TCreateProjectFlag;
TBoundsType = (btForm, btCustomModule);
TProjectEnumProc = function (Param: Pointer; const FileName, UnitName,
FormName: string): Boolean stdcall;
TProjectEnumModuleProc = function (Param: Pointer; const FileName, UnitName,
FormName, DesignClass: string): Boolean stdcall;
TIToolServices = class(TInterface)
public
{ Action interfaces }
function CloseProject: Boolean; virtual; stdcall; abstract;
function OpenProject(const ProjName: string): Boolean; virtual; stdcall; abstract;
function OpenProjectInfo(const ProjName: string): Boolean; virtual; stdcall; abstract;
function SaveProject: Boolean; virtual; stdcall; abstract;
function CloseFile(const FileName: string): Boolean; virtual; stdcall; abstract;
function SaveFile(const FileName: string): Boolean; virtual; stdcall; abstract;
function OpenFile(const FileName: string): Boolean; virtual; stdcall; abstract;
function ReloadFile(const FileName: string): Boolean; virtual; stdcall; abstract;
function ModalDialogBox(Instance: THandle; TemplateName: PChar; WndParent: HWnd;
DialogFunc: TFarProc; InitParam: LongInt): Integer; virtual; stdcall; abstract;
function CreateModule(const ModuleName: string;
Source, Form: IStream; CreateFlags: TCreateModuleFlags): Boolean;
virtual; stdcall; abstract;
function CreateModuleEx(const ModuleName, FormName, AncestorClass,
FileSystem: string; Source, Form: IStream;
CreateFlags: TCreateModuleFlags): TIModuleInterface; virtual; stdcall; abstract;
{ Project/UI information }
function GetParentHandle: HWND; virtual; stdcall; abstract;
function GetProjectName: string; virtual; stdcall; abstract;
function GetUnitCount: Integer; virtual; stdcall; abstract;
function GetUnitName(Index: Integer): string; virtual; stdcall; abstract;
function EnumProjectUnits(EnumProc: TProjectEnumProc; Param: Pointer): Boolean;
virtual; stdcall; abstract;
function GetFormCount: Integer; virtual; stdcall; abstract;
function GetFormName(Index: Integer): string; virtual; stdcall; abstract;
function GetCurrentFile: string; virtual; stdcall; abstract;
function IsFileOpen(const FileName: string): Boolean; virtual; stdcall; abstract;
function GetNewModuleName(var UnitIdent, FileName: string): Boolean; virtual; stdcall; abstract;
{ Component Library interface }
function GetModuleCount: Integer; virtual; stdcall; abstract;
function GetModuleName(Index: Integer): string; virtual; stdcall; abstract;
function GetComponentCount(ModIndex: Integer): Integer; virtual; stdcall; abstract;
function GetComponentName(ModIndex, CompIndex: Integer): string; virtual; stdcall; abstract;
{function InstallModule(const ModuleName: string): Boolean; virtual; stdcall; abstract;
function CompileLibrary: Boolean; virtual; stdcall; abstract;}
{ Virtual File system interfaces }
function RegisterFileSystem(AVirtualFileSystem: TIVirtualFileSystem): Boolean; virtual; stdcall; abstract;
function UnRegisterFileSystem(const Ident: string): Boolean; virtual; stdcall; abstract;
function GetFileSystem(const Ident: string): TIVirtualFileSystem; virtual; stdcall; abstract;
{ Editor Interfaces }
function GetModuleInterface(const FileName: string): TIModuleInterface;
virtual; stdcall; abstract;
function GetFormModuleInterface(const FormName: string): TIModuleInterface;
virtual; stdcall; abstract;
{ Menu Interfaces }
function GetMainMenu: TIMainMenuIntf; virtual; stdcall; abstract;
{ Notification registration }
function AddNotifier(AddInNotifier: TIAddInNotifier): Boolean;
virtual; stdcall; abstract;
function RemoveNotifier(AddInNotifier: TIAddInNotifier): Boolean;
virtual; stdcall; abstract;
{ Pascal string handling functions }
function NewPascalString(Str: PChar): Pointer; virtual; stdcall; abstract;
procedure FreePascalString(var Str: Pointer); virtual; stdcall; abstract;
procedure ReferencePascalString(var Str: Pointer); virtual; stdcall; abstract;
procedure AssignPascalString(var Dest, Src: Pointer); virtual; stdcall; abstract;
{ Error handling }
procedure RaiseException(const Message: string); virtual; stdcall; abstract;
{ Configuration Access }
function GetBaseRegistryKey: string; virtual; stdcall; abstract;
{ Extensions }
function GetFormBounds(BoundsType: TBoundsType): TRect; virtual; stdcall; abstract;
function ProjectCreate(ProjectCreator: TIProjectCreator;
CreateFlags: TCreateProjectFlags): TIModuleInterface; virtual; stdcall; abstract;
function ModuleCreate(ModuleCreator: TIModuleCreator;
CreateFlags: TCreateModuleFlags): TIModuleInterface; virtual; stdcall; abstract;
{ Extended Notification registration }
function AddNotifierEx(AddInNotifier: TIAddInNotifier): Boolean;
virtual; stdcall; abstract;
{ Create a unique unit name and class name }
function GetNewModuleAndClassName(const Prefix: string; var UnitIdent,
ClassName, FileName: string): Boolean; virtual; stdcall; abstract;
function CreateCppModule(const ModuleName, FormName, AncestorClass,
FileSystem: string; HdrSource, Source, Form: IStream;
CreateFlags: TCreateModuleFlags): TIModuleInterface; virtual; stdcall; abstract;
function GetVcsCount: Integer; virtual; stdcall; abstract;
procedure GetVcsList(List: TStringList); virtual; stdcall; abstract;
function GetVcsName(Index: Integer): string; virtual; stdcall; abstract;
function EnumProjectModules(EnumProc: TProjectEnumModuleProc; Param: Pointer): Boolean;
virtual; stdcall; abstract;
function ProjectCreateEx(ProjectCreator: TIProjectCreatorEx;
CreateFlags: TCreateProjectFlags): TIModuleInterface; virtual; stdcall; abstract;
function ModuleCreateEx(ModuleCreator: TIModuleCreatorEx;
CreateFlags: TCreateModuleFlags): TIModuleInterface; virtual; stdcall; abstract;
end;
implementation
end.
|
unit Rx.Implementations;
interface
uses Rx, Generics.Collections, Classes, SyncObjs;
type
IAutoRefObject = interface
['{AE37B031-074C-4F46-B475-1E392E4775CB}']
function GetValue: TObject;
end;
TAutoRefObjectImpl = class(TInterfacedObject, IAutoRefObject)
strict private
FValue: TObject;
public
constructor Create(Value: TObject);
destructor Destroy; override;
function GetValue: TObject;
end;
TSubscriptionImpl = class(TInterfacedObject, ISubscription)
strict private
FIsUnsubscribed: Boolean;
protected
FLock: TCriticalSection;
procedure UnsubscribeInterceptor; dynamic;
public
constructor Create;
destructor Destroy; override;
procedure Unsubscribe;
function IsUnsubscribed: Boolean;
procedure SetProducer(P: IProducer);
end;
IContract<T> = interface(ISubscription)
procedure Lock;
procedure Unlock;
function GetSubscriber: IObserver<T>;
end;
TContractImpl<T> = class(TSubscriptionImpl, IContract<T>)
strict private
[Weak] FSubscriber: IObserver<T>;
FHardRef: IInterface;
protected
procedure UnsubscribeInterceptor; override;
public
destructor Destroy; override;
procedure Lock;
procedure Unlock;
function GetSubscriber: IObserver<T>;
procedure SetSubscriber(Value: IObserver<T>; const WeakRef: Boolean=True);
end;
TSubscriberImpl<T> = class(TInterfacedObject, ISubscriber<T>, IObserver<T>, ISubscription)
type
TOnNext = TOnNext<T>;
strict private
FContract: IContract<T>;
FOnNext: TOnNext;
FOnError: TOnError;
FOnCompleted: TOnCompleted;
public
constructor Create(Contract: IContract<T>; const OnNext: TOnNext=nil;
const OnError: TOnError = nil; const OnCompleted: TOnCompleted=nil);
destructor Destroy; override;
procedure OnNext(const A: T);
procedure OnError(E: IThrowable);
procedure OnCompleted;
procedure Unsubscribe;
function IsUnsubscribed: Boolean;
procedure SetProducer(P: IProducer);
end;
IFromSubscription<T> = interface(ISubscriber<T>)
procedure Lock;
procedure Unlock;
function GetObservable: IObservable<T>;
end;
TFromSbscriptionImpl<T> = class(TSubscriptionImpl, IFromSubscription<T>, ISubscription)
type
TOnNext = TOnNext<T>;
strict private
[Weak] FObservable: IObservable<T>;
FOnNext: TOnNext;
FOnError: TOnError;
FOnCompleted: TOnCompleted;
protected
procedure UnsubscribeInterceptor; override;
public
constructor Create(Observable: IObservable<T>; const OnNext: TOnNext=nil;
const OnError: TOnError = nil; const OnCompleted: TOnCompleted=nil);
procedure Lock;
procedure Unlock;
procedure OnNext(const A: T); dynamic;
procedure OnError(E: IThrowable);
procedure OnCompleted;
function GetObservable: IObservable<T>;
end;
TSubscriberDecorator<T> = class(TInterfacedObject, ISubscriber<T>, IObserver<T>)
strict private
FSubscriber: ISubscriber<T>;
FScheduler: IScheduler;
FLock: TCriticalSection;
FContract: IContract<T>;
public
constructor Create(S: ISubscriber<T>; Scheduler: IScheduler; Contract: IContract<T>);
destructor Destroy; override;
procedure OnNext(const A: T);
procedure OnError(E: IThrowable);
procedure OnCompleted;
procedure Unsubscribe;
function IsUnsubscribed: Boolean;
procedure SetProducer(P: IProducer);
end;
TOnNextAction<T> = class(TInterfacedObject, IAction)
strict private
FData: TSmartVariable<T>;
FContract: IContract<T>;
public
constructor Create(const Data: T; Contract: IContract<T>);
procedure Emit;
end;
TOnErrorAction<T> = class(TInterfacedObject, IAction)
strict private
FThrowable: IThrowable;
FContract: IContract<T>;
public
constructor Create(const Throwable: IThrowable; Contract: IContract<T>);
procedure Emit;
end;
TOnCompletedAction<T> = class(TInterfacedObject, IAction)
strict private
FContract: IContract<T>;
public
constructor Create(Contract: IContract<T>);
procedure Emit;
end;
TOnSubscribeAction<T> = class(TInterfacedObject, IAction)
strict private
FSubscriber: ISubscriber<T>;
FRoutine: TOnSubscribe<T>;
FRoutine2: TOnSubscribe2<T>;
public
constructor Create(Subscriber: ISubscriber<T>; const Routine: TOnSubscribe<T>); overload;
constructor Create(Subscriber: ISubscriber<T>; const Routine: TOnSubscribe2<T>); overload;
procedure Emit;
end;
TObservableImpl<T> = class(TInterfacedObject, IObservable<T>, IObserver<T>)
type
IContract = IContract<T>;
tContractCollection = array of IContract;
IFromSubscription = IFromSubscription<T>;
strict private
FLock: TCriticalSection;
FContracts: TList<IContract>;
FInputs: TList<IFromSubscription>;
FScheduler: IScheduler;
FSubscribeOnScheduler: IScheduler;
FDoOnNext: TOnNext<T>;
FOnSubscribe: TOnSubscribe<T>;
FOnSubscribe2: TOnSubscribe2<T>;
FName: string;
FOnCompleted: TEvent;
function SubscribeInternal(OnNext: TOnNext<T>; const OnError: TOnError; const OnCompleted: TOnCompleted): ISubscription;
function FindContract(Subscr: ISubscriber<T>): IContract<T>;
protected
procedure Lock; inline;
procedure Unlock; inline;
class threadvar OffOnSubscribe: Boolean;
property Inputs: TList<IFromSubscription> read FInputs;
function Freeze: tContractCollection;
property Scheduler: IScheduler read FScheduler;
procedure OnSubscribe(Subscriber: ISubscriber<T>); dynamic;
public
constructor Create; overload;
constructor Create(const OnSubscribe: TOnSubscribe<T>); overload;
constructor Create(const OnSubscribe: TOnSubscribe2<T>); overload;
destructor Destroy; override;
// debug-only purposes
procedure SetName(const Value: string);
property Name: string read FName write SetName;
function Subscribe(const OnNext: TOnNext<T>): ISubscription; overload;
function Subscribe(const OnNext: TOnNext<T>; const OnError: TOnError): ISubscription; overload;
function Subscribe(const OnNext: TOnNext<T>; const OnError: TOnError; const OnCompleted: TOnCompleted): ISubscription; overload;
function Subscribe(const OnNext: TOnNext<T>; const OnCompleted: TOnCompleted): ISubscription; overload;
function Subscribe(const OnError: TOnError): ISubscription; overload;
function Subscribe(const OnCompleted: TOnCompleted): ISubscription; overload;
function Subscribe(A: ISubscriber<T>): ISubscription; overload;
function Merge(O: IObservable<T>): ISubscription;
procedure OnNext(const Data: T); dynamic;
procedure OnError(E: IThrowable); dynamic;
procedure OnCompleted; dynamic;
procedure ScheduleOn(Scheduler: IScheduler);
procedure SubscribeOn(Scheduler: IScheduler);
procedure DoOnNext(const Cb: TOnNext<T>);
function WaitCompletition(const Timeout: LongWord): Boolean;
end;
TIntervalThread = class(TThread)
strict private
FSubscription: ISubscriber<LongWord>;
FDelay: LongWord;
FInitialDelay: LongWord;
FOnTerminate: TEvent;
protected
procedure Execute; override;
public
constructor Create(Subscription: ISubscriber<LongWord>; Delay: LongWord;
InitialDelay: LongWord);
destructor Destroy; override;
procedure Terminate; reintroduce;
end;
TIntervalObserver = class(TObservableImpl<LongWord>)
strict private
FThreads: TList<TIntervalThread>;
protected
procedure OnSubscribe(Subscriber: ISubscriber<LongWord>); override;
class threadvar CurDelay: LongWord;
class threadvar InitialDelay: LongWord;
public
constructor Create;
destructor Destroy; override;
end;
implementation
uses SysUtils, Rx.Schedulers;
type
TLockBasket = class
strict private
FLock: TCriticalSection;
FRefs: TDictionary<Pointer, Integer>;
procedure Lock; inline;
procedure Unlock; inline;
public
constructor Create;
destructor Destroy; override;
procedure AddRef(A: TObject);
procedure Release(A: TObject);
end;
TRefRegistry = class
const
HASH_SIZE = 1024;
strict private
// reduce probability of race conditions by Lock basket
FBaskets: array[0..HASH_SIZE-1] of TLockBasket;
function HashFunc(A: TObject): LongWord;
public
constructor Create;
destructor Destroy; override;
procedure AddRef(A: TObject);
procedure Release(A: TObject);
end;
var
RefRegistry: TRefRegistry;
{ TRefRegistry }
procedure TRefRegistry.AddRef(A: TObject);
begin
FBaskets[HashFunc(A)].AddRef(A);
end;
constructor TRefRegistry.Create;
var
I: Integer;
begin
for I := 0 to HASH_SIZE-1 do
FBaskets[I] := TLockBasket.Create;
end;
destructor TRefRegistry.Destroy;
var
I: Integer;
begin
for I := 0 to HASH_SIZE-1 do
FBaskets[I].Free;
inherited;
end;
function TRefRegistry.HashFunc(A: TObject): LongWord;
var
H: UInt64;
begin
// hash calculation example: TThreadLocalCounter.HashIndex
H := Uint64(A);
Result := Int64Rec(H).Words[0] xor Int64Rec(H).Words[1] or
Int64Rec(H).Words[2] xor Int64Rec(H).Words[3];
Result := Result mod HASH_SIZE;
end;
procedure TRefRegistry.Release(A: TObject);
begin
FBaskets[HashFunc(A)].Release(A);
end;
{ TLockBasket }
procedure TLockBasket.AddRef(A: TObject);
begin
Lock;
try
if not FRefs.ContainsKey(A) then
FRefs.Add(A, 1)
else
FRefs[A] := FRefs[A] + 1
finally
Unlock;
end;
end;
constructor TLockBasket.Create;
begin
FLock := TCriticalSection.Create;
FRefs := TDictionary<Pointer, Integer>.Create;
end;
destructor TLockBasket.Destroy;
begin
FRefs.Free;
FLock.Free;
inherited;
end;
procedure TLockBasket.Lock;
begin
FLock.Acquire;
end;
procedure TLockBasket.Release(A: TObject);
var
RefCount: Integer;
begin
Lock;
try
RefCount := FRefs[A];
Dec(RefCount);
if RefCount > 0 then
FRefs[A] := RefCount
else begin
FRefs.Remove(A);
A.Free;
end;
finally
Unlock;
end;
end;
procedure TLockBasket.Unlock;
begin
FLock.Release;
end;
{ TAutoRefObjectImpl }
constructor TAutoRefObjectImpl.Create(Value: TObject);
begin
FValue := Value;
RefRegistry.AddRef(Value);
end;
destructor TAutoRefObjectImpl.Destroy;
begin
RefRegistry.Release(FValue);
inherited;
end;
function TAutoRefObjectImpl.GetValue: TObject;
begin
Result := FValue;
end;
{ TOnNextAction }
constructor TOnNextAction<T>.Create(const Data: T; Contract: IContract<T>);
begin
FData := Data;
FContract := Contract;
end;
procedure TOnNextAction<T>.Emit;
var
Subscriber: IObserver<T>;
begin
FContract.Lock;
try
if Assigned(FContract.GetSubscriber) then
FContract.GetSubscriber.OnNext(FData)
else
FContract.Unsubscribe;
finally
FContract.Unlock
end;
end;
{ TOnErrorAction<T> }
constructor TOnErrorAction<T>.Create(const Throwable: IThrowable;
Contract: IContract<T>);
begin
FThrowable := Throwable;
FContract := Contract;
end;
procedure TOnErrorAction<T>.Emit;
begin
FContract.Lock;
try
if Assigned(FContract.GetSubscriber) then begin
FContract.GetSubscriber.OnError(FThrowable);
FContract.Unsubscribe;
end
else
FContract.Unsubscribe;
finally
FContract.Unlock
end;
end;
{ TOnCompletedAction<T> }
constructor TOnCompletedAction<T>.Create(Contract: IContract<T>);
begin
FContract := Contract;
end;
procedure TOnCompletedAction<T>.Emit;
begin
FContract.Lock;
try
if Assigned(FContract.GetSubscriber) then begin
FContract.GetSubscriber.OnCompleted;
FContract.Unsubscribe;
end
else
FContract.Unsubscribe;
finally
FContract.Unlock
end;
end;
{ TOnSubscribeAction<T> }
constructor TOnSubscribeAction<T>.Create(Subscriber: ISubscriber<T>; const Routine: TOnSubscribe<T>);
begin
FSubscriber := Subscriber;
FRoutine := Routine;
end;
constructor TOnSubscribeAction<T>.Create(Subscriber: ISubscriber<T>; const Routine: TOnSubscribe2<T>);
begin
FSubscriber := Subscriber;
FRoutine2 := Routine;
end;
procedure TOnSubscribeAction<T>.Emit;
begin
try
if Assigned(FRoutine) then
FRoutine(FSubscriber)
else if Assigned(FRoutine2) then
FRoutine2(FSubscriber)
except
FSubscriber.OnError(Observable.CatchException);
end;
end;
{ TObservableImpl<T> }
constructor TObservableImpl<T>.Create;
begin
FLock := TCriticalSection.Create;
FScheduler := TCurrentThreadScheduler.Create;
FContracts := TList<IContract>.Create;
FInputs := TList<IFromSubscription>.Create;
FOnCompleted := TEvent.Create(nil, True, False, '');
end;
constructor TObservableImpl<T>.Create(const OnSubscribe: TOnSubscribe<T>);
begin
Create;
FOnSubscribe := OnSubscribe;
end;
constructor TObservableImpl<T>.Create(const OnSubscribe: TOnSubscribe2<T>);
begin
Create;
FOnSubscribe2 := OnSubscribe;
end;
destructor TObservableImpl<T>.Destroy;
var
S: IFromSubscription;
C: IContract;
begin
Lock;
try
for S in FInputs do begin
S.Unsubscribe;
end;
for C in FContracts do
C.Unsubscribe;
finally
Unlock;
end;
FContracts.Free;
FInputs.Free;
FScheduler := nil;
FLock.Free;
FOnCompleted.Free;
inherited;
end;
procedure TObservableImpl<T>.DoOnNext(const Cb: TOnNext<T>);
begin
FDoOnNext := Cb;
end;
function TObservableImpl<T>.WaitCompletition(const Timeout: LongWord): Boolean;
begin
Result := FOnCompleted.WaitFor(Timeout) = wrSignaled
end;
function TObservableImpl<T>.Freeze: tContractCollection;
var
I: Integer;
Contract: IContract;
begin
Lock;
try
for I := FContracts.Count-1 downto 0 do begin
Contract := FContracts[I];
if Contract.IsUnsubscribed then
FContracts.Delete(I);
end;
SetLength(Result, FContracts.Count);
for I := 0 to FContracts.Count-1 do
Result[I] := FContracts[I];
finally
Unlock;
end;
end;
procedure TObservableImpl<T>.Lock;
begin
FLock.Acquire
end;
function TObservableImpl<T>.Merge(O: IObservable<T>): ISubscription;
var
S: IFromSubscription;
SImpl: TFromSbscriptionImpl<T>;
Found: Boolean;
begin
Lock;
OffOnSubscribe := True;
try
Found := False;
for S in FInputs do
if S.GetObservable = O then begin
Found := True;
Break
end;
if not Found then begin
SImpl := TFromSbscriptionImpl<T>.Create(O, Self.OnNext, Self.OnError, Self.OnCompleted);
S := SImpl;
FInputs.Add(SImpl);
O.Subscribe(S);
Result := SImpl;
end;
finally
OffOnSubscribe := False;
Unlock;
end;
end;
procedure TObservableImpl<T>.OnCompleted;
var
Contract: IContract;
begin
for Contract in Freeze do begin
FScheduler.Invoke(TOnCompletedAction<T>.Create(Contract));
end;
FOnCompleted.SetEvent;
end;
procedure TObservableImpl<T>.OnError(E: IThrowable);
var
Contract: IContract;
begin
for Contract in Freeze do begin
FScheduler.Invoke(TOnErrorAction<T>.Create(E, Contract));
end;
FOnCompleted.SetEvent;
end;
procedure TObservableImpl<T>.OnNext(const Data: T);
begin
if Assigned(FDoOnNext) then
FDoOnNext(Data);
// Descendant can override
end;
procedure TObservableImpl<T>.OnSubscribe(Subscriber: ISubscriber<T>);
var
S: IFromSubscription;
Once: ISubscription;
Succ: Boolean;
SubscribeOnScheduler: IScheduler;
SubscriberDecorator: ISubscriber<T>;
Contract: IContract<T>;
begin
if OffOnSubscribe then
Exit;
Lock;
SubscribeOnScheduler := FSubscribeOnScheduler;
Contract := FindContract(Subscriber);
Unlock;
SubscriberDecorator := TSubscriberDecorator<T>.Create(Subscriber, FScheduler, Contract);
if Assigned(FOnSubscribe) then
if Assigned(SubscribeOnScheduler) then
SubscribeOnScheduler.Invoke(TOnSubscribeAction<T>.Create(SubscriberDecorator, FOnSubscribe))
else begin
try
FOnSubscribe(SubscriberDecorator);
except
SubscriberDecorator.OnError(Observable.CatchException)
end;
end;
if Assigned(FOnSubscribe2) then
if Assigned(SubscribeOnScheduler) then
SubscribeOnScheduler.Invoke(TOnSubscribeAction<T>.Create(SubscriberDecorator, FOnSubscribe2))
else begin
try
FOnSubscribe2(SubscriberDecorator);
except
SubscriberDecorator.OnError(Observable.CatchException)
end;
end;
for S in FInputs do begin
S.Lock;
try
Succ := not S.IsUnsubscribed and Assigned(S.GetObservable);
if Succ then
Once := nil;
try
Once := S.GetObservable.Subscribe(OnNext, OnError, OnCompleted)
finally
if Assigned(Once) then
Once.Unsubscribe;
end;
finally
S.Unlock;
end;
end;
end;
function TObservableImpl<T>.Subscribe(const OnError: TOnError): ISubscription;
begin
Result := SubscribeInternal(nil, OnError, nil);
end;
function TObservableImpl<T>.Subscribe(const OnNext: TOnNext<T>;
const OnCompleted: TOnCompleted): ISubscription;
begin
Result := Subscribe(OnNext, nil, OnCompleted);
end;
procedure TObservableImpl<T>.ScheduleOn(Scheduler: IScheduler);
begin
Lock;
FScheduler := Scheduler;
Unlock;
end;
procedure TObservableImpl<T>.SubscribeOn(Scheduler: IScheduler);
begin
Lock;
FSubscribeOnScheduler := Scheduler;
Unlock;
end;
function TObservableImpl<T>.Subscribe(A: ISubscriber<T>): ISubscription;
var
Contract: TContractImpl<T>;
begin
Contract := TContractImpl<T>.Create;
Contract.SetSubscriber(A);
Lock;
FContracts.Add(Contract);
Unlock;
OnSubscribe(A);
Result := Contract;
end;
function TObservableImpl<T>.SubscribeInternal(OnNext: TOnNext<T>;
const OnError: TOnError; const OnCompleted: TOnCompleted): ISubscription;
var
Sub: TSubscriberImpl<T>;
Contract: TContractImpl<T>;
begin
Contract := TContractImpl<T>.Create;
Sub := TSubscriberImpl<T>.Create(Contract, OnNext, OnError, OnCompleted);
Contract.SetSubscriber(Sub);
Lock;
FContracts.Add(Contract);
Unlock;
OnSubscribe(Sub);
Result := Contract;
end;
function TObservableImpl<T>.FindContract(Subscr: ISubscriber<T>): IContract<T>;
var
I: Integer;
begin
Result := nil;
Lock;
try
for I := 0 to FContracts.Count-1 do
if FContracts[I].GetSubscriber = Subscr then begin
Exit(FContracts[I]);
end;
finally
Unlock;
end;
end;
procedure TObservableImpl<T>.SetName(const Value: string);
begin
FName := Value;
end;
function TObservableImpl<T>.Subscribe(
const OnCompleted: TOnCompleted): ISubscription;
begin
Result := SubscribeInternal(nil, nil, OnCompleted);
end;
function TObservableImpl<T>.Subscribe(const OnNext: TOnNext<T>;
const OnError: TOnError): ISubscription;
begin
Result := SubscribeInternal(OnNext, OnError, nil);
end;
function TObservableImpl<T>.Subscribe(const OnNext: TOnNext<T>;
const OnError: TOnError; const OnCompleted: TOnCompleted): ISubscription;
begin
Result := SubscribeInternal(OnNext, OnError, OnCompleted)
end;
function TObservableImpl<T>.Subscribe(const OnNext: TOnNext<T>): ISubscription;
begin
Result := SubscribeInternal(OnNext, nil, nil);
end;
procedure TObservableImpl<T>.Unlock;
begin
FLock.Release;
end;
{ TSubscriberImpl<T> }
constructor TSubscriberImpl<T>.Create(Contract: IContract<T>; const OnNext: TOnNext=nil;
const OnError: TOnError = nil; const OnCompleted: TOnCompleted=nil);
begin
FContract := Contract;
FOnNext := OnNext;
FOnError := OnError;
FOnCompleted := OnCompleted;
end;
destructor TSubscriberImpl<T>.Destroy;
begin
FContract.Unsubscribe;
FContract := nil;
inherited;
end;
function TSubscriberImpl<T>.IsUnsubscribed: Boolean;
begin
Result := FContract.IsUnsubscribed
end;
procedure TSubscriberImpl<T>.OnCompleted;
begin
if Assigned(FOnCompleted) then
FOnCompleted()
end;
procedure TSubscriberImpl<T>.OnError(E: IThrowable);
begin
if Assigned(FOnError) then
FOnError(E)
end;
procedure TSubscriberImpl<T>.OnNext(const A: T);
begin
if Assigned(FOnNext) then
FOnNext(A)
end;
procedure TSubscriberImpl<T>.SetProducer(P: IProducer);
begin
FContract.SetProducer(P);
end;
procedure TSubscriberImpl<T>.Unsubscribe;
begin
FContract.Unsubscribe;
end;
{ TSubscriptionImpl }
constructor TSubscriptionImpl.Create;
begin
FLock := TCriticalSection.Create;
end;
destructor TSubscriptionImpl.Destroy;
begin
FLock.Free;
inherited;
end;
function TSubscriptionImpl.IsUnsubscribed: Boolean;
begin
FLock.Acquire;
Result := FIsUnsubscribed;
FLock.Release;
end;
procedure TSubscriptionImpl.SetProducer(P: IProducer);
begin
end;
procedure TSubscriptionImpl.Unsubscribe;
begin
FLock.Acquire;
try
if not FIsUnsubscribed then begin
FIsUnsubscribed := True;
UnsubscribeInterceptor;
end;
finally
FLock.Release;
end;
end;
procedure TSubscriptionImpl.UnsubscribeInterceptor;
begin
end;
{ TContractImpl<T> }
destructor TContractImpl<T>.Destroy;
begin
SetSubscriber(nil, True);
inherited;
end;
function TContractImpl<T>.GetSubscriber: IObserver<T>;
begin
Lock;
Result := FSubscriber;
Unlock;
end;
procedure TContractImpl<T>.Lock;
begin
FLock.Acquire
end;
procedure TContractImpl<T>.SetSubscriber(Value: IObserver<T>; const WeakRef: Boolean=True);
begin
Lock;
FSubscriber := Value;
if not WeakRef then
FHardRef := Value;
Unlock;
end;
procedure TContractImpl<T>.Unlock;
begin
FLock.Release;
end;
procedure TContractImpl<T>.UnsubscribeInterceptor;
begin
FSubscriber := nil;
end;
{ TSubscriberDecorator<T> }
constructor TSubscriberDecorator<T>.Create(S: ISubscriber<T>; Scheduler: IScheduler;
Contract: IContract<T>);
begin
FSubscriber := S;
FScheduler := Scheduler;
FLock := TCriticalSection.Create;
FContract := Contract;
end;
destructor TSubscriberDecorator<T>.Destroy;
begin
if Assigned(FSubscriber) then begin
FSubscriber := nil;
end;
FContract := nil;
FLock.Free;
inherited;
end;
procedure TSubscriberDecorator<T>.Unsubscribe;
begin
if Assigned(FSubscriber) then
FSubscriber.Unsubscribe;
end;
function TSubscriberDecorator<T>.IsUnsubscribed: Boolean;
begin
if Assigned(FSubscriber) then
Result := FSubscriber.IsUnsubscribed
else
Result := False;
end;
procedure TSubscriberDecorator<T>.SetProducer(P: IProducer);
begin
if Assigned(FSubscriber) then
FSubscriber.SetProducer(P);
end;
procedure TSubscriberDecorator<T>.OnCompleted;
begin
FLock.Acquire;
try
if Assigned(FSubscriber) then begin
if Supports(FScheduler, StdSchedulers.ICurrentThreadScheduler) then
FSubscriber.OnCompleted
else begin
FScheduler.Invoke(TOnCompletedAction<T>.Create(FContract));
end;
FSubscriber := nil;
end;
finally
FLock.Release
end;
end;
procedure TSubscriberDecorator<T>.OnError(E: IThrowable);
begin
FLock.Acquire;
try
if Assigned(FSubscriber) then begin
if Supports(FScheduler, StdSchedulers.ICurrentThreadScheduler) then
FSubscriber.OnError(E)
else begin
FScheduler.Invoke(TOnErrorAction<T>.Create(E, FContract));
end;
FSubscriber := nil;
end;
finally
FLock.Release;
end;
end;
procedure TSubscriberDecorator<T>.OnNext(const A: T);
begin
FLock.Acquire;
try
if Assigned(FSubscriber) then begin
// work through contract protect from memory leaks
FScheduler.Invoke(TOnNextAction<T>.Create(A, FContract));
end;
finally
FLock.Release
end;
end;
{ TFromSbscriptionImpl<T> }
constructor TFromSbscriptionImpl<T>.Create(Observable: IObservable<T>;
const OnNext: TOnNext; const OnError: TOnError;
const OnCompleted: TOnCompleted);
begin
inherited Create;
FObservable := Observable;
FOnNext := OnNext;
FOnError := OnError;
FOnCompleted := OnCompleted;
end;
function TFromSbscriptionImpl<T>.GetObservable: IObservable<T>;
begin
Lock;
Result := FObservable;
Unlock;
end;
procedure TFromSbscriptionImpl<T>.Lock;
begin
FLock.Acquire;
end;
procedure TFromSbscriptionImpl<T>.OnCompleted;
begin
Lock;
try
if not IsUnsubscribed and Assigned(FOnCompleted) then begin
FOnCompleted;
Unsubscribe;
end;
finally
Unlock;
end;
end;
procedure TFromSbscriptionImpl<T>.OnError(E: IThrowable);
begin
Lock;
try
if not IsUnsubscribed and Assigned(FOnError) then begin
FOnError(E);
Unsubscribe;
end;
finally
Unlock;
end;
end;
procedure TFromSbscriptionImpl<T>.OnNext(const A: T);
begin
Lock;
try
if not IsUnsubscribed and Assigned(FOnNext) then
FOnNext(A)
finally
Unlock;
end;
end;
procedure TFromSbscriptionImpl<T>.Unlock;
begin
FLock.Release;
end;
procedure TFromSbscriptionImpl<T>.UnsubscribeInterceptor;
begin
FObservable := nil;
end;
{ TIntervalThread }
constructor TIntervalThread.Create(Subscription: ISubscriber<LongWord>;
Delay: LongWord; InitialDelay: LongWord);
begin
FOnTerminate := TEvent.Create(nil, True, False, '');
inherited Create(False);
FSubscription := Subscription;
FDelay := Delay;
FInitialDelay := InitialDelay;
end;
destructor TIntervalThread.Destroy;
begin
FSubscription := nil;
FOnTerminate.Free;
inherited;
end;
procedure TIntervalThread.Terminate;
begin
inherited Terminate;
FOnTerminate.SetEvent;
end;
procedure TIntervalThread.Execute;
var
Iter: LongWord;
begin
Iter := 0;
if FOnTerminate.WaitFor(FInitialDelay) = wrSignaled then begin
Exit;
end;
while (not Terminated) and (not FSubscription.IsUnsubscribed) do begin
if FOnTerminate.WaitFor(FDelay) = wrSignaled then begin
Exit;
end;
FSubscription.OnNext(Iter);
Inc(Iter);
end
end;
{ TIntervalObserver }
constructor TIntervalObserver.Create;
begin
inherited Create;
FThreads := TList<TIntervalThread>.Create;
end;
destructor TIntervalObserver.Destroy;
var
Th: TIntervalThread;
begin
for Th in FThreads do begin
Th.Terminate;
end;
for Th in FThreads do begin
Th.WaitFor;
Th.Free;
end;
FThreads.Free;
inherited;
end;
procedure TIntervalObserver.OnSubscribe(Subscriber: ISubscriber<LongWord>);
var
I: Integer;
Th: TIntervalThread;
begin
// reintroduce parent method
// clear non-active thread pool
for I := FThreads.Count-1 downto 0 do begin
if FThreads[I].Terminated then begin
FThreads[I].Free;
FThreads.Delete(I);
end;
end;
Th := TIntervalThread.Create(Subscriber, CurDelay, InitialDelay);
FThreads.Add(Th);
end;
initialization
RefRegistry := TRefRegistry.Create;
finalization
RefRegistry.Free;
end.
|
unit UBaby;
interface
uses
System.SysUtils, System.Generics.Collections, FMX.Graphics, FMX.Objects,
System.iOUtils, System.UITypes, FMX.Dialogs;
type
{$METHODINFO ON}
TBaby = class
private
_Id: integer;
_Age: single;
_FirstName: string;
_LastName: string;
_ProfileImage: TBitmap;
_Present: Boolean;
procedure SetFirstName(const Value: string);
procedure SetId(const Value: integer);
procedure SetLastName(const Value: string);
procedure SetProfileImage(const Value: TBitmap);
procedure SetPresent(const Value: Boolean);
// function ImagePathToCircleBitmap(imageName : string):TBitmap;
function GetProfileBitmap(): TBitmap;
function GetBgItemBitmap(): TBitmap;
procedure SetAge(const Value: single);
{ Private declarations }
public
{ Public declarations }
ProfileBitmap: TBitmap;
BabyName: string;
BgItem: TBitmap;
// Constructor Create; overload;
Constructor Create(id: integer; firstName: string; lastName: string;Age :single; profileImage: TBitmap; isPresent: Boolean);
Property id: integer read _Id write SetId;
Property Age: single read _Age write SetAge;
Property firstName: string read _FirstName write SetFirstName;
Property lastName: string read _LastName write SetLastName;
Property profileImage: TBitmap read _ProfileImage write SetProfileImage;
property Present: Boolean read _Present write SetPresent default True;
end;
{$METHODINFO OFF}
implementation
function ImagePathToCircleBitmap(imageName: string): TBitmap;
var
path: string;
circleItem: TCircle;
const
pathback = '..\Images';
begin
Try
Result := TBitmap.Create;
circleItem := TCircle.Create(nil);
path := TPath.GetLibraryPath + pathback + PathDelim + imageName;
circleItem.Fill.Bitmap.Bitmap.LoadFromFile(path);
circleItem.Fill.Bitmap.WrapMode := TWrapMode.TileStretch;
circleItem.Fill.Kind := TBrushKind.Bitmap;
circleItem.Stroke.Thickness := 0;
Finally
Result := circleItem.MakeScreenshot;
circleItem.Free;
End;
end;
function ImagePathToRectangleBitmap(imageName: string): TBitmap;
var
path: string;
RectangleItem: TRectangle;
const
pathback = '..\Images';
begin
Try
Result := TBitmap.Create;
RectangleItem := TRectangle.Create(nil);
path := TPath.GetLibraryPath + pathback + PathDelim + imageName;
RectangleItem.Fill.Bitmap.Bitmap.LoadFromFile(path);
RectangleItem.Fill.Bitmap.WrapMode := TWrapMode.TileStretch;
RectangleItem.Fill.Kind := TBrushKind.Bitmap;
RectangleItem.Stroke.Thickness := 0;
Finally
Result := RectangleItem.MakeScreenshot;
RectangleItem.Free;
End;
end;
function TBaby.GetProfileBitmap: TBitmap;
begin
Result := Self._ProfileImage;
end;
function TBaby.GetBgItemBitmap: TBitmap;
begin
Result := ImagePathToRectangleBitmap('itemBg.png');
end;
Constructor TBaby.Create(id: integer; firstName: string; lastName: string;Age: single; profileImage: TBitmap; isPresent: Boolean);
begin
Self._Id := id;
Self._FirstName := firstName;
Self._LastName := lastName;
Self.BabyName := Self._FirstName + ' ' + Self._LastName;
Self._ProfileImage := profileImage;
Self.Age := Age; // CalcAge();
Self._Present := isPresent;
Self.BgItem := GetBgItemBitmap();
Self.ProfileBitmap := GetProfileBitmap();
end;
procedure TBaby.SetAge(const Value: single);
begin
_Age:=value;
end;
procedure TBaby.SetFirstName(const Value: string);
begin
_FirstName := Value;
end;
procedure TBaby.SetId(const Value: integer);
begin
_Id := Value;
end;
procedure TBaby.SetLastName(const Value: string);
begin
_LastName := Value;
end;
procedure TBaby.SetPresent(const Value: Boolean);
begin
_Present := Value;
end;
procedure TBaby.SetProfileImage(const Value: TBitmap);
begin
_ProfileImage := Value;
end;
end.
|
unit uController.Usuario;
interface
uses
DB,
DBClient,
Classes,
System.JSON,
uDM,
uController.Base,
DataSet.Serialize,
Horse;
type
TControllerUsuario = class(TControllerBase)
public
procedure Index(Req: THorseRequest; Res: THorseResponse; Next: TProc);
procedure Store(Req: THorseRequest; Res: THorseResponse; Next: TProc);
procedure Update(Req: THorseRequest; Res: THorseResponse; Next: TProc);
procedure Delete(Req: THorseRequest; Res: THorseResponse; Next: TProc);
end;
var
ControllerUsuario: TControllerUsuario;
implementation
uses
System.SysUtils;
{ TControllerUsuario }
procedure TControllerUsuario.Index(Req: THorseRequest; Res: THorseResponse; Next: TProc);
begin
Res.Send<TJSONArray>(DM.cdsUsuario.ToJSONArray());
end;
procedure TControllerUsuario.Store(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
Body: TJSONObject;
begin
Body := Req.Body<TJSONObject>;
//------------------------------------------------------------------------------
// Valida parâmetros obrigatórios
//------------------------------------------------------------------------------
if not Assigned(Body.Values['name']) then
raise EHorseException.Create('O parâmetro "name" é obrigatório.');
if not Assigned(Body.Values['email']) then
raise EHorseException.Create('O parâmetro "email" é obrigatório.');
//------------------------------------------------------------------------------
// Valida duplicidades
//------------------------------------------------------------------------------
if DM.cdsUsuario.Locate('NOME', Body.Values['name'].Value, []) then
raise EHorseException.Create('Já existe um usuário com este nome.');
if DM.cdsUsuario.Locate('EMAIL', Body.Values['email'].Value, []) then
raise EHorseException.Create('Já existe um usuário com este e-mail.');
//------------------------------------------------------------------------------
// Salva
//------------------------------------------------------------------------------
DM.cdsUsuario.Append;
DM.cdsUsuario.FieldByName('NOME').AsString := Body.Values['name'].Value;
DM.cdsUsuario.FieldByName('EMAIL').AsString := Body.Values['email'].Value;
DM.cdsUsuario.FieldByName('DATE_CAD').AsDateTime := Now;
DM.cdsUsuario.Post;
Salvar;
Res.Status(200);
end;
procedure TControllerUsuario.Update(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
Id: Integer;
Body: TJSONObject;
begin
Id := Req.Params.Items['id'].ToInteger;
Body := Req.Body<TJSONObject>;
//------------------------------------------------------------------------------
// Valida
//------------------------------------------------------------------------------
if not DM.cdsUsuario.Locate('ID', Id, []) then
raise EHorseException.Create('Usuário não encontrado.');
//------------------------------------------------------------------------------
// Salva
//------------------------------------------------------------------------------
DM.cdsUsuario.Edit;
if Assigned(Body.Values['name']) then
DM.cdsUsuario.FieldByName('NOME').AsString := Body.Values['name'].Value;
if Assigned(Body.Values['email']) then
DM.cdsUsuario.FieldByName('EMAIL').AsString := Body.Values['email'].Value;
DM.cdsUsuario.FieldByName('DATE_UPDATE').AsDateTime := Now;
DM.cdsUsuario.Post;
Salvar;
Res.Status(200);
end;
procedure TControllerUsuario.Delete(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
Id: Integer;
begin
Id := Req.Params.Items['id'].ToInteger;
//------------------------------------------------------------------------------
// Valida
//------------------------------------------------------------------------------
if not DM.cdsUsuario.Locate('ID', Id, []) then
raise EHorseException.Create('Usuário não encontrado.');
//------------------------------------------------------------------------------
// Salva
//------------------------------------------------------------------------------
DM.cdsUsuario.Delete;
Salvar;
Res.Status(200);
end;
end.
|
{***************************************************************************
*
* Orion-project.org Lazarus Helper Library
* Copyright (C) 2016-2017 by Nikolay Chunosov
*
* This file is part of the Orion-project.org Lazarus Helper Library
* https://github.com/Chunosov/orion-lazarus
*
* This Library is free software: you can redistribute it and/or modify it
* under the terms of the MIT License. See enclosed LICENSE.txt for details.
*
***************************************************************************}
unit OriEditors;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Controls, StdCtrls, LMessages,
OriMath;
{%region TOriFloatEdit}
type
TFloatEditOption = (
feoAdvFormatting, // Use Mathcad-like formatting (see OriMath)
feoUseInfinity, // Ctrl+0 inserts Infinity
feoDisablePaste, // Disable pasting from Clipboard
feoZeroFill // Paremeter for feoAdvFormatting
);
TFloatEditOptions = set of TFloatEditOption;
TOriFloatEdit = class(TCustomEdit)
private
FMinValue: Extended;
FMaxValue: Extended;
FFormatString: String;
FFloatFormat: TFloatFormat;
FPrecision: Byte; // for AdvFormatting it is ExpThreshold
FDigits: Byte;
FSavedText: String;
FOptions: TFloatEditOptions;
procedure SetValue(AValue: Extended);
procedure SetMinValue(AValue: Extended);
procedure SetMaxValue(AValue: Extended);
procedure SetFormatString(AValue: String);
procedure SetFloatFormat(AValue: TFloatFormat);
procedure SetDigits(AValue: Byte);
procedure SetPrecision(AValue: Byte);
procedure SetOptions(AValue: TFloatEditOptions);
function GetValue: Extended;
function GetText: string;
function CheckValue(NewValue: Extended): Extended;
function FormatText(Value: Extended): String;
procedure LMPasteFromClip(var Message: TLMessage); message LM_PASTE;
protected
procedure CalculatePreferredSize(var PreferredWidth, PreferredHeight: integer; WithThemeSpace: Boolean); override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure KeyPress(var Key: Char); override;
procedure DoExit; override;
procedure DoEnter; override;
public
constructor Create(AOwner: TComponent); override;
property Text: string read GetText; // disable SetTest
procedure SetFormatting(APrecision, ADigits: Byte; AZerofill: Boolean);
published
property MinValue: Extended read FMinValue write SetMinValue;
property MaxValue: Extended read FMaxValue write SetMaxValue;
property FormatString: String read FFormatString write SetFormatString;
property FloatFormat: TFloatFormat read FFloatFormat write SetFloatFormat default ffGeneral;
property Digits: Byte read FDigits write SetDigits default 9;
property Precision: Byte read FPrecision write SetPrecision default 18;
property Value: Extended read GetValue write SetValue;
property Options: TFloatEditOptions read FOptions write SetOptions default [];
property Align;
property Alignment;
property Anchors;
property AutoSize;
property AutoSelect;
property BidiMode;
property BorderSpacing;
property BorderStyle;
property CharCase;
property Color;
property Constraints;
property DragCursor;
property DragKind;
property DragMode;
property EchoMode;
property Enabled;
property Font;
property HideSelection;
property MaxLength;
property ParentBidiMode;
property OnChange;
property OnChangeBounds;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEditingDone;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnStartDrag;
property OnUTF8KeyPress;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ReadOnly;
property ShowHint;
property TabStop;
property TabOrder;
property Visible;
end;
procedure PrepareFloatEditsFormat(AParent: TWinControl;
AExpThreshold, ADigits: Byte; AZerofill, Recursive: Boolean); overload;
procedure PrepareFloatEditsFormat(AParent: TWinControl;
const AFormat: TOriFloatFormatParams; Recursive: Boolean); overload;
{%endregion}
implementation
uses
Math, Graphics,
OriStrings;
{%region TOriFloatEdit}
procedure PrepareFloatEditsFormat(AParent: TWinControl;
AExpThreshold, ADigits: Byte; AZerofill, Recursive: Boolean);
var
I: Integer;
begin
with AParent do
for I := 0 to ControlCount-1 do
if Controls[I] is TOriFloatEdit then
with TOriFloatEdit(Controls[I]) do
begin
Options := Options + [feoAdvFormatting];
SetFormatting(AExpThreshold, ADigits, AZerofill);
end
else if Recursive and (Controls[I] is TWinControl) then
PrepareFloatEditsFormat(TWinControl(Controls[I]),
AExpThreshold, ADigits, AZerofill, True);
end;
procedure PrepareFloatEditsFormat(AParent: TWinControl;
const AFormat: TOriFloatFormatParams; Recursive: Boolean);
begin
with AFormat do
PrepareFloatEditsFormat(AParent, Exponent, Digits, Zerofill, Recursive);
end;
constructor TOriFloatEdit.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FMinValue := 0;
FMaxValue := 0;
FFormatString := '';
FFloatFormat := ffGeneral;
FDigits := 9;
FPrecision := 18;
inherited Text := FormatText(FMinValue);
end;
function TOriFloatEdit.GetText: string;
begin
Result := inherited Text;
end;
procedure TOriFloatEdit.CalculatePreferredSize(var PreferredWidth, PreferredHeight: integer; WithThemeSpace: Boolean);
begin
inherited CalculatePreferredSize(PreferredWidth, PreferredHeight, WithThemeSpace);
PreferredWidth := ScaleX(100 , 96);
end;
procedure TOriFloatEdit.SetMinValue(AValue: Extended);
begin
if FMinValue <> AValue then
begin
FMinValue := AValue;
Value := Value;
end;
end;
procedure TOriFloatEdit.SetMaxValue(AValue: Extended);
begin
if FMaxValue <> AValue then
begin
FMaxValue := AValue;
Value := Value;
end;
end;
procedure TOriFloatEdit.SetFloatFormat(AValue: TFloatFormat);
begin
if AValue <> FFloatFormat then
begin
FFloatFormat := AValue;
Value := Value;
end;
end;
procedure TOriFloatEdit.SetPrecision(AValue: Byte);
begin
if AValue > 18 then AValue := 18;
if AValue <> FPrecision then
begin
FPrecision := AValue;
Value := Value;
end;
end;
procedure TOriFloatEdit.SetDigits(AValue: Byte);
begin
if AValue > 18 then AValue := 18;
if FDigits <> AValue then
begin
FDigits := AValue;
Value := Value;
end;
end;
procedure TOriFloatEdit.SetFormatString(AValue: String);
begin
if AValue <> FFormatString then
begin
FFormatString := AValue;
Value := Value;
end;
end;
procedure TOriFloatEdit.SetFormatting(APrecision, ADigits: Byte; AZerofill: Boolean);
begin
if APrecision > 18
then FPrecision := 18
else FPrecision := APrecision;
if FDigits > 18
then FDigits := 18
else FDigits := ADigits;
if AZerofill
then Include(FOptions, feoZeroFill)
else Exclude(FOptions, feoZeroFill);
Value := Value;
end;
procedure TOriFloatEdit.SetValue(AValue: Extended);
begin
inherited Text := FormatText(CheckValue(AValue));
end;
function TOriFloatEdit.GetValue: Extended;
var S: String;
begin
S := inherited Text;
case Length(S) of
3:
if CharInSet(S[1], ['N','n'])
and CharInSet(S[2], ['A','a'])
and CharInSet(S[3], ['N','n']) then Result := NaN
else if CharInSet(S[1], ['I','i'])
and CharInSet(S[2], ['N','n'])
and CharInSet(S[3], ['F','f']) then Result := Infinity
else Result := CheckValue(StrToFloatDef(S, 0));
4:
if (S[1] = '-')
and CharInSet(S[2], ['I','i'])
and CharInSet(S[3], ['N','n'])
and CharInSet(S[4], ['F','f']) then Result := NegInfinity
else Result := CheckValue(StrToFloatDef(S, 0));
else Result := CheckValue(StrToFloatDef(S, 0));
end;
end;
function TOriFloatEdit.FormatText(Value: Extended): String;
begin
if not (feoAdvFormatting in Options) then
begin
if FormatString <> '' then
Result := FormatFloat(FormatString, Value)
else if Precision > 0 then
Result := FloatToStrF(Value, FloatFormat, Precision, Digits)
else
Result := FloatToStr(Value);
end
else
Result := StringFromFloat(Value, Precision, FDigits, feoZeroFill in Options);
case CharCase of
ecLowerCase: Result := ReplaceChar(Result, 'E', 'e');
ecUppercase: Result := ReplaceChar(Result, 'e', 'E');
end;
end;
procedure TOriFloatEdit.DoEnter;
begin
if AutoSelect and not (csLButtonDown in ControlState) then SelectAll;
inherited;
end;
procedure TOriFloatEdit.DoExit;
var
Tmp: Extended;
begin
Tmp := Value;
Value := Tmp; // do formatting
inherited;
end;
function TOriFloatEdit.CheckValue(NewValue: Extended): Extended;
begin
Result := NewValue;
// unable to compare with Infinity and NaN
if IsNaN(NewValue) or IsInfinite(NewValue) then Exit;
if (FMaxValue <> FMinValue) then
begin
if (FMaxValue > FMinValue) then
begin
if NewValue < FMinValue then Result := FMinValue
else if NewValue > FMaxValue then Result := FMaxValue;
end
else
begin
if FMaxValue = 0 then
begin
if NewValue < FMinValue then Result := FMinValue;
end
else if FMinValue = 0 then
begin
if NewValue > FMaxValue then Result := FMaxValue;
end;
end;
end;
end;
procedure TOriFloatEdit.KeyDown(var Key: Word; Shift: TShiftState);
begin
case Key of
Ord('A'): SelectAll;
Ord('0'):
if (feoUseInfinity in Options) and (Shift = [ssCtrl]) then
begin
Key := 0;
Value := Infinity;
Changed;
end;
end;
inherited;
end;
procedure TOriFloatEdit.KeyPress(var Key: Char);
var
ts: string;
flTemp: Extended;
tmp, tmp1: Integer;
begin
FSavedText := inherited Text;
case Key of
'.', ',': Key := DefaultFormatSettings.DecimalSeparator;
'*', 'E': Key := 'e'; // let only lowercase 'E' allowed
'-': // invert value sign or exponent sign by pressing '-'
// If all the text is selected then do not change sign.
// If all text is selected then it is most probably that user
// is trying to replace all the text with a new one.
if SelLength < Length(inherited Text) then
begin
ts := inherited Text;
if (ts <> '') and (ts <> '-') then
begin
tmp := Pos('e', ts);
if tmp = 0 then
tmp := MaxInt;
// invert value sign
if SelStart < tmp then
begin
tmp := SelStart;
if ts[1] = '-' then
begin
inherited Text := Copy(ts, 2, Length(ts)-1);
SelStart := tmp - 1;
end
else
begin
inherited Text := '-' + ts;
SelStart := tmp + 1;
end;
inherited;
Key := #0;
Exit;
end
else // invert exponent sign
if tmp < Length(ts) then
begin
tmp1 := SelStart;
case ts[tmp+1] of
'-': inherited Text := Copy(ts, 1, tmp) + '+' + Copy(ts, tmp+2, MaxInt);
'+': inherited Text := Copy(ts, 1, tmp) + '-' + Copy(ts, tmp+2, MaxInt);
else inherited Text := Copy(ts, 1, tmp) + '-' + Copy(ts, tmp+1, MaxInt);
end;
SelStart := tmp1;
inherited;
Key := #0;
Exit;
end;
end;
end;
end;
case Key of
#10, #13:
begin
Value := Value; // formatting on Enter
Key := #0;
end;
#32..#255:
begin
if not CharInSet(Key, ['0'..'9', DefaultFormatSettings.DecimalSeparator, '-', 'e']) then
begin
inherited;
Key := #0;
Exit;
end;
// guessed new text
ts := Copy(Text, 1, SelStart) + Key + Copy(Text, SelStart + SelLength + 1, MaxInt);
// select all and press 'minus'
if ts = '-' then
begin
inherited;
Key := #0;
inherited Text := '-0';
SelStart := 1;
SelLength := 1;
Exit;
end;
// select all and press decimal separator
if ts = DefaultFormatSettings.DecimalSeparator then
begin
inherited;
Key := #0;
inherited Text := '0' + DefaultFormatSettings.DecimalSeparator + '0';
SelStart := 2;
SelLength := 1;
Exit;
end;
// select all and delete
if ts = '' then
begin
inherited;
Key := #0;
inherited Text := FormatText(FMinValue);
SelectAll;
Exit;
end;
// other cases
if not TryStrToFloat(ts, flTemp) then
begin
inherited;
Key := #0;
Exit;
end;
// not allow type more than FDigits after decimal separator -
// remove unnecessary digits from the end (or before E)
tmp1 := CharPos(ts, 'e')-1;
if tmp1 = -1 then tmp1 := Length(ts);
tmp := CharPos(ts, DefaultFormatSettings.DecimalSeparator);
if (tmp > 0) and (tmp1 - tmp > Digits) then
begin
inherited;
Key := #0;
tmp := SelStart;
inherited Text := Copy(ts, 1, tmp1-1) + Copy(ts, tmp1+1, MaxInt);
SelStart := tmp;
Exit;
end;
inherited;
end;
else
inherited;
end;
end;
procedure TOriFloatEdit.LMPasteFromClip(var Message: TLMessage);
var
S: string;
Temp: Extended;
begin
inherited;
if feoDisablePaste in Options then
begin
inherited Text := FSavedText;
Exit;
end;
S := Trim(inherited Text);
S := ReplaceChar(S, '.', DefaultFormatSettings.DecimalSeparator);
S := ReplaceChar(S, ',', DefaultFormatSettings.DecimalSeparator);
if not TryStrToFloat(S, Temp) then
begin
// restore original text
inherited Text := FSavedText;
SelStart := 1;
SelLength := 0;
end
else Value := CheckValue(Temp);
end;
procedure TOriFloatEdit.SetOptions(AValue: TFloatEditOptions);
begin
if FOptions <> AValue then
begin
FOptions := AValue;
Value := Value; // re-format value
end;
end;
{%endregion}
end.
|
{*******************************************************}
{ }
{ 泛型动态数组扩展类 }
{ }
{ 版权所有 (C) 2016 武稀松 }
{ }
{*******************************************************}
unit UI.Utils.ArrayEx;
interface
uses System.Generics.Defaults, System.SysUtils;
type
TArrayEx<T> = record
strict private
type
TEnumerator = class
private
FValue: TArray<T>;
FIndex: NativeInt;
function GetCurrent: T;
public
constructor Create(const AValue: TArray<T>);
function MoveNext: Boolean;
property Current: T read GetCurrent;
end;
public
function GetEnumerator(): TEnumerator;
strict private
FData: TArray<T>;
function GetRawData: TArray<T>;
function GetElements(Index: Integer): T;
procedure SetElements(Index: Integer; const Value: T);
private
class function EqualArray(A, B: TArray<T>): Boolean; static;
class function CompareT(const A, B: T): Boolean; static;
class procedure CopyArray(var FromArray, ToArray: TArray<T>;
FromIndex: NativeInt = 0; ToIndex: NativeInt = 0;
Count: NativeInt = -1); static;
class procedure MoveArray(var AArray: array of T;
FromIndex, ToIndex, Count: Integer); static;
class function DynArrayToTArray(const Value: array of T): TArray<T>; static;
class function Min(A, B: NativeInt): NativeInt; static;
procedure QuickSort(const Comparer: IComparer<T>; L, R: Integer);
public // operators
class operator Implicit(Value: TArray<T>): TArrayEx<T>; overload;
class operator Implicit(Value: array of T): TArrayEx<T>; overload;
(*
这个无解,Delphi不允许array of T作为返回值.也就是这个转换是被废了.只好用AssignTo
class operator Implicit(Value: TArrayEx<T>):array of T; overload;
*)
class operator Implicit(Value: TArrayEx<T>): TArray<T>; overload;
class operator Explicit(Value: TArrayEx<T>): TArray<T>; overload;
class operator Explicit(Value: array of T): TArrayEx<T>; overload;
class operator Add(const A, B: TArrayEx<T>): TArrayEx<T>; overload;
class operator Add(const A: TArrayEx<T>; const B: T): TArrayEx<T>; overload;
class operator Add(const A: T; B: TArrayEx<T>): TArrayEx<T>; overload;
class operator Add(A: TArrayEx<T>; B: array of T): TArrayEx<T>; overload;
class operator Add(A: array of T; B: TArrayEx<T>): TArrayEx<T>; overload;
class operator In (A: T; B: TArrayEx<T>): Boolean; overload;
//
class operator Equal(A, B: TArrayEx<T>): Boolean; overload;
class operator Equal(A: TArrayEx<T>; B: TArray<T>): Boolean; overload;
class operator Equal(A: TArray<T>; B: TArrayEx<T>): Boolean; overload;
class operator Equal(A: array of T; B: TArrayEx<T>): Boolean; overload;
class operator Equal(A: TArrayEx<T>; B: array of T): Boolean; overload;
public
procedure SetLen(Value: NativeInt); inline;
function GetLen: NativeInt; inline;
function ByteLen: NativeInt; inline;
class function Create(Value: array of T): TArrayEx<T>; overload; static;
class function Create(Value: TArrayEx<T>): TArrayEx<T>; overload; static;
class function Create(const Value: T): TArrayEx<T>; overload; static;
function Clone(): TArrayEx<T>;
procedure Clear;
procedure SetValue(Value: array of T);
function ToArray(): TArray<T>;
function SubArray(AFrom, ACount: NativeInt): TArrayEx<T>;
procedure Delete(AFrom, ACount: NativeInt); overload;
procedure Delete(AIndex: NativeInt); overload;
procedure Append(Values: TArrayEx<T>); overload;
procedure Append(const Value: T); overload;
procedure Append(Values: array of T); overload;
procedure Append(Values: TArray<T>); overload;
function Insert(AIndex: NativeInt; const Value: T): NativeInt; overload;
function Insert(AIndex: NativeInt; const Values: array of T): NativeInt; overload;
function Insert(AIndex: NativeInt; const Values: TArray<T>): NativeInt; overload;
function Insert(AIndex: NativeInt; const Values: TArrayEx<T>): NativeInt; overload;
procedure Unique();
// 排序
procedure Sort(); overload;
procedure Sort(const Comparer: IComparer<T>); overload;
procedure Sort(const Comparer: IComparer<T>; Index, Count: Integer); overload;
// 搜索
function BinarySearch(const Item: T; out FoundIndex: Integer;
const Comparer: IComparer<T>; Index, Count: Integer): Boolean; overload;
function BinarySearch(const Item: T; out FoundIndex: Integer;
const Comparer: IComparer<T>): Boolean; overload;
function BinarySearch(const Item: T; out FoundIndex: Integer): Boolean; overload;
property Size: NativeInt read GetLen write SetLen;
property Len: NativeInt read GetLen write SetLen;
property RawData: TArray<T> read GetRawData;
property Elements[Index: Integer]: T read GetElements
write SetElements; default;
end;
implementation
uses System.RTLConsts;
class operator TArrayEx<T>.Add(const A, B: TArrayEx<T>): TArrayEx<T>;
begin
Result := A.Clone;
Result.Append(B);
end;
class operator TArrayEx<T>.Add(const A: TArrayEx<T>; const B: T): TArrayEx<T>;
begin
Result := A.Clone;
Result.Append(B);
end;
class operator TArrayEx<T>.Add(const A: T; B: TArrayEx<T>): TArrayEx<T>;
begin
Result.SetValue([A]);
Result.Append(B);
end;
class operator TArrayEx<T>.Add(A: TArrayEx<T>; B: array of T): TArrayEx<T>;
begin
Result := A.Clone;
Result.Append(B);
end;
class operator TArrayEx<T>.Add(A: array of T; B: TArrayEx<T>): TArrayEx<T>;
begin
Result.FData := DynArrayToTArray(A);
Result.Append(B);
end;
class operator TArrayEx<T>.In(A: T; B: TArrayEx<T>): Boolean;
var
Tmp: T;
begin
Result := False;
for Tmp in B.FData do
if CompareT(A, Tmp) then
begin
Result := True;
Break;
end;
end;
class operator TArrayEx<T>.Equal(A, B: TArrayEx<T>): Boolean;
begin
Result := EqualArray(A.FData, B.FData);
end;
class operator TArrayEx<T>.Equal(A: TArrayEx<T>; B: TArray<T>): Boolean;
begin
Result := EqualArray(A.FData, B);
end;
class operator TArrayEx<T>.Equal(A: TArray<T>; B: TArrayEx<T>): Boolean;
begin
Result := EqualArray(A, B.FData);
end;
class operator TArrayEx<T>.Equal(A: array of T; B: TArrayEx<T>): Boolean;
begin
Result := EqualArray(DynArrayToTArray(A), B.FData);
end;
class operator TArrayEx<T>.Equal(A: TArrayEx<T>; B: array of T): Boolean;
begin
Result := EqualArray(A.FData, DynArrayToTArray(B));
end;
function TArrayEx<T>.BinarySearch(const Item: T; out FoundIndex: Integer;
const Comparer: IComparer<T>; Index, Count: Integer): Boolean;
var
L, H: Integer;
mid, cmp: Integer;
begin
if (Index < Low(FData)) or ((Index > High(FData)) and (Count > 0)) or
(Index + Count - 1 > High(FData)) or (Count < 0) or (Index + Count < 0) then
raise EArgumentOutOfRangeException.CreateRes(@SArgumentOutOfRange);
if Count = 0 then
begin
FoundIndex := Index;
Exit(False);
end;
Result := False;
L := Index;
H := Index + Count - 1;
while L <= H do
begin
mid := L + (H - L) shr 1;
cmp := Comparer.Compare(FData[mid], Item);
if cmp < 0 then
L := mid + 1
else
begin
H := mid - 1;
if cmp = 0 then
Result := True;
end;
end;
FoundIndex := L;
end;
function TArrayEx<T>.BinarySearch(const Item: T; out FoundIndex: Integer;
const Comparer: IComparer<T>): Boolean;
begin
Result := BinarySearch(Item, FoundIndex, Comparer, Low(FData), Length(FData));
end;
function TArrayEx<T>.BinarySearch(const Item: T;
out FoundIndex: Integer): Boolean;
begin
Result := BinarySearch(Item, FoundIndex, TComparer<T>.Default, Low(FData),
Length(FData));
end;
function TArrayEx<T>.ByteLen: NativeInt;
begin
Result := Length(FData) * Sizeof(T);
end;
class function TArrayEx<T>.Min(A, B: NativeInt): NativeInt;
begin
Result := A;
if Result > B then
Result := B;
end;
class procedure TArrayEx<T>.CopyArray(var FromArray, ToArray: TArray<T>;
FromIndex, ToIndex, Count: NativeInt);
var
i: Integer;
begin
if Count = 0 then
Exit;
if Count < 0 then
Count := Min(Length(FromArray), Length(ToArray));
if Length(FromArray) < (FromIndex + Count) then
Count := Length(FromArray) - FromIndex;
if Length(ToArray) < (ToIndex + Count) then
Count := Length(ToArray) - ToIndex;
if Count > 0 then
for i := 0 to Count - 1 do
ToArray[ToIndex + i] := FromArray[FromIndex + i];
end;
class procedure TArrayEx<T>.MoveArray(var AArray: array of T;
FromIndex, ToIndex, Count: Integer);
var
i: Integer;
begin
if Count > 0 then
begin
if FromIndex < ToIndex then
for i := Count - 1 downto 0 do
AArray[ToIndex + i] := AArray[FromIndex + i]
else if FromIndex > ToIndex then
for i := 0 to Count - 1 do
AArray[ToIndex + i] := AArray[FromIndex + i];
end;
end;
procedure TArrayEx<T>.QuickSort(const Comparer: IComparer<T>; L, R: Integer);
var
i, J: Integer;
pivot, temp: T;
begin
if (Length(FData) = 0) or ((R - L) <= 0) then
Exit;
repeat
i := L;
J := R;
pivot := FData[L + (R - L) shr 1];
repeat
while Comparer.Compare(FData[i], pivot) < 0 do
Inc(i);
while Comparer.Compare(FData[J], pivot) > 0 do
Dec(J);
if i <= J then
begin
if i <> J then
begin
temp := FData[i];
FData[i] := FData[J];
FData[J] := temp;
end;
Inc(i);
Dec(J);
end;
until i > J;
if L < J then
QuickSort(Comparer, L, J);
L := i;
until i >= R;
end;
class function TArrayEx<T>.DynArrayToTArray(const Value: array of T): TArray<T>;
var
i: Integer;
begin
SetLength(Result, Length(Value));
for i := Low(Value) to High(Value) do
Result[i] := Value[i];
end;
class function TArrayEx<T>.EqualArray(A, B: TArray<T>): Boolean;
var
i: Integer;
begin
Result := True;
if A = B then
Exit;
if Length(A) <> Length(B) then
begin
Result := False;
end
else
begin
for i := Low(A) to High(A) do
if not CompareT(A[i], B[i]) then
begin
Result := False;
Break;
end;
end;
end;
class function TArrayEx<T>.CompareT(const A, B: T): Boolean;
var
Compare: IComparer<T>;
begin
Compare := TComparer<T>.Default;
Result := Compare.Compare(A, B) = 0;
end;
// class function TArrayEx<T>.CompareT(const A, B: T): Boolean;
// var
// p1, p2: PByte;
// i: Integer;
// begin
// Result := True;
// p1 := PByte(@A);
// p2 := PByte(@B);
// for i := 0 to Sizeof(T) - 1 do
// begin
// //
// if p1^ <> p2^ then
// begin
// Result := False;
// Exit;
// end;
// Inc(p1);
// Inc(p2);
// end;
// end;
function TArrayEx<T>.GetElements(Index: Integer): T;
begin
Result := FData[Index];
end;
function TArrayEx<T>.GetEnumerator: TEnumerator;
begin
Result := TEnumerator.Create(FData);
end;
function TArrayEx<T>.GetLen: NativeInt;
begin
Result := Length(FData);
end;
function TArrayEx<T>.GetRawData: TArray<T>;
begin
Result := FData;
end;
class operator TArrayEx<T>.Implicit(Value: TArrayEx<T>): TArray<T>;
begin
SetLength(Result, Length(Value.FData));
CopyArray(Value.FData, Result, 0, 0, Length(Value.FData));
end;
class operator TArrayEx<T>.Explicit(Value: array of T): TArrayEx<T>;
begin
Result.SetValue(Value);
end;
class operator TArrayEx<T>.Implicit(Value: array of T): TArrayEx<T>;
begin
Result.SetValue(Value);
end;
class operator TArrayEx<T>.Implicit(Value: TArray<T>): TArrayEx<T>;
begin
SetLength(Result.FData, Length(Value));
CopyArray(Value, Result.FData, 0, 0, Length(Value));
end;
class operator TArrayEx<T>.Explicit(Value: TArrayEx<T>): TArray<T>;
begin
SetLength(Result, Length(Value.FData));
CopyArray(Value.FData, Result, 0, 0, Length(Value.FData));
end;
procedure TArrayEx<T>.SetElements(Index: Integer; const Value: T);
begin
FData[Index] := Value;
end;
procedure TArrayEx<T>.SetLen(Value: NativeInt);
begin
SetLength(FData, Value);
end;
procedure TArrayEx<T>.SetValue(Value: array of T);
begin
FData := DynArrayToTArray(Value);
end;
procedure TArrayEx<T>.Sort;
begin
QuickSort(TComparer<T>.Default, Low(FData), High(FData));
end;
procedure TArrayEx<T>.Sort(const Comparer: IComparer<T>; Index, Count: Integer);
begin
if (Index < Low(FData)) or ((Index > High(FData)) and (Count > 0)) or
(Index + Count - 1 > High(FData)) or (Count < 0) or (Index + Count < 0) then
raise EArgumentOutOfRangeException.CreateRes(@SArgumentOutOfRange);
if Count <= 1 then
Exit;
QuickSort(Comparer, Index, Index + Count - 1);
end;
procedure TArrayEx<T>.Sort(const Comparer: IComparer<T>);
begin
QuickSort(Comparer, Low(FData), High(FData));
end;
function TArrayEx<T>.ToArray(): TArray<T>;
begin
SetLength(Result, Length(FData));
CopyArray(FData, Result, 0, 0, Length(FData));
end;
class function TArrayEx<T>.Create(Value: array of T): TArrayEx<T>;
begin
Result.SetValue(Value);
end;
class function TArrayEx<T>.Create(Value: TArrayEx<T>): TArrayEx<T>;
begin
Result := Value.Clone;
end;
class function TArrayEx<T>.Create(const Value: T): TArrayEx<T>;
begin
Result.SetValue([Value]);
end;
procedure TArrayEx<T>.Clear;
begin
SetLength(FData, 0);
end;
function TArrayEx<T>.Clone(): TArrayEx<T>;
begin
Result := SubArray(0, Length(FData));
end;
function TArrayEx<T>.SubArray(AFrom, ACount: NativeInt): TArrayEx<T>;
begin
SetLength(Result.FData, ACount);
CopyArray(FData, Result.FData, AFrom, 0, ACount);
end;
procedure TArrayEx<T>.Delete(AFrom, ACount: NativeInt);
begin
if AFrom >= Length(FData) then
Exit;
if (AFrom + ACount) > Length(FData) then
ACount := Length(FData) - AFrom;
MoveArray(FData, AFrom + ACount, AFrom, Length(FData) - (AFrom + ACount));
SetLength(FData, Length(FData) - ACount);
end;
procedure TArrayEx<T>.Delete(AIndex: NativeInt);
begin
Delete(AIndex, 1);
end;
procedure TArrayEx<T>.Append(Values: TArrayEx<T>);
begin
Insert(Length(FData), Values);
end;
procedure TArrayEx<T>.Append(Values: TArray<T>);
begin
Insert(Length(FData), Values);
end;
procedure TArrayEx<T>.Append(const Value: T);
begin
SetLength(FData, Length(FData) + 1);
FData[High(FData)] := Value;
end;
procedure TArrayEx<T>.Append(Values: array of T);
begin
Insert(Length(FData), Values);
end;
function TArrayEx<T>.Insert(AIndex: NativeInt; const Value: T): NativeInt;
var
i: Integer;
begin
Result := -1;
if (AIndex > Length(FData)) or (AIndex < 0) then
Exit;
SetLength(FData, Length(FData) + 1);
MoveArray(FData, AIndex, AIndex + 1, Length(FData) - AIndex);
FData[AIndex] := Value;
Result := AIndex;
end;
function TArrayEx<T>.Insert(AIndex: NativeInt; const Values: array of T)
: NativeInt;
var
i: Integer;
begin
SetLength(FData, Length(Values));
MoveArray(FData, AIndex, AIndex + Length(Values), Length(FData) - AIndex);
for i := 0 to Length(Values) - 1 do
FData[AIndex + i] := Values[i];
Result := AIndex;
end;
function TArrayEx<T>.Insert(AIndex: NativeInt; const Values: TArray<T>)
: NativeInt;
var
i: Integer;
begin
SetLength(FData, Length(FData) + Length(Values));
MoveArray(FData, AIndex, AIndex + Length(Values), Length(FData) - AIndex);
for i := 0 to Length(Values) - 1 do
FData[AIndex + i] := Values[i];
Result := AIndex;
end;
function TArrayEx<T>.Insert(AIndex: NativeInt; const Values: TArrayEx<T>)
: NativeInt;
begin
Result := Insert(AIndex, Values.ToArray);
end;
procedure TArrayEx<T>.Unique();
var
i, J: Integer;
Tmp: TArrayEx<T>;
Flag: Boolean;
begin
for i := High(FData) downto Low(FData) do
begin
Flag := False;
for J := High(Tmp.FData) downto Low(Tmp.FData) do
begin
if CompareT(FData[i], Tmp[J]) then
begin
Flag := True;
Break;
end;
end;
if not Flag then
Tmp.Append(FData[i]);
end;
FData := Tmp.FData;
end;
{ TArrayEx<T>.TEnumerator }
constructor TArrayEx<T>.TEnumerator.Create(const AValue: TArray<T>);
begin
FValue := AValue;
FIndex := -1;
end;
function TArrayEx<T>.TEnumerator.GetCurrent: T;
begin
Result := FValue[FIndex];
end;
function TArrayEx<T>.TEnumerator.MoveNext: Boolean;
begin
Result := False;
if (FIndex >= Length(FValue)) then
Exit;
Inc(FIndex);
Result := FIndex < Length(FValue);
end;
end.
|
{ *********************************************************************** }
{ }
{ Delphi / Kylix Cross-Platform Runtime Library }
{ Variants Unit }
{ }
{ Copyright (C) 1995-2001 Borland Software Corporation }
{ }
{ *********************************************************************** }
unit Variants;
{$RANGECHECKS OFF}
interface
uses
Types;
{ Variant support procedures and functions }
function VarType(const V: Variant): TVarType;
function VarAsType(const V: Variant; AVarType: TVarType): Variant;
function VarIsType(const V: Variant; AVarType: TVarType): Boolean; overload;
function VarIsType(const V: Variant; const AVarTypes: array of TVarType): Boolean; overload;
function VarIsByRef(const V: Variant): Boolean;
function VarIsEmpty(const V: Variant): Boolean;
procedure VarCheckEmpty(const V: Variant);
function VarIsNull(const V: Variant): Boolean;
function VarIsClear(const V: Variant): Boolean;
function VarIsCustom(const V: Variant): Boolean;
function VarIsOrdinal(const V: Variant): Boolean;
function VarIsFloat(const V: Variant): Boolean;
function VarIsNumeric(const V: Variant): Boolean;
function VarIsStr(const V: Variant): Boolean;
function VarToStr(const V: Variant): string;
function VarToStrDef(const V: Variant; const ADefault: string): string;
function VarToWideStr(const V: Variant): WideString;
function VarToWideStrDef(const V: Variant; const ADefault: WideString): WideString;
function VarToDateTime(const V: Variant): TDateTime;
function VarFromDateTime(const DateTime: TDateTime): Variant;
function VarInRange(const AValue, AMin, AMax: Variant): Boolean;
function VarEnsureRange(const AValue, AMin, AMax: Variant): Variant;
type
TVariantRelationship = (vrEqual, vrLessThan, vrGreaterThan, vrNotEqual);
function VarSameValue(const A, B: Variant): Boolean;
function VarCompareValue(const A, B: Variant): TVariantRelationship;
function VarIsEmptyParam(const V: Variant): Boolean;
function VarSupports(const V: Variant; const IID: TGUID; out Intf): Boolean; overload;
function VarSupports(const V: Variant; const IID: TGUID): Boolean; overload;
{ Variant copy support }
procedure VarCopyNoInd(var Dest: Variant; const Source: Variant);
{ Variant array support procedures and functions }
function VarIsArray(const A: Variant): Boolean; overload;
function VarIsArray(const A: Variant; AResolveByRef: Boolean): Boolean; overload;
function VarArrayCreate(const Bounds: array of Integer; AVarType: TVarType): Variant;
function VarArrayOf(const Values: array of Variant): Variant;
function VarArrayRef(const A: Variant): Variant;
function VarTypeIsValidArrayType(const AVarType: TVarType): Boolean;
function VarTypeIsValidElementType(const AVarType: TVarType): Boolean;
{ The following functions will handle normal variant arrays as well as
variant arrays references by another variant using byref }
function VarArrayDimCount(const A: Variant): Integer;
function VarArrayLowBound(const A: Variant; Dim: Integer): Integer;
function VarArrayHighBound(const A: Variant; Dim: Integer): Integer;
function VarArrayLock(const A: Variant): Pointer;
procedure VarArrayUnlock(const A: Variant);
function VarArrayGet(const A: Variant; const Indices: array of Integer): Variant;
procedure VarArrayPut(var A: Variant; const Value: Variant; const Indices: array of Integer);
{ Variant <--> Dynamic Arrays }
procedure DynArrayToVariant(var V: Variant; const DynArray: Pointer; TypeInfo: Pointer);
procedure DynArrayFromVariant(var DynArray: Pointer; const V: Variant; TypeInfo: Pointer);
{ Global constants }
function Unassigned: Variant; // Unassigned standard constant
function Null: Variant; // Null standard constant
var
EmptyParam: OleVariant; // "Empty parameter" standard constant which can be
{$EXTERNALSYM EmptyParam} // passed as an optional parameter on a dual
// interface.
{ Custom variant base class }
type
TVarCompareResult = (crLessThan, crEqual, crGreaterThan);
TCustomVariantType = class(TObject, IInterface)
private
FVarType: TVarType;
protected
{ IInterface }
function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
procedure SimplisticClear(var V: TVarData);
procedure SimplisticCopy(var Dest: TVarData; const Source: TVarData;
const Indirect: Boolean = False);
procedure RaiseInvalidOp;
procedure RaiseCastError;
procedure RaiseDispError;
function LeftPromotion(const V: TVarData; const Operator: TVarOp;
out RequiredVarType: TVarType): Boolean; virtual;
function RightPromotion(const V: TVarData; const Operator: TVarOp;
out RequiredVarType: TVarType): Boolean; virtual;
function OlePromotion(const V: TVarData;
out RequiredVarType: TVarType): Boolean; virtual;
procedure DispInvoke(var Dest: TVarData; const Source: TVarData;
CallDesc: PCallDesc; Params: Pointer); virtual;
procedure VarDataInit(var Dest: TVarData);
procedure VarDataClear(var Dest: TVarData);
procedure VarDataCopy(var Dest: TVarData; const Source: TVarData);
procedure VarDataCopyNoInd(var Dest: TVarData; const Source: TVarData);
procedure VarDataCast(var Dest: TVarData; const Source: TVarData);
procedure VarDataCastTo(var Dest: TVarData; const Source: TVarData;
const AVarType: TVarType); overload;
procedure VarDataCastTo(var Dest: TVarData; const AVarType: TVarType); overload;
procedure VarDataCastToOleStr(var Dest: TVarData);
procedure VarDataFromStr(var V: TVarData; const Value: string);
procedure VarDataFromOleStr(var V: TVarData; const Value: WideString);
function VarDataToStr(const V: TVarData): string;
function VarDataIsEmptyParam(const V: TVarData): Boolean;
function VarDataIsByRef(const V: TVarData): Boolean;
function VarDataIsArray(const V: TVarData): Boolean;
function VarDataIsOrdinal(const V: TVarData): Boolean;
function VarDataIsFloat(const V: TVarData): Boolean;
function VarDataIsNumeric(const V: TVarData): Boolean;
function VarDataIsStr(const V: TVarData): Boolean;
public
constructor Create; overload;
constructor Create(RequestedVarType: TVarType); overload;
destructor Destroy; override;
property VarType: TVarType read FVarType;
function IsClear(const V: TVarData): Boolean; virtual;
procedure Cast(var Dest: TVarData; const Source: TVarData); virtual;
procedure CastTo(var Dest: TVarData; const Source: TVarData;
const AVarType: TVarType); virtual;
procedure CastToOle(var Dest: TVarData; const Source: TVarData); virtual;
// The following three procedures must be overridden by your custom
// variant type class. Simplistic versions of Clear and Copy are
// available in the protected section of this class but depending on the
// type of data contained in your custom variant type those functions
// may not handle your situation.
procedure Clear(var V: TVarData); virtual; abstract;
procedure Copy(var Dest: TVarData; const Source: TVarData;
const Indirect: Boolean); virtual; abstract;
procedure BinaryOp(var Left: TVarData; const Right: TVarData;
const Operator: TVarOp); virtual;
procedure UnaryOp(var Right: TVarData; const Operator: TVarOp); virtual;
function CompareOp(const Left, Right: TVarData;
const Operator: TVarOp): Boolean; virtual;
procedure Compare(const Left, Right: TVarData;
var Relationship: TVarCompareResult); virtual;
end;
TCustomVariantTypeClass = class of TCustomVariantType;
TVarDataArray = array of TVarData;
IVarInvokeable = interface
['{1CB65C52-BBCB-41A6-9E58-7FB916BEEB2D}']
function DoFunction(var Dest: TVarData; const V: TVarData;
const Name: string; const Arguments: TVarDataArray): Boolean;
function DoProcedure(const V: TVarData; const Name: string;
const Arguments: TVarDataArray): Boolean;
function GetProperty(var Dest: TVarData; const V: TVarData;
const Name: string): Boolean;
function SetProperty(const V: TVarData; const Name: string;
const Value: TVarData): Boolean;
end;
TInvokeableVariantType = class(TCustomVariantType, IVarInvokeable)
protected
procedure DispInvoke(var Dest: TVarData; const Source: TVarData;
CallDesc: PCallDesc; Params: Pointer); override;
public
{ IVarInvokeable }
function DoFunction(var Dest: TVarData; const V: TVarData;
const Name: string; const Arguments: TVarDataArray): Boolean; virtual;
function DoProcedure(const V: TVarData; const Name: string;
const Arguments: TVarDataArray): Boolean; virtual;
function GetProperty(var Dest: TVarData; const V: TVarData;
const Name: string): Boolean; virtual;
function SetProperty(const V: TVarData; const Name: string;
const Value: TVarData): Boolean; virtual;
end;
IVarInstanceReference = interface
['{5C176802-3F89-428D-850E-9F54F50C2293}']
function GetInstance(const V: TVarData): TObject;
end;
function FindCustomVariantType(const AVarType: TVarType;
out CustomVariantType: TCustomVariantType): Boolean; overload;
function FindCustomVariantType(const TypeName: string;
out CustomVariantType: TCustomVariantType): Boolean; overload;
type
TAnyProc = procedure (var V: TVarData);
TVarDispProc = procedure (Dest: PVariant; const Source: Variant;
CallDesc: PCallDesc; Params: Pointer); cdecl;
var
VarDispProc: TVarDispProc;
ClearAnyProc: TAnyProc; { Handler clearing a varAny }
ChangeAnyProc: TAnyProc; { Handler to change any to variant }
RefAnyProc: TAnyProc; { Handler to add a reference to an varAny }
implementation
uses
SysConst, SysUtils, VarUtils;
{ ----------------------------------------------------- }
{ Variant support }
{ ----------------------------------------------------- }
var
GVariantManager,
GOldVariantManager: TVariantManager;
type
TBaseType = (btErr, btNul, btInt, btFlt, btCur, btStr, btBol, btDat, btI64);
const
varLast = varInt64;
const
BaseTypeMap: array[0..varLast] of TBaseType = (
btErr, { varEmpty }
btNul, { varNull }
btInt, { varSmallint }
btInt, { varInteger }
btFlt, { varSingle }
btFlt, { varDouble }
btCur, { varCurrency }
btDat, { varDate }
btStr, { varOleStr }
btErr, { varDispatch }
btErr, { varError }
btBol, { varBoolean }
btErr, { varVariant }
btErr, { varUnknown }
btErr, { vt_decimal }
btErr, { undefined }
btInt, { varShortInt }
btInt, { varByte }
btI64, { varWord }
btI64, { varLongWord }
btI64); { varInt64 }
const
OpTypeMap: array[TBaseType, TBaseType] of TBaseType = (
{btErr, btNul, btInt, vtFlt, btCur, btStr, btBol, btDat, btI64}
{btErr}(btErr, btErr, btErr, btErr, btErr, btErr, btErr, btErr, btErr),
{btNul}(btErr, btNul, btNul, btNul, btNul, btNul, btNul, btNul, btNul),
{btInt}(btErr, btNul, btInt, btFlt, btCur, btFlt, btInt, btDat, btI64),
{btFlt}(btErr, btNul, btFlt, btFlt, btCur, btFlt, btFlt, btDat, btFlt),
{btCur}(btErr, btNul, btCur, btCur, btCur, btCur, btCur, btDat, btCur),
{btStr}(btErr, btNul, btFlt, btFlt, btCur, btStr, btBol, btDat, btFlt),
{btBol}(btErr, btNul, btInt, btFlt, btCur, btBol, btBol, btDat, btI64),
{btDat}(btErr, btNul, btDat, btDat, btDat, btDat, btDat, btDat, btDat),
{btI64}(btErr, btNul, btI64, btFlt, btCur, btFlt, btI64, btDat, btI64));
{ TCustomVariantType support }
{ Currently we have reserve room for 1791 ($6FF) custom types. But, since the
first sixteen are reserved, we actually only have room for 1775 ($6EF) types. }
const
CMaxNumberOfCustomVarTypes = $06FF;
CMinVarType = $0100;
CMaxVarType = CMinVarType + CMaxNumberOfCustomVarTypes;
CIncVarType = $000F;
CFirstUserType = CMinVarType + CIncVarType;
CInvalidCustomVariantType: TCustomVariantType = TCustomVariantType($FFFFFFFF);
procedure _DispInvokeError;
asm
MOV AL,System.reVarDispatch
JMP System.Error
end;
procedure VarCastError;
asm
MOV AL,System.reVarTypeCast
JMP System.Error
end;
procedure VarInvalidOp;
asm
MOV AL,System.reVarInvalidOp
JMP System.Error
end;
procedure _VarInit(var V: TVarData);
begin
VariantInit(V);
end;
procedure _VarClear(var V: TVarData);
var
LType: TVarType;
LHandler: TCustomVariantType;
begin
LType := V.VType and varTypeMask;
if LType < CFirstUserType then
begin
if ((V.VType and varByRef) <> 0) or (LType < varOleStr) then
V.VType := varEmpty
else if LType = varString then
begin
V.VType := varEmpty;
String(V.VString) := '';
end
else if LType = varAny then
ClearAnyProc(V)
else
VariantClear(V);
end
else if FindCustomVariantType(LType, LHandler) then
LHandler.Clear(V)
else
VarInvalidOp;
end;
procedure _DispInvoke(Dest: PVarData; const Source: TVarData;
CallDesc: PCallDesc; Params: Pointer); cdecl;
var
LSourceType: TVarType;
LSourceHandler: TCustomVariantType;
begin
LSourceType := Source.VType and varTypeMask;
if Assigned(Dest) then
_VarClear(Dest^);
if LSourceType < CFirstUserType then
VarDispProc(PVariant(Dest), Variant(Source), CallDesc, @Params)
else if FindCustomVariantType(LSourceType, LSourceHandler) then
LSourceHandler.DispInvoke(TVarData(Dest^), Source, CallDesc, @Params)
else
VarInvalidOp;
end;
type
TVarArrayForEach = procedure(var Dest: TVarData; const Src: TVarData);
procedure VarArrayCopyForEach(var Dest: TVarData; const Src: TVarData; AProc: TVarArrayForEach);
var
I, UBound, DimCount: Integer;
VarArrayRef, SrcArrayRef: PVarArray;
VarBounds: array[0..63] of TVarArrayBound;
VarPoint: array[0..63] of Integer;
PFrom, PTo: Pointer;
function Increment(At: Integer): Boolean;
begin
Result := True;
Inc(VarPoint[At]);
if VarPoint[At] = VarBounds[At].LowBound + VarBounds[At].ElementCount then
if At = 0 then
Result := False
else
begin
VarPoint[At] := VarBounds[At].LowBound;
Result := Increment(At - 1);
end;
end;
begin
if Src.VType and varTypeMask <> varVariant then
VariantCopy(Dest, Src)
else
begin
if (TVarData(Src).VType and varByRef) <> 0 then
SrcArrayRef := PVarArray(TVarData(Src).VPointer^)
else
SrcArrayRef := TVarData(Src).VArray;
DimCount := SrcArrayRef^.DimCount;
for I := 0 to DimCount - 1 do
with VarBounds[I] do
begin
if SafeArrayGetLBound(SrcArrayRef, I + 1, LowBound) <> VAR_OK then
System.Error(System.reVarArrayBounds);
if SafeArrayGetUBound(SrcArrayRef, I + 1, UBound) <> VAR_OK then
System.Error(System.reVarArrayBounds);
ElementCount := UBound - LowBound + 1;
end;
VarArrayRef := SafeArrayCreate(varVariant, DimCount, PVarArrayBoundArray(@VarBounds)^);
if VarArrayRef = nil then
System.Error(System.reVarArrayCreate);
_VarClear(Dest);
Dest.VType := varVariant or varArray;
Dest.VArray := VarArrayRef;
for I := 0 to DimCount - 1 do
VarPoint[I] := VarBounds[I].LowBound;
repeat
if SafeArrayPtrOfIndex(SrcArrayRef, PVarArrayCoorArray(@VarPoint), PFrom) <> VAR_OK then
System.Error(System.reVarArrayBounds);
if SafeArrayPtrOfIndex(VarArrayRef, PVarArrayCoorArray(@VarPoint), PTo) <> VAR_OK then
System.Error(System.reVarArrayBounds);
AProc(PVarData(PTo)^, PVarData(PFrom)^);
until not Increment(DimCount - 1);
end;
end;
procedure VarArrayCopyProc(var Dest: TVarData; const Src: TVarData);
begin
Variant(Dest) := Variant(Src);
end;
procedure VarCopyCommon(var Dest: TVarData; const Source: TVarData; Indirect: Boolean);
var
LSourceType: TVarType;
LSourceHandler: TCustomVariantType;
begin
if @Dest = @Source then
Exit;
LSourceType := Source.VType and varTypeMask;
_VarClear(Dest);
if LSourceType < CFirstUserType then
begin
if LSourceType < varOleStr then
Dest := Source // block copy
else
case LSourceType of
varString:
begin
Dest.VType := varString;
Dest.VString := nil; // prevent string assignment from trying to free garbage
String(Dest.VString) := String(Source.VString);
end;
varAny:
begin
Dest := Source; // block copy
RefAnyProc(Dest);
end;
varInt64:
begin
Dest.VType := varInt64;
Dest.VInt64 := Source.VInt64;
end;
else
if Indirect then
begin
if Source.VType and varArray <> 0 then
VarArrayCopyForEach(Dest, Source, VarArrayCopyProc)
else if VariantCopyInd(Dest, Source) <> VAR_OK then
VarInvalidOp;
end
else
if (Source.VType and varArray <> 0) and
(Source.VType and varByRef = 0) then
VarArrayCopyForEach(Dest, Source, VarArrayCopyProc)
else
VariantCopy(Dest, Source);
end
end
else if FindCustomVariantType(LSourceType, LSourceHandler) then
LSourceHandler.Copy(Dest, Source, Indirect)
else
VarInvalidOp;
end;
procedure _VarCopy(var Dest: TVarData; const Source: TVarData);
asm
MOV CL, 0
JMP VarCopyCommon
end;
procedure VarCopyNoInd(var Dest: Variant; const Source: Variant);
asm
MOV CL, 1
JMP VarCopyCommon
end;
procedure _VarFromWStr(var V: TVarData; const Value: WideString); forward;
procedure VarInt64FromVar(var Dest: TVarData; const Source: TVarData;
DestType: TVarType);
begin
case Source.VType and varTypeMask of
varEmpty:;
varSmallInt: Dest.VInt64 := Source.VSmallInt;
varInteger: Dest.VInt64 := Source.VInteger;
varSingle: Dest.VInt64 := Round(Source.VSingle);
varDouble: Dest.VInt64 := Round(Source.VDouble);
varCurrency: Dest.VInt64 := Round(Source.VCurrency);
varDate: Dest.VInt64 := Round(Source.VDate);
varOleStr: Dest.VInt64 := StrToInt64(Source.VOleStr);
varBoolean: Dest.VInt64 := SmallInt(Source.VBoolean);
varShortInt: Dest.VInt64 := Source.VShortInt;
varByte: Dest.VInt64 := Source.VByte;
varWord: Dest.VInt64 := Source.VWord;
varLongWord: Dest.VInt64 := Source.VLongWord;
varInt64: Dest.VInt64 := Source.VInt64;
else
VarCastError;
end;
Dest.VType := DestType;
end;
procedure VarInt64ToVar(var Dest: TVarData; const Source: TVarData;
DestType: TVarType);
begin
case DestType of
varEmpty:;
varSmallInt: Dest.VSmallInt := Source.VInt64;
varInteger: Dest.VInteger := Source.VInt64;
varSingle: Dest.VSingle := Source.VInt64;
varDouble: Dest.VDouble := Source.VInt64;
varCurrency: Dest.VCurrency := Source.VInt64;
varDate: Dest.VDate := Source.VInt64;
varOleStr: _VarFromWStr(Dest, IntToStr(Source.VInt64));
varBoolean: Dest.VBoolean := Source.VInt64 <> 0;
varShortInt: Dest.VShortInt := Source.VInt64;
varByte: Dest.VByte := Source.VInt64;
varWord: Dest.VWord := Source.VInt64;
varLongWord: Dest.VLongWord := Source.VInt64;
varInt64: Dest.VInt64 := Source.VInt64;
else
VarCastError;
end;
Dest.VType := DestType;
end;
procedure VarChangeType(var Dest: TVarData; const Source: TVarData;
DestType: TVarType); forward;
procedure AnyChangeType(var Dest: TVarData; const Source: TVarData; DestType: TVarType);
var
LTemp: TVarData;
begin
_VarInit(LTemp);
try
_VarCopy(LTemp, Source);
ChangeAnyProc(LTemp);
VarChangeType(Dest, LTemp, DestType);
finally
_VarClear(LTemp);
end;
end;
procedure VarChangeType(var Dest: TVarData; const Source: TVarData;
DestType: TVarType);
function ChangeSourceAny(var Dest: TVarData; const Source: TVarData;
DestType: TVarType): Boolean;
begin
Result := False;
if Source.VType = varAny then
begin
AnyChangeType(Dest, Source, DestType);
Result := True;
end;
end;
var
Temp: TVarData;
LDestType, LSourceType: TVarType;
LDestHandler, LSourceHandler: TCustomVariantType;
begin
LSourceType := Source.VType and varTypeMask;
LDestType := DestType and varTypeMask;
_VarClear(Dest);
if LSourceType < CFirstUserType then
begin
case LDestType of
varString:
begin
if not ChangeSourceAny(Dest, Source, DestType) then
begin
_VarInit(Temp);
try
if VariantChangeTypeEx(Temp, Source, $400, 0, DestType) <> VAR_OK then
VarCastError;
Dest := Temp; // block copy
finally
_VarClear(Temp);
end;
end;
end;
varAny:
AnyChangeType(Dest, Source, DestType);
varInt64:
VarInt64FromVar(Dest, Source, DestType);
else
if LDestType < CFirstUserType then
begin
if LSourceType = varInt64 then
VarInt64ToVar(Dest, Source, DestType)
else
if not ChangeSourceAny(Dest, Source, DestType) then
if VariantChangeTypeEx(Dest, Source, $400, 0, DestType) <> VAR_OK then
VarCastError;
end
else
if FindCustomVariantType(LDestType, LDestHandler) then
LDestHandler.Cast(Dest, Source)
else
VarInvalidOp;
end
end
else if FindCustomVariantType(LSourceType, LSourceHandler) then
LSourceHandler.CastTo(Dest, Source, DestType)
else
VarInvalidOp;
end;
procedure _VarOleStrToString(var Dest: TVarData; const Source: TVarData);
var
StringPtr: Pointer;
begin
StringPtr := nil;
OleStrToStrVar(Source.VOleStr, string(StringPtr));
_VarClear(Dest);
Dest.VType := varString;
Dest.VString := StringPtr;
end;
procedure VarOleStrToString(var Dest: Variant; const Source: Variant);
asm
JMP _VarOleStrToString
end;
procedure _VarStringToOleStr(var Dest: TVarData; const Source: TVarData);
var
OleStrPtr: PWideChar;
begin
OleStrPtr := StringToOleStr(string(Source.VString));
_VarClear(Dest);
Dest.VType := varOleStr;
Dest.VOleStr := OleStrPtr;
end;
procedure VarStringToOleStr(var Dest: Variant; const Source: Variant);
asm
JMP _VarStringToOleStr
end;
procedure _VarCast(var Dest: TVarData; const Source: TVarData; AVarType: Integer);
var
SourceType, DestType: TVarType;
Temp: TVarData;
begin
SourceType := Source.VType;
DestType := TVarType(AVarType);
_VarClear(Dest);
if SourceType = DestType then
_VarCopy(Dest, Source)
else if SourceType = varString then
if DestType = varOleStr then
_VarStringToOleStr(Dest, Source)
else
begin
_VarInit(Temp);
try
_VarStringToOleStr(Temp, Source);
VarChangeType(Dest, Temp, DestType);
finally
_VarClear(Temp);
end;
end
else if (DestType = varString) and (SourceType <> varAny) then
if SourceType = varOleStr then
_VarOleStrToString(Dest, Source)
else
begin
_VarInit(Temp);
try
VarChangeType(Temp, Source, varOleStr);
_VarOleStrToString(Dest, Temp);
finally
_VarClear(Temp);
end;
end
else
VarChangeType(Dest, Source, DestType);
end;
(* VarCast when the destination is OleVariant *)
procedure _VarCastOle(var Dest: TVarData; const Source: TVarData; AVarType: Integer);
var
LSourceType: TVarType;
LSourceHandler: TCustomVariantType;
begin
if AVarType >= CMinVarType then
VarCastError
else
begin
LSourceType := Source.VType and varTypeMask;
_VarClear(Dest);
if LSourceType < CFirstUserType then
_VarCast(Dest, Source, AVarType)
else if FindCustomVariantType(LSourceType, LSourceHandler) then
LSourceHandler.CastTo(Dest, Source, AVarType)
else
VarCastError;
end;
end;
function _VarToInt(const V: TVarData): Integer;
var
Temp: TVarData;
begin
case V.VType of
varInteger : Result := V.VInteger;
varSmallInt : Result := V.VSmallInt;
varByte : Result := V.VByte;
varShortInt : Result := V.VShortInt;
varWord : Result := V.VWord;
varLongWord : Result := V.VLongWord;
varInt64 : Result := V.VInt64;
varDouble : Result := Round(V.VDouble);
varSingle : Result := Round(V.VSingle);
varCurrency : Result := Round(V.VCurrency);
else
_VarInit(Temp);
_VarCast(Temp, V, varInteger);
Result := Temp.VInteger;
end;
end;
function _VarToInt64(const V: TVarData): Int64;
var
Temp: TVarData;
begin
case V.VType of
varInteger : Result := V.VInteger;
varSmallInt : Result := V.VSmallInt;
varByte : Result := V.VByte;
varShortInt : Result := V.VShortInt;
varWord : Result := V.VWord;
varLongWord : Result := V.VLongWord;
varInt64 : Result := V.VInt64;
varDouble : Result := Round(V.VDouble);
varSingle : Result := Round(V.VSingle);
varCurrency : Result := Round(V.VCurrency);
else
_VarInit(Temp);
_VarCast(Temp, V, varInteger);
Result := Temp.VInteger;
end;
end;
function _VarToBool(const V: TVarData): Boolean;
var
Temp: TVarData;
begin
if V.VType = varBoolean then
Result := V.VBoolean
else
begin
_VarInit(Temp);
_VarCast(Temp, V, varBoolean);
Result := Temp.VBoolean;
end;
end;
function _VarToReal(const V: TVarData): Extended;
var
Temp: TVarData;
begin
case V.VType of
varDouble : Result := V.VDouble;
varDate : Result := V.VDate;
varSingle : Result := V.VSingle;
varCurrency : Result := V.VCurrency;
varInteger : Result := V.VInteger;
varSmallInt : Result := V.VSmallInt;
varByte : Result := V.VByte;
varShortInt : Result := V.VShortInt;
varWord : Result := V.VWord;
varLongWord : Result := V.VLongWord;
varInt64 : Result := V.VInt64;
else
_VarInit(Temp);
_VarCast(Temp, V, varDouble);
Result := Temp.VDouble;
end;
end;
function _VarToCurr(const V: TVarData): Currency;
var
Temp: TVarData;
begin
case V.VType of
varCurrency : Result := V.VCurrency;
varDouble : Result := V.VDouble;
varSingle : Result := V.VSingle;
varInteger : Result := V.VInteger;
varSmallInt : Result := V.VSmallInt;
varByte : Result := V.VByte;
varShortInt : Result := V.VShortInt;
varWord : Result := V.VWord;
varLongWord : Result := V.VLongWord;
varInt64 : Result := V.VInt64;
else
_VarInit(Temp);
_VarCast(Temp, V, varCurrency);
Result := Temp.VCurrency;
end;
end;
procedure _VarToLStr(var S: string; const V: TVarData);
var
Temp: TVarData;
begin
if V.VType = varString then
S := String(V.VString)
else
begin
_VarInit(Temp);
try
_VarCast(Temp, V, varString);
S := String(Temp.VString);
finally
_VarClear(Temp);
end;
end;
end;
procedure _VarToPStr(var S; const V: TVarData);
var
Temp: string;
begin
_VarToLStr(Temp, V);
ShortString(S) := Temp;
end;
procedure _VarToWStr(var S: WideString; const V: TVarData);
var
Temp: TVarData;
begin
if V.VType = varOleStr then
S := WideString(V.VOleStr)
else
begin
_VarInit(Temp);
try
_VarCast(Temp, V, varOleStr);
S := WideString(Temp.VOleStr);
finally
_VarClear(Temp);
end;
end;
end;
procedure AnyToIntf(var Intf: IInterface; const V: TVarData);
var
LTemp: TVarData;
begin
_VarInit(LTemp);
try
_VarCopy(LTemp, V);
ChangeAnyProc(LTemp);
if LTemp.VType <> varUnknown then
VarCastError;
Intf := IInterface(LTemp.VUnknown);
finally
_VarClear(LTemp);
end;
end;
procedure _VarToIntf(var Intf: IInterface; const V: TVarData);
var
LHandler: TCustomVariantType;
begin
case V.VType of
varEmpty : Intf := nil;
varUnknown,
varDispatch : Intf := IInterface(V.VUnknown);
varUnknown + varByRef,
varDispatch + varByRef : Intf := IInterface(V.VPointer^);
varAny : AnyToIntf(Intf, V);
else
if not FindCustomVariantType(V.VType, LHandler) or
not LHandler.GetInterface(IInterface, Intf) then
VarCastError;
end;
end;
procedure _VarToDisp(var Dispatch: IDispatch; const V: TVarData);
var
LHandler: TCustomVariantType;
begin
case V.VType of
varEmpty : Dispatch := nil;
varDispatch : Dispatch := IDispatch(V.VDispatch);
varDispatch+varByRef : Dispatch := IDispatch(V.VPointer^);
else
if not FindCustomVariantType(V.VType, LHandler) or
not LHandler.GetInterface(IDispatch, Dispatch) then
VarCastError;
end;
end;
procedure _VarToDynArray(var DynArray: Pointer; const V: TVarData; TypeInfo: Pointer);
asm
CALL DynArrayFromVariant
OR EAX, EAX
JNZ @@1
JMP VarCastError
@@1:
end;
{ pardon the strange case format but it lays out better this way }
procedure _VarFromInt(var V: TVarData; const Value, Range: Integer);
begin
if V.VType >= varOleStr then
_VarClear(V);
case Range of
{-4: varInteger is handled by the else clause }
-2: begin V.VType := varSmallInt; V.VSmallInt := Value; end;
-1: begin V.VType := varShortInt; V.VShortInt := Value; end;
1: begin V.VType := varByte; V.VByte := Value; end;
2: begin V.VType := varWord; V.VWord := Value; end;
4: begin V.VType := varLongWord; V.VLongWord := Value; end;
-3, 0, 3: V.VType := varError;
else
V.VType := varInteger; V.VInteger := Value;
end;
end;
procedure _OleVarFromInt(var V: TVarData; const Value, Range: Integer);
begin
if V.VType >= varOleStr then
_VarClear(V);
V.VType := varInteger;
V.VInteger := Value;
end;
procedure _VarFromInt64(var V: TVarData; const Value: Int64);
begin
if V.VType >= varOleStr then
_VarClear(V);
V.VType := varInt64;
V.VInt64 := Value;
end;
procedure _VarFromBool(var V: TVarData; const Value: Boolean);
begin
if V.VType >= varOleStr then
_VarClear(V);
V.VType := varBoolean;
V.VBoolean := Value;
end;
procedure _VarFromReal; // var V: Variant; const Value: Real
asm
CMP [EAX].TVarData.VType,varOleStr
JB @@1
PUSH EAX
CALL _VarClear
POP EAX
@@1: MOV [EAX].TVarData.VType,varDouble
FSTP [EAX].TVarData.VDouble
FWAIT
end;
procedure _VarFromTDateTime; // var V: Variant; const Value: TDateTime
asm
CMP [EAX].TVarData.VType,varOleStr
JB @@1
PUSH EAX
CALL _VarClear
POP EAX
@@1: MOV [EAX].TVarData.VType,varDate
FSTP [EAX].TVarData.VDouble
FWAIT
end;
procedure _VarFromCurr; // var V: Variant; const Value: Currency
asm
CMP [EAX].TVarData.VType,varOleStr
JB @@1
PUSH EAX
CALL _VarClear
POP EAX
@@1: MOV [EAX].TVarData.VType,varCurrency
FISTP [EAX].TVarData.VCurrency
FWAIT
end;
procedure _VarFromLStr(var V: TVarData; const Value: string);
begin
if V.VType >= varOleStr then
_VarClear(V);
V.VString := nil;
V.VType := varString;
String(V.VString) := Value;
end;
procedure _VarFromPStr(var V: TVarData; const Value: ShortString);
begin
_VarFromLStr(V, Value);
end;
procedure _VarFromWStr(var V: TVarData; const Value: WideString);
begin
if V.VType >= varOleStr then
_VarClear(V);
V.VOleStr := nil;
V.VType := varOleStr;
WideString(Pointer(V.VOleStr)) := Copy(Value, 1, MaxInt);
end;
procedure _VarFromIntf(var V: TVarData; const Value: IInterface);
begin
if V.VType >= varOleStr then
_VarClear(V);
V.VUnknown := nil;
V.VType := varUnknown;
IInterface(V.VUnknown) := Value;
end;
procedure _VarFromDisp(var V: TVarData; const Value: IDispatch);
begin
if V.VType >= varOleStr then
_VarClear(V);
V.VDispatch := nil;
V.VType := varDispatch;
IInterface(V.VDispatch) := Value;
end;
procedure _VarFromDynArray(var V: TVarData; const DynArray: Pointer; TypeInfo: Pointer);
asm
PUSH EAX
CALL DynArrayToVariant
POP EAX
CMP [EAX].TVarData.VType,varEmpty
JNE @@1
JMP VarCastError
@@1:
end;
procedure _OleVarFromLStr(var V: TVarData {OleVariant}; const Value: string);
begin
_VarFromWStr(V, WideString(Value));
end;
procedure _OleVarFromPStr(var V: TVarData {OleVariant}; const Value: ShortString);
begin
_OleVarFromLStr(V, Value);
end;
procedure _OleVarFromVar(var Dest: TVarData {OleVariant}; const Source: TVarData); forward;
procedure OleVarFromAny(var V: TVarData {OleVariant}; const Value: TVarData);
var
LTemp: TVarData;
begin
_VarInit(LTemp);
try
_VarCopy(LTemp, Value);
ChangeAnyProc(LTemp);
_VarCopy(V, LTemp);
finally
_VarClear(LTemp);
end;
end;
procedure OleVarFromVarArrayProc(var Dest: TVarData; const Src: TVarData);
var
LFromType: TVarType;
LFromHandler: TCustomVariantType;
begin
LFromType := Src.VType and varTypeMask;
if LFromType < CFirstUserType then
_OleVarFromVar(Dest, Src)
else if FindCustomVariantType(LFromType, LFromHandler) then
LFromHandler.CastToOle(Dest, Src)
else
VarInvalidOp;
end;
procedure _OleVarFromVar(var Dest: TVarData {OleVariant}; const Source: TVarData);
var
LSourceType: TVarType;
LSourceHandler: TCustomVariantType;
begin
_VarClear(Dest);
LSourceType := Source.VType and varTypeMask;
if LSourceType < CFirstUserType then
begin
{ This won't strip the array bit so only simple types will be handled by case }
case Source.VType and not varByRef of
varShortInt, varByte, varWord:
VarChangeType(Dest, Source, varInteger);
varLongWord:
if Source.VLongWord <= Cardinal(High(Integer)) then
VarChangeType(Dest, Source, varInteger)
else
VarChangeType(Dest, Source, varDouble);
varInt64:
if (Source.VInt64 <= High(Integer)) and
(Source.VInt64 >= Low(Integer)) then
VarChangeType(Dest, Source, varInteger)
else
VarChangeType(Dest, Source, varDouble);
varString:
_OleVarFromLStr(Dest, String(Source.VString));
varAny:
OleVarFromAny(Dest, Source);
else
if Source.VType and varArray <> 0 then
VarArrayCopyForEach(Dest, Source, OleVarFromVarArrayProc)
else
_VarCopy(Dest, Source);
end;
end
else if FindCustomVariantType(LSourceType, LSourceHandler) then
LSourceHandler.CastToOle(Dest, Source)
else
VarInvalidOp;
end;
procedure VarStrCat(var Dest: Variant; const Source: Variant);
begin
if TVarData(Dest).VType = varString then
Dest := string(Dest) + string(Source)
else
Dest := WideString(Dest) + WideString(Source);
end;
procedure _SimpleVarOp(var Left: TVarData; const Right: TVarData; const OpCode: TVarOp); forward;
procedure _VarOp(var Left: TVarData; const Right: TVarData; const OpCode: TVarOp);
var
LLeftType, LRightType, LNewLeftType, LNewRightType: TVarType;
LLeftHandler, LRightHandler: TCustomVariantType;
LTemp: TVarData;
begin
LLeftType := Left.VType and varTypeMask;
LRightType := Right.VType and varTypeMask;
// just in case we need it
_VarInit(LTemp);
try
// simple and ???
if LLeftType < CFirstUserType then
begin
// simple and simple
if LRightType < CFirstUserType then
_SimpleVarOp(Left, Right, OpCode)
// simple and custom but the custom doesn't really exist (nasty but possible )
else if not FindCustomVariantType(LRightType, LRightHandler) then
VarInvalidOp
// does the custom want to take over?
else if LRightHandler.LeftPromotion(Left, OpCode, LNewLeftType) then
begin
// convert the left side
if LLeftType <> LNewLeftType then
begin
_VarCast(LTemp, Left, LNewLeftType);
_VarCopy(Left, LTemp);
if (Left.VType and varTypeMask) <> LNewLeftType then
VarCastError;
end;
LRightHandler.BinaryOp(Left, Right, OpCode);
end
// simple then converts custom then
else
begin
// convert the right side to the left side's type
_VarCast(LTemp, Right, LLeftType);
if (LTemp.VType and varTypeMask) <> LLeftType then
VarCastError;
_SimpleVarOp(Left, LTemp, OpCode);
end;
end
// custom and something else
else
begin
if not FindCustomVariantType(LLeftType, LLeftHandler) then
VarInvalidOp;
// does the left side like what is in the right side?
if LLeftHandler.RightPromotion(Right, OpCode, LNewRightType) then
begin
// make the right side right
if LRightType <> LNewRightType then
begin
_VarCast(LTemp, Right, LNewRightType);
if (LTemp.VType and varTypeMask) <> LNewRightType then
VarCastError;
LLeftHandler.BinaryOp(Left, LTemp, OpCode);
end
// type is correct so lets go!
else
LLeftHandler.BinaryOp(Left, Right, OpCode);
end
// custom and simple and the right one can't convert the simple
else if LRightType < CFirstUserType then
begin
// convert the left side to the right side's type
if LLeftType <> LRightType then
begin
_VarCast(LTemp, Left, LRightType);
_VarCopy(Left, LTemp);
if (Left.VType and varTypeMask) <> LRightType then
VarCastError;
end;
_SimpleVarOp(Left, Right, OpCode);
end
// custom and custom but the right one doesn't really exist (nasty but possible )
else if not FindCustomVariantType(LRightType, LRightHandler) then
VarInvalidOp
// custom and custom and the right one can handle the left's type
else if LRightHandler.LeftPromotion(Left, OpCode, LNewLeftType) then
begin
// convert the left side
if LLeftType <> LNewLeftType then
begin
_VarCast(LTemp, Left, LNewLeftType);
_VarCopy(Left, LTemp);
if (Left.VType and varTypeMask) <> LNewLeftType then
VarCastError;
end;
LRightHandler.BinaryOp(Left, Right, OpCode);
end
// custom and custom but neither type can deal with each other
else
VarInvalidOp;
end;
finally
_VarClear(LTemp);
end;
end;
procedure AnyOp(var Left: TVarData; const Right: TVarData; const OpCode: TVarOp);
var
LTemp: TVarData;
begin
if Left.VType = varAny then
ChangeAnyProc(Left);
if Right.VType = varAny then
begin
_VarInit(LTemp);
try
_VarCopy(LTemp, Right);
ChangeAnyProc(LTemp);
_VarOp(Left, LTemp, OpCode);
finally
_VarClear(LTemp);
end;
end
else
_VarOp(Left, Right, OpCode);
end;
procedure _SimpleVarOp(var Left: TVarData; const Right: TVarData; const OpCode: TVarOp);
procedure Failure(const Prefix: string);
begin
Assert(False, Prefix + ': Lt = ' + IntToStr(Left.VType) + ' Rt = ' +
IntToStr(Right.VType) + ' Op = ' + IntToStr(OpCode));
end;
procedure AnyOp(var Left: TVarData; const Right: TVarData; const OpCode: TVarOp);
var
vTemp: TVarData;
begin
if Left.VType = varAny then
ChangeAnyProc(Left);
if Right.VType = varAny then
begin
_VarInit(vTemp);
_VarCopy(vTemp, Right);
try
ChangeAnyProc(vTemp);
_VarOp(Left, vTemp, OpCode);
finally
_VarClear(vTemp);
end;
end
else
_VarOp(Left, Right, OpCode);
end;
function CheckType(T: TVarType): TVarType;
begin
Result := T and varTypeMask;
if Result > varLast then
if Result = varString then
Result := varOleStr
else if Result = varAny then
AnyOp(Left, Right, OpCode)
else
VarInvalidOp;
end;
procedure RealOp(var Left: TVarData; const Right: TVarData; const OpCode: TVarOp);
var
L, R: Double;
begin
L := _VarToReal(Left);
R := _VarToReal(Right);
case OpCode of
opAdd : L := L + R;
opSubtract : L := L - R;
opMultiply : L := L * R;
opDivide : L := L / R;
else
Failure('RealOp');
end;
Variant(Left) := L;
end;
procedure IntOp(var Left: TVarData; const Right: TVarData; const OpCode: TVarOp);
var
L, R: Integer;
Overflow: Boolean;
begin
Overflow := False;
L := _VarToInt(Left);
R := _VarToInt(Right);
case OpCode of
opAdd : asm
MOV EAX, L
MOV EDX, R
ADD EAX, EDX
SETO Overflow
MOV L, EAX
end;
opSubtract : asm
MOV EAX, L
MOV EDX, R
SUB EAX, EDX
SETO Overflow
MOV L, EAX
end;
opMultiply : asm
MOV EAX, L
MOV EDX, R
IMUL EDX
SETO Overflow
MOV L, EAX
end;
opDivide : Failure('IntOp');
opIntDivide : L := L div R;
opModulus : L := L mod R;
opShiftLeft : L := L shl R;
opShiftRight : L := L shr R;
opAnd : L := L and R;
opOr : L := L or R;
opXor : L := L xor R;
else
Failure('IntOp');
end;
if Overflow then
RealOp(Left, Right, OpCode)
else
Variant(Left) := L;
end;
procedure Int64Op(var Left: TVarData; const Right: TVarData; const OpCode: TVarOp);
var
L, R: Int64;
Overflow: Boolean;
begin
Overflow := False;
L := _VarToInt64(Left);
R := _VarToInt64(Right);
case OpCode of
opAdd, opSubtract, opMultiply:
{$RANGECHECKS ON}
try
case OpCode of
opAdd : L := L + R;
opSubtract : L := L - R;
opMultiply : L := L * R;
end;
except
on EOverflow do
Overflow := True;
end;
{$RANGECHECKS OFF}
opDivide : Failure('Int64Op');
opIntDivide : L := L div R;
opModulus : L := L mod R;
opShiftLeft : L := L shl R;
opShiftRight : L := L shr R;
opAnd : L := L and R;
opOr : L := L or R;
opXor : L := L xor R;
else
Failure('Int64Op');
end;
if Overflow then
RealOp(Left, Right, OpCode)
else
Variant(Left) := L;
end;
var
L, R: TBaseType;
C: Currency;
D: Double;
begin
L := BaseTypeMap[CheckType(Left.VType)];
R := BaseTypeMap[CheckType(Right.VType)];
case OpTypeMap[L, R] of
btErr:
VarInvalidOp;
btNul:
begin
_VarClear(Left);
Left.VType := varNull;
end;
btInt:
if OpCode = opDivide then
RealOp(Left, Right, OpCode)
else
IntOp(Left, Right, OpCode);
btFlt:
if OpCode >= opIntDivide then
IntOp(Left, Right, OpCode)
else
RealOp(Left, Right, OpCode);
btCur:
case OpCode of
opAdd : Variant(Left) := _VarToCurr(Left) + _VarToCurr(Right);
opSubtract : Variant(Left) := _VarToCurr(Left) - _VarToCurr(Right);
opMultiply,
opDivide :
begin
if (L = btCur) and (R = btCur) then
begin
if OpCode = opMultiply then
Variant(Left) := Left.VCurrency * Right.VCurrency
else
Variant(Left) := Left.VCurrency / Right.VCurrency;
end
else if R = btCur then
begin // L <> btCur
if OpCode = opMultiply then
begin
C := _VarToReal(Left) * Right.VCurrency;
Variant(Left) := C;
end
else
begin
D := _VarToCurr(Left) / Right.VCurrency;
Variant(Left) := D;
end;
end
else // L = btCur, R <> btCur
begin
if OpCode = opMultiply then
begin
C := Left.VCurrency * _VarToReal(Right);
Variant(Left) := C;
end
else
begin
C := Left.VCurrency / _VarToReal(Right);
Variant(Left) := C;
end;
end;
end;
else
IntOp(Left, Right, OpCode);
end;
btStr:
if OpCode = opAdd then
VarStrCat(Variant(Left), Variant(Right))
else
if OpCode >= opIntDivide then
IntOp(Left, Right, OpCode)
else
RealOp(Left, Right, OpCode);
btBol:
if OpCode < opAnd then
if OpCode >= opIntDivide then
IntOp(Left, Right, OpCode)
else
RealOp(Left, Right, OpCode)
else
begin
case OpCode of
opAnd: Variant(Left) := _VarToBool(Left) and _VarToBool(Right);
opOr : Variant(Left) := _VarToBool(Left) or _VarToBool(Right);
opXor: Variant(Left) := _VarToBool(Left) xor _VarToBool(Right);
end;
end;
btDat:
case OpCode of
opAdd:
begin
RealOp(Left, Right, OpCode);
Left.VType := varDate;
end;
opSubtract:
begin
RealOp(Left, Right, OpCode);
if (L = btDat) and (R = btDat) then
Left.VType := varDate;
end;
opMultiply,
opDivide:
RealOp(Left, Right, OpCode);
else
IntOp(Left, Right, OpCode);
end;
btI64:
if OpCode = opDivide then
RealOp(Left, Right, OpCode)
else
Int64Op(Left, Right, OpCode);
else
Failure('VarOp');
end;
end;
(*
const
C10000: Single = 10000;
procedure _SimpleVarOp(var Left: TVarData; const Right: TVarData; const OpCode: TVarOp);
asm
PUSH EBX
PUSH ESI
PUSH EDI
MOV EDI,EAX
MOV ESI,EDX
MOV EBX,ECX
MOV EAX,[EDI].TVarData.VType.Integer
MOV EDX,[ESI].TVarData.VType.Integer
AND EAX,varTypeMask
AND EDX,varTypeMask
CMP EAX,varLast
JBE @@1
CMP EAX,varString
JNE @@4
MOV EAX,varOleStr
@@1: CMP EDX,varLast
JBE @@2
CMP EDX,varString
JNE @@3
MOV EDX,varOleStr
@@2: MOV AL,BaseTypeMap.Byte[EAX]
MOV DL,BaseTypeMap.Byte[EDX]
MOVZX ECX,OpTypeMap.Byte[EAX*8+EDX]
CALL @VarOpTable.Pointer[ECX*4]
POP EDI
POP ESI
POP EBX
RET
@@3: MOV EAX,EDX
@@4: CMP EAX,varAny
JNE @InvalidOp
POP EDI
POP ESI
POP EBX
JMP AnyOp
@VarOpTable:
DD @VarOpError
DD @VarOpNull
DD @VarOpInteger
DD @VarOpReal
DD @VarOpCurr
DD @VarOpString
DD @VarOpBoolean
DD @VarOpDate
@VarOpError:
POP EAX
@InvalidOp:
POP EDI
POP ESI
POP EBX
JMP VarInvalidOp
@VarOpNull:
MOV EAX,EDI
CALL _VarClear
MOV [EDI].TVarData.VType,varNull
RET
@VarOpInteger:
CMP BL,opDivide
JE @RealOp
@IntegerOp:
MOV EAX,ESI
CALL _VarToInt
PUSH EAX
MOV EAX,EDI
CALL _VarToInt
POP EDX
CALL @IntegerOpTable.Pointer[EBX*4]
MOV EDX,EAX
MOV EAX,EDI
JMP _VarFromInt
@IntegerOpTable:
DD @IntegerAdd
DD @IntegerSub
DD @IntegerMul
DD 0
DD @IntegerDiv
DD @IntegerMod
DD @IntegerShl
DD @IntegerShr
DD @IntegerAnd
DD @IntegerOr
DD @IntegerXor
@IntegerAdd:
ADD EAX,EDX
JO @IntToRealOp
RET
@IntegerSub:
SUB EAX,EDX
JO @IntToRealOp
RET
@IntegerMul:
IMUL EDX
JO @IntToRealOp
RET
@IntegerDiv:
MOV ECX,EDX
CDQ
IDIV ECX
RET
@IntegerMod:
MOV ECX,EDX
CDQ
IDIV ECX
MOV EAX,EDX
RET
@IntegerShl:
MOV ECX,EDX
SHL EAX,CL
RET
@IntegerShr:
MOV ECX,EDX
SHR EAX,CL
RET
@IntegerAnd:
AND EAX,EDX
RET
@IntegerOr:
OR EAX,EDX
RET
@IntegerXor:
XOR EAX,EDX
RET
@IntToRealOp:
POP EAX
JMP @RealOp
@VarOpReal:
CMP BL,opIntDivide
JAE @IntegerOp
@RealOp:
MOV EAX,ESI
CALL _VarToReal
SUB ESP,12
FSTP TBYTE PTR [ESP]
MOV EAX,EDI
CALL _VarToReal
FLD TBYTE PTR [ESP]
ADD ESP,12
CALL @RealOpTable.Pointer[EBX*4]
@RealResult:
MOV EAX,EDI
JMP _VarFromReal
@VarOpCurr:
CMP BL,opIntDivide
JAE @IntegerOp
CMP BL,opMultiply
JAE @CurrMulDvd
MOV EAX,ESI
CALL _VarToCurr
SUB ESP,12
FSTP TBYTE PTR [ESP]
MOV EAX,EDI
CALL _VarToCurr
FLD TBYTE PTR [ESP]
ADD ESP,12
CALL @RealOpTable.Pointer[EBX*4]
@CurrResult:
MOV EAX,EDI
JMP _VarFromCurr
@CurrMulDvd:
CMP DL,btCur
JE @CurrOpCurr
MOV EAX,ESI
CALL _VarToReal
FILD [EDI].TVarData.VCurrency
FXCH
CALL @RealOpTable.Pointer[EBX*4]
JMP @CurrResult
@CurrOpCurr:
CMP BL,opDivide
JE @CurrDvdCurr
CMP AL,btCur
JE @CurrMulCurr
MOV EAX,EDI
CALL _VarToReal
FILD [ESI].TVarData.VCurrency
FMUL
JMP @CurrResult
@CurrMulCurr:
FILD [EDI].TVarData.VCurrency
FILD [ESI].TVarData.VCurrency
FMUL
FDIV C10000
JMP @CurrResult
@CurrDvdCurr:
MOV EAX,EDI
CALL _VarToCurr
FILD [ESI].TVarData.VCurrency
FDIV
JMP @RealResult
@RealOpTable:
DD @RealAdd
DD @RealSub
DD @RealMul
DD @RealDvd
@RealAdd:
FADD
RET
@RealSub:
FSUB
RET
@RealMul:
FMUL
RET
@RealDvd:
FDIV
RET
@VarOpString:
CMP BL,opAdd
JNE @VarOpReal
MOV EAX,EDI
MOV EDX,ESI
JMP VarStrCat
@VarOpBoolean:
CMP BL,opAnd
JB @VarOpReal
MOV EAX,ESI
CALL _VarToBool
PUSH EAX
MOV EAX,EDI
CALL _VarToBool
POP EDX
CALL @IntegerOpTable.Pointer[EBX*4]
MOV EDX,EAX
MOV EAX,EDI
JMP _VarFromBool
@VarOpDate:
CMP BL,opSubtract
JA @VarOpReal
JB @DateOp
MOV AH,DL
CMP AX,btDat+btDat*256
JE @RealOp
@DateOp:
CALL @RealOp
MOV [EDI].TVarData.VType,varDate
RET
end;
*)
(*function VarCompareString(const S1, S2: string): Integer;
asm
PUSH ESI
PUSH EDI
MOV ESI,EAX
MOV EDI,EDX
OR EAX,EAX
JE @@1
MOV EAX,[EAX-4]
@@1: OR EDX,EDX
JE @@2
MOV EDX,[EDX-4]
@@2: MOV ECX,EAX
CMP ECX,EDX
JBE @@3
MOV ECX,EDX
@@3: CMP ECX,ECX
REPE CMPSB
JE @@4
MOVZX EAX,BYTE PTR [ESI-1]
MOVZX EDX,BYTE PTR [EDI-1]
@@4: SUB EAX,EDX
POP EDI
POP ESI
end;
function VarCmpStr(const V1, V2: Variant): Integer;
begin
Result := VarCompareString(V1, V2);
end;*)
function SimpleVarCmp(const Left, Right: TVarData): TVarCompareResult; forward;
function VarCompare(const Left, Right: TVarData; const OpCode: TVarOp): TVarCompareResult;
const
CBooleanToRelationship: array [opCmpEQ..opCmpGE, Boolean] of TVarCompareResult =
// False True
((crLessThan, crEqual), // opCmpEQ = 14;
(crEqual, crLessThan), // opCmpNE = 15;
(crEqual, crLessThan), // opCmpLT = 16;
(crGreaterThan, crLessThan), // opCmpLE = 17;
(crEqual, crGreaterThan), // opCmpGT = 18;
(crLessThan, crGreaterThan)); // opCmpGE = 19;
var
LLeftType, LRightType, LNewLeftType, LNewRightType: TVarType;
LLeftHandler, LRightHandler: TCustomVariantType;
LTemp, LLeft: TVarData;
begin
LLeftType := TVarData(Left).VType and varTypeMask;
LRightType := TVarData(Right).VType and varTypeMask;
Result := crEqual;
// just in case we need to
_VarInit(LTemp);
try
// simple and ???
if LLeftType < CFirstUserType then
begin
// simple and simple
if LRightType < CFirstUserType then
begin
// are ANYs involved?
if (LLeftType = varAny) or (LRightType = varAny) then
begin
_VarInit(LLeft);
try
// resolve the left side into a normal simple type
_VarCopy(LLeft, Left);
if LLeftType = varAny then
ChangeAnyProc(LLeft);
// does the right side need to be reduced to a simple type
if LRightType = varAny then
begin
_VarCopy(LTemp, Right);
ChangeAnyProc(LTemp);
Result := VarCompare(LLeft, LTemp, OpCode);
end
// right side is fine as is
else
Result := VarCompare(LLeft, Right, OpCode);
finally
_VarClear(LLeft);
end;
end
// just simple vs simple
else
Result := SimpleVarCmp(Left, Right);
end
// simple and custom but the custom doesn't really exist (nasty but possible )
else if not FindCustomVariantType(LRightType, LRightHandler) then
VarInvalidOp
// does the custom want to take over?
else if LRightHandler.LeftPromotion(Left, opCompare, LNewLeftType) then
begin
// convert the left side
if Left.VType <> LNewLeftType then
begin
_VarCast(LTemp, Left, LNewLeftType);
if (LTemp.VType and varTypeMask) <> LNewLeftType then
VarCastError;
Result := CBooleanToRelationship[OpCode, LRightHandler.CompareOp(LTemp, Right, OpCode)];
end
// already that type!
else
Result := CBooleanToRelationship[OpCode, LRightHandler.CompareOp(Left, Right, OpCode)];
end
// simple then converts custom then
else
begin
// convert the right side to the left side's type
_VarCast(LTemp, Right, LLeftType);
if (LTemp.VType and varTypeMask) <> LLeftType then
VarCastError;
Result := SimpleVarCmp(Left, LTemp)
end;
end
// custom and something else
else
begin
if not FindCustomVariantType(LLeftType, LLeftHandler) then
VarInvalidOp
// does the left side like what is in the right side?
else if LLeftHandler.RightPromotion(Right, opCompare, LNewRightType) then
begin
// make the right side right
if LRightType <> LNewRightType then
begin
_VarCast(LTemp, Right, LNewRightType);
if (LTemp.VType and varTypeMask) <> LNewRightType then
VarCastError;
Result := CBooleanToRelationship[OpCode, LLeftHandler.CompareOp(Left, LTemp, OpCode)];
end
// already that type
else
Result := CBooleanToRelationship[OpCode, LLeftHandler.CompareOp(Left, Right, OpCode)];
end
// custom and simple
else if LRightType < CFirstUserType then
begin
// convert the left side to the right side's type
_VarCast(LTemp, Left, LRightType);
if (LTemp.VType and varTypeMask) <> LRightType then
VarCastError;
Result := SimpleVarCmp(LTemp, Right)
end
// custom and custom but the right one doesn't really exist (nasty but possible )
else if not FindCustomVariantType(LRightType, LRightHandler) then
VarInvalidOp
// custom and custom and the right one can handle the left's type
else if LRightHandler.LeftPromotion(Left, opCompare, LNewLeftType) then
begin
// convert the left side
if LLeftType <> LNewLeftType then
begin
_VarCast(LTemp, Left, LNewLeftType);
if (LTemp.VType and varTypeMask) <> LNewLeftType then
VarCastError;
Result := CBooleanToRelationship[OpCode, LRightHandler.CompareOp(LTemp, Right, OpCode)];
end
// it's already correct!
else
Result := CBooleanToRelationship[OpCode, LRightHandler.CompareOp(Left, Right, OpCode)];
end
// custom and custom but neither type can deal with each other
else
VarInvalidOp;
end;
// we may have to
finally
_VarClear(LTemp);
end;
end;
procedure _VarCmp(const Left, Right: Variant; const OpCode: TVarOp); // compiler requires result in flags
asm
// IN: EAX = Left
// IN: EDX = Right
// OUT: Flags register indicates less than, greater than, or equal
CALL VarCompare
CMP AL, crEqual
end;
function SimpleVarCmp(const Left, Right: TVarData): TVarCompareResult;
function CheckType(T: TVarType): TVarType;
begin
Result := T and varTypeMask;
if Result > varLast then
if Result = varString then
Result := varOleStr
else
VarInvalidOp;
end;
function IntCompare(A, B: Integer): TVarCompareResult;
begin
if A < B then
Result := crLessThan
else if A > B then
Result := crGreaterThan
else
Result := crEqual;
end;
function Int64Compare(const A, B: Int64): TVarCompareResult;
begin
if A < B then
Result := crLessThan
else if A > B then
Result := crGreaterThan
else
Result := crEqual;
end;
function RealCompare(const A, B: Double): TVarCompareResult;
begin
if A < B then
Result := crLessThan
else if A > B then
Result := crGreaterThan
else
Result := crEqual;
end;
// keep string temps out of the main proc
function StringCompare(const L, R: TVarData): TVarCompareResult;
var
A, B: string;
begin
_VarToLStr(A, L);
_VarToLStr(B, R);
Result := IntCompare(StrComp(PChar(A), PChar(B)), 0);
end;
var
L, R: TBaseType;
begin
Result := crEqual;
L := BaseTypeMap[CheckType(Left.VType)];
R := BaseTypeMap[CheckType(Right.VType)];
case OpTypeMap[L, R] of
btErr: VarInvalidOp;
btNul: Result := IntCompare(Ord(L), Ord(R));
btInt: Result := IntCompare(_VarToInt(Left), _VarToInt(Right)); //<<<<============================
btI64: Result := Int64Compare(_VarToInt64(Left), _VarToInt64(Right));
btFlt,
btDat: Result := RealCompare(_VarToReal(Left), _VarToReal(Right));
btCur: Result := RealCompare(_VarToCurr(Left), _VarToCurr(Right));
btStr: Result := StringCompare(Left, Right);
btBol: Result := IntCompare(Integer(_VarToBool(Left)), Integer(_VarToBool(Right)));
else
assert(False, 'VarCmp L = ' + IntToStr(Left.VType) + ' R = ' + IntToStr(Right.VType));
end;
end;
(*
function SimpleVarCmp(const Left, Right: TVarData): TVarCompareResult;
asm
PUSH ESI
PUSH EDI
MOV EDI,EAX
MOV ESI,EDX
MOV EAX,[EDI].TVarData.VType.Integer
MOV EDX,[ESI].TVarData.VType.Integer
AND EAX,varTypeMask
AND EDX,varTypeMask
CMP EAX,varLast
JBE @@1
CMP EAX,varString
JNE @VarCmpError
MOV EAX,varOleStr
@@1: CMP EDX,varLast
JBE @@2
CMP EDX,varString
JNE @VarCmpError
MOV EDX,varOleStr
@@2: MOV AL,BaseTypeMap.Byte[EAX]
MOV DL,BaseTypeMap.Byte[EDX]
MOVZX ECX,OpTypeMap.Byte[EAX*8+EDX]
JMP @VarCmpTable.Pointer[ECX*4]
@VarCmpTable:
DD @VarCmpError
DD @VarCmpNull
DD @VarCmpInteger
DD @VarCmpReal
DD @VarCmpCurr
DD @VarCmpString
DD @VarCmpBoolean
DD @VarCmpDate
@VarCmpError:
POP EDI
POP ESI
JMP VarInvalidOp
@VarCmpNull:
CMP AL,DL
JMP @Exit
@VarCmpInteger:
MOV EAX,ESI
CALL _VarToInt
XCHG EAX,EDI
CALL _VarToInt
CMP EAX,EDI
JMP @Exit
@VarCmpReal:
@VarCmpDate:
MOV EAX,EDI
CALL _VarToReal
SUB ESP,12
FSTP TBYTE PTR [ESP]
MOV EAX,ESI
CALL _VarToReal
FLD TBYTE PTR [ESP]
ADD ESP,12
@RealCmp:
FCOMPP
FNSTSW AX
MOV AL,AH { Move CF into SF }
AND AX,4001H
ROR AL,1
OR AH,AL
SAHF
JMP @Exit
@VarCmpCurr:
MOV EAX,EDI
CALL _VarToCurr
SUB ESP,12
FSTP TBYTE PTR [ESP]
MOV EAX,ESI
CALL _VarToCurr
FLD TBYTE PTR [ESP]
ADD ESP,12
JMP @RealCmp
@VarCmpString:
MOV EAX,EDI
MOV EDX,ESI
CALL VarCmpStr
CMP EAX,0
JMP @Exit
@VarCmpBoolean:
MOV EAX,ESI
CALL _VarToBool
XCHG EAX,EDI
CALL _VarToBool
MOV EDX,EDI
CMP AL,DL
@Exit:
MOV AL, crLessThan
JL @Exit2
MOV AL, crEqual
JE @Exit2
MOV AL, crGreaterThan
@Exit2:
AND EAX, $FF
POP EDI
POP ESI
end;
*)
procedure _SimpleVarNeg(var V: TVarData); forward;
procedure _VarNeg(var V: TVarData);
var
LType: TVarType;
LHandler: TCustomVariantType;
begin
LType := V.VType and varTypeMask;
if LType < CFirstUserType then
_SimpleVarNeg(V)
else
if FindCustomVariantType(LType, LHandler) then
LHandler.UnaryOp(V, opNegate)
else
VarInvalidOp;
end;
procedure _SimpleVarNeg(var V: TVarData);
var
T: TVarType;
begin
T := V.VType and varTypeMask;
if T > varLast then
if T = varString then
T := varOleStr
else
VarInvalidOp;
case BaseTypeMap[T] of
btErr : VarInvalidOp;
btNul : ; // do nothing
btBol,
btInt : _VarFromInt(V, -_VarToInt(V), -4); //<<<<============================
btI64 : _VarFromInt64(V, -_VarToInt64(V));
btStr,
btFlt : Variant(V) := -_VarToReal(V);
btCur : V.VCurrency := -V.VCurrency;
btDat : V.VDate := -V.VDate;
end;
end;
(*
procedure _SimpleVarNeg(var V: TVarData);
asm
MOV EDX,[EAX].TVarData.VType.Integer
AND EDX,varTypeMask
CMP EDX,varLast
JBE @@1
CMP EDX,varString
JNE @VarNegError
MOV EDX,varOleStr
@@1: MOV DL,BaseTypeMap.Byte[EDX]
JMP @VarNegTable.Pointer[EDX*4]
@@2: CMP EAX,varAny
JNE @VarNegError
PUSH EAX
CALL [ChangeAnyProc]
POP EAX
JMP _VarNeg
@VarNegTable:
DD @VarNegError
DD @VarNegNull
DD @VarNegInteger
DD @VarNegReal
DD @VarNegCurr
DD @VarNegReal
DD @VarNegInteger
DD @VarNegDate
@VarNegError:
JMP VarInvalidOp
@VarNegNull:
RET
@VarNegInteger:
PUSH EAX
CALL _VarToInt
NEG EAX
MOV EDX,EAX
POP EAX
JMP _VarFromInt
@VarNegReal:
PUSH EAX
CALL _VarToReal
FCHS
POP EAX
JMP _VarFromReal
@VarNegCurr:
FILD [EAX].TVarData.VCurrency
FCHS
FISTP [EAX].TVarData.VCurrency
FWAIT
RET
@VarNegDate:
FLD [EAX].TVarData.VDate
FCHS
FSTP [EAX].TVarData.VDate
FWAIT
end;
*)
procedure _SimpleVarNot(var V: TVarData); forward;
procedure _VarNot(var V: TVarData);
var
LType: TVarType;
LHandler: TCustomVariantType;
begin
LType := V.VType and varTypeMask;
if LType < CFirstUserType then
_SimpleVarNot(V)
else
if FindCustomVariantType(LType, LHandler) then
LHandler.UnaryOp(V, opNot)
else
VarInvalidOp;
end;
procedure _SimpleVarNot(var V: TVarData);
var
T: TVarType;
begin
T := V.VType and varTypeMask;
case T of
varEmpty : VarInvalidOp;
varBoolean : V.VBoolean := not V.VBoolean;
varNull : ; // do nothing
varAny :
begin
ChangeAnyProc(V);
_VarNot(V);
end;
else
if (T = varInt64) then
_VarFromInt64(V, not _VarToInt64(V))
else if (T = varString) or (T <= varLast) then
_VarFromInt(V, not _VarToInt(V), -4)
else
VarInvalidOp;
end;
end;
(*
procedure _SimpleVarNot(var V: TVarData);
asm
MOV EDX,[EAX].TVarData.VType.Integer
AND EDX,varTypeMask
JE @@2
CMP EDX,varBoolean
JE @@3
CMP EDX,varNull
JE @@4
CMP EDX,varLast
JBE @@1
CMP EDX,varString
JE @@1
CMP EAX,varAny
JNE @@2
PUSH EAX
CALL [ChangeAnyProc]
POP EAX
JMP _VarNot
@@1: PUSH EAX
CALL _VarToInt
NOT EAX
MOV EDX,EAX
POP EAX
JMP _VarFromInt
@@2: JMP VarInvalidOp
@@3: MOV DX,[EAX].TVarData.VBoolean
NEG DX
SBB EDX,EDX
NOT EDX
MOV [EAX].TVarData.VBoolean,DX
@@4:
end;
*)
procedure _VarCopyNoInd; // ARGS PLEASE!
asm
JMP VarCopyNoInd
end;
procedure _VarAddRef(var V: Variant);
asm
CMP [EAX].TVarData.VType,varOleStr
JB @@1
PUSH [EAX].Integer[12]
PUSH [EAX].Integer[8]
PUSH [EAX].Integer[4]
PUSH [EAX].Integer[0]
MOV [EAX].TVarData.VType,varEmpty
MOV EDX,ESP
CALL _VarCopy
ADD ESP,16
@@1:
end;
function VarType(const V: Variant): TVarType;
begin
Result := TVarData(V).VType;
end;
function VarAsType(const V: Variant; AVarType: TVarType): Variant;
begin
_VarCast(TVarData(Result), TVarData(V), AVarType);
end;
function VarIsType(const V: Variant; AVarType: TVarType): Boolean;
begin
Result := (TVarData(V).VType and varTypeMask) = AVarType;
end;
function VarIsType(const V: Variant; const AVarTypes: array of TVarType): Boolean;
var
I: Integer;
begin
Result := False;
for I := Low(AVarTypes) to High(AVarTypes) do
if (TVarData(V).VType and varTypeMask) = AVarTypes[I] then
begin
Result := True;
Break;
end;
end;
function VarIsClear(const V: Variant): Boolean;
var
LSourceType: TVarType;
LSourceHandler: TCustomVariantType;
begin
Result := False;
LSourceType := TVarData(V).VType and varTypeMask;
if LSourceType < CFirstUserType then
with TVarData(V) do
Result := (VType = varEmpty) or
(((VType = varDispatch) or (VType = varUnknown)) and
(VDispatch = nil))
else if FindCustomVariantType(LSourceType, LSourceHandler) then
Result := LSourceHandler.IsClear(TVarData(V))
else
VarInvalidOp;
end;
function VarTypeIsCustom(const AVarType: TVarType): Boolean;
var
LSourceHandler: TCustomVariantType;
begin
Result := ((AVarType and varTypeMask) >= CFirstUserType) and
FindCustomVariantType((AVarType and varTypeMask), LSourceHandler);
end;
function VarIsCustom(const V: Variant): Boolean;
begin
Result := VarTypeIsCustom(TVarData(V).VType);
end;
function VarTypeIsOrdinal(const AVarType: TVarType): Boolean;
begin
Result := (AVarType and varTypeMask) in [varSmallInt, varInteger, varBoolean,
varShortInt, varByte, varWord,
varLongWord, varInt64];
end;
function VarIsOrdinal(const V: Variant): Boolean;
begin
Result := VarTypeIsOrdinal(TVarData(V).VType);
end;
function VarTypeIsFloat(const AVarType: TVarType): Boolean;
begin
Result := (AVarType and varTypeMask) in [varSingle, varDouble, varCurrency];
end;
function VarIsFloat(const V: Variant): Boolean;
begin
Result := VarTypeIsFloat(TVarData(V).VType);
end;
function VarTypeIsNumeric(const AVarType: TVarType): Boolean;
begin
Result := VarTypeIsOrdinal(AVarType) or VarTypeIsFloat(AVarType);
end;
function VarIsNumeric(const V: Variant): Boolean;
begin
Result := VarTypeIsNumeric(TVarData(V).VType);
end;
function VarTypeIsStr(const AVarType: TVarType): Boolean;
begin
Result := ((AVarType and varTypeMask) = varOleStr) or
((AVarType and varTypeMask) = varString);
end;
function VarIsStr(const V: Variant): Boolean;
begin
Result := VarTypeIsStr(TVarData(V).VType);
end;
function VarIsEmpty(const V: Variant): Boolean;
begin
Result := TVarData(V).VType = varEmpty;
end;
procedure VarCheckEmpty(const V: Variant);
begin
if VarIsEmpty(V) then
raise EVariantError.Create(SVarIsEmpty);
end;
function VarIsNull(const V: Variant): Boolean;
begin
Result := TVarData(V).VType = varNull;
end;
function VarToStr(const V: Variant): string;
begin
Result := VarToStrDef(V, '');
end;
function VarToStrDef(const V: Variant; const ADefault: string): string;
begin
if TVarData(V).VType <> varNull then
Result := V
else
Result := ADefault;
end;
function VarToWideStr(const V: Variant): WideString;
begin
Result := VarToWideStrDef(V, '');
end;
function VarToWideStrDef(const V: Variant; const ADefault: WideString): WideString;
begin
if TVarData(V).VType <> varNull then
Result := V
else
Result := ADefault;
end;
function VarFromDateTime(const DateTime: TDateTime): Variant;
begin
_VarClear(TVarData(Result));
TVarData(Result).VType := varDate;
TVarData(Result).VDate := DateTime;
end;
function VarToDateTime(const V: Variant): TDateTime;
var
Temp: TVarData;
begin
_VarInit(Temp);
_VarCast(Temp, TVarData(V), varDate);
Result := Temp.VDate;
end;
function VarInRange(const AValue, AMin, AMax: Variant): Boolean;
begin
Result := (AValue >= AMin) and (AValue <= AMax);
end;
function VarEnsureRange(const AValue, AMin, AMax: Variant): Variant;
begin
Result := AValue;
if Result < AMin then
Result := AMin;
if Result > AMax then
Result := AMax;
end;
function VarSameValue(const A, B: Variant): Boolean;
begin
if TVarData(A).VType = varEmpty then
Result := TVarData(B).VType = varEmpty
else if TVarData(A).VType = varNull then
Result := TVarData(B).VType = varNull
else if TVarData(B).VType in [varEmpty, varNull] then
Result := False
else
Result := A = B;
end;
function VarCompareValue(const A, B: Variant): TVariantRelationship;
const
CTruth: array [Boolean] of TVariantRelationship = (vrNotEqual, vrEqual);
begin
if TVarData(A).VType = varEmpty then
Result := CTruth[TVarData(B).VType = varEmpty]
else if TVarData(A).VType = varNull then
Result := CTruth[TVarData(B).VType = varNull]
else if TVarData(B).VType in [varEmpty, varNull] then
Result := vrNotEqual
else if A = B then
Result := vrEqual
else if A < B then
Result := vrLessThan
else
Result := vrGreaterThan;
end;
function VarIsEmptyParam(const V: Variant): Boolean;
begin
Result := (TVarData(V).VType = varError) and
(TVarData(V).VError = $80020004); {DISP_E_PARAMNOTFOUND}
end;
procedure SetClearVarToEmptyParam(var V: TVarData);
begin
V.VType := varError;
V.VError := $80020004; {DISP_E_PARAMNOTFOUND}
end;
function VarIsByRef(const V: Variant): Boolean;
begin
Result := (TVarData(V).VType and varByRef) <> 0;
end;
function VarSupports(const V: Variant; const IID: TGUID; out Intf): Boolean;
var
LInstance: IVarInstanceReference;
begin
Result := (Supports(V, IVarInstanceReference, LInstance) and
Supports(LInstance.GetInstance(TVarData(V)), IID, Intf)) or
Supports(V, IID, Intf);
end;
function VarSupports(const V: Variant; const IID: TGUID): Boolean;
var
LInstance: IVarInstanceReference;
LInterface: IInterface;
begin
Result := (Supports(V, IVarInstanceReference, LInstance) and
Supports(LInstance.GetInstance(TVarData(V)), IID, LInterface)) or
Supports(V, IID, LInterface);
end;
function _WriteVariant(var T: Text; const V: Variant; Width: Integer): Pointer;
var
S: string;
begin
if (TVarData(V).VType <> varEmpty) and (TVarData(V).VType <> varNull) then
S := V;
Write(T, S: Width);
Result := @T;
end;
function _Write0Variant(var T: Text; const V: Variant): Pointer;
begin
Result := _WriteVariant(T, V, 0);
end;
{ ----------------------------------------------------- }
{ Variant array support }
{ ----------------------------------------------------- }
function GetVarDataArrayInfo(const AVarData: TVarData; out AVarType: TVarType;
out AVarArray: PVarArray): Boolean;
var
LVarDataPtr: PVarData;
begin
// original type
LVarDataPtr := @AVarData;
AVarType := LVarDataPtr^.VType;
// if original type is not an array but is pointing to one
if (AVarType = (varByRef or varVariant)) and
((PVarData(LVarDataPtr^.VPointer)^.VType and varArray) <> 0) then
begin
LVarDataPtr := PVarData(LVarDataPtr^.VPointer);
AVarType := LVarDataPtr^.VType;
end;
// make sure we are pointing to an array then
Result := (AVarType and varArray) <> 0;
// figure out the array data pointer
if Result then
if (AVarType and varByRef) <> 0 then
AVarArray := PVarArray(LVarDataPtr^.VPointer^)
else
AVarArray := LVarDataPtr^.VArray
else
AVarArray := nil;
end;
const
tkDynArray = 17;
function VarArrayCreate(const Bounds: array of Integer;
AVarType: TVarType): Variant;
var
I, DimCount: Integer;
VarArrayRef: PVarArray;
VarBounds: array[0..63] of TVarArrayBound;
begin
if (not Odd(High(Bounds)) or (High(Bounds) > 127)) or
(not VarTypeIsValidArrayType(AVarType)) then
System.Error(System.reVarArrayCreate);
DimCount := (High(Bounds) + 1) div 2;
for I := 0 to DimCount - 1 do
with VarBounds[I] do
begin
LowBound := Bounds[I * 2];
ElementCount := Bounds[I * 2 + 1] - LowBound + 1;
end;
VarArrayRef := SafeArrayCreate(AVarType, DimCount, PVarArrayBoundArray(@VarBounds)^);
if VarArrayRef = nil then
System.Error(System.reVarArrayCreate);
_VarClear(TVarData(Result));
TVarData(Result).VType := AVarType or varArray;
TVarData(Result).VArray := VarArrayRef;
end;
function VarArrayOf(const Values: array of Variant): Variant;
var
I: Integer;
begin
Result := VarArrayCreate([0, High(Values)], varVariant);
for I := 0 to High(Values) do
Result[I] := Values[I];
end;
procedure _VarArrayRedim(var A: Variant; HighBound: Integer);
var
VarBound: TVarArrayBound;
LVarType: TVarType;
LVarArray: PVarArray;
begin
if not GetVarDataArrayInfo(TVarData(A), LVarType, LVarArray) then
System.Error(System.reVarNotArray);
with LVarArray^ do
VarBound.LowBound := Bounds[DimCount - 1].LowBound;
VarBound.ElementCount := HighBound - VarBound.LowBound + 1;
if SafeArrayRedim(LVarArray, VarBound) <> VAR_OK then
System.Error(System.reVarArrayCreate);
end;
function GetVarArray(const A: Variant): PVarArray;
var
LVarType: TVarType;
begin
if not GetVarDataArrayInfo(TVarData(A), LVarType, Result) then
System.Error(System.reVarNotArray);
end;
function VarArrayDimCount(const A: Variant): Integer;
var
LVarType: TVarType;
LVarArray: PVarArray;
begin
if GetVarDataArrayInfo(TVarData(A), LVarType, LVarArray) then
Result := LVarArray^.DimCount
else
Result := 0;
end;
function VarArrayLowBound(const A: Variant; Dim: Integer): Integer;
begin
if SafeArrayGetLBound(GetVarArray(A), Dim, Result) <> VAR_OK then
System.Error(System.reVarArrayBounds);
end;
function VarArrayHighBound(const A: Variant; Dim: Integer): Integer;
begin
if SafeArrayGetUBound(GetVarArray(A), Dim, Result) <> VAR_OK then
System.Error(System.reVarArrayBounds);
end;
function VarArrayLock(const A: Variant): Pointer;
begin
if SafeArrayAccessData(GetVarArray(A), Result) <> VAR_OK then
System.Error(System.reVarNotArray);
end;
procedure VarArrayUnlock(const A: Variant);
begin
if SafeArrayUnaccessData(GetVarArray(A)) <> VAR_OK then
System.Error(System.reVarNotArray);
end;
function VarArrayRef(const A: Variant): Variant;
begin
if (TVarData(A).VType and varArray) = 0 then
System.Error(System.reVarNotArray);
_VarClear(TVarData(Result));
TVarData(Result).VType := TVarData(A).VType or varByRef;
if (TVarData(A).VType and varByRef) <> 0 then
TVarData(Result).VPointer := TVarData(A).VPointer
else
TVarData(Result).VPointer := @TVarData(A).VArray;
end;
function VarIsArray(const A: Variant): Boolean;
begin
Result := VarIsArray(A, False);
end;
function VarIsArray(const A: Variant; AResolveByRef: Boolean): Boolean;
var
LVarType: TVarType;
LVarArray: PVarArray;
begin
if AResolveByRef then
Result := GetVarDataArrayInfo(TVarData(A), LVarType, LVarArray)
else
Result := (TVarData(A).VType and varArray) = varArray;
end;
function VarTypeIsValidArrayType(const AVarType: TVarType): Boolean;
var
LVarType: TVarType;
begin
LVarType := AVarType and varTypeMask;
Result := (LVarType in [CMinArrayVarType..CMaxArrayVarType]) and
CVarTypeToElementInfo[LVarType].ValidBase;
end;
function VarTypeIsValidElementType(const AVarType: TVarType): Boolean;
var
LVarType: TVarType;
begin
LVarType := AVarType and varTypeMask;
Result := ((LVarType in [CMinArrayVarType..CMaxArrayVarType]) and
CVarTypeToElementInfo[LVarType].ValidElement) or
VarTypeIsCustom(LVarType);
end;
function _VarArrayGet(var A: Variant; IndexCount: Integer;
const Indices: TVarArrayCoorArray): Variant; cdecl;
var
LVarType: TVarType;
LVarArrayPtr: PVarArray;
LArrayVarType: Integer;
P: Pointer;
LResult: TVarData;
begin
if not GetVarDataArrayInfo(TVarData(A), LVarType, LVarArrayPtr) then
System.Error(System.reVarNotArray);
if LVarArrayPtr^.DimCount <> IndexCount then
System.Error(System.reVarArrayBounds);
// use a temp for result just in case the result points back to source, icky
_VarInit(LResult);
try
LArrayVarType := LVarType and varTypeMask;
if LArrayVarType = varVariant then
begin
if SafeArrayPtrOfIndex(LVarArrayPtr, @Indices, P) <> VAR_OK then
System.Error(System.reVarArrayBounds);
_VarCopy(LResult, PVarData(P)^);
end
else
begin
if SafeArrayGetElement(LVarArrayPtr, @Indices, @TVarData(LResult).VPointer) <> VAR_OK then
System.Error(System.reVarArrayBounds);
TVarData(LResult).VType := LArrayVarType;
end;
// copy the temp result over to result
_VarCopy(TVarData(Result), LResult);
finally
_VarClear(LResult);
end;
end;
function VarArrayGet(const A: Variant; const Indices: array of Integer): Variant;
asm
{ ->EAX Pointer to A }
{ EDX Pointer to Indices }
{ ECX High bound of Indices }
{ [EBP+8] Pointer to result }
PUSH EBX
MOV EBX,ECX
INC EBX
JLE @@endLoop
@@loop:
PUSH [EDX+ECX*4].Integer
DEC ECX
JNS @@loop
@@endLoop:
PUSH EBX
PUSH EAX
MOV EAX,[EBP+8]
PUSH EAX
CALL _VarArrayGet
LEA ESP,[ESP+EBX*4+3*4]
POP EBX
end;
procedure _VarArrayPut(var A: Variant; const Value: Variant;
IndexCount: Integer; const Indices: TVarArrayCoorArray); cdecl;
type
TAnyPutArrayProc = procedure (var A: Variant; const Value: Variant; Index: Integer);
var
LVarType: TVarType;
LVarArrayPtr: PVarArray;
LValueType: TVarType;
LValueArrayPtr: PVarArray;
LArrayVarType: Integer;
P: Pointer;
Temp: TVarData;
begin
if not GetVarDataArrayInfo(TVarData(A), LVarType, LVarArrayPtr) then
System.Error(System.reVarNotArray);
if not GetVarDataArrayInfo(TVarData(Value), LValueType, LValueArrayPtr) and
not VarTypeIsValidElementType(LValueType) and
(LValueType <> varString) then
System.Error(System.reVarTypeCast);
if LVarArrayPtr^.DimCount <> IndexCount then
System.Error(System.reVarArrayBounds);
LArrayVarType := LVarType and varTypeMask;
if (LArrayVarType = varVariant) and
((LValueType <> varString) or
VarTypeIsCustom(LValueType)) then
begin
if SafeArrayPtrOfIndex(LVarArrayPtr, @Indices, P) <> VAR_OK then
System.Error(System.reVarArrayBounds);
PVariant(P)^ := Value;
end else
begin
_VarInit(Temp);
try
if LArrayVarType = varVariant then
begin
VarStringToOleStr(Variant(Temp), Value);
P := @Temp;
end else
begin
_VarCast(Temp, TVarData(Value), LArrayVarType);
case LArrayVarType of
varOleStr, varDispatch, varUnknown:
P := Temp.VPointer;
else
P := @Temp.VPointer;
end;
end;
if SafeArrayPutElement(LVarArrayPtr, @Indices, P) <> VAR_OK then
System.Error(System.reVarArrayBounds);
finally
_VarClear(Temp);
end;
end;
end;
procedure VarArrayPut(var A: Variant; const Value: Variant; const Indices: array of Integer);
asm
{ ->EAX Pointer to A }
{ EDX Pointer to Value }
{ ECX Pointer to Indices }
{ [EBP+8] High bound of Indices }
PUSH EBX
MOV EBX,[EBP+8]
TEST EBX,EBX
JS @@endLoop
@@loop:
PUSH [ECX+EBX*4].Integer
DEC EBX
JNS @@loop
@@endLoop:
MOV EBX,[EBP+8]
INC EBX
PUSH EBX
PUSH EDX
PUSH EAX
CALL _VarArrayPut
LEA ESP,[ESP+EBX*4+3*4]
POP EBX
end;
function DynArrayIndex(const P: Pointer; const Indices: array of Integer; const TypInfo: Pointer): Pointer;
asm
{ ->EAX P }
{ EDX Pointer to Indices }
{ ECX High bound of Indices }
{ [EBP+8] TypInfo }
PUSH EBX
PUSH ESI
PUSH EDI
PUSH EBP
MOV ESI,EDX
MOV EDI,[EBP+8]
MOV EBP,EAX
XOR EBX,EBX { for i := 0 to High(Indices) do }
TEST ECX,ECX
JGE @@start
@@loop:
MOV EBP,[EBP]
@@start:
XOR EAX,EAX
MOV AL,[EDI].TDynArrayTypeInfo.name
ADD EDI,EAX
MOV EAX,[ESI+EBX*4] { P := P + Indices[i]*TypInfo.elSize }
MUL [EDI].TDynArrayTypeInfo.elSize
MOV EDI,[EDI].TDynArrayTypeInfo.elType
TEST EDI,EDI
JE @@skip
MOV EDI,[EDI]
@@skip:
ADD EBP,EAX
INC EBX
CMP EBX,ECX
JLE @@loop
@@loopEnd:
MOV EAX,EBP
POP EBP
POP EDI
POP ESI
POP EBX
end;
{ Returns the DynArrayTypeInfo of the Element Type of the specified DynArrayTypeInfo }
function DynArrayElTypeInfo(typeInfo: PDynArrayTypeInfo): PDynArrayTypeInfo;
begin
Result := nil;
if typeInfo <> nil then
begin
Inc(PChar(typeInfo), Length(typeInfo.name));
if typeInfo.elType <> nil then
Result := typeInfo.elType^;
end;
end;
{ Returns # of dimemsions of the DynArray described by the specified DynArrayTypeInfo}
function DynArrayDim(typeInfo: PDynArrayTypeInfo): Integer;
begin
Result := 0;
while (typeInfo <> nil) and (typeInfo.kind = tkDynArray) do
begin
Inc(Result);
typeInfo := DynArrayElTypeInfo(typeInfo);
end;
end;
{ Returns size of the Dynamic Array}
function DynArraySize(a: Pointer): Integer;
asm
TEST EAX, EAX
JZ @@exit
MOV EAX, [EAX-4]
@@exit:
end;
// Returns whether array is rectangular
function IsDynArrayRectangular(const DynArray: Pointer; typeInfo: PDynArrayTypeInfo): Boolean;
var
Dim, I, J, Size, SubSize: Integer;
P: Pointer;
begin
// Assume we have a rectangular array
Result := True;
P := DynArray;
Dim := DynArrayDim(typeInfo);
{NOTE: Start at 1. Don't need to test the first dimension - it's rectangular by definition}
for I := 1 to dim-1 do
begin
if P <> nil then
begin
{ Get size of this dimension }
Size := DynArraySize(P);
{ Get Size of first sub. dimension }
SubSize := DynArraySize(PPointerArray(P)[0]);
{ Walk through every dimension making sure they all have the same size}
for J := 1 to Size-1 do
if DynArraySize(PPointerArray(P)[J]) <> SubSize then
begin
Result := False;
Exit;
end;
{ Point to next dimension}
P := PPointerArray(P)[0];
end;
end;
end;
// Returns Bounds of Dynamic array as an array of integer containing the 'high' of each dimension
function DynArrayBounds(const DynArray: Pointer; typeInfo: PDynArrayTypeInfo): TBoundArray;
var
Dim, I: Integer;
P: Pointer;
begin
P := DynArray;
Dim := DynArrayDim(typeInfo);
SetLength(Result, Dim);
for I := 0 to dim-1 do
if P <> nil then
begin
Result[I] := DynArraySize(P)-1;
P := PPointerArray(P)[0]; // Assume rectangular arrays
end;
end;
{ Decrements to next lower index - Returns True if successful }
{ Indices: Indices to be decremented }
{ Bounds : High bounds of each dimension }
function DecIndices(var Indices: TBoundArray; const Bounds: TBoundArray): Boolean;
var
I, J: Integer;
begin
{ Find out if we're done: all at zeroes }
Result := False;
for I := Low(Indices) to High(Indices) do
if Indices[I] <> 0 then
begin
Result := True;
break;
end;
if not Result then
Exit;
{ Two arrays must be of same length }
Assert(Length(Indices) = Length(Bounds));
{ Find index of item to tweak }
for I := High(Indices) downto Low(Bounds) do
begin
// If not reach zero, dec and bail out
if Indices[I] <> 0 then
begin
Dec(Indices[I]);
Exit;
end
else
begin
J := I;
while Indices[J] = 0 do
begin
// Restore high bound when we've reached zero on a particular dimension
Indices[J] := Bounds[J];
// Move to higher dimension
Dec(J);
Assert(J >= 0);
end;
Dec(Indices[J]);
Exit;
end;
end;
end;
// Returns Bounds of a DynamicArray in a format usable for creating a Variant.
// i.e. The format of the bounds returns contains pairs of lo and hi bounds where
// lo is always 0, and hi is the size dimension of the array-1.
function DynArrayVariantBounds(const DynArray: Pointer; typeInfo: PDynArrayTypeInfo): TBoundArray;
var
Dim, I: Integer;
P: Pointer;
begin
P := DynArray;
Dim := DynArrayDim(typeInfo);
SetLength(Result, Dim*2);
I := 0;
while I < dim*2 do
begin
Result[I] := 0; // Always use 0 as low-bound in low/high pair
Inc(I);
if P <> nil then
begin
Result[I] := DynArraySize(P)-1; // Adjust for 0-base low-bound
P := PPointerArray(p)[0]; // Assume rectangular arrays
end;
Inc(I);
end;
end;
// The dynamicArrayTypeInformation contains the VariantType of the element type
// when the kind == tkDynArray. This function returns that VariantType.
function DynArrayVarType(typeInfo: PDynArrayTypeInfo): Integer;
begin
Result := varNull;
if (typeInfo <> nil) and (typeInfo.Kind = tkDynArray) then
begin
Inc(PChar(typeInfo), Length(typeInfo.name));
Result := typeInfo.varType;
end;
{ NOTE: DECL.H and SYSTEM.PAS have different values for varString }
if Result = $48 then
Result := varString;
end;
// Copy Contents of Dynamic Array to Variant
// NOTE: The Dynamic array must be rectangular
// The Dynamic array must contain items whose type is Automation compatible
// In case of failure, the function returns with a Variant of type VT_EMPTY.
procedure DynArrayToVariant(var V: Variant; const DynArray: Pointer; TypeInfo: Pointer);
var
VarBounds, Bounds, Indices: TBoundArray;
DAVarType, VVarType, DynDim: Integer;
PDAData: Pointer;
Value: Variant;
begin
VarBounds := nil;
Bounds := nil;
{ This resets the Variant to VT_EMPTY - flag which is used to determine whether the }
{ the cast to Variant succeeded or not }
VarClear(V);
{ Get variantType code from DynArrayTypeInfo }
DAVarType := DynArrayVarType(PDynArrayTypeInfo(TypeInfo));
{ Validate the Variant Type }
if ((DAVarType > varNull) and (DAVarType <= varByte)) or (DAVarType = varString) then
begin
{NOTE: Map varString to varOleStr for SafeArrayCreate call }
if DAVarType = varString then
VVarType := varOleStr
else
VVarType := DAVarType;
{ Get dimension of Dynamic Array }
DynDim := DynarrayDim(PDynArrayTypeInfo(TypeInfo));
{ If more than one dimension, make sure we're dealing with a rectangular array }
if DynDim > 1 then
if not IsDynArrayRectangular(DynArray, PDynArrayTypeInfo(TypeInfo)) then
Exit;
{ Get Variant-style Bounds (lo/hi pair) of Dynamic Array }
VarBounds := DynArrayVariantBounds(DynArray, TypeInfo);
{ Get DynArray Bounds }
Bounds := DynArrayBounds(DynArray, TypeInfo);
Indices:= Copy(Bounds);
{ Create Variant of SAFEARRAY }
V := VarArrayCreate(VarBounds, VVarType);
Assert(VarArrayDimCount(V) = DynDim);
repeat
PDAData := DynArrayIndex(DynArray, Indices, TypeInfo);
if PDAData <> nil then
begin
case DAVarType of
varSmallInt: Value := PSmallInt(PDAData)^;
varInteger: Value := PInteger(PDAData)^;
varSingle: value := PSingle(PDAData)^;
varDouble: value := PDouble(PDAData)^;
varCurrency: Value := PCurrency(PDAData)^;
varDate: Value := PDouble(PDAData)^;
varOleStr: Value := PWideString(PDAData)^;
varDispatch: Value := PDispatch(PDAData)^;
varError: Value := Integer(PError(PDAData)^);
varBoolean: Value := PWordBool(PDAData)^;
varVariant: Value := PVariant(PDAData)^;
varUnknown: Value := PUnknown(PDAData)^;
varShortInt: Value := PShortInt(PDAData)^;
varByte: Value := PByte(PDAData)^; //<<<<============================
varWord: Value := PWord(PDAData)^;
varLongWord: Value := PLongWord(PDAData)^;
varString: Value := PString(PDAData)^;
else
VarClear(Value);
end; { case }
VarArrayPut(V, Value, Indices);
end;
until not DecIndices(Indices, Bounds);
end;
end;
// Copies data from the Variant to the DynamicArray
procedure DynArrayFromVariant(var DynArray: Pointer; const V: Variant; TypeInfo: Pointer);
var
DADimCount, VDimCount: Integer;
DAVarType, I: Integer;
lengthVec: System.PLongInt;
Bounds, Indices: TBoundArray;
Value: Variant;
PDAData: Pointer;
begin
{ Get Variant information }
VDimCount:= VarArrayDimCount(V);
{ Allocate vector for lengths }
GetMem(lengthVec, VDimCount * sizeof(Integer));
{ Initialize lengths - NOTE: VarArrayxxxxBound are 1-based.}
for I := 0 to VDimCount-1 do
PIntegerArray(lengthVec)[I]:= (VarArrayHighBound(V, I+1) - VarArrayLowBound(V, I+1)) + 1;
{ Set Length of DynArray }
DynArraySetLength(DynArray, PDynArrayTypeInfo(TypeInfo), VDimCount, lengthVec);
{ Get DynArray information }
DADimCount:= DynArrayDim(PDynArrayTypeInfo(TypeInfo));
DAVarType := DynArrayVarType(PDynArrayTypeInfo(TypeInfo));
Assert(VDimCount = DADimCount);
{ Get DynArray Bounds }
Bounds := DynArrayBounds(DynArray, TypeInfo);
Indices:= Copy(Bounds);
{ Copy data over}
repeat
Value := VarArrayGet(V, Indices);
PDAData := DynArrayIndex(DynArray, Indices, TypeInfo);
case DAVarType of
varSmallInt: PSmallInt(PDAData)^ := Value;
varInteger: PInteger(PDAData)^ := Value;
varSingle: PSingle(PDAData)^ := Value;
varDouble: PDouble(PDAData)^ := Value;
varCurrency: PCurrency(PDAData)^ := Value;
varDate: PDouble(PDAData)^ := Value;
varOleStr: PWideString(PDAData)^ := Value;
varDispatch: PDispatch(PDAData)^ := Value;
varError: PError(PDAData)^ := Value;
varBoolean: PWordBool(PDAData)^ := Value;
varVariant: PVariant(PDAData)^ := Value;
varUnknown: PUnknown(PDAData)^ := Value;
varShortInt: PShortInt(PDAData)^ := Value;
varByte: PByte(PDAData)^ := Value;
varWord: PWord(PDAData)^ := Value;
varLongWord: PLongWord(PDAData)^ := Value;
varString: PString(PDAData)^ := Value;
end; { case }
until not DecIndices(Indices, Bounds);
{ Free vector of lengths }
FreeMem(lengthVec);
end;
{ TCustomVariantType support }
var
LVarTypes: array of TCustomVariantType;
LNextVarType: Integer = CFirstUserType;
LVarTypeSync: TMultiReadExclusiveWriteSynchronizer;
procedure ClearVariantTypeList;
var
I: Integer;
begin
LVarTypeSync.BeginWrite;
try
for I := Length(LVarTypes) - 1 downto 0 do
if LVarTypes[I] <> CInvalidCustomVariantType then
LVarTypes[I].Free;
finally
LVarTypeSync.EndWrite;
end;
end;
{ TCustomVariantType }
procedure TCustomVariantType.BinaryOp(var Left: TVarData;
const Right: TVarData; const Operator: TVarOp);
begin
RaiseInvalidOp;
end;
procedure TCustomVariantType.Cast(var Dest: TVarData; const Source: TVarData);
var
LSourceHandler: TCustomVariantType;
begin
if FindCustomVariantType(Source.VType, LSourceHandler) then
LSourceHandler.CastTo(Dest, Source, VarType)
else
RaiseCastError;
end;
procedure TCustomVariantType.CastTo(var Dest: TVarData; const Source: TVarData;
const AVarType: TVarType);
var
LSourceHandler: TCustomVariantType;
begin
if (AVarType <> VarType) and
FindCustomVariantType(Source.VType, LSourceHandler) then
LSourceHandler.CastTo(Dest, Source, AVarType)
else
RaiseCastError;
end;
procedure TCustomVariantType.Compare(const Left, Right: TVarData;
var Relationship: TVarCompareResult);
begin
RaiseInvalidOp;
end;
function TCustomVariantType.CompareOp(const Left, Right: TVarData;
const Operator: TVarOp): Boolean;
const
CRelationshipToBoolean: array [opCmpEQ..opCmpGE, TVarCompareResult] of Boolean =
// crLessThan, crEqual, crGreaterThan
((False, True, False), // opCmpEQ = 14;
(True, False, True), // opCmpNE = 15;
(True, False, False), // opCmpLT = 16;
(True, True, False), // opCmpLE = 17;
(False, False, True), // opCmpGT = 18;
(False, True, True)); // opCmpGE = 19;
var
LRelationship: TVarCompareResult;
begin
Compare(Left, Right, LRelationship);
Result := CRelationshipToBoolean[Operator, LRelationship];
end;
procedure TCustomVariantType.CastToOle(var Dest: TVarData;
const Source: TVarData);
var
LBestOleType: TVarType;
begin
if OlePromotion(Source, LBestOleType) then
CastTo(Dest, Source, LBestOleType)
else
RaiseCastError;
end;
constructor TCustomVariantType.Create;
begin
Create(LNextVarType);
Inc(LNextVarType);
end;
constructor TCustomVariantType.Create(RequestedVarType: TVarType);
var
LSlot, LWas, LNewLength, I: Integer;
begin
inherited Create;
LVarTypeSync.BeginWrite;
try
LSlot := RequestedVarType - CMinVarType;
LWas := Length(LVarTypes);
if LSlot >= LWas then
begin
LNewLength := ((LSlot div CIncVarType) + 1) * CIncVarType;
if LNewLength > CMaxVarType then
raise EVariantError.Create(SVarTypeTooManyCustom);
SetLength(LVarTypes, LNewLength);
for I := LWas to Length(LVarTypes) - 1 do
LVarTypes[I] := nil;
end;
if LVarTypes[LSlot] <> nil then
if LVarTypes[LSlot] = CInvalidCustomVariantType then
raise EVariantError.CreateFmt(SVarTypeNotUsable, [RequestedVarType])
else
raise EVariantError.CreateFmt(SVarTypeAlreadyUsed, [RequestedVarType, LVarTypes[LSlot].ClassName]);
LVarTypes[LSlot] := Self;
FVarType := RequestedVarType;
finally
LVarTypeSync.EndWrite;
end;
end;
destructor TCustomVariantType.Destroy;
begin
LVarTypeSync.BeginWrite;
try
LVarTypes[VarType - CMinVarType] := CInvalidCustomVariantType;
finally
LVarTypeSync.EndWrite;
end;
inherited;
end;
function TCustomVariantType.IsClear(const V: TVarData): Boolean;
begin
Result := False;
end;
function TCustomVariantType.LeftPromotion(const V: TVarData;
const Operator: TVarOp; out RequiredVarType: TVarType): Boolean;
begin
RequiredVarType := VarType;
Result := True;
end;
function TCustomVariantType.OlePromotion(const V: TVarData;
out RequiredVarType: TVarType): Boolean;
begin
RequiredVarType := varOleStr;
Result := True;
end;
procedure TCustomVariantType.RaiseCastError;
begin
VarCastError;
end;
procedure TCustomVariantType.RaiseInvalidOp;
begin
VarInvalidOp;
end;
procedure TCustomVariantType.RaiseDispError;
begin
_DispInvokeError;
end;
function TCustomVariantType.RightPromotion(const V: TVarData;
const Operator: TVarOp; out RequiredVarType: TVarType): Boolean;
begin
RequiredVarType := VarType;
Result := True;
end;
procedure TCustomVariantType.SimplisticClear(var V: TVarData);
begin
VarDataInit(V);
end;
procedure TCustomVariantType.SimplisticCopy(var Dest: TVarData;
const Source: TVarData; const Indirect: Boolean);
begin
if Indirect and VarDataIsByRef(Source) then
VarDataCopyNoInd(Dest, Source)
else
Dest := Source; // block copy
end;
procedure TCustomVariantType.UnaryOp(var Right: TVarData; const Operator: TVarOp);
begin
RaiseInvalidOp;
end;
procedure TCustomVariantType.VarDataInit(var Dest: TVarData);
begin
_VarInit(Dest);
end;
procedure TCustomVariantType.VarDataClear(var Dest: TVarData);
begin
_VarClear(Dest);
end;
procedure TCustomVariantType.VarDataCopy(var Dest: TVarData; const Source: TVarData);
begin
VarCopyCommon(Dest, Source, False);
end;
procedure TCustomVariantType.VarDataCopyNoInd(var Dest: TVarData; const Source: TVarData);
begin
VarCopyCommon(Dest, Source, True);
end;
procedure TCustomVariantType.VarDataCast(var Dest: TVarData;
const Source: TVarData);
begin
VarDataCastTo(Dest, Source, VarType);
end;
procedure TCustomVariantType.VarDataCastTo(var Dest: TVarData;
const Source: TVarData; const AVarType: TVarType);
begin
_VarCast(Dest, Source, AVarType);
end;
procedure TCustomVariantType.VarDataCastTo(var Dest: TVarData;
const AVarType: TVarType);
begin
VarDataCastTo(Dest, Dest, AVarType);
end;
procedure TCustomVariantType.VarDataCastToOleStr(var Dest: TVarData);
begin
if Dest.VType = varString then
_VarStringToOleStr(Dest, Dest)
else
VarDataCastTo(Dest, Dest, varOleStr);
end;
function TCustomVariantType.VarDataIsArray(const V: TVarData): Boolean;
begin
Result := (V.VType and varArray) <> 0;
end;
function TCustomVariantType.VarDataIsByRef(const V: TVarData): Boolean;
begin
Result := (V.VType and varByRef) <> 0;
end;
procedure TCustomVariantType.DispInvoke(var Dest: TVarData;
const Source: TVarData; CallDesc: PCallDesc; Params: Pointer);
begin
RaiseDispError;
end;
function TCustomVariantType.VarDataIsEmptyParam(const V: TVarData): Boolean;
begin
Result := VarIsEmptyParam(Variant(V));
end;
procedure TCustomVariantType.VarDataFromStr(var V: TVarData; const Value: string);
begin
_VarFromPStr(V, Value);
end;
procedure TCustomVariantType.VarDataFromOleStr(var V: TVarData; const Value: WideString);
begin
_VarFromWStr(V, Value);
end;
function TCustomVariantType._AddRef: Integer;
begin
Result := -1;
end;
function TCustomVariantType._Release: Integer;
begin
Result := -1;
end;
function TCustomVariantType.QueryInterface(const IID: TGUID; out Obj): HResult;
const
E_NOINTERFACE = HResult($80004002);
begin
if GetInterface(IID, Obj) then
Result := S_OK
else
Result := E_NOINTERFACE;
end;
function TCustomVariantType.VarDataIsNumeric(const V: TVarData): Boolean;
begin
Result := VarTypeIsNumeric(V.VType);
end;
function TCustomVariantType.VarDataIsOrdinal(const V: TVarData): Boolean;
begin
Result := VarTypeIsOrdinal(V.VType);
end;
function TCustomVariantType.VarDataIsStr(const V: TVarData): Boolean;
begin
Result := VarTypeIsStr(V.VType);
end;
function TCustomVariantType.VarDataIsFloat(const V: TVarData): Boolean;
begin
Result := VarTypeIsFloat(V.VType);
end;
function TCustomVariantType.VarDataToStr(const V: TVarData): string;
begin
Result := VarToStr(Variant(V));
end;
{ TInvokeableVariantType }
procedure TInvokeableVariantType.DispInvoke(var Dest: TVarData; const Source: TVarData;
CallDesc: PCallDesc; Params: Pointer);
type
PParamRec = ^TParamRec;
TParamRec = array[0..3] of LongInt;
TStringDesc = record
BStr: WideString;
PStr: PString;
end;
const
CDoMethod = $01;
CPropertyGet = $02;
CPropertySet = $04;
var
LArguments: TVarDataArray;
LStrings: array of TStringDesc;
LStrCount: Integer;
LParamPtr: Pointer;
procedure ParseParam(I: Integer);
const
CArgTypeMask = $7F;
CArgByRef = $80;
var
LArgType: Integer;
LArgByRef: Boolean;
begin
LArgType := CallDesc^.ArgTypes[I] and CArgTypeMask;
LArgByRef := (CallDesc^.ArgTypes[I] and CArgByRef) <> 0;
// error is an easy expansion
if LArgType = varError then
SetClearVarToEmptyParam(LArguments[I])
// literal string
else if LArgType = varStrArg then
begin
with LStrings[LStrCount] do
if LArgByRef then
begin
//BStr := StringToOleStr(PString(ParamPtr^)^);
BStr := System.Copy(PString(LParamPtr^)^, 1, MaxInt);
PStr := PString(LParamPtr^);
LArguments[I].VType := varOleStr or varByRef;
LArguments[I].VOleStr := @BStr;
end
else
begin
//BStr := StringToOleStr(PString(ParamPtr)^);
BStr := System.Copy(PString(LParamPtr)^, 1, MaxInt);
PStr := nil;
LArguments[I].VType := varOleStr;
LArguments[I].VOleStr := PWideChar(BStr);
end;
Inc(LStrCount);
end
// value is by ref
else if LArgByRef then
begin
if (LArgType = varVariant) and
(PVarData(LParamPtr^)^.VType = varString) then
//VarCast(PVariant(ParamPtr^)^, PVariant(ParamPtr^)^, varOleStr);
VarDataCastTo(PVarData(LParamPtr^)^, PVarData(LParamPtr^)^, varOleStr);
LArguments[I].VType := LArgType or varByRef;
LArguments[I].VPointer := Pointer(LParamPtr^);
end
// value is a variant
else if LArgType = varVariant then
if PVarData(LParamPtr)^.VType = varString then
begin
with LStrings[LStrCount] do
begin
//BStr := StringToOleStr(string(PVarData(ParamPtr^)^.VString));
BStr := System.Copy(string(PVarData(LParamPtr^)^.VString), 1, MaxInt);
PStr := nil;
LArguments[I].VType := varOleStr;
LArguments[I].VOleStr := PWideChar(BStr);
end;
Inc(LStrCount);
end
else
begin
LArguments[I] := PVarData(LParamPtr)^;
Inc(Integer(LParamPtr), SizeOf(TVarData) - SizeOf(Pointer));
end
else
begin
LArguments[I].VType := LArgType;
case CVarTypeToElementInfo[LArgType].Size of
1, 2, 4:
begin
LArguments[I].VLongs[1] := PParamRec(LParamPtr)^[0];
end;
8:
begin
LArguments[I].VLongs[1] := PParamRec(LParamPtr)^[0];
LArguments[I].VLongs[2] := PParamRec(LParamPtr)^[1];
Inc(Integer(LParamPtr), 8 - SizeOf(Pointer));
end;
else
RaiseDispError;
end;
end;
Inc(Integer(LParamPtr), SizeOf(Pointer));
end;
var
I, LArgCount: Integer;
LIdent: string;
LTemp: TVarData;
begin
// Grab the identifier
LArgCount := CallDesc^.ArgCount;
LIdent := Uppercase(String(PChar(@CallDesc^.ArgTypes[LArgCount])));
// Parse the arguments
LParamPtr := Params;
SetLength(LArguments, LArgCount);
LStrCount := 0;
SetLength(LStrings, LArgCount);
for I := 0 to LArgCount - 1 do
ParseParam(I);
// What type of invoke is this?
case CallDesc^.CallType of
CDoMethod:
// procedure with N arguments
if @Dest = nil then
begin
if not DoProcedure(Source, LIdent, LArguments) then
begin
// ok maybe its a function but first we must make room for a result
VarDataInit(LTemp);
try
// notate that the destination shouldn't be bothered with
// functions can still return stuff, we just do this so they
// can tell that they don't need to if they don't want to
SetClearVarToEmptyParam(LTemp);
// ok lets try for that function
if not DoFunction(LTemp, Source, LIdent, LArguments) then
RaiseDispError;
finally
VarDataClear(LTemp);
end;
end
end
// property get or function with 0 argument
else if LArgCount = 0 then
begin
if not GetProperty(Dest, Source, LIdent) and
not DoFunction(Dest, Source, LIdent, LArguments) then
RaiseDispError;
end
// function with N arguments
else if not DoFunction(Dest, Source, LIdent, LArguments) then
RaiseDispError;
CPropertyGet:
if not ((@Dest <> nil) and // there must be a dest
(LArgCount = 0) and // only no args
GetProperty(Dest, Source, LIdent)) then // get op be valid
RaiseDispError;
CPropertySet:
if not ((@Dest = nil) and // there can't be a dest
(LArgCount = 1) and // can only be one arg
SetProperty(Source, LIdent, LArguments[0])) then // set op be valid
RaiseDispError;
else
RaiseDispError;
end;
// copy back the string info
I := LStrCount;
while I <> 0 do
begin
Dec(I);
with LStrings[I] do
if Assigned(PStr) then
PStr^ := System.Copy(BStr, 1, MaxInt);
end;
end;
function TInvokeableVariantType.GetProperty(var Dest: TVarData; const V: TVarData;
const Name: string): Boolean;
begin
Result := False;
end;
function TInvokeableVariantType.SetProperty(const V: TVarData; const Name: string;
const Value: TVarData): Boolean;
begin
Result := False;
end;
function TInvokeableVariantType.DoFunction(var Dest: TVarData; const V: TVarData;
const Name: string; const Arguments: TVarDataArray): Boolean;
begin
Result := False;
end;
function TInvokeableVariantType.DoProcedure(const V: TVarData; const Name: string;
const Arguments: TVarDataArray): Boolean;
begin
Result := False;
end;
{ TCustomVariantType support }
function FindCustomVariantType(const AVarType: TVarType; out CustomVariantType: TCustomVariantType): Boolean;
begin
LVarTypeSync.BeginRead;
try
Result := (AVarType >= CMinVarType) and (AVarType - CMinVarType < Length(LVarTypes));
if Result then
begin
CustomVariantType := LVarTypes[AVarType - CMinVarType];
Result := (CustomVariantType <> nil) and
(CustomVariantType <> CInvalidCustomVariantType);
end;
finally
LVarTypeSync.EndRead;
end;
end;
function FindCustomVariantType(const TypeName: string; out CustomVariantType: TCustomVariantType): Boolean;
var
I: Integer;
LPossible: TCustomVariantType;
begin
Result := False;
LVarTypeSync.BeginRead;
try
for I := Low(LVarTypes) to High(LVarTypes) do
begin
LPossible := LVarTypes[I];
if (LPossible <> nil) and (LPossible <> CInvalidCustomVariantType) and
SameText(LPossible.ClassName, TypeName) then
begin
CustomVariantType := LPossible;
Result := True;
Break;
end;
end;
finally
LVarTypeSync.EndRead;
end;
end;
function Unassigned: Variant;
begin
_VarClear(TVarData(Result));
end;
function Null: Variant;
begin
_VarClear(TVarData(Result));
TVarData(Result).VType := varNull;
end;
initialization
SetClearVarToEmptyParam(TVarData(EmptyParam));
VarDispProc := @_DispInvokeError;
ClearAnyProc := @VarInvalidOp;
ChangeAnyProc := @VarCastError;
RefAnyProc := @VarInvalidOp;
GVariantManager.VarClear := @_VarClear;
GVariantManager.VarCopy := @_VarCopy;
GVariantManager.VarCopyNoInd := @_VarCopyNoInd;
GVariantManager.VarCast := @_VarCast;
GVariantManager.VarCastOle := @_VarCastOle;
GVariantManager.VarToInt := @_VarToInt;
GVariantManager.VarToInt64 := @_VarToInt64;
GVariantManager.VarToBool := @_VarToBool;
GVariantManager.VarToReal := @_VarToReal;
GVariantManager.VarToCurr := @_VarToCurr;
GVariantManager.VarToPStr := @_VarToPStr;
GVariantManager.VarToLStr := @_VarToLStr;
GVariantManager.VarToWStr := @_VarToWStr;
GVariantManager.VarToIntf := @_VarToIntf;
GVariantManager.VarToDisp := @_VarToDisp;
GVariantManager.VarToDynArray := @_VarToDynArray;
GVariantManager.VarFromInt := @_VarFromInt;
GVariantManager.VarFromInt64 := @_VarFromInt64;
GVariantManager.VarFromBool := @_VarFromBool;
GVariantManager.VarFromReal := @_VarFromReal;
GVariantManager.VarFromTDateTime := @_VarFromTDateTime;
GVariantManager.VarFromCurr := @_VarFromCurr;
GVariantManager.VarFromPStr := @_VarFromPStr;
GVariantManager.VarFromLStr := @_VarFromLStr;
GVariantManager.VarFromWStr := @_VarFromWStr;
GVariantManager.VarFromIntf := @_VarFromIntf;
GVariantManager.VarFromDisp := @_VarFromDisp;
GVariantManager.VarFromDynArray := @_VarFromDynArray;
GVariantManager.OleVarFromPStr := @_OleVarFromPStr;
GVariantManager.OleVarFromLStr := @_OleVarFromLStr;
GVariantManager.OleVarFromVar := @_OleVarFromVar;
GVariantManager.OleVarFromInt := @_OleVarFromInt;
GVariantManager.VarOp := @_VarOp;
GVariantManager.VarCmp := @_VarCmp;
GVariantManager.VarNeg := @_VarNeg;
GVariantManager.VarNot := @_VarNot;
GVariantManager.DispInvoke := @_DispInvoke;
GVariantManager.VarAddRef := @_VarAddRef;
GVariantManager.VarArrayRedim := @_VarArrayRedim;
GVariantManager.VarArrayGet := @_VarArrayGet;
GVariantManager.VarArrayPut := @_VarArrayPut;
GVariantManager.WriteVariant := @_WriteVariant;
GVariantManager.Write0Variant := @_Write0Variant;
GetVariantManager(GOldVariantManager);
SetVariantManager(GVariantManager);
LVarTypeSync := TMultiReadExclusiveWriteSynchronizer.Create;
finalization
ClearVariantTypeList;
FreeAndNil(LVarTypeSync);
SetVariantManager(GOldVariantManager);
end.
|
unit MD5.FileUtils;
// String default is UnicodeString
INTERFACE
{$DEFINE FINDFILES_DEBUG}
uses
MD5.Utils,
MD5.Message,
System.SysUtils,
System.Classes,
System.StrUtils,
Windows;
const
ALL_FILES_MASK = '*'; // NOT *.* !!!
EXTENDED_PATH_PREFIX = '\\?\';
SKIP_FOLDER_NAME_1 = '.';
SKIP_FOLDER_NAME_2 = '..';
// for MatchMask
MASK_CHAR_ZERO_OF_MANY = '*';
MASK_CHAR_ANY = '?';
MASK_END_OF_STRING = #0;
var
UpperCaseTable: array[Char] of Char;
type
TExtendedPathBuffer = array[0..32768] of Char;
// Размер файла, обернутый в объект
// (для того, чтобы хранить размер в TStringList)
TFileSizeInfo = class
private
FSize: UInt64;
public
constructor Create(Size: UInt64);
// properties to read the file information
property Size: UInt64 read FSize;
end;
TFindFileInfo = class // size is 4*4 + 8 = 24 bytes
private
FSize: UInt64;
FAttributes: Cardinal;
FCreationTime: _FILETIME;
FLastAccessTime: _FILETIME;
FLastWriteTime: _FILETIME;
public
constructor Create(var WS: WIN32_FIND_DATA);
// properties to read the file information
property Size: UInt64 read FSize;
property Attributes: Cardinal read FAttributes;
property CreationTime: _FILETIME read FCreationTime;
property LastAccessTime: _FILETIME read FLastAccessTime;
property LastWriteTime: _FILETIME read FLastWriteTime;
end;
const
SFR_CLOSED = $ffffffff; // -1
SFR_READINCORRECT = $fffffffe; // -2
SFR_NOMEM = $fffffffd; // -3
SFR_ENDOFFILE = $fffffffc; // -4
type
TSequentialFileReader = class
private
FStatus: DWORD; // Код последней ошибки (0, если нет ошибок)
FHandle: THANDLE; // Хэндл файла
FSize: UInt64; // Размер файла
FBuffer: Pointer; // Буфер для чтения
FBufferSize: Cardinal; // Размер буфера для чтения
// Инф. о процессе чтения
FLastReaded: Cardinal; // Прочитано в последнем чтении
FTotalReaded: UInt64; // Прочитано с начала чтения
public
constructor Create(const FileName: String; BufferSize: Cardinal);
destructor Destroy; override;
function StatusMessage: String;
/// <summary>
/// Читаем очередную порцию из файла.
/// </summary>
/// <returns>
/// Возвращает TRUE, если есть информация для обработки.
/// Иначе возвращает FALSE (достигнут конец файла).
/// Также, в Status возвращается статус операции. 0 означает - нет ошибки,
/// любое другое значение - код ошибки.
/// </returns>
/// <remarks>
/// После чтения обязательно проверить Status.
/// </remarks>
function ReadNextBlock: Boolean;
/// <summary>
/// Возвращает статут последней операции. 0 означает - нет ошибок.
/// Любое другое число - код ошибки.
/// </summary>
property Status: Cardinal read FStatus;
/// <summary>
/// Возвращает размер файла в байтах.
/// </summary>
property Size: UInt64 read FSize;
/// <summary>
/// Возвращает количество байт, прочитанных в последнем чтении.
/// </summary>
property LastReaded: Cardinal read FLastReaded;
/// <summary>
/// Возвращает количество байт, прочитанных с начала файла.
/// </summary>
property TotalReaded: UInt64 read FTotalReaded;
/// <summary>
/// Возвращает адрес буфера, куда читаются байты из файла.
/// </summary>
property Buffer: Pointer read FBuffer;
end;
/// <summary>
/// Уменьшить длину пути
/// </summary>
function ReduceFileName(const FileName: String; MaxLength: Integer): String;
/// <summary>
/// Вернуть имя тома для пути BasePath.
/// </summary>
function GetVolumeName(const BasePath: String): String;
/// <summary>
/// Функция возвращает размер файла (по имени файла)
/// </summary>
/// <param name="FileName">
/// Имя файла, для которого нужно узнать размер.
/// В функции к имени файла прибавляется Extended Prefix, '\\?\'.
/// </param>
/// <param name="FileSize">
/// Ссылка на переменную, принимающую размер файла.
/// </param>
/// <returns>
/// TRUE, если размер файла возвращен в переменную FileSize. FALSE, если произошла ошибка (в FileSize при этом возвращается 0).
/// </returns>
function GetFileSize(const FileName: String; out FileSize: UInt64): Boolean; overload;
/// <summary>
/// Функция возвращает размер файла (по дескриптору файла)
/// </summary>
/// <param name="H">
/// Дескриптор файла, для которого нужно узнать размер.
/// </param>
/// <param name="FileSize">
/// Ссылка на переменную, принимающую размер файла.
/// </param>
/// <returns>
/// TRUE, если размер файла возвращен в переменную FileSize. FALSE, если произошла ошибка (в FileSize при этом возвращается 0).
/// </returns>
function GetFileSize(H: THandle; out FileSize: UInt64): Boolean; overload;
/// <summary>
/// Функция ищет файлы и, если необходимо, добавляет информацию о них.
/// </summary>
///
/// <param name="StartPath">С этого каталога начинается поиск</param>
///
/// <param name="Mask">Маска поиска. Маская для всех файлов такая: "*".
/// Проверка маски осуществляется функцией CompareMask (не системой!).
/// В процессе изучения FindFirstFileW оказалось, что эта функция
/// не различает маски "*.md5" и "*.md5file", поэтому пришлось написать
/// свою функцию.</param>
///
/// <param name="Recursive">TRUE, если необходим рекурсивный поиск.
/// FALSE - если нужно искать только в каталоге StartPath.</param>
///
/// <param name="AddInfo">TRUE, если необходимо добавить информацию о файле
/// (размер, атрибуты, время создания; модификации; доступа).</param>
///
/// <param name="RemoveStartPath">TRUE, если из имени найденного файла
/// необходимо удалить стартовый каталог.</param>
///
/// <param name="StatProc">Процедура, которая будет показывать статистическую
/// информацию. Для подробностей - смотрите описание класса
/// <see cref="TScreenMessage"/>. По умолчанию, значение параметра равно nil.
/// </param>
///
/// <param name="StatUpdateInterval">Время, через которое нужно вызывать
/// функцию StatProc. По умолчанию, значение параметра равно 1500.</param>
///
/// <remarks>Рекомендуется указывать интервал обновления, StatUpdateInterval,
/// в пределах 1000-1500 миллисекунд.</remarks>
///
/// <returns>
/// Функция возвращает список имён файлов, в объекте
/// <see cref="TStringList"/>.
/// </returns>
function FindFiles(const StartPath: String;
const Mask: String;
Recursive: Boolean;
AddInfo: Boolean = FALSE;
RemoveStartPath: Boolean = FALSE;
StatProc: TScreenMessageProc = nil;
StatUpdateInterval: Cardinal = 1500): TStringList;
/// <summary>
/// Форматирует сообщение об ошибке по номеру ошибки.
/// </summary>
function FormatMessage(const MessageId: Integer): String;
// Функции для преобразования пути и имени файла
function GetLocalFileName(const WorkPath: String; const FileName: String): String;
function GetFullFileName(const WorkPath: String; const FileName: String): String;
function GetExtendedFileName(const FileName: String): String;
// Функции для работы с масками
function CompareMask(Name, Mask: PChar): Boolean; overload;
function CompareMask(Name, Mask: String): Boolean; overload;
function CompareChar(const C1, C2: Char): Boolean;
procedure PathBeautifuler(var S: String);
/// <summary>
/// Reduce file name to fit to MaxLength chars.
/// </summary>
//function ReduceFileName(const FileName: String; MaxLength: Integer): String;
IMPLEMENTATION
procedure PathBeautifuler(var S: String);
begin
if (S.Length >= 2) then
begin
if (S[2] = ':') AND (S[1] >= 'a') AND (S[1] <= 'z') then
begin
S[1] := UpCase(S[1]);
end;
end;
end;
function FormatMessage(const MessageId: Integer): String;
var
R: DWORD;
Buffer: array[0..1000] of Char;
begin
// format message for information
FillChar(Buffer, sizeof(Buffer), 0);
R := FormatMessageW(
FORMAT_MESSAGE_FROM_SYSTEM OR
FORMAT_MESSAGE_MAX_WIDTH_MASK, // dwFlags
nil, // lpSource
MessageId, // dwMessageId
0, // dwLanguageId
Buffer, // lpBuffer
Length(Buffer), // nSize
nil); // Arguments
if R = 0 then Result := 'N/A' // result is N/A, if FormatMessageW fails.
else Result := Buffer;
// Форматирование
Result := Result.Trim;
if Result.EndsWith('.') then Result := Result.Substring(0, Result.Length-1);
Result := Format('#%x, %s', [MessageId, Result]);
end;
// Сравнение по маске
// Специальные символы маски:
// ? заменяет собой один символ
// * заменяет собой 0 или более символов
// Планируется:
// [a-b] любой символ из диапазона a-b, например [a-f] - символы a,b,c,d,e,f
// [~a-b] любой символ кроме символа из диапазона a-b, например [~a] - любой символ, кроме a
// [abcd] любой символ из списка, например [!@#] - символы !, @, #
// [~abcd] любой символ, кроме символов из списка, например [~!] - любой символ, кроме !
// () - группировка, | - или, & - и, например ([a-b]|[x-z])
//
// Особенности:
// CompareMask('','')); = true
// CompareMask('', '*')); = true
// CompareMask('some', '')); = false
// CompareMask('filename', '*')); = true
// CompareMask('abc', 'def')); = false
function CompareMask(Name, Mask: PChar): Boolean;
// передача параметров через указатели более удобна.
// в противном случае, требуется создание локальных переменных - индексов,
// а параметры Name, Mask будут неизменяемые. И потребуется ещё одна
// вложенность процедуры - сравнивателя, которая будет работать
// непосредственно с индексами.
begin
repeat
// Проверка на конец сравнения
if (Name^ = MASK_END_OF_STRING) AND
(Mask^ = MASK_END_OF_STRING) then Exit(TRUE);
// Анализируем символ маски
if Mask^ = MASK_CHAR_ANY then
else if Mask^ = MASK_CHAR_ZERO_OF_MANY then
begin
// Пропускаем 0 или более символов в Name, и сравниваем с маской
Inc(Mask);
// Оптимизация (если после '*' идёт символ #0 - дальше можно не сравнивать)
if Mask^ = MASK_END_OF_STRING then Exit(TRUE);
// Указатель маски остается на месте, а мы
// пропускаем в Name 0 или более символов
repeat
if CompareMask(Name, Mask) then Exit(TRUE);
Inc(Name);
if (Name^ = MASK_END_OF_STRING) then Exit(FALSE);
until FALSE;
// Отсюда возврата нет!
end else
begin
// Сравниваем символы маски и строки
if NOT CompareChar(Name^, Mask^) then Exit(FALSE);
end;
// Переходим к следующим символам маски и строки
Inc(Name);
Inc(Mask);
until FALSE;
end;
function CompareMask(Name, Mask: String): Boolean;
begin
Exit(CompareMask(PChar(Name), PChar(Mask)));
end;
function FindFiles(const StartPath: String;
const Mask: String;
Recursive: Boolean;
AddInfo: Boolean = FALSE;
RemoveStartPath: Boolean = FALSE;
StatProc: TScreenMessageProc = nil;
StatUpdateInterval: Cardinal = 1500): TStringList;
var
CurrentPath: String;
FileInfo: TFindFileInfo;
//
S: TScreenMessage;
procedure FindHelper;
var
FF: THandle;
WS: WIN32_FIND_DATA;
begin
{ DONE -cvery important :
Объединить part1 и part2, т.к. сигнатуры поиска ( путь + '*' ) одинаковые.
А в текущий момент поиск происходит 2 раза: первый проход - файлы, второй проход - каталоги
===ИСПРАВЛЕНО}
FF := FindFirstFileW( PChar(EXTENDED_PATH_PREFIX + CurrentPath + ALL_FILES_MASK), WS);
if FF <> INVALID_HANDLE_VALUE then
begin
repeat
// Обрабатываем ФАЙЛ
if (WS.dwFileAttributes AND FILE_ATTRIBUTE_DIRECTORY) = 0 then
begin
// Сравниваем с маской (используем нашу процедуру сравнения, т.к.
// системная для маски *.md5 находит файлы checksum.md5, checksum.md5abc)
if Mask.Length > 0 then
begin
if NOT CompareMask(WS.cFileName, Mask) then Continue;
end;
// Нашли файл
S[0] := S[0] + 1;
// Inc(StatInfo.FilesFound);
// Добавляем информацию о файле
if AddInfo then
begin
FileInfo := TFindFileInfo.Create(WS);
end else
begin
FileInfo := nil;
end;
if RemoveStartPath then
begin
Result.AddObject(GetLocalFileName(StartPath, CurrentPath + WS.cFileName), FileInfo);
end else
begin
Result.AddObject(CurrentPath + WS.cFileName, FileInfo);
end;
end else if (WS.dwFileAttributes AND FILE_ATTRIBUTE_DIRECTORY) = FILE_ATTRIBUTE_DIRECTORY then
begin
// Only if recursive!!!
if Recursive then
begin
// Папки с именами '.' и '..' не нужны!
if (StrComp(WS.cFileName, SKIP_FOLDER_NAME_1) = 0) OR
(StrComp(WS.cFileName, SKIP_FOLDER_NAME_2) = 0) then Continue;
// Нашли папку
S[1] := S[1] + 1;
// Inc(StatInfo.FoldersFound);
// Сформировать новый текущий путь
CurrentPath := CurrentPath + WS.cFileName + PathDelim;
// recursive scan
FindHelper;
// Восстановить старый
SetLength(CurrentPath, CurrentPath.Length -
Integer(StrLen(WS.cFileName)) -
Length(PathDelim));
end;
end;
S.Show(smNORMAL);
until NOT FindNextFile( FF, WS );
FindClose(FF);
end;
end;
begin
// Инициализация переменных
//StatTick := 0;
//T := TTimer.Create;
S := TScreenMessage.Create(StatProc, StatUpdateInterval);
Result := TStringList.Create;
Result.OwnsObjects := TRUE;
// FillChar(StatInfo, sizeof(StatInfo), 0);
// Готовим стартовый путь
CurrentPath := IncludeTrailingPathDelimiter(StartPath);
// Поехали!
S.Show(smNORMAL);
// StatHelper(FALSE);
FindHelper;
S.Show(smDONE);
// StatHelper(TRUE);
// Заключительная обработка
//Result.Sort;
// T.Free;
S.Free;
end;
function GetFullFileName(const WorkPath: String; const FileName: String): String;
// Функция возвращает полный путь файла FileName
// (спереди добавляется WorkPath, если он не равен пустой строке,
// в ином случае, текущая рабочая папка)
begin
Result := IncludeTrailingPathDelimiter( WorkPath ) + FileName;
end;
// Функция "откусывает" от полного пути к файлу текущий путь
// В системе существует аналог моей функции, но более навороченный:
// s:=ExtractRelativePath('Y:\Projects\','Y:\Projects\Boulder MY\files.inc');
function GetLocalFileName(const WorkPath: String; const FileName: String): String;
var
i: Integer;
begin
i := 1;
while (i<=WorkPath.Length) AND
(i<=FileName.Length) AND
CompareChar(WorkPath[i], FileName[i]) do Inc(i);
//
Exit( FileName.Substring(i-1) ); // index zero-based
end;
function CompareChar(const C1, C2: Char): Boolean; inline;
begin
Exit(UpperCaseTable[C1] = UpperCaseTable[C2]);
end;
procedure MakeUpperCaseTable;
var
Ch: Char;
begin
// Генерация таблицы преобразования в верхний регистр
for Ch := Low(Char) to High(Char) do UpperCaseTable[Ch] := Ch;
CharUpperBuffW(UpperCaseTable, Length(UpperCaseTable));
end;
function GetFileSize(const FileName: String; out FileSize: UInt64): Boolean;
var
FS: WIN32_FILE_ATTRIBUTE_DATA;
begin
Result := GetFileAttributesEx(PChar( EXTENDED_PATH_PREFIX + FileName ), GetFileExInfoStandard, @FS);
if Result then
begin
FileSize := MakeUInt64(FS.nFileSizeLow, FS.nFileSizeHigh);
end else
begin
FileSize := MakeUInt64(0, 0);
end;
end;
function GetFileSize(H: THandle; out FileSize: UInt64): Boolean;
var
FileSizeLow, FileSizeHigh: Cardinal;
begin
FileSizeLow := Windows.GetFileSize(H, @FileSizeHigh);
if (FileSizeLow = $ffffffff) AND (GetLastError <> 0) then
begin
FileSize := MakeUInt64(0, 0);
Result := FALSE;
end else
begin
FileSize := MakeUInt64(FileSizeLow, FileSizeHigh);
Result := TRUE;
end;
end;
function GetVolumeName(const BasePath: String): String;
var
// Интересно, что если записать размерность 1..MAX_PATH,
// то команда Result := Buffer1 перестанет рассматривать
// буфер Buffer1 как ASCII-Z строку.
Buffer1, Buffer2: array[0..MAX_PATH] of Char;
Dummy1, Dummy2: DWORD;
R: Boolean;
begin
R := GetVolumeInformation(
PChar(IncludeTrailingPathDelimiter(ExtractFileDrive(BasePath))),
@Buffer1, Length(Buffer1),
NIL,
Dummy1,
Dummy2,
@Buffer2, Length(Buffer2));
//
if R then Result := Buffer1
else Result := 'N/A';
end;
function GetExtendedFileName(const FileName: String): String;
begin
if FileName.StartsWith(EXTENDED_PATH_PREFIX) then
begin
Result := FileName;
end else
begin
Result := EXTENDED_PATH_PREFIX + FileName;
end;
end;
{ TFindFilesFileInfo }
constructor TFindFileInfo.Create(var WS: WIN32_FIND_DATA);
begin
// Размер файла
FSize := MakeUInt64(WS.nFileSizeLow, WS.nFileSizeHigh);
(*
// !!! НЕВЕРНО КОМПИЛИРУЕТСЯ !!!
FSize := $ffffffffffffffff; // работает правильно
TFileSize(FSize).Lo := 1; // FSize не изменяется!
TFileSize(FSize).Hi := 1; // FSize не изменяется!
*)
// Атрибуты
FAttributes := WS.dwFileAttributes;
FCreationTime := WS.ftCreationTime;
FLastAccessTime := WS.ftLastAccessTime;
FLastWriteTime := WS.ftLastWriteTime;
end;
{ TSequentialFileReader }
constructor TSequentialFileReader.Create(const FileName: String; BufferSize: Cardinal);
begin
inherited Create;
//
FBuffer := nil;
FLastReaded := 0;
FTotalReaded := 0;
FStatus := 0;
FBufferSize := 0;
//
FHandle := CreateFile(
PChar( GetExtendedFileName(FileName) ), // lpFileName
GENERIC_READ, // dwDesiredAccess
FILE_SHARE_READ, // dwShareMode
nil, // lpSecurityAttributes
OPEN_EXISTING, // dwCreationDisposition
FILE_ATTRIBUTE_NORMAL, // dwFlagsAndAttribute
0); // hTemplateFile
// Файл не открылся - ошибка
if FHandle = INVALID_HANDLE_VALUE then
begin
// store error code
FStatus := GetLastError;
FHandle := INVALID_HANDLE_VALUE;
end else
begin
// Файл открылся, задаем константы для работы
if NOT GetFileSize(FHandle, FSize) then
begin
// Получить размер файла не удалось - ошибка
FStatus := GetLastError;
CloseHandle(FHandle);
FHandle := INVALID_HANDLE_VALUE;
end else
begin
// all ok, file opened, and we get's it size
FBufferSize := BufferSize;
FStatus := 0;
// Пытаемся выделить буфер для файла
FBuffer := GetMemory(FBufferSize);
if FBuffer = nil then FStatus := SFR_NOMEM;
end;
end;
end;
destructor TSequentialFileReader.Destroy;
begin
if FBuffer <> nil then
begin
FreeMemory(FBuffer);
FBuffer := nil;
end;
if FHandle <> INVALID_HANDLE_VALUE then
begin
CloseHandle(FHandle);
FHandle := INVALID_HANDLE_VALUE;
end;
FStatus := SFR_CLOSED;
inherited;
end;
function TSequentialFileReader.ReadNextBlock: Boolean;
var
R, Readed: DWORD;
begin
// Проверка на достижение конца файла
if FSize - FTotalReaded = 0 then Exit(FALSE);
// Вычисляем размер очередной порции для чтения
if FSize - FTotalReaded > FBufferSize then R := FBufferSize
else R := FSize - FTotalReaded;
//
{$IFDEF SPECIAL_FAST_MODE}
{$MESSAGE 'SPECIAL MODE: on (read from zero-file)'}
Readed := R;
Result := TRUE;
FillChar(FBuffer^, R, 0);
{$ELSE}
{$MESSAGE 'SPECIAL MODE: off'}
// Читаем файл
Result := Windows.ReadFile(FHandle, // hFile
FBuffer^, // lpBuffer
R, // nNumberOfBytesToRead
Readed, // lpNumberOfBytesRead
nil); // lpOverlapped
{$ENDIF}
// Установка ошибки, если ошибка при чтении
if NOT Result then
begin
FStatus := GetLastError;
Exit(TRUE);
end;
// Установка ошибки, если прочитано не столько, сколько просили
if Readed <> R then
begin
FStatus := SFR_READINCORRECT;
Exit(TRUE);
end;
// Иначе, нет ошибки
FLastReaded := R;
Inc(FTotalReaded, R);
Result := TRUE;
end;
function TSequentialFileReader.StatusMessage: String;
begin
case FStatus of
SFR_CLOSED: Exit('attempt to use destroyed object'); // 'the object is already destroyed';
SFR_READINCORRECT: Exit('the number of bytes read does not equal the number requested'); // read bytes != request bytes
SFR_NOMEM: Exit('not enough memory for allocate the read buffer');
0: Exit('');
else Exit(FormatMessage(FStatus));
end;
end;
//==============================================================================
{ TFileSize }
constructor TFileSizeInfo.Create(Size: UInt64);
begin
FSize := Size;
end;
function ReduceFileName(const FileName: String; MaxLength: Integer): String;
// Возможны следующие пути:
// "\\сервер\share\путь\файл" - сокращения начинать с "путь\файл"
// "C:\путь\имя" - сокращения начинать с "путь\файл"
// если путь начинается с "\\?\", эту часть ("\\?\") можно убрать
var
IndexStart, IndexEnd, IndexRemove: Integer;
const
SUBST_CHARS = '...';
function BeginsWithDrive(const S: String): Boolean;
begin
Result := (S.Length>=3) AND
(CharInSet(S[1], ['A'..'Z', 'a'..'z'])) AND
(S[2]=':') AND
(S[3]='\');
end;
begin
Result := FileName;
if MaxLength < 0 then Exit;
// Убрать ненужные части
if FileName.StartsWith('\\?\') then
begin
Result := Result.Substring(4);
end;
//
if Result.Length > MaxLength then
begin
if MaxLength <= SUBST_CHARS.Length then
begin
Result := SUBST_CHARS.Substring(0, MaxLength);
end else
begin
IndexStart := 1;
IndexEnd := Result.Length;
// Проверка: FileName это путь с буквой диска
// (буква диска) ":" "\"
if BeginsWithDrive(Result) then
begin
IndexStart := 4;
end;
//
IndexRemove := IndexStart + (Result.Length - MaxLength + SUBST_CHARS.Length);
if IndexRemove >= IndexEnd then
begin
// Пробуем сместить IndexStart на начало
IndexStart := 1;
IndexRemove := IndexStart + (Result.Length - MaxLength + SUBST_CHARS.Length);
end;
// Remove chars IndexStart..IndexRemove
Result := Result.Substring(0, IndexStart-1) + SUBST_CHARS +
Result.Substring(IndexRemove-1, IndexEnd-IndexRemove+1);
end;
end;
end;
initialization
MakeUpperCaseTable;
finalization
end.
|
unit IdTCPStream;
interface
uses
Classes,
IdTCPConnection;
type
TIdTCPStream = class(TStream)
protected
FConnection: TIdTCPConnection;
public
constructor Create(AConnection: TIdTCPConnection); reintroduce;
function Read(var ABuffer; ACount: Longint): Longint; override;
function Write(const ABuffer; ACount: Longint): Longint; override;
function Seek(AOffset: Longint; AOrigin: Word): Longint; override;
//
property Connection: TIdTCPConnection read FConnection;
end;
implementation
{ TIdTCPStream }
constructor TIdTCPStream.Create(AConnection: TIdTCPConnection);
begin
inherited Create;
FConnection := AConnection;
end;
function TIdTCPStream.Read(var ABuffer; ACount: Integer): Longint;
begin
Connection.ReadBuffer(ABuffer, ACount);
Result := ACount;
end;
function TIdTCPStream.Seek(AOffset: Integer; AOrigin: Word): Longint;
begin
Result := -1;
end;
function TIdTCPStream.Write(const ABuffer; ACount: Integer): Longint;
begin
Connection.WriteBuffer(ABuffer, ACount);
Result := ACount;
end;
end.
|
(* Multiset: MM, 2020-04-17 *)
(* ------ *)
(* Unit to create String Multisets as ADT *)
(* ========================================================================= *)
UNIT Multiset;
INTERFACE
TYPE
StrMSet = POINTER;
PROCEDURE NewStrMSet(VAR ms: StrMSet);
PROCEDURE DisposeStrMSet(VAR ms: StrMSet);
PROCEDURE Insert(VAR ms: StrMSet; element: STRING);
PROCEDURE WriteTree(ms: StrMSet; space: INTEGER);
PROCEDURE Remove(VAR ms: StrMSet; element: STRING);
FUNCTION IsEmpty(ms: StrMSet): BOOLEAN;
FUNCTION Contains(ms: StrMSet; element: STRING): BOOLEAN;
FUNCTION Count(ms: StrMSet; element: STRING): INTEGER;
FUNCTION Cardinality(ms: StrMSet): INTEGER;
FUNCTION CountUnique(ms: StrMSet): INTEGER;
PROCEDURE WriteTreeAsList(ms: StrMSet);
PROCEDURE ToArray(ms: StrMSet; VAR a: ARRAY OF STRING; VAR count: INTEGER);
IMPLEMENTATION
TYPE
StrMSetPtr = ^StrMultSet;
StrMultSet = RECORD
element: STRING;
count: INTEGER;
left: StrMSetPtr;
right: StrMSetPtr;
END; (* StrMSet *)
PROCEDURE ToArray(ms: StrMSet; VAR a: ARRAY OF STRING; VAR count: INTEGER);
BEGIN (* ToArray *)
IF (ms <> NIL) THEN BEGIN
{$R-}
a[count] := StrMSetPtr(ms)^.element;
{$R+}
Inc(count);
ToArray(StrMSetPtr(ms)^.left, a, count);
Inc(count);
ToArray(StrMSetPtr(ms)^.right, a, count);
END; (* IF *)
END; (* ToArray *)
FUNCTION NewNode(x: STRING): StrMSetPtr;
VAR n: StrMSetPtr;
BEGIN (* NewNode *)
New(n);
n^.element := x;
n^.count := 1;
n^.left := NIL;
n^.right := NIL;
NewNode := n;
END; (* NewNode *)
PROCEDURE NewStrMSet(VAR ms: StrMSet);
BEGIN (* NewStrMSet *)
GetMem(ms, SizeOf(STRING) + 2 * SizeOf(StrMSetPtr) + SizeOf(INTEGER));
StrMSetPtr(ms)^.element := '';
StrMSetPtr(ms)^.count := 0;
StrMSetPtr(ms)^.left := NIL;
StrMSetPtr(ms)^.right := NIL;
END; (* NewStrMSet *)
PROCEDURE DisposeStrMSet(VAR ms: StrMSet);
BEGIN (* DisposeStrMSet *)
IF (ms <> NIL) THEN BEGIN
DisposeStrMSet(StrMSetPtr(ms)^.left);
DisposeStrMSet(StrMSetPtr(ms)^.right);
FreeMem(ms, SizeOf(STRING) + 2 * SizeOf(StrMSetPtr));
END; (* IF *)
END; (* DisposeStrMSet *)
PROCEDURE Insert(VAR ms: StrMSet; element: STRING);
BEGIN (* Insert *)
IF ((ms <> NIL) AND (StrMSetPtr(ms)^.element <> '')) THEN BEGIN
IF (StrMSetPtr(ms)^.element = element) THEN BEGIN
Inc(StrMSetPtr(ms)^.count);
END ELSE IF (StrMSetPtr(ms)^.element < element) THEN BEGIN
IF (StrMSetPtr(ms)^.right <> NIL) THEN BEGIN
Insert(StrMSetPtr(ms)^.right, element);
END ELSE BEGIN
StrMSetPtr(ms)^.right := NewNode(element);
END; (* IF *)
END ELSE IF (StrMSetPtr(ms)^.element > element) THEN BEGIN
IF (StrMSetPtr(ms)^.left <> NIL) THEN BEGIN
Insert(StrMSetPtr(ms)^.left, element);
END ELSE BEGIN
StrMSetPtr(ms)^.left := NewNode(element);
END; (* IF *)
END ELSE BEGIN
WriteLn('ERROR: Could not insert element "', element, '" into data structure.');
HALT;
END; (* IF *)
END ELSE BEGIN
StrMSetPtr(ms)^.element := element;
StrMSetPtr(ms)^.count := 1;
END; (* IF *)
END; (* Insert *)
PROCEDURE WriteTree(ms: StrMSet; space: INTEGER);
VAR i: INTEGER;
BEGIN (* WriteTree *)
IF (ms <> NIL) THEN BEGIN
space := space + 10;
WriteTree(StrMSetPtr(ms)^.right, space);
WriteLn;
FOR i := 10 TO space DO BEGIN
Write(' ');
END; (* FOR *)
WriteLn(StrMSetPtr(ms)^.element, ': ', StrMSetPtr(ms)^.count);
WriteTree(StrMSetPtr(ms)^.left, space);
END; (* IF *)
END; (* WriteTree *)
PROCEDURE Remove(VAR ms: StrMSet; element: STRING);
VAR cur, prev, child, next, nextPrev: StrMSetPtr;
BEGIN (* Remove *)
prev := NIL;
cur := StrMSetPtr(ms);
WHILE ((cur <> NIL) AND (cur^.element <> element)) DO BEGIN
prev := cur;
IF (element < cur^.element) THEN
cur := cur^.left
ELSE
cur := cur^.right;
END; (* WHILE *)
IF (cur <> NIL) THEN BEGIN
IF (cur^.right = NIL) THEN BEGIN
child := cur^.left;
END ELSE IF (cur^.right^.left = NIL) THEN BEGIN
child := cur^.right;
child^.left := cur^.left;
END ELSE BEGIN
nextPrev := NIL;
next := cur^.right;
WHILE (next^.left <> NIL) DO BEGIN
nextPrev := next;
next := next^.left;
END; (* WHILE *)
nextPrev^.left := next^.right;
next^.left := cur^.left;
child := next;
END; (* IF *)
IF (prev = NIL) THEN BEGIN
StrMSetPtr(ms) := child;
END ELSE IF (cur^.element < prev^.element) THEN BEGIN
prev^.left := child;
END ELSE BEGIN
prev^.right := child
END; (* IF *)
cur^.left := NIL;
cur^.right := NIL;
Dispose(cur);
END; (* IF *)
END; (* Remove *)
FUNCTION IsEmpty(ms: StrMSet): BOOLEAN;
BEGIN (* IsEmpty *)
IsEmpty := (ms = NIL) OR (StrMSetPtr(ms)^.element = '');
END; (* IsEmpty *)
FUNCTION Contains(ms: StrMSet; element: STRING): BOOLEAN;
BEGIN (* Contains *)
IF (ms = NIL) THEN BEGIN
Contains := FALSE;
END ELSE IF (StrMSetPtr(ms)^.element = element) THEN BEGIN
Contains := TRUE;
END ELSE IF (element < StrMSetPtr(ms)^.element) THEN BEGIN
Contains := Contains(StrMSetPtr(ms)^.left, element);
END ELSE BEGIN
Contains := Contains(StrMSetPtr(ms)^.right, element);
END; (* IF *)
END; (* Contains *)
FUNCTION Count(ms: StrMSet; element: STRING): INTEGER;
BEGIN (* Count *)
IF (ms = NIL) THEN BEGIN
Count := 0;
END ELSE IF (StrMSetPtr(ms)^.element = element) THEN BEGIN
Count := StrMSetPtr(ms)^.count;
END ELSE IF (element < StrMSetPtr(ms)^.element) THEN BEGIN
Count := Count(StrMSetPtr(ms)^.left, element);
END ELSE BEGIN
Count := Count(StrMSetPtr(ms)^.right, element);
END; (* IF *)
END; (* Count *)
FUNCTION Cardinality(ms: StrMSet): INTEGER;
BEGIN (* Cardinality *)
IF (ms <> NIL) THEN BEGIN
Cardinality := StrMSetPtr(ms)^.count + Cardinality(StrMSetPtr(ms)^.left) + Cardinality(StrMSetPtr(ms)^.right);
END ELSE BEGIN
Cardinality := 0;
END; (* IF *)
END; (* Cardinality *)
FUNCTION CountUnique(ms: StrMSet): INTEGER;
BEGIN (* CountUnique *)
IF (ms <> NIL) THEN BEGIN
CountUnique := 1 + CountUnique(StrMSetPtr(ms)^.left) + CountUnique(StrMSetPtr(ms)^.right);
END ELSE BEGIN
CountUnique := 0;
END; (* IF *)
END; (* CountUnique *)
PROCEDURE WriteTreeAsList(ms: StrMSet);
BEGIN (* WriteTreeAsList *)
IF (ms <> NIL) THEN BEGIN
WriteLn(StrMSetPtr(ms)^.element, ': ', StrMSetPtr(ms)^.count);
WriteTreeAsList(StrMSetPtr(ms)^.left);
WriteTreeAsList(StrMSetPtr(ms)^.right);
END; (* IF *)
END; (* WriteTreeAsList *)
BEGIN (* Multiset *)
END. (* Multiset *) |
unit uMain;
{
* Copyright 2017 ZXing.NET authors
*
* 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.
*
* Implemented by E. Spelt for Delphi
*
* Uses examples from https://quality.embarcadero.com/browse/RSP-10592 from Erik van Bilsen
READ ME
This project is an example of a professional barcode project.
No support what so ever ids offered cause this is just a sample project and uses soms exotic libraries.
It offers:
- Huge camera performance tweak from Erik van Bilsen. See: https://quality.embarcadero.com/browse/RSP-10592
Look in the path settings of the project for the tweak.
- Plays sound VIA NATIVE API for fast sounds via the audio manager from fmxexpress.com
- Barcode scanning via our perfomant native ZXing library.
- A good barcode strategie.
- Background task based and therefore a responsive GUI.
- Fancy GUI.
- Check + warning for slow camera fps (frames per second). 20fps is recommended minimum.
- Marks your barcode hit in the HUD
- Tested in Delphi Tokyo edition.
Performance TIPS:
- Tweak with SCAN_EVERY_N_FRAME_FREQ maybe you can set it higher, depending on your situation.
- Use only the Barcode Types you need to scan. Set it on auto with care.
}
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
System.Math.Vectors, FMX.Media,
FMX.Objects, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Layouts,
ZXing.BarcodeFormat,
ZXing.ResultPoint,
FMX.Platform,
System.Generics.Defaults,
System.Generics.Collections,
System.Diagnostics,
System.Threading,
System.Math,
System.IOUtils,
ZXing.ReadResult,
ZXing.ScanManager, FMX.ListBox, FMX.ExtCtrls, FMX.ScrollBox, FMX.Memo,
FMX.Ani,
FMX.Effects,
System.Permissions,
System.Rtti,
AudioManager;
const
// Seconds to wait before update and check the frame rate
FPS_POLLING_FREQ: Integer = 3;
// Skip n frames to do a barcode scan
FRAME_PER_SECOND_SPEED_ALERT_THRESHOLD: Integer = 20;
// Skip n frames to do a barcode scan
SCAN_EVERY_N_FRAME_FREQ: Integer = 4;
type
TScanBufferEvent = procedure(Sender: TObject; ABitmap: TBitmap) of object;
TFormMain = class(TForm)
Layout2: TLayout;
Memo1: TMemo;
ToolBar3: TRectangle;
SwitchScanning: TSwitch;
LabelFPS: TLabel;
btnBackCamera: TSpeedButton;
btnFrontCamera: TSpeedButton;
ListBox1: TListBox;
ListBoxItem1: TListBoxItem;
ListBoxItem2: TListBoxItem;
CameraComponent1: TCameraComponent;
PopupBoxSetting: TPopupBox;
RectImageSurface: TRectangle;
PlotGridVizer: TPlotGrid;
RectVizer: TRectangle;
lblScanning: TLabel;
FaLblScanning: TFloatAnimation;
Layout1: TLayout;
lblSlowWarning: TLabel;
rectSlowWarning: TRectangle;
TimerShowHit: TTimer;
Label1: TLabel;
TimerAutoFocus: TTimer;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure SwitchScanningSwitch(Sender: TObject);
procedure btnBackCameraClick(Sender: TObject);
procedure btnFrontCameraClick(Sender: TObject);
procedure CameraComponent1SampleBufferReady(Sender: TObject; const ATime: TMediaTime);
procedure PopupBoxSettingChange(Sender: TObject);
procedure TimerShowHitTimer(Sender: TObject);
procedure TimerAutoFocusTimer(Sender: TObject);
private
FPermissionCamera: string;
FScanManager: TScanManager;
FScanInProgress: Boolean;
FFrameTake: Integer;
FStopwatch: TStopwatch;
FFrameCount: Integer;
FCaptureSettings: TArray<TVideoCaptureSetting>;
targetRect: TRect;
FActive: Boolean;
FBuffer: TBitmap;
FScanBitmap: TBitmap;
FAudioMgr: TAudioManager;
procedure ParseBitmap;
function AppEvent(AAppEvent: TApplicationEvent; AContext: TObject): Boolean;
procedure UpdateCaptureSettings(CameraKind: TCameraKind);
procedure StartCapture;
procedure StopCapture;
procedure StartStopWatch;
procedure DisplaySlowWarning(Show: Boolean);
procedure MarkBarcode(resultPoints: TArray<IResultPoint>);
procedure AccessCameraPermissionRequestResult(Sender: TObject; const APermissions: TArray<string>;
const AGrantResults: TArray<TPermissionStatus>);
procedure DisplayRationale(Sender: TObject; const APermissions: TArray<string>; const APostRationaleProc: TProc);
procedure ActivateCameraPermissionRequestResult(Sender: TObject; const APermissions: TArray<string>;
const AGrantResults: TArray<TPermissionStatus>);
procedure SyncBitmap;
procedure SetCameraParamaters;
procedure FocusReady;
end;
var
FormMain: TFormMain;
implementation
uses
{$IFDEF ANDROID}
Androidapi.Helpers,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.Os,
Androidapi.JNI.Hardware,
Androidapi.JNIBridge,
CameraConfigUtils,
{$ENDIF}
FMX.DialogService;
{$R *.fmx}
type
TMyCamera = class(TCameraComponent)
end;
{$IFDEF ANDROID}
TAndroidCameraCallback = class(TJavaLocal, JCamera_AutoFocusCallback)
private
[Weak] FFormMain: TFormMain;
public
procedure onAutoFocus(success: Boolean; camera: JCamera); cdecl;
end;
procedure TAndroidCameraCallback.onAutoFocus(success: Boolean; camera: JCamera); cdecl;
{$IFDEF ANDROID}
var
params: JCamera_Parameters;
area: JList;
{$ENDIF}
begin
FFormMain.FocusReady;
// camera.cancelAutoFocus();
end;
var
CameraCallBack: TAndroidCameraCallback = nil;
function GetCameraCallBack: TAndroidCameraCallback;
begin
if CameraCallBack = nil then
CameraCallBack := TAndroidCameraCallback.Create;
Result := CameraCallBack;
end;
{$ENDIF}
procedure TFormMain.FormCreate(Sender: TObject);
var
AppEventSvc: IFMXApplicationEventService;
AudioFilePath: string;
begin
{$IFDEF ANDROID}
FPermissionCamera := JStringToString(TJManifest_permission.JavaClass.CAMERA);
{$ENDIF}
PermissionsService.RequestPermissions([FPermissionCamera], AccessCameraPermissionRequestResult, DisplayRationale);
if TPlatformServices.Current.SupportsPlatformService(IFMXApplicationEventService, IInterface(AppEventSvc)) then
begin
AppEventSvc.SetApplicationEventHandler(AppEvent);
end;
FAudioMgr := TAudioManager.Create;
AudioFilePath := TPath.Combine(TPath.GetDocumentsPath, 'Ok.wav');
if FileExists(AudioFilePath) then
FAudioMgr.AddSound(AudioFilePath)
else
Showmessage('Error loading OK.wav');
FActive := False;
FBuffer := TBitmap.Create();
FScanBitmap := TBitmap.Create();
FFrameTake := 0;
FScanInProgress := False;
UpdateCaptureSettings(TCameraKind.BackCamera);
btnBackCamera.IsPressed := True;
// Use only the Barcode Types you need to scan. Set it on auto with care!!
FScanManager := TScanManager.Create(TBarcodeFormat.Auto, nil);
DisplaySlowWarning(False);
end;
procedure TFormMain.FormDestroy(Sender: TObject);
begin
FScanBitmap.Free;
FBuffer.Free;
StopCapture();
CameraComponent1.Active := False;
FScanManager.Free;
FAudioMgr.Free
end;
procedure TFormMain.AccessCameraPermissionRequestResult(Sender: TObject; const APermissions: TArray<string>;
const AGrantResults: TArray<TPermissionStatus>);
begin
// 1 permission involved: CAMERA
if (Length(AGrantResults) = 1) and (AGrantResults[0] = TPermissionStatus.Granted) then
{ Fill the resolutions. }
begin
CameraComponent1.Quality := TVideoCaptureQuality.PhotoQuality;
CameraComponent1.FocusMode := TFocusMode.ContinuousAutoFocus;
end
else
Showmessage('Cannot access the camera because the required permission has not been granted')
end;
// Optional rationale display routine to display permission requirement rationale to the user
procedure TFormMain.DisplayRationale(Sender: TObject; const APermissions: TArray<string>; const APostRationaleProc: TProc);
begin
// Show an explanation to the user *asynchronously* - don't block this thread waiting for the user's response!
// After the user sees the explanation, invoke the post-rationale routine to request the permissions
TDialogService.Showmessage('The app needs to access the camera in order to work',
procedure(const AResult: TModalResult)
begin
APostRationaleProc
end)
end;
{ Make sure the camera is released if you're going away. }
function TFormMain.AppEvent(AAppEvent: TApplicationEvent; AContext: TObject): Boolean;
begin
case AAppEvent of
TApplicationEvent.EnteredBackground, TApplicationEvent.WillTerminate:
StopCapture();
end;
end;
procedure TFormMain.StartCapture;
begin
FBuffer.Clear(TAlphaColors.White);
FActive := True;
LabelFPS.Text := 'Starting capture...';
PermissionsService.RequestPermissions([FPermissionCamera], ActivateCameraPermissionRequestResult, DisplayRationale);
StartStopWatch();
lblScanning.Text := 'Scanning on';
FaLblScanning.Enabled := True;
end;
procedure TFormMain.ActivateCameraPermissionRequestResult(Sender: TObject; const APermissions: TArray<string>;
const AGrantResults: TArray<TPermissionStatus>);
begin
// 1 permission involved: CAMERA
if (Length(AGrantResults) = 1) and (AGrantResults[0] = TPermissionStatus.Granted) then
begin
{ Turn on the Camera }
CameraComponent1.Active := True;
end
else
Showmessage('Cannot start the camera because the required permission has not been granted')
end;
procedure TFormMain.StopCapture;
begin
SwitchScanning.IsChecked := False;
lblScanning.Text := 'No scanning';
FaLblScanning.Enabled := False;
FActive := False;
DisplaySlowWarning(False);
CameraComponent1.Active := False; // WARNING: CAUSES A CRASH WITH THE CAMERA SPEED TWEAK
LabelFPS.Text := '';
end;
procedure TFormMain.StartStopWatch();
begin
FStopwatch := TStopwatch.StartNew;
FFrameCount := 0;
end;
procedure TFormMain.CameraComponent1SampleBufferReady(Sender: TObject; const ATime: TMediaTime);
begin
TThread.Synchronize(TThread.CurrentThread, SyncBitmap);
ParseBitmap();
end;
procedure TFormMain.SyncBitmap();
begin
CameraComponent1.SampleBufferToBitmap(FBuffer, True);
end;
procedure TFormMain.ParseBitmap;
var
sec, fps: double;
ReadResult: TReadResult;
begin
sec := FStopwatch.Elapsed.TotalSeconds;
Inc(FFrameCount);
if (Ceil(sec) mod FPS_POLLING_FREQ = 0) then
begin
fps := FFrameCount / sec;
LabelFPS.Text := Format('%.1f fps (%d x %d)', [fps, CameraComponent1.CaptureSetting.Width, CameraComponent1.CaptureSetting.Height]);
DisplaySlowWarning(fps < FRAME_PER_SECOND_SPEED_ALERT_THRESHOLD);
StartStopWatch();
end;
if not FActive then
begin
Exit;
end;
RectImageSurface.Fill.Bitmap.Bitmap := FBuffer;
if FScanInProgress then
Exit;
if ((FFrameCount mod SCAN_EVERY_N_FRAME_FREQ) <> 0) then
Exit;
FScanBitmap.Assign(FBuffer);
ReadResult := nil;
TTask.Run(
procedure
begin
try
try
FScanInProgress := True;
ReadResult := FScanManager.Scan(FScanBitmap);
except
on E: Exception do
begin
TThread.Synchronize(nil,
procedure
begin
Memo1.Lines.Insert(0, formatdatetime('c ', Now) + E.Message);
end);
Exit;
end;
end;
if (ReadResult <> nil) then
begin
TThread.Synchronize(nil,
procedure
begin
MarkBarcode(ReadResult.resultPoints);
FAudioMgr.PlaySound(0); // 0 is the 0 index of the sound collecion
Memo1.Lines.Insert(0, formatdatetime('c ', Now) + ReadResult.Text);
end);
end;
finally
ReadResult.Free;
FScanInProgress := False;
end;
end);
end;
procedure TFormMain.MarkBarcode(resultPoints: TArray<IResultPoint>);
const
iSize = 15;
begin
FActive := False;
TimerShowHit.Enabled := True;
RectImageSurface.Fill.Bitmap.Bitmap.Assign(FScanBitmap); // make sure it is the same bitmap
RectImageSurface.Fill.Bitmap.Bitmap.Canvas.BeginScene;
try
RectImageSurface.Fill.Bitmap.Bitmap.Canvas.Fill.Color := TAlphaColors.Orange;
if (Length(resultPoints) = 2) then
begin
// When 2 points then draw a line on the bitmap.
RectImageSurface.Fill.Bitmap.Bitmap.Canvas.FillRect(TRectF.Create(resultPoints[0].x - iSize, resultPoints[0].y - iSize,
resultPoints[1].x + iSize, resultPoints[1].y + iSize), 0, 0, AllCorners, 1);
end
else if (Length(resultPoints) = 3) then
begin
// When 3 points then draw a square on the bitmap.
RectImageSurface.Fill.Bitmap.Bitmap.Canvas.FillRect(TRectF.Create(resultPoints[0].x, resultPoints[0].y, resultPoints[2].x,
resultPoints[2].y), 0, 0, AllCorners, 1);
end;
finally
RectImageSurface.Fill.Bitmap.Bitmap.Canvas.EndScene;
end;
end;
procedure TFormMain.FocusReady;
{$IFDEF ANDROID}
var
JC: JCamera;
Device: TCaptureDevice;
ClassRef: TClass;
ctx: TRttiContext;
t: TRttiType;
previewSize: TSize;
params: JCamera_Parameters;
{$ENDIF}
begin
{$IFDEF ANDROID}
try
Device := TMyCamera(CameraComponent1).Device;
ClassRef := Device.ClassType;
ctx := TRttiContext.Create;
t := ctx.GetType(ClassRef);
JC := t.GetProperty('Camera').GetValue(Device).AsInterface as JCamera;
params := JC.getParameters;
// Params.setFocusMode(TJCamera_Parameters.JavaClass.FOCUS_MODE_MACRO); // crash on some devices
TCameraConfigUtils.setFocus(Params, true, false, true);
JC.setparameters(params);
finally
JC.startPreview();
end;
{$ENDIF}
end;
procedure TFormMain.TimerAutoFocusTimer(Sender: TObject);
{$IFDEF ANDROID}
var
JC: JCamera;
Device: TCaptureDevice;
ClassRef: TClass;
ctx: TRttiContext;
t: TRttiType;
params: JCamera_Parameters;
{$ENDIF}
begin
if FActive = false then
Exit();
{$IFDEF ANDROID}
Device := TMyCamera(CameraComponent1).Device;
ClassRef := Device.ClassType;
ctx := TRttiContext.Create;
try
t := ctx.GetType(ClassRef);
JC := t.GetProperty('Camera').GetValue(Device).AsInterface as JCamera;
JC.cancelAutoFocus;
GetCameraCallback().FFormMain := Self;
JC.autoFocus(GetCameraCallback()); // key - set it again
JC.startPreview;
finally
ctx.Free;
end;
{$ENDIF}
end;
procedure TFormMain.TimerShowHitTimer(Sender: TObject);
begin
FActive := True;
TimerShowHit.Enabled := False;
end;
procedure TFormMain.DisplaySlowWarning(Show: Boolean);
begin
rectSlowWarning.Visible := Show;
end;
procedure TFormMain.PopupBoxSettingChange(Sender: TObject);
begin
if (PopupBoxSetting.ItemIndex < 0) then
Exit;
CameraComponent1.CaptureSetting := FCaptureSettings[PopupBoxSetting.ItemIndex];
StartCapture();
end;
procedure TFormMain.SwitchScanningSwitch(Sender: TObject);
begin
if (SwitchScanning.IsChecked) then
StartCapture()
else
StopCapture();
end;
procedure TFormMain.btnBackCameraClick(Sender: TObject);
begin
UpdateCaptureSettings(TCameraKind.BackCamera);
end;
procedure TFormMain.btnFrontCameraClick(Sender: TObject);
begin
UpdateCaptureSettings(TCameraKind.FrontCamera);
end;
procedure TFormMain.UpdateCaptureSettings(CameraKind: TCameraKind);
var
Setting, MaxSetting: TVideoCaptureSetting;
UsefulSettings: TDictionary<TSize, TVideoCaptureSetting>;
Size: TSize;
I: Integer;
begin
StopCapture();
CameraComponent1.Kind := CameraKind;
{ GetAvailableCaptureSettings can return A LOT of settings. For each supported
resolution, it can return a large number of settings with different frame
rates. We only care about the highest framerate supported by each
resolution. We use a dictionary to keep track of this. }
UsefulSettings := TDictionary<TSize, TVideoCaptureSetting>.Create;
try
for Setting in CameraComponent1.GetAvailableCaptureSettings(nil) do
begin
Size := TSize.Create(Setting.Width, Setting.Height);
if (UsefulSettings.TryGetValue(Size, MaxSetting)) then
begin
{ Dictionary contains requested resolution. Update its framerate to the
maximum supported one. }
if (Setting.FrameRate > MaxSetting.FrameRate) then
UsefulSettings.AddOrSetValue(Size, Setting);
end
else
UsefulSettings.Add(Size, Setting);
end;
{ Now we can get a list of settings, with only one per resolution. We sort it
maually by resolution. }
FCaptureSettings := UsefulSettings.Values.ToArray;
{ Now we can get a list of settings, with only one per resolution. We sort it
maually by resolution. }
FCaptureSettings := UsefulSettings.Values.ToArray;
TArray.Sort<TVideoCaptureSetting>(FCaptureSettings, TComparer<TVideoCaptureSetting>.Construct(
function(const Left, right: TVideoCaptureSetting): Integer
var
Difference: Integer;
begin
Difference := (Left.Width * Left.Height) - (right.Width * right.Height);
if (Difference < 0) then
Result := 1
else if (Difference > 0) then
Result := -1
else
Result := 0;
end));
finally
UsefulSettings.Free;
end;
{ Populate popup box with settings }
PopupBoxSetting.BeginUpdate;
try
PopupBoxSetting.Items.Clear;
for I := 0 to Length(FCaptureSettings) - 1 do
begin
Setting := FCaptureSettings[I];
PopupBoxSetting.Items.Add(Format('%d x %d x %dfps ', [Setting.Width, Setting.Height, Round(Setting.FrameRate)]));
end;
finally
PopupBoxSetting.EndUpdate;
end;
PopupBoxSetting.ItemIndex := -1;
end;
procedure TFormMain.SetCameraParamaters;
{$IFDEF ANDROID}
var
JC: JCamera;
Device: TCaptureDevice;
ClassRef: TClass;
ctx: TRttiContext;
t: TRttiType;
params: JCamera_Parameters;
{$ENDIF}
begin
{$IFDEF ANDROID}
Device := TMyCamera(CameraComponent1).Device;
ClassRef := Device.ClassType;
ctx := TRttiContext.Create;
try
t := ctx.GetType(ClassRef);
JC := t.GetProperty('Camera').GetValue(Device).AsInterface as JCamera;
JC.cancelAutoFocus();
Params := JC.getParameters;
// TCameraConfigUtils.setBarcodeSceneMode(Params);
// TCameraConfigUtils.setVideoStabilization(Params);
TCameraConfigUtils.setFocus(Params, false, false, true);
JC.setParameters(params);
JC.startPreview();
GetCameraCallback().FFormMain := Self;
JC.autoFocus(GetCameraCallback());
TimerAutoFocus.Enabled := true;
finally
ctx.Free;
end;
{$ENDIF}
end;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
April '2000
Problem 115 O(NLgN) Greedy Method
}
program
Experiments;
var
N : Integer;
Fl : Boolean;
I, J, K : Integer;
procedure ReadInput;
begin
Readln(N);
end;
procedure WriteOutput;
begin
Assign(Output, 'output.txt');
Rewrite(Output);
J := N;
while J <> 0 do
begin
Inc(K);
J := J div 2;
end;
Writeln('The minimum number of experiments = ', K);
J := 1;
for K := 1 to K do
begin
Fl := False;
Write('Experiment #', K, ':');
for I := 1 to N do
if I div J mod 2 = 1 then
begin
if Fl then
Write(',');
Write(' ', I);
Fl := True;
end;
Writeln;
J := J * 2;
end;
Close(Output);
end;
begin
ReadInput;
WriteOutput;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
April '2000
Problem 66 Winning Strategy
N=(M+1)K => Second Pl. else First Pl.
N=(M+1)K is the kernel of the game
}
program
MatchesGame;
var
N, M, T : Integer;
procedure ReadInput;
begin
Write('Enter N ? ');
Readln(N);
Write('Enter m ? ');
Readln(M);
end;
procedure Play (Nn : Integer);
begin
while Nn > 0 do
begin
Writeln('Number of remaining matches = ', Nn);
if Nn mod (M + 1) = 0 then
begin
Write('How many matches do you take? ');
Readln(T);
if (T < 1) or (T > M) then begin Writeln('Error'); Halt; end;
Dec(Nn, T);
end
else
begin
Writeln('I take ', Nn mod (M + 1), ' match(es).');
Dec(Nn, Nn mod (M + 1));
end;
end;
end;
procedure Solve;
begin
if N mod (M + 1) <> 0 then
begin
Writeln('The first player has a winning strategy.');
Writeln('I take ', N mod (M + 1), ' match(es).');
Dec(N, N mod (M + 1));
end
else
Writeln('The second player has a winning strategy.');
Play(N);
Writeln('I won!');
end;
begin
ReadInput;
Solve;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2016-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Vcl.AppAnalytics.Consts;
interface
resourcestring
SPrivacyMessage = 'Privacy Notice:'#13#10#13#10 +
'This application anonymously tracks your usage and sends it to us for analysis. We use this analysis to make the software work better for you.'#13#10#13#10 +
'This tracking is completely anonymous. No personally identifying information is tracked, and nothing about your usage can be tracked back to you.'#13#10#13#10 +
'Thank you for helping us to improve this software.';
SOneAnalyticsComponentAllowed = 'Only one analytics component can be used per application';
SCBTHookFailed = 'CBT hook could not be installed. Error code: %d';
SInvalidApplicationID = 'Invalid Application ID';
implementation
end.
|
{@author Tarun Amarnath
@version 1
@description This program creates a virtual bank with a set number of customers (10)}
PROGRAM BankOriginal (input, output);
USES
CRT;
TYPE
Customer_Info = Record
Name : String;
Address : String;
PhoneNumber : String;
MaritalStatus : Char;
Gender : Char;
SocialSecurityNumber : String;
AnnualSalary : Real;
Password : Integer;
MoneyInAccount : Real;
LoanAmount : Real;
END;
VAR
G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten : Customer_Info;
G_Accounts : Text;
G_Flag : Integer;
G_Repeat_Yes_Or_No : String;
G_Name : String;
G_Choice : String;
G_NameOfTransfer : String;
G_DeleteOrNot : String;
G_MoneyInBank : Real;
G_ReserveRequirement : Real;
{@param Accounts - The text file with all information of the users
@param One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten - the customer records
@param MoneyInBank - The amount of money in the bank
@param ReserveRequirement - The reserve requirement of this bank
@return Filled-in variables }
PROCEDURE GetInformation (VAR Accounts : Text; VAR One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten : Customer_Info; VAR MoneyInBank, ReserveRequirement : Real);
BEGIN
Assign (Accounts, '/Users/tarunamarnath/Desktop/Pascal/TextFiles/Accounts.txt');
Reset (Accounts);
WITH One DO
BEGIN
Readln (Accounts, Name);
Readln (Accounts, Address);
Readln (Accounts, PhoneNumber);
Readln (Accounts, MaritalStatus);
Readln (Accounts, Gender);
Readln (Accounts, SocialSecurityNumber);
Readln (Accounts, AnnualSalary);
Readln (Accounts, Password);
Readln (Accounts, MoneyInAccount);
Readln (Accounts, LoanAmount);
END;
WITH Two DO
BEGIN
Readln (Accounts, Name);
Readln (Accounts, Address);
Readln (Accounts, PhoneNumber);
Readln (Accounts, MaritalStatus);
Readln (Accounts, Gender);
Readln (Accounts, SocialSecurityNumber);
Readln (Accounts, AnnualSalary);
Readln (Accounts, Password);
Readln (Accounts, MoneyInAccount);
Readln (Accounts, LoanAmount);
END;
WITH Three DO
BEGIN
Readln (Accounts, Name);
Readln (Accounts, Address);
Readln (Accounts, PhoneNumber);
Readln (Accounts, MaritalStatus);
Readln (Accounts, Gender);
Readln (Accounts, SocialSecurityNumber);
Readln (Accounts, AnnualSalary);
Readln (Accounts, Password);
Readln (Accounts, MoneyInAccount);
Readln (Accounts, LoanAmount);
END;
WITH Four DO
BEGIN
Readln (Accounts, Name);
Readln (Accounts, Address);
Readln (Accounts, PhoneNumber);
Readln (Accounts, MaritalStatus);
Readln (Accounts, Gender);
Readln (Accounts, SocialSecurityNumber);
Readln (Accounts, AnnualSalary);
Readln (Accounts, Password);
Readln (Accounts, MoneyInAccount);
Readln (Accounts, LoanAmount);
END;
WITH Five DO
BEGIN
Readln (Accounts, Name);
Readln (Accounts, Address);
Readln (Accounts, PhoneNumber);
Readln (Accounts, MaritalStatus);
Readln (Accounts, Gender);
Readln (Accounts, SocialSecurityNumber);
Readln (Accounts, AnnualSalary);
Readln (Accounts, Password);
Readln (Accounts, MoneyInAccount);
Readln (Accounts, LoanAmount);
END;
WITH Six DO
BEGIN
Readln (Accounts, Name);
Readln (Accounts, Address);
Readln (Accounts, PhoneNumber);
Readln (Accounts, MaritalStatus);
Readln (Accounts, Gender);
Readln (Accounts, SocialSecurityNumber);
Readln (Accounts, AnnualSalary);
Readln (Accounts, Password);
Readln (Accounts, MoneyInAccount);
Readln (Accounts, LoanAmount);
END;
WITH Seven DO
BEGIN
Readln (Accounts, Name);
Readln (Accounts, Address);
Readln (Accounts, PhoneNumber);
Readln (Accounts, MaritalStatus);
Readln (Accounts, Gender);
Readln (Accounts, SocialSecurityNumber);
Readln (Accounts, AnnualSalary);
Readln (Accounts, Password);
Readln (Accounts, MoneyInAccount);
Readln (Accounts, LoanAmount);
END;
WITH Eight DO
BEGIN
Readln (Accounts, Name);
Readln (Accounts, Address);
Readln (Accounts, PhoneNumber);
Readln (Accounts, MaritalStatus);
Readln (Accounts, Gender);
Readln (Accounts, SocialSecurityNumber);
Readln (Accounts, AnnualSalary);
Readln (Accounts, Password);
Readln (Accounts, MoneyInAccount);
Readln (Accounts, LoanAmount);
END;
WITH Nine DO
BEGIN
Readln (Accounts, Name);
Readln (Accounts, Address);
Readln (Accounts, PhoneNumber);
Readln (Accounts, MaritalStatus);
Readln (Accounts, Gender);
Readln (Accounts, SocialSecurityNumber);
Readln (Accounts, AnnualSalary);
Readln (Accounts, Password);
Readln (Accounts, MoneyInAccount);
Readln (Accounts, LoanAmount);
END;
WITH Ten DO
BEGIN
Readln (Accounts, Name);
Readln (Accounts, Address);
Readln (Accounts, PhoneNumber);
Readln (Accounts, MaritalStatus);
Readln (Accounts, Gender);
Readln (Accounts, SocialSecurityNumber);
Readln (Accounts, AnnualSalary);
Readln (Accounts, Password);
Readln (Accounts, MoneyInAccount);
Readln (Accounts, LoanAmount);
END;
Readln (Accounts, ReserveRequirement);
Readln (Accounts, MoneyInBank);
Close (Accounts);
END;
{@param Accounts - The text file with all information of the users
@param One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten - the customer records
@param ReserveRequirement - The reserve requirement of this bank
@return Changed text file}
PROCEDURE TransferInformation (VAR Accounts : Text; One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten : Customer_Info; ReserveRequirement : Real; MoneyInBank : Real);
BEGIN
Assign (Accounts, '/Users/tarunamarnath/Desktop/Pascal/TextFiles/Accounts.txt');
Rewrite (Accounts);
WITH One DO
BEGIN
Writeln (Accounts, Name);
Writeln (Accounts, Address);
Writeln (Accounts, PhoneNumber);
Writeln (Accounts, MaritalStatus);
Writeln (Accounts, Gender);
Writeln (Accounts, SocialSecurityNumber);
Writeln (Accounts, AnnualSalary:1:2);
Writeln (Accounts, Password);
Writeln (Accounts, MoneyInAccount:1:2);
Writeln (Accounts, LoanAmount:1:2);
END;
WITH Two DO
BEGIN
Writeln (Accounts, Name);
Writeln (Accounts, Address);
Writeln (Accounts, PhoneNumber);
Writeln (Accounts, MaritalStatus);
Writeln (Accounts, Gender);
Writeln (Accounts, SocialSecurityNumber);
Writeln (Accounts, AnnualSalary:1:2);
Writeln (Accounts, Password);
Writeln (Accounts, MoneyInAccount:1:2);
Writeln (Accounts, LoanAmount:1:2);
END;
WITH Three DO
BEGIN
Writeln (Accounts, Name);
Writeln (Accounts, Address);
Writeln (Accounts, PhoneNumber);
Writeln (Accounts, MaritalStatus);
Writeln (Accounts, Gender);
Writeln (Accounts, SocialSecurityNumber);
Writeln (Accounts, AnnualSalary:1:2);
Writeln (Accounts, Password);
Writeln (Accounts, MoneyInAccount:1:2);
Writeln (Accounts, LoanAmount:1:2);
END;
WITH Four DO
BEGIN
Writeln (Accounts, Name);
Writeln (Accounts, Address);
Writeln (Accounts, PhoneNumber);
Writeln (Accounts, MaritalStatus);
Writeln (Accounts, Gender);
Writeln (Accounts, SocialSecurityNumber);
Writeln (Accounts, AnnualSalary:1:2);
Writeln (Accounts, Password);
Writeln (Accounts, MoneyInAccount:1:2);
Writeln (Accounts, LoanAmount:1:2);
END;
WITH Five DO
BEGIN
Writeln (Accounts, Name);
Writeln (Accounts, Address);
Writeln (Accounts, PhoneNumber);
Writeln (Accounts, MaritalStatus);
Writeln (Accounts, Gender);
Writeln (Accounts, SocialSecurityNumber);
Writeln (Accounts, AnnualSalary:1:2);
Writeln (Accounts, Password);
Writeln (Accounts, MoneyInAccount:1:2);
Writeln (Accounts, LoanAmount:1:2);
END;
WITH Six DO
BEGIN
Writeln (Accounts, Name);
Writeln (Accounts, Address);
Writeln (Accounts, PhoneNumber);
Writeln (Accounts, MaritalStatus);
Writeln (Accounts, Gender);
Writeln (Accounts, SocialSecurityNumber);
Writeln (Accounts, AnnualSalary:1:2);
Writeln (Accounts, Password);
Writeln (Accounts, MoneyInAccount:1:2);
Writeln (Accounts, LoanAmount:1:2);
END;
WITH Seven DO
BEGIN
Writeln (Accounts, Name);
Writeln (Accounts, Address);
Writeln (Accounts, PhoneNumber);
Writeln (Accounts, MaritalStatus);
Writeln (Accounts, Gender);
Writeln (Accounts, SocialSecurityNumber);
Writeln (Accounts, AnnualSalary:1:2);
Writeln (Accounts, Password);
Writeln (Accounts, MoneyInAccount:1:2);
Writeln (Accounts, LoanAmount:1:2);
END;
WITH Eight DO
BEGIN
Writeln (Accounts, Name);
Writeln (Accounts, Address);
Writeln (Accounts, PhoneNumber);
Writeln (Accounts, MaritalStatus);
Writeln (Accounts, Gender);
Writeln (Accounts, SocialSecurityNumber);
Writeln (Accounts, AnnualSalary:1:2);
Writeln (Accounts, Password);
Writeln (Accounts, MoneyInAccount:1:2);
Writeln (Accounts, LoanAmount:1:2);
END;
WITH Nine DO
BEGIN
Writeln (Accounts, Name);
Writeln (Accounts, Address);
Writeln (Accounts, PhoneNumber);
Writeln (Accounts, MaritalStatus);
Writeln (Accounts, Gender);
Writeln (Accounts, SocialSecurityNumber);
Writeln (Accounts, AnnualSalary:1:2);
Writeln (Accounts, Password);
Writeln (Accounts, MoneyInAccount:1:2);
Writeln (Accounts, LoanAmount:1:2);
END;
WITH Ten DO
BEGIN
Writeln (Accounts, Name);
Writeln (Accounts, Address);
Writeln (Accounts, PhoneNumber);
Writeln (Accounts, MaritalStatus);
Writeln (Accounts, Gender);
Writeln (Accounts, SocialSecurityNumber);
Writeln (Accounts, AnnualSalary:1:2);
Writeln (Accounts, Password);
Writeln (Accounts, MoneyInAccount:1:2);
Writeln (Accounts, LoanAmount:1:2);
END;
Writeln (Accounts, ReserveRequirement:1:2);
Writeln (Accounts, MoneyInBank:1:2);
Close (Accounts);
END;
{@param Customer - An empty customer record
@return The filled-in information for that new customer}
PROCEDURE CreateAnAccount (VAR Customer : Customer_Info);
BEGIN
Writeln ('Hello! To create an account, please enter the following information: ');
Writeln;
Writeln;
Writeln ('Enter your name (this will also be your username): ');
Write (' ');
Readln (Customer.Name);
Writeln;
Writeln;
Writeln ('Enter your address: ');
Write (' ');
Readln (Customer.Address);
Writeln;
Writeln;
Writeln ('Enter your phone number: ');
Write (' ');
Readln (Customer.PhoneNumber);
Writeln;
Writeln;
Writeln ('Enter your marital status (M or N for married or unmarried): ');
Write (' ');
Readln (Customer.MaritalStatus);
Writeln;
Writeln;
Writeln ('Enter your gender (M or F): ');
Write (' ');
Readln (Customer.Gender);
Writeln;
Writeln;
Writeln ('Enter your social security number: ');
Write (' ');
Readln (Customer.SocialSecurityNumber);
Writeln;
Writeln;
Writeln ('Enter your annual salary: ');
Write (' ');
Readln (Customer.AnnualSalary);
Writeln;
Writeln;
Writeln ('Enter a pin for your account: ');
Write (' ');
Readln (Customer.Password);
Writeln;
Writeln;
Writeln ('How much money would you like to deposit right now? ');
Write (' ');
Readln (Customer.MoneyInAccount);
Writeln;
Writeln;
Writeln ('Thank you for creating an account in the Challenger Bank, ', Customer.Name, '!');
Delay (1500);
END;
{param One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten - the customer records
@return A created account for the appropriate user}
PROCEDURE OptionCreateAnAccount (VAR One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten : Customer_Info);
BEGIN
IF One.Name = '' THEN
CreateAnAccount (One)
ELSE IF Two.Name = '' THEN
CreateAnAccount (Two)
ELSE IF Three.Name = '' THEN
CreateAnAccount (Three)
ELSE IF Four.Name = '' THEN
CreateAnAccount (Four)
ELSE IF Five.Name = '' THEN
CreateAnAccount (Five)
ELSE IF Six.Name = '' THEN
CreateAnAccount (Six)
ELSE IF Seven.Name = '' THEN
CreateAnAccount (Seven)
ELSE IF Eight.Name = '' THEN
CreateAnAccount (Eight)
ELSE IF Nine.Name = '' THEN
CreateAnAccount (Nine)
ELSE IF Ten.Name = '' THEN
CreateAnAccount (Ten)
ELSE IF ((One.Name <> '')
AND (Two.Name <> '')
AND (Three.Name <> '')
AND (Four.Name <> '')
AND (Five.Name <> '')
AND (Six.Name <> '')
AND (Seven.Name <> '')
AND (Eight.Name <> '')
AND (Nine.Name <> '')
AND (Ten.Name <> '')) THEN
BEGIN
Writeln ('I''m afraid we have reached a limit to the number of customers we can have.');
Writeln ('Please check back in later to see if we have space!');
END;
END;
{@param The users with all of their information
@return A signed-in user}
PROCEDURE SignIn (VAR CustomerName : String; One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten : Customer_Info);
VAR
Name : String;
Password : Integer;
BEGIN
GOTOXY (20, 18);
Write ('Enter your username: ');
Readln (Name);
GOTOXY (20, 19);
Write ('Enter your pin: ');
Readln (Password);
IF (Name = One.Name) AND (Password = One.Password) THEN
CustomerName := One.Name;
IF (Name = Two.Name) AND (Password = Two.Password) THEN
CustomerName := Two.Name;
IF (Name = Three.Name) AND (Password = Three.Password) THEN
CustomerName := Three.Name;
IF (Name = Four.Name) AND (Password = Four.Password) THEN
CustomerName := Four.Name;
IF (Name = Five.Name) AND (Password = Five.Password) THEN
CustomerName := Five.Name;
IF (Name = Six.Name) AND (Password = Six.Password) THEN
CustomerName := Six.Name;
IF (Name = Seven.Name) AND (Password = Seven.Password) THEN
CustomerName := Seven.Name;
IF (Name = Eight.Name) AND (Password = Eight.Password) THEN
CustomerName := Eight.Name;
IF (Name = Nine.Name) AND (Password = Nine.Password) THEN
CustomerName := Nine.Name;
IF (Name = Ten.Name) AND (Password = Ten.Password) THEN
CustomerName := Ten.Name;
IF (Name = 'Bank') AND (Password = 00) THEN
BEGIN
CustomerName := 'Bank';
END;
IF ((Name <> One.Name) OR (Password <> One.Password))
AND ((Name <> Two.Name) OR (Password <> Two.Password))
AND ((Name <> Three.Name) OR (Password <> Three.Password))
AND ((Name <> Four.Name) OR (Password <> Four.Password))
AND ((Name <> Five.Name) OR (Password <> Five.Password))
AND ((Name <> Six.Name) OR (Password <> Six.Password))
AND ((Name <> Seven.Name) OR (Password <> Seven.Password))
AND ((Name <> Eight.Name) OR (Password <> Eight.Password))
AND ((Name <> Nine.Name) OR (Password <> Nine.Password))
AND ((Name <> Ten.Name) OR (Password <> Ten.Password))
AND ((Name <> 'Bank') OR (Password <> 00)) THEN
BEGIN
Writeln;
Writeln;
Writeln;
Writeln;
Writeln;
TextColor (LightRed);
Writeln ('Sorry, you have not entered a proper username and password. Please try again.');
TextColor (LightGreen);
Delay (2000);
CLRSCR;
SignIn (G_Name, G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten);
END;
END;
{@param Name - The name of the customer
@param One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten - The customer records
@param MoneyInBank - The amount of money in the bank
@return User with money added to his account; bank with more money to give out on loan}
PROCEDURE DepositMoney (Name : String; VAR One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten : Customer_Info; VAR MoneyInBank : Real);
VAR
AmountOfMoney : Real;
BEGIN
Writeln ('How much money would you like to deposit?');
Readln (AmountOfMoney);
Writeln;
IF (Name = One.Name) THEN
BEGIN
One.MoneyInAccount := One.MoneyInAccount + AmountOfMoney;
Writeln ('You have successfully deposited ', AmountOfMoney:1:2, '!');
Delay (500);
Writeln ('The balance in your account is ', One.MoneyInAccount:1:2, '.');
Delay (2000);
MoneyInBank := MoneyInBank + AmountOfMoney;
END;
IF (Name = Two.Name) THEN
BEGIN
Two.MoneyInAccount := Two.MoneyInAccount + AmountOfMoney;
Writeln ('You have successfully deposited ', AmountOfMoney:1:2, '!');
Delay (500);
Writeln ('The balance in your account is ', Two.MoneyInAccount:1:2, '.');
Delay (2000);
MoneyInBank := MoneyInBank + AmountOfMoney;
END;
IF (Name = Three.Name) THEN
BEGIN
Three.MoneyInAccount := Three.MoneyInAccount + AmountOfMoney;
Writeln ('You have successfully deposited ', AmountOfMoney:1:2, '!');
Delay (500);
Writeln ('The balance in your account is ', Three.MoneyInAccount:1:2, '.');
Delay (2000);
MoneyInBank := MoneyInBank + AmountOfMoney;
END;
IF (Name = Four.Name) THEN
BEGIN
Four.MoneyInAccount := Four.MoneyInAccount + AmountOfMoney;
Writeln ('You have successfully deposited ', AmountOfMoney:1:2, '!');
Delay (500);
Writeln ('The balance in your account is ', Four.MoneyInAccount:1:2, '.');
Delay (2000);
MoneyInBank := MoneyInBank + AmountOfMoney;
END;
IF (Name = Five.Name) THEN
BEGIN
Five.MoneyInAccount := Five.MoneyInAccount + AmountOfMoney;
Writeln ('You have successfully deposited ', AmountOfMoney:1:2, '!');
Delay (500);
Writeln ('The balance in your account is ', Five.MoneyInAccount:1:2, '.');
Delay (2000);
MoneyInBank := MoneyInBank + AmountOfMoney;
END;
IF (Name = Six.Name) THEN
BEGIN
Six.MoneyInAccount := Six.MoneyInAccount + AmountOfMoney;
Writeln ('You have successfully deposited ', AmountOfMoney:1:2, '!');
Delay (500);
Writeln ('The balance in your account is ', Six.MoneyInAccount:1:2, '.');
Delay (2000);
MoneyInBank := MoneyInBank + AmountOfMoney;
END;
IF (Name = Seven.Name) THEN
BEGIN
Seven.MoneyInAccount := Seven.MoneyInAccount + AmountOfMoney;
Writeln ('You have successfully deposited ', AmountOfMoney:1:2, '!');
Delay (500);
Writeln ('The balance in your account is ', Seven.MoneyInAccount:1:2, '.');
Delay (2000);
MoneyInBank := MoneyInBank + AmountOfMoney;
END;
IF (Name = Eight.Name) THEN
BEGIN
Eight.MoneyInAccount := Eight.MoneyInAccount + AmountOfMoney;
Writeln ('You have successfully deposited ', AmountOfMoney:1:2, '!');
Delay (500);
Writeln ('The balance in your account is ', Eight.MoneyInAccount:1:2, '.');
Delay (2000);
MoneyInBank := MoneyInBank + AmountOfMoney;
END;
IF (Name = Nine.Name) THEN
BEGIN
Nine.MoneyInAccount := Nine.MoneyInAccount + AmountOfMoney;
Writeln ('You have successfully deposited ', AmountOfMoney:1:2, '!');
Delay (500);
Writeln ('The balance in your account is ', Nine.MoneyInAccount:1:2, '.');
Delay (2000);
MoneyInBank := MoneyInBank + AmountOfMoney;
END;
IF (Name = Ten.Name) THEN
BEGIN
Ten.MoneyInAccount := Ten.MoneyInAccount + AmountOfMoney;
Writeln ('You have successfully deposited ', AmountOfMoney:1:2, '!');
Delay (500);
Writeln ('The balance in your account is ', Ten.MoneyInAccount:1:2, '.');
Delay (2000);
MoneyInBank := MoneyInBank + AmountOfMoney;
END;
END;
{@param Name - The name of the siged-in person
@param One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten - The customer records
@param MoneyInBank - The amount of money in the bank
@return A changed amount of money in both the user's account as well as in the bank}
PROCEDURE WithdrawMoney (Name : String; VAR One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten : Customer_Info; VAR MoneyInBank : Real);
VAR
AmountOfMoney : Real;
BEGIN
Writeln ('How much money would you like to withdraw?');
Readln (AmountOfMoney);
Writeln;
IF ((Name = One.Name) AND (One.MoneyInAccount - AmountOfMoney >= 0)) THEN
BEGIN
One.MoneyInAccount := One.MoneyInAccount - AmountOfMoney;
Writeln ('You have successfully withdrawn ', AmountOfMoney:1:2, '!');
Writeln ('The balance in your account is ', One.MoneyInAccount:1:2, '.');
MoneyInBank := MoneyInBank - AmountOfMoney;
END
ELSE IF ((Name = Two.Name) AND (Two.MoneyInAccount - AmountOfMoney >= 0)) THEN
BEGIN
Two.MoneyInAccount := Two.MoneyInAccount - AmountOfMoney;
Writeln ('You have successfully withdrawn ', AmountOfMoney:1:2, '!');
Writeln ('The balance in your account is ', Two.MoneyInAccount:1:2, '.');
MoneyInBank := MoneyInBank - AmountOfMoney;
END
ELSE IF ((Name = Three.Name) AND (Three.MoneyInAccount - AmountOfMoney >= 0)) THEN
BEGIN
Three.MoneyInAccount := Three.MoneyInAccount - AmountOfMoney;
Writeln ('You have successfully withdrawn ', AmountOfMoney:1:2, '!');
Writeln ('The balance in your account is ', Three.MoneyInAccount:1:2, '.');
MoneyInBank := MoneyInBank - AmountOfMoney;
END
ELSE IF ((Name = Four.Name) AND (Four.MoneyInAccount - AmountOfMoney >= 0)) THEN
BEGIN
Four.MoneyInAccount := Four.MoneyInAccount - AmountOfMoney;
Writeln ('You have successfully withdrawn ', AmountOfMoney:1:2, '!');
Writeln ('The balance in your account is ', Four.MoneyInAccount:1:2, '.');
MoneyInBank := MoneyInBank - AmountOfMoney;
END
ELSE IF ((Name = Five.Name) AND (Five.MoneyInAccount - AmountOfMoney >= 0)) THEN
BEGIN
Five.MoneyInAccount := Five.MoneyInAccount - AmountOfMoney;
Writeln ('You have successfully withdrawn ', AmountOfMoney:1:2, '!');
Writeln ('The balance in your account is ', Five.MoneyInAccount:1:2, '.');
MoneyInBank := MoneyInBank - AmountOfMoney;
END
ELSE IF ((Name = Six.Name) AND (Six.MoneyInAccount - AmountOfMoney >= 0)) THEN
BEGIN
Six.MoneyInAccount := Six.MoneyInAccount - AmountOfMoney;
Writeln ('You have successfully withdrawn ', AmountOfMoney:1:2, '!');
Writeln ('The balance in your account is ', Six.MoneyInAccount:1:2, '.');
MoneyInBank := MoneyInBank - AmountOfMoney;
END
ELSE IF ((Name = Seven.Name) AND (Seven.MoneyInAccount - AmountOfMoney >= 0)) THEN
BEGIN
Seven.MoneyInAccount := Seven.MoneyInAccount - AmountOfMoney;
Writeln ('You have successfully withdrawn ', AmountOfMoney:1:2, '!');
Writeln ('The balance in your account is ', Seven.MoneyInAccount:1:2, '.');
MoneyInBank := MoneyInBank - AmountOfMoney;
END
ELSE IF ((Name = Eight.Name) AND (Eight.MoneyInAccount - AmountOfMoney >= 0)) THEN
BEGIN
Eight.MoneyInAccount := Eight.MoneyInAccount - AmountOfMoney;
Writeln ('You have successfully withdrawn ', AmountOfMoney:1:2, '!');
Writeln ('The balance in your account is ', Eight.MoneyInAccount:1:2, '.');
MoneyInBank := MoneyInBank - AmountOfMoney;
END
ELSE IF ((Name = Nine.Name) AND (Nine.MoneyInAccount - AmountOfMoney >= 0)) THEN
BEGIN
Nine.MoneyInAccount := Nine.MoneyInAccount - AmountOfMoney;
Writeln ('You have successfully withdrawn ', AmountOfMoney:1:2, '!');
Writeln ('The balance in your account is ', Nine.MoneyInAccount:1:2, '.');
MoneyInBank := MoneyInBank - AmountOfMoney;
END
ELSE IF ((Name = Ten.Name) AND (Ten.MoneyInAccount - AmountOfMoney >= 0)) THEN
BEGIN
Ten.MoneyInAccount := Ten.MoneyInAccount - AmountOfMoney;
Writeln ('You have successfully withdrawn ', AmountOfMoney:1:2, '!');
Writeln ('The balance in your account is ', Ten.MoneyInAccount:1:2, '.');
MoneyInBank := MoneyInBank - AmountOfMoney;
END
ELSE
Writeln ('You do not have enough money to withdraw. If you would like, you may take a loan.');
END;
{@param Name - The name of the signed-in person
@param One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten - The customer records
@param ReserveRequriement - The reserve requirement of this bank
@param MoneyInBank - the amount of money in the bank
@return A person with a loan. The amount of money in the bank's vaults will decrease, but the amount of money with the user will increase}
PROCEDURE Loan (Name : String; VAR One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten : Customer_Info; ReserveRequirement : Real; VAR MoneyInBank : Real);
VAR
AmountOfMoney : Real;
BEGIN
Writeln ('How much money would you like to take on loan?');
Readln (AmountOfMoney);
Writeln;
IF ((Name = One.Name) AND (MoneyInBank - AmountOfMoney >= MoneyInBank * ReserveRequirement)) THEN
BEGIN
One.LoanAmount := One.LoanAmount + AmountOfMoney;
One.MoneyInAccount := One.MoneyInAccount + AmountOfMoney;
MoneyInBank := MoneyInBank - AmountOfMoney;
Writeln ('You have successfully taken a loan of ', AmountOfMoney:1:2, '!');
Delay (500);
Writeln ('The balance in your account is ', One.MoneyInAccount:1:2, '.');
Delay (500);
Writeln ('The total amount of money you have on loan is ', One.LoanAmount:1:2, '.');
Delay (2000);
END
ELSE IF ((Name = Two.Name) AND (MoneyInBank - AmountOfMoney >= MoneyInBank * ReserveRequirement)) THEN
BEGIN
Two.LoanAmount := Two.LoanAmount + AmountOfMoney;
Two.MoneyInAccount := Two.MoneyInAccount + AmountOfMoney;
MoneyInBank := MoneyInBank - AmountOfMoney;
Writeln ('You have successfully taken a loan of ', AmountOfMoney:1:2, '!');
Delay (500);
Writeln ('The balance in your account is ', Two.MoneyInAccount:1:2, '.');
Delay (500);
Writeln ('The total amount of money you have on loan is ', Two.LoanAmount:1:2, '.');
Delay (2000);
END
ELSE IF ((Name = Three.Name) AND (MoneyInBank - AmountOfMoney >= MoneyInBank * ReserveRequirement)) THEN
BEGIN
Three.LoanAmount := Three.LoanAmount + AmountOfMoney;
Three.MoneyInAccount := Three.MoneyInAccount + AmountOfMoney;
MoneyInBank := MoneyInBank - AmountOfMoney;
Writeln ('You have successfully taken a loan of ', AmountOfMoney:1:2, '!');
Delay (500);
Writeln ('The balance in your account is ', Three.MoneyInAccount:1:2, '.');
Delay (500);
Writeln ('The total amount of money you have on loan is ', Three.LoanAmount:1:2, '.');
Delay (2000);
END
ELSE IF ((Name = Four.Name) AND (MoneyInBank - AmountOfMoney >= MoneyInBank * ReserveRequirement)) THEN
BEGIN
Four.LoanAmount := Four.LoanAmount + AmountOfMoney;
Four.MoneyInAccount := Four.MoneyInAccount + AmountOfMoney;
MoneyInBank := MoneyInBank - AmountOfMoney;
Writeln ('You have successfully taken a loan of ', AmountOfMoney:1:2, '!');
Delay (500);
Writeln ('The balance in your account is ', Four.MoneyInAccount:1:2, '.');
Delay (500);
Writeln ('The total amount of money you have on loan is ', Four.LoanAmount:1:2, '.');
Delay (2000);
END
ELSE IF ((Name = Five.Name) AND (MoneyInBank - AmountOfMoney >= MoneyInBank * ReserveRequirement)) THEN
BEGIN
Five.LoanAmount := Five.LoanAmount + AmountOfMoney;
Five.MoneyInAccount := Five.MoneyInAccount + AmountOfMoney;
MoneyInBank := MoneyInBank - AmountOfMoney;
Writeln ('You have successfully taken a loan of ', AmountOfMoney:1:2, '!');
Delay (500);
Writeln ('The balance in your account is ', Five.MoneyInAccount:1:2, '.');
Delay (500);
Writeln ('The total amount of money you have on loan is ', Five.LoanAmount:1:2, '.');
Delay (2000);
END
ELSE IF ((Name = Six.Name) AND (MoneyInBank - AmountOfMoney >= MoneyInBank * ReserveRequirement)) THEN
BEGIN
Six.LoanAmount := Six.LoanAmount + AmountOfMoney;
Six.MoneyInAccount := Six.MoneyInAccount + AmountOfMoney;
MoneyInBank := MoneyInBank - AmountOfMoney;
Writeln ('You have successfully taken a loan of ', AmountOfMoney:1:2, '!');
Delay (500);
Writeln ('The balance in your account is ', Six.MoneyInAccount:1:2, '.');
Delay (500);
Writeln ('The total amount of money you have on loan is ', Six.LoanAmount:1:2, '.');
Delay (2000);
END
ELSE IF ((Name = Seven.Name) AND (MoneyInBank - AmountOfMoney >= MoneyInBank * ReserveRequirement)) THEN
BEGIN
Seven.LoanAmount := Seven.LoanAmount + AmountOfMoney;
Seven.MoneyInAccount := Seven.MoneyInAccount + AmountOfMoney;
MoneyInBank := MoneyInBank - AmountOfMoney;
Writeln ('You have successfully taken a loan of ', AmountOfMoney:1:2, '!');
Delay (500);
Writeln ('The balance in your account is ', Seven.MoneyInAccount:1:2, '.');
Delay (500);
Writeln ('The total amount of money you have on loan is ', Seven.LoanAmount:1:2, '.');
Delay (2000);
END
ELSE IF ((Name = Eight.Name) AND (MoneyInBank - AmountOfMoney >= MoneyInBank * ReserveRequirement)) THEN
BEGIN
Eight.LoanAmount := Eight.LoanAmount + AmountOfMoney;
Eight.MoneyInAccount := Eight.MoneyInAccount + AmountOfMoney;
MoneyInBank := MoneyInBank - AmountOfMoney;
Writeln ('You have successfully taken a loan of ', AmountOfMoney:1:2, '!');
Delay (500);
Writeln ('The balance in your account is ', Eight.MoneyInAccount:1:2, '.');
Delay (500);
Writeln ('The total amount of money you have on loan is ', Eight.LoanAmount:1:2, '.');
Delay (2000);
END
ELSE IF ((Name = Nine.Name) AND (MoneyInBank - AmountOfMoney >= MoneyInBank * ReserveRequirement)) THEN
BEGIN
Nine.LoanAmount := Nine.LoanAmount + AmountOfMoney;
Nine.MoneyInAccount := Nine.MoneyInAccount + AmountOfMoney;
MoneyInBank := MoneyInBank - AmountOfMoney;
Writeln ('You have successfully taken a loan of ', AmountOfMoney:1:2, '!');
Delay (500);
Writeln ('The balance in your account is ', Nine.MoneyInAccount:1:2, '.');
Delay (500);
Writeln ('The total amount of money you have on loan is ', Nine.LoanAmount:1:2, '.');
Delay (2000);
END
ELSE IF ((Name = Ten.Name) AND (MoneyInBank - AmountOfMoney >= MoneyInBank * ReserveRequirement)) THEN
BEGIN
Ten.LoanAmount := Ten.LoanAmount + AmountOfMoney;
Ten.MoneyInAccount := Ten.MoneyInAccount + AmountOfMoney;
MoneyInBank := MoneyInBank - AmountOfMoney;
Writeln ('You have successfully taken a loan of ', AmountOfMoney:1:2, '!');
Delay (500);
Writeln ('The balance in your account is ', Ten.MoneyInAccount:1:2, '.');
Delay (500);
Writeln ('The total amount of money you have on loan is ', Ten.LoanAmount:1:2, '.');
Delay (2000);
END
ELSE IF (MoneyInBank - AmountOfMoney < MoneyInBank * ReserveRequirement) THEN
BEGIN
Writeln ('I''m sorry, we don''t have enough money in our vaults to give you a loan.');
Delay (1000);
Writeln ('Please check back in later.');
Delay (2000);
END;
END;
{@param Customer - A customer record
@return A customer with his or her loan paid back; which customer will be decided in OptionPayBackLoan}
PROCEDURE PayBackLoan (VAR Customer : Customer_Info; VAR MoneyInBank : Real);
VAR
AmountOfMoney : Real;
BEGIN
Writeln ('How much money would you like to pay back from your loan of ', Customer.LoanAmount:1:2, '?');
Readln (AmountOfMoney);
Writeln;
Delay (750);
IF (Customer.MoneyInAccount - AmountOfMoney >= 0) THEN
BEGIN
Customer.LoanAmount := Customer.LoanAmount - AmountOfMoney;
Customer.MoneyInAccount := Customer.MoneyInAccount - AmountOfMoney;
MoneyInBank := MoneyInBank + AmountOfMoney;
Writeln ('You successfully paid back a loan of ', AmountOfMoney:1:2, '!');
Delay (500);
Writeln ('The balance of your loan is ', Customer.LoanAmount:1:2, '.');
Delay (500);
Writeln ('The balance of money in your account is ', Customer.MoneyInAccount:1:2, '.');
Delay (300);
END
ELSE
BEGIN
Writeln ('I''m sorry, you don''t have enough money to pay the chosen amount back ');
Writeln (' or you don''t have a loan to pay back.');
Writeln;
Delay (1000);
Writeln ('If you don''t have the money, ');
Writeln (' please deposit money and then pay back the loan.');
Delay (3000);
END;
END;
{@param Name - The name of the customer
@param One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten - The customer records
@param MoneyInBank - The amount of money in the bank
@return The loan paid back to the actual customer}
PROCEDURE OptionPayBackLoan (Name : String; VAR One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten : Customer_Info; VAR MoneyInBank : Real);
BEGIN
IF (Name = One.Name) THEN
PayBackLoan (One, MoneyInBank)
ELSE IF (Name = Two.Name) THEN
PayBackLoan (Two, MoneyInBank)
ELSE IF (Name = Three.Name) THEN
PayBackLoan (Three, MoneyInBank)
ELSE IF (Name = Four.Name) THEN
PayBackLoan (Four, MoneyInBank)
ELSE IF (Name = Five.Name) THEN
PayBackLoan (Five, MoneyInBank)
ELSE IF (Name = Six.Name) THEN
PayBackLoan (Six, MoneyInBank)
ELSE IF (Name = Seven.Name) THEN
PayBackLoan (Seven, MoneyInBank)
ELSE IF (Name = Eight.Name) THEN
PayBackLoan (Eight, MoneyInBank)
ELSE IF (Name = Nine.Name) THEN
PayBackLoan (Nine, MoneyInBank)
ELSE IF (Name = Ten.Name) THEN
PayBackLoan (Ten, MoneyInBank);
END;
{@param Name - The name of the customer
@param One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten - The customer records
@return Prints out all the customer information}
PROCEDURE PrintInformation (Name : String; One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten : Customer_Info);
BEGIN
IF (Name = One.Name) THEN
BEGIN
WITH One DO
BEGIN
Writeln ('Name: ', Name);
Delay (500);
Writeln ('Address: ', Address);
Delay (500);
Writeln ('Phone number: ', PhoneNumber);
Delay (500);
Writeln ('MaritalStatus: ', MaritalStatus);
Delay (500);
Writeln ('Gender: ', Gender);
Delay (500);
Writeln ('Social security number: ', SocialSecurityNumber);
Delay (500);
Writeln ('Annual salary: ', AnnualSalary:1:2);
Delay (500);
Writeln ('Pin: ', Password);
Delay (500);
Writeln ('Money in account: ', MoneyInAccount:1:2);
Delay (500);
Writeln ('Money on loan: ', LoanAmount:1:2);
Delay (500);
END;
END;
IF (Name = Two.Name) THEN
BEGIN
WITH Two DO
BEGIN
Writeln ('Name: ', Name);
Delay (500);
Writeln ('Address: ', Address);
Delay (500);
Writeln ('Phone number: ', PhoneNumber);
Delay (500);
Writeln ('MaritalStatus: ', MaritalStatus);
Delay (500);
Writeln ('Gender: ', Gender);
Delay (500);
Writeln ('Social security number: ', SocialSecurityNumber);
Delay (500);
Writeln ('Annual salary: ', AnnualSalary:1:2);
Delay (500);
Writeln ('Pin: ', Password);
Delay (500);
Writeln ('Money in account: ', MoneyInAccount:1:2);
Delay (500);
Writeln ('Money on loan: ', LoanAmount:1:2);
Delay (500);
END;
END;
IF (Name = Three.Name) THEN
BEGIN
WITH Three DO
BEGIN
Writeln ('Name: ', Name);
Delay (500);
Writeln ('Address: ', Address);
Delay (500);
Writeln ('Phone number: ', PhoneNumber);
Delay (500);
Writeln ('MaritalStatus: ', MaritalStatus);
Delay (500);
Writeln ('Gender: ', Gender);
Delay (500);
Writeln ('Social security number: ', SocialSecurityNumber);
Delay (500);
Writeln ('Annual salary: ', AnnualSalary:1:2);
Delay (500);
Writeln ('Pin: ', Password);
Delay (500);
Writeln ('Money in account: ', MoneyInAccount:1:2);
Delay (500);
Writeln ('Money on loan: ', LoanAmount:1:2);
Delay (500);
END;
END;
IF (Name = Four.Name) THEN
BEGIN
WITH Four DO
BEGIN
Writeln ('Name: ', Name);
Delay (500);
Writeln ('Address: ', Address);
Delay (500);
Writeln ('Phone number: ', PhoneNumber);
Delay (500);
Writeln ('MaritalStatus: ', MaritalStatus);
Delay (500);
Writeln ('Gender: ', Gender);
Delay (500);
Writeln ('Social security number: ', SocialSecurityNumber);
Delay (500);
Writeln ('Annual salary: ', AnnualSalary:1:2);
Delay (500);
Writeln ('Pin: ', Password);
Delay (500);
Writeln ('Money in account: ', MoneyInAccount:1:2);
Delay (500);
Writeln ('Money on loan: ', LoanAmount:1:2);
Delay (500);
END;
END;
IF (Name = Five.Name) THEN
BEGIN
WITH Five DO
BEGIN
Writeln ('Name: ', Name);
Delay (500);
Writeln ('Address: ', Address);
Delay (500);
Writeln ('Phone number: ', PhoneNumber);
Delay (500);
Writeln ('MaritalStatus: ', MaritalStatus);
Delay (500);
Writeln ('Gender: ', Gender);
Delay (500);
Writeln ('Social security number: ', SocialSecurityNumber);
Delay (500);
Writeln ('Annual salary: ', AnnualSalary:1:2);
Delay (500);
Writeln ('Pin: ', Password);
Delay (500);
Writeln ('Money in account: ', MoneyInAccount:1:2);
Delay (500);
Writeln ('Money on loan: ', LoanAmount:1:2);
Delay (500);
END;
END;
IF (Name = Six.Name) THEN
BEGIN
WITH Six DO
BEGIN
Writeln ('Name: ', Name);
Delay (500);
Writeln ('Address: ', Address);
Delay (500);
Writeln ('Phone number: ', PhoneNumber);
Delay (500);
Writeln ('MaritalStatus: ', MaritalStatus);
Delay (500);
Writeln ('Gender: ', Gender);
Delay (500);
Writeln ('Social security number: ', SocialSecurityNumber);
Delay (500);
Writeln ('Annual salary: ', AnnualSalary:1:2);
Delay (500);
Writeln ('Pin: ', Password);
Delay (500);
Writeln ('Money in account: ', MoneyInAccount:1:2);
Delay (500);
Writeln ('Money on loan: ', LoanAmount:1:2);
Delay (500);
END;
END;
IF (Name = Seven.Name) THEN
BEGIN
WITH Seven DO
BEGIN
Writeln ('Name: ', Name);
Delay (500);
Writeln ('Address: ', Address);
Delay (500);
Writeln ('Phone number: ', PhoneNumber);
Delay (500);
Writeln ('MaritalStatus: ', MaritalStatus);
Delay (500);
Writeln ('Gender: ', Gender);
Delay (500);
Writeln ('Social security number: ', SocialSecurityNumber);
Delay (500);
Writeln ('Annual salary: ', AnnualSalary:1:2);
Delay (500);
Writeln ('Pin: ', Password);
Delay (500);
Writeln ('Money in account: ', MoneyInAccount:1:2);
Delay (500);
Writeln ('Money on loan: ', LoanAmount:1:2);
Delay (500);
END;
END;
IF (Name = Eight.Name) THEN
BEGIN
WITH Eight DO
BEGIN
Writeln ('Name: ', Name);
Delay (500);
Writeln ('Address: ', Address);
Delay (500);
Writeln ('Phone number: ', PhoneNumber);
Delay (500);
Writeln ('MaritalStatus: ', MaritalStatus);
Delay (500);
Writeln ('Gender: ', Gender);
Delay (500);
Writeln ('Social security number: ', SocialSecurityNumber);
Delay (500);
Writeln ('Annual salary: ', AnnualSalary:1:2);
Delay (500);
Writeln ('Pin: ', Password);
Delay (500);
Writeln ('Money in account: ', MoneyInAccount:1:2);
Delay (500);
Writeln ('Money on loan: ', LoanAmount:1:2);
Delay (500);
END;
END;
IF (Name = Nine.Name) THEN
BEGIN
WITH Nine DO
BEGIN
Writeln ('Name: ', Name);
Delay (500);
Writeln ('Address: ', Address);
Delay (500);
Writeln ('Phone number: ', PhoneNumber);
Delay (500);
Writeln ('MaritalStatus: ', MaritalStatus);
Delay (500);
Writeln ('Gender: ', Gender);
Delay (500);
Writeln ('Social security number: ', SocialSecurityNumber);
Delay (500);
Writeln ('Annual salary: ', AnnualSalary:1:2);
Delay (500);
Writeln ('Pin: ', Password);
Delay (500);
Writeln ('Money in account: ', MoneyInAccount:1:2);
Delay (500);
Writeln ('Money on loan: ', LoanAmount:1:2);
Delay (500);
END;
END;
IF (Name = Ten.Name) THEN
BEGIN
WITH Ten DO
BEGIN
Writeln ('Name: ', Name);
Delay (500);
Writeln ('Address: ', Address);
Delay (500);
Writeln ('Phone number: ', PhoneNumber);
Delay (500);
Writeln ('MaritalStatus: ', MaritalStatus);
Delay (500);
Writeln ('Gender: ', Gender);
Delay (500);
Writeln ('Social security number: ', SocialSecurityNumber);
Delay (500);
Writeln ('Annual salary: ', AnnualSalary:1:2);
Delay (500);
Writeln ('Pin: ', Password);
Delay (500);
Writeln ('Money in account: ', MoneyInAccount:1:2);
Delay (500);
Writeln ('Money on loan: ', LoanAmount:1:2);
Delay (500);
END;
END;
END;
{@param Name - The name of the user
@param NameOfTransfer - The name of the person whose account the user is transferring the money to
@param One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten - The customer records
@param TransferringTo - The record of the person to whom the money is being transferred
@return The money deducted from the original account and added to the other account}
PROCEDURE PayMoneyToAnotherPerson (Name, NameOfTransfer : String; VAR One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, TransferringTo : Customer_Info);
VAR
AmountOfMoney : Real;
BEGIN
Writeln ('How much money would you like to transfer to ', NameOfTransfer, '''s account?');
Readln (AmountOfMoney);
Writeln;
IF ((Name = One.Name) AND (One.MoneyInAccount - AmountOfMoney >= 0)) THEN
BEGIN
One.MoneyInAccount := One.MoneyInAccount - AmountOfMoney;
TransferringTo.MoneyInAccount := TransferringTo.MoneyInAccount + AmountOfMoney;
Writeln ('You have successfully transferred ', AmountOfMoney:1:2, ' to ', NameOfTransfer, '''s account!');
Writeln ('The balance in your account is ', One.MoneyInAccount:1:2, '.');
END
ELSE IF ((Name = Two.Name) AND (Two.MoneyInAccount - AmountOfMoney >= 0)) THEN
BEGIN
Two.MoneyInAccount := Two.MoneyInAccount - AmountOfMoney;
TransferringTo.MoneyInAccount := TransferringTo.MoneyInAccount + AmountOfMoney;
Writeln ('You have successfully transferred ', AmountOfMoney:1:2, ' to ', NameOfTransfer, '''s account!');
Writeln ('The balance in your account is ', Two.MoneyInAccount:1:2, '.');
END
ELSE IF ((Name = Three.Name) AND (Three.MoneyInAccount - AmountOfMoney >= 0)) THEN
BEGIN
Three.MoneyInAccount := Three.MoneyInAccount - AmountOfMoney;
TransferringTo.MoneyInAccount := TransferringTo.MoneyInAccount + AmountOfMoney;
Writeln ('You have successfully transferred ', AmountOfMoney:1:2, ' to ', NameOfTransfer, '''s account!');
Writeln ('The balance in your account is ', Three.MoneyInAccount:1:2, '.');
END
ELSE IF ((Name = Four.Name) AND (Four.MoneyInAccount - AmountOfMoney >= 0)) THEN
BEGIN
Four.MoneyInAccount := Four.MoneyInAccount - AmountOfMoney;
TransferringTo.MoneyInAccount := TransferringTo.MoneyInAccount + AmountOfMoney;
Writeln ('You have successfully transferred ', AmountOfMoney:1:2, ' to ', NameOfTransfer, '''s account!');
Writeln ('The balance in your account is ', Four.MoneyInAccount:1:2, '.');
END
ELSE IF ((Name = Five.Name) AND (Five.MoneyInAccount - AmountOfMoney >= 0)) THEN
BEGIN
Five.MoneyInAccount := Five.MoneyInAccount - AmountOfMoney;
TransferringTo.MoneyInAccount := TransferringTo.MoneyInAccount + AmountOfMoney;
Writeln ('You have successfully transferred ', AmountOfMoney:1:2, ' to ', NameOfTransfer, '''s account!');
Writeln ('The balance in your account is ', Five.MoneyInAccount:1:2, '.');
END
ELSE IF ((Name = Six.Name) AND (Six.MoneyInAccount - AmountOfMoney >= 0)) THEN
BEGIN
Six.MoneyInAccount := Six.MoneyInAccount - AmountOfMoney;
TransferringTo.MoneyInAccount := TransferringTo.MoneyInAccount + AmountOfMoney;
Writeln ('You have successfully transferred ', AmountOfMoney:1:2, ' to ', NameOfTransfer, '''s account!');
Writeln ('The balance in your account is ', Six.MoneyInAccount:1:2, '.');
END
ELSE IF ((Name = Seven.Name) AND (Seven.MoneyInAccount - AmountOfMoney >= 0)) THEN
BEGIN
Seven.MoneyInAccount := Seven.MoneyInAccount - AmountOfMoney;
TransferringTo.MoneyInAccount := TransferringTo.MoneyInAccount + AmountOfMoney;
Writeln ('You have successfully transferred ', AmountOfMoney:1:2, ' to ', NameOfTransfer, '''s account!');
Writeln ('The balance in your account is ', Seven.MoneyInAccount:1:2, '.');
END
ELSE IF ((Name = Eight.Name) AND (Eight.MoneyInAccount - AmountOfMoney >= 0)) THEN
BEGIN
Eight.MoneyInAccount := Eight.MoneyInAccount - AmountOfMoney;
TransferringTo.MoneyInAccount := TransferringTo.MoneyInAccount + AmountOfMoney;
Writeln ('You have successfully transferred ', AmountOfMoney:1:2, ' to ', NameOfTransfer, '''s account!');
Writeln ('The balance in your account is ', Eight.MoneyInAccount:1:2, '.');
END
ELSE IF ((Name = Nine.Name) AND (Nine.MoneyInAccount - AmountOfMoney >= 0)) THEN
BEGIN
Nine.MoneyInAccount := Nine.MoneyInAccount - AmountOfMoney;
TransferringTo.MoneyInAccount := TransferringTo.MoneyInAccount + AmountOfMoney;
Writeln ('You have successfully transferred ', AmountOfMoney:1:2, ' to ', NameOfTransfer, '''s account!');
Writeln ('The balance in your account is ', Nine.MoneyInAccount:1:2, '.');
END
ELSE IF ((Name = Ten.Name) AND (Ten.MoneyInAccount - AmountOfMoney >= 0)) THEN
BEGIN
Ten.MoneyInAccount := Ten.MoneyInAccount - AmountOfMoney;
TransferringTo.MoneyInAccount := TransferringTo.MoneyInAccount + AmountOfMoney;
Writeln ('You have successfully transferred ', AmountOfMoney:1:2, ' to ', NameOfTransfer, '''s account!');
Writeln ('The balance in your account is ', Ten.MoneyInAccount:1:2, '.');
END
ELSE
BEGIN
Writeln ('You do not have enough money to transfer.');
Writeln ('If you would like, you may take a loan.');
END;
END;
{@param Customer - The customer whose info will be filled in in Procedure OptionChangeInformation
@return The changed information}
PROCEDURE ChangeInformation (VAR Customer : Customer_Info);
VAR
Choice : String;
ChangeToStr : String;
BEGIN
Writeln ('What would you like to change?');
Writeln;
Writeln ('Type in address, phone number, marital status, ');
Writeln (' social security number, annual salary, or pin.');
Writeln;
Readln (Choice);
IF (Choice = 'Address') OR (Choice = 'address') THEN
BEGIN
Writeln;
Writeln ('What would you like to change it to?');
Readln (ChangeToStr);
Customer.Address := ChangeToStr;
Writeln;
Writeln ('Your address has successfullly been changed to:');
Writeln (' ', Customer.Address);
END;
IF (Choice = 'Phone number') OR (Choice = 'Phone Number') OR (Choice = 'phone number') THEN
BEGIN
Writeln;
Writeln ('What would you like to change it to?');
Readln (Customer.PhoneNumber);
Writeln;
Writeln ('Your phone number has successfullly been changed to:');
Writeln (' ', Customer.PhoneNumber);
END;
IF (Choice = 'Marital Status') OR (Choice = 'Marital status') OR (Choice = 'marital status') THEN
BEGIN
Writeln;
Writeln ('What would you like to change it to?');
Readln (Customer.MaritalStatus);
Writeln;
Writeln ('Your marital status has successfullly been changed to:');
Writeln (' ', Customer.MaritalStatus);
END;
IF (Choice = 'Social Security Number') OR (Choice = 'social security number') THEN
BEGIN
Writeln;
Writeln ('What would you like to change it to?');
Readln (Customer.SocialSecurityNumber);
Writeln;
Writeln ('Your social security number has successfullly been changed to:');
Writeln (' ', Customer.SocialSecurityNumber);
END;
IF (Choice = 'Annual Salary') OR (Choice = 'annual salary') THEN
BEGIN
Writeln;
Writeln ('What would you like to change it to?');
Readln (Customer.AnnualSalary);
Writeln;
Writeln ('Your annual salary has successfullly been changed to:');
Writeln (' ', Customer.AnnualSalary);
END;
IF (Choice = 'Pin') OR (Choice = 'pin') THEN
BEGIN
Writeln;
Writeln ('What would you like to change it to?');
Readln (Customer.Password);
Writeln;
Writeln ('Your pin has successfullly been changed to:');
Writeln (' ', Customer.Password);
END;
END;
{@param Name - The name of the user
@param One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten - The customer records
@return Changed information}
PROCEDURE OptionChangeInformation (Name : String; VAR One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten : Customer_Info);
BEGIN
IF (Name = One.Name) THEN
BEGIN
Writeln;
Writeln ('The following is your current information:');
Delay (1000);
Writeln;
PrintInformation (Name, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten);
Writeln;
Writeln;
Writeln;
ChangeInformation (One);
Writeln;
END;
IF (Name = Two.Name) THEN
BEGIN
Writeln;
Writeln ('The following is your current information:');
Delay (1000);
Writeln;
PrintInformation (Name, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten);
Writeln;
Writeln;
Writeln;
ChangeInformation (Two);
Writeln;
END;
IF (Name = Three.Name) THEN
BEGIN
Writeln;
Writeln ('The following is your current information:');
Delay (1000);
Writeln;
PrintInformation (Name, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten);
Writeln;
Writeln;
Writeln;
ChangeInformation (Three);
Writeln;
END;
IF (Name = Four.Name) THEN
BEGIN
Writeln;
Writeln ('The following is your current information:');
Delay (1000);
Writeln;
PrintInformation (Name, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten);
Writeln;
Writeln;
Writeln;
ChangeInformation (Four);
Writeln;
END;
IF (Name = Five.Name) THEN
BEGIN
Writeln;
Writeln ('The following is your current information:');
Delay (1000);
Writeln;
PrintInformation (Name, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten);
Writeln;
Writeln;
Writeln;
ChangeInformation (Five);
Writeln;
END;
IF (Name = Six.Name) THEN
BEGIN
Writeln;
Writeln ('The following is your current information:');
Delay (1000);
Writeln;
PrintInformation (Name, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten);
Writeln;
Writeln;
Writeln;
ChangeInformation (Six);
Writeln;
END;
IF (Name = Seven.Name) THEN
BEGIN
Writeln;
Writeln ('The following is your current information:');
Delay (1000);
Writeln;
PrintInformation (Name, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten);
Writeln;
Writeln;
Writeln;
ChangeInformation (Seven);
Writeln;
END;
IF (Name = Eight.Name) THEN
BEGIN
Writeln;
Writeln ('The following is your current information:');
Delay (1000);
Writeln;
PrintInformation (Name, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten);
Writeln;
Writeln;
Writeln;
ChangeInformation (Eight);
Writeln;
END;
IF (Name = Nine.Name) THEN
BEGIN
Writeln;
Writeln ('The following is your current information:');
Delay (1000);
Writeln;
PrintInformation (Name, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten);
Writeln;
Writeln;
Writeln;
ChangeInformation (Nine);
Writeln;
END;
IF (Name = Ten.Name) THEN
BEGIN
Writeln;
Writeln ('The following is your current information:');
Delay (1000);
Writeln;
PrintInformation (Name, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten);
Writeln;
Writeln;
Writeln;
ChangeInformation (Ten);
Writeln;
END;
END;
{@param Name - The name of the customer
@param One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten - The customers' information
@param Accounts - The text file
@param ReserveRequirement - The reserve requirement}
PROCEDURE DeleteAnAccount (Name : String; VAR One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten : Customer_Info; VAR Accounts : Text; ReserveRequirement, MoneyInBank : Real);
BEGIN
IF (Name = One.Name) THEN
BEGIN
WITH One DO
BEGIN
Name := '';
Address := '';
PhoneNumber := '';
MaritalStatus := '0';
Gender := '0';
SocialSecurityNumber := '';
AnnualSalary := 0;
Password := 0;
MoneyInAccount := 0;
LoanAmount := 0;
END;
END;
IF (Name = Two.Name) THEN
BEGIN
WITH Two DO
BEGIN
Name := '';
Address := '';
PhoneNumber := '';
MaritalStatus := '0';
Gender := '0';
SocialSecurityNumber := '';
AnnualSalary := 0;
Password := 0;
MoneyInAccount := 0;
LoanAmount := 0;
END;
END;
IF (Name = Three.Name) THEN
BEGIN
WITH Three DO
BEGIN
Name := '';
Address := '';
PhoneNumber := '';
MaritalStatus := '0';
Gender := '0';
SocialSecurityNumber := '';
AnnualSalary := 0;
Password := 0;
MoneyInAccount := 0;
LoanAmount := 0;
END;
END;
IF (Name = Four.Name) THEN
BEGIN
WITH Four DO
BEGIN
Name := '';
Address := '';
PhoneNumber := '';
MaritalStatus := '0';
Gender := '0';
SocialSecurityNumber := '';
AnnualSalary := 0;
Password := 0;
MoneyInAccount := 0;
LoanAmount := 0;
END;
END;
IF (Name = Five.Name) THEN
BEGIN
WITH Five DO
BEGIN
Name := '';
Address := '';
PhoneNumber := '';
MaritalStatus := '0';
Gender := '0';
SocialSecurityNumber := '';
AnnualSalary := 0;
Password := 0;
MoneyInAccount := 0;
LoanAmount := 0;
END;
END;
IF (Name = Six.Name) THEN
BEGIN
WITH Six DO
BEGIN
Name := '';
Address := '';
PhoneNumber := '';
MaritalStatus := '0';
Gender := '0';
SocialSecurityNumber := '';
AnnualSalary := 0;
Password := 0;
MoneyInAccount := 0;
LoanAmount := 0;
END;
END;
IF (Name = Seven.Name) THEN
BEGIN
WITH Seven DO
BEGIN
Name := '';
Address := '';
PhoneNumber := '';
MaritalStatus := '0';
Gender := '0';
SocialSecurityNumber := '';
AnnualSalary := 0;
Password := 0;
MoneyInAccount := 0;
LoanAmount := 0;
END;
END;
IF (Name = Eight.Name) THEN
BEGIN
WITH Eight DO
BEGIN
Name := '';
Address := '';
PhoneNumber := '';
MaritalStatus := '0';
Gender := '0';
SocialSecurityNumber := '';
AnnualSalary := 0;
Password := 0;
MoneyInAccount := 0;
LoanAmount := 0;
END;
END;
IF (Name = Nine.Name) THEN
BEGIN
WITH Nine DO
BEGIN
Name := '';
Address := '';
PhoneNumber := '';
MaritalStatus := '0';
Gender := '0';
SocialSecurityNumber := '';
AnnualSalary := 0;
Password := 0;
MoneyInAccount := 0;
LoanAmount := 0;
END;
END;
IF (Name = Ten.Name) THEN
BEGIN
WITH Ten DO
BEGIN
Name := '';
Address := '';
PhoneNumber := '';
MaritalStatus := '0';
Gender := '0';
SocialSecurityNumber := '';
AnnualSalary := 0;
Password := 0;
MoneyInAccount := 0;
LoanAmount := 0;
END;
END;
Writeln;
Writeln;
Writeln ('You have deleted your account.');
Delay (750);
Writeln ('We will really miss your business.');
Delay (750);
Writeln ('Please come back soon!');
Delay (1750);
TransferInformation (Accounts, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, ReserveRequirement, MoneyInBank);
Halt;
END;
{@param ReserveRequirement - The amount of money that must be in the banks vaults that the bank cannot give out on a loan
@return The changed reserve requirement}
PROCEDURE ChangeReserveRequirement (VAR ReserveRequirement : Real);
VAR
ChangeTo : Real;
BEGIN
Writeln ('What would you like to change the reserve requirement to?');
Writeln ('It is currently ', ReserveRequirement, '.');
Readln (ChangeTo);
Writeln;
ReserveRequirement := ChangeTo;
Writeln ('The reserve requirement has successfully been changed.');
Delay (500);
Writeln ('It is now ', ChangeTo:1:2, '.');
Delay (750);
END;
{@param One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten - The customers' information
@return The printed customer information}
PROCEDURE ViewCustomerInformation (One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten : Customer_Info);
VAR
TempName : String;
BEGIN
Writeln ('Enter the nmae of the customer whose information you would like to see.');
Readln (TempName);
CLRSCR;
PrintInformation (TempName, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, ten);
END;
{@param AmountOfMoneyInTheBank - The amount of money in the bank
@return Prints the amount of money in the bank}
PROCEDURE ViewMoneyInBank (AmountOfMoneyInTheBank : Real);
BEGIN
Writeln ('The amount of money in the bank is ', AmountOfMoneyInTheBank:1:2);
END;
//All right, here we go!
begin
//Gets everything from the text file
GetInformation (G_Accounts, G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten, G_MoneyInBank, G_ReserveRequirement);
//Welcome
TextColor (LightGreen);
GoToXY (25, 15);
Writeln ('Welcome to the Challenger Bank!');
Delay (1500);
CLRSCR;
//Do you want to create an account?
GoToXY (20, 15);
Write ('Do you want to create an account? ');
Readln (G_Choice);
CLRSCR;
//Creating an account
IF (G_Choice = 'Yes') OR (G_Choice = 'yes') THEN
BEGIN
OptionCreateAnAccount (G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten);
CLRSCR;
END;
//Signing in: who are you?
GoToXY (20, 15);
Writeln ('Please sign in.');
SignIn (G_Name, G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten);
CLRSCR;
//User procedures
IF(G_Name <> 'Bank') THEN
BEGIN
TextColor (White);
//What would you like to do now?
GOTOXY (25, 15);
Writeln ('Hello, ', G_Name, ', I recognize you!');
Delay (1500);
CLRSCR;
//Starts recursion sequence
G_Flag := 2;
//Begins the While-Do loop for recursion
WHILE G_Flag > 0 DO
BEGIN
//Gives a menu of options
Writeln ('What would you like to do on this fine day?');
Writeln ('1. Deposit money ');
Writeln ('2. Withdraw money ');
Writeln ('3. Take a loan ');
Writeln ('4. Pay back a loan ');
Writeln ('5. View your information');
Writeln ('6. Transfer money to another person''s account ');
Writeln ('7. Change any of your information ');
Writeln ('8. Delete your account ');
Writeln ('9. Exit ');
Writeln;
Writeln ('Please enter the number of your choice.');
Writeln;
Readln (G_Choice);
CLRSCR;
//Deposit money
IF (G_Choice = '1') THEN
BEGIN
DepositMoney (G_Name, G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten, G_MoneyInBank);
END
//Withdraw money
ELSE IF (G_Choice = '2') THEN
BEGIN
WithdrawMoney (G_Name, G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten, G_MoneyInBank);
Delay (1000);
END
//Take a loan
ELSE IF (G_Choice = '3') THEN
BEGIN
Loan (G_Name, G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten, G_ReserveRequirement, G_MoneyInBank);
END
//Pay back a lona
ELSE IF (G_Choice = '4') THEN
BEGIN
OptionPayBackLoan (G_Name, G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten, G_MoneyInBank);
END
//Print user information
ELSE IF (G_Choice = '5') THEN
BEGIN
PrintInformation (G_Name, G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten);
END
//Transfer money to another user's account
ELSE IF (G_Choice = '6') THEN
BEGIN
//Checks whose account to transfer the money to
Writeln ('Enter the name of the person whose account ');
Writeln (' you would like to transfer money to.');
Readln (G_NameOfTransfer);
Writeln;
IF (G_NameOfTransfer = G_One.Name) THEN
PayMoneyToAnotherPerson (G_Name, G_NameOfTransfer, G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten, G_One);
IF (G_NameOfTransfer = G_Two.Name) THEN
PayMoneyToAnotherPerson (G_Name, G_NameOfTransfer, G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten, G_Two);
IF (G_NameOfTransfer = G_Three.Name) THEN
PayMoneyToAnotherPerson (G_Name, G_NameOfTransfer, G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten, G_Three);
IF (G_NameOfTransfer = G_Four.Name) THEN
PayMoneyToAnotherPerson (G_Name, G_NameOfTransfer, G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten, G_Four);
IF (G_NameOfTransfer = G_Five.Name) THEN
PayMoneyToAnotherPerson (G_Name, G_NameOfTransfer, G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten, G_Five);
IF (G_NameOfTransfer = G_Six.Name) THEN
PayMoneyToAnotherPerson (G_Name, G_NameOfTransfer, G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten, G_Six);
IF (G_NameOfTransfer = G_Seven.Name) THEN
PayMoneyToAnotherPerson (G_Name, G_NameOfTransfer, G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten, G_Seven);
IF (G_NameOfTransfer = G_Eight.Name) THEN
PayMoneyToAnotherPerson (G_Name, G_NameOfTransfer, G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten, G_Eight);
IF (G_NameOfTransfer = G_Nine.Name) THEN
PayMoneyToAnotherPerson (G_Name, G_NameOfTransfer, G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten, G_Nine);
IF (G_NameOfTransfer = G_Ten.Name) THEN
PayMoneyToAnotherPerson (G_Name, G_NameOfTransfer, G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten, G_Ten);
//Delay formatting
Delay (1500);
END
//Change your information
ELSE IF (G_Choice = '7') THEN
BEGIN
OptionChangeInformation (G_Name, G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten);
Delay (1000);
END
//Delete an account
ELSE IF (G_Choice = '8') THEN
BEGIN
Writeln ('Are you sure about deleting your account?');
Readln (G_DeleteOrNot);
IF (G_DeleteOrNot = 'Yes') OR (G_DeleteOrNot = 'yes') THEN
DeleteAnAccount (G_Name, G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten, G_Accounts, G_ReserveRequirement, G_MoneyInBank);
END
//Exiting
ELSE IF (G_Choice = '9') THEN
BEGIN
TextColor (LightGreen);
CLRSCR;
GOTOXY (20, 15);
Writeln ('Thank you for coming to the Challenger Bank!');
Delay (2000);
//Transfers information to the text file
TransferInformation (G_Accounts, G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten, G_ReserveRequirement, G_MoneyInBank);
//Ends program
Exit;
END
ELSE
BEGIN
TextColor (LightRed);
Writeln ('Oh no! You didn''t enter a valid input!');
Delay (1000);
END;
//Delay
Delay (1000);
//Transfers information to the text file
TransferInformation (G_Accounts, G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten, G_ReserveRequirement, G_MoneyInBank);
//Does the user want to do something else?
CLRSCR;
TextColor (LightGreen);
GOTOXY (15, 15);
Writeln ('Type in yes or no if you want to');
GOTOXY (15, 16);
Writeln ('do something else in the Challenger Bank.');
GOTOXY (25, 20);
Writeln ('***********');
GOTOXY (25, 21);
Writeln ('* *');
GOTOXY (25, 22);
Writeln ('***********');
GOTOXY (29, 21);
Readln (G_Repeat_Yes_Or_No);
IF (G_Repeat_Yes_Or_No = 'Yes') OR (G_Repeat_Yes_Or_No = 'yes') THEN
BEGIN
CLRSCR;
END;
IF (G_Repeat_Yes_Or_No = 'No') OR (G_Repeat_Yes_Or_No = 'no') THEN
BEGIN
TextColor (LightGreen);
CLRSCR;
GOTOXY (20, 15);
Writeln ('Thank you for coming to the Challenger Bank!');
Delay (2000);
Halt;
END;
//Ends the While-Do loop for all recursion and ends all customer procedures
END;
END;
//Bank procedures
G_Flag := 2;
IF (G_Name = 'Bank') THEN
BEGIN
WHILE G_Flag > 0 DO
BEGIN
//Formatting
TextColor (Yellow);
//Menu for doing things
Writeln ('As the bank, what would you like to do?');
Writeln ('1. Change the reserve requirement');
Writeln ('2. View customer information');
Writeln ('3. View the amount of money in the bank');
Writeln ('4. Exit');
Writeln;
Writeln ('Please enter the number of your choice.');
Writeln;
Readln (G_Choice);
CLRSCR;
//Change the reserve requirement
IF (G_Choice = '1') THEN
ChangeReserveRequirement (G_ReserveRequirement)
//View any user's information
ELSE IF (G_Choice = '2') THEN
ViewCustomerInformation (G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten)
//View the money in the bank
ELSE IF (G_Choice = '3') THEN
ViewMoneyInBank (G_MoneyInBank)
//Exit
ELSE IF (G_Choice = '4') THEN
BEGIN
TextColor (LightGreen);
CLRSCR;
GOTOXY (20, 15);
Writeln ('Thank you for coming to the Challenger Bank!');
Delay (2000);
//Transfers information to the text file
TransferInformation (G_Accounts, G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten, G_ReserveRequirement, G_MoneyInBank);
//Exit
Halt;
END
ELSE
BEGIN
TextColor (LightRed);
Writeln ('Sorry, you have entered an invalid input!');
END;
//Delay and clear the screen
Delay (2000);
CLRSCR;
//Transfer to txt file
TransferInformation (G_Accounts, G_One, G_Two, G_Three, G_Four, G_Five, G_Six, G_Seven, G_Eight, G_Nine, G_Ten, G_ReserveRequirement, G_MoneyInBank);
//Do you want to do anything else?
CLRSCR;
TextColor (LightGreen);
GOTOXY (15, 15);
Writeln ('Type in yes or no if you want to');
GOTOXY (15, 16);
Writeln ('do something else in the Challenger Bank.');
GOTOXY (25, 20);
Writeln ('***********');
GOTOXY (25, 21);
Writeln ('* *');
GOTOXY (25, 22);
Writeln ('***********');
GOTOXY (29, 21);
Readln (G_Repeat_Yes_Or_No);
IF (G_Repeat_Yes_Or_No = 'Yes') OR (G_Repeat_Yes_Or_No = 'yes') THEN
BEGIN
CLRSCR;
END;
IF (G_Repeat_Yes_Or_No = 'No') OR (G_Repeat_Yes_Or_No = 'no') THEN
BEGIN
TextColor (LightGreen);
CLRSCR;
GOTOXY (20, 15);
Writeln ('Thank you for coming to the Challenger Bank!');
Delay (2000);
Halt;
END;
//Ends the bank procedures as well as the recursion
END;
END;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC async notify form }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$HPPEMIT LINKUNIT}
unit FireDAC.VCLUI.Async;
interface
uses
{$IFDEF MSWINDOWS}
Winapi.Messages, Winapi.Windows,
{$ENDIF}
System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.ExtCtrls, Vcl.Buttons, Vcl.StdCtrls,
FireDAC.Stan.Intf,
FireDAC.UI.Intf, FireDAC.VCLUI.OptsBase;
type
TfrmFDGUIxFormsAsyncExecute = class(TfrmFDGUIxFormsOptsBase)
tmrDelay: TTimer;
btnCancel2: TSpeedButton;
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure btnCancelClick(Sender: TObject);
procedure tmrDelayTimer(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FExecutor: IFDStanAsyncExecutor;
FRequestShow: Boolean;
FModalData: Pointer;
FShowDelay, FHideDelay: Integer;
protected
// IFDGUIxAsyncExecuteDialog
procedure Show(const AExecutor: IFDStanAsyncExecutor);
procedure Hide;
{$IFDEF MSWINDOWS}
function IsFormActive: Boolean;
function IsFormMouseMessage(const AMsg: TMsg): Boolean;
{$ENDIF}
end;
var
frmFDGUIxFormsAsyncExecute: TfrmFDGUIxFormsAsyncExecute;
implementation
{$R *.dfm}
uses
Vcl.Consts,
FireDAC.Stan.Consts, FireDAC.Stan.Factory, FireDAC.Stan.ResStrs, FireDAC.Stan.Util,
FireDAC.UI, FireDAC.VCLUI.Controls;
{-------------------------------------------------------------------------------}
{ TfrmFDGUIxFormsAsyncExecute }
{-------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsAsyncExecute.FormCreate(Sender: TObject);
begin
Caption := S_FD_AsyncDialogDefCaption;
lblPrompt.Caption := S_FD_AsyncDialogDefPrompt;
FShowDelay := C_FD_DelayBeforeFWait;
FHideDelay := C_FD_DelayBeforeFWait;
btnCancel2.Caption := '&' + SCancelButton;
end;
{-------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsAsyncExecute.FormDestroy(Sender: TObject);
begin
if frmFDGUIxFormsAsyncExecute = Self then
frmFDGUIxFormsAsyncExecute := nil;
end;
{-------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsAsyncExecute.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_ESCAPE then begin
btnCancelClick(nil);
Key := 0;
end;
end;
{-------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsAsyncExecute.btnCancelClick(Sender: TObject);
begin
if (FExecutor <> nil) and FExecutor.Operation.AbortSupported then
FExecutor.AbortJob;
end;
{-------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsAsyncExecute.tmrDelayTimer(Sender: TObject);
begin
if (FRequestShow <> Visible) and not (csDestroying in ComponentState) then begin
FDGUIxCancel;
if FRequestShow then begin
FModalData := FDGUIxBeginModal(Self, False);
inherited Show;
end
else begin
if FModalData <> nil then
FDGUIxEndModal(FModalData);
inherited Hide;
end;
tmrDelay.Enabled := False;
end;
end;
{-------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsAsyncExecute.Show(const AExecutor: IFDStanAsyncExecutor);
begin
FExecutor := AExecutor;
if not FRequestShow then begin
FRequestShow := True;
btnCancel2.Visible := AExecutor.Operation.AbortSupported;
tmrDelay.Interval := FShowDelay;
tmrDelay.Enabled := True;
end;
end;
{-------------------------------------------------------------------------------}
procedure TfrmFDGUIxFormsAsyncExecute.Hide;
begin
if FRequestShow then begin
FRequestShow := False;
FExecutor := nil;
tmrDelay.Interval := FHideDelay;
tmrDelay.Enabled := True;
end;
end;
{-------------------------------------------------------------------------------}
{$IFDEF MSWINDOWS}
function TfrmFDGUIxFormsAsyncExecute.IsFormActive: Boolean;
begin
Result := Screen.ActiveForm = Self;
end;
{-------------------------------------------------------------------------------}
function TfrmFDGUIxFormsAsyncExecute.IsFormMouseMessage(const AMsg: TMsg): Boolean;
var
oCtrl: TControl;
begin
oCtrl := FindControl(AMsg.hwnd);
if oCtrl <> nil then
Result := (GetParentForm(oCtrl) = Self)
else
Result := False;
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
{ TFDGUIxFormsAsyncExecuteImpl }
{-------------------------------------------------------------------------------}
type
TFDGUIxFormsAsyncExecuteImpl = class(TFDGUIxObject, IFDGUIxAsyncExecuteDialog)
private
function GetForm: TfrmFDGUIxFormsAsyncExecute;
protected
// IFDGUIxAsyncExecuteDialog
function GetOnShow: TNotifyEvent;
procedure SetOnShow(const AValue: TNotifyEvent);
function GetOnHide: TNotifyEvent;
procedure SetOnHide(const AValue: TNotifyEvent);
function GetCaption: String;
procedure SetCaption(const AValue: String);
function GetPrompt: String;
procedure SetPrompt(const AValue: String);
function GetShowDelay: Integer;
procedure SetShowDelay(AValue: Integer);
function GetHideDelay: Integer;
procedure SetHideDelay(AValue: Integer);
procedure Show(const AExecutor: IFDStanAsyncExecutor);
procedure Hide;
{$IFDEF MSWINDOWS}
function IsFormActive: Boolean;
function IsFormMouseMessage(const AMsg: TMsg): Boolean;
{$ENDIF}
public
procedure Initialize; override;
destructor Destroy; override;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxFormsAsyncExecuteImpl.Initialize;
begin
inherited Initialize;
frmFDGUIxFormsAsyncExecute := nil;
end;
{-------------------------------------------------------------------------------}
destructor TFDGUIxFormsAsyncExecuteImpl.Destroy;
begin
FDFreeAndNil(frmFDGUIxFormsAsyncExecute);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxFormsAsyncExecuteImpl.GetForm: TfrmFDGUIxFormsAsyncExecute;
begin
if frmFDGUIxFormsAsyncExecute = nil then
frmFDGUIxFormsAsyncExecute := TfrmFDGUIxFormsAsyncExecute.Create(Application);
Result := frmFDGUIxFormsAsyncExecute;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxFormsAsyncExecuteImpl.Show(const AExecutor: IFDStanAsyncExecutor);
begin
if not FDGUIxSilent() then
GetForm.Show(AExecutor);
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxFormsAsyncExecuteImpl.Hide;
begin
if not FDGUIxSilent() then
GetForm.Hide;
end;
{-------------------------------------------------------------------------------}
{$IFDEF MSWINDOWS}
function TFDGUIxFormsAsyncExecuteImpl.IsFormActive: Boolean;
begin
Result := not FDGUIxSilent() and GetForm.IsFormActive;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxFormsAsyncExecuteImpl.IsFormMouseMessage(
const AMsg: TMsg): Boolean;
begin
Result := not FDGUIxSilent() and GetForm.IsFormMouseMessage(AMsg);
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
function TFDGUIxFormsAsyncExecuteImpl.GetOnHide: TNotifyEvent;
begin
Result := GetForm.OnHide;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxFormsAsyncExecuteImpl.GetOnShow: TNotifyEvent;
begin
Result := GetForm.OnShow;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxFormsAsyncExecuteImpl.SetOnHide(const AValue: TNotifyEvent);
begin
if Assigned(AValue) or Assigned(frmFDGUIxFormsAsyncExecute) then
GetForm.OnHide := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxFormsAsyncExecuteImpl.SetOnShow(const AValue: TNotifyEvent);
begin
if Assigned(AValue) or Assigned(frmFDGUIxFormsAsyncExecute) then
GetForm.OnShow := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxFormsAsyncExecuteImpl.GetCaption: String;
begin
Result := GetForm.Caption;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxFormsAsyncExecuteImpl.SetCaption(const AValue: String);
begin
if (AValue <> '') or Assigned(frmFDGUIxFormsAsyncExecute) then
GetForm.Caption := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxFormsAsyncExecuteImpl.GetPrompt: String;
begin
Result := GetForm.lblPrompt.Caption;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxFormsAsyncExecuteImpl.SetPrompt(const AValue: String);
begin
if (AValue <> '') or Assigned(frmFDGUIxFormsAsyncExecute) then
GetForm.lblPrompt.Caption := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxFormsAsyncExecuteImpl.GetShowDelay: Integer;
begin
Result := GetForm.FShowDelay;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxFormsAsyncExecuteImpl.SetShowDelay(AValue: Integer);
begin
if (AValue <> 0) or Assigned(frmFDGUIxFormsAsyncExecute) then
GetForm.FShowDelay := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxFormsAsyncExecuteImpl.GetHideDelay: Integer;
begin
Result := GetForm.FHideDelay;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxFormsAsyncExecuteImpl.SetHideDelay(AValue: Integer);
begin
if (AValue <> 0) or Assigned(frmFDGUIxFormsAsyncExecute) then
GetForm.FHideDelay := AValue;
end;
{-------------------------------------------------------------------------------}
var
oFact: TFDFactory;
initialization
oFact := TFDSingletonFactory.Create(TFDGUIxFormsAsyncExecuteImpl,
IFDGUIxAsyncExecuteDialog, C_FD_GUIxFormsProvider);
finalization
FDReleaseFactory(oFact);
end.
|
unit UDaoProduto;
interface
uses uDao, DB, SysUtils, Messages, UProduto, UDaoMarca, UDaoCategoria,
UProdutoFornecedor, UFornecedor, UDaoUnidade, UDaoNcm, UEndereco;
type DaoProduto = class(Dao)
private
protected
umProduto : Produto;
umaDaoMarca : DaoMarca;
umaDaoCategoria : DaoCategoria;
umaDaoUnidade : DaoUnidade;
umaFornecedor : Fornecedor;
umaDaoNcm : DaoNcm;
umProdutoFornecedor : ProdutoFornecedor;
public
Constructor CrieObjeto;
Destructor Destrua_se;
function Salvar(obj:TObject): string; override;
function GetDS : TDataSource; override;
function Carrega(obj:TObject): TObject; override;
function Buscar(obj : TObject) : Boolean; override;
function Excluir(obj : TObject) : string ; override;
function CarregarFornececor(obj: TObject): TObject;
function RelacaoProduto (tipo : Integer) : Boolean;
procedure AtualizaGrid;
procedure Ordena(campo: string);
end;
implementation
{ DaoProduto }
function DaoProduto.Buscar(obj: TObject): Boolean;
var
prim: Boolean;
sql, e, onde: string;
umProduto: Produto;
begin
e := ' and ';
onde := ' where';
prim := true;
umProduto := Produto(obj);
sql := 'select * from produto';
if umProduto.getId <> 0 then
begin
if prim then //SE FOR O PRIMEIRO, SETA COMO FLAG COMO FALSO PQ É O PRIMEIRO
begin
prim := false;
sql := sql+onde;
end
else //SE NAO, COLOCA CLAUSULA AND PARA JUNTAR CONDIÇOES
sql := sql+e;
sql := sql+' idproduto = '+inttostr(umProduto.getId); //COLOCA CONDIÇAO NO SQL
end;
if umProduto.getDescricao <> '' then
begin
if prim then
begin
prim := false;
sql := sql+onde;
end
else
sql := sql+e;
sql := sql+' descricao like '+quotedstr('%'+umProduto.getDescricao+'%');
end;
with umDM do
begin
QProduto.Close;
QProduto.sql.Text := sql+' order by idproduto';
QProduto.Open;
if QProduto.RecordCount > 0 then
result := True
else
result := false;
end;
end;
procedure DaoProduto.AtualizaGrid;
begin
with umDM do
begin
QProduto.Close;
QProduto.sql.Text := 'select * from produto order by idproduto';
QProduto.Open;
end;
end;
function DaoProduto.RelacaoProduto(tipo: Integer): Boolean;
var sql : string;
begin
sql := 'select * from produto';
with umDM do
begin
QProduto.Close;
QProduto.sql.Text := sql+' order by idproduto';
QProduto.Open;
if QProduto.RecordCount > 0 then
result := True
else
result := false;
end;
end;
function DaoProduto.Carrega(obj: TObject): TObject;
var umProduto: Produto;
begin
umProduto := Produto(obj);
with umDM do
begin
if not QProduto.Active then
QProduto.Open;
if umProduto.getId <> 0 then
begin
QProduto.Close;
QProduto.SQL.Text := 'select * from produto where idproduto = '+IntToStr(umProduto.getId);
QProduto.Open;
end;
umProduto.setId(QProdutoidproduto.AsInteger);
umProduto.setDescricao(QProdutodescricao.AsString);
umProduto.setQuantidade(QProdutoquantidade.AsFloat);
umProduto.setUnidade(QProdutounidade.AsString);
umProduto.setICMS(QProdutoicms.AsFloat);
umProduto.setCst(QProdutocst.AsString);
umProduto.setIPI(QProdutoipi.AsFloat);
umProduto.setPrecoCompra(QProdutopreco_compra.AsFloat);
umProduto.setICMSAnterior(QProdutoicms_anterior.AsFloat);
umProduto.setIPIAnterior(QProdutoipi_anterior.AsFloat);
umProduto.setPrecoCompraAnt(QProdutopreco_compra_ant.AsFloat);
umProduto.setPrecoVenda(QProdutopreco_venda.AsFloat);
umProduto.setObservacao(QProdutoobservacao.AsString);
umProduto.setDataCadastro(QProdutodatacadastro.AsDateTime);
umProduto.setDataAlteracao(QProdutodataalteracao.AsDateTime);
// Busca Marca referente a Produto
umProduto.getUmaMarca.setId(QProdutoidmarca.AsInteger);
umaDaoMarca.Carrega(umProduto.getUmaMarca);
// Busca Categoria referente a Produto
umProduto.getUmaCategoria.setId(QProdutoidcategoria.AsInteger);
umaDaoCategoria.Carrega(umProduto.getUmaCategoria);
// Busca NCM referente a Produto
umProduto.getUmNcm.setId(QProdutoidncm.AsInteger);
umaDaoNcm.Carrega(umProduto.getUmNcm);
end;
result := umProduto;
Self.AtualizaGrid;
end;
function DaoProduto.CarregarFornececor(obj: TObject): TObject;
var
umFornecedor : Fornecedor;
umEndereco : Endereco;
umProduto : Produto;
begin
umProduto := Produto(obj);
with umDM do
begin
//Carregar os Fornecedores
QProdutoFornecedor.Close;
QProdutoFornecedor.SQL.Text := 'select * from produto_fornecedor where idproduto = '+IntToStr(umProduto.getId);
QProdutoFornecedor.Open;
QProdutoFornecedor.First;
if umProdutoFornecedor.CountFornecedores <> 0 then
umProdutoFornecedor.LimparListaFornecedor; //Limpar a lista caso a lista vim com itens carregados
while not QProdutoFornecedor.Eof do
begin
umProdutoFornecedor.CrieObejtoFornecedor;
umProdutoFornecedor.addFornecedor(umProdutoFornecedor.getUmFornecedor);
umProdutoFornecedor.getUmFornecedor.setId(QProdutoFornecedoridfornecedor.AsInteger);
umEndereco := Endereco.CrieObjeto;
if not QFornecedor.Active then
QFornecedor.Open;
if umProdutoFornecedor.getUmFornecedor.getId <> 0 then
begin
QFornecedor.Close;
QFornecedor.SQL.Text := 'select * from fornecedor where idfornecedor = '+IntToStr(umProdutoFornecedor.getUmFornecedor.getId);
QFornecedor.Open;
end;
umProdutoFornecedor.getUmFornecedor.setId(QFornecedoridfornecedor.AsInteger);
umProdutoFornecedor.getUmFornecedor.setNome_RazaoSoCial(QFornecedornome_razaosocial.AsString);
//Endereço
umEndereco.setLogradouro(QFornecedorlogradouro.AsString);
umEndereco.setNumero(QFornecedornumero.AsString);
umEndereco.setCEP(QFornecedorcep.AsString);
umEndereco.setBairro(QFornecedorbairro.AsString);
umEndereco.setComplemento(QFornecedorcomplemento.AsString);
umProdutoFornecedor.getUmFornecedor.setumEndereco(umEndereco);
umProdutoFornecedor.getUmFornecedor.setEmail(QFornecedoremail.AsString);
umProdutoFornecedor.getUmFornecedor.setTelefone(QFornecedortelefone.AsString);
umProdutoFornecedor.getUmFornecedor.setCelular(QFornecedorcelular.AsString);
umProdutoFornecedor.getUmFornecedor.setCPF_CNPJ(QFornecedorcpf_cnpj.AsString);
umProdutoFornecedor.getUmFornecedor.setRG_IE(QFornecedorrg_ie.AsString);
umProdutoFornecedor.getUmFornecedor.setTipoPessoa(QFornecedortipopessoa.AsString);
QProdutoFornecedor.Next;
end;
end;
result := umProdutoFornecedor;
end;
constructor DaoProduto.CrieObjeto;
begin
inherited;
umaDaoMarca := DaoMarca.CrieObjeto;
umaDaoCategoria := DaoCategoria.CrieObjeto;
umaDaoUnidade := DaoUnidade.CrieObjeto;
umaDaoNcm := DaoNcm.CrieObjeto;
umProdutoFornecedor := ProdutoFornecedor.CrieObjeto;
end;
destructor DaoProduto.Destrua_se;
begin
inherited;
end;
function DaoProduto.Excluir(obj: TObject): string;
var
umProduto: Produto;
begin
umProduto := Produto(obj);
with umDM do
begin
try
beginTrans;
QProduto.SQL := UpdateProduto.DeleteSQL;
QProduto.Params.ParamByName('OLD_idproduto').Value := umProduto.getId;
QProduto.ExecSQL;
Commit;
result := 'Produto excluído com sucesso!'
except
on e:Exception do
begin
rollback;
if pos('violates foreign key',e.Message)>0 then
result := 'Ocorreu um erro! O Produto não pode ser excluído pois ja está sendo usado pelo sistema.'
else
result := 'Ocorreu um erro! Produto não foi excluído. Erro: '+e.Message
end;
end;
end;
Self.AtualizaGrid;
end;
function DaoProduto.GetDS: TDataSource;
begin
(umDM.QProduto.FieldByName('quantidade') as TFloatField).DisplayFormat := '0.000';
(umDM.QProduto.FieldByName('icms') as TFloatField).DisplayFormat := '0.00';
(umDM.QProduto.FieldByName('ipi') as TFloatField).DisplayFormat := '0.00';
(umDM.QProduto.FieldByName('preco_compra') as TFloatField).DisplayFormat := '0.00';
(umDM.QProduto.FieldByName('icms_anterior') as TFloatField).DisplayFormat := '0.00';
(umDM.QProduto.FieldByName('ipi_anterior') as TFloatField).DisplayFormat := '0.00';
(umDM.QProduto.FieldByName('preco_compra_ant') as TFloatField).DisplayFormat := '0.00';
umDM.QProduto.FieldByName('cst').DisplayLabel := 'CST';
umDM.QProduto.FieldByName('icms').DisplayLabel := 'ICMS';
umDM.QProduto.FieldByName('ipi').DisplayLabel := 'IPI';
umDM.QProduto.FieldByName('preco_compra').DisplayLabel := 'Média Compra';
umDM.QProduto.FieldByName('preco_venda').DisplayLabel := 'Preco Venda';
umDM.QProduto.FieldByName('icms_anterior').DisplayLabel := 'Icms Anterior';
umDM.QProduto.FieldByName('ipi_anterior').DisplayLabel := 'Ipi Anterior';
umDM.QProduto.FieldByName('preco_compra_ant').DisplayLabel := 'Preco Compra Ant.';
Self.AtualizaGrid;
Result := umDM.DSProduto;
end;
procedure DaoProduto.Ordena(campo: string);
begin
umDM.QProduto.IndexFieldNames := campo;
end;
function DaoProduto.Salvar(obj: TObject): string;
var umProduto : Produto;
begin
umProduto := Produto(obj);
with umDM do
begin
try
beginTrans;
QProduto.Close;
if umProduto.getId = 0 then
begin
if(Self.Buscar(umProduto)) then
begin
Result := 'Esse Produto já existe!';
Self.AtualizaGrid;
Exit;
end;
QProduto.SQL := UpdateProduto.InsertSQL
end
else
begin
QProduto.SQL := UpdateProduto.ModifySQL;
QProduto.Params.ParamByName('OLD_idproduto').Value := umProduto.getId;
end;
QProduto.Params.ParamByName('descricao').Value := umProduto.getDescricao;
QProduto.Params.ParamByName('unidade').Value := umProduto.getUnidade;
QProduto.Params.ParamByName('idncm').Value := umProduto.getUmNcm.getId;
QProduto.Params.ParamByName('quantidade').Value := umProduto.getQuantidade;
QProduto.Params.ParamByName('idmarca').Value := umProduto.getUmaMarca.getId;
QProduto.Params.ParamByName('idcategoria').Value := umProduto.getUmaCategoria.getId;
QProduto.Params.ParamByName('cst').Value := umProduto.getCst;
QProduto.Params.ParamByName('icms').Value := umProduto.getICMS;
QProduto.Params.ParamByName('ipi').Value := umProduto.getIPI;
QProduto.Params.ParamByName('preco_compra').Value := umProduto.getPrecoCompra;
QProduto.Params.ParamByName('icms_anterior').Value := umProduto.getICMSAnterior;
QProduto.Params.ParamByName('ipi_anterior').Value := umProduto.getIPIAnterior;
QProduto.Params.ParamByName('preco_compra_ant').Value := umProduto.getPrecoCompraAnt;
QProduto.Params.ParamByName('preco_venda').Value := umProduto.getPrecoVenda;
QProduto.Params.ParamByName('observacao').Value := umProduto.getObservacao;
QProduto.Params.ParamByName('datacadastro').Value := umProduto.getDataCadastro;
QProduto.Params.ParamByName('dataalteracao').Value := umProduto.getDataAlteracao;
QProduto.ExecSQL;
Commit;
result := 'Produto salvo com sucesso!';
except
on e: Exception do
begin
rollback;
Result := 'Ocorreu um erro! Produto não foi salvo. Erro: '+e.Message
end;
end;
end;
Self.AtualizaGrid;
end;
end.
|
unit CompFrameUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, dxSkinsCore, dxSkinBlack,
dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom,
dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy,
dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian,
dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis,
dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black,
dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink,
dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue,
dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray,
dxSkinOffice2013White, dxSkinOffice2016Colorful, dxSkinOffice2016Dark,
dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus,
dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008,
dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine,
dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark,
dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint,
dxSkinXmas2008Blue, dxBar, cxClasses, System.Actions, Vcl.ActnList,
NotifyEvents;
type
TfrmComp = class(TFrame)
dxBarManager: TdxBarManager;
dxBarManager1Bar1: TdxBar;
dxBarSubItem1: TdxBarSubItem;
dxBarSubItem2: TdxBarSubItem;
ActionList: TActionList;
actLoadFromExcelFolder: TAction;
actLoadFromExcelDocument: TAction;
actLoadParametricTable: TAction;
actLoadParametricData: TAction;
dxBarButton1: TdxBarButton;
dxBarButton2: TdxBarButton;
dxBarSubItem3: TdxBarSubItem;
dxBarButton3: TdxBarButton;
dxBarButton4: TdxBarButton;
dxBarSubItem4: TdxBarSubItem;
actLoadParametricTableRange: TAction;
dxBarButton5: TdxBarButton;
dxBarSubItem5: TdxBarSubItem;
actAutoBindingDoc: TAction;
actAutoBindingDescriptions: TAction;
dxBarButton6: TdxBarButton;
dxBarButton7: TdxBarButton;
procedure actAutoBindingDescriptionsExecute(Sender: TObject);
procedure actAutoBindingDocExecute(Sender: TObject);
procedure actLoadFromExcelDocumentExecute(Sender: TObject);
procedure actLoadFromExcelFolderExecute(Sender: TObject);
procedure actLoadParametricDataExecute(Sender: TObject);
procedure actLoadParametricTableExecute(Sender: TObject);
private
FOnLoadCompFromExcelFolder: TNotifyEventsEx;
FOnLoadCompFromExcelDocument: TNotifyEventsEx;
FOnLoadParametricTable: TNotifyEventsEx;
FOnLoadParametricData: TNotifyEventsEx;
FOnAutoBindingDoc: TNotifyEventsEx;
FOnAutoBindingDescription: TNotifyEventsEx;
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property OnLoadCompFromExcelFolder: TNotifyEventsEx read
FOnLoadCompFromExcelFolder;
property OnLoadCompFromExcelDocument: TNotifyEventsEx read
FOnLoadCompFromExcelDocument;
property OnLoadParametricTable: TNotifyEventsEx read FOnLoadParametricTable;
property OnLoadParametricData: TNotifyEventsEx read FOnLoadParametricData;
property OnAutoBindingDoc: TNotifyEventsEx read FOnAutoBindingDoc;
property OnAutoBindingDescription: TNotifyEventsEx read
FOnAutoBindingDescription;
{ Public declarations }
end;
implementation
{$R *.dfm}
uses RepositoryDataModule, FormsHelper, ProjectConst;
constructor TfrmComp.Create(AOwner: TComponent);
begin
inherited;
FOnLoadCompFromExcelFolder := TNotifyEventsEx.Create(Self);
FOnLoadCompFromExcelDocument := TNotifyEventsEx.Create(Self);
FOnLoadParametricTable := TNotifyEventsEx.Create(Self);
FOnLoadParametricData := TNotifyEventsEx.Create(Self);
FOnAutoBindingDoc := TNotifyEventsEx.Create(Self);
FOnAutoBindingDescription := TNotifyEventsEx.Create(Self);
TFormsHelper.SetFont(Self, BaseFontSize);
end;
destructor TfrmComp.Destroy;
begin
inherited;
FreeAndNil(FOnLoadCompFromExcelFolder);
FreeAndNil(FOnLoadCompFromExcelDocument);
FreeAndNil(FOnLoadParametricTable);
FreeAndNil(FOnLoadParametricData);
FreeAndNil(FOnAutoBindingDoc);
FreeAndNil(FOnAutoBindingDescription);
end;
procedure TfrmComp.actAutoBindingDescriptionsExecute(Sender: TObject);
begin
FOnAutoBindingDescription.CallEventHandlers(Self);
end;
procedure TfrmComp.actAutoBindingDocExecute(Sender: TObject);
begin
FOnAutoBindingDoc.CallEventHandlers(Self);
end;
procedure TfrmComp.actLoadFromExcelDocumentExecute(Sender: TObject);
begin
FOnLoadCompFromExcelDocument.CallEventHandlers(Self);
end;
procedure TfrmComp.actLoadFromExcelFolderExecute(Sender: TObject);
begin
FOnLoadCompFromExcelFolder.CallEventHandlers(Self);
end;
procedure TfrmComp.actLoadParametricDataExecute(Sender: TObject);
begin
FOnLoadParametricData.CallEventHandlers(Self);
end;
procedure TfrmComp.actLoadParametricTableExecute(Sender: TObject);
begin
FOnLoadParametricTable.CallEventHandlers(Self);
end;
end.
|
unit h_LangLib;
interface
uses Classes,SysUtils ;
//type
// TLANG_DESC = Record
// FORMID : String;
// DB_COLUMN_YN : String;
// FIELD_NAME: String;
// DESC : Array [1..5] of String;
// end;
//
// TLANG_INFO = Record // Form Field Description
// ID : String;
// LANG : Array [0..100] of TLANG_DESC ;
// end;
//
// TLANG_PGM = Record // Form Name Description
// LANG : Array [0..100] of TLANG_DESC ;
// end;
//==============================================================================
// 암호화에 사용되는 기본 키값
//==============================================================================
const
programClose_1 = '프로그램을 종료하시겠습니까? ';
programClose_2 = 'Close applications?';
//programClose_3 = '结束吗?';
// 언어를 변환해 온다.
function ExGetLang( Source:String; LANGUAGE : String ): String;
implementation
//==============================================================================
// 지정된 수만큼 증가한다.
//==============================================================================
function ExGetLang( Source, LANGUAGE : String ): String;
begin
Result := Source;
end;
end.
|
unit Support.Fallback.CDI;
interface
uses
SMARTSupport, SMARTSupport.Factory,
SysUtils,
Support, Device.SMART.List;
type
TFallbackCDISupport = class sealed(TNSTSupport)
private
FSMARTSupport: TSMARTSupport;
FIsWriteValueSupported: Boolean;
function GetCDISupport: TSupportStatus;
function IsSupportedByCDI: Boolean;
function IsValidSSD: Boolean;
public
function GetSupportStatus: TSupportStatus; override;
function GetSMARTInterpreted(SMARTValueList: TSMARTValueList):
TSMARTInterpreted; override;
destructor Destroy; override;
end;
implementation
{ TFallbackCDISupport }
function TFallbackCDISupport.IsSupportedByCDI: Boolean;
var
SMARTSupportFactory: TSMARTSupportFactory;
begin
result := FSMARTSupport <> nil;
if result then
begin
exit;
end;
try
try
SMARTSupportFactory := TSMARTSupportFactory.Create;
FSMARTSupport := SMARTSupportFactory.GetSuitableSMARTSupport(
Identify, SMART);
result := FSMARTSupport <> nil;
except
result := false;
end;
finally
if SMARTSupportFactory <> nil then
FreeAndNil(SMARTSupportFactory);
if FSMARTSupport <> nil then
FIsWriteValueSupported := FSMARTSupport.IsWriteValueSupported(SMART);
end;
end;
function TFallbackCDISupport.IsValidSSD: Boolean;
begin
result := Identify.IsDataSetManagementSupported;
end;
destructor TFallbackCDISupport.Destroy;
begin
if FSMARTSupport <> nil then
FreeAndNil(FSMARTSupport);
inherited;
end;
function TFallbackCDISupport.GetCDISupport: TSupportStatus;
begin
if (FSMARTSupport.IsInsufficientSMART) or (not FIsWriteValueSupported) then
begin
result.Supported := CDIInsufficient;
result.TotalWriteType := TTotalWriteType.WriteNotSupported;
end
else
begin
result.Supported := CDISupported;
result.TotalWriteType := TTotalWriteType.WriteSupportedAsValue;
end;
result.FirmwareUpdate := false;
end;
function TFallbackCDISupport.GetSupportStatus: TSupportStatus;
begin
result.Supported := NotSupported;
if IsSupportedByCDI and IsValidSSD then
result := GetCDISupport;
end;
function TFallbackCDISupport.GetSMARTInterpreted(
SMARTValueList: TSMARTValueList): TSMARTInterpreted;
const
ReplacedSectorThreshold = 50;
EraseErrorThreshold = 10;
begin
try
result := FSMARTSupport.GetSMARTInterpreted(SMARTValueList);
except
on E: EEntryNotFound do
begin
FillChar(result, SizeOf(result), 0);
end;
end;
result.SMARTAlert.ReplacedSector :=
result.ReplacedSectors >= ReplacedSectorThreshold;
result.SMARTAlert.ReadEraseError :=
result.ReadEraseError.Value >= EraseErrorThreshold;
if FSMARTSupport <> nil then
result.SMARTAlert.CriticalError :=
FSMARTSupport.GetDriveStatus(SMARTValueList) = BAD;
end;
end.
|
{ *************************************************************************** }
{ }
{ Audio Tools Library (Freeware) }
{ Class TAPEtag - for manipulating with APE tags }
{ }
{ Copyright (c) 2001,2002 by Jurgen Faul }
{ E-mail: jfaul@gmx.de }
{ http://jfaul.de/atl }
{ }
{ Version 1.0 (21 April 2002) }
{ - Reading & writing support for APE 1.0 tags }
{ - Reading support for APE 2.0 tags (UTF-8 decoding) }
{ - Tag info: title, artist, album, track, year, genre, comment, copyright }
{ }
{ *************************************************************************** }
unit APEtag;
interface
uses
Classes, SysUtils;
type
{ Class TAPEtag }
TAPEtag = class(TObject)
private
{ Private declarations }
FExists: Boolean;
FVersion: Integer;
FSize: Integer;
FTitle: string;
FArtist: string;
FAlbum: string;
FTrack: Byte;
FYear: string;
FGenre: string;
FComment: string;
FCopyright: string;
procedure FSetTitle(const NewTitle: string);
procedure FSetArtist(const NewArtist: string);
procedure FSetAlbum(const NewAlbum: string);
procedure FSetTrack(const NewTrack: Byte);
procedure FSetYear(const NewYear: string);
procedure FSetGenre(const NewGenre: string);
procedure FSetComment(const NewComment: string);
procedure FSetCopyright(const NewCopyright: string);
public
{ Public declarations }
constructor Create; { Create object }
procedure ResetData; { Reset all data }
function ReadFromFile(const FileName: string): Boolean; { Load tag }
function RemoveFromFile(const FileName: string): Boolean; { Delete tag }
function SaveToFile(const FileName: string): Boolean; { Save tag }
property Exists: Boolean read FExists; { True if tag found }
property Version: Integer read FVersion; { Tag version }
property Size: Integer read FSize; { Total tag size }
property Title: string read FTitle write FSetTitle; { Song title }
property Artist: string read FArtist write FSetArtist; { Artist name }
property Album: string read FAlbum write FSetAlbum; { Album title }
property Track: Byte read FTrack write FSetTrack; { Track number }
property Year: string read FYear write FSetYear; { Release year }
property Genre: string read FGenre write FSetGenre; { Genre name }
property Comment: string read FComment write FSetComment; { Comment }
property Copyright: string read FCopyright write FSetCopyright; { (c) }
end;
implementation
const
{ Tag ID }
ID3V1_ID = 'TAG'; { ID3v1 }
APE_ID = 'APETAGEX'; { APE }
{ Size constants }
ID3V1_TAG_SIZE = 128; { ID3v1 tag }
APE_TAG_FOOTER_SIZE = 32; { APE tag footer }
APE_TAG_HEADER_SIZE = 32; { APE tag header }
{ First version of APE tag }
APE_VERSION_1_0 = 1000;
{ Max. number of supported tag fields }
APE_FIELD_COUNT = 8;
{ Names of supported tag fields }
APE_FIELD: array [1..APE_FIELD_COUNT] of string =
('Title', 'Artist', 'Album', 'Track', 'Year', 'Genre',
'Comment', 'Copyright');
type
{ APE tag data - for internal use }
TagInfo = record
{ Real structure of APE footer }
ID: array [1..8] of Char; { Always "APETAGEX" }
Version: Integer; { Tag version }
Size: Integer; { Tag size including footer }
Fields: Integer; { Number of fields }
Flags: Integer; { Tag flags }
Reserved: array [1..8] of Char; { Reserved for later use }
{ Extended data }
DataShift: Byte; { Used if ID3v1 tag found }
FileSize: Integer; { File size (bytes) }
Field: array [1..APE_FIELD_COUNT] of string; { Information from fields }
end;
{ ********************* Auxiliary functions & procedures ******************** }
function ReadFooter(const FileName: string; var Tag: TagInfo): Boolean;
var
SourceFile: file;
TagID: array [1..3] of Char;
Transferred: Integer;
begin
{ Load footer from file to variable }
try
Result := true;
{ Set read-access and open file }
AssignFile(SourceFile, FileName);
FileMode := 0;
Reset(SourceFile, 1);
Tag.FileSize := FileSize(SourceFile);
{ Check for existing ID3v1 tag }
Seek(SourceFile, Tag.FileSize - ID3V1_TAG_SIZE);
BlockRead(SourceFile, TagID, SizeOf(TagID));
if TagID = ID3V1_ID then Tag.DataShift := ID3V1_TAG_SIZE;
{ Read footer data }
Seek(SourceFile, Tag.FileSize - Tag.DataShift - APE_TAG_FOOTER_SIZE);
BlockRead(SourceFile, Tag, APE_TAG_FOOTER_SIZE, Transferred);
CloseFile(SourceFile);
{ if transfer is not complete }
if Transferred < APE_TAG_FOOTER_SIZE then Result := false;
except
{ Error }
Result := false;
end;
end;
{ --------------------------------------------------------------------------- }
function ConvertFromUTF8(const Source: string): string;
var
Iterator, SourceLength, FChar, NChar: Integer;
begin
{ Convert UTF-8 string to ANSI string }
Result := '';
Iterator := 0;
SourceLength := Length(Source);
while Iterator < SourceLength do
begin
Inc(Iterator);
FChar := Ord(Source[Iterator]);
if FChar >= $80 then
begin
Inc(Iterator);
if Iterator > SourceLength then break;
FChar := FChar and $3F;
if (FChar and $20) <> 0 then
begin
FChar := FChar and $1F;
NChar := Ord(Source[Iterator]);
if (NChar and $C0) <> $80 then break;
FChar := (FChar shl 6) or (NChar and $3F);
Inc(Iterator);
if Iterator > SourceLength then break;
end;
NChar := Ord(Source[Iterator]);
if (NChar and $C0) <> $80 then break;
Result := Result + WideChar((FChar shl 6) or (NChar and $3F));
end
else
Result := Result + WideChar(FChar);
end;
end;
{ --------------------------------------------------------------------------- }
procedure SetTagItem(const FieldName, FieldValue: string; var Tag: TagInfo);
var
Iterator: Byte;
begin
{ Set tag item if supported field found }
for Iterator := 1 to APE_FIELD_COUNT do
if UpperCase(FieldName) = UpperCase(APE_FIELD[Iterator]) then
if Tag.Version > APE_VERSION_1_0 then
Tag.Field[Iterator] := ConvertFromUTF8(FieldValue)
else
Tag.Field[Iterator] := FieldValue;
end;
{ --------------------------------------------------------------------------- }
procedure ReadFields(const FileName: string; var Tag: TagInfo);
var
SourceFile: file;
FieldName: string;
FieldValue: array [1..250] of Char;
NextChar: Char;
Iterator, ValueSize, ValuePosition, FieldFlags: Integer;
begin
try
{ Set read-access, open file }
AssignFile(SourceFile, FileName);
FileMode := 0;
Reset(SourceFile, 1);
Seek(SourceFile, Tag.FileSize - Tag.DataShift - Tag.Size);
{ Read all stored fields }
for Iterator := 1 to Tag.Fields do
begin
FillChar(FieldValue, SizeOf(FieldValue), 0);
BlockRead(SourceFile, ValueSize, SizeOf(ValueSize));
BlockRead(SourceFile, FieldFlags, SizeOf(FieldFlags));
FieldName := '';
repeat
BlockRead(SourceFile, NextChar, SizeOf(NextChar));
FieldName := FieldName + NextChar;
until Ord(NextChar) = 0;
ValuePosition := FilePos(SourceFile);
BlockRead(SourceFile, FieldValue, ValueSize mod SizeOf(FieldValue));
SetTagItem(Trim(FieldName), Trim(FieldValue), Tag);
Seek(SourceFile, ValuePosition + ValueSize);
end;
CloseFile(SourceFile);
except
end;
end;
{ --------------------------------------------------------------------------- }
function GetTrack(const TrackString: string): Byte;
var
Index, Value, Code: Integer;
begin
{ Get track from string }
Index := Pos('/', TrackString);
if Index = 0 then Val(TrackString, Value, Code)
else Val(Copy(TrackString, 1, Index - 1), Value, Code);
if Code = 0 then Result := Value
else Result := 0;
end;
{ --------------------------------------------------------------------------- }
function TruncateFile(const FileName: string; TagSize: Integer): Boolean;
var
SourceFile: file;
begin
try
Result := true;
{ Allow write-access and open file }
FileSetAttr(FileName, 0);
AssignFile(SourceFile, FileName);
FileMode := 2;
Reset(SourceFile, 1);
{ Delete tag }
Seek(SourceFile, FileSize(SourceFile) - TagSize);
Truncate(SourceFile);
CloseFile(SourceFile);
except
{ Error }
Result := false;
end;
end;
{ --------------------------------------------------------------------------- }
procedure BuildFooter(var Tag: TagInfo);
var
Iterator: Integer;
begin
{ Build tag footer }
Tag.ID := APE_ID;
Tag.Version := APE_VERSION_1_0;
Tag.Size := APE_TAG_FOOTER_SIZE;
for Iterator := 1 to APE_FIELD_COUNT do
if Tag.Field[Iterator] <> '' then
begin
Inc(Tag.Size, Length(APE_FIELD[Iterator] + Tag.Field[Iterator]) + 10);
Inc(Tag.Fields);
end;
end;
{ --------------------------------------------------------------------------- }
function AddToFile(const FileName: string; TagData: TStream): Boolean;
var
FileData: TFileStream;
begin
try
{ Add tag data to file }
FileData := TFileStream.Create(FileName, fmOpenWrite or fmShareExclusive);
FileData.Seek(0, soFromEnd);
TagData.Seek(0, soFromBeginning);
FileData.CopyFrom(TagData, TagData.Size);
FileData.Free;
Result := true;
except
{ Error }
Result := false;
end;
end;
{ --------------------------------------------------------------------------- }
function SaveTag(const FileName: string; Tag: TagInfo): Boolean;
var
TagData: TStringStream;
Iterator, ValueSize, Flags: Integer;
begin
{ Build and write tag fields and footer to stream }
TagData := TStringStream.Create('');
for Iterator := 1 to APE_FIELD_COUNT do
if Tag.Field[Iterator] <> '' then
begin
ValueSize := Length(Tag.Field[Iterator]) + 1;
Flags := 0;
TagData.Write(ValueSize, SizeOf(ValueSize));
TagData.Write(Flags, SizeOf(Flags));
TagData.WriteString(APE_FIELD[Iterator] + #0);
TagData.WriteString(Tag.Field[Iterator] + #0);
end;
BuildFooter(Tag);
TagData.Write(Tag, APE_TAG_FOOTER_SIZE);
{ Add created tag to file }
Result := AddToFile(FileName, TagData);
TagData.Free;
end;
{ ********************** Private functions & procedures ********************* }
procedure TAPEtag.FSetTitle(const NewTitle: string);
begin
{ Set song title }
FTitle := Trim(NewTitle);
end;
{ --------------------------------------------------------------------------- }
procedure TAPEtag.FSetArtist(const NewArtist: string);
begin
{ Set artist name }
FArtist := Trim(NewArtist);
end;
{ --------------------------------------------------------------------------- }
procedure TAPEtag.FSetAlbum(const NewAlbum: string);
begin
{ Set album title }
FAlbum := Trim(NewAlbum);
end;
{ --------------------------------------------------------------------------- }
procedure TAPEtag.FSetTrack(const NewTrack: Byte);
begin
{ Set track number }
FTrack := NewTrack;
end;
{ --------------------------------------------------------------------------- }
procedure TAPEtag.FSetYear(const NewYear: string);
begin
{ Set release year }
FYear := Trim(NewYear);
end;
{ --------------------------------------------------------------------------- }
procedure TAPEtag.FSetGenre(const NewGenre: string);
begin
{ Set genre name }
FGenre := Trim(NewGenre);
end;
{ --------------------------------------------------------------------------- }
procedure TAPEtag.FSetComment(const NewComment: string);
begin
{ Set comment }
FComment := Trim(NewComment);
end;
{ --------------------------------------------------------------------------- }
procedure TAPEtag.FSetCopyright(const NewCopyright: string);
begin
{ Set copyright information }
FCopyright := Trim(NewCopyright);
end;
{ ********************** Public functions & procedures ********************** }
constructor TAPEtag.Create;
begin
{ Create object }
inherited;
ResetData;
end;
{ --------------------------------------------------------------------------- }
procedure TAPEtag.ResetData;
begin
{ Reset all variables }
FExists := false;
FVersion := 0;
FSize := 0;
FTitle := '';
FArtist := '';
FAlbum := '';
FTrack := 0;
FYear := '';
FGenre := '';
FComment := '';
FCopyright := '';
end;
{ --------------------------------------------------------------------------- }
function TAPEtag.ReadFromFile(const FileName: string): Boolean;
var
Tag: TagInfo;
begin
{ Reset data and load footer from file to variable }
ResetData;
FillChar(Tag, SizeOf(Tag), 0);
Result := ReadFooter(FileName, Tag);
{ Process data if loaded and footer valid }
if (Result) and (Tag.ID = APE_ID) then
begin
FExists := true;
{ Fill properties with footer data }
FVersion := Tag.Version;
FSize := Tag.Size;
{ Get information from fields }
ReadFields(FileName, Tag);
FTitle := Tag.Field[1];
FArtist := Tag.Field[2];
FAlbum := Tag.Field[3];
FTrack := GetTrack(Tag.Field[4]);
FYear := Tag.Field[5];
FGenre := Tag.Field[6];
FComment := Tag.Field[7];
FCopyright := Tag.Field[8];
end;
end;
{ --------------------------------------------------------------------------- }
function TAPEtag.RemoveFromFile(const FileName: string): Boolean;
var
Tag: TagInfo;
begin
{ Remove tag from file if found }
FillChar(Tag, SizeOf(Tag), 0);
if ReadFooter(FileName, Tag) then
begin
if Tag.ID <> APE_ID then Tag.Size := 0;
if (Tag.Flags shr 31) > 0 then Inc(Tag.Size, APE_TAG_HEADER_SIZE);
Result := TruncateFile(FileName, Tag.DataShift + Tag.Size)
end
else
Result := false;
end;
{ --------------------------------------------------------------------------- }
function TAPEtag.SaveToFile(const FileName: string): Boolean;
var
Tag: TagInfo;
begin
{ Prepare tag data and save to file }
FillChar(Tag, SizeOf(Tag), 0);
Tag.Field[1] := FTitle;
Tag.Field[2] := FArtist;
Tag.Field[3] := FAlbum;
if FTrack > 0 then Tag.Field[4] := IntToStr(FTrack);
Tag.Field[5] := FYear;
Tag.Field[6] := FGenre;
Tag.Field[7] := FComment;
Tag.Field[8] := FCopyright;
{ Delete old tag if exists and write new tag }
Result := (RemoveFromFile(FileName)) and (SaveTag(FileName, Tag));
end;
end.
|
unit Ths.Erp.Database.Table.Adres;
interface
{$I ThsERP.inc}
uses
SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils,
FireDAC.Stan.Param, System.Variants, Data.DB,
Ths.Erp.Database,
Ths.Erp.Database.Table
, Ths.Erp.Database.Table.SysCountry
, Ths.Erp.Database.Table.SysCity
;
type
TAdres = class(TTable)
private
FUlkeID: TFieldDB;
FSehirID: TFieldDB;
FIlce: TFieldDB;
FMahalle: TFieldDB;
FCadde: TFieldDB;
FSokak: TFieldDB;
FBina: TFieldDB;
FKapiNo: TFieldDB;
FPostaKutusu: TFieldDB;
FPostaKodu: TFieldDB;
FWebSitesi: TFieldDB;
FePostaAdresi: TFieldDB;
protected
procedure BusinessSelect(pFilter: string; pLock: Boolean;
pPermissionControl: Boolean); override;
published
constructor Create(OwnerDatabase:TDatabase);override;
public
procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override;
procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override;
procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override;
procedure Update(pPermissionControl: Boolean=True); override;
function Clone():TTable;override;
Property UlkeID: TFieldDB read FUlkeID write FUlkeID;
Property SehirID: TFieldDB read FSehirID write FSehirID;
Property Ilce: TFieldDB read FIlce write FIlce;
Property Mahalle: TFieldDB read FMahalle write FMahalle;
Property Cadde: TFieldDB read FCadde write FCadde;
Property Sokak: TFieldDB read FSokak write FSokak;
Property Bina: TFieldDB read FBina write FBina;
Property KapiNo: TFieldDB read FKapiNo write FKapiNo;
Property PostaKutusu: TFieldDB read FPostaKutusu write FPostaKutusu;
Property PostaKodu: TFieldDB read FPostaKodu write FPostaKodu;
Property WebSitesi: TFieldDB read FWebSitesi write FWebSitesi;
Property ePostaAdresi: TFieldDB read FePostaAdresi write FePostaAdresi;
end;
implementation
uses
Ths.Erp.Constants,
Ths.Erp.Database.Singleton;
constructor TAdres.Create(OwnerDatabase:TDatabase);
begin
TableName := 'adres';
SourceCode := '1000';
inherited Create(OwnerDatabase);
FUlkeID := TFieldDB.Create('ulke_id', ftInteger, 0, 0, True, False);
FUlkeID.FK.FKTable := TSysCountry.Create(Database);
FUlkeID.FK.FKCol := TFieldDB.Create(TSysCountry(FUlkeID.FK.FKTable).CountryName.FieldName, TSysCountry(FUlkeID.FK.FKTable).CountryName.FieldType, '', 0, False, False);
FSehirID := TFieldDB.Create('sehir_id', ftInteger, 0, 0, True, False);
FSehirID.FK.FKTable := TSysCity.Create(Database);
FSehirID.FK.FKCol := TFieldDB.Create(TSysCity(FSehirID.FK.FKTable).CityName.FieldName, TSysCity(FSehirID.FK.FKTable).CityName.FieldType, '', 0, False, False);
FIlce := TFieldDB.Create('ilce', ftString, '', 0, False, True);
FMahalle := TFieldDB.Create('mahalle', ftString, '', 0, False, True);
FCadde := TFieldDB.Create('cadde', ftString, '', 0, False, True);
FSokak := TFieldDB.Create('sokak', ftString, '', 0, False, True);
FBina := TFieldDB.Create('bina', ftString, '', 0, False, True);
FKapiNo := TFieldDB.Create('kapi_no', ftString, '', 0, False, True);
FPostaKutusu := TFieldDB.Create('posta_kutusu', ftString, '', 0, False, True);
FPostaKodu := TFieldDB.Create('posta_kodu', ftString, '', 0, False, True);
FWebSitesi := TFieldDB.Create('web_sitesi', ftString, '', 0, False, True);
FePostaAdresi := TFieldDB.Create('eposta_adresi', ftString, '', 0, False, True);
end;
procedure TAdres.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
with QueryOfDS do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FUlkeID.FieldName,
ColumnFromIDCol(TSysCountry(FUlkeID.FK.FKTable).CountryName.FieldName, FUlkeID.FK.FKTable.TableName, FUlkeID.FieldName, FUlkeID.FK.FKCol.FieldName, TableName),
TableName + '.' + FSehirID.FieldName,
ColumnFromIDCol(TSysCity(FSehirID.FK.FKTable).CityName.FieldName, FSehirID.FK.FKTable.TableName, FSehirID.FieldName, FSehirID.FK.FKCol.FieldName, TableName),
TableName + '.' + FIlce.FieldName,
TableName + '.' + FMahalle.FieldName,
TableName + '.' + FCadde.FieldName,
TableName + '.' + FSokak.FieldName,
TableName + '.' + FBina.FieldName,
TableName + '.' + FKapiNo.FieldName,
TableName + '.' + FPostaKutusu.FieldName,
TableName + '.' + FPostaKodu.FieldName,
TableName + '.' + FWebSitesi.FieldName,
TableName + '.' + FePostaAdresi.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
Active := True;
Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID';
Self.DataSource.DataSet.FindField(FUlkeID.FieldName).DisplayLabel := 'Ülke ID';
Self.DataSource.DataSet.FindField(FUlkeID.FK.FKCol.FieldName).DisplayLabel := 'Ülke';
Self.DataSource.DataSet.FindField(FSehirID.FieldName).DisplayLabel := 'Şehir ID';
Self.DataSource.DataSet.FindField(FSehirID.FK.FKCol.FieldName).DisplayLabel := 'Şehir';
Self.DataSource.DataSet.FindField(FIlce.FieldName).DisplayLabel := 'İlçe';
Self.DataSource.DataSet.FindField(FMahalle.FieldName).DisplayLabel := 'Mahalle';
Self.DataSource.DataSet.FindField(FCadde.FieldName).DisplayLabel := 'Cadde';
Self.DataSource.DataSet.FindField(FSokak.FieldName).DisplayLabel := 'Sokak';
Self.DataSource.DataSet.FindField(FBina.FieldName).DisplayLabel := 'Bina';
Self.DataSource.DataSet.FindField(FKapiNo.FieldName).DisplayLabel := 'Kapı No';
Self.DataSource.DataSet.FindField(FPostaKutusu.FieldName).DisplayLabel := 'Posta Kutusu';
Self.DataSource.DataSet.FindField(FPostaKodu.FieldName).DisplayLabel := 'Posta Kodu';
Self.DataSource.DataSet.FindField(FWebSitesi.FieldName).DisplayLabel := 'Web Sitesi';
Self.DataSource.DataSet.FindField(FePostaAdresi.FieldName).DisplayLabel := 'E-Posta Adresi';
end;
end;
end;
procedure TAdres.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
if (pLock) then
pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT';
with QueryOfList do
begin
Close;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FUlkeID.FieldName,
ColumnFromIDCol(TSysCountry(FUlkeID.FK.FKTable).CountryName.FieldName, FUlkeID.FK.FKTable.TableName, FUlkeID.FieldName, FUlkeID.FK.FKCol.FieldName, TableName),
TableName + '.' + FSehirID.FieldName,
ColumnFromIDCol(TSysCity(FSehirID.FK.FKTable).CityName.FieldName, FSehirID.FK.FKTable.TableName, FSehirID.FieldName, FSehirID.FK.FKCol.FieldName, TableName),
TableName + '.' + FIlce.FieldName,
TableName + '.' + FMahalle.FieldName,
TableName + '.' + FCadde.FieldName,
TableName + '.' + FSokak.FieldName,
TableName + '.' + FBina.FieldName,
TableName + '.' + FKapiNo.FieldName,
TableName + '.' + FPostaKutusu.FieldName,
TableName + '.' + FPostaKodu.FieldName,
TableName + '.' + FWebSitesi.FieldName,
TableName + '.' + FePostaAdresi.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
FreeListContent();
List.Clear;
while NOT EOF do
begin
Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value);
FUlkeID.Value := FormatedVariantVal(FieldByName(FUlkeID.FieldName).DataType, FieldByName(FUlkeID.FieldName).Value);
FUlkeID.FK.FKCol.Value := FormatedVariantVal(FieldByName(FUlkeID.FK.FKCol.FieldName).DataType, FieldByName(FUlkeID.FK.FKCol.FieldName).Value);
FSehirID.Value := FormatedVariantVal(FieldByName(FSehirID.FieldName).DataType, FieldByName(FSehirID.FieldName).Value);
FSehirID.FK.FKCol.Value := FormatedVariantVal(FieldByName(FSehirID.FK.FKCol.FieldName).DataType, FieldByName(FSehirID.FK.FKCol.FieldName).Value);
FIlce.Value := FormatedVariantVal(FieldByName(FIlce.FieldName).DataType, FieldByName(FIlce.FieldName).Value);
FMahalle.Value := FormatedVariantVal(FieldByName(FMahalle.FieldName).DataType, FieldByName(FMahalle.FieldName).Value);
FCadde.Value := FormatedVariantVal(FieldByName(FCadde.FieldName).DataType, FieldByName(FCadde.FieldName).Value);
FSokak.Value := FormatedVariantVal(FieldByName(FSokak.FieldName).DataType, FieldByName(FSokak.FieldName).Value);
FBina.Value := FormatedVariantVal(FieldByName(FBina.FieldName).DataType, FieldByName(FBina.FieldName).Value);
FKapiNo.Value := FormatedVariantVal(FieldByName(FKapiNo.FieldName).DataType, FieldByName(FKapiNo.FieldName).Value);
FPostaKutusu.Value := FormatedVariantVal(FieldByName(FPostaKutusu.FieldName).DataType, FieldByName(FPostaKutusu.FieldName).Value);
FPostaKodu.Value := FormatedVariantVal(FieldByName(FPostaKodu.FieldName).DataType, FieldByName(FPostaKodu.FieldName).Value);
FWebSitesi.Value := FormatedVariantVal(FieldByName(FWebSitesi.FieldName).DataType, FieldByName(FWebSitesi.FieldName).Value);
FePostaAdresi.Value := FormatedVariantVal(FieldByName(FePostaAdresi.FieldName).DataType, FieldByName(FePostaAdresi.FieldName).Value);
List.Add(Self.Clone());
Next;
end;
Close;
end;
end;
end;
procedure TAdres.Insert(out pID: Integer; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptAddRecord, pPermissionControl) then
begin
with QueryOfInsert do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [
FUlkeID.FieldName,
FSehirID.FieldName,
FIlce.FieldName,
FMahalle.FieldName,
FCadde.FieldName,
FSokak.FieldName,
FBina.FieldName,
FKapiNo.FieldName,
FPostaKutusu.FieldName,
FPostaKodu.FieldName,
FWebSitesi.FieldName,
FePostaAdresi.FieldName
]);
NewParamForQuery(QueryOfInsert, FUlkeID);
NewParamForQuery(QueryOfInsert, FSehirID);
NewParamForQuery(QueryOfInsert, FIlce);
NewParamForQuery(QueryOfInsert, FMahalle);
NewParamForQuery(QueryOfInsert, FCadde);
NewParamForQuery(QueryOfInsert, FSokak);
NewParamForQuery(QueryOfInsert, FBina);
NewParamForQuery(QueryOfInsert, FKapiNo);
NewParamForQuery(QueryOfInsert, FPostaKutusu);
NewParamForQuery(QueryOfInsert, FPostaKodu);
NewParamForQuery(QueryOfInsert, FWebSitesi);
NewParamForQuery(QueryOfInsert, FePostaAdresi);
Open;
if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then
pID := Fields.FieldByName(Self.Id.FieldName).AsInteger
else
pID := 0;
EmptyDataSet;
Close;
end;
Self.notify;
end;
end;
procedure TAdres.Update(pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptUpdate, pPermissionControl) then
begin
with QueryOfUpdate do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [
FUlkeID.FieldName,
FSehirID.FieldName,
FIlce.FieldName,
FMahalle.FieldName,
FCadde.FieldName,
FSokak.FieldName,
FBina.FieldName,
FKapiNo.FieldName,
FPostaKutusu.FieldName,
FPostaKodu.FieldName,
FWebSitesi.FieldName,
FePostaAdresi.FieldName
]);
NewParamForQuery(QueryOfUpdate, FUlkeID);
NewParamForQuery(QueryOfUpdate, FSehirID);
NewParamForQuery(QueryOfUpdate, FIlce);
NewParamForQuery(QueryOfUpdate, FMahalle);
NewParamForQuery(QueryOfUpdate, FCadde);
NewParamForQuery(QueryOfUpdate, FSokak);
NewParamForQuery(QueryOfUpdate, FBina);
NewParamForQuery(QueryOfUpdate, FKapiNo);
NewParamForQuery(QueryOfUpdate, FPostaKutusu);
NewParamForQuery(QueryOfUpdate, FPostaKodu);
NewParamForQuery(QueryOfUpdate, FWebSitesi);
NewParamForQuery(QueryOfUpdate, FePostaAdresi);
NewParamForQuery(QueryOfUpdate, Id);
ExecSQL;
Close;
end;
Self.notify;
end;
end;
procedure TAdres.BusinessSelect(pFilter: string; pLock, pPermissionControl: Boolean);
var
n1: Integer;
begin
inherited;
for n1 := 0 to Self.List.Count-1 do
begin
if Assigned(TAdres(Self.List[n1]).FUlkeID.FK.FKTable) then
TAdres(Self.List[n1]).FUlkeID.FK.FKTable.SelectToList(
' AND ' + TAdres(Self.List[n1]).FUlkeID.FK.FKTable.TableName + '.' +
TSysCountry(TAdres(Self.List[n1]).FUlkeID.FK.FKTable).Id.FieldName + '=' + IntToStr(TAdres(Self.List[n1]).FUlkeID.Value), False, False);
if Assigned(TAdres(Self.List[n1]).FSehirID.FK.FKTable) then
TAdres(Self.List[n1]).FSehirID.FK.FKTable.SelectToList(
' AND ' + TAdres(Self.List[n1]).FSehirID.FK.FKTable.TableName + '.' +
TSysCity(TAdres(Self.List[n1]).FSehirID.FK.FKTable).Id.FieldName + '=' + IntToStr(TAdres(Self.List[n1]).FSehirID.Value), False, False);
end;
end;
function TAdres.Clone():TTable;
begin
Result := TAdres.Create(Database);
Self.Id.Clone(TAdres(Result).Id);
FUlkeID.Clone(TAdres(Result).FUlkeID);
FSehirID.Clone(TAdres(Result).FSehirID);
FIlce.Clone(TAdres(Result).FIlce);
FMahalle.Clone(TAdres(Result).FMahalle);
FCadde.Clone(TAdres(Result).FCadde);
FSokak.Clone(TAdres(Result).FSokak);
FBina.Clone(TAdres(Result).FBina);
FKapiNo.Clone(TAdres(Result).FKapiNo);
FPostaKutusu.Clone(TAdres(Result).FPostaKutusu);
FPostaKodu.Clone(TAdres(Result).FPostaKodu);
FWebSitesi.Clone(TAdres(Result).FWebSitesi);
FePostaAdresi.Clone(TAdres(Result).FePostaAdresi);
end;
end.
|
unit UpdatePASUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls, ComCtrls, Buttons, ShellAPI;
type
TUpdatePASForm = class(TForm)
StartCopyTimer: TTimer;
Label1: TLabel;
CancelButton: TBitBtn;
TryLabel: TLabel;
FileCopyAnimate: TAnimate;
procedure FormCreate(Sender: TObject);
procedure StartCopyTimerTimer(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
SourceFileName, LocalFileName, StartingDirectory : String;
FileSize : LongInt;
Cancelled : Boolean;
NumberOfTries : Integer;
Procedure RestartPAS(Parameter : String);
end;
var
UpdatePASForm: TUpdatePASForm;
implementation
{$R *.DFM}
{==================================================================}
Function CopyOneFile(SourceName,
DestinationName : String) : Boolean;
{Actual copy of file routine that copies from a fully qualified source file name
to a fully qualified destination name.}
var
SourceLen, DestLen : Integer;
SourceNamePChar, DestNamePChar : PChar;
begin
SourceLen := Length(SourceName);
DestLen := Length(DestinationName);
SourceNamePChar := StrAlloc(SourceLen + 1);
DestNamePChar := StrAlloc(DestLen + 1);
StrPCopy(SourceNamePChar, SourceName);
StrPCopy(DestNamePChar, DestinationName);
Result := CopyFile(SourceNamePChar, DestNamePChar, False);
StrDispose(SourceNamePChar);
StrDispose(DestNamePChar);
end; {CopyOneFile}
{======================================================}
Procedure TUpdatePASForm.RestartPAS(Parameter : String);
{Start PAS up again.}
var
ProgramToExecutePChar, ParameterPChar, StartingDirectoryPChar : PChar;
TempLen : Integer;
begin
TempLen := Length(LocalFileName);
ProgramToExecutePChar := StrAlloc(TempLen + 1);
StrPCopy(ProgramToExecutePChar, LocalFileName);
If (Parameter = '')
then ParameterPChar := nil
else
begin
TempLen := Length(Parameter);
ParameterPChar := StrAlloc(TempLen + 1);
StrPCopy(ParameterPChar, Parameter);
end;
TempLen := Length(StartingDirectory);
StartingDirectoryPChar := StrAlloc(TempLen + 1);
StrPCopy(StartingDirectoryPChar, StartingDirectory);
(* WinExec(ProgramToExecutePChar, SW_SHOW);*)
{FXX05082003-2(2.07a): Actually, start it using ShellExecute so that we can specify the directory.}
ShellExecute(Handle, 'open', ProgramToExecutePChar, ParameterPChar, StartingDirectoryPChar, SW_SHOW);
StrDispose(ProgramToExecutePChar);
StrDispose(ParameterPChar);
Close;
Application.Terminate;
end; {RestartPAS}
{====================================================================}
Function ReturnPath(Path : String) : String;
{Remove the file name from a path.}
var
TempLen, Index : Integer;
SlashFound : Boolean;
begin
TempLen := Length(Path);
Index := TempLen;
SlashFound := False;
while ((Index > 0) and
(not SlashFound)) do
If (Path[Index] = '\')
then SlashFound := True
else Index := Index - 1;
If (Index = 0)
then Result := ''
else Result := Copy(Path, 1, Index);
end; {ReturnPath}
{======================================================}
Procedure TUpdatePASForm.FormCreate(Sender: TObject);
var
I, EqualsPOS : Integer;
begin
Cancelled := False;
NumberOfTries := 0;
For I := 1 to ParamCount do
begin
If (Pos('SOURCEFILE', ANSIUppercase(ParamStr(I))) > 0)
then
begin
EqualsPos := Pos('=', ParamStr(I));
SourceFileName := Copy(ParamStr(I), (EqualsPos + 1), 200);
SourceFileName := Trim(SourceFileName);
end; {If (Pos('SOURCEFILE', ANSIUppercase(ParamStr(I))) > 0)}
If (Pos('LOCALFILE', ANSIUppercase(ParamStr(I))) > 0)
then
begin
EqualsPos := Pos('=', ParamStr(I));
LocalFileName := Copy(ParamStr(I), (EqualsPos + 1), 200);
LocalFileName := Trim(LocalFileName);
end; {If (Pos('LOCALFILE', ANSIUppercase(ParamStr(I))) > 0)}
end; {For I := 1 to ParamCount do}
try
Application.Icon.LoadFromFile('PASUpdate.ico');
except
end;
StartingDirectory := ReturnPath(SourceFileName);
FileCopyAnimate.Active := True;
StartCopyTimer.Enabled := True;
end; {FormCreate}
{======================================================}
Procedure TUpdatePASForm.StartCopyTimerTimer(Sender: TObject);
begin
StartCopyTimer.Enabled := False;
Refresh;
Application.ProcessMessages;
If CopyOneFile(SourceFileName, LocalFileName)
then RestartPAS('')
else
begin
TryLabel.Visible := True;
NumberOfTries := NumberOfTries + 1;
TryLabel.Caption := 'Attempt #' + IntToStr(NumberOfTries);
Application.ProcessMessages;
If not Cancelled
then StartCopyTimer.Enabled := True;
end; {else of If CopyOneFile(SourceFileName, LocalFileName)}
end; {StartCopyTimerTimer}
{======================================================}
Procedure TUpdatePASForm.CancelButtonClick(Sender: TObject);
begin
Cancelled := True;
RestartPAS('CANCELUPDATE');
end; {CancelButtonClick}
end.
|
unit FMainForm;
interface
uses
Winapi.Windows,
System.SysUtils, System.Classes, System.Actions, System.Math,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ValEdit,
Vcl.Grids, Vcl.Menus, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ToolWin,
Vcl.ExtCtrls, Vcl.ActnList, Vcl.ImgList,
//GLS
GLHeightTileFile;
type
TSrc = record
fs : TFileStream;
x, y, w, h : Integer;
format : Integer;
FlipRotate : Integer;
end;
PSrc = ^TSrc;
TMainForm = class(TForm)
MainMenu: TMainMenu;
StringGrid: TStringGrid;
File1: TMenuItem;
ActionList: TActionList;
ImageList: TImageList;
ACOpen: TAction;
ACSave: TAction;
ACExit: TAction;
Open1: TMenuItem;
Save1: TMenuItem;
N1: TMenuItem;
Exit1: TMenuItem;
Panel1: TPanel;
Label1: TLabel;
Label2: TLabel;
EDHTFName: TEdit;
EDDEMPath: TEdit;
BUDEMPath: TButton;
BUPickHTF: TButton;
ToolBar: TToolBar;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
DEMs1: TMenuItem;
ACNewDEM: TAction;
ACRemoveDEM: TAction;
ToolButton4: TToolButton;
ToolButton5: TToolButton;
AddDEMsource1: TMenuItem;
RemoveDEMsource1: TMenuItem;
SDHTF: TSaveDialog;
PopupMenu: TPopupMenu;
AddDEMsource2: TMenuItem;
RemoveDEMsource2: TMenuItem;
MIAbout: TMenuItem;
CBType: TComboBox;
CBFile: TComboBox;
Label3: TLabel;
EDSizeX: TEdit;
EDSizeY: TEdit;
Label4: TLabel;
Label5: TLabel;
EDDefaultZ: TEdit;
ODTerrainPack: TOpenDialog;
SDTerrainPack: TSaveDialog;
ToolButton6: TToolButton;
ACProcess: TAction;
ToolButton7: TToolButton;
N2: TMenuItem;
Process1: TMenuItem;
PanelFoot: TPanel;
ProgressBar: TProgressBar;
EDTileSize: TEdit;
Label6: TLabel;
ToolButton8: TToolButton;
ACViewer: TAction;
N3: TMenuItem;
HTFViewer1: TMenuItem;
ToolButton9: TToolButton;
ODPath: TOpenDialog;
Label7: TLabel;
EDTileOverlap: TEdit;
Label8: TLabel;
EDZFilter: TEdit;
Label9: TLabel;
EDZScale: TEdit;
CBWholeOnly: TCheckBox;
CBFlipRotate: TComboBox;
procedure ACExitExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure BUDEMPathClick(Sender: TObject);
procedure BUPickHTFClick(Sender: TObject);
procedure MIAboutClick(Sender: TObject);
procedure ActionListUpdate(Action: TBasicAction; var Handled: Boolean);
procedure ACNewDEMExecute(Sender: TObject);
procedure ACRemoveDEMExecute(Sender: TObject);
procedure StringGridSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
procedure CBTypeChange(Sender: TObject);
procedure ACSaveExecute(Sender: TObject);
procedure ACOpenExecute(Sender: TObject);
procedure EDDEMPathChange(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure EDDefaultZChange(Sender: TObject);
procedure ACProcessExecute(Sender: TObject);
procedure ACViewerExecute(Sender: TObject);
procedure EDZFilterChange(Sender: TObject);
procedure EDZScaleChange(Sender: TObject);
private
{ Private declarations }
sources : array of TSrc;
defaultZ : SmallInt;
filterZ : SmallInt;
zScale : Single;
procedure Parse;
procedure Cleanup;
procedure SrcExtractFlip(src : PSrc; relX, relY, len : Integer; dest : PSmallInt);
procedure SrcExtract(src : PSrc; relX, relY, len : Integer; dest : PSmallInt; DiagFlip:boolean=false);
procedure WorldExtract(x, y, len : Integer; dest : PSmallInt);
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
uses
FViewerForm;
{$R *.dfm}
procedure TMainForm.FormCreate(Sender: TObject);
var
i : Integer;
begin
with ActionList do
for i:=0 to ActionCount-1 do with TAction(Actions[i]) do
Hint:=Caption;
with StringGrid do begin
Cells[0, 0]:='File Name'; ColWidths[0]:=140;
Cells[1, 0]:='World Offset'; ColWidths[1]:=80;
Cells[2, 0]:='Size (rotated)'; ColWidths[2]:=80;
Cells[3, 0]:='Data type'; ColWidths[3]:=120;
Cells[4, 0]:='Flip and Rotate'; ColWidths[4]:=110;
Row:=0;
end;
zScale:=1;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
Cleanup;
end;
procedure TMainForm.ACExitExecute(Sender: TObject);
begin
Close;
end;
procedure TMainForm.BUDEMPathClick(Sender: TObject);
begin
ODPath.InitialDir:=EDDEMPath.Text;
ODPath.FileName:=EDDEMPath.Text+'pick a dummy.file';
if ODPath.Execute then
EDDEMPath.Text:=ExtractFilePath(ODPath.FileName);
end;
procedure TMainForm.BUPickHTFClick(Sender: TObject);
begin
SDHTF.FileName:=EDHTFName.Text;
if SDHTF.Execute then
EDHTFName.Text:=SDHTF.FileName;
end;
procedure TMainForm.MIAboutClick(Sender: TObject);
begin
ShowMessage(Caption+#13#10#13#10
+'HTF Generation Utility'#13#10
+'Part of GLScene library.'#13#10#13#10
+'http://glscene.org');
end;
procedure TMainForm.ActionListUpdate(Action: TBasicAction;
var Handled: Boolean);
begin
ACRemoveDEM.Enabled:=(StringGrid.RowCount>2);
end;
procedure TMainForm.ACNewDEMExecute(Sender: TObject);
begin
StringGrid.RowCount:=StringGrid.RowCount+1;
end;
procedure TMainForm.ACRemoveDEMExecute(Sender: TObject);
var
i : Integer;
begin
with StringGrid do begin
i:=Row;
if i<RowCount-1 then begin
while i<RowCount-1 do begin
Rows[i]:=Rows[i+1];
Inc(i);
end;
end else Row:=i-1;
RowCount:=RowCount-1;
end;
end;
procedure TMainForm.StringGridSelectCell(Sender: TObject; ACol,
ARow: Integer; var CanSelect: Boolean);
procedure SetCB(const cb : TComboBox);
var
r : TRect;
i : Integer;
begin
r:=StringGrid.CellRect(ACol, ARow);
cb.Left:=r.Left+StringGrid.Left;
cb.Top:=r.Top+StringGrid.Top;
cb.Width:=r.Right+1-r.Left;
i:=cb.Items.IndexOf(StringGrid.Cells[ACol, ARow]);
if i>=0 then
cb.ItemIndex:=i
else cb.Text:=StringGrid.Cells[ACol, ARow];
if Visible then
cb.SetFocus;
end;
begin
if ARow>0 then begin
if ACol=0 then begin
CBFile.Visible:=True;
SetCB(CBFile);
end else CBFile.Visible:=False;
if ACol=3 then begin
CBType.Visible:=True;
SetCB(CBType);
end else CBType.Visible:=False;
if ACol=4 then begin
CBFlipRotate.Visible:=True;
SetCB(CBFlipRotate);
end else CBFlipRotate.Visible:=False;
CanSelect:=True;
end;
end;
procedure TMainForm.CBTypeChange(Sender: TObject);
begin
with StringGrid do
Cells[Col, Row]:=(Sender as TComboBox).Text;
end;
procedure TMainForm.ACSaveExecute(Sender: TObject);
var
i : Integer;
sl, sg : TStringList;
begin
if SDTerrainPack.Execute then begin
sl:=TStringList.Create;
with sl do begin
Values['HTFName']:=EDHTFName.Text;
Values['WorldSizeX']:=EDSizeX.Text;
Values['WorldSizeY']:=EDSizeY.Text;
Values['TileSize']:=EDTileSize.Text;
Values['TileOverlap']:=EDTileOverlap.Text;
Values['DefaultZ']:=EDDefaultZ.Text;
Values['FilterZ']:=EDZFilter.Text;
Values['ZScale']:=EDZScale.Text;
Values['DEMPath']:=EDDEMPath.Text;
Values['WholeTiles']:=IntToStr(Integer(CBWholeOnly.Checked));
sg:=TStringList.Create;
for i:=1 to StringGrid.RowCount-1 do
sg.Add(StringGrid.Rows[i].CommaText);
Values['DEMs']:=sg.CommaText;
sg.Free;
end;
sl.SaveToFile(SDTerrainPack.FileName);
sl.Free;
end;
end;
procedure TMainForm.ACOpenExecute(Sender: TObject);
var
i : Integer;
sl, sg : TStringList;
begin
if ODTerrainPack.Execute then begin
sl:=TStringList.Create;
sl.LoadFromFile(ODTerrainPack.FileName);
with sl do begin
EDHTFName.Text:=Values['HTFName'];
EDSizeX.Text:=Values['WorldSizeX'];
EDSizeY.Text:=Values['WorldSizeY'];
EDTileSize.Text:=Values['TileSize'];
EDTileOverlap.Text:=Values['TileOverlap'];
EDDefaultZ.Text:=Values['DefaultZ'];
EDZFilter.Text:=Values['FilterZ'];
EDZScale.Text:=Values['ZScale'];
EDDEMPath.Text:=Values['DEMPath'];
CBWholeOnly.Checked:=(Values['WholeTiles']='1');
sg:=TStringList.Create;
sg.CommaText:=Values['DEMs'];
StringGrid.RowCount:=sg.Count+1;
for i:=0 to sg.Count-1 do
StringGrid.Rows[i+1].CommaText:=sg[i];
sg.Free;
end;
sl.Free;
SDTerrainPack.FileName:=ODTerrainPack.FileName;
end;
end;
procedure TMainForm.EDDEMPathChange(Sender: TObject);
var
f : TSearchRec;
r : Integer;
begin
CBFile.Items.Clear;
r:=FindFirst(EDDEMPath.Text+'\*.*', faAnyFile, f);
while r=0 do begin
if (f.Attr and faDirectory)=0 then
CBFile.Items.Add(f.Name);
r:=FindNext(f);
end;
FindClose(f);
end;
procedure TMainForm.EDDefaultZChange(Sender: TObject);
begin
defaultZ:=StrToIntDef(EDDefaultZ.Text, 0);
if EDZFilter.Text='' then
filterZ:=defaultZ;
end;
procedure TMainForm.EDZFilterChange(Sender: TObject);
begin
filterZ:=StrToIntDef(EDZFilter.Text, defaultZ);
end;
procedure TMainForm.EDZScaleChange(Sender: TObject);
begin
zScale:=StrToFloatDef(EDZScale.Text, 1.0);
end;
procedure TMainForm.Parse;
var
i, p : Integer;
row : TStrings;
begin
Cleanup;
SetLength(sources, StringGrid.RowCount-1);
for i:=0 to High(sources) do begin
row:=StringGrid.Rows[i+1];
sources[i].fs:=TFileStream.Create(EDDEMPath.Text+'\'+row[0], fmOpenRead+fmShareDenyNone);
p:=Pos(',', row[1]);
sources[i].x:=StrToInt(Copy(row[1], 1, p-1));
sources[i].y:=StrToInt(Copy(row[1], p+1, MaxInt));
p:=Pos('x', row[2]);
sources[i].w:=StrToInt(Copy(row[2], 1, p-1));
sources[i].h:=StrToInt(Copy(row[2], p+1, MaxInt));
sources[i].format:=CBType.Items.IndexOf(row[3]); //File format
sources[i].FlipRotate:=CBFlipRotate.Items.IndexOf(row[4]); //Flip and Rotate
end;
end;
procedure TMainForm.Cleanup;
var
i : Integer;
begin
for i:=0 to High(sources) do
sources[i].fs.Free;
SetLength(sources, 0);
end;
procedure TMainForm.SrcExtractFlip(src : PSrc; relX, relY, len : Integer; dest : PSmallInt);
var i:integer;
val:SmallInt;
begin
if src.FlipRotate<=0 then SrcExtract(src,relX, relY, len, dest) //None
else begin
for i:=0 to len-1 do begin
case src.FlipRotate of
//0 : SrcExtract(src,relX, relY+i,1,@val); //No change ( )
1 : SrcExtract(src,src.w-(relX+i),relY,1,@val); //H-Flip (Flip)
2 : SrcExtract(src,relY,src.w-(relX+i),1,@val,true); //DiagFlip + H-Flip (90deg)
3 : SrcExtract(src,src.w-(relX+i),src.h-relY,1,@val); //H-Flip + V-Flip (180deg)
4 : SrcExtract(src,src.h-relY,(relX+i),1,@val,true); //DiagFlip + V-Flip (270deg)
5 : SrcExtract(src,src.h-relY,src.w-(relX+i),1,@val,true); //DiagFlip + V-Flip + H-Flip (Flip-90deg)
6 : SrcExtract(src,relX+i,src.h-relY,1,@val); //V-FLIP (Flip-180deg)
7 : SrcExtract(src,relY, relX+i,1,@val,true); //DiagFlip (Flip-270deg)
end;
PSmallIntArray(dest)[i]:=val;
end;
end;
end;
procedure TMainForm.SrcExtract(src : PSrc; relX, relY, len : Integer; dest : PSmallInt; DiagFlip:boolean=false);
var
i, c : Integer;
wd : Word;
buf : array of Single;
bmp : TBitmap;
rw : integer; //rotated width
begin
if DiagFlip then rw:=src.h else rw:=src.w;
with src^ do begin
case format of
0 : begin // 16bits Intel
fs.Position:=(relX+relY*rw)*2;
fs.Read(dest^, len*2);
end;
1 : begin // 16bits unsigned Intel
fs.Position:=(relX+relY*rw)*2;
fs.Read(dest^, len*2);
for i:=0 to len-1 do begin
wd:=PWord(Integer(dest)+i*2)^;
PSmallInt(Integer(dest)+i*2)^:=Integer(wd)-32768;
end;
end;
2 : begin // 16bits non-Intel
fs.Position:=(relX+relY*rw)*2;
fs.Read(dest^, len*2);
for i:=0 to len-1 do begin
wd:=PWord(Integer(dest)+i*2)^;
PWord(Integer(dest)+i*2)^:=((wd and 255) shl 8)+(wd shr 8);
end;
end;
3 : begin // VTP's BT single
fs.Position:=(relX+relY*rw)*4+256;
SetLength(buf, len);
fs.Read(buf[0], len*4);
for i:=0 to len-1 do
PSmallInt(Integer(dest)+i*2)^:=Round(buf[i]);
end;
4 : begin // windows BMP
bmp:=TBitmap.Create;
try
fs.Position:=0;
bmp.LoadFromStream(fs);
if DiagFlip then rw:=bmp.Width else rw:=bmp.Height;
for i:=0 to len-1 do begin
c:=bmp.Canvas.Pixels[relX+i, rw-relY-1];
PSmallInt(Integer(dest)+i*2)^:=(GetGValue(c)-128) shl 7;
end;
finally
bmp.Free;
end;
end;
5 : begin // 32bits FP Intel
fs.Position:=(relX+relY*rw)*4;
SetLength(buf, len);
fs.Read(buf[0], len*4);
for i:=0 to len-1 do
PSmallInt(Integer(dest)+i*2)^:=Round((buf[i]-0.5)*32000);
end;
6 : begin // DTED
fs.Position:=3434+(relX+relY*rw)*2 +(relY*12);
fs.Read(dest^, len*2);
for i:=0 to len-1 do begin
wd:=PWord(Integer(dest)+i*2)^;
PWord(Integer(dest)+i*2)^:=((wd and 255) shl 8)+(wd shr 8);
end;
end;
end;
end;
end;
procedure TMainForm.WorldExtract(x, y, len : Integer; dest : PSmallInt);
var
i, n, rx, ry : Integer;
src : PSrc;
begin
while len>0 do begin
src:=nil;
for i:=0 to High(sources) do begin
if (sources[i].x<=x) and (sources[i].y<=y)
and (x<sources[i].x+sources[i].w)
and (y<sources[i].y+sources[i].h) then begin
src:=@sources[i];
Break;
end;
end;
if Assigned(src) then begin
rx:=x-src.x;
ry:=y-src.y;
n:=len;
if rx+n>src.w then
n:=src.w-rx;
SrcExtractFlip(src, rx, ry, n, dest);
if filterZ<>defaultZ then begin
for i:=0 to n-1 do
if PSmallIntArray(dest)[i]=filterZ then
PSmallIntArray(dest)[i]:=defaultZ;
end;
if zScale<>1 then begin
for i:=0 to n-1 do
PSmallIntArray(dest)[i]:=Round(PSmallIntArray(dest)[i]*zScale);
end;
Dec(len, n);
Inc(dest, n);
Inc(x, n);
end else begin
dest^:=defaultZ;
Inc(dest);
Dec(len);
Inc(x);
end;
end;
end;
procedure TMainForm.ACProcessExecute(Sender: TObject);
var
x, y, wx, wy, ts, tx, ty, i, j, overlap : Integer;
n, maxN : Cardinal;
htf : THeightTileFile;
buf : array of SmallInt;
f : file of Byte;
begin
Screen.Cursor:=crHourGlass;
wx:=StrToInt(EDSizeX.Text);
wy:=StrToInt(EDSizeY.Text);
ts:=StrToInt(EDTileSize.Text);
overlap:=StrToInt(EDTileOverlap.Text);
Parse;
SetLength(buf, ts*ts);
htf:=THeightTileFile.CreateNew(EDHTFName.Text, wx, wy, ts);
htf.DefaultZ:=defaultZ;
ProgressBar.Max:=1000;
maxN:=Ceil(wx/ts)*Ceil(wy/ts);
n:=0;
ProgressBar.Position:=0;
y:=0; while y<wy do begin
ty:=wy+overlap-y;
if ty>ts then
ty:=ts;
x:=0; while x<wx do begin
tx:=wx+overlap-x;
if (not CBWholeOnly.Checked) or ((tx>=ts) and ((wy-y)>=ts)) then begin
if tx>ts then
tx:=ts;
for i:=0 to ty-1 do begin
WorldExtract(x, y+i, tx, @buf[i*ts]);
if overlap>0 then begin
for j:=tx to ts-1 do
buf[i*ts+j]:=buf[i*ts+tx-1];
end else begin
for j:=tx to ts-1 do
buf[i*ts+j]:=defaultZ;
end;
end;
if overlap>0 then begin
for i:=ty to ts-1 do for j:=0 to ts-1 do
buf[i*ts+j]:=buf[(i-1)*ts+j];
end else begin
for i:=ty to ts-1 do for j:=0 to ts-1 do
buf[i*ts+j]:=defaultZ;
end;
htf.CompressTile(x, y, ts, ts, @buf[0]);
end;
Inc(x, ts-overlap);
Inc(n);
ProgressBar.Position:=(n*1000) div maxN;
if (n and 15)=0 then begin
Application.ProcessMessages;
end;
end;
Inc(y, ts-overlap);
end;
htf.Free;
Cleanup;
Screen.Cursor:=crDefault;
AssignFile(f, EDHTFName.Text);
Reset(f);
i:=FileSize(f);
CloseFile(f);
ShowMessage( 'HTF file created.'#13#10#13#10
+IntToStr(i)+' bytes in file'#13#10
+'('+IntToStr(wx*wy*2)+' raw bytes)');
end;
procedure TMainForm.ACViewerExecute(Sender: TObject);
var
viewer : TViewerForm;
begin
viewer:=TViewerForm.Create(nil);
try
Viewer.htf:=THeightTileFile.Create(EDHTFName.Text); //R
Viewer.Caption:='HTFViewer - '+ExtractFileName(EDHTFName.Text); //R
viewer.ShowModal;
finally
viewer.Free;
end;
end;
end.
|
PROGRAM Test;
USES VectorClass, NaturalVectorClass, PrimeVectorClass;
PROCEDURE TestVector;
VAR v: Vector;
i: INTEGER;
success: BOOLEAN;
BEGIN (* TestVector *)
New(v, Init);
FOR i := 0 TO 9 DO BEGIN
v^.Add(i - 5);
END; (* FOR *)
v^.WriteVector;
WriteLn('IsFull? ', v^.IsFull);
v^.InsertElementAt(5, 20);
v^.WriteVector;
v^.GetElementAt(0, success, i);
IF (success) THEN BEGIN
WriteLn('Position: 0 | Element: ', i);
END ELSE BEGIN
WriteLn('Position in Vector not found.');
END; (* IF *)
v^.GetElementAt(6, success, i);
IF (success) THEN BEGIN
WriteLn('Position: 6 | Element: ', i);
END ELSE BEGIN
WriteLn('Position in Vector not found.');
END; (* IF *)
v^.GetElementAt(23, success, i);
IF (success) THEN BEGIN
WriteLn('Position: 23 | Element: ', i);
END ELSE BEGIN
WriteLn('Position 23 in Vector not found.');
END; (* IF *)
v^.GetElementAt(-6, success, i);
IF (success) THEN BEGIN
WriteLn('Position: -6 | Element: ', i);
END ELSE BEGIN
WriteLn('Position -6 in Vector not found.');
END; (* IF *)
WriteLn('GetSize: ', v^.GetSize);
WriteLn('GetCapa: ', v^.GetCapacity);
v^.Clear;
v^.WriteVector;
Dispose(v, Done);
END; (* TestVector *)
PROCEDURE TestNaturalVector;
VAR v: NaturalVector;
i: INTEGER;
BEGIN (* TestNaturalVector *)
New(v, Init);
FOR i := 0 TO 9 DO BEGIN
v^.Add(i - 5);
END; (* FOR *)
v^.WriteVector;
WriteLn('IsFull? ', v^.IsFull);
v^.InsertElementAt(5, 20);
v^.InsertElementAt(8, -6);
v^.WriteVector;
Dispose(v, Done);
END; (* TestNaturalVector *)
PROCEDURE TestPrimeVector;
VAR v: PrimeVector;
i: INTEGER;
BEGIN (* TestPrimeVector *)
New(v, Init);
FOR i := 1 TO 11 DO BEGIN
v^.Add(i);
END; (* FOR *)
v^.WriteVector;
WriteLn('IsFull? ', v^.IsFull);
v^.InsertElementAt(9, 31171);
v^.InsertElementAt(4, 31183);
v^.WriteVector;
Dispose(v, Done);
END; (* TestPrimeVector *)
BEGIN (* Test *)
TestVector;
TestNaturalVector;
TestPrimeVector;
END. (* Test *) |
unit PlotReadersAux;
interface
uses
Classes,
PlotReaders;
type
TRSFileReader = class(TDataReader)
private
FSettings: TStream;
public
procedure Read(const AFileName: String); override;
procedure Read(AStream: TStream); override;
class procedure FileFilters(Strings: TStrings); override;
class procedure FileExts(Strings: TStrings); override;
end;
TOOFileReader = class(TCSVFileReader)
class procedure FileFilters(Strings: TStrings); override;
class procedure FileExts(Strings: TStrings); override;
end;
TDagatronFileReaders = class(TCSVFileReader)
protected
procedure InitFloatFormat; override;
procedure ProcessString(const Str: String); override;
public
class procedure FileFilters(Strings: TStrings); override;
end;
implementation
uses
SysUtils,
OriStrings, SpectrumStrings, SpectrumSettings, SpectrumTypes;
{%region TRSFileReader}
procedure TRSFileReader.Read(const AFileName: String);
var
DataStream: TStream;
SetFile: String;
begin
SetFile := ChangeFileExt(AFileName, '.set');
if not FileExists(SetFile) then
raise ESpectrumError.CreateFmt(Err_RSNoSetFile, [SetFile]);
FSettings := TFileStream.Create(SetFile, fmOpenRead or fmShareDenyWrite);
try
DataStream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);
try
Read(DataStream);
finally
DataStream.Free;
end;
finally
FSettings.Free;
end;
end;
procedure TRSFileReader.Read(AStream: TStream);
var
Vers: Byte;
Buf: array [0..3] of Char;
dwAddrStart, dwAddrStop, dwAddrData: Cardinal;
Xmin, Xmax, Xstep: Double;
X: Double;
Y: Single;
I, IncValue: Integer;
begin
Buf[0] := #0; // warning suppress
Xmin := 0; // warning suppress
Xmax := 0; // warning suppress
Y := 0; // warning suppress
ResetResults;
ResetValues;
Vers := Preferences.RSFileVersion;
if Vers = 0 then
begin // try autodetect
AStream.Seek($0029, soFromBeginning);
AStream.Read(Buf, 4);
if (Buf[0] = '1') and (Buf[1] = '.') and (Buf[3] = '0') then
case Buf[2] of
'8': Vers := 1; // Version 1.80 - FSE 40GHz
'6': Vers := 2; // Version 1.60 - FSE 3GHz
end;
end;
case Vers of
1: {FSE 40Ghz}
begin
dwAddrStart := $21DB;
dwAddrStop := $21E3;
dwAddrData := $03B7;
end;
2: {FSE 3Ghz}
begin
dwAddrStart := $1E67;
dwAddrStop := $1EB8;
dwAddrData := $0847;
end;
else
raise ESpectrumError.Create(Err_RSUnknownVersion);
end;
FSettings.Seek(dwAddrStart, soFromBeginning);
FSettings.Read(Xmin, 8);
FSettings.Seek(dwAddrStop, soFromBeginning);
FSettings.Read(Xmax, 8);
Xstep := (Xmax - Xmin) / 499.0;
X := Xmin;
IncValue := 1 + Ord(Preferences.RSReadLowValues);
SetLength(FValuesX, 500 * IncValue);
SetLength(FValuesY, 500 * IncValue);
AStream.Seek(dwAddrData, soFromBeginning);
FValueIndex := 0;
I := 0;
while I < 500 do
begin
AStream.Read(Y, 4);
FValuesX[FValueIndex] := X;
FValuesY[FValueIndex] := Y;
Inc(FValueIndex, IncValue);
X := X + Xstep;
Inc(I);
end;
if Preferences.RSReadLowValues then
begin
X := Xmin;
FValueIndex := 1;
I := 0;
while I < 500 do
begin
AStream.Read(Y, 4);
FValuesX[FValueIndex] := X;
FValuesY[FValueIndex] := Y;
Inc(FValueIndex, IncValue);
X := X + Xstep;
Inc(I);
end;
end;
AddResult(FValuesX, FValuesY);
end;
class procedure TRSFileReader.FileFilters(Strings: TStrings);
begin
Strings.Add(Filter_RS);
end;
class procedure TRSFileReader.FileExts(Strings: TStrings);
begin
Strings.Add('tr1');
Strings.Add('tr2');
Strings.Add('tr3');
Strings.Add('tr4');
end;
{%endregion}
{%region TOOFileReader}
class procedure TOOFileReader.FileFilters(Strings: TStrings);
begin
Strings.Add(Filter_OO);
end;
class procedure TOOFileReader.FileExts(Strings: TStrings);
begin
Strings.Add('scope');
end;
{%endregion}
{%region TDagatronFileReaders}
procedure TDagatronFileReaders.InitFloatFormat;
begin
FFloatFmt.DecimalSeparator := '.';
end;
procedure TDagatronFileReaders.ProcessString(const Str: String);
var
S: String;
I: Integer;
P, P1: PChar;
Value: Double;
begin
S := '';
P := PChar(Str);
P1 := P;
repeat
Inc(P);
if P^ = #0 then
begin
// First column is timestamp, skip it.
// The rest columns are sticked together.
if CharPos(P1, ':') = 0 then
begin
S := S + P1;
end;
P1 := P + 1;
end;
until P1^ = #0;
// Remove all non digit chars from the end
for I := Length(S) downto 1 do
if S[I] in ['0'..'9'] then
begin
SetLength(S, I);
Break;
end;
// Skip some scrap (lines like "14:12:53 ð 0")
// and zero values (lines like "17:10:48 0")
// (samples are taken from a real file written by Dagatron counter)
if TryStrToFloat(S, Value, FFloatFmt) and (Value > 0) then
begin
CheckValuesSize;
if FValueIndex > 0 then
// Skip several consecutive identical values
if FValuesY[FValueIndex-1] = Value then Exit;
FValuesX[FValueIndex] := FOneColumnX;
FValuesY[FValueIndex] := Value;
FOneColumnX := FOneColumnX + Preferences.OneColumnInc;
Inc(FValueIndex);
end;
end;
class procedure TDagatronFileReaders.FileFilters(Strings: TStrings);
begin
Strings.Add(Filter_Dag);
end;
{%endregion}
end.
|
unit ReadingFrame;
interface
uses
Global,
LTClasses,
Generics.Collections,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ReadingQuestionFrame;
type
TfmReading = class(TFrame)
lbQuestionInput: TLabel;
ScrollBox1: TScrollBox;
ScrollBox2: TScrollBox;
lbText: TLabel;
lbTextNumber: TLabel;
private
{ Private declarations }
FCurrentQuiz: TReading;
FQuestionFrames: TObjectList<TfmReadingQuestion>;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Binding(Quiz: TQuiz);
function GetTestResultDetails: TList<TTestResultDetail>;
end;
implementation
{$R *.dfm}
{ TfmReading }
procedure TfmReading.Binding(Quiz: TQuiz);
var
I: Integer;
Frame: TfmReadingQuestion;
begin
FQuestionFrames.Clear;
FCurrentQuiz := Quiz as TReading;
lbTextNumber.Caption := IntToStr(FCurrentQuiz.ExampleNumber);
lbText.Caption := FCurrentQuiz.ExampleText;
for I := 0 to FCurrentQuiz.QuizList.Count - 1 do
begin
Frame := TfmReadingQuestion.Create(nil);
Frame.Binding(FCurrentQuiz.QuizList.Items[I]);
Frame.Parent := ScrollBox1;
Frame.Top := MaxInt;
Frame.Align := alTop;
FQuestionFrames.Add(Frame);
end;
end;
constructor TfmReading.Create(AOwner: TComponent);
begin
inherited;
FQuestionFrames := TObjectList<TfmReadingQuestion>.Create;
end;
destructor TfmReading.Destroy;
begin
FQuestionFrames.Free;
inherited;
end;
function TfmReading.GetTestResultDetails: TList<TTestResultDetail>;
var
I: Integer;
TestResultDetail: TTestResultDetail;
begin
// Assert(FCurrentQuiz.QuizList.Count = FQuestionFrames.Count, 'Frame 개수가 틀리다');
Result := TList<TTestResultDetail>.Create;
for I := 0 to FQuestionFrames.Count - 1 do
Result.Add(FQuestionFrames.Items[I].GetTestResultDetail);
end;
end.
|
unit u_xpl_gui_resource;
{$mode objfpc}{$H+}
interface
uses Classes
, SysUtils
, ImgList
;
type // TxPLGUIResource =======================================================
TxPLGUIResource = class
private
fImages16 : TCustomImageList;
fImages32 : TCustomImageList;
function Get_Images16 : TCustomImageList;
function Get_Images32 : TCustomImageList;
public
constructor Create;
property Images16 : TCustomImageList read Get_Images16;
property Images32 : TCustomImageList read Get_Images32;
end;
var xPLGUIResource : TxPLGUIResource;
var K_IMG_THREAD, K_IMG_pkg_installed, K_IMG_NETWORK, K_IMG_MAIL_FORWARD,
K_IMG_MESSAGE, K_IMG_STAT, K_IMG_EDIT_FIND, K_IMG_TRIG, K_IMG_CMND,
K_IMG_PREFERENCE, K_IMG_LOUPE, K_IMG_CE_PROCEDURE, K_IMG_SYNCHRONIZE,
K_IMG_EDIT_ADD, K_IMG_BUILD, K_IMG_TEST, K_IMG_EDIT_REMOVE, K_IMG_REFRESH,
K_IMG_PLAYER_PAUSE, K_IMG_PLAYER_STOP, K_IMG_DOCUMENT_SAVE, K_IMG_RECORD,
K_IMG_DOCUMENT_OPEN, K_IMG_MENU_RUN, K_IMG_BLUE_BADGE, K_IMG_ORANGE_BADGE,
K_IMG_GREEN_BADGE, K_IMG_TRASH, K_IMG_RED_BADGE, K_IMG_RECONNECT,
K_IMG_CLOSE, K_IMG_COPY, K_IMG_XPL, K_IMG_LOGVIEW, K_IMG_TXT,
K_IMG_DOWNLOAD, K_IMG_LOOP,
K_IMG_DISCONNECt,K_IMG_PASTE, K_IMG_CHECK, K_IMG_CLEAN, K_IMG_FILTER,
K_IMG_PREVIOUS, K_IMG_NEXT, K_IMG_OK, K_IMG_CANCEL,K_IMG_EDIT : integer;
implementation // =============================================================
uses Forms
, LResources
;
constructor TxPLGUIResource.Create;
begin
inherited;
fImages16 := TCustomImageList.Create(Application);
fImages32 := TCustomImageList.Create(Application);
end;
function TxPLGUIResource.Get_Images32: TCustomImageList;
begin
Result := fImages32;
if fImages32.Count = 0 then begin // Resources are only loaded if they are accessed at least once
fImages32.AddLazarusResource('etError'); // 29
fImages32.AddLazarusResource('etInfo'); // 30
fImages32.AddLazarusResource('etWarning'); // 31
end;
end;
function TxPLGUIResource.Get_Images16: TCustomImageList;
begin
Result := fImages16;
if fImages16.Count = 0 then begin // Resources are only loaded if they are accessed at least once
K_IMG_XPL := fImages16.AddLazarusResource('xpl'); // 0
K_IMG_CLOSE := fImages16.AddLazarusResource('menu_exit'); // 1
fImages16.AddLazarusResource('menu_information'); // 2
K_IMG_DOCUMENT_SAVE := fImages16.AddLazarusResource('laz_save'); // 3
K_IMG_REFRESH := fImages16.AddLazarusResource('laz_refresh'); // 4
K_IMG_CE_PROCEDURE := fImages16.AddLazarusResource('ce_procedure'); // 5
K_IMG_MENU_RUN := fImages16.AddLazarusResource('menu_run'); // 6
K_IMG_pkg_installed := fImages16.AddLazarusResource('pkg_installed'); // 7
K_IMG_TXT := fImages16.AddLazarusResource('txt'); // 8
K_IMG_DOWNLOAD := fImages16.AddLazarusResource('2downarrow'); // 9
K_IMG_EDIT_ADD := fImages16.AddLazarusResource('edit_add'); // 10
K_IMG_EDIT_REMOVE := fImages16.AddLazarusResource('edit_remove'); // 11
fImages16.AddLazarusResource('ledgreen'); // 12
fImages16.AddLazarusResource('ledorange'); // 13
fImages16.AddLazarusResource('ledred'); // 14
K_IMG_OK := fImages16.AddLazarusResource('button_ok'); // 15
K_IMG_CANCEL := fImages16.AddLazarusResource('button_cancel'); // 16
K_IMG_DOCUMENT_OPEN := fImages16.AddLazarusResource('fileopen'); // 17
K_IMG_COPY := fImages16.AddLazarusResource('editcopy'); // 18
K_IMG_PASTE := fImages16.AddLazarusResource('editpaste'); // 19
K_IMG_MAIL_FORWARD := fImages16.AddLazarusResource('mail_forward'); // 20
fImages16.AddLazarusResource('misc'); // 21
K_IMG_PLAYER_PAUSE := fImages16.AddLazarusResource('player_pause'); // 22
K_IMG_PLAYER_STOP := fImages16.AddLazarusResource('player_stop'); // 23
K_IMG_FILTER := fImages16.AddLazarusResource('item_filter'); // 24
K_IMG_CLEAN := fImages16.AddLazarusResource('menu_clean'); // 25
fImages16.AddLazarusResource('up'); // 26
fImages16.AddLazarusResource('down'); // 27
fImages16.AddLazarusResource('clock'); // 28
fImages16.AddLazarusResource('exit'); // 29
K_IMG_DISCONNECT := fImages16.AddLazarusResource('disconnect'); // 30
K_IMG_RECONNECT := fImages16.AddLazarusResource('reconnect'); // 31
fImages16.AddLazarusResource('activity'); // 32
K_IMG_TRASH := fImages16.AddLazarusResource('trash');
K_IMG_CHECK := fImages16.AddLazarusResource('check'); // 34
fImages16.AddLazarusResource('notchecked'); // 35
K_IMG_LOGVIEW := fImages16.AddLazarusResource('logview'); // 36
K_IMG_SYNCHRONIZE := fImages16.AddLazarusResource('synchronize'); // 37
K_IMG_PREFERENCE := fImages16.AddLazarusResource('preferences'); // 38
K_IMG_GREEN_BADGE := fImages16.AddLazarusResource('greenbadge'); // 39
K_IMG_RED_BADGE := fImages16.AddLazarusResource('redbadge'); // 40
K_IMG_BLUE_BADGE:= fImages16.AddLazarusResource('bluebadge'); // 41
K_IMG_ORANGE_BADGE := fImages16.AddLazarusResource('orangebadge'); // 42
K_IMG_EDIT_FIND := fImages16.AddLazarusResource('edit-find'); // 43
K_IMG_THREAD := fImages16.AddLazarusResource('thread'); // 44
K_IMG_MESSAGE := fImages16.AddLazarusResource('message'); // 45
K_IMG_NETWORK := fImages16.AddLazarusResource('network');
K_IMG_LOUPE := fImages16.AddLazarusResource('loupe');
K_IMG_RECORD := fImages16.AddLazarusResource('record');
K_IMG_BUILD := fImages16.AddLazarusResource('menu_build');
K_IMG_TEST := fImages16.AddLazarusResource('menu_test');
K_IMG_PREVIOUS := fImages16.AddLazarusResource('resultset_previous');
K_IMG_NEXT := fImages16.AddLazarusResource('resultset_next');
K_IMG_EDIT := fImages16.AddLazarusResource('page_edit');
K_IMG_LOOP := fImages16.AddLazarusResource('loop');
// Msgtype ==============================================================
K_IMG_CMND := fImages16.AddLazarusResource('xpl-cmnd');
K_IMG_STAT := fImages16.AddLazarusResource('xpl-stat');
K_IMG_TRIG := fImages16.AddLazarusResource('xpl-trig');
end;
end;
initialization // =============================================================
{$I menu.lrs} // Interface icons
{$I class.lrs} // Message classes
{$I msgtype.lrs} // Message types
xPLGUIResource := TxPLGUIResource.Create;
finalization // ===============================================================
xPLGUIResource.Free;
end.
|
unit ClsProducto;
interface
uses Windows, Messages, SysUtils, Classes, Graphics, Controls,VCIF1Lib_TLB,
IB_Components, StrMan, ESBDates,IniFiles,
ClsTablas;
type
TExistencias = record
NumAlmacen: string;
NombreAlmacen: string;
Existencia: Double;
end;
type TProducto = class(TObject)
constructor Create;
destructor Destroy;
private
// Campos de la tabla MBA10004
FCODPRODSER:String;
FDESCRIPPRO:String;
FCARAC1:String;
FCARAC2:String;
FCARAC3:String;
FCATEGPROD:String;
FCODFAMILIA:String;
FCOSTOPROM:Double;
FCOSTOSTD:Double;
FCOSTOTOTAL:Double;
FDIASINVFIS:Double;
FDISTCOMP:String;
FDISTDEVCTE:String;
FDISTDEVPRO:String;
FDISTVTA:String;
FEDOACTPROD:SmallInt;
FESTADPROD:SmallInt;
FEXISCONSIG:Double;
FEXISREMIS:Double;
FEXISTOTAL:Double;
FEXISALMACEN:Double;
FFECCONTEO:TDateTime;
FFAMPRDSRV:SmallInt;
FFECALTPROD:TDateTime;
FFECHABAJA:TDateTime;
FFECINIEST:TDateTime;
FFECULTCOMP:TDateTime;
FFECULTENTP:TDateTime;
FFECULTSALP:TDateTime;
FFECULTVTAP:TDateTime;
FPCIOCOMPRA:Double;
FDESCTO1:Double;
FDESCTO2:Double;
FDESCTO3:Double;
FDESCTO4:Double;
FDESCTO5:Double;
FDESCTO6:Double;
FDESCTO7:Double;
FDESCTO8:Double;
FDESCTO9:Double;
FDESCTO10:Double;
FPCIONETO:Double;
FGTOSIMPORT:Double;
FGTOSFLETE:Double;
FGTOSOTROS:Double;
FCTOREAL:Double;
FMARGEN1:Double;
FMARGEN2:Double;
FMARGEN3:Double;
FMARGEN4:Double;
FMARGEN5:Double;
FMARGEN6:Double;
FMARGEN7:Double;
FMARGEN8:Double;
FMARGEN9:Double;
FMARGEN10:Double;
FPCIOVTA1:Double;
FPCIOVTA2:Double;
FPCIOVTA3:Double;
FPCIOVTA4:Double;
FPCIOVTA5:Double;
FPCIOVTA6:Double;
FPCIOVTA7:Double;
FPCIOVTA8:Double;
FPCIOVTA9:Double;
FPCIOVTA10:Double;
FPEDIMENTOS:SmallInt;
FPESO:Double;
FPORCOMVTA:Double;
FPORDESCAUT:Double;
FPORC2VTA:Double;
FPORC3VTA:Double;
FPORC4VTA:Double;
FPORC5VTA:Double;
FPORCMARGEN:Double;
FSERIES:SmallInt;
FTABMEDIDA:String;
FTIPOPROD:String;
FULTCOSTO:Double;
FUNIDPEDCTE:Double;
FUNIDPEDPRO:Double;
FUNIVTA:String;
FUNIADQ:String;
FINCLUYE:String;
FERRORCOSTO:SmallInt;
FFECERRCOST:TDateTime;
FCOSTOENT:Double;
FTOTALENT:Double;
FEXTRA1:String;
FEXTRA2:String;
FEXTRA3:String;
FUSERACT1:String;
FFECHAACT1:TDateTime;
FUSERACT2:String;
FFECHAACT2:TDateTime;
FUSERACT3:String;
FFECHAACT3:TDateTime;
FPATHFOTO:String;
FCODCTEPROV:String;
FCODCTEPROV2:String;
// Campos adicionales
FUNIVTADESC:String; //Descripcion de Unidad de Venta
FUNIADQDESC:String; //Descripcion de Unidad de Compra / adquisición
FDESCROTA:Double;
FSTATUSROTA:SmallInt;
FTIPOCALCULO:SmallInt;
FMAXIMO:Double;
FMINIMO:Double;
FREORDEN:Double;
FPRIORIDAD: Integer;
FLONGITUD: Double;
FFIGURA: String;
FNUMALMAC: String;
// Campos adicionales
FDESCRIPTEC: String;
FNUMSERIE: String;
FCAMBIO:SmallInt;
// Campos Oct/2017
FCLAVESAT: String;
FCLAVEUNIDAD:String;
FCOBRO_IVA:SmallInt;
FCOBRO_RETIVA:SmallInt;
FCOBRO_IEPS:SmallInt;
FPORC_IVA:Double;
FPORC_RETIVA:Double;
FPORC_IEPS:Double;
FES_DLS:SmallInt;
FError:Integer;
oTabla:TTabla;
icu:TIB_Cursor;
icu0:TIB_Cursor;
icu1:TIB_Cursor;
icu2:TIB_Cursor;
icu3:TIB_Cursor;
function GetCODPRODSER:String;
procedure SetCODPRODSER(pCODPRODSER:String);
function GetDESCRIPPRO:String;
procedure SetDESCRIPPRO(pDESCRIPPRO:String);
function GetCARAC1:String;
procedure SetCARAC1(pCARAC1:String);
function GetCARAC2:String;
procedure SetCARAC2(pCARAC2:String);
function GetCARAC3:String;
procedure SetCARAC3(pCARAC3:String);
function GetCATEGPROD:String;
procedure SetCATEGPROD(pCATEGPROD:String);
function GetCODFAMILIA:String;
procedure SetCODFAMILIA(pCODFAMILIA:String);
function GetCOSTOPROM:Double;
procedure SetCOSTOPROM(pCOSTOPROM:Double);
function GetCOSTOSTD:Double;
procedure SetCOSTOSTD(pCOSTOSTD:Double);
function GetCOSTOTOTAL:Double;
procedure SetCOSTOTOTAL(pCOSTOTOTAL:Double);
function GetDIASINVFIS:Double;
procedure SetDIASINVFIS(pDIASINVFIS:Double);
function GetDISTCOMP:String;
procedure SetDISTCOMP(pDISTCOMP:String);
function GetDISTDEVCTE:String;
procedure SetDISTDEVCTE(pDISTDEVCTE:String);
function GetDISTDEVPRO:String;
procedure SetDISTDEVPRO(pDISTDEVPRO:String);
function GetDISTVTA:String;
procedure SetDISTVTA(pDISTVTA:String);
function GetEDOACTPROD:SmallInt;
procedure SetEDOACTPROD(pEDOACTPROD:SmallInt);
function GetESTADPROD:SmallInt;
procedure SetESTADPROD(pESTADPROD:SmallInt);
function GetEXISCONSIG:Double;
procedure SetEXISCONSIG(pEXISCONSIG:Double);
function GetEXISREMIS:Double;
procedure SetEXISREMIS(pEXISREMIS:Double);
function GetEXISTOTAL:Double;
function GetEXISALMACEN:Double;
procedure SetEXISTOTAL(pEXISTOTAL:Double);
function GetFAMPRDSRV:SmallInt;
procedure SetFAMPRDSRV(pFAMPRDSRV:SmallInt);
function GetFECALTPROD:TDateTime;
procedure SetFECALTPROD(pFECALTPROD:TDateTime);
function GetFECHABAJA:TDateTime;
procedure SetFECHABAJA(pFECHABAJA:TDateTime);
function GetFECINIEST:TDateTime;
procedure SetFECINIEST(pFECINIEST:TDateTime);
function GetFECULTCOMP:TDateTime;
procedure SetFECULTCOMP(pFECULTCOMP:TDateTime);
function GetFECULTENTP:TDateTime;
procedure SetFECULTENTP(pFECULTENTP:TDateTime);
function GetFECULTSALP:TDateTime;
procedure SetFECULTSALP(pFECULTSALP:TDateTime);
function GetFECULTVTAP:TDateTime;
procedure SetFECULTVTAP(pFECULTVTAP:TDateTime);
function GetPCIOCOMPRA:Double;
procedure SetPCIOCOMPRA(pPCIOCOMPRA:Double);
function GetDESCTO1:Double;
procedure SetDESCTO1(pDESCTO1:Double);
function GetDESCTO2:Double;
procedure SetDESCTO2(pDESCTO2:Double);
function GetDESCTO3:Double;
procedure SetDESCTO3(pDESCTO3:Double);
function GetDESCTO4:Double;
procedure SetDESCTO4(pDESCTO4:Double);
function GetDESCTO5:Double;
procedure SetDESCTO5(pDESCTO5:Double);
function GetDESCTO6:Double;
procedure SetDESCTO6(pDESCTO6:Double);
function GetDESCTO7:Double;
procedure SetDESCTO7(pDESCTO7:Double);
function GetDESCTO8:Double;
procedure SetDESCTO8(pDESCTO8:Double);
function GetDESCTO9:Double;
procedure SetDESCTO9(pDESCTO9:Double);
function GetDESCTO10:Double;
procedure SetDESCTO10(pDESCTO10:Double);
function GetPCIONETO:Double;
procedure SetPCIONETO(pPCIONETO:Double);
function GetGTOSIMPORT:Double;
procedure SetGTOSIMPORT(pGTOSIMPORT:Double);
function GetGTOSFLETE:Double;
procedure SetGTOSFLETE(pGTOSFLETE:Double);
function GetGTOSOTROS:Double;
procedure SetGTOSOTROS(pGTOSOTROS:Double);
function GetCTOREAL:Double;
procedure SetCTOREAL(pCTOREAL:Double);
function GetMARGEN1:Double;
procedure SetMARGEN1(pMARGEN1:Double);
function GetMARGEN2:Double;
procedure SetMARGEN2(pMARGEN2:Double);
function GetMARGEN3:Double;
procedure SetMARGEN3(pMARGEN3:Double);
function GetMARGEN4:Double;
procedure SetMARGEN4(pMARGEN4:Double);
function GetMARGEN5:Double;
procedure SetMARGEN5(pMARGEN5:Double);
function GetMARGEN6:Double;
procedure SetMARGEN6(pMARGEN6:Double);
function GetMARGEN7:Double;
procedure SetMARGEN7(pMARGEN7:Double);
function GetMARGEN8:Double;
procedure SetMARGEN8(pMARGEN8:Double);
function GetMARGEN9:Double;
procedure SetMARGEN9(pMARGEN9:Double);
function GetMARGEN10:Double;
procedure SetMARGEN10(pMARGEN10:Double);
function GetPCIOVTA1:Double;
procedure SetPCIOVTA1(pPCIOVTA1:Double);
function GetPCIOVTA2:Double;
procedure SetPCIOVTA2(pPCIOVTA2:Double);
function GetPCIOVTA3:Double;
procedure SetPCIOVTA3(pPCIOVTA3:Double);
function GetPCIOVTA4:Double;
procedure SetPCIOVTA4(pPCIOVTA4:Double);
function GetPCIOVTA5:Double;
procedure SetPCIOVTA5(pPCIOVTA5:Double);
function GetPCIOVTA6:Double;
procedure SetPCIOVTA6(pPCIOVTA6:Double);
function GetPCIOVTA7:Double;
procedure SetPCIOVTA7(pPCIOVTA7:Double);
function GetPCIOVTA8:Double;
procedure SetPCIOVTA8(pPCIOVTA8:Double);
function GetPCIOVTA9:Double;
procedure SetPCIOVTA9(pPCIOVTA9:Double);
function GetPCIOVTA10:Double;
procedure SetPCIOVTA10(pPCIOVTA10:Double);
function GetPEDIMENTOS:SmallInt;
procedure SetPEDIMENTOS(pPEDIMENTOS:SmallInt);
function GetPESO:Double;
procedure SetPESO(pPESO:Double);
function GetPORCOMVTA:Double;
procedure SetPORCOMVTA(pPORCOMVTA:Double);
function GetPORDESCAUT:Double;
procedure SetPORDESCAUT(pPORDESCAUT:Double);
function GetPORC2VTA:Double;
procedure SetPORC2VTA(pPORC2VTA:Double);
function GetPORC3VTA:Double;
procedure SetPORC3VTA(pPORC3VTA:Double);
function GetPORC4VTA:Double;
procedure SetPORC4VTA(pPORC4VTA:Double);
function GetPORC5VTA:Double;
procedure SetPORC5VTA(pPORC5VTA:Double);
function GetPORCMARGEN:Double;
procedure SetPORCMARGEN(pPORCMARGEN:Double);
function GetSERIES:SmallInt;
procedure SetSERIES(pSERIES:SmallInt);
function GetTABMEDIDA:String;
procedure SetTABMEDIDA(pTABMEDIDA:String);
function GetTIPOPROD:String;
procedure SetTIPOPROD(pTIPOPROD:String);
function GetULTCOSTO:Double;
procedure SetULTCOSTO(pULTCOSTO:Double);
function GetUNIDPEDCTE:Double;
procedure SetUNIDPEDCTE(pUNIDPEDCTE:Double);
function GetUNIDPEDPRO:Double;
procedure SetUNIDPEDPRO(pUNIDPEDPRO:Double);
function GetUNIVTA:String;
procedure SetUNIVTA(pUNIVTA:String);
function GetUNIADQ:String;
procedure SetUNIADQ(pUNIADQ:String);
function GetINCLUYE:String;
procedure SetINCLUYE(pINCLUYE:String);
function GetERRORCOSTO:SmallInt;
procedure SetERRORCOSTO(pERRORCOSTO:SmallInt);
function GetFECERRCOST:TDateTime;
procedure SetFECERRCOST(pFECERRCOST:TDateTime);
function GetCOSTOENT:Double;
procedure SetCOSTOENT(pCOSTOENT:Double);
function GetTOTALENT:Double;
procedure SetTOTALENT(pTOTALENT:Double);
function GetEXTRA1:String;
procedure SetEXTRA1(pEXTRA1:String);
function GetEXTRA2:String;
procedure SetEXTRA2(pEXTRA2:String);
function GetEXTRA3:String;
procedure SetEXTRA3(pEXTRA3:String);
function GetUSERACT1:String;
procedure SetUSERACT1(pUSERACT1:String);
function GetFECHAACT1:TDateTime;
procedure SetFECHAACT1(pFECHAACT1:TDateTime);
function GetUSERACT2:String;
procedure SetUSERACT2(pUSERACT2:String);
function GetFECHAACT2:TDateTime;
procedure SetFECHAACT2(pFECHAACT2:TDateTime);
function GetUSERACT3:String;
procedure SetUSERACT3(pUSERACT3:String);
function GetFECHAACT3:TDateTime;
procedure SetFECHAACT3(pFECHAACT3:TDateTime);
function GetPATHFOTO:String;
procedure SetPATHFOTO(pPATHFOTO:String);
public
property CODPRODSER: String read GetCODPRODSER write SetCODPRODSER;
property CODPRODSER_SF: String read FCODPRODSER write FCODPRODSER;
property DESCRIPPRO: String read GetDESCRIPPRO write SetDESCRIPPRO;
property CARAC1: String read GetCARAC1 write SetCARAC1;
property CARAC2: String read GetCARAC2 write SetCARAC2;
property CARAC3: String read GetCARAC3 write SetCARAC3;
property CATEGPROD: String read GetCATEGPROD write SetCATEGPROD;
property CODFAMILIA: String read GetCODFAMILIA write SetCODFAMILIA;
property COSTOPROM: Double read GetCOSTOPROM write SetCOSTOPROM;
property COSTOSTD: Double read GetCOSTOSTD write SetCOSTOSTD;
property COSTOTOTAL: Double read GetCOSTOTOTAL write SetCOSTOTOTAL;
property DIASINVFIS: Double read GetDIASINVFIS write SetDIASINVFIS;
property DISTCOMP: String read GetDISTCOMP write SetDISTCOMP;
property DISTDEVCTE: String read GetDISTDEVCTE write SetDISTDEVCTE;
property DISTDEVPRO: String read GetDISTDEVPRO write SetDISTDEVPRO;
property DISTVTA: String read GetDISTVTA write SetDISTVTA;
property EDOACTPROD: SmallInt read GetEDOACTPROD write SetEDOACTPROD;
property ESTADPROD: SmallInt read GetESTADPROD write SetESTADPROD;
property EXISCONSIG: Double read GetEXISCONSIG write SetEXISCONSIG;
property EXISREMIS: Double read GetEXISREMIS write SetEXISREMIS;
property EXISTOTAL: Double read GetEXISTOTAL write SetEXISTOTAL;
property EXISALMACEN: Double read GetEXISALMACEN;
property FECCONTEO: TDateTime read FFECCONTEO write FFECCONTEO;
property FAMPRDSRV: SmallInt read GetFAMPRDSRV write SetFAMPRDSRV;
property FECALTPROD: TDateTime read GetFECALTPROD write SetFECALTPROD;
property FECHABAJA: TDateTime read GetFECHABAJA write SetFECHABAJA;
property FECINIEST: TDateTime read GetFECINIEST write SetFECINIEST;
property FECULTCOMP: TDateTime read GetFECULTCOMP write SetFECULTCOMP;
property FECULTENTP: TDateTime read GetFECULTENTP write SetFECULTENTP;
property FECULTSALP: TDateTime read GetFECULTSALP write SetFECULTSALP;
property FECULTVTAP: TDateTime read GetFECULTVTAP write SetFECULTVTAP;
property PCIOCOMPRA: Double read GetPCIOCOMPRA write SetPCIOCOMPRA;
property DESCTO1: Double read GetDESCTO1 write SetDESCTO1;
property DESCTO2: Double read GetDESCTO2 write SetDESCTO2;
property DESCTO3: Double read GetDESCTO3 write SetDESCTO3;
property DESCTO4: Double read GetDESCTO4 write SetDESCTO4;
property DESCTO5: Double read GetDESCTO5 write SetDESCTO5;
property DESCTO6: Double read GetDESCTO6 write SetDESCTO6;
property DESCTO7: Double read GetDESCTO7 write SetDESCTO7;
property DESCTO8: Double read GetDESCTO8 write SetDESCTO8;
property DESCTO9: Double read GetDESCTO9 write SetDESCTO9;
property DESCTO10: Double read GetDESCTO10 write SetDESCTO10;
property PCIONETO: Double read GetPCIONETO write SetPCIONETO;
property GTOSIMPORT: Double read GetGTOSIMPORT write SetGTOSIMPORT;
property GTOSFLETE: Double read GetGTOSFLETE write SetGTOSFLETE;
property GTOSOTROS: Double read GetGTOSOTROS write SetGTOSOTROS;
property CTOREAL: Double read GetCTOREAL write SetCTOREAL;
property MARGEN1: Double read GetMARGEN1 write SetMARGEN1;
property MARGEN2: Double read GetMARGEN2 write SetMARGEN2;
property MARGEN3: Double read GetMARGEN3 write SetMARGEN3;
property MARGEN4: Double read GetMARGEN4 write SetMARGEN4;
property MARGEN5: Double read GetMARGEN5 write SetMARGEN5;
property MARGEN6: Double read GetMARGEN6 write SetMARGEN6;
property MARGEN7: Double read GetMARGEN7 write SetMARGEN7;
property MARGEN8: Double read GetMARGEN8 write SetMARGEN8;
property MARGEN9: Double read GetMARGEN9 write SetMARGEN9;
property MARGEN10: Double read GetMARGEN10 write SetMARGEN10;
property PCIOVTA1: Double read GetPCIOVTA1 write SetPCIOVTA1;
property PCIOVTA2: Double read GetPCIOVTA2 write SetPCIOVTA2;
property PCIOVTA3: Double read GetPCIOVTA3 write SetPCIOVTA3;
property PCIOVTA4: Double read GetPCIOVTA4 write SetPCIOVTA4;
property PCIOVTA5: Double read GetPCIOVTA5 write SetPCIOVTA5;
property PCIOVTA6: Double read GetPCIOVTA6 write SetPCIOVTA6;
property PCIOVTA7: Double read GetPCIOVTA7 write SetPCIOVTA7;
property PCIOVTA8: Double read GetPCIOVTA8 write SetPCIOVTA8;
property PCIOVTA9: Double read GetPCIOVTA9 write SetPCIOVTA9;
property PCIOVTA10: Double read GetPCIOVTA10 write SetPCIOVTA10;
property PEDIMENTOS: SmallInt read GetPEDIMENTOS write SetPEDIMENTOS;
property PESO: Double read GetPESO write SetPESO;
property PORCOMVTA: Double read GetPORCOMVTA write SetPORCOMVTA;
property PORDESCAUT: Double read GetPORDESCAUT write SetPORDESCAUT;
property PORC2VTA: Double read GetPORC2VTA write SetPORC2VTA;
property PORC3VTA: Double read GetPORC3VTA write SetPORC3VTA;
property PORC4VTA: Double read GetPORC4VTA write SetPORC4VTA;
property PORC5VTA: Double read GetPORC5VTA write SetPORC5VTA;
property PORCMARGEN: Double read GetPORCMARGEN write SetPORCMARGEN;
property SERIES: SmallInt read GetSERIES write SetSERIES;
property TABMEDIDA: String read GetTABMEDIDA write SetTABMEDIDA;
property TIPOPROD: String read GetTIPOPROD write SetTIPOPROD;
property ULTCOSTO: Double read GetULTCOSTO write SetULTCOSTO;
property UNIDPEDCTE: Double read GetUNIDPEDCTE write SetUNIDPEDCTE;
property UNIDPEDPRO: Double read GetUNIDPEDPRO write SetUNIDPEDPRO;
property UNIVTA: String read GetUNIVTA write SetUNIVTA;
property UNIADQ: String read GetUNIADQ write SetUNIADQ;
property INCLUYE: String read GetINCLUYE write SetINCLUYE;
property ERRORCOSTO: SmallInt read GetERRORCOSTO write SetERRORCOSTO;
property FECERRCOST: TDateTime read GetFECERRCOST write SetFECERRCOST;
property COSTOENT: Double read GetCOSTOENT write SetCOSTOENT;
property TOTALENT: Double read GetTOTALENT write SetTOTALENT;
property EXTRA1: String read GetEXTRA1 write SetEXTRA1;
property EXTRA2: String read GetEXTRA2 write SetEXTRA2;
property EXTRA3: String read GetEXTRA3 write SetEXTRA3;
property USERACT1: String read GetUSERACT1 write SetUSERACT1;
property FECHAACT1: TDateTime read GetFECHAACT1 write SetFECHAACT1;
property USERACT2: String read GetUSERACT2 write SetUSERACT2;
property FECHAACT2: TDateTime read GetFECHAACT2 write SetFECHAACT2;
property USERACT3: String read GetUSERACT3 write SetUSERACT3;
property FECHAACT3: TDateTime read GetFECHAACT3 write SetFECHAACT3;
property PATHFOTO: String read GetPATHFOTO write SetPATHFOTO;
property CODCTEPROV: String read FCODCTEPROV write FCODCTEPROV;
property CODCTEPROV2: String read FCODCTEPROV2 write FCODCTEPROV2;
property UNIVTADESC:String read FUNIVTADESC;
property DESCROTA:Double read FDESCROTA write FDESCROTA;
property STATUSROTA:smallint read FSTATUSROTA write FSTATUSROTA;
property TIPOCALCULO:smallint read FTIPOCALCULO write FTIPOCALCULO;
property MAXIMO:Double read FMAXIMO write FMAXIMO;
property MINIMO:Double read FMINIMO write FMINIMO;
property REORDEN:Double read FREORDEN write FREORDEN;
property PRIORIDAD: Integer read FPRIORIDAD write FPRIORIDAD;
property LONGITUD: Double read FLONGITUD write FLONGITUD;
property FIGURA: String read FFIGURA write FFIGURA;
property NUMALMAC: String read FNUMALMAC write FNUMALMAC;
property DESCRIPTEC: String read FDESCRIPTEC write FDESCRIPTEC;
property NUMSERIE: String read FNUMSERIE write FNUMSERIE;
property CAMBIO:smallint read FCAMBIO write FCAMBIO;
property CLAVESAT:String read FCLAVESAT write FCLAVESAT;
property CLAVEUNIDAD:String read FCLAVEUNIDAD write FCLAVEUNIDAD;
property COBRO_IVA:smallint read FCOBRO_IVA write FCOBRO_IVA;
property COBRO_RETIVA:smallint read FCOBRO_RETIVA write FCOBRO_RETIVA;
property COBRO_IEPS:smallint read FCOBRO_IEPS write FCOBRO_IEPS;
property PORC_IVA:Double read FPORC_IVA write FPORC_IVA;
property PORC_RETIVA:Double read FPORC_RETIVA write FPORC_RETIVA;
property PORC_IEPS:Double read FPORC_IEPS write FPORC_IEPS;
property ES_DLS:smallint read FES_DLS write FES_DLS;
property Error:Integer read FError write FError;
procedure Retrieve;
procedure RetrieveHRC(AHoja,ARen,ACol:Integer);
procedure RetrieveDescri(ADescri:String);
procedure Save;
procedure Delete;
procedure Clear;
function GetPrecio(piLista:Integer):Double;
function FormateaCodigo(ptCodigo :String):String;
function ValidarCodigo(ACodigo:String):Integer;
procedure CalculaExistencias;
function GetExistencia(ANumAlmac:String):Double;
end;
function GetNombreStatusRota(piNumero:Smallint):String;
var
aExistencia: array [1..10] of TExistencias;
implementation
uses DM_MBA;
{==================================================================
Implementacion: TProducto
==================================================================}
constructor TProducto.Create;
begin
inherited Create; // Inicializa las partes heredadas
oTabla := TTabla.Create;
icu := TIB_Cursor.Create(nil);
icu.IB_Connection := DM1.cnMBA;
icu.IB_Transaction := DM1.trMBA;
icu.SQL.Clear;
icu.SQL.Add('Select sum(ExisIniPer+EntPerExis-SalPerExis) from MBA10016 where CodProdSer = ?CodProdSer;');
icu.Prepare;
icu0 := TIB_Cursor.Create(nil);
icu0.IB_Connection := DM1.cnMBA;
icu0.IB_Transaction := DM1.trMBA;
icu0.SQL.Clear;
icu0.SQL.Add('Select ExisIniPer+EntPerExis-SalPerExis, fecconteo from MBA10016 where (CodProdSer = ?CodProdSer) AND (NUMALMAC = ?NumAlmac);');
icu0.Prepare;
icu1 := TIB_Cursor.Create(nil);
icu1.IB_Connection := DM1.cnMBA;
icu1.IB_Transaction := DM1.trMBA;
icu1.SQL.Clear;
icu1.SQL.Add('Select CODPRODSER FROM MBA10004 WHERE (HOJA =?HOJA) AND (REN = ?REN) AND (COL = ?COL);');
icu1.Prepare;
icu2 := TIB_Cursor.Create(nil);
icu2.IB_Connection := DM1.cnMBA;
icu2.IB_Transaction := DM1.trMBA;
icu2.SQL.Clear;
icu2.SQL.Add('Select CODPRODSER,DESCRIPPRO,CTOREAL,UNIVTA FROM MBA10004 WHERE (DESCRIPPRO = ?DESCRIPPRO);');
icu2.Prepare;
icu3 := TIB_Cursor.Create(nil);
icu3.IB_Connection := DM1.cnMBA;
icu3.IB_Transaction := DM1.trMBA;
icu3.SQL.Clear;
icu3.SQL.Add('Select * from EXISTENCIAS_ALMACEN1(?CodProdSer)');
icu3.Prepare;
end;
destructor TProducto.Destroy;
begin
icu.Free;
oTabla.Free;
inherited Destroy;
end;
function TProducto.GetPrecio(piLista:Integer):Double;
begin
case piLista of
0,1: Result := PCIOVTA1;
2: Result := PCIOVTA2;
3: Result := PCIOVTA3;
4: Result := PCIOVTA4;
5: Result := PCIOVTA5;
6: Result := PCIOVTA6;
7: Result := PCIOVTA7;
8: Result := PCIOVTA8;
9: Result := PCIOVTA9;
10: Result := PCIOVTA10;
else
Result := PCIOVTA1;
end;
end;
procedure TProducto.Retrieve;
begin
//
DM1.ispProd_S.ParamByName('P_CODPRODSER').AsString := FCODPRODSER;
DM1.ispProd_S.ExecProc;
// FCODPRODSER := DM1.ispProd_S.FieldByName('CODPRODSER').String;
FDESCRIPPRO := DM1.ispProd_S.FieldByName('DESCRIPPRO').AsString;
FCARAC1 := DM1.ispProd_S.FieldByName('CARAC1').AsString;
FCARAC2 := DM1.ispProd_S.FieldByName('CARAC2').AsString;
FCARAC3 := DM1.ispProd_S.FieldByName('CARAC3').AsString;
FCATEGPROD := DM1.ispProd_S.FieldByName('CATEGPROD').AsString;
FCODFAMILIA := DM1.ispProd_S.FieldByName('CODFAMILIA').AsString;
FCOSTOPROM := DM1.ispProd_S.FieldByName('COSTOPROM').AsDouble;
FCOSTOSTD := DM1.ispProd_S.FieldByName('COSTOSTD').AsDouble;
FCOSTOTOTAL := DM1.ispProd_S.FieldByName('COSTOTOTAL').AsDouble;
FDIASINVFIS := DM1.ispProd_S.FieldByName('DIASINVFIS').AsDouble;
FDISTCOMP := DM1.ispProd_S.FieldByName('DISTCOMP').AsString;
FDISTDEVCTE := DM1.ispProd_S.FieldByName('DISTDEVCTE').AsString;
FDISTDEVPRO := DM1.ispProd_S.FieldByName('DISTDEVPRO').AsString;
FDISTVTA := DM1.ispProd_S.FieldByName('DISTVTA').AsString;
FEDOACTPROD := DM1.ispProd_S.FieldByName('EDOACTPROD').AsSmallInt;
FESTADPROD := DM1.ispProd_S.FieldByName('ESTADPROD').AsSmallInt;
FEXISCONSIG := DM1.ispProd_S.FieldByName('EXISCONSIG').AsDouble;
FEXISREMIS := DM1.ispProd_S.FieldByName('EXISREMIS').AsDouble;
FEXISTOTAL := DM1.ispProd_S.FieldByName('EXISTOTAL').AsDouble;
FFAMPRDSRV := DM1.ispProd_S.FieldByName('FAMPRDSRV').AsSmallInt;
FFECALTPROD := DM1.ispProd_S.FieldByName('FECALTPROD').AsDateTime;
FFECHABAJA := DM1.ispProd_S.FieldByName('FECHABAJA').AsDateTime;
FFECINIEST := DM1.ispProd_S.FieldByName('FECINIEST').AsDateTime;
FFECULTCOMP := DM1.ispProd_S.FieldByName('FECULTCOMP').AsDateTime;
FFECULTENTP := DM1.ispProd_S.FieldByName('FECULTENTP').AsDateTime;
FFECULTSALP := DM1.ispProd_S.FieldByName('FECULTSALP').AsDateTime;
FFECULTVTAP := DM1.ispProd_S.FieldByName('FECULTVTAP').AsDateTime;
FPCIOCOMPRA := DM1.ispProd_S.FieldByName('PCIOCOMPRA').AsDouble;
FDESCTO1 := DM1.ispProd_S.FieldByName('DESCTO1').AsDouble;
FDESCTO2 := DM1.ispProd_S.FieldByName('DESCTO2').AsDouble;
FDESCTO3 := DM1.ispProd_S.FieldByName('DESCTO3').AsDouble;
FDESCTO4 := DM1.ispProd_S.FieldByName('DESCTO4').AsDouble;
FDESCTO5 := DM1.ispProd_S.FieldByName('DESCTO5').AsDouble;
FDESCTO6 := DM1.ispProd_S.FieldByName('DESCTO6').AsDouble;
FDESCTO7 := DM1.ispProd_S.FieldByName('DESCTO7').AsDouble;
FDESCTO8 := DM1.ispProd_S.FieldByName('DESCTO8').AsDouble;
FDESCTO9 := DM1.ispProd_S.FieldByName('DESCTO9').AsDouble;
FDESCTO10 := DM1.ispProd_S.FieldByName('DESCTO10').AsDouble;
FPCIONETO := DM1.ispProd_S.FieldByName('PCIONETO').AsDouble;
FGTOSIMPORT := DM1.ispProd_S.FieldByName('GTOSIMPORT').AsDouble;
FGTOSFLETE := DM1.ispProd_S.FieldByName('GTOSFLETE').AsDouble;
FGTOSOTROS := DM1.ispProd_S.FieldByName('GTOSOTROS').AsDouble;
FCTOREAL := DM1.ispProd_S.FieldByName('CTOREAL').AsDouble;
FMARGEN1 := DM1.ispProd_S.FieldByName('MARGEN1').AsDouble;
FMARGEN2 := DM1.ispProd_S.FieldByName('MARGEN2').AsDouble;
FMARGEN3 := DM1.ispProd_S.FieldByName('MARGEN3').AsDouble;
FMARGEN4 := DM1.ispProd_S.FieldByName('MARGEN4').AsDouble;
FMARGEN5 := DM1.ispProd_S.FieldByName('MARGEN5').AsDouble;
FMARGEN6 := DM1.ispProd_S.FieldByName('MARGEN6').AsDouble;
FMARGEN7 := DM1.ispProd_S.FieldByName('MARGEN7').AsDouble;
FMARGEN8 := DM1.ispProd_S.FieldByName('MARGEN8').AsDouble;
FMARGEN9 := DM1.ispProd_S.FieldByName('MARGEN9').AsDouble;
FMARGEN10 := DM1.ispProd_S.FieldByName('MARGEN10').AsDouble;
FPCIOVTA1 := DM1.ispProd_S.FieldByName('PCIOVTA1').AsDouble;
FPCIOVTA2 := DM1.ispProd_S.FieldByName('PCIOVTA2').AsDouble;
FPCIOVTA3 := DM1.ispProd_S.FieldByName('PCIOVTA3').AsDouble;
FPCIOVTA4 := DM1.ispProd_S.FieldByName('PCIOVTA4').AsDouble;
FPCIOVTA5 := DM1.ispProd_S.FieldByName('PCIOVTA5').AsDouble;
FPCIOVTA6 := DM1.ispProd_S.FieldByName('PCIOVTA6').AsDouble;
FPCIOVTA7 := DM1.ispProd_S.FieldByName('PCIOVTA7').AsDouble;
FPCIOVTA8 := DM1.ispProd_S.FieldByName('PCIOVTA8').AsDouble;
FPCIOVTA9 := DM1.ispProd_S.FieldByName('PCIOVTA9').AsDouble;
FPCIOVTA10 := DM1.ispProd_S.FieldByName('PCIOVTA10').AsDouble;
FPEDIMENTOS := DM1.ispProd_S.FieldByName('PEDIMENTOS').AsSmallInt;
FPESO := DM1.ispProd_S.FieldByName('PESO').AsDouble;
FPORCOMVTA := DM1.ispProd_S.FieldByName('PORCOMVTA').AsDouble;
FPORDESCAUT := DM1.ispProd_S.FieldByName('PORDESCAUT').AsDouble;
FPORC2VTA := DM1.ispProd_S.FieldByName('PORC2VTA').AsDouble;
FPORC3VTA := DM1.ispProd_S.FieldByName('PORC3VTA').AsDouble;
FPORC4VTA := DM1.ispProd_S.FieldByName('PORC4VTA').AsDouble;
FPORC5VTA := DM1.ispProd_S.FieldByName('PORC5VTA').AsDouble;
FPORCMARGEN := DM1.ispProd_S.FieldByName('PORCMARGEN').AsDouble;
FSERIES := DM1.ispProd_S.FieldByName('SERIES').AsSmallInt;
FTABMEDIDA := DM1.ispProd_S.FieldByName('TABMEDIDA').AsString;
FTIPOPROD := DM1.ispProd_S.FieldByName('TIPOPROD').AsString;
FULTCOSTO := DM1.ispProd_S.FieldByName('ULTCOSTO').AsDouble;
FUNIDPEDCTE := DM1.ispProd_S.FieldByName('UNIDPEDCTE').AsDouble;
FUNIDPEDPRO := DM1.ispProd_S.FieldByName('UNIDPEDPRO').AsDouble;
FUNIVTA := DM1.ispProd_S.FieldByName('UNIVTA').AsString;
FUNIADQ := DM1.ispProd_S.FieldByName('UNIADQ').AsString;
FINCLUYE := DM1.ispProd_S.FieldByName('INCLUYE').AsString;
FERRORCOSTO := DM1.ispProd_S.FieldByName('ERRORCOSTO').AsSmallInt;
FFECERRCOST := DM1.ispProd_S.FieldByName('FECERRCOST').AsDateTime;
FCOSTOENT := DM1.ispProd_S.FieldByName('COSTOENT').AsDouble;
FTOTALENT := DM1.ispProd_S.FieldByName('TOTALENT').AsDouble;
FEXTRA1 := DM1.ispProd_S.FieldByName('EXTRA1').AsString;
FEXTRA2 := DM1.ispProd_S.FieldByName('EXTRA2').AsString;
FEXTRA3 := DM1.ispProd_S.FieldByName('EXTRA3').AsString;
FUSERACT1 := DM1.ispProd_S.FieldByName('USERACT1').AsString;
FFECHAACT1 := DM1.ispProd_S.FieldByName('FECHAACT1').AsDateTime;
FUSERACT2 := DM1.ispProd_S.FieldByName('USERACT2').AsString;
FFECHAACT2 := DM1.ispProd_S.FieldByName('FECHAACT2').AsDateTime;
FUSERACT3 := DM1.ispProd_S.FieldByName('USERACT3').AsString;
FFECHAACT3 := DM1.ispProd_S.FieldByName('FECHAACT3').AsDateTime;
FPATHFOTO := DM1.ispProd_S.FieldByName('PATHFOTO').AsString;
FCODCTEPROV := DM1.ispProd_S.FieldByName('CODCTEPROV').AsString;
FCODCTEPROV2 := DM1.ispProd_S.FieldByName('CODCTEPROV2').AsString;
FDESCRIPTEC := DM1.ispProd_S.FieldByName('DESCRIPTEC').AsString;
SetUniVta(FUNIVTA);
FDESCROTA := DM1.ispProd_S.FieldByName('DESCROTA').AsDouble;
FSTATUSROTA := DM1.ispProd_S.FieldByName('STATUSROTA').AsSmallint;
FTIPOCALCULO := DM1.ispProd_S.FieldByName('TIPOCALCULO').AsSmallInt;
FMAXIMO := DM1.ispProd_S.FieldByName('MAXIMO').AsDouble;
FMINIMO := DM1.ispProd_S.FieldByName('MINIMO').AsDouble;
FREORDEN := DM1.ispProd_S.FieldByName('REORDEN').AsDouble;
FPRIORIDAD := DM1.ispProd_S.FieldByName('PRIORIDAD').AsInteger;
FLONGITUD := DM1.ispProd_S.FieldByName('LONGITUD').AsDouble;
FFIGURA := DM1.ispProd_S.FieldByName('FIGURA').AsString;
FNUMSERIE := DM1.ispProd_S.FieldByName('NUMSERIE').AsString;
FCAMBIO := DM1.ispProd_S.FieldByName('CAMBIO').AsSmallInt;
FCLAVESAT := DM1.ispProd_S.FieldByName('CLAVEPRODSERV').AsString;
FCLAVEUNIDAD := DM1.ispProd_S.FieldByName('CLAVEUNIDAD').AsString;
FCOBRO_IVA := DM1.ispProd_S.FieldByName('COBRO_IVA').AsSmallInt;
FCOBRO_RETIVA := DM1.ispProd_S.FieldByName('COBRO_RETIVA').AsSmallInt;
FCOBRO_IEPS := DM1.ispProd_S.FieldByName('COBRO_IEPS').AsSmallInt;
FPORC_IVA := DM1.ispProd_S.FieldByName('PORC_IVA').AsDouble;
FPORC_RETIVA := DM1.ispProd_S.FieldByName('PORC_RETIVA').AsDouble;
FPORC_IEPS := DM1.ispProd_S.FieldByName('PORC_IEPS').AsDouble;
FES_DLS := DM1.ispProd_S.FieldByName('ES_DLS').AsSmallInt;
end;
procedure TProducto.RetrieveHRC(AHoja,ARen,ACol:Integer);
begin
FError := 0;
icu1.Close;
icu1.ParamByName('HOJA').AsInteger := AHoja;
icu1.ParamByName('REN').AsInteger := ARen;
icu1.ParamByName('COL').AsInteger := ACol;
icu1.Open;
if icu1.eof then begin
FError := 10;
icu1.Close;
Exit;
end;
FCODPRODSER := icu1.FieldByName('CODPRODSER').AsString;
Retrieve;
icu1.Close;
end;
procedure TProducto.RetrieveDescri(ADescri:String);
begin
FError := 0;
icu2.Close;
icu2.ParamByName('DESCRIPPRO').AsString := ADescri;
icu2.Open;
if icu2.eof then begin
FError := 10;
icu2.Close;
Exit;
end;
FCODPRODSER := icu2.FieldByName('CODPRODSER').AsString;
FDESCRIPPRO := icu2.FieldByName('DESCRIPPRO').AsString;
FUNIVTA := icu2.FieldByName('UNIVTA').AsString;
FCTOREAL := icu2.FieldByName('CTOREAL').AsDouble;
icu2.Close;
end;
procedure TProducto.Save;
var iFolio:Integer;
begin
//
DM1.ispProd_U.ParamByName('CODPRODSER').AsString := FCODPRODSER;
DM1.ispProd_U.ParamByName('DESCRIPPRO').AsString := FDESCRIPPRO;
// DM1.ispProd_U.ParamByName('CARAC1').AsString := FCARAC1;
// DM1.ispProd_U.ParamByName('CARAC2').AsString := FCARAC2;
// DM1.ispProd_U.ParamByName('CARAC3').AsString := FCARAC3;
// DM1.ispProd_U.ParamByName('CATEGPROD').AsString := FCATEGPROD;
DM1.ispProd_U.ParamByName('CODFAMILIA').AsString := FCODFAMILIA;
DM1.ispProd_U.ParamByName('CODCTEPROV').AsString := FCODCTEPROV;
// DM1.ispProd_U.ParamByName('COSTOPROM').AsDouble := FCOSTOPROM;
// DM1.ispProd_U.ParamByName('COSTOSTD').AsDouble := FCOSTOSTD;
// DM1.ispProd_U.ParamByName('COSTOTOTAL').AsDouble := FCOSTOTOTAL;
// DM1.ispProd_U.ParamByName('DIASINVFIS').AsDouble := FDIASINVFIS;
// DM1.ispProd_U.ParamByName('DISTCOMP').AsString := FDISTCOMP;
// DM1.ispProd_U.ParamByName('DISTDEVCTE').AsString := FDISTDEVCTE;
// DM1.ispProd_U.ParamByName('DISTDEVPRO').AsString := FDISTDEVPRO;
// DM1.ispProd_U.ParamByName('DISTVTA').AsString := FDISTVTA;
DM1.ispProd_U.ParamByName('EDOACTPROD').AsSmallInt := FEDOACTPROD;
// DM1.ispProd_U.ParamByName('ESTADPROD').AsSmallInt := FESTADPROD;
// DM1.ispProd_U.ParamByName('EXISCONSIG').AsDouble := FEXISCONSIG;
// DM1.ispProd_U.ParamByName('EXISREMIS').AsDouble := FEXISREMIS;
// DM1.ispProd_U.ParamByName('EXISTOTAL').AsDouble := FEXISTOTAL;
// DM1.ispProd_U.ParamByName('FAMPRDSRV').AsSmallInt := FFAMPRDSRV;
DM1.ispProd_U.ParamByName('FECALTPROD').AsDateTime := FFECALTPROD;
// DM1.ispProd_U.ParamByName('FECHABAJA').AsDateTime := FFECHABAJA;
// DM1.ispProd_U.ParamByName('FECINIEST').AsDateTime := FFECINIEST;
// DM1.ispProd_U.ParamByName('FECULTCOMP').AsDateTime := FFECULTCOMP;
// DM1.ispProd_U.ParamByName('FECULTENTP').AsDateTime := FFECULTENTP;
// DM1.ispProd_U.ParamByName('FECULTSALP').AsDateTime := FFECULTSALP;
// DM1.ispProd_U.ParamByName('FECULTVTAP').AsDateTime := FFECULTVTAP;
// DM1.ispProd_U.ParamByName('PCIOCOMPRA').AsDouble := FPCIOCOMPRA;
// DM1.ispProd_U.ParamByName('DESCTO1').AsDouble := FDESCTO1;
// DM1.ispProd_U.ParamByName('DESCTO2').AsDouble := FDESCTO2;
// DM1.ispProd_U.ParamByName('DESCTO3').AsDouble := FDESCTO3;
// DM1.ispProd_U.ParamByName('DESCTO4').AsDouble := FDESCTO4;
// DM1.ispProd_U.ParamByName('DESCTO5').AsDouble := FDESCTO5;
// DM1.ispProd_U.ParamByName('DESCTO6').AsDouble := FDESCTO6;
// DM1.ispProd_U.ParamByName('DESCTO7').AsDouble := FDESCTO7;
// DM1.ispProd_U.ParamByName('DESCTO8').AsDouble := FDESCTO8;
// DM1.ispProd_U.ParamByName('DESCTO9').AsDouble := FDESCTO9;
// DM1.ispProd_U.ParamByName('DESCTO10').AsDouble := FDESCTO10;
// DM1.ispProd_U.ParamByName('PCIONETO').AsDouble := FPCIONETO;
// DM1.ispProd_U.ParamByName('GTOSIMPORT').AsDouble := FGTOSIMPORT;
// DM1.ispProd_U.ParamByName('GTOSFLETE').AsDouble := FGTOSFLETE;
// DM1.ispProd_U.ParamByName('GTOSOTROS').AsDouble := FGTOSOTROS;
DM1.ispProd_U.ParamByName('CTOREAL').AsDouble := FCTOREAL;
// DM1.ispProd_U.ParamByName('MARGEN1').AsDouble := FMARGEN1;
// DM1.ispProd_U.ParamByName('MARGEN2').AsDouble := FMARGEN2;
// DM1.ispProd_U.ParamByName('MARGEN3').AsDouble := FMARGEN3;
// DM1.ispProd_U.ParamByName('MARGEN4').AsDouble := FMARGEN4;
// DM1.ispProd_U.ParamByName('MARGEN5').AsDouble := FMARGEN5;
// DM1.ispProd_U.ParamByName('MARGEN6').AsDouble := FMARGEN6;
// DM1.ispProd_U.ParamByName('MARGEN7').AsDouble := FMARGEN7;
// DM1.ispProd_U.ParamByName('MARGEN8').AsDouble := FMARGEN8;
// DM1.ispProd_U.ParamByName('MARGEN9').AsDouble := FMARGEN9;
// DM1.ispProd_U.ParamByName('MARGEN10').AsDouble := FMARGEN10;
DM1.ispProd_U.ParamByName('PCIOVTA1').AsDouble := FPCIOVTA1;
DM1.ispProd_U.ParamByName('PCIOVTA2').AsDouble := FPCIOVTA2;
// DM1.ispProd_U.ParamByName('PCIOVTA3').AsDouble := FPCIOVTA3;
// DM1.ispProd_U.ParamByName('PCIOVTA4').AsDouble := FPCIOVTA4;
// DM1.ispProd_U.ParamByName('PCIOVTA5').AsDouble := FPCIOVTA5;
// DM1.ispProd_U.ParamByName('PCIOVTA6').AsDouble := FPCIOVTA6;
// DM1.ispProd_U.ParamByName('PCIOVTA7').AsDouble := FPCIOVTA7;
// DM1.ispProd_U.ParamByName('PCIOVTA8').AsDouble := FPCIOVTA8;
// DM1.ispProd_U.ParamByName('PCIOVTA9').AsDouble := FPCIOVTA9;
// DM1.ispProd_U.ParamByName('PCIOVTA10').AsDouble := FPCIOVTA10;
// DM1.ispProd_U.ParamByName('PEDIMENTOS').AsSmallInt := FPEDIMENTOS;
DM1.ispProd_U.ParamByName('PESO').AsDouble := FPESO;
// DM1.ispProd_U.ParamByName('PORCOMVTA').AsDouble := FPORCOMVTA;
// DM1.ispProd_U.ParamByName('PORDESCAUT').AsDouble := FPORDESCAUT;
// DM1.ispProd_U.ParamByName('PORC2VTA').AsDouble := FPORC2VTA;
// DM1.ispProd_U.ParamByName('PORC3VTA').AsDouble := FPORC3VTA;
// DM1.ispProd_U.ParamByName('PORC4VTA').AsDouble := FPORC4VTA;
// DM1.ispProd_U.ParamByName('PORC5VTA').AsDouble := FPORC5VTA;
// DM1.ispProd_U.ParamByName('PORCMARGEN').AsDouble := FPORCMARGEN;
// DM1.ispProd_U.ParamByName('SERIES').AsSmallInt := FSERIES;
// DM1.ispProd_U.ParamByName('TABMEDIDA').AsString := FTABMEDIDA;
// DM1.ispProd_U.ParamByName('TIPOPROD').AsString := FTIPOPROD;
// DM1.ispProd_U.ParamByName('ULTCOSTO').AsDouble := FULTCOSTO;
// DM1.ispProd_U.ParamByName('UNIDPEDCTE').AsDouble := FUNIDPEDCTE;
// DM1.ispProd_U.ParamByName('UNIDPEDPRO').AsDouble := FUNIDPEDPRO;
DM1.ispProd_U.ParamByName('UNIVTA').AsString := FUNIVTA;
// DM1.ispProd_U.ParamByName('UNIADQ').AsString := FUNIADQ;
// DM1.ispProd_U.ParamByName('INCLUYE').AsString := FINCLUYE;
// DM1.ispProd_U.ParamByName('ERRORCOSTO').AsSmallInt := FERRORCOSTO;
// DM1.ispProd_U.ParamByName('FECERRCOST').AsDateTime := FFECERRCOST;
// DM1.ispProd_U.ParamByName('COSTOENT').AsDouble := FCOSTOENT;
// DM1.ispProd_U.ParamByName('TOTALENT').AsDouble := FTOTALENT;
// DM1.ispProd_U.ParamByName('EXTRA1').AsString := FEXTRA1;
// DM1.ispProd_U.ParamByName('EXTRA2').AsString := FEXTRA2;
// DM1.ispProd_U.ParamByName('EXTRA3').AsString := FEXTRA3;
DM1.ispProd_U.ParamByName('USERACT1').AsString := FUSERACT1;
DM1.ispProd_U.ParamByName('FECHAACT1').AsDateTime := FFECHAACT1;
// DM1.ispProd_U.ParamByName('USERACT2').AsString := FUSERACT2;
// DM1.ispProd_U.ParamByName('FECHAACT2').AsDateTime := FFECHAACT2;
// DM1.ispProd_U.ParamByName('USERACT3').AsString := FUSERACT3;
// DM1.ispProd_U.ParamByName('FECHAACT3').AsDateTime := FFECHAACT3;
// DM1.ispProd_U.ParamByName('PATHFOTO').AsString := FPATHFOTO;
// DM1.ispProd_U.ParamByName('CODCTEPROV2').AsString := FCODCTEPROV2;
// DM1.ispProd_U.ParamByName('DESCROTA').AsDouble := FDESCROTA;
// DM1.ispProd_U.ParamByName('STATUSROTA').AsDouble := FSTATUSROTA;
DM1.ispProd_U.ParamByName('TIPOCALCULO').AsSmallInt := FTIPOCALCULO;
DM1.ispProd_U.ParamByName('MAXIMO').AsDouble := FMAXIMO;
DM1.ispProd_U.ParamByName('MINIMO').AsDouble := FMINIMO;
DM1.ispProd_U.ParamByName('REORDEN').AsDouble:= FREORDEN;
DM1.ispProd_U.ParamByName('PRIORIDAD').AsInteger:= FPRIORIDAD;
DM1.ispProd_U.ParamByName('LONGITUD').AsDouble:= FLONGITUD;
DM1.ispProd_U.ParamByName('FIGURA').AsString:= FFIGURA;
DM1.ispProd_U.ParamByName('NUMSERIE').AsString:= FNUMSERIE;
DM1.ispProd_U.ParamByName('CAMBIO').AsSmallInt:= FCAMBIO;
DM1.ispProd_U.ParamByName('TIPOPROD').AsString:= FTIPOPROD;
DM1.ispProd_U.ParamByName('PATHFOTO').AsString:= FPATHFOTO;
DM1.ispProd_U.ParamByName('DESCRIPTEC').AsString:= FDESCRIPTEC;
DM1.ispProd_U.ExecProc;
end;
procedure TProducto.Delete;
begin
//
// DM1.ispProd_U.ParamByName('CODPRODSER').AsString := FCODPRODSER;
// DM1.ispDoc_U.ExecProc;
end;
//-------------------------------------------------------------
function TProducto.FormateaCodigo(ptCodigo :String):String;
var tKey,tLet,tNum:String;
iPos,iCant:Integer;
begin
tKey := sm.Strip (ptCodigo);
iPos := pos(tKey,'-');
if iPos <= 0 then begin
tLet := sm.GetAlpha (tKey);
tLet := uppercase(tLet);
tNum := sm.GetDigit (tKey);
tNum := sm.PadLeft (tNum,4,'0');
tKey := tLet+'-'+tNum;
end else begin
tLet := copy(tKey,1,iPos-1);
tNum := copy(tKey,iPos+1,length(tKey) - iPos);
tNum := sm.PadLeft (tNum,4,'0');
tKey := tLet+'-'+tNum;
end;
Result := tKey;
end;
procedure TProducto.Clear;
begin
FCODPRODSER:='';
FDESCRIPPRO:='';
FCARAC1:='';
FCARAC2:='';
FCARAC3:='';
FCATEGPROD:='';
FCODFAMILIA:='';
FCOSTOPROM:=0;
FCOSTOSTD:=0;
FCOSTOTOTAL:=0;
FDIASINVFIS:=0;
FDISTCOMP:='';
FDISTDEVCTE:='';
FDISTDEVPRO:='';
FDISTVTA:='';
FEDOACTPROD:=0;
FESTADPROD:=0;
FEXISCONSIG:=0;
FEXISREMIS:=0;
FEXISTOTAL:=0;
FFAMPRDSRV:=0;
FFECALTPROD:=1;
FFECHABAJA:=1;
FFECINIEST:=1;
FFECULTCOMP:=1;
FFECULTENTP:=1;
FFECULTSALP:=1;
FFECULTVTAP:=1;
FPCIOCOMPRA:=0;
FDESCTO1:=0;
FDESCTO2:=0;
FDESCTO3:=0;
FDESCTO4:=0;
FDESCTO5:=0;
FDESCTO6:=0;
FDESCTO7:=0;
FDESCTO8:=0;
FDESCTO9:=0;
FDESCTO10:=0;
FPCIONETO:=0;
FGTOSIMPORT:=0;
FGTOSFLETE:=0;
FGTOSOTROS:=0;
FCTOREAL:=0;
FMARGEN1:=0;
FMARGEN2:=0;
FMARGEN3:=0;
FMARGEN4:=0;
FMARGEN5:=0;
FMARGEN6:=0;
FMARGEN7:=0;
FMARGEN8:=0;
FMARGEN9:=0;
FMARGEN10:=0;
FPCIOVTA1:=0;
FPCIOVTA2:=0;
FPCIOVTA3:=0;
FPCIOVTA4:=0;
FPCIOVTA5:=0;
FPCIOVTA6:=0;
FPCIOVTA7:=0;
FPCIOVTA8:=0;
FPCIOVTA9:=0;
FPCIOVTA10:=0;
FPEDIMENTOS:=0;
FPESO:=0;
FPORCOMVTA:=0;
FPORDESCAUT:=0;
FPORC2VTA:=0;
FPORC3VTA:=0;
FPORC4VTA:=0;
FPORC5VTA:=0;
FPORCMARGEN:=0;
FSERIES:=0;
FTABMEDIDA:='';
FTIPOPROD:='';
FULTCOSTO:=0;
FUNIDPEDCTE:=0;
FUNIDPEDPRO:=0;
FUNIVTA:='';
FUNIADQ:='';
FINCLUYE:='';
FERRORCOSTO:=0;
FFECERRCOST:=1;
FCOSTOENT:=0;
FTOTALENT:=0;
FEXTRA1:='';
FEXTRA2:='';
FEXTRA3:='';
FUSERACT1:='';
FFECHAACT1:=1;
FUSERACT2:='';
FFECHAACT2:=1;
FUSERACT3:='';
FFECHAACT3:=1;
FPATHFOTO:='';
FCODCTEPROV:='';
FCODCTEPROV2:='';
FUNIVTADESC:=''; //Descripcion de Unidad de Venta
FUNIADQDESC:=''; //Descripcion de Unidad de Compra / adquisición
FDESCROTA:=0;
FSTATUSROTA:=0;
FTIPOCALCULO:=0;
FMAXIMO:=0;
FMINIMO:=0;
FREORDEN:=0;
FPRIORIDAD:=0;
FLONGITUD:=0;
FFIGURA:='';
FError:=0;
end;
//============================================================
function TProducto.GetCODPRODSER:String;
begin
Result := FCODPRODSER
end;
procedure TProducto.SetCODPRODSER(pCODPRODSER:String);
begin
// FCODPRODSER := FormateaCodigo(pCODPRODSER);
//-- Le quite el formateo debido a que en AR no se utiliza,
//-- y talvez en ASH no haya problema si se lo quito
//-- 08/Mar/2010 14:29 FPG
FCODPRODSER := UpperCase(pCODPRODSER);
end;
function TProducto.GetDESCRIPPRO:String;
begin
Result := FDESCRIPPRO
end;
procedure TProducto.SetDESCRIPPRO(pDESCRIPPRO:String);
begin
FDESCRIPPRO := pDESCRIPPRO;
end;
function TProducto.GetCARAC1:String;
begin
Result := FCARAC1
end;
procedure TProducto.SetCARAC1(pCARAC1:String);
begin
FCARAC1 := pCARAC1;
end;
function TProducto.GetCARAC2:String;
begin
Result := FCARAC2
end;
procedure TProducto.SetCARAC2(pCARAC2:String);
begin
FCARAC2 := pCARAC2;
end;
function TProducto.GetCARAC3:String;
begin
Result := FCARAC3
end;
procedure TProducto.SetCARAC3(pCARAC3:String);
begin
FCARAC3 := pCARAC3;
end;
function TProducto.GetCATEGPROD:String;
begin
Result := FCATEGPROD
end;
procedure TProducto.SetCATEGPROD(pCATEGPROD:String);
begin
FCATEGPROD := pCATEGPROD;
end;
function TProducto.GetCODFAMILIA:String;
begin
Result := FCODFAMILIA
end;
procedure TProducto.SetCODFAMILIA(pCODFAMILIA:String);
begin
FCODFAMILIA := pCODFAMILIA;
end;
function TProducto.GetCOSTOPROM:Double;
begin
Result := FCOSTOPROM
end;
procedure TProducto.SetCOSTOPROM(pCOSTOPROM:Double);
begin
FCOSTOPROM := pCOSTOPROM;
end;
function TProducto.GetCOSTOSTD:Double;
begin
Result := FCOSTOSTD
end;
procedure TProducto.SetCOSTOSTD(pCOSTOSTD:Double);
begin
FCOSTOSTD := pCOSTOSTD;
end;
function TProducto.GetCOSTOTOTAL:Double;
begin
Result := FCOSTOTOTAL
end;
procedure TProducto.SetCOSTOTOTAL(pCOSTOTOTAL:Double);
begin
FCOSTOTOTAL := pCOSTOTOTAL;
end;
function TProducto.GetDIASINVFIS:Double;
begin
Result := FDIASINVFIS
end;
procedure TProducto.SetDIASINVFIS(pDIASINVFIS:Double);
begin
FDIASINVFIS := pDIASINVFIS;
end;
function TProducto.GetDISTCOMP:String;
begin
Result := FDISTCOMP
end;
procedure TProducto.SetDISTCOMP(pDISTCOMP:String);
begin
FDISTCOMP := pDISTCOMP;
end;
function TProducto.GetDISTDEVCTE:String;
begin
Result := FDISTDEVCTE
end;
procedure TProducto.SetDISTDEVCTE(pDISTDEVCTE:String);
begin
FDISTDEVCTE := pDISTDEVCTE;
end;
function TProducto.GetDISTDEVPRO:String;
begin
Result := FDISTDEVPRO
end;
procedure TProducto.SetDISTDEVPRO(pDISTDEVPRO:String);
begin
FDISTDEVPRO := pDISTDEVPRO;
end;
function TProducto.GetDISTVTA:String;
begin
Result := FDISTVTA
end;
procedure TProducto.SetDISTVTA(pDISTVTA:String);
begin
FDISTVTA := pDISTVTA;
end;
function TProducto.GetEDOACTPROD:SmallInt;
begin
Result := FEDOACTPROD
end;
procedure TProducto.SetEDOACTPROD(pEDOACTPROD:SmallInt);
begin
FEDOACTPROD := pEDOACTPROD;
end;
function TProducto.GetESTADPROD:SmallInt;
begin
Result := FESTADPROD
end;
procedure TProducto.SetESTADPROD(pESTADPROD:SmallInt);
begin
FESTADPROD := pESTADPROD;
end;
function TProducto.GetEXISCONSIG:Double;
begin
Result := FEXISCONSIG
end;
procedure TProducto.SetEXISCONSIG(pEXISCONSIG:Double);
begin
FEXISCONSIG := pEXISCONSIG;
end;
function TProducto.GetEXISREMIS:Double;
begin
Result := FEXISREMIS
end;
procedure TProducto.SetEXISREMIS(pEXISREMIS:Double);
begin
FEXISREMIS := pEXISREMIS;
end;
function TProducto.GetEXISTOTAL:Double;
begin
icu.ParamByName('CodPRodSer').AsString := FCODPRODSER;
icu.Open;
FEXISTOTAL := icu.Fields[0].AsDouble;
icu.Close;
Result := FEXISTOTAL
end;
function TProducto.GetEXISALMACEN:Double;
begin
icu0.ParamByName('CodPRodSer').AsString := FCODPRODSER;
icu0.ParamByName('NumAlmac').AsString := FNUMALMAC;
icu0.Open;
FEXISALMACEN := icu0.Fields[0].AsDouble;
FFECCONTEO := icu0.Fields[1].AsDateTime;
icu0.Close;
Result := FEXISALMACEN;
end;
procedure TProducto.SetEXISTOTAL(pEXISTOTAL:Double);
begin
FEXISTOTAL := pEXISTOTAL;
end;
function TProducto.GetFAMPRDSRV:SmallInt;
begin
Result := FFAMPRDSRV
end;
procedure TProducto.SetFAMPRDSRV(pFAMPRDSRV:SmallInt);
begin
FFAMPRDSRV := pFAMPRDSRV;
end;
function TProducto.GetFECALTPROD:TDateTime;
begin
Result := FFECALTPROD
end;
procedure TProducto.SetFECALTPROD(pFECALTPROD:TDateTime);
begin
FFECALTPROD := pFECALTPROD;
end;
function TProducto.GetFECHABAJA:TDateTime;
begin
Result := FFECHABAJA
end;
procedure TProducto.SetFECHABAJA(pFECHABAJA:TDateTime);
begin
FFECHABAJA := pFECHABAJA;
end;
function TProducto.GetFECINIEST:TDateTime;
begin
Result := FFECINIEST
end;
procedure TProducto.SetFECINIEST(pFECINIEST:TDateTime);
begin
FFECINIEST := pFECINIEST;
end;
function TProducto.GetFECULTCOMP:TDateTime;
begin
Result := FFECULTCOMP
end;
procedure TProducto.SetFECULTCOMP(pFECULTCOMP:TDateTime);
begin
FFECULTCOMP := pFECULTCOMP;
end;
function TProducto.GetFECULTENTP:TDateTime;
begin
Result := FFECULTENTP
end;
procedure TProducto.SetFECULTENTP(pFECULTENTP:TDateTime);
begin
FFECULTENTP := pFECULTENTP;
end;
function TProducto.GetFECULTSALP:TDateTime;
begin
Result := FFECULTSALP
end;
procedure TProducto.SetFECULTSALP(pFECULTSALP:TDateTime);
begin
FFECULTSALP := pFECULTSALP;
end;
function TProducto.GetFECULTVTAP:TDateTime;
begin
Result := FFECULTVTAP
end;
procedure TProducto.SetFECULTVTAP(pFECULTVTAP:TDateTime);
begin
FFECULTVTAP := pFECULTVTAP;
end;
function TProducto.GetPCIOCOMPRA:Double;
begin
Result := FPCIOCOMPRA
end;
procedure TProducto.SetPCIOCOMPRA(pPCIOCOMPRA:Double);
begin
FPCIOCOMPRA := pPCIOCOMPRA;
end;
function TProducto.GetDESCTO1:Double;
begin
Result := FDESCTO1
end;
procedure TProducto.SetDESCTO1(pDESCTO1:Double);
begin
FDESCTO1 := pDESCTO1;
end;
function TProducto.GetDESCTO2:Double;
begin
Result := FDESCTO2
end;
procedure TProducto.SetDESCTO2(pDESCTO2:Double);
begin
FDESCTO2 := pDESCTO2;
end;
function TProducto.GetDESCTO3:Double;
begin
Result := FDESCTO3
end;
procedure TProducto.SetDESCTO3(pDESCTO3:Double);
begin
FDESCTO3 := pDESCTO3;
end;
function TProducto.GetDESCTO4:Double;
begin
Result := FDESCTO4
end;
procedure TProducto.SetDESCTO4(pDESCTO4:Double);
begin
FDESCTO4 := pDESCTO4;
end;
function TProducto.GetDESCTO5:Double;
begin
Result := FDESCTO5
end;
procedure TProducto.SetDESCTO5(pDESCTO5:Double);
begin
FDESCTO5 := pDESCTO5;
end;
function TProducto.GetDESCTO6:Double;
begin
Result := FDESCTO6
end;
procedure TProducto.SetDESCTO6(pDESCTO6:Double);
begin
FDESCTO6 := pDESCTO6;
end;
function TProducto.GetDESCTO7:Double;
begin
Result := FDESCTO7
end;
procedure TProducto.SetDESCTO7(pDESCTO7:Double);
begin
FDESCTO7 := pDESCTO7;
end;
function TProducto.GetDESCTO8:Double;
begin
Result := FDESCTO8
end;
procedure TProducto.SetDESCTO8(pDESCTO8:Double);
begin
FDESCTO8 := pDESCTO8;
end;
function TProducto.GetDESCTO9:Double;
begin
Result := FDESCTO9
end;
procedure TProducto.SetDESCTO9(pDESCTO9:Double);
begin
FDESCTO9 := pDESCTO9;
end;
function TProducto.GetDESCTO10:Double;
begin
Result := FDESCTO10
end;
procedure TProducto.SetDESCTO10(pDESCTO10:Double);
begin
FDESCTO10 := pDESCTO10;
end;
function TProducto.GetPCIONETO:Double;
begin
Result := FPCIONETO
end;
procedure TProducto.SetPCIONETO(pPCIONETO:Double);
begin
FPCIONETO := pPCIONETO;
end;
function TProducto.GetGTOSIMPORT:Double;
begin
Result := FGTOSIMPORT
end;
procedure TProducto.SetGTOSIMPORT(pGTOSIMPORT:Double);
begin
FGTOSIMPORT := pGTOSIMPORT;
end;
function TProducto.GetGTOSFLETE:Double;
begin
Result := FGTOSFLETE
end;
procedure TProducto.SetGTOSFLETE(pGTOSFLETE:Double);
begin
FGTOSFLETE := pGTOSFLETE;
end;
function TProducto.GetGTOSOTROS:Double;
begin
Result := FGTOSOTROS
end;
procedure TProducto.SetGTOSOTROS(pGTOSOTROS:Double);
begin
FGTOSOTROS := pGTOSOTROS;
end;
function TProducto.GetCTOREAL:Double;
begin
Result := FCTOREAL
end;
procedure TProducto.SetCTOREAL(pCTOREAL:Double);
begin
FCTOREAL := pCTOREAL;
end;
function TProducto.GetMARGEN1:Double;
begin
Result := FMARGEN1
end;
procedure TProducto.SetMARGEN1(pMARGEN1:Double);
begin
FMARGEN1 := pMARGEN1;
end;
function TProducto.GetMARGEN2:Double;
begin
Result := FMARGEN2
end;
procedure TProducto.SetMARGEN2(pMARGEN2:Double);
begin
FMARGEN2 := pMARGEN2;
end;
function TProducto.GetMARGEN3:Double;
begin
Result := FMARGEN3
end;
procedure TProducto.SetMARGEN3(pMARGEN3:Double);
begin
FMARGEN3 := pMARGEN3;
end;
function TProducto.GetMARGEN4:Double;
begin
Result := FMARGEN4
end;
procedure TProducto.SetMARGEN4(pMARGEN4:Double);
begin
FMARGEN4 := pMARGEN4;
end;
function TProducto.GetMARGEN5:Double;
begin
Result := FMARGEN5
end;
procedure TProducto.SetMARGEN5(pMARGEN5:Double);
begin
FMARGEN5 := pMARGEN5;
end;
function TProducto.GetMARGEN6:Double;
begin
Result := FMARGEN6
end;
procedure TProducto.SetMARGEN6(pMARGEN6:Double);
begin
FMARGEN6 := pMARGEN6;
end;
function TProducto.GetMARGEN7:Double;
begin
Result := FMARGEN7
end;
procedure TProducto.SetMARGEN7(pMARGEN7:Double);
begin
FMARGEN7 := pMARGEN7;
end;
function TProducto.GetMARGEN8:Double;
begin
Result := FMARGEN8
end;
procedure TProducto.SetMARGEN8(pMARGEN8:Double);
begin
FMARGEN8 := pMARGEN8;
end;
function TProducto.GetMARGEN9:Double;
begin
Result := FMARGEN9
end;
procedure TProducto.SetMARGEN9(pMARGEN9:Double);
begin
FMARGEN9 := pMARGEN9;
end;
function TProducto.GetMARGEN10:Double;
begin
Result := FMARGEN10
end;
procedure TProducto.SetMARGEN10(pMARGEN10:Double);
begin
FMARGEN10 := pMARGEN10;
end;
function TProducto.GetPCIOVTA1:Double;
begin
Result := FPCIOVTA1
end;
procedure TProducto.SetPCIOVTA1(pPCIOVTA1:Double);
begin
FPCIOVTA1 := pPCIOVTA1;
end;
function TProducto.GetPCIOVTA2:Double;
begin
Result := FPCIOVTA2
end;
procedure TProducto.SetPCIOVTA2(pPCIOVTA2:Double);
begin
FPCIOVTA2 := pPCIOVTA2;
end;
function TProducto.GetPCIOVTA3:Double;
begin
Result := FPCIOVTA3
end;
procedure TProducto.SetPCIOVTA3(pPCIOVTA3:Double);
begin
FPCIOVTA3 := pPCIOVTA3;
end;
function TProducto.GetPCIOVTA4:Double;
begin
Result := FPCIOVTA4
end;
procedure TProducto.SetPCIOVTA4(pPCIOVTA4:Double);
begin
FPCIOVTA4 := pPCIOVTA4;
end;
function TProducto.GetPCIOVTA5:Double;
begin
Result := FPCIOVTA5
end;
procedure TProducto.SetPCIOVTA5(pPCIOVTA5:Double);
begin
FPCIOVTA5 := pPCIOVTA5;
end;
function TProducto.GetPCIOVTA6:Double;
begin
Result := FPCIOVTA6
end;
procedure TProducto.SetPCIOVTA6(pPCIOVTA6:Double);
begin
FPCIOVTA6 := pPCIOVTA6;
end;
function TProducto.GetPCIOVTA7:Double;
begin
Result := FPCIOVTA7
end;
procedure TProducto.SetPCIOVTA7(pPCIOVTA7:Double);
begin
FPCIOVTA7 := pPCIOVTA7;
end;
function TProducto.GetPCIOVTA8:Double;
begin
Result := FPCIOVTA8
end;
procedure TProducto.SetPCIOVTA8(pPCIOVTA8:Double);
begin
FPCIOVTA8 := pPCIOVTA8;
end;
function TProducto.GetPCIOVTA9:Double;
begin
Result := FPCIOVTA9
end;
procedure TProducto.SetPCIOVTA9(pPCIOVTA9:Double);
begin
FPCIOVTA9 := pPCIOVTA9;
end;
function TProducto.GetPCIOVTA10:Double;
begin
Result := FPCIOVTA10
end;
procedure TProducto.SetPCIOVTA10(pPCIOVTA10:Double);
begin
FPCIOVTA10 := pPCIOVTA10;
end;
function TProducto.GetPEDIMENTOS:SmallInt;
begin
Result := FPEDIMENTOS
end;
procedure TProducto.SetPEDIMENTOS(pPEDIMENTOS:SmallInt);
begin
FPEDIMENTOS := pPEDIMENTOS;
end;
function TProducto.GetPESO:Double;
begin
Result := FPESO
end;
procedure TProducto.SetPESO(pPESO:Double);
begin
FPESO := pPESO;
end;
function TProducto.GetPORCOMVTA:Double;
begin
Result := FPORCOMVTA
end;
procedure TProducto.SetPORCOMVTA(pPORCOMVTA:Double);
begin
FPORCOMVTA := pPORCOMVTA;
end;
function TProducto.GetPORDESCAUT:Double;
begin
Result := FPORDESCAUT
end;
procedure TProducto.SetPORDESCAUT(pPORDESCAUT:Double);
begin
FPORDESCAUT := pPORDESCAUT;
end;
function TProducto.GetPORC2VTA:Double;
begin
Result := FPORC2VTA
end;
procedure TProducto.SetPORC2VTA(pPORC2VTA:Double);
begin
FPORC2VTA := pPORC2VTA;
end;
function TProducto.GetPORC3VTA:Double;
begin
Result := FPORC3VTA
end;
procedure TProducto.SetPORC3VTA(pPORC3VTA:Double);
begin
FPORC3VTA := pPORC3VTA;
end;
function TProducto.GetPORC4VTA:Double;
begin
Result := FPORC4VTA
end;
procedure TProducto.SetPORC4VTA(pPORC4VTA:Double);
begin
FPORC4VTA := pPORC4VTA;
end;
function TProducto.GetPORC5VTA:Double;
begin
Result := FPORC5VTA
end;
procedure TProducto.SetPORC5VTA(pPORC5VTA:Double);
begin
FPORC5VTA := pPORC5VTA;
end;
function TProducto.GetPORCMARGEN:Double;
begin
Result := FPORCMARGEN
end;
procedure TProducto.SetPORCMARGEN(pPORCMARGEN:Double);
begin
FPORCMARGEN := pPORCMARGEN;
end;
function TProducto.GetSERIES:SmallInt;
begin
Result := FSERIES
end;
procedure TProducto.SetSERIES(pSERIES:SmallInt);
begin
FSERIES := pSERIES;
end;
function TProducto.GetTABMEDIDA:String;
begin
Result := FTABMEDIDA
end;
procedure TProducto.SetTABMEDIDA(pTABMEDIDA:String);
begin
FTABMEDIDA := pTABMEDIDA;
end;
function TProducto.GetTIPOPROD:String;
begin
Result := FTIPOPROD
end;
procedure TProducto.SetTIPOPROD(pTIPOPROD:String);
begin
FTIPOPROD := pTIPOPROD;
end;
function TProducto.GetULTCOSTO:Double;
begin
Result := FULTCOSTO
end;
procedure TProducto.SetULTCOSTO(pULTCOSTO:Double);
begin
FULTCOSTO := pULTCOSTO;
end;
function TProducto.GetUNIDPEDCTE:Double;
begin
Result := FUNIDPEDCTE
end;
procedure TProducto.SetUNIDPEDCTE(pUNIDPEDCTE:Double);
begin
FUNIDPEDCTE := pUNIDPEDCTE;
end;
function TProducto.GetUNIDPEDPRO:Double;
begin
Result := FUNIDPEDPRO
end;
procedure TProducto.SetUNIDPEDPRO(pUNIDPEDPRO:Double);
begin
FUNIDPEDPRO := pUNIDPEDPRO;
end;
function TProducto.GetUNIVTA:String;
begin
Result := FUNIVTA
end;
procedure TProducto.SetUNIVTA(pUNIVTA:String);
begin
pUniVta := Trim(pUniVta);
FUNIVTA := pUniVta;
FUNIVTADESC := oTabla.GetDescri ('11',FUNIVTA);
end;
function TProducto.GetUNIADQ:String;
begin
Result := FUNIADQ
end;
procedure TProducto.SetUNIADQ(pUNIADQ:String);
begin
FUNIADQ := pUNIADQ;
end;
function TProducto.GetINCLUYE:String;
begin
Result := FINCLUYE
end;
procedure TProducto.SetINCLUYE(pINCLUYE:String);
begin
FINCLUYE := pINCLUYE;
end;
function TProducto.GetERRORCOSTO:SmallInt;
begin
Result := FERRORCOSTO
end;
procedure TProducto.SetERRORCOSTO(pERRORCOSTO:SmallInt);
begin
FERRORCOSTO := pERRORCOSTO;
end;
function TProducto.GetFECERRCOST:TDateTime;
begin
Result := FFECERRCOST
end;
procedure TProducto.SetFECERRCOST(pFECERRCOST:TDateTime);
begin
FFECERRCOST := pFECERRCOST;
end;
function TProducto.GetCOSTOENT:Double;
begin
Result := FCOSTOENT
end;
procedure TProducto.SetCOSTOENT(pCOSTOENT:Double);
begin
FCOSTOENT := pCOSTOENT;
end;
function TProducto.GetTOTALENT:Double;
begin
Result := FTOTALENT
end;
procedure TProducto.SetTOTALENT(pTOTALENT:Double);
begin
FTOTALENT := pTOTALENT;
end;
function TProducto.GetEXTRA1:String;
begin
Result := FEXTRA1
end;
procedure TProducto.SetEXTRA1(pEXTRA1:String);
begin
FEXTRA1 := pEXTRA1;
end;
function TProducto.GetEXTRA2:String;
begin
Result := FEXTRA2
end;
procedure TProducto.SetEXTRA2(pEXTRA2:String);
begin
FEXTRA2 := pEXTRA2;
end;
function TProducto.GetEXTRA3:String;
begin
Result := FEXTRA3
end;
procedure TProducto.SetEXTRA3(pEXTRA3:String);
begin
FEXTRA3 := pEXTRA3;
end;
function TProducto.GetUSERACT1:String;
begin
Result := FUSERACT1
end;
procedure TProducto.SetUSERACT1(pUSERACT1:String);
begin
FUSERACT1 := pUSERACT1;
end;
function TProducto.GetFECHAACT1:TDateTime;
begin
Result := FFECHAACT1
end;
procedure TProducto.SetFECHAACT1(pFECHAACT1:TDateTime);
begin
FFECHAACT1 := pFECHAACT1;
end;
function TProducto.GetUSERACT2:String;
begin
Result := FUSERACT2
end;
procedure TProducto.SetUSERACT2(pUSERACT2:String);
begin
FUSERACT2 := pUSERACT2;
end;
function TProducto.GetFECHAACT2:TDateTime;
begin
Result := FFECHAACT2
end;
procedure TProducto.SetFECHAACT2(pFECHAACT2:TDateTime);
begin
FFECHAACT2 := pFECHAACT2;
end;
function TProducto.GetUSERACT3:String;
begin
Result := FUSERACT3
end;
procedure TProducto.SetUSERACT3(pUSERACT3:String);
begin
FUSERACT3 := pUSERACT3;
end;
function TProducto.GetFECHAACT3:TDateTime;
begin
Result := FFECHAACT3
end;
procedure TProducto.SetFECHAACT3(pFECHAACT3:TDateTime);
begin
FFECHAACT3 := pFECHAACT3;
end;
function TProducto.GetPATHFOTO:String;
begin
Result := FPATHFOTO
end;
procedure TProducto.SetPATHFOTO(pPATHFOTO:String);
begin
FPATHFOTO := pPATHFOTO;
end;
function TProducto.ValidarCodigo(ACodigo:String):Integer;
var
t:String;
begin
Result := 0;
// t := sm.GetChars(ACodigo,[' ' ,'/','\','%','?']);
t := sm.GetType(ACodigo,[cfPunct,cfControl,cfDelim]);
if length(t) > 0 then Result := 1;
end;
procedure TProducto.CalculaExistencias;
var
i:Integer;
dAcum:Double;
begin
icu3.ParamByName('CodPRodSer').AsString := FCODPRODSER;
icu3.Open;
dAcum := 0;
i:= 1;
while not icu3.Eof do begin
aExistencia[i].NumAlmacen := icu3.FieldByName('NUMALMAC').AsString;
aExistencia[i].NombreAlmacen := icu3.FieldByName('NOMBREALM').AsString;
aExistencia[i].Existencia := icu3.FieldByName('EXISTENCIA').AsDouble;
{-- Acumular existencias que NO es transito --}
if aExistencia[i].NumAlmacen <> 'T' then
dAcum := dAcum + aExistencia[i].Existencia;
i := i + 1;
if i >= 10 then break;
icu3.Next;
end;
aExistencia[i].NumAlmacen := '*';
aExistencia[i].NombreAlmacen := '* Todos *';
aExistencia[i].Existencia := dAcum;
icu3.Close;
end;
function TProducto.GetExistencia(ANumAlmac:String):Double;
var i:Integer;
begin
Result := 0;
for i := 1 to 10 do begin
if ANumAlmac = aExistencia[i].NumAlmacen then begin
Result := aExistencia[i].Existencia;
break;
end;
end;
end;
function GetNombreStatusRota(piNumero:Smallint):String;
begin
Result := '';
case piNumero of
1: Result := 'Normal';
2: Result := 'Baja';
3: Result := 'Nulo';
end;
end;
end.
|
{$A8} {$R-}
{*************************************************************}
{ }
{ Embarcadero Delphi Visual Component Library }
{ InterBase Express core components }
{ }
{ Copyright (c) 1998-2017 Embarcadero Technologies, Inc.}
{ All rights reserved }
{ }
{ Additional code created by Jeff Overcash and used }
{ with permission. }
{*************************************************************}
unit IBX.IBExtract;
interface
uses
System.Classes, IBX.IBDatabase, IBX.IBDatabaseInfo, IBX.IBSQL, IBX.IBHeader,
System.Generics.Collections, IBX.IB, IBX.IBExternals;
type
TExtractObjectTypes =
(eoDatabase, eoDomain, eoTable, eoView, eoProcedure, eoFunction,
eoGenerator, eoException, eoBLOBFilter, eoRole, eoTrigger, eoForeign,
eoIndexes, eoChecks, eoData, eoEUAUser, eoEncryption, eoGrants,
eoSubscription);
TExtractType =
(etDomain, etTable, etRole, etTrigger, etForeign,
etIndex, etData, etGrant, etCheck, etAlterProc, etEUAUser, etEncryption);
TExtractTypes = Set of TExtractType;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TIBExtract = class(TComponent)
private
FBase : TIBBase;
FMetaData: TStrings;
FDatabaseInfo: TIBDatabaseInfo;
FShowSystem: Boolean;
FIncludeSetTerm: Boolean;
FDefaultCharSet : Integer;
FConnectAsOwner: Boolean;
FOverrideSQLDialect: Integer;
qryTables, qryConstraints, qryRelConstraints, qryEncryption : TIBSQL;
{ used in subscription stuff }
sqlMain, sqlTables, sqlColumns : TIBSQL;
qryProcedures : TIBSQL;
ODSMajorVersion : Integer;
DBSQLDialect : Integer;
FullODS : Extended;
FIncludeComments: Boolean;
{ Private declarations }
function GetDatabase: TIBDatabase;
function GetIndexSegments ( indexname : String) : String;
function GetTransaction: TIBTransaction;
procedure SetDatabase(const Value: TIBDatabase);
procedure SetTransaction(const Value: TIBTransaction);
function PrintValidation(ToValidate : String; flag : Boolean) : String;
procedure ShowGrants(MetaObject: String; Terminator : String);
procedure ShowGrantRoles(Terminator : String);
procedure GetProcedureArgs(Proc : String; args : TStrings);
function GetFieldLength(sql : TIBSQL) : Integer; overload;
function CreateIBSQL : TIBSQL;
procedure BuildConnectString;
function GetDialect : Integer; inline;
procedure SetOverrideSQLDialect(const Value: Integer);
protected
function ExtractDDL(Flag : Boolean; TableName : String) : Boolean;
function ExtractListTable(RelationName, NewName : String; DomainFlag : Boolean; aQry : TIBSQL = nil) : Boolean;
procedure ExtractListView (ViewName : String);
procedure ListData(ObjectName : String);
procedure ListRoles(ObjectName : String = ''); {do not localize}
procedure ListGrants; overload;
procedure ListGrants(ObjectName : string); overload;
procedure ListProcs(ProcedureName : String = ''; AlterOnly : Boolean = false); {do not localize}
procedure ListAllTables(flag : Boolean);
procedure ListTriggers(ObjectName : String = ''; ExtractType : TExtractType = etTrigger); {do not localize}
procedure ListCheck(ObjectName : String = ''; ExtractType : TExtractType = etCheck); {do not localize}
function PrintSet(var Used : Boolean) : String;
procedure ListCreateDb(TargetDb : String = ''); {do not localize}
procedure ListDomains(ObjectName : String = ''; ExtractType : TExtractType = etDomain); {do not localize}
procedure ListException(ExceptionName : String = ''); {do not localize}
procedure ListFilters(FilterName : String = ''); {do not localize}
procedure ListForeign(ObjectName : String = ''; ExtractType : TExtractType = etForeign); {do not localize}
procedure ListFunctions(FunctionName : String = ''); {do not localize}
procedure ListGenerators(GeneratorName : String = ''); {do not localize}
procedure ListIndex(ObjectName : String = ''; ExtractType : TExtractType = etIndex); {do not localize}
procedure ListViews(ViewName : String = ''); {do not localize}
procedure ListEUAUsers;
procedure ListEncryptions(EncryptionName : String = ''); {do not localize}
procedure ListSubscriptions(SubscriptionName : String = ''); { do not localize }
procedure CheckAssigned;
{ Protected declarations }
public
{ Public declarations }
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
function GetArrayField(FieldName : String) : String;
function GetFieldType(FieldType, FieldSubType, FieldScale, FieldSize,
FieldPrec, FieldLen : Integer) : String;
function GetCharacterSets(CharSetId, Collation : Short; CollateOnly : Boolean) : String;
procedure ExtractObject(ObjectType : TExtractObjectTypes; ObjectName : String = ''; {do not localize}
ExtractTypes : TExtractTypes = []);
property DatabaseInfo : TIBDatabaseInfo read FDatabaseInfo;
property Items : TStrings read FMetaData;
published
{ Published declarations }
property Database : TIBDatabase read GetDatabase write SetDatabase;
property Transaction : TIBTransaction read GetTransaction write SetTransaction;
property ShowSystem: Boolean read FShowSystem write FShowSystem default false;
property IncludeSetTerm : Boolean read FIncludeSetTerm write FIncludeSetTerm Default false;
property ConnectAsOwner : Boolean read FConnectAsOwner write FConnectAsOwner Default false;
property OverrideSQLDialect : Integer read FOverrideSQLDialect write SetOverrideSQLDialect;
[default (True)]
property IncludeComments : Boolean read FIncludeComments write FIncludeComments;
end;
TSQLType = record
SqlType : Integer;
TypeName : String;
end;
TPrivTypes = record
PrivFlag : Integer;
PrivString : String;
end;
TSQLTypes = Array[0..14] of TSQLType;
const
priv_UNKNOWN = 1;
priv_SELECT = 2;
priv_INSERT = 4;
priv_UPDATE = 8;
priv_DELETE = 16;
priv_EXECUTE = 32;
priv_REFERENCES = 64;
priv_DECRYPT = 128;
PrivTypes : Array[0..6] of TPrivTypes = (
(PrivFlag : priv_DELETE; PrivString : 'DELETE' ), {do not localize}
(PrivFlag : priv_EXECUTE; PrivString : 'EXECUTE' ), {do not localize}
(PrivFlag : priv_INSERT; PrivString : 'INSERT' ), {do not localize}
(PrivFlag : priv_SELECT; PrivString : 'SELECT' ), {do not localize}
(PrivFlag : priv_UPDATE; PrivString : 'UPDATE' ), {do not localize}
(PrivFlag : priv_REFERENCES; PrivString : 'REFERENCES'), {do not localize}
(PrivFlag : priv_DECRYPT; PrivString : 'DECRYPT')); {do not localize}
SubTypes : Array[0..8] of String = (
'UNKNOWN', {do not localize}
'TEXT', {do not localize}
'BLR', {do not localize}
'ACL', {do not localize}
'RANGES', {do not localize}
'SUMMARY', {do not localize}
'FORMAT', {do not localize}
'TRANSACTION_DESCRIPTION', {do not localize}
'EXTERNAL_FILE_DESCRIPTION'); {do not localize}
TriggerTypes : Array[0..6] of String = (
'', {do not localize}
'BEFORE INSERT', {do not localize}
'AFTER INSERT', {do not localize}
'BEFORE UPDATE', {do not localize}
'AFTER UPDATE', {do not localize}
'BEFORE DELETE', {do not localize}
'AFTER DELETE'); {do not localize}
IntegralSubtypes : Array[0..2] of String = (
'UNKNOWN', {do not localize}
'NUMERIC', {do not localize}
'DECIMAL'); {do not localize}
ODS_VERSION6 = 6; { on-disk structure as of v3.0 }
ODS_VERSION7 = 7; { new on disk structure for fixing index bug }
ODS_VERSION8 = 8; { new btree structure to support pc semantics }
ODS_VERSION9 = 9; { btree leaf pages are always propogated up }
ODS_VERSION10 = 10; { V6.0 features. SQL delimited idetifier,
SQLDATE, and 64-bit exact numeric
type }
ODS_VERSION16 = 16; {XE7 Subscriptions }
{ flags for RDB$FILE_FLAGS }
FILE_shadow = 1;
FILE_inactive = 2;
FILE_manual = 4;
FILE_cache = 8;
FILE_conditional = 16;
{ flags for RDB$LOG_FILES }
LOG_serial = 1;
LOG_default = 2;
LOG_raw = 4;
LOG_overflow = 8;
MAX_INTSUBTYPES = 2;
MAXSUBTYPES = 8; { Top of subtypes array }
{ Object types used in RDB$DEPENDENCIES and RDB$USER_PRIVILEGES }
obj_relation = 0;
obj_view = 1;
obj_trigger = 2;
obj_computed = 3;
obj_validation = 4;
obj_procedure = 5;
obj_expression_index = 6;
obj_exception = 7;
obj_user = 8;
obj_field = 9;
obj_index = 10;
obj_count = 11;
obj_user_group = 12;
obj_sql_role = 13;
obj_subscription = 16;
var
ColumnTypes : TDictionary<SmallInt, string>;
implementation
uses
System.SysUtils, IBX.IBUtils, IBX.IBXConst, System.Character, System.Math;
const
NEWLINE = #13#10; {do not localize}
TERM = ';'; {do not localize}
ProcTerm = '^'; {do not localize}
SPassword = 'Enter Password here'; {do not localize}
CollationSQL =
'SELECT CST.RDB$CHARACTER_SET_NAME, COL.RDB$COLLATION_NAME, CST.RDB$DEFAULT_COLLATE_NAME ' + {do not localize}
' FROM RDB$COLLATIONS COL JOIN RDB$CHARACTER_SETS CST ON ' + {do not localize}
' COL.RDB$CHARACTER_SET_ID = CST.RDB$CHARACTER_SET_ID ' + {do not localize}
' WHERE COL.RDB$COLLATION_ID = :COLLATION AND ' + {do not localize}
' CST.RDB$CHARACTER_SET_ID = :CHAR_SET_ID ' + {do not localize}
' ORDER BY COL.RDB$COLLATION_NAME, CST.RDB$CHARACTER_SET_NAME'; {do not localize}
NonCollationSQL =
'SELECT CST.RDB$CHARACTER_SET_NAME ' + {do not localize}
' FROM RDB$CHARACTER_SETS CST ' + {do not localize}
' WHERE CST.RDB$CHARACTER_SET_ID = :CHARSETID ' + {do not localize}
' ORDER BY CST.RDB$CHARACTER_SET_NAME'; {do not localize}
PrecisionSQL =
'SELECT * FROM RDB$FIELDS ' + {do not localize}
' WHERE RDB$FIELD_NAME = :FIELDNAME'; {do not localize}
ArraySQL =
'SELECT * FROM RDB$FIELD_DIMENSIONS FDIM ' + {do not localize}
' WHERE ' + {do not localize}
' FDIM.RDB$FIELD_NAME = :FIELDNAME ' + {do not localize}
' ORDER BY FDIM.RDB$DIMENSION'; {do not localize}
DefaultCharSetSQL = 'SELECT CST.RDB$CHARACTER_SET_ID ' + {not not localize}
' FROM RDB$CHARACTER_SETS CST JOIN RDB$DATABASE DB ON ' + {do not localize}
' CST.RDB$CHARACTER_SET_NAME = DB.RDB$CHARACTER_SET_NAME '; {do not localize}
{ TIBExtract }
{ ArrayDimensions
Functional description
Retrieves the dimensions of arrays and prints them.
Parameters: fieldname -- the actual name of the array field }
function TIBExtract.GetArrayField(FieldName: String): String;
var
qryArray : TIBSQL;
begin
qryArray := CreateIBSQL;
Result := '['; {do not localize}
qryArray.SQL.Add(ArraySQL);
qryArray.Params.ByName('FieldName').AsTrimString := FieldName; {do not localize}
qryArray.ExecQuery;
{ Format is [lower:upper, lower:upper,..] }
while not qryArray.Eof do
begin
if (qryArray.FieldByName('RDB$DIMENSION').AsInteger > 0) then {do not localize}
Result := Result + ', '; {do not localize}
Result := Result + qryArray.FieldByName('RDB$LOWER_BOUND').AsTrimString + ':' + {do not localize}
qryArray.FieldByName('RDB$UPPER_BOUND').AsTrimString; {do not localize}
qryArray.Next;
end;
Result := Result + '] '; {do not localize}
qryArray.Free;
end;
procedure TIBExtract.CheckAssigned;
begin
if not Assigned(FBase.Transaction) then
IBError(ibxeTransactionNotAssigned, []);
if not Assigned(FBase.Database) then
IBError(ibxeDatabaseNotAssigned, []);
end;
constructor TIBExtract.Create(AOwner: TComponent);
begin
inherited;
FMetaData := TStringList.Create;
FDatabaseInfo := TIBDatabaseInfo.Create(nil);
FBase := TIBBase.Create(self);
if AOwner is TIBDatabase then
Database := TIBDatabase(AOwner);
if AOwner is TIBTransaction then
Transaction := TIBTransaction(AOwner);
FDatabaseInfo.Database := FBase.Database;
FIncludeComments := True;
end;
destructor TIBExtract.Destroy;
begin
FMetaData.Free;
FDatabasEInfo.Free;
{ All owned by component so do not Free }
qryTables := nil;
qryConstraints := nil;
qryRelConstraints := nil;
qryEncryption := nil;
qryProcedures := nil;
FBase.DisposeOf;
FBase := nil;
inherited;
end;
function TIBExtract.ExtractDDL(Flag: Boolean; TableName: String) : Boolean;
var
DidConnect : Boolean;
DidStart : Boolean;
begin
Result := true;
DidConnect := false;
DidStart := false;
if not FBase.Database.Connected then
begin
FBase.Database.Connected := true;
didConnect := true;
end;
FMetaData.Add(Format('SET SQL DIALECT %d;', [GetDialect])); {do not localize}
FMetaData.Add('');
if not FBase.Transaction.Active then
begin
FBase.Transaction.StartTransaction;
DidStart := true;
end;
if TableName <> '' then
begin
if not ExtractListTable(TableName, '', true) then
Result := false;
end
else
begin
ListCreateDb;
ListEUAUsers;
ListEncryptions;
if ConnectAsOwner then
BuildConnectString;
ListFilters;
ListFunctions;
ListDomains;
ListAllTables(flag);
ListIndex;
ListForeign;
ListGenerators;
ListSubscriptions;
ListViews;
ListCheck;
ListException;
ListProcs;
ListTriggers;
ListGrants;
end;
if DidStart then
FBase.Transaction.Commit;
if DidConnect then
FBase.Database.Connected := false;
end;
{ ExtractListTable
Functional description
Shows columns, types, info for a given table name
and text of views.
If a new_name is passed, substitute it for relation_name
relation_name -- Name of table to investigate
new_name -- Name of a new name for a replacement table
domain_flag -- extract needed domains before the table }
function TIBExtract.ExtractListTable(RelationName, NewName: String; DomainFlag: Boolean; aQry: TIBSQL = nil): Boolean;
const
TableListSQL = 'SELECT * FROM RDB$RELATIONS REL JOIN RDB$RELATION_FIELDS RFR ON ' + { Do Not Localize }
' RFR.RDB$RELATION_NAME = REL.RDB$RELATION_NAME JOIN RDB$FIELDS FLD ON ' + { do not localize }
' RFR.RDB$FIELD_SOURCE = FLD.RDB$FIELD_NAME ' + { do not localize }
'WHERE REL.RDB$RELATION_NAME = :RelationName ' + { do not localize }
'ORDER BY RFR.RDB$FIELD_POSITION, RFR.RDB$FIELD_NAME'; { do not localize }
ConstraintSQL = 'SELECT RCO.RDB$CONSTRAINT_NAME, RDB$CONSTRAINT_TYPE, RDB$RELATION_NAME, ' + { do not localize }
'RDB$DEFERRABLE, RDB$INITIALLY_DEFERRED, RDB$INDEX_NAME, RDB$TRIGGER_NAME ' + { do not localize }
'FROM RDB$RELATION_CONSTRAINTS RCO, RDB$CHECK_CONSTRAINTS CON ' + { do not localize }
'WHERE ' + { do not localize }
' CON.RDB$TRIGGER_NAME = :FIELDNAME AND ' + { do not localize }
' CON.RDB$CONSTRAINT_NAME = RCO.RDB$CONSTRAINT_NAME AND ' + { do not localize }
' RCO.RDB$CONSTRAINT_TYPE = ''NOT NULL'' AND ' + { do not localize }
' RCO.RDB$RELATION_NAME = :RELATIONNAME'; { do not localize }
RelConstraintsSQL = 'SELECT * FROM RDB$RELATION_CONSTRAINTS RELC ' + { do not localize }
'WHERE ' + { do not localize }
' (RELC.RDB$CONSTRAINT_TYPE = ''PRIMARY KEY'' OR ' + { do not localize }
' RELC.RDB$CONSTRAINT_TYPE = ''UNIQUE'') AND ' + { do not localize }
' RELC.RDB$RELATION_NAME = :RELATIONNAME ' + { do not localize }
'ORDER BY RELC.RDB$CONSTRAINT_NAME'; { do not localize }
ColumnEncrptionSQL = 'SELECT * FROM RDB$ENCRYPTIONS ' + { do not localize }
'WHERE ' + { do not localize }
' RDB$ENCRYPTION_ID = :ENCRYPTION_ID'; { do not localize }
var
Collation, CharSetId: Short;
ColList, Column, Constraint, TableBase, OnCommit: String;
SubType: Short;
IntChar: Short;
qryMain: TIBSQL;
PrecisionKnown, ValidRelation: Boolean;
FieldScale, FieldType: Integer;
function FixupDefault(default: string): String;
var
i: Integer;
begin
if (GetDialect = 1) or (default [high(default)] <> '"') then
Exit(default);
i := default.ToUpper.IndexOf('DEFAULT ') + 8;
while (i <= High(default)) and (default [i] = ' ') do
Inc(i);
if default [i] = '"' then
begin
default [i] := '''';
default [High(default)] := '''';
end;
Result := default;
end;
begin
Result := true;
ColList := ''; { do not localize }
IntChar := 0;
ValidRelation := false;
if DomainFlag then
ListDomains(RelationName);
if not Assigned(qryTables) then
begin
qryTables := CreateIBSQL;
qryTables.sql.Add(TableListSQL);
end;
if not Assigned(qryConstraints) then
begin
qryConstraints := CreateIBSQL;
qryConstraints.sql.Add(ConstraintSQL);
end;
if not Assigned(qryRelConstraints) then
begin
qryRelConstraints := CreateIBSQL;
qryRelConstraints.sql.Add(RelConstraintsSQL);
end;
if not Assigned(qryEncryption) then
begin
qryEncryption := CreateIBSQL;
qryEncryption.sql.Add(ColumnEncrptionSQL);
end;
if Assigned(aQry) then
qryMain := aQry
else
begin
qryMain := qryTables;
qryMain.Params.ByName('RelationName').AsTrimString := RelationName; { do not localize }
qryMain.ExecQuery;
end;
if not qryMain.Eof then
begin
if (FullODS > 11.1) then
case qryMain.FieldByName('RDB$Flags').AsInt64 of
11:
OnCommit := ' ON COMMIT DELETE ROWS';
19:
OnCommit := ' ON COMMIT PRESERVE ROWS';
else
OnCommit := '';
end
else
OnCommit := '';
ValidRelation := true;
if (not qryMain.FieldByName('RDB$OWNER_NAME').IsNull) and { do not localize }
(Trim(qryMain.FieldByName('RDB$OWNER_NAME').AsTrimString) <> '') then { do not localize }
if IncludeComments then
FMetaData.Add(Format('%s/* Table: %s, Owner: %s */%s', { do not localize }
[NEWLINE, RelationName, qryMain.FieldByName('RDB$OWNER_NAME').AsTrimString, NEWLINE])); { do not localize }
TableBase := 'CREATE TABLE %s ';
if FullODS > 11.1 then
if qryMain.FieldByName('RDB$RELATION_TYPE').AsString.Contains('TEMPORARY') then
TableBase := 'CREATE GLOBAL TEMPORARY TABLE %s';
if NewName <> '' then { do not localize }
FMetaData.Add(Format(TableBase, [QuoteIdentifier(GetDialect, NewName)])) { do not localize }
else
FMetaData.Add(Format(TableBase, [QuoteIdentifier(GetDialect, RelationName)])); { do not localize }
if not qryMain.FieldByName('RDB$EXTERNAL_FILE').IsNull then { do not localize }
FMetaData.Add(Format('EXTERNAL FILE %s ', { do not localize }
[QuotedStr(qryMain.FieldByName('RDB$EXTERNAL_FILE').AsTrimString)])); { do not localize }
FMetaData.Add('(');
end;
while (not qryMain.Eof) and qryMain.FieldByName('rdb$relation_name').AsString.Trim.Equals(RelationName.Trim) do
begin
Column := ' ' + QuoteIdentifier(GetDialect, qryMain.FieldByName('RDB$FIELD_NAME').AsTrimString) + TAB; { do not localize }
{ Check first for computed fields, then domains.
If this is a known domain, then just print the domain rather than type
Domains won't have length, array, or blob definitions, but they
may have not null, default and check overriding their definitions }
if not qryMain.FieldByName('rdb$computed_blr').IsNull then { do not localize }
begin
Column := Column + ' COMPUTED BY '; { do not localize }
if not qryMain.FieldByName('RDB$COMPUTED_SOURCE').IsNull then { do not localize }
Column := Column + PrintValidation(qryMain.FieldByName('RDB$COMPUTED_SOURCE').AsTrimString, true); { do not localize }
end
else
begin
FieldType := qryMain.FieldByName('RDB$FIELD_TYPE').AsInteger; { do not localize }
FieldScale := qryMain.FieldByName('RDB$FIELD_SCALE').AsInteger; { do not localize }
if not((qryMain.FieldByName('RDB$FIELD_NAME1').AsString.Trim.StartsWith('RDB$')) and { do not localize }
qryMain.FieldByName('RDB$FIELD_NAME1').AsTrimString[Low(String) + 4].IsNumber) and { do not localize }
(qryMain.FieldByName('RDB$SYSTEM_FLAG').AsInteger <> 1) then { do not localize }
begin
Column := Column + QuoteIdentifier(GetDialect, qryMain.FieldByName('RDB$FIELD_NAME1').AsTrimString); { do not localize }
{ International character sets }
if (qryMain.FieldByName('RDB$FIELD_TYPE').AsInteger in [blr_text, blr_varying]) { do not localize }
and (not qryMain.FieldByName('RDB$COLLATION_ID').IsNull) { do not localize }
and (qryMain.FieldByName('RDB$COLLATION_ID').AsShort <> 0) then { do not localize }
IntChar := 1;
end
else
begin
PrecisionKnown := false;
if ODSMajorVersion >= ODS_VERSION10 then
begin
{ Handle Integral subtypes NUMERIC and DECIMAL }
if qryMain.FieldByName('RDB$FIELD_TYPE').AsShort in { do not localize }
[blr_short, blr_long, blr_int64] then
begin
{ We are ODS >= 10 and could be any Dialect }
if not qryMain.FieldByName('RDB$FIELD_PRECISION').IsNull then { do not localize }
begin
{ We are Dialect >=3 since FIELD_PRECISION is non-NULL }
if (qryMain.FieldByName('RDB$FIELD_SUB_TYPE').AsInteger > 0) and { do not localize }
(qryMain.FieldByName('RDB$FIELD_SUB_TYPE').AsInteger <= MAX_INTSUBTYPES) then { do not localize }
begin
Column := Column + Format('%s(%d, %d)', { do not localize }
[IntegralSubtypes[qryMain.FieldByName('RDB$FIELD_SUB_TYPE').AsInteger], { do not localize }
qryMain.FieldByName('RDB$FIELD_PRECISION').AsInteger, { do not localize }
-qryMain.FieldByName('RDB$FIELD_SCALE').AsInteger]); { do not localize }
PrecisionKnown := true;
end;
end;
end;
end;
if PrecisionKnown = false then
begin
{ Take a stab at numerics and decimals }
if (FieldType = blr_short) and (FieldScale < 0) then
Column := Column + Format('NUMERIC(4, %d)', [-FieldScale]) { do not localize }
else
if (FieldType = blr_long) and (FieldScale < 0) then
Column := Column + Format('NUMERIC(9, %d)', [-FieldScale]) { do not localize }
else
if (FieldType = blr_double) and (FieldScale < 0) then
Column := Column + Format('NUMERIC(15, %d)', [-FieldScale]) { do not localize }
else
Column := Column + ColumnTypes.Items[qryMain.FieldByName('RDB$FIELD_TYPE').AsShort];
end;
if FieldType in [blr_text, blr_varying] then
Column := Column + Format('(%d)', [GetFieldLength(qryMain)]); { do not localize }
{ Catch arrays after printing the type }
if not qryMain.FieldByName('RDB$DIMENSIONS').IsNull then { do not localize }
Column := Column + GetArrayField(qryMain.FieldByName('RDB$FIELD_NAME1').AsTrimString); { do not localize }
if FieldType = blr_blob then
begin
SubType := qryMain.FieldByName('RDB$FIELD_SUB_TYPE').AsShort; { do not localize }
Column := Column + ' SUB_TYPE '; { do not localize }
if (SubType > 0) and (SubType <= MAXSUBTYPES) then
Column := Column + SubTypes[SubType]
else
Column := Column + IntToStr(SubType);
Column := Column + Format(' SEGMENT SIZE %d', { do not localize }
[qryMain.FieldByName('RDB$SEGMENT_LENGTH').AsInteger]); { do not localize }
end;
{ International character sets }
if ((FieldType in [blr_text, blr_varying]) or (FieldType = blr_blob)) and (not qryMain.FieldByName('RDB$CHARACTER_SET_ID').IsNull) and
{ do not localize }
(qryMain.FieldByName('RDB$CHARACTER_SET_ID').AsInteger <> 0) then { do not localize }
begin
{ Override rdb$fields id with relation_fields if present }
CharSetId := 0;
if not qryMain.FieldByName('RDB$CHARACTER_SET_ID').IsNull then { do not localize }
CharSetId := qryMain.FieldByName('RDB$CHARACTER_SET_ID').AsInteger; { do not localize }
Column := Column + GetCharacterSets(CharSetId, 0, false);
IntChar := 1;
end;
end;
{ Handle defaults for columns }
{ Originally This called PrintMetadataTextBlob,
should no longer need }
if not qryMain.FieldByName('RDB$DEFAULT_SOURCE').IsNull then { do not localize }
Column := Column + ' ' + FixupDefault(qryMain.FieldByName('RDB$DEFAULT_SOURCE').AsTrimString); { do not localize }
{ The null flag is either 1 or null (for nullable) . if there is
a constraint name, print that too. Domains cannot have named
constraints. The column name is in rdb$trigger_name in
rdb$check_constraints. We hope we get at most one row back. }
if qryMain.FieldByName('RDB$NULL_FLAG').AsInteger = 1 then { do not localize }
begin
qryConstraints.Params.ByName('FIELDNAME').AsTrimString := qryMain.FieldByName('RDB$FIELD_NAME').AsTrimString; { do not localize }
qryConstraints.Params.ByName('RELATIONNAME').AsTrimString := qryMain.FieldByName('RDB$RELATION_NAME').AsTrimString; { do not localize }
qryConstraints.ExecQuery;
while not qryConstraints.Eof do
begin
if not qryConstraints.FieldByName('RDB$CONSTRAINT_NAME').AsTrimString.StartsWith('INTEG') then { do not localize }
Column := Column + Format(' CONSTRAINT %s', { do not localize }
[QuoteIdentifier(GetDialect, qryConstraints.FieldByName('RDB$CONSTRAINT_NAME').AsTrimString)]); { do not localize }
qryConstraints.Next;
end;
qryConstraints.Close;
Column := Column + ' NOT NULL'; { do not localize }
end;
if ((FieldType in [blr_text, blr_varying]) or (FieldType = blr_blob)) and (not qryMain.FieldByName('RDB$CHARACTER_SET_ID').IsNull) and { do not localize }
(qryMain.FieldByName('RDB$CHARACTER_SET_ID').AsInteger <> 0) and { do not localize }
(IntChar <> 0) then
begin
Collation := 0;
if not qryMain.FieldByName('RDB$COLLATION_ID1').IsNull then { do not localize }
Collation := qryMain.FieldByName('RDB$COLLATION_ID1').AsInteger { do not localize }
else
if not qryMain.FieldByName('RDB$COLLATION_ID').IsNull then { do not localize }
Collation := qryMain.FieldByName('RDB$COLLATION_ID').AsInteger; { do not localize }
CharSetId := 0;
if not qryMain.FieldByName('RDB$CHARACTER_SET_ID').IsNull then { do not localize }
CharSetId := qryMain.FieldByName('RDB$CHARACTER_SET_ID').AsInteger; { do not localize }
if Collation <> 0 then
Column := Column + GetCharacterSets(CharSetId, Collation, true);
end;
end;
if (FullODS >= 13.0) and (not qryMain.FieldByName('RDB$ENCRYPTION_ID').IsNull) then
begin
try
qryEncryption.Params.ByName('ENCRYPTION_ID').AsInteger := qryMain.FieldByName('RDB$ENCRYPTION_ID').AsInteger; { do not localize }
qryEncryption.ExecQuery;
if not qryEncryption.Eof then
begin
Column := Column + ' ENCRYPT WITH ' + { do not localize }
QuoteIdentifier(GetDialect, qryEncryption.FieldByName('RDB$ENCRYPTION_NAME').AsTrimString); { do not localize }
if not qryMain.FieldByName('RDB$DECRYPT_DEFAULT_SOURCE').IsNull then { do not localize }
Column := Column + ' ' + qryMain.FieldByName('RDB$DECRYPT_DEFAULT_SOURCE').AsTrimString; { do not localize }
end;
qryEncryption.Close;
except
// if the user does no have access to the Encryption table to read
// ignore exception. This can happen on upgraded databases as the
// rights are not set correctly in IB 2009
end;
end;
qryMain.Next;
if not qryMain.Eof and qryMain.FieldByName('rdb$relation_name').AsString.Trim.Equals(RelationName) then
Column := Column + ','; { do not localize }
FMetaData.Add(Column);
end;
{ Do primary and unique keys only. references come later }
qryRelConstraints.Params.ByName('relationname').AsTrimString := RelationName; { do not localize }
qryRelConstraints.ExecQuery;
while not qryRelConstraints.Eof do
begin
Constraint := '';
FMetaData.Strings[FMetaData.Count - 1] := FMetaData.Strings[FMetaData.Count - 1] + ','; { do not localize }
{ If the name of the constraint is not INTEG..., print it }
if not qryRelConstraints.FieldByName('RDB$CONSTRAINT_NAME').AsTrimString.StartsWith('INTEG') then { do not localize }
Constraint := Constraint + 'CONSTRAINT ' + { do not localize }
QuoteIdentifier(GetDialect, qryRelConstraints.FieldByName('RDB$CONSTRAINT_NAME').AsTrimString); { do not localize }
if qryRelConstraints.FieldByName('RDB$CONSTRAINT_TYPE').AsTrimString.StartsWith('PRIMARY') then { do not localize }
begin
FMetaData.Add(Constraint + Format(' PRIMARY KEY (%s)', { do not localize }
[GetIndexSegments(qryRelConstraints.FieldByName('RDB$INDEX_NAME').AsTrimString)])); { do not localize }
end
else
if qryRelConstraints.FieldByName('RDB$CONSTRAINT_TYPE').AsTrimString.StartsWith('UNIQUE') then { do not localize }
begin
FMetaData.Add(Constraint + Format(' UNIQUE (%s)', { do not localize }
[GetIndexSegments(qryRelConstraints.FieldByName('RDB$INDEX_NAME').AsTrimString)])); { do not localize }
end;
qryRelConstraints.Next;
end;
if ValidRelation then
FMetaData.Add(')' + OnCommit + TERM);
if not Assigned(aQry) then
qryMain.Close;
qryConstraints.Close;
qryRelConstraints.Close;
qryEncryption.Close;
end;
{ ExtractListView
Functional description
Show text of the specified view.
Use a SQL query to get the info and print it.
Note: This should also contain check option }
procedure TIBExtract.ExtractListView(ViewName: String);
const
ViewsSQL = 'SELECT * FROM RDB$RELATIONS REL ' + {do not localize}
' WHERE ' + {do not localize}
' (REL.RDB$SYSTEM_FLAG <> 1 OR REL.RDB$SYSTEM_FLAG IS NULL) AND ' + {do not localize}
' NOT REL.RDB$VIEW_BLR IS NULL AND ' + {do not localize}
' REL.RDB$RELATION_NAME = :VIEWNAME AND ' + {do not localize}
' REL.RDB$FLAGS = 1 ' + {do not localize}
'ORDER BY REL.RDB$RELATION_ID '; {do not localize}
ColumnsSQL = 'SELECT * FROM RDB$RELATION_FIELDS RFR ' + {do not localize}
'WHERE ' + {do not localize}
' RFR.RDB$RELATION_NAME = :RELATIONNAME ' + {do not localize}
'ORDER BY RFR.RDB$FIELD_POSITION '; {do not localize}
var
qryViews, qryColumns : TIBSQL;
RelationName, ColList : String;
begin
qryViews := CreateIBSQL;
qryColumns := CreateIBSQL;
try
qryViews.SQL.Add(ViewsSQL);
qryViews.Params.ByName('viewname').AsTrimString := ViewName; {do not localize}
qryViews.ExecQuery;
while not qryViews.Eof do
begin
FMetaData.Add('');
RelationName := QuoteIdentifier(GetDialect,
qryViews.FieldByName('RDB$RELATION_NAME').AsTrimString); {do not localize}
if IncludeComments then
FMetaData.Add(Format('%s/* View: %s, Owner: %s */%s', [ {do not localize}
RelationName,
Trim(qryViews.FieldByName('RDB$OWNER_NAME').AsTrimString)])); {do not localize}
FMetaData.Add('');
FMetaData.Add(Format('CREATE VIEW %s (', [RelationName])); {do not localize}
{ Get Column List}
qryColumns.SQL.Add(ColumnsSQL);
qryColumns.Params.ByName('relationname').AsTrimString := RelationName; {do not localize}
qryColumns.ExecQuery;
while not qryColumns.Eof do
begin
ColList := ColList + QuoteIdentifier(GetDialect,
qryColumns.FieldByName('RDB$FIELD_NAME').AsTrimString); {do not localize}
qryColumns.Next;
if not qryColumns.Eof then
ColList := ColList + ', '; {do not localize}
end;
FMetaData.Add(ColList + ') AS'); {do not localize}
FMetaData.Add(qryViews.FieldByName('RDB$VIEW_SOURCE').AsTrimString + Term); {do not localize}
qryViews.Next;
end;
finally
qryViews.Free;
qryColumns.Free;
end;
end;
function TIBExtract.GetCharacterSets(CharSetId, Collation: Short;
CollateOnly: Boolean): String;
var
CharSetSQL : TIBSQL;
DidActivate : Boolean;
begin
if not FBase.Transaction.Active then
begin
FBase.Transaction.StartTransaction;
DidActivate := true;
end
else
DidActivate := false;
Result := '';
CharSetSQL := CreateIBSQL;
try
if Collation <> 0 then
begin
CharSetSQL.SQL.Add(CollationSQL);
CharSetSQL.Params.ByName('Char_Set_Id').AsInteger := CharSetId; {do not localize}
CharSetSQL.Params.ByName('Collation').AsInteger := Collation; {do not localize}
CharSetSQL.ExecQuery;
{ Is specified collation the default collation for character set? }
if (Trim(CharSetSQL.FieldByName('RDB$DEFAULT_COLLATE_NAME').AsTrimString) = {do not localize}
Trim(CharSetSQL.FieldByName('RDB$COLLATION_NAME').AsTrimString)) then {do not localize}
begin
if not CollateOnly then
Result := ' CHARACTER SET ' + Trim(CharSetSQL.FieldByName('RDB$CHARACTER_SET_NAME').AsTrimString); {do not localize}
end
else
if CollateOnly or (CharSetId = FDefaultCharSet) then {do not localize}
Result := ' COLLATE ' + Trim(CharSetSQL.FieldByName('RDB$COLLATION_NAME').AsTrimString) {do not localize}
else
Result := ' CHARACTER SET ' + {do not localize}
Trim(CharSetSQL.FieldByName('RDB$CHARACTER_SET_NAME').AsTrimString) + {do not localize}
' COLLATE ' + {do not localize}
Trim(CharSetSQL.FieldByName('RDB$COLLATION_NAME').AsTrimString); {do not localize}
end
else
if CharSetId <> 0 then
begin
CharSetSQL.SQL.Add(NonCollationSQL);
CharSetSQL.Params.ByName('CharSetId').AsShort := CharSetId; {do not localize}
CharSetSQL.ExecQuery;
if (CharSetId <> FDefaultCharSet) then
Result := ' CHARACTER SET ' + Trim(CharSetSQL.FieldByName('RDB$CHARACTER_SET_NAME').AsTrimString); {do not localize}
end;
finally
CharSetSQL.Free;
end;
if DidActivate then
FBase.Transaction.Commit;
end;
function TIBExtract.GetDatabase: TIBDatabase;
begin
result := FBase.Database;
end;
function TIBExtract.GetDialect: Integer;
begin
if FOverrideSQLDialect = 0 then
Result := FBase.Database.SQLDialect
else
Result := FOverrideSQLDialect;
end;
{ GetIndexSegments
Functional description
returns the list of columns in an index. }
function TIBExtract.GetIndexSegments(IndexName: String): String;
const
IndexNamesSQL =
'SELECT * FROM RDB$INDEX_SEGMENTS SEG ' + {do not localize}
'WHERE SEG.RDB$INDEX_NAME = :INDEXNAME ' + {do not localize}
'ORDER BY SEG.RDB$FIELD_POSITION'; {do not localize}
var
qryColNames : TIBSQL;
begin
{ Query to get column names }
Result := '';
qryColNames := CreateIBSQL;
try
qryColNames.SQL.Add(IndexNamesSQL);
qryColNames.Params.ByName('IndexName').AsTrimString := IndexName; {do not localize}
qryColNames.ExecQuery;
while not qryColNames.Eof do
begin
{ Place a comma and a blank between each segment column name }
Result := Result + QuoteIdentifier(GetDialect,
qryColNames.FieldByName('RDB$FIELD_NAME').AsTrimString); {do not localize}
qryColNames.Next;
if not qryColNames.Eof then
Result := Result + ', '; {do not localize}
end;
finally
qryColNames.Free;
end;
end;
function TIBExtract.GetTransaction: TIBTransaction;
begin
Result := FBase.Transaction;
end;
{ ListAllGrants
Functional description
Print the permissions on all user tables.
Get separate permissions on table/views and then procedures }
procedure TIBExtract.ListGrants;
const
SecuritySQL = 'SELECT * FROM RDB$RELATIONS ' + {do not localize}
'WHERE ' + {do not localize}
' (RDB$SYSTEM_FLAG <> 1 OR RDB$SYSTEM_FLAG IS NULL) AND ' + {do not localize}
' RDB$SECURITY_CLASS STARTING WITH ''SQL$'' ' + {do not localize}
'ORDER BY RDB$RELATION_NAME'; {do not localize}
ProcedureSQL = 'select * from RDB$PROCEDURES ' + {do not localize}
'Order BY RDB$PROCEDURE_NAME'; {do not localize}
SubscriptionSQL = 'select distinct rdb$subscription_name from RDB$SUBSCRIPTIONS ' + {do not localize}
'Order BY RDB$SUBSCRIPTION_NAME'; {do not localize}
var
qryRoles : TIBSQL;
RelationName : String;
begin
ListRoles;
qryRoles := CreateIBSQL;
try
{ This version of cursor gets only sql tables identified by security class
and misses views, getting only null view_source }
FMetaData.Add(''); {do not localize}
if IncludeComments then
FMetaData.Add('/* Grant permissions for this database */'); {do not localize}
FMetaData.Add(''); {do not localize}
try
qryRoles.SQL.Text := SecuritySQL;
qryRoles.ExecQuery;
while not qryRoles.Eof do
begin
RelationName := qryRoles.FieldByName('rdb$relation_Name').AsString.Trim; {do not localize}
ShowGrants(RelationName, Term);
qryRoles.Next;
end;
finally
qryRoles.Close;
end;
ShowGrantRoles(Term);
qryRoles.SQL.Text := ProcedureSQL;
qryRoles.ExecQuery;
try
while not qryRoles.Eof do
begin
ShowGrants(qryRoles.FieldByName('RDB$PROCEDURE_NAME').AsString.Trim, Term); {do not localize}
qryRoles.Next;
end;
finally
qryRoles.Close;
end;
if ODSMajorVersion >= ODS_VERSION16 then
begin
qryRoles.SQL.Text := SubscriptionSQL;
qryRoles.ExecQuery;
try
while not qryRoles.Eof do
begin
ShowGrants(qryRoles.FieldByName('RDB$SUBSCRIPTION_NAME').AsString.Trim, Term); {do not localize}
qryRoles.Next;
end;
finally
qryRoles.Close;
end;
end;
finally
qryRoles.Free;
end;
end;
{ ListAllProcs
Functional description
Shows text of a stored procedure given a name.
or lists procedures if no argument.
Since procedures may reference each other, we will create all
dummy procedures of the correct name, then alter these to their
correct form.
Add the parameter names when these procedures are created.
procname -- Name of procedure to investigate }
procedure TIBExtract.ListProcs(ProcedureName : String; AlterOnly : Boolean);
const
CreateProcedureStr1 = 'CREATE PROCEDURE %s '; {do not localize}
CreateProcedureStr2 = 'BEGIN EXIT; END %s%s'; {do not localize}
ProcedureSQL =
'SELECT PRO.RDB$PROCEDURE_NAME, PRO.RDB$PROCEDURE_SOURCE, RDB$PARAMETER_NAME, RDB$PARAMETER_TYPE, ' + {do not localize}
' RDB$FIELD_TYPE, RDB$FIELD_SCALE, RDB$FIELD_PRECISION, RDB$FIELD_SUB_TYPE, ' + {do not localize}
' RDB$SEGMENT_LENGTH, RDB$COLLATION_ID, RDB$CHARACTER_SET_ID, RDB$CHARACTER_LENGTH ' + {do not localize}
' FROM RDB$PROCEDURES PRO LEFT OUTER join RDB$PROCEDURE_PARAMETERS PRM ON ' + {do not localize}
' PRO.RDB$PROCEDURE_NAME = PRM.RDB$PROCEDURE_NAME LEFT OUTER JOIN RDB$FIELDS FLD ON ' + {do not localize}
' PRM.RDB$FIELD_SOURCE = FLD.RDB$FIELD_NAME ' + {do not localize}
' ORDER BY PRO.RDB$PROCEDURE_NAME, PRM.RDB$PARAMETER_TYPE, PRM.RDB$PARAMETER_NUMBER'; {do not localize}
ProcedureNameSQL =
'SELECT PRO.RDB$PROCEDURE_NAME, PRO.RDB$PROCEDURE_SOURCE, RDB$PARAMETER_NAME, RDB$PARAMETER_TYPE, ' + {do not localize}
' RDB$FIELD_TYPE, RDB$FIELD_SCALE, RDB$FIELD_PRECISION, RDB$FIELD_SUB_TYPE, ' + {do not localize}
' RDB$SEGMENT_LENGTH, RDB$COLLATION_ID, RDB$CHARACTER_SET_ID, RDB$CHARACTER_LENGTH ' + {do not localize}
' FROM RDB$PROCEDURES PRO LEFT OUTER join RDB$PROCEDURE_PARAMETERS PRM ON ' + {do not localize}
' PRO.RDB$PROCEDURE_NAME = PRM.RDB$PROCEDURE_NAME LEFT OUTER JOIN RDB$FIELDS FLD ON ' + {do not localize}
' PRM.RDB$FIELD_SOURCE = FLD.RDB$FIELD_NAME ' + {do not localize}
' WHERE PRO.RDB$PROCEDURE_NAME = :ProcedureName ' + {do not localize}
' ORDER BY PRO.RDB$PROCEDURE_NAME, PRM.RDB$PARAMETER_TYPE, PRM.RDB$PARAMETER_NUMBER'; {do not localize}
var
ProcName : String;
SList, sAlter, sCreate, sArgs : TStrings;
Header : Boolean;
begin
Header := true;
if not Assigned(qryProcedures) then
qryProcedures := CreateIBSQL;
if ProcedureName = '' then
qryProcedures.SQL.Text := ProcedureSQL
else
qryProcedures.SQL.Text := ProcedureNameSQL;
SList := TStringList.Create;
sAlter := TStringList.Create;
sCreate := TStringList.Create;
sArgs := TStringList.Create;
try
{ First the dummy procedures
create the procedures with their parameters }
if Header then
begin
FMetaData.Add('COMMIT WORK;'); {do not localize}
if FIncludeSetTerm then
FMetaData.Add(Format('SET TERM %s %s', [ProcTerm, Term])); {do not localize}
if IncludeComments then
FMetaData.Add(Format('%s/* Stored procedures */%s', [NEWLINE, NEWLINE])); {do not localize}
Header := false;
end;
if ProcedureName <> '' then
qryProcedures.Params.ByName('ProcedureName').AsTrimString := ProcedureName; {do not localize}
qryProcedures.ExecQuery;
while not qryProcedures.Eof do
begin
ProcName := qryProcedures.FieldByName('RDB$PROCEDURE_NAME').AsString.Trim; {do not localize}
SList.Clear;
if not qryProcedures.FieldByName('RDB$PROCEDURE_SOURCE').IsNull then {do not localize}
begin
SList.Text := qryProcedures.FieldByName('RDB$PROCEDURE_SOURCE').AsString.Trim; {do not localize}
while (Slist.Count > 0) and (Trim(SList[0]) = '') do {do not localize}
SList.Delete(0);
if IncludeSetTerm then
SList.Add(' ' + ProcTerm + NEWLINE)
else
SList.Add(' ' + Term + NEWLINE);
sArgs.Clear;
GetProcedureArgs(ProcName, sArgs);
if not AlterOnly then
begin
sCreate.Add(Format(CreateProcedureStr1, [QuoteIdentifier(GetDialect,
ProcName)]));
sCreate.AddStrings(sArgs);
if IncludeSetTerm then
sCreate.Add(Format(CreateProcedureStr2, [ProcTerm, NEWLINE]))
else
sCreate.Add(Format(CreateProcedureStr2, [Term, NEWLINE]));
end;
sAlter.Add('');
sAlter.Add(Format('ALTER PROCEDURE %s ', {do not localize}
[QuoteIdentifier(GetDialect, ProcName)]));
sAlter.AddStrings(sArgs);
end;
sAlter.AddStrings(SList);
end;
{ This query gets the procedure name and the source. We then nest a query
to retrieve the parameters. Alter is used, because the procedures are
already there}
FMetaData.AddStrings(sCreate);
FMetaData.AddStrings(sAlter);
if not Header then
begin
if FIncludeSetTerm then
FMetaData.Add(Format('SET TERM %s %s', [Term, ProcTerm])); {do not localize}
FMetaData.Add('COMMIT WORK;'); {do not localize}
end;
finally
qryProcedures.Close;
SList.Free;
sAlter.Free;
sCreate.Free;
sArgs.Free;
end;
end;
{ ListAllTables
Functional description
Extract the names of all user tables from
rdb$relations. Filter SQL tables by
security class after we fetch them
Parameters: flag -- 0, get all tables }
procedure TIBExtract.ListAllTables(flag: Boolean);
const
TableSQL =
'SELECT * ' +
' FROM RDB$RELATIONS REL JOIN RDB$RELATION_FIELDS RFR ON ' + {do not localize}
' RFR.RDB$RELATION_NAME = REL.RDB$RELATION_NAME JOIN RDB$FIELDS FLD ON ' + {do not localize}
' RFR.RDB$FIELD_SOURCE = FLD.RDB$FIELD_NAME ' + {do not localize}
' where (RDB$SYSTEM_FLAG <> 1 OR RDB$SYSTEM_FLAG IS NULL) AND ' + {do not localize}
' RDB$VIEW_BLR IS NULL ' + {do not localize}
' ORDER BY RDB$RELATION_NAME, RFR.RDB$FIELD_POSITION, RFR.RDB$FIELD_NAME'; {do not localize}
var
qryRelations : TIBSQL;
begin
{ This version of cursor gets only sql tables identified by security class
and misses views, getting only null view_source }
qryRelations := CreateIBSQL;
try
qryRelations.SQL.Text := TableSQL;
qryRelations.ExecQuery;
while not qryRelations.Eof do
begin
if ((qryRelations.FieldByName('RDB$FLAGS').AsInteger <> 1) and {do not localize}
(not Flag)) then
continue;
if flag or (not qryRelations.FieldByName('RDB$SECURITY_CLASS').AsTrimString.StartsWith('SQL$')) then {do not localize}
ExtractListTable(qryRelations.FieldByName('RDB$RELATION_NAME').AsTrimString, {do not localize}
'', false, qryRelations); {do not localize}
end;
finally
qryRelations.Free;
end;
end;
{ ListAllTriggers
Functional description
Lists triggers in general on non-system
tables with sql source only. }
procedure TIBExtract.ListTriggers(ObjectName : String; ExtractType : TExtractType);
const
{ Query gets the trigger info for non-system triggers with
source that are not part of an SQL constraint }
TriggerSQL =
'SELECT * FROM RDB$TRIGGERS TRG JOIN RDB$RELATIONS REL ON ' + {do not localize}
' TRG.RDB$RELATION_NAME = REL.RDB$RELATION_NAME ' + {do not localize}
'WHERE ' +
' (REL.RDB$SYSTEM_FLAG <> 1 OR REL.RDB$SYSTEM_FLAG IS NULL) AND ' + {do not localize}
' NOT EXISTS (SELECT * FROM RDB$CHECK_CONSTRAINTS CHK WHERE ' + {do not localize}
' TRG.RDB$TRIGGER_NAME = CHK.RDB$TRIGGER_NAME) ' + {do not localize}
'ORDER BY TRG.RDB$RELATION_NAME, TRG.RDB$TRIGGER_TYPE, ' + {do not localize}
' TRG.RDB$TRIGGER_SEQUENCE, TRG.RDB$TRIGGER_NAME'; {do not localize}
TriggerNameSQL =
'SELECT * FROM RDB$TRIGGERS TRG JOIN RDB$RELATIONS REL ON ' + {do not localize}
' TRG.RDB$RELATION_NAME = REL.RDB$RELATION_NAME ' + {do not localize}
'WHERE ' + {do not localize}
' REL.RDB$RELATION_NAME = :TableName AND ' + {do not localize}
' (REL.RDB$SYSTEM_FLAG <> 1 OR REL.RDB$SYSTEM_FLAG IS NULL) AND ' + {do not localize}
' NOT EXISTS (SELECT * FROM RDB$CHECK_CONSTRAINTS CHK WHERE ' + {do not localize}
' TRG.RDB$TRIGGER_NAME = CHK.RDB$TRIGGER_NAME) ' + {do not localize}
'ORDER BY TRG.RDB$RELATION_NAME, TRG.RDB$TRIGGER_TYPE, ' + {do not localize}
' TRG.RDB$TRIGGER_SEQUENCE, TRG.RDB$TRIGGER_NAME'; {do not localize}
TriggerByNameSQL =
'SELECT * FROM RDB$TRIGGERS TRG JOIN RDB$RELATIONS REL ON ' + {do not localize}
' TRG.RDB$RELATION_NAME = REL.RDB$RELATION_NAME ' + {do not localize}
'WHERE ' + {do not localize}
' TRG.RDB$TRIGGER_NAME = :TriggerName AND ' + {do not localize}
' (REL.RDB$SYSTEM_FLAG <> 1 OR REL.RDB$SYSTEM_FLAG IS NULL) AND ' + {do not localize}
' NOT EXISTS (SELECT * FROM RDB$CHECK_CONSTRAINTS CHK WHERE ' + {do not localize}
' TRG.RDB$TRIGGER_NAME = CHK.RDB$TRIGGER_NAME) ' + {do not localize}
'ORDER BY TRG.RDB$RELATION_NAME, TRG.RDB$TRIGGER_TYPE, ' + {do not localize}
' TRG.RDB$TRIGGER_SEQUENCE, TRG.RDB$TRIGGER_NAME'; {do not localize}
var
Header : Boolean;
TriggerName, RelationName, InActive: String;
qryTriggers : TIBSQL;
SList : TStrings;
begin
Header := true;
SList := TStringList.Create;
qryTriggers := CreateIBSQL;
try
if ObjectName = '' then {do not localize}
qryTriggers.SQL.Text := TriggerSQL
else
begin
if ExtractType = etTable then
begin
qryTriggers.SQL.Text := TriggerNameSQL;
qryTriggers.Params.ByName('TableName').AsTrimString := ObjectName; {do not localize}
end
else
begin
qryTriggers.SQL.Text := TriggerByNameSQL;
qryTriggers.Params.ByName('TriggerName').AsTrimString := ObjectName; {do not localize}
end;
end;
qryTriggers.ExecQuery;
while not qryTriggers.Eof do
begin
SList.Clear;
if Header then
begin
if FIncludeSetTerm then
FMetaData.Add(Format('SET TERM %s %s%s', [Procterm, Term, NEWLINE])); {do not localize}
if IncludeComments then
FMetaData.Add(Format('%s/* Triggers only will work for SQL triggers */%s', {do not localize}
[NEWLINE, NEWLINE]));
Header := false;
end;
TriggerName := qryTriggers.FieldByName('RDB$TRIGGER_NAME').AsTrimString; {do not localize}
RelationName := qryTriggers.FieldByName('RDB$RELATION_NAME').AsTrimString; {do not localize}
if qryTriggers.FieldByName('RDB$TRIGGER_INACTIVE').IsNull then {do not localize}
InActive := 'INACTIVE' {do not localize}
else
if qryTriggers.FieldByName('RDB$TRIGGER_INACTIVE').AsInteger = 1 then {do not localize}
InActive := 'INACTIVE' {do not localize}
else
InActive := 'ACTIVE'; {do not localize}
if qryTriggers.FieldByName('RDB$FLAGS').AsInteger <> 1 then {do not localize}
SList.Add('/* '); {do not localize}
SList.Add(Format('CREATE TRIGGER %s FOR %s %s%s %s POSITION %d', {do not localize}
[QuoteIdentifier(GetDialect, TriggerName),
QuoteIdentifier(GetDialect, RelationName),
NEWLINE, InActive,
TriggerTypes[qryTriggers.FieldByName('RDB$TRIGGER_TYPE').AsInteger], {do not localize}
qryTriggers.FieldByName('RDB$TRIGGER_SEQUENCE').AsInteger])); {do not localize}
if not qryTriggers.FieldByName('RDB$TRIGGER_SOURCE').IsNull then {do not localize}
SList.Text := SList.Text +
qryTriggers.FieldByName('RDB$TRIGGER_SOURCE').AsTrimString; {do not localize}
if IncludeSetTerm then
SList.Add(' ' + ProcTerm + NEWLINE)
else
SList.Add(' ' + Term + NEWLINE);
if qryTriggers.FieldByName('RDB$FLAGS').AsInteger <> 1 then {do not localize}
SList.Add(' */'); {do not localize}
FMetaData.AddStrings(SList);
qryTriggers.Next;
end;
if not Header then
begin
if IncludeSetTerm then
begin
FMetaData.Add('COMMIT WORK ' + ProcTerm); {do not localize}
FMetaData.Add('SET TERM ' + Term + ProcTerm); {do not localize}
end
else
FMetaData.Add('COMMIT WORK ' + Term); {do not localize}
end;
finally
qryTriggers.Free;
SList.Free;
end;
end;
{ ListCheck
Functional description
List check constraints for all objects to allow forward references }
procedure TIBExtract.ListCheck(ObjectName : String; ExtractType : TExtractType);
const
{ Query gets the check clauses for triggers stored for check constraints }
CheckSQL =
'SELECT * FROM RDB$TRIGGERS TRG JOIN RDB$CHECK_CONSTRAINTS CHK ON ' + {do not localize}
' TRG.RDB$TRIGGER_NAME = CHK.RDB$TRIGGER_NAME ' + {do not localize}
'WHERE ' + {do not localize}
' TRG.RDB$TRIGGER_TYPE = 1 AND ' + {do not localize}
' EXISTS (SELECT RDB$CONSTRAINT_NAME FROM RDB$RELATION_CONSTRAINTS RELC WHERE ' + {do not localize}
' CHK.RDB$CONSTRAINT_NAME = RELC.RDB$CONSTRAINT_NAME) ' + {do not localize}
'ORDER BY CHK.RDB$CONSTRAINT_NAME'; {do not localize}
CheckNameSQL =
'SELECT * FROM RDB$TRIGGERS TRG JOIN RDB$CHECK_CONSTRAINTS CHK ON ' + {do not localize}
' TRG.RDB$TRIGGER_NAME = CHK.RDB$TRIGGER_NAME ' + {do not localize}
'WHERE ' + {do not localize}
' TRG.RDB$RELATION_NAME = :TableName AND ' + {do not localize}
' TRG.RDB$TRIGGER_TYPE = 1 AND ' + {do not localize}
' EXISTS (SELECT RDB$CONSTRAINT_NAME FROM RDB$RELATION_CONSTRAINTS RELC WHERE ' + {do not localize}
' CHK.RDB$CONSTRAINT_NAME = RELC.RDB$CONSTRAINT_NAME) ' + {do not localize}
'ORDER BY CHK.RDB$CONSTRAINT_NAME'; {do not localize}
CheckByNameSQL =
'SELECT * FROM RDB$TRIGGERS TRG JOIN RDB$CHECK_CONSTRAINTS CHK ON ' + {do not localize}
' TRG.RDB$TRIGGER_NAME = CHK.RDB$TRIGGER_NAME ' + {do not localize}
'WHERE ' + {do not localize}
' TRG.RDB$TRIGGER_NAME = :TriggerName AND ' + {do not localize}
' TRG.RDB$TRIGGER_TYPE = 1 AND ' + {do not localize}
' EXISTS (SELECT RDB$CONSTRAINT_NAME FROM RDB$RELATION_CONSTRAINTS RELC WHERE ' + {do not localize}
' CHK.RDB$CONSTRAINT_NAME = RELC.RDB$CONSTRAINT_NAME) ' + {do not localize}
'ORDER BY CHK.RDB$CONSTRAINT_NAME'; {do not localize}
var
qryChecks : TIBSQL;
SList : TStrings;
RelationName : String;
begin
qryChecks := CreateIBSQL;
SList := TStringList.Create;
try
if ObjectName = '' then {do not localize}
qryChecks.SQL.Text := CheckSQL
else
if ExtractType = etTable then
begin
qryChecks.SQL.Text := CheckNameSQL;
qryChecks.Params.ByName('TableName').AsTrimString := ObjectName; {do not localize}
end
else
begin
qryChecks.SQL.Text := CheckByNameSQL;
qryChecks.Params.ByName('TriggerName').AsTrimString := ObjectName; {do not localize}
end;
qryChecks.ExecQuery;
while not qryChecks.Eof do
begin
SList.Clear;
RelationName := qryChecks.FieldByName('RDB$RELATION_NAME').AsTrimString; {do not localize}
SList.Add(Format('ALTER TABLE %s ADD ', {do not localize}
[QuoteIdentifier(GetDialect, RelationName)]));
if not qryChecks.FieldByName('RDB$CONSTRAINT_NAME').AsTrimString.StartsWith('INTEG') then {do not localize}
SList.Add(Format('%sCONSTRAINT %s ', [TAB, {do not localize}
QuoteIdentifier(GetDialect, qryChecks.FieldByName('RDB$CONSTRAINT_NAME').AsTrimString)])); {do not localize}
if not qryChecks.FieldByName('RDB$TRIGGER_SOURCE').IsNull then {do not localize}
SList.Text := SList.Text + qryChecks.FieldByName('RDB$TRIGGER_SOURCE').AsTrimString; {do not localize}
SList.Strings[SList.Count - 1] := SList.Strings[SList.Count - 1] + (Term) + NEWLINE;
FMetaData.AddStrings(SList);
qryChecks.Next;
end;
finally
qryChecks.Free;
SList.Free;
end;
end;
{ ListCreateDb
Functional description
Print the create database command if requested. At least put
the page size in a comment with the extracted db name }
procedure TIBExtract.ListCreateDb(TargetDb : String);
const
CharInfoSQL =
'SELECT * FROM RDB$DATABASE DBP ' + {do not localize}
'WHERE NOT DBP.RDB$CHARACTER_SET_NAME IS NULL ' + {do not localize}
' AND DBP.RDB$CHARACTER_SET_NAME != '' '''; {do not localize}
FilesSQL =
'select * from RDB$FILES ' + {do not localize}
'order BY RDB$SHADOW_NUMBER, RDB$FILE_SEQUENCE'; {do not localize}
LogsSQL =
'SELECT * FROM RDB$LOG_FILES ' + {do not localize}
'ORDER BY RDB$FILE_FLAGS, RDB$FILE_SEQUENCE'; {do not localize}
var
NoDb, First, FirstFile, HasWal, SetUsed : Boolean;
Buffer : String;
qryDB : TIBSQL;
FileFlags, FileLength, FileSequence, FileStart : Integer;
begin
NoDb := FALSE;
First := TRUE;
FirstFile := TRUE;
HasWal := FALSE;
SetUsed := FALSE;
Buffer := ''; {do not localize}
if TargetDb = '' then {do not localize}
begin
Buffer := '/* '; {do not localize}
TargetDb := FBase.Database.DatabaseName;
NoDb := true;
end;
Buffer := Buffer + 'CREATE DATABASE ' + QuotedStr(TargetDb) + ' USER ' + {do not localize}
QuotedStr(FBase.Database.Params.Values['user_name']) + ' password ' + QuotedStr(SPassword) + {do not localize}
' PAGE_SIZE ' + IntToStr(FDatabaseInfo.PageSize); {do not localize}
FMetaData.Add(Buffer);
Buffer := '';
qryDB := CreateIBSQL;
try
qryDB.SQL.Text := CharInfoSQL;
qryDB.ExecQuery;
Buffer := Format(' DEFAULT CHARACTER SET %s', {do not localize}
[qryDB.FieldByName('RDB$CHARACTER_SET_NAME').AsTrimString]); {do not localize}
if FDatabaseInfo.EUAActive then
FMetaData.Add(' WITH ADMIN OPTION'); {do not localize}
if NoDB then
Buffer := Buffer + ' */' {do not localize}
else
Buffer := Buffer + Term;
FMetaData.Add(Buffer);
qryDB.Close;
{List secondary files and shadows as
alter db and create shadow in comment}
qryDB.SQL.Text := FilesSQL;
qryDB.ExecQuery;
while not qryDB.Eof do
begin
if First then
begin
FMetaData.Add(NEWLINE + '/* Add secondary files in comments '); {do not localize}
First := false;
end; //end_if
if qryDB.FieldByName('RDB$FILE_FLAGS').IsNull then {do not localize}
FileFlags := 0
else
FileFlags := qryDB.FieldByName('RDB$FILE_FLAGS').AsInteger; {do not localize}
if qryDB.FieldByName('RDB$FILE_LENGTH').IsNull then {do not localize}
FileLength := 0
else
FileLength := qryDB.FieldByName('RDB$FILE_LENGTH').AsInteger; {do not localize}
if qryDB.FieldByName('RDB$FILE_SEQUENCE').IsNull then {do not localize}
FileSequence := 0
else
FileSequence := qryDB.FieldByName('RDB$FILE_SEQUENCE').AsInteger; {do not localize}
if qryDB.FieldByName('RDB$FILE_START').IsNull then {do not localize}
FileStart := 0
else
FileStart := qryDB.FieldByName('RDB$FILE_START').AsInteger; {do not localize}
{ Pure secondary files }
if FileFlags = 0 then
begin
Buffer := Format('%sALTER DATABASE ADD FILE ''%s''', {do not localize}
[NEWLINE, qryDB.FieldByName('RDB$FILE_NAME').AsTrimString]); {do not localize}
if FileStart <> 0 then
Buffer := Buffer + Format(' STARTING %d', [FileStart]); {do not localize}
if FileLength <> 0 then
Buffer := Buffer + Format(' LENGTH %d', [FileLength]); {do not localize}
FMetaData.Add(Buffer);
end; //end_if
if (FileFlags and FILE_cache) <> 0 then
FMetaData.Add(Format('%sALTER DATABASE ADD CACHE ''%s'' LENGTH %d', {do not localize}
[NEWLINE, qryDB.FieldByName('RDB$FILE_NAME').AsTrimString, FileLength])); {do not localize}
Buffer := '';
if (FileFlags and FILE_shadow) <> 0 then
begin
if FileSequence <> 0 then
Buffer := Format('%sFILE ''%s''', {do not localize}
[TAB, qryDB.FieldByName('RDB$FILE_NAME').AsTrimString]) {do not localize}
else
begin
Buffer := Format('%sCREATE SHADOW %d ''%s'' ', {do not localize}
[NEWLINE, qryDB.FieldByName('RDB$SHADOW_NUMBER').AsInteger, {do not localize}
qryDB.FieldByName('RDB$FILE_NAME').AsTrimString]); {do not localize}
if (FileFlags and FILE_inactive) <> 0 then
Buffer := Buffer + 'INACTIVE '; {do not localize}
if (FileFlags and FILE_manual) <> 0 then
Buffer := Buffer + 'MANUAL ' {do not localize}
else
Buffer := Buffer + 'AUTO '; {do not localize}
if (FileFlags and FILE_conditional) <> 0 then
Buffer := Buffer + 'CONDITIONAL '; {do not localize}
end; //end_else
if FileLength <> 0 then
Buffer := Buffer + Format('LENGTH %d ', [FileLength]); {do not localize}
if FileStart <> 0 then
Buffer := Buffer + Format('STARTING %d ', [FileStart]); {do not localize}
FMetaData.Add(Buffer);
end; //end_if
qryDB.Next;
end;
qryDB.Close;
qryDB.SQL.Text := LogsSQL;
qryDB.ExecQuery;
while not qryDB.Eof do
begin
if qryDB.FieldByName('RDB$FILE_FLAGS').IsNull then {do not localize}
FileFlags := 0
else
FileFlags := qryDB.FieldByName('RDB$FILE_FLAGS').AsInteger; {do not localize}
if qryDB.FieldByName('RDB$FILE_LENGTH').IsNull then {do not localize}
FileLength := 0
else
FileLength := qryDB.FieldByName('RDB$FILE_LENGTH').AsInteger; {do not localize}
Buffer := '';
HasWal := true;
if First then
begin
if NoDB then
Buffer := '/* '; {do not localize}
Buffer := Buffer + NEWLINE + 'ALTER DATABASE ADD '; {do not localize}
First := false;
end; //end_if
if FirstFile then
Buffer := Buffer + 'LOGFILE '; {do not localize}
{ Overflow files also have the serial bit set }
if (FileFlags and LOG_default) = 0 then
begin
if (FileFlags and LOG_overflow) <> 0 then
Buffer := Buffer + Format(')%s OVERFLOW ''%s''', {do not localize}
[NEWLINE, qryDB.FieldByName('RDB$FILE_NAME').AsTrimString]) {do not localize}
else
if (FileFlags and LOG_serial) <> 0 then
Buffer := Buffer + Format('%s BASE_NAME ''%s''', {do not localize}
[NEWLINE, qryDB.FieldByName('RDB$FILE_NAME').AsTrimString]) {do not localize}
{ Since we are fetching order by FILE_FLAGS, the LOG_0verflow will
be last. It will only appear if there were named round robin,
so we must close the parens first }
{ We have round robin and overflow file specifications }
else
begin
if FirstFile then
Buffer := Buffer + '(' {do not localize}
else
Buffer := Buffer + Format(',%s ', [NEWLINE]); {do not localize}
FirstFile := false;
Buffer := Buffer + Format('''%s''', [qryDB.FieldByName('RDB$FILE_NAME').AsTrimString]); {do not localize}
end; //end_else
end;
{ Any file can have a length }
if FileLength <> 0 then
Buffer := Buffer + Format(' SIZE %d ', [FileLength]); {do not localize}
FMetaData.Add(Buffer);
qryDB.Next;
end;
qryDB.Close;
Buffer := '';
if HasWal then
begin
Buffer := Buffer + PrintSet(SetUsed);
Buffer := Buffer + Format('NUM_LOG_BUFFERS = %d', {do not localize}
[FDatabaseInfo.GetLongDatabaseInfo(isc_info_num_wal_buffers)]);
Buffer := Buffer + PrintSet(SetUsed);
Buffer := Buffer + Format('LOG_BUFFER_SIZE = %d', {do not localize}
[FDatabaseInfo.GetLongDatabaseInfo(isc_info_wal_buffer_size)]);
Buffer := Buffer + PrintSet(SetUsed);
Buffer := Buffer + Format('GROUP_COMMIT_WAIT_TIME = %d', {do not localize}
[FDatabaseInfo.GetLongDatabaseInfo(isc_info_wal_ckpt_interval)]);
Buffer := Buffer + PrintSet(SetUsed);
Buffer := Buffer + Format('CHECK_POINT_LENGTH = %d', {do not localize}
[FDatabaseInfo.GetLongDatabaseInfo(isc_info_wal_ckpt_length)]);
FMetaData.Add(Buffer);
end;
if not First then
begin
if NoDB then
FMetaData.Add(Format('%s */%s', [NEWLINE, NEWLINE])) {do not localize}
else
FMetaData.Add(Format('%s%s%s', [Term, NEWLINE, NEWLINE])); {do not localize}
end;
FMetaData.Add('COMMIT;'); {do not localize}
finally
qryDB.Free;
end;
end;
{ ListDomainTable
Functional description
List domains as identified by fields with any constraints on them
for the named table
Parameters: table_name == only extract domains for this table }
procedure TIBExtract.ListDomains(ObjectName: String; ExtractType : TExtractType);
const
DomainSQL =
'SELECT distinct fld.* FROM RDB$FIELDS FLD JOIN RDB$RELATION_FIELDS RFR ON ' + {do not localize}
' RFR.RDB$FIELD_SOURCE = FLD.RDB$FIELD_NAME ' + {do not localize}
'WHERE RFR.RDB$RELATION_NAME = :TABLE_NAME ' + {do not localize}
'ORDER BY FLD.RDB$FIELD_NAME'; {do not localize}
DomainByNameSQL =
'SELECT * FROM RDB$FIELDS FLD ' + {do not localize}
'WHERE FLD.RDB$FIELD_NAME = :DomainName ' + {do not localize}
'ORDER BY FLD.RDB$FIELD_NAME'; {do not localize}
AllDomainSQL =
'select * from RDB$FIELDS ' + {do not localize}
'where RDB$SYSTEM_FLAG <> 1 ' + {do not localize}
'order BY RDB$FIELD_NAME'; {do not localize}
var
First : Boolean;
qryDomains : TIBSQL;
FieldName, Line : String;
function FormatDomainStr : String;
var
SubType : Integer;
PrecisionKnown : Boolean;
begin
Result := ''; {do not localize}
// for i := Low(ColumnTypes) to High(ColumnTypes) do
// if qryDomains.FieldByName('RDB$FIELD_TYPE').AsInteger = ColumnTypes[i].SQLType then {do not localize}
// begin
PrecisionKnown := FALSE;
if ODSMajorVersion >= ODS_VERSION10 then
begin
if qryDomains.FieldByName('RDB$FIELD_TYPE').AsInteger in [blr_short, blr_long, blr_int64] then {do not localize}
begin
{ We are ODS >= 10 and could be any Dialect }
if (DBSQLDialect >= 3) and
(not qryDomains.FieldByName('RDB$FIELD_PRECISION').IsNull) and {do not localize}
(qryDomains.FieldByName('RDB$FIELD_SUB_TYPE').AsInteger > 0) and {do not localize}
(qryDomains.FieldByName('RDB$FIELD_SUB_TYPE').AsInteger <= MAX_INTSUBTYPES) then {do not localize}
begin
Result := Result + Format('%s(%d, %d)', [ {do not localize}
IntegralSubtypes [qryDomains.FieldByName('RDB$FIELD_SUB_TYPE').AsInteger], {do not localize}
qryDomains.FieldByName('RDB$FIELD_PRECISION').AsInteger, {do not localize}
-1 * qryDomains.FieldByName('RDB$FIELD_SCALE').AsInteger]); {do not localize}
PrecisionKnown := true;
end;
end;
end;
if PrecisionKnown = false then
begin
{ Take a stab at numerics and decimals }
if (qryDomains.FieldByName('RDB$FIELD_TYPE').AsInteger = blr_short) and {do not localize}
(qryDomains.FieldByName('RDB$FIELD_SCALE').AsInteger < 0) then {do not localize}
Result := Result + Format('NUMERIC(4, %d)', {do not localize}
[-qryDomains.FieldByName('RDB$FIELD_SCALE').AsInteger] ) {do not localize}
else
if (qryDomains.FieldByName('RDB$FIELD_TYPE').AsInteger = blr_long) and {do not localize}
(qryDomains.FieldByName('RDB$FIELD_SCALE').AsInteger < 0) then {do not localize}
Result := Result + Format('NUMERIC(9, %d)', {do not localize}
[-qryDomains.FieldByName('RDB$FIELD_SCALE').AsInteger] ) {do not localize}
else
if (qryDomains.FieldByName('RDB$FIELD_TYPE').AsInteger = blr_double) and {do not localize}
(qryDomains.FieldByName('RDB$FIELD_SCALE').AsInteger < 0) then {do not localize}
Result := Result + Format('NUMERIC(15, %d)', {do not localize}
[-qryDomains.FieldByName('RDB$FIELD_SCALE').AsInteger] ) {do not localize}
else
Result := Result + ColumnTypes.Items[qryDomains.FieldByName('RDB$FIELD_TYPE').AsInteger];
end;
// break;
// end;
if qryDomains.FieldByName('RDB$FIELD_TYPE').AsInteger = blr_blob then {do not localize}
begin
subtype := qryDomains.FieldByName('RDB$FIELD_SUB_TYPE').AsInteger; {do not localize}
Result := Result + ' SUB_TYPE '; {do not localize}
if (subtype > 0) and (subtype <= MAXSUBTYPES) then
Result := Result + SubTypes[subtype]
else
Result := Result + Format('%d', [subtype]); {do not localize}
Result := Result + Format(' SEGMENT SIZE %d', [qryDomains.FieldByName('RDB$SEGMENT_LENGTH').AsInteger]); {do not localize}
end //end_if
else
if qryDomains.FieldByName('RDB$FIELD_TYPE').AsInteger in [blr_text, blr_varying] then {do not localize}
Result := Result + Format('(%d)', [GetFieldLength(qryDomains)]); {do not localize}
{ since the character set is part of the field type, display that
information now. }
if not qryDomains.FieldByName('RDB$CHARACTER_SET_ID').IsNull then {do not localize}
Result := Result + GetCharacterSets(qryDomains.FieldByName('RDB$CHARACTER_SET_ID').AsInteger, {do not localize}
0, FALSE);
if not qryDomains.FieldByName('RDB$DIMENSIONS').IsNull then {do not localize}
Result := Result + GetArrayField(FieldName);
if not qryDomains.FieldByName('RDB$DEFAULT_SOURCE').IsNull then {do not localize}
Result := Result + Format('%s%s %s', [NEWLINE, TAB, {do not localize}
qryDomains.FieldByName('RDB$DEFAULT_SOURCE').AsTrimString]); {do not localize}
if not qryDomains.FieldByName('RDB$VALIDATION_SOURCE').IsNull then {do not localize}
if qryDomains.FieldByName('RDB$VALIDATION_SOURCE').AsTrimString.ToUpper.StartsWith('CHECK') then {do not localize}
Result := Result + Format('%s%s %s', [NEWLINE, TAB, {do not localize}
qryDomains.FieldByName('RDB$VALIDATION_SOURCE').AsTrimString]) {do not localize}
else
Result := Result + Format('%s%s /* %s */', [NEWLINE, TAB, {do not localize}
qryDomains.FieldByName('RDB$VALIDATION_SOURCE').AsTrimString]); {do not localize}
if qryDomains.FieldByName('RDB$NULL_FLAG').AsInteger = 1 then {do not localize}
Result := Result + ' NOT NULL'; {do not localize}
{ Show the collation order if one has been specified. If the collation
order is the default for the character set being used, then no collation
order will be shown ( because it isn't needed ).
If the collation id is 0, then the default for the character set is
being used so there is no need to retrieve the collation information.}
if (not qryDomains.FieldByName('RDB$COLLATION_ID').IsNull) and {do not localize}
(qryDomains.FieldByName('RDB$COLLATION_ID').AsInteger <> 0) then {do not localize}
Result := Result + GetCharacterSets(qryDomains.FieldByName('RDB$CHARACTER_SET_ID').AsInteger, {do not localize}
qryDomains.FieldByName('RDB$COLLATION_ID').AsInteger, true); {do not localize}
end;
begin
First := true;
qryDomains := CreateIBSQL;
try
if ObjectName <> '' then {do not localize}
begin
if ExtractType = etTable then
begin
qryDomains.SQL.Text := DomainSQL;
qryDomains.Params.ByName('table_name').AsTrimString := ObjectName; {do not localize}
end
else
begin
qryDomains.SQL.Text := DomainByNameSQL;
qryDomains.Params.ByName('DomainName').AsTrimString := ObjectName; {do not localize}
end;
end
else
qryDomains.SQL.Text := AllDomainSQL;
qryDomains.ExecQuery;
while not qryDomains.Eof do
begin
FieldName := qryDomains.FieldByName('RDB$FIELD_NAME').AsTrimString; {do not localize}
{ Skip over artifical domains }
if FieldName.StartsWith('RDB$') and {do not localize}
FieldName[Low(String) + 4].IsNumber and {do not localize}
(qryDomains.FieldByName('RDB$SYSTEM_FLAG').AsInteger <> 1) then {do not localize}
begin
qryDomains.Next;
continue;
end;
if First then
begin
if IncludeComments then
FMetaData.Add('/* Domain definitions */'); {do not localize}
First := false;
end;
Line := Format('CREATE DOMAIN %s AS ', [QuoteIdentifier(GetDialect, FieldName)]); {do not localize}
Line := Line + FormatDomainStr + Term;
FMetaData.Add(Line);
qryDomains.Next;
end;
finally
qryDomains.Free;
end;
end;
{ ListException
Functional description
List all exceptions defined in the database
Parameters: none }
procedure TIBExtract.ListException(ExceptionName : String = '');
const
ExceptionSQL =
'select * from RDB$EXCEPTIONS ' + {do not localize}
'ORDER BY RDB$EXCEPTION_NAME'; {do not localize}
ExceptionNameSQL =
'select * from RDB$EXCEPTIONS ' + {do not localize}
'WHERE RDB$EXCEPTION_NAME = :ExceptionName ' + {do not localize}
'ORDER BY RDB$EXCEPTION_NAME'; {do not localize}
var
First : Boolean;
qryException : TIBSQL;
begin
First := true;
qryException := CreateIBSQL;
try
if ExceptionName = '' then {do not localize}
qryException.SQL.Text := ExceptionSQL
else
begin
qryException.SQL.Text := ExceptionNameSQL;
qryException.Params.ByName('ExceptionName').AsTrimString := ExceptionName; {do not localize}
end;
qryException.ExecQuery;
while not qryException.Eof do
begin
if First then
begin
FMetaData.Add(''); {do not localize}
if IncludeComments then
FMetaData.Add('/* Exceptions */'); {do not localize}
FMetaData.Add(''); {do not localize}
First := false;
end; //end_if
FMetaData.Add(Format('CREATE EXCEPTION %s %s%s', {do not localize}
[QuoteIdentifier(GetDialect, qryException.FieldByName('RDB$EXCEPTION_NAME').AsTrimString), {do not localize}
QuotedStr(qryException.FieldByName('RDB$MESSAGE').AsTrimString), Term])); {do not localize}
qryException.Next;
end;
finally
qryException.Free;
end;
end;
{ ListFilters
Functional description
List all blob filters
Parameters: none
Results in
DECLARE FILTER <fname> INPUT_TYPE <blob_sub_type> OUTPUT_TYPE <blob_subtype>
ENTRY_POINT <string> MODULE_NAME <string> }
procedure TIBExtract.ListFilters(FilterName : String = '');
const
FiltersSQL =
'SELECT * FROM RDB$FILTERS ' + {do not localize}
'ORDER BY RDB$FUNCTION_NAME'; {do not localize}
FilterNameSQL =
'SELECT * FROM RDB$FILTERS ' + {do not localize}
'WHERE RDB$FUNCTION_NAME = :FunctionName ' + {do not localize}
'ORDER BY RDB$FUNCTION_NAME'; {do not localize}
var
First : Boolean;
qryFilters : TIBSQL;
begin
First := true;
qryFilters := CreateIBSQL;
try
if FilterName = '' then {do not localize}
qryFilters.SQL.Text := FiltersSQL
else
begin
qryFilters.SQL.Text := FilterNameSQL;
qryFilters.Params.ByName('FunctionName').AsTrimString := FilterName; {do not localize}
end;
qryFilters.ExecQuery;
while not qryFilters.Eof do
begin
if First then
begin
FMetaData.Add(''); {do not localize}
if IncludeComments then
FMetaData.Add('/* BLOB Filter declarations */'); {do not localize}
FMetaData.Add(''); {do not localize}
First := false;
end; //end_if
FMetaData.Add(Format('DECLARE FILTER %s INPUT_TYPE %d OUTPUT_TYPE %d', {do not localize}
[qryFilters.FieldByName('RDB$FUNCTION_NAME').AsTrimString, {do not localize}
qryFilters.FieldByName('RDB$INPUT_SUB_TYPE').AsInteger, {do not localize}
qryFilters.FieldByName('RDB$OUTPUT_SUB_TYPE').AsInteger])); {do not localize}
FMetaData.Add(Format('%sENTRY_POINT ''%s'' MODULE_NAME ''%s''%s%', {do not localize}
[TAB, qryFilters.FieldByName('RDB$ENTRYPOINT').AsTrimString, {do not localize}
qryFilters.FieldByName('RDB$MODULE_NAME').AsTrimString, Term])); {do not localize}
FMetaData.Add(''); {do not localize}
qryFilters.Next;
end;
finally
qryFilters.Free;
end;
end;
{ ListForeign
Functional description
List all foreign key constraints and alter the tables }
procedure TIBExtract.ListForeign(ObjectName : String; ExtractType : TExtractType);
const
{ Static queries for obtaining foreign constraints, where RELC1 is the
foreign key constraints, RELC2 is the primary key lookup and REFC
is the join table }
ForeignSQL =
'SELECT REFC.RDB$UPDATE_RULE REFC_UPDATE_RULE, REFC.RDB$DELETE_RULE REFC_DELETE_RULE, ' + {do not localize}
' RELC1.RDB$RELATION_NAME RELC1_RELATION_NAME, RELC2.RDB$RELATION_NAME RELC2_RELATION_NAME, ' + {do not localize}
' RELC1.RDB$INDEX_NAME RELC1_INDEX_NAME, RELC1.RDB$CONSTRAINT_NAME RELC1_CONSTRAINT_NAME, ' + {do not localize}
' RELC2.RDB$INDEX_NAME RELC2_INDEX_NAME ' + {do not localize}
'FROM RDB$REF_CONSTRAINTS REFC, RDB$RELATION_CONSTRAINTS RELC1, ' + {do not localize}
' RDB$RELATION_CONSTRAINTS RELC2 ' + {do not localize}
'WHERE ' + {do not localize}
' RELC1.RDB$CONSTRAINT_TYPE = ''FOREIGN KEY'' AND ' + {do not localize}
' REFC.RDB$CONST_NAME_UQ = RELC2.RDB$CONSTRAINT_NAME AND ' + {do not localize}
' REFC.RDB$CONSTRAINT_NAME = RELC1.RDB$CONSTRAINT_NAME AND ' + {do not localize}
' (RELC2.RDB$CONSTRAINT_TYPE = ''UNIQUE'' OR ' + {do not localize}
' RELC2.RDB$CONSTRAINT_TYPE = ''PRIMARY KEY'') ' + {do not localize}
'ORDER BY RELC1.RDB$RELATION_NAME, RELC1.RDB$CONSTRAINT_NAME'; {do not localize}
ForeignNameSQL =
'SELECT REFC.RDB$UPDATE_RULE REFC_UPDATE_RULE, REFC.RDB$DELETE_RULE REFC_DELETE_RULE, ' + {do not localize}
' RELC1.RDB$RELATION_NAME RELC1_RELATION_NAME, RELC2.RDB$RELATION_NAME RELC2_RELATION_NAME, ' + {do not localize}
' RELC1.RDB$INDEX_NAME RELC1_INDEX_NAME, RELC1.RDB$CONSTRAINT_NAME RELC1_CONSTRAINT_NAME, ' + {do not localize}
' RELC2.RDB$INDEX_NAME RELC2_INDEX_NAME ' + {do not localize}
'FROM RDB$REF_CONSTRAINTS REFC, RDB$RELATION_CONSTRAINTS RELC1, ' + {do not localize}
' RDB$RELATION_CONSTRAINTS RELC2 ' + {do not localize}
'WHERE ' + {do not localize}
' RELC1.RDB$RELATION_NAME = :TableName AND ' + {do not localize}
' RELC1.RDB$CONSTRAINT_TYPE = ''FOREIGN KEY'' AND ' + {do not localize}
' REFC.RDB$CONST_NAME_UQ = RELC2.RDB$CONSTRAINT_NAME AND ' + {do not localize}
' REFC.RDB$CONSTRAINT_NAME = RELC1.RDB$CONSTRAINT_NAME AND ' + {do not localize}
' (RELC2.RDB$CONSTRAINT_TYPE = ''UNIQUE'' OR ' + {do not localize}
' RELC2.RDB$CONSTRAINT_TYPE = ''PRIMARY KEY'') ' + {do not localize}
'ORDER BY RELC1.RDB$RELATION_NAME, RELC1.RDB$CONSTRAINT_NAME'; {do not localize}
ForeignByNameSQL =
'SELECT REFC.RDB$UPDATE_RULE REFC_UPDATE_RULE, REFC.RDB$DELETE_RULE REFC_DELETE_RULE, ' + {do not localize}
' RELC1.RDB$RELATION_NAME RELC1_RELATION_NAME, RELC2.RDB$RELATION_NAME RELC2_RELATION_NAME, ' + {do not localize}
' RELC1.RDB$INDEX_NAME RELC1_INDEX_NAME, RELC1.RDB$CONSTRAINT_NAME RELC1_CONSTRAINT_NAME, ' + {do not localize}
' RELC2.RDB$INDEX_NAME RELC2_INDEX_NAME ' + {do not localize}
'FROM RDB$REF_CONSTRAINTS REFC, RDB$RELATION_CONSTRAINTS RELC1, ' + {do not localize}
' RDB$RELATION_CONSTRAINTS RELC2 ' + {do not localize}
'WHERE ' + {do not localize}
' RELC1.RDB$CONSTRAINT_NAME = :ConstraintName AND ' + {do not localize}
' RELC1.RDB$CONSTRAINT_TYPE = ''FOREIGN KEY'' AND ' + {do not localize}
' REFC.RDB$CONST_NAME_UQ = RELC2.RDB$CONSTRAINT_NAME AND ' + {do not localize}
' REFC.RDB$CONSTRAINT_NAME = RELC1.RDB$CONSTRAINT_NAME AND ' + {do not localize}
' (RELC2.RDB$CONSTRAINT_TYPE = ''UNIQUE'' OR ' + {do not localize}
' RELC2.RDB$CONSTRAINT_TYPE = ''PRIMARY KEY'') ' + {do not localize}
'ORDER BY RELC1.RDB$RELATION_NAME, RELC1.RDB$CONSTRAINT_NAME'; {do not localize}
var
qryForeign : TIBSQL;
Line : String;
begin
qryForeign := CreateIBSQL;
try
if ObjectName = '' then {do not localize}
qryForeign.SQL.Text := ForeignSQL
else
begin
if ExtractType = etTable then
begin
qryForeign.SQL.Text := ForeignNameSQL;
qryForeign.Params.ByName('TableName').AsTrimString := ObjectName; {do not localize}
end
else
begin
qryForeign.SQL.Text := ForeignByNameSQL;
qryForeign.Params.ByName('ConstraintName').AsTrimString := ObjectName; {do not localize}
end;
end;
qryForeign.ExecQuery;
while not qryForeign.Eof do
begin
Line := Format('ALTER TABLE %s ADD ', [QuoteIdentifier(GetDialect, {do not localize}
qryForeign.FieldByName('RELC1_RELATION_NAME').AsTrimString)]); {do not localize}
{ If the name of the constraint is not INTEG..., print it.
INTEG... are internally generated names. }
if (not qryForeign.FieldByName('RELC1_CONSTRAINT_NAME').IsNull) and {do not localize}
(not qryForeign.FieldByName('RELC1_CONSTRAINT_NAME').AsTrimString.StartsWith('INTEG')) then {do not localize}
Line := Line + Format('CONSTRAINT %s ', [QuoteIdentifier(GetDialect, {do not localize}
Trim(qryForeign.FieldByName('RELC1_CONSTRAINT_NAME').AsTrimString))]); {do not localize}
Line := Line + Format('FOREIGN KEY (%s) REFERENCES %s ', [ {do not localize}
GetIndexSegments(qryForeign.FieldByName('RELC1_INDEX_NAME').AsTrimString), {do not localize}
QuoteIdentifier(GetDialect, Trim(qryForeign.FieldByName('RELC2_RELATION_NAME').AsTrimString))]); {do not localize}
Line := Line + Format('(%s)', {do not localize}
[GetIndexSegments(qryForeign.FieldByName('RELC2_INDEX_NAME').AsTrimString)]); {do not localize}
{ Add the referential actions, if any }
if (not qryForeign.FieldByName('REFC_UPDATE_RULE').IsNull) and {do not localize}
(Trim(qryForeign.FieldByName('REFC_UPDATE_RULE').AsTrimString) <> 'RESTRICT') then {do not localize}
Line := Line + Format(' ON UPDATE %s', {do not localize}
[Trim(qryForeign.FieldByName('REFC_UPDATE_RULE').AsTrimString)]); {do not localize}
if (not qryForeign.FieldByName('REFC_DELETE_RULE').IsNull) and {do not localize}
(Trim(qryForeign.FieldByName('REFC_DELETE_RULE').AsTrimString) <> 'RESTRICT') then {do not localize}
Line := Line + Format(' ON DELETE %s', {do not localize}
[Trim(qryForeign.FieldByName('REFC_DELETE_RULE').AsTrimString)]); {do not localize}
Line := Line + Term;
FMetaData.Add(Line);
qryForeign.Next;
end;
finally
qryForeign.Free;
end;
end;
{ ListFunctions
Functional description
List all external functions
Parameters: none
Results in
DECLARE EXTERNAL FUNCTION function_name
CHAR [256] , INTEGER, ....
RETURNS INTEGER BY VALUE
ENTRY_POINT entrypoint MODULE_NAME module; }
procedure TIBExtract.ListFunctions(FunctionName : String = '');
const
FunctionSQL =
'SELECT * FROM RDB$FUNCTIONS ' + {do not localize}
'ORDER BY RDB$FUNCTION_NAME'; {do not localize}
FunctionNameSQL =
'SELECT * FROM RDB$FUNCTIONS ' + {do not localize}
'WHERE RDB$FUNCTION_NAME = :FunctionName ' + {do not localize}
'ORDER BY RDB$FUNCTION_NAME'; {do not localize}
FunctionArgsSQL =
'SELECT * FROM RDB$FUNCTION_ARGUMENTS ' + {do not localize}
'WHERE ' + {do not localize}
' :FUNCTION_NAME = RDB$FUNCTION_NAME ' + {do not localize}
'ORDER BY RDB$ARGUMENT_POSITION'; {do not localize}
FuncArgsPosSQL =
'SELECT * FROM RDB$FUNCTION_ARGUMENTS ' + {do not localize}
'WHERE ' + {do not localize}
' RDB$FUNCTION_NAME = :RDB$FUNCTION_NAME AND ' + {do not localize}
' RDB$ARGUMENT_POSITION = :RDB$ARGUMENT_POSITION'; {do not localize}
CharSetSQL =
'SELECT * FROM RDB$CHARACTER_SETS ' + {do not localize}
'WHERE ' + {do not localize}
' RDB$CHARACTER_SET_ID = :CHARACTER_SET_ID'; {do not localize}
var
qryFunctions, qryFuncArgs, qryCharSets, qryFuncPos : TIBSQL;
First, FirstArg, DidCharset, PrecisionKnown : Boolean;
ReturnBuffer, TypeBuffer, Line : String;
FieldType : Integer;
AddParam : Boolean;
begin
First := true;
qryFunctions := CreateIBSQL;
qryFuncArgs := CreateIBSQL;
qryFuncPos := CreateIBSQL;
qryCharSets := CreateIBSQL;
try
if FunctionName = '' then {do not localize}
qryFunctions.SQL.Text := FunctionSQL
else
begin
qryFunctions.SQL.Text := FunctionNameSQL;
qryFunctions.Params.ByName('FunctionName').AsTrimString := FunctionName; {do not localize}
end;
qryFuncArgs.SQL.Text := FunctionArgsSQL;
qryFuncPos.SQL.Text := FuncArgsPosSQL;
qryCharSets.SQL.Text := CharSetSQL;
qryFunctions.ExecQuery;
while not qryFunctions.Eof do
begin
if First then
begin
if IncludeComments then
FMEtaData.Add(Format('%s/* External Function declarations */%s', {do not localize}
[NEWLINE, NEWLINE]));
First := false;
end; //end_if
{ Start new function declaration }
FMetaData.Add(Format('DECLARE EXTERNAL FUNCTION %s', {do not localize}
[qryFunctions.FieldByName('RDB$FUNCTION_NAME').AsTrimString])); {do not localize}
Line := ''; {do not localize}
FirstArg := true;
qryFuncArgs.Params.ByName('FUNCTION_NAME').AsTrimString := {do not localize}
qryFunctions.FieldByName('RDB$FUNCTION_NAME').AsTrimString; {do not localize}
qryFuncArgs.ExecQuery;
while not qryFuncArgs.Eof do
begin
{ Find parameter type }
FieldType := qryFuncArgs.FieldByName('RDB$FIELD_TYPE').AsInteger; {do not localize}
{ Print length where appropriate }
if FieldType in [ blr_text, blr_varying, blr_cstring] then
begin
DidCharset := false;
qryCharSets.Params.ByName('CHARACTER_SET_ID').AsInteger := {do not localize}
qryFuncArgs.FieldByName('RDB$CHARACTER_SET_ID').AsInteger; {do not localize}
qryCharSets.ExecQuery;
while not qryCharSets.Eof do
begin
DidCharset := true;
TypeBuffer := Format('%s(%d) CHARACTER SET %s', {do not localize}
[ColumnTypes.Items[FieldType],
qryFuncArgs.FieldByName('RDB$FIELD_LENGTH').AsInteger div {do not localize}
Max(1,qryCharSets.FieldByName('RDB$BYTES_PER_CHARACTER').AsInteger), {do not localize}
qryCharSets.FieldByName('RDB$CHARACTER_SET_NAME').AsTrimString]); {do not localize}
qryCharSets.Next;
end;
qryCharSets.Close;
if not DidCharset then
TypeBuffer := Format('%s(%d)', [ColumnTypes.Items[FieldType], {do not localize}
qryFuncArgs.FieldByName('RDB$FIELD_LENGTH').AsInteger]); {do not localize}
end //end_if
else
begin
PrecisionKnown := false;
if (ODSMajorVersion >= ODS_VERSION10) and
(FieldType in [blr_short, blr_long, blr_int64]) then
begin
qryFuncPos.Params.ByName('RDB$FUNCTION_NAME').AsTrimString := {do not localize}
qryFuncArgs.FieldByName('RDB$FUNCTION_NAME').AsTrimString; {do not localize}
qryFuncPos.Params.ByName('RDB$ARGUMENT_POSITION').AsInteger := {do not localize}
qryFuncArgs.FieldByName('RDB$ARGUMENT_POSITION').AsInteger; {do not localize}
qryFuncPos.ExecQuery;
while not qryFuncPos.Eof do
begin
{ We are ODS >= 10 and could be any Dialect }
if not qryFuncPos.FieldByName('RDB$FIELD_PRECISION').IsNull then {do not localize}
begin
{ We are Dialect >=3 since FIELD_PRECISION is non-NULL }
if (qryFuncPos.FieldByName('RDB$FIELD_SUB_TYPE').AsInteger > 0) and {do not localize}
(qryFuncPos.FieldByName('RDB$FIELD_SUB_TYPE').AsInteger <= MAX_INTSUBTYPES) then {do not localize}
begin
TypeBuffer := Format('%s(%d, %d)', {do not localize}
[IntegralSubtypes[qryFuncPos.FieldByName('RDB$FIELD_SUB_TYPE').AsInteger], {do not localize}
qryFuncPos.FieldByName('RDB$FIELD_PRECISION').AsInteger, {do not localize}
-qryFuncPos.FieldByName('RDB$FIELD_SCALE').AsInteger] ); {do not localize}
PrecisionKnown := true;
end; //end_if
end; { if field_precision is not null }
qryFuncPos.Next;
end;
qryFuncPos.Close;
end; { if major_ods >= ods_version10 && }
if not PrecisionKnown then
begin
{ Take a stab at numerics and decimals }
if (FieldType = blr_short) and
(qryFuncArgs.FieldByName('RDB$FIELD_SCALE').AsInteger < 0) then {do not localize}
TypeBuffer := Format('NUMERIC(4, %d)', {do not localize}
[-qryFuncArgs.FieldByName('RDB$FIELD_SCALE').AsInteger]) {do not localize}
else
if (FieldType = blr_long) and
(qryFuncArgs.FieldByName('RDB$FIELD_SCALE').AsInteger < 0) then {do not localize}
TypeBuffer := Format('NUMERIC(9, %d)', {do not localize}
[-qryFuncArgs.FieldByName('RDB$FIELD_SCALE').AsInteger]) {do not localize}
else
if (FieldType = blr_double) and
(qryFuncArgs.FieldByName('RDB$FIELD_SCALE').AsInteger < 0) then {do not localize}
TypeBuffer := Format('NUMERIC(15, %d)', {do not localize}
[-qryFuncArgs.FieldByName('RDB$FIELD_SCALE').AsInteger]) {do not localize}
else
TypeBuffer := ColumnTypes.Items[FieldType];
end; { if not PrecisionKnown }
end; { if FCHAR or VARCHAR or CSTRING ... else }
AddParam := true;
if qryFunctions.FieldByName('RDB$RETURN_ARGUMENT').AsInteger = {do not localize}
qryFuncArgs.FieldByName('RDB$ARGUMENT_POSITION').AsInteger then {do not localize}
begin
if qryFunctions.FieldByName('RDB$RETURN_ARGUMENT').AsInteger = 0 then {do not localize}
begin
ReturnBuffer := 'RETURNS ' + TypeBuffer; {do not localize}
AddParam:=False;
end
else
ReturnBuffer := 'RETURNS PARAMETER ' + IntToStr(qryFunctions.FieldByName('RDB$RETURN_ARGUMENT').AsInteger); {do not localize}
if qryFuncArgs.FieldByName('RDB$MECHANISM').AsInteger = 0 then {do not localize}
ReturnBuffer := ReturnBuffer + ' BY VALUE '; {do not localize}
if qryFuncArgs.FieldByName('RDB$MECHANISM').AsInteger < 0 then {do not localize}
ReturnBuffer := ReturnBuffer + ' FREE_IT'; {do not localize}
end;
if AddParam then
begin
{ First arg needs no comma }
if FirstArg then
begin
Line := Line + TypeBuffer;
FirstArg := false;
end
else
Line := Line + ', ' + TypeBuffer;
end; //end_else
qryFuncArgs.Next;
end;
qryFuncArgs.Close;
FMetaData.Add(Line);
FMetaData.Add(ReturnBuffer);
FMetaData.Add(Format('ENTRY_POINT ''%s'' MODULE_NAME ''%s''%s%s%s', {do not localize}
[qryFunctions.FieldByName('RDB$ENTRYPOINT').AsTrimString, {do not localize}
qryFunctions.FieldByName('RDB$MODULE_NAME').AsTrimString, {do not localize}
Term, NEWLINE, NEWLINE]));
qryFunctions.Next;
end;
finally
qryFunctions.Free;
qryFuncArgs.Free;
qryCharSets.Free;
qryFuncPos.Free;
end;
end;
{ ListGenerators
Functional description
Re create all non-system generators }
procedure TIBExtract.ListGenerators(GeneratorName : String = ''); {do not localize}
const
GeneratorSQL =
'SELECT RDB$GENERATOR_NAME ' + {do not localize}
'FROM RDB$GENERATORS ' + {do not localize}
'WHERE ' + {do not localize}
' (RDB$SYSTEM_FLAG IS NULL OR RDB$SYSTEM_FLAG <> 1) ' + {do not localize}
'ORDER BY RDB$GENERATOR_NAME'; {do not localize}
GeneratorNameSQL =
'SELECT RDB$GENERATOR_NAME ' + {do not localize}
'FROM RDB$GENERATORS ' + {do not localize}
'WHERE RDB$GENERATOR_NAME = :GeneratorName AND ' + {do not localize}
' (RDB$SYSTEM_FLAG IS NULL OR RDB$SYSTEM_FLAG <> 1) ' + {do not localize}
'ORDER BY RDB$GENERATOR_NAME'; {do not localize}
var
qryGenerator : TIBSQL;
GenName : String;
begin
qryGenerator := CreateIBSQL;
try
if GeneratorName = '' then {do not localize}
qryGenerator.SQL.Text := GeneratorSQL
else
begin
qryGenerator.SQL.Text := GeneratorNameSQL;
qryGenerator.Params.ByName('GeneratorName').AsTrimString := GeneratorName; {do not localize}
end;
qryGenerator.ExecQuery;
FMetaData.Add(''); {do not localize}
while not qryGenerator.Eof do
begin
GenName := qryGenerator.FieldByName('RDB$GENERATOR_NAME').AsTrimString; {do not localize}
if (GenName.StartsWith('RDB$') and {do not localize}
GenName[Low(String) + 4].IsNumber) or {do not localize}
(GenName.StartsWith('SQL$') and {do not localize}
GenName[Low(String) + 4].IsNumber) then {do not localize}
begin
qryGenerator.Next;
continue;
end;
FMetaData.Add(Format('CREATE GENERATOR %s%s', {do not localize}
[QuoteIdentifier(GetDialect, GenName), Term]));
qryGenerator.Next;
end;
finally
qryGenerator.Free;
end;
end;
procedure TIBExtract.ListGrants(ObjectName: string);
begin
if ObjectName = '' then
ListGrants
else
ShowGrants(ObjectName, Term);
end;
{ ListIndex
Functional description
Define all non-constraint indices
Use a static SQL query to get the info and print it.
Uses get_index_segment to provide a key list for each index }
procedure TIBExtract.ListIndex(ObjectName : String; ExtractType : TExtractType);
const
IndexSQL =
'SELECT IDX.RDB$RELATION_NAME, IDX.RDB$INDEX_NAME, IDX.RDB$UNIQUE_FLAG, ' + {do not localize}
' IDX.RDB$INDEX_TYPE, RDB$INDEX_INACTIVE ' + {do not localize}
'FROM RDB$INDICES IDX JOIN RDB$RELATIONS RELC ON ' + {do not localize}
' IDX.RDB$RELATION_NAME = RELC.RDB$RELATION_NAME ' + {do not localize}
'WHERE (RELC.RDB$SYSTEM_FLAG <> 1 OR RELC.RDB$SYSTEM_FLAG IS NULL) AND ' + {do not localize}
' NOT EXISTS (SELECT * FROM RDB$RELATION_CONSTRAINTS RC ' + {do not localize}
' WHERE RC.RDB$INDEX_NAME = IDX.RDB$INDEX_NAME) ' + {do not localize}
'ORDER BY IDX.RDB$RELATION_NAME, IDX.RDB$INDEX_NAME'; {do not localize}
IndexNameSQL =
'SELECT IDX.RDB$RELATION_NAME, IDX.RDB$INDEX_NAME, IDX.RDB$UNIQUE_FLAG, ' + {do not localize}
' IDX.RDB$INDEX_TYPE, RDB$INDEX_INACTIVE ' + {do not localize}
'FROM RDB$INDICES IDX JOIN RDB$RELATIONS RELC ON ' + {do not localize}
' IDX.RDB$RELATION_NAME = RELC.RDB$RELATION_NAME ' + {do not localize}
'WHERE (RELC.RDB$SYSTEM_FLAG <> 1 OR RELC.RDB$SYSTEM_FLAG IS NULL) AND ' + {do not localize}
' RELC.RDB$RELATION_NAME = :RelationName AND ' + {do not localize}
' NOT EXISTS (SELECT * FROM RDB$RELATION_CONSTRAINTS RC ' + {do not localize}
' WHERE RC.RDB$INDEX_NAME = IDX.RDB$INDEX_NAME) ' + {do not localize}
'ORDER BY IDX.RDB$RELATION_NAME, IDX.RDB$INDEX_NAME'; {do not localize}
IndexByNameSQL =
'SELECT IDX.RDB$RELATION_NAME, IDX.RDB$INDEX_NAME, IDX.RDB$UNIQUE_FLAG, ' + {do not localize}
' IDX.RDB$INDEX_TYPE, RDB$INDEX_INACTIVE ' + {do not localize}
'FROM RDB$INDICES IDX JOIN RDB$RELATIONS RELC ON ' + {do not localize}
' IDX.RDB$RELATION_NAME = RELC.RDB$RELATION_NAME ' + {do not localize}
'WHERE (RELC.RDB$SYSTEM_FLAG <> 1 OR RELC.RDB$SYSTEM_FLAG IS NULL) AND ' + {do not localize}
' IDX.RDB$INDEX_NAME = :IndexName AND ' + {do not localize}
' NOT EXISTS (SELECT * FROM RDB$RELATION_CONSTRAINTS RC ' + {do not localize}
' WHERE RC.RDB$INDEX_NAME = IDX.RDB$INDEX_NAME) ' + {do not localize}
'ORDER BY IDX.RDB$RELATION_NAME, IDX.RDB$INDEX_NAME'; {do not localize}
var
qryIndex : TIBSQL;
First : Boolean;
Unique, IdxType, Line : String;
begin
First := true;
qryIndex := CreateIBSQL;
try
if ObjectName = '' then {do not localize}
qryIndex.SQL.Text := IndexSQL
else
begin
if ExtractType = etTable then
begin
qryIndex.SQL.Text := IndexNameSQL;
qryIndex.Params.ByName('RelationName').AsTrimString := ObjectName; {do not localize}
end
else
begin
qryIndex.SQL.Text := IndexByNameSQL;
qryIndex.Params.ByName('IndexName').AsTrimString := ObjectName; {do not localize}
end;
end;
qryIndex.ExecQuery;
while not qryIndex.Eof do
begin
if First then
begin
if IncludeComments then
begin
if ObjectName = '' then {do not localize}
FMetaData.Add(NEWLINE + '/* Index definitions for all user tables */' + NEWLINE) {do not localize}
else
FMetaData.Add(NEWLINE + '/* Index definitions for ' + ObjectName + ' */'); {do not localize}
end;
First := false;
end; //end_if
if qryIndex.FieldByName('RDB$UNIQUE_FLAG').AsInteger = 1 then {do not localize}
Unique := ' UNIQUE' {do not localize}
else
Unique := ''; {do not localize}
if qryIndex.FieldByName('RDB$INDEX_TYPE').AsInteger = 1 then {do not localize}
IdxType := ' DESCENDING' {do not localize}
else
IdxType := ''; {do not localize}
Line := Format('CREATE%s%s INDEX %s ON %s(', [Unique, IdxType, {do not localize}
QuoteIdentifier(GetDialect,
qryIndex.FieldByName('RDB$INDEX_NAME').AsTrimString), {do not localize}
QuoteIdentifier(GetDialect,
qryIndex.FieldByName('RDB$RELATION_NAME').AsTrimString)]); {do not localize}
Line := Line + GetIndexSegments(qryIndex.FieldByName('RDB$INDEX_NAME').AsTrimString) + {do not localize}
')' + Term; {do not localize}
FMetaData.Add(Line);
if qryIndex.FieldByName('RDB$INDEX_INACTIVE').AsInteger = 1 then {do not localize}
begin
Line := Format('ALTER INDEX %S INACTIVE;', [QuoteIdentifier(GetDialect, {do not localize}
qryIndex.FieldByName('RDB$INDEX_NAME').AsTrimString)]); {do not localize}
FMetaData.Add(Line);
end;
qryIndex.Next;
end;
finally
qryIndex.Free;
end;
end;
{ ListViews
Functional description
Show text of views.
Use a SQL query to get the info and print it.
Note: This should also contain check option }
procedure TIBExtract.ListViews(ViewName : String);
const
ViewSQL =
'SELECT RDB$RELATION_NAME, RDB$OWNER_NAME, RDB$VIEW_SOURCE ' + {do not localize}
'FROM RDB$RELATIONS ' + {do not localize}
'WHERE ' + {do not localize}
' (RDB$SYSTEM_FLAG <> 1 OR RDB$SYSTEM_FLAG IS NULL) AND ' + {do not localize}
' NOT RDB$VIEW_BLR IS NULL AND ' + {do not localize}
' RDB$FLAGS = 1 ' + {do not localize}
'ORDER BY RDB$RELATION_ID'; {do not localize}
ViewNameSQL =
'SELECT RDB$RELATION_NAME, RDB$OWNER_NAME, RDB$VIEW_SOURCE ' + {do not localize}
'FROM RDB$RELATIONS ' + {do not localize}
'WHERE ' + {do not localize}
' (RDB$SYSTEM_FLAG <> 1 OR RDB$SYSTEM_FLAG IS NULL) AND ' + {do not localize}
' NOT RDB$VIEW_BLR IS NULL AND ' + {do not localize}
' RDB$FLAGS = 1 AND ' + {do not localize}
' RDB$RELATION_NAME = :ViewName ' + {do not localize}
'ORDER BY RDB$RELATION_ID'; {do not localize}
ColumnSQL =
'SELECT RDB$FIELD_NAME FROM RDB$RELATION_FIELDS ' + {do not localize}
'WHERE ' + {do not localize}
' RDB$RELATION_NAME = :RELATION_NAME ' + {do not localize}
'ORDER BY RDB$FIELD_POSITION'; {do not localize}
var
qryView, qryColumns : TIBSQL;
SList : TStrings;
begin
qryView := CreateIBSQL;
qryColumns := CreateIBSQL;
SList := TStringList.Create;
try
if ViewName = '' then {do not localize}
qryView.SQL.Text := ViewSQL
else
begin
qryView.SQL.Text := ViewNameSQL;
qryView.Params.ByName('ViewName').AsTrimString := ViewName; {do not localize}
end;
qryColumns.SQL.Text := ColumnSQL;
qryView.ExecQuery;
while not qryView.Eof do
begin
if IncludeComments then
SList.Add(Format('%s/* View: %s, Owner: %s */%s', {do not localize}
[NEWLINE, qryView.FieldByName('RDB$RELATION_NAME').AsTrimString, {do not localize}
qryView.FieldByName('RDB$OWNER_NAME').AsTrimString, NEWLINE])); {do not localize}
SList.Add(Format('CREATE VIEW %s (', [QuoteIdentifier(GetDialect, {do not localize}
qryView.FieldByName('RDB$RELATION_NAME').AsTrimString)])); {do not localize}
qryColumns.Params.ByName('RELATION_NAME').AsTrimString := {do not localize}
qryView.FieldByName('RDB$RELATION_NAME').AsTrimString; {do not localize}
qryColumns.ExecQuery;
while not qryColumns.Eof do
begin
SList.Add(' ' + QuoteIdentifier(GetDialect, {do not localize}
qryColumns.FieldByName('RDB$FIELD_NAME').AsTrimString)); {do not localize}
qryColumns.Next;
if not qryColumns.Eof then
SList.Strings[SList.Count - 1] := SList.Strings[SList.Count - 1] + ', '; {do not localize}
end;
qryColumns.Close;
SList.Text := SList.Text + Format(') %0:sAS%0:s', [NEWLINE]); {do not localize}
if not qryView.FieldByName('RDB$VIEW_SOURCE').IsNull then {do not localize}
SList.Text := SList.Text + qryView.FieldByName('RDB$VIEW_SOURCE').AsString.Trim; {do not localize}
SList.Text := SList.Text + Format('%s%s', [Term, NEWLINE]); {do not localize}
FMetaData.AddStrings(SList);
SList.Clear;
qryView.Next;
end;
finally
qryView.Free;
qryColumns.Free;
SList.Free;
end;
end;
{ PrintSet
Functional description
print (using ISQL_printf) the word "SET"
if the first line of the ALTER DATABASE
settings options. Also, add trailing
comma for end of prior line if needed.
uses Print_buffer, a global }
function TIBExtract.PrintSet(var Used: Boolean) : String;
begin
if not Used then
begin
Result := ' SET '; {do not localize}
Used := true;
end
else
Result := Format(', %s ', [NEWLINE]); {do not localize}
end;
{
PrintValidation
Functional description
This does some minor syntax adjustmet for extracting
validation blobs and computed fields.
if it does not start with the word CHECK
if this is a computed field blob,look for () or insert them.
if flag = false, this is a validation clause,
if flag = true, this is a computed field }
function TIBExtract.PrintValidation(ToValidate: String;
flag: Boolean): String;
var
IsSQL : Boolean;
begin
IsSql := false;
Result := ''; {do not localize}
ToValidate := Trim(ToValidate);
if flag then
begin
if ToValidate[Low(ToValidate)] = '(' then {do not localize}
IsSQL := true;
end
else
if 'check'.StartsWith(ToValidate.ToLower) then {do not localize}
IsSQL := TRUE;
if not IsSQL then
begin
if Flag then
Result := Result + '/* ' + ToValidate + ' */' {do not localize}
else
Result := Result + '(' + ToValidate + ')'; {do not localize}
end
else
Result := ToValidate;
end;
procedure TIBExtract.SetDatabase(const Value: TIBDatabase);
begin
FBase.Database := Value;
FDatabaseInfo.Database := Value;
end;
procedure TIBExtract.SetOverrideSQLDialect(const Value: Integer);
begin
if not (value in [0, 1, 3]) then
Exception.Create(SInvalidSQLOverride);
FOverrideSQLDialect := Value;
end;
procedure TIBExtract.SetTransaction(const Value: TIBTransaction);
begin
if FBase.Transaction <> Value then
begin
FBase.Transaction := Value;
if (not Assigned(FBase.Database)) and (FBase.Transaction <> nil) then
Database := FBase.Transaction.DefaultDatabase;
end;
end;
procedure TIBExtract.ExtractObject(ObjectType : TExtractObjectTypes;
ObjectName : String = ''; ExtractTypes : TExtractTypes = []);
var
DidActivate : Boolean;
DefaultCharSet : TIBSQL;
begin
DidActivate := false;
CheckAssigned;
if not FBase.Transaction.Active then
begin
FBase.Transaction.StartTransaction;
DidActivate := true;
end;
FMetaData.Clear;
DefaultCharSet := TIBSQL.Create(FBase.Transaction);
try
DefaultCharSet.SQL.Text := DefaultCharSetSQL;
DefaultCharSet.ExecQuery;
if not DefaultCharSet.Eof then
FDefaultCharSet := DefaultCharSet.Fields[0].AsInteger
else
FDefaultCharSet := -1;
finally
DefaultCharSet.Free;
end;
ODSMajorVersion := FDatabaseInfo.ODSMajorVersion;
DBSQLDialect := FDatabaseInfo.DBSQLDialect;
FullODS := FDatabaseInfo.FullODS;
case ObjectType of
eoDatabase : ExtractDDL(true, '');
eoDomain :
if etTable in ExtractTypes then
ListDomains(ObjectName, etTable)
else
ListDomains(ObjectName);
eoTable :
begin
if ObjectName <> '' then
begin
if etDomain in ExtractTypes then
ListDomains(ObjectName, etTable);
ExtractListTable(ObjectName, '', false);
if etIndex in ExtractTypes then
ListIndex(ObjectName, etTable);
if etForeign in ExtractTypes then
ListForeign(ObjectName, etTable);
if etCheck in ExtractTypes then
ListCheck(ObjectName, etTable);
if etTrigger in ExtractTypes then
ListTriggers(ObjectName, etTable);
if etGrant in ExtractTypes then
ShowGrants(ObjectName, Term);
if etData in ExtractTypes then
ListData(ObjectName);
if etEUAUser in ExtractTypes then
ListEUAUsers;
if etEncryption in ExtractTypes then
ListEncryptions(ObjectName);
end
else
ListAllTables(true);
end;
eoSubscription : ListSubscriptions(ObjectName);
eoView :
begin
ListViews(ObjectName);
if etTrigger in ExtractTypes then
ListTriggers(ObjectName, etTable);
if etGrant in ExtractTypes then
begin
FMetaData.Add('');
ShowGrants(ObjectName, Term);
end;
end;
eoProcedure : ListProcs(ObjectName, (etAlterProc in ExtractTypes));
eoFunction : ListFunctions(ObjectName);
eoGenerator : ListGenerators(ObjectName);
eoException : ListException(ObjectName);
eoBLOBFilter : ListFilters(ObjectName);
eoRole : ListRoles(ObjectName);
eoTrigger :
if etTable in ExtractTypes then
ListTriggers(ObjectName, etTable)
else
ListTriggers(ObjectName);
eoForeign :
if etTable in ExtractTypes then
ListForeign(ObjectName, etTable)
else
ListForeign(ObjectName);
eoIndexes :
if etTable in ExtractTypes then
ListIndex(ObjectName, etTable)
else
ListIndex(ObjectName);
eoChecks :
if etTable in ExtractTypes then
ListCheck(ObjectName, etTable)
else
ListCheck(ObjectName);
eoData : ListData(ObjectName);
eoEUAUser : ListEUAUsers;
eoEncryption : ListEncryptions(ObjectName);
eoGrants : ListGrants(ObjectName);
end;
if DidActivate then
FBase.Transaction.Commit;
end;
function TIBExtract.GetFieldType(FieldType, FieldSubType, FieldScale,
FieldSize, FieldPrec, FieldLen: Integer): String;
var
PrecisionKnown : Boolean;
begin
Result := '';
PrecisionKnown := FALSE;
if ODSMajorVersion >= ODS_VERSION10 then
begin
if FieldType in [blr_short, blr_long, blr_int64] then
begin
{ We are ODS >= 10 and could be any Dialect }
if (FieldPrec <> 0) and
(FieldSubType > 0) and
(FieldSubType <= MAX_INTSUBTYPES) then
begin
Result := Result + Format('%s(%d, %d)', [ {do not localize}
IntegralSubtypes [FieldSubType],
FieldPrec,
-1 * FieldScale]);
PrecisionKnown := true;
end;
end;
end;
if PrecisionKnown = false then
begin
{ Take a stab at numerics and decimals }
if (FieldType = blr_short) and
(FieldScale < 0) then
Result := Result + Format('NUMERIC(4, %d)', {do not localize}
[-FieldScale] )
else
if (FieldType = blr_long) and
(FieldScale < 0) then
Result := Result + Format('NUMERIC(9, %d)', {do not localize}
[-FieldScale] )
else
if (FieldType = blr_double) and
(FieldScale < 0) then
Result := Result + Format('NUMERIC(15, %d)', {do not localize}
[-FieldScale] )
else
Result := Result + ColumnTypes.Items[FieldType];
end;
if (FieldType in [blr_text, blr_varying]) and
(FieldSize <> 0) then
Result := Result + Format('(%d)', [FieldSize]); {do not localize}
end;
{ S H O W _ g r a n t s
Functional description
Show grants for given object name
This function is also called by extract for privileges.
It must extract granted privileges on tables/views to users,
- these may be compound, so put them on the same line.
Grant execute privilege on procedures to users
Grant various privilegs to procedures.
All privileges may have the with_grant option set. }
procedure TIBExtract.ShowGrants(MetaObject, Terminator: String);
const
{ This query only finds tables, eliminating owner privileges }
OwnerPrivSQL =
'SELECT PRV.RDB$USER, PRV.RDB$GRANT_OPTION, PRV.RDB$FIELD_NAME, ' + {do not localize}
' PRV.RDB$USER_TYPE, PRV.RDB$PRIVILEGE ' + {do not localize}
'FROM RDB$USER_PRIVILEGES PRV, RDB$RELATIONS REL ' + {do not localize}
'WHERE ' + {do not localize}
' PRV.RDB$RELATION_NAME = :METAOBJECT AND ' + {do not localize}
' REL.RDB$RELATION_NAME = :METAOBJECT AND ' + {do not localize}
' PRV.RDB$PRIVILEGE <> ''M'' AND ' + {do not localize}
' REL.RDB$OWNER_NAME <> PRV.RDB$USER ' + {do not localize}
'ORDER BY PRV.RDB$USER, PRV.RDB$FIELD_NAME, PRV.RDB$GRANT_OPTION'; {do not localize}
ProcPrivSQL =
'SELECT PRV.RDB$USER, PRV.RDB$GRANT_OPTION, PRV.RDB$FIELD_NAME, ' + {do not localize}
' PRV.RDB$USER_TYPE, PRV.RDB$PRIVILEGE, PRV.RDB$RELATION_NAME ' + {do not localize}
'FROM RDB$USER_PRIVILEGES PRV, RDB$PROCEDURES PRC ' + {do not localize}
'where ' + {do not localize}
' PRV.RDB$OBJECT_TYPE = 5 AND ' + {do not localize}
' PRV.RDB$RELATION_NAME = :METAOBJECT AND ' + {do not localize}
' PRC.RDB$PROCEDURE_NAME = :METAOBJECT AND ' + {do not localize}
' PRV.RDB$PRIVILEGE = ''X'' AND ' + {do not localize}
' PRC.RDB$OWNER_NAME <> PRV.RDB$USER ' + {do not localize}
'ORDER BY PRV.RDB$USER, PRV.RDB$FIELD_NAME, PRV.RDB$GRANT_OPTION'; {do not localize}
RolePrivSQL =
'SELECT * FROM RDB$USER_PRIVILEGES ' + {do not localize}
'WHERE ' + {do not localize}
' RDB$OBJECT_TYPE = 13 AND ' + {do not localize}
' RDB$USER_TYPE = 8 AND ' + {do not localize}
' RDB$RELATION_NAME = :METAOBJECT AND ' + {do not localize}
' RDB$PRIVILEGE = ''M'' ' + {do not localize}
'ORDER BY RDB$USER'; {do not localize}
SubscriptionSQL =
'SELECT distinct UP.* ' + {do not localize}
' FROM RDB$USER_PRIVILEGES UP JOIN RDB$SUBSCRIPTIONS s on ' + {do not localize}
' UP.RDB$RELATION_NAME = s.RDB$SUBSCRIPTION_NAME ' + {do not localize}
' WHERE ' + {do not localize}
' UP.RDB$OBJECT_TYPE = 16 AND ' + {do not localize}
' UP.RDB$USER_TYPE = 8 AND ' + {do not localize}
' UP.RDB$RELATION_NAME = :METAOBJECT AND ' + {do not localize}
' UP.RDB$PRIVILEGE = ''B'' and ' + {do not localize}
' UP.RDB$USER <> S.RDB$OWNER_NAME ' + {do not localize}
' ORDER BY RDB$USER'; {do not localize}
var
PrevUser, PrevField, WithOption,
PrivString, ColString, UserString,
FieldName, User : String;
c : Char;
PrevOption, PrivFlags, GrantOption : Integer;
First, PrevFieldNull : Boolean;
qryOwnerPriv : TIBSQL;
{ Given a bit-vector of privileges, turn it into a
string list. }
function MakePrivString(cflags : Integer) : String;
var
i : Integer;
begin
Result := '';
for i := Low(PrivTypes) to High(PrivTypes) do
begin
if (cflags and PrivTypes[i].PrivFlag) <> 0 then
begin
if Result <> '' then {do not localize}
Result := Result + ', '; {do not localize}
Result := Result + PrivTypes[i].PrivString;
end; //end_if
end; //end_for
end; //end_fcn MakePrivDtring
begin
if MetaObject = '' then
exit;
First := true;
PrevOption := -1;
PrevUser := '';
PrivString := '';
ColString := '';
WithOption := '';
PrivFlags := 0;
PrevFieldNull := false;
PrevField := '';
qryOwnerPriv := CreateIBSQL;
try
qryOwnerPriv.SQL.Text := OwnerPrivSQL;
qryOwnerPriv.Params.ByName('metaobject').AsTrimString := MetaObject; {do not localize}
qryOwnerPriv.ExecQuery;
while not qryOwnerPriv.Eof do
begin
{ Sometimes grant options are null, sometimes 0. Both same }
if qryOwnerPriv.FieldByName('RDB$GRANT_OPTION').IsNull then {do not localize}
GrantOption := 0
else
GrantOption := qryOwnerPriv.FieldByName('RDB$GRANT_OPTION').AsInteger; {do not localize}
if qryOwnerPriv.FieldByName('RDB$FIELD_NAME').IsNull then {do not localize}
FieldName := ''
else
FieldName := qryOwnerPriv.FieldByName('RDB$FIELD_NAME').AsTrimString; {do not localize}
User := Trim(qryOwnerPriv.FieldByName('RDB$USER').AsTrimString); {do not localize}
{ Print a new grant statement for each new user or change of option }
if ((PrevUser <> '') and (PrevUser <> User)) or
((Not First) and
((PrevFieldNull <> qryOwnerPriv.FieldByName('RDB$FIELD_NAME').IsNull) or {do not localize}
((not PrevFieldNull) and (PrevField <> FieldName)) or
((PrevOption <> -1) and (PrevOption <> GrantOption)))) then
begin
PrivString := MakePrivString(PrivFlags);
First := false;
FMetaData.Add(Format('GRANT %s%s ON %s TO %s%s%s', [PrivString, {do not localize}
ColString, QuoteIdentifier(GetDialect, MetaObject),
UserString, WithOption, Terminator]));
{ re-initialize strings }
PrivString := '';
WithOption := '';
ColString := '';
PrivFlags := 0;
end; //end_if
PrevUser := User;
PrevOption := GrantOption;
PrevFieldNull := qryOwnerPriv.FieldByName('RDB$FIELD_NAME').IsNull; {do not localize}
PrevField := FieldName;
case qryOwnerPriv.FieldByName('RDB$USER_TYPE').AsInteger of {do not localize}
obj_relation,
obj_view,
obj_trigger,
obj_procedure,
obj_sql_role:
UserString := QuoteIdentifier(GetDialect, User);
else
UserString := User;
end; //end_case
case qryOwnerPriv.FieldByName('RDB$USER_TYPE').AsInteger of {do not localize}
obj_view :
UserString := 'VIEW ' + UserString; {do not localize}
obj_trigger :
UserString := 'TRIGGER '+ UserString; {do not localize}
obj_procedure :
UserString := 'PROCEDURE ' + UserString; {do not localize}
end; //end_case
c := qryOwnerPriv.FieldByName('RDB$PRIVILEGE').AsTrimString[Low(String)]; {do not localize}
case c of
'S' : PrivFlags := PrivFlags or priv_SELECT; {do not localize}
'I' : PrivFlags := PrivFlags or priv_INSERT; {do not localize}
'U' : PrivFlags := PrivFlags or priv_UPDATE; {do not localize}
'D' : PrivFlags := PrivFlags or priv_DELETE; {do not localize}
'R' : PrivFlags := PrivFlags or priv_REFERENCES; {do not localize}
'T' : PrivFlags := PrivFlags or priv_DECRYPT; {do not localize}
'X' : ; {do not localize}
{ Execute should not be here -- special handling below }
'E' : ; {do not localize}
{Special handling in ListEncryptions}
else
PrivFlags := PrivFlags or priv_UNKNOWN;
end; //end_switch
{ Column level privileges for update only }
if FieldName = '' then
ColString := ''
else
ColString := Format(' (%s)', [QuoteIdentifier(GetDialect, FieldName)]); {do not localize}
if GrantOption <> 0 then
WithOption := ' WITH GRANT OPTION'; {do not localize}
qryOwnerPriv.Next;
end;
{ Print last case if there was anything to print }
if PrevOption <> -1 then
begin
PrivString := MakePrivString(PrivFlags);
First := false;
FMetaData.Add(Format('GRANT %s%s ON %s TO %s%s%s', [PrivString, {do not localize}
ColString, QuoteIdentifier(GetDialect, MetaObject),
UserString, WithOption, Terminator]));
{ re-initialize strings }
end; //end_if
qryOwnerPriv.Close;
if First then
begin
{ Part two is for stored procedures only }
qryOwnerPriv.SQL.Text := ProcPrivSQL;
qryOwnerPriv.Params.ByName('metaobject').AsTrimString := MetaObject; {do not localize}
qryOwnerPriv.ExecQuery;
while not qryOwnerPriv.Eof do
begin
First := false;
User := Trim(qryOwnerPriv.FieldByName('RDB$USER').AsTrimString); {do not localize}
case qryOwnerPriv.FieldByName('RDB$USER_TYPE').AsInteger of {do not localize}
obj_relation,
obj_view,
obj_trigger,
obj_procedure,
obj_sql_role:
UserString := QuoteIdentifier(GetDialect, User);
else
UserString := User;
end; //end_case
case qryOwnerPriv.FieldByName('RDB$USER_TYPE').AsInteger of {do not localize}
obj_view :
UserString := 'VIEW ' + UserString; {do not localize}
obj_trigger :
UserString := 'TRIGGER '+ UserString; {do not localize}
obj_procedure :
UserString := 'PROCEDURE ' + UserString; {do not localize}
end; //end_case
if qryOwnerPriv.FieldByName('RDB$GRANT_OPTION').AsInteger = 1 then {do not localize}
WithOption := ' WITH GRANT OPTION' {do not localize}
else
WithOption := '';
FMetaData.Add(Format('GRANT EXECUTE ON PROCEDURE %s TO %s%s%s', {do not localize}
[QuoteIdentifier(GetDialect, MetaObject), UserString,
WithOption, terminator]));
qryOwnerPriv.Next;
end;
qryOwnerPriv.Close;
end;
if First then
begin
qryOwnerPriv.SQL.Text := RolePrivSQL;
qryOwnerPriv.Params.ByName('metaobject').AsTrimString := MetaObject; {do not localize}
qryOwnerPriv.ExecQuery;
while not qryOwnerPriv.Eof do
begin
First := false;
if qryOwnerPriv.FieldByName('RDB$GRANT_OPTION').AsInteger = 1 then {do not localize}
WithOption := ' WITH ADMIN OPTION' {do not localize}
else
WithOption := '';
FMetaData.Add(Format('GRANT %s TO %s%s%s', {do not localize}
[QuoteIdentifier(GetDialect, qryOwnerPriv.FieldByName('RDB$RELATION_NAME').AsTrimString), {do not localize}
qryOwnerPriv.FieldByName('RDB$USER_NAME').AsTrimString, {do not localize}
WithOption, terminator]));
qryOwnerPriv.Next;
end;
qryOwnerPriv.Close;
end;
if First and (ODSMajorVersion >= ODS_VERSION16) then
begin
qryOwnerPriv.SQL.Text := SubscriptionSQL;
qryOwnerPriv.Params.ByName('metaobject').AsTrimString := MetaObject; {do not localize}
qryOwnerPriv.ExecQuery;
while not qryOwnerPriv.Eof do
begin
if qryOwnerPriv.FieldByName('RDB$GRANT_OPTION').AsInteger = 1 then {do not localize}
WithOption := ' WITH ADMIN OPTION' {do not localize}
else
WithOption := '';
FMetaData.Add(Format('GRANT SUBSCRIBE ON SUBSCRIPTION %s to %s%s%s', {do not localize}
[QuoteIdentifier(GetDialect, qryOwnerPriv.FieldByName('RDB$RELATION_NAME').AsTrimString), {do not localize}
qryOwnerPriv.FieldByName('RDB$USER').AsTrimString, {do not localize}
WithOption, terminator]));
qryOwnerPriv.Next;
end;
qryOwnerPriv.Close;
end;
finally
qryOwnerPriv.Free;
end;
end;
{ ShowGrantRoles
Functional description
Show grants for given role name
This function is also called by extract for privileges.
All membership privilege may have the with_admin option set. }
procedure TIBExtract.ShowGrantRoles(Terminator: String);
const
RoleSQL =
'SELECT RDB$USER, RDB$GRANT_OPTION, RDB$RELATION_NAME ' + {do not localize}
'FROM RDB$USER_PRIVILEGES ' + {do not localize}
'WHERE ' + {do not localize}
' RDB$OBJECT_TYPE = %d AND ' + {do not localize}
' RDB$USER_TYPE = %d AND ' + {do not localize}
' RDB$PRIVILEGE = ''M'' ' + {do not localize}
'ORDER BY RDB$RELATION_NAME, RDB$USER'; {do not localize}
var
WithOption, UserString : String;
qryRole : TIBSQL;
begin
qryRole := CreateIBSQL;
try
qryRole.SQL.Text := Format(RoleSQL, [obj_sql_role, obj_user]);
qryRole.ExecQuery;
while not qryRole.Eof do
begin
UserString := Trim(qryRole.FieldByName('RDB$USER').AsTrimString); {do not localize}
if (not qryRole.FieldByName('RDB$GRANT_OPTION').IsNull) and {do not localize}
(qryRole.FieldByName('RDB$GRANT_OPTION').AsInteger = 1) then {do not localize}
WithOption := ' WITH ADMIN OPTION' {do not localize}
else
WithOption := '';
FMetaData.Add(Format('GRANT %s TO %s%s%s%s', {do not localize}
[ QuoteIdentifier(GetDialect, qryRole.FieldByName('RDB$RELATION_NAME').AsTrimString), {do not localize}
UserString, WithOption, Terminator, NEWLINE]));
qryRole.Next;
end;
finally
qryRole.Free;
end;
end;
{ GetProcedureArgs
Functional description
This function extract the procedure parameters and adds it to the
extract file }
procedure TIBExtract.GetProcedureArgs(Proc: String; args : TStrings);
const
{ query to retrieve the input parameters. }
ProcHeaderSQL =
'SELECT * ' + {do not localize}
' FROM RDB$PROCEDURE_PARAMETERS PRM JOIN RDB$FIELDS FLD ON ' + {do not localize}
' PRM.RDB$FIELD_SOURCE = FLD.RDB$FIELD_NAME ' + {do not localize}
'WHERE ' + {do not localize}
' PRM.RDB$PROCEDURE_NAME = :PROCNAME ' + {do not localize}
'ORDER BY PRM.RDB$PARAMETER_TYPE, PRM.RDB$PARAMETER_NUMBER'; {do not localize}
var
FirstTime, PrecisionKnown : Boolean;
Line : String;
function FormatParamStr : String;
var
CollationID, CharSetID, subtype : Integer;
FieldType, FieldScale : Integer;
begin
Result := Format(' %s ', [QuoteIdentifier(GetDialect, qryProcedures.FieldByName('RDB$PARAMETER_NAME').AsString.Trim)]); {do not localize}
PrecisionKnown := FALSE;
FieldType := qryProcedures.FieldByName('RDB$FIELD_TYPE').AsInteger;
FieldScale := qryProcedures.FieldByName('RDB$FIELD_SCALE').AsInteger;
if ODSMajorVersion >= ODS_VERSION10 then
begin
if FieldType in [blr_short, blr_long, blr_int64] then {do not localize}
begin
{ We are ODS >= 10 and could be any Dialect }
if (DBSQLDialect >= 3) and
(not qryProcedures.FieldByName('RDB$FIELD_PRECISION').IsNull) and {do not localize}
(qryProcedures.FieldByName('RDB$FIELD_SUB_TYPE').AsInteger > 0) and {do not localize}
(qryProcedures.FieldByName('RDB$FIELD_SUB_TYPE').AsInteger <= MAX_INTSUBTYPES) then {do not localize}
begin
Result := Result + Format('%s(%d, %d)', [ {do not localize}
IntegralSubtypes [qryProcedures.FieldByName('RDB$FIELD_SUB_TYPE').AsInteger], {do not localize}
qryProcedures.FieldByName('RDB$FIELD_PRECISION').AsInteger, {do not localize}
-1 * FieldScale]); {do not localize}
PrecisionKnown := true;
end;
end;
end;
if PrecisionKnown = false then
begin
{ Take a stab at numerics and decimals }
if (FieldType = blr_short) and {do not localize}
(FieldScale < 0) then {do not localize}
Result := Result + Format('NUMERIC(4, %d)', {do not localize}
[-FieldScale] ) {do not localize}
else
if (FieldType = blr_long) and {do not localize}
(FieldScale < 0) then {do not localize}
Result := Result + Format('NUMERIC(9, %d)', {do not localize}
[-FieldScale] ) {do not localize}
else
if (FieldType = blr_double) and {do not localize}
(FieldScale < 0) then {do not localize}
Result := Result + Format('NUMERIC(15, %d)', {do not localize}
[-FieldScale] ) {do not localize}
else
Result := Result + ColumnTypes.Items[FieldType];
end;
if FieldType in [blr_text, blr_varying] then {do not localize}
Result := Result + Format('(%d)', [GetFieldLength(qryProcedures)]); {do not localize}
if FieldType = blr_blob then
begin
subtype := qryProcedures.Current.ByName('RDB$FIELD_SUB_TYPE').AsShort; {do not localize}
Result := Result + ' SUB_TYPE '; {do not localize}
if (subtype > 0) and (subtype <= MAXSUBTYPES) then
Result := Result + SubTypes[subtype]
else
Result := Result + IntToStr(subtype);
Result := Result + Format(' SEGMENT SIZE %d', {do not localize}
[qryProcedures.FieldByName('RDB$SEGMENT_LENGTH').AsInteger]); {do not localize}
end;
{ Show international character sets and collations }
if (not qryProcedures.FieldByName('RDB$COLLATION_ID').IsNull) or {do not localize}
(not qryProcedures.FieldByName('RDB$CHARACTER_SET_ID').IsNull) then {do not localize}
begin
if qryProcedures.FieldByName('RDB$COLLATION_ID').IsNull then {do not localize}
CollationId := 0
else
CollationId := qryProcedures.FieldByName('RDB$COLLATION_ID').AsInteger; {do not localize}
if qryProcedures.FieldByName('RDB$CHARACTER_SET_ID').IsNull then {do not localize}
CharSetId := 0
else
CharSetId := qryProcedures.FieldByName('RDB$CHARACTER_SET_ID').AsInteger; {do not localize}
Result := Result + GetCharacterSets(CharSetId, CollationId, false);
end;
end;
begin
FirstTime := true;
if not qryProcedures.FieldByName('RDB$PARAMETER_NAME').IsNull then
begin
while (not qryProcedures.Eof) and
(qryProcedures.FieldByName('RDB$PROCEDURE_NAME').AsString.Trim = Proc) and
(qryProcedures.FieldByName('RDB$PARAMETER_TYPE').AsInteger = 0) do
begin
if FirstTime then
begin
FirstTime := false;
args.Add('('); {do not localize}
end;
Line := FormatParamStr;
qryProcedures.Next;
if not qryProcedures.Eof and
(qryProcedures.FieldByName('RDB$PROCEDURE_NAME').AsString.Trim = Proc) and
(qryProcedures.FieldByName('RDB$PARAMETER_TYPE').AsInteger = 0) then
Line := Line + ','; {do not localize}
args.Add(Line);
end;
{ If there was at least one param, close parens }
if not FirstTime then
begin
args.Add( ')'); {do not localize}
end;
FirstTime := true;
while (not qryProcedures.Eof) and
(qryProcedures.FieldByName('RDB$PROCEDURE_NAME').AsString.Trim = Proc) do
begin
if FirstTime then
begin
FirstTime := false;
args.Add('RETURNS' + NEWLINE + '('); {do not localize}
end;
Line := FormatParamStr;
qryProcedures.Next;
if (not qryProcedures.Eof) and
(qryProcedures.FieldByName('RDB$PROCEDURE_NAME').AsString.Trim = Proc) then
Line := Line + ','; {do not localize}
args.Add(Line);
end;
{ If there was at least one param, close parens }
if not FirstTime then
begin
args.Add( ')'); {do not localize}
end;
end
else
qryProcedures.Next;
args.Add('AS'); {do not localize}
end;
procedure TIBExtract.BuildConnectString;
const
OwnerSQL = 'SELECT RDB$OWNER_NAME FROM RDB$RELATIONS WHERE RDB$RELATION_NAME=''RDB$DATABASE'''; {do not localize}
var
qryOwner : TIBSQL;
begin
qryOwner := CreateIBSQL;
try
qryOwner.SQL.Text := OwnerSQL;
qryOwner.ExecQuery;
FMetaData.Add('/* CONNECT ' + QuotedStr(FBase.Database.DatabaseName) + {do not localize}
' USER ' + QuotedStr(QryOwner.FieldByName('RDB$OWNER_NAME').AsTrimString) + {do not localize}
' PASSWORD ' + QuotedStr(SPassword) + '*/'); {do not localize}
qryOwner.Close;
finally
qryOwner.Free;
end;
end;
procedure TIBExtract.ListData(ObjectName: String);
const
SelectSQL = 'SELECT * FROM %s'; {do not localize}
var
qrySelect : TIBSQL;
Line, FieldName, Fields, Values, DateStr : String;
i : Integer;
AFormatSettings : TFormatSettings;
begin
qrySelect := CreateIBSQL;
AFormatSettings.DateSeparator := '/'; {do not localize}
AFormatSettings.TimeSeparator := ':'; {do not localize}
try
qrySelect.SQL.Text := Format(SelectSQL,
[QuoteIdentifier(GetDialect, ObjectName)]);
qrySelect.ExecQuery;
Fields := '';
for i := 0 to qrySelect.Current.Count - 1 do
if (qrySelect.Fields[i].SQLType <> SQL_ARRAY) and
(not ((qrySelect.Fields[i].SQLType = SQL_BLOB) and
(qrySelect.Fields[i].Data.SqlSubtype <> 1))) and
(not Database.Has_COMPUTED_BLR(ObjectName, qrySelect.Fields[i].Name)) then
begin
FieldName := String(qrySelect.Fields[i].SQLVAR.sqlname);
if Fields <> '' then
Fields := Fields + ', '; {do not localize}
Fields := Fields + QuoteIdentifier(GetDialect, FieldName);
end;
while not qrySelect.Eof do
begin
Line := 'INSERT INTO ' + QuoteIdentifier(GetDialect, ObjectName) + ' ('; {do not localize}
Line := Line + Fields + ') VALUES ('; {do not localize}
Values := '';
for i := 0 to qrySelect.Current.Count - 1 do
begin
if Database.Has_COMPUTED_BLR(ObjectName, qrySelect.Fields[i].Name) then
Continue;
if (Values <> '') and (qrySelect.Fields[i].SQLType <> SQL_ARRAY) and
(not ((qrySelect.Fields[i].SQLType = SQL_BLOB) and
(qrySelect.Fields[i].Data.SqlSubtype <> 1))) then
Values := Values + ', ';
if qrySelect.Fields[i].IsNull and
(qrySelect.Fields[i].SQLType <> SQL_ARRAY) and
(not ((qrySelect.Fields[i].SQLType = SQL_BLOB) and
(qrySelect.Fields[i].Data.SqlSubtype <> 1))) then
begin
Values := Values + 'NULL'; {do not localize}
end
else
case qrySelect.Fields[i].SQLType of
SQL_TEXT, SQL_VARYING, SQL_BLOB :
if not ((qrySelect.Fields[i].SQLType = SQL_BLOB) and
(qrySelect.Fields[i].Data.SqlSubtype <> 1)) then
Values := Values + QuotedStr(qrySelect.Fields[i].AsString);
SQL_TYPE_DATE :
begin
DateTimeToString(DateStr, 'mm/dd/yyyy', qrySelect.Fields[i].AsDate, AFormatSettings); {do not localize}
Values := Values + QuotedStr(DateStr);
end;
SQL_TYPE_TIME :
begin
DateTimeToString(DateStr, 'hh:mm:ssss', qrySelect.Fields[i].AsTime, AFormatSettings); {do not localize}
Values := Values + QuotedStr(DateStr);
end;
SQL_TIMESTAMP :
begin
DateTimeToString(DateStr, 'mm/dd/yyyy hh:mm:ssss', qrySelect.Fields[i].AsDateTime, AFormatSettings); {do not localize}
Values := Values + QuotedStr(DateStr);
end;
SQL_SHORT, SQL_LONG, SQL_INT64,
SQL_DOUBLE, SQL_FLOAT, SQL_D_FLOAT, SQL_BOOLEAN:
Values := Values + qrySelect.Fields[i].AsTrimString;
SQL_ARRAY : ;
else
IBError(ibxeInvalidDataConversion, [nil]);
end;
end;
Line := Line + Values + ')' + Term; {do not localize}
FMetaData.Add(Line);
qrySelect.Next;
end;
finally
qrySelect.Free;
end;
end;
procedure TIBExtract.ListRoles(ObjectName: String);
const
RolesSQL =
'select * from RDB$ROLES ' + {do not localize}
'order by RDB$ROLE_NAME'; {do not localize}
RolesByNameSQL =
'select * from RDB$ROLES ' + {do not localize}
'WHERE RDB$ROLE_NAME = :RoleName ' + {do not localize}
'order by RDB$ROLE_NAME'; {do not localize}
var
qryRoles : TIBSQL;
PrevOwner, RoleName, OwnerName : String;
begin
{Process GRANT roles}
qryRoles := CreateIBSQL;
try
if ODSMajorVersion >= ODS_VERSION9 then
begin
PrevOwner := '';
FMetaData.Add('');
if IncludeComments then
FMetaData.Add('/* Grant Roles for this database */'); {do not localize}
FMetaData.Add('');
if ObjectName = '' then
qryRoles.SQL.Text := RolesSQL
else
begin
qryRoles.SQL.Text := RolesByNameSQL;
qryRoles.Params.ByName('RoleName').AsTrimString := ObjectName; {do not localize}
end;
qryRoles.ExecQuery;
try
while not qryRoles.Eof do
begin
RoleName := QuoteIdentifier(GetDialect,
qryRoles.FieldByName('rdb$Role_Name').AsTrimString); {do not localize}
OwnerName := Trim(qryRoles.FieldByName('rdb$Owner_Name').AsTrimString); {do not localize}
if PrevOwner <> OwnerName then
begin
FMetaData.Add('');
if IncludeComments then
FMetaData.Add(Format('/* Role: %s, Owner: %s */', [RoleName, OwnerName])); {do not localize}
FMetaData.Add('');
PrevOwner := OwnerName;
end;
FMetaData.Add('CREATE ROLE ' + RoleName + Term); {do not localize}
qryRoles.Next;
end;
finally
qryRoles.Close;
end;
end;
finally
qryRoles.Free;
end;
end;
procedure TIBExtract.ListSubscriptions(SubscriptionName: String);
const
SNamedSubscription = 'select SBS.RDB$SUBSCRIPTION_NAME, SBS.RDB$OWNER_NAME, SBS.RDB$DESCRIPTION ' + {do not localize}
' from RDB$SUBSCRIPTIONS SBS ' + {do not localize}
' where SBS.RDB$RELATION_NAME IS NULL AND ' + {do not localize}
' SBS.RDB$SUBSCRIPTION_NAME = :subscription_name'; {do not localize}
SAllSubscription = 'select SBS.RDB$SUBSCRIPTION_NAME, SBS.RDB$OWNER_NAME, SBS.RDB$DESCRIPTION ' + {do not localize}
' from RDB$SUBSCRIPTIONS SBS ' + {do not localize}
' where SBS.RDB$RELATION_NAME IS NULL ' + {do not localize }
' order by RDB$SUBSCRIPTION_NAME'; {do not localize}
STables = 'select RDB$RELATION_NAME, RDB$RELATION_COUNTER, RDB$CHANGE, RDB$INSERT, ' + {do not localize}
' RDB$UPDATE, RDB$DELETE ' + {do not localize}
' from RDB$SUBSCRIPTIONS SBS2 ' + {do not localize}
' where SBS2.RDB$SUBSCRIPTION_NAME = :subscription_name AND ' + {do not localize}
' SBS2.RDB$RELATION_NAME is not NULL AND ' + {do not localize}
' SBS2.RDB$FIELD_NAME is NULL ' + {do not localize}
' ORDER BY SBS2.RDB$SUBSCRIPTION_NAME, SBS2.RDB$RELATION_COUNTER, SBS2.RDB$FLAGS '; {do not localize}
SColumns = 'select * ' + {do not localize}
' from RDB$SUBSCRIPTIONS SBS3 ' + {do not localize}
' where SBS3.RDB$SUBSCRIPTION_NAME = :subscription_name AND ' + {do not localize}
' SBS3.RDB$RELATION_COUNTER = :RELATION_COUNTER AND ' + {do not localize}
' SBS3.RDB$FIELD_NAME is not NULL AND ' + {do not localize}
' SBS3.RDB$FLAGS = 0 ' + {do not localize}
' ORDER BY SBS3.RDB$SUBSCRIPTION_NAME, SBS3.RDB$RELATION_COUNTER '; {do not localize}
var
SLine, SDelim : String;
FColumn : Boolean;
begin
if ODSMajorVersion < ODS_VERSION16 then
Exit;
if not Assigned(sqlMain) then
sqlMain := CreateIBSQL;
if SubscriptionName <> '' then
begin
{ stops from unnecessarily re prepaing this }
if sqlMain.SQL.Text <> SNamedSubscription then
sqlMain.SQL.Text := SNamedSubscription;
sqlMain.ParamByName('subscription_name').AsString := SubscriptionName;
end
else
if sqlMain.SQL.Text <> SAllSubscription then
sqlMain.SQL.Text := SAllSubscription;
if not Assigned(sqlTables) then
begin
sqlTables := CreateIBSQL;
sqlTables.SQL.Text := STables;
end;
if not Assigned(sqlColumns) then
begin
sqlColumns := CreateIBSQL;
sqlColumns.SQL.Text := SColumns;
end;
if IncludeComments then
FMetaData.Add('/* Subscriptions */'); { do not localize }
sqlMain.ExecQuery;
try
while not sqlMain.Eof do
begin
if IncludeComments then
begin
FMetaData.Add('/* SubScription Name: ' + sqlMain.FieldByName('RDB$SUBSCRIPTION_NAME').AsString.Trim); { do not localize }
FMetaData.Add(' Owner: ' + sqlMain.FieldByName('rdb$owner_name').AsString.Trim); { do not localize }
FMetaData.Add(' Description: ' + sqlMain.FieldByName('RDB$DESCRIPTION').AsString.Trim + ' */'); { do not localize }
end;
FMetaData.Add(''); { do not localize }
FMetaData.Add('CREATE SUBSCRIPTION ' + QuoteIdentifier(GetDialect, sqlMain.FieldByName('RDB$SUBSCRIPTION_NAME').AsString.Trim) + ' ON '); {do not localize }
sqlTables.ParamByName('subscription_name').AsString := sqlMain.FieldByName('RDB$SUBSCRIPTION_NAME').AsString; {do not localize }
sqlTables.ExecQuery;
while not sqlTables.Eof do
begin
if SLine <> '' then {do not localize}
begin
SLine := SLine + ','; {do not localize}
FMetaData.Add(SLine);
end;
SLine := ' ' + QuoteIdentifier(GetDialect, sqlTables.FieldByName('RDB$RELATION_NAME').AsString.Trim); {do not localize }
sqlColumns.ParamByName('subscription_name').AsString := sqlMain.FieldByName('RDB$SUBSCRIPTION_NAME').AsString; {do not localize}
sqlColumns.ParamByName('relation_counter').AsInteger := sqlTables.FieldByName('RDB$RELATION_COUNTER').AsInteger; {do not localize }
sqlColumns.ExecQuery;
FColumn := True;
while not sqlColumns.Eof do
begin
if FColumn then
begin
SLine := SLine + ' (' + QuoteIdentifier(GetDialect, sqlColumns.FieldByName('RDB$FIELD_NAME').AsString.Trim); {do not localize }
FColumn := False;
end
else
SLine := SLine + ', ' + QuoteIdentifier(GetDialect, sqlColumns.FieldByName('RDB$FIELD_NAME').AsString.Trim); {do not localize }
sqlColumns.Next;
end;
if not (sqlColumns.IsEmpty) then
SLine := SLine + ') '; {do not localize }
sqlColumns.Close;
SDelim := '';
if not sqlTables.FieldByName('RDB$CHANGE').AsBoolean then {do not localize}
begin
SLine := SLine + ' FOR ROW ('; {do not localize}
if sqlTables.FieldByName('RDB$INSERT').AsBoolean then {do not localize}
begin
SLine := SLine + 'INSERT'; {do not localize}
SDelim := ', '; {do not localize}
end;
if sqlTables.FieldByName('RDB$UPDATE').AsBoolean then {do not localize}
begin
SLine := SLine + SDelim + 'UPDATE'; {do not localize}
SDelim := ', '; {do not localize}
end;
if sqlTables.FieldByName('RDB$DELETE').AsBoolean then {do not localize}
begin
SLine := SLine + SDelim + 'DELETE'; {do not localize}
SDelim := ', '; {do not localize}
end;
SLine := SLine + ')'; {do not localize}
end;
sqlTables.Next;
end;
FMetaData.Add(SLine);
sqlTables.Close;
if not sqlMain.FieldByName('RDB$DESCRIPTION').IsNull then {do not localize}
FMetaData.Add('DESCRIPTION ' + QuotedStr(sqlMain.FieldByName('RDB$DESCRIPTION').AsString.Trim)); {do not localize}
FMetaData[FMetaData.Count - 1] := FMetaData[FMetaData.Count - 1] + TERM; {do not localize}
FMetaData.Add(''); {do not localize}
sqlMain.Next;
end;
finally
sqlMain.Close;
end;
end;
Procedure TIBExtract.ListEUAUsers;
const
UserSQL = 'SELECT * FROM RDB$USERS ' + {do not localize}
'WHERE RDB$USER_NAME NOT IN '+ {do not localize}
' (SELECT RDB$OWNER_NAME FROM RDB$RELATIONS ' + {do not localize}
' WHERE RDB$RELATION_NAME=''RDB$DATABASE'')'; {do not localize}
var
qryUsers : TIBSQL;
function BuildAddSQL : String;
begin
Result := '/* CREATE USER ' + qryUsers.FieldByName('RDB$USER_NAME').AsTrimString + {do not localize}
' SET PASSWORD /* Password needed */ '; {do not localize}
if qryUsers.FieldByName('RDB$DEFAULT_ROLE').AsTrimString <> '' then {do not localize}
Result := Result + ' DEFAULT ROLE ' + {do not localize}
QuotedStr(qryUsers.FieldByName('RDB$DEFAULT_ROLE').AsTrimString); {do not localize}
if qryUsers.FieldByName('RDB$SYSTEM_USER_NAME').AsTrimString <> '' then {do not localize}
Result := Result + ' SYSTEM USER NAME ' + {do not localize}
QuotedStr(qryUsers.FieldByName('RDB$SYSTEM_USER_NAME').AsTrimString); {do not localize}
if qryUsers.FieldByName('RDB$GROUP_NAME').AsTrimString <> '' then {do not localize}
Result := Result + ' GROUP NAME ' + {do not localize}
QuotedStr(qryUsers.FieldByName('RDB$GROUP_NAME').AsTrimString); {do not localize}
if qryUsers.FieldByName('RDB$UID').AsInteger > 0 then {do not localize}
Result := Result + ' UID ' + IntToStr(qryUsers.FieldByName('RDB$UID').AsInteger); {do not localize}
if qryUsers.FieldByName('RDB$GID').AsInteger > 0 then {do not localize}
Result := Result + ' GID ' + IntToStr(qryUsers.FieldByName('RDB$GID').AsInteger); {do not localize}
if qryUsers.FieldByName('RDB$DESCRIPTION').AsTrimString <> '' then {do not localize}
Result := Result + ' DESCRIPTION ' + {do not localize}
QuotedStr(qryUsers.FieldByName('RDB$DESCRIPTION').AsTrimString); {do not localize}
if qryUsers.FieldByName('RDB$FIRST_NAME').AsTrimString <> '' then {do not localize}
Result := Result + ' FIRST NAME ' + {do not localize}
QuotedStr(qryUsers.FieldByName('RDB$FIRST_NAME').AsTrimString); {do not localize}
if qryUsers.FieldByName('RDB$MIDDLE_NAME').AsTrimString <> '' then {do not localize}
Result := Result + ' MIDDLE NAME ' + {do not localize}
QuotedStr(qryUsers.FieldByName('RDB$MIDDLE_NAME').AsTrimString); {do not localize}
if qryUsers.FieldByName('RDB$LAST_NAME').AsTrimString <> '' then
Result := Result + ' LAST NAME ' + {do not localize}
QuotedStr(qryUsers.FieldByName('RDB$LAST_NAME').AsTrimString); {do not localize}
Result := Result + TERM + '*/'; {do not localize}
end;
begin
if (FDatabaseInfo.EUAActive) then
begin
qryUsers:= CreateIBSQL;
try
qryUsers.SQL.Text := UserSQL;
qryUsers.ExecQuery;
try
if not qryUsers.eof then
FMetaData.Add('/* Users in Database (passwords need to be added)*/'); {do not localize}
while not qryUsers.eof do
begin
FMetaData.Add(BuildAddSQL);
if qryUsers.FieldByName('RDB$USER_ACTIVE').AsTrimString <> 'Y' then {do not localize}
FMetaData.Add('/*ALTER USER ' + qryUsers.FieldByName('RDB$USER_NAME').AsTrimString + {do not localize}
' SET INACTIVE */'); {do not localize}
qryUsers.Next;
end;
finally
qryUsers.Close;
end;
finally
qryUsers.Free;
end;
end;
end;
Procedure TIBExtract.ListEncryptions(EncryptionName : String);
const
EncryptionsByNameSQL =
'SELECT * FROM RDB$ENCRYPTIONS ' + {do not localize}
'WHERE RDB$ENCRYPTION_NAME = :ENCRYPTION_NAME'; {do not localize}
EncryptionsSQL =
'SELECT * FROM RDB$ENCRYPTIONS;'; {do not localize}
GrantsSQL =
'SELECT RDB$USER, RDB$RELATION_NAME FROM RDB$USER_PRIVILEGES A INNER JOIN ' + {do not localize}
'RDB$ENCRYPTIONS B ON A.RDB$RELATION_NAME = B.RDB$ENCRYPTION_NAME ' + {do not localize}
'WHERE A.RDB$USER <> ''SYSDSO'' AND A.RDB$PRIVILEGE=''E'''; {do not localize}
var
qryEncryptions, qryGrants : TIBSQL;
Buffer : String;
begin
if (FullODS >= 13.0) then
begin
qryEncryptions := CreateIBSQL;
qryGrants := CreateIBSQL;
try
if EncryptionName = '' then
qryEncryptions.SQL.Text := EncryptionsSQL
else
begin
qryEncryptions.SQL.Text := EncryptionsByNameSQL;
qryEncryptions.Params.ByName('ENCRYPTION_NAME').AsTrimString := EncryptionName; {do not localize}
end;
FMetaData.Add('/*CONNECT ' + QuotedStr(FBase.Database.DatabaseName) + {do not localize}
' USER ''SYSDSO'' PASSWORD ' + QuotedStr(SPassword) + '*/'); {do not localize}
FMetaData.Add('/* ALTER DATABASE SET SYSTEM ENCRYPTION PASSWORD ' + {do not localize}
QuotedStr(SEncryptionPassword) + TERM + '*/'); {do not localize}
try
qryEncryptions.ExecQuery;
except
// Exceptions will be because of no permissions ot read, jsut drop out if
// this happens and continue on
Exit;
end;
while not qryEncryptions.eof do
begin
Buffer := 'CREATE ENCRYPTION ' + {do not localize}
qryEncryptions.FieldByName('RDB$ENCRYPTION_NAME').AsTrimString + {do not localize}
' FOR ' + {do not localize}
qryEncryptions.FieldByName('RDB$ENCRYPTION_CIPHER').AsTrimString + {do not localize}
' WITH LENGTH ' + {do not localize}
qryEncryptions.FieldByName('RDB$ENCRYPTION_LENGTH').AsString + {do not localize}
' BITS INIT_VECTOR '; {do not localize}
if qryEncryptions.FieldByName('RDB$ENCRYPTION_INIT_VECTOR').IsNull then {do not localize}
Buffer := Buffer + ' NULL' {do not localize}
else
Buffer := Buffer + ' RANDOM'; {do not localize}
Buffer := Buffer + ' PAD '; {do not localize}
if qryEncryptions.FieldByName('RDB$ENCRYPTION_PAD').IsNull then {do not localize}
Buffer := Buffer + ' NULL' {do not localize}
else
Buffer := Buffer + ' RANDOM'; {do not localize}
if not qryEncryptions.FieldByName('RDB$DESCRIPTION').isnull then {do not localize}
Buffer := Buffer + ' DESCRIPTION ' + {do not localize}
QuotedStr(qryEncryptions.FieldByName('RDB$DESCRIPTION').AsTrimString); {do not localize}
if not qryEncryptions.FieldByName('RDB$PASSWORD2').isnull then {do not localize}
Buffer := '/* ' + Buffer + ' PASSWORD ' + QuotedStr(SEncryptionPassword); {do not localize}
Buffer := Buffer + TERM;
if not qryEncryptions.FieldByName('RDB$PASSWORD2').isnull then {do not localize}
Buffer := Buffer + '*/'; {do not localize}
FMetaData.Add(Buffer);
qryEncryptions.Next;
end;
qryEncryptions.Close;
qryGrants.SQL.Text := GrantsSQL;
qryGrants.ExecQuery;
while not qryGrants.eof do
begin
FMetaData.Add('GRANT ENCRYPT ON ENCRYPTION ' + {do not localize}
qryGrants.FieldByName('RDB$RELATION_NAME').AsTrimString + {do not localize}
' TO ' + qryGrants.FieldByName('RDB$USER').AsTrimString + {do not localize}
TERM);
qryGrants.Next;
end;
qryGrants.Close;
FMetaData.Add('COMMIT' + TERM); {do not localize}
finally
qryEncryptions.Free;
qryGrants.Free;
end;
end;
end;
function TIBExtract.GetFieldLength(sql: TIBSQL): Integer;
begin
if sql.FieldByName('RDB$CHARACTER_LENGTH').IsNull then {do not localize}
Result := sql.FieldByName('RDB$FIELD_LENGTH').AsInteger {do not localize}
else
Result := sql.FieldByName('RDB$CHARACTER_LENGTH').AsInteger; {do not localize}
end;
function TIBExtract.CreateIBSQL: TIBSQL;
begin
Result := TIBSQL.Create(Self);
Result.Database := FBase.Database;
if FBase.Transaction <> FBase.Database.DefaultTransaction then
Result.Transaction := FBase.Transaction;
end;
procedure SetupTypes;
begin
ColumnTypes := TDictionary<SmallInt, string>.Create(15);
ColumnTypes.Add(blr_short, 'SMALLINT'); {do not localize}
ColumnTypes.Add(blr_long, 'INTEGER'); {do not localize}
ColumnTypes.Add(blr_quad, 'QUAD'); {do not localize}
ColumnTypes.Add(blr_float, 'FLOAT'); {do not localize}
ColumnTypes.Add(blr_text, 'CHAR'); {do not localize}
ColumnTypes.Add(blr_double, 'DOUBLE PRECISION'); {do not localize}
ColumnTypes.Add(blr_varying, 'VARCHAR'); {do not localize}
ColumnTypes.Add(blr_cstring, 'CSTRING'); {do not localize}
ColumnTypes.Add(blr_blob_id, 'BLOB_ID'); {do not localize}
ColumnTypes.Add(blr_blob, 'BLOB'); {do not localize}
ColumnTypes.Add(blr_sql_time, 'TIME'); {do not localize}
ColumnTypes.Add(blr_sql_date, 'DATE'); {do not localize}
ColumnTypes.Add(blr_timestamp, 'TIMESTAMP'); {do not localize}
ColumnTypes.Add(blr_int64, 'INT64'); {do not localize}
ColumnTypes.Add(blr_boolean_dtype, 'BOOLEAN'); {do not localize}
end;
initialization
SetupTypes;
finalization
ColumnTypes.Free;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Data.DBXFirebirdMetaDataReader;
interface
uses
Data.DBXCommon,
Data.DBXCommonTable,
Data.DBXMetaDataNames,
Data.DBXMetaDataReader,
Data.DBXPlatform;
type
/// <summary> TDBXFirebirdCustomMetaDataReader contains custom code for Firebird.
/// </summary>
/// <remarks> This class handles data types and type mapping for table columns and
/// procedure parameters.
/// </remarks>
TDBXFirebirdCustomMetaDataReader = class(TDBXBaseMetaDataReader)
public
destructor Destroy; override;
/// <summary> Overrides the implementation in TDBXBaseMetaDataProvider.
/// </summary>
/// <remarks> A custom filter is added to extract the type information for each column.
/// </remarks>
/// <seealso cref="TDBXFirebirdTypeFilterCursor"/>
function FetchColumns(const Catalog: UnicodeString; const Schema: UnicodeString; const Table: UnicodeString): TDBXTable; override;
/// <summary> Overrides the implementation in TDBXBaseMetaDataProvider.
/// </summary>
/// <remarks> A custom filter is added to extract the type information for each column.
/// </remarks>
/// <seealso cref="TDBXFirebirdTypeFilterCursor"/>
function FetchProcedureParameters(const Catalog: UnicodeString; const Schema: UnicodeString; const &Procedure: UnicodeString; const Parameter: UnicodeString): TDBXTable; override;
protected
procedure SetContext(const Context: TDBXProviderContext); override;
function IsDefaultCharSetUnicode: Boolean; virtual;
function GetSqlIdentifierQuotePrefix: UnicodeString; override;
function GetSqlIdentifierQuoteSuffix: UnicodeString; override;
function GetSqlIdentifierQuoteChar: UnicodeString; override;
function GetDataTypeDescriptions: TDBXDataTypeDescriptionArray; override;
function GetAllDataTypes: TDBXDataTypeDescriptionArray; virtual;
public
FDefaultCharSetIsUnicode: Boolean;
private
FAlltypes: TDBXDataTypeDescriptionArray;
FQuoteChar: UnicodeString;
public
property DefaultCharSetUnicode: Boolean read IsDefaultCharSetUnicode;
property AllDataTypes: TDBXDataTypeDescriptionArray read GetAllDataTypes;
public
const CharType = 0;
const VarcharType = 1;
const IntegerType = 2;
const SmallintType = 3;
const FloatType = 4;
const DoubleType = 5;
const NumericType = 6;
const DecimalType = 7;
const DateType = 8;
const TimeType = 9;
const TimestampType = 10;
const BlobType = 11;
const BigintType = 12;
const DefaultCharset = 0;
const CharsetUnicodeFss = 3;
const CharsetSjis208 = 5;
const CharsetEucj208 = 6;
private
const TypesCount = 13;
const DefaultStringStart = 'DEFAULT ';
const DefaultCharsetIsUnicode = 'UnicodeEncoding';
const QuoteCharacterEnabled = 'QuoteCharEnabled';
const ColumnsFieldType = TDBXColumnsIndex.TypeName;
const ColumnsSubtype = TDBXColumnsIndex.DbxDataType;
const ParametersFieldType = TDBXProcedureParametersIndex.TypeName;
const ParametersSubtype = TDBXProcedureParametersIndex.DbxDataType;
end;
TDBXFirebirdMetaDataReader = class(TDBXFirebirdCustomMetaDataReader)
public
function FetchCatalogs: TDBXTable; override;
function FetchSchemas(const CatalogName: UnicodeString): TDBXTable; override;
function FetchColumnConstraints(const CatalogName: UnicodeString; const SchemaName: UnicodeString; const TableName: UnicodeString): TDBXTable; override;
function FetchSynonyms(const CatalogName: UnicodeString; const SchemaName: UnicodeString; const SynonymName: UnicodeString): TDBXTable; override;
function FetchPackages(const CatalogName: UnicodeString; const SchemaName: UnicodeString; const PackageName: UnicodeString): TDBXTable; override;
function FetchPackageProcedures(const CatalogName: UnicodeString; const SchemaName: UnicodeString; const PackageName: UnicodeString; const ProcedureName: UnicodeString; const ProcedureType: UnicodeString): TDBXTable; override;
function FetchPackageProcedureParameters(const CatalogName: UnicodeString; const SchemaName: UnicodeString; const PackageName: UnicodeString; const ProcedureName: UnicodeString; const ParameterName: UnicodeString): TDBXTable; override;
function FetchPackageSources(const CatalogName: UnicodeString; const SchemaName: UnicodeString; const PackageName: UnicodeString): TDBXTable; override;
protected
function GetProductName: UnicodeString; override;
function IsDescendingIndexSupported: Boolean; override;
function IsDescendingIndexColumnsSupported: Boolean; override;
function IsNestedTransactionsSupported: Boolean; override;
function IsParameterMetadataSupported: Boolean; override;
function GetSqlForTables: UnicodeString; override;
function GetSqlForViews: UnicodeString; override;
function GetSqlForColumns: UnicodeString; override;
function GetSqlForIndexes: UnicodeString; override;
function GetSqlForIndexColumns: UnicodeString; override;
function GetSqlForForeignKeys: UnicodeString; override;
function GetSqlForForeignKeyColumns: UnicodeString; override;
function GetSqlForProcedures: UnicodeString; override;
function GetSqlForProcedureSources: UnicodeString; override;
function GetSqlForProcedureParameters: UnicodeString; override;
function GetSqlForUsers: UnicodeString; override;
function GetSqlForRoles: UnicodeString; override;
function GetReservedWords: TDBXStringArray; override;
end;
/// <summary> TDBXFirebirdTypeFilterCursor is a filter for a cursor providing table columns and procedure parameters.
/// </summary>
/// <remarks> In Firebird the typename and scale are all encoded in the system tables.
/// This filter also normalizes the default value.
/// </remarks>
TDBXFirebirdTypeFilterCursor = class(TDBXCustomMetaDataTable)
public
type
Tibase_const = class
public
const FBlr_text = 14;
const FBlr_text2 = 15;
const FBlr_short = 7;
const FBlr_long = 8;
const FBlr_quad = 9;
const FBlr_int64 = 16;
const FBlr_float = 10;
const FBlr_double = 27;
const FBlr_d_float = 11;
const FBlr_timestamp = 35;
const FBlr_varying = 37;
const FBlr_varying2 = 38;
const FBlr_blob = 261;
const FBlr_cstring = 40;
const FBlr_cstring2 = 41;
const FBlr_blob_id = 45;
const FBlr_sql_date = 12;
const FBlr_sql_time = 13;
end;
public
destructor Destroy; override;
function Next: Boolean; override;
protected
/// <summary> Constructor for TDBXFirebirdTypeFilterCursor.
/// </summary>
/// <param name="provider">MetadataReader</param>
/// <param name="MetadataCollectionName">Name of the collection</param>
/// <param name="columns">ValueType[] The columns this cursor must generate.</param>
/// <param name="cursor">DBXTable A cursor with the data from the database.</param>
/// <param name="ordinalTypeName">int The ordinal where the computed typename should go.</param>
/// <param name="ordinalFieldType">int The ordinal where the field type is found from the input cursor.</param>
/// <param name="ordinalSubType">int The ordinal where the subtype is found from the input cursor.</param>
/// <param name="ordinalScale">int The ordinal where the scale is found and corrected.</param>
/// <param name="ordinalDefaultValue">int The ordinal where the default value is found and corrected. This value may be -1 which means do not correct default values.</param>
constructor Create(const Provider: TDBXFirebirdCustomMetaDataReader; const MetadataCollectionName: UnicodeString; const Columns: TDBXValueTypeArray; const Cursor: TDBXTable; const OrdinalTypeName: Integer; const OrdinalFieldType: Integer; const OrdinalSubType: Integer; const OrdinalScale: Integer; const OrdinalDefaultValue: Integer);
function FindStringSize(const Ordinal: Integer; const SourceColumns: TDBXValueTypeArray): Integer; override;
function GetWritableValue(const Ordinal: Integer): TDBXWritableValue; override;
private
procedure ComputeDataType;
function ComputeTypeName: UnicodeString;
function ComputeUnicode: Boolean;
function ComputeDefaultValue: UnicodeString;
function GetIBType(const FieldType: SmallInt; const FieldSubType: SmallInt; const FieldScale: SmallInt): Integer;
private
FCustomProvider: TDBXFirebirdCustomMetaDataReader;
FOrdinalTypeName: Integer;
FOrdinalFieldType: Integer;
FOrdinalSubType: Integer;
FOrdinalCharSet: Integer;
FOrdinalScale: Integer;
FOrdinalDefaultValue: Integer;
FDataType: TDBXDataTypeDescription;
FRow: TDBXSingleValueRow;
private
const DefaultStringStart = 'DEFAULT ';
end;
implementation
uses
System.SysUtils;
destructor TDBXFirebirdCustomMetaDataReader.Destroy;
begin
FreeObjectArray(TDBXFreeArray(FAlltypes));
inherited Destroy;
end;
procedure TDBXFirebirdCustomMetaDataReader.SetContext(const Context: TDBXProviderContext);
begin
inherited SetContext(Context);
FDefaultCharSetIsUnicode := (Context.GetVendorProperty(DefaultCharsetIsUnicode) = 'true');
FQuoteChar := C_Conditional((Context.GetVendorProperty(QuoteCharacterEnabled) = 'true'), '"', '');
end;
function TDBXFirebirdCustomMetaDataReader.IsDefaultCharSetUnicode: Boolean;
begin
Result := FDefaultCharSetIsUnicode;
end;
function TDBXFirebirdCustomMetaDataReader.GetSqlIdentifierQuotePrefix: UnicodeString;
begin
Result := FQuoteChar;
end;
function TDBXFirebirdCustomMetaDataReader.GetSqlIdentifierQuoteSuffix: UnicodeString;
begin
Result := FQuoteChar;
end;
function TDBXFirebirdCustomMetaDataReader.GetSqlIdentifierQuoteChar: UnicodeString;
begin
Result := FQuoteChar;
end;
function TDBXFirebirdCustomMetaDataReader.GetDataTypeDescriptions: TDBXDataTypeDescriptionArray;
var
DataTypes: TDBXDataTypeDescriptionArray;
Index: Integer;
begin
AllDataTypes;
SetLength(DataTypes,Length(FAlltypes));
for index := 0 to Length(DataTypes) - 1 do
DataTypes[Index] := TDBXDataTypeDescription.Create(FAlltypes[Index]);
Result := DataTypes;
end;
function TDBXFirebirdCustomMetaDataReader.GetAllDataTypes: TDBXDataTypeDescriptionArray;
var
Newtypes: TDBXDataTypeDescriptionArray;
StringType: Integer;
begin
if FAlltypes = nil then
begin
SetLength(Newtypes,TypesCount);
StringType := TDBXDataTypes.AnsiStringType;
if FDefaultCharSetIsUnicode then
StringType := TDBXDataTypes.WideStringType;
Newtypes[CharType] := TDBXDataTypeDescription.Create('CHAR', StringType, 32768, 'CHAR({0})', 'Precision', -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike or TDBXTypeFlag.Unsigned or TDBXTypeFlag.UnicodeOption);
Newtypes[VarcharType] := TDBXDataTypeDescription.Create('VARCHAR', StringType, 32678, 'VARCHAR({0})', 'Precision', -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike or TDBXTypeFlag.Unsigned or TDBXTypeFlag.UnicodeOption);
Newtypes[IntegerType] := TDBXDataTypeDescription.Create('INTEGER', TDBXDataTypes.Int32Type, 10, 'INTEGER', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Newtypes[SmallintType] := TDBXDataTypeDescription.Create('SMALLINT', TDBXDataTypes.Int16Type, 5, 'SMALLINT', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Newtypes[FloatType] := TDBXDataTypeDescription.Create('FLOAT', TDBXDataTypes.SingleType, 53, 'FLOAT({0})', 'Precision', -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Newtypes[DoubleType] := TDBXDataTypeDescription.Create('DOUBLE PRECISION', TDBXDataTypes.DoubleType, 53, 'DOUBLE PRECISION', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Newtypes[NumericType] := TDBXDataTypeDescription.Create('NUMERIC', TDBXDataTypes.BcdType, 18, 'NUMERIC({0}, {1})', 'Precision, Scale', 18, 0, NullString, NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Newtypes[DecimalType] := TDBXDataTypeDescription.Create('DECIMAL', TDBXDataTypes.BcdType, 18, 'DECIMAL({0}, {1})', 'Precision, Scale', 18, 0, NullString, NullString, NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.Unsigned);
Newtypes[DateType] := TDBXDataTypeDescription.Create('DATE', TDBXDataTypes.DateType, 0, 'DATE', NullString, -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Newtypes[TimeType] := TDBXDataTypeDescription.Create('TIME', TDBXDataTypes.TimeType, 0, 'TIME', NullString, -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Newtypes[TimestampType] := TDBXDataTypeDescription.Create('TIMESTAMP', TDBXDataTypes.TimeStampType, 0, 'TIMESTAMP', NullString, -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Newtypes[BlobType] := TDBXDataTypeDescription.Create('BLOB', TDBXDataTypes.BlobType, 2147483647, 'BLOB', 'Precision', -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.Long or TDBXTypeFlag.Nullable or TDBXTypeFlag.Unsigned or TDBXTypeFlag.StringOption or TDBXTypeFlag.UnicodeOption);
Newtypes[BigintType] := TDBXDataTypeDescription.Create('BIGINT', TDBXDataTypes.Int64Type, 19, 'BIGINT', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.BestMatch + TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
FAlltypes := Newtypes;
end;
Result := FAlltypes;
end;
function TDBXFirebirdCustomMetaDataReader.FetchColumns(const Catalog: UnicodeString; const Schema: UnicodeString; const Table: UnicodeString): TDBXTable;
var
ParameterNames: TDBXStringArray;
ParameterValues: TDBXStringArray;
Cursor: TDBXTable;
Columns: TDBXValueTypeArray;
begin
SetLength(ParameterNames,3);
ParameterNames[0] := TDBXParameterName.CatalogName;
ParameterNames[1] := TDBXParameterName.SchemaName;
ParameterNames[2] := TDBXParameterName.TableName;
SetLength(ParameterValues,3);
ParameterValues[0] := Catalog;
ParameterValues[1] := Schema;
ParameterValues[2] := Table;
Cursor := Context.ExecuteQuery(SqlForColumns, ParameterNames, ParameterValues);
Columns := TDBXMetaDataCollectionColumns.CreateColumnsColumns;
Result := TDBXFirebirdTypeFilterCursor.Create(self, TDBXMetaDataCollectionName.Columns, Columns, Cursor, TDBXColumnsIndex.TypeName, ColumnsFieldType, ColumnsSubtype, TDBXColumnsIndex.Scale, TDBXColumnsIndex.DefaultValue);
end;
function TDBXFirebirdCustomMetaDataReader.FetchProcedureParameters(const Catalog: UnicodeString; const Schema: UnicodeString; const &Procedure: UnicodeString; const Parameter: UnicodeString): TDBXTable;
var
ParameterNames: TDBXStringArray;
ParameterValues: TDBXStringArray;
Cursor: TDBXTable;
Columns: TDBXValueTypeArray;
begin
SetLength(ParameterNames,4);
ParameterNames[0] := TDBXParameterName.CatalogName;
ParameterNames[1] := TDBXParameterName.SchemaName;
ParameterNames[2] := TDBXParameterName.ProcedureName;
ParameterNames[3] := TDBXParameterName.ParameterName;
SetLength(ParameterValues,4);
ParameterValues[0] := Catalog;
ParameterValues[1] := Schema;
ParameterValues[2] := &Procedure;
ParameterValues[3] := Parameter;
Cursor := Context.ExecuteQuery(SqlForProcedureParameters, ParameterNames, ParameterValues);
Columns := TDBXMetaDataCollectionColumns.CreateProcedureParametersColumns;
Result := TDBXFirebirdTypeFilterCursor.Create(self, TDBXMetaDataCollectionName.ProcedureParameters, Columns, Cursor, TDBXProcedureParametersIndex.TypeName, ParametersFieldType, ParametersSubtype, TDBXProcedureParametersIndex.Scale, -1);
end;
function TDBXFirebirdMetaDataReader.GetProductName: UnicodeString;
begin
Result := 'Firebird';
end;
function TDBXFirebirdMetaDataReader.IsDescendingIndexSupported: Boolean;
begin
Result := True;
end;
function TDBXFirebirdMetaDataReader.IsDescendingIndexColumnsSupported: Boolean;
begin
Result := False;
end;
function TDBXFirebirdMetaDataReader.IsNestedTransactionsSupported: Boolean;
begin
Result := True;
end;
function TDBXFirebirdMetaDataReader.IsParameterMetadataSupported: Boolean;
begin
Result := True;
end;
function TDBXFirebirdMetaDataReader.FetchCatalogs: TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateCatalogsColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Catalogs, Columns);
end;
function TDBXFirebirdMetaDataReader.FetchSchemas(const CatalogName: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateSchemasColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Schemas, Columns);
end;
function TDBXFirebirdMetaDataReader.GetSqlForTables: UnicodeString;
begin
Result := 'SELECT NULL, NULL, RDB$RELATION_NAME, CASE WHEN RDB$SYSTEM_FLAG > 0 THEN ''SYSTEM TABLE'' WHEN RDB$VIEW_SOURCE IS NOT NULL THEN ''VIEW'' ELSE ''TABLE'' END AS TABLE_TYPE ' +
'FROM RDB$RELATIONS ' +
'WHERE (1<2 OR (:CATALOG_NAME IS NULL)) AND (1<2 OR (:SCHEMA_NAME IS NULL)) AND (RDB$RELATION_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' +
' AND ((RDB$SYSTEM_FLAG > 0 AND :SYSTEM_TABLES=''SYSTEM TABLE'') OR (RDB$VIEW_SOURCE IS NOT NULL AND :VIEWS=''VIEW'') OR (RDB$SYSTEM_FLAG = 0 AND RDB$VIEW_SOURCE IS NULL AND :TABLES=''TABLE'')) ' +
'ORDER BY 3';
end;
function TDBXFirebirdMetaDataReader.GetSqlForViews: UnicodeString;
begin
Result := 'SELECT NULL, NULL, RDB$RELATION_NAME, RDB$VIEW_SOURCE ' +
'FROM RDB$RELATIONS ' +
'WHERE (1<2 OR (:CATALOG_NAME IS NULL)) AND (1<2 OR (:SCHEMA_NAME IS NULL)) AND (RDB$RELATION_NAME = :VIEW_NAME OR (:VIEW_NAME IS NULL)) AND (RDB$VIEW_SOURCE IS NOT NULL) ' +
'ORDER BY 3';
end;
function TDBXFirebirdMetaDataReader.GetSqlForColumns: UnicodeString;
begin
Result := 'SELECT NULL, NULL, RF.RDB$RELATION_NAME, RF.RDB$FIELD_NAME, F.RDB$FIELD_TYPE, COALESCE(F.RDB$FIELD_PRECISION,F.RDB$CHARACTER_LENGTH,F.RDB$FIELD_LENGTH), F.RDB$FIELD_SCALE, RF.RDB$FIELD_POSITION+1, RF.RDB$DEFAULT_SOURCE, CASE WHEN RF.RDB$NULL_FLAG=1 THEN 0' + ' ELSE 1 END, 0, NULL, F.RDB$FIELD_SUB_TYPE, F.RDB$CHARACTER_SET_ID ' +
'FROM RDB$RELATION_FIELDS RF, RDB$FIELDS F ' +
'WHERE (RF.RDB$FIELD_SOURCE = F.RDB$FIELD_NAME) ' +
' AND (1<2 OR (:CATALOG_NAME IS NULL)) AND (1<2 OR (:SCHEMA_NAME IS NULL)) AND (RF.RDB$RELATION_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' +
'ORDER BY 3, RF.RDB$FIELD_POSITION';
end;
function TDBXFirebirdMetaDataReader.FetchColumnConstraints(const CatalogName: UnicodeString; const SchemaName: UnicodeString; const TableName: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateColumnConstraintsColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.ColumnConstraints, Columns);
end;
function TDBXFirebirdMetaDataReader.GetSqlForIndexes: UnicodeString;
begin
Result := 'SELECT NULL, NULL, I.RDB$RELATION_NAME, CASE WHEN C.RDB$CONSTRAINT_NAME IS NULL THEN I.RDB$INDEX_NAME ELSE C.RDB$CONSTRAINT_NAME END, C.RDB$CONSTRAINT_NAME, CASE WHEN C.RDB$CONSTRAINT_TYPE=''PRIMARY KEY'' THEN 1 ELSE 0 END, COALESCE(I.RDB$UNIQUE_FLAG,0), CO' + 'ALESCE(1-I.RDB$INDEX_TYPE,1) ' +
'FROM RDB$INDICES I LEFT OUTER JOIN RDB$RELATION_CONSTRAINTS C ON I.RDB$INDEX_NAME = C.RDB$INDEX_NAME ' +
'WHERE (1<2 OR (:CATALOG_NAME IS NULL)) AND (1<2 OR (:SCHEMA_NAME IS NULL)) AND (I.RDB$RELATION_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' +
'ORDER BY 3, 4';
end;
function TDBXFirebirdMetaDataReader.GetSqlForIndexColumns: UnicodeString;
begin
Result := 'SELECT NULL, NULL, I.RDB$RELATION_NAME, CASE WHEN C.RDB$CONSTRAINT_NAME IS NULL THEN I.RDB$INDEX_NAME ELSE C.RDB$CONSTRAINT_NAME END, S.RDB$FIELD_NAME, S.RDB$FIELD_POSITION+1, 1 ' +
'FROM RDB$INDICES I LEFT OUTER JOIN RDB$RELATION_CONSTRAINTS C ON I.RDB$INDEX_NAME = C.RDB$INDEX_NAME, RDB$INDEX_SEGMENTS S ' +
'WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME ' +
' AND (1<2 OR (:CATALOG_NAME IS NULL)) AND (1<2 OR (:SCHEMA_NAME IS NULL)) AND (I.RDB$RELATION_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) AND (CASE WHEN C.RDB$CONSTRAINT_NAME IS NULL THEN I.RDB$INDEX_NAME ELSE C.RDB$CONSTRAINT_NAME END = :INDEX_NAME OR (' + ':INDEX_NAME IS NULL)) ' +
'ORDER BY 3, 4, 6';
end;
function TDBXFirebirdMetaDataReader.GetSqlForForeignKeys: UnicodeString;
begin
Result := 'SELECT NULL, NULL, FK.RDB$RELATION_NAME, FK.RDB$CONSTRAINT_NAME ' +
'FROM RDB$RELATION_CONSTRAINTS FK ' +
'WHERE FK.RDB$CONSTRAINT_TYPE = ''FOREIGN KEY'' ' +
' AND (1<2 OR (:CATALOG_NAME IS NULL)) AND (1<2 OR (:SCHEMA_NAME IS NULL)) AND (FK.RDB$RELATION_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' +
'ORDER BY 3,4';
end;
function TDBXFirebirdMetaDataReader.GetSqlForForeignKeyColumns: UnicodeString;
begin
Result := 'SELECT NULL, NULL, FK.RDB$RELATION_NAME, FK.RDB$CONSTRAINT_NAME, ISF.RDB$FIELD_NAME, NULL, NULL, PK.RDB$RELATION_NAME, PK.RDB$CONSTRAINT_NAME, ISP.RDB$FIELD_NAME, ISP.RDB$FIELD_POSITION + 1 ' +
'FROM RDB$RELATION_CONSTRAINTS PK, RDB$RELATION_CONSTRAINTS FK, RDB$REF_CONSTRAINTS FRC, RDB$REF_CONSTRAINTS PRC, RDB$INDEX_SEGMENTS ISP, RDB$INDEX_SEGMENTS ISF ' +
'WHERE FK.RDB$CONSTRAINT_TYPE = ''FOREIGN KEY'' ' +
' AND FK.RDB$CONSTRAINT_NAME = FRC.RDB$CONSTRAINT_NAME ' +
' AND FRC.RDB$CONST_NAME_UQ = PK.RDB$CONSTRAINT_NAME ' +
' AND PK.RDB$INDEX_NAME = ISP.RDB$INDEX_NAME ' +
' AND ISF.RDB$INDEX_NAME = FK.RDB$INDEX_NAME ' +
' AND ISP.RDB$FIELD_POSITION = ISF.RDB$FIELD_POSITION ' +
' AND PRC.RDB$CONSTRAINT_NAME = FK.RDB$CONSTRAINT_NAME ' +
' AND (1<2 OR (:CATALOG_NAME IS NULL)) AND (1<2 OR (:SCHEMA_NAME IS NULL)) AND (FK.RDB$RELATION_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) AND (FK.RDB$CONSTRAINT_NAME = :FOREIGN_KEY_NAME OR (:FOREIGN_KEY_NAME IS NULL)) ' +
' AND (1<2 OR (:PRIMARY_CATALOG_NAME IS NULL)) AND (1<2 OR (:PRIMARY_SCHEMA_NAME IS NULL)) AND (PK.RDB$RELATION_NAME = :PRIMARY_TABLE_NAME OR (:PRIMARY_TABLE_NAME IS NULL)) AND (PK.RDB$CONSTRAINT_NAME = :PRIMARY_KEY_NAME OR (:PRIMARY_KEY_NAME IS NULL)) ' +
'ORDER BY 3,4,ISP.RDB$FIELD_POSITION';
end;
function TDBXFirebirdMetaDataReader.FetchSynonyms(const CatalogName: UnicodeString; const SchemaName: UnicodeString; const SynonymName: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateSynonymsColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Synonyms, Columns);
end;
function TDBXFirebirdMetaDataReader.GetSqlForProcedures: UnicodeString;
begin
Result := 'SELECT NULL, NULL, RDB$PROCEDURE_NAME, CAST(''PROCEDURE'' AS VARCHAR(10)) ' +
'FROM RDB$PROCEDURES ' +
'WHERE (1<2 OR (:CATALOG_NAME IS NULL)) AND (1<2 OR (:SCHEMA_NAME IS NULL)) AND (RDB$PROCEDURE_NAME = :PROCEDURE_NAME OR (:PROCEDURE_NAME IS NULL)) AND (CAST(''PROCEDURE'' AS VARCHAR(10)) = :PROCEDURE_TYPE OR (:PROCEDURE_TYPE IS NULL)) ' +
'UNION ALL ' +
'SELECT NULL, NULL, RDB$FUNCTION_NAME, CAST(''FUNCTION'' AS VARCHAR(10)) ' +
'FROM RDB$FUNCTIONS ' +
'WHERE (1<2 OR (:CATALOG_NAME IS NULL)) AND (1<2 OR (:SCHEMA_NAME IS NULL)) AND (RDB$FUNCTION_NAME = :PROCEDURE_NAME OR (:PROCEDURE_NAME IS NULL)) AND (CAST(''FUNCTION'' AS VARCHAR(10)) = :PROCEDURE_TYPE OR (:PROCEDURE_TYPE IS NULL)) ' +
'ORDER BY 3';
end;
function TDBXFirebirdMetaDataReader.GetSqlForProcedureSources: UnicodeString;
begin
Result := 'SELECT NULL, NULL, RDB$PROCEDURE_NAME, ''PROCEDURE'', RDB$PROCEDURE_SOURCE, NULL ' +
'FROM RDB$PROCEDURES ' +
'WHERE (1<2 OR (:CATALOG_NAME IS NULL)) AND (1<2 OR (:SCHEMA_NAME IS NULL)) AND (RDB$PROCEDURE_NAME = :PROCEDURE_NAME OR (:PROCEDURE_NAME IS NULL)) ' +
'ORDER BY 3';
end;
function TDBXFirebirdMetaDataReader.GetSqlForProcedureParameters: UnicodeString;
begin
Result := 'SELECT NULL, NULL, P.RDB$PROCEDURE_NAME, P.RDB$PARAMETER_NAME, CASE ' +
'WHEN P.RDB$PARAMETER_TYPE > 0 THEN CAST(''OUT'' AS CHAR(6)) ELSE CAST(''IN'' AS CHAR(6)) END, ' +
'C.RDB$FIELD_TYPE, COALESCE(C.RDB$FIELD_PRECISION,C.RDB$CHARACTER_LENGTH,C.RDB$FIELD_LENGTH), ' +
'C.RDB$FIELD_SCALE, CAST(P.RDB$PARAMETER_NUMBER+1 AS SMALLINT), CAST(COALESCE(1-C.RDB$NULL_FLAG,1) AS INTEGER), ' +
'C.RDB$FIELD_SUB_TYPE, C.RDB$CHARACTER_SET_ID ' +
'FROM RDB$PROCEDURE_PARAMETERS P, RDB$FIELDS C ' +
'WHERE P.RDB$FIELD_SOURCE = C.RDB$FIELD_NAME ' +
' AND (1<2 OR (:CATALOG_NAME IS NULL)) AND (1<2 OR (:SCHEMA_NAME IS NULL)) AND (P.RDB$PROCEDURE_NAME = :PROCEDURE_NAME OR (:PROCEDURE_NAME IS NULL)) AND (P.RDB$PARAMETER_NAME = :PARAMETER_NAME OR (:PARAMETER_NAME IS NULL)) ' +
'UNION ALL ' +
'SELECT NULL, NULL, F.RDB$FUNCTION_NAME, F.RDB$FUNCTION_NAME, CASE WHEN F.RDB$ARGUMENT_POSITION = 0 THEN CAST(''OUT'' AS CHAR(6)) ELSE CAST(''IN'' AS CHAR(6)) END, ' +
'F.RDB$FIELD_TYPE, COALESCE(F.RDB$FIELD_PRECISION,F.RDB$CHARACTER_LENGTH,F.RDB$FIELD_LENGTH), ' +
'F.RDB$FIELD_SCALE, F.RDB$ARGUMENT_POSITION, CAST (0 AS INTEGER), F.RDB$FIELD_SUB_TYPE, ' +
'F.RDB$CHARACTER_SET_ID ' +
'FROM RDB$FUNCTION_ARGUMENTS F ' +
'WHERE (1<2 OR (:CATALOG_NAME IS NULL)) AND (1<2 OR (:SCHEMA_NAME IS NULL)) AND (CAST(''ARG'' || (F.RDB$ARGUMENT_POSITION+1) AS CHAR(67)) = :PROCEDURE_NAME OR (:PROCEDURE_NAME IS NULL)) AND (F.RDB$FUNCTION_NAME = :PARAMETER_NAME OR (:PARAMETER_NAME IS NULL))' + ' ' +
'ORDER BY 5, 9';
end;
function TDBXFirebirdMetaDataReader.FetchPackages(const CatalogName: UnicodeString; const SchemaName: UnicodeString; const PackageName: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreatePackagesColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Packages, Columns);
end;
function TDBXFirebirdMetaDataReader.FetchPackageProcedures(const CatalogName: UnicodeString; const SchemaName: UnicodeString; const PackageName: UnicodeString; const ProcedureName: UnicodeString; const ProcedureType: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreatePackageProceduresColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.PackageProcedures, Columns);
end;
function TDBXFirebirdMetaDataReader.FetchPackageProcedureParameters(const CatalogName: UnicodeString; const SchemaName: UnicodeString; const PackageName: UnicodeString; const ProcedureName: UnicodeString; const ParameterName: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreatePackageProcedureParametersColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.PackageProcedureParameters, Columns);
end;
function TDBXFirebirdMetaDataReader.FetchPackageSources(const CatalogName: UnicodeString; const SchemaName: UnicodeString; const PackageName: UnicodeString): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreatePackageSourcesColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.PackageSources, Columns);
end;
function TDBXFirebirdMetaDataReader.GetSqlForUsers: UnicodeString;
begin
Result := 'SELECT DISTINCT RDB$USER FROM RDB$USER_PRIVILEGES ORDER BY 1';
end;
function TDBXFirebirdMetaDataReader.GetSqlForRoles: UnicodeString;
begin
Result := 'SELECT RDB$ROLE_NAME FROM RDB$ROLES ORDER BY 1';
end;
function TDBXFirebirdMetaDataReader.GetReservedWords: TDBXStringArray;
var
Words: TDBXStringArray;
begin
SetLength(Words,289);
Words[0] := 'ACTION';
Words[1] := 'ACTIVE';
Words[2] := 'ADD';
Words[3] := 'ADMIN';
Words[4] := 'AFTER';
Words[5] := 'ALL';
Words[6] := 'ALTER';
Words[7] := 'AND';
Words[8] := 'ANY';
Words[9] := 'AS';
Words[10] := 'ASC';
Words[11] := 'ASCENDING';
Words[12] := 'AT';
Words[13] := 'AUTO';
Words[14] := 'AUTODDL';
Words[15] := 'AVG';
Words[16] := 'BASED';
Words[17] := 'BASENAME';
Words[18] := 'BASE_NAME';
Words[19] := 'BEFORE';
Words[20] := 'BEGIN';
Words[21] := 'BETWEEN';
Words[22] := 'BLOB';
Words[23] := 'BLOBEDIT';
Words[24] := 'BOOLEAN';
Words[25] := 'BUFFER';
Words[26] := 'BY';
Words[27] := 'CACHE';
Words[28] := 'CASCADE';
Words[29] := 'CAST';
Words[30] := 'CHAR';
Words[31] := 'CHARACTER';
Words[32] := 'CHARACTER_LENGTH';
Words[33] := 'CHAR_LENGTH';
Words[34] := 'CHECK';
Words[35] := 'CHECK_POINT_LEN';
Words[36] := 'CHECK_POINT_LENGTH';
Words[37] := 'COLLATE';
Words[38] := 'COLLATION';
Words[39] := 'COLUMN';
Words[40] := 'COMMIT';
Words[41] := 'COMMITTED';
Words[42] := 'COMPILETIME';
Words[43] := 'COMPUTED';
Words[44] := 'CLOSE';
Words[45] := 'CONDITIONAL';
Words[46] := 'CONNECT';
Words[47] := 'CONSTRAINT';
Words[48] := 'CONTAINING';
Words[49] := 'CONTINUE';
Words[50] := 'COUNT';
Words[51] := 'CREATE';
Words[52] := 'CSTRING';
Words[53] := 'CURRENT';
Words[54] := 'CURRENT_DATE';
Words[55] := 'CURRENT_TIME';
Words[56] := 'CURRENT_TIMESTAMP';
Words[57] := 'CURSOR';
Words[58] := 'DATABASE';
Words[59] := 'DATE';
Words[60] := 'DAY';
Words[61] := 'DB_KEY';
Words[62] := 'DEBUG';
Words[63] := 'DEC';
Words[64] := 'DECIMAL';
Words[65] := 'DECLARE';
Words[66] := 'DEFAULT';
Words[67] := 'DELETE';
Words[68] := 'DESC';
Words[69] := 'DESCENDING';
Words[70] := 'DESCRIBE';
Words[71] := 'DESCRIPTOR';
Words[72] := 'DISCONNECT';
Words[73] := 'DISPLAY';
Words[74] := 'DISTINCT';
Words[75] := 'DO';
Words[76] := 'DOMAIN';
Words[77] := 'DOUBLE';
Words[78] := 'DROP';
Words[79] := 'ECHO';
Words[80] := 'EDIT';
Words[81] := 'ELSE';
Words[82] := 'END';
Words[83] := 'ENTRY_POINT';
Words[84] := 'ESCAPE';
Words[85] := 'EVENT';
Words[86] := 'EXCEPTION';
Words[87] := 'EXECUTE';
Words[88] := 'EXISTS';
Words[89] := 'EXIT';
Words[90] := 'EXTERN';
Words[91] := 'EXTERNAL';
Words[92] := 'EXTRACT';
Words[93] := 'FALSE';
Words[94] := 'FETCH';
Words[95] := 'FILE';
Words[96] := 'FILTER';
Words[97] := 'FLOAT';
Words[98] := 'FOR';
Words[99] := 'FOREIGN';
Words[100] := 'FOUND';
Words[101] := 'FREE_IT';
Words[102] := 'FROM';
Words[103] := 'FULL';
Words[104] := 'FUNCTION';
Words[105] := 'GDSCODE';
Words[106] := 'GENERATOR';
Words[107] := 'GEN_ID';
Words[108] := 'GLOBAL';
Words[109] := 'GOTO';
Words[110] := 'GRANT';
Words[111] := 'GROUP';
Words[112] := 'GROUP_COMMIT_WAIT';
Words[113] := 'GROUP_COMMIT_WAIT_TIME';
Words[114] := 'HAVING';
Words[115] := 'HELP';
Words[116] := 'HOUR';
Words[117] := 'IF';
Words[118] := 'IMMEDIATE';
Words[119] := 'IN';
Words[120] := 'INACTIVE';
Words[121] := 'INDEX';
Words[122] := 'INDICATOR';
Words[123] := 'INIT';
Words[124] := 'INNER';
Words[125] := 'INPUT';
Words[126] := 'INPUT_TYPE';
Words[127] := 'INSERT';
Words[128] := 'INT';
Words[129] := 'INTEGER';
Words[130] := 'INTO';
Words[131] := 'IS';
Words[132] := 'ISOLATION';
Words[133] := 'ISQL';
Words[134] := 'JOIN';
Words[135] := 'KEY';
Words[136] := 'LC_MESSAGES';
Words[137] := 'LC_TYPE';
Words[138] := 'LEFT';
Words[139] := 'LENGTH';
Words[140] := 'LEV';
Words[141] := 'LEVEL';
Words[142] := 'LIKE';
Words[143] := 'LOGFILE';
Words[144] := 'LOG_BUFFER_SIZE';
Words[145] := 'LOG_BUF_SIZE';
Words[146] := 'LONG';
Words[147] := 'MANUAL';
Words[148] := 'MAX';
Words[149] := 'MAXIMUM';
Words[150] := 'MAXIMUM_SEGMENT';
Words[151] := 'MAX_SEGMENT';
Words[152] := 'MERGE';
Words[153] := 'MESSAGE';
Words[154] := 'MIN';
Words[155] := 'MINIMUM';
Words[156] := 'MINUTE';
Words[157] := 'MODULE_NAME';
Words[158] := 'MONTH';
Words[159] := 'NAMES';
Words[160] := 'NATIONAL';
Words[161] := 'NATURAL';
Words[162] := 'NCHAR';
Words[163] := 'NO';
Words[164] := 'NOAUTO';
Words[165] := 'NOT';
Words[166] := 'NULL';
Words[167] := 'NUMERIC';
Words[168] := 'NUM_LOG_BUFS';
Words[169] := 'NUM_LOG_BUFFERS';
Words[170] := 'OCTET_LENGTH';
Words[171] := 'OF';
Words[172] := 'ON';
Words[173] := 'ONLY';
Words[174] := 'OPEN';
Words[175] := 'OPTION';
Words[176] := 'OR';
Words[177] := 'ORDER';
Words[178] := 'OUTER';
Words[179] := 'OUTPUT';
Words[180] := 'OUTPUT_TYPE';
Words[181] := 'OVERFLOW';
Words[182] := 'PAGE';
Words[183] := 'PAGELENGTH';
Words[184] := 'PAGES';
Words[185] := 'PAGE_SIZE';
Words[186] := 'PARAMETER';
Words[187] := 'PASSWORD';
Words[188] := 'PERCENT';
Words[189] := 'PLAN';
Words[190] := 'POSITION';
Words[191] := 'POST_EVENT';
Words[192] := 'PRECISION';
Words[193] := 'PREPARE';
Words[194] := 'PRESERVE';
Words[195] := 'PROCEDURE';
Words[196] := 'PROTECTED';
Words[197] := 'PRIMARY';
Words[198] := 'PRIVILEGES';
Words[199] := 'PUBLIC';
Words[200] := 'QUIT';
Words[201] := 'RAW_PARTITIONS';
Words[202] := 'RDB$DB_KEY';
Words[203] := 'READ';
Words[204] := 'REAL';
Words[205] := 'RECORD_VERSION';
Words[206] := 'REFERENCES';
Words[207] := 'RELEASE';
Words[208] := 'RESERV';
Words[209] := 'RESERVING';
Words[210] := 'RESTRICT';
Words[211] := 'RETAIN';
Words[212] := 'RETURN';
Words[213] := 'RETURNING_VALUES';
Words[214] := 'RETURNS';
Words[215] := 'REVOKE';
Words[216] := 'RIGHT';
Words[217] := 'ROLE';
Words[218] := 'ROLLBACK';
Words[219] := 'ROWS';
Words[220] := 'RUNTIME';
Words[221] := 'SCHEMA';
Words[222] := 'SECOND';
Words[223] := 'SEGMENT';
Words[224] := 'SELECT';
Words[225] := 'SET';
Words[226] := 'SHADOW';
Words[227] := 'SHARED';
Words[228] := 'SHELL';
Words[229] := 'SHOW';
Words[230] := 'SINGULAR';
Words[231] := 'SIZE';
Words[232] := 'SMALLINT';
Words[233] := 'SNAPSHOT';
Words[234] := 'SOME';
Words[235] := 'SORT';
Words[236] := 'SQLCODE';
Words[237] := 'SQLERROR';
Words[238] := 'SQLWARNING';
Words[239] := 'STABILITY';
Words[240] := 'STARTING';
Words[241] := 'STARTS';
Words[242] := 'STATEMENT';
Words[243] := 'STATIC';
Words[244] := 'STATISTICS';
Words[245] := 'SUB_TYPE';
Words[246] := 'SUM';
Words[247] := 'SUSPEND';
Words[248] := 'TABLE';
Words[249] := 'TEMPORARY';
Words[250] := 'TERMINATOR';
Words[251] := 'THEN';
Words[252] := 'TIES';
Words[253] := 'TIME';
Words[254] := 'TIMESTAMP';
Words[255] := 'TO';
Words[256] := 'TRANSACTION';
Words[257] := 'TRANSLATE';
Words[258] := 'TRANSLATION';
Words[259] := 'TRIGGER';
Words[260] := 'TRIM';
Words[261] := 'TRUE';
Words[262] := 'TYPE';
Words[263] := 'UNCOMMITTED';
Words[264] := 'UNION';
Words[265] := 'UNIQUE';
Words[266] := 'UNKNOWN';
Words[267] := 'UPDATE';
Words[268] := 'UPPER';
Words[269] := 'USER';
Words[270] := 'USING';
Words[271] := 'VALUE';
Words[272] := 'VALUES';
Words[273] := 'VARCHAR';
Words[274] := 'VARIABLE';
Words[275] := 'VARYING';
Words[276] := 'VERSION';
Words[277] := 'VIEW';
Words[278] := 'WAIT';
Words[279] := 'WEEKDAY';
Words[280] := 'WHEN';
Words[281] := 'WHENEVER';
Words[282] := 'WHERE';
Words[283] := 'WHILE';
Words[284] := 'WITH';
Words[285] := 'WORK';
Words[286] := 'WRITE';
Words[287] := 'YEAR';
Words[288] := 'YEARDAY';
Result := Words;
end;
constructor TDBXFirebirdTypeFilterCursor.Create(const Provider: TDBXFirebirdCustomMetaDataReader; const MetadataCollectionName: UnicodeString; const Columns: TDBXValueTypeArray; const Cursor: TDBXTable; const OrdinalTypeName: Integer; const OrdinalFieldType: Integer; const OrdinalSubType: Integer; const OrdinalScale: Integer; const OrdinalDefaultValue: Integer);
begin
inherited Create(Provider.Context, MetadataCollectionName, Columns, Cursor);
self.FCustomProvider := Provider;
self.FOrdinalTypeName := OrdinalTypeName;
self.FOrdinalFieldType := OrdinalFieldType;
self.FOrdinalSubType := OrdinalSubType;
self.FOrdinalCharSet := OrdinalSubType + 1;
self.FOrdinalScale := OrdinalScale;
self.FOrdinalDefaultValue := OrdinalDefaultValue;
FRow := TDBXSingleValueRow.Create;
FRow.Columns := CopyColumns;
end;
destructor TDBXFirebirdTypeFilterCursor.Destroy;
begin
FreeAndNil(FRow);
inherited Destroy;
end;
function TDBXFirebirdTypeFilterCursor.FindStringSize(const Ordinal: Integer; const SourceColumns: TDBXValueTypeArray): Integer;
begin
if Ordinal = FOrdinalTypeName then
Result := Length('DOUBLE PRECISION') * 2
else
Result := inherited FindStringSize(Ordinal, SourceColumns);
end;
function TDBXFirebirdTypeFilterCursor.Next: Boolean;
var
Ordinal: Integer;
begin
FDataType := nil;
if not inherited Next then
Exit(False);
ComputeDataType;
if FDataType = nil then
begin
FRow.Value[FOrdinalTypeName].SetNull;
for Ordinal := FOrdinalSubType to Length(FColumns) - 1 do
FRow.Value[Ordinal].SetNull;
end
else
begin
FRow.Value[FOrdinalTypeName].AsString := ComputeTypeName;
FRow.Value[FOrdinalSubType].AsInt32 := FDataType.DbxDataType;
FRow.Value[TDBXColumnsIndex.IsFixedLength + FOrdinalSubType - TDBXColumnsIndex.DbxDataType].AsBoolean := FDataType.FixedLength;
FRow.Value[TDBXColumnsIndex.IsUnicode + FOrdinalSubType - TDBXColumnsIndex.DbxDataType].AsBoolean := ComputeUnicode;
FRow.Value[TDBXColumnsIndex.IsLong + FOrdinalSubType - TDBXColumnsIndex.DbxDataType].AsBoolean := FDataType.Long;
FRow.Value[TDBXColumnsIndex.IsUnsigned + FOrdinalSubType - TDBXColumnsIndex.DbxDataType].AsBoolean := FDataType.Unsigned;
end;
if FOrdinalDefaultValue >= 0 then
FRow.Value[FOrdinalDefaultValue].AsString := ComputeDefaultValue;
FRow.Value[FOrdinalScale].AsInt32 := Abs(FCursor.Value[FOrdinalScale].AsInt32);
Result := True;
end;
function TDBXFirebirdTypeFilterCursor.GetWritableValue(const Ordinal: Integer): TDBXWritableValue;
begin
if (Ordinal >= FOrdinalSubType) or (Ordinal = FOrdinalTypeName) or (Ordinal = FOrdinalDefaultValue) or (Ordinal = FOrdinalScale) or (Ordinal = FOrdinalSubType) or (Ordinal = FOrdinalFieldType) then
Exit(FRow.Value[Ordinal]);
Result := inherited GetWritableValue(Ordinal);
end;
procedure TDBXFirebirdTypeFilterCursor.ComputeDataType;
var
FieldType: SmallInt;
SubType: SmallInt;
Scale: SmallInt;
&Type: Integer;
Types: TDBXDataTypeDescriptionArray;
begin
FieldType := FCursor.Value[FOrdinalFieldType].AsInt16;
SubType := FCursor.Value[FOrdinalSubType].AsInt16;
Scale := FCursor.Value[FOrdinalScale].AsInt16;
&Type := GetIBType(FieldType, SubType, Scale);
Types := FCustomProvider.AllDataTypes;
if (&Type >= 0) and (&Type < Length(Types)) then
FDataType := Types[&Type];
end;
function TDBXFirebirdTypeFilterCursor.ComputeTypeName: UnicodeString;
var
SubType: SmallInt;
begin
if FDataType.DbxDataType <> TDBXDataTypes.BlobType then
Exit(FDataType.TypeName);
SubType := FCursor.Value[FOrdinalSubType].AsInt16;
Result := 'BLOB SUB_TYPE ' + IntToStr(SubType);
end;
function TDBXFirebirdTypeFilterCursor.ComputeUnicode: Boolean;
var
CharSet: SmallInt;
begin
if FCursor.Value[FOrdinalCharSet].IsNull then
Exit(False);
CharSet := FCursor.Value[FOrdinalCharSet].AsInt16;
case CharSet of
TDBXFirebirdCustomMetaDataReader.DefaultCharset:
Result := FCustomProvider.FDefaultCharSetIsUnicode;
TDBXFirebirdCustomMetaDataReader.CharsetUnicodeFss,
TDBXFirebirdCustomMetaDataReader.CharsetSjis208,
TDBXFirebirdCustomMetaDataReader.CharsetEucj208:
Result := True;
else
Result := False;
end;
end;
function TDBXFirebirdTypeFilterCursor.ComputeDefaultValue: UnicodeString;
var
DefaultValue: UnicodeString;
begin
DefaultValue := NullString;
if not FCursor.Value[FOrdinalDefaultValue].IsNull then
begin
DefaultValue := Trim(FCursor.Value[FOrdinalDefaultValue].AsString);
if StringStartsWith(DefaultValue,DefaultStringStart) then
DefaultValue := Copy(DefaultValue,Length(DefaultStringStart)+1,Length(DefaultValue)-(Length(DefaultStringStart)));
end;
Result := DefaultValue;
end;
function TDBXFirebirdTypeFilterCursor.GetIBType(const FieldType: SmallInt; const FieldSubType: SmallInt; const FieldScale: SmallInt): Integer;
begin
// CJL-IB6 -- Decimal/int64 types possible
if FieldScale < 0 then
case FieldType of
TDBXFirebirdTypeFilterCursor.Tibase_const.FBlr_short:
Exit(TDBXFirebirdCustomMetaDataReader.NumericType);
TDBXFirebirdTypeFilterCursor.Tibase_const.FBlr_long:
if FieldSubType = 2 then
Exit(TDBXFirebirdCustomMetaDataReader.DecimalType)
else
Exit(TDBXFirebirdCustomMetaDataReader.NumericType);
TDBXFirebirdTypeFilterCursor.Tibase_const.FBlr_int64:
if FieldSubType = 2 then
Exit(TDBXFirebirdCustomMetaDataReader.DecimalType)
else
Exit(TDBXFirebirdCustomMetaDataReader.NumericType);
TDBXFirebirdTypeFilterCursor.Tibase_const.FBlr_double:
Exit(TDBXFirebirdCustomMetaDataReader.NumericType);
else
end;
// CJL-IB6 -- end
case FieldType of
TDBXFirebirdTypeFilterCursor.Tibase_const.FBlr_short:
Result := TDBXFirebirdCustomMetaDataReader.SmallintType;
TDBXFirebirdTypeFilterCursor.Tibase_const.FBlr_long:
Result := TDBXFirebirdCustomMetaDataReader.IntegerType;
TDBXFirebirdTypeFilterCursor.Tibase_const.FBlr_double,
TDBXFirebirdTypeFilterCursor.Tibase_const.FBlr_d_float:
Result := TDBXFirebirdCustomMetaDataReader.DoubleType;
TDBXFirebirdTypeFilterCursor.Tibase_const.FBlr_float:
Result := TDBXFirebirdCustomMetaDataReader.FloatType;
TDBXFirebirdTypeFilterCursor.Tibase_const.FBlr_text:
Result := TDBXFirebirdCustomMetaDataReader.CharType;
TDBXFirebirdTypeFilterCursor.Tibase_const.FBlr_varying:
Result := TDBXFirebirdCustomMetaDataReader.VarcharType;
TDBXFirebirdTypeFilterCursor.Tibase_const.FBlr_timestamp:
Result := TDBXFirebirdCustomMetaDataReader.TimestampType;
TDBXFirebirdTypeFilterCursor.Tibase_const.FBlr_sql_time:
Result := TDBXFirebirdCustomMetaDataReader.TimeType;
TDBXFirebirdTypeFilterCursor.Tibase_const.FBlr_sql_date:
Result := TDBXFirebirdCustomMetaDataReader.DateType;
TDBXFirebirdTypeFilterCursor.Tibase_const.FBlr_int64:
if FieldSubType = 2 then
Result := TDBXFirebirdCustomMetaDataReader.DecimalType
else if FieldSubType = 1 then
Result := TDBXFirebirdCustomMetaDataReader.NumericType
else
Result := TDBXFirebirdCustomMetaDataReader.BigintType;
261:
Result := TDBXFirebirdCustomMetaDataReader.BlobType;
9:
Result := -1;
else
Result := -1;
end;
end;
// CJL-IB6 added types
// CJL-IB6 end
end.
|
{ ***************************************************************************
Copyright (c) 2016-2018 Kike Pérez
Unit : Quick.ImageFX.Types
Description : Image manipulation with multiple graphic libraries
Author : Kike Pérez
Version : 4.0
Created : 10/04/2013
Modified : 27/03/2018
This file is part of QuickImageFX: https://github.com/exilon/QuickImageFX
***************************************************************************
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.ImageFX.Types;
interface
uses
Classes,
SysUtils,
Vcl.Controls,
Vcl.Graphics,
Vcl.Imaging.pngimage,
Vcl.Imaging.jpeg,
Vcl.Imaging.GIFImg;
const
MinGraphicSize = 44;
DEF_USERAGENT = 'Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
DEF_CONNECTION_TIMEOUT = 60000;
DEF_RESPONSE_TIMEOUT = 60000;
type
TRGB = record
R : Byte;
G : Byte;
B : Byte;
end;
TocvColorEncode = (ceNone,ceRGB,ceBGR, ceGRAY);
TPixelInfo = record
R : Byte;
G : Byte;
B : Byte;
A : Byte;
GV : Byte;
ColorEncode : TocvColorEncode;
EncodeInfo : Byte;
end;
EImageError = class(Exception);
EImageDrawError = class(Exception);
EImageRotationError = class(Exception);
EImageResizeError = class(Exception);
EImageTransformError = class(Exception);
EImageConversionError = class(Exception);
TImageFormat = (ifBMP, ifJPG, ifPNG, ifGIF);
TImageActionResult = (arNone, arAlreadyOptim, arOk, arUnknowFmtType, arUnknowError, arNoOverwrited, arResizeError, arRotateError,
arColorizeError,arConversionError, arFileNotExist, arZeroBytes, arCorruptedData);
TJPGQualityLevel = 1..100;
TPNGCompressionLevel = 0..9;
TScanlineMode = (smHorizontal, smVertical);
TResizeFlags = set of (rfNoMagnify, //not stretch if source image is smaller than target size
rfCenter, //center image if target is bigger
rfFillBorders //if target is bigger fills borders with a color
);
TResizeMode = (rmStretch, //stretch original image to fit target size without preserving original aspect ratio
rmScale, //recalculate width or height target size to preserve original aspect ratio
rmCropToFill, //preserve target aspect ratio cropping original image to fill whole size
rmFitToBounds //resize image to fit max bounds of target size
);
TResamplerMode = (rsAuto, //uses rmArea for downsampling and rmLinear for upsampling
rsGDIStrech, //used only by GDI
rsNearest, //low quality - High performance
rsGR32Draft, //medium quality - High performance (downsampling only)
rsOCVArea, //medium quality - High performance (downsampling only)
rsLinear, // medium quality - Medium performance
rsGR32Kernel, //high quality - Low performance (depends on kernel width)
rsOCVCubic,
rsOCVLanczos4,
rsVAMPBicubic,
rsVAMPLanczos); //high quality - Low performance
TResizeOptions = class
NoMagnify : Boolean;
ResizeMode : TResizeMode;
ResamplerMode : TResamplerMode;
Center : Boolean;
FillBorders : Boolean;
BorderColor : TColor;
SkipSmaller : Boolean; //avoid resize smaller resolution images
end;
THTTPOptions = class
UserAgent : string;
HandleRedirects : Boolean;
MaxRedirects : Integer;
AllowCookies : Boolean;
ConnectionTimeout : Integer;
ResponseTimeout : Integer;
end;
function GCD(a,b : integer):integer;
function Lerp(a, b: Byte; t: Double): Byte;
function MinEx(a, b: Longint): Longint;
function MaxEx(a, b: Longint): Longint;
implementation
function GCD(a,b : integer):integer;
begin
if (b mod a) = 0 then Result := a
else Result := GCD(b, a mod b);
end;
function Lerp(a, b: Byte; t: Double): Byte;
var
tmp: Double;
begin
tmp := t*a + (1-t)*b;
if tmp<0 then result := 0 else
if tmp>255 then result := 255 else
result := Round(tmp);
end;
function MinEx(a, b: Longint): Longint;
begin
if a > b then Result := b
else
Result := a;
end;
function MaxEx(a, b: Longint): Longint;
begin
if a > b then Result := a
else
Result := b;
end;
end.
|
unit Umisc; // SpyroTAS is licensed under WTFPL
interface
uses
Windows, Forms, Classes, SysUtils, Graphics, Math;
// TCustomIntegerArray class:
type
TCustomIntegerArray = class(TObject)
public
procedure SetSize(NewSize: Integer);
function GetSize(): Integer;
procedure ClearFrom(Index: Integer);
procedure Write(Index, Value: Integer);
function Read(Index: Integer): Integer;
function Addr(Index: Integer = 0): PInteger;
procedure Push(Value: Integer);
private
Data: array of Integer; // managed type, no need in destructor
Count: Integer; // user assigned
Size: Integer; // internal allocated
procedure RaiseError(Index: Integer);
end;
type
TCustomIntegerArrays = class(TObject)
constructor Create(Count: Integer);
destructor Destroy(); override;
public
function GetDim(): Integer;
procedure SetSize(NewSize: Integer);
function GetSize(): Integer;
procedure ClearFrom(Index: Integer);
procedure Write(Arr, Index, Value: Integer);
function Read(Arr, Index: Integer): Integer;
function Addr(Arr: Integer; Index: Integer = 0): PInteger;
procedure Assign(Other: TCustomIntegerArrays);
procedure FromStream(Arr: Integer; Values: Integer; Stream: TStream; NoFatal:
Boolean = False);
procedure ToStream(Arr: Integer; Stream: TStream; Last: Integer);
private
procedure RaiseError(Arr, Index: Integer);
private
Data: array of TCustomIntegerArray;
Size: Integer;
Count: Integer;
end;
function Ignores(const a): Pointer; overload;
function Ignores(const a; const b): Pointer; overload;
function Ignores(const a; const b; const c): Pointer; overload;
function Ignores(const a; const b; const c; const d): Pointer; overload;
function Initializes(out a): Pointer;
procedure Report(Caption, Text: string; Hand: HWND); overload;
procedure Report(Caption, Text: string; Form: TForm = nil); overload;
function FormatNumberWithZero(Value: Integer; StrLength: Integer; Zero: Char =
'0'): string;
function PathFixBackslash(const Path: string): string;
function HashCRC(DataPtr: Pointer; DataSize: Integer): Integer;
function TimeToString(Time: TDateTime): string;
function IntegerToBase26(Number, Size: Integer): string;
function PluginTitleFromNameAndVersion(Name: string; version: Integer): string;
function SquaredDistance(X, Y: Integer; Z: Integer = 0): Real;
function SwapWords(Value: Integer): Integer;
procedure BitmapDataAndSize(Bitmap: TBitmap; out Data: PChar; out Size: Integer);
function AnyBaseToInt(Text: string; Base: Integer): Int64;
function StringToRamOffset(Text: string): Integer;
function IsOurWindow(Wind: HWND): Boolean;
function IsAbsolutePath(FileName: string): Boolean;
procedure SaveBitmapToPng(Bitmap: TBitmap; PngFilename: string; Compression: Integer);
procedure LoadPngAsBitmap(Bitmap: TBitmap; PngFilename: string);
function ArrayCalc(Start: PInteger; Size: Integer; out Dev: Double): Double;
function HashFile(Path: string): Integer;
procedure CryptData(Start: PInteger; Words: Integer; Key: Integer; UseShift: Boolean);
function Print8087CW(): string;
{$IFDEF SpyroTAS_no_Libs}
const
PngIsAvailable = False;
{$ELSE}
const
PngIsAvailable = True;
{$ENDIF}
implementation
uses
DateUtils, StrUtils, Uglob
{$IFNDEF SpyroTAS_no_Libs}
, PNGImage
{$ENDIF}
;
// one entry point for errors:
procedure TCustomIntegerArray.RaiseError(Index: Integer);
begin
raise Exception.Create('TCustomIntegerArray wrong index (' + IntToStr(Index) + ')');
end;
// zerofill from target index till available memory:
procedure TCustomIntegerArray.ClearFrom(Index: Integer);
begin
if Size <= 0 then // nothing to clear
Exit;
if (Index < 0) or (Index > Size) then // if called with wrong index
RaiseError(Index);
FillChar(Addr(Index)^, (Size - Index) * SizeOf(Integer), 0); // get the tail
end;
// change length of array;
procedure TCustomIntegerArray.SetSize(NewSize: Integer);
const
MaxSize: Integer = $0FFFFFFF; // hard limit ~1Gb
var
OldCount: Integer;
begin
if NewSize < 0 then // protection
RaiseError(NewSize);
if NewSize > MaxSize then
NewSize := MaxSize;
OldCount := Count; // don't forget old
Size := (NewSize + 16) * 2; // add overhead
SetLength(Data, Size + 64); // resize
Count := NewSize;
if OldCount < Size then // if became larger
ClearFrom(OldCount); // clear new memory
end;
// simple getter or length:
function TCustomIntegerArray.GetSize(): Integer;
begin
Result := Count; // public Size, not internal
end;
// set new value, but array will grow automatically if next index was pushed:
procedure TCustomIntegerArray.Write(Index, Value: Integer);
begin
if (Index < 0) or (Index > Count) then
RaiseError(Index); // don't allow to write at arbitrary index, only sequental
if Index >= Size then
SetSize(Index); // resize memory
if Index = Count then
Inc(Count); // increment user length
Data[Index] := Value;
end;
// get from array:
function TCustomIntegerArray.Read(Index: Integer): Integer;
begin
if (Index < 0) or (Index > Count) then
RaiseError(Index); // don't allow resizing at reads
Result := Data[Index];
end;
// retrieve a pointer to raw data:
function TCustomIntegerArray.Addr(Index: Integer = 0): PInteger;
begin
if (Index < 0) or (Index > Size) then
RaiseError(Index); // like in Read()
Result := PInteger(@Data[Index]);
end;
procedure TCustomIntegerArray.Push(Value: Integer);
begin
Write(Count, Value);
end;
// for ignoring arguments, to make Lazarus silent:
function Ignores(const a): Pointer; overload;
begin
Result := @a;
end;
function Ignores(const a; const b): Pointer; overload;
begin
Ignores(a);
Result := Ignores(b);
end;
function Ignores(const a; const b; const c): Pointer; overload;
begin
Ignores(a, b);
Result := Ignores(c);
end;
function Ignores(const a; const b; const c; const d): Pointer; overload;
begin
Ignores(a, b, c);
Result := Ignores(d);
end;
function Initializes(out a): Pointer;
begin
Result := @a;
end;
//TODO
procedure Report(Caption, Text: string; Hand: HWND); overload;
begin
if GuiClosing then
Exit;
Caption := Caption + #0#0#0#0;
Text := Text + #0#0#0#0;
MessageBox(Hand, PChar(Text), PChar(Caption), MB_SYSTEMMODAL);
end;
procedure Report(Caption, Text: string; Form: TForm = nil); overload;
begin
if Form = nil then
Report(Caption, Text, 0)
else
Report(Caption, Text, Form.Handle);
end;
// get hash of data, Size must be dword-aligned:
function HashCRC(DataPtr: Pointer; DataSize: Integer): Integer;
const
CRC32Table: array[0..255] of Cardinal = ($00000000, $77073096, $ee0e612c,
$990951ba, $076dc419, $706af48f, $e963a535, $9e6495a3, $0edb8832, $79dcb8a4,
$e0d5e91e, $97d2d988, $09b64c2b, $7eb17cbd, $e7b82d07, $90bf1d91, $1db71064,
$6ab020f2, $f3b97148, $84be41de, $1adad47d, $6ddde4eb, $f4d4b551, $83d385c7,
$136c9856, $646ba8c0, $fd62f97a, $8a65c9ec, $14015c4f, $63066cd9, $fa0f3d63,
$8d080df5, $3b6e20c8, $4c69105e, $d56041e4, $a2677172, $3c03e4d1, $4b04d447,
$d20d85fd, $a50ab56b, $35b5a8fa, $42b2986c, $dbbbc9d6, $acbcf940, $32d86ce3,
$45df5c75, $dcd60dcf, $abd13d59, $26d930ac, $51de003a, $c8d75180, $bfd06116,
$21b4f4b5, $56b3c423, $cfba9599, $b8bda50f, $2802b89e, $5f058808, $c60cd9b2,
$b10be924, $2f6f7c87, $58684c11, $c1611dab, $b6662d3d, $76dc4190, $01db7106,
$98d220bc, $efd5102a, $71b18589, $06b6b51f, $9fbfe4a5, $e8b8d433, $7807c9a2,
$0f00f934, $9609a88e, $e10e9818, $7f6a0dbb, $086d3d2d, $91646c97, $e6635c01,
$6b6b51f4, $1c6c6162, $856530d8, $f262004e, $6c0695ed, $1b01a57b, $8208f4c1,
$f50fc457, $65b0d9c6, $12b7e950, $8bbeb8ea, $fcb9887c, $62dd1ddf, $15da2d49,
$8cd37cf3, $fbd44c65, $4db26158, $3ab551ce, $a3bc0074, $d4bb30e2, $4adfa541,
$3dd895d7, $a4d1c46d, $d3d6f4fb, $4369e96a, $346ed9fc, $ad678846, $da60b8d0,
$44042d73, $33031de5, $aa0a4c5f, $dd0d7cc9, $5005713c, $270241aa, $be0b1010,
$c90c2086, $5768b525, $206f85b3, $b966d409, $ce61e49f, $5edef90e, $29d9c998,
$b0d09822, $c7d7a8b4, $59b33d17, $2eb40d81, $b7bd5c3b, $c0ba6cad, $edb88320,
$9abfb3b6, $03b6e20c, $74b1d29a, $ead54739, $9dd277af, $04db2615, $73dc1683,
$e3630b12, $94643b84, $0d6d6a3e, $7a6a5aa8, $e40ecf0b, $9309ff9d, $0a00ae27,
$7d079eb1, $f00f9344, $8708a3d2, $1e01f268, $6906c2fe, $f762575d, $806567cb,
$196c3671, $6e6b06e7, $fed41b76, $89d32be0, $10da7a5a, $67dd4acc, $f9b9df6f,
$8ebeeff9, $17b7be43, $60b08ed5, $d6d6a3e8, $a1d1937e, $38d8c2c4, $4fdff252,
$d1bb67f1, $a6bc5767, $3fb506dd, $48b2364b, $d80d2bda, $af0a1b4c, $36034af6,
$41047a60, $df60efc3, $a867df55, $316e8eef, $4669be79, $cb61b38c, $bc66831a,
$256fd2a0, $5268e236, $cc0c7795, $bb0b4703, $220216b9, $5505262f, $c5ba3bbe,
$b2bd0b28, $2bb45a92, $5cb36a04, $c2d7ffa7, $b5d0cf31, $2cd99e8b, $5bdeae1d,
$9b64c2b0, $ec63f226, $756aa39c, $026d930a, $9c0906a9, $eb0e363f, $72076785,
$05005713, $95bf4a82, $e2b87a14, $7bb12bae, $0cb61b38, $92d28e9b, $e5d5be0d,
$7cdcefb7, $0bdbdf21, $86d3d2d4, $f1d4e242, $68ddb3f8, $1fda836e, $81be16cd,
$f6b9265b, $6fb077e1, $18b74777, $88085ae6, $ff0f6a70, $66063bca, $11010b5c,
$8f659eff, $f862ae69, $616bffd3, $166ccf45, $a00ae278, $d70dd2ee, $4e048354,
$3903b3c2, $a7672661, $d06016f7, $4969474d, $3e6e77db, $aed16a4a, $d9d65adc,
$40df0b66, $37d83bf0, $a9bcae53, $debb9ec5, $47b2cf7f, $30b5ffe9, $bdbdf21c,
$cabac28a, $53b39330, $24b4a3a6, $bad03605, $cdd70693, $54de5729, $23d967bf,
$b3667a2e, $c4614ab8, $5d681b02, $2a6f2b94, $b40bbe37, $c30c8ea1, $5a05df1b,
$2d02ef8d);
var
EndOfData, Source: PChar;
Value: Integer;
begin
Result := -1; // $FFFFFFFF
Source := PChar(DataPtr);
EndOfData := Source + (DataSize and not 3); // mod 4
while Source < EndOfData do
begin
Value := PInteger(Source)^; // do for each byte:
Result := (Result shr 8) xor Integer(CRC32Table[(Result xor (Value and 255))
and $FF]);
Value := Value shr 8;
Result := (Result shr 8) xor Integer(CRC32Table[(Result xor (Value and 255))
and $FF]);
Value := Value shr 8;
Result := (Result shr 8) xor Integer(CRC32Table[(Result xor (Value and 255))
and $FF]);
Value := Value shr 8;
Result := (Result shr 8) xor Integer(CRC32Table[(Result xor (Value and 255))
and $FF]);
Inc(Source, 4);
end;
Result := Result xor - 1;
end;
// represent a number as a letter string:
function IntegerToBase26(Number, Size: Integer): string;
var
Modulo: Integer;
begin
Result := StringOfChar('A', Size); // pad "zeroes" from left
repeat
if Size = 0 then // need more space
begin
Size := 1;
Result := '_' + Result; // one digit
end;
Modulo := Number mod 26;
Result[Size] := Chr(Ord('A') + Modulo); // letter
Number := Number div 26;
Dec(Size); // next position
until Number = 0;
end;
// encode timestamp to alphanumeric:
function TimeToString(Time: TDateTime): string;
begin
Result := IntegerToBase26(DateTimeToUnix(Time) - DateTimeToUnix(EncodeDate(2017,
1, 1)), 6); // count from 2017 year to get shorter strings
end;
// $12345678 -> $56781234
function SwapWords(Value: Integer): Integer;
begin
Result := (Value shl 16) or (Value shr 16);
end;
// returns 2D or 3D distance without sqrt():
function SquaredDistance(X, Y: Integer; Z: Integer = 0): Real;
begin
Result := X * X + Y * Y + Z * Z; // use Real to ensure not overflow
end;
// pad a value with zeroes from left to desired length
function FormatNumberWithZero(Value: Integer; StrLength: Integer; Zero: Char =
'0'): string;
begin
Result := RightStr(StringOfChar(Zero, StrLength) + IntToStr(Value), StrLength);
end;
// name in ePSXe's manner:
function PluginTitleFromNameAndVersion(Name: string; version: Integer): string;
begin
Result := Name + ' ' + IntToStr(((version shr 8) and 255)) + '.' + IntToStr((version
and 255));
end;
// fixes a directory name to always have "\" at the end:
// ( also replaces "/", "\\" and "\.\" to "\")
function PathFixBackslash(const Path: string): string;
var
Share: Boolean;
begin
Share := False;
Result := Trim(StringReplace(Path, '/', '\', [rfReplaceAll]));
while (Result <> '') and (Result[Length(Result)] = '\') do
Delete(Result, Length(Result), 1);
if Result = '' then
Exit;
Result := Result + '\';
if Result[1] = '\' then
begin
Share := True;
Delete(Result, 1, 1);
end;
Result := StringReplace(Result, '\.\', '\', [rfReplaceAll]);
Result := StringReplace(Result, '\\', '\', [rfReplaceAll]);
if Share then
Result := '\' + Result;
end;
procedure BitmapDataAndSize(Bitmap: TBitmap; out Data: PChar; out Size: Integer);
var
A0, A1, Ah: PChar;
H: Integer;
begin
Data := nil;
Size := 0;
if (Bitmap = nil) or (Bitmap.Height < 2) then
Exit;
H := Bitmap.Height;
A0 := Bitmap.{%H-}ScanLine[0];
A1 := Bitmap.{%H-}ScanLine[1];
Ah := Bitmap.{%H-}ScanLine[H - 1];
if A0 < Ah then
begin
Data := A0;
Size := (A1 - A0) * H;
end
else
begin
Data := Ah;
Size := (A0 - A1) * H;
end;
end;
function AnyBaseToInt(Text: string; Base: Integer): Int64;
var
Index, Value: Integer;
begin
Result := 0;
for Index := 1 to Length(Text) do
begin
Value := Ord(Text[Index]) - Ord('0');
if Value > 9 then
Value := 10 + Ord(Text[Index]) - Ord('A');
if (Value >= 0) and (Value < Base) then
Result := Result * Base + Value
else
begin
Result := -1;
Exit;
end;
end;
end;
function StringToRamOffset(Text: string): Integer;
var
Line: string;
Size, Index: Integer;
Ch: Byte;
begin
Result := -1;
Text := UpperCase(Trim(Text));
SetLength(Line, Length(Text));
Size := 0;
for Index := 1 to Length(Text) do
begin
Ch := Ord(Text[Index]);
if (Ch >= Ord('A')) and (Ch <= Ord('Z')) or ((Ch >= Ord('0')) and (Ch <= Ord
('9'))) then
begin
Inc(Size);
Line[Size] := Text[Index];
end;
end;
if Size = 0 then
Exit;
if Line[1] = '0' then
if Size > 1 then
Delete(Line, 1, 1)
else
begin
Result := 0;
Exit;
end;
case Line[1] of
'X':
Result := AnyBaseToInt(Copy(Line, 2, Length(Line)), 16);
'O':
Result := AnyBaseToInt(Copy(Line, 2, Length(Line)), 8);
'B':
Result := AnyBaseToInt(Copy(Line, 2, Length(Line)), 2);
else
case Line[Length(Line)] of
'H':
Result := AnyBaseToInt(Copy(Line, 1, Length(Line) - 1), 16);
'O':
Result := AnyBaseToInt(Copy(Line, 1, Length(Line) - 1), 8);
'B':
Result := AnyBaseToInt(Copy(Line, 1, Length(Line) - 1), 2);
else
Result := AnyBaseToInt(Line, 10)
end;
end;
end;
function IsOurWindow(Wind: HWND): Boolean;
var
Pid: Cardinal;
begin
Result := False;
if (Wind = 0) or (Wind = INVALID_HANDLE_VALUE) then
Exit;
if not IsWindow(Wind) then
Exit;
Pid := 0;
GetWindowThreadProcessId(Wind, Pid);
Result := (Pid = GetCurrentProcessId());
end;
function IsAbsolutePath(FileName: string): Boolean;
begin
Result := False;
FileName := PathFixBackslash(FileName);
if Length(FileName) < 3 then
Exit;
if (FileName[2] = ':') or ((FileName[1] = '\') and (FileName[2] = '\')) then
Result := True;
end;
{$IFDEF SpyroTAS_no_Libs}
procedure SaveBitmapToPng(Bitmap: TBitmap; PngFilename: string; Compression: Integer);
begin
Ignores(Bitmap, PngFilename, Compression);
end;
procedure LoadPngAsBitmap(Bitmap: TBitmap; PngFilename: string);
begin
Ignores(Bitmap, PngFilename);
end;
{$ELSE}
procedure SaveBitmapToPng(Bitmap: TBitmap; PngFilename: string; Compression: Integer);
var
Png: TPNGObject;
begin
DeleteFile(PngFilename);
Png := TPNGObject.Create{%H-};
Png.Assign(Bitmap);
Png.CompressionLevel := Compression;
Png.SaveToFile(PngFilename);
Png.Free();
end;
procedure LoadPngAsBitmap(Bitmap: TBitmap; PngFilename: string);
var
Png: TPNGObject;
begin
Png := TPNGObject.Create{%H-};
Png.LoadFromFile(PngFilename);
if (Png.Width mod 4) = 0 then // choose bit depth
Bitmap.PixelFormat := pf24bit
else
Bitmap.PixelFormat := pf32bit;
Bitmap.Assign(Png);
Png.Free();
end;
{$ENDIF}
constructor TCustomIntegerArrays.Create(Count: Integer);
var
Arr: Integer;
begin
inherited Create();
if Count > 0 then
begin
Size := Count;
SetLength(Data, Size);
Dec(Size);
for Arr := 0 to Size do
Data[Arr] := TCustomIntegerArray.Create();
SetSize(1);
end;
end;
destructor TCustomIntegerArrays.Destroy();
var
Arr: Integer;
begin
for Arr := 0 to Size do
Data[Arr].Free();
end;
function TCustomIntegerArrays.GetDim(): Integer;
begin
Result := Size + 1;
end;
procedure TCustomIntegerArrays.SetSize(NewSize: Integer);
var
Arr: Integer;
begin
Count := NewSize;
for Arr := 0 to Size do
Data[Arr].SetSize(NewSize);
end;
procedure TCustomIntegerArrays.RaiseError(Arr, Index: Integer);
begin
raise Exception.Create('TCustomIntegerArrays wrong index (' + IntToStr(Arr) +
',' + IntToStr(Index) + ')');
end;
function TCustomIntegerArrays.GetSize(): Integer;
begin
Result := Count;
end;
procedure TCustomIntegerArrays.ClearFrom(Index: Integer);
var
Arr: Integer;
begin
for Arr := 0 to Size do
Data[Arr].ClearFrom(Index);
end;
procedure TCustomIntegerArrays.Write(Arr, Index, Value: Integer);
var
I: Integer;
begin
if (Arr < 0) or (Arr > Size) or (Index < 0) or (Index > Count) then
RaiseError(Arr, Index);
if Index = Count then
begin
Inc(Count);
for I := 0 to Size do
Data[I].Write(Index, 0);
end;
Data[Arr].Write(Index, Value);
end;
function TCustomIntegerArrays.Read(Arr, Index: Integer): Integer;
begin
if (Arr < 0) or (Arr > Size) or (Index < 0) or (Index > Count) then
RaiseError(Arr, Index);
Result := Data[Arr].Read(Index);
end;
function TCustomIntegerArrays.Addr(Arr: Integer; Index: Integer = 0): PInteger;
begin
if (Arr < 0) or (Arr > Size) then
RaiseError(Arr, Index);
Result := Data[Arr].Addr(Index);
end;
procedure TCustomIntegerArrays.Assign(Other: TCustomIntegerArrays);
var
Arr, Cnt: Integer;
begin
SetSize(0);
Size := Other.GetDim();
SetLength(Data, Size);
if Size > 0 then
begin
Dec(Size);
Cnt := Other.GetSize();
SetSize(Cnt);
if Cnt > 0 then
for Arr := 0 to Size do
CopyMemory(Addr(Arr), Other.Addr(Arr), Cnt * 4);
end;
end;
procedure TCustomIntegerArrays.FromStream(Arr: Integer; Values: Integer; Stream:
TStream; NoFatal: Boolean = False);
begin
if (Arr < 0) or (Arr > Size) then
RaiseError(Arr, 0);
if NoFatal then
begin
Data[Arr].ClearFrom(0);
Stream.Read(Data[Arr].Addr()^, Values * 4);
end
else
Stream.ReadBuffer(Data[Arr].Addr()^, Values * 4);
end;
procedure TCustomIntegerArrays.ToStream(Arr: Integer; Stream: TStream; Last: Integer);
begin
if (Arr < 0) or (Arr > Size) or (Last < 0) or (Last > Count) then
RaiseError(Arr, Size);
Stream.WriteBuffer(Data[Arr].Addr()^, Last * 4);
end;
function ArrayCalc(Start: PInteger; Size: Integer; out Dev: Double): Double;
var
s, m: Integer;
a: PInteger;
r: Real;
begin
Result := 0;
if Size < 0 then
Exit;
s := Size;
a := Start;
m := 0;
while s > 0 do
begin
Inc(m, a^);
Inc(a);
Dec(s);
end;
s := Size;
a := Start;
Result := m / s;
Dev := 0;
while s > 0 do
begin
r := a^ - Result;
Dev := Dev + r * r;
Inc(a);
Dec(s);
end;
Dev := Sqrt(Dev / Size);
end;
function HashFile(Path: string): Integer;
var
Stream: TFileStream;
Size: Integer;
Data: PChar;
begin
Result := 0;
if not FileExists(Path) then
Exit;
Stream := nil;
Data := nil;
try
Stream := TFileStream.Create(Path, fmOpenRead or fmShareDenyNone);
Size := Stream.Size;
if (Size < 16) or (Size > 16 * 1024 * 1024) then
Abort;
GetMem(Data, Size + 4);
ZeroMemory(Data, Size + 4);
Stream.ReadBuffer(Data^, Size);
except
if Data = nil then
FreeMem(Data);
Stream.Free();
Exit;
end;
Stream.Free();
Result := HashCRC(Data, Size) + Size;
if Result = 0 then
Dec(Result, Size);
FreeMem(Data);
end;
procedure CryptData(Start: PInteger; Words: Integer; Key: Integer; UseShift: Boolean);
var
Seed: Integer;
begin
if UseShift then
Seed := Key
else
Seed := 0;
while Words > 0 do
begin
if UseShift then
begin
Seed := Seed xor (Seed shl 13);
Seed := Seed xor (Seed shr 17);
Seed := Seed xor (Seed shl 5);
end;
Start^ := Start^ xor Seed xor Key;
Inc(Start);
Dec(Words);
end;
end;
function Print8087CW(): string;
var
m: TFPUExceptionMask;
p: TFPUPrecisionMode;
r: TFPURoundingMode;
begin
Result := '8087CW(';
m := GetExceptionMask();
Result := Result + 'MASK:';
if exInvalidOp in m then
Result := Result + 'InvalidOp,';
if exDenormalized in m then
Result := Result + 'Denormalized,';
if exZeroDivide in m then
Result := Result + 'ZeroDivide,';
if exOverflow in m then
Result := Result + 'Overflow,';
if exUnderflow in m then
Result := Result + 'Underflow,';
if exPrecision in m then
Result := Result + 'Precision,';
p := GetPrecisionMode();
Result := Result + ' PREC:';
case p of
pmSingle:
Result := Result + 'Single';
pmReserved:
Result := Result + 'Reserved';
pmDouble:
Result := Result + 'Double';
pmExtended:
Result := Result + 'Extended';
end;
r := GetRoundMode();
Result := Result + ', ROUND:';
case r of
rmNearest:
Result := Result + 'Nearest';
rmDown:
Result := Result + 'Down';
rmUp:
Result := Result + 'Up';
rmTruncate:
Result := Result + 'Truncate';
end;
Result := Result + ')';
end;
end.
// EOF
|
unit CardsUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls, Menus, MMSystem, Buttons;
var
CardHeight, CardWidth, CardRadius: integer;
AllCardBitmaps: TBitmap;
CardBitmap: TBitmap;
const
CARD_COUNT_ON_ROW = 9;
type
TCardId = byte;
TSet36 = set of 1 .. 36;
TCardArray = array [1 .. 36] of TCardId;
TCardImg = class(TButton)
private
IsFocused: boolean;
Canvas: TCanvas;
procedure CNDrawItem(var Msg: TWMDrawItem); message cn_DrawItem;
procedure WMLButtonDblClk(var Message: TWMLButtonDblClk); message wm_LButtonDblClk;
protected
procedure CreateWnd; override;
procedure CreateParams(var Params: TCreateParams); override;
procedure SetButtonStyle(ADefault: boolean); override;
public
CardNumber: byte;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure RefreshRegion;
end;
TCardImages = array [1 .. 36] of TCardImg;
procedure DrawCard(x, y: integer; cardId: byte; Canvas: TCanvas);
implementation
procedure DisableVclStyles(Control: TControl; const ClassToIgnore: string);
var
i: integer;
begin
if Control = nil then
Exit;
if not Control.ClassNameIs(ClassToIgnore) then
Control.StyleElements := [];
if Control is TWinControl then
for i := 0 to TWinControl(Control).ControlCount - 1 do
DisableVclStyles(TWinControl(Control).Controls[i], ClassToIgnore);
end;
procedure DrawCard(x, y: integer; cardId: byte; Canvas: TCanvas);
var
i, j: byte;
begin
i := cardId mod 4;
j := (cardId - 1) div 4;
CardBitmap.Canvas.CopyRect(Rect(0, 0, CardWidth, CardHeight), AllCardBitmaps.Canvas,
Rect(j * CardWidth, i * CardHeight, (j + 1) * CardWidth, (i + 1) * CardHeight));
Canvas.Draw(x, y, CardBitmap);
end;
procedure TCardImg.CNDrawItem(var Msg: TWMDrawItem);
begin
Canvas.Handle := Msg.DrawItemStruct^.hDC;
DrawCard(0, 0, CardNumber, Canvas);
if Focused then
Canvas.DrawFocusRect(Rect(3, 3, CardWidth - 3, CardHeight - 3));
end;
constructor TCardImg.Create(AOwner: TComponent);
begin
inherited;
//For ability to draw on surface
DisableVclStyles(self, 'TButton');
Canvas := TCanvas.Create;
end;
procedure TCardImg.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
with Params do
Style := Style or BS_OWNERDRAW;
end;
procedure TCardImg.CreateWnd;
begin
inherited;
RefreshRegion;
end;
destructor TCardImg.Destroy;
begin
inherited;
Canvas.Free;
end;
procedure TCardImg.RefreshRegion;
var
CardRegion: THandle;
begin
SetBounds(Left, Top, CardWidth, CardHeight);
CardRegion := CreateRoundRectRgn(0, -1, CardWidth + 1, CardHeight + 1, CardRadius, CardRadius);
SetWindowRgn(Handle, CardRegion, true);
end;
procedure TCardImg.SetButtonStyle(ADefault: boolean);
begin
if ADefault <> IsFocused then
begin
IsFocused := ADefault;
Invalidate;
end;
end;
procedure TCardImg.WMLButtonDblClk(var Message: TWMLButtonDblClk);
begin
Perform(WM_LBUTTONDOWN, Message.Keys, LongInt(Message.Pos));
end;
end.
|
unit UImplementacao;
interface
uses
InvokeRegistry;
type
Iinterface = interface(IInvokable)
{ id da interface gerada pelo delphi CTRL + SHIFT + G}
['{0E756257-0A15-47C2-8EE2-A172A60E5B2D}']
{ param param type return deixa disponivel para o ws}
function somar(valorA, valorB: Integer) : Integer; stdcall;
end;
{ herda implementa}
Timplementacao = class(TInvokableClass, IInterface)
{ CTRL + SHIFT + C cria a funcao}
public function somar(valorA, valorB : Integer) : Integer; stdcall;
end;
implementation
function Timplementacao.somar(valorA, valorB: Integer): Integer;
begin
Result := valorA + valorB;
end;
{ ao inicializar a classe registra a interface e a implementacao }
initialization
InvRegistry.RegisterInvokableClass(Timplementacao);
InvRegistry.RegisterInterface(TypeInfo(Iinterface));
end.
|
unit TestSpaceBeforeColon;
{ AFS October 2008
Test the option for spacing before colon
}
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is TestSpaceBeforeColon, released October 2008.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 2008 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
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.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
uses
TestFrameWork,
BaseTestProcess,
SettingsTypes;
type
TTestSpaceBeforeColon = class(TBaseTestProcess)
private
fiSaveMaxSpaces: integer;
feSaveOperatorSetting: TTriOptionStyle;
fiSaveSpacesBeforeColonVar: integer;
fiSaveSpacesBeforeColonConst: integer;
fiSaveSpacesBeforeColonParam: integer;
fiSaveSpacesBeforeColonFn: integer;
fiSaveSpacesBeforeColonClassVar: integer;
fiSaveSpacesBeforeColonRecordField: integer;
fiSaveSpacesBeforeColonCaseLabel: integer;
fiSaveSpacesBeforeColonLabel: integer;
fiSaveSpacesBeforeColonInGeneric: integer;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestNoSpaceBeforeColonFnRemove;
procedure TestNoSpaceBeforeColonFnSame;
procedure TestSingleSpaceBeforeColonFnAdd;
procedure TestSingleSpaceBeforeColonFnSame;
procedure TestNoSpaceBeforeColonVarRemove;
procedure TestNoSpaceBeforeColonVarSame;
procedure TestSingleSpaceBeforeColonVarAdd;
procedure TestSingleSpaceBeforeColonVarSame;
procedure TestNoSpaceBeforeColonConstRemove;
procedure TestNoSpaceBeforeColonConstSame;
procedure TestSingleSpaceBeforeColonConstAdd;
procedure TestSingleSpaceBeforeColonConstSame;
end;
implementation
uses JclAnsiStrings,
JcfSettings,
SpaceBeforeColon;
procedure TTestSpaceBeforeColon.Setup;
begin
inherited;
fiSaveMaxSpaces := JcfFormatSettings.Spaces.MaxSpacesInCode;
feSaveOperatorSetting := JcfFormatSettings.Spaces.SpaceForOperator;
fiSaveSpacesBeforeColonVar := JcfFormatSettings.Spaces.SpacesBeforeColonVar;
fiSaveSpacesBeforeColonConst := JcfFormatSettings.Spaces.SpacesBeforeColonConst;
fiSaveSpacesBeforeColonParam := JcfFormatSettings.Spaces.SpacesBeforeColonParam;
fiSaveSpacesBeforeColonFn := JcfFormatSettings.Spaces.SpacesBeforeColonFn;
fiSaveSpacesBeforeColonClassVar := JcfFormatSettings.Spaces.SpacesBeforeColonClassVar;
fiSaveSpacesBeforeColonRecordField := JcfFormatSettings.Spaces.SpacesBeforeColonRecordField;
fiSaveSpacesBeforeColonCaseLabel := JcfFormatSettings.Spaces.SpacesBeforeColonCaseLabel;
fiSaveSpacesBeforeColonLabel := JcfFormatSettings.Spaces.SpacesBeforeColonLabel;
fiSaveSpacesBeforeColonInGeneric := JcfFormatSettings.Spaces.SpacesBeforeColonInGeneric;
end;
procedure TTestSpaceBeforeColon.Teardown;
begin
inherited;
JcfFormatSettings.Spaces.MaxSpacesInCode := fiSaveMaxSpaces;
JcfFormatSettings.Spaces.SpaceForOperator := feSaveOperatorSetting;
JcfFormatSettings.Spaces.SpacesBeforeColonVar := fiSaveSpacesBeforeColonVar;
JcfFormatSettings.Spaces.SpacesBeforeColonConst := fiSaveSpacesBeforeColonConst;
JcfFormatSettings.Spaces.SpacesBeforeColonParam := fiSaveSpacesBeforeColonParam;
JcfFormatSettings.Spaces.SpacesBeforeColonFn := fiSaveSpacesBeforeColonFn;
JcfFormatSettings.Spaces.SpacesBeforeColonClassVar := fiSaveSpacesBeforeColonClassVar;
JcfFormatSettings.Spaces.SpacesBeforeColonRecordField := fiSaveSpacesBeforeColonRecordField;
JcfFormatSettings.Spaces.SpacesBeforeColonCaseLabel := fiSaveSpacesBeforeColonCaseLabel;
JcfFormatSettings.Spaces.SpacesBeforeColonLabel := fiSaveSpacesBeforeColonLabel;
JcfFormatSettings.Spaces.SpacesBeforeColonInGeneric := fiSaveSpacesBeforeColonInGeneric;
end;
procedure TTestSpaceBeforeColon.TestNoSpaceBeforeColonFnRemove;
const
IN_UNIT_TEXT = UNIT_HEADER + ' function foo : integer; begin result := 2; end; ' +
UNIT_FOOTER;
OUT_UNIT_TEXT = UNIT_HEADER + ' function foo: integer; begin result := 2; end; ' +
UNIT_FOOTER;
begin
JcfFormatSettings.Spaces.SpacesBeforeColonFn := 0;
TestProcessResult(TSpaceBeforeColon, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSpaceBeforeColon.TestNoSpaceBeforeColonFnSame;
const
IN_UNIT_TEXT = UNIT_HEADER + ' function foo: integer; begin result := 2; end; ' +
UNIT_FOOTER;
OUT_UNIT_TEXT = UNIT_HEADER + ' function foo: integer; begin result := 2; end; ' +
UNIT_FOOTER;
begin
JcfFormatSettings.Spaces.SpacesBeforeColonFn := 0;
TestProcessResult(TSpaceBeforeColon, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSpaceBeforeColon.TestSingleSpaceBeforeColonFnAdd;
const
//JcfSettings.SetSpaces.SpacesBeforeColonFn := 0;
IN_UNIT_TEXT = UNIT_HEADER + ' function foo: integer; begin result := 2; end; ' +
UNIT_FOOTER;
OUT_UNIT_TEXT = UNIT_HEADER + ' function foo : integer; begin result := 2; end; ' +
UNIT_FOOTER;
begin
JcfFormatSettings.Spaces.SpacesBeforeColonFn := 1;
TestProcessResult(TSpaceBeforeColon, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSpaceBeforeColon.TestSingleSpaceBeforeColonFnSame;
const
//JcfSettings.SetSpaces.SpacesBeforeColonFn := 0;
IN_UNIT_TEXT = UNIT_HEADER + ' function foo : integer; begin result := 2; end; ' +
UNIT_FOOTER;
OUT_UNIT_TEXT = UNIT_HEADER + ' function foo : integer; begin result := 2; end; ' +
UNIT_FOOTER;
begin
JcfFormatSettings.Spaces.SpacesBeforeColonFn := 1;
TestProcessResult(TSpaceBeforeColon, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSpaceBeforeColon.TestNoSpaceBeforeColonVarRemove;
const
IN_UNIT_TEXT = UNIT_HEADER + ' var foo : integer;' +
UNIT_FOOTER;
OUT_UNIT_TEXT = UNIT_HEADER + ' var foo: integer;' +
UNIT_FOOTER;
begin
JcfFormatSettings.Spaces.SpacesBeforeColonVar := 0;
TestProcessResult(TSpaceBeforeColon, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSpaceBeforeColon.TestNoSpaceBeforeColonVarSame;
const
IN_UNIT_TEXT = UNIT_HEADER + ' var foo: integer;' +
UNIT_FOOTER;
OUT_UNIT_TEXT = UNIT_HEADER + ' var foo: integer;' +
UNIT_FOOTER;
begin
JcfFormatSettings.Spaces.SpacesBeforeColonVar := 0;
TestProcessResult(TSpaceBeforeColon, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSpaceBeforeColon.TestSingleSpaceBeforeColonVarAdd;
const
IN_UNIT_TEXT = UNIT_HEADER + ' var foo: integer;' +
UNIT_FOOTER;
OUT_UNIT_TEXT = UNIT_HEADER + ' var foo : integer;' +
UNIT_FOOTER;
begin
JcfFormatSettings.Spaces.SpacesBeforeColonVar := 1;
TestProcessResult(TSpaceBeforeColon, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSpaceBeforeColon.TestSingleSpaceBeforeColonVarSame;
const
IN_UNIT_TEXT = UNIT_HEADER + ' var foo : integer;' +
UNIT_FOOTER;
OUT_UNIT_TEXT = UNIT_HEADER + ' var foo : integer;' +
UNIT_FOOTER;
begin
JcfFormatSettings.Spaces.SpacesBeforeColonVar := 1;
TestProcessResult(TSpaceBeforeColon, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSpaceBeforeColon.TestNoSpaceBeforeColonConstRemove;
const
IN_UNIT_TEXT = UNIT_HEADER + ' const foo : integer = 3;' +
UNIT_FOOTER;
OUT_UNIT_TEXT = UNIT_HEADER + ' const foo: integer = 3;' +
UNIT_FOOTER;
begin
JcfFormatSettings.Spaces.SpacesBeforeColonConst := 0;
TestProcessResult(TSpaceBeforeColon, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSpaceBeforeColon.TestNoSpaceBeforeColonConstSame;
const
IN_UNIT_TEXT = UNIT_HEADER + ' const foo: integer = 3;' +
UNIT_FOOTER;
OUT_UNIT_TEXT = UNIT_HEADER + ' const foo: integer = 3;' +
UNIT_FOOTER;
begin
JcfFormatSettings.Spaces.SpacesBeforeColonConst := 0;
TestProcessResult(TSpaceBeforeColon, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSpaceBeforeColon.TestSingleSpaceBeforeColonConstAdd;
const
IN_UNIT_TEXT = UNIT_HEADER + ' const foo: integer = 3;' +
UNIT_FOOTER;
OUT_UNIT_TEXT = UNIT_HEADER + ' const foo : integer = 3;' +
UNIT_FOOTER;
begin
JcfFormatSettings.Spaces.SpacesBeforeColonConst := 1;
TestProcessResult(TSpaceBeforeColon, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestSpaceBeforeColon.TestSingleSpaceBeforeColonConstSame;
const
IN_UNIT_TEXT = UNIT_HEADER + ' const foo : integer = 3;' +
UNIT_FOOTER;
OUT_UNIT_TEXT = UNIT_HEADER + ' const foo : integer = 3;' +
UNIT_FOOTER;
begin
JcfFormatSettings.Spaces.SpacesBeforeColonConst := 1;
TestProcessResult(TSpaceBeforeColon, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
initialization
TestFramework.RegisterTest('Processes', TTestSpaceBeforeColon.Suite);
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2019 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit RSConsole.ExplorerConsts;
interface
const
NOT_BUSY = 0;
BUSY = 1;
resourcestring
RSCannotProceedWithoutRequest = 'Cannot proceed without Request-Token';
RSProvideAuthEndPoint = 'Please provide an Authentication-Endpoint';
RSProvideClientID = 'Please provide a Client-ID (sometimes called "App-Key")';
RSProvideAuthCode = 'Please provide an Authentication-Code. This value can be requested in Step #1 "Authorization" ';
RSProvideTokenEndPoint = 'Please provide a Token-Endpoint';
RSProvideClientIDAndClientSecret = 'Please provide a Client-ID and a Client-Secret (sometimes called "App-Key" / "App-Secret")';
RSComponentsCopied = 'The following components have been copied to the clipboard: %s';
RSConfirmDeleteCustomParameter = 'Are you sure you want to delete the custom parameter?';
RSConfirmClearRecentRequests = 'Are you sure that you want to clear the list of the most recent requests?';
RSNoCustomParameterSelected = 'No custom parameter selected.';
RSBytesOfDataReturnedAndTiming = '%d : %s - %d bytes of data returned. Timing: Pre: %dms - Exec: %dms - Post: %dms - Total: %dms';
RSProxyServerEnabled = 'Proxy-server enabled: ';
RSProxyServerDisabled = 'Proxy-server disabled';
RSContentIsValidJSON = 'Content is valid JSON';
RSInvalidRootElement = 'Invalid root element';
RSContentIsNotJSON = 'Content is not JSON';
RSRootElementAppliesToJSON = 'Root Element, "%s" not applied. Root Element is only applied to JSON content. Content is not JSON.';
RSEditCustomParameter = 'Edit custom parameter';
RSAddCustomParameter = 'Add custom parameter';
RSUnableToValidateCertifcate = 'Unable to validate the certificate of this website. Continue with this request?';
implementation
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
///<summary>
/// This unit contains several <c>TDBXReader</c> implementations for the TParams
/// class as well as the TDataSet and TClientDataSet components. These TDBXReader
/// implementations allow the contents of these classes and components to be
/// used as parameters for a <c>TDBXCommand</c>. DataSnap server methods support
/// <c>TDBXReader</c> parameters.
///</summary>
unit Data.DBXDBReaders;
interface
uses
Data.DB,
System.Classes,
Data.DBXCommon,
Data.DBXPlatform,
DataSnap.DBClient,
Data.DBXCommonTable,
System.SysUtils,
Data.SqlTimSt,
Data.FMTBcd,
System.Generics.Collections
;
type
TDBXOriginalRow = class;
///<summary>
/// This is not used directly by applications.
///</summary>
TDBXParamsRow = class(TDBXRow)
private
FParams: TParams;
public
constructor Create(Params: TParams);
function CreateCustomValue(const ValueType: TDBXValueType): TDBXValue; override;
///<summary>Returns a UnicodeString from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetWideString(DbxValue: TDBXWideStringValue;
var Value: UnicodeString; var IsNull: LongBool); override;
///<summary>Returns a LongBool from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetBoolean(DbxValue: TDBXBooleanValue; var Value: LongBool;
var IsNull: LongBool); override;
///<summary>Returns a Byte from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetUInt8(DbxValue: TDBXUInt8Value; var Value: Byte;
var IsNull: LongBool); override;
///<summary>Returns a ShortInt from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetInt8(DbxValue: TDBXInt8Value; var Value: ShortInt;
var IsNull: LongBool); override;
///<summary>Returns a Word from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetUInt16(DbxValue: TDBXUInt16Value; var Value: Word;
var IsNull: LongBool); override;
///<summary>Returns a SmallInt from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetInt16(DbxValue: TDBXInt16Value; var Value: SmallInt;
var IsNull: LongBool); override;
///<summary>Returns an Integer from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetInt32(DbxValue: TDBXInt32Value; var Value: TInt32;
var IsNull: LongBool); override;
///<summary>Returns an Int64 from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetInt64(DbxValue: TDBXInt64Value; var Value: Int64;
var IsNull: LongBool); override;
///<summary>Returns a Single from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetSingle(DbxValue: TDBXSingleValue; var Value: Single;
var IsNull: LongBool); override;
///<summary>Returns a Double from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetDouble(DbxValue: TDBXDoubleValue; var Value: Double;
var IsNull: LongBool); override;
///<summary>Returns a PAnsiChar from the row in the AnsiStringBuilder parameter or sets IsNull to true.</summary>
procedure GetAnsiString(DbxValue: TDBXAnsiStringValue;
var AnsiStringBuilder: PAnsiChar; var IsNull: LongBool); override;
///<summary>Returns a TDBXDate from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetDate(DbxValue: TDBXDateValue; var Value: TDBXDate;
var IsNull: LongBool); override;
///<summary>Returns a TBytes from the row in the Buffer parameter, and the number
/// of bytes copied into the Buffer in the ReturnLength parameter or sets IsNull to true.</summary>
procedure GetBytes(DbxValue: TDBXByteArrayValue; Offset: Int64;
const Buffer: TBytes; BufferOffset: Int64; Length: Int64;
var ReturnLength: Int64; var IsNull: LongBool); override;
///<summary>Returns the DataSize from the row in the ByteLength parameter or sets IsNull to true.</summary>
procedure GetByteLength(DbxValue: TDBXByteArrayValue; var ByteLength: Int64;
var IsNull: LongBool); override;
///<summary>Returns a TDBXTime from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetTime(DbxValue: TDBXTimeValue; var Value: TDBXTime;
var IsNull: LongBool); override;
///<summary>Returns a TBcd from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetBcd(DbxValue: TDBXBcdValue; var Value: TBcd;
var IsNull: LongBool); override;
///<summary>Returns a TSQLTimeStamp from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetTimeStamp(DbxValue: TDBXTimeStampValue;
var Value: TSQLTimeStamp; var IsNull: LongBool); override;
///<summary>Returns a TSQLTimeStampOffset from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetTimeStampOffset(DbxValue: TDBXTimeStampOffsetValue;
var Value: TSQLTimeStampOffset; var IsNull: LongBool); override;
///<summary>Returns a TStream from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetStream(DbxValue: TDBXStreamValue; var Stream: TStream;
var IsNull: LongBool); overload; override;
///<summary>Sets the param value to null.</summary>
procedure SetNull(DbxValue: TDBXValue); override;
///<summary>Sets the param value to the UnicodeString Value.</summary>
procedure SetWideString(DbxValue: TDBXWideStringValue;
const Value: UnicodeString); override;
///<summary>Sets the param value to the Boolean Value.</summary>
procedure SetBoolean(DbxValue: TDBXBooleanValue; Value: Boolean); override;
///<summary>Sets the param value to the Byte Value.</summary>
procedure SetUInt8(DbxValue: TDBXUInt8Value; Value: Byte); override;
///<summary>Sets the param value to the ShortInt Value.</summary>
procedure SetInt8(DbxValue: TDBXInt8Value; Value: ShortInt); override;
///<summary>Sets the param value to the Word Value.</summary>
procedure SetUInt16(DbxValue: TDBXUInt16Value; Value: Word); override;
///<summary>Sets the param value to the SmallInt Value.</summary>
procedure SetInt16(DbxValue: TDBXInt16Value; Value: SmallInt); override;
///<summary>Sets the param value to the Integer Value.</summary>
procedure SetInt32(DbxValue: TDBXInt32Value; Value: TInt32); override;
///<summary>Sets the param value to the Int64 Value.</summary>
procedure SetInt64(DbxValue: TDBXInt64Value; Value: Int64); override;
///<summary>Sets the param value to the Single Value.</summary>
procedure SetSingle(DbxValue: TDBXSingleValue; Value: Single); override;
///<summary>Sets the param value to the Double Value.</summary>
procedure SetDouble(DbxValue: TDBXDoubleValue; Value: Double); override;
///<summary>Sets the param value to the AnsiString Value.</summary>
procedure SetAnsiString(DbxValue: TDBXAnsiStringValue;
const Value: AnsiString); override;
///<summary>Sets the param value to the AnsiString Value.</summary>
procedure SetString(DbxValue: TDBXAnsiStringValue; const Value: AnsiString); override;
///<summary>Sets the param value to the TDBXDate Value.</summary>
procedure SetDate(DbxValue: TDBXDateValue; Value: TDBXDate); override;
///<summary>Sets the param value to the TDBXTime Value.</summary>
procedure SetTime(DbxValue: TDBXTimeValue; Value: TDBXTime); override;
///<summary>Sets the param value to the TBcd Value.</summary>
procedure SetBCD(DbxValue: TDBXBcdValue; var Value: TBcd); override;
///<summary>Sets the param value to the TSQLTimeStamp Value unless the DataType
/// of the DbxValue is TDBXDataTypes.DateTimeType. In that case, the field value
/// is set to a TDateTime after converting Value.
///</summary>
procedure SetTimestamp(DbxValue: TDBXTimeStampValue;
var Value: TSQLTimeStamp); override;
///<summary>Sets the param value to the TSQLTimeStampOffset Value unless the DataType
/// of the DbxValue is TDBXDataTypes.DateTimeType. In that case, the param value
/// is set to a TDateTime after converting Value.
///</summary>
procedure SetTimestampOffset(DbxValue: TDBXTimeStampOffsetValue;
var Value: TSQLTimeStampOffset); override;
///<summary>Sets the param value to the TDBXStreamReader Value.</summary>
procedure SetStream(DbxValue: TDBXStreamValue;
StreamReader: TDBXStreamReader); override;
procedure ValueSet(Value: TDBXWritableValue); override;
end;
///<summary>
/// This is not used directly by applications.
///</summary>
TDBXMemoryTable = class(TDBXTable)
private
FIndex: Integer;
FOrderByColumn: Integer;
FName: string;
FValueTypes: TDBXValueTypeArray;
FValueRows: TList<TDBXWritableValueArray>;
function CreateWritableValueArray: TDBXWritableValueArray;
procedure ClearValues(AValues: TDBXWritableValueArray);
procedure ClearValueTypes(AValueTypes: TDBXValueTypeArray);
protected
function GetTableCount: Integer; override;
procedure OrderByColumn(Column: Integer); virtual;
public
constructor Create;
destructor Destroy; override;
procedure Insert; override;
procedure Post; override;
function InBounds: Boolean; override;
function Next: Boolean; override;
function First: Boolean; override;
procedure SetColumns(const Columns: TDBXValueTypeArray); override;
function GetColumns: TDBXValueTypeArray; override;
procedure SetDBXTableName(const AName: UnicodeString); override;
function GetDBXTableName: string; override;
procedure AcceptChanges; override;
function CreateTableView(const OrderByColumnName: UnicodeString): TDBXTable; override;
///<summary>Checks whether the string key Value is in the Ordinal column.</summary>
///<returns>True if the string key is found and False otherwise</returns>
function FindStringKey(const Ordinal: Integer; const Value: UnicodeString): Boolean; override;
end;
///<summary>
/// This is not used directly by applications.
///</summary>
TDBXDBTable = class(TDBXRowTable)
private
FCollectionName: UnicodeString;
FValueTypes: TDBXValueTypeArray;
///<summary> TFieldType to DBX type mapper</summary>
class function ToDataType(FieldType: TFieldType): Integer; static;
///<summary> TFieldType to DBX subtype mapper</summary>
class function ToDataSubType(FieldType: TFieldType): Integer; static;
class function ToFieldType(ValueType: TDBXValueType): TFieldType; static;
class function ToDBXParameterDirection(ParameterType: TParamType): Integer; static;
class function ToParameterType(ParameterDirection: Integer): TParamType; static;
procedure FreeValueTypes;
protected
procedure SetDBXTableName(const CollectionName: UnicodeString); override;
function GetDBXTableName: UnicodeString; override;
end;
///<summary>
/// <c>TDBXTable</c> implementation for TParams object used by <c>TDBXParamsReader</c>.
///</summary>
TDBXParamsTable = class(TDBXDBTable)
private
FParams: TParams;
FAtEnd: Boolean;
FInstanceOwner: Boolean;
class procedure CopyValueTypes(const ValueTypes: TDBXValueTypeArray; const Params: TParams); static;
class procedure CopyValueType(Ordinal: Integer; ValueType: TDBXValueType; Param: TParam); static;
protected
function GetColumns: TDBXValueTypeArray; override;
procedure SetColumns(const Columns: TDBXValueTypeArray); override;
function GetStorage: TObject; override;
public
constructor Create(); overload;
constructor Create(Params: TParams; InstanceOwner: Boolean = true); overload;
destructor Destroy; override;
function First: Boolean; override;
function Next: Boolean; override;
function InBounds: Boolean; override;
procedure Close; override;
function GetOrdinal(const ColumnName: UnicodeString): Integer; override;
end;
///<summary>
/// <c>TDBXReader</c> implementation for <c>TParams</c> object.
///</summary>
TDBXParamsReader = class(TDBXTableReader)
public
/// <summary>
/// Creates a <c>TDBXReader</c> for a <c>TParams</c> instance. If
/// <c>InstanceOwner</c> is true, the <c>TParams</c> instance will be
/// freed when this <c>TDBXParamsReader</c> instance is freed.
/// </summary>
constructor Create(Params: TParams; InstanceOwner: Boolean = true);
/// <summary>
/// Copies the contents of the current <c>Reader</c> row into the <c>Params</c>
/// instance.
/// </summary>
class procedure CopyReaderToParams(Reader: TDBXReader; Params: TParams); static;
/// <summary>
/// Copies the contents of the current <c>Reader</c> row into a new <c>TParams</c>
/// instance. The new <c>TParams</c> instance will constructed with the
/// <c>AOwner</c> instance as its owner.
/// </summary>
class function ToParams(AOwner: TPersistent; Reader: TDBXReader;
AOwnsInstance: Boolean): TParams; static;
destructor Destroy; override;
end;
///<summary>
/// This is not used directly by applications.
///</summary>
TDBXDataSetRow = class(TDBXRow)
private
FTable: TDataset;
function EnsureEditState: Boolean;
public
constructor Create(Table: TDataset);
///<summary>Returns a TDBXWideStringBuiler from the row in the WideStringBuilder
/// parameter or sets IsNull to true.</summary>
procedure GetWideString(DbxValue: TDBXWideStringValue;
var WideStringBuilder: TDBXWideStringBuilder; var IsNull: LongBool); override;
///<summary>Returns a LongBool from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetBoolean(DbxValue: TDBXBooleanValue; var Value: LongBool;
var IsNull: LongBool); override;
///<summary>Returns a Byte from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetUInt8(DbxValue: TDBXUInt8Value; var Value: Byte;
var IsNull: LongBool); override;
///<summary>Returns a ShortInt from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetInt8(DbxValue: TDBXInt8Value; var Value: ShortInt;
var IsNull: LongBool); override;
///<summary>Returns a Word from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetUInt16(DbxValue: TDBXUInt16Value; var Value: Word;
var IsNull: LongBool); override;
///<summary>Returns a SmallInt from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetInt16(DbxValue: TDBXInt16Value; var Value: SmallInt;
var IsNull: LongBool); override;
///<summary>Returns an Integer from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetInt32(DbxValue: TDBXInt32Value; var Value: TInt32;
var IsNull: LongBool); override;
///<summary>Returns an Int64 from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetInt64(DbxValue: TDBXInt64Value; var Value: Int64;
var IsNull: LongBool); override;
///<summary>Returns a Single from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetSingle(DbxValue: TDBXSingleValue; var Value: Single;
var IsNull: LongBool); override;
///<summary>Returns a Double from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetDouble(DbxValue: TDBXDoubleValue; var Value: Double;
var IsNull: LongBool); override;
///<summary>Returns a PAnsiChar from the row in the AnsiStringBuilder parameter
/// or sets IsNull to true.</summary>
procedure GetAnsiString(DbxValue: TDBXAnsiStringValue;
var AnsiStringBuilder: PAnsiChar; var IsNull: LongBool); override;
///<summary>Returns a TDBXDate from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetDate(DbxValue: TDBXDateValue; var Value: TDBXDate;
var IsNull: LongBool); override;
///<summary>Returns a TDBXTime from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetTime(DbxValue: TDBXTimeValue; var Value: TDBXTime;
var IsNull: LongBool); override;
///<summary>Returns a TSQLTimeStamp from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetTimeStamp(DbxValue: TDBXTimeStampValue;
var Value: TSQLTimeStamp; var IsNull: LongBool); override;
///<summary>Returns a TSQLTimeStampOffset from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetTimeStampOffset(DbxValue: TDBXTimeStampOffsetValue;
var Value: TSQLTimeStampOffset; var IsNull: LongBool); override;
///<summary>Returns a TBcd from the row in the Value parameter or sets IsNull to true.</summary>
procedure GetBcd(DbxValue: TDBXBcdValue; var Value: TBcd;
var IsNull: LongBool); override;
///<summary>Returns a TBytes from the row in the Buffer parameter, and the number
/// of bytes copied into the Buffer in the ReturnLength parameter or sets IsNull to true.
///</summary>
procedure GetBytes(DbxValue: TDBXByteArrayValue; Offset: Int64;
const Buffer: TBytes; BufferOffset: Int64; Length: Int64;
var ReturnLength: Int64; var IsNull: LongBool); override;
///<summary>Returns the DataSize or the BlobSize from the row in the ByteLength
/// parameter or sets IsNull to true.</summary>
procedure GetByteLength(DbxValue: TDBXByteArrayValue; var ByteLength: Int64;
var IsNull: LongBool); override;
///<summary>Returns a TStream from the row in the Stream parameter or sets IsNull to true.</summary>
procedure GetStream(DbxValue: TDBXStreamValue; var Stream: TStream;
var IsNull: LongBool); overload; override;
///<summary>Sets the field value to null.</summary>
procedure SetNull(DbxValue: TDBXValue); override;
///<summary>Sets the field value to the UnicodeString Value.</summary>
procedure SetWideString(DbxValue: TDBXWideStringValue;
const Value: UnicodeString); override;
///<summary>Sets the field value to the Boolean Value.</summary>
procedure SetBoolean(DbxValue: TDBXBooleanValue; Value: Boolean); override;
///<summary>Sets the field value to the Byte Value.</summary>
procedure SetUInt8(DbxValue: TDBXUInt8Value; Value: Byte); override;
///<summary>Sets the field value to the ShortInt Value.</summary>
procedure SetInt8(DbxValue: TDBXInt8Value; Value: ShortInt); override;
///<summary>Sets the field value to the Word Value.</summary>
procedure SetUInt16(DbxValue: TDBXUInt16Value; Value: Word); override;
///<summary>Sets the field value to the SmallInt Value.</summary>
procedure SetInt16(DbxValue: TDBXInt16Value; Value: SmallInt); override;
///<summary>Sets the field value to the Integer Value.</summary>
procedure SetInt32(DbxValue: TDBXInt32Value; Value: TInt32); override;
///<summary>Sets the field value to the Int64 Value.</summary>
procedure SetInt64(DbxValue: TDBXInt64Value; Value: Int64); override;
///<summary>Sets the field value to the Single Value.</summary>
procedure SetSingle(DbxValue: TDBXSingleValue; Value: Single); override;
///<summary>Sets the field value to the Double Value.</summary>
procedure SetDouble(DbxValue: TDBXDoubleValue; Value: Double); override;
///<summary>Sets the field value to AnsiString Value.</summary>
procedure SetAnsiString(DbxValue: TDBXAnsiStringValue;
const Value: AnsiString); override;
///<summary>Sets the field value to the Value.</summary>
procedure SetString(DbxValue: TDBXAnsiStringValue; const Value: AnsiString); override;
///<summary>Sets the field value to a TDateTime after converting Value.</summary>
procedure SetDate(DbxValue: TDBXDateValue; Value: TDBXDate); override;
///<summary>Sets the field value to a TDateTime after converting Value.</summary>
procedure SetTime(DbxValue: TDBXTimeValue; Value: TDBXTime); override;
///<summary>Sets the field value to the TBcd Value.</summary>
procedure SetBCD(DbxValue: TDBXBcdValue; var Value: TBcd); override;
///<summary>Sets the field value to the TSQLTimeStamp Value unless the DataType
/// of the DbxValue is TDBXDataTypes.DateTimeType. In that case, the field value
/// is set to a TDateTime after converting Value.
///</summary>
procedure SetTimestamp(DbxValue: TDBXTimeStampValue;
var Value: TSQLTimeStamp); override;
///<summary>Sets the field value to the TSQLTimeStampOffset Value unless the DataType
/// of the DbxValue is TDBXDataTypes.DateTimeType. In that case, the field value
/// is set to a TDateTime after converting Value.
///</summary>
procedure SetTimestampOffset(DbxValue: TDBXTimeStampOffsetValue;
var Value: TSQLTimeStampOffset); override;
procedure ValueSet(Value: TDBXWritableValue); override;
end;
///<summary>
/// <c>TDBXTable</c> implementation for TParams object used by <c>TDBXParamsReader</c>.
///</summary>
TDBXDataSetTable = class(TDBXDBTable)
private
FOwnsTable: Boolean;
FTable: TDataset;
FOriginal: TDBXOriginalRow;
procedure SkipOriginalRow; virtual;
constructor Create(const CollectionName: UnicodeString; Table: TDataset;
OwnsTable: Boolean; ValuesNeedCreate: Boolean); overload;
protected
procedure SetDBXTableName(const CollectionName: UnicodeString); override;
function GetDBXTableName: UnicodeString; override;
function GetColumns: TDBXValueTypeArray; override;
function GetStorage: TObject; override;
function GetDataSize(FieldDef: TFieldDef; Field: TField): Integer;
public
constructor Create(Dataset: TDataset; InstanceOwner: Boolean = true); overload;
destructor Destroy; override;
function First: Boolean; override;
function Next: Boolean; override;
function InBounds: Boolean; override;
procedure Insert; override;
procedure Post; override;
procedure DeleteRow; override;
procedure Close; override;
function GetOrdinal(const ColumnName: UnicodeString): Integer; override;
procedure FailIfRowIsNew;
procedure CopyValueTypeProperties(FieldDef: TFieldDef;
ValueType: TDBXValueType; Ordinal: Integer);
end;
///<summary>
/// This is not used directly by applications.
///</summary>
TDBXClientDataSetTable = class(TDBXDataSetTable)
private
FClientDataset: TClientDataSet;
constructor Create(const CollectionName: UnicodeString;
TableColumns: TDBXValueTypeArray; Table: TClientDataSet;
OwnsTable: Boolean = true); overload;
procedure SkipOriginalRow; override;
protected
function GetDeletedRows: TDBXTable; override;
function GetInsertedRows: TDBXTable; override;
function GetUpdatedRows: TDBXTable; override;
function GetOriginalRow: TDBXTableRow; override;
public
constructor Create; overload;
constructor Create(ClientDataSet: TClientDataSet; OwnsTable: Boolean); overload;
procedure AcceptChanges; override;
procedure Clear; override;
function CreateTableView(const OrderByColumnName: UnicodeString): TDBXTable; override;
function FindStringKey(const Ordinal: Integer; const Value: UnicodeString): Boolean; override;
procedure SetColumns(const Columns: TDBXValueTypeArray); override;
end;
///<summary>
/// <c>TDBXReader</c> implementation for <c>TDataSet</c> object.
///</summary>
TDBXDataSetReader = class(TDBXTableReader)
public
/// <summary>
/// Creates a <c>TDBXReader</c> for a <c>TDataSet</c> instance. If
/// <c>InstanceOwner</c> is true, the <c>TDataSet</c> instance will be
/// freed when this <c>TDBXDataSetReader</c> instance is freed.
/// </summary>
constructor Create(Params: TDataset; InstanceOwner: Boolean = true);
/// <summary>
/// Copies the contents of <c>Reader</c> into the <c>TDataSet</c>
/// instance.
/// </summary>
/// <returns>
/// The same <c>DataSet</c> instance that was passed into this method.
/// </returns>
class procedure CopyReaderToClientDataSet(Reader: TDBXReader;
Dataset: TClientDataSet); static;
class function ToClientDataSet(AOwner: TComponent; Reader: TDBXReader;
AOwnsInstance: Boolean): TClientDataSet; static;
destructor Destroy; override;
end;
///<summary>
/// This is not used directly by applications.
///</summary>
TDBXOriginalRow = class(TDBXDBTable)
private
FAtEnd: Boolean;
FClonedTable: TDBXClientDataSetTable;
FClientTable: TDBXClientDataSetTable;
protected
function GetWritableValue(const Ordinal: TInt32): TDBXWritableValue; override;
public
constructor Create(ClientTable: TDBXClientDataSetTable);
function GetOrdinal(const ColumnName: UnicodeString): Integer; override;
function First: Boolean; override;
function Next: Boolean; override;
function InBounds: Boolean; override;
function GetColumns: TDBXValueTypeArray; override;
end;
implementation
uses
System.Variants,
System.Generics.Defaults,
Data.DBXCommonResStrs
;
type
TDBXDataSetRowExt = class(TDBXDataSetRow)
protected
procedure SetDynamicBytes( DbxValue: TDBXValue;
Offset: Int64;
const Buffer: TBytes;
BufferOffset: Int64;
Length: Int64); override;
end;
TDBXWritableValueArrayComparer = class(TInterfacedObject, IComparer<TDBXWritableValueArray>)
private
FColumnIndex: Integer;
public
constructor Create(AColumnIndex: Integer);
function Compare(const Left, Right: TDBXWritableValueArray): Integer; overload;
property ColumnIndex: Integer read FColumnIndex;
end;
{ TDBXDataSetTable }
constructor TDBXDataSetTable.Create(const CollectionName: UnicodeString; Table: TDataSet; OwnsTable: Boolean; ValuesNeedCreate: Boolean);
begin
Inherited Create(nil, TDBXDataSetRowExt.Create(Table));
FTable := Table;
FCollectionName := CollectionName;
FOwnsTable := OwnsTable;
if ValuesNeedCreate then
CreateValues;
end;
destructor TDBXDataSetTable.Destroy;
begin
FreeAndNil(FOriginal);
if FOwnsTable then
FreeAndNil(FTable);
FreeValueTypes;
inherited Destroy;
end;
function TDBXDataSetTable.First;
begin
RowNavigated;
// Some implementations don't support this.
//
if FTable.IsUniDirectional then
Result := True
else
begin
FTable.First;
SkipOriginalRow;
Result := FTable.RecordCount > 0;
end;
end;
function TDBXDataSetTable.Next: Boolean;
begin
FailIfRowIsNew();
FTable.Next;
SkipOriginalRow;
RowNavigated;
Result := not FTable.Eof;
end;
function TDBXDataSetTable.InBounds: Boolean;
begin
FailIfRowIsNew();
Result := not FTable.Eof and (FTable.RecordCount > 0);
// if Result and FTable.Bof then
// FTable.Next;
end;
procedure TDBXDataSetTable.Insert;
begin
FailIfRowIsNew();
FTable.Append;
end;
procedure TDBXDataSetTable.Post;
begin
if FTable.State <> dsInsert then
raise TDBXError.Create(SInsertNotCalled);
FTable.Post;
end;
procedure TDBXDataSetTable.DeleteRow;
begin
if FTable.State = dsInsert then
FTable.Cancel
else
FTable.Delete;
end;
procedure TDBXDataSetTable.Close;
begin
Clear;
end;
function TDBXDataSetTable.GetOrdinal(const ColumnName: UnicodeString): Integer;
var
FieldDef: TFieldDef;
begin
FieldDef := FTable.FieldDefs.Find(ColumnName);
Result := FieldDef.FieldNo - 1;
end;
procedure TDBXClientDataSetTable.AcceptChanges;
begin
FailIfRowIsNew();
FClientDataSet.MergeChangeLog;
end;
procedure TDBXClientDataSetTable.Clear;
begin
if (FClientDataSet.State in dsEditModes) then
FClientDataSet.Post;
if not (usModified in FClientDataSet.StatusFilter)
and not (usDeleted in FClientDataSet.StatusFilter)
and not (usInserted in FClientDataSet.StatusFilter) then
FClientDataSet.EmptyDataSet;
end;
function TDBXClientDataSetTable.CreateTableView(const OrderByColumnName: UnicodeString): TDBXTable;
var
View: TClientDataSet;
begin
View := TClientDataSet.Create(nil);
View.CloneCursor(FClientDataSet,True);
if not StringIsNil(OrderByColumnName) then
View.IndexFieldNames := OrderByColumnName;
Result := TDBXClientDataSetTable.Create(FCollectionName, CopyColumns, View);
end;
function TDBXClientDataSetTable.FindStringKey(const Ordinal: Integer; const Value: UnicodeString): Boolean;
var
ColumnName: UnicodeString;
begin
ColumnName := FClientDataSet.FieldDefs[Ordinal].Name;
if FClientDataSet.IndexFieldNames <> ColumnName then
FClientDataSet.IndexFieldNames := ColumnName;
Result := FClientDataSet.FindKey([Value]);
end;
function TDBXDataSetTable.GetDataSize(FieldDef: TFieldDef;
Field: TField): Integer;
begin
case FieldDef.DataType of
ftVarBytes:
Result := Field.DataSize - sizeof(Word);
else
if Field is TBlobField then
Result := (Field as TBlobField).BlobSize
else
Result := Field.DataSize;
end;
end;
function TDBXDataSetTable.GetDBXTableName: UnicodeString;
begin
Result := FCollectionName;
end;
procedure TDBXDataSetTable.SetDBXTableName(const CollectionName: UnicodeString);
begin
FCollectionName := CollectionName;
end;
procedure TDBXDataSetTable.SkipOriginalRow;
begin
end;
procedure TDBXClientDataSetTable.SkipOriginalRow;
begin
if (usModified in FClientDataSet.StatusFilter) and (FClientDataSet.UpdateStatus = usUnmodified) then
FClientDataSet.Next;
end;
function TDBXDataSetTable.GetColumns: TDBXValueTypeArray;
var
Ordinal: Integer;
FieldDef: TFieldDef;
ValueType: TDBXValueType;
Field: TField;
begin
if FValueTypes = nil then
begin
SetLength(FValueTypes, FTable.FieldDefs.Count);
for Ordinal := Low(FValueTypes) to High(FValueTypes) do
begin
FieldDef := FTable.FieldDefs[Ordinal];
Field := FTable.Fields[Ordinal];
ValueType := TDBXValueType.Create;
ValueType.Name := FieldDef.Name;
ValueType.DisplayName := FieldDef.DisplayName;
ValueType.DataType := ToDataType(FieldDef.DataType);
ValueType.SubType := ToDataSubType(FieldDef.DataType);
ValueType.Size := GetDataSize(FieldDef, Field);
ValueType.Precision := FieldDef.Precision;
if ValueType.Precision = 0 then
case ValueType.DataType of
TDBXDataTypes.WideStringType, TDBXDataTypes.BlobType:
ValueType.Precision := ValueType.Size;
end;
ValueType.Scale := FieldDef.Size;
FValueTypes[Ordinal] := ValueType;
end;
end;
Result := FValueTypes;
end;
procedure TDBXClientDataSetTable.SetColumns(const Columns: TDBXValueTypeArray);
var
Ordinal: Integer;
begin
FreeValueTypes;
FValueTypes := Columns;
if FClientDataSet <> nil then
begin
FClientDataSet.Close;
for Ordinal := Low(Columns) to High(Columns) do
begin
if Ordinal >= FClientDataSet.FieldDefs.Count then
CopyValueTypeProperties(FClientDataSet.FieldDefs.AddFieldDef, Columns[Ordinal], Ordinal)
else if not (FClientDataSet.FieldDefs[Ordinal].Name = Columns[Ordinal].Name) then
raise TDBXError.Create(SMustKeepOriginalColumnOrder);
end;
FClientDataSet.CreateDataSet;
end;
CreateValues;
end;
function TDBXClientDataSetTable.GetDeletedRows: TDBXTable;
var
View: TClientDataSet;
begin
View := TClientDataSet.Create(nil);
View.CloneCursor(FClientDataSet,True);
View.StatusFilter := [usDeleted];
View.Filtered := True;
Result := TDBXClientDataSetTable.Create(FCollectionName, CopyColumns, View);
Result.First;
end;
function TDBXClientDataSetTable.GetInsertedRows: TDBXTable;
var
View: TClientDataSet;
begin
View := TClientDataSet.Create(nil);
View.CloneCursor(FClientDataSet,True);
View.StatusFilter := [usInserted];
View.Filtered := True;
Result := TDBXClientDataSetTable.Create(FCollectionName, CopyColumns, View);
Result.First;
end;
function TDBXClientDataSetTable.GetUpdatedRows: TDBXTable;
var
View: TClientDataSet;
begin
View := TClientDataSet.Create(nil);
View.CloneCursor(FClientDataSet, False, False);
View.StatusFilter := [usModified];
View.Filtered := True;
Result := TDBXClientDataSetTable.Create(FCollectionName, CopyColumns, View);
Result.First;
end;
function TDBXClientDataSetTable.GetOriginalRow: TDBXTableRow;
begin
if FOriginal = nil then
FOriginal := TDBXOriginalRow.Create(self);
if FClientDataSet.UpdateStatus = usInserted then
Result := nil
else
Result := FOriginal;
end;
function TDBXDataSetTable.GetStorage: TObject;
begin
Result := FTable;
end;
procedure TDBXDataSetTable.FailIfRowIsNew;
begin
if FTable.State = dsInsert then
raise TDBXError.Create(SPostNotCalled);
end;
procedure TDBXDataSetTable.CopyValueTypeProperties(FieldDef: TFieldDef; ValueType: TDBXValueType; Ordinal: Integer);
begin
FieldDef.Name := ValueType.Name;
FieldDef.DisplayName := ValueType.DisplayName;
FieldDef.DataType := ToFieldType(ValueType);
FieldDef.FieldNo := Ordinal;
if (ValueType.DataType = TDBXDataTypes.WideStringType) or (ValueType.DataType = TDBXDataTypes.AnsiStringType) then
begin
if ValueType.Size <= 0 then
FieldDef.Size := 128 // default size (make constant)
else
FieldDef.Size := ValueType.Size;
end;
// Don't set the size. It is error prone and not neccessary:
// FieldDef.Size := Descriptor.DataSize;
// Don't set the hidden attribute. Field access is forbidden to hidden fields !!
// if Descriptor.Hidden then
// FieldDef.Attributes := FieldDef.Attributes + [faHiddenCol];
end;
constructor TDBXDataSetTable.Create(Dataset: TDataSet; InstanceOwner: Boolean);
begin
Create('', DataSet, InstanceOwner, true);
end;
{ TDBXOriginalRow }
constructor TDBXOriginalRow.Create(ClientTable: TDBXClientDataSetTable);
var
ClientDataSet: TClientDataSet;
begin
ClientDataSet := TClientDataSet.Create(nil);
ClientDataSet.CloneCursor(ClientTable.FClientDataSet, True);
ClientDataSet.StatusFilter := [usModified];
FClonedTable := TDBXClientDataSetTable.Create(ClientTable.FCollectionName, ClientTable.CopyColumns, ClientDataSet);
inherited Create(nil, TDBXDataSetRowExt.Create(ClientDataSet));
FClientTable := ClientTable;
end;
function TDBXOriginalRow.First: Boolean;
begin
FAtEnd := false;
Result := true;
end;
function TDBXOriginalRow.GetColumns: TDBXValueTypeArray;
begin
Result := FClientTable.GetColumns;
end;
function TDBXOriginalRow.GetOrdinal(const ColumnName: UnicodeString): Integer;
begin
Result := FClientTable.GetOrdinal(ColumnName);
end;
function TDBXOriginalRow.GetWritableValue(
const Ordinal: TInt32): TDBXWritableValue;
var
TargetRecNo: Integer;
begin
if FClientTable.FTable.UpdateStatus in [usDeleted, usUnmodified] then
Result := FClientTable.GetWritableValue(Ordinal)
else if FClientTable.FTable.UpdateStatus = usModified then
begin
if usModified in FClientTable.FClientDataset.StatusFilter then
TargetRecNo := FClientTable.FTable.RecNo - 1
else
TargetRecNo := (FClientTable.FTable.RecNo * 2) - 1;
if FClonedTable.FTable.RecNo <> TargetRecNo then
begin
FClonedTable.FTable.MoveBy(TargetRecNo - FClonedTable.FTable.RecNo);
FClonedTable.RowNavigated;
end;
Result := FClonedTable.GetWritableValue(Ordinal);
end
else
Result := nil;
end;
function TDBXOriginalRow.InBounds: Boolean;
begin
Result := not FAtEnd;
end;
function TDBXOriginalRow.Next: Boolean;
begin
if FAtEnd then
Result := false
else
begin
FAtEnd := true;
Result := true;
end;
end;
{ TDBXDataSetRow }
constructor TDBXDataSetRow.Create(Table: TDataSet);
begin
inherited Create(nil);
FTable := Table;
end;
procedure TDBXDataSetRow.GetBoolean(DbxValue: TDBXBooleanValue;
var Value, IsNull: LongBool);
var
Field: TField;
begin
Field := FTable.Fields[DbxValue.ValueType.Ordinal];
IsNull := Field.IsNull;
if not IsNull then
Value := Field.AsBoolean;
end;
procedure TDBXDataSetRow.GetInt16(DbxValue: TDBXInt16Value; var Value: SmallInt;
var IsNull: LongBool);
var
Field: TField;
begin
Field := FTable.Fields[DbxValue.ValueType.Ordinal];
IsNull := Field.IsNull;
if not IsNull then
Value := Field.Value;
end;
procedure TDBXDataSetRow.GetInt32(DbxValue: TDBXInt32Value; var Value: TInt32;
var IsNull: LongBool);
var
Field: TField;
begin
Field := FTable.Fields[DbxValue.ValueType.Ordinal];
IsNull := Field.IsNull;
if not IsNull then
Value := Field.AsInteger;
end;
procedure TDBXDataSetRow.GetInt64(DbxValue: TDBXInt64Value; var Value: Int64;
var IsNull: LongBool);
var
Field: TField;
begin
Field := FTable.Fields[DbxValue.ValueType.Ordinal];
IsNull := Field.IsNull;
if not IsNull then
Value := Field.Value;
end;
procedure TDBXDataSetRow.GetInt8(DbxValue: TDBXInt8Value; var Value: ShortInt;
var IsNull: LongBool);
var
Field: TField;
begin
Field := FTable.Fields[DbxValue.ValueType.Ordinal];
IsNull := Field.IsNull;
if not IsNull then
Value := Field.Value;
end;
procedure TDBXDataSetRow.GetDouble(DbxValue: TDBXDoubleValue; var Value: Double; var IsNull: LongBool);
var
Field: TField;
begin
Field := FTable.Fields[DbxValue.ValueType.Ordinal];
IsNull := Field.IsNull;
if not IsNull then
Value := Field.Value;
end;
procedure TDBXDataSetRow.GetWideString(DbxValue: TDBXWideStringValue;
var WideStringBuilder: TDBXWideStringBuilder; var IsNull: LongBool);
var
Field: TField;
Value: UnicodeString;
begin
Field := FTable.Fields[DbxValue.ValueType.Ordinal];
IsNull := Field.IsNull;
if not IsNull then
begin
Value := Field.AsWideString;
TDBXPlatform.CopyWideStringToBuilder(Value, Length(Value)+1, WideStringBuilder);
end;
end;
procedure TDBXDataSetRow.GetAnsiString(DbxValue: TDBXAnsiStringValue; var AnsiStringBuilder: PAnsiChar; var IsNull: LongBool);
var
Field: TField;
Value: AnsiString;
begin
Field := FTable.Fields[DbxValue.ValueType.Ordinal];
IsNull := Field.IsNull;
if not IsNull then
begin
Value := Field.AsAnsiString;
TDBXPlatform.CopyStringToBuilder(Value, Length(Value)+1, AnsiStringBuilder);
end;
end;
procedure TDBXDataSetRow.GetDate(DbxValue: TDBXDateValue; var Value: TDBXDate; var IsNull: LongBool);
var
Field: TField;
begin
Field := FTable.Fields[DbxValue.ValueType.Ordinal];
IsNull := Field.IsNull;
if not IsNull then
Value := DateTimeToTimeStamp(Field.AsDateTime).Date;
end;
procedure TDBXDataSetRow.GetTime(DbxValue: TDBXTimeValue; var Value: TDBXTime; var IsNull: LongBool);
var
Field: TField;
begin
Field := FTable.Fields[DbxValue.ValueType.Ordinal];
IsNull := Field.IsNull;
if not IsNull then
Value := DateTimeToTimeStamp(Field.AsDateTime).Time;
end;
procedure TDBXDataSetRow.GetTimeStamp(DbxValue: TDBXTimeStampValue; var Value: TSQLTimeStamp; var IsNull: LongBool);
var
Field: TField;
begin
Field := FTable.Fields[DbxValue.ValueType.Ordinal];
IsNull := Field.IsNull;
if not IsNull then
Value := Field.AsSQLTimeStamp;
end;
procedure TDBXDataSetRow.GetTimeStampOffset(DbxValue: TDBXTimeStampOffsetValue;
var Value: TSQLTimeStampOffset; var IsNull: LongBool);
var
Field: TField;
begin
Field := FTable.Fields[DbxValue.ValueType.Ordinal];
IsNull := Field.IsNull;
if not IsNull then
Value := Field.AsSQLTimeStampOffset;
end;
procedure TDBXDataSetRow.GetUInt16(DbxValue: TDBXUInt16Value; var Value: Word;
var IsNull: LongBool);
var
Field: TField;
begin
Field := FTable.Fields[DbxValue.ValueType.Ordinal];
IsNull := Field.IsNull;
if not IsNull then
Value := Field.Value;
end;
procedure TDBXDataSetRow.GetUInt8(DbxValue: TDBXUInt8Value; var Value: Byte;
var IsNull: LongBool);
var
Field: TField;
begin
Field := FTable.Fields[DbxValue.ValueType.Ordinal];
IsNull := Field.IsNull;
if not IsNull then
Value := Field.Value;
end;
procedure TDBXDataSetRow.GetBcd(DbxValue: TDBXBcdValue; var Value: TBcd; var IsNull: LongBool);
var
Field: TField;
begin
Field := FTable.Fields[DbxValue.ValueType.Ordinal];
IsNull := Field.IsNull;
if not IsNull then
Value := Field.AsBCD;
end;
procedure TDBXDataSetRow.GetBytes(DbxValue: TDBXByteArrayValue; Offset: Int64; const Buffer: TBytes; BufferOffset: Int64; Length: Int64; var ReturnLength: Int64; var IsNull: LongBool);
var
Field: TField;
DataSize: Integer;
begin
Field := FTable.Fields[DbxValue.ValueType.Ordinal];
IsNull := Field.IsNull;
if not IsNull then
begin
if Field is TBlobField then
DataSize := (Field as TBlobField).BlobSize
else
DataSize := Field.DataSize;
if Length + BufferOffset > DataSize then
ReturnLength := DataSize - BufferOffset
else
ReturnLength := Length;
Move(Field.AsBytes[0], Buffer[BufferOffset], ReturnLength);
end;
end;
procedure TDBXDataSetRow.GetByteLength(DbxValue: TDBXByteArrayValue; var ByteLength: Int64; var IsNull: LongBool);
var
Field: TField;
begin
Field := FTable.Fields[DbxValue.ValueType.Ordinal];
IsNull := Field.IsNull;
if not IsNull then
if Field is TBlobField then
ByteLength := (Field as TBlobField).BlobSize
else
ByteLength := Field.DataSize;
end;
procedure TDBXDataSetRow.GetSingle(DbxValue: TDBXSingleValue; var Value: Single;
var IsNull: LongBool);
var
Field: TField;
begin
Field := FTable.Fields[DbxValue.ValueType.Ordinal];
IsNull := Field.IsNull;
if not IsNull then
Value := Field.Value;
end;
procedure TDBXDataSetRow.GetStream(DbxValue: TDBXStreamValue;
var Stream: TStream; var IsNull: LongBool);
var
ByteLength: Int64;
Bytes: TBytes;
ReturnLength: Int64;
begin
GetByteLength(DbxValue, ByteLength, IsNull);
if not IsNull then
begin
SetLength(Bytes, Integer(ByteLength));
GetBytes(DbxValue, 0, Bytes, 0, Integer(ByteLength), ReturnLength, IsNull);
Stream := TBytesStream.Create(Bytes);
end;
end;
procedure TDBXDataSetRow.SetBoolean(DbxValue: TDBXBooleanValue; Value: Boolean);
begin
EnsureEditState;
FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXDataSetRow.SetInt16(DbxValue: TDBXInt16Value; Value: SmallInt);
begin
EnsureEditState;
FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXDataSetRow.SetInt32(DbxValue: TDBXInt32Value; Value: TInt32);
begin
EnsureEditState;
FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXDataSetRow.SetInt64(DbxValue: TDBXInt64Value; Value: Int64);
begin
EnsureEditState;
FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXDataSetRow.SetInt8(DbxValue: TDBXInt8Value; Value: ShortInt);
begin
EnsureEditState;
FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXDataSetRow.SetDouble(DbxValue: TDBXDoubleValue; Value: Double);
begin
EnsureEditState;
FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXDataSetRow.SetNull(DbxValue: TDBXValue);
begin
EnsureEditState;
FTable.Fields[DbxValue.ValueType.Ordinal].Value := Null;
end;
procedure TDBXDataSetRow.SetSingle(DbxValue: TDBXSingleValue; Value: Single);
begin
EnsureEditState;
FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXDataSetRow.SetString(DbxValue: TDBXAnsiStringValue;
const Value: AnsiString);
begin
EnsureEditState;
FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXDataSetRow.SetWideString(DbxValue: TDBXWideStringValue;
const Value: UnicodeString);
begin
EnsureEditState;
FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXDataSetRow.SetAnsiString(DbxValue: TDBXAnsiStringValue; const Value: AnsiString);
begin
EnsureEditState;
FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXDataSetRow.SetDate(DbxValue: TDBXDateValue; Value: TDBXDate);
var
TimeStamp: TTimeStamp;
begin
TimeStamp.Date := Value;
TimeStamp.Time := 0;
EnsureEditState;
FTable.Fields[DBXValue.ValueType.Ordinal].AsDateTime := TimeStampToDateTime(TimeStamp);
end;
procedure TDBXDataSetRow.SetTime(DbxValue: TDBXTimeValue; Value: TDBXTime);
var
TimeStamp: TTimeStamp;
begin
TimeStamp.Date := DateDelta;
TimeStamp.Time := Value;
EnsureEditState;
FTable.Fields[DBXValue.ValueType.Ordinal].AsDateTime := TimeStampToDateTime(TimeStamp);
end;
procedure TDBXDataSetRow.SetTimestamp(DbxValue: TDBXTimeStampValue;
var Value: TSQLTimeStamp);
begin
EnsureEditState;
if DbxValue.ValueType.DataType = TDBXDataTypes.DateTimeType then
FTable.Fields[DBXValue.ValueType.Ordinal].AsDateTime := SQLTimeStampToDateTime(Value)
else
FTable.Fields[DbxValue.ValueType.Ordinal].AsSQLTimeStamp := Value;
end;
procedure TDBXDataSetRow.SetTimestampOffset(DbxValue: TDBXTimeStampOffsetValue;
var Value: TSQLTimeStampOffset);
begin
EnsureEditState;
if DbxValue.ValueType.DataType = TDBXDataTypes.DateTimeType then
FTable.Fields[DBXValue.ValueType.Ordinal].AsDateTime := SQLTimeStampOffsetToDateTime(Value)
else
FTable.Fields[DbxValue.ValueType.Ordinal].AsSQLTimeStampOffset := Value;
end;
procedure TDBXDataSetRow.SetUInt16(DbxValue: TDBXUInt16Value; Value: Word);
begin
EnsureEditState;
FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXDataSetRow.SetUInt8(DbxValue: TDBXUInt8Value; Value: Byte);
begin
EnsureEditState;
FTable.Fields[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXDataSetRow.SetBCD(DbxValue: TDBXBcdValue; var Value: TBcd);
begin
EnsureEditState;
FTable.Fields[DbxValue.ValueType.Ordinal].AsBCD := Value;
end;
procedure TDBXDataSetRow.ValueSet(Value: TDBXWritableValue);
begin
TDBXDriverHelp.SetPendingValue(Value);
end;
function TDBXDataSetRow.EnsureEditState: Boolean;
begin
Result := False;
if not(FTable.State in dsEditModes) then
begin
FTable.Edit;
Result := True;
end;
end;
constructor TDBXParamsRow.Create(Params: TParams);
begin
inherited Create(nil);
FParams := Params;
end;
function TDBXParamsRow.CreateCustomValue(const ValueType: TDBXValueType): TDBXValue;
begin
Result := nil;
case ValueType.DataType of
TDBXDataTypes.WideStringType:
Result := TDBXStringValue.Create(ValueType);
// TDBXDataTypes.AnsiStringType:
// Result := TDBXAnsiCharsValue.Create(ValueType);
TDBXDataTypes.BlobType:
case ValueType.SubType of
TDBXDataTypes.HMemoSubType,
TDBXDataTypes.MemoSubType,
TDBXDataTypes.WideMemoSubType:
Result := TDBXStringValue.Create(ValueType);
end;
end;
end;
procedure TDBXParamsRow.GetBoolean(DbxValue: TDBXBooleanValue;
var Value, IsNull: LongBool);
var
Param: TParam;
begin
Param := FParams[DbxValue.ValueType.Ordinal];
IsNull := Param.IsNull;
if not IsNull then
Value := Param.AsBoolean;
end;
procedure TDBXParamsRow.GetInt16(DbxValue: TDBXInt16Value; var Value: SmallInt;
var IsNull: LongBool);
var
Param: TParam;
begin
Param := FParams[DbxValue.ValueType.Ordinal];
IsNull := Param.IsNull;
if not IsNull then
Value := Param.Value;
end;
procedure TDBXParamsRow.GetInt32(DbxValue: TDBXInt32Value; var Value: TInt32;
var IsNull: LongBool);
var
Param: TParam;
begin
Param := FParams[DbxValue.ValueType.Ordinal];
IsNull := Param.IsNull;
if not IsNull then
Value := Param.AsInteger;
end;
procedure TDBXParamsRow.GetInt64(DbxValue: TDBXInt64Value; var Value: Int64;
var IsNull: LongBool);
var
Param: TParam;
begin
Param := FParams[DbxValue.ValueType.Ordinal];
IsNull := Param.IsNull;
if not IsNull then
Value := Param.Value;
end;
procedure TDBXParamsRow.GetInt8(DbxValue: TDBXInt8Value; var Value: ShortInt;
var IsNull: LongBool);
var
Param: TParam;
begin
Param := FParams[DbxValue.ValueType.Ordinal];
IsNull := Param.IsNull;
if not IsNull then
Value := Param.Value;
end;
procedure TDBXParamsRow.GetSingle(DbxValue: TDBXSingleValue; var Value: Single;
var IsNull: LongBool);
var
Param: TParam;
begin
Param := FParams[DbxValue.ValueType.Ordinal];
IsNull := Param.IsNull;
if not IsNull then
Value := Param.Value;
end;
procedure TDBXParamsRow.GetStream(DbxValue: TDBXStreamValue;
var Stream: TStream; var IsNull: LongBool);
var
Param: TParam;
begin
Param := FParams[DbxValue.ValueType.Ordinal];
IsNull := Param.IsNull;
if not IsNull then
begin
Stream := Param.AsStream;
// release ownership. Row implementations should not
// maintain ownership of objects.
//
Param.SetStream(Stream, False);
end;
end;
procedure TDBXParamsRow.GetDouble(DbxValue: TDBXDoubleValue; var Value: Double;
var IsNull: LongBool);
var
Param: TParam;
begin
Param := FParams[DbxValue.ValueType.Ordinal];
IsNull := Param.IsNull;
if not IsNull then
Value := Param.Value;
end;
procedure TDBXParamsRow.GetWideString(DbxValue: TDBXWideStringValue;
var Value: UnicodeString; var IsNull: LongBool);
var
Param: TParam;
begin
Param := FParams[DbxValue.ValueType.Ordinal];
IsNull := Param.IsNull;
if not IsNull then
Value := Param.AsWideString
else
Value := '';
end;
procedure TDBXParamsRow.GetAnsiString(DbxValue: TDBXAnsiStringValue;
var AnsiStringBuilder: PAnsiChar; var IsNull: LongBool);
var
Param: TParam;
Value: AnsiString;
begin
Param := FParams[DbxValue.ValueType.Ordinal];
IsNull := Param.IsNull;
if not IsNull then
begin
Value := Param.AsAnsiString;
TDBXPlatform.CopyStringToBuilder(Value, Length(Value)+1, AnsiStringBuilder);
end;
end;
procedure TDBXParamsRow.GetDate(DbxValue: TDBXDateValue; var Value: TDBXDate; var IsNull: LongBool);
var
Param: TParam;
begin
Param := FParams[DbxValue.ValueType.Ordinal];
IsNull := Param.IsNull;
if not IsNull then
Value := Param.Value;
end;
procedure TDBXParamsRow.GetTime(DbxValue: TDBXTimeValue; var Value: TDBXTime; var IsNull: LongBool);
var
Param: TParam;
begin
Param := FParams[DbxValue.ValueType.Ordinal];
IsNull := Param.IsNull;
if not IsNull then
Value := Param.Value;
end;
procedure TDBXParamsRow.GetTimeStamp(DbxValue: TDBXTimeStampValue;
var Value: TSQLTimeStamp; var IsNull: LongBool);
var
Param: TParam;
begin
Param := FParams[DbxValue.ValueType.Ordinal];
IsNull := Param.IsNull;
if not IsNull then
Value := Param.AsSQLTimeStamp;
end;
procedure TDBXParamsRow.GetTimeStampOffset(DbxValue: TDBXTimeStampOffsetValue;
var Value: TSQLTimeStampOffset; var IsNull: LongBool);
var
Param: TParam;
begin
Param := FParams[DbxValue.ValueType.Ordinal];
IsNull := Param.IsNull;
if not IsNull then
Value := Param.AsSQLTimeStampOffset;
end;
procedure TDBXParamsRow.GetUInt16(DbxValue: TDBXUInt16Value; var Value: Word;
var IsNull: LongBool);
var
Param: TParam;
begin
Param := FParams[DbxValue.ValueType.Ordinal];
IsNull := Param.IsNull;
if not IsNull then
Value := Param.Value;
end;
procedure TDBXParamsRow.GetUInt8(DbxValue: TDBXUInt8Value; var Value: Byte;
var IsNull: LongBool);
var
Param: TParam;
begin
Param := FParams[DbxValue.ValueType.Ordinal];
IsNull := Param.IsNull;
if not IsNull then
Value := Param.Value;
end;
procedure TDBXParamsRow.GetBcd(DbxValue: TDBXBcdValue; var Value: TBcd; var IsNull: LongBool);
var
Param: TParam;
begin
Param := FParams[DbxValue.ValueType.Ordinal];
IsNull := Param.IsNull;
if not IsNull then
Value := Param.AsFMTBCD;
end;
procedure TDBXParamsRow.GetBytes(DbxValue: TDBXByteArrayValue; Offset: Int64; const Buffer: TBytes; BufferOffset: Int64; Length: Int64; var ReturnLength: Int64; var IsNull: LongBool);
var
Param: TParam;
begin
Param := FParams[DbxValue.ValueType.Ordinal];
IsNull := Param.IsNull;
if not IsNull then
begin
if Length + BufferOffset > Param.GetDataSize then
ReturnLength := Param.GetDataSize - BufferOffset
else
ReturnLength := Length;
Move(Param.AsBytes[0], Buffer[BufferOffset], ReturnLength);
end;
end;
procedure TDBXParamsRow.GetByteLength(DbxValue: TDBXByteArrayValue; var ByteLength: Int64; var IsNull: LongBool);
var
Param: TParam;
begin
Param := FParams[DbxValue.ValueType.Ordinal];
IsNull := Param.IsNull;
if not IsNull then
ByteLength := Param.GetDataSize;
end;
procedure TDBXParamsRow.SetBoolean(DbxValue: TDBXBooleanValue; Value: Boolean);
begin
FParams[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXParamsRow.SetInt16(DbxValue: TDBXInt16Value; Value: SmallInt);
begin
FParams[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXParamsRow.SetInt32(DbxValue: TDBXInt32Value; Value: TInt32);
begin
FParams[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXParamsRow.SetInt64(DbxValue: TDBXInt64Value; Value: Int64);
begin
FParams[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXParamsRow.SetInt8(DbxValue: TDBXInt8Value; Value: ShortInt);
begin
FParams[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXParamsRow.SetDouble(DbxValue: TDBXDoubleValue; Value: Double);
begin
FParams[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXParamsRow.SetNull(DbxValue: TDBXValue);
begin
FParams[DbxValue.ValueType.Ordinal].Value := Null;
end;
procedure TDBXParamsRow.SetSingle(DbxValue: TDBXSingleValue; Value: Single);
begin
FParams[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXParamsRow.SetStream(DbxValue: TDBXStreamValue;
StreamReader: TDBXStreamReader);
var
MemoryStream: TMemoryStream;
Buffer: TBytes;
BytesRead: Integer;
begin
MemoryStream := TMemoryStream.Create;
SetLength(Buffer, 512);
BytesRead := 1;
while BytesRead > 0 do
begin
BytesRead := StreamReader.Read(Buffer, 0, Length(Buffer));
if BytesRead > 0 then
MemoryStream.Write(Buffer[0], BytesRead);
end;
MemoryStream.Seek(0, soBeginning);
FParams[DBXValue.ValueType.Ordinal].SetStream(MemoryStream, True, MemoryStream.Size);
end;
procedure TDBXParamsRow.SetString(DbxValue: TDBXAnsiStringValue;
const Value: AnsiString);
begin
FParams[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXParamsRow.SetWideString(DbxValue: TDBXWideStringValue;
const Value: UnicodeString);
begin
FParams[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXParamsRow.SetAnsiString(DbxValue: TDBXAnsiStringValue; const Value: AnsiString);
begin
FParams[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXParamsRow.SetDate(DbxValue: TDBXDateValue; Value: TDBXDate);
begin
FParams[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXParamsRow.SetTime(DbxValue: TDBXTimeValue; Value: TDBXTime);
begin
FParams[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXParamsRow.SetTimestamp(DbxValue: TDBXTimeStampValue;
var Value: TSQLTimeStamp);
begin
if DbxValue.ValueType.DataType = TDBXDataTypes.DateTimeType then
FParams[DBXValue.ValueType.Ordinal].AsDateTime := SQLTimeStampToDateTime(Value)
else
FParams[DbxValue.ValueType.Ordinal].AsSQLTimeStamp := Value;
end;
procedure TDBXParamsRow.SetTimestampOffset(DbxValue: TDBXTimeStampOffsetValue;
var Value: TSQLTimeStampOffset);
begin
if DbxValue.ValueType.DataType = TDBXDataTypes.DateTimeType then
FParams[DBXValue.ValueType.Ordinal].AsDateTime := SQLTimeStampOffsetToDateTime(Value)
else
FParams[DbxValue.ValueType.Ordinal].AsSQLTimeStampOffset := Value;
end;
procedure TDBXParamsRow.SetUInt16(DbxValue: TDBXUInt16Value; Value: Word);
begin
FParams[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXParamsRow.SetUInt8(DbxValue: TDBXUInt8Value; Value: Byte);
begin
FParams[DbxValue.ValueType.Ordinal].Value := Value;
end;
procedure TDBXParamsRow.SetBCD(DbxValue: TDBXBcdValue; var Value: TBcd);
begin
FParams[DbxValue.ValueType.Ordinal].AsFMTBCD := Value;
end;
procedure TDBXParamsRow.ValueSet(Value: TDBXWritableValue);
begin
TDBXDriverHelp.SetPendingValue(Value);
end;
constructor TDBXParamsTable.Create;
begin
FParams := TParams.Create(nil);
Inherited Create(nil, TDBXParamsRow.Create(FParams));
end;
constructor TDBXParamsTable.Create(Params: TParams; InstanceOwner: Boolean);
begin
Inherited Create(nil, TDBXParamsRow.Create(Params));
FParams := Params;
FInstanceOwner := InstanceOwner;
CreateValues;
end;
destructor TDBXParamsTable.Destroy;
begin
if FInstanceOwner then
FreeAndNil(FParams);
FreeValueTypes;
inherited Destroy;
end;
function TDBXParamsTable.First;
begin
RowNavigated;
FAtEnd := False;
Result := true;
end;
function TDBXParamsTable.Next: Boolean;
begin
FAtEnd := True;
Result := False;
// if FAtEnd then
// Result := false
// else
// begin
// FAtEnd := true;
// Result := true;
// end;
end;
function TDBXParamsTable.InBounds: Boolean;
begin
Result := not FAtEnd;
end;
procedure TDBXParamsTable.Close;
begin
end;
function TDBXParamsTable.GetOrdinal(const ColumnName: UnicodeString): Integer;
begin
Result := FParams.ParamByName(ColumnName).Index;
end;
function TDBXParamsTable.GetColumns: TDBXValueTypeArray;
var
Ordinal: Integer;
Param: TParam;
ValueType: TDBXValueType;
begin
if FValueTypes = nil then
begin
SetLength(FValueTypes, FParams.Count);
for Ordinal := Low(FValueTypes) to High(FValueTypes) do
begin
Param := FParams[Ordinal];
ValueType := TDBXValueType.Create(DBXContext);
ValueType.Name := Param.Name;
ValueType.DisplayName := Param.DisplayName;
ValueType.DataType := ToDataType(Param.DataType);
ValueType.SubType := ToDataSubType(Param.DataType);
ValueType.Precision := Param.Precision;
ValueType.Scale := Param.NumericScale;
ValueType.Size := Param.GetDataSize;
ValueType.ParameterDirection := ToDBXParameterDirection(Param.ParamType);
FValueTypes[Ordinal] := ValueType;
end;
end;
Result := FValueTypes;
end;
procedure TDBXParamsTable.SetColumns(const Columns: TDBXValueTypeArray);
begin
FreeValueTypes;
FValueTypes := Columns;
if FParams <> nil then
CopyValueTypes(Columns, FParams);
end;
class procedure TDBXParamsTable.CopyValueTypes(const ValueTypes: TDBXValueTypeArray; const Params: TParams);
var
Ordinal: Integer;
begin
Params.Clear;
for Ordinal := Low(ValueTypes) to High(ValueTypes) do
begin
if Ordinal >= Params.Count then
CopyValueType(Ordinal, ValueTypes[Ordinal], Params[Ordinal])
else if not(Params[Ordinal].Name = ValueTypes[Ordinal].Name) then
raise TDBXError.Create(SMustKeepOriginalColumnOrder);
end;
end;
function TDBXParamsTable.GetStorage: TObject;
begin
Result := FParams;
end;
class procedure TDBXParamsTable.CopyValueType(Ordinal: Integer; ValueType: TDBXValueType; Param: TParam);
begin
Param.Name := ValueType.Name;
Param.DisplayName := ValueType.DisplayName;
Param.DataType := ToFieldType(ValueType);
Param.ParamType := ToParameterType(ValueType.ParameterDirection);
Param.Precision := ValueType.Precision;
Param.NumericScale := ValueType.Scale;
Param.Size := ValueType.Size;
// if ValueType.DataType = TDBXDataTypes.WideStringType then
// begin
// if ValueType.Size <= 0 then
// Param.Size := 128 // default size (make constant)
// else
// Param.Size := ValueType.Size;
// end;
end;
procedure TDBXDBTable.FreeValueTypes;
begin
ClearValues;
FValueTypes := nil;
end;
class function TDBXDBTable.ToDataSubType(FieldType: TFieldType): Integer;
begin
case FieldType of
ftWideMemo:
Result := TDBXDataTypes.WideMemoSubType;
else
Result := 0;
end;
end;
class function TDBXDBTable.ToDataType(FieldType: TFieldType): Integer;
begin
case FieldType of
ftBoolean:
Result := TDBXDataTypes.BooleanType;
ftByte:
Result := TDBXDataTypes.UInt8Type;
ftShortint:
Result := TDBXDataTypes.Int8Type;
ftSmallInt:
Result := TDBXDataTypes.Int16Type;
ftInteger, ftAutoInc:
Result := TDBXDataTypes.Int32Type;
ftLargeint:
Result := TDBXDataTypes.Int64Type;
ftSingle:
Result := TDBXDataTypes.SingleType;
ftFloat:
Result := TDBXDataTypes.DoubleType;
ftGuid, ftOraInterval:
Result := TDBXDataTypes.AnsiStringType;
ftString, ftFixedChar:
Result := TDBXDataTypes.AnsiStringType;
ftWideString, ftFixedWideChar:
Result := TDBXDataTypes.WideStringType;
ftMemo, ftWideMemo, ftBlob, ftGraphic, ftFmtMemo, ftParadoxOle, ftDBaseOle,
ftTypedBinary, ftOraBlob, ftOraClob:
Result := TDBXDataTypes.BlobType;
ftFMTBcd:
Result := TDBXDataTypes.BcdType;
ftBcd:
Result := TDBXDataTypes.CurrencyType;
ftBytes:
Result := TDBXDataTypes.BytesType;
ftDate:
Result := TDBXDataTypes.DateType;
ftTime:
Result := TDBXDataTypes.TimeType;
ftTimeStamp, ftOraTimeStamp:
Result := TDBXDataTypes.TimeStampType;
ftTimeStampOffset:
Result := TDBXDataTypes.TimeStampOffsetType;
ftDateTime:
Result := TDBXDataTypes.DateTimeType;
ftStream:
Result := TDBXDataTypes.BinaryBlobType;
ftVarBytes:
Result := TDBXDataTypes.VarBytesType;
ftWord:
Result := TDBXDataTypes.UInt16Type;
ftCurrency:
Result := TDBXDataTypes.DoubleType; // TDBXDataTypes.CurrencyType;
ftCursor:
Result := TDBXDataTypes.CursorType;
ftADT:
Result := TDBXDataTypes.AdtType;
ftArray:
Result := TDBXDataTypes.ArrayType;
ftReference:
Result := TDBXDataTypes.RefType;
ftDataSet, ftParams:
Result := TDBXDataTypes.TableType;
ftVariant:
Result := TDBXDataTypes.VariantType;
ftConnection:
Result := TDBXDataTypes.DBXConnectionType;
{
ftDataSet:
Result := TDBXDataTypes.TableType;
}
else
raise TDBXError.Create(SUnexpectedMetaDataType);
end;
end;
constructor TDBXClientDataSetTable.Create(const CollectionName: UnicodeString;
TableColumns: TDBXValueTypeArray; Table: TClientDataSet; OwnsTable: Boolean);
begin
inherited Create(CollectionName, Table, OwnsTable, False);
Columns := TableColumns;
FClientDataset := Table;
end;
constructor TDBXClientDataSetTable.Create;
begin
Create('', nil, TClientDataSet.Create(nil), true);
end;
constructor TDBXClientDataSetTable.Create(ClientDataSet: TClientDataSet;
OwnsTable: Boolean);
begin
Create('', nil, ClientDataSet, OwnsTable);
end;
{ TDBXClientDataSetReader }
class function TDBXDataSetReader.ToClientDataSet(AOwner: TComponent; Reader: TDBXReader; AOwnsInstance: Boolean): TClientDataSet;
begin
Result := TClientDataSet.Create(AOwner);
CopyReaderToClientDataSet(Reader, Result);
if AOwnsInstance then
Reader.Free;
end;
class procedure TDBXDataSetReader.CopyReaderToClientDataSet(
Reader: TDBXReader; DataSet: TClientDataSet);
var
Ordinal: Integer;
Table: TDBXTable;
ValueTypes: TDBXValueTypeArray;
ColumnCount: Integer;
begin
ColumnCount := Reader.ColumnCount;
SetLength(ValueTypes, Reader.ColumnCount);
for Ordinal := 0 to ColumnCount - 1 do
begin
ValueTypes[Ordinal] := Reader.ValueType[Ordinal].WritableClone;
end;
Table := TDBXClientDataSetTable.Create('', nil, DataSet, False);
Table.Columns := ValueTypes;
try
while Reader.Next do
begin
Table.Insert;
for Ordinal := 0 to ColumnCount - 1 do
Table.Value[Ordinal].SetValue(Reader.Value[Ordinal]);
Table.Post;
end;
finally
Table.Free;
end;
end;
constructor TDBXDataSetReader.Create(Params: TDataset; InstanceOwner: Boolean);
begin
if Params is TClientDataSet then
inherited Create(TDBXClientDataSetTable.Create(Params.Name, nil, TClientDataSet(Params), InstanceOwner))
else
inherited Create(TDBXDataSetTable.Create(Params.Name, Params, InstanceOwner, true))
end;
destructor TDBXDataSetReader.Destroy;
begin
inherited;
end;
{ TDBXParamsReader }
class procedure TDBXParamsReader.CopyReaderToParams(Reader: TDBXReader;
Params: TParams);
var
Ordinal: Integer;
Count: Integer;
Param: TParam;
DBXRow: TDBXParamsRow;
begin
Reader.Next;
Params.Clear;
Count := Reader.ColumnCount;
for Ordinal := 0 to Count - 1 do
begin
Param := TParam.Create(Params);
TDBXParamsTable.CopyValueType(Ordinal, Reader.ValueType[Ordinal], Param);
end;
DBXRow := TDBXParamsRow.Create(Params);
try
for Ordinal := 0 to Count - 1 do
begin
TDBXDriverHelp.CopyRowValue(Reader.Value[Ordinal], DBXRow);
end;
finally
FreeAndNil(DBXRow);
end;
end;
class function TDBXParamsReader.ToParams(AOwner: TPersistent; Reader: TDBXReader; AOwnsInstance: Boolean): TParams;
begin
Result := TParams.Create(AOwner);
CopyReaderToParams(Reader, Result);
if AOwnsInstance then
Reader.Free;
end;
constructor TDBXParamsReader.Create(Params: TParams; InstanceOwner: Boolean);
begin
inherited Create(TDBXParamsTable.Create(Params, InstanceOwner));
end;
destructor TDBXParamsReader.Destroy;
begin
inherited;
end;
class function TDBXDBTable.ToFieldType(ValueType: TDBXValueType): TFieldType;
begin
case ValueType.DataType of
TDBXDataTypes.BooleanType:
Result := ftBoolean;
TDBXDataTypes.UInt8Type:
Result := ftByte;
TDBXDataTypes.Int8Type:
Result := ftShortint;
TDBXDataTypes.Int16Type:
Result := ftSmallInt;
TDBXDataTypes.Int32Type:
Result := ftInteger;
TDBXDataTypes.Int64Type:
Result := ftLargeint;
TDBXDataTypes.SingleType:
Result := ftSingle;
TDBXDataTypes.DoubleType:
Result := ftFloat;
TDBXDataTypes.WideStringType:
// Switched back to this because metadata layer cannot create
// Unicode identifiers without it. If there ar issues, we need
// to find the root cause. TClientDataSet does support Unicode.
//
Result := ftWideString; // All strings are truncated to the empty string (bug!)
// Result := ftWideMemo; // Cannot create an index for this column type (needed for keyword search)
// Result := ftString; // Cannot hold unicode chars (bad)
TDBXDataTypes.AnsiStringType:
Result := ftString;
TDBXDataTypes.DateType:
Result := ftDate;
TDBXDataTypes.TimeStampType:
Result := ftTimeStamp;
TDBXDataTypes.TimeStampOffsetType:
Result := ftTimeStampOffset;
TDBXDataTypes.BlobType:
case ValueType.SubType of
TDBXDataTypes.WideMemoSubType:
Result := ftWideMemo;
else
Result := ftBlob;
end;
TDBXDataTypes.BcdType:
Result := ftFMTBcd;
TDBXDataTypes.CurrencyType:
Result := ftCurrency;
TDBXDataTypes.BytesType:
Result := ftBytes;
TDBXDataTypes.TimeType:
Result := ftTime;
TDBXDataTypes.BinaryBlobType:
Result := ftStream;
TDBXDataTypes.UInt16Type:
Result := ftWord;
TDBXDataTypes.CursorType:
Result := ftCursor;
TDBXDataTypes.AdtType:
Result := ftADT;
TDBXDataTypes.ArrayType:
Result := ftArray;
TDBXDataTypes.RefType:
Result := ftReference;
TDBXDataTypes.TableType:
Result := ftDataSet;
TDBXDataTypes.VariantType:
Result := ftVariant;
TDBXDataTypes.VarBytesType:
Result := ftVarBytes;
TDBXDataTypes.DBXConnectionType:
Result := ftConnection;
TDBXDataTypes.DateTimeType:
Result := ftDateTime;
else
raise TDBXError.Create(SUnexpectedMetaDataType);
end;
end;
function TDBXDBTable.GetDBXTableName: UnicodeString;
begin
Result := FCollectionName;
end;
procedure TDBXDBTable.SetDBXTableName(const CollectionName: UnicodeString);
begin
FCollectionName := CollectionName;
end;
class function TDBXDBTable.ToDBXParameterDirection(ParameterType: TParamType): Integer;
begin
case ParameterType of
ptInput: Result := TDBXParameterDirections.InParameter;
ptOutput: Result := TDBXParameterDirections.OutParameter;
ptInputOutput: Result := TDBXParameterDirections.InOutParameter;
ptResult: Result := TDBXParameterDirections.ReturnParameter;
else
Result := TDBXParameterDirections.Unknown;
end;
end;
class function TDBXDBTable.ToParameterType(ParameterDirection: Integer): TParamType;
begin
case ParameterDirection of
TDBXParameterDirections.InParameter: Result := ptInput;
TDBXParameterDirections.OutParameter: Result := ptOutput;
TDBXParameterDirections.InOutParameter: Result := ptInputOutput;
TDBXParameterDirections.ReturnParameter: Result := ptResult;
else
Result := ptUnknown;
end;
end;
{ TDBXMemoryTable }
procedure TDBXMemoryTable.AcceptChanges;
begin
// do nothing for memory tables
end;
procedure TDBXMemoryTable.ClearValues(AValues: TDBXWritableValueArray);
var
Value: TDBXWritableValue;
begin
for Value in AValues do
Value.Free;
SetLength(AValues, 0);
end;
procedure TDBXMemoryTable.ClearValueTypes(AValueTypes: TDBXValueTypeArray);
var
ValueType: TDBXValueType;
begin
for ValueType in AValueTypes do
ValueType.Free;
SetLength(AValueTypes, 0);
end;
constructor TDBXMemoryTable.Create;
begin
FValueRows := TList<TDBXWritableValueArray>.Create;
FIndex := 0;
FOrderByColumn := -1;
end;
function TDBXMemoryTable.CreateTableView(
const OrderByColumnName: UnicodeString): TDBXTable;
var
Column: Integer;
begin
// get the column index
Column := ColumnIndex(OrderByColumnName);
if Column = -1 then
raise TDBXError.Create(Format(SInvalidOrderByColumn, [OrderByColumnName]));
Result := TDBXMemoryTable.Create;
Result.Columns := CopyColumns;
FIndex := -1;
Result.CopyFrom(self);
// sort the list based on the column value
(Result as TDBXMemoryTable).OrderByColumn(Column);
end;
function TDBXMemoryTable.CreateWritableValueArray: TDBXWritableValueArray;
var
Value: TDBXWritableValue;
Values: TDBXWritableValueArray;
Ordinal: Integer;
begin
SetLength(Values, Length(Columns));
for Ordinal := 0 to Length(Values) - 1 do
begin
if Columns[Ordinal] <> nil then
begin
// Note that we must clone the column here because a TDBXValue owns the TDBXValueType.
// Would be nice to add ownership control
Value := TDBXWritableValue(TDBXValue.CreateValue(nil, Columns[Ordinal].Clone, nil, False));
Value.ValueType.Ordinal := Ordinal;
Values[Ordinal] := Value;
end;
end;
Result := Values;
end;
destructor TDBXMemoryTable.Destroy;
var
I: Integer;
begin
// Free rows
for I := 0 to FValueRows.Count - 1 do
begin
ClearValues(FValueRows[I]);
FValueRows[I] := nil;
end;
// Prevent ancestor from freeing current row
SetValues(TDBXWritableValueArray(nil));
FValueRows.Free;
// Free column types
ClearValueTypes(FValueTypes);
inherited;
end;
function TDBXMemoryTable.FindStringKey(const Ordinal: Integer;
const Value: UnicodeString): Boolean;
var
refRow: TDBXWritableValueArray;
Comparer: TDBXWritableValueArrayComparer;
begin
// false for an empty table
if FValueRows.Count = 0 then
exit(False);
// sort if not sorted on the column, thinking is there is a repeat
if Ordinal <> FOrderByColumn then
OrderByColumn(Ordinal);
// prepare the reference row, only Ordinal column is important
SetLength(refRow, Ordinal + 1);
refRow[Ordinal] := TDBXValue.CreateValue(FValueRows[0][Ordinal].ValueType.Clone);
refRow[Ordinal].AsString := Value;
// allocate the comparer and perform a binary search
// if success, move index to the found column
Comparer := TDBXWritableValueArrayComparer.Create(Ordinal);
Result := FValueRows.BinarySearch(refRow, FIndex, Comparer);
if Result then
SetValues(FValueRows[FIndex]);
// clean up
Comparer.Free;
refRow[Ordinal].Free;
end;
function TDBXMemoryTable.First: Boolean;
begin
FIndex := 0;
Result := FIndex < FValueRows.Count;
if Result then
SetValues(FValueRows[FIndex]);
end;
function TDBXMemoryTable.GetColumns: TDBXValueTypeArray;
begin
Result := FValueTypes;
end;
function TDBXMemoryTable.GetDBXTableName: string;
begin
Result := FName;
end;
function TDBXMemoryTable.GetTableCount: Integer;
begin
Result := FValueRows.Count
end;
function TDBXMemoryTable.InBounds: Boolean;
begin
Result := (FIndex >= 0) and (FIndex < FValueRows.Count);
end;
procedure TDBXMemoryTable.Insert;
var
LRow: TDBXWritableValueArray;
begin
LRow := CreateWritableValueArray;
SetValues(LRow, Length(LRow));
FValueRows.Add(LRow);
FIndex := FValueRows.Count - 1;
end;
function TDBXMemoryTable.Next: Boolean;
begin
Inc(FIndex);
Result := FIndex < FValueRows.Count;
if Result then
SetValues(FValueRows[FIndex]);
end;
procedure TDBXMemoryTable.OrderByColumn(Column: Integer);
var
Comparer: TDBXWritableValueArrayComparer;
begin
Comparer := TDBXWritableValueArrayComparer.Create(Column);
try
FValueRows.Sort(Comparer);
FOrderByColumn := Column;
finally
Comparer.Free;
end;
end;
procedure TDBXMemoryTable.Post;
begin
// Nothing to do because data is written to the actual row rather than a buffer row
end;
procedure TDBXMemoryTable.SetColumns(const Columns: TDBXValueTypeArray);
begin
FValueTypes := Columns;
end;
procedure TDBXMemoryTable.SetDBXTableName(const AName: UnicodeString);
begin
FName := AName;
end;
{ TDBXWritableValueArrayComparer }
function TDBXWritableValueArrayComparer.Compare(const Left, Right: TDBXWritableValueArray): Integer;
var
LeftValue, RightValue: TDBXValue;
begin
LeftValue := Left[ColumnIndex];
RightValue := Right[ColumnIndex];
if LeftValue.IsNull or RightValue.IsNull then
if LeftValue.IsNull then
if RightValue.IsNull then
Result := 0
else
Result := -1
else
Result := 1
else
Result := LeftValue.Compare(RightValue);
end;
constructor TDBXWritableValueArrayComparer.Create(AColumnIndex: Integer);
begin
FColumnIndex := AColumnIndex;
end;
{ TDBXDataSetRowExt }
procedure TDBXDataSetRowExt.SetDynamicBytes(DbxValue: TDBXValue; Offset: Int64;
const Buffer: TBytes; BufferOffset, Length: Int64);
var
LData: TBytes;
begin
EnsureEditState;
SetLength(LData, Length);
TDBXPlatform.CopyByteArray(Buffer, BufferOffset, LData, 0, Length);
FTable.Fields[DbxValue.ValueType.Ordinal].AsBytes := LData;
end;
end.
|
unit PlayerThreads;
{$mode objfpc}{$H+}
interface
uses
{$ifdef unix}
cthreads,
cmem,
{$endif}
Classes, SysUtils, CpuCount;
type
TPlayerThread = class;
TCustomPlayerThread = class(TThread)
public
property Terminated;
end;
{ TPlayerThreadManager }
TPlayerThreadManager = class(TCustomPlayerThread)
private
FEvent, FStopEvent: pRTLEvent;
FList: TThreadList;
FForceTerminated: Boolean;
FMaxThreadCount: Integer;
protected
procedure Execute; override;
function GetNextThread: TPlayerThread; virtual;
function GetMaxThreadCount: Integer; virtual;
procedure Process(AFinishedThread: TPlayerThread = nil);
public
constructor Create;
destructor Destroy; override;
procedure Interrupt(const Force: Boolean = False); virtual;
property ThreadList: TThreadList read FList;
property MaxThreadCount: Integer read FMaxThreadCount;
end;
{ TPlayerThread }
TPlayerThread = class(TCustomPlayerThread)
private
FManager: TPlayerThreadManager;
public
constructor Create(AManager: TPlayerThreadManager);
destructor Destroy; override;
property Manager: TPlayerThreadManager read FManager;
end;
implementation
{ TPlayerThread }
constructor TPlayerThread.Create(AManager: TPlayerThreadManager);
begin
FreeOnTerminate:=True;
FManager:=AManager;
inherited Create(True);
end;
destructor TPlayerThread.Destroy;
begin
FManager.Process(Self);
inherited;
end;
{ TPlayerThreadManager }
procedure TPlayerThreadManager.Execute;
var
List: TList;
Index: Integer;
begin
Process;
RtlEventWaitFor(FEvent);
Terminate;
List:=FList.LockList;
try
if List.Count = 0 then Exit;
if FForceTerminated then
for Index:=0 to List.Count - 1 do
TThread(List[Index]).Terminate;
finally
FList.UnlockList;
end;
RTLeventWaitFor(FStopEvent);
end;
function TPlayerThreadManager.GetNextThread: TPlayerThread;
begin
Result:=nil;
end;
function TPlayerThreadManager.GetMaxThreadCount: Integer;
begin
Result:=GetLogicalCpuCount;
end;
procedure TPlayerThreadManager.Process(AFinishedThread: TPlayerThread);
var
List: TList;
NextThread: TPlayerThread;
Stop: Boolean;
begin
List:=FList.LockList;
try
Stop:=Terminated or not (List.Count < MaxThreadCount);
if AFinishedThread <> nil then
begin
List.Remove(AFinishedThread);
if List.Count = 0 then
RtlEventSetEvent(FStopEvent);
end;
if Stop then Exit;
repeat
NextThread:=GetNextThread;
if NextThread <> nil then
begin
List.Add(NextThread);
NextThread.Start;
end;
until (NextThread = nil) or Terminated or not (List.Count < MaxThreadCount);
if NextThread = nil then Interrupt;
finally
FList.UnlockList;
end;
end;
constructor TPlayerThreadManager.Create;
begin
FMaxThreadCount:=GetMaxThreadCount;
FList:=TThreadList.Create;
FEvent:=RTLEventCreate;
FStopEvent:=RTLEventCreate;
FForceTerminated:=False;
FreeOnTerminate:=False;
inherited Create(True);
end;
destructor TPlayerThreadManager.Destroy;
begin
FList.Free;
RTLeventdestroy(FEvent);
RTLeventdestroy(FStopEvent);
inherited;
end;
procedure TPlayerThreadManager.Interrupt(const Force: Boolean);
begin
FForceTerminated:=Force;
Terminate;
RtlEventSetEvent(FEvent);
end;
end.
|
unit ScrollBarImpl1;
interface
uses
Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls,
ComServ, StdVCL, AXCtrls, DelCtrls_TLB;
type
TScrollBarX = class(TActiveXControl, IScrollBarX)
private
{ Private declarations }
FDelphiControl: TScrollBar;
FEvents: IScrollBarXEvents;
procedure ChangeEvent(Sender: TObject);
procedure KeyPressEvent(Sender: TObject; var Key: Char);
procedure ScrollEvent(Sender: TObject; ScrollCode: TScrollCode;
var ScrollPos: Integer);
protected
{ Protected declarations }
procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override;
procedure EventSinkChanged(const EventSink: IUnknown); override;
procedure InitializeControl; override;
function ClassNameIs(const Name: WideString): WordBool; safecall;
function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall;
function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall;
function Get_BiDiMode: TxBiDiMode; safecall;
function Get_Ctl3D: WordBool; safecall;
function Get_Cursor: Smallint; safecall;
function Get_DoubleBuffered: WordBool; safecall;
function Get_DragCursor: Smallint; safecall;
function Get_DragMode: TxDragMode; safecall;
function Get_Enabled: WordBool; safecall;
function Get_Kind: TxScrollBarKind; safecall;
function Get_LargeChange: Smallint; safecall;
function Get_Max: Integer; safecall;
function Get_Min: Integer; safecall;
function Get_PageSize: Integer; safecall;
function Get_ParentCtl3D: WordBool; safecall;
function Get_Position: Integer; safecall;
function Get_SmallChange: Smallint; safecall;
function Get_Visible: WordBool; safecall;
function GetControlsAlignment: TxAlignment; safecall;
function IsRightToLeft: WordBool; safecall;
function UseRightToLeftAlignment: WordBool; safecall;
function UseRightToLeftReading: WordBool; safecall;
function UseRightToLeftScrollBar: WordBool; safecall;
procedure AboutBox; safecall;
procedure FlipChildren(AllLevels: WordBool); safecall;
procedure InitiateAction; safecall;
procedure Set_BiDiMode(Value: TxBiDiMode); safecall;
procedure Set_Ctl3D(Value: WordBool); safecall;
procedure Set_Cursor(Value: Smallint); safecall;
procedure Set_DoubleBuffered(Value: WordBool); safecall;
procedure Set_DragCursor(Value: Smallint); safecall;
procedure Set_DragMode(Value: TxDragMode); safecall;
procedure Set_Enabled(Value: WordBool); safecall;
procedure Set_Kind(Value: TxScrollBarKind); safecall;
procedure Set_LargeChange(Value: Smallint); safecall;
procedure Set_Max(Value: Integer); safecall;
procedure Set_Min(Value: Integer); safecall;
procedure Set_PageSize(Value: Integer); safecall;
procedure Set_ParentCtl3D(Value: WordBool); safecall;
procedure Set_Position(Value: Integer); safecall;
procedure Set_SmallChange(Value: Smallint); safecall;
procedure Set_Visible(Value: WordBool); safecall;
procedure SetParams(APosition, AMin, AMax: Integer); safecall;
end;
implementation
uses ComObj, About27;
{ TScrollBarX }
procedure TScrollBarX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage);
begin
{ Define property pages here. Property pages are defined by calling
DefinePropertyPage with the class id of the page. For example,
DefinePropertyPage(Class_ScrollBarXPage); }
end;
procedure TScrollBarX.EventSinkChanged(const EventSink: IUnknown);
begin
FEvents := EventSink as IScrollBarXEvents;
end;
procedure TScrollBarX.InitializeControl;
begin
FDelphiControl := Control as TScrollBar;
FDelphiControl.OnChange := ChangeEvent;
FDelphiControl.OnKeyPress := KeyPressEvent;
FDelphiControl.OnScroll := ScrollEvent;
end;
function TScrollBarX.ClassNameIs(const Name: WideString): WordBool;
begin
Result := FDelphiControl.ClassNameIs(Name);
end;
function TScrollBarX.DrawTextBiDiModeFlags(Flags: Integer): Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlags(Flags);
end;
function TScrollBarX.DrawTextBiDiModeFlagsReadingOnly: Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly;
end;
function TScrollBarX.Get_BiDiMode: TxBiDiMode;
begin
Result := Ord(FDelphiControl.BiDiMode);
end;
function TScrollBarX.Get_Ctl3D: WordBool;
begin
Result := FDelphiControl.Ctl3D;
end;
function TScrollBarX.Get_Cursor: Smallint;
begin
Result := Smallint(FDelphiControl.Cursor);
end;
function TScrollBarX.Get_DoubleBuffered: WordBool;
begin
Result := FDelphiControl.DoubleBuffered;
end;
function TScrollBarX.Get_DragCursor: Smallint;
begin
Result := Smallint(FDelphiControl.DragCursor);
end;
function TScrollBarX.Get_DragMode: TxDragMode;
begin
Result := Ord(FDelphiControl.DragMode);
end;
function TScrollBarX.Get_Enabled: WordBool;
begin
Result := FDelphiControl.Enabled;
end;
function TScrollBarX.Get_Kind: TxScrollBarKind;
begin
Result := Ord(FDelphiControl.Kind);
end;
function TScrollBarX.Get_LargeChange: Smallint;
begin
Result := Smallint(FDelphiControl.LargeChange);
end;
function TScrollBarX.Get_Max: Integer;
begin
Result := FDelphiControl.Max;
end;
function TScrollBarX.Get_Min: Integer;
begin
Result := FDelphiControl.Min;
end;
function TScrollBarX.Get_PageSize: Integer;
begin
Result := FDelphiControl.PageSize;
end;
function TScrollBarX.Get_ParentCtl3D: WordBool;
begin
Result := FDelphiControl.ParentCtl3D;
end;
function TScrollBarX.Get_Position: Integer;
begin
Result := FDelphiControl.Position;
end;
function TScrollBarX.Get_SmallChange: Smallint;
begin
Result := Smallint(FDelphiControl.SmallChange);
end;
function TScrollBarX.Get_Visible: WordBool;
begin
Result := FDelphiControl.Visible;
end;
function TScrollBarX.GetControlsAlignment: TxAlignment;
begin
Result := TxAlignment(FDelphiControl.GetControlsAlignment);
end;
function TScrollBarX.IsRightToLeft: WordBool;
begin
Result := FDelphiControl.IsRightToLeft;
end;
function TScrollBarX.UseRightToLeftAlignment: WordBool;
begin
Result := FDelphiControl.UseRightToLeftAlignment;
end;
function TScrollBarX.UseRightToLeftReading: WordBool;
begin
Result := FDelphiControl.UseRightToLeftReading;
end;
function TScrollBarX.UseRightToLeftScrollBar: WordBool;
begin
Result := FDelphiControl.UseRightToLeftScrollBar;
end;
procedure TScrollBarX.AboutBox;
begin
ShowScrollBarXAbout;
end;
procedure TScrollBarX.FlipChildren(AllLevels: WordBool);
begin
FDelphiControl.FlipChildren(AllLevels);
end;
procedure TScrollBarX.InitiateAction;
begin
FDelphiControl.InitiateAction;
end;
procedure TScrollBarX.Set_BiDiMode(Value: TxBiDiMode);
begin
FDelphiControl.BiDiMode := TBiDiMode(Value);
end;
procedure TScrollBarX.Set_Ctl3D(Value: WordBool);
begin
FDelphiControl.Ctl3D := Value;
end;
procedure TScrollBarX.Set_Cursor(Value: Smallint);
begin
FDelphiControl.Cursor := TCursor(Value);
end;
procedure TScrollBarX.Set_DoubleBuffered(Value: WordBool);
begin
FDelphiControl.DoubleBuffered := Value;
end;
procedure TScrollBarX.Set_DragCursor(Value: Smallint);
begin
FDelphiControl.DragCursor := TCursor(Value);
end;
procedure TScrollBarX.Set_DragMode(Value: TxDragMode);
begin
FDelphiControl.DragMode := TDragMode(Value);
end;
procedure TScrollBarX.Set_Enabled(Value: WordBool);
begin
FDelphiControl.Enabled := Value;
end;
procedure TScrollBarX.Set_Kind(Value: TxScrollBarKind);
begin
FDelphiControl.Kind := TScrollBarKind(Value);
end;
procedure TScrollBarX.Set_LargeChange(Value: Smallint);
begin
FDelphiControl.LargeChange := TScrollBarInc(Value);
end;
procedure TScrollBarX.Set_Max(Value: Integer);
begin
FDelphiControl.Max := Value;
end;
procedure TScrollBarX.Set_Min(Value: Integer);
begin
FDelphiControl.Min := Value;
end;
procedure TScrollBarX.Set_PageSize(Value: Integer);
begin
FDelphiControl.PageSize := Value;
end;
procedure TScrollBarX.Set_ParentCtl3D(Value: WordBool);
begin
FDelphiControl.ParentCtl3D := Value;
end;
procedure TScrollBarX.Set_Position(Value: Integer);
begin
FDelphiControl.Position := Value;
end;
procedure TScrollBarX.Set_SmallChange(Value: Smallint);
begin
FDelphiControl.SmallChange := TScrollBarInc(Value);
end;
procedure TScrollBarX.Set_Visible(Value: WordBool);
begin
FDelphiControl.Visible := Value;
end;
procedure TScrollBarX.SetParams(APosition, AMin, AMax: Integer);
begin
FDelphiControl.SetParams(APosition, AMin, AMax);
end;
procedure TScrollBarX.ChangeEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnChange;
end;
procedure TScrollBarX.KeyPressEvent(Sender: TObject; var Key: Char);
var
TempKey: Smallint;
begin
TempKey := Smallint(Key);
if FEvents <> nil then FEvents.OnKeyPress(TempKey);
Key := Char(TempKey);
end;
procedure TScrollBarX.ScrollEvent(Sender: TObject; ScrollCode: TScrollCode;
var ScrollPos: Integer);
var
TempScrollPos: Integer;
begin
TempScrollPos := Integer(ScrollPos);
if FEvents <> nil then FEvents.OnScroll(TxScrollCode(ScrollCode), TempScrollPos);
ScrollPos := Integer(TempScrollPos);
end;
initialization
TActiveXControlFactory.Create(
ComServer,
TScrollBarX,
TScrollBar,
Class_ScrollBarX,
27,
'{695CDBA8-02E5-11D2-B20D-00C04FA368D4}',
0,
tmApartment);
end.
|
unit MediaStream.Framer.HV;
interface
uses Windows,SysUtils,Classes,MediaProcessing.Definitions,MediaStream.Framer,H264Parser;
type
TStreamFramerHV = class (TStreamFramer)
private
FStream : TStream;
FH264Parser: TH264Parser;
FBuffer: TBytes;
public
constructor Create; override;
destructor Destroy; override;
procedure OpenStream(aStream: TStream); override;
function GetNextFrame(out aOutFormat: TMediaStreamDataHeader; out aOutData: pointer; out aOutDataSize: cardinal; out aOutInfo: pointer; out aOutInfoSize: cardinal):boolean; override;
function VideoStreamType: TStreamType; override;
function AudioStreamType: TStreamType; override;
function StreamInfo: TBytes; override;
end;
implementation
uses HikVisionAPI;
{ TStreamFramerHV }
constructor TStreamFramerHV.Create;
begin
inherited;
FH264Parser:=TH264Parser.Create;
end;
destructor TStreamFramerHV.Destroy;
begin
FStream:=nil;
FreeAndNil(FH264Parser);
inherited;
end;
function TStreamFramerHV.GetNextFrame(out aOutFormat: TMediaStreamDataHeader; out aOutData: pointer; out aOutDataSize: cardinal; out aOutInfo: pointer; out aOutInfoSize: cardinal): boolean;
var
aFrameType: FrameType_t;
aDataSize: cardinal;
begin
Assert(FStream<>nil);
if FStream.Read(aFrameType,sizeof(aFrameType))<sizeof(aFrameType) then
exit(false);
FStream.ReadBuffer(aDataSize,sizeof(aDataSize));
if cardinal(Length(FBuffer))<aDataSize then
SetLength(FBuffer,aDataSize*3 div 2);
FStream.ReadBuffer(FBuffer[0],aDataSize);
aOutFormat.Clear;
if aFrameType = PktAudioFrames then
aOutFormat.biMediaType:=mtAudio
else if aFrameType in [PktIFrames,PktPFrames] then
aOutFormat.biMediaType:=mtVideo
else begin
result:=GetNextFrame(aOutFormat,aOutData,aOutDataSize,aOutInfo,aOutInfoSize);
exit;
end;
aOutData:=FBuffer;
aOutDataSize:=aDataSize;
if aOutFormat.biMediaType=mtVideo then
begin
result:=HikVisionGetH264Data(aOutData,aOutDataSize);
if not result then
exit;
aOutFormat.biStreamType:=stH264;
aOutFormat.VideoWidth:=FH264Parser.LastParams.PictureWidth;
aOutFormat.VideoHeight:=FH264Parser.LastParams.PictureHeight;
//aOutFormat.biBitCount:=24; //??
//aOutFormat.DataSize:=aDataSize;
Assert(PDWORD(aOutData)^=$1000000); //NAL_START_MARKER
FH264Parser.Parse(PByte(aOutData)+4,aDataSize-4);
end
else begin
result:=true; //??
Assert(false); //TODO
end;
aOutInfo:=nil;
aOutInfoSize:=0;
if aFrameType=PktIFrames then
Include(aOutFormat.biFrameFlags,ffKeyFrame);
end;
procedure TStreamFramerHV.OpenStream(aStream: TStream);
var
c: array [0..3] of AnsiChar;
begin
FStream:=aStream;
FStream.ReadBuffer(c[0],4);
if (c[0]<>'H') or (c[1]<>'V') or (c[2]<>'D') or (c[3]<>'P') then
raise Exception.Create('Неверный формат файла');
end;
function TStreamFramerHV.StreamInfo: TBytes;
begin
result:=nil;
end;
function TStreamFramerHV.VideoStreamType: TStreamType;
begin
result:=stH264;
end;
function TStreamFramerHV.AudioStreamType: TStreamType;
begin
result:=0; //TODO
end;
end.
|
namespace OxygeneStack;
interface
type
StackItem<T> = class
public
property Data: T;
property Prev: StackItem<T>;
end;
Stack<T> = public class
private
property Top: StackItem<T>;
public
method Count: Integer;
method Pop: T;
method Push(aData: T);
end;
implementation
method Stack<T>.Pop: T;
begin
if Top=nil then
raise new Exception('Empty Stack');
Result := Top.Data;
Top := Top.Prev;
end;
method Stack<T>.Push(aData: T);
var last: StackItem<T>;
begin
last := Top; // may be nil
Top := new StackItem<T>;
Top.Data := aData;
Top.Prev := last;
end;
method Stack<T>.Count: integer;
var last: StackItem<T>;
begin
if Top = nil then exit(0);
last := Top;
repeat
inc(Result);
last := last.Prev;
until last = nil;
end;
end. |
unit glslang.ShaderLang;
interface //#################################################################### ■
//
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
uses glslang.ResourceLimits, glslang.Versions,
LUX.Code.C;
const DLLNAME = 'glslang.dll';
//
// This is the platform independent interface between an OGL driver
// and the shading language compiler/linker.
//
//
// Driver must call this first, once, before doing any other
// compiler/linker operations.
//
// (Call once per process, not once per thread.)
//
function ShInitialize :T_int; cdecl; external DLLNAME;
//
// Driver should call this at process shutdown.
//
function ShFinalize :T_int; cdecl; external DLLNAME;
//
// Types of languages the compiler can consume.
//
type T_EShLanguage = (
EShLangVertex,
EShLangTessControl,
EShLangTessEvaluation,
EShLangGeometry,
EShLangFragment,
EShLangCompute,
EShLangCount
);
type T_EShLanguageMask = (
EShLangVertexMask = 1 shl EShLangVertex,
EShLangTessControlMask = 1 shl EShLangTessControl,
EShLangTessEvaluationMask = 1 shl EShLangTessEvaluation,
EShLangGeometryMask = 1 shl EShLangGeometry,
EShLangFragmentMask = 1 shl EShLangFragment,
EShLangComputeMask = 1 shl EShLangCompute
);
function StageName(EShLanguage) :P_char; cdecl; external DLLNAME;
//
// Types of output the linker will create.
//
type T_EShExecutable = (
EShExVertexFragment,
EShExFragment
);
//
// Optimization level for the compiler.
//
type T_EShOptimizationLevel = (
EShOptNoGeneration,
EShOptNone,
EShOptSimple, // Optimizations that can be done quickly
EShOptFull // Optimizations that will take more time
);
//
// Message choices for what errors and warnings are given.
//
type T_EShMessages = (
EShMsgDefault = 0, // default is to give all required errors and extra warnings
EShMsgRelaxedErrors = 1 shl 0, // be liberal in accepting input
EShMsgSuppressWarnings = 1 shl 1, // suppress all warnings, except those required by the specification
EShMsgAST = 1 shl 2, // print the AST intermediate representation
EShMsgSpvRules = 1 shl 3, // issue messages for SPIR-V generation
EShMsgVulkanRules = 1 shl 4, // issue messages for Vulkan-requirements of GLSL for SPIR-V
EShMsgOnlyPreprocessor = 1 shl 5 // only print out errors produced by the preprocessor
);
//
// Build a table for bindings. This can be used for locating
// attributes, uniforms, globals, etc., as needed.
//
type P_ShBinding = ^T_ShBinding;
T_ShBinding = record
name :P_char;
binding :T_int;
end;
type PP_ShBindingTable = ^P_ShBindingTable;
P_ShBindingTable = ^T_ShBindingTable;
T_ShBindingTable = record
numBindings :T_int;
bindings :P_ShBinding; // array of bindings
end;
//
// ShHandle held by but opaque to the driver. It is allocated,
// managed, and de-allocated by the compiler/linker. It's contents
// are defined by and used by the compiler and linker. For example,
// symbol table information and object code passed from the compiler
// to the linker can be stored where ShHandle points.
//
// If handle creation fails, 0 will be returned.
//
type T_ShHandle = P_void;
//
// Driver calls these to create and destroy compiler/linker
// objects.
//
function ShConstructCompiler( const EShLanguage_:T_EShLanguage; debugOptions:T_int ) :T_ShHandle; cdecl; external DLLNAME; // one per shader
function ShConstructLinker( const EShExecutable_:T_EShExecutable; debugOptions:T_int ) :T_ShHandle; cdecl; external DLLNAME; // one per shader pair
function ShConstructUniformMap :T_ShHandle; cdecl; external DLLNAME; // one per uniform namespace (currently entire program object)
procedure ShDestruct( ShHandle_:T_ShHandle ); cdecl; external DLLNAME;
//
// The return value of ShCompile is boolean, non-zero indicating
// success.
//
// The info-log should be written by ShCompile into
// ShHandle, so it can answer future queries.
//
function ShCompile(
const ShHandle_ :T_ShHandle;
const shaderStrings :array of P_char;
const numStrings :T_int;
const lengths :P_int;
const EShOptimizationLevel_ :T_EShOptimizationLevel;
const resources :PBuiltInResource;
debugOptions :T_int;
defaultVersion :T_int = 110; // use 100 for ES environment, overridden by #version in shader
forwardCompatible :T_bool = false; // give errors for use of deprecated features
messages :T_EShMessages = EShMsgDefault // warnings and errors
) :T_int; cdecl; external DLLNAME;
function ShLink(
const ShHandle_ :T_ShHandle; // linker object
const h :array of T_ShHandle; // compiler objects to link together
const numHandles :T_int;
uniformMap :T_ShHandle; // updated with new uniforms
uniformsAccessed :array of P_short_int; // returned with indexes of uniforms accessed
numUniformsAccessed :P_int ) :T_int; cdecl; external DLLNAME;
function ShLinkExt(
const ShHandle_ :T_ShHandle; // linker object
const h :array of T_ShHandle; // compiler objects to link together
const numHandles :T_int ) :T_int; cdecl; external DLLNAME;
//
// ShSetEncrpytionMethod is a place-holder for specifying
// how source code is encrypted.
//
procedure ShSetEncryptionMethod( _ShHandle:T_ShHandle ); cdecl; external DLLNAME;
//
// All the following return 0 if the information is not
// available in the object passed down, or the object is bad.
//
function ShGetInfoLog( const ShHandle_:T_ShHandle ) :P_char; cdecl; external DLLNAME;
function ShGetExecutable( const ShHandle_:T_ShHandle ) :P_void; cdecl; external DLLNAME;
function ShSetVirtualAttributeBindings( const ShHandle_:T_ShHandle; const ShBindingTable_:P_ShBindingTable ) :T_int; cdecl; external DLLNAME; // to detect user aliasing
function ShSetFixedAttributeBindings( const ShHandle_:T_ShHandle; const ShBindingTable_:P_ShBindingTable ) :T_int; cdecl; external DLLNAME; // to force any physical mappings
function ShGetPhysicalAttributeBindings( const ShHandle_:T_ShHandle; const ShBindingTable_:PP_ShBindingTable ) :T_int; cdecl; external DLLNAME; // for all attributes
//
// Tell the linker to never assign a vertex attribute to this list of physical attributes
//
function ShExcludeAttributes( const ShHandle_:T_ShHandle; attributes:P_int; count:T_int ) :T_int; cdecl; external DLLNAME;
//
// Returns the location ID of the named uniform.
// Returns -1 if error.
//
function ShGetUniformLocation( const uniformMap:T_ShHandle; const name:P_char ) :T_int; cdecl; external DLLNAME;
implementation //############################################################### ■
end. //######################################################################### ■
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ SOAP Support }
{ }
{ Copyright (c) 2001 Borland Software Corporation }
{ }
{*******************************************************}
unit WSDLSoap;
interface
uses InvokeRegistry, Types;
type
TWSDLSOAPPort = class(TRemotable)
private
FPortName: WideString;
FAddresses: TWideStringDynArray;
published
property PortName: WideString read FPortName write FPortName;
property Addresses: TWideStringDynArray read FAddresses write FAddresses;
end;
TWSDLSOAPPortArray = array of TWSDLSOAPPort;
implementation
initialization
RemClassRegistry.RegisterXSClass(TWSDLSOAPPort);
end.
|
unit UnitFactorPeriodo;
interface
uses
SysUtils, frm_connection, DBCtrls,
DB, Global, frxDBSet, Classes,ZAbstractRODataset, ZAbstractDataset,
ZDataset, RXDBCtrl, Math;
type
TFactorPeriodo=class(TComponent)
private
bError:boolean;
sContrato:string;
rFactorPer:real;
fFechaIni:tDateTime;
fFechaFin:tDateTime;
bCriterio:byte;
//metodos para propiedades
function getFactPer:real;
//metodos de operacion
function diasDelMes(wMes:word):integer;
function diasAlMes(fecha:tDateTime):real;
function diasALaQuincena(fecha:tDateTime):real;
function diaDeLaSemana(fecha:tDateTime):real;
function diario:real;
function semanal:real;
function quincenal:real;
function mensual:real;
public
//propiedades
property error:boolean read bError;
property factorPer:real read getFactPer;
//metodos publicos
constructor Create(sContrato:string);
function facCriterio:real;
function obtenerConf:boolean;
function generarConf:boolean;
function calcular:real;
end;
implementation
constructor TFactorPeriodo.Create(sContrato:string);
BEGIN
self.sContrato:=sContrato;
rFactorPer:=0;
bError:=false;
if not obtenerConf then
bError := not generarConf;
calcular;
END;
function TFactorPeriodo.getFactPer:real;
BEGIN
result:=roundto(rFactorPer, -2);
END;
function TFactorPeriodo.facCriterio:real;
BEGIN
result:=0;
case self.bCriterio of
0:result:=365.25;
1:result:=52.18;
2:result:=24;
3:result:=12;
end;
END;
function TFactorPeriodo.obtenerConf:boolean;
var
zConsulta:TZQuery;
sSQL:string;
BEGIN
result:=true;
//buscar la configuracion
sSQL:='SELECT * FROM confcalculoindirectos'
+' WHERE sContrato = :contrato';
zConsulta := TZQuery.Create(self);
zConsulta.Connection := connection.zConnection;
zConsulta.Active := False;
zConsulta.SQL.Clear;
zConsulta.SQL.Add(sSQL);
zConsulta.Params.ParamByName('contrato').DataType := ftString ;
zConsulta.Params.ParamByName('contrato').Value := sContrato ;
zConsulta.Open;
if zConsulta.RecordCount>0 then begin
fFechaIni := zConsulta.FieldValues['fFechaIni'];
fFechaFin := zConsulta.FieldValues['fFechaFin'];
if zConsulta.FieldValues['sPeriodo'] = 'Días' then
bCriterio := 0
else if zConsulta.FieldValues['sPeriodo'] = 'Semanas' then
bCriterio := 1
else if zConsulta.FieldValues['sPeriodo'] = 'Quincenas' then
bCriterio := 2
else //meses
bCriterio := 3;
end
else
result:=false;
END;
function TFactorPeriodo.generarConf:boolean;
var
zConsulta:TZQuery;
sSQL:string;
BEGIN
result:=true;
//aqui se averiguan los valores
sSQL:='SELECT * FROM actividadesxanexo'
+' WHERE sContrato = :contrato AND sWbs = :wbs';
zConsulta := TZQuery.Create(self);
zConsulta.Connection := connection.zConnection;
zConsulta.Active := False;
zConsulta.SQL.Clear;
zConsulta.SQL.Add(sSQL);
zConsulta.Params.ParamByName('contrato').DataType := ftString ;
zConsulta.Params.ParamByName('contrato').Value := sContrato ;
zConsulta.Params.ParamByName('wbs').DataType := ftString ;
zConsulta.Params.ParamByName('wbs').Value := 'A' ;
zConsulta.Open;
fFechaIni:=zConsulta.FieldValues['dFechaInicio'];
fFechaFin:=zConsulta.FieldValues['dFechaFinal'];
bCriterio := 3;//meses
//aqui se insertan los datos recien generados
//si algo sale mal: result:=false;
END;
function TFactorPeriodo.diasDelMes(wMes:word):integer;
BEGIN
result:=0;
case wMes of
1 : result := 31;
2 : result := 28;
3 : result := 31;
4 : result := 30;
5 : result := 31;
6 : result := 30;
7 : result := 31;
8 : result := 31;
9 : result := 30;
10 : result := 31;
11 : result := 30;
12 : result := 31;
end;
END;
function TFactorPeriodo.diasALaQuincena(fecha:tDateTime):real;
var
myYear, myMonth, myDay : Word;
fIni,fFin:tDateTime;
rAcDias:real;
BEGIN
rAcDias:=0;
DecodeDate(fecha, myYear, myMonth, myDay);
if myDay>15 then begin//segunda quincena
fIni := EncodeDate(myYear, myMonth, 16);
fFin := EncodeDate(myYear, myMonth, diasDelMes(myMonth));
end
else begin//primera quincena
fIni := EncodeDate(myYear, myMonth, 1);
fFin := EncodeDate(myYear, myMonth, 15);
end;
while fIni<=fFin do begin
rAcDias:=rAcDias+diaDeLaSemana(fIni);
fIni:=fIni+1;
end;
result:=rAcDias;
END;
function TFactorPeriodo.diasAlMes(fecha:tDateTime):real;
var
myYear, myMonth, myDay : Word;
fIni,fFin:tDateTime;
rAcDias:real;
BEGIN
rAcDias:=0;
DecodeDate(fecha, myYear, myMonth, myDay);
fIni := EncodeDate(myYear, myMonth, 1);
fFin := EncodeDate(myYear, myMonth, diasDelMes(myMonth));
while fIni<=fFin do begin
rAcDias:=rAcDias+diaDeLaSemana(fIni);
fIni:=fIni+1;
end;
result:=rAcDias;
END;
function TFactorPeriodo.diaDeLaSemana(fecha:tDateTime):real;
BEGIN
result:=0;
if (DayOfWeek(fecha) > 1)and (DayOfWeek(fecha) < 7) then //lunes a viernes
result := result + 1
else if DayOfWeek(fecha) = 7 then //sabado
result := result + 0.5;
//domingo, no se hace nada, se queda result:=0
END;
function TFactorPeriodo.diario:real;
var
fDia:tDateTime;
BEGIN
result:=0;
fDia := fFechaIni;
while fDia<=fFechaFin do begin
result := result + diaDeLaSemana(fDia);
fDia:=fDia+1;
end;
END;
function TFactorPeriodo.semanal:real;
var
fDia:tDateTime;
BEGIN
result:=0;
fDia := fFechaIni;
while fDia<=fFechaFin do begin
result := result + diaDeLaSemana(fDia);
fDia:=fDia+1;
end;
result:=result/5.5;
END;
function TFactorPeriodo.quincenal:real;
var
fDia:tDateTime;
myYear, myMonth, myDay : Word;
wMes: word;
iDiasQuincena :real;
rAcDias,rAcTotal: real;
bNoCambio:boolean;
BEGIN
fDia:=fFechaIni;
RAcDias:=0;
rAcTotal:=0;
DecodeDate(fDia, myYear, myMonth, myDay);
wMes:=myMonth;
iDiasQuincena:=diasALaQuincena(fDia);
bNoCambio:=true;
if myDay>15 then
bNoCambio:=false;
while fDia<=fFechaFin do begin
DecodeDate(fDia, myYear, myMonth, myDay);
if wMes = myMonth then begin
if (bNoCambio)and(myDay>15) then begin//cambiar de quincena
bNoCambio:=false;
if iDiasQuincena <> 0 then
rAcTotal:=rAcTotal+(rAcDias/iDiasQuincena);
rAcDias:=diaDeLaSemana(fDia);
iDiasQuincena:=diasALaQuincena(fDia);
end
else begin
rAcDias:=rAcDias+diaDeLaSemana(fDia);
end;
end
else begin//cambiar de mes
bNoCambio:=true;
if iDiasQuincena <> 0 then
rAcTotal:=rAcTotal+(rAcDias/iDiasQuincena);
rAcDias:=diaDeLaSemana(fDia);
iDiasQuincena:=diasALaQuincena(fDia);
wMes:=myMonth;
end;
fDia:=fDia+1;
end;
if iDiasQuincena <> 0 then
rAcTotal:=rAcTotal+(rAcDias/iDiasQuincena);
result:=rAcTotal;
END;
function TFactorPeriodo.mensual:real;
var
fDia:tDateTime;
myYear, myMonth, myDay : Word;
wMes: word;
iDiasMes :real;
rAcDias,rAcTotal: real;
BEGIN
fDia:=fFechaIni;
RAcDias:=0;
rAcTotal:=0;
DecodeDate(fDia, myYear, myMonth, myDay);
wMes:=myMonth;
iDiasMes:=diasAlMes(fDia);
while fDia<=fFechaFin do begin
DecodeDate(fDia, myYear, myMonth, myDay);
if wMes = myMonth then begin
rAcDias:=rAcDias+diaDeLaSemana(fDia);
end
else begin
if iDiasMes <> 0 then
rAcTotal:=rAcTotal+(rAcDias/iDiasMes);
rAcDias:=diaDeLaSemana(fDia);
iDiasMes:=diasAlMes(fDia);
wMes:=myMonth;
end;
fDia:=fDia+1;
end;
if iDiasMes <> 0 then
rAcTotal:=rAcTotal+(rAcDias/iDiasMes);
result:=rAcTotal;
END;
function TFactorPeriodo.calcular:real;
BEGIN
result:=0;
case bCriterio of
0 : result := diario;
1 : result := semanal;
2 : result := quincenal;
3 : result := mensual;
end;
rFactorPer:=result;
END;
end.
|
unit MainUnit;
interface
uses
Windows, Types, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Math,
StdCtrls, ExtCtrls, GR32_Image, GR32_LowLevel,
{$IFDEF FPC} LResources, {$ENDIF}
GR32, GR32_Polygons, GR32_Math, GR32_Transforms, GR32_Blend,
GR32_Layers, GR32_Misc, GR32_Text, ComCtrls;
type
TForm1 = class(TForm)
Panel1: TPanel;
sbRotation: TScrollBar;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
sbSkewX: TScrollBar;
Label4: TLabel;
sbSkewY: TScrollBar;
Label5: TLabel;
sbScaleX: TScrollBar;
Label6: TLabel;
sbScaleY: TScrollBar;
Label7: TLabel;
lblRotation: TLabel;
lblSkewY: TLabel;
lblScaleY: TLabel;
lblSkewX: TLabel;
lblScaleX: TLabel;
Button1: TButton;
Button2: TButton;
FontDialog1: TFontDialog;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
Image: TImage32;
TabSheet2: TTabSheet;
Image2: TImage32;
TabSheet3: TTabSheet;
Image3: TImage32;
TabSheet4: TTabSheet;
Image4: TImage32;
procedure FormCreate(Sender: TObject);
procedure sbRotationChange(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure PageControl1Change(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
suspendRedraw: boolean;
procedure RedrawBitmap;
procedure RedrawBitmapPage1;
procedure RedrawBitmapPage2;
procedure RedrawBitmapPage3;
procedure RedrawBitmapPage4;
public
ttfc, ttfcArial16, ttfcCourNew18, ttfc30, ttfc96: TTrueTypeFont;
fCnt: integer;
fPts: TArrayOfFixedPoint;
end;
var
Form1: TForm1;
implementation
uses DateUtils;
{$IFNDEF FPC}
{$R *.DFM}
{$ENDIF}
{$R pattern.res}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
procedure TForm1.FormCreate(Sender: TObject);
begin
GR32.SetGamma(1.1); //text looks a bit thin at higher gammas
Image.SetupBitmap;
Image.Bitmap.DrawMode := dmOpaque;
Image.Bitmap.CombineMode := cmBlend;
Image.Bitmap.Clear($FFE8E8D8);
Image2.SetupBitmap;
Image2.Bitmap.DrawMode := dmOpaque;
Image2.Bitmap.CombineMode := cmBlend;
Image2.Bitmap.Clear($FFE8E8D8);
Image3.SetupBitmap;
Image3.Bitmap.DrawMode := dmOpaque;
Image3.Bitmap.CombineMode := cmBlend;
Image3.Bitmap.Clear($FFE8E8D8);
Image4.SetupBitmap;
Image4.Bitmap.DrawMode := dmOpaque;
Image4.Bitmap.CombineMode := cmBlend;
Image4.Bitmap.Clear($FFE8E8D8);
ttfc := TrueTypeFontClass.Create(self.Font.Name, 16);
ttfc.Hinted := true;
ttfcArial16 := TrueTypeFontClass.Create('Arial', 16);
ttfcCourNew18 := TrueTypeFontClass.Create('Courier New', 18, [fsBold]);
ttfc30 := TrueTypeFontClass.Create(self.Font.Name, 30);
ttfc96 := TrueTypeFontClass.Create(self.Font.Name, 96);
RedrawBitmap;
end;
//------------------------------------------------------------------------------
procedure TForm1.FormDestroy(Sender: TObject);
begin
ttfc.Free;
ttfcArial16.Free;
ttfcCourNew18.Free;
ttfc30.Free;
ttfc96.Free;
end;
//------------------------------------------------------------------------------
procedure TForm1.PageControl1Change(Sender: TObject);
begin
suspendRedraw := true;
//reset transformations ...
sbScaleX.Position := 50;
sbScaleY.Position := 50;
sbSkewX.Position := 0;
sbSkewY.Position := 0;
sbRotation.Position := 0;
sbScaleY.Enabled := (PageControl1.ActivePage = TabSheet1) or
(PageControl1.ActivePage = TabSheet4);
sbScaleX.Enabled := (PageControl1.ActivePage <> TabSheet3);
sbSkewY.Enabled := (PageControl1.ActivePage <> TabSheet3);
sbRotation.Enabled := (PageControl1.ActivePage <> TabSheet3);
suspendRedraw := false;
sbRotationChange(nil); //now do the redraw etc
end;
//------------------------------------------------------------------------------
procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key = VK_TAB) then
if (Shift = [ssCtrl]) then
PageControl1.SelectNextPage(true)
else if (Shift = [ssShift, ssCtrl]) then
PageControl1.SelectNextPage(false);
end;
//------------------------------------------------------------------------------
procedure TForm1.Button1Click(Sender: TObject);
begin
with FontDialog1 do
begin
font := self.Font;
if not execute then exit;
self.Font := font;
ttfc.FontName := Font.Name;
ttfc.Size := Font.Size;
ttfc.Style := Font.Style;
ttfc30.FontName := Font.Name;
ttfc96.FontName := Font.Name;
RedrawBitmap;
end;
end;
//------------------------------------------------------------------------------
procedure TForm1.Button2Click(Sender: TObject);
begin
close;
end;
//------------------------------------------------------------------------------
procedure TForm1.sbRotationChange(Sender: TObject);
begin
if suspendRedraw then exit;
if PageControl1.ActivePage = TabSheet4 then
lblRotation.Caption := format('%d',[Constrain(sbRotation.Position, -45, 45)]) else
lblRotation.Caption := format('%d',[sbRotation.Position]);
lblSkewX.Caption := format('%1.2f',[sbSkewX.Position/10]);
lblSkewY.Caption := format('%1.2f',[sbSkewY.Position/40]);
lblScaleX.Caption := format('%1.2f',[sbScaleX.Position/50]);
lblScaleY.Caption := format('%1.2f',[sbScaleY.Position/50]);
RedrawBitmap;
end;
//------------------------------------------------------------------------------
//GradientRainbow: returns a color based on a parameter value between 0 and 1.
function GradientRainbow(fraction: single): TColor32;
begin
if (fraction >= 1) or (fraction <= 0) then result := clRed32
else
begin
fraction := fraction * 6;
case trunc(fraction) of
0: result := GradientColor(clRed32, clYellow32, frac(fraction));
1: result := GradientColor(clYellow32, clLime32, frac(fraction));
2: result := GradientColor(clLime32, clAqua32, frac(fraction));
3: result := GradientColor(clAqua32, clBlue32, frac(fraction));
4: result := GradientColor(clBlue32, clFuchsia32, frac(fraction));
else result := GradientColor(clFuchsia32, clRed32, frac(fraction));
end;
end;
end;
//------------------------------------------------------------------------------
//SinScale: returns a value based on a sine curve where 'x' indicates the
// relative position within the sine curve (looping at xLoop) ...
function SinScale(x: single; xLoop: integer; minScale, maxScale: single): single;
var
dx: integer;
diff: single;
begin
diff := maxScale - minScale;
if diff <= 0 then
result := minScale
else
begin
dx := round(x) mod xLoop;
result := minScale + diff/2 + cos(dx/xLoop *2*pi)*(diff/2);
end;
end;
//------------------------------------------------------------------------------
function LoopScale(x: single; xLoop: integer; minScale, maxScale: single): single;
var
dx: integer;
diff: single;
begin
diff := maxScale - minScale;
if (diff <= 0) or (xLoop < 1) then
result := minScale
else
begin
dx := round(x) mod xLoop;
result := minScale + diff * dx/xLoop;
end;
end;
//------------------------------------------------------------------------------
procedure TForm1.RedrawBitmap;
begin
if PageControl1.ActivePage = tabSheet1 then RedrawBitmapPage1
else if PageControl1.ActivePage = tabSheet2 then RedrawBitmapPage2
else if PageControl1.ActivePage = tabSheet3 then RedrawBitmapPage3
else RedrawBitmapPage4;
end;
//------------------------------------------------------------------------------
procedure TForm1.RedrawBitmapPage1;
var
i,j: integer;
pt: TFloatPoint;
pts: TArrayOfFixedPoint;
polyPts: TArrayOfArrayOfFixedPoint;
polyPolyPts: TArrayOfArrayOfArrayOfFixedPoint;
const
txt: widestring = 'Sample text!';
begin
caption := 'TText32 demo - ' + Self.Font.Name;
Image.Bitmap.Clear($FFE8E8D8);
Image.Bitmap.BeginUpdate;
//first a bit of cosmetic fun (a broken circle around 'GR32') ...
setlength(polyPts,4);
polyPts[0] := GetPipeCornerPoints(FloatRect(450,0,510,60),20,cTopLeft);
polyPts[1] := GetPipeCornerPoints(FloatRect(515,0,575,60),20,cTopRight);
polyPts[2] := GetPipeCornerPoints(FloatRect(515,65,575,125),20,cBottomRight);
polyPts[3] := GetPipeCornerPoints(FloatRect(450,65,510,125),20,cBottomLeft);
SimpleShadow(Image.Bitmap, polyPts, 4, 4, MAXIMUM_SHADOW_FADE, $FFA0A0A0, true);
SimpleGradientFill(Image.Bitmap, polyPts, $0, [$FFFFFFFF, $FFC0C0C0], -45);
SimpleText(Image.Bitmap, panel1.Font, 496, 55, 'GR32', $FF404040);
//3 pretty stars before we get to drawing text ...
pts := GetStarPoints(FixedPoint(515,250),7,12,30);
//SimpleShadow(image.Bitmap,pts,-2,-2,NO_SHADOW_FADE,$FFFFFFFF, true);
SimpleShadow(Image.Bitmap, pts, 4, 4, MAXIMUM_SHADOW_FADE, $66000000, true);
SimpleRadialFill(Image.Bitmap,pts,[$FFEEFF66,$00CC33CC]);
pts := GetStarPoints(FixedPoint(548,220),5,5,10);
//SimpleShadow(image.Bitmap,pts,-2,-2,NO_SHADOW_FADE,$FFFFFFFF, true);
SimpleShadow(Image.Bitmap, pts, 4, 4, MAXIMUM_SHADOW_FADE, $66000000, true);
SimpleRadialFill(Image.Bitmap,pts,[$FFEEFF66,$00CC33CC]);
pts := GetStarPoints(FixedPoint(560,250),5,5,10);
//SimpleShadow(image.Bitmap,pts,-2,-2,NO_SHADOW_FADE,$FFFFFFFF, true);
SimpleShadow(Image.Bitmap, pts, 4, 4, MAXIMUM_SHADOW_FADE, $66000000, true);
SimpleRadialFill(Image.Bitmap,pts,[$FFEEFF66,$00CC33CC]);
// //some very basic stuff that doesn't require a TText32 object ...
// Image.Bitmap.Canvas.Brush.Style := bsClear;
// Image.Bitmap.Canvas.Font.Assign(self.Font);
// //nb: the following line won't work if Image.Bitmap.DrawMode := dmBlend;
// Image.Bitmap.Canvas.TextOut(500,150, 'TextOut');
with TText32.Create do
try
//first, apply text transformations according to scrollbar sliders ...
Scale(sbScaleX.Position/50, sbScaleY.Position/50);
Skew(sbSkewX.Position/10, sbSkewY.Position/40);
Angle := sbRotation.Position;
////////////////////////////////////////////////////////////////////////////
// Draw a line of text using different colors, fonts and sizes 젨
////////////////////////////////////////////////////////////////////////////
//nb: the first line sets the position and subsequent lines (without X & Y
//parameters) will continue drawing at the appropriate insertion points ...
Draw(Image.Bitmap, 20, 55, 'This is some text using different ', ttfcArial16, $FF004800);
Draw(Image.Bitmap, 'sizes', ttfc30, $FFC36217);
Draw(Image.Bitmap, ', ', ttfcArial16, $FF004800);
Draw(Image.Bitmap, 'fonts', ttfcCourNew18, $FF0000FF);
Draw(Image.Bitmap, ' and ', ttfcArial16, $FF004800);
Draw(Image.Bitmap, 'colors', ttfcArial16, $FF00B19B);
Draw(Image.Bitmap, '.', ttfcArial16, $FF004800);
////////////////////////////////////////////////////////////////////////////
// Draw text filled and outlined ... 젨
////////////////////////////////////////////////////////////////////////////
//nb: we're still using the same transformations as above ...
polyPts := Get(20,170, txt, ttfc96, pt);
//now outline 'txt' with a 1.8px pen and with a semi-transparent fill ...
DrawAndOutline(Image.Bitmap, 20,170, txt, ttfc96, 1.8, $FF008000, $99C6EBAF);
Simple3D(Image.Bitmap, polyPts,6,6,MAXIMUM_SHADOW_FADE,clWhite32,clBlack32);
////////////////////////////////////////////////////////////////////////////
// Draw text along a bezier path ... ?
////////////////////////////////////////////////////////////////////////////
//ignore rotation and skew ...
ClearTransformations;
Scale(sbScaleX.Position/100, sbScaleY.Position/100);
Skew(sbSkewX.Position/10, 0);
//create a bezier path on which to locate some text ...
pts := GetCBezierPoints([FixedPoint(20,260),FixedPoint(170,180),
FixedPoint(170,340),FixedPoint(320,260)]);
SimpleLine(Image.Bitmap, pts, $40009900); //draw the path
//draw the text centered on this path...
//This is a bit more sophisticated than what a Draw method offers since
//rather than simply drawing, we get the points to apply custom coloring etc.
//Also, we'll offset the text a couple of pixels away from the line ...
polyPolyPts := GetEx(pts, txt, ttfc96, aCenter, aMiddle, true, 2);
for i := 0 to high(polyPolyPts) do
begin
SimpleShadow(image.Bitmap,
polyPolyPts[i],-3,-3,MINIMUM_SHADOW_FADE, clWhite32, true, true);
SimpleShadow(image.Bitmap,
polyPolyPts[i],3,3,MAXIMUM_SHADOW_FADE, $80000000, true, true);
if length(polyPolyPts[i]) > 0 then
begin
j := FixedRound(polyPolyPts[i][0][0].X);
SimpleFill(image.Bitmap, polyPolyPts[i],
$20000000, GradientRainbow(LoopScale(j, 1100, 0, 1)));
end;
end;
finally
free;
end;
Image.Bitmap.EndUpdate;
end;
//------------------------------------------------------------------------------
procedure TForm1.RedrawBitmapPage2;
var
i: integer;
s: single;
clr: TColor32;
pts: TArrayOfFixedPoint;
polyPts, inflatedPolyPts: TArrayOfArrayOfFixedPoint;
pos, nextpos: TFloatPoint;
const
txt: wideString = 'FUN WITH GRAPHICS32';
procedure DoFill(const pts: TArrayOfFixedPoint; clrs: array of TColor32);
begin
SimpleShadow(image2.Bitmap,pts,3,3,MAXIMUM_SHADOW_FADE, clrs[2], true);
SimpleLine(Image2.Bitmap, pts, clrs[2]);
SimpleGradientFill(Image2.Bitmap,pts,$0,clrs,-90);
end;
begin
caption := 'TText32 demo - ' + Self.Font.Name;
Image2.Bitmap.Clear($FFE8E8D8);
Image2.Bitmap.BeginUpdate;
pts := nil;
////////////////////////////////////////////////////////////////////////////////
// something a bit more complicated ... ?
////////////////////////////////////////////////////////////////////////////////
//first, just a couple of pretty lines ...
pts := MakeArrayOfFixedPoints([20,30, 550,30, 550,36, 20,36]);
DoFill(pts, [$FF6666FF,$FFAAAAFF,$FF000033]);
pts := MakeArrayOfFixedPoints([30,26, 40,26, 40,40, 30,40]);
DoFill(pts, [$FF6666FF,$FFAAAAFF,$FF000033]);
pts := MakeArrayOfFixedPoints([530,26, 540,26, 540,40, 530,40]);
DoFill(pts, [$FF6666FF,$FFAAAAFF,$FF000033]);
pts := MakeArrayOfFixedPoints([20,250, 550,250, 550,256, 20,256]);
DoFill(pts, [$FFAA66AA,$FFFF99FF,$FF330033]);
pts := MakeArrayOfFixedPoints([30,246, 40,246, 40,260, 30,260]);
DoFill(pts, [$FFAA66AA,$FFFF99FF,$FF330033]);
pts := MakeArrayOfFixedPoints([530,246, 540,246, 540,260, 530,260]);
DoFill(pts, [$FFAA66AA,$FFFF99FF,$FF330033]);
//This only looks good with Option 1 (see below), otherwise leave commented out.
// SimpleGradientFill(Image2.Bitmap,
// [FixedPoint(10,70),FixedPoint(560,70),FixedPoint(560,220),FixedPoint(10,220)],
// $0, [$FFF4B651, $FFD75F00], -90);
with TText32.Create do
try
Angle := sbRotation.Position;
Skew(sbSkewX.Position/10, sbSkewY.Position/40);
Spacing := 0;
pos := FloatPoint(20, 170);
for i := 1 to length(txt) do
begin
//scale and translate depending the position of the char in the line ...
s := SinScale(pos.X, 330, 1, 2.5); //ie makes 's' between 1 and 2.5
Scale(0.5* sbScaleX.Position/50, 0.6* s);
//make the taller (larger Y scaled) characters start a little lower down
//so all the characters are aligned roughly through their middles ...
Translate(0, SinScale(pos.X, 330, 0, 18));
//get the polypoints for each individual character ...
polyPts := Get(pos.X, pos.Y, txt[i], ttfc96, nextpos);
inflatedPolyPts := GetInflated(pos.X, pos.Y, 2.0, txt[i], ttfc96, nextpos);
OffsetPolyPoints(inflatedPolyPts, -1,-1);
pos := nextpos;
//Option 1.
// SimpleShadow(Image2.Bitmap, inflatedPolyPts, 4, 4, MEDIUM_SHADOW_FADE, $80000000, true);
// SimpleGradientFill(Image2.Bitmap, inflatedPolyPts, $0, [clWhite32, $FFC0C0C0], -90);
//Option 2.
// SimpleShadow(Image2.Bitmap, inflatedPolyPts, 4, 4, MEDIUM_SHADOW_FADE, $80000000, true);
// SimpleFill(Image2.Bitmap, inflatedPolyPts, $0, clWhite32);
// clr := GradientRainbow(LoopScale(pos.X, 500, 0, 1));
// SimpleFill(Image2.Bitmap, polyPts, $0, clr);
//Option 3.
SimpleShadow(Image2.Bitmap, inflatedPolyPts, 4, 4, MEDIUM_SHADOW_FADE, $80000000, true);
SimpleFill(Image2.Bitmap, inflatedPolyPts, $0, clWhite32);
clr := GradientRainbow(LoopScale(pos.X, 500, 0, 1));
SimpleGradientFill(Image2.Bitmap, polyPts, $0,
[GradientColor(clr,clBlack32,0.25), clr, clr, clr, SetAlpha(clr, 64)],115);
end;
finally
free;
end;
Image2.Bitmap.EndUpdate;
end;
//------------------------------------------------------------------------------
procedure TForm1.RedrawBitmapPage3;
var
pts, upperPts, lowerPts: TArrayOfFixedPoint;
ppFx: TArrayOfArrayOfFixedPoint;
ppFt: TArrayOfArrayOfFloatPoint;
bmp: TBitmap32;
const
txt: wideString = 'Text between paths ...';
begin
caption := 'TText32 demo - ' + Self.Font.Name;
Image3.Bitmap.Clear($FFE8E8D8);
Image3.Bitmap.BeginUpdate;
Image3.Bitmap.DrawMode := dmBlend;
Image3.Bitmap.CombineMode := cmBlend;
////////////////////////////////////////////////////////////////////////////////
// Text between 2 straight lines ... ?
////////////////////////////////////////////////////////////////////////////////
upperPts := MakeArrayOfFixedPoints([10,50, 110,20]);
lowerPts := MakeArrayOfFixedPoints([10,100, 110,130]);
//first, draw a subtle shade between these 2 lines ...
pts := MakeArrayOfFixedPoints([10,50, 110,20, 110,130, 10,100]);
SimpleGradientFill(Image3.Bitmap, Pts, $0, [$80E0F8E0,$80FFFFD0,$00FFFFD0],0);
//next, draw the lines ...
SimpleLine(Image3.Bitmap, upperPts, $40999900);
SimpleLine(Image3.Bitmap, lowerPts, $40999900);
//get the text outline points ...
with TText32.Create do
try
Skew(sbSkewX.Position/10, 0);
ppFx := GetBetweenPaths(lowerPts,upperPts,'GR32', ttfc96);
finally
free;
end;
//create a 3D effect for the text ...
SimpleShadow(Image3.Bitmap,ppFx, -3, -3, NO_SHADOW_FADE, $FFFFFFFF, true);
SimpleShadow(Image3.Bitmap,ppFx, 2, 2, NO_SHADOW_FADE, $88333300, true);
//finally, fill the text with a green, yellow and red color gradient ...
SimpleGradientFill(Image3.Bitmap, ppFx, $0,
[$80FF0000,$80FF0000,$80FFFF00,$FFFFFF00,$FF00FF00],115);
////////////////////////////////////////////////////////////////////////////////
// Text between 2 very wavy curves ... ?
////////////////////////////////////////////////////////////////////////////////
upperPts := GetCBezierPoints([FixedPoint(170,40),FixedPoint(270,-60),
FixedPoint(270,140),FixedPoint(370,40),
FixedPoint(470,-60),FixedPoint(470,140),FixedPoint(570,40)]);
lowerPts := GetCBezierPoints([FixedPoint(170,110),FixedPoint(270,10),
FixedPoint(270,210),FixedPoint(370,110),
FixedPoint(470,10),FixedPoint(470,210),FixedPoint(570,110)]);
SimpleLine(Image3.Bitmap, upperPts, $400000AA);
SimpleLine(Image3.Bitmap, lowerPts, $400000AA);
with TText32.Create do
try
Spacing := 10;
Skew(sbSkewX.Position/10, 0);
ppFx := GetBetweenPaths(lowerPts,upperPts,txt,ttfc96);
finally
free;
end;
//3D drop shadow effect ...
SimpleShadow(Image3.Bitmap,ppFx, 4, 4, MINIMUM_SHADOW_FADE, $FF330066, true);
//draw a 3px wide text outline (will be partly obscured by following pattern)
ppFt := MakeArrayOfArrayOfFloatPoints(ppFx);
PolyPolylineFS(image3.Bitmap, ppFt, $FF330066, true, 3);
//finally fill the text with a bitmap pattern ...
bmp := TBitmap32.Create;
try
bmp.LoadFromResourceName(hInstance, 'PATTERN2');
SimpleFill(Image3.Bitmap, ppFx, $0, bmp);
finally
bmp.Free;
end;
////////////////////////////////////////////////////////////////////////////////
// Text in a triangle (but still between 2 paths) ... ?
////////////////////////////////////////////////////////////////////////////////
//some fancy text in a triangle ...
upperPts := MakeArrayOfFixedPoints([10,280, 160,110, 310,280]);
lowerPts := MakeArrayOfFixedPoints([10,280, 310,280]);
//shade the triangle with a very subtle radial gradient ...
SimpleRadialFill(Image3.Bitmap,upperPts,[$30C0C020,$20C08020,$00FF8080]);
SimpleLine(Image3.Bitmap, upperPts, $40FF0000);
SimpleLine(Image3.Bitmap, lowerPts, $40FF0000);
//get the text outline ...
with TText32.Create do
try
Skew(sbSkewX.Position/10, 0);
ppFx := GetBetweenPaths(lowerPts,upperPts,' Graphics ',ttfc96);
finally
free;
end;
//3D effects ...
SimpleShadow(Image3.Bitmap,ppFx,-3,-3,NO_SHADOW_FADE, clWhite32, True);
SimpleShadow(Image3.Bitmap,ppFx, 2, 2,NO_SHADOW_FADE, $AA333300, True);
SimpleRadialFill(Image3.Bitmap,ppFx,[$FFF0F080,$FFFF8080]);
////////////////////////////////////////////////////////////////////////////////
// Text in a circle (but still between 2 paths) ... ?
////////////////////////////////////////////////////////////////////////////////
pts := GetEllipsePoints(FloatRect(327,107,513,293));
SimpleRadialFill(Image3.Bitmap,pts,
[$60FFFF66,$40FFFF66,$80AAFF66,$60AAFF66,$0060AA80]);
//divide the ellipse into a top half and bottom half
upperPts := GetArcPoints(FloatRect(330,110,510,290),0,180);
//GetArcPoints returns the arc in an anticlockwise direction so it's important
//to make the curve (like the text) go from left to right ...
upperPts := ReversePoints(upperPts);
//lowerPts don't need reversing ...
lowerPts := GetArcPoints(FloatRect(330,110,510,290),180,0);
SimpleLine(Image3.Bitmap, upperPts, $8088FF66);
SimpleLine(Image3.Bitmap, lowerPts, $8088FF66);
//now get the text outline points ...
with TText32.Create do
try
Skew(sbSkewX.Position/10, 0);
ppFx := GetBetweenPaths(lowerPts,upperPts,' Delphi ',ttfc96);
finally
free;
end;
//3D effects ...
SimpleShadow(Image3.Bitmap,ppFx,-3,-3,NO_SHADOW_FADE, clWhite32, True);
SimpleShadow(Image3.Bitmap,ppFx, 2, 2,NO_SHADOW_FADE, $AA333300, True);
bmp := TBitmap32.Create;
try
bmp.LoadFromResourceName(hInstance, 'PATTERN');
SimpleFill(Image3.Bitmap, ppFx, $0, bmp);
finally
bmp.Free;
end;
Image3.Bitmap.EndUpdate;
end;
//------------------------------------------------------------------------------
procedure TForm1.RedrawBitmapPage4;
var
chrCnt,len,linePos,textArrayPos,chrPos: integer;
lineHeight: single;
pt, startPt: TFloatPoint;
currentText, currentLine: UnicodeString;
currentColor: TColor32;
rec1, rec2: TFloatRect;
pts: TArrayOfFixedPoint;
text32: TText32;
tm: TTextMetric;
const
txt1: UnicodeString = 'This text is horizontally justified and vertically '+
'centered with a line break at a LineFeed (#10) character.'#10+
'Alignment is also preserved when text is skewed or scaled.';
txt2: UnicodeString = 'This text is centered horizontally and vertically.';
txt3: array [0..6] of UnicodeString = (
'With a small amount of effort it''s possible to display ',
'formatted text. ',
'This example demonstrates left justified text with simple ',
'text coloring',
'. However it wouldn''t require too much more work to add in ',
'text styles ',
'too.');
procedure GetCurrentColor(arrayPos: integer);
begin
case arrayPos of
1: currentColor := clRed32;
3: currentColor := clBlue32;
5: currentColor := clGreen32;
else currentColor := clBlack32;
end;
end;
begin
caption := 'TText32 demo - ' + Self.Font.Name;
Image4.Bitmap.Clear($FFE8E8D8);
Image4.Bitmap.BeginUpdate;
////////////////////////////////////////////////////////////////////////////////
// Justified and centered text in bounding rectangles ... ?
////////////////////////////////////////////////////////////////////////////////
//define and draw bounding rectangle 1 ...
rec1 := FloatRect(20, 20, 290, 165);
pts := MakeArrayOfFixedPoints(rec1);
SimpleShadow(Image4.Bitmap, pts, 5, 5, MAXIMUM_SHADOW_FADE, $FF000000, true);
SimpleFill(Image4.Bitmap, pts, $80000000, $FFFFFFFF);
InflateRect(rec1,-10,-10);
SimpleLine(Image4.Bitmap, MakeArrayOfFixedPoints(rec1), $20000000, true);
//define and draw bounding rectangle 2 ...
rec2 := FloatRect(45, 175, 265, 280);
pts := GetEllipsePoints(rec2);
SimpleShadow(Image4.Bitmap, pts, 5, 5, MAXIMUM_SHADOW_FADE, $FF000000, true);
SimpleFill(Image4.Bitmap, pts, $80000000, $FFFFFFFF);
InflateRect(rec2,-55,-8);
//SimpleLine(Image4.Bitmap, MakeArrayOfFixedPoints(rec2), $20000000, true);
//now draw text within the two bounding rectangles ...
text32 := TText32.Create;
try
text32.Scale(sbScaleX.Position/50, sbScaleY.Position/50);
text32.Skew(sbSkewX.Position/10, 0);
text32.draw(Image4.Bitmap, rec1, txt1, ttfc, clBlack32, aJustify, aMiddle, true);
text32.draw(Image4.Bitmap, rec2, txt2, ttfc, clBlack32, aCenter, aMiddle, true);
finally
text32.Free;
end;
////////////////////////////////////////////////////////////////////////////////
// Left aligned text with color highlighting ... ?
////////////////////////////////////////////////////////////////////////////////
//define and draw a new bounding rectangle ...
rec1 := FloatRect(300, 20, Image4.ClientWidth -20, Image4.ClientHeight -20);
pts := MakeArrayOfFixedPoints(rec1);
SimpleShadow(Image4.Bitmap, pts, 5, 5, MAXIMUM_SHADOW_FADE, $FF000000, true);
SimpleFill(Image4.Bitmap, pts, $80000000, $FFFFFFFF);
InflateRect(rec1,-10,-10);
SimpleLine(Image4.Bitmap, MakeArrayOfFixedPoints(rec1), $20000000, true);
text32 := TText32.Create;
try
text32.Scale(sbScaleX.Position/50, sbScaleY.Position/50);
text32.Skew(sbSkewX.Position/10, sbSkewY.Position/40);
text32.Angle := Constrain(sbRotation.Position, -45, 45);
linePos := 0;
textArrayPos := 0;
ttfc.GetTextMetrics(tm);
lineHeight := round(tm.tmHeight * text32.ScaleY *6/5);
//set starting point for text drawing ...
startPt := FloatPoint(rec1.Left, rec1.Top + lineHeight);
pt := startPt;
while textArrayPos < length(txt3) do
begin
//nb: while we're starting a new string in txt3[] here,
//it's very likely we're *not* at the start of a new line.
GetCurrentColor(textArrayPos);
currentText := txt3[textArrayPos];
inc(textArrayPos);
len := length(currentText);
chrPos := 1;
while chrPos <= len do
begin
currentLine := copy(currentText, chrPos, MaxInt);
//Because the first char in each line is flush up against the left side
//of the bounding rectangle, it's possible for the glyph to partially
//overlap that boundary (especially when the text is skewed or rotated).
//Therefore if we're at the start of a line, it's important to adjust
//the X offset (and rounding just minimizes any character blurring) ...
if pt.X = startPt.X then
pt.X := round(pt.X - text32.GetTextFixedRect(0,0,
currentLine[1], ttfc).Left *FixedToFloat);
//now trim currentLine so that it fits inside rec ...
chrCnt := text32.CountCharsThatFit(pt.X, pt.Y, currentLine, ttfc, rec1, true);
if (chrCnt < length(currentLine))
and (currentLine[chrCnt+1] = ' ') then inc(chrCnt);
currentLine := copy(currentLine, 1, chrCnt);
text32.Draw(Image4.Bitmap, pt.X, pt.Y, currentLine, ttfc, currentColor);
//finally, get ready for the next loop ...
inc(chrPos, chrCnt);
if chrPos > len then break;
inc(linePos);
pt.X := startPt.X;
pt.Y := startPt.Y + linePos*lineHeight;
if chrPos > len then
text32.CurrentPos := FixedPoint(pt);
//and make sure we haven't reached the bottom ...
if pt.Y > rec1.Bottom then
begin
textArrayPos := MaxInt; //ie force a complete break
break;
end;
end;
//make sure the next string in txt3[] starts drawing at the right place...
pt := FloatPoint(text32.CurrentPos);
end;
finally
text32.Free;
end;
Image4.Bitmap.EndUpdate;
end;
//------------------------------------------------------------------------------
end.
|
unit XERO.API.Invoices;
interface
uses
System.SysUtils, DB,
Classes, XERO.API, XERO.API.Response.ClientDataset;
// Invoice Status
// ---
// DRAFT A Draft Invoice (default)
// SUBMITTED An Awaiting Approval Invoice
// DELETED A Deleted Invoice
// AUTHORISED An Invoice that is Approved and Awaiting Payment OR partially paid
// PAID An Invoice that is completely Paid
// VOIDED A Voided Invoice
type
TXEROInvoiceStatus = (isUnspecified, isDraft, isSubmitted, isDeleted,
isAuthorised, isPaid, isVoided);
// Invoice Type
// ---
// ACCPAY A bill – commonly known as a Accounts Payable or supplier invoice
// ACCREC A sales invoice – commonly known as an Accounts Receivable or customer invoice
type
TXEROInvoiceType = (itUnspecified, itAccPay, itAccRec);
type
TXEROInvoiceResponse = class(TXEROResponseDatasetBase)
protected
procedure AddCustomMasterDatasetFields; override;
procedure AddCustomDetailDatasetFields; override;
procedure GetFieldInformation(AFieldName: string;
var AFieldType: TFieldType; var ASize: Integer); override;
procedure GetDefaultValues; override;
published
property MasterDataset;
property DetailDataset;
end;
type
TXEROInvoices = class(TXEROAPI)
private
protected
function GetAPIURL: string; override;
function GetInvoiceStatus(AInvoiceStatus: TXEROInvoiceStatus): string;
function GetInvoiceType(AInvoiceType: TXEROInvoiceType): string;
public
function Find(APage: Integer = 0; AOrderBy: string = '';
AInvoiceType: TXEROInvoiceType = itUnspecified;
AInvoiceStatus: TXEROInvoiceStatus = isUnspecified;
AInvoiceID: string = ''; AInvoiceNumber: string = '';
AReference: string = ''; ADate: TDateTime = 0; ADueDate: TDateTime = 0;
ALastModified: TDateTime = 0): Boolean; overload;
function GetDateRange(AStartDate: TDateTime; AEndDate: TDateTime;
APage: Integer = 0;
AInvoiceType: TXEROInvoiceType = itUnspecified): Boolean;
published
end;
implementation
uses
XERO.Utils;
// TXEROInvoiceResponse
procedure TXEROInvoiceResponse.AddCustomMasterDatasetFields;
begin
end;
procedure TXEROInvoiceResponse.AddCustomDetailDatasetFields;
begin
end;
procedure TXEROInvoiceResponse.GetFieldInformation(AFieldName: string;
var AFieldType: TFieldType; var ASize: Integer);
begin
inherited GetFieldInformation(AFieldName, AFieldType, ASize);
if (UpperCase(AFieldName) = 'DATE') or (UpperCase(AFieldName) = 'DUEDATE') or
(UpperCase(AFieldName) = 'FULLYPAIDONDATE') then
begin
AFieldType := ftDate;
ASize := 0;
end;
if (UpperCase(AFieldName) = 'UPDATEDDATEUTC') then
begin
AFieldType := ftDateTime;
ASize := 0;
end;
if (UpperCase(AFieldName) = 'SUBTOTAL') or
(UpperCase(AFieldName) = 'TOTALTAX') or (UpperCase(AFieldName) = 'TOTAL') or
(UpperCase(AFieldName) = 'AMOUNTDUE') or
(UpperCase(AFieldName) = 'AMOUNTPAID') or
(UpperCase(AFieldName) = 'AMOUNTCREDITED') or
(UpperCase(AFieldName) = 'UNITAMOUNT') or
(UpperCase(AFieldName) = 'TAXAMOUNT') then
begin
AFieldType := ftCurrency;
ASize := 0;
end;
end;
procedure TXEROInvoiceResponse.GetDefaultValues;
begin
MasterListNodeName := 'Invoices';
MasterNodeName := 'Invoice';
DetailListNodeName := 'LineItems';
DetailNodeName := 'LineItem';
MasterFields := 'InvoiceID';
end;
// TXEROInvoices
function TXEROInvoices.GetAPIURL: string;
begin
Result := XERO_API_BASE_URL + 'Invoices';
end;
function TXEROInvoices.GetInvoiceStatus(AInvoiceStatus
: TXEROInvoiceStatus): string;
begin
case AInvoiceStatus of
isUnspecified:
Result := '';
isDraft:
Result := 'DRAFT';
isSubmitted:
Result := 'SUBMITTED';
isDeleted:
Result := 'DELETED';
isAuthorised:
Result := 'AUTHORISED';
isPaid:
Result := 'PAID';
isVoided:
Result := 'VOIDED';
end;
end;
function TXEROInvoices.GetInvoiceType(AInvoiceType: TXEROInvoiceType): string;
begin
case AInvoiceType of
itUnspecified:
Result := '';
itAccPay:
Result := 'ACCPAY';
itAccRec:
Result := 'ACCREC';
end;
end;
function TXEROInvoices.Find(APage: Integer = 0; AOrderBy: string = '';
AInvoiceType: TXEROInvoiceType = itUnspecified;
AInvoiceStatus: TXEROInvoiceStatus = isUnspecified; AInvoiceID: string = '';
AInvoiceNumber: string = ''; AReference: string = ''; ADate: TDateTime = 0;
ADueDate: TDateTime = 0; ALastModified: TDateTime = 0): Boolean;
var
Filter: string;
InvoiceStatus, InvoiceType, InvoiceDueDate, InvoiceDate: string;
procedure AddToFilter(AFieldName: string; AData: string;
AQuoteData: Boolean = true);
var
Data: string;
begin
if AQuoteData then
begin
Data := '"' + AData + '"';
end
else
begin
Data := AData;
end;
if not IsEmptyString(AData) then
begin
if not IsEmptyString(Filter) then
begin
Filter := Filter + ' AND ';
end;
Filter := Filter + AFieldName + '==' + Data;
end;
end;
begin
Filter := '';
InvoiceStatus := GetInvoiceStatus(AInvoiceStatus);
InvoiceType := GetInvoiceType(AInvoiceType);
InvoiceDueDate := GetDateTimeFilterString(ADueDate);
InvoiceDate := GetDateTimeFilterString(ADate);
AddToFilter('Status', InvoiceStatus);
AddToFilter('Type', InvoiceType);
AddToFilter('InvoiceID', AInvoiceID);
AddToFilter('InvoiceNumber', AInvoiceNumber);
AddToFilter('Reference', AReference);
AddToFilter('DueDate', InvoiceDueDate, False);
AddToFilter('Date', InvoiceDate, False);
Debug('Find', Format('Filter: %s', [Filter]));
Result := Find(Filter, AOrderBy, APage, ALastModified);
end;
function TXEROInvoices.GetDateRange(AStartDate: TDateTime; AEndDate: TDateTime;
APage: Integer = 0; AInvoiceType: TXEROInvoiceType = itUnspecified): Boolean;
var
Filter: string;
InvoiceType: string;
StartDate, EndDate: string;
begin
Filter := '';
InvoiceType := GetInvoiceType(AInvoiceType);
StartDate := GetDateTimeFilterString(AStartDate);
EndDate := GetDateTimeFilterString(AEndDate);
if not IsEmptyString(InvoiceType) then
begin
Filter := Filter + 'Type=="' + InvoiceType + '"';
end;
if not IsEmptyString(Filter) then
begin
Filter := Filter + ' AND ';
end;
Filter := Filter + 'Date>=' + StartDate + ' AND Date <= ' + EndDate;
Debug('GetDateRange', Format('Filter: %s', [Filter]));
Result := Find(Filter, 'Date ASC', APage);
end;
end.
|
unit Vigilante.Aplicacao.SituacaoBuild;
interface
type
TSituacaoBuild = (sbUnknow, sbProgresso, sbFalhouInfra, sbAbortado, sbFalhou,
sbSucesso);
TSituacaoBuildSet = set of TSituacaoBuild;
TSituacaoHelper = record helper for TSituacaoBuild
class function Parse(const AValue: string): TSituacaoBuild; overload;
static; inline;
class function Parse(const AValue: integer): TSituacaoBuild; overload;
static; inline;
function AsInteger: integer; inline;
function AsString: string; inline;
function Equals(const ASituacao: TSituacaoBuild): boolean; inline;
end;
const
SITUACOES_NOTIFICAVEIS: TSituacaoBuildSet = [sbSucesso, sbFalhou,
sbFalhouInfra, sbAbortado];
implementation
uses
System.SysUtils, System.TypInfo;
function TSituacaoHelper.AsInteger: integer;
begin
result := Ord(Self);
end;
class function TSituacaoHelper.Parse(const AValue: string): TSituacaoBuild;
var
_situacao: string;
begin
_situacao := AValue.ToUpper;
result := sbUnknow;
if _situacao.Equals('SUCCESS') then
Exit(sbSucesso);
if _situacao.Equals('FAILURE') then
Exit(sbFalhou);
if _situacao.Equals('ABORTED') then
Exit(sbAbortado);
end;
function TSituacaoHelper.AsString: string;
begin
case Self of
sbUnknow:
result := 'Não informado';
sbProgresso:
result := 'Em progresso';
sbFalhouInfra:
result := 'Falha de infra';
sbAbortado:
result := 'Abortado';
sbFalhou:
result := 'Falhou';
sbSucesso:
result := 'Sucesso';
end;
end;
function TSituacaoHelper.Equals(const ASituacao: TSituacaoBuild): boolean;
begin
result := Self.AsInteger = ASituacao.AsInteger;
end;
class function TSituacaoHelper.Parse(const AValue: integer): TSituacaoBuild;
begin
result := TSituacaoBuild(AValue);
end;
end.
|
unit BTREE;
INTERFACE
TYPE
TreePtr = ^Tree;
Tree = RECORD
DataPtr : POINTER;
left,
right : TreePtr;
END;
CompProc = FUNCTION(ptr1,ptr2 : POINTER) : BOOLEAN;
{ Return TRUE if first item is less than second }
VAR
LessThan : CompProc;
PROCEDURE AddData(VAR BaseRoot : TreePtr; Data : POINTER);
{ root should be NIL first time AddData is called }
FUNCTION DummyCompProc( ptr1,ptr2 : POINTER) : BOOLEAN;
IMPLEMENTATION
FUNCTION DummyCompProc( ptr1,ptr2 : POINTER) : BOOLEAN;
BEGIN
Writeln('You must initialize the LessThan process! to use STree!');
HALT;
END;
FUNCTION STree(root, r : TreePtr;
Data : POINTER) : TreePtr;
BEGIN
IF r = NIL THEN
BEGIN
New(r);
r^.left := NIL;
r^.right := NIL;
r^.dataptr := Data;
IF LessThan(Data,root^.dataptr) THEN
root^.left := r
ELSE
root^.right := r;
STree := r;
END ELSE
IF LessThan(Data,root^.dataptr) THEN
STree := STree(r,r^.left,Data)
ELSE
Stree := STree(r,r^.right,Data);
END {STree};
PROCEDURE AddData(VAR BaseRoot : TreePtr; Data : POINTER);
VAR
dummy : TreePtr;
BEGIN
IF BaseRoot = NIL THEN
BaseRoot := STree(BaseRoot,BaseRoot,Data)
{
BEGIN
New(BaseRoot);
WITH BaseRoot^ DO
BEGIN
left := NIL;
right := NIL;
dataptr := Data;
END;
END
}
ELSE
dummy := STree(BaseRoot,BaseRoot,Data);
END {AddData};
BEGIN
LessThan := DummyCompProc;
END. |
unit HKSearchHeader;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls,
StdCtrls, HKPaginationModel, ZConnection, ZDataset;
type
{ THKSearchHeader }
{ THKSearchPanelHeader }
THKSearchPanelHeader=class(TPanel)
private
FOnPerPageChange: TNotifyEvent;
FOnReloadBtnClick: TNotifyEvent;
FOnSearchKeyPress: TKeyPressEvent;
FPerPageValue: Integer;
FSearch:TEdit;
FBtn:TButton;
FCbPerPage:TComboBox;
fLabel:TLabel;
procedure BtnClick(Sender: TObject);
procedure CbPerPageChanged(Sender: TObject);
function GetSearchText: String;
procedure SearchKeyPress(Sender: TObject; var Key: char);
procedure SetOnPerPageChange(AValue: TNotifyEvent);
procedure SetOnReloadBtnClick(AValue: TNotifyEvent);
procedure SetOnSearchKeyPress(AValue: TKeyPressEvent);
protected
procedure DoOnResize; override;
procedure DoReloadBtnClick;virtual;
procedure DoCbPerPageChange(newPerPage:Integer);virtual;
procedure DoSearchKeyPress(var key:Char);virtual;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
property OnReloadBtnClick:TNotifyEvent read FOnReloadBtnClick write SetOnReloadBtnClick;
property OnSearchKeyPress:TKeyPressEvent read FOnSearchKeyPress write SetOnSearchKeyPress;
property OnPerPageChange:TNotifyEvent read FOnPerPageChange write SetOnPerPageChange;
property PerPageValue:Integer read FPerPageValue;
property SearchText:String read GetSearchText;
end;
THKSearchHeader = class(THKSearchPanelHeader)
private
FPaginationModel: THKPaginationModel;
procedure SetPaginationModel(AValue: THKPaginationModel);
protected
procedure DoReloadBtnClick; override;
procedure DoCbPerPageChange(newPerPage: Integer); override;
procedure DoSearchKeyPress(var key: Char); override;
published
property PaginationModel:THKPaginationModel read FPaginationModel write SetPaginationModel;
end;
THKSearchHeaderComp=class(THKSearchPanelHeader)
published
property OnPerPageChange;
property OnReloadBtnClick;
property OnSearchKeyPress;
property PerPageValue;
end;
procedure Register;
implementation
procedure Register;
begin
{$I hksearchheader_icon.lrs}
RegisterComponents('HKCompPacks',[THKSearchHeader]);
RegisterComponents('HKCompPacks',[THKSearchHeaderComp]);
end;
{ THKSearchPanelHeader }
procedure THKSearchPanelHeader.BtnClick(Sender: TObject);
begin
FSearch.Text:='';
DoReloadBtnClick;
end;
procedure THKSearchPanelHeader.CbPerPageChanged(Sender: TObject);
var
newPage: Longint;
begin
TryStrToInt(FCbPerPage.Text, newPage);
DoCbPerPageChange(newPage);
end;
function THKSearchPanelHeader.GetSearchText: String;
begin
Result:=FSearch.Text;
end;
procedure THKSearchPanelHeader.SearchKeyPress(Sender: TObject; var Key: char);
begin
DoSearchKeyPress(Key);
end;
procedure THKSearchPanelHeader.SetOnPerPageChange(AValue: TNotifyEvent);
begin
if FOnPerPageChange=AValue then Exit;
FOnPerPageChange:=AValue;
end;
procedure THKSearchPanelHeader.SetOnReloadBtnClick(AValue: TNotifyEvent);
begin
if FOnReloadBtnClick=AValue then Exit;
FOnReloadBtnClick:=AValue;
end;
procedure THKSearchPanelHeader.SetOnSearchKeyPress(AValue: TKeyPressEvent);
begin
if FOnSearchKeyPress=AValue then Exit;
FOnSearchKeyPress:=AValue;
end;
procedure THKSearchPanelHeader.DoOnResize;
begin
inherited DoOnResize;
FBtn.Left:=Width-80;
FSearch.Left:=Width-290;
end;
procedure THKSearchPanelHeader.DoReloadBtnClick;
begin
if Assigned(OnReloadBtnClick)then OnReloadBtnClick(Self);
end;
procedure THKSearchPanelHeader.DoCbPerPageChange(newPerPage: Integer);
begin
FPerPageValue:=newPerPage;
if Assigned(OnPerPageChange)then OnPerPageChange(Self);
end;
procedure THKSearchPanelHeader.DoSearchKeyPress(var key: Char);
begin
if Assigned(OnSearchKeyPress)then OnSearchKeyPress(FSearch, key);
end;
constructor THKSearchPanelHeader.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
FPerPageValue:=25;
BevelOuter:=bvNone;
BevelInner:=bvNone;
Width:=400;
Height:=50;
FBtn:=TButton.Create(Self);
FBtn.Parent:=Self;
FBtn.Width:=60;
FBtn.Left:=350;
FBtn.Height:=40;
FBtn.Top:=5;
FBtn.Caption:='Reload';
FBtn.OnClick:=@BtnClick;
FBtn.Anchors:=[akTop, akRight, akBottom];
FSearch:=TEdit.Create(Self);
FSearch.Parent:=Self;
FSearch.Width:=200;
FSearch.Left:=120;
FSearch.Height:=30;
FSearch.Top:=10;
FSearch.OnKeyPress:=@SearchKeyPress;
FSearch.Anchors:=[akTop, akRight, akBottom];
fLabel:=TLabel.Create(Self);
fLabel.Parent:=Self;
fLabel.Left:=10;
fLabel.Width:=105;
fLabel.Height:=30;
fLabel.Top:=12;
fLabel.Caption:='Row Per Page';
fLabel.Anchors:=[akTop, akLeft, akBottom];
FCbPerPage:=TComboBox.Create(Self);
FCbPerPage.Parent:=Self;
FCbPerPage.Left:=110;
FCbPerPage.Width:=65;
FCbPerPage.Height:=30;
FCbPerPage.Top:=10;
FCbPerPage.Anchors:=[akTop, akLeft, akBottom];
FCbPerPage.Items.Add('10');
FCbPerPage.Items.Add('25');
FCbPerPage.Items.Add('50');
FCbPerPage.Items.Add('100');
FCbPerPage.ItemIndex:=1;
FCbPerPage.OnChange:=@CbPerPageChanged;
end;
destructor THKSearchPanelHeader.Destroy;
begin
FBtn.Free;
FCbPerPage.Free;
fLabel.Free;
FSearch.Free;
inherited Destroy;
end;
{ THKSearchHeader }
procedure THKSearchHeader.SetPaginationModel(AValue: THKPaginationModel);
begin
if FPaginationModel=AValue then Exit;
FPaginationModel:=AValue;
FCbPerPage.Text:=FPaginationModel.RowPerPage.ToString;
end;
procedure THKSearchHeader.DoReloadBtnClick;
begin
if not Assigned(PaginationModel) then Exit;
FPaginationModel.SearchQry:='';
FSearch.Text:='';
FPaginationModel.FirstPage;
end;
procedure THKSearchHeader.DoCbPerPageChange(newPerPage: Integer);
begin
if not Assigned(PaginationModel) then Exit;
if newPerPage<=0 then exit;
FPaginationModel.RowPerPage:=newPerPage;
FPaginationModel.Refresh;
end;
procedure THKSearchHeader.DoSearchKeyPress(var key: Char);
begin
if not Assigned(PaginationModel) then Exit;
if Key=#$0d then
begin
FPaginationModel.Search(FSearch.Text);
Key:=#$0;
end;
end;
end.
|
{ Описание модуля Help предназначенного
для создания справочных служб программ,
написанных на языке Turbo Pascal
Version 2.0 Copyright (C)1995 Yury Konovalov Moscow,RASSIA.}
Unit Help;
Interface
Uses Crt;
Const
BlockBegin= '<#Begin'; {Маркер начала блока}
BlockEnd= '<#End'; {Маркер конца блока}
BlockJump= '<#=>'; {Маркер ссылки на блок}
BlockSeparator= '#:'; {Маркер разделения}
BlockCloser= '#>'; {Маркер конца служебной информации}
{ Структра файла помощи :
- состоит из последовательности блоков с оригинальным названием
- блоки не должны перекрываться
- блок начинается с заголовка Начала блока и
заканчивается заголовком конца блока.
- Заголовка Начала блока:
<#Begin[ Имя блока ]#:[ Заголовок окна отображения]#>
[ и ] не ставятся
- Заголовка Конца блока:
<#End[ Имя блока ]#>
[ и ] не ставятся
- В теле блока можно использовать ссылки на другие блоки
структура ссылки :
<#=>[ Имя блока на который перейти ]#:[ строка выделения в окне ]#>
[ и ] не ставятся
Замечание :
Все структуры должны строго соблюдаться ! }
Type
Keys=Set Of Char;
Procedure PutHelp(fs,OrgStr:string;Exs:Keys;col:Byte;ShCol:Byte);
{ fs - строка содержащая полное имя файла помощи }
{ OrgStr - строка содержащая имя блока помощи }
{ Замечание : ВАЖНО собюдать Up и Lo CASE букв в строке}
{ Exs - множество кодов клавиш по которым производить выход}
{ col,ShCol - цвет фона и тени соответственно [0..15]}
End.
{
Пример файла помощи:
<#Begin NoItem #: Не найдено ... #>
Нет информации по этому вопросу.
<#End NoItem #>
<#Begin Help #: Помощь по программе #>
Данная программа предназначена
для расчета сумарной интенсивности отказов
родио-<#=> Тип элемента #: электронного устройства #>эксплуатационной
интенсивности отказов каждого элемента
входящего в это устройство
<#End Help #>
<#Begin Число элементов #: Справка #>
Это число полностью одинаковых элементов.
<#End Число элементов #>
<#Begin Тип элемента #: Типы элементов #>
Это один из типов элементов.
1 - ИС
2 - Диоды
3 - Транзисторы
4 - Конденсаторы
5 - Резисторы
6 - Коммутационные изделия
7 - Трансформаторы
8 - НЧ соединители
9 - Соединения
10- Неопределенный тип
<#End Тип элемента #>
} |
unit MyTreeView;
//# BEGIN TODO Completed by: author name, id.nr., date
{ E.I.R. van Delden, 0618959, 29-06-2008 }
//# END TODO
//------------------------------------------------------------------------------
// This unit defines class TMyTreeView, which is a descendant of the standard
// TTreeView component from the Delphi VCL (Vusial Component Library).
// See the Delphi Help for information on TTreeView !!
//
interface
uses
ComCtrls,
Nodes;
type
TMyTreeView =
class(TTreeView)
private
public
procedure SelectNode(ANode: TNode);
procedure Show(ANode: TNode);
end;
implementation
{ TMyTreeView }
procedure TMyTreeView.SelectNode(ANode: TNode);
var
I: integer;
begin
with Items do
for I := 0 to Count - 1 do
if Item[I].Data = ANode
then Selected := Item[I];
end;
procedure TMyTreeView.Show(ANode: TNode);
//# BEGIN TODO
// Add declarations of local variables and/or functions, if necessary
var
I: Integer;
AFather: TTreeNode;
//# END TODO
procedure RecAddSons(AFather: TTreeNode; ANode: TNode);
var
I: Integer;
begin
//# BEGIN TODO
// Recursively build a tree of TTreeNode with root AFather corresponding to
// the formula tree with root ANode
for I := 0 to ANode.GetNrofSons - 1 do
begin
if ANode.HasData then
begin
Items.AddChild(AFather, ANode.OpName+ '[' + ANode.GetData + ']');
end
else
begin
Items.AddChild( AFather, ANode.OpName);
end;
AFather.Item[I].Data := ANode.GetSon(I);
RecAddSons( AFather.Item[I] , ANode.GetSon(I)); // voeg zoon toe aan de laatste node in de tree view
end;
//# END TODO
end;
begin
//# BEGIN TODO
{ Add code corresponding to the following steps:}
// Clear Items
// Add a new root object corresponding to ANode
// Recursively add sons by means of procedure RecAddSons
// Show the tree in expanded form
Items.Clear; // clear items list
AFather := Items.AddFirst(nil, ANode.OpName); // add root
AFather.Data := ANode;
// Add Nodse
RecAddSons( AFather, ANode);
AFather.Expand(true);
//# END TODO
end;
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Soap.SOAPHTTPDisp;
interface
uses System.Classes, Soap.WSDLIntf;
type
IHTTPSoapDispatch = interface
['{9E733EDC-7639-4DAF-96FF-BCF141F7D8F2}']
procedure DispatchSOAP(const Path, SoapAction: AnsiString; const Request: TStream;
Response: TStream; var BindingType: TWebServiceBindingType);
end;
THTTPSoapDispatchNode = class(TComponent)
private
procedure SetSoapDispatcher(const Value: IHTTPSoapDispatch);
protected
FSoapDispatcher: IHTTPSoapDispatch;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
procedure DispatchSOAP(const Path, SoapAction: AnsiString; const Request: TStream;
Response: TStream); virtual;
published
property Dispatcher: IHTTPSoapDispatch read FSoapDispatcher write SetSoapDispatcher;
end;
implementation
procedure THTTPSoapDispatchNode.SetSoapDispatcher(const Value: IHTTPSoapDispatch);
begin
ReferenceInterface(FSoapDispatcher, opRemove);
FSoapDispatcher := Value;
ReferenceInterface(FSoapDispatcher, opInsert);
end;
procedure THTTPSoapDispatchNode.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and AComponent.IsImplementorOf(FSoapDispatcher) then
FSoapDispatcher := nil;
end;
procedure THTTPSoapDispatchNode.DispatchSOAP(const Path, SoapAction: AnsiString;
const Request: TStream; Response: TStream);
begin
end;
end.
|
{ ********************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ Component and Property Editor Source }
{ }
{ Copyright (C) 2000, 2001 Borland Software Corporation }
{ }
{ Licensees holding valid Kylix Desktop Developer Edition or }
{ Kylix Server Developer Edition licenses may use this file in }
{ accordance with the Borland No-Nonsense License Agreement }
{ provided with the Software, appearing in the file license.txt. }
{ }
{ ********************************************************************** }
unit ClxIconEdit;
interface
uses
SysUtils, Classes, QGraphics, QForms, QDialogs,
LibHelp, DesignIntf, DesignEditors, DsnConst, QStdCtrls, QComCtrls, QControls;
type
TItemInfo = class(TObject)
private
FCaption: string;
FImageIndex: Integer;
public
constructor Create(Item: TIconViewItem);
end;
TClxIconViewItemsEditor = class(TForm)
GroupBox1: TGroupBox;
PropGroupBox: TGroupBox;
New: TButton;
Delete: TButton;
Label1: TLabel;
Label2: TLabel;
TreeView: TTreeView;
Text: TEdit;
Image: TEdit;
Button4: TButton;
Cancel: TButton;
Apply: TButton;
Button7: TButton;
procedure NewClick(Sender: TObject);
procedure DeleteClick(Sender: TObject);
procedure ValueChange(Sender: TObject);
procedure TextExit(Sender: TObject);
procedure ImageExit(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ApplyClick(Sender: TObject);
procedure TreeViewChange(Sender: TObject; Node: TTreeNode);
procedure TreeViewEdited(Sender: TObject; Node: TTreeNode;
var S: string);
procedure Button7Click(Sender: TObject);
procedure TreeViewKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure TreeViewEditing(Sender: TObject; Node: TTreeNode;
var AllowEdit: Boolean);
private
FItems: TIconViewItems;
procedure FlushControls;
procedure GetItem(ItemInfo: TItemInfo; Value: TIconViewItem);
procedure SetItem(Value: TItemInfo);
procedure SetStates;
public
property Items: TIconViewItems read FItems;
end;
{ TIconViewEditor }
type
TIconViewEditor = class(TComponentEditor)
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
TIconViewItemsProperty = class(TClassProperty)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
function EditIconViewItems(AItems: TIconViewItems): Boolean;
implementation
uses Qt;
{$R *.xfm}
function EditIconViewItems(AItems: TIconViewItems): Boolean;
var
I: Integer;
ItemInfo: TItemInfo;
begin
with TClxIconViewItemsEditor.Create(Application) do
try
FItems := AItems;
for I := 0 to Items.Count - 1 do
begin
ItemInfo := TItemInfo.Create(Items[I]);
TreeView.Items.AddObject(nil, ItemInfo.FCaption, ItemInfo);
end;
with TreeView do
if Items.Count > 0 then
begin
Selected := Items.GetFirstNode;
TreeViewChange(nil, Selected);
end;
SetStates;
Result := ShowModal = mrOK;
if Result and Apply.Enabled then
ApplyClick(nil);
finally
Free;
end;
end;
procedure ConvertError(Value: TEdit);
begin
with Value do
begin
SetFocus;
SelectAll;
end;
end;
{ TItemInfo }
constructor TItemInfo.Create(Item: TIconViewItem);
begin
inherited Create;
if Item <> nil then
begin
with Item do
begin
FCaption := Caption;
FImageIndex := ImageIndex;
end;
end
else
FImageIndex := -1;
end;
{ TClxIconViewItemsEditor }
procedure TClxIconViewItemsEditor.SetStates;
begin
Delete.Enabled := TreeView.Items.Count > 0;
PropGroupBox.Enabled := Delete.Enabled;
if not PropGroupBox.Enabled then
New.SetFocus;
Apply.Enabled := False;
end;
procedure TClxIconViewItemsEditor.GetItem(ItemInfo: TItemInfo; Value: TIconViewItem);
begin
with Value do
begin
Caption := ItemInfo.FCaption;
ImageIndex := ItemInfo.FImageIndex;
end;
end;
procedure TClxIconViewItemsEditor.SetItem(Value: TItemInfo);
begin
Image.Enabled := True;
if Value <> nil then
with Value do
begin
Text.Text := FCaption;
Image.Text := IntToStr(FImageIndex);
end
else begin
Text.Text := '';
Image.Text := '';
end;
end;
procedure TClxIconViewItemsEditor.FlushControls;
begin
TextExit(nil);
ImageExit(nil);
end;
procedure TClxIconViewItemsEditor.TreeViewChange(Sender: TObject; Node: TTreeNode);
var
TempEnabled: Boolean;
begin
TempEnabled := Apply.Enabled;
if Node <> nil then
begin
SetStates;
SetItem(TItemInfo(Node.Data));
end
else SetItem(nil);
Apply.Enabled := TempEnabled;
end;
procedure TClxIconViewItemsEditor.NewClick(Sender: TObject);
var
Node: TTreeNode;
begin
Node := TreeView.Items.AddObject(nil, '', TItemInfo.Create(nil));
Node.MakeVisible;
TreeView.Selected := Node;
Text.SetFocus;
Apply.Enabled := True;
end;
procedure TClxIconViewItemsEditor.DeleteClick(Sender: TObject);
var
Node: TTreeNode;
begin
Node := TreeView.Selected;
if Node <> nil then
begin
TItemInfo(Node.Data).Free;
Node.Free;
end;
if TreeView.Items.Count = 0 then SetItem(nil);
SetStates;
Apply.Enabled := True;
end;
procedure TClxIconViewItemsEditor.ValueChange(Sender: TObject);
begin
Apply.Enabled := True;
if Sender = Text then TextExit(Sender);
end;
procedure TClxIconViewItemsEditor.TextExit(Sender: TObject);
var
Node: TTreeNode;
begin
Node := TreeView.Selected;
if Node <> nil then
begin
TItemInfo(Node.Data).FCaption := Text.Text;
Node.Text := Text.Text;
end;
end;
procedure TClxIconViewItemsEditor.ImageExit(Sender: TObject);
var
Node: TTreeNode;
begin
if ActiveControl <> Cancel then
try
Node := TreeView.Selected;
if (Node <> nil) then
begin
if (Node.Data <> nil) then
TItemInfo(Node.Data).FImageIndex := StrToInt(Image.Text);
end;
except
ConvertError(Image);
raise;
end;
end;
procedure TClxIconViewItemsEditor.FormCreate(Sender: TObject);
begin
HelpContext := hcDIconViewItemEdit;
end;
procedure TClxIconViewItemsEditor.ApplyClick(Sender: TObject);
var
Node: TTreeNode;
IconViewItem: TIconViewItem;
begin
FlushControls;
Items.BeginUpdate;
try
Items.Clear;
if TreeView.Items.Count > 0 then Node := TreeView.Items[0]
else Node := nil;
while Node <> nil do
begin
if Node.Data <> nil then
begin
IconViewItem := Items.Add;
GetItem(TItemInfo(Node.Data), IconViewItem);
Node := Node.GetNextSibling;
end
end;
finally
Items.EndUpdate;
end;
with TIconView(Items.Owner) do UpdateItems(0, Items.Count -1);
Apply.Enabled := False;
end;
procedure TClxIconViewItemsEditor.TreeViewEdited(Sender: TObject; Node: TTreeNode;
var S: string);
begin
Text.Text := S;
TextExit(nil);
New.Default := True;
end;
procedure TClxIconViewItemsEditor.Button7Click(Sender: TObject);
begin
InvokeHelp;
end;
procedure TClxIconViewItemsEditor.TreeViewKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
// PostMessage(Handle, UM_TREEEDIT, Key, Longint(Self));
end;
procedure TClxIconViewItemsEditor.TreeViewEditing(Sender: TObject; Node: TTreeNode;
var AllowEdit: Boolean);
begin
New.Default := False;
end;
{ TIconViewEditor }
resourcestring
SIconViewEditor = 'Items Editor...';
procedure TIconViewEditor.ExecuteVerb(Index: Integer);
begin
if EditIconViewItems(TIconView(Component).Items) and
Assigned(Designer) then
Designer.Modified;
end;
function TIconViewEditor.GetVerb(Index: Integer): string;
begin
Result := SIconViewEditor;
end;
function TIconViewEditor.GetVerbCount: Integer;
begin
Result := 1;
end;
{ TIconViewItemsProperty }
procedure TIconViewItemsProperty.Edit;
var
Component: TComponent;
begin
Component := TComponent(GetComponent(0));
if not Assigned(Component) then
Exit;
if EditIconViewItems(TIconView(Component).Items) and
Assigned(Designer) then
Designer.Modified;
end;
function TIconViewItemsProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paMultiSelect, paRevertable];
end;
end.
|
namespace MetalExample;
interface
// Buffer index values shared between shader and Oxygene code to ensure Metal shader buffer inputs match
// Metal API buffer set calls
const AAPLVertexInputIndexVertices = 0;
const AAPLVertexInputIndexViewportSize = 1;
type
vector_float2 = Array[0..1] of Single;
vector_float4 = Array[0..3] of Single;
//vector_float2 = TVector2;
//vector_float4 = TVector4;
type
// This structure defines the layout of each vertex in the array of vertices set as an input to our
// Metal vertex shader. Since this header is shared between our .metal shader and C code,
// we can be sure that the layout of the vertex array in our C code matches the layout that
// our .metal vertex shader expects
// Used in Example1
AAPLVertex1 = record
// Positions in pixel space
// (e.g. a value of 100 indicates 100 pixels from the center)
{$HIDE H7}
position : vector_float2;
// Floating-point RGBA colors
color : Color;//vector_float4;
end;
// Used in Example2
AAPLVertex2 = AAPLVertex1;
//Used in Example 3 and 4
AAPLVertex3 = record
// Positions in pixel space (i.e. a value of 100 indicates 100 pixels from the origin/center)
position : vector_float2;
// 2D texture coordinate
textureCoordinate : vector_float2;
end;
type Color = record
red, green, blue, alpha : Single;
class method create(const r,g,b,a : Single) : Color;
class method createRed() : Color;
class method createGreen() : Color;
class method createBlue() : Color;
end;
Vertex3d = record
position : array[0..2] of Single;
normal : array[0..2] of Single;
color : Color;
tex : array[0..1] of Single;
method toBuffer : array of Single;
class method fromBuffer(const buffer : Array of Single) : Vertex3d;
end;
implementation
class method Color.create(const r: single; const g: single; const b: single; const a: single): Color;
begin
result.red := r;
result.green := g;
result.blue := b;
result.alpha := a;
end;
class method Color.createRed: Color;
begin
result.red := 1;
result.green := 0;
result.blue := 0;
result.alpha := 1;
end;
class method Color.createGreen: Color;
begin
result.red := 0;
result.green := 1;
result.blue := 0;
result.alpha := 1;
end;
class method Color.createBlue: Color;
begin
result.red := 0;
result.green := 0;
result.blue := 1;
result.alpha := 1;
end;
method Vertex3d.toBuffer: array of Single;
begin
result := [position[0], position[1], position[2], normal[0], normal[1], normal[2], tex[0], tex[1]];
end;
class method Vertex3d.fromBuffer(const buffer: array of Single) : Vertex3d;
begin
result := new Vertex3d();
result.position[0] := buffer[0];
result.position[1] := buffer[1];
result.position[2] := buffer[2];
result.normal[0] := buffer[3];
result.normal[1] := buffer[4];
result.normal[2] := buffer[5];
result.color := Color.create(1,0,0,1);
end;
end. |
UNIT afsSect;
INTERFACE
function GetSector( secfield, secnum : BYTE;
short : BOOLEAN) : STRING;
procedure RemapSect(VAR sec1 : BYTE; VAR sec2 : BYTE;VAR sec3 : BYTE);
implementation
TYPE
Codes = ARRAY[0..1] OF CHAR;
CONST
Sec1Array : ARRAY[0..8] OF STRING[30] = (
'NA NOT SPECIFIED',
'HY',
'US',
'MU',
'CB',
'AG',
'MB',
'FO',
'HD'
);
Sec2Array : ARRAY[0..112] OF STRING[30] = (
'NA NOT SPECIFIED',
' 1',
' 2',
' 3',
' 4',
' 5',
' 6',
' 7',
' 8',
' 9',
'10',
'11',
'12',
'13',
'14',
'15',
'16',
'17',
'18',
'19',
'20',
'21',
'22',
'23',
'24',
'25',
'26',
'27',
'28',
'29',
'30',
'31',
'32',
'33',
'34',
'35',
'36',
'37',
'38',
'39',
'40',
'41',
'42',
'43',
'44',
'45',
'46',
'47',
'48',
'49',
'50',
'51',
'52',
'53',
'54',
'55',
'56',
'57',
'58',
'59',
'60',
'61',
'62',
'63',
'64',
'65',
'66',
'67',
'68',
'69',
'70',
'71',
'72',
'73',
'74',
'75',
'76',
'77',
'78',
'79',
'80',
'81',
'82',
'83',
'84',
'85',
'86',
'87',
'88',
'89',
'90',
'91',
'92',
'93',
'94',
'95',
'96',
'97',
'98',
'99',
'GN',
'G2',
'FN',
'FH',
'BD',
'NT',
'OP',
'FU',
'AU',
'CN',
'UK',
'IT',
'US'
);
Sec1New : ARRAY[0..8] OF BYTE = ( 0,11,10,9,11,10,12,13,14);
Sec2New : ARRAY[0..44] OF BYTE = (
{ 0 } 0 { NOT SPECIFIED},
{ 1 } 1 { AEROSPACE/DEFENSE},
{ 2 } 2 { AIR TRANSPORTATION},
{ 3 } 3 { AUTO/VEHICLE},
{ 4 } 4 { BANKS/SAVINGS & LOANS},
{ 5 } 6 { BUILDING MATERIALS},
{ 6 } 5 { CABLE/BROADCASTING},
{ 7 } 7 { CHEMICALS/PLASTICS},
{ 8 } 8 { CONSUMER PRODUCTS},
{ 9 } 9 { CONTAINERS},
{ 10 } 16 { DATA PROCESSING/ELECTRONICS},
{ 11 } 18 { DIVERSE MANUFACTURING},
{ 12 } 35 { DIVERSIFIED},
{ 13 } 17 { FILMED ENTERTAINMENT},
{ 14 } 12 { FOOD/BEVERAGE},
{ 15 } 13 { GAMING},
{ 16 } 14 { HEALTHCARE FAC./SUPPLIES},
{ 17 } 15 { HOMEBUILDERS},
{ 18 } 11 { INSURANCE FINANCIAL},
{ 19 } 17 { LEISURE/AMUSEMENT},
{ 20 } 13 { LODGING},
{ 21 } 18 { MACHINERY},
{ 22 } 20 { OFFICE EQUIPMENT},
{ 23 } 21 { OIL & GAS: FIELD SERVICES},
{ 24 } 22 { OIL & GAS: INTEGRATED},
{ 25 } 23 { OIL & GAS: PRODUCTION},
{ 26 } 24 { OIL & GAS: REFINING},
{ 27 } 10 { PAPER},
{ 28 } 25 { PUBLISHING},
{ 29 } 26 { RAILROADS/EQUIPMENT},
{ 30 } 15 { REAL ESTATE/DEVELOPMENT},
{ 31 } 12 { RESTAURANTS},
{ 32 } 29 { RETAIL: BUILDING SUPPLIES},
{ 33 } 27 { RETAIL: FOOD AND DRUG},
{ 34 } 28 { RETAIL: GENERAL},
{ 35 } 29 { RETAIL: SPECIALTY},
{ 36 } 30 { SERVICES},
{ 37 } 33 { SHIPPING/TRANSPORTATION},
{ 38 } 19 { STEEL/MINING},
{ 39 } 31 { TELECOMMUNICATIONS},
{ 40 } 32 { TEXTILE/APPAREL},
{ 41 } 34 { UTILITIES},
{ 42 } 35 { OTHER CORPORATE},
{ 43 } 1 { Foreign Govt.},
{ 44 } 1 { US Treasury}
);
CountryCode : ARRAY[0..36] OF Codes = (
'US' { 0 US/DOLLAR},
'AD' { 1 AUSTRALIA/$},
'AS' { 2 AUSTRIA/SCHILLING},
'BD' { 3 BAHRAIN/DINAR},
'BF' { 4 BELGIUM/FRANC},
'BK' { 5 BURMA/KYAT},
'CD' { 6 CANADA/DOLLAR},
'DK' { 7 DENMARK/KRONER},
'DM' { 8 GERMANY/MARK},
'EC' { 9 EURO CURR UNIT},
'FF' { 10 FRANCE/FRANC},
'FM' { 11 FINLAND/MARKKA},
'GD' { 12 GREECE/DRACHMA},
'HK' { 13 HONG KONG/$},
'IL' { 14 ITALY/LIRA},
'IP' { 15 IRELAND/PUNT},
'IR' { 16 INDIA/RUPEE},
'JY' { 17 JAPAN/YEN},
'KD' { 18 KUWAIT/DINAR},
'MR' { 19 MALAYSIA/RINGGIT},
'MX' { 36 Multi-Currency},
'NG' { 20 NETH/GUILDER},
'NK' { 21 NORWAY/KRONER},
'NZ' { 22 NEW ZEALAND/$},
'PE' { 23 PORTUGAL/ESCUDO},
'PK' { 24 PAKISTAN/RUPEE},
'SA' { 25 SAUDI/RIYAL},
'SD' { 26 SINGAPORE/$},
'SF' { 27 SWITZ/FRANC},
'SK' { 28 SWEDEN/KRONER},
'SL' { 29 SRI LANKA/RUPEE},
'SO' { 30 S AFRICA/RAND},
'SP' { 31 SPAIN/PESATA},
'TB' { 32 THAILAND/BHAT},
'UD' { 33 UAE/DIRHAM},
'UG' { 34 UGANDA/SCHILLING},
'UK' { 35 BRITAIN/POUND}
);
function GetSector( secfield, secnum : BYTE;
short : BOOLEAN) : STRING;
VAR
tempstr : string;
BEGIN
CASE secfield OF
1: tempstr := Sec1Array[secnum];
2: tempstr := Sec2Array[secnum];
END;
IF Short THEN
GetSector := copy(tempstr,1,2)
ELSE
GetSector := tempstr;
END;
procedure RemapSect(VAR sec1 : BYTE; VAR sec2 : BYTE;VAR sec3 : BYTE);
BEGIN
IF sec2 > 44 THEN
BEGIN
CASE sec2 OF
108 : sec3 := 1;
109 : sec3 := 6;
110 : sec3 := 35;
111 : sec3 := 14;
112 : sec3 := 36;
113 : sec3 := 22;
114 : sec3 := 10;
115 : sec3 := 7;
116 : sec3 := 28;
END;
CASE sec2 OF
100,101,104,105,106 : sec2 := 1;
102,103,107 : sec2 := 2;
ELSE
sec2 := 0;
END
END
ELSE
sec2 := sec2New[sec2];
CASE sec1 OF
2 : sec2 := 1;
5 : sec2 := 3;
END;
sec1 := sec1new[sec1];
END {RemapSect};
END.
|
{*******************************************************}
{ }
{ Delphi REST Client Framework }
{ }
{ Copyright(c) 2013-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$HPPEMIT LINKUNIT}
unit REST.Utils;
interface
uses
System.Classes,
System.SysUtils,
System.Character;
type
TRESTFindDefaultComponent = class
public
class function FindDefaultT<T: TComponent>(AComp: TComponent): T;
class function FindDefaultIntfT<T: IInterface>(AComp: TComponent): T;
class procedure FindAllT<T: TComponent>(AComp: TComponent; ACallback: TProc<T>); overload;
end;
// This URIEncode variant implements an encoding as specified by OAuth mechanisms
function URIEncode(const S: string): string;
procedure ExtractURLSegmentNames(const AUrl: string; AParams: TStrings);
procedure ExtractGetParams(const AUrl: string; var AParams: TStrings);
function RESTComponentIsDesigning(AComp: TComponent): boolean;
implementation
uses
System.TypInfo, System.NetEncoding;
function URIEncode(const S: string): string;
const
RestUnsafeChars: TURLEncoding.TUnsafeChars = [Ord('"'), Ord(''''), Ord(':'), Ord(';'), Ord('<'), Ord('='), Ord('>'),
Ord('@'), Ord('['), Ord(']'), Ord('^'), Ord('`'), Ord('{'), Ord('}'), Ord('|'), Ord('/'), Ord('\'), Ord('?'), Ord('#'),
Ord('&'), Ord('!'), Ord('$'), Ord('('), Ord(')'), Ord(','), Ord('~'), Ord(' '), Ord('*'), Ord('+')];
begin
Result := TNetEncoding.URL.Encode(S, RestUnsafeChars, [TURLEncoding.TEncodeOption.EncodePercent]);
end;
function RESTComponentIsDesigning(AComp: TComponent): boolean;
begin
result := ([csDesigning, csLoading] * AComp.ComponentState = [csDesigning]) and
((AComp.Owner = nil) or ([csDesigning, csLoading] * AComp.Owner.ComponentState = [csDesigning]));
end;
procedure ExtractURLSegmentNames(const AUrl: string; AParams: TStrings);
var
LIndex: integer;
LResource: string;
LName: string;
begin
LResource := AUrl;
LIndex := LResource.IndexOf('{');
while (LIndex >= 0) do
begin
LResource := LResource.Substring(LIndex + 1);
LIndex := LResource.IndexOf('}');
if (LIndex >= 0) then
begin
LName := LResource.Substring(0, LIndex);
if (LName <> '') and (AParams.IndexOf(LName) < 0) then
AParams.Add(LName);
LResource := LResource.Substring(LIndex + 1);
LIndex := LResource.IndexOf('{');
end;
end;
end;
procedure ExtractGetParams(const AUrl: string; var AParams: TStrings);
var
LTokenPos: integer;
LParams: string;
begin
LParams := AUrl;
// absolute URI - remove the protocol
LTokenPos := Pos('://', LParams); { Do not Localize }
if LTokenPos > 0 then
Delete(LParams, 1, LTokenPos + 2);
// separate the path from the parameters
LTokenPos := Pos('?', LParams); { Do not Localize }
if LTokenPos > 0 then
LParams := Copy(LParams, LTokenPos + 1, MaxInt);
// separate the bookmark from the parameters
LTokenPos := Pos('#', LParams); { Do not Localize }
if LTokenPos > 0 then
LParams := Copy(LParams, 1, LTokenPos - 1);
AParams := TStringList.Create;
AParams.NameValueSeparator := '=';
AParams.Delimiter := '&';
AParams.DelimitedText := LParams;
end;
class function TRESTFindDefaultComponent.FindDefaultT<T>(AComp: TComponent): T;
var
I: Integer;
LRoot: TComponent;
begin
Result := nil;
LRoot := AComp;
if (LRoot <> nil) and (LRoot.Owner <> nil) then
LRoot := LRoot.Owner;
if LRoot <> nil then
for I := 0 to LRoot.ComponentCount - 1 do
if LRoot.Components[I] is T then
if not Assigned(Result) then
Result := T(LRoot.Components[I])
else
Exit(nil);
end;
class function TRESTFindDefaultComponent.FindDefaultIntfT<T>(AComp: TComponent): T;
var
I: Integer;
LRoot: TComponent;
LGuid: TGuid;
LIntf: T;
begin
LGuid := GetTypeData(TypeInfo(T)).Guid;
Result := nil;
LRoot := AComp;
if (LRoot <> nil) and (LRoot.Owner <> nil) then
LRoot := LRoot.Owner;
if LRoot <> nil then
for I := 0 to LRoot.ComponentCount - 1 do
if Supports(LRoot.Components[I], LGuid, LIntf) then
if not Assigned(Result) then
Result := LIntf
else
Exit(nil);
end;
class procedure TRESTFindDefaultComponent.FindAllT<T>(AComp: TComponent; ACallback: TProc<T>);
var
I: Integer;
LRoot: TComponent;
begin
LRoot := AComp;
if (LRoot <> nil) and (LRoot.Owner <> nil) then
LRoot := LRoot.Owner;
if LRoot <> nil then
for I := 0 to LRoot.ComponentCount - 1 do
if LRoot.Components[I] is T then
ACallback(T(LRoot.Components[I]));
end;
end.
|
unit fAbout;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
fAutoSz, StdCtrls, ExtCtrls, VA508AccessibilityManager;
type
TfrmAbout = class(TfrmAutoSz)
pnlLogo: TPanel;
Image1: TImage;
lblProductName: TStaticText;
lblFileVersion: TStaticText;
lblCompanyName: TStaticText;
lblComments: TStaticText;
lblCRC: TStaticText;
lblInternalName: TStaticText;
lblOriginalFileName: TStaticText;
pnlBottom: TPanel;
pnlButton: TPanel;
cmdOK: TButton;
pnlCopyright: TPanel;
lblLegalCopyright: TMemo;
pnl508Disclaimer: TPanel;
lbl508Notice: TMemo;
Panel2: TPanel;
Panel3: TPanel;
Panel4: TPanel;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
procedure ShowAbout;
implementation
{$R *.DFM}
uses VAUtils, ORFn;
procedure ShowAbout;
var
frmAbout: TfrmAbout;
begin
frmAbout := TfrmAbout.Create(Application);
try
// ResizeFormToFont(TForm(frmAbout));
frmAbout.lblLegalCopyright.SelStart := 0;
frmAbout.lblLegalCopyright.SelLength := 0;
frmAbout.lbl508Notice.SelStart := 0;
frmAbout.lbl508Notice.SelLength := 0;
frmAbout.ShowModal;
finally
frmAbout.Release;
end;
end;
procedure TfrmAbout.FormCreate(Sender: TObject);
begin
inherited;
lblCompanyName.Caption := 'Developed by the ' + FileVersionValue(Application.ExeName, FILE_VER_COMPANYNAME);
// lblFileDescription.Caption := 'Compiled ' + FileVersionValue(Application.ExeName, FILE_VER_FILEDESCRIPTION); //date
lblFileVersion.Caption := FileVersionValue(Application.ExeName, FILE_VER_FILEVERSION);
lblInternalName.Caption := FileVersionValue(Application.ExeName, FILE_VER_INTERNALNAME);
lblLegalCopyright.Text := FileVersionValue(Application.ExeName, FILE_VER_LEGALCOPYRIGHT);
lblOriginalFileName.Caption := FileVersionValue(Application.ExeName, FILE_VER_ORIGINALFILENAME); //patch
lblProductName.Caption := FileVersionValue(Application.ExeName, FILE_VER_PRODUCTNAME);
lblComments.Caption := FileVersionValue(Application.ExeName, FILE_VER_COMMENTS); // version comment
lblCRC.Caption := 'CRC: ' + IntToHex(CRCForFile(Application.ExeName), 8);
end;
end.
|
unit Legend;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, SUIListBox, Grids, ExtCtrls, Buttons, SUIForm, StrUtils;
type
TLegendForm = class(TForm)
suiForm1: TsuiForm;
btn_Print: TBitBtn;
btn_ok: TBitBtn;
btn_cancel: TBitBtn;
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
sgPingMian: TStringGrid;
sgPaoMian: TStringGrid;
lstLegendAll: TsuiListBox;
Label1: TLabel;
btnDefault: TBitBtn;
procedure sgPingMianExit(Sender: TObject);
procedure sgPaoMianExit(Sender: TObject);
procedure lstLegendAllDblClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure sgPingMianDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure btn_PrintClick(Sender: TObject);
procedure btnDefaultClick(Sender: TObject);
procedure btn_okClick(Sender: TObject);
private
{ Private declarations }
procedure GetRecord;
procedure GetAllLegend;
public
{ Public declarations }
end;
type
TGridCell = record
Grid: TStringGrid;
Col : integer;
Row : integer;
end;
var
LegendForm: TLegendForm;
m_GridCell: TGridCell;
m_LegendNameList_cn:TStringList;
m_LegendNameList_en:TStringList;
implementation
uses MainDM, public_unit;
{$R *.dfm}
procedure TLegendForm.sgPingMianExit(Sender: TObject);
begin
m_GridCell.Grid:= TStringGrid(Sender);
m_GridCell.Col:= TStringGrid(Sender).Col;
m_GridCell.Row:= TStringGrid(Sender).Row;
end;
procedure TLegendForm.sgPaoMianExit(Sender: TObject);
begin
m_GridCell.Grid:= TStringGrid(Sender);
m_GridCell.Col:= TStringGrid(Sender).Col;
m_GridCell.Row:= TStringGrid(Sender).Row;
end;
procedure TLegendForm.lstLegendAllDblClick(Sender: TObject);
begin
m_GridCell.Grid.Cells[m_GridCell.Col, m_GridCell.Row]:= lstLegendAll.Items[lstLegendAll.ItemIndex];
end;
procedure TLegendForm.FormCreate(Sender: TObject);
begin
self.Left := trunc((screen.Width -self.Width)/2);
self.Top := trunc((Screen.Height - self.Height)/2);
sgPingMian.RowHeights[0] := 18;
sgPaoMian.RowHeights[0] := 18;
sgPingMian.Cells[0,0]:= '平';
sgPingMian.Cells[1,0]:= '面';
sgPingMian.Cells[2,0]:= '图';
sgPingMian.Cells[3,0]:= '图';
sgPingMian.Cells[4,0]:= '例';
sgPaoMian.Cells[0,0]:= '部';
sgPaoMian.Cells[1,0]:= '面';
sgPaoMian.Cells[2,0]:= '图';
sgPaoMian.Cells[3,0]:= '图';
sgPaoMian.Cells[4,0]:= '例';
GetAllLegend;
GetRecord;
m_GridCell.Grid:= sgPingMian;
m_GridCell.Col:= 0;
m_GridCell.Row:= 1;
end;
procedure TLegendForm.sgPingMianDrawCell(Sender: TObject; ACol,
ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
if ARow=0 then
AlignGridCell(Sender,ACol,ARow,Rect,taCenter);
end;
procedure TLegendForm.btn_PrintClick(Sender: TObject);
var
I: Integer;
strFileName, strCell, strL_names: string;
FileList: TStringList;
aRow, aCol: integer;
begin
if g_ProjectInfo.prj_no ='' then exit;
FileList := TStringList.Create;
strFileName:= g_AppInfo.PathOfChartFile + 'legend.ini';
try
FileList.Add('[图例]');
if g_ProjectInfo.prj_ReportLanguage= trChineseReport then
FileList.Add('图纸名称='+g_ProjectInfo.prj_name+'图例图')
else if g_ProjectInfo.prj_ReportLanguage= trEnglishReport then
FileList.Add('图纸名称='+g_ProjectInfo.prj_name_en+' Legend');
FileList.Add('工程编号='+g_ProjectInfo.prj_no);
if g_ProjectInfo.prj_ReportLanguage= trChineseReport then
FileList.Add('工程名称='+g_ProjectInfo.prj_name)
else if g_ProjectInfo.prj_ReportLanguage= trEnglishReport then
FileList.Add('工程名称='+g_ProjectInfo.prj_name_en) ;
//开始加入平面图图例
strL_names:='';
for aRow:=1 to sgPingMian.RowCount-1 do
for aCol:= 0 to sgPingMian.ColCount-1 do
begin
strCell:= trim(sgPingMian.Cells[aCol, aRow]);
if strCell<>'' then
begin
if g_ProjectInfo.prj_ReportLanguage =trEnglishReport then
begin
for I := 0 to m_LegendNameList_cn.Count - 1 do // Iterate
begin
if strCell = m_LegendNameList_cn.Strings[i] then
begin
strCell := strCell + REPORT_PRINT_SPLIT_CHAR +
m_LegendNameList_en.Strings[i];
break;
end;
end; // for
end;
strL_names:= strL_names + strCell+',';
end;
end;
if copy(ReverseString(strL_names),1,1)=',' then
delete(strL_names,length(strL_names),1);
FileList.Add('平面图图例='+ strL_names);
//开始加入剖面图图例
strL_names:='';
for aRow:=1 to sgPaoMian.RowCount-1 do
for aCol:= 0 to sgPaoMian.ColCount-1 do
begin
strCell:= trim(sgPaoMian.Cells[aCol, aRow]);
if strCell<>'' then
begin
if g_ProjectInfo.prj_ReportLanguage =trEnglishReport then
begin
for I := 0 to m_LegendNameList_cn.Count - 1 do // Iterate
begin
if strCell = m_LegendNameList_cn.Strings[i] then
begin
strCell := strCell + REPORT_PRINT_SPLIT_CHAR +
m_LegendNameList_en.Strings[i];
break;
end;
end; // for
end;
strL_names:= strL_names + strCell+',';
end;
end;
if copy(ReverseString(strL_names),1,1)=',' then
delete(strL_names,length(strL_names),1);
FileList.Add('剖面图图例='+ strL_names);
FileList.SaveToFile(strFileName);
finally
FileList.Free;
end;
winexec(pAnsichar(getCadExcuteName+' 5,'+strFileName+ ','
+ REPORT_PRINT_SPLIT_CHAR),sw_normal);
end;
procedure TLegendForm.GetRecord;
var
strSQL,strPingMianAll,strPaoMianAll,strL_type,strL_names: String;
i,j, iCount: integer;
LegendList: TStringList;
begin
strPingMianAll:='';
strPaoMianAll:='';
strL_type:='';
strL_names:='';
strSQL:='SELECT prj_no,l_type,l_names '
+'FROM prj_legend '
+' WHERE prj_no='
+''''+g_ProjectInfo.prj_no_ForSQL +'''';
with MainDataModule.qryLegend do
begin
close;
sql.Clear;
sql.Add(strSQL);
open;
i:= 0;
while not Eof do
begin
inc(i);
strL_type:= FieldByName('l_type').AsString;
strL_names:= FieldByName('l_names').AsString;
if strL_type='0' then
strPingMianAll:= strL_names
else if strL_type='1' then
strPaoMianAll:= strL_names;
next;
end;
close;
end;
if i>0 then
begin
LegendList := TStringList.Create;
//开始给sgPingMian的各个Cell赋值
if strPingMianAll<>'' then
begin
DivideString(strPingMianAll,',',LegendList);
if LegendList.Count >0 then
begin
iCount:= -1;
for i:= 1 to sgPingMian.RowCount -1 do
for j:= 0 to sgPingMian.ColCount -1 do
begin
Inc(iCount);
if iCount<LegendList.Count then
sgPingMian.Cells[j,i]:= LegendList.Strings[iCount];
end;
end;
end;
//开始给sgPaoMian的各个Cell赋值
if strPaoMianAll<>'' then
begin
DivideString(strPaoMianAll,',',LegendList);
if LegendList.Count >0 then
begin
iCount:= -1;
for i:= 1 to sgPaoMian.RowCount -1 do
for j:= 0 to sgPaoMian.ColCount -1 do
begin
Inc(iCount);
if iCount<LegendList.Count then
sgPaoMian.Cells[j,i]:= LegendList.Strings[iCount];
end;
end;
end;
LegendList.Free;
end;
end;
procedure TLegendForm.GetAllLegend;
var
strSQL: string;
begin
m_LegendNameList_cn := TStringList.Create ;
m_LegendNameList_en := TStringList.Create ;
strSQL:='SELECT l_type,l_name,l_name_en FROM legend_type';
with MainDataModule.qryPublic do
begin
close;
sql.Clear;
sql.Add(strSQL);
open;
lstLegendAll.Clear;
while not eof do
begin
lstLegendAll.Items.Add(FieldByName('l_name').AsString);
m_LegendNameList_cn.Add(FieldByName('l_name').AsString);
m_LegendNameList_en.Add(FieldByName('l_name_en').AsString);
next;
end;
close;
end;
//取得当前工程的土的图例
strSQL:='select et.ea_name,ISNULL(et.ea_name_en,'''') as ea_name_en'
+' from earthtype et'
+' inner join (select DISTINCT ea_name from stratum_description'
+' WHERE prj_no=' +''''+g_ProjectInfo.prj_no_ForSQL +''') as sd'
+' on sd.ea_name=et.ea_name';
with MainDataModule.qryPublic do
begin
close;
sql.Clear;
sql.Add(strSQL);
open;
while not eof do
begin
lstLegendAll.Items.Add(FieldByName('ea_name').AsString);
m_LegendNameList_cn.Add(FieldByName('ea_name').AsString);
m_LegendNameList_en.Add(FieldByName('ea_name_en').AsString);
next;
end;
close;
end;
SetListBoxHorizonbar(lstLegendAll);
end;
procedure TLegendForm.btnDefaultClick(Sender: TObject);
var
strSQL: string;
aCol,aRow: integer;
procedure ClearGrid(aStringGrid: TStringGrid);
var g: integer;
begin
for g:= 1 to aStringGrid.RowCount-1 do
aStringGrid.rows[g].Clear;
end;
begin
ClearGrid(sgPingMian);
ClearGrid(sgPaoMian);
//取得工程默认的平面图图例。
strSQL:='SELECT l_type,l_name from legend_type WHERE l_default=0';
with MainDataModule.qryPublic do
begin
close;
sql.Clear;
sql.Add(strSQL);
open;
aCol:= 0;
aRow:=1;
while not eof do
begin
if aCol=sgPingMian.ColCount then
begin
aCol:=0;
Inc(aRow);
end;
sgPingMian.Cells[aCol, aRow]:=(FieldByName('l_name').AsString);
Inc(aCol);
next;
end;
close;
end;
//取得当前工程的土的图例
strSQL:='SELECT DISTINCT ea_name FROM stratum_description'
+' WHERE prj_no=' +''''+g_ProjectInfo.prj_no_ForSQL +'''';
with MainDataModule.qryPublic do
begin
close;
sql.Clear;
sql.Add(strSQL);
open;
aCol:= 0;
aRow:=1;
while not eof do
begin
if aCol=sgPaoMian.ColCount then
begin
aCol:=0;
Inc(aRow);
end;
sgPaoMian.Cells[aCol, aRow]:=(FieldByName('ea_name').AsString);
Inc(aCol);
next;
end;
close;
end;
end;
procedure TLegendForm.btn_okClick(Sender: TObject);
var
strSQL, strCell,strL_names: string;
aRow,aCol: integer;
begin
//开始增加或更新平面图图例到工程图例表中。
strSQL:= 'SELECT * FROM prj_legend WHERE prj_no='
+''''+g_ProjectInfo.prj_no_ForSQL +''''
+' AND l_type=0';
strL_names:='';
for aRow:=1 to sgPingMian.RowCount-1 do
for aCol:= 0 to sgPingMian.ColCount-1 do
begin
strCell:= trim(sgPingMian.Cells[aCol, aRow]);
if strCell<>'' then
strL_names:= strL_names + strCell+',';
end;
if copy(ReverseString(strL_names),1,1)=',' then
delete(strL_names,length(strL_names),1);
if isExistedRecord(MainDataModule.qryLegend,strSQL) then
begin
strSQL:= 'UPDATE prj_legend SET l_names=';
strSQL:= strSQL +''''+strL_names+''''+ ' WHERE prj_no='
+''''+g_ProjectInfo.prj_no_ForSQL +''''
+' AND l_type=0';
if not Update_onerecord(MainDataModule.qryLegend,strSQL) then
MessageBox(self.Handle,'平面图图例数据更新失败,不能保存。','提示',MB_OK+MB_ICONERROR);
end
else //当前的平面图图例记录在工程图例表中不存在。
begin
strSQL:= 'INSERT prj_legend (prj_no,l_type,l_names) VALUES(';
strSQL:= strSQL
+''''+g_ProjectInfo.prj_no_ForSQL +'''' +','
+' 0,'+ ''''+strL_names+''''+ ')';
if not Insert_oneRecord(MainDataModule.qryLegend,strSQL) then
MessageBox(self.Handle,'平面图图例数据增加失败,不能保存。','提示',MB_OK+MB_ICONERROR);
end;
//开始增加或更新部面图图例到工程图例表中。
strSQL:= 'SELECT * FROM prj_legend WHERE prj_no='
+''''+g_ProjectInfo.prj_no_ForSQL +''''
+' AND l_type=1';
strL_names:='';
for aRow:=1 to sgPaoMian.RowCount-1 do
for aCol:= 0 to sgPaoMian.ColCount-1 do
begin
strCell:= trim(sgPaoMian.Cells[aCol, aRow]);
if strCell<>'' then
strL_names:= strL_names + strCell+',';
end;
if copy(ReverseString(strL_names),1,1)=',' then
delete(strL_names,length(strL_names),1);
if isExistedRecord(MainDataModule.qryLegend,strSQL) then
begin
strSQL:= 'UPDATE prj_legend SET l_names=';
strSQL:= strSQL +''''+strL_names+''''+ ' WHERE prj_no='
+''''+g_ProjectInfo.prj_no_ForSQL +''''
+' AND l_type=1';
if not Update_onerecord(MainDataModule.qryLegend,strSQL) then
MessageBox(self.Handle,'部面图图例数据更新失败,不能保存。','提示',MB_OK+MB_ICONERROR);
end
else //当前的部面图图例记录在工程图例表中不存在。
begin
strSQL:= 'INSERT prj_legend (prj_no,l_type,l_names) VALUES(';
strSQL:= strSQL
+''''+g_ProjectInfo.prj_no_ForSQL +'''' +','
+' 1,'+ ''''+strL_names+''''+ ')';
if not Insert_oneRecord(MainDataModule.qryLegend,strSQL) then
MessageBox(self.Handle,'部面图图例数据增加失败,不能保存。','提示',MB_OK+MB_ICONERROR);
end;
end;
end.
|
{####################################################################################################################
TINJECT - Componente de comunicação (Não Oficial)
www.tinject.com.br
Novembro de 2019
####################################################################################################################
Owner.....: Joathan Theiller - jtheiller@hotmail.com -
Developer.: Mike W. Lustosa - mikelustosa@gmail.com - +55 81 9.9630-2385
Daniel Oliveira Rodrigues - Dor_poa@hotmail.com - +55 51 9.9155-9228
Robson André de Morais - robinhodemorais@gmail.com
####################################################################################################################
Obs:
- Código aberto a comunidade Delphi, desde que mantenha os dados dos autores e mantendo sempre o nome do IDEALIZADOR
Mike W. Lustosa;
- Colocar na evolução as Modificação juntamente com as informaçoes do colaborador: Data, Nova Versao, Autor;
- Mantenha sempre a versao mais atual acima das demais;
- Todo Commit ao repositório deverá ser declarado as mudança na UNIT e ainda o Incremento da Versão de
compilação (último digito);
####################################################################################################################
Evolução do Código
####################################################################################################################
Autor........:
Email........:
Data.........:
Identificador:
Modificação..:
####################################################################################################################
}
///CEF DOCUMENTAÇÃO
//https://www.briskbard.com/index.php?lang=en&pageid=cef
unit uTInject.ConfigCEF;
interface
uses
System.Classes,
System.SysUtils,
Winapi.Windows,
Vcl.Forms,
DateUtils,
IniFiles,
uCEFApplication, uCEFConstants,
uCEFChromium,
uTInject,
uTInject.constant, Vcl.ExtCtrls, uTInject.Classes ;
type
TCEFConfig = class(TCefApplication)
private
FChromium : TChromium;
FChromiumForm : TForm;
FIniFIle : TIniFile;
Falterdo : Boolean;
FInject : TInject;
FPathFrameworkDirPath: String;
FPathResourcesDirPath: String;
FPathLocalesDirPath : String;
FPathCache : String;
FPathUserDataPath : String;
FPathLogFile : String;
FPathJS : String;
FStartTimeOut : Cardinal;
FErrorInt : Boolean;
FPathJsUpdate : TdateTime;
FLogConsole : String;
FHandleFrm : HWND;
FInDesigner : Boolean;
FLogConsoleActive : Boolean;
FDirIni : String;
procedure SetDefault;
procedure SetPathCache (const Value: String);
procedure SetPathFrameworkDirPath(const Value: String);
procedure SetPathLocalesDirPath (const Value: String);
procedure SetPathLogFile (const Value: String);
procedure SetPathResourcesDirPath(const Value: String);
procedure SetPathUserDataPath (const Value: String);
function TestaOk (POldValue, PNewValue: String): Boolean;
procedure SetChromium (const Value: TChromium);
Function VersaoCEF4Aceita: Boolean;
procedure SetLogConsole(const Value: String);
procedure SetLogConsoleActive(const Value: Boolean);
public
SetEnableGPU : Boolean;
SetDisableFeatures : String;
SetLogSeverity : Boolean;
Procedure UpdateIniFile(Const PSection, PKey, PValue :String);
Procedure UpdateDateIniFile;
function StartMainProcess : boolean;
Procedure SetError;
constructor Create;
destructor Destroy; override;
Function PathJsOverdue : Boolean;
property PathJsUpdate : TdateTime Read FPathJsUpdate;
property IniFIle : TIniFile Read FIniFIle Write FIniFIle;
property PathFrameworkDirPath : String Read FPathFrameworkDirPath Write SetPathFrameworkDirPath;
property PathResourcesDirPath : String Read FPathResourcesDirPath Write SetPathResourcesDirPath;
property PathLocalesDirPath : String Read FPathLocalesDirPath Write SetPathLocalesDirPath;
property PathCache : String Read FPathCache Write SetPathCache;
property PathUserDataPath : String Read FPathUserDataPath Write SetPathUserDataPath;
property PathLogFile : String Read FPathLogFile Write SetPathLogFile;
property PathJs : String Read FPathJS;
property LogConsole : String Read FLogConsole Write SetLogConsole;
property LogConsoleActive : Boolean Read FLogConsoleActive Write SetLogConsoleActive;
Property StartTimeOut : Cardinal Read FStartTimeOut Write FStartTimeOut;
Property Chromium : TChromium Read FChromium Write SetChromium;
Property ChromiumForm : TForm Read FChromiumForm;
Property ErrorInt : Boolean Read FErrorInt;
Property DirINI : String Read FDirINI Write FDirINI;
end;
procedure DestroyGlobalCEFApp;
var
GlobalCEFApp: TCEFConfig = nil;
implementation
uses
uCEFTypes, Vcl.Dialogs, uTInject.Diversos;
{ TCEFConfig }
procedure DestroyGlobalCEFApp;
begin
if (GlobalCEFApp <> nil) then
FreeAndNil(GlobalCEFApp);
end;
procedure TCEFConfig.UpdateDateIniFile;
begin
FPathJsUpdate := Now;
UpdateIniFile('Tinject Comp', 'Ultima interação', FormatDateTime('dd/mm/yy hh:nn:ss', FPathJsUpdate));
end;
procedure TCEFConfig.UpdateIniFile(const PSection, PKey, PValue: String);
begin
if FInDesigner then
Exit;
if (LowerCase(FIniFIle.ReadString(PSection, PKey, '')) <> LowerCase(PValue)) or
(FIniFIle.ValueExists(PSection, PKey) = false) Then
Begin
FIniFIle.WriteString(PSection, PKey, PValue);
Falterdo := true;
End;
end;
constructor TCEFConfig.Create;
begin
FInDesigner := True;
FDirIni := '';
inherited;
end;
procedure TCEFConfig.SetChromium(const Value: TChromium);
Var
LObj: TCOmponent;
begin
//Acha o FORM que esta o componente
try
if FChromium = Value then
Exit;
FChromium := Value;
if FChromium = Nil then
Begin
FChromiumForm := Nil;
Exit;
End;
try
LObj := FChromium;
Repeat
if LObj.Owner is Tform then
Begin
FChromiumForm := Tform(LObj.Owner);
FHandleFrm := FChromiumForm.Handle;
if FChromiumForm.Owner is TInject then
FInject := TInject(FChromiumForm.Owner);
end else //Achou
begin
LObj := LObj.Owner //Nao Achou entao, continua procurando
end;
Until FChromiumForm <> Nil;
Except
raise Exception.Create(MSG_ExceptErrorLocateForm);
end;
Except
//Esse erro nunca deve acontecer.. o TESTADOR nao conseguiu pelo menos..
end;
end;
Procedure TCEFConfig.SetDefault;
begin
if not FInDesigner then //padrão aqui é if not FInDesigner - Mike 28/12/2020
Begin
FIniFIle.WriteString ('Informacao', 'Aplicativo vinculado', Application.ExeName);
FIniFIle.WriteBool ('Informacao', 'Valor True', True);
FIniFIle.WriteBool ('Informacao', 'Valor False', False);
SetDisableFeatures := 'NetworkService,OutOfBlinkCors';
SetEnableGPU := FIniFIle.ReadBool ('Path Defines', 'GPU', True);
SetLogSeverity := FIniFIle.ReadBool ('Path Defines', 'Log Severity', False);
LogConsoleActive := FIniFIle.ReadBool ('Path Defines', 'Log Console Active', False);
PathFrameworkDirPath := FIniFIle.ReadString('Path Defines', 'FrameWork', '');
PathResourcesDirPath := FIniFIle.ReadString('Path Defines', 'Binary', '');
PathLocalesDirPath := FIniFIle.ReadString('Path Defines', 'Locales', '');
Pathcache := FIniFIle.ReadString('Path Defines', 'Cache', '');
PathUserDataPath := FIniFIle.ReadString('Path Defines', 'Data User', '');
PathLogFile := FIniFIle.ReadString('Path Defines', 'Log File', '');
LogConsole := FIniFIle.ReadString('Path Defines', 'Log Console', '');
if LogConsole = '' then
LogConsole := IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName))+'LogTinject\';
End;
Self.FrameworkDirPath := '';
Self.ResourcesDirPath := '';
Self.LocalesDirPath := 'locales';
Self.cache := 'cache';
Self.UserDataPath := 'User Data';
end;
procedure TCEFConfig.SetError;
begin
FErrorInt := True;
end;
procedure TCEFConfig.SetLogConsole(const Value: String);
begin
if Value <> '' then
Begin
FLogConsole := IncludeTrailingPathDelimiter(ExtractFilePath(Value));
ForceDirectories(FLogConsole);
end else
Begin
FLogConsole := '';
End;
end;
procedure TCEFConfig.SetLogConsoleActive(const Value: Boolean);
begin
FLogConsoleActive := Value;
if (LogConsoleActive) and (LogConsole <> '') then
ForceDirectories(LogConsole);
end;
function TCEFConfig.TestaOk(POldValue, PNewValue: String):Boolean;
var
LDir : String;
begin
if AnsiLowerCase(POldValue) = AnsiLowerCase(PNewValue) Then
Begin
Result := False;
Exit;
End;
LDir := ExtractFilePath(PNewValue);
if Self.status = asInitialized then
raise Exception.Create(MSG_ConfigCEF_ExceptNotFoundPATH);
if not DirectoryExists(LDir) then
raise Exception.Create(Format(MSG_ExceptPath, [LDir]));
Result := true;
end;
function TCEFConfig.VersaoCEF4Aceita: Boolean;
begin
if CEF_SUPPORTED_VERSION_MAJOR > VersaoMinima_CF4_Major then
Begin
//Versao e maior!!! entaoo pode1
Result := True;
Exit;
End;
//Se chegou aki!! a versao e MENOR ou IGUAL
//Continuar a testar!
if (CEF_SUPPORTED_VERSION_MAJOR < VersaoMinima_CF4_Major) or
(CEF_SUPPORTED_VERSION_MINOR < VersaoMinima_CF4_Minor) or
(CEF_SUPPORTED_VERSION_BUILD < VersaoMinima_CF4_Release) Then
Result := False else
Result := True;
end;
procedure TCEFConfig.SetPathFrameworkDirPath(const Value: String);
begin
if not TestaOk(FPathFrameworkDirPath, Value) Then
Exit;
FPathFrameworkDirPath := Value;
end;
procedure TCEFConfig.SetPathResourcesDirPath(const Value: String);
begin
if not TestaOk(FPathResourcesDirPath, Value) Then
Exit;
FPathResourcesDirPath := Value;
end;
procedure TCEFConfig.SetPathLocalesDirPath(const Value: String);
begin
if not TestaOk(FPathLocalesDirPath, Value) Then
Exit;
FPathLocalesDirPath := Value;
end;
procedure TCEFConfig.SetPathCache(const Value: String);
begin
if AnsiLowerCase(FPathCache) = AnsiLowerCase(Value) Then
Exit;
ForceDirectories(PWideChar(ExtractFilePath(Value)));
if not TestaOk(FPathCache, Value) Then
Exit;
FPathCache := Value;
end;
procedure TCEFConfig.SetPathUserDataPath(const Value: String);
begin
if not TestaOk(FPathUserDataPath, Value) Then
Exit;
FPathUserDataPath := Value;
end;
function TCEFConfig.StartMainProcess: boolean;
var
Linicio: Cardinal;
LVReque, LVerIdent: String;
FDirApp, Lx: String;
begin
//ta lento pq estou conectado em um tunel estou daki ao meu pc.;. do meu pc a
Result := (Self.status = asInitialized);
if (Result) Then
Begin
//Ja iniciada!! cai fora!!
Exit;
end;
FInDesigner := False;
FDirApp := IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName));
if FDirIni = '' then
FDirIni := FDirApp;
FIniFIle := TIniFile.create(FDirIni + NomeArquivoIni);
Lx := FIniFIle.ReadString('Tinject Comp', 'Ultima interação', '01/01/1500 05:00:00');
FPathJS := FDirApp + NomeArquivoInject;
FErrorInt := False;
FStartTimeOut := 5000; //(+- 5 Segundos)
FPathJsUpdate := StrToDateTimeDef(Lx, StrTodateTime('01/01/1500 00:00'));
SetDefault;
if not VersaoCEF4Aceita then
Begin
FErrorInt := true;
LVReque := IntToStr(VersaoMinima_CF4_Major) + '.' + IntToStr(VersaoMinima_CF4_Minor) + '.' + IntToStr(VersaoMinima_CF4_Release);
LVerIdent := IntToStr(CEF_SUPPORTED_VERSION_MAJOR) + '.' + IntToStr(CEF_SUPPORTED_VERSION_MINOR) + '.' + IntToStr(CEF_SUPPORTED_VERSION_BUILD);
Application.MessageBox(PWideChar(Format(MSG_ConfigCEF_ExceptVersaoErrada, [LVReque, LVerIdent])),
PWideChar(Application.Title), MB_ICONERROR + mb_ok
);
result := False;
Exit;
End;
Self.EnableGPU := SetEnableGPU;
Self.DisableFeatures := SetDisableFeatures;
If PathFrameworkDirPath <> '' then
Self.FrameworkDirPath := PathFrameworkDirPath;
If PathResourcesDirPath <> '' then
Self.ResourcesDirPath := PathResourcesDirPath;
If PathLocalesDirPath <> '' Then
Self.LocalesDirPath := PathLocalesDirPath;
If Pathcache <> '' then
Self.cache := Pathcache;
If PathUserDataPath <> '' then
Self.UserDataPath := PathUserDataPath;
If PathLogFile <> '' then
Self.LogFile := PathLogFile;
If SetLogSeverity then
Self.LogSeverity := LOGSEVERITY_INFO;
DestroyApplicationObject := true;
UpdateIniFile('Path Defines', 'FrameWork', Self.FrameworkDirPath);
UpdateIniFile('Path Defines', 'Binary', Self.ResourcesDirPath);
UpdateIniFile('Path Defines', 'Locales', Self.LocalesDirPath);
UpdateIniFile('Path Defines', 'Cache', Self.cache);
UpdateIniFile('Path Defines', 'Data User', Self.UserDataPath);
UpdateIniFile('Path Defines', 'Log File', Self.LogFile);
UpdateIniFile('Path Defines', 'Log Console', LogConsole);
FIniFIle.WriteBool('Path Defines', 'GPU', SetEnableGPU);
FIniFIle.WriteBool('Path Defines', 'Log Severity', SetLogSeverity);
FIniFIle.WriteBool('Path Defines', 'Log Console Active', LogConsoleActive);
UpdateIniFile('Tinject Comp', 'TInject Versão', TInjectVersion);
UpdateIniFile('Tinject Comp', 'Caminho JS' , TInjectJS_JSUrlPadrao);
UpdateIniFile('Tinject Comp', 'CEF4 Versão' , IntToStr(CEF_SUPPORTED_VERSION_MAJOR) +'.'+ IntToStr(CEF_SUPPORTED_VERSION_MINOR) +'.'+ IntToStr(CEF_SUPPORTED_VERSION_RELEASE) +'.'+ IntToStr(CEF_SUPPORTED_VERSION_BUILD));
UpdateIniFile('Tinject Comp', 'CHROME Versão' , IntToStr(CEF_CHROMEELF_VERSION_MAJOR) +'.'+ IntToStr(CEF_CHROMEELF_VERSION_MINOR) +'.'+ IntToStr(CEF_CHROMEELF_VERSION_RELEASE) +'.'+ IntToStr(CEF_CHROMEELF_VERSION_BUILD));
UpdateIniFile('Tinject Comp', 'Dlls' , LIBCEF_DLL + ' / ' + CHROMEELF_DLL);
if Falterdo then
UpdateDateIniFile;
//Chegou aqui, é porque os PATH são validos e pode continuar
inherited; //Dispara a THREAD la do objeto PAI
if Self.status <> asInitialized then
Exit; //estado invalido!!!! pode trer dado erro acima
Linicio := GetTickCount;
try
if Self.status <> asInitialized then
Self.StartMainProcess;
while Self.status <> asInitialized do
Begin
Sleep(10);
if (GetTickCount - Linicio) >= FStartTimeOut then
Break;
End;
finally
Result := (Self.status = asInitialized);
if not Result then
Application.MessageBox(PWideChar(MSG_ConfigCEF_ExceptConnection), PWideChar(Application.Title), MB_ICONERROR + mb_ok);
end;
end;
procedure TCEFConfig.SetPathLogFile(const Value: String);
begin
if not TestaOk(FPathLogFile, Value) Then
Exit;
FPathLogFile := Value;
end;
destructor TCEFConfig.Destroy;
begin
if not FInDesigner then
FreeandNil(FIniFIle);
inherited;
end;
function TCEFConfig.PathJsOverdue: Boolean;
begin
Result := (MinutesBetween(Now, FPathJsUpdate) > MinutosCOnsideradoObsoletooJS)
end;
initialization
if not Assigned(GlobalCEFApp) then
GlobalCEFApp := TCEFConfig.Create;
finalization
if Assigned(GlobalCEFApp) then
GlobalCEFApp.Free;
end.
|
inherited fBlankLines: TfBlankLines
Width = 380
Height = 280
Font.Charset = ANSI_CHARSET
Font.Height = -15
Font.Name = 'Segoe UI'
ParentFont = False
object Label1: TLabel
Left = 8
Top = 144
Width = 284
Height = 20
Caption = 'Number of returns after the unit'#39's final end.'
end
object Label2: TLabel
Left = 8
Top = 200
Width = 243
Height = 20
Caption = 'Max consecutive blank lines anwhere'
end
object Label3: TLabel
Left = 8
Top = 226
Width = 153
Height = 20
Caption = 'Lines before procedure'
end
object eNumReturnsAfterFinalEnd: TJvValidateEdit
Left = 314
Top = 140
Width = 49
Height = 28
CriticalPoints.MaxValueIncluded = False
CriticalPoints.MinValueIncluded = False
EditText = '0'
HasMaxValue = True
HasMinValue = True
MaxLength = 3
MaxValue = 255.000000000000000000
TabOrder = 1
end
object cbRemoveConsecutiveBlankLines: TCheckBox
Left = 8
Top = 176
Width = 262
Height = 17
Caption = 'Remove consecutive blank lines'
TabOrder = 2
end
object edtMaxConsecutiveBlankLines: TJvValidateEdit
Left = 314
Top = 192
Width = 49
Height = 28
CriticalPoints.MaxValueIncluded = False
CriticalPoints.MinValueIncluded = False
EditText = '0'
HasMaxValue = True
HasMinValue = True
MaxLength = 3
MaxValue = 99.000000000000000000
TabOrder = 3
end
object gbRemoveBlankLines: TGroupBox
Left = 8
Top = 3
Width = 366
Height = 126
Caption = 'Remove blank lines'
TabOrder = 0
object Label4: TLabel
Left = 8
Top = 94
Width = 289
Height = 20
Caption = 'Max consecutive blank lines before removal'
end
object cbRemoveBlockBlankLines: TCheckBox
Left = 8
Top = 67
Width = 289
Height = 17
Caption = 'At start and end of begin..end block'
TabOrder = 2
end
object cbRemoveBlankLinesAfterProcHeader: TCheckBox
Left = 8
Top = 44
Width = 289
Height = 17
Caption = 'After procedure header'
TabOrder = 1
end
object cbRemoveVarBlankLines: TCheckBox
Left = 8
Top = 21
Width = 289
Height = 17
Caption = 'In procedure var section'
TabOrder = 0
end
object edtMaxBlankLinesInSection: TJvValidateEdit
Left = 306
Top = 91
Width = 49
Height = 28
CriticalPoints.MaxValueIncluded = False
CriticalPoints.MinValueIncluded = False
EditText = '0'
HasMaxValue = True
HasMinValue = True
MaxLength = 3
MaxValue = 99.000000000000000000
TabOrder = 3
end
end
object edtLinesBeforeProcedure: TJvValidateEdit
Left = 314
Top = 226
Width = 49
Height = 28
CriticalPoints.MaxValueIncluded = False
CriticalPoints.MinValueIncluded = False
EditText = '0'
HasMaxValue = True
HasMinValue = True
MaxLength = 1
MaxValue = 9.000000000000000000
TabOrder = 4
end
end
|
unit main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, JvGammaPanel,
JvTypes;
type
{ TDemoForm }
TDemoForm = class(TForm)
FgColorBtn: TColorButton;
BgColorBtn: TColorButton;
JvGammaPanel1: TJvGammaPanel;
DemoLabel: TLabel;
procedure BgColorBtnColorChanged(Sender: TObject);
procedure FgColorBtnColorChanged(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure JvGammaPanel1ChangeColor(Sender: TObject; FgColor, BgColor: TColor);
private
public
end;
var
DemoForm: TDemoForm;
implementation
{$R *.lfm}
{ TDemoForm }
procedure TDemoForm.BgColorBtnColorChanged(Sender: TObject);
begin
JvGammaPanel1.BackgroundColor := BgColorBtn.ButtonColor;
end;
procedure TDemoForm.FgColorBtnColorChanged(Sender: TObject);
begin
JvGammaPanel1.ForegroundColor := FgColorBtn.ButtonColor;
end;
procedure TDemoForm.FormCreate(Sender: TObject);
begin
FgColorBtn.ButtonColor := JvGammaPanel1.ForegroundColor;
BgColorBtn.ButtonColor := JvGammaPanel1.BackgroundColor;
DemoLabel.Color := JvGammaPanel1.BackgroundColor;
Demolabel.Font.Color := JvGammaPanel1.ForegroundColor;
end;
procedure TDemoForm.JvGammaPanel1ChangeColor(Sender: TObject; FgColor, BgColor: TColor);
begin
DemoLabel.Color := BgColor;
DemoLabel.Font.Color := FgColor;
end;
end.
|
unit Thread.Download;
interface
uses
Classes, SysUtils,
Thread.Download.Helper;
type
TDownloadThread = class(TThread)
private
Downloader: TDownloader;
Request: TDownloadRequest;
IsRequestSet: Boolean;
PostDownloadMethod: TThreadMethod;
IsPostDownloadMethodSet: Boolean;
protected
procedure Execute; override;
procedure PostDownloadMethodWithSynchronization;
public
constructor Create; overload;
constructor Create(CreateSuspended: Boolean); overload;
destructor Destroy; override;
procedure SetRequest(Request: TDownloadRequest);
procedure SetPostDownloadMethod(PostDownloadMethod: TThreadMethod);
end;
implementation
constructor TDownloadThread.Create;
begin
Create(true);
end;
constructor TDownloadThread.Create(CreateSuspended: Boolean);
begin
inherited Create(CreateSuspended);
Downloader := TDownloader.Create;
IsRequestSet := false;
IsPostDownloadMethodSet := false;
FreeOnTerminate := true;
end;
destructor TDownloadThread.Destroy;
begin
FreeAndNil(Downloader);
inherited Destroy;
end;
procedure TDownloadThread.Execute;
begin
if IsRequestSet then
begin
Downloader.DownloadFile(Request, self);
PostDownloadMethodWithSynchronization;
end;
end;
procedure TDownloadThread.PostDownloadMethodWithSynchronization;
begin
Synchronize(PostDownloadMethod);
end;
procedure TDownloadThread.SetPostDownloadMethod(
PostDownloadMethod: TThreadMethod);
begin
IsPostDownloadMethodSet := true;
self.PostDownloadMethod := PostDownloadMethod;
end;
procedure TDownloadThread.SetRequest(Request: TDownloadRequest);
begin
IsRequestSet := true;
self.Request := Request;
end;
end.
|
unit RuleConfig;
interface
uses
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls;
type
TRuleConfigForm = class(TForm)
CB1: TCheckBox;
CB2: TCheckBox;
CB3: TCheckBox;
Label1: TLabel;
LowRuleEdit: TEdit;
CB4: TCheckBox;
CB5: TCheckBox;
CB6: TCheckBox;
Label2: TLabel;
Label3: TLabel;
RuleHighEdit: TEdit;
OutPutCB: TCheckBox;
NextBtn: TButton;
DisplayAllBtn: TButton;
CloseBTN: TButton;
ClearBtn: TButton;
procedure CB3Click(Sender: TObject);
procedure OutPutCBClick(Sender: TObject);
procedure CloseBTNClick(Sender: TObject);
procedure LowRuleEditChange(Sender: TObject);
procedure RuleHighEditChange(Sender: TObject);
procedure ClearBtnClick(Sender: TObject);
private
{ Private declarations }
public
procedure GetStateOut;
end;
var
RuleConfigForm: TRuleConfigForm;
implementation
uses
UserIterface;
{$R *.dfm}
{ TForm2 }
procedure TRuleConfigForm.GetStateOut;
var
StateIndex : Integer;
begin
StateIndex := 0;
if CB1.Checked then StateIndex := StateIndex or 1;
if CB2.Checked then StateIndex := StateIndex or 2;
if CB3.Checked then StateIndex := StateIndex or 4;
if CB4.Checked then StateIndex := StateIndex or 8;
if CB5.Checked then StateIndex := StateIndex or 16;
if CB6.Checked then StateIndex := StateIndex or 32;
OutPutCB.Checked := (UserInterfaceForm.Automata.PossibleStates.GetResult(StateIndex) = 1);
end;
procedure TRuleConfigForm.CB3Click(Sender: TObject);
begin
GetStateOut;
end;
procedure TRuleConfigForm.OutPutCBClick(Sender: TObject);
var
StateIndex : Integer;
Value : Integer;
begin
StateIndex := 0;
if CB1.Checked then StateIndex := StateIndex or 1;
if CB2.Checked then StateIndex := StateIndex or 2;
if CB3.Checked then StateIndex := StateIndex or 4;
if CB4.Checked then StateIndex := StateIndex or 8;
if CB5.Checked then StateIndex := StateIndex or 16;
if CB6.Checked then StateIndex := StateIndex or 32;
if OutPutCB.Checked then
Value := 1
else
Value := 0;
UserInterfaceForm.Automata.PossibleStates.SetResult(StateIndex, Value);
//LowRuleEdit.Text := IntToStr(UserInterfaceForm.Automata.PossibleStates.RuleNumberLow);
//RuleHighEdit.Text := IntToStr(UserInterfaceForm.Automata.PossibleStates.RuleNumberHigh);
end;
procedure TRuleConfigForm.CloseBTNClick(Sender: TObject);
begin
Close;
end;
procedure TRuleConfigForm.LowRuleEditChange(Sender: TObject);
begin
try
//UserInterfaceForm.Automata.PossibleStates.RuleNumberLow := StrToInt(LowRuleEdit.Text);
//CB3Click(nil);
except
end;
end;
procedure TRuleConfigForm.RuleHighEditChange(Sender: TObject);
begin
try
//UserInterfaceForm.Automata.PossibleStates.RuleNumberHigh := StrToInt(RuleHighEdit.Text);
//CB3Click(nil);
except
end;
end;
procedure TRuleConfigForm.ClearBtnClick(Sender: TObject);
begin
UserInterfaceForm.Automata.PossibleStates.Clear;
CB1.Checked := False;
CB2.Checked := False;
CB3.Checked := False;
CB4.Checked := False;
CB5.Checked := False;
CB6.Checked := False;
end;
end.
|
unit VA508ImageListLabeler;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, ImgList, VAClasses, Graphics, ComCtrls,
Contnrs, Forms, oleacc2, VA508MSAASupport;
type
TVA508ImageListLabeler = class;
TVA508ImageListLabels = class;
TVA508ImageListLabel = class(TCollectionItem)
private
FImageIndex: integer;
FCaption: string;
FOverlayIndex: integer;
procedure SetImageIndex(const Value: integer);
procedure Changed;
procedure SetCaption(const Value: string);
procedure SetOverlayIndex(const Value: integer);
protected
procedure Refresh;
function Labeler: TVA508ImageListLabeler;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
published
property Caption: string read FCaption write SetCaption;
property ImageIndex: integer read FImageIndex write SetImageIndex;
property OverlayIndex: integer read FOverlayIndex write SetOverlayIndex;
end;
TVA508ImageListLabels = class(TCollection)
private
FOwner: TVA508ImageListLabeler;
FColumns: TStringList;
FImageData: TStrings;
FOverlayData: TStrings;
FBuildOverlayData: boolean;
protected
function GetAttrCount: Integer; override;
function GetAttr(Index: Integer): string; override;
function GetItemAttr(Index, ItemIndex: Integer): string; override;
function GetItem(Index: Integer): TVA508ImageListLabel;
procedure SetItem(Index: Integer; Value: TVA508ImageListLabel);
procedure Notify(Item: TCollectionItem; Action: TCollectionNotification); override;
procedure Update(Item: TCollectionItem); override;
function GetImageData: TStrings;
function GetOverlayData: TStrings;
procedure ResetData;
public
constructor Create(Owner: TVA508ImageListLabeler);
destructor Destroy; override;
function GetOwner: TPersistent; override;
function Add: TVA508ImageListLabel;
property Items[Index: Integer]: TVA508ImageListLabel read GetItem write SetItem; default;
end;
TVA508ImageListComponent = class(TCollectionItem)
private
FComponent: TWinControl;
FComponentNotifier: TVANotificationEventComponent;
procedure ComponentNotifyEvent(AComponent: TComponent; Operation: TOperation);
procedure SetComponent(const Value: TWinControl);
function Labeler: TVA508ImageListLabeler;
protected
function GetDisplayName: string; override;
public
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
function ImageListTypes: TVA508ImageListTypes;
published
property Component: TWinControl read FComponent write SetComponent;
end;
TVA508ImageListComponents = class(TCollection)
private
FOwner: TVA508ImageListLabeler;
protected
function GetItem(Index: Integer): TVA508ImageListComponent;
procedure SetItem(Index: Integer; Value: TVA508ImageListComponent);
procedure Notify(Item: TCollectionItem; Action: TCollectionNotification); override;
public
constructor Create(Owner: TVA508ImageListLabeler);
destructor Destroy; override;
function GetOwner: TPersistent; override;
function Add: TVA508ImageListComponent;
property Items[Index: Integer]: TVA508ImageListComponent read GetItem write SetItem; default;
end;
TVA508ImageListLabeler = class(TComponent)
private
FStartup: boolean;
FOldComponentList: TList;
FImageListChanging: boolean;
FImageListChanged: boolean;
FItemChange: boolean;
FOnChange: TNotifyEvent;
FChangeLink: TChangeLink;
FImageList: TCustomImageList;
FComponents: TVA508ImageListComponents;
FItems: TVA508ImageListLabels;
FRemoteLabeler: TVA508ImageListLabeler;
procedure SetImageList(const Value: TCustomImageList);
procedure SetRemoteLabeler(const Value: TVA508ImageListLabeler);
protected
procedure ImageIndexQuery(Sender: TObject; ImageIndex: integer;
ImageType: TVA508ImageListType; var ImageText: string);
procedure Loaded; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure ImageListChange(Sender: TObject);
procedure ItemChanged;
procedure SaveChanges(Reregister: boolean);
property OnChange: TNotifyEvent read FOnChange write FOnChange;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ComponentImageListChanged;
published
property Components: TVA508ImageListComponents read FComponents write FComponents;
property ImageList: TCustomImageList read FImageList write SetImageList;
property Labels: TVA508ImageListLabels read FItems write FItems;
property RemoteLabeler: TVA508ImageListLabeler read FRemoteLabeler write SetRemoteLabeler;
end;
procedure Register;
implementation
uses VA508Classes, VA508AccessibilityRouter;
procedure Register;
begin
RegisterComponents('VA 508', [TVA508ImageListLabeler]);
end;
{ TVA508ImageListLabeler }
procedure TVA508ImageListLabeler.ComponentImageListChanged;
begin
SaveChanges(TRUE);
end;
constructor TVA508ImageListLabeler.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FStartup := TRUE;
FOldComponentList := TList.Create;
FItems := TVA508ImageListLabels.Create(Self);
FComponents := TVA508ImageListComponents.Create(Self);
FChangeLink := TChangeLink.Create;
FChangeLink.OnChange := ImageListChange;
VA508ComponentCreationCheck(Self, AOwner, TRUE, TRUE);
end;
destructor TVA508ImageListLabeler.Destroy;
begin
FItems.Clear;
FComponents.Clear;
SaveChanges(FALSE);
SetImageList(nil);
FreeAndNil(FItems);
FreeAndNil(FComponents);
FChangeLink.Free;
FreeAndNil(FOldComponentList);
inherited;
end;
procedure TVA508ImageListLabeler.ImageIndexQuery(Sender: TObject; ImageIndex: integer;
ImageType: TVA508ImageListType; var ImageText: string);
var
list: TStrings;
begin
if ImageIndex < 0 then exit;
if ImageType = iltOverlayImages then
begin
if assigned(RemoteLabeler) then
list := RemoteLabeler.FItems.GetOverlayData
else
list := FItems.GetOverlayData;
end
else
begin
if assigned(RemoteLabeler) then
list := RemoteLabeler.FItems.GetImageData
else
list := FItems.GetImageData;
end;
if ImageIndex < list.Count then
ImageText := list[ImageIndex]
else
ImageText := '';
end;
procedure TVA508ImageListLabeler.ImageListChange(Sender: TObject);
var
i: integer;
begin
if assigned(FOnChange) then
begin
FItemChange := FALSE;
FImageListChanged := TRUE;
try
for I := 0 to FItems.Count - 1 do
begin
FItems.Items[i].Refresh;
if FItemChange then
break;
end;
if FItemChange then
FOnChange(Self);
finally
FImageListChanged := FALSE;
end;
end;
end;
procedure TVA508ImageListLabeler.ItemChanged;
begin
if FImageListChanged then
FItemChange := TRUE
else if assigned(FOnChange) then
FOnChange(Self);
end;
procedure TVA508ImageListLabeler.Loaded;
begin
inherited;
FStartup := FALSE;
Application.ProcessMessages;
SaveChanges(FALSE);
end;
procedure TVA508ImageListLabeler.SaveChanges(Reregister: boolean);
var
i, idx: integer;
Item: TVA508ImageListComponent;
Comp: TWinControl;
NewList: TList;
reg: boolean;
begin
if FStartup or (csDesigning in ComponentState) or (not ScreenReaderSystemActive) then exit;
if (FComponents.Count = 0) and (FOldComponentList.Count = 0) then exit;
NewList := TList.Create;
try
for i := 0 to FComponents.Count - 1 do
begin
Item := FComponents.Items[i];
if assigned(Item.Component) then
begin
NewList.Add(Item.Component);
idx := FOldComponentList.IndexOf(Item.Component);
if idx < 0 then
reg := TRUE
else
begin
FOldComponentList.Delete(idx);
reg := Reregister;
end;
if reg then
RegisterComponentImageListQueryEvent(Item.Component, Item.ImageListTypes, ImageIndexQuery);
end;
end;
for i := 0 to FOldComponentList.Count-1 do
begin
Comp := TWinControl(FOldComponentList[i]);
UnregisterComponentImageListQueryEvent(Comp, ImageIndexQuery);
end;
finally
FOldComponentList.Free;
FOldComponentList := NewList;
end;
end;
procedure TVA508ImageListLabeler.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (AComponent = FImageList) and (Operation = opRemove) then
SetImageList(nil);
end;
procedure TVA508ImageListLabeler.SetImageList(const Value: TCustomImageList);
var
i,idx: integer;
list: string;
begin
if FImageListChanging then exit;
if assigned(FRemoteLabeler) then
begin
FImageList := nil;
exit;
end;
if FImageList <> Value then
begin
FImageListChanging := TRUE;
try
if assigned(FImageList) then
begin
FImageList.UnRegisterChanges(FChangeLink);
FImageList.RemoveFreeNotification(Self);
end;
FImageList := Value;
if assigned(FImageList) then
begin
FImageList.FreeNotification(Self);
FImageList.RegisterChanges(FChangeLink);
if FImageList.count > 0 then
begin
list := StringOfChar('x',FImageList.Count);
for i := 0 to FItems.Count - 1 do
begin
idx := FItems[i].ImageIndex + 1;
if idx > 0 then
list[idx] := ' ';
end;
for i := 0 to FImageList.Count - 1 do
begin
if list[i+1] = 'x' then
FItems.Add.ImageIndex := i;
end;
end;
end;
if assigned(FOnChange) then
FOnChange(Self);
finally
FImageListChanging := FALSE;
end;
end;
end;
procedure TVA508ImageListLabeler.SetRemoteLabeler(const Value: TVA508ImageListLabeler);
begin
if (FRemoteLabeler <> Value) then
begin
if assigned(Value) then
begin
FItems.Clear;
SetImageList(nil);
end;
FRemoteLabeler := Value;
end;
end;
{ TVA508ImageListItems }
function TVA508ImageListLabels.Add: TVA508ImageListLabel;
begin
Result := TVA508ImageListLabel(inherited Add);
end;
constructor TVA508ImageListLabels.Create(Owner: TVA508ImageListLabeler);
begin
inherited Create(TVA508ImageListLabel);
FImageData := TStringList.Create;
FOverlayData := TStringList.Create;
FOwner := Owner;
FColumns := TStringList.Create;
FColumns.Add('Image');
FColumns.Add('ImageIndex');
FColumns.Add('OverlayIndex');
FColumns.Add('Caption');
end;
destructor TVA508ImageListLabels.Destroy;
begin
Clear;
FreeAndNil(FColumns);
FreeAndNil(FImageData);
FreeAndNil(FOverlayData);
inherited;
end;
function TVA508ImageListLabels.GetAttr(Index: Integer): string;
begin
Result := FColumns[Index];
end;
function TVA508ImageListLabels.GetAttrCount: Integer;
begin
Result := FColumns.Count;
end;
function TVA508ImageListLabels.GetImageData: TStrings;
var
i: integer;
item: TVA508ImageListLabel;
begin
if (FImageData.Count = 0) and (Count > 0) then
begin
for i := 0 to Count-1 do
begin
item := Items[i];
while FImageData.Count <= item.ImageIndex do
FImageData.Add('');
FImageData[item.ImageIndex] := item.Caption;
end;
end;
Result := FImageData;
end;
function TVA508ImageListLabels.GetItem(Index: Integer): TVA508ImageListLabel;
begin
Result := TVA508ImageListLabel(inherited GetItem(Index));
end;
function TVA508ImageListLabels.GetItemAttr(Index, ItemIndex: Integer): string;
begin
case Index of
0: Result := ' '; // needs something on index 0 or it doesn't display anything on entire line
1: if GetItem(ItemIndex).ImageIndex < 0 then
Result := ' '
else
Result := IntToStr(GetItem(ItemIndex).ImageIndex);
2: begin
if (GetItem(ItemIndex).OverlayIndex < 0) then
Result := ' '
else
Result := IntToStr(GetItem(ItemIndex).OverlayIndex);
end;
3: Result := GetItem(ItemIndex).Caption;
else Result := '';
end;
end;
function TVA508ImageListLabels.GetOverlayData: TStrings;
var
i: integer;
item: TVA508ImageListLabel;
begin
if FBuildOverlayData then
begin
FBuildOverlayData := FALSE;
if (Count > 0) then
begin
for i := 0 to Count-1 do
begin
item := Items[i];
if item.OverlayIndex >= 0 then
begin
while FOverlayData.Count <= item.OverlayIndex do
FOverlayData.Add('');
FOverlayData[item.OverlayIndex] := item.Caption;
end;
end;
end;
end;
Result := FOverlayData;
end;
function TVA508ImageListLabels.GetOwner: TPersistent;
begin
Result := FOwner;
end;
procedure TVA508ImageListLabels.Notify(Item: TCollectionItem;
Action: TCollectionNotification);
begin
inherited;
ResetData;
end;
procedure TVA508ImageListLabels.ResetData;
begin
FImageData.Clear;
FOverlayData.Clear;
FBuildOverlayData := TRUE;
end;
procedure TVA508ImageListLabels.SetItem(Index: Integer; Value: TVA508ImageListLabel);
begin
inherited SetItem(Index, Value);
end;
procedure TVA508ImageListLabels.Update(Item: TCollectionItem);
begin
inherited;
ResetData;
end;
{ TVA508GraphicLabel }
procedure TVA508ImageListLabel.Assign(Source: TPersistent);
var
item: TVA508ImageListLabel;
begin
if Source is TVA508ImageListLabel then
begin
item := TVA508ImageListLabel(Source);
SetImageIndex(item.ImageIndex);
FCaption := item.Caption;
end
else
inherited Assign(Source);
end;
procedure TVA508ImageListLabel.Changed;
begin
labeler.ItemChanged;
end;
constructor TVA508ImageListLabel.Create(Collection: TCollection);
begin
inherited Create(Collection);
FImageIndex := -1;
FOverlayIndex := -1;
end;
destructor TVA508ImageListLabel.Destroy;
begin
inherited;
end;
function TVA508ImageListLabel.Labeler: TVA508ImageListLabeler;
begin
Result := TVA508ImageListLabeler(TVA508ImageListLabels(GetOwner).GetOwner);
end;
procedure TVA508ImageListLabel.Refresh;
begin
SetImageIndex(FImageIndex);
end;
procedure TVA508ImageListLabel.SetCaption(const Value: string);
begin
if (FCaption <> Value) then
begin
FCaption := Value;
TVA508ImageListLabels(GetOwner).Update(Self);
end;
end;
procedure TVA508ImageListLabel.SetImageIndex(const Value: integer);
var
before: integer;
begin
if csReading in labeler.ComponentState then
FImageIndex := Value
else
begin
before := FImageIndex;
if not assigned(labeler.ImageList) then
FImageIndex := -1
else
if (Value >= 0) and (Value < labeler.ImageList.Count) then
FImageIndex := Value
else
FImageIndex := -1;
if FImageIndex <> before then
begin
Changed;
TVA508ImageListLabels(GetOwner).Update(Self);
end;
end;
end;
procedure TVA508ImageListLabel.SetOverlayIndex(const Value: integer);
begin
if (FOverlayIndex <> Value) and (Value >= 0) and (Value < 16) then
begin
FOverlayIndex := Value;
end;
end;
{ TVA508ImageListComponents }
function TVA508ImageListComponents.Add: TVA508ImageListComponent;
begin
Result := TVA508ImageListComponent(inherited Add);
end;
constructor TVA508ImageListComponents.Create(Owner: TVA508ImageListLabeler);
begin
inherited Create(TVA508ImageListComponent);
FOwner := Owner;
end;
destructor TVA508ImageListComponents.Destroy;
begin
Clear;
inherited;
end;
function TVA508ImageListComponents.GetItem(
Index: Integer): TVA508ImageListComponent;
begin
Result := TVA508ImageListComponent(inherited GetItem(Index));
end;
function TVA508ImageListComponents.GetOwner: TPersistent;
begin
Result := FOwner;
end;
procedure TVA508ImageListComponents.Notify(Item: TCollectionItem;
Action: TCollectionNotification);
begin
inherited;
FOwner.SaveChanges(FALSE);
end;
procedure TVA508ImageListComponents.SetItem(Index: Integer;
Value: TVA508ImageListComponent);
begin
inherited SetItem(Index, Value);
end;
{ TVA508ImageListComponent }
procedure TVA508ImageListComponent.Assign(Source: TPersistent);
var
comp: TVA508ImageListComponent;
begin
if Source is TVA508ImageListComponent then
begin
comp := TVA508ImageListComponent(Source);
comp.Component := FComponent;
end
else
inherited Assign(Source);
end;
procedure TVA508ImageListComponent.ComponentNotifyEvent(AComponent: TComponent;
Operation: TOperation);
begin
if (Operation = opRemove) and assigned(AComponent) and (AComponent = FComponent) then
SetComponent(nil);
end;
destructor TVA508ImageListComponent.Destroy;
begin
SetComponent(nil);
if assigned(FComponentNotifier) then
FreeAndNil(FComponentNotifier);
inherited;
end;
function TVA508ImageListComponent.GetDisplayName: string;
begin
if assigned(FComponent) and (length(FComponent.Name) > 0) then
Result := FComponent.Name + ' (' + FComponent.ClassName + ')'
else
Result := inherited GetDisplayName;
end;
type
TExposedTreeView = class(TCustomTreeView);
TExposedListView = class(TCustomListView);
function TVA508ImageListComponent.ImageListTypes: TVA508ImageListTypes;
var
list: TCustomImageList;
begin
Result := [];
list := Labeler.ImageList;
if (not assigned(list)) and assigned(Labeler.FRemoteLabeler) then
list := Labeler.FRemoteLabeler.ImageList;
if (not assigned(list)) then exit;
if FComponent is TCustomTreeView then
begin
with TExposedTreeView(FComponent) do
begin
if list = Images then
Result := Result + [iltImages, iltOverlayImages];
if list = StateImages then
Include(Result, iltStateImages);
end;
end
else if FComponent is TCustomListView then
begin
with TExposedListView(FComponent) do
begin
if list = LargeImages then
Result := Result + [iltLargeImages, iltOverlayImages];
if list = SmallImages then
Result := Result + [iltSmallImages, iltOverlayImages];
if list = StateImages then
Include(Result, iltStateImages);
end;
end;
end;
function TVA508ImageListComponent.Labeler: TVA508ImageListLabeler;
begin
Result := TVA508ImageListLabeler(TVA508ImageListLabels(GetOwner).GetOwner);
end;
procedure TVA508ImageListComponent.SetComponent(const Value: TWinControl);
var
i: integer;
found: boolean;
begin
if FComponent <> Value then
begin
if assigned(Value) then
begin
Found := false;
for i := low(VA508ImageListLabelerClasses) to high(VA508ImageListLabelerClasses) do
begin
if Value is VA508ImageListLabelerClasses[i] then
begin
Found := true;
break;
end;
end;
if not found then
raise EVA508AccessibilityException.Create('Invalid component class used in ' + TVA508ImageListComponent.ClassName);
end;
if assigned(FComponentNotifier) and assigned(FComponent) then
FComponentNotifier.RemoveFreeNotification(FComponent);
if assigned(Value) then
begin
if not assigned(FComponentNotifier) then
FComponentNotifier := TVANotificationEventComponent.NotifyCreate(nil, ComponentNotifyEvent);
FComponentNotifier.FreeNotification(Value);
end;
FComponent := Value;
Labeler.SaveChanges(FALSE);
end;
end;
end.
|
{
*** Get MAC Adress ***
*** by Filip Skalka, fip@post.cz ***
*** September 2002 ***
}
unit MACAdress;
interface
uses classes;
function GetMACAdresses(const Adresses:TStringList;const MachineName:string=''):integer;
function GetMACAdress(const MachineName:string=''):string;
implementation
uses NB30,sysutils;
type
ENetBIOSError=class(Exception);
function NetBiosCheck(const b:char):char;
begin
if b<>chr(NRC_GOODRET) then raise ENetBIOSError.create('NetBios error'#13#10'Error code '+inttostr(ord(b)));
result:=b;
end;
function AdapterToString(const Adapter:PAdapterStatus):string;
begin
with Adapter^ do Result :=Format('%2.2x-%2.2x-%2.2x-%2.2x-%2.2x-%2.2x',[Integer(adapter_address[0]),Integer(adapter_address[1]),Integer(adapter_address[2]), Integer(adapter_address[3]),Integer(adapter_address[4]), Integer(adapter_address[5])]);
end;
procedure MachineNameToAdapter(Name:string;var AdapterName:array of char);
begin
if Name='' then Name:='*' else Name:=ansiuppercase(Name);
Name:=Name+StringOfChar(' ',length(AdapterName)-Length(Name));
move(Name[1],AdapterName[0],length(AdapterName));
end;
function GetMACAdresses(const Adresses:TStringList;const MachineName:string=''):integer;
var i:integer;
NCB: PNCB;
Adapter:PAdapterStatus;
Lenum:PLanaEnum;
RetCode:char;
begin
Adresses.clear;
New(NCB);
New(Adapter);
New(Lenum);
try
Fillchar(NCB^,SizeOf(TNCB),0);
fillchar(Lenum^,SizeOf(TLanaEnum),0);
NCB.ncb_command:=chr(NCBENUM);
NCB.ncb_buffer:=Pointer(Lenum);
NCB.ncb_length:=SizeOf(Lenum);
NetBiosCheck(Netbios(NCB));
result:=ord(Lenum.Length);
for i:=0 to result-1 do
begin
Fillchar(NCB^,SizeOf(TNCB),0);
Ncb.ncb_command:=chr(NCBRESET);
Ncb.ncb_lana_num:=lenum.lana[i];
NetBiosCheck(Netbios(Ncb));
FillChar(NCB^,SizeOf(TNCB),0);
FillChar(Adapter^,SizeOf(TAdapterStatus),0);
Ncb.ncb_command:=chr(NCBASTAT);
Ncb.ncb_lana_num:=lenum.lana[i];
MachineNameToAdapter(MachineName,Ncb.ncb_callname);
Ncb.ncb_buffer:=Pointer(Adapter);
Ncb.ncb_length:=SizeOf(TAdapterStatus);
RetCode:=Netbios(NCB);
if RetCode in [chr(NRC_GOODRET),chr(NRC_INCOMP)] then Adresses.add(AdapterToString(Adapter));
end;
finally
Dispose(NCB);
Dispose(Adapter);
Dispose(Lenum);
end;
end;
function GetMACAdress(const MachineName:string=''):string;
var stringlist:tstringlist;
begin
stringlist:=tstringlist.create;
try
if GetMACAdresses(stringlist,MachineName)=0 then result:='' else result:=stringlist[0];
finally
stringlist.destroy;
end;
end;
end.
|
unit WebSite;
interface
type
IWebSite = interface
['{D9458634-F21B-4CE2-BB4E-587E95CF4694}']
function GetContent(const Url: string): string;
end;
function BuildWebSiteWithCache: IWebSite;
implementation
uses
Code02.HttpGet,
HttpCache;
type
TWebSiteWithCache = class(TInterfacedObject, IWebSite)
private
class var Cache: THttpCache;
class constructor Create;
class destructor Destroy;
public
function GetContent(const Url: string): string;
end;
class constructor TWebSiteWithCache.Create;
begin
Cache := THttpCache.Create;
end;
class destructor TWebSiteWithCache.Destroy;
begin
Cache.Free;
end;
function TWebSiteWithCache.GetContent(const Url: string): string;
begin
if Cache.Contains(Url) then begin
Result := Cache.GetContent(Url)
end
else begin
Result := TMyHttpGet.GetWebsiteContent(Url);
Cache.SetContent(Url, Result);
end;
end;
function BuildWebSiteWithCache: IWebSite;
begin
Result := TWebSiteWithCache.Create;
end;
end.
|
{********************************************}
{ TeeChart Pro Charting Library }
{ Themes Editor Dialog }
{ Copyright (c) 2003-2004 by David Berneda }
{ All Rights Reserved }
{********************************************}
unit TeeThemeEditor;
{$I TeeDefs.inc}
interface
uses {$IFNDEF LINUX}
Windows, Messages, SysUtils,
{$ENDIF}
Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QComCtrls, QExtCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls,
{$ENDIF}
TeeProcs, TeEngine, Chart, TeeThemes, TeeTools, TeCanvas, TeeDraw3D;
type
TChartThemeSelector = class(TForm)
Panel1: TPanel;
Splitter1: TSplitter;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
PreviewChart: TChart;
PageControl2: TPageControl;
TabSheet2: TTabSheet;
LBThemes: TListBox;
Panel2: TPanel;
Panel3: TPanel;
BOK: TButton;
Button2: TButton;
CheckBox1: TCheckBox;
ChartTool1: TRotateTool;
Panel4: TPanel;
Label1: TLabel;
CBPalette: TComboFlat;
CBScale: TCheckBox;
ScaledChart: TDraw3D;
procedure LBThemesClick(Sender: TObject);
procedure BOKClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure CheckBox1Click(Sender: TObject);
procedure Panel4Resize(Sender: TObject);
procedure CBPaletteChange(Sender: TObject);
procedure CBScaleClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure ScaledChartAfterDraw(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
{ Private declarations }
procedure CheckScale;
procedure InitPreviewChart;
{$IFNDEF CLX}
procedure CMShowingChanged(var Message: TMessage); message CM_SHOWINGCHANGED;
{$ENDIF}
public
{ Public declarations }
Chart : TCustomChart;
Function SelectedTheme:TChartThemeClass;
end;
// Shows the Chart Theme editor. Returns the selected Theme class or nil.
Function ChartThemeSelector(AChart:TCustomChart):TChartThemeClass;
// Adds all available registered Chart Themes to "Items"
Procedure AddChartThemes(Items:TStrings);
implementation
{$R *.dfm}
uses {$IFNDEF CLR}
Math,
{$ENDIF}
TeePenDlg, TeeEditCha, TeeConst, TeeProCo;
Procedure AddChartThemes(Items:TStrings);
var t : Integer;
tmp : TChartTheme;
begin
for t:=0 to ChartThemes.Count-1 do
begin
tmp:=ChartThemes[t].Create(nil);
try
Items.AddObject(tmp.Description,TObject(ChartThemes[t]));
finally
tmp.Free;
end;
end;
end;
Function ChartThemeSelector(AChart:TCustomChart):TChartThemeClass;
begin
with TChartThemeSelector.Create(nil) do
try
Chart:=AChart;
if ShowModal=mrOk then
result:=SelectedTheme
else
result:=nil;
finally
Free;
end;
end;
procedure TChartThemeSelector.LBThemesClick(Sender: TObject);
begin
if LBThemes.ItemIndex>0 then
begin
ApplyChartTheme(SelectedTheme,PreviewChart,CBPalette.ItemIndex-1);
BOK.Enabled:=True;
end
else
begin
InitPreviewChart;
BOK.Enabled:=False;
end;
if CBScale.Checked then ScaledChart.Invalidate;
end;
Function TChartThemeSelector.SelectedTheme:TChartThemeClass;
begin
if LBThemes.ItemIndex<=0 then
result:=nil
else
result:=TChartThemeClass(LBThemes.Items.Objects[LBThemes.ItemIndex]);
end;
type
TSeriesAccess=class(TChartSeries);
procedure TChartThemeSelector.InitPreviewChart;
var t : Integer;
Old : Boolean;
begin
PreviewChart.FreeAllSeries;
if Assigned(Chart) then
begin
PreviewChart.Assign(Chart);
for t:=0 to Chart.SeriesCount-1 do
begin
Old:=TSeriesAccess(Chart[t]).ManualData;
TSeriesAccess(Chart[t]).ManualData:=True;
try
CloneChartSeries(Chart[t],PreviewChart,PreviewChart);
finally
TSeriesAccess(Chart[t]).ManualData:=Old;
end;
end;
CheckScale;
CheckBox1.Checked:=Chart.View3D;
end;
end;
procedure TChartThemeSelector.BOKClick(Sender: TObject);
begin
Chart.View3D:=CheckBox1.Checked;
if SelectedTheme<>nil then
ApplyChartTheme(SelectedTheme,Chart,CBPalette.ItemIndex-1)
else
ColorPalettes.ApplyPalette(Chart,CBPalette.ItemIndex-1);
BOK.Enabled:=False;
end;
procedure TChartThemeSelector.FormShow(Sender: TObject);
var t : Integer;
begin
// Fill listbox with registered Themes...
LBThemes.Clear;
LBThemes.Items.Add(TeeMsg_Current);
AddChartThemes(LBThemes.Items);
LBThemes.ItemIndex:=0;
// Fill Color Palette combo...
CBPalette.Clear;
CBPalette.Items.Add(TeeMsg_Default);
for t:=0 to ColorPalettes.Count-1 do
CBPalette.Items.Add(ColorPalettes[t]);
CBPalette.ItemIndex:=0; // select always the "default" palette.
InitPreviewChart;
BOk.Enabled:=False;
TeeTranslateControl(Self);
end;
procedure TChartThemeSelector.CheckBox1Click(Sender: TObject);
begin
PreviewChart.View3D:=CheckBox1.Checked;
if CBScale.Checked then ScaledChart.Invalidate;
BOk.Enabled:=True;
end;
Procedure TeeThemeShowEditor(Editor:TChartEditForm; Tab:TTabSheet);
var tmpForm : TChartThemeSelector;
tmpActive : TTabSheet;
begin
tmpActive:=Editor.MainPage.ActivePage;
if not Assigned(Tab) then
begin
Tab:=TTabSheet.Create(Editor);
Tab.Caption:=TeeMsg_Themes;
Tab.PageControl:=Editor.MainPage;
end
else
if (Tab.ControlCount=0) and (Tab.Caption=TeeMsg_Themes) then
begin
tmpForm:=TChartThemeSelector.Create(Editor);
with tmpForm do
begin
Chart:=Editor.Chart;
Button2.Visible:=False;
BOK.Left:=Button2.Left;
BOK.ModalResult:=mrNone;
BOK.Caption:=TeeMsg_Apply;
Align:=alClient;
PageControl2.Width:=100;
end;
AddFormTo(tmpForm,Tab);
{$IFNDEF CLR}
tmpForm.RequestAlign;
{$ENDIF}
end;
Editor.MainPage.ActivePage:=tmpActive;
end;
procedure TChartThemeSelector.Panel4Resize(Sender: TObject);
begin
CBPalette.Width:=Panel4.Width-12;
end;
procedure TChartThemeSelector.CBPaletteChange(Sender: TObject);
begin
if CBPalette.ItemIndex=0 then
LBThemesClick(Self)
else
ColorPalettes.ApplyPalette(PreviewChart,CBPalette.ItemIndex-1);
if CBScale.Checked then ScaledChart.Invalidate;
BOK.Enabled:=True;
end;
procedure TChartThemeSelector.CBScaleClick(Sender: TObject);
begin
CheckScale;
end;
procedure TChartThemeSelector.CheckScale;
begin
if CBScale.Checked then
begin
PreviewChart.Align:=alNone;
PreviewChart.Width:=Chart.Width;
PreviewChart.Height:=Chart.Height;
PreviewChart.Hide;
ScaledChart.Show;
end
else
begin
PreviewChart.Align:=alClient;
PreviewChart.Show;
ScaledChart.Hide;
end;
end;
procedure TChartThemeSelector.FormActivate(Sender: TObject);
begin
// InitPreviewChart;
end;
procedure TChartThemeSelector.ScaledChartAfterDraw(Sender: TObject);
var tmp : TBitmap;
begin
if CBScale.Checked then
begin
if not PreviewChart.Canvas.ReDrawBitmap then PreviewChart.Draw;
tmp:=TTeeCanvas3D(PreviewChart.Canvas).Bitmap;
if Assigned(tmp) then
SmoothStretch(tmp,TTeeCanvas3D(ScaledChart.Canvas).Bitmap);
end;
end;
type
TButtonAccess=class(TButton);
procedure TChartThemeSelector.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
if BOk.Enabled then
Case MessageDlg(TeeMsg_SureToApply,mtConfirmation,[mbYes,mbNo,mbCancel],0) of
mrYes: begin
TButtonAccess(BOk).Click;
CanClose:=not BOk.Enabled;
end;
mrNo: begin
BOk.Enabled:=False;
CanClose:=True;
end;
mrCancel: CanClose:=False;
end;
end;
{$IFNDEF CLX}
procedure TChartThemeSelector.CMShowingChanged(var Message: TMessage);
begin
inherited;
if Assigned(Parent) then Parent.UpdateControlState;
end;
{$ENDIF}
procedure InstallHook;
{$IFDEF CLR}
var p: TTeeOnCreateEditor;
{$ENDIF}
begin
{$IFDEF CLR}
p:=TeeThemeShowEditor;
TeeOnShowEditor.Add(@p);
{$ELSE}
TeeOnShowEditor.Add(@TeeThemeShowEditor);
{$ENDIF}
end;
procedure RemoveHook;
{$IFDEF CLR}
var p: TTeeOnCreateEditor;
{$ENDIF}
begin
{$IFDEF CLR}
p:=TeeThemeShowEditor;
TeeOnShowEditor.Remove(@p);
{$ELSE}
TeeOnShowEditor.Remove(@TeeThemeShowEditor);
{$ENDIF}
end;
initialization
InstallHook;
TeeThemeSelectorHook:=ChartThemeSelector;
finalization
TeeThemeSelectorHook:=nil;
RemoveHook;
end.
|
{
Copyright (c) 2010, Loginov Dmitry Sergeevich
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
}
unit TableUnit;
interface
uses
Windows, Messages, Classes, SysUtils, HTMLGlobal, SHDocVw, MSHTML, Math;
type
TTableMask = record
Num: Integer;
Cell: IHTMLTableCell;
IsCellStart: Boolean;
end;
TTableMaskArray = array of array of TTableMask;
TTableClass = class
HTMLInfo: THTMLEditorInfo;
// Отыскивает таблицу. В качестве Index передается ячейка / строка / таблица
function GetCurrentTable(var Index: Integer): IHTMLTable;
// Отыскивает строку. В качестве Index передается таблица / строка
function GetCurrentTableRow(var Index: Integer): IHTMLTableRow;
// Отыскивает ячейку. В качестве Index передается таблица / строка / ячейка
function GetCurrentTableCell(var Index: Integer): IHTMLTableCell;
procedure CopyCellProp(ACell, NewCell: IHTMLTableCell);
// Осуществляет разбиение указанной ячейки
procedure DoCellDeSpan(Tab: IHTMLTable; ARow: IHTMLTableRow; ACell: IHTMLTableCell);
// Возвращает структуру таблицы в массиве TTableMaskArray
function GetTableMask(Tab: IHTMLTable; RowCount, AllColCount: Integer): TTableMaskArray;
// Возвращает настоящее кол-во столбцов в таблице
function GetTableRealColCount(Tab: IHTMLTable): Integer;
// Добавляем строку в таблицу
procedure DoTableAddRow(ToBottom: Boolean);
procedure DoTableAddCol(ToLeft: Boolean);
procedure DoTableMergeCell(ToRight: Boolean);
procedure DoDelAttribSize(Width: Boolean);
procedure DoTabDelColumn();
procedure DoTabDelRow();
procedure AddNewTable();
// T - Все явно включены; F - Все явно выключены; D - стиль сброшен
procedure ResetAllCellBorders(Value: Char);
procedure ResetOneCellBorder(Side: Char; Value: Char);
private
function DocRange: IHTMLTxtRange;
end;
implementation
uses PropertyFrm;
{ TTableClass }
procedure TTableClass.AddNewTable;
var
TextRange: IHTMLTxtRange;
AList, TableList: TStringList;
AttrIdx, I, J, Cnt: Integer;
attr: THTMLTagAttribs;
S, S1, CellSpString, CellPadString, SCollapse, STabStyle, SCaption: string;
SWidth, SHeight, SAlign, SBGColor, SBorderColor, SBorder: string;
SBackGround, Stdwidth, Stdheight, Stdalign, Stdvalign, Stdbackground: string;
Stdbgcolor, Stdbordercolor, Snowrap: string;
Rows, Cols, Border: Integer;
WidthRowNum: Integer;
atrValue: THTMLAttribType;
begin
TextRange := DocRange;
if Assigned(TextRange) then
begin
AList := TStringList.Create;
TableList := TStringList.Create;
try
AttrIdx := TagTranslatesList.IndexOfName('ADDNEWTABLE');
attr := THTMLTagAttribs(TagTranslatesList.Objects[AttrIdx]);
// Заполняем список
for I := 0 to attr.AttrList.Count - 1 do
begin
S := attr.AttrList.Names[I];
atrValue := THTMLAttribType(StrToInt(attr.AttrList.ValueFromIndex[I]));
S1 := '';
if S = 'TABROWS' then
S1 := '3'
else if S = 'TABCOLS' then
S1 := '3'
else if S = 'BORDER' then
S1 := '1'
else if S = 'WIDTH' then
S1 := '70%'
else if S = 'CELLSPACING' then
S1 := '0';
AList.AddObject(S + '=' + S1, TObject(atrValue));
end;
if ShowPropertyForm(AList, nil, 'Новая таблица') then
begin
Rows := StrToIntDef(AList.Values['TABROWS'], 1);
Cols := StrToIntDef(AList.Values['TABCOLS'], 1);
Border := StrToIntDef(AList.Values['BORDER'], 1);
if Border > 0 then
SBorder := ' BORDER=' + IntToStr(Border);
S := AList.Values['CELLSPACING'];
if StrToIntDef(S, -1) >= 0 then
CellSpString := ' CELLSPACING=' + S;
S := AList.Values['CELLPADDING'];
if StrToIntDef(S, -1) >= 0 then
CellPadString := ' CELLPADDING=' + S;
if AList.Values['BORDERCOLLAPSE'] = '1' then
SCollapse := 'border-collapse: collapse;';
if SCollapse <> '' then
STabStyle := ' style="' + SCollapse + '"';
SCaption := AList.Values['TABLECAPTION'];
if SCaption <> '' then
SCaption := '<CAPTION>' + SCaption + '</CAPTION>';
SWidth := AList.Values['WIDTH'];
if SWidth <> '' then
SWidth := ' WIDTH="' + SWidth + '"';
SHeight := AList.Values['HEIGHT'];
if SHeight <> '' then
SHeight := ' HEIGHT="' + SHeight + '"';
SAlign := AList.Values['ALIGN'];
if SAlign <> '' then
SAlign := ' ALIGN=' + SAlign;
SBGColor := AList.Values['BGCOLOR'];
if SBGColor <> '' then
SBGColor := ' BGCOLOR=' + SBGColor;
SBorderColor := AList.Values['BORDERCOLOR'];
if SBorderColor <> '' then
SBorderColor := ' BORDERCOLOR=' + SBorderColor;
SBackGround := AList.Values['BACKGROUND'];
if SBackGround <> '' then
SBackGround := ' BACKGROUND="' + SBackGround + '"';
// Свойства ячейки
Stdwidth := AList.Values['TDWIDTH'];
if Stdwidth <> '' then
Stdwidth := ' WIDTH="' + Stdwidth + '"';
Stdheight := AList.Values['TDHEIGHT'];
if Stdheight <> '' then
Stdheight := ' HEIGHT="' + Stdheight + '"';
Stdalign := AList.Values['TDALIGN'];
if Stdalign <> '' then
Stdalign := ' ALIGN=' + Stdalign;
Stdvalign := AList.Values['TDVALIGN'];
if Stdvalign <> '' then
Stdvalign := ' VALIGN=' + Stdvalign;
Stdbackground := AList.Values['TDBACKGROUND'];
if Stdbackground <> '' then
Stdbackground := ' BACKGROUND="' + Stdbackground + '"';
Stdbgcolor := AList.Values['TDBGCOLOR'];
if Stdbgcolor <> '' then
Stdbgcolor := ' BGCOLOR=' + Stdbgcolor;
Stdbordercolor := AList.Values['TDBORDERCOLOR'];
if Stdbordercolor <> '' then
Stdbordercolor := ' BORDERCOLOR=' + Stdbordercolor;
if AList.Values['NOWRAP'] = '1' then
Snowrap := ' nowrap';
WidthRowNum := StrToIntDef(AList.Values['TDWIDTHROWNUM'], 0);
Cnt := 0;
S := Format('<TABLE%s%s%s%s%s%s%s%s%s%s>',
[SWidth, SHeight, SBorder, CellSpString, CellPadString, STabStyle,
SAlign, SBGColor, SBorderColor, SBackGround]);
TableList.Add(S);
if SCaption <> '' then
TableList.Add(SCaption);
for I := 1 to Rows do
begin
TableList.Add('<TR>');
for J := 1 to Cols do
begin
Inc(Cnt);
S1 := Stdwidth;
if (WidthRowNum > 0) and (WidthRowNum <> I) then S1 := '';
S := Format('%s%s%s%s%s%s%s%s', [S1, Stdheight, Stdalign, Stdvalign,
Stdbackground, Stdbgcolor, Stdbordercolor, Snowrap]);
S := Format('<TD%s>%d</TD>', [S, Cnt]);
TableList.Add(S);
end;
TableList.Add('</TR>');
end;
TableList.Add('</TABLE>');
TextRange.pasteHTML(TableList.Text);
end;
finally
AList.Free;
TableList.Free;
end;
end;
end;
procedure TTableClass.CopyCellProp(ACell, NewCell: IHTMLTableCell);
begin
NewCell.rowSpan := ACell.rowSpan;
NewCell.align := ACell.align;
NewCell.vAlign := ACell.vAlign;
NewCell.bgColor := ACell.bgColor;
NewCell.noWrap := ACell.noWrap;
if ACell.background <> '' then
NewCell.background := ACell.background;
NewCell.borderColor := ACell.borderColor;
//NewCell.height := ACell.height;
(NewCell as IHTMLElement).style.cssText := (ACell as IHTMLElement).style.cssText
end;
procedure TTableClass.DoCellDeSpan(Tab: IHTMLTable; ARow: IHTMLTableRow;
ACell: IHTMLTableCell);
var
HSpanCnt, VSpanCnt, I, J, ACellIndex, RowSpanCellIndex, RowIndex, CellNumber: Integer;
TmpCounter: Integer;
NewCell, TmpCell: IHTMLTableCell;
TmpRow: IHTMLTableRow;
begin
if Assigned(ACell) then
begin
HSpanCnt := ACell.colSpan;
VSpanCnt := ACell.rowSpan;
ACellIndex := ACell.cellIndex;
RowIndex := ARow.rowIndex;
CellNumber := 0;
// Определяем порядковый номер ячейки
for I := 0 to ACellIndex - 1 do
begin
TmpCell := ARow.cells.item(I, 0) as IHTMLTableCell;
if TmpCell.rowSpan = 1 then
CellNumber := CellNumber + TmpCell.colSpan;
end;
// Именно ячейка с №CellNumber будет первой из разъединенных
// Сначало разбиваем ячейки по горизонтали
if HSpanCnt > 1 then
begin
ACell.colSpan := 1;
// Добавляем необходимое кол-во новых ячеек
for I := 2 to HSpanCnt do
begin
NewCell := ARow.insertCell(ACellIndex + 1) as IHTMLTableCell;
CopyCellProp(ACell, NewCell);
end;
end;
// Разбиваем ячейки по вертикали
if VSpanCnt > 1 then
begin
for J := RowIndex + 1 to (RowIndex + VSpanCnt - 1) do
begin
TmpRow := (Tab.rows.item(J, 0) as IHTMLTableRow);
TmpCounter := 0;
RowSpanCellIndex := 0;
// Определяем, какая ячейка в TmpRow соответствует CellNumber
if CellNumber = 0 then
RowSpanCellIndex := -1
else
for I := 0 to TmpRow.cells.length - 1 do
begin
TmpCell := TmpRow.cells.item(I, 0) as IHTMLTableCell;
TmpCounter := TmpCounter + TmpCell.colSpan;
if TmpCounter >= CellNumber then
begin
RowSpanCellIndex := I; // Запоминаем номер ячейки для копирования
Break;
end;
end;
// Вставляем оставшиеся ячейки
for I := 1 to HSpanCnt do
begin
TmpCell := ARow.cells.item(ACellIndex + I - 1, 0) as IHTMLTableCell;
TmpCell.rowSpan := 1;
// Вставляем начальную ячейку
NewCell := TmpRow.insertCell(RowSpanCellIndex + 1) as IHTMLTableCell;
CopyCellProp(ACell, NewCell);
end;
end;
end;
end;
end;
procedure TTableClass.DoDelAttribSize(Width: Boolean);
var
Index: Integer;
Tab: IHTMLTable;
ARow: IHTMLTableRow;
ACell: IHTMLTableCell;
ATagName: string;
procedure DelCellAttrib(ACell: IHTMLTableCell);
begin
if Width then
begin
ACell.width := '';
(ACell as IHTMLElement).style.width := '';
end else
begin
ACell.height := '';
(ACell as IHTMLElement).style.height := '';
end
end;
procedure DelRowAttrib(ARow: IHTMLTableRow);
var
I: Integer;
begin
if Width then
(ARow as IHTMLElement).style.width := ''
else
(ARow as IHTMLElement).style.height := '';
for I := 0 to ARow.cells.length - 1 do
DelCellAttrib(ARow.cells.item(I, 0) as IHTMLTableCell);
end;
procedure DelTableAttrib(Tab: IHTMLTable);
var
I: Integer;
begin
if Width then
Tab.width := ''
else
Tab.height := '';
(Tab as IHTMLElement).style.width := '';
for I := 0 to Tab.rows.length - 1 do
DelRowAttrib(Tab.rows.item(I, 0) as IHTMLTableRow);
end;
begin
Index := HTMLInfo.CurrentIndex;
Tab := GetCurrentTable(Index);
ARow := GetCurrentTableRow(Index);
ACell := GetCurrentTableCell(Index);
ATagName := HTMLInfo.ElemDescArray[HTMLInfo.CurrentIndex].edTagName;
if (ATagName = 'TD') or (ATagName = 'TH') then
DelCellAttrib(ACell)
else if ATagName = 'TR' then
DelRowAttrib(ARow)
else if ATagName = 'TABLE' then
DelTableAttrib(Tab);
end;
procedure TTableClass.DoTabDelColumn;
var
Index, I, J, ARowIndex, ACellIndex, DelMaskCol, DelCellCount: Integer;
Tab: IHTMLTable;
ARow, TmpRow: IHTMLTableRow;
ACell, TmpCell: IHTMLTableCell;
AllColCount, RowCount, TmpInt: Integer;
TableMask: TTableMaskArray;
begin
Index := HTMLInfo.CurrentIndex;
Tab := GetCurrentTable(Index);
ARow := GetCurrentTableRow(Index);
ACell := GetCurrentTableCell(Index);
if ACell = nil then
raise Exception.Create('Столбец таблицы не выбран!');
RowCount := Tab.rows.length;
AllColCount := GetTableRealColCount(Tab);
ARowIndex := ARow.rowIndex;
ACellIndex := ACell.cellIndex;
TableMask := GetTableMask(Tab, RowCount, AllColCount);
DelCellCount := ACell.colSpan;
// Определяем номер столбца в TableMask, который должен быть удален
DelMaskCol := -1;
TmpInt := -1;
for I := 0 to AllColCount - 1 do
begin
if (TableMask[ARowIndex, I].Num = -1) and (TableMask[ARowIndex, I].IsCellStart) then
Inc(TmpInt);
if TmpInt = ACellIndex then
begin
DelMaskCol := I;
Break;
end;
end;
// Удаляем столбцы снизу вверх, т.к. при таком подходе мы имеем информацию
// по верхним ячейкам, от которых распространяется span
for I := RowCount - 1 downto 0 do
begin
TmpRow := tab.rows.item(I, 0) as IHTMLTableRow;
for J := DelMaskCol + DelCellCount - 1 downto DelMaskCol do
begin
if TableMask[I, J].Num = -1 then
begin
TmpCell := TableMask[I, J].Cell;
if Assigned(TmpCell) then
begin
if TmpCell.colSpan > 1 then
TmpCell.colSpan := TmpCell.colSpan - 1
else
begin
TmpRow.deleteCell(TmpCell.cellIndex);
end;
end;
end;
end;
end;
end;
procedure TTableClass.DoTabDelRow;
var
Index, I, J: Integer;
Tab: IHTMLTable;
ARow, TmpRow: IHTMLTableRow;
CurRowIndex: Integer;
ACell, TmpCell: IHTMLTableCell;
function GetRowSpacedCell: IHTMLTableCell;
var
I: Integer;
begin
for I := 0 to ARow.cells.length - 1 do
begin
Result := ARow.cells.item(I, 0) as IHTMLTableCell;
if Result.rowSpan > 1 then Exit;
end;
Result := nil;
end;
begin
Index := HTMLInfo.CurrentIndex;
Tab := GetCurrentTable(Index);
if Tab = nil then
raise Exception.Create('Тэг TABLE не найден!');
if Tab.rows.length = 1 then
begin
(Tab as IHTMLElement).outerHTML := '';
Exit;
end;
ARow := GetCurrentTableRow(Index);
if ARow = nil then
ARow := Tab.rows.item(Tab.rows.length - 1, 0) as IHTMLTableRow;
// Сперва выполняем разбиение ячеек В ДАННОЙ СТРОКЕ, у которых выставлено rowSpace
ACell := GetRowSpacedCell;
while Assigned(ACell) do
begin
DoCellDeSpan(Tab, ARow, ACell);
ACell := GetRowSpacedCell;
end;
CurRowIndex := ARow.rowIndex;
// Ищем во всех верхних строках ячейки, которые могут распространяться на эту
// строку. Уменьшаем во всех найденных ячейках св-во rowSpan
for I := 0 to CurRowIndex - 1 do
begin
TmpRow := Tab.rows.item(I, 0) as IHTMLTableRow;
for J := 0 to TmpRow.cells.length - 1 do
begin
TmpCell := TmpRow.cells.item(J, 0) as IHTMLTableCell;
if TmpCell.rowSpan > (CurRowIndex - TmpRow.rowIndex) then
TmpCell.rowSpan := TmpCell.rowSpan - 1;
end;
end;
Tab.deleteRow(CurRowIndex);
end;
procedure TTableClass.DoTableAddCol(ToLeft: Boolean);
var
Index, I, J, ARowIndex, ACellIndex, AddMaskCol, AddCellCount: Integer;
Tab: IHTMLTable;
ARow, TmpRow: IHTMLTableRow;
ACell, TmpCell, OldCell: IHTMLTableCell;
AllColCount, RowCount, TmpInt, VisCells: Integer;
TableMask: TTableMaskArray;
function IsClearRow(ARowIndex: Integer): Boolean;
var
I: Integer;
ACell: IHTMLTableCell;
begin
Result := False;
ACell := TableMask[ARowIndex, 0].Cell;
if ACell.colSpan < 5 then Exit;
for I := 1 to AllColCount - 1 do
if Pointer(TableMask[ARowIndex, I].Cell) <> Pointer(ACell) then Exit;
Result := True;
end;
begin
Index := HTMLInfo.CurrentIndex;
Tab := GetCurrentTable(Index);
ARow := GetCurrentTableRow(Index);
ACell := GetCurrentTableCell(Index);
if ACell = nil then
raise Exception.Create('Столбец таблицы не выбран!');
RowCount := Tab.rows.length;
AllColCount := GetTableRealColCount(Tab);
ARowIndex := ARow.rowIndex;
ACellIndex := ACell.cellIndex;
TableMask := GetTableMask(Tab, RowCount, AllColCount);
if Assigned(HTMLInfo.ActiveElement) then
HTMLInfo.ActiveElement.style.backgroundColor := HTMLInfo.ActiveElementColor;
AddCellCount := ACell.colSpan;
// Определяем номер столбца в TableMask, с которое следует начать добавление
AddMaskCol := -1;
TmpInt := -1;
for I := 0 to AllColCount - 1 do
begin
if (TableMask[ARowIndex, I].Num = -1) and (TableMask[ARowIndex, I].IsCellStart) then
Inc(TmpInt);
if TmpInt = ACellIndex then
begin
AddMaskCol := I;
Break;
end;
end;
for I := RowCount - 1 downto 0 do
begin
TmpRow := tab.rows.item(I, 0) as IHTMLTableRow;
if IsClearRow(I) then // Если это одна пустая строка...
begin
TableMask[I, 0].Cell.colSpan := TableMask[I, 0].Cell.colSpan + AddCellCount
end else
begin
//AddCounter := AddCellCount;
// Определяем количество видимых ячеек для требуемого диапазона
TmpCell := nil;
VisCells := 0;
for J := AddMaskCol to AddMaskCol + AddCellCount - 1 do
begin
if TableMask[I, J].Num = -1 then
begin
if Pointer(TableMask[I, J].Cell) <> Pointer(TmpCell) then
begin
Inc(VisCells);
TmpCell := TableMask[I, J].Cell;
end;
end;
end;
OldCell := nil;
TmpCell := nil;
if ToLeft then
begin
for J := AddMaskCol + AddCellCount - 1 downto AddMaskCol do
begin
if TableMask[I, J].Num = -1 then
begin
if Pointer(TableMask[I, J].Cell) = Pointer(OldCell) then
TmpCell.colSpan := TmpCell.colSpan + 1
else
begin
TmpCell := TmpRow.insertCell(TableMask[I, J].Cell.cellIndex - VisCells + 1) as IHTMLTableCell;
CopyCellProp(TableMask[I, J].Cell, TmpCell);
(TmpCell as IHTMLElement).innerText := '???';
end;
OldCell := TableMask[I, J].Cell;
end;
end;
end else
begin
for J := AddMaskCol to AddMaskCol + AddCellCount - 1 do
begin
if TableMask[I, J].Num = -1 then
begin
if Pointer(TableMask[I, J].Cell) = Pointer(OldCell) then
TmpCell.colSpan := TmpCell.colSpan + 1
else
begin
TmpCell := TmpRow.insertCell(TableMask[I, J].Cell.cellIndex + VisCells) as IHTMLTableCell;
CopyCellProp(TableMask[I, J].Cell, TmpCell);
(TmpCell as IHTMLElement).innerText := '???';
end;
OldCell := TableMask[I, J].Cell;
end;
end;
end;
end;
end;
end;
procedure TTableClass.DoTableAddRow(ToBottom: Boolean);
var
Index, I, J, ARowIndex: Integer;
Tab: IHTMLTable;
ARow, NewRow: IHTMLTableRow;
NewCell, TmpCell: IHTMLTableCell;
AllColCount, RowCount, CellCounter: Integer;
TableMask: TTableMaskArray;
function CanReplaceSpan(ARowIndex: Integer; MaskValue: TTableMask): Boolean;
begin
Result := False;
if (MaskValue.Num >= 0) and Assigned(MaskValue.Cell) then
begin
Result := (ARowIndex + 1) >= (MaskValue.Num + MaskValue.Cell.rowSpan);
end;
end;
begin
if Assigned(HTMLInfo.ActiveElement) then
HTMLInfo.ActiveElement.style.backgroundColor := HTMLInfo.ActiveElementColor;
Index := HTMLInfo.CurrentIndex;
Tab := GetCurrentTable(Index);
ARow := GetCurrentTableRow(Index);
if ARow = nil then // Берем последнюю строку
ARow := Tab.rows.item(Tab.rows.length - 1, 0) as IHTMLTableRow;
RowCount := Tab.rows.length;
AllColCount := GetTableRealColCount(Tab);
ARowIndex := ARow.rowIndex;
TableMask := GetTableMask(Tab, RowCount, AllColCount);
if ToBottom then // Вставить вниз
NewRow := Tab.insertRow(ARowIndex + 1) as IHTMLTableRow
else // Вставить вверх
NewRow := Tab.insertRow(ARowIndex) as IHTMLTableRow;
CellCounter := 0;
for I := 0 to AllColCount - 1 do
begin
TmpCell := TableMask[ARowIndex, I].Cell;
if Assigned(TmpCell) then
begin
if (TableMask[ARowIndex, I].Num = -1) then // Если собственная ячейка
begin
if TableMask[ARowIndex, I].IsCellStart then // Если это-начало ячейки
begin
if (TmpCell.rowSpan = 1) or (not ToBottom) then // Если не распространяется вниз
begin
NewCell := NewRow.insertCell(CellCounter) as IHTMLTableCell;
Inc(CellCounter);
CopyCellProp(TmpCell, NewCell);
NewCell.rowSpan := 1;
NewCell.colSpan := TmpCell.colSpan;
end else
begin
// Иначе просто увеличиваем rowSpan для предыдущего ряда
TmpCell.rowSpan := TmpCell.rowSpan + 1;
end;
end;
end
else if TableMask[ARowIndex, I].Num >= 0 then
begin // Если ячейка распространена сверху, но достигла предела..
if ToBottom and CanReplaceSpan(ARowIndex, TableMask[ARowIndex, I]) then
begin
NewCell := NewRow.insertCell(CellCounter) as IHTMLTableCell;
Inc(CellCounter);
CopyCellProp(TmpCell, NewCell);
NewCell.rowSpan := 1;
NewCell.colSpan := TmpCell.colSpan;
end else
TmpCell.rowSpan := TmpCell.rowSpan + 1;
// Обнуляем ссылки на такие же ячейки
for J := 0 to AllColCount - 1 do
if Pointer(TableMask[ARowIndex, J].Cell) = Pointer(TmpCell) then
TableMask[ARowIndex, J].Cell := nil;
end;
end;
end;
end;
procedure TTableClass.DoTableMergeCell(ToRight: Boolean);
var
Index, I, J, ARowIndex, ACellIndex, MergeMaskCol, MergeCellCount, MergeRowCount: Integer;
Tab: IHTMLTable;
ARow: IHTMLTableRow;
ACell, TmpCell, OldCell: IHTMLTableCell;
AllColCount, RowCount, TmpInt, ACounter: Integer;
TableMask: TTableMaskArray;
CanDelRow: Boolean;
begin
Index := HTMLInfo.CurrentIndex;
Tab := GetCurrentTable(Index);
if Tab = nil then
raise Exception.Create('Таблица не выбрана!');
ARow := GetCurrentTableRow(Index);
ACell := GetCurrentTableCell(Index);
if ACell = nil then
raise Exception.Create('Столбец таблицы не выбран!');
RowCount := Tab.rows.length;
AllColCount := GetTableRealColCount(Tab);
ARowIndex := ARow.rowIndex;
ACellIndex := ACell.cellIndex;
if ToRight and (ACellIndex = ARow.cells.length - 1) then
Exit;
TableMask := GetTableMask(Tab, RowCount, AllColCount);
MergeCellCount := ACell.colSpan; // Число столбцов в первоначальной ячейке
MergeRowCount := ACell.rowSpan; // Число строк в первоначальной ячейке
if (not ToRight) and (ARowIndex + MergeRowCount = Tab.rows.length) then
Exit;
// Определяем номер столбца в TableMask, с которого должно начаться объединение
MergeMaskCol := -1;
TmpInt := -1;
for I := 0 to AllColCount - 1 do
begin
if (TableMask[ARowIndex, I].Num = -1) and (TableMask[ARowIndex, I].IsCellStart) then
Inc(TmpInt);
if TmpInt = ACellIndex then
begin
MergeMaskCol := I;
Break;
end;
end;
if ToRight then
begin
// Проверяем для первой строки
if TableMask[ARowIndex, MergeMaskCol + MergeCellCount].Num <> -1 then
raise Exception.Create('Ячейка справа уже является объединенной! Воспользуйтесь сначала '+
'командой разбиения!');
// Запоминаем ячейку из верхней строки
TmpCell := TableMask[ARowIndex, MergeMaskCol + MergeCellCount].Cell;
if TmpCell.rowSpan > MergeRowCount then
raise Exception.Create('Ячейка справа имеет слишком много строк! Воспользуйтесь сначала '+
'командой разбиения!');
ACounter := TmpCell.rowSpan;;
// При необходимости объединяем ячейки справа
for I := ARowIndex + 1 to ARowIndex + MergeRowCount - 1 do
begin
if TableMask[I, MergeMaskCol + MergeCellCount].Cell.colSpan <> TmpCell.colSpan then
raise Exception.Create('Невозможно объединить с правыми ячейками, т.к. они имеют разную ширину!');
if TableMask[I, MergeMaskCol + MergeCellCount].Num = -1 then
ACounter := ACounter + TableMask[I, MergeMaskCol + MergeCellCount].Cell.rowSpan;
end;
if ACounter <> MergeRowCount then
raise Exception.Create('Невозможно объединить с правой ячейкой! Воспользуйтесь сначала '+
'разбиением или вертикальным объединением правой ячейки!');
// Объединяем строки в правом столбце
for I := ARowIndex + MergeRowCount - 1 downto ARowIndex + 1 do
begin
if TableMask[I, MergeMaskCol + MergeCellCount].Num = -1 then
begin
OldCell := TableMask[I, MergeMaskCol + MergeCellCount].Cell;
if Pointer(OldCell) <> Pointer(TmpCell) then
begin
TmpCell.rowSpan := TmpCell.rowSpan + OldCell.rowSpan;
(TmpCell as IHTMLElement).innerHTML := (TmpCell as IHTMLElement).innerHTML +
(OldCell as IHTMLElement).innerHTML;
(Tab.rows.item(I, 0) as IHTMLTableRow).deleteCell(OldCell.cellIndex);
TableMask[I, MergeMaskCol + MergeCellCount].Num := -2;
TableMask[I, MergeMaskCol + MergeCellCount].Cell := nil;
if (Tab.rows.item(I, 0) as IHTMLTableRow).cells.length = 0 then
begin
if ACell.rowSpan > 1 then
ACell.rowSpan := ACell.rowSpan - 1;
for J := 0 to AllColCount - 1 do
if TableMask[I, J].Num >= 0 then
if TableMask[I, J].Cell.rowSpan > 1 then
TableMask[I, J].Cell.rowSpan := TableMask[I, J].Cell.rowSpan - 1;
Tab.deleteRow(I);
end;
end;
end;
end;
ACell.colSpan := ACell.colSpan + TmpCell.colSpan;
(ACell as IHTMLElement).innerHTML := (ACell as IHTMLElement).innerHTML +
(TmpCell as IHTMLElement).innerHTML;
ARow.deleteCell(TmpCell.cellIndex);
TableMask[ARowIndex, MergeMaskCol + MergeCellCount].Num := -2;
end else
begin
if (TableMask[ARowIndex + MergeRowCount, MergeMaskCol].Num <> -1) or
(not TableMask[ARowIndex + MergeRowCount, MergeMaskCol].IsCellStart) then
raise Exception.Create('Ячейка снизу уже является объединенной! Воспользуйтесь сначала '+
'командой разбиения!');
TmpCell := TableMask[ARowIndex + MergeRowCount, MergeMaskCol].Cell;
ACounter := TmpCell.colSpan;
for I := MergeMaskCol + 1 to MergeMaskCol + MergeCellCount - 1 do
begin
if TableMask[ARowIndex + MergeRowCount, I].Cell.rowSpan <> TmpCell.rowSpan then
raise Exception.Create('Невозможно объединить с нижними ячейками, т.к. они имеют разную высоту!');
if TableMask[ARowIndex + MergeRowCount, I].IsCellStart and
(TableMask[ARowIndex + MergeRowCount, I].Num = -1) then
ACounter := ACounter + TableMask[ARowIndex + MergeRowCount, I].Cell.colSpan;
end;
if ACounter <> MergeCellCount then
raise Exception.Create('Невозможно объединить с нижней ячейкой! Воспользуйтесь сначала '+
'разбиением или горизонтальным объединением нижней ячейки!');
// Объединяем столбцы в нижней ячейке
for I := MergeMaskCol + MergeCellCount - 1 downto MergeMaskCol + 1 do
begin
if TableMask[ARowIndex + MergeRowCount, I].IsCellStart then
begin
OldCell := TableMask[ARowIndex + MergeRowCount, I].Cell;
if Pointer(OldCell) <> Pointer(TmpCell) then
begin
TmpCell.colSpan := TmpCell.colSpan + OldCell.colSpan;
(TmpCell as IHTMLElement).innerHTML := (TmpCell as IHTMLElement).innerHTML +
(OldCell as IHTMLElement).innerHTML;
(Tab.rows.item(ARowIndex + MergeRowCount, 0) as IHTMLTableRow).deleteCell(
OldCell.cellIndex);
TableMask[ARowIndex + MergeRowCount, I].Num := -2;
TableMask[ARowIndex + MergeRowCount, I].Cell := nil;
end;
end;
end;
ACell.rowSpan := ACell.rowSpan + TmpCell.rowSpan;
(ACell as IHTMLElement).innerHTML := (ACell as IHTMLElement).innerHTML +
(TmpCell as IHTMLElement).innerHTML;
(Tab.rows.item(ARowIndex + MergeRowCount, 0) as IHTMLTableRow).deleteCell(TmpCell.cellIndex);
TableMask[ARowIndex + MergeRowCount, MergeMaskCol].Num := -2;
TableMask[ARowIndex + MergeRowCount, MergeMaskCol].Cell := nil;
if (Tab.rows.item(ARowIndex + MergeRowCount, 0) as IHTMLTableRow).cells.length = 0 then
begin
if ACell.rowSpan > 1 then
ACell.rowSpan := ACell.rowSpan - 1;
for J := 0 to AllColCount - 1 do
if Assigned(TableMask[ARowIndex + MergeRowCount, J].Cell) and
(TableMask[ARowIndex + MergeRowCount, J].Num >= 0) then
if TableMask[TableMask[ARowIndex + MergeRowCount, J].Num, J].IsCellStart then
if TableMask[ARowIndex + MergeRowCount, J].Cell.rowSpan > 1 then
TableMask[ARowIndex + MergeRowCount, J].Cell.rowSpan :=
TableMask[ARowIndex + MergeRowCount, J].Cell.rowSpan - 1;
Tab.deleteRow(ARowIndex + MergeRowCount);
end;
end;
end;
function TTableClass.GetCurrentTable(var Index: Integer): IHTMLTable;
var
I: Integer;
begin
Result := nil;
if HTMLInfo.ElemDescArray[Index].edTagName <> 'TABLE' then
begin
for I := Index + 1 to High(HTMLInfo.ElemDescArray) do
if HTMLInfo.ElemDescArray[I].edTagName = 'TABLE' then
begin
Index := I;
Break;
end;
end;
if HTMLInfo.ElemDescArray[Index].edTagName = 'TABLE' then
Result := HTMLInfo.ElemDescArray[Index].edElem as IHTMLTable;
end;
function TTableClass.GetCurrentTableCell(var Index: Integer): IHTMLTableCell;
var
I: Integer;
function IsCell(S: string): Boolean;
begin
Result := (S = 'TD') or (S = 'TH');
end;
begin
Result := nil;
if not IsCell(HTMLInfo.ElemDescArray[Index].edTagName) then
begin
for I := Index - 1 downto 0 do
if IsCell(HTMLInfo.ElemDescArray[I].edTagName) then
begin
Index := I;
Break;
end;
end;
if IsCell(HTMLInfo.ElemDescArray[Index].edTagName) then
Result := HTMLInfo.ElemDescArray[Index].edElem as IHTMLTableCell;
end;
function TTableClass.GetCurrentTableRow(var Index: Integer): IHTMLTableRow;
var
I: Integer;
begin
Result := nil;
if HTMLInfo.ElemDescArray[Index].edTagName <> 'TR' then
begin
for I := Index - 1 downto 0 do
if HTMLInfo.ElemDescArray[I].edTagName = 'TR' then
begin
Index := I;
Break;
end;
end;
if HTMLInfo.ElemDescArray[Index].edTagName = 'TR' then
Result := HTMLInfo.ElemDescArray[Index].edElem as IHTMLTableRow;
end;
function TTableClass.GetTableMask(Tab: IHTMLTable; RowCount,
AllColCount: Integer): TTableMaskArray;
var
I, J, K, L, M, CSpan, RSpan: Integer;
ARow: IHTMLTableRow;
TmpCell: IHTMLTableCell;
LastI, LastJ, LastK, LastL, LastM: Integer;
begin
// Инициализируем массив. Забиваем его значениями -2
SetLength(Result, RowCount, AllColCount);
for I := 0 to RowCount - 1 do
for J := 0 to AllColCount - 1 do
begin
Result[I, J].Num := -2;
Result[I, J].Cell := nil;
Result[I, J].IsCellStart := False;
end;
LastI := -1;
LastJ := -1;
LastK := -1;
LastL := -1;
LastM := -1;
try
for I := 0 to RowCount - 1 do
begin
LastI := I;
ARow := Tab.rows.item(I, 0) as IHTMLTableRow;
for J := 0 to ARow.cells.length - 1 do
begin
LastJ := J;
TmpCell := ARow.cells.item(J, 0) as IHTMLTableCell;
CSpan := TmpCell.colSpan;
RSpan := TmpCell.rowSpan;
// Отыскиваем в массиве первую ячейку с -2.
for K := 0 to AllColCount - 1 do
begin
LastK := K;
if Result[I, K].Num = -2 then
begin
// Записываем значения "-1" (т.е. здесь - реальные ячейки строки)
for L := K to Min(K + CSpan - 1, AllColCount - 1) do
begin
LastL := L;
Result[I, L].Num := -1;
if L = K then
Result[I, L].IsCellStart := True;
Result[I, L].Cell := TmpCell;
// Заполняем элементы ниже (для RSpan)
for M := I + 1 to I + RSpan - 1 do
begin
LastM := M;
Result[M, L].Num := I; // Действует rowSpan от I-й строки
Result[M, L].Cell := TmpCell; // Сохраняем действующую ячейку
end;
end;
Break;
end;
end;
end;
end;
except
//LastI, LastJ, LastK, LastL, LastM
on E: Exception do
raise Exception.CreateFmt('LastI=%d, LastJ=%d, LastK=%d, LastL=%d, LastM=%d. ' + E.Message,
[LastI, LastJ, LastK, LastL, LastM]);
end;
end;
function TTableClass.GetTableRealColCount(Tab: IHTMLTable): Integer;
var
I: Integer;
ARow: IHTMLTableRow;
begin
Result := 0;
// Считаем, что первый ряд описывает кол-во столбцов в таблице
ARow := Tab.rows.item(0, 0) as IHTMLTableRow;
for I := 0 to ARow.cells.length - 1 do
Result := Result + (ARow.cells.item(I, 0) as IHTMLTableCell).colSpan;
end;
procedure TTableClass.ResetAllCellBorders(Value: Char);
var
Index: Integer;
ACell: IHTMLTableCell;
Param: string;
begin
Index := HTMLInfo.CurrentIndex;
ACell := GetCurrentTableCell(Index);
if ACell <> nil then
begin
case Value of
'T': Param := 'solid';
'F': Param := 'none';
else
Param := '';
end;
(ACell as IHTMLElement).style.borderLeftStyle := Param;
(ACell as IHTMLElement).style.borderTopStyle := Param;
(ACell as IHTMLElement).style.borderRightStyle := Param;
(ACell as IHTMLElement).style.borderBottomStyle := Param;
end;
end;
procedure TTableClass.ResetOneCellBorder(Side, Value: Char);
var
Index: Integer;
ACell: IHTMLTableCell;
Param: string;
begin
Index := HTMLInfo.CurrentIndex;
ACell := GetCurrentTableCell(Index);
if ACell <> nil then
begin
case Value of
'T': Param := 'solid';
'F': Param := 'none';
else
Param := '';
end;
case Side of
'L': (ACell as IHTMLElement).style.borderLeftStyle := Param;
'T': (ACell as IHTMLElement).style.borderTopStyle := Param;
'R': (ACell as IHTMLElement).style.borderRightStyle := Param;
'B': (ACell as IHTMLElement).style.borderBottomStyle := Param;
end;
end;
end;
function TTableClass.DocRange: IHTMLTxtRange;
var
SelType: string;
begin
Result := nil;
SelType := HTMLInfo.editor.selection.type_; // None / Text / Control
if SelType <> 'Control' then
Result := (HTMLInfo.editor.selection.createRange as IHTMLTxtRange);
end;
end.
|
unit frmReplaceU;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Menus;
type
TfrmReplace = class(TForm)
Label1: TLabel;
Label2: TLabel;
edtKey: TEdit;
edtReplace: TEdit;
btnReplace: TButton;
btnReplaceAll: TButton;
chkSelectArea: TCheckBox;
popRep: TPopupMenu;
Copy1: TMenuItem;
Cut1: TMenuItem;
popPaste: TMenuItem;
popAll: TMenuItem;
N3: TMenuItem;
procedure btnReplaceClick(Sender: TObject);
procedure btnReplaceAllClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure Copy1Click(Sender: TObject);
procedure Cut1Click(Sender: TObject);
procedure popPasteClick(Sender: TObject);
procedure popAllClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure edtKeyEnter(Sender: TObject);
procedure edtReplaceEnter(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private 宣言 }
public
{ Public 宣言 }
edts: array[0..1]of TEdit;
FIndex: Integer;
end;
var
frmReplace: TfrmReplace;
implementation
uses sakurapadU, StrUnit, gui_benri, HEditor;
{$R *.dfm}
procedure TfrmReplace.btnReplaceClick(Sender: TObject);
var
key, txt: string;
idx,cur: Integer;
begin
key := edtKey.Text ;
txt := frmSakuraPad.ActiveEditor.Lines.Text ;
cur := frmSakuraPad.ActiveEditor.SelStart +1;
idx := JPosEx(key, txt , cur);
if idx<=0 then begin
cur := 0;
idx := JPosEx(key, txt , cur+1);
if idx<=0 then begin
ShowMessage('検索語「'+key+'」は見つかりませんでした。');
Exit;
end;
end;
{if MsgYesNo('"'+key+'"が見つかりました。'#13#10+
'"'+edtReplace.Text+'"に、置換しますか?') then}
begin
Delete(txt, idx, Length(key));
Insert(edtReplace.Text, txt, idx);
with frmSakuraPad.ActiveEditor do begin
Lines.Text := txt;
SetFocus ;
SelStart := idx-1 + Length(Self.edtReplace.Text);
SelLength := 0;//Length(Self.edtReplace.Text);
frmSakuraPad.PlayModify := True;
end;
end;
end;
procedure TfrmReplace.btnReplaceAllClick(Sender: TObject);
begin
//if MsgYesNo('全て置換します。よろしいですか?')=False then Exit;
with frmSakuraPad.ActiveEditor do
begin
if chkSelectArea.Checked then
begin
SelText := JReplace(SelText, Self.edtKey.Text, Self.edtReplace.Text, True);
end else
begin
Lines.Text := JReplace(Lines.Text, Self.edtKey.Text, Self.edtReplace.Text, True);
end;
end;
end;
procedure TfrmReplace.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_ESCAPE then Close;
end;
procedure TfrmReplace.Copy1Click(Sender: TObject);
begin
edts[FIndex].CopyToClipboard ;
end;
procedure TfrmReplace.Cut1Click(Sender: TObject);
begin
edts[FIndex].CutToClipboard ;
end;
procedure TfrmReplace.popPasteClick(Sender: TObject);
begin
edts[FIndex].PasteFromClipboard ;
end;
procedure TfrmReplace.popAllClick(Sender: TObject);
begin
edts[FIndex].SelectAll ;
end;
procedure TfrmReplace.FormCreate(Sender: TObject);
begin
if frmSakuraPad.FlagForceClose then Exit;
frmSakuraPad.ini.LoadForm(Self);
edts[0] := edtKey ;
edts[1] := edtReplace ;
FIndex := 0;
end;
procedure TfrmReplace.edtKeyEnter(Sender: TObject);
begin
FIndex := 0;
end;
procedure TfrmReplace.edtReplaceEnter(Sender: TObject);
begin
FIndex := 1;
end;
procedure TfrmReplace.FormDestroy(Sender: TObject);
begin
if frmSakuraPad.FlagForceClose then Exit;
frmSakuraPad.ini.SaveForm(Self);
end;
end.
|
{$mode objfpc}{$H+}{$J-}
uses SysUtils;
type
TFruit = class
procedure Eat;
end;
TApple = class(TFruit)
procedure Eat;
end;
procedure TFruit.Eat;
begin
Writeln('Изядохме плод');
end;
procedure TApple.Eat;
begin
Writeln('Изядохме ябълка');
end;
procedure DoSomethingWithAFruit(const Fruit: TFruit);
begin
Writeln('Имаме плод от клас ', Fruit.ClassName);
Writeln('Ядем го:');
Fruit.Eat;
end;
var
Apple: TApple; // Забележка: тук също така може да декларирате "Apple: TFruit"
begin
Apple := TApple.Create;
try
DoSomethingWithAFruit(Apple);
finally FreeAndNil(Apple) end;
end.
|
unit query_filter;
{$mode objfpc}{$H+}
interface
uses
Classes, lcltype, SysUtils, Forms, DB,
ExtCtrls, Dialogs, Controls, StdCtrls, metadata, Spin, Buttons;
type
TRelationalOperation = (roContaining, roStartsWith, roGreater, roLess, roNotLess, roNotGreater, roEqual,
roInequal);
TCustomEditClass = class of TCustomEdit;
TRelOperation = class
private
FCaption: string;
FCode: string;
public
property Caption: string read FCaption;
property Code: string read FCode;
constructor Create(aCaption, aCode: string);
end;
TFilter = record
ChosenField: TDBField;
Operation: TRelOperation;
Value: string;
end;
TQueryFilter = class;
TQueryFilterDynArray = array of TQueryFilter;
TQueryFilter = class
private
FTag: integer;
FDestroying: TNotifyEvent;
FChangingData: TNotifyEvent;
FPanel: TCustomControl;
FHeight: integer;
FTop: integer;
FAddingFilter: TNotifyEvent;
cbbFields: TComboBox;
cbbOperations: TComboBox;
btnDeleteFilter: TButton;
btnAddFilter: TButton;
FTable: TDBTable;
procedure SetFilterTop(Value: integer);
procedure SetFilterHeight(Value: integer);
procedure SetFilterTag(Value: integer);
procedure SetOperation(Value: TRelOperation);
procedure SetField(Value: TDBField);
procedure SetValue(Value: Variant);
function GetField: TDBField;
function GetValue: Variant;
function GetOperation: TRelOperation;
public
ConstantEditor: TCustomEdit;
property ChosenField: TDBField read GetField write SetField;
property Tag: integer read FTag write SetFilterTag;
property OnDestroy: TNotifyEvent read FDestroying write FDestroying;
property OnChangeData: TNotifyEvent read FChangingData write FChangingData;
property OnFilterAdd: TNotifyEvent read FAddingFilter write FAddingFilter;
property Top: integer read FTop write SetFilterTop;
property Height: integer read FHeight write SetFilterHeight;
property Value: variant read GetValue write SetValue;
property Operation: TRelOperation read GetOperation write SetOperation;
procedure ChosenFieldChange(Sender: TObject);
procedure DeleteFilterClick(Sender: TObject; MouseButton: TMouseButton;
ShiftState: TShiftState; X, Y: longint);
procedure AddFieldsForChoose(ATable: TDBTable);
procedure EditChange(Sender: TObject);
procedure OperationChange(Sender: TObject);
procedure AddFilterClick(Sender: TObject);
class procedure CopyFilters(AToTable: TDBTable; var AFrom, ATo:
TQueryFilterDynArray; AToPanel: TCustomControl);
constructor Create(ATable: TDBTable; AIndex: integer; APanel: TCustomControl);
destructor Destroy; override;
end;
const
FilterHeight = 26;
var
Operations: array [Low(TRelationalOperation)..High(TRelationalOperation)] of TRelOperation;
TypeOfEditor: array [Low(TFieldType)..High(TFieldType)] of TCustomEditClass;
AvailableOperations: array [Low(TFieldType)..High(TFieldType)] of set of TRelationalOperation;
NoneOperation: TRelOperation;
implementation
constructor TQueryFilter.Create(ATable: TDBTable; AIndex: integer; APanel: TCustomControl);
var
sbxPanel: TScrollBox;
begin
FPanel := APanel;
FTag := AIndex;
sbxPanel := APanel as TScrollBox;
FTable := ATable;
btnDeleteFilter := TButton.Create(sbxPanel);
with btnDeleteFilter do begin
Parent := sbxPanel;
Height := FilterHeight;
Width := Height;
FHeight := Height;
Caption := 'X';
Left := 2;
Tag := AIndex;
OnMouseUp := @DeleteFilterClick;
end;
cbbFields := TComboBox.Create(sbxPanel);
with cbbFields do begin
Parent := sbxPanel;
Left := btnDeleteFilter.Left + btnDeleteFilter.Width + 1;
AutoSize := false;
Height := btnDeleteFilter.Height + 2;
Style := csDropDownList;
AddFieldsForChoose(FTable);
AddItem('ИЛИ', nil);
OnChange := @ChosenFieldChange;
end;
btnAddFilter := TButton.Create(sbxPanel);
btnAddFilter.Parent := sbxPanel;
with btnAddFilter do begin
Height := btnDeleteFilter.Height;
Width := Height;
FHeight := Height;
Caption := '+';
Tag := btnDeleteFilter.Tag;
Top := btnDeleteFilter.Top;
Left := cbbFields.Left + cbbFields.Width + 1;
OnClick := @AddFilterClick;
end;
end;
procedure TQueryFilter.AddFieldsForChoose(ATable: TDBTable);
var
i: integer;
begin
with cbbFields do
with ATable do
for i := 0 to High(Fields) do begin
if Fields[i].Visible then begin
AddItem(Fields[i].Caption, Fields[i]);
end;
if Assigned(Fields[i].TableRef) then
AddFieldsForChoose(Fields[i].TableRef);
end;
end;
procedure TQueryFilter.DeleteFilterClick(Sender: TObject; MouseButton: TMouseButton; ShiftState: TShiftState; X, Y: longint);
begin
if Assigned(FChangingData) then FChangingData(Self);
FDestroying(Sender);
end;
procedure TQueryFilter.ChosenFieldChange(Sender: TObject);
var
VSender: TComboBox;
tempft: TFieldType;
ro: TRelationalOperation;
Panel: TScrollBox;
begin
VSender := (Sender as TComboBox);
Panel := FPanel as TScrollBox;
if Assigned(ConstantEditor) then begin
FreeAndNil(ConstantEditor);
FreeAndNil(cbbOperations);
end;
btnAddFilter.Left := VSender.Left + VSender.Width + 1;
if VSender.ItemIndex < 0 then exit;
if Assigned(VSender.Items.Objects[VSender.ItemIndex]) then
tempft := ((VSender.Items.Objects[VSender.ItemIndex]) as TDBField).FieldType
else
tempft := ftUnknown;
cbbOperations := TComboBox.Create(Panel);
cbbOperations.Parent := Panel;
with cbbOperations do begin
AutoSize := false;
Top := btnDeleteFilter.Top;
Left := cbbFields.Left + cbbFields.Width + 1;
Height := cbbFields.Height;
Style := csDropDownList;
for ro := Low(TRelationalOperation) to High(TRelationalOperation) do
if ro in AvailableOperations[tempft] then
AddItem(Operations[ro].Caption, Operations[ro]);
ItemIndex := 0;
OnChange := @OperationChange;
end;
ConstantEditor := TypeOfEditor[tempft].Create(Panel);
ConstantEditor.Parent := Panel;
with ConstantEditor do begin
AutoSize := false;
Height := cbbFields.Height;
Width := cbbFields.Width;;
Top := btnDeleteFilter.Top;
Left := cbbOperations.Left + cbbOperations.Width + 1;
if TypeOfEditor[tempft] = TSpinEdit then
with (ConstantEditor as TSpinEdit) do begin
MaxValue := High(Integer);
MinValue := Low(Integer);
end;
if TypeOfEditor[tempft] = TEdit then
with (ConstantEditor as TEdit) do
if Assigned(VSender.Items.Objects[VSender.ItemIndex]) then
MaxLength := ((VSender.Items.Objects[VSender.ItemIndex]) as TDBField).VarCharLimit;
OnChange := @EditChange;
end;
if tempft = ftUnknown then begin
ConstantEditor.Text := ' ';
ConstantEditor.Visible := false;
cbbOperations.ItemIndex := -1;
cbbOperations.Visible := false;
end else
btnAddFilter.Left := ConstantEditor.Left + ConstantEditor.Width + 1;
if Assigned(FChangingData) then FChangingData(Self);
end;
procedure TQueryFilter.EditChange(Sender: TObject);
begin
if Assigned(FChangingData) then FChangingData(Self);
end;
procedure TQueryFilter.OperationChange(Sender: TObject);
begin
if Assigned(FChangingData) then FChangingData(Self);
end;
procedure TQueryFilter.AddFilterClick(Sender: TObject);
begin
FAddingFilter(Sender);
end;
procedure TQueryFilter.SetFilterTop(Value: integer);
begin
btnDeleteFilter.Top := Value;
cbbFields.Top := Value;
btnAddFilter.Top := Value;
if Assigned(ConstantEditor) then begin
ConstantEditor.Top := Value;
cbbOperations.Top := Value;
end;
FTop := Value;
end;
procedure TQueryFilter.SetFilterHeight(Value: integer);
begin
btnDeleteFilter.Height := Value;
cbbFields.Height := Value;
btnAddFilter.Height := Value;
if Assigned(ConstantEditor) then begin
ConstantEditor.Height := Value;
cbbOperations.Height := Value;
end;
FHeight := Value;
end;
procedure TQueryFilter.SetFilterTag(Value: integer);
begin
btnDeleteFilter.Tag := Value;
btnAddFilter.Tag := Value;
FTag := Value;
end;
function TQueryFilter.GetField: TDBField;
var
Field: TDBField;
begin
if cbbFields.ItemIndex < 0 then exit(nil);
if Assigned(cbbFields.Items.Objects[cbbFields.ItemIndex] as TDBField) then
Result := cbbFields.Items.Objects[cbbFields.ItemIndex] as TDBField
else
Result := nil;
end;
procedure TQueryFilter.SetField(Value: TDBField);
begin
if Value = nil then exit;
with cbbFields do
ItemIndex := Items.IndexOfObject(Value);
ChosenFieldChange(cbbFields);
end;
function TQueryFilter.GetOperation: TRelOperation;
begin
if not Assigned(cbbOperations) or not cbbOperations.Visible then
exit(NoneOperation);
Result := cbbOperations.Items.Objects[cbbOperations.ItemIndex] as TRelOperation;
end;
procedure TQueryFilter.SetOperation(Value: TRelOperation);
begin
with cbbOperations do
ItemIndex := Items.IndexOfObject(Value);
end;
function TQueryFilter.GetValue: Variant;
begin
if (not Assigned(ConstantEditor)) or (not ConstantEditor.Visible) then exit(' ');
if ((cbbFields.Items.Objects[cbbFields.ItemIndex]) as TDBField).FieldType = ftInteger then
Result := (ConstantEditor as TSpinEdit).Value
else
Result := ConstantEditor.Text;
end;
procedure TQueryFilter.SetValue(Value: Variant);
begin
ConstantEditor.Text := Value;
end;
class procedure TQueryFilter.CopyFilters(AToTable: TDBTable; var AFrom, ATo:
TQueryFilterDynArray; AToPanel: TCustomControl);
var
i: integer;
begin
for i := 0 to Length(ATo) - 1 do
ATo[i].Destroy;
SetLength(ATo, Length(AFrom));
for i := 0 to Length(ATo) - 1 do
ATo[i] := TQueryFilter.Create(AToTable, i, AToPanel);
for i := 0 to Length(AFrom) - 1 do begin
ATo[i].ChosenField := AFrom[i].ChosenField;
if Assigned(ATo[i].ChosenField) then begin
ATo[i].Operation := AFrom[i].Operation;
ATo[i].Value := AFrom[i].Value;
end else
if AFrom[i].cbbFields.ItemIndex = AFrom[i].cbbFields.Items.Count - 1 then begin
ATo[i].cbbFields.ItemIndex := ATo[i].cbbFields.Items.Count - 1;
ATo[i].ChosenFieldChange(ATo[i].cbbFields);
end;
end;
end;
destructor TQueryFilter.Destroy;
begin
FreeAndNil(btnDeleteFilter);
FreeAndNil(cbbFields);
FreeAndNil(btnAddFilter);
if Assigned(ConstantEditor) then begin
FreeAndNil(ConstantEditor);
FreeAndNil(cbbOperations);
end;
inherited;
end;
constructor TRelOperation.Create(ACaption, ACode: string);
begin
FCaption := ACaption;
FCode := ACode;
end;
initialization
TypeOfEditor[ftInteger] := TSpinEdit;
TypeOfEditor[ftString] := TEdit;
TypeOfEditor[ftUnknown] := TEdit;
AvailableOperations[ftInteger] := [roEqual, roInequal, roGreater, roNotGreater, roNotLess, roLess];
AvailableOperations[ftString] := [roContaining, roStartsWith, roEqual, roInequal, roGreater, roNotGreater, roNotLess, roLess];
Operations[roGreater] := TRelOperation.Create('>', ' > ');
Operations[roContaining] := TRelOperation.Create('Содержит', ' containing ');
Operations[roEqual] := TRelOperation.Create('=', ' = ');
Operations[roInequal] := TRelOperation.Create('<>', ' <> ');
Operations[roLess] := TRelOperation.Create('<', ' < ');
Operations[roNotGreater] := TRelOperation.Create('<=', ' <= ');
Operations[roNotLess] := TRelOperation.Create('>=', ' >= ');
Operations[roStartsWith] := TRelOperation.Create('Начинается с', ' starts with ');
NoneOperation := TRelOperation.Create(' ', ' ');
end.
|
unit CoordinatesSystems;
interface
uses SysUtils, Classes, Graphics, Points;
type
TCoordinatesSystem = class
Private
Canvas : TCanvas;
ClientWidth : Integer;
ClientHeight : Integer;
procedure ConvertCoordinates(x, y : Real; var xOut, yOut : Real);
Public
XCenter : Integer;
YCenter : Integer;
AxisColor : TColor;
AxisStyle : TPenStyle;
AxisWidth : Integer;
GridColor : TColor;
GridStyle : TPenStyle;
GridWidth : Integer;
GridStep : Integer;
constructor Create(canvas : TCanvas; clientWidth, clientHeight : Integer);
procedure Draw();
procedure DrawPoint(point : TPoint); Overload;
procedure DrawPoint(point : TPoint; color : TColor; style : TPenStyle; width : Integer); Overload;
procedure DrawLine(point1, point2 : TPoint); Overload;
procedure DrawLine(point1, point2 : TPoint; color : TColor; style : TPenStyle; width : Integer); Overload;
procedure DrawPointsList(pointsList : TList); Overload;
procedure DrawPointsList(pointsList : TList; color : TColor; style : TPenStyle; width : Integer); Overload;
procedure DrawPointsHull(pointsList : TList); Overload;
procedure DrawPointsHull(pointsList : TList; color : TColor; style : TPenStyle; width : Integer); Overload;
procedure ScreenToPointCoordinates(x1, y1 : Integer; var xOut, yOut : Integer);
end;
implementation
constructor TCoordinatesSystem.Create(canvas : TCanvas; clientWidth, clientHeight : Integer);
begin
self.Canvas := canvas;
self.GridStep := 15;
self.ClientWidth := clientWidth;
self.ClientHeight := clientHeight;
self.XCenter := round(self.ClientWidth / 2);
self.YCenter := round(self.ClientHeight / 2);
self.XCenter := self.XCenter - (self.XCenter mod self.GridStep);
self.YCenter := self.YCenter - (self.YCenter mod self.GridStep);
self.AxisColor := clblack;
self.AxisStyle := psSolid;
self.AxisWidth := 3;
self.GridColor := clSilver;
self.GridStyle := psSolid;
self.GridWidth := 1;
end;
procedure TCoordinatesSystem.Draw();
var i : Integer;
begin
with self.Canvas do
begin
Pen.Color := self.AxisColor;
Pen.Style := self.AxisStyle;
Pen.Width := self.AxisWidth;
MoveTo(0, self.YCenter);
LineTo(self.ClientWidth, self.YCenter);
MoveTo(self.XCenter, self.ClientHeight);
LineTo(self.XCenter, 0);
i := 0;
while i <= self.ClientWidth do
begin
Pen.Color := self.GridColor;
Pen.Width := self.GridWidth;
if (i <> XCenter) then
begin
MoveTo(i, 0);
LineTo(i - 1, self.ClientHeight);
end;
// малюємо вертикальні штрихи на осі Х
Pen.Color := self.AxisColor;
Pen.Width := self.AxisWidth - 1;
MoveTo(i, self.YCenter - 3);
LineTo(i - 1, self.YCenter + 3);
i := i + self.GridStep;
end;
i := 0;
while i <= self.ClientHeight do
begin
Pen.Color := self.GridColor;
Pen.Width := self.GridWidth;
if (i <> YCenter) then
begin
MoveTo(0, i);
LineTo(self.ClientWidth, i + 1);
end;
Pen.Color := self.AxisColor;
Pen.Width := self.AxisWidth - 1;
MoveTo(self.XCenter - 3, i);
LineTo(self.XCenter + 3, i - 1);
i := i + self.GridStep;
end;
end;
end;
procedure TCoordinatesSystem.DrawPoint(point : TPoint; color : TColor; style : TPenStyle; width : Integer);
var a, b : Real;
begin
ConvertCoordinates(point.X, point.Y, a, b);
with self.Canvas do
begin
Pen.Color := color;
Pen.Style := style;
Pen.Width := width;
Ellipse(round(a - 1), round(b - 1), round(a + 1), round(b + 1));
TextOut(round(a), round(b), point.Name);
end;
end;
procedure TCoordinatesSystem.DrawPoint(point : TPoint);
begin
self.DrawPoint(point, clRed, psSolid, 3);
end;
procedure TCoordinatesSystem.ConvertCoordinates(x, y : Real; var xOut, yOut : Real);
begin
xOut := self.GridStep * x + XCenter;
yOut := -self.GridStep * y + YCenter;
end;
procedure TCoordinatesSystem.ScreenToPointCoordinates(x1, y1 : Integer; var xOut, yOut : Integer);
begin
xOut := round ((x1 - XCenter) / self.GridStep);
yOut := round ((y1 - YCenter) / -self.GridStep);
end;
procedure TCoordinatesSystem.DrawPointsList(pointsList : TList; color : TColor; style : TPenStyle; width : Integer);
var i : Integer;
begin
for i:=0 to pointsList.Count - 1 do
DrawPoint(TPoint(pointsList[i]), color, style, width);
end;
procedure TCoordinatesSystem.DrawPointsList(pointsList : TList);
begin
DrawPointsList(pointsList, clRed, psSolid, 3);
end;
procedure TCoordinatesSystem.DrawPointsHull(pointsList : TList; color : TColor; style : TPenStyle; width : Integer);
var i : Integer; point, nextPoint : TPoint;
begin
for i:=0 to pointsList.Count - 2 do
begin
point := TPoint(pointsList[i]);
nextPoint := TPoint(pointsList[i + 1]);
DrawLine(point, nextPoint, color, style, width);
end;
point := nextPoint;
nextPoint := TPoint(pointsList.First);
DrawLine(point, nextPoint, color, style, width);
end;
procedure TCoordinatesSystem.DrawPointsHull(pointsList : TList);
begin
DrawPointsHull(pointsList, clRed, psSolid, 1);
end;
procedure TCoordinatesSystem.DrawLine(point1, point2 : TPoint);
begin
DrawLine(point1, point2, clRed, psSolid, 1);
end;
procedure TCoordinatesSystem.DrawLine(point1, point2 : TPoint; color : TColor; style : TPenStyle; width : Integer);
var x1, x2, y1, y2 : Real;
begin
with self.Canvas do
begin
Pen.Color := color;
Pen.Style := style;
Pen.Width := width;
end;
ConvertCoordinates(point1.X, point1.Y, x1, y1);
ConvertCoordinates(point2.X, point2.Y, x2, y2);
self.Canvas.MoveTo(round(x1), round(y1));
self.Canvas.LineTo(round(x2), round(y2));
end;
end.
|
unit Validator;
interface
uses
Dictionary, Classes, ForestTypes;
type
TValidator = class(TObject)
private
DictForestries: TDictionary;
DictLocalForestries: TDictionary;
DictLanduse: TDictionary;
DictProtectCategory: TDictionary;
DictSpecies: TDictionary;
DictDamage: TDictionary;
DictPest: TDictionary;
FRecNo: Integer;
FRecordStatus: AnsiString;
FLogDetails: TLogDetails;
FValidationResult: TValidationResult;
procedure AddRecordStatus(const Status: AnsiString; const ValidationID: TLogDetail);
procedure AddValidationResult(const ValResult: TValidationRes);
procedure StringValidateField(var Field: AnsiString; var FieldID: Integer;
const Dict: TDictionary; const Prompt: AnsiString; const RelationID: Integer = 0);
procedure RelationValidateRecord(var CurrentRecord: TValuesRec);
procedure MathValidateRecord(var CurrentRecord: TValuesRec);
procedure MathExtraValidateRecord(var CurrentRecord: TValuesRec);
procedure StringValidateRecord(var CurrentRecord: TValuesRec);
public
constructor Create(Owner: TObject);
destructor Destroy; override;
procedure InitCheck(LogDetails: TLogDetails);
function GetDictionary(DictCaption: AnsiString): TDictionary;
procedure Validate(const RecNo: Integer; var CurrentRecord: TValuesRec);
property ValidationResult: TValidationResult read FValidationResult;
property RecordStatus: AnsiString read FRecordStatus;
end;
implementation
uses
SysUtils, Edit, ForestConsts, Data;
//---------------------------------------------------------------------------
{ TValidator }
procedure TValidator.AddRecordStatus(const Status: AnsiString; const ValidationID: TLogDetail);
begin
case ValidationID of
ldMathErrors:
begin
if ldMathErrors in FLogDetails then
FRecordStatus := FRecordStatus + Status;
end;
ldDictReplaces:
begin
if ldDictReplaces in FLogDetails then
FRecordStatus := FRecordStatus + Status;
end;
ldRelationErrors:
begin
if ldRelationErrors in FLogDetails then
FRecordStatus := FRecordStatus + Status;
end;
end;
end;
//---------------------------------------------------------------------------
procedure TValidator.AddValidationResult(const ValResult: TValidationRes);
begin
Include(FValidationResult, ValResult);
end;
//---------------------------------------------------------------------------
constructor TValidator.Create(Owner: TObject);
begin
DictForestries := TDictionary.Create(S_DICT_FORESTRIES_FILE, S_DICT_FORESTRIES_NAME);
DictForestries.SQLScript := S_SQL_GET_FORESTRIES_DICT;
DictLocalForestries := TDictionary.Create(S_DICT_LOCAL_FORESTRIES_FILE, S_DICT_LOCAL_FORESTRIES_NAME);
DictLocalForestries.SQLScript := S_SQL_GET_LOCAL_FORESTRIES_DICT;
DictLanduse := TDictionary.Create(S_DICT_LANDUSE_FILE, S_DICT_LANDUSE_NAME);
DictLanduse.SQLScript := S_SQL_GET_LANDUSE_DICT;
DictProtectCategory := TDictionary.Create(S_DICT_PROTECT_CATEGORY_FILE, S_DICT_PROTECT_CATEGORY_NAME);
DictProtectCategory.SQLScript := S_SQL_GET_PROTECT_CATEGORY_DICT;
DictSpecies := TDictionary.Create(S_DICT_SPECIES_FILE, S_DICT_SPECIES_NAME);
DictSpecies.SQLScript := S_SQL_GET_SPECIES_DICT;
DictDamage := TDictionary.Create(S_DICT_DAMAGE_FILE, S_DICT_DAMAGE_NAME);
DictDamage.SQLScript := S_SQL_GET_DAMAGE_DICT;
DictPest := TDictionary.Create(S_DICT_PEST_FILE, S_DICT_PEST_NAME);
DictPest.SQLScript := S_SQL_GET_PEST_DICT;
end;
//---------------------------------------------------------------------------
destructor TValidator.Destroy;
begin
DictForestries.Free();
DictLocalForestries.Free();
DictLanduse.Free();
DictProtectCategory.Free();
DictSpecies.Free();
DictDamage.Free();
DictPest.Free();
inherited;
end;
//---------------------------------------------------------------------------
function TValidator.GetDictionary(DictCaption: AnsiString): TDictionary;
begin
if DictCaption = S_DICT_FORESTRIES_NAME then
Result := DictForestries
else if DictCaption = S_DICT_LOCAL_FORESTRIES_NAME then
Result := DictLocalForestries
else if DictCaption = S_DICT_LANDUSE_NAME then
Result := DictLanduse
else if DictCaption = S_DICT_PROTECT_CATEGORY_NAME then
Result := DictProtectCategory
else if DictCaption = S_DICT_SPECIES_NAME then
Result := DictSpecies
else if DictCaption = S_DICT_DAMAGE_NAME then
Result := DictDamage
else if DictCaption = S_DICT_PEST_NAME then
Result := DictPest;
end;
//---------------------------------------------------------------------------
procedure TValidator.InitCheck(LogDetails: TLogDetails);
begin
DictForestries.ForceSkip := False;
DictLocalForestries.ForceSkip := False;
DictLanduse.ForceSkip := False;
DictProtectCategory.ForceSkip := False;
DictSpecies.ForceSkip := False;
DictDamage.ForceSkip := False;
DictPest.ForceSkip := False;
FLogDetails := LogDetails;
end;
//---------------------------------------------------------------------------
procedure TValidator.MathExtraValidateRecord(var CurrentRecord: TValuesRec);
begin
if CurrentRecord.F59 > CurrentRecord.F13 then
begin
AddValidationResult(vrExtraInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 59, 13]), ldMathErrors);
end;
if CurrentRecord.F60 > CurrentRecord.F13 then
begin
AddValidationResult(vrExtraInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 60, 13]), ldMathErrors);
end;
if CurrentRecord.F61 > CurrentRecord.F13 then
begin
AddValidationResult(vrExtraInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 61, 13]), ldMathErrors);
end;
if CurrentRecord.F62 > CurrentRecord.F13 then
begin
AddValidationResult(vrExtraInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 62, 13]), ldMathErrors);
end;
if CurrentRecord.F63 > CurrentRecord.F13 then
begin
AddValidationResult(vrExtraInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 63, 13]), ldMathErrors);
end;
if CurrentRecord.F64 > CurrentRecord.F13 then
begin
AddValidationResult(vrExtraInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 64, 13]), ldMathErrors);
end;
if CurrentRecord.F65 > CurrentRecord.F13 then
begin
AddValidationResult(vrExtraInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 65, 13]), ldMathErrors);
end;
if CurrentRecord.F66 > CurrentRecord.F13 then
begin
AddValidationResult(vrExtraInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 66, 13]), ldMathErrors);
end;
if CurrentRecord.F67 > CurrentRecord.F13 then
begin
AddValidationResult(vrExtraInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 67, 13]), ldMathErrors);
end;
if CurrentRecord.F68 > CurrentRecord.F13 then
begin
AddValidationResult(vrExtraInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 68, 13]), ldMathErrors);
end;
end;
//---------------------------------------------------------------------------
procedure TValidator.MathValidateRecord(var CurrentRecord: TValuesRec);
var
Tmp: Currency;
begin
// 2
if CurrentRecord.F13 > CurrentRecord.F12 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 13, 12]), ldMathErrors);
end;
// 3
if (CurrentRecord.F14 + CurrentRecord.F15 + CurrentRecord.F16 <> CurrentRecord.F13) then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_SUM_ONE_DIFF_THAN_TWO, [FRecNo, '14-16', 13]), ldMathErrors);
end;
if CurrentRecord.F14 > CurrentRecord.F13 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 14, 13]), ldMathErrors);
end;
if CurrentRecord.F15 > CurrentRecord.F13 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 15, 13]), ldMathErrors);
end;
if CurrentRecord.F16 > CurrentRecord.F13 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 16, 13]), ldMathErrors);
end;
// 4
if CurrentRecord.F17 > CurrentRecord.F13 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 17, 13]), ldMathErrors);
end;
if CurrentRecord.F18 > CurrentRecord.F13 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 18, 13]), ldMathErrors);
end;
if CurrentRecord.F19 > CurrentRecord.F13 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 19, 13]), ldMathErrors);
end;
if CurrentRecord.F20 > CurrentRecord.F13 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 20, 13]), ldMathErrors);
end;
if CurrentRecord.F21 > CurrentRecord.F13 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 21, 13]), ldMathErrors);
end;
if CurrentRecord.F22 > CurrentRecord.F13 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 22, 13]), ldMathErrors);
end;
if CurrentRecord.F23 > CurrentRecord.F13 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 23, 13]), ldMathErrors);
end;
if CurrentRecord.F24 > CurrentRecord.F13 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 24, 13]), ldMathErrors);
end;
if CurrentRecord.F25 > CurrentRecord.F13 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 25, 13]), ldMathErrors);
end;
if CurrentRecord.F26 > CurrentRecord.F13 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 26, 13]), ldMathErrors);
end;
// 5
if (CurrentRecord.F17 + CurrentRecord.F18 - CurrentRecord.F34 -
CurrentRecord.F40 - CurrentRecord.F46 - CurrentRecord.F53) <> CurrentRecord.F19 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_FORMULA_ONE_DIFF_THAN_TWO, [FRecNo, '17+18-34-40-46-53', 19]), ldMathErrors);
end;
// 6
if (CurrentRecord.F20 + CurrentRecord.F21 + CurrentRecord.F22 + CurrentRecord.F23) <> CurrentRecord.F19 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_SUM_ONE_DIFF_THAN_TWO, [FRecNo, '20-23', 19]), ldMathErrors);
end;
// 7
if CurrentRecord.F24 > CurrentRecord.F17 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 24, 17]), ldMathErrors);
end;
if CurrentRecord.F25 > CurrentRecord.F18 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 25, 18]), ldMathErrors);
end;
if CurrentRecord.F26 > CurrentRecord.F19 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 26, 19]), ldMathErrors);
end;
// 8
Tmp := CurrentRecord.F17 + CurrentRecord.F18;
if CurrentRecord.F27 > Tmp then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_DIFF_THAN_SUM_TWO, [FRecNo, 27, '17-18']), ldMathErrors);
end;
if CurrentRecord.F28 > Tmp then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_DIFF_THAN_SUM_TWO, [FRecNo, 28, '17-18']), ldMathErrors);
end;
if CurrentRecord.F29 > Tmp then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_DIFF_THAN_SUM_TWO, [FRecNo, 29, '17-18']), ldMathErrors);
end;
if CurrentRecord.F31 > Tmp then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_DIFF_THAN_SUM_TWO, [FRecNo, 31, '17-18']), ldMathErrors);
end;
if CurrentRecord.F32 > Tmp then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_DIFF_THAN_SUM_TWO, [FRecNo, 32, '17-18']), ldMathErrors);
end;
if CurrentRecord.F33 > Tmp then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_DIFF_THAN_SUM_TWO, [FRecNo, 33, '17-18']), ldMathErrors);
end;
if CurrentRecord.F34 > Tmp then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_DIFF_THAN_SUM_TWO, [FRecNo, 34, '17-18']), ldMathErrors);
end;
if CurrentRecord.F35 > Tmp then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_DIFF_THAN_SUM_TWO, [FRecNo, 35, '17-18']), ldMathErrors);
end;
if CurrentRecord.F38 > Tmp then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_DIFF_THAN_SUM_TWO, [FRecNo, 38, '17-18']), ldMathErrors);
end;
if CurrentRecord.F39 > Tmp then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_DIFF_THAN_SUM_TWO, [FRecNo, 39, '17-18']), ldMathErrors);
end;
if CurrentRecord.F40 > Tmp then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_DIFF_THAN_SUM_TWO, [FRecNo, 40, '17-18']), ldMathErrors);
end;
if CurrentRecord.F41 > Tmp then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_DIFF_THAN_SUM_TWO, [FRecNo, 41, '17-18']), ldMathErrors);
end;
if CurrentRecord.F44 > Tmp then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_DIFF_THAN_SUM_TWO, [FRecNo, 44, '17-18']), ldMathErrors);
end;
if CurrentRecord.F45 > Tmp then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_DIFF_THAN_SUM_TWO, [FRecNo, 45, '17-18']), ldMathErrors);
end;
if CurrentRecord.F46 > Tmp then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_DIFF_THAN_SUM_TWO, [FRecNo, 46, '17-18']), ldMathErrors);
end;
if CurrentRecord.F47 > Tmp then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_DIFF_THAN_SUM_TWO, [FRecNo, 47, '17-18']), ldMathErrors);
end;
if CurrentRecord.F51 > Tmp then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_DIFF_THAN_SUM_TWO, [FRecNo, 51, '17-18']), ldMathErrors);
end;
if CurrentRecord.F52 > Tmp then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_DIFF_THAN_SUM_TWO, [FRecNo, 52, '17-18']), ldMathErrors);
end;
if CurrentRecord.F53 > Tmp then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_DIFF_THAN_SUM_TWO, [FRecNo, 53, '17-18']), ldMathErrors);
end;
if CurrentRecord.F54 > Tmp then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_DIFF_THAN_SUM_TWO, [FRecNo, 54, '17-18']), ldMathErrors);
end;
//9
if CurrentRecord.F32 > CurrentRecord.F27 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 32, 27]), ldMathErrors);
end;
if CurrentRecord.F33 > CurrentRecord.F27 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 33, 27]), ldMathErrors);
end;
if CurrentRecord.F34 > CurrentRecord.F27 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 34, 27]), ldMathErrors);
end;
if CurrentRecord.F35 > CurrentRecord.F27 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 35, 27]), ldMathErrors);
end;
if CurrentRecord.F38 > CurrentRecord.F28 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 38, 28]), ldMathErrors);
end;
if CurrentRecord.F39 > CurrentRecord.F28 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 39, 28]), ldMathErrors);
end;
if CurrentRecord.F40 > CurrentRecord.F28 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 40, 28]), ldMathErrors);
end;
if CurrentRecord.F41 > CurrentRecord.F28 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 41, 28]), ldMathErrors);
end;
if CurrentRecord.F44 > CurrentRecord.F29 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 44, 29]), ldMathErrors);
end;
if CurrentRecord.F45 > CurrentRecord.F29 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 45, 29]), ldMathErrors);
end;
if CurrentRecord.F46 > CurrentRecord.F29 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 46, 29]), ldMathErrors);
end;
if CurrentRecord.F47 > CurrentRecord.F29 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 47, 29]), ldMathErrors);
end;
if CurrentRecord.F51 > CurrentRecord.F31 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 51, 31]), ldMathErrors);
end;
if CurrentRecord.F52 > CurrentRecord.F31 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 52, 31]), ldMathErrors);
end;
if CurrentRecord.F53 > CurrentRecord.F31 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 53, 31]), ldMathErrors);
end;
if CurrentRecord.F54 > CurrentRecord.F31 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 54, 31]), ldMathErrors);
end;
//10
if CurrentRecord.F32 > CurrentRecord.F34 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 32, 34]), ldMathErrors);
end;
if CurrentRecord.F33 > CurrentRecord.F35 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 33, 35]), ldMathErrors);
end;
//11
if CurrentRecord.F38 > CurrentRecord.F40 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 38, 40]), ldMathErrors);
end;
if CurrentRecord.F39 > CurrentRecord.F41 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 39, 41]), ldMathErrors);
end;
//12
if CurrentRecord.F44 > CurrentRecord.F46 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 44, 46]), ldMathErrors);
end;
if CurrentRecord.F45 > CurrentRecord.F47 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 45, 47]), ldMathErrors);
end;
//13
if CurrentRecord.F51 > CurrentRecord.F53 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 51, 53]), ldMathErrors);
end;
if CurrentRecord.F52 > CurrentRecord.F54 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 52, 54]), ldMathErrors);
end;
//14
if CurrentRecord.F33 > CurrentRecord.F32 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 33, 32]), ldMathErrors);
end;
if CurrentRecord.F35 > CurrentRecord.F34 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 35, 34]), ldMathErrors);
end;
if CurrentRecord.F39 > CurrentRecord.F38 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 39, 38]), ldMathErrors);
end;
if CurrentRecord.F41 > CurrentRecord.F40 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 41, 40]), ldMathErrors);
end;
if CurrentRecord.F45 > CurrentRecord.F44 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 45, 44]), ldMathErrors);
end;
if CurrentRecord.F47 > CurrentRecord.F46 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 47, 46]), ldMathErrors);
end;
if CurrentRecord.F52 > CurrentRecord.F51 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 52, 51]), ldMathErrors);
end;
if CurrentRecord.F54 > CurrentRecord.F53 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 54, 53]), ldMathErrors);
end;
//15
if (CurrentRecord.F59 + CurrentRecord.F60 - CurrentRecord.F61 - CurrentRecord.F62) > CurrentRecord.F63 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_FORMULA_ONE_DIFF_THAN_TWO, [FRecNo, '59+60-61-62', 63]), ldMathErrors);
end;
//16
if CurrentRecord.F64 > CurrentRecord.F63 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 64, 63]), ldMathErrors);
end;
// 17
if (CurrentRecord.F65 + CurrentRecord.F66 + CurrentRecord.F67 + CurrentRecord.F68 <> CurrentRecord.F63) then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_SUM_ONE_DIFF_THAN_TWO, [FRecNo, '65-68', 63]), ldMathErrors);
end;
//18
if CurrentRecord.F59 > CurrentRecord.F12 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 59, 12]), ldMathErrors);
end;
if CurrentRecord.F60 > CurrentRecord.F12 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 60, 12]), ldMathErrors);
end;
if CurrentRecord.F61 > CurrentRecord.F12 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 61, 12]), ldMathErrors);
end;
if CurrentRecord.F62 > CurrentRecord.F12 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 62, 12]), ldMathErrors);
end;
if CurrentRecord.F63 > CurrentRecord.F12 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 63, 12]), ldMathErrors);
end;
if CurrentRecord.F64 > CurrentRecord.F12 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 64, 12]), ldMathErrors);
end;
if CurrentRecord.F65 > CurrentRecord.F12 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 65, 12]), ldMathErrors);
end;
if CurrentRecord.F66 > CurrentRecord.F12 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 66, 12]), ldMathErrors);
end;
if CurrentRecord.F67 > CurrentRecord.F12 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 67, 12]), ldMathErrors);
end;
if CurrentRecord.F68 > CurrentRecord.F12 then
begin
AddValidationResult(vrMainInvalid);
AddRecordStatus(Format(S_LOG_ONE_MORE_THAN_TWO, [FRecNo, 68, 12]), ldMathErrors);
end;
end;
//---------------------------------------------------------------------------
procedure TValidator.RelationValidateRecord(var CurrentRecord: TValuesRec);
begin
// Species relation check
if dmData.GetIntField(Format(S_DB_GET_SPECIES_RELATION,
[CurrentRecord.DamageSpeciesName, CurrentRecord.DamageReasonName])) <= 0 then
begin
AddValidationResult(vrRelationInvalid);
AddRecordStatus(Format(S_LOG_NO_SPECIES_RELATION, [FRecNo]), ldRelationErrors);
end;
case CurrentRecord.DamageReasonID of
881, 882, 883, 870, 871, 872, 873, 874, 875:
if CurrentRecord.F10 <> CurrentRecord.ReportYear then
begin
AddValidationResult(vrRelationInvalid);
AddRecordStatus(Format(S_LOG_NO_CAUSE_RELATION, [FRecNo]), ldRelationErrors);
end;
821, 822, 823:
if CurrentRecord.F10 >= CurrentRecord.ReportYear then
begin
AddValidationResult(vrRelationInvalid);
AddRecordStatus(Format(S_LOG_NO_CAUSE_RELATION, [FRecNo]), ldRelationErrors);
end;
851, 854, 856, 863, 864, 865:
if (CurrentRecord.F10 > CurrentRecord.ReportYear - 1) or (CurrentRecord.F10
< CurrentRecord.ReportYear - 3) then
begin
AddValidationResult(vrRelationInvalid);
AddRecordStatus(Format(S_LOG_NO_CAUSE_RELATION, [FRecNo]), ldRelationErrors);
end;
852, 855, 857, 866, 867, 868:
if (CurrentRecord.F10 > CurrentRecord.ReportYear - 4) or (CurrentRecord.F10
< CurrentRecord.ReportYear - 10) then
begin
AddValidationResult(vrRelationInvalid);
AddRecordStatus(Format(S_LOG_NO_CAUSE_RELATION, [FRecNo]), ldRelationErrors);
end;
853, 858, 869:
if (CurrentRecord.F10 > CurrentRecord.ReportYear - 10) then
begin
AddValidationResult(vrRelationInvalid);
AddRecordStatus(Format(S_LOG_NO_CAUSE_RELATION, [FRecNo]), ldRelationErrors);
end;
end;
end;
//---------------------------------------------------------------------------
procedure TValidator.StringValidateField(var Field: AnsiString; var FieldID: Integer;
const Dict: TDictionary; const Prompt: AnsiString;
const RelationID: Integer = 0);
var
CatalogRecord: TCatalogRecord;
Magic: AnsiString;
WordIndex: Integer;
begin
if Dict.ForceSkip then
begin
AddValidationResult(vrSkip);
Exit;
end;
// Empty string - ask to replace and not remember
if Trim(Field) = '' then
begin
case ShowEdit(Field, Prompt, Dict) of
srReplace:
begin
Field := frmEdit.CurrentText;
FieldID := frmEdit.CurrentIndex;
end;
srForceSkip:
begin
AddValidationResult(vrSkip);
Dict.ForceSkip := True;
end;
srSkip:
AddValidationResult(vrSkip);
srStop:
AddValidationResult(vrStop);
end;
Exit;
end;
WordIndex := Dict.Validate(Field, RelationID);
if WordIndex <> -1 then
// Word is correct and full-valid
FieldID := WordIndex
else
begin
// Found in dictionary - autoreplace, log only
if Dict.FindRecord(Field, RelationID, CatalogRecord) then
begin
AddValidationResult(vrStringInvalid);
AddRecordStatus(Format(S_LOG_REPLACE_FROM_DICTIONARY, [FRecNo, CatalogRecord.NewWord, Field]), ldDictReplaces);
end
// Not found in dictionary - ask to replace, remember and log
else
begin
// here ask...
case ShowEdit(Field, Prompt, Dict) of
srReplace:
begin
// ...here remember...
CatalogRecord.OldWord := Field;
CatalogRecord.NewWord := frmEdit.CurrentText;
CatalogRecord.NewIndex := frmEdit.CurrentIndex;
CatalogRecord.RelationID := RelationID;
Dict.WriteRecord(CatalogRecord);
// ...here log...
AddValidationResult(vrStringInvalid);
AddRecordStatus(Format(S_LOG_REPLACE_FROM_DICTIONARY, [FRecNo, CatalogRecord.NewWord, Field]), ldDictReplaces);
// ...here replace
Field := frmEdit.cmbSynonim.Text;
FieldID := frmEdit.CurrentIndex;
end;
srStop:
begin
AddValidationResult(vrStop);
Exit;
end;
srSkip:
begin
AddValidationResult(vrSkip);
Exit;
end;
srForceSkip:
begin
AddValidationResult(vrSkip);
Dict.ForceSkip := True;
end;
end;
end;
// Some magic to set new word into variable
FieldID := CatalogRecord.NewIndex;
Magic := CatalogRecord.NewWord;
Field := Magic;
end;
end;
//---------------------------------------------------------------------------
procedure TValidator.StringValidateRecord(var CurrentRecord: TValuesRec);
var
Prompt: AnsiString;
begin
// LocalForestries - validate always
Prompt := Format('%s%s%s: "%s"', [ARR_FIELD_NAMES[2], S_EDIT_PROMPT, ARR_FIELD_NAMES[1], CurrentRecord.ForestryName]);
StringValidateField(CurrentRecord.LocalForestryName, CurrentRecord.LocalForestryID, DictLocalForestries, Prompt, CurrentRecord.ForestryID);
if vrStop in FValidationResult then
Exit;
// LanduseName - validate always
Prompt := Format('%s%s%s: "%s"', [ARR_FIELD_NAMES[5], S_EDIT_PROMPT, ARR_FIELD_NAMES[6], CurrentRecord.DefenseCategoryName]);
StringValidateField(CurrentRecord.LanduseName, CurrentRecord.LanduseID, DictLanduse, Prompt);
if vrStop in FValidationResult then
Exit;
// DefenseCategoryName - validate only if LanduseID <> 2 or if
// non-empty for LaduseID = 2
// wherein, if result (DefenseCategoryID) = 120 some next fields must be 0
if (CurrentRecord.LanduseID <> 2) or ((CurrentRecord.LanduseID = 2) and
(CurrentRecord.DefenseCategoryName <> '')) then
begin
StringValidateField(CurrentRecord.DefenseCategoryName, CurrentRecord.DefenseCategoryID, DictProtectCategory, ARR_FIELD_NAMES[6]);
if vrStop in FValidationResult then
Exit;
if CurrentRecord.DefenseCategoryID = 120 then
begin
CurrentRecord.F27 := 0;
CurrentRecord.F32 := 0;
CurrentRecord.F33 := 0;
CurrentRecord.F34 := 0;
CurrentRecord.F35 := 0;
CurrentRecord.F36 := 0;
CurrentRecord.F37 := 0;
end;
end;
// MainSpeciesName - validate always
Prompt := Format('%s%s%s: "%s"', [ARR_FIELD_NAMES[7], S_EDIT_PROMPT, ARR_FIELD_NAMES[8], CurrentRecord.DamageSpeciesName]);
StringValidateField(CurrentRecord.MainSpeciesName, CurrentRecord.MainSpeciesID, DictSpecies, Prompt);
if vrStop in FValidationResult then
Exit;
// DamageSpeciesName - validate always
Prompt := Format('%s%s%s: "%s"', [ARR_FIELD_NAMES[8], S_EDIT_PROMPT, ARR_FIELD_NAMES[7], CurrentRecord.MainSpeciesName]);
StringValidateField(CurrentRecord.DamageSpeciesName, CurrentRecord.DamageSpeciesID, DictSpecies, Prompt);
if vrStop in FValidationResult then
Exit;
// DamageReasonName - validate always
Prompt := Format('%s%s%s: "%s"', [ARR_FIELD_NAMES[9], S_EDIT_PROMPT, ARR_FIELD_NAMES[58], CurrentRecord.PestName]);
StringValidateField(CurrentRecord.DamageReasonName, CurrentRecord.DamageReasonID, DictDamage, Prompt);
if vrStop in FValidationResult then
Exit;
// PestName - validate if non-empty and if at least one of some fields is non-zero
// else result (PestID) must be 0 and PestStatus must be ''
if CurrentRecord.PestName <> '' then
begin
if (CurrentRecord.F59 = 0) and (CurrentRecord.F60 = 0) and (CurrentRecord.F61 = 0) and
(CurrentRecord.F62 = 0) and (CurrentRecord.F63 = 0) and (CurrentRecord.F64 = 0) and
(CurrentRecord.F65 = 0) and (CurrentRecord.F66 = 0) and (CurrentRecord.F67 = 0) and
(CurrentRecord.F68 = 0) then
begin
CurrentRecord.PestStatus := '';
CurrentRecord.PestID := 0;
end
else
begin
Prompt := Format('%s%s%s: "%s"', [ARR_FIELD_NAMES[58], S_EDIT_PROMPT, ARR_FIELD_NAMES[9],
CurrentRecord.DamageReasonName]);
StringValidateField(CurrentRecord.PestName, CurrentRecord.PestID, DictPest, Prompt);
if vrStop in FValidationResult then
Exit;
end;
end;
end;
//---------------------------------------------------------------------------
procedure TValidator.Validate(const RecNo: Integer; var CurrentRecord: TValuesRec);
begin
FValidationResult := [];
FRecordStatus := '';
FRecNo := RecNo;
StringValidateRecord(CurrentRecord);
CurrentRecord.ValidationResult := FValidationResult;
if vrStop in FValidationResult then
Exit;
RelationValidateRecord(CurrentRecord);
MathValidateRecord(CurrentRecord);
MathExtraValidateRecord(CurrentRecord);
CurrentRecord.ValidationResult := FValidationResult;
end;
end.
|
unit main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, Buttons,
ExtCtrls, Menus, DbCtrls, DBGrids, db, uPSUtils,
uPSComponent_Default, uPSComponent, uPSC_strutils, RxMemDS, LCLIntf;
type
{ TfrmMain }
TfrmMain = class(TForm)
btnAdd: TBitBtn;
btnEdit: TBitBtn;
btnDelete: TBitBtn;
btnClose: TBitBtn;
cbScriptCategory: TComboBox;
dbgridScripts: TDBGrid;
dlgOpen: TOpenDialog;
dlgSave: TSaveDialog;
dsScripts: TDatasource;
Scripts: TRxMemoryData;
ScriptsCategory: TStringField;
ScriptsDescription: TStringField;
ScriptsScript1: TMemoField;
ScriptsScriptIndex1: TLongintField;
ScriptsScriptName: TStringField;
ScriptsScriptType: TLongintField;
lblScriptCategory: TLabel;
MenuItem1: TMenuItem;
miOptions: TMenuItem;
miLoadFromFile: TMenuItem;
miSaveToFile: TMenuItem;
MenuItem9: TMenuItem;
miClearClipbrd: TMenuItem;
miAbout: TMenuItem;
MenuItem2: TMenuItem;
miExit: TMenuItem;
MenuItem4: TMenuItem;
miScripts: TMenuItem;
miEditScripts: TMenuItem;
popupClipManMenu: TPopupMenu;
PSImport_Classes1: TPSImport_Classes;
PSImport_DateUtils1: TPSImport_DateUtils;
PSImport_StrUtils1: TPSImport_StrUtils;
RuntimeScript: TPSScript;
ScriptsTestData1: TMemoField;
tryicnClipman: TTrayIcon;
BalloonTimer: TTimer;
btnHelp: TBitBtn;
miHelp: TMenuItem;
procedure btnAddClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
procedure btnEditClick(Sender: TObject);
procedure btnHelpClick(Sender: TObject);
procedure cbScriptCategoryChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure miAboutClick(Sender: TObject);
procedure miClearClipbrdClick(Sender: TObject);
procedure miLoadFromFileClick(Sender: TObject);
procedure miExitClick(Sender: TObject);
procedure miEditScriptsClick(Sender: TObject);
procedure miOptionsClick(Sender: TObject);
procedure miSaveToFileClick(Sender: TObject);
procedure popupClipManMenuPopup(Sender: TObject);
procedure popupScriptsClick(Sender: TObject);
procedure RuntimeScriptAfterExecute(Sender: TPSScript);
procedure RuntimeScriptCompile(Sender: TPSScript);
procedure RuntimeScriptExecute(Sender: TPSScript);
procedure UpdateScriptNames;
function ShowSaveDialog:string;
function ShowOpenDialog:string;
function IfFileExists(Filename:string):boolean;
procedure ShowMessageDialog(Msg:string);
function InputBoxDialog(Title, Msg, DefaultText :String):string;
function ConfirmationDialog(Msg:string):boolean;
procedure ErrorMessageDialog(Msg:string);
procedure BalloonTimerTimer(Sender: TObject);
procedure populateCategoryCombo(Strings:TStrings);
procedure RefreshCombo;
private
{ private declarations }
ScriptsDAT:String;
ScriptInProgress:boolean;
WindowBeingShown:boolean;
public
{ public declarations }
Clippy:TStringList;
end;
var
frmMain: TfrmMain;
implementation
uses LCLType, Clipbrd, editscript, aboutform, fpimage, FPDitherer,
FPQuantizer, FPReadBMP, FPWriteBMP, options, LResources, EngLangRes;
{$R *.lfm}
{ TfrmMain }
procedure TfrmMain.btnCloseClick(Sender: TObject);
begin
Hide;
end;
procedure TfrmMain.populateCategoryCombo(Strings:TStrings);
var Category:String;
FilterState:Boolean;
begin
Scripts.DisableControls;
FilterState := Scripts.Filtered;
Scripts.Filtered := False;
Strings.Clear;
Scripts.First;
while not Scripts.EOF do begin
Category := Scripts.FieldByName('category').AsString;
if (Category <> '') and (Strings.IndexOf(Category) = -1)
then Strings.Add(Category);
Scripts.Next;
end;
Scripts.Filtered := FilterState;
Scripts.EnableControls;
end;
procedure TfrmMain.btnEditClick(Sender: TObject);
var ScriptIndex:Integer;
ScriptCategory:String;
begin
if Scripts.RecordCount > 0 then begin
//need to get the Index of the currently selected script (or the one doubleclicked upon)
ScriptCategory := cbScriptCategory.Text;
ScriptIndex := Scripts.FieldByName('ScriptIndex').asInteger;
frmScriptEditor.ScriptID := ScriptIndex;
frmScriptEditor.edScriptName.Text := Scripts.FieldByName('ScriptName').asString;
frmScriptEditor.cbScriptCategory.Text := Scripts.FieldByName('Category').asString;
frmScriptEditor.edDescription.Text := Scripts.FieldByName('Description').asString;
frmScriptEditor.synmemCodeEditor.Text := Scripts.FieldByName('Script').asString;
frmScriptEditor.memoSource.Text := Scripts.FieldByName('TestData').asString;
frmScriptEditor.SetupTargetTestAreas;
populateCategoryCombo(frmScriptEditor.cbScriptCategory.Items);
if frmScriptEditor.ShowModal = mrOK then begin
//need to find the original in case the search
//for a scriptname conflict on the edit page moved the database cursor
Scripts.Locate('ScriptIndex',frmScriptEditor.ScriptID,[]);
Scripts.Edit;
Scripts.FieldByName('ScriptName').asString := frmScriptEditor.edScriptName.Text;
Scripts.FieldByName('Category').asString := frmScriptEditor.cbScriptCategory.Text;
Scripts.FieldByName('Script').asString := frmScriptEditor.synmemCodeEditor.Text;
Scripts.FieldByName('TestData').AsString := frmScriptEditor.memoSource.Lines.Text;
Scripts.FieldByName('Description').asString := frmScriptEditor.edDescription.Text;
Scripts.Post;
end;
end;
Scripts.SaveToFile(ScriptsDAT);
RefreshCombo;
cbScriptCategory.Text := ScriptCategory;
UpdateScriptNames;
//relocate the script we edited!
Scripts.Locate('ScriptIndex',ScriptIndex,[]);
end;
procedure TfrmMain.btnHelpClick(Sender: TObject);
var clippyHelpFile:String;
begin
clippyHelpFile := IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName))
+IncludeTrailingPathDelimiter('Other')+IncludeTrailingPathDelimiter('Help')+'ClipmanHelp.html';
if FileExists(clippyHelpFile) then begin
OpenURL(clippyHelpFile);
end else begin
end;
end;
procedure TfrmMain.cbScriptCategoryChange(Sender: TObject);
begin
if cbScriptCategory.Text <> '' then begin
Scripts.Filter := 'Category = '+#39+cbScriptCategory.Text+#39;
Scripts.Filtered := True;
end else begin
Scripts.Filtered := False;
Scripts.Filter := '';
end;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
ScriptsDAT := IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName))
+IncludeTrailingPathDelimiter('Data')+'Scripts.DAT';
Scripts.Active := True;
if FileExists(ScriptsDAT) then begin
Scripts.LoadFromFile(ScriptsDAT);
end;
UpdateScriptNames;
end;
procedure TfrmMain.RefreshCombo;
begin
populateCategoryCombo(cbScriptCategory.Items);
cbScriptCategory.Items.Insert(0,'');
end;
procedure TfrmMain.FormShow(Sender: TObject);
begin
RefreshCombo;
Scripts.First;
end;
procedure TfrmMain.btnDeleteClick(Sender: TObject);
var ScriptName:String;
ScriptCategory:String;
begin
ScriptCategory := cbScriptCategory.Text;
if Scripts.RecordCount > 0 then begin
ScriptName := Scripts.FieldByName('ScriptName').asString;
if (MessageDlg(msgConfirmDelete+' "'+ ScriptName+'"?', mtConfirmation, [mbYes, mbNo], 0) = mrYes) then begin
Scripts.Delete;
end;
end;
//deleting should position us on the next in the list/grid
ScriptName := Scripts.FieldByName('ScriptName').asString;
Scripts.SaveToFile(ScriptsDAT);
RefreshCombo;
cbScriptCategory.Text := ScriptCategory;
UpdateScriptNames;
//now we refind the "Next" one - just looks cleaner than going to the start of the list again
Scripts.Locate('ScriptName', ScriptName, [locaseinsensitive]);
end;
procedure TfrmMain.btnAddClick(Sender: TObject);
var idx:integer;
ScriptName:String;
HashedScriptName:LongInt;
ScriptCategory:String;
begin
idx := 1;
repeat
ScriptName := 'NewScript'+IntToStr(idx);
inc(idx);
until not Scripts.Locate('ScriptName',ScriptName,[locaseinsensitive]);
ScriptCategory := cbScriptCategory.Text;
frmScriptEditor.edScriptName.Text := ScriptName;
frmScriptEditor.edDescription.Text := '';
populateCategoryCombo(frmScriptEditor.cbScriptCategory.Items);
//assume that if we have the filter enabled then we want to add to that category
frmScriptEditor.cbScriptCategory.Text := ScriptCategory;
frmScriptEditor.SetupScriptArea;
frmScriptEditor.SetupSourceTestAreas;
frmScriptEditor.SetupTargetTestAreas;
if frmScriptEditor.ShowModal = mrOK then begin
ScriptName := frmScriptEditor.edScriptName.Text;
//ensure it's got a unique index!
HashedScriptName := Hash(Scriptname);
while Scripts.Locate('ScriptIndex',HashedScriptName,[]) do begin
HashedScriptName := Hash(Scriptname) + 1;
end;
Scripts.Append;
Scripts.FieldByName('ScriptIndex').asInteger := HashedScriptName;
Scripts.FieldByName('ScriptName').asString := Scriptname;
Scripts.FieldByName('Category').asString := frmScriptEditor.cbScriptCategory.Text;
Scripts.FieldByName('Description').asString := frmScriptEditor.edDescription.Text;
Scripts.FieldByName('Script').AsString := frmScriptEditor.synmemCodeEditor.Lines.Text;
Scripts.FieldByName('TestData').AsString := frmScriptEditor.memoSource.Lines.Text;
Scripts.FieldByName('ScriptType').AsInteger := frmScriptEditor.cbScriptType.ItemIndex; //for potential different types of clipboard maniuplation in future
Scripts.Post;
end;
Scripts.SaveToFile(ScriptsDAT);
RefreshCombo;
cbScriptCategory.Text := ScriptCategory;
UpdateScriptNames;
//find the one we've just added
Scripts.Locate('ScriptIndex',HashedScriptName,[]);
end;
procedure TfrmMain.miAboutClick(Sender: TObject);
begin
if WindowBeingShown then Exit;
WindowBeingShown := True;
frmAbout.ShowModal;
WindowBeingShown := False;
end;
procedure TfrmMain.miClearClipbrdClick(Sender: TObject);
begin
//this doesn't always work
Clipboard.Clear;
//so lets try this too!
Clipboard.AsText := '';
tryicnClipman.BalloonTitle := '';
tryicnClipman.BalloonHint := msgClipboardCleared;
tryicnClipman.ShowBalloonHint;
BalloonTimer.Interval := Trunc(frmOptions.spineditPeriod.Value * 1000);
BalloonTimer.Enabled:=true;
end;
procedure TfrmMain.miLoadFromFileClick(Sender: TObject);
var Filename, FileExt:String;
Image:TImage;
procedure LoadFileAsText(Filename:String);
var
T:TStringList;
begin
T := TStringList.Create;
T.LoadFromFile(Filename);
Clipboard.AsText:= T.Text;
T.Free;
end;
begin
if WindowBeingShown then Exit;
WindowBeingShown := True;
dlgOpen.FileName:='';
dlgOpen.Title:= msgLoadFileTitle;
dlgOpen.Filter := msgLoadFiles;
dlgOpen.FilterIndex := 1;
if dlgOpen.Execute then begin
Filename := dlgOpen.FileName;
FileExt := ExtractFileExt(dlgOpen.FileName);
if (CompareText(FileExt,'.txt') = 0) or (CompareText(FileExt,'.txt') = 0) or (CompareText(FileExt,'.txt') = 0) then begin
LoadFileAsText(Filename);
end else begin
if (CompareText(FileExt,'.bmp') = 0) or (CompareText(FileExt,'.jpg') = 0) or (CompareText(FileExt,'.img') = 0) then begin
Image := TImage.Create(self);
Image.Picture.LoadFromFile(Filename);
Clipboard.Assign(Image.picture.bitmap);
Image.Free;
end else begin
if MessageDlg(msgFormatNotRecognisedTitle, msgFormatNotRecognised+#13#10+MsgFormatNotRecognisedTryToLoad, mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin
LoadFileAsText(Filename);
end;
end;
end;
end;
WindowBeingShown := False;
end;
procedure ReduceBitmapColors(BMPFile:String);
var
SourceBitmap, TargetBitmap: TFPMemoryImage;
FPMedianCutQuantizer : TFPMedianCutQuantizer;
FPPalette : TFPPalette;
FPFloydSteinbergDitherer:TFPFloydSteinbergDitherer;
ImageReader : TFPReaderBMP;
ImageWriter : TFPWriterBMP;
begin
if FileExists(BMPFile) then begin
SourceBitmap := TFPMemoryImage.Create(0,0);
TargetBitmap := TFPMemoryImage.Create(0,0);
ImageReader := TFPReaderBMP.Create;
ImageWriter := TFPWriterBMP.create;
try
SourceBitmap.LoadFromFile(BMPFile);
FPMedianCutQuantizer := TFPMedianCutQuantizer.Create;
FPMedianCutQuantizer.Add(SourceBitmap);
FPPalette := FPMedianCutQuantizer.Quantize;
FPFloydSteinbergDitherer := TFPFloydSteinbergDitherer.Create(FPPalette);
FPFloydSteinbergDitherer.Dither(SourceBitmap, TargetBitmap);
ImageWriter.BitsPerPixel:=8;
TargetBitmap.SaveToFile(BMPFile, ImageWriter);
finally
SourceBitmap.Free;
TargetBitmap.Free;
FPMedianCutQuantizer.Free;
FPFloydSteinbergDitherer.Free;
ImageReader.Free;
ImageWriter.Free;
end;
end;
end;
procedure TfrmMain.miExitClick(Sender: TObject);
begin
Close;
end;
procedure TfrmMain.UpdateScriptNames;
var NewMenuItem:TMenuItem;
SubMenu:TMenuItem;
ScriptIndex:Integer;
Category:String;
LastCategory:String;
FilterState:Boolean;
begin
FilterState := Scripts.Filtered;
if Filterstate then begin
Scripts.Filtered := False;
end;
ScriptIndex := Scripts.FieldByName('ScriptIndex').asInteger;
Scripts.SortOnFields('Category;ScriptName');
LastCategory := '';
miScripts.Clear;
Scripts.First;
while not Scripts.EOF do begin
//need to create a category submenu if this isn't blank
Category := Scripts.FieldByName('Category').asString;
if Category <> '' then begin
if Category <> LastCategory then begin
//create new submenu
SubMenu := TMenuItem.Create(miScripts);
SubMenu.Caption := Category;
miScripts.Add(SubMenu);
end;
NewMenuItem := TMenuItem.Create(SubMenu);
NewMenuItem.Caption := Scripts.FieldByName('ScriptName').asString;;
NewMenuItem.Tag := Scripts.FieldByName('ScriptIndex').asInteger;
NewMenuItem.Hint := Scripts.FieldByName('Description').asString;
NewMenuItem.OnClick := @popupScriptsClick;
SubMenu.Add(NewMenuItem);
end else begin
NewMenuItem := TMenuItem.Create(miScripts);
NewMenuItem.Caption := Scripts.FieldByName('ScriptName').asString;;
NewMenuItem.Tag := Scripts.FieldByName('ScriptIndex').asInteger;
NewMenuItem.Hint := Scripts.FieldByName('Description').asString;
NewMenuItem.OnClick := @popupScriptsClick;
miScripts.Add(NewMenuItem);
end;
Scripts.Next;
LastCategory := Category;
end;
Scripts.Locate('ScriptIndex',ScriptIndex,[]);
if FilterState then begin
Scripts.Filtered := True;
end;
end;
procedure TfrmMain.miEditScriptsClick(Sender: TObject);
begin
if WindowBeingShown then Exit;
WindowBeingShown := True;
//make sure filter is turned off before displaying the window!
Scripts.Filtered := False;
Scripts.Filter := '';
UpdateScriptNames;
ShowModal;
WindowBeingShown := False;
//make sure filter is turned off again after window closes!
Scripts.Filtered := False;
Scripts.Filter := '';
end;
procedure TfrmMain.miOptionsClick(Sender: TObject);
begin
if WindowBeingShown then Exit;
WindowBeingShown := True;
frmOptions.ShowModal;
WindowBeingShown := False;
end;
procedure TfrmMain.miSaveToFileClick(Sender: TObject);
var FileExt:String;
Filename:String;
procedure SaveClipboardAsText(Filename:String);
var
T:TStringList;
begin
T := TStringList.Create;
T.Text := Clipboard.AsText;
T.SaveToFile(Filename);
T.Free;
end;
procedure SaveClipboardAsImage(Filename:String; FileExt:String; LimitColors:Boolean);
var cfPng:TClipboardFormat;
cfJpg:TClipboardFormat;
strm:TMemoryStream;
Image:TImage;
// SupportedFormats:TStringList;
begin
{SupportedFormats := TStringList.Create;
Clipboard.SupportedFormats(SupportedFormats); //see what's there
ShowMessage(SupportedFormats.Text);
SupportedFormats.Free; }
Image := TImage.Create(Self);
cfPng:=RegisterClipboardFormat('image/png');
cfJpg:=RegisterClipboardFormat('image/jpeg');
strm:=TMemoryStream.create;
if Clipboard.HasFormat(cf_bitmap) then begin //this doesn't appear to work in windows
Clipboard.GetFormat(cf_bitmap,strm);
strm.Position:=0;
Image.Picture.LoadFromStream(strm);
end else begin
if Clipboard.HasFormat(cfPng) then begin
Clipboard.GetFormat(cfPng,strm);
strm.Position:=0;
Image.Picture.LoadFromStream(strm);
end else begin
if Clipboard.HasFormat(cfJpg) then begin
Clipboard.GetFormat(cfJpg,strm);
strm.Position:=0;
Image.Picture.LoadFromStream(strm);
end else begin
try
Image.Picture.LoadFromClipboardFormat(cf_bitmap); //but this does and on Linux we've already taken a different route
except
MessageDlg(msgImageFormatNotSupported, mtInformation, [mbOK] ,0);
Exit;
end;
end;
end;
end;
strm.free;
Image.Picture.SaveToFile(Filename, FileExt);
Image.Free;
if LimitColors then begin
ReduceBitmapColors(Filename);
end;
end;
begin
if WindowBeingShown then Exit;
WindowBeingShown := True;
dlgSave.FileName:='';
if Clipboard.HasPictureFormat then begin
dlgSave.Title:= msgSaveImgClipboardTitle;
dlgSave.Filter := msgSaveImgClipboardFilter;
end else begin
dlgSave.Title := msgSaveTxtClipboardTitle;
dlgSave.Filter := msgSaveTxtClipboardFilter ;
end;
dlgSave.FilterIndex := 1;
if dlgSave.Execute then begin
//Save Clipboard contents to filetype
Filename := dlgSave.FileName;
if Clipboard.HasPictureFormat then begin
if ((CompareText(ExtractFileExt(Filename),'.bmp') = 0)
or (CompareText(ExtractFileExt(FileName),'.jpg') = 0)
or (CompareText(ExtractFileExt(FileName),'.png') = 0)
or (CompareText(ExtractFileExt(FileName),'.xpm') = 0)
) then begin
FileExt := ExtractFileExt(Filename);
end else begin
case dlgSave.FilterIndex of
1,4 : FileExt := '.bmp';
2 : FileExt := '.jpg';
3 : FileExt := '.png';
5 : FileExt := '.xpm';
end;
Filename := ChangeFileExt(Filename, FileExt);
end;
SaveClipboardAsImage(FileName, FileExt, dlgSave.FilterIndex = 4);
end else begin
if ((CompareText(ExtractFileExt(Filename),'.txt') = 0)
or (CompareText(ExtractFileExt(FileName),'.csv') = 0)
or (CompareText(ExtractFileExt(FileName),'.tab') = 0)) then begin
FileExt := ExtractFileExt(Filename);
end else begin
case dlgSave.FilterIndex of
1 : FileExt := '.txt';
2 : FileExt := '.csv';
3 : FileExt := '.tab';
end;
Filename := ChangeFileExt(Filename, FileExt);
end;
SaveClipboardAsText(FileName);
end;
end;
WindowBeingShown := False;
end;
procedure TfrmMain.popupClipManMenuPopup(Sender: TObject);
begin
//reserved for future use!!!
//check what's on the clipboard - if it's a bitmap then only enable the bitmapscripts (scripttype = 1)
//else if it's text then only scripts of scripttype = 0
end;
procedure TfrmMain.popupScriptsClick(Sender: TObject);
var ScriptMenuItem:TMenuItem;
ScriptIndex:Integer;
Compiled:boolean;
idx:integer;
begin
if WindowBeingShown then Exit;
WindowBeingShown := True;
if ScriptInProgress then exit;
ScriptInProgress := True;
BalloonTimer.Enabled:=False;
if Clipboard.HasFormat(cf_text) or (not (Clipboard.HasFormat(cf_bitmap) or Clipboard.HasFormat(cf_picture) or Clipboard.HasFormat(cf_metafilepict))) then begin
ScriptMenuItem := Sender as TMenuItem;
ScriptIndex := ScriptMenuItem.Tag;;
if Scripts.Locate('ScriptIndex',ScriptIndex,[]) then begin
RuntimeScript.Script.Text := Scripts.FieldByName('Script').asString;
Compiled := RuntimeScript.Compile;
if Compiled then begin
if not RuntimeScript.Execute
then MessageDlg(msgExecutionError, mtError, [mbOK], 0);
end else begin
for idx := 0 to RuntimeScript.CompilerMessageCount-1
do MessageDlg(msgErrorCompiling+':'+RuntimeScript.CompilerMessages[idx].MessageToString, mtError, [mbOK], 0);
end;
end;
end else begin
MessageDlg(msgClpbrdFrmtNotSpprtdForScriptsTitle, msgClpbrdFrmtNotSpprtdForScripts, mtInformation, [mbOK], 0);
end;
WindowBeingShown := False;
ScriptInProgress := False;
end;
procedure TfrmMain.RuntimeScriptAfterExecute(Sender: TPSScript);
var T:TStringList;
ScriptName:String;
begin
Clipboard.AsText := Clippy.Text;
Clippy.Free;
if frmOptions.chkbxShowBalloon.Checked then begin
ScriptName := Scripts.FieldByName('ScriptName').AsString;
tryicnClipman.BalloonTitle := msgScriptExecutedTitle +ScriptName+ msgScriptExecutedSuccess;
T := TStringList.Create;
T.Text := Clipboard.AsText;
if T.Count > 5 then begin
while T.Count > 5 do T.Delete(T.Count-1); //only show the 1st 5 lines
T.Add('...'); //indicate there's more!
end;
tryicnClipman.BalloonHint := T.Text;
T.Free;
tryicnClipman.ShowBalloonHint;
BalloonTimer.Interval := Trunc(frmOptions.spineditPeriod.Value * 1000);
BalloonTimer.Enabled:=true;
end;
end;
procedure TfrmMain.RuntimeScriptCompile(Sender: TPSScript);
begin
Clippy := TStringList.Create;
Clippy.Text := Clipboard.AsText;
Sender.AddRegisteredPTRVariable('Clippy','TStringList');
Sender.AddMethod(Self, @TfrmMain.ShowSaveDialog, 'function ShowSaveDialog:string;');
Sender.AddMethod(Self, @TfrmMain.ShowOpenDialog, 'function ShowOpenDialog:string;');
Sender.AddMethod(Self, @TfrmMain.IfFileExists, 'function IfFileExists(Filename:String):boolean;');
Sender.AddMethod(Self, @TfrmMain.ShowMessageDialog, 'procedure ShowMessage(Msg:string)');
Sender.AddMethod(Self, @TfrmMain.ErrorMessageDialog, 'procedure ErrorMessage(Msg:string)');
Sender.AddMethod(Self, @TfrmMain.ConfirmationDialog, 'function IsConfirmed(Msg:string):boolean;');
Sender.AddMethod(Self, @TfrmMain.InputBoxDialog, 'function InputBox(Title, Msg, DefaultText :String):string;');
end;
procedure TfrmMain.RuntimeScriptExecute(Sender: TPSScript);
begin
Sender.SetPointerToData('Clippy',@Clippy, Sender.FindNamedType('TStringList'));
end;
function TfrmMain.ShowSaveDialog:string;
begin
Result := '';
dlgSave.FilterIndex:=1;
dlgSave.Filter := msgAllFiles;
if dlgSave.Execute then begin
Result := dlgSave.FileName;
end;
end;
function TfrmMain.ShowOpenDialog: string;
begin
Result := '';
dlgOpen.FilterIndex:=1;
dlgOpen.Filter := msgAllFiles;
if dlgOpen.Execute then begin
Result := dlgOpen.FileName;
end;
end;
procedure TfrmMain.ShowMessageDialog(Msg:string);
begin
MessageDlg(Msg, mtInformation, [mbOK], 0);
end;
function TfrmMain.IfFileExists(Filename:string):boolean;
begin
Result := FileExists(Filename);
end;
procedure TfrmMain.ErrorMessageDialog(Msg:string);
begin
MessageDlg(Msg, mtError, [mbOK], 0);
end;
function TfrmMain.ConfirmationDialog(Msg:string):boolean;
begin
Result := MessageDlg(Msg, mtConfirmation, [mbYes, mbNo], 0) = mrYes;
end;
function TfrmMain.InputBoxDialog(Title, Msg, DefaultText :String):string;
begin
Result := InputBox(Title, Msg, DefaultText);
end;
procedure TfrmMain.BalloonTimerTimer(Sender: TObject);
begin
//a blank Balloonhint closes the hint window
tryicnClipman.BalloonHint :='';
tryicnClipman.ShowBalloonHint;
BalloonTimer.Enabled:=false;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 2015-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.JSON.Writers;
interface
{$SCOPEDENUMS ON}
uses
System.SysUtils, System.Classes, System.Generics.Collections, System.Types,
System.Rtti, System.JSON, System.JSON.Types, System.JSON.Readers;
type
/// <summary>
/// TJsonWriter state
/// </summary>
TJsonWriteState = (Error, Closed, &Object, &Array, &Constructor, &Property, Start);
/// <summary>
/// Base class that provides logic to serialize JSON data.
/// </summary>
TJsonWriter = class
protected type
/// <summary> States of the writer </summary>
TState = (Start, &Property, ObjectStart, &Object, ArrayStart, &Array, ConstructorStart, &Constructor, Closed, Error);
const
/// <summary> Template table with all posible states and their transitions for the token being written</summary>
StateArrayTemplate: array[0..7, 0..9] of TState = (
// Start // PropertyName // ObjectStart // Object // ArrayStart // Array // ConstructorStart // Constructor // Closed // Error
{None } (TState.Error , TState.Error , TState.Error , TState.Error , TState.Error , TState.Error , TState.Error , TState.Error , TState.Error , TState.Error ),
{StartObject } (TState.ObjectStart , TState.ObjectStart , TState.Error , TState.Error , TState.ObjectStart , TState.ObjectStart , TState.ObjectStart , TState.ObjectStart , TState.Error , TState.Error ),
{StartArray } (TState.ArrayStart , TState.ArrayStart , TState.Error , TState.Error , TState.ArrayStart , TState.ArrayStart , TState.ArrayStart , TState.ArrayStart , TState.Error , TState.Error ),
{StartConstructor } (TState.ConstructorStart, TState.ConstructorStart, TState.Error , TState.Error , TState.ConstructorStart, TState.ConstructorStart, TState.ConstructorStart, TState.ConstructorStart, TState.Error , TState.Error ),
{Property } (TState.Property , TState.Error , TState.Property , TState.Property , TState.Error , TState.Error , TState.Error , TState.Error , TState.Error , TState.Error ),
{Comment } (TState.Start , TState.Property , TState.ObjectStart , TState.Object , TState.ArrayStart , TState.Array , TState.Constructor , TState.Constructor , TState.Error , TState.Error ),
{Raw } (TState.Start , TState.Property , TState.ObjectStart , TState.Object , TState.ArrayStart , TState.Array , TState.Constructor , TState.Constructor , TState.Error , TState.Error ),
{Value } (TState.Start , TState.Object , TState.Error , TState.Error , TState.Array , TState.Array , TState.Constructor , TState.Constructor , TState.Error , TState.Error )
);
private
FStack: TList<TJsonPosition>;
FCloseOutput: Boolean;
FEmptyValueHandling: TJsonEmptyValueHandling;
FDateTimeZoneHandling: TJsonDateTimeZoneHandling;
class var StateArray: array of array of TState;
class var FRttiCtx: TRTTIContext;
procedure AutoCompleteAll;
procedure AutoCompleteClose(ContainerType: TJsonContainerType);
function GetCloseTokenForType(ContainerType: TJsonContainerType): TJsonToken;
function Peek: TJsonContainerType;
procedure Push(Value: TJsonContainerType);
function Pop: TJsonContainerType;
procedure WriteConstructorDate(const Reader: TJsonReader);
function GetContainerPath: string;
function GetPath: string;
function GetWriteState: TJsonWriteState;
class procedure BuildStateArray;
protected
/// <summary> Current writer state </summary>
FCurrentState: TState;
/// <summary> Current Position </summary>
FCurrentPosition: TJsonPosition;
/// <summary> Updates the current state with the token begin written </summary>
procedure AutoComplete(TokenBeginWritten: TJsonToken);
function GetTop: Integer;
function GetTopContainer: TJsonContainerType;
/// <summary> Get the position based on the depth </summary>
function GetPosition(ADepth: Integer): TJsonPosition;
/// <summary> Updates the position </summary>
procedure UpdateScopeWithFinishedValue;
/// <summary> Write the end token based on container </summary>
procedure InternalWriteEnd(Container: TJsonContainerType);
/// <summary> Writes a property name </summary>
procedure InternalWritePropertyName(const Name: string);
/// <summary> Writes an start token based on the current container </summary>
procedure InternalWriteStart(Token: TJsonToken; Container: TJsonContainerType);
/// <summary> Writes an start token </summary>
procedure InternalWriteValue(Token: TJsonToken);
/// <summary> Writes a comment </summary>
procedure InternalWriteComment;
/// <summary> Sets the internal state </summary>
procedure SetWriteState(Token: TJsonToken; const Value: TValue);
/// <summary> Write the end token based on container </summary>
procedure WriteEnd(ContainerType: TJsonContainerType); overload;
/// <summary> Write the end token based on the token, this method does not updates the internal state </summary>
procedure WriteEnd(const Token: TJsonToken); overload; virtual;
/// <summary> Implementation for WriteToken </summary>
procedure WriteToken(const Reader: TJsonReader; WriteChildren, WriteDateConstructorAsDate: Boolean); overload;
/// <summary> Implementation for WriteToken </summary>
procedure WriteToken(const Reader: TJsonReader; InitialDepth: Integer;
WriteChildren, WriteDateConstructorAsDate: Boolean); overload;
/// <summary> Writes a TValue </summary>
class procedure WriteValue(const Writer: TJsonWriter; const Value: TValue); overload;
/// <summary> Checks whether the token is an end token </summary>
class function IsEndToken(Token: TJsonToken): Boolean;
/// <summary> Checks whether the token is an start token </summary>
class function IsStartToken(Token: TJsonToken): Boolean;
/// <summary> Event called before write a token </summary>
procedure OnBeforeWriteToken(TokenBeginWriten: TJsonToken); virtual;
constructor Create;
public
class constructor Create;
destructor Destroy; override;
/// <summary> Resets the internal state allowing write from the begining </summary>
procedure Rewind; virtual;
/// <summary> Closes the Writer </summary>
procedure Close; virtual;
/// <summary> Flushes the content if needed </summary>
procedure Flush; virtual;
/// <summary> Writes a comment</summary>
procedure WriteComment(const Comment: string); virtual;
/// <summary> Writes the start of a json object </summary>
procedure WriteStartObject; virtual;
/// <summary> Writes the end of a json object </summary>
procedure WriteEndObject; virtual;
/// <summary> Writes the start of a json array </summary>
procedure WriteStartArray; virtual;
/// <summary> Writes the end of a json array </summary>
procedure WriteEndArray; virtual;
/// <summary> Writes the start of a javascript constructor </summary>
procedure WriteStartConstructor(const Name: string); virtual;
/// <summary> Writes the end of a javascript constructor </summary>
procedure WriteEndConstructor; virtual;
/// <summary> Writes a property name </summary>
procedure WritePropertyName(const Name: string); overload; virtual;
/// <summary> Writes the end token for the current container (object, array or constructor) </summary>
procedure WriteEnd; overload; virtual;
/// <summary> Writes a null value </summary>
procedure WriteNull; virtual;
/// <summary> Writes a raw json, it does not update the internal state </summary>
procedure WriteRaw(const Json: string); virtual;
/// <summary> Writes a raw json, it updates the internal state </summary>
procedure WriteRawValue(const Json: string); virtual;
/// <summary> Writes an undefined value </summary>
procedure WriteUndefined; virtual;
/// <summary> Writes the token/s given by the Reader </summary>
procedure WriteToken(const Reader: TJsonReader); overload;
/// <summary> Writes the token/s given by the Reader </summary>
procedure WriteToken(const Reader: TJsonReader; WriteChildren: Boolean); overload;
/// <summary> Writes an string value </summary>
procedure WriteValue(const Value: string); overload; virtual;
/// <summary> Writes an Integer value </summary>
procedure WriteValue(Value: Integer); overload; virtual;
/// <summary> Writes an UInt32 value </summary>
procedure WriteValue(Value: UInt32); overload; virtual;
/// <summary> Writes an Int64 value </summary>
procedure WriteValue(Value: Int64); overload; virtual;
/// <summary> Writes an UInt64 value value </summary>
procedure WriteValue(Value: UInt64); overload; virtual;
/// <summary> Writes a Single value </summary>
procedure WriteValue(Value: Single); overload; virtual;
/// <summary> Writes a Double value </summary>
procedure WriteValue(Value: Double); overload; virtual;
/// <summary> Writes an Extended value </summary>
procedure WriteValue(Value: Extended); overload; virtual;
/// <summary> Writes a Boolean value </summary>
procedure WriteValue(Value: Boolean); overload; virtual;
/// <summary> Writes a Char value </summary>
procedure WriteValue(Value: Char); overload; virtual;
/// <summary> Writes a Byte value </summary>
procedure WriteValue(Value: Byte); overload; virtual;
/// <summary> Writes a TDateTime value </summary>
procedure WriteValue(Value: TDateTime); overload; virtual;
/// <summary> Writes a <see cref="TGUID">TGUID</see> value </summary>
procedure WriteValue(const Value: TGUID); overload; virtual;
/// <summary> Writes a Binary value. See http://bsonspec.org/spec.html </summary>
procedure WriteValue(const Value: TBytes; BinaryType: TJsonBinaryType = TJsonBinaryType.Generic); overload; virtual;
/// <summary> Writes a <see cref="TJsonOid">TJsonOid</see> value. See http://bsonspec.org/spec.html </summary>
procedure WriteValue(const Value: TJsonOid); overload; virtual;
/// <summary> Writes a <see cref="TJsonRegEx">TJsonRegEx</see> value. See http://bsonspec.org/spec.html </summary>
procedure WriteValue(const Value: TJsonRegEx); overload; virtual;
/// <summary> Writes a <see cref="TJsonDBRef">TJsonDBRef</see> value. See http://bsonspec.org/spec.html </summary>
procedure WriteValue(const Value: TJsonDBRef); overload; virtual;
/// <summary> Writes a <see cref="TJsonCodeWScope">TJsonCodeWScope</see> value. See http://bsonspec.org/spec.html </summary>
procedure WriteValue(const Value: TJsonCodeWScope); overload; virtual;
/// <summary> Writes a MinKey value. See http://bsonspec.org/spec.html </summary>
procedure WriteMinKey; overload; virtual;
/// <summary> Writes a MinKey value. See http://bsonspec.org/spec.html </summary>
procedure WriteMaxKey; overload; virtual;
/// <summary> Writes a <see cref="TValue">TValue</see> value </summary>
procedure WriteValue(const Value: TValue); overload; virtual;
/// <summary> Indicates whether the input should be closed when the writer is closed </summary>
property CloseOutput: Boolean read FCloseOutput write FCloseOutput;
/// <summary> Gets the path for the current container </summary>
property ContainerPath: string read GetContainerPath;
/// <summary> Gets the writer state </summary>
property Top: Integer read GetTop;
/// <summary> Gets the writer state </summary>
property TopContainer: TJsonContainerType read GetTopContainer;
/// <summary> Gets the writer state </summary>
property WriteState: TJsonWriteState read GetWriteState;
/// <summary> Gets the current path </summary>
property Path: string read GetPath;
/// <summary> Indicates how the empty values (arrays/strings) should be written </summary>
property EmptyValueHandling: TJsonEmptyValueHandling read FEmptyValueHandling write FEmptyValueHandling;
/// <summary> Indicates how the TDateTime should be treated when are written </summary>
property DateTimeZoneHandling: TJsonDateTimeZoneHandling read FDateTimeZoneHandling write FDateTimeZoneHandling;
end;
/// <summary>
/// Exception type for the <see cref="TJsonWriter"/>
/// </summary>
EJsonWriterException = class (EJsonException)
private
FPath: string;
public
constructor Create(const Msg: string; const Ex: Exception; const APath: string); overload;
constructor Create(const Writer: TJsonWriter; const Msg: string; const Ex: Exception = nil); overload;
constructor Create(const APath, Msg: string; const Ex: Exception); overload;
/// <summary> Gets the where the exception was raised </summary>
property Path: string read FPath;
end;
TASCIIStreamWriter = class(TStreamWriter)
private
procedure Write(ASrc: PChar; ACount: Integer); overload;
public
constructor Create(Stream: TStream; BufferSize: Integer = 4096); overload;
constructor Create(const Filename: string; Append: Boolean; BufferSize: Integer = 4096); overload;
procedure Write(Value: Boolean); override;
procedure Write(Value: Char); override;
procedure Write(const Value: TCharArray); override;
procedure Write(Value: Double); override;
procedure Write(Value: Integer); override;
procedure Write(Value: Int64); override;
procedure Write(Value: TObject); override;
procedure Write(Value: Single); override;
procedure Write(const Value: string); override;
procedure Write(Value: Cardinal); override;
procedure Write(Value: UInt64); override;
procedure Write(const Format: string; Args: array of const); override;
procedure Write(const Value: TCharArray; Index, Count: Integer); override;
procedure WriteLine; override;
procedure WriteLine(Value: Boolean); override;
procedure WriteLine(Value: Char); override;
procedure WriteLine(const Value: TCharArray); override;
procedure WriteLine(Value: Double); override;
procedure WriteLine(Value: Integer); override;
procedure WriteLine(Value: Int64); override;
procedure WriteLine(Value: TObject); override;
procedure WriteLine(Value: Single); override;
procedure WriteLine(const Value: string); override;
procedure WriteLine(Value: Cardinal); override;
procedure WriteLine(Value: UInt64); override;
procedure WriteLine(const Format: string; Args: array of const); override;
procedure WriteLine(const Value: TCharArray; Index, Count: Integer); override;
end;
/// <summary>
/// Writer to serialize JSON data.
/// </summary>
TJsonTextWriter = class(TJsonWriter)
private
FDateFormatHandling: TJsonDateFormatHandling;
FFormatSettings: TFormatSettings;
FStringEscapeHandling: TJsonStringEscapeHandling;
FFloatFormatHandling: TJsonFloatFormatHandling;
FFormatting: TJsonFormatting;
FWriter: TTextWriter;
FIndentChar: Char;
FIndentation: Integer;
FQuoteChar: Char;
FQuoteName: Boolean;
FExtendedJsonMode: TJsonExtendedJsonMode;
FCharEscapeFlags: TBooleanDynArray;
FWriterBuffer: array of Char;
FOwnsWriter: Boolean;
procedure EnsureBufferSize;
procedure UpdateCharEscapeFlags;
procedure WriteValueInternal(const Value: string; Token: TJsonToken);
procedure WriteEscapedString(const Value: string; Quote: Boolean);
procedure SetIndentation(Value: Integer);
procedure SetQuoteChar(Value: Char);
procedure SetStringEscapeHandling(Value: TJsonStringEscapeHandling);
procedure WriteNumberLong(const ANum: string);
protected
/// <summary> Writes indentation </summary>
procedure WriteIndent;
/// <summary> Writes a delimiter </summary>
procedure WriteValueDelimiter; inline;
/// <summary> Writes an space as indentation </summary>
procedure WriteIndentSpace; inline;
/// <summary> Write the end token based on the token, this method does not updates the internal state </summary>
procedure WriteEnd(const Token: TJsonToken); override;
/// <summary> Write the needed indents/spaces if required </summary>
procedure OnBeforeWriteToken(TokenBeginWritten: TJsonToken); override;
public
constructor Create(const TextWriter: TTextWriter; OwnsWriter: Boolean); overload;
constructor Create(const TextWriter: TTextWriter); overload;
constructor Create(const Stream: TStream); overload;
destructor Destroy; override;
/// <summary> Closes the underlitying writer </summary>
procedure Close; override;
/// <summary> Flushes the underlitying writer </summary>
procedure Flush; override;
/// <summary> Writes a comment</summary>
procedure WriteComment(const Comment: string); override;
/// <summary> Writes a null value </summary>
procedure WriteNull; override;
/// <summary> Writes a property name </summary>
procedure WritePropertyName(const Name: string); overload; override;
/// <summary> Writes a property name </summary>
procedure WritePropertyName(const Name: string; Escape: Boolean); overload;
/// <summary> Writes a raw json, it does not update the internal state </summary>
procedure WriteRaw(const Json: string); override;
/// <summary> Writes the start of a javascript constructor </summary>
procedure WriteStartConstructor(const Name: string); override;
/// <summary> Writes the start of a json object </summary>
procedure WriteStartObject; override;
/// <summary> Writes the start of a json array </summary>
procedure WriteStartArray; override;
/// <summary> Writes an string value </summary>
procedure WriteValue(const Value: string); override;
/// <summary> Writes an Integer value </summary>
procedure WriteValue(Value: Integer); override;
/// <summary> Writes an UInt32 value </summary>
procedure WriteValue(Value: UInt32); override;
/// <summary> Writes an Int64 value </summary>
procedure WriteValue(Value: Int64); override;
/// <summary> Writes an UInt64 value </summary>
procedure WriteValue(Value: UInt64); override;
/// <summary> Writes a Single value </summary>
procedure WriteValue(Value: Single); override;
/// <summary> Writes a Double value </summary>
procedure WriteValue(Value: Double); override;
/// <summary> Writes a Extended value </summary>
procedure WriteValue(Value: Extended); override;
/// <summary> Writes a Boolean value </summary>
procedure WriteValue(Value: Boolean); override;
/// <summary> Writes a Char value </summary>
procedure WriteValue(Value: Char); override;
/// <summary> Writes a Byte value </summary>
procedure WriteValue(Value: Byte); override;
/// <summary> Writes a TDateTime value </summary>
procedure WriteValue(Value: TDateTime); override;
/// <summary> Writes a <see cref="TGUID">TGUID</see> value </summary>
procedure WriteValue(const Value: TGUID); override;
/// <summary> Writes a Binary value. See http://bsonspec.org/spec.html </summary>
procedure WriteValue(const Value: TBytes; BinaryType: TJsonBinaryType = TJsonBinaryType.Generic); override;
/// <summary> Writes a <see cref="TJsonOid">TJsonOid</see> value. See http://bsonspec.org/spec.html </summary>
procedure WriteValue(const Value: TJsonOid); override;
/// <summary> Writes a <see cref="TJsonRegEx">TJsonRegEx</see> value. See http://bsonspec.org/spec.html </summary>
procedure WriteValue(const Value: TJsonRegEx); override;
/// <summary> Writes a <see cref="TJsonDBRef">TJsonDBRef</see> value. See http://bsonspec.org/spec.html </summary>
procedure WriteValue(const Value: TJsonDBRef); override;
/// <summary> Writes a <see cref="TJsonCodeWScope">TJsonCodeWScope</see> value. See http://bsonspec.org/spec.html </summary>
procedure WriteValue(const Value: TJsonCodeWScope); override;
/// <summary> Writes a MinKey value. See http://bsonspec.org/spec.html </summary>
procedure WriteMinKey; override;
/// <summary> Writes a MaxKey value. See http://bsonspec.org/spec.html </summary>
procedure WriteMaxKey; override;
/// <summary> Writes a <see cref="TValue">TValue</see> value </summary>
procedure WriteValue(const Value: TValue); override;
/// <summary> Writes an undefined value </summary>
procedure WriteUndefined; override;
/// <summary> Writes an white space </summary>
procedure WriteWhitespace(const Ws: string);
/// <summary> Gets the underlying writer </summary>
property Writer: TTextWriter read FWriter;
/// <summary> Gets or sets how many IndentChars to write for each level in the hierarchy when <see cref="Formatting"/> is set to TJsonFormatting.Indented </summary>
property Indentation: Integer read FIndentation write SetIndentation;
/// <summary> Gets or sets which character to use for indenting when <see cref="Formatting"/> is set to TJsonFormatting.Indented </summary>
property IndentChar: Char read FIndentChar write FIndentChar;
/// <summary>Gets or sets which character to use to quote attribute values </summary>
property QuoteChar: Char read FQuoteChar write SetQuoteChar;
/// <summary> Gets or sets a value indicating whether object names will be surrounded with quotes </summary>
property QuoteName: Boolean read FQuoteName write FQuoteName;
/// <summary> Indicates how JSON text output is formatted </summary>
property Formatting: TJsonFormatting read FFormatting write FFormatting;
/// <summary> Gets or sets the format settings used to convert numbers and datetimes. Default value is TFormatSettings.Invariant </summary>
property FormatSettings: TFormatSettings read FFormatSettings write FFormatSettings;
/// <summary> Indicates how strings are escaped when writing JSON text </summary>
property StringEscapeHandling: TJsonStringEscapeHandling read FStringEscapeHandling write SetStringEscapeHandling;
/// <summary> Indicates the format of TDateTime to be written in </summary>
property DateFormatHandling: TJsonDateFormatHandling read FDateFormatHandling write FDateFormatHandling;
/// <summary> Indicates the format of TDateTime to be written in </summary>
property FloatFormatHandling: TJsonFloatFormatHandling read FFloatFormatHandling write FFloatFormatHandling;
/// <summary> Indicates the mode in which the writer should operate when writes extended tokens (TJsonOid, TJsonRegEx...) </summary>
property ExtendedJsonMode: TJsonExtendedJsonMode read FExtendedJsonMode write FExtendedJsonMode;
end;
/// <summary>
/// Writer to convert JSON data into TJSONValue objects.
/// </summary>
TJsonObjectWriter = class(TJsonWriter)
private
FDateFormatHandling: TJsonDateFormatHandling;
FRoot: TJSONAncestor;
FContainerStack: TStack<TJSONAncestor>;
FOwnValue: Boolean;
procedure AppendContainer(const JSONValue: TJSONValue);
procedure AppendValue(const JsonValue: TJSONValue);
function GetContainer: TJSONValue;
procedure SetContainer(const Value: TJSONValue);
protected
procedure WriteEnd(const Token: TJsonToken); override;
public
constructor Create(OwnValue: Boolean = True);
destructor Destroy; override;
/// <summary> Resets the internal state allowing write from the begining </summary>
procedure Rewind; override;
/// <summary> Writes a null value </summary>
procedure WriteNull; override;
/// <summary> Writes a property name </summary>
procedure WritePropertyName(const Name: string); overload; override;
/// <summary> Writes the start of a javascript constructor </summary>
procedure WriteStartConstructor(const Name: string); override;
/// <summary> Writes the start of a json object </summary>
procedure WriteStartObject; override;
/// <summary> Writes the start of a json array </summary>
procedure WriteStartArray; override;
/// <summary> Writes a raw json, it does not update the internal state </summary>
procedure WriteRaw(const Json: string); override;
/// <summary> Writes a raw json, it updates the internal state </summary>
procedure WriteRawValue(const Json: string); override;
/// <summary> Writes an string value </summary>
procedure WriteValue(const Value: string); override;
/// <summary> Writes an Integer value </summary>
procedure WriteValue(Value: Integer); override;
/// <summary> Writes an UInt32 value </summary>
procedure WriteValue(Value: UInt32); override;
/// <summary> Writes an Int64 value </summary>
procedure WriteValue(Value: Int64); override;
/// <summary> Writes an UInt64 value </summary>
procedure WriteValue(Value: UInt64); override;
/// <summary> Writes a Single value </summary>
procedure WriteValue(Value: Single); override;
/// <summary> Writes a Double value </summary>
procedure WriteValue(Value: Double); override;
/// <summary> Writes a Extended value </summary>
procedure WriteValue(Value: Extended); override;
/// <summary> Writes a Boolean value </summary>
procedure WriteValue(Value: Boolean); override;
/// <summary> Writes a Char value </summary>
procedure WriteValue(Value: Char); override;
/// <summary> Writes a Byte value </summary>
procedure WriteValue(Value: Byte); override;
/// <summary> Writes a TDateTime value </summary>
procedure WriteValue(Value: TDateTime); override;
/// <summary> Writes a <see cref="TGUID">TGUID</see> value </summary>
procedure WriteValue(const Value: TGUID); override;
/// <summary> Writes a Binary value. See http://bsonspec.org/spec.html </summary>
procedure WriteValue(const Value: TBytes; BinaryType: TJsonBinaryType = TJsonBinaryType.Generic); override;
/// <summary> Writes a <see cref="TJsonOid">TJsonOid</see> value. See http://bsonspec.org/spec.html </summary>
procedure WriteValue(const Value: TJsonOid); override;
/// <summary> Writes a <see cref="TJsonRegEx">TJsonRegEx</see> value. See http://bsonspec.org/spec.html </summary>
procedure WriteValue(const Value: TJsonRegEx); override;
/// <summary> Writes a <see cref="TJsonDBRef">TJsonDBRef</see> value. See http://bsonspec.org/spec.html </summary>
procedure WriteValue(const Value: TJsonDBRef); override;
/// <summary> Writes a <see cref="TJsonCodeWScope">TJsonCodeWScope</see> value. See http://bsonspec.org/spec.html </summary>
procedure WriteValue(const Value: TJsonCodeWScope); override;
/// <summary> Writes a MinKey value. See http://bsonspec.org/spec.html </summary>
procedure WriteMinKey; override;
/// <summary> Writes a MaxKey value. See http://bsonspec.org/spec.html </summary>
procedure WriteMaxKey; override;
/// <summary> Writes an undefined value </summary>
procedure WriteUndefined; override;
/// <summary> Gets the JSON value created </summary>
/// <remarks> To take the ownership of the returned object, set <see cref="OwnValue">OwnValue</see> property to false </remarks>
property JSON: TJSONAncestor read FRoot;
property Container: TJSONValue read GetContainer write SetContainer;
/// <summary> Indicates how the TDateTime should be treated when are written </summary>
property DateFormatHandling: TJsonDateFormatHandling read FDateFormatHandling write FDateFormatHandling;
/// <summary> Indicates if the JSON value is owned by the writer or not </summary>
property OwnValue: Boolean read FOwnValue write FOwnValue;
end;
implementation
uses
System.TypInfo, System.DateUtils, System.Math, System.NetEncoding,
System.JSONConsts, System.JSON.Utils;
{ Helpers }
function GetName(Value: TJsonToken): string; overload;
begin
Result := GetEnumName(TypeInfo(TJsonToken), Integer(Value));
end;
function GetName(Value: TJsonWriter.TState): string; overload;
begin
Result := GetEnumName(TypeInfo(TJsonWriter.TState), Integer(Value));
end;
function GetName(Value: TJsonContainerType): string; overload;
begin
Result := GetEnumName(TypeInfo(TJsonContainerType), Integer(Value));
end;
{ TJsonWriterException }
constructor EJsonWriterException.Create(const Msg: string; const Ex: Exception; const APath: string);
begin
inherited Create(Msg, Ex);
FPath := APath;
end;
constructor EJsonWriterException.Create(const Writer: TJsonWriter; const Msg: string; const Ex: Exception);
begin
Create(Writer.ContainerPath, Msg, Ex);
end;
constructor EJsonWriterException.Create(const APath, Msg: string; const Ex: Exception);
begin
Create(TJsonPosition.FormatMessage(nil, APath, Msg), Ex, APath);
end;
{ TJsonWriter }
procedure TJsonWriter.AutoComplete(TokenBeginWritten: TJsonToken);
procedure ErrorInvalidState;
begin
raise EJsonWriterException.Create(Self, Format(STokenInStateInvalid, [GetName(TokenBeginWritten),
GetName(FCurrentState)]));
end;
var
NewState: TState;
begin
NewState := StateArray[Integer(TokenBeginWritten)][Integer(FCurrentState)];
if NewState = TState.Error then
ErrorInvalidState;
OnBeforeWriteToken(TokenBeginWritten);
FCurrentState := NewState;
end;
procedure TJsonWriter.AutoCompleteAll;
begin
while Top > 0 do
WriteEnd;
end;
procedure TJsonWriter.AutoCompleteClose(ContainerType: TJsonContainerType);
var
LevelsToComplete, CurrentLevel: Integer;
CurrentLevelType: TJsonContainerType;
LTop: Integer;
Token: TJsonToken;
I: Integer;
procedure ErrorNoToken;
begin
raise EJsonWriterException.Create(Self, SNoTokenToClose);
end;
procedure ErrorUnknownContainer;
begin
raise EJsonWriterException.Create(Self, Format(SUnknowContainerType, [GetName(CurrentLevelType)]));
end;
begin
LevelsToComplete := 0;
if FCurrentPosition.ContainerType = ContainerType then
LevelsToComplete := 1
else
begin
LTop := Top - 2;
for I := LTop downto 0 do
begin
CurrentLevel := LTop - I;
if FStack[CurrentLevel].ContainerType = ContainerType then
begin
LevelsToComplete := I + 2;
Break;
end;
end;
end;
if LevelsToComplete = 0 then
ErrorNoToken;
for I := 0 to LevelsToComplete - 1 do
begin
Token := GetCloseTokenForType(Pop);
if FCurrentState = TState.Property then
WriteNull;
OnBeforeWriteToken(Token);
WriteEnd(Token);
CurrentLevelType := Peek;
case CurrentLevelType of
TJsonContainerType.Object:
FCurrentState := TState.Object;
TJsonContainerType.Array:
FCurrentState := TState.Array;
TJsonContainerType.Constructor:
FCurrentState := TState.Array;
TJsonContainerType.None:
FCurrentState := TState.Start;
else
ErrorUnknownContainer;
end;
end;
end;
procedure TJsonWriter.OnBeforeWriteToken(TokenBeginWriten: TJsonToken);
begin
// implement in child classes
end;
class procedure TJsonWriter.BuildStateArray;
var
Token: TJsonToken;
Len, I: Integer;
PLine: ^TJsonToken;
begin
Len := Length(StateArrayTemplate);
SetLength(StateArray, Len);
for I := Low(StateArrayTemplate) to High(StateArrayTemplate) do
begin
SetLength(StateArray[I], Length(StateArrayTemplate[I]));
Move(StateArrayTemplate[I][0], StateArray[I][0], Length(StateArrayTemplate[I]));
end;
I := 0;
for Token := Low(TJsonToken) to High(TJsonToken) do
begin
if Len <= I then
case Token of
TJsonToken.Integer,
TJsonToken.Float,
TJsonToken.String,
TJsonToken.Boolean,
TJsonToken.Null,
TJsonToken.Undefined,
TJsonToken.Date,
TJsonToken.Bytes,
TJsonToken.Oid,
TJsonToken.RegEx,
TJsonToken.DBRef,
TJsonToken.CodeWScope,
TJsonToken.MinKey,
TJsonToken.MaxKey:
begin
Inc(Len);
SetLength(StateArray, Len);
SetLength(StateArray[Len - 1], Length(StateArrayTemplate[7]));
PLine := @StateArray[Len - 1][0];
Move(StateArray[7][0], PLine^, Length(StateArrayTemplate[7]));
end;
else
begin
Inc(Len);
SetLength(StateArray, Len);
SetLength(StateArray[Len - 1], Length(StateArrayTemplate[0]));
PLine := @StateArray[Len - 1][0];
Move(StateArray[0][0], PLine^, Length(StateArrayTemplate[0]));
end;
end;
Inc(I);
end;
end;
class constructor TJsonWriter.Create;
begin
BuildStateArray;
end;
procedure TJsonWriter.Close;
begin
AutoCompleteAll;
end;
constructor TJsonWriter.Create;
begin
FStack := TList<TJsonPosition>.Create;
FEmptyValueHandling := TJsonEmptyValueHandling.Empty;
FStack.Capacity := 4;
FCurrentState := TState.Start;
CloseOutput := True;
FCurrentPosition := TJsonPosition.Create(TJsonContainerType.None);
FDateTimeZoneHandling := TJsonDateTimeZoneHandling.Local;
end;
destructor TJsonWriter.Destroy;
begin
if FCurrentState <> TState.Closed then
Close;
FStack.Free;
inherited Destroy;
end;
procedure TJsonWriter.Flush;
begin
// implement in child classes
end;
function TJsonWriter.GetCloseTokenForType(ContainerType: TJsonContainerType): TJsonToken;
procedure ErrorNoToken;
begin
raise EJsonWriterException.Create(Self, Format(SNoTokenForType, [GetName(ContainerType)]));
end;
begin
case ContainerType of
TJsonContainerType.Object:
Result := TJsonToken.EndObject;
TJsonContainerType.Array:
Result := TJsonToken.EndArray;
TJsonContainerType.Constructor:
Result := TJsonToken.EndConstructor;
else
begin
Result := TJsonToken.None;
ErrorNoToken;
end;
end;
end;
function TJsonWriter.GetContainerPath: string;
begin
if FCurrentPosition.ContainerType = TJsonContainerType.None then
Result := ''
else
Result := TJsonPosition.BuildPath(FStack)
end;
function TJsonWriter.GetPath: string;
var
InsideContainer: Boolean;
Positions: TList<TJsonPosition>;
begin
if FCurrentPosition.ContainerType = TJsonContainerType.None then
Result := ''
else
begin
InsideContainer := (FCurrentState <> TState.ArrayStart) and
(FCurrentState <> TState.ConstructorStart) and (FCurrentState <> TState.ObjectStart);
if not InsideContainer then
Positions := FStack
else
begin
Positions := TList<TJsonPosition>.Create(FStack);
Positions.Add(FCurrentPosition);
end;
try
Result := TJsonPosition.BuildPath(Positions);
finally
if InsideContainer then
Positions.Free;
end;
end;
end;
function TJsonWriter.GetPosition(ADepth: Integer): TJsonPosition;
begin
if ADepth < FStack.Count then
Result := FStack[ADepth]
else
Result := FCurrentPosition;
end;
function TJsonWriter.GetTop: Integer;
begin
Result := FStack.Count;
if Peek <> TJsonContainerType.None then
Inc(Result);
end;
function TJsonWriter.GetTopContainer: TJsonContainerType;
begin
Result := FCurrentPosition.ContainerType;
end;
function TJsonWriter.GetWriteState: TJsonWriteState;
procedure ErrorInvalidState;
begin
raise EJsonWriterException.Create(Self, Format(SInvalidState, [GetName(FCurrentState)]));
end;
begin
case FCurrentState of
TJsonWriter.TState.Error:
Result := TJsonWriteState.Error;
TJsonWriter.TState.Closed:
Result := TJsonWriteState.Closed;
TJsonWriter.TState.Object,
TJsonWriter.TState.ObjectStart:
Result := TJsonWriteState.Object;
TJsonWriter.TState.Array,
TJsonWriter.TState.ArrayStart:
Result := TJsonWriteState.Array;
TJsonWriter.TState.Constructor,
TJsonWriter.TState.ConstructorStart:
Result := TJsonWriteState.Constructor;
TJsonWriter.TState.Property:
Result := TJsonWriteState.Property;
TJsonWriter.TState.Start:
Result := TJsonWriteState.Start;
else
begin
Result := TJsonWriteState.Error;
ErrorInvalidState;
end;
end;
end;
procedure TJsonWriter.InternalWriteComment;
begin
AutoComplete(TJsonToken.Comment);
end;
procedure TJsonWriter.InternalWriteEnd(Container: TJsonContainerType);
begin
AutoCompleteClose(Container);
end;
procedure TJsonWriter.InternalWritePropertyName(const Name: string);
begin
FCurrentPosition.PropertyName := Name;
AutoComplete(TJsonToken.PropertyName);
end;
procedure TJsonWriter.InternalWriteStart(Token: TJsonToken; Container: TJsonContainerType);
begin
UpdateScopeWithFinishedValue;
AutoComplete(Token);
Push(Container);
end;
procedure TJsonWriter.InternalWriteValue(Token: TJsonToken);
begin
UpdateScopeWithFinishedValue;
AutoComplete(Token);
end;
class function TJsonWriter.IsEndToken(Token: TJsonToken): Boolean;
begin
case Token of
TJsonToken.EndObject,
TJsonToken.EndArray,
TJsonToken.EndConstructor:
Result := True;
else
Result := False;
end;
end;
class function TJsonWriter.IsStartToken(Token: TJsonToken): Boolean;
begin
case Token of
TJsonToken.StartObject,
TJsonToken.StartArray,
TJsonToken.StartConstructor:
Result := True;
else
Result := False;
end;
end;
function TJsonWriter.Peek: TJsonContainerType;
begin
Result := FCurrentPosition.ContainerType;
end;
function TJsonWriter.Pop: TJsonContainerType;
var
OldPosition: TJsonPosition;
begin
OldPosition := FCurrentPosition;
if FStack.Count > 0 then
begin
FCurrentPosition := FStack[FStack.Count - 1];
FStack.Delete(FStack.Count - 1);
end
else
FCurrentPosition := TJsonPosition.Create;
Result := OldPosition.ContainerType;
end;
procedure TJsonWriter.Push(Value: TJsonContainerType);
begin
if FCurrentPosition.ContainerType <> TJsonContainerType.None then
FStack.Add(FCurrentPosition);
FCurrentPosition := TJsonPosition.Create(Value);
end;
procedure TJsonWriter.Rewind;
begin
FStack.Clear;
FStack.Capacity := 4;
FCurrentState := TState.Start;
CloseOutput := True;
FCurrentPosition := TJsonPosition.Create(TJsonContainerType.None);
end;
procedure TJsonWriter.SetWriteState(Token: TJsonToken; const Value: TValue);
begin
case Token of
TJsonToken.StartObject:
InternalWriteStart(Token, TJsonContainerType.Object);
TJsonToken.StartArray:
InternalWriteStart(Token, TJsonContainerType.Array);
TJsonToken.StartConstructor:
InternalWriteStart(Token, TJsonContainerType.Constructor);
TJsonToken.PropertyName:
begin
if not (Value.TypeInfo^.Kind in [tkString, tkWChar, tkLString, tkWString, tkUString]) then
raise EArgumentException.Create(SRequiredPropertyName);
InternalWritePropertyName(Value.AsString);
end;
TJsonToken.Comment:
InternalWriteComment;
TJsonToken.Raw:
// raw does not change the state
;
TJsonToken.Integer,
TJsonToken.Float,
TJsonToken.String,
TJsonToken.Boolean,
TJsonToken.Date,
TJsonToken.Bytes,
TJsonToken.Null,
TJsonToken.Undefined,
TJsonToken.Oid,
TJsonToken.RegEx,
TJsonToken.DBRef,
TJsonToken.CodeWScope,
TJsonToken.MinKey,
TJsonToken.MaxKey:
InternalWriteValue(Token);
TJsonToken.EndObject:
InternalWriteEnd(TJsonContainerType.Object);
TJsonToken.EndArray:
InternalWriteEnd(TJsonContainerType.Array);
TJsonToken.EndConstructor:
InternalWriteEnd(TJsonContainerType.Constructor);
else
raise EArgumentOutOfRangeException.Create('Token');
end;
end;
procedure TJsonWriter.UpdateScopeWithFinishedValue;
begin
if FCurrentPosition.HasIndex then
Inc(FCurrentPosition.Position);
end;
procedure TJsonWriter.WriteComment(const Comment: string);
begin
InternalWriteComment;
end;
procedure TJsonWriter.WriteConstructorDate(const Reader: TJsonReader);
var
Ticks: Int64;
Date: TDateTime;
begin
if not Reader.Read then
raise EJsonWriterException.Create(Self, SUnexpectedEndConstructorDate);
if Reader.TokenType <> TJsonToken.Integer then
raise EJsonWriterException.Create(Self, Format(SUnexpectedTokenDateConstructorExpInt, [GetName(Reader.TokenType)]));
Ticks := Reader.Value.AsInt64;
Date := IncMilliSecond(621355968000000000 + (Ticks * 1000));
if not reader.Read then
raise EJsonWriterException.Create(Self, SUnexpectedEndConstructorDate);
if reader.TokenType <> TJsonToken.EndConstructor then
raise EJsonWriterException.Create(Self, Format(SUnexpectedTokenDateConstructorExpEnd, [GetName(Reader.TokenType)]));
WriteValue(Date);
end;
procedure TJsonWriter.WriteEnd;
begin
WriteEnd(Peek);
end;
procedure TJsonWriter.WriteEnd(const Token: TJsonToken);
begin
// implement in child classes
end;
procedure TJsonWriter.WriteEnd(ContainerType: TJsonContainerType);
procedure ErrorUnexpectedType;
begin
raise EJsonWriterException.Create(Self, Format(SUnexpectedTypeOnEnd, [GetName(ContainerType)]));
end;
begin
case ContainerType of
TJsonContainerType.Object:
WriteEndObject;
TJsonContainerType.Array:
WriteEndArray;
TJsonContainerType.Constructor:
WriteEndConstructor;
else
ErrorUnexpectedType;
end;
end;
procedure TJsonWriter.WriteEndArray;
begin
InternalWriteEnd(TJsonContainerType.Array);
end;
procedure TJsonWriter.WriteEndConstructor;
begin
InternalWriteEnd(TJsonContainerType.Constructor);
end;
procedure TJsonWriter.WriteEndObject;
begin
InternalWriteEnd(TJsonContainerType.Object);
end;
procedure TJsonWriter.WriteNull;
begin
InternalWriteValue(TJsonToken.Null);
end;
procedure TJsonWriter.WriteRaw(const Json: string);
begin
// implement in child class
end;
procedure TJsonWriter.WriteRawValue(const Json: string);
begin
UpdateScopeWithFinishedValue;
AutoComplete(TJsonToken.Undefined);
WriteRaw(Json);
end;
procedure TJsonWriter.WritePropertyName(const Name: string);
begin
InternalWritePropertyName(Name);
end;
procedure TJsonWriter.WriteStartArray;
begin
InternalWriteStart(TJsonToken.StartArray, TJsonContainerType.Array);
end;
procedure TJsonWriter.WriteStartConstructor(const Name: string);
begin
InternalWriteStart(TJsonToken.StartConstructor, TJsonContainerType.Constructor);
end;
procedure TJsonWriter.WriteStartObject;
begin
InternalWriteStart(TJsonToken.StartObject, TJsonContainerType.Object);
end;
procedure TJsonWriter.WriteToken(const Reader: TJsonReader; InitialDepth: Integer; WriteChildren,
WriteDateConstructorAsDate: Boolean);
var
DepthOffset: Integer;
ConstructorName: string;
S: Single;
D: Double;
E: Extended;
Date: TDateTime;
begin
repeat
case Reader.TokenType of
TJsonToken.None:
;
TJsonToken.StartObject:
WriteStartObject;
TJsonToken.StartArray:
WriteStartArray;
TJsonToken.StartConstructor:
begin
ConstructorName := Reader.Value.AsString;
// write a JValue date when the constructor is for a date
if WriteDateConstructorAsDate and string.Equals(ConstructorName, 'Date') then
WriteConstructorDate(Reader)
else
WriteStartConstructor(ConstructorName);
end;
TJsonToken.PropertyName:
WritePropertyName(Reader.Value.AsString);
TJsonToken.Comment:
if Reader.Value.IsEmpty then
WriteComment('')
else
WriteComment(Reader.Value.AsString);
TJsonToken.Raw:
WriteRawValue(Reader.Value.AsString);
TJsonToken.Integer:
if Reader.Value.TypeInfo^.Kind = tkInteger then
WriteValue(Reader.Value.AsInteger)
else
WriteValue(Reader.Value.AsInt64);
TJsonToken.Float:
case TRttiFloatType(FRttiCtx.GetType(Reader.Value.TypeInfo)).FloatType of
ftSingle:
begin
S := Reader.Value.AsExtended;
WriteValue(S);
end;
ftDouble:
begin
D := Reader.Value.AsExtended;
WriteValue(D);
end;
ftExtended,
ftCurr:
begin
E := Reader.Value.AsExtended;
WriteValue(E);
end;
end;
TJsonToken.String:
WriteValue(Reader.Value.AsString);
TJsonToken.Boolean:
WriteValue(Reader.Value.AsBoolean);
TJsonToken.Null:
WriteNull;
TJsonToken.Undefined:
WriteUndefined;
TJsonToken.EndObject:
WriteEndObject;
TJsonToken.EndArray:
WriteEndArray;
TJsonToken.EndConstructor:
WriteEndConstructor;
TJsonToken.Date:
begin
Date := Reader.Value.AsExtended;
WriteValue(Date);
end;
TJsonToken.Bytes:
WriteValue(Reader.Value.AsType<TBytes>);
TJsonToken.Oid:
WriteValue(Reader.Value.AsType<TJsonOid>);
TJsonToken.RegEx:
WriteValue(Reader.Value.AsType<TJsonRegEx>);
TJsonToken.DBRef:
WriteValue(Reader.Value.AsType<TJsonDBRef>);
TJsonToken.CodeWScope:
WriteValue(Reader.Value.AsType<TJsonCodeWScope>);
TJsonToken.MinKey:
WriteMinKey;
TJsonToken.MaxKey:
WriteMaxKey;
end;
if IsEndToken(Reader.TokenType) then
DepthOffset := 1
else
DepthOffset := 0;
until not (((InitialDepth - 1) < (Reader.Depth - DepthOffset)) and WriteChildren and Reader.Read);
end;
procedure TJsonWriter.WriteToken(const Reader: TJsonReader; WriteChildren, WriteDateConstructorAsDate: Boolean);
var
InitialDepth: Integer;
begin
if Reader.TokenType = TJsonToken.None then
InitialDepth := -1
else if not IsStartToken(Reader.TokenType) then
InitialDepth := Reader.Depth + 1
else
InitialDepth := Reader.Depth;
WriteToken(Reader, InitialDepth, WriteChildren, WriteDateConstructorAsDate);
end;
procedure TJsonWriter.WriteToken(const Reader: TJsonReader; WriteChildren: Boolean);
begin
WriteToken(Reader, WriteChildren, True);
end;
procedure TJsonWriter.WriteToken(const Reader: TJsonReader);
begin
WriteToken(Reader, True, True);
end;
procedure TJsonWriter.WriteUndefined;
begin
InternalWriteValue(TJsonToken.Undefined);
end;
procedure TJsonWriter.WriteValue(Value: UInt64);
begin
InternalWriteValue(TJsonToken.Integer);
end;
procedure TJsonWriter.WriteValue(Value: Single);
begin
InternalWriteValue(TJsonToken.Float);
end;
procedure TJsonWriter.WriteValue(Value: Double);
begin
InternalWriteValue(TJsonToken.Float);
end;
procedure TJsonWriter.WriteValue(Value: Int64);
begin
InternalWriteValue(TJsonToken.Integer);
end;
procedure TJsonWriter.WriteValue(const Value: string);
begin
if (Length(Value) = 0) and (EmptyValueHandling = TJsonEmptyValueHandling.Null) then
WriteNull
else
InternalWriteValue(TJsonToken.String);
end;
procedure TJsonWriter.WriteValue(Value: Integer);
begin
InternalWriteValue(TJsonToken.Integer);
end;
procedure TJsonWriter.WriteValue(Value: UInt32);
begin
InternalWriteValue(TJsonToken.Integer);
end;
procedure TJsonWriter.WriteValue(Value: Boolean);
begin
InternalWriteValue(TJsonToken.Boolean);
end;
procedure TJsonWriter.WriteValue(const Value: TGUID);
begin
InternalWriteValue(TJsonToken.String);
end;
procedure TJsonWriter.WriteValue(const Value: TBytes;
BinaryType: TJsonBinaryType = TJsonBinaryType.Generic);
begin
if (Length(Value) = 0) and (EmptyValueHandling = TJsonEmptyValueHandling.Null) then
WriteNull
else
InternalWriteValue(TJsonToken.Bytes);
end;
procedure TJsonWriter.WriteValue(const Value: TJsonOid);
begin
InternalWriteValue(TJsonToken.Oid);
end;
procedure TJsonWriter.WriteValue(const Value: TJsonRegEx);
begin
InternalWriteValue(TJsonToken.RegEx);
end;
procedure TJsonWriter.WriteValue(const Value: TJsonDBRef);
begin
InternalWriteValue(TJsonToken.DBRef);
end;
procedure TJsonWriter.WriteValue(const Value: TJsonCodeWScope);
begin
InternalWriteValue(TJsonToken.CodeWSCope);
end;
procedure TJsonWriter.WriteMinKey;
begin
InternalWriteValue(TJsonToken.MinKey);
end;
procedure TJsonWriter.WriteMaxKey;
begin
InternalWriteValue(TJsonToken.MaxKey);
end;
class procedure TJsonWriter.WriteValue(const Writer: TJsonWriter; const Value: TValue);
procedure ErrorUnsupportedType;
begin
raise EJsonWriterException.Create(Writer, Format(SUnsupportedType,
[GetEnumName(TypeInfo(TTypeKind), Integer(Value.TypeInfo^.Kind))]));
end;
var
S: Single;
D: Double;
E: Extended;
Date: TDateTime;
begin
if Value.IsEmpty then
Writer.WriteNull
else
case Value.TypeInfo^.Kind of
tkFloat:
if Value.TypeInfo = TypeInfo(TDateTime) then
begin
Date := Value.AsExtended;
Writer.WriteValue(Date);
end
else
case TRttiFloatType(FRttiCtx.GetType(Value.TypeInfo)).FloatType of
ftSingle:
begin
S := Value.AsExtended;
Writer.WriteValue(S);
end;
ftDouble:
begin
D := Value.AsExtended;
Writer.WriteValue(D);
end;
ftExtended,
ftCurr:
begin
E := Value.AsExtended;
Writer.WriteValue(E);
end;
end;
tkInteger:
Writer.WriteValue(Value.AsInteger);
tkInt64:
Writer.WriteValue(Value.AsInt64);
tkString, tkWChar, tkChar, tkLString, tkWString, tkUString:
Writer.WriteValue(Value.AsString);
tkEnumeration:
if Value.TypeInfo = TypeInfo(Boolean) then
Writer.WriteValue(Value.AsBoolean)
else
Writer.WriteValue(GetEnumName(Value.TypeInfo, PInteger(Value.GetReferenceToRawData)^));
tkUnknown, tkSet, tkClass, tkMethod, tkDynArray, tkVariant,
tkArray, tkRecord, tkMRecord, tkInterface, tkClassRef, tkPointer, tkProcedure:
ErrorUnsupportedType;
end;
end;
procedure TJsonWriter.WriteValue(Value: Char);
begin
InternalWriteValue(TJsonToken.String);
end;
procedure TJsonWriter.WriteValue(Value: Byte);
begin
InternalWriteValue(TJsonToken.Integer);
end;
procedure TJsonWriter.WriteValue(Value: TDateTime);
begin
InternalWriteValue(TJsonToken.Date);
end;
procedure TJsonWriter.WriteValue(Value: Extended);
begin
InternalWriteValue(TJsonToken.Float);
end;
procedure TJsonWriter.WriteValue(const Value: TValue);
begin
WriteValue(Self, Value);
end;
{ TASCIIStreamWriter }
constructor TASCIIStreamWriter.Create(Stream: TStream; BufferSize: Integer);
begin
inherited Create(Stream, TEncoding.ASCII, BufferSize);
end;
constructor TASCIIStreamWriter.Create(const Filename: string; Append: Boolean;
BufferSize: Integer);
begin
inherited Create(FileName, Append, TEncoding.ASCII, BufferSize);
end;
procedure TASCIIStreamWriter.Write(ASrc: PChar; ACount: Integer);
begin
while ACount > 0 do
begin
FBuffer[FBufferIndex] := Byte(ASrc^);
Inc(ASrc);
Dec(ACount);
Inc(FBufferIndex);
if FBufferIndex >= Length(FBuffer) then
Flush;
end;
if AutoFlush then
Flush;
end;
procedure TASCIIStreamWriter.Write(Value: Char);
begin
Write(@Value, 1);
end;
procedure TASCIIStreamWriter.Write(const Value: string);
begin
Write(PChar(Value), Length(Value));
end;
procedure TASCIIStreamWriter.Write(const Value: TCharArray; Index, Count: Integer);
begin
Write(@Value[Index], Count);
end;
procedure TASCIIStreamWriter.Write(Value: Cardinal);
begin
Write(UIntToStr(Value));
end;
procedure TASCIIStreamWriter.Write(Value: UInt64);
begin
Write(UIntToStr(Value));
end;
procedure TASCIIStreamWriter.Write(const Format: string; Args: array of const);
begin
Write(System.SysUtils.Format(Format, Args));
end;
procedure TASCIIStreamWriter.Write(Value: Single);
begin
Write(FloatToStr(Value));
end;
procedure TASCIIStreamWriter.Write(const Value: TCharArray);
begin
Write(Value, 0, Length(Value));
end;
procedure TASCIIStreamWriter.Write(Value: Double);
begin
Write(FloatToStr(Value));
end;
procedure TASCIIStreamWriter.Write(Value: Integer);
begin
Write(IntToStr(Value));
end;
procedure TASCIIStreamWriter.Write(Value: TObject);
begin
Write(Value.ToString);
end;
procedure TASCIIStreamWriter.Write(Value: Int64);
begin
Write(IntToStr(Value));
end;
procedure TASCIIStreamWriter.Write(Value: Boolean);
begin
Write(BoolToStr(Value, True));
end;
procedure TASCIIStreamWriter.WriteLine;
begin
Write(NewLine);
end;
procedure TASCIIStreamWriter.WriteLine(const Value: string);
begin
Write(Value);
WriteLine;
end;
procedure TASCIIStreamWriter.WriteLine(const Value: TCharArray);
begin
Write(Value);
WriteLine;
end;
procedure TASCIIStreamWriter.WriteLine(Value: Double);
begin
Write(Value);
WriteLine;
end;
procedure TASCIIStreamWriter.WriteLine(Value: Integer);
begin
Write(Value);
WriteLine;
end;
procedure TASCIIStreamWriter.WriteLine(Value: Boolean);
begin
Write(BoolToStr(Value, True));
WriteLine;
end;
procedure TASCIIStreamWriter.WriteLine(Value: Char);
begin
Write(Value);
WriteLine;
end;
procedure TASCIIStreamWriter.WriteLine(Value: Int64);
begin
Write(Value);
WriteLine;
end;
procedure TASCIIStreamWriter.WriteLine(Value: UInt64);
begin
Write(Value);
WriteLine;
end;
procedure TASCIIStreamWriter.WriteLine(const Format: string; Args: array of const);
begin
Write(System.SysUtils.Format(Format, Args));
WriteLine;
end;
procedure TASCIIStreamWriter.WriteLine(const Value: TCharArray; Index, Count: Integer);
begin
Write(Value, Index, Count);
WriteLine;
end;
procedure TASCIIStreamWriter.WriteLine(Value: Cardinal);
begin
Write(Value);
WriteLine;
end;
procedure TASCIIStreamWriter.WriteLine(Value: TObject);
begin
Write(Value);
WriteLine;
end;
procedure TASCIIStreamWriter.WriteLine(Value: Single);
begin
Write(Value);
WriteLine;
end;
{ TJsonTextWriter }
constructor TJsonTextWriter.Create(const TextWriter: TTextWriter; OwnsWriter: Boolean);
begin
FOwnsWriter := OwnsWriter;
FWriter := TextWriter;
FQuoteChar := '"';
FQuoteName := True;
FIndentChar := ' ';
FIndentation := 4;
FFormatting := TJsonFormatting.None;
UpdateCharEscapeFlags;
FormatSettings := JSONFormatSettings;
FFloatFormatHandling := TJsonFloatFormatHandling.Symbol;
FDateFormatHandling := TJsonDateFormatHandling.Iso;
FExtendedJsonMode := TJsonExtendedJsonMode.None;
inherited Create;
end;
constructor TJsonTextWriter.Create(const TextWriter: TTextWriter);
begin
Create(TextWriter, False);
end;
constructor TJsonTextWriter.Create(const Stream: TStream);
var
LWriter: TASCIIStreamWriter;
begin
LWriter := TASCIIStreamWriter.Create(Stream, 32768);
LWriter.AutoFlush := False;
FStringEscapeHandling := TJsonStringEscapeHandling.EscapeNonAscii;
Create(LWriter, True);
end;
destructor TJsonTextWriter.Destroy;
begin
inherited Destroy;
if FOwnsWriter then
FWriter.Free;
end;
procedure TJsonTextWriter.OnBeforeWriteToken(TokenBeginWritten: TJsonToken);
begin
// Delimiter
case TokenBeginWritten of
TJsonToken.EndObject,
TJsonToken.EndArray,
TJsonToken.EndConstructor,
TJsonToken.Comment:
// skip delimiter
else
case FCurrentState of
TState.Object,
TState.Array,
TState.Constructor:
WriteValueDelimiter;
end;
end;
// Formatting if required
if FFormatting = TJsonFormatting.Indented then
begin
// don't indent a property when it is the first token to be written (i.e. at the start)
if FCurrentState = TState.Property then
WriteIndentSpace;
// skip indentation in empty arrays, objects and constructors
case TokenBeginWritten of
TJsonToken.EndArray:
if FCurrentState = TState.ArrayStart then Exit;
TJsonToken.EndObject:
if FCurrentState = TState.ObjectStart then Exit;
TJsonToken.EndConstructor:
if FCurrentState = TState.ConstructorStart then Exit;
end;
case FCurrentState of
TState.Array,
TState.ArrayStart,
TState.ObjectStart,
TState.Object,
TState.Constructor,
TState.ConstructorStart:
WriteIndent;
TState.Start:
if TokenBeginWritten = TJsonToken.PropertyName then
WriteIndent;
end;
end;
end;
procedure TJsonTextWriter.Close;
begin
inherited Close;
if CloseOutput and (FWriter <> nil) then
FWriter.Close;
end;
procedure TJsonTextWriter.EnsureBufferSize;
begin
if Length(FWriterBuffer) = 0 then
SetLength(FWriterBuffer, 64);
end;
procedure TJsonTextWriter.Flush;
begin
FWriter.Flush;
end;
procedure TJsonTextWriter.SetIndentation(Value: Integer);
begin
if Value < 0 then
raise EArgumentException.Create(SIdentationGreaterThanZero);
FIndentation := Value;
end;
procedure TJsonTextWriter.SetQuoteChar(Value: Char);
begin
if (Value <> '"') and (Value <> '''') then
raise EArgumentException.Create(SInvalidJavascriptQuote);
FQuoteChar := Value;
UpdateCharEscapeFlags;
end;
procedure TJsonTextWriter.SetStringEscapeHandling(Value: TJsonStringEscapeHandling);
begin
FStringEscapeHandling := Value;
UpdateCharEscapeFlags;
end;
procedure TJsonTextWriter.UpdateCharEscapeFlags;
begin
if StringEscapeHandling = TJsonStringEscapeHandling.EscapeHtml then
FCharEscapeFlags := TJsonTextUtils.HtmlCharEscapeFlags
else if FQuoteChar = '"' then
FCharEscapeFlags := TJsonTextUtils.DoubleQuoteCharEscapeFlags
else
FCharEscapeFlags := TJsonTextUtils.SingleQuoteCharEscapeFlags;
end;
procedure TJsonTextWriter.WriteComment(const Comment: string);
begin
InternalWriteComment;
FWriter.Write('/*');
FWriter.Write(Comment);
FWriter.Write('*/');
end;
procedure TJsonTextWriter.WriteEnd(const Token: TJsonToken);
procedure ErrorInvalidToken;
begin
raise EJsonWriterException.Create(Self, Format(SInvalidJsonToken, [GetName(Token)]));
end;
begin
case Token of
TJsonToken.EndObject:
FWriter.Write('}');
TJsonToken.EndArray:
FWriter.Write(']');
TJsonToken.EndConstructor:
FWriter.Write(')');
else
ErrorInvalidToken;
end;
end;
procedure TJsonTextWriter.WriteEscapedString(const Value: string; Quote: Boolean);
begin
EnsureBufferSize;
TJsonTextUtils.WriteEscapedString(FWriter, Value, FQuoteChar, Quote,
FCharEscapeFlags, StringEscapeHandling, TCharArray(FWriterBuffer));
end;
procedure TJsonTextWriter.WriteIndent;
var
CurrentIndentCount, WriteCount: Integer;
begin
FWriter.WriteLine;
CurrentIndentCount := Top * FIndentation;
while CurrentIndentCount > 0 do
begin
WriteCount := Min(CurrentIndentCount, 10);
FWriter.Write(FIndentChar, WriteCount);
Dec(CurrentIndentCount, WriteCount);
end;
end;
procedure TJsonTextWriter.WriteIndentSpace;
begin
FWriter.Write(' ');
end;
procedure TJsonTextWriter.WriteNull;
begin
InternalWriteValue(TJsonToken.Null);
WriteValueInternal(JsonNull, TJsonToken.Null);
end;
procedure TJsonTextWriter.WritePropertyName(const Name: string; Escape: Boolean);
begin
InternalWritePropertyName(Name);
if Escape then
WriteEscapedString(Name, FQuoteName)
else
begin
if FQuoteName then
FWriter.Write(FQuoteChar);
FWriter.Write(Name);
if FQuoteName then
FWriter.Write(FQuoteChar);
end;
FWriter.Write(':');
end;
procedure TJsonTextWriter.WritePropertyName(const Name: string);
begin
InternalWritePropertyName(Name);
WriteEscapedString(Name, FQuoteName);
FWriter.Write(':');
end;
procedure TJsonTextWriter.WriteRaw(const Json: string);
begin
FWriter.Write(Json);
end;
procedure TJsonTextWriter.WriteStartArray;
begin
InternalWriteStart(TJsonToken.StartArray, TJsonContainerType.Array);
FWriter.Write('[');
end;
procedure TJsonTextWriter.WriteStartConstructor(const Name: string);
begin
InternalWriteStart(TJsonToken.StartConstructor, TJsonContainerType.&Constructor);
FWriter.Write('new ');
FWriter.Write(Name);
FWriter.Write('(');
end;
procedure TJsonTextWriter.WriteStartObject;
begin
InternalWriteStart(TJsonToken.StartObject, TJsonContainerType.Object);
FWriter.Write('{');
end;
procedure TJsonTextWriter.WriteUndefined;
begin
inherited WriteUndefined;
case ExtendedJsonMode of
TJsonExtendedJsonMode.None,
TJsonExtendedJsonMode.MongoShell:
WriteValueInternal(JsonUndefined, TJsonToken.Undefined);
TJsonExtendedJsonMode.StrictMode:
begin
FWriter.Write('{');
FWriter.Write(FQuoteChar);
FWriter.Write(JsonExtUndefinedPropertyName);
FWriter.Write(FQuoteChar);
FWriter.Write(':');
FWriter.Write(JsonTrue);
FWriter.Write('}');
end;
end;
end;
procedure TJsonTextWriter.WriteValue(const Value: string);
begin
inherited WriteValue(Value);
if (Length(Value) = 0) and (EmptyValueHandling = TJsonEmptyValueHandling.Null) then
Exit;
WriteEscapedString(Value, True);
end;
procedure TJsonTextWriter.WriteValue(const Value: TValue);
begin
WriteValue(Self, Value);
end;
procedure TJsonTextWriter.WriteValue(Value: Extended);
var
Str: string;
begin
inherited WriteValue(Value);
if Value.IsPositiveInfinity then
Str := JsonPositiveInfinity
else if Value.IsNegativeInfinity then
Str := JsonNegativeInfinity
else if Value.IsNan then
Str := JsonNaN
else
Str := FloatToStr(Value, FFormatSettings);
if (FloatFormatHandling = TJsonFloatFormatHandling.Symbol) or not (Value.IsInfinity or Value.IsNan) then
// nothing
else
if FloatFormatHandling = TJsonFloatFormatHandling.DefaultValue then
Str := '0.0'
else
Str := QuoteChar + Str + QuoteChar;
FWriter.Write(Str);
end;
procedure TJsonTextWriter.WriteValue(Value: Single);
var
Str: string;
begin
inherited WriteValue(Value);
if Value.IsPositiveInfinity then
Str := JsonPositiveInfinity
else if Value.IsNegativeInfinity then
Str := JsonNegativeInfinity
else if Value.IsNan then
Str := JsonNaN
else
Str := FloatToStr(Value, FFormatSettings);
if (FloatFormatHandling = TJsonFloatFormatHandling.Symbol) or not (Value.IsInfinity or Value.IsNan) then
// nothing
else
if FloatFormatHandling = TJsonFloatFormatHandling.DefaultValue then
Str := '0.0'
else
Str := QuoteChar + Str + QuoteChar;
FWriter.Write(Str);
end;
procedure TJsonTextWriter.WriteValue(Value: Double);
var
Str: string;
begin
inherited WriteValue(Value);
if Value.IsPositiveInfinity then
Str := JsonPositiveInfinity
else if Value.IsNegativeInfinity then
Str := JsonNegativeInfinity
else if Value.IsNan then
Str := JsonNaN
else
Str := FloatToStr(Value, FFormatSettings);
if (FloatFormatHandling = TJsonFloatFormatHandling.Symbol) or not (Value.IsInfinity or Value.IsNan) then
// nothing
else
if FloatFormatHandling = TJsonFloatFormatHandling.DefaultValue then
Str := '0.0'
else
Str := QuoteChar + Str + QuoteChar;
FWriter.Write(Str);
end;
procedure TJsonTextWriter.WriteValue(Value: Boolean);
begin
inherited WriteValue(Value);
if Value then
FWriter.Write(JsonTrue)
else
FWriter.Write(JsonFalse);
end;
procedure TJsonTextWriter.WriteValue(Value: UInt32);
begin
inherited WriteValue(Value);
FWriter.Write(UIntToStr(Value));
end;
procedure TJsonTextWriter.WriteNumberLong(const ANum: string);
begin
case ExtendedJsonMode of
TJsonExtendedJsonMode.None:
FWriter.Write(ANum);
TJsonExtendedJsonMode.StrictMode:
begin
FWriter.Write('{');
FWriter.Write(FQuoteChar);
FWriter.Write(JsonExtNumberLongPropertyName);
FWriter.Write(FQuoteChar);
FWriter.Write(':');
FWriter.Write(FQuoteChar);
FWriter.Write(ANum);
FWriter.Write(FQuoteChar);
FWriter.Write('}');
end;
TJsonExtendedJsonMode.MongoShell:
begin
FWriter.Write('NumberLong(');
FWriter.Write(FQuoteChar);
FWriter.Write(ANum);
FWriter.Write(FQuoteChar);
FWriter.Write(')');
end;
end;
end;
procedure TJsonTextWriter.WriteValue(Value: Int64);
begin
inherited WriteValue(Value);
WriteNumberLong(IntToStr(Value));
end;
procedure TJsonTextWriter.WriteValue(Value: UInt64);
begin
inherited WriteValue(Value);
WriteNumberLong(UIntToStr(Value));
end;
procedure TJsonTextWriter.WriteValue(const Value: TGUID);
begin
inherited WriteValue(Value);
FWriter.Write(FQuoteChar);
FWriter.Write(Value.ToString);
FWriter.Write(FQuoteChar);
end;
procedure TJsonTextWriter.WriteValue(const Value: TBytes;
BinaryType: TJsonBinaryType = TJsonBinaryType.Generic);
var
LBase64Enc: TBase64Encoding;
LBase64: string;
begin
inherited WriteValue(Value);
if (Length(Value) = 0) and (EmptyValueHandling = TJsonEmptyValueHandling.Null) then
Exit;
LBase64Enc := TBase64Encoding.Create(0, '');
try
LBase64 := LBase64Enc.EncodeBytesToString(Value);
finally
LBase64Enc.Free;
end;
case ExtendedJsonMode of
TJsonExtendedJsonMode.None:
begin
FWriter.Write(FQuoteChar);
FWriter.Write(LBase64);
FWriter.Write(FQuoteChar);
end;
TJsonExtendedJsonMode.StrictMode:
begin
FWriter.Write('{');
FWriter.Write(FQuoteChar);
FWriter.Write(JsonExtBinaryPropertyName);
FWriter.Write(FQuoteChar);
FWriter.Write(':');
FWriter.Write(FQuoteChar);
FWriter.Write(LBase64);
FWriter.Write(FQuoteChar);
FWriter.Write(',');
FWriter.Write(FQuoteChar);
FWriter.Write(JsonExtTypePropertyName);
FWriter.Write(FQuoteChar);
FWriter.Write(':');
FWriter.Write(FQuoteChar);
FWriter.Write(IntToStr(Integer(BinaryType)));
FWriter.Write(FQuoteChar);
FWriter.Write('}');
end;
TJsonExtendedJsonMode.MongoShell:
begin
FWriter.Write('BinData(');
FWriter.Write(IntToStr(Integer(BinaryType)));
FWriter.Write(',');
FWriter.Write(FQuoteChar);
FWriter.Write(LBase64);
FWriter.Write(FQuoteChar);
FWriter.Write(')');
end;
end;
end;
procedure TJsonTextWriter.WriteValue(const Value: TJsonOid);
begin
InternalWriteValue(TJsonToken.Oid);
case ExtendedJsonMode of
TJsonExtendedJsonMode.None:
begin
FWriter.Write(FQuoteChar);
FWriter.Write(Value.AsString);
FWriter.Write(FQuoteChar);
end;
TJsonExtendedJsonMode.StrictMode:
begin
FWriter.Write('{');
FWriter.Write(FQuoteChar);
FWriter.Write(JsonExtOidPropertyName);
FWriter.Write(FQuoteChar);
FWriter.Write(':');
FWriter.Write(FQuoteChar);
FWriter.Write(Value.AsString);
FWriter.Write(FQuoteChar);
FWriter.Write('}');
end;
TJsonExtendedJsonMode.MongoShell:
begin
FWriter.Write('ObjectId(');
FWriter.Write(FQuoteChar);
FWriter.Write(Value.AsString);
FWriter.Write(FQuoteChar);
FWriter.Write(')');
end;
end;
end;
procedure TJsonTextWriter.WriteValue(Value: Char);
begin
InternalWriteValue(TJsonToken.String);
WriteEscapedString(Value, True);
end;
procedure TJsonTextWriter.WriteValue(Value: Byte);
begin
InternalWriteValue(TJsonToken.Integer);
FWriter.Write(UIntToStr(Value));
end;
procedure TJsonTextWriter.WriteValue(Value: TDateTime);
begin
InternalWriteValue(TJsonToken.Date);
case ExtendedJsonMode of
TJsonExtendedJsonMode.None:
begin
FWriter.Write(QuoteChar);
case DateFormatHandling of
TJsonDateFormatHandling.Iso:
FWriter.Write(DateToISO8601(Value, DateTimeZoneHandling = TJsonDateTimeZoneHandling.Utc));
TJsonDateFormatHandling.Unix:
FWriter.Write(DateTimeToUnix(Value, DateTimeZoneHandling = TJsonDateTimeZoneHandling.Utc));
TJsonDateFormatHandling.FormatSettings:
if DateTimeZoneHandling = TJsonDateTimeZoneHandling.Local then
FWriter.Write(DateTimeToStr(TTimezone.Local.ToLocalTime(Value), FormatSettings))
else
FWriter.Write(DateTimeToStr(Value, FormatSettings));
end;
FWriter.Write(QuoteChar);
end;
TJsonExtendedJsonMode.StrictMode:
begin
FWriter.Write('{');
FWriter.Write(FQuoteChar);
FWriter.Write(JsonExtDatePropertyName);
FWriter.Write(FQuoteChar);
FWriter.Write(':');
FWriter.Write(FQuoteChar);
FWriter.Write(DateToISO8601(Value, DateTimeZoneHandling = TJsonDateTimeZoneHandling.Utc));
FWriter.Write(FQuoteChar);
FWriter.Write('}');
end;
TJsonExtendedJsonMode.MongoShell:
begin
FWriter.Write('ISODate(');
FWriter.Write(FQuoteChar);
FWriter.Write(DateToISO8601(Value, DateTimeZoneHandling = TJsonDateTimeZoneHandling.Utc));
FWriter.Write(FQuoteChar);
FWriter.Write(')');
end;
end;
end;
procedure TJsonTextWriter.WriteValue(Value: Integer);
begin
InternalWriteValue(TJsonToken.Integer);
FWriter.Write(IntToStr(Value));
end;
procedure TJsonTextWriter.WriteValue(const Value: TJsonRegEx);
begin
InternalWriteValue(TJsonToken.RegEx);
case ExtendedJsonMode of
TJsonExtendedJsonMode.None,
TJsonExtendedJsonMode.MongoShell:
begin
FWriter.Write(FQuoteChar);
FWriter.Write('/');
WriteEscapedString(Value.RegEx, False);
FWriter.Write('/');
WriteEscapedString(Value.Options, False);
FWriter.Write(FQuoteChar);
end;
TJsonExtendedJsonMode.StrictMode:
begin
FWriter.Write('{');
FWriter.Write(FQuoteChar);
FWriter.Write(JsonExtRegexPropertyName);
FWriter.Write(FQuoteChar);
FWriter.Write(':');
WriteEscapedString(Value.RegEx, True);
FWriter.Write(',');
FWriter.Write(FQuoteChar);
FWriter.Write(JsonExtOptionsPropertyName);
FWriter.Write(FQuoteChar);
FWriter.Write(':');
WriteEscapedString(Value.Options, True);
FWriter.Write('}');
end;
end;
end;
procedure TJsonTextWriter.WriteValue(const Value: TJsonDBRef);
begin
InternalWriteValue(TJsonToken.DBRef);
case ExtendedJsonMode of
TJsonExtendedJsonMode.None:
begin
FWriter.Write(FQuoteChar);
if Value.DB <> '' then begin
FWriter.Write(Value.DB);
FWriter.Write('.');
end;
FWriter.Write(Value.Ref);
FWriter.Write('.');
FWriter.Write(Value.Id.AsString);
FWriter.Write(FQuoteChar);
end;
TJsonExtendedJsonMode.StrictMode:
begin
FWriter.Write('{');
FWriter.Write(FQuoteChar);
FWriter.Write(JsonExtRefPropertyName);
FWriter.Write(FQuoteChar);
FWriter.Write(':');
FWriter.Write(FQuoteChar);
FWriter.Write(Value.Ref);
FWriter.Write(FQuoteChar);
FWriter.Write(',');
FWriter.Write(FQuoteChar);
FWriter.Write(JsonExtIdPropertyName);
FWriter.Write(FQuoteChar);
FWriter.Write(':');
FWriter.Write(FQuoteChar);
FWriter.Write(Value.Id.AsString);
FWriter.Write(FQuoteChar);
if Value.DB <> '' then begin
FWriter.Write(',');
FWriter.Write(FQuoteChar);
FWriter.Write(JsonExtDbPropertyName);
FWriter.Write(FQuoteChar);
FWriter.Write(':');
FWriter.Write(FQuoteChar);
FWriter.Write(Value.DB);
FWriter.Write(FQuoteChar);
end;
FWriter.Write('}');
end;
TJsonExtendedJsonMode.MongoShell:
begin
FWriter.Write('DBRef(');
FWriter.Write(FQuoteChar);
FWriter.Write(Value.Ref);
FWriter.Write(FQuoteChar);
FWriter.Write(',');
FWriter.Write(FQuoteChar);
FWriter.Write(Value.Id.AsString);
FWriter.Write(FQuoteChar);
FWriter.Write(')');
end;
end;
end;
procedure TJsonTextWriter.WriteValue(const Value: TJsonCodeWScope);
var
i: Integer;
begin
InternalWriteValue(TJsonToken.CodeWScope);
case ExtendedJsonMode of
TJsonExtendedJsonMode.None,
TJsonExtendedJsonMode.MongoShell:
begin
FWriter.Write(FQuoteChar);
FWriter.Write(Value.Code);
FWriter.Write(FQuoteChar);
end;
TJsonExtendedJsonMode.StrictMode:
begin
FWriter.Write('{');
FWriter.Write(FQuoteChar);
FWriter.Write(JsonExtCodePropertyName);
FWriter.Write(FQuoteChar);
FWriter.Write(':');
FWriter.Write(FQuoteChar);
FWriter.Write(Value.Code);
FWriter.Write(FQuoteChar);
if Length(Value.Scope) > 0 then begin
FWriter.Write(',');
FWriter.Write(FQuoteChar);
FWriter.Write(JsonExtScopePropertyName);
FWriter.Write(FQuoteChar);
FWriter.Write(':');
FWriter.Write('{');
for i := 0 to Length(Value.Scope) - 1 do begin
FWriter.Write(FQuoteChar);
FWriter.Write(Value.Scope[i].ident);
FWriter.Write(FQuoteChar);
FWriter.Write(':');
FWriter.Write(FQuoteChar);
FWriter.Write(Value.Scope[i].value);
FWriter.Write(FQuoteChar);
end;
FWriter.Write('}');
end;
FWriter.Write('}');
end;
end;
end;
procedure TJsonTextWriter.WriteMinKey;
begin
InternalWriteValue(TJsonToken.MinKey);
case ExtendedJsonMode of
TJsonExtendedJsonMode.None,
TJsonExtendedJsonMode.MongoShell:
FWriter.Write('MinKey');
TJsonExtendedJsonMode.StrictMode:
begin
FWriter.Write('{');
FWriter.Write(FQuoteChar);
FWriter.Write(JsonExtMinKeyPropertyName);
FWriter.Write(FQuoteChar);
FWriter.Write(':');
FWriter.Write('1');
FWriter.Write('}');
end;
end;
end;
procedure TJsonTextWriter.WriteMaxKey;
begin
InternalWriteValue(TJsonToken.MaxKey);
case ExtendedJsonMode of
TJsonExtendedJsonMode.None,
TJsonExtendedJsonMode.MongoShell:
FWriter.Write('MaxKey');
TJsonExtendedJsonMode.StrictMode:
begin
FWriter.Write('{');
FWriter.Write(FQuoteChar);
FWriter.Write(JsonExtMaxKeyPropertyName);
FWriter.Write(FQuoteChar);
FWriter.Write(':');
FWriter.Write('1');
FWriter.Write('}');
end;
end;
end;
procedure TJsonTextWriter.WriteValueDelimiter;
begin
FWriter.Write(',');
end;
procedure TJsonTextWriter.WriteValueInternal(const Value: string; Token: TJsonToken);
begin
FWriter.Write(Value);
end;
procedure TJsonTextWriter.WriteWhitespace(const Ws: string);
procedure ErrorNotWhitespace;
begin
raise EJsonWriterException.Create(Self, SWhitespaceOnly);
end;
begin
if not TJsonTextUtils.IsWhiteSpace(Ws) then
ErrorNotWhitespace;
FWriter.Write(Ws);
end;
{ TJsonObjectWriter }
procedure TJsonObjectWriter.AppendContainer(const JSONValue: TJSONValue);
begin
AppendValue(JSONValue);
FContainerStack.Push(JSONValue);
end;
procedure TJsonObjectWriter.AppendValue(const JsonValue: TJSONValue);
var
LParent: TJSONAncestor;
begin
if FRoot = nil then
FRoot := JsonValue
else
begin
if FContainerStack.Count = 0 then
begin
if FOwnValue then
FRoot.Free;
FRoot := JsonValue;
end;
end;
if FContainerStack.Count > 0 then
begin
LParent := FContainerStack.Peek;
if LParent is TJSONPair then
begin
TJSONPair(LParent).JsonValue := JsonValue;
FContainerStack.Pop;
end
else if LParent is TJSONArray then
TJSONArray(LParent).AddElement(JsonValue)
end;
end;
constructor TJsonObjectWriter.Create(OwnValue: Boolean);
begin
inherited Create;
FOwnValue := OwnValue;
FContainerStack := TStack<TJSONAncestor>.Create;
FDateFormatHandling := TJsonDateFormatHandling.Iso;
end;
destructor TJsonObjectWriter.Destroy;
begin
if FCurrentState <> TState.Closed then
Close;
FContainerStack.Free;
if FOwnValue and (FRoot <> nil) then
FRoot.Free;
inherited Destroy;
end;
procedure TJsonObjectWriter.Rewind;
begin
inherited;
FContainerStack.Clear;
if FOwnValue and (FRoot <> nil) then
FRoot.Free;
FRoot := nil;
end;
procedure TJsonObjectWriter.WriteEnd(const Token: TJsonToken);
procedure ErrorInvalidToken;
begin
raise EJsonWriterException.Create(Self, Format(SInvalidJsonToken, [GetName(Token)]));
end;
begin
case Token of
TJsonToken.EndObject,
TJsonToken.EndArray:
FContainerStack.Pop;
else
ErrorInvalidToken;
end;
end;
procedure TJsonObjectWriter.WriteNull;
begin
inherited WriteNull;
AppendValue(TJSONNull.Create);
end;
procedure TJsonObjectWriter.WritePropertyName(const Name: string);
var
JSONPair: TJSONPair;
begin
inherited WritePropertyName(Name);
JSONPair := TJSONPair.Create(Name, nil);
if FRoot = nil then
FRoot := JSONPair
else
TJSONObject(FContainerStack.Peek).AddPair(JSONPair);
FContainerStack.Push(JSONPair);
end;
procedure TJsonObjectWriter.WriteRaw(const Json: string);
begin
raise EJsonWriterException.Create(SUnsupportedJSONValueRaw);
end;
procedure TJsonObjectWriter.WriteRawValue(const Json: string);
begin
raise EJsonWriterException.Create(SUnsupportedJSONValueRaw);
end;
procedure TJsonObjectWriter.WriteStartArray;
begin
inherited WriteStartArray;
AppendContainer(TJSONArray.Create);
end;
procedure TJsonObjectWriter.WriteStartConstructor(const Name: string);
begin
raise EJsonWriterException.Create(SUnsupportedJSONValueConstructor);
end;
procedure TJsonObjectWriter.WriteStartObject;
begin
inherited WriteStartObject;
AppendContainer(TJSONObject.Create);
end;
procedure TJsonObjectWriter.WriteUndefined;
begin
WriteNull;
end;
procedure TJsonObjectWriter.WriteValue(Value: Int64);
begin
inherited WriteValue(Value);
AppendValue(TJSONNumber.Create(Value));
end;
procedure TJsonObjectWriter.WriteValue(Value: UInt64);
begin
inherited WriteValue(Value);
AppendValue(TJSONNumber.Create(Value));
end;
procedure TJsonObjectWriter.WriteValue(Value: Single);
begin
inherited WriteValue(Value);
AppendValue(TJSONNumber.Create(Value));
end;
procedure TJsonObjectWriter.WriteValue(const Value: string);
begin
inherited WriteValue(Value);
if (Length(Value) = 0) and (EmptyValueHandling = TJsonEmptyValueHandling.Null) then
Exit;
AppendValue(TJSONString.Create(Value));
end;
procedure TJsonObjectWriter.WriteValue(Value: Integer);
begin
inherited WriteValue(Value);
AppendValue(TJSONNumber.Create(Value));
end;
procedure TJsonObjectWriter.WriteValue(Value: UInt32);
begin
inherited WriteValue(Value);
AppendValue(TJSONNumber.Create(Value));
end;
procedure TJsonObjectWriter.WriteValue(Value: Double);
begin
inherited WriteValue(Value);
AppendValue(TJSONNumber.Create(Value));
end;
procedure TJsonObjectWriter.WriteValue(const Value: TGUID);
begin
inherited WriteValue(Value);
AppendValue(TJSONString.Create(Value.ToString));
end;
procedure TJsonObjectWriter.WriteValue(Value: TDateTime);
var
StrDate: string;
IntDate: Int64;
begin
inherited WriteValue(Value);
StrDate := '';
case DateFormatHandling of
TJsonDateFormatHandling.Iso:
begin
StrDate := DateToISO8601(Value, DateTimeZoneHandling = TJsonDateTimeZoneHandling.Utc);
AppendValue(TJSONString.Create(StrDate));
end;
TJsonDateFormatHandling.Unix:
begin
IntDate := DateTimeToUnix(Value, DateTimeZoneHandling = TJsonDateTimeZoneHandling.Utc);
AppendValue(TJSONNumber.Create(IntDate));
end;
TJsonDateFormatHandling.FormatSettings:
begin
if DateTimeZoneHandling = TJsonDateTimeZoneHandling.Local then
StrDate := DateTimeToStr(TTimezone.Local.ToLocalTime(Value), FormatSettings)
else
StrDate := DateTimeToStr(Value, FormatSettings);
AppendValue(TJSONString.Create(StrDate));
end;
end;
end;
procedure TJsonObjectWriter.WriteValue(const Value: TBytes; BinaryType: TJsonBinaryType = TJsonBinaryType.Generic);
var
LBase64Enc: TBase64Encoding;
LBase64: string;
begin
inherited WriteValue(Value, BinaryType);
if (Length(Value) = 0) and (EmptyValueHandling = TJsonEmptyValueHandling.Null) then
Exit;
LBase64Enc := TBase64Encoding.Create(0, '');
try
LBase64 := LBase64Enc.EncodeBytesToString(Value);
finally
LBase64Enc.Free;
end;
AppendValue(TJSONString.Create(LBase64));
end;
procedure TJsonObjectWriter.WriteValue(Value: Boolean);
begin
inherited WriteValue(Value);
AppendValue(TJSONBool.Create(Value));
end;
procedure TJsonObjectWriter.WriteValue(Value: Extended);
begin
inherited WriteValue(Value);
AppendValue(TJSONNumber.Create(Value));
end;
procedure TJsonObjectWriter.WriteValue(Value: Byte);
begin
inherited WriteValue(Value);
AppendValue(TJSONNumber.Create(Value));
end;
procedure TJsonObjectWriter.WriteValue(Value: Char);
begin
inherited WriteValue(Value);
AppendValue(TJSONString.Create(Value));
end;
procedure TJsonObjectWriter.WriteValue(const Value: TJsonRegEx);
begin
inherited WriteValue(Value);
WriteStartObject;
WritePropertyName(JsonExtRegexPropertyName);
WriteValue(Value.RegEx);
WritePropertyName(JsonExtOptionsPropertyName);
WriteValue(Value.Options);
WriteEnd(TJsonToken.EndObject);
end;
procedure TJsonObjectWriter.WriteValue(const Value: TJsonOid);
begin
inherited WriteValue(Value);
WriteStartObject;
WritePropertyName(JsonExtOidPropertyName);
WriteValue(Value.AsBytes);
WriteEnd(TJsonToken.EndObject);
end;
procedure TJsonObjectWriter.WriteValue(const Value: TJsonCodeWScope);
var
I: Integer;
begin
inherited WriteValue(Value);
WriteStartObject;
WritePropertyName(JsonExtCodePropertyName);
WriteValue(Value.Code);
if Length(Value.Scope) > 0 then
begin
WritePropertyName(JsonExtScopePropertyName);
WriteStartObject;
for I := 0 to Length(Value.Scope) do
begin
WritePropertyName(Value.Scope[I].Ident);
WriteValue(Value.Scope[I].Value);
end;
WriteEnd(TJsonToken.EndObject);
end;
WriteEnd(TJsonToken.EndObject);
end;
procedure TJsonObjectWriter.WriteValue(const Value: TJsonDBRef);
begin
inherited WriteValue(Value);
WriteStartObject;
WritePropertyName(JsonExtRefPropertyName);
WriteValue(Value.Ref);
WritePropertyName(JsonExtIdPropertyName);
WriteValue(Value.Id.AsBytes);
if Value.DB <> '' then
begin
WritePropertyName(JsonExtDbPropertyName);
WriteValue(Value.DB);
end;
WriteEnd(TJsonToken.EndObject);
end;
procedure TJsonObjectWriter.WriteMinKey;
begin
inherited WriteMinKey;
WriteStartObject;
WritePropertyName(JsonExtMinKeyPropertyName);
WriteValue(1);
WriteEnd(TJsonToken.EndObject);
end;
procedure TJsonObjectWriter.WriteMaxKey;
begin
inherited WriteMinKey;
WriteStartObject;
WritePropertyName(JsonExtMaxKeyPropertyName);
WriteValue(1);
WriteEnd(TJsonToken.EndObject);
end;
function TJsonObjectWriter.GetContainer: TJSONValue;
begin
if FContainerStack.Count > 0 then
Result := FContainerStack.Peek as TJSONValue
else
Result := nil;
end;
procedure TJsonObjectWriter.SetContainer(const Value: TJSONValue);
var
LContainer: TJSONAncestor;
begin
LContainer := Container;
if LContainer = Value then
Exit;
if LContainer <> nil then
begin
FContainerStack.Pop;
if LContainer <> FRoot then
LContainer.Free;
end;
AppendContainer(Value);
end;
end.
|
unit u_xpl_listener;
{==============================================================================
UnitName = uxPLListener
UnitDesc = xPL Listener object and function
UnitCopyright = GPL by Clinique / xPL Project
==============================================================================
1.00 : Added Prerequisite modules handling
1.01 : *** TODO : applications has up to 6 seconds to answer an HBeatRequest,
*** the module should take this in account to decide that prereq are not met
}
{$mode objfpc}{$H+}
interface
uses Classes
, SysUtils
, u_xpl_common
, u_configuration_record
, u_xPL_Message
, u_xPL_Config
, u_xPL_Body
, u_xpl_custom_listener
, u_xpl_heart_beater
;
type // TxPLListener ==========================================================
TxPLListener = class(TxPLCustomListener)
protected
fDiscovered : TConfigurationRecordList;
private
fPrereqList : TStringList;
function Is_PrereqMet: boolean;
public
OnxPLPrereqMet : TNoParamEvent; // Called when needed modules has been seen on the xPL network
constructor Create(const aOwner : TComponent); dynamic; overload;
destructor destroy; override;
procedure Set_ConnectionStatus(const aValue : TConnectionStatus); override;
property PrereqList : TStringList read fPrereqList;
property PrereqMet : boolean read Is_PrereqMet;
function DoHBeatApp (const aMessage : TxPLMessage) : boolean; override;
function DeviceAddress (const aDevice : string) : string;
procedure DoxPLPrereqMet ; dynamic;
procedure OnDie(Sender : TObject); dynamic;
end;
implementation // =============================================================
uses u_xpl_header
, u_xpl_schema
, u_xpl_messages
;
const K_MSG_PREREQ_MET = 'All required modules found';
K_MSG_PREREQ_PROBING = 'Probing for presence of required modules : %s';
// TxPLListener ===============================================================
constructor TxPLListener.Create(const aOwner : TComponent);
begin
inherited;
fPrereqList := TStringList.Create;
fDiscovered := TConfigurationRecordList.Create;
Config.FilterSet.Add('xpl-stat.*.*.*.hbeat.app'); // Add mine
Config.FilterSet.Add('xpl-stat.*.*.*.hbeat.end');
Config.FilterSet.Add('xpl-stat.*.*.*.config.app');
end;
destructor TxPLListener.destroy;
begin
fPrereqList.Free;
fDiscovered.Free;
inherited;
end;
procedure TxPLListener.DoxPLPrereqMet;
begin
Log(etInfo,K_MSG_PREREQ_MET);
if Assigned(OnxPLPrereqMet) then OnxPLPrereqMet;
end;
procedure TxPLListener.Set_ConnectionStatus(const aValue : TConnectionStatus);
begin
if aValue = connectionStatus then exit;
inherited;
if (ConnectionStatus = connected) and (not PrereqMet) and (Config.IsValid) then begin
Log(etInfo,K_MSG_PREREQ_PROBING,[PrereqList.CommaText]);
SendHBeatRequestMsg;
end;
end;
function TxPLListener.Is_PrereqMet : boolean;
begin
result := (PrereqList.Count = 0);
end;
procedure TxPLListener.OnDie(Sender: TObject);
var Config_Elmt : TConfigurationRecord;
begin
Config_Elmt := TConfigurationRecord(Sender);
fDiscovered.Remove(Config_Elmt.Address.Device);
Config_Elmt.Free;
end;
{------------------------------------------------------------------------
DoHBeatApp :
Transfers the message to the application only if the message completes
required tests : has to be of xpl-stat type and the
schema has to be hbeat.app
IN : the message to test and transmit
OUT : result indicates wether the message has been transmitted or not
------------------------------------------------------------------------}
function TxPLListener.DoHBeatApp(const aMessage: TxPLMessage): boolean;
var i : integer;
begin
result := false;
with aMessage do begin
if IsLifeSign then begin
i := fDiscovered.IndexOf(Source.Device);
if (i=-1)
then fDiscovered.Add(Source.Device, TConfigurationRecord.Create(self,THeartBeatMsg(aMessage),@OnDie))
else fDiscovered.Data[i].HBeatReceived(THeartBeatMsg(aMessage));
if Schema.Equals(Schema_HBeatApp) then begin
if not PrereqMet then begin
i := PrereqList.IndexOf(Source.Device);
if i<>-1 then begin
PrereqList.Delete(i);
if PrereqMet then DoxPLPrereqMet;
end;
end;
if Assigned(OnxPLHBeatApp) and not Source.Equals(Adresse) then begin
OnxPLHBeatApp( aMessage);
result := true;
end;
end;
end;
end;
end;
function TxPLListener.DeviceAddress(const aDevice: string): string;
var i : integer;
begin
if fDiscovered.Find(aDevice,i) then Result := fDiscovered.Data[i].Address.RawxPL
else Result := '';
end;
end.
|
unit emrinject;
{$mode delphi}
interface
uses
Classes, SysUtils, winhooks;
const
{$IFDEF CPUX86}
HookDLLName = 'emrhook.dll';
{$ELSE}
HookDLLName = 'emrhook64.dll';
{$ENDIF}
AppTitle = 'Exemusic Recorder';
type
{ TEMRThread }
TEMRThread = class(TThread)
private
FFinished: Boolean;
FTargetExe,
FTargetArgs,
FError: ansistring;
FSimpleInject: Boolean;
FSettings: THookSettings;
protected
procedure Execute; override;
public
constructor Create(TargetExe, TargetArgs: ansistring; Settings: THookSettings; SimpleInject: Boolean = False);
property Error: ansistring read FError;
property Finished: Boolean read FFinished;
end;
{ return values for GetHookDLLStatus }
THookDLLStatus = (dtUsable, dtNotFound, dtInvalidVersion);
function GetHookDLLStatus: THookDLLStatus;
implementation
uses
dllinject,
Windows;
type
THookDLLVersionProc = function: longword; cdecl;
function GetHookDLLStatus: THookDLLStatus;
var
Handle: HINST;
VersionProc: THookDLLVersionProc;
s: ansistring;
begin
result:=dtNotFound;
s:=ExtractFilePath(Paramstr(0)) + HookDLLName;
Handle:=LoadLibrary(PChar(s));
if Handle = 0 then
Exit;
result:=dtInvalidVersion;
VersionProc:=GetProcAddress(Handle, 'GetVersion');
if Assigned(VersionProc) then
begin
if VersionProc() = WinHookVersion then
result:=dtUsable;
end;
FreeLibrary(Handle);
end;
{ TEMRThread }
procedure TEMRThread.Execute;
begin
try
if Trim(FTargetExe) = '' then
raise Exception.Create('No target exe specified');
injectLoader(FTargetExe, FTargetArgs, ExtractFilePath(Paramstr(0))+HookDLLName, 'StartHook', @FSettings, SizeOf(FSettings), FSimpleInject);
except
on e: Exception do
FError:=e.Message;
end;
FFinished:=True;
end;
constructor TEMRThread.Create(TargetExe, TargetArgs: ansistring;
Settings: THookSettings; SimpleInject: Boolean);
begin
FFinished:=False;
FTargetExe:=TargetExe;
FTargetArgs:=TargetArgs;
FSettings:=Settings;
FreeOnTerminate:=False;
FSimpleInject:=SimpleInject;
inherited Create(False);
end;
end.
|
program Aleatorio;
uses crt;
const
MAX_CANTIDAD_SERIES = 4;
MAX_TEMPORADAS_POR_SERIE = 5;
MAX_EPISODIOS_POR_TEMPORADA = 5;
type
{Estructura de datos de las series}
trVideo = record
titulo : string[72];
descripcion : string[234];
duracionEnSegundos : longint;
visualizaciones : longint;
end;
tvVideo = array[1..MAX_EPISODIOS_POR_TEMPORADA] of trVideo;
trTemp = record
anioDeEmision : string[4];
cantEpiDeTemp : byte;
vVideo:tvVideo;
end;
tvTemp = array[1..MAX_TEMPORADAS_POR_SERIE] of trTemp;
trSerie = record
nombre : string[71];
descripcion : string[140];
cantTemp : byte;
vTemp : tvTemp;
end;
tvSerie = array[1..MAX_CANTIDAD_SERIES] of trSerie;
tmlvSerie : tmlogico;
tmlogico : integer;
procedure GenerarVisualizaciones(var vSerie:tvSerie;var vTemp:tvTemp;var vVideo:tvVideo);
var
i,j,k,aux:byte;
begin
randomize;
aux:=0;
for i:=1 to MAX_CANTIDAD_SERIES do
begin
for j:=1 to MAX_TEMPORADAS_POR_SERIE do
begin
for k:=1 to MAX_EPISODIOS_POR_TEMPORADA do
begin
aux:=random(101);
if(aux<61) then
aux:=0;
if(aux>61)and(aux<81) then
aux:=1;
if(aux>81)and(aux<91) then
aux:=2;
if(aux>91)and(aux<96) then
aux:=3;
if(aux>96)and(aux<99) then
aux:=4;
if(aux=99) then
aux:=5;
if(aux=100) then
aux:=150;
vSerie[i].vTemp[j].vVideo[k].visualizaciones:=aux;
writeln(vSerie[i].vTemp[j].vVideo[k].visualizaciones);
end;
end;
end;
end;
procedure Inicializar(var vSerie:tvSerie;var vTemp:tvTemp;var vVideo:tvVideo);
var
i,j,k:byte;
begin
i:=1;
j:=1;
k:=1;
while (i<=MAX_CANTIDAD_SERIES)do
begin
vSerie[i].nombre:='0';
vSerie[i].descripcion:='0';
vSerie[i].cantTemp:=0;
while(j<=MAX_TEMPORADAS_POR_SERIE)do
begin
vTemp[j].anioDeEmision:='0';
vTemp[j].cantEpideTemp:=0;
while(k<=MAX_EPISODIOS_POR_TEMPORADA)do
begin
vVideo[k].titulo:='0';
vVideo[k].descripcion:='0';
vVideo[k].duracionEnSegundos:=0;
vVideo[k].visualizaciones:=0;
inc(k);
end;
inc(j);
end;
inc(i);
end;
end;
var
vVideo:tvVideo;
vSerie:tvSerie;
vTemp:tvTemp;
begin
clrscr;
Inicializar(vSerie,vTemp,vVideo);
Writeln('BIENVENIDOS A NETFLIX');
writeln('CANTIDAD DE VISUALIZACIONES HECHAS');
GenerarVisualizaciones(vSerie,vTemp,vVideo);
writeln();
readkey;
end.
|
unit iaExample.ConsumerThread;
interface
uses
System.Classes,
System.Generics.Collections;
type
TConsumerState = (ConsumerWorking,
ConsumerDone,
ConsumerAbortedWithException);
TExampleLinkedConsumerThread = class(TThread)
private
fTaskQueue:TThreadedQueue<TObject>;
fQueueTimeout:Cardinal;
fThreadState:TConsumerState;
fTasksConsumed:Integer;
fTasksUnderflow:Integer;
fQueueFailures:Integer;
public
constructor Create(const pTaskQueue:TThreadedQueue<TObject>; const pQueueTimeout:Cardinal);
procedure Execute(); override;
property ThreadState:TConsumerState read fThreadState write fThreadState;
property TasksConsumed:Integer read fTasksConsumed write fTasksConsumed;
property TasksUnderflow:Integer read fTasksUnderflow write fTasksUnderflow;
property QueueFailures:Integer read fQueueFailures write fQueueFailures;
end;
implementation
uses
System.SysUtils,
System.SyncObjs,
System.RTTI,
iaExample.TaskData,
iaTestSupport.Log;
constructor TExampleLinkedConsumerThread.Create(const pTaskQueue:TThreadedQueue<TObject>; const pQueueTimeout:Cardinal);
const
CreateSuspendedParam = False;
begin
self.FreeOnTerminate := False;
fTaskQueue := pTaskQueue;
fQueueTimeout := pQueueTimeout;
inherited Create(CreateSuspendedParam);
end;
procedure TExampleLinkedConsumerThread.Execute();
var
vPopResult:TWaitResult;
vDataItem:TExampleTaskData;
begin
NameThreadForDebugging('ExampleLinkedConsumer_' + FormatDateTime('hhnnss.zzzz', Now));
try
while (not self.Terminated) and (not fTaskQueue.ShutDown) do
begin
vPopResult := fTaskQueue.PopItem(TObject(vDataItem));
if (vPopResult = wrSignaled) then
begin
if Assigned(vDataItem) then
begin
Inc(fTasksConsumed);
vDataItem.Free();
end
else if not fTaskQueue.ShutDown then
begin
LogIt('PopItem failed to return object');
Int(fQueueFailures);
end;
//else: queue signal to shut down
end
else if (vPopResult = wrTimeout) then
begin
if fQueueTimeout = INFINITE then
begin
//shouldn't get here
LogIt('PopItem logic failure: Queue timeout was INFINITE but the Pop resulted in Timeout');
Inc(fQueueFailures);
end
else
begin
//queue caught up, keep consuming
Inc(fTasksUnderflow);
end;
end
else
begin
LogIt('PopItem failed: ' + TRttiEnumerationType.GetName(vPopResult));
Inc(fQueueFailures);
end;
end;
fThreadState := TConsumerState.ConsumerDone;
except on E:Exception do
begin
LogIt('Consumer thread exception trapped: ' + E.Message);
fThreadState := TConsumerState.ConsumerAbortedWithException;
end;
end;
end;
end.
|
unit FormsUtil;
interface
uses
Vcl.Controls, RzDBCmbo, RzDBGrid, RzGrids, DB, RzLstBox, RzChkLst, Vcl.ExtCtrls,
System.Classes, RzCmboBx, IFinanceGlobal, Location, PaymentMethod;
procedure OpenDropdownDataSources(const parentCtrl: TWinControl;
const open: boolean = true);
procedure OpenGridDataSources(const parentCtrl: TWinControl;
const open: boolean = true);
procedure ButtonDown(Sender: TObject);
procedure ButtonUp(Sender: TObject);
procedure ExtendLastColumn(grid: TRzDBGrid); overload;
procedure ExtendLastColumn(grid: TRzStringGrid); overload;
procedure PopulateBranchComboBox(comboBox: TRzComboBox);
procedure PopulateComboBox(source: TDataSet; comboBox: TRzComboBox;
const codeField, nameField: string; const closeOpenSource: boolean = false); overload;
procedure PopulatePaymentMethodComboBox(comboBox: TRzComboBox; const bankWithdrawalOnly: boolean = false);
function FirstRow(grid: TRzStringGrid): boolean;
implementation
procedure OpenDropdownDataSources(const parentCtrl: TWinControl;
const open: boolean = true);
var
ctrlCnt: integer;
i: integer;
ds: TDataSet;
begin
ctrlCnt := parentCtrl.ControlCount - 1;
for i := 0 to ctrlCnt do
begin
if parentCtrl.Controls[i] is TRzDBLookupComboBox then
begin
if (parentCtrl.Controls[i] as TRzDBLookupComboBox).DataSource <> nil then
begin
ds := (parentCtrl.Controls[i] as TRzDBLookupComboBox).ListSource.DataSet;
ds.Close;
if open then
ds.Open;
end
end
end;
end;
procedure OpenGridDataSources(const parentCtrl: TWinControl;
const open: boolean = true);
var
ctrlCnt: integer;
i: integer;
ds: TDataSet;
begin
ctrlCnt := parentCtrl.ControlCount - 1;
for i := 0 to ctrlCnt do
begin
if parentCtrl.Controls[i] is TRzDBGrid then
begin
if (parentCtrl.Controls[i] as TRzDBGrid).DataSource <> nil then
begin
ds := (parentCtrl.Controls[i] as TRzDBGrid).DataSource.DataSet;
// remove filters
ds.Filter := '';
ds.Close;
if open then
ds.Open;
end
end
end;
end;
procedure ButtonDown(Sender: TObject);
begin
(Sender as TImage).Left := (Sender as TImage).Left + 1;
(Sender as TImage).Top := (Sender as TImage).Top + 1;
end;
procedure ButtonUp(Sender: TObject);
begin
(Sender as TImage).Left := (Sender as TImage).Left - 1;
(Sender as TImage).Top := (Sender as TImage).Top - 1;
end;
procedure ExtendLastColumn(grid: TRzDBGrid);
var
widths, i: integer;
begin
widths := 0;
// get total width
for i := 0 to grid.Columns.Count - 1 do widths := widths + grid.Columns[i].Width;
// add extra column
grid.Columns.Add;
//extend to the size of the grid
grid.Columns[grid.Columns.Count - 1].Width := grid.Width - widths + 5;
end;
procedure ExtendLastColumn(grid: TRzStringGrid);
var
widths, i: integer;
begin
widths := 0;
// get total width
for i := 0 to grid.ColCount - 1 do widths := widths + grid.ColWidths[i];
// add extra column
grid.ColCount := grid.ColCount + 1;
//extend to the size of the grid
grid.ColWidths[grid.ColCount - 1] := grid.Width - widths - 4;
end;
procedure PopulateBranchComboBox(comboBox: TRzComboBox);
var
i, cnt: integer;
begin
cnt := ifn.LocationCount - 1;
for i := 0 to cnt do
comboBox.AddItemValue(ifn.Locations[i].LocationName,ifn.Locations[i].LocationCode);
// set default
comboBox.FindItem(ifn.GetLocationNameByCode(ifn.LocationCode));
end;
procedure PopulateComboBox(source: TDataSet; comboBox: TRzComboBox;
const codeField, nameField: string; const closeOpenSource: boolean); overload;
begin
with source, comboBox do
begin
if closeOpenSource then source.Open;
DisableControls;
while not Eof do
begin
AddItemValue(FieldByName(nameField).AsString,FieldByName(codeField).AsString);
Next;
end;
if closeOpenSource then source.Close;
EnableControls;
end;
end;
procedure PopulatePaymentMethodComboBox(comboBox: TRzComboBox; const bankWithdrawalOnly: boolean);
var
i, cnt: integer;
begin
cnt := Length(pmtMethods) - 1;
for i := 0 to cnt do
begin
if not bankWithdrawalOnly then
begin
if pmtMethods[i].Method in [mdCash,mdCheck] then
comboBox.AddObject(pmtMethods[i].Name,TObject(pmtMethods[i]));
end
else begin
if pmtMethods[i].Method = mdBankWithdrawal then
comboBox.AddObject(pmtMethods[i].Name,TObject(pmtMethods[i]));
end;
end;
// set first item as default
comboBox.ItemIndex := 0;
end;
function FirstRow(grid: TRzStringGrid): boolean;
begin
with grid do
Result := (RowCount = FixedRows + 1) and (not Assigned(Objects[0,1]));
end;
end.
|
{===================}
{ ZXing is required }
{===================}
unit DataPak.Android.BarcodeScanner;
interface
uses
System.Classes
{$IFDEF ANDROID}
, FMX.Platform, FMX.Helpers.Android, System.RTTI, FMX.Types
, System.SysUtils, AndroidAPI.JNI.GraphicsContentViewText
, AndroidAPI.JNI.JavaTypes, FMX.StdCtrls, FMX.Edit, AndroidAPI.Helpers
{$ENDIF};
type
TBarcodeScannerResult = procedure(Sender: TObject; AResult: string) of object;
TBarcodeScannerAbort = procedure(Sender: TObject) of object;
[ComponentPlatformsAttribute(pidAndroid)]
TBarcodeScanner = class(TComponent)
public
type TBarcodeType = (btOneD, btQRCode, btProduct, btDataMatrix);
type TBarcodeTypes = set of TBarcodeType;
protected
FOnScanAbort: TBarcodeScannerAbort;
FOnScanResult: TBarcodeScannerResult;
FBarcodeTypes: TBarcodeTypes;
{$IFDEF ANDROID}
FClipboardService: IFMXClipboardService;
FPreservedClipboardValue: TValue;
FMonitorClipboard: Boolean;
const BarcodeTypeName: array [btOneD .. btDataMatrix] of string =
('ONE_D_MODE', 'QR_CODE_MODE', 'PRODUCT_MODE', 'DATA_MATRIX_MODE');
function HandleAppEvent(AAppEvent: TApplicationEvent; AContext: TObject): Boolean;
function GetScanCommand: string;
{$ENDIF}
public
procedure Scan;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property BarcodeTypes: TBarcodeTypes read FBarcodeTypes write FBarcodeTypes;
property OnScanAbort: TBarcodeScannerAbort read FOnScanAbort write FOnScanAbort;
property OnScanResult: TBarcodeScannerResult read FOnScanResult write FOnScanResult;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('DataPak Android Components', [TBarcodeScanner]);
end;
{ TBarcodeScanner }
constructor TBarcodeScanner.Create(AOwner: TComponent);
{$IFDEF ANDROID}
var
aFMXApplicationEventService: IFMXApplicationEventService;
{$ENDIF}
begin
inherited Create(AOwner);
{$IFDEF ANDROID}
FMonitorClipboard := False;
if not TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService,
IInterface(FClipboardService)) then
begin
FClipboardService := nil;
Log.d('Clipboard Service is not supported.');
end;
if TPlatformServices.Current.SupportsPlatformService(IFMXApplicationEventService,
IInterface(aFMXApplicationEventService)) then
aFMXApplicationEventService.SetApplicationEventHandler(HandleAppEvent)
else
Log.d('Application Event Service is not supported.');
{$ENDIF}
FBarcodeTypes := [btOneD, btQRCode, btProduct, btDataMatrix];
end;
destructor TBarcodeScanner.Destroy;
begin
inherited Destroy;
end;
procedure TBarcodeScanner.Scan;
{$IFDEF ANDROID}
var
Intent: JIntent;
{$ENDIF}
begin
{$IFDEF ANDROID}
if Assigned(FClipboardService) then
begin
FPreservedClipboardValue := FClipboardService.GetClipboard;
FMonitorClipboard := True;
FClipboardService.SetClipboard('');
Intent := TJIntent.JavaClass.Init(StringToJString('com.google.zxing.client.android.SCAN'));
with Intent do
begin
SetPackage(StringToJString('com.google.zxing.client.android'));
PutExtra(StringToJString('SCAN_MODE'), StringToJString(GetScanCommand));
end;
SharedActivityContext.StartActivity(Intent);
end;
{$ENDIF}
end;
{$IFDEF ANDROID}
function TBarcodeScanner.HandleAppEvent(AAppEvent:
TApplicationEvent; AContext: TObject): Boolean;
begin
Result := False;
if FMonitorClipboard and (AAppEvent = TApplicationEvent.aeBecameActive) then
begin
FMonitorClipboard := False;
if FClipboardService.GetClipboard.ToString <> '' then
if Assigned(FOnScanResult) then
FOnScanResult(Self, FClipboardService.GetClipboard.ToString)
else
else
if Assigned(FOnScanAbort) then
FOnScanAbort(Self);
FClipboardService.SetClipboard(FPreservedClipboardValue);
Result := True;
end;
end;
function TBarcodeScanner.GetScanCommand: string;
var
BarcodeType: TBarcodeType;
begin
Result := '';
for BarcodeType in FBarcodeTypes do
Result := Result + ',' + BarcodeTypeName[BarcodeType];
end;
{$ENDIF}
end.
|
unit BrickCamp.Repositories.IQuestion;
interface
uses
System.JSON,
BrickCamp.Model.TQuestion;
type
IQuestionRepository = interface(IInterface)
['{7F4F7450-E7AF-4CD5-9B69-1FA0A99E09E9}']
function GetOne(const Id: Integer): TQuestion;
function GetList: TJSONArray;
procedure Insert(const Question: TQuestion);
procedure Update(const Question: TQuestion);
procedure Delete(const Id: Integer);
function GetListByProductId(const ProductId: Integer): TJSONArray;
end;
implementation
end.
|
unit TestuFuncionarioController;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, Vcl.Forms, System.Generics.Collections, uFuncionario,
uDependente,
uFuncionarioController;
type
// Test methods for class TFuncionarioController
TestTFuncionarioController = class(TTestCase)
strict private
FFuncionarioController: TFuncionarioController;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestCalcularImpostoIR;
procedure TestCalcularImpostoINSS;
procedure TestCalcularImpostoINSSSemDependetes;
procedure TestCalcularImpostoIRSemDependetes;
end;
implementation
procedure TestTFuncionarioController.SetUp;
begin
FFuncionarioController := TFuncionarioController.Create;
end;
procedure TestTFuncionarioController.TearDown;
begin
FFuncionarioController.Free;
FFuncionarioController := nil;
end;
procedure TestTFuncionarioController.TestCalcularImpostoIR;
var
ReturnValue: Real;
oFuncionario: TFuncionario;
oDependente1: TDependente;
oDependente2: TDependente;
begin
oFuncionario := TFuncionario.Create;
oDependente1 := TDependente.Create;
oDependente2 := TDependente.Create;
try
oFuncionario.Salario := 1000;
oDependente1.IsCalculaIR := true;
oDependente2.IsCalculaIR := true;
oFuncionario.Dependentes.Add(oDependente1);
oFuncionario.Dependentes.Add(oDependente2);
FFuncionarioController.AdicionarFuncionario(oFuncionario);
ReturnValue := FFuncionarioController.CalcularImpostoIR;
CheckEquals(120, ReturnValue);
finally
oFuncionario.Free;
oFuncionario := nil;
end;
end;
procedure TestTFuncionarioController.TestCalcularImpostoINSS;
var
ReturnValue: Real;
oFuncionario: TFuncionario;
oDependente1: TDependente;
oDependente2: TDependente;
begin
oFuncionario := TFuncionario.Create;
oDependente1 := TDependente.Create;
oDependente2 := TDependente.Create;
try
oFuncionario.Salario := 1000;
oDependente1.IsCalculaINSS := true;
oDependente2.IsCalculaIR := true;
oFuncionario.Dependentes.Add(oDependente1);
oFuncionario.Dependentes.Add(oDependente2);
FFuncionarioController.AdicionarFuncionario(oFuncionario);
ReturnValue := FFuncionarioController.CalcularImpostoINSS;
CheckEquals(80, ReturnValue);
finally
oFuncionario.Free;
oFuncionario := nil;
end;
end;
procedure TestTFuncionarioController.TestCalcularImpostoINSSSemDependetes;
var
ReturnValue: Real;
oFuncionario: TFuncionario;
begin
oFuncionario := TFuncionario.Create;
try
oFuncionario.Salario := 1000;
FFuncionarioController.AdicionarFuncionario(oFuncionario);
ReturnValue := FFuncionarioController.CalcularImpostoINSS;
CheckEquals(0, ReturnValue);
finally
oFuncionario.Free;
oFuncionario := nil;
end;
end;
procedure TestTFuncionarioController.TestCalcularImpostoIRSemDependetes;
var
ReturnValue: Real;
oFuncionario: TFuncionario;
begin
oFuncionario := TFuncionario.Create;
try
oFuncionario.Salario := 1000;
FFuncionarioController.AdicionarFuncionario(oFuncionario);
ReturnValue := FFuncionarioController.CalcularImpostoIR;
CheckEquals(0, ReturnValue);
finally
oFuncionario.Free;
oFuncionario := nil;
end;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTFuncionarioController.Suite);
end.
|
/////////////////////////////////////////////////////////
// //
// FlexGraphics library //
// Copyright (c) 2002-2009, FlexGraphics software. //
// //
// FlexGraphics library file formats support //
// Scalable Vector Graphics (svg) files //
// //
/////////////////////////////////////////////////////////
unit FormatSvgFile;
{$I FlexDefs.inc}
interface
uses
Windows, Classes, Graphics, FlexBase, FlexFileFormats;
resourcestring
sSvgFileDescription = 'Scalable Vector Graphics';
type
TFlexSvgFormat = class(TFlexFileFormat)
protected
procedure RegisterSupportedExtensions; override;
procedure ExportSVG(AFlexPanel: TFlexPanel; AStream: TStream);
public
procedure ExportToStream(AStream: TStream; AFlexPanel: TFlexPanel;
const Extension: TFlexFileExtension; const AFileName: string); override;
end;
implementation
uses
SysUtils, StdCtrls, FlexProps, FlexPath, FlexControls, FlexUtils;
function FormatCoord(Coord: Integer): string;
var Module: integer;
begin
Result := IntToStr(Coord div PixelScaleFactor);
Module := Coord mod PixelScaleFactor;
if Module <> 0 then Result := Result + '.' + IntToStr(Module);
end;
function SVGColor(AColor: TColor; Braces: boolean = True): string;
begin
AColor:=ColorToRGB(AColor);
case AColor of
clBlack: Result := 'black';
clWhite: Result := 'white';
clRed: Result := 'red';
clGreen: Result := 'green';
clBlue: Result := 'blue';
clYellow: Result := 'yellow';
clGray: Result := 'gray';
clNavy: Result := 'navy';
clOlive: Result := 'olive';
clLime: Result := 'lime';
clTeal: Result := 'teal';
clSilver: Result := 'silver';
clPurple: Result := 'purple';
clFuchsia: Result := 'fuchsia';
clMaroon: Result := 'maroon';
else
Result := 'rgb(' +
IntToStr(GetRValue(AColor)) + ',' +
IntToStr(GetGValue(AColor)) + ',' +
IntToStr(GetBValue(AColor)) + ')';
end;
if Braces then result := '"' + result + '"';
end;
function PointToStr(X, Y: Integer): string;
begin
Result := FormatCoord(X) + ',' + FormatCoord(Y);
end;
function SVGPoints(const Left, Top: integer; const Points: TPointArray): string;
var t: Integer;
begin
Result := ' points="';
for t:=Low(Points) to High(Points) do
Result := Result +
PointToStr((Left + Points[t].X), (Top + Points[t].Y)) + ' ';
Result := Result + '"';
end;
function SVGPen(Pen: TPenProp; Braces: boolean = true): string;
var bc: string;
function PenStyle: string;
begin
case Pen.Style of
psDash : Result := '4, 2';
psDot : Result := '2, 2';
psDashDot : Result := '4, 2, 2, 2';
psDashDotDot : Result := '4, 2, 2, 2, 2, 2';
else Result := '';
end;
end;
begin
if Braces
then bc := '"'
else bc := '';
if Pen.Style = psClear then
Result := ' stroke=' + bc + 'none' + bc
else begin
Result := ' stroke=' + SVGColor(Pen.Color, Braces);
if Pen.Width > 1 then
Result := Result + ' stroke-width='+ bc + FormatCoord(Pen.Width) + bc;
if Pen.Style <> psSolid then
Result := Result + ' stroke-dasharray=' + bc + PenStyle + bc + ' '; // fill="none" breaks brush ??
end;
end;
function SVGBrushPen(Brush: TBrushProp; Pen: TPenProp = Nil;
Brushes: TStrings = Nil): string;
var
Control: TFlexControl;
Index: integer;
begin
if Assigned(Brushes) then begin
// Try to find brush style in list
Control := Brush.Owner.Owner as TFlexControl;
Index := Brushes.IndexOfObject(pointer(Control.IdProp.Value));
if Index >= 0 then begin
Result := 'fill:url(#' + Brushes[Index] +')';
if Result <> '' then Result := Format(' style="%s"', [Result]);
end;
end else
Index := -1;
if Index < 0 then
if Brush.Style <> bsClear then begin
Result := ' fill=' + SVGColor(Brush.Color);
if Brush.Color = clNone then
Result := Result + ' fill-opacity="0"';
end else
Result := ' fill="none"';
if Assigned(Pen) then Result := Result + SVGPen(Pen);
end;
function SVGFont(Font: TFontProp): string;
function GetFontName(const aName: string): string;
begin
if aName = '宋体' then
Result := 'SimSun'
else if aName = '黑体' then
Result := 'SimHei'
else if aName = '仿宋_GB2312' then
Result := 'FangSong_GB2312'
else if aName = '楷体_GB2312' then
Result := 'KaiTi_GB2312'
else if aName = '幼圆' then
Result := 'YouYuan'
else if aName = '华文宋体' then
Result := 'STSong'
else if aName = '华文中宋' then
Result := 'STZhongsong'
else if aName = '华文楷体' then
Result := 'STKaiti'
else if aName = '华文仿宋' then
Result := 'STFangsong'
else if aName = '华文细黑' then
Result := 'STXihei'
else if aName = '华文隶书' then
Result := 'STLiti'
else if aName = '华文行楷' then
Result := 'STXingkai'
else if aName = '华文新魏' then
Result := 'STXinwei'
else if aName = '华文琥珀' then
Result := 'STHupo'
else if aName = '华文彩云' then
Result := 'STCaiyun'
else if aName = '方正姚体简体' then
Result := 'FZYaoTi'
else if aName = '方正舒体简体' then
Result := 'FZShuTi'
else if aName = '新宋体' then
Result := 'NSimSun'
else if aName = '隶书' then
Result := 'LiSu'
else
Result := aName;
end;
begin
Result :=
' font-family="' + GetFontName(Font.Name) +
'" font-size="' + FormatCoord(Abs(Font.Size)) + 'pt" ';
if fsItalic in Font.Style then
Result := Result + ' font-style="italic"';
if fsBold in Font.Style then
Result := Result + ' font-weight="bold"';
if fsUnderline in Font.Style then
Result := Result + ' text-decoration="underline"'
else
if fsStrikeOut in Font.Style then
Result := Result + ' text-decoration="line-through"';
Result := Result + ' fill=' + SVGColor(Font.Color);
end;
function GetTextWidth(aFont: TFontProp; const aText: string): integer;
var
Bmp: TBitmap;
begin
Bmp := TBitmap.Create;
try
Bmp.Canvas.Font.Size := aFont.Size div 1000;
Bmp.Canvas.Font.Name := aFont.Name;
Bmp.Canvas.Font.Style := aFont.Style;
Bmp.Canvas.Font.Charset := aFont.Charset;
Result := Bmp.Canvas.TextWidth(aText);
finally
Bmp.Free;
end;
end;
function GetTextHeight(aFont: TFontProp; const aText: string): integer;
var
Bmp: TBitmap;
TM: TTextMetric;
begin
Bmp := TBitmap.Create;
try
Bmp.Canvas.Font.Size := aFont.Size div 1000;
Bmp.Canvas.Font.Name := aFont.Name;
Bmp.Canvas.Font.Style := aFont.Style;
Bmp.Canvas.Font.Charset := aFont.Charset;
Result := Bmp.Canvas.TextHeight(aText);
if GetTextMetrics(Bmp.Canvas.Handle, TM) then
dec(Result, TM.tmDescent); // Move to baseline
finally
Bmp.Free;
end;
end;
// TFlexSvgFormat /////////////////////////////////////////////////////////////
procedure TFlexSvgFormat.RegisterSupportedExtensions;
begin
RegisterExtension('svg', sSvgFileDescription, [skExport]);
end;
procedure TFlexSvgFormat.ExportToStream(AStream: TStream;
AFlexPanel: TFlexPanel; const Extension: TFlexFileExtension;
const AFileName: string);
begin
if CompareText(Extension.Extension, 'svg') <> 0 then begin
inherited;
exit;
end;
ExportSVG(AFlexPanel, AStream);
end;
procedure TFlexSvgFormat.ExportSVG;
var
List: TStrings;
str,LStr, StyleName: string;
Control: TFlexControl;
PassRec: TPassControlRec;
PO: TPaintOrder;
LayerIdx, ControlIdx: integer;
i,x,y,w,h,r: integer;
CurvePoints: TPointArray;
Prop: TCustomProp;
Brushes: TStringList;
StartColor, EndColor: TColor;
begin
Brushes := Nil;
List := TStringList.Create;
try
List.Add('<?xml version="1.0" encoding="UTF-8"?>');
List.Add('<svg width="' + IntToStr(AFlexPanel.DocWidth div 1000) +
'" height="' + IntToStr(AFlexPanel.DocHeight div 1000) + '">');
// SVG defs section
List.Add('<defs>');
try
Brushes := TStringList.Create;
Control := AFlexPanel.ActiveScheme;
FirstControl(Control, PassRec);
while Assigned(Control) do begin
// Check brush
Prop := Control.Props['Brush'];
if Assigned(Prop) and (Prop is TBrushProp) then
with TBrushProp(Prop) do
if not IsClear and IsPaintAlternate then begin
// Try add brush style
if (Method = bmGradient) and
(Control.IdProp.Value <> 0) then begin
// Create gradient brush
if GradStyle = gsElliptic
then LStr := 'radialGradient'
else LStr := 'linearGradient';
StyleName :=
Control.NameProp.Value +
IntToStr(Control.IdProp.Value) +
'_Brush';
str :=
'id="' + StyleName + '" gradientUnits="objectBoundingBox" ';
case GradStyle of
gsHorizontal : str := str + 'x1="0" y1="0" x2="1" y2="0"';
gsVertical : str := str + 'x1="0" y1="0" x2="0" y2="1"';
gsSquare : str := str + 'x1="0" y1="0" x2="0" y2="0"'; // NOT IMPLEMENTED
gsElliptic : str := str + 'cx="0.5" cy="0.5" r="0.5" fx="0.5" fy="0.5"';
gsTopLeft : str := str + 'x1="0" y1="0" x2="1" y2="1"';
gsTopRight : str := str + 'x1="1" y1="0" x2="0" y2="1"';
gsBottomLeft : str := str + 'x1="0" y1="1" x2="1" y2="0"';
gsBottomRight : str := str + 'x1="1" y1="1" x2="0" y2="0"';
end;
List.Add('<' + LStr + ' ' + str + '>');
if GradStyle = gsElliptic then begin
EndColor := GradBeginColor;
StartColor := GradEndColor;
end else begin
StartColor := GradBeginColor;
EndColor := GradEndColor;
end;
List.Add('<stop offset="0%" style="stop-color:' +
SVGColor(StartColor,false) + '; stop-opacity:1"/>');
List.Add('<stop offset="100%" style="stop-color:' +
SVGColor(EndColor,false) + '; stop-opacity:1"/>');
List.Add('</' + LStr + '>');
Brushes.AddObject(StyleName, pointer(Control.IdProp.Value));
end;
end;
// Next control
Control := NextControl(PassRec);
end;
ClosePassRec(PassRec);
finally
List.Add('</defs>');
end;
// Scheme background
List.Add(
'<rect x="0" y="0" width="' + IntToStr(AFlexPanel.DocWidth div 1000) +
'" height="' + IntToStr(AFlexPanel.DocHeight div 1000) + '"' +
SVGBrushPen(TFlexScheme(AFlexPanel.ActiveScheme).BrushProp, Nil, Brushes) +
//'" fill=' + SVGColor(TFlexScheme(Flex.ActiveScheme).BrushProp.Color) +
//' stroke=' + SVGColor(TFlexScheme(Flex.ActiveScheme).BrushProp.Color) +
' stroke="none" stroke-width="0" />');
// SVG graphics section
InitPaintOrder(PO);
try
AFlexPanel.ActiveScheme.CreatePaintOrder(PO);
for LayerIdx:=0 to High(PO.LayerRefs) do begin
ControlIdx := PO.LayerRefs[LayerIdx].First;
while ControlIdx >= 0 do begin
Control := PO.ControlRefs[ControlIdx].Control;
FirstControl(Control, PassRec);
while Assigned(Control) do begin
if Control is TFlexBox then with TFlexBox(Control) do begin
str :=
'<rect x = "' + IntToStr(DocRect.Left div 1000) +
'" y="' + IntToStr(DocRect.Top div 1000) +
'" width="' + IntToStr(Width div 1000) +
'" height="' + IntToStr(Height div 1000) + '" ' +
SVGBrushPen(BrushProp, PenProp, Brushes);
if RoundnessProp.Value > 0 then begin
r := RoundnessProp.Value div (2*PixelScaleFactor);
str := Format('%s rx="%d" ry="%d"', [str, r, r]);
end;
str := str + '/>';
List.Add(str);
if Control is TFlexText then with TFlexText(Control) do begin
x := DocRect.Left div 1000;
y := DocRect.Bottom div 1000;
w := Width div 1000 - GetTextWidth(FontProp, TextProp.Text);
h := Height div 1000 - GetTextHeight(FontProp, ' ');
case Alignment of
taRightJustify : x := x + w;
taCenter : x := x + w div 2;
end;
case Layout of
tlTop : y := y - h;
tlCenter : y := y - h div 2;
end;
str :=
'<text x="' + IntToStr(x) + '" y="' + IntToStr(y) + '"' +
SVGFont(FontProp) + '> ' + TextProp.Text + ' </text>';
List.Add(str);
end;
end else
if Control is TFlexEllipse then with TFlexEllipse(Control) do begin
str :=
'<ellipse cx = "' +
IntToStr((DocRect.Right - Width div 2) div 1000) +
'" cy="' + IntToStr((DocRect.Bottom - Height div 2) div 1000) +
'" rx="' + IntToStr(Width div 2000) +
'" ry="' + IntToStr(Height div 2000) + '" ' +
SVGBrushPen(BrushProp, PenProp, Brushes) + '/>';
List.Add(str);
end else
if Control is TFlexCurve then with TFlexCurve(Control) do begin
SetLength(CurvePoints, PointCount);
for i := 0 to PointCount-1 do
CurvePoints[i] := Points[i];
if IsSolidProp.Value then
Str := '<polygon ' + SVGBrushPen(BrushProp, PenProp, Brushes)
else
Str := '<polyline fill="none" marker-start="url(#arrow)"' +
SVGPen(PenProp);
str :=
str + SVGPoints(DocRect.Left, DocRect.Top, CurvePoints) + '/>';
List.Add(str);
end else
if Control is TFlexPicture then with TFlexPicture(Control) do begin
// TODO: Not implemented
end;
Control := NextControl(PassRec);
end;
ClosePassRec(PassRec);
ControlIdx := PO.ControlRefs[ControlIdx].Next;
end;
end;
finally
ClearPaintOrder(PO);
end;
List.Add('</svg>');
{$IFNDEF FG_D12}
List.Text := AnsiToUtf8(List.Text);
List.SaveToStream(AStream);
{$ELSE}
List.SaveToStream(AStream, TEncoding.UTF8);
{$ENDIF}
finally
List.Free;
Brushes.Free;
end;
end;
initialization
RegisteredFlexFileFormats.RegisterFormat(TFlexSvgFormat);
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FiltEdit;
interface
uses Windows, Messages, Classes, Graphics, Forms, Controls, Tabs,
Buttons, DesignIntf, DesignEditors, Grids, StdCtrls, ExtCtrls;
type
TFilterEditor = class(TForm)
Bevel1: TBevel;
OKButton: TButton;
CancelButton: TButton;
HelpButton: TButton;
procedure FormCreate(Sender: TObject);
procedure HelpBtnClick(Sender: TObject);
private
procedure SetFilter(Value: string);
function GetFilter: string;
end;
TFilterProperty = class(TStringProperty)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
implementation
uses SysUtils, DsnConst, LibHelp;
{$R *.dfm}
const
NameCol = 0;
FiltCol = 1;
FirstRow = 1;
var
FilterGrid: TStringGrid;
{ TFilterEditor }
procedure TFilterEditor.FormCreate(Sender: TObject);
begin
HelpContext := hcDFilterEditor;
FilterGrid := TStringGrid.Create(Self);
FilterGrid.BoundsRect := Bevel1.BoundsRect;
with FilterGrid do
begin
ColCount := 2;
FixedCols := 0;
RowCount := 25;
ScrollBars := ssVertical;
Options := [goFixedVertLine, goHorzLine, goVertLine, goEditing, goTabs,
goAlwaysShowEditor];
Parent := Self;
TabOrder := 1;
ColWidths[NameCol] := ClientWidth div 2;
ColWidths[FiltCol] := (ClientWidth div 2) - 1;
DefaultRowHeight := Canvas.TextHeight('W') + 2;
Cells[NameCol,0] := SFilterName;
Cells[FiltCol,0] := SFilter;
end;
ActiveControl := FilterGrid;
end;
function TFilterEditor.GetFilter: string;
var
I: Integer;
function EmptyRow: Boolean;
begin
Result := True;
with FilterGrid do
if (Cells[NameCol, I] <> '') or (Cells[FiltCol, I] <> '') then
Result := False;
end;
begin
Result := '';
with FilterGrid do
begin
for I := FirstRow to RowCount - 1 do
begin
if not EmptyRow then
begin
Result := Result+Cells[NameCol, I];
Result := Result+'|';
Result := Result+Cells[FiltCol, I];
Result := Result+'|';
end;
end;
end;
I := Length(Result);
if I > 0 then
while IsDelimiter('|', Result, I) do
begin
SetLength(Result, Length(Result) - 1);
Dec(I);
end;
end;
procedure TFilterEditor.SetFilter(Value: string);
var
Index: Byte;
r, c: Integer;
begin
if Value <> '' then
begin
r := FirstRow;
c := NameCol;
Index := AnsiPos('|', Value);
with FilterGrid do
begin
while Index > 0 do
begin
Cells[c, r] := Copy(Value, 1, Index - 1);
if c = FiltCol then
begin
c := NameCol;
if r = RowCount - 1 then
RowCount := RowCount + 1;
r := r + 1;
end
else c := FiltCol;
Delete(Value, 1, Index);
Index := AnsiPos('|', Value);
end;
Cells[c, r] := Copy(Value, 1, Length(Value));
end;
end;
end;
{ TFilterProperty }
procedure TFilterProperty.Edit;
var
FilterEditor: TFilterEditor;
begin
FilterEditor := TFilterEditor.Create(Application);
try
FilterEditor.SetFilter(GetValue);
FilterEditor.ShowModal;
if FilterEditor.ModalResult = mrOK then
SetValue(FilterEditor.GetFilter);
finally
FilterEditor.Free;
end;
end;
function TFilterProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paMultiSelect];
end;
procedure TFilterEditor.HelpBtnClick(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
end.
|
program HelloWorld;
var
length : real;
width : real;
height : real;
Volume : real;
begin
length := 7;
width := 5;
height := 3;
Volume:=(length * (height * width))/3;
writeln('The Volume of this Pyramid is ' , Volume);
writeln('This is test5')
end. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.