text stringlengths 14 6.51M |
|---|
{
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi
Copyright (c) 2016, Isaque Pinheiro
All rights reserved.
GNU Lesser General Public License
Versão 3, 29 de junho de 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
A todos é permitido copiar e distribuir cópias deste documento de
licença, mas mudá-lo não é permitido.
Esta versão da GNU Lesser General Public License incorpora
os termos e condições da versão 3 da GNU General Public License
Licença, complementado pelas permissões adicionais listadas no
arquivo LICENSE na pasta principal.
}
{ @abstract(ORMBr Framework.)
@created(12 Out 2016)
@author(Isaque Pinheiro <isaquepsp@gmail.com>)
@author(Skype : ispinheiro)
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi.
}
unit dbcbr.ddl.generator.mssql;
interface
uses
SysUtils,
StrUtils,
Generics.Collections,
dbebr.factory.interfaces,
dbcbr.ddl.register,
dbcbr.ddl.generator,
dbcbr.database.mapping;
type
TDDLSQLGeneratorMSSQL = class(TDDLSQLGenerator)
protected
public
function GenerateCreateTable(ATable: TTableMIK): string; override;
function GenerateCreateSequence(ASequence: TSequenceMIK): string; override;
function GenerateEnableForeignKeys(AEnable: Boolean): string; override;
function GenerateEnableTriggers(AEnable: Boolean): string; override;
end;
implementation
{ TDDLSQLGeneratorMSSQL }
function TDDLSQLGeneratorMSSQL.GenerateCreateSequence(ASequence: TSequenceMIK): string;
begin
Result := 'CREATE SEQUENCE %s AS int START WITH %s INCREMENT BY %s;';
Result := Format(Result, [ASequence.Name,
IntToStr(ASequence.InitialValue),
IntToStr(ASequence.Increment)]);
end;
function TDDLSQLGeneratorMSSQL.GenerateCreateTable(ATable: TTableMIK): string;
var
oSQL: TStringBuilder;
oColumn: TPair<string,TColumnMIK>;
begin
oSQL := TStringBuilder.Create;
Result := inherited GenerateCreateTable(ATable);
try
if ATable.Database.Schema <> '' then
oSQL.Append(Format(Result, [ATable.Database.Schema + '.' + ATable.Name]))
else
oSQL.Append(Format(Result, [ATable.Name]));
/// <summary>
/// Add Colunas
/// </summary>
for oColumn in ATable.FieldsSort do
begin
oSQL.AppendLine;
oSQL.Append(' ' + BuilderCreateFieldDefinition(oColumn.Value));
oSQL.Append(',');
end;
/// <summary>
/// Add PrimariKey
/// </summary>
if ATable.PrimaryKey.Fields.Count > 0 then
begin
oSQL.AppendLine;
oSQL.Append(BuilderPrimayKeyDefinition(ATable));
end;
/// <summary>
/// Add ForeignKey
/// </summary>
// if ATable.ForeignKeys.Count > 0 then
// begin
// oSQL.Append(',');
// oSQL.Append(BuilderForeignKeyDefinition(ATable));
// end;
/// <summary>
/// Add Checks
/// </summary>
if ATable.Checks.Count > 0 then
begin
oSQL.Append(',');
oSQL.Append(BuilderCheckDefinition(ATable));
end;
oSQL.AppendLine;
oSQL.Append(');');
/// <summary>
/// Add Indexe
/// </summary>
if ATable.IndexeKeys.Count > 0 then
oSQL.Append(BuilderIndexeDefinition(ATable));
oSQL.AppendLine;
Result := oSQL.ToString;
finally
oSQL.Free;
end;
end;
function TDDLSQLGeneratorMSSQL.GenerateEnableForeignKeys(AEnable: Boolean): string;
begin
if AEnable then
Result := 'EXEC sp_MSforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all";'
else
Result := 'EXEC sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all";';
end;
function TDDLSQLGeneratorMSSQL.GenerateEnableTriggers(AEnable: Boolean): string;
begin
if AEnable then
Result := 'EXEC sp_MSforeachtable "ALTER TABLE ? ENABLE TRIGGER ALL";'
else
Result := 'EXEC sp_MSforeachtable "ALTER TABLE ? DISABLE TRIGGER ALL";';
end;
initialization
TSQLDriverRegister.GetInstance.RegisterDriver(dnMSSQL, TDDLSQLGeneratorMSSQL.Create);
end.
|
unit uCompany;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uBase, StdCtrls, Buttons, ExtCtrls, ShellAPI, uApp;
type
TfrmCompany = class(TfrmBase)
img: TImage;
Label3: TLabel;
Label1: TLabel;
edtName: TEdit;
Label2: TLabel;
edtLinkMan: TEdit;
Label4: TLabel;
edtLawMan: TEdit;
Label5: TLabel;
edtAddr: TEdit;
Label6: TLabel;
edtTel: TEdit;
Label8: TLabel;
edtUrl: TEdit;
Label9: TLabel;
edtMail: TEdit;
Label10: TLabel;
meoDes: TMemo;
Label11: TLabel;
edtPostCode: TEdit;
procedure edtUrlDblClick(Sender: TObject);
procedure edtMailDblClick(Sender: TObject);
private
{ Private declarations }
FCompany: TCompany;
protected
procedure LoadData; override;
procedure SaveData; override;
public
{ Public declarations }
end;
var
frmCompany: TfrmCompany;
function ShowCompany(ACompany: TCompany): Boolean;
implementation
uses uGlobal;
{$R *.dfm}
function ShowCompany(ACompany: TCompany): Boolean;
begin
with TfrmCompany.Create(Application.MainForm) do
begin
HelpHtml := 'company.html';
try
FCompany := ACompany;
LoadData();
Result := ShowModal() = mrOk;
finally
Free;
end;
end;
end;
{ TfrmCompany }
procedure TfrmCompany.LoadData;
begin
with FCompany do
begin
edtName.Text := Name;
edtLinkMan.Text := LinkMan;
edtLawMan.Text := LawMan;
edtAddr.Text := Address;
edtPostCode.Text := PostCode;
edtTel.Text := Tel;
edtUrl.Text := HomePage;
edtMail.Text := EMail;
meoDes.Text := Description;
end;
end;
procedure TfrmCompany.SaveData;
begin
with FCompany do
begin
Name := edtName.Text;
LinkMan := edtLinkMan.Text;
LawMan := edtLawMan.Text;
Address := edtAddr.Text;
PostCode := edtPostCode.Text;
Tel := edtTel.Text;
HomePage := edtUrl.Text;
EMail := edtMail.Text;
Description := meoDes.Text;
SaveToIni();
end;
Log.Write(App.UserID + '更新单位信息');
end;
procedure TfrmCompany.edtUrlDblClick(Sender: TObject);
begin
ShellExecute(Handle, 'open', PAnsiChar(edtUrl.Text), nil, nil, SW_SHOW);
end;
procedure TfrmCompany.edtMailDblClick(Sender: TObject);
begin
ShellExecute(Handle, 'open', PAnsiChar('mailto:' + edtMail.Text), nil, nil, SW_SHOW);
end;
end.
|
unit Aurelius.Schema.MSSQL;
{$I Aurelius.Inc}
interface
uses
Aurelius.Drivers.Interfaces,
Aurelius.Schema.AbstractImporter,
Aurelius.Sql.Metadata;
type
TMSSQLSchemaImporter = class(TAbstractSchemaImporter)
strict protected
procedure GetDatabaseMetadata(Connection: IDBConnection; Database: TDatabaseMetadata); override;
end;
TMSSQLSchemaRetriever = class(TSchemaRetriever)
strict private
procedure GetTables;
procedure GetColumns;
procedure GetPrimaryKeys;
procedure GetUniqueKeys;
procedure GetForeignKeys;
procedure GetFieldDefinition(Column: TColumnMetadata; ADataType: String;
ASize, APrecision, AScale: Integer);
public
procedure RetrieveDatabase; override;
end;
implementation
uses
SysUtils,
Aurelius.Schema.Register;
{ TMSSQLSchemaImporter }
procedure TMSSQLSchemaImporter.GetDatabaseMetadata(Connection: IDBConnection;
Database: TDatabaseMetadata);
var
Retriever: TSchemaRetriever;
begin
Retriever := TMSSQLSchemaRetriever.Create(Connection, Database);
try
Retriever.RetrieveDatabase;
finally
Retriever.Free;
end;
end;
{ TMSSQLSchemaRetriever }
procedure TMSSQLSchemaRetriever.GetColumns;
begin
RetrieveColumns(
'select t.name as TABLE_NAME, '#13#10+
'SCHEMA_NAME(t.schema_id) as TABLE_OWNER, '#13#10+
'c.name as COLUMN_NAME, '#13#10+
'd.name as DATA_TYPE, '#13#10+
'c.max_length as CHAR_LENGTH, '#13#10+
'convert(int, OdbcPrec(c.system_type_id, c.max_length, c.precision)) as NUMERIC_PRECISION, '#13#10+
'c.scale as NUMERIC_SCALE, '#13#10+
'c.is_nullable as IS_NULLABLE, '#13#10+
'c.is_identity as IS_IDENTITY '#13#10+
'from sys.columns c, sys.types d, sys.tables t '#13#10+
'where c.user_type_id = d.user_type_id and c.object_id = t.object_id '#13#10+
'order by SCHEMA_NAME(t.schema_id), t.name, c.column_id',
procedure (Column: TColumnMetadata; ResultSet: IDBResultSet)
begin
Column.NotNull := not AsBoolean(ResultSet.GetFieldValue('IS_NULLABLE'));
Column.AutoGenerated := AsBoolean(ResultSet.GetFieldValue('IS_IDENTITY'));
GetFieldDefinition(Column,
ResultSet.GetFieldValue('DATA_TYPE'),
AsInteger(ResultSet.GetFieldValue('CHAR_LENGTH')),
AsInteger(ResultSet.GetFieldValue('NUMERIC_PRECISION')),
AsInteger(ResultSet.GetFieldValue('NUMERIC_SCALE'))
);
end);
end;
procedure TMSSQLSchemaRetriever.GetFieldDefinition(Column: TColumnMetadata;
ADataType: String; ASize, APrecision, AScale: Integer);
const
vNoSizeTypes : array[0..22] of string =
('bigint', 'bit', 'date', 'datetime', 'float', 'image', 'int', 'money', 'ntext',
'real', 'smalldatetime', 'smallint', 'smallmoney', 'sql_variant',
'sysname', 'text', 'timestamp', 'tinyint', 'uniqueidentifier', 'xml',
'geometry', 'hierarchyid', 'geography');
function NeedSize: Boolean;
var
I: Integer;
begin
for i := 0 to high(vNoSizeTypes) do
if vNoSizeTypes[I] = ADataType then
Exit(false);
Result := true;
end;
begin
Column.DataType := ADataType;
ADataType := LowerCase(ADataType);
if NeedSize then
begin
if (ASize = -1) and (
(ADatatype = 'nvarchar') or
(ADatatype = 'varbinary') or
(ADatatype = 'varchar')
) then
begin
Column.DataType := Column.DataType + '(MAX)';
end
else
if (ADataType = 'decimal') or (ADataType = 'numeric') then
begin
Column.DataType := 'numeric';
Column.Precision := APrecision;
Column.Scale := AScale;
end
else
if (ADataType = 'nchar') or (ADataType = 'nvarchar') then
begin
Column.Length := APrecision;
end
else
if (ADataType = 'datetime2') or (ADataType = 'datetimeoffset') or
(ADataType = 'time') then
begin
// Just keep the size 0
end else
Column.Length := ASize;
end;
end;
procedure TMSSQLSchemaRetriever.GetForeignKeys;
begin
RetrieveForeignKeys(
'SELECT '+
' O1.name AS PK_TABLE_NAME, '+
' C1.name AS PK_COLUMN_NAME, '+
' O2.name AS FK_TABLE_NAME, '+
' C2.name AS FK_COLUMN_NAME, '+
' F.name AS CONSTRAINT_NAME '+
' FROM sys.all_objects O1, '+
' sys.all_objects O2, '+
' sys.all_columns C1, '+
' sys.all_columns C2, '+
' sys.foreign_keys F '+
' INNER JOIN sys.foreign_key_columns K '+
' ON (K.constraint_object_id = F.object_id) '+
' WHERE O1.object_id = F.referenced_object_id '+
' AND O2.object_id = F.parent_object_id '+
' AND C1.object_id = F.referenced_object_id '+
' AND C2.object_id = F.parent_object_id '+
' AND C1.column_id = K.referenced_column_id '+
' AND C2.column_id = K.parent_column_id '+
' AND K.constraint_object_id = F.object_id '+
' ORDER BY O2.name, F.name, K.constraint_column_id');
end;
procedure TMSSQLSchemaRetriever.GetPrimaryKeys;
begin
RetrievePrimaryKeys(
'SELECT kcu.TABLE_NAME, kcu.CONSTRAINT_NAME, kcu.COLUMN_NAME, kcu.ORDINAL_POSITION '+
'FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS as tc '+
'INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE as kcu '+
'ON kcu.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA '+
'AND kcu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME '+
'AND kcu.TABLE_SCHEMA = tc.TABLE_SCHEMA '+
'AND kcu.TABLE_NAME = tc.TABLE_NAME '+
'WHERE tc.CONSTRAINT_TYPE = ''PRIMARY KEY'' '+
'ORDER BY kcu.TABLE_NAME, tc.CONSTRAINT_TYPE, kcu.CONSTRAINT_NAME, kcu.ORDINAL_POSITION');
end;
procedure TMSSQLSchemaRetriever.GetUniqueKeys;
begin
RetrieveUniqueKeys(
'SELECT kcu.TABLE_NAME, kcu.CONSTRAINT_NAME, kcu.COLUMN_NAME, kcu.ORDINAL_POSITION '+
'FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS as tc '+
'INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE as kcu '+
'ON kcu.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA '+
'AND kcu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME '+
'AND kcu.TABLE_SCHEMA = tc.TABLE_SCHEMA '+
'AND kcu.TABLE_NAME = tc.TABLE_NAME '+
'WHERE tc.CONSTRAINT_TYPE = ''UNIQUE'' '+
'ORDER BY kcu.TABLE_NAME, tc.CONSTRAINT_TYPE, kcu.CONSTRAINT_NAME, kcu.ORDINAL_POSITION');
end;
procedure TMSSQLSchemaRetriever.GetTables;
begin
RetrieveTables(
'SELECT t.name as TABLE_NAME '+
'FROM sys.tables t '+
'WHERE t.is_ms_shipped = 0 '+
'ORDER BY t.name');
end;
procedure TMSSQLSchemaRetriever.RetrieveDatabase;
begin
Database.Clear;
GetTables;
GetColumns;
GetPrimaryKeys;
GetUniqueKeys;
GetForeignKeys;
end;
initialization
TSchemaImporterRegister.GetInstance.RegisterImporter('MSSQL', TMSSQLSchemaImporter.Create);
end.
|
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
{+ +}
{+ Filename : FileIO.pas +}
{+ Date : 18.05.2004 +}
{+ Last Edit: 26.05.2004 +}
{+ Part of : VierGewinnt in Pascal +}
{+ Von Michael Contento und Florian Rubel +}
{+ +}
{+ Author : Michael Contento +}
{+ Email : MichaelContento (at) web (dot) de +}
{+ +}
{+ +}
{+ Info : Alle Programteile die auf Dateien zugreifen. +}
{+ +}
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
Unit FileIO;
{~~~~~~~~~~~}
{ Interface }
{~~~~~~~~~~~}
Interface
{ Units }
Uses TypDef;
{ Type }
{ Type }
{ Konstanten }
{ Const }
{ Variablen }
{ Var }
{ Prozeduren / Funktionen }
Procedure SaveGame (var Spielfeld : SpielfeldArray;
var Spielmodus : string;
var Spieler : integer );
Function LoadGame (var SpielArt : string;
var Spielfeld : SpielfeldArray;
var Spieler : integer ) : boolean;
Procedure SaveHighscore(var Punkte : integer;
var Gewinner : integer;
var SpielArt : string );
{Function LoadHighscore(Zeile : integer) : HighscoreStruktur;}
{~~~~~~~~~~~~~~~~}
{ Implementation }
{~~~~~~~~~~~~~~~~}
Implementation
{~~~~~~~~~~~~~~~~~~~~~~}
{ Spielstand Speichern }
{~~~~~~~~~~~~~~~~~~~~~~}
Procedure SaveGame (var Spielfeld : SpielfeldArray;
var Spielmodus : string;
var Spieler : integer );
var SaveFile : text; { Datei die gespeichert wird ist eine textdatei :) }
x : 1..7; { x Koordinate }
y : 1..6; { y Koordinate }
begin
{ File init }
assign(SaveFile, 'Game.sav');
rewrite(SaveFile);
{ Daten Schreiben }
writeln(SaveFile, Spielmodus);
writeln(SaveFile, Spieler);
for y := 1 to 6 do
for x := 1 to 7 do
writeln(SaveFile, Spielfeld[y,x]);
{ SEHR wichtigen Info Block ans SaveGame anhängen! ;) }
writeln(SaveFile, '------------------------------------------------------------------');
writeln(SaveFile, ' ');
writeln(SaveFile, 'VierGewinnt 2004 von Michael Contento (Core) & Florian Rubel (Gui)');
writeln(SaveFile, ' - Danke fürs Spielen :) - ');
writeln(SaveFile, ' ');
writeln(SaveFile, 'Denkt dran! Cheater haben einen kleinen (oder keinen) Schwanz! ;) ');
writeln(SaveFile, ' ');
writeln(SaveFile, ' www.dazed-confused.de.vu ');
{ File Close }
Close(SaveFile);
end;
{~~~~~~~~~~~~~~~~~~}
{ Spielstand Laden }
{~~~~~~~~~~~~~~~~~~}
Function LoadGame (var SpielArt : string;
var Spielfeld : SpielfeldArray;
var Spieler : integer ) : boolean;
var SaveFile : text; { Datei die gespeichert wird ist eine textdatei :) }
x : 1..7; { x Koordinate }
y : 1..6; { y Koordinate }
begin
{$I-}
{ File init }
assign(SaveFile, 'Game.sav');
reset(SaveFile);
{ Daten Lesen }
readln(SaveFile, SpielArt);
readln(SaveFile, Spieler);
for y := 1 to 6 do
for x := 1 to 7 do
readln(SaveFile, Spielfeld[y,x]);
{ File Close }
Close(SaveFile);
{$I+}
{ Wenn die Datei nicht existiert fehler ausgeben }
if IOResult <> 0 then LoadGame := false
else LoadGame := true;
end;
{~~~~~~~~~~~~~~~~~~~~~}
{ Highscore Speichern }
{~~~~~~~~~~~~~~~~~~~~~}
Procedure SaveHighscore (var Punkte : integer;
var Gewinner : integer;
var SpielArt : string );
var SaveFile : file of HighscoreStruktur;
Highscore : HighscoreStruktur;
begin
{ Nur wenn ein Mensch mitspielt kommts in die Liste }
if SpielArt <> 'ComputerVsComputer' then
begin
{ File init }
assign(SaveFile, 'Score.sav');
{$I-}
reset(SaveFile);
{$I+}
{ Wann das öffnen fehlschlug neu erstellen }
if IOResult <> 0 then
rewrite(SaveFile);
{ Daten zum schreiben festlegen }
Highscore.Punkte := Punkte; { Punkte }
Highscore.Gewinner := Gewinner; { Gewinner }
Highscore.SpielArt := SpielArt; { Spielart }
{ Daten schreiben und zugriff beenden }
write(SaveFile, Highscore);
close(SaveFile);
end;
end;
{~~~~~~~~~~~~~~~~~}
{ Highscore Laden }
{~~~~~~~~~~~~~~~~~}
{Function LoadHighscore (Zeile : integer) : HighscoreStruktur;
{var SaveFile : file of HighscoreStruktur;
{ Highscore : HighscoreStruktur;
{begin
{ {$I-}
{ { File Init }
{ assign(SaveFile, 'Score.sav');
{ reset(SaveFile);
{
{ { Gewünschten eintrag suchen }
{ seek(SaveFile, (Zeile - 1)); { Zeile - 1 weil seek bei 0 anfängt und nich bei 1 }
{
{ { Daten einlesen }
{ read(SaveFile, Highscore);
{
{ { Datei schließen }
{ close(SaveFile);
{ {$I+}
{
{ { Wenns es einen Fehler gab "leer" zurückgeben }
{ if IOResult <> 0 then
{ begin
{ Highscore.Punkte := 0;
{ Highscore.Gewinner := 0;
{ Highscore.SpielArt := 'Leer';
{ end;
{
{ { Und das feld zurückgeben }
{ LoadHighscore := Highscore;
{end;
{~~~~~~~~~~~~~~~~~~~~~~~~}
{ Hauptprogramm der Unit }
{~~~~~~~~~~~~~~~~~~~~~~~~}
begin
{ Leer da dashier nur die Auslagerung von Funktionen / Prozeduren ist +g+ }
end.
|
unit CommonValueDictChkBxFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Mask, ToolEdit, Registrator, BaseObjects;
type
TfrmFilterChkBx = class(TFrame)
grpgbx: TGroupBox;
cbxActiveObjects: TComboEdit;
procedure cbxActiveObjectsButtonClick(Sender: TObject);
private
FActiveObjects: TRegisteredIDObjects;
FAllObjects: TRegisteredIDObjects;
FObjectClass: TIDObjectClass;
procedure SetActiveObjects(const Value: TRegisteredIDObjects);
{ Private declarations }
public
property ActiveObjects: TRegisteredIDObjects read FActiveObjects write SetActiveObjects;
property AllObjects: TRegisteredIDObjects read FAllObjects write FAllObjects;
// класс объектов
property ObjectClass: TIDObjectClass read FObjectClass write FObjectClass;
procedure Reload;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override; end;
implementation
uses CommonValueDictSelectChkBxForm, Well;
{$R *.dfm}
constructor TfrmFilterChkBx.Create(AOwner: TComponent);
begin
inherited;
end;
destructor TfrmFilterChkBx.Destroy;
begin
inherited;
end;
procedure TfrmFilterChkBx.cbxActiveObjectsButtonClick(Sender: TObject);
var i: Integer;
o : TRegisteredIDObject;
begin
if Assigned (AllObjects) then
begin
frmValueDictSelectChkBx := TfrmValueDictSelectChkBx.Create(Self);
frmValueDictSelectChkBx.AllObjects := AllObjects;
if frmValueDictSelectChkBx.ShowModal = mrOk then
begin
if ObjectClass = TWellProperty then
begin
for i := 0 to frmValueDictSelectChkBx.lstObjects.Count - 1 do
if frmValueDictSelectChkBx.lstObjects.Checked[i] then
(ActiveObjects.Items[i] as TWellProperty).flShow := True
else (ActiveObjects.Items[i] as TWellProperty).flShow := False;
end
else for i := 0 to frmValueDictSelectChkBx.lstObjects.Count - 1 do
if frmValueDictSelectChkBx.lstObjects.Checked[i] then
begin
o := frmValueDictSelectChkBx.lstObjects.Items.Objects[i] as TRegisteredIDObject;
ActiveObjects.Add(o);
end;
Reload;
end;
frmValueDictSelectChkBx.Free;
end
else MessageBox(0, 'Справочник для объекта не указан.' + #10#13 + 'Обратитесь к разработчику.', 'Сообщение', MB_OK + MB_APPLMODAL + MB_ICONWARNING)
end;
procedure TfrmFilterChkBx.Reload;
begin
if Assigned (ActiveObjects) then
begin
if ObjectClass = TWellProperty then
cbxActiveObjects.Text := (TWellProperties(ActiveObjects)).ObjectsToStr
else cbxActiveObjects.Text := ActiveObjects.ObjectsToStr;
cbxActiveObjects.Hint := cbxActiveObjects.Text;
end
else
begin
cbxActiveObjects.Text := '';
cbxActiveObjects.Hint := '';
end;
end;
procedure TfrmFilterChkBx.SetActiveObjects(
const Value: TRegisteredIDObjects);
begin
if FActiveObjects <> Value then
begin
FActiveObjects := Value;
Reload;
end;
end;
end.
|
(*======================================================================*
| unitExIniSettings |
| |
| Ini file application settings classes. |
| |
| The contents of this file are subject to the Mozilla Public License |
| Version 1.1 (the "License"); you may not use this file except in |
| compliance with the License. You may obtain a copy of the License |
| at http://www.mozilla.org/MPL/ |
| |
| Software distributed under the License is distributed on an "AS IS" |
| basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See |
| the License for the specific language governing rights and |
| limitations under the License. |
| |
| Copyright © Colin Wilson 2006 All Rights Reserved |
| |
| Version Date By Description |
| ------- ---------- ---- ------------------------------------------|
| 1.0 02/03/2006 CPWW Original |
*======================================================================*)
unit unitExIniSettings;
interface
uses Classes, Sysutils, unitExSettings, unitExFileSettings, IniFiles;
type
//-----------------------------------------------------------------------
// TIniExSettings.
//
// Class to store application and other settings to INI files
TExIniSettings = class (TExFileSettings)
private
fIniFile : TCustomIniFile;
fAutoReadOnly : boolean;
function FixSection : string;
protected
function IsOpen : boolean; override;
function CheckIsOpen (readOnly, autoReadOnly : boolean) : TIsOpen; override;
procedure InternalSetStringValue (const valueName, value : string); override;
public
procedure Close; override;
function Open (readOnly : boolean = false) : boolean; override;
procedure DeleteValue (const valueName : string); override;
procedure DeleteSection (const sectionName : string); override;
function HasSection (const ASection : string) : boolean; override;
function HasValue (const AValue : string) : boolean; override;
procedure GetValueNames (names : TStrings); override;
procedure GetSectionNames (names : TStrings); override;
function GetStringValue (const valueName : string; const deflt : string = '') : string; override;
function GetIntegerValue (const valueName : string; deflt : Integer = 0) : Integer; override;
end;
implementation
{ TExIniSettings }
(*----------------------------------------------------------------------*
| function TExIniSettings.CheckIsOpen |
| |
| Ensure that the file is open. |
*----------------------------------------------------------------------*)
function TExIniSettings.CheckIsOpen (readOnly, autoReadOnly : boolean) : TIsOpen;
var
fn : string;
begin
result := inherited CheckIsOpen (readOnly, autoReadOnly);
case result of
woClosed :
begin
if Open (readOnly) then
begin
result := woOpen;
fReadOnly := False
end
else
result := woClosed;
end;
woReopen:
begin
fAutoReadOnly := readOnly;
fn := GetFileName ('.ini');
if not readOnly then
ForceDirectories (ExtractFilePath (fn));
result := woOpen;
end
end
end;
(*----------------------------------------------------------------------*
| procedure TExINISettings.Close |
| |
| Close the INI file |
*----------------------------------------------------------------------*)
procedure TExIniSettings.Close;
begin
FreeAndNil (fIniFile);
end;
(*----------------------------------------------------------------------*
| procedure TExINISettings.DeleteValue |
| |
| Delete a value |
*----------------------------------------------------------------------*)
procedure TExIniSettings.DeleteSection(const sectionName: string);
begin
CheckIsOpen (false, fAutoReadOnly);
fIniFile.EraseSection(FixSection);
end;
procedure TExIniSettings.DeleteValue(const valueName: string);
begin
CheckIsOpen (false, fAutoReadOnly);
fIniFile.DeleteKey(FixSection, valueName);
end;
(*----------------------------------------------------------------------*
| procedure TExINISettings.FixSection |
| |
| Return a valid INI file section name for the current section |
*----------------------------------------------------------------------*)
function TExIniSettings.FixSection: string;
begin
result := Section;
if result = '' then
result := 'Default';
end;
(*----------------------------------------------------------------------*
| function TExINISettings.GetIntegerValue |
| |
| Return an integer value, or default if the value doesn't exist |
*----------------------------------------------------------------------*)
function TExIniSettings.GetIntegerValue(const valueName: string;
deflt: Integer): Integer;
var
st : string;
begin
CheckIsOpen (true, fAutoReadOnly);
st := fIniFile.ReadString(FixSection, valueName, #1);
if st = #1 then
result := deflt
else
if not TryStrToInt (st, result) then
raise EExSettings.Create('Integer value expected');
end;
(*----------------------------------------------------------------------*
| function TExINISettings.GetStringValue |
| |
| Return a string value, or default if the value doesn't exist |
*----------------------------------------------------------------------*)
procedure TExIniSettings.GetSectionNames(names: TStrings);
begin
names.Clear;
if CheckIsOpen (true, fAutoReadOnly) = woOpen then
fIniFile.ReadSections(names);
end;
function TExIniSettings.GetStringValue(const valueName, deflt: string): string;
begin
if CheckIsOpen (true, fAutoReadOnly) = woOpen then
result := fIniFile.ReadString(FixSection, valueName, deflt)
else
result := deflt;
end;
procedure TExIniSettings.GetValueNames(names: TStrings);
begin
names.Clear;
if CheckIsOpen (true, fAutoReadOnly) = woOpen then
fIniFile.ReadSection(FixSection, names);
end;
function TExIniSettings.HasSection(const ASection: string): boolean;
var
sec : string;
begin
if CheckIsOpen (true, fAutoReadOnly) = woOpen then
begin
if Section = '' then
sec := ASection
else
sec := Section + '\' + ASection;
if sec = '' then
result := True
else
result := fIniFile.SectionExists(sec)
end
else
result := False
end;
function TExIniSettings.HasValue(const AValue: string): boolean;
begin
if CheckIsOpen (true, fAutoReadOnly) = woOpen then
result := fIniFile.ValueExists(FixSection, AValue)
else
result := False
end;
(*----------------------------------------------------------------------*
| procedure TExINISettings.InternalSetStringValue |
| |
| Set a string value |
*----------------------------------------------------------------------*)
procedure TExIniSettings.InternalSetStringValue(const valueName, value: string);
begin
CheckIsOpen (false, fAutoReadOnly);
fIniFile.WriteString(FixSection, valueName, value);
end;
(*----------------------------------------------------------------------*
| function TExINISettings.IsOpen |
| |
| Return true if the object is Open |
*----------------------------------------------------------------------*)
function TExIniSettings.IsOpen: boolean;
begin
result := fIniFile <> Nil;
end;
(*----------------------------------------------------------------------*
| procedure TExIniSettings.Open |
| |
| Open the Ini file. Create it if it doesn't exist |
*----------------------------------------------------------------------*)
function TExIniSettings.Open(readOnly: boolean) : boolean;
var
fn : string;
begin
inherited Open (readOnly);
result := True;
Close;
fAutoReadOnly := readOnly;
fn := GetFileName ('.ini');
if not readOnly then
ForceDirectories (ExtractFilePath (fn))
else
if not FileExists (fn) then
begin
result := False;
Exit;
end;
fIniFile := TIniFile.Create(fn);
end;
end.
|
{
Realizar un programa que lea una secuencia de caracteres finalizada en ".".
Determinar si la secuencia cumple con el patrón A@B (en caso de no cumplir, informar qué parte del patrón
no se cumplió).
- @ seguro existe.
- A es una secuencia de caracteres en donde no aparecen los caracteres “+” y “-”.
- B es una secuencia de caracteres que posee la misma cantidad de letras ‘a’ y ‘e’ que aparecen en A.
Modularizar su solución.
}
program ejercicio3;
procedure patronA (var cantA, cantE: integer; var cumple: boolean);
var car: char;
begin
cantA:= 0;
cantE:= 0;
cumple:= true;
read (car);
while (car<>'@') and (cumple) do
begin
if (car = '+') or (car = '-')
then cumple:= false
else begin
if (car = 'a') then cantA:= cantA + 1
else if (car = 'e')
then cantE:= cantE + 1;
read (car);
end;
end;
end;
function patronB (cantA, cantE: integer): boolean;
var car: char;
begin
read (car);
while (car <> '.') and (cantA >= 0) and (cantE >= 0) do
begin
if (car = 'a') then cantA:= cantA - 1
else if (car = 'e')
then cantE:= cantE - 1;
read (car);
end;
patronB:= (cantA=0) and (cantE=0);
end;
var cantA, cantE: integer;
cumple: boolean;
begin
patronA (cantA, cantE, cumple);
If cumple
then begin
cumple:= patronB (cantA, cantE);
If cumple then writeln ('La secuencia cumple con el patron')
else writeln ('La secuencia no cumple con la parte B')
end
else writeln ('La secuencia no cumple con la parte A')
end.
|
{*======================================================================*
| unitImpersonator |
| |
| TImpersonator class. |
| |
| The contents of this file are subject to the Mozilla Public License |
| Version 1.1 (the "License"); you may not use this file except in |
| compliance with the License. You may obtain a copy of the License |
| at http://www.mozilla.org/MPL/ |
| |
| Software distributed under the License is distributed on an "AS IS" |
| basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See |
| the License for the specific language governing rights and |
| limitations under the License. |
| |
| Copyright © Colin Wilson 2004 All Rights Reserved
| |
| Version Date By Description |
| ------- ---------- ---- ------------------------------------------|
| 1.0 27/04/2004 CPWW Original |
*======================================================================*}
unit unitImpersonator;
interface
uses Windows, Classes, SysUtils;
type
TProfileInfo = record
dwSize : DWORD;
dwFlags : DWORD;
lpUserName : PChar;
lpProfilePath : PChar;
lpDefaultPath : PChar;
lpServerName : PChar;
lpPolicyPath : PChar;
hProfile : HKEY;
end;
TImpersonator = class
private
fTokenHandle : THandle;
fImpersonating: boolean;
fProfileLoaded : boolean;
fProfileInfo : TProfileInfo;
fLoggedOn : boolean;
procedure Impersonate;
function GetImpersonating: boolean;
function GetHKCURootKey: HKEY;
public
constructor Create (const domain, user, password : string);
constructor CreateLoggedOn; // Impersonate the currently logged on user.
destructor Destroy; override;
function CreateProcess(lpApplicationName: PChar; lpCommandLine: PChar;
lpProcessAttributes, lpThreadAttributes: PSecurityAttributes;
bInheritHandles: BOOL; dwCreationFlags: DWORD; lpEnvironment: Pointer;
lpCurrentDirectory: PChar; const lpStartupInfo: TStartupInfo;
var lpProcessInformation: TProcessInformation): BOOL;
property RawImpersonating : boolean read fImpersonating;
property RawProfileLoaded : boolean read fProfileLoaded;
property Impersonating : boolean read GetImpersonating;
property HKCURootKey : HKEY read GetHKCURootKey;
property ProfileLoaded : boolean read fProfileLoaded;
end;
const
PI_NOUI = 1; // Prevents displaying of messages
PI_APPLYPOLICY = 2; // Apply NT4 style policy
LOGON_WITH_PROFILE = 1;
LOGON_NETCREDENTIALS_ONLY = 2;
function LoadUserProfile (hToken : THandle; var profileInfo : TProfileInfo) : BOOL; stdcall;
function UnloadUserProfile (hToken, HKEY : THandle) : BOOL; stdcall;
function GetCurrentUserName : string;
function OpenProcessHandle (const process : string) : THandle;
function CreateProcessWithLogonW
(lpUserName, lpDomain, lpPassword : PWideChar;
dwLogonFlags : DWORD;
lpApplicationName : PWideChar;
lpCommandLine : PWideChar;
dwCreationFlags : DWORD;
lpEnvironment : pointer;
lpCurrentDirectory : PWideChar;
const lpStartupInformation : TStartupInfo;
var lpProcessInfo : TProcessInformation) : BOOL; stdcall;
implementation
uses psapi;
function LoadUserProfile; external 'userenv.dll' name 'LoadUserProfileA';
function UnLoadUserProfile; external 'userenv.dll';
function CreateProcessWithLogonW; external 'advapi32.dll';
{*----------------------------------------------------------------------*
| function OpenProcessHandle |
| |
| Return the process handle for a named running process. |
| |
| Parameters: |
| const process : string eg. explorer.exe |
| |
| The function returns the process handle - or '0' if the prcoess |
| is not running. |
*----------------------------------------------------------------------*}
function OpenProcessHandle (const process : string) : THandle;
var
buffer, pid : PDWORD;
bufLen, cbNeeded : DWORD;
hp : THandle;
fileName : array [0..256] of char;
i : Integer;
begin
result := 0;
bufLen := 65536;
GetMem (buffer, bufLen);
try
if EnumProcesses (buffer, bufLen, cbNeeded) then
begin
pid := buffer;
for i := 0 to cbNeeded div sizeof (DWORD) - 1 do
begin
hp := OpenProcess (PROCESS_VM_READ or PROCESS_QUERY_INFORMATION, False, pid^);
if hp <> 0 then
try
if (GetModuleBaseName (hp, 0, fileName, sizeof (fileName)) > 0) and
(CompareText (fileName, process) = 0) then
begin
result := hp;
break
end
finally
if result = 0 then
CloseHandle (hp)
end;
Inc (pid)
end
end
finally
FreeMem (buffer)
end
end;
function GetExplorerProcessToken : THandle;
var
explorerProcessHandle : THandle;
begin
explorerProcessHandle := OpenProcessHandle ('explorer.exe');
if explorerProcesshandle <> 0 then
try
if not OpenProcessToken (explorerProcessHandle, TOKEN_QUERY or TOKEN_IMPERSONATE or TOKEN_DUPLICATE, result) then
RaiseLastOSError;
finally
CloseHandle (explorerProcessHandle)
end
else
result := INVALID_HANDLE_VALUE;
end;
function GetCurrentUserName : string;
var
unLen : DWORD;
begin
unLen := 512;
SetLength (result, unLen);
GetUserName (PChar (result), unLen);
result := PChar (result);
end;
{ TImpersonator }
constructor TImpersonator.Create(const domain, user, password: string);
begin
if LogonUser (PChar (user), PChar (domain), PChar (password), LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, fTokenHandle) then
Impersonate;
end;
procedure TImpersonator.Impersonate;
var
userName : string;
rv : DWORD;
begin
userName := GetCurrentUserName;
ZeroMemory (@fProfileInfo, sizeof (fProfileInfo));
fProfileInfo.dwSize := sizeof (fProfileInfo);
fProfileInfo.lpUserName := PChar (userName);
fProfileInfo.dwFlags := PI_APPLYPOLICY;
fProfileLoaded := LoadUserProfile (fTokenHandle, fProfileInfo);
if not fProfileLoaded then
RaiseLastOSError;
fImpersonating := ImpersonateLoggedOnUser (fTokenHandle);
if not fImpersonating then
begin
rv := GetLastError;
if fProfileLoaded then
begin
UnloadUserProfile (fTokenHandle, fProfileInfo.hProfile);
fProfileLoaded := False
end;
SetLastError (rv);
RaiseLastOSError
end
end;
constructor TImpersonator.CreateLoggedOn;
begin
fLoggedOn := True;
fTokenHandle := GetExplorerProcessToken;
if fTokenHandle <> INVALID_HANDLE_VALUE then
Impersonate;
end;
destructor TImpersonator.Destroy;
begin
if fProfileLoaded then
UnloadUserProfile (fTokenHandle, fProfileInfo.hProfile);
if fImpersonating then
RevertToSelf;
CloseHandle (fTokenHandle);
end;
function TImpersonator.GetImpersonating: boolean;
begin
result := fImpersonating and fProfileLoaded
end;
function TImpersonator.GetHKCURootKey: HKEY;
begin
if fProfileLoaded then
result := fProfileInfo.hProfile
else
result := HKEY_CURRENT_USER;
end;
function TImpersonator.CreateProcess(lpApplicationName,
lpCommandLine: PChar; lpProcessAttributes,
lpThreadAttributes: PSecurityAttributes; bInheritHandles: BOOL;
dwCreationFlags: DWORD; lpEnvironment: Pointer;
lpCurrentDirectory: PChar; const lpStartupInfo: TStartupInfo;
var lpProcessInformation: TProcessInformation): BOOL;
var
h : THandle;
begin
if DuplicateTokenEx (fTokenHandle, MAXIMUM_ALLOWED, Nil, SecurityAnonymous, TokenPrimary, h) then
try
result := CreateProcessAsUser (h,
lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes,
bInheritHandles, dwCreationFlags, lpEnvironment,
lpCurrentDirectory, lpStartupInfo, lpProcessInformation)
finally
CloseHandle (h)
end
else
result := False;
end;
end.
|
unit untDataStore;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, untfieldarraylist, untField, dateutils, IdGlobal, Dialogs
,untUtils;
const
SocketBufferSize:word=2048;
type
SocketBufferArray = array[0..2047] of byte;
TemplateByteArray = array[0..503] of byte;
PFieldArrayList=^TFieldArrayList;
type
{ DataStore }
{ TDataStore }
TDataStore = class
private
aryDataArray: TIdBytes;
pfalFields: PFieldArrayList;
nStartIndex: integer;
public
constructor Create(Data: TIdBytes; Fields: PFieldArrayList);
destructor Destroy; override;
function GetInt32(Index: word): LongInt; overload;
function GetInt32(FieldName: string): LongInt; overload;
function GetString(Index: word): string; overload;
function GetString(FieldName: string): string; overload;
function GetDateTime(Index: word): TDateTime; overload;
function GetDateTime(FieldName: string): TDateTime; overload;
function GetTemplateByteArray(Index: word): TemplateByteArray; overload;
function GetTemplateByteArray(FieldName: string): TemplateByteArray; overload;
function GetBoolean(Index: word): boolean; overload;
function GetBoolean(FieldName: string): boolean; overload;
end;
implementation
constructor TDataStore.Create(Data: TIdBytes; Fields: PFieldArrayList);
begin
aryDataArray := Data;
pfalFields := Fields;
end;
destructor TDataStore.Destroy;
begin
SetLength(aryDataArray,0 );
//falFields.Destroy;
FreeAndNil(aryDataArray);
//if(Assigned(falFields)) then FreeAndNil(falFields);
inherited Destroy;
end;
function TDataStore.GetInt32(Index: word): LongInt;
var
fldArea: Field;
begin
fldArea := pfalFields^.GetItems(Index);
Result:=aryDataArray[fldArea.nIndex]+aryDataArray[fldArea.nIndex+1]*256+
aryDataArray[fldArea.nIndex+2]*256*256+aryDataArray[fldArea.nIndex+3]*256*256*256;
end;
function TDataStore.GetInt32(FieldName: string): LongInt;
var
i, r: integer;
begin
for i := 0 to pfalFields^.Count - 1 do
begin
r:=CompareStr(pfalFields^.GetItems(i).strName, FieldName);
if (r = 0) then
begin
Result := GetInt32(i);
break;
end;
end;
end;
function TDataStore.GetString(Index: word): string;
var
str: string;
fldArea: Field;
begin
fldArea := pfalFields^.GetItems(Index);
SetString(str, PChar(@aryDataArray[fldArea.nIndex]), fldArea.nDataSize);
Result := Trim(str);
end;
function TDataStore.GetString(FieldName: string): string;
var
i: integer;
begin
for i := 0 to pfalFields^.Count - 1 do
begin
if (pfalFields^.GetItems(i).strName = FieldName) then
begin
Result := GetString(i);
break;
end;
end;
end;
function TDataStore.GetDateTime(Index: word): TDateTime;
var
dt: TDateTime;
fldArea: Field;
//day, month, year, hour, minute, second:word;
//strDateTime:string;
seconds:Int64;
begin
fldArea := pfalFields^.GetItems(Index);
seconds:= Unaligned(PInt64(@aryDataArray[fldArea.nIndex])^);
dt:=EncodeDateTime(1970,1, 1, 0, 0, 0,0);
dt:=IncSecond(dt, seconds);
Result := dt;
end;
function TDataStore.GetDateTime(FieldName: string): TDateTime;
var
i: integer;
begin
for i := 0 to pfalFields^.Count - 1 do
begin
if (pfalFields^.GetItems(i).strName = FieldName) then
begin
Result := GetDateTime(i);
break;
end;
end;
end;
function TDataStore.GetTemplateByteArray(Index: word): TemplateByteArray;
var
fldArea: Field;
resultArray: array[0..503] of byte;
begin
fldArea := pfalFields^.GetItems(Index);
Move(aryDataArray[fldArea.nIndex], resultArray, Length(resultArray) * sizeof(byte));
Result := resultArray;
end;
function TDataStore.GetTemplateByteArray(FieldName: string): TemplateByteArray;
var
i: integer;
begin
for i := 0 to pfalFields^.Count - 1 do
begin
if (pfalFields^.GetItems(i).strName = FieldName) then
begin
Result := GetTemplateByteArray(i);
break;
end;
end;
end;
function TDataStore.GetBoolean(Index: word): boolean;
var
fldArea: Field;
begin
Result := True;
fldArea := pfalFields^.GetItems(Index);
if (aryDataArray[fldArea.nIndex] = 0) then
Result := False;
end;
function TDataStore.GetBoolean(FieldName: string): boolean;
var
i: integer;
begin
for i := 0 to pfalFields^.Count - 1 do
begin
if (pfalFields^.GetItems(i).strName = FieldName) then
begin
Result := GetBoolean(i);
break;
end;
end;
end;
end.
|
unit roStrings;
interface
uses
SysUtils, StrUtils, Classes, Windows;
function StartsStr(const pSubStr: string; const pInStr: string;
pCaseSensitive: Boolean = True): Boolean;
function MakeStr(C: AnsiChar; N: Integer): AnsiString;
function StringToFloat(S : String): Extended;
function SubStrInclude(const SubString, s : string; CaseInsensitive : boolean):
boolean;
function WordPosition(const N: Integer; const S: AnsiString; const WordDelims:
TSysCharSet): Integer;
function WordCount(const S: AnsiString; const WordDelims: TSysCharSet): Integer;
function AddChar(C: AnsiChar; const S: AnsiString; N: Integer): AnsiString;
function AddCharR(C: AnsiChar; const S: AnsiString; N: Integer): AnsiString;
function ReplaceStr(const S, Srch, Replace: string): string;
function AnsiProperCase(const S: AnsiString; const WordDelims: TSysCharSet):
AnsiString;
function CorrectString(const s : string): string;
function DelBSpace(const S: string): string;
function DelChars(const S: string; Chr: Char): string;
function DelESpace(const S: string): string;
function DelRSpace(const S: string): string;
function ExtractWord(N: Integer; const S: AnsiString; const WordDelims:
TSysCharSet): AnsiString;
function GetWordNumber(const W, S: string; const WordDelims: TSysCharSet):
integer;
function IsEmptyStr(const S: AnsiString; const EmptyChars: TSysCharSet):
Boolean;
function IsWordPresent(const W, S: string; const WordDelims: TSysCharSet):
Boolean;
function OemToAnsiStr(const OemStr: string): string;
implementation
//------------------------------------------------------------------------------
// StartsStr
//
// Returns true if the leading part of pInStr matches, with or without case-
// sensitivity, pSubStr
//------------------------------------------------------------------------------
function StartsStr(const pSubStr: string; const pInStr: string;
pCaseSensitive: Boolean): Boolean;
begin
if pCaseSensitive then
Result := pSubStr = Copy(pInStr, 1, Length(pSubStr))
else
Result := SameText(pSubStr, Copy(pInStr, 1, Length(pSubStr)));
end;
function MakeStr(C: AnsiChar; N: Integer): AnsiString;
begin
if N < 1 then begin
Result := ''
end
else begin
SetLength(Result, N);
FillChar(Result[1], Length(Result), C);
end;
end;
function StringToFloat(S : String): Extended;
var
E, i: Integer;
begin
s := Trim(s);
for i := 1 to Length(s) do if S[i] = ',' then S[i] := '.';
Val(S, Result, E);
if E <> 0 then Result := 0;
end;
function SubStrInclude(const SubString, s : string; CaseInsensitive : boolean):
boolean;
begin
if CaseInsensitive then
Result := pos(UpperCase(SubString), UpperCase(s)) > 0
else
Result := pos(SubString, s) > 0;
end;
function WordPosition(const N: Integer; const S: AnsiString; const WordDelims:
TSysCharSet): Integer;
var
Count, I: Integer;
begin
Count := 0;
I := 1;
Result := 0;
while (I <= Length(S)) and (Count <> N) do begin
while (I <= Length(S)) and CharInSet(S[I], WordDelims) do Inc(I);
if I <= Length(S) then Inc(Count);
if Count <> N then while (I <= Length(S)) and not CharInSet(S[I], WordDelims) do Inc(I)
else Result := I;
end;
end;
function WordCount(const S: AnsiString; const WordDelims: TSysCharSet): Integer;
var
SLen, I: Cardinal;
begin
Result := 0;
I := 1;
SLen := Length(S);
while I <= SLen do begin
while (I <= SLen) and CharInSet(S[I], WordDelims) do Inc(I);
if I <= SLen then Inc(Result);
while (I <= SLen) and not CharInSet(S[I], WordDelims) do Inc(I);
end;
end;
function ExtractWord(N: Integer; const S: AnsiString; const WordDelims:
TSysCharSet): AnsiString;
var
I: Integer;
Len: Integer;
begin
Len := 0;
I := WordPosition(N, S, WordDelims);
if I <> 0 then begin
while (I <= Length(S)) and not CharInSet(S[I], WordDelims) do begin
Inc(Len);
SetLength(Result, Len);
Result[Len] := S[I];
Inc(I);
end;
end;
SetLength(Result, Len);
end;
function GetWordNumber(const W, S: string; const WordDelims: TSysCharSet):
integer;
var
Count, i: Integer;
begin
Result := -1;
Count := WordCount(S, WordDelims);
for i := 1 to Count do begin
if ExtractWord(i, S, WordDelims) = W then begin
Result := i;
Exit;
end;
end;
end;
function ReplaceStr(const S, Srch, Replace: string): string;
var
I: Integer;
Source: string;
begin
Source := S;
Result := '';
repeat
I := Pos(Srch, Source);
if I > 0 then begin
Result := Result + Copy(Source, 1, I - 1) + Replace;
Source := Copy(Source, I + Length(Srch), MaxInt);
end
else begin
Result := Result + Source;
end;
until I <= 0;
end;
function IsEmptyStr(const S: AnsiString; const EmptyChars: TSysCharSet):
Boolean;
var
I, SLen: Integer;
begin
SLen := Length(S);
I := 1;
while I <= SLen do begin
if not CharInSet(S[I], EmptyChars) then begin
Result := False;
Exit;
end
else begin
Inc(I);
end;
end;
Result := True;
end;
function OemToAnsiStr(const OemStr: string): string;
begin
SetLength(Result, Length(OemStr));
if Length(Result) > 0 then begin
OemToCharBuff(PAnsiChar(OemStr), PChar(Result), Length(Result));
end;
end;
function AddChar(C: AnsiChar; const S: AnsiString; N: Integer): AnsiString;
begin
if Length(S) < N then begin
Result := MakeStr(C, N - Length(S)) + S
end
else begin
Result := S;
end;
end;
function AddCharR(C: AnsiChar; const S: AnsiString; N: Integer): AnsiString;
begin
if Length(S) < N then
Result := S + MakeStr(C, N - Length(S))
else Result := S;
end;
function IsWordPresent(const W, S: string; const WordDelims: TSysCharSet):
Boolean;
var
Count, I: Integer;
begin
Result := False;
Count := WordCount(S, WordDelims);
for I := 1 to Count do begin
if ExtractWord(I, S, WordDelims) = W then begin
Result := True;
Exit;
end;
end;
end;
function AnsiProperCase(const S: AnsiString; const WordDelims: TSysCharSet):
AnsiString;
var
SLen, I: Cardinal;
begin
Result := AnsiLowerCase(S);
I := 1;
SLen := Length(Result);
while I <= SLen do begin
while (I <= SLen) and CharInSet(Result[I], WordDelims) do Inc(I);
if I <= SLen then Result[I] := AnsiChar(AnsiUpperCase(Result[I])[1]);
while (I <= SLen) and not CharInSet(Result[I], WordDelims) do Inc(I);
end;
end;
function CorrectString(const s : string): string;
begin
Result := s;
Result := ReplaceStr(Result, '''', '`');
Result := ReplaceStr(Result, '�', 'I');
Result := ReplaceStr(Result, #13, ' ');
Result := ReplaceStr(Result, #10, ' ');
Result := DelRSpace(Result);
end;
function DelRSpace(const S: string): string;
begin
Result := DelBSpace(DelESpace(S));
end;
function DelESpace(const S: string): string;
var
I: Integer;
begin
I := Length(S);
while (I > 0) and (S[I] = ' ') do Dec(I);
Result := Copy(S, 1, I);
end;
function DelBSpace(const S: string): string;
var
I, L: Integer;
begin
L := Length(S);
I := 1;
while (I <= L) and (S[I] = ' ') do Inc(I);
Result := Copy(S, I, MaxInt);
end;
function DelChars(const S: string; Chr: Char): string;
var
I: Integer;
begin
Result := S;
for I := Length(Result) downto 1 do begin
if Result[I] = Chr then Delete(Result, I, 1);
end;
end;
end.
|
unit SumoSystemType;
{$mode objfpc}{$H+}
interface
type
TSumoSystemType = (stNoType, stEsso, stEssoM,stEssoMv2);
TSumoSystemTypeSet = set of TSumoSystemType;
TSumoSystemTypeArrayName = Array[TSumoSystemType] of String;
const
DEF_ADDR = '127.0.0.1';
DEF_PORT = 80;
DEF_MAX_RETRY_COUNT = 5;
DEF_RETRY_INTERVAL = 5000;
SUMO_NOTYPE = 'notype';
SUMO_ESSO = 'esso';
SUMO_ESSO_M = 'esso-m';
SUMO_ESSO_M_v2 = 'esso-m-2';
SystemTypeNames : TSumoSystemTypeArrayName = (SUMO_NOTYPE,SUMO_ESSO, SUMO_ESSO_M,SUMO_ESSO_M_v2);
function GetSystemIDFromString(AName : String): TSumoSystemType;
implementation
uses sysutils;
function GetSystemIDFromString(AName : String): TSumoSystemType;
begin
Result := stNoType;
if SameText(SUMO_ESSO,AName)then Result := stEsso;
if SameText(SUMO_ESSO_M,AName)then Result := stEssoM;
if SameText(SUMO_ESSO_M_v2,AName)then Result := stEssoMv2;
end;
end.
|
unit FileSelectForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, VirtualTrees, VSTUtils;
type
TfrmFileSelect = class(TForm)
vstFiles: TVirtualStringTree;
pnlButtons: TPanel;
btnCancel: TButton;
btnOK: TButton;
pnlFilter: TPanel;
cbxFilter: TCheckBox;
procedure cbxFilterClick(Sender: TObject);
procedure vstFilesChange(Sender: TBaseVirtualTree; Node: PVirtualNode);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure vstFilesGetImageIndex(Sender: TBaseVirtualTree;
Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
var Ghosted: Boolean; var ImageIndex: Integer);
procedure vstFilesHeaderClick(Sender: TVTHeader; Column: TColumnIndex;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure vstFilesCompareNodes(Sender: TBaseVirtualTree; Node1,
Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer);
procedure vstFilesGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
procedure vstFilesInitNode(Sender: TBaseVirtualTree; ParentNode,
Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
private
FFileList : TStrings;
FNodeList : TNodeArray;
function GetOriginalNodeData(Tree : TBaseVirtualTree; Node : PVirtualNode) : PFileTreeData;
function GetMultiSelect : Boolean;
procedure SetMultiSelect(NewValue : Boolean);
function GetFileName : String;
function GetFileNode : PVirtualNode;
function FileExtInFilters(Data : PFileTreeData) : Boolean;
procedure ApplyFilter;
public
procedure CopyTreeData(Tree : TBaseVirtualTree; sShowIcons : Boolean);
procedure SetFilter(const FilterStr : String; const Title : String);
function Execute : Boolean;
property MultiSelect : Boolean read GetMultiSelect write SetMultiSelect;
property Filename : String read GetFilename;
property FileNode : PVirtualNode read GetFileNode;
property FileList : TStrings read FFileList;
property NodeList : TNodeArray read FNodeList;
const FOLDER_WILDCARD : String = '[folder]';
end;
rFileMirrorTreeData = record
OriginalNode : PVirtualNode;
IsFiltered : Boolean;
end;
PFileMirrorTreeData = ^rFileMirrorTreeData;
var
frmFileSelect: TfrmFileSelect;
OriginalTree: TBaseVirtualTree;
Successful : Boolean;
ShowIcons : Boolean;
Filters : TStrings;
implementation
uses StrUtils,
{$Ifdef Win32}
VSTIcons_win;
{$Else}
VSTIcons_lin;
{$Endif}
{$R *.dfm}
function TfrmFileSelect.GetOriginalNodeData(Tree : TBaseVirtualTree; Node: PVirtualNode) : PFileTreeData;
var temp : PFileMirrorTreeData;
begin
temp := Tree.GetNodeData(Node);
Result := OriginalTree.GetNodeData(temp.OriginalNode)
end;
function TfrmFileSelect.GetMultiSelect : Boolean;
begin
Result := (toMultiSelect in vstFiles.TreeOptions.SelectionOptions);
end;
procedure TfrmFileSelect.SetMultiSelect(NewValue : Boolean);
begin
vstFiles.TreeOptions.SelectionOptions := vstFiles.TreeOptions.SelectionOptions + [toMultiSelect];
end;
function TfrmFileSelect.GetFilename : String;
begin
if FileList.Count > 0 then
Result := FFileList[0]
else
Result := '';
end;
function TfrmFileSelect.GetFileNode : PVirtualNode;
begin
if Length(NodeList) > 0 then
Result := FNodeList[0]
else
Result := nil;
end;
function TfrmFileSelect.FileExtInFilters(Data : PFileTreeData) : Boolean;
var Ext : String;
I : Integer;
begin
Result := false;
if Filters.Count = 0 then
begin
Result := true;
Exit;
end;
if (Data.Attr and faDirectory > 0) then
begin
if Filters[0] = FOLDER_WILDCARD then
Result := true
else
Result := false;
end else
begin
Ext := ExtractFileExt(Data.Name);
for I := 0 to Filters.Count - 1 do
begin
if Filters[I] = Ext then
begin
Result := true;
Exit;
end;
end;
end;
end;
procedure TfrmFileSelect.ApplyFilter;
var Node : PVirtualNode;
PData : PFileMirrorTreeData;
POrigData : PFileTreeData;
begin
Node := vstFiles.GetFirst();
while Node <> nil do
begin
PData := vstFiles.GetNodeData(Node);
POrigData := GetOriginalNodeData(OriginalTree,Node);
if vstFiles.HasChildren[Node] OR FileExtInFilters(POrigData) then
begin
PData.IsFiltered := false;
vstFiles.IsVisible[Node] := cbxFilter.Checked;
vstFiles.IsDisabled[Node] := NOT cbxFilter.Checked;
end else
begin
PData.IsFiltered := true;
vstFiles.IsVisible[Node] := NOT cbxFilter.Checked;
vstFiles.IsDisabled[Node] := cbxFilter.Checked;
end;
Node := vstFiles.GetNext(Node);
end;
end;
procedure TfrmFileSelect.CopyTreeData(Tree : TBaseVirtualTree; sShowIcons : Boolean);
procedure CopyChildNodes(Tree : TBaseVirtualTree; Parent : PVirtualNode = nil;
OriginalParent : PVirtualNode = nil);
var PData : PFileMirrorTreeData;
POrigData : PFileTreeData;
Node, OriginalNode : PVirtualNode;
begin
OriginalNode := Tree.GetFirstChild(OriginalParent);
while OriginalNode <> nil do
begin
POrigData := OriginalTree.GetNodeData(OriginalNode);
Node := vstFiles.AddChild(Parent);
PData := vstFiles.GetNodeData(Node);
PData.OriginalNode := OriginalNode;
PData.IsFiltered := true;
if Tree.HasChildren[OriginalNode] then
begin
PData.IsFiltered := false;
CopyChildNodes(Tree,Node,OriginalNode);
end else
begin
if FileExtInFilters(POrigData) then
PData.IsFiltered := false;
end;
if PData.IsFiltered then
begin
vstFiles.IsVisible[Node] := NOT cbxFilter.Checked;
vstFiles.IsDisabled[Node] := cbxFilter.Checked;
end;
OriginalNode := Tree.GetNextSibling(OriginalNode);
end;
end;
begin
vstFiles.Clear;
OriginalTree := Tree;
ShowIcons := sShowIcons;
CopyChildNodes(Tree);
end;
procedure TfrmFileSelect.SetFilter(const FilterStr : String; const Title : String);
var temp, S : String;
I : Integer;
begin
Filters.Clear;
if FilterStr = FOLDER_WILDCARD then
begin
Filters.Add(FOLDER_WILDCARD);
cbxFilter.Caption := 'Filter: ' + Title;
end else
begin
temp := Trim(FilterStr);
if RightStr(temp,1) <> ';' then
temp := temp + ';';
while Pos(';',temp) <> 0 do
begin
Filters.Add(LeftStr(temp,Pos(';',temp)-1));
temp := RightStr(temp,Length(temp)-Pos(';',temp));
end;
for I := 0 to Filters.Count - 1 do
S := S + '*' + Filters[I] + ';';
S := LeftStr(S,Length(S)-1);
cbxFilter.Caption := 'Filter: ' + Title + ' (' + S + ')';
end;
end;
function TfrmFileSelect.Execute : Boolean;
begin
Successful := false;
FFileList.Clear;
SetLength(FNodeList,0);
vstFiles.ClearSelection;
ShowModal;
Result := Successful;
end;
// --- Buttons -----------------------------------------------------------------
procedure TfrmFileSelect.btnCancelClick(Sender: TObject);
begin
Successful := false;
Close;
end;
procedure TfrmFileSelect.btnOKClick(Sender: TObject);
var Node : PVirtualNode;
PData : PFileMirrorTreeData;
begin
Node := vstFiles.GetFirstSelected();
while Node <> nil do
begin
PData := vstFiles.GetNodeData(Node);
if IsFile(OriginalTree,PData.OriginalNode) OR (Filters.Count = 0) OR
(Filters[0] = FOLDER_WILDCARD) then
begin
FFileList.Add(GetFilepathInPND(OriginalTree,PData.OriginalNode));
SetLength(FNodeList,Length(FNodeList)+1);
FNodeList[High(FNodeList)] := PData.OriginalNode;
end;
Node := vstFiles.GetNextSelected(Node);
end;
Successful := true;
Close;
end;
procedure TfrmFileSelect.cbxFilterClick(Sender: TObject);
var Node : PVirtualNode;
PData : PFileMirrorTreeData;
begin
Node := vstFiles.GetFirst();
while Node <> nil do
begin
PData := vstFiles.GetNodeData(Node);
if PData.IsFiltered then
begin
vstFiles.IsVisible[Node] := NOT cbxFilter.Checked;
vstFiles.IsDisabled[Node] := cbxFilter.Checked;
if cbxFilter.Checked AND vstFiles.Selected[Node] then
vstFiles.Selected[Node] := false;
end;
Node := vstFiles.GetNext(Node);
end;
end;
procedure TfrmFileSelect.FormCreate(Sender: TObject);
begin
vstFiles.NodeDataSize := sizeof(rFileMirrorTreeData);
Filters := TStringList.Create;
FFileList := TStringList.Create;
end;
procedure TfrmFileSelect.FormShow(Sender: TObject);
begin
Successful := false;
end;
// --- Files Tree --------------------------------------------------------------
procedure TfrmFileSelect.vstFilesChange(Sender: TBaseVirtualTree;
Node: PVirtualNode);
var PData : PFileMirrorTreeData;
ValidSelectionCount : Integer;
begin
Node := vstFiles.GetFirstSelected();
ValidSelectionCount := 0;
while Node <> nil do
begin
PData := vstFiles.GetNodeData(Node);
if IsFile(OriginalTree,PData.OriginalNode) OR (Filters.Count = 0) OR (Filters[0] = FOLDER_WILDCARD) then
Inc(ValidSelectionCount);
Node := vstFiles.GetNextSelected(Node);
end;
btnOK.Enabled := (ValidSelectionCount > 0);
end;
procedure TfrmFileSelect.vstFilesCompareNodes(Sender: TBaseVirtualTree; Node1,
Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer);
var
PData1, PData2 : PFileTreeData;
begin
PData1 := GetOriginalNodeData(Sender,Node1);
PData2 := GetOriginalNodeData(Sender,Node2);
if Column = 0 then
begin
if (PData1.Attr and faDirectory > 0) XOR (PData2.Attr and faDirectory > 0) then
begin
if (PData1.Attr and faDirectory > 0) then
Result := -1
else
Result := 1;
end else
{$Ifdef Win32}
Result := CompareText(ExtractFileName(PData1.Name), ExtractFileName(PData2.Name));
{$Else}
Result := CompareStr(ExtractFileName(PData1.Name), ExtractFileName(PData2.Name));
{$Endif}
end
end;
procedure TfrmFileSelect.vstFilesGetImageIndex(Sender: TBaseVirtualTree;
Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
var Ghosted: Boolean; var ImageIndex: Integer);
var
PData : PFileTreeData;
begin
if (Column <> 0) OR (Kind = ikOverlay) then
Exit;
PData := GetOriginalNodeData(Sender,Node);
if Sender.Expanded[Node] then
ImageIndex := PData.OpenIndex
else
ImageIndex := PData.ClosedIndex;
end;
procedure TfrmFileSelect.vstFilesGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
var
PData : PFileTreeData;
begin
PData := GetOriginalNodeData(Sender,Node);
case Column of
0 : CellText := ExtractFileName(PData.Name);
end;
end;
procedure TfrmFileSelect.vstFilesHeaderClick(Sender: TVTHeader; Column: TColumnIndex;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if Sender.SortColumn = Column then
begin
if Sender.SortDirection=sdAscending then
Sender.SortDirection:=sdDescending
else
Sender.SortDirection:=sdAscending;
end else
Sender.SortColumn := Column;
Sender.Treeview.SortTree(Column,Sender.SortDirection,True);
end;
procedure TfrmFileSelect.vstFilesInitNode(Sender: TBaseVirtualTree; ParentNode,
Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
var
PData : PFileTreeData;
begin
PData := GetOriginalNodeData(Sender,Node);
if ShowIcons then
begin
PData.ClosedIndex := GetIconIndex(PData.Name,false);
PData.OpenIndex := GetIconIndex(PData.Name,true);
end else
begin
if (PData.Attr and faDirectory = 0) then
begin
PData.ClosedIndex := 0;
PData.OpenIndex := 0;
end else
begin
PData.ClosedIndex := 1;
PData.OpenIndex := 1;
end;
end;
end;
end.
|
unit UMyCloudXmlInfo;
interface
uses UChangeInfo, xmldom, XMLIntf, msxmldom, XMLDoc, UXmlUtil, UMyUtil;
type
{$Region ' 数据修改 云路径信息 ' }
// 父类
TCloudPcChangeXml = class( TXmlChangeInfo )
protected
MyCloudNode : IXMLNode;
CloudPcNodeList : IXMLNode;
protected
procedure Update;override;
end;
// 重设
TCloudPathReSetXml = class( TCloudPcChangeXml )
public
CloudPath : string;
public
constructor Create( _CloudPath : string );
protected
procedure Update;override;
end;
{$EndRegion}
{$Region ' 数据修改 Pc信息 ' }
// 修改
TCloudPcWriteXml = class( TCloudPcChangeXml )
public
PcID : string;
protected
CloudPcIndex : Integer;
CloudPcNode : IXMLNode;
public
constructor Create( _PcID : string );
protected
function FindCloudPcNode: Boolean;
end;
// 添加
TCloudPcAddXml = class( TCloudPcWriteXml )
public
protected
procedure Update;override;
end;
// 删除
TCloudPcRemoveXml = class( TCloudPcWriteXml )
protected
procedure Update;override;
end;
{$EndRegion}
{$Region ' 数据修改 备份信息 ' }
// 父类
TCloudPcBackupChangeXml = class( TCloudPcWriteXml )
protected
CloudPcBackupNodeList : IXMLNode;
protected
function FindCloudPcBackupNodeList : Boolean;
end;
// 修改
TCloudPcBackupWriteXml = class( TCloudPcBackupChangeXml )
public
BackupPath : string;
protected
CloudPcBackupIndex : Integer;
CloudPcBackupNode : IXMLNode;
public
procedure SetBackupPath( _BackupPath : string );
protected
function FindCloudPcBackupNode: Boolean;
end;
// 添加
TCloudPcBackupAddXml = class( TCloudPcBackupWriteXml )
public
IsFile : boolean;
public
FileCount : integer;
ItemSize : int64;
public
LastBackupTime : TDateTime;
public
procedure SetIsFile( _IsFile : boolean );
procedure SetSpaceInfo( _FileCount : integer; _ItemSize : int64 );
procedure SetLastBackupTime( _LastBackupTime : TDateTime );
protected
procedure Update;override;
end;
// 删除
TCloudPcBackupRemoveXml = class( TCloudPcBackupWriteXml )
protected
procedure Update;override;
end;
{$EndRegion}
{$Region ' 数据读取 ' }
// 读取
TCloudPcBackupReadXml = class
public
CloudPcBackupNode : IXMLNode;
PcID : string;
public
constructor Create( _CloudPcBackupNode : IXMLNode );
procedure SetPcID( _PcID : string );
procedure Update;
end;
// 读取
TCloudPcReadXml = class
public
CloudPcNode : IXMLNode;
public
PcID : string;
public
constructor Create( _CloudPcNode : IXMLNode );
procedure Update;
private
procedure ReadCloudPcBackupList;
end;
// 读取
TMyCloudInfoReadXml = class
private
MyCloudNode : IXMLNode;
public
procedure Update;
private
procedure ReadCloudPath;
procedure ReadCloudPcList;
end;
{$EndRegion}
const
Xml_MyCloudInfo = 'mcif';
Xml_CloudPath = 'cp';
Xml_CloudPcList = 'cpl';
Xml_PcID = 'pid';
Xml_CloudPcInfo = 'cpi';
Xml_CloudPcBackupList = 'cpbl';
Xml_BackupPath = 'bp';
Xml_IsFile = 'if';
Xml_FileCount = 'fc';
Xml_ItemSize = 'is';
Xml_LastBackupTime = 'lbt';
implementation
uses UMyCloudApiInfo;
{ TCloudPcChangeXml }
procedure TCloudPcChangeXml.Update;
begin
MyCloudNode := MyXmlUtil.AddChild( MyXmlDoc.DocumentElement, Xml_MyCloudInfo );
CloudPcNodeList := MyXmlUtil.AddChild( MyCloudNode, Xml_CloudPcList );
end;
{ TCloudPcWriteXml }
constructor TCloudPcWriteXml.Create( _PcID : string );
begin
PcID := _PcID;
end;
function TCloudPcWriteXml.FindCloudPcNode: Boolean;
var
i : Integer;
SelectNode : IXMLNode;
begin
Result := False;
for i := 0 to CloudPcNodeList.ChildNodes.Count - 1 do
begin
SelectNode := CloudPcNodeList.ChildNodes[i];
if ( MyXmlUtil.GetChildValue( SelectNode, Xml_PcID ) = PcID ) then
begin
Result := True;
CloudPcIndex := i;
CloudPcNode := CloudPcNodeList.ChildNodes[i];
break;
end;
end;
end;
{ TCloudPcAddXml }
procedure TCloudPcAddXml.Update;
begin
inherited;
if FindCloudPcNode then
Exit;
CloudPcNode := MyXmlUtil.AddListChild( CloudPcNodeList );
MyXmlUtil.AddChild( CloudPcNode, Xml_PcID, PcID );
end;
{ TCloudPcRemoveXml }
procedure TCloudPcRemoveXml.Update;
begin
inherited;
if not FindCloudPcNode then
Exit;
MyXmlUtil.DeleteListChild( CloudPcNodeList, CloudPcIndex );
end;
{ TCloudPcBackupChangeXml }
function TCloudPcBackupChangeXml.FindCloudPcBackupNodeList : Boolean;
begin
Result := FindCloudPcNode;
if Result then
CloudPcBackupNodeList := MyXmlUtil.AddChild( CloudPcNode, Xml_CloudPcBackupList );
end;
{ TCloudPcBackupWriteXml }
procedure TCloudPcBackupWriteXml.SetBackupPath( _BackupPath : string );
begin
BackupPath := _BackupPath;
end;
function TCloudPcBackupWriteXml.FindCloudPcBackupNode: Boolean;
var
i : Integer;
SelectNode : IXMLNode;
begin
Result := False;
if not FindCloudPcBackupNodeList then
Exit;
for i := 0 to CloudPcBackupNodeList.ChildNodes.Count - 1 do
begin
SelectNode := CloudPcBackupNodeList.ChildNodes[i];
if ( MyXmlUtil.GetChildValue( SelectNode, Xml_BackupPath ) = BackupPath ) then
begin
Result := True;
CloudPcBackupIndex := i;
CloudPcBackupNode := CloudPcBackupNodeList.ChildNodes[i];
break;
end;
end;
end;
{ TCloudPcBackupAddXml }
procedure TCloudPcBackupAddXml.SetIsFile( _IsFile : boolean );
begin
IsFile := _IsFile;
end;
procedure TCloudPcBackupAddXml.SetLastBackupTime(_LastBackupTime: TDateTime);
begin
LastBackupTime := _LastBackupTime;
end;
procedure TCloudPcBackupAddXml.SetSpaceInfo( _FileCount : integer; _ItemSize : int64 );
begin
FileCount := _FileCount;
ItemSize := _ItemSize;
end;
procedure TCloudPcBackupAddXml.Update;
begin
inherited;
// 不存在 则创建
if not FindCloudPcBackupNode then
begin
CloudPcBackupNode := MyXmlUtil.AddListChild( CloudPcBackupNodeList );
MyXmlUtil.AddChild( CloudPcBackupNode, Xml_BackupPath, BackupPath );
MyXmlUtil.AddChild( CloudPcBackupNode, Xml_IsFile, IsFile );
end;
// 存在 则重新设置 空间信息
MyXmlUtil.AddChild( CloudPcBackupNode, Xml_FileCount, FileCount );
MyXmlUtil.AddChild( CloudPcBackupNode, Xml_ItemSize, ItemSize );
MyXmlUtil.AddChild( CloudPcBackupNode, Xml_LastBackupTime, LastBackupTime );
end;
{ TCloudPcBackupRemoveXml }
procedure TCloudPcBackupRemoveXml.Update;
begin
inherited;
if not FindCloudPcBackupNode then
Exit;
MyXmlUtil.DeleteListChild( CloudPcBackupNodeList, CloudPcBackupIndex );
end;
{ TCloudPathReSetXml }
constructor TCloudPathReSetXml.Create(_CloudPath: string);
begin
CloudPath := _CloudPath;
end;
procedure TCloudPathReSetXml.Update;
begin
inherited;
MyXmlUtil.AddChild( MyCloudNode, Xml_CloudPath, CloudPath );
CloudPcNodeList.ChildNodes.Clear;
end;
{ TMyCloudInfoReadXml }
procedure TMyCloudInfoReadXml.ReadCloudPath;
var
CloudPath : string;
CloudPathReSetXml : TCloudPathReSetXml;
CloudPathReadHandle : TCloudPathReadHandle;
begin
CloudPath := MyXmlUtil.GetChildValue( MyCloudNode, Xml_CloudPath );
if CloudPath = '' then
begin
CloudPath := MyHardDisk.getBiggestHardDIsk + 'BackupCow.Backup';
CloudPathReSetXml := TCloudPathReSetXml.Create( CloudPath );
CloudPathReSetXml.AddChange;
end;
// 处理
CloudPathReadHandle := TCloudPathReadHandle.Create( CloudPath );
CloudPathReadHandle.Update;
CloudPathReadHandle.Free;
end;
procedure TMyCloudInfoReadXml.ReadCloudPcList;
var
CloudPcNodeList : IXMLNode;
i : Integer;
CloudPcNode : IXMLNode;
CloudPcReadXml : TCloudPcReadXml;
begin
CloudPcNodeList := MyXmlUtil.AddChild( MyCloudNode, Xml_CloudPcList );
for i := 0 to CloudPcNodeList.ChildNodes.Count - 1 do
begin
CloudPcNode := CloudPcNodeList.ChildNodes[i];
CloudPcReadXml := TCloudPcReadXml.Create( CloudPcNode );
CloudPcReadXml.Update;
CloudPcReadXml.Free;
end;
end;
procedure TMyCloudInfoReadXml.Update;
begin
MyCloudNode := MyXmlUtil.AddChild( MyXmlDoc.DocumentElement, Xml_MyCloudInfo );
ReadCloudPath;
ReadCloudPcList;
end;
{ CloudPcNode }
constructor TCloudPcReadXml.Create( _CloudPcNode : IXMLNode );
begin
CloudPcNode := _CloudPcNode;
end;
procedure TCloudPcReadXml.ReadCloudPcBackupList;
var
CloudPcBackupNodeList : IXMLNode;
i : Integer;
CloudPcBackupNode : IXMLNode;
CloudPcBackupReadXml : TCloudPcBackupReadXml;
begin
CloudPcBackupNodeList := MyXmlUtil.AddChild( CloudPcNode, Xml_CloudPcBackupList );
for i := 0 to CloudPcBackupNodeList.ChildNodes.Count - 1 do
begin
CloudPcBackupNode := CloudPcBackupNodeList.ChildNodes[i];
CloudPcBackupReadXml := TCloudPcBackupReadXml.Create( CloudPcBackupNode );
CloudPcBackupReadXml.SetPcID( PcID );
CloudPcBackupReadXml.Update;
CloudPcBackupReadXml.Free;
end;
end;
procedure TCloudPcReadXml.Update;
var
CloudPcReadHandle : TCloudPcReadHandle;
begin
PcID := MyXmlUtil.GetChildValue( CloudPcNode, Xml_PcID );
CloudPcReadHandle := TCloudPcReadHandle.Create( PcID );
CloudPcReadHandle.Update;
CloudPcReadHandle.Free;
ReadCloudPcBackupList;
end;
{ CloudPcBackupNode }
constructor TCloudPcBackupReadXml.Create( _CloudPcBackupNode : IXMLNode );
begin
CloudPcBackupNode := _CloudPcBackupNode;
end;
procedure TCloudPcBackupReadXml.SetPcID(_PcID: string);
begin
PcID := _PcID;
end;
procedure TCloudPcBackupReadXml.Update;
var
BackupPath : string;
IsFile : boolean;
FileCount : integer;
ItemSize : int64;
LastBackupTime : TDateTime;
CloudPcBackupReadHandle : TCloudPcBackupReadHandle;
begin
BackupPath := MyXmlUtil.GetChildValue( CloudPcBackupNode, Xml_BackupPath );
IsFile := MyXmlUtil.GetChildBoolValue( CloudPcBackupNode, Xml_IsFile );
FileCount := MyXmlUtil.GetChildIntValue( CloudPcBackupNode, Xml_FileCount );
ItemSize := MyXmlUtil.GetChildInt64Value( CloudPcBackupNode, Xml_ItemSize );
LastBackupTime := MyXmlUtil.GetChildFloatValue( CloudPcBackupNode, Xml_LastBackupTime );
CloudPcBackupReadHandle := TCloudPcBackupReadHandle.Create( PcID );
CloudPcBackupReadHandle.SetBackupPath( BackupPath );
CloudPcBackupReadHandle.SetIsFile( IsFile );
CloudPcBackupReadHandle.SetSpaceInfo( FileCount, ItemSize );
CloudPcBackupReadHandle.SetLastBackupTime( LastBackupTime );
CloudPcBackupReadHandle.Update;
CloudPcBackupReadHandle.Free;
end;
end.
|
unit ToolkitSettings;
interface
uses
SysUtils, Classes,
EncodeSupport,
AdvJson,
SmartOnFHIRUtilities,
FHIRClientSettings;
const
DEF_TIMEOUT = 10;
DEF_SHOWHELP = false;
DEF_CHECKUPGRADES = true;
type
TFHIRToolkitSettings = class (TFHIRClientSettings)
private
function GetTimeout: integer;
procedure SetTimeout(const Value: integer);
procedure SetProxy(const Value: String);
function GetProxy: String;
function GetShowHelp: boolean;
procedure SetShowHelp(const Value: boolean);
function GetCheckForUpgradesOnStart: boolean;
procedure SetCheckForUpgradesOnStart(const Value: boolean);
function GetRegistryPassword: String;
function GetRegistryUsername: String;
procedure SetRegistryPassword(const Value: String);
procedure SetRegistryUsername(const Value: String);
protected
procedure initSettings; virtual;
public
function link : TFHIRToolkitSettings; overload;
property timeout: integer read GetTimeout write SetTimeout;
property Proxy : String read GetProxy write SetProxy;
property ShowHelp : boolean read GetShowHelp write SetShowHelp;
property CheckForUpgradesOnStart : boolean read GetCheckForUpgradesOnStart write SetCheckForUpgradesOnStart;
property RegistryUsername : String read GetRegistryUsername write SetRegistryUsername;
property RegistryPassword : String read GetRegistryPassword write SetRegistryPassword;
procedure storeValues(name : String; values : TStrings); overload;
procedure storeValue(section, name, value : String); overload;
procedure storeValue(section, name : String; value : integer); overload;
procedure storeValue(section, name : String; value : boolean); overload;
procedure getValues(name : String; values : TStrings); overload;
function getValue(section, name, default : String) : String; overload;
function getValue(section, name : String; default : integer) : integer; overload;
function getValue(section, name : String; default : boolean) : boolean; overload;
end;
implementation
{ TFHIRToolkitSettings }
function TFHIRToolkitSettings.GetCheckForUpgradesOnStart: boolean;
begin
result := StrToBoolDef(json.vStr['CheckForUpgrades'], DEF_CHECKUPGRADES);
end;
function TFHIRToolkitSettings.GetProxy: String;
var
o : TJsonObject;
begin
o := json.vObj['Client'];
if (o = nil) then
result := ''
else
result := o.vStr['Proxy'];
end;
function TFHIRToolkitSettings.GetRegistryPassword: String;
begin
result := strDecrypt(json.vStr['RegistryPassword'], 53423);
end;
function TFHIRToolkitSettings.GetRegistryUsername: String;
begin
result := json.vStr['RegistryUsername'];
end;
function TFHIRToolkitSettings.GetShowHelp: boolean;
begin
result := StrToBoolDef(json.vStr['ShowHelp'], DEF_SHOWHELP);
end;
function TFHIRToolkitSettings.GetTimeout: integer;
var
o : TJsonObject;
begin
o := json.vObj['Client'];
if (o = nil) then
result := DEF_TIMEOUT
else
result := StrToIntDef(o.vStr['Timeout'], DEF_TIMEOUT);
end;
function TFHIRToolkitSettings.getValue(section, name, default: String): String;
var
o : TJsonObject;
begin
o := json.forceObj['Memory'];
o := o.forceObj[section];
result := o.vStr[name];
if result = '' then
result := default;
end;
function TFHIRToolkitSettings.getValue(section, name: String; default: integer): integer;
var
o : TJsonObject;
begin
o := json.forceObj['Memory'];
o := o.forceObj[section];
result := StrToIntDef(o.vStr[name], default);
end;
function TFHIRToolkitSettings.getValue(section, name: String; default: boolean): boolean;
var
o : TJsonObject;
begin
o := json.forceObj['Memory'];
o := o.forceObj[section];
result := StrToBoolDef(o.vStr[name], default);
end;
procedure TFHIRToolkitSettings.getValues(name: String; values: TStrings);
var
a : TJsonArray;
i : TJsonNode;
begin
values.Clear;
a := json.forceArr[name];
for i in a do
if i is TJsonString then
values.add(TJsonString(i).value);
end;
procedure TFHIRToolkitSettings.initSettings;
var
server : TRegisteredFHIRServer;
begin
server := TRegisteredFHIRServer.Create;
try
server.name := 'FHIR Terminology Server';
server.fhirEndpoint := 'http://tx.fhir.org/r3';
registerServer('Terminology', server);
finally
server.free;
end;
end;
function TFHIRToolkitSettings.link: TFHIRToolkitSettings;
begin
result := TFHIRToolkitSettings(inherited Link);
end;
procedure TFHIRToolkitSettings.SetCheckForUpgradesOnStart(const Value: boolean);
begin
if value <> GetCheckForUpgradesOnStart then
begin
json.vStr['CheckForUpgrades'] := BoolToStr(value);
Save;
end;
end;
procedure TFHIRToolkitSettings.SetProxy(const Value: String);
var
o : TJsonObject;
begin
if value <> GetProxy then
begin
o := json.forceObj['Client'];
o.vStr['Proxy'] := value;
Save;
end;
end;
procedure TFHIRToolkitSettings.SetRegistryPassword(const Value: String);
begin
json.vStr['RegistryPassword'] := strEncrypt(Value, 53423);
end;
procedure TFHIRToolkitSettings.SetRegistryUsername(const Value: String);
begin
json.vStr['RegistryUsername'] := value;
end;
procedure TFHIRToolkitSettings.SetShowHelp(const Value: boolean);
begin
if value <> GetShowHelp then
begin
json.vStr['ShowHelp'] := BoolToStr(value);
Save;
end;
end;
procedure TFHIRToolkitSettings.SetTimeout(const Value: integer);
var
o : TJsonObject;
begin
if value <> GetTimeout then
begin
o := json.forceObj['Client'];
o.vStr['Timeout'] := inttostr(value);
Save;
end;
end;
procedure TFHIRToolkitSettings.StoreValue(section, name: String; value: boolean);
var
o : TJsonObject;
begin
o := json.forceObj['Memory'];
o := o.forceObj[section];
o.vStr[name] := BoolToStr(value);
end;
procedure TFHIRToolkitSettings.storeValues(name: String; values: TStrings);
var
a : TJsonArray;
s : String;
begin
a := json.forceArr[name];
a.clear;
for s in values do
a.add(s);
end;
procedure TFHIRToolkitSettings.StoreValue(section, name: String; value: integer);
var
o : TJsonObject;
begin
o := json.forceObj['Memory'];
o := o.forceObj[section];
o.vStr[name] := inttostr(value);
end;
procedure TFHIRToolkitSettings.StoreValue(section, name, value: String);
var
o : TJsonObject;
begin
o := json.forceObj['Memory'];
o := o.forceObj[section];
o.vStr[name] := value;
end;
end.
// FIni.ReadInteger('HTTP', 'timeout', 5)
FIni.ReadString('HTTP', 'proxy', ''));
|
unit DigitalSignatureTests;
{
Copyright (c) 2011+, Health Intersections Pty Ltd (http://www.healthintersections.com.au)
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 HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
Interface
Uses
SysUtils, Classes,
FHIR.Support.Signatures,
DUnitX.TestFramework;
Type
[TextFixture]
TDigitalSignatureTests = Class (TObject)
private
procedure testFile(filename : String);
Published
[TestCase] Procedure testFileRSA;
[TestCase] Procedure testFileDSA;
[TestCase] Procedure testFileJames;
[TestCase] Procedure testGenRSA_1;
[TestCase] Procedure testGenRSA_256;
// [TestCase] Procedure testGenDSA_1;
// [TestCase] Procedure testGenDSA_256;
End;
implementation
{ TDigitalSignatureTests }
procedure TDigitalSignatureTests.testFile(filename : String);
var
bytes : TBytes;
f : TFileStream;
sig : TDigitalSigner;
begin
f := TFileStream.Create(filename, fmOpenRead);
try
setLength(bytes, f.Size);
f.Read(bytes[0], length(bytes));
finally
f.free;
end;
sig := TDigitalSigner.Create;
try
Assert.isTrue(sig.verifySignature(bytes));
finally
sig.Free;
end;
end;
procedure TDigitalSignatureTests.testFileDSA;
begin
testFile('C:\work\fhirserver\tests\signatures\java_example_dsa.xml');
end;
procedure TDigitalSignatureTests.testFileJames;
begin
testFile('C:\work\fhirserver\tests\signatures\james.xml');
end;
procedure TDigitalSignatureTests.testFileRSA;
begin
testFile('C:\work\fhirserver\tests\signatures\java_example_rsa.xml');
end;
procedure TDigitalSignatureTests.testGenRsa_1;
var
bytes : TBytes;
sig : TDigitalSigner;
begin
sig := TDigitalSigner.Create;
try
sig.PrivateKey := 'C:\work\fhirserver\tests\signatures\private_key.pem';
bytes := sig.signEnveloped(TEncoding.UTF8.GetBytes('<Envelope xmlns="urn:envelope">'+#13#10+'</Envelope>'+#13#10), sdXmlRSASha1, true);
finally
sig.Free;
end;
sig := TDigitalSigner.Create;
try
Assert.IsTrue(sig.verifySignature(bytes));
finally
sig.Free;
end;
end;
procedure TDigitalSignatureTests.testGenRsa_256;
var
bytes : TBytes;
sig : TDigitalSigner;
begin
sig := TDigitalSigner.Create;
try
sig.PrivateKey := 'C:\work\fhirserver\tests\signatures\private_key.pem';
bytes := sig.signEnveloped(TEncoding.UTF8.GetBytes('<Envelope xmlns="urn:envelope">'+#13#10+'</Envelope>'+#13#10), sdXmlRSASha256, true);
finally
sig.Free;
end;
sig := TDigitalSigner.Create;
try
Assert.IsTrue(sig.verifySignature(bytes));
finally
sig.Free;
end;
end;
//procedure TDigitalSignatureTests.testGenDsa_1;
//var
// bytes : TBytes;
// sig : TDigitalSigner;
// output : string;
//begin
// sig := TDigitalSigner.Create;
// try
// sig.PrivateKey := 'C:\work\fhirserver\tests\signatures\private_key.pem';
//
// bytes := sig.signEnveloped(TEncoding.UTF8.GetBytes('<Envelope xmlns="urn:envelope">'+#13#10+'</Envelope>'+#13#10), sdXmlDSASha1, true);
// finally
// sig.Free;
// end;
//
// sig := TDigitalSigner.Create;
// try
// Assert.IsTrue(sig.verifySignature(bytes));
// finally
// sig.Free;
// end;
//end;
//
//procedure TDigitalSignatureTests.testGenDsa_256;
//var
// bytes : TBytes;
// sig : TDigitalSigner;
// output : string;
//begin
// sig := TDigitalSigner.Create;
// try
// sig.PrivateKey := 'C:\work\fhirserver\tests\signatures\private_key.pem';
//
// bytes := sig.signEnveloped(TEncoding.UTF8.GetBytes('<Envelope xmlns="urn:envelope">'+#13#10+'</Envelope>'+#13#10), sdXmlDSASha256, true);
// finally
// sig.Free;
// end;
//
// sig := TDigitalSigner.Create;
// try
// Assert.IsTrue(sig.verifySignature(bytes));
// finally
// sig.Free;
// end;
//end;
initialization
TDUnitX.RegisterTestFixture(TDigitalSignatureTests);
end.
|
{
IndySOAP: Exception types raised by IndySOAP
}
unit IdSoapExceptions;
{$I IdSoapDefines.inc}
interface
uses
IdException;
type
// base class for all IndySoap exceptions
EIdSoapException = class (EIdException);
// raised when a parameter type is not registered with the TypeRegistry
EIdSoapUnknownType = class(EIdSoapException);
// raised when there is some other problem with a parameter of an interface in the ITI,
// or at run time when a parameter value is bad
EIdSoapBadParameterValue = class(EIdSoapException);
// raised when there is some other problem with an interface in the ITI
EIdSoapBadDefinition = class(EIdSoapException);
// raised when there is some other problem with a stored ITI
EIdSoapBadITIStore = class(EIdSoapException);
// raised when some condition that is required for execution to
// continue has not been met (usually related to a failure on the
// part of a developer)
EIdSoapRequirementFail = class(EIdSoapException);
EIdUnderDevelopment = class(EIdSoapException);
// raised when the SOAP encoder does not like a parameter name
EIdSoapBadParameterName = class(EIdSoapException);
// raised when there is a problem with the binary format
EIdSoapBadBinaryFormat = class(EIdSoapException);
// raised when a property name is not found
EIdSoapUnknownPropertyName = class(EIdSoapException);
// raised if method not found in VMT
EIdSoapMethodNotFound = class(EIdSoapException);
// raised when there is name space problems encoding
EIdSoapNamespaceProblem = class (EIdException);
// a date format was invalid
EIdSoapDateTimeError = class (EIdSoapException);
// server or client was unhappy with mime type of soap message
EIdSoapBadMimeType = class (EIdException);
// server or client had a SOAP header related error
EIdSoapHeaderException = class (EIdSoapException);
EIdSoapSessionRequired = class (EIdSoapException);
// for the server application to raise if session is not valid
EIdSoapSessionInvalid = class (EIdSoapException);
// raised by the client when interfaces are tied to the client session and the session has been changed
EIdSoapSessionChanged = class (EIdSoapException);
// raised by TIdSoapTwoWayTCPIP if an attempt is made to send while there is no connection
EIdSoapNotConnected = class (EIdSoapException);
// raised by TIdSoapTwoWayTCPIP if it can't connect
EIdSoapUnableToConnect = class (EIdSoapException);
EIdSoapSchemaException = class (EIdSoapException);
EIdSoapSchemaParseException = class (EIdSoapSchemaException);
// a problem with the XML reported by the Custom Parser
EIdSoapXmlParseError = class (EIdSoapException);
implementation
end.
|
unit util_u;
// Craig Stroberg
// 70854
// Some reuseable functions
interface
type
TUtil = class
private
{ Private declarations }
public
function isNumber(s: string): Boolean;
function isValidEmail(email: string): Boolean;
{ Public declarations }
end;
var
util: TUtil;
implementation
{ TMatcoUtil }
function TUtil.isNumber(s: string): Boolean;
var
i: Integer;
begin
i := 1;
while (i <= Length(s)) and
(s[i] in ['0' .. '9', '.', 'A' .. 'F', 'a' .. 'f']) do
inc(i);
result := i > Length(s);
end;
function TUtil.isValidEmail(email: string): Boolean;
// http://www.howtodothings.com/computers/a1169-validating-email-addresses-in-delphi.html
// Returns True if the email address is valid
const
// Valid characters in an "atom"
atom_chars = [#33 .. #255] - ['(', ')', '<', '>', '@', ',', ';', ':', '\',
'/', '"', '.', '[', ']', #127];
// Valid characters in a "quoted-string"
quoted_string_chars = [#0 .. #255] - ['"', #13, '\'];
// Valid characters in a subdomain
letters = ['A' .. 'Z', 'a' .. 'z'];
letters_digits = ['0' .. '9', 'A' .. 'Z', 'a' .. 'z'];
subdomain_chars = ['-', '0' .. '9', 'A' .. 'Z', 'a' .. 'z'];
type
States = (STATE_BEGIN, STATE_ATOM, STATE_QTEXT, STATE_QCHAR, STATE_QUOTE,
STATE_LOCAL_PERIOD, STATE_EXPECTING_SUBDOMAIN, STATE_SUBDOMAIN,
STATE_HYPHEN);
var
State: States;
i, n, subdomains: Integer;
c: char;
begin
State := STATE_BEGIN;
n := Length(email);
i := 1;
subdomains := 1;
while (i <= n) do
begin
c := email[i];
case State of
STATE_BEGIN:
if c in atom_chars then
State := STATE_ATOM
else if c = '"' then
State := STATE_QTEXT
else
break;
STATE_ATOM:
if c = '@' then
State := STATE_EXPECTING_SUBDOMAIN
else if c = '.' then
State := STATE_LOCAL_PERIOD
else if not(c in atom_chars) then
break;
STATE_QTEXT:
if c = '\' then
State := STATE_QCHAR
else if c = '"' then
State := STATE_QUOTE
else if not(c in quoted_string_chars) then
break;
STATE_QCHAR:
State := STATE_QTEXT;
STATE_QUOTE:
if c = '@' then
State := STATE_EXPECTING_SUBDOMAIN
else if c = '.' then
State := STATE_LOCAL_PERIOD
else
break;
STATE_LOCAL_PERIOD:
if c in atom_chars then
State := STATE_ATOM
else if c = '"' then
State := STATE_QTEXT
else
break;
STATE_EXPECTING_SUBDOMAIN:
if c in letters then
State := STATE_SUBDOMAIN
else
break;
STATE_SUBDOMAIN:
if c = '.' then
begin
inc(subdomains);
State := STATE_EXPECTING_SUBDOMAIN
end
else if c = '-' then
State := STATE_HYPHEN
else if not(c in letters_digits) then
break;
STATE_HYPHEN:
if c in letters_digits then
State := STATE_SUBDOMAIN
else if c <> '-' then
break;
end;
inc(i);
end;
if i <= n then
result := False
else
result := (State = STATE_SUBDOMAIN) and (subdomains >= 2);
end;
end.
|
unit GameMainMenu;
{******************************************************************************}
{ }
{ Siege Of Avalon : Open Source Edition }
{ ------------------------------------- }
{ }
{ Portions created by Digital Tome L.P. Texas USA are }
{ Copyright ©1999-2000 Digital Tome L.P. Texas USA }
{ All Rights Reserved. }
{ }
{ Portions created by Team SOAOS are }
{ Copyright (C) 2003 - Team SOAOS. }
{ }
{ }
{ Contributor(s) }
{ -------------- }
{ Dominique Louis <Dominique@SavageSoftware.com.au> }
{ }
{ }
{ }
{ You may retrieve the latest version of this file at the SOAOS project page : }
{ http://www.sourceforge.com/projects/soaos }
{ }
{ The contents of this file maybe used with permission, subject to }
{ the GNU Lesser General Public License Version 2.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.opensource.org/licenses/lgpl-license.php }
{ }
{ 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. }
{ }
{ Description }
{ ----------- }
{ }
{ }
{ }
{ }
{ }
{ }
{ }
{ Requires }
{ -------- }
{ SDL ( http://www.libsdl.org ) and DirectX ( http://www.microsoft.com ) }
{ Runtime libraris on Win32 and just SDL ( http://www.libsdl.org ) shared }
{ objects or their equivalents on Linux and other Unixes }
{ }
{ Programming Notes }
{ ----------------- }
{ Should compile with Delphi, Kylix and FreePascal on Win32 and Linux for }
{ starter and FreeBSD and MacOS X etc there after. }
{ }
{ }
{ Revision History }
{ ---------------- }
{ September 30 2004 - DL : Initial Creation }
{ }
{
$Log: GameMainMenu.pas,v $
Revision 1.9 2005/06/13 19:36:15 savage
Patch for Menu locations submitted by Stefan Kloe - Thanks.
Revision 1.8 2005/06/02 22:51:54 savage
More Cross-Platform additions and amendments
Revision 1.7 2005/05/28 16:16:56 savage
If InGame and we click Exit we want to go back to the MainMenu.
Revision 1.6 2005/05/25 23:15:42 savage
Latest Changes
Revision 1.5 2005/05/13 12:33:15 savage
Various Changes and bug fixes. Main work on the NewGame screen.
Revision 1.4 2005/05/10 14:12:48 savage
Latest Enhancments and bug fixes
Revision 1.3 2005/05/07 19:50:53 savage
Added Exception logging to help track down errors
Revision 1.2 2004/10/06 22:48:46 savage
Changes required to make use of YesNoDialog
Revision 1.1 2004/09/30 22:49:20 savage
Initial Game Interface units.
}
{******************************************************************************}
interface
uses
sdl,
SiegeInterfaces;
type
TMainMenuRect = record
Rect : TSDL_Rect;
Image : PSDL_Surface;
Enabled : boolean;
end;
TMainMenu = class( TSimpleSoAInterface )
private
FMenuChoice : integer;
FPrevChoice : integer;
procedure GetMenuRect( var MenuItem : TMainMenuRect; X, Y : integer; BM : PSDL_Surface );
procedure SetNextGameInterface;
function Exit : boolean;
public
MenuItems : array[ 1..8 ] of TMainMenuRect;
procedure FreeSurfaces; override;
procedure LoadSurfaces; override;
procedure Render; override;
procedure MouseDown( Button : Integer; Shift : TSDLMod; CurrentPos : TPoint ); override;
procedure MouseMove( Shift : TSDLMod; CurrentPos : TPoint; RelativePos : TPoint ); override;
procedure KeyDown( var Key : TSDLKey; Shift : TSDLMod; unicode : UInt16 ); override;
end;
implementation
uses
SysUtils,
xplatformutils,
logger,
globals,
NewGame,
LoadSaveGame,
GameOptions,
GameJournal,
GameCredits,
YesNoDialog;
const
XFrame = 106;
YFrame = 41;
{ TMainMenu }
procedure TMainMenu.FreeSurfaces;
var
i : integer;
begin
for i := Low( MenuItems ) to High( MenuItems ) do
begin
SDL_FreeSurface( MenuItems[ i ].Image );
end;
inherited;
end;
procedure TMainMenu.KeyDown( var Key : TSDLKey; Shift : TSDLMod; unicode : UInt16 );
const
FailName : string = 'TMainMenu.KeyDown';
begin
inherited;
try
case Key of
SDLK_RETURN :
begin
SetNextGameInterface;
end;
SDLK_ESCAPE :
begin
FMenuChoice := 7;
SetNextGameInterface;
end;
SDLK_UP :
begin
dec( FMenuChoice );
if FMenuChoice < Low( MenuItems ) then
FMenuChoice := High( MenuItems );
while not MenuItems[ FMenuChoice ].Enabled do
dec( FMenuChoice );
end;
SDLK_DOWN :
begin
inc( FMenuChoice );
while not MenuItems[ FMenuChoice ].Enabled do
inc( FMenuChoice );
if FMenuChoice > High( MenuItems ) then
FMenuChoice := Low( MenuItems );
end;
end;
except
on E: Exception do
Log.LogError( E.Message, FailName );
end;
end;
procedure TMainMenu.LoadSurfaces;
const
XFrame = 106;
YFrame = 41;
FailName : string = 'TMainMenu.LoadSurfaces';
Flags : Cardinal = SDL_SRCCOLORKEY or SDL_RLEACCEL or SDL_HWACCEL;
var
Rect : TSDL_Rect;
MainText : PSDL_Surface;
Y1 : integer;
FileData : TSearchRec;
begin
inherited;
try
FPrevChoice := 0; // Reset menu item
FMenuChoice := 1; // Highlight new game
DXBack := SDL_LoadBMP( PChar( SoASettings.InterfacePath + DIR_SEP + 'gMainMenuBlank.bmp' ) );
SDL_SetColorKey( DXBack, Flags, SDL_MapRGB( DXBack.format, 0, 255, 255 ) );
MainText := SDL_LoadBMP( PChar( SoASettings.InterfacePath + DIR_SEP + SoASettings.LanguagePath + DIR_SEP + 'gMainMenuText.bmp' ) );
SDL_SetColorKey( DXBack, Flags, SDL_MapRGB( DXBack.format, 0, 255, 255 ) );
Rect.x := 106;
Rect.y := 41;
Rect.w := 582;
Rect.h := 416;
SDL_BlitSurface( MainText, nil, DXBack, @Rect );
SDL_FreeSurface( MainText );
MainText := SDL_LoadBMP( PChar( SoASettings.InterfacePath + DIR_SEP + SoASettings.LanguagePath + DIR_SEP + 'gMainMenuTextBttns.bmp' ) );
Y1 := YFrame;
GetMenuRect( MenuItems[ 1 ], XFrame, Y1, MainText );
MenuItems[ 1 ].Enabled := not bInGame;
inc( Y1, 52 );
GetMenuRect( MenuItems[ 2 ], XFrame, Y1, MainText );
MenuItems[ 2 ].Enabled := FindFirst( ExtractFilePath( ParamStr( 0 ) ) + 'games/*.sav', faAnyFile, FileData ) = 0;
inc( Y1, 52 );
GetMenuRect( MenuItems[ 3 ], XFrame, Y1, MainText );
MenuItems[ 3 ].Enabled := bInGame;
inc( Y1, 52 );
GetMenuRect( MenuItems[ 4 ], XFrame, Y1, MainText );
MenuItems[ 4 ].Enabled := true;
inc( Y1, 52 );
GetMenuRect( MenuItems[ 5 ], XFrame, Y1, MainText );
MenuItems[ 5 ].Enabled := true;
inc( Y1, 52 );
GetMenuRect( MenuItems[ 6 ], XFrame, Y1, MainText );
MenuItems[ 6 ].Enabled := true;
inc( Y1, 52 );
GetMenuRect( MenuItems[ 7 ], XFrame, Y1, MainText );
MenuItems[ 7 ].Enabled := true;
inc( Y1, 52 );
GetMenuRect( MenuItems[ 8 ], XFrame, Y1, MainText );
MenuItems[ 8 ].Enabled := bInGame;
ExText.Open( 'Intro' );
SDL_FreeSurface( MainText );
except
on E: Exception do
Log.LogError( E.Message, FailName );
end;
end;
procedure TMainMenu.GetMenuRect( var MenuItem : TMainMenuRect; X, Y : integer; BM : PSDL_Surface );
const
W = 582;
H = 52;
FailName : string = 'TMainMenu.GetMenuRect';
var
Flags : Cardinal;
begin
try
MenuItem.Rect.x := X - XFrame;
MenuItem.Rect.y := Y - YFrame;
MenuItem.Rect.w := X + W;
MenuItem.Rect.h := Y + H;
MenuItem.Image := SDL_CreateRGBSurface( SDL_SWSURFACE, W, H,
MainWindow.DisplaySurface.format.BitsPerPixel, MainWindow.DisplaySurface.format.RMask, MainWindow.DisplaySurface.format.GMask,
MainWindow.DisplaySurface.format.BMask, MainWindow.DisplaySurface.format.AMask );
Flags := SDL_SRCCOLORKEY or SDL_RLEACCEL or SDL_HWACCEL;
SDL_SetColorKey( MenuItem.Image, Flags, SDL_MapRGB( MenuItem.Image.format, 255, 0, 255 ) );
SDL_BlitSurface( BM, @MenuItem.Rect, MenuItem.Image, nil );
except
on E: Exception do
Log.LogError( E.Message, FailName );
end;
end;
procedure TMainMenu.MouseDown( Button : Integer; Shift : TSDLMod; CurrentPos : TPoint );
const
FailName : string = 'TMainMenu.MouseDown';
var
i : integer;
begin
inherited;
try
for i := 1 to 8 do
begin
if ( MenuItems[ i ].enabled )
and ( PointIsInRect( CurrentPos, MenuItems[ i ].Rect.x, MenuItems[ i ].Rect.x, MenuItems[ i ].Rect.w, MenuItems[ i ].Rect.h ) ) then
begin
FMenuChoice := i;
SetNextGameInterface;
break;
end;
end;
except
on E: Exception do
Log.LogError( E.Message, FailName );
end;
end;
procedure TMainMenu.MouseMove( Shift : TSDLMod; CurrentPos, RelativePos : TPoint );
const
FailName : string = 'TMainMenu.MouseMove';
var
i : integer;
begin
inherited;
try
for i := 1 to 8 do
begin
if ( MenuItems[ i ].enabled )
and ( PointIsInRect( CurrentPos, MenuItems[ i ].Rect.x, MenuItems[ i ].Rect.x, MenuItems[ i ].Rect.w, MenuItems[ i ].Rect.h ) ) then
begin
FMenuChoice := i;
break;
end;
end;
except
on E: Exception do
Log.LogError( E.Message, FailName );
end;
end;
procedure TMainMenu.Render;
const
FailName : string = 'TMainMenu.Render';
var
Rect : TSDL_Rect;
begin
inherited;
try
if FMenuChoice <> FPrevChoice then
begin
Rect.x := MenuItems[ FMenuChoice ].Rect.x + 106;
Rect.y := MenuItems[ FMenuChoice ].Rect.y + 41;
Rect.w := MenuItems[ FMenuChoice ].Rect.w - MenuItems[ FMenuChoice ].Rect.x;
Rect.h := MenuItems[ FMenuChoice ].Rect.h - MenuItems[ FMenuChoice ].Rect.y;
SDL_BlitSurface( MenuItems[ FMenuChoice ].Image, nil, MainWindow.DisplaySurface, @Rect );
end;
except
on E: Exception do
Log.LogError( E.Message, FailName );
end;
end;
procedure TMainMenu.SetNextGameInterface;
const
FailName : string = 'TMainMenu.SetNextGameInterface';
begin
try
MainWindow.Rendering := false;
case FMenuChoice of
1 : NextGameInterface := TNewGame;
2 : NextGameInterface := TLoadGame;
3 : NextGameInterface := TSaveGame;
4 : NextGameInterface := TGameOptions;
5 : NextGameInterface := TGameJournal;
6 : NextGameInterface := TGameCredits;
7 :
begin
if Exit then
if bInGame then
NextGameInterface := TMainMenu
else
NextGameInterface := nil
else
MainWindow.Rendering := true;
end ;
8 : NextGameInterface := TMainMenu;
end;
except
on E: Exception do
Log.LogError( E.Message, FailName );
end;
end;
function TMainMenu.Exit: boolean;
const
FailName : string = 'TMainMenu.Exit';
var
YesNo : TYesNoDialog;
begin
Result := false;
try
YesNo := TYesNoDialog.Create( Application );
try
YesNo.QuestionText := ExText.GetText( 'Message0' );
YesNo.LoadSurfaces;
Application.Show;
Result := ( YesNo.DialogResult = drYes );
finally
YesNo.Free;
end;
ResetInputManager;
except
on E: Exception do
Log.LogError( E.Message, FailName );
end;
end;
end.
|
unit Utils;
interface
function isNumber(const s: String): boolean;
implementation
function isNumber(const s: String): boolean;
var
iValue, iCode: Integer;
begin
val(s, iValue, iCode);
result := (iCode = 0)
end;
end.
|
unit MainFrm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ExtDlgs, JPEG, Vcl.ComCtrls, Vcl.OleCtrls,
SHDocVw, IdBaseComponent, IdAntiFreezeBase, IdAntiFreeze, RuCaptcha,
System.Actions, Vcl.ActnList, HCaptchaFrm, ReCaptchaFrm, TextCaptchaFrm,
SimpleCaptchaFrm;
type
TMainForm = class(TForm)
edtAPIKey: TEdit;
Label2: TLabel;
lblBalance: TLabel;
edtCaptchaId: TEdit;
btnReportBad: TButton;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
TabSheet3: TTabSheet;
IdAntiFreeze1: TIdAntiFreeze;
edtCaptchaAnswer: TEdit;
btnReportGood: TButton;
lblCaptchaAnswer: TLabel;
lblCaptchaId: TLabel;
ActionList1: TActionList;
actReportGood: TAction;
actReportBad: TAction;
TabSheet4: TTabSheet;
HCaptchaFrame1: THCaptchaFrame;
ReCaptchaFrame1: TReCaptchaFrame;
TextCaptchaFrame1: TTextCaptchaFrame;
SimpleCaptchaFrame1: TSimpleCaptchaFrame;
procedure lblBalanceClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure actReportBadExecute(Sender: TObject);
procedure actReportGoodExecute(Sender: TObject);
procedure edtAPIKeyChange(Sender: TObject);
private
{ Private declarations }
FRuCaptcha: TRuCaptcha;
public
{ Public declarations }
property RuCaptcha: TRuCaptcha read FRuCaptcha;
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
procedure TMainForm.edtAPIKeyChange(Sender: TObject);
begin
FRuCaptcha.APIKey := edtAPIKey.Text;
lblBalance.OnClick(Sender);
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
FRuCaptcha := TRuCaptcha.Create;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
FRuCaptcha.Free;
end;
procedure TMainForm.actReportBadExecute(Sender: TObject);
begin
FRuCaptcha.ReportBad(edtCaptchaId.Text);
end;
procedure TMainForm.actReportGoodExecute(Sender: TObject);
begin
FRuCaptcha.ReportGood(edtCaptchaId.Text);
end;
procedure TMainForm.lblBalanceClick(Sender: TObject);
begin
lblBalance.Caption := Format('Баланс: %s', [FRuCaptcha.Balance]);
end;
end.
|
unit RTTIUtilsTests;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpcunit, testregistry, fpjson;
type
{ TRTTIClass }
TRTTIClass = class
private
FJSONArray: TJSONArray;
FJSONData: TJSONData;
FStr: String;
published
property Str: String read FStr write FStr;
property JSONData: TJSONData read FJSONData write FJSONData;
property JSONArray: TJSONArray read FJSONArray write FJSONArray;
end;
{ TSetPropertiesTestCase }
TSetPropertiesTestCase = class(TTestCase)
private
FObj: TRTTIClass;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure SetClassPropertyWithDerivedClass_PropertySet;
procedure SetClassPropertyWithNonDerivedClass_Exception;
end;
implementation
uses
LuiRTTIUtils;
procedure TSetPropertiesTestCase.SetUp;
begin
FObj := TRTTIClass.Create;
end;
procedure TSetPropertiesTestCase.TearDown;
begin
FreeAndNil(FObj);
end;
procedure TSetPropertiesTestCase.SetClassPropertyWithDerivedClass_PropertySet;
var
JSONArray: TJSONArray;
begin
JSONArray := TJSONArray.Create;
SetObjectProperties(FObj, ['JSONArray', JSONArray]);
CheckSame(JSONArray, FObj.JSONArray);
SetObjectProperties(FObj, ['JSONData', JSONArray]);
CheckSame(JSONArray, FObj.JSONData);
JSONArray.Destroy;
end;
procedure TSetPropertiesTestCase.SetClassPropertyWithNonDerivedClass_Exception;
var
JSONObject: TJSONObject;
Raised: Boolean;
begin
Raised := False;
JSONObject := TJSONObject.Create;
try
SetObjectProperties(FObj, ['JSONArray', JSONObject]);
except
Raised := True;
end;
CheckTrue(Raised);
JSONObject.Destroy;
end;
initialization
RegisterTest('RTTIUtils', TSetPropertiesTestCase);
end.
|
{ *********************************************************************
*
* Autor: Efimov A.A.
* E-mail: infocean@gmail.com
* GitHub: https://github.com/AndrewEfimov/
* Platform: only Android (API 21+)
* Created: 24.05.2016
* Updated: 22.03.2022
*
******************************************************************** }
unit uUniversalReceiver;
interface
uses
Androidapi.JNI.Embarcadero, Androidapi.JNIBridge, Androidapi.Helpers, Androidapi.JNI.GraphicsContentViewText,
Androidapi.JNI.JavaTypes;
type
TBroadcastReceiveEvent = procedure(context: JContext; intent: JIntent) of object;
TBroadcastReceiver = class;
TListener = class(TJavaLocal, JFMXBroadcastReceiverListener)
strict private
FOwner: TBroadcastReceiver;
public
constructor Create(AOwner: TBroadcastReceiver);
procedure OnReceive(context: JContext; intent: JIntent); cdecl;
end;
TBroadcastReceiver = class
strict private
FListener: TListener;
FBroadcastReceiver: JFMXBroadcastReceiver;
FIntentFilter: JIntentFilter;
FOnReceive: TBroadcastReceiveEvent;
public
property OnReceive: TBroadcastReceiveEvent read FOnReceive write FOnReceive;
constructor Create;
destructor Destroy; override;
procedure IntentFilterAdd(const AValue: JString); overload;
procedure IntentFilterAdd(const AValues: array of JString); overload;
procedure registerReceiver;
procedure unregisterReceiver;
end;
implementation
{ TListener }
constructor TListener.Create(AOwner: TBroadcastReceiver);
begin
inherited Create;
FOwner := AOwner;
end;
procedure TListener.OnReceive(context: JContext; intent: JIntent);
begin
if Assigned(FOwner.OnReceive) then
FOwner.OnReceive(context, intent);
end;
{ TBroadcastReceiver }
constructor TBroadcastReceiver.Create;
begin
inherited Create;
FListener := TListener.Create(Self);
FBroadcastReceiver := TJFMXBroadcastReceiver.JavaClass.init(FListener);
FIntentFilter := TJIntentFilter.Create;
end;
destructor TBroadcastReceiver.Destroy;
begin
unregisterReceiver;
inherited Destroy;
end;
procedure TBroadcastReceiver.IntentFilterAdd(const AValues: array of JString);
var
I: Integer;
begin
for I := 0 to Length(AValues) - 1 do
IntentFilterAdd(AValues[I]);
end;
procedure TBroadcastReceiver.IntentFilterAdd(const AValue: JString);
begin
if not AValue.isEmpty then
FIntentFilter.addAction(AValue);
end;
procedure TBroadcastReceiver.registerReceiver;
begin
if FIntentFilter.countActions > 0 then
TAndroidHelper.Context.registerReceiver(FBroadcastReceiver, FIntentFilter);
end;
procedure TBroadcastReceiver.unregisterReceiver;
begin
if FBroadcastReceiver <> nil then
TAndroidHelper.Context.unregisterReceiver(FBroadcastReceiver);
FBroadcastReceiver := nil;
FListener.Free;
FIntentFilter := nil;
end;
end.
|
unit PLAT_SQLLawRuleDBManager;
interface
uses dialogs, sysutils, Classes, DBClient, Plat_LawRuleDBManager, PLAT_AdvInterfacedObject;
type
TSQLLawRuleDBManager = class(TAdvInterfacedObject, ILawRuleDBManager)
FClientDataset: TClientDataset;
public
constructor Create();
procedure Insert(LawRuleName: string; LawRuleTitle: string; LawRuleAuthor: string; LawRuleKeyWords: string; LawRuleAbstract: string; LawRuleFileName: string; GroupName: string; AInMenu: Boolean);
procedure UpdateClientDataset(ClientDataset: TClientDataset);
//procedure UpdateDB(ClientDataset:TClientDataset;LRName:String);
procedure UpdateDB(LRName, LRTitle, LRAuthor, LRKeyWords, LRAbstract, LRGroupName: string; LRInMenu: Boolean);
procedure Delete(KeyValue: string);
procedure FetchFile(LRName, FileName: string);
procedure CommitFile(LRName, FileName: string);
procedure GetRelations(LRName: string; strs: TStringList);
procedure AddRelations(LRA, LRB: string);
procedure DeleteRelations(LRA, LRB: string);
procedure GetLawRuleByGroupName(GroupName: string; strs: TStringList);
procedure GetGroupItems(strs: TStringList);
end;
implementation
uses DB, PLAT_Utils, DatamoduleMain, Pub_Function;
{ TSQLLawRuleDBManager }
procedure TSQLLawRuleDBManager.AddRelations(LRA, LRB: string);
begin
FClientDataset.Close;
POpenSql(FClientDataset, 'select * from PT_LRRELATIONS where (LRA=''' + LRA + ''' and LRB=''' + LRB + ''') or (LRA=''' + LRB + ''' and LRB=''' + LRA + ''') ');
if FClientDataset.RecordCount > 0 then
exit
else
begin
FClientDataset.Insert;
FClientDataset.FieldByName('LRA').AsString := LRA;
FClientDataset.FieldByName('LRB').AsString := LRB;
FClientDataset.Post;
// DataModulePub.MidasConnectionPub.appServer.SetTableName('PT_LRRELATIONS');
FClientDataset.ApplyUpdates(0, 'PT_LRRELATIONS');
end;
end;
procedure TSQLLawRuleDBManager.CommitFile(LRName, FileName: string);
begin
FClientDataset.Close;
POpenSql(FClientDataset, 'select * from PT_LAWRULES where LRName=''' + LRName + '''');
if FClientDataset.RecordCount = 0 then
raise Exception.Create('不存在的记录');
FClientDataset.First;
FClientDataset.edit;
FClientDataset.FieldByName('LRModifier').AsString := TUtils.GetCurrentUser;
FClientDataset.FieldByName('LRModifiedTime').AsString := FormatDateTime('YYYYMMDDhhmmss', Now());
FClientDataset.FieldByName('LRDocType').AsString := ExtractFileExt(FileName);
TBlobField(FClientDataset.FieldByName('LRDocument')).LoadFromFile(FileName);
FClientDataset.Post;
// DataModulePub.MidasConnectionPub.appServer.SetTableName('PT_LAWRULES');
FClientDataset.ApplyUpdates(0, 'PT_LAWRULES');
end;
constructor TSQLLawRuleDBManager.Create;
begin
FClientDataset := TClientDataset.Create(nil);
FClientDataset.ProviderName := Tutils.GetSearchProviderName;
FClientdataset.RemoteServer := TUtils.GetRemoteServer;
FClientDataset.FetchOnDemand := true;
end;
procedure TSQLLawRuleDBManager.Delete(KeyValue: string);
begin
FClientDataset.Close;
POpenSql(FClientDataset, 'select * from PT_LAWRULES where LRName=''' + KeyValue + '''');
FClientDataset.delete;
// DataModulePub.MidasConnectionPub.appServer.SetTableName('PT_LAWRULES');
FClientDataset.ApplyUpdates(0, 'PT_LAWRULES');
end;
procedure TSQLLawRuleDBManager.DeleteRelations(LRA, LRB: string);
begin
FClientDataset.Close;
POpenSql(FClientDataset, 'select * from PT_LRRELATIONS where (LRA=''' + LRA + ''' and LRB=''' + LRB + ''') or (LRA=''' + LRB + ''' and LRB=''' + LRA + ''') ');
if FClientDataset.RecordCount = 0 then
exit
else
begin
FClientDataset.First;
FClientDataset.DElete;
// DataModulePub.MidasConnectionPub.appServer.SetTableName('PT_LRRELATIONS');
FClientDataset.ApplyUpdates(0, 'PT_LRRELATIONS');
end;
end;
procedure TSQLLawRuleDBManager.FetchFile(LRName, FileName: string);
begin
FClientDataset.Close;
POpenSql(FClientDataset, 'select * from PT_LAWRULES where LRName=''' + LRName + '''');
if FClientDataset.RecordCount = 0 then
raise Exception.Create('不存在的记录');
FClientDataset.First;
TBlobField(FClientDataset.FieldByName('LRDocument')).SaveToFile(FileName);
end;
procedure TSQLLawRuleDBManager.GetGroupItems(strs: TStringList);
const
ASQL = 'select * from PT_GroupItems ';
begin
FClientDataset.Close;
POpenSql(FClientDataset, ASQL);
strs.Clear;
if FClientDataset.RecordCount = 0 then
exit;
FClientDataset.First;
while not FClientDataset.Eof do
begin
strs.Add(FClientDataset.FieldBYName('ItemName').AsString);
FClientDataset.Next;
end;
end;
procedure TSQLLawRuleDBManager.GetLawRuleByGroupName(GroupName: string;
strs: TStringList);
const
ASQL = 'select * from PT_lawrules,PT_GroupItems where PT_Lawrules.LRGroupName=PT_GroupItems.ItemName and Itemcode=''%s'' and LRINMENU=1';
begin
FClientDataset.Close;
POpenSql(FClientDataset, Format(ASQL, [Groupname]));
strs.Clear;
if FClientDataset.RecordCount = 0 then
exit;
FClientDataset.First;
while not FClientDataset.Eof do
begin
strs.Add(FClientDataset.FieldBYName('LRName').AsString);
FClientDataset.Next;
end;
end;
procedure TSQLLawRuleDBManager.GetRelations(LRName: string; strs: TStringList);
begin
FClientDataset.Close;
POpenSql(FClientDataset, 'select * from PT_LRRELATIONS where LRA=''' + LRName + ''' or LRB=''' + LRName + '''');
if FClientdataset.RecordCount = 0 then
exit;
FClientDataset.First;
while not FClientDataset.Eof do
begin
if LRname = FClientDataset.FieldByName('LRA').AsString then
begin
if strs.IndexOf(FClientDataset.FieldByName('LRB').AsString) = -1 then
begin
strs.Add(FClientDataset.FieldByName('LRB').AsString);
end;
end
else
begin
if strs.IndexOf(FClientDataset.FieldByName('LRA').AsString) = -1 then
begin
strs.Add(FClientDataset.FieldByName('LRA').AsString);
end;
end;
FClientDataset.Next;
end;
end;
procedure TSQLLawRuleDBManager.Insert(LawRuleName, LawRuleTitle,
LawRuleAuthor, LawRuleKeyWords, LawRuleAbstract,
LawRuleFileName: string; GroupName: string; AInMenu: Boolean);
var
sSQL : string;
begin
{
FClientDataset.Close;
FClientDataset.DataRequest ('select * from Pt_lrrelations where 1=2');
FClientDataset.Open;
FClientDataset.Insert;
FClientDataset.FieldByName('LRA').AsString:='sdfasdf';
FClientDataset.FieldByName('LRB').AsString:='LawRuleTitle';
FClientDAtaset.Post;
DataModulePub.MidasConnectionPub.appServer.SetTableName('PT_LRRELATIONS');
FclientDataset.ApplyUpdates (0);
exit;
}
FClientDataset.Close;
POpenSql(FClientDataset, 'select LRName,LRTitle,LRAuthor, LRKeyWords,LRAbstract,LRCreateBy, LRCreateTime ,LRModifier, LRModifiedTime,LRGroupName,LRINMENU from PT_LAWRULES where 1=2');
FClientDataset.append;
FClientDataset.FieldByName('LRName').AsString := LawRuleName;
FClientDataset.FieldByName('LRTitle').AsString := LawRuleTitle;
FClientDataset.FieldByName('LRAuthor').AsString := LawRuleAuthor;
FClientDataset.FieldByName('LRKeyWords').AsString := LawRuleKeyWords;
FClientDataset.FieldByName('LRAbstract').AsString := LawRuleAbstract;
FClientDataset.FieldByName('LRGRoupName').AsString := GroupName;
//FClientDataset.FieldByName('LRINMENU').AsBoolean := AInMenu;
if AInMenu Then // Lzn
FClientDataset.FieldByName('LRINMENU').AsInteger := 1
else FClientDataset.FieldByName('LRINMENU').AsInteger := 0;
{
if LawRuleFileName<>'' then
begin
(FClientDataset.FieldByName('LRDocument') as TBlobField).LoadFromFile(LawRuleFileName);
FClientDataset.FieldByName('LRDoctype').AsString:=ExtractFileExt(LawRuleFileName);
end;
}
FClientDataset.FieldByName('LRCreateBy').AsString := Tutils.GetCurrentUser();
FClientDataset.FieldByName('LRCreateTime').AsString := FormatDateTime('YYYYMMDDhhmmss', now());
FClientDataset.FieldByName('LRModifier').AsString := Tutils.GetCurrentUser();
FClientDataset.FieldByName('LRModifiedTime').AsString := FormatDateTime('YYYYMMDDhhmmss', now());
FClientDataset.Post;
// DataModulePub.MidasConnectionPub.appServer.SetTableName('PT_LAWRULES');
FclientDataset.ApplyUpdates(0, 'PT_LAWRULES');
if LawRuleFileName <> '' then
begin
FClientDataset.Close;
POpenSql(FClientDataset, 'select LRNAME,LRDOCUMENT,LRDOCTYPE from PT_LAWRULES where LRName=''' + LawRuleName + '''');
if FClientDataset.recordcount = 0 then
raise Exception.Create('数据库无记录');
FClientDataset.First;
FClientDataset.Edit;
(FClientDataset.FieldByName('LRDOCUMENT') as TBlobField).LoadFromFile(LawRuleFileName);
FClientDataset.FieldByName('LRDOCTYPE').AsString := ExtractFileExt(LawRuleFileName);
FClientDataset.Post;
// DataModulePub.MidasConnectionPub.appServer.SetTableName('PT_LAWRULES');
FclientDataset.ApplyUpdates(0, 'PT_LAWRULES');
end;
end;
procedure TSQLLawRuleDBManager.UpdateClientDataset(
ClientDataset: TClientDataset);
begin
try
ClientDataset.Close; // 要先关闭,以免报错 Lzn
ClientDataset.ProviderName := TUtils.GetSearchProviderName;
ClientDataset.RemoteServer := TUtils.GetRemoteServer;
ClientDataset.Close;
except;
end;
POpenSql(ClientDataset, 'select lrname,lrtitle,lrauthor,lrkeywords,lrabstract,lrcreateby,lrcreateTime,lrmodifier,lrmodifiedtime,lrdoctype,LRGroupName,LRInMenu from PT_LAWRULES');
end;
procedure TSQLLawRuleDBManager.UpdateDB(LRName, LRTitle, LRAuthor,
LRKeyWords, LRAbstract, LRGroupName: string; LRInMenu: Boolean);
begin
FClientDataset.Close;
POpenSql(FClientDataset, 'select * from PT_LAWRULES where LRName=''' + LRName + '''');
if FClientDataset.RecordCount = 0 then
raise Exception.Create('不存在的记录');
FClientDataset.First;
FClientDataset.edit;
FClientDataset.FieldByName('LRName').AsString := LRName;
FClientDataset.FieldByName('LRTitle').AsString := LRTitle;
FClientDataset.FieldByName('LRAuthor').AsString := LRAuthor;
FClientDataset.FieldByName('LRKeyWords').AsString := LRKeyWords;
FClientDataset.FieldByName('LRAbstract').AsString := LRAbstract;
FClientDataset.FieldByName('LRGroupName').AsString := LRGroupName;
FClientDataset.FieldByName('LRINMENU').AsBoolean := LRInMenu;
FClientDataset.Post;
FClientDataset.ApplyUpdates(0, 'PT_LAWRULES');
end;
end.
|
unit ufrmCrazyPriceDialog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterDialogBrowse, ExtCtrls, Mask, StdCtrls,
math, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
cxContainer, cxEdit, cxTextEdit, cxCurrencyEdit, System.Actions, Vcl.ActnList,
ufraFooterDialog3Button, cxStyles, cxCustomData, cxFilter, cxData,
cxDataStorage, cxNavigator, Data.DB, cxDBData, cxGridLevel, cxClasses,
cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxGrid, Vcl.Menus, cxButtons;
type
TFormMode = (fmAdd, fmEdit);
TfrmCrazyPriceDialog = class(TfrmMasterDialogBrowse)
pnl2: TPanel;
lbl3: TLabel;
lbl7: TLabel;
lbl9: TLabel;
lbl11: TLabel;
edtCode: TEdit;
edtName: TEdit;
edtDisc: TcxCurrencyEdit;
edtCrazyPrice: TcxCurrencyEdit;
lbl10: TLabel;
edtConValue: TcxCurrencyEdit;
cbbUOM: TComboBox;
curredtStorePrice: TcxCurrencyEdit;
lbl1: TLabel;
curredtPriceDisc: TcxCurrencyEdit;
edtDiscPersen: TcxCurrencyEdit;
lbl2: TLabel;
lbl4: TLabel;
curredtDiscNominal: TcxCurrencyEdit;
Label1: TLabel;
cbTipeHarga: TComboBox;
btnAdd: TcxButton;
btnRemove: TcxButton;
procedure footerDialogMasterbtnSaveClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure edtCodeKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure btnAddClick(Sender: TObject);
procedure strgGridGetFloatFormat(Sender: TObject; ACol, ARow: Integer;
var IsFloat: Boolean; var FloatFormat: String);
procedure strgGridCanEditCell(Sender: TObject; ARow, ACol: Integer;
var CanEdit: Boolean);
procedure cbbUOMChange(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure cbbUOMKeyPress(Sender: TObject; var Key: Char);
procedure edtDiscPersenKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure btnRemoveClick(Sender: TObject);
procedure edtCrazyPriceKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure strgGridCellValidate(Sender: TObject; ACol, ARow: Integer;
var Value: String; var Valid: Boolean);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edtDiscPersenExit(Sender: TObject);
procedure edtCrazyPriceExit(Sender: TObject);
procedure curredtDiscNominalKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure curredtDiscNominalExit(Sender: TObject);
procedure strgGridDblClickCell(Sender: TObject; ARow, ACol: Integer);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
FSellPrice : Currency;
FisEditRec : Boolean;
Fidx : Integer;
FIdxTipeHarga: Integer;
FTipeHrg: Integer;
procedure GetUOMByBrgCode;
// function FindOnGrid(strBrgCode: String): Boolean;
procedure CalcDiscAndNominalDisc;
procedure setHarga;
public
{ Public declarations }
IsProcessSuccessfull: Boolean;
formMode: TFormMode;
CrazID: Integer;
procedure ClearTextValue;
procedure LoadTipeHarga;
procedure ParseHeaderGrid;
procedure SaveDataCrazyPrice_New;
property IdxTipeHarga: Integer read FIdxTipeHarga write FIdxTipeHarga;
property TipeHrg: Integer read FTipeHrg write FTipeHrg;
end;
var
frmCrazyPriceDialog: TfrmCrazyPriceDialog;
const
_KolBrgKode : Integer = 0;
_KolBrgNama : Integer = 1;
_KolSatKode : Integer = 2;
_KolConValue : Integer = 3;
_KolBuyPrice : Integer = 4;
_KolBHJMarkUp : Integer = 5;
_KolBHJSellPrice : Integer = 6;
_KolBHJDiscPersen : Integer = 7;
_KolBHJDiscNominal : Integer = 8;
_KolBHJSellPriceDisc : Integer = 9;
_KolStorePrice : Integer = 10;
implementation
uses uTSCommonDlg, ufrmSearchProduct, uRetnoUnit;
{$R *.dfm}
procedure TfrmCrazyPriceDialog.footerDialogMasterbtnSaveClick(
Sender: TObject);
begin
inherited;
// if not IsValidDateKarenaEOD(dialogunit,cGetServerTime,FMasterIsStore) then
Exit;
{
if strgGrid.RowCount > 1 then
begin
SaveDataCrazyPrice_New;
end
Else
Begin
CommonDlg.ShowMessage('Daftar product masih kosong !');
Exit;
End;
}
Close;
end;
procedure TfrmCrazyPriceDialog.FormDestroy(Sender: TObject);
begin
inherited;
frmCrazyPriceDialog := nil;
end;
procedure TfrmCrazyPriceDialog.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TfrmCrazyPriceDialog.edtCodeKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
s: string;
Code: String;
begin
inherited;
if (Key = VK_F5) OR (Key = VK_DOWN) then
begin
s := 'Select BRG_CODE as KODE, BRG_NAME as NAMA, BRG_MERK as MERK, BRG_ALIAS as ALIAS, BRG_CATALOG as KATALOG, BRG_HARGA_AVERAGE as HARGAAVERAGE'
+ ' From BARANG ';
// + ' AND BRG_IS_ACTIVE = 1';
{with clookup('Daftar PLU', s) do
begin
Try
if Strings[0] = '' then Exit;
if not Assigned(SellingPrice) then
SellingPrice := TSellingPrice.Create;
Code := Strings[0];
edtCode.Text := Code;
edtName.Text := Strings[1];
GetUOMByBrgCode();
curredtStorePrice.Value := SellingPrice.GetStorePrice(Code, DialogUnit);
if cbbUOM.Items.Count > 0 then
begin
cbbUOM.ItemIndex := 0;
cbbUOMChange(Self);
end;
Finally
Free;
End;
end; }
end else
if Key = VK_RETURN then
begin
if Length(edtCode.Text) < igProd_Code_Length then
Exit
else if Length(edtCode.Text) = igProd_Code_Length then
begin
{if not assigned(SellingPrice) then
SellingPrice := TSellingPrice.Create;
edtName.Text := SellingPrice.GetProductName(edtCode.Text, DialogUnit);
GetUOMByBrgCode();
curredtStorePrice.Value := SellingPrice.GetStorePrice(edtCode.Text, DialogUnit);
}
if cbbUOM.Items.Count > 0 then
begin
cbbUOM.ItemIndex := 0;
cbbUOMChange(Self);
end;
edtCrazyPrice.SetFocus;
edtCrazyPrice.SelectAll;
end;
end;
end;
procedure TfrmCrazyPriceDialog.btnAddClick(Sender: TObject);
var
aRow : Integer;
begin
inherited;
if edtCode.Text = '' then
Exit;
if edtCrazyPrice.Value = 0 then
Exit;
{
aRow := strgGrid.RowCount - strgGrid.FixedRows;//initialisasi
if FisEditRec and (Fidx <> 0) then
begin
aRow := Fidx;
end
else
begin
if strgGrid.RowCount > strgGrid.FixedRows then
begin
if strgGrid.Cells[_KolBrgKode, strgGrid.Row] <> '' then
begin
strgGrid.AddRow;
end;
aRow := strgGrid.RowCount - strgGrid.FixedRows;
end;
end;
strgGrid.Cells[_KolBrgKode, aRow] := edtCode.Text;
strgGrid.Cells[_KolBrgNama, aRow] := edtName.Text;
strgGrid.Cells[_KolSatKode, aRow] := cbbUOM.Text;
strgGrid.Cells[_KolConValue, aRow] := FloatToStr(edtConValue.Value);
strgGrid.Cells[_KolBuyPrice, aRow] := CurrToStr(curredtPriceDisc.Value);
strgGrid.Cells[_KolBHJMarkUp, aRow] := FloatToStr(edtDisc.Value);
strgGrid.Cells[_KolBHJSellPrice, aRow] := CurrToStr(FSellPrice);
strgGrid.Cells[_KolBHJDiscPersen, aRow] := FloatToStr(edtDiscPersen.Value);
strgGrid.Cells[_KolBHJDiscNominal, aRow] := CurrToStr(curredtDiscNominal.Value);
strgGrid.Cells[_KolBHJSellPriceDisc, aRow] := CurrToStr(edtCrazyPrice.Value);
strgGrid.Cells[_KolStorePrice, aRow] := CurrToStr(curredtStorePrice.Value);
}
CbbUom.Clear;
edtCode.Clear;
edtName.Clear;
curredtStorePrice.Value := 0;
ClearTextValue;
edtCode.SetFocus;
end;
procedure TfrmCrazyPriceDialog.strgGridGetFloatFormat(Sender: TObject;
ACol, ARow: Integer; var IsFloat: Boolean; var FloatFormat: String);
begin
inherited;
if ACol in [_KolBrgKode.._KolSatKode] then
IsFloat := False;
if IsFloat then
FloatFormat := '%.2n';
end;
procedure TfrmCrazyPriceDialog.strgGridCanEditCell(Sender: TObject; ARow,
ACol: Integer; var CanEdit: Boolean);
begin
inherited;
if ACol in [_KolBHJDiscPersen, _KolBHJSellPriceDisc] then CanEdit := True else CanEdit := False;
end;
procedure TfrmCrazyPriceDialog.GetUOMByBrgCode;
var
s: string;
begin
s := 'SELECT DISTINCT BHJ_SAT_CODE'
+ ' FROM BARANG_HARGA_JUAL'
+ ' WHERE BHJ_BRG_CODE = ' + QuotedStr(edtCode.Text);
// cQueryToCombo(cbbUOM, s);
end;
procedure TfrmCrazyPriceDialog.cbbUOMChange(Sender: TObject);
begin
inherited;
ClearTextValue;
setHarga;
end;
procedure TfrmCrazyPriceDialog.FormShow(Sender: TObject);
begin
inherited;
Fidx := 0;
if formMode = fmAdd then
begin
LoadTipeHarga;
ParseHeaderGrid;
end;
// strgGrid.ColWidths[_KolBHJMarkUp] := 0;
edtCode.SetFocus;
end;
procedure TfrmCrazyPriceDialog.cbbUOMKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Ord(Key) in [97..122] then
Key:= UpCase(Key)
end;
procedure TfrmCrazyPriceDialog.ParseHeaderGrid;
begin
{with strgGrid do
begin
ColCount:= 11;
RowCount:= 2;
Cells[_KolBrgKode, 0] := 'PRODUCT CODE';
Cells[_KolBrgNama, 0] := 'PRODUCT NAME';
Cells[_KolSatKode, 0] := 'UOM';
Cells[_KolConValue, 0] := 'CONV. VALUE';
Cells[_KolBuyPrice, 0] := 'BUY PRICE';
Cells[_KolBHJMarkUp, 0] := 'MARK UP %';
Cells[_KolBHJSellPrice, 0] := 'SELL PRICE';
Cells[_KolBHJDiscPersen, 0] := 'DISC %';
Cells[_KolBHJDiscNominal, 0] := 'DISC NOMINAL';
Cells[_KolBHJSellPriceDisc, 0] := 'CRAZY PRICE';
Cells[_KolStorePrice, 0] := 'STORE PRICE';
FixedRows := 1;
ColWidths[_KolBuyPrice] := 0;
ColWidths[_KolStorePrice] := 0;
end;
}
end;
procedure TfrmCrazyPriceDialog.CalcDiscAndNominalDisc;
var
curCP,
curSP,
curNominalDisc: Currency;
NominalMarkup,
ExtDisc,
ExtMarkup: Real;
begin
ExtDisc := edtDiscPersen.Value;
curSP := curredtStorePrice.Value;
curCP := edtCrazyPrice.Value;
NominalMarkup := curCP - curredtPriceDisc.Value;
if curredtPriceDisc.Value <> 0 then
ExtMarkUp := StrToFloat(FormatFloat('0.00', (NominalMarkup/ curredtPriceDisc.Value)*100))
else
ExtMarkup := 0;
edtDisc.Value := ExtMarkUp;
curNominalDisc := (ExtDisc * curSP)/100;
FSellPrice := curCP + curNominalDisc;
curredtDiscNominal.Value:= curNominalDisc;
end;
procedure TfrmCrazyPriceDialog.edtDiscPersenKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if Key = VK_RETURN then
begin
edtDiscPersenExit(Self);
curredtDiscNominal.SetFocus;
end;
end;
procedure TfrmCrazyPriceDialog.LoadTipeHarga;
var
s: string;
begin
// TODO -cMM: TfrmCrazyPriceDialog.LoadTipeHarga default body inserted
s := 'Select TPHRG_ID, TPHRG_NAME From REF$TIPE_HARGA Where TPHRG_CODE <> ' + QuotedStr('H002')
+ ' AND TPHRG_UNT_ID = ' + IntToStr(DialogUnit)
+ ' Order By TPHRG_NAME';
// cQueryToComboObject(cbTipeHarga, s);
cbTipeHarga.ItemIndex := IdxTipeHarga;
end;
procedure TfrmCrazyPriceDialog.SaveDataCrazyPrice_New;
var
FTipeHrgID: Integer;
strSat: string;
strCode: string;
i: Integer;
FBarangHargaJualID: Integer;
// FBarangHargaJual: TBarangHargaJual;
begin
// TODO -cMM: TfrmCrazyPriceDialog.SaveDataCrazyPrice_New default body inserted
{try
Self.Enabled := False;
IsProcessSuccessfull := False;
FBarangHargaJual := TBarangHargaJual.Create(nil);
FTipeHrgID := cGetIDfromCombo(cbTipeHarga, cbTipeHarga.ItemIndex);
for i := 1 to strgGrid.RowCount - 1 do
begin
strCode := strgGrid.Cells[_KolBrgKode, i];
strSat := strgGrid.Cells[_KolSatKode, i];
FBarangHargaJual.ClearProperties;
if FBarangHargaJual.LoadByBarangKodeTipeHarga(strCode, strSat, FTipeHrgID) then
begin
FBarangHargaJualID := FBarangHargaJual.ID;
end
else
begin
FBarangHargaJualID := 0;
if DialogUnit <> 1 then
begin
CommonDlg.ShowMessage('Tipe Harga ' + cbTipeHarga.Text + ' Untuk PLU ' + strCode + ' belum diset di HO' + #13 +
'Proses simpan tidak bisa dilanjutkan');
Exit;
end;
end;
FBarangHargaJual.UpdateData(0,
StrToFloat(strgGrid.Cells[_KolBHJDiscNominal, i]),
StrToFloat(strgGrid.Cells[_KolBHJDiscPersen, i]),
FBarangHargaJualID,
0,
0,
StrToFloat(strgGrid.Cells[_KolConValue, i]),
0,
0,
StrToFloat(strgGrid.Cells[_KolBHJMarkUp, i]),
strCode,
DialogUnit,
strSat,
0,
0,
'',
StrToFloat(strgGrid.Cells[_KolBHJSellPrice, i]),
0,
StrToFloat(strgGrid.Cells[_KolBHJSellPriceDisc, i]),
FTipeHrgID,
0,
0);
if not FBarangHargaJual.ExecuteGenerateSQL then
begin
cRollbackTrans;
CommonDlg.ShowMessage('Gagal Simpan Crazy Price');
Exit;
end;
end;
cCommitTrans;
IsProcessSuccessfull := True;
CommonDlg.ShowMessage('Sukses Simpan Crazy Price');
finally
Self.Enabled := True;
cRollbackTrans;
if FBarangHargaJual <> nil then FreeAndNil(FBarangHargaJual);
end;
}
end;
procedure TfrmCrazyPriceDialog.btnRemoveClick(Sender: TObject);
var
i: Integer;
begin
inherited;
{if strgGrid.Row > 0 then
begin
if strgGrid.Row > 1 then
strgGrid.RemoveSelectedRows
else
begin
for i := 0 to strgGrid.ColCount - 1 do
strgGrid.Cells[i, 1] := '';
end;
end;
}
end;
procedure TfrmCrazyPriceDialog.ClearTextValue;
begin
// TODO -cMM: TfrmCrazyPriceDialog.ClearTextValue default body inserted
edtDisc.Value := 0;
edtConValue.Value := 0;
curredtPriceDisc.Value := 0;
edtCrazyPrice.Value := 0;
edtDiscPersen.Value := 0;
curredtDiscNominal.Value := 0;
end;
procedure TfrmCrazyPriceDialog.edtCrazyPriceKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if Key = VK_RETURN then
begin
edtCrazyPriceExit(Self);
edtDiscPersen.SetFocus;
end;
end;
procedure TfrmCrazyPriceDialog.strgGridCellValidate(Sender: TObject; ACol,
ARow: Integer; var Value: String; var Valid: Boolean);
var
dDiscNominal: Double;
dMarkUp: Double;
begin
inherited;
if (ACol = _KolBHJSellPriceDisc) Or (Acol = _KolBHJDiscPersen) then
begin
{if strgGrid.Cells[_KolBuyPrice, ARow] = '0' then
strgGrid.Cells[_KolBHJMarkUp, ARow] := '0'
else
begin
dMarkUp := (StrToFloat(strgGrid.Cells[_KolBuyPrice, ARow]) - StrToFloat(strgGrid.Cells[_KolBHJSellPriceDisc, ARow])) / StrToFloat(strgGrid.Cells[_KolBuyPrice, ARow]) * 100;
dMarkUp := StrToFloat(FormatFloat('0.00', dMarkUp));
strgGrid.Cells[_KolBHJMarkUp, ARow] := FloatToStr(dMarkUp);
end;
if strgGrid.Cells[_KolBHJDiscPersen, ARow] = '0' then
strgGrid.Cells[_KolBHJDiscPersen, ARow] := '0'
else
begin
dDiscNominal := (StrToFloat(strgGrid.Cells[_KolBHJDiscPersen, ARow]) / 100) * StrToFloat(strgGrid.Cells[_KolStorePrice, ARow]);
FSellPrice := StrToFloat(strgGrid.Cells[_KolBHJSellPriceDisc, ARow]) + dDiscNominal;
strgGrid.Cells[_KolBHJDiscNominal, ARow] := FloatToStr(dDiscNominal);
strgGrid.Cells[_KolBHJSellPrice, ARow] := FloatToStr(FSellPrice);
end;
}
end;
end;
procedure TfrmCrazyPriceDialog.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
//var
// K: String;
begin
inherited;
if (ssctrl in Shift) and (Key = Ord('R')) then
Begin
btnRemoveClick(Sender);
End
else if (ssctrl in Shift) and (Key=Ord('T')) then
btnAddClick(Sender)
else if (key=VK_ESCAPE) then
Close
else if (key=VK_RETURN) and (ssctrl in Shift) then
footerDialogMasterbtnSaveClick(Sender);
end;
procedure TfrmCrazyPriceDialog.edtDiscPersenExit(Sender: TObject);
begin
inherited;
CalcDiscAndNominalDisc
end;
procedure TfrmCrazyPriceDialog.edtCrazyPriceExit(Sender: TObject);
begin
inherited;
CalcDiscAndNominalDisc;
end;
procedure TfrmCrazyPriceDialog.curredtDiscNominalKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if Key = VK_RETURN then
begin
btnAdd.SetFocus;
end;
end;
procedure TfrmCrazyPriceDialog.curredtDiscNominalExit(Sender: TObject);
begin
inherited;
if curredtStorePrice.Value <> 0 then
edtDiscPersen.Value := StrToFloat(FormatFloat('0.00', (curredtDiscNominal.Value / curredtStorePrice.Value) * 100))
else
edtDiscPersen.Value := 0;
FSellPrice := edtCrazyPrice.Value + curredtDiscNominal.Value;
end;
procedure TfrmCrazyPriceDialog.setHarga;
var
iTipeHrgID : Integer;
dHargaAvg : Double;
dConValue : Double;
// FBarangHargaJual : TBarangHargaJual;
begin
{try
FBarangHargaJual := TBarangHargaJual.create(nil);
if cbbUOM.Text <> '' then
begin
FBarangHargaJual.SetHargaAverage(edtCode.Text, DialogUnit, UpperCase(cbbUOM.Text), dConValue, dHargaAvg);
edtConValue.Value := dConValue;
curredtPriceDisc.Value := dHargaAvg;
//semua tipe harga toko
if TipeHrg = 0 then
iTipeHrgID := cGetIDfromCombo(cbTipeHarga, cbTipeHarga.ItemIndex)
else
iTipeHrgID := TipeHrg;
FBarangHargaJual.LoadByBarangKodeTipeHarga(edtCode.Text,
UpperCase(cbbUOM.Text),
iTipeHrgID);
curredtStorePrice.Value := FBarangHargaJual.SellPrice;
if curredtStorePrice.Value = 0 then
CommonDlg.ShowMessage('Tidak Ada Penjualan Toko dengan Uom '+ cbbUOM.Text );
end;
finally
if FBarangHargaJual <> nil then FreeAndNil(FBarangHargaJual);
end;
}
end;
procedure TfrmCrazyPriceDialog.strgGridDblClickCell(Sender: TObject; ARow,
ACol: Integer);
begin
inherited;
ClearTextValue;
FisEditRec := True;
{edtCode.Text := strgGrid.Cells[_KolBrgKode, aRow];
edtName.Text := strgGrid.Cells[_KolBrgNama, aRow];
GetUOMByBrgCode();
cbbUOM.Text := strgGrid.Cells[_KolSatKode, aRow];
edtConValue.Value := StrToFloat(strgGrid.Cells[_KolConValue, aRow]);
edtCrazyPrice.Value := StrToCurr(strgGrid.Cells[_KolBHJSellPriceDisc, aRow]);
edtDiscPersen.Value := StrToFloat(strgGrid.Cells[_KolBHJDiscPersen, aRow]);
curredtDiscNominal.Value := StrToCurr(strgGrid.Cells[_KolBHJDiscNominal, aRow]);
edtDisc.Value := StrToFloat(strgGrid.Cells[_KolBHJMarkUp, aRow]);
setHarga;
curredtStorePrice.Value := StrToCurr(strgGrid.Cells[_KolStorePrice, aRow]);
}
Fidx := ARow;
end;
procedure TfrmCrazyPriceDialog.FormCreate(Sender: TObject);
begin
inherited;
FIdxTipeHarga := 0;
FTipeHrg := 0;
end;
end.
|
unit RRManagerEditReservesFrame;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
RRManagerBaseObjects, ComCtrls, ToolWin, StdCtrls, ActnList, ImgList,
Mask, ToolEdit, CommonComplexCombo, ExtCtrls, RRManagerObjects,
ClientCommon, RRManagerEditVersionFrame, RRManagerBaseGUI,
RRManagerVersionsFrame, Contnrs;
type
// TfrmReserves = class(TFrame)
TfrmReserves = class(TBaseFrame)
gbxProperties: TGroupBox;
pgctl: TPageControl;
tshReserveEditor: TTabSheet;
cmplxFluidType: TfrmComplexCombo;
cmplxReserveKind: TfrmComplexCombo;
cmplxReserveCategory: TfrmComplexCombo;
edtValue: TEdit;
Label4: TLabel;
Bevel1: TBevel;
frmVersions: TfrmVersions;
Splitter1: TSplitter;
cmplxResourceType: TfrmComplexCombo;
btnSave: TButton;
Label1: TLabel;
cmplxReservesValueType: TfrmComplexCombo;
Label2: TLabel;
cmbxLicenseZone: TComboBox;
lblOrganization: TLabel;
procedure trwReservesChange(Sender: TObject; Node: TTreeNode);
procedure cmplxFluidTypecmbxNameChange(Sender: TObject);
procedure cmplxReserveCategorycmbxNameChange(Sender: TObject);
procedure cmplxReserveTypecmbxNameChange(Sender: TObject);
procedure edtValueChange(Sender: TObject);
procedure trwReservesChanging(Sender: TObject; Node: TTreeNode;
var AllowChange: Boolean);
procedure frmVersioncmbxDocNameChange(Sender: TObject);
procedure cmplxFluidTypecmbxNameSelect(Sender: TObject);
procedure cmplxReserveCategorycmbxNameSelect(Sender: TObject);
procedure cmplxReserveKindcmbxNameSelect(Sender: TObject);
procedure cmplxResourceTypecmbxNameSelect(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure frmVersionstlbtnAddVersionClick(Sender: TObject);
procedure frmVersionsAddVersionExecute(Sender: TObject);
procedure frmVersionstlbtnAddReserveClick(Sender: TObject);
procedure cmplxReservesValueTypecmbxNameChange(Sender: TObject);
procedure cmplxResourceTypecmbxNameChange(Sender: TObject);
procedure cmplxReservesValueTypecmbxNameSelect(Sender: TObject);
procedure frmVersionstlbtnDeleteReserveClick(Sender: TObject);
procedure cmbxLicenseZoneChange(Sender: TObject);
private
{ Private declarations }
FVersions: TOldAccountVersions;
FReserve: TOldReserve;
FTempObject: TbaseObject;
FCreatedCollection: TBaseCollection;
FCreatedObject: TBaseObject;
FLoadAction, FElementAction: TBaseAction;
function GetBed: TOldBed;
function GetLayer: TOldLayer;
function GetSubstructure: TOldSubstructure;
function GetVersions: TOldAccountVersions;
procedure SetReserve(const Value: TOldReserve);
procedure SaveReserve;
procedure ClearOnlyControls;
procedure OnChangeVersion(Sender: TObject);
procedure OnSaveVersion(Sender: TObject);
procedure AddVersion(Sender: TObject);
procedure DeleteVersion(Sender: TObject);
procedure AddReserve(Sender: TObject);
procedure DeleteReserve(Sender: TObject);
procedure SaveCurrentChecked(Sender: TObject);
procedure MakeClear(Sender: TObject);
procedure MakeUndo(Sender: TObject);
procedure ViewChange(Sender: TObject);
protected
procedure FillControls(ABaseObject: TBaseObject); override;
procedure ClearControls; override;
procedure FillParentControls; override;
procedure RegisterInspector; override;
procedure LocalRegisterInspector;
public
{ Public declarations }
property Versions: TOldAccountVersions read GetVersions;
property Layer: TOldLayer read GetLayer;
property Bed: TOldBed read GetBed;
property Substructure: TOldSubstructure read GetSubstructure;
property Reserve: TOldReserve read FReserve write SetReserve;
function Check: boolean; override;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Save; override;
end;
implementation
{$R *.DFM}
uses RRManagerLoaderCommands, LicenseZone;
type
TFakeObject = class
private
FID: integer;
public
property ID: integer read FID;
constructor Create(AID: integer);
end;
TReserveVersionLoadAction = class(TVersionBaseLoadAction)
public
function Execute(ABaseObject: TBaseObject): boolean; override;
end;
TReserveByVersionLoadAction = class(TReserveByVersionBaseLoadAction)
public
function Execute(ABaseObject: TBaseObject): boolean; override;
end;
{ TfrmResourceReserves }
procedure TfrmReserves.ClearControls;
begin
FVersions.Free;
FVersions := nil;
FReserve := nil;
ClearOnlyControls;
end;
constructor TfrmReserves.Create(AOwner: TComponent);
begin
inherited;
NeedCopyState := false;
FCreatedCollection := TBaseCollection.Create(TBaseObject);
FCreatedObject := FCreatedCollection.Add;
FElementAction := TReserveByVersionLoadAction.Create(Self);
FLoadAction := TReserveVersionLoadAction.Create(Self);
frmVersions.Prepare(Versions, 'запасы', TOldReserve, FElementAction);
frmVersions.OnAddSubElement := AddReserve;
frmVersions.OnDeleteSubElement := DeleteReserve;
frmVersions.OnAddVersion := AddVersion;
frmVersions.OnDeleteVersion := DeleteVersion;
frmVersions.OnViewChanged := ViewChange;
frmVersions.OnSaveCurrentChecked := SaveCurrentChecked;
frmVersions.OnSaveVersion := OnSaveVersion;
frmVersions.OnUndo := MakeUndo;
frmVersions.OnClear := MakeClear;
cmplxFluidType.Caption := 'Тип флюида';
cmplxFluidType.FullLoad := true;
cmplxFluidType.DictName := 'TBL_FLUID_TYPE_DICT';
cmplxReserveKind.Caption := 'Вид запасов';
cmplxReserveKind.FullLoad := true;
cmplxReserveKind.DictName := 'TBL_RESERVES_KIND_DICT';
cmplxReserveCategory.Caption := 'Категория запасов';
cmplxReserveCategory.FullLoad := true;
cmplxReserveCategory.DictName := 'TBL_RESOURCES_CATEGORY_DICT';
cmplxResourceType.Caption := 'Тип запасов';
cmplxResourceType.FullLoad := true;
cmplxResourceType.DictName := 'TBL_RESOURSE_TYPE_DICT';
cmplxReservesValueType.Caption := 'Запасы или тип изменения балансовых запасов';
cmplxReservesValueType.FullLoad := true;
cmplxReservesValueType.DictName := 'TBL_RESERVES_VALUE_TYPE';
tshReserveEditor.TabVisible := false;
end;
procedure TfrmReserves.FillControls(ABaseObject: TBaseObject);
var actn: TReserveVersionLoadAction;
Node: TTreeNode;
begin
FTempObject := ABaseObject;
FVersions.Free;
FVersions := nil;
actn := TReserveVersionLoadAction.Create(Self);
if Assigned(Bed) then
begin
cmbxLicenseZone.Clear;
cmbxLicenseZone.AddItem('<в целом по объекту(структуре/месторождению/продуктивному пласту/залежи)>', nil);
Bed.Field.LicenseZones.MakeList(cmbxLicenseZone.Items, true, false);
cmbxLicenseZone.ItemIndex := 0;
actn.Execute(Bed);
end
else
begin
actn.Execute(ABaseObject);
end;
frmVersions.Versions := FVersions;
actn.Free;
if frmVersions.trw.Items.Count > 0 then
frmVersions.trw.Selected := frmVersions.trw.Items[0];
Node := frmVersions.trw.Items.GetFirstNode;
if Assigned(Node) then
Node.Expand(true);
end;
procedure TfrmReserves.FillParentControls;
begin
end;
function TfrmReserves.GetBed: TOldBed;
begin
Result := nil;
if EditingObject is TOldBed then
Result := EditingObject as TOldBed
else
if EditingObject is TOldLayer then
Result := (EditingObject as TOldLayer).Bed;
end;
function TfrmReserves.GetLayer: TOldLayer;
begin
Result := nil;
if EditingObject is TOldLayer then
Result := EditingObject as TOldLayer;
end;
function TfrmReserves.GetSubstructure: TOldSubstructure;
begin
Result := nil;
if EditingObject is TOldSubstructure then
Result := EditingObject as TOldSubstructure
else
if EditingObject is TOldLayer then
Result := (EditingObject as TOldLayer).Substructure;
end;
function TfrmReserves.GetVersions: TOldAccountVersions;
begin
Result := nil;
if Assigned(FVersions) then Result := FVersions
else
if Assigned(Layer) then
begin
FVersions := TOldAccountVersions.Create(nil);
FVersions.Assign(Layer.Versions);
Result := FVersions;
// копируем владельца, а то запросы самих ресурсов неудобно делать
FVersions.Owner := Layer;
end
else if Assigned(Bed) then
begin
FVersions := TOldAccountVersions.Create(nil);
FVersions.Assign(Bed.Versions);
Result := FVersions;
// копируем владельца, а то запросы самих ресурсов неудобно делать
FVersions.Owner := Bed;
end
else
if Assigned(FTempObject) then
begin
FVersions := TOldAccountVersions.Create(nil);
if FTempObject is TOldLayer then
FVersions.Assign((FTempObject as TOldLayer).Versions)
else if FTempObject is TOldBed then
FVersions.Assign((FTempObject as TOldBed).Versions);
Result := FVersions;
// копируем владельца, а то запросы самих ресурсов неудобно делать
FVersions.Owner := FTempObject;
end
else
begin
FVersions := TOldAccountVersions.Create(nil);
FVersions.Owner := FCreatedObject;
Result := FVersions;
end
end;
procedure TfrmReserves.Save;
var i: integer;
actn: TBaseAction;
begin
inherited;
if Assigned(FVersions) then
begin
actn := TReserveByVersionLoadAction.Create(Self);
for i := 0 to FVersions.Count - 1 do
begin
if FVersions.Items[i].Reserves.NeedsUpdate then
actn.Execute(FVersions.Items[i]);
// копируем отсюда только запасы
FVersions.Items[i].Resources.CopyCollection := false;
FVersions.Items[i].Reserves.CopyCollection := true;
FVersions.Items[i].Parameters.CopyCollection := false;
end;
actn.Free;
if Assigned(Layer) then
begin
Layer.Versions.ReservesClear;
Layer.Versions.AddItems(Versions);
end
else
begin
Bed.Versions.ReservesClear;
Bed.Versions.AddItems(Versions);
end;
end;
end;
procedure TfrmReserves.SetReserve(const Value: TOldReserve);
begin
FReserve := Value;
if Assigned(FReserve) then
begin
if FReserve.ReserveKindID > 0 then
cmplxReserveKind.AddItem(FReserve.ReserveKindID, FReserve.ReserveKind);
if FReserve.ReserveCategoryID > 0 then
cmplxReserveCategory.AddItem(FReserve.ReserveCategoryID, FReserve.ReserveCategory);
if FReserve.FluidTypeID > 0 then
cmplxFluidType.AddItem(FReserve.FluidTypeID, FReserve.FluidType);
if FReserve.ReserveTypeID > 0 then
cmplxResourceType.AddItem(FReserve.ReserveTypeID, FReserve.ReserveType);
if FReserve.ReserveValueTypeID > 0 then
cmplxReservesValueType.AddItem(FReserve.ReserveValueTypeID, FReserve.ReserveValueTypeName);
if Assigned(FReserve.LicenseZone) then
cmbxLicenseZone.ItemIndex := cmbxLicenseZone.Items.IndexOfObject(FReserve.LicenseZone);
edtValue.Text := trim(Format('%7.3f', [FReserve.Value]));
end
else ClearOnlyControls;
end;
procedure TfrmReserves.SaveReserve;
begin
if Assigned(Reserve) then
begin
Reserve.FluidTypeID := cmplxFluidType.SelectedElementID;
Reserve.FluidType := cmplxFluidType.SelectedElementName;
Reserve.ReserveKindID := cmplxReserveKind.SelectedElementID;
Reserve.ReserveKind := cmplxReserveKind.SelectedElementName;
Reserve.ReserveCategoryID := cmplxReserveCategory.SelectedElementID;
Reserve.ReserveCategory := cmplxReserveCategory.SelectedElementName;
Reserve.ReserveTypeID := cmplxResourceType.SelectedElementID;
Reserve.ReserveType := cmplxResourceType.SelectedElementName;
Reserve.ReserveValueTypeID := cmplxReservesValueType.SelectedElementID;
Reserve.ReserveValueTypeName := cmplxReservesValueType.SelectedElementName;
if cmbxLicenseZone.ItemIndex > -1 then
Reserve.LicenseZone := TLicenseZone(cmbxLicenseZone.Items.Objects[cmbxLicenseZone.ItemIndex])
else
Reserve.LicenseZone := nil;
try
Reserve.Value := StrToFloat(edtValue.Text);
except
Reserve.Value := 0;
end;
if TBaseObject(frmVersions.trw.Selected.Data) is TOldReserve then
frmVersions.trw.Selected.Text := Reserve.List(AllOpts.Current.ListOption, AllOpts.Current.ShowUINs, false);
end;
end;
{ TResourceVersionLoadAction }
function TReserveVersionLoadAction.Execute(
ABaseObject: TBaseObject): boolean;
var node: TTreeNode;
i: integer;
begin
if ABaseObject is TOldLayer then
LastCollection := (ABaseObject as TOldLayer).Versions
else if ABaseObject is TOldBed then
LastCollection := (ABaseObject as TOldBed).Versions;
if LastCollection.NeedsUpdate then
Result := inherited Execute(ABaseObject)
else Result := true;
if Result then
begin
// загружаем в интерфейс
if Assigned(LastCollection) then
with Owner as TfrmReserves do
begin
// получаем версии на форму
Versions;
frmVersions.trw.Items.BeginUpdate;
frmVersions.trw.Selected := nil;
// чистим
try
frmVersions.trw.Items.Clear;
except
end;
// добавляем в дерево не реальные версии
// а их копии, чтобы потом сохранять изменения
for i := 0 to Versions.Count - 1 do
begin
if (((frmVersions.cmbxView.ItemIndex = 0) and Versions.Items[i].ContainsReserves)
or (frmVersions.cmbxView.ItemIndex = 1)) then
begin
// загружаем только те в которых есть запасы
Node := frmVersions.trw.Items.AddObject(nil, Versions.Items[i].List(AllOpts.Current.ListOption, AllOpts.Current.ShowUINs, false), Versions.Items[i]);
Node.SelectedIndex := 10;
frmVersions.trw.Items.AddChild(Node, 'будут запасы');
end;
end;
frmVersions.trw.Items.EndUpdate;
end;
end;
end;
{ TResourceByVersionLoadAction }
function TReserveByVersionLoadAction.Execute(
ABaseObject: TBaseObject): boolean;
var ParentNode, Node: TTreeNode;
i: integer;
r: TOldReserve;
NodeList: TObjectList;
begin
NodeList := TObjectList.Create(false);
NodeList.Count := 10;
LastCollection := (ABaseObject as TOldAccountVersion).Reserves;
if LastCollection.NeedsUpdate then
Result := inherited Execute(ABaseObject)
else Result := true;
if Result then
begin
// загружаем в интерфейс
if Assigned(LastCollection) then
with Owner as TfrmReserves do
begin
frmVersions.trw.Items.BeginUpdate;
// чистим
if Assigned(frmVersions.trw.Selected) then
begin
if (TBaseObject(frmVersions.trw.Selected.Data) is TOldAccountVersion) then
ParentNode := frmVersions.trw.Selected
else
ParentNode := frmVersions.trw.Selected.Parent;
Node := ParentNode.getFirstChild;
while Assigned(Node) do
begin
Node.Delete;
Node := ParentNode.getFirstChild;
end;
(ABaseObject as TOldAccountVersion).ContainsReserves := LastCollection.Count > 0;
// добавляем
for i := 0 to LastCollection.Count - 1 do
begin
r := LastCollection.Items[i] as TOldReserve;
if not Assigned(NodeList.Items[r.ReserveValueTypeID]) then NodeList.Items[r.ReserveValueTypeID] := frmVersions.trw.Items.AddChildObject(ParentNode, r.ReserveValueTypeName, TFakeObject.Create(r.ReserveValueTypeID));
Node := frmVersions.trw.Items.AddChildObject(NodeList.Items[r.ReserveValueTypeID] as TTreeNode, r.List(AllOpts.Current.ListOption, AllOpts.Current.ShowUINs, false), r);
Node.SelectedIndex := 11;
end;
end;
frmVersions.trw.Items.EndUpdate;
end;
end;
NodeList.Free;
end;
procedure TfrmReserves.trwReservesChange(Sender: TObject;
Node: TTreeNode);
begin
if Assigned(Node) then
begin
if TBaseObject(Node.data) is TOldAccountVersion then
begin
tshReserveEditor.TabVisible := false;
end
else
if TBaseObject(Node.data) is TOldReserve then
begin
Reserve := TBaseObject(Node.data) as TOldReserve;
tshReserveEditor.TabVisible := true;
end;
end;
end;
procedure TfrmReserves.cmplxFluidTypecmbxNameChange(Sender: TObject);
begin
cmplxFluidType.cmbxNameChange(Sender);
if frmVersions.SaveCurrent.Checked then SaveReserve;
end;
procedure TfrmReserves.cmplxReserveCategorycmbxNameChange(Sender: TObject);
begin
cmplxReserveCategory.cmbxNameChange(Sender);
if frmVersions.SaveCurrent.Checked then SaveReserve;
end;
procedure TfrmReserves.cmplxReserveTypecmbxNameChange(Sender: TObject);
begin
cmplxReserveKind.cmbxNameChange(Sender);
if frmVersions.SaveCurrent.Checked then SaveReserve;
end;
procedure TfrmReserves.edtValueChange(Sender: TObject);
begin
if frmVersions.SaveCurrent.Checked then SaveReserve;
end;
procedure TfrmReserves.ClearOnlyControls;
begin
cmplxFluidType.Clear;
cmplxReserveKind.Clear;
cmplxReserveCategory.Clear;
edtValue.Clear;
end;
procedure TfrmReserves.trwReservesChanging(Sender: TObject;
Node: TTreeNode; var AllowChange: Boolean);
begin
if Assigned(frmVersions.trw.Selected) then
begin
if frmVersions.trw.Selected.Level = 2 then
AllowChange := Inspector.Check
end;
end;
procedure TfrmReserves.RegisterInspector;
begin
inherited;
end;
procedure TfrmReserves.LocalRegisterInspector;
begin
Inspector.Clear;
// возвращаем исходное состояние
// здесь не так как на других фрэймах
// инспектор регистрится при добавлении нового параметра
cmplxReserveKind.cmbxName.OnChange := cmplxReserveTypecmbxNameChange;
cmplxReserveCategory.cmbxName.OnChange := cmplxReserveCategorycmbxNameChange;
cmplxFluidType.cmbxName.OnChange := cmplxFluidTypecmbxNameChange;
edtValue.OnChange := edtValueChange;
Inspector.Add(cmplxFluidType.cmbxName, nil, ptString, 'тип флюида', false);
Inspector.Add(cmplxReserveKind.cmbxName, nil, ptString, 'вид запасов', false);
Inspector.Add(cmplxReserveCategory.cmbxName, nil, ptString, 'категория запасов', false);
Inspector.Add(cmplxResourceType.cmbxName, nil, ptString, 'тип запасов', false);
Inspector.Add(edtValue, nil, ptFloat, 'значение', false);
end;
procedure TfrmReserves.frmVersioncmbxDocNameChange(Sender: TObject);
begin
if Assigned(frmVersions.trw.Selected) and (TObject(frmVersions.trw.Selected.Data) is TOldAccountVersion) then
frmVersions.trw.Selected.Text := TOldAccountVersion(frmVersions.trw.Selected.Data).List(AllOpts.Current.ListOption, AllOpts.Current.ShowUINs, false)
end;
procedure TfrmReserves.OnChangeVersion(Sender: TObject);
var v: TOldAccountVersion;
Node: TTreeNode;
i: integer;
begin
v := Versions.Items[Versions.Count - 1];
Node := frmVersions.trw.Items.AddObject(nil, v.List(AllOpts.Current.ListOption, AllOpts.Current.ShowUINs, false), v);
Node.SelectedIndex := 10;
frmVersions.trw.Items.AddChild(Node, 'будут запасы');
v.Reserves.NeedsUpdate := false;
i := frmVersions.FindObject(v);
if i > -1 then
frmVersions.trw.Items[i].Selected := true;
end;
procedure TfrmReserves.AddVersion(Sender: TObject);
var i: integer;
begin
frmVersions.Version.Reserves.NeedsUpdate := false;
i := frmVersions.FindObject(frmVersions.Version);
if i > -1 then
frmVersions.trw.Items[i].Selected := true;
end;
procedure TfrmReserves.DeleteVersion(Sender: TObject);
begin
end;
procedure TfrmReserves.AddReserve(Sender: TObject);
var r: TOldReserve;
Node: TTreeNode;
i: integer;
begin
r := frmVersions.Version.Reserves.Add;
if (TBaseObject(frmVersions.trw.Selected.Data) is TOldAccountVersion) then
Node := frmVersions.trw.Selected
else if (TBaseObject(frmVersions.trw.Selected.Data) is TOldReserve) then
Node := frmVersions.trw.Selected.Parent
else
begin
Node := frmVersions.trw.Selected.Parent;
r.ReserveValueTypeID := TFakeObject(frmVersions.trw.Selected.Data).ID;
end;
frmVersions.trw.Items.AddChildObject(Node, r.List(AllOpts.Current.ListOption, AllOpts.Current.ShowUINs, false), r).SelectedIndex := 11;
Node.Expand(true);
LocalRegisterInspector;
Reserve := r;
i := frmVersions.FindObject(Reserve);
if i > -1 then
frmVersions.trw.Items[i].Selected := true;
end;
procedure TfrmReserves.DeleteReserve(Sender: TObject);
var Node: TTreeNode;
begin
Node := frmVersions.trw.Selected.Parent;
frmVersions.Version.Reserves.Remove(TBaseObject(frmVersions.trw.Selected.Data));
frmVersions.trw.Selected.Delete;
Reserve := nil;
frmVersions.trw.Selected := nil;
if not Node.HasChildren then Node.Delete;
UnCheck;
end;
procedure TfrmReserves.MakeClear(Sender: TObject);
begin
ClearOnlyControls;
end;
procedure TfrmReserves.MakeUndo(Sender: TObject);
begin
with pgctl do
case ActivePageIndex of
0:
begin
Reserve := nil;
Reserve := TOldReserve(frmVersions.trw.Selected.Data);
end;
end;
end;
procedure TfrmReserves.SaveCurrentChecked(Sender: TObject);
begin
SaveReserve;
end;
procedure TfrmReserves.ViewChange(Sender: TObject);
begin
Reserve := nil;
FLoadAction.Execute(Layer);
end;
procedure TfrmReserves.OnSaveVersion(Sender: TObject);
begin
end;
destructor TfrmReserves.Destroy;
begin
FCreatedCollection.Free;
inherited;
end;
procedure TfrmReserves.cmplxFluidTypecmbxNameSelect(Sender: TObject);
begin
cmplxFluidType.cmbxNameSelect(Sender);
if frmVersions.SaveCurrent.Checked then SaveReserve;
end;
procedure TfrmReserves.cmplxReserveCategorycmbxNameSelect(Sender: TObject);
begin
cmplxReserveCategory.cmbxNameSelect(Sender);
if frmVersions.SaveCurrent.Checked then SaveReserve;
end;
procedure TfrmReserves.cmplxReserveKindcmbxNameSelect(Sender: TObject);
begin
cmplxReserveKind.cmbxNameSelect(Sender);
if frmVersions.SaveCurrent.Checked then SaveReserve;
end;
procedure TfrmReserves.cmplxResourceTypecmbxNameSelect(Sender: TObject);
begin
cmplxResourceType.cmbxNameSelect(Sender);
if frmVersions.SaveCurrent.Checked then SaveReserve;
end;
procedure TfrmReserves.btnSaveClick(Sender: TObject);
begin
SaveReserve;
end;
function TfrmReserves.Check: boolean;
var i: integer;
begin
Result := inherited Check;
if pgctl.Visible then
for i := 0 to Versions.Count - 1 do
Result := Result and Versions.Items[i].Reserves.Check;
end;
{ TFakeObject }
constructor TFakeObject.Create(AID: integer);
begin
inherited Create;
FID := AID;
end;
procedure TfrmReserves.frmVersionstlbtnAddVersionClick(Sender: TObject);
begin
frmVersions.AddVersionExecute(Sender);
end;
procedure TfrmReserves.frmVersionsAddVersionExecute(Sender: TObject);
begin
frmVersions.AddVersionExecute(Sender);
end;
procedure TfrmReserves.frmVersionstlbtnAddReserveClick(Sender: TObject);
begin
frmVersions.AddSubElementExecute(Sender);
end;
procedure TfrmReserves.cmplxReservesValueTypecmbxNameChange(
Sender: TObject);
begin
cmplxReservesValueType.cmbxNameChange(Sender);
frmVersions.trw.Selected.Parent.Expand(true);
end;
procedure TfrmReserves.cmplxResourceTypecmbxNameChange(Sender: TObject);
begin
cmplxResourceType.cmbxNameChange(Sender);
end;
procedure TfrmReserves.cmplxReservesValueTypecmbxNameSelect(
Sender: TObject);
var Node: TTreeNode;
iIndex: integer;
begin
cmplxReservesValueType.cmbxNameSelect(Sender);
if frmVersions.SaveCurrent.Checked then SaveReserve;
Node := frmVersions.trw.Selected;
while Node.Level > 0 do
Node := Node.Parent;
Node.Expand(true);
iIndex := frmVersions.FindObject(Reserve);
if iIndex > -1 then
frmVersions.trw.Items[iIndex].Selected := true;
end;
procedure TfrmReserves.frmVersionstlbtnDeleteReserveClick(Sender: TObject);
begin
frmVersions.DeleteSubElementExecute(Sender);
end;
procedure TfrmReserves.cmbxLicenseZoneChange(Sender: TObject);
var lz: TSimpleLicenseZone;
begin
SaveReserve;
lz := nil;
if cmbxLicenseZone.ItemIndex > -1 then
lz := cmbxLicenseZone.Items.Objects[cmbxLicenseZone.ItemIndex] as TSimpleLicenseZone;
if Assigned(lz) and Assigned(lz.OwnerOrganization) then
lblOrganization.Caption := lz.OwnerOrganization.List
else
lblOrganization.Caption := '';
end;
end.
|
unit uInNomineCharacter;
interface
uses
uInNomineSystem, Contnrs;
type
TInNomineCharacter = class
private
FForces: array [0..2] of TForces;
function getStrength(): TAttributeValue;
function getAgility(): TAttributeValue;
function getIntelligence(): TAttributeValue;
function getPrecision(): TAttributeValue;
function getWill(): TAttributeValue;
function getPerception(): TAttributeValue;
function getNumberForces(): integer;
function getForces(index: integer): TForces;
procedure setForces(index: integer; const value: TForces);
public
name: string;
concept: PCharacterConcept;
celestialKind: PCelestialKind;
superior: TSuperior;
essencePoints: TEssence;
dissonancePoints: TDissonance;
distinctions: TObjectList;
resources: TObjectList;
word: string;
resourcePoints: integer;
characterPoints: integer;
constructor Create;
destructor Destroy; override;
property forces[index: integer]: TForces read getForces write setForces;
property corporealForces: TForces index 0 read getForces write setForces;
property etherealForces: TForces index 1 read getForces write setForces;
property celestialForces: TForces index 2 read getForces write setForces;
property strength: TAttributeValue read getStrength;
property agility: TAttributeValue read getAgility;
property intelligence: TAttributeValue read getIntelligence;
property precision: TAttributeValue read getPrecision;
property will: TAttributeValue read getWill;
property perception: TAttributeValue read getPerception;
property numberForces: integer read getNumberForces;
end;
implementation
uses
SysUtils;
{ TInNomineCharacter }
constructor TInNomineCharacter.Create;
begin
name := '';
concept := nil;
celestialKind := nil;
superior := nil;
essencePoints := 0;
dissonancePoints := 0;
FForces[0] := TCorporealForces.Create;
FForces[1] := TEtherealForces.Create;
FForces[2] := TCelestialForces.Create;
distinctions := TObjectList.Create(False);
resources := TObjectList.Create(False);
end;
destructor TInNomineCharacter.Destroy;
begin
freeAndNil(FForces[0]);
freeAndNil(FForces[1]);
freeAndNil(FForces[2]);
freeAndNil(resources);
end;
function TInNomineCharacter.getAgility: TAttributeValue;
begin
Result := TCorporealForces(FForces[0]).agility;
end;
function TInNomineCharacter.getForces(index: integer): TForces;
begin
Result := FForces[index];
end;
function TInNomineCharacter.getIntelligence: TAttributeValue;
begin
Result := TEtherealForces(FForces[1]).intelligence;
end;
function TInNomineCharacter.getNumberForces(): integer;
begin
Result := FForces[0].number + FForces[1].number + FForces[2].number;
end;
function TInNomineCharacter.getPerception: TAttributeValue;
begin
Result := TCelestialForces(FForces[2]).perception;
end;
function TInNomineCharacter.getPrecision: TAttributeValue;
begin
Result := TEtherealForces(FForces[1]).precision;
end;
function TInNomineCharacter.getStrength: TAttributeValue;
begin
Result := TCorporealForces(FForces[0]).strength;
end;
function TInNomineCharacter.getWill: TAttributeValue;
begin
Result := TCelestialForces(FForces[2]).will;
end;
procedure TInNomineCharacter.setForces(index: Integer;
const value: TForces);
begin
FForces[index] := value;
end;
end.
|
unit uMsVpn;
interface
uses
Windows, SysUtils;
type
GUID = record
Data1: Integer;
Data2: ShortInt;
Data3: ShortInt;
Data4: array[0..7] of Byte;
end;
type
TRasIPAddr = record
a: byte;
b: byte;
c: byte;
d: byte;
end;
LPRasDialExtensions = ^TRasDialExtensions;
TRasDialExtensions = record
dwSize : LongInt;
dwfOptions : LongInt;
hwndParent : HWnd;
reserved : LongInt;
end;
type
TRasEntry = record
dwSize,
dwfOptions,
dwCountryID,
dwCountryCode : Longint;
szAreaCode : array[0.. 10] of Byte;
szLocalPhoneNumber : array[0..128] of Byte;
dwAlternatesOffset : Longint;
ipaddr,
ipaddrDns,
ipaddrDnsAlt,
ipaddrWins,
ipaddrWinsAlt : TRasIPAddr;
dwFrameSize,
dwfNetProtocols,
dwFramingProtocol : Longint;
szScript : Array [0..259] of Byte;
szAutodialDll : Array [0..259] of Byte;
szAutodialFunc : Array [0..259] of Byte;
szDeviceType : Array [0..16] of Byte;
szDeviceName : Array [0..128] of Byte;
szX25PadType : Array [0..32] of Byte;
szX25Address : Array [0..200] of Byte;
szX25Facilities : Array [0..200] of Byte;
szX25UserData : Array [0..200] of Byte;
dwChannels,
dwReserved1,
dwReserved2,
dwSubEntries,
dwDialMode,
dwDialExtraPercent,
dwDialExtraSampleSeconds,
dwHangUpExtraPercent,
dwHangUpExtraSampleSeconds,
dwIdleDisconnectSeconds,
dwType,
dwEncryptionType,
dwCustomAuthKey : Longint;
guidId : GUID;
szCustomDialDll : Array [0..259] of Byte;
dwVpnStrategy,
dwfOptions2,
dwfOptions3 : Longint;
szDnsSuffix : Array [0..255] of Byte;
dwTcpWindowSize : Longint;
szPrerequisitePbk : Array [0..259] of Byte;
szPrerequisiteEntry : Array [0..256] of Byte;
dwRedialCount,
dwRedialPause : Longint;
end;
TRasCredentialsA = record
dwSize, dwMask: Longint;
szUserName: array[0..256] of Byte;
szPassword: array[0..256] of Byte;
szDomain: array[0..15] of Byte;
end;
//LPRasDialParamsA = ^TRasDialParamsA;
// TRasDialParamsA = record
// dwSize : LongInt;
// szEntryName : array[0..RAS_MaxEntryName] of AnsiChar;
// szPhoneNumber : array[0..RAS_MaxPhoneNumber] of AnsiChar;
// szCallbackNumber : array[0..RAS_MaxCallbackNumber] of AnsiChar;
// szUserName : array[0..UNLEN] of AnsiChar;
// szPassword : array[0..PWLEN] of AnsiChar;
// szDomain : array[0..DNLEN] of AnsiChar;
// end;
function RasSetEntryPropertiesA(lpszPhonebook, lpszEntry: PAnsichar; lpRasEntry: Pointer; dwEntryInfoSize: LongInt;lpbDeviceInfo:Pointer;dwDeviceInfoSize: Longint): Longint; stdcall;
function RasSetCredentialsA(lpszPhoneBook, lpszEntry: PAnsichar; lpCredentials: Pointer; fClearCredentials: Longint): Longint; stdcall;
function RasDialA(lpRasDialExt: LPRasDialExtensions; lpszPhoneBook: PAnsiChar; var Params: TRasCredentialsA; dwNotifierType: Longint; lpNotifier: Pointer; var RasConn: LongInt): Longint; stdcall;
function Create_VPN_Connection(sEntryName, sServer, sUsername, sPassword: AnsiString): Boolean;
implementation
function RasSetEntryPropertiesA; external 'Rasapi32.dll' name 'RasSetEntryPropertiesA';
function RasSetCredentialsA; external 'Rasapi32.dll' name 'RasSetCredentialsA';
function RasDialA; external 'Rasapi32.dll' name 'RasDialA';
function Create_VPN_Connection(sEntryName, sServer, sUsername, sPassword: AnsiString): Boolean;
var
sDeviceName, sDeviceType: AnsiString;
re: TRasEntry;
rc: TRasCredentialsA;
hRAS: Longint;
begin
sDeviceName := 'WAN 微型端口 (PPTP)';
sDeviceType := 'VPN';
with re do
begin
Result := False;
ZeroMemory(@re,SizeOf(re));
dwSize := Sizeof(re);
dwType := 2; //5;
dwfOptions := 67110160; //1024262928-16;
StrCopy(@szDeviceName[0], PansiChar(sDeviceName));
StrCopy(@szDeviceType[0], PansiChar(sDeviceType));
StrCopy(@szLocalPhoneNumber[0], PansiChar(sServer));
dwFramingProtocol := 1;
dwfNetProtocols := 4;
dwVpnStrategy := 1;
dwCountryCode := 86;
dwCountryID := 86;
dwDialExtraPercent := 75;
dwDialExtraSampleSeconds := 120;
dwDialMode := 1;
dwEncryptionType := 0;
dwfOptions2 := 367;
dwHangUpExtraPercent := 10;
dwHangUpExtraSampleSeconds := 120;
dwRedialCount := 3;
dwRedialPause := 60;
dwEncryptionType := 3; //0 无 1 VPN 默认值 3 拨号默认值 可选
end;
with rc do
begin
ZeroMemory(@rc,Sizeof(rc));
dwSize := sizeof(rc);
dwMask := 11;
StrCopy(@szUserName[0],PansiChar(sUsername));
StrCopy(@szPassword[0],PansiChar(sPassword));
//StrCopy(@szDomain[0],PansiChar('PPTP'));
end;
if RasSetEntryPropertiesA(Nil, PAnsiChar(sEntryName),@re, SizeOf(re), nil, 0)=0 then
if RasSetCredentialsA(Nil, PAnsiChar(sEntryName),@rc,0) = 0 then
Result := True;
//Result := RasDialA(nil, nil, rc, nil, nil, hRAS) = 0;
end;
//procedure TVpnForm.Button1Click(Sender: TObject);
//var
// sServer, sEntryName, sUsername, sPassword: string;
//begin
// //WinExec('rasdial '+'vpn 1 17 /domain:PPTP',SW_hide);
// //Exit;
// WinExec('rasphone.exe -h '+'vpn',SW_SHOWNORMAL);
// sEntryName := 'VPN';
// sServer := ServerIPEd.Text;
// sUsername := UserEd.Text;
// sPassword := PwdEd.Text;
// if Create_VPN_Connection(sEntryName, sServer, sUsername, sPassword) then
// begin
// // Application.MessageBox('VPN连接建立成功!','VPN连接',MB_OK+MB_ICONWARNING+MB_TOPMOST);
// // WinExec('rasphone.exe -h '+'vpn',SW_SHOWNORMAL);
// WinExec('rasdial ' + 'vpn 1 17', SW_hide);
// end
// else
// begin
// Application.MessageBox('VPN连接建立失败!', 'VPN连接', MB_OK + MB_ICONWARNING + MB_TOPMOST);
// end;
//end;
//
//
//
//procedure TVpnForm.Button2Click(Sender: TObject);
//begin
// //WinExec('rasphone.exe -r '+'vpn',SW_SHOWNORMAL);
// WinExec('rasphone.exe -h '+'vpn',SW_SHOWNORMAL);
//end;
end.
|
{
Copyright (C) 2013-2018 Tim Sinaeve tim.sinaeve@gmail.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
}
unit DataGrabber.Settings;
{ Persistable application settings component. }
interface
uses
System.Classes, System.Generics.Collections,
Vcl.Graphics,
Data.DB,
Spring,
DataGrabber.Interfaces, DataGrabber.FormSettings,
DataGrabber.ConnectionSettings, DataGrabber.ConnectionProfiles;
type
TSettings = class(TComponent, ISettings, IDataViewSettings)
private
FFormSettings : TFormSettings;
FDataTypeColors : TDictionary<TDataType, TColor>;
FGridCellColoring : Boolean;
FConnectionProfiles : TConnectionProfiles;
FFileName : string;
FGridType : string;
FDefaultConnectionProfile : string;
FConnectionSettings : TConnectionSettings;
FDataInspectorVisible : Boolean;
FShowVerticalGridLines : Boolean;
FShowHorizontalGridLines : Boolean;
FResultDisplayLayout : TResultDisplayLayout;
FGroupByBoxVisible : Boolean;
FMergeColumnCells : Boolean;
FUpdateLock : Integer;
FOnChanged : Event<TNotifyEvent>;
FEditorFont : TFont;
FGridFont : TFont;
{$REGION 'property access methods'}
function GetGridCellColoring: Boolean;
procedure SetGridCellColoring(const Value: Boolean);
function GetFieldTypeColor(Index: TFieldType): TColor;
function GetDataTypeColor(Index: TDataType): TColor;
procedure SetDataTypeColor(Index: TDataType; const Value: TColor);
function GetConnectionProfiles: TConnectionProfiles;
procedure SetConnectionProfiles(const Value: TConnectionProfiles);
function GetFormSettings: TFormSettings;
procedure SetFormSettings(const Value: TFormSettings);
function GetConnectionSettings: TConnectionSettings;
function GetDataInspectorVisible: Boolean;
function GetDefaultConnectionProfile: string;
procedure SetConnectionSettings(const Value: TConnectionSettings);
procedure SetDataInspectorVisible(const Value: Boolean);
procedure SetDefaultConnectionProfile(const Value: string);
function GetGridType: string;
procedure SetGridType(const Value: string);
function GetFileName: string;
procedure SetFileName(const Value: string);
function GetShowHorizontalGridLines: Boolean;
function GetShowVerticalGridLines: Boolean;
procedure SetShowHorizontalGridLines(const Value: Boolean);
procedure SetShowVerticalGridLines(const Value: Boolean);
function GetResultDisplayLayout: TResultDisplayLayout;
procedure SetResultDisplayLayout(const Value: TResultDisplayLayout);
function GetGroupByBoxVisible: Boolean;
procedure SetGroupByBoxVisible(const Value: Boolean);
function GetOnChanged: IEvent<TNotifyEvent>;
function GetMergeColumnCells: Boolean;
procedure SetMergeColumnCells(const Value: Boolean);
function GetEditorFont: TFont;
procedure SetEditorFont(const Value: TFont);
function GetGridFont: TFont;
procedure SetGridFont(const Value: TFont);
{$ENDREGION}
procedure FormSettingsChanged(Sender: TObject);
protected
procedure BeginUpdate;
procedure EndUpdate;
procedure Changed;
public
constructor Create(AOwner: TComponent); override;
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
procedure Load;
procedure Save;
property FieldTypeColors[Index: TFieldType]: TColor
read GetFieldTypeColor;
property DataTypeColors[Index: TDataType]: TColor
read GetDataTypeColor write SetDataTypeColor;
property FileName: string
read GetFileName write SetFileName;
property OnChanged: IEvent<TNotifyEvent>
read GetOnChanged;
published
property GroupByBoxVisible: Boolean
read GetGroupByBoxVisible write SetGroupByBoxVisible default True;
property MergeColumnCells: Boolean
read GetMergeColumnCells write SetMergeColumnCells default False;
property GridCellColoring: Boolean
read GetGridCellColoring write SetGridCellColoring default True;
property ShowHorizontalGridLines: Boolean
read GetShowHorizontalGridLines write SetShowHorizontalGridLines default True;
property ShowVerticalGridLines: Boolean
read GetShowVerticalGridLines write SetShowVerticalGridLines default True;
property FormSettings: TFormSettings
read GetFormSettings write SetFormSettings;
property ConnectionProfiles: TConnectionProfiles
read GetConnectionProfiles write SetConnectionProfiles;
property EditorFont: TFont
read GetEditorFont write SetEditorFont;
property GridFont: TFont
read GetGridFont write SetGridFont;
property GridType: string
read GetGridType write SetGridType;
property ConnectionSettings: TConnectionSettings
read GetConnectionSettings write SetConnectionSettings;
property DefaultConnectionProfile: string
read GetDefaultConnectionProfile write SetDefaultConnectionProfile;
property DataInspectorVisible: Boolean
read GetDataInspectorVisible write SetDataInspectorVisible;
property ResultDisplayLayout: TResultDisplayLayout
read GetResultDisplayLayout
write SetResultDisplayLayout
default TResultDisplayLayout.Horizontal;
end;
implementation
uses
System.SysUtils,
Vcl.Forms, Vcl.GraphUtil,
JsonDataObjects,
DataGrabber.Resources;
{$REGION 'construction and destruction'}
procedure TSettings.Changed;
begin
OnChanged.Invoke(Self);
end;
constructor TSettings.Create(AOwner: TComponent);
begin
if not Assigned(AOwner) then
inherited Create(Application)
else
inherited Create(AOwner);
end;
procedure TSettings.AfterConstruction;
var
I : TDataType;
begin
inherited AfterConstruction;
Name := 'Settings';
FShowVerticalGridLines := True;
FShowHorizontalGridLines := True;
FDataTypeColors := TDictionary<TDataType, TColor>.Create;
FConnectionSettings := TConnectionSettings.Create;
for I := Low(TDataType) to High(TDataType) do
FDataTypeColors.Add(I, ColorAdjustLuma(DEFAULT_DATATYPE_COLORS[I], 6, False));
FFormSettings := TFormSettings.Create;
FFormSettings.OnChanged.Add(FormSettingsChanged);
FConnectionProfiles := TConnectionProfiles.Create(Self);
FFileName := SETTINGS_FILE;
FGridCellColoring := True;
FGroupByBoxVisible := True;
FResultDisplayLayout := TResultDisplayLayout.Horizontal;
FEditorFont := TFont.Create;
FGridFont := TFont.Create;
end;
procedure TSettings.BeforeDestruction;
begin
FreeAndNil(FConnectionProfiles);
FFormSettings.OnChanged.Remove(FormSettingsChanged);
FreeAndNil(FFormSettings);
FreeAndNil(FDataTypeColors);
FreeAndNil(FConnectionSettings);
FreeAndNil(FEditorFont);
FreeAndNil(FGridFont);
inherited BeforeDestruction;
end;
{$ENDREGION}
{$REGION 'property access methods'}
function TSettings.GetFieldTypeColor(Index: TFieldType): TColor;
begin
case Index of
ftString, ftFixedChar, ftWideString, ftFixedWideChar, ftWideMemo, ftMemo,
ftFmtMemo:
Result := DataTypeColors[dtString];
ftSmallint, ftInteger, ftWord, ftAutoInc, ftLargeint, ftLongWord,
ftShortint, ftByte:
Result := DataTypeColors[dtInteger];
ftBoolean:
Result := DataTypeColors[dtBoolean];
ftFloat, ftCurrency, ftBCD, ftExtended, ftFMTBcd:
Result := DataTypeColors[dtFloat];
ftDate:
Result := DataTypeColors[dtDate];
ftTime:
Result := DataTypeColors[dtTime];
ftDateTime, ftTimeStamp, ftOraTimeStamp:
Result := DataTypeColors[dtDateTime];
ftBytes, ftVarBytes, ftBlob, ftGraphic, ftUnknown, ftParadoxOle, ftGuid,
ftDBaseOle, ftTypedBinary, ftCursor, ftADT, ftArray, ftReference, ftStream,
ftDataSet, ftOraBlob, ftOraClob, ftVariant, ftInterface, ftIDispatch,
ftOraInterval, ftConnection, ftParams:
Result := clWhite;
else
Result := clWhite;
end;
end;
function TSettings.GetGridCellColoring: Boolean;
begin
Result := FGridCellColoring;
end;
function TSettings.GetGridFont: TFont;
begin
Result := FGridFont;
end;
procedure TSettings.SetGridFont(const Value: TFont);
begin
FGridFont.Assign(Value);
Changed;
end;
procedure TSettings.SetGridCellColoring(const Value: Boolean);
begin
if Value <> GridCellColoring then
begin
FGridCellColoring := Value;
Changed;
end;
end;
function TSettings.GetGridType: string;
begin
Result := FGridType;
end;
procedure TSettings.SetGridType(const Value: string);
begin
if Value <> GridType then
begin
FGridType := Value;
Changed;
end;
end;
function TSettings.GetGroupByBoxVisible: Boolean;
begin
Result := FGroupByBoxVisible;
end;
function TSettings.GetMergeColumnCells: Boolean;
begin
Result := FMergeColumnCells;
end;
procedure TSettings.SetMergeColumnCells(const Value: Boolean);
begin
if Value <> MergeColumnCells then
begin
FMergeColumnCells := Value;
Changed;
end;
end;
procedure TSettings.SetGroupByBoxVisible(const Value: Boolean);
begin
if Value <> GroupByBoxVisible then
begin
FGroupByBoxVisible := Value;
Changed;
end;
end;
function TSettings.GetOnChanged: IEvent<TNotifyEvent>;
begin
Result := FOnChanged;
end;
function TSettings.GetConnectionProfiles: TConnectionProfiles;
begin
Result := FConnectionProfiles;
end;
procedure TSettings.SetConnectionProfiles(const Value: TConnectionProfiles);
begin
FConnectionProfiles.Assign(Value);
Changed;
end;
function TSettings.GetResultDisplayLayout: TResultDisplayLayout;
begin
Result := FResultDisplayLayout;
end;
procedure TSettings.SetResultDisplayLayout(const Value: TResultDisplayLayout);
begin
if Value <> ResultDisplayLayout then
begin
FResultDisplayLayout := Value;
Changed;
end;
end;
function TSettings.GetShowHorizontalGridLines: Boolean;
begin
Result := FShowHorizontalGridLines;
end;
procedure TSettings.SetShowHorizontalGridLines(const Value: Boolean);
begin
if Value <> ShowHorizontalGridLines then
begin
FShowHorizontalGridLines := Value;
Changed;
end;
end;
function TSettings.GetShowVerticalGridLines: Boolean;
begin
Result := FShowVerticalGridLines;
end;
procedure TSettings.SetShowVerticalGridLines(const Value: Boolean);
begin
if Value <> ShowVerticalGridLines then
begin
FShowVerticalGridLines := Value;
Changed;
end;
end;
function TSettings.GetConnectionSettings: TConnectionSettings;
begin
Result := FConnectionSettings;
end;
procedure TSettings.SetConnectionSettings(const Value: TConnectionSettings);
begin
FConnectionSettings.Assign(Value);
Changed;
end;
function TSettings.GetDataTypeColor(Index: TDataType): TColor;
begin
Result := FDataTypeColors[Index];
end;
procedure TSettings.SetDataTypeColor(Index: TDataType; const Value: TColor);
begin
if FDataTypeColors[Index] <> Value then
begin
FDataTypeColors[Index] := Value;
Changed;
end;
end;
function TSettings.GetDefaultConnectionProfile: string;
begin
Result := FDefaultConnectionProfile;
end;
procedure TSettings.SetDefaultConnectionProfile(const Value: string);
begin
if Value <> DefaultConnectionProfile then
begin
FDefaultConnectionProfile := Value;
end;
end;
function TSettings.GetDataInspectorVisible: Boolean;
begin
Result := FDataInspectorVisible;
end;
procedure TSettings.SetDataInspectorVisible(const Value: Boolean);
begin
if Value <> DataInspectorVisible then
begin
FDataInspectorVisible := Value;
Changed;
end;
end;
function TSettings.GetEditorFont: TFont;
begin
Result := FEditorFont;
end;
procedure TSettings.SetEditorFont(const Value: TFont);
begin
FEditorFont.Assign(Value);
Changed;
end;
function TSettings.GetFileName: string;
begin
Result := FFileName;
end;
procedure TSettings.SetFileName(const Value: string);
begin
if Value <> FileName then
begin
FFileName := Value;
Changed;
end;
end;
function TSettings.GetFormSettings: TFormSettings;
begin
Result := FFormSettings;
end;
procedure TSettings.SetFormSettings(const Value: TFormSettings);
begin
FFormSettings.Assign(Value);
Changed;
end;
{$ENDREGION}
{$REGION 'event handlers'}
procedure TSettings.FormSettingsChanged(Sender: TObject);
begin
Changed;
end;
{$ENDREGION}
{$REGION 'protected methods'}
procedure TSettings.BeginUpdate;
begin
Inc(FUpdateLock);
end;
procedure TSettings.EndUpdate;
begin
if FUpdateLock > 0 then
begin
Dec(FUpdateLock);
if FUpdateLock = 0 then
Changed;
end;
end;
{$ENDREGION}
{$REGION 'public methods'}
procedure TSettings.Load;
var
JO : TJsonObject;
I : Integer;
CP : TConnectionProfile;
begin
if FileExists(FileName) then
begin
JO := TJsonObject.Create;
try
JO.LoadFromFile(FileName);
JO.ToSimpleObject(Self);
JO['FormSettings'].ObjectValue.ToSimpleObject(FFormSettings);
JO['EditorFont'].ObjectValue.ToSimpleObject(FEditorFont);
JO['GridFont'].ObjectValue.ToSimpleObject(FGridFont);
for I := 0 to JO['ConnectionProfiles'].ArrayValue.Count - 1 do
begin
CP := FConnectionProfiles.Add;
JO['ConnectionProfiles'].ArrayValue[I].ObjectValue.ToSimpleObject(CP);
JO['ConnectionProfiles']
.ArrayValue[I].O['ConnectionSettings']
.ObjectValue.ToSimpleObject(CP.ConnectionSettings);
end;
finally
JO.Free;
end;
end;
end;
procedure TSettings.Save;
var
JO : TJsonObject;
I : Integer;
begin
JO := TJsonObject.Create;
try
JO.FromSimpleObject(Self);
JO['FormSettings'].ObjectValue.FromSimpleObject(FormSettings);
JO['EditorFont'].ObjectValue.FromSimpleObject(EditorFont);
JO['GridFont'].ObjectValue.FromSimpleObject(GridFont);
for I := 0 to ConnectionProfiles.Count - 1 do
begin
JO['ConnectionProfiles'].ArrayValue
.AddObject
.FromSimpleObject(ConnectionProfiles[I]);
JO['ConnectionProfiles'].ArrayValue
.Values[I]
.O['ConnectionSettings']
.ObjectValue
.FromSimpleObject(ConnectionProfiles[I].ConnectionSettings);
end;
JO.SaveToFile(FileName, False);
finally
JO.Free;
end;
end;
{$ENDREGION}
end.
|
program Sumar10;
var
i,numero, suma, cant : integer;
begin
suma := 0;
cant := 0;
for i := 1 to 10 do begin
writeln('Ingrese un numero');
read(numero);
suma := suma + numero;
if (numero > 5) then
cant := cant + 1;
end;
writeln('La suma de los 10 números leídos es: ',suma);
writeln('La cantidad de números mayores a 5 es: ',cant);
end.
|
unit FreeOTFEfmeOptions_SystemTray;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, FreeOTFESettings, SDUStdCtrls,
CommonfmeOptions_Base, FreeOTFEfmeOptions_Base;
type
TfmeOptions_SystemTray = class(TfmeFreeOTFEOptions_Base)
gbSystemTrayIcon: TGroupBox;
ckUseSystemTrayIcon: TSDUCheckBox;
ckMinToIcon: TSDUCheckBox;
ckCloseToIcon: TSDUCheckBox;
gbClickActions: TGroupBox;
rbSingleClick: TRadioButton;
rbDoubleClick: TRadioButton;
Label1: TLabel;
Label2: TLabel;
cbClickAction: TComboBox;
procedure ckUseSystemTrayIconClick(Sender: TObject);
private
procedure PopulateAndSetClickAction(cbox: TComboBox; selectedAction: TSystemTrayClickAction);
function GetClickAction(cbox: TComboBox): TSystemTrayClickAction;
protected
procedure _ReadSettings(config: TFreeOTFESettings); override;
procedure _WriteSettings(config: TFreeOTFESettings); override;
public
procedure Initialize(); override;
procedure EnableDisableControls(); override;
end;
implementation
{$R *.dfm}
uses
Math,
SDUGeneral;
procedure TfmeOptions_SystemTray.ckUseSystemTrayIconClick(Sender: TObject);
begin
inherited;
EnableDisableControls();
end;
procedure TfmeOptions_SystemTray.Initialize();
var
maxToIconCkBoxWidth: integer;
maxgbWidth: integer;
begin
// ckHotkeyDismount and ckHotkeyDismountEmerg have AutoSize := TRUE
// Use the autosized controls to determine how big the groupbox needs to be
maxToIconCkBoxWidth := max(ckMinToIcon.width, ckCloseToIcon.width);
maxgbWidth := 0;
maxgbWidth := max(
maxgbWidth,
(ckUseSystemTrayIcon.left * 2) + ckUseSystemTrayIcon.width
);
maxgbWidth := max(
maxgbWidth,
(ckMinToIcon.left + maxToIconCkBoxWidth + ckUseSystemTrayIcon.left)
);
maxgbWidth := max(
maxgbWidth,
(gbClickActions.left + gbClickActions.width + ckUseSystemTrayIcon.left)
);
gbSystemTrayIcon.width := maxgbWidth;
SDUCenterControl(gbSystemTrayIcon, ccHorizontal);
SDUCenterControl(gbSystemTrayIcon, ccVertical, 25);
end;
procedure TfmeOptions_SystemTray.EnableDisableControls();
begin
inherited;
SDUEnableControl(ckMinToIcon, ckUseSystemTrayIcon.checked);
SDUEnableControl(ckCloseToIcon, ckUseSystemTrayIcon.checked);
SDUEnableControl(gbClickActions, ckUseSystemTrayIcon.checked);
end;
procedure TfmeOptions_SystemTray._ReadSettings(config: TFreeOTFESettings);
begin
// System tray icon related...
ckUseSystemTrayIcon.checked := config.OptSystemTrayIconDisplay;
ckMinToIcon.checked := config.OptSystemTrayIconMinTo;
ckCloseToIcon.checked := config.OptSystemTrayIconCloseTo;
if (config.OptSystemTrayIconActionSingleClick <> stcaDoNothing) then
begin
rbSingleClick.checked := TRUE;
PopulateAndSetClickAction(cbClickAction, config.OptSystemTrayIconActionSingleClick);
end
else
begin
rbDoubleClick.checked := TRUE;
PopulateAndSetClickAction(cbClickAction, config.OptSystemTrayIconActionDoubleClick);
end;
end;
procedure TfmeOptions_SystemTray._WriteSettings(config: TFreeOTFESettings);
begin
// System tray icon related...
config.OptSystemTrayIconDisplay := ckUseSystemTrayIcon.checked;
config.OptSystemTrayIconMinTo := ckMinToIcon.checked;
config.OptSystemTrayIconCloseTo := ckCloseToIcon.checked;
if rbSingleClick.checked then
begin
config.OptSystemTrayIconActionSingleClick := GetClickAction(cbClickAction);
config.OptSystemTrayIconActionDoubleClick := stcaDoNothing;
end
else
begin
config.OptSystemTrayIconActionSingleClick := stcaDoNothing;
config.OptSystemTrayIconActionDoubleClick := GetClickAction(cbClickAction);
end;
end;
procedure TfmeOptions_SystemTray.PopulateAndSetClickAction(cbox: TComboBox; selectedAction: TSystemTrayClickAction);
var
stca: TSystemTrayClickAction;
idx: integer;
useIdx: integer;
begin
// Populate and set default store op dropdown
cbox.Items.Clear();
idx := -1;
useIdx := -1;
for stca:=low(stca) to high(stca) do
begin
inc(idx);
cbox.Items.Add(SystemTrayClickActionTitle(stca));
if (selectedAction = stca) then
begin
useIdx := idx;
end;
end;
cbox.ItemIndex := useIdx;
end;
function TfmeOptions_SystemTray.GetClickAction(cbox: TComboBox): TSystemTrayClickAction;
var
stca: TSystemTrayClickAction;
retval: TSystemTrayClickAction;
begin
retval := stcaDoNothing;
// Decode click action...
for stca:=low(stca) to high(stca) do
begin
if (SystemTrayClickActionTitle(stca) = cbox.Items[cbox.ItemIndex]) then
begin
retval := stca;
break;
end;
end;
Result := retval;
end;
END.
|
unit unit_pas2c64_CodeGenerator;
{$MODE Delphi}
interface
uses
SysUtils,
Classes,
unit_Expressions;
const
cTAB = AnsiChar(#9);
cCRLF = AnsiString(#13#10);
cLabelIndent = 0;
cCommentIndent = 0;
cCodeIndent = 4;
cIndentChar = AnsiChar(' ');
type
MathException = class(Exception);
TMathRegister = (
mregI,
mregW,
mregF,
mregS
);
const
cRegisterCount = 8;
cRegister: array[TMathRegister] of String = (
'I',
'W',
'F',
'S'
);
type
C64OpException = Class(Exception);
Tc64Register = (
regA,
regX,
regY
);
TOpCode = (
opADC,
opAND,
opASL,
opBCC,
opBCS,
opBEQ,
opBIT,
opBMI,
opBNE,
opBPL,
opBRK,
opBVC,
opBVS,
opCLC,
opCLD,
opCLI,
opCLV,
opCMP,
opCPX,
opCPY,
opDEC,
opDEX,
opDEY,
opEOR,
opINC,
opINX,
opINY,
opJMP,
opJSR,
opLDA,
opLDX,
opLDY,
opLSR,
opNOP,
opORA,
opPHA,
opPHP,
opPLA,
opPLP,
opROL,
opROR,
opRTI,
opRTS,
opSBC,
opSEC,
opSED,
opSEI,
opSTA,
opSTX,
opSTY,
opTAX,
opTAY,
opTSX,
opTXA,
opTXS,
opTYA
);
TMode = (
modeA, // OPC A
modeAbs, // OPC $HHLL
modeAbsX, // OPC $HHLL,X
modeAbsY, // OPC $HHLL,Y
modeImmed, // OPC #$BB
modeImpl, // OPC
modeInd, // OPC ($HHLL)
modeXInd, // OPC ($BB,X)
modeIndY, // OPC ($LL),Y
modeRel, // OPC $BB
modeZpg, // OPC $LL
modeZpgX, // OPC $LL,X
modeZpgY // OPC $LL,Y
);
const
cRegisterName : array[Tc64Register] of AnsiString = (
'a',
'x',
'y'
);
cOpCodeName : array[TOpCode] of AnsiString = (
'adc',
'and',
'asl',
'bcc',
'bcs',
'beq',
'bit',
'bmi',
'bne',
'bpl',
'brk',
'bvc',
'bvs',
'clc',
'cld',
'cli',
'clv',
'cmp',
'cpx',
'cpy',
'dec',
'dex',
'dey',
'eor',
'inc',
'inx',
'iny',
'jmp',
'jsr',
'lda',
'ldx',
'ldy',
'lsr',
'nop',
'ora',
'pha',
'php',
'pla',
'plp',
'rol',
'ror',
'rti',
'rts',
'sbc',
'sec',
'sed',
'sei',
'sta',
'stx',
'sty',
'tax',
'tay',
'tsx',
'txa',
'txs',
'tya'
);
cLoadRegIm = [regA,regX,regY];
cLoadReg = [regA,regX,regY];
cStoreReg = [regA,regX,regY];
{
A .. Accumulator OPC A operand is AC
abs .. absolute OPC $HHLL operand is address $HHLL
abs,X .. absolute, X-indexed OPC $HHLL,X operand is address incremented by X with carry
abs,Y .. absolute, Y-indexed OPC $HHLL,Y operand is address incremented by Y with carry
# .. immediate OPC #$BB operand is byte (BB)
impl .. implied OPC operand implied
ind .. indirect OPC ($HHLL) operand is effective address; effective address is value of address
X,ind .. X-indexed, indirect OPC ($BB,X) operand is effective zeropage address; effective address is byte (BB) incremented by X without carry
ind,Y .. indirect, Y-indexed OPC ($LL),Y operand is effective address incremented by Y with carry; effective address is word at zeropage address
rel .. relative OPC $BB branch target is PC + offset (BB), bit 7 signifies negative offset
zpg .. zeropage OPC $LL operand is of address; address hibyte = zero ($00xx)
zpg,X .. zeropage, X-indexed OPC $LL,X operand is address incremented by X; address hibyte = zero ($00xx); no page transition
zpg,Y .. zeropage, Y-indexed OPC $LL,Y operand is address incremented by Y; address hibyte = zero ($00xx); no page transition
}
type
TCodeGenerator_C64 = class
private
FOutputStream : TStream;
FLabelIndex : Integer;
FRegId : array[TMathRegister] of Integer;
public
constructor Create;
destructor Destroy; override;
// output control
procedure SetOutputStream(const aStream: TStream);
// code generation
procedure ResetLabels;
function NewLabel: AnsiString;
function PushReg(aReg : TMathRegister) : String;
function PopReg(aReg : TMathRegister) : String;
procedure WriteOutput(const aStr: AnsiString);
procedure WriteOutputCR(aStr: AnsiString = '');
procedure WriteLabel(const aStr: AnsiString);
procedure WriteComment(const aStr: AnsiString);
procedure WriteCode(const aStr: AnsiString);
procedure WriteOrigin(const aAddr: Word);
// used with no basic loader
procedure WriteProgramStart(const aCodeAddr: Word); overload;
// used with a basic loader
procedure WriteProgramStart; overload;
procedure WriteMainStart;
procedure LoadReg_IM(const aReg: Tc64Register; const aConstValue: Byte);
procedure LoadRegW_IM(const aLoReg,aHiReg: Tc64Register; const aConstValue: Word);
procedure LoadReg_Mem(const aReg: Tc64Register; const aAddr: Word);
procedure StoreReg(const aReg: Tc64Register; const aAddr: Word);
procedure OpCode(const aOpCode: TOpCode);
procedure SwapRegisters(const aSrcReg,aDstReg: Tc64Register);
procedure OpA(const aOpCode: TOpCode); // OPC A
procedure OpAbs(const aOpCode: TOpCode; const aAddr: Word); // OPC $HHLL
procedure OpAbsX(const aOpCode: TOpCode; const aAddr: Word); // OPC $HHLL,X
procedure OpAbsY(const aOpCode: TOpCode; const aAddr: Word); // OPC $HHLL,Y
procedure OpImmed(const aOpCode: TOpCode; const aValue: Byte); // OPC #$BB
procedure OpImpl(const aOpCode: TOpCode); // OPC
procedure OpInd(const aOpCode: TOpCode; const aAddr: Word); // OPC ($HHLL)
procedure OpXInd(const aOpCode: TOpCode; const aAddr: Byte); // OPC ($BB,X)
procedure OpIndY(const aOpCode: TOpCode; const aAddr: Byte); // OPC ($LL),Y
procedure OpRel(const aOpCode: TOpCode; const aAddr: Byte); // OPC $BB
procedure OpZpg(const aOpCode: TOpCode; const aAddr: Byte); // OPC $LL
procedure OpZpgX(const aOpCode: TOpCode; const aAddr: Byte); // OPC $LL,X
procedure OpZpgY(const aOpCode: TOpCode; const aAddr: Byte); // OPC $LL,Y
end;
TC64Mantissa = array[0..3] of Byte;
PC64MemFloat = ^TC64MemFloat;
TC64MemFloat = packed record
Exponent: Byte;
Mantissa: TC64Mantissa;
end;
PC64RegFloat = ^TC64RegFloat;
TC64RegFloat = packed record
Exponent: Byte;
Mantissa: TC64Mantissa;
Sign: Byte;
end;
procedure FloatToC64Float(num: Double; out aC64Float: TC64MemFloat); overload;
procedure FloatToC64Float(num: Double; out aC64Float: TC64RegFloat); overload;
function C64FloatToStr(var aC64Float: TC64MemFloat): String; overload;
function C64FloatToStr(var aC64Float: TC64RegFloat): String; overload;
function C64MemFloat(const aExponent,aMan0,aMan1,aMan2,aMan3: Byte): TC64MemFloat;
function C64RegFloat(const aExponent,aMan0,aMan1,aMan2,aMan3,aSign: Byte): TC64RegFloat;
function C64FloatToFloat(var aC64Float: TC64MemFloat): Double; overload;
function C64FloatToFloat(var aC64Float: TC64RegFloat): Double; overload;
implementation
procedure FloatToC64Float(num: Double; out aC64Float: TC64MemFloat);
// converts a floating point number to 5-byte memory FP representation: exponent (1), mantissa (4)
//ftp://n2dvm.com/Commodore/Commie-CDs/Kazez%20FREE-CD/c64-knowledge-base/197.htm
var
ExpCount: Integer;
SignBit: Integer;
Index: Integer;
begin
Write(Format('%.10f = ',[num]));
// save sign bit
SignBit := 0;
if num < 0 then
begin
SignBit := 128;
num := -num;
end;
if Abs(num) < 0.000001 then
// if input is zero, set output
begin
aC64Float.Exponent := 0;
aC64Float.Mantissa[0] := 0;
aC64Float.Mantissa[1] := 0;
aC64Float.Mantissa[2] := 0;
aC64Float.Mantissa[3] := 0;
Exit;
end;
// calculate exponent byte
ExpCount := 0;
if num < 1 then
while num < 1 do
begin
Dec(ExpCount);
num := num * 2;
end
else
if num >= 2 then
while num >= 2 do
begin
Inc(ExpCount);
num := num / 2;
end;
aC64Float.Exponent := 129 + ExpCount;
num := num / 2; // 'un-normalize' it for forther processing (immediate mantissa)
// calculate mantissa digits
for Index := 0 to 3 do
begin
num := num * 256;
aC64Float.Mantissa[Index] := Trunc(num);
num := Frac(num);
end;
// round last mantissa digit when required
if num > 0.5 then Inc(aC64Float.Mantissa[3]);
// include sign bit in first mantissa digit
aC64Float.Mantissa[0] := (aC64Float.Mantissa[0] and $7F) or SignBit;
end;
procedure FloatToC64Float(num: Double; out aC64Float: TC64RegFloat);
// converts a floating point number to 6-byte register FP representation: exponent (1), mantissa (4), separate sign (1)
//ftp://n2dvm.com/Commodore/Commie-CDs/Kazez%20FREE-CD/c64-knowledge-base/197.htm
var
ExpCount: Integer;
SignBit: Integer;
Index: Integer;
begin
Write(Format('%.10f = ',[num]));
// save sign bit
SignBit := 0;
if num < 0 then
begin
SignBit := 128;
num := -num;
end;
if Abs(num) < 0.000001 then
begin
// if input is zero, set output
aC64Float.Exponent := 0;
aC64Float.Mantissa[0] := 0;
aC64Float.Mantissa[1] := 0;
aC64Float.Mantissa[2] := 0;
aC64Float.Mantissa[3] := 0;
aC64Float.Sign := 0;
Exit;
end;
// calculate exponent byte
ExpCount := 0;
if num < 1 then
while num < 1 do
begin
Dec(ExpCount);
num := num * 2;
end
else
if num >= 2 then
while num >= 2 do
begin
Inc(ExpCount);
num := num / 2;
end;
aC64Float.Exponent := 129 + ExpCount;
num := num / 2; // 'un-normalize' it for forther processing (immediate mantissa)
// calculate mantissa digits
for Index := 0 to 3 do
begin
num := num * 256;
aC64Float.Mantissa[Index] := Trunc(num);
num := Frac(num);
end;
// round last mantissa digit when required
if num > 0.5 then Inc(aC64Float.Mantissa[3]);
// include sign bit in sign part
aC64Float.Mantissa[4] := SignBit;
end;
function C64MemFloat(const aExponent,aMan0,aMan1,aMan2,aMan3: Byte): TC64MemFloat;
begin
Result.Exponent := aExponent;
Result.Mantissa[0] := aMan0;
Result.Mantissa[1] := aMan1;
Result.Mantissa[2] := aMan2;
Result.Mantissa[3] := aMan3;
end;
function C64RegFloat(const aExponent,aMan0,aMan1,aMan2,aMan3,aSign: Byte): TC64RegFloat;
begin
Result.Exponent := aExponent;
Result.Mantissa[0] := aMan0;
Result.Mantissa[1] := aMan1;
Result.Mantissa[2] := aMan2;
Result.Mantissa[3] := aMan3;
Result.Sign := aSign;
end;
function C64FloatToFloat(var aC64Float: TC64MemFloat): Double; overload;
const
cSignBit = 128;
var
Sign: Integer;
Mult: Integer;
Mantissa: TC64Mantissa;
Index: Integer;
begin
Result := 0;
if aC64Float.Exponent = 0 then Exit;
Mult := 1 shl Abs(aC64Float.Exponent - 129);
Mantissa := aC64Float.Mantissa;
// get sign bit and convert #1 mantissa digit if required
Sign := -1;
if (Mantissa[0] and cSignBit) = 0 then
begin
Sign := 1;
Mantissa[0] := Mantissa[0] or cSignBit;
end;
for Index := 0 to 3 do
Result := (Result + Mantissa[Index]) / 256;
if aC64Float.Exponent >= 129 then
Result := Result * 2 * Sign * Mult
else
Result := Result * 2 * Sign * 1/Mult;
end;
function C64FloatToFloat(var aC64Float: TC64RegFloat): Double; overload;
const
cSignBit = 128;
var
Sign: Integer;
Mult: Integer;
Mantissa: TC64Mantissa;
Index: Integer;
begin
Result := 0;
if aC64Float.Exponent = 0 then Exit;
Mult := 1 shl Abs(aC64Float.Exponent - 129);
Mantissa := aC64Float.Mantissa;
// get sign bit
Sign := -1;
if (aC64Float.Sign and cSignBit) = 0 then
Sign := 1;
for Index := 0 to 3 do
Result := (Result + Mantissa[Index]) / 256;
if aC64Float.Exponent >= 129 then
Result := Result * 2 * Sign * Mult
else
Result := Result * 2 * Sign * {1/}Mult;
end;
function C64FloatToStr(var aC64Float: TC64MemFloat): String;
begin
//output C64 mem floating point as hex (Exponent, Mantissa)
Result := LowerCase(Format('$%.2x,$%.2x,$%.2x,$%.2x,$%.2x',// (mem FP)',
[aC64Float.Exponent,
aC64Float.Mantissa[0],
aC64Float.Mantissa[1],
aC64Float.Mantissa[2],
aC64Float.Mantissa[3]]));
end;
function C64FloatToStr(var aC64Float: TC64RegFloat): String;
begin
//output C64 reg floating point as hex (Exponent, Mantissa, Sign)
Result := LowerCase(Format('$%.2x,$%.2x,$%.2x,$%.2x,$%.2x,$%.2x',// (reg FP)',
[aC64Float.Exponent,
aC64Float.Mantissa[0],
aC64Float.Mantissa[1],
aC64Float.Mantissa[2],
aC64Float.Mantissa[3],
aC64Float.Sign]));
end;
constructor TCodeGenerator_C64.Create;
begin
inherited Create;
FOutputStream := nil;
ResetLabels;
end;
destructor TCodeGenerator_C64.Destroy;
begin
inherited Destroy;
end;
procedure TCodeGenerator_C64.ResetLabels;
var
r: TMathRegister;
begin
FLabelIndex := 0;
// clear register ids
for r := Low(TMathRegister) to High(TMathRegister) do
FRegId[r] := -1;
end;
function TCodeGenerator_C64.NewLabel: AnsiString;
begin
Result := Format('L%d',[FLabelIndex]);
Inc(FLabelIndex);
end;
function TCodeGenerator_C64.PushReg(aReg : TMathRegister) : String;
begin
Inc(FRegID[aReg]);
if FRegID[aReg] = cRegisterCount then
raise MathException.Create(cRegister[aReg]+' Registers overflow!')
else
Result := cRegister[aReg] + IntToStr(FRegID[aReg]);
end;
{..............................................................................}
{..............................................................................}
function TCodeGenerator_C64.PopReg(aReg : TMathRegister) : String;
begin
if FRegID[aReg] = cRegisterCount then
raise MathException.Create(cRegister[aReg]+' Registers underflow!')
else
Result := cRegister[aReg] + IntToStr(FRegID[aReg]);
Dec(FRegID[aReg]);
end;
procedure TCodeGenerator_C64.SetOutputStream(const aStream: TStream);
begin
FOutputStream := aStream;
end;
procedure TCodeGenerator_C64.WriteOutput(const aStr: AnsiString);
begin
if not Assigned(FOutputStream) then Exit;
if aStr = '' then Exit;
FOutputStream.Write(PWideChar(aStr)^,Length(aStr));
end;
procedure TCodeGenerator_C64.WriteOutputCR(aStr: AnsiString = '');
begin
if not Assigned(FOutputStream) then Exit;
aStr := aStr + #13#10;
FOutputStream.Write(PWideChar(aStr)^,Length(aStr));
end;
procedure TCodeGenerator_C64.WriteLabel(const aStr: AnsiString);
begin
WriteOutputCR(StringOfChar(cIndentChar,cLabelIndent) + aStr + ':');
end;
procedure TCodeGenerator_C64.WriteComment(const aStr: AnsiString);
begin
WriteOutputCR(StringOfChar(cIndentChar,cCommentIndent) + '//' + aStr);
end;
procedure TCodeGenerator_C64.WriteCode(const aStr: AnsiString);
begin
WriteOutputCR(StringOfChar(cIndentChar,cCodeIndent) + aStr);
end;
procedure TCodeGenerator_C64.WriteOrigin(const aAddr: Word);
begin
WriteOutputCR(StringOfChar(cIndentChar,cCodeIndent) + '.pc = $' + LowerCase(IntToHex(aAddr,4)));
end;
procedure TCodeGenerator_C64.WriteProgramStart;
begin
WriteCode(':BasicUpstart2(main) // 10 sys <start address>');
WriteCode('');
WriteCode('');
{ WriteCode('.pc = $0800 // start at BASIC');
WriteCode('');
WriteCode('.import source "rtl\Macros_RTL.asm"');
WriteCode('');
WriteCode('.byte $00,$0c,$08,$0a,$00,$9e,$20,$32 // encode SYS 2064');
WriteCode('.byte $30,$36,$34,$00,$00,$00,$00,$00 // as BASIC line');
WriteOutputCR;
WriteLabel('Lab2064');
WriteCode('jmp start');}
end;
procedure TCodeGenerator_C64.WriteProgramStart(const aCodeAddr: Word);
begin
WriteOrigin(aCodeAddr);
WriteCode('');
WriteCode('jmp main');
end;
procedure TCodeGenerator_C64.WriteMainStart;
begin
WriteLabel('main');
end;
procedure TCodeGenerator_C64.LoadReg_IM(const aReg: Tc64Register; const aConstValue: Byte);
begin
if not(aReg in cLoadRegIM) then
raise C64OpException.Create('LoadReg_IM: Invalid register "'+cRegisterName[aReg]+'"');
WriteCode(LowerCase(Format('ld%s #$%.2x',[cRegisterName[aReg],aConstValue])));
end;
procedure TCodeGenerator_C64.LoadRegW_IM(const aLoReg,aHiReg: Tc64Register; const aConstValue: Word);
begin
if not (aLoReg in cLoadRegIM) or not (aHiReg in cLoadRegIM) then
raise C64OpException.Create('LoadRegW_IM: Invalid register(s) '+Format('"%s, %s"',[cRegisterName[aLoReg]+cRegisterName[aHiReg]]));
WriteCode(LowerCase(Format('ld%s <#$%.4x',[cRegisterName[aLoReg],aConstValue])));
WriteCode(LowerCase(Format('ld%s >#$%.4x',[cRegisterName[aHiReg],aConstValue])));
end;
procedure TCodeGenerator_C64.LoadReg_Mem(const aReg: Tc64Register; const aAddr: Word);
begin
if not(aReg in cLoadReg) then
raise C64OpException.Create('LoadReg_Mem: Invalid register "'+cRegisterName[aReg]+'"');
WriteCode(LowerCase(Format('ld%s $%.4x',[cRegisterName[aReg],aAddr])));
end;
procedure TCodeGenerator_C64.StoreReg(const aReg: Tc64Register; const aAddr: Word);
begin
if not(aReg in cStoreReg) then
raise C64OpException.Create('StoreReg: Invalid register "'+cRegisterName[aReg]+'"');
if aAddr <= 255 then
WriteCode(LowerCase(Format('st%s $%.2x',[cRegisterName[aReg],aAddr])))
else
WriteCode(LowerCase(Format('st%s $%.4x',[cRegisterName[aReg],aAddr])));
end;
procedure TCodeGenerator_C64.OpCode(const aOpCode: TOpCode);
begin
WriteCode(cOpCodeName[aOpCode]);
end;
procedure TCodeGenerator_C64.SwapRegisters(const aSrcReg,aDstReg: Tc64Register);
var
IllegalRegs: Boolean;
begin
IllegalRegs := (aSrcReg = aDstReg) or ((aSrcReg <> regA) and (aDstReg <> regA));
if IllegalRegs then raise C64OpException.Create('SwapRegisters: Invalid registers "'+cRegisterName[aSrcReg] + '&' + cRegisterName[aDstReg] +'"');
WriteCode('t' + cRegisterName[aSrcReg] + cRegisterName[aDstReg]);
end;
procedure TCodeGenerator_C64.OpA(const aOpCode: TOpCode); // OPC A
begin
WriteCode(cOpCodeName[aOpCode]);
end;
procedure TCodeGenerator_C64.OpAbs(const aOpCode: TOpCode; const aAddr: Word); // OPC $HHLL
begin
WriteCode(cOpCodeName[aOpCode] + ' $' + LowerCase(IntToHex(aAddr,4)));
end;
procedure TCodeGenerator_C64.OpAbsX(const aOpCode: TOpCode; const aAddr: Word); // OPC $HHLL,X
begin
WriteCode(cOpCodeName[aOpCode] + ' $' + LowerCase(IntToHex(aAddr,4) + ',X'));
end;
procedure TCodeGenerator_C64.OpAbsY(const aOpCode: TOpCode; const aAddr: Word); // OPC $HHLL,Y
begin
WriteCode(cOpCodeName[aOpCode] + ' $' + LowerCase(IntToHex(aAddr,4) + ',Y'));
end;
procedure TCodeGenerator_C64.OpImmed(const aOpCode: TOpCode; const aValue: Byte); // OPC #$BB
begin
WriteCode(cOpCodeName[aOpCode] + '#$' + LowerCase(IntToHex(aValue,2)));
end;
procedure TCodeGenerator_C64.OpImpl(const aOpCode: TOpCode); // OPC
begin
WriteCode(cOpCodeName[aOpCode]);
end;
procedure TCodeGenerator_C64.OpInd(const aOpCode: TOpCode; const aAddr: Word); // OPC ($HHLL)
begin
WriteCode(cOpCodeName[aOpCode] + ' ($' + LowerCase(IntToHex(aAddr,4) + ')'));
end;
procedure TCodeGenerator_C64.OpXInd(const aOpCode: TOpCode; const aAddr: Byte); // OPC ($BB,X)
begin
WriteCode(cOpCodeName[aOpCode] + ' ($' + LowerCase(IntToHex(aAddr,2) + ',X)'));
end;
procedure TCodeGenerator_C64.OpIndY(const aOpCode: TOpCode; const aAddr: Byte); // OPC ($LL),Y
begin
WriteCode(cOpCodeName[aOpCode] + ' ($' + LowerCase(IntToHex(aAddr,2) + '),Y'));
end;
procedure TCodeGenerator_C64.OpRel(const aOpCode: TOpCode; const aAddr: Byte); // OPC $BB
begin
WriteCode(cOpCodeName[aOpCode] + ' $' + LowerCase(IntToHex(aAddr,2)));
end;
procedure TCodeGenerator_C64.OpZpg(const aOpCode: TOpCode; const aAddr: Byte); // OPC $LL
begin
WriteCode(cOpCodeName[aOpCode] + ' $' + LowerCase(IntToHex(aAddr,2)));
end;
procedure TCodeGenerator_C64.OpZpgX(const aOpCode: TOpCode; const aAddr: Byte); // OPC $LL,X
begin
WriteCode(cOpCodeName[aOpCode] + ' $' + LowerCase(IntToHex(aAddr,2) + ',X'));
end;
procedure TCodeGenerator_C64.OpZpgY(const aOpCode: TOpCode; const aAddr: Byte); // OPC $LL,Y
begin
WriteCode(cOpCodeName[aOpCode] + ' $' + LowerCase(IntToHex(aAddr,2) + ',Y'));
end;
end.
|
unit usftp;
interface
uses windows,sysutils,classes,
libssh2_sftp,libssh2,
//blcksock,
winsock,
Dokan,DokanWin ;
function UNIXTimeToDateTimeFAST(UnixTime: LongWord): TDateTime;
function _FindFiles(FileName: LPCWSTR;
FillFindData: TDokanFillFindData;
var DokanFileInfo: DOKAN_FILE_INFO
): NTSTATUS; stdcall;
function _GetFileInformation(
FileName: LPCWSTR; var HandleFileInformation: BY_HANDLE_FILE_INFORMATION;
var DokanFileInfo: DOKAN_FILE_INFO): NTSTATUS; stdcall;
function _ReadFile(FileName: LPCWSTR; var Buffer;
BufferLength: DWORD;
var ReadLength: DWORD;
Offset: LONGLONG;
var DokanFileInfo: DOKAN_FILE_INFO): NTSTATUS; stdcall;
function _WriteFile(FileName: LPCWSTR; const Buffer;
NumberOfBytesToWrite: DWORD;
var NumberOfBytesWritten: DWORD;
Offset: LONGLONG;
var DokanFileInfo: DOKAN_FILE_INFO): NTSTATUS; stdcall;
function _MoveFile(FileName: LPCWSTR; // existing file name
NewFileName: LPCWSTR; ReplaceIfExisting: BOOL;
var DokanFileInfo: DOKAN_FILE_INFO): NTSTATUS; stdcall;
procedure _CloseFile(FileName: LPCWSTR;
var DokanFileInfo: DOKAN_FILE_INFO); stdcall;
procedure _Cleanup(FileName: LPCWSTR;
var DokanFileInfo: DOKAN_FILE_INFO); stdcall;
function _CreateFile(FileName: LPCWSTR; var SecurityContext: DOKAN_IO_SECURITY_CONTEXT;
DesiredAccess: ACCESS_MASK; FileAttributes: ULONG;
ShareAccess: ULONG; CreateDisposition: ULONG;
CreateOptions: ULONG; var DokanFileInfo: DOKAN_FILE_INFO): NTSTATUS; stdcall;
Function _DeleteFile(FileName: LPCWSTR;var DokanFileInfo: DOKAN_FILE_INFO): NTSTATUS; stdcall;
function _DeleteDirectory(FileName: LPCWSTR;var DokanFileInfo: DOKAN_FILE_INFO): NTSTATUS; stdcall;
function _Mount(rootdirectory:pwidechar):boolean;stdcall;
function _unMount: ntstatus;stdcall;
implementation
var
debug:boolean=true;
sock:tsocket;
session:PLIBSSH2_SESSION;
tmp:string;
host:string='';
username:string='';
password:string='';
sftp_session:PLIBSSH2_SFTP;
const
DOKAN_MAX_PATH = MAX_PATH;
type
WCHAR_PATH = array [0 .. DOKAN_MAX_PATH-1] of WCHAR;
function UNIXTimeToDateTimeFAST(UnixTime: LongWord): TDateTime;
begin
Result := (UnixTime / 86400) + 25569;
end;
procedure log(msg:string;level:byte=0);
begin
if (level=0) and (debug=false) then exit;
{$i-}writeln(msg);{$i+}
end;
procedure DbgPrint(format: string; const args: array of const); overload;
begin
//dummy
end;
procedure DbgPrint(fmt: string); overload;
begin
//dummy
end;
function _FindFiles(FileName: LPCWSTR;
FillFindData: TDokanFillFindData;
var DokanFileInfo: DOKAN_FILE_INFO
): NTSTATUS; stdcall;
var
str_type,str_size:string;
p:pchar;
findData: WIN32_FIND_DATAW;
ws:widestring;
systime_:systemtime;
filetime_:filetime;
path:string;
//
sftp_handle:PLIBSSH2_SFTP_HANDLE=nil;
i:integer;
mem:array [0..1023] of char;
longentry:array [0..511] of char;
attrs:LIBSSH2_SFTP_ATTRIBUTES;
begin
result:=2;
//
path := WideCharToString(filename);
path:=stringreplace(path,'\','/',[rfReplaceAll, rfIgnoreCase]);
if path='' then ;
log('***************************************');
log('_FindFiles');
log(path);
//
log('libssh2_sftp_opendir');
log('path:'+path);
sftp_handle := libssh2_sftp_opendir(sftp_session, pchar(path));
if sftp_handle=nil then
begin
log('cannot libssh2_sftp_opendir:'+path,1);
exit;
end;
while 1=1 do
begin
fillchar(mem,sizeof(mem),0);
FillChar (findData ,sizeof(findData ),0);
i := libssh2_sftp_readdir_ex(sftp_handle, @mem[0], sizeof(mem),longentry, sizeof(longentry), @attrs);
if i>0 then
begin
log(strpas(@mem[0])+':'+inttostr(attrs.filesize));
if ((attrs.flags and LIBSSH2_SFTP_ATTR_SIZE)=LIBSSH2_SFTP_ATTR_SIZE) then
begin
if (attrs.permissions and LIBSSH2_SFTP_S_IFMT) = LIBSSH2_SFTP_S_IFDIR
//if (attrs.filesize=4096)
then findData.dwFileAttributes := FILE_ATTRIBUTE_DIRECTORY
else findData.dwFileAttributes := FILE_ATTRIBUTE_NORMAL;
{
if findData.dwFileAttributes=FILE_ATTRIBUTE_DIRECTORY
then DokanFileInfo.isdirectory:=true
else DokanFileInfo.isdirectory:=false;
}
findData.nFileSizeHigh :=LARGE_INTEGER(attrs.filesize).HighPart;
findData.nFileSizeLow :=LARGE_INTEGER(attrs.filesize).LowPart;
end;
//
DateTimeToSystemTime(UNIXTimeToDateTimeFAST(attrs.atime ),systime_);
SystemTimeToFileTime(systime_ ,filetime_);
findData.ftCreationTime :=filetime_ ;
DateTimeToSystemTime(UNIXTimeToDateTimeFAST(attrs.atime ),systime_);
SystemTimeToFileTime(systime_ ,filetime_);
findData.ftLastAccessTime :=filetime_ ;
DateTimeToSystemTime(UNIXTimeToDateTimeFAST(attrs.mtime ),systime_);
SystemTimeToFileTime(systime_ ,filetime_);
findData.ftLastWriteTime :=filetime_ ;
//
ws:=widestring(strpas(@mem[0]));
Move(ws[1], findData.cFileName,Length(ws)*Sizeof(Widechar));
FillFindData(findData, DokanFileInfo);
end
else break;
end; //while 1=1 do
libssh2_sftp_closedir(sftp_handle);
Result := STATUS_SUCCESS;
end;
//invalid folder name if not implemented correctly
function _GetFileInformation(
FileName: LPCWSTR; var HandleFileInformation: BY_HANDLE_FILE_INFORMATION;
var DokanFileInfo: DOKAN_FILE_INFO): NTSTATUS; stdcall;
var
handle: THandle;
error: DWORD;
find: WIN32_FIND_DATAW;
findHandle: THandle;
opened: Boolean;
//
path:string;
systime_:systemtime;
filetime_:filetime;
attrs:LIBSSH2_SFTP_ATTRIBUTES;
rc:integer;
begin
result:=STATUS_NO_SUCH_FILE;
path := WideCharToString(filename);
path:=stringreplace(path,'\','/',[rfReplaceAll, rfIgnoreCase]);
//if path='/' then begin exit;end;
log('***************************************');
log('_GetFileInformation');
log(path);
//writeln(DokanFileInfo.IsDirectory );
log('libssh2_sftp_stat');
rc:= libssh2_sftp_stat(sftp_session,pchar(path),@attrs) ;
if rc=0 then
begin
//if LIBSSH2_SFTP_S_ISDIR() ... macro ...
//or flags ?
if (attrs.permissions and LIBSSH2_SFTP_S_IFMT) = LIBSSH2_SFTP_S_IFDIR
//if attrs.filesize =4096 //tricky ...
then HandleFileInformation.dwFileAttributes := FILE_ATTRIBUTE_DIRECTORY
else HandleFileInformation.dwFileAttributes := FILE_ATTRIBUTE_NORMAL ;
if HandleFileInformation.dwFileAttributes=FILE_ATTRIBUTE_DIRECTORY
then DokanFileInfo.isdirectory:=true
else DokanFileInfo.isdirectory:=false;
HandleFileInformation.nFileSizeHigh := LARGE_INTEGER(attrs.filesize ).highPart;
HandleFileInformation.nFileSizeLow := LARGE_INTEGER(attrs.filesize).LowPart;
DateTimeToSystemTime(UNIXTimeToDateTimeFAST(attrs.atime ),systime_);
SystemTimeToFileTime(systime_ ,filetime_);
HandleFileInformation.ftLastAccessTime :=filetime_ ;
DateTimeToSystemTime(UNIXTimeToDateTimeFAST(attrs.mtime),systime_);
SystemTimeToFileTime(systime_ ,filetime_);
HandleFileInformation.ftLastWriteTime :=filetime_ ;
//
Result := STATUS_SUCCESS;
end;
//else log('cannot libssh2_sftp_stat for:'+path,1);
end;
function _ReadFile(FileName: LPCWSTR; var Buffer;
BufferLength: DWORD;
var ReadLength: DWORD;
Offset: LONGLONG;
var DokanFileInfo: DOKAN_FILE_INFO): NTSTATUS; stdcall;
var
handle: THandle;
offset_: ULONG;
opened: Boolean;
error: DWORD;
distanceToMove: LARGE_INTEGER;
//
path:string;
sftp_handle:PLIBSSH2_SFTP_HANDLE=nil;
rc:integer;
ptr:pointer;
begin
result:=STATUS_NO_SUCH_FILE;
path := WideCharToString(filename);
path:=stringreplace(path,'\','/',[rfReplaceAll, rfIgnoreCase]);
if path='/' then begin exit;end;
log('***************************************');
log('_ReadFile');
log(path);
if DokanFileInfo.isdirectory=true then exit;
if DokanFileInfo.Context <>0 then sftp_handle :=pointer(DokanFileInfo.Context);
if DokanFileInfo.Context =0 then
begin
log('libssh2_sftp_open');
//* Request a file via SFTP */
sftp_handle :=libssh2_sftp_open(sftp_session, pchar(path), LIBSSH2_FXF_READ, 0);
DokanFileInfo.Context:=integer(sftp_handle);
end;
if sftp_handle=nil then
begin
log('cannot libssh2_sftp_open:'+path,1);
exit;
end;
//while 1=1 do
// begin
log('libssh2_sftp_seek:'+inttostr(offset));
libssh2_sftp_seek(sftp_handle,offset);
log('BufferLength:'+inttostr(BufferLength));
ReadLength :=0;
ptr:=@buffer;
while rc>0 do
begin
log('libssh2_sftp_read');
//seems that max readlength is 30000 bytes...so lets loop
rc := libssh2_sftp_read(sftp_handle, ptr, min(4096*4,bufferlength));
if rc<=0 then break;
inc(ReadLength ,rc);
inc(nativeuint(ptr),rc);
dec(bufferlength,rc);
end;
log('bytes read:'+inttostr(ReadLength));
if ReadLength>0
then Result := STATUS_SUCCESS
else log('libssh2_sftp_read failed:'+path,1);
//end; //while 1=1 do
end;
function _WriteFile(FileName: LPCWSTR; const Buffer;
NumberOfBytesToWrite: DWORD;
var NumberOfBytesWritten: DWORD;
Offset: LONGLONG;
var DokanFileInfo: DOKAN_FILE_INFO): NTSTATUS; stdcall;
var
filePath: WCHAR_PATH;
handle: THandle;
opened: Boolean;
error: DWORD;
fileSize: UINT64;
fileSizeLow: DWORD;
fileSizeHigh: DWORD;
z: LARGE_INTEGER;
bytes: UINT64;
distanceToMove: LARGE_INTEGER;
//
path:string;
sftp_handle:PLIBSSH2_SFTP_HANDLE=nil;
ptr:pointer;
rc:integer;
begin
log('***************************************');
log('_WriteFile');
result:=STATUS_NO_SUCH_FILE;
path := WideCharToString(filename);
path:=stringreplace(path,'\','/',[rfReplaceAll, rfIgnoreCase]);
if path='/' then begin exit;end;
log(path);
if DokanFileInfo.Context <>0 then sftp_handle :=pointer(DokanFileInfo.Context);
if DokanFileInfo.Context =0 then
begin
log('libssh2_sftp_open');
//* Request a file via SFTP */
sftp_handle :=libssh2_sftp_open(sftp_session, pchar(path), LIBSSH2_FXF_WRITE or LIBSSH2_FXF_CREAT or LIBSSH2_FXF_TRUNC,
LIBSSH2_SFTP_S_IRUSR or LIBSSH2_SFTP_S_IWUSR or
LIBSSH2_SFTP_S_IRGRP or LIBSSH2_SFTP_S_IROTH);
DokanFileInfo.Context:=integer(sftp_handle);
end;
if sftp_handle=nil then
begin
log('cannot libssh2_sftp_open',1);
exit;
end;
log('libssh2_sftp_seek:'+inttostr(offset));
libssh2_sftp_seek(sftp_handle,offset);
log('NumberOfBytesToWrite:'+inttostr(NumberOfBytesToWrite));
NumberOfBytesWritten :=0;
//NumberOfBytesWritten := libssh2_sftp_write(sftp_handle, @buffer, NumberOfBytesToWrite);
//windows seems to be smart enough if NumberOfBytesWritten<NumberOfBytesToWrite
//still we could/should it properly (code below to be reviewed)
ptr:=@buffer;
while rc>0 do
begin
log('libssh2_sftp_write');
rc := libssh2_sftp_write(sftp_handle, ptr, min(4096*4,NumberOfBytesToWrite));
if rc<=0 then break;
//writeln(rc);
inc(NumberOfBytesWritten,rc);
//writeln(NumberOfBytesWritten);
inc(nativeuint(ptr),rc);
dec(NumberOfBytesToWrite,rc);
//writeln(NumberOfBytesToWrite);
//writeln('.............');
end;
log('bytes written:'+inttostr(NumberOfBytesWritten));
if NumberOfBytesWritten>0
then Result := STATUS_SUCCESS
else log('libssh2_sftp_write failed',1);
end;
function _MoveFile(FileName: LPCWSTR; // existing file name
NewFileName: LPCWSTR; ReplaceIfExisting: BOOL;
var DokanFileInfo: DOKAN_FILE_INFO): NTSTATUS; stdcall;
var
old_path,new_path:string;
begin
log('***************************************');
log('_MoveFile');
old_path := WideCharToString(filename);
old_path:=stringreplace(old_path,'\','/',[rfReplaceAll, rfIgnoreCase]);
new_path := WideCharToString(NewFileName);
new_path:=stringreplace(new_path,'\','/',[rfReplaceAll, rfIgnoreCase]);
log('libssh2_sftp_rename');
if libssh2_sftp_rename (sftp_session,pchar(old_path),pchar(new_path ))=0
then result:=STATUS_SUCCESS
else result:=STATUS_NO_SUCH_FILE ;
end;
procedure _Cleanup(FileName: LPCWSTR;
var DokanFileInfo: DOKAN_FILE_INFO); stdcall;
var
path:string;
rc:integer;
begin
//
log('***************************************');
log('_Cleanup');
path := WideCharToString(filename);
path:=stringreplace(path,'\','/',[rfReplaceAll, rfIgnoreCase]);
if path='/' then begin exit;end;
log(path);
if DokanFileInfo.DeleteOnClose=true then
begin
if DokanFileInfo.IsDirectory =false then
begin
log('libssh2_sftp_unlink');
rc:=libssh2_sftp_unlink(sftp_session ,pchar(path));
if rc<>0 then log('libssh2_sftp_unlink failed',1)
end
else
//is a directory
begin
log('libssh2_sftp_rmdir');
rc:=libssh2_sftp_rmdir(sftp_session ,pchar(path));
if rc<>0 then log('libssh2_sftp_rmdir failed',1)
end;//if DokanFileInfo.IsDirectory =false then
end;//if DokanFileInfo.DeleteOnClose=true then
end;
//
procedure _CloseFile(FileName: LPCWSTR;
var DokanFileInfo: DOKAN_FILE_INFO); stdcall;
var
path:string;
begin
path := WideCharToString(filename);
path:=stringreplace(path,'\','/',[rfReplaceAll, rfIgnoreCase]);
log('***************************************');
log('_CloseFile');
log(path);
if DokanFileInfo.Context <>0 then
begin
log('libssh2_sftp_close');
libssh2_sftp_close(pointer(DokanFileInfo.Context ));
DokanFileInfo.Context := 0;
end;
end;
//
function _CreateFile(FileName: LPCWSTR; var SecurityContext: DOKAN_IO_SECURITY_CONTEXT;
DesiredAccess: ACCESS_MASK; FileAttributes: ULONG;
ShareAccess: ULONG; CreateDisposition: ULONG;
CreateOptions: ULONG; var DokanFileInfo: DOKAN_FILE_INFO): NTSTATUS; stdcall;
var
fileAttr: DWORD;
status: NTSTATUS;
creationDisposition: DWORD;
fileAttributesAndFlags: DWORD;
error: DWORD;
genericDesiredAccess: ACCESS_MASK;
path:string;
rc:integer;
begin
result := STATUS_SUCCESS;
log('***************************************');
log('_CreateFile');
path := WideCharToString(filename);
path:=stringreplace(path,'\','/',[rfReplaceAll, rfIgnoreCase]);
if path='/' then begin exit;end;
log(path);
DokanMapKernelToUserCreateFileFlags(
DesiredAccess, FileAttributes, CreateOptions, CreateDisposition,
@genericDesiredAccess, @fileAttributesAndFlags, @creationDisposition);
if (creationDisposition = CREATE_NEW) then
begin
if DokanFileInfo.IsDirectory =true then
begin
log('libssh2_sftp_mkdir');
rc:=libssh2_sftp_mkdir(sftp_session ,pchar(path),
LIBSSH2_SFTP_S_IRWXU or
LIBSSH2_SFTP_S_IRGRP or LIBSSH2_SFTP_S_IXGRP or
LIBSSH2_SFTP_S_IROTH or LIBSSH2_SFTP_S_IXOTH);
if rc<>0 then log('libssh2_sftp_mkdir failed',1)
end
else//if DokanFileInfo.IsDirectory =true then
begin
log('libssh2_sftp_open');
//DokanFileInfo.Context:=integer(...
if libssh2_sftp_open (sftp_session,pchar(path),LIBSSH2_FXF_CREAT,
LIBSSH2_SFTP_S_IRUSR or LIBSSH2_SFTP_S_IWUSR or
LIBSSH2_SFTP_S_IRGRP or LIBSSH2_SFTP_S_IROTH) =nil then log('libssh2_sftp_open failed',1)
end; //if DokanFileInfo.IsDirectory =true then
end;//if (creationDisposition = CREATE_NEW) then
end;
//cleanup is called instead
Function _DeleteFile (FileName: LPCWSTR;var DokanFileInfo: DOKAN_FILE_INFO): NTSTATUS; stdcall;
var
path:string;
rc:integer;
begin
result := STATUS_NO_SUCH_FILE;
log('***************************************');
log('_DeleteFile');
path := WideCharToString(filename);
path:=stringreplace(path,'\','/',[rfReplaceAll, rfIgnoreCase]);
log('libssh2_sftp_unlink');
rc:=libssh2_sftp_unlink(sftp_session ,pchar(path));
if rc<>0
then log('libssh2_sftp_unlink failed',1)
else result := STATUS_SUCCESS;
end;
//cleanup is called instead
function _DeleteDirectory(FileName: LPCWSTR;var DokanFileInfo: DOKAN_FILE_INFO): NTSTATUS; stdcall;
var
path:string;
rc:integer;
begin
result := STATUS_NO_SUCH_FILE;
log('***************************************');
log('_DeleteDirectory');
path := WideCharToString(filename);
path:=stringreplace(path,'\','/',[rfReplaceAll, rfIgnoreCase]);
log('libssh2_sftp_rmdir');
rc:=libssh2_sftp_rmdir(sftp_session ,pchar(path));
if rc<>0
then log('libssh2_sftp_rmdir failed',1)
else result := STATUS_SUCCESS;
end;
//previous version was using synapse
//lets switch to winsock2
function init_socket(var sock_:tsocket):boolean;
var
wsadata:TWSADATA;
err:longint;
hostaddr:u_long;
sin:sockaddr_in;
begin
result:=false;
//
err := WSAStartup(MAKEWORD(2, 0), wsadata);
if(err <> 0) then raise exception.Create ('WSAStartup failed with error: '+inttostr(err));
//
hostaddr := inet_addr(pchar(host));
//
sock_ := socket(AF_INET, SOCK_STREAM, 0);
//
sin.sin_family := AF_INET;
sin.sin_port := htons(22);
sin.sin_addr.s_addr := hostaddr;
if connect(sock_, tsockaddr(sin), sizeof(sockaddr_in)) <> 0
then raise exception.Create ('failed to connect');
//
result:=true;
end;
function _Mount(rootdirectory:pwidechar):boolean;stdcall;
var
i:integer;
fingerprint,userauthlist:PAnsiChar;
List: TStrings;
begin
result:=false;
//
debug:=false;
//
log ('******** proxy loaded ********',1);
log('rootdirectory:'+strpas(rootdirectory),1);
List := TStringList.Create;
ExtractStrings([':'], [], PChar(string(strpas(rootdirectory))), List);
if list.Count =3 then
begin
username:=list[0];
password:=list[1];
host:=list[2];
end;
List.Free;
if host='' then begin log('host is empty',1);exit; end;
if init_socket(sock)=false then raise exception.Create ('sock error');
log('libssh2_init...');
if libssh2_init(0)<>0 then
begin
log('Cannot libssh2_init',1);
exit;
end;
{ /* Create a session instance and start it up. This will trade welcome
* banners, exchange keys, and setup crypto, compression, and MAC layers
*/
}
log('libssh2_session_init...');
session := libssh2_session_init();
//* tell libssh2 we want it all done non-blocking */
//libssh2_session_set_blocking(session, 0);
log('libssh2_session_startup...');
if libssh2_session_startup(session, sock)<>0 then
begin
log('Cannot establishing SSH session',1);
exit;
end;
//
{
if libssh2_session_handshake(session, sock.socket)<>0 then
begin
writeln('Cannot libssh2_session_handshake');
exit;
end;
}
//
//writeln(libssh2_trace(session,LIBSSH2_TRACE_ERROR or LIBSSH2_TRACE_CONN or LIBSSH2_TRACE_TRANS or LIBSSH2_TRACE_SOCKET));
log('libssh2_version:'+libssh2_version(0));
//
{
/* At this point we havn't authenticated. The first thing to do is check
* the hostkey's fingerprint against our known hosts Your app may have it
* hard coded, may go to a file, may present it to the user, that's your
* call
*/
}
log('libssh2_hostkey_hash...');
fingerprint := libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
if fingerprint=nil then begin log('no fingerpint',1);exit;end;
log('Host fingerprint ');
i:=0;
//while fingerprint[i]<>#0 do
for i:=0 to 19 do
begin
tmp:=tmp+inttohex(ord(fingerprint[i]),2)+':';
//i:=i+1;
end;
log(tmp);
log('Assuming known host...');
//
log('libssh2_userauth_list...');
userauthlist := libssh2_userauth_list(session, pchar(username), strlen(pchar(username)));
log(strpas(userauthlist));
//
log('libssh2_userauth_password...');
if libssh2_userauth_password(session, pchar(username), pchar(password))<>0 then
begin
log('Authentication by password failed',1);
exit;
end;
log('Authentication succeeded');
log('libssh2_sftp_init...');
sftp_session := libssh2_sftp_init(session);
if sftp_session=nil then
begin
log('cannot libssh2_sftp_init',1);
exit;
end;
//* Since we have not set non-blocking, tell libssh2 we are blocking */
libssh2_session_set_blocking(session, 1);
result:=true;
end;
function _unMount: ntstatus;stdcall;
begin
libssh2_sftp_shutdown(sftp_session);
libssh2_session_disconnect(session, 'bye');
libssh2_session_free(session);
closesocket(sock);
libssh2_exit();
result:=STATUS_SUCCESS;
end;
end.
|
unit AsyncHttpServer.Headers;
interface
type
HttpHeader = record
Name: string;
Value: string;
end;
// HttpHeaderRef = record
// public
// type HttpHeaderPtr = ^HttpHeader;
// strict private
// FHeader: HttpHeaderPtr;
//
// function GetName: string;
// function GetValue: string;
//
// procedure SetName(const Value: string);
// procedure SetValue(const Value: string);
// public
// class operator Implicit(const HeaderPtr: HttpHeaderPtr): HttpHeaderRef;
//
// property Name: string read GetName write SetName;
// property Value: string read GetValue write SetValue;
// end;
HttpHeaders = TArray<HttpHeader>;
HttpHeadersHelper = record helper for HttpHeaders
{$REGION 'Property accessors'}
function GetValue(const Name: string): string;
procedure SetValue(const Name, Value: string);
{$ENDREGION}
// procedure Append; overload;
procedure Append(const Header: HttpHeader); overload;
function IsEmpty: boolean;
// function Last: HttpHeaderRef;
function ToDebugString: string;
property Value[const Name: string]: string read GetValue write SetValue;
end;
function EmptyHttpHeader(): HttpHeader;
implementation
uses
System.SysUtils;
function EmptyHttpHeader(): HttpHeader;
begin
result.Name := '';
result.Value := '';
end;
//{ HttpHeaderRef }
//
//function HttpHeaderRef.GetName: string;
//begin
// result := FHeader^.Name;
//end;
//
//function HttpHeaderRef.GetValue: string;
//begin
// result := FHeader^.Value;
//end;
//
//class operator HttpHeaderRef.Implicit(
// const HeaderPtr: HttpHeaderPtr): HttpHeaderRef;
//begin
// result.FHeader := HeaderPtr;
//end;
//
//procedure HttpHeaderRef.SetName(const Value: string);
//begin
// FHeader^.Name := Value;
//end;
//
//procedure HttpHeaderRef.SetValue(const Value: string);
//begin
// FHeader^.Value := Value;
//end;
{ HttpHeadersHelper }
//procedure HttpHeadersHelper.Append;
//var
// header: HttpHeader;
//begin
// Self.Append(header);
//end;
procedure HttpHeadersHelper.Append(const Header: HttpHeader);
begin
if (Header.Name = '') then
exit;
Insert(Header, Self, Length(Self));
end;
function HttpHeadersHelper.GetValue(const Name: string): string;
var
i: integer;
begin
result := '';
for i := 0 to High(Self) do
begin
if (Self[i].Name = Name) then
begin
result := Self[i].Value;
exit;
end;
end;
end;
function HttpHeadersHelper.IsEmpty: boolean;
begin
result := (Length(Self) = 0);
end;
//function HttpHeadersHelper.Last: HttpHeaderRef;
//begin
// if (Self.IsEmpty) then
// raise EInvalidOpException.Create('HttpHeaders.Last called on empty instance');
//
// result := @Self[High(Self)];
//end;
procedure HttpHeadersHelper.SetValue(const Name, Value: string);
var
i: integer;
header: HttpHeader;
begin
for i := 0 to High(Self) do
begin
if (Self[i].Name = Name) then
begin
Self[i].Value := Value;
exit;
end;
end;
// append new header
header.Name := Name;
header.Value := Value;
Self.Append(header);
end;
function HttpHeadersHelper.ToDebugString: string;
var
h: HttpHeader;
begin
result := '';
for h in Self do
begin
result := result + #13#10 + ' ' + h.Name + ': ' + h.Value;
end;
end;
end.
|
unit SCryptTests;
{
see https://github.com/JackTrapper/scrypt-for-delphi
}
interface
uses
TestFramework, SysUtils, Scrypt;
type
TScryptTests = class(TTestCase)
protected
FScrypt: TScrypt;
FFreq: Int64;
procedure SetUp; override;
procedure TearDown; override;
function GetTimestamp: Int64;
class function StringToUtf8Bytes(const s: UnicodeString): TBytes;
procedure Tester_HMAC_SHA1(HMACsha1: IHmacAlgorithm);
procedure Tester_HMAC_SHA256(HMACsha256: IHmacAlgorithm);
procedure Tester_PBKDF2_SHA1(Pbkdf: IPBKDF2Algorithm);
procedure Tester_PBKDF2_SHA256(Pbkdf2sha256: IPBKDF2Algorithm);
procedure Test_Scrypt_PasswordFormatting; //todo
public
procedure Benchmark_SHA1_PurePascal; //because native code should be fast
procedure Benchmark_SHA256_PurePascal;
procedure Benchmark_Hashes; //Compares SHA1 pure, Csp, Cng, SHA256 pure, Csp, Cng
procedure Benchmark_HMACs;
procedure Benchmark_PBKDF2s;
procedure ScryptBenchmarks; //Duration for different cost factor (N) and block size factor (r)
published
procedure Test_Base64;
//Even though we don't use SHA-1, we implemented it because PBKDF2_SHA1 is the only one with published test vectors
procedure Test_SHA1;
procedure Test_SHA1_PurePascal;
procedure Test_SHA1_Csp;
procedure Test_SHA1_Cng;
//Scrypt uses PBKDF2_SHA256. We fallback through Cng -> Csp -> PurePascal
procedure Test_SHA256;
procedure Test_SHA256_PurePascal;
procedure Test_SHA256_Csp;
procedure Test_SHA256_Cng;
//PBKDF2 uses HMAC. Test our implementation with known SHA1 and SHA256 test vectors
procedure Test_HMAC_SHA1;
procedure Test_HMAC_SHA1_PurePascal;
procedure Test_HMAC_SHA1_Cng;
procedure Test_HMAC_SHA256;
procedure Test_HMAC_SHA256_PurePascal;
procedure Test_HMAC_SHA256_Cng;
//Test PBKDF implementations; test with known SHA1 and SHA256 test vectors
procedure Test_PBKDF2_SHA1;
procedure Test_PBKDF2_SHA1_PurePascal;
procedure Test_PBKDF2_SHA1_Cng;
procedure Test_PBKDF2_SHA256;
procedure Test_PBKDF2_SHA256_PurePascal;
procedure Test_PBKDF2_SHA256_Cng;
//Salsa 20/8, BlockMix, and ROMix are the heart of scrypt. PBKDF2 is for key derivation. These are used for expensive salt
procedure Test_Salsa208Core;
procedure Test_BlockMix;
procedure Test_ROMix;
procedure Test_Scrypt; //official scrypt test vectors
//Password hashing
procedure Test_PasswordHashing; //Test, and verify, "correct horse battery staple"
procedure Test_JavaWgScrypt; //the only other example out there
procedure Test_RehashNeededKicksIn;
end;
TSHA1Tester = class(TObject)
protected
FSha1: IHashAlgorithm;
procedure SelfTest_Sizes; //block and digest sizes are right
procedure SelfTestA; //FIPS-180 AppendixA Test
procedure SelfTestB; //FIPS-180 AppendixB Test
procedure SelfTestC; //FIPS-180 AppendixC Test
procedure SelfTestD; //string i found that crashes the algoritm
public
constructor Create(SHA1: IHashAlgorithm);
destructor Destroy; override;
class procedure Test(SHA1: IHashAlgorithm);
end;
TSHA256Tester = class(TObject)
private
FSHA256: IHashAlgorithm;
function HexStringToBytes(s: string): TBytes;
function StringOfString(const s: string; Count: Integer): string;
procedure t(const s: string; expectedHash: string);
procedure tb(const Buffer; BufferLength: Integer; ExpectedHash: string);
protected
procedure TestSizes;
procedure OfficialVectors;
procedure OfficialVectors_HugeBuffers; //hashing of 100MB, or even 1.6 GB buffers - slow and out of memory
procedure UnofficialVectors;
public
constructor Create(SHA256: IHashAlgorithm);
destructor Destroy; override;
class procedure Test(SHA256: IHashAlgorithm);
end;
TScryptCracker = class(TScrypt)
public
end;
implementation
uses
Windows;
function HexToBytes(s: string): TBytes;
var
i, j: Integer;
n: Integer;
begin
for i := Length(s) downto 1 do
begin
if s[i] = ' ' then
Delete(s, i, 1);
end;
SetLength(Result, Length(s) div 2);
i := 1;
j := 0;
while (i < Length(s)) do
begin
n := StrToInt('0x'+s[i]+s[i+1]);
Result[j] := n;
Inc(i, 2);
Inc(j, 1);
end;
end;
{ TSHA1Tests }
constructor TSHA1Tester.Create(SHA1: IHashAlgorithm);
begin
inherited Create;
FSha1 := SHA1;
end;
destructor TSHA1Tester.Destroy;
begin
FSHA1 := nil;
inherited;
end;
procedure TSHA1Tester.SelfTestA;
const
Answer: array[0..19] of Byte =
($A9, $99, $3E, $36,
$47, $06, $81, $6A,
$BA, $3E, $25, $71,
$78, $50, $C2, $6C,
$9C, $D0, $D8, $9D);
var
szInData: UnicodeString;
testData: TBytes;
digest: TBytes;
begin
{This is the test data from FIPS-180 Appendix A}
szInData := 'abc';
testData := TScryptTests.StringToUtf8Bytes(szInData);
FSha1.HashData(testData[0], Length(testData));
Digest := FSha1.Finalize;
if not CompareMem(@digest[0], @Answer[0], Length(Answer)) then
raise EScryptException.Create('SHA-1 self-test A failed');
end;
procedure TSHA1Tester.SelfTestB;
const
Answer: array[0..19] of Byte =
($84, $98, $3E, $44,
$1C, $3B, $D2, $6E,
$BA, $AE, $4A, $A1,
$F9, $51, $29, $E5,
$E5, $46, $70, $F1);
var
szInData: UnicodeString;
testData: TBytes;
digest: TBytes;
begin
{This is the test data from FIPS-180 Appendix B}
szInData := 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq';
testData := TScryptTests.StringToUtf8Bytes(szInData);
FSha1.HashData(TestData[0], Length(TestData));
digest := FSha1.Finalize;
if not CompareMem(@digest[0], @Answer[0], Sizeof(Answer)) then
raise EScryptException.Create('SHA-1 self-test B failed');
end;
procedure TSHA1Tester.SelfTestC;
const
Answer: array[0..19] of Byte =
($34, $AA, $97, $3C,
$D4, $C4, $DA, $A4,
$F6, $1E, $EB, $2B,
$DB, $AD, $27, $31,
$65, $34, $01, $6F);
var
digest: TBytes;
testData: TBytes;
testValue: Byte;
begin
{Build a string which consists of 1,000,000 repetitions of "a"}
testValue := Ord('a');
SetLength(TestData, 1000000);
FillChar(TestData[0], 1000000, TestValue);
FSha1.HashData(testData[0], Length(testData));
digest := FSha1.Finalize;
if not CompareMem(@Digest[0], @Answer[0], Length(Answer)) then
raise EScryptException.Create('SHA-1 self-test C failed');
end;
procedure TSHA1Tester.SelfTestD;
const
Answer: array[0..19] of Byte =
($85, $B6, $95, $33,
$89, $5F, $9C, $08,
$18, $4F, $1F, $16,
$3C, $91, $51, $FD,
$47, $B1, $E4, $9E);
var
digest: TBytes;
TestData: TBytes;
TestValue: Byte;
begin
{Build a string which consists of 202 repetitions of "a"}
TestValue := Ord('a');
SetLength(TestData, 202);
FillChar(TestData[0], 202, TestValue);
FSha1.HashData(TestData[0], Length(testData));
digest := FSha1.Finalize;
if not CompareMem(@digest[0], @Answer[0], Sizeof(Answer)) then
raise EScryptException.Create('SHA-1 self-test A failed');
end;
procedure TSHA1Tester.SelfTest_Sizes;
begin
if FSha1.BlockSize <> 64 then
raise EScryptException.CreateFmt('SHA1 block size (%d) was not 64 bytes', [FSha1.BlockSize]);
if FSha1.DigestSize <> 20 then
raise EScryptException.CreateFmt('SHA1 digest size (%d) was not 20 bytes', [FSha1.DigestSize]);
end;
class procedure TSHA1Tester.Test(SHA1: IHashAlgorithm);
var
tester: TSHA1Tester;
begin
tester := TSHA1Tester.Create(SHA1);
try
tester.SelfTest_Sizes;
tester.SelfTestA;
tester.SelfTestB;
tester.SelfTestC;
tester.SelfTestD;
finally
tester.Free;
end;
end;
{ TScryptTests }
procedure TScryptTests.Test_SHA256;
var
sha256: IHashAlgorithm;
begin
sha256 := TScryptCracker.CreateObject('SHA256') as IHashAlgorithm;
TSHA256Tester.Test(sha256);
end;
procedure TScryptTests.Test_SHA256_Cng;
var
sha256: IHashAlgorithm;
begin
sha256 := TScryptCracker.CreateObject('SHA256.Cng') as IHashAlgorithm;
TSHA256Tester.Test(sha256);
end;
procedure TScryptTests.Test_SHA256_Csp;
var
sha256: IHashAlgorithm;
begin
sha256 := TScryptCracker.CreateObject('SHA256.Csp') as IHashAlgorithm;
TSHA256Tester.Test(sha256);
end;
procedure TScryptTests.Test_SHA256_PurePascal;
var
sha256: IHashAlgorithm;
begin
sha256 := TScryptCracker.CreateObject('SHA256.PurePascal') as IHashAlgorithm;
TSHA256Tester.Test(sha256);
end;
procedure TScryptTests.SetUp;
begin
inherited;
FScrypt := TScrypt.Create;
if not QueryPerformanceFrequency(FFreq) then //it's documented to never fail, but it can (see SO).
FFreq := -1;
end;
procedure TScryptTests.TearDown;
begin
FreeAndNil(FScrypt);
inherited;
end;
class function TScryptTests.StringToUtf8Bytes(const s: UnicodeString): TBytes;
var
strLen: Integer;
dw: DWORD;
begin
strLen := Length(s);
if strLen = 0 then
begin
SetLength(Result, 0);
Exit;
end;
// Determine real size of destination string, in bytes
strLen := WideCharToMultiByte(CP_UTF8, 0, PWideChar(s), Length(s), nil, 0, nil, nil);
if strLen = 0 then
begin
dw := GetLastError;
raise EConvertError.Create('Could not get length of destination string. Error '+IntToStr(dw)+' ('+SysErrorMessage(dw)+')');
end;
// Allocate memory for destination string
SetLength(Result, strLen);
// Convert source UTF-16 string (UnicodeString) to the destination using the code-page
strLen := WideCharToMultiByte(CP_UTF8, 0, PWideChar(s), Length(s), PAnsiChar(@Result[0]), strLen, nil, nil);
if strLen = 0 then
begin
dw := GetLastError;
raise EConvertError.Create('Could not convert utf16 to utf8 string. Error '+IntToStr(dw)+' ('+SysErrorMessage(dw)+')');
end;
end;
procedure TScryptTests.Test_JavaWgScrypt;
var
passwordRehashNeeded: Boolean;
begin
{
From: https://github.com/wg/scrypt
Passwd = "secret"
N = 16384
r = 8
p = 1
}
TScrypt.CheckPassword('secret', '$s0$e0801$epIxT/h6HbbwHaehFnh/bw==$7H0vsXlY8UxxyW/BWx/9GuY7jEvGjT71GFd6O4SZND0=', {out}passwordRehashNeeded);
end;
procedure TScryptTests.Test_Base64;
var
buffer, bufferActual: TBytes;
function BASE64(s: AnsiString): string;
var
b: TBytes;
begin
SetLength(b, Length(s));
if Length(s) > 0 then
Move(s[1], b[0], Length(s));
Result := TScryptCracker.Base64Encode(b);
end;
procedure Test(Original: AnsiString; Expected: string);
var
actual: string;
recovered: AnsiString;
data: TBytes;
begin
actual := BASE64(Original);
CheckEquals(Expected, actual);
//Do the reverse
data := TScryptCracker.Base64Decode(Expected);
SetLength(recovered, Length(data));
if Length(data) > 0 then
Move(data[0], recovered[1], Length(data));
CheckEquals(Original, recovered);
end;
begin
{
From RFC4648 - The Base16, Base32, and Base64 Data Encodings
https://tools.ietf.org/html/rfc4648#section-10
}
Test('', '');
Test('f', 'Zg==');
Test('fo', 'Zm8=');
Test('foo', 'Zm9v');
Test('foob', 'Zm9vYg==');
Test('fooba', 'Zm9vYmE=');
Test('foobar', 'Zm9vYmFy');
{
From the wg/scrypt example
epIxT/h6HbbwHaehFnh/bw== ==> 122 146 49 79 248 122 29 182 240 29 167 161 22 120 127 111
}
buffer := HexToBytes('7a 92 31 4f f8 7a 1d b6 f0 1d a7 a1 16 78 7f 6f');
CheckEquals('epIxT/h6HbbwHaehFnh/bw==', TScryptCracker.Base64Encode(buffer));
bufferActual := TScryptCracker.Base64Decode('epIxT/h6HbbwHaehFnh/bw==');
CheckEquals(Length(buffer), Length(bufferActual));
CheckEqualsMem(@buffer[0], @bufferActual[0], Length(bufferActual));
end;
procedure TScryptTests.Test_RehashNeededKicksIn;
var
passwordRehashNeeded: Boolean;
const
SHash = '$s1$0E0101$dVmS3NXyc0SHM0MBt4qR6Q==$kIF3PYaFHgoetpsSNxi08PGuC7/u+edZd1fRNCtUNnrQsKTCEjI2y6HOGH+S/J2yy7f1JywsSIyBkUfPeMrU9w==';
begin
{
N=14,r=1,p=1 (2 MB, 37ms) is too weak for any password on any computer. You target is:
- regular passwords: 500ms
- sensitive passwords: 12,000ms
}
CheckTrue(TScrypt.CheckPassword('Hashes too fast', SHash, {out}passwordRehashNeeded));
CheckTrue(passwordRehashNeeded);
end;
{ TSHA256Tester }
function TSHA256Tester.StringOfString(const s: string; Count: Integer): string;
var
i: Integer;
begin
Result := '';
for i := 1 to Count do
Result := Result+s;
end;
constructor TSHA256Tester.Create(SHA256: IHashAlgorithm);
begin
inherited Create;
FSHA256 := SHA256;
end;
destructor TSHA256Tester.Destroy;
begin
FSHA256 := nil;
inherited;
end;
function TSHA256Tester.HexStringToBytes(s: string): TBytes;
var
i, j: Integer;
n: Integer;
begin
for i := Length(s) downto 1 do
begin
if s[i] = ' ' then
Delete(s, i, 1);
end;
SetLength(Result, Length(s) div 2);
i := 1;
j := 0;
while (i < Length(s)) do
begin
n := StrToInt('0x'+s[i]+s[i+1]);
Result[j] := n;
Inc(i, 2);
Inc(j, 1);
end;
end;
procedure TSHA256Tester.tb(const Buffer; BufferLength: Integer; ExpectedHash: string);
var
digest: TBytes;
expectedBytes: TBytes;
begin
FSHA256.HashData(Buffer, BufferLength);
digest := FSHA256.Finalize;
expectedBytes := HexStringToBytes(ExpectedHash);
if not CompareMem(@digest[0], @expectedBytes[0], Length(expectedBytes)) then
raise EScryptException.Create('SHA2-256 hash failed');
end;
procedure TSHA256Tester.t(const s: string; expectedHash: string);
var
utf8Data: TBytes;
digest: TBytes;
expectedBytes: TBytes;
begin
utf8Data := TScryptTests.StringToUtf8Bytes(s);
expectedBytes := HexStringToBytes(expectedHash);
FSHA256.HashData(Pointer(utf8Data)^, Length(utf8Data));
digest := FSHA256.Finalize;
if not CompareMem(@digest[0], @expectedBytes[0], Length(expectedBytes)) then
raise EScryptException.Create('SHA2-256 hash failed');
end;
procedure TSHA256Tester.OfficialVectors;
var
buff: TBytes;
begin
{
http://csrc.nist.gov/groups/ST/toolkit/documents/Examples/SHA256.pdf
}
t('abc', 'BA7816BF 8F01CFEA 414140DE 5DAE2223 B00361A3 96177A9C B410FF61 F20015AD');
t('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', '248D6A61 D20638B8 E5C02693 0C3E6039 A33CE459 64FF2167 F6ECEDD4 19DB06C1');
SetLength(buff, 3);
buff[0] := $61; //'a'
buff[1] := $62; //'b'
buff[2] := $63; //'c'
tb(buff[0], Length(buff), 'BA7816BF 8F01CFEA 414140DE 5DAE2223 B00361A3 96177A9C B410FF61 F20015AD');
{
http://csrc.nist.gov/groups/ST/toolkit/documents/Examples/SHA2_Additional.pdf
}
//#1) 1 byte 0xbd
SetLength(buff, 1);
buff[0] := $bd;
tb(buff[0], Length(buff), '68325720 aabd7c82 f30f554b 313d0570 c95accbb 7dc4b5aa e11204c0 8ffe732b');
//#2) 4 bytes 0xc98c8e55
SetLength(buff, 4);
PDWORD(@buff[0])^ := $558e8cc9;
tb(buff[0], Length(buff), '7abc22c0 ae5af26c e93dbb94 433a0e0b 2e119d01 4f8e7f65 bd56c61c cccd9504');
//#3) 55 bytes of zeros
SetLength(buff, 55);
FillChar(buff[0], Length(buff), 0);
tb(buff[0], Length(buff), '02779466 cdec1638 11d07881 5c633f21 90141308 1449002f 24aa3e80 f0b88ef7');
//#4) 56 bytes of zeros
SetLength(buff, 56);
FillChar(buff[0], Length(buff), 0);
tb(buff[0], Length(buff), 'd4817aa5 497628e7 c77e6b60 6107042b bba31308 88c5f47a 375e6179 be789fbb');
//#5) 57 bytes of zeros
SetLength(buff, 57);
FillChar(buff[0], Length(buff), 0);
tb(buff[0], Length(buff), '65a16cb7 861335d5 ace3c607 18b5052e 44660726 da4cd13b b745381b 235a1785');
//#6) 64 bytes of zeros
SetLength(buff, 64);
FillChar(buff[0], Length(buff), 0);
tb(buff[0], Length(buff), 'f5a5fd42 d16a2030 2798ef6e d309979b 43003d23 20d9f0e8 ea9831a9 2759fb4b');
//#7) 1000 bytes of zeros
SetLength(buff, 1000);
FillChar(buff[0], Length(buff) , 0);
tb(buff[0], Length(buff), '541b3e9d aa09b20b f85fa273 e5cbd3e8 0185aa4e c298e765 db87742b 70138a53');
//#8) 1000 bytes of 0x41 ‘A’
SetLength(buff, 1000);
FillChar(buff[0], Length(buff), $41);
tb(buff[0], Length(buff), 'c2e68682 3489ced2 017f6059 b8b23931 8b6364f6 dcd835d0 a519105a 1eadd6e4');
//#9) 1005 bytes of 0x55 ‘U’
SetLength(buff, 1005);
FillChar(buff[0], Length(buff), $55);
tb(buff[0], Length(buff), 'f4d62dde c0f3dd90 ea1380fa 16a5ff8d c4c54b21 740650f2 4afc4120 903552b0');
end;
procedure TSHA256Tester.OfficialVectors_HugeBuffers;
var
data: PByte;
begin
{
http://csrc.nist.gov/groups/ST/toolkit/documents/Examples/SHA256.pdf
}
//#10) 1,000,000 bytes of zeros
GetMem(data, 1000000);
try
FillChar(data^, 1000000, 0);
tb(data^, 1000000, 'd29751f2 649b32ff 572b5e0a 9f541ea6 60a50f94 ff0beedf b0b692b9 24cc8025');
finally
FreeMem(data);
end;
//#11) 0x20000000 (536,870,912) bytes of 0x5a ‘Z’
GetMem(data, $20000000);
try
FillChar(data^, $20000000, $5a);
tb(data^, $20000000, '15a1868c 12cc5395 1e182344 277447cd 0979536b adcc512a d24c67e9 b2d4f3dd');
finally
FreeMem(data);
end;
//#12) 0x41000000 (1,090,519,040) bytes of zeros
GetMem(data, $41000000);
try
FillChar(data^, $41000000, 0);
tb(data^, $41000000, '461c19a9 3bd4344f 9215f5ec 64357090 342bc66b 15a14831 7d276e31 cbc20b53');
finally
FreeMem(data);
end;
//#13) 0x6000003e (1,610,612,798) bytes of 0x42 ‘B’
GetMem(data, $6000003e);
try
FillChar(data^, $6000003e, $420);
tb(data^, $6000003e, 'c23ce8a7 895f4b21 ec0daf37 920ac0a2 62a22004 5a03eb2d fed48ef9 b05aabea');
finally
FreeMem(data);
end;
end;
class procedure TSHA256Tester.Test(SHA256: IHashAlgorithm);
var
t: TSHA256Tester;
begin
t := TSHA256Tester.Create(SHA256);
try
t.TestSizes;
t.OfficialVectors;
t.UnofficialVectors;
finally
t.Free;
end;
end;
procedure TSHA256Tester.TestSizes;
begin
if FSha256.BlockSize <> 64 then
raise EScryptException.CreateFmt('SHA256 block size (%d) was not 64 bytes', [FSha256.BlockSize]);
if FSha256.DigestSize <> 32 then
raise EScryptException.CreateFmt('SHA256 digest size (%d) was not 32 bytes', [FSha256.DigestSize]);
end;
procedure TSHA256Tester.UnofficialVectors;
begin
{
https://www.cosic.esat.kuleuven.be/nessie/testvectors/hash/sha/Sha-2-256.unverified.test-vectors
}
t('abcdefghijklmnopqrstuvwxyz', '71C480DF93D6AE2F1EFAD1447C66C9525E316218CF51FC8D9ED832F2DAF18B73');
t('', 'E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855');
t('a', 'CA978112CA1BBDCAFAC231B39A23DC4DA786EFF8147C4E72B9807785AFEE48BB');
t('abc', 'BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD');
t('message digest', 'F7846F55CF23E14EEBEAB5B4E1550CAD5B509E3348FBC4EFA3A1413D393CB650');
t('abcdefghijklmnopqrstuvwxyz', '71C480DF93D6AE2F1EFAD1447C66C9525E316218CF51FC8D9ED832F2DAF18B73');
t('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', '248D6A61D20638B8E5C026930C3E6039A33CE45964FF2167F6ECEDD419DB06C1');
t('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', 'DB4BFCBD4DA0CD85A60C3C37D3FBD8805C77F15FC6B1FDFE614EE0A7C8FDB4C0');
t(StringOfString('1234567890', 8), 'F371BC4A311F2B009EEF952DD83CA80E2B60026C8E935592D0F9C308453C813E');
t(StringOfChar('a', 1000000), 'CDC76E5C9914FB9281A1C7E284D73E67F1809A48A497200E046D39CCC7112CD0');
t('The quick brown fox jumps over the lazy dog', 'd7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592');
end;
procedure TScryptTests.Benchmark_Hashes;
var
data: TBytes;
procedure Test(HashAlgorithmName: string);
var
hash: IHashAlgorithm;
t1, t2: Int64;
bestTime: Int64;
i: Integer;
begin
hash := TScryptCracker.CreateObject(HashAlgorithmName) as IHashAlgorithm;
bestTime := 0;
//Fastest time of 5 runs
for i := 1 to 5 do
begin
t1 := GetTimestamp;
hash.HashData(data[0], Length(data));
t2 := GetTimestamp;
t2 := t2-t1;
if (bestTime = 0) or (t2 < bestTime) then
bestTime := t2;
end;
Status(Format('%s %.3f MB/s', [HashAlgorithmName, (Length(data)/1024/1024) / (bestTime/FFreq)]));
end;
begin
data := TScrypt.GetBytes('hash test', 'Scrypt for Delphi', 1, 1, 1, 1*1024*1024); //1 MB
Status(Format('%s %s', ['Algorithm', 'Speed (MB/s)']));
Test('SHA1.PurePascal');
Test('SHA1.Csp');
Test('SHA1.Cng');
Test('SHA256.PurePascal');
Test('SHA256.Csp');
Test('SHA256.Cng');
end;
procedure TScryptTests.Benchmark_SHA1_PurePascal;
var
hash: IHashAlgorithm;
t1, t2: Int64;
data: TBytes;
best: Int64;
i: Integer;
begin
//Generate 1 MB of test data to hash
data := TScrypt.GetBytes('hash test', 'Scrypt for Delphi', 1, 1, 1, 1*1024*1024); //1 MB
//Get our pure pascal SHA-1 implementation
hash := TScryptCracker.CreateObject('SHA1.PurePascal') as IHashAlgorithm;
best := 0;
OutputDebugString('SAMPLING ON');
for i := 1 to 60 do
begin
t1 := GetTimestamp;
hash.HashData(data[0], Length(data));
t2 := GetTimestamp;
if (((t2-t1) < best) or (best = 0)) then
best := (t2-t1);
end;
OutputDebugString('SAMPLING OFF');
Status(Format('%s: %.3f MB/s', ['TSHA1', (Length(data)/1024/1024) / (best/FFreq)]));
end;
procedure TScryptTests.Benchmark_SHA256_PurePascal;
var
hash: IHashAlgorithm;
t1, t2: Int64;
data: TBytes;
best: Int64;
i: Integer;
begin
//Generate 1 MB of test data to hash
data := TScrypt.GetBytes('hash test', 'Scrypt for Delphi', 1, 1, 1, 1*1024*1024); //1 MB
//Benchmark SHA256PurePascal with the test data
best := 0;
hash := TScryptCracker.CreateObject('SHA256.PurePascal') as IHashAlgorithm;
OutputDebugString('SAMPLING ON');
for i := 1 to 60 do
begin
t1 := GetTimestamp;
hash.HashData(data[0], Length(data));
t2 := GetTimestamp;
if (((t2-t1) < best) or (best = 0)) then
best := (t2-t1);
end;
OutputDebugString('SAMPLING OFF');
Status(Format('%s: %.3f MB/s', ['SHA256', (Length(data)/1024/1024) / (best/FFreq)]));
end;
function TScryptTests.GetTimestamp: Int64;
begin
if not QueryPerformanceCounter(Result) then //it's documented to never fail; but it can. See SO
Result := 0;
end;
procedure TScryptTests.ScryptBenchmarks;
var
freq, t1, t2: Int64;
N, r: Integer;
s: string;
RowLeader, ColumnSeparator, RowTrailer: string;
function ElapsedTicks(StartTicks: Int64): Int64;
var
endTicks: Int64;
begin
if not QueryPerformanceCounter(endTicks) then endTicks := 0;
Result := (endTicks - StartTicks);
end;
const
UseTsv: Boolean = True;
N_max = 20; //20 trips up on VM and address space limits
r_max = 16; //8 ==> 1 KB block. 16 ==> 2 KB block
//Tab separated values (copy-paste to Excel)
TsvRowLeader = ''; //'|';
TsvColumnSeparator = ' '; //'|';
TsvRowTrailer = ''; //'|';
//Markdown
MRowLeader = '| ';
MColumnSeparator = ' | ';
MRowTrailer = ' |';
const
STestPassword = 'correct horse battery staple';
begin
QueryPerformanceFrequency(freq);
if UseTsv then
begin
RowLeader := TsvRowLeader;
ColumnSeparator := TsvColumnSeparator;
RowTrailer := TsvRowTrailer;
end
else
begin
RowLeader := MRowLeader;
ColumnSeparator := MColumnSeparator;
RowTrailer := MRowTrailer;
end;
s := RowLeader+'N';
for r := 1 to r_max do
s := s+ColumnSeparator+'r='+IntToStr(r);
s := s+RowTrailer;
Status(s);
if not UseTsv then
begin
s := '|---';
for r := 1 to r_max do
s := s+'|----';
s := s+'|';
Status(s);
end;
for N := 1 to N_max do
begin
s := RowLeader+IntToStr(N);
for r := 1 to r_max do
begin
if (N < 16*r) and ((1 shl N)*r*Int(128) < $7FFFFFFF) then
begin
try
QueryPerformanceCounter(t1);
TScrypt.HashPassword(STestPassword, N, r, 1);
t2 := ElapsedTicks(t1);
s := s+Format(ColumnSeparator+'%.1f', [t2/freq*1000]);
except
on E:EOutOfMemory do
begin
s := s+Format(ColumnSeparator+'%s', ['#mem']);
end;
end;
end
else
begin
//invalid cost
s := s+ColumnSeparator+'#N/A';
end;
end;
s := s+RowTrailer;
Status(s);
end;
end;
procedure TScryptTests.Tester_HMAC_SHA1(HMACsha1: IHmacAlgorithm);
procedure t(const Key: AnsiString; const Data: AnsiString; const ExpectedDigest: array of Byte);
var
digest: TBytes;
begin
digest := HMACsha1.HashData(Key[1], Length(Key), Data[1], Length(Data));
if (Length(ExpectedDigest) <> Length(digest)) then
raise EScryptException.CreateFmt('Scrypt self-test failed: Length failed with Key "%s" and Data "%s"',
[Key, Data]);
if not CompareMem(@ExpectedDigest, @digest[0], 20) then
raise EScryptException.CreateFmt('Scrypt self-test failed: Compare failed with Key "%s" and Data "%s"',
[Key, Data]);
end;
//var
// key: TBytes;
begin
//From RFC 2022: Test Cases for HMAC-MD5 and HMAC-SHA-1
{
test_case = 1
key = 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
key_len = 20
data = "Hi There"
data_len = 8
digest = 0xb617318655057264e28bc0b6fb378c8ef146be00
}
t(StringOfChar(AnsiChar($0b), 20), 'Hi There', [$b6, $17, $31, $86, $55, $05, $72, $64, $e2, $8b, $c0, $b6, $fb, $37, $8c, $8e, $f1, $46, $be, $00]);
{
test_case = 2
key = "Jefe"
key_len = 4
data = "what do ya want for nothing?"
data_len = 28
digest = 0xeffcdf6ae5eb2fa2d27416d5f184df9c259a7c79
}
t('Jefe', 'what do ya want for nothing?', [$ef, $fc, $df, $6a, $e5, $eb, $2f, $a2, $d2, $74, $16, $d5, $f1, $84, $df, $9c, $25, $9a, $7c, $79]);
{
test_case = 3
key = 0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
key_len = 20
data = 0xdd repeated 50 times
data_len = 50
digest = 0x125d7342b9ac11cd91a39af48aa17b4f63f175d3
}
t(StringOfChar(AnsiChar($aa), 20), StringOfChar(AnsiChar($dd), 50), [$12, $5d, $73, $42, $b9, $ac, $11, $cd, $91, $a3, $9a, $f4, $8a, $a1, $7b, $4f, $63, $f1, $75, $d3]);
{
test_case = 4
key = 0x0102030405060708090a0b0c0d0e0f10111213141516171819
key_len = 25
data = 0xcd repeated 50 times
data_len = 50
digest = 0x4c9007f4026250c6bc8414f9bf50c86c2d7235da
}
t(#$01#$02#$03#$04#$05#$06#$07#$08#$09#$0a#$0b#$0c#$0d#$0e#$0f#$10#$11#$12#$13#$14#$15#$16#$17#$18#$19,
StringOfChar(AnsiChar($cd), 50),
[$4c,$90,$07,$f4,$02,$62,$50,$c6,$bc,$84,$14,$f9,$bf,$50,$c8,$6c,$2d,$72,$35,$da]);
{
test_case = 5
key = 0x0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c
key_len = 20
data = "Test With Truncation"
data_len = 20
digest = 0x4c1a03424b55e07fe7f27be1d58bb9324a9a5a04
digest-96 = 0x4c1a03424b55e07fe7f27be1
}
t(StringOfChar(AnsiChar($0c), 20), 'Test With Truncation',
[$4c,$1a,$03,$42,$4b,$55,$e0,$7f,$e7,$f2,$7b,$e1,$d5,$8b,$b9,$32,$4a,$9a,$5a,$04]);
{
test_case = 6
key = 0xaa repeated 80 times
key_len = 80
data = "Test Using Larger Than Block-Size Key - Hash Key First"
data_len = 54
digest = 0xaa4ae5e15272d00e95705637ce8a3b55ed402112
}
t(StringOfChar(AnsiChar($aa), 80), 'Test Using Larger Than Block-Size Key - Hash Key First',
[$aa,$4a,$e5,$e1,$52,$72,$d0,$0e,$95,$70,$56,$37,$ce,$8a,$3b,$55,$ed,$40,$21,$12]);
{
test_case = 7
key = 0xaa repeated 80 times
key_len = 80
data = "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data"
data_len = 73
digest = 0xe8e99d0f45237d786d6bbaa7965c7808bbff1a91
}
t(StringOfChar(AnsiChar($aa), 80),
'Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data',
[$e8,$e9,$9d,$0f,$45,$23,$7d,$78,$6d,$6b,$ba,$a7,$96,$5c,$78,$08,$bb,$ff,$1a,$91]);
end;
procedure TScryptTests.Test_HMAC_SHA1;
var
hash: IHmacAlgorithm;
begin
hash := TScryptCracker.CreateObject('HMAC.SHA1') as IHmacAlgorithm;
Tester_HMAC_SHA1(hash);
hash := nil;
end;
procedure TScryptTests.Test_HMAC_SHA1_Cng;
var
hash: IHmacAlgorithm;
begin
hash := TScryptCracker.CreateObject('HMAC.SHA1.Cng') as IHmacAlgorithm;
Tester_HMAC_SHA1(hash);
hash := nil;
end;
procedure TScryptTests.Test_HMAC_SHA1_PurePascal;
var
hash: IHmacAlgorithm;
begin
hash := TScryptCracker.CreateObject('HMAC.SHA1.PurePascal') as IHmacAlgorithm;
Tester_HMAC_SHA1(hash);
hash := nil;
end;
procedure TScryptTests.Test_HMAC_SHA256;
var
hmac: IHmacAlgorithm;
begin
hmac := TScryptCracker.CreateObject('HMAC.SHA256') as IHmacAlgorithm;
Tester_HMAC_SHA256(hmac);
end;
procedure TScryptTests.Test_HMAC_SHA256_Cng;
var
hmac: IHmacAlgorithm;
begin
hmac := TScryptCracker.CreateObject('HMAC.SHA256.Cng') as IHmacAlgorithm;
Tester_HMAC_SHA256(hmac);
end;
procedure TScryptTests.Test_HMAC_SHA256_PurePascal;
var
hmac: IHmacAlgorithm;
begin
hmac := TScryptCracker.CreateObject('HMAC.SHA256.PurePascal') as IHmacAlgorithm;
Tester_HMAC_SHA256(hmac);
end;
procedure TScryptTests.Tester_HMAC_SHA256(HMACsha256: IHmacAlgorithm);
procedure Test(const KeyHexString: string; const DataHexString: string; const ExpectedDigestHexString: string; TruncateToBytes: Integer=0);
var
key: TBytes;
data: TBytes;
expected: TBytes;
actual: TBytes;
begin
//Deserialize the test data
key := HexToBytes(KeyHexString);
data := HexToBytes(DataHexString);
expected := HexToBytes(ExpectedDigestHexString);
actual := HMACsha256.HashData(key[0], Length(key), data[0], Length(data));
if TruncateToBytes > 0 then
actual := Copy(actual, 0, TruncateToBytes);
if (Length(expected) <> Length(actual)) then
raise EScryptException.CreateFmt('Scrypt self-test failed: Length failed with Key "%s" and Data "%s"',
[Key, Data]);
if not CompareMem(@expected[0], @actual[0], Length(expected)) then
raise EScryptException.CreateFmt('Scrypt self-test failed: Compare failed with Key "%s" and Data "%s"',
[Key, Data]);
end;
begin
{
From RFC4231
Identifiers and Test Vectors for HMAC-SHA-224, HMAC-SHA-256, HMAC-SHA-384, and HMAC-SHA-512
https://www.ietf.org/rfc/rfc4231.txt
}
//Test Case 1
Test(
{Key= } '0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', // (20 bytes)
{Data= } '4869205468657265', // ("Hi There")
{HMAC-SHA-256} 'b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7');
//Test Case 2
//Test with a key shorter than the length of the HMAC output.
Test(
{Key =} '4a656665', // ("Jefe")
{Data =} '7768617420646f2079612077616e7420666f72206e6f7468696e673f', // ("what do ya want for nothing?")
{HMAC-SHA-256} '5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843');
//Test Case 3
//Test with a combined length of key and data that is larger than 64 bytes (= block-size of SHA-224 and SHA-256).
Test(
{Key} 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', // (20 bytes)
{Data} 'dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd', // (50 bytes)
{HMAC-SHA-256} '773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe');
//Test Case 4
//Test with a combined length of key and data that is larger than 64 bytes (= block-size of SHA-224 and SHA-256).
Test(
{Key} '0102030405060708090a0b0c0d0e0f10111213141516171819', // (25 bytes)
{Data} 'cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd', // (50 bytes)
{HMAC-SHA-256} '82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b');
//Test Case 5
//Test with a truncation of output to 128 bits.
Test(
{Key} '0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c', // (20 bytes)
{Data} '546573742057697468205472756e636174696f6e', // ("Test With Truncation")
{HMAC-SHA-256} 'a3b6167473100ee06e0c796c2955552b', 16);
//Test Case 6
//Test with a key larger than 128 bytes (= block-size of SHA-384 and SHA-512).
Test(
{Key} 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'+
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'+
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'+
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', // (131 bytes)
{Data} '54657374205573696e67204c6172676572205468616e20426c6f636b2d53697a'+
'65204b6579202d2048617368204b6579204669727374', //("Test Using Larger Than Block-Size Key - Hash Key") (" First")
{HMAC-SHA-256} '60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54');
//Test Case 7
//Test with a key and data that is larger than 128 bytes (= block-size of SHA-384 and SHA-512).
Test(
{Key} 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'+
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'+
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'+
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', // (131 bytes)
{Data} '5468697320697320612074657374207573696e672061206c6172676572207468'+
'616e20626c6f636b2d73697a65206b657920616e642061206c61726765722074'+
'68616e20626c6f636b2d73697a6520646174612e20546865206b6579206e6565'+
'647320746f20626520686173686564206265666f7265206265696e6720757365'+
'642062792074686520484d414320616c676f726974686d2e', //"This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm."
{HMAC-SHA-256} '9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2');
end;
procedure TScryptTests.Tester_PBKDF2_SHA256(Pbkdf2sha256: IPBKDF2Algorithm);
procedure t(Password: UnicodeString; Salt: AnsiString; IterationCount: Integer; DerivedKeyLength: Integer;
const ExpectedDerivedKeyHexString: string);
var
expected: TBytes;
actual: TBytes; //derivedKey
begin
expected := HexToBytes(ExpectedDerivedKeyHexString);
actual := Pbkdf2sha256.GetBytes(Password, Salt[1], Length(Salt), IterationCount, DerivedKeyLength);
if (DerivedKeyLength <> Length(actual)) then
raise EScryptException.CreateFmt('Scrypt self-test failed: Derived key length (%d) wasn''t the required %d',
[Length(actual), DerivedKeyLength]);
if not CompareMem(@expected[0], @actual[0], DerivedKeyLength) then
raise EScryptException.CreateFmt('Scrypt self-test failed: Derived key was invalid for Password "%s", Salt="%s", IterationCount="%d", DerivedKeyLength=%d',
[Password, Salt, IterationCount, DerivedKeyLength]);
end;
begin
{
From http://stackoverflow.com/a/5136918/12597
}
{
Input:
P = "password" (8 octets)
S = "salt" (4 octets)
c = 1
dkLen = 32
Output:
DK = 12 0f b6 cf fc f8 b3 2c 43 e7 22 52 56 c4 f8 37 a8 65 48 c9 2c cc 35 48 08 05 98 7c b7 0b e1 7b (20 octets)
}
t('password', 'salt', 1, 32, '12 0f b6 cf fc f8 b3 2c 43 e7 22 52 56 c4 f8 37 a8 65 48 c9 2c cc 35 48 08 05 98 7c b7 0b e1 7b');
{
Input:
P = "password" (8 octets)
S = "salt" (4 octets)
c = 2
dkLen = 32
Output:
DK = ae 4d 0c 95 af 6b 46 d3 2d 0a df f9 28 f0 6d d0 2a 30 3f 8e f3 c2 51 df d6 e2 d8 5a 95 47 4c 43 (32 octets)
}
t('password', 'salt', 2, 32, 'ae 4d 0c 95 af 6b 46 d3 2d 0a df f9 28 f0 6d d0 2a 30 3f 8e f3 c2 51 df d6 e2 d8 5a 95 47 4c 43');
{
Input:
P = "password" (8 octets)
S = "salt" (4 octets)
c = 4096
dkLen = 32
Output:
DK = c5 e4 78 d5 92 88 c8 41 aa 53 0d b6 84 5c 4c 8d 96 28 93 a0 01 ce 4e 11 a4 96 38 73 aa 98 13 4a (32 octets)
}
t('password', 'salt', 4096, 20, 'c5 e4 78 d5 92 88 c8 41 aa 53 0d b6 84 5c 4c 8d 96 28 93 a0 01 ce 4e 11 a4 96 38 73 aa 98 13 4a');
{
Input:
P = "password" (8 octets)
S = "salt" (4 octets)
c = 16777216
dkLen = 32
Output:
DK = cf 81 c6 6f e8 cf c0 4d 1f 31 ec b6 5d ab 40 89 f7 f1 79 e8 9b 3b 0b cb 17 ad 10 e3 ac 6e ba 46 (32 octets)
}
//This test works, but it's 16,777,216 rounds
// t('password', 'salt', 16777216, 20, 'cf 81 c6 6f e8 cf c0 4d 1f 31 ec b6 5d ab 40 89 f7 f1 79 e8 9b 3b 0b cb 17 ad 10 e3 ac 6e ba 46');
{
Input:
P = "passwordPASSWORDpassword" (24 octets)
S = "saltSALTsaltSALTsaltSALTsaltSALTsalt" (36 octets)
c = 4096
dkLen = 40
Output:
DK = 34 8c 89 db cb d3 2b 2f 32 d8 14 b8 11 6e 84 cf 2b 17 34 7e bc 18 00 18 1c 4e 2a 1f b8 dd 53 e1 c6 35 51 8c 7d ac 47 e9 (40 octets)
}
t('passwordPASSWORDpassword', 'saltSALTsaltSALTsaltSALTsaltSALTsalt', 4096, 25,
'34 8c 89 db cb d3 2b 2f 32 d8 14 b8 11 6e 84 cf 2b 17 34 7e bc 18 00 18 1c 4e 2a 1f b8 dd 53 e1 c6 35 51 8c 7d ac 47 e9');
{
Input:
P = "pass\0word" (9 octets)
S = "sa\0lt" (5 octets)
c = 4096
dkLen = 16
Output:
DK = 89 b6 9d 05 16 f8 29 89 3c 69 62 26 65 0a 86 87 (16 octets)
}
t('pass'#0'word', 'sa'#0'lt', 4096, 16, '89 b6 9d 05 16 f8 29 89 3c 69 62 26 65 0a 86 87');
{
http://tools.ietf.org/html/draft-josefsson-scrypt-kdf-00#section-10
10. Test Vectors for PBKDF2 with HMAC-SHA-256
The test vectors below can be used to verify the PBKDF2-HMAC-SHA-256
[RFC2898] function. The password and salt strings are passed as
sequences of ASCII [ANSI.X3-4.1986] octets.
}
t('passwd', 'salt', 1, 64,
'55 ac 04 6e 56 e3 08 9f ec 16 91 c2 25 44 b6 05 f9 41 85 21 6d de 04 65 e6 8b 9d 57 c2 0d ac bc'+
'49 ca 9c cc f1 79 b6 45 99 16 64 b3 9d 77 ef 31 7c 71 b8 45 b1 e3 0b d5 09 11 20 41 d3 a1 97 83');
t('Password', 'NaCl', 80000, 64,
'4d dc d8 f6 0b 98 be 21 83 0c ee 5e f2 27 01 f9 64 1a 44 18 d0 4c 04 14 ae ff 08 87 6b 34 ab 56'+
'a1 d4 25 a1 22 58 33 54 9a db 84 1b 51 c9 b3 17 6a 27 2b de bb a1 d0 78 47 8f 62 b3 97 f3 3c 8d');
end;
procedure TScryptTests.Test_PasswordHashing;
var
password: string;
hash: string;
freq, t1, t2: Int64;
passwordRehashNeeded: Boolean;
begin
{
Test round trip of generating a hash, and then verifying it
}
if not QueryPerformanceFrequency(freq) then freq := -1;
password := 'correct horse battery staple';
if not QueryPerformanceCounter(t1) then t1 := 0;
hash := TScrypt.HashPassword(password);
if not QueryPerformanceCounter(t2) then t2 := 0;
Status('Password: "'+password+'"');
Status('Hash: "'+hash+'"');
Status(Format('Time to hash password: %.4f ms', [(t2-t1)/freq*1000]));
Self.CheckFalse(hash='');
if not QueryPerformanceCounter(t1) then t1 := 0;
Self.CheckTrue(TScrypt.CheckPassword('correct horse battery staple', hash, {out}passwordRehashNeeded));
if not QueryPerformanceCounter(t2) then t2 := 0;
Status(Format('Time to verify password: %.4f ms', [(t2-t1)/freq*1000]));
end;
procedure TScryptTests.Tester_PBKDF2_SHA1(Pbkdf: IPBKDF2Algorithm);
procedure t(Password: UnicodeString; Salt: AnsiString; IterationCount: Integer; DerivedKeyLength: Integer;
const ExpectedDerivedKey: array of byte);
var
derivedKey: TBytes; //derivedKey
t1, t2: Int64;
s: string;
begin
t1 := Self.GetTimestamp;
derivedKey := Pbkdf.GetBytes(Password, Salt[1], Length(Salt), IterationCount, DerivedKeyLength);
t2 := Self.GetTimestamp;
s := Format('%.4f ms', [(t2-t1)/FFreq*1000]);
Status(s);
if (DerivedKeyLength <> Length(derivedKey)) then
raise EScryptException.CreateFmt('Scrypt self-test failed: Derived key length (%d) wasn''t the required %d',
[Length(DerivedKey), DerivedKeyLength]);
if not CompareMem(@ExpectedDerivedKey[0], @derivedKey[0], DerivedKeyLength) then
raise EScryptException.CreateFmt('Scrypt self-test failed: Derived key was invalid for Password "%s", Salt="%s", IterationCount="%d", DerivedKeyLength=%d',
[Password, Salt, IterationCount, DerivedKeyLength]);
end;
begin
{
PKCS #5: Password-Based Key Derivation Function 2 (PBKDF2) Test Vectors
http://tools.ietf.org/html/rfc6070
Input:
P = "password" (8 octets)
S = "salt" (4 octets)
c = 1
dkLen = 20
Output:
DK = 0c 60 c8 0f 96 1f 0e 71 f3 a9 b5 24 af 60 12 06 2f e0 37 a6 (20 octets)
}
t('password', 'salt', 1, 20, [$0c,$60,$c8,$0f,$96,$1f,$0e,$71,$f3,$a9,$b5,$24,$af,$60,$12,$06,$2f,$e0,$37,$a6]);
{
Input:
P = "password" (8 octets)
S = "salt" (4 octets)
c = 2
dkLen = 20
Output:
DK = ea 6c 01 4d c7 2d 6f 8c cd 1e d9 2a ce 1d 41 f0 d8 de 89 57 (20 octets)
}
t('password', 'salt', 2, 20, [$ea,$6c,$01,$4d,$c7,$2d,$6f,$8c,$cd,$1e,$d9,$2a,$ce,$1d,$41,$f0,$d8,$de,$89,$57]);
{
Input:
P = "password" (8 octets)
S = "salt" (4 octets)
c = 4096
dkLen = 20
Output:
DK = 4b 00 79 01 b7 65 48 9a be ad 49 d9 26 f7 21 d0 65 a4 29 c1 (20 octets)
}
t('password', 'salt', 4096, 20, [$4b,$00,$79,$01,$b7,$65,$48,$9a,$be,$ad,$49,$d9,$26,$f7,$21,$d0,$65,$a4,$29,$c1]);
{
Input:
P = "password" (8 octets)
S = "salt" (4 octets)
c = 16777216
dkLen = 20
Output:
DK = ee fe 3d 61 cd 4d a4 e4 e9 94 5b 3d 6b a2 15 8c 26 34 e9 84 (20 octets)
}
//This test passes, but it's 16,777,216 rounds (2m 17s)
// t('password', 'salt', 16777216, 20, [$ee,$fe,$3d,$61,$cd,$4d,$a4,$e4,$e9,$94,$5b,$3d,$6b,$a2,$15,$8c,$26,$34,$e9,$84]);
{
Input:
P = "passwordPASSWORDpassword" (24 octets)
S = "saltSALTsaltSALTsaltSALTsaltSALTsalt" (36 octets)
c = 4096
dkLen = 25
Output:
DK = 3d 2e ec 4f e4 1c 84 9b 80 c8 d8 36 62 c0 e4 4a 8b 29 1a 96 4c f2 f0 70 38 (25 octets)
}
t('passwordPASSWORDpassword', 'saltSALTsaltSALTsaltSALTsaltSALTsalt', 4096, 25,
[$3d,$2e,$ec,$4f,$e4,$1c,$84,$9b,$80,$c8,$d8,$36,$62,$c0,$e4,$4a,$8b,$29,$1a,$96,$4c,$f2,$f0,$70,$38]);
{
Input:
P = "pass\0word" (9 octets)
S = "sa\0lt" (5 octets)
c = 4096
dkLen = 16
Output:
DK = 56 fa 6a a7 55 48 09 9d cc 37 d7 f0 34 25 e0 c3 (16 octets)
}
t('pass'#0'word', 'sa'#0'lt', 4096, 16,
[$56,$fa,$6a,$a7,$55,$48,$09,$9d,$cc,$37,$d7,$f0,$34,$25,$e0,$c3]);
end;
procedure TScryptTests.Benchmark_HMACs;
var
data: TBytes;
const
password: AnsiString = 'correct horse battery staple';
procedure Test(HmacAlgorithmName: string);
var
hmac: IHmacAlgorithm;
t1, t2: Int64;
bestTime: Int64;
i: Integer;
begin
hmac := TScryptCracker.CreateObject(HmacAlgorithmName) as IHmacAlgorithm;
bestTime := 0;
//Fastest time of 5 runs
for i := 1 to 5 do
begin
t1 := GetTimestamp;
hmac.HashData(password[1], Length(password), data[0], Length(data));
t2 := GetTimestamp;
t2 := t2-t1;
if (bestTime = 0) or (t2 < bestTime) then
bestTime := t2;
end;
Status(Format('%s %.3f MB/s', [HmacAlgorithmName, (Length(data)/1024/1024) / (bestTime/FFreq)]));
end;
begin
//generate 1 MB of sample data to HMAC
data := TScrypt.GetBytes('hash test', 'Scrypt for Delphi', 1, 1, 1, 1*1024*1024); //1 MB
Status(Format('%s %s', ['Algorithm', 'Speed (MB/s)']));
Test('HMAC.SHA1');
Test('HMAC.SHA1.PurePascal');
Test('HMAC.SHA1.csp');
Test('HMAC.SHA1.Cng');
Test('HMAC.SHA256');
Test('HMAC.SHA256.PurePascal');
Test('HMAC.SHA256.csp');
Test('HMAC.SHA256.Cng');
end;
procedure TScryptTests.Benchmark_PBKDF2s;
const
password: string = 'correct horse battery staple';
salt: AnsiString = 'sea salt';
procedure Test(HmacAlgorithmName: string);
var
db: IPBKDF2Algorithm;
t1, t2: Int64;
bestTime: Int64;
i: Integer;
begin
db := TScryptCracker.CreateObject(HmacAlgorithmName) as IPBKDF2Algorithm;
bestTime := 0;
//Fastest time of 5 runs
for i := 1 to 5 do
begin
t1 := GetTimestamp;
db.GetBytes(password, salt[1], Length(salt), 1000, 32);
t2 := GetTimestamp;
t2 := t2-t1;
if (bestTime = 0) or (t2 < bestTime) then
bestTime := t2;
end;
Status(Format('%s %.4f ms', [HmacAlgorithmName, (bestTime/FFreq*1000)]));
end;
begin
Status(Format('%s %s', ['Algorithm', 'Speed (ms)']));
Test('PBKDF2.SHA1');
Test('PBKDF2.SHA1.PurePascal');
// Test('PBKDF2.SHA1.csp');
Test('PBKDF2.SHA1.Cng');
Test('PBKDF2.SHA256');
Test('PBKDF2.SHA256.PurePascal');
// Test('PBKDF2.SHA256.csp');
Test('PBKDF2.SHA256.Cng');
end;
procedure TScryptTests.Test_Salsa208Core;
type
TLongWordArray = array[0..15] of LongWord;
PLongWordArray = ^TLongWordArray;
var
actual: TBytes;
expected: TBytes;
begin
{
https://tools.ietf.org/html/draft-josefsson-scrypt-kdf-02#section-7
7. Test Vectors for Salsa20/8 Core
Below is a sequence of octets to illustrate input and output values
for the Salsa20/8 Core. The octets are hex encoded and whitespace is
inserted for readability. The value corresponds to the first input
and output pair generated by the first scrypt test vector below.
INPUT:
7e 87 9a 21 4f 3e c9 86 7c a9 40 e6 41 71 8f 26
ba ee 55 5b 8c 61 c1 b5 0d f8 46 11 6d cd 3b 1d
ee 24 f3 19 df 9b 3d 85 14 12 1e 4b 5a c5 aa 32
76 02 1d 29 09 c7 48 29 ed eb c6 8d b8 b8 c2 5e
OUTPUT:
a4 1f 85 9c 66 08 cc 99 3b 81 ca cb 02 0c ef 05
04 4b 21 81 a2 fd 33 7d fd 7b 1c 63 96 68 2f 29
b4 39 31 68 e3 c9 e6 bc fe 6b c5 b7 a0 6d 96 ba
e4 24 cc 10 2c 91 74 5c 24 ad 67 3d c7 61 8f 81
}
actual := HexToBytes(
'7e 87 9a 21 4f 3e c9 86 7c a9 40 e6 41 71 8f 26 '+
'ba ee 55 5b 8c 61 c1 b5 0d f8 46 11 6d cd 3b 1d '+
'ee 24 f3 19 df 9b 3d 85 14 12 1e 4b 5a c5 aa 32 '+
'76 02 1d 29 09 c7 48 29 ed eb c6 8d b8 b8 c2 5e ');
TScryptCracker(FScrypt).Salsa20InPlace(actual[0]);
expected := HexToBytes(
'a4 1f 85 9c 66 08 cc 99 3b 81 ca cb 02 0c ef 05 '+
'04 4b 21 81 a2 fd 33 7d fd 7b 1c 63 96 68 2f 29 '+
'b4 39 31 68 e3 c9 e6 bc fe 6b c5 b7 a0 6d 96 ba '+
'e4 24 cc 10 2c 91 74 5c 24 ad 67 3d c7 61 8f 81 ');
Self.CheckEquals(Length(expected), Length(actual), 'Salsa20/8 array length');
Self.CheckEqualsMem(@expected[0], @actual[0], Length(expected), 'Salsa20/8 data failed');
end;
procedure TScryptTests.Test_Scrypt_PasswordFormatting;
begin
end;
procedure TScryptTests.Test_BlockMix;
var
input: TBytes;
expected: TBytes;
actual: TBytes;
begin
{
8. Test Vectors for scryptBlockMix
https://tools.ietf.org/html/draft-josefsson-scrypt-kdf-02#section-8
Below is a sequence of octets to illustrate input and output values
for scryptBlockMix. The test vector uses an r value of 1. The
octets are hex encoded and whitespace is inserted for readability.
The value corresponds to the first input and output pair generated by
the first scrypt test vector below.
INPUT
B[0] = f7 ce 0b 65 3d 2d 72 a4 10 8c f5 ab e9 12 ff dd
77 76 16 db bb 27 a7 0e 82 04 f3 ae 2d 0f 6f ad
89 f6 8f 48 11 d1 e8 7b cc 3b d7 40 0a 9f fd 29
09 4f 01 84 63 95 74 f3 9a e5 a1 31 52 17 bc d7
B[1] = 89 49 91 44 72 13 bb 22 6c 25 b5 4d a8 63 70 fb
cd 98 43 80 37 46 66 bb 8f fc b5 bf 40 c2 54 b0
67 d2 7c 51 ce 4a d5 fe d8 29 c9 0b 50 5a 57 1b
7f 4d 1c ad 6a 52 3c da 77 0e 67 bc ea af 7e 89
OUTPUT
B'[0] = a4 1f 85 9c 66 08 cc 99 3b 81 ca cb 02 0c ef 05
04 4b 21 81 a2 fd 33 7d fd 7b 1c 63 96 68 2f 29
b4 39 31 68 e3 c9 e6 bc fe 6b c5 b7 a0 6d 96 ba
e4 24 cc 10 2c 91 74 5c 24 ad 67 3d c7 61 8f 81
B'[1] = 20 ed c9 75 32 38 81 a8 05 40 f6 4c 16 2d cd 3c
21 07 7c fe 5f 8d 5f e2 b1 a4 16 8f 95 36 78 b7
7d 3b 3d 80 3b 60 e4 ab 92 09 96 e5 9b 4d 53 b6
5d 2a 22 58 77 d5 ed f5 84 2c b9 f1 4e ef e4 25
}
input := HexToBytes(
'f7 ce 0b 65 3d 2d 72 a4 10 8c f5 ab e9 12 ff dd '+
'77 76 16 db bb 27 a7 0e 82 04 f3 ae 2d 0f 6f ad '+
'89 f6 8f 48 11 d1 e8 7b cc 3b d7 40 0a 9f fd 29 '+
'09 4f 01 84 63 95 74 f3 9a e5 a1 31 52 17 bc d7 '+
'89 49 91 44 72 13 bb 22 6c 25 b5 4d a8 63 70 fb '+
'cd 98 43 80 37 46 66 bb 8f fc b5 bf 40 c2 54 b0 '+
'67 d2 7c 51 ce 4a d5 fe d8 29 c9 0b 50 5a 57 1b '+
'7f 4d 1c ad 6a 52 3c da 77 0e 67 bc ea af 7e 89 ');
expected := HexToBytes(
'a4 1f 85 9c 66 08 cc 99 3b 81 ca cb 02 0c ef 05 '+
'04 4b 21 81 a2 fd 33 7d fd 7b 1c 63 96 68 2f 29 '+
'b4 39 31 68 e3 c9 e6 bc fe 6b c5 b7 a0 6d 96 ba '+
'e4 24 cc 10 2c 91 74 5c 24 ad 67 3d c7 61 8f 81 '+
'20 ed c9 75 32 38 81 a8 05 40 f6 4c 16 2d cd 3c '+
'21 07 7c fe 5f 8d 5f e2 b1 a4 16 8f 95 36 78 b7 '+
'7d 3b 3d 80 3b 60 e4 ab 92 09 96 e5 9b 4d 53 b6 '+
'5d 2a 22 58 77 d5 ed f5 84 2c b9 f1 4e ef e4 25 ');
actual := TScryptCracker(FScrypt).BlockMix(input);
Self.CheckEquals(Length(expected), Length(actual), 'BlockMix array length');
Self.CheckEqualsMem(@expected[0], @actual[0], Length(expected), 'BlockMix data failed');
end;
procedure TScryptTests.Test_ROMix;
var
input: TBytes;
actual: TBytes;
expected: TBytes;
begin
{
9. Test Vectors for scryptROMix
https://tools.ietf.org/html/draft-josefsson-scrypt-kdf-02#section-9
Below is a sequence of octets to illustrate input and output values
for scryptROMix. The test vector uses an r value of 1 and an N value
of 16. The octets are hex encoded and whitespace is inserted for
readability. The value corresponds to the first input and output
pair generated by the first scrypt test vector below.
INPUT:
B = f7 ce 0b 65 3d 2d 72 a4 10 8c f5 ab e9 12 ff dd
77 76 16 db bb 27 a7 0e 82 04 f3 ae 2d 0f 6f ad
89 f6 8f 48 11 d1 e8 7b cc 3b d7 40 0a 9f fd 29
09 4f 01 84 63 95 74 f3 9a e5 a1 31 52 17 bc d7
89 49 91 44 72 13 bb 22 6c 25 b5 4d a8 63 70 fb
cd 98 43 80 37 46 66 bb 8f fc b5 bf 40 c2 54 b0
67 d2 7c 51 ce 4a d5 fe d8 29 c9 0b 50 5a 57 1b
7f 4d 1c ad 6a 52 3c da 77 0e 67 bc ea af 7e 89
OUTPUT:
B = 79 cc c1 93 62 9d eb ca 04 7f 0b 70 60 4b f6 b6
2c e3 dd 4a 96 26 e3 55 fa fc 61 98 e6 ea 2b 46
d5 84 13 67 3b 99 b0 29 d6 65 c3 57 60 1f b4 26
a0 b2 f4 bb a2 00 ee 9f 0a 43 d1 9b 57 1a 9c 71
ef 11 42 e6 5d 5a 26 6f dd ca 83 2c e5 9f aa 7c
ac 0b 9c f1 be 2b ff ca 30 0d 01 ee 38 76 19 c4
ae 12 fd 44 38 f2 03 a0 e4 e1 c4 7e c3 14 86 1f
4e 90 87 cb 33 39 6a 68 73 e8 f9 d2 53 9a 4b 8e
}
input := HexToBytes(
'f7 ce 0b 65 3d 2d 72 a4 10 8c f5 ab e9 12 ff dd '+
'77 76 16 db bb 27 a7 0e 82 04 f3 ae 2d 0f 6f ad '+
'89 f6 8f 48 11 d1 e8 7b cc 3b d7 40 0a 9f fd 29 '+
'09 4f 01 84 63 95 74 f3 9a e5 a1 31 52 17 bc d7 '+
'89 49 91 44 72 13 bb 22 6c 25 b5 4d a8 63 70 fb '+
'cd 98 43 80 37 46 66 bb 8f fc b5 bf 40 c2 54 b0 '+
'67 d2 7c 51 ce 4a d5 fe d8 29 c9 0b 50 5a 57 1b '+
'7f 4d 1c ad 6a 52 3c da 77 0e 67 bc ea af 7e 89 ');
expected := HexToBytes(
'79 cc c1 93 62 9d eb ca 04 7f 0b 70 60 4b f6 b6 '+
'2c e3 dd 4a 96 26 e3 55 fa fc 61 98 e6 ea 2b 46 '+
'd5 84 13 67 3b 99 b0 29 d6 65 c3 57 60 1f b4 26 '+
'a0 b2 f4 bb a2 00 ee 9f 0a 43 d1 9b 57 1a 9c 71 '+
'ef 11 42 e6 5d 5a 26 6f dd ca 83 2c e5 9f aa 7c '+
'ac 0b 9c f1 be 2b ff ca 30 0d 01 ee 38 76 19 c4 '+
'ae 12 fd 44 38 f2 03 a0 e4 e1 c4 7e c3 14 86 1f '+
'4e 90 87 cb 33 39 6a 68 73 e8 f9 d2 53 9a 4b 8e ');
actual := TScryptCracker(FScrypt).ROMix(input[0], Length(input), 4); //N=16 --> costFactor = 4 (2^4 = 16)
Self.CheckEquals(Length(expected), Length(actual), 'ROMix array length');
Self.CheckEqualsMem(@expected[0], @actual[0], Length(expected), 'ROMix data failed');
end;
procedure TScryptTests.Test_PBKDF2_SHA1;
var
db: IPBKDF2Algorithm;
begin
db := TScryptCracker.CreateObject('PBKDF2.SHA1') as IPBKDF2Algorithm;
Tester_PBKDF2_SHA1(db);
end;
procedure TScryptTests.Test_PBKDF2_SHA1_Cng;
var
db: IPBKDF2Algorithm;
begin
db := TScryptCracker.CreateObject('PBKDF2.SHA1.Cng') as IPBKDF2Algorithm;
Tester_PBKDF2_SHA1(db);
end;
procedure TScryptTests.Test_PBKDF2_SHA1_PurePascal;
var
db: IPBKDF2Algorithm;
begin
db := TScryptCracker.CreateObject('PBKDF2.SHA1.PurePascal') as IPBKDF2Algorithm;
Tester_PBKDF2_SHA1(db);
end;
procedure TScryptTests.Test_PBKDF2_SHA256;
var
db: IPBKDF2Algorithm;
begin
db := TScryptCracker.CreateObject('PBKDF2.SHA256') as IPBKDF2Algorithm;
Tester_PBKDF2_SHA256(db);
end;
procedure TScryptTests.Test_PBKDF2_SHA256_Cng;
var
db: IPBKDF2Algorithm;
begin
db := TScryptCracker.CreateObject('PBKDF2.SHA256.Cng') as IPBKDF2Algorithm;
Tester_PBKDF2_SHA256(db);
end;
procedure TScryptTests.Test_PBKDF2_SHA256_PurePascal;
var
db: IPBKDF2Algorithm;
begin
db := TScryptCracker.CreateObject('PBKDF2.SHA256.PurePascal') as IPBKDF2Algorithm;
Tester_PBKDF2_SHA256(db);
end;
procedure TScryptTests.Test_Scrypt;
var
freq: Int64;
procedure test(password: string; salt: string; CostFactor, r, p: Integer; DesiredBytes: Integer; ExpectedHexString: string);
var
expected: TBytes;
actual: TBytes;
t1, t2: Int64;
begin
//N = CPU/memory cost parameter
//p = parallelization parameter
expected := HexToBytes(ExpectedHexString);
QueryPerformanceCounter(t1);
actual := FScrypt.GetBytes(password, salt, CostFactor, r, p, DesiredBytes);
QueryPerformanceCounter(t2);
Self.Status(Format('Test "%s" duration: %.4f ms', [password, (t2-t1)/freq*1000]));
if Length(expected) <> Length(actual) then
raise EScryptException.CreateFmt('Self-test failed: actual length (%d) does not match expected (%d)', [Length(actual), Length(expected)]);
if not CompareMem(@expected[0], @actual[0], Length(expected)) then
raise EScryptException.Create('Scrypt self-test failed: data does not match');
end;
begin
{
From the official PDF (http://www.tarsnap.com/scrypt/scrypt.pdf)
Appendix B. Test vectors
For reference purposes, we provide the following test vectors for scrypt, where
the password and salt strings are passed as sequences of ASCII bytes without a
terminating NUL
}
if not QueryPerformanceFrequency(freq) then
freq := -1;
//uses 512 bytes
test('', '', {N=16=2^}4, {r=}1, {p=}1, 64,
'77 d6 57 62 38 65 7b 20 3b 19 ca 42 c1 8a 04 97 f1 6b 48 44 e3 07 4a e8 df df fa 3f ed e2 14 42'+
'fc d0 06 9d ed 09 48 f8 32 6a 75 3a 0f c8 1f 17 e8 d3 e0 fb 2e 0d 36 28 cf 35 e2 0c 38 d1 89 06');
//uses 1 MB
test('password', 'NaCl', {N=1024=2^}10, {r=}8, {p=}16, 64,
'fd ba be 1c 9d 34 72 00 78 56 e7 19 0d 01 e9 fe 7c 6a d7 cb c8 23 78 30 e7 73 76 63 4b 37 31 62'+
'2e af 30 d9 2e 22 a3 88 6f f1 09 27 9d 98 30 da c7 27 af b9 4a 83 ee 6d 83 60 cb df a2 cc 06 40');
//uses 16 MB
test('pleaseletmein', 'SodiumChloride', {N=16384=2^}14, {r=}8, {p=}1, 64,
'70 23 bd cb 3a fd 73 48 46 1c 06 cd 81 fd 38 eb fd a8 fb ba 90 4f 8e 3e a9 b5 43 f6 54 5d a1 f2'+
'd5 43 29 55 61 3f 0f cf 62 d4 97 05 24 2a 9a f9 e6 1e 85 dc 0d 65 1e 40 df cf 01 7b 45 57 58 87');
if FindCmdLineSwitch('IncludeSlowTests', ['-','/'], True) then
begin
OutputDebugString('SAMPLING ON');
//uses 1 GB
test('pleaseletmein', 'SodiumChloride', {N=1048576=2^}20, {r=}8, {p=}1, 64,
'21 01 cb 9b 6a 51 1a ae ad db be 09 cf 70 f8 81 ec 56 8d 57 4a 2f fd 4d ab e5 ee 98 20 ad aa 47'+
'8e 56 fd 8f 4b a5 d0 9f fa 1c 6d 92 7c 40 f4 c3 37 30 40 49 e8 a9 52 fb cb f4 5c 6f a7 7a 41 a4');
OutputDebugString('SAMPLING OFF');
end
else
Status('1 GB slow test skipped. Use -IncludeSlowTests');
end;
procedure TScryptTests.Test_SHA1_PurePascal;
var
sha1: IHashAlgorithm;
begin
sha1 := TScryptCracker(FScrypt).CreateObject('SHA1.PurePascal') as IHashAlgorithm;
TSHA1Tester.Test(sha1);
end;
procedure TScryptTests.Test_SHA1;
var
sha1: IHashAlgorithm;
begin
sha1 := TScryptCracker.CreateObject('SHA1') as IHashAlgorithm;
TSHA1Tester.Test(sha1);
end;
procedure TScryptTests.Test_SHA1_Cng;
var
sha1: IHashAlgorithm;
begin
sha1 := TScryptCracker(FScrypt).CreateObject('SHA1.Cng') as IHashAlgorithm;
TSHA1Tester.Test(sha1);
end;
procedure TScryptTests.Test_SHA1_Csp;
var
sha1: IHashAlgorithm;
begin
sha1 := TScryptCracker(FScrypt).CreateObject('SHA1.Csp') as IHashAlgorithm;
TSHA1Tester.Test(sha1);
end;
{$IFDEF UnitTests}
initialization
TestFramework.RegisterTest('Library/Scrypt', TScryptTests.Suite);
{$ENDIF}
end.
|
unit Form.Main;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.TabControl, FMX.Layouts, FMX.Controls.Presentation,
FMX.StdCtrls, FMX.Memo.Types, FMX.ScrollBox, FMX.Memo, FMX.ListView.Types, FMX.ListView.Appearances,
FMX.ListView.Adapters.Base, FMX.ListView,
uUniversalReceiver,
Androidapi.JNI.GraphicsContentViewText,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.Net,// or Androidapi.JNI.net.wifi (https://github.com/AndrewEfimov/Wrappers/blob/master/Androidapi.JNI.net.wifi.pas)
Androidapi.Helpers,
Androidapi.JNI,
Androidapi.JNIBridge,
System.Permissions;
type
TFormMain = class(TForm)
TabControl1: TTabControl;
Layout1: TLayout;
tiInfo: TTabItem;
tiScanResult: TTabItem;
sbGetInfo: TSpeedButton;
sbScan: TSpeedButton;
mInfo: TMemo;
lvScanResults: TListView;
Layout2: TLayout;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure sbGetInfoClick(Sender: TObject);
procedure sbScanClick(Sender: TObject);
private const
PermissionAccessFineLocation = 'android.permission.ACCESS_FINE_LOCATION';
private
FBroadcastReceiver: TBroadcastReceiver;
FWifiManager: JWifiManager;
procedure OnReceiveScanResults(context: JContext; intent: JIntent);
procedure LoadWifiInfo(Sender: TObject; const APermissions: TArray<string>;
const AGrantResults: TArray<TPermissionStatus>);
procedure StartScan(Sender: TObject; const APermissions: TArray<string>;
const AGrantResults: TArray<TPermissionStatus>);
public
{ Public declarations }
end;
var
FormMain: TFormMain;
implementation
{$R *.fmx}
{ TFormMain }
function DecToIpv4(const AValue: Cardinal): string;
begin
// LITTLE_ENDIAN
Result := Format('%d.%d.%d.%d', [AValue and $FF, (AValue shr 8) and $FF, (AValue shr 16) and $FF, AValue shr 24]);
end;
procedure TFormMain.FormCreate(Sender: TObject);
begin
FBroadcastReceiver := TBroadcastReceiver.Create;
FBroadcastReceiver.OnReceive := OnReceiveScanResults;
FBroadcastReceiver.IntentFilterAdd([TJWifiManager.JavaClass.SCAN_RESULTS_AVAILABLE_ACTION]);
FBroadcastReceiver.registerReceiver;
FWifiManager := TJWifiManager.Wrap(TAndroidHelper.context.getSystemService(TJContext.JavaClass.WIFI_SERVICE));
end;
procedure TFormMain.FormDestroy(Sender: TObject);
begin
FBroadcastReceiver.Free;
end;
procedure TFormMain.LoadWifiInfo(Sender: TObject; const APermissions: TArray<string>;
const AGrantResults: TArray<TPermissionStatus>);
var
WifiInfo: JWifiInfo;
begin
if (Length(AGrantResults) = 1) and (AGrantResults[0] = TPermissionStatus.Granted) then
begin
WifiInfo := FWifiManager.getConnectionInfo();
mInfo.Lines.Clear;
mInfo.Lines.Add('BSSID: ' + TAndroidHelper.JStringToString(WifiInfo.getBSSID));
mInfo.Lines.Add('HiddenSSID: ' + WifiInfo.getHiddenSSID.ToString);
mInfo.Lines.Add('IpAddress: ' + DecToIpv4(WifiInfo.getIpAddress));
mInfo.Lines.Add('LinkSpeed: ' + WifiInfo.getLinkSpeed.ToString + ' Mbps');
mInfo.Lines.Add('MacAddress: ' + TAndroidHelper.JStringToString(WifiInfo.getMacAddress));
mInfo.Lines.Add('NetworkId: ' + WifiInfo.getNetworkId.ToString);
mInfo.Lines.Add('Rssi: ' + WifiInfo.getRssi.ToString + ' dBm');
mInfo.Lines.Add('SSID: ' + TAndroidHelper.JStringToString(WifiInfo.getSSID));
mInfo.Lines.Add('SupplicantState: ' + TAndroidHelper.JStringToString(WifiInfo.getSupplicantState.ToString));
end;
end;
procedure TFormMain.OnReceiveScanResults(context: JContext; intent: JIntent);
var
ScanResults: JList;
I: Integer;
ScanResultsItem: JScanResult;
LItem: TListViewItem;
begin
if intent.getBooleanExtra(TJWifiManager.JavaClass.EXTRA_RESULTS_UPDATED, False) then
begin
ScanResults := FWifiManager.getScanResults();
lvScanResults.Items.Clear;
lvScanResults.BeginUpdate;
try
for I := 0 to ScanResults.size - 1 do
begin
ScanResultsItem := TJScanResult.Wrap(ScanResults.get(I));
LItem := lvScanResults.Items.Add;
LItem.Text := TAndroidHelper.JStringToString(ScanResultsItem.SSID);
end;
finally
lvScanResults.EndUpdate;
end;
end;
end;
procedure TFormMain.sbGetInfoClick(Sender: TObject);
begin
PermissionsService.RequestPermissions([PermissionAccessFineLocation], LoadWifiInfo);
end;
procedure TFormMain.sbScanClick(Sender: TObject);
begin
PermissionsService.RequestPermissions([PermissionAccessFineLocation], StartScan);
end;
procedure TFormMain.StartScan(Sender: TObject; const APermissions: TArray<string>;
const AGrantResults: TArray<TPermissionStatus>);
begin
if (Length(AGrantResults) = 1) and (AGrantResults[0] = TPermissionStatus.Granted) then
FWifiManager.StartScan();
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [FICHA_TECNICA]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit FichaTecnicaVO;
interface
uses
Data.DB,
VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils;
type
[TEntity]
[TTable('FICHA_TECNICA')]
TFichaTecnicaVO = class(TVO)
private
FID: Integer;
FID_PRODUTO: Integer;
FDESCRICAO: String;
FID_PRODUTO_FILHO: Integer;
FQUANTIDADE: Extended;
FSEQUENCIA_PRODUCAO: Integer;
FPersiste: String;
public
[TId('ID', [])]
[TGeneratedValue(sAuto)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Id: Integer read FID write FID;
[TColumn('ID_PRODUTO', 'Id Produto', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdProduto: Integer read FID_PRODUTO write FID_PRODUTO;
[TColumn('DESCRICAO', 'Descricao', 450, [ldGrid, ldLookup, ldCombobox], False)]
property Descricao: String read FDESCRICAO write FDESCRICAO;
[TColumn('ID_PRODUTO_FILHO', 'Id Produto Filho', 80, [ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdProdutoFilho: Integer read FID_PRODUTO_FILHO write FID_PRODUTO_FILHO;
[TColumn('QUANTIDADE', 'Quantidade', 152, [], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property Quantidade: Extended read FQUANTIDADE write FQUANTIDADE;
[TColumn('SEQUENCIA_PRODUCAO', '', 80, [], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property SequenciaProducao: Integer read FSEQUENCIA_PRODUCAO write FSEQUENCIA_PRODUCAO;
[TColumn('PERSISTE', 'Persiste', 60, [], True)]
property Persiste: String read FPersiste write FPersiste;
end;
implementation
initialization
Classes.RegisterClass(TFichaTecnicaVO);
finalization
Classes.UnRegisterClass(TFichaTecnicaVO);
end.
|
unit Form.Form2;
interface
uses
Winapi.Windows, Winapi.Messages,
System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
Plus.Vcl.Form;
type
TForm2 = class(TFormPlus)
GroupBox1: TGroupBox;
Label1: TLabel;
ListBox1: TListBox;
ListBox2: TListBox;
procedure FormCreate(Sender: TObject);
private
FText: string;
procedure FormReady; override;
procedure FormIdle; override;
public
constructor Create (Owner: TComponent); override;
end;
implementation
{$R *.dfm}
constructor TForm2.Create(Owner: TComponent);
begin
inherited;
FText := 'constructor Create';
end;
procedure TForm2.FormCreate(Sender: TObject);
begin
ListBox1.Clear;
ListBox1.Items.Add(FText);
ListBox1.Items.Add('FormCreate');
end;
procedure TForm2.FormIdle;
begin
ListBox2.Tag := ListBox2.Tag + 1;
ListBox2.Items.Text := ListBox2.Tag.ToString;
end;
{ TForm2 }
procedure TForm2.FormReady;
begin
ListBox1.Items.Add('FormReady');
end;
end.
|
(* Pascal *)
program problemTheMostBeautifulCity;
uses sysutils;
procedure assert( ok: boolean; err: ansistring );
begin
if ( not ok ) then
begin
writeln( err );
halt( 1 );
end;
end;
var n, k, i, j, x: longInt;
cnt, ans: array[ 1..1000000 ] of longInt;
begin
fillchar( cnt, sizeOf(cnt), 0 );
fillchar( ans, sizeOf(ans), 0 );
readln( n, k );
assert( ( n >= 1 ) and ( n <= round(1.0e+6) ), 'n violates the constraints' );
assert( ( k >= 1 ) and ( k <= round(1.0e+6) ), 'k violates the constraints' );
for i := 1 to n do
for j := 1 to n div i do
inc( cnt[i * j] );
for i := 1 to k do
begin
read( x );
assert( ( x >= 1 ) and ( x <= n ), 'the most beautiful city of traveler ' + intToStr(i) + ' violates the constraints, outside the range [1, n]' );
inc( ans[x] );
end;
for i := 1 to n do
if ( odd( cnt[i] ) ) and ( ans[i] > 0 ) then
writeln( i, ' ', ans[i] );
end. |
unit CommonConsts;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.FreeOTFE.org/
//
// -----------------------------------------------------------------------------
//
interface
const
// Homepage...
URL_HOMEPAGE = 'http://www.FreeOTFE.org/';
// Download URL...
URL_DOWNLOAD = 'http://www.FreeOTFE.org/download.html';
ENGLISH_TRANSLATION_CONTACT = 'Sarah Dean <sdean12@sdean12.org>';
resourcestring
USE_DEFAULT = 'Use default';
// "English" is required as both a const, and a resourcestring (to be included
// in the .po file)
const
CONST_LANGUAGE_ENGLISH = 'English'; // Hardcoded "English"
resourcestring
RS_LANGUAGE_ENGLISH = 'English';
implementation
END.
|
unit uTopicModel;
interface
uses uGlobals, Graphics, uSavePoint, Classes;
type
TContentFolder = (cntUnknown, cntContent, cntTask);
PSection = ^TSection;
TSection = record
topic_id: integer;
task_count: integer;
pages_count: integer;
expire: TDate;
name: string;
display_lable, short: string;
visible: boolean;
typeOf: TTopicType;
end;
TSectionList = array of TSection;
TTopic = class
private
mid: integer;
mname: string;
display_lable: string;
mMode: Tmode;
pageNo: integer;
mContentPageCount: integer;
mContentFolderType: TContentFolder;
mContentFolder: string;
msection: PSection;
mResultMask: TResultMask;
typeOf: TTopicType;
procedure doLoadPage();
procedure setMode(const Value: TMode);
procedure setPage(const Value: integer);
function getTaskCount: integer;
public
sections: TSectionList;
content: TBitmap;
OnAllTaskComplete: POnAllTaskComleteEvent;
procedure FirstPage;
procedure NextPage;
procedure PrevPage;
property Mode: TMode read mMode write setMode;
property Caption: string read display_lable write display_lable;
property ID: integer read mid;
property Name: string read mname;
property ResultMask: TResultMask read mResultMask write mResultMask;
property ContentType: TContentFolder read mContentFolderType;
property Section : PSection read mSection;
property Page: integer read PageNo write setPage;
property TaskCount: integer read getTaskCount;
property TopicType: TTopicType read typeOf;
procedure setSection(ContentType: TContentFolder; const Value: PSection);
function sectionByName(const name: string): PSection;
function sectionByID(topic_id: integer): PSection;
end;
TTopicList = class(TList)
public
procedure Free;
function getTopicByID(id: integer): TTopic;
constructor Create();
end;
implementation
uses uData, sysUtils, uOGE, XMLIntf;
var filename: string;
{ TTopicList }
constructor TTopicList.Create;
var info: string;
s: TStringStream;
i, j, scnt: integer;
item:TTopic;
root, node, sectionNodes: IXMLNode;
begin
inherited Create;
info := TOPIC_DIR + '/info.xml';
s := TStringStream.Create;
try
if not FindData(dm.DataFile, info, s) then abort;
dm.xmlDoc.LoadFromStream(s);
root := dm.xmlDoc.ChildNodes.FindNode('MODULES');
Capacity := root.ChildNodes.Count;
for i := 0 to Capacity - 1 do
begin
item := TTopic.Create;
Add(item);
node := root.ChildNodes.Get(i);
item.mid := strToInt(node.ChildNodes.FindNode('ID').Text);
item.mname := node.ChildNodes.FindNode('DIR').Text;
item.Caption := node.ChildNodes.FindNode('DISPLAY_LABEL').Text;
item.typeOf := TTopicType(strToInt(node.ChildNodes.FindNode('TYPE').Text));
sectionNodes := node.ChildNodes.FindNode('SECTIONS');
scnt := sectionNodes.ChildNodes.Count;
setLength(item.sections, scnt);
for j := 0 to scnt - 1 do
with item do
begin
node := sectionNodes.ChildNodes.Get(j);
with node.ChildNodes do
begin
sections[j].name := FindNode('DIR').Text;
sections[j].display_lable := FindNode('DISPLAY_LABEL').Text;
sections[j].topic_id := strToInt(FindNode('TOPIC_ID').Text);
sections[j].task_count := strToInt(FindNode('TASK_COUNT').Text);
sections[j].pages_count := strToInt(FindNode('PAGES_COUNT').Text);
sections[j].expire := strToDate(FindNode('FINAL').Text);
sections[j].short := FindNode('SHORT').Text;
sections[j].visible := FindNode('VISIBLE').Text = '0';
sections[j].typeOf := item.typeOf;
end;
end;
end;
finally
s.Free;
end;
end;
procedure TTopicList.Free;
var i: integer;
begin
for i := 0 to Count - 1 do freeAndNil(List[i]);
inherited Free;
end;
function TTopicList.getTopicByID(id: integer): TTopic;
var i: integer;
begin
result := nil;
for i := 0 to Count - 1 do
if(id = TTopic(Items[i]).ID) then exit(TTopic(Items[i]));
end;
{ TModule }
{
function TTopic.allTaskComplete: boolean;
begin
result := getNextFalseTask(pageNo, taskResultMask, true) = ALL_TASK_COMPLETE;
end;}
procedure TTopic.doLoadPage;
begin
filename := format('%s/%s/%s/%s/%d.jpg', [TOPIC_DIR, name, section.name, mContentFolder, pageNo]);
if assigned(content) then freeAndNil(content);
content := LoadPage(filename);
end;
procedure TTopic.FirstPage;
begin
if mode = mReTest then
begin
pageNo := getNextFalseTask(pageNo, mResultMask, true);
if pageNo = ALL_TASK_COMPLETE then
begin
mode := mNormal;
if assigned(OnAllTaskComplete) then OnAllTaskComplete();
exit;
end;
end
else pageNo := 1;
doLoadPage();
end;
function TTopic.getTaskCount: integer;
var i: Integer;
begin
result := 0;
if not assigned(sections) then exit;
for i := 0 to length(sections) - 1 do
result := result + sections[i].task_count;
end;
procedure TTopic.NextPage;
begin
if mode = mReTest then
begin
pageNo := getNextFalseTask(pageNo, mResultMask);
if pageNo = ALL_TASK_COMPLETE then
begin
mode := mNormal;
if assigned(OnAllTaskComplete) then OnAllTaskComplete();
exit;
end;
end
else inc(pageNo);
if pageNo > mContentPageCount then
begin
pageNo := mContentPageCount;
exit;
end;
doLoadPage();
end;
procedure TTopic.PrevPage;
begin
if mode = mRetest then
begin
pageNo := getPrevFalseTask(pageNo, mResultMask);
if pageNo = ALL_TASK_COMPLETE then
begin
mode := mNormal;
if assigned(OnAllTaskComplete) then OnAllTaskComplete();
exit;
end;
end
else dec(pageNo);
if (pageNo < 1) then
begin
pageNo := 1;
exit;
end;
doLoadPage();
end;
function TTopic.sectionByID(topic_id: integer): PSection;
var i: integer;
begin
result := nil;
for i := 0 to length(sections) - 1 do
if (sections[i].topic_id = topic_id) then exit(@sections[i]);
end;
function TTopic.sectionByName(const name: string): PSection;
var i: integer;
begin
result := nil;
for i := 0 to length(sections) - 1 do
if (sections[i].name = name) then exit(@sections[i]);
end;
procedure TTopic.setMode(const Value: TMode);
begin
mMode := value;
if mMode = mRetest then pageNo := 1;
end;
procedure TTopic.setPage(const Value: integer);
begin
if(value >= 1) and (value <= mContentPageCount) then
begin
pageNo := value - 1;
NextPage;
end;
end;
procedure TTopic.setSection(ContentType: TContentFolder; const Value: PSection);
begin
mMode := mNormal;
mSection := value;
mContentFolderType := ContentType;
case ContentType of
cntUnknown:begin mContentPageCount := 0; mContentFolder := ''; end;
cntContent: begin mContentPageCount := section.pages_count; mContentFolder := 'Content' end;
cntTask: begin mContentPageCount := section.task_count; mContentFolder := 'Task' end;
end;
end;
end.
|
unit fReceivables;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uReceivables, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, Data.DB,
Aurelius.Bind.Dataset, System.Actions, Vcl.ActnList, Aurelius.Criteria.Base, Entidades.Comercial;
type
TfmReceivables = class(TForm)
adsReceivables: TAureliusDataset;
adsReceivablesSelf: TAureliusEntityField;
adsReceivablesId: TIntegerField;
adsReceivablesDueDate: TDateTimeField;
adsReceivablesReceiveDate: TDateTimeField;
adsReceivablesAmount: TCurrencyField;
adsReceivablesReceived: TBooleanField;
adsReceivablesRegisterItem: TAureliusEntityField;
adsReceivablesRegisterItemPaymentTypeName: TStringField;
dsReceivables: TDataSource;
DBGrid1: TDBGrid;
cbFilter: TComboBox;
Button1: TButton;
Button2: TButton;
ActionList1: TActionList;
acReceive: TAction;
adsReceivablesRegisterItemSalePessoaNome: TStringField;
procedure Button1Click(Sender: TObject);
procedure acReceiveExecute(Sender: TObject);
procedure acReceiveUpdate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure cbFilterChange(Sender: TObject);
private
Model: IReceivables;
procedure RefreshData;
public
class procedure Start(AModel: IReceivables);
end;
implementation
{$R *.dfm}
{ TfmReceivables }
procedure TfmReceivables.acReceiveExecute(Sender: TObject);
var
DateStr: string;
D: TDateTime;
begin
DateStr := DateToStr(Date);
if InputQuery('Recebimento', 'Informe a data do recebimento:', DateStr) then
begin
D := StrToDate(DateStr);
Model.Receive(adsReceivables.Current<TReceivable>, D);
RefreshData;
end;
end;
procedure TfmReceivables.acReceiveUpdate(Sender: TObject);
begin
acReceive.Enabled := adsReceivables.Current<TReceivable> <> nil;
end;
procedure TfmReceivables.Button1Click(Sender: TObject);
begin
ModalResult := mrOk;
end;
procedure TfmReceivables.cbFilterChange(Sender: TObject);
begin
RefreshData;
end;
procedure TfmReceivables.FormShow(Sender: TObject);
begin
cbFilter.ItemIndex := 0;
cbFilterChange(nil);
end;
procedure TfmReceivables.RefreshData;
begin
adsReceivables.Close;
case cbFilter.ItemIndex of
0: adsReceivables.SetSourceCriteria(Model.FindPendingReceivables);
1: adsReceivables.SetSourceCriteria(Model.FindAllReceivables(30));
end;
adsReceivables.Open;
end;
class procedure TfmReceivables.Start(AModel: IReceivables);
var
Form: TfmReceivables;
begin
Form := TfmReceivables.Create(nil);
try
Form.Model := AModel;
Form.ShowModal;
finally
Form.Free;
end;
end;
end.
|
unit MenuEditor;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ComCtrls, RegIntf;
type
PNodeData = ^TNodeData;
TNodeData = record
Key: String;
end;
TFrm_MenuEditor = class(TForm)
tv_Menu: TTreeView;
btn_MoveUp: TSpeedButton;
btn_MoveDown: TSpeedButton;
btn_OK: TBitBtn;
btn_Cancel: TBitBtn;
procedure tv_MenuChange(Sender: TObject; Node: TTreeNode);
procedure btn_MoveUpClick(Sender: TObject);
procedure btn_MoveDownClick(Sender: TObject);
procedure tv_MenuDeletion(Sender: TObject; Node: TTreeNode);
procedure btn_OKClick(Sender: TObject);
private
Reg: IRegistry;
procedure DisMenu;
function GetTVNode(PNode: TTreeNode; const NodeText: String): TTreeNode;
procedure SaveModify;
function GetPath(Node: TTreeNode): String;
public
constructor Create(AOwner: TComponent; aReg: IRegistry); reintroduce;
end;
var
Frm_MenuEditor: TFrm_MenuEditor;
implementation
uses StdVcl, AxCtrls;
{$R *.dfm}
const MenuKey = 'SYSTEM\MENU';
{ TFrm_MenuEditor }
constructor TFrm_MenuEditor.Create(AOwner: TComponent; aReg: IRegistry);
begin
inherited Create(AOwner);
Reg := aReg;
self.tv_Menu.Items.BeginUpdate;
try
self.tv_Menu.Items.Clear;
DisMenu;
if self.tv_Menu.Items.Count > 0 then
self.tv_Menu.Items[0].Expanded := True;
finally
self.tv_Menu.Items.EndUpdate;
end;
end;
procedure TFrm_MenuEditor.DisMenu;
var i, j: Integer;
aList, vList: TStrings;
PNode, aNode: TTreeNode;
vName, vStr: WideString;
vAnsiStr, MStr: String;
NodeData: PNodeData;
begin
if Reg.OpenKey(MenuKey) then
begin
aList := TStringList.Create;
vList := TStringList.Create;
try
self.tv_Menu.Items.AddChild(nil, '菜单');
Reg.GetValueNames(aList);
for i := 0 to aList.Count - 1 do
begin
PNode := self.GetTVNode(nil, '菜单');
vName := aList[i];
if Reg.ReadString(vName, vStr) then
begin
aNode := nil;
vAnsiStr := vStr;
vList.Clear;
ExtractStrings(['\'], [], pchar(vAnsiStr), vList);
for j := 0 to vList.Count - 1 do
begin
MStr := vList[j];
aNode := self.GetTVNode(PNode, MStr);
if aNode = nil then
begin
aNode := self.tv_Menu.Items.AddChild(PNode, MStr);
//..
end;
PNode := aNode;
end;
New(NodeData);
NodeData^.Key := vName;
aNode.Data := NodeData;
end;
end;
finally
aList.Free;
vList.Free;
end;
end;
end;
function TFrm_MenuEditor.GetTVNode(PNode: TTreeNode; const NodeText: String): TTreeNode;
var i: Integer;
begin
Result := Nil;
if PNode = nil then
PNode := self.tv_Menu.TopItem;
if CompareText(PNode.Text, NodeText) = 0 then
begin
Result := PNode;
exit;
end;
for i := 0 to PNode.Count - 1 do
begin
if CompareText(PNode.Item[i].Text, NodeText) = 0 then
begin
Result := PNode.Item[i];
exit;
end;
end;
end;
procedure TFrm_MenuEditor.tv_MenuChange(Sender: TObject; Node: TTreeNode);
begin
btn_MoveUp.Enabled := not Node.IsFirstNode;
btn_MoveDown.Enabled := not Node.IsFirstNode;
end;
procedure TFrm_MenuEditor.btn_MoveUpClick(Sender: TObject);
var Node: TTreeNode;
begin
Node := self.tv_Menu.Selected;
if Node = nil then
exit;
if Node.getPrevSibling <> nil then
Node.MoveTo(Node.getPrevSibling, naInsert);
end;
procedure TFrm_MenuEditor.btn_MoveDownClick(Sender: TObject);
var Node: TTreeNode;
begin
Node := self.tv_Menu.Selected;
if Node = nil then
exit;
if Node.getNextSibling <> nil then
Node.getNextSibling.MoveTo(Node, naInsert);
end;
procedure TFrm_MenuEditor.tv_MenuDeletion(Sender: TObject;
Node: TTreeNode);
begin
if Assigned(Node.Data) then
Dispose(PNodeData(Node.Data));
end;
procedure TFrm_MenuEditor.btn_OKClick(Sender: TObject);
begin
self.SaveModify;
self.ModalResult := mrOk;
end;
procedure TFrm_MenuEditor.SaveModify;
var i: Integer;
Key, Path: String;
begin
Reg.DeleteKey(MenuKey);
if Reg.OpenKey(MenuKey, True) then
begin
for i := 0 to self.tv_Menu.Items.Count - 1 do
begin
if Assigned(self.tv_Menu.Items[i].Data) then
begin
Key := PNodeData(self.tv_Menu.Items[i].Data)^.Key;
Path := self.GetPath(self.tv_Menu.Items[i]);
Reg.WriteString(Key, Path);
end;
end;
end;
end;
function TFrm_MenuEditor.GetPath(Node: TTreeNode): String;
var PNode: TTreeNode;
Path: string;
begin
Path := Node.Text;
PNode := Node.Parent;
while not PNode.IsFirstNode do
begin
Path := PNode.Text + '\' + Path;
PNode := PNode.Parent;
end;
Result := Path;
end;
end.
|
unit u_feuille_style;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
Controls, ExtCtrls , Grids, StdCtrls, Graphics;
type
Tfeuille_style = CLASS
procedure fonte_defaut (ctrl : TControl);
procedure panel_defaut (pnl : TPanel);
procedure panel_selection (pnl : TPanel);
procedure panel_travail (pnl : TPanel);
procedure panel_bouton (pnl : TPanel);
procedure grille (grid : TStringGrid);
procedure label_titre (lbl : TLabel);
procedure label_erreur (lbl : TLabel);
procedure combo (cbo : TComboBox);
procedure memo_info (mmo : TMemo);
END;
var
style : Tfeuille_style;
implementation
// fonte par défaut
procedure Tfeuille_style.fonte_defaut (ctrl : TControl);
begin
ctrl.Font.Name := 'Calibri';
ctrl.Font.Size := 11;
ctrl.Font.Color := $00000000;
end;
// panel par défaut
procedure Tfeuille_style.panel_defaut (pnl : TPanel);
begin
pnl.Color := $00EBEBEB;
pnl.BorderStyle := bsNone;
pnl.BevelOuter := bvNone;
pnl.Alignment := taLeftJustify;
fonte_defaut(pnl);
end;
// panel sélection (fil d'Ariane, titre, ...)
procedure Tfeuille_style.panel_selection (pnl : TPanel);
begin
panel_defaut(pnl);
pnl.Color := $00505050;
pnl.Font.Color := $00FFFFFF;
end;
// panel zone de travail
procedure Tfeuille_style.panel_travail (pnl : TPanel);
begin
panel_defaut(pnl);
pnl.Color := $00FFFFFF;
pnl.Alignment := taCenter;
end;
// panel aspect bouton et comportement bouton
procedure Tfeuille_style.panel_bouton (pnl : TPanel);
begin
panel_defaut(pnl);
pnl.BorderStyle := bsSingle;
end;
procedure Tfeuille_style.grille (grid : TStringGrid);
begin
fonte_defaut (grid);
grid.Options := [goFixedHorzLine, goRowSelect, goColSizing, goSmoothScroll];
grid.BorderStyle := bsNone;
grid.Flat := true;
grid.FixedColor := $00EBEBEB;
grid.AlternateColor := $00EBEBEB;
grid.SelectedColor := $00505050;
grid.RowCount := 1;
grid.ColumnClickSorts := true;
end;
procedure Tfeuille_style.label_titre (lbl : TLabel);
begin
fonte_defaut (lbl);
lbl.color := $005B5B5B;
lbl.font.color := $00FFFFFF;
lbl.font.style := [fsBold];
end;
procedure Tfeuille_style.label_erreur (lbl : TLabel);
begin
fonte_defaut (lbl);
lbl.font.size := lbl.font.size -1;
lbl.transparent := true;
lbl.font.color := $000000FF;
lbl.font.style := [fsItalic];
end;
procedure Tfeuille_style.combo (cbo : TComboBox);
begin
fonte_defaut (cbo);
cbo.color := $00FFFFFF;
cbo.Style := csOwnerDrawFixed;
cbo.sorted := true;
cbo.AutoComplete := true;
end;
procedure Tfeuille_style.memo_info (mmo : TMemo);
begin
fonte_defaut (mmo);
mmo.BorderStyle := bsNone;
mmo.ReadOnly := True;
mmo.TabStop := False;
end;
end.
|
unit Reader;
interface
uses SysUtils, Generics.Collections, BinaryBitmap, ReadResult, DecodeHintType;
type
/// <summary>
/// Implementations of this interface can decode an image of a barcode in some format into
/// the String it encodes. For example, <see cref="ZXing.QrCode.QRCodeReader" /> can
/// decode a QR code. The decoder may optionally receive hints from the caller which may help
/// it decode more quickly or accurately.
///
/// See <see cref="MultiFormatReader" />, which attempts to determine what barcode
/// format is present within the image as well, and then decodes it accordingly.
/// </summary>
/// <author>Sean Owen</author>s
/// <author>dswitkin@google.com (Daniel Switkin)</author>
IReader = interface
/// <summary>
/// Locates and decodes a barcode in some format within an image.
/// </summary>
/// <param name="image">image of barcode to decode</param>
/// <returns>String which the barcode encodes</returns>
function Decode(image: TBinaryBitmap): TReadResult; overload;
/// <summary> Locates and decodes a barcode in some format within an image. This method also accepts
/// hints, each possibly associated to some data, which may help the implementation decode.
/// </summary>
/// <param name="image">image of barcode to decode</param>
/// <param name="hints">passed as a <see cref="IDictionary{TKey, TValue}" /> from <see cref="DecodeHintType" />
/// to arbitrary data. The
/// meaning of the data depends upon the hint type. The implementation may or may not do
/// anything with these hints.
/// </param>
/// <returns>String which the barcode encodes</returns>
function Decode(image: TBinaryBitmap;
hints: TDictionary<TDecodeHintType, TObject>): TReadResult; overload;
/// <summary>
/// Resets any internal state the implementation has after a decode, to prepare it
/// for reuse.
/// </summary>
procedure Reset();
end;
implementation
end.
|
unit Work.Table.History;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Generics.Collections, Vcl.Grids,
HGM.Controls.VirtualTable, SQLLang, SQLiteTable3, Work.DB;
type
TTableHistory = class;
THistoryAction = (haAdd, haChange, haDelete);
TItemHistory = class
private
FModifed:Boolean;
FOwner:TTableHistory;
FEmpty:Boolean;
public
ID:Integer;
Action:THistoryAction;
TableName:string;
RecordID:Integer;
Desc:string;
Date:TDateTime;
property Modifed:Boolean read FModifed write FModifed;
property Empty:Boolean read FEmpty write FEmpty;
procedure Update;
procedure GetBack;
constructor Create(AOwner:TTableHistory);
end;
TTableHistory = class(TTableData<TItemHistory>)
const TableName = 'History';
const fnID = 'hyID';
const fnAction = 'hyAction';
const fnTableName = 'hyTableName';
const fnRecordID = 'hyRecordID';
const fnDesc = 'hyDesc';
const fnDate = 'hyDate';
private
FDB:TDatabaseCore;
FFilter:THistoryAction;
FUseFilter:Boolean;
FOrderBy: string;
FOrderByDESC:Boolean;
public
procedure Load;
procedure Save;
procedure GetBack(Index:Integer); overload;
procedure GetBack(Item:TItemHistory); overload;
procedure Update(Index:Integer); overload;
procedure Update(Item:TItemHistory); overload;
procedure Delete(Item:TItemHistory); overload;
procedure Delete(Index:Integer); overload;
procedure Clear; override;
function Add(AAction:THistoryAction; ATableName:string; ARecordID:Integer; ADesc:string):Integer; overload;
property Filter:THistoryAction read FFilter write FFilter;
property UseFilter:Boolean read FUseFilter write FUseFilter;
property LoadOrderBy:string read FOrderBy write FOrderBy;
property LoadOrderByDESC:Boolean read FOrderByDESC write FOrderByDESC;
constructor Create(ADB:TDatabaseCore); overload;
property DatabaseCore:TDatabaseCore read FDB write FDB;
end;
implementation
uses Work.Table.Customers;
{ TTableHistory }
function TTableHistory.Add(AAction: THistoryAction; ATableName: string; ARecordID: Integer; ADesc: string): Integer;
var Item:TItemHistory;
begin
Item:=TItemHistory.Create(Self);
Item.Action:=AAction;
Item.RecordID:=ARecordID;
Item.TableName:=ATableName;
Item.Desc:=ADesc;
Item.Update;
Insert(0, Item);
Result:=0;
end;
procedure TTableHistory.Clear;
var i:Integer;
begin
for i:= 0 to Count-1 do Items[i].Free;
inherited;
end;
constructor TTableHistory.Create(ADB:TDatabaseCore);
begin
inherited Create;
FOrderBy:=fnDate;
FOrderByDESC:=True;
FDB:=ADB;
if not FDB.SQL.TableExists(TableName) then
with SQL.CreateTable(TableName) do
begin
AddField(fnID, ftInteger, True, True);
AddField(fnAction, ftInteger);
AddField(fnTableName, ftString);
AddField(fnRecordID, ftInteger);
AddField(fnDesc, ftString);
AddField(fnDate, ftDateTime);
FDB.SQL.ExecSQL(GetSQL);
EndCreate;
end;
end;
procedure TTableHistory.Delete(Item: TItemHistory);
begin
with SQL.Delete(TableName) do
begin
WhereFieldEqual(fnID, Item.ID);
FDB.SQL.ExecSQL(GetSQL);
EndCreate;
end;
end;
procedure TTableHistory.Delete(Index: Integer);
begin
Delete(Items[Index]);
inherited;
end;
procedure TTableHistory.GetBack(Item: TItemHistory);
var RTable:TSQLiteTable;
begin
with SQL.Select(TableName) do
begin
AddField(fnAction);
AddField(fnTableName);
AddField(fnRecordID);
AddField(fnDesc);
AddField(fnDate);
WhereFieldEqual(fnID, Item.ID);
RTable:=FDB.SQL.GetTable(GetSQL);
if RTable.Count > 0 then
begin
Item.Action:=THistoryAction(RTable.FieldAsInteger(0));
Item.TableName:=RTable.FieldAsString(1);
Item.RecordID:=RTable.FieldAsInteger(2);
Item.Desc:=RTable.FieldAsString(3);
Item.Date:=RTable.FieldAsDateTime(4);
Item.Modifed:=False;
Item.Empty:=False;
end;
RTable.Free;
EndCreate;
end;
end;
procedure TTableHistory.Load;
var RTable:TSQLiteTable;
Item:TItemHistory;
begin
BeginUpdate;
Clear;
try
with SQL.Select(TableName) do
begin
AddField(fnID);
AddField(fnAction);
AddField(fnTableName);
AddField(fnRecordID);
AddField(fnDesc);
AddField(fnDate);
if UseFilter then WhereFieldEqual(fnAction, Ord(FFilter));
OrderBy(FOrderBy, FOrderByDESC);
WhereField(fnDate, '>', Now - 30);
RTable:=FDB.SQL.GetTable(GetSQL);
while not RTable.EOF do
begin
Item:=TItemHistory.Create(Self);
Item.ID:=RTable.FieldAsInteger(0);
Item.Action:=THistoryAction(RTable.FieldAsInteger(1));
Item.TableName:=RTable.FieldAsString(2);
Item.RecordID:=RTable.FieldAsInteger(3);
Item.Desc:=RTable.FieldAsString(4);
Item.Date:=RTable.FieldAsDateTime(5);
Item.Modifed:=False;
Item.Empty:=False;
Add(Item);
RTable.Next;
end;
RTable.Free;
EndCreate;
end;
finally
EndUpdate;
end;
end;
procedure TTableHistory.GetBack(Index: Integer);
begin
GetBack(Items[Index]);
end;
procedure TTableHistory.Save;
var i:Integer;
begin
for i:= 0 to Count-1 do if Items[i].Modifed then Update(i);
end;
procedure TTableHistory.Update(Item: TItemHistory);
var Res:Integer;
begin
with SQL.Select(TableName) do
begin
AddField(fnID);
WhereFieldEqual(fnID, Item.ID);
Res:=FDB.SQL.GetTableValue(GetSQL);
EndCreate;
end;
if Res < 0 then
begin
with SQL.InsertInto(TableName) do
begin
AddValue(fnAction, Ord(Item.Action));
AddValue(fnTableName, Item.TableName);
AddValue(fnRecordID, Item.RecordID);
AddValueAsParam(fnDesc, '?', True);
AddValue(fnDate, Item.Date);
FDB.SQL.ExecSQL(GetSQL, [PAnsiChar(AnsiString(Item.Desc))]);
Item.ID:=FDB.SQL.GetLastInsertRowID;
EndCreate;
end;
end
else
begin
with SQL.Update(TableName) do
begin
AddValue(fnAction, Ord(Item.Action));
AddValue(fnTableName, Item.TableName);
AddValue(fnRecordID, Item.RecordID);
AddValueAsParam(fnDesc, '?', True);
AddValue(fnDate, Item.Date);
WhereFieldEqual(fnID, Item.ID);
FDB.SQL.ExecSQL(GetSQL, [PAnsiChar(AnsiString(Item.Desc))]);
EndCreate;
end;
end;
Item.Modifed:=False;
Item.Empty:=False;
end;
procedure TTableHistory.Update(Index: Integer);
begin
Update(Items[Index]);
end;
{ TItemHistory }
constructor TItemHistory.Create(AOwner:TTableHistory);
begin
inherited Create;
FModifed:=True;
FEmpty:=True;
FOwner:=AOwner;
Date:=Now;
end;
procedure TItemHistory.GetBack;
begin
FOwner.GetBack(Self);
end;
procedure TItemHistory.Update;
begin
FOwner.Update(Self);
end;
end.
|
// Banco de dados
unit uEstadoModel;
interface
uses
System.SysUtils, FireDAC.Comp.Client, Data.DB, FireDAC.DApt, FireDAC.Comp.UI,
FireDAC.Comp.DataSet, System.Generics.Collections,
uEstadoDto, uClassSingletonConexao;
type
TEstadoModel = class
private
oQueryListarEstados: TFDQuery;
public
function Inserir(var AEstado: TEstadoDto): Boolean;
function Alterar(var AEstado: TEstadoDto): Boolean;
function VerificarExcluir(AId: integer): Boolean;
function Deletar(const AIDUF: integer): Boolean;
function ADDListaHash(var oEstado: TObjectDictionary<string,
TEstadoDto>): Boolean;
function BuscarID: integer;
function Ler(var AEstado: TEstadoDto): Boolean;
procedure ListarEstados(var DsEstado: TDataSource);
function VerificarUF(AUF: String; out AId: integer): Boolean;
function Pesquisar(ANome: String): Boolean;
constructor Create;
destructor Destroy; override;
end;
implementation
{ TEstadoModel }
function TEstadoModel.ADDListaHash(var oEstado
: TObjectDictionary<string, TEstadoDto>): Boolean;
var
oEstadoDTO: TEstadoDto;
oQuery: TFDQuery;
begin
Result := False;
oQuery := TFDQuery.Create(nil);
try
oQuery.Connection := TSingletonConexao.GetInstancia;
oQuery.Open('select * from uf');
if (not(oQuery.IsEmpty)) then
begin
oQuery.First;
while (not(oQuery.Eof)) do
begin
// Instancia do objeto
oEstadoDTO := TEstadoDto.Create;
// Atribui os valores
oEstadoDTO.IdUF := oQuery.FieldByName('idUf').AsInteger;
oEstadoDTO.UF := oQuery.FieldByName('UF').AsString;
oEstadoDTO.Nome := oQuery.FieldByName('nome').AsString;
// Adiciona o objeto na lista hash
oEstado.Add(oEstadoDTO.Nome, oEstadoDTO);
// Vai para o próximo registro
oQuery.Next;
end;
Result := True;
end;
finally
if Assigned(oQuery) then
FreeAndNil(oQuery);
end;
end;
function TEstadoModel.Alterar(var AEstado: TEstadoDto): Boolean;
var
sSql: String;
begin
sSql := 'update UF' + ' set UF = ' + QuotedStr(AEstado.UF) +
' , Nome = ' + QuotedStr(AEstado.Nome) + ' where idUF = ' +
IntToStr(AEstado.IdUF);
Result := TSingletonConexao.GetInstancia.ExecSQL(sSql) > 0;
end;
function TEstadoModel.BuscarID: integer;
var
oQuery: TFDQuery;
begin
Result := 1;
oQuery := TFDQuery.Create(nil);
try
oQuery.Connection := TSingletonConexao.GetInstancia;
oQuery.Open('select max(IdUF) as ID' + ' from UF');
if (not(oQuery.IsEmpty)) then
Result := oQuery.FieldByName('ID').AsInteger + 1;
finally
if Assigned(oQuery) then
FreeAndNil(oQuery);
end;
end;
constructor TEstadoModel.Create;
begin
oQueryListarEstados := TFDQuery.Create(nil);
end;
function TEstadoModel.Deletar(const AIDUF: integer): Boolean;
begin
Result := TSingletonConexao.GetInstancia.ExecSQL
('delete from uf where iduf = ' + IntToStr(AIDUF)) > 0;
end;
destructor TEstadoModel.Destroy;
begin
oQueryListarEstados.Close;
if Assigned(oQueryListarEstados) then
FreeAndNil(oQueryListarEstados);
inherited;
end;
function TEstadoModel.Inserir(var AEstado: TEstadoDto): Boolean;
var
sSql: String;
begin
sSql := 'insert into uf (idUF, Nome, UF) values (' + IntToStr(AEstado.IdUF) +
', ' + QuotedStr(AEstado.Nome) + ', ' + QuotedStr(AEstado.UF) + ')';
Result := TSingletonConexao.GetInstancia.ExecSQL(sSql) > 0;
end;
function TEstadoModel.Ler(var AEstado: TEstadoDto): Boolean;
var
oQuery: TFDQuery;
begin
Result := False;
oQuery := TFDQuery.Create(nil);
try
oQuery.Connection := TSingletonConexao.GetInstancia;
oQuery.Open('select iduf, Nome, uf from uf where UF = ' +
QuotedStr(AEstado.UF));
if (not(oQuery.IsEmpty)) then
begin
AEstado.IdUF := oQuery.FieldByName('iduf').AsInteger;
AEstado.Nome := oQuery.FieldByName('Nome').AsString;
Result := True;
end;
finally
if Assigned(oQuery) then
FreeAndNil(oQuery);
end;
end;
procedure TEstadoModel.ListarEstados(var DsEstado: TDataSource);
begin
oQueryListarEstados.Connection := TSingletonConexao.GetInstancia;
oQueryListarEstados.Open('select iduf, Nome, uf from uf');
DsEstado.DataSet := oQueryListarEstados;
end;
function TEstadoModel.Pesquisar(ANome: String): Boolean;
begin
oQueryListarEstados.Open('select iduf, Nome, uf from uf WHERE Nome LIKE "%' +
ANome + '%"');
if (not(oQueryListarEstados.IsEmpty)) then
begin
Result := True;
end
else
begin
Result := False;
oQueryListarEstados.Open('select iduf, Nome, uf from uf');
end;
end;
function TEstadoModel.VerificarExcluir(AId: integer): Boolean;
var
oQuery: TFDQuery;
begin
oQuery := TFDQuery.Create(nil);
try
oQuery.Connection := TSingletonConexao.GetInstancia;
oQuery.Open('select idMunicipio from municipio where municipio_iduf = ' +
IntToStr(AId));
if (oQuery.IsEmpty) then
Result := True
else
Result := False;
finally
if Assigned(oQuery) then
FreeAndNil(oQuery);
end;
end;
function TEstadoModel.VerificarUF(AUF: String; out AId: integer): Boolean;
var
oQuery: TFDQuery;
begin
oQuery := TFDQuery.Create(nil);
try
oQuery.Connection := TSingletonConexao.GetInstancia;
oQuery.Open('select iduf from uf where UF = ' + QuotedStr(AUF));
if (not(oQuery.IsEmpty)) then
begin
AId := oQuery.FieldByName('iduf').AsInteger;
Result := True;
end
else
Result := False;
finally
if Assigned(oQuery) then
FreeAndNil(oQuery);
end;
end;
end.
|
unit CRCoreTransferFullReportForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Mask, ToolEdit;
type
TfrmCoreTransferFullReport = class(TForm)
pnlButtons: TPanel;
btnOK: TButton;
btnCancel: TButton;
gbxParameters: TGroupBox;
chbxUseCurrentWells: TCheckBox;
chbxSaveFiles: TCheckBox;
edtReportPath: TDirectoryEdit;
private
function GetUseFilterWells: boolean;
function GetSaveResult: boolean;
function GetSavingPath: string;
{ Private declarations }
public
{ Public declarations }
property UseFilterWells: boolean read GetUseFilterWells;
property SaveResult: boolean read GetSaveResult;
property SavingPath: string read GetSavingPath;
end;
var
frmCoreTransferFullReport: TfrmCoreTransferFullReport;
implementation
{$R *.dfm}
{ TfrmCoreTransferFullReport }
function TfrmCoreTransferFullReport.GetSaveResult: boolean;
begin
result := chbxSaveFiles.Checked;
end;
function TfrmCoreTransferFullReport.GetSavingPath: string;
begin
Result := edtReportPath.Text;
end;
function TfrmCoreTransferFullReport.GetUseFilterWells: boolean;
begin
Result := chbxUseCurrentWells.Checked;
end;
end.
|
PROGRAM PrintGutenTag(INPUT, OUTPUT);
BEGIN {PrintGutenTag}
WRITELN('GUTEN TAG')
END. {PrintGutenTag}
|
unit UProcesoCaptura;
interface
uses
Windows, Sysutils, StrUtils, IOUtils, classes, DB, DBClient, ZDataset,
UDAOCaptura, UFolioCaptura,URegistroCaptura, UFtpGestor, UFtpImagen, Ucliente, UDMAplicacion;
type
TProcesoCaptura = class
private
FDatosCaptura : TRegistroCaptura;
FDatosCliente : TCliente;
FDatosFolio : TFolioCaptura;
FDatosAsociados : TDataSource;
FDatosMTIANI : TDataSource;
FFondos : TDataSource;
FTiposIdentificacion : TDataSource;
{METODOS PROPIOS}
public
qr:TZQuery;
{CONSTRUCTORES}
constructor Create;
destructor Destroy;
{PROPIEDADES}
property DatosCaptura : TRegistroCaptura read FDatosCaptura;
property DatosCliente : TCliente read FDatosCliente;
property DatosFolio : TFolioCaptura read FDatosFolio;
property Fondos : TDataSource read FFondos;
property TiposIdentificacion : TDataSource read FTiposIdentificacion;
property DatosAsociados : TDataSource read FDatosAsociados;
property DatosMTIANI : TDataSource read FDatosMTIANI;
Procedure DescargarImagen;
Procedure EliminarAsociacion(p_IdenFoid: Int64);
Procedure GuardarDatoPlanilla;
Procedure GuardarRegistroCaptura;
Procedure MarcarFolioNoCapturable;
function ObtenerDatosAsociados(p_IdenFoli: Int64): TDataSource;
function ObtenerDatosANI (p_DescTipoIden: string; p_numedocu: string;
p_primnomb:string; p_primapel:string): TDataSource;
function ObtenerDatosMTI(p_identipo: variant; p_numedocu: string;
p_primnomb:string; p_primapel:string): TDataSource;
Procedure ObtenerFolioCaptura (p_CodiFoli: string);
Procedure ObtenerFondos;
Procedure ObtenerTiposIdentificacion;
Procedure RefrescarAsociados;
Procedure RegistrarNovedadSinCaptura;
Procedure TerminarGuardarFolio(p_ObseNove: string);
Procedure VerificarVersion(p_NombModu: string; p_VersModu: string; p_VeriRuta: Boolean);
end;
implementation
Uses
UCapturaDemanda;
var
DAOCaptura: TDAOCaptura;
ListArch : TSearchRec;
Procedure TProcesoCaptura.DescargarImagen;
var
ConexFTP : TFtpGestor;
CarpFtpp : string;
CarpLoca : string;
DatosFTP : TFtpImagen;
begin
try
DatosFTP := TFtpImagen.Create;
ConexFTP := TFtpGestor.Create(DatosFTP.HostFtpImg,DatosFTP.UsuarioFtpImg,
DatosFTP.PasswordFtpImg,DatosFTP.PuertoFtpImg);
ConexFTP.ConectarFTP;
FDatosFolio.ImagenLocal := FDatosCliente.RutaCaptura + FDatosFolio.NombreImagen;
if TDirectory.Exists(FDatosCliente.RutaCaptura) then
TDirectory.Delete(FDatosCliente.RutaCaptura,TRUE);
TDirectory.CreateDirectory(FDatosCliente.RutaCaptura);
ConexFTP.BajarArchivo(DatosFTP.CarpetaRaizFtpImg+FDatosFolio.RutaFtp,FDatosFolio.NombreImagen,
FDatosCliente.RutaCaptura );
ConexFTP.DesconectarFTP;
ConexFTP.Free;
DatosFTP.Free;
except
on e:exception do
raise Exception.Create('No es posible Descargar la Imagen [' + FDatosFolio.NombreImagen
+ '] en el equipo local.' + #10#13 + '* ' + e.Message);
end;
end;
Procedure TProcesoCaptura.EliminarAsociacion(p_IdenFoid: Int64);
begin
try
with DAOCaptura do
begin
IniciarTransaccion;
EliminarDatosAsociacion(p_IdenFoid, FDatosFolio.IdFolio, FDatosFolio.IdCarpeta,
FDatosFolio.IdDatoPlanilla);
RefrescarAsociados;
FinalizarTransaccion;
end;
except
on e:exception do
begin
DAOCaptura.CancelarTransaccion;
raise Exception.Create('No es posible eliminar la persona solicitada de la Imagen ['
+ FDatosFolio.NombreImagen + '].'
+ #10#13 + '* ' + e.Message)
end;
end;
end;
Procedure TProcesoCaptura.GuardarDatoPlanilla;
begin
try
with DAOCaptura do
begin
IniciarTransaccion;
AgregarDatosPanilla(StrToInt(FDatosFolio.IdDatoPlanilla), FDatosFolio.IdFondo,
FDatosFolio.FechaNomina, FDatosFolio.PeriodoCotizacion,
FDatosFolio.FechaPagoBanco);
FinalizarTransaccion;
end;
except
on e:exception do
begin
DAOCaptura.CancelarTransaccion;
raise Exception.Create('No es posible Guardar el Cambio soliciatdo.'
+ #10#13 + '* ' + e.Message);
end;
end;
end;
Procedure TProcesoCaptura.GuardarRegistroCaptura;
begin
try
with DAOCaptura do
begin
IniciarTransaccion;
if (FDatosCaptura.DescripcionFuenteIdentificacion = 'MTI-BASEDATOS') or
(FDatosCaptura.DescripcionFuenteIdentificacion = 'MTI-CAPTURA') then
FDatosCaptura.IdIdentificacion:=
AgregarNuevaIdentificacion(FDatosCaptura.DescripcionTipoIdentificacion,
FDatosCaptura.DescripcionFuenteIdentificacion,
FDatosCaptura.NumeroDocumento, FDatosCaptura.PrimerNombre,
FDatosCaptura.SegundoNombre, FDatosCaptura.PrimerApellido,
FDatosCaptura.SegundoApellido);
AgregarIdentificacionFolio(FDatosCaptura.IdFolio, FDatosCaptura.IdIdentificacion,
FDatosCaptura.Observacion,FDatosCaptura.DescripcionTipoIdentificacion,
FDatosCaptura.NumeroDocumento);
RefrescarAsociados;
FinalizarTransaccion;
end;
except
on e:exception do
begin
DAOCaptura.CancelarTransaccion;
raise Exception.Create('No es posible Guardar el Registro de la Captura.'
+ #10#13 + '* ' + e.Message);
end;
end;
end;
Procedure TProcesoCaptura.MarcarFolioNoCapturable;
begin
try
with DAOCaptura do
begin
IniciarTransaccion;
RegistrarMarcaFolio(FDatosFolio.IdFolio);
EliminarBloqueoFolioNoCapturable(FDatosFolio.IdFolio);
CambiarEstadoCarpeta(FDatosFolio.IdCarpeta);
FinalizarTransaccion;
end;
except
on e:exception do
begin
DAOCaptura.CancelarTransaccion;
raise Exception.Create('No es posible registrar la Marca NO-CAPTURABLE EN la Imagen ['
+ FDatosFolio.NombreImagen + '].'
+ #10#13 + '* ' + e.Message)
end;
end;
end;
function TProcesoCaptura.ObtenerDatosANI (p_DescTipoIden: string; p_numedocu: string;
p_primnomb:string; p_primapel:string): TDataSource;
begin
FDatosMTIANI:= DAOCaptura.ConsultarDatosANI(p_DescTipoIden,p_numedocu, p_primnomb,
p_primapel);
end;
function TProcesoCaptura.ObtenerDatosAsociados(p_IdenFoli: Int64): TDataSource;
begin
FDatosASociados:= DAOCaptura.ConsultarDatosAsociados(p_IdenFoli);
end;
function TProcesoCaptura.ObtenerDatosMTI (p_identipo: variant; p_numedocu: string;
p_primnomb:string; p_primapel:string): TDataSource;
begin
FDatosMTIANI:= DAOCaptura.ConsultarDatosMTI(p_identipo, p_numedocu, p_primnomb,p_primapel);
end;
Procedure TProcesoCaptura.ObtenerFolioCaptura (p_CodiFoli: string);
begin
FDatosFolio:= DAOCaptura.AsignarFolio('CAPTURA',p_CodiFoli,ParamStr(1));
end;
Procedure TProcesoCaptura.ObtenerFondos;
begin
FFondos:= DAOCaptura.ConsultarFondos;
end;
Procedure TProcesoCaptura.ObtenerTiposIdentificacion;
begin
FTiposIdentificacion:= DAOCaptura.ConsultarTiposIdentificacion;
end;
Procedure TProcesoCaptura.RefrescarAsociados;
var
bm:TBookmark;
begin
bm:= FDatosAsociados.DataSet.GetBookmark;
FDatosAsociados.DataSet.Refresh;
if FDatosAsociados.DataSet.BookmarkValid(bm) then
FDatosAsociados.DataSet.GotoBookmark(bm)
else
FDatosAsociados.DataSet.Last;
end;
Procedure TProcesoCaptura.RegistrarNovedadSinCaptura;
begin
try
with DAOCaptura do
begin
IniciarTransaccion;
AgregarNovedadFolio(FDatosFolio.IdFolio, FDatosFolio.IdTarea, FDatosCaptura.Observacion,'R');
{SE VERIFICA SI ES EL PRIMER REGISTRO AGREAGADO PARA REGISTRAR LOS DATOS DE LA PLANILLA}
{
if (FDatosAsociados.DataSet.RecordCount = 0) and (FDatosFolio.NovedadesFolio.Count = 0) then
AgregarDatosPanilla(FDatosCaptura.IdFolio,FDatosFolio.TipoPlanilla,
FDatosFolio.IdFondo, FDatosFolio.FechaNomina,
FDatosFolio.PeriodoCotizacion, FDatosFolio.FechaPagoBanco);
}
FDatosFolio.NovedadesFolio.Add(FDatosCaptura.Observacion);
FinalizarTransaccion;
end;
except
on e:exception do
begin
DAOCaptura.CancelarTransaccion;
raise Exception.Create('No es posible registrar la Novedad del Registro del Folio ['
+ FDatosFolio.NombreImagen + '].'
+ #10#13 + '* ' + e.Message);
end;
end;
end;
Procedure TProcesoCaptura.TerminarGuardarFolio(p_ObseNove: string);
begin
try
with DAOCaptura do
begin
IniciarTransaccion;
if p_ObseNove <> '' then
AgregarNovedadFolio(FDatosFolio.IdFolio, FDatosFolio.IdTarea, p_ObseNove, 'F');
DesbloquearFolio(FDatosFolio.IdFolio, 'CAPTURA');
CambiarEstadoCarpeta(FDatosFolio.IdCarpeta);
FinalizarTransaccion;
end;
except
on e:exception do
begin
DAOCaptura.CancelarTransaccion;
if p_ObseNove <> '' then
raise Exception.Create('No es posible registrar la Novedad de la Imagen ['
+ FDatosFolio.NombreImagen + '].'
+ #10#13 + '* ' + e.Message)
else
raise Exception.Create('No es posible Terminar y Guardar el Folio ['
+ FDatosFolio.NombreImagen + '].'
+ #10#13 + '* ' + e.Message);
end;
end;
end;
Procedure TProcesoCaptura.VerificarVersion(p_NombModu: string;p_VersModu: string; p_VeriRuta: Boolean);
begin
DMAplicacion.VerificarAplicacion(p_NombModu,p_VersModu, 'CAPTURA POR DEMANDA',p_VeriRuta);
end;
{$REGION 'CONSTRUTOR AND DESTRUCTOR'}
constructor TProcesoCaptura.Create;
begin
try
DAOCaptura := TDAOCaptura.create;
FDatosFolio := TFolioCaptura.Create;
FDatosCliente := TCliente.create;
FDatosCaptura := TRegistroCaptura.Create;
FTiposIdentificacion:= TDataSource.create(nil);
FDatosAsociados := TDataSource.create(nil);
FDatosCliente.ConfigurarCliente;
except
on e:Exception do
raise Exception.Create('No es posible Inicializar Componentes. '
+ #10#13 + '* ' + e.Message);
end;
end;
destructor TProcesoCaptura.Destroy;
begin
DAOCaptura.Free;
FDatosFolio.Free;
FDatosCliente.Free;
FDatosCaptura.Free;
FTiposIdentificacion.Free;
FDatosAsociados.free;
end;
{$ENDREGION}
{$REGION 'GETTERS AND SETTERS'}
{$ENDREGION}
end.
|
(*
@created(2019-12-27)
@author(J.Delauney (BeanzMaster))
Historique : @br
@unorderedList(
@item(27/12/2019 : Creation )
)
--------------------------------------------------------------------------------@br
------------------------------------------------------------------------------
Description : Simulation d'un shader GLSL
Code source de référence de Wouter Van Nifterick
https://www.shadertoy.com/view/4sXGRn
------------------------------------------------------------------------------
@bold(Notes :)
Quelques liens :
@unorderedList(
@item(http://www.shadertoy.com)
@item(http://glslsandbox.com)
)
------------------------------------------------------------------------------@br
@bold(Credits :)
@unorderedList(
@item(J.Delauney (BeanzMaster))
@item(https://github.com/WouterVanNifterick/delphi-shader)
)
------------------------------------------------------------------------------@br
LICENCE : GPL/MPL
@br
------------------------------------------------------------------------------
*==============================================================================*)
unit BZSoftwareShader_ReliefTunnel;
//==============================================================================
{$mode objfpc}{$H+}
{$i ..\..\..\bzscene_options.inc}
//------------------------
{$ALIGN 16}
{$CODEALIGN CONSTMIN=16}
{$CODEALIGN LOCALMIN=16}
{$CODEALIGN VARMIN=16}
//------------------------
//==============================================================================
interface
uses
Classes, SysUtils,
BZClasses, BZMath, BZVectorMath, BZRayMarchMath,
BZColors, BZGraphic, BZBitmap,
BZCadencer, BZCustomShader;
Type
{ TBZSoftShader_GroundAndDistortPhongSphere }
TBZSoftShader_ReliefTunnel = Class(TBZCustomSoftwareShader)
protected
public
Constructor Create; override;
Destructor Destroy; override;
function Clone : TBZCustomSoftwareShader; override;
function ShadePixelFloat:TBZColorVector; override;
end;
implementation
{ TBZSoftShader_GroundAndDistortPhongSphere }
Constructor TBZSoftShader_ReliefTunnel.Create;
begin
inherited Create;
end;
Destructor TBZSoftShader_ReliefTunnel.Destroy;
begin
inherited Destroy;
end;
function TBZSoftShader_ReliefTunnel.Clone : TBZCustomSoftwareShader;
begin
Result := TBZSoftShader_ReliefTunnel.Create;
Result.Assign(Self);
end;
function TBZSoftShader_ReliefTunnel.ShadePixelFloat : TBZColorVector;
//vec2 p = (-iResolution.xy + 2.0*fragCoord)/iResolution.y;
//
//p *= 0.75;
//
//float a = atan( p.y, p.x );
//float r = sqrt( dot(p,p) );
//
//a += sin(0.5*r-0.5*iTime );
//
//float h = 0.5 + 0.5*cos(9.0*a);
//
//float s = smoothstep(0.4,0.5,h);
//
//vec2 uv;
//uv.x = iTime + 1.0/(r + .1*s);
//uv.y = 3.0*a/3.1416;
//
//vec3 col = texture( iChannel0, uv ).xyz;
//
//float ao = smoothstep(0.0,0.3,h)-smoothstep(0.5,1.0,h);
//col *= 1.0 - 0.6*ao*r;
//col *= r;
//
//fragColor = vec4( col, 1.0 );
function ComputePixel(Coord:TBZVector2f; aTime:Single) : TBZColorVector;
var
{$CODEALIGN RECORDMIN=16}
p, uv: TBZVector2f;
Col : TBZColorVector;
{$CODEALIGN RECORDMIN=4}
a, r, s, w, ao,t: Double;
begin
//p.x := -1 + 2 * gl_FragCoord.x / Resolution.x;
//p.y := -1 + 2 * gl_FragCoord.y / Resolution.y;
p := (Coord * InvResolution) * 2.0 - 1.0;
p.x := p.x * 1.33333;
r := Sqrt(p.DotProduct(p));
a := arctan2(p.y, p.x) + 0.5 *
Sin(0.5 * r - 0.5 * aTime);
s := 0.5 + 0.5 * Cos(7 * a);
ao := s;
s := smoothstep(0, 1, s);
if System.abs(s)<0.0001 then s := 0;
// s := clamp(s,0.0001,1);
t := (r + 0.2 * s);
// Woute van Nifterick, 2013:
// sometimes at the end of the tunnel, t gets rounded to 0,
// because the tunnel is basically infinite. It's usually a single pixel.
// We can safely paint that black.
if t<0.001 then Col.Create(0,0,0,0);
uv.x := iTime + 1 / t;
uv.y := 3 * a / cPi;
w := (0.5 + 0.5 * s) * r * r;
col := texture2D(iChannel0, uv);
ao := smoothstep(0.0, 0.4, ao) -
smoothstep(0.4, 0.7, ao);
ao := 1 - 0.5 * ao * r;
Col := Col * w;
Result := Col * ao;
end;
begin
Result := ComputePixel(FragCoords, iTime);
end;
end.
|
{
DocuGes - Gestion Documental
Autor: Fco. Javier Perez Vidal <developer at f-javier dot es>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
}
unit documentos;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, sqldb, db, FileUtil, LResources, Forms, Controls, Graphics,
Dialogs, StdCtrls, ExtCtrls, Buttons, DbCtrls, DBGrids, DOS, LCLType,
ZDataset;
type
{ TfDocumentos }
TfDocumentos = class(TForm)
dbeDescripcion: TDBEdit;
DBNavigator1: TDBNavigator;
dsTipos: TDatasource;
dbeID: TDBEdit;
dbeDocumento: TDBEdit;
dbeFecha: TDBEdit;
dblcFormato: TDBLookupComboBox;
dbmDetalle: TDBMemo;
dsDocumentos: TDatasource;
dbgGrupos: TDBGrid;
dbgDocumentos: TDBGrid;
dbgSubGrupos: TDBGrid;
dsGrupos: TDatasource;
dsSubGrupos: TDatasource;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
OpenDialog1: TOpenDialog;
Panel1: TPanel;
Panel2: TPanel;
sbSalir: TSpeedButton;
sbVisualizar: TSpeedButton;
sbDocumento: TSpeedButton;
ZDocumentosDESCRIPCION: TStringField;
ZDocumentosDETALLE: TBlobField;
ZDocumentosDOCUMENTO: TStringField;
ZDocumentosFECHA: TDateField;
ZDocumentosFORMATO_ID: TLongintField;
ZDocumentosID_DOCUMENTO: TLongintField;
ZDocumentosSUBGRUPO_ID: TLongintField;
ZGrupos: TZQuery;
ZGruposID_GRUPO: TLongintField;
ZGruposNOMBRE: TStringField;
ZDocumentos: TZQuery;
ZTipos: TZQuery;
ZSubGrupos: TZQuery;
ZSubGruposGRUPO_ID: TLongintField;
ZSubGruposID_SUBGRUPO: TLongintField;
ZSubGruposNOMBRE: TStringField;
ZTiposID_TIPO: TLongintField;
ZTiposNOMBRE: TStringField;
ZTiposVISOR: TStringField;
procedure DBNavigator1Click(Sender: TObject; Button: TDBNavButtonType);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure sbDocumentoClick(Sender: TObject);
procedure sbSalirClick(Sender: TObject);
procedure sbVisualizarClick(Sender: TObject);
function NoExisteDirectorio(Directorio:String):Boolean;
procedure ZDocumentosBeforeDelete(DataSet: TDataSet);
procedure ZDocumentosBeforeInsert(DataSet: TDataSet);
procedure ZDocumentosNewRecord(DataSet: TDataSet);
private
{ private declarations }
public
{ public declarations }
end;
var
fDocumentos: TfDocumentos;
Separador:string;
implementation
{ TfDocumentos }
uses funciones, recursostexto, datos;
procedure TfDocumentos.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
if dsDocumentos.State in dsEDitModes then begin // No es posible Salir si está en modo Edición
ShowMessage(rsConfirmarCambios);
Abort;
end;
ZGrupos.Active:=False;
ZSubGrupos.Active:=False;
ZTipos.active:=false;
ZDocumentos.active:=false;
CloseAction:=caFree;
end;
procedure TfDocumentos.DBNavigator1Click(Sender: TObject;
Button: TDBNavButtonType);
begin
if button=nbInsert then dbeFecha.SetFocus;
end;
procedure TfDocumentos.FormCreate(Sender: TObject);
begin
{$IFDEF LINUX}
Separador:='/';
{$ELSE}
Separador:='\';
{$ENDIF}
if BaseNoConectada then Abort;
try
ZGrupos.Active:=True;
ZSubGrupos.Active:=True;
ZTipos.Active:=True;
ZDocumentos.Active:=True;
except
ShowMessage(rsNoExisteBase);
end;
end;
procedure TfDocumentos.sbDocumentoClick(Sender: TObject);
var
dir_destino, dir_verifica, arch_destino: string;
posicion: integer;
begin
if not(dsDocumentos.State in dsEditModes) then begin
ShowMessage(rsNoModoEdicion);
Abort;
end;
if (ZDocumentosID_DOCUMENTO.AsInteger=0) then begin
ShowMessage(rsNoInsertaDocumento);
Abort;
end;
// Se comprueba si existe la carpeta DOCUMENTOS/ dentro de la del programa
dir_verifica:=DirectorioDocumentos;
if NoExisteDirectorio (dir_verifica) then abort;
// Proceso para insertar el documento dentro de su ubicación definitiva
// El destino del documento está determinado por el ID del documento
// Ajustado a 3 niveles de directorios y el documento en sí.
// Ejemplo: El documento 1.pdf estará en 'documentos/00/00/00/01.pdf'
dir_destino:=ZDocumentosID_DOCUMENTO.AsString;
dir_destino:=funciones.LFill(dir_destino,8,'0'); // Ajustamos a 8 caracteres
// Verificación del directorio del primer nivel. Si no existe, lo creamos
dir_verifica:= DirectorioDocumentos+Separador+copy(dir_destino,1,2);
if NoExisteDirectorio (dir_verifica) then abort;
// Verificación del directorio del segundo nivel. Si no existe, lo creamos
dir_verifica:= dir_verifica+Separador+copy(dir_destino,3,2);
if NoExisteDirectorio (dir_verifica) then abort;
// Verificación del directorio del tercer nivel. Si no existe, lo creamos
dir_verifica:= dir_verifica+Separador+copy(dir_destino,5,2);
if NoExisteDirectorio (dir_verifica) then abort;
if OpenDialog1.FileName ='' then OpenDialog1.FileName :=DirectorioAplicacion;
if OpenDialog1.Execute then begin
arch_destino:=dir_verifica+Separador+funciones.LFill(ZDocumentosID_DOCUMENTO.AsString,2,'0')+copy(OpenDialog1.FileName,length(OpenDialog1.FileName)-3,4);
CopyFile(OpenDialog1.FileName,arch_destino);
posicion:=Pos(DirectorioAplicacion,arch_destino);
ZDocumentos.edit;
delete(arch_destino,1,posicion+length(DirectorioAplicacion)-1);
ZDocumentosDOCUMENTO.Value:=arch_destino;
// end else begin
// ZDocumentosDOCUMENTO.Value:='';
end;
end;
procedure TfDocumentos.sbSalirClick(Sender: TObject);
begin
Self.Close;
end;
procedure TfDocumentos.sbVisualizarClick(Sender: TObject);
begin
Exec(ZTiposVISOR.AsString,DirectorioAplicacion+ZDocumentosDOCUMENTO.AsString);
end;
function TfDocumentos.NoExisteDirectorio(Directorio: String): Boolean;
begin
result:=false;
if not DirectoryExists(Directorio) then
if not createdir(Directorio) then begin
result:=true;
ShowMessage(rsNoCreaDirectorio);
end;
end;
procedure TfDocumentos.ZDocumentosBeforeDelete(DataSet: TDataSet);
begin
if Pregunta(rsBorrar) = IDNO then Abort;
end;
procedure TfDocumentos.ZDocumentosBeforeInsert(DataSet: TDataSet);
begin
if ZSubGruposID_SUBGRUPO.AsInteger = 0 then begin
ShowMessage(rsNoInsertaDocumentoGrupo);
abort;
end;
end;
procedure TfDocumentos.ZDocumentosNewRecord(DataSet: TDataSet);
begin
ZDocumentosFECHA.Value := date();
ZDocumentosSUBGRUPO_ID.Value := ZSubGruposID_SUBGRUPO.AsInteger;
end;
initialization
{$I documentos.lrs}
end.
|
unit uPessoaServiceTest;
interface
uses
System.SysUtils,
DUnitX.TestFramework,
Delphi.Mocks,
uPessoa,
uPessoaService,
uPessoaService.Impl,
uPessoaRepository,
uPessoaRepository.impl;
type
[TestFixture]
TPessoaServiceTest = class(TObject)
private
function getPessoa: TPessoa;
public
[Test]
procedure TestSalvarPessoa;
[Test]
procedure TestSalvarPessoaDateBirthNotSpecified;
[Test]
procedure TestSalvarPessoaUnderAge;
[Test]
procedure TestSalvarPessoaNameEmpty;
[Test]
procedure TestSalvarPessoaDataBaseError;
[Test]
procedure TestSalvarPessoaException;
end;
implementation
uses
System.Math,
System.DateUtils,
Data.DB;
{ TPessoaServiceTest }
procedure TPessoaServiceTest.TestSalvarPessoa;
var
vPessoaService: IPessoaService;
vPessoa: TPessoa;
vMock: TMock<IPessoaRepository>;
begin
vMock := TMock<IPessoaRepository>.Create;
vMock.Setup.WillReturnDefault('PersistirDados',True);
vPessoaService := TPessoaService.Create(vMock.Instance);
vPessoa := Self.getPessoa;
Assert.IsTrue(vPessoaService.Salvar(vPessoa));
end;
procedure TPessoaServiceTest.TestSalvarPessoaDataBaseError;
var
vPessoaService: IPessoaService;
vPessoa: TPessoa;
vMock: TMock<IPessoaRepository>;
begin
vMock := TMock<IPessoaRepository>.Create;
vMock.Setup.WillRaise('PersistirDados',EDatabaseError);
vPessoaService := TPessoaService.Create(vMock.Instance);
vPessoa := Self.getPessoa;
Assert.WillRaiseWithMessage(
procedure
begin
vPessoaService.Salvar(vPessoa);
end,
EArgumentException
);
end;
procedure TPessoaServiceTest.TestSalvarPessoaDateBirthNotSpecified;
var
vPessoaService: IPessoaService;
vPessoa: TPessoa;
vMock: TMock<IPessoaRepository>;
begin
vMock := TMock<IPessoaRepository>.Create;
vMock.Setup.WillReturnDefault('PersistirDados',False);
vPessoaService := TPessoaService.Create(vMock.Instance);
vPessoa := Self.getPessoa;
vPessoa.DataNascimento := ZeroValue;
Assert.WillRaiseWithMessage(
procedure
begin
vPessoaService.Salvar(vPessoa);
end,
Exception,
'A Data de nascimento não foi informada'
);
end;
procedure TPessoaServiceTest.TestSalvarPessoaException;
var
vPessoaService: IPessoaService;
vPessoa: TPessoa;
vMock: TMock<IPessoaRepository>;
begin
vMock := TMock<IPessoaRepository>.Create;
vMock.Setup.WillRaise('PersistirDados',Exception);
vPessoaService := TPessoaService.Create(vMock.Instance);
vPessoa := Self.getPessoa;
Assert.WillRaiseWithMessage(
procedure
begin
vPessoaService.Salvar(vPessoa);
end,
Exception
);
end;
procedure TPessoaServiceTest.TestSalvarPessoaNameEmpty;
var
vPessoaService: IPessoaService;
vPessoa: TPessoa;
vMock: TMock<IPessoaRepository>;
begin
vMock := TMock<IPessoaRepository>.Create;
vMock.Setup.WillReturnDefault('PersistirDados',False);
vPessoaService := TPessoaService.Create(vMock.Instance);
vPessoa := Self.getPessoa;
vPessoa.Nome := EmptyStr;
Assert.WillRaiseWithMessage(
procedure
begin
vPessoaService.Salvar(vPessoa);
end,
Exception,
'O nome não foi informado'
);
end;
procedure TPessoaServiceTest.TestSalvarPessoaUnderAge;
var
vPessoaService: IPessoaService;
vPessoa: TPessoa;
vMock: TMock<IPessoaRepository>;
begin
vMock := TMock<IPessoaRepository>.Create;
vMock.Setup.WillReturnDefault('PersistirDados',False);
vPessoaService := TPessoaService.Create(vMock.Instance);
vPessoa := Self.getPessoa;
vPessoa.DataNascimento := IncYear(Now,-10);
Assert.WillRaiseWithMessage(
procedure
begin
vPessoaService.Salvar(vPessoa);
end,
Exception,
'Menor de idade não pode ser cadastrado'
);
end;
function TPessoaServiceTest.getPessoa: TPessoa;
begin
Result := TPessoa.Create;
Result.ID := TGuid.NewGuid;
Result.Nome := 'Messias Bueno';
Result.DataNascimento := StrToDate('25/03/1991');
Result.EstadoCivil := ecCasado;
end;
initialization
TDUnitX.RegisterTestFixture(TPessoaServiceTest);
end.
|
unit Casbin.Functions.KeyMatch2;
interface
/// <summary>
/// Determines whether key1 matches the pattern of key2
/// (as in REST paths)
/// key2 can contain '*'
/// eg. '/foo/bar' matches '/foo/*'
/// '/resource1' matches '/:resource'
/// </summary>
function KeyMatch2 (const aArgs: array of string): Boolean;
implementation
uses
System.RegularExpressions,
SysUtils;
function KeyMatch2 (const aArgs: array of string): Boolean;
var
key2: string;
regExp : TRegEx;
match : TMatch;
begin
if Length(aArgs)<>2 then
raise Exception.Create('Wrong number of arguments in KeyMatch2');
key2:=StringReplace(aArgs[1], '/*', '/.*', [rfReplaceAll]);
while Pos('/:', key2, low(string))<>0 do
begin
key2:=TRegEx.Replace(key2, '(.*):[^/]+(.*)', '$1[^/]+$2');
key2:='^'+key2+'$';
end;
regExp:=TRegEx.Create(key2);
match := regExp.Match(aArgs[0]);
Result:= match.Success;
end;
end.
|
unit sEdit;
{$I sDefs.inc}
{.$DEFINE LOGGED}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs{$IFNDEF DELPHI5}, Types{$ENDIF},
{$IFDEF TNTUNICODE}TntControls, TntActnList, TntStdCtrls, TntClasses, {$ENDIF}
StdCtrls, sCommonData, sConst, sDefaults{$IFDEF LOGGED}, sDebugMsgs{$ENDIF};
type
{$IFDEF TNTUNICODE}
TsEdit = class(TTntEdit)
{$ELSE}
TsEdit = class(TEdit)
{$ENDIF}
{$IFNDEF NOTFORHELP}
private
FCommonData: TsCtrlSkinData;
FDisabledKind: TsDisabledKind;
FBoundLabel: TsBoundLabel;
procedure SetDisabledKind(const Value: TsDisabledKind);
protected
procedure PaintBorder;
procedure PrepareCache; virtual;
procedure PaintText; virtual;
procedure OurPaintHandler(aDC : hdc = 0);
public
procedure AfterConstruction; override;
constructor Create(AOwner: TComponent); override;
procedure CreateParams(var Params: TCreateParams); override;
destructor Destroy; override;
procedure Loaded; override;
procedure WndProc (var Message: TMessage); override;
published
property Align;
{$ENDIF} // NOTFORHELP
property DisabledKind : TsDisabledKind read FDisabledKind write SetDisabledKind default DefDisabledKind;
property SkinData : TsCtrlSkinData read FCommonData write FCommonData;
property BoundLabel : TsBoundLabel read FBoundLabel write FBoundLabel;
end;
implementation
uses sStyleSimply, sMaskData, sVCLUtils, sMessages, sGraphUtils, sAlphaGraph, acntUtils, sSKinProps, sSkinManager;
{ TsEdit }
procedure TsEdit.AfterConstruction;
begin
inherited AfterConstruction;
FCommonData.Loaded;
end;
constructor TsEdit.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCommonData := TsCtrlSkinData.Create(Self, {$IFDEF DYNAMICCACHE} False {$ELSE} True {$ENDIF});
FCommonData.COC := COC_TsEdit;
FDisabledKind := DefDisabledKind;
FBoundLabel := TsBoundLabel.Create(Self, FCommonData);
end;
destructor TsEdit.Destroy;
begin
FreeAndNil(FBoundLabel);
if Assigned(FCommonData) then FreeAndNil(FCommonData);
inherited Destroy;
end;
procedure TsEdit.Loaded;
begin
inherited Loaded;
FCommonData.Loaded;
end;
procedure TsEdit.OurPaintHandler(aDC : hdc = 0);
var
DC, SavedDC : hdc;
PS : TPaintStruct;
begin
if not InAnimationProcess then BeginPaint(Handle, PS);
SavedDC := 0;
if aDC = 0 then begin
DC := GetWindowDC(Handle);
SavedDC := SaveDC(DC);
end
else DC := aDC;
FCommonData.Updating := FCommonData.Updating;
try
if not FCommonData.Updating then begin
FCommonData.BGChanged := FCommonData.BGChanged or FCommonData.HalfVisible or GetBoolMsg(Parent, AC_GETHALFVISIBLE);
FCommonData.HalfVisible := not RectInRect(Parent.ClientRect, BoundsRect);
if FCommonData.BGChanged and not FCommonData.UrgentPainting then PrepareCache;
UpdateCorners(FCommonData, 0);
BitBlt(DC, 0, 0, Width, Height, FCommonData.FCacheBmp.Canvas.Handle, 0, 0, SRCCOPY);
end;
finally
if aDC = 0 then begin
RestoreDC(DC, SavedDC);
ReleaseDC(Handle, DC);
end;
if not InAnimationProcess then EndPaint(Handle, PS);
end;
end;
procedure TsEdit.PrepareCache;
begin
InitCacheBmp(SkinData);
PaintItem(FCommonData, GetParentCache(SkinData), True, integer(ControlIsActive(FCommonData)), Rect(0, 0, Width, Height), Point(Left, top), FCommonData.FCacheBmp, False);
PaintText;
if not Enabled then BmpDisabledKind(FCommonData.FCacheBmp, FDisabledKind, Parent, GetParentCache(FCommonData), Point(Left, Top));
FCommonData.BGChanged := False;
end;
procedure TsEdit.PaintBorder;
var
DC, SavedDC: HDC;
BordWidth : integer;
begin
if InAnimationProcess then exit;
FCommonData.Updating := FCommonData.Updating;
if SkinData.Updating then Exit;
DC := GetWindowDC(Handle);
SavedDC := SaveDC(DC);
try
if FCommonData.BGChanged then PrepareCache;
BordWidth := integer(BorderStyle <> bsNone) * (1 + integer(Ctl3d));
{$IFDEF DELPHI7UP}
if BordWidth = 0 then begin
if BevelInner <> bvNone then inc(BordWidth);
if BevelOuter <> bvNone then inc(BordWidth);
end;
{$ENDIF}
UpdateCorners(FCommonData, 0);
BitBltBorder(DC, 0, 0, Width, Height, FCommonData.FCacheBmp.Canvas.Handle, 0, 0, BordWidth);
{$IFDEF DYNAMICCACHE}
if Assigned(FCommonData.FCacheBmp) then FreeAndNil(FCommonData.FCacheBmp);
{$ENDIF}
finally
RestoreDC(DC, SavedDC);
ReleaseDC(Handle, DC);
end;
end;
procedure TsEdit.PaintText;
var
R : TRect;
s : acString;
i : integer;
BordWidth : integer;
Flags : Cardinal;
pc : acChar;
begin
FCommonData.FCacheBMP.Canvas.Font.Assign(Font);
if BorderStyle <> bsNone then BordWidth := 1 + integer(Ctl3D) else BordWidth := 0;
BordWidth := BordWidth {$IFDEF DELPHI7UP} + integer(BevelKind <> bkNone) * (integer(BevelOuter <> bvNone) + integer(BevelInner <> bvNone)) {$ENDIF};
Flags := DT_TOP or DT_NOPREFIX or DT_SINGLELINE;
R := Rect(BordWidth + 1, BordWidth + 1, Width - BordWidth, Height - BordWidth);
if PasswordChar <> #0 then begin
{$IFDEF D2009}
if PasswordChar = '*' then pc := #9679 else
{$ENDIF}
pc := PasswordChar;
for i := 1 to Length(Text) do s := s + pc;
end
else s := Text;
acWriteTextEx(FCommonData.FCacheBMP.Canvas, PacChar(s), True, R, Flags {$IFDEF D2009}or GetStringFlags(Self, Alignment) and not DT_VCENTER{$ENDIF}, FCommonData, ControlIsActive(FCommonData));
end;
procedure TsEdit.SetDisabledKind(const Value: TsDisabledKind);
begin
if FDisabledKind <> Value then begin
FDisabledKind := Value;
FCommonData.Invalidate;
end;
end;
procedure TsEdit.WndProc(var Message: TMessage);
var
DC : hdc;
bw : integer;
PS: TPaintStruct;
begin
{$IFDEF LOGGED}
AddToLog(Message);
{$ENDIF}
if Message.Msg = SM_ALPHACMD then case Message.WParamHi of
AC_CTRLHANDLED : begin Message.Result := 1; Exit end;
AC_GETAPPLICATION : begin Message.Result := longint(Application); Exit end;
AC_REMOVESKIN : if LongWord(Message.LParam) = LongWord(SkinData.SkinManager) then begin
CommonWndProc(Message, FCommonData);
exit
end;
AC_REFRESH : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin
CommonWndProc(Message, FCommonData);
if not InAnimationProcess and HandleAllocated and Visible then RedrawWindow(Handle, nil, 0, RDW_INVALIDATE or RDW_ERASE or RDW_FRAME);
exit
end;
AC_SETNEWSKIN : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin
CommonWndProc(Message, FCommonData);
exit
end;
AC_CHILDCHANGED : begin
Message.LParam := 0; // Internal buttons not required in the repainting
Exit;
end;
AC_GETCONTROLCOLOR : if not FCommonData.Skinned then begin
Message.Result := ColorToRGB(Color);
Exit
end;
end;
if not ControlIsReady(Self) or not FCommonData.Skinned then inherited else begin
case Message.Msg of
WM_ERASEBKGND, CN_DRAWITEM : begin
if InAnimationProcess then exit;
SkinData.FUpdating := SkinData.Updating;
if SkinData.FUpdating then Exit;
if Enabled then inherited;
Exit;
end;
WM_NCPAINT : begin
if not InAnimationProcess then PaintBorder;
Exit;
end;
WM_PAINT : begin
FCommonData.FUpdating := FCommonData.Updating;
if InAnimationProcess or FCommonData.FUpdating then begin // Exit if parent is not ready yet
BeginPaint(Handle, PS);
EndPaint(Handle, PS);
Exit;
end;
{ if ControlIsActive(FCommonData) then begin
if SkinData.SkinManager.gd[SkinData.SkinIndex].States > 1
then C := FCommonData.SkinManager.gd[FCommonData.SkinIndex].HotColor
else C := FCommonData.SkinManager.gd[FCommonData.SkinIndex].Color;
C :=
if not FCommonData.CustomColor and (Color <> FCommonData.SkinManager.gd[FCommonData.SkinIndex].HotColor) then Color := FCommonData.SkinManager.gd[FCommonData.SkinIndex].HotColor;
if not FCommonData.CustomFont and (Font.Color <> FCommonData.SkinManager.gd[FCommonData.SkinIndex].HotFontColor[1]) then Font.Color := FCommonData.SkinManager.gd[FCommonData.SkinIndex].HotFontColor[1];
end
else begin
if not FCommonData.CustomColor and (Color <> FCommonData.SkinManager.gd[FCommonData.SkinIndex].Color) then Color := FCommonData.SkinManager.gd[FCommonData.SkinIndex].Color;
if not FCommonData.CustomFont and (Font.Color <> FCommonData.SkinManager.gd[FCommonData.SkinIndex].FontColor[1]) then Font.Color := FCommonData.SkinManager.gd[FCommonData.SkinIndex].FontColor[1];
end;
}
if Enabled then inherited else OurPaintHandler(TWMPaint(Message).DC);
exit;
end;
WM_PRINT : begin
SkinData.Updating := False;
DC := TWMPaint(Message).DC;
PrepareCache;
UpdateCorners(SkinData, 0);
try
bw := integer(BorderStyle <> bsNone) * (1 + integer(Ctl3d));
BitBltBorder(DC, 0, 0, SkinData.FCacheBmp.Width, SkinData.FCacheBmp.Height, SkinData.FCacheBmp.Canvas.Handle, 0, 0, bw);
OurPaintHandler(DC);
MoveWindowOrg(DC, bw, bw);
IntersectClipRect(DC, 0, 0, SkinData.FCacheBmp.Width - 2 * bw, SkinData.FCacheBmp.Height - 2 * bw);
finally
end;
end;
CM_COLORCHANGED: if FCommonData.CustomColor then FCommonData.BGChanged := True;
end;
if CommonWndProc(Message, FCommonData) then Exit;
inherited;
if Message.Msg = SM_ALPHACMD then case Message.WParamHi of
AC_ENDPARENTUPDATE : if FCommonData.Updating then begin
FCommonData.Updating := False;
Repaint;
SendMessage(Handle, WM_NCPAINT, 0, 0);
end;
end
else case Message.Msg of
WM_KILLFOCUS, CM_EXIT: begin
FCommonData.FFocused := False;
FCommonData.FMouseAbove := False;
FCommonData.BGChanged := True;
if Visible then Repaint;
end;
WM_SETTEXT, CM_TEXTCHANGED, CM_VISIBLECHANGED, CM_ENABLEDCHANGED, WM_SETFONT : if not (csLoading in ComponentState) and not InAnimationProcess then begin
FCommonData.Invalidate;
SendMessage(Handle, WM_NCPAINT, 0, 0);
end;
WM_SIZE : begin
SendMessage(Handle, WM_NCPAINT, 0, 0);
end;
end;
end;
// Aligning of the bound label
if Assigned(BoundLabel) and Assigned(BoundLabel.FtheLabel) then case Message.Msg of
WM_SIZE, WM_WINDOWPOSCHANGED : begin BoundLabel.AlignLabel end;
CM_VISIBLECHANGED : begin BoundLabel.FtheLabel.Visible := Visible; BoundLabel.AlignLabel end;
CM_ENABLEDCHANGED : begin BoundLabel.FtheLabel.Enabled := Enabled or not (dkBlended in DisabledKind); BoundLabel.AlignLabel end;
CM_BIDIMODECHANGED : begin BoundLabel.FtheLabel.BiDiMode := BiDiMode; BoundLabel.AlignLabel end;
end;
end;
procedure TsEdit.CreateParams(var Params: TCreateParams);
begin
inherited;
// Params.ExStyle := Params.ExStyle or WS_EX_TRANSPARENT;
end;
end.
|
(* @file UKeyConstants.pas
* @author Willi Schinmeyer
* @date 2011-10-24
*
* UKeyConstants Unit
*
* Defines constants for keyboard key ASCII codes as returned by
* readkey. *)
unit UKeyConstants;
interface
const
(* Extended Keys: Keys beyond usual ASCII codes, return 0 on
* first readkey call *)
(* Arrow Keys *)
EXT_KEY_UP = #72;
EXT_KEY_DOWN = #80;
EXT_KEY_LEFT = #75;
EXT_KEY_RIGHT = #77;
(* Escape *)
KEY_ESCAPE = #27;
(* Return *)
KEY_RETURN = #13;
implementation
begin
end.
|
unit PessoaDTO;
interface
uses
Atributos, Classes, Constantes, Generics.Collections,
SynCommons,
mORMot,
PessoaFisicaDTO, PessoaJuridicaDTO, PessoaEnderecoDTO, PessoaContatoDTO,
PessoaTelefoneDTO;
type
TPessoa = class(TSQLRecord)
private
FPK: Integer;
FNOME: RawUTF8;
FTIPO: RawUTF8;
FEMAIL: RawUTF8;
FSITE: RawUTF8;
FCLIENTE: RawUTF8;
FFORNECEDOR: RawUTF8;
FCOLABORADOR: RawUTF8;
FTRANSPORTADORA: RawUTF8;
//1:N
FListaPessoaContatoVO: TObjectList<TPessoa_Contato>;
FListaPessoaEnderecoVO: TObjectList<TPessoa_Endereco>;
FListaPessoaTelefoneVO: TObjectList<TPessoa_Telefone>;
//1:1
FPessoaFisicaVO: TPessoa_Fisica;
FPessoaJuridicaVO: TPessoa_Juridica;
public
//1:1
property PessoaFisicaVO: TPessoa_Fisica read FPessoaFisicaVO write FPessoaFisicaVO;
property PessoaJuridicaVO: TPessoa_Juridica read FPessoaJuridicaVO write FPessoaJuridicaVO;
//1:N
property ListaPessoaContatoVO: TObjectList<TPessoa_Contato> read FListaPessoaContatoVO write FListaPessoaContatoVO;
property ListaPessoaEnderecoVO: TObjectList<TPessoa_Endereco> read FListaPessoaEnderecoVO write FListaPessoaEnderecoVO;
property ListaPessoaTelefoneVO: TObjectList<TPessoa_Telefone> read FListaPessoaTelefoneVO write FListaPessoaTelefoneVO;
published
[TPK('ID', [ldGrid, ldLookup, ldComboBox])]
property PK: Integer read FPK write FPK;
[TColumn('NOME', 'Nome', [ldGrid, ldLookup,ldComboBox], False)]
property Nome: RawUTF8 read FNOME write FNOME;
[TColumn('TIPO','Tipo',40,[ldGrid, ldLookup] ,False)]
property Tipo: RawUTF8 read FTIPO write FTIPO;
[TColumn('EMAIL','Email',[ldGrid, ldLookup] ,False)]
property Email: RawUTF8 read FEMAIL write FEMAIL;
[TColumn('SITE','Site',[ldGrid, ldLookup] ,False)]
property Site: RawUTF8 read FSITE write FSITE;
[TColumn('CLIENTE','Cliente',50,[],False)]
property Cliente: RawUTF8 read FCLIENTE write FCLIENTE;
[TColumn('FORNECEDOR','Fornecedor',60,[],False)]
property Fornecedor: RawUTF8 read FFORNECEDOR write FFORNECEDOR;
[TColumn('COLABORADOR','Colaborador',70,[],False)]
property Colaborador: RawUTF8 read FCOLABORADOR write FCOLABORADOR;
[TColumn('TRANSPORTADORA','Transportadora',80,[],False)]
property Transportadora: RawUTF8 read FTRANSPORTADORA write FTRANSPORTADORA;
end;
implementation
end.
|
{ ------------------------------------
功能说明:模块管理
创建日期:2010/05/11
作者:wzw
版权:wzw
------------------------------------- }
unit SysModuleMgr;
interface
uses
SysUtils,
Classes,
Windows,
Contnrs,
RegIntf,
SplashFormIntf,
ModuleInfoIntf,
SvcInfoIntf,
SysModule,
ModuleLoaderIntf,
StrUtils,
uIntfObj,
ModuleInstallerIntf,
SysNotifyService,
NotifyServiceIntf,
Forms;
type
TGetModuleClassPro = function: TModuleClass;
TModuleType = (mtUnknow, mtBPL, mtDLL);
TTangramModule = class(TObject)
private
FLoadBatch: string;
FModuleHandle: HMODULE;
FModuleFileName: string;
FModuleObj: TModule;
FModuleCls: TModuleClass;
FValidModule: Boolean;
function GetModuleType: TModuleType;
function LoadModule: THandle;
procedure UnLoadModule;
function GetModuleName: string;
protected
public
constructor Create(const mFile: string; LoadBatch: string = '';
CreateModuleObjInstance: Boolean = True);
destructor Destroy; override;
property ModuleFileName: string read FModuleFileName;
property ModuleType: TModuleType read GetModuleType;
property ModuleName: string read GetModuleName;
procedure ModuleNotify(Flags: Integer; Intf: IInterface; Param: Cardinal);
procedure ModuleInit(const LoadBatch: string);
procedure ModuleFinal;
procedure Install;
procedure UnInstall;
property IsValidModule: Boolean read FValidModule;
end;
TModuleMgr = class(TIntfObj, IModuleInfo, IModuleLoader, IModuleInstaller,
ISvcInfoEx)
private
SplashForm: ISplashForm;
Tick: Cardinal;
FModuleList: TObjectList;
FLoadBatch: string;
FNotifyService: TNotifyService;
procedure WriteErrFmt(const err: string; const Args: array of const);
function FormatPath(const s: string): string;
procedure GetModuleList(RegIntf: IRegistry; ModuleList: TStrings; const Key:
string);
function FindModule(const ModuleFile: string): TTangramModule;
protected
{IModuleLoader}
procedure LoadBegin;
procedure LoadModuleFromFile(const ModuleFile: string);
procedure LoadModulesFromDir(const Dir: string = '');
procedure LoadFinish;
procedure UnLoadModule(const ModuleFile: string);
function ModuleLoaded(const ModuleFile: string): Boolean;
{ IModuleInfo }
procedure GetModuleInfo(ModuleInfoGetter: IModuleInfoGetter);
{ ISvcInfoEx }
procedure GetSvcInfo(Intf: ISvcInfoGetter);
{IModuleInstaller}
procedure InstallModule(const ModuleFile: string);
procedure UninstallModule(const ModuleFile: string);
public
constructor Create;
destructor Destroy; override;
procedure LoadModules;
procedure Init;
procedure final;
end;
implementation
uses
SysSvc,
LogIntf,
LoginIntf,
StdVcl,
AxCtrls,
SysFactoryMgr,
SysFactory,
SysFactoryEx,
IniFiles,
RegObj,
uSvcInfoObj,
SysMsg;
{$WARN SYMBOL_DEPRECATED OFF}
{$WARN SYMBOL_PLATFORM OFF}
const
Value_Module = 'Module';
Value_Load = 'LOAD';
SplashFormWaitTime = 1500;
key_LoadModule = 'SYSTEM\LOADMODULE';
function CreateRegObj(Param: Integer): TObject;
var
RegFile, IniFile, AppPath: string;
Ini: TIniFile;
begin
AppPath := ExtractFilePath(ParamStr(0));
IniFile := AppPath + 'Root.ini';
Ini := TIniFile.Create(IniFile);
try
RegFile := AppPath + Ini.ReadString('Default', 'Reg', 'Tangram.xml');
Result := TRegObj.Create(RegFile);
finally
Ini.Free;
end;
end;
function Create_SvcInfoObj(Param: Integer): TObject;
begin
Result := TSvcInfoObj.Create;
end;
{ TTangramModule }
constructor TTangramModule.Create(const mFile: string; LoadBatch: string = '';
CreateModuleObjInstance: Boolean = True);
var
GetModuleClassPro: TGetModuleClassPro;
begin
FValidModule := False;
FModuleObj := nil;
FModuleCls := nil;
FLoadBatch := LoadBatch;
FModuleFileName := mFile;
FModuleHandle := self.LoadModule;
@GetModuleClassPro := GetProcAddress(FModuleHandle, 'GetModuleClass');
if Assigned(GetModuleClassPro) then
begin
FModuleCls := GetModuleClassPro;
FValidModule := FModuleCls <> nil;
if (FModuleCls <> nil) and (CreateModuleObjInstance) then
FModuleObj := FModuleCls.Create;
end;
end;
destructor TTangramModule.Destroy;
begin
if Assigned(FModuleObj) then
FModuleObj.Free;
self.UnLoadModule;
inherited;
end;
function TTangramModule.GetModuleName: string;
begin
Result := ExtractFileName(FModuleFileName);
end;
function TTangramModule.GetModuleType: TModuleType;
var
ext: string;
begin
ext := ExtractFileExt(self.FModuleFileName);
if SameText(ext, '.bpl') then
Result := mtBPL
else
Result := mtDLL;
end;
function TTangramModule.LoadModule: THandle;
begin
Result := 0;
case GetModuleType of
mtBPL:
Result := SysUtils.LoadPackage(self.FModuleFileName);
mtDLL:
Result := Windows.LoadLibrary(Pchar(self.FModuleFileName));
end;
end;
procedure TTangramModule.ModuleFinal;
begin
if FModuleObj <> nil then
FModuleObj.final;
end;
procedure TTangramModule.ModuleInit(const LoadBatch: string);
begin
if FModuleObj <> nil then
begin
if self.FLoadBatch = LoadBatch then
FModuleObj.Init;
end;
end;
procedure TTangramModule.Install;
var
Reg: IRegistry;
begin
if FModuleCls <> nil then
begin
Reg := SysService as IRegistry;
FModuleCls.RegisterModule(Reg);
end;
end;
procedure TTangramModule.ModuleNotify(Flags: Integer; Intf: IInterface; Param:
Cardinal);
begin
if FModuleObj <> nil then
FModuleObj.Notify(Flags, Intf, Param);
end;
procedure TTangramModule.UnInstall;
var
Reg: IRegistry;
begin
if FModuleCls <> nil then
begin
Reg := SysService as IRegistry;
FModuleCls.UnRegisterModule(Reg);
end;
end;
procedure TTangramModule.UnLoadModule;
begin
case GetModuleType of
mtBPL:
SysUtils.UnloadPackage(self.FModuleHandle);
mtDLL:
Windows.FreeLibrary(self.FModuleHandle);
end;
end;
{ TModuleMgr }
procedure TModuleMgr.GetSvcInfo(Intf: ISvcInfoGetter);
var
SvrInfo: TSvcInfoRec;
begin
SvrInfo.ModuleName := ExtractFileName(SysUtils.GetModuleName(HInstance));
SvrInfo.GUID := GUIDToString(IModuleInfo);
SvrInfo.Title := '模块信息接口(IModuleInfo)';
SvrInfo.Version := '20100512.001';
SvrInfo.Comments := '用于获取当前系统加载包的信息及初始化包。';
Intf.SvcInfo(SvrInfo);
SvrInfo.GUID := GUIDToString(IModuleLoader);
SvrInfo.Title := '模块加载接口(IModuleLoader)';
SvrInfo.Version := '20110225.001';
SvrInfo.Comments :=
'用户可以用此接口自主加载模块,不用框架默认的从注册表加载方式';
Intf.SvcInfo(SvrInfo);
SvrInfo.GUID := GUIDToString(IModuleInstaller);
SvrInfo.Title := '模块安装接口(IModuleInstaller)';
SvrInfo.Version := '20110420.001';
SvrInfo.Comments := '用于安装和卸载模块';
Intf.SvcInfo(SvrInfo);
end;
constructor TModuleMgr.Create;
begin
FLoadBatch := '';
FModuleList := TObjectList.Create(True);
FNotifyService := TNotifyService.Create;
TSingletonFactory.Create(IRegistry, @CreateRegObj);
TObjFactoryEx.Create([IModuleInfo, IModuleLoader, IModuleInstaller], self);
TIntfFactory.Create(ISvcInfoEx, @Create_SvcInfoObj);
end;
destructor TModuleMgr.Destroy;
begin
FNotifyService.Free;
FModuleList.Free;
inherited;
end;
function TModuleMgr.FindModule(const ModuleFile: string): TTangramModule;
var
i: Integer;
Module: TTangramModule;
begin
Result := nil;
for i := 0 to FModuleList.Count - 1 do
begin
Module := TTangramModule(FModuleList[i]);
if SameText(Module.ModuleFileName, ModuleFile) then
begin
Result := Module;
Break;
end;
end;
end;
function TModuleMgr.FormatPath(const s: string): string;
const
Var_AppPath = '($APP_PATH)';
begin
Result := StringReplace(s, Var_AppPath, ExtractFilePath(Paramstr(0)), [rfReplaceAll,
rfIgnoreCase]);
end;
procedure TModuleMgr.GetModuleList(RegIntf: IRegistry; ModuleList: TStrings;
const Key: string);
var
SubKeyList, ValueList, aList: TStrings;
i: Integer;
valueStr: string;
valueName, vStr, ModuleFile, Load: WideString;
begin
SubKeyList := TStringList.Create;
ValueList := TStringList.Create;
aList := TStringList.Create;
try
RegIntf.OpenKey(Key, False);
// 处理值
RegIntf.GetValueNames(ValueList);
for i := 0 to ValueList.Count - 1 do
begin
aList.Clear;
valueName := ValueList[i];
if RegIntf.ReadString(valueName, vStr) then
begin
valueStr := AnsiUpperCase(vStr);
ExtractStrings([';'], [], pchar(valueStr), aList);
ModuleFile := FormatPath(aList.Values[Value_Module]);
Load := aList.Values[Value_Load];
if (ModuleFile <> '') and (CompareText(Load, 'TRUE') = 0) then
ModuleList.Add(ModuleFile);
end;
end;
// 向下查找
RegIntf.GetKeyNames(SubKeyList);
for i := 0 to SubKeyList.Count - 1 do
GetModuleList(RegIntf, ModuleList, Key + '\' + SubKeyList[i]); // 递归
finally
SubKeyList.Free;
ValueList.Free;
aList.Free;
end;
end;
function TModuleMgr.ModuleLoaded(const ModuleFile: string): Boolean;
begin
Result := FindModule(ModuleFile) <> nil;
end;
procedure TModuleMgr.GetModuleInfo(ModuleInfoGetter: IModuleInfoGetter);
var
i: Integer;
Module: TTangramModule;
MInfo: TModuleInfo;
begin
if ModuleInfoGetter = nil then
exit;
for i := 0 to FModuleList.Count - 1 do
begin
Module := TTangramModule(FModuleList[i]);
MInfo.PackageName := Module.ModuleFileName;
MInfo.Description := GetPackageDescription(pchar(MInfo.PackageName));
ModuleInfoGetter.ModuleInfo(MInfo);
end;
end;
procedure TModuleMgr.Init;
var
CurTick, UseTime, WaitTime: Cardinal;
LoginIntf: ILogin;
Module: TTangramModule;
i: Integer;
begin
Module := nil;
for i := 0 to FModuleList.Count - 1 do
begin
try
Module := TTangramModule(FModuleList.Items[i]);
if Assigned(SplashForm) then
SplashForm.loading(Format(Msg_InitingModule, [Module.ModuleName]));
Module.ModuleInit(self.FLoadBatch);
except
on E: Exception do
begin
WriteErrFmt(Err_InitModule, [Module.ModuleName, E.Message]);
end;
end;
end;
// 隐藏Splash窗体
if Assigned(SplashForm) then
begin
CurTick := GetTickCount;
UseTime := CurTick - Tick;
WaitTime := SplashForm.GetWaitTime;
if WaitTime = 0 then
WaitTime := SplashFormWaitTime;
if UseTime < WaitTime then
begin
SplashForm.loading(Msg_WaitingLogin);
sleep(WaitTime - UseTime);
end;
SplashForm.Hide;
//FactoryManager.FindFactory(ISplashForm).Free;
SplashForm := nil;
end;
// 检查登录
if SysService.QueryInterface(ILogin, LoginIntf) = S_OK then
begin
if not LoginIntf.Login then
begin
Application.ShowMainForm := False;
Application.Terminate;
end;
end;
end;
procedure TModuleMgr.LoadModules;
var
aList: TStrings;
i: Integer;
RegIntf: IRegistry;
ModuleFile: string;
begin
aList := TStringList.Create;
try
SplashForm := nil;
RegIntf := SysService as IRegistry;
GetModuleList(RegIntf, aList, key_LoadModule);
for i := 0 to aList.Count - 1 do
begin
ModuleFile := aList[i];
if Assigned(SplashForm) then
SplashForm.loading(Format(Msg_LoadingModule, [ExtractFileName(ModuleFile)]));
// 加载包
if FileExists(ModuleFile) then
LoadModuleFromFile(ModuleFile)
else
WriteErrFmt(Err_ModuleNotExists, [ModuleFile]);
// 显示Falsh窗体
if SplashForm = nil then
begin
if SysService.QueryInterface(ISplashForm, SplashForm) = S_OK then
begin
Tick := GetTickCount;
SplashForm.Show;
end;
end;
end;
finally
aList.Free;
end;
end;
procedure TModuleMgr.LoadBegin;
var
BatchID: TGUID;
begin
if CreateGUID(BatchID) = S_OK then
self.FLoadBatch := GUIDToString(BatchID);
end;
procedure TModuleMgr.LoadFinish;
begin
self.Init;
end;
procedure TModuleMgr.LoadModulesFromDir(const Dir: string);
var
DR: TSearchRec;
ZR: Integer;
TmpPath, FileExt, FullFileName: string;
begin
if Dir = '' then
TmpPath := ExtractFilePath(ParamStr(0))
else
begin
if RightStr(Dir, 1) = '\' then
TmpPath := Dir
else
TmpPath := Dir + '\';
end;
ZR := SysUtils.FindFirst(TmpPath + '*.*', FaAnyfile, DR);
try
while ZR = 0 do
begin
if ((DR.Attr and FaDirectory <> FaDirectory) and (DR.Attr and FaVolumeID
<> FaVolumeID)) and (DR.Name <> '.') and (DR.Name <> '..') then
begin
FullFileName := TmpPath + DR.Name;
FileExt := ExtractFileExt(FullFileName);
if SameText(FileExt, '.dll') or SameText(FileExt, '.bpl') then
self.LoadModuleFromFile(FullFileName);
end;
ZR := SysUtils.FindNext(DR);
end; //end while
finally
SysUtils.FindClose(DR);
end;
end;
procedure TModuleMgr.LoadModuleFromFile(const ModuleFile: string);
var
Module: TTangramModule;
begin
try
Module := TTangramModule.Create(ModuleFile, self.FLoadBatch);
if Module.IsValidModule then
FModuleList.Add(Module)
else
Module.Free;
except
on E: Exception do
begin
WriteErrFmt(Err_LoadModule, [ExtractFileName(ModuleFile), E.Message]);
end;
end;
end;
procedure TModuleMgr.UnLoadModule(const moduleFile: string);
var
Module: TTangramModule;
begin
Module := self.FindModule(moduleFile);
if Module <> nil then
FModuleList.Remove(Module);
end;
procedure TModuleMgr.final;
var
i: Integer;
Module: TTangramModule;
begin
for i := 0 to FModuleList.Count - 1 do
begin
Module := TTangramModule(FModuleList.Items[i]);
try
Module.ModuleFinal;
except
on E: Exception do
self.WriteErrFmt(Err_finalModule, [Module.ModuleName, E.Message]);
end;
end;
FactoryManager.ReleaseIntf;
end;
procedure TModuleMgr.WriteErrFmt(const err: string; const Args: array of const);
var
Log: ILog;
begin
if SysService.QueryInterface(ILog, Log) = S_OK then
Log.WriteLogFmt(err, Args);
end;
procedure TModuleMgr.InstallModule(const ModuleFile: string);
var
Module: TTangramModule;
begin
Module := self.FindModule(ModuleFile);
if Module = nil then
begin
Module := TTangramModule.Create(ModuleFile, '', False);
if Module.IsValidModule then
FModuleList.Add(Module)
else
begin
Module.Free;
exit;
end;
end;
Module.Install;
end;
procedure TModuleMgr.UninstallModule(const ModuleFile: string);
var
Module: TTangramModule;
begin
Module := self.FindModule(ModuleFile);
if Module = nil then
begin
Module := TTangramModule.Create(ModuleFile, '', False);
if Module.IsValidModule then
FModuleList.Add(Module)
else
begin
Module.Free;
exit;
end;
end;
Module.UnInstall;
end;
initialization
finalization
end.
|
{Ä Fido Pascal Conference ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ PASCAL Ä
Msg : 663 of 702
From : MIKE COPELAND 1:114/151.0 21 Apr 93 22:13
To : JON RUPERT
Subj : SECONDS TO H:M:S
ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ
JR> I'm looking for some FAST routines to change seconds into a
JR> readable format, (ie. H:M:S).
JR> For instance, 8071 seconds = 2:14:31
Here's the code I use, and it's fast enough for me: }
function FORMAT_TIME (V : integer) : STR8; { format time as hh:mm:ss }
var X,Z : integer;
PTIME : STR8;
begin { note: incoming time is in seconds }
Z := ord('0'); PTIME := ' : : '; { initialize }
X := V div 3600; V := V mod 3600; { process hours }
if (X > 0) and (X <= 9) then PTIME[2] := chr(X+Z)
else if X = 0 then PTIME[3] := ' ' { zero-suppress }
else PTIME[2] := '*'; { overflow... }
X := V div 60; V := V mod 60; { process minutes }
PTIME[4] := chr((X div 10)+Z); PTIME[5] := chr((X mod 10)+Z);
PTIME[7] := chr((V div 10)+Z); { process seconds }
PTIME[8] := chr((V mod 10)+Z); FORMAT_TIME := PTIME
end; { FORMAT_TIME } |
unit qdac_fmx_modaldlg;
{ FMX.ModalDlg FMX 下 ShowModal 的增强和接口统一
本单元统一了 FMX 和 TForm.ShowModal 的操作接口,原来 Delphi 自带的 ShowModal 的
匿名函数版本传递的只是一个 ModalResult 参数,无法通过局部变量进一步控制。此版本
参数改为窗体的实例,你可以访问其 ModalResult 以及各个相关的成员,以方便进一步控
制。
受平台限制,Android 下并不是实际的ShowModal(不过和 ShowModal 差不多,因为它都是
全屏覆盖的,下层的窗口你也操作不了),而其它平台都是真正的模态窗口。
2016.3.4
========
+ 1.0 版
}
interface
uses classes, sysutils, fmx.types, fmx.forms, fmx.controls, System.Messaging,
uitypes;
type
TFormModalProc = reference to procedure(F: TForm);
TFormClass = class of TForm;
/// <summary>显示一个模态窗口</summmary>
/// <param name="F">窗口实例</param>
/// <param name="OnResult">用户关闭窗口时的操作</param>
/// <param name="ACloseAction">窗口关闭时的动作,默认caFree释放掉</param>
/// <remarks>在 Windows/iOS/OSX 上是真正 ShowModal 出来,然后调用 OnResult,而在
/// Android 上,是 Show 以后,在用户关闭或设置 ModalResult 时调用的 OnResult。
/// 也就是说,Android 上受平台限制是模拟的 ShowModal 效果。</remarks>
procedure ModalDialog(F: TForm; OnResult: TFormModalProc;
ACloseAction: TCloseAction = TCloseAction.caFree); overload;
/// <summary>显示一个模态窗口,并在关闭时释放</summmary>
/// <param name="F">窗口实例</param>
/// <param name="OnResult">用户关闭窗口时的操作</param>
/// <remarks>在 Windows/iOS/OSX 上是真正 ShowModal 出来,然后调用 OnResult,而在
/// Android 上,是 Show 以后,在用户关闭或设置 ModalResult 时调用的 OnResult。
/// 也就是说,Android 上受平台限制是模拟的 ShowModal 效果。</remarks>
procedure ModalDialog(AClass: TFormClass; OnResult: TFormModalProc); overload;
implementation
type
TFormModalHook = class(TComponent)
private
FForm: TForm;
FCloseAction: TCloseAction;
FOldClose: TCloseEvent;
FResultProc: TFormModalProc;
procedure DoFormClose(Sender: TObject; var Action: TCloseAction);
public
constructor Create(AOwner: TComponent); override;
procedure ShowModal(AResult: TFormModalProc);
end;
procedure ModalDialog(F: TForm; OnResult: TFormModalProc;
ACloseAction: TCloseAction = TCloseAction.caFree);
var
AHook: TFormModalHook;
begin
AHook := TFormModalHook.Create(F);
AHook.FCloseAction := ACloseAction;
AHook.ShowModal(OnResult);
end;
procedure ModalDialog(AClass: TFormClass; OnResult: TFormModalProc); overload;
var
F: TForm;
begin
F := AClass.Create(Application);
ModalDialog(F, OnResult, TCloseAction.caFree);
end;
{ TFormModalHook }
constructor TFormModalHook.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FForm := AOwner as TForm;
FOldClose := FForm.OnClose;
FForm.OnClose := DoFormClose;
FCloseAction := TCloseAction.caFree;
end;
procedure TFormModalHook.DoFormClose(Sender: TObject; var Action: TCloseAction);
begin
if FForm.ModalResult = mrNone then
FForm.ModalResult := mrCancel;
Action := FCloseAction;
CloseAllPopups;
if Assigned(FOldClose) then
FOldClose(Sender, FCloseAction);
end;
procedure TFormModalHook.ShowModal(AResult: TFormModalProc);
begin
FResultProc := AResult;
{$IFDEF ANDROID}
FForm.ShowModal(
procedure(AResult: TModalResult)
begin
if Assigned(FForm) then
begin
FForm.OnClose := FOldClose;
if Assigned(FResultProc) then
FResultProc(FForm);
end;
end);
{$ELSE}
FForm.ShowModal;
if Assigned(FResultProc) then
FResultProc(FForm);
{$ENDIF}
end;
end.
|
//------------------------------------------------------------------------------
// File: UAsyncRdr.pas
// Original files: asyncrdr.h, asyncrdr.c
//
// Desc: Defines an IO source filter.
//
// This filter (CAsyncReader) supports IBaseFilter and IFileSourceFilter interfaces from the
// filter object itself. It has a single output pin (CAsyncOutputPin)
// which supports IPin and IAsyncReader.
//
// This filter is essentially a wrapper for the CAsyncFile class that does
// all the work.
//
//
// Portions created by Microsoft are
// Copyright (c) 2000-2002 Microsoft Corporation. All rights reserved.
//------------------------------------------------------------------------------
unit uAsyncRdr;
interface
uses
BaseClass, DirectShow9, DSUtil, ActiveX, Windows, SysUtils,
UAsyncIo;
const
//CLSID_AsyncSample: TGUID = '{10F9E8F1-FE54-470C-9F1A-FE587DF7BD0B}';
CLSID_AsyncSample: TGUID = '{8834FB41-B5DE-4b43-8690-D0DB3DE97EBA}';
type
// the filter class (defined below)
TBCAsyncReader = class;
// the output pin class
TBCAsyncOutputPin = class(TBCBasePin, IAsyncReader)
protected
FReader: TBCAsyncReader;
FIo: TBCAsyncIo;
// This is set every time we're asked to return an IAsyncReader
// interface
// This allows us to know if the downstream pin can use
// this transport, otherwise we can hook up to thinks like the
// dump filter and nothing happens
FQueriedForAsyncReader: Boolean;
function InitAllocator(out AAlloc: IMemAllocator): HRESULT; virtual;
public
// constructor and destructor
constructor Create(out hr: HResult; Reader: TBCAsyncReader;
IO: TBCAsyncIo; Lock: TBCCritSec);
destructor Destroy; override;
// --- CUnknown ---
// need to expose IAsyncReader
function NonDelegatingQueryInterface(const IID: TGUID;
out Obj): HResult; override; stdcall;
// --- IPin methods ---
function Connect(AReceivePin: IPin;
const pmt: PAMMediaType): HResult; reintroduce; stdcall;
// --- CBasePin methods ---
// return the types we prefer - this will return the known
// file type
function GetMediaType(Position: Integer;
out MediaType: PAMMediaType): HResult; override;
// can we support this type?
function CheckMediaType(AType: PAMMediaType): HResult; override;
// Clear the flag so we see if IAsyncReader is queried for
function CheckConnect(Pin: IPin): HResult; override;
// See if it was asked for
function CompleteConnect(ReceivePin: IPin): HResult; override;
// Remove our connection status
function BreakConnect: HResult; override;
// --- IAsyncReader methods ---
// pass in your preferred allocator and your preferred properties.
// method returns the actual allocator to be used. Call GetProperties
// on returned allocator to learn alignment and prefix etc chosen.
// this allocator will be not be committed and decommitted by
// the async reader, only by the consumer.
function RequestAllocator(APreferred: IMemAllocator;
AProps: PAllocatorProperties;
out AActual: IMemAllocator): HResult; stdcall;
// queue a request for data.
// media sample start and stop times contain the requested absolute
// byte position (start inclusive, stop exclusive).
// may fail if sample not obtained from agreed allocator.
// may fail if start/stop position does not match agreed alignment.
// samples allocated from source pin's allocator may fail
// GetPointer until after returning from WaitForNext.
function Request(ASample: IMediaSample; AUser: DWord): HResult; stdcall;
// block until the next sample is completed or the timeout occurs.
// timeout (millisecs) may be 0 or INFINITE. Samples may not
// be delivered in order. If there is a read error of any sort, a
// notification will already have been sent by the source filter,
// and STDMETHODIMP will be an error.
function WaitForNext(ATimeout: DWord; out ASample: IMediaSample;
out AUser: DWord): HResult; stdcall;
// sync read of data. Sample passed in must have been acquired from
// the agreed allocator. Start and stop position must be aligned.
// equivalent to a Request/WaitForNext pair, but may avoid the
// need for a thread on the source filter.
function SyncReadAligned(ASample: IMediaSample): HResult; stdcall;
// sync read. works in stopped state as well as run state.
// need not be aligned. Will fail if read is beyond actual total
// length.
function SyncRead(APosition: int64; ALength: Longint;
ABuffer: PByte): HResult; stdcall;
// return total length of stream, and currently available length.
// reads for beyond the available length but within the total length will
// normally succeed but may block for a long period.
function Length(out ATotal, AAvailable: int64): HResult; stdcall;
// cause all outstanding reads to return, possibly with a failure code
// (VFW_E_TIMEOUT) indicating they were cancelled.
// these are defined on IAsyncReader and IPin
function BeginFlush: HResult; override;
function EndFlush: HResult; override;
end;
//
// The filter object itself. Supports IBaseFilter through
// CBaseFilter and also IFileSourceFilter directly in this object
TBCAsyncReader = class(TBCBaseFilter)
protected
// filter-wide lock
FCSFilter: TBCCritSec;
// all i/o done here
FIO: TBCAsyncIo;
// our output pin
FOutputPin: TBCAsyncOutputPin;
// Type we think our data is
Fmt: TAMMediaType;
public
// construction / destruction
constructor Create(Name: String; Unk: IUnknown;
Stream: TBCAsyncStream; out hr: HResult);
destructor Destroy; override;
// --- CBaseFilter methods ---
function GetPinCount: Integer; override;
function GetPin(n: Integer): TBCBasePin; override;
// --- Access our media type
function LoadType: PAMMediaType; virtual;
function Connect(pReceivePin: IPin;
const pmt: PAMMediaType): HRESULT; virtual;
end;
implementation
// --- TBCCAsyncReader ---
constructor TBCAsyncReader.Create(Name: String; Unk: IUnknown;
Stream: TBCAsyncStream; out hr: HResult);
begin
FCSFilter := TBCCritSec.Create;
ZeroMemory(@Fmt, SizeOf(TAMMediaType));
Inherited Create(Name, Unk, FCSFilter, CLSID_AsyncSample, hr);
FIO := TBCAsyncIo.Create(Stream);
FOutputPin := TBCAsyncOutputPin.Create(hr, Self, FIO, FCSFilter);
end;
destructor TBCAsyncReader.Destroy;
begin
Inherited;
// FCSFilter is destroyed by parent class
end;
function TBCAsyncReader.GetPinCount: Integer;
begin
Result := 1;
end;
function TBCAsyncReader.GetPin(n: Integer): TBCBasePin;
begin
if ((GetPinCount > 0) and (n = 0)) then
Result := FOutputPin
else
Result := nil;
end;
function TBCAsyncReader.LoadType: PAMMediaType;
begin
Result := @Fmt;
end;
function TBCAsyncReader.Connect(pReceivePin: IPin;
const pmt: PAMMediaType): HRESULT;
begin
Result := FOutputPin.Connect(pReceivePin, pmt);
end;
// --- TBCAsyncOutputPin ---
constructor TBCAsyncOutputPin.Create(out hr: HResult; Reader: TBCAsyncReader;
IO: TBCAsyncIo; Lock: TBCCritSec);
begin
Inherited Create('Async output pin', Reader, Lock, hr, 'Output',
PINDIR_OUTPUT);
FReader := Reader;
FIO := IO;
end;
destructor TBCAsyncOutputPin.Destroy;
begin
Inherited;
end;
function TBCAsyncOutputPin.InitAllocator(out AAlloc: IMemAllocator): HRESULT;
begin
// Create a default memory allocator
Result := CreateMemoryAllocator(AAlloc);
if Failed(Result) then
Exit;
if (AAlloc = nil) then
begin
Result := E_OUTOFMEMORY;
Exit;
end;
end;
function TBCAsyncOutputPin.NonDelegatingQueryInterface(const IID: TGUID;
out Obj): HResult;
begin
if IsEqualGUID(IID, IID_IAsyncReader) then
begin
FQueriedForAsyncReader := True;
if GetInterface(IID_IAsyncReader, Obj) then
Result := S_OK
else
Result := E_FAIL;
end
else
Result := Inherited NonDelegatingQueryInterface(IID, Obj);
end;
function TBCAsyncOutputPin.Connect(AReceivePin: IPin;
const pmt: PAMMediaType): HResult;
begin
Result := FReader.Connect(AReceivePin, pmt);
end;
function TBCAsyncOutputPin.GetMediaType(Position: Integer;
out MediaType: PAMMediaType): HResult;
begin
if (Position < 0) then
Result := E_INVALIDARG
else
if (Position > 0) then
Result := VFW_S_NO_MORE_ITEMS
else
begin
if (FReader = nil) then
begin
Result := E_UNEXPECTED;
Exit;
end;
CopyMemory(MediaType, FReader.LoadType, SizeOf(TAMMediaType));
Result := S_OK;
end;
end;
function TBCAsyncOutputPin.CheckMediaType(AType: PAMMediaType): HResult;
begin
FLock.Lock;
try
// We treat MEDIASUBTYPE_NULL subtype as a wild card
with FReader do
if (IsEqualGUID(LoadType.majortype, AType.majortype) and
(IsEqualGUID(LoadType.subtype, MEDIASUBTYPE_NULL) or
IsEqualGUID(LoadType.subtype, AType.subtype))) then
Result := S_OK
else
Result := S_FALSE;
finally
FLock.Unlock;
end;
end;
function TBCAsyncOutputPin.CheckConnect(Pin: IPin): HResult;
begin
FQueriedForAsyncReader := False;
Result := Inherited CheckConnect(Pin);
end;
function TBCAsyncOutputPin.CompleteConnect(ReceivePin: IPin): HResult;
begin
if FQueriedForAsyncReader then
Result := inherited CompleteConnect(ReceivePin)
else
{$IFDEF VFW_E_NO_TRANSPORT}
Result := VFW_E_NO_TRANSPORT;
{$ELSE}
Result := E_FAIL;
{$ENDIF}
end;
function TBCAsyncOutputPin.BreakConnect: HResult;
begin
FQueriedForAsyncReader := False;
Result := Inherited BreakConnect;
end;
function TBCAsyncOutputPin.RequestAllocator(APreferred: IMemAllocator;
AProps: PAllocatorProperties; out AActual: IMemAllocator): HResult;
var
Actual: TAllocatorProperties;
Alloc: IMemAllocator;
begin
// we need to return an addrefed allocator, even if it is the preferred
// one, since he doesn't know whether it is the preferred one or not.
Assert(Assigned(FIO));
// we care about alignment but nothing else
if ((Not Boolean(AProps.cbAlign)) or
(Not FIo.IsAligned(AProps.cbAlign))) then
AProps.cbAlign := FIo.Alignment;
if Assigned(APreferred) then
begin
Result := APreferred.SetProperties(AProps^, Actual);
if (Succeeded(Result) and FIo.IsAligned(Actual.cbAlign)) then
begin
AActual := APreferred;
Result := S_OK;
Exit;
end;
end;
// create our own allocator
Result := InitAllocator(Alloc);
if Failed(Result) then
Exit;
//...and see if we can make it suitable
Result := Alloc.SetProperties(AProps^, Actual);
if (Succeeded(Result) and FIo.IsAligned(Actual.cbAlign)) then
begin
// we need to release our refcount on pAlloc, and addref
// it to pass a refcount to the caller - this is a net nothing.
AActual := Alloc;
Result := S_OK;
Exit;
end;
// failed to find a suitable allocator
Alloc._Release;
// if we failed because of the IsAligned test, the error code will
// not be failure
if Succeeded(Result) then
Result := VFW_E_BADALIGN;
end;
function TBCAsyncOutputPin.Request(ASample: IMediaSample; AUser: DWord): HResult;
var
Start, Stop: TReferenceTime;
Pos, Total, Available: LONGLONG;
Length, Align: Integer;
Buffer: PByte;
begin
// queue an aligned read request. call WaitForNext to get
// completion.
Result := ASample.GetTime(Start, Stop);
if Failed(Result) then
Exit;
Pos := Start div UNITS;
Length := (Stop - Start) div UNITS;
Total := 0;
Available := 0;
FIO.Length(Total, Available);
if (Pos + Length > Total) then
begin
// the end needs to be aligned, but may have been aligned
// on a coarser alignment.
FIo.Alignment(Align);
Total := (Total + Align -1) and (Not (Align-1));
if (Pos + Length > Total) then
begin
Length := Total - Pos;
// must be reducing this!
Assert((Total * UNITS) <= Stop);
Stop := Total * UNITS;
ASample.SetTime(@Start, @Stop);
end;
end;
Result := ASample.GetPointer(Buffer);
if Failed(Result) then
Exit;
Result := FIO.Request(Pos, Length, True, Buffer, Pointer(ASample), AUser);
end;
function TBCAsyncOutputPin.WaitForNext(ATimeout: DWord; out ASample: IMediaSample;
out AUser: DWord): HResult;
var
Actual: Integer;
Sample: IMediaSample;
begin
Sample := nil;
Result := FIo.WaitForNext(ATimeout, @Sample, AUser, Actual);
if Succeeded(Result) then
Sample.SetActualDataLength(Actual);
ASample := Sample;
end;
function TBCAsyncOutputPin.SyncReadAligned(ASample: IMediaSample): HResult;
var
Start, Stop: TReferenceTime;
Pos, Total, Available: LONGLONG;
Length, Align, Actual: Integer;
Buffer: PByte;
begin
Result := ASample.GetTime(Start, Stop);
if Failed(Result) then
Exit;
Pos := Start div UNITS;
Length := (Stop - Start) div UNITS;
FIo.Length(Total, Available);
if (Pos + Length > Total) then
begin
// the end needs to be aligned, but may have been aligned
// on a coarser alignment.
FIo.Alignment(Align);
Total := (Total + Align - 1) and (Not (Align - 1));
if (Pos + Length > Total) then
begin
Length := Total - Pos;
// must be reducing this!
Assert((Total * UNITS) <= Stop);
Stop := Total * UNITS;
ASample.SetTime(@Start, @Stop);
end;
end;
Result := ASample.GetPointer(Buffer);
if Failed(Result) then
Exit;
Result := FIO.SyncReadAligned(Pos, Length, Buffer, Actual, Pointer(ASample));
ASample.SetActualDataLength(Actual);
end;
function TBCAsyncOutputPin.SyncRead(APosition: Int64; ALength: Longint;
ABuffer: Pbyte): HResult;
begin
Result := FIO.SyncRead(APosition, ALength, ABuffer);
end;
function TBCAsyncOutputPin.Length(out ATotal, AAvailable: int64): HResult;
begin
Result := FIO.Length(ATotal, AAvailable);
end;
function TBCAsyncOutputPin.BeginFlush: HResult;
begin
Result := FIO.BeginFlush;
end;
function TBCAsyncOutputPin.EndFlush: HResult;
begin
Result := FIO.EndFlush;
end;
end.
|
unit sSkinMenus;
{$I sDefs.inc}
{.$DEFINE LOGGED}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, sConst,
Menus, ExtCtrls{$IFDEF LOGGED}, sDebugMsgs{$ENDIF} {$IFDEF TNTUNICODE}, TntMenus {$ENDIF};
type
TsMenuItemType = (smCaption, smDivider, smNormal, smTopLine);
TsMenuManagerDrawItemEvent = procedure (Sender: TObject; ACanvas: TCanvas; ARect: TRect; State: TOwnerDrawState; ItemType: TsMenuItemType) of object;
TacMenuSupport = class(TPersistent)
private
FIcoLineSkin: TsSkinSection;
FUseExtraLine: boolean;
FExtraLineWidth: integer;
FExtraLineFont: TFont;
procedure SetExtraLineFont(const Value: TFont);
public
constructor Create;
destructor Destroy; override;
published
property IcoLineSkin : TsSkinSection read FIcoLineSkin write FIcoLineSkin;
property UseExtraLine : boolean read FUseExtraLine write FUseExtraLine default False;
property ExtraLineWidth : integer read FExtraLineWidth write FExtraLineWidth default 32;
property ExtraLineFont : TFont read FExtraLineFont write SetExtraLineFont;
end;
TMenuItemData = record
Item : TMenuItem;
R : TRect;
end;
TacMenuInfo = record
FirstItem : TMenuItem;
Bmp : TBitmap;
Wnd : hwnd;
HaveExtraLine : boolean;
end;
TsSkinableMenus = class(TPersistent)
private
FMargin : integer;
FAlignment: TAlignment;
FBevelWidth: integer;
FBorderWidth: integer;
FCaptionFont: TFont;
FSkinBorderWidth: integer;
FSpacing: integer;
procedure SetCaptionFont(const Value: TFont);
procedure SetAlignment(const Value: TAlignment);
procedure SetBevelWidth(const Value: integer);
procedure SetBorderWidth(const Value: integer);
function GetSkinBorderWidth: integer;
protected
FOnDrawItem: TsMenuManagerDrawItemEvent;
function ParentHeight(aCanvas: TCanvas; Item: TMenuItem): integer;
function GetItemHeight(aCanvas: TCanvas; Item: TMenuItem): integer;
function ParentWidth(aCanvas: TCanvas; Item: TMenuItem): integer;
function GetItemWidth(aCanvas: TCanvas; Item: TMenuItem; mi : TacMenuInfo): integer;
function IsDivText(Item: TMenuItem): boolean;
procedure PaintDivider(aCanvas : TCanvas; aRect : TRect; Item: TMenuItem; MenuBmp : TBitmap; mi : TacMenuInfo);
procedure PaintCaption(aCanvas : TCanvas; aRect : TRect; Item : TMenuItem; BG : TBitmap; mi : TacMenuInfo);
function CursorMarginH : integer;
function CursorMarginV : integer;
function ItemRect(Item : TMenuItem; aRect : TRect) : TRect;
public
ArOR : TAOR;
FActive : boolean;
FOwner : TComponent;
Pressed : boolean;
BorderDrawing : boolean;
function IsTopLine(Item: TMenuItem): boolean;
procedure sMeasureItem(Sender: TObject; ACanvas: TCanvas; var Width, Height: Integer);
procedure sAdvancedDrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; State: TOwnerDrawState); dynamic;
procedure DrawWndBorder(Wnd : hWnd; MenuBmp : TBitmap);
function PrepareMenuBG(Item: TMenuItem; Width, Height : integer; Wnd : hwnd = 0) : TBitmap;
procedure sMeasureLineItem(Sender: TObject; ACanvas: TCanvas; var Width, Height: Integer);
procedure sAdvancedDrawLineItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; State: TOwnerDrawState); dynamic;
function IsOpened(Item : TMenuItem) : boolean;
procedure SetActive(const Value: boolean);
constructor Create (AOwner: TComponent);
destructor Destroy; override;
procedure InitItem(Item : TMenuItem; A : boolean);
procedure InitItems(A: boolean);
procedure InitMenuLine(Menu : TMainMenu; A : boolean);
procedure HookItem(MenuItem: TMenuItem; FActive: boolean);//!!!!
procedure HookPopupMenu(Menu: TPopupMenu; Active: boolean);
procedure UpdateMenus;
function LastItem(Item : TMenuItem) : boolean;
function IsPopupItem(Item : TMenuItem) : boolean;
function GetMenuInfo(Item : TMenuItem; const aWidth, aHeight : integer; aWnd : hwnd = 0) : TacMenuInfo;
function ExtraWidth(mi : TacMenuInfo) : integer;
published
property Alignment: TAlignment read FAlignment write SetAlignment;
property BevelWidth : integer read FBevelWidth write SetBevelWidth default 0;
property BorderWidth : integer read FBorderWidth write SetBorderWidth default 3;
property CaptionFont : TFont read FCaptionFont write SetCaptionFont;
property SkinBorderWidth : integer read GetSkinBorderWidth write FSkinBorderWidth;
property Margin: integer read FMargin write FMargin default 2;
property Spacing : integer read FSpacing write FSpacing default 8;
property OnDrawItem: TsMenuManagerDrawItemEvent read FOnDrawItem write FOnDrawItem;
end;
function Breaked(MenuItem : TMenuItem) : boolean;
function GlyphSize(Item: TMenuItem; Top: boolean): TSize;
function GetFirstItem(Item : TMenuItem) : TMenuItem;
procedure DeleteUnusedBmps(DeleteAll : boolean);
function ChildIconPresent : boolean;
procedure ClearCache;
var
MenuInfoArray : array of TacMenuInfo;
MDISkinProvider : TObject;
acCanHookMenu : boolean = False;
CustomMenuFont : TFont = nil;
const
s_SysMenu = 'SysMenu';
implementation
uses {sContextMenu, }sDefaults, math, sStyleSimply, sSkinProvider, sMaskData, sSkinProps, {$IFDEF TNTUNICODE}TntWindows, {$ENDIF}
sGraphUtils, sGradient, acntUtils, sAlphaGraph, sSkinManager, sMDIForm, sVclUtils, sMessages;
const
DontForget = 'Use OnGetExtraLineData event';
var
Measuring : boolean = False;
it : TsMenuItemType;
AlignToInt: array[TAlignment] of Cardinal = (DT_LEFT, DT_RIGHT, DT_CENTER);
// Temp data
IcoLineWidth : integer = 0;
GlyphSizeCX : integer = 0;
ExtraCaption : string;
ExtraSection : string;
ExtraGlyph : TBitmap;
function ChildIconPresent : boolean;
begin
Result := (MDISkinProvider <> nil) and
(TsSkinProvider(MDISkinProvider).Form <> nil) and
(TsSkinProvider(MDISkinProvider).Form.FormStyle = fsMDIForm) and
(TsSkinProvider(MDISkinProvider).Form.ActiveMDIChild <> nil) and
(TsSkinProvider(MDISkinProvider).Form.ActiveMDIChild.WindowState = wsMaximized) and (biSystemMenu in TsSkinProvider(MDISkinProvider).Form.ActiveMDIChild.BorderIcons) and
Assigned(TsSkinProvider(MDISkinProvider).Form.ActiveMDIChild.Icon);
end;
function GetFirstItem(Item : TMenuItem) : TMenuItem;
begin
Result := Item.Parent.Items[0];
end;
procedure DeleteUnusedBmps(DeleteAll : boolean);
var
i, l : integer;
begin
l := Length(MenuInfoArray);
// if DeleteAll then begin
for i := 0 to l - 1 do MenuInfoArray[i].Bmp.Free;
SetLength(MenuInfoArray, 0);
{ end
else for i := 0 to l - 1 do begin
for j := 0 to Length(MnuArray) - 1 do begin
if (MnuArray[j] <> nil) and not MnuArray[j].Destroyed and (MnuArray[j].CtrlHandle = MenuInfoArray[i].Wnd) then begin
if i <> l - 1 then begin
MenuInfoArray[i] := MenuInfoArray[l - 1];
end;
SetLength(MenuInfoArray, l - 1);
end;
end;
end;}
end;
{ TsSkinableMenus }
function Breaked(MenuItem : TMenuItem) : boolean;
var
i : integer;
begin
Result := False;
for i := 0 to MenuItem.MenuIndex do if MenuItem.Parent.Items[i].Break <> mbNone then begin
Result := True;
Break;
end;
end;
function GlyphSize(Item: TMenuItem; Top: boolean): TSize;
var
mi : TMenu;
begin
Result.cx := 0;
Result.cy := 0;
if Top then begin
if not Item.Bitmap.Empty then begin
Result.cx := Item.Bitmap.Width;
Result.cy := Item.Bitmap.Height;
end;
end
else begin
if not Item.Bitmap.Empty then begin
Result.cx := Item.Bitmap.Width;
Result.cy := Item.Bitmap.Height;
end
else begin
if Assigned(Item.Parent) and (Item.Parent.SubMenuImages <> nil) then begin
Result.cx := Item.Parent.SubMenuImages.Width;
Result.cy := Item.Parent.SubMenuImages.Height;
end
else begin
mi := Item.GetParentMenu;
if Assigned(mi) and Assigned(mi.Images) then begin
Result.cx := Item.GetParentMenu.Images.Width;
Result.cy := Item.GetParentMenu.Images.Height;
end
else begin
Result.cx := 16;
Result.cy := 16;
end;
end;
end;
end;
end;
constructor TsSkinableMenus.Create(AOwner: TComponent);
{var
pl : TList;
i : integer;}
begin
FOwner := AOwner;
FActive := False;
FCaptionFont := TFont.Create;
FMargin := 2;
FBevelWidth := 0;
FBorderWidth := 3;
BorderDrawing := False;
FSpacing := 8;
if csDesigning in FOwner.ComponentState then Exit;
{
if (PopupList <> nil) then if PopupList is TsPopupList then Exit else begin
pl := TList.Create;
for i := 0 to PopupList.Count - 1 do pl.Add(PopupList[i]);
FreeAndNil(PopupList);
PopupList := TsPopupList.Create;
for i := 0 to pl.Count - 1 do PopupList.Add(pl[i]);
FreeAndNil(pl);
end
else PopupList := TsPopupList.Create;
}
end;
procedure TsSkinableMenus.sAdvancedDrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; State: TOwnerDrawState);
const
s_Webdings = 'Webdings';
var
R, gRect, cRect : TRect;
i, j: integer;
ci : TCacheInfo;
Item : TMenuItem;
gChar : string;
Text: acString;
ItemBmp : TBitmap;
DrawStyle : longint;
Wnd : hwnd;
NewDC : hdc;
aMsg: TMSG;
Br : integer;
f : TCustomForm;
BGImage : TBitmap;
mi : TacMenuInfo;
RTL, RTLReading : boolean;
function TextRect: TRect; begin
Result := aRect;
OffsetRect(Result, - aRect.Left, - aRect.Top);
if RTL then begin
dec(Result.Right, Margin * 2 + GlyphSize(Item, False).cx + Spacing);
end
else begin
inc(Result.Left, Margin * 2 + GlyphSize(Item, False).cx + Spacing);
end;
end;
function ShortCutRect(const s : acString): TRect;
var
tr : TRect;
begin
Result := aRect;
tR := Rect(0, 0, 1, 0);
acDrawText(ItemBmp.Canvas.Handle, PacChar(Text), tR, DT_EXPANDTABS or DT_SINGLELINE or DT_CALCRECT);
OffsetRect(Result, - aRect.Left, - aRect.Top);
if RTL then begin
Result.Left := 6;
end
else Result.Left := aRect.Right - WidthOf(tr) - 8;
end;
function IsTopVisible(Item : TMenuItem) : boolean; var i : integer; begin
Result := False;
for i := 0 to Item.Parent.Count - 1 do if Item.Parent.Items[i].Visible then begin
if Item.Parent.Items[i] = Item then Result := True;
Break
end;
end;
function IsBtmVisible(Item : TMenuItem) : boolean; var i : integer; begin
Result := False;
for i := 0 to Item.Parent.Count - 1 do if Item.Parent.Items[Item.Parent.Count - 1 - i].Visible then begin
if Item.Parent.Items[Item.Parent.Count - 1 - i] = Item then Result := True;
Break
end;
end;
begin
if (FOwner = nil) or not (TsSkinManager(FOwner).Active) then Exit;
Item := TMenuItem(Sender);
Wnd := Item.GetParentMenu.WindowHandle;
if Wnd <> 0 then begin
RTLReading := GetWindowLong(Wnd, GWL_EXSTYLE) and WS_EX_RTLREADING = WS_EX_RTLREADING;
RTL := GetWindowLong(Wnd, GWL_EXSTYLE) and WS_EX_RIGHT = WS_EX_RIGHT;
end
else begin
RTLReading := False;
RTL := False;
end;
Br := integer(not Breaked(Item));
if TempControl <> nil then begin
if ShowHintStored then Application.ShowHint := AppShowHint;
SendAMessage(TControl(TempControl), WM_MOUSELEAVE);
TempControl := nil;
end;
try
if IsNT then Wnd := WindowFromDC(ACanvas.Handle) else Wnd := 0;
if Wnd <> 0 then GetWindowRect(Wnd, R) else begin
R.TopLeft := Point(0, 0);
R.Right := ParentWidth(ACanvas, Item) + BorderWidth * 2;
R.Bottom := ParentHeight(ACanvas, Item) + BorderWidth * 2;
end;
mi := GetMenuInfo(Item, WidthOf(R), HeightOf(R), Wnd);
BGImage := mi.Bmp; // !
if IsNT and (Wnd <> 0) then begin
NewDC := GetWindowDC(Wnd);
if (BGImage <> nil) and (BGImage.Canvas.Handle <> 0) then try
if IsTopVisible(Item) then // First item
BitBlt(NewDC, 0, 0, BGImage.Width, BorderWidth, BGImage.Canvas.Handle, 0, 0, SRCCOPY);
if IsBtmVisible(Item) then // Last item
BitBlt(NewDC, 0, BGImage.Height - BorderWidth, BGImage.Width, BorderWidth, BGImage.Canvas.Handle, 0, BGImage.Height - BorderWidth, SRCCOPY);
// Left border
BitBlt(NewDC, 0, aRect.Top + BorderWidth, ExtraWidth(mi) * Br + max(SkinBorderWidth, BorderWidth), HeightOf(aRect),
BGImage.Canvas.Handle, 0, aRect.Top + BorderWidth, SRCCOPY);
// Right border
BitBlt(NewDC, BGImage.Width - BorderWidth, aRect.Top + BorderWidth, BorderWidth, HeightOf(aRect),
BGImage.Canvas.Handle, BGImage.Width - BorderWidth, aRect.Top + BorderWidth, SRCCOPY);
finally
ReleaseDC(Wnd, NewDC);
end;
end;
if (Wnd = 0) then begin
if (Application.Handle <> 0) then begin
if not PeekMessage(aMsg, Application.Handle, WM_DRAWMENUBORDER, WM_DRAWMENUBORDER2, PM_NOREMOVE)
then PostMessage(Application.Handle, WM_DRAWMENUBORDER, 0, Integer(Item));
end
else begin
{ if GetMenuItemRect(PopupList.Window, Item.Parent.Handle, Item.MenuIndex, R) then begin
Wnd := WindowFromPoint(Point(r.Left + WidthOf(r) div 2, r.Top + HeightOf(r) div 2));
if (Wnd <> 0)
then DefaultManager.SkinableMenus.DrawWndBorder(Wnd, BGImage);
end; problem of LC, must be checked}
end;
end;
if Item.IsLine then begin
PaintDivider(aCanvas, aRect, Item, BGImage, mi);
Exit;
end
else if IsDivText(Item) then begin
mi := GetMenuInfo(Item, WidthOf(R), HeightOf(R), Wnd);
PaintCaption(aCanvas, aRect, Item, BGImage, mi);
Exit;
end;
it := smNormal;
if BGImage = nil then Exit;
// Check for multi-columned menus...
if (Item.MenuIndex < Item.Parent.Count - 1) then begin
if (Item.Parent.Items[Item.MenuIndex + 1].Break <> mbNone)
then BitBlt(ACanvas.Handle, aRect.Left, aRect.Bottom, WidthOf(aRect), BGImage.Height - 6 - aRect.Bottom, BGImage.Canvas.Handle, aRect.Left + 3, aRect.Bottom + 3, SrcCopy);
end
else if aRect.Bottom < BGImage.Height - 6
then BitBlt(ACanvas.Handle, aRect.Left, aRect.Bottom, WidthOf(aRect), BGImage.Height - 6 - aRect.Bottom, BGImage.Canvas.Handle, aRect.Left + 3, aRect.Bottom + 3, SrcCopy);
if (Item.Break <> mbNone) then begin
BitBlt(ACanvas.Handle, aRect.Left - 4, aRect.Top, 4, BGImage.Height - 6, BGImage.Canvas.Handle, aRect.Left - 1, aRect.Top + 3, SrcCopy);
end; //
ItemBmp := CreateBmp32(max(WidthOf(aRect, True) - ExtraWidth(mi) * Br, 0), HeightOf(aRect, True));
// Draw MenuItem
i := TsSkinManager(FOwner).GetSkinIndex(s_MenuItem);
// if odSelected in State
// then ItemBmp.Width := ItemBmp.Width;
if TsSkinManager(FOwner).IsValidSkinIndex(i) then begin
ci := MakeCacheInfo(BGImage, 3, 3);
PaintItem(i, s_MenuItem, ci, True, integer(Item.Enabled and (odSelected in State)), Rect(0, 0, ItemBmp.Width, HeightOf(aRect)),
Point(aRect.Left + ExtraWidth(mi) * Br, aRect.Top), ItemBmp.Canvas.Handle, FOwner);
end;
if odChecked in State then begin
if Item.Bitmap.Empty and ((Item.GetImageList = nil) or (Item.ImageIndex < 0)) then begin
if Item.RadioItem
then j := TsSkinManager(FOwner).GetMaskIndex(s_GlobalInfo, s_RadioButtonChecked)
else j := TsSkinManager(FOwner).GetMaskIndex(s_GlobalInfo, s_CheckGlyph);
if j = -1 then j := TsSkinManager(FOwner).GetMaskIndex(s_GlobalInfo, s_CheckBoxChecked);
if j > -1 then begin
cRect.Top := 0;
cRect.Bottom := HeightOfImage(TsSkinManager(FOwner).ma[j]);
if RTL then begin
cRect.Right := ItemBmp.Width - 2;
cRect.Left := cRect.Right - WidthOfImage(TsSkinManager(FOwner).ma[j]);
end
else begin
cRect.Left := 0;
cRect.Right := WidthOfImage(TsSkinManager(FOwner).ma[j]);
end;
OffsetRect(cRect, Margin, (HeightOf(aRect) - cRect.Bottom) div 2);
DrawSkinGlyph(ItemBmp, cRect.TopLeft, integer(Item.Enabled and (odSelected in State)), 1, TsSkinManager(FOwner).ma[j], MakeCacheInfo(ItemBmp))
end
end
end;
if not Item.Bitmap.Empty then begin
gRect.Top := (ItemBmp.Height - GlyphSize(Item, False).cy) div 2;
if RTL
then gRect.Left := ARect.Right - gRect.Top - GlyphSize(Item, False).cx - ExtraWidth(mi)
else gRect.Left := gRect.Top;
gRect.Bottom := gRect.top + Item.Bitmap.Height;
gRect.Right := gRect.Left + Item.Bitmap.Width;
if odChecked in State then begin
j := TsSkinManager(FOwner).GetSkinIndex(s_SpeedButton_Small);
if j > -1 then begin
CI.Bmp := ItemBmp;
InflateRect(gRect, 1, 1);
CI.X := 0;
CI.Y := 0;
CI.Ready := True;
PaintItem(j, s_SpeedButton_Small, CI, True, 2, gRect, Point(0, 0), ItemBmp, TsSkinManager(FOwner));
InflateRect(gRect, -1, -1);
end;
end;
if Item.Bitmap.PixelFormat = pf32bit then begin
CopyByMask(Rect(gRect.Left, gRect.Top, gRect.Left + Item.Bitmap.Width, gRect.Top + Item.Bitmap.Height),
Rect(0, 0, Item.Bitmap.Width, Item.Bitmap.Height), ItemBmp, Item.Bitmap, EmptyCI, False);
end
else ItemBmp.Canvas.Draw(gRect.Left, gRect.Top, Item.Bitmap);
end
else if (Item.GetImageList <> nil) and (Item.ImageIndex >= 0) then begin
gRect.Top := (ItemBmp.Height - Item.GetImageList.Height) div 2;
if RTL
then gRect.Left := ItemBmp.Width - gRect.Top - GlyphSize(Item, False).cx// - ExtraWidth(mi)
else gRect.Left := gRect.Top;
gRect.Bottom := gRect.top + Item.GetImageList.Height;
gRect.Right := gRect.Left + Item.GetImageList.Width;
if odChecked in State then begin
j := TsSkinManager(FOwner).GetSkinIndex(s_SpeedButton_Small);
if j > -1 then begin
CI := MakeCacheInfo(ItemBmp);
InflateRect(gRect, 1, 1);
PaintItem(j, s_SpeedButton_Small, CI, True, 2, gRect, Point(0, 0), ItemBmp, TsSkinManager(FOwner));
InflateRect(gRect, -1, -1);
end;
end;
Item.GetImageList.Draw(ItemBmp.Canvas, gRect.Left, gRect.Top, Item.ImageIndex, True);
end
else if (Item.GetParentMenu <> nil) and (Item.GetParentMenu.Name = s_SysMenu) then begin
gChar := #0;
ItemBmp.Canvas.Font.Name := s_Webdings;
ItemBmp.Canvas.Font.Style := [];
ItemBmp.Canvas.Font.Size := 10;
case Item.Tag of
SC_MINIMIZE : gChar := '0';
SC_MAXIMIZE : gChar := '1';
SC_RESTORE : gChar := '2';
SC_CLOSE : gChar := 'r'
end;
if gChar <> #0 then begin
j := ItemBmp.Canvas.TextHeight(gChar);
gRect.Top := (ItemBmp.Height - j) div 2;
gRect.Bottom := gRect.Top + j;
if RTL then begin
gRect.Right := aRect.Right - 4;
gRect.Left := gRect.Right - j;
DrawStyle := DT_RIGHT;
end
else begin
gRect.Left := 4;
gRect.Right := gRect.Left + j + 10;
DrawStyle := 0;
end;
sGraphUtils.acWriteTextEx(ItemBmp.Canvas, PacChar(gChar), True, gRect, DrawStyle, i, (Item.Enabled and ((odSelected in State) or (odHotLight in State))), FOwner);
end;
end;
// Text writing
if Assigned(CustomMenuFont) then ItemBmp.Canvas.Font.Assign(CustomMenuFont) else if Assigned(Screen.MenuFont) then ItemBmp.Canvas.Font.Assign(Screen.MenuFont);
f := GetOwnerForm(Item.GetParentMenu);
if f <> nil then ItemBmp.Canvas.Font.Charset := f.Font.Charset;
if odDefault in State then ItemBmp.Canvas.Font.Style := [fsBold];
R := TextRect;
{$IFDEF TNTUNICODE}
if Sender is TTntMenuItem then Text := TTntMenuItem(Sender).Caption else Text := TMenuItem(Sender).Caption;
{$ELSE}
Text := Item.Caption;
{$ENDIF}
if (Text <> '') and (Text[1] = #8) then begin
Delete(Text, 1, 1);
Text := Text + ' ';
DrawStyle := AlignToInt[taRightJustify];
end
else DrawStyle := AlignToInt[Alignment];
DrawStyle := DrawStyle or DT_EXPANDTABS or DT_SINGLELINE or DT_VCENTER or DT_NOCLIP;
if RTL then begin
DrawStyle := DrawStyle or DT_RIGHT;
dec(R.Right, ExtraWidth(mi));
end;
if odNoAccel in State then DrawStyle := DrawStyle or DT_HIDEPREFIX;
if RTLReading then DrawStyle := DrawStyle or DT_RTLREADING;
sGraphUtils.acWriteTextEx(ItemBmp.Canvas, PacChar(Text), True, R, DrawStyle, i, (Item.Enabled and ((odSelected in State) or (odHotLight in State))), FOwner);
Text := ShortCutToText(TMenuItem(Sender).ShortCut);
DrawStyle := DT_SINGLELINE or DT_VCENTER or DT_LEFT;
if Text <> '' then begin
r := ShortCutRect(Text);
dec(r.Right, 8);
OffsetRect(R, -ExtraWidth(mi), 0);
sGraphUtils.acWriteTextEx(ItemBmp.Canvas, PacChar(Text), True, R, DrawStyle, i, (Item.Enabled and ((odSelected in State) or (odHotLight in State))), FOwner);
end;
{
if (Item.Count > 0) and not (Item.GetParentMenu is TMainMenu) then begin // Paint arrow
ItemBmp.Canvas.Font.Name := s_Webdings;
ItemBmp.Canvas.Font.Style := [];
ItemBmp.Canvas.Font.Size := 10;
gChar := #52; // >
j := ItemBmp.Canvas.TextHeight(gChar);
gRect.Top := (ItemBmp.Height - j) div 2;
gRect.Bottom := gRect.Top + j;
if SysLocale.MiddleEast and (Item.GetParentMenu.BiDiMode = bdRightToLeft) then begin
gChar := #51; // <
gRect.Left := 4;
end
else begin
gRect.Left := ItemBmp.Width - gRect.Top - 15;
end;
gRect.Right := gRect.Left + j + 10;
DrawStyle := 0;
sGraphUtils.acWriteTextEx(ItemBmp.Canvas, PacChar(gChar), True, gRect, DrawStyle, i, (Item.Enabled and ((odSelected in State) or (odHotLight in State))), FOwner);
end;
}
if Assigned(FOnDrawItem) then FOnDrawItem(Item, ItemBmp.Canvas, Rect(0, 0, ItemBmp.Width, ItemBmp.Height), State, it);
if not Item.Enabled then begin
R := aRect;
OffsetRect(R, BorderWidth + ExtraWidth(mi) * Br, BorderWidth);
BlendTransRectangle(ItemBmp, 0, 0, BGImage, R, DefDisabledBlend);
end;
BitBlt(ACanvas.Handle, aRect.Left + ExtraWidth(mi) * Br, aRect.Top, ItemBmp.Width, ItemBmp.Height, ItemBmp.Canvas.Handle, 0, 0, SrcCopy);
if (Item = Item.Parent.Items[0]) and (ExtraWidth(mi) > 0) then begin
if not IsNT or (Win32MajorVersion >= 6) then begin
BitBlt(ACanvas.Handle, 0, 0, ExtraWidth(mi) * Br, BGImage.Height, BGImage.Canvas.Handle, 3, 3, SRCCOPY);
end;
end;
FreeAndNil(ItemBmp);
finally
end;
if Assigned(Item.OnDrawItem) then Item.OnDrawItem(Item, ACanvas, ARect, odSelected in State);
end;
procedure TsSkinableMenus.InitItems(A: boolean);
var
i : integer;
procedure ProcessComponent(c: TComponent);
var
i: integer;
begin
if (c <> nil) then begin
if (c is TMainMenu) then begin
InitMenuLine(TMainMenu(c), A);
for i := 0 to TMainMenu(c).Items.Count - 1 do HookItem(TMainMenu(c).Items[i], A and TsSkinManager(FOwner).SkinnedPopups);
end
else begin
if (c is TPopupMenu)
then HookPopupMenu(TPopupMenu(c), A and TsSkinManager(FOwner).SkinnedPopups)
else if (c is TMenuItem) then if not (TMenuItem(c).GetParentMenu is TMainMenu) then HookItem(TMenuItem(c), A and TsSkinManager(FOwner).SkinnedPopups);
end;
for i := 0 to c.ComponentCount - 1 do ProcessComponent(c.Components[i]);
end;
end;
begin
FActive := A;
if (csDesigning in Fowner.ComponentState) then Exit;
for i := 0 to Application.ComponentCount - 1 do ProcessComponent(Application.Components[i]);
end;
procedure TsSkinableMenus.HookItem(MenuItem: TMenuItem; FActive: boolean);
var
i : integer;
procedure HookSubItems(Item: TMenuItem);
var
i : integer;
begin
for i := 0 to Item.Count - 1 do begin
if FActive then begin
if not IsTopLine(Item.Items[i]) then begin
if not Assigned(Item.Items[i].OnAdvancedDrawItem) then Item.Items[i].OnAdvancedDrawItem := sAdvancedDrawItem;
if not Assigned(Item.Items[i].OnMeasureItem) then Item.Items[i].OnMeasureItem := sMeasureItem;
end;
end
else begin
if addr(Item.Items[i].OnAdvancedDrawItem) = addr(TsSkinableMenus.sAdvancedDrawItem) then Item.Items[i].OnAdvancedDrawItem := nil;
if addr(Item.Items[i].OnMeasureItem) = addr(TsSkinableMenus.sMeasureItem) then Item.Items[i].OnMeasureItem := nil;
end;
HookSubItems(Item.Items[i]);
end;
end;
begin
for i := 0 to MenuItem.Count - 1 do begin
if FActive then begin
if not IsTopLine(MenuItem.Items[i]) then begin
if not Assigned(MenuItem.Items[i].OnAdvancedDrawItem) then MenuItem.Items[i].OnAdvancedDrawItem := sAdvancedDrawItem;
if not Assigned(MenuItem.Items[i].OnMeasureItem) then MenuItem.Items[i].OnMeasureItem := sMeasureItem;
end;
end
else begin
if (addr(MenuItem.Items[i].OnAdvancedDrawItem) = addr(TsSkinableMenus.sAdvancedDrawItem)) then MenuItem.Items[i].OnAdvancedDrawItem := nil;
if (addr(MenuItem.Items[i].OnMeasureItem) = addr(TsSkinableMenus.sMeasureItem)) then MenuItem.Items[i].OnMeasureItem := nil;
end;
HookSubItems(MenuItem.Items[i]);
end;
end;
procedure TsSkinableMenus.SetActive(const Value: boolean);
begin
if FActive <> Value then begin
FActive := Value;
InitItems(Value);
end
end;
procedure TsSkinableMenus.sMeasureItem(Sender: TObject; ACanvas: TCanvas; var Width, Height: Integer);
var
Text : acString;
Item : TMenuItem;
R : TRect;
f : TCustomForm;
mi : TacMenuInfo;
begin
if csDestroying in TComponent(Sender).ComponentState then Exit;
acCanHookMenu := True;
Item := TMenuItem(Sender);
mi := GetMenuInfo(Item, 0, 0);
if Item.Caption = cLineCaption then it := smDivider else if IsdivText(Item) then it := smCaption else it := smNormal;
if mi.FirstItem = nil then begin // if not defined still
mi.FirstItem := Item.Parent.Items[0];
if not Measuring and not (csDesigning in TsSkinManager(FOwner).ComponentState) then begin
if (mi.FirstItem.Name <> s_SkinSelectItemName) then begin
Measuring := True;
ExtraSection := s_MenuExtraLine;
if ExtraGlyph <> nil then FreeAndNil(ExtraGlyph);
ExtraCaption := DontForget;
mi.HaveExtraLine := True;
if Assigned(TsSkinManager(FOwner).OnGetMenuExtraLineData) then TsSkinManager(FOwner).OnGetMenuExtraLineData(mi.FirstItem, ExtraSection, ExtraCaption, ExtraGlyph, mi.HaveExtraLine);
ExtraCaption := DelChars(ExtraCaption, '&');
if not mi.HaveExtraLine and Assigned(ExtraGlyph) then FreeAndNil(ExtraGlyph);
Measuring := False;
end else mi.HaveExtraLine := False;
end;
end;
if Assigned(CustomMenuFont) then ACanvas.Font.Assign(CustomMenuFont) else if Assigned(Screen.MenuFont) then ACanvas.Font.Assign(Screen.MenuFont);
f := GetOwnerForm(Item.GetParentMenu);
if f <> nil then ACanvas.Font.Charset := f.Font.Charset;
if Item.Default then ACanvas.Font.Style := ACanvas.Font.Style + [fsBold];
case it of
smDivider : Text := '';
smCaption : Text := cLineCaption + Item.Caption + cLineCaption;
else Text := Item.Caption + iff(ShortCutToText(Item.ShortCut) = '', '', ShortCutToText(Item.ShortCut));
end;
R := Rect(0, 0, 1, 0);
{$IFDEF TNTUNICODE}
if Sender is TTntMenuItem
then Tnt_DrawTextW(ACanvas.Handle, PacChar(Text), Length(Text), R, DT_EXPANDTABS or DT_SINGLELINE or DT_NOCLIP or DT_CALCRECT)
else
{$ENDIF}
acDrawText(ACanvas.Handle, PacChar(Text), R, DT_EXPANDTABS or DT_SINGLELINE or DT_NOCLIP or DT_CALCRECT);
Width := Margin * 3 + WidthOf(R) + GlyphSize(Item, False).cx * 2 + Spacing;
if mi.HaveExtraLine and not Breaked(Item) then inc(Width, ExtraWidth(mi));
Height := GetItemHeight(aCanvas, Item);
end;
destructor TsSkinableMenus.Destroy;
begin
FOwner := nil;
if Assigned(FCaptionfont) then FreeAndNil(FCaptionFont);
inherited Destroy;
end;
// Refresh list of all MenuItems on project
procedure TsSkinableMenus.UpdateMenus;
begin
SetActive(TsSkinManager(FOwner).SkinData.Active);
end;
// Return height of the menu panel
function TsSkinableMenus.ParentHeight(aCanvas: TCanvas; Item: TMenuItem): integer;
var
i, ret : integer;
begin
Result := 0;
ret := 0;
for i := 0 to Item.Parent.Count - 1 do if Item.Parent.Items[i].Visible then begin
if Item.Parent.Items[i].Break <> mbNone then begin
Result := max(Result, ret);
ret := GetItemHeight(aCanvas, Item.Parent.Items[i]);
end
else inc(ret, GetItemHeight(aCanvas, Item.Parent.Items[i]));
end;
Result := max(Result, ret);
end;
// Return height of the current MenuItem
function TsSkinableMenus.GetItemHeight(aCanvas: TCanvas; Item: TMenuItem): integer;
var
Text: string;
IsDivider : boolean;
begin
IsDivider := Item.Caption = cLineCaption;
if IsDivider then Text := '' else if IsDivText(Item) then begin
Text := Item.Caption;
end
else begin
Text := Item.Caption + iff(ShortCutToText(Item.ShortCut) = '', '', ShortCutToText(Item.ShortCut));
end;
if Assigned(CustomMenuFont) then ACanvas.Font.Assign(CustomMenuFont) else if Assigned(Screen.MenuFont) then ACanvas.Font.Assign(Screen.MenuFont);
if IsDivider then begin
Result := 2;
end
else if IsDivText(Item) then begin
Result := Round(ACanvas.TextHeight('W') * 1.25) + 2 * Margin;
end
else begin
Result := Maxi(Round(ACanvas.TextHeight('W') * 1.25), GlyphSize(Item, False).cy) + 2 * Margin;
end;
end;
function TsSkinableMenus.IsDivText(Item: TMenuItem): boolean;
begin
Result := (copy(Item.Caption, 1, 1) = cLineCaption) and (copy(Item.Caption, length(Item.Caption), 1) = cLineCaption);
end;
procedure TsSkinableMenus.SetAlignment(const Value: TAlignment);
begin
if FAlignment <> Value then begin
FAlignment := Value;
end;
end;
function TsSkinableMenus.IsTopLine(Item: TMenuItem): boolean;
var
i : integer;
m : TMenu;
begin
Result := False;
m := Item.GetParentMenu;
if m is TMainMenu then for i := 0 to m.Items.Count - 1 do if m.Items[i] = Item then begin
Result := True;
Exit;
end;
end;
procedure TsSkinableMenus.SetBevelWidth(const Value: integer);
begin
FBevelWidth := Value;
end;
procedure TsSkinableMenus.SetBorderWidth(const Value: integer);
begin
FBorderWidth := Value;
end;
function TsSkinableMenus.CursorMarginH: integer;
begin
Result := BorderWidth;
end;
function TsSkinableMenus.CursorMarginV: integer;
begin
Result := 0;
end;
function TsSkinableMenus.ItemRect(Item : TMenuItem; aRect: TRect): TRect;
begin
Result := aRect;
if Item.Parent.Items[0] = Item then Result.Top := Result.Top + CursorMarginV;
if Item.Parent.Items[Item.Parent.Count - 1] = Item then Result.Bottom := Result.Bottom - CursorMarginV;
Result.Left := Result.Left + CursorMarginH;
Result.Right := Result.Right - CursorMarginH;
end;
procedure TsSkinableMenus.PaintDivider(aCanvas : TCanvas; aRect : TRect; Item: TMenuItem; MenuBmp : TBitmap; mi : TacMenuInfo);
var
SkinIndex, BorderIndex : integer;
nRect : TRect;
s : string;
CI : TCacheInfo;
TempBmp : TBitmap;
begin
s := s_DIVIDERV;
SkinIndex := TsSkinManager(FOwner).GetSkinIndex(s);
BorderIndex := TsSkinManager(FOwner).GetMaskIndex(SkinIndex, s, s_BordersMask);
nRect := aRect;
OffsetRect(nRect, -nRect.Left + Margin + ExtraWidth(mi) + Spacing, -nRect.Top);
dec(nRect.Right, Margin + Margin + ExtraWidth(mi) + Spacing);
if nRect.Left < (IcoLineWidth + ExtraWidth(mi)) then nRect.Left := IcoLineWidth + ExtraWidth(mi) + 2;
if BorderIndex > -1 then begin
TempBmp := CreateBmp32(WidthOf(aRect), HeightOf(aRect));
if MenuBmp <> nil
then BitBlt(TempBmp.Canvas.Handle, 0, 0, WidthOf(aRect), HeightOf(aRect), MenuBmp.Canvas.Handle, aRect.Left + 3, aRect.Top + 3, SRCCOPY);
CI := MakeCacheInfo(TempBmp);
DrawSkinRect(TempBmp, nRect, True, CI, TsSkinManager(FOwner).ma[BorderIndex], 0, True, TsSkinManager(FOwner));
BitBlt(aCanvas.Handle, aRect.Left, aRect.Top, WidthOf(aRect), HeightOf(aRect), TempBmp.Canvas.Handle, 0, 0, SRCCOPY);
FreeAndnil(TempBmp);
end
else begin
BitBlt(aCanvas.Handle, aRect.Left, aRect.Top, WidthOf(aRect), HeightOf(aRect), MenuBmp.Canvas.Handle, aRect.Left + 3, aRect.Top + 3, SRCCOPY);
if TsSkinManager(FOwner).SkinData.BorderColor <> clFuchsia then aCanvas.Pen.Color := TsSkinManager(FOwner).SkinData.BorderColor else aCanvas.Pen.Color := clBtnShadow;
aCanvas.Pen.Style := psSolid;
aCanvas.MoveTo(nRect.Left, aRect.Top);
aCanvas.LineTo(nRect.Right, aRect.Top);
end;
end;
procedure TsSkinableMenus.PaintCaption(aCanvas: TCanvas; aRect: TRect; Item : TMenuItem; BG : TBitmap; mi : TacMenuInfo);
var
i : integer;
ItemBmp : TBitmap;
s : acString;
SkinSection : string;
Flags : integer;
R : TRect;
begin
ItemBmp := CreateBmp32(WidthOf(aRect), HeightOf(aRect));
R := Rect(ExtraWidth(mi) + 1, 1, ItemBmp.Width - 1, ItemBmp.Height - 1);
SkinSection := s_ToolBAr;
i := TsSkinManager(FOwner).GetSkinIndex(SkinSection);
if ExtraWidth(mi) > 0 then
BitBlt(ItemBmp.Canvas.Handle, 0, 0, ExtraWidth(mi) + 1, ItemBmp.Height,
BG.Canvas.Handle, aRect.Left + 3, aRect.Top + 3, SRCCOPY);
BitBltBorder(ItemBmp.Canvas.Handle, 0, 0, ItemBmp.Width, ItemBmp.Height,
BG.Canvas.Handle, aRect.Left + 3, aRect.Top + 3, 1);
if TsSkinManager(FOwner).IsValidSkinIndex(i) then begin
PaintItem(i, SkinSection, MakeCacheInfo(BG, 3, 3), True, 0,
R, Point(aRect.Left + ExtraWidth(mi), aRect.Top), ItemBmp.Canvas.Handle, FOwner);
end;
if Assigned(FCaptionFont) then ItemBmp.Canvas.Font.Assign(FCaptionFont);
s := ExtractWord(1, Item.Caption, [cLineCaption]);
Flags := DT_SINGLELINE or DT_VCENTER or DT_CENTER or DT_HIDEPREFIX;
R := Rect(ExtraWidth(mi), 0, ItemBmp.Width, ItemBmp.Height);
acWriteTextEx(ItemBmp.Canvas, PacChar(s), True, R, Flags, i, False);
BitBlt(ACanvas.Handle, aRect.Left, aRect.Top, ItemBmp.Width, ItemBmp.Height,
ItemBmp.Canvas.Handle, 0, 0, SrcCopy);
FreeAndNil(ItemBmp);
end;
procedure TsSkinableMenus.SetCaptionFont(const Value: TFont);
begin
FCaptionFont.Assign(Value);
end;
type
TAccessProvider = class(TsSkinProvider);
procedure TsSkinableMenus.sAdvancedDrawLineItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; State: TOwnerDrawState);
var
{$IFDEF TNTUNICODE}
ws : WideString;
{$ENDIF}
R, gRect : TRect;
i, l, t: integer;
ci : TCacheInfo;
Item : TMenuItem;
sp : TAccessProvider;
Bmp : TBitmap;
f : TCustomForm;
Flags : cardinal;
ItemSelected : boolean;
function TextRect: TRect; begin
Result := aRect;
inc(Result.Left, Margin);
dec(Result.Right, Margin);
end;
function ShortCutRect: TRect; begin
Result := aRect;
Result.Left := WidthOf(TextRect);
end;
begin
if (Self = nil) or (FOwner = nil) {or not (Sender is TMenuItem) v7.22 }then begin
inherited;
Exit;
end;
Item := TMenuItem(Sender);
try
sp := TAccessProvider(SendAMessage(Item.GetParentMenu.WindowHandle, AC_GETPROVIDER));
except
sp := nil;
end;
if (sp = nil) and (MDISkinProvider <> nil) then sp := TAccessProvider(MDISkinProvider);
// if (sp <> nil) and (sp.Form.FormStyle = fsMDIChild) then sp := TAccessProvider(MDISkinProvider);
if sp = nil then inherited else begin
if sp.SkinData.FCacheBmp = nil then Exit;
// Calc rectangle for painting and defining a Canvas
Bmp := CreateBmp32(WidthOf(aRect, True), HeightOf(aRect, True));
gRect := Rect(0, 0, Bmp.Width, Bmp.Height);
// BG for menu item
CI := MakeCacheInfo(sp.MenuLineBmp);
// Calc real offset to menu item in cache
if ACanvas = sp.SkinData.FCacheBmp.Canvas then begin // If paint in form cache
if sp.BorderForm <> nil then begin
t := aRect.Top - sp.CaptionHeight(True) - sp.ShadowSize.Top;
// if sp.FSysExHeight then dec(t, 4);
end
else t := aRect.Top - SysCaptHeight(sp.Form) - SysBorderWidth(sp.Form.Handle, sp.BorderForm, False);
l := aRect.Left - sp.ShadowSize.Left - SysBorderWidth(sp.Form.Handle, sp.BorderForm);
end
else begin // If procedure was called by system (DRAWITEM)
if sp.BorderForm <> nil
then t := aRect.Top - sp.CaptionHeight(True) + DiffTitle(sp.BorderForm) + integer(sp.FSysExHeight) * 4
else t := aRect.Top - SysCaptHeight(sp.Form) + DiffTitle(sp.BorderForm) - SysBorderWidth(sp.Form.Handle, sp.BorderForm, False);
// if sp.FSysExHeight then dec(t, 4);
l := aRect.Left - SysBorderWidth(sp.Form.Handle, sp.BorderForm) + DiffBorder(sp.BorderForm);
end;
// Skin index for menu item
i := TsSkinManager(FOwner).GetSkinIndex(s_MenuItem);
ItemSelected := Item.Enabled and ((odSelected in State) or (odHotLight in State) or IsOpened(Item));// (Item.MenuIndex = acSelectedItem));
if TsSkinManager(FOwner).IsValidSkinIndex(i)
then PaintItem(i, s_MenuItem, ci, True, integer(ItemSelected), gRect, Point(l, t), Bmp, FOwner);
gRect.Left := 0;
gRect.Right := 0;
if not Item.Bitmap.Empty then begin
gRect.Top := (HeightOf(ARect) - GlyphSize(Item, False).cy) div 2;// + aRect.Top;
if SysLocale.MiddleEast and (Item.GetParentMenu.BiDiMode = bdRightToLeft)
then gRect.Left := Bmp.Width - 3 - Item.Bitmap.Width
else gRect.Left := 3;
gRect.Right := gRect.Left + Item.Bitmap.Width + 3;
if not Item.Enabled then OffsetRect(gRect, -gRect.Left + 3, -gRect.Top + 1);
Bmp.Canvas.Draw(gRect.Left, gRect.Top, Item.Bitmap);
end
else if (Item.GetImageList <> nil) and (Item.ImageIndex >= 0) then begin
gRect.Top := (HeightOf(ARect) - Item.GetImageList.Height) div 2;// + aRect.Top;
if SysLocale.MiddleEast and (Item.GetParentMenu.BiDiMode = bdRightToLeft)
then gRect.Left := Bmp.Width - 3 - Item.GetImageList.Width
else gRect.Left := 3;
gRect.Right := gRect.Left + Item.GetImageList.Width + 3; //!!!
Item.GetImageList.Draw(Bmp.Canvas, gRect.Left, gRect.Top, Item.ImageIndex, True);
end;
// Text writing
if Assigned(CustomMenuFont) then Bmp.Canvas.Font.Assign(CustomMenuFont) else if Assigned(Screen.MenuFont) then Bmp.Canvas.Font.Assign(Screen.MenuFont);
f := GetOwnerForm(Item.GetParentMenu);
if f <> nil then ACanvas.Font.Charset := f.Font.Charset;
if odDefault in State then Bmp.Canvas.Font.Style := [fsBold] else Bmp.Canvas.Font.Style := [];
R := TextRect;
if SysLocale.MiddleEast and (Item.GetParentMenu.BiDiMode = bdRightToLeft) then R.Left := R.Left - WidthOf(gRect) else R.Left := R.Left + WidthOf(gRect);
if Bmp <> nil then OffsetRect(R, -TextRect.Left + 2, -R.Top);
i := TsSkinManager(FOwner).GetSkinIndex(s_MenuLine);
Flags := DT_CENTER or DT_EXPANDTABS or DT_SINGLELINE or DT_VCENTER or DT_NOCLIP;
if sp.Form.UseRightToLeftReading then Flags := Flags or DT_RTLREADING;
if odNoAccel in State then Flags := Flags + DT_HIDEPREFIX;
{$IFDEF TNTUNICODE}
if Sender is TTntMenuItem then begin
ws := WideString(TTntMenuItem(Sender).Caption);
sGraphUtils.WriteTextExW(Bmp.Canvas, PWideChar(ws), True, R, Flags or AlignToInt[Alignment], i, ItemSelected, FOwner);
end
else
{$ENDIF}
if (sp.BorderForm <> nil) then begin
WriteText32(Bmp, PacChar(Item.Caption), True, R, Flags or AlignToInt[Alignment], i, ItemSelected, FOwner{$IFDEF TNTUNICODE}, True{$ENDIF});
end
else begin
sGraphUtils.WriteTextEx(Bmp.Canvas, PChar(Item.Caption), True, R, Flags or AlignToInt[Alignment], i, ItemSelected, FOwner);
end;
if Assigned(FOnDrawItem) then FOnDrawItem(Item, Bmp.Canvas, gRect, State, smTopLine);
if Assigned(Bmp) then begin
if not Item.Enabled then begin
R := Rect(l, t, l + Bmp.Width, t + Bmp.Width);
SumBmpRect(Bmp, sp.MenuLineBmp, IntToByte(Round(DefDisabledBlend * MaxByte)), R, Point(0, 0));
end;
BitBlt(ACanvas.Handle, aRect.Left, aRect.Top, Bmp.Width, Bmp.Height, Bmp.Canvas.Handle, 0, 0, SRCCOPY);
FreeAndNil(Bmp);
end;
end;
end;
procedure TsSkinableMenus.sMeasureLineItem(Sender: TObject; ACanvas: TCanvas; var Width, Height: Integer);
var
Text: acString;
Item: TMenuItem;
W : integer;
Menu : TMenu;
begin
Item := TMenuItem(Sender);
Height := GetSystemMetrics(SM_CYMENU) - 1;
if Assigned(CustomMenuFont) then ACanvas.Font.Assign(CustomMenuFont) else if Assigned(Screen.MenuFont) then ACanvas.Font.Assign(Screen.MenuFont);
Text := ReplaceStr(Item.Caption, '&', '');
W := ACanvas.TextWidth(Text);
Menu := Item.GetParentMenu;
if Assigned(Menu.Images) and (Item.ImageIndex > -1)
then inc(W, Menu.Images.Width + 6)
else if not Item.Bitmap.Empty then inc(W, Item.Bitmap.Width + 6);
// If last item (for a MDIChild buttons drawing)
if LastItem(Item) then inc(W, 40);
Width := W;
end;
procedure TsSkinableMenus.InitItem(Item: TMenuItem; A : boolean);
begin
if Item.GetParentMenu <> nil then Item.GetParentMenu.OwnerDraw := A;
if A then begin
if not IsTopLine(Item) then begin
if not TsSkinManager(FOwner).SkinnedPopups then Exit;
if not Assigned(Item.OnAdvancedDrawItem) then Item.OnAdvancedDrawItem := sAdvancedDrawItem;
if not Assigned(Item.OnMeasureItem) then Item.OnMeasureItem := sMeasureItem;
end
else begin
Item.OnAdvancedDrawItem := sAdvancedDrawLineItem;
Item.OnMeasureItem := sMeasureLineItem;
end;
end
else begin
if (addr(Item.OnAdvancedDrawItem) = addr(TsSkinableMenus.sAdvancedDrawItem)) then Item.OnAdvancedDrawItem := nil;
if (addr(Item.OnMeasureItem) = addr(TsSkinableMenus.sMeasureItem)) then Item.OnMeasureItem := nil;
end;
end;
procedure TsSkinableMenus.InitMenuLine(Menu: TMainMenu; A: boolean);
var
i : integer;
begin
if not Assigned(Menu) then Exit;
for i := 0 to Menu.Items.Count - 1 do begin
if A then begin
if TsSkinManager(FOwner).SkinData.Active then begin
if not TsSkinManager(FOwner).SkinnedPopups then Exit;
Menu.Items[i].OnAdvancedDrawItem := sAdvancedDrawLineItem;
Menu.Items[i].OnMeasureItem := sMeasureLineItem;
end;
end
else begin
if addr(Menu.Items[i].OnAdvancedDrawItem) = addr(TsSkinableMenus.sAdvancedDrawLineItem) then Menu.Items[i].OnAdvancedDrawItem := nil;
if addr(Menu.Items[i].OnMeasureItem) = addr(TsSkinableMenus.sMeasureLineItem) then Menu.Items[i].OnMeasureItem := nil;
end;
end;
if csDestroying in Menu.ComponentState then Exit;
Menu.OwnerDraw := A;
end;
procedure TsSkinableMenus.HookPopupMenu(Menu: TPopupMenu; Active: boolean);
var
i : integer;
procedure HookSubItems(Item: TMenuItem);
var
i : integer;
begin
for i := 0 to Item.Count - 1 do begin
if Active then begin
if not Assigned(Item.Items[i].OnAdvancedDrawItem) then
Item.Items[i].OnAdvancedDrawItem := sAdvancedDrawItem;
if not Assigned(Item.Items[i].OnMeasureItem) then
Item.Items[i].OnMeasureItem := sMeasureItem;
end
else begin
if addr(Item.Items[i].OnAdvancedDrawItem) = addr(TsSkinableMenus.sAdvancedDrawItem) then
Item.Items[i].OnAdvancedDrawItem := nil;
if addr(Item.Items[i].OnMeasureItem) = addr(TsSkinableMenus.sMeasureItem) then
Item.Items[i].OnMeasureItem := nil;
end;
HookSubItems(Item.Items[i]);
end;
end;
begin
Menu.OwnerDraw := Active and TsSkinManager(Self.FOwner).SkinnedPopups;
if Active then Menu.MenuAnimation := Menu.MenuAnimation + [maNone] else Menu.MenuAnimation := Menu.MenuAnimation - [maNone];
for i := 0 to Menu.Items.Count - 1 do begin
if Active then begin
if not Assigned(Menu.Items[i].OnAdvancedDrawItem) then
Menu.Items[i].OnAdvancedDrawItem := sAdvancedDrawItem;
if not Assigned(Menu.Items[i].OnMeasureItem) then
Menu.Items[i].OnMeasureItem := sMeasureItem;
end
else begin
if (addr(Menu.Items[i].OnAdvancedDrawItem) = addr(TsSkinableMenus.sAdvancedDrawItem))
then Menu.Items[i].OnAdvancedDrawItem := nil;
if (addr(Menu.Items[i].OnMeasureItem) = addr(TsSkinableMenus.sMeasureItem))
then Menu.Items[i].OnMeasureItem := nil;
end;
HookSubItems(Menu.Items[i]);
end;
end;
function TsSkinableMenus.LastItem(Item: TMenuItem): boolean;
begin
Result := False;
end;
function TsSkinableMenus.IsPopupItem(Item: TMenuItem): boolean;
var
mi : TMenu;
begin
mi := Item.GetParentMenu;
Result := mi is TPopupMenu;
end;
procedure ClearCache;
begin
DeleteUnusedBmps(True);
end;
{
function MenuWindowProc(Wnd: HWND; uMsg: integer; WParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
begin
case uMsg of
WM_NCPAINT : begin
Result := 1;
end;
WM_ERASEBKGND : begin
Result := 1;
end;
WM_DESTROY : begin
ClearCache;
Result := CallWindowProc(Pointer(GetWindowLong(Wnd, GWL_USERDATA)), wnd, uMsg, wParam, lParam);
end
else Result := CallWindowProc(Pointer(GetWindowLong(Wnd, GWL_USERDATA)), wnd, uMsg, wParam, lParam);
end;
end;
}
procedure TsSkinableMenus.DrawWndBorder(Wnd : hWnd; MenuBmp : TBitmap);
var
l, i : integer;
rgn, subRgn : hrgn;
begin
if BorderDrawing then Exit;
{ if GetWindowLong(Wnd, GWL_WNDPROC) <> Longint(@MenuWindowProc) then begin
SetWindowLong(Wnd, GWL_USERDATA, GetWindowLong(Wnd, GWL_WNDPROC));
SetWindowLong(Wnd, GWL_WNDPROC, Longint(@MenuWindowProc));
end;}
if IsNT and (MenuBmp <> nil) and (SendMessage(Wnd, SM_ALPHACMD, MakeWParam(0, AC_UPDATING), 0) = 0) then begin
SendMessage(Wnd, SM_ALPHACMD, MakeWParam(0, AC_DROPPEDDOWN), 0);
BorderDrawing := True;
l := Length(ArOR);
rgn := CreateRectRgn(0, 0, MenuBmp.Width, MenuBmp.Height);
if (l > 0) then begin
for i := 0 to l - 1 do begin
subrgn := CreateRectRgn(ArOR[i].Left, ArOR[i].Top, ArOR[i].Right, ArOR[i].Bottom);
CombineRgn(rgn, rgn, subrgn, RGN_DIFF);
DeleteObject(subrgn);
end;
end
else begin
subrgn := CreateRectRgn(0, 0, 1, 1);
CombineRgn(rgn, rgn, subrgn, RGN_DIFF);
DeleteObject(subrgn);
end;
SetWindowRgn(Wnd, rgn, True);
end;
BorderDrawing := False;
end;
function TsSkinableMenus.GetSkinBorderWidth: integer;
var
i : integer;
begin
if FSkinBorderWidth < 0 then begin
i := TsSkinManager(FOwner).GetMaskIndex(s_MainMenu, s_BordersMask);
if i > -1 then begin
FSkinBorderWidth := TsSkinManager(FOwner).ma[i].BorderWidth;
if FSkinBorderWidth < 1 then FSkinBorderWidth := 3;
end
else FSkinBorderWidth := 0;
end;
Result := FSkinBorderWidth;
end;
function TsSkinableMenus.ExtraWidth(mi : TacMenuInfo): integer;
begin
if TsSkinManager(FOwner).MenuSupport.UseExtraLine and mi.HaveExtraLine then begin
Result := TsSkinManager(FOwner).MenuSupport.ExtraLineWidth;
end
else Result := 0;
end;
function TsSkinableMenus.GetItemWidth(aCanvas: TCanvas; Item: TMenuItem; mi : TacMenuInfo): integer;
var
Text : string;
R : TRect;
begin
if Assigned(CustomMenuFont) then ACanvas.Font.Assign(CustomMenuFont) else if Assigned(Screen.MenuFont) then ACanvas.Font.Assign(Screen.MenuFont);
case it of
smDivider : begin
Text := '';
Result := Margin * 3 + ACanvas.TextWidth(Text) + GlyphSize(Item, False).cx * 2 + Spacing;
end;
smCaption : begin
Text := cLineCaption + Item.Caption + cLineCaption;
Result := Margin * 3 + ACanvas.TextWidth(Text) + GlyphSize(Item, False).cx * 2 + Spacing;
end
else begin
Text := Item.Caption + iff(ShortCutToText(Item.ShortCut) = '', '', ShortCutToText(Item.ShortCut));
R := Rect(0, 0, 1, 0);
DrawText(ACanvas.Handle, PChar(Text), Length(Text), R, DT_EXPANDTABS or DT_SINGLELINE or DT_NOCLIP or DT_CALCRECT);
Result := WidthOf(R) + Margin * 3 + GlyphSize(Item, False).cx * 2 + Spacing;
end;
end;
if mi.HaveExtraLine then inc(Result, ExtraWidth(mi));
end;
function TsSkinableMenus.ParentWidth(aCanvas: TCanvas; Item: TMenuItem): integer;
var
i, OldRes, w, h : integer;
it : TMenuItem;
begin
Result := 0;
OldRes := 0;
for i := 0 to Item.Parent.Count - 1 do if Item.Parent.Items[i].Visible then begin
it := Item.Parent.Items[i];
if it.Break <> mbNone then begin
inc(OldRes, Result + 4{?});
Result := 0;
end;
w := 0;
h := 0;
sMeasureItem(it, aCanvas, w, h);
Result := max(Result, w + 12);
end;
inc(Result, OldRes);
end;
function TsSkinableMenus.PrepareMenuBG(Item: TMenuItem; Width, Height : integer; Wnd : hwnd = 0) : TBitmap;
var
R, gRect : TRect;
i, j, w, Marg : integer;
CI : TCacheInfo;
ItemBmp : TBitmap;
VertFont : TLogFont;
pFont : PLogFontA;
f : TCustomForm;
mi : TacMenuInfo;
procedure MakeVertFont(Orient : integer);
begin
ItemBmp.Canvas.Font.Assign(TsSkinManager(FOwner).MenuSupport.ExtraLineFont);
f := GetOwnerForm(Item.GetParentMenu);
if f <> nil then ItemBmp.Canvas.Font.Charset := f.Font.Charset;
pFont := PLogFontA(@VertFont);
StrPCopy(VertFont.lfFaceName, TsSkinManager(FOwner).MenuSupport.ExtraLineFont.Name);
GetObject(ItemBmp.Canvas.Handle, SizeOf(TLogFont), pFont);
VertFont.lfEscapement := Orient;
VertFont.lfHeight := TsSkinManager(FOwner).MenuSupport.ExtraLineFont.Size;
VertFont.lfStrikeOut := integer(fsStrikeOut in TsSkinManager(FOwner).MenuSupport.ExtraLineFont.Style);
VertFont.lfItalic := integer(fsItalic in TsSkinManager(FOwner).MenuSupport.ExtraLineFont.Style);
VertFont.lfUnderline := integer(fsUnderline in TsSkinManager(FOwner).MenuSupport.ExtraLineFont.Style);
VertFont.lfWeight := FW_NORMAL;
VertFont.lfCharSet := TsSkinManager(FOwner).MenuSupport.ExtraLineFont.Charset;
VertFont.lfWidth := 0;
Vertfont.lfOutPrecision := OUT_DEFAULT_PRECIS;
VertFont.lfClipPrecision := CLIP_DEFAULT_PRECIS;
VertFont.lfOrientation := VertFont.lfEscapement;
VertFont.lfPitchAndFamily := Default_Pitch;
VertFont.lfQuality := Default_Quality;
ItemBmp.Canvas.Font.Handle := CreateFontIndirect(VertFont);
ItemBmp.Canvas.Font.Color := TsSkinManager(FOwner).gd[j].FontColor[1];
end;
begin
Result := nil;
if not (csDesigning in TsSkinManager(FOwner).ComponentState) then begin
if (Item.Parent.Items[0].Name <> s_SkinSelectItemName) then begin
ExtraSection := s_MenuExtraLine;
if ExtraGlyph <> nil then FreeAndNil(ExtraGlyph);
ExtraCaption := DontForget;
mi.HaveExtraLine := True;
if Assigned(TsSkinManager(FOwner).OnGetMenuExtraLineData) then TsSkinManager(FOwner).OnGetMenuExtraLineData(Item.Parent.Items[0], ExtraSection, ExtraCaption, ExtraGlyph, mi.HaveExtraLine);
ExtraCaption := DelChars(ExtraCaption, '&');
if not mi.HaveExtraLine and Assigned(ExtraGlyph) then FreeAndNil(ExtraGlyph);
end
else mi.HaveExtraLine := False;
end;
mi.FirstItem := Item.Parent.Items[0];
mi.Wnd := Wnd;
mi.Bmp := CreateBmp32(Width, Height);
mi.Bmp.Canvas.Lock;
gRect := Rect(0, 0, Width, Height);
i := TsSkinManager(FOwner).GetSkinIndex(s_MainMenu);
// Draw Menu
GlyphSizeCX := GlyphSize(Item, false).cx;
IcoLineWidth := GlyphSizeCX + Margin + Spacing;
if TsSkinManager(FOwner).IsValidSkinIndex(i) then begin
// Background
PaintItemBG(i, s_MainMenu, EmptyCI, 0, gRect, Point(0, 0), mi.Bmp, FOwner);
ci := MakeCacheInfo(mi.Bmp);
// Ico line painting
if GetWindowLong(Item.GetParentMenu.WindowHandle, GWL_EXSTYLE) and WS_EX_RIGHT <> WS_EX_RIGHT then begin
j := TsSkinManager(FOwner).GetSkinIndex(TsSkinManager(FOwner).MenuSupport.IcoLineSkin);
if j > -1 then begin // Ico line
ItemBmp := CreateBmp32(IcoLineWidth, Mi.Bmp.Height - SkinBorderWidth * 2);
PaintItem(j, TsSkinManager(FOwner).MenuSupport.IcoLineSkin, ci, True, 0, Rect(0, 0, ItemBmp.Width, ItemBmp.Height), Point(SkinBorderWidth + ExtraWidth(mi), SkinBorderWidth), ITemBmp, FOwner);
BitBlt(mi.Bmp.Canvas.Handle, SkinBorderWidth + ExtraWidth(mi), SkinBorderWidth, ItemBmp.Width, ItemBmp.Height, ItemBmp.Canvas.Handle, 0, 0, SrcCopy);
FreeAndNil(ItemBmp);
end;
end;
// Border
j := TsSkinManager(FOwner).GetMaskIndex(i, s_MainMenu, s_BordersMask);
if TsSkinManager(FOwner).IsValidImgIndex(j) then DrawSkinRect(mi.Bmp, gRect, False, MakeCacheInfo(mi.Bmp), TsSkinManager(FOwner).ma[j], 0, False);
// Extra line painting
if TsSkinManager(FOwner).MenuSupport.UseExtraLine and mi.HaveExtraLine then begin
j := TsSkinManager(FOwner).GetSkinIndex(ExtraSection);
if j > -1 then begin // Extra line
ItemBmp := CreateBmp32(TsSkinManager(FOwner).MenuSupport.ExtraLineWidth, mi.Bmp.Height - SkinBorderWidth * 2);
R := Rect(0, 0, ItemBmp.Width, ItemBmp.Height);
PaintItem(j, ExtraSection, ci, True, 0, R, Point(SkinBorderWidth, SkinBorderWidth), ItemBmp, FOwner);
Marg := 12;
if ExtraGlyph <> nil then begin
inc(Marg, ExtraGlyph.Height + 8);
ItemBmp.Canvas.Draw((ItemBmp.Width - ExtraGlyph.Width) div 2, ItemBmp.Height - 12 - ExtraGlyph.Height, ExtraGlyph);
end;
if ExtraCaption <> '' then begin
MakeVertFont(-2700);
w := ItemBmp.Canvas.TextHeight(ExtraCaption);
ItemBmp.Canvas.Brush.Style := bsClear;
ItemBmp.Canvas.TextRect(R, R.Left + (WidthOf(R) - w) div 2, ItemBmp.Height - Marg, ExtraCaption);
end;
BitBlt(mi.Bmp.Canvas.Handle, SkinBorderWidth, SkinBorderWidth, ItemBmp.Width, ItemBmp.Height, ItemBmp.Canvas.Handle, 0, 0, SrcCopy);
FreeAndNil(ItemBmp);
end;
if Assigned(ExtraGlyph) then FreeAndNil(ExtraGlyph);
end;
// Prepare array of trans. px
SetLength(ArOR, 0);
i := TsSkinManager(FOwner).GetMaskIndex(i, s_MAINMENU, s_BORDERSMASK);
if TsSkinManager(FOwner).IsValidImgIndex(i) then begin
AddRgn(ArOR, mi.Bmp.Width, TsSkinManager(FOwner).ma[i], 0, False);
AddRgn(ArOR, mi.Bmp.Width, TsSkinManager(FOwner).ma[i],
mi.Bmp.Height - TsSkinManager(FOwner).ma[i].WB, True);
end;
if Wnd <> 0
then DrawWndBorder(Wnd, mi.Bmp);
end;
mi.Bmp.Canvas.UnLock;
SetLength(MenuInfoArray, Length(MenuInfoArray) + 1);
MenuInfoArray[Length(MenuInfoArray) - 1] := mi;
end;
function TsSkinableMenus.GetMenuInfo(Item : TMenuItem; const aWidth, aHeight : integer; aWnd : hwnd = 0): TacMenuInfo;
var
i, l : integer;
fi : TMenuItem;
begin
Result.FirstItem := nil;
Result.Bmp := nil;
l := Length(MenuInfoArray);
if Item <> nil then begin
fi := Item.Parent.Items[0];
for i := 0 to l - 1 do begin
if MenuInfoArray[i].FirstItem = fi then begin
Result := MenuInfoArray[i];
Exit;
end;
end;
// If not found but BG is required already
if aWidth <> 0 then begin
PrepareMenuBG(fi, aWidth, aHeight, aWnd);
Result := GetMenuInfo(fi, aWidth, aHeight);
end;
end
else if aWnd <> 0 then begin
for i := 0 to l - 1 do begin
if MenuInfoArray[i].Wnd = aWnd then begin
Result := MenuInfoArray[i];
Exit;
end;
end;
end;
end;
function TsSkinableMenus.IsOpened(Item: TMenuItem): boolean;
//var
// i, l : integer;
begin
Result := False;
{ if MenuInfoArray = nil then Exit;
l := Length(MenuInfoArray);
for i := 0 to l - 1 do begin
if MenuInfoArray[i].FirstItem.Parent = Item then begin
Result := True;
Exit;
end;
end;}
end;
{ TacMenuSupport }
constructor TacMenuSupport.Create;
begin
FUseExtraLine := False;
FExtraLineWidth := 32;
FExtraLineFont := TFont.Create;
end;
destructor TacMenuSupport.Destroy;
begin
FreeAndNil(FExtraLineFont);
inherited;
end;
procedure TacMenuSupport.SetExtraLineFont(const Value: TFont);
begin
FExtraLineFont.Assign(Value);
end;
initialization
finalization
ClearCache;
end.
|
UNIT uDmService;
INTERFACE
USES
SysUtils,
Classes,
SysTypes,
UDWDatamodule,
System.JSON,
UDWJSONObject,
Dialogs,
ServerUtils,
UDWConsts,
FireDAC.Dapt,
UDWConstsData,
FireDAC.Phys.FBDef,
FireDAC.UI.Intf,
FireDAC.VCLUI.Wait,
FireDAC.Stan.Intf,
FireDAC.Stan.Option,
FireDAC.Stan.Error,
FireDAC.Phys.Intf,
FireDAC.Stan.Def,
FireDAC.Stan.Pool,
FireDAC.Stan.Async,
FireDAC.Phys,
FireDAC.Phys.FB,
Data.DB,
FireDAC.Comp.Client,
FireDAC.Comp.UI,
FireDAC.Phys.IBBase,
FireDAC.Stan.StorageJSON,
RestDWServerFormU,
URESTDWPoolerDB,
URestDWDriverFD,
FireDAC.Phys.MSSQLDef,
FireDAC.Phys.ODBCBase,
FireDAC.Phys.MSSQL;
TYPE
TServerMethodDM = CLASS(TServerMethodDataModule)
RESTDWPoolerDB1: TRESTDWPoolerDB;
RESTDWDriverFD1: TRESTDWDriverFD;
Server_FDConnection: TFDConnection;
FDPhysFBDriverLink1: TFDPhysFBDriverLink;
FDStanStorageJSONLink1: TFDStanStorageJSONLink;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
FDPhysMSSQLDriverLink1: TFDPhysMSSQLDriverLink;
PROCEDURE ServerMethodDataModuleReplyEvent(SendType: TSendEvent; Context: STRING; VAR Params: TDWParams; VAR Result: STRING);
PROCEDURE ServerMethodDataModuleCreate(Sender: TObject);
PROCEDURE Server_FDConnectionBeforeConnect(Sender: TObject);
PROCEDURE ServerMethodDataModuleWelcomeMessage(Welcomemsg: STRING);
PROCEDURE Server_FDConnectionError(ASender, AInitiator: TObject; VAR AException: Exception);
PRIVATE
{ Private declarations }
FUNCTION ConsultaBanco(VAR Params: TDWParams): STRING; OVERLOAD;
PUBLIC
{ Public declarations }
END;
VAR
ServerMethodDM: TServerMethodDM;
IMPLEMENTATION
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
FUNCTION TServerMethodDM.ConsultaBanco(VAR Params: TDWParams): STRING;
VAR
VSQL: STRING;
JSONValue: TJSONValue;
FdQuery: TFDQuery;
BEGIN
IF Params.ItemsString['SQL'] <> NIL THEN
BEGIN
JSONValue := UDWJSONObject.TJSONValue.Create;
JSONValue.Encoding := GetEncoding(Encoding);
IF Params.ItemsString['SQL'].Value <> '' THEN
BEGIN
IF Params.ItemsString['TESTPARAM'] <> NIL THEN
Params.ItemsString['TESTPARAM'].SetValue('OK, OK');
VSQL := Params.ItemsString['SQL'].Value;
{$IFDEF FPC}
{$ELSE}
FdQuery := TFDQuery.Create(NIL);
TRY
FdQuery.Connection := Server_FDConnection;
FdQuery.SQL.Add(VSQL);
JSONValue.LoadFromDataset('sql', FdQuery, RestDWForm.CbEncode.Checked);
Result := JSONValue.ToJSON;
FINALLY
JSONValue.Free;
FdQuery.Free;
END;
{$ENDIF}
END;
END;
END;
PROCEDURE TServerMethodDM.ServerMethodDataModuleCreate(Sender: TObject);
BEGIN
RESTDWPoolerDB1.Active := RestDWForm.CbPoolerState.Checked;
END;
PROCEDURE TServerMethodDM.ServerMethodDataModuleReplyEvent(SendType: TSendEvent; Context: STRING; VAR Params: TDWParams; VAR Result: STRING);
VAR
JSONObject: TJSONObject;
BEGIN
JSONObject := TJSONObject.Create;
CASE SendType OF
SePOST:
BEGIN
IF UpperCase(Context) = UpperCase('EMPLOYEE') THEN
Result := ConsultaBanco(Params)
ELSE
BEGIN
JSONObject.AddPair(TJSONPair.Create('STATUS', 'NOK'));
JSONObject.AddPair(TJSONPair.Create('MENSAGEM', 'Método não encontrado'));
Result := JSONObject.ToJSON;
END;
END;
END;
JSONObject.Free;
END;
PROCEDURE TServerMethodDM.ServerMethodDataModuleWelcomeMessage(Welcomemsg: STRING);
BEGIN
RestDWForm.EdBD.Text := Welcomemsg;
END;
PROCEDURE TServerMethodDM.Server_FDConnectionBeforeConnect(Sender: TObject);
VAR
Driver_BD: STRING;
Porta_BD: STRING;
Servidor_BD: STRING;
DataBase: STRING;
Pasta_BD: STRING;
Usuario_BD: STRING;
Senha_BD: STRING;
BEGIN
database:= RestDWForm.EdBD.Text;
Driver_BD := RestDWForm.CbDriver.Text;
If RestDWForm.CkUsaURL.Checked Then
Begin
Servidor_BD := RestDWForm.EdURL.Text;
end
Else
Begin
Servidor_BD := RestDWForm.DatabaseIP;
end;
Case RestDWForm.CbDriver.ItemIndex Of
0: // FireBird
Begin
Pasta_BD := IncludeTrailingPathDelimiter(RestDWForm.EdPasta.Text);
Database := RestDWForm.edBD.Text;
Database := Pasta_BD + Database;
end;
1: // MSSQL
Begin
Database := RestDWForm.EdBD.Text;
end;
end;
Porta_BD := RestDWForm.EdPortaBD.Text;
Usuario_BD := RestDWForm.EdUserNameBD.Text;
Senha_BD := RestDWForm.EdPasswordBD.Text;
TFDConnection(Sender).Params.Clear;
TFDConnection(Sender).Params.Add('DriverID=' + Driver_BD);
TFDConnection(Sender).Params.Add('Server=' + Servidor_BD);
TFDConnection(Sender).Params.Add('Port=' + Porta_BD);
TFDConnection(Sender).Params.Add('Database=' + Database);
TFDConnection(Sender).Params.Add('User_Name=' + Usuario_BD);
TFDConnection(Sender).Params.Add('Password=' + Senha_BD);
TFDConnection(Sender).Params.Add('Protocol=TCPIP');
TFDConnection(Sender).DriverName := Driver_BD;
TFDConnection(Sender).LoginPrompt := FALSE;
TFDConnection(Sender).UpdateOptions.CountUpdatedRecords := False;
END;
PROCEDURE TServerMethodDM.Server_FDConnectionError(ASender, AInitiator: TObject; VAR AException: Exception);
BEGIN
RestDWForm.memoResp.Lines.Add(AException.Message);
END;
END.
|
unit Module.Orders;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.Stan.StorageBin, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool,
FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef,
FireDAC.Stan.ExprFuncs, FireDAC.VCLUI.Wait, FireDAC.DApt;
type
TModuleOrders = class(TDataModule)
FDConnection1: TFDConnection;
fdqOrders: TFDQuery;
FDPhysSQLiteDriverLink1: TFDPhysSQLiteDriverLink;
private
public
function OpenNotShippedOrders(ReportOrdersRequiredBefore: TDateTime)
: TDataSet;
end;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TModuleOrders }
function TModuleOrders.OpenNotShippedOrders(ReportOrdersRequiredBefore
: TDateTime): TDataSet;
var
sql: string;
begin
sql := 'SELECT OrderID, CustomerID, OrderDate, RequiredDate ' + sLineBreak +
'FROM Orders ' + sLineBreak +
'WHERE ShippedDate is NULL AND RequiredDate < :ADAY ' + sLineBreak +
'ORDER BY RequiredDate';
fdqOrders.Open( sql, [ReportOrdersRequiredBefore] );
Result := fdqOrders;
end;
end.
|
unit LuaCollectionItem;
//first new object added since the conversion (no initializeLuaCollectionItem because no backwards compatibility and no create)
{$mode delphi}
interface
uses
Classes, SysUtils, lua, lauxlib, lualib;
procedure collectionItem_addMetaData(L: PLua_state; metatable: integer; userdata: integer );
implementation
uses luahandler, LuaClass, LuaObject;
function collectionItem_getID(L: PLua_state):integer; cdecl;
var ci: TCollectionItem;
begin
ci:=luaclass_getClassObject(L);
lua_pushinteger(L, ci.ID);
result:=1;
end;
function collectionItem_getIndex(L: PLua_state):integer; cdecl;
var ci: TCollectionItem;
begin
ci:=luaclass_getClassObject(L);
lua_pushinteger(L, ci.Index);
result:=1;
end;
function collectionItem_setIndex(L: PLua_state):integer; cdecl;
var ci: TCollectionItem;
begin
ci:=luaclass_getClassObject(L);
if lua_gettop(l)=1 then
ci.index:=lua_tointeger(L,1);
result:=0;
end;
function collectionItem_getDisplayName(L: PLua_state):integer; cdecl;
var ci: TCollectionItem;
begin
ci:=luaclass_getClassObject(L);
lua_pushstring(L, ci.DisplayName);
result:=1;
end;
function collectionItem_setDisplayName(L: PLua_state):integer; cdecl;
var ci: TCollectionItem;
begin
ci:=luaclass_getClassObject(L);
if lua_gettop(l)=1 then
ci.DisplayName:=Lua_ToString(L,1);
result:=0;
end;
procedure collectionItem_addMetaData(L: PLua_state; metatable: integer; userdata: integer );
begin
object_addMetaData(L, metatable, userdata);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'getID', collectionItem_getID);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'getIndex', collectionItem_getIndex);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'setIndex', collectionItem_setIndex);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'getDisplayName', collectionItem_getDisplayName);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'setDisplayName', collectionItem_setDisplayName);
luaclass_addPropertyToTable(L, metatable, userdata, 'ID', collectionItem_getID, nil);
luaclass_addPropertyToTable(L, metatable, userdata, 'Index', collectionItem_getIndex, collectionItem_setIndex);
luaclass_addPropertyToTable(L, metatable, userdata, 'DisplayName', collectionItem_getDisplayName, collectionItem_setDisplayName);
end;
initialization
luaclass_register(TCollectionItem, collectionItem_addMetaData);
end.
|
unit Unit3;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, IPPeerClient,
IPPeerServer, System.Tether.Manager, System.Tether.AppProfile, FMX.StdCtrls,
FMX.Controls.Presentation, FMX.Edit, System.Actions, FMX.ActnList;
type
TForm3 = class(TForm)
TetheringManager1: TTetheringManager;
TetheringAppProfile1: TTetheringAppProfile;
Button1: TButton;
Label1: TLabel;
Edit1: TEdit;
EditButton1: TEditButton;
ImageControl1: TImageControl;
Button2: TButton;
OpenDialog1: TOpenDialog;
Label2: TLabel;
ImageControl2: TImageControl;
ActionList1: TActionList;
actReset: TAction;
Button3: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure TetheringManager1PairedToRemote(const Sender: TObject;
const AManagerInfo: TTetheringManagerInfo);
procedure TetheringManager1RequestManagerPassword(const Sender: TObject;
const ARemoteIdentifier: string; var Password: string);
procedure EditButton1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure TetheringAppProfile1ResourceReceived(const Sender: TObject;
const AResource: TRemoteResource);
procedure actResetExecute(Sender: TObject);
procedure actResetUpdate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form3: TForm3;
implementation
{$R *.fmx}
{$R *.LgXhdpiTb.fmx ANDROID}
procedure TForm3.actResetExecute(Sender: TObject);
begin
Edit1.Text := '';
Label2.Text := '';
end;
procedure TForm3.actResetUpdate(Sender: TObject);
begin
actReset.Enabled := (Edit1.Text <> '') OR
(Label2.Text <> '');
end;
procedure TForm3.Button1Click(Sender: TObject);
begin
TetheringManager1.AutoConnect;
end;
procedure TForm3.Button2Click(Sender: TObject);
var
LStream : TMemoryStream;
begin
if OpenDialog1.Execute then
begin
ImageControl1.LoadFromFile(OpenDialog1.FileName);
Lstream := TMemoryStream.Create;
ImageControl1.Bitmap.SaveToStream(LStream);
LStream.Position := 0;
TetheringAppProfile1.Resources.FindByName('SomeImage').Value := LStream;
end;
end;
procedure TForm3.EditButton1Click(Sender: TObject);
begin
TetheringAppProfile1.Resources.FindByName('SomeText').Value := Edit1.Text;
end;
procedure TForm3.FormCreate(Sender: TObject);
begin
Caption := Format('App1 : %s', [TetheringManager1.Identifier]);
end;
procedure TForm3.TetheringAppProfile1ResourceReceived(const Sender: TObject;
const AResource: TRemoteResource);
begin
if AResource.Hint = 'ReplyText' then
begin
Label2.Text := AResource.Value.AsString;
end
else if AResource.Hint = 'ReplyImage' then
begin
AResource.Value.AsStream.Position := 0;
ImageControl2.Bitmap.LoadFromStream(AResource.Value.AsStream);
end;
end;
procedure TForm3.TetheringManager1PairedToRemote(const Sender: TObject;
const AManagerInfo: TTetheringManagerInfo);
begin
Label1.Text := Format('Connected : %s %s', [AManagerInfo.ManagerIdentifier, AManagerInfo.ManagerName]);
end;
procedure TForm3.TetheringManager1RequestManagerPassword(const Sender: TObject;
const ARemoteIdentifier: string; var Password: string);
begin
Password := 'The wingless dove protects its nest';
end;
end.
|
{***************************************************************************}
{ }
{ DelphiWebDriver }
{ }
{ Copyright 2017 inpwtepydjuf@gmail.com }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit Commands.PostElement;
interface
uses
Vcl.Forms,
CommandRegistry,
HttpServerCommand;
type
/// <summary>
/// Handles 'POST' '/session/(.*)/element'
/// </summary>
TPostElementCommand = class(TRestCommand)
private
procedure GetElementByName(const value:String; AOwner: TForm);
procedure GetElementByCaption(const value:String; AOwner: TForm);
procedure GetElementByClassName(const value:String; AOwner: TForm);
procedure GetElementByPartialCaption(const value:String; AOwner: TForm);
function OKResponse(const sessionId, handle: String): String;
public
class function GetCommand: String; override;
class function GetRoute: String; override;
procedure Execute(AOwner: TForm); override;
end;
implementation
uses
System.JSON,
Vcl.controls,
Vcl.StdCtrls,
Vcl.ExtCtrls,
System.Types,
System.SysUtils,
System.Classes,
System.StrUtils,
System.JSON.Types,
System.JSON.Writers,
System.JSON.Builders;
procedure TPostElementCommand.GetElementByName(const value:String; AOwner: TForm);
var
comp: TComponent;
begin
try
if (AOwner.Caption = value) then
comp := AOwner
else
comp := AOwner.FindComponent(value);
if comp = nil then
raise Exception.Create('Control not found');
if (comp is TWinControl) then
ResponseJSON(self.OKResponse(self.Params[1], IntToStr((comp as TWinControl).Handle)))
else
ResponseJSON(self.OKResponse(self.Params[1], comp.name));
except on e: Exception do
// Probably should give a different reply
Error(404);
end;
end;
procedure TPostElementCommand.GetElementByClassName(const value:String; AOwner: TForm);
var
comp: TComponent;
i: Integer;
begin
comp := nil;
try
if (AOwner.ClassName = value) then
comp := AOwner
else
begin
for i := 0 to tForm(AOwner).ControlCount -1 do
if tForm(AOwner).Controls[i].ClassName = value then
begin
comp := tForm(AOwner).Controls[i];
break;
end;
end;
if comp = nil then
raise Exception.Create('Control not found');
ResponseJSON(self.OKResponse(self.Params[1], IntToStr((comp as TWinControl).Handle)));
except on e: Exception do
// Probably should give a different reply
Error(404);
end;
end;
procedure TPostElementCommand.GetElementByPartialCaption(const value:String; AOwner: TForm);
begin
Error(404);
end;
procedure TPostElementCommand.GetElementByCaption(const value:String; AOwner: TForm);
var
comp: TComponent;
i: Integer;
begin
comp := nil;
try
if (AOwner.Caption = value) then
comp := AOwner
else
begin
for i := 0 to tForm(AOwner).ControlCount -1 do
// Vcl.ExtCtrls ..
// TButtonedEdit
// THeader
// TPanel
// Vcl.StdCtrls ..
// TButton - done
// TCheckBox
// TComboBox
// TEdit
// TLabel
// TListBox
// TRadioButton
// TStaticText
// TMemo
// Specifically from the test host
// TTreeView
// TRichEdit
// TToolbar
// TToolbarButton
// TPageControl
// TTabSheet
// TStatusBar
// TMainMenu
// TMenuItem
// TPopupMenu
// TStringGrid
// TMaskedEdit
// TLinkLabel
// TSpeedButton - no window here, need to 'fake' one
// Need to get each type of control and check the caption / text
if (tForm(AOwner).Controls[i] is TButton) then
begin
if (tForm(AOwner).Controls[i] as TButton).caption = value then
begin
comp := tForm(AOwner).Controls[i];
break;
end;
end
else if (tForm(AOwner).Controls[i] is TPanel) then
begin
if (tForm(AOwner).Controls[i] as TPanel).caption = value then
begin
comp := tForm(AOwner).Controls[i];
break;
end;
end
else if (tForm(AOwner).Controls[i] is TEdit) then
begin
if (tForm(AOwner).Controls[i] as TEdit).Text = value then
begin
comp := tForm(AOwner).Controls[i];
break;
end;
end;
end;
if comp = nil then
raise Exception.Create('Control not found');
ResponseJSON(self.OKResponse(self.Params[1], IntToStr((comp as TWinControl).Handle)));
except on e: Exception do
// Probably should give a different reply
Error(404);
end;
end;
procedure TPostElementCommand.Execute(AOwner: TForm);
var
jsonObj : TJSONObject;
using: String;
value: String;
begin
jsonObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(self.StreamContents),0) as TJSONObject;
try
(jsonObj as TJsonObject).TryGetValue<String>('using', using);
(jsonObj as TJsonObject).TryGetValue<String>('value', value);
finally
jsonObj.Free;
end;
if (using = 'link text') then
GetElementByCaption(value, AOwner)
else if (using = 'name') then
GetElementByName(value, AOwner)
else if (using = 'class name') then
GetElementByClassName(value, AOwner)
else if (using = 'partial link text') then
GetElementByPartialCaption(value, AOwner)
else
Error(404);
// 'id' (automation id)
end;
function TPostElementCommand.OKResponse(const sessionId, handle: String): String;
var
Builder: TJSONObjectBuilder;
Writer: TJsonTextWriter;
StringWriter: TStringWriter;
StringBuilder: TStringBuilder;
begin
StringBuilder := TStringBuilder.Create;
StringWriter := TStringWriter.Create(StringBuilder);
Writer := TJsonTextWriter.Create(StringWriter);
Writer.Formatting := TJsonFormatting.Indented;
Builder := TJSONObjectBuilder.Create(Writer);
Builder
.BeginObject()
.Add('sessionId', sessionId)
.Add('status', 0)
.BeginObject('value')
.Add('ELEMENT', Handle)
.EndObject
.EndObject;
result := StringBuilder.ToString;
end;
class function TPostElementCommand.GetCommand: String;
begin
result := 'POST';
end;
class function TPostElementCommand.GetRoute: String;
begin
result := '/session/(.*)/element';
end;
end.
|
{: FRMaterialPreview<p>
Material Preview frame.<p>
<b>Historique : </b><font size=-1><ul>
<li>06/02/00 - Egg - Creation
</ul></font>
}
unit FRMaterialPreview;
interface
uses
Windows, Forms, StdCtrls, GLScene, GLObjects, Classes, Controls, GLTexture,
GLMisc;
type
TRMaterialPreview = class(TFrame)
GLScene1: TGLScene;
SceneViewer: TGLSceneViewer;
CBObject: TComboBox;
Camera: TGLCamera;
Cube: TCube;
Sphere: TSphere;
LightSource: TGLLightSource;
CBBackground: TComboBox;
PlanePattern: TPlane;
procedure CBObjectChange(Sender: TObject);
procedure CBBackgroundChange(Sender: TObject);
private
{ Déclarations privées }
function GetGLMaterial : TGLMaterial;
procedure SetGLMaterial(const val : TGLMaterial);
public
{ Déclarations publiques }
constructor Create(AOwner : TComponent); override;
property Material : TGLMaterial read GetGLMaterial write SetGLMaterial;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
{$R *.DFM}
uses Graphics;
constructor TRMaterialPreview.Create(AOwner : TComponent);
begin
inherited;
CBObject.ItemIndex:=0; CBObjectChange(Self);
CBBackground.ItemIndex:=0; CBBackgroundChange(Self);
end;
// GetGLMaterial
//
function TRMaterialPreview.GetGLMaterial : TGLMaterial;
begin
case CBObject.ItemIndex of
1 : Result:=Sphere.Material;
else
Result:=Cube.Material;
end;
end;
// SetGLMaterial
//
procedure TRMaterialPreview.SetGLMaterial(const val : TGLMaterial);
begin
Cube.Material.Assign(val);
Sphere.Material.Assign(val);
end;
procedure TRMaterialPreview.CBObjectChange(Sender: TObject);
var
i : Integer;
begin
i:=CBObject.ItemIndex;
Sphere.Visible:=((i and 1)=1);
Cube.Visible:=((i and 1)<>1);
if Sphere.Visible then
SetGLMaterial(Cube.Material)
else SetGLMaterial(Sphere.Material);
end;
procedure TRMaterialPreview.CBBackgroundChange(Sender: TObject);
var
bgColor : TColor;
begin
case CBBackground.ItemIndex of
1 : bgColor:=clWhite;
2 : bgColor:=clBlack;
3 : bgColor:=clBlue;
4 : bgColor:=clRed;
5 : bgColor:=clGreen;
else
bgColor:=clNone;
end;
with PlanePattern.Material do begin
Texture.Disabled:=(bgColor<>clNone);
FrontProperties.Diffuse.Color:=ConvertWinColor(bgColor);
end;
end;
end.
|
{ ##
@FILE UBinaryVerInfo.pas
@COMMENTS Provides definition of class implementing of
IVerInfoBinary and IVerInfoBinaryReader interfaces
that are exported from DLL. Also exports function
used to create objects supported by the DLL.
@PROJECT_NAME Binary Version Information Manipulator Library
@PROJECT_DESC Enables binary version information data to be read
from and written to streams and to be updated.
@DEPENDENCIES None.
@HISTORY(
@REVISION(
@VERSION 1.0
@DATE 04/08/2002
@COMMENTS Original version.
)
@REVISION(
@VERSION 1.1
@DATE 22/06/2003
@COMMENTS Fixed bug in TVerInfoBinary.AddStringTable where a
spurious call to QueryInterface was prematurely
freeing the object, causing access violation when
an attempt was made to add a string table.
)
@REVISION(
@VERSION 1.2
@DATE 19/10/2004
@COMMENTS Fixed error in error message resource string that
was causing exception in Format procedure.
)
)
}
{
* ***** BEGIN LICENSE BLOCK *****
*
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* The Original Code is UBinaryVerInfo.pas
*
* The Initial Developer of the Original Code is Peter Johnson
* (http://www.delphidabbler.com/).
*
* Portions created by the Initial Developer are Copyright (C) 2002-2004 Peter
* Johnson. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK *****
}
unit UBinaryVerInfo;
interface
uses
// Project
IntfBinaryVerInfo;
function CreateInstance(const CLSID: TGUID; out Obj): HResult; stdcall;
{If the library supports the object CLSID then an instance of the required
object is created. A reference to the object is stored in Obj and S_OK is
returned. If the library does not support CLSID then Obj is set to nil and
E_NOTIMPL is returned. If there is an error in creating the object Obj is set
to nil and E_FAIL is returned}
implementation
uses
// Delphi
SysUtils, Windows, ActiveX,
// Project
UVerInfoData;
type
TVerInfoBinary = class;
{
IVerInfoBinaryPvt:
Interface used to allow access to reference to implementing object instance.
Inheritance: IVerInfoBinaryPvt -> [IUnknown]
}
IVerInfoBinaryPvt = interface(IUnknown)
['{B92AB0E8-E7B5-4C54-AFA8-B049BB14EF4A}']
function GetSelf: TVerInfoBinary;
{Returns object's Self pointer}
end;
{
TVerInfoBinary:
Class that implements the IVerInfoBinary and IVerInfoBinaryReader interface
exported from the DLL.
Inheritance: TVerInfoBinary -> [TInterfacedObject] -> [TObject]
}
TVerInfoBinary = class(TInterfacedObject,
IUnknown, IVerInfoBinaryReader, IVerInfoBinary, IVerInfoBinaryPvt)
private
fVIData: TVerInfoData;
{Version information data object used to access and manipulate the binary
data}
fLastError: WideString;
{The last error message}
procedure Error(const FmtStr: string; const Args: array of const);
{Raises an EVerInfoBinary exception with a message made up from the given
format string and argumements}
function Success: HResult;
{Sets a successful result: returns S_OK and clears the last error message}
function HandleException(const E: Exception): HResult;
{Handles the exception passed as a parameter by returning E_FAIL and
stores the exception's message for use by LastErrorMessage}
protected
{ IVerInfoBinary / IVerInfoBinaryReader }
function GetFixedFileInfo(out Value: TVSFixedFileInfo): HResult; stdcall;
{Fetches the version information's fixed file information record and
passes it out in Value}
function GetFixedFileInfoArray(out Value: TFixedFileInfoArray): HResult;
stdcall;
{Fetches the version information's fixed file information record
interpreted as an array and passes it out in Value}
function GetFixedFileInfoItem(const Offset: TFixedFileInfoOffset;
out Value: DWORD): HResult; stdcall;
{Fetches the given element from the version information's fixed file
information and passes in out in Value}
function SetFixedFileInfo(const Value: TVSFixedFileInfo): HResult; stdcall;
{Sets fixed file information record in version information to given value}
function SetFixedFileInfoArray(const Value: TFixedFileInfoArray): HResult;
stdcall;
{Sets fixed file information in version information to information
contained in given array}
function SetFixedFileInfoItem(const Offset: TFixedFileInfoOffset;
const Value: DWORD): HResult; stdcall;
{Sets the given element of fixed file info to the given value}
function GetTranslationCount(out Count: Integer): HResult; stdcall;
{Sets Count to the number of translations in the version information}
function GetTranslation(const Index: Integer;
out Value: TTranslationCode): HResult; stdcall;
{Sets Value to the code of the translation at the given index. It is an
error if the translation index is out of bounds}
function GetTranslationAsString(const Index: Integer;
out Value: WideString): HResult; stdcall;
{Sets Value to the translation string of the translation at the given
index. It is an error if the translation index is out of bounds}
function SetTranslation(const Index: Integer;
const Value: TTranslationCode): HResult; stdcall;
{Sets the translation at the given index to the given code. It is an error
if the translation index is out of bounds}
function AddTranslation(const Value: TTranslationCode;
out NewIndex: Integer): HResult; stdcall;
{Adds a new translation identified by the given code. NewIndex is set to
the index of the new translation or -1 on error}
function DeleteTranslation(const Index: Integer): HResult; stdcall;
{Deletes the translation at the given index. It is an error of the
translation index is out of bounds}
function IndexOfTranslation(const Value: TTranslationCode;
out Index: Integer): HResult; stdcall;
{Sets Index to the index of the translation with the given code in the
version info, or -1 if there is no such translation}
function GetStringTableCount(out Count: Integer): HResult; stdcall;
{Return the number of string tables in the version information in Count}
function GetStringTableTransString(const Index: Integer;
out TransStr: WideString): HResult; stdcall;
{Sets TransCode to the translation string associated with the string table
at the given index. It is an error if the table index is out of bounds}
function GetStringTableTransCode(const Index: Integer;
out TransCode: TTranslationCode): HResult; stdcall;
{Returns the translation code associated with the string table at the
given index in TransCode. It is an error if the table index is out of
bounds}
function AddStringTable(const TransStr: WideString;
out NewIndex: Integer): HResult; stdcall;
{Adds a new string table indentified by the given translation string.
NewIndex is set to the index of the new string table or -1 if an error
occurs}
function AddStringTableByCode(const TransCode: TTranslationCode;
out NewIndex: Integer): HResult; stdcall;
{Adds a new string table indentified by the given translation code.
NewIndex is set to the index of the new string table or -1 if an error
occurs}
function DeleteStringTable(const Index: Integer): HResult; stdcall;
{Deletes the string table at the given index and all the string items that
belong to the table. It is an error if the string table index is out of
bounds}
function IndexOfStringTable(const TransStr: WideString;
out Index: Integer): HResult; stdcall;
{Sets Index to the index of the the string table identified by the the
given translation string, or -1 if no such string table}
function IndexOfStringTableByCode(const Code: TTranslationCode;
out Index: Integer): HResult; stdcall;
{Sets Index to the index of the string table identified by a translation
string made up from the given translation code, or -1 if no such string
table}
function GetStringCount(const TableIdx: Integer;
out Count: Integer): HResult; stdcall;
{Returns the number of string items in the given string table in Count. It
is an error if the string table index is out of bounds}
function GetStringName(const TableIdx, StringIdx: Integer;
out Name: WideString): HResult; stdcall;
{Returns the name of the string item at the given index in the string
table with the given string table index in Name. It is an error if either
index is out of bounds}
function GetStringValue(const TableIdx, StringIdx: Integer;
out Value: WideString): HResult; stdcall;
{Sets Value to the string item at the given index in the string table. It
is an error if either index is out of bounds}
function GetStringValueByName(const TableIdx: Integer;
const Name: WideString; out Value: WideString): HResult; stdcall;
{Sets Value to the string item with the given name in the string table
with the given string table index in Value. It is an error if there is no
string item with the given name in the table or if the table index is out
of bounds}
function SetString(const TableIdx, StringIdx: Integer;
const Value: WideString): HResult; stdcall;
{Sets the string value at the given index in the string table at the given
table index. It is an error if either index is out of bounds}
function SetStringByName(const TableIdx: Integer;
const Name, Value: WideString): HResult; stdcall;
{Sets the value of the string with the given name in the the string table
with the given index. It is an error if the string table index is out of
range or if a string with the given name does not exist}
function AddString(const TableIdx: Integer;
const Name, Value: WideString; out StrIdx: Integer): HResult; stdcall;
{Adds a new string with given name and value to the string table with the
given index. StrIdx is set to the the index of the new string within the
string table or -1 on error. It is an error if the string table index is
out of bounds or if the table already contains a string with the given
name}
function SetOrAddString(const TableIdx: Integer;
const Name, Value: WideString; out StrIndex: Integer): HResult; stdcall;
{Set the string information item with the given name in the string table
with the given index to the given value. If a string info item with the
given name aleady exists then its value is overwritten, otherwise name
item with the required name and value is created. StrIndex is set to the
index of the string info item that is updated. It is an error if the
string table index is out of bounds}
function DeleteString(const TableIdx, StringIdx: Integer): HResult; stdcall;
{Deletes the string information item at the given index in the string
table which has the given table index. It is an error if either index is
out of bounds}
function DeleteStringByName(const TableIdx: Integer;
const Name: WideString): HResult; stdcall;
{Deletes the string information item with the given name from the string
table which has the given table index. It is an error if no string item
with the given name exists in the string table or the string table index
is out of bounds}
function Clear: HResult; stdcall;
{Clears the version information data}
function Assign(const Source: IVerInfoBinaryReader): HResult; stdcall;
{Assigns contents of given object to this object}
function ReadFromStream(const Stm: IStream): HResult; stdcall;
{Reads binary version information from given stream}
function WriteToStream(const Stm: IStream): HResult; stdcall;
{Writes the binary version information to the given stream}
function LastErrorMsg: WideString; stdcall;
{Returns error message generated from last operation, or '' if last
operation was a success}
{ IVerInfoBinaryPvt }
function GetSelf: TVerInfoBinary;
{Returns object's Self pointer}
public
constructor Create(VerResType: TVerResType);
{Class constructor: creates a new version information data object that
interprets and updates version information data}
destructor Destroy; override;
{Class destructor: frees owned version info data object}
end;
{
EVerInfoBinary:
Private class of exception raised by TVerInfoBinary.
Inheritance: EVerInfoBinary -> [Exception] -> [TObject]
}
EVerInfoBinary = class(Exception);
{
TFixedFileInfoAccessor:
"Union" that allows fixed file version information to be accessed either as
a standard record or as an array of DWORD elements. This is used to enable
fixed file information read from binary data to be returned to user as an
array.
}
TFixedFileInfoAccessor = packed record
case Integer of
1: (Elements: TFixedFileInfoArray); // array of fixed file info
2: (Orig: TVSFixedFileInfo); // standard record
end;
resourcestring
// Error messages
sBadStrName = 'There is no string named "%0:s" in translation %1:d';
function CreateInstance(const CLSID: TGUID; out Obj): HResult; stdcall;
{If the library supports the object CLSID then an instance of the required
object is created. A reference to the object is stored in Obj and S_OK is
returned. If the library does not support CLSID then Obj is set to nil and
E_NOTIMPL is returned. If there is an error in creating the object Obj is set
to nil and E_FAIL is returned}
begin
try
// Assume success
Result := S_OK;
// Check for supported objects, creating objects of required type
if IsEqualIID(CLSID, CLSID_VerInfoBinaryA) then
// requested IVerInfoBinary for 16 bit version info data
IVerInfoBinary(Obj) := TVerInfoBinary.Create(vrtAnsi)
as IVerInfoBinary
else if IsEqualIID(CLSID, CLSID_VerInfoBinaryW) then
// requested IVerInfoBinary for 32 bit version info data
IVerInfoBinary(Obj) := TVerInfoBinary.Create(vrtUnicode)
as IVerInfoBinary
else if IsEqualIID(CLSID, CLSID_VerInfoBinaryReaderA) then
// requested IVerInfoBinaryReader for 16 bit version info data
IVerInfoBinaryReader(Obj) := TVerInfoBinary.Create(vrtAnsi)
as IVerInfoBinaryReader
else if IsEqualIID(CLSID, CLSID_VerInfoBinaryReaderW) then
// requested IVerInfoBinaryReader for 32 bit version info data
IVerInfoBinaryReader(Obj) := TVerInfoBinary.Create(vrtUnicode)
as IVerInfoBinaryReader
else
begin
// Unsupported object: set object nil and set error code
Pointer(Obj) := nil;
Result := E_NOTIMPL;
end;
except
// Something went wrong: set object to nil and set error code
Pointer(Obj) := nil;
Result := E_FAIL;
end;
end;
{ TVerInfoBinary }
function TVerInfoBinary.AddString(const TableIdx: Integer; const Name,
Value: WideString; out StrIdx: Integer): HResult;
{Adds a new string with given name and value to the string table with the
given index. StrIdx is set to the the index of the new string within the
string table or -1 on error. It is an error if the string table index is out
of bounds or if the table already contains a string with the given name}
begin
// Set error value of string index
StrIdx := -1;
try
// Try to add string and record its index
StrIdx := fVIData.AddString(TableIdx, Name, Value);
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.AddStringTable(const TransStr: WideString;
out NewIndex: Integer): HResult;
{Adds a new string table indentified by the given translation string. NewIndex
is set to the index of the new string table or -1 if an error occurs}
begin
// Set error value of string table index
NewIndex := -1;
try
// Try to add new string table and record its index
NewIndex := fVIData.AddStringTable(TransStr);
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.AddStringTableByCode(
const TransCode: TTranslationCode; out NewIndex: Integer): HResult;
{Adds a new string table indentified by the given translation code. NewIndex
is set to the index of the new string table or -1 if an error occurs}
begin
Result := AddStringTable(
TransToString(TransCode.LanguageID, TransCode.CharSet),
NewIndex
);
end;
function TVerInfoBinary.AddTranslation(const Value: TTranslationCode;
out NewIndex: Integer): HResult;
{Adds a new translation identified by the given code. NewIndex is set to the
index of the new translation or -1 on error}
begin
// Set error translation index value
NewIndex := -1;
try
// Try of add new translation and record its index
NewIndex := fVIData.AddTranslation(Value.LanguageID, Value.CharSet);
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.Assign(const Source: IVerInfoBinaryReader): HResult;
{Assigns contents of given object to this object}
begin
try
// Assign using source's object reference
fVIData.Assign((Source as IVerInfoBinaryPvt).GetSelf.fVIData);
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.Clear: HResult;
{Clears the version information data}
begin
try
fVIData.Reset;
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
constructor TVerInfoBinary.Create(VerResType: TVerResType);
{Class constructor: creates a new version information data object that
interprets and updates version information data}
begin
inherited Create;
fVIData := TVerInfoData.Create(VerResType);
end;
function TVerInfoBinary.DeleteString(const TableIdx,
StringIdx: Integer): HResult;
{Deletes the string information item at the given index in the string table
which has the given table index. It is an error if either index is out of
bounds}
begin
try
fVIData.DeleteString(TableIdx, StringIdx);
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.DeleteStringByName(const TableIdx: Integer;
const Name: WideString): HResult;
{Deletes the string information item with the given name from the string table
which has the given table index. It is an error if no string item with the
given name exists in the string table or the string table index is out of
bounds}
var
StrIdx: Integer; // index of string item with given name in string table
begin
try
// Get index of string item in table and check it exists
StrIdx := fVIData.IndexOfString(TableIdx, Name);
if StrIdx = -1 then
Error(sBadStrName, [Name, TableIdx]);
// Delete the string item
fVIData.DeleteString(TableIdx, StrIdx);
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.DeleteStringTable(
const Index: Integer): HResult;
{Deletes the string table at the given index and all the string items that
belong to the table. It is an error if the string table index is out of
bounds}
begin
try
fVIData.DeleteStringTable(Index);
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.DeleteTranslation(
const Index: Integer): HResult;
{Deletes the translation at the given index. It is an error of the translation
index is out of bounds}
begin
try
fVIData.DeleteTranslation(Index);
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
destructor TVerInfoBinary.Destroy;
{Class destructor: frees owned version info data object}
begin
fVIData.Free;
inherited;
end;
procedure TVerInfoBinary.Error(const FmtStr: string;
const Args: array of const);
{Raises an EVerInfoBinary exception with a message made up from the given
format string and argumements}
begin
raise EVerInfoBinary.CreateFmt(FmtStr, Args);
end;
function TVerInfoBinary.GetFixedFileInfo(
out Value: TVSFixedFileInfo): HResult;
{Fetches the version information's fixed file information record and passes it
out in Value}
begin
// Set empty record in case of error
FillChar(Value, SizeOf(Value), 0);
try
// Get the fixed file info record
Value := fVIData.GetFixedFileInfo;
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.GetFixedFileInfoArray(
out Value: TFixedFileInfoArray): HResult;
{Fetches the version information's fixed file information record interpreted
as an array and passes it out in Value}
var
FFIAccess: TFixedFileInfoAccessor; // record to interpret data as array
begin
Assert(SizeOf(TFixedFileInfoArray) = SizeOf(TVSFixedFileInfo));
// Get fixed file info record as store in "union"
Result := GetFixedFileInfo(FFIAccess.Orig);
// Return the data interpreted as an array
Value := FFIAccess.Elements;
end;
function TVerInfoBinary.GetFixedFileInfoItem(
const Offset: TFixedFileInfoOffset; out Value: DWORD): HResult;
{Fetches the given element from the version information's fixed file
information and passes in out in Value}
var
FFIArray: TFixedFileInfoArray; // array of fixed file info data
begin
// Get array of fixed file info data
Result := GetFixedFileInfoArray(FFIArray);
// Return the element at the required offset
Value := FFIArray[Offset];
end;
function TVerInfoBinary.GetSelf: TVerInfoBinary;
{Returns object's Self pointer}
begin
Result := Self;
end;
function TVerInfoBinary.GetStringCount(const TableIdx: Integer;
out Count: Integer): HResult;
{Returns the number of string items in the given string table in Count. It is
an error if the string table index is out of bounds}
begin
// Set count to zero in case of error
Count := 0;
try
// Try to get the count
Count := fVIData.GetStringCount(TableIdx);
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.GetStringName(const TableIdx,
StringIdx: Integer; out Name: WideString): HResult;
{Returns the name of the string item at the given index in the string table
with the given string table index in Name. It is an error if either index is
out of bounds}
begin
// Set name to empty string in case of error
Name := '';
try
// Try to get the name
Name := fVIData.GetStringName(TableIdx, StringIdx);
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.GetStringTableCount(
out Count: Integer): HResult;
{Return the number of string tables in the version information in Count}
begin
// Set count to 0 in case of error
Count := 0;
try
// Try to get number of string tables
Count := fVIData.GetStringTableCount;
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.GetStringTableTransCode(const Index: Integer;
out TransCode: TTranslationCode): HResult;
{Returns the translation code associated with the string table at the given
index in TransCode. It is an error if the table index is out of bounds}
// ---------------------------------------------------------------------------
function StrToTransCode(const Str: string): TTranslationCode;
{Converts a translation string to a translation code}
begin
Result.LanguageID := StrToInt('$' + Copy(Str, 1, 4));
Result.CharSet := StrToInt('$' + Copy(Str, 5, 4));
end;
// ---------------------------------------------------------------------------
begin
// Set translation code to 0 in case of error
TransCode.Code := 0;
try
// Attempt to get the transaltion code
TransCode := StrToTransCode(fVIData.GetStringTableTransStr(Index));
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.GetStringTableTransString(
const Index: Integer; out TransStr: WideString): HResult;
{Sets TransCode to the translation string associated with the string table at
the given index. It is an error if the table index is out of bounds}
begin
// Set a default 'nul' translation code in case of error
TransStr := '00000000';
try
// Attempt to get the translation string
TransStr := fVIData.GetStringTableTransStr(Index);
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.GetStringValue(const TableIdx,
StringIdx: Integer; out Value: WideString): HResult;
{Sets Value to the string item at the given index in the string table. It is
an error if either index is out of bounds}
begin
// Set empty value in case of error
Value := '';
try
// Try to get the string item value
Value := fVIData.GetStringValue(TableIdx, StringIdx);
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.GetStringValueByName(const TableIdx: Integer;
const Name: WideString; out Value: WideString): HResult;
{Sets Value to the string item with the given name in the string table with
the given string table index in Value. It is an error if there is no string
item with the given name in the table or if the table index is out of bounds}
var
StringIdx: Integer; // index of string item with given name in table
begin
// Set nul value in case of error
Value := '';
try
// Get index of string item with given name & check it exists
StringIdx := fVIData.IndexOfString(TableIdx, Name);
if StringIdx = -1 then
Error(sBadStrName, [Name, TableIdx]);
// Try to get value of string at required index
Value := fVIData.GetStringValue(TableIdx, StringIdx);
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.GetTranslation(const Index: Integer;
out Value: TTranslationCode): HResult;
{Sets Value to the code of the translation at the given index. It is an error
if the translation index is out of bounds}
begin
// Sets a zero translation code in case of error
Value.Code := 0;
try
// Try to set the translation code from the language id and character set
Value.LanguageID := fVIData.GetLanguageID(Index);
Value.CharSet := fVIData.GetCharSet(Index);
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.GetTranslationAsString(const Index: Integer;
out Value: WideString): HResult;
{Sets Value to the translation string of the translation at the given index.
It is an error if the translation index is out of bounds}
begin
// Set a zero translation string in case of error
Value := '00000000';
try
// Try to get the translation string
Value := fVIData.GetTranslationString(Index);
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.GetTranslationCount(
out Count: Integer): HResult;
{Sets Count to the number of translations in the version information}
begin
// Set count to zero in case of error
Count := 0;
try
// Try to get the number of translations
Count := fVIData.GetTranslationCount;
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.HandleException(const E: Exception): HResult;
{Handles the exception passed as a parameter by returning E_FAIL and stores
the exception's message for use by LastErrorMessage}
begin
Result := E_FAIL;
fLastError := E.Message;
end;
function TVerInfoBinary.IndexOfStringTable(const TransStr: WideString;
out Index: Integer): HResult;
{Sets Index to the index of the the string table identified by the the given
translation string, or -1 if no such string table}
begin
// Set index to -1 in case of error
Index := -1;
try
// Try to get the index
Index := fVIData.IndexOfStringTable(TransStr);
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.IndexOfStringTableByCode(
const Code: TTranslationCode; out Index: Integer): HResult;
{Sets Index to the index of the string table identified by a translation
string made up from the given translation code, or -1 if no such string table}
var
TransStr: string; // the translation string to look up
begin
// Make translation string from laguage id and code
TransStr := TransToString(Code.LanguageID, Code.CharSet);
// Find the index of the string table
Result := IndexOfStringTable(TransStr, Index);
end;
function TVerInfoBinary.IndexOfTranslation(
const Value: TTranslationCode; out Index: Integer): HResult;
{Sets Index to the index of the translation with the given code in the version
info, or -1 if there is no such translation}
begin
// Set index to -1 in case of error
Index := -1;
try
// Try to get index of translation
Index := fVIData.IndexOfTranslation(Value.LanguageID, Value.CharSet);
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.LastErrorMsg: WideString;
{Returns error message generated from last operation, or '' if last operation
was a success}
begin
Result := fLastError;
end;
function TVerInfoBinary.ReadFromStream(const Stm: IStream): HResult;
{Reads binary version information from given stream}
begin
try
fVIData.ReadFromStream(Stm);
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.SetFixedFileInfo(
const Value: TVSFixedFileInfo): HResult;
{Sets fixed file information record in version information to given value}
begin
try
fVIData.SetFixedFileInfo(Value);
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.SetFixedFileInfoArray(
const Value: TFixedFileInfoArray): HResult;
{Sets fixed file information in version information to information contained
in given array}
var
FFIAccess: TFixedFileInfoAccessor; // union used to access FFI as array
begin
Assert(SizeOf(TFixedFileInfoArray) = SizeOf(TVSFixedFileInfo));
// Set data to write using array part of union
FFIAccess.Elements := Value;
// Set FFI using fixed file info record from union
Result := SetFixedFileInfo(FFIAccess.Orig);
end;
function TVerInfoBinary.SetFixedFileInfoItem(
const Offset: TFixedFileInfoOffset; const Value: DWORD): HResult;
{Sets the given element of fixed file info to the given value}
var
FFIArray: TFixedFileInfoArray; // array used to access fixed file info
begin
// Get existing FFI from version info as array
Result := GetFixedFileInfoArray(FFIArray);
if Succeeded(Result) then
begin
// Update required element of array
FFIArray[Offset] := Value;
// Store uptated FFI array back in version info
Result := SetFixedFileInfoArray(FFIArray);
end;
end;
function TVerInfoBinary.SetOrAddString(const TableIdx: Integer;
const Name, Value: WideString; out StrIndex: Integer): HResult;
{Set the string information item with the given name in the string table with
the given index to the given value. If a string info item with the given name
aleady exists then its value is overwritten, otherwise name item with the
required name and value is created. StrIndex is set to the index of the string
info item that is updated. It is an error if the string table index is out of
bounds}
begin
// Set string index to -1 in case of error
StrIndex := -1;
try
// Find idex of string name (or -1 if no such item)
StrIndex := fVIData.IndexOfString(TableIdx, Name);
if StrIndex = -1 then
// No such string: add it and record index
StrIndex := fVIData.AddString(TableIdx, Name, Value)
else
// String exists: update value
fVIData.SetStringValue(TableIdx, StrIndex, Value);
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.SetString(const TableIdx, StringIdx: Integer;
const Value: WideString): HResult;
{Sets the string value at the given index in the string table at the given
table index. It is an error if either index is out of bounds}
begin
try
fVIData.SetStringValue(TableIdx, StringIdx, Value);
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.SetStringByName(const TableIdx: Integer;
const Name, Value: WideString): HResult;
{Sets the value of the string with the given name in the the string table with
the given index. It is an error if the string table index is out of range or
if a string with the given name does not exist}
var
StrIdx: Integer; // index of string in string table
begin
try
// Get index of string with given name: ensure it exists
StrIdx := fVIData.IndexOfString(TableIdx, Name);
if StrIdx = -1 then
Error(sBadStrName, [Name, TableIdx]);
// Set the string value
fVIData.SetStringValue(TableIdx, StrIdx, Value);
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.SetTranslation(const Index: Integer;
const Value: TTranslationCode): HResult;
{Sets the translation at the given index to the given code. It is an error if
the translation index is out of bounds}
begin
try
fVIData.SetTranslation(Index, Value.LanguageID, Value.CharSet);
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
function TVerInfoBinary.Success: HResult;
{Sets a successful result: returns S_OK and clears the last error message}
begin
Result := S_OK;
fLastError := '';
end;
function TVerInfoBinary.WriteToStream(const Stm: IStream): HResult;
{Writes the binary version information to the given stream}
begin
try
fVIData.WriteToStream(Stm);
Result := Success;
except
on E: Exception do
Result := HandleException(E);
end;
end;
end.
|
unit RegistryForm;
{
Copyright (c) 2017+, Health Intersections Pty Ltd (http://www.healthintersections.com.au)
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 HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Generics.Collections,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.Controls.Presentation, FMX.TabControl, FMX.ListBox, FMX.Layouts, FMX.DateTimeCtrls,
FMX.Edit, System.Rtti, FMX.Grid.Style, FMX.Grid, FMX.ScrollBox, FMX.Platform,
IdComponent,
DateSupport, StringSupport,
AdvGenerics,
FHIRBase, FHIRTypes, FHIRResources, FHIRClient, FHIRUtilities, FHIRXhtml,
BaseFrame, AppEndorserFrame, CapabilityStatementEditor, FMX.WebBrowser,
FMX.Memo;
type
TFrame = TBaseFrame; // re-aliasing the Frame to work around a designer bug
TRegistryFrame = class (TFrame)
Panel2: TPanel;
Panel3: TPanel;
lblOutcome: TLabel;
btnFetchMore: TButton;
Panel1: TPanel;
Panel4: TPanel;
pnlSearch: TPanel;
Label3: TLabel;
btnConfSearch: TButton;
cbConfUseLastUpdated: TCheckBox;
edtConfJurisdiction: TComboBox;
edtConfText: TEdit;
edtConfUpdated: TDateEdit;
edtConfUrl: TEdit;
Label11: TLabel;
Label8: TLabel;
Label1: TLabel;
cbxType: TComboBox;
Label2: TLabel;
cbxProfile: TComboBox;
gridConfMatches: TGrid;
StringColumn1: TStringColumn;
StringColumn2: TStringColumn;
StringColumn3: TStringColumn;
StringColumn4: TStringColumn;
StringColumn5: TStringColumn;
StringColumn6: TStringColumn;
StringColumn7: TStringColumn;
StringColumn8: TStringColumn;
Splitter1: TSplitter;
memSource: TMemo;
pnlMessages: TPanel;
lblMessages: TLabel;
procedure btnCloseClick(Sender: TObject);
procedure btnConfSearchClick(Sender: TObject);
procedure gridConfMatchesGetValue(Sender: TObject; const ACol, ARow: Integer; var Value: TValue);
procedure gridConfMatchesCellDblClick(const Column: TColumn; const Row: Integer);
procedure btnFetchMoreClick(Sender: TObject);
procedure cbxTypeChange(Sender: TObject);
procedure cbConfUseLastUpdatedClick(Sender: TObject);
procedure gridConfMatchesSelectCell(Sender: TObject; const ACol, ARow: Integer; var CanSelect: Boolean);
procedure lblOutcomeClick(Sender: TObject);
procedure lblMessagesClick(Sender: TObject);
private
FClient: TFHIRClient;
FCSTab : TTabItem;
FCsForm : TCapabilityStatementEditorFrame;
FPatBundle, FConfBundle : TFhirBundle;
FConfMatches : TAdvList<TFHIRResource>;
function client : TFhirClient;
procedure DoWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
public
Destructor Destroy; override;
procedure load; override;
end;
implementation
{$R *.fmx}
uses
ResourceEditingSupport;
{ TRegistryFrame }
procedure TRegistryFrame.btnCloseClick(Sender: TObject);
begin
try
Settings.storeValue('Registry-search', 'url', edtConfUrl.Text);
Settings.storeValue('Registry-search', 'text', edtConfText.Text);
Settings.storeValue('Registry-search', 'jurisdiction', edtConfJurisdiction.ItemIndex);
Settings.storeValue('Registry-search', 'updated', edtConfUpdated.Text);
Settings.storeValue('Registry-search', 'updated-opt', cbConfUseLastUpdated.IsChecked);
Settings.storeValue('Registry-search', 'type', cbxType.ItemIndex);
Settings.storeValue('Registry-search', 'profile', cbxProfile.ItemIndex);
Settings.save;
except
end;
Close;
end;
procedure TRegistryFrame.btnConfSearchClick(Sender: TObject);
var
t : TFHIRResourceType;
op : TFhirOperationOutcome;
begin
pnlMessages.Height := 0;
work('Fetch Resources', true,
procedure
var
be : TFhirBundleEntry;
params : TDictionary<String, String>;
start : TDateTime;
begin
FConfMatches.Clear;
gridConfMatches.RowCount := FConfMatches.Count;
FConfBundle.Free;
FConfBundle := nil;
params := TDictionary<String, String>.create;
try
case cbxType.ItemIndex of
0 : {Profiles}
begin
t := frtStructureDefinition;
end;
1 : {Value Sets}
begin
t := frtValueSet;
end;
2 : {Code Systems}
begin
t := frtCodeSystem;
end;
3 : {Capability Statements}
begin
t := frtCapabilityStatement;
end;
4 : {Search Parameters}
begin
t := frtSearchParameter;
end;
5 : {Operation Definitions}
begin
t := frtOperationDefinition;
end;
6 : {All Conformance Resources}
begin
t := frtNull;
params.Add('_type', 'CapabilityStatement,StructureDefinition,ImplementationGuide,SearchParameter,MessageDefinition,OperationDefinition,CompartmentDefinition,StructureMap,GraphDefinition,CodeSystem,ValueSet,ConceptMap,ExpansionProfile,NamingSystem');
end;
else{All Resources}
begin
t := frtNull;
end;
end;
params.Add('_summary', 'true');
if cbxProfile.Enabled then
params.add('type', cbxProfile.items[cbxProfile.itemIndex]);
if edtConfUrl.Text <> '' then
params.add('url', edtConfUrl.Text);
if edtConfText.Text <> '' then
params.add('_text', edtConfText.Text);
if cbConfUseLastUpdated.IsChecked then
params.add('_lastUpdated', edtConfUpdated.Text);
if edtConfJurisdiction.ItemIndex <> -1 then
params.add('jurisdiction', getJurisdictionSearch(edtConfJurisdiction.ItemIndex));
start := now;
FConfBundle := Client.search(t, false, params);
for be in FConfBundle.entryList do
if ((be.search = nil) or (be.search.mode = SearchEntryModeMatch)) and (be.resource <> nil) then
if (be.resource is TFhirOperationOutcome) then
begin
op := TFhirOperationOutcome(be.resource);
pnlMessages.Height := 26;
lblMessages.Text := op.asExceptionMessage;
end
else
FConfMatches.Add(be.resource.Link);
gridConfMatches.RowCount := FConfMatches.Count;
lblOutcome.Text := 'Fetched '+inttostr(FConfMatches.Count)+' of '+FConfBundle.total+' resources in '+describePeriod(now - start)+'. search String = '+FMXescape(FClient.lastURL);
btnFetchMore.Visible := FConfBundle.Links['next'] <> '';
finally
params.Free;
end;
end);
end;
procedure TRegistryFrame.btnFetchMoreClick(Sender: TObject);
begin
work('Fetch More', true,
procedure
var
be : TFhirBundleEntry;
start : TDateTime;
l : TFhirBundleLink;
i : integer;
url : String;
begin
btnFetchMore.Visible := false;
url := FConfBundle.Links['next'];
FConfBundle.Free;
FConfBundle := nil;
start := now;
FConfBundle := Client.searchAgain(url);
i := 0;
for be in FConfBundle.entryList do
if (be.search.mode = SearchEntryModeMatch) and (be.resource <> nil) then
begin
FConfMatches.Add(be.resource.Link);
inc(i);
end;
gridConfMatches.RowCount := FConfMatches.Count;
lblOutcome.Text := 'Fetched '+inttostr(i)+' of '+FConfBundle.total+' resources in '+describePeriod(now - start);
btnFetchMore.Visible := FConfBundle.Links['next'] <> '';
end);
end;
procedure TRegistryFrame.cbConfUseLastUpdatedClick(Sender: TObject);
begin
edtConfUpdated.Enabled := cbConfUseLastUpdated.IsChecked;
end;
procedure TRegistryFrame.cbxTypeChange(Sender: TObject);
begin
cbxProfile.Enabled := cbxType.ItemIndex = 0;
end;
function TRegistryFrame.client: TFhirClient;
begin
if FClient = nil then
FClient := TFhirHTTPClient.Create(nil, 'http://registry-api.fhir.org/open', false);
result := FClient;
end;
destructor TRegistryFrame.Destroy;
begin
FClient.free;
FConfBundle.Free;
FPatBundle.Free;
FConfMatches.Free;
inherited;
end;
procedure TRegistryFrame.DoWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
begin
Application.ProcessMessages;
if assigned(OnStopped) and OnStopped then
abort;
end;
procedure TRegistryFrame.gridConfMatchesCellDblClick(const Column: TColumn; const Row: Integer);
var
res : TFhirResource;
begin
res := Client.readResource(FConfMatches[Row].ResourceType, FConfMatches[Row].id);
try
OnOpenResource(self, client, client.format, res);
finally
res.Free;
end;
end;
procedure TRegistryFrame.gridConfMatchesGetValue(Sender: TObject; const ACol, ARow: Integer; var Value: TValue);
var
res : TFhirMetadataResource;
begin
if not (FConfMatches[aRow] is TFhirMetadataResource) then
begin
case ACol of
0: Value := FConfMatches[aRow].fhirType;
1: Value := FConfMatches[aRow].id;
end;
end
else
begin
res := FConfMatches[aRow] as TFhirMetadataResource;
case ACol of
0: Value := res.fhirType;
1: Value := res.id;
2: Value := res.url;
3: Value := res.name;
4: Value := res.version;
5: Value := CODES_TFhirPublicationStatusEnum[res.status];
6: Value := res.date.toXML;
7: Value := readJurisdiction(res);
end;
end;
end;
function top200(s : String) : String;
var
i, t : integer;
begin
i := 1;
t := 0;
while (i < length(s)) do
begin
if s[i] = #10 then
inc(t);
if t = 200 then
exit(s.Substring(0, i+1));
inc(i);
end;
result := s;
end;
procedure TRegistryFrame.gridConfMatchesSelectCell(Sender: TObject; const ACol, ARow: Integer; var CanSelect: Boolean);
var
res : TFHIRResource;
begin
if aRow = -1 then
memSource.Text := ''
else
begin
res := FConfMatches[aRow];
memSource.Text := top200(resourceToString(res, ffXml));
end;
end;
procedure TRegistryFrame.lblMessagesClick(Sender: TObject);
//var
// Svc: IFMXClipboardService;
begin
// TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService, Svc);
// svc.SetClipboard(lblMessages.Text);
end;
procedure TRegistryFrame.lblOutcomeClick(Sender: TObject);
var
Svc: IFMXClipboardService;
begin
TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService, Svc);
svc.SetClipboard(lblOutcome.Text);
end;
procedure TRegistryFrame.load;
begin
edtConfUrl.Text := Settings.getValue('Registry-search', 'url', '');
edtConfText.Text := Settings.getValue('Registry-search', 'text', '');
edtConfJurisdiction.ItemIndex := Settings.getValue('Registry-search', 'jurisdiction', 0);
edtConfUpdated.Text := Settings.getValue('Registry-search', 'updated', '');
cbConfUseLastUpdated.IsChecked := Settings.getValue('Registry-search', 'updated-opt', false);
cbxType.ItemIndex := Settings.getValue('Registry-search', 'type', 0);
cbxProfile.ItemIndex := Settings.getValue('Registry-search', 'profile', 0);
btnFetchMore.Visible := false;
FConfMatches := TAdvList<TFHIRResource>.create;
end;
end.
|
{ The TSmiley component is Copyright © 1995 }
{ by Nick Hodges All Rights Reserved }
{ email: 71563.2250@compuserve.com }
{ USED WITH PERMISSION for distribution with _Delphi 2.0 In-Depth_,
Cary Jensen, Editor.
MODIFIED by Michael Ax, ax@href.com, to demonstrate a few things
about property editors...
}
unit TSmile;
interface
uses
SysUtils
{$IFDEF WIN32}
, Windows
{$ELSE}
, WinProcs, WinTypes
{$ENDIF}
, Messages, Classes, Graphics, Controls,
Forms, Dialogs, Buttons, ExtCtrls, StdCtrls, DsgnIntF, TypInfo;
type
TSmileyMood = (smHappy, smSad, smShades, smTongue, smIndifferent, smOoh);
const
smInitialMood = smHappy;
smClickedMood = smSad;
MoodString : array[TSmileyMood] of PChar = ('smHappy', 'smSad', 'smShades', 'smTongue', 'smIndifferent', 'smOoh');
MaxHeight = 26;
MaxWidth = 26;
type
TSmiley = class(TImage)
private
{ Private declarations }
Face: TBitmap;
FMood: TSmileyMood;
procedure SetBitmap;
procedure SetSmileyMood(NewMood: TSmileyMood);
procedure WMSize (var Message: TWMSize); message wm_paint;
procedure MouseClicked(up:boolean);
procedure MaxSize;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Free;
procedure Toggle;
procedure MoodDialog;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
published
property Mood: TSmileyMood read FMood write SetSmileyMood;
end;
TSmileyMoodDlg = class(TForm)
BitBtn1: TBitBtn;
Panel1: TPanel;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
SpeedButton3: TSpeedButton;
SpeedButton4: TSpeedButton;
SpeedButton5: TSpeedButton;
SpeedButton6: TSpeedButton;
Label1: TLabel;
procedure SpeedButton1Click(Sender: TObject);
private
{ Private declarations }
FMood: TSmileyMood;
procedure SetSmileyMood(NewMood: TSmileyMood);
public
{ Public declarations }
property Mood: TSmileyMood read FMood write SetSmileyMood;
end;
TSmileyMoodProperty = class( TEnumProperty )
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
procedure Register;
{-------------------------------------------------
implementation
--------------------------------------------------}
implementation
{$R *.DFM}
{$IFDEF WIN32}
{$R TSmile32.res}
{$ELSE}
{$R TSmile16.res}
{$ENDIF}
{-------------------------------------------------
TSmiley
--------------------------------------------------}
constructor TSmiley.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Face := TBitmap.Create; {Note dynamic allocation of the pointer}
SetSmileyMood(smInitialMood);
end; {Create}
destructor TSmiley.Free;
begin
Face.Free; {Use Free rather than Destroy, as Free checks for a nil pointer first}
inherited Free;
end; {Free}
procedure TSmiley.Toggle;
begin
if fMood = high(TSmileyMood) then {Don't allow fMood to overflow}
Mood := low(TSmileyMood)
else
Mood := Succ(fMood);
end; {Toggle}
procedure TSmiley.SetSmileyMood(NewMood: TSmileyMood);
begin
if (face.handle=0) or (fMood<>NewMood) then begin
FMood := NewMood;
SetBitmap;
end;
end; {SetSmileyMood}
procedure TSmiley.SetBitmap;
begin
Face.Handle := LoadBitmap(hInstance, MoodString[fMood]);
Self.Picture.Graphic := Face as TGraphic; {Use RTTI to cast face as TGraphic, needed by TImage}
MaxSize;
end; {SetBitmap}
{This method will respond to a mouse push on the Smiley by storing the
old face for later use and giving the "Sad" face. Smileys don't like to get
clicked on!}
procedure TSmiley.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited MouseDown(Button, Shift, X, Y);
if Button=mbRight then
MoodDialog {here's where we run the property editor at runtime}
else
MouseClicked(false);
end; {MouseDown}
{This method restores the old face when the mouse comes back up}
procedure TSmiley.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited MouseUp(Button, Shift, X, Y);
if Button<>mbRight then
MouseClicked(true);
end; {MouseUp}
procedure TSmiley.MouseClicked(up:boolean);
const {the proc uses a constant rather than a field.}
OldMood: TSmileyMood=smInitialMood;
begin
if up then {button back up.}
SetSmileyMood(OldMood) {restore prior mood}
else {button now down}
if Mood<>smClickedMood then begin {store if different!}
{windows/delphi can loose the up sometimes so we must
not just act on any down but must see what it'd do first}
OldMood:= Mood; {store mood in local constant}
SetSmileyMood(smClickedMood); {express clicked-on mood}
end;
end;
procedure TSmiley.WMSize(var Message: TWMSize);
{This method keeps the user from sizing the Smiley at design time.
(remeber, it's a bitmap after all! You can use the 'csDesigning in
ComponentState' to control what the user can do at design time}
begin
inherited;
if (csDesigning in ComponentState) then
MaxSize;
end;
procedure TSmiley.MaxSize;
begin
Width := MaxWidth;
Height := MaxHeight;
end;
procedure TSmiley.MoodDialog; {here's where we run the property editor at runtime}
begin
with TSmileyMoodDlg.Create(Application) do try
Mood:=Self.Mood;
if ShowModal=mrOk then
Self.Mood:=Mood;
finally
Free
end;
end;
{-------------------------------------------------
TSmileyMoodDlg
--------------------------------------------------}
procedure TSmileyMoodDlg.SetSmileyMood(NewMood: TSmileyMood);
var
Counter: Integer;
begin
{ if (fMood<>NewMood) or (label1.caption='Label1') then }
for Counter:= 0 to ComponentCount - 1 do
if (Components[Counter] is TSpeedButton) then
with TSpeedButton(Components[Counter]) do
if Tag= Ord(NewMood) then begin
Down:= True; {sets fMood vis click}
fMood:= NewMood;
with Label1 do begin
Caption:= copy(strpas(MoodString[fMood]),3,255);
Update;
end;
end;
end;
procedure TSmileyMoodDlg.SpeedButton1Click(Sender: TObject);
begin
Mood := TSmileyMood((Sender as TSpeedButton).Tag);
end; {SpeedButton1Click}
{-------------------------------------------------
TMoodProperty
--------------------------------------------------}
function TSmileyMoodProperty.GetAttributes: TPropertyAttributes;
begin
Result:=[paDialog];
end;
procedure TSmileyMoodProperty.Edit; {here's where we run the property editor at design-time}
begin
with TSmileyMoodDlg.Create(Application) do try
Mood:=TSmileyMood(GetOrdValue); {small difference only to MoodDialog above}
if ShowModal=mrOk then
SetOrdValue(Ord(Mood))
finally
Free
end;
end; {Edit}
{-------------------------------------------------
Smiley ends, keep smiling.
--------------------------------------------------}
procedure Register;
begin
RegisterComponents('SAMPLES', [ TSmiley ] );
RegisterPropertyEditor( TypeInfo( TSmileyMood ), TSmiley, 'Mood', TSmileyMoodProperty );
end;
end.
|
unit VisibleDSA.Position;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils;
type
TPosition = class(TObject)
private
_x: integer;
_y: integer;
public
constructor Create(x, y: integer);
destructor Destroy; override;
property X: integer read _X;
property Y: integer read _Y;
end;
implementation
{ TPosition }
constructor TPosition.Create(x, y: integer);
begin
_x := x;
_y := y;
end;
destructor TPosition.Destroy;
begin
inherited Destroy;
end;
end.
|
UNIT medtronic_4b6b;
{$XDATA}
INTERFACE
USES queues, CStdInt;
FUNCTION decode_4b6b( VAR buffer : ARRAY OF uint8_t; start: size_t; finish : size_t ) : size_t;
FUNCTION decode_4b6b_symbol( VAR symbol : uint8_t ) : uint8_t;
IMPLEMENTATION
FUNCTION decode_4b6b_symbol( VAR symbol : uint8_t ) : uint8_t;
CONST
radio_symbol_table : ARRAY[0..52] OF uint8_t = (
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 11, 0, 13, 14, 0,
0, 0, 0, 0, 0, 0, 7, 0,
0, 9, 8, 0, 15, 0, 0, 0,
0, 0, 0, 3, 0, 5, 6, 0,
0, 0, 10, 0, 12, 0, 0, 0,
0, 1, 2, 0, 4 );
BEGIN
IF symbol > 52 THEN BEGIN
decode_4b6b_symbol := 0
END ELSE BEGIN
decode_4b6b_symbol := radio_symbol_table[symbol];
END;
END;
FUNCTION decode_4b6b( VAR buffer : ARRAY OF uint8_t; start: size_t; finish : size_t ) : size_t;
VAR
res : size_t;
nq : NibbleQueue XDATA;
bq : BitQueue XDATA;
n : size_t;
BEGIN
res := 0;
nibblequeue_clear( nq );
bitqueue_clear( bq );
FOR n := start TO finish DO BEGIN
nibblequeue_push_back( nq, buffer[n], 2 );
bitqueue_push_back( bq, nibblequeue_pop_front( nq, 1 ), 6 );
bitqueue_push_back( bq, nibblequeue_pop_front( nq, 1 ), 6 );
WHILE bitqueue_can_pop( bq, 8 ) DO BEGIN
buffer[res] := bitqueue_pop_front( bq, 8 );
res := res + 1;
END;
END;
IF NOT( bitqueue_empty( bq ) ) THEN BEGIN
WHILE bitqueue_can_pop( bq, 8 ) DO BEGIN
buffer[res] := bitqueue_pop_front( bq, 8 );
res := res + 1;
END;
END;
decode_4b6b := res;
END;
END. |
unit eAudioStream;
interface
uses
API_ORM,
eCommon;
type
TAudioStream = class(TEntity)
private
FBitDepth: Integer;
FBitRate: Integer;
FChannels: Integer;
FCodec: string;
FLanguage: string;
FSamplingRate: Integer;
FSize: Int64;
public
class function GetStructure: TSructure; override;
published
property BitDepth: Integer read FBitDepth write FBitDepth;
property BitRate: Integer read FBitRate write FBitRate;
property Channels: Integer read FChannels write FChannels;
property Codec: string read FCodec write FCodec;
property Language: string read FLanguage write FLanguage;
property SamplingRate: Integer read FSamplingRate write FSamplingRate;
property Size: Int64 read FSize write FSize;
end;
TV2AStremRel = class(TEntity)
private
FAudioStream: TAudioStream;
FAudioStreamID: Integer;
FVideoFileID: Integer;
public
class function GetStructure: TSructure; override;
published
property AudioStream: TAudioStream read FAudioStream write FAudioStream;
property AudioStreamID: Integer read FAudioStreamID write FAudioStreamID;
property VideoFileID: Integer read FVideoFileID write FVideoFileID;
end;
TV2AStreamRelList = TEntityList<TV2AStremRel>;
implementation
uses
eVideoFile;
class function TV2AStremRel.GetStructure: TSructure;
begin
Result.TableName := 'VIDEO_AUDIOSTREAMS';
AddForeignKey(Result.ForeignKeyArr, 'VIDEO_FILE_ID', TVideoFile, 'ID');
AddForeignKey(Result.ForeignKeyArr, 'AUDIO_STREAM_ID', TAudioStream, 'ID');
end;
class function TAudioStream.GetStructure: TSructure;
begin
Result.TableName := 'AUDIO_STREAMS';
end;
end.
|
unit AntDefine;
interface
uses
System.SysUtils,
System.Math,
Pengine.Collections,
Pengine.HashCollections,
Pengine.Vector,
Pengine.EventHandling,
Pengine.CollectionInterfaces,
Pengine.Bitfield,
GraphDefine;
type
TAnt = class;
TPheromoneData = class
private
FGraph: TGraph;
FPheromones: array of Single;
function GetPheromones(AConnection: TGraph.TConnection): Single;
procedure SetPheromones(AConnection: TGraph.TConnection; const Value: Single);
public
constructor Create(AGraph: TGraph);
function Copy: TPheromoneData;
procedure Assign(AFrom: TPheromoneData);
property Graph: TGraph read FGraph;
property Pheromones[AConnection: TGraph.TConnection]: Single read GetPheromones write SetPheromones; default;
procedure Clear;
procedure LeaveTrail(APath: IIterable<TGraph.TConnection>; AAmount: Single);
procedure Dissipate(APercentage: Single);
end;
TAnt = class
public type
TPath = TRefArray<TGraph.TConnection>;
TPoints = TRefArray<TGraph.TPoint>;
private
FPheromoneData: TPheromoneData;
FPassedPoints: TBitfield;
FInfluencedFactor: Single;
FSuccess: Boolean;
FPath: TPath;
FPoints: TPoints;
FPathLength: Single;
FMustReturn: Boolean;
function GetPheromoneAmount: Single;
/// <summary>Tries to choose a connection.</returns>
function ChooseConnection(APoint: TGraph.TPoint; out AConnection: TGraph.TConnection): Boolean;
function GetGraph: TGraph;
function GetPath: TPath.TReader;
function GetPoints: TPoints.TReader;
public
constructor Create(APheromoneData: TPheromoneData; AMustReturn: Boolean);
destructor Destroy; override;
property Graph: TGraph read GetGraph;
property PheromoneData: TPheromoneData read FPheromoneData;
/// <summary>How much the ant is influenced by pheromones on the graph.</summary>
property InfluencedFactor: Single read FInfluencedFactor write FInfluencedFactor;
/// <summary>The full path of points, that this ant took.</summary>
property Path: TPath.TReader read GetPath;
property Points: TPoints.TReader read GetPoints;
/// <returns>Whether the ant passed over the given point.</returns>
function PassedPoint(APoint: TGraph.TPoint): Boolean;
/// <summary>The total length of the path.</summary>
property PathLength: Single read FPathLength;
/// <summary>An arbitrary value ranging from 0 to 1, depending on how short the path is or zero on failure.</summary>
property PheromoneAmount: Single read GetPheromoneAmount;
property MustReturn: Boolean read FMustReturn;
/// <summary>Simulates the ant to traverse the graph.</summary>
procedure FindPath;
/// <summary>Leaves a trail on the graph, depending on how good the ant did and wether the finish was reached at all.</summary>
procedure LeaveTrail; overload;
/// <summary>Leaves a trail on the graph, depending only on the specified amount.</summary>
procedure LeaveTrail(AAmount: Single); overload;
/// <summary>Whether the ant managed to find a finish.</summary>
property Success: Boolean read FSuccess;
end;
TSimulation = class
public type
TStatisticType = (
stBest,
stWorst,
stAverage,
stMedian
);
TStatistic = array [TStatisticType] of Single;
TBatch = class
public type
TAnts = TObjectArray<TAnt>;
private
FSimulation: TSimulation;
FPheromoneData: TPheromoneData;
FAnts: TAnts;
function GetAnts: TAnts.TReader;
public
constructor Create(ASimulation: TSimulation; ACount: Integer);
destructor Destroy; override;
property Simulation: TSimulation read FSimulation;
property PheromoneData: TPheromoneData read FPheromoneData;
property Ants: TAnts.TReader read GetAnts;
function GetPathLengthStatistic: TStatistic;
end;
TBatches = TObjectArray<TBatch>;
private
FGraph: TGraph;
FInitialPheromoneData: TPheromoneData;
FInfluencedFactor: Single;
FPheromoneDissipation: Single;
FBatchSize: Integer;
FBatches: TBatches;
FMustReturn: Boolean;
function GetBatches: TBatches.TReader;
function GetPheromoneData: TPheromoneData;
public
constructor Create(AGraph: TGraph);
destructor Destroy; override;
property Graph: TGraph read FGraph;
/// <summary>The Pheromone Data of the lastly created Batch.</summary>
property PheromoneData: TPheromoneData read GetPheromoneData;
property BatchSize: Integer read FBatchSize write FBatchSize;
property Batches: TBatches.TReader read GetBatches;
property MustReturn: Boolean read FMustReturn write FMustReturn;
function GenerateBatch: TBatch;
property InfluencedFactor: Single read FInfluencedFactor write FInfluencedFactor;
property PheromoneDissipation: Single read FPheromoneDissipation write FPheromoneDissipation;
/// <summary>Removes all Batches.</summary>
procedure Clear;
end;
implementation
{ TAnt }
constructor TAnt.Create(APheromoneData: TPheromoneData; AMustReturn: Boolean);
begin
FPheromoneData := APheromoneData;
FPassedPoints := TBitfield.Create(Graph.Points.Count);
FPath := TPath.Create;
FPoints := TPoints.Create;
FMustReturn := AMustReturn;
end;
destructor TAnt.Destroy;
begin
FPoints.Free;
FPath.Free;
FPassedPoints.Free;
inherited;
end;
function TAnt.ChooseConnection(APoint: TGraph.TPoint; out AConnection: TGraph.TConnection): Boolean;
function InfluencePheromones(APheromones: Single): Single;
begin
// 1.0 -> p
// 0.5 -> p * 0.5 + 0.5
// 0.0 -> 1
Result := 1 + FInfluencedFactor * (APheromones - 1);
end;
var
Connections: TGraph.TConnections;
Connection: TGraph.TConnection;
TotalPheromones: Single;
ConnectionIndex: Integer;
begin
// Create a list of all valid next connections
TotalPheromones := 0;
Connections := TGraph.TConnections.Create;
for Connection in APoint.Connections do
begin
if not PassedPoint(Connection.Other(APoint)) then
begin
Connections.Add(Connection);
TotalPheromones := TotalPheromones + InfluencePheromones(PheromoneData[Connection]);
end;
end;
Result := not Connections.Empty;
if Result then
begin
ConnectionIndex := 0;
if Connections.Count > 1 then
begin
// Quick workaround for influence fator of 1 and pheromones all 0 resulting in a total of 0
Connections.Shuffle;
// Sort by best pheromone amount
Connections.Sort(
function(A, B: TGraph.TConnection): Boolean
begin
Result := PheromoneData[A] > PheromoneData[B];
end
);
// Randomize the value and find the now weighted random connection
TotalPheromones := Random * TotalPheromones;
while ConnectionIndex < Connections.MaxIndex do
begin
TotalPheromones := TotalPheromones - InfluencePheromones(PheromoneData[Connections[ConnectionIndex]]);
if TotalPheromones <= 0 then
Break;
Inc(ConnectionIndex);
end;
end;
AConnection := Connections[ConnectionIndex];
end;
Connections.Free;
end;
procedure TAnt.FindPath;
var
Current: TGraph.TPoint;
Connection: TGraph.TConnection;
PointsToPass: TBitfield;
AllPassedPoints: TBitfield;
Point: TGraph.TPoint;
begin
PointsToPass := TBitfield.Create(Graph.Points.Count);
AllPassedPoints := TBitfield.Create(Graph.Points.Count);
for Point in Graph.Points do
if Point.HasFood then
PointsToPass[Point.Index] := True;
Current := Graph.StartPoint;
FPoints.Add(Current);
FPassedPoints[Current.Index] := True;
AllPassedPoints[Current.Index] := True;
FSuccess := True;
while not PointsToPass.Empty or MustReturn and (Current <> Graph.StartPoint) do
begin
if ChooseConnection(Current, Connection) then
begin
FPath.Add(Connection);
Current := Connection.Other(Current);
FPoints.Add(Current);
FPassedPoints[Current.Index] := True;
AllPassedPoints[Current.Index] := True;
if PointsToPass[Current.Index] then
begin
PointsToPass[Current.Index] := False;
FPassedPoints.Clear;
FPassedPoints[Current.Index] := True;
end;
end
else
begin
if Path.Empty then
begin
FSuccess := False;
Break;
end;
Current := FPath.Last.Other(Current);
FPoints.RemoveLast;
FPath.RemoveLast;
end;
end;
FPassedPoints.Assign(AllPassedPoints);
PointsToPass.Free;
AllPassedPoints.Free;
FPathLength := 0;
for Connection in Path do
FPathLength := FPathLength + Connection.Cost;
end;
function TAnt.GetGraph: TGraph;
begin
Result := PheromoneData.Graph;
end;
function TAnt.GetPath: TPath.TReader;
begin
Result := FPath.Reader;
end;
function TAnt.GetPheromoneAmount: Single;
begin
if Success then
// Result := Power(1.001, -PathLength)
Result := 1000 / (1 + Sqr(PathLength))
else
Result := 0;
end;
function TAnt.GetPoints: TPoints.TReader;
begin
Result := FPoints.Reader;
end;
procedure TAnt.LeaveTrail(AAmount: Single);
begin
PheromoneData.LeaveTrail(FPath, AAmount);
end;
procedure TAnt.LeaveTrail;
begin
PheromoneData.LeaveTrail(FPath, PheromoneAmount);
end;
function TAnt.PassedPoint(APoint: TGraph.TPoint): Boolean;
begin
Result := FPassedPoints[APoint.Index];
end;
{ TSimulation }
constructor TSimulation.Create(AGraph: TGraph);
begin
FGraph := AGraph.Copy;
FInitialPheromoneData := TPheromoneData.Create(Graph);
FBatches := TBatches.Create;
FBatchSize := 20;
FInfluencedFactor := 0.9;
FPheromoneDissipation := 0.5;
end;
destructor TSimulation.Destroy;
begin
FGraph.Free;
FInitialPheromoneData.Free;
FBatches.Free;
inherited;
end;
function TSimulation.GenerateBatch: TBatch;
begin
Result := TBatch.Create(Self, BatchSize);
FBatches.Add(Result);
end;
function TSimulation.GetBatches: TBatches.TReader;
begin
Result := FBatches.Reader;
end;
function TSimulation.GetPheromoneData: TPheromoneData;
begin
if Batches.Empty then
Exit(FInitialPheromoneData);
Result := Batches.Last.PheromoneData;
end;
procedure TSimulation.Clear;
begin
FInitialPheromoneData.Clear;
FBatches.Clear;
end;
{ TSimulation.TBatch }
constructor TSimulation.TBatch.Create(ASimulation: TSimulation; ACount: Integer);
var
I: Integer;
Ant: TAnt;
begin
FSimulation := ASimulation;
FPheromoneData := Simulation.PheromoneData.Copy;
FAnts := TAnts.Create;
for I := 0 to ACount - 1 do
begin
Ant := TAnt.Create(PheromoneData, Simulation.MustReturn);
Ant.InfluencedFactor := Simulation.InfluencedFactor;
FAnts.Add(Ant);
Ant.FindPath;
end;
FAnts.Sort(
function(A, B: TAnt): Boolean
begin
Result := A.PathLength < B.PathLength;
end
);
PheromoneData.Dissipate(Simulation.PheromoneDissipation);
for I := 0 to Ants.MaxIndex do
if Ants[I].PathLength <> 0 then
Ants[I].LeaveTrail(Power(0.001, I / Ants.Count) * Sqr(Ants.First.PathLength / Ant.PathLength));
end;
destructor TSimulation.TBatch.Destroy;
begin
FPheromoneData.Free;
FAnts.Free;
inherited;
end;
function TSimulation.TBatch.GetAnts: TAnts.TReader;
begin
Result := FAnts.Reader;
end;
function TSimulation.TBatch.GetPathLengthStatistic: TStatistic;
var
Ant: TAnt;
begin
if Ants.Empty then
raise Exception.Create('Data required to generate statistic.');
Result[stBest] := Ants.First.PathLength;
Result[stWorst] := Ants.Last.PathLength;
Result[stAverage] := 0;
for Ant in Ants do
Result[stAverage] := Result[stAverage] + Ant.PathLength;
Result[stAverage] := Result[stAverage] / Ants.Count;
Result[stMedian] := Ants[Ants.MaxIndex div 2].PathLength;
if not Odd(FAnts.Count) then
Result[stMedian] := (Result[stMedian] + Ants[Ants.MaxIndex div 2 + 1].PathLength) / 2;
end;
{ TPheromoneData }
procedure TPheromoneData.Assign(AFrom: TPheromoneData);
begin
FGraph := AFrom.Graph;
SetLength(FPheromones, AFrom.Graph.Connections.Count);
Move(AFrom.FPheromones[0], FPheromones[0], Length(FPheromones) * SizeOf(FPheromones[0]));
end;
procedure TPheromoneData.Clear;
begin
FillChar(FPheromones[0], Length(FPheromones) * SizeOf(FPheromones[0]), 0);
end;
function TPheromoneData.Copy: TPheromoneData;
begin
Result := TPheromoneData.Create(Graph);
Result.Assign(Self);
end;
constructor TPheromoneData.Create(AGraph: TGraph);
begin
FGraph := AGraph;
SetLength(FPheromones, Graph.Connections.Count);
end;
procedure TPheromoneData.Dissipate(APercentage: Single);
var
I: Integer;
begin
for I := 0 to Length(FPheromones) - 1 do
FPheromones[I] := FPheromones[I] * (1 - APercentage);
end;
function TPheromoneData.GetPheromones(AConnection: TGraph.TConnection): Single;
begin
Result := FPheromones[AConnection.Index];
end;
procedure TPheromoneData.LeaveTrail(APath: IIterable<TGraph.TConnection>; AAmount: Single);
var
Connection: TGraph.TConnection;
begin
for Connection in APath do
Pheromones[Connection] := Pheromones[Connection] + AAmount;
end;
procedure TPheromoneData.SetPheromones(AConnection: TGraph.TConnection; const Value: Single);
begin
FPheromones[AConnection.Index] := Value;
end;
end.
|
unit URecentPage;
interface
uses UTypeDef, UPageSuper, UPageProperty, USysPageHandler, UxlClasses, UxlExtClasses, UxlList;
type
TRecentPage_Root = class (TPageContainer)
public
class function PageType (): TPageType; override;
function ChildShowInTree (ptChild: TPageType): boolean; override;
function CanOwnChild (ptChild: TPageType): boolean; override;
class function SingleInstance (): boolean; override;
end;
TRecentPageSuper = class (TListPageSuper)
private
public
procedure GetChildList (o_list: TxlIntList); override;
class procedure InitialListProperty (lp: TListProperty); override;
class function SingleInstance (): boolean; override;
end;
TRecentPage_Create = class (TRecentPageSuper)
public
class function PageType (): TPageType; override;
class procedure InitialListProperty (lp: TListProperty); override;
end;
TRecentPage_Modify = class (TRecentPageSuper)
public
class function PageType (): TPageType; override;
class procedure InitialListProperty (lp: TListProperty); override;
end;
TRecentPage_Visit = class (TRecentPageSuper)
public
class function PageType (): TPageType; override;
class procedure InitialListProperty (lp: TListProperty); override;
end;
type
TRecentCreateHandler = class (TSysPageContainerHandler)
protected
function PageType (): TPageType; override;
function NameResource (): integer; override;
function MenuItem_Manage (): integer; override;
function MenuItem_List (): integer; override;
end;
TRecentModifyHandler = class (TSysPageContainerHandler)
protected
function PageType (): TPageType; override;
function NameResource (): integer; override;
function MenuItem_Manage (): integer; override;
function MenuItem_List (): integer; override;
end;
TRecentVisitHandler = class (TSysPageContainerHandler)
protected
function PageType (): TPageType; override;
function NameResource (): integer; override;
function MenuItem_Manage (): integer; override;
function MenuItem_List (): integer; override;
end;
TRecentRootHandler = class (TSysPageHandlerSuper)
private
FCreateHandler: TRecentCreateHandler;
FModifyHandler: TRecentModifyHandler;
FVisitHandler: TRecentVisitHandler;
procedure AddChilds ();
protected
function PageType (): TPageType; override;
function NameResource (): integer; override;
function MenuItem_Manage (): integer; override;
public
constructor Create (AParent: TPageSuper); override;
destructor Destroy (); override;
procedure ExecuteCommand (opr: word); override;
end;
implementation
uses Windows, UPageStore, UxlStrUtils, UGlobalObj, UOptionManager, ULangManager, UPageFactory,
UxlDateTimeUtils, Resource;
class function TRecentPage_Root.PageType (): TPageType;
begin
result := ptRecentRoot;
end;
function TRecentPage_Root.ChildShowInTree (ptChild: TPageType): boolean;
begin
result := CanOwnChild (ptChild);
end;
function TRecentPage_Root.CanOwnChild (ptChild: TPageType): boolean;
begin
result := ptChild in [ptRecentCreate, ptRecentModify, ptRecentVisit];
end;
class function TRecentPage_Root.SingleInstance (): boolean;
begin
result := true;
end;
//--------------------
class function TRecentPageSuper.SingleInstance (): boolean;
begin
result := true;
end;
procedure TRecentPageSuper.GetChildList (o_list: TxlIntList);
var i: integer;
o_list2: TxlIntList;
begin
o_list2 := TxlIntList.Create;
PageStore.GetPageList(ptNone, o_list2);
for i := o_list2.Low to o_list2.High do
case PageType of
ptRecentCreate:
o_list2.Keys[i] := SystemTimeToString (PageStore[o_list2[i]].PageProperty.CreateTime, dtmDateTimeWithSecond);
ptRecentModify:
o_list2.Keys[i] := SystemTimeToString (PageStore[o_list2[i]].PageProperty.ModifyTime, dtmDateTimeWithSecond);
else
o_list2.Keys[i] := SystemTimeToString (PageStore[o_list2[i]].PageProperty.VisitTime, dtmDateTimeWithSecond);
end;
o_list2.SortByKey;
for i := o_list2.High downto o_list2.Low do
begin
o_list.Add (o_list2[i]);
if o_list.Count = OptionMan.Options.RecentNotesCount then exit;
end;
o_list2.free;
end;
class procedure TRecentPageSuper.InitialListProperty (lp: TListProperty);
begin
with lp do
begin
CheckBoxes := false;
View := lpvReport;
FullrowSelect := true;
GridLines := false;
end;
end;
//----------------------
class function TRecentPage_Create.PageType (): TPageType;
begin
result := ptRecentCreate;
end;
class procedure TRecentPage_Create.InitialListProperty (lp: TListProperty);
const c_cols: array[0..3] of integer = (sr_Title, sr_Abstract, sr_CreateTime, sr_NodePath);
c_widths: array[0..3] of integer = (100, 150, 80, 100);
begin
inherited InitialListProperty (lp);
lp.ColList.Populate (c_cols);
lp.WidthList.Populate (c_widths);
end;
//-------------------
class function TRecentPage_Modify.PageType (): TPageType;
begin
result := ptRecentModify;
end;
class procedure TRecentPage_Modify.InitialListProperty (lp: TListProperty);
const c_cols: array[0..3] of integer = (sr_Title, sr_Abstract, sr_ModifyTime, sr_NodePath);
c_widths: array[0..3] of integer = (100, 150, 80, 100);
begin
inherited InitialListProperty (lp);
lp.ColList.Populate (c_cols);
lp.WidthList.Populate (c_widths);
end;
//----------------------
class function TRecentPage_Visit.PageType (): TPageType;
begin
result := ptRecentVisit;
end;
class procedure TRecentPage_Visit.InitialListProperty (lp: TListProperty);
const c_cols: array[0..3] of integer = (sr_Title, sr_Abstract, sr_VisitTime, sr_NodePath);
c_widths: array[0..3] of integer = (100, 150, 80, 100);
begin
inherited InitialListProperty (lp);
lp.ColList.Populate (c_cols);
lp.WidthList.Populate (c_widths);
end;
//----------------------
constructor TRecentRootHandler.Create (AParent: TPageSuper);
begin
inherited Create (AParent);
FCreateHandler := TRecentCreateHandler.Create (FPage);
FModifyHandler := TRecentModifyHandler.Create (FPage);
FVisitHandler := TRecentVisitHandler.Create (FPage);
AddChilds;
end;
destructor TRecentRootHandler.Destroy ();
begin
FCreateHandler.free;
FModifyHandler.Free;
FVisitHandler.free;
inherited;
end;
function TRecentRootHandler.PageType (): TPageType;
begin
result := ptRecentRoot;
end;
function TRecentRootHandler.NameResource (): integer;
begin
result := sr_RecentRoot;
end;
function TRecentRootHandler.MenuItem_Manage (): integer;
begin
result := m_ManageRecent;
end;
procedure TRecentRootHandler.ExecuteCommand (opr: word);
begin
if opr = m_managerecent then
begin
inherited ExecuteCommand (opr);
AddChilds;
end;
end;
procedure TRecentRootHandler.AddChilds ();
begin
with FPage.Childs do
begin
AddChild (FCreateHandler.Page.id);
AddChild (FModifyHandler.Page.id);
AddChild (FVisitHandler.Page.id);
end;
end;
//--------------------------
function TRecentCreateHandler.PageType (): TPageType;
begin
result := ptRecentCreate;
end;
function TRecentCreateHandler.NameResource (): integer;
begin
result := sr_RecentCreate;
end;
function TRecentCreateHandler.MenuItem_Manage (): integer;
begin
result := -1;
end;
function TRecentCreateHandler.MenuItem_List (): integer;
begin
result := m_RecentCreate;
end;
//--------------------------
function TRecentModifyHandler.PageType (): TPageType;
begin
result := ptRecentModify;
end;
function TRecentModifyHandler.NameResource (): integer;
begin
result := sr_RecentModify;
end;
function TRecentModifyHandler.MenuItem_Manage (): integer;
begin
result := -1;
end;
function TRecentModifyHandler.MenuItem_List (): integer;
begin
result := m_RecentModify;
end;
//------------------------------
function TRecentVisitHandler.PageType (): TPageType;
begin
result := ptRecentVisit;
end;
function TRecentVisitHandler.NameResource (): integer;
begin
result := sr_RecentVisit;
end;
function TRecentVisitHandler.MenuItem_Manage (): integer;
begin
result := -1;
end;
function TRecentVisitHandler.MenuItem_List (): integer;
begin
result := m_RecentVisit;
end;
//--------------------------
initialization
PageFactory.RegisterClass (TRecentPage_Root);
PageImageList.AddImageWithOverlay (ptRecentRoot, m_recentroot);
PageFactory.RegisterClass (TRecentPage_Create);
PageImageList.AddImageWithOverlay (ptRecentCreate, m_recentcreate);
PageFactory.RegisterClass (TRecentPage_Modify);
PageImageList.AddImageWithOverlay (ptRecentModify, m_recentmodify);
PageFactory.RegisterClass (TRecentPage_Visit);
PageImageList.AddImageWithOverlay (ptRecentVisit, m_recentvisit);
finalization
end.
|
unit DrillingPlanFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Ex_Grid, Contnrs, Well, LicenseZone, LicenseZonePoster, baseObjects,
GRRObligation, ObligationToolsFrame;
type
TfrmDrillingPlan = class(TFrame)
frmObligationTools1: TfrmObligationTools;
procedure grdvwDrillingPlanGetCellText(Sender: TObject;
Cell: TGridCell; var Value: String);
procedure grdvwDrillingPlanGetCellColors(Sender: TObject;
Cell: TGridCell; Canvas: TCanvas);
procedure grdvwDrillingPlanEditAcceptKey(Sender: TObject;
Cell: TGridCell; Key: Char; var Accept: Boolean);
procedure grdvwDrillingPlanSetEditText(Sender: TObject;
Cell: TGridCell; var Value: String);
procedure grdvwDrillingPlanEditCloseUp(Sender: TObject;
Cell: TGridCell; ItemIndex: Integer; var Accept: Boolean);
procedure grdvwDrillingPlanChange(Sender: TObject; Cell: TGridCell;
Selected: Boolean);
procedure frmObligationTools1actnDeleteObligationExecute(
Sender: TObject);
private
{ Private declarations }
FLicenseZone: TLicenseZone;
FSaved: boolean;
procedure ObligationsChanged(Sender: TObject);
procedure SetLicenseZone(const Value: TLicenseZone);
procedure LoadDrillingObligations;
function GetCurrentObligation: TObligation;
public
{ Public declarations }
property LicenseZone: TLicenseZone read FLicenseZone write SetLicenseZone;
property CurrentObligation: TObligation read GetCurrentObligation;
procedure RefreshDrillingObligations;
property Saved: boolean read FSaved;
procedure Save;
procedure Cancel;
constructor Create(AOwner: TComponent); override;
end;
implementation
uses Facade;
{$R *.dfm}
constructor TfrmDrillingPlan.Create(AOwner: TComponent);
begin
inherited;
FSaved := true;
frmObligationTools1.OnObligationAdded := ObligationsChanged;
frmObligationTools1.OnObligationRemoved := ObligationsChanged;
end;
procedure TfrmDrillingPlan.LoadDrillingObligations;
begin
TMainFacade.GetInstance.AllWellCategories.MakeList(grdvwDrillingPlan.Columns[3].PickList, False, true);
frmObligationTools1.Obligations := FLicenseZone.License.AllDrillObligations;
RefreshDrillingObligations;
end;
procedure TfrmDrillingPlan.SetLicenseZone(const Value: TLicenseZone);
begin
if FLicenseZone <> Value then
begin
FLicenseZone := Value;
LoadDrillingObligations;
FSaved := true;
end;
end;
procedure TfrmDrillingPlan.grdvwDrillingPlanGetCellText(Sender: TObject;
Cell: TGridCell; var Value: String);
begin
case Cell.Col of
0: Value := IntToStr(LicenseZone.License.AllDrillObligations.Items[Cell.Row].WellCount);
1:
begin
if LicenseZone.License.AllDrillObligations.Items[Cell.Row].StartDate <> 0 then
Value := DateToStr(LicenseZone.License.AllDrillObligations.Items[Cell.Row].StartDate)
else
Value := '';
end;
2:
begin
if LicenseZone.License.AllDrillObligations.Items[Cell.Row].FinishDate <> 0 then
Value := DateToStr(LicenseZone.License.AllDrillObligations.Items[Cell.Row].FinishDate)
else
Value := '';
end;
3: Value := LicenseZone.License.AllDrillObligations.Items[Cell.Row].WellCategory.List();
4: Value := LicenseZone.License.AllDrillObligations.Items[Cell.Row].Comment;
5: Value := LicenseZone.License.AllDrillObligations.Items[Cell.Row].DoneString;
end;
end;
procedure TfrmDrillingPlan.grdvwDrillingPlanGetCellColors(Sender: TObject;
Cell: TGridCell; Canvas: TCanvas);
var o: TDrillObligation;
begin
o := LicenseZone.License.AllDrillObligations.Items[Cell.Row];
if (o.FinishDate > 0) and (o.FinishDate <= TMainFacade.GetInstance.ActiveVersion.VersionFinishDate) then
begin
if o.Done then Canvas.Brush.Color := $00C8F9E3
else Canvas.Brush.Color := $00DFE7FF;
end
else if o.Done then Canvas.Brush.Color := $00C8F9E3
end;
procedure TfrmDrillingPlan.grdvwDrillingPlanEditAcceptKey(Sender: TObject;
Cell: TGridCell; Key: Char; var Accept: Boolean);
begin
Accept := not(Cell.Col in [3, 5]);
if Accept then
begin
// well number
if Cell.Col = 0 then
Accept := Pos(Key, '0123456789') > 0
else if (Cell.Col in [1, 2]) then
Accept := (Pos(Key, '0123456789.') > 0);
end;
end;
procedure TfrmDrillingPlan.grdvwDrillingPlanSetEditText(Sender: TObject;
Cell: TGridCell; var Value: String);
begin
Value := trim(Value);
case Cell.Col of
0:
begin
LicenseZone.License.AllDrillObligations.Items[Cell.Row].WellCount := StrToInt(Value);
FSaved := false;
end;
1:
begin
if Value <> '' then
LicenseZone.License.AllDrillObligations.Items[Cell.Row].StartDate := StrToDateTime(Value)
else
LicenseZone.License.AllDrillObligations.Items[Cell.Row].StartDate := 0;
grdvwDrillingPlan.Refresh;
FSaved := false;
end;
2:
begin
if Value <> '' then
LicenseZone.License.AllDrillObligations.Items[Cell.Row].FinishDate := StrToDateTime(Value)
else
LicenseZone.License.AllDrillObligations.Items[Cell.Row].FinishDate := 0;
grdvwDrillingPlan.Refresh;
FSaved := false;
end;
4:
begin
LicenseZone.License.AllDrillObligations.Items[Cell.Row].Comment := Value;
FSaved := false;
end;
end;
end;
procedure TfrmDrillingPlan.grdvwDrillingPlanEditCloseUp(Sender: TObject;
Cell: TGridCell; ItemIndex: Integer; var Accept: Boolean);
begin
if ItemIndex > -1 then
begin
if Cell.Col = 3 then
begin
LicenseZone.License.AllDrillObligations.Items[Cell.Row].WellCategory := TMainFacade.GetInstance.AllWellCategories.Items[ItemIndex];
FSaved := false;
end;
end;
end;
procedure TfrmDrillingPlan.Cancel;
begin
LicenseZone.License.ClearDrillObligations;
end;
procedure TfrmDrillingPlan.Save;
begin
LicenseZone.License.AllDrillObligations.Update(nil);
end;
procedure TfrmDrillingPlan.ObligationsChanged(Sender: TObject);
begin
grdvwDrillingPlan.Rows.Count := LicenseZone.License.AllDrillObligations.Count;
FSaved := false;
grdvwDrillingPlan.Refresh;
end;
procedure TfrmDrillingPlan.grdvwDrillingPlanChange(Sender: TObject;
Cell: TGridCell; Selected: Boolean);
begin
frmObligationTools1.SelectedObligation := CurrentObligation;
end;
function TfrmDrillingPlan.GetCurrentObligation: TObligation;
begin
try
Result := FLicenseZone.AllDrillObligations.Items[grdvwDrillingPlan.Row]
except
Result := nil;
end;
end;
procedure TfrmDrillingPlan.frmObligationTools1actnDeleteObligationExecute(
Sender: TObject);
begin
frmObligationTools1.actnDeleteObligationExecute(Sender);
end;
procedure TfrmDrillingPlan.RefreshDrillingObligations;
begin
grdvwDrillingPlan.Rows.Count := FLicenseZone.License.AllDrillObligations.Count;
grdvwDrillingPlan.Refresh;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP 3.0
Description: Model relacionado à tabela [FORNECEDOR]
The MIT License
Copyright: Copyright (C) 2021 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (alberteije@gmail.com)
@version 1.0.0
*******************************************************************************}
unit Fornecedor;
interface
uses
MVCFramework.Serializer.Commons, ModelBase;
type
[MVCNameCase(ncLowerCase)]
TFornecedor = class(TModelBase)
private
FId: Integer;
FNome: string;
FFantasia: string;
FEmail: string;
FUrl: string;
FCpfCnpj: string;
FRg: string;
FOrgaoRg: string;
FDataEmissaoRg: Integer;
FSexo: string;
FInscricaoEstadual: string;
FInscricaoMunicipal: string;
FTipoPessoa: string;
FDataCadastro: Integer;
FLogradouro: string;
FNumero: string;
FComplemento: string;
FCep: string;
FBairro: string;
FCidade: string;
FUf: string;
FTelefone: string;
FCelular: string;
FContato: string;
FCodigoIbgeCidade: Integer;
FCodigoIbgeUf: Integer;
public
// procedure ValidarInsercao; override;
// procedure ValidarAlteracao; override;
// procedure ValidarExclusao; override;
[MVCColumnAttribute('ID', True)]
[MVCNameAsAttribute('id')]
property Id: Integer read FId write FId;
[MVCColumnAttribute('NOME')]
[MVCNameAsAttribute('nome')]
property Nome: string read FNome write FNome;
[MVCColumnAttribute('FANTASIA')]
[MVCNameAsAttribute('fantasia')]
property Fantasia: string read FFantasia write FFantasia;
[MVCColumnAttribute('EMAIL')]
[MVCNameAsAttribute('email')]
property Email: string read FEmail write FEmail;
[MVCColumnAttribute('URL')]
[MVCNameAsAttribute('url')]
property Url: string read FUrl write FUrl;
[MVCColumnAttribute('CPF_CNPJ')]
[MVCNameAsAttribute('cpfCnpj')]
property CpfCnpj: string read FCpfCnpj write FCpfCnpj;
[MVCColumnAttribute('RG')]
[MVCNameAsAttribute('rg')]
property Rg: string read FRg write FRg;
[MVCColumnAttribute('ORGAO_RG')]
[MVCNameAsAttribute('orgaoRg')]
property OrgaoRg: string read FOrgaoRg write FOrgaoRg;
[MVCColumnAttribute('DATA_EMISSAO_RG')]
[MVCNameAsAttribute('dataEmissaoRg')]
property DataEmissaoRg: Integer read FDataEmissaoRg write FDataEmissaoRg;
[MVCColumnAttribute('SEXO')]
[MVCNameAsAttribute('sexo')]
property Sexo: string read FSexo write FSexo;
[MVCColumnAttribute('INSCRICAO_ESTADUAL')]
[MVCNameAsAttribute('inscricaoEstadual')]
property InscricaoEstadual: string read FInscricaoEstadual write FInscricaoEstadual;
[MVCColumnAttribute('INSCRICAO_MUNICIPAL')]
[MVCNameAsAttribute('inscricaoMunicipal')]
property InscricaoMunicipal: string read FInscricaoMunicipal write FInscricaoMunicipal;
[MVCColumnAttribute('TIPO_PESSOA')]
[MVCNameAsAttribute('tipoPessoa')]
property TipoPessoa: string read FTipoPessoa write FTipoPessoa;
[MVCColumnAttribute('DATA_CADASTRO')]
[MVCNameAsAttribute('dataCadastro')]
property DataCadastro: Integer read FDataCadastro write FDataCadastro;
[MVCColumnAttribute('LOGRADOURO')]
[MVCNameAsAttribute('logradouro')]
property Logradouro: string read FLogradouro write FLogradouro;
[MVCColumnAttribute('NUMERO')]
[MVCNameAsAttribute('numero')]
property Numero: string read FNumero write FNumero;
[MVCColumnAttribute('COMPLEMENTO')]
[MVCNameAsAttribute('complemento')]
property Complemento: string read FComplemento write FComplemento;
[MVCColumnAttribute('CEP')]
[MVCNameAsAttribute('cep')]
property Cep: string read FCep write FCep;
[MVCColumnAttribute('BAIRRO')]
[MVCNameAsAttribute('bairro')]
property Bairro: string read FBairro write FBairro;
[MVCColumnAttribute('CIDADE')]
[MVCNameAsAttribute('cidade')]
property Cidade: string read FCidade write FCidade;
[MVCColumnAttribute('UF')]
[MVCNameAsAttribute('uf')]
property Uf: string read FUf write FUf;
[MVCColumnAttribute('TELEFONE')]
[MVCNameAsAttribute('telefone')]
property Telefone: string read FTelefone write FTelefone;
[MVCColumnAttribute('CELULAR')]
[MVCNameAsAttribute('celular')]
property Celular: string read FCelular write FCelular;
[MVCColumnAttribute('CONTATO')]
[MVCNameAsAttribute('contato')]
property Contato: string read FContato write FContato;
[MVCColumnAttribute('CODIGO_IBGE_CIDADE')]
[MVCNameAsAttribute('codigoIbgeCidade')]
property CodigoIbgeCidade: Integer read FCodigoIbgeCidade write FCodigoIbgeCidade;
[MVCColumnAttribute('CODIGO_IBGE_UF')]
[MVCNameAsAttribute('codigoIbgeUf')]
property CodigoIbgeUf: Integer read FCodigoIbgeUf write FCodigoIbgeUf;
end;
implementation
{ TFornecedor }
end. |
unit RT_DateProviderTest;
interface
uses
Windows, Classes, SysUtils, TestFramework,
RT_DateProvider;
type
TRTDateProviderTest = class (TTestCase, IRTDateProviderConfiguration)
private
FFakeDateEnabled: Boolean;
FFakeDateTime: TDateTime;
function IsFakeDateEnabled: Boolean;
function GetFakeDateTime: TDateTime;
protected
procedure Setup; override;
procedure Teardown; override;
published
procedure TestCreate;
procedure TestNow;
procedure TestDate;
end;
implementation
{ TRTDateProviderTest }
{ Private declarations }
function TRTDateProviderTest.IsFakeDateEnabled: Boolean;
begin
Result := FFakeDateEnabled;
end;
function TRTDateProviderTest.GetFakeDateTime: TDateTime;
begin
Result := FFakeDateTime;
end;
{ Protected declarations }
procedure TRTDateProviderTest.Setup;
begin
TRTDateProvider.Instance.Configuration := Self;
end;
procedure TRTDateProviderTest.Teardown;
begin
TRTDateProvider.Instance.Configuration := TRTDateProviderConfiguration.Create;
end;
{ Test cases }
procedure TRTDateProviderTest.TestCreate;
begin
CheckNotNull(TRTDateProvider.Instance);
end;
procedure TRTDateProviderTest.TestNow;
var
Settings: TFormatSettings;
begin
GetLocaleFormatSettings(1045, Settings);
FFakeDateTime := StrToDateTime('2005-01-02 12:13:14.015', Settings);
FFakeDateEnabled := False;
CheckNotEquals(StrToDateTime('2005-01-02 12:13:14.015', Settings), TRTDateProvider.Instance.Now);
FFakeDateEnabled := True;
CheckEquals(StrToDateTime('2005-01-02 12:13:14.015', Settings), TRTDateProvider.Instance.Now);
end;
procedure TRTDateProviderTest.TestDate;
var
Settings: TFormatSettings;
begin
GetLocaleFormatSettings(1045, Settings);
FFakeDateTime := StrToDateTime('2005-01-02 12:13:14.015', Settings);
FFakeDateEnabled := False;
CheckNotEquals(StrToDateTime('2005-01-02', Settings), TRTDateProvider.Instance.Date);
FFakeDateEnabled := True;
CheckEquals(StrToDateTime('2005-01-02', Settings), TRTDateProvider.Instance.Date);
end;
initialization
RegisterTest(TRTDateProviderTest.Suite)
end.
|
{@unit RLSpoolFilter - Implementação do filtro padrão para impressoras. }
unit RLSpoolFilter;
interface
uses
Classes, SysUtils, Contnrs,
{$ifndef LINUX}
Windows, Graphics, RLMetaVCL,
{$else}
Types, QGraphics, RLMetaCLX,
{$endif}
RLMetaFile, RLFilters, RLTypes, RLPrinters, RLConsts;
type
{ TRLSpoolFilter }
{@class TRLSpoolFilter - Filtro de impressão padrão.
É o filtro natural que envia as páginas para o spooler do SO.
@links TRLDraftFilter.
@pub }
TRLSpoolFilter=class(TRLCustomPrintFilter)
private
// variables
fPrinterRect:TRect;
fDocStarted :boolean;
fPaperWidth :double;
fPaperHeight:double;
fOrientation:TRLMetaOrientation;
procedure SetDocBounds(aPaperWidth,aPaperHeight:double; aOrientation:TRLMetaOrientation);
protected
// override methods
procedure InternalBeginDoc; override;
procedure InternalEndDoc; override;
procedure InternalNewPage; override;
procedure InternalDrawPage(aPage:TRLGraphicSurface); override;
public
// constructors & destructors
constructor Create(aOwner:TComponent); override;
end;
{/@class}
{@func SpoolFilter - Referência para o filtro padrão de impressora.
@links TRLSpoolFilter. :/}
function SpoolFilter:TRLSpoolFilter;
{/@unit}
implementation
var
SpoolFilterInstance:TRLSpoolFilter=nil;
function SpoolFilter:TRLSpoolFilter;
begin
if not Assigned(SpoolFilterInstance) then
SpoolFilterInstance:=TRLSpoolFilter.Create(nil);
result:=SpoolFilterInstance;
end;
{ TRLSpoolFilter }
constructor TRLSpoolFilter.Create(aOwner: TComponent);
begin
inherited;
end;
procedure TRLSpoolFilter.SetDocBounds(aPaperWidth,aPaperHeight:double; aOrientation:TRLMetaOrientation);
var
changed:boolean;
metrics:TRLPrinterMetrics;
begin
changed:=(aPaperWidth<>fPaperWidth) or (aPaperHeight<>fPaperHeight) or (aOrientation<>fOrientation);
if not fDocStarted or changed then
begin
fPaperWidth :=aPaperWidth;
fPaperHeight:=aPaperHeight;
fOrientation:=aOrientation;
if fDocStarted then
RLPrinter.EndDoc;
//
RLPrinter.SetPaperSize(fPaperWidth,fPaperHeight,fOrientation=MetaOrientationLandscape,false);
RLPrinter.LoadMetrics(metrics);
//
fPrinterRect.Left:=0;
fPrinterRect.Top :=0;
if fOrientation=MetaOrientationLandscape then
begin
fPrinterRect.Right :=Round(fPaperHeight*metrics.PPIX/InchAsMM);
fPrinterRect.Bottom:=Round(fPaperWidth *metrics.PPIY/InchAsMM);
OffsetRect(fPrinterRect,-metrics.MarginBottom,-metrics.MarginLeft);
end
else
begin
fPrinterRect.Right :=Round(fPaperWidth *metrics.PPIX/InchAsMM);
fPrinterRect.Bottom:=Round(fPaperHeight*metrics.PPIY/InchAsMM);
OffsetRect(fPrinterRect,-metrics.MarginLeft,-metrics.MarginTop);
end;
//
RLPrinter.BeginDoc;
fDocStarted:=true;
end;
end;
procedure TRLSpoolFilter.InternalBeginDoc;
begin
fDocStarted:=false;
SetDocBounds(Pages.PaperWidth,Pages.PaperHeight,Pages.Orientation);
end;
procedure TRLSpoolFilter.InternalEndDoc;
begin
RLPrinter.EndDoc;
end;
procedure TRLSpoolFilter.InternalNewPage;
begin
RLPrinter.NewPage;
end;
procedure TRLSpoolFilter.InternalDrawPage(aPage:TRLGraphicSurface);
var
xfactor :double;
yfactor :double;
cliprct :TRect;
clipstack:TList;
obj :TRLGraphicObject;
i :integer;
thecanvas:TCanvas;
procedure ProjectX(const s:integer; var d:integer);
begin
d:=fPrinterRect.Left+Round(s*xfactor);
end;
procedure ProjectY(const s:integer; var d:integer);
begin
d:=fPrinterRect.Top+Round(s*yfactor);
end;
procedure ProjectRect(const s:TRLMetaRect; var d:TRect);
begin
ProjectX(s.Left ,d.Left);
ProjectY(s.Top ,d.Top);
ProjectX(s.Right ,d.Right);
ProjectY(s.Bottom,d.Bottom);
if not (d.Right>d.Left) then
d.Right:=d.Left+1;
if not (d.Bottom>d.Top) then
d.Bottom:=d.Top+1;
end;
procedure DrawPixel(aObj:TRLPixelObject);
var
r:TRect;
begin
ProjectRect(aObj.BoundsRect,r);
//
thecanvas.Brush.Style:=bsSolid;
thecanvas.Brush.Color:=FromMetaColor(aObj.Color);
thecanvas.FillRect(r);
end;
procedure ProjectPoint(const s:TRLMetaPoint; var d:TPoint);
begin
ProjectX(s.X,d.X);
ProjectY(s.Y,d.Y);
end;
procedure DrawLine(aObj:TRLLineObject);
var
p1,p2:TPoint;
begin
ProjectPoint(aObj.FromPoint,p1);
ProjectPoint(aObj.ToPoint,p2);
//
FromMetaPen(aObj.Pen,thecanvas.Pen);
PenInflate(thecanvas.Pen,xfactor);
FromMetaBrush(aObj.Brush,thecanvas.Brush);
thecanvas.MoveTo(p1.X,p1.Y);
CanvasLineToEx(thecanvas,p2.X,p2.Y);
end;
procedure DrawRectangle(aObj:TRLRectangleObject);
var
r:TRect;
begin
ProjectRect(aObj.BoundsRect,r);
//
FromMetaPen(aObj.Pen,thecanvas.Pen);
PenInflate(thecanvas.Pen,xfactor);
FromMetaBrush(aObj.Brush,thecanvas.Brush);
thecanvas.Rectangle(r.Left,r.Top,r.Right,r.Bottom);
end;
procedure DrawText(aObj:TRLTextObject);
var
r:TRect;
o:TPoint;
t:string;
begin
ProjectRect(aObj.BoundsRect,r);
ProjectPoint(aObj.Origin,o);
//
FromMetaBrush(aObj.Brush,thecanvas.Brush);
FromMetaFont(aObj.Font,thecanvas.Font,yfactor);
t:=String(aObj.DisplayText);//bds2010
CanvasTextRectEx(thecanvas,r,o.X,o.Y,t,aObj.Alignment,aObj.Layout,aObj.TextFlags);
end;
procedure DrawFillRect(aObj:TRLFillRectObject);
var
r:TRect;
begin
ProjectRect(aObj.BoundsRect,r);
//
FromMetaBrush(aObj.Brush,thecanvas.Brush);
thecanvas.FillRect(r);
end;
procedure DrawEllipse(aObj:TRLEllipseObject);
var
r:TRect;
begin
ProjectRect(aObj.BoundsRect,r);
//
FromMetaPen(aObj.Pen,thecanvas.Pen);
PenInflate(thecanvas.Pen,xfactor);
FromMetaBrush(aObj.Brush,thecanvas.Brush);
thecanvas.Ellipse(r);
end;
procedure ProjectPoints(const s:TRLMetaPointArray; var p:TPointArray);
var
i:integer;
begin
SetLength(p,High(s)+1);
for i:=0 to High(p) do
ProjectPoint(s[i],p[i]);
end;
procedure DrawPolygon(aObj:TRLPolygonObject);
var
p:TPointArray;
begin
ProjectPoints(aObj.Points,p);
//
FromMetaPen(aObj.Pen,thecanvas.Pen);
PenInflate(thecanvas.Pen,xfactor);
FromMetaBrush(aObj.Brush,thecanvas.Brush);
thecanvas.Polygon(p);
end;
procedure DrawPolyline(aObj:TRLPolylineObject);
var
p:TPointArray;
begin
ProjectPoints(aObj.Points,p);
//
FromMetaPen(aObj.Pen,thecanvas.Pen);
PenInflate(thecanvas.Pen,xfactor);
thecanvas.Brush.Style:=bsClear;
thecanvas.Polyline(p);
end;
procedure DrawImage(aObj:TRLImageObject);
var
r:TRect;
begin
ProjectRect(aObj.BoundsRect,r);
CanvasStretchDraw(thecanvas,r,aObj.Data,aObj.Parity);
end;
procedure PushClipRect(const aRect:TRect);
var
p:PRect;
begin
New(p);
p^:=aRect;
clipstack.Insert(0,p);
end;
procedure PopClipRect(var aRect:TRect);
var
p:PRect;
begin
p:=clipstack[0];
aRect:=p^;
Dispose(p);
clipstack.Delete(0);
end;
procedure DrawSetClipRect(aObj:TRLSetClipRectObject);
begin
PushClipRect(cliprct);
ProjectRect(aObj.BoundsRect,cliprct);
CanvasSetClipRect(thecanvas,cliprct);
end;
procedure DrawResetClipRect(aObj:TRLResetClipRectObject);
begin
PopClipRect(cliprct);
CanvasSetClipRect(thecanvas,cliprct);
end;
begin
SetDocBounds(aPage.PaperWidth,aPage.PaperHeight,aPage.Orientation);
//
if aPage.Width=0 then
xfactor:=1
else
xfactor:=(fPrinterRect.Right-fPrinterRect.Left)/aPage.Width;
if aPage.Height=0 then
yfactor:=1
else
yfactor:=(fPrinterRect.Bottom-fPrinterRect.Top)/aPage.Height;
//
thecanvas:=RLPrinter.Canvas;
clipstack:=TList.Create;
try
CanvasStart(thecanvas);
try
cliprct:=fPrinterRect;
CanvasSetClipRect(thecanvas,cliprct);
try
for i:=0 to aPage.ObjectCount-1 do
begin
obj:=TRLGraphicObject(aPage.Objects[i]);
if obj is TRLPixelObject then
DrawPixel(TRLPixelObject(obj))
else if obj is TRLLineObject then
DrawLine(TRLLineObject(obj))
else if obj is TRLRectangleObject then
DrawRectangle(TRLRectangleObject(obj))
else if obj is TRLTextObject then
DrawText(TRLTextObject(obj))
else if obj is TRLFillRectObject then
DrawFillRect(TRLFillRectObject(obj))
else if obj is TRLEllipseObject then
DrawEllipse(TRLEllipseObject(obj))
else if obj is TRLPolygonObject then
DrawPolygon(TRLPolygonObject(obj))
else if obj is TRLPolylineObject then
DrawPolyline(TRLPolylineObject(obj))
else if obj is TRLImageObject then
DrawImage(TRLImageObject(obj))
else if obj is TRLSetClipRectObject then
DrawSetClipRect(TRLSetClipRectObject(obj))
else if obj is TRLResetClipRectObject then
DrawResetClipRect(TRLResetClipRectObject(obj));
end;
finally
CanvasResetClipRect(thecanvas);
end;
finally
CanvasStop(thecanvas);
end;
finally
while clipstack.Count>0 do
PopClipRect(cliprct);
clipstack.free;
end;
end;
initialization
finalization
if Assigned(SpoolFilterInstance) then
SpoolFilterInstance.free;
end.
|
unit AsyncIO.Coroutine.Net.IP;
interface
uses
AsyncIO, AsyncIO.OpResults, AsyncIO.Net.IP, AsyncIO.Coroutine;
type
ConnectResult = record
{$REGION 'Implementation details'}
strict private
FRes: OpResult;
FEndpoint: IPEndpoint;
function GetValue: integer;
function GetSuccess: boolean;
function GetMessage: string;
function GetResult: OpResult;
private
function GetEndpoint: IPEndpoint;
{$ENDREGION}
public
class function Create(const Res: OpResult; const Endpoint: IPEndpoint): ConnectResult; static;
class operator Implicit(const ConnectRes: ConnectResult): OpResult;
procedure RaiseException(const AdditionalInfo: string = '');
property Value: integer read GetValue;
property Success: boolean read GetSuccess;
property Message: string read GetMessage;
property Result: OpResult read GetResult;
property Endpoint: IPEndpoint read GetEndpoint;
end;
function AsyncAccept(const Acceptor: IPAcceptor; const Peer: IPSocket; const Yield: YieldContext): OpResult; overload;
function AsyncConnect(const Socket: IPSocket; const Endpoints: IPResolver.Results; const Yield: YieldContext): ConnectResult; overload;
function AsyncConnect(const Socket: IPSocket; const Endpoints: TArray<IPEndpoint>; const Yield: YieldContext): ConnectResult; overload;
function AsyncConnect(const Socket: IPSocket; const Endpoints: IPResolver.Results; const Condition: ConnectCondition; const Yield: YieldContext): ConnectResult; overload;
function AsyncConnect(const Socket: IPSocket; const Endpoints: TArray<IPEndpoint>; const Condition: ConnectCondition; const Yield: YieldContext): ConnectResult; overload;
implementation
uses
AsyncIO.Coroutine.Detail;
function AsyncAccept(const Acceptor: IPAcceptor; const Peer: IPSocket; const Yield: YieldContext): OpResult;
var
yieldImpl: IYieldContext;
handler: OpHandler;
opRes: OpResult;
begin
yieldImpl := Yield;
handler :=
procedure(const Res: OpResult)
begin
opRes := Res;
// set return
yieldImpl.SetServiceHandlerCoroutine();
end;
Acceptor.AsyncAccept(Peer, handler);
yieldImpl.Wait;
result := opRes;
end;
function AsyncConnect(const Socket: IPSocket; const Endpoints: IPResolver.Results; const Yield: YieldContext): ConnectResult;
var
yieldImpl: IYieldContext;
handler: ConnectHandler;
connectRes: ConnectResult;
begin
yieldImpl := Yield;
handler :=
procedure(const Res: OpResult; const Endpoint: IPEndpoint)
begin
connectRes := ConnectResult.Create(Res, Endpoint);
// set return
yieldImpl.SetServiceHandlerCoroutine();
end;
AsyncIO.Net.IP.AsyncConnect(Socket, Endpoints, handler);
yieldImpl.Wait;
result := connectRes;
end;
function AsyncConnect(const Socket: IPSocket; const Endpoints: TArray<IPEndpoint>; const Yield: YieldContext): ConnectResult;
var
yieldImpl: IYieldContext;
handler: ConnectHandler;
connectRes: ConnectResult;
begin
yieldImpl := Yield;
handler :=
procedure(const Res: OpResult; const Endpoint: IPEndpoint)
begin
connectRes := ConnectResult.Create(Res, Endpoint);
// set return
yieldImpl.SetServiceHandlerCoroutine();
end;
AsyncIO.Net.IP.AsyncConnect(Socket, Endpoints, handler);
yieldImpl.Wait;
result := connectRes;
end;
function AsyncConnect(const Socket: IPSocket; const Endpoints: IPResolver.Results; const Condition: ConnectCondition; const Yield: YieldContext): ConnectResult;
var
yieldImpl: IYieldContext;
handler: ConnectHandler;
connectRes: ConnectResult;
begin
yieldImpl := Yield;
handler :=
procedure(const Res: OpResult; const Endpoint: IPEndpoint)
begin
connectRes := ConnectResult.Create(Res, Endpoint);
// set return
yieldImpl.SetServiceHandlerCoroutine();
end;
AsyncIO.Net.IP.AsyncConnect(Socket, Endpoints, handler);
yieldImpl.Wait;
result := connectRes;
end;
function AsyncConnect(const Socket: IPSocket; const Endpoints: TArray<IPEndpoint>; const Condition: ConnectCondition; const Yield: YieldContext): ConnectResult;
var
yieldImpl: IYieldContext;
handler: ConnectHandler;
connectRes: ConnectResult;
begin
yieldImpl := Yield;
handler :=
procedure(const Res: OpResult; const Endpoint: IPEndpoint)
begin
connectRes := ConnectResult.Create(Res, Endpoint);
// set return
yieldImpl.SetServiceHandlerCoroutine();
end;
AsyncIO.Net.IP.AsyncConnect(Socket, Endpoints, handler);
yieldImpl.Wait;
result := connectRes;
end;
{ ConnectResult }
class function ConnectResult.Create(const Res: OpResult;
const Endpoint: IPEndpoint): ConnectResult;
begin
result.FRes := Res;
result.FEndpoint := Endpoint;
end;
function ConnectResult.GetEndpoint: IPEndpoint;
begin
result := FEndpoint;
end;
function ConnectResult.GetMessage: string;
begin
result := FRes.Message;
end;
function ConnectResult.GetResult: OpResult;
begin
result := FRes;
end;
function ConnectResult.GetSuccess: boolean;
begin
result := FRes.Success;
end;
function ConnectResult.GetValue: integer;
begin
result := FRes.Value;
end;
class operator ConnectResult.Implicit(
const ConnectRes: ConnectResult): OpResult;
begin
result := ConnectRes.FRes;
end;
procedure ConnectResult.RaiseException(const AdditionalInfo: string);
begin
FRes.RaiseException(AdditionalInfo);
end;
end.
|
unit Model;
interface
uses System.Classes, System.SysUtils, System.Generics.Collections, Data.Db,
vcl.Controls, vcl.ComCtrls, IBQuery, Utils;
type
TFieldInfo = class
type
TCompareRef = reference to function(): Boolean;
constructor Create(CurrentValue, PreviousValue, DisplayName: string);
overload;
constructor Create(CurrentValue, PreviousValue, DisplayName: string;
CompareRef: TCompareRef); overload;
private
CompareRef: TCompareRef;
public
CurrentValue: string;
PreviousValue: string;
DisplayName: string;
function Compare(): Boolean;
end;
TRecordInfo = class
type
TState = (stDefault, stAdded, stDeleted, stModified, stUnmodified, stChildModified);
constructor Create(); overload ;
constructor Create(QFields: TFields); overload;
protected
function GetState(QFields: TFields): TState; virtual;
function GetFields(QFields: TFields): TMyList<TFieldInfo>; virtual; abstract;
function GetItems(QFields: TFields): TMyList<TRecordInfo>;
virtual; abstract;
function GetDisplayText(QFields: TFields): String; virtual; abstract;
public
State: TState;
Fields: TMyList<TFieldInfo>;
Items: TMyList<TRecordInfo>;
DisplayName: string;
DisplayText: string;
function HaveChanges(): Boolean; virtual;
function GetView(Parent: TWinControl): TControl; virtual;
end;
TRecordContainer = class (TRecordInfo)
protected
function GetFields(QFields: TFields): TMyList<TFieldInfo>; override;
function GetItems(QFields: TFields): TMyList<TRecordInfo>; override;
function GetDisplayText(QFields: TFields): String; override;
end;
implementation
constructor TRecordInfo.Create(QFields: TFields);
begin
Fields := GetFields(QFields);
Items := GetItems(QFields);
State := GetState(QFields);
DisplayText := GetDisplayText(QFields);
end;
constructor TRecordInfo.Create();
begin
Fields := GetFields(nil);
Items := GetItems(nil);
end;
function TRecordInfo.GetState(QFields: TFields): TState;
begin
if QFields.FieldByName('ID').AsString = '' then
begin
Result := TState.stDeleted;
end
else if QFields.FieldByName('ID1').AsString = '' then
begin
Result := TState.stAdded;
end
else if HaveChanges() then
begin
if Items.Any(
function(X: TRecordInfo): Boolean
begin
Result := X.HaveChanges();
end) then
begin
Result := TState.stChildModified
end
else
begin
Result := TState.stModified;
end;
end
else
begin
Result := TState.stUnmodified;
end;
end;
function TRecordInfo.GetView(Parent: TWinControl): TControl;
var
listView: TListView;
column: TListColumn;
item: TListItem;
field: TFieldInfo;
begin
listView := TListView.Create(Parent);
listView.Parent := Parent;
listView.ViewStyle := TViewStyle.vsReport;
listView.Width := Parent.Width;
listView.Height := Parent.Height;
column := listView.Columns.Add();
column.AutoSize := True;
column.Width := 100;
column.Caption := 'Поле';
column := listView.Columns.Add();
column.AutoSize := True;
column.Width := 100;
column.Caption := 'Є зміни';
column := listView.Columns.Add();
column.AutoSize := True;
column.Width := 300;
column.Caption := 'Поточне значення';
column := listView.Columns.Add();
column.AutoSize := True;
column.Width := 300;
column.Caption := 'Попереднє значення';
for field in Fields do
begin
item := listView.Items.Add;
item.Caption := field.DisplayName;
if field.Compare() then
begin
item.SubItems.Add('Так');
item.SubItems.Add(field.CurrentValue);
item.SubItems.Add(field.PreviousValue);
end
else
begin
item.SubItems.Add('Ні');
item.SubItems.Add(field.CurrentValue);
end;
end;
Result := listView;
end;
function TRecordInfo.HaveChanges(): Boolean;
var
Res: Boolean;
begin
if State <> stDefault then
begin
if State = stUnmodified then
begin
Exit(False);
end
else
begin
Exit(True);
end;
end;
Result := False;
Res := Fields.Any(
function(X: TFieldInfo): Boolean
begin
Result := X.Compare();
end);
if Res then
Exit(True);
Res := Items.Any(
function(X: TRecordInfo): Boolean
begin
Result := X.HaveChanges();
end);
if Res then
Exit(True);
end;
{ TFieldInfo }
constructor TFieldInfo.Create(CurrentValue, PreviousValue, DisplayName: string);
begin
Self.CurrentValue := CurrentValue;
Self.PreviousValue := PreviousValue;
Self.DisplayName := DisplayName;
CompareRef := function(): Boolean
begin
Result := CurrentValue <> PreviousValue;
end;
end;
constructor TFieldInfo.Create(CurrentValue, PreviousValue, DisplayName: string;
CompareRef: TCompareRef);
begin
Self.CurrentValue := CurrentValue;
Self.PreviousValue := PreviousValue;
Self.CompareRef := CompareRef;
Self.DisplayName := DisplayName;
end;
function TFieldInfo.Compare(): Boolean;
begin
Result := CompareRef();
end;
{ TRecordContainer }
function TRecordContainer.GetDisplayText(QFields: TFields): String;
begin
Result := '';
end;
function TRecordContainer.GetFields(QFields: TFields): TMyList<TFieldInfo>;
begin
Result := TMyList<TFieldInfo>.Create;
end;
function TRecordContainer.GetItems(QFields: TFields): TMyList<TRecordInfo>;
begin
Result := TMyList<TRecordInfo>.Create;
end;
end.
|
unit UnitMain;
interface
uses
System.Threading,
System.Generics.Collections,
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls;
type
TFormMain = class(TForm)
MemoLog: TMemo;
PanelHeader: TPanel;
ButtonAsync: TButton;
procedure ButtonAsyncClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
TLimiteDeCredito = class
private
FLimite: Double;
public
property Limite: Double read FLimite write FLimite;
end;
var
FormMain: TFormMain;
implementation
{$R *.dfm}
procedure TFormMain.ButtonAsyncClick(Sender: TObject);
var
FutureAsync: IFuture<TLimiteDeCredito>;
FutureAsyncThread: TThread;
begin
// Esta Future Retorna uma Lista de Pessoas..
FutureAsync := TTask.Future<TLimiteDeCredito>(function: TLimiteDeCredito
begin
TThread.Queue(TThread.CurrentThread, procedure
begin
MemoLog.Lines.Add('Iniciando o Future...');
end
);
Result := TLimiteDeCredito.Create;
Result.Limite := Random(2018) * Frac(Now);
Sleep(3000);
TThread.Queue(TThread.CurrentThread, procedure
begin
MemoLog.Lines.Add('Future Finalizou...');
end
);
end);
MemoLog.Lines.Add('Aguardando o Future...');
// Buscar o Valor da Future, caso ela não terminou de Processar, é travado aqui até que ela retorne o Result...
// -> MemoLog.Lines.Add('Valor ' + FutureAsync.Value.Limite.ToString());
// Se precisa, iniciar uma Thread Anonima para não Travar a Tela ao Buscar o Resultado da Future...
FutureAsyncThread := TThread.CreateAnonymousThread(procedure
var
Limite: TLimiteDeCredito;
begin
// Caso já tenha sido chamada FutureAsync.Value a Future não executa de novo, traz o resultado já calculado...
Limite := FutureAsync.Value;
// Este NIL está aqui, ao usar a Future dentro dessa Thread o Contador de Referencia é Incrementado,
// então é passado Nil, Decrementar o RefCount...
FutureAsync := Nil;
TThread.Queue(Nil, procedure
begin
MemoLog.Lines.Add(Limite.Limite.ToString());
end
);
Limite.Free;
end
);
FutureAsyncThread.FreeOnTerminate := True;
// Se precisar, executar o Future sem Congelar a Tela...
FutureAsyncThread.Start;
end;
end.
|
unit FMX.Wait;
interface
uses
System.Classes, System.SysUtils, FMX.Wait.Intf, FMX.Forms, System.Threading, FMX.Types, FMX.Wait.Frame;
type
TWait = class(TInterfacedObject, IWait)
private
procedure Wait(const AProc: TProc); overload;
procedure Wait(const AParent: TFmxObject; const AProc: TProc); overload;
class function New: IWait;
public
class procedure Start(const AProc: TProc); overload;
class procedure Start(const AParent: TFmxObject; const AProc: TProc); overload;
class procedure Run(const AProc: TProc);
class procedure Synchronize(const AProc: TProc);
class procedure WaitFor(const AProc: TProc; const ASleepTime: Integer = 50);
end;
implementation
class function TWait.New: IWait;
begin
Result := TWait.Create;
end;
procedure TWait.Wait(const AParent: TFmxObject; const AProc: TProc);
begin
{$WARN SYMBOL_PLATFORM OFF}
if (DebugHook = 1) then
begin
AProc;
Exit;
end;
{$WARN SYMBOL_PLATFORM ON}
TThread.CreateAnonymousThread(
procedure
var
LFrame: TFrameWait;
begin
try
TWait.Synchronize(
procedure
begin
if Assigned(AParent) then
begin
LFrame := TFrameWait.Create(AParent);
LFrame.Parent := AParent;
end
else
begin
LFrame := TFrameWait.Create(Screen.ActiveForm);
LFrame.Parent := Screen.ActiveForm;
end;
LFrame.Align := TAlignLayout.Contents;
LFrame.BitmapListAnimation.Start;
end);
if Assigned(AProc) then
AProc;
finally
TWait.Synchronize(
procedure
begin
LFrame.Owner.RemoveComponent(LFrame);
LFrame.DisposeOf;
end);
end;
end).Start;
end;
class procedure TWait.WaitFor(const AProc: TProc; const ASleepTime: Integer);
begin
{$WARN SYMBOL_PLATFORM OFF}
if (DebugHook = 1) then
begin
Sleep(ASleepTime);
AProc;
Exit;
end;
{$WARN SYMBOL_PLATFORM ON}
TThread.CreateAnonymousThread(
procedure
begin
Sleep(ASleepTime);
TThread.Synchronize(TThread.Current,
procedure
begin
AProc;
end);
end).Start;
end;
procedure TWait.Wait(const AProc: TProc);
begin
Self.Wait(nil, AProc);
end;
class procedure TWait.Run(const AProc: TProc);
begin
{$WARN SYMBOL_PLATFORM OFF}
if (DebugHook = 1) then
begin
AProc;
Exit;
end;
{$WARN SYMBOL_PLATFORM ON}
TThread.CreateAnonymousThread(
procedure
begin
if Assigned(AProc) then
AProc;
end).Start;
end;
class procedure TWait.Start(const AParent: TFmxObject; const AProc: TProc);
begin
TWait.New.Wait(AParent, AProc);
end;
class procedure TWait.Start(const AProc: TProc);
begin
TWait.New.Wait(AProc);
end;
class procedure TWait.Synchronize(const AProc: TProc);
begin
TThread.Synchronize(TThread.CurrentThread,
procedure
begin
AProc;
end);
end;
end.
|
(*
* Test: Image multiplication.
*
* This program is a test for the ability
* to multiply two images together to produce
* a product image. Multiplication should be
* on corresponding pixels, i.e. distinct from
* array or matrix multiplication.
*)
program testImageMultiplication;
(*---------- Uses declarations ----------*)
uses bmp;
(*---------- Gloval variable declarations ----------*)
var
{Images}
ImageA, ImageB, ProductImage : pimage;
(*---------- Procedures ----------*)
(*
* Procedure to multiply together images
* (3D arrays) to test that the result is
* what is expected.
*)
procedure multImages;
var
{Temporary images for ImageA and ImageB}
ImageATemp, ImageBTemp : pimage;
begin
if loadbmpfile('../images/Left1.bmp', ImageA)
and loadbmpfile('../images/Right1.bmp', ImageB) then
begin
{Initialise temporary image arrays}
writeln('Initialising arrays...');
new(ImageATemp, ImageA ^.maxplane, ImageA ^.maxrow, ImageA ^.maxcol);
new(ImageBTemp, ImageB ^.maxplane, ImageB ^.maxrow, ImageB ^.maxcol);
new(ProductImage, ImageA ^.maxplane, ImageA ^.maxrow, ImageA ^.maxcol);
{Assign temp images to the corresponding image}
ImageATemp^ := ImageA^;
ImageBTemp^ := ImageB^;
{Produce product image}
writeln('Multiplying together images...');
ProductImage^ := ImageATemp^ * ImageBTemp^;
{Store the product image}
writeln('Storing product image...');
storebmpfile('multImagesProductImages.bmp', ProductImage^);
writeln('Product image stored.');
{Dispose of the temporary image buffers}
dispose(ImageATemp);
dispose(ImageBTemp);
dispose(ProductImage);
end
else
writeln('Error --> image files could not be loaded');
end;
(*---------- Main body of the program ----------*)
begin
writeln('/============================/');
writeln('/ Test: Image Multiplication /');
writeln('/============================/');
writeln;
{Multiply images, store image}
writeln('<Press ENTER to start image multiplication test>');
readln;
multImages;
{Dispose of image buffers}
dispose(ImageA);
dispose(ImageB);
end.
(*---------- End of the program ----------*) |
unit iterators;
interface
uses Classes, SysUtils, RegExpr, csv;
type
TBaseIterator = class(TObject)
public
function HasNext: Boolean; virtual;
function NextValueSet: Pointer; virtual;
function Eof: Boolean; virtual;
end;
// TTextIterator
TTextIterator = class(TBaseIterator)
private
FCode: TStringList;
FLine: Integer;
FVar: String;
public
constructor Create (Fn: String; VarName: String);
destructor Destroy; override;
function NextValueSet: Pointer; override;
function Eof: Boolean; override;
function HasNext: Boolean; override;
property VarName: String read FVar;
end;
// TCSVIterator
TCSVIterator = class(TBaseIterator)
private
FFields: TStringList;
FCode: TStringList;
FLine: Integer;
function GetField (Index: Integer): String;
public
constructor Create (Fn: String; var Fields: TStringList);
destructor Destroy; override;
function NextValueSet: Pointer; override;
function Eof: Boolean; override;
function HasNext: Boolean; override;
property Fields[Index: Integer]: String read GetField;
end;
// TRealCSVIterator
TRealCSVIterator = class(TBaseIterator)
private
FFields: TStringList;
FCode: TStringList;
FLine: Integer;
function GetField (Index: Integer): String;
public
constructor Create (Fn: String; var Fields: TStringList);
destructor Destroy; override;
function NextValueSet: Pointer; override;
function Eof: Boolean; override;
function HasNext: Boolean; override;
property Fields[Index: Integer]: String read GetField;
end;
// TRegexIterator
TRegexIterator = class(TBaseIterator)
private
FRegEx: TRegExpr;
FFields: TStringList;
FCode: TStringList;
FLine: Integer;
function GetField (Index: Integer): String;
public
constructor Create (Regex, Filename: String; var Fields: TStringList);
destructor Destroy; override;
function NextValueSet: Pointer; override;
function Eof: Boolean; override;
function HasNext: Boolean; override;
property Fields[Index: Integer]: String read GetField;
end;
// TRegexContextIterator
TRegexContextIterator = class(TBaseIterator)
private
FRegEx: TRegExpr;
FFields: TStringList;
FCode: TStringList;
FLine, FOffset: Integer;
FMatch: Boolean;
procedure FindNext;
function GetField (Index: Integer): String;
public
constructor Create (Regex, Filename: String; var Fields: TStringList);
destructor Destroy; override;
function NextValueSet: Pointer; override;
function Eof: Boolean; override;
function HasNext: Boolean; override;
property Fields[Index: Integer]: String read GetField;
end;
implementation
function TBaseIterator.NextValueSet: Pointer;
begin
Result := nil;
end;
function TBaseIterator.Eof: Boolean;
begin
Result := True;
end;
function TBaseIterator.HasNext: Boolean;
begin
Result := False;
end;
// TTextIterator
constructor TTextIterator.Create (Fn: String; VarName: String);
begin
inherited Create;
FCode := TStringList.Create;
FCode.LoadFromFile(Fn);
FVar := VarName;
FLine := -1;
end;
destructor TTextIterator.Destroy;
begin
FCode.Free;
inherited Destroy;
end;
function TTextIterator.HasNext: Boolean;
begin
Result := FLine+1 < FCode.Count-1;
end;
function TTextIterator.NextValueSet: Pointer; // PChar
begin
if Eof then begin
Result := nil;
Exit;
end;
Inc(FLine);
Result := AllocMem(Length(FCode.Strings[FLine])+1);
FillChar(Result^, length(FCode.Strings[FLine])+1, 0);
StrPCopy(Result, FCode.Strings[FLine]);
end;
function TTextIterator.Eof: Boolean;
begin
Result := FLine >= FCode.Count;
end;
// TCSVIterator
constructor TCSVIterator.Create (Fn: String; var Fields: TStringList);
begin
inherited Create;
FCode := TStringList.Create;
FLine := -1;
FCode.LoadFromFile(fn);
FFields := TStringList.Create;
FFields.AddStrings(Fields);
end;
destructor TCSVIterator.Destroy;
begin
FCode.Free;
FFields.Free;
inherited Destroy;
end;
function TCSVIterator.GetField (Index: Integer): String;
begin
Result := FFields.Strings[Index];
end;
function TCSVIterator.HasNext: Boolean;
begin
Result := FLine+1 < FCode.Count;
end;
function TCSVIterator.NextValueSet: Pointer;
//var sl: PStringList;
begin
Inc(FLine);
if Eof then begin
Result := nil;
Exit;
end;
//New(sl);
// Might cause some damage depending on whether Delphi decides to GC this
//sl^ := TStringList.Create;
Result := CSVSplit(FCode.Strings[FLine]);
//Result := sl;
end;
function TCSVIterator.Eof: Boolean;
begin
Result := FLine >= FCode.Count;
end;
// TRealCSVIterator
constructor TRealCSVIterator.Create (Fn: String; var Fields: TStringList);
var fl: PStringList;
begin
inherited Create;
FCode := TStringList.Create;
FLine := -1;
FCode.LoadFromFile(fn);
FFields := TStringList.Create;
FFields.AddStrings(Fields);
// Read first line
Inc(FLine);
// Add if no fields defined
if FFields.Count = 0 then begin
fl := CSVSplit(FCode.Strings[FLine]);
FFields.AddStrings(fl^);
fl^.Free;
end;
end;
destructor TRealCSVIterator.Destroy;
begin
FCode.Free;
FFields.Free;
inherited Destroy;
end;
function TRealCSVIterator.GetField (Index: Integer): String;
begin
Result := FFields.Strings[Index];
end;
function TRealCSVIterator.HasNext: Boolean;
begin
Result := FLine+1 < FCode.Count;
end;
function TRealCSVIterator.NextValueSet: Pointer;
//var sl: PStringList;
begin
Inc(FLine);
if Eof then begin
Result := nil;
Exit;
end;
//New(sl);
// Might cause some damage depending on whether Delphi decides to GC this
//sl^ := TStringList.Create;
Result := CSVSplit(FCode.Strings[FLine]);
//Result := sl;
end;
function TRealCSVIterator.Eof: Boolean;
begin
Result := FLine >= FCode.Count;
end;
// TRegexIterator
constructor TRegexIterator.Create (Regex, Filename: String; var Fields: TStringList);
begin
inherited Create;
FRegEx := TRegExpr.Create;
FRegEx.Expression := Regex;
FCode := TStringList.Create;
FCode.LoadFromFile(Filename);
FLine := -1;
FFields := TStringList.Create;
FFields.AddStrings(Fields);
end;
destructor TRegexIterator.Destroy;
begin
FCode.Free;
FFields.Free;
FRegex.Free;
inherited Destroy;
end;
function TRegexIterator.GetField (Index: Integer): String;
begin
Result := FFields.Strings[Index];
end;
function TRegexIterator.HasNext: Boolean;
begin
if FLine < 0 then FLine := 0;
if Eof then begin
Result := False;
Exit;
end;
Result := FRegex.Exec(FCode.Strings[FLine]);
while (not Eof) and (not Result) do begin
Inc(FLine);
Result := FRegex.Exec(FCode.Strings[FLine]);
end;
end;
function TRegexIterator.NextValueSet: Pointer;
var match: Boolean;
results: PStringList;
j: Integer;
begin
if Eof then begin
Result := nil;
Exit;
end;
if FLine < 0 then FLine := 0;
match := False;
while (not Eof) and (not match) do begin
match := FRegex.Exec(FCode.Strings[FLine]);
Inc(FLine);
end;
if match then begin
New(results);
results^ := TStringList.Create;
for j := 1 to FRegex.SubExprMatchCount do begin
results^.Add(FRegex.Match[j]);
end;
Result := results;
end else Result := nil;
end;
function TRegexIterator.Eof: Boolean;
begin
Result := FLine >= FCode.Count-1;
end;
// TRegexContextIterator
constructor TRegexContextIterator.Create (Regex, Filename: String; var Fields: TStringList);
begin
inherited Create;
FRegEx := TRegExpr.Create;
FRegEx.Expression := Regex;
FCode := TStringList.Create;
FCode.LoadFromFile(Filename);
FLine := 0;
FOffset := 1;
FFields := TStringList.Create;
FFields.AddStrings(Fields);
FindNext;
end;
destructor TRegexContextIterator.Destroy;
begin
FCode.Free;
FFields.Free;
FRegex.Free;
inherited Destroy;
end;
function TRegexContextIterator.GetField (Index: Integer): String;
begin
Result := FFields.Strings[Index];
end;
function TRegexContextIterator.HasNext: Boolean;
begin
Result := FMatch;
end;
function TRegexContextIterator.NextValueSet: Pointer;
var results: PStringList;
j: Integer;
begin
if not FMatch then begin
Result := nil;
Exit;
end;
New(results);
results^ := TStringList.Create;
for j := 1 to FRegex.SubExprMatchCount do begin
results^.Add(FRegex.Match[j]);
end;
Result := results;
FindNext;
end;
function TRegexContextIterator.Eof: Boolean;
begin
Result := not FMatch;
end;
procedure TRegexContextIterator.FindNext;
begin
FMatch := False;
while FLine < FCode.Count do begin
FRegex.InputString := FCode[FLine];
if (FOffset <= Length(FCode[FLine])) and (FRegex.Exec(FOffset)) then begin
FMatch := True;
FOffset := FRegex.MatchPos[0] + FRegex.MatchLen[0];
Exit;
end;
Inc(FLine);
end;
end;
end.
|
unit SQLiteObj;
interface
uses
SysUtils, SQLite3,Variants;
type
ESQLite = class(Exception)
public
SQLiteCode: integer;
WideMessage: WideString;
constructor Create(const ws: WideString; Code: integer);
end;
TSQLiteStmt = class(TObject)
protected
hStmt: SQLite3.TSQLiteStmt;
fDB: SQLite3.TSQLiteDB;
EOF: boolean;
fColCount: integer;
function GetHasNext(): boolean;
function GetColumn(i: integer): Variant;
function getColName(i:integer):WideString;
procedure CheckColCount();
public
constructor Create(hDB:SQLite3.TSQLiteDB);
destructor Destroy; override;
procedure Bind(ParIds, ParValues: array of const);
procedure Exec;
procedure Next;
procedure Reset;
property HasNext: boolean read GetHasNext;
property Column[i: integer]: Variant read GetColumn;
property ColCount:integer read fColCount;
property ColName[i:integer]:WideString read getColName;
end;
TSQLiteDB = class(TObject)
protected
hDB: SQLite3.TSQLiteDB;
stmtCommit,stmtRollback,stmtStartTrans:TSQLiteStmt;
function GetIsInTransaction():boolean;
public
destructor Destroy; override;
function CreateStmt(const SQL: WideString): TSQLiteStmt;
procedure Close();
procedure Open(const FileName: WideString;openFlags:integer=SQLITE_OPEN_READWRITE or SQLITE_OPEN_CREATE);
procedure StartTransaction();
procedure SetBusyTimeout(ms:integer);
procedure Commit();
procedure Rollback();
property IsInTransaction:boolean read GetIsInTransaction;
end;
implementation
{ TSQLiteDB }
procedure TSQLiteDB.Close;
begin
if assigned(hDB) then begin
SQLite3_Close(hDB);
hDB := nil;
end;
end;
procedure TSQLiteDB.Commit;
begin
if not assigned(stmtCommit) then begin
stmtCommit:=CreateStmt('COMMIT;');
end;
stmtCommit.Exec();
end;
function TSQLiteDB.CreateStmt(const SQL: WideString): TSQLiteStmt;
var
hStmt: SQLite3.TSQLiteStmt;
pWC: pWideChar;
r: integer;
begin
if not assigned(hDB) then
raise ESQLite.Create('TSQLiteDB.CreateStmt: DB not opened', SQLITE_ERROR);
r := SQLite3_Prepare16_v2(hDB, pWideChar(SQL), length(SQL) * sizeof(SQL[1]),
hStmt, pWC);
if (r <> SQLITE_OK) then begin
raise ESQLite.Create('TSQLiteDB.CreateStmt: Prepare failed '+SQLite3_ErrMsg(hDB) , r);
end;
if assigned(pWC) and (pWC^<>#0) then
raise ESQLite.Create('TSQLiteDB.CreateStmt: Multi-statement SQL not supported',SQLITE_TOOBIG);
result := TSQLiteStmt.Create(hDB);
result.hStmt := hStmt;
end;
destructor TSQLiteDB.Destroy;
begin
if assigned(stmtCommit) then
FreeAndNil(stmtCommit);
if assigned(stmtRollback) then
FreeAndNil(stmtRollback);
if assigned(stmtStartTrans) then
FreeAndNil(stmtStartTrans);
if (assigned(hDB)) then Close();
inherited;
end;
function TSQLiteDB.GetIsInTransaction: boolean;
begin
result := assigned(hDB) and (sqlite3_get_autocommit(hDB)=0);
end;
procedure TSQLiteDB.Open(const FileName: WideString;openFlags:integer=SQLITE_OPEN_READWRITE or SQLITE_OPEN_CREATE);
var
ec: integer;
//pc:PAnsiChar;
begin
if (assigned(hDB)) then
raise ESQLite.Create('TSQLiteDB.Open: already opened', SQLITE_ERROR);
ec := SQLite3_Open_v2(pAnsiChar(UTF8Encode(FileName)), hDB, openFlags,nil{use default vfs});
if (ec <> SQLITE_OK) then
raise ESQLite.Create('TSQLiteDB.Open: can`t open ' + FileName, ec);
SQLite3_enable_load_extension(hDB,1);
{pc:=nil;
SQLite3_load_extension(hDB,'c:\tmp\vcc\mydll\Debug\mydll.dll',nil,pc);
if assigned(pc) then SQlite3_Free(pc);}
end;
procedure TSQLiteDB.Rollback;
begin
if not assigned(stmtRollback) then begin
stmtRollback:=CreateStmt('ROLLBACK;');
end;
stmtRollback.Exec();
end;
procedure TSQLiteDB.SetBusyTimeout(ms: integer);
begin
SQLite3_BusyTimeout(hDB,ms);
end;
procedure TSQLiteDB.StartTransaction;
begin
if not assigned(stmtStartTrans) then begin
stmtStartTrans:=CreateStmt('BEGIN;');
end;
stmtStartTrans.Exec();
end;
{ ESQLite }
constructor ESQLite.Create(const ws: WideString; Code: integer);
begin
inherited Create(ws);
WideMessage := ws;
SQLiteCode := Code;
end;
{ TSQLiteStmt }
procedure TSQLiteStmt.Bind(ParIds, ParValues: array of const);
var
len, i, idx: integer;
pV:pVarData;
begin
len := length(ParIds);
if (len <> length(ParValues)) then
raise
ESQLite.Create('TSQLiteStmt.Bind: Ids[] and values[] must be same length.',
SQLITE_ERROR);
if HasNext then
Reset();
for i := low(ParIds) to high(ParIds) do begin
case ParIds[i].VType of
vtAnsiString: begin
idx := sqlite3_bind_parameter_index(hStmt, pAnsiChar(AnsiToUtf8(AnsiString(ParIds[i].VAnsiString))));
end;
vtInteger: idx := ParIds[i].VInteger;
vtWideString: begin
idx:=sqlite3_bind_parameter_index(hStmt,pAnsiChar(UTF8Encode(WideString(ParIds[i].VWideString))));
end;
else
raise ESQLite.Create('TSQLiteStmt.Bind: Id has invalid type',
SQLITE_ERROR);
end;
if (idx <= 0) then
raise ESQLite.Create('TSQLiteStmt.Bind: Id not found',
SQLITE_ERROR);
case ParValues[i].VType of
vtInteger: sqlite3_bind_int(hStmt, idx, ParValues[i].VInteger);
vtInt64: sqlite3_bind_int64(hStmt, idx, ParValues[i].VInt64^);
vtExtended: sqlite3_bind_double(hStmt, idx, ParValues[i].VExtended^);
vtAnsiString: sqlite3_bind_text(hStmt, idx, ParValues[i].VAnsiString,
length(AnsiString(ParValues[i].VAnsiString)), SQLITE_TRANSIENT);
vtWideString: sqlite3_bind_text16(hStmt, idx, ParValues[i].VWideString,
length(WideString(ParValues[i].VWideString)) * sizeof(WideChar),
SQLITE_TRANSIENT);
vtVariant: begin
pv:=PVarData(ParValues[i].VVariant);
while (pV^.VType and varByRef)<>0 do pV:=pV.VPointer;
case pV^.VType of
varInteger:
sqlite3_bind_int(hStmt, idx, pV.VInteger);
varInt64:
sqlite3_bind_int64(hStmt, idx, pV.VInt64);
varDouble:
sqlite3_bind_double(hStmt, idx, pV.VDouble);
varOleStr:
sqlite3_bind_text16(hStmt, idx, pV.VOleStr,
length(WideString(pV.VOleStr)) * sizeof(WideChar),
SQLITE_TRANSIENT);
else
raise ESQLite.Create('TSQLiteStmt.Bind: Value has invalid type',
SQLITE_ERROR);
end;
end;
else
raise ESQLite.Create('TSQLiteStmt.Bind: Value has invalid type',
SQLITE_ERROR);
end;
end;
end;
procedure TSQLiteStmt.CheckColCount;
begin
fColCount := SQLite3_ColumnCount(hStmt);
end;
constructor TSQLiteStmt.Create(hDB:SQLite3.TSQLiteDB);
begin
inherited Create();
fDB:=hDB;
hStmt := nil;
EOF := true;
fColCount := 0;
end;
destructor TSQLiteStmt.Destroy;
begin
if assigned(hStmt) then
SQLite3_Finalize(hStmt);
fDB:=nil;
hStmt := nil;
inherited Destroy;
end;
procedure TSQLiteStmt.Exec;
var
r: integer;
begin
if not EOF then
raise ESQLite.Create('TSQLiteStmt.Exec: Pending query', SQLITE_ERROR);
r := SQLite3_Step(hStmt);
case r of
SQLITE_DONE: begin
Reset();
fColCount:=0;
end;
SQLITE_ROW: begin
EOF := false;
CheckColCount();
end;
else
raise ESQLite.Create('TSQLiteStmt.Exec:'+SQLite3_ErrMsg(fDB),r);
end;
end;
function TSQLiteStmt.getColName(i: integer): WideString;
begin
CheckColCount();
if (i<0) or (i>=ColCount) then
raise ESQLite.Create('TSQLiteStmt.getColName: index out of bounds',SQLITE_ERROR);
result:=UTF8Decode(SQLite3_ColumnName(hStmt,i));
end;
function TSQLiteStmt.GetColumn(i: integer): Variant;
var
ct, ds: integer;
pb, pb2: PByte;
ws:WideString;
begin
if (i >= fColCount) then
raise ESQLite.Create('TSQLiteStmt.GetColumn: index out of bounds', SQLITE_ERROR);
ct := SQLite3_ColumnType(hStmt, i);
case ct of
SQLITE_INTEGER: result := SQLite3_ColumnInt64(hStmt, i);
SQLITE_FLOAT: result := SQLite3_ColumnDouble(hStmt, i);
SQLITE_BLOB: begin
ds := SQLite3_ColumnBytes(hStmt, i);
result := VarArrayCreate([0, ds - 1], varByte);
pb2 := SQLite3_ColumnBlob(hStmt, i);
try
pb := VarArrayLock(result);
if ds > 0 then
move(pb2^, pb^, ds);
finally
VarArrayUnlock(result);
end;
end;
SQLITE_NULL: result := Null;
else
//SQLITE_TEXT and all other datatypes
ws:=SQLite3_ColumnText16(hStmt, i);
result :=ws;
end;
end;
function TSQLiteStmt.GetHasNext: boolean;
begin
result := not EOF;
end;
procedure TSQLiteStmt.Next;
var
r: integer;
begin
if EOF then
raise ESQLite.Create('TSQLiteStmt.Next: no more data', SQLITE_ERROR);
r := SQLite3_Step(hStmt);
case r of
SQLITE_DONE: begin
Reset();
end;
SQLITE_ROW: EOF:=false;
else
raise ESQLite.Create('TSQLiteStmt.Next: step fail', r);
end;
end;
procedure TSQLiteStmt.Reset;
begin
SQLite3_clear_bindings(hStmt);
SQLite3_Reset(hStmt);
EOF:=true;
end;
end.
|
unit SoftacomParserMainFormUnit;
interface
uses
rtlconsts,
winsock,
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, System.IOUtils,
Vcl.ComCtrls;
type
TForm1 = class(TForm)
edtDirecotory: TEdit;
chbxRecursively: TCheckBox;
btnSelectDirectory: TButton;
gbDirectory: TGroupBox;
pnlBottom: TPanel;
btnRunParsingUses: TButton;
mmoUnits: TMemo;
dlgOpenDirectory: TFileOpenDialog;
lstComponentsGroup: TListBox;
pgcFunctions: TPageControl;
tsParsingUses: TTabSheet;
tsParsingProjects: TTabSheet;
lstProjectsList: TListBox;
pnlParsingProjects: TPanel;
btnRunParsingProjects: TButton;
lstProjectUnitUses: TListBox;
lstProjectUnits: TListBox;
Panel1: TPanel;
pnlProjectsListTitle: TPanel;
pnlProjectUnitsTitle: TPanel;
Panel4: TPanel;
splProjectsList: TSplitter;
splProjectUnits: TSplitter;
Button1: TButton;
lstProjectsGroupList: TListBox;
procedure FormCreate(Sender: TObject);
procedure btnSelectDirectoryClick(Sender: TObject);
procedure btnRunParsingUsesClick(Sender: TObject);
procedure btnRunParsingProjectsClick(Sender: TObject);
procedure lstProjectsListClick(Sender: TObject);
procedure lstProjectUnitsClick(Sender: TObject);
procedure splProjectsListMoved(Sender: TObject);
procedure splProjectUnitsMoved(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure lstProjectsGroupListClick(Sender: TObject);
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
SoftacomParser.UnitParser, SoftacomParser.ProjectParser,
SoftacomParser.ProjectGroupParser;
procedure TForm1.FormCreate(Sender: TObject);
begin
edtDirecotory.Text := 'C:\Release'; //TPath.GetLibraryPath;
dlgOpenDirectory.DefaultFolder := TPath.GetLibraryPath;
end;
procedure TForm1.lstProjectsGroupListClick(Sender: TObject);
var
pf: TProjectFile;
begin
lstProjectsList.Items.Clear;
for pf in ProjectsGroupList[lstProjectsGroupList.ItemIndex].Projects do
lstProjectsList.Items.Add(pf.Title + ' 1 ' + pf.FileName + ' 2 ' + pf.FullPath);
showmessage(inttostr(ProjectsGroupList[0].Projects.count));
end;
procedure TForm1.lstProjectsListClick(Sender: TObject);
var
uf: TUnitFile;
begin
lstProjectUnitUses.Items.Clear;
lstProjectUnits.Items.Clear;
// for uf in ProjectsList[lstProjectsList.ItemIndex].Units do
// lstProjectUnits.Items.Add(uf.UnitFileName + ' ' + uf.UnitPath + ' ' + uf.ClassVariable);
for uf in ProjectsGroupList[0].Projects[lstProjectsList.ItemIndex].Units do
lstProjectUnits.Items.Add(uf.UnitFileName + ' ' + uf.UnitPath + ' ' + uf.ClassVariable);
end;
procedure TForm1.lstProjectUnitsClick(Sender: TObject);
var
u: string;
begin
lstProjectUnitUses.Items.Clear;
for u in ProjectsGroupList[0].Projects[lstProjectsList.ItemIndex].Units[lstProjectUnits.ItemIndex].UsesList do
lstProjectUnitUses.Items.Add(u);
end;
procedure TForm1.splProjectsListMoved(Sender: TObject);
begin
pnlProjectsListTitle.Width := lstProjectsList.Width + splProjectsList.Width;
end;
procedure TForm1.splProjectUnitsMoved(Sender: TObject);
begin
pnlProjectUnitsTitle.Width := lstProjectUnits.Width + splProjectUnits.Width;
end;
procedure TForm1.btnSelectDirectoryClick(Sender: TObject);
begin
if dlgOpenDirectory.Execute then
begin
edtDirecotory.Text := dlgOpenDirectory.FileName;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
LPath: string;
pgf: TProjectGroupFile;
begin
lstProjectsGroupList.Clear;
LPath := edtDirecotory.Text;
if TDirectory.Exists(LPath) then
begin
ProjectsGroupList.ParseDirectory(LPath, chbxRecursively.Checked);
for pgf in ProjectsGroupList do
begin
if pgf.Title.IsEmpty then
lstProjectsGroupList.Items.Add(pgf.FileName +' : '+ pgf.Version +' : '+ pgf.FullPath )
else
lstProjectsGroupList.Items.Add(pgf.Title + ' (' + pgf.FileName + ')');
end;
lstProjectsGroupList.Items.SaveToFile('list2.txt');
end
else
ShowMessage('Incorrect path');
end;
procedure TForm1.btnRunParsingUsesClick(Sender: TObject);
var
LPath: string;
begin
mmoUnits.Clear;
LPath := edtDirecotory.Text;
if TDirectory.Exists(LPath) then
begin
UnitParser.ParseDirectories(LPath, chbxRecursively.Checked);
mmoUnits.Lines.Assign(UnitParser.Units);
lstComponentsGroup.Items.Assign(UnitParser.ComponentsGroup);
end
else
ShowMessage('Incorrect path');
end;
procedure TForm1.btnRunParsingProjectsClick(Sender: TObject);
var
LPath: string;
pf: TProjectFile;
begin
lstProjectsList.Clear;
LPath := edtDirecotory.Text;
if TDirectory.Exists(LPath) then
begin
ProjectsList.ParseDirectory(LPath, chbxRecursively.Checked);
for pf in ProjectsList do
begin
if pf.Title.IsEmpty then
lstProjectsList.Items.Add(pf.FileName)
else
lstProjectsList.Items.Add(pf.Title + ' (' + pf.FileName + ')');
end;
lstProjectsList.Items.SaveToFile('list.txt');
end
else
ShowMessage('Incorrect path');
end;
end.
|
unit FluentInterface.CRGP;
interface
type
TStringBuilder<T: class> = class
private
FData: String;
public
class constructor Create;
public
function Append(const AValue: String): T;
property Data: String read FData;
end;
type
THtmlStringBuilder = class(TStringBuilder<THtmlStringBuilder>)
public
function BoldOn: THtmlStringBuilder;
function BoldOff: THtmlStringBuilder;
end;
procedure TestFluentInterfaceCRGP;
implementation
uses
Utils;
procedure TestFluentInterfaceCRGP;
begin
StartSection;
WriteLn('A fluent string builder implementation using CRGP.');
Write('Building an HTML string: ');
var Builder := THtmlStringBuilder.Create;
try
Builder.Append('This is ').BoldOn.Append('bold').BoldOff.Append('!');
WriteLn(Builder.Data);
finally
Builder.Free;
end;
end;
{ TStringBuilder<T> }
function TStringBuilder<T>.Append(const AValue: String): T;
begin
FData := FData + AValue;
Result := T(Self);
end;
class constructor TStringBuilder<T>.Create;
begin
Assert(T.InheritsFrom(TStringBuilder<T>));
end;
{ THtmlStringBuilder }
function THtmlStringBuilder.BoldOff: THtmlStringBuilder;
begin
Append('</b>');
Result := Self;
end;
function THtmlStringBuilder.BoldOn: THtmlStringBuilder;
begin
Append('<b>');
Result := Self;
end;
end.
|
//~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
//
// Unidad: Ejecutar.pas
//
// Propósito:
// Frame para la ejecución de funciones. Este frame simplifica el código de main.pas
//
// Autor: José Manuel Navarro (jose_manuel_navarro@yahoo.es)
// Fecha: 01/04/2003
// Observaciones: Unidad creada en Delphi 5 para Síntesis nº 14 (http://www.grupoalbor.com)
// Copyright: Este código es de dominio público y se puede utilizar y/o mejorar siempre que
// SE HAGA REFERENCIA AL AUTOR ORIGINAL, ya sea a través de estos comentarios
// o de cualquier otro modo.
//
//~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
unit Ejecutar;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, ActnList;
type
TEjecutarFrame = class(TFrame)
p_pie: TPanel;
l_retorno: TLabel;
b_ejecutar: TButton;
l_retorno2: TLabel;
Bevel1: TBevel;
procedure Execute(Sender: TObject);
private
FAccion: TCustomAction;
public
procedure Init(accion: TCustomAction);
end;
implementation
uses main;
{$R *.DFM}
procedure TEjecutarFrame.Init(accion: TCustomAction);
begin
FAccion := accion;
end;
procedure TEjecutarFrame.Execute(Sender: TObject);
begin
FAccion.Execute();
// el evento OnExecute me guarda en el tag el código de error
if FAccion.Tag = 1 then
begin
l_retorno.caption := 'Correcto';
l_retorno.Font.Color := clGreen;
l_retorno.Hint := '';
l_retorno.ShowHint := false;
end
else if FAccion.Tag <> 0 then
begin
l_retorno.caption := 'Error: ' + SysErrorMessage(FAccion.Tag);
l_retorno.Hint := l_retorno.caption;
l_retorno.ShowHint := true;
l_retorno.Font.Color := clRed;
end;
end;
end.
|
program usingInheritance;
{$mode objfpc}
{$m+}
type { base class }
Books = class
protected
title: string;
price: real;
public
constructor Create(t: string; p: real); { default }
procedure setTitle(t: string); { setter }
function getTitle(): string; { getter }
procedure setPrice(p: real); { setter }
function getPrice(): real; { getter }
procedure display(); virtual;
end;
type { derived class }
Novels = class(Books)
private
author: string;
public
constructor Create(t: string); overload;
constructor Create(a: string; t: string; p: real); overload;
procedure setAuthor(a: string);
function getAuthor(): string;
procedure display(); override;
end;
var
n1, n2: Novels;
{ default constructor }
constructor Books.Create(t: string; p: real);
begin
title := t;
price := p;
end;
procedure Books.setTitle(t: string);
begin
title := t;
end;
function Books.getTitle(): string;
begin
getTitle := title;
end;
procedure Books.setPrice(p: real);
begin
price := p;
end;
function Books.getPrice(): real;
begin
getPrice := price;
end;
procedure Books.display();
begin
writeln;
writeln('title: ', title);
writeln('price: ', price:5:2);
writeln;
end;
{ derived class constructor }
constructor Novels.Create(t: string);
begin
inherited Create(t, 0.0);
author := ' ';
end;
constructor Novels.Create(a: string; t: string; p: real);
begin
inherited Create(t, p);
author := a;
end;
procedure Novels.setAuthor(a: string);
begin
author := a;
end;
function Novels.getAuthor(): string;
begin
getAuthor := author;
end;
procedure Novels.display();
begin
writeln;
writeln('title: ', title);
writeln('price: ', price:5:2);
writeln('author: ', author);
writeln;
end;
begin { main }
n1 := Novels.Create('Gone with the Wind');
n1.setAuthor('Margaret Mitchell');
n1.setPrice(67.99);
n2 := Novels.Create(
'Stephen Hawkin',
'A Brief History of Time',
69.99
);
n1.display;
n2.display;
end.
|
unit History;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls;
type
THistory = class(TMemo)
private
{ Private declarations }
fShowDate: boolean;
fShowTime: boolean;
protected
{ Protected declarations }
public
{ Public declarations }
procedure Append (msg : string);
published
{ Published declarations }
property ShowDate: boolean
read fShowDate
write fShowDate;
property ShowTime: boolean
read fShowtime
write fShowTime;
end;
implementation
//----------------------------------------------------------
// Append messages to a memo box so the user can see a
// history as the program executes.
//----------------------------------------------------------
procedure THistory.Append (msg : string);
var
stamp1 : string [32];
stamp2 : string [ 3];
curtime : TDateTime;
curhh : word;
curmm : word;
curss : word;
curms : word;
pc : PChar;
begin
if (length (msg) = 0) then
exit;
while (Lines.Count >= 128) do
Lines.Delete (0);
curTime := Now;
DecodeTime (curtime, curhh, curmm, curss, curms);
stamp1:='';
if fShowDate then
begin
stamp1 := formatDateTime ('mm/dd/yyyy ', curTime);
end;
if FShowtime then
begin
if stamp1 <> '' then
stamp1 := stamp1+formatDateTime (' hh:nn:ss', curTime)
else
stamp1 := formatDateTime ('hh:nn:ss', curTime);
end;
//stamp1 := formatDateTime ('mm/dd/yyyy hh:nn:ss', curTime);
str (curms:3, stamp2);
if (stamp2 [1] = ' ') then stamp2 [1] := '0';
if (stamp2 [2] = ' ') then stamp2 [2] := '0';
if (stamp2 [3] = ' ') then stamp2 [3] := '0';
pc := PChar (msg);
while (pc^ <> #0) do
begin
if (pc^ < ' ') then
pc^ := ' ';
INC (pc);
end;
Lines.Append (format ('%s.%s, %s', [stamp1, stamp2, msg]));
end;
end.
|
program tp3_2;
uses Crt, sysutils;
type
str20 = string[20];
str8 = string[8];
empleado = record
nomyape: str20;
tel: str20;
dni: longint;
n_emp: integer;
fecha: str20;
direc: str20;
end;
archivo = file of empleado;
procedure crearEmpleados();
var
empleados: archivo;
emp: empleado;
texto: Text;
begin
assign(empleados, 'data/ej2/empleados.dat');
rewrite(empleados);
assign(texto, 'data/ej2/empleados.txt');
reset(texto);
while(not eof(texto)) do begin
readln(texto, emp.n_emp, emp.nomyape);
readln(texto, emp.dni, emp.direc);
readln(texto, emp.tel);
readln(texto, emp.fecha);
write(empleados, emp);
end;
close(texto);
close(empleados);
ClrScr;
end;
procedure imprimirEmpleado(emp: empleado);
begin
writeln('Empleado #', emp.n_emp, ': ');
writeln('===============');
writeln('Apellido y nombre: '+emp.nomyape);
writeln('DNI: '+IntToStr(emp.dni));
writeln('Fecha de nacimiento: ',emp.fecha);
writeln('Dirección: ',emp.direc);
writeln('Telefono: ',emp.tel);
writeln();
end;
procedure listarEmpleados();
var
empleados: archivo;
emp: empleado;
begin
assign(empleados, 'data/ej2/empleados.dat');
reset(empleados);
ClrScr;
if (eof(empleados)) then begin
writeln('No hay empleados en la BD.');
end;
while (not eof(empleados)) do begin
Read(empleados, emp);
imprimirEmpleado(emp);
end;
close(empleados);
end;
procedure borrarEmpleados();
var
empleados: archivo;
emp: empleado;
begin
assign(empleados, 'data/ej2/empleados.dat');
reset(empleados);
ClrScr;
if (eof(empleados)) then begin
writeln('No hay empleados en la BD.');
end;
while (not eof(empleados)) do begin
Read(empleados, emp);
if(emp.dni<8000000) then begin
emp.nomyape := '*'+emp.nomyape;
seek(empleados, filePos(empleados)-1);
write(empleados, emp);
end;
end;
close(empleados);
end;
begin
crearEmpleados();
writeln('Archibo binario de empleados, creado correctamente...<ENTER>');
readln();
listarEmpleados();
writeln('Empleados impresos correctamente...<ENTER>');
readln();
borrarEmpleados();
writeln('Empleados borrados correctamente...<ENTER>');
readln();
listarEmpleados();
writeln('Empleados impresos correctamente...<ENTER>');
readln();
end. |
unit TravelTourEditFrom;
interface
uses
Forms, cxLookAndFeelPainters, Classes, Controls, StdCtrls, cxButtons,
ExtCtrls, ActnList, cxControls, cxContainer, cxEdit, cxTextEdit, cxDBEdit,
cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBExtLookupComboBox,
cxMaskEdit, cxCalendar, Messages, cxMemo, cxImageComboBox,
cxCurrencyEdit, cxCheckBox, cxStyles, cxCustomData, cxGraphics, cxFilter,
cxData, DB, cxDBData, cxGridLevel, cxClasses, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid,
TB2Item, TB2Dock, TB2Toolbar, cxDBLookupComboBox, cxSpinEdit, Dialogs;
type
TTourEditFrom = class(TForm)
btnOK: TcxButton;
Cancel: TcxButton;
Panel2: TPanel;
ActionList: TActionList;
ActionOK: TAction;
Panel1: TPanel;
Label1: TLabel;
Label4: TLabel;
description: TcxDBMemo;
Label5: TLabel;
EditDescr: TcxButton;
special_offer: TcxDBCheckBox;
Label6: TLabel;
Label7: TLabel;
Label2: TLabel;
cxGrid1DBTableView1: TcxGridDBTableView;
cxGrid1Level1: TcxGridLevel;
cxGrid1: TcxGrid;
Label3: TLabel;
TBToolbar1: TTBToolbar;
direction_id: TcxDBLookupComboBox;
currency_id: TcxDBLookupComboBox;
cxGrid1DBTableView1date_begin: TcxGridDBColumn;
date_begin: TcxDBDateEdit;
Ins: TAction;
Post: TAction;
TBItem1: TTBItem;
TBItem2: TTBItem;
Del: TAction;
priority: TcxDBComboBox;
low_price: TcxDBSpinEdit;
title: TcxDBTextEdit;
Label9: TLabel;
name: TcxDBMaskEdit;
tourtype_id: TcxDBLookupComboBox;
Label10: TLabel;
Attach: TcxButton;
plus_avia: TcxDBCheckBox;
length_day: TcxDBSpinEdit;
length_night: TcxDBSpinEdit;
Label11: TLabel;
OpenDialog: TOpenDialog;
Monday: TcxCheckBox;
Tuesday: TcxCheckBox;
Wednesday: TcxCheckBox;
Thursday: TcxCheckBox;
Friday: TcxCheckBox;
Saturday: TcxCheckBox;
Sunday: TcxCheckBox;
Label8: TLabel;
EveryDay: TcxCheckBox;
plus_train: TcxDBCheckBox;
cxButton1: TcxButton;
procedure ActionOKExecute(Sender: TObject);
procedure InsExecute(Sender: TObject);
procedure PostExecute(Sender: TObject);
procedure DelExecute(Sender: TObject);
procedure DelUpdate(Sender: TObject);
procedure PostUpdate(Sender: TObject);
procedure EditDescrClick(Sender: TObject);
procedure titlePropertiesEditValueChanged(Sender: TObject);
procedure AttachClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure EveryDayPropertiesChange(Sender: TObject);
procedure cxButton1Click(Sender: TObject);
private
FList: TStringList;
procedure CMDialogKey(var Msg: TWMKey); message CM_DIALOGKEY;
procedure SavePeriod;
procedure LoadPeriod;
public
property List: TStringList read FList write FList;
end;
// AList - списко уникальных имено для проверки
function GetTourEditFrom(const AList: String): Integer;
implementation
uses TravelDM, Windows, TravelMainForm, HTMLEditorIntf, DeviumLib,
SysUtils;
{$R *.dfm}
function GetTourEditFrom;
var
From: TTourEditFrom;
begin
From := TTourEditFrom.Create(Application);
try
From.List.Text := AList;
Result := From.ShowModal;
finally
From.Free;
end;
end;
procedure TTourEditFrom.ActionOKExecute(Sender: TObject);
begin
btnOK.SetFocus;
// проверка на уже сужествующие имена на "уникальность"
if FList.IndexOf(name.Text) > -1 then
MessageBox(Handle, PChar(Format('Данное имя "%s" уже используется!',
[name.Text])), PChar(Caption), MB_ICONERROR + MB_OK)
else
begin
// собираем переидочность
SavePeriod;
ModalResult := mrOK;
end;
end;
procedure TTourEditFrom.CMDialogKey(var Msg: TWMKey);
begin
if not (ActiveControl is TButton) then
if Msg.Charcode = VK_RETURN then
Msg.Charcode := VK_TAB;
inherited;
end;
procedure TTourEditFrom.InsExecute(Sender: TObject);
begin
DM.ToursDates.Append;
end;
procedure TTourEditFrom.PostExecute(Sender: TObject);
begin
DM.ToursDates.Post;
end;
procedure TTourEditFrom.DelExecute(Sender: TObject);
begin
DM.ToursDates.Delete;
end;
procedure TTourEditFrom.DelUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := (Dm.ToursDates.RecordCount > 0);
end;
procedure TTourEditFrom.PostUpdate(Sender: TObject);
begin
TAction(Sender).Enabled :=
(Dm.ToursDates.State = dsEdit) or
(Dm.ToursDates.State = dsInsert);
end;
procedure TTourEditFrom.EditDescrClick(Sender: TObject);
var
Editor: IHTMLEditor;
s: String;
begin
if DM.PluginManager.GetPlugin(IHTMLEditor, Editor) then
begin
s := description.DataBinding.Field.AsString;
if Editor.Execute(s) then
description.DataBinding.Field.Value := s;
end;
end;
procedure TTourEditFrom.titlePropertiesEditValueChanged(Sender: TObject);
begin
if Length(name.Text) = 0 then
name.DataBinding.Field.Value := TransLiterStr(title.Text);
end;
procedure TTourEditFrom.AttachClick(Sender: TObject);
begin
if OpenDialog.Execute then
begin
{ TODO -oPaladin :
1. Доделать добавлеине в базу данных имени файла
2. Положить его в папку программы
3. }
end;
end;
procedure TTourEditFrom.FormCreate(Sender: TObject);
begin
FList := TStringList.Create;
LoadPeriod;
end;
procedure TTourEditFrom.FormDestroy(Sender: TObject);
begin
FList.Free;
end;
procedure TTourEditFrom.EveryDayPropertiesChange(Sender: TObject);
var
i: Integer;
begin
for i := 0 to ComponentCount - 1 do
if (Components[i] is TcxCheckBox) and (Components[i].Tag > 0) then
begin
if TcxCheckBox(Sender).Checked then
TcxCheckBox(Components[i]).Checked := False;
TcxCheckBox(Components[i]).Enabled := not TcxCheckBox(Sender).Checked;
end;
end;
procedure TTourEditFrom.LoadPeriod;
var
i: Integer;
s: String;
begin
// собираем переидочность
s := DM.Tours.FieldByName('period').AsString;
if s = '8' then
EveryDay.Checked := True
else
begin
for i := 0 to ComponentCount - 1 do
begin
if (Components[i] is TcxCheckBox) and (Components[i].Tag > 0) then
if Pos(IntToStr(Components[i].Tag), s) > 0 then
TcxCheckBox(Components[i]).Checked := True;
end;
end;
end;
procedure TTourEditFrom.SavePeriod;
var
i: Integer;
s: String;
begin
// собираем переидочность
s := '';
if EveryDay.Checked then
s := '8'
else
begin
for i := 0 to ComponentCount - 1 do
begin
if (Components[i] is TcxCheckBox) and (Components[i].Tag > 0) then
if TcxCheckBox(Components[i]).Checked then
s := s + IntToStr(Components[i].Tag) + ',';
end;
s := Copy(s, 1, Length(s) - 1);
end;
DM.Tours['period'] := s;
end;
procedure TTourEditFrom.cxButton1Click(Sender: TObject);
begin
name.DataBinding.Field.Value := TransLiterStr(title.Text);
end;
end.
|
unit LuaPipeServer;
//pipe server class specifically made for lua. Only 1 client and 1 server connection at a time
{$mode delphi}
interface
{$ifdef windows}
uses
jwawindows, windows, Classes, SysUtils, lua, luaclass, luapipe;
procedure initializeLuaPipeServer;
{$endif}
implementation
{$ifdef windows}
uses LuaHandler;
type
TLuaPipeServer=class(TPipeConnection)
private
function isValidPipe: boolean;
public
function WaitForClientConnection: boolean;
constructor create(pipename: string; inputsize, outputsize: integer);
published
property valid: boolean read isValidPipe;
end;
function TLuaPipeServer.isValidPipe;
begin
result:=pipe<>INVALID_HANDLE_VALUE;
end;
function TLuaPipeServer.WaitForClientConnection;
begin
fconnected:=ConnectNamedPipe(pipe, nil);
if not fconnected then
fconnected:=getlasterror()=ERROR_PIPE_CONNECTED;
result:=fConnected;
end;
constructor TLuaPipeServer.create(pipename: string; inputsize, outputsize: integer);
var
a: SECURITY_ATTRIBUTES;
begin
inherited create;
a.nLength:=sizeof(a);
a.bInheritHandle:=TRUE;
ConvertStringSecurityDescriptorToSecurityDescriptor('D:(D;;FA;;;NU)(A;;0x12019f;;;WD)(A;;0x12019f;;;CO)', SDDL_REVISION_1, a.lpSecurityDescriptor, nil);
//AllocateAndInitializeSid();
{
LPCWSTR LOW_INTEGRITY_SDDL_SACL_W = L"S:(ML;;NW;;;LW)"
;
PSECURITY_DESCRIPTOR securitydescriptor;
ConvertStringSecurityDescriptorToSecurityDescriptorW(LOW_INTEGRITY_SDDL_SACL_W,SDDL_REVISION_1,&securitydescriptor,NULL);
sa.nLength = sizeof
(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = securitydescriptor;
sa.bInheritHandle = TRUE;
}
pipe:=CreateNamedPipe(pchar('\\.\pipe\'+pipename), PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE or PIPE_READMODE_BYTE or PIPE_WAIT, 1,inputsize, outputsize, INFINITE, @a);
LocalFree(HLOCAL(a.lpSecurityDescriptor));
end;
function luapipeserver_createNamedPipee(L: PLua_state): integer; cdecl;
var
pipename: string;
inputsize: integer;
outputsize: integer;
paramcount: integer;
begin
result:=0;
paramcount:=lua_gettop(L);
if paramcount>=1 then
begin
inputsize:=4096;
outputsize:=4096;
if paramcount>=2 then
inputsize:=lua_tointeger(L, 2);
if paramcount>=3 then
outputsize:=lua_tointeger(L, 3);
pipename:=lua_tostring(L, 1);
luaclass_newClass(L, TLuaPipeServer.create(pipename, inputsize, outputsize));
result:=1;
end;
end;
function luapipeserver_WaitForClientConnection(L: Plua_State): integer; cdecl;
var p: TLuaPipeServer;
begin
p:=luaclass_getClassObject(L);
p.WaitForClientConnection;
result:=0;
end;
procedure luapipeserver_addMetaData(L: PLua_state; metatable: integer; userdata: integer );
begin
pipecontrol_addMetaData(L, metatable, userdata);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'acceptConnection', luapipeserver_WaitForClientConnection);
end;
procedure initializeLuaPipeServer;
begin
lua_register(LuaVM, 'createPipe', luapipeserver_createNamedPipee);
end;
initialization
luaclass_register(TLuaPipeServer, luapipeserver_addMetaData );
{$endif}
end.
|
unit DevMax.Types;
interface
uses
System.SysUtils,
DevMax.Types.ViewInfo;
type
IManifestService = interface
['{37F598CA-9EF4-4CC2-91DF-6444B526BA38}']
function TryGetViewInfo(AViewId: string; out ViewInfo: TViewInfo): Boolean;
end;
IManifestDAO = interface
['{37F598CA-9EF4-4CC2-91DF-6444B526BA38}']
function TryGetViewInfo(AViewId: string; out ViewInfo: TViewInfo): Boolean;
end;
IDataAccessService = interface
['{16FB2C24-9511-4034-8570-011DF2FD6CDF}']
end;
IDataAccessAdapter = interface;
IDataAccessApi = interface;
IDataAccessParser = interface;
/// 실제 데이터를 가져오는 객체
IDataAccessObject = interface
['{77AE8F89-E92A-4522-BF4C-48D1BEF4CA91}']
function GetDataAccessAdapter: IDataAccessAdapter;
property DataAccessAdapter: IDataAccessAdapter read GetDataAccessAdapter;
end;
/// 데이터엑세스 기술 정의
IDataAccessAdapter = interface
['{060D8CED-4E9F-48BB-9865-07AFA477BBAC}']
end;
/// 연동할 서비스 API 정의
IDataAccessApi = interface
end;
// 수신 데이터 분석/전환 정의
IDataAccessParser = interface
end;
implementation
end.
|
unit sql.connection;
interface
uses System.Classes, System.SysUtils, System.IniFiles, System.Generics.Collections,
Data.DB, Data.DBXCommon, {$IFNDEF FMX} MidasLib, {$ENDIF}
sql.consts;
type
TDataBase = Class
private
FServer : String;
FPort : Integer;
FDataBase : String;
FUser : String;
FPassword : String;
FDialect : Integer;
FFilterPC1: String;
public
property Server : String Read FServer Write FServer;
property Port : Integer Read FPort Write FPort;
property DataBase : String Read FDataBase Write FDataBase;
property User : String Read FUser Write FUser;
property Password : String Read FPassword Write FPassword;
property Dialect : Integer Read FDialect Write FDialect;
property FilterPC1: String Read FFilterPC1 Write FFilterPC1;
End;
TDBConnection = Class
private
FSQL : TSQL;
FDataBase : TDataBase;
FError : String;
FLog : Boolean;
function GetDataBase : TDataBase;
protected
FDataSet : TObjectList<TDataSet>;
FSQLCurrent : String;
procedure ClearLog;
procedure AddLog(Value : String); Overload;
procedure AddLog(Value : TStrings); Overload;
public
property SQL : TSQL Read FSQL Write FSQL;
property DataBase : TDataBase Read GetDataBase;
property Error : String Read FError Write FError;
property Log : Boolean Read FLog Write FLog;
property SQLCurrent : String Read FSQLCurrent;
constructor Create; Virtual;
destructor Destroy; Override;
public
function Connect(Value : TFileName; Section : String = 'BANCO DE DADOS') : Boolean; Overload;
function Connect : Boolean; Overload; Virtual; Abstract;
procedure Disconnect; Virtual; Abstract;
function Connected : Boolean; Virtual;
function IsStart(Transact : Integer = 1) : Boolean; Virtual; Abstract;
function Start(Transact : Integer = 1) : Boolean; Virtual; Abstract;
function Commit(Transact : Integer = 1) : Boolean; Virtual; Abstract;
function Rollback(Transact : Integer = 1) : Boolean; Virtual; Abstract;
function ExecuteScript(Value : TStrings; OnProgress : TOnProgress) : Boolean; Overload; Virtual; Abstract;
function Execute(Value : String) : Boolean; Overload; Virtual; Abstract;
function Execute(Value : TStrings) : Boolean; Overload; Virtual; Abstract;
function Execute(Value : TStrings; Blobs : TList<TBlobData>) : Boolean; Overload; Virtual; Abstract;
function Exec(Value : String) : Boolean; Overload;
function Exec(Value : TStrings) : Boolean; Overload;
function Exec(Value : TStrings; Blobs : TList<TBlobData>) : Boolean; Overload;
function Open(Value : String) : TDataSet; Overload; Virtual; Abstract;
function Open(Value : TStrings) : TDataSet; Overload; Virtual; Abstract;
function Open(Value : TStrings; Blobs : TList<TBlobData>) : TDataSet; Overload; Virtual; Abstract;
procedure Open(DataSet : TDataSet; Value : String); Overload; Virtual; Abstract;
function Open(Value : String; const Params : Array Of Const) : TDataSet; Overload;
procedure Open(var Value : TDataSet; SQL : String; const Params : Array Of Const); Overload;
function OpenQry(Value : String) : TDataSet; Overload; Virtual; Abstract;
function OpenExec(Value : String) : TDataSet; Overload; Virtual; Abstract;
function OpenExec(Value : TStrings) : TDataSet; Overload; Virtual; Abstract;
function OpenExec(Value : TStrings; Blobs : TList<TBlobData>) : TDataSet; Overload; Virtual; Abstract;
function IsEmpty(Value : String) : Boolean; Overload;
function IsEmpty(Value : String; const Params : Array Of Const) : Boolean; Overload;
function IsCount(var Field1 : Variant; Value : String) : Integer; Overload;
function IsCount(var Field1 : Variant; Value : String; const Params : Array Of Const) : Integer; Overload;
procedure CloseDataSet;
procedure DataSetFree(var Value : TDataSet); Overload;
function GetGenerator(Name : String) : Integer;
function GetDateTime : TDateTime;
function GetDate : TDate;
function GetTime : TTime;
procedure SortIndex(Value : TDataSet; AscFields : String = ''; DescFields : String = ''); Virtual; Abstract;
End;
implementation
{ TDBConnection }
constructor TDBConnection.Create;
begin
FDataBase := TDataBase.Create;
FDataSet := TObjectList<TDataSet>.Create;
FError := '';
FLog := False;
ClearLog;
end;
procedure TDBConnection.DataSetFree(var Value: TDataSet);
var I : Integer;
begin
I := FDataSet.IndexOf(Value);
Try
If (I > -1) Then
FDataSet.Delete(I)
Else
FreeAndNil(Value);
Except
End;
Value := nil;
FDataSet.TrimExcess;
end;
destructor TDBConnection.Destroy;
begin
CloseDataSet;
Rollback;
Disconnect;
FreeAndNil(FDataBase);
FreeAndNil(FDataSet);
If Assigned(FSQL) Then
FreeAndNil(FSQL);
inherited;
end;
function TDBConnection.Exec(Value: String): Boolean;
begin
Try
Result := Execute(Value);
Commit;
Except
Rollback;
End;
end;
function TDBConnection.Exec(Value: TStrings): Boolean;
begin
Try
Result := Execute(Value);
Commit;
Except
Rollback;
End;
end;
function TDBConnection.Exec(Value: TStrings; Blobs: TList<TBlobData>): Boolean;
begin
Try
Result := Execute(Value,Blobs);
Commit;
Except
Rollback;
End;
end;
function TDBConnection.GetDataBase: TDataBase;
begin
If not Assigned(FDataBase) Then
FDataBase := TDataBase.Create;
Result := FDataBase;
end;
function TDBConnection.GetDate : TDate;
var DS : TDataSet;
begin
Result := 0;
DS := Open( SQL.SQLGetDate );
Try
Result := DS.FieldByName('V').AsDateTime;
Finally
DataSetFree(DS);
End;
end;
function TDBConnection.GetDateTime : TDateTime;
var DS : TDataSet;
begin
Result := 0;
DS := Open( SQL.SQLGetDateTime );
Try
Result := DS.FieldByName('V').AsDateTime;
Finally
DataSetFree(DS);
End;
end;
function TDBConnection.GetGenerator(Name: String): Integer;
var DS : TDataSet;
begin
Result := 0;
DS := Open( SQL.SQLGetGenerator(Name) );
Try
Result := DS.FieldByName('V').AsInteger;
Finally
DataSetFree(DS);
End;
end;
function TDBConnection.GetTime : TTime;
var DS : TDataSet;
begin
Result := 0;
DS := Open( SQL.SQLGetTime );
Try
Result := DS.FieldByName('V').AsDateTime;
Finally
DataSetFree(DS);
End;
end;
function TDBConnection.IsEmpty(Value: String): Boolean;
var DS : TDataSet;
begin
Try
DS := OpenQry(Value);
Result := DS.IsEmpty;
Finally
DataSetFree(DS);
End;
end;
function TDBConnection.IsCount(var Field1 : Variant; Value: String): Integer;
var DS : TDataSet;
begin
Try
DS := Open(Value);
Field1 := DS.Fields[0].Value;
Result := DS.RecordCount;
Finally
DataSetFree(DS);
End;
end;
function TDBConnection.IsCount(var Field1 : Variant; Value: String;
const Params: array of Const): Integer;
begin
Result := IsCount(Field1,Format(Value,Params));
end;
function TDBConnection.IsEmpty(Value: String;
const Params: array of Const): Boolean;
begin
Result := IsEmpty(Format(Value,Params));
end;
procedure TDBConnection.Open(var Value : TDataSet; SQL : String;
const Params: array of Const);
begin
If not Assigned(Value) Then
Value := Open(SQL,Params)
Else
Open(Value,Format(SQL,Params));
end;
function TDBConnection.Open(Value: String;
const Params: array of Const): TDataSet;
begin
Result := Open(Format(Value,Params));
end;
procedure TDBConnection.AddLog(Value: String);
var S : TStrings;
begin
FSQLCurrent := Value;
If not FLog Then
Exit;
S := TStringList.Create;
Try
If FileExists('log.sql') Then
S.LoadFromFile('log.sql');
S.Add('');
S.Add(FormatDateTime('dd/mm/yyyy hh:nn:ss.zzzz',Now) +'|'+ StringOfChar('-',20));
S.Add(Value);
S.Add('');
S.SaveToFile('log.sql');
Finally
FreeAndNil(S);
End;
end;
procedure TDBConnection.AddLog(Value: TStrings);
var S : TStrings;
begin
If not FLog Then
Exit;
S := TStringList.Create;
Try
If FileExists('log.sql') Then
S.LoadFromFile('log.sql');
S.Add('');
S.Add(FormatDateTime('dd/mm/yyyy hh:nn:ss.zzzz',Now) +'|'+ StringOfChar('-',20));
S.AddStrings(Value);
S.Add('');
S.SaveToFile('log.sql');
Finally
FreeAndNil(S);
End;
end;
procedure TDBConnection.ClearLog;
var S : TStrings;
begin
If not FileExists('log.sql') Then
Exit;
FLog := True;
S := TStringList.Create;
Try
S.LoadFromFile('log.sql');
S.Clear;
S.SaveToFile('log.sql');
Finally
FreeAndNil(S);
End;
end;
procedure TDBConnection.CloseDataSet;
var D : TDataSet;
begin
For D in FDataSet Do
D.Close;
FDataSet.Clear;
end;
function TDBConnection.Connect(Value: TFileName; Section : String): Boolean;
var F : TIniFile;
begin
If ExtractFileDir(Value).IsEmpty Then
Value := ExtractFilePath(GetModuleName(0)) + Value;
F := TIniFile.Create(Value);
Try
FSQL := TSQL.Factory( StringToSQLDB( F.ReadString(Section,'TYPE',SQLDBToString(dbFirebird)) ) );
DataBase.Server := F.ReadString(Section ,'SERVER','localhost');
If (Section = 'DATASNAP') Then
Begin
DataBase.Port := F.ReadInteger(Section,'PORT',211);
DataBase.User := '';
DataBase.Password := '';
DataBase.FilterPC1 := '';
End Else
Begin
DataBase.DataBase := F.ReadString(Section ,'DATABASE','');
DataBase.Port := F.ReadInteger(Section,'PORT' ,3050);
DataBase.User := F.ReadString(Section ,'USER' ,'SYSDBA');
DataBase.Password := F.ReadString(Section ,'PASSWORD','masterkey');
DataBase.Dialect := F.ReadInteger(Section,'DIALECT' ,3);
End;
If (Section <> 'DATASNAP') And not F.ValueExists(Section,'TYPE') Then
F.WriteString(Section ,'TYPE',SQLDBToString(FSQL.SQLDB));
If not F.ValueExists(Section,'SERVER') Then
F.WriteString(Section ,'SERVER', DataBase.Server);
If (Section <> 'DATASNAP') And not F.ValueExists(Section,'DATABASE') Then
F.WriteString(Section ,'DATABASE', DataBase.DataBase);
If not F.ValueExists(Section,'PORT') Then
F.WriteInteger(Section,'PORT' , DataBase.Port);
If (Section <> 'DATASNAP') And not F.ValueExists(Section,'USER') Then
F.WriteString(Section ,'USER', DataBase.User);
If (Section <> 'DATASNAP') And not F.ValueExists(Section,'PASSWORD') Then
F.WriteString(Section ,'PASSWORD', DataBase.Password);
If (Section <> 'DATASNAP') And not F.ValueExists(Section,'DIALECT') Then
F.WriteInteger(Section,'DIALECT', DataBase.Dialect);
Finally
FreeAndNil(F);
End;
Result := Connect;
end;
function TDBConnection.Connected: Boolean;
begin
Result := False;
end;
end.
|
unit PxDelphi5;
{$I PxDefines.inc}
interface
{$IFDEF VER130}
uses
SysUtils;
const
{$IFDEF WIN32}
PathDelim = '\';
SLineBreak = #13#10;
{$ENDIF}
{$IFDEF LINUX}
PathDelim = '/';
SLineBreak = #13;
{$ENDIF}
PathSep = ';';
type
UTF8String = type string;
TSeekOrigin = (soBeginning, soCurrent, soEnd);
function Utf8ToUnicode(Dest: PWideChar; MaxDestChars: Cardinal; Source: PChar; SourceBytes: Cardinal): Cardinal;
function Utf8Decode(const S: UTF8String): WideString;
function UnicodeToUtf8(Dest: PChar; MaxDestBytes: Cardinal; Source: PWideChar; SourceChars: Cardinal): Cardinal;
function Utf8Encode(const WS: WideString): UTF8String;
function WideFormat(S: WideString; Params: array of const): WideString;
procedure RaiseLastOsError;
function TryStrToInt(S: String; var Value: Integer): Boolean;
function IncludeTrailingPathDelimiter(S: String): String;
function ExcludeTrailingPathDelimiter(S: String): String;
{$ENDIF}
implementation
{$IFDEF VER130}
function Utf8ToUnicode(Dest: PWideChar; MaxDestChars: Cardinal; Source: PChar; SourceBytes: Cardinal): Cardinal;
var
i, count: Cardinal;
c: Byte;
wc: Cardinal;
begin
if Source = nil then
begin
Result := 0;
Exit;
end;
Result := Cardinal(-1);
count := 0;
i := 0;
if Dest <> nil then
begin
while (i < SourceBytes) and (count < MaxDestChars) do
begin
wc := Cardinal(Source[i]);
Inc(i);
if (wc and $80) <> 0 then
begin
if i >= SourceBytes then Exit; // incomplete multibyte char
wc := wc and $3F;
if (wc and $20) <> 0 then
begin
c := Byte(Source[i]);
Inc(i);
if (c and $C0) <> $80 then Exit; // malformed trail byte or out of range char
if i >= SourceBytes then Exit; // incomplete multibyte char
wc := (wc shl 6) or (c and $3F);
end;
c := Byte(Source[i]);
Inc(i);
if (c and $C0) <> $80 then Exit; // malformed trail byte
Dest[count] := WideChar((wc shl 6) or (c and $3F));
end
else
Dest[count] := WideChar(wc);
Inc(count);
end;
if count >= MaxDestChars then count := MaxDestChars-1;
Dest[count] := #0;
end
else
begin
while (i < SourceBytes) do
begin
c := Byte(Source[i]);
Inc(i);
if (c and $80) <> 0 then
begin
if i >= SourceBytes then Exit; // incomplete multibyte char
c := c and $3F;
if (c and $20) <> 0 then
begin
c := Byte(Source[i]);
Inc(i);
if (c and $C0) <> $80 then Exit; // malformed trail byte or out of range char
if i >= SourceBytes then Exit; // incomplete multibyte char
end;
c := Byte(Source[i]);
Inc(i);
if (c and $C0) <> $80 then Exit; // malformed trail byte
end;
Inc(count);
end;
end;
Result := count+1;
end;
function Utf8Decode(const S: UTF8String): WideString;
var
L: Integer;
Temp: WideString;
begin
Result := '';
if S = '' then Exit;
SetLength(Temp, Length(S));
L := Utf8ToUnicode(PWideChar(Temp), Length(Temp)+1, PChar(S), Length(S));
if L > 0 then
SetLength(Temp, L-1)
else
Temp := '';
Result := Temp;
end;
function UnicodeToUtf8(Dest: PChar; MaxDestBytes: Cardinal; Source: PWideChar; SourceChars: Cardinal): Cardinal;
var
i, count: Cardinal;
c: Cardinal;
begin
Result := 0;
if Source = nil then Exit;
count := 0;
i := 0;
if Dest <> nil then
begin
while (i < SourceChars) and (count < MaxDestBytes) do
begin
c := Cardinal(Source[i]);
Inc(i);
if c <= $7F then
begin
Dest[count] := Char(c);
Inc(count);
end
else if c > $7FF then
begin
if count + 3 > MaxDestBytes then
break;
Dest[count] := Char($E0 or (c shr 12));
Dest[count+1] := Char($80 or ((c shr 6) and $3F));
Dest[count+2] := Char($80 or (c and $3F));
Inc(count,3);
end
else // $7F < Source[i] <= $7FF
begin
if count + 2 > MaxDestBytes then
break;
Dest[count] := Char($C0 or (c shr 6));
Dest[count+1] := Char($80 or (c and $3F));
Inc(count,2);
end;
end;
if count >= MaxDestBytes then count := MaxDestBytes-1;
Dest[count] := #0;
end
else
begin
while i < SourceChars do
begin
c := Integer(Source[i]);
Inc(i);
if c > $7F then
begin
if c > $7FF then
Inc(count);
Inc(count);
end;
Inc(count);
end;
end;
Result := count+1; // convert zero based index to byte count
end;
function Utf8Encode(const WS: WideString): UTF8String;
var
L: Integer;
Temp: UTF8String;
begin
Result := '';
if WS = '' then Exit;
SetLength(Temp, Length(WS) * 3); // SetLength includes space for null terminator
L := UnicodeToUtf8(PChar(Temp), Length(Temp)+1, PWideChar(WS), Length(WS));
if L > 0 then
SetLength(Temp, L-1)
else
Temp := '';
Result := Temp;
end;
function WideFormat(S: WideString; Params: array of const): WideString;
begin
Result := Format(S, Params);
end;
procedure RaiseLastOsError;
begin
RaiseLastWin32Error;
end;
function TryStrToInt(S: String; var Value: Integer): Boolean;
var
Error: Integer;
begin
Val(S, Value, Error);
Result := Error = 0;
end;
function IncludeTrailingPathDelimiter(S: String): String;
begin
Result := IncludeTrailingBackslash(S);
end;
function ExcludeTrailingPathDelimiter(S: String): String;
begin
Result := ExcludeTrailingBackslash(S);
end;
{$ENDIF}
end.
|
unit UNavigatorSuper;
interface
uses UxlClasses, UPageSuper, UxlExtClasses, UxlDragControl, UPageFactory, UTypeDef;
type
TNavigatorSuper = class (TxlInterfacedObject, IPageObserver)
private
FOnDropItems: TDropPageEvent;
FActive: boolean;
procedure SetActive (value: boolean);
protected
function f_NameToLabel (o_page: TPageSuper): widestring;
procedure LoadIndex (); virtual; abstract;
procedure SelectPage (value: TPageSuper); virtual; abstract;
procedure AddPage (value: TPageSuper); virtual; abstract;
procedure ResetPage (value: TPageSuper); virtual; abstract;
procedure DeletePage (value: TPageSuper); virtual; abstract;
procedure RenamePage (value: TPageSuper); virtual; abstract;
public
function Control (): TxlDragControl; virtual; abstract;
procedure OnPageEvent (pct: TPageEvent; id, id2: integer);
property OnDropItems: TDropPageEvent read FOnDropItems write FOnDropItems;
property Active: boolean read FActive write SetActive;
end;
implementation
uses UGlobalObj, UPageStore, UxlCommDlgs, Resource;
function TNavigatorSuper.f_NameToLabel (o_page: TPageSuper): widestring;
begin
result := o_page.name;
case o_page.Status of
psLocked: result := '+ ' + result;
psProtected: result := '* ' + result;
psReadOnly: result := '# ' + result;
end;
end;
procedure TNavigatorSuper.SetActive (value: boolean);
begin
FActive := value;
if value then
begin
LoadIndex;
PageCenter.AddObserver (self);
if PageCenter.ActivePage <> nil then
SelectPage (PageCenter.ActivePage);
end
else
PageCenter.RemoveObserver (self);
end;
procedure TNavigatorSuper.OnPageEvent (pct: TPageEvent; id, id2: integer);
begin
case pct of
pctRenameDemand:
RenamePage (PageStore[id]);
pctFieldModified, pctSwitchStatus, pctIcon:
ResetPage (PageStore[id]);
pctAddChild:
if PageStore[id].ChildShowInTree (PageStore[id2].PageType) then
AddPage (PageStore[id2]);
pctRemoveChild:
if PageStore[id].ChildShowInTree (PageStore[id2].PageType) then
DeletePage (PageStore[id2]);
pctSetActive:
SelectPage (PageStore[id]);
end;
end;
end.
|
unit Marvin.Desktop.ClientClasses.AulaMulticamada;
interface
uses
uMRVClasses,
{ repositório }
Marvin.Desktop.Repositorio.AulaMulticamada;
type
coAulaMulticamadasClientJSON = class
private
{ singleton }
class var FInstancia: IMRVRepositorioAulaMulticamada;
strict private
class function GetInstancia: IMRVRepositorioAulaMulticamada; static;
public
class function Create: IMRVRepositorioAulaMulticamada;
end;
implementation
uses
{ ClientModule }
Marvin.Desktop.ClientModule.AulaMulticamada,
{ dados }
Marvin.AulaMulticamada.Listas.TipoCliente,
Marvin.AulaMulticamada.Classes.TipoCliente,
Marvin.AulaMulticamada.Listas.Cliente,
Marvin.AulaMulticamada.Classes.Cliente,
{ embarcadero }
System.SysUtils;
type
TMRVClientClassesAulaMulticamadaJSON = class(TMRVObjetoBase,
IMRVRepositorioAulaMulticamada)
private
protected
public
constructor Create; override;
destructor Destroy; override;
{ cliente }
function ClientesProcurarItens(const ACliente: TMRVDadosBase): TMRVListaBase;
function ClientesProcurarItem(const ACliente: TMRVDadosBase): TMRVDadosBase;
function ClientesInserir(const ACliente: TMRVDadosBase): TMRVDadosBase;
function ClientesAlterar(const ACliente: TMRVDadosBase): TMRVDadosBase;
function ClientesExcluir(const ACliente: TMRVDadosBase): string;
{ tipo de cliente }
function TiposClienteProcurarItens(const ATipoCliente: TMRVDadosBase): TMRVListaBase;
function TiposClienteInserir(const ATipoCliente: TMRVDadosBase): TMRVDadosBase;
function TiposClienteAlterar(const ATipoCliente: TMRVDadosBase): TMRVDadosBase;
function TiposClienteExcluir(const ATipoCliente: TMRVDadosBase): string;
end;
{ coAulaMulticamadasClient }
{ /************************************************************************/
| Fábrica que irá instanciar um objeto para conexão com o servidor. |
/************************************************************************/ }
class function coAulaMulticamadasClientJSON.Create: IMRVRepositorioAulaMulticamada;
begin
Result := coAulaMulticamadasClientJSON.GetInstancia;
end;
class function coAulaMulticamadasClientJSON.GetInstancia: IMRVRepositorioAulaMulticamada;
begin
if not (Assigned(FInstancia)) then
begin
FInstancia := TMRVClientClassesAulaMulticamadaJSON.Create;
end;
Result := FInstancia;
end;
{ TMRVClientClassesAulaMulticamadaJSON }
constructor TMRVClientClassesAulaMulticamadaJSON.Create;
begin
inherited;
if not Assigned(ClientModuleAulaMulticamada) then
begin
{ cria o ClientModule JSON/REST }
ClientModuleAulaMulticamada := TClientModuleAulaMulticamada.Create(nil);
end;
end;
destructor TMRVClientClassesAulaMulticamadaJSON.Destroy;
begin
FreeAndNil(ClientModuleAulaMulticamada);
inherited;
end;
{$REGION 'Métodos para Cliente.'}
{ /************************************************************************/
| Métodos para CLIENTE. |
/************************************************************************/ }
function TMRVClientClassesAulaMulticamadaJSON.ClientesAlterar(const ACliente:
TMRVDadosBase): TMRVDadosBase;
begin
{ recupera todos os clientes }
Result := ClientModuleAulaMulticamada.SendObject('Cliente', ACliente,
TMRVCliente, taPost);
end;
function TMRVClientClassesAulaMulticamadaJSON.ClientesExcluir(const ACliente:
TMRVDadosBase): string;
begin
{ excluí o cliente informado }
Result := ClientModuleAulaMulticamada.ExecuteJSONById('Cliente',
TMRVCliente(ACliente).Clienteid.ToString, taCancel);
{ verifica se existe alguma exceção }
ClientModuleAulaMulticamada.CheckException(Result);
{ recupera o resultado }
Result := ClientModuleAulaMulticamada.GetResultValue(Result, 'Mensagem');
end;
function TMRVClientClassesAulaMulticamadaJSON.ClientesInserir(const ACliente:
TMRVDadosBase): TMRVDadosBase;
begin
Result := ClientModuleAulaMulticamada.SendObject('Cliente', ACliente,
TMRVCliente, taAccept);
end;
function TMRVClientClassesAulaMulticamadaJSON.ClientesProcurarItem(const
ACliente: TMRVDadosBase): TMRVDadosBase;
begin
Result := ClientModuleAulaMulticamada.GetObject('Cliente', TMRVCliente);
end;
function TMRVClientClassesAulaMulticamadaJSON.ClientesProcurarItens(const
ACliente: TMRVDadosBase): TMRVListaBase;
begin
Result := ClientModuleAulaMulticamada.GetObjects('Cliente', TMRVListaCliente);
end;
{$ENDREGION}
{$REGION 'Métodos para Tipo de Cliente'}
{ /************************************************************************/
| Métodos para TIPO DE CLIENTE. |
/************************************************************************/ }
function TMRVClientClassesAulaMulticamadaJSON.TiposClienteAlterar(const
ATipoCliente: TMRVDadosBase): TMRVDadosBase;
begin
Result := ClientModuleAulaMulticamada.SendObject('TipoCliente', ATipoCliente,
TMRVTipoCliente, taPost);
end;
function TMRVClientClassesAulaMulticamadaJSON.TiposClienteExcluir(const
ATipoCliente: TMRVDadosBase): string;
begin
{ recupera os dados }
Result := ClientModuleAulaMulticamada.ExecuteJSONById('TipoCliente',
TMRVTipoCliente(ATipoCliente).TipoClienteId.ToString, taCancel);
{ verifica se existe alguma exceção }
ClientModuleAulaMulticamada.CheckException(Result);
{ recupera resultado }
Result := ClientModuleAulaMulticamada.GetResultValue(Result, 'Mensagem');
end;
function TMRVClientClassesAulaMulticamadaJSON.TiposClienteInserir(const
ATipoCliente: TMRVDadosBase): TMRVDadosBase;
begin
Result := ClientModuleAulaMulticamada.SendObject('TipoCliente', ATipoCliente,
TMRVTipoCliente, taAccept);
end;
function TMRVClientClassesAulaMulticamadaJSON.TiposClienteProcurarItens(const
ATipoCliente: TMRVDadosBase): TMRVListaBase;
begin
Result := ClientModuleAulaMulticamada.GetObjects('TipoCliente',
TMRVListaTipoCliente);
end;
{$ENDREGION}
initialization
finalization
{ libera o singleton }
if Assigned(coAulaMulticamadasClientJSON.FInstancia) then
begin
coAulaMulticamadasClientJSON.FInstancia := nil;
end;
end.
|
{ The Initial Developer is "Barbichette" and of the Original Code
can be found here: http://www.delphifr.com//code.aspx?ID=45846
His work was inspired from an "Oniria" source that can be found here: http://www.delphifr.com/codes/CALCULATRICE-CHAIN%20ES-MATHEMATIQUES_45537.aspx
The method used to parse is called "reverse Polish notation" :
http://en.wikipedia.org/wiki/Reverse_Polish_notation
From Wikipedia:
"Reverse Polish notation (or RPN) is a mathematical notation wherein every operator follows all of its operands, in contrast to Polish notation,
which puts the operator in the prefix position. It is also known as Postfix notation and is parenthesis-free as long as operator arities are fixed.
The description "Polish" refers to the nationality of logician Jan ?ukasiewicz, who invented (prefix) Polish notation in the 1920s."
Exemple:
Infix notation | RPN
-------------------------------
2+2*3 | 2 2 3 * +
2*2+3 | 2 2 x 3 +
}
{ Component(s):
tcyMathParser
Description:
Math parsing component that can evaluate an expression using common operators, some functions and variables
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$ €€€ Accept any PAYPAL DONATION $$$ €
$ to: mauricio_box@yahoo.com €
€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€
* ***** BEGIN LICENSE BLOCK *****
*
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* The Initial Developer of the Original Code is Mauricio
* (https://sourceforge.net/projects/tcycomponents/).
*
* No contributors for now ...
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or the
* GNU Lesser General Public License Version 2.1 or later (the "LGPL"), in which
* case the provisions of the GPL or the LGPL are applicable instead of those
* above. If you wish to allow use of your version of this file only under the
* terms of either the GPL or the LGPL, and not to allow others to use your
* version of this file under the terms of the MPL, indicate your decision by
* deleting the provisions above and replace them with the notice and other
* provisions required by the LGPL or the GPL. If you do not delete the
* provisions above, a recipient may use your version of this file under the
* terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK *****}
unit cyMathParser;
interface
uses Math, SysUtils, StrUtils, windows;
const
cNoError = 0;
// Internal error:
cInternalError = 1;
// Expression errors:
cErrorInvalidCar = 2;
cErrorUnknownName = 3;
cErrorInvalidFloat = 4;
cErrorOperator = 5;
cErrorFxNeedLeftParentese = 6;
cErrorNotEnoughArgs = 7;
cErrorSeparatorNeedArgument = 8;
cErrorMissingLeftParenteses = 9;
cErrorMissingRightParenteses = 10;
cErrorLeftParentese = 11;
cErrorRightParentese = 12;
cErrorSeparator = 13;
cErrorOperatorNeedArgument = 14;
// Calc errors:
cCalcError = 100; // From here, this is a calculation error ...
cErrorDivByZero = 101;
cErrorPower = 102;
cErrorFxInvalidValue = 103;
type
TTypeStack = (tsNotDef, tsValue, tsOperator, tsFunction, tsLeftParenthese, tsRightParenthese, tsSeparator, tsVariable);
// Handled operators and functions:
TOperationType = (opNone,
// Operators
OpPower, OpMultiply, OpDivide, OpAdd, OpSubstract, OpMod, OpNeg,
// Functions
OpCos, OpSin, OpTan, OpLog, OpLn, OpASin, OpACos, OpATan, OpExp, OpSqrt, OpSqr, OpLogN,OpInt,OpFrac,OpAbs,
OpCeil, OpFloor, OpLdexp, OpLnXP1, OpMax, OpMin, OpRoundTo, OpSign, OpSum);
// Operators and functions information :
TOperationInfo = record
Priority: byte;
Arguments: Integer;
Name: String;
OperationType: TOperationType;
end;
const
MaxOperationsInfo = 31;
// Operators and functions rules and specifications :
OperationsInfo: array[0..MaxOperationsInfo] of TOperationInfo = (
// None
(Priority: 0; Arguments: 0; Name: ''; OperationType: opNone) // opNone
// Operators
,(Priority: 3; Arguments: 2; Name: '^'; OperationType: OpPower) // OpPower
,(Priority: 2; Arguments: 2; Name: '*'; OperationType: OpMultiply) // OpMultiply
,(Priority: 2; Arguments: 2; Name: '/'; OperationType: OpDivide) // OpDivide
,(Priority: 1; Arguments: 2; Name: '+'; OperationType: OpAdd) // OpAdd
,(Priority: 1; Arguments: 2; Name: '-'; OperationType: OpSubstract) // OpSubstract
,(Priority: 2; Arguments: 2; Name: 'mod'; OperationType: OpMod) // OpMod (5 mod 3 = 2)
,(Priority: 4; Arguments: 1; Name: 'neg'; OperationType: OpNeg) // OpNeg (negative value, used for diferenciate with substract operator)
// Functions
,(Priority: 0; Arguments: 1; Name: 'cos'; OperationType: OpCos) // OpCos
,(Priority: 0; Arguments: 1; Name: 'sin'; OperationType: OpSin) // OpSin
,(Priority: 0; Arguments: 1; Name: 'tan'; OperationType: OpTan) // OpTan
,(Priority: 0; Arguments: 1; Name: 'log'; OperationType: OpLog) // OpLog
,(Priority: 0; Arguments: 1; Name: 'ln'; OperationType: OpLn) // OpLn
,(Priority: 0; Arguments: 1; Name: 'asin'; OperationType: OpASin) // OpASin
,(Priority: 0; Arguments: 1; Name: 'acos'; OperationType: OpACos) // OpACos
,(Priority: 0; Arguments: 1; Name: 'atan'; OperationType: OpATan) // OpATan
,(Priority: 0; Arguments: 1; Name: 'exp'; OperationType: OpExp) // OpExp
,(Priority: 0; Arguments: 1; Name: 'sqrt'; OperationType: OpSqrt) // OpSqrt
,(Priority: 0; Arguments: 1; Name: 'sqr'; OperationType: OpSqr) // OpSqr
,(Priority: 0; Arguments: 2; Name: 'logn'; OperationType: OpLogN) // OpLogN
,(Priority: 0; Arguments: 1; Name: 'int'; OperationType: OpInt) // OpInt
,(Priority: 0; Arguments: 1; Name: 'frac'; OperationType: OpFrac) // OpFrac
,(Priority: 0; Arguments: 1; Name: 'abs'; OperationType: OpAbs) // OpAbs
,(Priority: 0; Arguments: 1; Name: 'ceil'; OperationType: OpCeil) // OpCeil
,(Priority: 0; Arguments: 1; Name: 'floor'; OperationType: OpFloor) // OpFloor
,(Priority: 0; Arguments: 2; Name: 'ldexp'; OperationType: OpLdexp) // OpLdexp
,(Priority: 0; Arguments: 1; Name: 'lnxp1'; OperationType: OpLnXP1) // OpLnXP1
,(Priority: 0; Arguments: 2; Name: 'max'; OperationType: OpMax) // OpMax
,(Priority: 0; Arguments: 2; Name: 'min'; OperationType: OpMin) // OpMin
,(Priority: 0; Arguments: 2; Name: 'roundto'; OperationType: OpRoundTo) // OpRoundTo
,(Priority: 0; Arguments: 1; Name: 'sign'; OperationType: OpSign) // OpSign
,(Priority: 0; Arguments:-1; Name: 'sum'; OperationType: OpSum) // OpSum
);
function GetOperationType(s: string): TOperationType;
function GetOperationInfo(OperationType: TOperationType): TOperationInfo;
type
TStackInfo = record
Value: Extended;
OperationType: TOperationType;
TypeStack: TTypeStack;
VarName: string;
ArgumentsCount: Integer; // Number of arguments for functions with no fixed arguments
end;
TStack = class
private
fCount: Integer;
protected
fList: array of TStackInfo;
function GetStackInfo(Index: Integer): TStackInfo;
procedure SetStackInfo(Index: Integer; StackInfo: TStackInfo);
public
constructor create;
property Count: Integer read fCount;
property StackInfo[Index: Integer]: TStackInfo read GetStackInfo write SetStackInfo; default;
function Add(StackInfo: TStackInfo): Integer;
function Insert(StackInfo: TStackInfo; Index: Integer): Integer;
procedure Delete(Index: Integer);
function DeleteLast: TStackInfo;
function Last: TStackInfo;
procedure Clear;
end;
function ReturnTStackInfo(Value: Extended; TypeStack: TTypeStack; OperationType: TOperationType = opNone; VariableName: string = ''): TStackInfo;
type
TVariables = class
private
fCount: Integer;
fNames: Array of string;
fValues: Array of Extended;
function Add(Name: String; Value: Extended): Integer;
procedure Delete(Name: String);
protected
procedure Clear;
function GetName(Index: Integer): String;
function GetValue(Index: Integer): Extended; overload;
public
constructor create;
property Count: Integer read fCount;
property Names[Index: Integer]: String read GetName;
property Values[Index: Integer]: Extended read GetValue;
function GetIndex(Name: String): Integer;
function GetValue(Name: String; var Value: Extended): boolean; overload;
procedure SetValue(Name: String; Value: Extended);
end;
function ValidVariableName(Name: string): Boolean;
type
TcyMathParser = class
private
fLastError: integer;
fLastErrorBeforeParse: Integer;
fResultStack: TStack;
fPrefixStack: TStack;
fExpression: String;
procedure InfixToPreFix(infix: TStack; Prefix: TStack);
procedure StrToInfixStack(aExpression: String; aStack: TStack);
function ValidateInfixStack(aStack: TStack):Boolean;
function GetParserResult: Extended;
procedure SetExpression(const Value: String);
protected
public
Variables: TVariables;
constructor create;
destructor Destroy; override;
property Expression: String read fExpression write SetExpression;
property ParserResult: Extended read GetParserResult;
procedure Parse;
function GetLastError: Integer;
function GetLastErrorString: String;
end;
function GetErrorString(ErrorCode: integer): String;
implementation
function GetOperationType(s: string): TOperationType;
var
i: Integer;
begin
Result := opNone;
for i:= 0 to MaxOperationsInfo do
if OperationsInfo[i].Name = s
then begin
Result := OperationsInfo[i].OperationType;
break;
end;
end;
function GetOperationInfo(OperationType: TOperationType): TOperationInfo;
var i: Integer;
begin
Result := OperationsInfo[0]; // None
for i:= 1 to MaxOperationsInfo do
if OperationsInfo[i].OperationType = OperationType
then begin
Result := OperationsInfo[i];
break;
end;
end;
function ReturnTStackInfo(Value: Extended; TypeStack: TTypeStack; OperationType: TOperationType = opNone; VariableName: string = ''): TStackInfo;
begin
Result.Value := Value;
Result.OperationType := OperationType;
Result.TypeStack := TypeStack;
Result.VarName := VariableName;
end;
constructor TStack.Create;
begin
inherited;
fCount := 0;
SetLength(fList, 0);
end;
function TStack.GetStackInfo(Index: Integer): TStackInfo;
begin
Result := fList[Index];
end;
procedure TStack.SetStackInfo(Index: Integer; StackInfo: TStackInfo);
begin
fList[Index] := StackInfo;
end;
function TStack.Add(StackInfo: TStackInfo): Integer;
begin
inc(fCount);
Setlength(fList, fCount);
fList[fCount - 1] := StackInfo;
Result := fCount - 1;
end;
function TStack.Insert(StackInfo: TStackInfo; Index: Integer): Integer;
var i: Integer;
begin
if Index > fCount then Index := fCount;
if Index < 0 then Index := 0;
Setlength(fList, fCount + 1);
i:= fCount - 1;
while i >= Index do
begin
fList[i+1] := fList[i];
dec(i);
end;
fList[Index] := StackInfo;
inc(fCount);
Result := Index;
end;
procedure TStack.Delete(Index: Integer);
begin
dec(fCount);
while Index < fCount do
begin
fList[Index] := fList[Index+1];
inc(Index);
end;
Setlength(fList, fCount);
end;
function TStack.DeleteLast: TStackInfo;
begin
Result := fList[fCount-1];
Delete(fCount-1);
end;
function TStack.Last: TStackInfo;
begin
Result := fList[fCount-1];
end;
procedure TStack.Clear;
begin
fCount := 0;
Setlength(fList, 0);
end;
// Determine if variable Name is defined with 'a'..'z', '_' and does not enter in conflict with function Names:
function ValidVariableName(Name: string): Boolean;
var
i: Integer;
begin
Result:= false;
Name := trim(Lowercase(Name));
if (Name = '') or (Name = 'e') then exit; // ex: 5E3 = 5 * 10*10*10
if GetOperationType(Name) <> opNone then exit;
if not (Name[1] in ['_','a'..'z']) then exit;
for i:= 2 to length(Name) do
if not (Name[i] in ['_','a'..'z','0'..'9'])
then exit;
Result:= True;
end;
constructor TVariables.Create;
begin
Clear;
end;
procedure TVariables.Clear;
begin
fCount := 0;
setlength(fNames, 0);
setlength(fValues, 0);
end;
function TVariables.GetIndex(Name: String): Integer;
var i: Integer;
begin
Result := -1;
Name := lowercase(Name);
for i:= 0 to fCount - 1 do
if fNames[i] = Name
then begin
Result := i;
exit;
end;
end;
function TVariables.GetValue(Name: string; var Value: Extended): Boolean;
var i: Integer;
begin
Result:= false;
Name := lowercase(Name);
i := GetIndex(Name);
if i<> -1
then begin
Value := fValues[i];
Result := True;
end;
end;
procedure TVariables.SetValue(Name: String; Value: Extended);
var
i: Integer;
begin
Name := lowercase(Name);
i := GetIndex(Name);
if i = -1
then Add(Name, Value)
else fValues[i] := value;
end;
function TVariables.Add(Name: String; Value: Extended): Integer;
begin
Name := lowercase(Name);
Result := GetIndex(Name);
if Result = -1
then begin
inc(fCount);
setlength(fNames, fCount);
setlength(fValues, fCount);
fNames[fCount-1] := Name;
fValues[fCount-1] := Value;
Result := fCount-1;
end;
end;
procedure TVariables.Delete(Name: String);
var
i: Integer;
begin
Name := Lowercase(Name);
i := GetIndex(Name);
if i = -1 then exit;
dec(fCount);
move(fNames[i + 1], fNames[i], (fCount - i - 1) * sizeof(string));
move(fValues[i + 1], fValues[i], (fCount-i-1) * sizeof(extended));
setlength(fNames, fCount);
setlength(fValues, fCount);
end;
function TVariables.GetName(Index: Integer): String;
begin
Result := fNames[Index];
end;
function TVariables.GetValue(Index: Integer): Extended;
begin
Result := fValues[Index];
end;
constructor TcyMathParser.Create;
begin
inherited;
fExpression := '';
fLastError := cNoError;
fLastErrorBeforeParse := cNoError;
fResultStack := TStack.Create;
fPrefixStack := TStack.Create;
Variables := TVariables.Create;
//Variables.Add('pi', 3.1415926535897932385);
end;
destructor TcyMathParser.Destroy;
begin
fResultStack.Free;
fPrefixStack.Free;
Variables.Free;
inherited;
end;
procedure TcyMathParser.SetExpression(const Value: String);
var InfixStack: TStack;
begin
fExpression := Value;
fLastError := cNoError;
fLastErrorBeforeParse := cNoError;
fPrefixStack.Clear;
fResultStack.Clear;
if fExpression = '' then exit;
// Get infix stack :
InfixStack := TStack.create;
StrToInfixStack(fExpression, InfixStack);
if fLastError = cNoError then
if ValidateInfixStack(InfixStack) then
InfixToPreFix(InfixStack, fPrefixStack);
fLastErrorBeforeParse := fLastError;
InfixStack.Free;
end;
// Convert infix notation to stack infix notation :
procedure TcyMathParser.StrToInfixStack(aExpression: String; aStack: TStack);
var
i, j, lengthExpr: integer;
s: string;
v: Extended;
Op: TOperationType;
begin
aStack.Clear;
aExpression := LowerCase(aExpression);
lengthExpr := length(aExpression);
i := 1;
while i <= lengthExpr do
case aExpression[i] of
'(','{','[':
begin
aStack.Add(ReturnTStackInfo(0, tsLeftParenthese));
inc(i);
end;
')','}',']':
begin
aStack.Add(ReturnTStackInfo(0, tsRightParenthese));
inc(i);
end;
'a'..'z', '_': // Functions and variables must begin with a letter or with '_'
begin
s := '';
for j := i to lengthExpr do
if aExpression[j] in ['a'..'z', '_', '0'..'9', ' ']
then begin
// case of the function "E": (Exemple: 5E3 = 5 * 10*10*10), must be followed by a number :
if (s = 'e') and (aExpression[j] in ['0'..'9', ' '])
then begin
s := '';
inc(i); // Return to next car after "E"
// E must be replaced by *10^
aStack.Add(ReturnTStackInfo(0, tsOperator, GetOperationType('*')));
aStack.Add(ReturnTStackInfo(10, tsValue));
aStack.Add(ReturnTStackInfo(0, tsOperator, GetOperationType('^')));
Break;
end
else
// case of the operator "mod"
if (s = 'mod') and (aExpression[j] in ['0'..'9', ' '])
then begin
s := '';
i := i + 3; // Return to next car after "mod"
aStack.Add(ReturnTStackInfo(0, tsOperator, OpMod));
Break;
end
else
if aExpression[j] <> ' '
then s := s + aExpression[j]
else Break;
end
else
break;
if s <> ''
then begin
i := j;
Op := GetOperationType(s); // Know if it is a function or variable ...
if op = opNone
then
aStack.Add(ReturnTStackInfo(0, tsVariable, opNone, s))
else
if GetOperationInfo(Op).Priority <> 0 // Operators
then aStack.Add(ReturnTStackInfo(0, tsOperator, Op))
else aStack.Add(ReturnTStackInfo(0, tsFunction, Op));
end;
end;
'0'..'9', '.', ',':
begin
s:= '';
for j := i to lengthExpr do
if aExpression[j] in ['0'..'9']
then
s := s + aExpression[j]
else
if aExpression[j] in ['.', ',']
then s := s + DecimalSeparator
else break;
i := j;
if not TryStrToFloat(s, V)
then begin
fLastError := cErrorInvalidFloat;
Exit;
end;
aStack.Add(ReturnTStackInfo(v, tsValue));
end;
';':
begin
aStack.Add(ReturnTStackInfo(0, TsSeparator));
inc(i);
end;
'-', '+', '/', '*', '^':
begin
aStack.Add(ReturnTStackInfo(0, tsOperator, GetOperationType(aExpression[i])));
inc(i);
end;
'%':
begin
aStack.Add(ReturnTStackInfo(0, tsOperator, OpDivide));
aStack.Add(ReturnTStackInfo(100, tsValue));
inc(i);
end;
// Space, just ignore
' ':
Inc(i);
else begin
fLastError := cErrorInvalidCar;
exit;
end;
end;
end;
function TcyMathParser.ValidateInfixStack(aStack: TStack): Boolean;
var
LeftParentesesCount, RightParentesesCount: Integer;
i: Integer;
j, c, NbArguments: Integer;
begin
LeftParentesesCount := 0;
RightParentesesCount := 0;
i := 0;
while (fLastError = cNoError) and (i <= aStack.Count-1) do // Note that aStack.Count can change!
case aStack[i].TypeStack of
tsLeftParenthese:
begin
// *** Check for invalid position *** //
if i > 0
then begin
// Need multiply operator ?
if aStack[i-1].TypeStack in [tsValue, TsVariable, tsRightParenthese]
then begin
aStack.Insert(ReturnTStackInfo(0, tsOperator, OpMultiply), i);
Continue; // Will process this new stack
end;
end;
if (i = aStack.Count - 1)
then fLastError := cErrorMissingRightParenteses;
inc(LeftParentesesCount);
inc(i);
end;
tsRightParenthese:
begin
// *** Check for invalid position *** //
if i > 0
then begin
if aStack[i-1].TypeStack in [tsFunction, tsOperator, TsSeparator]
then fLastError := cErrorRightParentese;
end;
inc(RightParentesesCount);
inc(i);
if (fLastError = cNoError) and (RightParentesesCount > LeftParentesesCount)
then fLastError := cErrorMissingLeftParenteses;
end;
tsValue, TsVariable:
begin
// *** Check for invalid position *** //
if i > 0
then begin
// Need multiply operator ?
if aStack[i-1].TypeStack in [tsValue, TsVariable, tsRightParenthese]
then begin
aStack.Insert(ReturnTStackInfo(0, tsOperator, OpMultiply), i);
Continue; // Will process this new stack
end;
if aStack[i-1].TypeStack = tsFunction
then fLastError := cErrorFxNeedLeftParentese;
end;
inc(i);
end;
tsFunction:
begin
// *** Check for invalid position *** //
if i > 0
then begin
// Need multiply operator ?
if aStack[i-1].TypeStack in [tsValue, TsVariable, tsRightParenthese]
then begin
aStack.Insert(ReturnTStackInfo(0, tsOperator, OpMultiply), i);
Continue; // Will process this new stack
end;
end;
if (i = aStack.Count - 1)
then fLastError := cErrorFxNeedLeftParentese;
inc(i);
end;
tsSeparator:
begin
// *** Check for invalid use *** //
if i = 0
then
fLastError := cErrorSeparator
else
if (i = aStack.Count - 1)
then
fLastError := cErrorSeparatorNeedArgument
else
case aStack[i-1].TypeStack of
tsFunction: fLastError := cErrorFxNeedLeftParentese;
tsSeparator: fLastError := cErrorSeparatorNeedArgument;
tsOperator, tsLeftParenthese: fLastError := cErrorSeparator;
end;
inc(i);
end;
tsOperator:
begin
// *** Check for invalid use *** //
if i = 0
then begin
case aStack[0].OperationType of
OpAdd:
begin
aStack.Delete(0);
Dec(i);
end;
OpSubstract:
aStack.fList[0].OperationType := OpNeg;
else
fLastError := cErrorOperator;
end;
end
else
if (i = aStack.Count - 1)
then
fLastError := cErrorOperatorNeedArgument
else
case aStack[i-1].TypeStack of
tsFunction: fLastError := cErrorFxNeedLeftParentese;
tsOperator, tsLeftParenthese, tsSeparator: // excluding opNeg that is handled upper ...
case aStack[i].OperationType of // Check current operation
OpSubstract:
if (aStack[i-1].TypeStack = tsOperator) and (aStack[i-1].OperationType = OpNeg)
then begin
// opSubstract nullify opNeg :
aStack.Delete(i-1);
Dec(i);
aStack.Delete(i);
Dec(i);
end
else
aStack.fList[i].OperationType := OpNeg;
OpAdd:
begin
aStack.Delete(i);
Dec(i);
end;
else // like opMultiply etc ...
fLastError := cErrorOperator;
end;
end;
inc(i);
end;
end;
// Handle functions with undefined operands number :
i:= 0;
while (fLastError = cNoError) and (i < aStack.Count) do
begin
if (aStack[i].TypeStack = tsFunction) and (GetOperationInfo(aStack[i].OperationType).Arguments = -1)
then begin
c := 1;
NbArguments := 1;
j := i + 2;
while (j < aStack.Count) and (c > 0) do
begin
case aStack[j].TypeStack of
tsSeparator: if c = 1 then inc(NbArguments);
tsLeftParenthese: Inc(c);
tsRightParenthese: dec(c);
end;
inc(j);
end;
aStack.fList[i].ArgumentsCount := NbArguments; // Store the number of arguments
end;
inc(i);
end;
if (fLastError = cNoError) and (LeftParentesesCount <> RightParentesesCount)
then
if LeftParentesesCount > RightParentesesCount
then fLastError := cErrorMissingRightParenteses
else fLastError := cErrorMissingLeftParenteses;
Result := fLastError = cNoError;
end;
procedure TcyMathParser.InfixToPreFix(Infix: TStack; Prefix: TStack);
var
TmpStack: TStack;
i: Integer;
Current: TStackInfo;
begin
TmpStack := TStack.Create;
for i:= 0 to Infix.Count-1 do
begin
Current := Infix[i];
case Current.TypeStack of
tsValue, TsVariable:
Prefix.Add(Current);
tsFunction:
TmpStack.Add(Current);
tsLeftParenthese:
TmpStack.Add(Current);
tsRightParenthese: // end of previous argument or group of arguments
begin
while TmpStack.Count <> 0 do
if TmpStack.Last.TypeStack <> tsLeftParenthese
then Prefix.Add(TmpStack.DeleteLast)
else Break;
TmpStack.DeleteLast;
if TmpStack.Count <> 0 then
if TmpStack.Last.TypeStack = tsFunction then
Prefix.Add(TmpStack.DeleteLast);
end;
tsSeparator: // end of previous argument
begin
while TmpStack.Count <> 0 do
if TmpStack.Last.TypeStack <> tsLeftParenthese
then Prefix.Add(TmpStack.DeleteLast)
else Break;
end;
tsOperator:
begin
while (TmpStack.Count > 0) do
if (TmpStack.Last.TypeStack = tsOperator) and (GetOperationInfo(Current.OperationType).Priority <= GetOperationInfo(TmpStack.Last.OperationType).Priority)
then Prefix.Add(TmpStack.DeleteLast)
else Break;
TmpStack.Add(Current);
end;
end;
end;
while TmpStack.Count > 0 do
Prefix.Add(TmpStack.DeleteLast);
TmpStack.Free;
end;
procedure TcyMathParser.Parse;
function ExtendedMod(x, y: Extended): Extended;
begin
Result := x - int(x / y) * y;
end;
var
Current: TStackInfo;
i, j, Arguments: Integer;
aValue: Extended;
Values: array of Extended;
procedure ApplyOperation;
var v: Integer;
begin
try
case Current.OperationType of
opNone: ;
// Operators :
OpPower : if (frac(Values[0]) <> 0) and (Values[1] < 0)
then fLastError := cErrorPower
else fResultStack.Add(ReturnTStackInfo(power(Values[1], Values[0]), tsValue));
OpMultiply : fResultStack.Add(ReturnTStackInfo(Values[1] * Values[0], tsValue));
OpDivide : if Values[0] = 0
then fLastError := cErrorDivByZero
else fResultStack.Add(ReturnTStackInfo(Values[1] / Values[0], tsValue));
OpAdd : fResultStack.Add(ReturnTStackInfo(Values[1] + Values[0], tsValue));
OpSubstract: fResultStack.Add(ReturnTStackInfo(Values[1] - Values[0], tsValue));
OpNeg : fResultStack.Add(ReturnTStackInfo(-Values[0], tsValue));
opMod : if Values[0] = 0
then fLastError := cErrorDivByZero
else fResultStack.Add( ReturnTStackInfo(ExtendedMod(Values[1], Values[0]), tsValue) );
// Functions :
OpCos : fResultStack.Add(ReturnTStackInfo(cos(Values[0]), tsValue));
OpSin : fResultStack.Add(ReturnTStackInfo(sin(Values[0]), tsValue));
OpTan : fResultStack.Add(ReturnTStackInfo(tan(Values[0]), tsValue));
OpLog : if Values[0] <= 0
then fLastError := cErrorFxInvalidValue
else fResultStack.Add(ReturnTStackInfo(log10(Values[0]), tsValue));
OpLn : if Values[0] <= 0
then fLastError := cErrorFxInvalidValue
else fResultStack.Add(ReturnTStackInfo(ln(Values[0]), tsValue));
OpASin : if (Values[0] < -1) or (Values[0] > 1)
then fLastError := cErrorFxInvalidValue
else fResultStack.Add(ReturnTStackInfo(arcsin(Values[0]), tsValue));
OpACos : if (Values[0] < -1) or (Values[0] > 1)
then fLastError := cErrorFxInvalidValue
else fResultStack.Add(ReturnTStackInfo(arccos(Values[0]), tsValue));
OpATan : fResultStack.Add(ReturnTStackInfo(arctan(Values[0]), tsValue));
OpExp : fResultStack.Add(ReturnTStackInfo(exp(Values[0]), tsValue));
OpSqrt : if Values[0] < 0
then fLastError := cErrorFxInvalidValue
else fResultStack.Add(ReturnTStackInfo(sqrt(Values[0]), tsValue));
OpSqr : fResultStack.Add(ReturnTStackInfo(sqr(Values[0]), tsValue));
OpInt : fResultStack.Add(ReturnTStackInfo(int(Values[0]), tsValue));
OpFrac : fResultStack.Add(ReturnTStackInfo(frac(Values[0]), tsValue));
OpAbs : fResultStack.Add(ReturnTStackInfo(abs(Values[0]), tsValue));
OpLogN : if (Values[1] <= 0) or (Values[0] <= 0) or (Log2(Values[1]) = 0)
then fLastError := cErrorFxInvalidValue
else fResultStack.Add(ReturnTStackInfo(logn(Values[1], Values[0]), tsValue));
OpCeil : fResultStack.Add(ReturnTStackInfo(Ceil(Values[0]), tsValue));
OpFloor : fResultStack.Add(ReturnTStackInfo(Floor(Values[0]), tsValue));
OpLdexp : fResultStack.Add(ReturnTStackInfo(Ldexp(Values[1], round(Values[0])), tsValue));
OpLnXP1 : if Values[0] <= -1
then fLastError := cErrorFxInvalidValue
else fResultStack.Add(ReturnTStackInfo(LnXP1(Values[0]), tsValue));
OpMax : fResultStack.Add(ReturnTStackInfo(Max(Values[1], Values[0]), tsValue));
OpMin : fResultStack.Add(ReturnTStackInfo(Min(Values[1], Values[0]), tsValue));
OpRoundTo : fResultStack.Add(ReturnTStackInfo(RoundTo(Values[1], round(Values[0])), tsValue));
OpSign : fResultStack.Add(ReturnTStackInfo(Sign(Values[0]), tsValue));
OpSum : begin
aValue := 0;
for v := 0 to Arguments-1 do
aValue := aValue + Values[v];
fResultStack.Add(ReturnTStackInfo(aValue, tsValue));
end;
end;
except
on EInvalidOp do fLastError := cCalcError;
end;
end;
begin
fResultStack.Clear;
fLastError := fLastErrorBeforeParse;
i := 0;
while (fLastError = cNoError) and (i < fPrefixStack.Count) do
begin
Current := fPrefixStack[i];
inc(i);
case Current.TypeStack of
tsValue :
fResultStack.Add(Current);
tsVariable:
begin
if not Variables.GetValue(Current.VarName, aValue)
then fLastError := cErrorUnknownName
else fResultStack.Add(ReturnTStackInfo(aValue, tsValue));
end;
tsOperator, tsFunction:
begin
Arguments := GetOperationInfo(Current.OperationType).Arguments;
// Functions with undefined arguments :
if Arguments = -1
then Arguments := Current.ArgumentsCount;
if fResultStack.Count >= Arguments // Suficient arguments/operands?
then begin
SetLength(Values, Arguments);
// Store needed arguments/operands in array:
for j := 0 to Arguments - 1 do
Values[j] := fResultStack.DeleteLast.Value;
// Make the calc :
ApplyOperation;
end
else
fLastError := cErrorNotEnoughArgs;
end;
end;
end;
// All stacks parsed ?
if fResultStack.Count > 1 then
fLastError := cInternalError;
end;
function TcyMathParser.GetParserResult: Extended;
begin
if fResultStack.Count > 0
then Result := fResultStack[0].Value // Retrieve topmost stack
else Result := 0;
end;
function TcyMathParser.GetLastError: Integer;
begin
Result := fLastError;
end;
function TcyMathParser.GetLastErrorString: String;
begin
Result := GetErrorString(fLastError);
end;
function GetErrorString(ErrorCode: integer): String;
begin
case ErrorCode of
cNoError: Result := '';
cInternalError: Result := 'Cannot parse';
cErrorInvalidCar: Result := 'Invalid car';
cErrorUnknownName: Result := 'Unknown function or variable';
cErrorInvalidFloat: Result := 'Invalid float number';
cErrorOperator: Result := 'Operator cannot be placed here';
cErrorFxNeedLeftParentese: Result := 'A function must be followed by left parentese';
cErrorNotEnoughArgs: Result := 'Not enough arguments or operands';
cErrorSeparatorNeedArgument: Result := 'Missing argument after separator';
cErrorMissingLeftParenteses: Result := 'Missing at least one left parentese';
cErrorMissingRightParenteses: Result := 'Missing at least one right parentese';
cErrorLeftParentese: Result := 'Left parentese cannot be placed here';
cErrorRightParentese: Result := 'Right parentese cannot be placed here';
cErrorSeparator: Result := 'Separator cannot be placed here';
cErrorOperatorNeedArgument: Result := 'Operator must be followed by argument';
cCalcError: Result := 'Invalid operation';
cErrorDivByZero: Result := 'Division by zero';
cErrorPower: Result := 'Invalid use of power function';
cErrorFxInvalidValue: Result := 'Invalid parameter value for function';
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.