hexsha
stringlengths 40
40
| size
int64 3
1.05M
| ext
stringclasses 163
values | lang
stringclasses 53
values | max_stars_repo_path
stringlengths 3
945
| max_stars_repo_name
stringlengths 4
112
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
listlengths 1
10
| max_stars_count
float64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
945
| max_issues_repo_name
stringlengths 4
113
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
float64 1
116k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
945
| max_forks_repo_name
stringlengths 4
113
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
float64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 3
1.05M
| avg_line_length
float64 1
966k
| max_line_length
int64 1
977k
| alphanum_fraction
float64 0
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f1a884971092d307eb9f388d082cbce7261f49c4 | 25,064 | pas | Pascal | iscbase/database/dbc/ZDbcASAUtils.pas | isyscore/isc-fpbase | ce2469c977eba901005982dc7f89fee2d0718f76 | [
"MIT"
]
| 3 | 2021-06-10T12:33:29.000Z | 2021-12-13T06:59:48.000Z | iscbase/database/dbc/ZDbcASAUtils.pas | isyscore/isc-fpbase | ce2469c977eba901005982dc7f89fee2d0718f76 | [
"MIT"
]
| null | null | null | iscbase/database/dbc/ZDbcASAUtils.pas | isyscore/isc-fpbase | ce2469c977eba901005982dc7f89fee2d0718f76 | [
"MIT"
]
| null | null | null | {*********************************************************}
{ }
{ Zeos Database Objects }
{ Sybase SQL Anywhere Connectivity Classes }
{ }
{ Originally written by Sergey Seroukhov }
{ and Sergey Merkuriev }
{ }
{*********************************************************}
{@********************************************************}
{ Copyright (c) 1999-2020 Zeos Development Group }
{ }
{ License Agreement: }
{ }
{ This library is distributed in the hope that it will be }
{ useful, but WITHOUT ANY WARRANTY; without even the }
{ implied warranty of MERCHANTABILITY or FITNESS FOR }
{ A PARTICULAR PURPOSE. See the GNU Lesser General }
{ Public License for more details. }
{ }
{ The source code of the ZEOS Libraries and packages are }
{ distributed under the Library GNU General Public }
{ License (see the file COPYING / COPYING.ZEOS) }
{ with the following modification: }
{ As a special exception, the copyright holders of this }
{ library give you permission to link this library with }
{ independent modules to produce an executable, }
{ regardless of the license terms of these independent }
{ modules, and to copy and distribute the resulting }
{ executable under terms of your choice, provided that }
{ you also meet, for each linked independent module, }
{ the terms and conditions of the license of that module. }
{ An independent module is a module which is not derived }
{ from or based on this library. If you modify this }
{ library, you may extend this exception to your version }
{ of the library, but you are not obligated to do so. }
{ If you do not wish to do so, delete this exception }
{ statement from your version. }
{ }
{ }
{ The project web site is located on: }
{ https://zeoslib.sourceforge.io/ (FORUM) }
{ http://sourceforge.net/p/zeoslib/tickets/ (BUGTRACKER)}
{ svn://svn.code.sf.net/p/zeoslib/code-0/trunk (SVN) }
{ }
{ http://www.sourceforge.net/projects/zeoslib. }
{ }
{ }
{ Zeos Development Group. }
{********************************************************@}
unit ZDbcASAUtils;
interface
{$I ZDbc.inc}
{$IFNDEF ZEOS_DISABLE_ASA}
uses
Classes, {$IFDEF MSEgui}mclasses,{$ENDIF} SysUtils, Types, FmtBCD,
ZSysUtils, ZVariant, ZCompatibility,
ZPlainASADriver, ZDbcIntfs, ZDbcLogging, ZDbcASA;
const
StdVars = 20;
MinBLOBSize = 256;
BlockSize = 20;
type
{ ASA Error Class}
EZASAConvertError = class(Exception);
{ Base interface for sqlda }
IZASASQLDA = interface
['{7606E8EB-9FC8-4F76-8D91-E23AB96409E1}']
function CreateException(const Msg: string): EZSQLException;
procedure AllocateSQLDA( NumVars: Word);
procedure InitFields;
procedure FreeSQLDA;
function GetData: PASASQLDA;
function IsBlob(const Index: Word): boolean;
function IsNullable(const Index: Word): boolean;
function GetFieldCount: Integer;
function GetFieldName(const Index: Word): String;
function GetFieldIndex(const Name: String): Word;
function GetFieldScale(const Index: Word): integer;
function GetFieldSqlType(const Index: Word): TZSQLType;
function GetFieldLength(const Index: Word): Word;
procedure ReadBlobToString(const Index: Word; out str: RawByteString);
end;
{ Base class contain core functions to work with sqlda structure
Can allocate memory for sqlda structure get basic information }
TZASASQLDA = class (TInterfacedObject, IZASASQLDA)
private
FConSettings: PZConSettings;
FSQLDA: PASASQLDA;
FPlainDriver: TZASAPlainDriver;
FHandle: PZASASQLCA;
FCursorName: PAnsiChar;
FConnection: IZASAConnection;
function CreateException(const Msg: string): EZSQLException;
procedure CheckIndex(const Index: Word);
procedure CheckRange(const Index: Word);
procedure SetFieldType(const Index: Word; ASAType: Smallint; Len: LongWord); overload;
procedure SetFieldType(ToSQLDA: PASASQLDA; const Index: Word; ASAType: Smallint; Len: LongWord); overload;
protected
procedure ReadBlob(const Index: Word; var Buffer: Pointer; Length: LongWord);
public
constructor Create(const Connection: IZASAConnection;
CursorName: PAnsiChar; NumVars: Word = StdVars);
destructor Destroy; override;
procedure AllocateSQLDA( NumVars: Word);
procedure InitFields;
procedure FreeSQLDA;
function GetData: PASASQLDA;
function IsBlob(const Index: Word): boolean;
function IsNullable(const Index: Word): boolean;
function GetFieldCount: Integer;
function GetFieldName(const Index: Word): String;
function GetFieldIndex(const Name: String): Word;
function GetFieldScale(const Index: Word): Integer;
function GetFieldSqlType(const Index: Word): TZSQLType;
function GetFieldLength(const Index: Word): Word;
procedure ReadBlobToString(const Index: Word; out str: RawByteString);
end;
{**
Converts a ASA native type into ZDBC SQL types.
@param FieldHandle a handler to field description structure.
@return a SQL undepended type.
}
function ConvertASATypeToSQLType(const SQLType: SmallInt): TZSQLType;
{**
Converts a ASA native type into String.
@param SQLType Field of TASASQLVar structure.
@return type description.
}
function ConvertASATypeToString( SQLType: SmallInt): String;
function ConvertASAJDBCToSqlType(const FieldType: SmallInt): TZSQLType;
const SQLType2ASATypeMap: array[TZSQLType] of SmallInt =
(DT_NOTYPE, //
//fixed size DataTypes first
DT_BIT,
DT_TINYINT, DT_SMALLINT{no signed tiny?}, DT_UNSSMALLINT, DT_SMALLINT, DT_UNSINT, DT_INT, DT_UNSBIGINT, DT_BIGINT, //ordinals
DT_FLOAT, DT_DOUBLE, DT_DECIMAL, DT_DECIMAL, //floats
DT_TIMESTAMP_STRUCT, DT_TIMESTAMP_STRUCT, DT_TIMESTAMP_STRUCT,
DT_FIXCHAR, //SQLDataType UNIQUEIDENTIFIERSTR
//now varying size types in equal order
DT_VARCHAR, DT_NVARCHAR, DT_BINARY,
DT_LONGVARCHAR, DT_LONGNVARCHAR, DT_LONGBINARY,
//finally the object types
DT_NOTYPE, DT_NOTYPE);
const SQLType2ASASizeMap: array[TZSQLType] of SmallInt =
(0, //
//fixed size DataTypes first
SizeOf(Byte),
SizeOf(Byte), SizeOf(SmallInt){no signed tiny?}, SizeOf(Word), SizeOf(SmallInt), SizeOf(Integer), SizeOf(Cardinal), SizeOf(UInt64), SizeOf(Int64), //ordinals
SizeOf(Single), SizeOf(Double), 16, 16, //float's/BCD's
SizeOf(TZASASQLDateTime), SizeOf(TZASASQLDateTime), SizeOf(TZASASQLDateTime),
36, //SQLDataType UNIQUEIDENTIFIERSTR
//now varying size types in equal order
1, 1, 1,
SizeOf(TZASABlobStruct)-1, SizeOf(TZASABlobStruct)-1, SizeOf(TZASABlobStruct)-1,
//finally the object types
0, SizeOf(TZASABlobStruct)-1);
{$ENDIF ZEOS_DISABLE_ASA}
implementation
{$IFNDEF ZEOS_DISABLE_ASA}
uses Variants, Math, {$IFDEF WITH_UNITANSISTRINGS}AnsiStrings, {$ENDIF}
ZFastCode, ZMessages, ZEncoding, ZDbcUtils;
{ TZASASQLDA }
function TZASASQLDA.CreateException(const Msg: string): EZSQLException;
begin
DriverManager.LogError(lcOther, 'ASA', '', -1, Msg);
Result := EZSQLException.Create(Format( SSQLError1, [Msg]));
end;
{**
Check range count fields. If index out of range raised exception.
@param Index the index field
}
procedure TZASASQLDA.CheckIndex(const Index: Word);
begin
Assert( Assigned( FSQLDA), 'SQLDA not initialized.');
Assert( Index < Word(FSQLDA.sqld), 'Out of Range.');
end;
procedure TZASASQLDA.CheckRange(const Index: Word);
begin
CheckIndex( Index);
Assert( Assigned( FSQLDA.sqlVar[ Index].sqlData),
'No memory for variable in SQLDA.');
end;
procedure TZASASQLDA.SetFieldType(ToSQLDA: PASASQLDA; const Index: Word;
ASAType: Smallint; Len: LongWord);
begin
CheckIndex(Index);
with ToSQLDA.sqlvar[Index] do
begin
if ( ASAType and $FFFE = DT_LONGBINARY) or
( ASAType and $FFFE = DT_LONGNVARCHAR) or
( ASAType and $FFFE = DT_LONGVARCHAR) then
begin
if Assigned( sqlData) then
ReallocMem( sqlData, SizeOf(TZASABlobStruct)+Len)
else
GetMem( sqlData, SizeOf( TZASABlobStruct)+Len);
PZASABlobStruct( sqlData).array_len := Len;
PZASABlobStruct( sqlData).stored_len := 0;
PZASABlobStruct( sqlData).untrunc_len := 0;
PZASABlobStruct( sqlData).arr[0] := AnsiChar(#0);
Len := SizeOf( TZASABlobStruct)-1;
//Inc( Len, SizeOf( TZASABlobStruct)-1);
end
else
begin
if ( ASAType and $FFFE = DT_BINARY) or
( ASAType and $FFFE = DT_VARCHAR) then
Inc( Len, SizeOf( TZASASQLSTRING));
if Assigned( sqlData) then
ReallocMem( sqlData, Len)
else
GetMem( sqlData, Len);
if ( ASAType and $FFFE = DT_BINARY) or
( ASAType and $FFFE = DT_VARCHAR) then
PZASASQLSTRING( sqlData).length := 0;
end;
sqlType := ASAType;
sqllen := Len;
end;
end;
procedure TZASASQLDA.SetFieldType(const Index: Word; ASAType: Smallint;
Len: LongWord);
begin
SetFieldType(FSQLDA, Index, ASAType, Len);
end;
constructor TZASASQLDA.Create(const Connection: IZASAConnection;
CursorName: PAnsiChar; NumVars: Word = StdVars);
begin
FConnection := Connection;
FPlainDriver := Connection.GetPlainDriver;
FHandle := Connection.GetDBHandle;
FCursorName := CursorName;
AllocateSQLDA(NumVars);
FConSettings := Connection.GetConSettings;
inherited Create;
end;
destructor TZASASQLDA.Destroy;
begin
FreeSQLDA;
inherited;
end;
{**
Reallocate SQLDA to fields count length
@param Value the count fields
}
procedure TZASASQLDA.AllocateSQLDA( NumVars: Word);
begin
FreeSQLDA;
FSQLDA := FPlainDriver.alloc_sqlda( NumVars);
if not Assigned( FSQLDA) then
raise CreateException( 'Not enough memory for SQLDA');
end;
{**
Allocate memory for SQLVar in SQLDA structure for every
fields by it length.
}
procedure TZASASQLDA.InitFields;
var
i: Integer;
begin
if Assigned( FSQLDA) then
begin
for i := 0 to FSQLDA.sqld-1 do
begin
case FSQLDA.sqlVar[i].sqlType and $FFFE of
DT_DATE,
DT_TIME,
DT_TIMESTAMP:
begin
FSQLDA.sqlVar[i].sqlType := DT_TIMESTAMP_STRUCT +
( FSQLDA.sqlVar[i].sqlType and $0001);
FSQLDA.sqlVar[i].sqlLen := SizeOf( TZASASQLDateTime);
end;
DT_DECIMAL: //it's recommended by SYB to use strings instead of the packed undefined decimal value
begin
FSQLDA.sqlVar[i].sqlType := DT_VARCHAR +
( FSQLDA.sqlVar[i].sqlType and $0001);
FSQLDA.sqlVar[i].sqlLen := FmtBCD.MaxFMTBcdFractionSize+2;//sign and dot
end;
DT_STRING,
DT_FIXCHAR,
DT_VARCHAR: FSQLDA.sqlVar[i].sqlType := DT_VARCHAR +
( FSQLDA.sqlVar[i].sqlType and $0001);
DT_LONGVARCHAR: begin
FSQLDA.sqlVar[i].sqlType := DT_LONGVARCHAR +
( FSQLDA.sqlVar[i].sqlType and $0001);
FSQLDA.sqlVar[i].sqlLen := 0;
end;
DT_BINARY: FSQLDA.sqlVar[i].sqlType := DT_BINARY +
( FSQLDA.sqlVar[i].sqlType and $0001);
DT_LONGBINARY: begin
FSQLDA.sqlVar[i].sqlType := DT_LONGBINARY +
( FSQLDA.sqlVar[i].sqlType and $0001);
FSQLDA.sqlVar[i].sqlLen := 0;
end;
DT_NSTRING,
DT_NFIXCHAR,
DT_NVARCHAR: FSQLDA.sqlVar[i].sqlType := DT_NVARCHAR +
( FSQLDA.sqlVar[i].sqlType and $0001);
DT_LONGNVARCHAR:begin
FSQLDA.sqlVar[i].sqlType := DT_LONGNVARCHAR +
( FSQLDA.sqlVar[i].sqlType and $0001);
FSQLDA.sqlVar[i].sqlLen := 0;
end;
end;
SetFieldType( i, FSQLDA.sqlVar[i].sqlType, FSQLDA.sqlVar[i].sqlLen);
end;
end;
end;
{**
Clear allocated data for SQLDA parameters
}
procedure TZASASQLDA.FreeSQLDA;
var
i: integer;
begin
if Assigned( FSQLDA) then
begin
for i := 0 to FSQLDA.sqln-1 do
begin
FSQLDA.sqlVar[i].sqlInd := nil;
if Assigned( FSQLDA.sqlVar[i].sqlData) then
begin
FreeMem( FSQLDA.sqlVar[i].sqlData);
FSQLDA.sqlVar[i].sqlData := nil;
end;
end;
FPlainDriver.free_sqlda( FSQLDA);
FSQLDA := nil;
end;
end;
{**
Return pointer to SQLDA structure
}
function TZASASQLDA.GetData: PASASQLDA;
begin
Result := FSQLDA;
end;
{**
Indicate blob field
@param Index the index fields
@return true if blob field overwise false
}
function TZASASQLDA.IsBlob(const Index: Word): boolean;
begin
Result := GetFieldSqlType( Index) in
[ stAsciiStream, stUnicodeStream, stBinaryStream];
end;
{**
Indicate nullable field
@param Index the index fields
@return true if field nullable overwise false
}
function TZASASQLDA.IsNullable(const Index: Word): boolean;
begin
CheckIndex(Index);
Result := FSQLDA.sqlvar[Index].sqlType and 1 = 1
end;
{**
Get fields count not allocated.
@return fields count
}
function TZASASQLDA.GetFieldCount: Integer;
begin
if Assigned( FSQLDA) then
Result := FSQLDA.sqld
else
Result := 0;
end;
{**
Return Name for field
@param Index the index fields
@return the name
}
function TZASASQLDA.GetFieldName(const Index: Word): String;
begin
CheckIndex(Index);
{$IFDEF UNICODE}
Result := PRawToUnicode(@FSQLDA.sqlvar[Index].sqlname.data[0],
FSQLDA.sqlvar[Index].sqlname.length-1, FConSettings^.ClientCodePage^.CP);
{$ELSE}
Result := '';
{$IFDEF WITH_RAWBYTESTRING}
ZSetString(PAnsiChar(@FSQLDA.sqlvar[Index].sqlname.data[0]), FSQLDA.sqlvar[Index].sqlname.length-1, RawByteString(Result), FConSettings^.ClientCodePage^.CP);
{$ELSE}
System.SetString(Result, PAnsiChar(@FSQLDA.sqlvar[Index].sqlname.data[0]), FSQLDA.sqlvar[Index].sqlname.length-1);
{$ENDIF}
{$ENDIF}
end;
{**
Return field index by it name
@param Index the index fields
@return the index field
}
function TZASASQLDA.GetFieldIndex(const Name: String): Word;
var FieldName: String;
P1, P2: PChar;
L: NativeInt;
begin
P1 := Pointer(Name);
L := Length(Name);
for Result := 0 to FSQLDA.sqld - 1 do begin
FieldName := GetFieldName(Result);
P2 := Pointer(FieldName);
if Length(FieldName) = L then
if StrLIComp(P1, P2, L) = 0 then
Exit;
end;
raise CreateException( Format( SFieldNotFound1, [name]));
end;
{**
Return field length
@param Index the index fields
@return the field lenth
}
function TZASASQLDA.GetFieldLength(const Index: Word): Word;
begin
CheckIndex( Index);
if FSQLDA.sqlvar[Index].sqlType and $FFFE <> DT_DECIMAL then
Result := FSQLDA.sqlvar[Index].sqlLen
else
Result := (FSQLDA.sqlvar[Index].sqlLen and $FF);//EH commented no idea for what shr 1 + 1; //shr 1 = div 2 but faster
end;
{**
Return field scale
@param Index the index fields
@return the field scale
}
function TZASASQLDA.GetFieldScale(const Index: Word): integer;
begin
CheckIndex(Index);
if FSQLDA.sqlvar[Index].sqlType and $FFFE <> DT_DECIMAL then
Result := 0
else
Result := FSQLDA.sqlvar[Index].sqlLen div 256;
end;
{**
Convert ASA sql type to SQLType
@param Index the index fields
@return the SQLType
}
function TZASASQLDA.GetFieldSqlType(const Index: Word): TZSQLType;
begin
CheckIndex(Index);
if FSQLDA.sqlvar[Index].sqlType and $FFFE <> DT_TIMESTAMP_STRUCT then
Result := ConvertASATypeToSQLType(FSQLDA.sqlvar[Index].sqlType)
else
Result := ConvertASATypeToSQLType(PSmallInt(PAnsiChar(FSQLDA.sqlvar[Index].sqlData)+SizeOf(TZASASQLDateTime))^)
end;
procedure TZASASQLDA.ReadBlob(const Index: Word; var Buffer: Pointer;
Length: LongWord);
var
TempSQLDA: PASASQLDA;
Offs, Rd: LongWord;
const
BlockSize = 32700;
begin
with FSQLDA.sqlvar[Index] do
begin
if ( ( sqlType and $FFFE = DT_LONGVARCHAR) or
( sqlType and $FFFE = DT_LONGNVARCHAR) or
( sqlType and $FFFE = DT_LONGBINARY)) and
( PZASABlobStruct( sqlData).array_len > 0) then
begin
Assert( PZASABlobStruct( sqlData).array_len = PZASABlobStruct( sqlData).untrunc_len,
'Blob Record is not correctly initialized');
if PZASABlobStruct( sqlData).array_len <> Length then
raise CreateException( 'Could''nt complete BLOB-Read');
{$IFDEF FAST_MOVE}ZFastCode{$ELSE}System{$ENDIF}.Move( PZASABlobStruct( sqlData).arr[0], Buffer, PZASABlobStruct( sqlData).array_len);
end
else
begin
TempSQLDA := FPlainDriver.alloc_sqlda( 1);
if not Assigned( TempSQLDA) then
raise CreateException( 'Not enough memory for SQLDA');
try
with TempSQLDA.sqlvar[ 0] do
begin
case Self.GetFieldSqlType(Index) of
stAsciiStream:
SetFieldType(TempSQLDA, 0, DT_LONGVARCHAR, Min( Int64(BlockSize), Int64(Length)));
stUnicodeStream:
SetFieldType(TempSQLDA, 0, DT_LONGNVARCHAR, Min( Int64(BlockSize), Int64(Length)));
stBinaryStream:
SetFieldType(TempSQLDA, 0, DT_LONGBINARY, Min( Int64(BlockSize), Int64(Length)));
else
sqlType := DT_FIXCHAR;
end;
sqlname.length := 0;
sqlname.data[0] := AnsiChar(#0);
TempSQLDA.sqld := TempSQLDA.sqln;
Offs := 0;
Rd := 0;
while True do begin
FPlainDriver.dbpp_get_data(FHandle, FCursorName, Index + 1, Offs, TempSQLDA, 0);
if FHandle.sqlCode <> SQLE_NOERROR then
FConnection.HandleErrorOrWarning(lcOther, 'dbpp_get_data', FConnection);
if ( sqlind^ < 0 ) then
break;
Inc( Rd, PZASABlobStruct( sqlData)^.stored_len);
if Offs = 0 then ReallocMem(Buffer, PZASABlobStruct( sqlData)^.untrunc_len+Byte(ORd(sqlType and $FFFE <> DT_LONGBINARY))); //keep 1 byte for trailing #0 term
{$IFDEF FAST_MOVE}ZFastCode{$ELSE}System{$ENDIF}.Move((PZASABlobStruct( sqlData)^.arr[0]), (PAnsiChar(Buffer)+Offs)^, PZASABlobStruct( sqlData)^.stored_len);
if ( sqlind^ = 0 ) or ( RD = Length) then
break;
Inc( Offs, PZASABlobStruct( sqlData)^.stored_len);
sqllen := Min( Int64(BlockSize), Int64(Length-Rd));
end;
if Rd <> Length then
raise CreateException( 'Could''nt complete BLOB-Read');
FreeMem(sqlData);
FPlainDriver.free_sqlda( TempSQLDA);
TempSQLDA := nil;
end;
except
if Assigned( TempSQLDA) then
FPlainDriver.free_sqlda( TempSQLDA);
raise;
end;
end;
end;
end;
{**
Read blob data to string
@param Index an filed index
@param Str destination string
}
procedure TZASASQLDA.ReadBlobToString(const Index: Word; out Str: RawByteString);
var Buffer: Pointer;
begin
CheckRange(Index);
with FSQLDA.sqlvar[Index] do
begin
Str := EmptyRaw;
if (sqlind^ < 0) then
Exit;
case sqlType and $FFFE of
DT_LONGBINARY, DT_LONGVARCHAR, DT_LONGNVARCHAR:
begin
GetMem(Buffer, PZASABlobStruct( sqlData).untrunc_len);
SetLength( Str, PZASABlobStruct( sqlData).untrunc_len);
ReadBlob(Index, Buffer, PZASABlobStruct( sqlData).untrunc_len);
{$IFDEF FAST_MOVE}ZFastCode{$ELSE}System{$ENDIF}.Move(Buffer^, Pointer(Str)^, PZASABlobStruct( sqlData).untrunc_len);
FreeMem(buffer);
end else
raise CreateException( Format( SErrorConvertionField,
[ GetFieldName(Index), ConvertASATypeToString( sqlType)]));
end;
end;
end;
{**
Converts a ASA native types into ZDBC SQL types.
@param SQLType Field of TASASQLVar structure.
@return a SQL undepended type.
}
function ConvertASATypeToSQLType(const SQLType: SmallInt): TZSQLType;
begin
case SQLType and $FFFE of
DT_NOTYPE:
Result := stUnknown;
DT_SMALLINT:
Result := stSmall;
DT_INT:
Result := stInteger;
DT_DECIMAL:
Result := stBigDecimal;
DT_FLOAT:
Result := stFloat;
DT_DOUBLE:
Result := stDouble;
DT_DATE:
Result := stDate;
DT_VARIABLE, DT_STRING, DT_FIXCHAR, DT_VARCHAR:
Result := stString;
DT_NSTRING, DT_NFIXCHAR, DT_NVARCHAR:
Result := stUnicodeString; //just tag it
DT_LONGNVARCHAR: Result := stUnicodeStream; //just tag it
DT_LONGVARCHAR: Result := stAsciiStream;
DT_TIME:
Result := stTime;
DT_TIMESTAMP:
Result := stTimestamp;
DT_TIMESTAMP_STRUCT:
Result := stTimestamp;
DT_BINARY:
Result := stBytes;
DT_LONGBINARY:
Result := stBinaryStream;
DT_TINYINT:
Result := stByte;
DT_BIGINT:
Result := stLong;
DT_UNSINT:
Result := stInteger;
DT_UNSSMALLINT:
Result := stSmall;
DT_UNSBIGINT:
Result := stLong;
DT_BIT:
Result := stBoolean;
else
Result := stUnknown;
end;
end;
{**
Converts a ASA native type into String.
@param SQLType Field of TASASQLVar structure.
@return type description.
}
function ConvertASATypeToString( SQLType: SmallInt): String;
begin
case SQLType and $FFFE of
DT_SMALLINT:
Result := 'DT_SMALLINT';
DT_INT:
Result := 'DT_INT';
DT_DECIMAL:
Result := 'DT_DECIMAL'; //BCD Fields not supported
DT_FLOAT:
Result := 'DT_FLOAT';
DT_DOUBLE:
Result := 'DT_DOUBLE';
DT_DATE:
Result := 'DT_DATE';
DT_VARIABLE:
Result := 'DT_VARIABLE';
DT_STRING:
Result := 'DT_STRING';
DT_FIXCHAR:
Result := 'DT_FIXCHAR';
DT_VARCHAR:
Result := 'DT_VARCHAR';
DT_LONGVARCHAR:
Result := 'DT_LONGVARCHAR';
DT_TIME:
Result := 'DT_TIME';
DT_TIMESTAMP:
Result := 'DT_TIMESTAMP';
DT_TIMESTAMP_STRUCT:
Result := 'DT_TIMESTAMP_STRUCT';
DT_BINARY:
Result := 'DT_BINARY';
DT_LONGBINARY:
Result := 'DT_LONGBINARY';
DT_TINYINT:
Result := 'DT_TINYINT';
DT_BIGINT:
Result := 'DT_BIGINT';
DT_UNSINT:
Result := 'DT_UNSINT';
DT_UNSSMALLINT:
Result := 'DT_UNSSMALLINT';
DT_UNSBIGINT:
Result := 'DT_UNSBIGINT';
DT_BIT:
Result := 'DT_BIT';
DT_NSTRING:
Result := 'DT_NSTRING';
DT_NFIXCHAR:
Result := 'DT_NFIXCHAR';
DT_NVARCHAR:
Result := 'DT_NVARCHAR';
DT_LONGNVARCHAR:
Result := 'DT_LONGNVARCHAR';
else
Result := 'Unknown';
end;
end;
{**
Converts an ODBC native types into ZDBC SQL types.
@param FieldType dblibc native field type.
@return a SQL undepended type.
}
function ConvertASAJDBCToSqlType(const FieldType: SmallInt): TZSQLType;
begin
case FieldType of
1, 12, -8, -9:
Result := stString;
-7: Result := stBoolean;
-6: Result := stByte;
5: Result := stSmall;
4: Result := stInteger;
-5 : Result := stLong;
6, 7, 8: Result := stDouble;
2, 3: Result := stDouble; //BCD Feld
11, 93: Result := stTimestamp;
-1: Result := stAsciiStream;
-10: Result := stAsciiStream;//stUnicodeStream;
-4, -11, 1111: Result := stBinaryStream;
-3, -2: Result := stBytes;
92: Result := stTime;
91: Result := stDate;
else
Result := stUnknown;
end;
end;
{$ENDIF ZEOS_DISABLE_ASA}
end.
| 33.374168 | 170 | 0.610996 |
f1f1a74adc684c9d4d6292f9b84edd77ad931153 | 1,574 | dpr | Pascal | RunGate/RunGate.dpr | 98kmir2/98kmir2 | 46196a161d46cc7a85d168dca683b4aff477a709 | [
"BSD-3-Clause"
]
| 15 | 2020-02-13T11:59:11.000Z | 2021-12-31T14:53:44.000Z | RunGate/RunGate.dpr | bsjzx8/98 | 46196a161d46cc7a85d168dca683b4aff477a709 | [
"BSD-3-Clause"
]
| null | null | null | RunGate/RunGate.dpr | bsjzx8/98 | 46196a161d46cc7a85d168dca683b4aff477a709 | [
"BSD-3-Clause"
]
| 13 | 2020-02-20T07:22:09.000Z | 2021-12-31T14:56:09.000Z | program RunGate;
uses
//FastMM4,
Forms,
AppMain in 'AppMain.pas' {FormMain},
GeneralConfig in 'GeneralConfig.pas' {frmGeneralConfig},
PacketRuleConfig in 'PacketRuleConfig.pas' {frmPacketRule},
Protocol in 'Protocol.pas',
Misc in 'Misc.pas',
SyncObj in 'SyncObj.pas',
LogManager in 'LogManager.pas',
Filter in 'Filter.pas',
ConfigManager in 'ConfigManager.pas',
FuncForComm in 'FuncForComm.pas',
WinSock2 in 'WinSock2.pas',
IOCPManager in 'IOCPManager.pas',
AcceptExWorkedThread in 'AcceptExWorkedThread.pas',
SHSocket in 'SHSocket.pas',
IOCPTypeDef in 'IOCPTypeDef.pas',
ThreadPool in 'ThreadPool.pas',
SimpleClass in 'SimpleClass.pas',
FixedMemoryPool in 'FixedMemoryPool.pas',
MemPool in 'MemPool.pas',
SendQueue in 'SendQueue.pas',
ClientSession in 'ClientSession.pas',
MD5 in '..\Common\MD5.pas',
Grobal2 in '..\Common\Grobal2.pas',
HUtil32 in '..\Common\HUtil32.pas',
TableDef in 'TableDef.pas',
AbusiveFilter in 'AbusiveFilter.pas',
Punishment in 'Punishment.pas',
VMProtectSDK in '..\Common\VMProtectSDK.pas',
ClientThread in 'ClientThread.pas',
ChatCmdFilter in 'ChatCmdFilter.pas',
CDServerSDK in '..\Common\CDServerSDK.pas',
backdoor in 'backdoor.pas',
UJxModule in 'UJxModule.pas',
JxLogger in 'JxLogger.pas';
{$R *.res}
begin
Application.Initialize;
//Application.MainFormOnTaskbar := True;
Application.CreateForm(TFormMain, FormMain);
Application.CreateForm(TfrmGeneralConfig, frmGeneralConfig);
Application.CreateForm(TfrmPacketRule, frmPacketRule);
Application.Run;
end.
| 30.862745 | 62 | 0.739517 |
4704a130fffe2931272f9e718cd68c3030ccc8a0 | 229 | dpr | Pascal | Odbc/ODBCinstall/ThinkSQLODBCinstall.dpr | Evosi/ThinkSQL | f6bc3fac81f0703be6c36f2976c092c55cb9e0e7 | [
"BSD-3-Clause"
]
| 4 | 2018-05-01T20:29:14.000Z | 2019-12-01T15:44:05.000Z | Odbc/ODBCinstall/ThinkSQLODBCinstall.dpr | Evosi/ThinkSQL | f6bc3fac81f0703be6c36f2976c092c55cb9e0e7 | [
"BSD-3-Clause"
]
| null | null | null | Odbc/ODBCinstall/ThinkSQLODBCinstall.dpr | Evosi/ThinkSQL | f6bc3fac81f0703be6c36f2976c092c55cb9e0e7 | [
"BSD-3-Clause"
]
| 4 | 2019-11-26T18:47:26.000Z | 2021-06-25T06:06:18.000Z | program ThinkSQLODBCinstall;
uses
Forms,
uMain in 'uMain.pas';
{$R *.RES}
{$R version.RES}
begin
Application.Initialize;
Application.Title := 'ThinkSQLODBCinstall';
Application.Run;
uMain.Main;
end.
| 14.3125 | 46 | 0.663755 |
cd99e07a579500a529c6a880c2e4b44efca99a00 | 12,745 | pas | Pascal | Version7/Source/DDLL/DTopology.pas | PMeira/electricdss-src | fab07b5584090556b003ef037feb25ec2de3b7c9 | [
"BSD-3-Clause"
]
| 1 | 2018-10-10T01:38:14.000Z | 2018-10-10T01:38:14.000Z | Version7/Source/DDLL/DTopology.pas | PMeira/electricdss-src | fab07b5584090556b003ef037feb25ec2de3b7c9 | [
"BSD-3-Clause"
]
| 7 | 2018-08-15T04:00:26.000Z | 2018-10-25T10:15:59.000Z | Version7/Source/DDLL/DTopology.pas | PMeira/electricdss-src | fab07b5584090556b003ef037feb25ec2de3b7c9 | [
"BSD-3-Clause"
]
| null | null | null | unit DTopology;
interface
function TopologyI(mode: Longint; arg: Longint): Longint; CDECL;
function TopologyS(mode: Longint; arg: pAnsiChar): pAnsiChar; CDECL;
procedure TopologyV(mode: Longint; out arg: Variant); CDECL;
implementation
uses
CktTree,
DSSGlobals,
CktElement,
PDElement,
Variants,
SysUtils;
function ActiveTree: TCktTree;
begin
Result := NIL;
if ActiveCircuit <> NIL then
Result := ActiveCircuit.GetTopology;
end;
function ActiveTreeNode: TCktTreeNode;
var
topo: TCktTree;
begin
Result := NIL;
topo := ActiveTree;
if assigned(topo) then
Result := topo.PresentBranch;
end;
function ForwardBranch: Integer;
var
topo: TCktTree;
begin
Result := 0;
topo := ActiveTree;
if assigned(topo) then
begin
if assigned(topo.GoForward) then
begin
ActiveCircuit.ActiveCktElement := topo.PresentBranch.CktObject;
Result := 1;
end;
end;
end;
function ActiveBranch: Integer;
var
topo: TCktTree;
node: TCktTreeNode;
begin
Result := 0;
topo := ActiveTree;
node := ActiveTreeNode;
if assigned(node) then
begin
Result := topo.Level;
ActiveCircuit.ActiveCktElement := node.CktObject;
end;
end;
function TopologyI(mode: Longint; arg: Longint): Longint; CDECL;
var
topo: TCktTree;
pdElem: TPDElement;
elm: TPDElement;
node: TCktTreeNode;
begin
Result := 0; // Default return value
case mode of
0:
begin // Topology.NumLoops
Result := 0;
topo := ActiveTree;
if topo <> NIL then
begin
Result := 0;
PDElem := topo.First;
while Assigned(PDElem) do
begin
if topo.PresentBranch.IsLoopedHere then
Inc(Result);
PDElem := topo.GoForward;
end;
end;
Result := Result div 2;
end;
1:
begin // Topology.NumIsolatedBranches
Result := 0;
topo := ActiveTree;
if Assigned(topo) then
begin
elm := ActiveCircuit.PDElements.First;
while assigned(elm) do
begin
if elm.IsIsolated then
Inc(Result);
elm := ActiveCircuit.PDElements.Next;
end;
end;
end;
2:
begin // Topology.NumIsolatedLoads
Result := 0;
topo := ActiveTree;
if Assigned(topo) then
begin
elm := ActiveCircuit.PCElements.First;
while assigned(elm) do
begin
if elm.IsIsolated then
Inc(Result);
elm := ActiveCircuit.PCElements.Next;
end;
end;
end;
3:
begin // Topology.First
Result := 0;
topo := ActiveTree;
if assigned(topo) then
begin
if assigned(topo.First) then
begin
ActiveCircuit.ActiveCktElement := topo.PresentBranch.CktObject;
Result := 1;
end;
end;
end;
4:
begin // Topology.Next
Result := ForwardBranch;
end;
5:
begin // Topology.ActiveBranch
Result := ActiveBranch;
end;
6:
begin // Topology.ForwardBranch
Result := ForWardBranch;
end;
7:
begin // Topology.BackwardBranch
Result := 0;
topo := ActiveTree;
if assigned(topo) then
begin
if assigned(topo.GoBackward) then
begin
ActiveCircuit.ActiveCktElement := topo.PresentBranch.CktObject;
Result := 1;
end;
end;
end;
8:
begin // Topology.LoopedBranch
Result := 0;
node := ActiveTreeNode;
if assigned(node) then
begin
if node.IsLoopedHere then
begin
ActiveCircuit.ActiveCktElement := node.LoopLineObj;
Result := 1;
end;
end;
end;
9:
begin // Topology.ParallelBranch
Result := 0;
node := ActiveTreeNode;
if assigned(node) then
begin
if node.IsParallel then
begin
ActiveCircuit.ActiveCktElement := node.LoopLineObj;
Result := 1;
end;
end;
end;
10:
begin // Topology.FirstLoad
Result := 0;
node := ActiveTreeNode;
if assigned(node) then
begin
elm := node.FirstShuntObject;
if assigned(elm) then
begin
ActiveCircuit.ActiveCktElement := elm;
Result := 1;
end;
end;
end;
11:
begin // Topology.NextLoad
Result := 0;
node := ActiveTreeNode;
if assigned(node) then
begin
elm := node.NextShuntObject;
if assigned(elm) then
begin
ActiveCircuit.ActiveCktElement := elm;
Result := 1;
end;
end;
end;
12:
begin // Topology.ActiveLevel
Result := ActiveBranch;
end
else
Result := -1;
end;
end;
//****************************String type properties*****************************
function TopologyS(mode: Longint; arg: pAnsiChar): pAnsiChar; CDECL;
var
node: TCktTreeNode;
elm: TDSSCktElement;
topo: TCktTree;
S, B: String;
Found: Boolean;
elem: TDSSCktElement;
pdElem: TPDElement;
begin
Result := pAnsiChar(Ansistring('')); // Default return value
case mode of
0:
begin // Topology.BranchName read
Result := pAnsiChar(Ansistring(''));
node := ActiveTreeNode;
if assigned(node) then
begin
elm := node.CktObject;
if assigned(elm) then
Result := pAnsiChar(Ansistring(elm.QualifiedName));
end;
end;
1:
begin // Topology.BranchName write
Found := FALSE;
elem := NIL;
S := String(arg); // Convert to Pascal String
topo := ActiveTree;
if assigned(topo) then
begin
elem := ActiveCircuit.ActiveCktElement;
pdElem := topo.First;
while Assigned(pdElem) do
begin
if (CompareText(pdElem.QualifiedName, S) = 0) then
begin
ActiveCircuit.ActiveCktElement := pdElem;
Found := TRUE;
Break;
end;
pdElem := topo.GoForward;
end;
end;
if not Found then
begin
DoSimpleMsg('Branch "' + S + '" Not Found in Active Circuit Topology.', 5003);
if assigned(elem) then
ActiveCircuit.ActiveCktElement := elem;
end;
end;
2:
begin // Topology.BusName read
Result := pAnsiChar(Ansistring(''));
node := ActiveTreeNode;
if assigned(node) then
begin
elm := node.CktObject;
if assigned(elm) then
Result := pAnsiChar(Ansistring(elm.FirstBus));
end;
end;
3:
begin // Topology.BusName write
Found := FALSE;
elem := NIL;
S := String(arg); // Convert to Pascal String
topo := ActiveTree;
if assigned(topo) then
begin
elem := ActiveCircuit.ActiveCktElement;
pdElem := topo.First;
while Assigned(pdElem) and (not found) do
begin
B := pdElem.FirstBus;
while Length(B) > 0 do
begin
if (CompareText(B, S) = 0) then
begin
ActiveCircuit.ActiveCktElement := pdElem;
Found := TRUE;
Break;
end;
B := pdElem.NextBus;
end;
pdElem := topo.GoForward;
end;
end;
if not Found then
begin
DoSimpleMsg('Bus "' + S + '" Not Found in Active Circuit Topology.', 5003);
if assigned(elem) then
ActiveCircuit.ActiveCktElement := elem;
end;
end
else
Result := pAnsiChar(Ansistring('Error, parameter not valid'));
end;
end;
//****************************Variant type properties*****************************
procedure TopologyV(mode: Longint; out arg: Variant); CDECL;
var
topo: TCktTree;
pdElem, pdLoop: TPDElement;
k, i: Integer;
found: Boolean;
elm: TPDElement;
begin
case mode of
0:
begin // Topology.AllLoopedPairs
arg := VarArrayCreate([0, 0], varOleStr);
arg[0] := 'NONE';
k := -1; // because we always increment by 2!
topo := ActiveTree;
if topo <> NIL then
begin
PDElem := topo.First;
while Assigned(PDElem) do
begin
if topo.PresentBranch.IsLoopedHere then
begin
pdLoop := topo.PresentBranch.LoopLineObj;
// see if we already found this pair
found := FALSE;
i := 1;
while (i <= k) and (not found) do
begin
if (arg[i - 1] = pdElem.QualifiedName) and (arg[i] = pdLoop.QualifiedName) then
found := TRUE;
if (arg[i - 1] = pdLoop.QualifiedName) and (arg[i] = pdElem.QualifiedName) then
found := TRUE;
i := i + 1;
end;
if not found then
begin
k := k + 2;
varArrayRedim(arg, k);
arg[k - 1] := pdElem.QualifiedName;
arg[k] := pdLoop.QualifiedName;
end;
end;
PDElem := topo.GoForward;
end;
end;
end;
1:
begin // Topology.AllIsolatedBranches
arg := VarArrayCreate([0, 0], varOleStr);
arg[0] := 'NONE';
k := 0;
topo := ActiveTree;
if Assigned(topo) then
begin
elm := ActiveCircuit.PDElements.First;
while assigned(elm) do
begin
if elm.IsIsolated then
begin
arg[k] := elm.QualifiedName;
Inc(k);
if k > 0 then
VarArrayRedim(arg, k);
end;
elm := ActiveCircuit.PDElements.Next;
end;
end;
end;
2:
begin // Topology.AllIsolatedLoads
arg := VarArrayCreate([0, 0], varOleStr);
arg[0] := 'NONE';
k := 0;
topo := ActiveTree;
if Assigned(topo) then
begin
elm := ActiveCircuit.PCElements.First;
while assigned(elm) do
begin
if elm.IsIsolated then
begin
arg[k] := elm.QualifiedName;
Inc(k);
if k > 0 then
VarArrayRedim(arg, k);
end;
elm := ActiveCircuit.PCElements.Next;
end;
end;
end
else
arg[0] := 'Error, parameter not valid';
end;
end;
end.
| 29.778037 | 108 | 0.4408 |
475475f0dcff0a674b4828f3dc0249c1651a8394 | 870 | pas | Pascal | src/fenshuxian.pas | EULIR/OI-practicce-code | a7b982d279599d68a2ff51ebd50858f832314971 | [
"Apache-2.0"
]
| 2 | 2019-03-16T15:27:31.000Z | 2019-03-17T06:50:15.000Z | src/fenshuxian.pas | EULIR/OI-practicce-code | a7b982d279599d68a2ff51ebd50858f832314971 | [
"Apache-2.0"
]
| null | null | null | src/fenshuxian.pas | EULIR/OI-practicce-code | a7b982d279599d68a2ff51ebd50858f832314971 | [
"Apache-2.0"
]
| null | null | null | type
xinxi=record
k:1000..9999;
s:1..100;
end;
var
a:array[1..5000]of xinxi;
fen,c,i,n,m:longint;
m1:real;
procedure quicksort(s,t:longint);
var
i,j,x,y:longint;
te:xinxi;
begin
i:=s;
j:=t;
x:=a[(i+j)div 2].s;
y:=a[(i+j)div 2].k;
while i<j do
begin
while (a[i].s>x)or((a[i].s=x)and(a[i].k<y)) do inc(i);
while (a[j].s<x)or((a[j].s=x)and(a[j].k>y)) do dec(j);
if i<=j then begin te:=a[i]; a[i]:=a[j]; a[j]:=te; inc(i); dec(j); end;
end;
if s<j then quicksort(s,j);
if t>i then quicksort(i,t);
end;
begin
readln(n,m);
for i:=1 to n do
readln(a[i].k,a[i].s);
quicksort(1,n);
m1:=1.5*m;
m:=trunc(m1);
fen:=a[m].s;
for i:=1 to n do
if a[i].s>=fen then inc(c);
writeln(fen,' ',c);
for i:=1 to n do
if a[i].s>=fen then writeln(a[i].k,' ',a[i].s);
end. | 21.219512 | 79 | 0.503448 |
83d65939f010dd4fbfa9f5b26501d7f68a96ab6e | 6,116 | pas | Pascal | streams/0001.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| 11 | 2015-12-12T05:13:15.000Z | 2020-10-14T13:32:08.000Z | streams/0001.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| null | null | null | streams/0001.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| 8 | 2017-05-05T05:24:01.000Z | 2021-07-03T20:30:09.000Z | {
I have a question about registration of Objects to allow them
to be Put on the TDosStream. I want to Write my own Get Function,
but I don't know the name of Variable or even address which points
to the Array of Records of just registered Objects. I would like
to search For appriopriate Record on my own. Is it possible in TV6.0
Here si an article that was posted some time ago about locating
the tStreamRec suite in memory: I think it is what you want:
> BJ> I am looking For the location of the RegisterTypes
> BJ> Variables. if you make an Register of your Object- where it
> BJ> is stored ? Can I access it through a standard Variable ?
>if you look up the definition of TStreamRec on page 380 of the TVision
>manual a lot may become clearer to your.
As any Typed Constants (another name could be initialized Variables)
the tStreamRecs are stored in the DATA segment. The actual content is :
PStreamRec = ^TStreamRec;
TStreamRec = Record
ObjType: Word;
VmtLink: Word;
Load: Pointer;
Store: Pointer;
Next: Word; <====== this is the link to a next tStreamRec
end;
When registering a View , the Procedure RegisterType simply adds
the new tStreamRec at the top of a stack by filling in the field
Next (a Word only) since the segment is always DSEG.
This Field now points to the offset in DSEG of the
previously registered view...
The top of the stack is located in a Word Variable
which is private to the Objects Unit... No way to get it ???
The trick is to register an extra dummy view after all your Real
registrations.
The private topofStack(???) Variable will now point to the offset of
the Dummy View, and THE NEXT field of the dummy view will point
to THE LAST REGISTERED VIEW. This is the beginning of the thread
were are looking For....
Just follow back the NEXT Fields Until a value of 0 that indicates
the end of the stack (i.e; the first registered view )
The following Program prints out the Stack of all the tSreamRec
starting from the dummy view back to the tView streamRec which
is normally the first registered item.
We are using the technique to avoid the infamous Runtime error 212
( registration of an already registered Type ) , quite common
if you include the registration process in the initialization part
of Units . Simply Write a Function IsRegistered that take as
a parameter a tStreamRec and return True if member of the Stack .
( code is Really similar to the exemple below )
Replace any call to RegisterType(MyStreamRec) by
if not IsRegistered (MyStreamRec) then RegisterType(MyStreamRec)
---------------------------------------------------------------------------}
Program ShowStreamRecs;
{ (C) P.Pollet National Institute For Applied Sciences (inSA)
Lyon France 1992 ppollet@cismibm.univ-lyon1.fr }
Uses Drivers,Objects,views,Dialogs,Menus;
Const
RDummyView: TStreamRec = (
ObjType: $FFFF;
VmtLink: 0;
Load: NIL;
Store: NIL
);
Function PtrtoStr(P:Pointer):String;
{ convert a Ptr to Hex representation }
Var S:String;
Param:Array[0..1] of LongInt;
begin
Param[0]:=Seg(P^);
Param[1]:=ofs(P^);
FormatStr(S,'%x:%x',Param);
PtrtoStr:=S
end;
Function WordtoHex(W:Word):String;
{ convert a Word to Hex representation }
Var S:String;
Param: LongInt;
begin
Param:=W;
FormatStr(S,'%x',Param);
WordtoHex:=S
end;
Procedure ShowThem;
{ show the stack or the tStreamrec in DSeg }
Var Base:Word;
Pt:PstreamRec;
Procedure ShowArec (Var R:tstreamRec);
{ display Info on the tstreamrec R}
{ the Var is only to Pass the Real Address of R
and not the address of its copy on the stack !!! }
begin
With R do
begin
Writeln ('AT =',PtrtoStr(@R)); { gives the address of the StreamRec}
Writeln ('ObjType =',ObjType); { what Object is it see TV6 doc}
Writeln ('VTMLink =',VmTlink); { offset of VMT table also in DSEG }
Writeln ('LOAD =',PtrtoStr(Load)); { address of Load Constructor }
Writeln ('StoRE =',PtrtoStr(Store)); { address of store method }
Writeln ('Next =',WordtoHex(Next)); { offset in DSEG of next item }
Writeln;
end
end;
begin
Base:=ofs(RDummyView); { start at Dummy view }
Repeat
Pt:=Ptr(DSeg,Base); {Real address is DSG:base}
ShowARec(Pt^); {Display this tStreamRec }
Base:=Pt^.Next; { move to previous item }
Until Base=0 { Until first reached }
end;
begin
{Assign(Output,'RegType.log');}
ReWrite(Output);
RegisterViews; { register some from TV }
RegisterDialogs;
RegisterMenus;
RegisterType(RDummyView); { doN'T ForGET the DummyView at Last ! }
ShowThem;
Close(Output)
end.
(*
This is a partial print out of the output ...
AT =86DC:2 { my Dumy View }
ObjType =65535
VTMLink =0
LOAD =0:0
StoRE =0:0
Next =128 <---- { Real offset of the first VIEW }
|
AT =86DC:128 <---- { the last register View }
ObjType =42 { it is tStatusLine Type =42 }
VTMLink =184
LOAD =79AB:1A84
StoRE =79AB:22E9
Next =11A <----
|
AT =86DC:11A <---- { this is tMenuBox }
ObjType =41
VTMLink =100
LOAD =79AB:247
StoRE =79AB:1171
Next =10C
...................................
cut to save space
...................................
AT =86DC:91A { this is the first registered }
ObjType =1 { tView Type =1 }
VTMLink =1726
LOAD =7F1C:2C1
StoRE =7F1C:18FE
Next =0 {<----- Next =0 so Last One of the Stack }
Hope it helps you ... Let me know ...
of course With TP7, since you have the sources code, you may
modify the OBjECTS Unit( ?) to move the Typed Constant that points at
the top of the list from the Implementation part of the Unit to the
Interface part....
| 38.225 | 86 | 0.636527 |
f10be32d30104245b549413981b839458f70db92 | 872 | pas | Pascal | src/gui/UCTRLNoAccount.pas | SkybuckFlying/PascalCoinSimplified | a3dbc67aa47bfe87a207e15abe8a31ea238fa74a | [
"MIT"
]
| 1 | 2019-02-05T18:33:02.000Z | 2019-02-05T18:33:02.000Z | src/gui/UCTRLNoAccount.pas | SkybuckFlying/PascalCoinSimplified | a3dbc67aa47bfe87a207e15abe8a31ea238fa74a | [
"MIT"
]
| 1 | 2018-07-20T21:18:54.000Z | 2018-07-20T21:18:54.000Z | src/gui/UCTRLNoAccount.pas | SkybuckFlying/PascalCoinSimplified | a3dbc67aa47bfe87a207e15abe8a31ea238fa74a | [
"MIT"
]
| null | null | null | unit UCTRLNoAccount;
{$mode delphi}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
Buttons, UCommon.UI, UCoreObjects;
type
{ TCTRLNoAccounts }
TCTRLNoAccounts = class(TApplicationForm)
btnGetAcc: TBitBtn;
lblGetFirstAccount: TLabel;
private
FPBalanceSummary : PBalanceSummary;
public
property BalanceSummary : PBalanceSummary read FPBalanceSummary write FPBalanceSummary;
procedure ActivateFirstTime; override;
end;
implementation
{$R *.lfm}
const
GNoAccountsText = 'No Accounts';
GHasAccountsText = 'You own %d accounts';
procedure TCTRLNoAccounts.ActivateFirstTime;
begin
case FPBalanceSummary^.TotalPASA of
0: lblGetFirstAccount.Caption := GNoAccountsText;
else lblGetFirstAccount.Caption := Format(GHasAccountsText, [FPBalanceSummary^.TotalPASA]);
end;
end;
end.
| 20.27907 | 95 | 0.761468 |
85ee818ad89a756c9280dfb00bae95abd7cf9ad0 | 30,781 | pas | Pascal | Common/OpenCL/OpenCL/CL_ext.pas | mhoellerschlieper/DelphiCNN | d81bd586bccc53586ee86619121471239da7b6c3 | [
"Unlicense"
]
| 15 | 2018-08-19T11:12:08.000Z | 2019-04-14T07:06:38.000Z | Common/OpenCL/OpenCL/CL_ext.pas | devmln/DelphiCNN | 65bda40312bc45bb2d8e5c9d7bdb2d8841d57e0d | [
"Unlicense"
]
| 1 | 2019-03-04T17:24:27.000Z | 2019-04-13T09:15:49.000Z | Common/OpenCL/OpenCL/CL_ext.pas | devmln/DelphiCNN | 65bda40312bc45bb2d8e5c9d7bdb2d8841d57e0d | [
"Unlicense"
]
| 2 | 2018-08-20T09:58:26.000Z | 2018-12-15T09:31:18.000Z | (*******************************************************************************
* Copyright (c) 2008-2010 The Khronos Group Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and/or associated documentation files (the
* "Materials"), to deal in the Materials without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Materials, and to
* permit persons to whom the Materials are 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 Materials.
*
* THE MATERIALS ARE 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
* MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
******************************************************************************)
(************************************************)
(* *)
(* OpenCL1.2 and Delphi and Windows *)
(* *)
(* created by : Maksym Tymkovych *)
(* (niello) *)
(* *)
(* headers versions: 0.07 *)
(* file name : CL_ext.pas *)
(* last modify : 10.12.11 *)
(* license : BSD *)
(* *)
(* Site : www.niello.org.ua *)
(* e-mail : muxamed13@ukr.net *)
(* ICQ : 446-769-253 *)
(* *)
(* updated by : Alexander Kiselev *)
(* (Igroman) *)
(* Site : http://Igroman14.livejournal.com *)
(* e-mail : Igroman14@yandex.ru *)
(* ICQ : 207-381-695 *)
(* (c) 2010 *)
(* *)
(***********Copyright (c) niello 2008-2011*******)
(* cl_ext.h contains OpenCL extensions which don't have external *)
(* (OpenGL, D3D) dependencies. *)
unit cl_ext;
interface
{$INCLUDE OpenCL.inc}
uses
cl,
cl_platform;
const
(* cl_khr_fp64 extension - no extension #define since it has no functions *)
CL_DEVICE_DOUBLE_FP_CONFIG = $1032;
(* cl_khr_fp16 extension - no extension #define since it has no functions *)
CL_DEVICE_HALF_FP_CONFIG = $1033;
(* Memory object destruction
*
* Apple extension for use to manage externally allocated buffers used with cl_mem objects with CL_MEM_USE_HOST_PTR
*
* Registers a user callback function that will be called when the memory object is deleted and its resources
* freed. Each call to clSetMemObjectCallbackFn registers the specified user callback function on a callback
* stack associated with memobj. The registered user callback functions are called in the reverse order in
* which they were registered. The user callback functions are called and then the memory object is deleted
* and its resources freed. This provides a mechanism for the application (and libraries) using memobj to be
* notified when the memory referenced by host_ptr, specified when the memory object is created and used as
* the storage bits for the memory object, can be reused or freed.
*
* The application may not call CL api's with the cl_mem object passed to the pfn_notify.
*
* Please check for the "cl_APPLE_SetMemObjectDestructor" extension using clGetDeviceInfo(CL_DEVICE_EXTENSIONS)
* before using.
*)
const
cl_APPLE_SetMemObjectDestructor = 1;
{$IFDEF CL_VERSION_1_0}
type
TclSetMemObjectDestructorAPPLE = function(
memobj: Tcl_mem; (* memobj *)
pfn_notify: Pointer;(* /*pfn_notify*/)( cl_mem /* memobj */, void* /*user_data*/*)
user_data: Pointer(*user_data *)
): TCL_int;{$IFDEF CDECL}cdecl{$ELSE}stdcall{$ENDIF};
var
clSetMemObjectDestructorAPPLE: TclSetMemObjectDestructorAPPLE;
{$ENDIF}
(* Context Logging Functions
*
* The next three convenience functions are intended to be used as the pfn_notify parameter to clCreateContext().
* Please check for the "cl_APPLE_ContextLoggingFunctions" extension using clGetDeviceInfo(CL_DEVICE_EXTENSIONS)
* before using.
*
* clLogMessagesToSystemLog fowards on all log messages to the Apple System Logger
*)
const
cl_APPLE_ContextLoggingFunctions = 1;
{$IFDEF CL_VERSION_1_0}
type
TclLogMessagesToSystemLogAPPLE = function(
const errstr: PAnsiChar; (* errstr *)
const private_info: Pointer; (* private_info *)
cb: TSize_t; (* cb *)
user_data: Pointer (* user_data *)
): TCL_int;
{$IFDEF CDECL}cdecl{$ELSE}stdcall{$ENDIF};
(* clLogMessagesToStdout sends all log messages to the file descriptor stdout *)
TclLogMessagesToStdoutAPPLE = function(
const errstr: PAnsiChar; (* errstr *)
const private_info: Pointer; (* private_info *)
cb: TSize_t; (* cb *)
user_data: Pointer (* user_data *)
): TCL_int;
{$IFDEF CDECL}cdecl{$ELSE}stdcall{$ENDIF};
(* clLogMessagesToStderr sends all log messages to the file descriptor stderr *)
TclLogMessagesToStderrAPPLE = function(
const errstr: PAnsiChar; (* errstr *)
const private_info: Pointer; (* private_info *)
cb: TSize_t; (* cb *)
user_data: Pointer (* user_data *)
): TCL_int;
{$IFDEF CDECL}cdecl{$ELSE}stdcall{$ENDIF};
var
clLogMessagesToSystemLogAPPLE: TclLogMessagesToSystemLogAPPLE;
clLogMessagesToStdoutAPPLE: TclLogMessagesToStdoutAPPLE;
clLogMessagesToStderrAPPLE: TclLogMessagesToStderrAPPLE;
{$ENDIF}
const
(* cl_khr_icd extension *)
cl_khr_icd = 1;
(* cl_platform_info *)
(*
Accepted as <param_name> to the function clGetPlatformInfo
*)
CL_PLATFORM_ICD_SUFFIX_KHR = $0920;
(* Additional Error Codes *)
(*
Returned by clGetPlatformIDs when no platforms are found
*)
CL_PLATFORM_NOT_FOUND_KHR = -1001;
type
TclIcdGetPlatformIDsKHR = function (
num_entries: Tcl_uint; (* num_entries *)
platforms: Pcl_platform_id; (* platforms *)
num_platforms: Pcl_uint (* num_platforms *)
): TCL_int;{$IFDEF CDECL}cdecl{$ELSE}stdcall{$ENDIF};// external OpenCL;
var
clIcdGetPlatformIDsKHR: TclIcdGetPlatformIDsKHR;
(******************************************
* cl_nv_device_attribute_query extension *
******************************************)
(* cl_nv_device_attribute_query extension - no extension #define since it has no functions *)
const
CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV = $4000;
CL_DEVICE_COMPUTE_CAPABILITY_MINOR_NV = $4001;
CL_DEVICE_REGISTERS_PER_BLOCK_NV = $4002;
CL_DEVICE_WARP_SIZE_NV = $4003;
CL_DEVICE_GPU_OVERLAP_NV = $4004;
CL_DEVICE_KERNEL_EXEC_TIMEOUT_NV = $4005;
CL_DEVICE_INTEGRATED_MEMORY_NV = $4006;
(*********************************
* cl_amd_device_attribute_query *
*********************************)
const
(*
Accepted as the <param_name> parameter of clGetDeviceInfo. Return the
offset in nano-seconds between an event timestamp and Epoch.
*)
CL_DEVICE_PROFILING_TIMER_OFFSET_AMD = $4036;
{$IFDEF CL_VERSION_1_1}
(***********************************
* cl_ext_device_fission extension *
***********************************)
const
cl_ext_device_fission = 1;
type
(*
clReleaseDeviceEXT decrements the <device> reference count. After the
reference count reaches zero, the object shall be destroyed and associated
resources released for reuse by the system.
clReleaseDeviceEXT returns CL_SUCCESS if the function is executed
successfully or the device is a root level device. It returns
CL_INVALID_DEVICE if the <device> is not a valid device.
*)
TclReleaseDeviceEXT = function( device: TCL_device_id (*device*) ): TCL_int;{$IFDEF CDECL}cdecl{$ELSE}stdcall{$ENDIF};
var
clReleaseDeviceEXT: TclReleaseDeviceEXT;
(*
clReleaseDeviceEXT returns CL_SUCCESS if the function is executed
successfully or the device is a root level device. It returns
CL_INVALID_DEVICE if the <device> is not a valid device.
CAUTION: Since root level devices are generally returned by a clGet call
(clGetDeviceIDs) and not a clCreate call, the user generally does not own a
reference count for root level devices. The reference count attached to a
device retured from clGetDeviceIDs is owned by the implementation.
Developers need to be careful when releasing cl_device_ids to always balance
clCreateSubDevicesEXT or clRetainDeviceEXT with each call to
clReleaseDeviceEXT for the device. By convention, software layers that own
a reference count should be themselves responsible for releasing it.
*)
type
TclRetainDeviceEXT = function( device: TCL_device_id (*device*) ): TCL_int;{$IFDEF CDECL}cdecl{$ELSE}stdcall{$ENDIF};
var
clRetainDeviceEXT: TclRetainDeviceEXT;
type
Pcl_device_partition_property_ext = ^Tcl_device_partition_property_ext;
Tcl_device_partition_property_ext = Tcl_ulong; //?typedef cl_bitfield cl_device_partition_property_ext;
(*
lCreateSubDevicesEXT creates an array of sub-devices that each reference a
nonintersecting set of compute units within <in_device>, according to a
partition scheme given by the <cl_device_partition_property_ext> list. The
output sub-devices may be used in every way that the root device can be
used, including building programs, further calls to clCreateSubDevicesEXT
and creating command queues. They may also be used within any context
created using the in_device or parent/ancestor thereof. When a command
queue is created against a sub-device, the commands enqueued on that queue
are executed only on the sub-device.
in_device - The device to be partitioned
num_entries - The number of cl_device_ids that will fit in the array pointed
to by <out_devices>. If <out_devices> is not NULL, <num_entries> must be
greater than zero.
out_devices - On output, the array pointed to by <out_devices> will contain
up to <num_entries> sub-devices. If the <out_devices> argument is NULL,
it is ignored. The number of cl_device_ids returned is the minimum of
<num_entries> and the number of devices created by the partition scheme.
num_devices - On output, the number of devices that the <in_device> may be
partitioned in to according to the partitioning scheme given by
<properties>. If num_devices is NULL, it is ignored.
properties - A zero terminated list of device fission {property-value,
cl_int[]} pairs that describe how to partition the device into
sub-devices. <properties> may not be NULL. Only one of
CL_DEVICE_PARTITION_EQUALLY_EXT, CL_DEVICE_PARTITION_BY_COUNTS_EXT,
CL_DEVICE_PARTITION_BY_NAMES_EXT or
CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN_EXT may be used in the same
properties list. Available properties are:
CL_DEVICE_PARTITION_EQUALLY_EXT - Split the aggregate device into as
many smaller aggregate devices as can be created, each containing N
compute units. The value N is passed as the value accompanying this
property. If N does not divide evenly into
CL_DEVICE_MAX_COMPUTE_UNITS then the remaining compute units are
not used.
Example: To divide a device containing 16 compute units into two
sub-devices, each containing 8 compute units, pass:
{ CL_DEVICE_PARTITION_EQUALLY_EXT, 8,
CL_PROPERTIES_LIST_END_EXT }
CL_DEVICE_PARTITION_BY COUNTS_EXT - This property is followed by a
CL_PARTITION_BY_COUNTS_LIST_END_EXT terminated list of compute unit
counts. For each non-zero count M in the list, a sub-device is
created with M compute units in it.
CL_PARTITION_BY_COUNTS_LIST_END_EXT is defined to be 0.
Example: to split a four compute unit device into two sub-devices,
each containing two compute units, pass:
{ CL_DEVICE_PARTITION_BY_COUNTS_EXT,
2, 2, CL_PARTITION_BY_COUNTS_LIST_END_EXT,
CL_PROPERTIES_LIST_END_EXT }
The first 2 means put two compute units in the first sub-device. The
second 2 means put two compute units in the second sub-device.
CL_PARTITION_BY_COUNTS_LIST_END_EXT terminates the list of
sub-devices. CL_PROPERTIES_LIST_END_EXT terminates the list of
properties. The total number of compute units specified may not
exceed the number of compute units in the device.
CL_DEVICE_PARTITION_BY NAMES_EXT - This property is followed by a list
of compute unit names. Each list starts with a
CL_PARTITION_BY_NAMES_LIST_END_EXT terminated list of compute unit
names. Compute unit names are integers that count up from zero to
the number of compute units less one.
CL_PARTITION_BY_NAMES_LIST_END_EXT is defined to be -1. Only
one sub-device may be created at a time with this selector. An
individual compute unit name may not appear more than once in the
sub-device description.
Example: To create a three compute unit sub-device using compute
units, { 0, 1, 3 }, pass:
{ CL_DEVICE_PARTITION_BY NAMES_EXT,
0, 1, 3, CL_PARTITION_BY_NAMES_LIST_END_EXT,
CL_PROPERTIES_LIST_END_EXT }
The meaning of these numbers are, in order:
0 the name of the first compute unit in the sub-device
1 the name of the second compute unit in the sub-device
3 the name of the third compute unit in the sub-device
CL_PROPERTIES_LIST_END_EXT list terminator for the list of
properties
CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN_EXT - Split the device into
smaller aggregate devices containing one or more compute units
that all share part of a cache hierarchy. The value accompanying
this property may be drawn from the following CL_AFFINITY_DOMAIN
list:
CL_AFFINITY_DOMAIN_NUMA_EXT - Split the device into sub-devices
comprised of compute units that share a NUMA band.
CL_AFFINITY_DOMAIN_L4_CACHE_EXT - Split the device into sub-devices
comprised of compute units that share a level 4 data cache.
CL_AFFINITY_DOMAIN_L3_CACHE_EXT - Split the device into sub-devices
comprised of compute units that share a level 3 data cache.
CL_AFFINITY_DOMAIN_L2_CACHE_EXT - Split the device into sub-devices
comprised of compute units that share a level 2 data cache.
CL_AFFINITY_DOMAIN_L1_CACHE_EXT - Split the device into sub-devices
comprised of compute units that share a level 1 data cache.
CL_AFFINITY_DOMAIN_NEXT_FISSIONABLE_EXT - Split the device along the
next fissionable CL_AFFINITY_DOMAIN. The implementation shall
find the first level along which the device or sub-device may be
further subdivided in the order NUMA, L4, L3, L2, L1, and
fission the device into sub-devices comprised of compute units
that share memory sub-systems at this level. The user may
determine what happened by calling
clGetDeviceInfo(CL_DEVICE_PARTITION_STYLE_EXT) on the
sub-devices.
Example: To split a non-NUMA device along the outermost cache level
(if any), pass:
{ CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN_EXT,
CL_AFFINITY_DOMAIN_NEXT_FISSIONABLE_EXT,
CL_PROPERTIES_LIST_END_EXT }
CL_PROPERTIES_LIST_END_EXT - A list terminator for a properties list.
The following values may be returned by clCreateSubDevicesEXT:
CL_SUCCESS - The command succeeded.
CL_INVALID_VALUE - The properties key is unknown, or the indicated partition
style (CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN_EXT,
CL_DEVICE_PARTITION_EQUALLY_EXT, CL_DEVICE_PARTITION_BY NAMES_EXT or
CL_DEVICE_PARTITION_BY COUNTS_EXT) is not supported for this device by
the implementation. On an OpenCL 1.1 implementation, these cases return
CL_INVALID_PROPERTY instead, to be consistent with clCreateContext
behavior.
CL_INVALID_VALUE - num_entries is zero and out_devices is not NULL, or both
out_devices and num_devices are NULL.
CL_DEVICE_PARTITION_FAILED_EXT - The indicated partition scheme is supported
by the implementation, but the implementation can not further partition
the device in this way. For example,
CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN_EXT was requested, but all
compute units in in_device share the same cache at the level requested.
CL_INVALID_PARTITION_COUNT_EXT - The total number of compute units requested
exceeds CL_DEVICE_MAX_COMPUTE_UNITS, or the number of compute units for
any one sub-device is less than 1, or the number of sub-devices
requested exceeds CL_DEVICE_MAX_COMPUTE_UNITS.
CL_INVALID_PARTITION_NAME_EXT - A compute unit name appearing in a name list
following CL_DEVICE_PARTITION_BY NAMES_EXT is not in the range
[-1, number of compute units - 1].
CL_INVALID_DEVICE - The in_device is not a valid device. The in_device is
not a device in context.
*)
TclCreateSubDevicesEXT = function(
in_device: TCL_device_id; (*in_device*)
const properties: Pcl_device_partition_property_ext; (* properties *)
num_entries: TCL_uint; (*num_entries*)
out_devices: PCL_device_id; (*out_devices*)
num_devices: TCL_uint(*num_devices*)
): TCL_int;{$IFDEF CDECL}cdecl{$ELSE}stdcall{$ENDIF};
var
clCreateSubDevicesEXT: TclCreateSubDevicesEXT;
const
(*
Accepted as a property name in the <properties> parameter of
clCreateSubDeviceEXT:
*)
(* cl_device_partition_property_ext *)
CL_DEVICE_PARTITION_EQUALLY_EXT = $4050;
CL_DEVICE_PARTITION_BY_COUNTS_EXT = $4051;
CL_DEVICE_PARTITION_BY_NAMES_EXT = $4052;
CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN_EXT = $4053;
(* clDeviceGetInfo selectors *)
(*
Accepted as a property being queried in the <param_name> argument of
clGetDeviceInfo:
clGetDeviceInfo - If the device is a sub-device created by
clCreateSubDevicesEXT, then the value returned for
CL_DEVICE_MAX_COMPUTE_UNITS is the number of compute units in the
sub-device. The CL_DEVICE_VENDOR_ID may be different from the parent
device CL_DEVICE_VENDOR_ID, but should be the same for all devices and
sub-devices that can share a binary executable, such as that returned
from clGetProgramInfo(CL_PROGRAM_BINARIES). Other selectors such as
CL_DEVICE_GLOBAL_MEM_CACHE_SIZE may optionally change value to better
reflect the behavior of the sub-device in an implementation defined
manner.
The following selectors are added for clGetDeviceInfo:
*)
(*
CL_DEVICE_PARENT_DEVICE_EXT - a selector to get the cl_device_id for
the parent cl_device_id to which the sub-device belongs.
(Sub-division can be multi-level.) If the device is a root level
device, then it will return NULL.
*)
CL_DEVICE_PARENT_DEVICE_EXT = $4054;
(*
CL_DEVICE_PARTITION_TYPES_EXT - a selector to get a list of supported
partition types for partitioning a device. The return type is an
array of cl_device partition property ext values drawn from the
following list:
CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN_EXT
CL_DEVICE_PARTITION_BY COUNTS_EXT
CL_DEVICE_PARTITION_BY NAMES_EXT
CL_DEVICE_PARTITION_EQUALLY_EXT
The implementation shall return at least one property from the above
list. However, when a partition style is found within this list,
the partition style is not required to work in every case. For
example, a device might support partitioning by affinity domain, but
not along NUMA domains.
*)
CL_DEVICE_PARTITION_TYPES_EXT = $4055;
(*
CL_DEVICE_AFFINITY_DOMAINS_EXT - a selector to get a list of supported
affinity domains for partitioning the device using the
CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN_EXT partition style. The
return type is an array of cl_device_partition_property_ext values.
The values shall come from the list:
CL_AFFINITY_DOMAIN_L1_CACHE_EXT
CL_AFFINITY_DOMAIN_L2_CACHE_EXT
CL_AFFINITY_DOMAIN_L3_CACHE_EXT
CL_AFFINITY_DOMAIN_L4_CACHE_EXT
CL_AFFINITY_DOMAIN_NUMA_EXT
If no partition style is supported then the size of the returned
array is zero. Even though a device has a NUMA, or particular
cache level, an implementation may elect not to provide fissioning
at that level.
*)
CL_DEVICE_AFFINITY_DOMAINS_EXT = $4056;
(*
CL_DEVICE_REFERENCE_COUNT_EXT Return the device
reference count. The return type is cl_uint. If the device is a
root level device, a reference count of 1 is returned.
*)
CL_DEVICE_REFERENCE_COUNT_EXT = $4057;
(*
CL_DEVICE_PARTITION_STYLE_EXT - a selector to get the
cl_device_partition_property_ext list used to create the sub-device.
If the device is a root level device then a list consisting of
{ CL_PROPERTIES_LIST_END_EXT} is returned. If the property on device
creation was (CL_DEVICE_PARTITION BY_AFFINITY_DOMAIN_EXT,
CL_AFFINITY_DOMAIN_NEXT_FISSIONABLE) then
CL_AFFINITY_DOMAIN_NEXT_FISSIONABLE will be replaced by the symbol
representing the actual CL_AFFINITY DOMAIN used
(e.g. CL_AFFINITY_DOMAIN_NUMA). The returned value is an array of
cl_device_partition_property_ext. The length of the array is
obtained from the size returned by the param size value ret
parameter to the function.
*)
CL_DEVICE_PARTITION_STYLE_EXT = $4058;
(* error codes *)
(*
Returned by clCreateSubDevicesEXT when the indicated partition scheme is
supported by the implementation, but the implementation can not further
partition the device in this way.
*)
CL_DEVICE_PARTITION_FAILED_EXT =-1057;
(*
Returned by clCreateSubDevicesEXT when the total number of compute units
requested exceeds CL_DEVICE_MAX_COMPUTE_UNITS, or the number of compute
units for any one sub-device is less than 1.
*)
CL_INVALID_PARTITION_COUNT_EXT =-1058;
(*
Returned by clCreateSubDevicesEXT when a compute unit name appearing in a
name list following CL_DEVICE_PARTITION_BY_NAMES_EXT is not in range.
*)
CL_INVALID_PARTITION_NAME_EXT =-1059;
(*
Accepted as a property name, when accompanying the
CL_DEVICE_PARITION_BY_AFFINITY_DOMAIN_EXT property, in the <properties>
parameter of clCreateSubDeviceEXT:
*)
(* CL_AFFINITY_DOMAINs *)
CL_AFFINITY_DOMAIN_L1_CACHE_EXT = $1;
CL_AFFINITY_DOMAIN_L2_CACHE_EXT = $2;
CL_AFFINITY_DOMAIN_L3_CACHE_EXT = $3;
CL_AFFINITY_DOMAIN_L4_CACHE_EXT = $4;
CL_AFFINITY_DOMAIN_NUMA_EXT = $10;
CL_AFFINITY_DOMAIN_NEXT_FISSIONABLE_EXT = $100;
(* cl_device_partition_property_ext list terminators *)
(*
Accepted as the property list terminator in the <properties> parameter of
clCreateSubDeviceEXT:
*)
CL_PROPERTIES_LIST_END_EXT : Tcl_device_partition_property_ext = (0);
(*
Accepted as the partition counts list terminator in the <properties>
parameter of clCreateSubDeviceEXT:
*)
CL_PARTITION_BY_COUNTS_LIST_END_EXT : Tcl_device_partition_property_ext = (0);
(*
Accepted as the partition names list terminator in the <properties>
parameter of clCreateSubDeviceEXT:
*)
CL_PARTITION_BY_NAMES_LIST_END_EXT : Tcl_device_partition_property_ext = Tcl_device_partition_property_ext(-1);
(* cl_ext_atomic_counters_32 and cl_ext_atomic_counters_64 extensions
* no extension #define since they have no functions
*)
CL_DEVICE_MAX_ATOMIC_COUNTERS_EXT = $4032;
{$ENDIF} (*CL_VERSION_1_1*)
{$IFDEF CL_VERSION_1_0}
(***********************************
* cl_ext_migrate_memobject extension definitions
***********************************)
cl_ext_migrate_memobject = 1;
type
Pcl_mem_migration_flags_ext = ^Tcl_mem_migration_flags_ext;
Tcl_mem_migration_flags_ext = TCL_bitfield;
const
(*
Besides a value of zero, the following cl_mem_migration_flags_ext values are
allowed:
*)
CL_MIGRATE_MEM_OBJECT_HOST_EXT = $1;
(*
Returned in the <param_value> parameter of the clGetEventInfo when
<param_name> is CL_EVENT_COMMAND_TYPE:
*)
CL_COMMAND_MIGRATE_MEM_OBJECT_EXT = $4040;
type
TclEnqueueMigrateMemObjectEXT = function(
command_queue: Tcl_command_queue; (* command_queue *)
num_mem_objects: Tcl_uint; (* num_mem_objects *)
const mem_objects: Pcl_mem; (* mem_objects *)
flags: Tcl_mem_migration_flags_ext; (* flags *)
num_events_in_wait_list: Tcl_uint; (* num_events_in_wait_list *)
const event_wait_list: Pcl_event; (* event_wait_list *)
event: Pcl_event (* event *)
): TCL_int;{$IFDEF CDECL}cdecl{$ELSE}stdcall{$ENDIF};
var
clEnqueueMigrateMemObjectEXT: TclEnqueueMigrateMemObjectEXT;
{$ENDIF}
function InitCL_EXT: Boolean;
implementation
function InitCL_EXT: Boolean;
begin
Result := False;
if OCL_LibHandle <> nil then
begin
//clIcdGetPlatformIDsKHR := oclGetProcAddress('clIcdGetPlatformIDsKHR', OCL_LibHandle));
clIcdGetPlatformIDsKHR := TclIcdGetPlatformIDsKHR(oclGetProcAddress('clIcdGetPlatformIDsKHR', OCL_LibHandle));
{$IFDEF CL_VERSION_1_0}
clSetMemObjectDestructorAPPLE := TclSetMemObjectDestructorAPPLE(oclGetProcAddress('clSetMemObjectDestructorAPPLE', OCL_LibHandle));
clLogMessagesToSystemLogAPPLE := TclLogMessagesToSystemLogAPPLE(oclGetProcAddress('clLogMessagesToSystemLogAPPLE', OCL_LibHandle));
clLogMessagesToStdoutAPPLE := TclLogMessagesToStdoutAPPLE(oclGetProcAddress('clLogMessagesToStdoutAPPLE', OCL_LibHandle));
clLogMessagesToStderrAPPLE := TclLogMessagesToStderrAPPLE(oclGetProcAddress('clLogMessagesToStderrAPPLE', OCL_LibHandle));
{$ENDIF}
{$IFDEF CL_VERSION_1_1}
clReleaseDeviceEXT := TclReleaseDeviceEXT(oclGetProcAddress('clReleaseDeviceEXT', OCL_LibHandle));
clRetainDeviceEXT := TclRetainDeviceEXT(oclGetProcAddress('clRetainDeviceEXT', OCL_LibHandle));
clCreateSubDevicesEXT := TclCreateSubDevicesEXT(oclGetProcAddress('clCreateSubDevicesEXT', OCL_LibHandle));
{$ENDIF}
{$IFDEF CL_VERSION_1_0}
clEnqueueMigrateMemObjectEXT := TclEnqueueMigrateMemObjectEXT(oclGetProcAddress('clEnqueueMigrateMemObjectEXT', OCL_LibHandle));
{$ENDIF}
Result := True;
end;
end;
end.
| 47.796584 | 138 | 0.626458 |
f1c4f5e28d86069ffe266cf9d5430775e2f6c1ad | 10,544 | pas | Pascal | src/Security/PasswordHash/Implementations/Argon2i/Argon2iPasswordHashImpl.pas | zamronypj/fano-framework | 559e385be5e1d26beada94c46eb8e760c4d855da | [
"MIT"
]
| 78 | 2019-01-31T13:40:48.000Z | 2022-03-22T17:26:54.000Z | src/Security/PasswordHash/Implementations/Argon2i/Argon2iPasswordHashImpl.pas | zamronypj/fano-framework | 559e385be5e1d26beada94c46eb8e760c4d855da | [
"MIT"
]
| 24 | 2020-01-04T11:50:53.000Z | 2022-02-17T09:55:23.000Z | src/Security/PasswordHash/Implementations/Argon2i/Argon2iPasswordHashImpl.pas | zamronypj/fano-framework | 559e385be5e1d26beada94c46eb8e760c4d855da | [
"MIT"
]
| 9 | 2018-11-05T03:43:24.000Z | 2022-01-21T17:23:30.000Z | {*!
* Fano Web Framework (https://fanoframework.github.io)
*
* @link https://github.com/fanoframework/fano
* @copyright Copyright (c) 2018 Zamrony P. Juhara
* @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT)
*}
unit Argon2iPasswordHashImpl;
interface
{$MODE OBJFPC}
{$H+}
uses
InjectableObjectImpl,
PasswordHashIntf,
HlpIHashInfo,
HlpArgon2TypeAndVersion;
type
(*!------------------------------------------------
* Argon2i password hash
*
* @author Zamrony P. Juhara <zamronypj@yahoo.com>
*-----------------------------------------------*)
TArgon2iPasswordHash = class (TInjectableObject, IPasswordHash)
private
fSalt : string;
fCost : integer;
fHashLen : integer;
fSecret : string;
fMemoryAsKB : integer;
fParallelism : integer;
fArgon2Version : TArgon2Version;
fArgon2ParametersBuilder : IArgon2ParametersBuilder;
public
constructor create(
const defSecret : string;
const defSalt : string = '';
const defCost : integer = 10;
const defLen : integer = 64;
const defMemAsKb : integer = 32;
const defParallel : integer = 4
);
destructor destroy(); override;
(*!------------------------------------------------
* set hash generator cost
*-----------------------------------------------
* @param algorithmCost cost of hash generator
* @return current instance
*-----------------------------------------------*)
function cost(const algorithmCost : integer) : IPasswordHash;
(*!------------------------------------------------
* set hash memory cost (if applicable)
*-----------------------------------------------
* @param memCost cost of memory
* @return current instance
*-----------------------------------------------*)
function memory(const memCost : integer) : IPasswordHash;
(*!------------------------------------------------
* set hash paralleism cost (if applicable)
*-----------------------------------------------
* @param paralleismCost cost of paralleisme
* @return current instance
*-----------------------------------------------*)
function paralleism(const paralleismCost : integer) : IPasswordHash;
(*!------------------------------------------------
* set hash length
*-----------------------------------------------
* @param hashLen length of hash
* @return current instance
*-----------------------------------------------*)
function len(const hashLen : integer) : IPasswordHash;
(*!------------------------------------------------
* set password salt
*-----------------------------------------------
* @param saltValue salt
* @return current instance
*-----------------------------------------------*)
function salt(const saltValue : string) : IPasswordHash;
(*!------------------------------------------------
* set secret key
*-----------------------------------------------
* @param secretValue a secret value
* @return current instance
*-----------------------------------------------*)
function secret(const secretValue : string) : IPasswordHash;
(*!------------------------------------------------
* generate password hash
*-----------------------------------------------
* @param plainPassw input password
* @return password hash in lowercase hex string
*-----------------------------------------------*)
function hash(const plainPassw : string) : string;
(*!------------------------------------------------
* verify plain password against password hash
*-----------------------------------------------
* @param plainPassw input password
* @param hashedPassw password hash in hex string
* @return true if password match password hash
*-----------------------------------------------*)
function verify(
const plainPassw : string;
const hashedPasswd : string
) : boolean;
end;
implementation
uses
Classes,
SysUtils,
HlpIHash,
HlpHashFactory,
HlpConverters,
HlpPBKDF_Argon2NotBuildInAdapter;
constructor TArgon2iPasswordHash.create(
const defSecret : string;
const defSalt : string = '';
const defCost : integer = 10;
const defLen : integer = 64;
const defMemAsKb : integer = 32;
const defParallel : integer = 4
);
begin
fSecret := defSecret;
fSalt := defSalt;
fCost := defCost;
fHashLen := defLen;
fMemoryAsKB := defMemAsKb;
fParallelism := defParallel;
fArgon2Version := TArgon2Version.a2vARGON2_VERSION_13;
fArgon2ParametersBuilder := TArgon2iParametersBuilder.Builder();
end;
destructor TArgon2iPasswordHash.destroy();
begin
fArgon2ParametersBuilder := nil;
inherited destroy();
end;
(*!------------------------------------------------
* set hash generator cost
*-----------------------------------------------
* @param algorithmCost cost of hash generator
* @return current instance
*-----------------------------------------------*)
function TArgon2iPasswordHash.cost(const algorithmCost : integer) : IPasswordHash;
begin
fCost := algorithmCost;
result := self;
end;
(*!------------------------------------------------
* set hash memory cost (if applicable)
*-----------------------------------------------
* @param memCost cost of memory
* @return current instance
*-----------------------------------------------*)
function TArgon2iPasswordHash.memory(const memCost : integer) : IPasswordHash;
begin
fMemoryAsKB := memCost;
result := self;
end;
(*!------------------------------------------------
* set hash paralleism cost (if applicable)
*-----------------------------------------------
* @param paralleismCost cost of paralleisme
* @return current instance
*-----------------------------------------------*)
function TArgon2iPasswordHash.paralleism(const paralleismCost : integer) : IPasswordHash;
begin
fParallelism := paralleismCost;
result := self;
end;
(*!------------------------------------------------
* set hash length
*-----------------------------------------------
* @param hashLen length of hash
* @return current instance
*-----------------------------------------------*)
function TArgon2iPasswordHash.len(const hashLen : integer) : IPasswordHash;
begin
fHashLen := hashLen;
result := self;
end;
(*!------------------------------------------------
* set password salt
*-----------------------------------------------
* @param salt
* @return current instance
*-----------------------------------------------*)
function TArgon2iPasswordHash.salt(const saltValue : string) : IPasswordHash;
begin
fSalt := saltValue;
result := self;
end;
(*!------------------------------------------------
* set secret key
*-----------------------------------------------
* @param secretValue a secret value
* @return current instance
*-----------------------------------------------*)
function TArgon2iPasswordHash.secret(const secretValue : string) : IPasswordHash;
begin
fSecret := secretValue;
result := self;
end;
(*!------------------------------------------------
* generate password hash
*-----------------------------------------------
* @param plainPassw input password
* @return password hash in lowercase hex string
*-----------------------------------------------
* @credit https://github.com/Xor-el/HashLib4Pascal/blob/master/HashLib.Tests/src/PBKDF_Argon2Tests.pas
*-----------------------------------------------*)
function TArgon2iPasswordHash.hash(const plainPassw : string) : string;
var
LGenerator: IPBKDF_Argon2;
LSecret, LSalt, LPassword: TBytes;
LArgon2Parameter: IArgon2Parameters;
begin
fArgon2ParametersBuilder.WithVersion(fArgon2Version)
.WithIterations(fCost)
.WithMemoryAsKB(fMemoryAsKB)
.WithParallelism(fParallelism);
if (fSecret <> '') then
begin
//use secret
LSecret := TConverters.ConvertStringToBytes(fSecret, TEncoding.ASCII);
fArgon2ParametersBuilder.WithSecret(LSecret);
end;
if (fSalt <> '') then
begin
//use salt
LSalt := TConverters.ConvertStringToBytes(fSalt, TEncoding.ASCII);
fArgon2ParametersBuilder.WithSalt(LSalt);
end;
LPassword := TConverters.ConvertStringToBytes(plainPassw, TEncoding.ASCII);
//
// Set the password.
//
LArgon2Parameter := fArgon2ParametersBuilder.Build();
fArgon2ParametersBuilder.Clear();
LGenerator := TKDF.TPBKDF_Argon2.CreatePBKDF_Argon2(
LPassword,
LArgon2Parameter
);
//ConvertBytesToHexString output uppercase hex string
//many argon2 tools output lower case. For easier comparison make it lower
result := lowercase(TConverters.ConvertBytesToHexString(
LGenerator.GetBytes(fHashLen),
false
));
LArgon2Parameter.Clear();
LGenerator.Clear();
end;
(*!------------------------------------------------
* verify plain password against password hash
*-----------------------------------------------
* @param plainPassw input password
* @param hashedPassw password hash in hex string
* @return true if password match password hash
*-----------------------------------------------*)
function TArgon2iPasswordHash.verify(
const plainPassw : string;
const hashedPasswd : string
) : boolean;
begin
//compare with lowercase hex string to make comparison consistent
result := (hash(plainPassw) = lowercase(hashedPasswd));
end;
end.
| 35.0299 | 107 | 0.460926 |
cd669d328a58acb5512c8d5db05a42667d793827 | 933 | pas | Pascal | Part2/8.2 Window for non-visual components/GearU.pas | dalijap/code-delphi-async | 4a7ccb8ca89024ce2435ea5e72fd47493e785439 | [
"MIT"
]
| 26 | 2021-01-03T06:34:46.000Z | 2022-01-22T17:12:36.000Z | Part2/8.2 Window for non-visual components/GearU.pas | kitesoft/code-delphi-async | 2d729af96e7b71f310994749391b40fadd8455a3 | [
"MIT"
]
| null | null | null | Part2/8.2 Window for non-visual components/GearU.pas | kitesoft/code-delphi-async | 2d729af96e7b71f310994749391b40fadd8455a3 | [
"MIT"
]
| 9 | 2021-01-11T16:45:40.000Z | 2022-02-26T13:38:01.000Z | unit GearU;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Classes;
const
CM_MY_EVENT = WM_USER + 100;
type
TGear = class(TObject)
protected
FWndHandle: THandle;
procedure WndProc(var Msg: TMessage); virtual;
public
constructor Create;
destructor Destroy; override;
property WndHandle: THandle read FWndHandle;
end;
implementation
constructor TGear.Create;
begin
inherited;
FWndHandle := AllocateHWnd(WndProc);
end;
destructor TGear.Destroy;
begin
DeallocateHWnd(FWndHandle);
inherited;
end;
procedure TGear.WndProc(var Msg: TMessage);
begin
case Msg.Msg of
CM_MY_EVENT:
begin
OutputDebugString('GEAR MY EVENT');
end;
else
// mandatory call to default message handler
Msg.Result := DefWindowProc(FWndHandle, Msg.Msg, Msg.wParam, Msg.lParam);
end;
end;
end.
| 17.603774 | 80 | 0.66881 |
6a54f65975c80f31a512c4e225d3030d6c0fe3a6 | 13,455 | dfm | Pascal | windows/src/ext/jedi/jvcl/tests/archive/jvcl/examples/RxDemo/ABOUT.dfm | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 219 | 2017-06-21T03:37:03.000Z | 2022-03-27T12:09:28.000Z | windows/src/ext/jedi/jvcl/tests/archive/jvcl/examples/RxDemo/ABOUT.dfm | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 4,451 | 2017-05-29T02:52:06.000Z | 2022-03-31T23:53:23.000Z | windows/src/ext/jedi/jvcl/tests/archive/jvcl/examples/RxDemo/ABOUT.dfm | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 72 | 2017-05-26T04:08:37.000Z | 2022-03-03T10:26:20.000Z | object AboutForm: TAboutForm
Left = 426
Top = 198
BorderIcons = []
BorderStyle = bsDialog
Caption = 'About RX Library'
ClientHeight = 192
ClientWidth = 267
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = True
Position = poScreenCenter
OnCreate = FormCreate
PixelsPerInch = 96
TextHeight = 13
object SecretPanel1: TJvSecretPanel
Left = 0
Top = 0
Width = 267
Height = 192
Cycled = True
Glyph.Data = {
E60E0000424DE60E0000000000007600000028000000A40000002C0000000100
040000000000700E000000000000000000001000000000000000000000000000
80000080000000808000800000008000800080800000C0C0C000808080000000
FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00DDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDD0000DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
0000DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD0000DDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDD0000DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD80088DDDDDDDDDDDDDDDDDDD0000DDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDD000008DDDDDDDDDDDDDDDDDD0000DDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD0008888DDDDDDDDD
DDDDDDDD0000DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDFF7777808DDDDDDDDDDDDDDDD0000DDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDFF
FFF777808DDDDDDDDDDDDDDD0000DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDFFFFDFF7800DDDDDDDDDDDDDDD
0000DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDFFFDDDF78008DDDDDDDDDDDDDD0000DDDDDDDD000000008DDD
DD800000000000DDDDD8000000008DDDDDDDD8000000000000000008DDD80088
DDDD888000888DDDDDD00008DDDDDDDDD80088D880088DD00008DDDDDDDDFF70
008DDDDDDDDDDDDD0000DDDDDDDDD8000088DDDDDD000088D8008DDDDDDD8800
0088DDDDDDDDDDD8000008DD88800008DD8000008DD80008788008DDDDD80008
DDDDDDDD80000088000008D80008DDDDDDDDFFF00008DDDDDDDDDDDD0000DDDD
DDDDDD80008DDDDDD80000DDDD808DDDDDDDD80000DDDDDDDDDDDDDD80000DDD
DDD88000DD80008D88D800087778008DDDD80000DDDDDDDD0000888800008888
0000DDDDDDDDFFF70080DDDDDDDDDDDD0000DDDDDDFFFFFFFFDDDDDDFFFFFFFF
FFFF8DDDDFFFFFFFFFDDDDDDDDDFFFFFFFFFFFFFFFFFF7008FFF780DD8DF7FFF
FF770008DFFFF8008DDDDDDFFF7877FFF7808FFFF8008DDDDDDDFFFF80788DDD
DDDDDDDD0000DDDDDDDFFFFF780DDDDDFFFFDDDFFFFD88DDDDDFFFFFDDDDDDDD
DDDDDFFFFFF808DFFFFFFF807FFFFFD8DFFFF7087FFF80008FFFF8008DDDDDFF
FFFF77FFFFF88FFFF8008DDDDDDDFFFFF87788DDDDDDDDDD0000DDDDDDDDFFFF
8008DDDFFFFF8DDDFFFDD888DDDFFFFF8DDDDDDDDDDDDDFFFFF008DDDDFFFFD8
8FFF70DDDDFFF7008FFFF00007FFFF000DDDDDFFFF8877FFFF8787FFFF000DDD
DDDDFFFF8F77708DDDDDDDDD0000DDDDDDDDDFFF7008DDDFFFF88DDDDFFDDD88
8DDFFFF88DDDDDDDDDDDDDDFFFF800DDDDDFFFDDDFFFF00DFDFFFF0087FFF700
08FFFF8008DDDDFFFF008FFFFF8878FFFF8008DDDDDDFFFF07F7788DDDDDDDDD
0000DDDDDDDDDFFFF008DDDFFFF88DDDDDFFDDDD88DFFFF8DDDDDDDDDDDDDDDF
FFF8008DDDDDDFFDDFFFF8008DFFFF8008FFFF8008FFFF8008DDDDFFFF0007FF
FF7008FFFF8008DDDDDDFFFF08FF7788DDDDDDDD0000DDDDDDDDDFFFF800DDDF
FF70DDDDDDDFFDDDD8DFFF88DDDDDDDDDDDDDDDFFFF7008DDDDDDFFDDFFFF700
8DFFFF80087FFFF000DFFFF0088DDDFFFF8008FFFFF0007FFFF0088DDDDDFFF7
08DF7780DDDDDDDD0000DDDDDDDDDDFFF8008DFFFF88DDDDDDDDFFDDDDFFFFDD
DDDDDDDDDDDDDDDDFFFF000DDDDDDDDDDDFFFF008DDFFF70087FFFF800DFFFF8
0808807FFF80087FFFF8008FFFF80808808DFFF708DDF7808DDDDDDD0000DDDD
DDDDDDFFF70000FFFF888DDDDDDDDFFDDFFFF78DDDDDDDDDDDDDDDDDFFFF8008
DDDDDDDDDDFFFF800DDFFFF80087FFF700DFFFF70080008FFFF0008FFFF8008F
FFF70080008DFFF708DDF7808DDDDDDD0000DDDDDDDDDDFFFF0007FFFF00008D
DDDDDDFFFFFFF8DDDDDDDDDDDDDDDDDDFFFF8008DDDDDDDDDDDFFF8008DFFFF8
0088FFFF08DFFFF78080000FFFF70087FFFF008FFFF78080000DFFF708DDDF00
0DDDDDDD0000DDDDDDDDDDDFFF8007FFFF800008DDDDDDDFFFFF708DDDDDDDDD
DDDDDDDDDFFFF008DDDDDDDDDDDFFF7008DDFFF70080FFFF08DDFFF7F87F800D
FFFF8008FFFF8007FFF7F87F800DFFF80DDDDF800DDDDDDD0000DDDDDDDDDDDF
FFFFFFFFFFF800008DDDDDDDFFFF8888DDDDDDDDDDDDDDDDDFFFF800DDDDDDDD
DDDFFFF800DDFFFF8007FFFF8DDDFFFF7FFF708DDFFF7780FFFF8008FFFF7FFF
708DFFFD8DDDFF708DDDDDDD0000DDDDDDDDDDDFFFF00DDFFFFF70008DDDDDDD
FFFF8DD88DDDDDDDDDDDDDDDDFFFF8008DDDDDDDDDDFFFFFDDDDFFFF7807FFFF
DDDDFFFF7FFFFDDDDFFFF777FFFFFDDDFFFF7FFFFDDFFFFDDDDFFFFDDDDDDDDD
0000DDDDDDDDDDDFFFF800DDDFFFF7000DDDDDDFFFFFDDDD88DDDDDDDDDDDDDD
DFFFF7008DDDDDDDDDFFFFFFDDDDFFFF7FFFFFFDDDFFFFFFFFFFFDDDDDDFFF7F
FFFFFDFFFFFFFFFFFDFFFFFDDDDFFFFDDDDDDDDD0000DDDDDDDDDDDDFFF8008D
DDFFFF800DDDDDDFFFF7FFDDD88DDDDDDDDDDDDDDDFFFF008DDDDDDDDDDDFFFF
DDDDDFFFF07FFFDDDDDDFFFFFDFFFDDDDDDDFFFFDFFFFDDDFFFFFDFFFDDFFFFD
DDDFFFDDDDDDDDDD0000DDDDDDDDDDDDFFF7008DDDFFFF708DDDDDFFFF78DFFD
DD888DDDDDDDDDDDDDFFFF8008DDDDDDDDDDDDDDDDDDDFFFF800DDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD0000DDDD
DDDDDDDDFFFF000DDDDFFFF08DDDDDFFFF8DDDFFDDD808DDDDDDDDDDDDFFFF80
08DDDDDDDDDDDDD8008DDFFFF8008DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD0000DDDDDDDDDDDDDFFF8008DD8FFFF8
DDDDDDFFF708DDDFFDD80088DDDDDDDDDDDFFF700088DDDDDDDDDDD0000DDDFF
F7008DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDD0000DDDDDDDDDDDDDFFF7000000FFFDDDDDD0FFFF8008DDDFFD00000
0DDDDDDDDDDFFFF800008DDDDDDDDDD0000DDDFFFF000DDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD0000DDDDDDDDDDDD
DFFFFDDDDDFFFFFDDDDDFFFFFDDDDDDDDFFDDDDDDDDDDDDDDDDFFFFFDDDDDDDD
DDDDDFFF808DDDFFFF7808DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDD0000DDDDDDDDDDDDDFFFFDDDDFFFFFDDDDDFFFFF
FFDDDDDDDFFFFDDDDDDDDDDDDDDFFFFFFDDDDDDDDDDDDFFFFDDDDDFFFFFDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
0000DDDDDDDDDDDFFFFFFFFFFFFFDDDDDDFFFFFFFFFDDDDDFFFFFFFDDDDDDDDD
DFFFFFFFFFFDDDDDDDDDDFFFFDDDDFFFFFFDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD0000DDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDFFF
FDDDDDDFFFFDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDD0000DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD0000DDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD0000DDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDD0000DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD0000DDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDD0000DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
0000DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD0000DDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDD0000}
GlyphLayout = glGlyphTop
Lines.Strings = (
''
''
''
''
'Delphi VCL Extensions'
'(RX) Library'
''
'Moscow'
''
'Fedor V.Koshevnikov'
'Igor V.Pavluk'
'Serge V.Korolev'
''
#169' 1995,1998'
'')
Align = alClient
BevelOuter = bvNone
Font.Charset = DEFAULT_CHARSET
Font.Color = clHighlight
Font.Height = -13
Font.Name = 'Times New Roman'
Font.Style = [fsBold]
ParentFont = False
TabOrder = 0
OnDblClick = SecretPanel1DblClick
object Label2: TLabel
Left = 13
Top = 63
Width = 182
Height = 13
Caption = ' Copyright '#169' AO ROSNO 1995, 1996 '
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
ParentFont = False
end
object Label1: TLabel
Left = 13
Top = 47
Width = 65
Height = 13
Caption = ' Version 2.50 '
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
ParentFont = False
end
object AppIcon: TImage
Left = 12
Top = 8
Width = 32
Height = 32
Hint = 'Click twice here!|'
AutoSize = True
ParentShowHint = False
ShowHint = True
OnDblClick = AppIconDblClick
end
object WebLabel: TJvLabel
Left = 80
Top = 10
Width = 145
Height = 29
Hint = 'RX Library Web Site|'
Alignment = taCenter
AutoSize = False
Caption = 'Delphi VCL Extensions Library (RX) Demo'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = [fsBold]
ParentFont = False
ParentShowHint = False
ShadowPos = spRightBottom
ShowHint = True
WordWrap = True
OnClick = LabelClick
OnMouseEnter = LabelMouseEnter
OnMouseLeave = LabelMouseEnter
end
object Label3: TLabel
Left = 13
Top = 79
Width = 185
Height = 13
Caption = ' Copyright '#169' Master-Bank 1997, 1998 '
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
ParentFont = False
end
object Bevel1: TBevel
Left = 5
Top = 96
Width = 257
Height = 9
Shape = bsTopLine
end
object Label4: TLabel
Left = 8
Top = 104
Width = 250
Height = 13
Alignment = taCenter
AutoSize = False
Caption = 'Contact points are: '
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
ParentFont = False
end
object Label5: TLabel
Left = 8
Top = 118
Width = 250
Height = 13
Alignment = taCenter
AutoSize = False
Caption = 'Web: http://rx.demo.ru'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
ParentFont = False
end
object Label6: TLabel
Left = 8
Top = 132
Width = 250
Height = 41
Alignment = taCenter
AutoSize = False
Caption = 'E-Mail: fkozh@usa.net; ipavluk@usa.net; korolev@usa.net'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
ParentFont = False
WordWrap = True
end
object OkBtn: TBitBtn
Left = 95
Top = 163
Width = 77
Height = 25
Cancel = True
Caption = 'OK'
Default = True
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
ModalResult = 1
ParentFont = False
TabOrder = 0
NumGlyphs = 2
end
end
end
| 42.046875 | 74 | 0.764846 |
83bfa8b3bac535bd418e9c0c13c8fe9bf5d83c4c | 1,564 | pas | Pascal | Components/Innerfuse Pascal Script/ifps3CEImp_Forms.pas | sabatex/Delphi | 0efbe6eb38bf8aa2bf269d1866741266e90b9cbf | [
"MIT"
]
| null | null | null | Components/Innerfuse Pascal Script/ifps3CEImp_Forms.pas | sabatex/Delphi | 0efbe6eb38bf8aa2bf269d1866741266e90b9cbf | [
"MIT"
]
| null | null | null | Components/Innerfuse Pascal Script/ifps3CEImp_Forms.pas | sabatex/Delphi | 0efbe6eb38bf8aa2bf269d1866741266e90b9cbf | [
"MIT"
]
| 1 | 2019-12-24T08:39:18.000Z | 2019-12-24T08:39:18.000Z | {
@abstract(Forms Import Unit)
@author(Carlo Kok <ck@carlo-kok.com>)
Forms Import Unit
}
unit ifps3CEImp_Forms;
interface
uses
SysUtils, Classes, IFPS3CompExec, ifpscomp, ifps3;
type
{@abstract(Forms import class)}
TIFPS3CE_Forms = class(TIFPS3Plugin)
private
FEnableForms: Boolean;
FEnableMenus: Boolean;
protected
procedure CompileImport1(CompExec: TIFPS3CompExec); override;
procedure ExecImport1(CompExec: TIFPS3CompExec; const ri: TIFPSRuntimeClassImporter); override;
public
constructor Create(AOwner: TComponent); override;
published
property EnableForms: Boolean read FEnableForms write FEnableForms;
property EnableMenus: Boolean read FEnableMenus write FEnableMenus;
end;
procedure Register;
implementation
uses
ifpii_forms,
ifpii_menus,
ifpiir_forms,
ifpiir_menus;
procedure Register;
begin
RegisterComponents('Innerfuse', [TIFPS3CE_Forms]);
end;
{ TIFPS3CE_Forms }
procedure TIFPS3CE_Forms.CompileImport1(CompExec: TIFPS3CompExec);
begin
if FEnableForms then
SIRegister_Forms(CompExec.comp);
if FEnableMenus then
SIRegister_Menus(CompExec.comp);
end;
constructor TIFPS3CE_Forms.Create(AOwner: TComponent);
begin
inherited Create(Aowner);
FEnableForms := True;
FEnableMenus := True;
end;
procedure TIFPS3CE_Forms.ExecImport1(CompExec: TIFPS3CompExec;
const ri: TIFPSRuntimeClassImporter);
begin
if FEnableForms then
RIRegister_Forms(ri);
if FEnableMenus then
begin
RIRegister_Menus(ri);
RIRegister_Menus_Routines(compexec.Exec);
end;
end;
end.
| 22.028169 | 99 | 0.772379 |
f1acee746420580e7276b80011fe9f23038f307a | 12,766 | dfm | Pascal | src/GenInfDlg.dfm | baobabx/NyanFi_x64 | 0f63856c427f2d46b9c079845bfd3ca0d82e920e | [
"MIT"
]
| 21 | 2019-03-11T15:02:20.000Z | 2022-01-06T04:13:10.000Z | src/GenInfDlg.dfm | baobabx/NyanFi_x64 | 0f63856c427f2d46b9c079845bfd3ca0d82e920e | [
"MIT"
]
| null | null | null | src/GenInfDlg.dfm | baobabx/NyanFi_x64 | 0f63856c427f2d46b9c079845bfd3ca0d82e920e | [
"MIT"
]
| 2 | 2019-04-13T17:10:37.000Z | 2021-06-29T10:15:11.000Z | object GeneralInfoDlg: TGeneralInfoDlg
Left = 0
Top = 0
HelpContext = 73
BorderIcons = [biSystemMenu]
ClientHeight = 512
ClientWidth = 530
Color = clBtnFace
Constraints.MinWidth = 320
ParentFont = True
KeyPreview = True
OldCreateOrder = False
Position = poDesigned
ShowHint = True
OnClose = FormClose
OnCreate = FormCreate
OnDestroy = FormDestroy
OnKeyDown = FormKeyDown
OnShow = FormShow
PixelsPerInch = 96
TextHeight = 13
object StatusBar1: TStatusBar
Left = 0
Top = 492
Width = 530
Height = 20
DoubleBuffered = False
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Pitch = fpVariable
Font.Style = []
Panels = <
item
Style = psOwnerDraw
Width = 240
end
item
Style = psOwnerDraw
Width = 100
end
item
Style = psOwnerDraw
Width = 80
end
item
Style = psOwnerDraw
Width = 50
end>
ParentDoubleBuffered = False
UseSystemFont = False
StyleElements = [seBorder]
OnDrawPanel = StatusBar1DrawPanel
end
object MianPanel: TPanel
Left = 0
Top = 0
Width = 530
Height = 492
Align = alClient
BevelOuter = bvNone
TabOrder = 0
object ListPanel: TPanel
Left = 0
Top = 0
Width = 530
Height = 473
Align = alClient
BevelOuter = bvNone
DoubleBuffered = False
ParentDoubleBuffered = False
TabOrder = 0
DesignSize = (
530
473)
object GenListBox: TListBox
Left = 0
Top = 0
Width = 530
Height = 473
Style = lbVirtualOwnerDraw
Anchors = [akLeft, akTop, akRight, akBottom]
BorderStyle = bsNone
Constraints.MinHeight = 32
Constraints.MinWidth = 32
DoubleBuffered = False
ItemHeight = 13
MultiSelect = True
ParentDoubleBuffered = False
PopupMenu = InfPopupMenu
TabOrder = 0
StyleElements = [seBorder]
OnClick = GenListBoxClick
OnData = GenListBoxData
OnDataObject = GenListBoxDataObject
OnDblClick = GenListBoxDblClick
OnDrawItem = GenListBoxDrawItem
OnExit = GenListBoxExit
OnKeyDown = GenListBoxKeyDown
OnKeyPress = GenListBoxKeyPress
end
end
object OpeToolBar: TToolBar
Left = 0
Top = 473
Width = 530
Height = 19
Align = alBottom
AutoSize = True
ButtonHeight = 19
ButtonWidth = 59
DrawingStyle = dsGradient
List = True
ShowCaptions = True
AllowTextButtons = True
TabOrder = 1
object FilterBtn: TToolButton
Left = 0
Top = 0
Caption = #12501#12451#12523#12479'(&F)'
ImageIndex = 0
Style = tbsTextButton
OnClick = FilterBtnClick
end
object FilterEdit: TEdit
Left = 63
Top = 0
Width = 120
Height = 19
Align = alLeft
Constraints.MinWidth = 60
PopupMenu = UserModule.EditPopupMenuE
TabOrder = 0
OnChange = FilterEditChange
OnClick = FilterEditChange
OnEnter = FilterEditEnter
OnExit = FilterEditExit
OnKeyDown = FilterEditKeyDown
OnKeyPress = FilterEditKeyPress
end
object FilterSplitter: TSplitter
Left = 183
Top = 0
Width = 4
Height = 19
end
object MigemoBtn: TToolButton
Left = 187
Top = 0
Action = MigemoAction
Style = tbsTextButton
end
object AndOrBtn: TToolButton
Left = 234
Top = 0
Action = AndOrAction
Style = tbsTextButton
end
object HighlightBtn: TToolButton
Left = 285
Top = 0
Action = HighlightAction
Style = tbsTextButton
end
object ToolButton5: TToolButton
Left = 335
Top = 0
Width = 8
ImageIndex = 4
Style = tbsSeparator
end
object WatchBtn: TToolButton
Left = 343
Top = 0
Action = WatchAction
Style = tbsTextButton
end
object NotifyBtn: TToolButton
Left = 396
Top = 0
Action = NotifyAction
Style = tbsTextButton
end
object PlayPrevBtn: TToolButton
Left = 446
Top = 0
Action = PlayPrevAction
Style = tbsTextButton
end
object PlayPauseBtn: TToolButton
Left = 473
Top = 0
Action = PlayPauseAction
Style = tbsTextButton
end
object PlayNextBtn: TToolButton
Left = 501
Top = 0
Action = PlayNextAction
Style = tbsTextButton
end
end
end
object InfPopupMenu: TPopupMenu
OnPopup = InfPopupMenuPopup
Left = 48
Top = 86
object InfEditCopyItem: TMenuItem
Action = CopyAction
end
object InfEditCopyValItem: TMenuItem
Action = CopyValAction
end
object InfEditSelectAllItem: TMenuItem
Action = SelAllAction
end
object FindTextItem: TMenuItem
Caption = #26908#32034'(&F)...'
OnClick = FindTextItemClick
end
object Sep_1: TMenuItem
Caption = '-'
end
object ClrCmdHistoryItem: TMenuItem
Action = ClrCmdHistoryAction
end
object CopyCmdItem: TMenuItem
Action = CopyCmdAction
end
object SaveAsNbtItem: TMenuItem
Action = SaveAsNbtAction
end
object Sep_2: TMenuItem
Caption = '-'
end
object SortItem: TMenuItem
Caption = #19968#35239#12434#12477#12540#12488'(&O)'
object SortAscItem: TMenuItem
Action = SortAscAction
end
object SortDesItem: TMenuItem
Action = SortDesAction
end
object OrgOrderItem: TMenuItem
Action = OrgOrderAction
end
end
object DelDuplItem: TMenuItem
Action = DelDuplAction
end
object RestoreListItem: TMenuItem
Action = RestoreListAction
end
object Sep_3: TMenuItem
Caption = '-'
end
object SaveAsItem: TMenuItem
Action = SaveAsAction
end
object ViewListItem: TMenuItem
Action = ViewListAction
end
object Sep_4: TMenuItem
Caption = '-'
end
object ViewFileItem: TMenuItem
Action = ViewFileAction
end
object EditFileItem: TMenuItem
Action = EditFileAction
end
object Sep_5: TMenuItem
Caption = '-'
end
object ShowFileInfoItem: TMenuItem
Action = ShowFileInfoAction
end
object PropertyItem: TMenuItem
Action = PropertyAction
end
object Sep_6: TMenuItem
Caption = '-'
end
object ShowLineNoItem: TMenuItem
Action = ShowLineNoAction
end
object FileName1stItem: TMenuItem
Action = FileName1stAction
end
object OmitComPathItem: TMenuItem
Action = OmitComPathAction
end
object KeepIndexItem: TMenuItem
Action = KeepIndexAction
end
object ErrOnlyItem: TMenuItem
Action = ErrOnlyAction
end
object FitSizePosItem: TMenuItem
Action = UserModule.SizePosToFlieListAction
end
end
object ActionList1: TActionList
Left = 48
Top = 13
object CopyAction: TAction
Caption = #12467#12500#12540'(&C)'
OnExecute = CopyActionExecute
OnUpdate = CopyActionUpdate
end
object CopyValAction: TAction
Caption = #12459#12540#12477#12523#34892#12398#20516#12434#12467#12500#12540'(&X)'
OnExecute = CopyValActionExecute
OnUpdate = CopyValActionUpdate
end
object SelAllAction: TAction
Caption = #12377#12409#12390#36984#25246'(&A)'
OnExecute = SelAllActionExecute
end
object SaveAsAction: TAction
Caption = #19968#35239#12434#12501#12449#12452#12523#12395#20445#23384'(&S)...'
OnExecute = SaveAsActionExecute
end
object ClrCmdHistoryAction: TAction
Caption = #12467#12510#12531#12489#23653#27508#12434#12463#12522#12450
OnExecute = ClrCmdHistoryActionExecute
OnUpdate = ClrCmdHistoryActionUpdate
end
object CopyCmdAction: TAction
Caption = #12467#12510#12531#12489#12434#12467#12500#12540'(&B)'
OnExecute = CopyCmdActionExecute
OnUpdate = CopyCmdActionUpdate
end
object SaveAsNbtAction: TAction
Caption = #36984#25246#34892#12434#12467#12510#12531#12489#12501#12449#12452#12523#12392#12375#12390#20445#23384'...'
OnExecute = SaveAsNbtActionExecute
OnUpdate = CopyCmdActionUpdate
end
object ViewListAction: TAction
Caption = #19968#35239#12434#12486#12461#12473#12488#12499#12517#12450#12540#12391#38283#12367'(&V)'
OnExecute = ViewListActionExecute
OnUpdate = ViewListActionUpdate
end
object ViewFileAction: TAction
Caption = #12501#12449#12452#12523#12434#12486#12461#12473#12488#12499#12517#12450#12540#12391#38283#12367'(&V)'
OnExecute = ViewFileActionExecute
OnUpdate = OpenFileActionUpdate
end
object EditFileAction: TAction
Caption = #12501#12449#12452#12523#12434#12486#12461#12473#12488#12456#12487#12451#12479#12391#38283#12367'(&E)'
ShortCut = 32837
OnExecute = EditFileActionExecute
OnUpdate = OpenFileActionUpdate
end
object ShowLineNoAction: TAction
Caption = #34892#30058#21495#12434#34920#31034'(&N)'
OnExecute = ShowLineNoActionExecute
end
object FileName1stAction: TAction
Caption = #12501#12449#12452#12523#21517#12434#20808#12395#34920#31034'(&F)'
OnExecute = FileName1stActionExecute
OnUpdate = FileName1stActionUpdate
end
object OmitComPathAction: TAction
Caption = #12497#12473#12398#20849#36890#37096#20998#12434#30465#30053'(&P)'
OnExecute = OmitComPathActionExecute
OnUpdate = OmitComPathActionUpdate
end
object KeepIndexAction: TAction
Caption = #12459#12540#12477#12523#20301#32622#12434#32173#25345'(&K)'
OnExecute = KeepIndexActionExecute
OnUpdate = KeepIndexActionUpdate
end
object ErrOnlyAction: TAction
Caption = #12456#12521#12540#31623#25152#12398#32094#12426#36796#12415'(&X)'
OnExecute = ErrOnlyActionExecute
OnUpdate = ErrOnlyActionUpdate
end
object SortAscAction: TAction
Caption = #26119#38918' (&A)'
OnExecute = SortAscActionExecute
OnUpdate = ListActionUpdate
end
object SortDesAction: TAction
Caption = #38477#38918'(&D)'
OnExecute = SortDesActionExecute
OnUpdate = ListActionUpdate
end
object OrgOrderAction: TAction
Caption = #35299#38500'(&R)'
OnExecute = OrgOrderActionExecute
OnUpdate = ListActionUpdate
end
object DelDuplAction: TAction
Caption = #19968#35239#12398#37325#35079#34892#12434#38500#22806'(&D)'
OnExecute = DelDuplActionExecute
OnUpdate = ListActionUpdate
end
object RestoreListAction: TAction
Caption = #19968#35239#12398#20869#23481#12434#20803#12395#25147#12377
OnExecute = RestoreListActionExecute
OnUpdate = ListActionUpdate
end
object ShowFileInfoAction: TAction
Caption = #12501#12449#12452#12523#24773#22577'(&I)'
OnExecute = ShowFileInfoActionExecute
OnUpdate = PropertyActionUpdate
end
object PropertyAction: TAction
Caption = #12503#12525#12497#12486#12451'(&R)'
OnExecute = PropertyActionExecute
OnUpdate = PropertyActionUpdate
end
object MigemoAction: TAction
Caption = '&Migomo'
OnExecute = ToggleActionExecute
end
object AndOrAction: TAction
Caption = '&ADN/OR'
OnExecute = ToggleActionExecute
end
object HighlightAction: TAction
Caption = #24375#35519'(&H)'
OnExecute = ToggleActionExecute
end
object WatchAction: TAction
Caption = #30435#35222'(&W)'
OnExecute = ToggleActionExecute
OnUpdate = TailActionUpdate
end
object NotifyAction: TAction
Caption = #36890#30693'(&N)'
OnExecute = ToggleActionExecute
OnUpdate = TailActionUpdate
end
object PlayNextAction: TAction
Caption = '>>'
Hint = #27425#12398#26354#12434#20877#29983
OnExecute = PlayNextActionExecute
OnUpdate = PlayActionUpdate
end
object PlayPrevAction: TAction
Caption = '<<'
Hint = #21069#12398#26354#12434#20877#29983
OnExecute = PlayPrevActionExecute
OnUpdate = PlayActionUpdate
end
object PlayPauseAction: TAction
Caption = #9655'||'
OnExecute = PlayPauseActionExecute
OnUpdate = PlayPauseActionUpdate
end
end
object Timer1: TTimer
Enabled = False
OnTimer = Timer1Timer
Left = 48
Top = 152
end
end
| 27.632035 | 123 | 0.645543 |
8381cb758a8a8bd51160df9bacfb8e9628af7852 | 22,402 | pas | Pascal | source/DeLaFitsCommon.pas | felleroff/delafits | f6ba88bf6eddd2942d0908d39882e716b0530d6f | [
"MIT"
]
| 1 | 2018-08-15T03:03:07.000Z | 2018-08-15T03:03:07.000Z | source/DeLaFitsCommon.pas | felleroff/delafits | f6ba88bf6eddd2942d0908d39882e716b0530d6f | [
"MIT"
]
| null | null | null | source/DeLaFitsCommon.pas | felleroff/delafits | f6ba88bf6eddd2942d0908d39882e716b0530d6f | [
"MIT"
]
| 3 | 2018-08-15T03:03:09.000Z | 2021-12-25T15:42:47.000Z | { **************************************************** }
{ DeLaFits - Library FITS for Delphi & Lazarus }
{ }
{ Types, constants, keyword dictionary }
{ and simple functions }
{ }
{ Copyright(c) 2013-2021, felleroff }
{ delafits.library@gmail.com }
{ https://github.com/felleroff/delafits }
{ **************************************************** }
unit DeLaFitsCommon;
{$I DeLaFitsDefine.inc}
interface
uses
SysUtils;
{$I DeLaFitsSuppress.inc}
const
cDeLaFits = 'DeLaFits';
{ FITS Standard. Each FITS structure shall consist of an integral number
of FITS blocks which are each 2880 bytes (23040 bits) in length }
cSizeBlock = 2880;
cSizeLine = 80;
cCountLinesInBlock = cSizeBlock div cSizeLine; // 36
cSizeKeyword = 08;
cChrValueIndicator: Char = '='; // $3D
cChrNoteIndicator : Char = '/'; // $2F
cChrBlank : Char = ' '; // $20
cChrNull : Char = Char(0); // $00
cChrQuote : Char = ''''; // $27
cWidthLineValue = 20;
cWidthLineValueQuote = 08;
{ FITS Standard. A sequence of data values. This sequence corresponds
to the elements in a rectilinear, n-dimension matrix (1 <= n <= 999,
or n = 0 in the case of a null array) }
cMaxAxis = 999;
{ FITS Standard. The ASCII-table extension / Binary-table extension. The value
field TFIELDS shall contain a non-negative integer representing the number
of fields in each row. The maximum permissible value is 999 }
cMaxFields = 999;
const
{ FITS Standard. Basic and other commonly used keywords:
https://heasarc.gsfc.nasa.gov/docs/fcg/standard_dict.html
https://heasarc.gsfc.nasa.gov/docs/fcg/common_dict.html }
cSIMPLE = 'SIMPLE';
cEXTEND = 'EXTEND'; // Boolean: may the FITS file contain extensions? optional
cXTENSION = 'XTENSION'; // String: name of the extension type
cEXTNAME = 'EXTNAME'; // String: for distinguish among different extensions of the same type, i.e., with the same value of XTENSION
cEXTVER = 'EXTVER'; // Integer: for distinguish among different extensions in a FITS file with the same type and name, i.e., the same values for XTENSION and EXTNAME , default = 1
cEXTLEVEL = 'EXTLEVEL'; // Integer: specifying the level in a hierarchy of extension levels of the extension header containing it, default = 1
cBITPIX = 'BITPIX';
cGCOUNT = 'GCOUNT'; // Integer: group count, optional, default = 1
cPCOUNT = 'PCOUNT'; // Integer: parameter count, optional, default = 0
cNAXIS = 'NAXIS';
cNAXISn = 'NAXIS%d';
cNAXIS1 = 'NAXIS1';
cNAXIS2 = 'NAXIS2';
cNAXIS3 = 'NAXIS3';
cGROUPS = 'GROUPS'; // Boolean: indicates random groups structure
cBSCALE = 'BSCALE';
cBZERO = 'BZERO';
cTFIELDS = 'TFIELDS';
cTBCOLn = 'TBCOL%d';
cTFORMn = 'TFORM%d';
cTTYPEn = 'TTYPE%d';
cTUNITn = 'TUNIT%d';
cTSCALn = 'TSCAL%d';
cTZEROn = 'TZERO%d';
cTNULLn = 'TNULL%d';
cTDISPn = 'TDISP%d';
cTDMINn = 'TDMIN%d';
cTDMAXn = 'TDMAX%d';
cTLMINn = 'TLMIN%d';
cTLMAXn = 'TLMAX%d';
cAUTHOR = 'AUTHOR';
cBLANK = '';
cCOMMENT = 'COMMENT';
cDATAMAX = 'DATAMAX'; // Double
cDATAMIN = 'DATAMIN'; // Double
cDATE = 'DATE'; // String: 'yyyy-mm-dd' or 'yyyy-mm-ddTHH:MM:SS[.sss]'
cDATE_OBS = 'DATE-OBS';
cEPOCH = 'EPOCH';
cEQUINOX = 'EQUINOX'; // Double: equinox of celestial coordinate system
cHISTORY = 'HISTORY';
cINSTRUME = 'INSTRUME';
cOBJECT = 'OBJECT';
cOBSERVER = 'OBSERVER';
cORIGIN = 'ORIGIN';
cTELESCOP = 'TELESCOP';
cAPERTURE = 'APERTURE';
cCREATOR = 'CREATOR'; // String: name of software that created the file
cDATE_END = 'DATE-END'; // String: end date of observation
cDEC = 'DEC'; // String or Double, 'sdd(.d)' or 'sdd:mm:ss(.sss)'
cELAPTIME = 'ELAPTIME'; // Double: elapsed time of observation, number of seconds
cEXPOSURE = 'EXPOSURE'; // Double: excerpt from the observations in units of seconds (exposure). Exact, syn. EXPTIME
cEXPTIME = 'EXPTIME'; // Double: exposure time
cFILTER = 'FILTER';
cLATITUDE = 'LATITUDE'; // Double: geographical latitude observations
cLIVETIME = 'LIVETIME'; // Double: the exposure time after Deadtime correction
cOBJNAME = 'OBJNAME'; // String: IUA name of the monitored object
cOBS_ID = 'OBS_ID'; // String: unique identifier for of observation
cORIENTAT = 'ORIENTAT'; // Double: position angle of the image axis Y (deg. E of N)
cRA = 'RA'; // String or Double: 'ddd(.d)' or 'ddd:mm:ss(.s)' or 'hh(.h)' or 'hh:mm:ss(.sss)'
cTIME_OBS = 'TIME-OBS'; // String: start time of observation
cEND = 'END';
type
{ Numbers: f ~ floating-point, u ~ unsigned binary integer, c ~ two's
complement binary integer }
T08u = Byte;
T08c = ShortInt;
T16u = Word;
T16c = SmallInt;
T32f = Single;
T32u = LongWord;
T32c = LongInt;
T64f = Double;
T64c = Int64;
T80f = Extended;
{ Arrays }
TA08u = array of T08u;
TA08c = array of T08c;
TA16u = array of T16u;
TA16c = array of T16c;
TA32f = array of T32f;
TA32u = array of T32u;
TA32c = array of T32c;
TA64f = array of T64f;
TA64c = array of T64c;
TA80f = array of T80f;
TABol = array of Boolean;
TAStr = array of string;
type
{ System order bytes: big-endian or little-endian }
TEndianness = (sysBE, sysLE);
function GetEndianness: TEndianness;
type
{ The type of data in the temporary buffer when dealing with stream, possible
need packed }
TBuffer = array of T08u;
const
{ Max size the temporary buffer for operation with stream }
cMaxSizeBuffer: Integer = 1024 * 64;
function GetMaxSizeBuffer: Integer;
procedure SetMaxSizeBuffer(const AValue: Integer);
type
{ Numbers type of the data elements: physical values representation of the
data block }
TRepNumber = (repUnknown, rep80f, rep64f, rep32f, rep08c, rep08u, rep16c,
rep16u, rep32c, rep32u, rep64c);
type
{ Fits Standard. BITPIX (bits per data value):
-64 ~ IEEE double precision floating-point
-32 ~ IEEE single precision floating-point
+08 ~ Character or unsigned binary integer
+16 ~ 16-bit two's complement binary integer
+32 ~ 32-bit two's complement binary integer
+64 ~ 64-bit two's complement binary integer }
TBitPix = (biUnknown, bi64f, bi32f, bi08u, bi16c, bi32c, bi64c);
function BitPixToInt(Value: TBitPix): Integer; {$IFDEF HAS_INLINE} inline; {$ENDIF}
function IntToBitPix(Value: Integer): TBitPix; {$IFDEF HAS_INLINE} inline; {$ENDIF}
function BitPixToRep(Value: TBitPix): TRepNumber; {$IFDEF HAS_INLINE} inline; {$ENDIF}
// Returns size BitPix in bytes
function BitPixSize(Value: TBitPix): Byte; {$IFDEF HAS_INLINE} inline; {$ENDIF} overload;
function BitPixSize(Value: Integer): Byte; {$IFDEF HAS_INLINE} inline; {$ENDIF} overload;
const
{ Usage of BZERO to represent non-default integer data types }
cZero08c = -$80;
cZero16u = +$8000;
cZero32u = +$80000000;
const
{ Constant string values parsing rules }
cCast = 0;
cCastChars = cCast + 1; // ~ string as is, one line (len ~ 80)
cCastText = cCast + 2; // ~ string as is long
cCastString = cCast + 3; // ~ quoted/unquoted string
cCastBoolean = cCast + 4; // ~ Boolean
cCastInteger = cCast + 5; // ~ Int64
cCastFloat = cCast + 6; // ~ Extended
cCastRa = cCast + 7; // ~ Extended
cCastDe = cCast + 8; // ~ Extended
cCastDateTime = cCast + 9; // ~ TDateTime
cCastDate = cCast + 10; // ~ TDateTime, only Date
cCastTime = cCast + 11; // ~ TDateTime, only Time
type
TSliceDateTime = cCastDateTime .. cCastTime; // DateTime, only Date, only Time
{ Fits Standard. Each 80-character header keyword record shall consist of
a keyword name, a value indicator (only required if a value is present),
an optional value, and an optional comment.
Card.Value contains only one! value: string, Boolean, Int64, Extended
or TDateTime, ie this simple analog of the type Variant }
TCard = record
Keyword: string;
ValueIndicate: Boolean;
Value: record
Str: string;
Bol: Boolean;
Int: Int64;
Ext: Extended;
Dtm: TDateTime;
end;
NoteIndicate: Boolean;
Note: string;
end;
// Just a wrapper, no checks
function ToCard(const Keyword: string; ValueIndicate: Boolean; Value: string;
NoteIndicate: Boolean; const Note: string): TCard; overload;
function ToCard(const Keyword: string; ValueIndicate: Boolean; Value: Boolean;
NoteIndicate: Boolean; const Note: string): TCard; overload;
function ToCard(const Keyword: string; ValueIndicate: Boolean; Value: Int64;
NoteIndicate: Boolean; const Note: string): TCard; overload;
function ToCard(const Keyword: string; ValueIndicate: Boolean; Value: Extended;
NoteIndicate: Boolean; const Note: string): TCard; overload;
function ToCard(const Keyword: string; ValueIndicate: Boolean; Value: TDateTime;
NoteIndicate: Boolean; const Note: string): TCard; overload;
type
TFmtShortDate = (yymmdd, ddmmyy); // Fits format short date ~ yymmdd
TFmtRepCoord = (coWhole, coParts); // G.(g) or GG MM SS.(s)
TFmtMeaCoord = (coDegree, coHour); // DDD:MM:SS.(s) or HH:MM:SS.(s)
{ Format equatorial coordinate system (Ra, De). Fits standard:
Ra in [coHour, coParts], De in [coDegree, coParts]
|------|------------------------|----------------------------|
| | Ra | De |
|------|------------------------|----------------------------|
| Fits | HH:MM:SS.(s) | 0..24 | +/-DD:MM:SS.(s) | -90..+90 |
| ~ | HH.(h) | 0..24 | +/-DD.(d) | -90..+90 |
| ~ | DDD:MM:SS.(s) | 0..360 | +/-DD:MM:SS.(s) | -90..+90 |
| ~ | DDD.(d) | 0..360 | +/-DD.(d) | -90..+90 |
|------------------------------------------------------------| }
{ Formatting options header lines: additional parameters when parsing
the header lines }
PFormatLine = ^TFormatLine;
TFormatLine = record
vaStr: record
wWidth: ShortInt; // default = -cWidthLineValue ~ <text >
wWidthQuoteInside: ShortInt; // default = -cWidthLineValueQuote ~ 'text '
end;
vaBol: record
wWidth: ShortInt; // default = cWidthLineValue ~ < text>
end;
vaInt: record
wWidth: ShortInt; // default = cWidthLineValue ~ < text>
wSign: Boolean; // default = False
wFmt: string; // see Format function; default = '%d'
end;
vaFloat: record
wWidth: ShortInt; // default = cWidthLineValue ~ < text>
wSign: Boolean; // default = False
wFmt: string; // see Format function; default = '%g'
end;
vaDateTime: record
rFmtShortDate: TFmtShortDate; // used as a prompt when reading short date format; default = yymmdd
wWidth: ShortInt; // default = -cWidthLineValue ~ <text >
wWidthQuoteInside: ShortInt; // default = -cWidthLineValueQuote ~ <text >
end;
vaCoord: record
rFmtMeaRa: TFmtMeaCoord; // used as a prompt when reading Ra (Equatorial coordinate system); default = coHour
wWidth: ShortInt; // default = -cWidthLineValue ~ <text >, used Abs(cWidthLineValue) for coDec representation
wWidthQuoteInside: ShortInt; // default = -cWidthLineValueQuote ~ <text >
wPrecRa: Word; // in [degree], '%.(wPrecRa)f'; default = 4 ~ hh:mm:ss.ss, ie (0.1")
wPrecDe: Word; // in [degree], '%.(wPrecDe)f'; default = 4 ~ dd:mm:ss.s, ie (0.1")
wFmtMeaRa: TFmtMeaCoord; // default = coHour
wFmtRepCoord: TFmtRepCoord; // default = coParts
end;
end;
function FormatLineDefault: TFormatLine;
{ String }
function IfThen(AValue: Boolean; const ATrue: string; const AFalse: string = ''): string; {$IFDEF HAS_INLINE} inline; {$ENDIF} overload;
type
{ Picture frame histogram }
PHistogramBucket = ^THistogramBucket;
THistogramBucket = record
Elem: Extended;
Freq: Integer;
end;
THistogramBuckets = array of PHistogramBucket;
THistogramIndexRange = record
Black: Integer;
White: Integer;
end;
const
cHistogramMaxQuota = 1024 * 1024; // maximum pixel sample size
cHistogramMaxCount = 50 * 1000; // maximum bucket size, eq ~586 kb
const
{ Picture frame tone: Y = Co * (X ^ Ga - 0.5) + 0.5 + Br }
cBrightnessMax = +1.0;
cBrightnessMin = -1.0;
cBrightnessDef = 0.0;
cContrastMax = 3.0;
cContrastMin = 0.0;
cContrastDef = 1.0;
cGammaMax = 3.0;
cGammaMin = 0.0;
cGammaDef = 1.0;
const
{ Picture frame palette }
cPaletteCount = 256;
type
TPaletteTuple = record
R, G, B: Byte;
end;
PPaletteTuples = ^TPaletteTuples;
TPaletteTuples = array [0 .. cPaletteCount - 1] of TPaletteTuple;
TPaletteIndexs = array of array of Byte;
type
{ Picture frame pixel map }
TPixmap = record
Pix: TPaletteIndexs;
Map: TPaletteTuples;
end;
const
{ Picture frame band: opeartor "pixel value -> palette index" }
cFrameBandCount = cPaletteCount;
type
TFrameBand = array [0 .. cFrameBandCount - 1] of Extended;
type
{ Picture frame geometry }
TMatrix = array [1 .. 3, 1 .. 3] of Double;
TPix = record
X, Y: Integer;
end;
TPnt = record
X, Y: Double;
end;
TDesignPoint = (xy00, xyLT, xyRT, xyRB, xyLB, xyCC);
TDesignShift = (xyLTat00, xyRTat00, xyRBat00, xyLBat00, xyCCat00);
function ToPnt(const X, Y: Double): TPnt;
function ToPix(const X, Y: Integer): TPix;
type
TRegion = record
X1, Y1: Integer;
Width, Height: Integer;
end;
function ToRegion(X1, Y1: Integer; Width, Height: Integer): TRegion;
type
TBound = record
Xmin: Integer;
Ymin: Integer;
Xmax: Integer;
Ymax: Integer;
Xcount: Integer;
Ycount: Integer;
end;
function ToBound(const Region: TRegion): TBound;
type
TPntsQuad = array [1 .. 4] of TPnt;
TQuad = record
case Integer of
0: (X1, Y1, X2, Y2, X3, Y3, X4, Y4: Double);
1: (P1, P2, P3, P4: TPnt);
2: (PA: TPntsQuad);
end;
function ToQuad(const X1, Y1, X2, Y2, X3, Y3, X4, Y4: Double): TQuad; overload;
function ToQuad(const Region: TRegion): TQuad; overload;
type
TPntsClip = array [1 .. 8] of TPnt;
TClip = record
PN: Integer;
case Integer of
0: (X1, Y1, X2, Y2, X3, Y3, X4, Y4, X5, Y5, X6, Y6, X7, Y7, X8, Y8: Double);
1: (P1, P2, P3, P4, P5, P6, P7, P8: TPnt);
2: (PA: TPntsClip);
end;
function ToClip(const XA, YA: array of Double): TClip;
const
{ The base class of exceptions and their codes }
ERROR_FITS = 1000;
ERROR_NULL = 1001;
ERROR_UNKNOWN = 1002;
resourcestring
SAssertionFailure = 'DeLaFits assertion failure';
type
EFitsException = class(Exception)
private
FCode: Integer;
public
constructor Create(const AMsg: string; ACode: Integer);
constructor CreateFmt(const AMsg: string; const Args: array of const; ACode: Integer); overload;
constructor CreateFmt(const AMsg: string; const Args: array of const; const EMsg: string; ACode: Integer); overload;
property Code: Integer read FCode;
end;
implementation
{ TEndianness }
function GetEndianness: TEndianness;
const
A: array [0 .. 1] of Byte = ($12, $34);
var
X: Word;
begin
X := 0;
Move(A[0], X, 2);
if X = $1234 then
Result := sysBE
else { X = $3412 }
Result := sysLE
end;
{ Temporary buffer }
function GetMaxSizeBuffer: Integer;
begin
Result := cMaxSizeBuffer;
end;
procedure SetMaxSizeBuffer(const AValue: Integer);
begin
if AValue > 0 then
PInteger(@cMaxSizeBuffer)^ := AValue;
end;
{ TBitPix }
function BitPixToInt(Value: TBitPix): Integer;
begin
case Value of
bi64f: Result := -64;
bi32f: Result := -32;
bi08u: Result := 08;
bi16c: Result := 16;
bi32c: Result := 32;
bi64c: Result := 64;
else Result := 00;
end;
end;
function IntToBitPix(Value: Integer): TBitPix;
begin
case Value of
-64: Result := bi64f;
-32: Result := bi32f;
08: Result := bi08u;
16: Result := bi16c;
32: Result := bi32c;
64: Result := bi64c;
else Result := biUnknown;
end;
end;
function BitPixToRep(Value: TBitPix): TRepNumber;
begin
case Value of
bi64f: Result := rep64f;
bi32f: Result := rep32f;
bi08u: Result := rep08u;
bi16c: Result := rep16c;
bi32c: Result := rep32c;
bi64c: Result := rep64c;
else Result := repUnknown;
end;
end;
function BitPixSize(Value: TBitPix): Byte;
begin
case Value of
bi64f: Result := 8;
bi32f: Result := 4;
bi08u: Result := 1;
bi16c: Result := 2;
bi32c: Result := 4;
bi64c: Result := 8;
else Result := 0;
end;
end;
function BitPixSize(Value: Integer): Byte;
var
BitPix: TBitPix;
begin
BitPix := IntToBitPix(Value);
Result := BitPixSize(BitPix);
end;
{ TCard }
function EmptyCard(const Keyword: string; ValueIndicate: Boolean;
NoteIndicate: Boolean; const Note: string): TCard;
begin
Result.Keyword := Keyword;
Result.ValueIndicate := ValueIndicate;
with Result.Value do
begin
Str := '';
Bol := False;
Int := 0;
Ext := 0.0;
Dtm := Now;
end;
Result.NoteIndicate := NoteIndicate;
Result.Note := Note;
end;
function ToCard(const Keyword: string; ValueIndicate: Boolean; Value: string;
NoteIndicate: Boolean; const Note: string): TCard; overload;
begin
Result := EmptyCard(Keyword, ValueIndicate, NoteIndicate, Note);
Result.Value.Str := Value;
end;
function ToCard(const Keyword: string; ValueIndicate: Boolean; Value: Boolean;
NoteIndicate: Boolean; const Note: string): TCard; overload;
begin
Result := EmptyCard(Keyword, ValueIndicate, NoteIndicate, Note);
Result.Value.Bol := Value;
end;
function ToCard(const Keyword: string; ValueIndicate: Boolean; Value: Int64;
NoteIndicate: Boolean; const Note: string): TCard; overload;
begin
Result := EmptyCard(Keyword, ValueIndicate, NoteIndicate, Note);
Result.Value.Int := Value;
end;
function ToCard(const Keyword: string; ValueIndicate: Boolean; Value: Extended;
NoteIndicate: Boolean; const Note: string): TCard; overload;
begin
Result := EmptyCard(Keyword, ValueIndicate, NoteIndicate, Note);
Result.Value.Ext := Value;
end;
function ToCard(const Keyword: string; ValueIndicate: Boolean; Value: TDateTime;
NoteIndicate: Boolean; const Note: string): TCard; overload;
begin
Result := EmptyCard(Keyword, ValueIndicate, NoteIndicate, Note);
Result.Value.Dtm := Value;
end;
{ TFormatLine }
function FormatLineDefault: TFormatLine;
begin
with Result do
begin
vaStr.wWidth := -cWidthLineValue;
vaStr.wWidthQuoteInside := -cWidthLineValueQuote;
vaBol.wWidth := cWidthLineValue;
vaInt.wWidth := cWidthLineValue;
vaInt.wSign := False;
vaInt.wFmt := '%d';
vaFloat.wWidth := cWidthLineValue;
vaFloat.wSign := False;
vaFloat.wFmt := '%g';
vaDateTime.rFmtShortDate := yymmdd;
vaDateTime.wWidth := -cWidthLineValue;
vaDateTime.wWidthQuoteInside := -cWidthLineValueQuote;
vaCoord.rFmtMeaRa := coHour;
vaCoord.wWidth := -cWidthLineValue;
vaCoord.wWidthQuoteInside := -cWidthLineValueQuote;
vaCoord.wPrecRa := 4;
vaCoord.wPrecDe := 4;
vaCoord.wFmtMeaRa := coHour;
vaCoord.wFmtRepCoord := coParts;
end;
end;
{ String }
function IfThen(AValue: Boolean; const ATrue: string; const AFalse: string = ''): string; {$IFDEF HAS_INLINE} inline; {$ENDIF} overload;
begin
if AValue then
Result := ATrue
else
Result := AFalse;
end;
{ Picture frame geometry }
function ToPnt(const X, Y: Double): TPnt;
begin
Result.X := X;
Result.Y := Y;
end;
function ToPix(const X, Y: Integer): TPix;
begin
Result.X := X;
Result.Y := Y;
end;
function ToRegion(X1, Y1: Integer; Width, Height: Integer): TRegion;
begin
Assert((Width >= 0) and (Height >= 0), SAssertionFailure);
Result.X1 := X1;
Result.Y1 := Y1;
Result.Width := Width;
Result.Height := Height;
end;
function ToBound(const Region: TRegion): TBound;
begin
Assert((Region.Width >= 0) and (Region.Height >= 0), SAssertionFailure);
Result.Xmin := Region.X1;
Result.Ymin := Region.Y1;
Result.Xmax := Region.X1 + Region.Width - 1;
Result.Ymax := Region.Y1 + Region.Height - 1;
Result.Xcount := Region.Width;
Result.Ycount := Region.Height;
end;
function ToQuad(const X1, Y1, X2, Y2, X3, Y3, X4, Y4: Double): TQuad; overload;
begin
Result.X1 := X1;
Result.Y1 := Y1;
Result.X2 := X2;
Result.Y2 := Y2;
Result.X3 := X3;
Result.Y3 := Y3;
Result.X4 := X4;
Result.Y4 := Y4;
end;
function ToQuad(const Region: TRegion): TQuad; overload;
var
dx, dy: Integer;
begin
dx := Region.Width;
dy := Region.Height;
with Region do
begin
Result.P1 := ToPnt(X1, Y1);
Result.P2 := ToPnt(X1 + dx, Y1);
Result.P3 := ToPnt(X1 + dx, Y1 + dy);
Result.P4 := ToPnt(X1, Y1 + dy);
end;
end;
function ToClip(const XA, YA: array of Double): TClip;
var
I: Integer;
begin
Assert(Length(XA) = Length(YA), SAssertionFailure);
Result.PN := Length(XA);
for I := 1 to Result.PN do
begin
Result.PA[I].X := XA[I - 1];
Result.PA[I].Y := YA[I - 1];
end;
end;
{ EFitsException }
constructor EFitsException.Create(const AMsg: string; ACode: Integer);
var
Msg: string;
begin
FCode := ACode;
Msg := Format('%s %.4d', [cDeLaFits, FCode]);
Msg := Msg + IfThen(AMsg = '', '', ', ' + AMsg);
inherited Create(Msg);
end;
constructor EFitsException.CreateFmt(const AMsg: string; const Args: array of const; ACode: Integer);
var
Msg: string;
begin
Msg := Format(AMsg, Args);
Create(Msg, ACode);
end;
constructor EFitsException.CreateFmt(const AMsg: string; const Args: array of const; const EMsg: string; ACode: Integer);
var
Msg: string;
begin
Msg := Format(AMsg, Args);
Msg := Msg + IfThen(Msg = '', '.', '');
Msg := Msg + IfThen(Msg[Length(Msg)] = '.', '', '.');
Msg := Msg + IfThen(EMsg = '', '', sLineBreak + EMsg);
Create(Msg, ACode);
end;
end.
| 28.0025 | 185 | 0.630346 |
f1e3732196a4dc9164568bec52bb089ab1f7cf1e | 21,368 | pas | Pascal | Jx3Full/Source/Source/Tools/LuaWorkshop/synedit/Source/SynHighlighterGeneral.pas | RivenZoo/FullSource | cfd7fd7ad422fd2dae5d657a18839c91ff9521fd | [
"MIT"
]
| 2 | 2021-07-31T15:35:01.000Z | 2022-02-28T05:54:54.000Z | Jx3Full/Source/Source/Tools/LuaWorkshop/synedit/Source/SynHighlighterGeneral.pas | RivenZoo/FullSource | cfd7fd7ad422fd2dae5d657a18839c91ff9521fd | [
"MIT"
]
| null | null | null | Jx3Full/Source/Source/Tools/LuaWorkshop/synedit/Source/SynHighlighterGeneral.pas | RivenZoo/FullSource | cfd7fd7ad422fd2dae5d657a18839c91ff9521fd | [
"MIT"
]
| 5 | 2021-02-03T10:25:39.000Z | 2022-02-23T07:08:37.000Z | {-------------------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
the specific language governing rights and limitations under the License.
The Original Code is: SynHighlighterGeneral.pas, released 2000-04-07.
The Original Code is based on the mwGeneralSyn.pas file from the
mwEdit component suite by Martin Waldenburg and other developers, the Initial
Author of this file is Martin Waldenburg.
Portions written by Martin Waldenburg are copyright 1999 Martin Waldenburg.
All Rights Reserved.
Contributors to the SynEdit and mwEdit projects are listed in the
Contributors.txt file.
Alternatively, the contents of this file may be used under the terms of the
GNU General Public License Version 2 or later (the "GPL"), in which case
the provisions of the GPL are applicable instead of those above.
If you wish to allow use of your version of this file only under the terms
of the GPL and not to allow others to use your version of this file
under the MPL, indicate your decision by deleting the provisions above and
replace them with the notice and other provisions required by the GPL.
If you do not delete the provisions above, a recipient may use your version
of this file under either the MPL or the GPL.
$Id: SynHighlighterGeneral.pas,v 1.1 2005/06/20 03:13:25 zhujianqiu Exp $
You may retrieve the latest version of this file at the SynEdit home page,
located at http://SynEdit.SourceForge.net
Known Issues:
-------------------------------------------------------------------------------}
{
@abstract(Provides a customizable highlighter for SynEdit)
@author(Martin Waldenburg, converted to SynEdit by Michael Hieke)
@created(1999)
@lastmod(2000-06-23)
The SynHighlighterGeneral unit provides a customizable highlighter for SynEdit.
}
{$IFNDEF QSYNHIGHLIGHTERGENERAL}
unit SynHighlighterGeneral;
{$ENDIF}
{$I SynEdit.inc}
interface
uses
{$IFDEF SYN_CLX}
QGraphics,
QSynEditTypes,
QSynEditHighlighter,
{$ELSE}
Windows,
Graphics,
SynEditTypes,
SynEditHighlighter,
{$ENDIF}
SysUtils,
Classes;
type
TtkTokenKind = (tkComment, tkIdentifier, tkKey, tkNull, tkNumber,
tkPreprocessor, tkSpace, tkString, tkSymbol, tkUnknown);
TCommentStyle = (csAnsiStyle, csPasStyle, csCStyle, csAsmStyle, csBasStyle,
csCPPStyle);
TCommentStyles = set of TCommentStyle;
TRangeState = (rsANil, rsAnsi, rsPasStyle, rsCStyle, rsUnKnown);
TStringDelim = (sdSingleQuote, sdDoubleQuote);
TProcTableProc = procedure of object;
type
TSynGeneralSyn = class(TSynCustomHighlighter)
private
fRange: TRangeState;
fLine: PChar;
fProcTable: array[#0..#255] of TProcTableProc;
Run: LongInt;
fTokenPos: Integer;
fTokenID: TtkTokenKind;
fLineNumber : Integer;
fCommentAttri: TSynHighlighterAttributes;
fIdentifierAttri: TSynHighlighterAttributes;
fKeyAttri: TSynHighlighterAttributes;
fNumberAttri: TSynHighlighterAttributes;
fPreprocessorAttri: TSynHighlighterAttributes;
fSpaceAttri: TSynHighlighterAttributes;
fStringAttri: TSynHighlighterAttributes;
fSymbolAttri: TSynHighlighterAttributes;
fKeyWords: TStrings;
fComments: TCommentStyles;
fStringDelimCh: char;
fIdentChars: TSynIdentChars;
fDetectPreprocessor: boolean;
procedure AsciiCharProc;
procedure BraceOpenProc;
procedure PointCommaProc;
procedure CRProc;
procedure IdentProc;
procedure IntegerProc;
procedure LFProc;
procedure NullProc;
procedure NumberProc;
procedure RoundOpenProc;
procedure SlashProc;
procedure SpaceProc;
procedure StringProc;
procedure UnknownProc;
procedure MakeMethodTables;
procedure AnsiProc;
procedure PasStyleProc;
procedure CStyleProc;
procedure SetKeyWords(const Value: TStrings);
procedure SetComments(Value: TCommentStyles);
function GetStringDelim: TStringDelim;
procedure SetStringDelim(const Value: TStringDelim);
function GetIdentifierChars: string;
procedure SetIdentifierChars(const Value: string);
procedure SetDetectPreprocessor(Value: boolean);
protected
function GetIdentChars: TSynIdentChars; override;
public
class function GetLanguageName: string; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetDefaultAttribute(Index: integer): TSynHighlighterAttributes;
override;
function GetEol: Boolean; override;
function GetRange: Pointer; override;
function GetTokenID: TtkTokenKind;
function GetToken: String; override;
function GetTokenAttribute: TSynHighlighterAttributes; override;
function GetTokenKind: integer; override;
function GetTokenPos: Integer; override;
function IsKeyword(const AKeyword: string): boolean; override; //mh 2000-11-08
procedure Next; override;
procedure ResetRange; override;
procedure SetRange(Value: Pointer); override;
procedure SetLine(NewValue: String; LineNumber: Integer); override;
{$IFNDEF SYN_CLX}
function SaveToRegistry(RootKey: HKEY; Key: string): boolean; override;
function LoadFromRegistry(RootKey: HKEY; Key: string): boolean; override;
{$ENDIF}
published
property CommentAttri: TSynHighlighterAttributes read fCommentAttri
write fCommentAttri;
property Comments: TCommentStyles read fComments write SetComments;
property DetectPreprocessor: boolean read fDetectPreprocessor
write SetDetectPreprocessor;
property IdentifierAttri: TSynHighlighterAttributes read fIdentifierAttri
write fIdentifierAttri;
property IdentifierChars: string read GetIdentifierChars
write SetIdentifierChars;
property KeyAttri: TSynHighlighterAttributes read fKeyAttri write fKeyAttri;
property KeyWords: TStrings read fKeyWords write SetKeyWords;
property NumberAttri: TSynHighlighterAttributes read fNumberAttri
write fNumberAttri;
property PreprocessorAttri: TSynHighlighterAttributes
read fPreprocessorAttri write fPreprocessorAttri;
property SpaceAttri: TSynHighlighterAttributes read fSpaceAttri
write fSpaceAttri;
property StringAttri: TSynHighlighterAttributes read fStringAttri
write fStringAttri;
property SymbolAttri: TSynHighlighterAttributes read fSymbolAttri
write fSymbolAttri;
property StringDelim: TStringDelim read GetStringDelim write SetStringDelim
default sdSingleQuote;
end;
implementation
uses
{$IFDEF SYN_CLX}
QSynEditStrConst;
{$ELSE}
SynEditStrConst;
{$ENDIF}
var
Identifiers: array[#0..#255] of ByteBool;
mHashTable: array[#0..#255] of Integer;
procedure MakeIdentTable;
var
I, J: Char;
begin
for I := #0 to #255 do
begin
Case I of
'_', '0'..'9', 'a'..'z', 'A'..'Z': Identifiers[I] := True;
else Identifiers[I] := False;
end;
J := UpCase(I);
Case I in ['_', 'a'..'z', 'A'..'Z'] of
True: mHashTable[I] := Ord(J) - 64
else mHashTable[I] := 0;
end;
end;
end;
function TSynGeneralSyn.IsKeyword(const AKeyword: string): boolean; //mh 2000-11-08
var
First, Last, I, Compare: Integer;
Token: String;
begin
First := 0;
Last := fKeywords.Count - 1;
Result := False;
Token := UpperCase(AKeyword);
while First <= Last do
begin
I := (First + Last) shr 1;
Compare := AnsiCompareText(fKeywords[i], Token);
if Compare = 0 then
begin
Result := True;
break;
end else
if Compare < 0 then First := I + 1 else Last := I - 1;
end;
end; { IsKeyWord }
procedure TSynGeneralSyn.MakeMethodTables;
var
I: Char;
begin
for I := #0 to #255 do
case I of
'#': fProcTable[I] := AsciiCharProc;
'{': fProcTable[I] := BraceOpenProc;
';': fProcTable[I] := PointCommaProc;
#13: fProcTable[I] := CRProc;
'A'..'Z', 'a'..'z', '_': fProcTable[I] := IdentProc;
'$': fProcTable[I] := IntegerProc;
#10: fProcTable[I] := LFProc;
#0: fProcTable[I] := NullProc;
'0'..'9': fProcTable[I] := NumberProc;
'(': fProcTable[I] := RoundOpenProc;
'/': fProcTable[I] := SlashProc;
#1..#9, #11, #12, #14..#32: fProcTable[I] := SpaceProc;
else fProcTable[I] := UnknownProc;
end;
fProcTable[fStringDelimCh] := StringProc;
end;
constructor TSynGeneralSyn.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fKeyWords := TStringList.Create;
TStringList(fKeyWords).Sorted := True;
TStringList(fKeyWords).Duplicates := dupIgnore;
fCommentAttri := TSynHighlighterAttributes.Create(SYNS_AttrComment);
fCommentAttri.Style := [fsItalic];
AddAttribute(fCommentAttri);
fIdentifierAttri := TSynHighlighterAttributes.Create(SYNS_AttrIdentifier);
AddAttribute(fIdentifierAttri);
fKeyAttri := TSynHighlighterAttributes.Create(SYNS_AttrReservedWord);
fKeyAttri.Style := [fsBold];
AddAttribute(fKeyAttri);
fNumberAttri := TSynHighlighterAttributes.Create(SYNS_AttrNumber);
AddAttribute(fNumberAttri);
fSpaceAttri := TSynHighlighterAttributes.Create(SYNS_AttrSpace);
AddAttribute(fSpaceAttri);
fStringAttri := TSynHighlighterAttributes.Create(SYNS_AttrString);
AddAttribute(fStringAttri);
fSymbolAttri := TSynHighlighterAttributes.Create(SYNS_AttrSymbol);
AddAttribute(fSymbolAttri);
fPreprocessorAttri := TSynHighlighterAttributes.Create(SYNS_AttrPreprocessor);
AddAttribute(fPreprocessorAttri);
SetAttributesOnChange(DefHighlightChange);
fStringDelimCh := '''';
fIdentChars := inherited GetIdentChars;
MakeMethodTables;
fRange := rsUnknown;
end; { Create }
destructor TSynGeneralSyn.Destroy;
begin
fKeyWords.Free;
inherited Destroy;
end; { Destroy }
procedure TSynGeneralSyn.SetLine(NewValue: String; LineNumber:Integer);
begin
fLine := PChar(NewValue);
Run := 0;
fLineNumber := LineNumber;
Next;
end; { SetLine }
procedure TSynGeneralSyn.AnsiProc;
begin
case fLine[Run] of
#0: NullProc;
#10: LFProc;
#13: CRProc;
else
fTokenID := tkComment;
repeat
if (fLine[Run] = '*') and (fLine[Run + 1] = ')') then begin
fRange := rsUnKnown;
Inc(Run, 2);
break;
end;
Inc(Run);
until fLine[Run] in [#0, #10, #13];
end;
end;
procedure TSynGeneralSyn.PasStyleProc;
begin
case fLine[Run] of
#0: NullProc;
#10: LFProc;
#13: CRProc;
else
fTokenID := tkComment;
repeat
if fLine[Run] = '}' then begin
fRange := rsUnKnown;
Inc(Run);
break;
end;
Inc(Run);
until fLine[Run] in [#0, #10, #13];
end;
end;
procedure TSynGeneralSyn.CStyleProc;
begin
case fLine[Run] of
#0: NullProc;
#10: LFProc;
#13: CRProc;
else
fTokenID := tkComment;
repeat
if (fLine[Run] = '*') and (fLine[Run + 1] = '/') then begin
fRange := rsUnKnown;
Inc(Run, 2);
break;
end;
Inc(Run);
until fLine[Run] in [#0, #10, #13];
end;
end;
procedure TSynGeneralSyn.AsciiCharProc;
begin
if fDetectPreprocessor then begin
fTokenID := tkPreprocessor;
repeat
inc(Run);
until fLine[Run] in [#0, #10, #13];
end else begin
fTokenID := tkString;
repeat
inc(Run);
until not (fLine[Run] in ['0'..'9']);
end;
end;
procedure TSynGeneralSyn.BraceOpenProc;
begin
if csPasStyle in fComments then
begin
fTokenID := tkComment;
fRange := rsPasStyle;
inc(Run);
while FLine[Run] <> #0 do
case FLine[Run] of
'}':
begin
fRange := rsUnKnown;
inc(Run);
break;
end;
#10: break;
#13: break;
else inc(Run);
end;
end else
begin
inc(Run);
fTokenID := tkSymbol;
end;
end;
procedure TSynGeneralSyn.PointCommaProc;
begin
if (csASmStyle in fComments) or (csBasStyle in fComments) then
begin
fTokenID := tkComment;
fRange := rsUnknown;
inc(Run);
while FLine[Run] <> #0 do
begin
fTokenID := tkComment;
inc(Run);
end;
end else
begin
inc(Run);
fTokenID := tkSymbol;
end;
end;
procedure TSynGeneralSyn.CRProc;
begin
fTokenID := tkSpace;
Inc(Run);
if fLine[Run] = #10 then Inc(Run);
end;
procedure TSynGeneralSyn.IdentProc;
begin
while Identifiers[fLine[Run]] do inc(Run);
if IsKeyWord(GetToken) then fTokenId := tkKey else fTokenId := tkIdentifier;
end;
procedure TSynGeneralSyn.IntegerProc;
begin
inc(Run);
fTokenID := tkNumber;
while FLine[Run] in ['0'..'9', 'A'..'F', 'a'..'f'] do inc(Run);
end;
procedure TSynGeneralSyn.LFProc;
begin
fTokenID := tkSpace;
inc(Run);
end;
procedure TSynGeneralSyn.NullProc;
begin
fTokenID := tkNull;
end;
procedure TSynGeneralSyn.NumberProc;
begin
inc(Run);
fTokenID := tkNumber;
while FLine[Run] in ['0'..'9', '.', 'e', 'E', 'x'] do
begin
case FLine[Run] of
'x': begin // handle C style hex numbers
IntegerProc;
break;
end;
'.':
if FLine[Run + 1] = '.' then break;
end;
inc(Run);
end;
end;
procedure TSynGeneralSyn.RoundOpenProc;
begin
inc(Run);
if csAnsiStyle in fComments then
begin
case fLine[Run] of
'*':
begin
fTokenID := tkComment;
fRange := rsAnsi;
inc(Run);
while fLine[Run] <> #0 do
case fLine[Run] of
'*':
if fLine[Run + 1] = ')' then
begin
fRange := rsUnKnown;
inc(Run, 2);
break;
end else inc(Run);
#10: break;
#13: break;
else inc(Run);
end;
end;
'.':
begin
inc(Run);
fTokenID := tkSymbol;
end;
else
begin
FTokenID := tkSymbol;
end;
end;
end else fTokenId := tkSymbol;
end;
procedure TSynGeneralSyn.SlashProc;
begin
Inc(Run);
case FLine[Run] of
'/':
begin
if csCPPStyle in fComments then
begin
fTokenID := tkComment;
Inc(Run);
while FLine[Run] <> #0 do
begin
case FLine[Run] of
#10, #13: break;
end;
inc(Run);
end;
end
else
fTokenId := tkSymbol;
end;
'*':
begin
if csCStyle in fComments then
begin
fTokenID := tkComment;
fRange := rsCStyle;
Inc(Run);
while fLine[Run] <> #0 do
case fLine[Run] of
'*':
if fLine[Run + 1] = '/' then
begin
fRange := rsUnKnown;
inc(Run, 2);
break;
end else inc(Run);
#10, #13:
break;
else
Inc(Run);
end;
end
else
fTokenId := tkSymbol;
end;
else
fTokenID := tkSymbol;
end;
end;
procedure TSynGeneralSyn.SpaceProc;
begin
inc(Run);
fTokenID := tkSpace;
while FLine[Run] in [#1..#9, #11, #12, #14..#32] do inc(Run);
end;
procedure TSynGeneralSyn.StringProc;
begin
fTokenID := tkString;
if (fLine[Run + 1] = fStringDelimCh) and (fLine[Run + 2] = fStringDelimCh) then
Inc(Run, 2);
repeat
case FLine[Run] of
#0, #10, #13: break;
end;
inc(Run);
until FLine[Run] = fStringDelimCh;
if FLine[Run] <> #0 then inc(Run);
end;
procedure TSynGeneralSyn.UnknownProc;
begin
inc(Run);
fTokenID := tkUnKnown;
end;
procedure TSynGeneralSyn.Next;
begin
fTokenPos := Run;
case fRange of
rsAnsi: AnsiProc;
rsPasStyle: PasStyleProc;
rsCStyle: CStyleProc;
else
fProcTable[fLine[Run]];
end;
end;
function TSynGeneralSyn.GetDefaultAttribute(Index: integer): TSynHighlighterAttributes;
begin
case Index of
SYN_ATTR_COMMENT: Result := fCommentAttri;
SYN_ATTR_IDENTIFIER: Result := fIdentifierAttri;
SYN_ATTR_KEYWORD: Result := fKeyAttri;
SYN_ATTR_STRING: Result := fStringAttri;
SYN_ATTR_WHITESPACE: Result := fSpaceAttri;
SYN_ATTR_SYMBOL: Result := fSymbolAttri;
else
Result := nil;
end;
end;
function TSynGeneralSyn.GetEol: Boolean;
begin
Result := fTokenId = tkNull;
end;
function TSynGeneralSyn.GetRange: Pointer;
begin
Result := Pointer(fRange);
end;
function TSynGeneralSyn.GetToken: String;
var
Len: LongInt;
begin
Len := Run - fTokenPos;
SetString(Result, (FLine + fTokenPos), Len);
end;
function TSynGeneralSyn.GetTokenID: TtkTokenKind;
begin
Result := fTokenId;
end;
function TSynGeneralSyn.GetTokenAttribute: TSynHighlighterAttributes;
begin
case fTokenID of
tkComment: Result := fCommentAttri;
tkIdentifier: Result := fIdentifierAttri;
tkKey: Result := fKeyAttri;
tkNumber: Result := fNumberAttri;
tkPreprocessor: Result := fPreprocessorAttri;
tkSpace: Result := fSpaceAttri;
tkString: Result := fStringAttri;
tkSymbol: Result := fSymbolAttri;
tkUnknown: Result := fSymbolAttri;
else
Result := nil;
end;
end;
function TSynGeneralSyn.GetTokenKind: integer;
begin
Result := Ord(fTokenId);
end;
function TSynGeneralSyn.GetTokenPos: Integer;
begin
Result := fTokenPos;
end;
procedure TSynGeneralSyn.ReSetRange;
begin
fRange := rsUnknown;
end;
procedure TSynGeneralSyn.SetRange(Value: Pointer);
begin
fRange := TRangeState(Value);
end;
procedure TSynGeneralSyn.SetKeyWords(const Value: TStrings);
var
i: Integer;
begin
if Value <> nil then
begin
Value.BeginUpdate;
for i := 0 to Value.Count - 1 do
Value[i] := UpperCase(Value[i]);
Value.EndUpdate;
end;
fKeyWords.Assign(Value);
DefHighLightChange(nil);
end;
procedure TSynGeneralSyn.SetComments(Value: TCommentStyles);
begin
if fComments <> Value then
begin
fComments := Value;
DefHighLightChange(Self);
end;
end;
class function TSynGeneralSyn.GetLanguageName: string;
begin
Result := SYNS_LangGeneral;
end;
{$IFNDEF SYN_CLX}
function TSynGeneralSyn.LoadFromRegistry(RootKey: HKEY; Key: string): boolean;
var
r: TBetterRegistry;
begin
r:= TBetterRegistry.Create;
try
r.RootKey := RootKey;
if r.OpenKeyReadOnly(Key) then begin
if r.ValueExists('KeyWords') then KeyWords.Text:= r.ReadString('KeyWords');
Result := inherited LoadFromRegistry(RootKey, Key);
end
else Result := false;
finally r.Free; end;
end;
function TSynGeneralSyn.SaveToRegistry(RootKey: HKEY; Key: string): boolean;
var
r: TBetterRegistry;
begin
r:= TBetterRegistry.Create;
try
r.RootKey := RootKey;
if r.OpenKey(Key,true) then begin
Result := true;
r.WriteString('KeyWords', KeyWords.Text);
Result := inherited SaveToRegistry(RootKey, Key);
end
else Result := false;
finally r.Free; end;
end;
{$ENDIF}
function TSynGeneralSyn.GetStringDelim: TStringDelim;
begin
if fStringDelimCh = '''' then
Result := sdSingleQuote
else
Result := sdDoubleQuote;
end;
procedure TSynGeneralSyn.SetStringDelim(const Value: TStringDelim);
var
newCh: char;
begin
case Value of
sdSingleQuote: newCh := '''';
else newCh := '"';
end; //case
if newCh <> fStringDelimCh then begin
fStringDelimCh := newCh;
MakeMethodTables;
end;
end;
function TSynGeneralSyn.GetIdentifierChars: string;
var
ch: char;
s: shortstring;
begin
s := '';
for ch := #0 to #255 do
if ch in fIdentChars then s := s + ch;
Result := s;
end;
procedure TSynGeneralSyn.SetIdentifierChars(const Value: string);
var
i: integer;
begin
fIdentChars := [];
for i := 1 to Length(Value) do begin
fIdentChars := fIdentChars + [Value[i]];
end; //for
WordBreakChars := WordBreakChars - fIdentChars;
end;
function TSynGeneralSyn.GetIdentChars: TSynIdentChars;
begin
Result := fIdentChars;
end;
procedure TSynGeneralSyn.SetDetectPreprocessor(Value: boolean);
begin
if Value <> fDetectPreprocessor then begin
fDetectPreprocessor := Value;
DefHighlightChange(Self);
end;
end;
initialization
MakeIdentTable;
{$IFNDEF SYN_CPPB_1}
RegisterPlaceableHighlighter(TSynGeneralSyn);
{$ENDIF}
end.
| 26.81054 | 96 | 0.640678 |
4748bd91166abef4bd10e5b1afc1bc1f52dec3d4 | 336 | dpr | Pascal | Diverses/D7/Football.dpr | joecare99/Public | 9eee060fbdd32bab33cf65044602976ac83f4b83 | [
"MIT"
]
| 11 | 2017-06-17T05:13:45.000Z | 2021-07-11T13:18:48.000Z | Diverses/D7/Football.dpr | joecare99/Public | 9eee060fbdd32bab33cf65044602976ac83f4b83 | [
"MIT"
]
| 2 | 2019-03-05T12:52:40.000Z | 2021-12-03T12:34:26.000Z | Diverses/D7/Football.dpr | joecare99/Public | 9eee060fbdd32bab33cf65044602976ac83f4b83 | [
"MIT"
]
| 6 | 2017-09-07T09:10:09.000Z | 2022-02-19T20:19:58.000Z | program Football;
uses
Forms,
Main in '..\Source\D7Demos\Football\Main.pas' {MainForm},
about in '..\Source\D7Demos\Football\about.pas' {AboutForm};
{$R *.RES}
begin
Application.Initialize;
Application.CreateForm(TMainForm, MainForm);
Application.CreateForm(TAboutForm, AboutForm);
Application.Run;
end.
| 21 | 63 | 0.702381 |
475b4a470e050bca7295f06e9c4b561ea6ac66df | 124 | pas | Pascal | test_pascal/test_array/test_char_array_access.pas | tranleduy2000/pascalnide | c7f3f79ecf4cf6a81b32c7d389aad7f4034c8f01 | [
"Apache-2.0"
]
| 81 | 2017-05-07T13:26:56.000Z | 2022-03-03T19:39:15.000Z | test_pascal/test_array/test_char_array_access.pas | tranleduy2000/pascalnide | c7f3f79ecf4cf6a81b32c7d389aad7f4034c8f01 | [
"Apache-2.0"
]
| 52 | 2017-06-13T08:46:43.000Z | 2021-06-09T09:50:07.000Z | test_pascal/test_array/test_char_array_access.pas | tranleduy2000/pascalnide | c7f3f79ecf4cf6a81b32c7d389aad7f4034c8f01 | [
"Apache-2.0"
]
| 28 | 2017-05-22T21:09:58.000Z | 2021-09-07T13:05:27.000Z | var
arr : array['a'..'z'] of string;
c : Char;
begin
arr['a'] := 'Hello';
for c := 'a' to 'z' do Write(arr[c]);
end. | 17.714286 | 39 | 0.5 |
83692e48fdf8cf0f5cda5a59fc8387f69820d3f8 | 20,644 | pas | Pascal | memory/0076.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| 11 | 2015-12-12T05:13:15.000Z | 2020-10-14T13:32:08.000Z | memory/0076.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| null | null | null | memory/0076.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| 8 | 2017-05-05T05:24:01.000Z | 2021-07-03T20:30:09.000Z | {
witold@aed.dsto.gov.au
{--------------------------------------------------------------------------}
Program TestMat(Input,Output);
{ Description: Allocating/deallocating 2D arrays larger than 64kB in size }
{ Date : 12 December 1994 }
{ Author : Witold Waldman }
{ }
{ This is a sample program showing how to go about using the matrix memory }
{ allocation/deallocation functions contained in the unit MATMEM. }
{ }
{ In this example, a two-dimensional array of double precision numbers is }
{ allocated. The total size of the array is chosen to be greater than the }
{ maximum size of a 64kB data segment to illustrate how the techniques }
{ that are implemented here can be used to work with large matrices. }
{ }
{ After the array storage has been created, each element of the array is }
{ filled with a unique number, and the last element in each row is then }
{ displayed on the screen. }
{ }
{ Finally, the array is deallocated and the heap is checked to see if any }
{ memory leaks have occurred. }
{ }
{ Because all memory allocation occurs on the heap at run-time, the use }
{ of extended memory is automatic if the Borland Pascal program is }
{ compiled as a protected mode application. }
{ }
{ The basic idea for the approach used here was taken from a short article }
{ by William F. Polik (PC Tech Journal, December 1986, p. 49). }
{ }
{ Feel free to use this code as you see fit, and I hope that it provides }
{ a useful example of how large arrays can be allocated and accessed from }
{ Turbo Pascal without suffering too greatly from the 64kB segment limit }
{ imposed by the medium memory model used by the compiler. }
{ }
{ NOTE: The source code to the MATMEM unit is located at the bottom of }
{ this program. Just cut and paste it into a separate file. }
{$N+}
{$E+}
{$M 65520,250000,655360 }
Uses CRT,MATMEM;
var
AD : pArrayDD; { Pointer to a two-dimensional array of doubles }
NR : word; { Maximum row dimension of array }
NC : word; { Maximum column dimension of array }
i : word; { Index variable used for traversing rows }
j : word; { Index variable used for traversing columns }
MemBefore : longint; { Memory available before array allocation }
MemAlloc : longint; { Memory available after array allocation }
begin
ClrScr;
{ Configure the size of the 2D matrix we wish to allocate }
NR := 2;
NC := MaxSizeArrayD;
{ Allocate dynamic memory for the 2D array }
MemBefore := MaxAvail;
AD := NewArrayDD(NR,NC);
MemAlloc := MaxAvail;
{ Check to see whether the pointer is nil. If it is, then }
{ the allocation of the array failed. }
If AD = nil then
begin
Writeln('Not enough dynamic memory available for array.');
Halt;
end;
{ Write some info about what was just allocated on the heap }
Writeln('Dynamic memory allocated for array = ',MemBefore-MaxAvail,' bytes');
Writeln;
Writeln('Number of array elements = ',(NR+1)*(NC+1));
Writeln;
{ Proceed to access each element in the array and store a unique number }
{ in each and every array location. Display the value of the last element }
{ in each row of the array for checking purposes. }
For i := 0 to NR do
begin
For j := 0 to NC do
begin
AD^[i]^[j] := j*1.0E0 + i*100000.0E0;
end;
Writeln('Selected array contents: AD^[',i,']^[',NC,'] = ',
AD^[i]^[NC]:10:1);
end;
{ Deallocate dynamic memory for the 2D array }
AD := DisposeArrayDD(AD,NR,NC);
Writeln;
Writeln('Dynamic memory deallocated = ',MaxAvail-MemAlloc,' bytes');
If MaxAvail = MemBefore then
begin
Writeln;
Writeln('No memory leaks detected.');
end
else
begin
Writeln;
Writeln('A memory leak has been detected.');
end;
end.
{---------------------------------------------------------------------------}
{$N+}
{$E+}
UNIT MATMEM;
INTERFACE
const
PtrSize = SizeOf(Pointer);
MaxSegmentSize = 65535;
MaxSizeArrayP = MaxSegmentSize div PtrSize - 1;
MaxSizeArrayR = MaxSegmentSize div SizeOf(Real) - 1;
MaxSizeArrayS = MaxSegmentSize div SizeOf(Single) - 1;
MaxSizeArrayD = MaxSegmentSize div SizeOf(Double) - 1;
MaxSizeArrayI = MaxSegmentSize div SizeOf(Integer) - 1;
type
ArrayPtr = array [0..MaxSizeArrayP] of Pointer;
ArrayR = array [0..MaxSizeArrayR] of Real;
ArrayS = array [0..MaxSizeArrayS] of Single;
ArrayD = array [0..MaxSizeArrayD] of Double;
ArrayI = array [0..MaxSizeArrayI] of Integer;
ArrayRR = array [0..MaxSizeArrayP-1] of ^ArrayR;
ArraySS = array [0..MaxSizeArrayP-1] of ^ArrayS;
ArrayDD = array [0..MaxSizeArrayP-1] of ^ArrayD;
ArrayII = array [0..MaxSizeArrayP-1] of ^ArrayI;
pArrayR = ^ArrayR;
pArrayS = ^ArrayS;
pArrayD = ^ArrayD;
pArrayI = ^ArrayI;
pArrayRR = ^ArrayRR;
pArraySS = ^ArraySS;
pArrayDD = ^ArrayDD;
pArrayII = ^ArrayII;
{ Functions for allocating/deallocating single dimensional arrays. }
{ }
{ NRmax = maximum number of rows allocated/deallocated. }
{ NCmax = maximum number of columns allocated/deallocated. }
function NewArrayS(Nmax:Word):Pointer;
function DisposeArrayS(A:Pointer; Nmax:Word):Pointer;
function NewArrayD(Nmax:Word):Pointer;
function DisposeArrayD(A:Pointer; Nmax:Word):Pointer;
function NewArrayI(Nmax:Word):Pointer;
function DisposeArrayI(A:Pointer; Nmax:Word):Pointer;
function NewArrayR(Nmax:Word):Pointer;
function DisposeArrayR(A:Pointer; Nmax:Word):Pointer;
{ Functions for allocating/deallocating two dimensional arrays. }
{ }
{ NRmax = maximum number of rows allocated/deallocated. }
{ NCmax = maximum number of columns allocated/deallocated. }
function NewArraySS(NRmax,NCmax:Word):Pointer;
function DisposeArraySS(A:Pointer; NRmax,NCmax:Word):Pointer;
function NewArrayDD(NRmax,NCmax:Word):Pointer;
function DisposeArrayDD(A:Pointer; NRmax,NCmax:Word):Pointer;
function NewArrayII(NRmax,NCmax:Word):Pointer;
function DisposeArrayII(A:Pointer; NRmax,NCmax:Word):Pointer;
function NewArrayRR(NRmax,NCmax:Word):Pointer;
function DisposeArrayRR(A:Pointer; NRmax,NCmax:Word):Pointer;
IMPLEMENTATION
{==========================================================================}
function NewArray1D(Nmax:Word; DataSize:Integer):Pointer;
var
MemP : Word;
P : Pointer;
begin
MemP := (Nmax+1)*DataSize;
If MaxAvail >= MemP then
GetMem(P,MemP)
else
P := nil;
NewArray1D := P;
end;
{==========================================================================}
function DisposeArray1D(A:Pointer; Nmax:Word; DataSize:Integer):Pointer;
begin
If A <> nil then
begin
FreeMem(A,(Nmax+1)*DataSize);
DisposeArray1D := nil;
end;
end;
{==========================================================================}
function DisposeArray2D(A:Pointer; NRmax,NCmax:Word; DataSize:Integer):Pointer;
var
I : Word;
Q : ^ArrayPtr;
begin
If A <> nil then
begin
Q := A;
For I := 0 to NRmax do
begin
If Q^[I] <> nil then
FreeMem(Q^[I],(NCmax+1)*DataSize);
end;
FreeMem(A,(NRmax+1)*PtrSize);
DisposeArray2D := nil;
end;
end;
{==========================================================================}
function NewArray2D(NRmax,NCmax:Word; DataSize:Integer):Pointer;
var
Error : Boolean;
I : Word;
MemP : Word; { Memory for pointers to each row of data }
MemR : Word; { Memory for row of data }
P : ^ArrayPtr;
begin
MemP := (NRmax+1)*PtrSize;
If MaxAvail >= MemP then
GetMem(P,MemP)
else
P := nil;
If P <> nil then
begin
Error := false;
MemR := (NCmax+1)*DataSize;
For I := 0 to NRmax do
begin
If MaxAvail >= MemR then
GetMem(P^[I],MemR)
else
begin
Error := true;
P^[I] := nil;
end;
end;
If Error then
begin
P := DisposeArray2D(P,NRmax,NCmax,DataSize);
end;
end;
NewArray2D := P;
end;
{==========================================================================}
function NewArrayS(Nmax:Word):Pointer;
begin
NewArrayS := NewArray1D(Nmax,SizeOf(Single));
end;
{==========================================================================}
function DisposeArrayS(A:Pointer; Nmax:Word):Pointer;
begin
DisposeArrayS := DisposeArray1D(A,Nmax,SizeOf(Single));
end;
{==========================================================================}
function NewArrayD(Nmax:Word):Pointer;
begin
NewArrayD := NewArray1D(Nmax,SizeOf(Double));
end;
{==========================================================================}
function DisposeArrayD(A:Pointer; Nmax:Word):Pointer;
begin
DisposeArrayD := DisposeArray1D(A,Nmax,SizeOf(Double));
end;
{==========================================================================}
function NewArrayI(Nmax:Word):Pointer;
begin
NewArrayI := NewArray1D(Nmax,SizeOf(Integer));
end;
{==========================================================================}
function DisposeArrayI(A:Pointer; Nmax:Word):Pointer;
begin
DisposeArrayI := DisposeArray1D(A,Nmax,SizeOf(Integer));
end;
{==========================================================================}
function NewArrayR(Nmax:Word):Pointer;
begin
NewArrayR := NewArray1D(Nmax,SizeOf(Real));
end;
{==========================================================================}
function DisposeArrayR(A:Pointer; Nmax:Word):Pointer;
begin
DisposeArrayR := DisposeArray1D(A,Nmax,SizeOf(Real));
end;
{==========================================================================}
function NewArraySS(NRmax,NCmax:Word):Pointer;
begin
NewArraySS := NewArray2D(NRmax,NCmax,SizeOf(Single));
end;
{==========================================================================}
function DisposeArraySS(A:Pointer; NRmax,NCmax:Word):Pointer;
begin
DisposeArraySS := DisposeArray2D(A,NRmax,NCmax,SizeOf(Single));
end;
{==========================================================================}
function NewArrayDD(NRmax,NCmax:Word):Pointer;
begin
NewArrayDD := NewArray2D(NRmax,NCmax,SizeOf(Double));
end;
{==========================================================================}
function DisposeArrayDD(A:Pointer; NRmax,NCmax:Word):Pointer;
begin
DisposeArrayDD := DisposeArray2D(A,NRmax,NCmax,SizeOf(Double));
end;
{==========================================================================}
function NewArrayII(NRmax,NCmax:Word):Pointer;
begin
NewArrayII := NewArray2D(NRmax,NCmax,SizeOf(Integer));
end;
{==========================================================================}
function DisposeArrayII(A:Pointer; NRmax,NCmax:Word):Pointer;
begin
DisposeArrayII := DisposeArray2D(A,NRmax,NCmax,SizeOf(Integer));
end;
{==========================================================================}
function NewArrayRR(NRmax,NCmax:Word):Pointer;
begin
NewArrayRR := NewArray2D(NRmax,NCmax,SizeOf(Real));
end;
{==========================================================================}
function DisposeArrayRR(A:Pointer; NRmax,NCmax:Word):Pointer;
begin
DisposeArrayRR := DisposeArray2D(A,NRmax,NCmax,SizeOf(Real));
end;
END.
{$N+}
{$E+}
UNIT MATMEM;
INTERFACE
const
PtrSize = SizeOf(Pointer);
MaxSegmentSize = 65535;
MaxSizeArrayP = MaxSegmentSize div PtrSize - 1;
MaxSizeArrayR = MaxSegmentSize div SizeOf(Real) - 1;
MaxSizeArrayS = MaxSegmentSize div SizeOf(Single) - 1;
MaxSizeArrayD = MaxSegmentSize div SizeOf(Double) - 1;
MaxSizeArrayI = MaxSegmentSize div SizeOf(Integer) - 1;
type
ArrayPtr = array [0..MaxSizeArrayP] of Pointer;
ArrayR = array [0..MaxSizeArrayR] of Real;
ArrayS = array [0..MaxSizeArrayS] of Single;
ArrayD = array [0..MaxSizeArrayD] of Double;
ArrayI = array [0..MaxSizeArrayI] of Integer;
ArrayRR = array [0..MaxSizeArrayP] of ^ArrayR;
ArraySS = array [0..MaxSizeArrayP] of ^ArrayS;
ArrayDD = array [0..MaxSizeArrayP] of ^ArrayD;
ArrayII = array [0..MaxSizeArrayP] of ^ArrayI;
pArrayR = ^ArrayR;
pArrayS = ^ArrayS;
pArrayD = ^ArrayD;
pArrayI = ^ArrayI;
pArrayRR = ^ArrayRR;
pArraySS = ^ArraySS;
pArrayDD = ^ArrayDD;
pArrayII = ^ArrayII;
{ Functions for allocating/deallocating single dimensional arrays. }
{ }
{ NRmax = maximum number of rows allocated/deallocated. }
{ NCmax = maximum number of columns allocated/deallocated. }
function NewArrayS(Nmax:Word):Pointer;
function DisposeArrayS(A:Pointer; Nmax:Word):Pointer;
function NewArrayD(Nmax:Word):Pointer;
function DisposeArrayD(A:Pointer; Nmax:Word):Pointer;
function NewArrayI(Nmax:Word):Pointer;
function DisposeArrayI(A:Pointer; Nmax:Word):Pointer;
function NewArrayR(Nmax:Word):Pointer;
function DisposeArrayR(A:Pointer; Nmax:Word):Pointer;
{ Functions for allocating/deallocating two dimensional arrays. }
{ }
{ NRmax = maximum number of rows allocated/deallocated. }
{ NCmax = maximum number of columns allocated/deallocated. }
function NewArraySS(NRmax,NCmax:Word):Pointer;
function DisposeArraySS(A:Pointer; NRmax,NCmax:Word):Pointer;
function NewArrayDD(NRmax,NCmax:Word):Pointer;
function DisposeArrayDD(A:Pointer; NRmax,NCmax:Word):Pointer;
function NewArrayII(NRmax,NCmax:Word):Pointer;
function DisposeArrayII(A:Pointer; NRmax,NCmax:Word):Pointer;
function NewArrayRR(NRmax,NCmax:Word):Pointer;
function DisposeArrayRR(A:Pointer; NRmax,NCmax:Word):Pointer;
IMPLEMENTATION
{==============================================================================
function NewArray1D(Nmax:Word; DataSize:Integer):Pointer;
var
MemP : Word;
P : Pointer;
begin
MemP := (Nmax+1)*DataSize;
If MaxAvail >= MemP then
GetMem(P,MemP)
else
P := nil;
NewArray1D := P;
end;
{==============================================================================
function DisposeArray1D(A:Pointer; Nmax:Word; DataSize:Integer):Pointer;
begin
If A <> nil then
begin
FreeMem(A,(Nmax+1)*DataSize);
DisposeArray1D := nil;
end;
end;
{==============================================================================
function DisposeArray2D(A:Pointer; NRmax,NCmax:Word; DataSize:Integer):Pointer;
var
I : Word;
Q : ^ArrayPtr;
begin
If A <> nil then
begin
Q := A;
For I := 0 to NRmax do
begin
If Q^[I] <> nil then
FreeMem(Q^[I],(NCmax+1)*DataSize);
end;
FreeMem(A,(NRmax+1)*PtrSize);
DisposeArray2D := nil;
end;
end;
{==========================================================================}
function NewArray2D(NRmax,NCmax:Word; DataSize:Integer):Pointer;
var
Error : Boolean;
I : Word;
MemP : Word; { Memory for pointers to each row of data }
MemR : Word; { Memory for row of data }
P : ^ArrayPtr;
begin
MemP := (NRmax+1)*PtrSize;
If MaxAvail >= MemP then
GetMem(P,MemP)
else
P := nil;
If P <> nil then
begin
Error := false;
MemR := (NCmax+1)*DataSize;
For I := 0 to NRmax do
begin
If MaxAvail >= MemR then
GetMem(P^[I],MemR)
else
begin
Error := true;
P^[I] := nil;
end;
end;
If Error then
begin
P := DisposeArray2D(P,NRmax,NCmax,DataSize);
end;
end;
NewArray2D := P;
end;
{==========================================================================}
function NewArrayS(Nmax:Word):Pointer;
begin
NewArrayS := NewArray1D(Nmax,SizeOf(Single));
end;
{==============================================================================
function DisposeArrayS(A:Pointer; Nmax:Word):Pointer;
begin
DisposeArrayS := DisposeArray1D(A,Nmax,SizeOf(Single));
end;
{==============================================================================
function NewArrayD(Nmax:Word):Pointer;
begin
NewArrayD := NewArray1D(Nmax,SizeOf(Double));
end;
{==============================================================================
function DisposeArrayD(A:Pointer; Nmax:Word):Pointer;
begin
DisposeArrayD := DisposeArray1D(A,Nmax,SizeOf(Double));
end;
{==============================================================================
function NewArrayI(Nmax:Word):Pointer;
begin
NewArrayI := NewArray1D(Nmax,SizeOf(Integer));
end;
{==============================================================================
function DisposeArrayI(A:Pointer; Nmax:Word):Pointer;
begin
DisposeArrayI := DisposeArray1D(A,Nmax,SizeOf(Integer));
end;
{==============================================================================
function NewArrayR(Nmax:Word):Pointer;
begin
NewArrayR := NewArray1D(Nmax,SizeOf(Real));
end;
{==============================================================================
function DisposeArrayR(A:Pointer; Nmax:Word):Pointer;
begin
DisposeArrayR := DisposeArray1D(A,Nmax,SizeOf(Real));
end;
{==============================================================================
function NewArraySS(NRmax,NCmax:Word):Pointer;
begin
NewArraySS := NewArray2D(NRmax,NCmax,SizeOf(Single));
end;
{==============================================================================
function DisposeArraySS(A:Pointer; NRmax,NCmax:Word):Pointer;
begin
DisposeArraySS := DisposeArray2D(A,NRmax,NCmax,SizeOf(Single));
end;
{==============================================================================
function NewArrayDD(NRmax,NCmax:Word):Pointer;
begin
NewArrayDD := NewArray2D(NRmax,NCmax,SizeOf(Double));
end;
{==============================================================================
function DisposeArrayDD(A:Pointer; NRmax,NCmax:Word):Pointer;
begin
DisposeArrayDD := DisposeArray2D(A,NRmax,NCmax,SizeOf(Double));
end;
{==============================================================================
function NewArrayII(NRmax,NCmax:Word):Pointer;
begin
NewArrayII := NewArray2D(NRmax,NCmax,SizeOf(Integer));
end;
{==============================================================================
function DisposeArrayII(A:Pointer; NRmax,NCmax:Word):Pointer;
begin
DisposeArrayII := DisposeArray2D(A,NRmax,NCmax,SizeOf(Integer));
end;
{==============================================================================
function NewArrayRR(NRmax,NCmax:Word):Pointer;
begin
NewArrayRR := NewArray2D(NRmax,NCmax,SizeOf(Real));
end;
{==============================================================================
function DisposeArrayRR(A:Pointer; NRmax,NCmax:Word):Pointer;
begin
DisposeArrayRR := DisposeArray2D(A,NRmax,NCmax,SizeOf(Real));
end;
END.
| 26.775616 | 80 | 0.51148 |
47571958d55e108248e45f796bc2c949c22ae4a3 | 500 | pas | Pascal | solutions/beecrowd/1010/1010.pas | deniscostadsc/playground | 11fa8e2b708571940451f005e1f55af0b6e5764a | [
"MIT"
]
| 18 | 2015-01-22T04:08:51.000Z | 2022-01-08T22:36:47.000Z | solutions/beecrowd/1010/1010.pas | deniscostadsc/playground | 11fa8e2b708571940451f005e1f55af0b6e5764a | [
"MIT"
]
| 4 | 2016-04-25T12:32:46.000Z | 2021-06-15T18:01:30.000Z | solutions/beecrowd/1010/1010.pas | deniscostadsc/playground | 11fa8e2b708571940451f005e1f55af0b6e5764a | [
"MIT"
]
| 25 | 2015-03-02T06:21:51.000Z | 2021-09-12T20:49:21.000Z | Uses types,
strutils,
sysutils;
Var stdin : text;
line : String;
b, c, result : Double;
numbers : TStringDynArray;
begin
result := 0.0;
assign(stdin, '');
reset(stdin);
while not eof(stdin) do
begin
readln(stdin, line);
numbers := SplitString(line, ' ');
val(numbers[1], b);
val(numbers[2], c);
result := result + (b * c);
end;
close(stdin);
writeln(Format('VALOR A PAGAR: R$ %.2f', [result]));
end.
| 17.241379 | 56 | 0.528 |
6a7193f63e53eb67b7c0581cc6ea524bd31a3298 | 743 | pas | Pascal | 2016.Database/Assignment3/src/delphi/UnitTitle.pas | primetong/LearningCollectionOfWitt | a15dc8ac80618a3995c2b930c634b87ed8f1f0af | [
"MIT"
]
| null | null | null | 2016.Database/Assignment3/src/delphi/UnitTitle.pas | primetong/LearningCollectionOfWitt | a15dc8ac80618a3995c2b930c634b87ed8f1f0af | [
"MIT"
]
| 14 | 2020-06-30T20:52:56.000Z | 2022-03-02T14:53:18.000Z | 2016.Database/Assignment3/src/delphi/UnitTitle.pas | primetong/LearningCollectionOfWitt | a15dc8ac80618a3995c2b930c634b87ed8f1f0af | [
"MIT"
]
| null | null | null | unit UnitTitle;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, UnitMain;
type
TFrameTitle = class(TFrame)
ScrollBoxTitle: TScrollBox;
PanelTitle: TPanel;
LabeledEditDataBase: TLabeledEdit;
LabeledEditUserName: TLabeledEdit;
LabelTitle: TLabel;
private
{ Private declarations }
public
{ Public declarations }
constructor Create(AOwner: TComponent) ; override;
end;
implementation
{$R *.dfm}
constructor TFrameTitle.Create(AOwner: TComponent);
begin
{ inital main }
inherited Create(AOwner);
LabeledEditDataBase.Text := FormMain.Database.DefaultDatabase;
LabeledEditUserName.Text := FormMain.UserName;
end;
end.
| 20.081081 | 77 | 0.741588 |
8354c6fbd873cd7fd2daf2fff68b3874e3455796 | 346 | dpr | Pascal | ISBeer.dpr | PauloRamalho7/ISBeer | 2539598e1d2be066bda1a7bdc80d464cff26c519 | [
"MIT"
]
| 1 | 2020-07-18T17:37:31.000Z | 2020-07-18T17:37:31.000Z | ISBeer.dpr | PauloRamalho7/ISBeer | 2539598e1d2be066bda1a7bdc80d464cff26c519 | [
"MIT"
]
| null | null | null | ISBeer.dpr | PauloRamalho7/ISBeer | 2539598e1d2be066bda1a7bdc80d464cff26c519 | [
"MIT"
]
| 1 | 2020-07-18T17:37:35.000Z | 2020-07-18T17:37:35.000Z | program ISBeer;
uses
System.StartUpCopy,
FMX.Forms,
uFrmMain in 'uFrmMain.pas' {frmMain},
Datamodule in 'Datamodule.pas' {DataM: TDataModule};
{$R *.res}
begin
ReportMemoryLeaksOnShutdown := True;
Application.Initialize;
Application.CreateForm(TfrmMain, frmMain);
Application.CreateForm(TDataM, DataM);
Application.Run;
end.
| 19.222222 | 54 | 0.742775 |
8346b561effdac1a05fc603445d73ec3c3cfc71c | 24,079 | pas | Pascal | source/glscene/GLCadencer.pas | xtreme3d/xtreme3d | 0d9128d427f0f29290f1b9a2b25e7297ace900a9 | [
"FTL",
"MIT",
"BSD-3-Clause"
]
| 22 | 2016-04-23T07:54:02.000Z | 2021-07-11T14:21:40.000Z | source/glscene/GLCadencer.pas | xtreme3d/xtreme3d | 0d9128d427f0f29290f1b9a2b25e7297ace900a9 | [
"FTL",
"MIT",
"BSD-3-Clause"
]
| 62 | 2016-05-02T21:36:13.000Z | 2020-02-22T15:11:52.000Z | source/glscene/GLCadencer.pas | xtreme3d/xtreme3d | 0d9128d427f0f29290f1b9a2b25e7297ace900a9 | [
"FTL",
"MIT",
"BSD-3-Clause"
]
| 6 | 2017-12-29T18:38:33.000Z | 2020-07-26T18:52:19.000Z | {: GLCadencer<p>
Cadencing composant for GLScene (ease Progress processing)<p>
<b>History : </b><font size=-1><ul>
<li>28/06/04 - LR - Added some ifdef Win32 for Linux
<li>20/10/03 - EG - Fixed issues about cadencer destruction
<li>29/08/03 - EG - Added MinDeltaTime and FixedDeltaTime
<li>21/08/03 - EG - Fixed Application.OnIdle reset bug (Solerman Kaplon)
<li>04/07/03 - EG - Improved TimeMultiplier transitions (supports zero)
<li>06/06/03 - EG - Added cmApplicationIdle Mode
<li>19/05/03 - EG - Added Reset (Roberto Bussola)
<li>04/03/02 - EG - Added SetTimeMultiplier
<li>01/07/02 - EG - Added TGLCadencedComponent
<li>05/12/01 - EG - Fix in subscription mechanism (D6 IDE freezes gone?)
<li>30/11/01 - EG - Added IsBusy (thx Chris S)
<li>08/09/01 - EG - Added MaxDeltaTime limiter
<li>23/08/01 - EG - No more "deprecated" warning for Delphi6
<li>12/08/01 - EG - Protection against "timer flood"
<li>19/07/01 - EG - Fixed Memory Leak in RegisterASAPCadencer,
Added speed limiter TASAPHandler.WndProc
<li>01/02/01 - EG - Fixed "Freezing" when Enabled set to False
<li>08/10/00 - EG - Added TASAPHandler to support multiple ASAP cadencers
<li>19/06/00 - EG - Fixed TGLCadencer.Notification
<li>14/04/00 - EG - Minor fixes
<li>13/04/00 - EG - Creation
</ul></font>
}
unit GLCadencer;
interface
{$i GLScene.inc}
uses GLScene, Classes, GLMisc, GLCrossPlatform,
{$ifdef WIN32}
Windows, Controls, Messages, StdCtrls, Forms
{$endif}
{$ifdef LINUX}
QForms
{$endif}
;
type
// TGLCadencerMode
//
{: Determines how the TGLCadencer operates.<p>
- cmManual : you must trigger progress manually (in your code)<br>
- cmASAP : progress is triggered As Soon As Possible after a previous
progress (uses windows messages).
- cmApplicationIdle : will hook Application.OnIdle, this will overwrite
any previous event handle, and only one cadencer may be in this mode. }
TGLCadencerMode = (cmManual, cmASAP, cmApplicationIdle);
// TGLCadencerTimeReference
//
{: Determines which time reference the TGLCadencer should use.<p>
- cmRTC : the Real Time Clock is used (precise over long periods, but
not accurate to the millisecond, may limit your effective framerate
to less than 50 FPS on some systems)<br>
- cmPerformanceCounter : the windows performance counter is used (nice
precision, may derive over long periods, this is the default option
as it allows the smoothest animation on fast systems)<br>
- cmExternal : the CurrentTime property is used }
TGLCadencerTimeReference = (cmRTC, cmPerformanceCounter, cmExternal);
// TGLCadencer
//
{: This component allows auto-progression of animation.<p>
Basicly dropping this component and linking it to your TGLScene will send
it real-time progression events (time will be measured in seconds) while
keeping the CPU 100% busy if possible (ie. if things change in your scene).<p>
The progression time (the one you'll see in you progression events)
is calculated using (CurrentTime-OriginTime)*TimeMultiplier,
CurrentTime being either manually or automatically updated using
TimeReference (setting CurrentTime does NOT trigger progression). }
TGLCadencer = class (TComponent)
private
{ Private Declarations }
FSubscribedCadenceableComponents : TList;
FScene : TGLScene;
FTimeMultiplier : Double;
lastTime, downTime, lastMultiplier : Double;
FEnabled : Boolean;
FSleepLength : Integer;
FMode : TGLCadencerMode;
FTimeReference : TGLCadencerTimeReference;
FCurrentTime : Double;
FOriginTime : Double;
FMaxDeltaTime, FMinDeltaTime, FFixedDeltaTime : Double;
FOnProgress : TGLProgressEvent;
FProgressing : Integer;
protected
{ Protected Declarations }
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function StoreTimeMultiplier : Boolean;
procedure SetEnabled(const val : Boolean);
procedure SetScene(const val : TGLScene);
procedure SetMode(const val : TGLCadencerMode);
procedure SetTimeReference(const val : TGLCadencerTimeReference);
procedure SetTimeMultiplier(const val : Double);
{: Returns raw ref time (no multiplier, no offset) }
function GetRawReferenceTime : Double;
procedure RestartASAP;
procedure Loaded; override;
procedure OnIdleEvent(Sender: TObject; var Done: Boolean);
public
{ Public Declarations }
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure Subscribe(aComponent : TGLCadenceAbleComponent);
procedure UnSubscribe(aComponent : TGLCadenceAbleComponent);
{: Allows to manually trigger a progression.<p>
Time stuff is handled automatically.<br>
If cadencer is disabled, this functions does nothing. }
procedure Progress;
{: Adjusts CurrentTime if necessary, then returns its value. }
function GetCurrentTime : Double;
{: Returns True if a "Progress" is underway.<p>
Be aware that as long as IsBusy is True, the Cadencer may be
sending messages and progression calls to cadenceable components
and scenes. }
function IsBusy : Boolean;
{: Reset the time parameters and returns to zero.<p>}
procedure Reset;
{: Value soustracted to current time to obtain progression time. }
property OriginTime : Double read FOriginTime write FOriginTime;
{: Current time (manually or automatically set, see TimeReference). }
property CurrentTime : Double read FCurrentTime write FCurrentTime;
published
{ Published Declarations }
{: The TGLScene that will be cadenced (progressed). }
property Scene : TGLScene read FScene write SetScene;
{: Enables/Disables cadencing.<p>
Disabling won't cause a jump when restarting, it is working like
a play/pause (ie. may modify OriginTime to keep things smooth). }
property Enabled : Boolean read FEnabled write SetEnabled default True;
{: Defines how CurrentTime is updated.<p>
See TGLCadencerTimeReference.<br>
Dynamically changeing the TimeReference may cause a "jump". }
property TimeReference : TGLCadencerTimeReference read FTimeReference write SetTimeReference default cmPerformanceCounter;
{: Multiplier applied to the time reference.<p>
Zero isn't an allowed value, and be aware that if negative values
are accepted, they may not be supported by other GLScene objects.<br>
Changing the TimeMultiplier will alter OriginTime. }
property TimeMultiplier : Double read FTimeMultiplier write SetTimeMultiplier stored StoreTimeMultiplier;
{: Maximum value for deltaTime in progression events.<p>
If null or negative, no max deltaTime is defined, otherwise, whenever
an event whose actual deltaTime would be superior to MaxDeltaTime
occurs, deltaTime is clamped to this max, and the extra time is hidden
by the cadencer (it isn't visible in CurrentTime either).<br>
This option allows to limit progression rate in simulations where
high values would result in errors/random behaviour. }
property MaxDeltaTime : Double read FMaxDeltaTime write FMaxDeltaTime;
{: Minimum value for deltaTime in progression events.<p>
If superior to zero, this value specifies the minimum time step
between two progression events.<br>
This option allows to limit progression rate in simulations where
low values would result in errors/random behaviour. }
property MinDeltaTime : Double read FMinDeltaTime write FMinDeltaTime;
{: Fixed time-step value for progression events.<p>
If superior to zero, progression steps will happen with that fixed
delta time. The progression remains time based, so zero to N events
may be fired depending on the actual deltaTime (if deltaTime is
inferior to FixedDeltaTime, no event will be fired, if it is superior
to two times FixedDeltaTime, two events will be fired, etc.).<br>
This option allows to use fixed time steps in simulations (while the
animation and rendering itself may happen at a lower or higher
framerate). }
property FixedDeltaTime : Double read FFixedDeltaTime write FFixedDeltaTime;
{: Adjusts how progression events are triggered.<p>
See TGLCadencerMode. }
property Mode : TGLCadencerMode read FMode write SetMode default cmASAP;
{: Allows relinquishing time to other threads/processes.<p>
A "sleep" is issued BEFORE each progress if SleepLength>=0 (see
help for the "sleep" procedure in delphi for details). }
property SleepLength : Integer read FSleepLength write FSleepLength default -1;
{: Happens AFTER scene was progressed. }
property OnProgress : TGLProgressEvent read FOnProgress write FOnProgress;
end;
// TGLCustomCadencedComponent
//
{: Adds a property to connect/subscribe to a cadencer.<p> }
TGLCustomCadencedComponent = class (TGLUpdateAbleComponent)
private
{ Private Declarations }
FCadencer : TGLCadencer;
protected
{ Protected Declarations }
procedure SetCadencer(const val : TGLCadencer);
property Cadencer : TGLCadencer read FCadencer write SetCadencer;
public
{ Public Declarations }
destructor Destroy; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
end;
// TGLCadencedComponent
//
TGLCadencedComponent = class (TGLCustomCadencedComponent)
published
{ Published Declarations }
property Cadencer;
end;
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
implementation
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
uses SysUtils;
var
vCounterFrequency : Int64;
{$ifdef WIN32}
type
TASAPHandler = class
FWindowHandle : HWND;
FTooFastCounter : Integer;
FTimer : Cardinal;
procedure WndProc(var Msg: TMessage);
constructor Create;
destructor Destroy; override;
end;
var
vWMTickCadencer : Cardinal;
vASAPCadencerList : TList;
vHandler : TASAPHandler;
const
cTickGLCadencer = 'TickGLCadencer';
// RegisterASAPCadencer
//
procedure RegisterASAPCadencer(aCadencer : TGLCadencer);
begin
if aCadencer.Mode=cmASAP then begin
if not Assigned(vASAPCadencerList) then
vASAPCadencerList:=TList.Create;
if vASAPCadencerList.IndexOf(aCadencer)<0 then begin
vASAPCadencerList.Add(aCadencer);
if not Assigned(vHandler) then
vHandler:=TASAPHandler.Create;
end;
end else if aCadencer.Mode=cmApplicationIdle then
Application.OnIdle:=aCadencer.OnIdleEvent;
end;
// UnRegisterASAPCadencer
//
procedure UnRegisterASAPCadencer(aCadencer : TGLCadencer);
var
i : Integer;
begin
if aCadencer.Mode=cmASAP then begin
if Assigned(vASAPCadencerList) then begin
i:=vASAPCadencerList.IndexOf(aCadencer);
if i>=0 then
vASAPCadencerList[i]:=nil;
end;
end else if aCadencer.Mode=cmApplicationIdle then
Application.OnIdle:=nil;
end;
// ------------------
// ------------------ TASAPHandler ------------------
// ------------------
// Create
//
constructor TASAPHandler.Create;
begin
inherited Create;
{$ifdef GLS_DELPHI_6_UP}
FWindowHandle:=Classes.AllocateHWnd(WndProc);
{$else}
FWindowHandle:=AllocateHWnd(WndProc);
{$endif}
PostMessage(FWindowHandle, vWMTickCadencer, 0, 0);
end;
// Destroy
//
destructor TASAPHandler.Destroy;
begin
if FTimer<>0 then
KillTimer(FWindowHandle, FTimer);
{$ifdef GLS_DELPHI_6_UP}
Classes.DeallocateHWnd(FWindowHandle);
{$else}
DeallocateHWnd(FWindowHandle);
{$endif}
inherited Destroy;
end;
// WndProc
//
var
vWndProcInLoop : Boolean;
procedure TASAPHandler.WndProc(var Msg: TMessage);
var
i : Integer;
cad : TGLCadencer;
begin
// Windows.Beep(440, 10);
with Msg do begin
if Msg=WM_TIMER then begin
KillTimer(FWindowHandle, FTimer);
FTimer:=0;
end;
if (Msg<>WM_TIMER) and (Cardinal(GetMessageTime)=GetTickCount) then begin
// if we're going too fast, "sleep" for 1 msec
Inc(FTooFastCounter);
if FTooFastCounter>5000 then begin
if FTimer=0 then
FTimer:=SetTimer(FWindowHandle, 1, 1, nil);
FTooFastCounter:=0;
end;
end else FTooFastCounter:=0;
if FTimer<>0 then begin
Result:=0;
Exit;
end;
if not vWndProcInLoop then begin
vWndProcInLoop:=True;
try
if (Msg=vWMTickCadencer) or (Msg=WM_TIMER) then begin
// Progress
for i:=vASAPCadencerList.Count-1 downto 0 do begin
cad:=TGLCadencer(vASAPCadencerList[i]);
if Assigned(cad) and (cad.Mode=cmASAP)
and cad.Enabled and (cad.FProgressing=0) then begin
if Application.Terminated then begin
// force stop
cad.Enabled:=False
end else begin
try
// do stuff
cad.Progress;
except
Application.HandleException(Self);
// it faulted, stop it
cad.Enabled:=False
end
end;
end;
end;
// care for nils
vASAPCadencerList.Pack;
if vASAPCadencerList.Count=0 then begin
vASAPCadencerList.Free;
vASAPCadencerList:=nil;
vHandler.Free;
vHandler:=nil;
end else begin
// Prepare the return of the infernal loop...
PostMessage(FWindowHandle, vWMTickCadencer, 0, 0);
end;
end;
finally
vWndProcInLoop:=False;
end;
end;
Result:=0;
end;
end;
{$endif}
// ------------------
// ------------------ TGLCadencer ------------------
// ------------------
// Create
//
constructor TGLCadencer.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
FTimeReference:=cmPerformanceCounter;
downTime:=GetRawReferenceTime;
FOriginTime:=downTime;
FTimeMultiplier:=1;
FSleepLength:=-1;
Mode:=cmASAP;
Enabled:=True;
end;
// Destroy
//
destructor TGLCadencer.Destroy;
begin
Assert(FProgressing=0);
{$ifdef WIN32}
UnRegisterASAPCadencer(Self);
{$endif}
FSubscribedCadenceableComponents.Free;
FSubscribedCadenceableComponents:=nil;
inherited Destroy;
end;
// Subscribe
//
procedure TGLCadencer.Subscribe(aComponent : TGLCadenceAbleComponent);
begin
if not Assigned(FSubscribedCadenceableComponents) then
FSubscribedCadenceableComponents:=TList.Create;
if FSubscribedCadenceableComponents.IndexOf(aComponent)<0 then begin
FSubscribedCadenceableComponents.Add(aComponent);
aComponent.FreeNotification(Self);
end;
end;
// UnSubscribe
//
procedure TGLCadencer.UnSubscribe(aComponent : TGLCadenceAbleComponent);
var
i : Integer;
begin
if Assigned(FSubscribedCadenceableComponents) then begin
i:=FSubscribedCadenceableComponents.IndexOf(aComponent);
if i>=0 then begin
FSubscribedCadenceableComponents.Delete(i);
aComponent.RemoveFreeNotification(Self);
end;
end;
end;
// Notification
//
procedure TGLCadencer.Notification(AComponent: TComponent; Operation: TOperation);
begin
if Operation=opRemove then begin
if AComponent=FScene then FScene:=nil;
if Assigned(FSubscribedCadenceableComponents) then
FSubscribedCadenceableComponents.Remove(AComponent);
end;
inherited;
end;
// Loaded
//
procedure TGLCadencer.Loaded;
begin
inherited Loaded;
RestartASAP;
end;
// OnIdleEvent
//
procedure TGLCadencer.OnIdleEvent(Sender: TObject; var Done: Boolean);
begin
Progress;
Done:=False;
end;
// RestartASAP
//
procedure TGLCadencer.RestartASAP;
begin
if not (csLoading in ComponentState) then begin
{$ifdef WIN32}
if (Mode in [cmASAP, cmApplicationIdle]) and (not (csDesigning in ComponentState))
and Assigned(FScene) and Enabled then
RegisterASAPCadencer(Self)
else UnRegisterASAPCadencer(Self);
{$endif}
end;
end;
// SetEnabled
//
procedure TGLCadencer.SetEnabled(const val : Boolean);
begin
if FEnabled<>val then begin
FEnabled:=val;
if not (csDesigning in ComponentState) then begin
if Enabled then
FOriginTime:=FOriginTime+GetRawReferenceTime-downTime
else downTime:=GetRawReferenceTime;
RestartASAP;
end;
end;
end;
// SetScene
//
procedure TGLCadencer.SetScene(const val : TGLScene);
begin
if FScene<>val then begin
if Assigned(FScene) then
FScene.RemoveFreeNotification(Self);
FScene:=val;
if Assigned(FScene) then
FScene.FreeNotification(Self);
RestartASAP;
end;
end;
// SetTimeMultiplier
//
procedure TGLCadencer.SetTimeMultiplier(const val : Double);
var
rawRef : Double;
begin
if val<>FTimeMultiplier then begin
if val=0 then begin
lastMultiplier:=FTimeMultiplier;
Enabled:=False;
end else begin
rawRef:=GetRawReferenceTime;
if FTimeMultiplier=0 then begin
Enabled:=True;
// continuity of time:
// (rawRef-newOriginTime)*val = (rawRef-FOriginTime)*lastMultiplier
FOriginTime:=rawRef-(rawRef-FOriginTime)*lastMultiplier/val;
end else begin
// continuity of time:
// (rawRef-newOriginTime)*val = (rawRef-FOriginTime)*FTimeMultiplier
FOriginTime:=rawRef-(rawRef-FOriginTime)*FTimeMultiplier/val;
end;
end;
FTimeMultiplier:=val;
end;
end;
// StoreTimeMultiplier
//
function TGLCadencer.StoreTimeMultiplier : Boolean;
begin
Result:=(FTimeMultiplier<>1);
end;
// SetMode
//
procedure TGLCadencer.SetMode(const val : TGLCadencerMode);
begin
if FMode<>val then begin
{$ifdef WIN32}
if FMode<>cmManual then
UnRegisterASAPCadencer(Self);
{$endif}
FMode:=val;
RestartASAP;
end;
end;
// SetTimeReference
//
procedure TGLCadencer.SetTimeReference(const val : TGLCadencerTimeReference);
begin
// nothing more, yet
FTimeReference:=val;
end;
// Progress
//
procedure TGLCadencer.Progress;
var
deltaTime, newTime, totalDelta : Double;
i : Integer;
pt : TProgressTimes;
begin
// basic protection against infinite loops,
// shall never happen, unless there is a bug in user code
if FProgressing<0 then Exit;
if Enabled then begin
// avoid stalling everything else...
if SleepLength>=0 then
Sleep(SleepLength);
// in manual mode, the user is supposed to make sure messages are handled
// in Idle mode, this processing is implicit
if Mode=cmASAP then begin
Application.ProcessMessages;
{$ifdef WIN32}
if (not Assigned(vASAPCadencerList))
or (vASAPCadencerList.IndexOf(Self)<0) then Exit;
{$endif}
end;
end;
Inc(FProgressing);
try
if Enabled then begin
// One of the processed messages might have disabled us
if Enabled then begin
// ...and progress !
newTime:=GetCurrentTime;
deltaTime:=newTime-lastTime;
if (deltaTime>=MinDeltaTime) and (deltaTime>=FixedDeltaTime) then begin
if FMaxDeltaTime>0 then begin
if deltaTime>FMaxDeltaTime then begin
FOriginTime:=FOriginTime+(deltaTime-FMaxDeltaTime)/FTimeMultiplier;
deltaTime:=FMaxDeltaTime;
newTime:=lastTime+deltaTime;
end;
end;
totalDelta:=deltaTime;
if FixedDeltaTime>0 then
deltaTime:=FixedDeltaTime;
while totalDelta>=deltaTime do begin
lastTime:=lastTime+deltaTime;
if Assigned(FScene) and (deltaTime<>0) then begin
FProgressing:=-FProgressing;
try
FScene.Progress(deltaTime, lastTime);
finally
FProgressing:=-FProgressing;
end;
end;
pt.deltaTime:=deltaTime;
pt.newTime:=lastTime;
if Assigned(FSubscribedCadenceableComponents) then
for i:=0 to FSubscribedCadenceableComponents.Count-1 do
with TGLCadenceAbleComponent(FSubscribedCadenceableComponents[i]) do
DoProgress(pt);
if Assigned(FOnProgress) and (not (csDesigning in ComponentState)) then
FOnProgress(Self, deltaTime, newTime);
if deltaTime<=0 then Break;
totalDelta:=totalDelta-deltaTime;
end;
end;
end;
end;
finally
Dec(FProgressing);
end;
end;
// GetRawReferenceTime
//
function TGLCadencer.GetRawReferenceTime : Double;
var
counter : Int64;
begin
case FTimeReference of
cmRTC : // Real Time Clock
Result:=Now*(3600*24);
cmPerformanceCounter : begin // HiRes Performance Counter
QueryPerformanceCounter(counter);
Result:=counter/vCounterFrequency;
end;
cmExternal : // User defined value
Result:=FCurrentTime;
else
Result:=0;
Assert(False);
end;
end;
// GetCurrentTime
//
function TGLCadencer.GetCurrentTime : Double;
begin
Result:=(GetRawReferenceTime-FOriginTime)*FTimeMultiplier;
FCurrentTime:=Result;
end;
// IsBusy
//
function TGLCadencer.IsBusy : Boolean;
begin
Result:=(FProgressing<>0);
end;
// Reset
//
procedure TGLCadencer.Reset;
begin
lasttime:=0;
downTime:=GetRawReferenceTime;
FOriginTime:=downTime;
end;
// ------------------
// ------------------ TGLCustomCadencedComponent ------------------
// ------------------
// Destroy
//
destructor TGLCustomCadencedComponent.Destroy;
begin
Cadencer:=nil;
inherited Destroy;
end;
// Notification
//
procedure TGLCustomCadencedComponent.Notification(AComponent: TComponent; Operation: TOperation);
begin
if (Operation=opRemove) and (AComponent=FCadencer) then
Cadencer:=nil;
inherited;
end;
// SetCadencer
//
procedure TGLCustomCadencedComponent.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;
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
initialization
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// Get our Windows message ID
{$ifdef WIN32}
vWMTickCadencer:=RegisterWindowMessage(cTickGLCadencer);
{$endif}
// Preparation for high resolution timer
if not QueryPerformanceFrequency(vCounterFrequency) then
vCounterFrequency := 0;
finalization
{$ifdef WIN32}
FreeAndNil(vHandler);
FreeAndNil(vASAPCadencerList);
{$endif}
end.
| 32.105333 | 125 | 0.641846 |
f136a6dfde6afdaace79f4da4487b9292cf8ab73 | 941 | pas | Pascal | delphi/0027.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| 11 | 2015-12-12T05:13:15.000Z | 2020-10-14T13:32:08.000Z | delphi/0027.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| null | null | null | delphi/0027.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| 8 | 2017-05-05T05:24:01.000Z | 2021-07-03T20:30:09.000Z |
I wrote the following function to copy a file and keep the
attributes/date-time the same on the copied file. Hope this helps!
function FileCopy(source,dest: String): Boolean;
var
fSrc,fDst,len: Integer;
size: Longint;
buffer: packed array [0..2047] of Byte;
begin
Result := False; { Assume that it WONT work }
if source <> dest then begin
fSrc := FileOpen(source,fmOpenRead);
if fSrc >= 0 then begin
size := FileSeek(fSrc,0,2);
FileSeek(fSrc,0,0);
fDst := FileCreate(dest);
if fDst >= 0 then begin
while size > 0 do begin
len := FileRead(fSrc,buffer,sizeof(buffer));
FileWrite(fDst,buffer,len);
size := size - len;
end;
FileSetDate(fDst,FileGetDate(fSrc));
FileClose(fDst);
FileSetAttr(dest,FileGetAttr(source));
Result := True;
end;
FileClose(fSrc);
end;
end;
end;
| 28.515152 | 68 | 0.597237 |
834068fb174e745d8605f69a0285051eff93c2fc | 160,614 | pas | Pascal | thirdparty/OTL/OtlCommon.pas | d-mozulyov/Tiny.Library | d79fb2b2e9a28bc273a509814c3fc9fe970e077c | [
"MIT"
]
| 54 | 2020-05-25T09:35:57.000Z | 2021-12-29T03:12:06.000Z | thirdparty/OTL/OtlCommon.pas | d-mozulyov/Tiny.Rtti | d79fb2b2e9a28bc273a509814c3fc9fe970e077c | [
"MIT"
]
| 5 | 2019-10-07T01:34:58.000Z | 2020-05-14T18:04:36.000Z | thirdparty/OTL/OtlCommon.pas | d-mozulyov/Tiny.Library | d79fb2b2e9a28bc273a509814c3fc9fe970e077c | [
"MIT"
]
| 7 | 2020-05-25T18:58:37.000Z | 2021-10-15T08:39:15.000Z | ///<summary>Stuff common to the OmniThreadLibrary project.</summary>
///<author>Primoz Gabrijelcic</author>
///<license>
///This software is distributed under the BSD license.
///
///Copyright (c) 2019, Primoz Gabrijelcic
///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.
///- The name of the Primoz Gabrijelcic may not be used to endorse or promote
/// products derived from this software without specific prior written permission.
///
///THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
///ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
///WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
///DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
///ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
///(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
///LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
///ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
///(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
///SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
///</license>
///<remarks><para>
/// Home : http://www.omnithreadlibrary.com
/// Support : https://plus.google.com/communities/112307748950248514961
/// Author : Primoz Gabrijelcic
/// E-Mail : primoz@gabrijelcic.org
/// Blog : http://thedelphigeek.com
/// Contributors : GJ, Lee_Nover, scarre, Sean B. Durkin, HHasenack
/// Creation date : 2008-06-12
/// Last modification : 2018-04-13
/// Version : 1.50
///</para><para>
/// History:
/// 1.51: 2019-01-03
/// - [HHasenack] On XE3 and above, TOmniValue.CastTo<T> supports casting
/// to an interface. Fixes #128.
/// 1.50: 2018-04-13
/// - Implemented TOmniValue.LogValue, useful for debug logging.
/// 1.49: 2018-03-12
/// - Added TOmniValue.FromRecordUnsafe<T> which works same as FromRecord<T> but
/// doesn't enforce a 'record' constraint on T.
/// 1.48: 2017-07-26
/// - TOmniMessageID can now hold TProc<integer>.
/// 1.47: 2017-02-03
/// - AsInt64 now marks TOmniValue as a type ovtInt64 so that
/// ov.CastTo<TArray<Int64>> can work. [issue #89]
/// 1.46a: 2016-10-24
/// - Corrected Environment.GroupAffinity and Environment.LoadNUMAInfo to work
/// on Windows XP.
/// 1.46: 2016-10-19
/// - Implemented TOmniValue.Wrap<T> and .Unwrap<T>, a way to wrap anything
/// (including TMethod and 'reference to procedure') in a TOmniObject.
/// [Unwrap<T> must be called as follows: omnivalue.Unwrap<T>()]
/// 1.45: 2016-10-17
/// - Implemented TOmniRecord<T>, a simple way to wrap "anything" in a record.
/// 1.44b: 2016-08-31
/// - Environment.Thread was not thread safe!
/// 1.44a: 2016-07-29
/// - [HHasenack] TOmniValue.IsInterfacedType was returning wrong result for the
/// 'owned object' data type. This could cause objects assigned to .AsOwnedObject
/// to hang in memory and never be destroyed.
/// 1.44: 2016-07-18
/// - Implemented Environment.NUMANodes.Distance which returns relative distance
/// between two nodes, as reported by the ACPI (5.2.17 System Locality Distance
/// Information Table).
/// 1.43a: 2016-07-13
/// - TOmniIntegerSet only calls OnChange event when value is actually changed.
/// (Was called on each assign.)
/// 1.43: 2016-07-05
/// - Implemented IOmniIntegerSet.
/// - Implemented IOmniThreadEnvironment.GroupAffinity.
/// 1.42: 2016-07-01
/// - Implemented Environment.NUMANodes.FindNode.
/// 1.41: 2016-06-27
/// - Environment.ProcessorGroups and .NUMANodes are supported on all platforms.
/// Pseudo-group 0 and NUMA node 0 are reported on non-Windows platforms.
/// 1.40: 2016-06-23
/// - Implemented Environment.ProcessorGroups and Environment.NUMANodes (Win64 only).
/// - IOmniAffinity.Mask changed from DWORD to NativeUInt to properly support
/// up to 64 processors on Win64.
/// 1.39: 2015-10-03
/// - [Sean] Implemented TOmniAlignedInt32 (clone of GpStuff.TGp4AlignedInt)
/// and TOmniAlignedInt64 (clone of GpStuff.TGp8AlignedInt64).
/// 1.38: 2015-09-28
/// - [Sean] Introduced non-Windows compatibility.
/// 1.37b: 2015-08-30
/// - Fixed record type handling in FromArray<T> and ToArray<T>.
/// 1.37a: 2015-04-17
/// - Added vtWideChar and vtPWideChar handling to TOmniValue.Create and .CreateNamed.
/// 1.37: 2015-02-09
/// - Added writer for TOmniExecutable.Delegate.
/// 1.36: 2015-02-03
/// - Type of TOmniValue data is now an external type - TOmniValueDataType. That
/// way causes less internal errors in the compiler.
/// - Added TOmniValue.DataType property.
/// 1.35: 2014-09-23
/// - Implemented TOmniValueContainer.AssignNamed.
/// 1.34: 2014-01-13
/// - Implemented TOmniValue.HasArrayItem.
/// 1.33: 2014-01-10
/// - TOmniValue can 'own' a TObject (object gets destroyed when a TOmniValue goes
/// out of scope). Supporting properties: IsOwnedObject, AsOwnedObject,
/// OwnsObject.
/// 1.32b: 2013-10-17
/// - Fixed exception format string in TOmniValue.SetAsTValue.
/// 1.32a: 2013-10-14
/// - Removed XE5 compilation warnings.
/// 1.32: 2013-10-13
/// - ToObject<T> is working in D2010 again (thx to [Tomasso Ercole]).
/// 1.31a: 2013-10-07
/// - Compiles with D2009 and D2010 again.
/// 1.31: 2013-05-06
/// - AnsiString type is supported in TOmniValue.
/// - Implemented FromArray<T> and ToArray<T>.
/// - CastAs<T> renamed to CastTo<T>.
/// - AsRecord<T> renamed to ToRecord<T>.
/// - CastFrom<T> and CastTo<T> work for byte- and word-sized integer types.
/// 1.30: 2013-04-29
/// - GetAsXXX family renamed to CastToXXX.
/// - TryGetAsXXX familiy renamed to TryCastToXXX.
/// 1.29: 2013-04-26
/// - Added TOmniValue.TryGetAsXXX family of functions.
/// - Added TOmniValue.GetAsXXXDef family of functions.
/// 1.28a: 2013-02-27
/// - Fixed TOmniValue._AddRef and _Release when 'nil' interface was stored in
/// the TOmniValue.
/// 1.28: 2012-07-30
/// - Implemented TOmniValue.IsRecord.
/// 1.27: 2012-05-18
/// - Added property CountPhysical to the IOmniAffinity.
/// 1.26c: 2012-02-28
/// - Fixed object and interface casting in TOmniValue.CreateNamed.
/// 1.26b: 2012-02-25
/// - TOmniValue.CreateNamed was casting pointer to integer.
/// 1.26a: 2012-02-03
/// - TOmniValueContainer.Insert did not update internal 'count' field.
/// Big thanks to [andi] for bug report and fix.
/// 1.26: 2012-01-19
/// - Added TOmniValueObj, class wrapper for TOmniValue.
/// 1.25g: 2011-12-20
/// - TOmniValue.AsInteger, AsString and AsWideString now work if the TOmniValue
/// contains a Variant of the appropriate type.
/// 1.25f: 2011-12-18
/// - Fixed various TOmniInterfaceDictionary bugs (big tnx to Zarko Gajic).
/// - Clear properly clears interface refence before destroying the bucket.
/// - Resize properly clears interface reference in old bucket after copy.
/// - Resize preserves the internal item count.
/// - Resize releases old buckets.
/// 1.25e: 2011-12-09
/// - Removed compilation hint "Private symbol 'GetAsRecord' declared but never used".
/// 1.25d: 2011-12-02
/// - Removed compilation hint "Private symbol 'GetAsArrayItem' declared but never used".
/// 1.25c: 2011-11-29
/// - Reference count handling in TOmniValue was ignoring array and record wrappers.
/// 1.25b: 2011-11-18
/// - Overloaded property getters in TOmniValue are not inlined on 2009/
/// 2010 because of the buggy compiler.
/// 1.25a: 2011-11-15
/// - Some inlining removed because it would not work reliably.
/// 1.25: 2011-11-08
/// - Less casting in TOmniValue.Create.
/// - TOmniValue can store records by using FromRecord<T> and AsRecord<T>.
/// - Added a class which can wrap any record - TOmniRecordWrapper<T>.
/// - Added an interface which can wrap any object and destroy it when the
/// interface goes out of scope - IOmniAutoDestroyObject.
/// 1.24: 2011-11-05
/// - TOmniValue.Create now internally creates TOmniValueContainer to store values.
/// Variant arrays are no longer used. IsArray tests it TOmniValue contains an
/// array and AsArray returns this internal container. Default indexed property
/// still accesses individual elements in this container. See demo
/// 50_OmniValueArray for an example.
/// - TOmniValue.Create creates internal TOmniValueContainer containing named items.
/// See demo 50_OmniValueArray for an example.
/// 1.23: 2011-09-06
/// - Implemented IOmniCounter.Take.
/// 1.22: 2011-08-31
/// - [Lee_Nover] SetThreadName implementation moved into a separate unit with debug
/// info disabled. That way, debugger doesn't stop on SetThreadName while
/// single-stepping in another thread.
/// 1.21: 2011-08-28
/// - TOmniValue can natively store exception objects (AsException, IsException).
/// 1.20: 2011-07-14
/// - Removed EXIT_EXCEPTION error code.
/// 1.19a: 2010-12-12
/// - Define implicit TOmniValue<->TDateTime conversion operators only for Delphi XE
/// and higher.
/// 1.19: 2010-12-03
/// - [scarre] Added TDateTime support to TOmniValue.
/// 1.18a: 2010-09-21
/// - IOmniWaitableValue fully compatible with TOmniWaitableValue.
/// 1.18: 2010-09-20
/// - Declared interface IOmniWaitableValue and added function CreateWaitableValue.
/// - Implemented TOmniMessageID.AsString.
/// 1.17a: 2010-07-08
/// - TOmniValue.CastAs<T> and .CastFrom<T> are partially supported in D2009.
/// 1.17: 2010-07-01
/// - Includes OTLOptions.inc.
/// 1.16: 2010-05-12
/// - TOmniValue can be cast as Int64.
/// - Implemented TOmniValue.CastFrom<T> and .CastAs<T>.
/// 1.15: 2010-05-08
/// - Implemented conversions from/to TOmniValue to/from TValue (Delphi 2010 and newer).
/// 1.14: 2010-05-06
/// - Implemented TOmniValue._AddRef, _Release, _ReleaseAndClear.
/// 1.13: 2010-04-14
/// - Removed TOmniEnumerableRange and associated code.
/// 1.12: 2010-03-16
/// - Implemented TOmniMessageID record, used internally to implement timers.
/// 1.11: 2010-03-10
/// - Implemented TOmniCounter, auto-initialized wrapper around the IOmniCounter.
/// 1.10b: 2010-03-03
/// - Replacement AnonCopy, by Serg.
/// 1.10a: 2010-02-22
/// - D2009-compatible way of setting a delegate in TOmniExecutable.
/// 1.10: 2010-02-09
/// - Implemented TOmniExecutor - a record that can store TProcedure, TMethod, or
/// TProc.
/// 1.09: 2010-02-01
/// - TOmniValue getters know how to process empty TOmniValue.
/// - Added Environment.Thread interface.
/// - Environment.SystemAffinity moved to Environment.System.Affinity.
/// 1.08: 2010-01-14
/// - Added TOmniValue.IsInteger.
/// - Refactored and enhanced TOmniValueContainer.
/// - Defined IOmniValueEnumerable interface.
/// 1.07: 2010-01-05
/// - Renamed: IInterfaceDictionary -> IOmniInterfaceDictionary,
/// IInterfaceDictionaryEnumerator -> IOmniInterfaceDictionaryEnumerator,
/// TInterfaceDictionaryPair -> TOmniInterfaceDictionaryPair.
/// - Implemented IOmniEnvironment interface and function Environment returning
/// some information on system and process.
/// 1.06: 2009-12-21
/// - Added pointer conversions and AsPointer cast to TOmniValue.
/// 1.05: 2009-11-15
/// - Removed lots of stuff that is now implemented using container observers.
/// 1.04: 2009-04-18
/// - Added WideString support to TOmniValue.
/// 1.03a: 2009-04-05
/// - Bug fixed: TInterfaceDictionaryEnumerator was ignoring first bucket.
/// 1.03: 2009-03-30
/// - TOmniCS and IOmniCriticalSection moved to the OtlSync unit.
/// 1.02a: 2009-02-09
/// - Simplified TOmniCS.Initialize.
/// 1.02: 2009-02-03
/// - Added accessor to the internal critical section to the TOmniCS record.
/// 1.01: 2009-01-26
/// - Implemented TOmniCS critical section wrapper.
/// - Added TOmniWaitableValue class.
/// 1.0d: 2008-10-05
/// - Use GetGoodHashSize from GpStringHash unit.
/// 1.0c: 2008-09-26
/// - Check PostMessage result.
/// 1.0b: 2008-09-19
/// - Bug fixed: TOmniValue.Null was not really initialized to Null.
/// 1.0a: 2008-09-02
/// - Fixed memory leak that could occur in TOmniMonitorSupport.Notify (in fact it
/// was possible to cause it in demo 11).
/// 1.0: 2008-08-26
/// - First official release.
///</para></remarks>
unit OtlCommon;
{$I OtlOptions.inc}
{$WARN SYMBOL_PLATFORM OFF}
interface
uses
Classes,
Variants,
TypInfo,
SyncObjs,
Types,
{$IFDEF MSWINDOWS}
Windows,
DSiWin32,
{$ENDIF}
{$IFDEF POSIX}
Posix.Pthread,
{$ENDIF}
{$IFDEF OTL_ERTTI}
RTTI,
{$ENDIF OTL_ERTTI}
{$IFDEF OTL_Generics}
Generics.Defaults,
Generics.Collections,
{$ENDIF OTL_Generics}
SysUtils;
const
// reserved exit statuses
EXIT_OK = 0;
EXIT_INTERNAL = integer($80000000);
EXIT_THREADPOOL_QUEUE_TOO_LONG = EXIT_INTERNAL + 0;
EXIT_THREADPOOL_STALE_TASK = EXIT_INTERNAL + 1;
EXIT_THREADPOOL_CANCELLED = EXIT_INTERNAL + 2;
EXIT_THREADPOOL_INTERNAL_ERROR = EXIT_INTERNAL + 3;
type
{$IFNDEF OTL_HasCorrectNativeInt}
NativeInt = integer;
NativeUInt = cardinal;
PNativeInt = PInteger;
PNativeUInt = PCardinal;
{$ENDIF}
//:TOmniValue conversion exception.
EOmniValueConv = class(Exception);
TOmniValueContainer = class;
IOmniAutoDestroyObject = interface;
//Update IsInterfacedType function when changing this enum!
TOmniValueDataType = (ovtNull,
{ovData} ovtBoolean, ovtInteger, ovtInt64, ovtDouble, ovtObject, ovtPointer, ovtDateTime, ovtException,
{ovIntf} ovtExtended, ovtString, ovtInterface, ovtVariant, ovtArray, ovtRecord, ovtOwnedObject
{$IFDEF MSWINDOWS}
, ovtWideString, ovtAnsiString
{$ENDIF});
TOmniValue = packed record // 13 bytes in 32-bit, 17 bytes in 64-bit
private
ovData: int64;
ovIntf: IInterface;
ovType: TOmniValueDataType;
function CastToBoolean: boolean; inline;
function CastToCardinal: cardinal; inline;
function CastToDouble: Double;
function CastToDateTime: TDateTime;
function CastToException: Exception;
function CastToExtended: Extended;
function CastToInt64: int64; inline;
function CastToInteger: integer; inline;
function CastToInterface: IInterface; inline;
function CastToObject: TObject; overload; inline;
function CastToPointer: pointer;
function CastToRecord: IOmniAutoDestroyObject; inline;
function CastToString: string;
function CastToVariant: Variant;
function GetAsArray: TOmniValueContainer; inline;
function GetAsArrayItem(idx: integer): TOmniValue; overload; {$IF CompilerVersion >= 22}inline;{$IFEND}
function GetAsArrayItem(const name: string): TOmniValue; overload; {$IF CompilerVersion >= 22}inline;{$IFEND}
{$IF CompilerVersion >= 19}//D2007 has problems understanding this overload
function GetAsArrayItem(const param: TOmniValue): TOmniValue; overload; {$IF CompilerVersion >= 22}inline;{$IFEND}
//GetAsArrayItemOV is used in D2007 instead
{$IFEND}
function GetAsArrayItemOV(const param: TOmniValue): TOmniValue; overload; {$IF CompilerVersion >= 22}inline;{$IFEND}
procedure SetAsArray(value: TOmniValueContainer); inline;
procedure SetAsArrayItem(idx: integer; const value: TOmniValue); overload; {$IF CompilerVersion >= 22}inline;{$IFEND}
procedure SetAsArrayItem(const name: string; const value: TOmniValue); overload; {$IF CompilerVersion >= 22}inline;{$IFEND}
{$IF CompilerVersion >= 19}//D2007 has problems understanding this overload
procedure SetAsArrayItem(const param, value: TOmniValue); overload; {$IF CompilerVersion >= 22}inline;{$IFEND}
//SetAsArrayItemOV is used in D2007 instead
{$IFEND}
procedure SetAsArrayItemOV(const param, value: TOmniValue); overload; {$IF CompilerVersion >= 22}inline;{$IFEND}
procedure SetAsBoolean(const value: boolean); inline;
procedure SetAsCardinal(const value: cardinal); inline;
procedure SetAsDouble(value: Double); inline;
procedure SetAsDateTime(value: TDateTime); inline;
procedure SetAsException(value: Exception);
procedure SetAsExtended(value: Extended);
procedure SetAsInt64(const value: int64); inline;
procedure SetAsInteger(const value: integer); inline;
procedure SetAsInterface(const value: IInterface); //don't inline, something is broken in codegen (XE)
procedure SetAsObject(const value: TObject); inline;
procedure SetAsOwnedObject(const value: TObject); inline;
procedure SetAsPointer(const value: pointer); inline;
procedure SetAsRecord(const intf: IOmniAutoDestroyObject); inline;
procedure SetAsString(const value: string);
procedure SetAsVariant(const value: Variant);
procedure SetOwnsObject(const value: boolean);
{$REGION 'Documentation'}
/// <summary>Most of the code in this method never executes. It is just here so that
/// stupid compilation hints such as "Private symbol 'GetAsArrayItem' declared but
/// never used" are not shown.</summary>
{$ENDREGION}
class procedure _RemoveWarnings; inline; static;
procedure ClearIntf; inline;
{$IFDEF MSWINDOWS}
function CastToAnsiString: AnsiString; inline;
function CastToWideString: WideString;
procedure SetAsAnsiString(const value: AnsiString);
procedure SetAsWideString(const value: WideString);
{$ENDIF}
{$IFDEF OTL_ERTTI}
private
function GetAsTValue: TValue;
function GetArrayFromTValue(const value: TValue): TOmniValueContainer;
function GetTValueFromArray(const a: TOmniValueContainer): TValue;
procedure SetAsTValue(const value: TValue);
{$ENDIF}
public
constructor Create(const values: array of const);
constructor CreateNamed(const values: array of const; const cppDupConWorkaround: boolean = false);
procedure _AddRef; inline;
procedure _Release; inline;
procedure _ReleaseAndClear; inline;
function CastToBooleanDef(defValue: boolean): boolean; inline;
function CastToCardinalDef(defValue: cardinal): cardinal; inline;
function CastToDoubleDef(defValue: Double): Double; inline;
function CastToDateTimeDef(defValue: TDateTime): TDateTime; inline;
function CastToExceptionDef(defValue: Exception): Exception; inline;
function CastToExtendedDef(defValue: Extended): Extended; inline;
function CastToInt64Def(defValue: int64): int64; inline;
function CastToIntegerDef(defValue: integer): integer; inline;
function CastToInterfaceDef(const defValue: IInterface): IInterface; inline;
function CastToObjectDef(defValue: TObject): TObject; inline;
function CastToPointerDef(defValue: pointer): pointer; inline;
function CastToStringDef(const defValue: string): string; inline;
function CastToVariantDef(defValue: Variant): Variant; inline;
procedure Clear; inline;
function HasArrayItem(idx: integer): boolean; overload; inline;
function HasArrayItem(const name: string): boolean; overload; inline;
function HasArrayItem(const param: TOmniValue): boolean; overload; inline;
function IsArray: boolean; inline;
function IsBoolean: boolean; inline;
function IsEmpty: boolean; inline;
function IsException: boolean; inline;
function IsFloating: boolean; inline;
function IsDateTime: boolean; inline;
function IsInteger: boolean; inline;
function IsInterface: boolean; inline;
function IsInterfacedType: boolean; inline;
function IsObject: boolean; inline;
function IsOwnedObject: boolean; inline;
function IsPointer: boolean; inline;
function IsRecord: boolean; inline;
function IsString: boolean; inline;
function IsVariant: boolean; inline;
function LogValue: string;
class function Null: TOmniValue; static;
function RawData: PInt64; inline;
procedure RawZero; inline;
function TryCastToBoolean(var value: boolean): boolean; inline;
function TryCastToCardinal(var value: cardinal): boolean; inline;
function TryCastToDouble(var value: Double): boolean;
function TryCastToDateTime(var value: TDateTime): boolean;
function TryCastToException(var value: Exception): boolean;
function TryCastToExtended(var value: Extended): boolean;
function TryCastToInt64(var value: int64): boolean; inline;
function TryCastToInteger(var value: integer): boolean; inline;
function TryCastToInterface(var value: IInterface): boolean; inline;
function TryCastToObject(var value: TObject): boolean; inline;
function TryCastToPointer(var value: pointer): boolean;
function TryCastToString(var value: string): boolean;
function TryCastToVariant(var value: Variant): boolean;
class operator Equal(const a: TOmniValue; i: integer): boolean; inline;
class operator Equal(const a: TOmniValue; const s: string): boolean; inline;
class operator Implicit(const a: boolean): TOmniValue; inline;
class operator Implicit(const a: Double): TOmniValue; inline;
class operator Implicit(const a: Extended): TOmniValue; inline;
class operator Implicit(const a: integer): TOmniValue; inline;
class operator Implicit(const a: int64): TOmniValue; inline;
class operator Implicit(const a: pointer): TOmniValue; inline;
class operator Implicit(const a: string): TOmniValue; inline;
class operator Implicit(const a: IInterface): TOmniValue; //don't inline, something is broken in codegen (XE)
class operator Implicit(const a: TObject): TOmniValue; inline;
class operator Implicit(const a: Exception): TOmniValue; inline;
class operator Implicit(const a: TOmniValue): int64; inline;
class operator Implicit(const a: TOmniValue): TObject; inline;
class operator Implicit(const a: TOmniValue): Double; inline;
class operator Implicit(const a: TOmniValue): Exception; inline;
class operator Implicit(const a: TOmniValue): Extended; inline;
class operator Implicit(const a: TOmniValue): string; inline;
class operator Implicit(const a: TOmniValue): integer; inline;
class operator Implicit(const a: TOmniValue): pointer; inline;
class operator Implicit(const a: TOmniValue): boolean; inline;
class operator Implicit(const a: TOmniValue): IInterface; inline;
class operator Implicit(const a: Variant): TOmniValue; inline;
{$IFDEF OTL_TOmniValueImplicitDateTime}
class operator Implicit(const a: TDateTime): TOmniValue; inline;
class operator Implicit(const a: TOmniValue): TDateTime; inline;
{$ENDIF OTL_TOmniValueImplicitDateTime}
property AsArray: TOmniValueContainer read GetAsArray;
property AsArrayItem[idx: integer]: TOmniValue read GetAsArrayItem write SetAsArrayItem; default;
property AsArrayItem[const name: string]: TOmniValue read GetAsArrayItem write SetAsArrayItem; default;
{$IF CompilerVersion >= 19}//D2007 has problems understanding this overload
property AsArrayItem[const param: TOmniValue]: TOmniValue read GetAsArrayItem write SetAsArrayItem; default;
{$IFEND}
property AsArrayItemOV[const param: TOmniValue]: TOmniValue read GetAsArrayItemOV write SetAsArrayItemOV;
property AsBoolean: boolean read CastToBoolean write SetAsBoolean;
property AsCardinal: cardinal read CastToCardinal write SetAsCardinal;
property AsDouble: Double read CastToDouble write SetAsDouble;
property AsDateTime: TDateTime read CastToDateTime write SetAsDateTime;
property AsException: Exception read CastToException write SetAsException;
property AsExtended: Extended read CastToExtended write SetAsExtended;
property AsInt64: int64 read CastToInt64 write SetAsInt64;
property AsInteger: integer read CastToInteger write SetAsInteger;
property AsInterface: IInterface read CastToInterface write SetAsInterface;
property AsObject: TObject read CastToObject write SetAsObject;
property AsOwnedObject: TObject read CastToObject write SetAsOwnedObject;
property AsPointer: pointer read CastToPointer write SetAsPointer;
property AsString: string read CastToString write SetAsString;
property AsVariant: Variant read CastToVariant write SetAsVariant;
property DataType: TOmniValueDataType read ovType;
property OwnsObject: boolean read IsOwnedObject write SetOwnsObject;
{$IFDEF MSWINDOWS}
function CastToAnsiStringDef(const defValue: AnsiString): AnsiString; inline;
function CastToWideStringDef(defValue: WideString): WideString; inline;
function IsAnsiString: boolean; inline;
function IsWideString: boolean; inline;
function TryCastToAnsiString(var value: AnsiString): boolean;
function TryCastToWideString(var value: WideString): boolean;
{$IFDEF Unicode}
class operator Implicit(const a: TOmniValue): AnsiString; inline;
class operator Implicit(const a: AnsiString): TOmniValue; inline;
{$ENDIF Unicode}
class operator Implicit(const a: TOmniValue): WideString; inline;
class operator Implicit(const a: WideString): TOmniValue; inline;
property AsAnsiString: AnsiString read CastToAnsiString write SetAsAnsiString;
property AsWideString: WideString read CastToWideString write SetAsWideString;
{$ENDIF}
{$IFDEF OTL_Generics}
class function CastFrom<T>(const value: T): TOmniValue; static;
function CastTo<T>: T;
class function FromRecord<T: record>(const value: T): TOmniValue; static;
class function FromRecordUnsafe<T>(const value: T): TOmniValue; static;
function ToRecord<T>: T;
class function Wrap<T>(const value: T): TOmniValue; static;
function Unwrap<T>: T; //Use this form to call: omnivalue.Unwrap<T>()
{$IFDEF OTL_HasArrayOfT}
class function FromArray<T>(const values: TArray<T>): TOmniValue; static;
function ToArray<T>: TArray<T>;
{$ENDIF OTL_HasArrayOfT}
{$IF CompilerVersion > 20}
function CastToObject<T: class>: T; overload;
function ToObject<T: class>: T;
{$IFEND}
{$ENDIF OTL_Generics}
{$IFDEF OTL_ERTTI}
class operator Implicit(const a: TValue): TOmniValue; inline;
class operator Implicit(const a: TOmniValue): TValue; inline;
property AsTValue: TValue read GetAsTValue write SetAsTValue;
{$ENDIF OTL_ERTTI}
end; { TOmniValue }
/// <summary>TOmniValue wrapper - for when you need to treat TOmniValue as an object.</summary>
TOmniValueObj = class
strict private
FValue: TOmniValue;
public
constructor Create(const value: TOmniValue);
property Value: TOmniValue read FValue;
end; { TOmniValueObj }
{$IFDEF OTL_Generics}
TOmniRecord<T> = record
strict private
FValue: T;
public
constructor Create(const aValue: T);
property Value: T read FValue write FValue;
end;
{$ENDIF OTL_Generics}
///<summary>Slightly different from the IEnumerable:
/// - Returns TOmniValue.
/// - Must ensure correct operation of multiple simultaneous enumerators.
/// - TryTake must be implemented to support mutable collections (as TOmniBlockingCollection).
/// For non-mutable collections TryTake can simply return false if the collection
/// is empty.
/// - TryTake must be threadsafe - when used in Parallel.For, data manager will call
/// it simultaneously from multiple threads at the same time.
///</summary>
IOmniValueEnumerator = interface ['{F60EBBD8-2F87-4ACD-A014-452F296F4699}']
function GetCurrent: TOmniValue;
function MoveNext: boolean;
function TryTake(var value: TOmniValue; timeout_ms: cardinal): boolean;
property Current: TOmniValue read GetCurrent;
end; { IOmniValueEnumerator }
IOmniValueEnumerable = interface ['{50C1C176-C61F-41F5-AA0B-6FD215E5159F}']
function GetEnumerator: IOmniValueEnumerator;
end; { IOmniValueEnumerable }
///<summary>Abstract enumerator class, used as a base for internal classes passed to the
/// OtlDataManager.</summary>
TOmniValueEnumerator = class abstract
function GetCurrent: TOmniValue; virtual; abstract;
function MoveNext: boolean; virtual; abstract;
property Current: TOmniValue read GetCurrent;
end; { TOmniValueEnumerator }
IOmniWaitableValue = interface ['{46EB21E0-B5E8-47DA-8E34-E4DE04C4D8D9}']
{$IFDEF MSWINDOWS}
function GetHandle: THandle;
{$ENDIF}
function GetEvent: TEvent;
function GetValue: TOmniValue;
//
procedure Reset;
procedure Signal; overload;
procedure Signal(const data: TOmniValue); overload;
function WaitFor(maxWait_ms: cardinal = INFINITE): boolean;
{$IFDEF MSWINDOWS}
property Handle: THandle read GetHandle;
{$ENDIF}
property Event: TEvent read GetEvent;
property Value: TOmniValue read GetValue;
end; { IOmniWaitableValue }
TOmniWaitableValue = class(TInterfacedObject, IOmniWaitableValue)
strict private
FEvent: TEvent;
FValue: TOmniValue;
protected
{$IFDEF MSWINDOWS}
function GetHandle: THandle;
{$ENDIF}
function GetEvent: TEvent;
function GetValue: TOmniValue;
public
constructor Create;
destructor Destroy; override;
procedure Reset; inline;
procedure Signal; overload; inline;
procedure Signal(const data: TOmniValue); overload; inline;
function WaitFor(maxWait_ms: cardinal = INFINITE): boolean; inline;
{$IFDEF MSWINDOWS}
property Handle: THandle read GetHandle;
{$ENDIF}
property Event: TEvent read GetEvent;
property Value: TOmniValue read GetValue;
end; { TOmniWaitableValue }
TOmniValueContainer = class
strict private
ovcCanModify: boolean;
ovcCount : integer;
ovcNames : array of string;
ovcValues : array of TOmniValue;
strict protected
function AddParam(const paramName: string): integer;
procedure Clear;
function GetItem(paramIdx: integer): TOmniValue; overload;
function GetItem(const paramName: string): TOmniValue; overload;
function GetItem(const param: TOmniValue): TOmniValue; overload;
procedure SetItem(idx: integer; const value: TOmniValue); overload; {$IF CompilerVersion >= 22}inline;{$IFEND}
procedure SetItem(const name: string; const value: TOmniValue); overload;
procedure SetItem(const param, value: TOmniValue); overload;
procedure Grow(requiredIdx: integer = -1);
public
constructor Create;
procedure Add(const paramValue: TOmniValue; const paramName: string = '');
procedure Assign(const parameters: array of TOmniValue);
procedure AssignNamed(const parameters: array of TOmniValue);
function ByName(const paramName: string): TOmniValue; overload;
function ByName(const paramName: string; const defValue: TOmniValue): TOmniValue; overload;
function Count: integer;
function Exists(const paramName: string): boolean;
function IndexOf(const paramName: string): integer;
procedure Insert(paramIdx: integer; const value: TOmniValue);
function IsLocked: boolean; inline;
procedure Lock; inline;
property Item[paramIdx: integer]: TOmniValue read GetItem write SetItem; default;
property Item[const paramName: string]: TOmniValue read GetItem write SetItem; default;
property Item[const param: TOmniValue]: TOmniValue read GetItem write SetItem; default;
end; { TOmniValueContainer }
//:Thread-safe counter
IOmniCounter = interface ['{3A73CCF3-EDC5-484F-8459-532B8C715E3C}']
function GetValue: integer;
procedure SetValue(const value: integer);
//
function Increment: integer;
function Decrement: integer;
function Take(count: integer): integer; overload;
function Take(count: integer; var taken: integer): boolean; overload;
property Value: integer read GetValue write SetValue;
end; { IOmniCounter }
TOmniCounter = record
strict private
{$IFNDEF MSWINDOWS}[Volatile]{$ENDIF}
ocCounter: IOmniCounter;
function GetValue: integer;
procedure SetValue(const value: integer);
public
procedure Initialize;
function Increment: integer;
function Decrement: integer;
function Take(count: integer): integer; overload;
function Take(count: integer; var taken: integer): boolean; overload;
property Value: integer read GetValue write SetValue;
end; { TOmniCounter }
{$IFDEF OTL_GoodGenerics}
TOmniInterfaceDictionaryPair = TPair<int64, IInterface>;
{$ELSE}
TOmniInterfaceDictionaryPair = class
strict private
idpKey : int64;
idpValue: IInterface;
protected
procedure SetKeyValue(const key: int64; const value: IInterface);
public
property Key: int64 read idpKey;
property Value: IInterface read idpValue;
end; { TOmniInterfaceDictionaryPair }
IOmniInterfaceDictionaryEnumerator = interface
function GetCurrent: TOmniInterfaceDictionaryPair;
function MoveNext: boolean;
property Current: TOmniInterfaceDictionaryPair read GetCurrent;
end; { IOmniInterfaceDictionaryEnumerator }
{$ENDIF OTL_GoodGenerics}
IOmniInterfaceDictionary = interface ['{619FCCF3-E810-4DCF-B902-1EF1A5A72DB5}']
{$IFDEF OTL_GoodGenerics}
function GetEnumerator: TDictionary<int64, IInterface>.TPairEnumerator;
{$ELSE}
function GetEnumerator: IOmniInterfaceDictionaryEnumerator;
{$ENDIF OTL_GoodGenerics}
//
procedure Add(const key: int64; const value: IInterface);
procedure Clear;
function Count: integer;
procedure Remove(const key: int64);
function ValueOf(const key: int64): IInterface;
end; { IOmniInterfaceDictionary }
IOmniIntegerSet = interface;
TOmniIntegerSetChangedEvent = procedure(const intSet: IOmniIntegerSet) of object;
IOmniIntegerSet = interface ['{571F85D0-CFD8-40FE-8860-A8C1C932028C}']
function GetAsBits: TBits;
function GetAsIntArray: TIntegerDynArray;
function GetAsMask: int64;
function GetItem(idx: integer): integer;
function GetOnChange: TOmniIntegerSetChangedEvent;
procedure SetAsBits(const value: TBits);
procedure SetAsIntArray(const Value: TIntegerDynArray);
procedure SetAsMask(const value: int64);
procedure SetOnChange(const value: TOmniIntegerSetChangedEvent);
{$IFDEF OTL_HasArrayOfT}
function GetAsArray: TArray<integer>;
procedure SetAsArray(const Value: TArray<integer>);
{$ENDIF OTL_HasArrayOfT}
//
function Add(value: integer): boolean;
procedure Assign(const value: IOmniIntegerSet);
procedure Clear;
function Contains(value: integer): boolean;
function Count: integer;
function IsEmpty: boolean;
function Remove(value: integer): boolean;
{$IFDEF OTL_HasArrayOfT}
property AsArray: TArray<integer> read GetAsArray write SetAsArray;
{$ENDIF OTL_HasArrayOfT}
property AsBits: TBits read GetAsBits write SetAsBits;
property AsIntArray: TIntegerDynArray read GetAsIntArray write SetAsIntArray;
property AsMask: int64 read GetAsMask write SetAsMask;
property OnChange: TOmniIntegerSetChangedEvent read GetOnChange write SetOnChange;
property Item[idx: integer]: integer read GetItem; default;
end; { IOmniIntegerSet }
TOmniIntegerSet = class(TInterfacedObject, IOmniIntegerSet)
strict private
FBits : TBits;
FHasValueCopy: boolean;
FOnChange : TOmniIntegerSetChangedEvent;
FValueCopy : TIntegerDynArray;
protected
procedure DoOnChange;
function GetAsBits: TBits; inline;
function GetAsIntArray: TIntegerDynArray;
function GetAsMask: int64;
function GetItem(idx: integer): integer;
function GetOnChange: TOmniIntegerSetChangedEvent; inline;
procedure PrepareValueCopy;
procedure SetAsBits(const value: TBits);
procedure SetAsIntArray(const value: TIntegerDynArray);
procedure SetAsMask(const value: int64);
procedure SetOnChange(const value: TOmniIntegerSetChangedEvent); inline;
{$IFDEF OTL_HasArrayOfT}
function GetAsArray: TArray<integer>;
procedure SetAsArray(const value: TArray<integer>);
{$ENDIF OTL_HasArrayOfT}
public
constructor Create;
constructor Clone(const value: IOmniIntegerSet);
destructor Destroy; override;
function Add(value: integer): boolean;
procedure Assign(const value: IOmniIntegerSet); overload;
procedure Assign(const value: TOmniIntegerSet); overload;
procedure Clear; inline;
function Contains(value: integer): boolean; inline;
function Count: integer;
function IsEmpty: boolean;
function Remove(value: integer): boolean;
{$IFDEF OTL_HasArrayOfT}
property AsArray: TArray<integer> read GetAsArray write SetAsArray;
{$ENDIF OTL_HasArrayOfT}
property AsBits: TBits read GetAsBits write SetAsBits;
property AsIntArray: TIntegerDynArray read GetAsIntArray write SetAsIntArray;
property AsMask: int64 read GetAsMask write SetAsMask;
property OnChange: TOmniIntegerSetChangedEvent read GetOnChange write SetOnChange;
property Item[idx: integer]: integer read GetItem; default;
end; { TOmniIntegerSet }
IOmniAffinity = interface ['{8A6DDC70-F705-4577-869B-6810E776132B}']
function GetAsString: string;
function GetCount: integer;
function GetCountPhysical: integer;
procedure SetAsString(const value: string);
procedure SetCount(const value: integer);
{$IFDEF MSWINDOWS}
function GetMask: NativeUInt;
procedure SetMask(const value: NativeUInt);
{$ENDIF}
//
property AsString: string read GetAsString write SetAsString;
property Count: integer read GetCount write SetCount;
property CountPhysical: integer read GetCountPhysical;
{$IFDEF MSWINDOWS}
property Mask: NativeUInt read GetMask write SetMask;
{$ENDIF}
end; { IOmniAffinity }
{$IFDEF MSWINDOWS}
TOmniProcessMemoryCounters = TProcessMemoryCounters;
{$ENDIF}
{$IFDEF MSWINDOWS}
TOmniProcessTimes = record
CreationTime: TDateTime;
UserTime : int64;
KernelTime : int64;
end; { TOmniProcessTimes }
{$ENDIF}
TOmniProcessPriorityClass = (pcIdle, pcBelowNormal, pcNormal, pcAboveNormal, pcHigh,
pcRealtime);
IOmniProcessEnvironment = interface ['{98D6BDA3-840B-4E19-B01D-633E6A239FE9}']
function GetAffinity: IOmniAffinity;
function GetPriorityClass: TOmniProcessPriorityClass;
{$IFDEF MSWINDOWS}
function GetMemory: TOmniProcessMemoryCounters;
function GetTimes: TOmniProcessTimes;
{$ENDIF}
//
property Affinity: IOmniAffinity read GetAffinity;
property PriorityClass: TOmniProcessPriorityClass read GetPriorityClass;
{$IFDEF MSWINDOWS}
property Memory: TOmniProcessMemoryCounters read GetMemory;
property Times: TOmniProcessTimes read GetTimes;
{$ENDIF}
end; { IOmniProcessEnvironment }
IOmniSystemEnvironment = interface ['{9BE1EFE3-4ABB-4C2F-B2A4-B014D0949FEC}']
function GetAffinity: IOmniAffinity;
//
property Affinity: IOmniAffinity read GetAffinity;
end; { IOmniSystemEnvironment }
{$IFNDEF OTL_HasThreadID}
TThreadID = LongWord;
{$ENDIF ~OTL_HasThreadID}
TOmniGroupAffinity = record
private
FAffinity: IOmniIntegerSet;
FGroup : integer;
function GetAffinity: IOmniIntegerSet;
public
constructor Create(groupNumber: integer; const affinity: IOmniIntegerSet); overload;
constructor Create(groupNumber: integer; const affinityMask: int64); overload;
property Group: integer read FGroup write FGroup;
property Affinity: IOmniIntegerSet read GetAffinity;
end; { TOmniGroupAffinity }
IOmniThreadEnvironment = interface ['{5C11FEC7-9FBE-423F-B30E-543C8240E3A3}']
function GetAffinity: IOmniAffinity;
function GetGroupAffinity: TOmniGroupAffinity;
function GetID: TThreadId;
procedure SetGroupAffinity(const value: TOmniGroupAffinity);
//
property Affinity: IOmniAffinity read GetAffinity;
property GroupAffinity: TOmniGroupAffinity read GetGroupAffinity write SetGroupAffinity;
property ID: TThreadId read GetID;
end; { IOmniThreadEnvironment }
{$IFDEF OTL_NUMASupport}
IOmniNUMANode = interface ['{8D3B415F-8B13-4BFF-B7C7-2D0BC1705217}']
function GetAffinity: IOmniIntegerSet;
function GetGroupNumber: integer;
function GetNodeNumber: integer;
//
property NodeNumber: integer read GetNodeNumber;
property GroupNumber: integer read GetGroupNumber;
property Affinity: IOmniIntegerSet read GetAffinity;
end; { IOmniNUMANode }
IOmniNUMANodes = interface ['{4407E795-ED35-4DD1-9EC6-D59758BAF581}']
function GetItem(idx: integer): IOmniNUMANode;
//
function All: IOmniIntegerSet;
function Count: integer;
function Distance(fromNode, toNode: integer): integer;
function FindNode(nodeNumber: integer): IOmniNUMANode;
function GetEnumerator: TList<IOmniNUMANode>.TEnumerator;
property Item[idx: integer]: IOmniNUMANode read GetItem; default;
end; { IOmniNUMANodes }
IOmniProcessorGroup = interface ['{BCFB0AE8-A378-4A4B-AD73-EF9B59218B55}']
function GetAffinity: IOmniIntegerSet;
function GetGroupNumber: integer;
//
property GroupNumber: integer read GetGroupNumber;
property Affinity: IOmniIntegerSet read GetAffinity;
end; { IOmniProcessorGroup }
IOmniProcessorGroups = interface ['{B4C871C0-CF61-4BC9-98DE-87F720F51853}']
function GetItem(idx: integer): IOmniProcessorGroup;
//
function All: IOmniIntegerSet;
function Count: integer;
function FindGroup(groupNumber: integer): IOmniProcessorGroup;
function GetEnumerator: TList<IOmniProcessorGroup>.TEnumerator;
property Item[idx: integer]: IOmniProcessorGroup read GetItem; default;
end; { IOmniProcessorGroups }
{$ENDIF OTL_NUMASupport}
IOmniEnvironment = interface ['{4F9594E2-8B88-483C-9616-85B50493406D}']
{$IFDEF OTL_NUMASupport}
function GetNUMANodes: IOmniNUMANodes;
function GetProcessorGroups: IOmniProcessorGroups;
{$ENDIF OTL_NUMASupport}
function GetProcess: IOmniProcessEnvironment;
function GetSystem: IOmniSystemEnvironment;
function GetThread: IOmniThreadEnvironment;
//
{$IFDEF OTL_NUMASupport}
property NUMANodes: IOmniNUMANodes read GetNUMANodes;
property ProcessorGroups: IOmniProcessorGroups read GetProcessorGroups;
{$ENDIF OTL_NUMASupport}
property Process: IOmniProcessEnvironment read GetProcess;
property System: IOmniSystemEnvironment read GetSystem;
property Thread: IOmniThreadEnvironment read GetThread;
end; { IOmniEnvironment }
TOmniExecutableKind = (oekNull, oekProcedure, oekMethod {$IFDEF OTL_Anonymous},
oekDelegate{$ENDIF});
TOmniExecutable = record
{$IFDEF OTL_Anonymous}
strict private
oeDelegate: TProc;
procedure SetAnonDelegate(const value: TProc); inline;
function GetDelegate: TProc; inline;
{$ENDIF OTL_Anonymous}
strict private
oeMethod : TMethod;
oeProcedure: TProcedure;
oeKind : TOmniExecutableKind;
procedure CheckKind(kind: TOmniExecutableKind); inline;
function GetMethod: TMethod; inline;
function GetProc: TProcedure; inline;
procedure SetMethod(const value: TMethod); inline;
procedure SetProc(const value: TProcedure); inline;
public
class operator Explicit(const a: TOmniExecutable): TMethod; inline;
class operator Explicit(const a: TOmniExecutable): TProcedure; inline;
class operator Explicit(const a: TMethod): TOmniExecutable; inline;
class operator Explicit(const a: TProcedure): TOmniExecutable; inline;
class operator Implicit(const a: TMethod): TOmniExecutable; inline;
class operator Implicit(const a: TProcedure): TOmniExecutable; inline;
class operator Implicit(const a: TOmniExecutable): TMethod; inline;
class operator Implicit(const a: TOmniExecutable): TProcedure; inline;
procedure Clear; inline;
function IsNull: boolean; inline;
property Kind: TOmniExecutableKind read oeKind;
property Method: TMethod read GetMethod write SetMethod;
property Proc: TProcedure read GetProc write SetProc;
public
{$IFDEF OTL_Anonymous}
class procedure AnonCopy(var Dest; const Source); static;
class operator Explicit(const a: TOmniExecutable): TProc; inline;
class operator Explicit(const a: TProc): TOmniExecutable; inline;
class operator Implicit(const a: TOmniExecutable): TProc; inline;
class operator Implicit(const a: TProc): TOmniExecutable; inline;
procedure SetDelegate(const source);
property Delegate: TProc read GetDelegate write SetAnonDelegate;
{$ENDIF OTL_Anonymous}
end; { TOmniExecutable }
TOmniMessageIDType = (mitInteger, mitString, mitPointer {$IFDEF OTL_Anonymous}, mitAnon{$ENDIF});
///<summary>Describes 'smart' IOmniTaskControl message (either message ID, method name,
/// or method pointer.</summary>
///<since>2010-03-16</since>
TOmniMessageID = record
strict private
{$IFDEF OTL_Anonymous}
omidAnon : TProc<integer>;
{$ENDIF OTL_Anonymous}
omidInteger : integer;
omidMessageType: TOmniMessageIDType;
omidPointer : pointer;
omidString : string;
public
class operator Implicit(const a: integer): TOmniMessageID; inline;
class operator Implicit(const a: pointer): TOmniMessageID; inline;
class operator Implicit(const a: string): TOmniMessageID; inline;
class operator Implicit(const a: TOmniMessageID): integer; inline;
class operator Implicit(const a: TOmniMessageID): string; inline;
class operator Implicit(const a: TOmniMessageID): pointer; inline;
{$IFDEF OTL_Anonymous}
constructor Create(const proc: TProc<integer>);
{$ENDIF OTL_Anonymous}
function AsString: string;
property MessageType: TOmniMessageIDType read omidMessageType;
{$IFDEF OTL_Anonymous}
property Proc: TProc<integer> read omidAnon;
{$ENDIF OTL_Anonymous}
end; { TOmniMessageID }
{$IFDEF OTL_Generics}
TOmniRecordWrapper<T> = class
strict private
FValue: T;
public
constructor Create(const value: T);
function GetRecord: T;
procedure SetRecord(const value: T);
property Value: T read GetRecord write SetRecord;
end; { TOmniRecordWrapper<T> }
{$ENDIF OTL_Generics}
IOmniAutoDestroyObject = interface ['{37DE60D3-C53D-4D13-B87C-C70BDC76A530}']
function GetValue: TObject;
function Detach: TObject;
//
property Value: TObject read GetValue;
end; { IOmniAutoDestroyObject }
TOmniAlignedInt32 = record
strict private
FData: int64;
FAddr: PInteger;
function GetValue: integer; inline;
procedure SetValue(value: integer); inline;
public
procedure Initialize; inline;
function Add(value: integer): integer; inline;
function Addr: PInteger; inline;
function CAS(oldValue, newValue: integer): boolean;
function Decrement: integer; overload; inline;
function Decrement(value: integer): integer; overload; inline;
function Increment: integer; overload; inline;
function Increment(value: integer): integer; overload; inline;
function Subtract(value: integer): integer; inline;
class operator Add(const ai: TOmniAlignedInt32; i: integer): cardinal; {$IFDEF OTL_CanInlineOperators}inline;{$ENDIF}
class operator Equal(const ai: TOmniAlignedInt32; i: integer): boolean; {$IFDEF OTL_CanInlineOperators}inline;{$ENDIF}
class operator GreaterThan(const ai: TOmniAlignedInt32; i: integer): boolean; {$IFDEF OTL_CanInlineOperators}inline;{$ENDIF}
class operator GreaterThanOrEqual(const ai: TOmniAlignedInt32; i: integer): boolean; {$IFDEF OTL_CanInlineOperators}inline;{$ENDIF}
class operator Implicit(const ai: TOmniAlignedInt32): integer; inline;
class operator Implicit(const ai: TOmniAlignedInt32): cardinal; inline;
class operator Implicit(const ai: TOmniAlignedInt32): PInteger; inline;
class operator LessThan(const ai: TOmniAlignedInt32; i: integer): boolean; {$IFDEF OTL_CanInlineOperators}inline;{$ENDIF}
class operator LessThanOrEqual(const ai: TOmniAlignedInt32; i: integer): boolean; {$IFDEF OTL_CanInlineOperators}inline;{$ENDIF}
class operator NotEqual(const ai: TOmniAlignedInt32; i: integer): boolean; {$IFDEF OTL_CanInlineOperators}inline;{$ENDIF}
class operator Subtract(const ai: TOmniAlignedInt32; i: integer): cardinal;
property Value: integer read GetValue write SetValue;
end; { TOmniAlignedInt32 }
TOmniAlignedInt64 = record
strict private
FData: packed record
DataLo, DataHi: int64;
end;
FAddr: PInt64;
function GetValue: int64; inline;
procedure SetValue(value: int64); inline;
public
procedure Initialize; inline;
function Add(value: int64): int64; inline;
function Addr: PInt64; inline;
function CAS(oldValue, newValue: int64): boolean;
function Decrement: int64; overload; inline;
function Decrement(value: int64): int64; overload; inline;
function Increment: int64; overload; inline;
function Increment(value: int64): int64; overload; inline;
function Subtract(value: int64): int64; inline;
property Value: int64 read GetValue write SetValue;
end; { TOmniAlignedInt64 }
{$IFNDEF MSWINDOWS}
TObjectList = class(TObjectList<TObject>)
end;
{$ENDIF}
function CreateCounter(initialValue: integer = 0): IOmniCounter;
function CreateInterfaceDictionary: IOmniInterfaceDictionary;
function CreateWaitableValue: IOmniWaitableValue;
function CreateAutoDestroyObject(obj: TObject): IOmniAutoDestroyObject;
function Environment: IOmniEnvironment;
function VarToObj(const v: Variant): TObject; inline;
function NextOid: int64;
var
{$IFDEF OTL_USE_ALIGN}
[Volatile] OtlUID: int64 = 0;
{$ELSE}
OtlUID: TOmniAlignedInt64;
{$ENDIF}
TOmniValue_DataSize: array [TTypeKind] of integer;
implementation
{$IFDEF MSWINDOWS}
uses
{$IFDEF OTL_StrPasInAnsiStrings}System.AnsiStrings,{$ENDIF}
GpStringHash,
OtlCommon.Utils,
OtlSync;
{$ENDIF}
type
{$IFDEF MSWINDOWS}
IOmniAnsiStringData = interface ['{DBF5674C-AEFF-4CBD-AEC5-95F7A2FC80FF}']
function GetValue: AnsiString;
procedure SetValue(const value: AnsiString);
property Value: AnsiString read GetValue write SetValue;
end; { IOmniStringData }
TOmniAnsiStringData = class(TInterfacedObject, IOmniAnsiStringData)
strict private
osdValue: AnsiString;
public
constructor Create(const value: AnsiString);
function GetValue: AnsiString;
procedure SetValue(const value: AnsiString);
property Value: AnsiString read GetValue write SetValue;
end; { TOmniAnsiStringData }
{$ENDIF}
IOmniStringData = interface ['{21E52E56-390C-4066-B9FC-83862FFBCBF3}']
function GetValue: string;
procedure SetValue(const value: string);
property Value: string read GetValue write SetValue;
end; { IOmniStringData }
TOmniStringData = class(TInterfacedObject, IOmniStringData)
strict private
osdValue: string;
public
constructor Create(const value: string);
function GetValue: string;
procedure SetValue(const value: string);
property Value: string read GetValue write SetValue;
end; { TOmniStringData }
{$IFDEF MSWINDOWS}
IOmniWideStringData = interface ['{B303DB23-4A06-4D25-814A-8A9EDC90D066}']
function GetValue: WideString;
procedure SetValue(const value: WideString);
property Value: WideString read GetValue write SetValue;
end; { IOmniWideStringData }
TOmniWideStringData = class(TInterfacedObject, IOmniWideStringData)
strict private
osdValue: WideString;
public
constructor Create(const value: WideString);
function GetValue: WideString;
procedure SetValue(const value: WideString);
property Value: WideString read GetValue write SetValue;
end; { TOmniWideStringData }
{$ENDIF}
IOmniVariantData = interface ['{65311D7D-67F1-452E-A0BD-C90596671FC8}']
function GetValue: Variant;
procedure SetValue(const value: Variant);
property Value: Variant read GetValue write SetValue;
end; { IOmniVariantData }
TOmniVariantData = class(TInterfacedObject, IOmniVariantData)
strict private
ovdValue: Variant;
public
constructor Create(const value: Variant);
function GetValue: Variant;
procedure SetValue(const value: Variant);
property Value: Variant read GetValue write SetValue;
end; { TOmniVariantData }
IOmniExtendedData = interface ['{B6CD371F-A461-436A-8767-9BCA194B1D0E}']
function GetValue: Extended;
procedure SetValue(const value: Extended);
property Value: Extended read GetValue write SetValue;
end; { IOmniExtendedData }
TOmniExtendedData = class(TInterfacedObject, IOmniExtendedData)
strict private
oedValue: Extended;
public
constructor Create(const value: Extended);
function GetValue: Extended;
procedure SetValue(const value: Extended);
property Value: Extended read GetValue write SetValue;
end; { TOmniExtendedData }
TOmniCounterImpl = class(TInterfacedObject, IOmniCounter)
strict private
{$IFDEF OTL_USE_ALIGN}
[Volatile] FValue: integer;
{$ELSE}
ocValue: TOmniAlignedInt32;
{$ENDIF}
protected
function GetValue: integer; inline;
procedure SetValue(const value: integer); inline;
public
constructor Create(initialValue: integer);
function Decrement: integer; inline;
function Increment: integer; inline;
function Take(count: integer): integer; overload;
function Take(count: integer; var taken: integer): boolean; overload; inline;
property Value: integer read GetValue write SetValue;
end; { TOmniCounterImpl }
{$IFNDEF OTL_GoodGenerics}
PPHashItem = ^PHashItem;
PHashItem = ^THashItem;
THashItem = record
Next : PHashItem;
Key : int64;
Value: IInterface;
end; { THashItem }
TBucketArray = array of PHashItem;
PBucketArray = ^TBucketArray;
TOmniInterfaceDictionaryEnumerator = class(TInterfacedObject, IOmniInterfaceDictionaryEnumerator)
strict private
ideBuckets : PBucketArray;
ideBucketIdx: integer;
ideCurrent : PHashItem;
ideItem : PHashItem;
idePair : TOmniInterfaceDictionaryPair;
public
constructor Create(buckets: PBucketArray);
destructor Destroy; override;
function GetCurrent: TOmniInterfaceDictionaryPair;
function MoveNext: boolean;
property Current: TOmniInterfaceDictionaryPair read GetCurrent;
end; { IOmniInterfaceDictionaryEnumerator }
{$ENDIF ~OTL_GoodGenerics}
TOmniInterfaceDictionary = class(TInterfacedObject, IOmniInterfaceDictionary)
{$IFDEF OTL_GoodGenerics}
strict private
FDictionary: TDictionary<int64, IInterface>;
{$ELSE}
strict private
idBuckets: TBucketArray;
idCount : integer;
strict protected
function Find(const key: int64): PPHashItem;
function HashOf(const key: int64): integer; inline;
procedure Resize(size: Cardinal);
{$ENDIF OTL_GoodGenerics}
public
constructor Create;
destructor Destroy; override;
procedure Add(const key: int64; const value: IInterface);
procedure Clear;
function Count: integer; inline;
{$IFDEF OTL_GoodGenerics}
function GetEnumerator: TDictionary<int64, IInterface>.TPairEnumerator;
{$ELSE}
function GetEnumerator: IOmniInterfaceDictionaryEnumerator;
{$ENDIF ~OTL_GoodGenerics}
procedure Remove(const key: int64);
function ValueOf(const key: int64): IInterface;
end; { TOmniInterfaceDictionary }
TOmniAffinityTarget = (atSystem, atProcess, atThread);
TOmniAffinity = class(TInterfacedObject, IOmniAffinity)
strict private
oaTarget: TOmniAffinityTarget;
protected
function GetAsString: string;
function GetCount: integer;
function GetCountPhysical: integer;
procedure SetAsString(const value: string);
procedure SetCount(const value: integer);
{$IFDEF MSWINDOWS}
function GetMask: NativeUInt;
procedure SetMask(const value: NativeUInt);
{$ENDIF}
public
constructor Create(target: TOmniAffinityTarget);
property AsString: string read GetAsString write SetAsString;
property Count: integer read GetCount write SetCount;
{$IFDEF MSWINDOWS}
property Mask: NativeUInt read GetMask write SetMask;
{$ENDIF}
end; { TOmniAffinity }
TOmniProcessEnvironment = class(TInterfacedObject, IOmniProcessEnvironment)
strict private
opeAffinity: IOmniAffinity;
protected
function GetAffinity: IOmniAffinity;
function GetPriorityClass: TOmniProcessPriorityClass;
{$IFDEF MSWINDOWS}
function GetMemory: TOmniProcessMemoryCounters;
function GetTimes: TOmniProcessTimes;
{$ENDIF}
public
constructor Create;
property Affinity: IOmniAffinity read GetAffinity;
property PriorityClass: TOmniProcessPriorityClass read GetPriorityClass;
{$IFDEF MSWINDOWS}
property Memory: TOmniProcessMemoryCounters read GetMemory;
property Times: TOmniProcessTimes read GetTimes;
{$ENDIF}
end; { TOmniProcessEnvironment }
TOmniSystemEnvironment = class(TInterfacedObject, IOmniSystemEnvironment)
strict private
oseAffinity: IOmniAffinity;
protected
function GetAffinity: IOmniAffinity;
public
constructor Create;
property Affinity: IOmniAffinity read GetAffinity;
end; { TOmniSystemEnvironment }
TOmniThreadEnvironment = class(TInterfacedObject, IOmniThreadEnvironment)
strict private
oteAffinity: IOmniAffinity;
oteThreadID: TThreadID;
protected
function GetAffinity: IOmniAffinity;
function GetGroupAffinity: TOmniGroupAffinity;
function GetID: TThreadID;
procedure SetGroupAffinity(const value: TOmniGroupAffinity);
public
constructor Create;
property Affinity: IOmniAffinity read GetAffinity;
property GroupAffinity: TOmniGroupAffinity read GetGroupAffinity write SetGroupAffinity;
property ID: TThreadID read GetID;
end; { TOmniThreadEnvironment }
{$IFDEF OTL_NUMASupport}
TOmniNUMANode = class(TInterfacedObject, IOmniNUMANode)
private
FAffinity : IOmniIntegerSet;
FGroupNumber: integer;
FNodeNumber : integer;
protected
function GetAffinity: IOmniIntegerSet;
function GetGroupNumber: integer;
function GetNodeNumber: integer;
public
constructor Create(nodeNumber, groupNumber: integer; affinity: NativeUInt);
property Affinity: IOmniIntegerSet read GetAffinity;
property GroupNumber: integer read GetGroupNumber;
property NodeNumber: integer read GetNodeNumber;
end; { TOmniNUMANode }
IOmniNUMANodesInternal = interface ['{080E0660-4D9C-4F47-994E-9D0337AABB2B}']
procedure Add(const node: IOmniNUMANode);
procedure Sort;
end; { IOmniNUMANodesInternal }
TOmniNUMANodes = class(TInterfacedObject, IOmniNUMANodes,
IOmniNUMANodesInternal)
private
FNodes : TList<IOmniNUMANode>;
FProximityInitialized: boolean;
FProximity : array of array of integer;
protected
function GetItem(idx: integer): IOmniNUMANode; inline;
procedure InitializeProximity;
public
constructor Create;
destructor Destroy; override;
procedure Add(const node: IOmniNUMANode); inline;
function All: IOmniIntegerSet;
function Count: integer; inline;
function Distance(fromNode, toNode: integer): integer;
function FindNode(nodeNumber: integer): IOmniNUMANode;
function GetEnumerator: TList<IOmniNUMANode>.TEnumerator; inline;
procedure Sort;
property Item[idx: integer]: IOmniNUMANode read GetItem; default;
end; { TOmniNUMANodes }
TOmniProcessorGroup = class(TInterfacedObject, IOmniProcessorGroup)
private
FAffinity : IOmniIntegerSet;
FGroupNumber: integer;
protected
function GetAffinity: IOmniIntegerSet;
function GetGroupNumber: integer;
public
constructor Create(groupNumber: integer; affinity: NativeUInt);
property Affinity: IOmniIntegerSet read GetAffinity;
property GroupNumber: integer read GetGroupNumber;
end; { TOmniProcessorGroup }
IOmniProcessorGroupsInternal = interface ['{E9A146BC-C1CF-4D2B-8764-2041AC24D424}']
procedure Add(const group: IOmniProcessorGroup);
end; { IOmniProcessorGroupsInternal }
TOmniProcessorGroups = class(TInterfacedObject, IOmniProcessorGroups,
IOmniProcessorGroupsInternal)
private
FGroups: TList<IOmniProcessorGroup>;
protected
function GetItem(idx: integer): IOmniProcessorGroup; inline;
public
constructor Create;
destructor Destroy; override;
procedure Add(const group: IOmniProcessorGroup); inline;
function All: IOmniIntegerSet;
function Count: integer; inline;
function FindGroup(groupNumber: integer): IOmniProcessorGroup; inline;
function GetEnumerator: TList<IOmniProcessorGroup>.TEnumerator; inline;
property Item[idx: integer]: IOmniProcessorGroup read GetItem; default;
end; { IOmniProcessorGroups }
{$ENDIF OTL_NUMASupport}
TOmniEnvironment = class(TInterfacedObject, IOmniEnvironment)
strict private
oeProcessEnv: IOmniProcessEnvironment;
oeSystemEnv : IOmniSystemEnvironment;
{$IFDEF OTL_NUMASupport}
oeNUMANodes : IOmniNUMANodes;
oeProcessorGroups: IOmniProcessorGroups;
strict protected
procedure CreateFakeNUMAInfo;
procedure LoadNUMAInfo;
{$ENDIF OTL_NUMASupport}
protected
{$IFDEF OTL_NUMASupport}
function GetNUMANodes: IOmniNUMANodes;
function GetProcessorGroups: IOmniProcessorGroups;
{$ENDIF OTL_NUMASupport}
function GetProcess: IOmniProcessEnvironment;
function GetSystem: IOmniSystemEnvironment;
function GetThread: IOmniThreadEnvironment;
public
constructor Create;
{$IFDEF OTL_NUMASupport}
destructor Destroy; override;
property NUMANodes: IOmniNUMANodes read GetNUMANodes;
property ProcessorGroups: IOmniProcessorGroups read GetProcessorGroups;
{$ENDIF OTL_NUMASupport}
property Process: IOmniProcessEnvironment read GetProcess;
property System: IOmniSystemEnvironment read GetSystem;
property Thread: IOmniThreadEnvironment read GetThread;
end; { TOmniEnvironment }
TOmniAutoDestroyObject = class(TInterfacedObject, IOmniAutoDestroyObject)
strict private
FValue: TObject;
protected
function Detach: TObject;
protected
function GetValue: TObject;
procedure SetValue(const value: TObject);
public
constructor Create(obj: TObject);
destructor Destroy; override;
property Value: TObject read FValue write SetValue;
end; { TOmniAutoDestroyObject }
var
GEnvironment: IOmniEnvironment;
{ exports }
function CreateAutoDestroyObject(obj: TObject): IOmniAutoDestroyObject;
begin
Result := TOmniAutoDestroyObject.Create(obj);
end; { CreateAutoDestroyObject }
function CreateCounter(initialValue: integer): IOmniCounter;
begin
Result := TOmniCounterImpl.Create(initialValue);
end; { CreateCounter }
function CreateInterfaceDictionary: IOmniInterfaceDictionary;
begin
Result := TOmniInterfaceDictionary.Create;
end; { CreateInterfaceDictionary }
function CreateWaitableValue: IOmniWaitableValue;
begin
Result := TOmniWaitableValue.Create;
end; { CreateWaitableValue }
function Environment: IOmniEnvironment;
begin
Result := GEnvironment;
end; { Environment }
function VarToObj(const v: Variant): TObject;
begin
Result := TObject({$IFDEF Unicode}NativeUInt{$ELSE}cardinal{$ENDIF}(v));
end; { VarToObj }
{ globals }
{$IFDEF MSWINDOWS}
function StrPasA(const Str: PAnsiChar): AnsiString;
begin
Result := {$IFDEF OTL_StrPasInAnsiStrings}System.AnsiStrings.{$ENDIF}StrPas(Str);
end; { StrPasA }
{$ENDIF}
{$IFDEF OTL_Generics}
{ TOmniRecordWrapper }
constructor TOmniRecordWrapper<T>.Create(const value: T);
begin
inherited Create;
SetRecord(value);
end; { TOmniRecordWrapper<T>.Create }
function TOmniRecordWrapper<T>.GetRecord: T;
begin
Result := FValue;
end; { TOmniRecordWrapper<T>.GetRecord }
procedure TOmniRecordWrapper<T>.SetRecord(const value: T);
begin
FValue := value;
end; { TOmniRecordWrapper<T>.SetRecord }
{$ENDIF OTL_Generics}
{ TOmniAutoDestroyObject }
constructor TOmniAutoDestroyObject.Create(obj: TObject);
begin
inherited Create;
FValue := obj;
end; { TOmniAutoDestroyObject.Create }
destructor TOmniAutoDestroyObject.Destroy;
begin
FreeAndNil(FValue);
inherited;
end; { TOmniAutoDestroyObject.Destroy }
function TOmniAutoDestroyObject.GetValue: TObject;
begin
Result := FValue;
end; { TOmniAutoDestroyObject.GetValue }
procedure TOmniAutoDestroyObject.SetValue(const value: TObject);
begin
FValue := value;
end; { TOmniAutoDestroyObject.SetValue }
function TOmniAutoDestroyObject.Detach: TObject;
begin
Result := FValue;
FValue := nil
end; { TOmniAutoDestroyObject.Detach }
{ TOmniValueContainer }
constructor TOmniValueContainer.Create;
begin
inherited Create;
ovcCanModify := true;
ovcCount := 0;
end; { TOmniValueContainer.Create }
procedure TOmniValueContainer.Clear; //inline
begin
SetLength(ovcNames, 0);
SetLength(ovcValues, 0);
ovcCount := 0;
end; { TOmniValueContainer.Clear }
procedure TOmniValueContainer.Add(const paramValue: TOmniValue; const paramName: string);
var
idxParam: integer;
begin
if not ovcCanModify then
raise Exception.Create('TOmniValueContainer: Locked');
if paramName = '' then
idxParam := -1
else
idxParam := IndexOf( paramName);
if idxParam < 0 then
idxParam := AddParam( paramName);
ovcValues[ idxParam] := paramValue;
end; { TOmniValueContainer.Add }
function TOmniValueContainer.AddParam(const paramName: string): integer;
begin
Result := ovcCount;
Inc(ovcCount);
if Result > High(ovcValues) then
Grow;
ovcNames[Result] := paramName;
end; { TOmniValueContainer.AddParam }
procedure TOmniValueContainer.Assign(const parameters: array of TOmniValue);
var
value: TOmniValue;
begin
if not ovcCanModify then
raise Exception.Create('TOmniValueContainer: Already locked');
Clear;
Grow(Length(parameters)-1);
for value in parameters do
Add(value);
end; { TOmniValueContainer.Assign }
procedure TOmniValueContainer.AssignNamed(const parameters: array of TOmniValue);
var
i: integer;
begin
if not ovcCanModify then
raise Exception.Create('TOmniValueContainer.AssignNamed: Already locked');
if Odd(Length(parameters)) then
raise Exception.Create('TOmniValueContainer.AssignNamed: Not a proper number of parameters');
Clear;
Grow(Length(parameters) div 2 - 1);
i := Low(parameters);
while i < High(parameters) do begin
Add(parameters[i+1], parameters[i]);
Inc(i, 2);
end;
end; { TOmniValueContainer.AssignNamed }
function TOmniValueContainer.ByName(const paramName: string): TOmniValue;
begin
Result := ByName(paramName, TOmniValue.Null);
end; { TOmniValueContainer.ByName }
function TOmniValueContainer.ByName(const paramName: string; const defValue: TOmniValue):
TOmniValue;
var
idxParam: integer;
begin
idxParam := IndexOf(paramName);
if idxParam >= 0 then
Result := GetItem(idxParam)
else
Result := defValue;
end; { TOmniValueContainer.ByName }
function TOmniValueContainer.Count: integer;
begin
Result := ovcCount;
end; { TOmniValueContainer.Count }
function TOmniValueContainer.Exists(const paramName: string): boolean;
begin
Result := (IndexOf(paramName) >= 0);
end; { TOmniValueContainer.Exists }
function TOmniValueContainer.GetItem(paramIdx: integer): TOmniValue;
begin
Assert(paramIdx < ovcCount);
Result := ovcValues[paramIdx];
end; { TOmniValueContainer.GetItem }
function TOmniValueContainer.GetItem(const paramName: string): TOmniValue;
var
idxParam: integer;
begin
idxParam := IndexOf(paramName);
if idxParam >= 0 then
Result := GetItem(idxParam)
else
raise Exception.CreateFmt('TOmniValueContainer.GetItem: Parameter %s does not exist', [paramName]);
end; { TOmniValueContainer.GetItem }
function TOmniValueContainer.GetItem(const param: TOmniValue): TOmniValue;
begin
if param.IsInteger then
Result := GetItem(param.AsInteger)
else if param.IsString then
Result := GetItem(param.AsString)
else
raise Exception.Create('TOmniValueContainer.GetItem: Container can only be indexed by integer or string.');
end; { TOmniValueContainer.GetItem }
procedure TOmniValueContainer.Grow(requiredIdx: integer = -1);
var
iValue : integer;
newLength: integer;
tmpNames : array of string;
tmpValues: array of TOmniValue;
begin
Assert(Length(ovcNames) = Length(ovcValues));
SetLength(tmpNames, Length(ovcNames));
SetLength(tmpValues, Length(ovcValues));
for iValue := 0 to High(ovcValues) - 1 do begin
tmpNames[iValue] := ovcNames[iValue];
tmpValues[iValue] := ovcValues[iValue];
end;
newLength := 2*Length(ovcValues)+1;
if newLength <= requiredIdx then
newLength := requiredIdx + 1;
SetLength(ovcNames, newLength);
SetLength(ovcValues, newLength);
for iValue := 0 to High(tmpValues) - 1 do begin
ovcNames[iValue] := tmpNames[iValue];
ovcValues[iValue] := tmpValues[iValue];
end;
end; { TOmniValueContainer.Grow }
function TOmniValueContainer.IndexOf(const paramName: string): integer;
begin
for Result := 0 to ovcCount - 1 do
if SameText(paramName, ovcNames[Result]) then
Exit;
Result := -1;
end; { TOmniValueContainer.IndexOf }
procedure TOmniValueContainer.Insert(paramIdx: integer; const value: TOmniValue);
begin
if paramIdx > High(ovcValues) then
Grow(paramIdx);
if paramIdx >= ovcCount then
ovcCount := paramIdx + 1;
ovcValues[paramIdx] := value;
end; { TOmniValueContainer.Insert }
function TOmniValueContainer.IsLocked: boolean;
begin
Result := not ovcCanModify;
end; { TOmniValueContainer.IsLocked }
procedure TOmniValueContainer.Lock;
begin
ovcCanModify := false;
end; { TOmniValueContainer.Lock }
procedure TOmniValueContainer.SetItem(idx: integer; const value: TOmniValue);
begin
if IsLocked then
raise Exception.Create('TOmniValueContainer.SetItem: Container is locked');
Insert(idx, value);
end; { TOmniValueContainer.SetItem }
procedure TOmniValueContainer.SetItem(const name: string; const value: TOmniValue);
var
idx: integer;
begin
if IsLocked then
raise Exception.Create('TOmniValueContainer.SetItem: Container is locked');
idx := IndexOf(name);
if idx < 0 then
idx := AddParam(name);
SetItem(idx, value);
end; { TOmniValueContainer.SetItem }
procedure TOmniValueContainer.SetItem(const param, value: TOmniValue);
begin
if param.IsInteger then
SetItem(param.AsInteger, value)
else if param.IsString then
SetItem(param.AsString, value)
else
raise Exception.Create('TOmniValueContainer.SetItem: Container can only be indexed by integer or string.');
end; { TOmniValueContainer.SetItem }
{ TOmniCounter }
function TOmniCounter.Decrement: integer;
begin
Initialize;
Result := ocCounter.Decrement;
end; { TOmniCounter.Decrement }
function TOmniCounter.GetValue: integer;
begin
Initialize;
Result := ocCounter.GetValue;
end;
function TOmniCounter.Increment: integer;
begin
Initialize;
Result := ocCounter.Increment;
end; { TOmniCounter.Increment }
procedure TOmniCounter.Initialize;
{$IFDEF MSWINDOWS}
var
countIntf: IOmniCounter;
begin
Assert(cardinal(@ocCounter) mod SizeOf(ocCounter) = 0,
Format('TOmniCS.Initialize: ocsSync is not %d-aligned!', [SizeOf(ocCounter)]));
if not assigned(ocCounter) then
begin
countIntf := CreateCounter;
{$IFDEF CPUX64}
if InterlockedCompareExchange64(PInt64(@ocCounter)^, int64(countIntf), 0) = 0 then
{$ELSE}
if InterlockedCompareExchange(PInteger(@ocCounter)^, integer(countIntf), 0) = 0 then
{$ENDIF ~CPUX64}
pointer(countIntf) := nil;
end;
{$ELSE}
var
Newbie: IOmniCounter;
begin
if assigned(ocCounter) then exit;
Newbie := CreateCounter;
if AtomicCmpExchange(pointer(ocCounter), pointer(Newbie), nil) = nil then
// Clear Newbie without decrementing the reference count.
PPointer(@Newbie)^ := nil
{$ENDIF}
end; { TOmniCounter.Initialize }
procedure TOmniCounter.SetValue(const value: integer);
begin
Initialize;
ocCounter.SetValue(value);
end; { TOmniCounter.SetValue }
function TOmniCounter.Take(count: integer): integer;
begin
Result := ocCounter.Take(count);
end; { TOmniCounter.Take }
function TOmniCounter.Take(count: integer; var taken: integer): boolean;
begin
Result := ocCounter.Take(count, taken);
end; { TOmniCounter.Take }
{ TOmniCounterImpl }
constructor TOmniCounterImpl.Create( initialValue: integer);
begin
{$IFDEF OTL_USE_ALIGN}
FValue := initialValue;
{$ELSE}
ocValue.Initialize;
ocValue.Value := initialValue;
{$ENDIF}
end; { TOmniCounterImpl.Create }
function TOmniCounterImpl.GetValue: integer;
begin
{$IFDEF OTL_USE_ALIGN}
Result := FValue;
{$ELSE}
Result := ocValue.Value
{$ENDIF}
end; { TOmniCounterImpl.GetValue }
function TOmniCounterImpl.Decrement: integer;
begin
{$IFDEF OTL_USE_ALIGN}
Result := TInterlocked.Decrement(FValue);
{$ELSE}
Result := ocValue.Decrement;
{$ENDIF} { TOmniCounterImpl.Decrement }
end;
function TOmniCounterImpl.Increment: integer;
begin
{$IFDEF OTL_USE_ALIGN}
Result := TInterlocked.Increment(FValue);
{$ELSE}
Result := ocValue.Increment;
{$ENDIF}
end; { TOmniCounterImpl.Increment }
procedure TOmniCounterImpl.SetValue(const Value: integer);
begin
{$IFDEF OTL_USE_ALIGN}
FValue := Value
{$ELSE}
ocValue.Value := value;
{$ENDIF}
end; { TOmniCounterImpl.SetValue }
function TOmniCounterImpl.Take(count: integer): integer;
{$IFDEF OTL_USE_ALIGN}
var
current : integer;
newValue: integer;
request : integer;
begin
request := count;
while request > 0 do begin
current := FValue;
if current <= 0 then
break;
newValue := current - request;
if newValue < 0 then
newValue := 0;
if TInterlocked.CompareExchange(FValue, newValue, current) = current then begin
Dec(request, current - newValue);
current := newValue;
end;
end;
Result := count - request;
{$ELSE}
var
current : integer;
newValue: integer;
begin
repeat
current := Value;
if current <= 0 then begin
Result := 0;
Exit;
end;
newValue := current - count;
if newValue < 0 then
newValue := 0;
if ocValue.CAS(current, newValue) then begin
Result := current - newValue;
Exit;
end;
until false;
{$ENDIF}
end; { TOmniCounterImpl.Take }
function TOmniCounterImpl.Take(count: integer; var taken: integer): boolean;
begin
taken := Take(count);
Result := taken > 0
end; { TOmniCounterImpl.Take }
{$IFNDEF OTL_GoodGenerics}
{ TOmniInterfaceDictionaryPair }
procedure TOmniInterfaceDictionaryPair.SetKeyValue(const key: int64; const value: IInterface);
begin
idpKey := key;
idpValue := value;
end; { TOmniInterfaceDictionaryPair.SetKeyValue }
{ TOmniInterfaceDictionaryEnumerator }
constructor TOmniInterfaceDictionaryEnumerator.Create(buckets: PBucketArray);
begin
ideBuckets := buckets;
ideBucketIdx := Low(ideBuckets^);
ideItem := nil;
idePair := TOmniInterfaceDictionaryPair.Create;
end; { TOmniInterfaceDictionaryEnumerator.Create }
destructor TOmniInterfaceDictionaryEnumerator.Destroy;
begin
FreeAndNil(idePair);
inherited Destroy;
end; { TOmniInterfaceDictionaryEnumerator.Destroy }
function TOmniInterfaceDictionaryEnumerator.GetCurrent: TOmniInterfaceDictionaryPair;
begin
idePair.SetKeyValue(ideCurrent^.Key, ideCurrent^.Value);
Result := idePair;
end; { TOmniInterfaceDictionaryEnumerator.GetCurrent }
function TOmniInterfaceDictionaryEnumerator.MoveNext: boolean;
begin
Result := false;
while not assigned(ideItem) do begin
Inc(ideBucketIdx);
if ideBucketIdx > High(ideBuckets^) then
Exit;
ideItem := ideBuckets^[ideBucketIdx];
end;
ideCurrent := ideItem;
ideItem := ideItem^.Next;
Result := true;
end; { TOmniInterfaceDictionaryEnumerator.MoveNext }
{$ENDIF ~OTL_GoodGenerics}
{ TOmniInterfaceDictionary }
constructor TOmniInterfaceDictionary.Create;
begin
inherited Create;
{$IFDEF OTL_GoodGenerics}
FDictionary := TDictionary<int64, IInterface>.Create(100);
{$ELSE}
Resize(1);
{$ENDIF ~OTL_GoodGenerics}
end; { TOmniInterfaceDictionary.Create }
destructor TOmniInterfaceDictionary.Destroy;
begin
{$IFDEF OTL_GoodGenerics}
FreeAndNil(FDictionary);
{$ELSE}
Clear;
{$ENDIF ~OTL_GoodGenerics}
inherited;
end; { TOmniInterfaceDictionary.Destroy }
procedure TOmniInterfaceDictionary.Add(const key: int64; const value: IInterface);
{$IFNDEF OTL_GoodGenerics}
var
bucket: PHashItem;
hash : integer;
{$ENDIF ~OTL_GoodGenerics}
begin
{$IFDEF OTL_GoodGenerics}
FDictionary.AddOrSetValue(key, value);
{$ELSE}
hash := HashOf(key);
New(bucket);
bucket^.Key := key;
bucket^.Value := value;
bucket^.Next := idBuckets[hash];
idBuckets[hash] := bucket;
Inc(idCount);
if idCount > (1.5 * Length(idBuckets)) then
Resize(idCount * 2);
{$ENDIF ~OTL_GoodGenerics}
end; { TOmniInterfaceDictionary.Add }
procedure TOmniInterfaceDictionary.Clear;
{$IFNDEF OTL_GoodGenerics}
var
bucket : PHashItem;
iBucket: integer;
next : PHashItem;
{$ENDIF ~OTL_GoodGenerics}
begin
{$IFDEF OTL_GoodGenerics}
FDictionary.Clear;
{$ELSE}
for iBucket := 0 to Length(idBuckets) - 1 do begin
bucket := idBuckets[iBucket];
while bucket <> nil do begin
next := bucket^.Next;
bucket^.Value := nil;
Dispose(bucket);
bucket := next;
end;
idBuckets[iBucket] := nil;
end;
idCount := 0;
{$ENDIF ~OTL_GoodGenerics}
end; { TOmniInterfaceDictionary.Clear }
function TOmniInterfaceDictionary.Count: integer;
begin
{$IFDEF OTL_GoodGenerics}
Result := FDictionary.Count;;
{$ELSE}
Result := idCount;
{$ENDIF ~OTL_GoodGenerics}
end; { TOmniInterfaceDictionary.Count }
{$IFNDEF OTL_GoodGenerics}
function TOmniInterfaceDictionary.Find(const key: int64): PPHashItem;
var
hash: integer;
begin
hash := HashOf(key);
Result := @idBuckets[hash];
while Result^ <> nil do begin
if Result^.key = key then
Exit
else
Result := @Result^.Next;
end;
end; { TOmniInterfaceDictionary.Find }
{$ENDIF ~OTL_GoodGenerics}
function TOmniInterfaceDictionary.GetEnumerator: {$IFDEF OTL_GoodGenerics}TDictionary<int64, IInterface>.TPairEnumerator{$ELSE}IOmniInterfaceDictionaryEnumerator{$ENDIF OTL_GoodGenerics};
begin
{$IFDEF OTL_GoodGenerics}
Result := FDictionary.GetEnumerator;
{$ELSE}
Result := TOmniInterfaceDictionaryEnumerator.Create(@idBuckets);
{$ENDIF ~OTL_GoodGenerics}
end; { TOmniInterfaceDictionary.GetEnumerator }
{$IFNDEF OTL_GoodGenerics}
function TOmniInterfaceDictionary.HashOf(const key: int64): integer;
begin
Result := key mod Length(idBuckets);
end; { TOmniInterfaceDictionary.HashOf }
{$ENDIF ~OTL_GoodGenerics}
procedure TOmniInterfaceDictionary.Remove(const key: int64);
{$IFNDEF OTL_GoodGenerics}
var
bucket : PHashItem;
bucketHead: PPHashItem;
{$ENDIF ~OTL_GoodGenerics}
begin
{$IFDEF OTL_GoodGenerics}
if FDictionary.ContainsKey(key) then
FDictionary.Remove(key);
{$ELSE}
bucketHead := Find(key);
bucket := bucketHead^;
if assigned(bucket) then begin
bucketHead^ := bucket^.Next;
Dispose(bucket);
Dec(idCount);
end;
{$ENDIF ~OTL_GoodGenerics}
end; { TOmniInterfaceDictionary.Remove }
{$IFNDEF OTL_GoodGenerics}
procedure TOmniInterfaceDictionary.Resize(size: Cardinal);
var
bucket : PHashItem;
iBucket : integer;
next : PHashItem;
oldBuckets: TBucketArray;
oldSize : integer;
begin
if Cardinal(Length(idBuckets)) >= size then
Exit;
oldSize := Count;
oldBuckets := idBuckets;
idBuckets := nil;
idCount := 0;
SetLength(idBuckets, GetGoodHashSize(size));
for iBucket := 0 to High(oldBuckets) do begin
bucket := oldBuckets[iBucket];
while assigned(bucket) do begin
Add(bucket.Key, bucket.Value);
bucket.Value := nil;
next := bucket.Next;
Dispose(bucket);
bucket := next;
end;
end;
Assert(oldSize = Count);
end; { TOmniInterfaceDictionary.Resize }
{$ENDIF ~OTL_GoodGenerics}
function TOmniInterfaceDictionary.ValueOf(const key: int64): IInterface;
{$IFNDEF OTL_GoodGenerics}
var
bucketHead: PHashItem;
{$ENDIF ~OTL_GoodGenerics}
begin
{$IFDEF OTL_GoodGenerics}
if not FDictionary.TryGetValue(key, Result) then
Result := nil;
{$ELSE}
bucketHead := Find(key)^;
if bucketHead <> nil then
Result := bucketHead^.Value
else
Result := nil;
{$ENDIF ~OTL_GoodGenerics}
end; { TOmniInterfaceDictionary.ValueOf }
{ TOmniValue }
procedure TOmniValue.SetAsArray(value: TOmniValueContainer); //inline
begin
ovType := ovtArray;
ovIntf := CreateAutoDestroyObject(value);
ovData := int64(value);
end; { TOmniValue.SetAsArray }
function TOmniValue.TryCastToBoolean(var value: boolean): boolean; //inline
begin
if ovType <> ovtBoolean then
Result := false
else begin
value := PByte(@ovData)^ <> 0;
Result := true;
end;
end; { TOmniValue.TryCastToBoolean }
function TOmniValue.TryCastToInt64(var value: int64): boolean; //inline
begin
Result := true;
case ovType of
ovtInteger,
ovtInt64: value := ovData;
ovtNull: value := 0;
ovtVariant: value := integer(AsVariant);
else Result := false;
end;
end; { TOmniValue.TryGetAsInt64 }
function TOmniValue.TryCastToInteger(var value: integer): boolean; //integer
var
val64: int64;
begin
Result := TryCastToInt64(val64);
if Result then
value := val64;
end; { TOmniValue.TryCastToInteger }
function TOmniValue.TryCastToCardinal(var value: cardinal): boolean; //inline
var
val64: int64;
begin
Result := TryCastToInt64(val64);
if Result then
value := val64;
end; { TOmniValue.TryCastToCardinal }
function TOmniValue.TryCastToInterface(var value: IInterface): boolean;
begin
Result := true;
case ovType of
ovtInterface: value := ovIntf;
ovtNull: value := nil;
else Result := false;
end;
end; { TOmniValue.TryCastToInterface }
function TOmniValue.TryCastToObject(var value: TObject): boolean;
begin
Result := true;
case ovType of
ovtObject,
ovtException: value := TObject(ovData);
ovtOwnedObject: value := (ovIntf as IOmniAutoDestroyObject).Value;
ovtNull: value := nil;
else Result := false;
end;
end; { TOmniValue.TryCastToObject }
constructor TOmniValue.Create(const values: array of const);
var
i : integer;
ovc: TOmniValueContainer;
begin
ovc := TOmniValueContainer.Create;
for i := Low(values) to High(values) do begin
with values[i] do begin
case VType of
vtInteger: ovc.Add(VInteger);
vtBoolean: ovc.Add(VBoolean);
vtExtended: ovc.Add(VExtended^);
vtPointer: ovc.Add(VPointer);
vtCurrency: ovc.Add(VCurrency^);
vtVariant: ovc.Add(VVariant^);
vtObject: ovc.Add(VObject);
vtInterface: ovc.Add(IInterface(VInterface));
vtInt64: ovc.Add(VInt64^);
{$IFDEF UNICODE}
vtUnicodeString: ovc.Add(string(VUnicodeString));
{$ENDIF UNICODE}
{$IFNDEF NEXTGEN}
vtChar: ovc.Add(string(VChar));
vtString: ovc.Add(string(VString^));
{$ENDIF NEXTGEN}
{$IFDEF MSWINDOWS}
vtAnsiString: ovc.Add(AnsiString(VAnsiString));
vtWideString: ovc.Add(WideString(VWideString));
vtPChar: ovc.Add(string(StrPasA(VPChar)));
{$ENDIF MSWINDOWS}
else
raise Exception.Create ('TOmniValue.Create: invalid data type')
end; //case
end; //with
end; //for i
SetAsArray(ovc);
end; { TOmniValue.Create }
constructor TOmniValue.CreateNamed(const values: array of const;
const cppDupConWorkaround: boolean);
var
i : integer;
name: string;
ovc : TOmniValueContainer;
begin
ovc := TOmniValueContainer.Create;
Assert(not Odd(Low(values)));
name := '';
for i := Low(values) to High(values) do begin
with values[i] do begin
if not Odd(i) then
case VType of
vtVariant: name := string(VVariant^);
{$IFDEF UNICODE}
vtUnicodeString: name := string(VUnicodeString);
{$ENDIF UNICODE}
{$IFNDEF NEXTGEN}
vtChar: name := string(VChar);
vtString: name := string(VString^);
{$ENDIF NEXTGEN}
{$IFDEF MSWINDOWS}
vtAnsiString: name := string(VAnsiString);
vtWideString: name := WideString(VWideString);
vtPChar: name := string(StrPasA(VPChar));
{$ENDIF MSWINDOWS}
else
raise Exception.Create ('TOmniValue.CreateNamed: invalid name type')
end //case
else
case VType of
vtInteger: ovc.Add(VInteger, name);
vtBoolean: ovc.Add(VBoolean, name);
vtExtended: ovc.Add(VExtended^, name);
vtPointer: ovc.Add(VPointer, name);
vtCurrency: ovc.Add(VCurrency^, name);
vtVariant: ovc.Add(VVariant^, name);
vtObject: ovc.Add(VObject, name);
vtInterface: ovc.Add(IInterface(VInterface), name);
vtInt64: ovc.Add(VInt64^, name);
{$IFDEF UNICODE}
vtUnicodeString: ovc.Add(string(VUnicodeString), name);
{$ENDIF UNICODE}
{$IFNDEF NEXTGEN}
vtChar: ovc.Add(string(VChar), name);
vtString: ovc.Add(string(VString^), name);
{$ENDIF NEXTGEN}
{$IFDEF MSWINDOWS}
vtAnsiString: ovc.Add(AnsiString(VAnsiString), name);
vtWideString: ovc.Add(WideString(VWideString), name);
vtPChar: ovc.Add(string(StrPasA(VPChar)), name);
{$ENDIF MSWINDOWS}
else
raise Exception.Create ('TOmniValue.CreateNamed: invalid data type')
end; //case
end; //with
end; //for i
SetAsArray(ovc);
end; { TOmniValue.CreateNamed }
{$IFDEF OTL_Generics}
{$IFDEF OTL_HasArrayOfT}
function TOmniValue.ToArray<T>: TArray<T>;
var
iItem: integer;
begin
if not IsArray then
raise Exception.Create('TOmniValue does not contain an array');
SetLength(Result, TOmniValueContainer(ovData).Count);
for iItem := 0 to TOmniValueContainer(ovData).Count - 1 do
Result[iItem] := TOmniValueContainer(ovData)[iItem].CastTo<T>;
end; { TOmniValue.ToArray }
{$ENDIF OTL_HasArrayOfT}
function TOmniValue.ToRecord<T>: T;
begin
Result := TOmniRecordWrapper<T>(CastToRecord.Value).Value;
end; { TOmniValue.ToRecord }
function TOmniValue.CastTo<T>: T;
var
ds : integer;
maxValue: uint64;
ti : PTypeInfo;
{$IFDEF OTL_TypeInfoHasTypeData}
var
intf : IInterface;
value : TValue;
{$ENDIF OTL_TypeInfoHasTypeData}
begin
ds := 0;
ti := System.TypeInfo(T);
if assigned(ti) then
if (ti = System.TypeInfo(byte)) or (ti = System.TypeInfo(shortint)) then
ds := 1
else if (ti = System.TypeInfo(word)) or (ti = System.TypeInfo(smallint)) then
ds := 2
else
ds := TOmniValue_DataSize[ti^.Kind];
if ds = 0 then begin // complicated stuff
if ti.Kind = tkRecord then
Result := TOmniRecordWrapper<T>(CastToRecord.Value).Value
else begin
{$IFDEF OTL_ERTTI}
{$IFDEF OTL_TypeInfoHasTypeData}
if (ti.Kind = tkInterface)
and Supports(AsInterface, ti.TypeData.Guid, intf)
then begin
TValue.Make(@intf, ti, value);
Result := value.AsType<T>;
end
else
{$ENDIF OTL_TypeInfoHasTypeData}
Result := AsTValue.AsType<T>;
{$ELSE}
raise Exception.Create('Only casting to simple types is supported in Delphi 2009')
{$ENDIF OTL_ERTTI}
end;
end
else begin // simple types
if ds < 8 then begin
maxValue := uint64($FF) SHL ((ds-1) * 8);
if ovData > maxValue then
raise EOmniValueConv.CreateFmt('Value %d is too big to fit into %s', [ovData, ti^.Name]);
end;
Move(ovData, Result, ds);
end;
end; { TOmniValue.CastTo }
class function TOmniValue.CastFrom<T>(const value: T): TOmniValue;
var
data: int64;
ds : integer;
ti : PTypeInfo;
begin
ds := 0;
ti := System.TypeInfo(T);
if assigned(ti) then begin
if (ti = System.TypeInfo(byte)) or (ti = System.TypeInfo(shortint)) then
ds := 1
else if (ti = System.TypeInfo(word)) or (ti = System.TypeInfo(smallint)) then
ds := 2
else
ds := TOmniValue_DataSize[ti^.Kind];
end;
if ds = 0 then begin // complicated stuff
if ti^.Kind = tkRecord then
Result.SetAsRecord(CreateAutoDestroyObject(TOmniRecordWrapper<T>.Create(value)))
else
{$IFDEF OTL_ERTTI}
Result.AsTValue := TValue.From<T>(value)
{$ELSE}
raise Exception.Create('Only casting from simple types is supported in Delphi 2009')
{$ENDIF OTL_ERTTI}
end
else begin // simple types
data := 0;
Move(value, data, ds);
case ti^.Kind of
tkInteger:
Result.AsInteger := data;
tkClass:
Result.AsObject := TObject(data);
tkMethod:
Result.AsInt64 := data;
tkInt64:
Result.AsInt64 := data;
{$IFDEF OTL_HasTkPointer}
tkPointer:
Result.AsPointer := pointer(data);
{$ENDIF OTL_HasTkPointer}
else
raise Exception.CreateFmt('TOmniValue: CastFrom<%s> is broken!', [ti^.Name]);
end;
end;
end; { TOmniValue.CastFrom }
{$IFDEF OTL_HasArrayOfT}
class function TOmniValue.FromArray<T>(const values: TArray<T>): TOmniValue;
var
ovc : TOmniValueContainer;
value: T;
begin
ovc := TOmniValueContainer.Create;
for value in values do
ovc.Add(TOmniValue.CastFrom<T>(value));
Result.SetAsArray(ovc);
end; { TOmniValue.FromArray }
{$ENDIF OTL_HasArrayOfT}
class function TOmniValue.FromRecord<T>(const value: T): TOmniValue;
begin
Result.SetAsRecord(CreateAutoDestroyObject(TOmniRecordWrapper<T>.Create(value)));
end; { TOmniValue.FromRecord<T> }
class function TOmniValue.FromRecordUnsafe<T>(const value: T): TOmniValue;
begin
Result.SetAsRecord(CreateAutoDestroyObject(TOmniRecordWrapper<T>.Create(value)));
end; { TOmniValue.FromRecordUnsafe<T> }
{$IF CompilerVersion > 20}
function TOmniValue.ToObject<T>: T;
begin
{$IF CompilerVersion <= 21}
Result := T(AsObject as TClass(T));
{$ELSE}
Result := AsObject as T;
{$IFEND}
end; { TOmniValue.ToObject<T> }
{$IFEND}
{$IF CompilerVersion > 20}
function TOmniValue.CastToObject<T>: T;
begin
Result := T(AsObject);
end; { TOmniValue.CastToObject<T> }
{$IFEND}
function TOmniValue.Unwrap<T>: T;
begin
Result := TOmniRecordWrapper<T>(AsOwnedObject).Value;
end; { TOmniValue.Unwrap }
class function TOmniValue.Wrap<T>(const value: T): TOmniValue;
begin
Result.AsOwnedObject := TOmniRecordWrapper<T>.Create(value);
end; { TOmniValue.Wrap }
{$ENDIF OTL_Generics}
procedure TOmniValue.Clear;
begin
ovData := 0;
ovIntf := nil;
ovType := ovtNull;
end; { TOmniValue.Clear }
procedure TOmniValue.ClearIntf;
begin
if pointer(ovIntf) <> nil then
ovIntf := nil;
end; { TOmniValue.ClearIntf }
function TOmniValue.GetAsArray: TOmniValueContainer;
begin
if not IsArray then
raise Exception.Create('TOmniValue does not contain an array');
Result := TOmniValueContainer(ovData);
end; { TOmniValue.GetAsArray }
function TOmniValue.GetAsArrayItem(const name: string): TOmniValue;
begin
if not IsArray then
raise Exception.Create('TOmniValue does not contain an array');
Result := TOmniValueContainer(ovData)[name];
end; { TOmniValue.GetAsArrayItem }
{$IF CompilerVersion >= 19}//D2007 has problems understanding this overload
function TOmniValue.GetAsArrayItem(const param: TOmniValue): TOmniValue;
begin
if not IsArray then
raise Exception.Create('TOmniValue does not contain an array');
Result := TOmniValueContainer(ovData)[param];
end; { TOmniValue.GetAsArrayItem }
{$IFEND}
function TOmniValue.GetAsArrayItemOV(const param: TOmniValue): TOmniValue;
begin
if not IsArray then
raise Exception.Create('TOmniValue does not contain an array');
Result := TOmniValueContainer(ovData)[param];
end; { TOmniValue.GetAsArrayItemOV }
function TOmniValue.HasArrayItem(idx: integer): boolean;
begin
if not IsArray then
raise Exception.Create('TOmniValue does not contain an array');
Result := (idx >= 0) and (idx < TOmniValueContainer(ovData).Count);
end; { TOmniValue.HasArrayItem }
function TOmniValue.HasArrayItem(const name: string): boolean;
begin
if not IsArray then
raise Exception.Create('TOmniValue does not contain an array');
Result := (TOmniValueContainer(ovData).IndexOf(name) >= 0);
end; { TOmniValue.HasArrayItem }
function TOmniValue.HasArrayItem(const param: TOmniValue): boolean;
begin
if param.IsInteger then
Result := HasArrayItem(param.AsInteger)
else if param.IsString then
Result := HasArrayItem(param.AsString)
else
raise Exception.Create('TOmniValue contains neither an integer, string nor array');
end; { TOmniValue.HasArrayItem }
function TOmniValue.GetAsArrayItem(idx: integer): TOmniValue;
begin
if not IsArray then
raise Exception.Create('TOmniValue does not contain an array');
Result := TOmniValueContainer(ovData)[idx];
end; { TOmniValue.GetAsArrayItem }
{$IFDEF MSWINDOWS}
function TOmniValue.CastToAnsiString: AnsiString;
begin
if not TryCastToAnsiString(Result) then
raise Exception.Create('TOmniValue cannot be converted to AnsiString');
end; { TOmniValue.CastToAnsiString }
function TOmniValue.CastToAnsiStringDef(const defValue: AnsiString): AnsiString;
begin
if not TryCastToAnsiString(Result) then
Result := defValue;
end; { TOmniValue.CastToAnsiStringDef }
{$ENDIF}
function TOmniValue.CastToBoolean: boolean;
begin
if not TryCastToBoolean(Result) then
raise Exception.Create('TOmniValue cannot be converted to boolean');
end; { TOmniValue.CastToBoolean }
function TOmniValue.CastToBooleanDef(defValue: boolean): boolean;
begin
if not TryCastToBoolean(Result) then
Result := defValue;
end; { TOmniValue.CastToBooleanDef }
function TOmniValue.CastToCardinal: cardinal;
begin
Result := AsInt64;
end; { TOmniValue.CastToCardinal }
function TOmniValue.CastToCardinalDef(defValue: cardinal): cardinal;
begin
if not TryCastToCardinal(Result) then
Result := defValue;
end; { TOmniValue.CastToCardinalDef }
function TOmniValue.CastToDateTime: TDateTime;
begin
if not TryCastToDateTime(Result) then
raise Exception.Create('TOmniValue cannot be converted to TDateTime');
end; { TOmniValue.CastToDateTime }
function TOmniValue.CastToDateTimeDef(defValue: TDateTime): TDateTime;
begin
if not TryCastToDateTime(Result) then
Result := defValue;
end; { TOmniValue.CastToDateTimeDef }
function TOmniValue.CastToDouble: Double;
begin
if not TryCastToDouble(Result) then
raise Exception.Create('TOmniValue cannot be converted to double');
end; { TOmniValue.CastToDouble }
function TOmniValue.CastToDoubleDef(defValue: Double): Double;
begin
if not TryCastToDouble(Result) then
Result := defValue;
end; { TOmniValue.CastToDoubleDef }
function TOmniValue.CastToException: Exception;
begin
if not TryCastToException(Result) then
raise Exception.Create('TOmniValue cannot be converted to exception');
end; { TOmniValue.CastToException }
function TOmniValue.CastToExceptionDef(defValue: Exception): Exception;
begin
if not TryCastToException(Result) then
Result := defValue;
end; { TOmniValue.CastToExceptionDef }
function TOmniValue.CastToExtended: Extended;
begin
if not TryCastToExtended(Result) then
raise Exception.Create('TOmniValue cannot be converted to extended');
end; { TOmniValue.CastToExtended }
function TOmniValue.CastToExtendedDef(defValue: Extended): Extended;
begin
if not TryCastToExtended(Result) then
Result := defValue;
end; { TOmniValue.CastToExtendedDef }
function TOmniValue.CastToInt64: int64;
begin
if not TryCastToInt64(Result) then
raise Exception.Create('TOmniValue cannot be converted to int64');
end; { TOmniValue.CastToInt64 }
function TOmniValue.CastToInt64Def(defValue: int64): int64;
begin
if not TryCastToInt64(Result) then
Result := defValue;
end; { TOmniValue.CastToInt64Def }
function TOmniValue.CastToInteger: integer;
begin
Result := AsInt64;
end; { TOmniValue.CastToInteger }
function TOmniValue.CastToIntegerDef(defValue: integer): integer;
begin
if not TryCastToInteger(Result) then
Result := defValue;
end; { TOmniValue.CastToIntegerDef }
function TOmniValue.CastToInterface: IInterface;
begin
if not TryCastToInterface(Result) then
raise Exception.Create('TOmniValue cannot be converted to interface');
end; { TOmniValue.CastToInterface }
function TOmniValue.CastToInterfaceDef(const defValue: IInterface): IInterface;
begin
if not TryCastToInterface(Result) then
Result := defValue;
end; { TOmniValue.CastToInterfaceDef }
function TOmniValue.CastToObject: TObject;
begin
if not TryCastToObject(Result) then
raise Exception.Create('TOmniValue cannot be converted to object');
end; { TOmniValue.CastToObject }
function TOmniValue.CastToObjectDef(defValue: TObject): TObject;
begin
if not TryCastToObject(Result) then
Result := defValue;
end; { TOmniValue.CastToObjectDef }
function TOmniValue.CastToPointer: pointer;
begin
if not TryCastToPointer(Result) then
raise Exception.Create('TOmniValue cannot be converted to pointer');
end; { TOmniValue.CastToPointer }
function TOmniValue.CastToPointerDef(defValue: pointer): pointer;
begin
if not TryCastToPointer(Result) then
Result := defValue;
end; { TOmniValue.CastToPointerDef }
function TOmniValue.CastToRecord: IOmniAutoDestroyObject;
begin
case ovType of
ovtRecord: Result := IOmniAutoDestroyObject(ovIntf);
else raise Exception.Create('TOmniValue cannot be converted to record');
end;
end; { TOmniValue.CastToRecord }
function TOmniValue.CastToString: string;
begin
if not TryCastToString(Result) then
raise Exception.Create('TOmniValue cannot be converted to string');
end; { TOmniValue.CastToString }
function TOmniValue.CastToStringDef(const defValue: string): string;
begin
if not TryCastToString(Result) then
Result := defValue;
end; { TOmniValue.CastToStringDef }
{$IFDEF OTL_ERTTI}
function TOmniValue.GetArrayFromTValue(const value: TValue): TOmniValueContainer;
var
ov: TOmniValue;
idxItem: Integer;
begin
Result := TOmniValueContainer.Create;
for idxItem := 0 to value.GetArrayLength-1 do
begin
ov.AsTValue := value.GetArrayElement(idxItem);
Result.Add(ov);
end;
end; { TOmniValue.GetArrayFromTValue }
function TOmniValue.GetTValueFromArray(const a: TOmniValueContainer): TValue;
var
vItem: TValue;
arrItems: TArray<TValue>;
idxItem: Integer;
typInfo: PTypeInfo;
begin
if a.Count = 0 then
Exit(TValue.Empty);
SetLength(arrItems, a.Count);
for idxItem := 0 to a.Count-1 do
begin
vItem := a[idxItem].AsTValue;
arrItems[idxItem] := vItem;
end;
case a[0].ovType of
ovtBoolean: typInfo := TypeInfo(TArray<Boolean>);
ovtInteger: typInfo := TypeInfo(TArray<Integer>);
ovtInt64: typInfo := TypeInfo(TArray<int64>);
ovtObject: typInfo := TypeInfo(TArray<TObject>);
ovtPointer: typInfo := TypeInfo(TArray<Pointer>);
ovtDateTime: typInfo := TypeInfo(TArray<TDateTime>);
ovtException: typInfo := TypeInfo(TArray<Exception>);
ovtExtended: typInfo := TypeInfo(TArray<Extended>);
ovtString: typInfo := TypeInfo(TArray<string>);
ovtInterface: typInfo := TypeInfo(TArray<IInterface>);
ovtVariant: typInfo := TypeInfo(TArray<Variant>);
{$IFDEF MSWINDOWS}
ovtAnsiString: typInfo := TypeInfo(TArray<AnsiString>);
ovtWideString: typInfo := TypeInfo(TArray<WideString>);
{$ENDIF MSWINDOWS}
else
typInfo := TypeInfo(TArray<Pointer>);
end;
Result := TValue.FromArray(typInfo, arrItems);
end; { TOmniValue.GetTValueFromArray }
function TOmniValue.GetAsTValue: TValue;
begin
case ovType of
ovtNull:
Result := nil;
ovtBoolean:
Result := AsBoolean;
ovtInteger:
Result := AsInteger;
ovtInt64:
Result := AsInt64;
ovtDouble,
ovtExtended:
Result := AsExtended;
{$IFDEF MSWINDOWS}
ovtAnsiString:
Result := string(AsAnsiString);
ovtWideString:
Result := AsWideString;
{$ENDIF}
ovtString:
Result := AsString;
ovtObject:
Result := AsObject;
ovtOwnedObject:
Result := AsOwnedObject;
ovtException:
Result := AsException;
ovtInterface:
Result := TValue.From<IInterface>(AsInterface);
ovtVariant:
Result := TValue.FromVariant(AsVariant);
ovtPointer:
Result := AsPointer;
ovtArray:
Result := GetTValueFromArray(AsArray);
end;
end; { TOmniValue.GetAsTValue }
{$ENDIF OTL_ERRTI}
function TOmniValue.CastToVariant: Variant;
begin
if not TryCastToVariant(Result) then
raise Exception.Create('TOmniValue cannot be converted to variant');
end; { TOmniValue.CastToVariant }
function TOmniValue.CastToVariantDef(defValue: Variant): Variant;
begin
if not TryCastToVariant(Result) then
Result := defValue;
end; { TOmniValue.CastToVariantDef }
{$IFDEF MSWINDOWS}
function TOmniValue.CastToWideString: WideString;
begin
if not TryCastToWideString(Result) then
raise Exception.Create('TOmniValue cannot be converted to WideString');
end; { TOmniValue.CastToWideString }
function TOmniValue.CastToWideStringDef(defValue: WideString): WideString;
begin
if not TryCastToWideString(Result) then
Result := defValue;
end; { TOmniValue.CastToWideStringDef }
function TOmniValue.IsAnsiString: boolean;
begin
Result := (ovType = ovtAnsiString);
end; { TOmniValue.IsAnsiString }
{$ENDIF}
function TOmniValue.IsArray: boolean;
begin
Result := (ovType = ovtArray);
end; { TOmniValue.IsArray }
function TOmniValue.IsBoolean: boolean;
begin
Result := (ovType = ovtBoolean);
end; { TOmniValue.IsBoolean }
function TOmniValue.IsEmpty: boolean;
begin
Result := (ovType = ovtNull);
end; { TOmniValue.IsEmpty }
function TOmniValue.IsFloating: boolean;
begin
Result := (ovType in [ovtDouble, ovtExtended]);
end; { TOmniValue.IsFloating }
function TOmniValue.IsDateTime: boolean;
begin
Result := (ovType = ovtDateTime);
end; { TOmniValue.IsDateTime }
function TOmniValue.IsException: boolean;
begin
Result := (ovType = ovtException);
end; { TOmniValue.IsException }
function TOmniValue.IsInteger: boolean;
begin
Result := (ovType in [ovtInteger, ovtInt64]);
end; { TOmniValue.IsInteger }
function TOmniValue.IsInterface: boolean;
begin
Result := (ovType = ovtInterface);
end; { TOmniValue.IsInterface }
function TOmniValue.IsInterfacedType: boolean;
begin
Result := ovType in [ovtInterface, ovtExtended, ovtString, ovtVariant, ovtArray, ovtRecord, ovtOwnedObject
{$IFDEF MSWINDOWS}, ovtWideString, ovtAnsiString {$ENDIF}];
end; { TOmniValue.IsInterfacedType }
function TOmniValue.IsObject: boolean;
begin
Result := (ovType = ovtObject);
end; { TOmniValue.IsObject }
function TOmniValue.IsOwnedObject: boolean;
begin
Result := (ovType = ovtOwnedObject);
end; { TOmniValue.IsOwnedObject }
function TOmniValue.IsPointer: boolean;
begin
Result := (ovType = ovtPointer);
end; { TOmniValue.IsPointer }
function TOmniValue.IsRecord: boolean;
begin
Result := (ovType = ovtRecord);
end; { TOmniValue.IsRecord }
function TOmniValue.IsString: boolean;
begin
Result := (ovType = ovtString);
end; { TOmniValue.IsString }
function TOmniValue.IsVariant: boolean;
begin
Result := (ovType = ovtVariant);
end; { TOmniValue.IsVariant }
{$IFDEF MSWINDOWS}
function TOmniValue.IsWideString: boolean;
begin
Result := (ovType = ovtWideString);
end; { TOmniValue.IsWideString }
{$ENDIF}
function TOmniValue.LogValue: string;
const
CBoolStr: array [boolean] of string = ('F', 'T');
begin
try
case DataType of
ovtNull: Result := '[0]';
ovtBoolean: Result := '[B]' + CBoolStr[AsBoolean];
ovtInteger: Result := '[4]' + AsString;
ovtInt64: Result := '[8]' + AsString;
ovtDouble: Result := '[D]' + AsString;
ovtObject: Result := '[O]' + AsObject.ClassName;
ovtPointer: Result := '[P]' + Format('%p', [AsPointer]);
ovtDateTime: Result := '[T]' + FormatDateTime('yyyymmddhhnnsszzz', AsDateTime);
ovtException: Result := '[E]' + AsException.ClassName;
ovtExtended: Result := '[X]' + AsString;
ovtString: Result := '[S]' + AsString;
ovtInterface: Result := '[I]';
ovtVariant: Result := '[V]' + AsString;
ovtArray: Result := '[A]' + IntToStr(AsArray.Count);
ovtRecord: Result := '[R]';
ovtOwnedObject: Result := '[o]' + AsObject.ClassName;
{$IFDEF MSWINDOWS}
ovtWideString: Result := '[W]' + AsString;
ovtAnsiString: Result := '[N]' + AsString;
{$ENDIF MSWINDOWS}
end;
except
Result := '!' + IntToStr(Ord(DataType));
end;
end; { TOmniValue.LogValue }
class function TOmniValue.Null: TOmniValue;
begin
Result.ovType := ovtNull;
end; { TOmniValue.Null }
function TOmniValue.RawData: PInt64;
begin
Result := @ovData;
end; { TOmniValue.RawData }
procedure TOmniValue.RawZero;
begin
ovData := 0;
pointer(ovIntf) := nil;
ovType := ovtNull;
end; { TOmniValue.RawZero }
class procedure TOmniValue._RemoveWarnings;
var
a : integer;
intf: IOmniAutoDestroyObject;
ov : TOmniValue;
begin
a := 0;
if a = (a + 1) then begin
ov := ov.GetAsArrayItem('');
ov := ov.GetAsArrayItemOV(ov);
ov.SetAsArrayItem('', 0);
ov.SetAsArrayItemOV(ov, 0);
intf := ov.CastToRecord;
ov.SetAsRecord(intf);
{$IF CompilerVersion >= 19}
ov := ov.GetAsArrayItem(ov);
ov.SetAsArrayItem(ov, 0);
{$IFEND}
end;
end; { TOmniValue._RemoveWarnings }
{$IFDEF MSWINDOWS}
procedure TOmniValue.SetAsAnsiString(const value: AnsiString);
begin
ovIntf := TOmniAnsiStringData.Create(value);
ovType := ovtAnsiString;
end; { TOmniValue.SetAsAnsiString }
{$ENDIF}
procedure TOmniValue.SetAsArrayItem(idx: integer; const value: TOmniValue);
begin
if IsEmpty then
SetAsArray(TOmniValueContainer.Create);
if not IsArray then
raise Exception.Create('TOmniValue does not contain an array');
TOmniValueContainer(ovData)[idx] := value;
end; { TOmniValue.SetAsArrayItem }
procedure TOmniValue.SetAsArrayItem(const name: string; const value: TOmniValue);
begin
if IsEmpty then
SetAsArray(TOmniValueContainer.Create);
if not IsArray then
raise Exception.Create('TOmniValue does not contain an array');
TOmniValueContainer(ovData)[name] := value;
end; { TOmniValue.SetAsArrayItem }
{$IF CompilerVersion >= 19}//D2007 has problems understanding this overload
procedure TOmniValue.SetAsArrayItem(const param, value: TOmniValue);
begin
if IsEmpty then
SetAsArray(TOmniValueContainer.Create);
if not IsArray then
raise Exception.Create('TOmniValue does not contain an array');
TOmniValueContainer(ovData)[param] := value;
end; { TOmniValue.SetAsArrayItem }
{$IFEND}
procedure TOmniValue.SetAsArrayItemOV(const param, value: TOmniValue);
begin
if IsEmpty then
SetAsArray(TOmniValueContainer.Create);
if not IsArray then
raise Exception.Create('TOmniValue does not contain an array');
TOmniValueContainer(ovData)[param] := value;
end; { TOmniValue.SetAsArrayItemOV }
{ TOmniValue.SetAsArrayItem }
procedure TOmniValue.SetAsBoolean(const value: boolean);
begin
ClearIntf;
PByte(@ovData)^ := Ord(value);
ovType := ovtBoolean;
end; { TOmniValue.SetAsBoolean }
procedure TOmniValue.SetAsCardinal(const value: cardinal);
begin
AsInt64 := value;
end; { TOmniValue.SetAsCardinal }
procedure TOmniValue.SetAsDouble(value: Double);
begin
ClearIntf;
PDouble(@ovData)^ := value;
ovType := ovtDouble;
end; { TOmniValue.SetAsDouble }
procedure TOmniValue.SetAsDateTime(value: TDateTime);
begin
ClearIntf;
PDouble(@ovData)^ := value;
ovType := ovtDateTime;
end; { TOmniValue.SetAsDateTime }
procedure TOmniValue.SetAsException(value: Exception);
begin
ClearIntf;
PInt64(@ovData)^ := int64(value);
ovType := ovtException
end; { TOmniValue.SetAsException }
procedure TOmniValue.SetAsExtended(value: Extended);
begin
ovIntf := TOmniExtendedData.Create(value);
ovType := ovtExtended;
end; { TOmniValue.SetAsExtended }
procedure TOmniValue.SetAsInt64(const value: int64);
begin
ClearIntf;
ovData := value;
ovType := ovtInt64;
end; { TOmniValue.SetAsInt64 }
procedure TOmniValue.SetAsInteger(const value: integer);
begin
ClearIntf;
ovData := value;
ovType := ovtInteger;
end; { TOmniValue.SetAsInteger }
procedure TOmniValue.SetAsInterface(const value: IInterface);
begin
ovIntf := value;
ovType := ovtInterface;
end; { TOmniValue.SetAsInterface }
procedure TOmniValue.SetAsObject(const value: TObject);
begin
ClearIntf;
PInt64(@ovData)^ := int64(value);
ovType := ovtObject;
end; { TOmniValue.SetAsObject }
procedure TOmniValue.SetAsOwnedObject(const value: TObject);
begin
ovType := ovtOwnedObject;
ovIntf := CreateAutoDestroyObject(value);
ovData := int64(value);
end;
procedure TOmniValue.SetAsPointer(const value: pointer);
begin
ClearIntf;
PInt64(@ovData)^ := int64(value);
ovType := ovtPointer;
end; { TOmniValue.SetAsPointer }
procedure TOmniValue.SetAsRecord(const intf: IOmniAutoDestroyObject);
begin
ovIntf := intf;
ovType := ovtRecord;
end; { TOmniValue.SetAsRecord }
procedure TOmniValue.SetAsString(const value: string);
begin
ovIntf := TOmniStringData.Create(value);
ovType := ovtString;
end; { TOmniValue.SetAsString }
{$IFDEF OTL_ERTTI}
procedure TOmniValue.SetAsTValue(const value: TValue);
begin
case value.Kind of
tkInteger:
AsInteger := value.AsInteger;
tkChar,
tkString,
tkWChar,
tkLString,
tkWString,
tkUString:
AsString := value.AsString;
tkFloat:
AsExtended := value.AsExtended;
tkVariant:
AsVariant := value.AsVariant;
tkInterface:
AsInterface := value.AsInterface;
tkInt64:
AsInt64 := value.AsInt64;
tkPointer:
begin
Assert(SizeOf(pointer) <= SizeOf(int64));
AsPointer := pointer(value.GetReferenceToRawData^);
end;
tkArray,
tkDynArray:
SetAsArray(GetArrayFromTValue(value));
else
raise Exception.CreateFmt('TValue of type %s cannot be converted to TOmniValue',
[GetEnumName(TypeInfo(TTypeKind), Ord(value.Kind))]);
end;
end; { TOmniValue.SetAsTValue }
{$ENDIF OTL_ERTTI}
procedure TOmniValue.SetAsVariant(const value: Variant);
begin
ovIntf := TOmniVariantData.Create(value);
ovType := ovtVariant;
end; { TOmniValue.SetAsVariant }
{$IFDEF MSWINDOWS}
procedure TOmniValue.SetAsWideString(const value: WideString);
begin
ovIntf := TOmniWideStringData.Create(value);
ovType := ovtWideString;
end; { TOmniValue.SetAsWideString }
{$ENDIF}
procedure TOmniValue.SetOwnsObject(const value: boolean);
var
obj: TObject;
begin
if value then begin
if not IsObject then
raise Exception.Create('TOmniValue does not contain an object');
SetAsOwnedObject(TObject(ovData));
end
else begin
if not IsOwnedObject then
raise Exception.Create('TOmniValue does not contain an owned object');
obj := (ovIntf as IOmniAutoDestroyObject).Detach;
SetAsObject(obj);
end;
end; { TOmniValue.SetOwnsObject }
{$IFDEF MSWINDOWS}
function TOmniValue.TryCastToAnsiString(var value: AnsiString): boolean;
begin
Result := true;
case ovType of
ovtNull: value := '';
ovtBoolean: value := AnsiString(BoolToStr(AsBoolean, true));
ovtInteger,
ovtInt64: value := AnsiString(IntToStr(ovData));
ovtDouble,
ovtDateTime,
ovtExtended: value := AnsiString(FloatToStr(AsExtended));
ovtAnsiString: value := (ovIntf as IOmniAnsiStringData).Value;
ovtString: value := AnsiString((ovIntf as IOmniStringData).Value);
ovtWideString: value := AnsiString((ovIntf as IOmniWideStringData).Value);
ovtVariant: value := AnsiString(AsVariant);
else Result := false;
end;
end; { TOmniValue.TryCastToAnsiString }
{$ENDIF}
function TOmniValue.TryCastToDateTime(var value: TDateTime): boolean;
begin
Result := true;
case ovType of
ovtDouble,
ovtDateTime: value := PDouble(@ovData)^;
ovtExtended: value := (ovIntf as IOmniExtendedData).Value;
ovtNull: value := 0;
else Result := false;
end;
end; { TOmniValue.TryCastToDateTime }
function TOmniValue.TryCastToDouble(var value: Double): boolean;
begin
Result := true;
case ovType of
ovtInteger,
ovtInt64,
ovtNull: value := AsInt64;
ovtDouble,
ovtDateTime: value := PDouble(@ovData)^;
ovtExtended: value := (ovIntf as IOmniExtendedData).Value;
else Result := false;
end;
end; { TOmniValue.TryCastToDouble }
function TOmniValue.TryCastToException(var value: Exception): boolean;
begin
Result := true;
if IsException or
(IsObject and AsObject.InheritsFrom(Exception))
then
value := Exception(ovData)
else if IsEmpty then
value := nil
else
Result := false;
end; { TOmniValue.TryCastToException }
function TOmniValue.TryCastToExtended(var value: Extended): boolean;
begin
Result := true;
case ovType of
ovtInteger,
ovtInt64,
ovtNull: value := AsInt64;
ovtDouble,
ovtDateTime: value := PDouble(@ovData)^;
ovtExtended: value := (ovIntf as IOmniExtendedData).Value;
else Result := false;
end;
end; { TOmniValue.TryCastToExtended }
function TOmniValue.TryCastToPointer(var value: pointer): boolean;
begin
Result := true;
case ovType of
ovtPointer,
ovtObject,
ovtException: value := pointer(ovData);
ovtOwnedObject: value := pointer((ovIntf as IOmniAutoDestroyObject).Value);
ovtNull: value := nil;
else Result := false;
end;
end; { TOmniValue.TryCastToPointer }
function TOmniValue.TryCastToString(var value: string): boolean;
begin
Result := true;
case ovType of
ovtNull: value := '';
ovtBoolean: value := BoolToStr(AsBoolean, true);
ovtInteger,
ovtInt64: value := IntToStr(ovData);
ovtDouble,
ovtDateTime,
ovtExtended: value := FloatToStr(AsExtended);
{$IFDEF MSWINDOWS}
ovtAnsiString: value := string((ovIntf as IOmniAnsiStringData).Value);
ovtWideString: value := (ovIntf as IOmniWideStringData).Value;
{$ENDIF}
ovtString: value := (ovIntf as IOmniStringData).Value;
ovtVariant: value := string(AsVariant);
else Result := false;
end;
end; { TOmniValue.TryCastToString }
function TOmniValue.TryCastToVariant(var value: Variant): boolean;
begin
Result := true;
case ovType of
ovtVariant: value := (ovIntf as IOmniVariantData).Value;
ovtNull: value := Variants.Null;
else Result := false;
end;
end; { TOmniValue.TryCastToVariant }
{$IFDEF MSWINDOWS}
function TOmniValue.TryCastToWideString(var value: WideString): boolean;
var
str: string;
begin
Result := true;
case ovType of
ovtWideString: value := (ovIntf as IOmniWideStringData).Value;
ovtVariant: value := WideString(AsVariant);
else begin
Result := TryCastToString(str);
if Result then
value := str;
end;
end;
end; { TOmniValue.TryCastToWideString }
{$ENDIF}
procedure TOmniValue._AddRef;
begin
if IsInterfacedType and assigned(ovIntf) then
ovIntf._AddRef;
end; { TOmniValue._AddRef }
procedure TOmniValue._Release;
begin
if IsInterfacedType and assigned(ovIntf) then
ovIntf._Release;
end; { TOmniValue._Release }
procedure TOmniValue._ReleaseAndClear;
begin
if IsInterfacedType then begin
ovIntf._Release;
RawZero;
end;
end; { TOmniValue._ReleaseAndClear }
class operator TOmniValue.Equal(const a: TOmniValue; i: integer): boolean;
begin
Result := (a.AsInteger = i);
end; { TOmniValue.Equal }
class operator TOmniValue.Equal(const a: TOmniValue; const s: string): boolean;
begin
Result := (a.AsString = s);
end; { TOmniValue.Equal }
{$IFDEF MSWINDOWS}
{$IFDEF UNICODE}
class operator TOmniValue.Implicit(const a: AnsiString): TOmniValue;
begin
Result.AsAnsiString := a;
end; { TOmniValue.Implicit }
{$ENDIF UNICODE}
{$ENDIF}
class operator TOmniValue.Implicit(const a: boolean): TOmniValue;
begin
Result.AsBoolean := a;
end; { TOmniValue.Implicit }
class operator TOmniValue.Implicit(const a: Double): TOmniValue;
begin
Result.AsDouble := a;
end; { TOmniValue.Implicit }
{$IFDEF OTL_TOmniValueImplicitDateTime}
class operator TOmniValue.Implicit(const a: TDateTime): TOmniValue;
begin
Result.AsDateTime := a;
end; { TOmniValue.Implicit }
{$ENDIF OTL_TOmniValueImplicitDateTime}
class operator TOmniValue.Implicit(const a: Extended): TOmniValue;
begin
Result.AsExtended := a;
end; { TOmniValue.Implicit }
class operator TOmniValue.Implicit(const a: integer): TOmniValue;
begin
Result.AsInteger := a;
end; { TOmniValue.Implicit }
class operator TOmniValue.Implicit(const a: int64): TOmniValue;
begin
Result.AsInt64 := a;
end; { TOmniValue.Implicit }
class operator TOmniValue.Implicit(const a: string): TOmniValue;
begin
Result.AsString := a;
end; { TOmniValue.Implicit }
class operator TOmniValue.Implicit(const a: IInterface): TOmniValue;
begin
Result.AsInterface := a;
end; { TOmniValue.Implicit }
class operator TOmniValue.Implicit(const a: TObject): TOmniValue;
begin
Result.AsObject := a;
end; { TOmniValue.Implicit }
class operator TOmniValue.Implicit(const a: Exception): TOmniValue;
begin
Result.AsException := a;
end; { TOmniValue.Implicit }
{$IFDEF MSWINDOWS}
{$IFDEF UNICODE}
class operator TOmniValue.Implicit(const a: TOmniValue): AnsiString;
begin
Result := a.AsAnsiString;
end; { TOmniValue.Implicit }
{$ENDIF UNICODE}
class operator TOmniValue.Implicit(const a: TOmniValue): WideString;
begin
Result := a.AsWideString;
end; { TOmniValue.Implicit }
{$ENDIF}
class operator TOmniValue.Implicit(const a: TOmniValue): Extended;
begin
Result := a.AsExtended;
end; { TOmniValue.Implicit }
class operator TOmniValue.Implicit(const a: TOmniValue): int64;
begin
Result := a.AsInt64;
end; { TOmniValue.Implicit }
class operator TOmniValue.Implicit(const a: TOmniValue): boolean;
begin
Result := a.AsBoolean;
end; { TOmniValue.Implicit }
class operator TOmniValue.Implicit(const a: TOmniValue): Double;
begin
Result := a.AsDouble;
end; { TOmniValue.Implicit }
{$IFDEF OTL_TOmniValueImplicitDateTime}
class operator TOmniValue.Implicit(const a: TOmniValue): TDateTime;
begin
Result := a.AsDateTime;
end; { TOmniValue.Implicit }
{$ENDIF OTL_TOmniValueImplicitDateTime}
class operator TOmniValue.Implicit(const a: TOmniValue): integer;
begin
Result := a.AsInteger;
end; { TOmniValue.Implicit }
class operator TOmniValue.Implicit(const a: TOmniValue): IInterface;
begin
Result := a.AsInterface;
end; { TOmniValue.Implicit }
class operator TOmniValue.Implicit(const a: TOmniValue): TObject;
begin
Result := a.AsObject;
end; { TOmniValue.Implicit }
class operator TOmniValue.Implicit(const a: TOmniValue): Exception;
begin
Result := a.AsException;
end; { TOmniValue.Implicit }
class operator TOmniValue.Implicit(const a: TOmniValue): string;
begin
Result := a.AsString;
end; { TOmniValue.Implicit }
{$IFDEF MSWINDOWS}
class operator TOmniValue.Implicit(const a: WideString): TOmniValue;
begin
Result.AsWideString := a;
end; { TOmniValue.Implicit }
{$ENDIF}
class operator TOmniValue.Implicit(const a: Variant): TOmniValue;
begin
Result.AsVariant := a;
end; { TOmniValue.Implicit }
class operator TOmniValue.Implicit(const a: pointer): TOmniValue;
begin
Result.AsPointer := a;
end; { TOmniValue.Implicit }
class operator TOmniValue.Implicit(const a: TOmniValue): pointer;
begin
Result := a.AsPointer;
end; { TOmniValue.Implicit }
{$IFDEF OTL_ERTTI}
class operator TOmniValue.Implicit(const a: TValue): TOmniValue;
begin
Result.AsTValue := a;
end; { TOmniValue.Implicit }
class operator TOmniValue.Implicit(const a: TOmniValue): TValue;
begin
Result := a.AsTValue;
end; { TOmniValue.Implicit }
{$ENDIF OTL_ERTTI}
{ TOmniValueObj }
constructor TOmniValueObj.Create(const value: TOmniValue);
begin
inherited Create;
FValue := value;
end; { TOmniValueObj.Create }
{$IFDEF OTL_Generics}
{ TOmniRecord<T> }
constructor TOmniRecord<T>.Create(const aValue: T);
begin
Value := aValue;
end; { TOmniRecord<T>.Create }
{$ENDIF OTL_Generics}
{ TOmniWaitableValue }
constructor TOmniWaitableValue.Create;
begin
FEvent := TEvent.Create(false);
FValue := TOmniValue.Null;
end; { TOmniWaitableValue.Create }
destructor TOmniWaitableValue.Destroy;
begin
FreeAndNil( FEvent);
inherited
end; { TOmniWaitableValue.Destroy }
{$IFDEF MSWINDOWS}
function TOmniWaitableValue.GetHandle: THandle;
begin
Result := FEvent.Handle
end; { TOmniWaitableValue.GetHandle }
{$ENDIF}
function TOmniWaitableValue.GetEvent: TEvent;
begin
Result := FEvent
end; { TOmniWaitableValue.GetEvent }
function TOmniWaitableValue.GetValue: TOmniValue;
begin
Result := FValue;
end; { TOmniWaitableValue.GetValue }
procedure TOmniWaitableValue.Reset;
begin
FEvent.ResetEvent
end; { TOmniWaitableValue.Reset }
procedure TOmniWaitableValue.Signal;
begin
FEvent.SetEvent
end; { TOmniWaitableValue.Signal }
procedure TOmniWaitableValue.Signal(const data: TOmniValue);
begin
FValue := data;
Signal;
end; { TOmniWaitableValue.Signal }
function TOmniWaitableValue.WaitFor(maxWait_ms: cardinal): boolean;
begin
Result := FEvent.WaitFor(maxWait_ms) = wrSignaled;
end; { TOmniWaitableValue.WaitFor }
{ TOmniStringData }
constructor TOmniStringData.Create(const value: string);
begin
inherited Create;
osdValue := value;
end; { TOmniStringData.Create }
function TOmniStringData.GetValue: string;
begin
Result := osdValue;
end; { TOmniStringData.GetValue }
procedure TOmniStringData.SetValue(const value: string);
begin
osdValue := value;
end; { TOmniStringData.SetValue }
{ TOmniAnsiStringData }
{$IFDEF MSWINDOWS}
constructor TOmniAnsiStringData.Create(const value: AnsiString);
begin
inherited Create;
osdValue := value;
end; { TOmniAnsiStringData.Create }
function TOmniAnsiStringData.GetValue: AnsiString;
begin
Result := osdValue;
end; { TOmniAnsiStringData.GetValue }
procedure TOmniAnsiStringData.SetValue(const value: AnsiString);
begin
osdValue := value;
end; { TOmniAnsiStringData.SetValue }
{ TOmniWideStringData }
constructor TOmniWideStringData.Create(const value: WideString);
begin
inherited Create;
osdValue := value;
end; { TOmniWideStringData.Create }
function TOmniWideStringData.GetValue: WideString;
begin
Result := osdValue;
end; { TOmniWideStringData.GetValue }
procedure TOmniWideStringData.SetValue(const value: WideString);
begin
osdValue := value;
end; { TOmniWideStringData.SetValue }
{$ENDIF}
{ TOmniVariantData }
constructor TOmniVariantData.Create(const value: Variant);
begin
inherited Create;
ovdValue := value;
end; { TOmniVariantData.Create }
function TOmniVariantData.GetValue: Variant;
begin
Result := ovdValue;
end; { TOmniVariantData.GetValue }
procedure TOmniVariantData.SetValue(const value: Variant);
begin
ovdValue := value;
end; { TOmniVariantData.SetValue }
{ TOmniExtendedData }
constructor TOmniExtendedData.Create(const value: Extended);
begin
inherited Create;
oedValue := value;
end; { TOmniExtendedData.Create }
function TOmniExtendedData.GetValue: Extended;
begin
Result := oedValue;
end; { TOmniExtendedData.GetValue }
procedure TOmniExtendedData.SetValue(const value: Extended);
begin
oedValue := value;
end; { TOmniExtendedData.SetValue }
{ TOmniAffinity }
constructor TOmniAffinity.Create(target: TOmniAffinityTarget);
begin
Assert(target in [atSystem, atProcess, atThread]);
inherited Create;
oaTarget := target;
end; { TOmniAffinity.Create }
function TOmniAffinity.GetAsString: string;
{$IFNDEF MSWINDOWS}
var
i: integer;
{$ENDIF MSWINDOWS}
begin
{$IFDEF MSWINDOWS}
// TODO 1 -oPrimoz Gabrijelcic : Port this to non-Windows
Result := DSiAffinityMaskToString(Mask);
{$ELSE}
for i := 1 to System.CPUCount do
Result := result + 'P'
{$ENDIF !MSWINDOWS}
end; { TOmniAffinity.GetAsString }
function TOmniAffinity.GetCount: integer;
{$IFDEF MSWINDOWS}
var
affMask: DWORD;
begin
Result := 0;
affMask := Mask;
while affMask <> 0 do begin
if Odd(affMask) then
Inc(Result);
affMask := affMask SHR 1;
end;
{$ELSE}
begin
Result := System.CPUCount;
{$ENDIF}
end;
function TOmniAffinity.GetCountPhysical: integer;
{$IFDEF MSWINDOWS}
var
info: TSystemLogicalProcessorInformationArr;
item: TSystemLogicalProcessorInformation;
mask: DWORD;
begin
if not DSiGetLogicalProcessorInfo(info) then
Result := GetCount // running on pre-XP SP3 OS, just get the best approximation
else begin
Result := 0;
mask := GetMask;
for item in info do begin
if (item.Relationship = RelationProcessorCore) and
((item.ProcessorMask AND mask) <> 0) then
begin
mask := mask AND NOT item.ProcessorMask;
Inc(Result);
end;
end;
end;
end;
{$ELSE}
begin
Result := System.CPUCount;
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
function TOmniAffinity.GetMask: NativeUInt;
begin
case oaTarget of
atSystem:
Result := DSiGetSystemAffinityMask;
atProcess:
Result := DSiGetProcessAffinityMask;
atThread:
Result := DSiGetThreadAffinityMask;
else
Result := 0; // to keep compiler happy
end;
end; { TOmniAffinity.GetMask }
{$ENDIF}
procedure TOmniAffinity.SetAsString(const value: string);
begin
{$IFDEF MSWINDOWS}
case oaTarget of
atSystem:
raise Exception.Create('TOmniAffinity.SetMask: Cannot modify system affinity mask.');
atProcess:
DSiSetProcessAffinity(value);
atThread:
DSiSetThreadAffinity(value);
end;
{$ENDIF}
end; { TOmniAffinity.SetAsString }
procedure TOmniAffinity.SetCount(const value: integer);
{$IFDEF MSWINDOWS}
var
affMask: string;
numCore: integer;
pCore : integer;
sysMask: string;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
sysMask := DSiGetSystemAffinity;
affMask := '';
numCore := value;
while (numCore > 0) and (sysMask <> '') do begin
pCore := Random(Length(sysMask)) + 1;
affMask := affMask + sysMask[pCore];
Delete(sysMask, pCore, 1);
Dec(numCore);
end;
AsString := affMask;
{$ENDIF}
end; { TOmniAffinity.SetCount }
{$IFDEF MSWINDOWS}
procedure TOmniAffinity.SetMask(const value: NativeUInt);
begin
AsString := DSiAffinityMaskToString(value);
end; { TOmniAffinity.SetMask }
{$ENDIF}
{ TOmniProcessEnvironment }
constructor TOmniProcessEnvironment.Create;
begin
inherited Create;
opeAffinity := TOmniAffinity.Create(atProcess);
end; { TOmniProcessEnvironment.Create }
function TOmniProcessEnvironment.GetAffinity: IOmniAffinity;
begin
Result := opeAffinity;
end; { TOmniProcessEnvironment.GetAffinity }
{$IFDEF MSWINDOWS}
function TOmniProcessEnvironment.GetMemory: TOmniProcessMemoryCounters;
begin
if not DSiGetProcessMemory(Result) then
FillChar(Result, SizeOf(Result), 0);
end; { TOmniProcessEnvironment.GetMemory }
{$ENDIF}
function TOmniProcessEnvironment.GetPriorityClass: TOmniProcessPriorityClass;
{$IFDEF MSWINDOWS}
var
priority: DWORD;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
priority := Windows.GetPriorityClass(GetCurrentProcess);
if priority = $8000 then
Result := pcAboveNormal
else if priority = $4000 then
Result := pcBelowNormal
else if priority = $80 then
Result := pcHigh
else if priority = $40 then
Result := pcIdle
else if priority = $100 then
Result := pcRealtime
else
Result := pcNormal;
{$ELSE}
Result := pcNormal;
{$ENDIF}
end; { TOmniProcessEnvironment.GetPriorityClass }
{$IFDEF MSWINDOWS}
function TOmniProcessEnvironment.GetTimes: TOmniProcessTimes;
begin
if not DSiGetProcessTimes(Result.CreationTime, Result.UserTime, Result.KernelTime) then
FillChar(Result, SizeOf(Result), 0);
end; { TOmniProcessEnvironment.GetTimes }
{$ENDIF}
{ TOmniSystemEnvironment }
constructor TOmniSystemEnvironment.Create;
begin
oseAffinity := TOmniAffinity.Create(atSystem);
end; { TOmniSystemEnvironment.Create }
function TOmniSystemEnvironment.GetAffinity: IOmniAffinity;
begin
Result := oseAffinity;
end; { TOmniSystemEnvironment.GetAffinity }
{ TOmniThreadEnvironment }
constructor TOmniThreadEnvironment.Create;
begin
oteAffinity := TOmniAffinity.Create(atThread);
oteThreadID := GetCurrentThreadID;
end; { TOmniThreadEnvironment.Create }
function TOmniThreadEnvironment.GetAffinity: IOmniAffinity;
begin
Result := oteAffinity;
end; { TOmniThreadEnvironment.GetAffinity }
function TOmniThreadEnvironment.GetGroupAffinity: TOmniGroupAffinity;
var
groupAffinity: TGroupAffinity;
begin
{$IFDEF MSWindows}
if DSiGetThreadGroupAffinity(GetCurrentThread, groupAffinity) then begin
Result.Group := groupAffinity.Group;
Result.Affinity.AsMask := groupAffinity.Mask;
end
else if GetLastError <> ERROR_NOT_SUPPORTED then
raise Exception.CreateFmt('TOmniEnvironment.LoadNUMAInfo: DSiGetThreadGroupAffinity failed with [%d] %s', [GetLastError, SysErrorMessage(GetLastError)])
else
{$ENDIF MSWindows}
begin
Result.Group := 0;
Result.Affinity.AsMask := Affinity.Mask;
end;
end; { TOmniThreadEnvironment.GetGroupAffinity }
function TOmniThreadEnvironment.GetID: TThreadId;
begin
Result := oteThreadID;
end; { TOmniThreadEnvironment.GetID }
procedure TOmniThreadEnvironment.SetGroupAffinity(const value: TOmniGroupAffinity);
var
groupAffinity: TGroupAffinity;
begin
{$IFDEF MSWindows}
FillChar(groupAffinity, SizeOf(groupAffinity), 0);
groupAffinity.Group := value.Group;
groupAffinity.Mask := value.Affinity.AsMask;
DSiSetThreadGroupAffinity(GetCurrentThread, groupAffinity, nil);
{$ELSE}
if value.Group <> 0 then
raise Exception.Create('TOmniThreadEnvironment.SetGroupAffinity: Processor group must be 0');
Affinity.Mask := value.Affinity.AsMask;
{$ENDIF}
end; { TOmniThreadEnvironment.SetGroupAffinity }
{$IFDEF OTL_NUMASupport}
{ TOmniNUMANode }
constructor TOmniNUMANode.Create(nodeNumber, groupNumber: integer; affinity: NativeUInt);
begin
inherited Create;
FAffinity := TOmniIntegerSet.Create;
FAffinity.AsMask := affinity;
FGroupNumber := groupNumber;
FNodeNumber := nodeNumber;
end; { TOmniNUMANode.Create }
function TOmniNUMANode.GetAffinity: IOmniIntegerSet;
begin
Result := FAffinity;
end; { TOmniNUMANode.GetAffinity }
function TOmniNUMANode.GetGroupNumber: integer;
begin
Result := FGroupNumber;
end; { TOmniNUMANode.GetGroupNumber }
function TOmniNUMANode.GetNodeNumber: integer;
begin
Result := FNodeNumber;
end; { TOmniNUMANode.GetNodeNumber }
{ TOmniNUMANodes }
constructor TOmniNUMANodes.Create;
begin
inherited Create;
FNodes := TList<IOmniNUMANode>.Create;
end; { TOmniNUMANodes.Create }
destructor TOmniNUMANodes.Destroy;
begin
FreeAndNil(FNodes);
inherited;
end; { TOmniNUMANodes.Destroy }
procedure TOmniNUMANodes.Add(const node: IOmniNUMANode);
begin
FNodes.Add(node);
end; { TOmniNUMANodes.Add }
function TOmniNUMANodes.All: IOmniIntegerSet;
var
i : integer;
nodes: TIntegerDynArray;
begin
SetLength(nodes, Count);
for i := 0 to Count - 1 do
nodes[i] := Item[i].NodeNumber;
Result := TOmniIntegerSet.Create;
Result.AsIntArray := nodes;
end; { TOmniNUMANodes.All }
function TOmniNUMANodes.Count: integer;
begin
Result := FNodes.Count;
end; { TOmniNUMANodes.Count }
function TOmniNUMANodes.Distance(fromNode, toNode: integer): integer;
begin
if not FProximityInitialized then
InitializeProximity;
Result := FProximity[fromNode, toNode];
end; { TOmniNUMANodes.Distance }
function TOmniNUMANodes.FindNode(nodeNumber: integer): IOmniNUMANode;
var
node: IOmniNUMANode;
begin
Result := nil;
for node in Environment.NUMANodes do
if node.NodeNumber = nodeNumber then
Exit(node);
end; { TOmniNUMANodes.FindNode }
function TOmniNUMANodes.GetEnumerator: TList<IOmniNUMANode>.TEnumerator;
begin
Result := FNodes.GetEnumerator;
end; { TOmniNUMANodes.GetEnumerator }
function TOmniNUMANodes.GetItem(idx: integer): IOmniNUMANode;
begin
Result := FNodes[idx];
end; { TOmniNUMANodes.GetItem }
procedure TOmniNUMANodes.InitializeProximity;
function MakeDWORD(const name: AnsiString): DWORD;
begin
Result := (Ord(name[1]) SHL 24)
OR (Ord(name[2]) SHL 16)
OR (Ord(name[3]) SHL 8)
OR (Ord(name[4]) );
end; { MakeDWORD }
var
highestNuma : cardinal;
i : integer;
j : integer;
node : word;
nodeFrom : integer;
nodeTo : integer;
numLocalities : integer;
p : pointer;
proximityToNuma: array of integer;
q : PByte;
size : integer;
begin { TOmniNUMANodes.InitializeProximity }
if not DSiGetNumaHighestNodeNumber(highestNuma) then
raise Exception.Create('TOmniNUMANodes.InitializeProximity: Failed to read highest NUMA node number');
SetLength(FProximity, highestNuma+1);
for i := 0 to highestNuma do begin
Setlength(FProximity[i], highestNuma + 1);
for j := 0 to highestNuma do
FProximity[i,j] := 10;
end;
size := DSiGetSystemFirmwareTable(MakeDWORD('ACPI'), MakeDWORD('TILS'), nil, 0);
if size > 44 then begin
GetMem(p, size);
try
DSiGetSystemFirmwareTable(MakeDWORD('ACPI'), MakeDWORD('TILS'), p, size);
q := PByte(NativeUInt(p) + 36);
numLocalities := PInt64(q)^;
Inc(q, 8);
SetLength(proximityToNuma, numLocalities);
for i := 0 to numLocalities - 1do
if DSiGetNumaProximityNodeEx(i, node) then
proximityToNuma[i] := node
else
proximityToNuma[i] := -1;
for i := 0 to numLocalities - 1 do begin
nodeFrom := proximityToNuma[i];
for j := 0 to numLocalities - 1 do begin
nodeTo := proximityToNuma[j];
if (nodeFrom >= 0) and (nodeTo >= 0) then
FProximity[nodeFrom, nodeTo] := q^;
Inc(q);
end;
end;
finally FreeMem(p); end;
end; // if size > 44
FProximityInitialized := true;
end; { TOmniNUMANodes.InitializeProximity }
procedure TOmniNUMANodes.Sort;
begin
FNodes.Sort(TComparer<IOmniNUMANode>.Construct(
function (const N1, N2: IOmniNUMANode): integer
begin
Result := N1.NodeNumber - N2.NodeNumber;
end));
end; { TOmniNUMANodes.Sort }
{ TOmniProcessorGroup }
constructor TOmniProcessorGroup.Create(groupNumber: integer; affinity: NativeUInt);
begin
inherited Create;
FAffinity := TOmniIntegerSet.Create;
FAffinity.AsMask := affinity;
FGroupNumber := groupNumber;
end; { TOmniProcessorGroup.Create }
function TOmniProcessorGroup.GetAffinity: IOmniIntegerSet;
begin
Result := FAffinity;
end; { TOmniProcessorGroup.GetAffinity }
function TOmniProcessorGroup.GetGroupNumber: integer;
begin
Result := FGroupNumber;
end; { TOmniProcessorGroup.GetGroupNumber }
{ TOmniProcessorGroups }
constructor TOmniProcessorGroups.Create;
begin
inherited Create;
FGroups := TList<IOmniProcessorGroup>.Create;
end; { TOmniProcessorGroups.Create }
destructor TOmniProcessorGroups.Destroy;
begin
FreeAndNil(FGroups);
inherited;
end; { TOmniProcessorGroups.Destroy }
procedure TOmniProcessorGroups.Add(const group: IOmniProcessorGroup);
begin
FGroups.Add(group);
end; { TOmniProcessorGroups.Add }
function TOmniProcessorGroups.All: IOmniIntegerSet;
var
i : integer;
nodes: TIntegerDynArray;
begin
SetLength(nodes, Count);
for i := 0 to Count - 1 do
nodes[i] := Item[i].GroupNumber;
Result := TOmniIntegerSet.Create;
Result.AsIntArray := nodes;
end; { TOmniProcessorGroups.All }
function TOmniProcessorGroups.Count: integer;
begin
Result := FGroups.Count;
end; { TOmniProcessorGroups.Count }
function TOmniProcessorGroups.FindGroup(groupNumber: integer): IOmniProcessorGroup;
begin
Result := Item[groupNumber];
end; { TOmniProcessorGroups.FindGroup }
function TOmniProcessorGroups.GetEnumerator: TList<IOmniProcessorGroup>.TEnumerator;
begin
Result := FGroups.GetEnumerator;
end; { TOmniProcessorGroups.GetEnumerator }
function TOmniProcessorGroups.GetItem(idx: integer): IOmniProcessorGroup;
begin
Result := FGroups[idx];
end; { TOmniProcessorGroups.GetItem }
{$ENDIF OTL_NUMASupport}
{ TOmniEnvironment }
constructor TOmniEnvironment.Create;
begin
inherited Create;
oeProcessEnv := TOmniProcessEnvironment.Create;
oeSystemEnv := TOmniSystemEnvironment.Create;
{$IFDEF OTL_NUMASupport}
oeNUMANodes := TOmniNUMANodes.Create;
oeProcessorGroups := TOmniProcessorGroups.Create;
LoadNUMAInfo;
{$ENDIF OTL_NUMASupport}
end; { TOmniEnvironment.Create }
{$IFDEF OTL_NUMASupport}
destructor TOmniEnvironment.Destroy;
begin
oeNUMANodes := nil;
oeProcessorGroups := nil;
inherited;
end; { TOmniEnvironment.Destroy }
procedure TOmniEnvironment.CreateFakeNUMAInfo;
var
i : integer;
mask: DWORD;
begin
mask := 0;
for i := 1 to System.Affinity.Count do
mask := (mask shl 1) OR 1;
(oeProcessorGroups as IOmniProcessorGroupsInternal).Add(TOmniProcessorGroup.Create(0, mask));
(oeNUMANodes as IOmniNUMANodesInternal).Add(TOmniNUMANode.Create(0, 0, mask));
end; { TOmniEnvironment.CreateFakeNUMAInfo }
function TOmniEnvironment.GetNUMANodes: IOmniNUMANodes;
begin
Result := oeNUMANodes;
end; { TOmniEnvironment.GetNUMANodes }
function TOmniEnvironment.GetProcessorGroups: IOmniProcessorGroups;
begin
Result := oeProcessorGroups;
end; { TOmniEnvironment.GetProcessorGroups }
{$ENDIF OTL_NUMASupport}
function TOmniEnvironment.GetProcess: IOmniProcessEnvironment;
begin
Result := oeProcessEnv;
end; { TOmniEnvironment.GetProcess }
function TOmniEnvironment.GetSystem: IOmniSystemEnvironment;
begin
Result := oeSystemEnv;
end; { TOmniEnvironment.GetSystem }
function TOmniEnvironment.GetThread: IOmniThreadEnvironment;
begin
Result := TOmniThreadEnvironment.Create;
end; { TOmniEnvironment.GetThread }
{$IFDEF OTL_NUMASupport}
procedure TOmniEnvironment.LoadNUMAInfo;
{$IFDEF MSWindows}
var
bufLen : DWORD;
currentInfo : PSystemLogicalProcessorInformationEx;
iGroup : integer;
numaNodesInternal : IOmniNUMANodesInternal;
pGroupInfo : PProcessorGroupInfo;
processorGroupsInternal: IOmniProcessorGroupsInternal;
procInfo : PSystemLogicalProcessorInformationEx;
{$ENDIF}
begin
{$IFNDEF MSWindows}
CreateFakeNUMAInfo;
{$ELSE}
bufLen := 0;
DSiGetLogicalProcessorInformationEx(DSiWin32._LOGICAL_PROCESSOR_RELATIONSHIP.RelationAll, nil, bufLen);
if GetLastError = ERROR_NOT_SUPPORTED then
CreateFakeNUMAInfo
else begin
if GetLastError <> ERROR_INSUFFICIENT_BUFFER then
raise Exception.CreateFmt('TOmniEnvironment.LoadNUMAInfo: DSiGetLogicalProcessorInformation[1] failed with [%d] %s', [GetLastError, SysErrorMessage(GetLastError)]);
GetMem(procInfo, bufLen);
try
if not DSiGetLogicalProcessorInformationEx(DSiWin32._LOGICAL_PROCESSOR_RELATIONSHIP.RelationAll, DSiWin32.PSYSTEM_LOGICAL_PROCESSOR_INFORMATION(procInfo), bufLen) then
raise Exception.CreateFmt('TOmniEnvironment.LoadNUMAInfo: DSiGetLogicalProcessorInformation[2] failed with [%d] %s', [GetLastError, SysErrorMessage(GetLastError)]);
numaNodesInternal := (oeNUMANodes as IOmniNUMANodesInternal);
processorGroupsInternal := (oeProcessorGroups as IOmniProcessorGroupsInternal);
currentInfo := procInfo;
while (NativeUInt(currentInfo) - NativeUInt(procInfo)) < bufLen do begin
if DSiWin32._LOGICAL_PROCESSOR_RELATIONSHIP(currentInfo.Relationship) = DSiWin32._LOGICAL_PROCESSOR_RELATIONSHIP.RelationNumaNode then
numaNodesInternal.Add(TOmniNUMANode.Create(currentInfo.NumaNode.NodeNumber,
currentInfo.NumaNode.GroupMask.Group, currentInfo.NumaNode.GroupMask.Mask))
else if DSiWin32._LOGICAL_PROCESSOR_RELATIONSHIP(currentInfo.Relationship) = DSiWin32._LOGICAL_PROCESSOR_RELATIONSHIP.RelationGroup then begin
pGroupInfo := @currentInfo.Group.GroupInfo;
for iGroup := 0 to currentInfo.Group.ActiveGroupCount - 1 do begin
processorGroupsInternal.Add(TOmniProcessorGroup.Create(iGroup, pGroupInfo^.ActiveProcessorMask));
Inc(pGroupInfo);
end;
end;
currentInfo := PSystemLogicalProcessorInformationEx(NativeUInt(currentInfo) + currentInfo.Size);
end;
numaNodesInternal.Sort;
finally FreeMem(procInfo); end;
end;
{$ENDIF MSWindows}
end; { TOmniEnvironment.LoadNUMAInfo }
{$ENDIF OTL_NUMASupport}
{ TOmniExecutable }
procedure TOmniExecutable.CheckKind(kind: TOmniExecutableKind);
begin
if oeKind <> kind then
raise Exception.CreateFmt('TOmniExecutable: Wrong kind of executable %s, expected %s',
[GetEnumName(TypeInfo(TOmniExecutableKind), Ord(oeKind)),
GetEnumName(TypeInfo(TOmniExecutableKind), Ord(kind))]);
end; { TOmniExecutable.CheckKind }
procedure TOmniExecutable.Clear;
begin
oeKind := oekNull;
end; { TOmniExecutable.IsNull }
class operator TOmniExecutable.Explicit(const a: TProcedure): TOmniExecutable;
begin
Result.Proc := a;
end; { TOmniExecutable.Explicit }
class operator TOmniExecutable.Explicit(const a: TMethod): TOmniExecutable;
begin
Result.Method := a;
end; { TOmniExecutable.Explicit }
class operator TOmniExecutable.Explicit(const a: TOmniExecutable): TMethod;
begin
Result := a.Method;
end; { TOmniExecutable.Explicit }
class operator TOmniExecutable.Explicit(const a: TOmniExecutable): TProcedure;
begin
Result := a.Proc;
end; { TOmniExecutable.Explicit }
function TOmniExecutable.IsNull: boolean;
begin
Result := (oeKind = oekNull);
end; { TOmniExecutable.IsNull }
class operator TOmniExecutable.Implicit(const a: TProcedure): TOmniExecutable;
begin
Result.Proc := a;
end; { TOmniExecutable.Implicit }
class operator TOmniExecutable.Implicit(const a: TMethod): TOmniExecutable;
begin
Result.Method := a;
end; { TOmniExecutable.Implicit }
class operator TOmniExecutable.Implicit(const a: TOmniExecutable): TProcedure;
begin
Result := a.Proc;
end; { TOmniExecutable.Implicit }
class operator TOmniExecutable.Implicit(const a: TOmniExecutable): TMethod;
begin
Result := a.Method;
end; { TOmniExecutable.Implicit }
function TOmniExecutable.GetMethod: TMethod;
begin
CheckKind(oekMethod);
Result := oeMethod;
end; { TOmniExecutable.Method }
function TOmniExecutable.GetProc: TProcedure;
begin
CheckKind(oekProcedure);
Result := oeProcedure;
end; { TOmniExecutable.Proc }
procedure TOmniExecutable.SetMethod(const value: TMethod);
begin
oeKind := oekMethod;
oeMethod := value;
end; { TOmniExecutable.SetMethod }
procedure TOmniExecutable.SetProc(const value: TProcedure);
begin
oeKind := oekProcedure;
oeProcedure := value;
end; { TOmniExecutable.SetProc }
{$IFDEF OTL_Anonymous}
class procedure TOmniExecutable.AnonCopy(var Dest; const Source);
var
P: Pointer;
begin
P:= Pointer(Dest);
if Pointer(Source) <> nil then
IInterface(Source)._AddRef;
Pointer(Dest):= Pointer(Source);
if P <> nil then
IInterface(P)._Release;
end; { TOmniExecutable.AnonCopy }
class operator TOmniExecutable.Explicit(const a: TOmniExecutable): TProc;
begin
Result := a.Delegate;
end; { TOmniExecutable.Explicit }
class operator TOmniExecutable.Explicit(const a: TProc): TOmniExecutable;
begin
Result.SetDelegate(a);
end; { TOmniExecutable.Explicit }
class operator TOmniExecutable.Implicit(const a: TProc): TOmniExecutable;
begin
Result.SetDelegate(a);
end; { TOmniExecutable.Implicit }
class operator TOmniExecutable.Implicit(const a: TOmniExecutable): TProc;
begin
Result := a.Delegate;
end; { TOmniExecutable.Implicit }
function TOmniExecutable.GetDelegate: TProc;
begin
CheckKind(oekDelegate);
Result := oeDelegate;
end; { TOmniExecutable.GetDelegate }
procedure TOmniExecutable.SetAnonDelegate(const value: TProc);
begin
oeDelegate := value;
oeKind := oekDelegate;
end; { TOmniExecutable.SetAnonDelegate }
procedure TOmniExecutable.SetDelegate(const source);
begin
oeKind := oekDelegate;
AnonCopy(oeDelegate, source);
end; { TOmniExecutable.SetDelegate }
{$ENDIF OTL_Anonymous}
{ TOmniMessageID }
{$IFDEF OTL_Anonymous}
constructor TOmniMessageID.Create(const proc: TProc<integer>);
begin
omidMessageType := mitAnon;
omidAnon := proc;
end; { TOmniMessageID.Create }
{$ENDIF OTL_Anonymous}
function TOmniMessageID.AsString: string;
begin
case MessageType of
mitInteger: Result := IntToStr(omidInteger);
mitString: Result := omidString;
mitPointer: Result := Format('%p', [omidPointer]);
else raise Exception.CreateFmt('TOmniMessageID.AsString: Unexpected message type %d', [Ord(MessageType)]);
end;
end; { TOmniMessageID.AsString }
class operator TOmniMessageID.Implicit(const a: integer): TOmniMessageID;
begin
Result.omidMessageType := mitInteger;
Result.omidInteger := a;
end; { TOmniMessageID.Implicit }
class operator TOmniMessageID.Implicit(const a: pointer): TOmniMessageID;
begin
Result.omidMessageType := mitPointer;
Result.omidPointer := a;
end; { TOmniMessageID.Implicit }
class operator TOmniMessageID.Implicit(const a: string): TOmniMessageID;
begin
Result.omidMessageType := mitString;
Result.omidString := a;
UniqueString(Result.omidString);
end; { TOmniMessageID.Implicit }
class operator TOmniMessageID.Implicit(const a: TOmniMessageID): integer;
begin
Assert(a.omidMessageType = mitInteger);
Result := a.omidInteger;
end; { TOmniMessageID.Implicit }
class operator TOmniMessageID.Implicit(const a: TOmniMessageID): string;
begin
Assert(a.omidMessageType = mitString);
Result := a.omidString;
end; { TOmniMessageID.Implicit }
class operator TOmniMessageID.Implicit(const a: TOmniMessageID): pointer;
begin
Assert(a.omidMessageType = mitPointer);
Result := a.omidPointer;
end; { TOmniMessageID.Implicit }
{$IFDEF OTL_Anonymous}
{$ENDIF OTL_Anonymous}
function NextOid: int64;
begin
{$IFDEF OTL_USE_ALIGN}
Result := TInterlocked.Increment(OtlUID);
{$ELSE}
Result := OtlUID.Increment;
{$ENDIF}
end; { NextOid }
{ TOmniAlignedInt32 }
function TOmniAlignedInt32.Subtract(value: integer): integer; //inline
begin
{$IFDEF MSWINDOWS}
Result := InterlockedExchangeAdd(Addr^, -value) - value;
{$ELSE}
Result := TInterlocked.Add(Addr^, -value);
{$ENDIF}
end; { TOmniAlignedInt32.Subtract }
procedure TOmniAlignedInt32.Initialize;
begin
FAddr := PInteger((NativeInt(@FData) + 3) AND NOT 3);
end; { TOmniAlignedInt32.Initialize }
function TOmniAlignedInt32.Add(value: integer): integer;
begin
{$IFDEF MSWINDOWS}
Result := InterlockedExchangeAdd(Addr^, value) + value;
{$ELSE}
Result := TInterlocked.Add(Addr^, value);
{$ENDIF}
end; { TOmniAlignedInt32.Add }
function TOmniAlignedInt32.Addr: PInteger;
begin
Initialize;
Result := FAddr;
end; { TOmniAlignedInt32.Addr }
function TOmniAlignedInt32.CAS(oldValue, newValue: integer): boolean;
begin
{$IFDEF MSWINDOWS}
Result := InterlockedCompareExchange(Addr^, newValue, oldValue) = oldValue;
{$ELSE}
Result := TInterlocked.CompareExchange(Addr^, newValue, OldValue) = oldValue;
{$ENDIF}
end; { TOmniAlignedInt32.CAS }
function TOmniAlignedInt32.Decrement: integer;
begin
{$IFDEF MSWINDOWS}
Result := InterlockedDecrement(Addr^);
{$ELSE}
Result := TInterlocked.Decrement(Addr^);
{$ENDIF}
end; { TOmniAlignedInt32.Decrement }
function TOmniAlignedInt32.Decrement(value: integer): integer;
begin
{$IFDEF MSWINDOWS}
Result := Subtract(value);
{$ELSE}
Result := TInterlocked.Add(Addr^, -value);
{$ENDIF}
end; { TOmniAlignedInt32.Decrement }
function TOmniAlignedInt32.GetValue: integer;
begin
Result := Addr^;
end; { TOmniAlignedInt32.GetValue }
function TOmniAlignedInt32.Increment: integer;
begin
{$IFDEF MSWINDOWS}
Result := InterlockedIncrement(Addr^);
{$ELSE}
Result := TInterlocked.Increment(Addr^);
{$ENDIF}
end; { TOmniAlignedInt32.Increment }
function TOmniAlignedInt32.Increment(value: integer): integer;
begin
{$IFDEF MSWINDOWS}
Result := Add(value);
{$ELSE}
Result := TInterlocked.Add(Addr^, value);
{$ENDIF}
end; { TOmniAlignedInt32.Increment }
procedure TOmniAlignedInt32.SetValue(value: integer);
begin
Addr^ := value;
end; { TOmniAlignedInt32.SetValue }
class operator TOmniAlignedInt32.Add(const ai: TOmniAlignedInt32; i: integer): cardinal;
begin
Result := cardinal(int64(ai.Value) + i);
end; { TOmniAlignedInt32.Add }
class operator TOmniAlignedInt32.Equal(const ai: TOmniAlignedInt32; i: integer): boolean;
begin
Result := (ai.Value = i);
end; { TOmniAlignedInt32.Equal }
class operator TOmniAlignedInt32.GreaterThan(const ai: TOmniAlignedInt32; i: integer): boolean;
begin
Result := (ai.Value > i);
end; { TOmniAlignedInt32.GreaterThan }
class operator TOmniAlignedInt32.GreaterThanOrEqual(const ai: TOmniAlignedInt32; i: integer):
boolean;
begin
Result := (ai.Value >= i);
end; { TOmniAlignedInt32.GreaterThanOrEqual }
class operator TOmniAlignedInt32.Implicit(const ai: TOmniAlignedInt32): PInteger;
begin
Result := ai.Addr;
end; { TOmniAlignedInt32.Implicit }
class operator TOmniAlignedInt32.Implicit(const ai: TOmniAlignedInt32): cardinal;
begin
Result := ai.Value;
end; { TOmniAlignedInt32.Implicit }
class operator TOmniAlignedInt32.Implicit(const ai: TOmniAlignedInt32): integer;
begin
Result := integer(ai.Value);
end; { TOmniAlignedInt32.Implicit }
class operator TOmniAlignedInt32.LessThan(const ai: TOmniAlignedInt32; i: integer): boolean;
begin
Result := (ai.Value < i);
end; { TOmniAlignedInt32.LessThan }
class operator TOmniAlignedInt32.LessThanOrEqual(const ai: TOmniAlignedInt32; i: integer):
boolean;
begin
Result := (ai.Value <= i);
end; { TOmniAlignedInt32.LessThanOrEqual }
class operator TOmniAlignedInt32.NotEqual(const ai: TOmniAlignedInt32; i: integer): boolean;
begin
Result := (ai.Value <> i);
end; { TOmniAlignedInt32.NotEqual }
class operator TOmniAlignedInt32.Subtract(const ai: TOmniAlignedInt32; i: integer): cardinal;
begin
Result := cardinal(int64(ai.Value) - i);
end; { TOmniAlignedInt32.Subtract }
{ TOmniAlignedInt64 }
function TOmniAlignedInt64.Subtract(value: int64): int64; //inline
begin
{$IFDEF MSWINDOWS}
Result := DSiInterlockedExchangeAdd64(Addr^, -value) - value;
{$ELSE}
Result := TInterlocked.Add(Addr^, -value);
{$ENDIF}
end; { TOmniAlignedInt64.Subtract }
procedure TOmniAlignedInt64.Initialize;
begin
Assert(SizeOf(pointer) = SizeOf(NativeInt));
FAddr := PInt64((NativeInt(@FData) + 7) AND NOT 7);
end; { TOmniAlignedInt64.Initialize }
function TOmniAlignedInt64.Add(value: int64): int64;
begin
{$IFDEF MSWINDOWS}
Result := DSiInterlockedExchangeAdd64(Addr^, value) + value;
{$ELSE}
Result := TInterlocked.Add(Addr^, value);
{$ENDIF}
end; { TOmniAlignedInt64.Add }
function TOmniAlignedInt64.Addr: PInt64;
begin
Initialize;
Result := FAddr;
end; { TOmniAlignedInt64.Addr }
function TOmniAlignedInt64.CAS(oldValue, newValue: int64): boolean;
begin
{$IFDEF MSWINDOWS}
Result := DSiInterlockedCompareExchange64(Addr, newValue, oldValue) = oldValue;
{$ELSE}
Result := TInterlocked.CompareExchange(Addr^, newValue, OldValue) = oldValue;
{$ENDIF}
end; { TOmniAlignedInt64.CAS }
function TOmniAlignedInt64.Decrement: int64;
begin
{$IFDEF MSWINDOWS}
Result := DSiInterlockedDecrement64(Addr^);
{$ELSE}
Result := TInterlocked.Decrement(Addr^)
{$ENDIF}
end; { TOmniAlignedInt64.Decrement }
function TOmniAlignedInt64.Decrement(value: int64): int64;
begin
{$IFDEF MSWINDOWS}
Result := Subtract(value);
{$ELSE}
Result := TInterlocked.Add(Addr^, -value);
{$ENDIF}
end; { TOmniAlignedInt64.Decrement }
function TOmniAlignedInt64.GetValue: int64;
begin
Result := Addr^;
end; { TOmniAlignedInt64.GetValue }
function TOmniAlignedInt64.Increment: int64;
begin
{$IFDEF MSWINDOWS}
Result := DSiInterlockedIncrement64(Addr^);
{$ELSE}
Result := TInterlocked.Increment(Addr^);
{$ENDIF}
end; { TOmniAlignedInt64.Increment }
function TOmniAlignedInt64.Increment(value: int64): int64;
begin
{$IFDEF MSWINDOWS}
Result := Add(value);
{$ELSE}
Result := TInterlocked.Add(Addr^, value);
{$ENDIF}
end; { TOmniAlignedInt64.Increment }
procedure TOmniAlignedInt64.SetValue(value: int64);
begin
Addr^ := value;
end; { TOmniAlignedInt64.SetValue }
{ TOmniIntegerSet }
constructor TOmniIntegerSet.Clone(const value: IOmniIntegerSet);
begin
Create;
Assign(value);
end; { TOmniIntegerSet.Clone }
constructor TOmniIntegerSet.Create;
begin
inherited Create;
FBits := TBits.Create;
end; { TOmniIntegerSet.Create }
destructor TOmniIntegerSet.Destroy;
begin
FreeAndNil(FBits);
inherited;
end; { TOmniIntegerSet.Destroy }
function TOmniIntegerSet.Add(value: integer): boolean;
begin
if value >= FBits.Size then
FBits.Size := value + 1;
Result := FBits[value];
FBits[value] := true;
if not Result then
DoOnChange;
end; { TOmniIntegerSet.Add }
procedure TOmniIntegerSet.Assign(const value: IOmniIntegerSet);
var
i : integer;
oldValue: int64;
valBits : TBits;
begin
oldValue := AsMask;
valBits := value.AsBits;
FBits.Size := valBits.Size;
for i := 0 to FBits.Size - 1 do
FBits[i] := valBits[i];
if oldValue <> AsMask then
DoOnChange;
end; { TOmniIntegerSet.Assign }
procedure TOmniIntegerSet.Assign(const value: TOmniIntegerSet);
begin
Assign(value as IOmniIntegerSet);
end; { TOmniIntegerSet.Assign }
procedure TOmniIntegerSet.Clear;
begin
AsMask := 0;
end; { TOmniIntegerSet.Clear }
function TOmniIntegerSet.Contains(value: integer): boolean;
begin
Result := (value < FBits.Size) and FBits[value];
end; { TOmniIntegerSet.Contains }
function TOmniIntegerSet.Count: integer;
begin
PrepareValueCopy;
Result := Length(FValueCopy);
end; { TOmniIntegerSet.Count }
procedure TOmniIntegerSet.DoOnChange;
begin
FHasValueCopy := false;
if assigned(OnChange) then
OnChange(Self);
end; { TOmniIntegerSet.DoOnChange }
{$IFDEF OTL_HasArrayOfT}
function TOmniIntegerSet.GetAsArray: TArray<integer>;
var
count: integer;
i : integer;
begin
count := 0;
for i := 0 to FBits.Size - 1 do
if FBits[i] then
Inc(count);
SetLength(Result, count);
count := 0;
for i := 0 to FBits.Size - 1 do
if FBits[i] then begin
Result[count] := i;
Inc(count);
end;
end; { TOmniIntegerSet.GetAsArray }
{$ENDIF OTL_HasArrayOfT}
function TOmniIntegerSet.GetAsBits: TBits;
begin
Result := FBits;
end; { TOmniIntegerSet.GetAsBits }
function TOmniIntegerSet.GetAsIntArray: TIntegerDynArray;
var
i : integer;
numBits: integer;
begin
numBits := 0;
for i := 0 to FBits.Size - 1 do
if FBits[i] then
Inc(numBits);
SetLength(Result, numBits);
numBits := 0;
for i := 0 to FBits.Size - 1 do
if FBits[i] then begin
Result[numBits] := i;
Inc(numBits);
end;
end; { TOmniIntegerSet.GetAsIntArray }
function TOmniIntegerSet.GetAsMask: int64;
var
i: integer;
begin
if FBits.Size > 64 then
raise Exception.CreateFmt('Cannot convert %d elements to a 8-byte mask', [FBits.Size]);
Result := 0;
for i := FBits.Size - 1 downto 0 do begin
Result := Result SHL 1;
if FBits[i] then
Result := Result OR 1;
end;
end; { TOmniIntegerSet.GetAsMask }
function TOmniIntegerSet.GetItem(idx: integer): integer;
begin
PrepareValueCopy;
Result := FValueCopy[idx];
end; { TOmniIntegerSet.GetItem }
function TOmniIntegerSet.GetOnChange: TOmniIntegerSetChangedEvent;
begin
Result := FOnChange;
end; { TOmniIntegerSet.GetOnChange }
function TOmniIntegerSet.IsEmpty: boolean;
var
i: integer;
begin
Result := true;
for i := 0 to FBits.Size - 1 do
if FBits[i] then begin
Result := false;
Exit;
end;
end; { TOmniIntegerSet.IsEmpty }
procedure TOmniIntegerSet.PrepareValueCopy;
begin
if FHasValueCopy then
Exit;
FValueCopy := AsIntArray;
FHasValueCopy := true;
end; { TOmniIntegerSet.PrepareValueCopy }
function TOmniIntegerSet.Remove(value: integer): boolean;
begin
Result := FBits[value];
FBits[value] := false;
if Result then
DoOnChange;
end; { TOmniIntegerSet.Remove }
{$IFDEF OTL_HasArrayOfT}
procedure TOmniIntegerSet.SetAsArray(const value: TArray<integer>);
var
max : integer;
oldValue: int64;
val : integer;
begin
oldValue := AsMask;
max := 0;
for val in value do
if val > max then
max := val;
FBits.Size := max + 1;
for val := 0 to FBits.Size - 1 do
FBits[val] := false;
for val in value do
FBits[val] := true;
if oldValue <> AsMask then
DoOnChange;
end; { TOmniIntegerSet.SetAsArray }
{$ENDIF OTL_HasArrayOfT}
procedure TOmniIntegerSet.SetAsBits(const value: TBits);
var
i : integer;
max : integer;
oldValue: int64;
begin
oldValue := AsMask;
max := 0;
for i := 0 to value.Size - 1 do
if value[i] then
max := i;
FBits.Size := max+1;
for i := 0 to FBits.Size - 1 do
FBits[i] := value[i];
if oldValue <> AsMask then
DoOnChange;
end; { TOmniIntegerSet.SetAsBits }
procedure TOmniIntegerSet.SetAsIntArray(const value: TIntegerDynArray);
var
max : integer;
oldValue: int64;
val : integer;
begin
oldValue := AsMask;
max := 0;
for val in value do
if val > max then
max := val;
FBits.Size := max + 1;
for val := 0 to FBits.Size - 1 do
FBits[val] := false;
for val in value do
FBits[val] := true;
if oldValue <> AsMask then
DoOnChange;
end; { TOmniIntegerSet.SetAsIntArray }
procedure TOmniIntegerSet.SetAsMask(const value: int64);
var
b : boolean;
i : integer;
max : integer;
oldValue: int64;
val : int64;
begin
oldValue := AsMask;
FBits.Size := 64;
val := value;
max := 0;
for i := 0 to FBits.Size - 1 do begin
b := Odd(val);
if b then
max := i;
FBits[i] := b;
val := val SHR 1;
end;
if max <> 63 then
FBits.Size := max + 1;
if oldValue <> value then
DoOnChange;
end; { TOmniIntegerSet.SetAsMask }
procedure TOmniIntegerSet.SetOnChange(const value: TOmniIntegerSetChangedEvent);
begin
FOnChange := value;
end; { TOmniIntegerSet.SetOnChange }
{ TOmniGroupAffinity }
constructor TOmniGroupAffinity.Create(groupNumber: integer; const affinity: IOmniIntegerSet);
begin
Create(groupNumber, affinity.AsMask);
end; { TOmniGroupAffinity.Create }
constructor TOmniGroupAffinity.Create(groupNumber: integer; const affinityMask: int64);
begin
FGroup := groupNumber;
FAffinity := TOmniIntegerSet.Create;
FAffinity.AsMask := affinityMask;
end; { TOmniGroupAffinity.Create }
function TOmniGroupAffinity.GetAffinity: IOmniIntegerSet;
var
syncMask: IOmniIntegerSet;
begin
if not assigned(FAffinity) then begin
syncMask := TOmniIntegerSet.Create;
{$IFDEF MSWINDOWS}
if CAS(nil, pointer(syncMask), FAffinity) then
{$ELSE}
if TInterlocked.CompareExchange(pointer(FAffinity), pointer(syncMask), nil) = nil then
{$ENDIF}
pointer(syncMask) := nil;
end;
Result := FAffinity;
end; { TOmniGroupAffinity.GetAffinity }
initialization
Assert(SizeOf(TObject) = {$IFDEF CPUX64}SizeOf(NativeUInt){$ELSE}SizeOf(cardinal){$ENDIF}); //in VarToObj
GEnvironment := TOmniEnvironment.Create;
FillChar(TOmniValue_DataSize, SizeOf(TOmniValue_DataSize), 0);
TOmniValue_DataSize[tkInteger] := SizeOf(integer);
TOmniValue_DataSize[tkClass] := SizeOf(TObject);
TOmniValue_DataSize[tkMethod] := SizeOf(TMethod);
TOmniValue_DataSize[tkInt64] := SizeOf(int64);
{$IFDEF OTL_HasTkPointer}
TOmniValue_DataSize[tkPointer] := SizeOf(pointer);
{$ENDIF OTL_HasTkPointer}
TOmniValue._RemoveWarnings;
end.
| 31.710563 | 187 | 0.727097 |
834fa10feb72d4c8f655de126d482862d2d77dc0 | 1,983 | dfm | Pascal | Components/JVCL/lib/d7/JvWallpaperEditForm.dfm | sabatex/Delphi | 0efbe6eb38bf8aa2bf269d1866741266e90b9cbf | [
"MIT"
]
| null | null | null | Components/JVCL/lib/d7/JvWallpaperEditForm.dfm | sabatex/Delphi | 0efbe6eb38bf8aa2bf269d1866741266e90b9cbf | [
"MIT"
]
| null | null | null | Components/JVCL/lib/d7/JvWallpaperEditForm.dfm | sabatex/Delphi | 0efbe6eb38bf8aa2bf269d1866741266e90b9cbf | [
"MIT"
]
| 1 | 2019-12-24T08:39:18.000Z | 2019-12-24T08:39:18.000Z | object FoWallpaperChooser: TFoWallpaperChooser
Left = 401
Top = 250
Width = 400
Height = 308
BorderIcons = [biSystemMenu]
Caption = 'Wallpaper Chooser'
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
Position = poScreenCenter
Scaled = False
OnCreate = FormCreate
OnDestroy = FormDestroy
PixelsPerInch = 96
TextHeight = 13
object Button1: TButton
Left = 6
Top = 245
Width = 75
Height = 25
Anchors = [akLeft, akBottom]
Caption = '&OK'
ModalResult = 1
TabOrder = 2
end
object Button2: TButton
Left = 84
Top = 245
Width = 75
Height = 25
Anchors = [akLeft, akBottom]
Caption = '&Cancel'
ModalResult = 2
TabOrder = 3
end
object Button3: TButton
Left = 309
Top = 245
Width = 75
Height = 25
Anchors = [akRight, akBottom]
Caption = '&Clear'
TabOrder = 4
OnClick = Button3Click
end
object GroupBox1: TGroupBox
Left = 6
Top = 6
Width = 382
Height = 39
Anchors = [akLeft, akTop, akRight]
TabOrder = 0
object Label1: TLabel
Left = 8
Top = 16
Width = 42
Height = 13
Caption = 'Directory'
end
object DirectoryBox1: TJvDirectoryEdit
Left = 58
Top = 12
Width = 318
Height = 21
OnAfterDialog = DirectoryBox1AfterDialog
DialogKind = dkWin32
ButtonFlat = False
Anchors = [akLeft, akTop, akRight]
TabOrder = 0
end
end
object ScrollBox1: TScrollBox
Left = 6
Top = 48
Width = 382
Height = 186
Anchors = [akLeft, akTop, akRight, akBottom]
TabOrder = 1
end
object SearchFiles1: TJvSearchFiles
DirOption = doExcludeSubDirs
FileParams.SearchTypes = [stFileMask]
FileParams.FileMasks.Strings = (
'*.bmp')
OnFindFile = SearchFile1Found
Left = 112
Top = 64
end
end
| 20.873684 | 48 | 0.620272 |
4717f0f3dcac4a54a71953ee5ca03ea06e825626 | 106 | lpr | Pascal | Data/PassRc/MiniTest10.lpr | joecare99/Public | 9eee060fbdd32bab33cf65044602976ac83f4b83 | [
"MIT"
]
| 11 | 2017-06-17T05:13:45.000Z | 2021-07-11T13:18:48.000Z | Data/PassRc/MiniTest10.lpr | joecare99/Public | 9eee060fbdd32bab33cf65044602976ac83f4b83 | [
"MIT"
]
| 2 | 2019-03-05T12:52:40.000Z | 2021-12-03T12:34:26.000Z | Data/PassRc/MiniTest10.lpr | joecare99/Public | 9eee060fbdd32bab33cf65044602976ac83f4b83 | [
"MIT"
]
| 6 | 2017-09-07T09:10:09.000Z | 2022-02-19T20:19:58.000Z | begin case true of true:if false then write('t')else else write('f')end; readln end. // try if then else
| 53 | 105 | 0.707547 |
477bf5b743ce104a516893f0386a99bb30bedcf8 | 399 | pas | Pascal | Test/SimpleScripts/implies.pas | synapsea/DW-Script | b36c2e57f0285c217f8f0cae8e4e158d21127163 | [
"Condor-1.1"
]
| 1 | 2022-02-18T22:14:44.000Z | 2022-02-18T22:14:44.000Z | Test/SimpleScripts/implies.pas | synapsea/DW-Script | b36c2e57f0285c217f8f0cae8e4e158d21127163 | [
"Condor-1.1"
]
| null | null | null | Test/SimpleScripts/implies.pas | synapsea/DW-Script | b36c2e57f0285c217f8f0cae8e4e158d21127163 | [
"Condor-1.1"
]
| null | null | null | var t = True;
var f = not t;
function Oopsie : Boolean;
begin
PrintLn('Oops');
Result:=False;
end;
function Ookie : Boolean;
begin
PrintLn('Ookie');
exit True;
end;
PrintLn(t implies t);
PrintLn(t implies f);
PrintLn(f implies t);
PrintLn(f implies f);
if (f implies Oopsie) then
PrintLn('Ok')
else PrintLn('Bug');
if (t implies Ookie) then
PrintLn('Ok')
else PrintLn('Bug');
| 14.25 | 26 | 0.661654 |
472cd5f90c8ecb70ee79caed976cd498064c0ed8 | 369 | dfm | Pascal | SpringAndDMVC/Server/Views/Main.View.dfm | ezequieljuliano/DelphiLaboratory | 14bd04efcd4a1d8234d103aead8de3056fdf1237 | [
"Apache-2.0"
]
| 23 | 2016-02-10T16:35:03.000Z | 2022-02-18T19:24:40.000Z | SpringAndDMVC/Server/Views/Main.View.dfm | AngusPasc/DelphiLaboratory | 14bd04efcd4a1d8234d103aead8de3056fdf1237 | [
"Apache-2.0"
]
| 1 | 2016-03-16T12:08:08.000Z | 2016-09-02T11:05:17.000Z | SpringAndDMVC/Server/Views/Main.View.dfm | AngusPasc/DelphiLaboratory | 14bd04efcd4a1d8234d103aead8de3056fdf1237 | [
"Apache-2.0"
]
| 7 | 2016-04-15T17:52:32.000Z | 2020-01-26T21:04:05.000Z | object MainView: TMainView
Left = 0
Top = 0
Caption = 'Standalone Server Main View'
ClientHeight = 300
ClientWidth = 635
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
Position = poScreenCenter
PixelsPerInch = 96
TextHeight = 13
end
| 20.5 | 41 | 0.701897 |
475436c6004f3d4429566078becd687a317d39ff | 1,922 | pas | Pascal | src/Libs/HttpClient/Implementations/Fpc/Factories/FpcHttpPutFactoryImpl.pas | zamronypj/fano-framework | 559e385be5e1d26beada94c46eb8e760c4d855da | [
"MIT"
]
| 78 | 2019-01-31T13:40:48.000Z | 2022-03-22T17:26:54.000Z | src/Libs/HttpClient/Implementations/Fpc/Factories/FpcHttpPutFactoryImpl.pas | zamronypj/fano-framework | 559e385be5e1d26beada94c46eb8e760c4d855da | [
"MIT"
]
| 24 | 2020-01-04T11:50:53.000Z | 2022-02-17T09:55:23.000Z | src/Libs/HttpClient/Implementations/Fpc/Factories/FpcHttpPutFactoryImpl.pas | zamronypj/fano-framework | 559e385be5e1d26beada94c46eb8e760c4d855da | [
"MIT"
]
| 9 | 2018-11-05T03:43:24.000Z | 2022-01-21T17:23:30.000Z | {*!
* Fano Web Framework (https://fanoframework.github.io)
*
* @link https://github.com/fanoframework/fano
* @copyright Copyright (c) 2018 - 2021 Zamrony P. Juhara
* @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT)
*}
unit FpcHttpPutFactoryImpl;
interface
{$MODE OBJFPC}
uses
DependencyIntf,
DependencyContainerIntf,
FactoryImpl;
type
(*!------------------------------------------------
* TFpcHttpPut factory class
*------------------------------------------------
* This class can serve as factory class for TFpcHttpPut
* and also can be injected into dependency container
* directly to build TFpcHttpPut class
*-------------------------------------------------
* @author Zamrony P. Juhara <zamronypj@yahoo.com>
*-----------------------------------------------*)
TFpcHttpPutFactory = class(TFactory)
public
(*!---------------------------------------------------
* build class instance
*----------------------------------------------------
* @param container dependency container instance
*----------------------------------------------------
* This is implementation of IDependencyFactory
*---------------------------------------------------*)
function build(const container : IDependencyContainer) : IDependency; override;
end;
implementation
uses
FpcHttpPutImpl,
QueryStrBuilderImpl;
(*!---------------------------------------------------
* build class instance
*----------------------------------------------------
* @param container dependency container instance
*---------------------------------------------------*)
function TFpcHttpPutFactory.build(const container : IDependencyContainer) : IDependency;
begin
result := TFpcHttpPut.create(TQueryStrBuilder.create());
end;
end.
| 32.033333 | 92 | 0.469303 |
83dfd61ded3eb3e91d9dadb085ae816362d63080 | 289 | pas | Pascal | 1. Konsep Pemilihan/pascalcredit1.pas | belajarstatistik/Algoritma-Pemrograman | 4f33b359254db167b6107757d35d50d391d836e2 | [
"MIT"
]
| null | null | null | 1. Konsep Pemilihan/pascalcredit1.pas | belajarstatistik/Algoritma-Pemrograman | 4f33b359254db167b6107757d35d50d391d836e2 | [
"MIT"
]
| null | null | null | 1. Konsep Pemilihan/pascalcredit1.pas | belajarstatistik/Algoritma-Pemrograman | 4f33b359254db167b6107757d35d50d391d836e2 | [
"MIT"
]
| null | null | null | program pascalcredit1;
const
limit=1000000;
var
jumlah:real;
begin
write('Masukkan jumlah : ');readln(jumlah);
if jumlah <= limit then
writeln('Tagihan Anda diterima '); {Akhir pernyataan
if}
writeln('Tekan ENTER untuk keluar ...');
readln;
end. | 22.230769 | 57 | 0.633218 |
47726f9a7ec77b0109d5970b0363aac50fd47494 | 29,120 | pas | Pascal | Ext/SynEdit/Source/SynHighlighterWebIDL.pas | CloudDelphi/FExplorer | cb2c1a3145245535915e63b7da1bfb02525bd350 | [
"Apache-2.0"
]
| 63 | 2021-02-05T15:47:56.000Z | 2022-03-09T11:36:39.000Z | Kide/Externals/SynEdit/Source/SynHighlighterWebIDL.pas | gz818/kitto3 | e76eea45028d732730a66c2d6238d13cd2e65392 | [
"Apache-2.0"
]
| 13 | 2021-02-11T08:39:38.000Z | 2022-03-28T22:48:09.000Z | Kide/Externals/SynEdit/Source/SynHighlighterWebIDL.pas | gz818/kitto3 | e76eea45028d732730a66c2d6238d13cd2e65392 | [
"Apache-2.0"
]
| 5 | 2021-02-12T15:35:55.000Z | 2021-07-11T02:34:40.000Z | {-------------------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
the specific language governing rights and limitations under the License.
Code template generated with SynGen.
The original code is: SynHighlighterWebIDL.pas, released 2013-02-14.
Description: Syntax Parser/Highlighter
The initial author of this file is Christian-W. Budde.
Copyright (c) 2013, all rights reserved.
Contributors to the SynEdit and mwEdit projects are listed in the
Contributors.txt file.
Alternatively, the contents of this file may be used under the terms of the
GNU General Public License Version 2 or later (the "GPL"), in which case
the provisions of the GPL are applicable instead of those above.
If you wish to allow use of your version of this file only under the terms
of the GPL and not to allow others to use your version of this file
under the MPL, indicate your decision by deleting the provisions above and
replace them with the notice and other provisions required by the GPL.
If you do not delete the provisions above, a recipient may use your version
of this file under either the MPL or the GPL.
$Id: $
You may retrieve the latest version of this file at the SynEdit home page,
located at http://SynEdit.SourceForge.net
-------------------------------------------------------------------------------}
unit SynHighlighterWebIDL;
{$I SynEdit.inc}
interface
uses
Graphics,
SynEditTypes,
SynEditHighlighter,
SynUnicode,
SysUtils,
Classes;
type
TtkTokenKind = (
tkArguments,
tkComment,
tkExtendedAttributes,
tkIdentifier,
tkKey,
tkNull,
tkNumber,
tkSpace,
tkString,
tkTypes,
tkSymbol,
tkUnknown);
TstkSymbolTokenKind = (
stkBraceOpen,
stkBraceClose,
stkSquareOpen,
stkSquareClose,
stkQuestionMark,
stkColon,
stkGreater,
stkLess
);
TRangeState = (rsUnknown, rsSingleComment, rsCStyleComment, rsString,
rsExtendedAttributes);
TProcTableProc = procedure of object;
PIdentFuncTableFunc = ^TIdentFuncTableFunc;
TIdentFuncTableFunc = function (Index: Integer): TtkTokenKind of object;
type
TSynWebIDLSyn = class(TSynCustomHighlighter)
private
fRange: TRangeState;
fTokenID: TtkTokenKind;
fSymbolTokenID: TstkSymbolTokenKind;
fIdentFuncTable: array [0..58] of TIdentFuncTableFunc;
fArgumentsAttri: TSynHighlighterAttributes;
fExtendedAttri: TSynHighlighterAttributes;
fCommentAttri: TSynHighlighterAttributes;
fIdentifierAttri: TSynHighlighterAttributes;
fKeyAttri: TSynHighlighterAttributes;
fNumberAttri: TSynHighlighterAttributes;
fSpaceAttri: TSynHighlighterAttributes;
fStringAttri: TSynHighlighterAttributes;
fSymbolAttri: TSynHighlighterAttributes;
fTypesAttri: TSynHighlighterAttributes;
function HashKey(Str: PWideChar): Cardinal;
function FuncAny(Index: Integer): TtkTokenKind;
function FuncAttribute(Index: Integer): TtkTokenKind;
function FuncBoolean(Index: Integer): TtkTokenKind;
function FuncByte(Index: Integer): TtkTokenKind;
function FuncBytestring(Index: Integer): TtkTokenKind;
function FuncCallback(Index: Integer): TtkTokenKind;
function FuncConst(Index: Integer): TtkTokenKind;
function FuncCreator(Index: Integer): TtkTokenKind;
function FuncDate(Index: Integer): TtkTokenKind;
function FuncDeleter(Index: Integer): TtkTokenKind;
function FuncDictionary(Index: Integer): TtkTokenKind;
function FuncDomstring(Index: Integer): TtkTokenKind;
function FuncDouble(Index: Integer): TtkTokenKind;
function FuncEnum(Index: Integer): TtkTokenKind;
function FuncException(Index: Integer): TtkTokenKind;
function FuncFloat(Index: Integer): TtkTokenKind;
function FuncGetter(Index: Integer): TtkTokenKind;
function FuncImplements(Index: Integer): TtkTokenKind;
function FuncInherit(Index: Integer): TtkTokenKind;
function FuncInterface(Index: Integer): TtkTokenKind;
function FuncLegacycaller(Index: Integer): TtkTokenKind;
function FuncLong(Index: Integer): TtkTokenKind;
function FuncObject(Index: Integer): TtkTokenKind;
function FuncOctet(Index: Integer): TtkTokenKind;
function FuncOptional(Index: Integer): TtkTokenKind;
function FuncPartial(Index: Integer): TtkTokenKind;
function FuncReadonly(Index: Integer): TtkTokenKind;
function FuncRegexp(Index: Integer): TtkTokenKind;
function FuncSequence(Index: Integer): TtkTokenKind;
function FuncSetter(Index: Integer): TtkTokenKind;
function FuncShort(Index: Integer): TtkTokenKind;
function FuncStatic(Index: Integer): TtkTokenKind;
function FuncStringifier(Index: Integer): TtkTokenKind;
function FuncTypedef(Index: Integer): TtkTokenKind;
function FuncUnresticted(Index: Integer): TtkTokenKind;
function FuncUnrestricted(Index: Integer): TtkTokenKind;
function FuncUnsigned(Index: Integer): TtkTokenKind;
function FuncVoid(Index: Integer): TtkTokenKind;
procedure IdentProc;
procedure UnknownProc;
function AltFunc(Index: Integer): TtkTokenKind;
procedure InitIdent;
function IdentKind(MayBe: PWideChar): TtkTokenKind;
procedure BraceCloseProc;
procedure BraceOpenProc;
procedure ColonProc;
procedure CRProc;
procedure CStyleCommentProc;
procedure GreaterProc;
procedure LessProc;
procedure LFProc;
procedure NullProc;
procedure NumberProc;
procedure QuestionMarkProc;
procedure SlashProc;
procedure SpaceProc;
procedure SquareCloseProc;
procedure SquareOpenProc;
procedure StringOpenProc;
procedure StringProc;
protected
function GetSampleSource: UnicodeString; override;
function IsFilterStored: Boolean; override;
public
constructor Create(AOwner: TComponent); override;
class function GetFriendlyLanguageName: UnicodeString; override;
class function GetLanguageName: string; override;
function GetRange: Pointer; override;
procedure ResetRange; override;
procedure SetRange(Value: Pointer); override;
function GetDefaultAttribute(Index: Integer): TSynHighlighterAttributes; override;
function GetEol: Boolean; override;
function GetKeyWords(TokenKind: Integer): UnicodeString; override;
function GetTokenID: TtkTokenKind;
function GetTokenAttribute: TSynHighlighterAttributes; override;
function GetTokenKind: Integer; override;
function IsIdentChar(AChar: WideChar): Boolean; override;
procedure Next; override;
published
property ArgumentsAttri: TSynHighlighterAttributes read fArgumentsAttri write fArgumentsAttri;
property CommentAttri: TSynHighlighterAttributes read fCommentAttri write fCommentAttri;
property ExtendedAttri: TSynHighlighterAttributes read fExtendedAttri write fExtendedAttri;
property IdentifierAttri: TSynHighlighterAttributes read fIdentifierAttri write fIdentifierAttri;
property KeyAttri: TSynHighlighterAttributes read fKeyAttri write fKeyAttri;
property NumberAttri: TSynHighlighterAttributes read fNumberAttri write fNumberAttri;
property SpaceAttri: TSynHighlighterAttributes read fSpaceAttri write fSpaceAttri;
property StringAttri: TSynHighlighterAttributes read fStringAttri write fStringAttri;
property SymbolAttri: TSynHighlighterAttributes read fSymbolAttri write fSymbolAttri;
property TypesAttri: TSynHighlighterAttributes read fTypesAttri write fTypesAttri;
end;
implementation
uses
SynEditStrConst;
resourcestring
SYNS_FilterWebIDL = 'Web IDL (*.idl)|*.idl';
SYNS_LangWebIDL = 'Web IDL';
SYNS_FriendlyLangWebIDL = 'Web IDL';
SYNS_AttrArguments = 'Arguments';
SYNS_FriendlyAttrArguments = 'Arguments';
SYNS_AttrExtended = 'Extended';
SYNS_FriendlyAttrExtended = 'Extended';
const
// as this language is case-insensitive keywords *must* be in lowercase
KeyWords: array[0..37] of UnicodeString = (
'any', 'attribute', 'boolean', 'byte', 'bytestring', 'callback', 'const',
'creator', 'date', 'deleter', 'dictionary', 'domstring', 'double', 'enum',
'exception', 'float', 'getter', 'implements', 'inherit', 'interface',
'legacycaller', 'long', 'object', 'octet', 'optional', 'partial',
'readonly', 'regexp', 'sequence', 'setter', 'short', 'static',
'stringifier', 'typedef', 'unresticted', 'unrestricted', 'unsigned', 'void'
);
KeyIndices: array[0..58] of Integer = (
14, 28, 4, 37, 21, -1, -1, 12, 17, -1, -1, 22, -1, 3, -1, -1, 29, -1, 27,
31, -1, 1, 20, -1, 24, 15, 2, -1, -1, -1, -1, 23, -1, 19, 0, 13, 11, 16, 34,
10, 36, 25, -1, 30, -1, 33, 32, 6, -1, 9, 7, -1, 8, -1, 26, 18, -1, 5, 35
);
constructor TSynWebIDLSyn.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fCaseSensitive := False;
fArgumentsAttri := TSynHighLighterAttributes.Create(SYNS_AttrArguments,
SYNS_FriendlyAttrArguments);
fArgumentsAttri.Style := [fsBold];
fArgumentsAttri.Foreground := clNavy;
AddAttribute(fArgumentsAttri);
fCommentAttri := TSynHighLighterAttributes.Create(SYNS_AttrComment,
SYNS_FriendlyAttrComment);
fCommentAttri.Style := [fsItalic];
fCommentAttri.Foreground := clGreen;
AddAttribute(fCommentAttri);
fExtendedAttri := TSynHighlighterAttributes.Create(SYNS_AttrExtended,
SYNS_FriendlyAttrExtended);
fExtendedAttri.Style := [fsBold, fsItalic];
fExtendedAttri.Foreground := clMaroon;
AddAttribute(fExtendedAttri);
fIdentifierAttri := TSynHighLighterAttributes.Create(SYNS_AttrIdentifier,
SYNS_FriendlyAttrIdentifier);
AddAttribute(fIdentifierAttri);
fKeyAttri := TSynHighLighterAttributes.Create(SYNS_AttrReservedWord,
SYNS_FriendlyAttrReservedWord);
fKeyAttri.Style := [fsBold];
fKeyAttri.Foreground := clNavy;
AddAttribute(fKeyAttri);
fNumberAttri := TSynHighlighterAttributes.Create(SYNS_AttrNumber, SYNS_FriendlyAttrNumber);
fNumberAttri.Foreground := clBlue;
AddAttribute(fNumberAttri);
fSpaceAttri := TSynHighLighterAttributes.Create(SYNS_AttrSpace, SYNS_FriendlyAttrSpace);
AddAttribute(fSpaceAttri);
fStringAttri := TSynHighLighterAttributes.Create(SYNS_AttrString, SYNS_FriendlyAttrString);
fStringAttri.Foreground := clPurple;
AddAttribute(fStringAttri);
fSymbolAttri := TSynHighLighterAttributes.Create(SYNS_AttrSymbol, SYNS_FriendlyAttrSymbol);
fSymbolAttri.Style := [fsBold];
fSymbolAttri.Foreground := clMaroon;
AddAttribute(fSymbolAttri);
fTypesAttri := TSynHighLighterAttributes.Create(SYNS_AttrDataType, SYNS_FriendlyAttrDataType);
fTypesAttri.Foreground := clNavy;
AddAttribute(fTypesAttri);
SetAttributesOnChange(DefHighlightChange);
InitIdent;
fDefaultFilter := SYNS_FilterWebIDL;
fRange := rsUnknown;
end;
procedure TSynWebIDLSyn.InitIdent;
var
i: Integer;
begin
for i := Low(fIdentFuncTable) to High(fIdentFuncTable) do
if KeyIndices[i] = -1 then
fIdentFuncTable[i] := AltFunc;
fIdentFuncTable[34] := FuncAny;
fIdentFuncTable[21] := FuncAttribute;
fIdentFuncTable[26] := FuncBoolean;
fIdentFuncTable[13] := FuncByte;
fIdentFuncTable[2] := FuncBytestring;
fIdentFuncTable[57] := FuncCallback;
fIdentFuncTable[47] := FuncConst;
fIdentFuncTable[50] := FuncCreator;
fIdentFuncTable[52] := FuncDate;
fIdentFuncTable[49] := FuncDeleter;
fIdentFuncTable[39] := FuncDictionary;
fIdentFuncTable[36] := FuncDomstring;
fIdentFuncTable[7] := FuncDouble;
fIdentFuncTable[35] := FuncEnum;
fIdentFuncTable[0] := FuncException;
fIdentFuncTable[25] := FuncFloat;
fIdentFuncTable[37] := FuncGetter;
fIdentFuncTable[8] := FuncImplements;
fIdentFuncTable[55] := FuncInherit;
fIdentFuncTable[33] := FuncInterface;
fIdentFuncTable[22] := FuncLegacycaller;
fIdentFuncTable[4] := FuncLong;
fIdentFuncTable[11] := FuncObject;
fIdentFuncTable[31] := FuncOctet;
fIdentFuncTable[24] := FuncOptional;
fIdentFuncTable[41] := FuncPartial;
fIdentFuncTable[54] := FuncReadonly;
fIdentFuncTable[18] := FuncRegexp;
fIdentFuncTable[1] := FuncSequence;
fIdentFuncTable[16] := FuncSetter;
fIdentFuncTable[43] := FuncShort;
fIdentFuncTable[19] := FuncStatic;
fIdentFuncTable[46] := FuncStringifier;
fIdentFuncTable[45] := FuncTypedef;
fIdentFuncTable[38] := FuncUnresticted;
fIdentFuncTable[58] := FuncUnrestricted;
fIdentFuncTable[40] := FuncUnsigned;
fIdentFuncTable[3] := FuncVoid;
end;
procedure TSynWebIDLSyn.ColonProc;
begin
Inc(Run);
fTokenId := tkSymbol;
fSymbolTokenID := stkColon;
end;
{$Q-}
function TSynWebIDLSyn.HashKey(Str: PWideChar): Cardinal;
begin
Result := 0;
while IsIdentChar(Str^) do
begin
Result := Result * 622 + Ord(Str^) * 657;
inc(Str);
end;
Result := Result mod 59;
fStringLen := Str - fToIdent;
end;
{$Q+}
function TSynWebIDLSyn.FuncAny(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkTypes
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncAttribute(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkArguments
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncBoolean(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkTypes
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncByte(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkTypes
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncBytestring(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkTypes
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncCallback(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkKey
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncConst(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkArguments
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncCreator(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkArguments
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncDate(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkTypes
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncDeleter(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkArguments
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncDictionary(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkKey
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncDomstring(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkTypes
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncDouble(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkTypes
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncEnum(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkKey
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncException(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkKey
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncFloat(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkTypes
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncGetter(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkArguments
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncImplements(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkArguments
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncInherit(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkArguments
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncInterface(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkKey
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncLegacycaller(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkArguments
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncLong(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkTypes
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncObject(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkTypes
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncOctet(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkTypes
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncOptional(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkArguments
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncPartial(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkKey
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncReadonly(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkArguments
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncRegexp(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkTypes
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncSequence(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkTypes
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncSetter(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkArguments
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncShort(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkTypes
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncStatic(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkArguments
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncStringifier(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkArguments
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncTypedef(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkArguments
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncUnresticted(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkTypes
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncUnrestricted(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkArguments
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncUnsigned(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkTypes
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.FuncVoid(Index: Integer): TtkTokenKind;
begin
if IsCurrentToken(KeyWords[Index]) then
Result := tkTypes
else
Result := tkIdentifier;
end;
function TSynWebIDLSyn.AltFunc(Index: Integer): TtkTokenKind;
begin
Result := tkIdentifier;
end;
function TSynWebIDLSyn.IdentKind(MayBe: PWideChar): TtkTokenKind;
var
Key: Cardinal;
begin
fToIdent := MayBe;
Key := HashKey(MayBe);
if Key <= High(fIdentFuncTable) then
Result := fIdentFuncTable[Key](KeyIndices[Key])
else
Result := tkIdentifier;
end;
procedure TSynWebIDLSyn.SpaceProc;
begin
inc(Run);
fTokenID := tkSpace;
while (FLine[Run] <= #32) and not IsLineEnd(Run) do inc(Run);
end;
procedure TSynWebIDLSyn.NullProc;
begin
fTokenID := tkNull;
inc(Run);
end;
procedure TSynWebIDLSyn.NumberProc;
function IsNumberChar: Boolean;
begin
case fLine[Run] of
'0'..'9', '.', 'a'..'f', 'A'..'F', 'x', 'X':
Result := True;
else
Result := False;
end;
end;
function IsHexChar(Run: Integer): Boolean;
begin
case fLine[Run] of
'0'..'9', 'a'..'f', 'A'..'F':
Result := True;
else
Result := False;
end;
end;
var
idx1: Integer; // token[1]
isHex: Boolean;
begin
fTokenID := tkNumber;
isHex := False;
idx1 := Run;
Inc(Run);
while IsNumberChar do
begin
case FLine[Run] of
'.':
if FLine[Succ(Run)] = '.' then
Break;
'a'..'f', 'A'..'F':
if not isHex then
Break;
'x', 'X':
begin
if (FLine[idx1] <> '0') or (Run > Succ(idx1)) then
Break;
if not IsHexChar(Succ(Run)) then
Break;
isHex := True;
end;
end;
Inc(Run);
end;
end;
procedure TSynWebIDLSyn.QuestionMarkProc;
begin
Inc(Run);
fTokenID := tkSymbol;
fSymbolTokenID := stkQuestionMark;
end;
procedure TSynWebIDLSyn.CRProc;
begin
fTokenID := tkSpace;
inc(Run);
if fLine[Run] = #10 then
inc(Run);
end;
procedure TSynWebIDLSyn.GreaterProc;
begin
Inc(Run);
fTokenId := tkSymbol;
fSymbolTokenID := stkGreater;
end;
procedure TSynWebIDLSyn.LessProc;
begin
Inc(Run);
fTokenId := tkSymbol;
fSymbolTokenID := stkLess;
end;
procedure TSynWebIDLSyn.LFProc;
begin
fTokenID := tkSpace;
inc(Run);
end;
procedure TSynWebIDLSyn.SlashProc;
begin
Inc(Run);
case fLine[Run] of
'/':
begin
repeat
Inc(Run);
until IsLineEnd(Run);
fRange := rsSingleComment;
fTokenID := tkComment;
end;
'*':
begin
Inc(Run, 1);
fRange := rsCStyleComment;
fTokenID := tkComment;
end
else
fTokenID := tkIdentifier;
end;
end;
procedure TSynWebIDLSyn.CStyleCommentProc;
begin
case fLine[Run] of
#0: NullProc;
#10: LFProc;
#13: CRProc;
else
begin
fTokenID := tkComment;
repeat
if (fLine[Run] = '*') and
(fLine[Run + 1] = '/') then
begin
Inc(Run, 2);
fRange := rsUnKnown;
Break;
end;
if not IsLineEnd(Run) then
Inc(Run);
until IsLineEnd(Run);
end;
end;
end;
procedure TSynWebIDLSyn.StringOpenProc;
begin
Inc(Run);
fRange := rsString;
fTokenID := tkString;
end;
procedure TSynWebIDLSyn.StringProc;
begin
case fLine[Run] of
#0: NullProc;
#10: LFProc;
#13: CRProc;
else
begin
fTokenID := tkString;
repeat
if (fLine[Run] = '"') then
begin
Inc(Run, 1);
fRange := rsUnKnown;
Break;
end;
if not IsLineEnd(Run) then
Inc(Run);
until IsLineEnd(Run);
end;
end;
end;
procedure TSynWebIDLSyn.IdentProc;
begin
fTokenID := IdentKind((fLine + Run));
Inc(Run, fStringLen);
while IsIdentChar(fLine[Run]) do
Inc(Run);
end;
procedure TSynWebIDLSyn.BraceOpenProc;
begin
Inc(Run);
fTokenId := tkSymbol;
fSymbolTokenID := stkBraceOpen;
end;
procedure TSynWebIDLSyn.BraceCloseProc;
begin
Inc(Run);
fTokenId := tkSymbol;
fSymbolTokenID := stkBraceClose;
end;
procedure TSynWebIDLSyn.SquareOpenProc;
begin
Inc(Run);
fTokenID := tkSymbol;
fSymbolTokenID := stkSquareOpen;
fRange := rsExtendedAttributes;
end;
procedure TSynWebIDLSyn.SquareCloseProc;
begin
Inc(Run);
fTokenID := tkSymbol;
fSymbolTokenID := stkSquareClose;
fRange := rsUnknown
end;
procedure TSynWebIDLSyn.UnknownProc;
begin
inc(Run);
fTokenID := tkUnknown;
end;
procedure TSynWebIDLSyn.Next;
begin
fTokenPos := Run;
case fRange of
rsCStyleComment: CStyleCommentProc;
rsString: StringProc;
else
case fLine[Run] of
#0: NullProc;
#10: LFProc;
#13: CRProc;
'/': SlashProc;
'"': StringOpenProc;
#1..#9, #11, #12, #14..#32: SpaceProc;
'0'..'9': NumberProc;
'A'..'Z', 'a'..'z', '_': IdentProc;
'{': BraceOpenProc;
'}': BraceCloseProc;
']': SquareCloseProc;
'[': SquareOpenProc;
'?': QuestionMarkProc;
':': ColonProc;
'>': GreaterProc;
'<': LessProc;
else
UnknownProc;
end;
end;
inherited;
end;
function TSynWebIDLSyn.GetDefaultAttribute(Index: Integer): TSynHighLighterAttributes;
begin
case Index of
SYN_ATTR_COMMENT: Result := fCommentAttri;
SYN_ATTR_IDENTIFIER: Result := fIdentifierAttri;
SYN_ATTR_KEYWORD: Result := fKeyAttri;
SYN_ATTR_STRING: Result := fStringAttri;
SYN_ATTR_WHITESPACE: Result := fSpaceAttri;
SYN_ATTR_SYMBOL: Result := fSymbolAttri;
else
Result := nil;
end;
end;
function TSynWebIDLSyn.GetEol: Boolean;
begin
Result := Run = fLineLen + 1;
end;
function TSynWebIDLSyn.GetKeyWords(TokenKind: Integer): UnicodeString;
begin
Result :=
'any,attribute,boolean,byte,ByteString,callback,const,creator,Date,del' +
'eter,dictionary,DOMString,double,enum,exception,float,getter,implement' +
's,inherit,interface,legacycaller,long,object,octet,optional,partial,re' +
'adonly,RegExp,sequence,setter,short,static,stringifier,typedef,unresti' +
'cted,unrestricted,unsigned,void';
end;
function TSynWebIDLSyn.GetTokenID: TtkTokenKind;
begin
Result := fTokenId;
if (fRange = rsExtendedAttributes) and not ((fTokenID = tkSymbol) and
(fSymbolTokenID = stkSquareOpen)) then
Result := tkExtendedAttributes;
end;
function TSynWebIDLSyn.GetTokenAttribute: TSynHighLighterAttributes;
begin
case GetTokenID of
tkArguments: Result := fArgumentsAttri;
tkComment: Result := fCommentAttri;
tkExtendedAttributes: Result := fExtendedAttri;
tkIdentifier: Result := fIdentifierAttri;
tkKey: Result := fKeyAttri;
tkNumber: Result := fNumberAttri;
tkSpace: Result := fSpaceAttri;
tkString: Result := fStringAttri;
tkSymbol: Result := fSymbolAttri;
tkTypes: Result := fTypesAttri;
tkUnknown: Result := fIdentifierAttri;
else
Result := nil;
end;
end;
function TSynWebIDLSyn.GetTokenKind: Integer;
begin
Result := Ord(fTokenId);
end;
function TSynWebIDLSyn.IsIdentChar(AChar: WideChar): Boolean;
begin
case AChar of
'_', '0'..'9', 'a'..'z', 'A'..'Z':
Result := True;
else
Result := False;
end;
end;
function TSynWebIDLSyn.GetSampleSource: UnicodeString;
begin
Result :=
'/* WEB IDL sample source */'#13#10 +
'[Constructor]'#13#10 +
'interface GraphicalWindow {'#13#10 +
' readonly attribute unsigned long width;'#13#10 +
' readonly attribute unsigned long height;'#13#10 +
#13#10 +
' attribute Paint currentPaint;'#13#10 +
#13#10 +
' void drawRectangle(float x, float y, float width, float height);' +
#13#10#13#10 +
' void drawText(float x, float y, DOMString text);'#13#10 +
'};';
end;
function TSynWebIDLSyn.IsFilterStored: Boolean;
begin
Result := fDefaultFilter <> SYNS_FilterWebIDL;
end;
class function TSynWebIDLSyn.GetFriendlyLanguageName: UnicodeString;
begin
Result := SYNS_FriendlyLangWebIDL;
end;
class function TSynWebIDLSyn.GetLanguageName: string;
begin
Result := SYNS_LangWebIDL;
end;
procedure TSynWebIDLSyn.ResetRange;
begin
fRange := rsUnknown;
end;
procedure TSynWebIDLSyn.SetRange(Value: Pointer);
begin
fRange := TRangeState(Value);
end;
function TSynWebIDLSyn.GetRange: Pointer;
begin
Result := Pointer(fRange);
end;
initialization
{$IFNDEF SYN_CPPB_1}
RegisterPlaceableHighlighter(TSynWebIDLSyn);
{$ENDIF}
end.
| 27.759771 | 102 | 0.692376 |
839aa7596883805c3cac80ee449ba59238ca2ea0 | 29,409 | pas | Pascal | Source/Source/Tools/LuaWorkshop/synedit/Source/SynHighlighterGWS.pas | uvbs/FullSource | 07601c5f18d243fb478735b7bdcb8955598b9a90 | [
"MIT"
]
| 2 | 2018-07-26T07:58:14.000Z | 2019-05-31T14:32:18.000Z | Jx3Full/Source/Source/Tools/LuaWorkshop/synedit/Source/SynHighlighterGWS.pas | RivenZoo/FullSource | cfd7fd7ad422fd2dae5d657a18839c91ff9521fd | [
"MIT"
]
| null | null | null | Jx3Full/Source/Source/Tools/LuaWorkshop/synedit/Source/SynHighlighterGWS.pas | RivenZoo/FullSource | cfd7fd7ad422fd2dae5d657a18839c91ff9521fd | [
"MIT"
]
| 5 | 2021-02-03T10:25:39.000Z | 2022-02-23T07:08:37.000Z | {-------------------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
the specific language governing rights and limitations under the License.
The Original Code is: SynHighlighterCpp.pas, released 2000-04-10.
The Original Code is based on the dcjCppSyn.pas file from the
mwEdit component suite by Martin Waldenburg and other developers, the Initial
Author of this file is Michael Trier.
All Rights Reserved.
Contributors to the SynEdit and mwEdit projects are listed in the
Contributors.txt file.
Alternatively, the contents of this file may be used under the terms of the
GNU General Public License Version 2 or later (the "GPL"), in which case
the provisions of the GPL are applicable instead of those above.
If you wish to allow use of your version of this file only under the terms
of the GPL and not to allow others to use your version of this file
under the MPL, indicate your decision by deleting the provisions above and
replace them with the notice and other provisions required by the GPL.
If you do not delete the provisions above, a recipient may use your version
of this file under either the MPL or the GPL.
$Id: SynHighlighterGWS.pas,v 1.1 2005/06/20 03:13:24 zhujianqiu Exp $
You may retrieve the latest version of this file at the SynEdit home page,
located at http://SynEdit.SourceForge.net
-------------------------------------------------------------------------------}
{$IFNDEF QSYNHIGHLIGHTERGWS}
unit SynHighlighterGWS;
{$ENDIF}
{ This unit provides a syntax highlighter for GW-TEL Scripts }
{$I SynEdit.inc}
interface
uses
{$IFDEF SYN_CLX}
QGraphics,
QSynEditTypes,
QSynEditHighlighter,
{$ELSE}
Graphics,
SynEditTypes,
SynEditHighlighter,
{$ENDIF}
SysUtils,
Classes;
Type
TtkTokenKind = (
tkComment,
tkIdentifier,
tkKey,
tkNull,
tkNumber,
tkSpace,
tkString,
tkSymbol,
tkUnknown);
TxtkTokenKind = (
xtkAdd, xtkAddAssign, xtkAnd, xtkAndAssign, xtkArrow, xtkAssign,
xtkBitComplement, xtkBraceClose, xtkBraceOpen, xtkColon, xtkComma,
xtkDecrement, xtkDivide, xtkDivideAssign, xtkEllipse, xtkGreaterThan,
xtkGreaterThanEqual, xtkIncOr, xtkIncOrAssign, xtkIncrement, xtkLessThan,
xtkLessThanEqual, xtkLogAnd, xtkLogComplement, xtkLogEqual, xtkLogOr,
xtkMod, xtkModAssign, xtkMultiplyAssign, xtkNotEqual, xtkPoint, xtkQuestion,
xtkRoundClose, xtkRoundOpen, xtkScopeResolution, xtkSemiColon, xtkShiftLeft,
xtkShiftLeftAssign, xtkShiftRight, xtkShiftRightAssign, xtkSquareClose,
xtkSquareOpen, xtkStar, xtkSubtract, xtkSubtractAssign, xtkXor,
xtkXorAssign);
TRangeState = (rsAnsiC, rsUnKnown);
TProcTableProc = procedure of Object;
PIdentFuncTableFunc = ^TIdentFuncTableFunc; //mh 1999-12-06
TIdentFuncTableFunc = function: TtkTokenKind of Object;
TSynGWScriptSyn = class(TSynCustomHighlighter)
private
fRange: TRangeState;
fLine: PChar;
fProcTable: array[#0..#255] of TProcTableProc;
Run: LongInt;
fStringLen: Integer;
fToIdent: PChar;
fTokenPos: Integer;
FTokenID: TtkTokenKind;
FExtTokenID: TxtkTokenKind;
fLineNumber: Integer;
fIdentFuncTable: array[0..206] of TIdentFuncTableFunc;
fCommentAttri: TSynHighlighterAttributes;
fIdentifierAttri: TSynHighlighterAttributes;
fInvalidAttri: TSynHighlighterAttributes;
fKeyAttri: TSynHighlighterAttributes;
fNumberAttri: TSynHighlighterAttributes;
fSpaceAttri: TSynHighlighterAttributes;
fStringAttri: TSynHighlighterAttributes;
fSymbolAttri: TSynHighlighterAttributes;
function KeyHash(ToHash: PChar): Integer;
function KeyComp(const aKey: String): Boolean;
function Func17: TtkTokenKind;
function Func21: TtkTokenKind;
function Func34: TtkTokenKind;
function Func42: TtkTokenKind;
function Func45: TtkTokenKind;
function Func46: TtkTokenKind;
function Func48: TtkTokenKind;
function Func62: TtkTokenKind;
function Func68: TtkTokenKind;
function Func93: TtkTokenKind;
function Func102: TtkTokenKind;
procedure AnsiCProc;
procedure AndSymbolProc;
procedure AsciiCharProc;
procedure AtSymbolProc;
procedure BraceCloseProc;
procedure BraceOpenProc;
procedure CRProc;
procedure ColonProc;
procedure CommaProc;
procedure EqualProc;
procedure GreaterProc;
procedure IdentProc;
procedure LFProc;
procedure LowerProc;
procedure MinusProc;
procedure ModSymbolProc;
procedure NotSymbolProc;
procedure NullProc;
procedure NumberProc;
procedure OrSymbolProc;
procedure PlusProc;
procedure PointProc;
procedure QuestionProc;
procedure RoundCloseProc;
procedure RoundOpenProc;
procedure SemiColonProc;
procedure SlashProc;
procedure SpaceProc;
procedure SquareCloseProc;
procedure SquareOpenProc;
procedure StarProc;
procedure StringProc;
procedure TildeProc;
procedure XOrSymbolProc;
procedure UnknownProc;
function AltFunc: TtkTokenKind;
procedure InitIdent;
function IdentKind(MayBe: PChar): TtkTokenKind;
procedure MakeMethodTables;
protected
function GetIdentChars: TSynIdentChars; override;
function GetExtTokenID: TxtkTokenKind;
public
constructor Create(AOwner: TComponent); override;
class function GetLanguageName: string; override;
function GetDefaultAttribute (Index: integer): TSynHighlighterAttributes; override;
function GetEol: Boolean; override;
function GetRange: Pointer; override;
function GetTokenID: TtkTokenKind;
procedure SetLine(NewValue: String; LineNumber:Integer); override;
function GetToken: String; override;
function GetTokenAttribute: TSynHighlighterAttributes; override;
function GetTokenKind: integer; override;
function GetTokenPos: Integer; override;
procedure Next; override;
procedure SetRange(Value: Pointer); override;
procedure ReSetRange; override;
property ExtTokenID: TxtkTokenKind read GetExtTokenID;
published
property CommentAttri: TSynHighlighterAttributes read fCommentAttri write fCommentAttri;
property IdentifierAttri: TSynHighlighterAttributes read fIdentifierAttri write fIdentifierAttri;
property InvalidAttri: TSynHighlighterAttributes read fInvalidAttri write fInvalidAttri;
property KeyAttri: TSynHighlighterAttributes read fKeyAttri write fKeyAttri;
property NumberAttri: TSynHighlighterAttributes read fNumberAttri write fNumberAttri;
property SpaceAttri: TSynHighlighterAttributes read fSpaceAttri write fSpaceAttri;
property StringAttri: TSynHighlighterAttributes read fStringAttri write fStringAttri;
property SymbolAttri: TSynHighlighterAttributes read fSymbolAttri write fSymbolAttri;
end;
implementation
uses
{$IFDEF SYN_CLX}
QSynEditStrConst;
{$ELSE}
SynEditStrConst;
{$ENDIF}
var
Identifiers: array[#0..#255] of ByteBool;
mHashTable: array[#0..#255] of Integer;
procedure MakeIdentTable;
var
I: Char;
begin
for I := #0 to #255 do
begin
Case I of
'_', '0'..'9', 'a'..'z', 'A'..'Z': Identifiers[I] := True;
else Identifiers[I] := False;
end;
Case I in['_', 'a'..'z', 'A'..'Z'] of
True:
begin
if (I > #64) and (I < #91) then mHashTable[I] := Ord(I) - 64 else
if (I > #96) then mHashTable[I] := Ord(I) - 95;
end;
else mHashTable[I] := 0;
end;
end;
end;
procedure TSynGWScriptSyn.InitIdent;
var
I: Integer;
{begin} //mh 1999-12-06
pF: PIdentFuncTableFunc;
begin
pF := PIdentFuncTableFunc(@fIdentFuncTable);
for I := Low(fIdentFuncTable) to High(fIdentFuncTable) do begin
pF^ := AltFunc;
Inc(pF);
end;
fIdentFuncTable[17] := Func17;
fIdentFuncTable[21] := Func21;
fIdentFuncTable[34] := Func34;
fIdentFuncTable[42] := Func42;
fIdentFuncTable[45] := Func45;
fIdentFuncTable[46] := Func46;
fIdentFuncTable[48] := Func48;
fIdentFuncTable[62] := Func62;
fIdentFuncTable[68] := Func68;
fIdentFuncTable[93] := Func93;
fIdentFuncTable[102] := Func102;
{end} //mh 1999-12-06
end;
function TSynGWScriptSyn.KeyHash(ToHash: PChar): Integer;
begin
Result := 0;
while ToHash^ in ['_', '0'..'9', 'a'..'z', 'A'..'Z'] do
begin
inc(Result, mHashTable[ToHash^]);
inc(ToHash);
end;
fStringLen := ToHash - fToIdent;
end; { KeyHash }
function TSynGWScriptSyn.KeyComp(const aKey: String): Boolean;
var
I: Integer;
Temp: PChar;
begin
Temp := fToIdent;
if Length(aKey) = fStringLen then
begin
Result := True;
for i := 1 to fStringLen do
begin
if Temp^ <> aKey[i] then
begin
Result := False;
break;
end;
inc(Temp);
end;
end else Result := False;
end; { KeyComp }
function TSynGWScriptSyn.Func17: TtkTokenKind;
begin
if KeyComp('if') then Result := tkKey else Result := tkIdentifier;
end;
function TSynGWScriptSyn.Func21: TtkTokenKind;
begin
if KeyComp('do') then Result := tkKey else Result := tkIdentifier;
end;
function TSynGWScriptSyn.Func34: TtkTokenKind;
begin
if KeyComp('char') then Result := tkKey else Result := tkIdentifier;
end;
function TSynGWScriptSyn.Func42: TtkTokenKind;
begin
if KeyComp('for') then Result := tkKey else
if KeyComp('break') then Result := tkKey else Result := tkIdentifier;
end;
function TSynGWScriptSyn.Func45: TtkTokenKind;
begin
if KeyComp('else') then Result := tkKey else Result := tkIdentifier;
end;
function TSynGWScriptSyn.Func46: TtkTokenKind;
begin
if KeyComp('int') then Result := tkKey else Result := tkIdentifier;
end;
function TSynGWScriptSyn.Func48: TtkTokenKind;
begin
if KeyComp('false') then Result := tkKey else
if KeyComp('bool') then Result := tkKey else Result := tkIdentifier;
end;
function TSynGWScriptSyn.Func62: TtkTokenKind;
begin
if KeyComp('while') then Result := tkKey else Result := tkIdentifier;
end;
function TSynGWScriptSyn.Func68: TtkTokenKind;
begin
if KeyComp('true') then Result := tkKey else Result := tkIdentifier;
end;
function TSynGWScriptSyn.Func93: TtkTokenKind;
begin
if KeyComp('string') then Result := tkKey else Result := tkIdentifier;
end;
function TSynGWScriptSyn.Func102: TtkTokenKind;
begin
if KeyComp('return') then Result := tkKey else Result := tkIdentifier;
end;
function TSynGWScriptSyn.AltFunc: TtkTokenKind;
begin
Result := tkIdentifier;
end;
function TSynGWScriptSyn.IdentKind(MayBe: PChar): TtkTokenKind;
var
HashKey: Integer;
begin
fToIdent := MayBe;
HashKey := KeyHash(MayBe);
if HashKey < 207 then Result := fIdentFuncTable[HashKey] else Result := tkIdentifier;
end;
procedure TSynGWScriptSyn.MakeMethodTables;
var
I: Char;
begin
for I := #0 to #255 do
case I of
'&': fProcTable[I] := AndSymbolProc;
#39: fProcTable[I] := AsciiCharProc;
'@': fProcTable[I] := AtSymbolProc;
'}': fProcTable[I] := BraceCloseProc;
'{': fProcTable[I] := BraceOpenProc;
#13: fProcTable[I] := CRProc;
':': fProcTable[I] := ColonProc;
',': fProcTable[I] := CommaProc;
'=': fProcTable[I] := EqualProc;
'>': fProcTable[I] := GreaterProc;
'?': fProcTable[I] := QuestionProc;
'A'..'Z', 'a'..'z', '_': fProcTable[I] := IdentProc;
#10: fProcTable[I] := LFProc;
'<': fProcTable[I] := LowerProc;
'-': fProcTable[I] := MinusProc;
'%': fProcTable[I] := ModSymbolProc;
'!': fProcTable[I] := NotSymbolProc;
#0: fProcTable[I] := NullProc;
'0'..'9': fProcTable[I] := NumberProc;
'|': fProcTable[I] := OrSymbolProc;
'+': fProcTable[I] := PlusProc;
'.': fProcTable[I] := PointProc;
')': fProcTable[I] := RoundCloseProc;
'(': fProcTable[I] := RoundOpenProc;
';': fProcTable[I] := SemiColonProc;
'/': fProcTable[I] := SlashProc;
#1..#9, #11, #12, #14..#32: fProcTable[I] := SpaceProc;
']': fProcTable[I] := SquareCloseProc;
'[': fProcTable[I] := SquareOpenProc;
'*': fProcTable[I] := StarProc;
#34: fProcTable[I] := StringProc;
'~': fProcTable[I] := TildeProc;
'^': fProcTable[I] := XOrSymbolProc;
else
fProcTable[I] := UnknownProc;
end;
end;
constructor TSynGWScriptSyn.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fCommentAttri := TSynHighlighterAttributes.Create(SYNS_AttrComment);
fCommentAttri.Style:= [fsItalic];
fIdentifierAttri := TSynHighlighterAttributes.Create(SYNS_AttrIdentifier);
fInvalidAttri := TSynHighlighterAttributes.Create(SYNS_AttrIllegalChar);
fKeyAttri := TSynHighlighterAttributes.Create(SYNS_AttrReservedWord);
fKeyAttri.Style:= [fsBold];
fNumberAttri := TSynHighlighterAttributes.Create(SYNS_AttrNumber);
fSpaceAttri := TSynHighlighterAttributes.Create(SYNS_AttrSpace);
fSpaceAttri.Foreground := clWindow;
fStringAttri := TSynHighlighterAttributes.Create(SYNS_AttrString);
fSymbolAttri := TSynHighlighterAttributes.Create(SYNS_AttrSymbol);
AddAttribute(fCommentAttri);
AddAttribute(fIdentifierAttri);
AddAttribute(fInvalidAttri);
AddAttribute(fKeyAttri);
AddAttribute(fNumberAttri);
AddAttribute(fSpaceAttri);
AddAttribute(fStringAttri);
AddAttribute(fSymbolAttri);
SetAttributesOnChange(DefHighlightChange);
InitIdent;
MakeMethodTables;
fRange := rsUnknown;
fDefaultFilter := SYNS_FilterGWS;
end; { Create }
procedure TSynGWScriptSyn.SetLine(NewValue: String; LineNumber:Integer);
begin
fLine := PChar(NewValue);
Run := 0;
fLineNumber := LineNumber;
Next;
end; { SetLine }
procedure TSynGWScriptSyn.AnsiCProc;
begin
fTokenID := tkComment;
case FLine[Run] of
#0:
begin
NullProc;
exit;
end;
#10:
begin
LFProc;
exit;
end;
#13:
begin
CRProc;
exit;
end;
end;
while FLine[Run] <> #0 do
case FLine[Run] of
'*':
if fLine[Run + 1] = '/' then begin
inc(Run, 2);
fRange := rsUnKnown;
break;
end else
inc(Run);
#10: break;
#13: break;
else inc(Run);
end;
end;
procedure TSynGWScriptSyn.AndSymbolProc;
begin
fTokenID := tkSymbol; //mh 1999-12-06
case FLine[Run + 1] of
'=': {and assign}
begin
inc(Run, 2);
FExtTokenID := xtkAndAssign;
end;
'&': {logical and}
begin
inc(Run, 2);
FExtTokenID := xtkLogAnd;
end;
else {and}
begin
inc(Run);
FExtTokenID := xtkAnd;
end;
end;
end;
procedure TSynGWScriptSyn.AsciiCharProc;
begin
fTokenID := tkString;
repeat
if fLine[Run] = '\' then begin
if fLine[Run + 1] in [#39, '\'] then
inc(Run);
end;
inc(Run);
until fLine[Run] in [#0, #10, #13, #39];
if fLine[Run] = #39 then
inc(Run);
end;
procedure TSynGWScriptSyn.AtSymbolProc;
begin
fTokenID := tkUnknown;
inc(Run);
end;
procedure TSynGWScriptSyn.BraceCloseProc;
begin
inc(Run);
fTokenId := tkSymbol;
FExtTokenID := xtkBraceClose;
fRange := rsUnknown;
end;
procedure TSynGWScriptSyn.BraceOpenProc;
begin
inc(Run);
fTokenId := tkSymbol;
FExtTokenID := xtkBraceOpen;
end;
procedure TSynGWScriptSyn.CRProc;
begin
fTokenID := tkSpace;
Inc(Run);
if fLine[Run + 1] = #10 then Inc(Run);
end;
procedure TSynGWScriptSyn.ColonProc;
begin
fTokenID := tkSymbol; //mh 1999-12-06
Case FLine[Run + 1] of
':': {scope resolution operator}
begin
inc(Run, 2);
FExtTokenID := xtkScopeResolution;
end;
else {colon}
begin
inc(Run);
FExtTokenID := xtkColon;
end;
end;
end;
procedure TSynGWScriptSyn.CommaProc;
begin
inc(Run);
fTokenID := tkSymbol;
FExtTokenID := xtkComma;
end;
procedure TSynGWScriptSyn.EqualProc;
begin
fTokenID := tkSymbol; //mh 1999-12-06
case FLine[Run + 1] of
'=': {logical equal}
begin
inc(Run, 2);
FExtTokenID := xtkLogEqual;
end;
else {assign}
begin
inc(Run);
FExtTokenID := xtkAssign;
end;
end;
end;
procedure TSynGWScriptSyn.GreaterProc;
begin
fTokenID := tkSymbol; //mh 1999-12-06
Case FLine[Run + 1] of
'=': {greater than or equal to}
begin
inc(Run, 2);
FExtTokenID := xtkGreaterThanEqual;
end;
'>':
begin
if FLine[Run + 2] = '=' then {shift right assign}
begin
inc(Run, 3);
FExtTokenID := xtkShiftRightAssign;
end
else {shift right}
begin
inc(Run, 2);
FExtTokenID := xtkShiftRight;
end;
end;
else {greater than}
begin
inc(Run);
FExtTokenID := xtkGreaterThan;
end;
end;
end;
procedure TSynGWScriptSyn.QuestionProc;
begin
fTokenID := tkSymbol; {conditional}
FExtTokenID := xtkQuestion;
inc(Run);
end;
procedure TSynGWScriptSyn.IdentProc;
begin
fTokenID := IdentKind((fLine + Run));
inc(Run, fStringLen);
while Identifiers[fLine[Run]] do inc(Run);
end;
procedure TSynGWScriptSyn.LFProc;
begin
fTokenID := tkSpace;
inc(Run);
end;
procedure TSynGWScriptSyn.LowerProc;
begin
fTokenID := tkSymbol; //mh 1999-12-06
case FLine[Run + 1] of
'=': {less than or equal to}
begin
inc(Run, 2);
FExtTokenID := xtkLessThanEqual;
end;
'<':
begin
if FLine[Run + 2] = '=' then {shift left assign}
begin
inc(Run, 3);
FExtTokenID := xtkShiftLeftAssign;
end
else {shift left}
begin
inc(Run, 2);
FExtTokenID := xtkShiftLeft;
end;
end;
else {less than}
begin
inc(Run);
FExtTokenID := xtkLessThan;
end;
end;
end;
procedure TSynGWScriptSyn.MinusProc;
begin
fTokenID := tkSymbol; //mh 1999-12-06
case FLine[Run + 1] of
'=': {subtract assign}
begin
inc(Run, 2);
FExtTokenID := xtkSubtractAssign;
end;
'-': {decrement}
begin
inc(Run, 2);
FExtTokenID := xtkDecrement;
end;
'>': {arrow}
begin
inc(Run, 2);
FExtTokenID := xtkArrow;
end;
else {subtract}
begin
inc(Run);
FExtTokenID := xtkSubtract;
end;
end;
end;
procedure TSynGWScriptSyn.ModSymbolProc;
begin
fTokenID := tkSymbol; //mh 1999-12-06
case FLine[Run + 1] of
'=': {mod assign}
begin
inc(Run, 2);
FExtTokenID := xtkModAssign;
end;
else {mod}
begin
inc(Run);
FExtTokenID := xtkMod;
end;
end;
end;
procedure TSynGWScriptSyn.NotSymbolProc;
begin
fTokenID := tkSymbol; //mh 1999-12-06
case FLine[Run + 1] of
'=': {not equal}
begin
inc(Run, 2);
FExtTokenID := xtkNotEqual;
end;
else {not}
begin
inc(Run);
FExtTokenID := xtkLogComplement;
end;
end;
end;
procedure TSynGWScriptSyn.NullProc;
begin
fTokenID := tkNull;
end;
procedure TSynGWScriptSyn.NumberProc;
begin
inc(Run);
fTokenID := tkNumber;
while FLine[Run] in
['0'..'9', 'A'..'F', 'a'..'f', '.', 'u', 'U', 'l', 'L', 'x', 'X'] do
begin
case FLine[Run] of
'.':
if FLine[Run + 1] = '.' then break;
end;
inc(Run);
end;
end;
procedure TSynGWScriptSyn.OrSymbolProc;
begin
fTokenID := tkSymbol; //mh 1999-12-06
case FLine[Run + 1] of
'=': {or assign}
begin
inc(Run, 2);
FExtTokenID := xtkIncOrAssign;
end;
'|': {logical or}
begin
inc(Run, 2);
FExtTokenID := xtkLogOr;
end;
else {or}
begin
inc(Run);
FExtTokenID := xtkIncOr;
end;
end;
end;
procedure TSynGWScriptSyn.PlusProc;
begin
fTokenID := tkSymbol; //mh 1999-12-06
case FLine[Run + 1] of
'=': {add assign}
begin
inc(Run, 2);
FExtTokenID := xtkAddAssign;
end;
'+': {increment}
begin
inc(Run, 2);
FExtTokenID := xtkIncrement;
end;
else {add}
begin
inc(Run);
FExtTokenID := xtkAdd;
end;
end;
end;
procedure TSynGWScriptSyn.PointProc;
begin
fTokenID := tkSymbol; //mh 1999-12-06
if (FLine[Run + 1] = '.') and (FLine[Run + 2] = '.') then
begin {ellipse}
inc(Run, 3);
FExtTokenID := xtkEllipse;
end
else {point}
begin
inc(Run);
FExtTokenID := xtkPoint;
end;
end;
procedure TSynGWScriptSyn.RoundCloseProc;
begin
inc(Run);
fTokenID := tkSymbol;
FExtTokenID := xtkRoundClose;
end;
procedure TSynGWScriptSyn.RoundOpenProc;
begin
inc(Run);
FTokenID := tkSymbol;
FExtTokenID := xtkRoundOpen;
end;
procedure TSynGWScriptSyn.SemiColonProc;
begin
inc(Run);
fTokenID := tkSymbol;
FExtTokenID := xtkSemiColon;
fRange := rsUnknown;
end;
procedure TSynGWScriptSyn.SlashProc;
begin
case FLine[Run + 1] of
'/': {c++ style comments}
begin
fTokenID := tkComment;
inc(Run, 2);
while not (fLine[Run] in [#0, #10, #13]) do Inc(Run);
end;
'*': {c style comments}
begin
fTokenID := tkComment;
fRange := rsAnsiC;
inc(Run, 2);
while fLine[Run] <> #0 do
case fLine[Run] of
'*':
if fLine[Run + 1] = '/' then
begin
inc(Run, 2);
fRange := rsUnKnown;
break;
end else inc(Run);
#10: break;
#13: break;
else inc(Run);
end;
end;
'=': {divide assign}
begin
inc(Run, 2);
fTokenID := tkSymbol;
FExtTokenID := xtkDivideAssign;
end;
else {divide}
begin
inc(Run);
fTokenID := tkSymbol;
FExtTokenID := xtkDivide;
end;
end;
end;
procedure TSynGWScriptSyn.SpaceProc;
begin
inc(Run);
fTokenID := tkSpace;
while FLine[Run] in [#1..#9, #11, #12, #14..#32] do inc(Run);
end;
procedure TSynGWScriptSyn.SquareCloseProc;
begin
inc(Run);
fTokenID := tkSymbol;
FExtTokenID := xtkSquareClose;
end;
procedure TSynGWScriptSyn.SquareOpenProc;
begin
inc(Run);
fTokenID := tkSymbol;
FExtTokenID := xtkSquareOpen;
end;
procedure TSynGWScriptSyn.StarProc;
begin
fTokenID := tkSymbol; //mh 1999-12-06
case FLine[Run + 1] of
'=': {multiply assign}
begin
inc(Run, 2);
FExtTokenID := xtkMultiplyAssign;
end;
else {star}
begin
inc(Run);
FExtTokenID := xtkStar;
end;
end;
end;
procedure TSynGWScriptSyn.StringProc;
begin
fTokenID := tkString;
if (FLine[Run + 1] = #34) and (FLine[Run + 2] = #34) then inc(Run, 2);
repeat
case FLine[Run] of
#0, #10, #13: break;
#92: {backslash}
case FLine[Run + 1] of
#34: inc(Run); {escaped quote doesn't count}
#92: inc(Run); {escaped backslash doesn't count}
end;
end;
inc(Run);
until FLine[Run] = #34;
if FLine[Run] <> #0 then inc(Run);
end;
procedure TSynGWScriptSyn.TildeProc;
begin
inc(Run); {bitwise complement}
fTokenId := tkSymbol;
FExtTokenID := xtkBitComplement;
end;
procedure TSynGWScriptSyn.XOrSymbolProc;
begin
fTokenID := tkSymbol; //mh 1999-12-06
Case FLine[Run + 1] of
'=': {xor assign}
begin
inc(Run, 2);
FExtTokenID := xtkXorAssign;
end;
else {xor}
begin
inc(Run);
FExtTokenID := xtkXor;
end;
end;
end;
procedure TSynGWScriptSyn.UnknownProc;
begin
{$IFDEF SYN_MBCSSUPPORT}
if FLine[Run] in LeadBytes then
Inc(Run,2)
else
{$ENDIF}
inc(Run);
fTokenID := tkUnknown;
end;
procedure TSynGWScriptSyn.Next;
begin
fTokenPos := Run;
case fRange of
rsAnsiC : AnsiCProc;
else
begin
fRange := rsUnknown;
fProcTable[fLine[Run]];
end;
end;
end;
function TSynGWScriptSyn.GetEol: Boolean;
begin
Result := fTokenID = tkNull;
end;
function TSynGWScriptSyn.GetRange: Pointer;
begin
Result := Pointer(fRange);
end;
function TSynGWScriptSyn.GetToken: String;
var
Len: LongInt;
begin
Len := Run - fTokenPos;
SetString(Result, (FLine + fTokenPos), Len);
end;
function TSynGWScriptSyn.GetTokenID: TtkTokenKind;
begin
Result := fTokenId;
end;
function TSynGWScriptSyn.GetExtTokenID: TxtkTokenKind;
begin
Result := FExtTokenID;
end;
function TSynGWScriptSyn.GetTokenAttribute: TSynHighlighterAttributes;
begin
case fTokenID of
tkComment: Result := fCommentAttri;
tkIdentifier: Result := fIdentifierAttri;
tkKey: Result := fKeyAttri;
tkNumber: Result := fNumberAttri;
tkSpace: Result := fSpaceAttri;
tkString: Result := fStringAttri;
tkSymbol: Result := fSymbolAttri;
tkUnknown: Result := fInvalidAttri;
else Result := nil;
end;
end;
function TSynGWScriptSyn.GetTokenKind: integer;
begin
Result := Ord(GetTokenID);
end;
function TSynGWScriptSyn.GetTokenPos: Integer;
begin
Result := fTokenPos;
end;
procedure TSynGWScriptSyn.ReSetRange;
begin
fRange:= rsUnknown;
end;
procedure TSynGWScriptSyn.SetRange(Value: Pointer);
begin
fRange := TRangeState(Value);
end;
function TSynGWScriptSyn.GetIdentChars: TSynIdentChars;
begin
Result := TSynValidStringChars;
end;
class function TSynGWScriptSyn.GetLanguageName: string;
begin
Result := SYNS_LangGWS;
end;
function TSynGWScriptSyn.GetDefaultAttribute (Index: integer): TSynHighlighterAttributes;
begin
case Index of
SYN_ATTR_COMMENT : Result := fCommentAttri;
SYN_ATTR_IDENTIFIER : Result := fIdentifierAttri;
SYN_ATTR_KEYWORD : Result := fKeyAttri;
SYN_ATTR_STRING : Result := fStringAttri;
SYN_ATTR_WHITESPACE : Result := fSpaceAttri;
SYN_ATTR_SYMBOL : Result := fSymbolAttri;
else
Result := nil;
end;
end;
initialization
MakeIdentTable;
{$IFNDEF SYN_CPPB_1}
RegisterPlaceableHighlighter (TSynGWScriptSyn);
{$ENDIF}
end.
| 27.433769 | 104 | 0.586011 |
f14799b2ebf27a4fa27b85f83d84e6320c8eeefd | 807 | pas | Pascal | Delphi/RAD Studio/Source Codes/Demos/MasterDetail/Unit2.pas | coderserdar/Documents | 4ff1d19dd898f9235dddb773d0eb5c869f679dc7 | [
"Apache-2.0"
]
| 2 | 2022-02-17T06:21:25.000Z | 2022-02-17T07:11:13.000Z | Delphi/RAD Studio/Source Codes/Demos/MasterDetail/Unit2.pas | coderserdar/Documents | 4ff1d19dd898f9235dddb773d0eb5c869f679dc7 | [
"Apache-2.0"
]
| null | null | null | Delphi/RAD Studio/Source Codes/Demos/MasterDetail/Unit2.pas | coderserdar/Documents | 4ff1d19dd898f9235dddb773d0eb5c869f679dc7 | [
"Apache-2.0"
]
| null | null | null | unit Unit2;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DBXInterBase, Data.FMTBcd,
Datasnap.DBClient, Datasnap.Provider, Vcl.Grids, Vcl.DBGrids, Data.DB,
Data.SqlExpr;
type
TForm2 = class(TForm)
EMPLOYEE: TSQLConnection;
EMPLOYEE1: TSQLDataSet;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
DataSetProvider1: TDataSetProvider;
ClientDataSet1: TClientDataSet;
EMPLOYEE_PROJECT: TSQLDataSet;
DataSetProvider2: TDataSetProvider;
DBGrid2: TDBGrid;
ClientDataSet2: TClientDataSet;
DataSource2: TDataSource;
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
{$R *.dfm}
end.
| 21.236842 | 98 | 0.733581 |
4754198dcfdbeda27e5d68b465b976ea35ec1b5a | 3,611 | pas | Pascal | dependencies/Indy10/OpenSSL/static/IdOpenSSLHeaders_whrlpool.pas | grahamegrieve/fhirserver | 28f69977bde75490adac663e31a3dd77bc016f7c | [
"BSD-3-Clause"
]
| 132 | 2015-02-02T00:22:40.000Z | 2021-08-11T12:08:08.000Z | dependencies/Indy10/OpenSSL/static/IdOpenSSLHeaders_whrlpool.pas | grahamegrieve/fhirserver | 28f69977bde75490adac663e31a3dd77bc016f7c | [
"BSD-3-Clause"
]
| 113 | 2015-03-20T01:55:20.000Z | 2021-10-08T16:15:28.000Z | dependencies/Indy10/OpenSSL/static/IdOpenSSLHeaders_whrlpool.pas | grahamegrieve/fhirserver | 28f69977bde75490adac663e31a3dd77bc016f7c | [
"BSD-3-Clause"
]
| 49 | 2015-04-11T14:59:43.000Z | 2021-03-30T10:29:18.000Z | {******************************************************************************}
{ }
{ Indy (Internet Direct) - Internet Protocols Simplified }
{ }
{ https://www.indyproject.org/ }
{ https://gitter.im/IndySockets/Indy }
{ }
{******************************************************************************}
{ }
{ This file is part of the Indy (Internet Direct) project, and is offered }
{ under the dual-licensing agreement described on the Indy website. }
{ (https://www.indyproject.org/license/) }
{ }
{ Copyright: }
{ (c) 1993-2020, Chad Z. Hower and the Indy Pit Crew. All rights reserved. }
{ }
{******************************************************************************}
{ }
{ Originally written by: Fabian S. Biehn }
{ fbiehn@aagon.com (German & English) }
{ }
{ Contributers: }
{ Here could be your name }
{ }
{******************************************************************************}
// This File is auto generated!
// Any change to this file should be made in the
// corresponding unit in the folder "intermediate"!
// Generation date: 28.10.2020 15:24:33
unit IdOpenSSLHeaders_whrlpool;
interface
// Headers for OpenSSL 1.1.1
// whrlpool.h
{$i IdCompilerDefines.inc}
uses
IdCTypes,
IdGlobal,
IdOpenSSLConsts;
const
WHIRLPOOL_DIGEST_LENGTH = 512 div 8;
WHIRLPOOL_BBLOCK = 512;
WHIRLPOOL_COUNTER = 256 div 8;
type
WHIRLPOOL_CTX_union = record
case Byte of
0: (c: array[0 .. WHIRLPOOL_DIGEST_LENGTH -1] of Byte);
(* double q is here to ensure 64-bit alignment *)
1: (q: array[0 .. (WHIRLPOOL_DIGEST_LENGTH div SizeOf(TIdC_DOUBLE)) -1] of TIdC_DOUBLE);
end;
WHIRLPOOL_CTX = record
H: WHIRLPOOL_CTX_union;
data: array[0 .. (WHIRLPOOL_BBLOCK div 8) -1] of Byte;
bitoff: TIdC_UINT;
bitlen: array[0 .. (WHIRLPOOL_COUNTER div SizeOf(TIdC_SIZET)) -1] of TIdC_SIZET;
end;
PWHIRLPOOL_CTX = ^WHIRLPOOL_CTX;
function WHIRLPOOL_Init(c: PWHIRLPOOL_CTX): TIdC_INT cdecl; external CLibCrypto;
function WHIRLPOOL_Update(c: PWHIRLPOOL_CTX; inp: Pointer; bytes: TIdC_SIZET): TIdC_INT cdecl; external CLibCrypto;
procedure WHIRLPOOL_BitUpdate(c: PWHIRLPOOL_CTX; inp: Pointer; bits: TIdC_SIZET) cdecl; external CLibCrypto;
function WHIRLPOOL_Final(md: PByte; c: PWHIRLPOOL_CTX): TIdC_INT cdecl; external CLibCrypto;
function WHIRLPOOL(inp: Pointer; bytes: TIdC_SIZET; md: PByte): PByte cdecl; external CLibCrypto;
implementation
end.
| 47.513158 | 118 | 0.41512 |
f190f2ef3a04dc19541c735927ac2ca4a729aff4 | 34,551 | pas | Pascal | msData.pas | noomox/dexif | 2c069a1b39db7e835852ad899c2200e604e0c41f | [
"FSFAP"
]
| 13 | 2016-10-21T14:18:48.000Z | 2021-06-27T18:00:50.000Z | msData.pas | noomox/dexif | 2c069a1b39db7e835852ad899c2200e604e0c41f | [
"FSFAP"
]
| 6 | 2016-12-04T17:55:38.000Z | 2021-01-29T02:08:32.000Z | msData.pas | noomox/dexif | 2c069a1b39db7e835852ad899c2200e604e0c41f | [
"FSFAP"
]
| 18 | 2016-04-16T00:20:25.000Z | 2022-03-15T19:49:07.000Z | unit msData;
////////////////////////////////////////////////////////////////////////////////
// msData.pas - Copyright 2001-2004, Gerry McGuire
//--------------------------------------------------------------------------
// msData - maker specific data as encoded in exif structures
// for use with Dexif module (Delphi EXIF).
//
// Gerry McGuire, March - April 7, 2001 - Initial Beta Release - 0.8
// Gerry McGuire, September 3, 2001 - Second Beta Release - 0.9
// Gerry McGuire, June 1, 2003 - First Release - 1.0
//
//--------------------------------------------------------------------------
//
// Add a new TTagEntry and "if..else" in ReadMsData to extend for
// other makers/models. This can be modified to read values instead
// from an external file to permit end-user tailoring of data.
//
// Results from these table scans shows up in msTraceStr field of
// tImageInfo structure (declared in dExif.pas)
//
// Information here was derived from the following document:
//
// www.butaman.ne.jp/~tsuruzoh/Computer/Digicams/exif-e.html
//
//--------------------------------------------------------------------------
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
{$I dExif.inc}
interface
uses
Sysutils, math,
dglobal, dEXIF, dIPTC;
type
TmsInfo = class // manufactorer specific
isTiff:boolean;
IMGparent:tImageInfo;
makerOffset:integer;
gblUCMaker:ansistring ;
function ReadMSData(var DR:TImageInfo):boolean;
constructor Create(tiffFlag:boolean; p:tImageInfo);
end;
////////////////////////////////
// More complex fields can be formatted with a
// callback function. Declare them here and insert
// the code in the implemenetation section.
function NikonLens(InStr: String): String;
function NikonColorMode(InStr: String): String;
function CanonExp1(InStr: String): String;
function CanonExp2(InStr: String): String;
function CanonCustom1(InStr: String): String;
const
Nikon1Table : array [0..10] of TTagEntry = (
(TID:0; TType:0; Tag:$0002; Count:1; Name:'FamilyID'; Desc:'FamilyID'),
(TID:0; TType:0; Tag:$0003; Count:1; Name:'Quality'; Desc:'Quality';
Code:'1:Vga Basic,2:Vga Normal,'+
'3:Vga Fine,4:SXGA Basic,5:SXGA Normal,6:SXGA Fine'+
'10:2 Mpixel Basic,11:2 Mpixel Normal,12:2 Mpixel Fine'),
(TID:0; TType:0; Tag:$0004; Count:1; Name:'ColorMode'; Desc:'ColorMode';
Code:'1:Color,2:Monochrome'),
(TID:0; TType:0; Tag:$0005; Count:1; Name:'ImageAdjustment'; Desc:'ImageAdjustment';
Code:'0:Normal,1:Bright+,2:Bright-,3:Contrast+,4:Contrast-'),
(TID:0; TType:0; Tag:$0006; Count:1; Name:'ISOSpeed'; Desc:'ISOSpeed';
Code:'0:ISO80,2:ISO160,4:ISO320,5:ISO100'),
(TID:0; TType:0; Tag:$0007; Count:1; Name:'WhiteBalance'; Desc:'WhiteBalance';
Code:'0:Auto,1:Preset,2:Daylight,3:Incandescense,4:Fluorescence,5:Cloudy,6:SpeedLight'),
(TID:0; TType:0; Tag:$0008; Count:1; Name:'Focus'; Desc:'Focus'),
(TID:0; TType:0; Tag:$0009; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$000A; Count:1; Name:'DigitalZoom'; Desc:'DigitalZoom'),
(TID:0; TType:0; Tag:$000B; Count:1; Name:'Converter'; Desc:'Converter';
Code:'0:Not used,1:Used'),
(TID:0; TType:0; Tag:$0F00; Count:1; Name:'Skip'; Desc:'Skip')
);
Nikon2Table : array [0..27] of TTagEntry = (
(TID:0; TType:0; Tag:$0001; Count:1; Name:'FamilyID'; Desc:'Family ID'),
(TID:0; TType:0; Tag:$0002; Count:1; Name:'ISOSpeed'; Desc:'ISO Speed'),
(TID:0; TType:0; Tag:$0003; Count:1; Name:'ColorMode'; Desc:'Color Mode'),
(TID:0; TType:0; Tag:$0004; Count:1; Name:'Quality'; Desc:'Quality'),
(TID:0; TType:0; Tag:$0005; Count:1; Name:'WhiteBalance'; Desc:'White Balance'),
(TID:0; TType:0; Tag:$0006; Count:1; Name:'ImageSharpening'; Desc:'Image Sharpening'),
(TID:0; TType:0; Tag:$0007; Count:1; Name:'FocusMode'; Desc:'Focus Mode'),
(TID:0; TType:0; Tag:$0008; Count:1; Name:'FlashSetting'; Desc:'Flash Setting'),
(TID:0; TType:0; Tag:$0009; Count:1; Name:'AutoFlashMode'; Desc:'Auto Flash Mode'),
(TID:0; TType:0; Tag:$000A; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$000B; Count:1; Name:'WhiteBiasValue'; Desc:'White Bias Value'),
(TID:0; TType:0; Tag:$000F; Count:1; Name:'DigitalZoom'; Desc:'Digital Zoom'),
(TID:0; TType:0; Tag:$0010; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$0011; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$0080; Count:1; Name:'ImageAdjustment'; Desc:'Image Adjustment'),
(TID:0; TType:0; Tag:$0081; Count:1; Name:'ImageAdjustment'; Desc:'Image Adjustment'),
(TID:0; TType:0; Tag:$0082; Count:1; Name:'Adapter'; Desc:'Adapter'),
(TID:0; TType:0; Tag:$0084; Count:1; Name:'LensInformation'; Desc:'Lens information';
Code:''; Data:''; Raw:''; FormatS:''; Size:0; CallBack:NikonLens),
(TID:0; TType:0; Tag:$0085; Count:1; Name:'ManualFocusDistance'; Desc:'Manual Focus Distance'),
(TID:0; TType:0; Tag:$0086; Count:1; Name:'DigitalZoom'; Desc:'Digital Zoom'),
(TID:0; TType:0; Tag:$0088; Count:1; Name:'FocusArea'; Desc:'Focus Area'),
(TID:0; TType:0; Tag:$0089; Count:1; Name:'Mode'; Desc:'Mode'),
(TID:0; TType:0; Tag:$008D; Count:1; Name:'ColorMode'; Desc:'Color Mode';
Code:''; Data:''; Raw:''; FormatS:''; Size:0; CallBack:NikonColorMode),
(TID:0; TType:0; Tag:$008F; Count:1; Name:'SceneMode'; Desc:'Scene Mode'),
(TID:0; TType:0; Tag:$0092; Count:1; Name:'HueAdjustment'; Desc:'Hue Adjustment'), // ??
(TID:0; TType:0; Tag:$0094; Count:1; Name:'Saturation'; Desc:'Saturation'),
(TID:0; TType:0; Tag:$0095; Count:1; Name:'NoiseReduction'; Desc:'Noise Reduction'),
(TID:0; TType:0; Tag:$0F00; Count:1; Name:'Skip'; Desc:'Skip')
);
Olympus1Table : array [0..32] of TTagEntry = (
(TID:0; TType:0; Tag:$0200; Count:1; Name:'SpecialMode'; Desc:'SpecialMode'),
(TID:0; TType:0; Tag:$0201; Count:1; Name:'JpegQual'; Desc:'JpegQual';
Code:'1:SQ,2:HQ,3:SHQ,4:Raw'),
(TID:0; TType:0; Tag:$0202; Count:1; Name:'Macro'; Desc:'Macro';
Code:'0=Normal,1:Macro;'),
(TID:0; TType:0; Tag:$0203; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$0204; Count:1; Name:'DigiZoom'; Desc:'Digital Zoom Ratio'),
(TID:0; TType:0; Tag:$0205; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$0206; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$0207; Count:1; Name:'Firmware'; Desc:'Firmware'),
(TID:0; TType:0; Tag:$0208; Count:1; Name:'PictInfo'; Desc:'Picture Info'),
(TID:0; TType:0; Tag:$0209; Count:1; Name:'CameraID'; Desc:'Camera ID'),
(TID:0; TType:0; Tag:$0F00; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$1004; Count:1; Name:'FlashMode'; Desc:'Flash Mode'),
(TID:0; TType:0; Tag:$1006; Count:1; Name:'Bracket' ; Desc:'Bracket'),
(TID:0; TType:0; Tag:$100B; Count:1; Name:'FocusMode'; Desc:'Focus Mode'),
(TID:0; TType:0; Tag:$100C; Count:1; Name:'FocusDistance'; Desc:'Focus Distance'),
(TID:0; TType:0; Tag:$100D; Count:1; Name:'Zoom'; Desc:'Zoom'),
(TID:0; TType:0; Tag:$100E; Count:1; Name:'MacroFocus'; Desc:'Macro Focus'),
(TID:0; TType:0; Tag:$100F; Count:1; Name:'Sharpness'; Desc:'Sharpness'),
(TID:0; TType:0; Tag:$1011; Count:1; Name:'ColorMatrix'; Desc:'Color Matrix'),
(TID:0; TType:0; Tag:$1012; Count:1; Name:'BlackLevel'; Desc:'Black Level'),
(TID:0; TType:0; Tag:$1015; Count:1; Name:'WhiteBalance'; Desc:'White Balance'),
(TID:0; TType:0; Tag:$1017; Count:1; Name:'RedBias'; Desc:'Red Bias'),
(TID:0; TType:0; Tag:$1018; Count:1; Name:'BlueBias'; Desc:'Blue Bias'),
(TID:0; TType:0; Tag:$101A; Count:1; Name:'SerialNumber'; Desc:'SerialNumber'),
(TID:0; TType:0; Tag:$1023; Count:1; Name:'FlashBias'; Desc:'Flash Bias'),
(TID:0; TType:0; Tag:$1029; Count:1; Name:'Contrast'; Desc:'Contrast'),
(TID:0; TType:0; Tag:$102A; Count:1; Name:'SharpnessFactor'; Desc:'Sharpness Factor'),
(TID:0; TType:0; Tag:$102B; Count:1; Name:'ColorControl'; Desc:'Color Control'),
(TID:0; TType:0; Tag:$102C; Count:1; Name:'ValidBits'; Desc:'Valid Bits'),
(TID:0; TType:0; Tag:$102D; Count:1; Name:'Coring'; Desc:'Coring Filter'),
(TID:0; TType:0; Tag:$102E; Count:1; Name:'FinalWidth'; Desc:'Final Width'),
(TID:0; TType:0; Tag:$102F; Count:1; Name:'FinalHeight'; Desc:'Final Height'),
(TID:0; TType:0; Tag:$1034; Count:1; Name:'CompressionRatio'; Desc:'Compression Ratio')
);
Casio1Table : array [0..25] of TTagEntry = (
(TID:0; TType:0; Tag:$0001; Count:1; Name:'RecordingMode'; Desc:'RecordingMode';
Code:'1:Single Shutter,2:Panorama,3:Night Scene,4:Portrait,5:Landscape'),
(TID:0; TType:0; Tag:$0002; Count:1; Name:'Quality'; Desc:'Quality';
Code:'1:Economy,2:Normal,3:Fine'),
(TID:0; TType:0; Tag:$0003; Count:1; Name:'FocusingMode'; Desc:'FocusingMode';
Code:'2:Macro,3:Auto Focus,4:Manual Focus,5:Infinity'),
(TID:0; TType:0; Tag:$0004; Count:1; Name:'FlashMode'; Desc:'FlashMode';
Code:'1:Auto,2:On,3:Off,4:Red Eye Reduction'),
(TID:0; TType:0; Tag:$0005; Count:1; Name:'FlashIntensity'; Desc:'FlashIntensity';
Code:'11:Weak,13:Normal,15:Strong'),
(TID:0; TType:0; Tag:$0006; Count:1; Name:'ObjectDistance'; Desc:'ObjectDistance'),
(TID:0; TType:0; Tag:$0007; Count:1; Name:'WhiteBalance'; Desc:'WhiteBalance';
Code:'1:Auto,2:Tungsten,3:Daylight,4:Fluorescent,5:Shade,129:Manual'),
(TID:0; TType:0; Tag:$0008; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$0009; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$000A; Count:1; Name:'DigitalZoom'; Desc:'DigitalZoom';
Code:'65536:Off,65537:2X Digital Zoom'),
(TID:0; TType:0; Tag:$000B; Count:1; Name:'Sharpness'; Desc:'Sharpness';
Code:'0:Normal,1:Soft,2:Hard'),
(TID:0; TType:0; Tag:$000C; Count:1; Name:'Contrast'; Desc:'Contrast';
Code:'0:Normal,1:Low,2:High'),
(TID:0; TType:0; Tag:$000D; Count:1; Name:'Saturation'; Desc:'Saturation';
Code:'0:Normal,1:Low,2:High'),
(TID:0; TType:0; Tag:$000E; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$000F; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$0010; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$0011; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$0012; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$0013; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$0014; Count:1; Name:'CCDSensitivity'; Desc:'CCDSensitivity';
Code:'64:Normal,125:+1.0,250:+2.0,244:+3.0,80:Normal,100:High'),
(TID:0; TType:0; Tag:$0015; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$0016; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$0017; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$0018; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$0019; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$001A; Count:1; Name:'Skip'; Desc:'Skip')
);
Casio2Table : array [0..44] of TTagEntry = (
(TID:0; TType:0; Tag:$0002; Count:1; Name:'ThumbnailDimensions'; Desc:'Thumbnail Dimensions'),
(TID:0; TType:0; Tag:$0003; Count:1; Name:'ThumbnailSize'; Desc:'Thumbnail Size'),
(TID:0; TType:0; Tag:$0004; Count:1; Name:'ThumbnailOffset'; Desc:'Thumbnail OffSet'),
(TID:0; TType:0; Tag:$0008; Count:1; Name:'Quality'; Desc:'Quality';
Code:'1:Fine,2:Super Fine'),
(TID:0; TType:0; Tag:$0009; Count:1; Name:'ImageSize'; Desc:'ImageSize';
Code:'0:640 x 480,4:1600 x 1200,5:2048 x 1536,20:2288 x 1712,'+
'21:2592 x 1944,22:2304 x 1728,36:3008 x 2008'),
(TID:0; TType:0; Tag:$000D; Count:1; Name:'FocusMode'; Desc:'FocusMode';
Code:'0:Normal,1:Macro'),
(TID:0; TType:0; Tag:$0014; Count:1; Name:'IsoSensitivity'; Desc:'IsoSensitivity';
Code:'3:50,4:64,6:100,9:200'),
(TID:0; TType:0; Tag:$0019; Count:1; Name:'WhiteBalance'; Desc:'WhiteBalance';
Code:'0:Auto,1:Daylight,2:Shade,3:Tungsten,4:Fluorescent,5:Manual'),
(TID:0; TType:0; Tag:$1D; Count:1; Name:'FocalLength'; Desc:'Focal Length (.1 mm)'),
(TID:0; TType:0; Tag:$001F; Count:1; Name:'Saturation'; Desc:'Saturation';
Code:'0:-1,1:Normal,2:+1'),
(TID:0; TType:0; Tag:$0020; Count:1; Name:'Contrast'; Desc:'Contrast';
Code:'0:-1,1:Normal,2:+1'),
(TID:0; TType:0; Tag:$0021; Count:1; Name:'Sharpness'; Desc:'Sharpness';
Code:'0:-1,1:Normal,2:+1'),
(TID:0; TType:0; Tag:$0E00; Count:1; Name:'PIM'; Desc:'Print Image Matching Info'),
// (TID:0; TType:0; Tag:$2000; Name:'CasioPreviewThumbnail'; Desc:'Casio Preview Thumbnail'),
(TID:0; TType:0; Tag:$2000; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$2001; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$2002; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$2003; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$2011; Count:1; Name:'WhiteBalanceBias'; Desc:'White Balance Bias'),
(TID:0; TType:0; Tag:$2013; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$2012; Count:1; Name:'WhiteBalance'; Desc:'White Balance';
Code:'0:Manual,1:Auto,4:Flash,12:Flash'),
(TID:0; TType:0; Tag:$2021; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$2022; Count:1; Name:'ObjectDistance'; Desc:'Object Distance (mm)'),
(TID:0; TType:0; Tag:$2023; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$2031; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$2032; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$2033; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$2034; Count:1; Name:'FlashDistance'; Desc:'Flash Distance'),
(TID:0; TType:0; Tag:$3000; Count:1; Name:'RecordMode'; Desc:'Record Mode';
Code:'2:Normal'),
(TID:0; TType:0; Tag:$3001; Count:1; Name:'SelfTimer'; Desc:'Self Timer';
Code:'0:Off,1:On'),
(TID:0; TType:0; Tag:$3002; Count:1; Name:'Quality'; Desc:'Quality';
Code:'1:Economy,2:Normal,3:Fine'),
(TID:0; TType:0; Tag:$3003; Count:1; Name:'FocusMode'; Desc:'Focus Mode';
Code:'1:Fixed,3:Auto Focus,6:Multi-Area Auto Focus'),
(TID:0; TType:0; Tag:$3005; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$3006; Count:1; Name:'TimeZone'; Desc:'Time Zone'),
(TID:0; TType:0; Tag:$3007; Count:1; Name:'BestshotMode'; Desc:'Bestshot Mode';
Code:'0:Off,1:On'),
(TID:0; TType:0; Tag:$3011; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$3012; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$3013; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$3014; Count:1; Name:'CCDSensitivity'; Desc:'CCD Sensitivity'),
(TID:0; TType:0; Tag:$3015; Count:1; Name:'ColorMode'; Desc:'Color Mode';
Code:'0:Off,1:On'),
(TID:0; TType:0; Tag:$3016; Count:1; Name:'Enhancement'; Desc:'Enhancement';
Code:'0:Off,1:On'),
(TID:0; TType:0; Tag:$3017; Count:1; Name:'Filter'; Desc:'Filter';
Code:'0:Off,1:On'),
(TID:0; TType:0; Tag:$3018; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$3019; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$301A; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$301B; Count:1; Name:'Skip'; Desc:'Skip')
);
Fuji1Table : array [0..17] of TTagEntry = (
(TID:0; TType:0; Tag:$0000; Count:1; Name:'Version'; Desc:'Version'; Code:''),
(TID:0; TType:0; Tag:$1000; Count:1; Name:'Quality'; Desc:'Quality'; Code:''),
(TID:0; TType:0; Tag:$1001; Count:1; Name:'Sharpness'; Desc:'Sharpness';
Code:'1:Soft,2:Soft,3:Normal,4:Hard,5:Hard'),
(TID:0; TType:0; Tag:$1002; Count:1; Name:'WhiteBalance'; Desc:'WhiteBalance';
Code:'0:Auto,256:Daylight,512:Cloudy,768:DaylightColor-fluorescence,'+
'769:DaywhiteColor-fluorescence,770:White-fluorescence,'+
'1024:Incandenscense,3840:Custom white balance.'),
(TID:0; TType:0; Tag:$1003; Count:1; Name:'Color'; Desc:'Color';
Code:'0:Normal,256:High,512:Low'),
(TID:0; TType:0; Tag:$1004; Count:1; Name:'Tone'; Desc:'Tone';
Code:'0:Normal,256:High,512:Low'),
(TID:0; TType:0; Tag:$1010; Count:1; Name:'FlashMode'; Desc:'FlashMode';
Code:'0:Auto,1:On,2:Off,3:Red-eye reduction'),
(TID:0; TType:0; Tag:$1011; Count:1; Name:'FlashStrength'; Desc:'FlashStrength'; Code:''),
(TID:0; TType:0; Tag:$1020; Count:1; Name:'Macro'; Desc:'Macro';
Code:'0:Off,1:On'),
(TID:0; TType:0; Tag:$1021; Count:1; Name:'Focusmode'; Desc:'Focusmode';
Code:'0:Auto Focus,1:Manual Focus'),
(TID:0; TType:0; Tag:$1030; Count:1; Name:'SlowSync'; Desc:'SlowSync';
Code:'0:Off,1:On'),
(TID:0; TType:0; Tag:$1031; Count:1; Name:'PictureMode'; Desc:'PictureMode';
Code:'0:Auto,1:Portrait scene,'+
'2:Landscape scene,4:Sports scene,5:Night scene,6:Program AE,'+
'256:Aperture prior AE,512:Shutter prior AE,768:Manual exposure'),
(TID:0; TType:0; Tag:$1032; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$1100; Count:1; Name:'ContTake/Bracket'; Desc:'ContTake/Bracket';
Code:'0:Off,1:On'),
(TID:0; TType:0; Tag:$1200; Count:1; Name:'Skip'; Desc:'Skip'; Code:''),
(TID:0; TType:0; Tag:$1300; Count:1; Name:'BlurWarning'; Desc:'BlurWarning';
Code:'0:No blur warning,1:Blur warning'),
(TID:0; TType:0; Tag:$1301; Count:1; Name:'FocusWarning'; Desc:'FocusWarning';
Code:'0:Auto Focus good,1:Out of focus'),
(TID:0; TType:0; Tag:$1302; Count:1; Name:'AEWarning'; Desc:'AEWarning';
Code:'0:AE good,1:Over exposure')
);
Canon1Table : array [0..15] of TTagEntry = (
(TID:0; TType:0; Tag:$00; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$01; Count:1; Name:'ExposureInfo1'; Desc:'ExposureInfo1';
Code:''; Data:''; Raw:''; FormatS:''; Size:0; CallBack:CanonExp1),
(TID:0; TType:0; Tag:$02; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$03; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$04; Count:1; Name:'ExposureInfo2'; Desc:'ExposureInfo2';
Code:''; Data:''; Raw:''; FormatS:''; Size:0; CallBack:CanonExp2),
(TID:0; TType:0; Tag:$06; Count:1; Name:'ImageType'; Desc:'ImageType'),
(TID:0; TType:0; Tag:$07; Count:1; Name:'FirmwareVersion'; Desc:'FirmwareVersion'),
(TID:0; TType:0; Tag:$08; Count:1; Name:'ImageNumber'; Desc:'ImageNumber'),
(TID:0; TType:0; Tag:$09; Count:1; Name:'OwnerName'; Desc:'OwnerName'),
(TID:0; TType:0; Tag:$0A; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$0B; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$0C; Count:1; Name:'CameraSerialNumber'; Desc:'CameraSerialNumber'),
(TID:0; TType:0; Tag:$0D; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$0E; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$0F; Count:1; Name:'CustomFunctions'; Desc:'CustomFunctions';
Code:''; Data:''; Raw:''; FormatS:''; Size:0; CallBack:CanonCustom1),
(TID:0; TType:0; Tag:$10; Count:1; Name:'Skip'; Desc:'Skip')
);
Epson1Table : array [0..11] of TTagEntry = ( //For Epson pc850Z Lucas P.
(TID:0; TType:0; Tag:$0200; Count:1; Name:'Special Mode'; Desc:'Special Mode'),
(TID:0; TType:0; Tag:$0201; Count:1; Name:'JpegQuality'; Desc:'JpegQuality'),
(TID:0; TType:0; Tag:$0202; Count:1; Name:'Macro'; Desc:'Macro'),
(TID:0; TType:0; Tag:$0203; Count:1; Name:'Skip'; Desc:'Skip'), // ??
(TID:0; TType:0; Tag:$0204; Count:1; Name:'DigiZoom'; Desc:'DigiZoom'),
(TID:0; TType:0; Tag:$0209; Count:1; Name:'CameraID'; Desc:'CameraID'),
(TID:0; TType:0; Tag:$020a; Count:1; Name:'Comments'; Desc:'Comments'),
(TID:0; TType:0; Tag:$020b; Count:1; Name:'Width'; Desc:'Width'),
(TID:0; TType:0; Tag:$020c; Count:1; Name:'Height'; Desc:'Height'),
(TID:0; TType:0; Tag:$020d; Count:1; Name:'SoftRelease'; Desc:'SoftRelease'),
(TID:0; TType:0; Tag:$0300; Count:1; Name:'??'; Desc:'??'), // ??
(TID:0; TType:0; Tag:$0f00; Count:1; Name:'skip'; Desc:'skip')
);
Sanyo1Table: array [0..5] of TTagEntry = (
(TID:0; TType:0; Tag:$0200; Count:1; Name:'Special Mode'; Desc:'Special Mode'),
(TID:0; TType:0; Tag:$0201; Count:1; Name:'JpegQuality'; Desc:'JpegQuality'),
(TID:0; TType:0; Tag:$0202; Count:1; Name:'Macro'; Desc:'Macro'),
(TID:0; TType:0; Tag:$0203; Count:1; Name:'Skip'; Desc:'Skip'),
(TID:0; TType:0; Tag:$0204; Count:1; Name:'DigiZoom'; Desc:'DigiZoom'),
(TID:0; TType:0; Tag:$0F00; Count:1; Name:'DataDump'; Desc:'DataDump')
);
MinoltaTable: array[0..1] of TTagEntry = (
(TID:0; TType:0; Tag:$0000; Count:1; Name:'ModelID'; Desc:'ModelID'),
(TID:0; TType:0; Tag:$0E00; Count:1; Name:'PIMdata'; Desc:'PIMdata')
);
implementation
uses
dUtils;
////////////////
// Callback Functions - one per field
//
// Ok, Ok, usually you'd have a parser do the
// work but hey - this is just a simple example
Function NikonColorMode(InStr: String): String;
begin
InStr := Copy(InStr, 2, 5);
Result := InStr;
if InStr = 'MODE1' then
Result := 'Mode1 (sRGB)'
else
if InStr = 'MODE2' then
Result := 'Mode 2 (Adobe RGB)'
else
if InStr = 'MODE3' then
Result := 'Mode 3 (sRGB): higher saturation'
end;
function NikonLens(InStr: String): String;
var
i,sl: Integer;
tb: Ansistring;
MaxSp,MinSp,MaxFL,MinFL:double;
begin
Result := InStr; // if error return input string
sl := Length(dExifDataSep);
i := Pos(dExifDataSep, InStr);
tb := Copy(InStr, 1, i-1); // get first irrational number
MinFL := CvtRational(tb); // bottom of lens speed range
InStr := Copy(InStr, i+sl-1, 64);
i := Pos(dExifDataSep, InStr);
tb := Copy(InStr, 1, i-1); // get second irrational number
MaxFL := CvtRational(tb); // top of lens speed range
InStr := Copy(InStr, i+sl-1, 64);
i := Pos(dExifDataSep, instr);
tb := copy(InStr, 1, i-1); // get third irrational number
MinSp := CvtRational(tb); // minimum focal length
InStr := Copy(InStr, i+sl-1, 64);
MaxSp := CvtRational(InStr); // maximum focal length
Result := Format('%0.1f-%0.1f mm F%0.1f-F%0.1f', [MinFl, MaxFl, MinSp, MaxSp]);
end;
type
strArray = array of ansistring;
function CustBld(fname:ansistring; item:integer; decodeStr:ansistring): ansistring;
var
valStr:ansistring;
begin
valStr := DecodeField(decodeStr, AnsiString(inttostr(item)));
if trim(string(valStr)) <> '' then
begin
curTagArray.AddMSTag(fname,valStr, FMT_STRING);
result := crlf + fname + dExifDelim + valStr;
end
else
result := '';
end;
Function CustNth(instr, fname:ansistring; item:integer): ansistring;
var
valStr:ansistring;
begin
valStr := StrNth(instr,DexifDecodeSep,item);
if trim(string(valStr)) <> '' then
begin
curTagArray.AddMSTag(fname,valStr, FMT_STRING);
result := crlf + fname + dExifDelim + valStr;
end
else
result := '';
end;
Function CustAPick(InStr, fname: AnsiString; AItem:integer; ADecodeStr:String): String;
var
valStr: String;
begin
valStr := aPick(InStr, AItem, ADecodeStr);
if Trim(valStr) <> '' then
begin
curTagArray.AddMSTag(fname, valStr, FMT_STRING);
Result := crlf + fname + dExifDelim + valStr;
end
else
result := '';
end;
const
CanonGen : string = '65535:Low,0:Normal,1:High';
CanonMacro : string = '1:Macro,2:Normal';
CanonCompress: string = '0:SuperFine,1:Fine,2:Normal,3:Basic,5:SuperFine';
CanonFlash : string = '0:Not fired,1:Auto,2:On,3:Red-eye,4:Slow sync,'+
'5:Auto+red-eye,6:On+red eye,16:External flash';
CanonDrive : string = '0:Single,1:Continuous';
CanonFocus : string = '0:One-Shot,1:AI Servo,2:AI Focus,3:MF,4:Single,'+
'5:Continuous,6:MF';
CanonSize : string = '0:Large,1:Medium,2:Small,4:5MPixel,5:2 MPixel,6:1.5 MPixel';
CanonEasy : string = '0:Full Auto,1:Manual,2:Landscape,3:Fast Shutter,'+
'4:Slow Shutter,5:Night,6:B&W,7:Sepia,8:Portrait,9:Sports,'+
'10:Macro/Close-Up,11:Pan Focus';
CanonISO : string = '0:Not used,15:auto,16:50,17:100,18:200,19:400';
CanonMeter : string = '3:Evaluative,4:Partial,5:Center-weighted';
CanonAF : string = '12288:None (MF),12289:Auto-selected,12290:Right,'+
'12291:Center,12292:Left';
CanonExpose : string = '0:Easy shooting,1:Program,2:Tv-priority,'+
'3:Av-priority,4:Manual,5:A-DEP';
CanonFocus2 : string = '0:Single,1:Continuous';
function CanonExp1(instr: String): String;
var
s: String;
begin
rawDefered := true;
// s := instr;
s := '';
s := s + CustAPick(instr, 'Macro mode' , 1, CanonMacro);
s := s + CustNth( instr, 'Self Timer' , 2);
s := s + CustAPick(instr, 'Compression Rate', 3, CanonCompress);
s := s + CustAPick(instr, 'Flash Mode' , 4, CanonFlash);
s := s + CustAPick(instr, 'Drive Mode' , 5, CanonDrive);
s := s + CustAPick(instr, 'Focus Mode' , 7, CanonFocus);
s := s + CustAPick(instr, 'Image Size' ,10, CanonSize);
s := s + CustAPick(instr, 'Easy Shoot' ,11, CanonEasy);
s := s + CustAPick(instr, 'Contrast' ,13, CanonGen);
s := s + CustAPick(instr, 'Saturation' ,14, CanonGen);
s := s + CustAPick(instr, 'Sharpness' ,15, CanonGen);
s := s + CustAPick(instr, 'CCD ISO' ,16, CanonISO);
s := s + CustAPick(instr, 'Metering Mode' ,17, CanonGen);
s := s + CustAPick(instr, 'AF Point' ,19, CanonGen);
s := s + CustAPick(instr, 'Exposure Mode' ,20, CanonGen);
s := s + CustNth( instr, 'Long focal' ,24);
s := s + CustNth( instr, 'Short focal' ,25);
s := s + CustNth( instr, 'Focal Units' ,26);
s := s + CustNth( instr, 'Flash Details' ,29);
s := s + CustAPick(instr, 'Focus Mode' ,32, CanonGen);
result := s;
end;
const
CanonWhite: String = '0:Auto,1:Sunny,2:Cloudy,3:Tungsten,4:Flourescent,'+
'5:Flash,6:Custom';
CanonBias: String = '65472:-2 EV,65484:-1.67 EV,65488:-1.50 EV,65492:-1.33 EV,'+
'65504:-1 EV,65516:-0.67 EV,65520:-0.50 EV,65524:-0.33 EV,'+
'0:0 EV,12:0.33 EV,16:0.50 EV,20:0.67 EV,'+
'32:1 EV,44:1.33 EV,48:1.50 EV,52:1.67 EV,'+
'64:2 EV';
function CanonExp2(InStr: String): String;
var
s: ansistring;
begin
rawDefered := true;
// s := instr;
s := '';
s := s+ CustAPick(instr,'White balance' , 7,CanonWhite);
s := s+ CustNth( instr,'Sequence Number' , 9);
s := s+ CustNth( instr,'OpticalZoom Step',11);
s := s+ CustNth( instr,'AF point' ,14);
s := s+ CustAPick(instr,'Flash bias' ,15,CanonBias);
s := s+ CustNth( instr,'Distance' ,19);
result := s;
end;
Const
CanonOpt1 : ansistring = '0:Disable,1:Enable';
CanonOpt2 : ansistring = '0:Enable,1:Disable';
CanonNR : ansistring = '0: Off,1: On';
CanonYR : ansistring = '0: On,1: Off';
CanonAEBtn : ansistring = '0:AF/AE lock,1:AE lock/AF,2:AF/AF lock,3:AE+release/AE+AF';
CanonExpLevel: ansistring = '0:1/2 stop,1:1/3 stop';
CanonAFassist: ansistring = '0:On (auto),1:Off';
CanonAvSpeed : ansistring = '0:Automatic,1: 1/200 (fixed)';
CanonAEB : ansistring = '0:0, -, + / Enabled1: 0, -, + / Disabled,'+
'2: -, 0, + / Enabled,3: -, 0, + / Disabled';
CanonSCS : ansistring = '0:1st-curtain sync,1: 2nd-curtain sync';
CanonAFBtn : ansistring = '0:AF stop,1:Operate AF,2:Lock AE and start timer';
CanonMenu : ansistring = '0:Top,1:Previous (volatile),2:Previous';
CanonSetBtn : ansistring = '0:Not assigned,1:Change quality,2:Change ISO speed,'+
'3:Select parameters';
Function CanonCustom1(InStr: String): String;
var
fn, s, r: String;
fnct, data, i, j: Integer;
begin
s := '';
rawDefered := true;
for i := 1 to StrCount(InStr, ',') do
begin
try
fn := StrNth(InStr, ',', i);
j := StrToInt(fn);
fnct := j div 256; // upper 8 bits
data := j mod 256; // Lower 8 bits
case fnct of
1: r := CustBld('Noise Reduction', data, CanonNR);
2: r := CustBld('Shutter AE Lock Button', data, CanonAEBtn);
3: r := CustBld('Mirror Lockup', data, CanonOpt1);
4: r := CustBld('Exposure Level', data, CanonExpLevel);
5: r := CustBld('AF Assist', data, CanonAFassist);
6: r := CustBld('AV Shutter Speed', data, CanonAvSpeed);
7: r := CustBld('AEB Sequence', data, CanonAEB);
8: r := CustBld('Shutter Sync', data, CanonSCS);
9: r := CustBld('Lens AF Button', data, CanonAFBtn);
10: r := CustBld('Fill Flash Reduction', data, CanonOpt2);
11: r := CustBld('Menu Return', data, CanonMenu);
12: r := CustBld('Set Button', data, CanonSetBtn);
13: r := CustBld('Sensor Cleaning', data, CanonOpt1);
14: r := CustBld('Superimposed Display', data, CanonYR);
15: r := CustBld('Shutter Release w/o CF Card', data, CanonOpt2);
else
continue; // unknown value;
end
except
end;
s := s + r;
end;
result := s;
end;
////////////////
// The key to the following function is the call into
// dEXIF's parser: ProcessHWSpecific
//
// The arguments are:
// MakerNote: a Delphi string containing the maker note data
// TagTable: TTagEntry containing tag entries
// Initial offset: Offset to directory
// Data offset: subtracted from the data offset for long data
// elements - typically contains the offset of the
// makernote field from the start of the file
//
constructor TmsInfo.Create(tiffFlag: boolean; p: TImageInfo);
begin
inherited Create; // Initialize inherited parts
isTiff := tiffFlag;
IMGparent := p;
makerOffset := p.MakerOffset;
end;
function TmsInfo.ReadMSData(var DR:TImageInfo):boolean;
var
UCMaker, tmp, tmp2: ansistring;
MMode: boolean;
x: integer;
begin
UCMaker := Copy(AnsiString(AnsiUpperCase(DR.CameraMake)),1,5);
gblUCMaker := '';
curTagArray := IMGparent;
result := true;
if isTiff then
MakerOffset := MakerOffset+16;
with DR do
begin
if (UCMaker = 'NIKON') then
begin
tmp := copy(MakerNote,1,5);
x := max(0,Pos(' ', imgParent.CameraModel));
tmp2 := imgParent.CameraModel[x+1];
if (imgParent.ExifVersion > '0210') or
((imgParent.ExifVersion = '') and
(tmp2 = 'D') and isTiff) then
ProcessHWSpecific(MakerNote,Nikon2Table,18,9)
else
if (tmp = 'Nikon')
then ProcessHWSpecific(MakerNote,Nikon1Table,8,MakerOffset)
else ProcessHWSpecific(MakerNote,Nikon2Table,0,MakerOffset-8);
end
else if (UCMaker = 'OLYMP') then
begin
ProcessHWSpecific(MakerNote,Olympus1Table,8,MakerOffset,9)
end
else if (UCMaker = 'CASIO') then
begin
if Pos('QVC', MakerNote) <> 1 then // newer style: unknown format
ProcessHWSpecific(MakerNote,Casio1Table,0,MakerOffset-8)
else
begin
ProcessHWSpecific(MakerNote,Casio2Table,6,MakerOffset-2)
end;
end
else if (UCMaker = 'FUJIF') then
begin
MMode := MotorolaOrder; // Fuji uses motorola format for exif
MotorolaOrder := false; // but not for MakerNote!!
ProcessHWSpecific(MakerNote,Fuji1Table,12,12+1);
MotorolaOrder := MMode;
end
else if (UCMaker = 'CANON') then
begin
ProcessHWSpecific(MakerNote,Canon1Table,0,MakerOffset-8)
end
else if (UCMaker = 'SEIKO') then
begin
ProcessHWSpecific(MakerNote,Epson1Table,8,MakerOffset)
end
else if (UCMaker = 'SANYO') then
begin
ProcessHWSpecific(MakerNote,Sanyo1Table,8,MakerOffset)
end
else if (UCMaker = 'MINOL') then
begin
ProcessHWSpecific(MakerNote,MinoltaTable,0,MakerOffset-8)
end
else
result := false; // not a recognized maker
end;
if result then
gblUCMaker := DR.CameraMake; //only if there's a match
end;
end.
| 51.415179 | 101 | 0.569101 |
f12b7c64de4e707f507b345b6bf1beb953621be2 | 514 | pas | Pascal | Source/Services/SimpleNotificationService/Base/Model/AWS.SNS.Model.DeleteTopicResponse.pas | herux/aws-sdk-delphi | 4ef36e5bfc536b1d9426f78095d8fda887f390b5 | [
"Apache-2.0"
]
| 67 | 2021-07-28T23:47:09.000Z | 2022-03-15T11:48:35.000Z | Source/Services/SimpleNotificationService/Base/Model/AWS.SNS.Model.DeleteTopicResponse.pas | gabrielbaltazar/aws-sdk-delphi | ea1713b227a49cbbc5a2e1bf04cbf2de1f9b611a | [
"Apache-2.0"
]
| 5 | 2021-09-01T09:31:16.000Z | 2022-03-16T18:19:21.000Z | Source/Services/SimpleNotificationService/Base/Model/AWS.SNS.Model.DeleteTopicResponse.pas | gabrielbaltazar/aws-sdk-delphi | ea1713b227a49cbbc5a2e1bf04cbf2de1f9b611a | [
"Apache-2.0"
]
| 13 | 2021-07-29T02:41:16.000Z | 2022-03-16T10:22:38.000Z | unit AWS.SNS.Model.DeleteTopicResponse;
interface
uses
AWS.Runtime.Model;
type
TDeleteTopicResponse = class;
IDeleteTopicResponse = interface(IAmazonWebServiceResponse)
function Obj: TDeleteTopicResponse;
end;
TDeleteTopicResponse = class(TAmazonWebServiceResponse, IDeleteTopicResponse)
strict protected
function Obj: TDeleteTopicResponse;
end;
implementation
{ TDeleteTopicResponse }
function TDeleteTopicResponse.Obj: TDeleteTopicResponse;
begin
Result := Self;
end;
end.
| 17.133333 | 79 | 0.785992 |
f11ea8be18e7e6d73e7270e75b43cb20e675669e | 2,914 | dfm | Pascal | server/mainsrvr.dfm | showcode/SimpleServer | b2a784f9e3c759eb07212eb2c714fa1c83307469 | [
"MIT"
]
| null | null | null | server/mainsrvr.dfm | showcode/SimpleServer | b2a784f9e3c759eb07212eb2c714fa1c83307469 | [
"MIT"
]
| null | null | null | server/mainsrvr.dfm | showcode/SimpleServer | b2a784f9e3c759eb07212eb2c714fa1c83307469 | [
"MIT"
]
| null | null | null | object MainForm: TMainForm
Left = 771
Top = 310
BorderIcons = [biSystemMenu]
BorderStyle = bsToolWindow
Caption = 'Server Info'
ClientHeight = 347
ClientWidth = 362
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
Position = poDesktopCenter
OnCloseQuery = FormCloseQuery
OnCreate = FormCreate
OnDestroy = FormDestroy
PixelsPerInch = 96
TextHeight = 13
object PageControl: TPageControl
Left = 0
Top = 0
Width = 362
Height = 306
ActivePage = tsLog
Align = alClient
TabOrder = 1
object tsLog: TTabSheet
Caption = 'Statistic'
ImageIndex = 1
object mLog: TMemo
Left = 3
Top = 63
Width = 345
Height = 209
Anchors = [akLeft, akTop, akBottom]
ScrollBars = ssBoth
TabOrder = 1
WordWrap = False
end
object pnlStatistic: TPanel
Left = 3
Top = 3
Width = 345
Height = 54
BevelInner = bvLowered
TabOrder = 0
object lblMaxConnects: TLabel
Left = 128
Top = 27
Width = 18
Height = 13
Caption = '000'
end
object lblCurrConnects: TLabel
Left = 128
Top = 8
Width = 18
Height = 13
Caption = '000'
end
object Label1: TLabel
Left = 11
Top = 8
Width = 99
Height = 13
Caption = 'Current Connections'
end
object Label2: TLabel
Left = 11
Top = 27
Width = 106
Height = 13
Caption = 'Maximum Connections'
end
object btnStatClear: TButton
Left = 256
Top = 8
Width = 75
Height = 33
Caption = 'Clear'
TabOrder = 0
OnClick = btnStatClearClick
end
end
end
end
object pnlButtons: TPanel
Left = 0
Top = 306
Width = 362
Height = 41
Align = alBottom
TabOrder = 0
object btnHide: TButton
Left = 277
Top = 6
Width = 75
Height = 25
Caption = 'Hide'
Default = True
ModalResult = 1
TabOrder = 0
OnClick = btnHideClick
end
end
object pmTrayMenu: TPopupMenu
OnPopup = pmTrayMenuPopup
Left = 108
Top = 146
object pmiShutdown: TMenuItem
Caption = 'Shutdown'
OnClick = pmiShutdownClick
end
object pmiProperties: TMenuItem
Caption = 'Properties'
OnClick = pmiPropertiesClick
end
object pmiViewLog: TMenuItem
Caption = 'View Log'
Default = True
OnClick = pmiViewLogClick
end
end
end
| 22.765625 | 44 | 0.526081 |
f1e7c4195725a399138192ee611094f7da03b6a2 | 1,977 | pas | Pascal | AppPedido/CamadaNegocio/ServerContainerUnit1.pas | lucianojec/ViaSoft | 3e9995cc64d428f11e64d05b4f55e68dffe313f9 | [
"MIT"
]
| null | null | null | AppPedido/CamadaNegocio/ServerContainerUnit1.pas | lucianojec/ViaSoft | 3e9995cc64d428f11e64d05b4f55e68dffe313f9 | [
"MIT"
]
| null | null | null | AppPedido/CamadaNegocio/ServerContainerUnit1.pas | lucianojec/ViaSoft | 3e9995cc64d428f11e64d05b4f55e68dffe313f9 | [
"MIT"
]
| null | null | null | unit ServerContainerUnit1;
interface
uses System.SysUtils, System.Classes,
Datasnap.DSTCPServerTransport,
Datasnap.DSServer, Datasnap.DSCommonServer,
IPPeerServer, IPPeerAPI, Datasnap.DSAuth;
type
TServerContainer1 = class(TDataModule)
DSServer1: TDSServer;
DSTCPServerTransport1: TDSTCPServerTransport;
DSAuthenticationManager1: TDSAuthenticationManager;
DSServerClass1: TDSServerClass;
procedure DSServerClass1GetClass(DSServerClass: TDSServerClass;
var PersistentClass: TPersistentClass);
procedure DSAuthenticationManager1UserAuthorize(Sender: TObject;
EventObject: TDSAuthorizeEventObject; var valid: Boolean);
procedure DSAuthenticationManager1UserAuthenticate(Sender: TObject;
const Protocol, Context, User, Password: string; var valid: Boolean;
UserRoles: TStrings);
private
{ Private declarations }
public
end;
var
ServerContainer1: TServerContainer1;
implementation
{$R *.dfm}
uses
ServerMethodsUnit1;
procedure TServerContainer1.DSServerClass1GetClass(
DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass);
begin
PersistentClass := ServerMethodsUnit1.TServerMethods1;
end;
procedure TServerContainer1.DSAuthenticationManager1UserAuthenticate(
Sender: TObject; const Protocol, Context, User, Password: string;
var valid: Boolean; UserRoles: TStrings);
begin
{ TODO : Validate the client user and password.
If role-based authorization is needed, add role names to the UserRoles parameter }
valid := True;
end;
procedure TServerContainer1.DSAuthenticationManager1UserAuthorize(
Sender: TObject; EventObject: TDSAuthorizeEventObject;
var valid: Boolean);
begin
{ TODO : Authorize a user to execute a method.
Use values from EventObject such as UserName, UserRoles, AuthorizedRoles and DeniedRoles.
Use DSAuthenticationManager1.Roles to define Authorized and Denied roles
for particular server methods. }
valid := True;
end;
end.
| 29.507463 | 93 | 0.789074 |
f1dfe559d0e34af8d4fbe482e227d8bfea6c3f14 | 6,291 | pas | Pascal | windows/src/developer/TIKE/project/Keyman.Developer.UI.Project.UfrmNewProject.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 219 | 2017-06-21T03:37:03.000Z | 2022-03-27T12:09:28.000Z | windows/src/developer/TIKE/project/Keyman.Developer.UI.Project.UfrmNewProject.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 4,451 | 2017-05-29T02:52:06.000Z | 2022-03-31T23:53:23.000Z | windows/src/developer/TIKE/project/Keyman.Developer.UI.Project.UfrmNewProject.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 72 | 2017-05-26T04:08:37.000Z | 2022-03-03T10:26:20.000Z | (*
Name: UfrmNew
Copyright: Copyright (C) SIL International.
Documentation:
Description:
Create Date: 20 Jun 2006
Modified Date: 10 Aug 2015
Authors: mcdurdin
Related Files:
Dependencies:
Bugs:
Todo:
Notes:
History: 20 Jun 2006 - mcdurdin - Initial version
23 Aug 2006 - mcdurdin - Include 'add to project' checkbox
23 Aug 2006 - mcdurdin - Refactor to encourage naming file on creation rather than later
14 Sep 2006 - mcdurdin - Fix selection of items in list view
28 Sep 2006 - mcdurdin - Require a non-blank file name for the target
04 Dec 2006 - mcdurdin - Add default ext
04 Dec 2006 - mcdurdin - Rework file types listed
04 Jan 2007 - mcdurdin - Hide branding and distribution if branding pack not activated
14 Jun 2008 - mcdurdin - I1420 - Save as .htm
18 May 2012 - mcdurdin - I3306 - V9.0 - Remove TntControls + Win9x support
24 Jul 2015 - mcdurdin - I4796 - Refresh Keyman Developer look and feel for release
24 Jul 2015 - mcdurdin - I4798 - Split Path and Name boxes in New File dialogs
03 Aug 2015 - mcdurdin - I4821 - Update icons for version 9.0 in New File dialog
10 Aug 2015 - mcdurdin - I4852 - Create directories when creating new file
*)
unit Keyman.Developer.UI.Project.UfrmNewProject; // I3306 // I4796 // I4798
interface
uses
System.Classes,
System.ImageList,
System.SysUtils,
System.UITypes,
Vcl.ComCtrls,
Vcl.Controls,
Vcl.Dialogs,
Vcl.Forms,
Vcl.Graphics,
Vcl.ImgList,
Vcl.StdCtrls,
Winapi.Messages,
Winapi.Windows,
utilfiletypes,
UfrmTike;
type
TfrmNewProject = class(TTikeForm)
lvItems: TListView;
cmdOK: TButton;
cmdCancel: TButton;
ilLarge: TImageList;
ilSmall: TImageList;
lblDescription: TLabel;
procedure FormCreate(Sender: TObject);
procedure lvItemsDblClick(Sender: TObject);
procedure lvItemsSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
private
procedure EnableControls;
function GetProjectType: TKeymanProjectType;
procedure UpdateDescription;
protected
function GetHelpTopic: string; override;
public
property ProjectType: TKeymanProjectType read GetProjectType;
end;
function ShowNewProjectForm(Owner: TComponent): Boolean;
implementation
uses
Keyman.Developer.System.HelpTopics,
Keyman.Developer.System.Project.Project,
Keyman.Developer.System.Project.ProjectFile,
Keyman.Developer.UI.Project.ProjectUI,
Keyman.Developer.UI.Project.UfrmNewProjectParameters,
Keyman.Developer.UI.Project.UfrmNewModelProjectParameters,
Keyman.Developer.UI.ImportWindowsKeyboardDialogManager,
dmActionsMain,
utilsystem;
function ShowNewProjectForm(Owner: TComponent): Boolean;
var
p: TfrmNewProject;
pt: TKeymanProjectType;
begin
Result := False;
p := TfrmNewProject.Create(Owner);
try
if p.ShowModal = mrCancel then
Exit;
pt := p.ProjectType;
finally
p.Free;
end;
case pt of
kptUnknown:
Assert(False, 'Should not be able to have a project type of unknown here');
kptBasic:
Result := ShowNewProjectParameters(Owner);
kptWordlistLexicalModel:
Result := ShowNewModelProjectParameters(Owner);
kptBlankLexicalModel:
begin
modActionsMain.NewProject(ptLexicalModel);
Result := True;
end;
kptBlank:
begin
modActionsMain.NewProject(ptKeyboard);
Result := True;
end;
kptImportWindowsKeyboard:
Result := ShowImportWindowsKeyboard(Owner);
end;
end;
{$R *.DFM}
procedure TfrmNewProject.EnableControls;
var
e: Boolean;
begin
e := Assigned(lvItems.Selected);
cmdOK.Enabled := e;
end;
procedure TfrmNewProject.FormCreate(Sender: TObject);
begin
inherited;
lvItems.Selected := lvItems.Items[0];
lvItems.ItemFocused := lvItems.Items[0];
UpdateDescription;
EnableControls;
end;
function TfrmNewProject.GetProjectType: TKeymanProjectType;
begin
// Overly wordy but clarifies that we may have other types later
if not Assigned(lvItems.Selected) then
Result := kptUnknown
else if lvItems.Selected.Caption = 'Basic' then
Result := kptBasic
else if lvItems.Selected.Caption = 'Blank' then
Result := kptBlank
else if lvItems.Selected.Caption = 'Import Windows Keyboard' then
Result := kptImportWindowsKeyboard
else if lvItems.Selected.Caption = 'Blank Lexical Model' then
Result := kptBlankLexicalModel
else if lvItems.Selected.Caption = 'Wordlist Lexical Model' then
Result := kptWordlistLexicalModel
else
Result := kptUnknown;
end;
function TfrmNewProject.GetHelpTopic: string;
begin
Result := SHelpTopic_Context_NewProject;
end;
procedure TfrmNewProject.lvItemsDblClick(Sender: TObject);
begin
if cmdOK.Enabled then
cmdOK.Click;
end;
procedure TfrmNewProject.lvItemsSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
begin
UpdateDescription;
EnableControls;
end;
procedure TfrmNewProject.UpdateDescription;
begin
case ProjectType of
kptUnknown: lblDescription.Caption := '';
kptBasic: lblDescription.Caption :=
'Creates a keyboard project that matches the folder structure used in '+
'the Keyman keyboards repository and includes all basic files '+
'needed for a keyboard project.';
kptBlank: lblDescription.Caption :=
'Creates a blank, untitled keyboard project.';
kptImportWindowsKeyboard: lblDescription.Caption :=
'Creates a new keyboard project, importing from a Windows system keyboard '+
'and generating all the basic files needed for a keyboard project.';
kptBlankLexicalModel: lblDescription.Caption :=
'Creates a blank, untitled lexical model project.';
kptWordlistLexicalModel: lblDescription.Caption :=
'Creates a new lexical model project that matches the folder structure used in '+
'the Keyman lexical-models repository and includes all basic files '+
'needed for a wordlist lexical model.';
end;
end;
end.
| 30.245192 | 108 | 0.694961 |
477c2c0638a413b8bc62619e0963ed0017f9d963 | 3,878 | pas | Pascal | ProjectModelosMixtosConsola/UnitEstructura.pas | abarto/capstone-project-mixed-models | a687dc4a2b77e80b9c54a350639fc8d417d9792d | [
"MIT"
]
| null | null | null | ProjectModelosMixtosConsola/UnitEstructura.pas | abarto/capstone-project-mixed-models | a687dc4a2b77e80b9c54a350639fc8d417d9792d | [
"MIT"
]
| null | null | null | ProjectModelosMixtosConsola/UnitEstructura.pas | abarto/capstone-project-mixed-models | a687dc4a2b77e80b9c54a350639fc8d417d9792d | [
"MIT"
]
| null | null | null | {**
@abstract(Estructuras de varianza/covarianza.)
@author(Agustin Barto <abarto@gmail.com>)
@created(January 1, 2003)
@lastmod(December 27, 2004)
Este modulo contiene la definicion de estructuras de varianza y covarianza.
}
unit UnitEstructura;
interface
uses
Classes;
type
{** Definicion de estructura generica, sin orden.
@abstract(Definicion de estructura.) }
TEstructura = class
protected
{** Nombre de la estructura. }
FNombre: String;
{** Metodo de lectura de la propiedad @link(Texto). Devuelve la
representacion de cadena de caracteres de la estructura.
@returns(Representacion de cadena de caracteres de la estructura.) }
function GetTexto: String; virtual;
public
{** Constructor.
@param(ANombre Nombre de la estructura.) }
constructor Create(ANombre: String);
{** Valida la estructura.
@param(Bitacora Registro de posibles errores y advertencias producidas
durante el proceso de validacion.)
@returns(@true si la estructura es valida, o @false en caso
contrario.) }
function Validar(var Bitacora: TStrings): Boolean; virtual;
{** Nombre de la estructura. }
property Nombre: String read FNombre write FNombre;
{** Representacion de cadenadde caracteres de la estructura. }
property Texto: String read GetTexto;
end { TEstructura };
{** Definicion de estructura con parametro de orden.
@abstract(Definicion de estructura con parametro de orden.) }
TEstructuraOrden = class(TEstructura)
protected
{** Orden de la estructura. }
FOrden: Integer;
{** Ver @link(TEstructura.GetTexto). }
function GetTexto: String; override;
public
{** Constructor.
@param(ANombre Nombre de la estructura.)
@param(AOrden Parametro de orden.) }
constructor Create(ANombre: String; AOrden: Integer);
{** Ver @link(TEstructura.Validar). }
function Validar(var Bitacora: TStrings): Boolean; override;
{** Orden de la estructura. }
property Orden: Integer read FOrden write FOrden;
end { TEstructuraOrden };
implementation
uses
SysUtils;
// -----------------------------------------------------------------------------
// TEstructura
// -----------------------------------------------------------------------------
function TEstructura.GetTexto: String;
begin { TEstructura.GetTexto }
Result := FNombre;
end { TEstructura.GetTexto };
constructor TEstructura.Create(ANombre: String);
begin { TEstructura.Create }
Assert(ANombre <> '', 'TEstructura.Create: ''''');
FNombre := ANombre;
end { TEstructura.Create };
function TEstructura.Validar(var Bitacora: TStrings): Boolean;
begin { TEstructura.Validar }
Assert(Assigned(Bitacora), 'TEstructura.Validar: Assigned(Bitacora)');
Result := true;
end { TEstructura.Validar };
// -----------------------------------------------------------------------------
// TEstructuraOrden
// -----------------------------------------------------------------------------
function TEstructuraOrden.GetTexto: String;
begin { TEstructuraOrden.GetTexto }
Result := FNombre + '[' + IntToStr(FOrden) + ']';
end { TEstructuraOrden.GetTexto };
constructor TEstructuraOrden.Create(ANombre: String; AOrden: Integer);
begin { TEstructuraOrden.Create }
inherited Create(ANombre);
FOrden := AOrden;
end { TEstructuraOrden.Create };
function TEstructuraOrden.Validar(var Bitacora: TStrings): Boolean;
begin { TEstructuraOrden.Validar }
Assert(Assigned(Bitacora), 'TEstructuraOrden.Validar: Assigned(Bitacora)');
Result := true;
if FOrden <= 0 then
begin
Bitacora.Add('Numero de orden de estructura invalido: ' + IntToStr(FOrden));
Result := false;
end;
end { TEstructuraOrden.Validar };
end { UnitEstructura }.
| 32.864407 | 81 | 0.630995 |
47212e1f29655ac356f7ebf704ddf9367d8794b8 | 2,285 | pas | Pascal | Source/TextEditor.LeftMargin.MarksPanel.pas | ImperiumDelphi/TTextEditor | 823b171ceb6c3d5e914622479a2ad607634eb645 | [
"MIT"
]
| null | null | null | Source/TextEditor.LeftMargin.MarksPanel.pas | ImperiumDelphi/TTextEditor | 823b171ceb6c3d5e914622479a2ad607634eb645 | [
"MIT"
]
| null | null | null | Source/TextEditor.LeftMargin.MarksPanel.pas | ImperiumDelphi/TTextEditor | 823b171ceb6c3d5e914622479a2ad607634eb645 | [
"MIT"
]
| 1 | 2021-11-16T17:04:56.000Z | 2021-11-16T17:04:56.000Z | unit TextEditor.LeftMargin.MarksPanel;
interface
uses
System.Classes, Vcl.Graphics, TextEditor.Types;
type
TTextEditorLeftMarginMarksPanel = class(TPersistent)
strict private
FOnChange: TNotifyEvent;
FOptions: TTextEditorLeftMarginBookmarkPanelOptions;
FVisible: Boolean;
FWidth: Integer;
procedure DoChange;
procedure SetWidth(const AValue: Integer);
procedure SetVisible(const AValue: Boolean);
public
constructor Create;
procedure Assign(ASource: TPersistent); override;
procedure ChangeScale(const AMultiplier, ADivider: Integer);
property OnChange: TNotifyEvent read FOnChange write FOnChange;
published
property Options: TTextEditorLeftMarginBookmarkPanelOptions read FOptions write FOptions default [bpoToggleBookmarkByClick];
property Visible: Boolean read FVisible write SetVisible default True;
property Width: Integer read FWidth write SetWidth default 20;
end;
implementation
uses
Winapi.Windows, System.Math;
constructor TTextEditorLeftMarginMarksPanel.Create;
begin
inherited;
FWidth := 20;
FOptions := [bpoToggleBookmarkByClick];
FVisible := True;
end;
procedure TTextEditorLeftMarginMarksPanel.Assign(ASource: TPersistent);
begin
if Assigned(ASource) and (ASource is TTextEditorLeftMarginMarksPanel) then
with ASource as TTextEditorLeftMarginMarksPanel do
begin
Self.FVisible := FVisible;
Self.FWidth := FWidth;
if Assigned(Self.FOnChange) then
Self.FOnChange(Self);
end
else
inherited Assign(ASource);
end;
procedure TTextEditorLeftMarginMarksPanel.ChangeScale(const AMultiplier, ADivider: Integer);
var
LNumerator: Integer;
begin
LNumerator := (AMultiplier div ADivider) * ADivider;
FWidth := MulDiv(FWidth, LNumerator, ADivider);
end;
procedure TTextEditorLeftMarginMarksPanel.DoChange;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TTextEditorLeftMarginMarksPanel.SetWidth(const AValue: Integer);
var
LValue: Integer;
begin
LValue := Max(0, AValue);
if FWidth <> LValue then
begin
FWidth := LValue;
DoChange
end;
end;
procedure TTextEditorLeftMarginMarksPanel.SetVisible(const AValue: Boolean);
begin
if FVisible <> AValue then
begin
FVisible := AValue;
DoChange
end;
end;
end.
| 24.569892 | 128 | 0.76849 |
834cc45d380256bf816d5d264b5a2bb2c4e476d9 | 789 | pas | Pascal | unit2.pas | goHighMarketing/CT-Pic-Grabber | 2a3351dd3033350b86d94caf46dfdd71abbc8d7e | [
"CC0-1.0"
]
| null | null | null | unit2.pas | goHighMarketing/CT-Pic-Grabber | 2a3351dd3033350b86d94caf46dfdd71abbc8d7e | [
"CC0-1.0"
]
| null | null | null | unit2.pas | goHighMarketing/CT-Pic-Grabber | 2a3351dd3033350b86d94caf46dfdd71abbc8d7e | [
"CC0-1.0"
]
| null | null | null | unit Unit2;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls,
fileinfo, winpeimagereader, elfreader, machoreader;
type
{ TForm2 }
TForm2 = class(TForm)
Image1: TImage;
Label1: TLabel;
LabelVersion: TLabel;
Panel1: TPanel;
StaticText1: TStaticText;
procedure FormCreate(Sender: TObject);
private
public
end;
var
Form2: TForm2;
implementation
{$R *.frm}
{ TForm2 }
procedure TForm2.FormCreate(Sender: TObject);
var
FileVerInfo: TFileVersionInfo;
begin
FileVerInfo:= TFileVersionInfo.Create(nil);
try
FileVerInfo.ReadFileInfo;
LabelVersion.Caption:= 'Version: ' + FileVerInfo.VersionStrings.Values['FileVersion'];
finally
FileVerInfo.Free;
end;
end;
end.
| 15.173077 | 90 | 0.707224 |
8314b8f056b672aae9f72062385ebe813e32a8a1 | 239 | pas | Pascal | examples/c18.pas | AHalic/Pascal-Compiler | 6513ac14f7cc6c800dd74e7641906b005e24e340 | [
"MIT"
]
| null | null | null | examples/c18.pas | AHalic/Pascal-Compiler | 6513ac14f7cc6c800dd74e7641906b005e24e340 | [
"MIT"
]
| null | null | null | examples/c18.pas | AHalic/Pascal-Compiler | 6513ac14f7cc6c800dd74e7641906b005e24e340 | [
"MIT"
]
| null | null | null | program Arrays3;
var
a: integer;
b: integer;
c: integer;
numeros: array[1..20, 2..4, 1..10] of integer;
begin
a := 1;
b := 2;
c := 3;
numeros[1, 2, 3] := 23;
a := numeros[a, b, c];
writeln(a);
end.
| 14.9375 | 50 | 0.481172 |
f1739312b85df2b91424c1717bae6837480aa307 | 5,891 | pas | Pascal | windows/src/ext/jedi/jcl/jcl/experts/common/JclOtaExceptionForm.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 219 | 2017-06-21T03:37:03.000Z | 2022-03-27T12:09:28.000Z | windows/src/ext/jedi/jcl/jcl/experts/common/JclOtaExceptionForm.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 4,451 | 2017-05-29T02:52:06.000Z | 2022-03-31T23:53:23.000Z | windows/src/ext/jedi/jcl/jcl/experts/common/JclOtaExceptionForm.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 72 | 2017-05-26T04:08:37.000Z | 2022-03-03T10:26:20.000Z | {**************************************************************************************************}
{ }
{ Project JEDI Code Library (JCL) }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); }
{ you may not use this file except in compliance with the License. You may obtain a copy of the }
{ License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF }
{ ANY KIND, either express or implied. See the License for the specific language governing rights }
{ and limitations under the License. }
{ }
{ The Original Code is JclOtExceptionForm.pas. }
{ }
{ The Initial Developer of the Original Code is Florent Ouchet }
{ [outchy att users dott sourceforge dott net] }
{ Portions created by Florent Ouchet are Copyright (C) of Florent Ouchet. }
{ }
{**************************************************************************************************}
{ }
{ Last modified: $Date:: $ }
{ Revision: $Rev:: $ }
{ Author: $Author:: $ }
{ }
{**************************************************************************************************}
unit JclOtaExceptionForm;
interface
{$I jcl.inc}
{$I crossplatform.inc}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
JclOtaUtils;
type
TJclExpertExceptionForm = class(TForm)
MemoDetails: TMemo;
LabelURL: TLabel;
MemoCallStack: TMemo;
ButtonClose: TButton;
procedure LabelURLClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
protected
procedure CreateParams(var Params: TCreateParams); override;
public
procedure ShowException(AExceptionObj: TObject);
function Execute: Boolean;
end;
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$URL$';
Revision: '$Revision$';
Date: '$Date$';
LogPath: 'JCL\experts\common';
Extra: '';
Data: nil
);
{$ENDIF UNITVERSIONING}
implementation
{$R *.dfm}
uses
TypInfo, ShellApi,
{$IFDEF MSWINDOWS}
JclDebug,
{$ENDIF MSWINDOWS}
JclOtaResources;
procedure TJclExpertExceptionForm.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
// Fixing the Window Ghosting "bug"
Params.Style := params.Style or WS_POPUP;
if Assigned(Screen.ActiveForm) then
Params.WndParent := Screen.ActiveForm.Handle
else if Assigned (Application.MainForm) then
Params.WndParent := Application.MainForm.Handle
else
Params.WndParent := Application.Handle;
end;
function TJclExpertExceptionForm.Execute: Boolean;
begin
Result := ShowModal = mrOk;
end;
procedure TJclExpertExceptionForm.FormCreate(Sender: TObject);
begin
Caption := LoadResString(@RsReportFormCaption);
MemoDetails.Lines.Text := LoadResString(@RsExceptionDetails);
LabelURL.Caption := LoadResString(@RsReportCaption);
ButtonClose.Caption := LoadResString(@RsReportClose);
end;
procedure TJclExpertExceptionForm.LabelURLClick(Sender: TObject);
begin
ShellExecute(Handle, 'open', PChar(LoadResString(@RsReportURL)), '', '', SW_SHOW); // do not localize
end;
procedure TJclExpertExceptionForm.ShowException(AExceptionObj: TObject);
var
AStackInfoList: TJclStackInfoList;
AJclExpertException: EJclExpertException;
begin
MemoCallStack.Lines.Clear;
try
if Assigned(AExceptionObj) then
MemoCallStack.Lines.Add(Format(LoadResString(@RsDetailsExceptionName), [AExceptionObj.ClassName]));
if AExceptionObj is Exception then
begin
MemoCallStack.Lines.Add(Format(LoadResString(@RsDetailsExceptionMessage), [Exception(AExceptionObj).Message]));
if (AExceptionObj is EJclExpertException) then
begin
AJclExpertException := EJclExpertException(AExceptionObj);
if Assigned(AJclExpertException.StackInfo) then
begin
AJclExpertException.StackInfo.AddToStrings(MemoCallStack.Lines, True, True, True, True);
Exit;
end;
end;
end;
AStackInfoList := JclCreateStackList(True, 0, nil, False);
try
AStackInfoList.AddToStrings(MemoCallStack.Lines, True, True, True, True);
finally
AStackInfoList.Free;
end;
except
MemoCallStack.Lines.Add(LoadResString(@RsErrorWhileFormatting));
end;
end;
{$IFDEF UNITVERSIONING}
initialization
RegisterUnitVersion(HInstance, UnitVersioning);
finalization
UnregisterUnitVersion(HInstance);
{$ENDIF UNITVERSIONING}
end.
| 37.762821 | 117 | 0.526905 |
f18bcd93580592aa1a3c0185676453b35bcf28c1 | 27,948 | pas | Pascal | fpcdws/dwsRTTIExposer.pas | noshbar/c_dwscript | c2df9341a9f22d2974d1235f3968a4a3d9f3b32a | [
"Condor-1.1"
]
| 4 | 2018-09-18T07:35:52.000Z | 2021-02-18T18:21:54.000Z | fpcdws/dwsRTTIExposer.pas | noshbar/c_dwscript | c2df9341a9f22d2974d1235f3968a4a3d9f3b32a | [
"Condor-1.1"
]
| null | null | null | fpcdws/dwsRTTIExposer.pas | noshbar/c_dwscript | c2df9341a9f22d2974d1235f3968a4a3d9f3b32a | [
"Condor-1.1"
]
| 1 | 2020-10-30T07:24:05.000Z | 2020-10-30T07:24:05.000Z | {**********************************************************************}
{ }
{ "The contents of this file are subject to the Mozilla Public }
{ License Version 1.1 (the "License"); you may not use this }
{ file except in compliance with the License. You may obtain }
{ a copy of the License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an }
{ "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express }
{ or implied. See the License for the specific language }
{ governing rights and limitations under the License. }
{ }
{ Copyright Creative IT. }
{ Current maintainer: Eric Grange }
{ }
{**********************************************************************}
unit dwsRTTIExposer;
{$I dws.inc}
interface
uses
Classes, SysUtils, RTTI, TypInfo,
dwsXPlatform, dwsStrings,
dwsComp, dwsSymbols, dwsExprs, dwsStack;
type
TdwsRTTIExposerOption = (
eoExposeVirtual, eoNoFreeOnCleanup, eoExposePublic
);
TdwsRTTIExposerOptions = set of TdwsRTTIExposerOption;
{$RTTI EXPLICIT METHODS([vcPublic, vcPublished]) PROPERTIES([vcPublic, vcPublished])}
// TdwsPublished
//
dwsPublished = class (TCustomAttribute)
private
FNameOverride : String;
public
constructor Create(const nameOverride : String); overload;
property NameOverride : String read FNameOverride;
class function NameOf(item : TRttiNamedObject) : String; static;
end;
// TdwsNotPublished
//
dwsNotPublished = class (TCustomAttribute)
end;
{$RTTI EXPLICIT METHODS([]) PROPERTIES([]) FIELDS([])}
// TdwsRTTIExposer
//
TdwsRTTIExposer = class helper for TdwsUnit
protected
class var vRTTIContext : TRttiContext;
function ExposeRTTIClass(cls : TRttiInstanceType;
const options : TdwsRTTIExposerOptions) : TdwsClass;
function ExposeRTTIConstructor(meth : TRttiMethod; scriptClass : TdwsClass;
const options : TdwsRTTIExposerOptions) : TdwsConstructor;
function ExposeRTTIMethod(meth : TRttiMethod; scriptClass : TdwsClass;
const options : TdwsRTTIExposerOptions) : TdwsMethod;
function ExposeRTTIProperty(prop : TRttiProperty; scriptClass : TdwsClass;
const options : TdwsRTTIExposerOptions) : TdwsProperty;
function ExposeRTTIParameter(param : TRttiParameter; scriptParameters : TdwsParameters;
const options : TdwsRTTIExposerOptions) : TdwsParameter;
function ExposeRTTIEnumeration(enum : TRttiEnumerationType;
const options : TdwsRTTIExposerOptions) : TdwsEnumeration;
function ExposeRTTIRecord(rec : TRttiRecordType;
const options : TdwsRTTIExposerOptions) : TdwsRecord;
function ExposeRTTIInterface(intf : TRttiInterfaceType;
const options : TdwsRTTIExposerOptions) : TdwsInterface;
function ExposeRTTIDynamicArray(intf : TRttiDynamicArrayType;
const options : TdwsRTTIExposerOptions) : TdwsArray;
procedure DoStandardCleanUp(externalObject: TObject);
public
function ExposeRTTI(ATypeInfo : Pointer; const options : TdwsRTTIExposerOptions = []) : TdwsSymbol;
class function RTTITypeToScriptType(const aType : TRTTIType) : String; static;
class function RTTIVisibilityToVisibility(const aVisibility : TMemberVisibility) : TdwsVisibility; static;
end;
TdwsRTTIInvoker = class;
TdwsRTTIHelper = class;
// TdwsRTTIHelper
//
{: Helper to wraps a Delphi side object to DWS based on RTTI data. }
TdwsRTTIHelper = class
private
FInstanceType : TRttiInstanceType;
FInstanceConstructor : TRttiMethod;
FInvokers : array of TdwsRTTIInvoker;
public
constructor Create(anInstanceType : TRttiInstanceType);
destructor Destroy; override;
procedure AddInvoker(invoker : TdwsRTTIInvoker);
procedure DoStandardCreate(info: TProgramInfo; var extObject: TObject);
end;
// TdwsRTTIInvoker
//
{: Invokes a Delphi method from a DWS context. }
TdwsRTTIInvoker = class
private
FHelper : TdwsRTTIHelper;
public
procedure Invoke(info : TProgramInfo; externalObject : TObject); virtual; abstract;
property Helper : TdwsRTTIHelper read FHelper;
class procedure AssignIInfoFromValue(const info : IInfo; const value : TValue;
asType : TRttiType); static;
class procedure AssignRecordFromValue(const recInfo : IInfo; const value : TValue;
asType : TRttiType); static;
class function ValueFromParam(progInfo : TProgramInfo; const paramName : String;
asType : TRttiType) : TValue; static;
class function ValueFromIInfo(asType : TRttiType; const info : IInfo) : TValue; static;
class function ValueFromRecord(asType : TRttiType; const recInfo : IInfo) : TValue; static;
end;
// TdwsRTTIMethodInvoker
//
{: Invokes a Delphi method from a DWS context. }
TdwsRTTIMethodInvoker = class (TdwsRTTIInvoker)
private
FMethod : TRttiMethod; // referred, not owned
FTypParams : array of TRttiType;
FNameParams : array of String;
FVarParams : array of Integer;
FTypResult : TRttiType;
protected
procedure Initialize(aMethod : TRttiMethod);
public
constructor Create(aMethod : TRttiMethod);
procedure PrepareParams(info : TProgramInfo; var params : TArray<TValue>);
procedure Invoke(info : TProgramInfo; externalObject : TObject); override;
end;
// TdwsRTTIConstructorInvoker
//
TdwsRTTIConstructorInvoker = class (TdwsRTTIMethodInvoker)
public
procedure InvokeConstructor(info: TProgramInfo; var extObject: TObject);
end;
// TdwsRTTIPropertyInvoker
//
TdwsRTTIPropertyInvoker = class (TdwsRTTIInvoker)
protected
FProperty : TRttiProperty; // referred, not owned
FTyp : TRttiType;
procedure Initialize(aProperty : TRttiProperty);
public
constructor Create(aProperty : TRttiProperty);
end;
// TdwsRTTISetterInvoker
//
TdwsRTTISetterInvoker = class (TdwsRTTIPropertyInvoker)
public
procedure Invoke(info : TProgramInfo; externalObject : TObject); override;
end;
// TdwsRTTIGetterInvoker
//
TdwsRTTIGetterInvoker = class (TdwsRTTIPropertyInvoker)
public
procedure Invoke(info : TProgramInfo; externalObject : TObject); override;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
const
cTYPEKIND_NAMES: array[TTypeKind] of string = (
'Unknown', 'Integer', 'Char', 'Enumeration', 'Float',
'String', 'Set', 'Class', 'Method', 'WChar', 'LString', 'WString',
'Variant', 'Array', 'Record', 'Interface', 'Int64', 'DynArray', 'UString',
'ClassRef', 'Pointer', 'Procedure');
// ------------------
// ------------------ dwsPublished ------------------
// ------------------
// Create
//
constructor dwsPublished.Create(const nameOverride : String);
begin
FNameOverride:=nameOverride;
end;
// NameOf
//
class function dwsPublished.NameOf(item : TRttiNamedObject) : String;
var
attrib : TCustomAttribute;
begin
Result:='';
for attrib in item.GetAttributes do begin
if attrib.ClassType=dwsPublished then
Result:=dwsPublished(attrib).NameOverride;
end;
if Result='' then
Result:=item.Name;
end;
// ------------------
// ------------------ TdwsRTTIHelper ------------------
// ------------------
// Create
//
constructor TdwsRTTIHelper.Create(anInstanceType : TRttiInstanceType);
var
meth : TRttiMethod;
begin
inherited Create;
FInstanceType:=anInstanceType;
for meth in anInstanceType.GetMethods do begin
if (meth.MethodKind=TypInfo.mkConstructor)
and ASCIISameText(meth.Name, 'Create')
and (Length(meth.GetParameters)=0) then begin
FInstanceConstructor:=meth;
Break;
end;
end;
end;
// Destroy
//
destructor TdwsRTTIHelper.Destroy;
var
invoker : TdwsRTTIInvoker;
begin
for invoker in FInvokers do
invoker.Free;
inherited;
end;
// AddInvoker
//
procedure TdwsRTTIHelper.AddInvoker(invoker : TdwsRTTIInvoker);
var
n : Integer;
begin
n:=Length(FInvokers);
SetLength(FInvokers, n+1);
FInvokers[n]:=invoker;
invoker.FHelper:=Self;
end;
// DoStandardCreate
//
procedure TdwsRTTIHelper.DoStandardCreate(info: TProgramInfo; var extObject: TObject);
begin
extObject:=FInstanceConstructor.Invoke(FInstanceType.MetaclassType, []).AsObject;
end;
// ------------------
// ------------------ TdwsRTTIExposer ------------------
// ------------------
// ExposeRTTI
//
function TdwsRTTIExposer.ExposeRTTI(ATypeInfo : Pointer; const options : TdwsRTTIExposerOptions = []) : TdwsSymbol;
var
typ : TRttiType;
begin
typ:=vRTTIContext.GetType(ATypeInfo);
if typ is TRttiInstanceType then
Result:=ExposeRTTIClass(TRttiInstanceType(typ), options)
else if typ is TRttiEnumerationType then
Result:=ExposeRTTIEnumeration(TRttiEnumerationType(typ), options)
else if typ is TRttiRecordType then
Result:=ExposeRTTIRecord(TRttiRecordType(typ), options)
else if typ is TRttiInterfaceType then
Result:=ExposeRTTIInterface(TRttiInterfaceType(typ), options)
else if typ is TRttiDynamicArrayType then
Result := ExposeRTTIDynamicArray(TRttiDynamicArrayType(typ), options)
else raise Exception.CreateFmt('Expose unsupported for %s', [typ.ClassName]);
end;
// RTTITypeToScriptType
//
class function TdwsRTTIExposer.RTTITypeToScriptType(const aType : TRTTIType) : String;
var
LDynType: string;
LTypeKind: TTypeKind;
begin
if aType<>nil then begin
case aType.TypeKind of
tkInteger, tkInt64 :
Result := SYS_INTEGER;
tkChar, tkString, tkUString, tkWChar, tkLString, tkWString :
Result := SYS_STRING;
tkFloat :
Result := SYS_FLOAT;
tkVariant :
Result := SYS_VARIANT;
tkRecord :
Result:=dwsPublished.NameOf(aType);
tkSet, tkProcedure, tkPointer, {tkDynArray, }tkInterface, tkArray,
tkEnumeration, tkClassRef, tkClass, tkMethod : begin
Result := SYS_VARIANT; // todo, someday maybe...
end;
tkUnknown : begin
Result := SYS_VARIANT; // unsupported
Assert(False);
end;
tkDynArray: begin
LTypeKind := TRttiDynamicArrayType( aType ).ElementType.TypeKind;
// we want to raise exception if the tpe is not expected
case LTypeKind of
tkInteger, tkInt64:
LDynType := SYS_INTEGER;
tkChar, tkString, tkUString, tkWChar, tkLString, tkWString:
LDynType := SYS_STRING;
tkFloat:
LDynType := SYS_FLOAT;
tkVariant:
LDynType := SYS_VARIANT;
else
raise Exception.Create(
'Cannot handle this dynamic array RTTI type, maybe you haven''t exposed type"' + atype.name + '" yet?');
end;
// set the type, we expect that the type is already exposed
Result := aType.Name;
end
else
Result := SYS_VARIANT;
Assert(False);
end;
end else Result:='';
end;
// RTTIVisibilityToVisibility
//
class function TdwsRTTIExposer.RTTIVisibilityToVisibility(const aVisibility : TMemberVisibility) : TdwsVisibility;
const
cVisibilityMap : array [TMemberVisibility] of TdwsVisibility = (
cvPrivate, cvProtected, cvPublic, cvPublished
);
begin
Result:=cVisibilityMap[aVisibility];
end;
// ExposeRTTIClass
//
function TdwsRTTIExposer.ExposeRTTIClass(cls : TRttiInstanceType; const options : TdwsRTTIExposerOptions) : TdwsClass;
var
exposableVisibilities : set of TMemberVisibility;
function ShouldExpose(item : TRttiMember) : Boolean;
var
attrib : TCustomAttribute;
begin
Result:=(item.Visibility in exposableVisibilities);
for attrib in item.GetAttributes do begin
if attrib.ClassType=dwsPublished then
Result:=True
else if attrib.ClassType=dwsNotPublished then
Result:=False;
end;
end;
var
meth : TRttiMethod;
prop : TRttiProperty;
helper : TdwsRTTIHelper;
scriptConstructor : TdwsConstructor;
begin
if eoExposePublic in options then
exposableVisibilities:=[mvPublic, mvPublished]
else exposableVisibilities:=[mvPublished];
Result:=Classes.Add;
Result.Name:=dwsPublished.NameOf(cls);
if not (eoNoFreeOnCleanup in options) then
Result.OnCleanUp:=DoStandardCleanUp;
helper:=TdwsRTTIHelper.Create(cls);
Result.HelperObject:=helper;
for meth in cls.GetMethods do begin
if meth.Parent.Name='TObject' then continue;
if not meth.HasExtendedInfo then continue;
if ShouldExpose(meth) then begin
case meth.MethodKind of
TypInfo.mkProcedure, TypInfo.mkFunction, TypInfo.mkClassProcedure, TypInfo.mkClassFunction :
ExposeRTTIMethod(meth, Result, options);
TypInfo.mkConstructor :
ExposeRTTIConstructor(meth, Result, options);
end;
end;
end;
if Result.Constructors.IndexOf('Create')<0 then begin
scriptConstructor:=(Result.Constructors.Add as TdwsConstructor);
scriptConstructor.OnEval:=helper.DoStandardCreate;
scriptConstructor.Name:='Create';
end;
for prop in cls.GetProperties do begin
if ShouldExpose(prop) then begin
ExposeRTTIProperty(prop, Result, options);
end;
end;
end;
// ExposeRTTIConstructor
//
function TdwsRTTIExposer.ExposeRTTIConstructor(meth : TRttiMethod; scriptClass : TdwsClass;
const options : TdwsRTTIExposerOptions) : TdwsConstructor;
var
param : TRttiParameter;
helper : TdwsRTTIHelper;
invoker : TdwsRTTIConstructorInvoker;
begin
Result:=scriptClass.Constructors.Add;
Result.Name:=dwsPublished.NameOf(meth);
if eoExposeVirtual in options then begin
if meth.DispatchKind in [dkVtable, dkDynamic] then
Result.Attributes:=Result.Attributes+[maVirtual];
end;
for param in meth.GetParameters do
ExposeRTTIParameter(param, Result.Parameters, options);
helper:=scriptClass.HelperObject as TdwsRTTIHelper;
invoker:=TdwsRTTIConstructorInvoker.Create(meth);
helper.AddInvoker(invoker);
Result.OnEval:=invoker.InvokeConstructor;
end;
function TdwsRTTIExposer.ExposeRTTIDynamicArray(intf: TRttiDynamicArrayType;
const options: TdwsRTTIExposerOptions): TdwsArray;
var
LType: string;
LTypeKind: TTypeKind;
begin
LTypeKind := intf.ElementType.TypeKind;
case LTypeKind of
tkInteger,
tkInt64: LType := SYS_INTEGER;
tkFloat: LType := SYS_FLOAT;
tkChar, tkString, tkUString, tkWChar, tkLString, tkWString:
LType := SYS_STRING;
tkVariant: LType := SYS_VARIANT;
else raise Exception.CreateFmt('Cannot expose dynamic array of type: %s', [
cTYPEKIND_NAMES[LTypeKind]]);
end; // case LTypeKind of
Result := Self.Arrays.Add;
Result.DataType := LType;
Result.IsDynamic := True;
Result.Name := intf.Name;
end;
// ExposeRTTIMethod
//
function TdwsRTTIExposer.ExposeRTTIMethod(meth : TRttiMethod; scriptClass : TdwsClass;
const options : TdwsRTTIExposerOptions) : TdwsMethod;
var
param : TRttiParameter;
helper : TdwsRTTIHelper;
invoker : TdwsRTTIMethodInvoker;
begin
Result:=scriptClass.Methods.Add;
Result.Name:=dwsPublished.NameOf(meth);
Result.ResultType:=RTTITypeToScriptType(meth.ReturnType);
case meth.MethodKind of
TypInfo.mkClassProcedure :
Result.Kind:=TMethodKind.mkClassProcedure;
TypInfo.mkClassFunction :
Result.Kind:=TMethodKind.mkClassFunction;
end;
if eoExposeVirtual in options then begin
if meth.DispatchKind in [dkVtable, dkDynamic] then
Result.Attributes:=Result.Attributes+[maVirtual];
end;
for param in meth.GetParameters do
ExposeRTTIParameter(param, Result.Parameters, options);
helper:=scriptClass.HelperObject as TdwsRTTIHelper;
invoker:=TdwsRTTIMethodInvoker.Create(meth);
helper.AddInvoker(invoker);
Result.OnEval:=invoker.Invoke;
end;
// ExposeRTTIProperty
//
function TdwsRTTIExposer.ExposeRTTIProperty(prop : TRttiProperty; scriptClass : TdwsClass;
const options : TdwsRTTIExposerOptions) : TdwsProperty;
var
helper : TdwsRTTIHelper;
setterInvoker : TdwsRTTISetterInvoker;
getterInvoker : TdwsRTTIGetterInvoker;
setterMethod, getterMethod : TdwsMethod;
setterParam : TdwsParameter;
begin
Result:=scriptClass.Properties.Add;
Result.Name:=dwsPublished.NameOf(prop);
Result.DataType:=RTTITypeToScriptType(prop.PropertyType);
helper:=scriptClass.HelperObject as TdwsRTTIHelper;
if prop.IsReadable then begin
getterInvoker:=TdwsRTTIGetterInvoker.Create(prop);
helper.AddInvoker(getterInvoker);
getterMethod:=(scriptClass.Methods.Add as TdwsMethod);
getterMethod.Name:='Get'+prop.Name;
Result.ReadAccess:=getterMethod.Name;
getterMethod.ResultType:=RTTITypeToScriptType(prop.PropertyType);
getterMethod.OnEval:=getterInvoker.Invoke;
end;
if prop.IsWritable then begin
setterInvoker:=TdwsRTTISetterInvoker.Create(prop);
helper.AddInvoker(setterInvoker);
setterMethod:=(scriptClass.Methods.Add as TdwsMethod);
setterMethod.Name:='Set'+prop.Name;
Result.WriteAccess:=setterMethod.Name;
setterParam:=setterMethod.Parameters.Add;
setterParam.Name:='v';
setterParam.DataType:=RTTITypeToScriptType(prop.PropertyType);
setterMethod.OnEval:=setterInvoker.Invoke;
end;
end;
// ExposeRTTIParameter
//
function TdwsRTTIExposer.ExposeRTTIParameter(param : TRttiParameter; scriptParameters : TdwsParameters;
const options : TdwsRTTIExposerOptions) : TdwsParameter;
begin
Result:=scriptParameters.Add;
Result.Name:=dwsPublished.NameOf(param);
Result.DataType:=RTTITypeToScriptType(param.ParamType);
if pfVar in param.Flags then
Result.IsVarParam:=True;
if pfConst in param.Flags then
Result.IsWritable:=True;
end;
// ExposeRTTIEnumeration
//
function TdwsRTTIExposer.ExposeRTTIEnumeration(enum : TRttiEnumerationType;
const options : TdwsRTTIExposerOptions) : TdwsEnumeration;
var
i : Integer;
enumName : String;
element : TdwsElement;
begin
Result:=Enumerations.Add;
Result.Name:=dwsPublished.NameOf(enum);
for i:=enum.MinValue to enum.MaxValue do begin
enumName:=GetEnumName(enum.Handle, i);
element:=Result.Elements.Add;
element.Name:=enumName;
element.UserDefValue:=i;
end;
end;
// ExposeRTTIRecord
//
function TdwsRTTIExposer.ExposeRTTIRecord(rec : TRttiRecordType;
const options : TdwsRTTIExposerOptions) : TdwsRecord;
var
field : TRttiField;
member : TdwsMember;
begin
Result:=Records.Add;
Result.Name:=dwsPublished.NameOf(rec);
for field in rec.GetFields do begin
member:=Result.Members.Add;
member.Name:=field.Name;
member.DataType:=RTTITypeToScriptType(field.FieldType);
member.Visibility:=RTTIVisibilityToVisibility(field.Visibility);
end;
end;
// ExposeRTTIInterface
//
function TdwsRTTIExposer.ExposeRTTIInterface(intf : TRttiInterfaceType;
const options : TdwsRTTIExposerOptions) : TdwsInterface;
var
rttiMeth : TRttiMethod;
rttiParam : TRttiParameter;
meth : TdwsMethod;
begin
Result:=Interfaces.Add;
Result.Name:=dwsPublished.NameOf(intf);
for rttiMeth in intf.GetMethods do begin
meth:=Result.Methods.Add;
meth.Name:=rttiMeth.Name;
meth.ResultType:=RTTITypeToScriptType(rttiMeth.ReturnType);
for rttiParam in rttiMeth.GetParameters do
ExposeRTTIParameter(rttiParam, meth.Parameters, options);
end;
end;
// DoStandardCleanUp
//
procedure TdwsRTTIExposer.DoStandardCleanUp(externalObject: TObject);
begin
externalObject.Free;
end;
// ------------------
// ------------------ TdwsRTTIInvoker ------------------
// ------------------
// AssignIInfoFromValue
//
class procedure TdwsRTTIInvoker.AssignIInfoFromValue(const info : IInfo; const value : TValue;
asType : TRttiType);
begin
case asType.TypeKind of
tkInteger, tkInt64 :
info.Value:=value.AsInt64;
tkFloat :
info.Value:=value.AsType<Double>;
tkChar, tkString, tkUString, tkWChar, tkLString, tkWString :
info.Value:=value.AsString;
tkRecord :
AssignRecordFromValue(info, value, asType);
tkEnumeration :
if asType.Handle=TypeInfo(Boolean) then
info.Value:=value.AsBoolean
else info.Value:=value.AsInt64;
else
info.Value:=value.AsVariant;
end;
end;
// AssignRecordFromValue
//
class procedure TdwsRTTIInvoker.AssignRecordFromValue(const recInfo : IInfo; const value : TValue;
asType : TRttiType);
var
field : TRttiField;
rawData : Pointer;
begin
rawData:=value.GetReferenceToRawData;
for field in asType.AsRecord.GetFields do
AssignIInfoFromValue(recInfo.Member[field.Name],
field.GetValue(rawData),
field.FieldType);
end;
// ValueFromParam
//
class function TdwsRTTIInvoker.ValueFromParam(progInfo : TProgramInfo; const paramName : String;
asType : TRttiType) : TValue;
begin
Result:=ValueFromIInfo(asType, progInfo.Vars[paramName]);
end;
// ValueFromIInfo
//
class function TdwsRTTIInvoker.ValueFromIInfo(asType : TRttiType; const info : IInfo) : TValue;
type
TValueArray = TArray<TValue>;
var
LLen: Integer;
Index: Integer;
begin
case asType.TypeKind of
tkInteger, tkInt64 :
Result:=TValue.From<Int64>(info.ValueAsInteger);
tkFloat :
Result:=TValue.From<Double>(info.ValueAsFloat);
tkChar, tkString, tkUString, tkWChar, tkLString, tkWString :
Result:=TValue.From<String>(info.ValueAsString);
tkVariant :
Result:=TValue.From<Variant>(info.Value);
tkRecord :
Result:=ValueFromRecord(asType, info);
tkEnumeration :
if asType.Handle=TypeInfo(Boolean) then
Result:=info.ValueAsBoolean
else Result:=info.ValueAsInteger;
tkDynArray: begin
LLen := Length(info.Data);
TValue.MakeWithoutCopy(NIL, asType.Handle, Result);
DynArraySetLength(PPointer(Result.GetReferenceToRawData)^, Result.TypeInfo, 1, @LLen);
for Index := Low(info.Data) to High(info.Data) do
Result.SetArrayElement(Index, TValue.FromVariant(info.Data[Index]));
end
else
// Unsupported
Result:=TValue.Empty;
Assert(False);
end;
end;
// ValueFromRecord
//
class function TdwsRTTIInvoker.ValueFromRecord(asType : TRttiType; const recInfo : IInfo) : TValue;
var
field : TRttiField;
rawData : Pointer;
begin
TValue.Make(nil, asType.Handle, Result);
rawData:=Result.GetReferenceToRawData;
for field in asType.AsRecord.GetFields do
field.SetValue(rawData, ValueFromIInfo(field.FieldType, recInfo.Member[field.Name]));
end;
// ------------------
// ------------------ TdwsRTTIMethodInvoker ------------------
// ------------------
// Create
//
constructor TdwsRTTIMethodInvoker.Create(aMethod : TRttiMethod);
begin
inherited Create;
Initialize(aMethod);
end;
// Initialize
//
procedure TdwsRTTIMethodInvoker.Initialize(aMethod : TRttiMethod);
var
methParams : TArray<TRttiParameter>;
param : TRttiParameter;
i, n, k : Integer;
begin
FMethod:=aMethod;
methParams:=aMethod.GetParameters;
n:=Length(methParams);
SetLength(FTypParams, n);
SetLength(FNameParams, n);
k:=0;
for i:=0 to n-1 do begin
param:=methParams[i];
FTypParams[i]:=param.ParamType;
FNameParams[i]:=param.Name;
if (pfVar in param.Flags) then begin
SetLength(FVarParams, k+1);
FVarParams[k]:=i;
Inc(k);
end;
end;
FTypResult:=aMethod.ReturnType;
end;
// PrepareParams
//
procedure TdwsRTTIMethodInvoker.PrepareParams(info : TProgramInfo; var params : TArray<TValue>);
var
i : Integer;
begin
SetLength(params, Length(FTypParams));
for i:=0 to High(FTypParams) do begin
params[i]:=ValueFromParam(info, FNameParams[i], FTypParams[i]);
end;
end;
// Invoke
//
procedure TdwsRTTIMethodInvoker.Invoke(info : TProgramInfo; externalObject : TObject);
var
params : TArray<TValue>;
resultValue : TValue;
i : Integer;
begin
PrepareParams(info, params);
resultValue:=FMethod.Invoke(externalObject, params);
if FTypResult<>nil then
AssignIInfoFromValue(info.ResultVars, resultValue, FTypResult);
for i in FVarParams do
AssignIInfoFromValue(info.Vars[FNameParams[i]], params[i], FTypParams[i]);
end;
// ------------------
// ------------------ TdwsRTTIConstructorInvoker ------------------
// ------------------
// InvokeConstructor
//
procedure TdwsRTTIConstructorInvoker.InvokeConstructor(info: TProgramInfo; var extObject: TObject);
var
params : TArray<TValue>;
begin
PrepareParams(info, params);
extObject:=FMethod.Invoke(FHelper.FInstanceType.MetaclassType, params).AsObject;
end;
// ------------------
// ------------------ TdwsRTTIPropertyInvoker ------------------
// ------------------
// Create
//
constructor TdwsRTTIPropertyInvoker.Create(aProperty : TRttiProperty);
begin
inherited Create;
Initialize(aProperty);
end;
// Initialize
//
procedure TdwsRTTIPropertyInvoker.Initialize(aProperty : TRttiProperty);
begin
FProperty:=aProperty;
FTyp:=aProperty.PropertyType;
end;
// ------------------
// ------------------ TdwsRTTISetterInvoker ------------------
// ------------------
// Invoke
//
procedure TdwsRTTISetterInvoker.Invoke(info : TProgramInfo; externalObject : TObject);
var
value : TValue;
begin
value:=ValueFromParam(info, 'v', FTyp);
FProperty.SetValue(externalObject, value);
end;
// ------------------
// ------------------ TdwsRTTIGetterInvoker ------------------
// ------------------
// Invoke
//
procedure TdwsRTTIGetterInvoker.Invoke(info : TProgramInfo; externalObject : TObject);
var
resultValue : TValue;
begin
resultValue:=FProperty.GetValue(externalObject);
AssignIInfoFromValue(info.ResultVars, resultValue, FTyp);
end;
end.
| 32.013746 | 122 | 0.640547 |
f1a6f1461546c18dd63e9ee5047f0c84d00c78a7 | 2,858 | pas | Pascal | src/validators/Validator.Contains.pas | dliocode/datavalidator | ff0ef7a51e6f33c162a13582ab96a313e80bbf44 | [
"MIT"
]
| 21 | 2021-06-25T20:08:59.000Z | 2022-03-03T23:43:49.000Z | src/validators/Validator.Contains.pas | dliocode/datavalidator | ff0ef7a51e6f33c162a13582ab96a313e80bbf44 | [
"MIT"
]
| null | null | null | src/validators/Validator.Contains.pas | dliocode/datavalidator | ff0ef7a51e6f33c162a13582ab96a313e80bbf44 | [
"MIT"
]
| 6 | 2021-06-26T01:36:30.000Z | 2021-07-29T03:51:06.000Z | {
********************************************************************************
Github - https://github.com/dliocode/datavalidator
********************************************************************************
MIT License
Copyright (c) 2021 Danilo Lucas
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
********************************************************************************
}
unit Validator.Contains;
interface
uses
DataValidator.ItemBase,
System.SysUtils;
type
TValidatorContains = class(TDataValidatorItemBase, IDataValidatorItem)
private
FValueContains: TArray<string>;
FCaseSensitive: Boolean;
public
function Check: IDataValidatorResult;
constructor Create(const AValueContains: TArray<string>; const ACaseSensitive: Boolean; const AMessage: string; const AExecute: TDataValidatorInformationExecute = nil);
end;
implementation
{ TValidatorContains }
constructor TValidatorContains.Create(const AValueContains: TArray<string>; const ACaseSensitive: Boolean; const AMessage: string; const AExecute: TDataValidatorInformationExecute);
begin
FValueContains := AValueContains;
FCaseSensitive := ACaseSensitive;
SetMessage(AMessage);
SetExecute(AExecute);
end;
function TValidatorContains.Check: IDataValidatorResult;
var
LValue: string;
R: Boolean;
I: Integer;
begin
LValue := GetValueAsString;
R := False;
if not Trim(LValue).IsEmpty then
for I := Low(FValueContains) to High(FValueContains) do
begin
if FCaseSensitive then
R := Pos(FValueContains[I], LValue) > 0
else
R := Pos(LowerCase(FValueContains[I]), LowerCase(LValue)) > 0;
if R then
Break;
end;
if FIsNot then
R := not R;
Result := TDataValidatorResult.Create(R, TDataValidatorInformation.Create(LValue, GetMessage, FExecute));
end;
end.
| 31.406593 | 181 | 0.689993 |
f18e096c3275d3afa084424762e299111c5035c9 | 36,289 | pas | Pascal | windows/src/ext/jedi/jvcl/jvcl/run/JvgReport.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 219 | 2017-06-21T03:37:03.000Z | 2022-03-27T12:09:28.000Z | windows/src/ext/jedi/jvcl/jvcl/run/JvgReport.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 4,451 | 2017-05-29T02:52:06.000Z | 2022-03-31T23:53:23.000Z | windows/src/ext/jedi/jvcl/jvcl/run/JvgReport.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 72 | 2017-05-26T04:08:37.000Z | 2022-03-03T10:26:20.000Z | {-----------------------------------------------------------------------------
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: JvgReport.PAS, released on 2003-01-15.
The Initial Developer of the Original Code is Andrey V. Chudin, [chudin att yandex dott ru]
Portions created by Andrey V. Chudin are Copyright (C) 2003 Andrey V. Chudin.
All Rights Reserved.
Contributor(s):
Michael Beck [mbeck att bigfoot dott com].
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:
-----------------------------------------------------------------------------}
// $Id$
unit JvgReport;
{$I jvcl.inc}
interface
uses
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
Windows, Messages, Classes, Controls, Graphics,
Forms, OleCtnrs, ExtCtrls, SysUtils, Printers,
JvComponentBase, JvComponent,
JvgUtils, JvgTypes, JvgCommClasses;
type
TJvgReport = class;
TJvgReportParamKind = (gptUnknown, gptEdit, gptRadio, gptCheck);
TJvgReportScrollBox = class(TScrollBox)
private
FGridImage: TBitmap;
FOnDraw: TNotifyEvent;
procedure WMEraseBkgnd(var Msg: TWMEraseBkgnd); message WM_ERASEBKGND;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property OnDraw: TNotifyEvent read FOnDraw write FOnDraw;
end;
TJvgReportItem = class(TJvGraphicControl)
private
FSelected: Boolean;
FBkColor: Integer;
FBvColor: Integer;
FTransparent: Integer;
FAlignment: Word; //..1-left,2-right,3-center,4-boadwise
FSideLeft, FSideTop, FSideRight, FSideBottom: Word;
FPenStyle: Integer;
FPenWidth: Word;
FText: string;
PrintText: string;
FCompName: string;
FFName: string;
FFSize, FFColor, FFStyle: Integer;
FContainOLE: Boolean;
FFixed: Word;
FOLELinkToFile: string;
FOLESizeMode: Word;
// fRepaintOnlyBorder,
fSizing: Boolean;
R: array [1..8] of TRect;
DownPos: TPoint;
SizeDirection: Integer;
FExternalCanvas: TCanvas;
Cursors: array [1..8] of TCursor;
Bmp: TBitmap;
Report: TJvgReport;
procedure SetSelected(Value: Boolean);
procedure SetBkColor(Value: Integer);
procedure SetBvColor(Value: Integer);
procedure SetTransparent(Value: Integer);
procedure SetAlignment(Value: Word);
procedure SetSideLeft(Value: Word);
procedure SetSideTop(Value: Word);
procedure SetSideRight(Value: Word);
procedure SetSideBottom(Value: Word);
procedure SetPenStyle(Value: Integer);
procedure SetPenWidth(Value: Word);
procedure SetText(const Value: string);
procedure SetFName(const Value: string);
procedure SetFSize(Value: Integer);
procedure SetFColor(Value: Integer);
procedure SetFStyle(Value: Integer);
procedure SetContainOLE(Value: Boolean);
procedure SetOLELinkToFile(const Value: string);
procedure SetOLESizeMode(Value: Word);
procedure SetFixed(Value: Word);
function IsContainOLE: Boolean;
procedure WMMouseMove(var Msg: TWMMouse); message WM_MOUSEMOVE;
procedure WMLMouseDown(var Msg: TWMMouse); message WM_LBUTTONDOWN;
procedure WMLMouseUp(var Msg: TWMMouse); message WM_LBUTTONUP;
procedure WMSize(var Msg: TWMSize); message WM_SIZE;
protected
procedure MouseEnter(Control: TControl); override;
procedure MouseLeave(Control: TControl); override;
procedure FontChanged; override;
public
procedure Paint; override;
procedure PaintTo(Canvas: TCanvas);
protected
procedure SetParent(Value: TWinControl); override;
public
ResText: string;
OLEContainer: TOLEContainer;
property Selected: Boolean read FSelected write SetSelected default False;
property Visible;
property OnClick;
property OnDblClick;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
// property OnResize;
property ExternalCanvas: TCanvas read FExternalCanvas write FExternalCanvas;
// procedure RepaintBorder;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property BkColor: Integer read FBkColor write SetBkColor default clWhite;
property BvColor: Integer read FBvColor write SetBvColor default clBlack;
property Transparent: Integer read FTransparent write SetTransparent default 0;
property Alignment: Word read FAlignment write SetAlignment default 1;
property SideLeft: Word read FSideLeft write SetSideLeft default 1;
property SideTop: Word read FSideTop write SetSideTop default 1;
property SideRight: Word read FSideRight write SetSideRight default 1;
property SideBottom: Word read FSideBottom write SetSideBottom default 1;
property PenStyle: Integer read FPenStyle write SetPenStyle default Integer(psSolid);
property PenWidth: Word read FPenWidth write SetPenWidth default 1;
property Text: string read FText write SetText;
property CompName: string read FCompName write FCompName;
property FName: string read FFName write SetFName;
property FSize: Integer read FFSize write SetFSize;
property FColor: Integer read FFColor write SetFColor;
property FStyle: Integer read FFStyle write SetFStyle;
property ContainOLE: Boolean read FContainOLE write SetContainOLE default False;
property OLELinkToFile: string read FOLELinkToFile write SetOLELinkToFile stored IsContainOLE;
property OLESizeMode: Word read FOLESizeMode write SetOLESizeMode stored IsContainOLE default 2;
property Fixed: Word read FFixed write SetFixed default 0;
end;
TJvgReportBeforePrintEvent = procedure(Sender: TJvgReport) of object;
TJvgReport = class(TJvComponent)
private
procedure ValidateWnds;
function GetReportText: TStringList;
procedure SetReportText(Value: TStringList);
public
OwnerWnd, ParentWnd: TWinControl;
ParamNames: TStringList;
ParamValues: TStringList;
ParamMasks: TStringList;
ParamTypes: TList;
FReportList: TStringList;
ComponentList: TList;
FBeforePrint: TJvgReportBeforePrintEvent;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Save;
procedure LoadFromFile(const FileName: string);
procedure SaveToFile(const FileName: string);
procedure PaintTo(Canvas: TCanvas);
procedure PreviewTo(Window: TWinControl);
procedure Print;
procedure CreateReport(ParentWnd: TWinControl; fNeedClearOwner: Boolean);
function SetParam(const sParamName, sParamValue: string): Boolean;
function GetParam(const sParamName: string; var sParamValue: string): Boolean;
function AddComponent: TJvgReportItem;
procedure AnalyzeParams(Item: TJvgReportItem; const DefName: string);
private
procedure SetUnicalName(laBevel: TJvgReportItem);
protected
procedure Loaded; override;
procedure ClearReport;
published
property Report: TStringList read FReportList;
property ReportText: TStringList read GetReportText write SetReportText;
property BeforePrint: TJvgReportBeforePrintEvent read FBeforePrint write FBeforePrint;
end;
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$URL$';
Revision: '$Revision$';
Date: '$Date$';
LogPath: 'JVCL\run'
);
{$ENDIF UNITVERSIONING}
implementation
uses
Math,
JvResources, JvConsts;
const
S = 2;
DS = 2 * S + 1;
//=== { TJvgReportScrollBox } ================================================
constructor TJvgReportScrollBox.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FGridImage := TBitmap.Create;
FGridImage.Width := 8;
FGridImage.Height := 8;
FGridImage.Canvas.Brush.Color := clWhite; //clWindow;
FGridImage.Canvas.FillRect(Rect(0, 0, 8, 8));
FGridImage.Canvas.Pixels[7, 7] := 0;
end;
destructor TJvgReportScrollBox.Destroy;
begin
FGridImage.Free;
inherited Destroy;
end;
procedure TJvgReportScrollBox.WMEraseBkgnd(var Msg: TWMEraseBkgnd);
begin
Msg.Result := 1;
if csDestroying in ComponentState then
Exit;
with TCanvas.Create do
try
Handle := Msg.DC;
// Pen.Color := clWindow;
// Brush.Color := clWindow;
// Brush.Style := bsCross;
Brush.Bitmap := FGridImage;
FillRect(ClientRect);
Handle := 0;
finally
Free;
end;
if Assigned(FOnDraw) then
FOnDraw(Self);
end;
//=== { TJvgReportItem } =====================================================
constructor TJvgReportItem.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
//..defaults
Width := 50;
Height := 50;
Color := clWhite;
FBkColor := clWhite;
FBvColor := clBlack;
FAlignment := 1;
FSideLeft := 1;
FSideTop := 1;
FSideRight := 1;
FSideBottom := 1;
FPenStyle := Integer(psSolid);
FPenWidth := 1;
FOLESizeMode := 2;
Cursors[1] := crSizeNWSE;
Cursors[2] := crSizeNS;
Cursors[3] := crSizeNESW;
Cursors[4] := crSizeNESW;
Cursors[5] := crSizeNS;
Cursors[6] := crSizeNWSE;
Cursors[7] := crSizeWE;
Cursors[8] := crSizeWE;
ParentFont := False;
{$IFDEF GL_RUS}
Font.CharSet := RUSSIAN_CHARSET;
{$ENDIF GL_RUS}
FontChanged;
end;
destructor TJvgReportItem.Destroy;
begin
if Assigned(Bmp) then
Bmp.Free;
if Assigned(OLEContainer) then
begin
OLEContainer.DestroyObject;
if not (csDestroying in ComponentState) then
begin
OLEContainer.Free;
OLEContainer := nil;
end;
end;
inherited;
end;
{procedure TJvgReportItem.RepaintBorder;
var
R: TRect;
begin
R := ClientRect;
OffsetRect( R, Left, Top );
InvalidateRect( Parent.Handle, @R, False );
InflateRect( R, -DS, -DS );
// ValidateRect( Parent.Handle, @R );
fRepaintOnlyBorder := True;
Paint;
//fRepaintOnlyBorder := False;
end;
}
procedure TJvgReportItem.Paint;
begin
PaintTo(Canvas);
end;
procedure TJvgReportItem.PaintTo(Canvas: TCanvas);
const
Alignments: array[1..4] of TglAlignment = (ftaLeftJustify,
ftaRightJustify, ftaCenter, ftaBroadwise);
// SysAlignments: array[TglAlignment] of Word = (DT_LEFT, DT_RIGHT, DT_CENTER, 0);
var
I, L, T: Integer;
sPrintText: string;
R_, Client_Rect, RCalc: TRect;
begin
FFColor := 0;
with Canvas do
begin
if Canvas = Self.Canvas then
Client_Rect := Rect(0, 0, Width, Height)
else
begin
Client_Rect := Bounds(Left, Top, Width, Height);
Canvas.Font := Self.Canvas.Font;
Canvas.Font.Color := 0;
end;
R_ := Client_Rect;
L := Client_Rect.Left;
T := Client_Rect.Top;
InflateRect(R_, -DS, -S);
RCalc := R_;
if Transparent = 0 then
begin
Brush.Color := BkColor;
FillRect(Client_Rect);
end;
if Canvas = Self.Canvas then
begin
Pen.Style := psDot;
Pen.Width := 1;
Pen.Color := clSilver;
Brush.Style := bsClear;
Rectangle(L, T, L + Width, T + Height);
sPrintText := Text;
end
else
sPrintText := PrintText;
if sPrintText = '' then
sPrintText := Text;
Pen.Style := TPenStyle(PenStyle);
Pen.Width := PenWidth;
Pen.Color := BvColor;
if SideLeft <> 0 then
begin
MoveTo(L + PenWidth div 2, T + Height - 1);
LineTo(L + PenWidth div 2, T);
end;
if SideTop <> 0 then
begin
MoveTo(L + PenWidth div 2, T + PenWidth div 2);
LineTo(L + Width - PenWidth, T + PenWidth div 2);
end;
if SideRight <> 0 then
begin
MoveTo(L + Width - 1, T);
LineTo(L + Width - 1, T + Height - 1);
end;
if SideBottom <> 0 then
begin
MoveTo(L + Width - 1, T + Height - 1);
LineTo(L, T + Height - 1);
end;
if not ContainOLE then
begin
SetBkMode(Canvas.Handle, TRANSPARENT);
SetTextColor(Canvas.Handle, FColor);
Windows.DrawText(Canvas.Handle, PChar(sPrintText), Length(sPrintText), RCalc,
DT_CALCRECT or DT_WordBREAK);
R_.Top := R_.Top + max(0, (R_.Bottom - R_.Top - (RCalc.Bottom -
RCalc.Top)) div 2);
DrawTextExtAligned(Canvas, sPrintText, R_, Alignments[Alignment],
True);
end
else
if (OLELinkToFile <> '') and (ExtractFileExt(OLELinkToFile) = '.bmp') then
begin
if Assigned(OLEContainer) then
OLEContainer.Visible := False;
if Bmp = nil then
begin
Bmp := TBitmap.Create;
Bmp.LoadFromFile(OLELinkToFile);
end;
BitBlt(Canvas.Handle, L, T, Bmp.Width, Bmp.Height, Bmp.Canvas.Handle,
0, 0, SRCCOPY);
end;
if Selected then
begin
Pen.Style := psSolid;
Pen.Width := 1;
Pen.Color := 0;
Brush.Style := bsSolid;
if Fixed <> 0 then
Brush.Color := clBtnFace
else
Brush.Color := clWhite;
R[1] := Rect(0, 0, DS, DS); //...top-left
R[2] := Rect(Width div 2 - S, 0, Width div 2 + S + 1, DS); //...top-center
R[3] := Rect(Width - DS, 0, Width, DS); //...top-right
R[4] := Rect(0, Height - DS, DS, Height); //...bottom-left
R[5] := Rect(Width div 2 - S, Height - DS, Width div 2 + S + 1, Height); //...bottom-center
R[6] := Rect(Width - DS, Height - DS, Width, Height); //...bottom-right
R[7] := Rect(0, Height div 2 - S, DS, Height div 2 + S + 1); //...left-center
R[8] := Rect(Width - DS, Height div 2 - S, Width, Height div 2 + S + 1); //...right-center
for I := 1 to 8 do
Rectangle(R[I].Left, R[I].Top, R[I].Right, R[I].Bottom);
end;
end;
if Assigned(OLEContainer) then
OLEContainer.SetBounds(Left + DS, Top + DS, Width - 2 * DS, Height - 2 *
DS);
end;
procedure TJvgReportItem.SetParent(Value: TWinControl);
begin
inherited;
if Assigned(OLEContainer) and Assigned(Value) then
OLEContainer.Parent := Value;
end;
procedure TJvgReportItem.MouseEnter(Control: TControl);
begin
inherited MouseEnter(Control);
if csDesigning in ComponentState then
Exit;
//Cursor := crCross;
// SetCursor( Screen.Cursors[crCross] );
end;
procedure TJvgReportItem.MouseLeave(Control: TControl);
begin
if csDesigning in ComponentState then
Exit;
Cursor := crDefault;
inherited MouseLeave(Control);
// SetCursor( Screen.Cursors[crDefault] );
end;
procedure TJvgReportItem.WMMouseMove(var Msg: TWMMouse);
var
I, dX, dY, nLeft, nTop, nWidth, nHeight: Integer;
pt: TPoint;
begin
inherited;
if Fixed = 0 then
with Msg do
begin
pt.x := Pos.x;
pt.y := Pos.y;
if fSizing then
begin
dX := Pos.x - DownPos.x;
dY := Pos.y - DownPos.y;
Inc(Pos.x, 4);
Inc(Pos.y, 4);
nLeft := Left;
nTop := Top;
nWidth := Width;
nHeight := Height;
case SizeDirection of
1:
begin
nLeft := Left + dX;
nWidth := Width - dX;
nTop := Top + dY;
nHeight := Height - dY;
end;
2:
begin
nTop := Top + dY;
nHeight := Height - dY;
end;
3:
begin
nWidth := Pos.x;
nTop := Top + dY;
nHeight := Height - dY;
end;
4:
begin
nLeft := Left + dX;
nWidth := Width - dX;
nHeight := Pos.y;
end;
5:
begin
nHeight := Pos.y;
end;
6:
begin
nWidth := Pos.x;
nHeight := Pos.y;
end;
7:
begin
nLeft := Left + dX;
nWidth := Width - dX;
end;
8:
begin
nWidth := Pos.x;
end;
end;
Left := min(nLeft, nLeft + nWidth);
Top := min(nTop, nTop + nHeight);
Width := abs(nWidth);
Height := abs(nHeight);
if nWidth < 0 then
begin
case SizeDirection of
1: SizeDirection := 3;
3: SizeDirection := 1;
4: SizeDirection := 6;
6: SizeDirection := 4;
8: SizeDirection := 7;
7: SizeDirection := 8;
end;
DownPos.x := Pos.x;
end;
if nHeight < 0 then
begin
case SizeDirection of
1: SizeDirection := 4;
2: SizeDirection := 5;
3: SizeDirection := 6;
4: SizeDirection := 1;
5: SizeDirection := 2;
6: SizeDirection := 3;
end;
DownPos.y := Pos.y;
end;
end
else
for I := 1 to 8 do
if PtInRect(R[I], pt) then
begin
Cursor := Cursors[I];
SizeDirection := I;
Exit;
end;
end;
Cursor := crDefault;
// SetCursor( Screen.Cursors[crDefault] );
end;
procedure TJvgReportItem.WMLMouseDown(var Msg: TWMMouse);
begin
DownPos.x := Msg.Pos.x;
DownPos.y := Msg.Pos.y;
//DownPos := ClientToScreen(DownPos);
fSizing := Cursor <> crDefault;
inherited;
end;
{procedure TJvgReportItem.WMRMouseDown(var Msg: TWMMouse);
begin
DownPos.x := Msg.Pos.x;
DownPos.y := Msg.Pos.y;
if Assigned(PopupMenu)
inherited;
end;}
procedure TJvgReportItem.WMLMouseUp(var Msg: TWMMouse);
begin
fSizing := False;
inherited;
end;
procedure TJvgReportItem.FontChanged;
begin
inherited FontChanged;
FName := Font.Name;
FFSize := Font.Size;
FFColor := Font.Color;
FFStyle := 0;
if fsBold in Font.Style then
FFStyle := FFStyle or 1;
if fsItalic in Font.Style then
FFStyle := FFStyle or (1 shl 1);
if fsUnderline in Font.Style then
FFStyle := FFStyle or (1 shl 2);
Invalidate;
end;
procedure TJvgReportItem.WMSize(var Msg: TWMSize);
begin
inherited;
// if Assigned(OnResize) then OnResize(Self);
end;
procedure TJvgReportItem.SetSelected(Value: Boolean);
begin
FSelected := Value;
Repaint;
end;
procedure TJvgReportItem.SetBkColor(Value: Integer);
begin
FBkColor := Value;
Color := BkColor;
Repaint;
end;
procedure TJvgReportItem.SetBvColor(Value: Integer);
begin
FBvColor := Value;
Repaint;
end;
procedure TJvgReportItem.SetTransparent(Value: Integer);
begin
FTransparent := Value;
Repaint;
end;
procedure TJvgReportItem.SetAlignment(Value: Word);
begin
FAlignment := Value;
Invalidate;
end;
procedure TJvgReportItem.SetSideLeft(Value: Word);
begin
FSideLeft := Value;
Invalidate;
end;
procedure TJvgReportItem.SetSideTop(Value: Word);
begin
FSideTop := Value;
Invalidate;
end;
procedure TJvgReportItem.SetSideRight(Value: Word);
begin
FSideRight := Value;
Invalidate;
end;
procedure TJvgReportItem.SetSideBottom(Value: Word);
begin
FSideBottom := Value;
Invalidate;
end;
procedure TJvgReportItem.SetPenStyle(Value: Integer);
begin
FPenStyle := Value;
Invalidate;
end;
procedure TJvgReportItem.SetPenWidth(Value: Word);
begin
FPenWidth := Value;
Invalidate;
end;
procedure TJvgReportItem.SetText(const Value: string);
begin
if FText <> Value then
begin
FText := Value;
Invalidate;
end;
end;
procedure TJvgReportItem.SetFName(const Value: string);
begin
FFName := Value;
Canvas.Font.Name := Value;
Invalidate;
end;
procedure TJvgReportItem.SetFSize(Value: Integer);
begin
FFSize := Value;
Canvas.Font.Size := Value;
Invalidate;
end;
procedure TJvgReportItem.SetFColor(Value: Integer);
begin
FFColor := Value;
Canvas.Font.Color := Value;
Invalidate;
end;
procedure TJvgReportItem.SetFStyle(Value: Integer);
begin
FFStyle := Value;
with Canvas.Font do
begin
if (Value and 1) <> 0 then
Style := Style + [fsBold]
else
Style := Style - [fsBold];
if (Value and (1 shl 1)) <> 0 then
Style := Style + [fsItalic]
else
Style := Style - [fsItalic];
if (Value and (1 shl 2)) <> 0 then
Style := Style + [fsUnderline]
else
Style := Style - [fsUnderline];
end;
Invalidate;
end;
procedure TJvgReportItem.SetContainOLE(Value: Boolean);
begin
FContainOLE := Value;
if FContainOLE and (not Assigned(OLEContainer)) then
begin
if not Assigned(Parent) then
Exit;
OLEContainer := TOLEContainer.Create(Parent.Parent);
OLEContainer.AutoVerbMenu := False;
OLEContainer.BorderStyle := bsNone;
OLEContainer.Color := clWhite;
OLEContainer.SizeMode := smScale;
OLEContainer.Parent := Parent;
if (OLEContainer.State = osEmpty) and (OLELinkToFile <> '') then
SetOLELinkToFile(OLELinkToFile);
end;
end;
procedure TJvgReportItem.SetOLELinkToFile(const Value: string);
begin
FOLELinkToFile := Value;
if Assigned(OLEContainer) then
begin
OLEContainer.CreateLinkToFile(Value, False);
//OLEContainer.LoadFromFile( Value );
end;
end;
procedure TJvgReportItem.SetFixed(Value: Word);
begin
FFixed := Value;
Repaint;
end;
procedure TJvgReportItem.SetOLESizeMode(Value: Word);
begin
if FOLESizeMode = Value then
Exit;
FOLESizeMode := Value;
if Assigned(OLEContainer) then
OLEContainer.SizeMode := TSizeMode(Value);
end;
function TJvgReportItem.IsContainOLE: Boolean;
begin
Result := FContainOLE;
end;
//=== { TJvgReport } =========================================================
constructor TJvgReport.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ParamNames := TStringList.Create;
ParamValues := TStringList.Create;
ParamMasks := TStringList.Create;
FReportList := TStringList.Create;
ParamTypes := TList.Create;
ComponentList := TList.Create;
end;
destructor TJvgReport.Destroy;
begin
FReportList.Free;
ParamNames.Free;
ParamValues.Free;
ParamMasks.Free;
ParamTypes.Free;
ClearReport;
ComponentList.Free;
inherited Destroy;
end;
procedure TJvgReport.Loaded;
begin
inherited Loaded;
CreateReport(nil, False);
end;
procedure TJvgReport.Save;
var
msS, msT: TMemoryStream;
begin
ValidateWnds;
msS := TMemoryStream.Create;
msT := TMemoryStream.Create;
try
msS.WriteComponent(ParentWnd);
msS.Position := 0;
ObjectBinaryToText(msS, msT);
msT.Position := 0;
FReportList.LoadFromStream(msT);
finally
msS.Free;
msT.Free;
end;
end;
procedure TJvgReport.SaveToFile(const FileName: string);
var
fs: TFileStream;
begin
ValidateWnds;
fs := TFileStream.Create(FileName, fmCreate or fmOpenWrite);
try
fs.WriteComponent(ParentWnd);
finally
fs.Free;
end;
end;
procedure TJvgReport.LoadFromFile(const FileName: string);
var
fs: TFileStream;
ms: TMemoryStream;
begin
fs := TFileStream.Create(FileName, fmOpenRead);
ms := TMemoryStream.Create;
try
ObjectBinaryToText(fs, ms);
ms.Position := 0;
FReportList.LoadFromStream(ms);
finally
fs.Free;
ms.Free;
end;
end;
{procedure TJvgReport.Edit;
begin
CreateReport(True);
end;}
procedure TJvgReport.PaintTo(Canvas: TCanvas);
var
I: Integer;
begin
OwnerWnd := nil;
ParentWnd := nil;
// ParamNames.Clear;
// ParamMasks.Clear;
// ParamValues.Clear;
// ParamTypes.Clear;
ComponentList.Clear;
CreateReport(ParentWnd, False);
for I := 0 to ComponentList.Count - 1 do
TJvgReportItem(ComponentList[I]).PaintTo(Canvas);
end;
procedure TJvgReport.PreviewTo(Window: TWinControl);
begin
OwnerWnd := Window;
ParentWnd := OwnerWnd;
ParamNames.Clear;
ParamMasks.Clear;
ParamValues.Clear;
ParamTypes.Clear;
ComponentList.Clear;
CreateReport(ParentWnd, False);
// ProcessParams;
end;
procedure TJvgReport.Print;
var
I: Integer;
ScreenDC: HDC;
HS, WS, HP, WP: Integer;
begin
if Assigned(BeforePrint) then
BeforePrint(Self);
OwnerWnd := TForm(TJvForm).Create(nil); // ahuser: what was the intention here???
TForm(OwnerWnd).WindowState := wsMaximized;
ParentWnd := OwnerWnd;
//OwnerWnd.Show;
try
CreateReport(ParentWnd, True);
if ComponentList.Count = 0 then
Exit;
Printer.BeginDoc;
ScreenDC := GetDC(HWND_DESKTOP);
HS := CentimetersToPixels(ScreenDC, 21, True);
WS := CentimetersToPixels(ScreenDC, 21, False);
HP := CentimetersToPixels(Printer.Canvas.Handle, 21, True);
WP := CentimetersToPixels(Printer.Canvas.Handle, 21, False);
ReleaseDC(HWND_DESKTOP, ScreenDC);
for I := 0 to ComponentList.Count - 1 do
begin
TJvgReportItem(ComponentList[I]).Left :=
MulDiv(TJvgReportItem(ComponentList[I]).Left, WP, WS);
TJvgReportItem(ComponentList[I]).Top :=
MulDiv(TJvgReportItem(ComponentList[I]).Top, HP, HS);
TJvgReportItem(ComponentList[I]).Width :=
MulDiv(TJvgReportItem(ComponentList[I]).Width, WP, WS);
TJvgReportItem(ComponentList[I]).Height :=
MulDiv(TJvgReportItem(ComponentList[I]).Height, HP, HS);
TJvgReportItem(ComponentList[I]).PenWidth :=
MulDiv(TJvgReportItem(ComponentList[I]).PenWidth, HP, HS);
end;
for I := 0 to ComponentList.Count - 1 do
with TJvgReportItem(ComponentList[I]) do
begin
PaintTo(Printer.Canvas);
if ContainOLE then
OLEContainer.PaintTo(Printer.Canvas.Handle, Left, Top);
end;
Printer.EndDoc;
repeat Application.ProcessMessages;
until not TForm(OwnerWnd).Active;
finally
OwnerWnd.Free;
end;
end;
procedure TJvgReport.ClearReport;
var
I: Integer;
begin
for I := 0 to ComponentList.Count - 1 do
TJvgReportItem(ComponentList[I]).Free;
ComponentList.Count := 0;
end;
procedure TJvgReport.CreateReport(ParentWnd: TWinControl; fNeedClearOwner:
Boolean);
var
ms: TMemoryStream;
P: TParser;
c: Char;
Compon: TComponent;
sName, sClassName: string;
S1, S2: string;
procedure N2T;
begin
P.NextToken;
P.NextToken;
end;
procedure Create_Object(const sClassName, sName: string);
var
B: TJvgReportItem;
begin
B := nil;
if sClassName = 'TJvgReportItem' then //...process only TJvgReportItem class
begin
B := TJvgReportItem.Create(OwnerWnd);
B.Report := Self;
end;
if B = nil then
Exit;
ComponentList.Add(B);
c := P.NextToken;
while not P.TokenSymbolIs('end') do
with P do
begin
case c of
'+':
begin
P.NextToken;
B.Text := B.Text + TokenString;
end;
toSymbol:
begin
if TokenString = 'Left' then
begin
N2T;
B.Left := TokenInt;
end;
if TokenString = 'Top' then
begin
N2T;
B.Top := TokenInt;
end;
if TokenString = 'Width' then
begin
N2T;
B.Width := TokenInt;
end;
if TokenString = 'Height' then
begin
N2T;
B.Height := TokenInt;
end;
if TokenString = 'Text' then
begin
N2T;
B.Text := TokenString;
end;
if TokenString = 'BkColor' then
begin
N2T;
B.BkColor := TokenInt;
end;
if TokenString = 'BvColor' then
begin
N2T;
B.BvColor := TokenInt;
end;
if TokenString = 'Transparent' then
begin
N2T;
B.Transparent := TokenInt;
end;
if TokenString = 'Alignment' then
begin
N2T;
B.Alignment := TokenInt;
end;
if TokenString = 'SideLeft' then
begin
N2T;
B.SideLeft := TokenInt;
end;
if TokenString = 'SideTop' then
begin
N2T;
B.SideTop := TokenInt;
end;
if TokenString = 'SideRight' then
begin
N2T;
B.SideRight := TokenInt;
end;
if TokenString = 'SideBottom' then
begin
N2T;
B.SideBottom := TokenInt;
end;
if TokenString = 'PenStyle' then
begin
N2T;
B.PenStyle := TokenInt;
end;
if TokenString = 'PenWidth' then
begin
N2T;
B.PenWidth := TokenInt;
end;
if TokenString = 'CompName' then
begin
N2T;
B.CompName := TokenString;
end;
if TokenString = 'FName' then
begin
N2T;
B.FName := TokenString;
end;
if TokenString = 'FSize' then
begin
N2T;
B.FSize := TokenInt;
end;
if TokenString = 'FColor' then
begin
N2T;
B.FColor := TokenInt;
end;
if TokenString = 'FStyle' then
begin
N2T;
B.FStyle := TokenInt;
end;
if TokenString = 'OLELinkToFile' then
begin
N2T;
B.OLELinkToFile := TokenString;
end;
if TokenString = 'OLESizeMode' then
begin
N2T;
B.OLESizeMode := TokenInt;
end;
if TokenString = 'Fixed' then
begin
N2T;
B.Fixed := TokenInt;
end;
end;
end;
c := NextToken;
end;
B.Parent := ParentWnd;
try
B.ContainOLE := B.OLELinkToFile <> '';
except
S1 := RsOLELinkedObjectNotFound;
S2 := RsErrorText;
Application.MessageBox(PChar(S1), PChar(S2),
MB_APPLMODAL or MB_OK or MB_ICONSTOP);
end;
B.Name := sName;
if B.CompName = '' then
SetUnicalName(B);
AnalyzeParams(B, B.CompName);
end;
procedure ClearOwner;
var
I: Integer;
begin
// ParamNames.Clear;
// ParamMasks.Clear;
// ParamValues.Clear;
// ParamTypes.Clear;
ComponentList.Clear;
if Assigned(ParentWnd) then
begin
with ParentWnd do
for I := ControlCount - 1 downto 0 do
if Controls[I] is TJvgReportItem then
RemoveControl(Controls[I]);
with OwnerWnd do
for I := ComponentCount - 1 downto 0 do
begin
if Components[I] is TJvgReportItem then
begin
Compon := Components[I];
RemoveComponent(Compon);
Compon.Free;
end;
end;
end;
end;
begin
ValidateWnds;
if fNeedClearOwner then
ClearOwner
else
ClearReport;
ms := TMemoryStream.Create;
FReportList.SaveToStream(ms);
ms.Position := 0;
P := TParser.Create(ms);
c := P.Token;
with P do
repeat
if TokenSymbolIs('object') then //...only noname objects!
begin
NextToken;
sClassName := TokenString;
try
Create_Object(sClassName, sName);
except
S1 := RsErrorReadingComponent;
S2 := RsErrorText;
Application.MessageBox(PChar(S1), PChar(S2),
MB_APPLMODAL or MB_OK or MB_ICONSTOP);
end;
end;
c := NextToken;
until c = toEOF;
P.Free;
ms.Free;
end;
function TJvgReport.AddComponent: TJvgReportItem;
begin
//AnalyzeParams( ReportComponent );
ValidateWnds;
Result := TJvgReportItem.Create(OwnerWnd);
Result.Report := Self;
SetUnicalName(Result);
Result.Parent := ParentWnd;
ComponentList.Add(Result);
end;
procedure TJvgReport.SetUnicalName(laBevel: TJvgReportItem);
var
I: Integer;
function ComponentExists(No: Integer): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to OwnerWnd.ComponentCount - 1 do
if OwnerWnd.Components[I] is TJvgReportItem then
if TJvgReportItem(OwnerWnd.Components[I]).CompName = 'Component' +
IntToStr(No) then
begin
Result := True;
Break;
end;
end;
begin
I := 0;
repeat
Inc(I);
until not ComponentExists(I);
laBevel.CompName := 'Component' + IntToStr(I);
end;
procedure TJvgReport.AnalyzeParams(Item: TJvgReportItem; const DefName: string);
var
LastPos: Integer;
SList: TStringList;
ParamType: TJvgReportParamKind;
ParamText, ParamName, ParamMask, ParamValue: string;
function ExtractParam(Item: TJvgReportItem; var SrchPos: Integer;
var ParamName: string; var ParamType: TJvgReportParamKind): Boolean;
var
I, J: Integer;
f: Boolean;
Text: string;
begin
Result := False;
Text := Item.Text;
if Length(Text) = 0 then
Exit;
f := False;
for I := SrchPos to Length(Text) - 1 do
if Text[I] = '#' then
begin
f := True;
Break;
end;
if not f then
Exit;
if Text[I - 1] = '{' then
ParamType := gptEdit
else
if Text[I - 1] = '<' then
ParamType := gptRadio
else
if Text[I - 1] = '[' then
ParamType := gptCheck
else
ParamType := gptUnknown;
if not f or (ParamType = gptUnknown) then
Exit;
SrchPos := I + 1;
f := False;
for I := SrchPos to Length(Text) do
if (Text[I] = '}') or (Text[I] = ']') or (Text[I] = '>') then
begin
f := True;
Break;
end;
if not f then
Exit;
ParamName := Copy(Text, SrchPos, I - SrchPos);
J := ParamNames.IndexOf(ParamName);
if J <> -1 then
Item.PrintText := Copy(Text, 0, SrchPos - 3) + ParamValues[J] +
Copy(Text, I + 1, 255);
Result := True;
end;
begin
LastPos := 0;
SList := TStringList.Create;
try
repeat
if ExtractParam(Item, LastPos, ParamText, ParamType) then
begin
ParamMask := '';
ParamValue := '';
ParamTypes.Add(Pointer(ParamType));
if ParamType = gptEdit then
begin
if ParamText = '' then
ParamText := DefName;
SList.CommaText := ParamText;
if SList.Count = 0 then
continue;
ParamName := SList[0];
if SList.Count > 1 then
ParamMask := SList[1];
if SList.Count > 2 then
ParamValue := SList[2];
end
else
ParamName := ParamText;
if ParamNames.IndexOf(ParamName) <> -1 then
continue; //...already exists
ParamNames.Add(ParamName);
ParamMasks.Add(ParamMask);
ParamValues.Add(ParamValue);
// else ParamValues[ParamIndex] := sParamValue;
end
else
Break;
until False;
finally
SList.Free;
end;
end;
function TJvgReport.SetParam(const sParamName, sParamValue: string): Boolean;
var
I: Integer;
begin
Result := False;
I := ParamNames.IndexOf(sParamName);
if I <> -1 then
begin
Result := True;
ParamValues[I] := sParamValue;
end;
end;
function TJvgReport.GetParam(const sParamName: string; var sParamValue: string):
Boolean;
var
ParamIndex: Integer;
begin
ParamIndex := ParamNames.IndexOf(sParamName);
if ParamIndex = -1 then
Result := False
else
begin
Result := True;
sParamValue := ParamValues[ParamIndex];
end;
end;
procedure TJvgReport.ValidateWnds;
begin
OwnerWnd := ParentWnd;
// if (OwnerWnd=nil)or(ParentWnd=nil) then raise Exception.Create('TJvgReport: Unassigned Owner or Parent window.');
end;
function TJvgReport.GetReportText: TStringList;
begin
Result := FReportList;
end;
procedure TJvgReport.SetReportText(Value: TStringList);
begin
FReportList.Assign(Value);
end;
{$IFDEF UNITVERSIONING}
initialization
RegisterUnitVersion(HInstance, UnitVersioning);
finalization
UnregisterUnitVersion(HInstance);
{$ENDIF UNITVERSIONING}
end.
| 25.718639 | 119 | 0.619416 |
f14e1f5d3dff131c31dc0d029959b526d6bde7d6 | 4,065 | pas | Pascal | Source/BCEditor.Editor.Caret.pas | EricGrange/TBCEditor | ef037fc3638b9bcf4ecacafcfc30fac745712460 | [
"MIT"
]
| 2 | 2018-01-03T03:48:19.000Z | 2021-12-08T14:54:20.000Z | Source/BCEditor.Editor.Caret.pas | EricGrange/TBCEditor | ef037fc3638b9bcf4ecacafcfc30fac745712460 | [
"MIT"
]
| null | null | null | Source/BCEditor.Editor.Caret.pas | EricGrange/TBCEditor | ef037fc3638b9bcf4ecacafcfc30fac745712460 | [
"MIT"
]
| 1 | 2021-04-29T08:09:41.000Z | 2021-04-29T08:09:41.000Z | unit BCEditor.Editor.Caret;
interface
uses
Classes, BCEditor.Editor.Caret.NonBlinking, BCEditor.Editor.Caret.MultiEdit, BCEditor.Editor.Caret.Styles,
BCEditor.Editor.Caret.Offsets, BCEditor.Types;
type
TBCEditorCaret = class(TPersistent)
strict private
FMultiEdit: TBCEditorCaretMultiEdit;
FNonBlinking: TBCEditorCaretNonBlinking;
FOffsets: TBCEditorCaretOffsets;
FOnChange: TNotifyEvent;
FOptions: TBCEditorCaretOptions;
FStyles: TBCEditorCaretStyles;
FVisible: Boolean;
procedure DoChange(ASender: TObject);
procedure SetMultiEdit(AValue: TBCEditorCaretMultiEdit);
procedure SetNonBlinking(AValue: TBCEditorCaretNonBlinking);
procedure SetOffsets(AValue: TBCEditorCaretOffsets);
procedure SetOnChange(AValue: TNotifyEvent);
procedure SetOptions(const AValue: TBCEditorCaretOptions);
procedure SetStyles(const AValue: TBCEditorCaretStyles);
procedure SetVisible(AValue: Boolean);
public
constructor Create;
destructor Destroy; override;
procedure Assign(ASource: TPersistent); override;
procedure SetOption(const AOption: TBCEditorCaretOption; const AEnabled: Boolean);
published
property MultiEdit: TBCEditorCaretMultiEdit read FMultiEdit write SetMultiEdit;
property NonBlinking: TBCEditorCaretNonBlinking read FNonBlinking write SetNonBlinking;
property Offsets: TBCEditorCaretOffsets read FOffsets write SetOffsets;
property OnChange: TNotifyEvent read FOnChange write SetOnChange;
property Options: TBCEditorCaretOptions read FOptions write SetOptions;
property Styles: TBCEditorCaretStyles read FStyles write SetStyles;
property Visible: Boolean read FVisible write SetVisible default True;
end;
implementation
constructor TBCEditorCaret.Create;
begin
inherited;
FMultiEdit := TBCEditorCaretMultiEdit.Create;
FNonBlinking := TBCEditorCaretNonBlinking.Create;
FOffsets := TBCEditorCaretOffsets.Create;
FStyles := TBCEditorCaretStyles.Create;
FVisible := True;
end;
destructor TBCEditorCaret.Destroy;
begin
FMultiEdit.Free;
FNonBlinking.Free;
FOffsets.Free;
FStyles.Free;
inherited;
end;
procedure TBCEditorCaret.Assign(ASource: TPersistent);
begin
if Assigned(ASource) and (ASource is TBCEditorCaret) then
with ASource as TBCEditorCaret do
begin
Self.FStyles.Assign(FStyles);
Self.FMultiEdit.Assign(FMultiEdit);
Self.FNonBlinking.Assign(FNonBlinking);
Self.FOffsets.Assign(FOffsets);
Self.FOptions := FOptions;
Self.FVisible := FVisible;
Self.DoChange(Self);
end
else
inherited Assign(ASource);
end;
procedure TBCEditorCaret.SetOnChange(AValue: TNotifyEvent);
begin
FOnChange := AValue;
FOffsets.OnChange := AValue;
FStyles.OnChange := AValue;
FMultiEdit.OnChange := AValue;
FNonBlinking.OnChange := AValue;
end;
procedure TBCEditorCaret.DoChange(ASender: TObject);
begin
if Assigned(FOnChange) then
FOnChange(ASender);
end;
procedure TBCEditorCaret.SetStyles(const AValue: TBCEditorCaretStyles);
begin
FStyles.Assign(AValue);
end;
procedure TBCEditorCaret.SetMultiEdit(AValue: TBCEditorCaretMultiEdit);
begin
FMultiEdit.Assign(AValue);
end;
procedure TBCEditorCaret.SetNonBlinking(AValue: TBCEditorCaretNonBlinking);
begin
FNonBlinking.Assign(AValue);
end;
procedure TBCEditorCaret.SetVisible(AValue: Boolean);
begin
if FVisible <> AValue then
begin
FVisible := AValue;
DoChange(Self);
end;
end;
procedure TBCEditorCaret.SetOffsets(AValue: TBCEditorCaretOffsets);
begin
FOffsets.Assign(AValue);
end;
procedure TBCEditorCaret.SetOption(const AOption: TBCEditorCaretOption; const AEnabled: Boolean);
begin
if AEnabled then
Include(FOptions, AOption)
else
Exclude(FOptions, AOption);
end;
procedure TBCEditorCaret.SetOptions(const AValue: TBCEditorCaretOptions);
begin
if FOptions <> AValue then
begin
FOptions := AValue;
DoChange(Self);
end;
end;
end.
| 28.229167 | 109 | 0.753014 |
476ddf6144de1b60a10ed066d43900bd1ae3b9db | 1,808 | pas | Pascal | Source/BCEditor.Editor.Search.Highlighter.Colors.pas | x2nie/TBCEditor | 195a6de1fcc67e0dfac0c1dbc424ee3984998d2d | [
"MIT"
]
| 18 | 2015-08-04T06:39:05.000Z | 2022-01-20T03:43:57.000Z | Source/BCEditor.Editor.Search.Highlighter.Colors.pas | LaKraven/TBCEditor | e20c264b3634b78f109eac2613e9eec602a332be | [
"MIT"
]
| null | null | null | Source/BCEditor.Editor.Search.Highlighter.Colors.pas | LaKraven/TBCEditor | e20c264b3634b78f109eac2613e9eec602a332be | [
"MIT"
]
| 12 | 2017-07-06T13:53:32.000Z | 2022-01-08T17:10:41.000Z | unit BCEditor.Editor.Search.Highlighter.Colors;
interface
uses
System.Classes, Vcl.Graphics, BCEditor.Consts, BCEditor.Types;
type
TBCEditorSearchColors = class(TPersistent)
strict private
FBackground: TColor;
FForeground: TColor;
FOnChange: TBCEditorSearchChangeEvent;
procedure SetBackground(const AValue: TColor);
procedure SetForeground(const AValue: TColor);
procedure DoChange;
public
constructor Create;
procedure Assign(ASource: TPersistent); override;
published
property Background: TColor read FBackground write SetBackground default clSearchHighlighter;
property Foreground: TColor read FForeground write SetForeground default clWindowText;
property OnChange: TBCEditorSearchChangeEvent read FOnChange write FOnChange;
end;
implementation
{ TBCEditorSearchColors }
constructor TBCEditorSearchColors.Create;
begin
inherited;
FBackground := clSearchHighlighter;
FForeground := clWindowText;
end;
procedure TBCEditorSearchColors.Assign(ASource: TPersistent);
begin
if ASource is TBCEditorSearchColors then
with ASource as TBCEditorSearchColors do
begin
Self.FBackground := FBackground;
Self.FForeground := FForeground;
Self.DoChange;
end
else
inherited Assign(ASource);
end;
procedure TBCEditorSearchColors.DoChange;
begin
if Assigned(FOnChange) then
FOnChange(scRefresh);
end;
procedure TBCEditorSearchColors.SetBackground(const AValue: TColor);
begin
if FBackground <> AValue then
begin
FBackground := AValue;
DoChange;
end;
end;
procedure TBCEditorSearchColors.SetForeground(const AValue: TColor);
begin
if FForeground <> AValue then
begin
FForeground := AValue;
DoChange;
end;
end;
end.
| 23.789474 | 98 | 0.74115 |
4764a1da26327c0e055195841eb4b86ae662f4de | 4,207 | pas | Pascal | src/DataSet.Serialize.Config.pas | Daniel09Fernandes/dataset-serialize | 6dda55846cb1d3687f46d77d31a799ab5a05a274 | [
"MIT"
]
| 368 | 2019-05-24T01:05:14.000Z | 2022-03-31T13:13:35.000Z | src/DataSet.Serialize.Config.pas | Kyuorhan/dataset-serialize | 104a33168ce1e5925193e632cbc6ac592989cc03 | [
"MIT"
]
| 62 | 2019-05-30T09:09:35.000Z | 2022-03-22T17:11:28.000Z | src/DataSet.Serialize.Config.pas | Kyuorhan/dataset-serialize | 104a33168ce1e5925193e632cbc6ac592989cc03 | [
"MIT"
]
| 125 | 2019-06-05T06:03:49.000Z | 2022-03-22T08:28:55.000Z | unit DataSet.Serialize.Config;
{$IF DEFINED(FPC)}
{$MODE DELPHI}{$H+}
{$ENDIF}
interface
type
TCaseNameDefinition = (cndNone, cndLower, cndUpper, cndLowerCamelCase, cndUpperCamelCase);
TDataSetSerializeConfigExport = class
private
FExportNullValues: Boolean;
FExportNullAsEmptyString: Boolean;
FExportOnlyFieldsVisible: Boolean;
FExportEmptyDataSet: Boolean;
FFormatCurrency: string;
FFormatDate: string;
FFormatTime: string;
FFormatDateTime: string;
FExportChildDataSetAsJsonObject: Boolean;
public
constructor Create;
property FormatDate: string read FFormatDate write FFormatDate;
property FormatTime: string read FFormatTime write FFormatTime;
property FormatDateTime: string read FFormatDateTime write FFormatDateTime;
property FormatCurrency: string read FFormatCurrency write FFormatCurrency;
property ExportOnlyFieldsVisible: Boolean read FExportOnlyFieldsVisible write FExportOnlyFieldsVisible;
property ExportNullValues: Boolean read FExportNullValues write FExportNullValues;
property ExportNullAsEmptyString: Boolean read FExportNullAsEmptyString write FExportNullAsEmptyString;
property ExportEmptyDataSet: Boolean read FExportEmptyDataSet write FExportEmptyDataSet;
property ExportChildDataSetAsJsonObject: Boolean read FExportChildDataSetAsJsonObject write FExportChildDataSetAsJsonObject;
end;
TDataSetSerializeConfigImport = class
private
FImportOnlyFieldsVisible: Boolean;
public
constructor Create;
property ImportOnlyFieldsVisible: Boolean read FImportOnlyFieldsVisible write FImportOnlyFieldsVisible;
end;
TDataSetSerializeConfig = class
private
FCaseNameDefinition: TCaseNameDefinition;
FDataSetPrefix: TArray<string>;
FDateInputIsUTC: Boolean;
FExport: TDataSetSerializeConfigExport;
FImport: TDataSetSerializeConfigImport;
class var FInstance: TDataSetSerializeConfig;
protected
class function GetDefaultInstance: TDataSetSerializeConfig;
public
constructor Create;
destructor Destroy; override;
property DataSetPrefix: TArray<string> read FDataSetPrefix write FDataSetPrefix;
property CaseNameDefinition: TCaseNameDefinition read FCaseNameDefinition write FCaseNameDefinition;
property DateInputIsUTC: Boolean read FDateInputIsUTC write FDateInputIsUTC;
property &Export: TDataSetSerializeConfigExport read FExport write FExport;
property Import: TDataSetSerializeConfigImport read FImport write FImport;
class function GetInstance: TDataSetSerializeConfig;
class destructor UnInitialize;
end;
implementation
uses
{$IF DEFINED(FPC)}
SysUtils;
{$ELSE}
System.SysUtils;
{$ENDIF}
constructor TDataSetSerializeConfig.Create;
begin
if not Assigned(FExport) then
FExport := TDataSetSerializeConfigExport.Create;
if not Assigned(FImport) then
FImport := TDataSetSerializeConfigImport.Create;
end;
destructor TDataSetSerializeConfig.Destroy;
begin
if Assigned(FExport) then
FreeAndNil(FExport);
if Assigned(FImport) then
FreeAndNil(FImport);
inherited;
end;
class function TDataSetSerializeConfig.GetDefaultInstance: TDataSetSerializeConfig;
begin
if not Assigned(FInstance) then
begin
FInstance := TDataSetSerializeConfig.Create;
FInstance.CaseNameDefinition := cndLowerCamelCase;
FInstance.DataSetPrefix := ['mt', 'qry'];
FInstance.DateInputIsUTC := True;
end;
Result := FInstance;
end;
class function TDataSetSerializeConfig.GetInstance: TDataSetSerializeConfig;
begin
Result := TDataSetSerializeConfig.GetDefaultInstance;
end;
class destructor TDataSetSerializeConfig.UnInitialize;
begin
if Assigned(FInstance) then
FreeAndNil(FInstance);
end;
constructor TDataSetSerializeConfigExport.Create;
begin
FExportNullValues := True;
FExportNullAsEmptyString:= False;
FExportOnlyFieldsVisible := True;
ExportEmptyDataSet := False;
FFormatCurrency := EmptyStr;
FFormatDate := 'YYYY-MM-DD';
FFormatTime := 'hh:nn:ss.zzz';
FFormatDateTime := 'yyyy-mm-dd hh:nn:ss.zzz';
FExportChildDataSetAsJsonObject := False;
end;
constructor TDataSetSerializeConfigImport.Create;
begin
FImportOnlyFieldsVisible := True;
end;
end.
| 31.395522 | 128 | 0.79748 |
83d0e2866b308a2e5c31f6f02880492702fd14fc | 592 | pas | Pascal | CAT/tests/10. generics/records/nested types/generic_record_nested_types_1.pas | SkliarOleksandr/NextPascal | 4dc26abba6613f64c0e6b5864b3348711eb9617a | [
"Apache-2.0"
]
| 19 | 2018-10-22T23:45:31.000Z | 2021-05-16T00:06:49.000Z | CAT/tests/10. generics/records/nested types/generic_record_nested_types_1.pas | SkliarOleksandr/NextPascal | 4dc26abba6613f64c0e6b5864b3348711eb9617a | [
"Apache-2.0"
]
| 1 | 2019-06-01T06:17:08.000Z | 2019-12-28T10:27:42.000Z | CAT/tests/10. generics/records/nested types/generic_record_nested_types_1.pas | SkliarOleksandr/NextPascal | 4dc26abba6613f64c0e6b5864b3348711eb9617a | [
"Apache-2.0"
]
| 6 | 2018-08-30T05:16:21.000Z | 2021-05-12T20:25:43.000Z | unit generic_record_nested_types_1;
interface
type
TRec<T> = record
type
TInt = T;
var
F1, F2: TInt;
procedure S0(V: T);
procedure S1(V: TInt);
procedure S2(V: TInt);
end;
implementation
var
G1, G2: Int32;
procedure TRec<T>.S0(V: T);
begin
end;
procedure TRec<T>.S1(V: TInt);
begin
F1 := V;
G1 := F1;
end;
procedure TRec<T>.S2(V: TInt);
begin
F2 := V;
G2 := F2;
end;
var
R: TRec<Int32>;
procedure Test;
begin
R.S1(5);
R.S2(7);
end;
initialization
Test();
finalization
Assert(G1 = 5);
Assert(G2 = 7);
end. | 11.384615 | 38 | 0.577703 |
f1a0cd85723a31b395d70eaf9f7a4aed70708ac7 | 216,226 | pas | Pascal | Sources/Pascal/ThirdParty/NVJclFileUtils.pas | DelcioSbeghen/NetVCL | 7467db6f3b979b38d6dda4a93e0f708d1c3142d2 | [
"MIT"
]
| 5 | 2019-05-08T20:13:31.000Z | 2021-07-30T10:58:53.000Z | Sources/Pascal/ThirdParty/NVJclFileUtils.pas | DelcioSbeghen/NetVCL | 7467db6f3b979b38d6dda4a93e0f708d1c3142d2 | [
"MIT"
]
| null | null | null | Sources/Pascal/ThirdParty/NVJclFileUtils.pas | DelcioSbeghen/NetVCL | 7467db6f3b979b38d6dda4a93e0f708d1c3142d2 | [
"MIT"
]
| 4 | 2019-03-30T16:37:05.000Z | 2021-07-31T18:56:34.000Z | {**************************************************************************************************}
{ }
{ Project JEDI Code Library (JCL) }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); }
{ you may not use this file except in compliance with the License. You may obtain a copy of the }
{ License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF }
{ ANY KIND, either express or implied. See the License for the specific language governing rights }
{ and limitations under the License. }
{ }
{ The Original Code is JclFileUtils.pas. }
{ }
{ The Initial Developer of the Original Code is Marcel van Brakel. }
{ Portions created by Marcel van Brakel are Copyright (C) Marcel van Brakel. All rights reserved. }
{ }
{ Contributors: }
{ Andre Snepvangers (asnepvangers) }
{ Andreas Hausladen (ahuser) }
{ Anthony Steele }
{ Rik Barker (rikbarker) }
{ Azret Botash }
{ Charlie Calvert }
{ David Hervieux }
{ Florent Ouchet (outchy) }
{ Jean-Fabien Connault (cycocrew) }
{ Jens Fudickar (jfudickar) }
{ JohnML }
{ John Molyneux }
{ Marcel Bestebroer }
{ Marcel van Brakel }
{ Massimo Maria Ghisalberti }
{ Matthias Thoma (mthoma) }
{ Olivier Sannier (obones) }
{ Pelle F. S. Liljendal }
{ Robert Marquardt (marquardt) }
{ Robert Rossmair (rrossmair) }
{ Rudy Velthuis }
{ Scott Price }
{ Wim De Cleen }
{ }
{**************************************************************************************************}
{ }
{ This unit contains routines and classes for working with files, directories and path strings. }
{ Additionally it contains wrapper classes for file mapping objects and version resources. }
{ Generically speaking, everything that has to do with files and directories. Note that filesystem }
{ specific functionality has been extracted into external units, for example JclNTFS which }
{ contains NTFS specific utility routines, and that the JclShell unit contains some file related }
{ routines as well but they are specific to the Windows shell. }
{ }
{**************************************************************************************************}
{ }
{ Last modified: $Date:: 2016-08-03 17:32:24 +0200 $ }
{ Revision: $Rev:: 14e6d6b003f774b2aab7dda32aa5aa66d67e3f2b $ }
{ Author: $Author:: Andreas Hausladen $ }
{ }
{**************************************************************************************************}
unit NVJclFileUtils;
{$I NVjcl.inc}
{$I NVcrossplatform.inc}
interface
uses
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
{$IFDEF HAS_UNIT_LIBC}
Libc,
{$ENDIF HAS_UNIT_LIBC}
{$IFDEF HAS_UNITSCOPE}
{$IFDEF MSWINDOWS}
Winapi.Windows, NVJclWin32,
{$ENDIF MSWINDOWS}
System.Classes, System.SysUtils,
{$ELSE ~HAS_UNITSCOPE}
{$IFDEF MSWINDOWS}
Windows, JclWin32,
{$ENDIF MSWINDOWS}
Classes, SysUtils,
{$ENDIF ~HAS_UNITSCOPE}
NVJclBase, NVJclSysUtils;
// Path Manipulation
//
// Various support routines for working with path strings. For example, building a path from
// elements or extracting the elements from a path, interpretation of paths and transformations of
// paths.
const
{$IFDEF UNIX}
// renamed to DirDelimiter
// PathSeparator = '/';
DirDelimiter = '/';
DirSeparator = ':';
{$ENDIF UNIX}
{$IFDEF MSWINDOWS}
PathDevicePrefix = '\\.\';
// renamed to DirDelimiter
// PathSeparator = '\';
DirDelimiter = '\';
DirSeparator = ';';
PathUncPrefix = '\\';
{$ENDIF MSWINDOWS}
faSymLink = $00000040 {$IFDEF SUPPORTS_PLATFORM} platform {$ENDIF}; // defined since D7
faNormalFile = $00000080;
faTemporary = $00000100 {$IFDEF SUPPORTS_PLATFORM} platform {$ENDIF};
faSparseFile = $00000200 {$IFDEF SUPPORTS_PLATFORM} platform {$ENDIF};
faReparsePoint = $00000400 {$IFDEF SUPPORTS_PLATFORM} platform {$ENDIF};
faCompressed = $00000800 {$IFDEF SUPPORTS_PLATFORM} platform {$ENDIF};
faOffline = $00001000 {$IFDEF SUPPORTS_PLATFORM} platform {$ENDIF};
faNotContentIndexed = $00002000 {$IFDEF SUPPORTS_PLATFORM} platform {$ENDIF};
faEncrypted = $00004000 {$IFDEF SUPPORTS_PLATFORM} platform {$ENDIF};
// Note: faVolumeID is potentially dangerous and its usage has been discontinued
// Please see QC report 6003 for details, available online at this URL:
// http://qc.embarcadero.com/wc/qcmain.aspx?d=6003
faRejectedByDefault = faHidden + faSysFile + faDirectory;
faWindowsSpecific = faArchive + faTemporary + faSparseFile + faReparsePoint +
faCompressed + faOffline + faNotContentIndexed + faEncrypted;
faUnixSpecific = faSymLink;
type
TCompactPath = ({cpBegin, }cpCenter, cpEnd);
function CharIsDriveLetter(const C: char): Boolean;
function PathAddSeparator(const Path: string): string;
function PathAddExtension(const Path, Extension: string): string;
function PathAppend(const Path, Append: string): string;
function PathBuildRoot(const Drive: Byte): string;
function PathCanonicalize(const Path: string): string;
function PathCommonPrefix(const Path1, Path2: string): Integer;
{$IFDEF MSWINDOWS}
function PathCompactPath(const DC: HDC; const Path: string; const Width: Integer;
CmpFmt: TCompactPath): string;
{$ENDIF MSWINDOWS}
procedure PathExtractElements(const Source: string; var Drive, Path, FileName, Ext: string);
function PathExtractFileDirFixed(const S: string): string;
function PathExtractFileNameNoExt(const Path: string): string;
function PathExtractPathDepth(const Path: string; Depth: Integer): string;
function PathGetDepth(const Path: string): Integer;
{$IFDEF MSWINDOWS}
function PathGetLongName(const Path: string): string;
function PathGetShortName(const Path: string): string;
{$ENDIF MSWINDOWS}
function PathGetRelativePath(Origin, Destination: string): string;
function PathGetTempPath: string;
function PathIsAbsolute(const Path: string): Boolean;
function PathIsChild(const Path, Base: string): Boolean;
function PathIsEqualOrChild(const Path, Base: string): Boolean;
function PathIsDiskDevice(const Path: string): Boolean;
function PathIsUNC(const Path: string): Boolean;
function PathRemoveSeparator(const Path: string): string;
function PathRemoveExtension(const Path: string): string;
// Windows Vista uses localized path names in the Windows Explorer but these
// folders do not really exist on disk. This causes all I/O operations to fail
// if the user specifies such a localized directory like "C:\Benutzer\MyName\Bilder"
// instead of the physical folder "C:\Users\MyName\Pictures".
// These two functions allow to convert the user's input from localized to
// physical paths and vice versa.
function PathGetPhysicalPath(const LocalizedPath: string): string;
function PathGetLocalizedPath(const PhysicalPath: string): string;
// Files and Directories
//
// Routines for working with files and directories. Includes routines to extract various file
// attributes or update them, volume locking and routines for creating temporary files.
type
TDelTreeProgress = function (const FileName: string; Attr: DWORD): Boolean;
TFileListOption = (flFullNames, flRecursive, flMaskedSubfolders);
TFileListOptions = set of TFileListOption;
TJclAttributeMatch = (amAny, amExact, amSubSetOf, amSuperSetOf, amCustom);
TFileMatchFunc = function(const Attr: Integer; const FileInfo: TSearchRec): Boolean;
TFileHandler = procedure (const FileName: string) of object;
TFileHandlerEx = procedure (const Directory: string; const FileInfo: TSearchRec) of object;
TFileInfoHandlerEx = procedure (const FileInfo: TSearchRec) of object;
function BuildFileList(const Path: string; const Attr: Integer; const List: TStrings; IncludeDirectoryName: Boolean =
False): Boolean;
function AdvBuildFileList(const Path: string; const Attr: Integer; const Files: TStrings;
const AttributeMatch: TJclAttributeMatch = amSuperSetOf; const Options: TFileListOptions = [];
const SubfoldersMask: string = ''; const FileMatchFunc: TFileMatchFunc = nil): Boolean;
function VerifyFileAttributeMask(var RejectedAttributes, RequiredAttributes: Integer): Boolean;
function IsFileAttributeMatch(FileAttributes, RejectedAttributes,
RequiredAttributes: Integer): Boolean;
function FileAttributesStr(const FileInfo: TSearchRec): string;
function IsFileNameMatch(FileName: string; const Mask: string;
const CaseSensitive: Boolean = {$IFDEF MSWINDOWS} False {$ELSE} True {$ENDIF}): Boolean;
procedure EnumFiles(const Path: string; HandleFile: TFileHandlerEx;
RejectedAttributes: Integer = faRejectedByDefault; RequiredAttributes: Integer = 0;
Abort: PBoolean = nil); overload;
procedure EnumFiles(const Path: string; HandleFile: TFileInfoHandlerEx;
RejectedAttributes: Integer = faRejectedByDefault; RequiredAttributes: Integer = 0;
Abort: PBoolean = nil); overload;
procedure EnumDirectories(const Root: string; const HandleDirectory: TFileHandler;
const IncludeHiddenDirectories: Boolean = False; const SubDirectoriesMask: string = '';
Abort: PBoolean = nil {$IFDEF UNIX}; ResolveSymLinks: Boolean = True {$ENDIF});
{$IFDEF MSWINDOWS}
procedure CreateEmptyFile(const FileName: string);
function CloseVolume(var Volume: THandle): Boolean;
{$IFNDEF FPC}
//DELCIO function DeleteDirectory(const DirectoryName: string; MoveToRecycleBin: Boolean): Boolean;
function CopyDirectory(ExistingDirectoryName, NewDirectoryName: string): Boolean;
function MoveDirectory(ExistingDirectoryName, NewDirectoryName: string): Boolean;
{$ENDIF ~FPC}
function DelTree(const Path: string): Boolean;
function DelTreeEx(const Path: string; AbortOnFailure: Boolean; Progress: TDelTreeProgress): Boolean;
function DiskInDrive(Drive: Char): Boolean;
{$ENDIF MSWINDOWS}
function DirectoryExists(const Name: string {$IFDEF UNIX}; ResolveSymLinks: Boolean = True {$ENDIF}): Boolean;
function FileCreateTemp(var Prefix: string): THandle;
//DELCIO function FileBackup(const FileName: string; Move: Boolean = False): Boolean;
function FileCopy(const ExistingFileName, NewFileName: string; ReplaceExisting: Boolean = False): Boolean;
function FileDateTime(const FileName: string): TDateTime;
//DELCIO function FileDelete(const FileName: string; MoveToRecycleBin: Boolean = False): Boolean;
function FileExists(const FileName: string): Boolean;
/// <summary>procedure FileHistory Creates a list of history files of a specified
/// source file. Each version of the file get's an extention .~<Nr>~ The file with
/// the lowest number is the youngest file.
/// </summary>
/// <param name="FileName"> (string) Name of the source file</param>
/// <param name="HistoryPath"> (string) Folder where the history files should be
/// created. If no folder is defined the folder of the source file is used.</param>
/// <param name="MaxHistoryCount"> (Integer) Max number of files</param>
/// <param name="MinFileDate"> (TDateTime) Timestamp how old the file has to be to
/// create a new history version. For example: NOW-1/24 => Only once per hour a new
/// history file is created. Default 0 means allways
/// <param name="ReplaceExtention"> (boolean) Flag to define that the history file
/// extention should replace the current extention or should be added at the
/// end</param>
/// </param>
(*DELCIO procedure FileHistory(const FileName: string; HistoryPath: string = ''; MaxHistoryCount: Integer = 100; MinFileDate:
TDateTime = 0; ReplaceExtention: Boolean = true); *)
//DELCIO function FileMove(const ExistingFileName, NewFileName: string; ReplaceExisting: Boolean = False): Boolean;
//DELCIO function FileRestore(const FileName: string): Boolean;
function GetBackupFileName(const FileName: string): string;
function IsBackupFileName(const FileName: string): Boolean;
function FileGetDisplayName(const FileName: string): string;
//DELCIO function FileGetGroupName(const FileName: string {$IFDEF UNIX}; ResolveSymLinks: Boolean = True {$ENDIF}): string;
//DELCIO function FileGetOwnerName(const FileName: string {$IFDEF UNIX}; ResolveSymLinks: Boolean = True {$ENDIF}): string;
function FileGetSize(const FileName: string): Int64;
function FileGetTempName(const Prefix: string): string;
{$IFDEF MSWINDOWS}
function FileGetTypeName(const FileName: string): string;
{$ENDIF MSWINDOWS}
function FindUnusedFileName(FileName: string; const FileExt: string; NumberPrefix: string = ''): string;
function ForceDirectories(Name: string): Boolean;
function GetDirectorySize(const Path: string): Int64;
{$IFDEF MSWINDOWS}
function GetDriveTypeStr(const Drive: Char): string;
function GetFileAgeCoherence(const FileName: string): Boolean;
{$ENDIF MSWINDOWS}
procedure GetFileAttributeList(const Items: TStrings; const Attr: Integer);
{$IFDEF MSWINDOWS}
procedure GetFileAttributeListEx(const Items: TStrings; const Attr: Integer);
{$ENDIF MSWINDOWS}
function GetFileInformation(const FileName: string; out FileInfo: TSearchRec): Boolean; overload;
function GetFileInformation(const FileName: string): TSearchRec; overload;
{$IFDEF UNIX}
function GetFileStatus(const FileName: string; out StatBuf: TStatBuf64;
const ResolveSymLinks: Boolean): Integer;
{$ENDIF UNIX}
{$IFDEF MSWINDOWS}
//DELCIO function GetFileLastWrite(const FileName: string): TFileTime; overload;
//DELCIO function GetFileLastWrite(const FileName: string; out LocalTime: TDateTime): Boolean; overload;
//DELCIO function GetFileLastAccess(const FileName: string): TFileTime; overload;
//DELCIO function GetFileLastAccess(const FileName: string; out LocalTime: TDateTime): Boolean; overload;
//DELCIO function GetFileCreation(const FileName: string): TFileTime; overload;
//DELCIO function GetFileCreation(const FileName: string; out LocalTime: TDateTime): Boolean; overload;
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
function GetFileLastWrite(const FileName: string; out TimeStamp: Integer; ResolveSymLinks: Boolean = True): Boolean; overload;
function GetFileLastWrite(const FileName: string; out LocalTime: TDateTime; ResolveSymLinks: Boolean = True): Boolean; overload;
function GetFileLastWrite(const FileName: string; ResolveSymLinks: Boolean = True): Integer; overload;
function GetFileLastAccess(const FileName: string; out TimeStamp: Integer; ResolveSymLinks: Boolean = True): Boolean; overload;
function GetFileLastAccess(const FileName: string; out LocalTime: TDateTime; ResolveSymLinks: Boolean = True): Boolean; overload;
function GetFileLastAccess(const FileName: string; ResolveSymLinks: Boolean = True): Integer; overload;
function GetFileLastAttrChange(const FileName: string; out TimeStamp: Integer; ResolveSymLinks: Boolean = True): Boolean; overload;
function GetFileLastAttrChange(const FileName: string; out LocalTime: TDateTime; ResolveSymLinks: Boolean = True): Boolean; overload;
function GetFileLastAttrChange(const FileName: string; ResolveSymLinks: Boolean = True): Integer; overload;
{$ENDIF UNIX}
function GetModulePath(const Module: HMODULE): string;
function GetSizeOfFile(const FileName: string): Int64; overload;
function GetSizeOfFile(const FileInfo: TSearchRec): Int64; overload;
{$IFDEF MSWINDOWS}
function GetSizeOfFile(Handle: THandle): Int64; overload;
function GetStandardFileInfo(const FileName: string): TWin32FileAttributeData;
{$ENDIF MSWINDOWS}
function IsDirectory(const FileName: string {$IFDEF UNIX}; ResolveSymLinks: Boolean = True {$ENDIF}): Boolean;
function IsRootDirectory(const CanonicFileName: string): Boolean;
{$IFDEF MSWINDOWS}
function LockVolume(const Volume: string; var Handle: THandle): Boolean;
function OpenVolume(const Drive: Char): THandle;
//function SetDirLastWrite(const DirName: string; const DateTime: TDateTime; RequireBackupRestorePrivileges: Boolean = True): Boolean;
//function SetDirLastAccess(const DirName: string; const DateTime: TDateTime; RequireBackupRestorePrivileges: Boolean = True): Boolean;
//function SetDirCreation(const DirName: string; const DateTime: TDateTime; RequireBackupRestorePrivileges: Boolean = True): Boolean;
{$ENDIF MSWINDOWS}
function SetFileLastWrite(const FileName: string; const DateTime: TDateTime): Boolean;
function SetFileLastAccess(const FileName: string; const DateTime: TDateTime): Boolean;
{$IFDEF MSWINDOWS}
function SetFileCreation(const FileName: string; const DateTime: TDateTime): Boolean;
procedure ShredFile(const FileName: string; Times: Integer = 1);
function UnlockVolume(var Handle: THandle): Boolean;
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
function CreateSymbolicLink(const Name, Target: string): Boolean;
{ This function gets the value of the symbolic link filename. }
function SymbolicLinkTarget(const Name: string): string;
{$ENDIF UNIX}
// TJclFileAttributeMask
//
// File search helper class, allows to specify required/rejected attributes
type
TAttributeInterest = (aiIgnored, aiRejected, aiRequired);
TJclCustomFileAttrMask = class(TPersistent)
private
FRequiredAttr: Integer;
FRejectedAttr: Integer;
function GetAttr(Index: Integer): TAttributeInterest;
procedure SetAttr(Index: Integer; const Value: TAttributeInterest);
procedure ReadRequiredAttributes(Reader: TReader);
procedure ReadRejectedAttributes(Reader: TReader);
procedure WriteRequiredAttributes(Writer: TWriter);
procedure WriteRejectedAttributes(Writer: TWriter);
protected
procedure DefineProperties(Filer: TFiler); override;
property ReadOnly: TAttributeInterest index faReadOnly
read GetAttr write SetAttr stored False;
property Hidden: TAttributeInterest index faHidden
read GetAttr write SetAttr stored False;
property System: TAttributeInterest index faSysFile
read GetAttr write SetAttr stored False;
property Directory: TAttributeInterest index faDirectory
read GetAttr write SetAttr stored False;
property SymLink: TAttributeInterest index faSymLink
read GetAttr write SetAttr stored False;
property Normal: TAttributeInterest index faNormalFile
read GetAttr write SetAttr stored False;
property Archive: TAttributeInterest index faArchive
read GetAttr write SetAttr stored False;
property Temporary: TAttributeInterest index faTemporary
read GetAttr write SetAttr stored False;
property SparseFile: TAttributeInterest index faSparseFile
read GetAttr write SetAttr stored False;
property ReparsePoint: TAttributeInterest index faReparsePoint
read GetAttr write SetAttr stored False;
property Compressed: TAttributeInterest index faCompressed
read GetAttr write SetAttr stored False;
property OffLine: TAttributeInterest index faOffline
read GetAttr write SetAttr stored False;
property NotContentIndexed: TAttributeInterest index faNotContentIndexed
read GetAttr write SetAttr stored False;
property Encrypted: TAttributeInterest index faEncrypted
read GetAttr write SetAttr stored False;
public
constructor Create;
procedure Assign(Source: TPersistent); override;
procedure Clear;
function Match(FileAttributes: Integer): Boolean; overload;
function Match(const FileInfo: TSearchRec): Boolean; overload;
property Required: Integer read FRequiredAttr write FRequiredAttr;
property Rejected: Integer read FRejectedAttr write FRejectedAttr;
property Attribute[Index: Integer]: TAttributeInterest read GetAttr write SetAttr; default;
end;
TJclFileAttributeMask = class(TJclCustomFileAttrMask)
private
procedure ReadVolumeID(Reader: TReader);
protected
procedure DefineProperties(Filer: TFiler); override;
published
property ReadOnly;
property Hidden;
property System;
property Directory;
property Normal;
{$IFDEF UNIX}
property SymLink;
{$ENDIF UNIX}
{$IFDEF MSWINDOWS}
property Archive;
property Temporary;
property SparseFile;
property ReparsePoint;
property Compressed;
property OffLine;
property NotContentIndexed;
property Encrypted;
{$ENDIF MSWINDOWS}
end;
type
TFileSearchOption = (fsIncludeSubDirectories, fsIncludeHiddenSubDirectories, fsLastChangeAfter,
fsLastChangeBefore, fsMaxSize, fsMinSize);
TFileSearchOptions = set of TFileSearchOption;
TFileSearchTaskID = Integer;
TFileSearchTerminationEvent = procedure (const ID: TFileSearchTaskID; const Aborted: Boolean) of object;
TFileEnumeratorSyncMode = (smPerFile, smPerDirectory);
// IJclFileSearchOptions
//
// Interface for file search options
type
IJclFileSearchOptions = interface
['{B73D9E3D-34C5-4DA9-88EF-4CA730328FC9}']
function GetAttributeMask: TJclFileAttributeMask;
function GetCaseSensitiveSearch: Boolean;
function GetRootDirectories: TStrings;
function GetRootDirectory: string;
function GetFileMask: string;
function GetFileMasks: TStrings;
function GetFileSizeMax: Int64;
function GetFileSizeMin: Int64;
function GetIncludeSubDirectories: Boolean;
function GetIncludeHiddenSubDirectories: Boolean;
function GetLastChangeAfter: TDateTime;
function GetLastChangeBefore: TDateTime;
function GetLastChangeAfterStr: string;
function GetLastChangeBeforeStr: string;
function GetSubDirectoryMask: string;
function GetOption(const Option: TFileSearchOption): Boolean;
function GetOptions: TFileSearchoptions;
procedure SetAttributeMask(const Value: TJclFileAttributeMask);
procedure SetCaseSensitiveSearch(const Value: Boolean);
procedure SetRootDirectories(const Value: TStrings);
procedure SetRootDirectory(const Value: string);
procedure SetFileMask(const Value: string);
procedure SetFileMasks(const Value: TStrings);
procedure SetFileSizeMax(const Value: Int64);
procedure SetFileSizeMin(const Value: Int64);
procedure SetIncludeSubDirectories(const Value: Boolean);
procedure SetIncludeHiddenSubDirectories(const Value: Boolean);
procedure SetLastChangeAfter(const Value: TDateTime);
procedure SetLastChangeBefore(const Value: TDateTime);
procedure SetLastChangeAfterStr(const Value: string);
procedure SetLastChangeBeforeStr(const Value: string);
procedure SetOption(const Option: TFileSearchOption; const Value: Boolean);
procedure SetOptions(const Value: TFileSearchOptions);
procedure SetSubDirectoryMask(const Value: string);
// properties
property CaseSensitiveSearch: Boolean read GetCaseSensitiveSearch write SetCaseSensitiveSearch;
property RootDirectories: TStrings read GetRootDirectories write SetRootDirectories;
property RootDirectory: string read GetRootDirectory write SetRootDirectory;
property FileMask: string read GetFileMask write SetFileMask;
property SubDirectoryMask: string read GetSubDirectoryMask write SetSubDirectoryMask;
property AttributeMask: TJclFileAttributeMask read GetAttributeMask write SetAttributeMask;
property FileSizeMin: Int64 read GetFileSizeMin write SetFileSizeMin;
property FileSizeMax: Int64 read GetFileSizeMax write SetFileSizeMax; // default InvalidFileSize;
property LastChangeAfter: TDateTime read GetLastChangeAfter write SetLastChangeAfter;
property LastChangeBefore: TDateTime read GetLastChangeBefore write SetLastChangeBefore;
property LastChangeAfterAsString: string read GetLastChangeAfterStr write SetLastChangeAfterStr;
property LastChangeBeforeAsString: string read GetLastChangeBeforeStr write SetLastChangeBeforeStr;
property IncludeSubDirectories: Boolean read GetIncludeSubDirectories
write SetIncludeSubDirectories;
property IncludeHiddenSubDirectories: Boolean read GetIncludeHiddenSubDirectories
write SetIncludeHiddenSubDirectories;
end;
// IJclFileSearchOptions
//
// Interface for file search options
type
TJclFileSearchOptions = class(TJclInterfacedPersistent, IJclFileSearchOptions)
protected
FFileMasks: TStringList;
FRootDirectories: TStringList;
FSubDirectoryMask: string;
FAttributeMask: TJclFileAttributeMask;
FFileSizeMin: Int64;
FFileSizeMax: Int64;
FLastChangeBefore: TDateTime;
FLastChangeAfter: TDateTime;
FOptions: TFileSearchOptions;
FCaseSensitiveSearch: Boolean;
function IsLastChangeAfterStored: Boolean;
function IsLastChangeBeforeStored: Boolean;
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
{ IJclFileSearchOptions }
function GetAttributeMask: TJclFileAttributeMask;
function GetCaseSensitiveSearch: Boolean;
function GetRootDirectories: TStrings;
function GetRootDirectory: string;
function GetFileMask: string;
function GetFileMasks: TStrings;
function GetFileSizeMax: Int64;
function GetFileSizeMin: Int64;
function GetIncludeSubDirectories: Boolean;
function GetIncludeHiddenSubDirectories: Boolean;
function GetLastChangeAfter: TDateTime;
function GetLastChangeBefore: TDateTime;
function GetLastChangeAfterStr: string;
function GetLastChangeBeforeStr: string;
function GetSubDirectoryMask: string;
function GetOption(const Option: TFileSearchOption): Boolean;
function GetOptions: TFileSearchoptions;
procedure SetAttributeMask(const Value: TJclFileAttributeMask);
procedure SetCaseSensitiveSearch(const Value: Boolean);
procedure SetRootDirectories(const Value: TStrings);
procedure SetRootDirectory(const Value: string);
procedure SetFileMask(const Value: string);
procedure SetFileMasks(const Value: TStrings);
procedure SetFileSizeMax(const Value: Int64);
procedure SetFileSizeMin(const Value: Int64);
procedure SetIncludeSubDirectories(const Value: Boolean);
procedure SetIncludeHiddenSubDirectories(const Value: Boolean);
procedure SetLastChangeAfter(const Value: TDateTime);
procedure SetLastChangeBefore(const Value: TDateTime);
procedure SetLastChangeAfterStr(const Value: string);
procedure SetLastChangeBeforeStr(const Value: string);
procedure SetOption(const Option: TFileSearchOption; const Value: Boolean);
procedure SetOptions(const Value: TFileSearchOptions);
procedure SetSubDirectoryMask(const Value: string);
published
property CaseSensitiveSearch: Boolean read GetCaseSensitiveSearch write SetCaseSensitiveSearch
default {$IFDEF MSWINDOWS} False {$ELSE} True {$ENDIF};
property FileMasks: TStrings read GetFileMasks write SetFileMasks;
property RootDirectories: TStrings read GetRootDirectories write SetRootDirectories;
property RootDirectory: string read GetRootDirectory write SetRootDirectory;
property SubDirectoryMask: string read FSubDirectoryMask write FSubDirectoryMask;
property AttributeMask: TJclFileAttributeMask read FAttributeMask write SetAttributeMask;
property FileSizeMin: Int64 read FFileSizeMin write FFileSizeMin;
property FileSizeMax: Int64 read FFileSizeMax write FFileSizeMax;
property LastChangeAfter: TDateTime read FLastChangeAfter write FLastChangeAfter
stored IsLastChangeAfterStored;
property LastChangeBefore: TDateTime read FLastChangeBefore write FLastChangeBefore
stored IsLastChangeBeforeStored;
property Options: TFileSearchOptions read FOptions write FOptions
default [fsIncludeSubDirectories];
end;
// IJclFileEnumerator
//
// Interface for thread-based file search
type
IJclFileEnumerator = interface(IJclFileSearchOptions)
['{F7E747ED-1C41-441F-B25B-BB314E00C4E9}']
// property access methods
function GetRunningTasks: Integer;
function GetSynchronizationMode: TFileEnumeratorSyncMode;
function GetOnEnterDirectory: TFileHandler;
function GetOnTerminateTask: TFileSearchTerminationEvent;
procedure SetSynchronizationMode(const Value: TFileEnumeratorSyncMode);
procedure SetOnEnterDirectory(const Value: TFileHandler);
procedure SetOnTerminateTask(const Value: TFileSearchTerminationEvent);
// other methods
function FillList(List: TStrings): TFileSearchTaskID;
function ForEach(Handler: TFileHandler): TFileSearchTaskID; overload;
function ForEach(Handler: TFileHandlerEx): TFileSearchTaskID; overload;
procedure StopTask(ID: TFileSearchTaskID);
procedure StopAllTasks(Silently: Boolean = False); // Silently: Don't call OnTerminateTask
// properties
property RunningTasks: Integer read GetRunningTasks;
property SynchronizationMode: TFileEnumeratorSyncMode read GetSynchronizationMode
write SetSynchronizationMode;
property OnEnterDirectory: TFileHandler read GetOnEnterDirectory write SetOnEnterDirectory;
property OnTerminateTask: TFileSearchTerminationEvent read GetOnTerminateTask
write SetOnTerminateTask;
end;
// TJclFileEnumerator
//
// Class for thread-based file search
type
TJclFileEnumerator = class(TJclFileSearchOptions, IInterface, IJclFileSearchOptions, IJclFileEnumerator)
private
FTasks: TList;
FOnEnterDirectory: TFileHandler;
FOnTerminateTask: TFileSearchTerminationEvent;
FNextTaskID: TFileSearchTaskID;
FSynchronizationMode: TFileEnumeratorSyncMode;
function GetNextTaskID: TFileSearchTaskID;
protected
function CreateTask: TThread;
procedure TaskTerminated(Sender: TObject);
property NextTaskID: TFileSearchTaskID read GetNextTaskID;
public
constructor Create;
destructor Destroy; override;
{ IJclFileEnumerator }
function GetRunningTasks: Integer;
function GetSynchronizationMode: TFileEnumeratorSyncMode;
function GetOnEnterDirectory: TFileHandler;
function GetOnTerminateTask: TFileSearchTerminationEvent;
procedure SetSynchronizationMode(const Value: TFileEnumeratorSyncMode);
procedure SetOnEnterDirectory(const Value: TFileHandler);
procedure SetOnTerminateTask(const Value: TFileSearchTerminationEvent);
procedure Assign(Source: TPersistent); override;
function FillList(List: TStrings): TFileSearchTaskID;
function ForEach(Handler: TFileHandler): TFileSearchTaskID; overload;
function ForEach(Handler: TFileHandlerEx): TFileSearchTaskID; overload;
procedure StopTask(ID: TFileSearchTaskID);
procedure StopAllTasks(Silently: Boolean = False); // Silently: Don't call OnTerminateTask
property FileMask: string read GetFileMask write SetFileMask;
property IncludeSubDirectories: Boolean
read GetIncludeSubDirectories write SetIncludeSubDirectories;
property IncludeHiddenSubDirectories: Boolean
read GetIncludeHiddenSubDirectories write SetIncludeHiddenSubDirectories;
property SearchOption[const Option: TFileSearchOption]: Boolean read GetOption write SetOption;
property LastChangeAfterAsString: string read GetLastChangeAfterStr write SetLastChangeAfterStr;
property LastChangeBeforeAsString: string read GetLastChangeBeforeStr write SetLastChangeBeforeStr;
published
property RunningTasks: Integer read GetRunningTasks;
property SynchronizationMode: TFileEnumeratorSyncMode read FSynchronizationMode write FSynchronizationMode
default smPerDirectory;
property OnEnterDirectory: TFileHandler read FOnEnterDirectory write FOnEnterDirectory;
property OnTerminateTask: TFileSearchTerminationEvent read FOnTerminateTask write FOnTerminateTask;
end;
function FileSearch: IJclFileEnumerator;
{$IFDEF MSWINDOWS}
// TFileVersionInfo
//
// Class that enables reading the version information stored in a PE file.
type
TFileFlag = (ffDebug, ffInfoInferred, ffPatched, ffPreRelease, ffPrivateBuild, ffSpecialBuild);
TFileFlags = set of TFileFlag;
PLangIdRec = ^TLangIdRec;
TLangIdRec = packed record
case Integer of
0: (
LangId: Word;
CodePage: Word);
1: (
Pair: DWORD);
end;
EJclFileVersionInfoError = class(EJclError);
TJclFileVersionInfo = class(TObject)
private
FBuffer: AnsiString;
FFixedInfo: PVSFixedFileInfo;
FFileFlags: TFileFlags;
FItemList: TStringList;
FItems: TStringList;
FLanguages: array of TLangIdRec;
FLanguageIndex: Integer;
FTranslations: array of TLangIdRec;
function GetFixedInfo: TVSFixedFileInfo;
function GetItems: TStrings;
function GetLanguageCount: Integer;
function GetLanguageIds(Index: Integer): string;
function GetLanguageNames(Index: Integer): string;
function GetLanguages(Index: Integer): TLangIdRec;
function GetTranslationCount: Integer;
function GetTranslations(Index: Integer): TLangIdRec;
procedure SetLanguageIndex(const Value: Integer);
protected
procedure CreateItemsForLanguage;
procedure CheckLanguageIndex(Value: Integer);
procedure ExtractData;
procedure ExtractFlags;
function GetBinFileVersion: string;
function GetBinProductVersion: string;
function GetFileOS: DWORD;
function GetFileSubType: DWORD;
function GetFileType: DWORD;
function GetFileVersionBuild: string;
function GetFileVersionMajor: string;
function GetFileVersionMinor: string;
function GetFileVersionRelease: string;
function GetProductVersionBuild: string;
function GetProductVersionMajor: string;
function GetProductVersionMinor: string;
function GetProductVersionRelease: string;
function GetVersionKeyValue(Index: Integer): string;
public
constructor Attach(VersionInfoData: Pointer; Size: Integer);
constructor Create(const FileName: string); overload;
{$IFDEF MSWINDOWS}
{$IFDEF FPC}
constructor Create(const Window: HWND; Dummy: Pointer = nil); overload;
{$ELSE}
constructor Create(const Window: HWND); overload;
{$ENDIF}
constructor Create(const Module: HMODULE); overload;
{$ENDIF MSWINDOWS}
destructor Destroy; override;
function GetCustomFieldValue(const FieldName: string): string;
class function VersionLanguageId(const LangIdRec: TLangIdRec): string;
class function VersionLanguageName(const LangId: Word): string;
class function FileHasVersionInfo(const FileName: string): boolean;
function TranslationMatchesLanguages(Exact: Boolean = True): Boolean;
property BinFileVersion: string read GetBinFileVersion;
property BinProductVersion: string read GetBinProductVersion;
property Comments: string index 1 read GetVersionKeyValue;
property CompanyName: string index 2 read GetVersionKeyValue;
property FileDescription: string index 3 read GetVersionKeyValue;
property FixedInfo: TVSFixedFileInfo read GetFixedInfo;
property FileFlags: TFileFlags read FFileFlags;
property FileOS: DWORD read GetFileOS;
property FileSubType: DWORD read GetFileSubType;
property FileType: DWORD read GetFileType;
property FileVersion: string index 4 read GetVersionKeyValue;
property FileVersionBuild: string read GetFileVersionBuild;
property FileVersionMajor: string read GetFileVersionMajor;
property FileVersionMinor: string read GetFileVersionMinor;
property FileVersionRelease: string read GetFileVersionRelease;
property Items: TStrings read GetItems;
property InternalName: string index 5 read GetVersionKeyValue;
property LanguageCount: Integer read GetLanguageCount;
property LanguageIds[Index: Integer]: string read GetLanguageIds;
property LanguageIndex: Integer read FLanguageIndex write SetLanguageIndex;
property Languages[Index: Integer]: TLangIdRec read GetLanguages;
property LanguageNames[Index: Integer]: string read GetLanguageNames;
property LegalCopyright: string index 6 read GetVersionKeyValue;
property LegalTradeMarks: string index 7 read GetVersionKeyValue;
property OriginalFilename: string index 8 read GetVersionKeyValue;
property PrivateBuild: string index 12 read GetVersionKeyValue;
property ProductName: string index 9 read GetVersionKeyValue;
property ProductVersion: string index 10 read GetVersionKeyValue;
property ProductVersionBuild: string read GetProductVersionBuild;
property ProductVersionMajor: string read GetProductVersionMajor;
property ProductVersionMinor: string read GetProductVersionMinor;
property ProductVersionRelease: string read GetProductVersionRelease;
property SpecialBuild: string index 11 read GetVersionKeyValue;
property TranslationCount: Integer read GetTranslationCount;
property Translations[Index: Integer]: TLangIdRec read GetTranslations;
end;
function OSIdentToString(const OSIdent: DWORD): string;
function OSFileTypeToString(const OSFileType: DWORD; const OSFileSubType: DWORD = 0): string;
function VersionResourceAvailable(const FileName: string): Boolean; overload;
function VersionResourceAvailable(const Window: HWND): Boolean; overload;
function VersionResourceAvailable(const Module: HMODULE): Boolean; overload;
function WindowToModuleFileName(const Window: HWND): string;
{$ENDIF MSWINDOWS}
// Version Info formatting
type
TFileVersionFormat = (vfMajorMinor, vfFull);
function FormatVersionString(const HiV, LoV: Word): string; overload;
function FormatVersionString(const Major, Minor, Build, Revision: Word): string; overload;
{$IFDEF MSWINDOWS}
function FormatVersionString(const FixedInfo: TVSFixedFileInfo; VersionFormat: TFileVersionFormat = vfFull): string; overload;
// Version Info extracting
procedure VersionExtractFileInfo(const FixedInfo: TVSFixedFileInfo; var Major, Minor, Build, Revision: Word);
procedure VersionExtractProductInfo(const FixedInfo: TVSFixedFileInfo; var Major, Minor, Build, Revision: Word);
// Fixed Version Info routines
function VersionFixedFileInfo(const FileName: string; var FixedInfo: TVSFixedFileInfo): Boolean;
function VersionFixedFileInfoString(const FileName: string; VersionFormat: TFileVersionFormat = vfFull;
const NotAvailableText: string = ''): string;
{$ENDIF MSWINDOWS}
// Streams
//
// TStream descendent classes for dealing with temporary files and for using file mapping objects.
type
TJclTempFileStream = class(THandleStream)
private
FFileName: string;
public
constructor Create(const Prefix: string);
destructor Destroy; override;
property FileName: string read FFileName;
end;
{$IFDEF MSWINDOWS}
TJclCustomFileMapping = class;
TJclFileMappingView = class(TCustomMemoryStream)
private
FFileMapping: TJclCustomFileMapping;
FOffsetHigh: Cardinal;
FOffsetLow: Cardinal;
function GetIndex: Integer;
function GetOffset: Int64;
public
constructor Create(const FileMap: TJclCustomFileMapping;
Access, Size: Cardinal; ViewOffset: Int64);
constructor CreateAt(FileMap: TJclCustomFileMapping; Access,
Size: Cardinal; ViewOffset: Int64; Address: Pointer);
destructor Destroy; override;
function Flush(const Count: Cardinal): Boolean;
procedure LoadFromStream(const Stream: TStream);
procedure LoadFromFile(const FileName: string);
function Write(const Buffer; Count: Longint): Longint; override;
property Index: Integer read GetIndex;
property FileMapping: TJclCustomFileMapping read FFileMapping;
property Offset: Int64 read GetOffset;
end;
TJclFileMappingRoundOffset = (rvDown, rvUp);
TJclCustomFileMapping = class(TObject)
private
FExisted: Boolean;
FHandle: THandle;
FName: string;
FRoundViewOffset: TJclFileMappingRoundOffset;
FViews: TList;
function GetCount: Integer;
function GetView(Index: Integer): TJclFileMappingView;
protected
procedure ClearViews;
procedure InternalCreate(const FileHandle: THandle; const Name: string;
const Protect: Cardinal; MaximumSize: Int64; SecAttr: PSecurityAttributes);
procedure InternalOpen(const Name: string; const InheritHandle: Boolean;
const DesiredAccess: Cardinal);
public
constructor Create;
constructor Open(const Name: string; const InheritHandle: Boolean; const DesiredAccess: Cardinal);
destructor Destroy; override;
function Add(const Access, Count: Cardinal; const Offset: Int64): Integer;
function AddAt(const Access, Count: Cardinal; const Offset: Int64; const Address: Pointer): Integer;
procedure Delete(const Index: Integer);
function IndexOf(const View: TJclFileMappingView): Integer;
property Count: Integer read GetCount;
property Existed: Boolean read FExisted;
property Handle: THandle read FHandle;
property Name: string read FName;
property RoundViewOffset: TJclFileMappingRoundOffset read FRoundViewOffset write FRoundViewOffset;
property Views[index: Integer]: TJclFileMappingView read GetView;
end;
TJclFileMapping = class(TJclCustomFileMapping)
private
FFileHandle: THandle;
public
constructor Create(const FileName: string; FileMode: Cardinal;
const Name: string; Protect: Cardinal; const MaximumSize: Int64;
SecAttr: PSecurityAttributes); overload;
constructor Create(const FileHandle: THandle; const Name: string;
Protect: Cardinal; const MaximumSize: Int64;
SecAttr: PSecurityAttributes); overload;
destructor Destroy; override;
property FileHandle: THandle read FFileHandle;
end;
TJclSwapFileMapping = class(TJclCustomFileMapping)
public
constructor Create(const Name: string; Protect: Cardinal;
const MaximumSize: Int64; SecAttr: PSecurityAttributes);
end;
TJclFileMappingStream = class(TCustomMemoryStream)
private
FFileHandle: THandle;
FMapping: THandle;
protected
procedure Close;
public
constructor Create(const FileName: string; FileMode: Word = fmOpenRead or fmShareDenyWrite);
destructor Destroy; override;
function Write(const Buffer; Count: Longint): Longint; override;
end;
{$ENDIF MSWINDOWS}
TJclMappedTextReaderIndex = (tiNoIndex, tiFull);
PPAnsiCharArray = ^TPAnsiCharArray;
TPAnsiCharArray = array [0..MaxInt div SizeOf(PAnsiChar) - 1] of PAnsiChar;
TJclAnsiMappedTextReader = class(TPersistent)
private
FContent: PAnsiChar;
FEnd: PAnsiChar;
FIndex: PPAnsiCharArray;
FIndexOption: TJclMappedTextReaderIndex;
FFreeStream: Boolean;
FLastLineNumber: Integer;
FLastPosition: PAnsiChar;
FLineCount: Integer;
FMemoryStream: TCustomMemoryStream;
FPosition: PAnsiChar;
FSize: Integer;
function GetAsString: AnsiString;
function GetEof: Boolean;
function GetChars(Index: Integer): AnsiChar;
function GetLineCount: Integer;
function GetLines(LineNumber: Integer): AnsiString;
function GetPosition: Integer;
function GetPositionFromLine(LineNumber: Integer): Integer;
procedure SetPosition(const Value: Integer);
protected
procedure AssignTo(Dest: TPersistent); override;
procedure CreateIndex;
procedure Init;
function PtrFromLine(LineNumber: Integer): PAnsiChar;
function StringFromPosition(var StartPos: PAnsiChar): AnsiString;
public
constructor Create(MemoryStream: TCustomMemoryStream; FreeStream: Boolean = True;
const AIndexOption: TJclMappedTextReaderIndex = tiNoIndex); overload;
constructor Create(const FileName: TFileName;
const AIndexOption: TJclMappedTextReaderIndex = tiNoIndex); overload;
destructor Destroy; override;
procedure GoBegin;
function Read: AnsiChar;
function ReadLn: AnsiString;
property AsString: AnsiString read GetAsString;
property Chars[Index: Integer]: AnsiChar read GetChars;
property Content: PAnsiChar read FContent;
property Eof: Boolean read GetEof;
property IndexOption: TJclMappedTextReaderIndex read FIndexOption;
property Lines[LineNumber: Integer]: AnsiString read GetLines;
property LineCount: Integer read GetLineCount;
property PositionFromLine[LineNumber: Integer]: Integer read GetPositionFromLine;
property Position: Integer read GetPosition write SetPosition;
property Size: Integer read FSize;
end;
PPWideCharArray = ^TPWideCharArray;
TPWideCharArray = array [0..MaxInt div SizeOf(PWideChar) - 1] of PWideChar;
TJclWideMappedTextReader = class(TPersistent)
private
FContent: PWideChar;
FEnd: PWideChar;
FIndex: PPWideCharArray;
FIndexOption: TJclMappedTextReaderIndex;
FFreeStream: Boolean;
FLastLineNumber: Integer;
FLastPosition: PWideChar;
FLineCount: Integer;
FMemoryStream: TCustomMemoryStream;
FPosition: PWideChar;
FSize: Integer;
function GetAsString: WideString;
function GetEof: Boolean;
function GetChars(Index: Integer): WideChar;
function GetLineCount: Integer;
function GetLines(LineNumber: Integer): WideString;
function GetPosition: Integer;
function GetPositionFromLine(LineNumber: Integer): Integer;
procedure SetPosition(const Value: Integer);
protected
procedure AssignTo(Dest: TPersistent); override;
procedure CreateIndex;
procedure Init;
function PtrFromLine(LineNumber: Integer): PWideChar;
function StringFromPosition(var StartPos: PWideChar): WideString;
public
constructor Create(MemoryStream: TCustomMemoryStream; FreeStream: Boolean = True;
const AIndexOption: TJclMappedTextReaderIndex = tiNoIndex); overload;
constructor Create(const FileName: TFileName;
const AIndexOption: TJclMappedTextReaderIndex = tiNoIndex); overload;
destructor Destroy; override;
procedure GoBegin;
function Read: WideChar;
function ReadLn: WideString;
property AsString: WideString read GetAsString;
property Chars[Index: Integer]: WideChar read GetChars;
property Content: PWideChar read FContent;
property Eof: Boolean read GetEof;
property IndexOption: TJclMappedTextReaderIndex read FIndexOption;
property Lines[LineNumber: Integer]: WideString read GetLines;
property LineCount: Integer read GetLineCount;
property PositionFromLine[LineNumber: Integer]: Integer read GetPositionFromLine;
property Position: Integer read GetPosition write SetPosition;
property Size: Integer read FSize;
end;
{ TODO : UNTESTED/UNDOCUMENTED }
type
TJclFileMaskComparator = class(TObject)
private
FFileMask: string;
FExts: array of string;
FNames: array of string;
FWildChars: array of Byte;
FSeparator: Char;
procedure CreateMultiMasks;
function GetCount: Integer;
function GetExts(Index: Integer): string;
function GetMasks(Index: Integer): string;
function GetNames(Index: Integer): string;
procedure SetFileMask(const Value: string);
procedure SetSeparator(const Value: Char);
public
constructor Create;
function Compare(const NameExt: string): Boolean;
property Count: Integer read GetCount;
property Exts[Index: Integer]: string read GetExts;
property FileMask: string read FFileMask write SetFileMask;
property Masks[Index: Integer]: string read GetMasks;
property Names[Index: Integer]: string read GetNames;
property Separator: Char read FSeparator write SetSeparator;
end;
EJclPathError = class(EJclError);
EJclFileUtilsError = class(EJclError);
{$IFDEF UNIX}
EJclTempFileStreamError = class(EJclFileUtilsError);
{$ENDIF UNIX}
{$IFDEF MSWINDOWS}
EJclTempFileStreamError = class(EJclWin32Error);
EJclFileMappingError = class(EJclWin32Error);
EJclFileMappingViewError = class(EJclWin32Error);
{$ENDIF MSWINDOWS}
function SamePath(const Path1, Path2: string): Boolean;
// functions to add/delete paths from a separated list of paths
// on windows the separator is a semi-colon ';'
// on linux the separator is a colon ':'
// add items at the end
procedure PathListAddItems(var List: string; const Items: string);
// add items at the end if they are not present
procedure PathListIncludeItems(var List: string; const Items: string);
// delete multiple items
procedure PathListDelItems(var List: string; const Items: string);
// delete one item
procedure PathListDelItem(var List: string; const Index: Integer);
// return the number of item
function PathListItemCount(const List: string): Integer;
// return the Nth item
function PathListGetItem(const List: string; const Index: Integer): string;
// set the Nth item
procedure PathListSetItem(var List: string; const Index: Integer; const Value: string);
// return the index of an item
function PathListItemIndex(const List, Item: string): Integer;
// additional functions to access the commandline parameters of an application
// returns the name of the command line parameter at position index, which is
// separated by the given separator, if the first character of the name part
// is one of the AllowedPrefixCharacters, this character will be deleted.
function ParamName (Index : Integer; const Separator : string = '=';
const AllowedPrefixCharacters : string = '-/'; TrimName : Boolean = true) : string;
// returns the value of the command line parameter at position index, which is
// separated by the given separator
function ParamValue (Index : Integer; const Separator : string = '='; TrimValue : Boolean = true) : string; overload;
// seaches a command line parameter where the namepart is the searchname
// and returns the value which is which by the given separator.
// CaseSensitive defines the search type. if the first character of the name part
// is one of the AllowedPrefixCharacters, this character will be deleted.
function ParamValue (const SearchName : string; const Separator : string = '=';
CaseSensitive : Boolean = False;
const AllowedPrefixCharacters : string = '-/'; TrimValue : Boolean = true) : string; overload;
// seaches a command line parameter where the namepart is the searchname
// and returns the position index. if no separator is defined, the full paramstr is compared.
// CaseSensitive defines the search type. if the first character of the name part
// is one of the AllowedPrefixCharacters, this character will be deleted.
function ParamPos (const SearchName : string; const Separator : string = '=';
CaseSensitive : Boolean = False;
const AllowedPrefixCharacters : string = '-/'): Integer;
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$URL: jcl/source/common/JclFileUtils.pas $';
Revision: '$Revision: 14e6d6b003f774b2aab7dda32aa5aa66d67e3f2b $';
Date: '$Date: 2016-08-03 17:32:24 +0200 $';
LogPath: 'JCL\source\common';
Extra: '';
Data: nil
);
{$ENDIF UNITVERSIONING}
implementation
uses
{$IFDEF HAS_UNITSCOPE}
System.Types, // inlining of TList.Remove
{$IFDEF HAS_UNIT_CHARACTER}
System.Character,
{$ENDIF HAS_UNIT_CHARACTER}
System.Math,
{$IFDEF MSWINDOWS}
Winapi.ShellApi, Winapi.ActiveX, System.Win.ComObj, Winapi.ShlObj,
{DELCIO JclShell,} NVJclSysInfo, { DELCIO JclSecurity,}
{$ENDIF MSWINDOWS}
{$ELSE ~HAS_UNITSCOPE}
{$IFDEF HAS_UNIT_CHARACTER}
Character,
{$ENDIF HAS_UNIT_CHARACTER}
Math,
{$IFDEF MSWINDOWS}
ShellApi, ActiveX, ComObj, ShlObj,
JclShell, JclSysInfo, JclSecurity,
{$ENDIF MSWINDOWS}
{$ENDIF ~HAS_UNITSCOPE}
{DELCIO JclDateTime,} NVJclResources,
NVJclStrings;
{ Some general notes:
This unit redeclares some functions from FileCtrl.pas to avoid a dependency on that unit in the
JCL. The problem is that FileCtrl.pas uses some units (eg Forms.pas) which have ridiculous
initialization requirements. They add 4KB (!) to the executable and roughly 1 second of startup.
That initialization is only necessary for GUI applications and is unacceptable for high
performance services or console apps.
The routines which query files or directories for their attributes deliberately use FindFirst
even though there may be easier ways to get at the required information. This is because FindFirst
is about the only routine which doesn't cause the file's last modification/accessed time to be
changed which is usually an undesired side-effect. }
{$IFDEF UNIX}
const
ERROR_NO_MORE_FILES = -1;
INVALID_HANDLE_VALUE = THandle(-1);
{$ENDIF UNIX}
//=== { TJclTempFileStream } =================================================
constructor TJclTempFileStream.Create(const Prefix: string);
var
FileHandle: THandle;
begin
FFileName := Prefix;
FileHandle := FileCreateTemp(FFileName);
// (rom) is it really wise to throw an exception before calling inherited?
if FileHandle = INVALID_HANDLE_VALUE then
raise EJclTempFileStreamError.CreateRes(@RsFileStreamCreate);
inherited Create(FileHandle);
end;
destructor TJclTempFileStream.Destroy;
begin
if THandle(Handle) <> INVALID_HANDLE_VALUE then
FileClose(Handle);
inherited Destroy;
end;
//=== { TJclFileMappingView } ================================================
{$IFDEF MSWINDOWS}
constructor TJclFileMappingView.Create(const FileMap: TJclCustomFileMapping;
Access, Size: Cardinal; ViewOffset: Int64);
var
BaseAddress: Pointer;
OffsetLow, OffsetHigh: Cardinal;
begin
inherited Create;
if FileMap = nil then
raise EJclFileMappingViewError.CreateRes(@RsViewNeedsMapping);
FFileMapping := FileMap;
// Offset must be a multiple of system memory allocation granularity
RoundToAllocGranularity64(ViewOffset, FFileMapping.RoundViewOffset = rvUp);
I64ToCardinals(ViewOffset, OffsetLow, OffsetHigh);
FOffsetHigh := OffsetHigh;
FOffsetLow := OffsetLow;
BaseAddress := MapViewOfFile(FFileMapping.Handle, Access, FOffsetHigh, FOffsetLow, Size);
if BaseAddress = nil then
raise EJclFileMappingViewError.CreateRes(@RsCreateFileMappingView);
// If we are mapping a file and size = 0 then MapViewOfFile has mapped the entire file. We must
// figure out the size ourselves before we can call SetPointer. Since in case of failure to
// retrieve the size we raise an exception, we also have to explicitly unmap the view which
// otherwise would have been done by the destructor.
if (Size = 0) and (FileMap is TJclFileMapping) then
begin
Size := GetFileSize(TJclFileMapping(FileMap).FFileHandle, nil);
if Size = DWORD(-1) then
begin
UnMapViewOfFile(BaseAddress);
raise EJclFileMappingViewError.CreateRes(@RsFailedToObtainSize);
end;
end;
SetPointer(BaseAddress, Size);
FFileMapping.FViews.Add(Self);
end;
constructor TJclFileMappingView.CreateAt(FileMap: TJclCustomFileMapping;
Access, Size: Cardinal; ViewOffset: Int64; Address: Pointer);
var
BaseAddress: Pointer;
OffsetLow, OffsetHigh: Cardinal;
begin
inherited Create;
if FileMap = nil then
raise EJclFileMappingViewError.CreateRes(@RsViewNeedsMapping);
FFileMapping := FileMap;
// Offset must be a multiple of system memory allocation granularity
RoundToAllocGranularity64(ViewOffset, FFileMapping.RoundViewOffset = rvUp);
RoundToAllocGranularityPtr(Address, FFileMapping.RoundViewOffset = rvUp);
I64ToCardinals(ViewOffset, OffsetLow, OffsetHigh);
FOffsetHigh := OffsetHigh;
FOffsetLow := OffsetLow;
BaseAddress := MapViewOfFileEx(FFileMapping.Handle, Access, FOffsetHigh,
FOffsetLow, Size, Address);
if BaseAddress = nil then
raise EJclFileMappingViewError.CreateRes(@RsCreateFileMappingView);
// If we are mapping a file and size = 0 then MapViewOfFile has mapped the entire file. We must
// figure out the size ourselves before we can call SetPointer. Since in case of failure to
// retrieve the size we raise an exception, we also have to explicitly unmap the view which
// otherwise would have been done by the destructor.
if (Size = 0) and (FileMap is TJclFileMapping) then
begin
Size := GetFileSize(TJclFileMapping(FileMap).FFileHandle, nil);
if Size = DWORD(-1) then
begin
UnMapViewOfFile(BaseAddress);
raise EJclFileMappingViewError.CreateRes(@RsFailedToObtainSize);
end;
end;
SetPointer(BaseAddress, Size);
FFileMapping.FViews.Add(Self);
end;
destructor TJclFileMappingView.Destroy;
var
IndexOfSelf: Integer;
begin
if Memory <> nil then
begin
UnMapViewOfFile(Memory);
SetPointer(nil, 0);
end;
if FFileMapping <> nil then
begin
IndexOfSelf := FFileMapping.IndexOf(Self);
if IndexOfSelf <> -1 then
FFileMapping.FViews.Delete(IndexOfSelf);
end;
inherited Destroy;
end;
function TJclFileMappingView.Flush(const Count: Cardinal): Boolean;
begin
Result := FlushViewOfFile(Memory, Count);
end;
function TJclFileMappingView.GetIndex: Integer;
begin
Result := FFileMapping.IndexOf(Self);
end;
function TJclFileMappingView.GetOffset: Int64;
begin
CardinalsToI64(Result, FOffsetLow, FOffsetHigh);
end;
procedure TJclFileMappingView.LoadFromFile(const FileName: string);
var
Stream: TFileStream;
begin
Stream := TFileStream.Create(Filename, fmOpenRead or fmShareDenyWrite);
try
LoadFromStream(Stream);
finally
FreeAndNil(Stream);
end;
end;
procedure TJclFileMappingView.LoadFromStream(const Stream: TStream);
begin
if Stream.Size > Size then
raise EJclFileMappingViewError.CreateRes(@RsLoadFromStreamSize);
Stream.Position := 0;
Stream.ReadBuffer(Memory^, Stream.Size);
end;
function TJclFileMappingView.Write(const Buffer; Count: Integer): Longint;
begin
Result := 0;
if (Size - Position) >= Count then
begin
System.Move(Buffer, Pointer(TJclAddr(Memory) + TJclAddr(Position))^, Count);
Position := Position + Count;
Result := Count;
end;
end;
//=== { TJclCustomFileMapping } ==============================================
constructor TJclCustomFileMapping.Create;
begin
inherited Create;
FViews := TList.Create;
FRoundViewOffset := rvDown;
end;
constructor TJclCustomFileMapping.Open(const Name: string;
const InheritHandle: Boolean; const DesiredAccess: Cardinal);
begin
Create;
InternalOpen(Name, InheritHandle, DesiredAccess);
end;
destructor TJclCustomFileMapping.Destroy;
begin
ClearViews;
if FHandle <> 0 then
CloseHandle(FHandle);
FreeAndNil(FViews);
inherited Destroy;
end;
function TJclCustomFileMapping.Add(const Access, Count: Cardinal; const Offset: Int64): Integer;
var
View: TJclFileMappingView;
begin
// The view adds itself to the FViews list
View := TJclFileMappingView.Create(Self, Access, Count, Offset);
Result := View.Index;
end;
function TJclCustomFileMapping.AddAt(const Access, Count: Cardinal;
const Offset: Int64; const Address: Pointer): Integer;
var
View: TJclFileMappingView;
begin
// The view adds itself to the FViews list
View := TJclFileMappingView.CreateAt(Self, Access, Count, Offset, Address);
Result := View.Index;
end;
procedure TJclCustomFileMapping.ClearViews;
var
I: Integer;
begin
// Note that the view destructor removes the view object from the FViews list so we must loop
// downwards from count to 0
for I := FViews.Count - 1 downto 0 do
TJclFileMappingView(FViews[I]).Free;
end;
procedure TJclCustomFileMapping.Delete(const Index: Integer);
begin
// Note that the view destructor removes itself from FViews
TJclFileMappingView(FViews[Index]).Free;
end;
function TJclCustomFileMapping.GetCount: Integer;
begin
Result := FViews.Count;
end;
function TJclCustomFileMapping.GetView(Index: Integer): TJclFileMappingView;
begin
Result := TJclFileMappingView(FViews.Items[index]);
end;
function TJclCustomFileMapping.IndexOf(const View: TJclFileMappingView): Integer;
begin
Result := FViews.IndexOf(View);
end;
procedure TJclCustomFileMapping.InternalCreate(const FileHandle: THandle;
const Name: string; const Protect: Cardinal; MaximumSize: Int64;
SecAttr: PSecurityAttributes);
var
MaximumSizeLow, MaximumSizeHigh: Cardinal;
begin
FName := Name;
I64ToCardinals(MaximumSize, MaximumSizeLow, MaximumSizeHigh);
FHandle := CreateFileMapping(FileHandle, SecAttr, Protect, MaximumSizeHigh,
MaximumSizeLow, PChar(Name));
if FHandle = 0 then
raise EJclFileMappingError.CreateRes(@RsCreateFileMapping);
FExisted := GetLastError = ERROR_ALREADY_EXISTS;
end;
procedure TJclCustomFileMapping.InternalOpen(const Name: string;
const InheritHandle: Boolean; const DesiredAccess: Cardinal);
begin
FExisted := True;
FName := Name;
FHandle := OpenFileMapping(DesiredAccess, InheritHandle, PChar(Name));
if FHandle = 0 then
raise EJclFileMappingError.CreateRes(@RsCreateFileMapping);
end;
//=== { TJclFileMapping } ====================================================
constructor TJclFileMapping.Create(const FileName: string; FileMode: Cardinal;
const Name: string; Protect: Cardinal; const MaximumSize: Int64;
SecAttr: PSecurityAttributes);
begin
FFileHandle := INVALID_HANDLE_VALUE;
inherited Create;
FFileHandle := THandle(FileOpen(FileName, FileMode));
if FFileHandle = INVALID_HANDLE_VALUE then
raise EJclFileMappingError.CreateRes(@RsFileMappingOpenFile);
InternalCreate(FFileHandle, Name, Protect, MaximumSize, SecAttr);
end;
constructor TJclFileMapping.Create(const FileHandle: THandle; const Name: string;
Protect: Cardinal; const MaximumSize: Int64; SecAttr: PSecurityAttributes);
begin
FFileHandle := INVALID_HANDLE_VALUE;
inherited Create;
if FileHandle = INVALID_HANDLE_VALUE then
raise EJclFileMappingError.CreateRes(@RsFileMappingInvalidHandle);
InternalCreate(FileHandle, Name, Protect, MaximumSize, SecAttr);
// Duplicate the handle into FFileHandle as opposed to assigning it directly. This will cause
// FFileHandle to retrieve a unique copy which is independent of FileHandle. This makes the
// remainder of the class, especially the destructor, easier. The caller will have to close it's
// own copy of the handle explicitly.
DuplicateHandle(GetCurrentProcess, FileHandle, GetCurrentProcess,
@FFileHandle, 0, False, DUPLICATE_SAME_ACCESS);
end;
destructor TJclFileMapping.Destroy;
begin
if FFileHandle <> INVALID_HANDLE_VALUE then
CloseHandle(FFileHandle);
inherited Destroy;
end;
//=== { TJclSwapFileMapping } ================================================
constructor TJclSwapFileMapping.Create(const Name: string; Protect: Cardinal;
const MaximumSize: Int64; SecAttr: PSecurityAttributes);
begin
inherited Create;
InternalCreate(INVALID_HANDLE_VALUE, Name, Protect, MaximumSize, SecAttr);
end;
//=== { TJclFileMappingStream } ==============================================
constructor TJclFileMappingStream.Create(const FileName: string; FileMode: Word);
var
Protect, Access, Size: DWORD;
BaseAddress: Pointer;
begin
inherited Create;
FFileHandle := THandle(FileOpen(FileName, FileMode));
if FFileHandle = INVALID_HANDLE_VALUE then
RaiseLastOSError;
if (FileMode and $0F) = fmOpenReadWrite then
begin
Protect := PAGE_WRITECOPY;
Access := FILE_MAP_COPY;
end
else
begin
Protect := PAGE_READONLY;
Access := FILE_MAP_READ;
end;
FMapping := CreateFileMapping(FFileHandle, nil, Protect, 0, 0, nil);
if FMapping = 0 then
begin
Close;
raise EJclFileMappingError.CreateRes(@RsCreateFileMapping);
end;
BaseAddress := MapViewOfFile(FMapping, Access, 0, 0, 0);
if BaseAddress = nil then
begin
Close;
raise EJclFileMappingViewError.CreateRes(@RsCreateFileMappingView);
end;
Size := GetFileSize(FFileHandle, nil);
if Size = DWORD(-1) then
begin
UnMapViewOfFile(BaseAddress);
Close;
raise EJclFileMappingViewError.CreateRes(@RsFailedToObtainSize);
end;
SetPointer(BaseAddress, Size);
end;
destructor TJclFileMappingStream.Destroy;
begin
Close;
inherited Destroy;
end;
procedure TJclFileMappingStream.Close;
begin
if Memory <> nil then
begin
UnMapViewOfFile(Memory);
SetPointer(nil, 0);
end;
if FMapping <> 0 then
begin
CloseHandle(FMapping);
FMapping := 0;
end;
if FFileHandle <> INVALID_HANDLE_VALUE then
begin
FileClose(FFileHandle);
FFileHandle := INVALID_HANDLE_VALUE;
end;
end;
function TJclFileMappingStream.Write(const Buffer; Count: Integer): Longint;
begin
Result := 0;
if (Size - Position) >= Count then
begin
System.Move(Buffer, Pointer(TJclAddr(Memory) + TJclAddr(Position))^, Count);
Position := Position + Count;
Result := Count;
end;
end;
{$ENDIF MSWINDOWS}
//=== { TJclAnsiMappedTextReader } ===========================================
constructor TJclAnsiMappedTextReader.Create(MemoryStream: TCustomMemoryStream; FreeStream: Boolean;
const AIndexOption: TJclMappedTextReaderIndex);
begin
inherited Create;
FMemoryStream := MemoryStream;
FFreeStream := FreeStream;
FIndexOption := AIndexOption;
Init;
end;
constructor TJclAnsiMappedTextReader.Create(const FileName: TFileName;
const AIndexOption: TJclMappedTextReaderIndex);
begin
inherited Create;
{$IFDEF MSWINDOWS}
FMemoryStream := TJclFileMappingStream.Create(FileName);
{$ELSE ~ MSWINDOWS}
FMemoryStream := TMemoryStream.Create;
TMemoryStream(FMemoryStream).LoadFromFile(FileName);
{$ENDIF ~ MSWINDOWS}
FFreeStream := True;
FIndexOption := AIndexOption;
Init;
end;
destructor TJclAnsiMappedTextReader.Destroy;
begin
if FFreeStream then
FMemoryStream.Free;
FreeMem(FIndex);
inherited Destroy;
end;
procedure TJclAnsiMappedTextReader.AssignTo(Dest: TPersistent);
begin
if Dest is TStrings then
begin
GoBegin;
TStrings(Dest).BeginUpdate;
try
while not Eof do
TStrings(Dest).Add(string(ReadLn));
finally
TStrings(Dest).EndUpdate;
end;
end
else
inherited AssignTo(Dest);
end;
procedure TJclAnsiMappedTextReader.CreateIndex;
var
P, LastLineStart: PAnsiChar;
I: Integer;
begin
{$RANGECHECKS OFF}
P := FContent;
I := 0;
LastLineStart := P;
while P < FEnd do
begin
// CRLF, CR, LF and LFCR are seen as valid sets of chars for EOL marker
if CharIsReturn(Char(P^)) then
begin
if I and $FFFF = 0 then
ReallocMem(FIndex, (I + $10000) * SizeOf(Pointer));
FIndex[I] := LastLineStart;
Inc(I);
case P^ of
NativeLineFeed:
begin
Inc(P);
if (P < FEnd) and (P^ = NativeCarriageReturn) then
Inc(P);
end;
NativeCarriageReturn:
begin
Inc(P);
if (P < FEnd) and (P^ = NativeLineFeed) then
Inc(P);
end;
end;
LastLineStart := P;
end
else
Inc(P);
end;
if P > LastLineStart then
begin
ReallocMem(FIndex, (I + 1) * SizeOf(Pointer));
FIndex[I] := LastLineStart;
Inc(I);
end
else
ReallocMem(FIndex, I * SizeOf(Pointer));
FLineCount := I;
{$IFDEF RANGECHECKS_ON}
{$RANGECHECKS ON}
{$ENDIF RANGECHECKS_ON}
end;
function TJclAnsiMappedTextReader.GetEof: Boolean;
begin
Result := FPosition >= FEnd;
end;
function TJclAnsiMappedTextReader.GetAsString: AnsiString;
begin
SetString(Result, Content, Size);
end;
function TJclAnsiMappedTextReader.GetChars(Index: Integer): AnsiChar;
begin
if (Index < 0) or (Index >= Size) then
raise EJclError.CreateRes(@RsFileIndexOutOfRange);
Result := AnsiChar(PByte(FContent + Index)^);
end;
function TJclAnsiMappedTextReader.GetLineCount: Integer;
var
P: PAnsiChar;
begin
if FLineCount = -1 then
begin
FLineCount := 0;
if FContent < FEnd then
begin
P := FContent;
while P < FEnd do
begin
case P^ of
NativeLineFeed:
begin
Inc(FLineCount);
Inc(P);
if (P < FEnd) and (P^ = NativeCarriageReturn) then
Inc(P);
end;
NativeCarriageReturn:
begin
Inc(FLineCount);
Inc(P);
if (P < FEnd) and (P^ = NativeLineFeed) then
Inc(P);
end;
else
Inc(P);
end;
end;
if (P = FEnd) and (P > FContent) and not CharIsReturn(Char((P-1)^)) then
Inc(FLineCount);
end;
end;
Result := FLineCount;
end;
function TJclAnsiMappedTextReader.GetLines(LineNumber: Integer): AnsiString;
var
P: PAnsiChar;
begin
P := PtrFromLine(LineNumber);
Result := StringFromPosition(P);
end;
function TJclAnsiMappedTextReader.GetPosition: Integer;
begin
Result := FPosition - FContent;
end;
procedure TJclAnsiMappedTextReader.GoBegin;
begin
Position := 0;
end;
procedure TJclAnsiMappedTextReader.Init;
begin
FContent := FMemoryStream.Memory;
FSize := FMemoryStream.Size;
FEnd := FContent + FSize;
FPosition := FContent;
FLineCount := -1;
FLastLineNumber := 0;
FLastPosition := FContent;
if IndexOption = tiFull then
CreateIndex;
end;
function TJclAnsiMappedTextReader.GetPositionFromLine(LineNumber: Integer): Integer;
var
P: PAnsiChar;
begin
P := PtrFromLine(LineNumber);
if P = nil then
Result := -1
else
Result := P - FContent;
end;
function TJclAnsiMappedTextReader.PtrFromLine(LineNumber: Integer): PAnsiChar;
var
LineOffset: Integer;
begin
Result := nil;
{$RANGECHECKS OFF}
if (IndexOption <> tiNoIndex) and (LineNumber < FLineCount) and (FIndex[LineNumber] <> nil) then
Result := FIndex[LineNumber]
{$IFDEF RANGECHECKS_ON}
{$RANGECHECKS ON}
{$ENDIF RANGECHECKS_ON}
else
begin
LineOffset := LineNumber - FLastLineNumber;
if (FLineCount <> -1) and (LineNumber > 0) then
begin
if -LineOffset > LineNumber then
begin
FLastLineNumber := 0;
FLastPosition := FContent;
LineOffset := LineNumber;
end
else
if LineOffset > FLineCount - LineNumber then
begin
FLastLineNumber := FLineCount;
FLastPosition := FEnd;
LineOffset := LineNumber - FLineCount;
end;
end;
if LineNumber <= 0 then
Result := FContent
else
if LineOffset = 0 then
Result := FLastPosition
else
if LineOffset > 0 then
begin
Result := FLastPosition;
while (Result < FEnd) and (LineOffset > 0) do
begin
case Result^ of
NativeLineFeed:
begin
Dec(LineOffset);
Inc(Result);
if (Result < FEnd) and (Result^ = NativeCarriageReturn) then
Inc(Result);
end;
NativeCarriageReturn:
begin
Dec(LineOffset);
Inc(Result);
if (Result < FEnd) and (Result^ = NativeLineFeed) then
Inc(Result);
end;
else
Inc(Result);
end;
end;
end
else
if LineOffset < 0 then
begin
Result := FLastPosition;
while (Result > FContent) and (LineOffset < 1) do
begin
Dec(Result);
case Result^ of
NativeLineFeed:
begin
Inc(LineOffset);
if LineOffset >= 1 then
Inc(Result)
else
if (Result > FContent) and ((Result-1)^ = NativeCarriageReturn) then
Dec(Result);
end;
NativeCarriageReturn:
begin
Inc(LineOffset);
if LineOffset >= 1 then
Inc(Result)
else
if (Result > FContent) and ((Result-1)^ = NativeLineFeed) then
Dec(Result);
end;
end;
end;
end;
FLastLineNumber := LineNumber;
FLastPosition := Result;
end;
end;
function TJclAnsiMappedTextReader.Read: AnsiChar;
begin
if FPosition >= FEnd then
Result := #0
else
begin
Result := FPosition^;
Inc(FPosition);
end;
end;
function TJclAnsiMappedTextReader.ReadLn: AnsiString;
begin
Result := StringFromPosition(FPosition);
end;
procedure TJclAnsiMappedTextReader.SetPosition(const Value: Integer);
begin
FPosition := FContent + Value;
end;
function TJclAnsiMappedTextReader.StringFromPosition(var StartPos: PAnsiChar): AnsiString;
var
P: PAnsiChar;
begin
if (StartPos = nil) or (StartPos >= FEnd) then
Result := ''
else
begin
P := StartPos;
while (P < FEnd) and (not CharIsReturn(Char(P^))) do
Inc(P);
SetString(Result, StartPos, P - StartPos);
if P < FEnd then
begin
case P^ of
NativeLineFeed:
begin
Inc(P);
if (P < FEnd) and (P^ = NativeCarriageReturn) then
Inc(P);
end;
NativeCarriageReturn:
begin
Inc(P);
if (P < FEnd) and (P^ = NativeLineFeed) then
Inc(P);
end;
end;
end;
StartPos := P;
end;
end;
//=== { TJclWideMappedTextReader } ===========================================
constructor TJclWideMappedTextReader.Create(MemoryStream: TCustomMemoryStream; FreeStream: Boolean;
const AIndexOption: TJclMappedTextReaderIndex);
begin
inherited Create;
FMemoryStream := MemoryStream;
FFreeStream := FreeStream;
FIndexOption := AIndexOption;
Init;
end;
constructor TJclWideMappedTextReader.Create(const FileName: TFileName;
const AIndexOption: TJclMappedTextReaderIndex);
begin
inherited Create;
{$IFDEF MSWINDOWS}
FMemoryStream := TJclFileMappingStream.Create(FileName);
{$ELSE ~ MSWINDOWS}
FMemoryStream := TMemoryStream.Create;
TMemoryStream(FMemoryStream).LoadFromFile(FileName);
{$ENDIF ~ MSWINDOWS}
FFreeStream := True;
FIndexOption := AIndexOption;
Init;
end;
destructor TJclWideMappedTextReader.Destroy;
begin
if FFreeStream then
FMemoryStream.Free;
FreeMem(FIndex);
inherited Destroy;
end;
procedure TJclWideMappedTextReader.AssignTo(Dest: TPersistent);
begin
if Dest is TStrings then
begin
GoBegin;
TStrings(Dest).BeginUpdate;
try
while not Eof do
TStrings(Dest).Add(string(ReadLn));
finally
TStrings(Dest).EndUpdate;
end;
end
else
inherited AssignTo(Dest);
end;
procedure TJclWideMappedTextReader.CreateIndex;
var
P, LastLineStart: PWideChar;
I: Integer;
begin
{$RANGECHECKS OFF}
P := FContent;
I := 0;
LastLineStart := P;
while P < FEnd do
begin
// CRLF, CR, LF and LFCR are seen as valid sets of chars for EOL marker
if CharIsReturn(Char(P^)) then
begin
if I and $FFFF = 0 then
ReallocMem(FIndex, (I + $10000) * SizeOf(Pointer));
FIndex[I] := LastLineStart;
Inc(I);
case P^ of
NativeLineFeed:
begin
Inc(P);
if (P < FEnd) and (P^ = NativeCarriageReturn) then
Inc(P);
end;
NativeCarriageReturn:
begin
Inc(P);
if (P < FEnd) and (P^ = NativeLineFeed) then
Inc(P);
end;
end;
LastLineStart := P;
end
else
Inc(P);
end;
if P > LastLineStart then
begin
ReallocMem(FIndex, (I + 1) * SizeOf(Pointer));
FIndex[I] := LastLineStart;
Inc(I);
end
else
ReallocMem(FIndex, I * SizeOf(Pointer));
FLineCount := I;
{$IFDEF RANGECHECKS_ON}
{$RANGECHECKS ON}
{$ENDIF RANGECHECKS_ON}
end;
function TJclWideMappedTextReader.GetEof: Boolean;
begin
Result := FPosition >= FEnd;
end;
function TJclWideMappedTextReader.GetAsString: WideString;
begin
SetString(Result, Content, Size);
end;
function TJclWideMappedTextReader.GetChars(Index: Integer): WideChar;
begin
if (Index < 0) or (Index >= Size) then
raise EJclError.CreateRes(@RsFileIndexOutOfRange);
Result := WideChar(PByte(FContent + Index)^);
end;
function TJclWideMappedTextReader.GetLineCount: Integer;
var
P: PWideChar;
begin
if FLineCount = -1 then
begin
FLineCount := 0;
if FContent < FEnd then
begin
P := FContent;
while P < FEnd do
begin
case P^ of
NativeLineFeed:
begin
Inc(FLineCount);
Inc(P);
if (P < FEnd) and (P^ = NativeCarriageReturn) then
Inc(P);
end;
NativeCarriageReturn:
begin
Inc(FLineCount);
Inc(P);
if (P < FEnd) and (P^ = NativeLineFeed) then
Inc(P);
end;
else
Inc(P);
end;
end;
if (P = FEnd) and (P > FContent) and not CharIsReturn(Char((P-1)^)) then
Inc(FLineCount);
end;
end;
Result := FLineCount;
end;
function TJclWideMappedTextReader.GetLines(LineNumber: Integer): WideString;
var
P: PWideChar;
begin
P := PtrFromLine(LineNumber);
Result := StringFromPosition(P);
end;
function TJclWideMappedTextReader.GetPosition: Integer;
begin
Result := FPosition - FContent;
end;
procedure TJclWideMappedTextReader.GoBegin;
begin
Position := 0;
end;
procedure TJclWideMappedTextReader.Init;
begin
FContent := FMemoryStream.Memory;
FSize := FMemoryStream.Size;
FEnd := FContent + FSize;
FPosition := FContent;
FLineCount := -1;
FLastLineNumber := 0;
FLastPosition := FContent;
if IndexOption = tiFull then
CreateIndex;
end;
function TJclWideMappedTextReader.GetPositionFromLine(LineNumber: Integer): Integer;
var
P: PWideChar;
begin
P := PtrFromLine(LineNumber);
if P = nil then
Result := -1
else
Result := P - FContent;
end;
function TJclWideMappedTextReader.PtrFromLine(LineNumber: Integer): PWideChar;
var
LineOffset: Integer;
begin
Result := nil;
{$RANGECHECKS OFF}
if (IndexOption <> tiNoIndex) and (LineNumber < FLineCount) and (FIndex[LineNumber] <> nil) then
Result := FIndex[LineNumber]
{$IFDEF RANGECHECKS_ON}
{$RANGECHECKS ON}
{$ENDIF RANGECHECKS_ON}
else
begin
LineOffset := LineNumber - FLastLineNumber;
if (FLineCount <> -1) and (LineNumber > 0) then
begin
if -LineOffset > LineNumber then
begin
FLastLineNumber := 0;
FLastPosition := FContent;
LineOffset := LineNumber;
end
else
if LineOffset > FLineCount - LineNumber then
begin
FLastLineNumber := FLineCount;
FLastPosition := FEnd;
LineOffset := LineNumber - FLineCount;
end;
end;
if LineNumber <= 0 then
Result := FContent
else
if LineOffset = 0 then
Result := FLastPosition
else
if LineOffset > 0 then
begin
Result := FLastPosition;
while (Result < FEnd) and (LineOffset > 0) do
begin
case Result^ of
NativeLineFeed:
begin
Dec(LineOffset);
Inc(Result);
if (Result < FEnd) and (Result^ = NativeCarriageReturn) then
Inc(Result);
end;
NativeCarriageReturn:
begin
Dec(LineOffset);
Inc(Result);
if (Result < FEnd) and (Result^ = NativeLineFeed) then
Inc(Result);
end;
else
Inc(Result);
end;
end;
end
else
if LineOffset < 0 then
begin
Result := FLastPosition;
while (Result > FContent) and (LineOffset < 1) do
begin
Dec(Result);
case Result^ of
NativeLineFeed:
begin
Inc(LineOffset);
if LineOffset >= 1 then
Inc(Result)
else
if (Result > FContent) and ((Result-1)^ = NativeCarriageReturn) then
Dec(Result);
end;
NativeCarriageReturn:
begin
Inc(LineOffset);
if LineOffset >= 1 then
Inc(Result)
else
if (Result > FContent) and ((Result-1)^ = NativeLineFeed) then
Dec(Result);
end;
end;
end;
end;
FLastLineNumber := LineNumber;
FLastPosition := Result;
end;
end;
function TJclWideMappedTextReader.Read: WideChar;
begin
if FPosition >= FEnd then
Result := #0
else
begin
Result := FPosition^;
Inc(FPosition);
end;
end;
function TJclWideMappedTextReader.ReadLn: WideString;
begin
Result := StringFromPosition(FPosition);
end;
procedure TJclWideMappedTextReader.SetPosition(const Value: Integer);
begin
FPosition := FContent + Value;
end;
function TJclWideMappedTextReader.StringFromPosition(var StartPos: PWideChar): WideString;
var
P: PWideChar;
begin
if (StartPos = nil) or (StartPos >= FEnd) then
Result := ''
else
begin
P := StartPos;
while (P < FEnd) and (not CharIsReturn(Char(P^))) do
Inc(P);
SetString(Result, StartPos, P - StartPos);
if P < FEnd then
begin
case P^ of
NativeLineFeed:
begin
Inc(P);
if (P < FEnd) and (P^ = NativeCarriageReturn) then
Inc(P);
end;
NativeCarriageReturn:
begin
Inc(P);
if (P < FEnd) and (P^ = NativeLineFeed) then
Inc(P);
end;
end;
end;
StartPos := P;
end;
end;
function CharIsDriveLetter(const C: Char): Boolean;
begin
case C of
'a'..'z',
'A'..'Z':
Result := True;
else
Result := False;
end;
end;
//=== Path manipulation ======================================================
function PathAddSeparator(const Path: string): string;
begin
Result := Path;
if (Path = '') or (Path[Length(Path)] <> DirDelimiter) then
Result := Path + DirDelimiter;
end;
function PathAddExtension(const Path, Extension: string): string;
begin
Result := Path;
// (obones) Extension may not contain the leading dot while ExtractFileExt
// always returns it. Hence the need to use StrEnsurePrefix for the SameText
// test to return an accurate value.
if (Path <> '') and (Extension <> '') and
not SameText(ExtractFileExt(Path), StrEnsurePrefix('.', Extension)) then
begin
if Path[Length(Path)] = '.' then
Delete(Result, Length(Path), 1);
if Extension[1] = '.' then
Result := Result + Extension
else
Result := Result + '.' + Extension;
end;
end;
function PathAppend(const Path, Append: string): string;
var
PathLength: Integer;
B1, B2: Boolean;
begin
if Append = '' then
Result := Path
else
begin
PathLength := Length(Path);
if PathLength = 0 then
Result := Append
else
begin
// The following code may look a bit complex but all it does is add Append to Path ensuring
// that there is one and only one path separator character between them
B1 := Path[PathLength] = DirDelimiter;
B2 := Append[1] = DirDelimiter;
if B1 and B2 then
Result := Copy(Path, 1, PathLength - 1) + Append
else
begin
if not (B1 or B2) then
Result := Path + DirDelimiter + Append
else
Result := Path + Append;
end;
end;
end;
end;
function PathBuildRoot(const Drive: Byte): string;
begin
{$IFDEF UNIX}
Result := DirDelimiter;
{$ENDIF UNIX}
{$IFDEF MSWINDOWS}
// Remember, Win32 only allows 'a' to 'z' as drive letters (mapped to 0..25)
if Drive < 26 then
Result := Char(Drive + 65) + ':\'
else
raise EJclPathError.CreateResFmt(@RsPathInvalidDrive, [IntToStr(Drive)]);
{$ENDIF MSWINDOWS}
end;
function PathCanonicalize(const Path: string): string;
var
List: TStringList;
S: string;
I, K: Integer;
IsAbsolute: Boolean;
begin
I := Pos(':', Path); // for Windows' sake
K := Pos(DirDelimiter, Path);
IsAbsolute := K - I = 1;
if IsAbsolute then begin
if Copy(Path, 1, Length(PathUncPrefix)) = PathUncPrefix then // UNC path
K := 2;
end else
K := I;
if K = 0 then
S := Path
else
S := Copy(Path, K + 1, Length(Path));
List := TStringList.Create;
try
StrIToStrings(S, DirDelimiter, List, True);
I := 0;
while I < List.Count do
begin
if List[I] = '.' then
List.Delete(I)
else
if (IsAbsolute or (I > 0) and not (List[I-1] = '..')) and (List[I] = '..') then
begin
List.Delete(I);
if I > 0 then
begin
Dec(I);
List.Delete(I);
end;
end
else Inc(I);
end;
Result := StringsToStr(List, DirDelimiter, True);
finally
List.Free;
end;
if K > 0 then
Result := Copy(Path, 1, K) + Result
else
if Result = '' then
Result := '.';
end;
function PathCommonPrefix(const Path1, Path2: string): Integer;
var
Index1, Index2: Integer;
LastSeparator, LenS1: Integer;
S1, S2: string;
begin
Result := 0;
if (Path1 <> '') and (Path2 <> '') then
begin
// Initialize P1 to the shortest of the two paths so that the actual comparison loop below can
// use the terminating #0 of that string to terminate the loop.
if Length(Path1) <= Length(Path2) then
begin
S1 := Path1;
S2 := Path2;
end
else
begin
S1 := Path2;
S2 := Path1;
end;
Index1 := 1;
Index2 := 1;
LenS1 := Length(S1);
LastSeparator := 0;
while (S1[Index1] = S2[Index2]) and (Index1 <= LenS1) do
begin
Inc(Result);
if (S1[Index1] = DirDelimiter) or (S1[Index1] = ':') then
LastSeparator := Result;
Inc(Index1);
Inc(Index2);
end;
if (LastSeparator < Result) and (Index1 <= LenS1) then
Result := LastSeparator;
end;
end;
{$IFDEF MSWINDOWS}
function PathCompactPath(const DC: HDC; const Path: string;
const Width: Integer; CmpFmt: TCompactPath): string;
const
Compacts: array [TCompactPath] of Cardinal = (DT_PATH_ELLIPSIS, DT_END_ELLIPSIS);
var
TextRect: TRect;
Fmt: Cardinal;
begin
Result := '';
if (DC <> 0) and (Path <> '') and (Width > 0) then
begin
{ Here's a note from the Platform SDK to explain the + 5 in the call below:
"If dwDTFormat includes DT_MODIFYSTRING, the function could add up to four additional characters
to this string. The buffer containing the string should be large enough to accommodate these
extra characters." }
SetString(Result, PChar(Path), Length(Path) + 4);
TextRect := Rect(0, 0, Width, 255);
Fmt := DT_MODIFYSTRING or DT_CALCRECT or Compacts[CmpFmt];
if DrawTextEx(DC, PChar(Result), -1, TextRect, Fmt, nil) <> 0 then
StrResetLength(Result)
else
Result := ''; // in case of error
end;
end;
{$ENDIF MSWINDOWS}
procedure PathExtractElements(const Source: string; var Drive, Path, FileName, Ext: string);
begin
Drive := ExtractFileDrive(Source);
Path := ExtractFilePath(Source);
// Path includes drive so remove that
if Drive <> '' then
Delete(Path, 1, Length(Drive));
// add/remove separators
Drive := PathAddSeparator(Drive);
Path := PathRemoveSeparator(Path);
if (Path <> '') and (Path[1] = DirDelimiter) then
Delete(Path, 1, 1);
// and extract the remaining elements
FileName := PathExtractFileNameNoExt(Source);
Ext := ExtractFileExt(Source);
end;
function PathExtractFileDirFixed(const S: string): string;
begin
Result := PathAddSeparator(ExtractFileDir(S));
end;
function PathExtractFileNameNoExt(const Path: string): string;
begin
Result := PathRemoveExtension(ExtractFileName(Path));
end;
function PathExtractPathDepth(const Path: string; Depth: Integer): string;
var
List: TStringList;
LocalPath: string;
I: Integer;
begin
List := TStringList.Create;
try
if IsDirectory(Path) then
LocalPath := Path
else
LocalPath := ExtractFilePath(Path);
StrIToStrings(LocalPath, DirDelimiter, List, True);
I := Depth + 1;
if PathIsUNC(LocalPath) then
I := I + 2;
while I < List.Count do
List.Delete(I);
Result := PathAddSeparator(StringsToStr(List, DirDelimiter, True));
finally
List.Free;
end;
end;
// Notes: maybe this function should first apply PathCanonicalize() ?
function PathGetDepth(const Path: string): Integer;
var
List: TStringList;
LocalPath: string;
I, Start: Integer;
begin
Result := 0;
List := TStringList.Create;
try
if IsDirectory(Path) then
LocalPath := Path
else
LocalPath := ExtractFilePath(Path);
StrIToStrings(LocalPath, DirDelimiter, List, False);
if PathIsUNC(LocalPath) then
Start := 1
else
Start := 0;
for I := Start to List.Count - 1 do
begin
if Pos(':', List[I]) = 0 then
Inc(Result);
end;
finally
List.Free;
end;
end;
{$IFDEF MSWINDOWS}
function ShellGetLongPathName(const Path: string): string;
{$IFDEF FPC}
// As of 2004-10-17, FPC's ShlObj unit is just a dummy
begin
Result := Path;
end;
{$ElSE ~FPC}
var
PIDL: PItemIDList;
Desktop: IShellFolder;
{$IFNDEF SUPPORTS_UNICODE}
AnsiName: string;
WideName: array [0..MAX_PATH] of WideChar;
{$ENDIF ~SUPPORTS_UNICODE}
Eaten, Attr: ULONG; // both unused but API requires them (incorrect translation)
begin
Result := Path;
if Path <> '' then
begin
if Succeeded(SHGetDesktopFolder(Desktop)) then
begin
{$IFDEF SUPPORTS_UNICODE}
if Succeeded(Desktop.ParseDisplayName(0, nil, PChar(Path), Eaten, PIDL, Attr)) then
try
SetLength(Result, MAX_PATH);
if SHGetPathFromIDList(PIDL, PChar(Result)) then
StrResetLength(Result);
finally
CoTaskMemFree(PIDL);
end;
{$ELSE ~SUPPORTS_UNICODE}
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, PAnsiChar(Path), -1, WideName, MAX_PATH);
if Succeeded(Desktop.ParseDisplayName(0, nil, WideName, Eaten, PIDL, Attr)) then
try
SetLength(AnsiName, MAX_PATH);
if SHGetPathFromIDList(PIDL, PChar(AnsiName)) then
StrResetLength(AnsiName);
Result := AnsiName;
finally
CoTaskMemFree(PIDL);
end;
{$ENDIF ~SUPPORTS_UNICODE}
end;
end;
end;
{$ENDIF ~FPC}
{ TODO : Move RTDL code over to JclWin32 when JclWin32 gets overhauled. }
var
_Kernel32Handle: TModuleHandle = INVALID_MODULEHANDLE_VALUE;
_GetLongPathName: function (lpszShortPath: PChar; lpszLongPath: PChar;
cchBuffer: DWORD): DWORD; stdcall;
function Kernel32Handle: HMODULE;
begin
NVJclSysUtils.LoadModule(_Kernel32Handle, kernel32);
Result := _Kernel32Handle;
end;
function RtdlGetLongPathName(const Path: string): string;
begin
Result := Path;
if not Assigned(_GetLongPathName) then
_GetLongPathName := GetModuleSymbol(Kernel32Handle, 'GetLongPathName' + AWSuffix);
if not Assigned(_GetLongPathName) then
Result := ShellGetLongPathName(Path)
else
begin
SetLength(Result, MAX_PATH);
SetLength(Result, _GetLongPathName(PChar(Path), PChar(Result), MAX_PATH));
end;
end;
function PathGetLongName(const Path: string): string;
begin
if Pos('::', Path) > 0 then // Path contains '::{<GUID>}'
Result := ShellGetLongPathName(Path)
else
Result := RtdlGetLongPathName(Path);
if Result = '' then
Result := Path;
end;
function PathGetShortName(const Path: string): string;
var
Required: Integer;
begin
Result := Path;
Required := GetShortPathName(PChar(Path), nil, 0);
if Required <> 0 then
begin
SetLength(Result, Required);
Required := GetShortPathName(PChar(Path), PChar(Result), Required);
if (Required <> 0) and (Required = Length(Result) - 1) then
SetLength(Result, Required)
else
Result := Path;
end;
end;
{$ENDIF MSWINDOWS}
function PathGetRelativePath(Origin, Destination: string): string;
var
{$IFDEF MSWINDOWS}
OrigDrive: string;
DestDrive: string;
{$ENDIF MSWINDOWS}
OrigList: TStringList;
DestList: TStringList;
DiffIndex: Integer;
I: Integer;
function StartsFromRoot(const Path: string): Boolean;
{$IFDEF MSWINDOWS}
var
I: Integer;
begin
I := Length(ExtractFileDrive(Path));
Result := (Length(Path) > I) and (Path[I + 1] = DirDelimiter);
end;
{$ELSE ~MSWINDOWS}
begin
Result := Pos(DirDelimiter, Path) = 1;
end;
{$ENDIF ~MSWINDOWS}
function Equal(const Path1, Path2: string): Boolean;
begin
{$IFDEF MSWINDOWS} // case insensitive
Result := StrSame(Path1, Path2);
{$ELSE ~MSWINDOWS} // case sensitive
Result := Path1 = Path2;
{$ENDIF ~MSWINDOWS}
end;
begin
Origin := PathCanonicalize(Origin);
Destination := PathCanonicalize(Destination);
{$IFDEF MSWINDOWS}
OrigDrive := ExtractFileDrive(Origin);
DestDrive := ExtractFileDrive(Destination);
{$ENDIF MSWINDOWS}
if Equal(Origin, Destination) or (Destination = '') then
Result := '.'
else
if Origin = '' then
Result := Destination
else
{$IFDEF MSWINDOWS}
if (DestDrive <> '') and ((OrigDrive = '') or ((OrigDrive <> '') and not Equal(OrigDrive, DestDrive))) then
Result := Destination
else
if (OrigDrive <> '') and (Pos(DirDelimiter, Destination) = 1)
and not Equal(PathUncPrefix,Copy(Destination,1,Length(PathUncPrefix))) then
Result := OrigDrive + Destination // prepend drive part from Origin
else
{$ENDIF MSWINDOWS}
if StartsFromRoot(Origin) and not StartsFromRoot(Destination) then
Result := StrEnsureSuffix(DirDelimiter, Origin) +
StrEnsureNoPrefix(DirDelimiter, Destination)
else
begin
// create a list of paths as separate strings
OrigList := TStringList.Create;
DestList := TStringList.Create;
try
// NOTE: DO NOT USE DELIMITER AND DELIMITEDTEXT FROM
// TSTRINGS, THEY WILL SPLIT PATHS WITH SPACES !!!!
StrToStrings(Origin, DirDelimiter, OrigList, False);
StrToStrings(Destination, DirDelimiter, DestList, False);
begin
// find the first directory that is not the same
DiffIndex := OrigList.Count;
if DestList.Count < DiffIndex then
DiffIndex := DestList.Count;
for I := 0 to DiffIndex - 1 do
if not Equal(OrigList[I], DestList[I]) then
begin
DiffIndex := I;
Break;
end;
Result := StrRepeat('..' + DirDelimiter, OrigList.Count - DiffIndex);
Result := PathRemoveSeparator(Result);
for I := DiffIndex to DestList.Count - 1 do
begin
if Result <> '' then
Result := Result + DirDelimiter;
Result := Result + DestList[i];
end;
end;
finally
DestList.Free;
OrigList.Free;
end;
end;
end;
function PathGetTempPath: string;
{$IFDEF MSWINDOWS}
var
BufSize: Cardinal;
begin
BufSize := {$IFDEF HAS_UNITSCOPE}Winapi.{$ENDIF}Windows.GetTempPath(0, nil);
SetLength(Result, BufSize);
{ TODO : Check length (-1 or not) }
{$IFDEF HAS_UNITSCOPE}Winapi.{$ENDIF}Windows.GetTempPath(BufSize, PChar(Result));
StrResetLength(Result);
end;
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
begin
Result := GetEnvironmentVariable('TMPDIR');
end;
{$ENDIF UNIX}
function PathIsAbsolute(const Path: string): Boolean;
{$IFDEF MSWINDOWS}
var
I: Integer;
{$ENDIF MSWINDOWS}
begin
Result := False;
if Path <> '' then
begin
{$IFDEF UNIX}
Result := (Path[1] = DirDelimiter);
{$ENDIF UNIX}
{$IFDEF MSWINDOWS}
if not PathIsUnc(Path) then
begin
I := 0;
if PathIsDiskDevice(Path) then
I := Length(PathDevicePrefix);
Result := (Length(Path) > I + 2) and CharIsDriveLetter(Path[I + 1]) and
(Path[I + 2] = ':') and (Path[I + 3] = DirDelimiter);
end
else
Result := True;
{$ENDIF MSWINDOWS}
end;
end;
function PathIsChild(const Path, Base: string): Boolean;
var
L: Integer;
B, P: string;
begin
Result := False;
B := PathRemoveSeparator(Base);
P := PathRemoveSeparator(Path);
// an empty path or one that's not longer than base cannot be a subdirectory
L := Length(B);
if (P = '') or (L >= Length(P)) then
Exit;
{$IFDEF MSWINDOWS}
Result := AnsiSameText(StrLeft(P, L), B) and (P[L+1] = DirDelimiter);
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
Result := AnsiSameStr(StrLeft(P, L), B) and (P[L+1] = DirDelimiter);
{$ENDIF UNIX}
end;
function PathIsEqualOrChild(const Path, Base: string): Boolean;
var
L: Integer;
B, P: string;
begin
B := PathRemoveSeparator(Base);
P := PathRemoveSeparator(Path);
// an empty path or one that's not longer than base cannot be a subdirectory
L := Length(B);
{$IFDEF MSWINDOWS}
Result := AnsiSameText(P, B);
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
Result := AnsiSameStr(P, B);
{$ENDIF UNIX}
if Result or (P = '') or (L >= Length(P)) then
Exit;
{$IFDEF MSWINDOWS}
Result := AnsiSameText(StrLeft(P, L), B) and (P[L+1] = DirDelimiter);
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
Result := AnsiSameStr(StrLeft(P, L), B) and (P[L+1] = DirDelimiter);
{$ENDIF UNIX}
end;
function PathIsDiskDevice(const Path: string): Boolean;
{$IFDEF UNIX}
var
FullPath: string;
F: PIOFile;
Buffer: array [0..255] of AnsiChar;
MountEntry: TMountEntry;
FsTypes: TStringList;
procedure GetAvailableFileSystems(const List: TStrings);
var
F: TextFile;
S: string;
begin
AssignFile(F, '/proc/filesystems');
Reset(F);
repeat
Readln(F, S);
if Pos('nodev', S) = 0 then // how portable is this ?
List.Add(Trim(S));
until Eof(F);
List.Add('supermount');
CloseFile(F);
end;
begin
Result := False;
SetLength(FullPath, _POSIX_PATH_MAX);
if realpath(PChar(Path), PChar(FullPath)) = nil then
RaiseLastOSError;
StrResetLength(FullPath);
FsTypes := TStringList.Create;
try
GetAvailableFileSystems(FsTypes);
F := setmntent(_PATH_MOUNTED, 'r'); // PATH_MOUNTED is deprecated,
// but PATH_MNTTAB is defective in Libc.pas
try
// get drives from mtab
while not Result and (getmntent_r(F, MountEntry, Buffer, SizeOf(Buffer)) <> nil) do
if FsTypes.IndexOf(MountEntry.mnt_type) <> -1 then
Result := MountEntry.mnt_dir = FullPath;
finally
endmntent(F);
end;
finally
FsTypes.Free;
end;
end;
{$ENDIF UNIX}
{$IFDEF MSWINDOWS}
begin
Result := Copy(Path, 1, Length(PathDevicePrefix)) = PathDevicePrefix;
end;
{$ENDIF MSWINDOWS}
function CharIsMachineName(const C: Char): Boolean; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
begin
case C of
'a'..'z',
'A'..'Z',
'-', '_', '.':
Result := True;
else
Result := False;
end;
end;
function CharIsInvalidPathCharacter(const C: Char): Boolean; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
begin
case C of
'<', '>', '?', '/', ',', '*', '+', '=', '[', ']', '|', ':', ';', '"', '''':
Result := True;
else
Result := False;
end;
end;
function PathIsUNC(const Path: string): Boolean;
{$IFDEF MSWINDOWS}
const
cUNCSuffix = '?\UNC';
var
P: PChar;
function AbsorbSeparator: Boolean;
begin
Result := (P <> nil) and (P^ = DirDelimiter);
if Result then
Inc(P);
end;
function AbsorbMachineName: Boolean;
var
NonDigitFound: Boolean;
begin
// a valid machine name is a string composed of the set [a-z, A-Z, 0-9, -, _] but it may not
// consist entirely out of numbers
Result := True;
NonDigitFound := False;
while (P^ <> #0) and (P^ <> DirDelimiter) do
begin
if CharIsMachineName(P^) then
begin
NonDigitFound := True;
Inc(P);
end
else
if CharIsDigit(P^) then
Inc(P)
else
begin
Result := False;
Break;
end;
end;
Result := Result and NonDigitFound;
end;
function AbsorbShareName: Boolean;
begin
// a valid share name is a string composed of a set the set !InvalidCharacters note that a
// leading '$' is valid (indicates a hidden share)
Result := True;
while (P^ <> #0) and (P^ <> DirDelimiter) do
begin
if CharIsInvalidPathCharacter(P^) then
begin
Result := False;
Break;
end;
Inc(P);
end;
end;
begin
Result := Copy(Path, 1, Length(PathUncPrefix)) = PathUncPrefix;
if Result then
begin
if Copy(Path, 1, Length(PathUncPrefix + cUNCSuffix)) = PathUncPrefix + cUNCSuffix then
P := @Path[Length(PathUncPrefix + cUNCSuffix)]
else
begin
P := @Path[Length(PathUncPrefix)];
Result := AbsorbSeparator and AbsorbMachineName;
end;
Result := Result and AbsorbSeparator;
if Result then
begin
Result := AbsorbShareName;
// remaining, if anything, is path and or filename (optional) check those?
end;
end;
end;
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
begin
Result := False;
end;
{$ENDIF UNIX}
function PathRemoveSeparator(const Path: string): string;
var
L: Integer;
begin
L := Length(Path);
if (L <> 0) and (Path[L] = DirDelimiter) then
Result := Copy(Path, 1, L - 1)
else
Result := Path;
end;
function PathRemoveExtension(const Path: string): string;
var
I: Integer;
begin
I := LastDelimiter(':.' + DirDelimiter, Path);
if (I > 0) and (Path[I] = '.') then
Result := Copy(Path, 1, I - 1)
else
Result := Path;
end;
{$IFDEF MSWINDOWS}
function SHGetDisplayName(ShellFolder: IShellFolder; PIDL: PItemIDList; ForParsing: Boolean): string;
const
Flags: array[Boolean] of DWORD = (SHGDN_NORMAL, SHGDN_FORPARSING);
var
StrRet: TStrRet;
P: PChar;
begin
Result := '';
StrRet.utype := 0;
ShellFolder.GetDisplayNameOf(PIDL, Flags[ForParsing], StrRet);
case StrRet.uType of
STRRET_CSTR:
SetString(Result, StrRet.cStr, lstrlenA(StrRet.cStr));
STRRET_OFFSET:
begin
P := @PIDL.mkid.abID[StrRet.uOffset - SizeOf(PIDL.mkid.cb)];
SetString(Result, P, PIDL.mkid.cb - StrRet.uOffset);
end;
STRRET_WSTR:
Result := StrRet.pOleStr;
end;
Result := Copy(Result, 1, lstrlen(PChar(Result)));
end;
function CutFirstDirectory(var Path: string): string;
var
ps: Integer;
begin
ps := AnsiPos(DirDelimiter, Path);
if ps > 0 then
begin
Result := Copy(Path, 1, ps - 1);
Path := Copy(Path, ps + 1, Length(Path));
end
else
begin
Result := Path;
Path := '';
end;
end;
function PathGetPhysicalPath(const LocalizedPath: string): string;
var
Malloc: IMalloc;
DesktopFolder: IShellFolder;
RootFolder: IShellFolder;
Eaten: Cardinal;
Attributes: Cardinal;
pidl: PItemIDList;
EnumIDL: IEnumIDList;
Drive: WideString;
Featched: Cardinal;
ParsePath: WideString;
Path, Name: string;
Found: Boolean;
begin
if StrCompareRange('\\', LocalizedPath, 1, 2) = 0 then
begin
Result := LocalizedPath;
Exit;
end;
Drive := ExtractFileDrive(LocalizedPath);
if Drive = '' then
begin
Result := LocalizedPath;
Exit;
end;
Path := Copy(LocalizedPath, Length(Drive) + 2, Length(LocalizedPath));
ParsePath := Drive;
OLECheck( SHGetMalloc(Malloc) );
OleCheck( SHGetDesktopFolder(DesktopFolder) );
while Path <> '' do
begin
Name := CutFirstDirectory(Path);
Found := False;
pidl := nil;
Attributes := 0;
if Succeeded( DesktopFolder.ParseDisplayName(0, nil, PWideChar(ParsePath), Eaten, pidl, Attributes) ) then
begin
OleCheck( DesktopFolder.BindToObject(pidl, nil, IShellFolder, RootFolder) );
Malloc.Free(pidl);
OleCheck( RootFolder.EnumObjects(0, SHCONTF_FOLDERS or SHCONTF_NONFOLDERS or SHCONTF_INCLUDEHIDDEN, EnumIDL) );
Featched := 0;
while EnumIDL.Next(1, pidl, Featched) = NOERROR do
begin
if AnsiCompareText(Name, SHGetDisplayName(RootFolder, pidl, False)) = 0 then
begin
ParsePath := SHGetDisplayName(RootFolder, pidl, True);
Malloc.Free(pidl);
Found := True;
Break;
end;
Malloc.Free(pidl);
end;
EnumIDL := nil;
RootFolder := nil;
end;
if not Found then
ParsePath := ParsePath + DirDelimiter + Name;
end;
Result := ParsePath;
end;
function PathGetLocalizedPath(const PhysicalPath: string): string;
var
Malloc: IMalloc;
DesktopFolder: IShellFolder;
RootFolder: IShellFolder;
Eaten: Cardinal;
Attributes: Cardinal;
pidl: PItemIDList;
EnumIDL: IEnumIDList;
Drive: WideString;
Featched: Cardinal;
ParsePath: WideString;
Path, Name, ParseName, DisplayName: string;
Found: Boolean;
begin
if StrCompareRange('\\', PhysicalPath, 1, 2) = 0 then
begin
Result := PhysicalPath;
Exit;
end;
Drive := ExtractFileDrive(PhysicalPath);
if Drive = '' then
begin
Result := PhysicalPath;
Exit;
end;
Path := Copy(PhysicalPath, Length(Drive) + 2, Length(PhysicalPath));
ParsePath := Drive;
Result := Drive;
OLECheck( SHGetMalloc(Malloc) );
OleCheck( SHGetDesktopFolder(DesktopFolder) );
while Path <> '' do
begin
Name := CutFirstDirectory(Path);
Found := False;
pidl := nil;
Attributes := 0;
if Succeeded( DesktopFolder.ParseDisplayName(0, nil, PWideChar(ParsePath), Eaten, pidl, Attributes) ) then
begin
OleCheck( DesktopFolder.BindToObject(pidl, nil, IShellFolder, RootFolder) );
Malloc.Free(pidl);
OleCheck( RootFolder.EnumObjects(0, SHCONTF_FOLDERS or SHCONTF_NONFOLDERS or SHCONTF_INCLUDEHIDDEN, EnumIDL) );
Featched := 0;
while EnumIDL.Next(1, pidl, Featched) = NOERROR do
begin
ParseName := SHGetDisplayName(RootFolder, pidl, True);
DisplayName := SHGetDisplayName(RootFolder, pidl, False);
Malloc.Free(pidl);
if (AnsiCompareText(Name, ExtractFileName(ParseName)) = 0) or
(AnsiCompareText(Name, DisplayName) = 0) then
begin
Name := DisplayName;
ParsePath := ParseName;
Found := True;
Break;
end;
end;
EnumIDL := nil;
RootFolder := nil;
end;
Result := Result + DirDelimiter + Name;
if not Found then
ParsePath := ParsePath + DirDelimiter + Name;
end;
end;
{$ELSE ~MSWINDOWS}
function PathGetPhysicalPath(const LocalizedPath: string): string;
begin
Result := LocalizedPath;
end;
function PathGetLocalizedPath(const PhysicalPath: string): string;
begin
Result := PhysicalPath;
end;
{$ENDIF ~MSWINDOWS}
//=== Files and Directories ==================================================
{* Extended version of JclFileUtils.BuildFileList:
function parameter Path can include multiple FileMasks as:
c:\aaa\*.pas; pro*.dpr; *.d??
FileMask Seperator = ';'
*}
function BuildFileList(const Path: string; const Attr: Integer; const List: TStrings; IncludeDirectoryName: Boolean =
False): Boolean;
var
SearchRec: TSearchRec;
IndexMask: Integer;
MaskList: TStringList;
Masks, Directory: string;
begin
Assert(List <> nil);
MaskList := TStringList.Create;
try
{* extract the Directory *}
Directory := ExtractFileDir(Path);
{* files can be searched in the current directory *}
if Directory <> '' then
begin
Directory := PathAddSeparator(Directory);
{* extract the FileMasks portion out of Path *}
Masks := StrAfter(Directory, Path);
end
else
Masks := Path;
{* put the Masks into TStringlist *}
StrTokenToStrings(Masks, DirSeparator, MaskList);
{* search all files in the directory *}
Result := FindFirst(Directory + '*', faAnyFile, SearchRec) = 0;
List.BeginUpdate;
try
while Result do
begin
{* if the filename matches any mask then it is added to the list *}
for IndexMask := 0 to MaskList.Count - 1 do
if (SearchRec.Name <> '.') and (SearchRec.Name <> '..')
and ((SearchRec.Attr and Attr) = (SearchRec.Attr and faAnyFile))
and IsFileNameMatch(SearchRec.Name, MaskList.Strings[IndexMask]) then
begin
if IncludeDirectoryName then
List.Add(Directory+SearchRec.Name)
else
List.Add(SearchRec.Name);
Break;
end;
case FindNext(SearchRec) of
0:
;
ERROR_NO_MORE_FILES:
Break;
else
Result := False;
end;
end;
finally
{$IFDEF HAS_UNITSCOPE}System.{$ENDIF}SysUtils.FindClose(SearchRec);
List.EndUpdate;
end;
finally
MaskList.Free;
end;
end;
{$IFDEF MSWINDOWS}
procedure CreateEmptyFile(const FileName: string);
var
Handle: THandle;
begin
Handle := CreateFile(PChar(FileName), GENERIC_READ or GENERIC_WRITE, 0, nil, CREATE_ALWAYS, 0, 0);
if Handle <> INVALID_HANDLE_VALUE then
CloseHandle(Handle)
else
RaiseLastOSError;
end;
{$ENDIF MSWINDOWS}
{$IFDEF MSWINDOWS}
function CloseVolume(var Volume: THandle): Boolean;
begin
Result := False;
if Volume <> INVALID_HANDLE_VALUE then
begin
Result := CloseHandle(Volume);
if Result then
Volume := INVALID_HANDLE_VALUE;
end;
end;
{$IFNDEF FPC} // needs JclShell
(*DELCIO function DeleteDirectory(const DirectoryName: string; MoveToRecycleBin: Boolean): Boolean;
begin
if MoveToRecycleBin then
Result := SHDeleteFolder(0, DirectoryName, [doSilent, doAllowUndo])
else
Result := DelTree(DirectoryName);
end; *)
function CopyDirectory(ExistingDirectoryName, NewDirectoryName: string): Boolean;
var
SH: SHFILEOPSTRUCT;
begin
ResetMemory(SH, SizeOf(SH));
SH.Wnd := 0;
SH.wFunc := FO_COPY;
SH.pFrom := PChar(PathRemoveSeparator(ExistingDirectoryName) + #0);
SH.pTo := PChar(PathRemoveSeparator(NewDirectoryName) + #0);
SH.fFlags := FOF_ALLOWUNDO or FOF_NOCONFIRMATION or FOF_NOCONFIRMMKDIR or FOF_SILENT;
Result := SHFileOperation(SH) = 0;
end;
function MoveDirectory(ExistingDirectoryName, NewDirectoryName: string): Boolean;
var
SH: SHFILEOPSTRUCT;
begin
ResetMemory(SH, SizeOf(SH));
SH.Wnd := 0;
SH.wFunc := FO_MOVE;
SH.pFrom := PChar(PathRemoveSeparator(ExistingDirectoryName) + #0);
SH.pTo := PChar(PathRemoveSeparator(NewDirectoryName) + #0);
SH.fFlags := FOF_ALLOWUNDO or FOF_NOCONFIRMATION or FOF_NOCONFIRMMKDIR or FOF_SILENT;
Result := SHFileOperation(SH) = 0;
end;
{$ENDIF ~FPC}
function DelTree(const Path: string): Boolean;
begin
Result := DelTreeEx(Path, False, nil);
end;
function DelTreeEx(const Path: string; AbortOnFailure: Boolean; Progress: TDelTreeProgress): Boolean;
var
Files: TStringList;
LPath: string; // writable copy of Path
FileName: string;
I: Integer;
PartialResult: Boolean;
Attr: DWORD;
begin
Assert(Path <> '', LoadResString(@RsDelTreePathIsEmpty));
{$IFNDEF ASSERTIONS_ON}
if Path = '' then
begin
Result := False;
Exit;
end;
{$ENDIF ~ASSERTIONS_ON}
Result := True;
Files := TStringList.Create;
try
LPath := PathRemoveSeparator(Path);
BuildFileList(LPath + '\*.*', faAnyFile, Files);
for I := 0 to Files.Count - 1 do
begin
FileName := LPath + DirDelimiter + Files[I];
PartialResult := True;
// If the current file is itself a directory then recursively delete it
Attr := GetFileAttributes(PChar(FileName));
if (Attr <> DWORD(-1)) and ((Attr and FILE_ATTRIBUTE_DIRECTORY) <> 0) then
PartialResult := DelTreeEx(FileName, AbortOnFailure, Progress)
else
begin
if Assigned(Progress) then
PartialResult := Progress(FileName, Attr);
if PartialResult then
begin
// Set attributes to normal in case it's a readonly file
PartialResult := SetFileAttributes(PChar(FileName), FILE_ATTRIBUTE_NORMAL);
if PartialResult then
PartialResult := DeleteFile(FileName);
end;
end;
if not PartialResult then
begin
Result := False;
if AbortOnFailure then
Break;
end;
end;
finally
FreeAndNil(Files);
end;
if Result then
begin
// Finally remove the directory itself
Result := SetFileAttributes(PChar(LPath), FILE_ATTRIBUTE_NORMAL);
if Result then
begin
{$IOCHECKS OFF}
RmDir(LPath);
{$IFDEF IOCHECKS_ON}
{$IOCHECKS ON}
{$ENDIF IOCHECKS_ON}
Result := IOResult = 0;
end;
end;
end;
{$ENDIF MSWINDOWS}
{$IFDEF MSWINDOWS}
function DirectoryExists(const Name: string): Boolean;
var
R: DWORD;
begin
R := GetFileAttributes(PChar(Name));
Result := (R <> DWORD(-1)) and ((R and FILE_ATTRIBUTE_DIRECTORY) <> 0);
end;
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
function DirectoryExists(const Name: string; ResolveSymLinks: Boolean): Boolean;
begin
Result := IsDirectory(Name, ResolveSymLinks);
end;
{$ENDIF UNIX}
{$IFDEF MSWINDOWS}
function DiskInDrive(Drive: Char): Boolean;
var
ErrorMode: Cardinal;
begin
Result := False;
Assert(CharIsDriveLetter(Drive));
if CharIsDriveLetter(Drive) then
begin
Drive := CharUpper(Drive);
{ try to access the drive, it doesn't really matter how we access the drive and as such calling
DiskSize is more or less a random choice. The call to SetErrorMode supresses the system provided
error dialog if there is no disk in the drive and causes the to DiskSize to fail. }
ErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS);
try
Result := DiskSize(Ord(Drive) - $40) <> -1;
finally
SetErrorMode(ErrorMode);
end;
end;
end;
{$ENDIF MSWINDOWS}
function FileCreateTemp(var Prefix: string): THandle;
{$IFDEF MSWINDOWS}
var
TempName: string;
begin
Result := INVALID_HANDLE_VALUE;
TempName := FileGetTempName(Prefix);
if TempName <> '' then
begin
Result := CreateFile(PChar(TempName), GENERIC_READ or GENERIC_WRITE, 0, nil,
OPEN_EXISTING, FILE_ATTRIBUTE_TEMPORARY or FILE_FLAG_DELETE_ON_CLOSE, 0);
// In certain situations it's possible that CreateFile fails yet the file is actually created,
// therefore explicitly delete it upon failure.
if Result = INVALID_HANDLE_VALUE then
DeleteFile(TempName);
Prefix := TempName;
end;
end;
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
var
Template: string;
begin
// The mkstemp function generates a unique file name just as mktemp does, but
// it also opens the file for you with open. If successful, it modifies
// template in place and returns a file descriptor for that file open for
// reading and writing. If mkstemp cannot create a uniquely-named file, it
// returns -1. If template does not end with `XXXXXX', mkstemp returns -1 and
// does not modify template.
// The file is opened using mode 0600. If the file is meant to be used by
// other users this mode must be changed explicitly.
// Unlike mktemp, mkstemp is actually guaranteed to create a unique file that
// cannot possibly clash with any other program trying to create a temporary
// file. This is because it works by calling open with the O_EXCL flag, which
// says you want to create a new file and get an error if the file already
// exists.
Template := Prefix + 'XXXXXX';
Result := mkstemp(PChar(Template));
Prefix := Template;
end;
{$ENDIF UNIX}
(* DELCIO
function FileBackup(const FileName: string; Move: Boolean = False): Boolean;
begin
if Move then
Result := FileMove(FileName, GetBackupFileName(FileName), True)
else
Result := FileCopy(FileName, GetBackupFileName(FileName), True);
end; *)
function FileCopy(const ExistingFileName, NewFileName: string; ReplaceExisting: Boolean = False): Boolean;
var
{$IFDEF UNIX}
SrcFile, DstFile: file;
Buf: array[0..511] of Byte;
BytesRead: Integer;
{$ENDIF UNIX}
DestFileName: string;
begin
if IsDirectory(NewFileName) then
DestFileName := PathAddSeparator(NewFileName) + ExtractFileName(ExistingFileName)
else
DestFileName := NewFileName;
{$IFDEF MSWINDOWS}
{ TODO : Use CopyFileEx where available? }
Result := CopyFile(PChar(ExistingFileName), PChar(DestFileName), not ReplaceExisting);
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
Result := False;
if not FileExists(DestFileName) or ReplaceExisting then
begin
AssignFile(SrcFile, ExistingFileName);
Reset(SrcFile, 1);
AssignFile(DstFile, DestFileName);
Rewrite(DstFile, 1);
while not Eof(SrcFile) do
begin
BlockRead(SrcFile, Buf, SizeOf(Buf), BytesRead);
BlockWrite(DstFile, Buf, BytesRead);
end;
CloseFile(DstFile);
CloseFile(SrcFile);
Result := True;
end;
{$ENDIF UNIX}
end;
function FileDateTime(const FileName: string): TDateTime;
{$IFNDEF COMPILER10_UP}
var
Age: Longint;
{$ENDIF !COMPILER10_UP}
begin
{$IFDEF COMPILER10_UP}
if not FileAge(Filename, Result) then
Result := 0;
{$ELSE}
Age := FileAge(FileName);
{$IFDEF MSWINDOWS}
// [roko] -1 is valid FileAge value on Linux
if Age = -1 then
Result := 0
else
{$ENDIF MSWINDOWS}
Result := FileDateToDateTime(Age);
{$ENDIF COMPILER10_UP}
end;
(* DELCIO function FileDelete(const FileName: string; MoveToRecycleBin: Boolean = False): Boolean;
{$IFDEF MSWINDOWS}
begin
if MoveToRecycleBin then
Result := SHDeleteFiles(0, FileName, [doSilent, doAllowUndo, doFilesOnly])
else
Result := {$IFDEF HAS_UNITSCOPE}Winapi.{$ENDIF}Windows.DeleteFile(PChar(FileName));
end;
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
{ TODO : implement MoveToRecycleBin for appropriate Desktops (e.g. KDE) }
begin
Result := remove(PChar(FileName)) <> -1;
end;
{$ENDIF UNIX} *)
function FileExists(const FileName: string): Boolean;
{$IFDEF MSWINDOWS}
var
Attr: Cardinal;
{$ENDIF MSWINDOWS}
begin
if FileName <> '' then
begin
{$IFDEF MSWINDOWS}
// FileGetSize is very slow, GetFileAttributes is much faster
Attr := GetFileAttributes(Pointer(Filename));
Result := (Attr <> $FFFFFFFF) and (Attr and FILE_ATTRIBUTE_DIRECTORY = 0);
{$ELSE ~MSWINDOWS}
// Attempt to access the file, doesn't matter how, using FileGetSize is as good as anything else.
Result := FileGetSize(FileName) <> -1;
{$ENDIF ~MSWINDOWS}
end
else
Result := False;
end;
(* DELCIO
procedure FileHistory(const FileName: string; HistoryPath: string = ''; MaxHistoryCount: Integer = 100; MinFileDate:
TDateTime = 0; ReplaceExtention: Boolean = true);
Function Extention (Number : Integer) : String;
begin
Result := inttostr(Number);
while Length(Result) < 3 do
Result := '0' + Result;
Result := '.~'+Result+'~';
end;
procedure RenameToNumber(const RenameFileName: string; Number: Integer);
var
f1: string;
f2: string;
begin
f1 := ChangeFileExt(RenameFileName,Extention(Number-1));
f2 := ChangeFileExt(RenameFileName,Extention(Number));
if FileExists(f2) then
if Number >= MaxHistoryCount then
if not FileDelete(f2) then
Exception.Create('Unable to delete file "' + f2 + '".')
else
else
RenameToNumber(RenameFileName, Number + 1);
if FileExists(f1) then
if not FileMove(f1, f2, true) then
Exception.Create('Unable to rename file "' + f1 + '" to "' + f2 + '".')
end;
Var FirstFile : string;
begin
// TODO -cMM: FileHistory default body inserted
if not FileExists(FileName) or (MaxHistoryCount <= 0) then
Exit;
if HistoryPath = '' then
HistoryPath := ExtractFilePath(FileName);
FirstFile := PathAppend(HistoryPath, ExtractFileName(FileName));
if ReplaceExtention then
FirstFile := ChangeFileExt(FirstFile, Extention(1))
else
FirstFile := FirstFile+Extention(1);
if (FileDateTime(FirstFile) > MinFileDate) and (MinFileDate <> 0) then
Exit;
RenameToNumber(FirstFile, 2);
FileCopy(FileName, FirstFile, True);
end; *)
(* DELCIO
function FileMove(const ExistingFileName, NewFileName: string; ReplaceExisting: Boolean = False): Boolean;
{$IFDEF MSWINDOWS}
const
Flag: array[Boolean] of Cardinal = (0, MOVEFILE_REPLACE_EXISTING);
{$ENDIF MSWINDOWS}
begin
{$IFDEF MSWINDOWS}
Result := MoveFileEx(PChar(ExistingFileName), PChar(NewFileName), Flag[ReplaceExisting]);
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
Result := __rename(PChar(ExistingFileName), PChar(NewFileName)) = 0;
{$ENDIF UNIX}
if not Result then
begin
Result := FileCopy(ExistingFileName, NewFileName, ReplaceExisting);
if Result then
FileDelete(ExistingFileName);
end;
end; *)
(* DELCIO
function FileRestore(const FileName: string): Boolean;
var
TempFileName: string;
begin
Result := False;
TempFileName := FileGetTempName('');
if FileMove(GetBackupFileName(FileName), TempFileName, True) then
if FileBackup(FileName, False) then
Result := FileMove(TempFileName, FileName, True);
end; *)
function GetBackupFileName(const FileName: string): string;
var
NewExt: string;
begin
NewExt := ExtractFileExt(FileName);
if Length(NewExt) > 0 then
begin
NewExt[1] := '~';
NewExt := '.' + NewExt
end
else
NewExt := '.~';
Result := ChangeFileExt(FileName, NewExt);
end;
function IsBackupFileName(const FileName: string): Boolean;
begin
Result := (pos('.~', ExtractFileExt(FileName)) = 1);
end;
function FileGetDisplayName(const FileName: string): string;
{$IFDEF MSWINDOWS}
var
FileInfo: TSHFileInfo;
begin
ResetMemory(FileInfo, SizeOf(FileInfo));
if SHGetFileInfo(PChar(FileName), 0, FileInfo, SizeOf(FileInfo), SHGFI_DISPLAYNAME) <> 0 then
Result := FileInfo.szDisplayName
else
Result := FileName;
end;
{$ELSE ~MSWINDOWS}
begin
{ TODO -cHelp : mention this reduced solution }
Result := FileName;
end;
{$ENDIF ~MSWINDOWS}
(* DELCIO
function FileGetGroupName(const FileName: string {$IFDEF UNIX}; ResolveSymLinks: Boolean = True {$ENDIF}): string;
{$IFDEF MSWINDOWS}
var
DomainName: WideString;
TmpResult: WideString;
pSD: PSecurityDescriptor;
BufSize: DWORD;
begin
if IsWinNT then
begin
BufSize := 0;
GetFileSecurity(PChar(FileName), GROUP_SECURITY_INFORMATION, nil, 0, BufSize);
if BufSize > 0 then
begin
GetMem(pSD, BufSize);
GetFileSecurity(PChar(FileName), GROUP_SECURITY_INFORMATION,
pSD, BufSize, BufSize);
LookupAccountBySid(Pointer(TJclAddr(pSD) + TJclAddr(pSD^.Group)), TmpResult, DomainName, True);
FreeMem(pSD);
Result := Trim(TmpResult);
end;
end;
end;
{$ENDIF ~MSWINDOWS}
{$IFDEF UNIX}
var
Buf: TStatBuf64;
ResultBuf: TGroup;
ResultBufPtr: PGroup;
Buffer: array of Char;
begin
if GetFileStatus(FileName, Buf, ResolveSymLinks) = 0 then
begin
SetLength(Buffer, 128);
while getgrgid_r(Buf.st_gid, ResultBuf, @Buffer[0], Length(Buffer), ResultBufPtr) = ERANGE do
SetLength(Buffer, Length(Buffer) * 2);
Result := ResultBuf.gr_name;
end;
end;
{$ENDIF ~UNIX} *)
(* DELCIO
function FileGetOwnerName(const FileName: string {$IFDEF UNIX}; ResolveSymLinks: Boolean = True {$ENDIF}): string;
{$IFDEF MSWINDOWS}
var
DomainName: WideString;
TmpResult: WideString;
pSD: PSecurityDescriptor;
BufSize: DWORD;
begin
if IsWinNT then
begin
BufSize := 0;
GetFileSecurity(PChar(FileName), OWNER_SECURITY_INFORMATION, nil, 0, BufSize);
if BufSize > 0 then
begin
GetMem(pSD, BufSize);
try
GetFileSecurity(PChar(FileName), OWNER_SECURITY_INFORMATION,
pSD, BufSize, BufSize);
LookupAccountBySid(Pointer(TJclAddr(pSD) + TJclAddr(pSD^.Owner)), TmpResult, DomainName, True);
finally
FreeMem(pSD);
end;
Result := Trim(TmpResult);
end;
end;
end;
{$ENDIF ~MSWINDOWS}
{$IFDEF UNIX}
var
Buf: TStatBuf64;
ResultBuf: TPasswordRecord;
ResultBufPtr: PPasswordRecord;
Buffer: array of Char;
begin
if GetFileStatus(FileName, Buf, ResolveSymLinks) = 0 then
begin
SetLength(Buffer, 128);
while getpwuid_r(Buf.st_uid, ResultBuf, @Buffer[0], Length(Buffer), ResultBufPtr) = ERANGE do
SetLength(Buffer, Length(Buffer) * 2);
Result := ResultBuf.pw_name;
end;
end;
{$ENDIF ~UNIX} *)
function FileGetSize(const FileName: string): Int64;
{$IFDEF MSWINDOWS}
var
FileAttributesEx: WIN32_FILE_ATTRIBUTE_DATA;
OldMode: Cardinal;
Size: TJclULargeInteger;
begin
Result := -1;
OldMode := SetErrorMode(SEM_FAILCRITICALERRORS);
try
if GetFileAttributesEx(PChar(FileName), GetFileExInfoStandard, @FileAttributesEx) then
begin
Size.LowPart := FileAttributesEx.nFileSizeLow;
Size.HighPart := FileAttributesEx.nFileSizeHigh;
Result := Size.QuadPart;
end;
finally
SetErrorMode(OldMode);
end;
end;
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
var
Buf: TStatBuf64;
begin
Result := -1;
if GetFileStatus(FileName, Buf, False) = 0 then
Result := Buf.st_size;
end;
{$ENDIF UNIX}
{$IFDEF MSWINDOWS}
{$IFDEF FPC}
{ TODO : Move this over to JclWin32 when JclWin32 gets overhauled. }
function GetTempFileName(lpPathName, lpPrefixString: PChar;
uUnique: UINT; lpTempFileName: PChar): UINT; stdcall;
external kernel32 name 'GetTempFileNameA';
{$ENDIF FPC}
{$ENDIF MSWINDOWS}
function FileGetTempName(const Prefix: string): string;
{$IFDEF MSWINDOWS}
var
TempPath, TempFile: string;
R: Cardinal;
begin
Result := '';
TempPath := PathGetTempPath;
if TempPath <> '' then
begin
SetLength(TempFile, MAX_PATH);
R := GetTempFileName(PChar(TempPath), PChar(Prefix), 0, PChar(TempFile));
if R <> 0 then
begin
StrResetLength(TempFile);
Result := TempFile;
end;
end;
end;
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
// Warning: Between the time the pathname is constructed and the file is created
// another process might have created a file with the same name using tmpnam,
// leading to a possible security hole. The implementation generates names which
// can hardly be predicted, but when opening the file you should use the O_EXCL
// flag. Using tmpfile or mkstemp is a safe way to avoid this problem.
var
P: PChar;
begin
P := tempnam(PChar(PathGetTempPath), PChar(Prefix));
Result := P;
Libc.free(P);
end;
{$ENDIF UNIX}
{$IFDEF MSWINDOWS}
function FileGetTypeName(const FileName: string): string;
var
FileInfo: TSHFileInfo;
RetVal: DWORD;
begin
ResetMemory(FileInfo, SizeOf(FileInfo));
RetVal := SHGetFileInfo(PChar(FileName), 0, FileInfo, SizeOf(FileInfo),
SHGFI_TYPENAME or SHGFI_USEFILEATTRIBUTES);
if RetVal <> 0 then
Result := FileInfo.szTypeName;
if (RetVal = 0) or (Trim(Result) = '') then
begin
// Lookup failed so mimic explorer behaviour by returning "XYZ File"
Result := ExtractFileExt(FileName);
Delete(Result, 1, 1);
Result := TrimLeft(UpperCase(Result) + LoadResString(@RsDefaultFileTypeName));
end;
end;
{$ENDIF MSWINDOWS}
function FindUnusedFileName(FileName: string; const FileExt: string; NumberPrefix: string = ''): string;
var
I: Integer;
begin
Result := PathAddExtension(FileName, FileExt);
if not FileExists(Result) then
Exit;
if SameText(Result, FileName) then
Delete(FileName, Length(FileName) - Length(FileExt) + 1, Length(FileExt));
I := 0;
repeat
Inc(I);
Result := PathAddExtension(FileName + NumberPrefix + IntToStr(I), FileExt);
until not FileExists(Result);
end;
// This routine is copied from FileCtrl.pas to avoid dependency on that unit.
// See the remark at the top of this section
function ForceDirectories(Name: string): Boolean;
var
ExtractPath: string;
begin
Result := True;
if Length(Name) = 0 then
raise EJclFileUtilsError.CreateRes(@RsCannotCreateDir);
Name := PathRemoveSeparator(Name);
{$IFDEF MSWINDOWS}
ExtractPath := ExtractFilePath(Name);
if ((Length(Name) = 2) and (Copy(Name, 2,1) = ':')) or DirectoryExists(Name) or (ExtractPath = Name) then
Exit;
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
if (Length(Name) = 0) or DirectoryExists(Name) then
Exit;
ExtractPath := ExtractFilePath(Name);
{$ENDIF UNIX}
Result := (ExtractPath = '') or ForceDirectories(ExtractPath);
if Result then
begin
{$IFDEF MSWINDOWS}
SetLastError(ERROR_SUCCESS);
{$ENDIF MSWINDOWS}
Result := Result and CreateDir(Name);
{$IFDEF MSWINDOWS}
Result := Result or (GetLastError = ERROR_ALREADY_EXISTS);
{$ENDIF MSWINDOWS}
end;
end;
function GetDirectorySize(const Path: string): Int64;
function RecurseFolder(const Path: string): Int64;
var
F: TSearchRec;
R: Integer;
{$IFDEF MSWINDOWS}
TempSize: TJclULargeInteger;
{$ENDIF MSWINDOWS}
begin
Result := 0;
R := {$IFDEF HAS_UNITSCOPE}System.{$ENDIF}SysUtils.FindFirst(Path + '*.*', faAnyFile, F);
if R = 0 then
try
while R = 0 do
begin
if (F.Name <> '.') and (F.Name <> '..') then
begin
if (F.Attr and faDirectory) = faDirectory then
Inc(Result, RecurseFolder(Path + F.Name + DirDelimiter))
else
{$IFDEF MSWINDOWS}
begin
TempSize.LowPart := F.FindData.nFileSizeLow;
TempSize.HighPart := F.FindData.nFileSizeHigh;
Inc(Result, TempSize.QuadPart);
end;
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
// SysUtils.Find* don't perceive files >= 2 GB anyway
Inc(Result, Int64(F.Size));
{$ENDIF UNIX}
end;
R := {$IFDEF HAS_UNITSCOPE}System.{$ENDIF}SysUtils.FindNext(F);
end;
if R <> ERROR_NO_MORE_FILES then
Abort;
finally
{$IFDEF HAS_UNITSCOPE}System.{$ENDIF}SysUtils.FindClose(F);
end;
end;
begin
if not DirectoryExists(PathRemoveSeparator(Path)) then
Result := -1
else
try
Result := RecurseFolder(PathAddSeparator(Path))
except
Result := -1;
end;
end;
{$IFDEF MSWINDOWS}
function GetDriveTypeStr(const Drive: Char): string;
var
DriveType: Integer;
DriveStr: string;
begin
if not CharIsDriveLetter(Drive) then
raise EJclPathError.CreateResFmt(@RsPathInvalidDrive, [Drive]);
DriveStr := Drive + ':\';
DriveType := GetDriveType(PChar(DriveStr));
case DriveType of
DRIVE_REMOVABLE:
Result := LoadResString(@RsRemovableDrive);
DRIVE_FIXED:
Result := LoadResString(@RsHardDisk);
DRIVE_REMOTE:
Result := LoadResString(@RsRemoteDrive);
DRIVE_CDROM:
Result := LoadResString(@RsCDRomDrive);
DRIVE_RAMDISK:
Result := LoadResString(@RsRamDisk);
else
Result := LoadResString(@RsUnknownDrive);
end;
end;
function GetFileAgeCoherence(const FileName: string): Boolean;
var
FileAttributesEx: WIN32_FILE_ATTRIBUTE_DATA;
begin
Result := False;
if GetFileAttributesEx(PChar(FileName), GetFileExInfoStandard, @FileAttributesEx) then
{$IFDEF FPC}
Result := CompareFileTime(@FileAttributesEx.ftCreationTime, @FileAttributesEx.ftLastWriteTime) <= 0;
{$ELSE ~FPC}
Result := CompareFileTime(FileAttributesEx.ftCreationTime, FileAttributesEx.ftLastWriteTime) <= 0;
{$ENDIF ~FPC}
end;
{$ENDIF MSWINDOWS}
procedure GetFileAttributeList(const Items: TStrings; const Attr: Integer);
begin
{ TODO : clear list? }
Assert(Assigned(Items));
if not Assigned(Items) then
Exit;
Items.BeginUpdate;
try
{ TODO : differentiate Windows/UNIX idents }
if Attr and faDirectory = faDirectory then
Items.Add(LoadResString(@RsAttrDirectory));
if Attr and faReadOnly = faReadOnly then
Items.Add(LoadResString(@RsAttrReadOnly));
if Attr and faSysFile = faSysFile then
Items.Add(LoadResString(@RsAttrSystemFile));
if Attr and faArchive = faArchive then
Items.Add(LoadResString(@RsAttrArchive));
if Attr and faAnyFile = faAnyFile then
Items.Add(LoadResString(@RsAttrAnyFile));
if Attr and faHidden = faHidden then
Items.Add(LoadResString(@RsAttrHidden));
finally
Items.EndUpdate;
end;
end;
{$IFDEF MSWINDOWS}
{ TODO : GetFileAttributeListEx - Unix version }
procedure GetFileAttributeListEx(const Items: TStrings; const Attr: Integer);
begin
{ TODO : clear list? }
Assert(Assigned(Items));
if not Assigned(Items) then
Exit;
Items.BeginUpdate;
try
if Attr and FILE_ATTRIBUTE_READONLY = FILE_ATTRIBUTE_READONLY then
Items.Add(LoadResString(@RsAttrReadOnly));
if Attr and FILE_ATTRIBUTE_HIDDEN = FILE_ATTRIBUTE_HIDDEN then
Items.Add(LoadResString(@RsAttrHidden));
if Attr and FILE_ATTRIBUTE_SYSTEM = FILE_ATTRIBUTE_SYSTEM then
Items.Add(LoadResString(@RsAttrSystemFile));
if Attr and FILE_ATTRIBUTE_DIRECTORY = FILE_ATTRIBUTE_DIRECTORY then
Items.Add(LoadResString(@RsAttrDirectory));
if Attr and FILE_ATTRIBUTE_ARCHIVE = FILE_ATTRIBUTE_ARCHIVE then
Items.Add(LoadResString(@RsAttrArchive));
if Attr and FILE_ATTRIBUTE_NORMAL = FILE_ATTRIBUTE_NORMAL then
Items.Add(LoadResString(@RsAttrNormal));
if Attr and FILE_ATTRIBUTE_TEMPORARY = FILE_ATTRIBUTE_TEMPORARY then
Items.Add(LoadResString(@RsAttrTemporary));
if Attr and FILE_ATTRIBUTE_COMPRESSED = FILE_ATTRIBUTE_COMPRESSED then
Items.Add(LoadResString(@RsAttrCompressed));
if Attr and FILE_ATTRIBUTE_OFFLINE = FILE_ATTRIBUTE_OFFLINE then
Items.Add(LoadResString(@RsAttrOffline));
if Attr and FILE_ATTRIBUTE_ENCRYPTED = FILE_ATTRIBUTE_ENCRYPTED then
Items.Add(LoadResString(@RsAttrEncrypted));
if Attr and FILE_ATTRIBUTE_REPARSE_POINT = FILE_ATTRIBUTE_REPARSE_POINT then
Items.Add(LoadResString(@RsAttrReparsePoint));
if Attr and FILE_ATTRIBUTE_SPARSE_FILE = FILE_ATTRIBUTE_SPARSE_FILE then
Items.Add(LoadResString(@RsAttrSparseFile));
finally
Items.EndUpdate;
end;
end;
{$ENDIF MSWINDOWS}
function GetFileInformation(const FileName: string; out FileInfo: TSearchRec): Boolean;
begin
Result := FindFirst(FileName, faAnyFile, FileInfo) = 0;
if Result then
{$IFDEF HAS_UNITSCOPE}System.{$ENDIF}SysUtils.FindClose(FileInfo);
end;
function GetFileInformation(const FileName: string): TSearchRec;
begin
if not GetFileInformation(FileName, Result) then
RaiseLastOSError;
end;
{$IFDEF UNIX}
{ TODO -cHelp : Author: Robert Rossmair }
function GetFileStatus(const FileName: string; out StatBuf: TStatBuf64;
const ResolveSymLinks: Boolean): Integer;
begin
if ResolveSymLinks then
Result := stat64(PChar(FileName), StatBuf)
else
Result := lstat64(PChar(FileName), StatBuf);
end;
{$ENDIF UNIX}
(*
{$IFDEF MSWINDOWS}
function GetFileLastWrite(const FileName: string): TFileTime;
begin
Result := GetFileInformation(FileName).FindData.ftLastWriteTime;
end;
function GetFileLastWrite(const FileName: string; out LocalTime: TDateTime): Boolean;
var
FileInfo: TSearchRec;
begin
Result := GetFileInformation(FileName, FileInfo);
if Result then
LocalTime := FileTimeToLocalDateTime(FileInfo.FindData.ftLastWriteTime);
end;
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
function GetFileLastWrite(const FileName: string; out TimeStamp: Integer; ResolveSymLinks: Boolean): Boolean;
var
Buf: TStatBuf64;
begin
Result := GetFileStatus(FileName, Buf, ResolveSymLinks) = 0;
if Result then
TimeStamp := Buf.st_mtime
end;
function GetFileLastWrite(const FileName: string; out LocalTime: TDateTime; ResolveSymLinks: Boolean): Boolean;
var
Buf: TStatBuf64;
begin
Result := GetFileStatus(FileName, Buf, ResolveSymLinks) = 0;
if Result then
LocalTime := FileDateToDateTime(Buf.st_mtime);
end;
function GetFileLastWrite(const FileName: string; ResolveSymLinks: Boolean): Integer;
var
Buf: TStatBuf64;
begin
if GetFileStatus(FileName, Buf, ResolveSymLinks) = 0 then
Result := Buf.st_mtime
else
Result := -1;
end;
{$ENDIF UNIX} *)
(* DELCIO
{$IFDEF MSWINDOWS}
function GetFileLastAccess(const FileName: string): TFileTime;
begin
Result := GetFileInformation(FileName).FindData.ftLastAccessTime;
end;
function GetFileLastAccess(const FileName: string; out LocalTime: TDateTime): Boolean;
var
FileInfo: TSearchRec;
begin
Result := GetFileInformation(FileName, FileInfo);
if Result then
LocalTime := FileTimeToLocalDateTime(GetFileInformation(FileName).FindData.ftLastAccessTime);
end;
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
function GetFileLastAccess(const FileName: string; out TimeStamp: Integer; ResolveSymLinks: Boolean): Boolean;
var
Buf: TStatBuf64;
begin
Result := GetFileStatus(FileName, Buf, ResolveSymLinks) = 0;
if Result then
TimeStamp := Buf.st_atime
end;
function GetFileLastAccess(const FileName: string; out LocalTime: TDateTime; ResolveSymLinks: Boolean): Boolean;
var
Buf: TStatBuf64;
begin
Result := GetFileStatus(FileName, Buf, ResolveSymLinks) = 0;
if Result then
LocalTime := FileDateToDateTime(Buf.st_atime);
end;
function GetFileLastAccess(const FileName: string; ResolveSymLinks: Boolean): Integer;
var
Buf: TStatBuf64;
begin
if GetFileStatus(FileName, Buf, ResolveSymLinks) = 0 then
Result := Buf.st_atime
else
Result := -1;
end;
{$ENDIF UNIX} *)
(* DELCIO
{$IFDEF MSWINDOWS}
function GetFileCreation(const FileName: string): TFileTime;
begin
Result := GetFileInformation(FileName).FindData.ftCreationTime;
end;
function GetFileCreation(const FileName: string; out LocalTime: TDateTime): Boolean;
var
FileInfo: TSearchRec;
begin
Result := GetFileInformation(FileName, FileInfo);
if Result then
LocalTime := FileTimeToLocalDateTime(GetFileInformation(FileName).FindData.ftCreationTime);
end;
{$ENDIF MSWINDOWS} *)
{$IFDEF UNIX}
function GetFileLastAttrChange(const FileName: string; out TimeStamp: Integer; ResolveSymLinks: Boolean): Boolean;
var
Buf: TStatBuf64;
begin
Result := GetFileStatus(FileName, Buf, ResolveSymLinks) = 0;
if Result then
TimeStamp := Buf.st_ctime
end;
function GetFileLastAttrChange(const FileName: string; out LocalTime: TDateTime; ResolveSymLinks: Boolean): Boolean;
var
Buf: TStatBuf64;
begin
Result := GetFileStatus(FileName, Buf, ResolveSymLinks) = 0;
if Result then
LocalTime := FileDateToDateTime(Buf.st_ctime);
end;
function GetFileLastAttrChange(const FileName: string; ResolveSymLinks: Boolean): Integer;
var
Buf: TStatBuf64;
begin
if GetFileStatus(FileName, Buf, ResolveSymLinks) = 0 then
Result := Buf.st_ctime
else
Result := -1;
end;
{$ENDIF UNIX}
function GetModulePath(const Module: HMODULE): string;
var
L: Integer;
begin
L := MAX_PATH + 1;
SetLength(Result, L);
{$IFDEF MSWINDOWS}
L := {$IFDEF HAS_UNITSCOPE}Winapi.{$ENDIF}Windows.GetModuleFileName(Module, Pointer(Result), L);
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
{$IFDEF FPC}
L := 0; // FIXME
{$ELSE ~FPC}
L := GetModuleFileName(Module, Pointer(Result), L);
{$ENDIF ~FPC}
{$ENDIF UNIX}
SetLength(Result, L);
end;
function GetSizeOfFile(const FileName: string): Int64;
{$IFDEF MSWINDOWS}
var
FileAttributesEx: WIN32_FILE_ATTRIBUTE_DATA;
Size: TJclULargeInteger;
begin
Result := 0;
if GetFileAttributesEx(PChar(FileName), GetFileExInfoStandard, @FileAttributesEx) then
begin
Size.LowPart := FileAttributesEx.nFileSizeLow;
Size.HighPart := FileAttributesEx.nFileSizeHigh;
Result := Size.QuadPart;
end
else
RaiseLastOSError;
end;
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
var
Buf: TStatBuf64;
begin
if GetFileStatus(FileName, Buf, False) <> 0 then
RaiseLastOSError;
Result := Buf.st_size;
end;
{$ENDIF UNIX}
{$IFDEF MSWINDOWS}
function GetSizeOfFile(Handle: THandle): Int64; overload;
var
Size: TJclULargeInteger;
begin
Size.LowPart := GetFileSize(Handle, @Size.HighPart);
Result := Size.QuadPart;
end;
{$ENDIF MSWINDOWS}
function GetSizeOfFile(const FileInfo: TSearchRec): Int64;
{$IFDEF MSWINDOWS}
begin
Int64Rec(Result).Lo := FileInfo.FindData.nFileSizeLow;
Int64Rec(Result).Hi := FileInfo.FindData.nFileSizeHigh;
end;
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
var
Buf: TStatBuf64;
begin
// rr: Note that SysUtils.FindFirst/Next ignore files >= 2 GB under Linux,
// thus the following code is rather pointless at the moment of this writing.
// We apparently need to write our own set of Findxxx functions to overcome this limitation.
if GetFileStatus(FileInfo.PathOnly + FileInfo.Name, Buf, True) <> 0 then
Result := -1
else
Result := Buf.st_size
end;
{$ENDIF UNIX}
{$IFDEF MSWINDOWS}
{$IFDEF FPC}
{ TODO : Move this over to JclWin32 when JclWin32 gets overhauled. }
function GetFileAttributesEx(lpFileName: PChar;
fInfoLevelId: TGetFileExInfoLevels; lpFileInformation: Pointer): BOOL; stdcall;
external kernel32 name 'GetFileAttributesExA';
{$ENDIF FPC}
function GetStandardFileInfo(const FileName: string): TWin32FileAttributeData;
var
Handle: THandle;
FileInfo: TByHandleFileInformation;
begin
Assert(FileName <> '');
{ TODO : Use RTDL-Version of GetFileAttributesEx }
if IsWin95 or IsWin95OSR2 or IsWinNT3 then
begin
Handle := CreateFile(PChar(FileName), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0);
if Handle <> INVALID_HANDLE_VALUE then
try
FileInfo.dwFileAttributes := 0;
if not GetFileInformationByHandle(Handle, FileInfo) then
raise EJclFileUtilsError.CreateResFmt(@RsFileUtilsAttrUnavailable, [FileName]);
Result.dwFileAttributes := FileInfo.dwFileAttributes;
Result.ftCreationTime := FileInfo.ftCreationTime;
Result.ftLastAccessTime := FileInfo.ftLastAccessTime;
Result.ftLastWriteTime := FileInfo.ftLastWriteTime;
Result.nFileSizeHigh := FileInfo.nFileSizeHigh;
Result.nFileSizeLow := FileInfo.nFileSizeLow;
finally
CloseHandle(Handle);
end
else
raise EJclFileUtilsError.CreateResFmt(@RsFileUtilsAttrUnavailable, [FileName]);
end
else
begin
if not GetFileAttributesEx(PChar(FileName), GetFileExInfoStandard, @Result) then
raise EJclFileUtilsError.CreateResFmt(@RsFileUtilsAttrUnavailable, [FileName]);
end;
end;
{$ENDIF MSWINDOWS}
{$IFDEF MSWINDOWS}
function IsDirectory(const FileName: string): Boolean;
var
R: DWORD;
begin
R := GetFileAttributes(PChar(FileName));
Result := (R <> DWORD(-1)) and ((R and FILE_ATTRIBUTE_DIRECTORY) <> 0);
end;
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
function IsDirectory(const FileName: string; ResolveSymLinks: Boolean): Boolean;
var
Buf: TStatBuf64;
begin
Result := False;
if GetFileStatus(FileName, Buf, ResolveSymLinks) = 0 then
Result := S_ISDIR(Buf.st_mode);
end;
{$ENDIF UNIX}
function IsRootDirectory(const CanonicFileName: string): Boolean;
{$IFDEF MSWINDOWS}
var
I: Integer;
begin
I := Pos(':\', CanonicFileName);
Result := (I > 0) and (I + 1 = Length(CanonicFileName));
end;
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
begin
Result := CanonicFileName = DirDelimiter;
end;
{$ENDIF UNIX}
{$IFDEF MSWINDOWS}
function LockVolume(const Volume: string; var Handle: THandle): Boolean;
var
BytesReturned: DWORD;
begin
Result := False;
Handle := CreateFile(PChar('\\.\' + Volume), GENERIC_READ or GENERIC_WRITE,
FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING,
FILE_FLAG_NO_BUFFERING, 0);
if Handle <> INVALID_HANDLE_VALUE then
begin
BytesReturned := 0;
Result := DeviceIoControl(Handle, FSCTL_LOCK_VOLUME, nil, 0, nil, 0,
BytesReturned, nil);
if not Result then
begin
CloseHandle(Handle);
Handle := INVALID_HANDLE_VALUE;
end;
end;
end;
function OpenVolume(const Drive: Char): THandle;
var
VolumeName: array [0..6] of Char;
begin
VolumeName := '\\.\A:';
VolumeName[4] := Drive;
Result := CreateFile(VolumeName, GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE,
nil, OPEN_EXISTING, 0, 0);
end;
{$ENDIF MSWINDOWS}
type
// indicates the file time to set, used by SetFileTimesHelper and SetDirTimesHelper
TFileTimes = (ftLastAccess, ftLastWrite {$IFDEF MSWINDOWS}, ftCreation {$ENDIF});
{$IFDEF MSWINDOWS}
function SetFileTimesHelper(const FileName: string; const DateTime: TDateTime; Times: TFileTimes): Boolean;
var
Handle: THandle;
FileTime: TFileTime;
SystemTime: TSystemTime;
begin
Result := False;
Handle := CreateFile(PChar(FileName), GENERIC_WRITE, FILE_SHARE_READ, nil,
OPEN_EXISTING, 0, 0);
if Handle <> INVALID_HANDLE_VALUE then
try
//SysUtils.DateTimeToSystemTime(DateTimeToLocalDateTime(DateTime), SystemTime);
{$IFDEF HAS_UNITSCOPE}System.{$ENDIF}SysUtils.DateTimeToSystemTime(DateTime, SystemTime);
FileTime.dwLowDateTime := 0;
FileTime.dwHighDateTime := 0;
if {$IFDEF HAS_UNITSCOPE}Winapi.{$ENDIF}Windows.SystemTimeToFileTime(SystemTime, FileTime) then
begin
case Times of
ftLastAccess:
Result := SetFileTime(Handle, nil, @FileTime, nil);
ftLastWrite:
Result := SetFileTime(Handle, nil, nil, @FileTime);
ftCreation:
Result := SetFileTime(Handle, @FileTime, nil, nil);
end;
end;
finally
CloseHandle(Handle);
end;
end;
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
function SetFileTimesHelper(const FileName: string; const DateTime: TDateTime; Times: TFileTimes): Boolean;
var
FileTime: Integer;
StatBuf: TStatBuf64;
TimeBuf: utimbuf;
begin
Result := False;
FileTime := DateTimeToFileDate(DateTime);
if GetFileStatus(FileName, StatBuf, False) = 0 then
begin
TimeBuf.actime := StatBuf.st_atime;
TimeBuf.modtime := StatBuf.st_mtime;
case Times of
ftLastAccess:
TimeBuf.actime := FileTime;
ftLastWrite:
TimeBuf.modtime := FileTime;
end;
Result := utime(PChar(FileName), @TimeBuf) = 0;
end;
end;
{$ENDIF UNIX}
function SetFileLastAccess(const FileName: string; const DateTime: TDateTime): Boolean;
begin
Result := SetFileTimesHelper(FileName, DateTime, ftLastAccess);
end;
function SetFileLastWrite(const FileName: string; const DateTime: TDateTime): Boolean;
begin
Result := SetFileTimesHelper(FileName, DateTime, ftLastWrite);
end;
{$IFDEF MSWINDOWS}
function SetFileCreation(const FileName: string; const DateTime: TDateTime): Boolean;
begin
Result := SetFileTimesHelper(FileName, DateTime, ftCreation);
end;
// utility function for SetDirTimesHelper
(* DELCIO
function BackupPrivilegesEnabled: Boolean;
begin
Result := IsPrivilegeEnabled(SE_BACKUP_NAME) and IsPrivilegeEnabled(SE_RESTORE_NAME);
end; *)
(* DELCIO
function SetDirTimesHelper(const DirName: string; const DateTime: TDateTime;
Times: TFileTimes; RequireBackupRestorePrivileges: Boolean): Boolean;
var
Handle: THandle;
FileTime: TFileTime;
SystemTime: TSystemTime;
begin
Result := False;
if IsDirectory(DirName) and (not RequireBackupRestorePrivileges or BackupPrivilegesEnabled) then
begin
Handle := CreateFile(PChar(DirName), GENERIC_WRITE, FILE_SHARE_READ, nil,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
if Handle <> INVALID_HANDLE_VALUE then
try
{$IFDEF HAS_UNITSCOPE}System.{$ENDIF}SysUtils.DateTimeToSystemTime(DateTime, SystemTime);
FileTime.dwLowDateTime := 0;
FileTime.dwHighDateTime := 0;
{$IFDEF HAS_UNITSCOPE}Winapi.{$ENDIF}Windows.SystemTimeToFileTime(SystemTime, FileTime);
case Times of
ftLastAccess:
Result := SetFileTime(Handle, nil, @FileTime, nil);
ftLastWrite:
Result := SetFileTime(Handle, nil, nil, @FileTime);
ftCreation:
Result := SetFileTime(Handle, @FileTime, nil, nil);
end;
finally
CloseHandle(Handle);
end;
end;
end;
function SetDirLastWrite(const DirName: string; const DateTime: TDateTime; RequireBackupRestorePrivileges: Boolean = True): Boolean;
begin
Result := SetDirTimesHelper(DirName, DateTime, ftLastWrite, RequireBackupRestorePrivileges);
end;
function SetDirLastAccess(const DirName: string; const DateTime: TDateTime; RequireBackupRestorePrivileges: Boolean = True): Boolean;
begin
Result := SetDirTimesHelper(DirName, DateTime, ftLastAccess, RequireBackupRestorePrivileges);
end;
function SetDirCreation(const DirName: string; const DateTime: TDateTime; RequireBackupRestorePrivileges: Boolean = True): Boolean;
begin
Result := SetDirTimesHelper(DirName, DateTime, ftCreation, RequireBackupRestorePrivileges);
end;
*)
procedure FillByteArray(var Bytes: array of Byte; Count: Cardinal; B: Byte);
begin
FillMemory(@Bytes[0], Count, B);
end;
procedure ShredFile(const FileName: string; Times: Integer);
const
BUFSIZE = 4096;
ODD_FILL = $C1;
EVEN_FILL = $3E;
var
Fs: TFileStream;
Size: Integer;
N: Integer;
ContentPtr: array of Byte;
begin
Size := FileGetSize(FileName);
if Size > 0 then
begin
if Times < 0 then
Times := 2
else
Times := Times * 2;
ContentPtr := nil;
Fs := TFileStream.Create(FileName, fmOpenReadWrite);
try
SetLength(ContentPtr, BUFSIZE);
while Times > 0 do
begin
if Times mod 2 = 0 then
FillByteArray(ContentPtr, BUFSIZE, EVEN_FILL)
else
FillByteArray(ContentPtr, BUFSIZE, ODD_FILL);
Fs.Seek(0, soBeginning);
N := Size div BUFSIZE;
while N > 0 do
begin
Fs.Write(ContentPtr[0], BUFSIZE);
Dec(N);
end;
N := Size mod BUFSIZE;
if N > 0 then
Fs.Write(ContentPtr[0], N);
FlushFileBuffers(Fs.Handle);
Dec(Times);
end;
finally
ContentPtr := nil;
Fs.Free;
DeleteFile(FileName);
end;
end
else
DeleteFile(FileName);
end;
function UnlockVolume(var Handle: THandle): Boolean;
var
BytesReturned: DWORD;
begin
Result := False;
if Handle <> INVALID_HANDLE_VALUE then
begin
BytesReturned := 0;
Result := DeviceIoControl(Handle, FSCTL_UNLOCK_VOLUME, nil, 0, nil, 0,
BytesReturned, nil);
if Result then
begin
CloseHandle(Handle);
Handle := INVALID_HANDLE_VALUE;
end;
end;
end;
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
function CreateSymbolicLink(const Name, Target: string): Boolean;
begin
Result := symlink(PChar(Target), PChar(Name)) = 0;
end;
function SymbolicLinkTarget(const Name: string): string;
var
N, BufLen: Integer;
begin
BufLen := 128;
repeat
Inc(BufLen, BufLen);
SetLength(Result, BufLen);
N := readlink(PChar(Name), PChar(Result), BufLen);
if N < 0 then // Error
begin
Result := '';
Exit;
end;
until N < BufLen;
SetLength(Result, N);
end;
{$ENDIF UNIX}
//=== File Version info routines =============================================
{$IFDEF MSWINDOWS}
const
VerKeyNames: array [1..12] of string =
('Comments',
'CompanyName',
'FileDescription',
'FileVersion',
'InternalName',
'LegalCopyright',
'LegalTradeMarks',
'OriginalFilename',
'ProductName',
'ProductVersion',
'SpecialBuild',
'PrivateBuild');
function OSIdentToString(const OSIdent: DWORD): string;
begin
case OSIdent of
VOS_UNKNOWN:
Result := LoadResString(@RsVosUnknown);
VOS_DOS:
Result := LoadResString(@RsVosDos);
VOS_OS216:
Result := LoadResString(@RsVosOS216);
VOS_OS232:
Result := LoadResString(@RsVosOS232);
VOS_NT:
Result := LoadResString(@RsVosNT);
VOS__WINDOWS16:
Result := LoadResString(@RsVosWindows16);
VOS__PM16:
Result := LoadResString(@RsVosPM16);
VOS__PM32:
Result := LoadResString(@RsVosPM32);
VOS__WINDOWS32:
Result := LoadResString(@RsVosWindows32);
VOS_DOS_WINDOWS16:
Result := LoadResString(@RsVosDosWindows16);
VOS_DOS_WINDOWS32:
Result := LoadResString(@RsVosDosWindows32);
VOS_OS216_PM16:
Result := LoadResString(@RsVosOS216PM16);
VOS_OS232_PM32:
Result := LoadResString(@RsVosOS232PM32);
VOS_NT_WINDOWS32:
Result := LoadResString(@RsVosNTWindows32);
else
Result := '';
end;
if Result = '' then
Result := LoadResString(@RsVosUnknown)
else
Result := Format(LoadResString(@RsVosDesignedFor), [Result]);
end;
function OSFileTypeToString(const OSFileType: DWORD; const OSFileSubType: DWORD): string;
begin
case OSFileType of
VFT_UNKNOWN:
Result := LoadResString(@RsVftUnknown);
VFT_APP:
Result := LoadResString(@RsVftApp);
VFT_DLL:
Result := LoadResString(@RsVftDll);
VFT_DRV:
begin
case OSFileSubType of
VFT2_DRV_PRINTER:
Result := LoadResString(@RsVft2DrvPRINTER);
VFT2_DRV_KEYBOARD:
Result := LoadResString(@RsVft2DrvKEYBOARD);
VFT2_DRV_LANGUAGE:
Result := LoadResString(@RsVft2DrvLANGUAGE);
VFT2_DRV_DISPLAY:
Result := LoadResString(@RsVft2DrvDISPLAY);
VFT2_DRV_MOUSE:
Result := LoadResString(@RsVft2DrvMOUSE);
VFT2_DRV_NETWORK:
Result := LoadResString(@RsVft2DrvNETWORK);
VFT2_DRV_SYSTEM:
Result := LoadResString(@RsVft2DrvSYSTEM);
VFT2_DRV_INSTALLABLE:
Result := LoadResString(@RsVft2DrvINSTALLABLE);
VFT2_DRV_SOUND:
Result := LoadResString(@RsVft2DrvSOUND);
VFT2_DRV_COMM:
Result := LoadResString(@RsVft2DrvCOMM);
else
Result := '';
end;
Result := Result + ' ' + LoadResString(@RsVftDrv);
end;
VFT_FONT:
begin
case OSFileSubType of
VFT2_FONT_RASTER:
Result := LoadResString(@RsVft2FontRASTER);
VFT2_FONT_VECTOR:
Result := LoadResString(@RsVft2FontVECTOR);
VFT2_FONT_TRUETYPE:
Result := LoadResString(@RsVft2FontTRUETYPE);
else
Result := '';
end;
Result := Result + ' ' + LoadResString(@RsVftFont);
end;
VFT_VXD:
Result := LoadResString(@RsVftVxd);
VFT_STATIC_LIB:
Result := LoadResString(@RsVftStaticLib);
else
Result := '';
end;
Result := TrimLeft(Result);
end;
function VersionResourceAvailable(const FileName: string): Boolean;
var
Size: DWORD;
Handle: DWORD;
Buffer: string;
begin
Result := False;
Handle := 0;
Size := GetFileVersionInfoSize(PChar(FileName), Handle);
if Size > 0 then
begin
SetLength(Buffer, Size);
Result := GetFileVersionInfo(PChar(FileName), Handle, Size, PChar(Buffer));
end;
end;
function VersionResourceAvailable(const Window: HWND): Boolean;
begin
Result := VersionResourceAvailable(WindowToModuleFileName(Window));
end;
function VersionResourceAvailable(const Module: HMODULE): Boolean;
begin
if Module <> 0 then
Result :=VersionResourceAvailable(GetModulePath(Module))
else
raise EJclError.CreateResFmt(@RsEModuleNotValid, [Module]);
end;
function WindowToModuleFileName(const Window: HWND): string;
type
{$IFDEF SUPPORTS_UNICODE}
TGetModuleFileNameEx = function(hProcess: THandle; hModule: HMODULE; FileName: PWideChar; nSize: DWORD): DWORD; stdcall;
TQueryFullProcessImageName = function(HProcess: THandle; dwFlags: DWORD; lpExeName: PWideChar; lpdwSize: PDWORD): BOOL; stdcall;
{$ELSE ~SUPPORTS_UNICODE}
TGetModuleFileNameEx = function(hProcess: THandle; hModule: HMODULE; FileName: PAnsiChar; nSize: DWORD): DWORD; stdcall;
TQueryFullProcessImageName = function(HProcess: THandle; dwFlags: DWORD; lpExeName: PAnsiChar; lpdwSize: PDWORD): BOOL; stdcall;
{$ENDIF ~SUPPORTS_UNICODE}
var
FileName: array[0..300] of Char;
DllHinst: HMODULE;
ProcessID: DWORD;
HProcess: THandle;
GetModuleFileNameExAddress: TGetModuleFileNameEx;
QueryFullProcessImageNameAddress: TQueryFullProcessImageName;
Len: DWORD;
begin
Result := '';
if Window <> 0 then
begin
if not JclCheckWinVersion(5, 0) then // Win2k or newer required
raise EJclWin32Error.CreateRes(@RsEWindowsVersionNotSupported);
{$IFDEF HAS_UNITSCOPE}Winapi.{$ENDIF}Windows.GetWindowThreadProcessId(Window, @ProcessID);
hProcess := {$IFDEF HAS_UNITSCOPE}Winapi.{$ENDIF}Windows.OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, false, ProcessID);
if hProcess <> 0 then
begin
try
if JclCheckWinVersion(6, 0) then // WinVista or newer
begin
DllHinst := LoadLibrary('Kernel32.dll');
if DllHinst < HINSTANCE_ERROR then
begin
try
{$IFDEF SUPPORTS_UNICODE}
QueryFullProcessImageNameAddress := GetProcAddress(DllHinst, 'QueryFullProcessImageNameW');
{$ELSE ~SUPPORTS_UNICODE}
QueryFullProcessImageNameAddress := GetProcAddress(DllHinst, 'QueryFullProcessImageNameA');
{$ENDIF ~SUPPORTS_UNICODE}
if Assigned(QueryFullProcessImageNameAddress) then
begin
Len := Length(FileName);
if QueryFullProcessImageNameAddress(hProcess, 0, FileName, PDWORD(@Len)) then
Result := FileName;
//else
// RaiseLastOSError would be nice, but it didn't raise an exception before the return value was checked
end
else
raise EJclError.CreateResFmt(@RsEFunctionNotFound, ['Kernel32.dll', 'QueryFullProcessImageName']);
finally
FreeLibrary(DllHinst);
end;
end
else
raise EJclError.CreateResFmt(@RsELibraryNotFound, ['Kernel32.dll']);
end
else
begin
DllHinst := LoadLibrary('Psapi.dll');
if DllHinst < HINSTANCE_ERROR then
begin
try
{$IFDEF SUPPORTS_UNICODE}
GetModuleFileNameExAddress := GetProcAddress(DllHinst, 'GetModuleFileNameExW');
{$ELSE ~SUPPORTS_UNICODE}
GetModuleFileNameExAddress := GetProcAddress(DllHinst, 'GetModuleFileNameExA');
{$ENDIF ~SUPPORTS_UNICODE}
if Assigned(GetModuleFileNameExAddress) then
begin
Len := GetModuleFileNameExAddress(hProcess, 0, FileName, Length(FileName));
if Len > 0 then
Result := FileName;
//else
// RaiseLastOSError; would be nice, but it didn't raise an exception before the return value was checked
end
else
raise EJclError.CreateResFmt(@RsEFunctionNotFound, ['Psapi.dll', 'GetModuleFileNameEx']);
finally
FreeLibrary(DllHinst);
end;
end
else
raise EJclError.CreateResFmt(@RsELibraryNotFound, ['Psapi.dll']);
end;
finally
CloseHandle(hProcess);
end;
end
else
raise EJclError.CreateResFmt(@RsEProcessNotValid, [ProcessID]);
end
else
raise EJclError.CreateResFmt(@RsEWindowNotValid, [Window]);
end;
{$ENDIF MSWINDOWS}
// Version Info formatting
function FormatVersionString(const HiV, LoV: Word): string;
begin
Result := Format('%u.%.2u', [HiV, LoV]);
end;
function FormatVersionString(const Major, Minor, Build, Revision: Word): string;
begin
Result := Format('%u.%u.%u.%u', [Major, Minor, Build, Revision]);
end;
{$IFDEF MSWINDOWS}
function FormatVersionString(const FixedInfo: TVSFixedFileInfo; VersionFormat: TFileVersionFormat): string;
begin
case VersionFormat of
vfMajorMinor:
Result := Format('%u.%u', [HiWord(FixedInfo.dwFileVersionMS), LoWord(FixedInfo.dwFileVersionMS)]);
vfFull:
Result := Format('%u.%u.%u.%u', [HiWord(FixedInfo.dwFileVersionMS), LoWord(FixedInfo.dwFileVersionMS),
HiWord(FixedInfo.dwFileVersionLS), LoWord(FixedInfo.dwFileVersionLS)]);
end;
end;
// Version Info extracting
procedure VersionExtractFileInfo(const FixedInfo: TVSFixedFileInfo; var Major, Minor, Build, Revision: Word);
begin
Major := HiWord(FixedInfo.dwFileVersionMS);
Minor := LoWord(FixedInfo.dwFileVersionMS);
Build := HiWord(FixedInfo.dwFileVersionLS);
Revision := LoWord(FixedInfo.dwFileVersionLS);
end;
procedure VersionExtractProductInfo(const FixedInfo: TVSFixedFileInfo; var Major, Minor, Build, Revision: Word);
begin
Major := HiWord(FixedInfo.dwProductVersionMS);
Minor := LoWord(FixedInfo.dwProductVersionMS);
Build := HiWord(FixedInfo.dwProductVersionLS);
Revision := LoWord(FixedInfo.dwProductVersionLS);
end;
// Fixed Version Info routines
function VersionFixedFileInfo(const FileName: string; var FixedInfo: TVSFixedFileInfo): Boolean;
var
Size, FixInfoLen: DWORD;
Handle: DWORD;
Buffer: string;
FixInfoBuf: PVSFixedFileInfo;
begin
Result := False;
Handle := 0;
Size := GetFileVersionInfoSize(PChar(FileName), Handle);
if Size > 0 then
begin
SetLength(Buffer, Size);
FixInfoLen := 0;
FixInfoBuf := nil;
if GetFileVersionInfo(PChar(FileName), Handle, Size, Pointer(Buffer)) and
VerQueryValue(Pointer(Buffer), DirDelimiter, Pointer(FixInfoBuf), FixInfoLen) and
(FixInfoLen = SizeOf(TVSFixedFileInfo)) then
begin
Result := True;
FixedInfo := FixInfoBuf^;
end;
end;
end;
function VersionFixedFileInfoString(const FileName: string; VersionFormat: TFileVersionFormat;
const NotAvailableText: string): string;
var
FixedInfo: TVSFixedFileInfo;
begin
FixedInfo.dwSignature := 0;
if VersionFixedFileInfo(FileName, FixedInfo) then
Result := FormatVersionString(FixedInfo, VersionFormat)
else
Result := NotAvailableText;
end;
//=== { TJclFileVersionInfo } ================================================
constructor TJclFileVersionInfo.Attach(VersionInfoData: Pointer; Size: Integer);
begin
SetLength(FBuffer, Size);
CopyMemory(PAnsiChar(FBuffer), VersionInfoData, Size);
ExtractData;
end;
constructor TJclFileVersionInfo.Create(const FileName: string);
var
Handle: DWORD;
Size: DWORD;
begin
if not FileExists(FileName) then
raise EJclFileVersionInfoError.CreateResFmt(@RsFileUtilsFileDoesNotExist, [FileName]);
Handle := 0;
Size := GetFileVersionInfoSize(PChar(FileName), Handle);
if Size = 0 then
raise EJclFileVersionInfoError.CreateRes(@RsFileUtilsNoVersionInfo);
SetLength(FBuffer, Size);
Win32Check(GetFileVersionInfo(PChar(FileName), Handle, Size, PAnsiChar(FBuffer)));
ExtractData;
end;
{$IFDEF MSWINDOWS}
{$IFDEF FPC}
constructor TJclFileVersionInfo.Create(const Window: HWND; Dummy: Pointer = nil);
{$ELSE}
constructor TJclFileVersionInfo.Create(const Window: HWND);
{$ENDIF}
begin
Create(WindowToModuleFileName(Window));
end;
constructor TJclFileVersionInfo.Create(const Module: HMODULE);
begin
if Module <> 0 then
Create(GetModulePath(Module))
else
raise EJclError.CreateResFmt(@RsEModuleNotValid, [Module]);
end;
{$ENDIF MSWINDOWS}
destructor TJclFileVersionInfo.Destroy;
begin
FreeAndNil(FItemList);
FreeAndNil(FItems);
inherited Destroy;
end;
class function TJclFileVersionInfo.FileHasVersionInfo(const FileName: string): boolean;
var
Dummy: DWord;
begin
Result := GetFileVersionInfoSize(PChar(FileName), Dummy) <> 0;
end;
procedure TJclFileVersionInfo.CheckLanguageIndex(Value: Integer);
begin
if (Value < 0) or (Value >= LanguageCount) then
raise EJclFileVersionInfoError.CreateRes(@RsFileUtilsLanguageIndex);
end;
procedure TJclFileVersionInfo.CreateItemsForLanguage;
var
I: Integer;
begin
Items.Clear;
for I := 0 to FItemList.Count - 1 do
if Integer(FItemList.Objects[I]) = FLanguageIndex then
Items.AddObject(FItemList[I], Pointer(FLanguages[FLanguageIndex].Pair));
end;
procedure TJclFileVersionInfo.ExtractData;
var
Data, EndOfData: PAnsiChar;
Len, ValueLen, DataType: Word;
HeaderSize: Integer;
Key: string;
Error, IsUnicode: Boolean;
procedure Padding(var DataPtr: PAnsiChar);
begin
while TJclAddr(DataPtr) and 3 <> 0 do
Inc(DataPtr);
end;
procedure GetHeader;
var
P: PAnsiChar;
TempKey: PWideChar;
begin
Key := '';
P := Data;
Len := PWord(P)^;
if Len = 0 then
begin
// do not raise error in the case of resources padded with 0
while P < EndOfData do
begin
Error := P^ <> #0;
if Error then
Break;
Inc(P);
end;
Exit;
end;
Inc(P, SizeOf(Word));
ValueLen := PWord(P)^;
Inc(P, SizeOf(Word));
if IsUnicode then
begin
DataType := PWord(P)^;
Inc(P, SizeOf(Word));
TempKey := PWideChar(P);
Inc(P, (lstrlenW(TempKey) + 1) * SizeOf(WideChar)); // length + #0#0
Key := TempKey;
end
else
begin
DataType := 1;
Key := string(PAnsiChar(P));
Inc(P, lstrlenA(PAnsiChar(P)) + 1);
end;
Padding(P);
HeaderSize := P - Data;
Data := P;
end;
procedure FixKeyValue;
const
HexNumberCPrefix = '0x';
var
I: Integer;
begin // GAPI32.DLL version 5.5.2803.1 contanins '04050x04E2' value
repeat
I := Pos(HexNumberCPrefix, Key);
if I > 0 then
Delete(Key, I, Length(HexNumberCPrefix));
until I = 0;
I := 1;
while I <= Length(Key) do
if CharIsHexDigit(Key[I]) then
Inc(I)
else
Delete(Key, I, 1);
end;
procedure ProcessStringInfo(Size: Integer);
var
EndPtr, EndStringPtr: PAnsiChar;
LangIndex: Integer;
LangIdRec: TLangIdRec;
Value: string;
begin
EndPtr := Data + Size;
LangIndex := 0;
while not Error and (Data < EndPtr) do
begin
GetHeader; // StringTable
FixKeyValue;
if (ValueLen <> 0) or (Length(Key) <> 8) then
begin
Error := True;
Break;
end;
Padding(Data);
LangIdRec.LangId := StrToIntDef('$' + Copy(Key, 1, 4), 0);
LangIdRec.CodePage := StrToIntDef('$' + Copy(Key, 5, 4), 0);
SetLength(FLanguages, LangIndex + 1);
FLanguages[LangIndex] := LangIdRec;
EndStringPtr := Data + Len - HeaderSize;
while not Error and (Data < EndStringPtr) do
begin
GetHeader; // string
case DataType of
0:
if ValueLen in [1..4] then
Value := Format('$%.*x', [ValueLen * 2, PInteger(Data)^])
else
begin
if (ValueLen > 0) and IsUnicode then
Value:=PWideChar(Data)
else
Value := '';
end;
1:
if ValueLen = 0 then
Value := ''
else
if IsUnicode then
begin
Value := WideCharLenToString(PWideChar(Data), ValueLen);
StrResetLength(Value);
end
else
Value := string(PAnsiChar(Data));
else
Error := True;
Break;
end;
Inc(Data, Len - HeaderSize);
Padding(Data); // String.Padding
FItemList.AddObject(Format('%s=%s', [Key, Value]), Pointer(LangIndex));
end;
Inc(LangIndex);
end;
end;
procedure ProcessVarInfo;
var
TranslationIndex: Integer;
begin
GetHeader; // Var
if SameText(Key, 'Translation') then
begin
SetLength(FTranslations, ValueLen div SizeOf(TLangIdRec));
for TranslationIndex := 0 to Length(FTranslations) - 1 do
begin
FTranslations[TranslationIndex] := PLangIdRec(Data)^;
Inc(Data, SizeOf(TLangIdRec));
end;
end;
end;
begin
FItemList := TStringList.Create;
FItems := TStringList.Create;
Data := Pointer(FBuffer);
Assert(TJclAddr(Data) mod 4 = 0);
IsUnicode := (PWord(Data + 4)^ in [0, 1]);
Error := True;
GetHeader;
EndOfData := Data + Len - HeaderSize;
if SameText(Key, 'VS_VERSION_INFO') and (ValueLen = SizeOf(TVSFixedFileInfo)) then
begin
FFixedInfo := PVSFixedFileInfo(Data);
Error := FFixedInfo.dwSignature <> $FEEF04BD;
Inc(Data, ValueLen); // VS_FIXEDFILEINFO
Padding(Data); // VS_VERSIONINFO.Padding2
while not Error and (Data < EndOfData) do
begin
GetHeader;
Inc(Data, ValueLen); // some files (VREDIR.VXD 4.00.1111) has non zero value of ValueLen
Dec(Len, HeaderSize + ValueLen);
if SameText(Key, 'StringFileInfo') then
ProcessStringInfo(Len)
else
if SameText(Key, 'VarFileInfo') then
ProcessVarInfo
else
Break;
end;
ExtractFlags;
CreateItemsForLanguage;
end;
if Error then
raise EJclFileVersionInfoError.CreateRes(@RsFileUtilsNoVersionInfo);
end;
procedure TJclFileVersionInfo.ExtractFlags;
var
Masked: DWORD;
begin
FFileFlags := [];
Masked := FFixedInfo^.dwFileFlags and FFixedInfo^.dwFileFlagsMask;
if (Masked and VS_FF_DEBUG) <> 0 then
Include(FFileFlags, ffDebug);
if (Masked and VS_FF_INFOINFERRED) <> 0 then
Include(FFileFlags, ffInfoInferred);
if (Masked and VS_FF_PATCHED) <> 0 then
Include(FFileFlags, ffPatched);
if (Masked and VS_FF_PRERELEASE) <> 0 then
Include(FFileFlags, ffPreRelease);
if (Masked and VS_FF_PRIVATEBUILD) <> 0 then
Include(FFileFlags, ffPrivateBuild);
if (Masked and VS_FF_SPECIALBUILD) <> 0 then
Include(FFileFlags, ffSpecialBuild);
end;
function TJclFileVersionInfo.GetBinFileVersion: string;
begin
Result := Format('%u.%u.%u.%u', [HiWord(FFixedInfo^.dwFileVersionMS),
LoWord(FFixedInfo^.dwFileVersionMS), HiWord(FFixedInfo^.dwFileVersionLS),
LoWord(FFixedInfo^.dwFileVersionLS)]);
end;
function TJclFileVersionInfo.GetBinProductVersion: string;
begin
Result := Format('%u.%u.%u.%u', [HiWord(FFixedInfo^.dwProductVersionMS),
LoWord(FFixedInfo^.dwProductVersionMS), HiWord(FFixedInfo^.dwProductVersionLS),
LoWord(FFixedInfo^.dwProductVersionLS)]);
end;
function TJclFileVersionInfo.GetCustomFieldValue(const FieldName: string): string;
var
ItemIndex: Integer;
begin
if FieldName <> '' then
begin
ItemIndex := FItems.IndexOfName(FieldName);
if ItemIndex <> -1 then
//Return the required value, the value the user passed in was found.
Result := FItems.Values[FieldName]
else
raise EJclFileVersionInfoError.CreateResFmt(@RsFileUtilsValueNotFound, [FieldName]);
end
else
raise EJclFileVersionInfoError.CreateRes(@RsFileUtilsEmptyValue);
end;
function TJclFileVersionInfo.GetFileOS: DWORD;
begin
Result := FFixedInfo^.dwFileOS;
end;
function TJclFileVersionInfo.GetFileSubType: DWORD;
begin
Result := FFixedInfo^.dwFileSubtype;
end;
function TJclFileVersionInfo.GetFileType: DWORD;
begin
Result := FFixedInfo^.dwFileType;
end;
function TJclFileVersionInfo.GetFileVersionBuild: string;
var
Left: Integer;
begin
Result := FileVersion;
StrReplaceChar(Result, ',', '.');
Left := CharLastPos(Result, '.') + 1;
Result := StrMid(Result, Left, Length(Result) - Left + 1);
Result := Trim(Result);
end;
function TJclFileVersionInfo.GetFileVersionMajor: string;
begin
Result := FileVersion;
StrReplaceChar(Result, ',', '.');
Result := StrBefore('.', Result);
Result := Trim(Result);
end;
function TJclFileVersionInfo.GetFileVersionMinor: string;
var
Left, Right: integer;
begin
Result := FileVersion;
StrReplaceChar(Result, ',', '.');
Left := CharPos(Result, '.') + 1; // skip major
Right := CharPos(Result, '.', Left) {-1};
Result := StrMid(Result, Left, Right - Left {+1});
Result := Trim(Result);
end;
function TJclFileVersionInfo.GetFileVersionRelease: string;
var
Left, Right: Integer;
begin
Result := FileVersion;
StrReplaceChar(Result, ',', '.');
Left := CharPos(Result, '.') + 1; // skip major
Left := CharPos(Result, '.', Left) + 1; // skip minor
Right := CharPos(Result, '.', Left) {-1};
Result := StrMid(Result, Left, Right - Left {+1});
Result := Trim(Result);
end;
function TJclFileVersionInfo.GetFixedInfo: TVSFixedFileInfo;
begin
Result := FFixedInfo^;
end;
function TJclFileVersionInfo.GetItems: TStrings;
begin
Result := FItems;
end;
function TJclFileVersionInfo.GetLanguageCount: Integer;
begin
Result := Length(FLanguages);
end;
function TJclFileVersionInfo.GetLanguageIds(Index: Integer): string;
begin
CheckLanguageIndex(Index);
Result := VersionLanguageId(FLanguages[Index]);
end;
function TJclFileVersionInfo.GetLanguages(Index: Integer): TLangIdRec;
begin
CheckLanguageIndex(Index);
Result := FLanguages[Index];
end;
function TJclFileVersionInfo.GetLanguageNames(Index: Integer): string;
begin
CheckLanguageIndex(Index);
Result := VersionLanguageName(FLanguages[Index].LangId);
end;
function TJclFileVersionInfo.GetTranslationCount: Integer;
begin
Result := Length(FTranslations);
end;
function TJclFileVersionInfo.GetTranslations(Index: Integer): TLangIdRec;
begin
Result := FTranslations[Index];
end;
function TJclFileVersionInfo.GetProductVersionBuild: string;
var
Left: Integer;
begin
Result := ProductVersion;
StrReplaceChar(Result, ',', '.');
Left := CharLastPos(Result, '.') + 1;
Result := StrMid(Result, Left, Length(Result) - Left + 1);
Result := Trim(Result);
end;
function TJclFileVersionInfo.GetProductVersionMajor: string;
begin
Result := ProductVersion;
StrReplaceChar(Result, ',', '.');
Result := StrBefore('.', Result);
Result := Trim(Result);
end;
function TJclFileVersionInfo.GetProductVersionMinor: string;
var
Left, Right: integer;
begin
Result := ProductVersion;
StrReplaceChar(Result, ',', '.');
Left := CharPos(Result, '.') + 1; // skip major
Right := CharPos(Result, '.', Left) {-1};
Result := StrMid(Result, Left, Right - Left {+1});
Result := Trim(Result);
end;
function TJclFileVersionInfo.GetProductVersionRelease: string;
var
Left, Right: Integer;
begin
Result := ProductVersion;
StrReplaceChar(Result, ',', '.');
Left := CharPos(Result, '.') + 1; // skip major
Left := CharPos(Result, '.', Left) + 1; // skip minor
Right := CharPos(Result, '.', Left) {-1};
Result := StrMid(Result, Left, Right - Left {+1});
Result := Trim(Result);
end;
function TJclFileVersionInfo.GetVersionKeyValue(Index: Integer): string;
begin
Result := Items.Values[VerKeyNames[Index]];
end;
procedure TJclFileVersionInfo.SetLanguageIndex(const Value: Integer);
begin
CheckLanguageIndex(Value);
if FLanguageIndex <> Value then
begin
FLanguageIndex := Value;
CreateItemsForLanguage;
end;
end;
function TJclFileVersionInfo.TranslationMatchesLanguages(Exact: Boolean): Boolean;
var
TransIndex, LangIndex: Integer;
TranslationPair: DWORD;
begin
Result := (LanguageCount = TranslationCount) or (not Exact and (TranslationCount > 0));
if Result then
for TransIndex := 0 to TranslationCount - 1 do
begin
TranslationPair := FTranslations[TransIndex].Pair;
LangIndex := LanguageCount - 1;
while (LangIndex >= 0) and (TranslationPair <> FLanguages[LangIndex].Pair) do
Dec(LangIndex);
if LangIndex < 0 then
begin
Result := False;
Break;
end;
end;
end;
class function TJclFileVersionInfo.VersionLanguageId(const LangIdRec: TLangIdRec): string;
begin
with LangIdRec do
Result := Format('%.4x%.4x', [LangId, CodePage]);
end;
class function TJclFileVersionInfo.VersionLanguageName(const LangId: Word): string;
var
R: DWORD;
begin
SetLength(Result, MAX_PATH);
R := VerLanguageName(LangId, PChar(Result), MAX_PATH);
SetLength(Result, R);
end;
{$ENDIF MSWINDOWS}
//=== { TJclFileMaskComparator } =============================================
constructor TJclFileMaskComparator.Create;
begin
inherited Create;
FSeparator := DirSeparator;
end;
function TJclFileMaskComparator.Compare(const NameExt: string): Boolean;
var
I: Integer;
NamePart, ExtPart: string;
NameWild, ExtWild: Boolean;
begin
Result := False;
I := StrLastPos('.', NameExt);
if I = 0 then
begin
NamePart := NameExt;
ExtPart := '';
end
else
begin
NamePart := Copy(NameExt, 1, I - 1);
ExtPart := Copy(NameExt, I + 1, Length(NameExt));
end;
for I := 0 to Length(FNames) - 1 do
begin
NameWild := FWildChars[I] and 1 = 1;
ExtWild := FWildChars[I] and 2 = 2;
if ((not NameWild and StrSame(FNames[I], NamePart)) or
(NameWild and (StrMatches(FNames[I], NamePart, 1)))) and
((not ExtWild and StrSame(FExts[I], ExtPart)) or
(ExtWild and (StrMatches(FExts[I], ExtPart, 1)))) then
begin
Result := True;
Break;
end;
end;
end;
procedure TJclFileMaskComparator.CreateMultiMasks;
var
List: TStringList;
I, N: Integer;
NS, ES: string;
begin
FExts := nil;
FNames := nil;
FWildChars := nil;
List := TStringList.Create;
try
StrToStrings(FFileMask, FSeparator, List);
SetLength(FExts, List.Count);
SetLength(FNames, List.Count);
SetLength(FWildChars, List.Count);
for I := 0 to List.Count - 1 do
begin
N := StrLastPos('.', List[I]);
if N = 0 then
begin
NS := List[I];
ES := '';
end
else
begin
NS := Copy(List[I], 1, N - 1);
ES := Copy(List[I], N + 1, 255);
end;
FNames[I] := NS;
FExts[I] := ES;
N := 0;
if StrContainsChars(NS, CharIsWildcard, False) then
N := N or 1;
if StrContainsChars(ES, CharIsWildcard, False) then
N := N or 2;
FWildChars[I] := N;
end;
finally
List.Free;
end;
end;
function TJclFileMaskComparator.GetCount: Integer;
begin
Result := Length(FWildChars);
end;
function TJclFileMaskComparator.GetExts(Index: Integer): string;
begin
Result := FExts[Index];
end;
function TJclFileMaskComparator.GetMasks(Index: Integer): string;
begin
Result := FNames[Index] + '.' + FExts[Index];
end;
function TJclFileMaskComparator.GetNames(Index: Integer): string;
begin
Result := FNames[Index];
end;
procedure TJclFileMaskComparator.SetFileMask(const Value: string);
begin
FFileMask := Value;
CreateMultiMasks;
end;
procedure TJclFileMaskComparator.SetSeparator(const Value: Char);
begin
if FSeparator <> Value then
begin
FSeparator := Value;
CreateMultiMasks;
end;
end;
function AdvBuildFileList(const Path: string; const Attr: Integer; const Files: TStrings;
const AttributeMatch: TJclAttributeMatch; const Options: TFileListOptions;
const SubfoldersMask: string; const FileMatchFunc: TFileMatchFunc): Boolean;
var
FileMask: string;
RootDir: string;
Folders: TStringList;
CurrentItem: Integer;
Counter: Integer;
FindAttr: Integer;
procedure BuildFolderList;
var
FindInfo: TSearchRec;
Rslt: Integer;
begin
Counter := Folders.Count - 1;
CurrentItem := 0;
while CurrentItem <= Counter do
begin
// searching for subfolders (including hidden ones)
Rslt := FindFirst(Folders[CurrentItem] + '*.*', faAnyFile, FindInfo);
try
while Rslt = 0 do
begin
if (FindInfo.Name <> '.') and (FindInfo.Name <> '..') and
(FindInfo.Attr and faDirectory = faDirectory) then
Folders.Add(Folders[CurrentItem] + FindInfo.Name + DirDelimiter);
Rslt := FindNext(FindInfo);
end;
finally
FindClose(FindInfo);
end;
Counter := Folders.Count - 1;
Inc(CurrentItem);
end;
end;
procedure FillFileList(CurrentCounter: Integer);
var
FindInfo: TSearchRec;
Rslt: Integer;
CurrentFolder: string;
Matches: Boolean;
begin
CurrentFolder := Folders[CurrentCounter];
Rslt := FindFirst(CurrentFolder + FileMask, FindAttr, FindInfo);
try
while Rslt = 0 do
begin
Matches := False;
case AttributeMatch of
amAny:
Matches := True;
amExact:
Matches := Attr = FindInfo.Attr;
amSubSetOf:
Matches := (Attr and FindInfo.Attr) = Attr;
amSuperSetOf:
Matches := (Attr and FindInfo.Attr) = FindInfo.Attr;
amCustom:
if Assigned(FileMatchFunc) then
Matches := FileMatchFunc(Attr, FindInfo);
end;
if Matches then
if flFullNames in Options then
Files.Add(CurrentFolder + FindInfo.Name)
else
Files.Add(FindInfo.Name);
Rslt := FindNext(FindInfo);
end;
finally
FindClose(FindInfo);
end;
end;
begin
Assert(Assigned(Files));
FileMask := ExtractFileName(Path);
RootDir := ExtractFilePath(Path);
Folders := TStringList.Create;
Files.BeginUpdate;
try
Folders.Add(RootDir);
case AttributeMatch of
amExact, amSuperSetOf:
FindAttr := Attr;
else
FindAttr := faAnyFile;
end;
// here's the recursive search for nested folders
if flRecursive in Options then
BuildFolderList;
for Counter := 0 to Folders.Count - 1 do
begin
if (((flMaskedSubfolders in Options) and (StrMatches(SubfoldersMask,
Folders[Counter], 1))) or (not (flMaskedSubfolders in Options))) then
FillFileList(Counter);
end;
finally
Folders.Free;
Files.EndUpdate;
end;
Result := True;
end;
function VerifyFileAttributeMask(var RejectedAttributes, RequiredAttributes: Integer): Boolean;
begin
if RequiredAttributes and faNormalFile <> 0 then
RejectedAttributes := not faNormalFile or RejectedAttributes;
Result := RequiredAttributes and RejectedAttributes = 0;
end;
function AttributeMatch(FileAttributes, RejectedAttr, RequiredAttr: Integer): Boolean;
begin
if FileAttributes = 0 then
FileAttributes := faNormalFile;
{$IFDEF MSWINDOWS}
RequiredAttr := RequiredAttr and not faUnixSpecific;
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
RequiredAttr := RequiredAttr and not faWindowsSpecific;
{$ENDIF UNIX}
Result := (FileAttributes and RejectedAttr = 0)
and (FileAttributes and RequiredAttr = RequiredAttr);
end;
function IsFileAttributeMatch(FileAttributes, RejectedAttributes,
RequiredAttributes: Integer): Boolean;
begin
VerifyFileAttributeMask(RejectedAttributes, RequiredAttributes);
Result := AttributeMatch(FileAttributes, RejectedAttributes, RequiredAttributes);
end;
function FileAttributesStr(const FileInfo: TSearchRec): string;
{$IFDEF MSWINDOWS}
const
SAllAttrSet = 'rahs'; // readonly, archive, hidden, system
Attributes: array [1..4] of Integer =
(faReadOnly, faArchive, faHidden, faSysFile);
var
I: Integer;
begin
Result := SAllAttrSet;
for I := Low(Attributes) to High(Attributes) do
if (FileInfo.Attr and Attributes[I]) = 0 then
Result[I] := '-';
end;
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
const
SAllAttrSet = 'drwxrwxrwx';
var
I: Integer;
Flag: Cardinal;
begin
Result := SAllAttrSet;
if FileInfo.Attr and faDirectory = 0 then
Result[1] := '-'; // no directory
Flag := 1 shl 8;
for I := 2 to 10 do
begin
if FileInfo.Mode and Flag = 0 then
Result[I] := '-';
Flag := Flag shr 1;
end;
end;
{$ENDIF UNIX}
function IsFileNameMatch(FileName: string; const Mask: string;
const CaseSensitive: Boolean): Boolean;
begin
Result := True;
{$IFDEF MSWINDOWS}
if (Mask = '') or (Mask = '*') or (Mask = '*.*') then
Exit;
if Pos('.', FileName) = 0 then
FileName := FileName + '.'; // file names w/o extension match '*.'
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
if (Mask = '') or (Mask = '*') then
Exit;
{$ENDIF UNIX}
if CaseSensitive then
Result := StrMatches(Mask, FileName)
else
Result := StrMatches(AnsiUpperCase(Mask), AnsiUpperCase(FileName));
end;
// author: Robert Rossmair
function CanonicalizedSearchPath(const Directory: string): string;
begin
Result := PathCanonicalize(Directory);
{$IFDEF MSWINDOWS}
// avoid changing "X:" (current directory on drive X:) into "X:\" (root dir.)
if Result[Length(Result)] <> ':' then
{$ENDIF MSWINDOWS}
Result := PathAddSeparator(Result);
// strip leading "./" resp. ".\"
if Pos('.' + DirDelimiter, Result) = 1 then
Result := Copy(Result, 3, Length(Result) - 2);
end;
procedure EnumFiles(const Path: string; HandleFile: TFileHandlerEx;
RejectedAttributes: Integer; RequiredAttributes: Integer; Abort: PBoolean);
var
Directory: string;
FileInfo: TSearchRec;
Attr: Integer;
Found: Boolean;
begin
Assert(Assigned(HandleFile));
Assert(VerifyFileAttributeMask(RejectedAttributes, RequiredAttributes),
LoadResString(@RsFileSearchAttrInconsistency));
Directory := ExtractFilePath(Path);
Attr := faAnyFile and not RejectedAttributes;
Found := {$IFDEF HAS_UNITSCOPE}System.{$ENDIF}SysUtils.FindFirst(Path, Attr, FileInfo) = 0;
try
while Found do
begin
if (Abort <> nil) and LongBool(Abort^) then
Exit;
if AttributeMatch(FileInfo.Attr, RejectedAttributes, RequiredAttributes) then
if ((FileInfo.Attr and faDirectory = 0)
or ((FileInfo.Name <> '.') and (FileInfo.Name <> '..'))) then
HandleFile(Directory, FileInfo);
Found := FindNext(FileInfo) = 0;
end;
finally
FindClose(FileInfo);
end;
end;
procedure EnumFiles(const Path: string; HandleFile: TFileInfoHandlerEx;
RejectedAttributes: Integer; RequiredAttributes: Integer; Abort: PBoolean);
var
FileInfo: TSearchRec;
Attr: Integer;
Found: Boolean;
begin
Assert(Assigned(HandleFile));
Assert(VerifyFileAttributeMask(RejectedAttributes, RequiredAttributes),
LoadResString(@RsFileSearchAttrInconsistency));
Attr := faAnyFile and not RejectedAttributes;
Found := {$IFDEF HAS_UNITSCOPE}System.{$ENDIF}SysUtils.FindFirst(Path, Attr, FileInfo) = 0;
try
while Found do
begin
if (Abort <> nil) and LongBool(Abort^) then
Exit;
if AttributeMatch(FileInfo.Attr, RejectedAttributes, RequiredAttributes) then
if ((FileInfo.Attr and faDirectory = 0)
or ((FileInfo.Name <> '.') and (FileInfo.Name <> '..'))) then
HandleFile(FileInfo);
Found := FindNext(FileInfo) = 0;
end;
finally
FindClose(FileInfo);
end;
end;
procedure EnumDirectories(const Root: string; const HandleDirectory: TFileHandler;
const IncludeHiddenDirectories: Boolean; const SubDirectoriesMask: string;
Abort: PBoolean {$IFDEF UNIX}; ResolveSymLinks: Boolean {$ENDIF});
var
RootDir: string;
Attr: Integer;
procedure Process(const Directory: string);
var
DirInfo: TSearchRec;
SubDir: string;
Found: Boolean;
begin
HandleDirectory(Directory);
Found := {$IFDEF HAS_UNITSCOPE}System.{$ENDIF}SysUtils.FindFirst(Directory + '*', Attr, DirInfo) = 0;
try
while Found do
begin
if (Abort <> nil) and LongBool(Abort^) then
Exit;
if (DirInfo.Name <> '.') and (DirInfo.Name <> '..') and
{$IFDEF UNIX}
(IncludeHiddenDirectories or (Pos('.', DirInfo.Name) <> 1)) and
((DirInfo.Attr and faSymLink = 0) or ResolveSymLinks) and
{$ENDIF UNIX}
(DirInfo.Attr and faDirectory <> 0) then
begin
SubDir := Directory + DirInfo.Name + DirDelimiter;
if (SubDirectoriesMask = '') or StrMatches(SubDirectoriesMask, SubDir, Length(RootDir)) then
Process(SubDir);
end;
Found := FindNext(DirInfo) = 0;
end;
finally
FindClose(DirInfo);
end;
end;
begin
Assert(Assigned(HandleDirectory));
RootDir := CanonicalizedSearchPath(Root);
if IncludeHiddenDirectories then
Attr := faDirectory + faHidden // no effect on Linux
else
Attr := faDirectory;
Process(RootDir);
end;
//=== { TJclCustomFileAttributeMask } ==============================================
constructor TJclCustomFileAttrMask.Create;
begin
inherited Create;
FRejectedAttr := faRejectedByDefault;
end;
procedure TJclCustomFileAttrMask.Assign(Source: TPersistent);
begin
if Source is TJclCustomFileAttrMask then
begin
Required := TJclCustomFileAttrMask(Source).Required;
Rejected := TJclCustomFileAttrMask(Source).Rejected;
end
else
inherited Assign(Source);
end;
procedure TJclCustomFileAttrMask.Clear;
begin
Rejected := 0;
Required := 0;
end;
procedure TJclCustomFileAttrMask.DefineProperties(Filer: TFiler);
var
Ancestor: TJclCustomFileAttrMask;
Attr: Integer;
begin
Attr := 0;
Ancestor := TJclCustomFileAttrMask(Filer.Ancestor);
if Assigned(Ancestor) then
Attr := Ancestor.FRequiredAttr;
Filer.DefineProperty('Required', ReadRequiredAttributes, WriteRequiredAttributes,
Attr <> FRequiredAttr);
if Assigned(Ancestor) then
Attr := Ancestor.FRejectedAttr;
Filer.DefineProperty('Rejected', ReadRejectedAttributes, WriteRejectedAttributes,
Attr <> FRejectedAttr);
end;
function TJclCustomFileAttrMask.Match(FileAttributes: Integer): Boolean;
begin
Result := AttributeMatch(FileAttributes, Rejected, Required);
end;
function TJclCustomFileAttrMask.Match(const FileInfo: TSearchRec): Boolean;
begin
Result := Match(FileInfo.Attr);
end;
function TJclCustomFileAttrMask.GetAttr(Index: Integer): TAttributeInterest;
begin
if ((FRequiredAttr and Index) <> 0) or (Index = faNormalFile) and
(FRejectedAttr = not faNormalFile) then
Result := aiRequired
else
if (FRejectedAttr and Index) <> 0 then
Result := aiRejected
else
Result := aiIgnored;
end;
procedure TJclCustomFileAttrMask.ReadRejectedAttributes(Reader: TReader);
begin
FRejectedAttr := Reader.ReadInteger;
end;
procedure TJclCustomFileAttrMask.ReadRequiredAttributes(Reader: TReader);
begin
FRequiredAttr := Reader.ReadInteger;
end;
procedure TJclCustomFileAttrMask.SetAttr(Index: Integer; const Value: TAttributeInterest);
begin
case Value of
aiIgnored:
begin
FRequiredAttr := FRequiredAttr and not Index;
FRejectedAttr := FRejectedAttr and not Index;
end;
aiRejected:
begin
FRequiredAttr := FRequiredAttr and not Index;
FRejectedAttr := FRejectedAttr or Index;
end;
aiRequired:
begin
if Index = faNormalFile then
begin
FRequiredAttr := faNormalFile;
FRejectedAttr := not faNormalFile;
end
else
begin
FRequiredAttr := FRequiredAttr or Index;
FRejectedAttr := FRejectedAttr and not Index;
end;
end;
end;
end;
procedure TJclCustomFileAttrMask.WriteRejectedAttributes(Writer: TWriter);
begin
Writer.WriteInteger(FRejectedAttr);
end;
procedure TJclCustomFileAttrMask.WriteRequiredAttributes(Writer: TWriter);
begin
Writer.WriteInteger(FRequiredAttr);
end;
//=== { TJclFileAttributeMask } ==============================================
procedure TJclFileAttributeMask.ReadVolumeID(Reader: TReader);
begin
// Nothing, we are not interested in the value of the VolumeID property,
// this procedure and the associated DefineProperty call are here only
// to allow reading legacy DFMs that have this property defined.
end;
procedure TJclFileAttributeMask.DefineProperties(Filer: TFiler);
begin
inherited DefineProperties(Filer);
Filer.DefineProperty('VolumeID', ReadVolumeID, nil, False);
end;
//=== { TJclFileSearchOptions } ==============================================
constructor TJclFileSearchOptions.Create;
begin
inherited Create;
FAttributeMask := TJclFileAttributeMask.Create;
FRootDirectories := TStringList.Create;
FRootDirectories.Add('.');
FFileMasks := TStringList.Create;
FFileMasks.Add('*');
FSubDirectoryMask := '*';
FOptions := [fsIncludeSubDirectories];
FLastChangeAfter := MinDateTime;
FLastChangeBefore := MaxDateTime;
{$IFDEF UNIX}
FCaseSensitiveSearch := True;
{$ENDIF UNIX}
end;
destructor TJclFileSearchOptions.Destroy;
begin
FAttributeMask.Free;
FFileMasks.Free;
FRootDirectories.Free;
inherited Destroy;
end;
procedure TJclFileSearchOptions.Assign(Source: TPersistent);
var
Src: TJclFileSearchOptions;
begin
if Source is TJclFileSearchOptions then
begin
Src := TJclFileSearchOptions(Source);
FCaseSensitiveSearch := Src.FCaseSensitiveSearch;
FileMasks.Assign(Src.FileMasks);
RootDirectory := Src.RootDirectory;
SubDirectoryMask := Src.SubDirectoryMask;
AttributeMask := Src.AttributeMask;
Options := Src.Options;
FileSizeMin := Src.FileSizeMin;
FileSizeMax := Src.FileSizeMax;
LastChangeAfter := Src.LastChangeAfter;
LastChangeBefore := Src.LastChangeBefore;
end
else
inherited Assign(Source);
end;
function TJclFileSearchOptions.GetAttributeMask: TJclFileAttributeMask;
begin
Result := FAttributeMask;
end;
function TJclFileSearchOptions.GetCaseSensitiveSearch: Boolean;
begin
Result := FCaseSensitiveSearch;
end;
function TJclFileSearchOptions.GetFileMask: string;
begin
Result := StringsToStr(FileMasks, DirSeparator, False);
end;
function TJclFileSearchOptions.GetFileMasks: TStrings;
begin
Result := FFileMasks;
end;
function TJclFileSearchOptions.GetFileSizeMax: Int64;
begin
Result := FFileSizeMax;
end;
function TJclFileSearchOptions.GetFileSizeMin: Int64;
begin
Result := FFileSizeMin;
end;
function TJclFileSearchOptions.GetIncludeHiddenSubDirectories: Boolean;
begin
Result := fsIncludeHiddenSubDirectories in Options;
end;
function TJclFileSearchOptions.GetIncludeSubDirectories: Boolean;
begin
Result := fsIncludeSubDirectories in Options;
end;
function TJclFileSearchOptions.GetLastChangeAfter: TDateTime;
begin
Result := FLastChangeAfter;
end;
function TJclFileSearchOptions.GetLastChangeAfterStr: string;
begin
Result := DateTimeToStr(LastChangeAfter);
end;
function TJclFileSearchOptions.GetLastChangeBefore: TDateTime;
begin
Result := FLastChangeBefore;
end;
function TJclFileSearchOptions.GetLastChangeBeforeStr: string;
begin
Result := DateTimeToStr(LastChangeBefore);
end;
function TJclFileSearchOptions.GetOption(
const Option: TFileSearchOption): Boolean;
begin
Result := Option in FOptions;
end;
function TJclFileSearchOptions.GetOptions: TFileSearchoptions;
begin
Result := FOptions;
end;
function TJclFileSearchOptions.GetRootDirectories: TStrings;
begin
Result := FRootDirectories;
end;
function TJclFileSearchOptions.GetRootDirectory: string;
begin
if FRootDirectories.Count = 1 then
Result := FRootDirectories.Strings[0]
else
Result := '';
end;
function TJclFileSearchOptions.GetSubDirectoryMask: string;
begin
Result := FSubDirectoryMask;
end;
function TJclFileSearchOptions.IsLastChangeAfterStored: Boolean;
begin
Result := FLastChangeAfter <> MinDateTime;
end;
function TJclFileSearchOptions.IsLastChangeBeforeStored: Boolean;
begin
Result := FLastChangeBefore <> MaxDateTime;
end;
procedure TJclFileSearchOptions.SetAttributeMask(
const Value: TJclFileAttributeMask);
begin
FAttributeMask.Assign(Value);
end;
procedure TJclFileSearchOptions.SetCaseSensitiveSearch(const Value: Boolean);
begin
FCaseSensitiveSearch := Value;
end;
procedure TJclFileSearchOptions.SetFileMask(const Value: string);
begin
{ TODO : UNIX : ? }
StrToStrings(Value, DirSeparator, FFileMasks, False);
end;
procedure TJclFileSearchOptions.SetFileMasks(const Value: TStrings);
begin
FileMasks.Assign(Value);
end;
procedure TJclFileSearchOptions.SetFileSizeMax(const Value: Int64);
begin
FFileSizeMax := Value;
end;
procedure TJclFileSearchOptions.SetFileSizeMin(const Value: Int64);
begin
FFileSizeMin := Value;
end;
procedure TJclFileSearchOptions.SetIncludeHiddenSubDirectories(
const Value: Boolean);
begin
SetOption(fsIncludeHiddenSubDirectories, Value);
end;
procedure TJclFileSearchOptions.SetIncludeSubDirectories(const Value: Boolean);
begin
SetOption(fsIncludeSubDirectories, Value);
end;
procedure TJclFileSearchOptions.SetLastChangeAfter(const Value: TDateTime);
begin
FLastChangeAfter := Value;
end;
procedure TJclFileSearchOptions.SetLastChangeAfterStr(const Value: string);
begin
if Value = '' then
LastChangeAfter := MinDateTime
else
LastChangeAfter := StrToDateTime(Value);
end;
procedure TJclFileSearchOptions.SetLastChangeBefore(const Value: TDateTime);
begin
FLastChangeBefore := Value;
end;
procedure TJclFileSearchOptions.SetLastChangeBeforeStr(const Value: string);
begin
if Value = '' then
LastChangeBefore := MaxDateTime
else
LastChangeBefore := StrToDateTime(Value);
end;
procedure TJclFileSearchOptions.SetOption(const Option: TFileSearchOption;
const Value: Boolean);
begin
if Value then
Include(FOptions, Option)
else
Exclude(FOptions, Option);
end;
procedure TJclFileSearchOptions.SetOptions(const Value: TFileSearchOptions);
begin
FOptions := Value;
end;
procedure TJclFileSearchOptions.SetRootDirectories(const Value: TStrings);
begin
FRootDirectories.Assign(Value);
end;
procedure TJclFileSearchOptions.SetRootDirectory(const Value: string);
begin
FRootDirectories.Clear;
FRootDirectories.Add(Value);
end;
procedure TJclFileSearchOptions.SetSubDirectoryMask(const Value: string);
begin
FSubDirectoryMask := Value;
end;
//=== { TEnumFileThread } ====================================================
type
TEnumFileThread = class(TThread)
private
FID: TFileSearchTaskID;
FFileMasks: TStringList;
FDirectories: TStrings;
FCurrentDirectory: string;
FSubDirectoryMask: string;
FOnEnterDirectory: TFileHandler;
FFileHandlerEx: TFileHandlerEx;
FFileHandler: TFileHandler;
FInternalDirHandler: TFileHandler;
FInternalFileInfoHandler: TFileInfoHandlerEx;
FFileInfo: TSearchRec;
FRejectedAttr: Integer;
FRequiredAttr: Integer;
FFileSizeMin: Int64;
FFileSizeMax: Int64;
{$IFDEF RTL220_UP}
FFileTimeMin: TDateTime;
FFileTimeMax: TDateTime;
{$ELSE ~RTL220_UP}
FFileTimeMin: Integer;
FFileTimeMax: Integer;
{$ENDIF ~RTL220_UP}
FSynchronizationMode: TFileEnumeratorSyncMode;
FIncludeSubDirectories: Boolean;
FIncludeHiddenSubDirectories: Boolean;
FNotifyOnTermination: Boolean;
FCaseSensitiveSearch: Boolean;
FAllNamesMatch: Boolean;
procedure EnterDirectory;
procedure AsyncProcessDirectory(const Directory: string);
procedure SyncProcessDirectory(const Directory: string);
procedure AsyncProcessFile(const FileInfo: TSearchRec);
procedure SyncProcessFile(const FileInfo: TSearchRec);
function GetDirectories: TStrings;
function GetFileMasks: TStrings;
procedure SetDirectories(const Value: TStrings);
procedure SetFileMasks(const Value: TStrings);
protected
procedure DoTerminate; override;
procedure Execute; override;
function FileMatch: Boolean;
function FileNameMatchesMask: Boolean;
procedure ProcessDirectory;
procedure ProcessDirFiles;
procedure ProcessFile;
property AllNamesMatch: Boolean read FAllNamesMatch;
property CaseSensitiveSearch: Boolean read FCaseSensitiveSearch write FCaseSensitiveSearch;
property FileMasks: TStrings read GetFileMasks write SetFileMasks;
property FileSizeMin: Int64 read FFileSizeMin write FFileSizeMin;
property FileSizeMax: Int64 read FFileSizeMax write FFileSizeMax;
{$IFDEF RTL220_UP}
property FileTimeMin: TDateTime read FFileTimeMin write FFileTimeMin;
property FileTimeMax: TDateTime read FFileTimeMax write FFileTimeMax;
{$ELSE ~RTL220_UP}
property FileTimeMin: Integer read FFileTimeMin write FFileTimeMin;
property FileTimeMax: Integer read FFileTimeMax write FFileTimeMax;
{$ENDIF ~RTL220_UP}
property Directories: TStrings read GetDirectories write SetDirectories;
property IncludeSubDirectories: Boolean
read FIncludeSubDirectories write FIncludeSubDirectories;
property IncludeHiddenSubDirectories: Boolean
read FIncludeHiddenSubDirectories write FIncludeHiddenSubDirectories;
property RejectedAttr: Integer read FRejectedAttr write FRejectedAttr;
property RequiredAttr: Integer read FRequiredAttr write FRequiredAttr;
property SynchronizationMode: TFileEnumeratorSyncMode
read FSynchronizationMode write FSynchronizationMode;
public
constructor Create;
destructor Destroy; override;
property ID: TFileSearchTaskID read FID;
{$IFDEF FPC} // protected property
property Terminated;
{$ENDIF FPC}
end;
constructor TEnumFileThread.Create;
begin
inherited Create(True);
FDirectories := TStringList.Create;
FFileMasks := TStringList.Create;
{$IFDEF RTL220_UP}
FFileTimeMin := -MaxDouble;
FFileTimeMax := MaxDouble;
{$ELSE ~RTL220_UP}
FFileTimeMin := Low(FFileInfo.Time);
FFileTimeMax := High(FFileInfo.Time);
{$ENDIF ~RTL220_UP}
FFileSizeMax := High(FFileSizeMax);
{$IFDEF MSWINDOWS}
Priority := tpIdle;
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
{$IFDEF FPC}
Priority := tpIdle;
{$ELSE ~FPC}
Priority := 0;
{$ENDIF ~FPC}
{$ENDIF UNIX}
FreeOnTerminate := True;
FNotifyOnTermination := True;
end;
destructor TEnumFileThread.Destroy;
begin
FFileMasks.Free;
FDirectories.Free;
inherited Destroy;
end;
procedure TEnumFileThread.Execute;
var
Index: Integer;
begin
if SynchronizationMode = smPerDirectory then
begin
FInternalDirHandler := SyncProcessDirectory;
FInternalFileInfoHandler := AsyncProcessFile;
end
else // SynchronizationMode = smPerFile
begin
FInternalDirHandler := AsyncProcessDirectory;
FInternalFileInfoHandler := SyncProcessFile;
end;
if FIncludeSubDirectories then
begin
for Index := 0 to FDirectories.Count - 1 do
EnumDirectories(FDirectories.Strings[Index], FInternalDirHandler, FIncludeHiddenSubDirectories,
FSubDirectoryMask, @Terminated)
end
else
begin
for Index := 0 to FDirectories.Count - 1 do
FInternalDirHandler(CanonicalizedSearchPath(FDirectories.Strings[Index]));
end;
end;
procedure TEnumFileThread.DoTerminate;
begin
if FNotifyOnTermination then
inherited DoTerminate;
end;
procedure TEnumFileThread.EnterDirectory;
begin
FOnEnterDirectory(FCurrentDirectory);
end;
procedure TEnumFileThread.ProcessDirectory;
begin
if Assigned(FOnEnterDirectory) then
EnterDirectory;
ProcessDirFiles;
end;
procedure TEnumFileThread.AsyncProcessDirectory(const Directory: string);
begin
FCurrentDirectory := Directory;
if Assigned(FOnEnterDirectory) then
Synchronize(EnterDirectory);
ProcessDirFiles;
end;
procedure TEnumFileThread.SyncProcessDirectory(const Directory: string);
begin
FCurrentDirectory := Directory;
Synchronize(ProcessDirectory);
end;
procedure TEnumFileThread.ProcessDirFiles;
begin
EnumFiles(FCurrentDirectory + '*', FInternalFileInfoHandler, FRejectedAttr, FRequiredAttr, @Terminated);
end;
function TEnumFileThread.FileMatch: Boolean;
var
FileSize: Int64;
begin
{$IFDEF RTL220_UP}
Result := FileNameMatchesMask and (FFileInfo.TimeStamp >= FFileTimeMin) and (FFileInfo.TimeStamp <= FFileTimeMax);
{$ELSE ~RTL220_UP}
Result := FileNameMatchesMask and (FFileInfo.Time >= FFileTimeMin) and (FFileInfo.Time <= FFileTimeMax);
{$ENDIF ~RTL220_UP}
if Result then
begin
FileSize := GetSizeOfFile(FFileInfo);
Result := (FileSize >= FFileSizeMin) and (FileSize <= FFileSizeMax);
end;
end;
function TEnumFileThread.FileNameMatchesMask: Boolean;
var
I: Integer;
begin
Result := AllNamesMatch;
if not Result then
for I := 0 to FileMasks.Count - 1 do
if IsFileNameMatch(FFileInfo.Name, FileMasks[I], CaseSensitiveSearch) then
begin
Result := True;
Break;
end;
end;
procedure TEnumFileThread.ProcessFile;
begin
if Assigned(FFileHandlerEx) then
FFileHandlerEx(FCurrentDirectory, FFileInfo)
else
FFileHandler(FCurrentDirectory + FFileInfo.Name);
end;
procedure TEnumFileThread.AsyncProcessFile(const FileInfo: TSearchRec);
begin
FFileInfo := FileInfo;
if FileMatch then
ProcessFile;
end;
procedure TEnumFileThread.SyncProcessFile(const FileInfo: TSearchRec);
begin
FFileInfo := FileInfo;
if FileMatch then
Synchronize(ProcessFile);
end;
function TEnumFileThread.GetDirectories: TStrings;
begin
Result := FDirectories;
end;
function TEnumFileThread.GetFileMasks: TStrings;
begin
Result := FFileMasks;
end;
procedure TEnumFileThread.SetDirectories(const Value: TStrings);
begin
FDirectories.Assign(Value);
end;
procedure TEnumFileThread.SetFileMasks(const Value: TStrings);
var
I: Integer;
begin
FAllNamesMatch := Value.Count = 0;
for I := 0 to Value.Count - 1 do
if (Value[I] = '*') {$IFDEF MSWINDOWS} or (Value[I] = '*.*') {$ENDIF} then
begin
FAllNamesMatch := True;
Break;
end;
if FAllNamesMatch then
FileMasks.Clear
else
FileMasks.Assign(Value);
end;
//=== { TJclFileEnumerator } =================================================
constructor TJclFileEnumerator.Create;
begin
inherited Create;
FTasks := TList.Create;
end;
destructor TJclFileEnumerator.Destroy;
begin
StopAllTasks(True);
FTasks.Free;
inherited Destroy;
end;
procedure TJclFileEnumerator.Assign(Source: TPersistent);
var
Src: TJclFileEnumerator;
begin
if Source is TJclFileEnumerator then
begin
Src := TJclFileEnumerator(Source);
SynchronizationMode := Src.SynchronizationMode;
OnEnterDirectory := Src.OnEnterDirectory;
OnTerminateTask := Src.OnTerminateTask;
end;
inherited Assign(Source);
end;
function TJclFileEnumerator.CreateTask: TThread;
var
Task: TEnumFileThread;
begin
Task := TEnumFileThread.Create;
Task.FID := NextTaskID;
Task.CaseSensitiveSearch := FCaseSensitiveSearch;
Task.FileMasks := FileMasks;
Task.Directories := RootDirectories;
Task.RejectedAttr := AttributeMask.Rejected;
Task.RequiredAttr := AttributeMask.Required;
Task.IncludeSubDirectories := IncludeSubDirectories;
Task.IncludeHiddenSubDirectories := IncludeHiddenSubDirectories;
if fsMinSize in Options then
Task.FileSizeMin := FileSizeMin;
if fsMaxSize in Options then
Task.FileSizeMax := FileSizeMax;
if fsLastChangeAfter in Options then
Task.FFileTimeMin := {$IFDEF RTL220_UP}LastChangeAfter{$ELSE}DateTimeToFileDate(LastChangeAfter){$ENDIF};
if fsLastChangeBefore in Options then
Task.FFileTimeMax := {$IFDEF RTL220_UP}LastChangeBefore{$ELSE}DateTimeToFileDate(LastChangeBefore){$ENDIF};
Task.SynchronizationMode := SynchronizationMode;
Task.FOnEnterDirectory := OnEnterDirectory;
Task.OnTerminate := TaskTerminated;
FTasks.Add(Task);
if FRefCount > 0 then
_AddRef;
Result := Task;
end;
function TJclFileEnumerator.FillList(List: TStrings): TFileSearchTaskID;
begin
List.BeginUpdate;
try
Result := ForEach(List.Append);
finally
List.EndUpdate;
end;
end;
function TJclFileEnumerator.ForEach(Handler: TFileHandlerEx): TFileSearchTaskID;
var
Task: TEnumFileThread;
begin
Task := TEnumFileThread(CreateTask);
Task.FFileHandlerEx := Handler;
Result := Task.ID;
{$IFDEF RTL210_UP}
Task.Suspended := False;
{$ELSE ~RTL210_UP}
Task.Resume;
{$ENDIF ~RTL210_UP}
end;
function TJclFileEnumerator.ForEach(Handler: TFileHandler): TFileSearchTaskID;
var
Task: TEnumFileThread;
begin
Task := TEnumFileThread(CreateTask);
Task.FFileHandler := Handler;
Result := Task.ID;
{$IFDEF RTL210_UP}
Task.Suspended := False;
{$ELSE ~RTL210_UP}
Task.Resume;
{$ENDIF ~RTL210_UP}
end;
function TJclFileEnumerator.GetRunningTasks: Integer;
begin
Result := FTasks.Count;
end;
procedure TJclFileEnumerator.StopTask(ID: TFileSearchTaskID);
var
Task: TEnumFileThread;
I: Integer;
begin
for I := 0 to FTasks.Count - 1 do
begin
Task := TEnumFileThread(FTasks[I]);
if Task.ID = ID then
begin
Task.Terminate;
Break;
end;
end;
end;
procedure TJclFileEnumerator.StopAllTasks(Silently: Boolean = False);
var
I: Integer;
begin
for I := 0 to FTasks.Count - 1 do
begin
TEnumFileThread(FTasks[I]).FNotifyOnTermination := not Silently;
TEnumFileThread(FTasks[I]).Terminate;
end;
end;
procedure TJclFileEnumerator.TaskTerminated(Sender: TObject);
begin
FTasks.Remove(Sender);
try
if Assigned(FOnTerminateTask) then
FOnTerminateTask(TEnumFileThread(Sender).ID, TEnumFileThread(Sender).Terminated);
finally
if FRefCount > 0 then
_Release;
end;
end;
function TJclFileEnumerator.GetNextTaskID: TFileSearchTaskID;
begin
Result := FNextTaskID;
Inc(FNextTaskID);
end;
function TJclFileEnumerator.GetOnEnterDirectory: TFileHandler;
begin
Result := FOnEnterDirectory;
end;
function TJclFileEnumerator.GetOnTerminateTask: TFileSearchTerminationEvent;
begin
Result := FOnTerminateTask;
end;
function TJclFileEnumerator.GetSynchronizationMode: TFileEnumeratorSyncMode;
begin
Result := FSynchronizationMode;
end;
procedure TJclFileEnumerator.SetOnEnterDirectory(
const Value: TFileHandler);
begin
FOnEnterDirectory := Value;
end;
procedure TJclFileEnumerator.SetOnTerminateTask(
const Value: TFileSearchTerminationEvent);
begin
FOnTerminateTask := Value;
end;
procedure TJclFileEnumerator.SetSynchronizationMode(
const Value: TFileEnumeratorSyncMode);
begin
FSynchronizationMode := Value;
end;
function FileSearch: IJclFileEnumerator;
begin
Result := TJclFileEnumerator.Create;
end;
function SamePath(const Path1, Path2: string): Boolean;
begin
{$IFDEF MSWINDOWS}
Result := AnsiSameText(PathGetLongName(Path1), PathGetLongName(Path2));
{$ELSE ~MSWINDOWS}
Result := Path1 = Path2;
{$ENDIF ~MSWINDOWS}
end;
// add items at the end
procedure PathListAddItems(var List: string; const Items: string);
begin
ListAddItems(List, DirSeparator, Items);
end;
// add items at the end if they are not present
procedure PathListIncludeItems(var List: string; const Items: string);
var
StrList, NewItems: TStringList;
IndexNew, IndexList: Integer;
Item: string;
Duplicate: Boolean;
begin
StrList := TStringList.Create;
try
StrToStrings(List, DirSeparator, StrList);
NewItems := TStringList.Create;
try
StrToStrings(Items, DirSeparator, NewItems);
for IndexNew := 0 to NewItems.Count - 1 do
begin
Item := NewItems.Strings[IndexNew];
Duplicate := False;
for IndexList := 0 to StrList.Count - 1 do
if SamePath(Item, StrList.Strings[IndexList]) then
begin
Duplicate := True;
Break;
end;
if not Duplicate then
StrList.Add(Item);
end;
List := StringsToStr(StrList, DirSeparator);
finally
NewItems.Free;
end;
finally
StrList.Free;
end;
end;
// delete multiple items
procedure PathListDelItems(var List: string; const Items: string);
var
StrList, RemItems: TStringList;
IndexRem, IndexList: Integer;
Item: string;
begin
StrList := TStringList.Create;
try
StrToStrings(List, DirSeparator, StrList);
RemItems := TStringList.Create;
try
StrToStrings(Items, DirSeparator, RemItems);
for IndexRem := 0 to RemItems.Count - 1 do
begin
Item := RemItems.Strings[IndexRem];
for IndexList := StrList.Count - 1 downto 0 do
if SamePath(Item, StrList.Strings[IndexList]) then
StrList.Delete(IndexList);
end;
List := StringsToStr(StrList, DirSeparator);
finally
RemItems.Free;
end;
finally
StrList.Free;
end;
end;
// delete one item
procedure PathListDelItem(var List: string; const Index: Integer);
begin
ListDelItem(List, DirSeparator, Index);
end;
// return the number of item
function PathListItemCount(const List: string): Integer;
begin
Result := ListItemCount(List, DirSeparator);
end;
// return the Nth item
function PathListGetItem(const List: string; const Index: Integer): string;
begin
Result := ListGetItem(List, DirSeparator, Index);
end;
// set the Nth item
procedure PathListSetItem(var List: string; const Index: Integer; const Value: string);
begin
ListSetItem(List, DirSeparator, Index, Value);
end;
// return the index of an item
function PathListItemIndex(const List, Item: string): Integer;
var
StrList: TStringList;
IndexList: Integer;
begin
StrList := TStringList.Create;
try
StrToStrings(List, DirSeparator, StrList);
Result := -1;
for IndexList := 0 to StrList.Count - 1 do
if SamePath(StrList.Strings[IndexList], Item) then
begin
Result := IndexList;
Break;
end;
finally
StrList.Free;
end;
end;
// additional functions to access the commandline parameters of an application
// returns the name of the command line parameter at position index, which is
// separated by the given separator, if the first character of the name part
// is one of the AllowedPrefixCharacters, this character will be deleted.
function ParamName (Index : Integer; const Separator : string = '=';
const AllowedPrefixCharacters : string = '-/'; TrimName : Boolean = true) : string;
var s: string;
p: Integer;
begin
if (index > 0) and (index <= ParamCount) then
begin
s := ParamStr(index);
if Pos(Copy(s, 1, 1), AllowedPrefixCharacters) > 0 then
s := Copy (s, 2, Length(s)-1);
p := Pos(Separator, s);
if p > 0 then
s := Copy (s, 1, p-1);
if TrimName then
s := Trim(s);
Result := s;
end
else
Result := '';
end;
// returns the value of the command line parameter at position index, which is
// separated by the given separator
function ParamValue (Index : Integer; const Separator : string = '='; TrimValue : Boolean = true) : string;
var s: string;
p: Integer;
begin
if (index > 0) and (index <= ParamCount) then
begin
s := ParamStr(index);
p := Pos(Separator, s);
if p > 0 then
s := Copy (s, p+1, Length(s)-p);
if TrimValue then
s := Trim(s);
Result := s;
end
else
Result := '';
end;
// seaches a command line parameter where the namepart is the searchname
// and returns the value which is which by the given separator.
// CaseSensitive defines the search type. if the first character of the name part
// is one of the AllowedPrefixCharacters, this character will be deleted.
function ParamValue (const SearchName : string; const Separator : string = '=';
CaseSensitive : Boolean = False;
const AllowedPrefixCharacters : string = '-/'; TrimValue : Boolean = true) : string;
var pName : string;
i : Integer;
begin
Result := '';
for i := 1 to ParamCount do
begin
pName := ParamName(i, Separator, AllowedPrefixCharacters, True);
if (CaseSensitive and (pName = Trim(SearchName))) or
(UpperCase(pName) = Trim(UpperCase(SearchName))) then
begin
Result := ParamValue (i, Separator, TrimValue);
exit;
end;
end;
end;
// seaches a command line parameter where the namepart is the searchname
// and returns the position index. if no separator is defined, the full paramstr is compared.
// CaseSensitive defines the search type. if the first character of the name part
// is one of the AllowedPrefixCharacters, this character will be deleted.
function ParamPos (const SearchName : string; const Separator : string = '=';
CaseSensitive : Boolean = False;
const AllowedPrefixCharacters : string = '-/'): Integer;
var pName : string;
i : Integer;
begin
Result := -1;
for i := 1 to ParamCount do
begin
pName := ParamName(i, Separator, AllowedPrefixCharacters, True);
if (CaseSensitive and (pName = SearchName)) or
(UpperCase(pName) = UpperCase(SearchName)) then
begin
Result := i;
Exit;
end;
end;
end;
{$IFDEF UNITVERSIONING}
initialization
RegisterUnitVersion(HInstance, UnitVersioning);
finalization
UnregisterUnitVersion(HInstance);
{$ENDIF UNITVERSIONING}
end.
| 30.740119 | 137 | 0.694056 |
4711563b4928a111024f46dd563b3c803e406902 | 1,426 | pas | Pascal | delphi/0150.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| 11 | 2015-12-12T05:13:15.000Z | 2020-10-14T13:32:08.000Z | delphi/0150.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| null | null | null | delphi/0150.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| 8 | 2017-05-05T05:24:01.000Z | 2021-07-03T20:30:09.000Z | (*
In article 3A77@popalex1.linknet.net, Bill Taylor <btaylor@popalex1.linknet.net> () writes:
>How can you loop through and set properties of components without
>manually setting each component seperately. For example, I am writing a
>program which uses 16 TPanels and 16 TImages. Currently, I am setting the
>tag and color properties of these components as follows.
>
>Loc1.Tag := 0; Pos1.color := clBlack;
>Loc2.Tag := 0; Pos2.color := clBlack;
>Loc3.Tag := 0; Pos3.color := clBlack;
>Loc4.Tag := 0; Pos4.color := clBlack;
>Loc5.Tag := 0; Pos5.color := clBlack;
>Loc6.Tag := 0; Pos6.color := clBlack;
>Loc7.Tag := 0; Pos7.color := clBlack;
>Loc8.Tag := 0; Pos8.color := clBlack;
>Loc9.Tag := 0; Pos9.color := clBlack;
>Loc10.Tag := 0; Pos10.color := clBlack;
>Loc11.Tag := 0; Pos11.color := clBlack;
>Loc12.Tag := 0; Pos12.color := clBlack;
>Loc13.Tag := 0; Pos13.color := clBlack;
>Loc14.Tag := 0; Pos14.color := clBlack;
>Loc15.Tag := 0; Pos15.color := clBlack;
>Loc16.Tag := 0; Pos16.color := clBlack;
>
>This works, but doesn't look to good. I would like to do a for loop to
>set these properties.
*)
Try something of the following flavor:
for I := 0 to ComponentCount - 1 do
if (Components[I] is TLabel) or (Components[I] is TImage) then
with Components[I] as TLabel, Components[I] as TImage do
begin
Tag := 0;
Color := clBlack;
end;
| 37.526316 | 92 | 0.652174 |
6185df25163fd97cbc63f482046f721d89cf52ef | 10,089 | pas | Pascal | windows/src/ext/jedi/jvcl/jvcl/devtools/JvExVCL/src/JvExStdCtrls.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 219 | 2017-06-21T03:37:03.000Z | 2022-03-27T12:09:28.000Z | windows/src/ext/jedi/jvcl/jvcl/devtools/JvExVCL/src/JvExStdCtrls.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 4,451 | 2017-05-29T02:52:06.000Z | 2022-03-31T23:53:23.000Z | windows/src/ext/jedi/jvcl/jvcl/devtools/JvExVCL/src/JvExStdCtrls.pas | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 72 | 2017-05-26T04:08:37.000Z | 2022-03-03T10:26:20.000Z | {-----------------------------------------------------------------------------
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: JvExStdCtrls.pas, released on 2004-01-04
The Initial Developer of the Original Code is Andreas Hausladen [Andreas dott Hausladen att gmx dott de]
Portions created by Andreas Hausladen are Copyright (C) 2003 Andreas Hausladen.
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:
-----------------------------------------------------------------------------}
// $Id$
unit JvExStdCtrls;
{$I jvcl.inc}
{MACROINCLUDE JvExControls.macros}
WARNINGHEADER
interface
uses
Windows, Messages, Types,
SysUtils, Classes, Graphics, Controls, Forms, StdCtrls,
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
JvTypes, JvThemes, JVCLVer, JvExControls;
type
WINCONTROL_DECL_DEFAULT(CustomGroupBox)
{$DEFINE HASAUTOSIZE}
CONTROL_DECL_DEFAULT(CustomLabel)
CONTROL_DECL_DEFAULT(Label)
{$UNDEF HASAUTOSIZE}
TJvExCustomEdit = class(TCustomEdit, IJvExControl)
EDITCONTROL_DECL
private
{$IFNDEF COMPILER12_UP}
FTextHint: string;
procedure SetTextHint(const Value: string);
{$ENDIF ~COMPILER12_UP}
function UserTextHint: Boolean;
protected
procedure DoSetTextHint(const Value: string); {$IFDEF COMPILER12_UP}override;{$ELSE}virtual;{$ENDIF}
procedure PaintWindow(DC: HDC); override;
procedure WMSetFocus(var Msg: TWMSetFocus); message WM_SETFOCUS;
procedure WMKillFocus(var Msg: TWMKillFocus); message WM_KILLFOCUS;
{$IFNDEF COMPILER12_UP}
procedure CreateWnd; override;
property TextHint: string read FTextHint write SetTextHint;
{$ENDIF ~COMPILER12_UP}
end;
EDITCONTROL_DECL_DEFAULT(CustomMemo)
WINCONTROL_DECL_DEFAULT(CustomCombo)
TJvExCustomComboBox = class(TCustomComboBox, IJvExControl)
WINCONTROL_DECL
private
{$IFNDEF COMPILER12_UP}
FTextHint: string;
procedure SetTextHint(const Value: string);
{$ENDIF ~COMPILER12_UP}
function UserTextHint: Boolean;
function IsEditReadOnly: Boolean;
protected
procedure DoSetTextHint; {$IFDEF COMPILER12_UP}override;{$ELSE}virtual;{$ENDIF}
procedure ComboWndProc(var Message: TMessage; ComboWnd: HWND; ComboProc: Pointer); override;
{$IFNDEF COMPILER12_UP}
procedure CreateWnd; override;
property TextHint: string read FTextHint write SetTextHint;
{$ENDIF ~COMPILER12_UP}
end;
WINCONTROL_DECL_DEFAULT(ButtonControl)
WINCONTROL_DECL_DEFAULT(Button)
WINCONTROL_DECL_DEFAULT(CustomCheckBox)
WINCONTROL_DECL_DEFAULT(RadioButton)
WINCONTROL_DECL_DEFAULT(CustomListBox)
WINCONTROL_DECL_DEFAULT(ScrollBar)
WINCONTROL_DECL_DEFAULT(GroupBox)
WINCONTROL_DECL_DEFAULT(CheckBox)
WINCONTROL_DECL_DEFAULT(CustomStaticText)
WINCONTROL_DECL_DEFAULT(StaticText)
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$URL$';
Revision: '$Revision$';
Date: '$Date$';
LogPath: 'JVCL\run'
);
{$ENDIF UNITVERSIONING}
implementation
uses
JclSysInfo;
{$IFNDEF COMPILER12_UP}
const
ECM_FIRST = $1500;
EM_SETCUEBANNER = ECM_FIRST + 1; // Set the cue banner with the lParam = LPCWSTR
CBM_FIRST = $1700;
CB_SETCUEBANNER = CBM_FIRST + 3;
type
UnicodeString = WideString;
{$ENDIF ~COMPILER12_UP}
WINCONTROL_IMPL_DEFAULT(CustomGroupBox)
{$DEFINE HASAUTOSIZE}
CONTROL_IMPL_DEFAULT(CustomLabel)
CONTROL_IMPL_DEFAULT(Label)
{$UNDEF HASAUTOSIZE}
BEGIN_EDITCONTROL_CONSTRUCTOR(CustomEdit)
if UserTextHint then
ControlState := ControlState + [csCustomPaint]; // needed for PaintWindow
END_CONSTRUCTOR
EDITCONTROL_IMPL(CustomEdit)
EDITCONTROL_WNDPROC(CustomEdit)
{$IFNDEF COMPILER12_UP}
procedure TJvExCustomEdit.SetTextHint(const Value: string);
begin
if FTextHint <> Value then
begin
FTextHint := Value;
if not (csLoading in ComponentState) then
DoSetTextHint(FTextHint);
end;
end;
procedure TJvExCustomEdit.CreateWnd;
begin
inherited CreateWnd;
DoSetTextHint(FTextHint);
end;
{$ENDIF ~COMPILER12_UP}
function TJvExCustomEdit.UserTextHint: Boolean;
begin
{$IFDEF JVCLThemesEnabled}
Result := not (JclCheckWinVersion(5, 1) and StyleServices.Enabled);
{$ELSE}
Result := True;
{$ENDIF JVCLThemesEnabled}
end;
procedure TJvExCustomEdit.DoSetTextHint(const Value: string);
begin
{$IFDEF COMPILER12_UP}
inherited DoSetTextHint(Value);
{$ELSE}
{$IFDEF JVCLThemesEnabled}
if JclCheckWinVersion(5, 1) and StyleServices.Enabled and HandleAllocated then
SendMessage(Handle, EM_SETCUEBANNER, WPARAM(0), LPARAM(PWideChar(UnicodeString(Value))));
{$ENDIF JVCLThemesEnabled}
{$ENDIF COMPILER12_UP}
if UserTextHint and HandleAllocated and
not Focused and Enabled and not ReadOnly and (Text = '') then
Invalidate;
end;
procedure TJvExCustomEdit.PaintWindow(DC: HDC);
var
R: TRect;
OldFont: HFONT;
OldTextColor: TColorRef;
begin
inherited PaintWindow(DC);
if UserTextHint and (TextHint <> '') and
Enabled and not ReadOnly and not Focused and (Text = '') then
begin
SendMessage(Handle, EM_GETRECT, 0, LPARAM(@R));
OldFont := SelectObject(DC, Font.Handle);
OldTextColor := SetTextColor(DC, ColorToRGB(clGrayText));
DrawText(DC, PChar(TextHint), Length(TextHint), R, DT_LEFT or DT_VCENTER or DT_SINGLELINE or DT_NOPREFIX);
SetTextColor(DC, OldTextColor);
SelectObject(DC, OldFont);
end;
end;
procedure TJvExCustomEdit.WMKillFocus(var Msg: TWMKillFocus);
begin
inherited;
if UserTextHint and (TextHint <> '') then
Invalidate;
end;
procedure TJvExCustomEdit.WMSetFocus(var Msg: TWMSetFocus);
begin
if UserTextHint and (TextHint <> '') then
Invalidate;
inherited;
end;
EDITCONTROL_IMPL_DEFAULT(CustomMemo)
WINCONTROL_IMPL_DEFAULT(CustomCombo)
BEGIN_WINCONTROL_CONSTRUCTOR(CustomComboBox)
if UserTextHint then
ControlState := ControlState + [csCustomPaint]; // needed for PaintWindow
END_CONSTRUCTOR
WINCONTROL_IMPL(CustomComboBox)
WINCONTROL_WNDPROC(CustomComboBox)
{$IFNDEF COMPILER12_UP}
procedure TJvExCustomComboBox.SetTextHint(const Value: string);
begin
if FTextHint <> Value then
begin
FTextHint := Value;
if not (csLoading in ComponentState) then
DoSetTextHint;
end;
end;
procedure TJvExCustomComboBox.CreateWnd;
begin
inherited CreateWnd;
DoSetTextHint;
end;
{$ENDIF ~COMPILER12_UP}
function TJvExCustomComboBox.UserTextHint: Boolean;
begin
{$IFDEF JVCLThemesEnabled}
Result := not (JclCheckWinVersion(5, 1) and StyleServices.Enabled);
{$ELSE}
Result := True;
{$ENDIF JVCLThemesEnabled}
end;
function TJvExCustomComboBox.IsEditReadOnly: Boolean;
begin
Result := HandleAllocated and (GetWindowLong(FEditHandle, GWL_STYLE) and ES_READONLY <> 0);
end;
procedure TJvExCustomComboBox.DoSetTextHint;
begin
{$IFDEF COMPILER12_UP}
inherited DoSetTextHint;
{$ELSE}
{$IFDEF JVCLThemesEnabled}
if StyleServices.Enabled and HandleAllocated then
begin
if JclCheckWinVersion(6, 0) then
SendMessage(Handle, CB_SETCUEBANNER, WPARAM(0), LPARAM(PWideChar(UnicodeString(FTextHint))))
else if JclCheckWinVersion(5, 1) then
SendMessage(FEditHandle, EM_SETCUEBANNER, WPARAM(0), LPARAM(PWideChar(UnicodeString(FTextHint))));
end;
{$ENDIF JVCLThemesEnabled}
{$ENDIF COMPILER12_UP}
if UserTextHint and HandleAllocated and
not Focused and Enabled and not IsEditReadOnly and (Text = '') then
Invalidate;
end;
procedure TJvExCustomComboBox.ComboWndProc(var Message: TMessage; ComboWnd: HWND; ComboProc: Pointer);
procedure EditPaintWindow(DC: HDC);
var
R: TRect;
OldFont: HFONT;
OldTextColor: TColorRef;
begin
if UserTextHint and (TextHint <> '') and
Enabled and not IsEditReadOnly and not Focused and (Text = '') then
begin
SendMessage(FEditHandle, EM_GETRECT, 0, LPARAM(@R));
OldFont := SelectObject(DC, Font.Handle);
OldTextColor := SetTextColor(DC, ColorToRGB(clGrayText));
DrawText(DC, PChar(TextHint), Length(TextHint), R, DT_LEFT or DT_VCENTER or DT_SINGLELINE or DT_NOPREFIX);
SetTextColor(DC, OldTextColor);
SelectObject(DC, OldFont);
end;
end;
var
DC: HDC;
PaintStruct: TPaintStruct;
begin
DC := 0;
try
if (ComboWnd = FEditHandle) and UserTextHint and (Message.Msg = WM_PAINT) then
begin
if TWMPaint(Message).DC = 0 then
begin
DC := BeginPaint(ComboWnd, PaintStruct);
TWMPaint(Message).DC := DC;
end;
end;
inherited ComboWndProc(Message, ComboWnd, ComboProc);
if ComboWnd = FEditHandle then
begin
case Message.Msg of
WM_PAINT:
EditPaintWindow(DC);
WM_PRINTCLIENT:
EditPaintWindow(HDC(Message.WParam));
WM_KILLFOCUS, WM_SETFOCUS:
if UserTextHint and (TextHint <> '') then
Invalidate;
end;
end;
finally
if DC <> 0 then
begin
EndPaint(ComboWnd, PaintStruct);
TWMPaint(Message).DC := 0;
end;
end;
end;
WINCONTROL_IMPL_DEFAULT(ButtonControl)
WINCONTROL_IMPL_DEFAULT(Button)
WINCONTROL_IMPL_DEFAULT(CustomCheckBox)
WINCONTROL_IMPL_DEFAULT(RadioButton)
WINCONTROL_IMPL_DEFAULT(CustomListBox)
WINCONTROL_IMPL_DEFAULT(ScrollBar)
WINCONTROL_IMPL_DEFAULT(GroupBox)
WINCONTROL_IMPL_DEFAULT(CheckBox)
WINCONTROL_IMPL_DEFAULT(CustomStaticText)
WINCONTROL_IMPL_DEFAULT(StaticText)
{$IFDEF UNITVERSIONING}
initialization
RegisterUnitVersion(HInstance, UnitVersioning);
finalization
UnregisterUnitVersion(HInstance);
{$ENDIF UNITVERSIONING}
end. | 25.477273 | 112 | 0.73704 |
4781715a86612ebc072d5ca256ec49198a32ff63 | 2,187 | pas | Pascal | samples/concurrency_speed_test/WebModuleU.pas | JensMertelmeyer/delphimvcframework | 1c9bcea41cbded5eacffeaab3275b9b9aa9761de | [
"Apache-2.0"
]
| 1,009 | 2015-05-28T12:34:39.000Z | 2022-03-30T14:10:18.000Z | samples/concurrency_speed_test/WebModuleU.pas | FinCodeur/delphimvcframework | a45cb1383eaffc9e81a836247643390acbb7b9b0 | [
"Apache-2.0"
]
| 454 | 2015-05-28T12:44:27.000Z | 2022-03-31T22:35:45.000Z | samples/concurrency_speed_test/WebModuleU.pas | FinCodeur/delphimvcframework | a45cb1383eaffc9e81a836247643390acbb7b9b0 | [
"Apache-2.0"
]
| 377 | 2015-05-28T16:29:21.000Z | 2022-03-21T18:36:12.000Z | unit WebModuleU;
interface
uses System.SysUtils,
System.Classes,
Web.HTTPApp,
MVCFramework;
type
TMyWebModule = class(TWebModule)
procedure WebModuleCreate(Sender: TObject);
procedure WebModuleDestroy(Sender: TObject);
private
FMVC: TMVCEngine;
public
{ Public declarations }
end;
var
WebModuleClass: TComponentClass = TMyWebModule;
implementation
{$R *.dfm}
uses
MainControllerU,
System.IOUtils,
MVCFramework.Commons,
MVCFramework.Middleware.Compression,
MVCFramework.Middleware.StaticFiles;
procedure TMyWebModule.WebModuleCreate(Sender: TObject);
begin
FMVC := TMVCEngine.Create(Self,
procedure(Config: TMVCConfig)
begin
// session timeout (0 means session cookie)
Config[TMVCConfigKey.SessionTimeout] := '0';
//default content-type
Config[TMVCConfigKey.DefaultContentType] := TMVCConstants.DEFAULT_CONTENT_TYPE;
//default content charset
Config[TMVCConfigKey.DefaultContentCharset] := TMVCConstants.DEFAULT_CONTENT_CHARSET;
//unhandled actions are permitted?
Config[TMVCConfigKey.AllowUnhandledAction] := 'false';
//default view file extension
Config[TMVCConfigKey.DefaultViewFileExtension] := 'html';
//view path
Config[TMVCConfigKey.ViewPath] := 'templates';
//Max Record Count for automatic Entities CRUD
Config[TMVCConfigKey.MaxEntitiesRecordCount] := '20';
//Enable Server Signature in response
Config[TMVCConfigKey.ExposeServerSignature] := 'false';
// Max request size in bytes
Config[TMVCConfigKey.MaxRequestSize] := IntToStr(TMVCConstants.DEFAULT_MAX_REQUEST_SIZE);
end);
FMVC.AddController(TMyController);
// To enable compression (deflate, gzip) just add this middleware as the last one
FMVC.AddMiddleware(TMVCStaticFilesMiddleware.Create(
'/', { StaticFilesPath }
TPath.Combine(ExtractFilePath(GetModuleName(HInstance)), 'www'), { DocumentRoot }
'index.html' {IndexDocument - Before it was named fallbackresource}
));
FMVC.AddMiddleware(TMVCCompressionMiddleware.Create);
end;
procedure TMyWebModule.WebModuleDestroy(Sender: TObject);
begin
FMVC.Free;
end;
end.
| 29.554054 | 95 | 0.735711 |
f1febd68b414e137431a469445c198753b960794 | 2,499 | dpr | Pascal | Delphi/Semester-1/Matrix2.dpr | KvanTTT/Education | e9dc00bfc25ccf0e25c4e7ec187bccb680f126f9 | [
"MIT"
]
| 1 | 2018-04-06T19:47:37.000Z | 2018-04-06T19:47:37.000Z | Delphi/Semester-1/Matrix2.dpr | KvanTTT/BMSTU-Education | e9dc00bfc25ccf0e25c4e7ec187bccb680f126f9 | [
"MIT"
]
| null | null | null | Delphi/Semester-1/Matrix2.dpr | KvanTTT/BMSTU-Education | e9dc00bfc25ccf0e25c4e7ec187bccb680f126f9 | [
"MIT"
]
| null | null | null | program Matrix2;
{$APPTYPE CONSOLE}
{ Перемножение элементов столбцов исходной матрицы до минимального,
а также поиск значений в матрице, делящихся на 7 и занесение их в массив }
var
X: array[1..10] of array[1..8] of Integer; // Исходная матрица
A: array of Integer; // Массив, в который заносятся
// элементы из матрицы, делящиеся на 7
Row, Column: Integer; // Количество строк и столбцов в матрице Х
I, J: Integer; // Параметры цикла
Min: Real; // Минимальный элемент в каждом столбце матрицы Х
MinIndex: Integer; // Номер минимального элемента в каждом столбце матрицы Х
M: Integer; // Результат перемножение всех элементов в
// столбце матрицы до минимального элемента
begin
// Ввод матрицы
WriteLn('Enter matrix size Row x Column : ');
ReadLn(Row, Column);
WriteLn('Enter matrix X');
for I := 1 to Row do
for J := 1 to Column do
Read(X[I, J]);
ReadLn;
// Вывод исходной матрицы
WriteLn(' ');
WriteLn('Matrix X:');
for I := 1 to Row do
begin
for J := 1 to Column do
Write(X[I, J]:4);
WriteLn('');
end;
// Перемножение всех элементов в столбце матрицы до минимального элемента
for I := 1 to Column do
begin
Min := X[1, I];
M := X[1, I];
for J := 1 to Row do
if X[J, I] < Min then
begin
Min := X[J, I];
MinIndex := J;
end;
for J := 2 to MinIndex - 1 do
M := M * X[J, I];
X[MinIndex, I] := M;
end;
// Поиск в матрице значений, делящихся на 7 и их занесение в массив
for I := 1 to Row do
for J := 1 to Column do
if X[I, J] mod 7 = 0 then
begin
SetLength(A, Length(A) + 1);
A[High(A)] := X[I, J];
end;
// Вывод преобразованной матрицы
WriteLn('');
WriteLn('Transformed matrix:');
for I := 1 to Row do
begin
for J := 1 to Column do
Write(X[I, J]:4);
WriteLn('');
end;
// Вывод массива А
WriteLn('');
WriteLn('Vector A: ');
if Length(A) <> 0 then
begin
for I := 0 to High(A) do
if (I+1) mod 5 = 0 then
WriteLn('A[', I, '] = ', A[I], ', ')
else
Write('A[', I, '] = ', A[I], ', ');
end
else
WriteLn('There are 0 elements, which divided by 7');
ReadLn;
ReadLn;
end.
| 27.163043 | 103 | 0.523409 |
47293f54834b518203a51e0b2defc64275377352 | 170,307 | pas | Pascal | utilities/generator/project/templates/FHIR.R5.Types.pas | 17-years-old/fhirserver | 9575a7358868619311a5d1169edde3ffe261e558 | [
"BSD-3-Clause"
]
| null | null | null | utilities/generator/project/templates/FHIR.R5.Types.pas | 17-years-old/fhirserver | 9575a7358868619311a5d1169edde3ffe261e558 | [
"BSD-3-Clause"
]
| null | null | null | utilities/generator/project/templates/FHIR.R5.Types.pas | 17-years-old/fhirserver | 9575a7358868619311a5d1169edde3ffe261e558 | [
"BSD-3-Clause"
]
| null | null | null | unit FHIR.R5.Types;
{$I fhir.r5.inc}
{
Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
interface
{{mark}}
uses
Classes, SysUtils, EncdDecd,
FHIR.Support.Base, FHIR.Support.Utilities, FHIR.Support.Signatures, FHIR.Support.Stream,
FHIR.Base.Objects, FHIR.Base.Xhtml, FHIR.Base.Lang,
FHIR.R5.Base, FHIR.R5.Enums;
type
{{type.abstract.fwds}}
TFhirEnum = class;
TFhirEnumList = class;
TFhirDate = class;
TFhirDateList = class;
TFhirDateTime = class;
TFhirDateTimeList = class;
TFhirString = class;
TFhirStringList = class;
TFhirInteger = class;
TFhirIntegerList = class;
TFhirUri = class;
TFhirUriList = class;
TFhirInstant = class;
TFhirInstantList = class;
TFhirXhtml = class;
TFhirXhtmlList = class;
TFhirBoolean = class;
TFhirBooleanList = class;
TFhirBase64Binary = class;
TFhirBase64BinaryList = class;
TFhirTime = class;
TFhirTimeList = class;
TFhirDecimal = class;
TFhirDecimalList = class;
TFhirCode = class;
TFhirCodeList = class;
TFhirCanonical = class;
TFhirCanonicalList = class;
TFhirOid = class;
TFhirOidList = class;
TFhirUuid = class;
TFhirUuidList = class;
TFhirUrl = class;
TFhirUrlList = class;
TFhirMarkdown = class;
TFhirMarkdownList = class;
TFhirUnsignedInt = class;
TFhirUnsignedIntList = class;
TFhirId = class;
TFhirIdList = class;
TFhirPositiveInt = class;
TFhirPositiveIntList = class;
TFhirInteger64 = class;
TFhirInteger64List = class;
{{type.concrete.fwds}}
{{type.abstract.intf}}
// a complex Enum - has an Id attribute, and extensions.
// Used where a FHIR element is a Enum, and extensions
TFhirEnum = class (TFhirPrimitiveType)
private
FValue: String;
FSystem: String;
procedure setValue(value: String);
protected
procedure GetChildrenByName(child_name : string; list : TFHIRSelectionList); override;
procedure ListProperties(oList : TFHIRPropertyList; bInheritedProperties, bPrimitiveValues : Boolean); override;
function AsStringValue : String; override;
procedure SetStringValue(value : String); override;
public
constructor Create(system : String; value : String); overload;
destructor Destroy; override;
function Link : TFhirEnum; overload;
function Clone : TFhirEnum; overload;
procedure Assign(oSource : TFslObject); override;
function Equals(other : TObject) : boolean; override;
function isEmpty : boolean; override;
function isEnum : boolean; override;
function fhirType : string; override;
published
// The actual value of the enum
property value : String read FValue write SetValue;
property system : String read FSystem write FSystem;
End;
TFhirEnumListEnumerator = class (TFslObject)
private
FIndex : integer;
FList : TFhirEnumList;
function GetCurrent : TFhirEnum;
public
constructor Create(list : TFhirEnumList);
destructor Destroy; override;
function MoveNext : boolean;
property Current : TFhirEnum read GetCurrent;
end;
TFhirEnumList = class (TFHIRObjectList)
private
FSystems : Array Of String;
FCodes : Array Of String;
function GetItemN(index : Integer) : TFhirEnum;
procedure SetItemN(index : Integer; value : TFhirEnum);
protected
function ItemClass : TFslObjectClass; override;
public
constructor Create(Systems, Codes : Array Of String);
function Link : TFhirEnumList; overload;
function Clone : TFhirEnumList; overload;
function GetEnumerator : TFhirEnumListEnumerator;
// Add a FhirEnum to the end of the list.
function Append : TFhirEnum;
// Add an already existing FhirEnum to the end of the list.
procedure AddItem(value : TFhirEnum); overload;
// Add an already existing FhirEnum to the end of the list.
procedure AddItem(value : String); overload;
// See if an item is already in the list. returns -1 if not in the list
function IndexOf(value : TFhirEnum) : Integer;
// Insert FhirEnum before the designated index (0 = first item)
function Insert(index : Integer) : TFhirEnum;
// Insert an existing FhirEnum before the designated index (0 = first item)
procedure InsertItem(index : Integer; value : TFhirEnum);
// Get the iIndexth FhirEnum. (0 = first item)
procedure SetItemByIndex(index : Integer; value : TFhirEnum);
// The number of items in the collection
function Item(index : Integer) : TFhirEnum;
// The number of items in the collection
function Count : Integer; overload;
// Remove the indexth item. The first item is index 0.
procedure Remove(index : Integer);
// Remove All Items from the list
procedure ClearItems;
property FhirEnums[index : Integer] : TFhirEnum read GetItemN write SetItemN; default;
End;
// a complex Date - has an Id attribute, and extensions.
// Used where a FHIR element is a Date, and extensions
TFhirDate = class (TFhirPrimitiveType)
private
FValue: TFslDateTime;
procedure setValue(value: TFslDateTime);
protected
procedure GetChildrenByName(child_name : string; list : TFHIRSelectionList); override;
procedure ListProperties(oList : TFHIRPropertyList; bInheritedProperties, bPrimitiveValues : Boolean); override;
function AsStringValue : String; override;
procedure SetStringValue(value : String); override;
public
constructor Create(value : TFslDateTime); overload;
destructor Destroy; override;
function Link : TFhirDate; overload;
function Clone : TFhirDate; overload;
procedure Assign(oSource : TFslObject); override;
function Equals(other : TObject) : boolean; override;
function isEmpty : boolean; override;
function fhirType : string; override;
function dateValue : TFslDateTime; override;
published
// The actual value of the date
property value : TFslDateTime read FValue write SetValue;
End;
TFhirDateListEnumerator = class (TFslObject)
private
FIndex : integer;
FList : TFhirDateList;
function GetCurrent : TFhirDate;
public
constructor Create(list : TFhirDateList);
destructor Destroy; override;
function MoveNext : boolean;
property Current : TFhirDate read GetCurrent;
end;
TFhirDateList = class (TFHIRObjectList)
private
function GetItemN(index : Integer) : TFhirDate;
procedure SetItemN(index : Integer; value : TFhirDate);
protected
function ItemClass : TFslObjectClass; override;
public
function Link : TFhirDateList; overload;
function Clone : TFhirDateList; overload;
function GetEnumerator : TFhirDateListEnumerator;
// Add a FhirDate to the end of the list.
function Append : TFhirDate;
// Add an already existing FhirDate to the end of the list.
procedure AddItem(value : TFhirDate); overload;
// Add an already existing FhirDate to the end of the list.
procedure AddItem(value : TFslDateTime); overload;
// See if an item is already in the list. returns -1 if not in the list
function IndexOf(value : TFhirDate) : Integer;
// Insert FhirDate before the designated index (0 = first item)
function Insert(index : Integer) : TFhirDate;
// Insert an existing FhirDate before the designated index (0 = first item)
procedure InsertItem(index : Integer; value : TFhirDate);
// Get the iIndexth FhirDate. (0 = first item)
procedure SetItemByIndex(index : Integer; value : TFhirDate);
// The number of items in the collection
function Item(index : Integer) : TFhirDate;
// The number of items in the collection
function Count : Integer; overload;
// Remove the indexth item. The first item is index 0.
procedure Remove(index : Integer);
// Remove All Items from the list
procedure ClearItems;
property FhirDates[index : Integer] : TFhirDate read GetItemN write SetItemN; default;
End;
// a complex DateTime - has an Id attribute, and extensions.
// Used where a FHIR element is a DateTime, and extensions
TFhirDateTime = class (TFhirPrimitiveType)
private
FValue: TFslDateTime;
procedure setValue(value: TFslDateTime);
protected
procedure GetChildrenByName(child_name : string; list : TFHIRSelectionList); override;
procedure ListProperties(oList : TFHIRPropertyList; bInheritedProperties, bPrimitiveValues : Boolean); override;
function AsStringValue : String; override;
procedure SetStringValue(value : String); override;
public
constructor Create(value : TFslDateTime); overload;
destructor Destroy; override;
function Link : TFhirDateTime; overload;
function Clone : TFhirDateTime; overload;
procedure Assign(oSource : TFslObject); override;
function Equals(other : TObject) : boolean; override;
function isEmpty : boolean; override;
function fhirType : string; override;
function dateValue : TFslDateTime; override;
published
// The actual value of the dateTime
property value : TFslDateTime read FValue write SetValue;
End;
TFhirDateTimeListEnumerator = class (TFslObject)
private
FIndex : integer;
FList : TFhirDateTimeList;
function GetCurrent : TFhirDateTime;
public
constructor Create(list : TFhirDateTimeList);
destructor Destroy; override;
function MoveNext : boolean;
property Current : TFhirDateTime read GetCurrent;
end;
TFhirDateTimeList = class (TFHIRObjectList)
private
function GetItemN(index : Integer) : TFhirDateTime;
procedure SetItemN(index : Integer; value : TFhirDateTime);
protected
function ItemClass : TFslObjectClass; override;
public
function Link : TFhirDateTimeList; overload;
function Clone : TFhirDateTimeList; overload;
function GetEnumerator : TFhirDateTimeListEnumerator;
// Add a FhirDateTime to the end of the list.
function Append : TFhirDateTime;
// Add an already existing FhirDateTime to the end of the list.
procedure AddItem(value : TFhirDateTime); overload;
// Add an already existing FhirDateTime to the end of the list.
procedure AddItem(value : TFslDateTime); overload;
// See if an item is already in the list. returns -1 if not in the list
function IndexOf(value : TFhirDateTime) : Integer;
// Insert FhirDateTime before the designated index (0 = first item)
function Insert(index : Integer) : TFhirDateTime;
// Insert an existing FhirDateTime before the designated index (0 = first item)
procedure InsertItem(index : Integer; value : TFhirDateTime);
// Get the iIndexth FhirDateTime. (0 = first item)
procedure SetItemByIndex(index : Integer; value : TFhirDateTime);
// The number of items in the collection
function Item(index : Integer) : TFhirDateTime;
// The number of items in the collection
function Count : Integer; overload;
// Remove the indexth item. The first item is index 0.
procedure Remove(index : Integer);
// Remove All Items from the list
procedure ClearItems;
property FhirDateTimes[index : Integer] : TFhirDateTime read GetItemN write SetItemN; default;
End;
// a complex String - has an Id attribute, and extensions.
// Used where a FHIR element is a String, and extensions
TFhirString = class (TFhirPrimitiveType)
private
FValue: String;
procedure setValue(value: String);
protected
procedure GetChildrenByName(child_name : string; list : TFHIRSelectionList); override;
procedure ListProperties(oList : TFHIRPropertyList; bInheritedProperties, bPrimitiveValues : Boolean); override;
function AsStringValue : String; override;
procedure SetStringValue(value : String); override;
public
constructor Create(value : String); overload;
destructor Destroy; override;
function Link : TFhirString; overload;
function Clone : TFhirString; overload;
procedure Assign(oSource : TFslObject); override;
function Equals(other : TObject) : boolean; override;
function isEmpty : boolean; override;
function fhirType : string; override;
published
// The actual value of the string
property value : String read FValue write SetValue;
End;
TFhirStringListEnumerator = class (TFslObject)
private
FIndex : integer;
FList : TFhirStringList;
function GetCurrent : TFhirString;
public
constructor Create(list : TFhirStringList);
destructor Destroy; override;
function MoveNext : boolean;
property Current : TFhirString read GetCurrent;
end;
TFhirStringList = class (TFHIRObjectList)
private
function GetItemN(index : Integer) : TFhirString;
procedure SetItemN(index : Integer; value : TFhirString);
protected
function ItemClass : TFslObjectClass; override;
public
function Link : TFhirStringList; overload;
function Clone : TFhirStringList; overload;
function GetEnumerator : TFhirStringListEnumerator;
// Add a FhirString to the end of the list.
function Append : TFhirString;
// Add an already existing FhirString to the end of the list.
procedure AddItem(value : TFhirString); overload;
// Add an already existing FhirString to the end of the list.
procedure AddItem(value : String); overload;
// See if an item is already in the list. returns -1 if not in the list
function IndexOf(value : TFhirString) : Integer;
// Insert FhirString before the designated index (0 = first item)
function Insert(index : Integer) : TFhirString;
// Insert an existing FhirString before the designated index (0 = first item)
procedure InsertItem(index : Integer; value : TFhirString);
// Get the iIndexth FhirString. (0 = first item)
procedure SetItemByIndex(index : Integer; value : TFhirString);
// The number of items in the collection
function Item(index : Integer) : TFhirString;
// The number of items in the collection
function Count : Integer; overload;
// Remove the indexth item. The first item is index 0.
procedure Remove(index : Integer);
// Remove All Items from the list
procedure ClearItems;
property FhirStrings[index : Integer] : TFhirString read GetItemN write SetItemN; default;
End;
// a complex Integer - has an Id attribute, and extensions.
// Used where a FHIR element is a Integer, and extensions
TFhirInteger = class (TFhirPrimitiveType)
private
FValue: String;
procedure setValue(value: String);
protected
procedure GetChildrenByName(child_name : string; list : TFHIRSelectionList); override;
procedure ListProperties(oList : TFHIRPropertyList; bInheritedProperties, bPrimitiveValues : Boolean); override;
function AsStringValue : String; override;
procedure SetStringValue(value : String); override;
public
constructor Create(value : String); overload;
destructor Destroy; override;
function Link : TFhirInteger; overload;
function Clone : TFhirInteger; overload;
procedure Assign(oSource : TFslObject); override;
function Equals(other : TObject) : boolean; override;
function isEmpty : boolean; override;
function fhirType : string; override;
published
// The actual value of the integer
property value : String read FValue write SetValue;
End;
TFhirIntegerListEnumerator = class (TFslObject)
private
FIndex : integer;
FList : TFhirIntegerList;
function GetCurrent : TFhirInteger;
public
constructor Create(list : TFhirIntegerList);
destructor Destroy; override;
function MoveNext : boolean;
property Current : TFhirInteger read GetCurrent;
end;
TFhirIntegerList = class (TFHIRObjectList)
private
function GetItemN(index : Integer) : TFhirInteger;
procedure SetItemN(index : Integer; value : TFhirInteger);
protected
function ItemClass : TFslObjectClass; override;
public
function Link : TFhirIntegerList; overload;
function Clone : TFhirIntegerList; overload;
function GetEnumerator : TFhirIntegerListEnumerator;
// Add a FhirInteger to the end of the list.
function Append : TFhirInteger;
// Add an already existing FhirInteger to the end of the list.
procedure AddItem(value : TFhirInteger); overload;
// Add an already existing FhirInteger to the end of the list.
procedure AddItem(value : String); overload;
// See if an item is already in the list. returns -1 if not in the list
function IndexOf(value : TFhirInteger) : Integer;
// Insert FhirInteger before the designated index (0 = first item)
function Insert(index : Integer) : TFhirInteger;
// Insert an existing FhirInteger before the designated index (0 = first item)
procedure InsertItem(index : Integer; value : TFhirInteger);
// Get the iIndexth FhirInteger. (0 = first item)
procedure SetItemByIndex(index : Integer; value : TFhirInteger);
// The number of items in the collection
function Item(index : Integer) : TFhirInteger;
// The number of items in the collection
function Count : Integer; overload;
// Remove the indexth item. The first item is index 0.
procedure Remove(index : Integer);
// Remove All Items from the list
procedure ClearItems;
property FhirIntegers[index : Integer] : TFhirInteger read GetItemN write SetItemN; default;
End;
// a complex Uri - has an Id attribute, and extensions.
// Used where a FHIR element is a Uri, and extensions
TFhirUri = class (TFhirPrimitiveType)
private
FValue: String;
procedure setValue(value: String);
protected
procedure GetChildrenByName(child_name : string; list : TFHIRSelectionList); override;
procedure ListProperties(oList : TFHIRPropertyList; bInheritedProperties, bPrimitiveValues : Boolean); override;
function AsStringValue : String; override;
procedure SetStringValue(value : String); override;
public
constructor Create(value : String); overload;
destructor Destroy; override;
function Link : TFhirUri; overload;
function Clone : TFhirUri; overload;
procedure Assign(oSource : TFslObject); override;
function Equals(other : TObject) : boolean; override;
function isEmpty : boolean; override;
function fhirType : string; override;
published
// The actual value of the uri
property value : String read FValue write SetValue;
End;
TFhirUriListEnumerator = class (TFslObject)
private
FIndex : integer;
FList : TFhirUriList;
function GetCurrent : TFhirUri;
public
constructor Create(list : TFhirUriList);
destructor Destroy; override;
function MoveNext : boolean;
property Current : TFhirUri read GetCurrent;
end;
TFhirUriList = class (TFHIRObjectList)
private
function GetItemN(index : Integer) : TFhirUri;
procedure SetItemN(index : Integer; value : TFhirUri);
protected
function ItemClass : TFslObjectClass; override;
public
function Link : TFhirUriList; overload;
function Clone : TFhirUriList; overload;
function GetEnumerator : TFhirUriListEnumerator;
// Add a FhirUri to the end of the list.
function Append : TFhirUri;
// Add an already existing FhirUri to the end of the list.
procedure AddItem(value : TFhirUri); overload;
// Add an already existing FhirUri to the end of the list.
procedure AddItem(value : String); overload;
// See if an item is already in the list. returns -1 if not in the list
function IndexOf(value : TFhirUri) : Integer;
// Insert FhirUri before the designated index (0 = first item)
function Insert(index : Integer) : TFhirUri;
// Insert an existing FhirUri before the designated index (0 = first item)
procedure InsertItem(index : Integer; value : TFhirUri);
// Get the iIndexth FhirUri. (0 = first item)
procedure SetItemByIndex(index : Integer; value : TFhirUri);
// The number of items in the collection
function Item(index : Integer) : TFhirUri;
// The number of items in the collection
function Count : Integer; overload;
// Remove the indexth item. The first item is index 0.
procedure Remove(index : Integer);
// Remove All Items from the list
procedure ClearItems;
property FhirUris[index : Integer] : TFhirUri read GetItemN write SetItemN; default;
End;
// a complex Instant - has an Id attribute, and extensions.
// Used where a FHIR element is a Instant, and extensions
TFhirInstant = class (TFhirPrimitiveType)
private
FValue: TFslDateTime;
procedure setValue(value: TFslDateTime);
protected
procedure GetChildrenByName(child_name : string; list : TFHIRSelectionList); override;
procedure ListProperties(oList : TFHIRPropertyList; bInheritedProperties, bPrimitiveValues : Boolean); override;
function AsStringValue : String; override;
procedure SetStringValue(value : String); override;
public
constructor Create(value : TFslDateTime); overload;
destructor Destroy; override;
function Link : TFhirInstant; overload;
function Clone : TFhirInstant; overload;
procedure Assign(oSource : TFslObject); override;
function Equals(other : TObject) : boolean; override;
function isEmpty : boolean; override;
function fhirType : string; override;
function dateValue : TFslDateTime; override;
published
// The actual value of the instant
property value : TFslDateTime read FValue write SetValue;
End;
TFhirInstantListEnumerator = class (TFslObject)
private
FIndex : integer;
FList : TFhirInstantList;
function GetCurrent : TFhirInstant;
public
constructor Create(list : TFhirInstantList);
destructor Destroy; override;
function MoveNext : boolean;
property Current : TFhirInstant read GetCurrent;
end;
TFhirInstantList = class (TFHIRObjectList)
private
function GetItemN(index : Integer) : TFhirInstant;
procedure SetItemN(index : Integer; value : TFhirInstant);
protected
function ItemClass : TFslObjectClass; override;
public
function Link : TFhirInstantList; overload;
function Clone : TFhirInstantList; overload;
function GetEnumerator : TFhirInstantListEnumerator;
// Add a FhirInstant to the end of the list.
function Append : TFhirInstant;
// Add an already existing FhirInstant to the end of the list.
procedure AddItem(value : TFhirInstant); overload;
// Add an already existing FhirInstant to the end of the list.
procedure AddItem(value : TFslDateTime); overload;
// See if an item is already in the list. returns -1 if not in the list
function IndexOf(value : TFhirInstant) : Integer;
// Insert FhirInstant before the designated index (0 = first item)
function Insert(index : Integer) : TFhirInstant;
// Insert an existing FhirInstant before the designated index (0 = first item)
procedure InsertItem(index : Integer; value : TFhirInstant);
// Get the iIndexth FhirInstant. (0 = first item)
procedure SetItemByIndex(index : Integer; value : TFhirInstant);
// The number of items in the collection
function Item(index : Integer) : TFhirInstant;
// The number of items in the collection
function Count : Integer; overload;
// Remove the indexth item. The first item is index 0.
procedure Remove(index : Integer);
// Remove All Items from the list
procedure ClearItems;
property FhirInstants[index : Integer] : TFhirInstant read GetItemN write SetItemN; default;
End;
// a complex Xhtml - has an Id attribute, and extensions.
// Used where a FHIR element is a Xhtml, and extensions
TFhirXhtml = class (TFhirPrimitiveType)
private
FValue: String;
procedure setValue(value: String);
protected
procedure GetChildrenByName(child_name : string; list : TFHIRSelectionList); override;
procedure ListProperties(oList : TFHIRPropertyList; bInheritedProperties, bPrimitiveValues : Boolean); override;
function AsStringValue : String; override;
procedure SetStringValue(value : String); override;
public
constructor Create(value : String); overload;
destructor Destroy; override;
function Link : TFhirXhtml; overload;
function Clone : TFhirXhtml; overload;
procedure Assign(oSource : TFslObject); override;
function Equals(other : TObject) : boolean; override;
function isEmpty : boolean; override;
function fhirType : string; override;
published
// The actual value of the xhtml
property value : String read FValue write SetValue;
End;
TFhirXhtmlListEnumerator = class (TFslObject)
private
FIndex : integer;
FList : TFhirXhtmlList;
function GetCurrent : TFhirXhtml;
public
constructor Create(list : TFhirXhtmlList);
destructor Destroy; override;
function MoveNext : boolean;
property Current : TFhirXhtml read GetCurrent;
end;
TFhirXhtmlList = class (TFHIRObjectList)
private
function GetItemN(index : Integer) : TFhirXhtml;
procedure SetItemN(index : Integer; value : TFhirXhtml);
protected
function ItemClass : TFslObjectClass; override;
public
function Link : TFhirXhtmlList; overload;
function Clone : TFhirXhtmlList; overload;
function GetEnumerator : TFhirXhtmlListEnumerator;
// Add a FhirXhtml to the end of the list.
function Append : TFhirXhtml;
// Add an already existing FhirXhtml to the end of the list.
procedure AddItem(value : TFhirXhtml); overload;
// Add an already existing FhirXhtml to the end of the list.
procedure AddItem(value : String); overload;
// See if an item is already in the list. returns -1 if not in the list
function IndexOf(value : TFhirXhtml) : Integer;
// Insert FhirXhtml before the designated index (0 = first item)
function Insert(index : Integer) : TFhirXhtml;
// Insert an existing FhirXhtml before the designated index (0 = first item)
procedure InsertItem(index : Integer; value : TFhirXhtml);
// Get the iIndexth FhirXhtml. (0 = first item)
procedure SetItemByIndex(index : Integer; value : TFhirXhtml);
// The number of items in the collection
function Item(index : Integer) : TFhirXhtml;
// The number of items in the collection
function Count : Integer; overload;
// Remove the indexth item. The first item is index 0.
procedure Remove(index : Integer);
// Remove All Items from the list
procedure ClearItems;
property FhirXhtmls[index : Integer] : TFhirXhtml read GetItemN write SetItemN; default;
End;
// a complex Boolean - has an Id attribute, and extensions.
// Used where a FHIR element is a Boolean, and extensions
TFhirBoolean = class (TFhirPrimitiveType)
private
FValue: Boolean;
procedure setValue(value: Boolean);
protected
procedure GetChildrenByName(child_name : string; list : TFHIRSelectionList); override;
procedure ListProperties(oList : TFHIRPropertyList; bInheritedProperties, bPrimitiveValues : Boolean); override;
function AsStringValue : String; override;
procedure SetStringValue(value : String); override;
public
constructor Create(value : Boolean); overload;
destructor Destroy; override;
function Link : TFhirBoolean; overload;
function Clone : TFhirBoolean; overload;
procedure Assign(oSource : TFslObject); override;
function Equals(other : TObject) : boolean; override;
function isEmpty : boolean; override;
function fhirType : string; override;
published
// The actual value of the boolean
property value : Boolean read FValue write SetValue;
End;
TFhirBooleanListEnumerator = class (TFslObject)
private
FIndex : integer;
FList : TFhirBooleanList;
function GetCurrent : TFhirBoolean;
public
constructor Create(list : TFhirBooleanList);
destructor Destroy; override;
function MoveNext : boolean;
property Current : TFhirBoolean read GetCurrent;
end;
TFhirBooleanList = class (TFHIRObjectList)
private
function GetItemN(index : Integer) : TFhirBoolean;
procedure SetItemN(index : Integer; value : TFhirBoolean);
protected
function ItemClass : TFslObjectClass; override;
public
function Link : TFhirBooleanList; overload;
function Clone : TFhirBooleanList; overload;
function GetEnumerator : TFhirBooleanListEnumerator;
// Add a FhirBoolean to the end of the list.
function Append : TFhirBoolean;
// Add an already existing FhirBoolean to the end of the list.
procedure AddItem(value : TFhirBoolean); overload;
// Add an already existing FhirBoolean to the end of the list.
procedure AddItem(value : Boolean); overload;
// See if an item is already in the list. returns -1 if not in the list
function IndexOf(value : TFhirBoolean) : Integer;
// Insert FhirBoolean before the designated index (0 = first item)
function Insert(index : Integer) : TFhirBoolean;
// Insert an existing FhirBoolean before the designated index (0 = first item)
procedure InsertItem(index : Integer; value : TFhirBoolean);
// Get the iIndexth FhirBoolean. (0 = first item)
procedure SetItemByIndex(index : Integer; value : TFhirBoolean);
// The number of items in the collection
function Item(index : Integer) : TFhirBoolean;
// The number of items in the collection
function Count : Integer; overload;
// Remove the indexth item. The first item is index 0.
procedure Remove(index : Integer);
// Remove All Items from the list
procedure ClearItems;
property FhirBooleans[index : Integer] : TFhirBoolean read GetItemN write SetItemN; default;
End;
// a complex Base64Binary - has an Id attribute, and extensions.
// Used where a FHIR element is a Base64Binary, and extensions
TFhirBase64Binary = class (TFhirPrimitiveType)
private
FValue: TBytes;
procedure setValue(value: TBytes);
protected
procedure GetChildrenByName(child_name : string; list : TFHIRSelectionList); override;
procedure ListProperties(oList : TFHIRPropertyList; bInheritedProperties, bPrimitiveValues : Boolean); override;
function AsStringValue : String; override;
procedure SetStringValue(value : String); override;
public
constructor Create(value : TBytes); overload;
destructor Destroy; override;
function Link : TFhirBase64Binary; overload;
function Clone : TFhirBase64Binary; overload;
procedure Assign(oSource : TFslObject); override;
function Equals(other : TObject) : boolean; override;
function isEmpty : boolean; override;
function fhirType : string; override;
published
// The actual value of the base64Binary
property value : TBytes read FValue write SetValue;
End;
TFhirBase64BinaryListEnumerator = class (TFslObject)
private
FIndex : integer;
FList : TFhirBase64BinaryList;
function GetCurrent : TFhirBase64Binary;
public
constructor Create(list : TFhirBase64BinaryList);
destructor Destroy; override;
function MoveNext : boolean;
property Current : TFhirBase64Binary read GetCurrent;
end;
TFhirBase64BinaryList = class (TFHIRObjectList)
private
function GetItemN(index : Integer) : TFhirBase64Binary;
procedure SetItemN(index : Integer; value : TFhirBase64Binary);
protected
function ItemClass : TFslObjectClass; override;
public
function Link : TFhirBase64BinaryList; overload;
function Clone : TFhirBase64BinaryList; overload;
function GetEnumerator : TFhirBase64BinaryListEnumerator;
// Add a FhirBase64Binary to the end of the list.
function Append : TFhirBase64Binary;
// Add an already existing FhirBase64Binary to the end of the list.
procedure AddItem(value : TFhirBase64Binary); overload;
// Add an already existing FhirBase64Binary to the end of the list.
procedure AddItem(value : TBytes); overload;
// See if an item is already in the list. returns -1 if not in the list
function IndexOf(value : TFhirBase64Binary) : Integer;
// Insert FhirBase64Binary before the designated index (0 = first item)
function Insert(index : Integer) : TFhirBase64Binary;
// Insert an existing FhirBase64Binary before the designated index (0 = first item)
procedure InsertItem(index : Integer; value : TFhirBase64Binary);
// Get the iIndexth FhirBase64Binary. (0 = first item)
procedure SetItemByIndex(index : Integer; value : TFhirBase64Binary);
// The number of items in the collection
function Item(index : Integer) : TFhirBase64Binary;
// The number of items in the collection
function Count : Integer; overload;
// Remove the indexth item. The first item is index 0.
procedure Remove(index : Integer);
// Remove All Items from the list
procedure ClearItems;
property FhirBase64Binaries[index : Integer] : TFhirBase64Binary read GetItemN write SetItemN; default;
End;
// a complex Time - has an Id attribute, and extensions.
// Used where a FHIR element is a Time, and extensions
TFhirTime = class (TFhirPrimitiveType)
private
FValue: String;
procedure setValue(value: String);
protected
procedure GetChildrenByName(child_name : string; list : TFHIRSelectionList); override;
procedure ListProperties(oList : TFHIRPropertyList; bInheritedProperties, bPrimitiveValues : Boolean); override;
function AsStringValue : String; override;
procedure SetStringValue(value : String); override;
public
constructor Create(value : String); overload;
destructor Destroy; override;
function Link : TFhirTime; overload;
function Clone : TFhirTime; overload;
procedure Assign(oSource : TFslObject); override;
function Equals(other : TObject) : boolean; override;
function isEmpty : boolean; override;
function fhirType : string; override;
published
// The actual value of the time
property value : String read FValue write SetValue;
End;
TFhirTimeListEnumerator = class (TFslObject)
private
FIndex : integer;
FList : TFhirTimeList;
function GetCurrent : TFhirTime;
public
constructor Create(list : TFhirTimeList);
destructor Destroy; override;
function MoveNext : boolean;
property Current : TFhirTime read GetCurrent;
end;
TFhirTimeList = class (TFHIRObjectList)
private
function GetItemN(index : Integer) : TFhirTime;
procedure SetItemN(index : Integer; value : TFhirTime);
protected
function ItemClass : TFslObjectClass; override;
public
function Link : TFhirTimeList; overload;
function Clone : TFhirTimeList; overload;
function GetEnumerator : TFhirTimeListEnumerator;
// Add a FhirTime to the end of the list.
function Append : TFhirTime;
// Add an already existing FhirTime to the end of the list.
procedure AddItem(value : TFhirTime); overload;
// Add an already existing FhirTime to the end of the list.
procedure AddItem(value : String); overload;
// See if an item is already in the list. returns -1 if not in the list
function IndexOf(value : TFhirTime) : Integer;
// Insert FhirTime before the designated index (0 = first item)
function Insert(index : Integer) : TFhirTime;
// Insert an existing FhirTime before the designated index (0 = first item)
procedure InsertItem(index : Integer; value : TFhirTime);
// Get the iIndexth FhirTime. (0 = first item)
procedure SetItemByIndex(index : Integer; value : TFhirTime);
// The number of items in the collection
function Item(index : Integer) : TFhirTime;
// The number of items in the collection
function Count : Integer; overload;
// Remove the indexth item. The first item is index 0.
procedure Remove(index : Integer);
// Remove All Items from the list
procedure ClearItems;
property FhirTimes[index : Integer] : TFhirTime read GetItemN write SetItemN; default;
End;
// a complex Decimal - has an Id attribute, and extensions.
// Used where a FHIR element is a Decimal, and extensions
TFhirDecimal = class (TFhirPrimitiveType)
private
FValue: String;
procedure setValue(value: String);
protected
procedure GetChildrenByName(child_name : string; list : TFHIRSelectionList); override;
procedure ListProperties(oList : TFHIRPropertyList; bInheritedProperties, bPrimitiveValues : Boolean); override;
function AsStringValue : String; override;
procedure SetStringValue(value : String); override;
public
constructor Create(value : String); overload;
destructor Destroy; override;
function Link : TFhirDecimal; overload;
function Clone : TFhirDecimal; overload;
procedure Assign(oSource : TFslObject); override;
function Equals(other : TObject) : boolean; override;
function isEmpty : boolean; override;
function fhirType : string; override;
published
// The actual value of the decimal
property value : String read FValue write SetValue;
End;
TFhirDecimalListEnumerator = class (TFslObject)
private
FIndex : integer;
FList : TFhirDecimalList;
function GetCurrent : TFhirDecimal;
public
constructor Create(list : TFhirDecimalList);
destructor Destroy; override;
function MoveNext : boolean;
property Current : TFhirDecimal read GetCurrent;
end;
TFhirDecimalList = class (TFHIRObjectList)
private
function GetItemN(index : Integer) : TFhirDecimal;
procedure SetItemN(index : Integer; value : TFhirDecimal);
protected
function ItemClass : TFslObjectClass; override;
public
function Link : TFhirDecimalList; overload;
function Clone : TFhirDecimalList; overload;
function GetEnumerator : TFhirDecimalListEnumerator;
// Add a FhirDecimal to the end of the list.
function Append : TFhirDecimal;
// Add an already existing FhirDecimal to the end of the list.
procedure AddItem(value : TFhirDecimal); overload;
// Add an already existing FhirDecimal to the end of the list.
procedure AddItem(value : String); overload;
// See if an item is already in the list. returns -1 if not in the list
function IndexOf(value : TFhirDecimal) : Integer;
// Insert FhirDecimal before the designated index (0 = first item)
function Insert(index : Integer) : TFhirDecimal;
// Insert an existing FhirDecimal before the designated index (0 = first item)
procedure InsertItem(index : Integer; value : TFhirDecimal);
// Get the iIndexth FhirDecimal. (0 = first item)
procedure SetItemByIndex(index : Integer; value : TFhirDecimal);
// The number of items in the collection
function Item(index : Integer) : TFhirDecimal;
// The number of items in the collection
function Count : Integer; overload;
// Remove the indexth item. The first item is index 0.
procedure Remove(index : Integer);
// Remove All Items from the list
procedure ClearItems;
property FhirDecimals[index : Integer] : TFhirDecimal read GetItemN write SetItemN; default;
End;
// a complex Code - has an Id attribute, and extensions.
// Used where a FHIR element is a Code, and extensions
TFhirCode = class (TFhirString)
private
public
constructor Create(value : String); overload;
destructor Destroy; override;
function Link : TFhirCode; overload;
function Clone : TFhirCode; overload;
function fhirType : string; override;
End;
TFhirCodeListEnumerator = class (TFslObject)
private
FIndex : integer;
FList : TFhirCodeList;
function GetCurrent : TFhirCode;
public
constructor Create(list : TFhirCodeList);
destructor Destroy; override;
function MoveNext : boolean;
property Current : TFhirCode read GetCurrent;
end;
TFhirCodeList = class (TFHIRObjectList)
private
function GetItemN(index : Integer) : TFhirCode;
procedure SetItemN(index : Integer; value : TFhirCode);
protected
function ItemClass : TFslObjectClass; override;
public
function Link : TFhirCodeList; overload;
function Clone : TFhirCodeList; overload;
function GetEnumerator : TFhirCodeListEnumerator;
// Add a FhirCode to the end of the list.
function Append : TFhirCode;
// Add an already existing FhirCode to the end of the list.
procedure AddItem(value : TFhirCode); overload;
// Add an already existing FhirCode to the end of the list.
procedure AddItem(value : String); overload;
// See if an item is already in the list. returns -1 if not in the list
function IndexOf(value : TFhirCode) : Integer;
// Insert FhirCode before the designated index (0 = first item)
function Insert(index : Integer) : TFhirCode;
// Insert an existing FhirCode before the designated index (0 = first item)
procedure InsertItem(index : Integer; value : TFhirCode);
// Get the iIndexth FhirCode. (0 = first item)
procedure SetItemByIndex(index : Integer; value : TFhirCode);
// The number of items in the collection
function Item(index : Integer) : TFhirCode;
// The number of items in the collection
function Count : Integer; overload;
// Remove the indexth item. The first item is index 0.
procedure Remove(index : Integer);
// Remove All Items from the list
procedure ClearItems;
property FhirCodes[index : Integer] : TFhirCode read GetItemN write SetItemN; default;
End;
// a complex Canonical - has an Id attribute, and extensions.
// Used where a FHIR element is a Canonical, and extensions
TFhirCanonical = class (TFhirUri)
private
public
constructor Create(value : String); overload;
destructor Destroy; override;
function Link : TFhirCanonical; overload;
function Clone : TFhirCanonical; overload;
function fhirType : string; override;
End;
TFhirCanonicalListEnumerator = class (TFslObject)
private
FIndex : integer;
FList : TFhirCanonicalList;
function GetCurrent : TFhirCanonical;
public
constructor Create(list : TFhirCanonicalList);
destructor Destroy; override;
function MoveNext : boolean;
property Current : TFhirCanonical read GetCurrent;
end;
TFhirCanonicalList = class (TFHIRObjectList)
private
function GetItemN(index : Integer) : TFhirCanonical;
procedure SetItemN(index : Integer; value : TFhirCanonical);
protected
function ItemClass : TFslObjectClass; override;
public
function Link : TFhirCanonicalList; overload;
function Clone : TFhirCanonicalList; overload;
function GetEnumerator : TFhirCanonicalListEnumerator;
// Add a FhirCanonical to the end of the list.
function Append : TFhirCanonical;
// Add an already existing FhirCanonical to the end of the list.
procedure AddItem(value : TFhirCanonical); overload;
// Add an already existing FhirCanonical to the end of the list.
procedure AddItem(value : String); overload;
// See if an item is already in the list. returns -1 if not in the list
function IndexOf(value : TFhirCanonical) : Integer;
// Insert FhirCanonical before the designated index (0 = first item)
function Insert(index : Integer) : TFhirCanonical;
// Insert an existing FhirCanonical before the designated index (0 = first item)
procedure InsertItem(index : Integer; value : TFhirCanonical);
// Get the iIndexth FhirCanonical. (0 = first item)
procedure SetItemByIndex(index : Integer; value : TFhirCanonical);
// The number of items in the collection
function Item(index : Integer) : TFhirCanonical;
// The number of items in the collection
function Count : Integer; overload;
// Remove the indexth item. The first item is index 0.
procedure Remove(index : Integer);
// Remove All Items from the list
procedure ClearItems;
property FhirCanonicals[index : Integer] : TFhirCanonical read GetItemN write SetItemN; default;
End;
// a complex Oid - has an Id attribute, and extensions.
// Used where a FHIR element is a Oid, and extensions
TFhirOid = class (TFhirUri)
private
public
constructor Create(value : String); overload;
destructor Destroy; override;
function Link : TFhirOid; overload;
function Clone : TFhirOid; overload;
function fhirType : string; override;
End;
TFhirOidListEnumerator = class (TFslObject)
private
FIndex : integer;
FList : TFhirOidList;
function GetCurrent : TFhirOid;
public
constructor Create(list : TFhirOidList);
destructor Destroy; override;
function MoveNext : boolean;
property Current : TFhirOid read GetCurrent;
end;
TFhirOidList = class (TFHIRObjectList)
private
function GetItemN(index : Integer) : TFhirOid;
procedure SetItemN(index : Integer; value : TFhirOid);
protected
function ItemClass : TFslObjectClass; override;
public
function Link : TFhirOidList; overload;
function Clone : TFhirOidList; overload;
function GetEnumerator : TFhirOidListEnumerator;
// Add a FhirOid to the end of the list.
function Append : TFhirOid;
// Add an already existing FhirOid to the end of the list.
procedure AddItem(value : TFhirOid); overload;
// Add an already existing FhirOid to the end of the list.
procedure AddItem(value : String); overload;
// See if an item is already in the list. returns -1 if not in the list
function IndexOf(value : TFhirOid) : Integer;
// Insert FhirOid before the designated index (0 = first item)
function Insert(index : Integer) : TFhirOid;
// Insert an existing FhirOid before the designated index (0 = first item)
procedure InsertItem(index : Integer; value : TFhirOid);
// Get the iIndexth FhirOid. (0 = first item)
procedure SetItemByIndex(index : Integer; value : TFhirOid);
// The number of items in the collection
function Item(index : Integer) : TFhirOid;
// The number of items in the collection
function Count : Integer; overload;
// Remove the indexth item. The first item is index 0.
procedure Remove(index : Integer);
// Remove All Items from the list
procedure ClearItems;
property FhirOids[index : Integer] : TFhirOid read GetItemN write SetItemN; default;
End;
// a complex Uuid - has an Id attribute, and extensions.
// Used where a FHIR element is a Uuid, and extensions
TFhirUuid = class (TFhirUri)
private
public
constructor Create(value : String); overload;
destructor Destroy; override;
function Link : TFhirUuid; overload;
function Clone : TFhirUuid; overload;
function fhirType : string; override;
End;
TFhirUuidListEnumerator = class (TFslObject)
private
FIndex : integer;
FList : TFhirUuidList;
function GetCurrent : TFhirUuid;
public
constructor Create(list : TFhirUuidList);
destructor Destroy; override;
function MoveNext : boolean;
property Current : TFhirUuid read GetCurrent;
end;
TFhirUuidList = class (TFHIRObjectList)
private
function GetItemN(index : Integer) : TFhirUuid;
procedure SetItemN(index : Integer; value : TFhirUuid);
protected
function ItemClass : TFslObjectClass; override;
public
function Link : TFhirUuidList; overload;
function Clone : TFhirUuidList; overload;
function GetEnumerator : TFhirUuidListEnumerator;
// Add a FhirUuid to the end of the list.
function Append : TFhirUuid;
// Add an already existing FhirUuid to the end of the list.
procedure AddItem(value : TFhirUuid); overload;
// Add an already existing FhirUuid to the end of the list.
procedure AddItem(value : String); overload;
// See if an item is already in the list. returns -1 if not in the list
function IndexOf(value : TFhirUuid) : Integer;
// Insert FhirUuid before the designated index (0 = first item)
function Insert(index : Integer) : TFhirUuid;
// Insert an existing FhirUuid before the designated index (0 = first item)
procedure InsertItem(index : Integer; value : TFhirUuid);
// Get the iIndexth FhirUuid. (0 = first item)
procedure SetItemByIndex(index : Integer; value : TFhirUuid);
// The number of items in the collection
function Item(index : Integer) : TFhirUuid;
// The number of items in the collection
function Count : Integer; overload;
// Remove the indexth item. The first item is index 0.
procedure Remove(index : Integer);
// Remove All Items from the list
procedure ClearItems;
property FhirUuids[index : Integer] : TFhirUuid read GetItemN write SetItemN; default;
End;
// a complex Url - has an Id attribute, and extensions.
// Used where a FHIR element is a Url, and extensions
TFhirUrl = class (TFhirUri)
private
public
constructor Create(value : String); overload;
destructor Destroy; override;
function Link : TFhirUrl; overload;
function Clone : TFhirUrl; overload;
function fhirType : string; override;
End;
TFhirUrlListEnumerator = class (TFslObject)
private
FIndex : integer;
FList : TFhirUrlList;
function GetCurrent : TFhirUrl;
public
constructor Create(list : TFhirUrlList);
destructor Destroy; override;
function MoveNext : boolean;
property Current : TFhirUrl read GetCurrent;
end;
TFhirUrlList = class (TFHIRObjectList)
private
function GetItemN(index : Integer) : TFhirUrl;
procedure SetItemN(index : Integer; value : TFhirUrl);
protected
function ItemClass : TFslObjectClass; override;
public
function Link : TFhirUrlList; overload;
function Clone : TFhirUrlList; overload;
function GetEnumerator : TFhirUrlListEnumerator;
// Add a FhirUrl to the end of the list.
function Append : TFhirUrl;
// Add an already existing FhirUrl to the end of the list.
procedure AddItem(value : TFhirUrl); overload;
// Add an already existing FhirUrl to the end of the list.
procedure AddItem(value : String); overload;
// See if an item is already in the list. returns -1 if not in the list
function IndexOf(value : TFhirUrl) : Integer;
// Insert FhirUrl before the designated index (0 = first item)
function Insert(index : Integer) : TFhirUrl;
// Insert an existing FhirUrl before the designated index (0 = first item)
procedure InsertItem(index : Integer; value : TFhirUrl);
// Get the iIndexth FhirUrl. (0 = first item)
procedure SetItemByIndex(index : Integer; value : TFhirUrl);
// The number of items in the collection
function Item(index : Integer) : TFhirUrl;
// The number of items in the collection
function Count : Integer; overload;
// Remove the indexth item. The first item is index 0.
procedure Remove(index : Integer);
// Remove All Items from the list
procedure ClearItems;
property FhirUrls[index : Integer] : TFhirUrl read GetItemN write SetItemN; default;
End;
// a complex Markdown - has an Id attribute, and extensions.
// Used where a FHIR element is a Markdown, and extensions
TFhirMarkdown = class (TFhirString)
private
public
constructor Create(value : String); overload;
destructor Destroy; override;
function Link : TFhirMarkdown; overload;
function Clone : TFhirMarkdown; overload;
function fhirType : string; override;
End;
TFhirMarkdownListEnumerator = class (TFslObject)
private
FIndex : integer;
FList : TFhirMarkdownList;
function GetCurrent : TFhirMarkdown;
public
constructor Create(list : TFhirMarkdownList);
destructor Destroy; override;
function MoveNext : boolean;
property Current : TFhirMarkdown read GetCurrent;
end;
TFhirMarkdownList = class (TFHIRObjectList)
private
function GetItemN(index : Integer) : TFhirMarkdown;
procedure SetItemN(index : Integer; value : TFhirMarkdown);
protected
function ItemClass : TFslObjectClass; override;
public
function Link : TFhirMarkdownList; overload;
function Clone : TFhirMarkdownList; overload;
function GetEnumerator : TFhirMarkdownListEnumerator;
// Add a FhirMarkdown to the end of the list.
function Append : TFhirMarkdown;
// Add an already existing FhirMarkdown to the end of the list.
procedure AddItem(value : TFhirMarkdown); overload;
// Add an already existing FhirMarkdown to the end of the list.
procedure AddItem(value : String); overload;
// See if an item is already in the list. returns -1 if not in the list
function IndexOf(value : TFhirMarkdown) : Integer;
// Insert FhirMarkdown before the designated index (0 = first item)
function Insert(index : Integer) : TFhirMarkdown;
// Insert an existing FhirMarkdown before the designated index (0 = first item)
procedure InsertItem(index : Integer; value : TFhirMarkdown);
// Get the iIndexth FhirMarkdown. (0 = first item)
procedure SetItemByIndex(index : Integer; value : TFhirMarkdown);
// The number of items in the collection
function Item(index : Integer) : TFhirMarkdown;
// The number of items in the collection
function Count : Integer; overload;
// Remove the indexth item. The first item is index 0.
procedure Remove(index : Integer);
// Remove All Items from the list
procedure ClearItems;
property FhirMarkdowns[index : Integer] : TFhirMarkdown read GetItemN write SetItemN; default;
End;
// a complex UnsignedInt - has an Id attribute, and extensions.
// Used where a FHIR element is a UnsignedInt, and extensions
TFhirUnsignedInt = class (TFhirInteger)
private
public
constructor Create(value : String); overload;
destructor Destroy; override;
function Link : TFhirUnsignedInt; overload;
function Clone : TFhirUnsignedInt; overload;
function fhirType : string; override;
End;
TFhirUnsignedIntListEnumerator = class (TFslObject)
private
FIndex : integer;
FList : TFhirUnsignedIntList;
function GetCurrent : TFhirUnsignedInt;
public
constructor Create(list : TFhirUnsignedIntList);
destructor Destroy; override;
function MoveNext : boolean;
property Current : TFhirUnsignedInt read GetCurrent;
end;
TFhirUnsignedIntList = class (TFHIRObjectList)
private
function GetItemN(index : Integer) : TFhirUnsignedInt;
procedure SetItemN(index : Integer; value : TFhirUnsignedInt);
protected
function ItemClass : TFslObjectClass; override;
public
function Link : TFhirUnsignedIntList; overload;
function Clone : TFhirUnsignedIntList; overload;
function GetEnumerator : TFhirUnsignedIntListEnumerator;
// Add a FhirUnsignedInt to the end of the list.
function Append : TFhirUnsignedInt;
// Add an already existing FhirUnsignedInt to the end of the list.
procedure AddItem(value : TFhirUnsignedInt); overload;
// Add an already existing FhirUnsignedInt to the end of the list.
procedure AddItem(value : String); overload;
// See if an item is already in the list. returns -1 if not in the list
function IndexOf(value : TFhirUnsignedInt) : Integer;
// Insert FhirUnsignedInt before the designated index (0 = first item)
function Insert(index : Integer) : TFhirUnsignedInt;
// Insert an existing FhirUnsignedInt before the designated index (0 = first item)
procedure InsertItem(index : Integer; value : TFhirUnsignedInt);
// Get the iIndexth FhirUnsignedInt. (0 = first item)
procedure SetItemByIndex(index : Integer; value : TFhirUnsignedInt);
// The number of items in the collection
function Item(index : Integer) : TFhirUnsignedInt;
// The number of items in the collection
function Count : Integer; overload;
// Remove the indexth item. The first item is index 0.
procedure Remove(index : Integer);
// Remove All Items from the list
procedure ClearItems;
property FhirUnsignedInts[index : Integer] : TFhirUnsignedInt read GetItemN write SetItemN; default;
End;
// a complex Id - has an Id attribute, and extensions.
// Used where a FHIR element is a Id, and extensions
TFhirId = class (TFhirString)
private
public
constructor Create(value : String); overload;
destructor Destroy; override;
function Link : TFhirId; overload;
function Clone : TFhirId; overload;
function fhirType : string; override;
End;
TFhirIdListEnumerator = class (TFslObject)
private
FIndex : integer;
FList : TFhirIdList;
function GetCurrent : TFhirId;
public
constructor Create(list : TFhirIdList);
destructor Destroy; override;
function MoveNext : boolean;
property Current : TFhirId read GetCurrent;
end;
TFhirIdList = class (TFHIRObjectList)
private
function GetItemN(index : Integer) : TFhirId;
procedure SetItemN(index : Integer; value : TFhirId);
protected
function ItemClass : TFslObjectClass; override;
public
function Link : TFhirIdList; overload;
function Clone : TFhirIdList; overload;
function GetEnumerator : TFhirIdListEnumerator;
// Add a FhirId to the end of the list.
function Append : TFhirId;
// Add an already existing FhirId to the end of the list.
procedure AddItem(value : TFhirId); overload;
// Add an already existing FhirId to the end of the list.
procedure AddItem(value : String); overload;
// See if an item is already in the list. returns -1 if not in the list
function IndexOf(value : TFhirId) : Integer;
// Insert FhirId before the designated index (0 = first item)
function Insert(index : Integer) : TFhirId;
// Insert an existing FhirId before the designated index (0 = first item)
procedure InsertItem(index : Integer; value : TFhirId);
// Get the iIndexth FhirId. (0 = first item)
procedure SetItemByIndex(index : Integer; value : TFhirId);
// The number of items in the collection
function Item(index : Integer) : TFhirId;
// The number of items in the collection
function Count : Integer; overload;
// Remove the indexth item. The first item is index 0.
procedure Remove(index : Integer);
// Remove All Items from the list
procedure ClearItems;
property FhirIds[index : Integer] : TFhirId read GetItemN write SetItemN; default;
End;
// a complex PositiveInt - has an Id attribute, and extensions.
// Used where a FHIR element is a PositiveInt, and extensions
TFhirPositiveInt = class (TFhirInteger)
private
public
constructor Create(value : String); overload;
destructor Destroy; override;
function Link : TFhirPositiveInt; overload;
function Clone : TFhirPositiveInt; overload;
function fhirType : string; override;
End;
TFhirPositiveIntListEnumerator = class (TFslObject)
private
FIndex : integer;
FList : TFhirPositiveIntList;
function GetCurrent : TFhirPositiveInt;
public
constructor Create(list : TFhirPositiveIntList);
destructor Destroy; override;
function MoveNext : boolean;
property Current : TFhirPositiveInt read GetCurrent;
end;
TFhirPositiveIntList = class (TFHIRObjectList)
private
function GetItemN(index : Integer) : TFhirPositiveInt;
procedure SetItemN(index : Integer; value : TFhirPositiveInt);
protected
function ItemClass : TFslObjectClass; override;
public
function Link : TFhirPositiveIntList; overload;
function Clone : TFhirPositiveIntList; overload;
function GetEnumerator : TFhirPositiveIntListEnumerator;
// Add a FhirPositiveInt to the end of the list.
function Append : TFhirPositiveInt;
// Add an already existing FhirPositiveInt to the end of the list.
procedure AddItem(value : TFhirPositiveInt); overload;
// Add an already existing FhirPositiveInt to the end of the list.
procedure AddItem(value : String); overload;
// See if an item is already in the list. returns -1 if not in the list
function IndexOf(value : TFhirPositiveInt) : Integer;
// Insert FhirPositiveInt before the designated index (0 = first item)
function Insert(index : Integer) : TFhirPositiveInt;
// Insert an existing FhirPositiveInt before the designated index (0 = first item)
procedure InsertItem(index : Integer; value : TFhirPositiveInt);
// Get the iIndexth FhirPositiveInt. (0 = first item)
procedure SetItemByIndex(index : Integer; value : TFhirPositiveInt);
// The number of items in the collection
function Item(index : Integer) : TFhirPositiveInt;
// The number of items in the collection
function Count : Integer; overload;
// Remove the indexth item. The first item is index 0.
procedure Remove(index : Integer);
// Remove All Items from the list
procedure ClearItems;
property FhirPositiveInts[index : Integer] : TFhirPositiveInt read GetItemN write SetItemN; default;
End;
// a complex Integer64 - has an Id attribute, and extensions.
// Used where a FHIR element is a Integer64, and extensions
TFhirInteger64 = class (TFhirInteger)
private
public
constructor Create(value : String); overload;
destructor Destroy; override;
function Link : TFhirInteger64; overload;
function Clone : TFhirInteger64; overload;
function fhirType : string; override;
End;
TFhirInteger64ListEnumerator = class (TFslObject)
private
FIndex : integer;
FList : TFhirInteger64List;
function GetCurrent : TFhirInteger64;
public
constructor Create(list : TFhirInteger64List);
destructor Destroy; override;
function MoveNext : boolean;
property Current : TFhirInteger64 read GetCurrent;
end;
TFhirInteger64List = class (TFHIRObjectList)
private
function GetItemN(index : Integer) : TFhirInteger64;
procedure SetItemN(index : Integer; value : TFhirInteger64);
protected
function ItemClass : TFslObjectClass; override;
public
function Link : TFhirInteger64List; overload;
function Clone : TFhirInteger64List; overload;
function GetEnumerator : TFhirInteger64ListEnumerator;
// Add a FhirInteger64 to the end of the list.
function Append : TFhirInteger64;
// Add an already existing FhirInteger64 to the end of the list.
procedure AddItem(value : TFhirInteger64); overload;
// Add an already existing FhirInteger64 to the end of the list.
procedure AddItem(value : String); overload;
// See if an item is already in the list. returns -1 if not in the list
function IndexOf(value : TFhirInteger64) : Integer;
// Insert FhirInteger64 before the designated index (0 = first item)
function Insert(index : Integer) : TFhirInteger64;
// Insert an existing FhirInteger64 before the designated index (0 = first item)
procedure InsertItem(index : Integer; value : TFhirInteger64);
// Get the iIndexth FhirInteger64. (0 = first item)
procedure SetItemByIndex(index : Integer; value : TFhirInteger64);
// The number of items in the collection
function Item(index : Integer) : TFhirInteger64;
// The number of items in the collection
function Count : Integer; overload;
// Remove the indexth item. The first item is index 0.
procedure Remove(index : Integer);
// Remove All Items from the list
procedure ClearItems;
property FhirInteger64s[index : Integer] : TFhirInteger64 read GetItemN write SetItemN; default;
End;
{{type.concrete.intf}}
function asEnum(systems, values: array of String; obj : TFHIRObject) : TFhirEnum;
function asDate(obj : TFHIRObject) : TFhirDate;
function asDateTime(obj : TFHIRObject) : TFhirDateTime;
function asString(obj : TFHIRObject) : TFhirString;
function asInteger(obj : TFHIRObject) : TFhirInteger;
function asUri(obj : TFHIRObject) : TFhirUri;
function asInstant(obj : TFHIRObject) : TFhirInstant;
function asXhtml(obj : TFHIRObject) : TFhirXhtml;
function asBoolean(obj : TFHIRObject) : TFhirBoolean;
function asBase64Binary(obj : TFHIRObject) : TFhirBase64Binary;
function asTime(obj : TFHIRObject) : TFhirTime;
function asDecimal(obj : TFHIRObject) : TFhirDecimal;
function asCode(obj : TFHIRObject) : TFhirCode;
function asCanonical(obj : TFHIRObject) : TFhirCanonical;
function asOid(obj : TFHIRObject) : TFhirOid;
function asUuid(obj : TFHIRObject) : TFhirUuid;
function asUrl(obj : TFHIRObject) : TFhirUrl;
function asMarkdown(obj : TFHIRObject) : TFhirMarkdown;
function asUnsignedInt(obj : TFHIRObject) : TFhirUnsignedInt;
function asId(obj : TFHIRObject) : TFhirId;
function asPositiveInt(obj : TFHIRObject) : TFhirPositiveInt;
function asInteger64(obj : TFHIRObject) : TFhirInteger64;
implementation
uses
FHIR.R5.ElementModel, FHIR.R5.Utilities;
{{type.abstract.impl}}
{ TFhirEnum }
Constructor TFhirEnum.Create(system : String; value : String);
begin
Create;
FSystem := system;
FValue := value;
end;
destructor TFhirEnum.Destroy;
begin
inherited;
end;
function TFhirEnum.fhirType : string;
begin
result := 'code';
end;
function TFHIREnum.isEnum : boolean;
begin
result := true;
end;
procedure TFhirEnum.GetChildrenByName(child_name : string; list : TFHIRSelectionList);
begin
inherited;
if child_name = 'value' then
list.add(self.link, 'value', TFHIRObjectText.create(value));
end;
procedure TFhirEnum.ListProperties(oList: TFHIRPropertyList; bInheritedProperties, bPrimitiveValues: Boolean);
begin
inherited;
if (bPrimitiveValues) then
oList.add(TFHIRProperty.create(self, 'value', 'enum', false, nil, FValue));
end;
procedure TFhirEnum.Assign(oSource : TFslObject);
begin
inherited;
FValue := TFhirEnum(oSource).Value;
end;
function TFhirEnum.AsStringValue : string;
begin
result := FValue;
end;
procedure TFhirEnum.SetStringValue(value : string);
begin
FValue := value;
end;
function TFhirEnum.equals(other : TObject) : boolean;
var
o : TFhirEnum;
begin
if (not inherited equals(other)) then
result := false
else if (not (other is TFhirEnum)) then
result := false
else
begin
o := TFhirEnum(other);
result := o.value = value;
end;
end;
function TFhirEnum.isEmpty : boolean;
begin
result := inherited isEmpty and (FValue = '');
end;
function TFhirEnum.Link : TFhirEnum;
begin
result := TFhirEnum(inherited Link);
end;
function TFhirEnum.Clone : TFhirEnum;
begin
result := TFhirEnum(inherited Clone);
end;
procedure TFhirEnum.setValue(value : String);
begin
FValue := value;
end;
{ TFhirEnumListEnumerator }
Constructor TFhirEnumListEnumerator.Create(list : TFhirEnumList);
begin
inherited Create;
FIndex := -1;
FList := list;
end;
destructor TFhirEnumListEnumerator.Destroy;
begin
FList.Free;
inherited;
end;
function TFhirEnumListEnumerator.MoveNext : boolean;
begin
inc(FIndex);
Result := FIndex < FList.count;
end;
function TFhirEnumListEnumerator.GetCurrent : TFhirEnum;
begin
Result := FList[FIndex];
end;
{ TFhirEnumList }
procedure TFhirEnumList.AddItem(value: TFhirEnum);
begin
assert(value.ClassName = 'TFhirEnum', 'Attempt to add an item of type '+value.ClassName+' to a List of TFhirEnum');
add(value);
end;
constructor TFhirEnumList.Create(Systems, Codes : Array Of String);
var
i : integer;
begin
inherited create;
SetLength(FSystems, length(systems));
SetLength(FCodes, length(codes));
for i := 0 to length(systems) - 1 do
begin
FSystems[i] := systems[i];
FCodes[i] := codes[i];
end;
end;
procedure TFhirEnumList.AddItem(value: String);
begin
add(TFhirEnum.create(FSystems[StringArrayIndexOf(FCodes, value)], value));
end;
function TFhirEnumList.Append: TFhirEnum;
begin
result := TFhirEnum.create;
try
add(result.Link);
finally
result.free;
end;
end;
procedure TFhirEnumList.ClearItems;
begin
Clear;
end;
function TFhirEnumList.GetEnumerator : TFhirEnumListEnumerator;
begin
result := TFhirEnumListEnumerator.Create(self.link);
end;
function TFhirEnumList.Clone: TFhirEnumList;
begin
result := TFhirEnumList(inherited Clone);
end;
function TFhirEnumList.Count: Integer;
begin
result := Inherited Count;
end;
function TFhirEnumList.GetItemN(index: Integer): TFhirEnum;
begin
result := TFhirEnum(ObjectByIndex[index]);
end;
function TFhirEnumList.ItemClass: TFslObjectClass;
begin
result := TFhirEnum;
end;
function TFhirEnumList.IndexOf(value: TFhirEnum): Integer;
begin
result := IndexByReference(value);
end;
function TFhirEnumList.Insert(index: Integer): TFhirEnum;
begin
result := TFhirEnum.create;
try
inherited insert(index, result.Link);
finally
result.free;
end;
end;
procedure TFhirEnumList.InsertItem(index: Integer; value: TFhirEnum);
begin
assert(value is TFhirEnum);
Inherited Insert(index, value);
end;
function TFhirEnumList.Item(index: Integer): TFhirEnum;
begin
result := TFhirEnum(ObjectByIndex[index]);
end;
function TFhirEnumList.Link: TFhirEnumList;
begin
result := TFhirEnumList(inherited Link);
end;
procedure TFhirEnumList.Remove(index: Integer);
begin
DeleteByIndex(index);
end;
procedure TFhirEnumList.SetItemByIndex(index: Integer; value: TFhirEnum);
begin
assert(value is TFhirEnum);
FhirEnums[index] := value;
end;
procedure TFhirEnumList.SetItemN(index: Integer; value: TFhirEnum);
begin
assert(value is TFhirEnum);
ObjectByIndex[index] := value;
end;
{ TFhirDate }
Constructor TFhirDate.Create(value : TFslDateTime);
begin
Create;
FValue := value.fixPrecision(dtpDay);
end;
destructor TFhirDate.Destroy;
begin
inherited;
end;
function TFhirDate.fhirType : string;
begin
result := 'date';
end;
function TFhirDate.dateValue : TFslDateTime;
begin
result := FValue;
end;
procedure TFhirDate.GetChildrenByName(child_name : string; list : TFHIRSelectionList);
begin
inherited;
if child_name = 'value' then
list.add(self.link, 'value', TFHIRObjectText.create(value));
end;
procedure TFhirDate.ListProperties(oList: TFHIRPropertyList; bInheritedProperties, bPrimitiveValues: Boolean);
begin
inherited;
if (bPrimitiveValues) then
if (FValue.notNull) then
oList.add(TFHIRProperty.create(self, 'value', 'date', false, nil, FValue.ToString));
end;
procedure TFhirDate.Assign(oSource : TFslObject);
begin
inherited;
FValue := TFhirDate(oSource).Value;
end;
function TFhirDate.AsStringValue : string;
begin
if (FValue.null) then
result := ''
else
result := FValue.toXml;
end;
procedure TFhirDate.SetStringValue(value : string);
begin
if (value = '') then
FValue := TFslDateTime.makeNull
else
FValue := TFslDateTime.fromXml(value);
end;
function TFhirDate.equals(other : TObject) : boolean;
var
o : TFhirDate;
begin
if (not inherited equals(other)) then
result := false
else if (not (other is TFhirDate)) then
result := false
else
begin
o := TFhirDate(other);
result := o.value.equal(value);
end;
end;
function TFhirDate.isEmpty : boolean;
begin
result := inherited isEmpty and (FValue.null);
end;
function TFhirDate.Link : TFhirDate;
begin
result := TFhirDate(inherited Link);
end;
function TFhirDate.Clone : TFhirDate;
begin
result := TFhirDate(inherited Clone);
end;
procedure TFhirDate.setValue(value : TFslDateTime);
begin
FValue := value;
end;
{ TFhirDateListEnumerator }
Constructor TFhirDateListEnumerator.Create(list : TFhirDateList);
begin
inherited Create;
FIndex := -1;
FList := list;
end;
destructor TFhirDateListEnumerator.Destroy;
begin
FList.Free;
inherited;
end;
function TFhirDateListEnumerator.MoveNext : boolean;
begin
inc(FIndex);
Result := FIndex < FList.count;
end;
function TFhirDateListEnumerator.GetCurrent : TFhirDate;
begin
Result := FList[FIndex];
end;
{ TFhirDateList }
procedure TFhirDateList.AddItem(value: TFhirDate);
begin
assert(value.ClassName = 'TFhirDate', 'Attempt to add an item of type '+value.ClassName+' to a List of TFhirDate');
add(value);
end;
procedure TFhirDateList.AddItem(value: TFslDateTime);
begin
add(TFhirDate.create(value));
end;
function TFhirDateList.Append: TFhirDate;
begin
result := TFhirDate.create;
try
add(result.Link);
finally
result.free;
end;
end;
procedure TFhirDateList.ClearItems;
begin
Clear;
end;
function TFhirDateList.GetEnumerator : TFhirDateListEnumerator;
begin
result := TFhirDateListEnumerator.Create(self.link);
end;
function TFhirDateList.Clone: TFhirDateList;
begin
result := TFhirDateList(inherited Clone);
end;
function TFhirDateList.Count: Integer;
begin
result := Inherited Count;
end;
function TFhirDateList.GetItemN(index: Integer): TFhirDate;
begin
result := TFhirDate(ObjectByIndex[index]);
end;
function TFhirDateList.ItemClass: TFslObjectClass;
begin
result := TFhirDate;
end;
function TFhirDateList.IndexOf(value: TFhirDate): Integer;
begin
result := IndexByReference(value);
end;
function TFhirDateList.Insert(index: Integer): TFhirDate;
begin
result := TFhirDate.create;
try
inherited insert(index, result.Link);
finally
result.free;
end;
end;
procedure TFhirDateList.InsertItem(index: Integer; value: TFhirDate);
begin
assert(value is TFhirDate);
Inherited Insert(index, value);
end;
function TFhirDateList.Item(index: Integer): TFhirDate;
begin
result := TFhirDate(ObjectByIndex[index]);
end;
function TFhirDateList.Link: TFhirDateList;
begin
result := TFhirDateList(inherited Link);
end;
procedure TFhirDateList.Remove(index: Integer);
begin
DeleteByIndex(index);
end;
procedure TFhirDateList.SetItemByIndex(index: Integer; value: TFhirDate);
begin
assert(value is TFhirDate);
FhirDates[index] := value;
end;
procedure TFhirDateList.SetItemN(index: Integer; value: TFhirDate);
begin
assert(value is TFhirDate);
ObjectByIndex[index] := value;
end;
{ TFhirDateTime }
Constructor TFhirDateTime.Create(value : TFslDateTime);
begin
Create;
FValue := value;
end;
destructor TFhirDateTime.Destroy;
begin
inherited;
end;
function TFhirDateTime.fhirType : string;
begin
result := 'dateTime';
end;
function TFhirDateTime.dateValue : TFslDateTime;
begin
result := FValue;
end;
procedure TFhirDateTime.GetChildrenByName(child_name : string; list : TFHIRSelectionList);
begin
inherited;
if child_name = 'value' then
list.add(self.link, 'value', TFHIRObjectText.create(value));
end;
procedure TFhirDateTime.ListProperties(oList: TFHIRPropertyList; bInheritedProperties, bPrimitiveValues: Boolean);
begin
inherited;
if (bPrimitiveValues) then
if (FValue.notNull) then
oList.add(TFHIRProperty.create(self, 'value', 'dateTime', false, nil, FValue.ToString));
end;
procedure TFhirDateTime.Assign(oSource : TFslObject);
begin
inherited;
FValue := TFhirDateTime(oSource).Value;
end;
function TFhirDateTime.AsStringValue : string;
begin
if (FValue.null) then
result := ''
else
result := FValue.toXml;
end;
procedure TFhirDateTime.SetStringValue(value : string);
begin
if (value = '') then
FValue := TFslDateTime.makeNull
else
FValue := TFslDateTime.fromXml(value);
end;
function TFhirDateTime.equals(other : TObject) : boolean;
var
o : TFhirDateTime;
begin
if (not inherited equals(other)) then
result := false
else if (not (other is TFhirDateTime)) then
result := false
else
begin
o := TFhirDateTime(other);
result := o.value.equal(value);
end;
end;
function TFhirDateTime.isEmpty : boolean;
begin
result := inherited isEmpty and (FValue.null);
end;
function TFhirDateTime.Link : TFhirDateTime;
begin
result := TFhirDateTime(inherited Link);
end;
function TFhirDateTime.Clone : TFhirDateTime;
begin
result := TFhirDateTime(inherited Clone);
end;
procedure TFhirDateTime.setValue(value : TFslDateTime);
begin
FValue := value;
end;
{ TFhirDateTimeListEnumerator }
Constructor TFhirDateTimeListEnumerator.Create(list : TFhirDateTimeList);
begin
inherited Create;
FIndex := -1;
FList := list;
end;
destructor TFhirDateTimeListEnumerator.Destroy;
begin
FList.Free;
inherited;
end;
function TFhirDateTimeListEnumerator.MoveNext : boolean;
begin
inc(FIndex);
Result := FIndex < FList.count;
end;
function TFhirDateTimeListEnumerator.GetCurrent : TFhirDateTime;
begin
Result := FList[FIndex];
end;
{ TFhirDateTimeList }
procedure TFhirDateTimeList.AddItem(value: TFhirDateTime);
begin
assert(value.ClassName = 'TFhirDateTime', 'Attempt to add an item of type '+value.ClassName+' to a List of TFhirDateTime');
add(value);
end;
procedure TFhirDateTimeList.AddItem(value: TFslDateTime);
begin
add(TFhirDateTime.create(value));
end;
function TFhirDateTimeList.Append: TFhirDateTime;
begin
result := TFhirDateTime.create;
try
add(result.Link);
finally
result.free;
end;
end;
procedure TFhirDateTimeList.ClearItems;
begin
Clear;
end;
function TFhirDateTimeList.GetEnumerator : TFhirDateTimeListEnumerator;
begin
result := TFhirDateTimeListEnumerator.Create(self.link);
end;
function TFhirDateTimeList.Clone: TFhirDateTimeList;
begin
result := TFhirDateTimeList(inherited Clone);
end;
function TFhirDateTimeList.Count: Integer;
begin
result := Inherited Count;
end;
function TFhirDateTimeList.GetItemN(index: Integer): TFhirDateTime;
begin
result := TFhirDateTime(ObjectByIndex[index]);
end;
function TFhirDateTimeList.ItemClass: TFslObjectClass;
begin
result := TFhirDateTime;
end;
function TFhirDateTimeList.IndexOf(value: TFhirDateTime): Integer;
begin
result := IndexByReference(value);
end;
function TFhirDateTimeList.Insert(index: Integer): TFhirDateTime;
begin
result := TFhirDateTime.create;
try
inherited insert(index, result.Link);
finally
result.free;
end;
end;
procedure TFhirDateTimeList.InsertItem(index: Integer; value: TFhirDateTime);
begin
assert(value is TFhirDateTime);
Inherited Insert(index, value);
end;
function TFhirDateTimeList.Item(index: Integer): TFhirDateTime;
begin
result := TFhirDateTime(ObjectByIndex[index]);
end;
function TFhirDateTimeList.Link: TFhirDateTimeList;
begin
result := TFhirDateTimeList(inherited Link);
end;
procedure TFhirDateTimeList.Remove(index: Integer);
begin
DeleteByIndex(index);
end;
procedure TFhirDateTimeList.SetItemByIndex(index: Integer; value: TFhirDateTime);
begin
assert(value is TFhirDateTime);
FhirDateTimes[index] := value;
end;
procedure TFhirDateTimeList.SetItemN(index: Integer; value: TFhirDateTime);
begin
assert(value is TFhirDateTime);
ObjectByIndex[index] := value;
end;
{ TFhirString }
Constructor TFhirString.Create(value : String);
begin
Create;
FValue := value;
end;
destructor TFhirString.Destroy;
begin
inherited;
end;
function TFhirString.fhirType : string;
begin
result := 'string';
end;
procedure TFhirString.GetChildrenByName(child_name : string; list : TFHIRSelectionList);
begin
inherited;
if child_name = 'value' then
list.add(self.link, 'value', TFHIRObjectText.create(value));
end;
procedure TFhirString.ListProperties(oList: TFHIRPropertyList; bInheritedProperties, bPrimitiveValues: Boolean);
begin
inherited;
if (bPrimitiveValues) then
oList.add(TFHIRProperty.create(self, 'value', 'string', false, nil, FValue));
end;
procedure TFhirString.Assign(oSource : TFslObject);
begin
inherited;
FValue := TFhirString(oSource).Value;
end;
function TFhirString.AsStringValue : string;
begin
result := FValue;
end;
procedure TFhirString.SetStringValue(value : string);
begin
FValue := value;
end;
function TFhirString.equals(other : TObject) : boolean;
var
o : TFhirString;
begin
if (not inherited equals(other)) then
result := false
else if (not (other is TFhirString)) then
result := false
else
begin
o := TFhirString(other);
result := o.value = value;
end;
end;
function TFhirString.isEmpty : boolean;
begin
result := inherited isEmpty and (FValue = '');
end;
function TFhirString.Link : TFhirString;
begin
result := TFhirString(inherited Link);
end;
function TFhirString.Clone : TFhirString;
begin
result := TFhirString(inherited Clone);
end;
procedure TFhirString.setValue(value : String);
begin
FValue := value;
end;
{ TFhirStringListEnumerator }
Constructor TFhirStringListEnumerator.Create(list : TFhirStringList);
begin
inherited Create;
FIndex := -1;
FList := list;
end;
destructor TFhirStringListEnumerator.Destroy;
begin
FList.Free;
inherited;
end;
function TFhirStringListEnumerator.MoveNext : boolean;
begin
inc(FIndex);
Result := FIndex < FList.count;
end;
function TFhirStringListEnumerator.GetCurrent : TFhirString;
begin
Result := FList[FIndex];
end;
{ TFhirStringList }
procedure TFhirStringList.AddItem(value: TFhirString);
begin
assert(value.ClassName = 'TFhirString', 'Attempt to add an item of type '+value.ClassName+' to a List of TFhirString');
add(value);
end;
procedure TFhirStringList.AddItem(value: String);
begin
add(TFhirString.create(value));
end;
function TFhirStringList.Append: TFhirString;
begin
result := TFhirString.create;
try
add(result.Link);
finally
result.free;
end;
end;
procedure TFhirStringList.ClearItems;
begin
Clear;
end;
function TFhirStringList.GetEnumerator : TFhirStringListEnumerator;
begin
result := TFhirStringListEnumerator.Create(self.link);
end;
function TFhirStringList.Clone: TFhirStringList;
begin
result := TFhirStringList(inherited Clone);
end;
function TFhirStringList.Count: Integer;
begin
result := Inherited Count;
end;
function TFhirStringList.GetItemN(index: Integer): TFhirString;
begin
result := TFhirString(ObjectByIndex[index]);
end;
function TFhirStringList.ItemClass: TFslObjectClass;
begin
result := TFhirString;
end;
function TFhirStringList.IndexOf(value: TFhirString): Integer;
begin
result := IndexByReference(value);
end;
function TFhirStringList.Insert(index: Integer): TFhirString;
begin
result := TFhirString.create;
try
inherited insert(index, result.Link);
finally
result.free;
end;
end;
procedure TFhirStringList.InsertItem(index: Integer; value: TFhirString);
begin
assert(value is TFhirString);
Inherited Insert(index, value);
end;
function TFhirStringList.Item(index: Integer): TFhirString;
begin
result := TFhirString(ObjectByIndex[index]);
end;
function TFhirStringList.Link: TFhirStringList;
begin
result := TFhirStringList(inherited Link);
end;
procedure TFhirStringList.Remove(index: Integer);
begin
DeleteByIndex(index);
end;
procedure TFhirStringList.SetItemByIndex(index: Integer; value: TFhirString);
begin
assert(value is TFhirString);
FhirStrings[index] := value;
end;
procedure TFhirStringList.SetItemN(index: Integer; value: TFhirString);
begin
assert(value is TFhirString);
ObjectByIndex[index] := value;
end;
{ TFhirInteger }
Constructor TFhirInteger.Create(value : String);
begin
Create;
FValue := value;
end;
destructor TFhirInteger.Destroy;
begin
inherited;
end;
function TFhirInteger.fhirType : string;
begin
result := 'integer';
end;
procedure TFhirInteger.GetChildrenByName(child_name : string; list : TFHIRSelectionList);
begin
inherited;
if child_name = 'value' then
list.add(self.link, 'value', TFHIRObjectText.create(value));
end;
procedure TFhirInteger.ListProperties(oList: TFHIRPropertyList; bInheritedProperties, bPrimitiveValues: Boolean);
begin
inherited;
if (bPrimitiveValues) then
oList.add(TFHIRProperty.create(self, 'value', 'integer', false, nil, FValue));
end;
procedure TFhirInteger.Assign(oSource : TFslObject);
begin
inherited;
FValue := TFhirInteger(oSource).Value;
end;
function TFhirInteger.AsStringValue : string;
begin
result := FValue;
end;
procedure TFhirInteger.SetStringValue(value : string);
begin
FValue := value;
end;
function TFhirInteger.equals(other : TObject) : boolean;
var
o : TFhirInteger;
begin
if (not inherited equals(other)) then
result := false
else if (not (other is TFhirInteger)) then
result := false
else
begin
o := TFhirInteger(other);
result := o.value = value;
end;
end;
function TFhirInteger.isEmpty : boolean;
begin
result := inherited isEmpty and (FValue = '');
end;
function TFhirInteger.Link : TFhirInteger;
begin
result := TFhirInteger(inherited Link);
end;
function TFhirInteger.Clone : TFhirInteger;
begin
result := TFhirInteger(inherited Clone);
end;
procedure TFhirInteger.setValue(value : String);
begin
FValue := value;
end;
{ TFhirIntegerListEnumerator }
Constructor TFhirIntegerListEnumerator.Create(list : TFhirIntegerList);
begin
inherited Create;
FIndex := -1;
FList := list;
end;
destructor TFhirIntegerListEnumerator.Destroy;
begin
FList.Free;
inherited;
end;
function TFhirIntegerListEnumerator.MoveNext : boolean;
begin
inc(FIndex);
Result := FIndex < FList.count;
end;
function TFhirIntegerListEnumerator.GetCurrent : TFhirInteger;
begin
Result := FList[FIndex];
end;
{ TFhirIntegerList }
procedure TFhirIntegerList.AddItem(value: TFhirInteger);
begin
assert(value.ClassName = 'TFhirInteger', 'Attempt to add an item of type '+value.ClassName+' to a List of TFhirInteger');
add(value);
end;
procedure TFhirIntegerList.AddItem(value: String);
begin
add(TFhirInteger.create(value));
end;
function TFhirIntegerList.Append: TFhirInteger;
begin
result := TFhirInteger.create;
try
add(result.Link);
finally
result.free;
end;
end;
procedure TFhirIntegerList.ClearItems;
begin
Clear;
end;
function TFhirIntegerList.GetEnumerator : TFhirIntegerListEnumerator;
begin
result := TFhirIntegerListEnumerator.Create(self.link);
end;
function TFhirIntegerList.Clone: TFhirIntegerList;
begin
result := TFhirIntegerList(inherited Clone);
end;
function TFhirIntegerList.Count: Integer;
begin
result := Inherited Count;
end;
function TFhirIntegerList.GetItemN(index: Integer): TFhirInteger;
begin
result := TFhirInteger(ObjectByIndex[index]);
end;
function TFhirIntegerList.ItemClass: TFslObjectClass;
begin
result := TFhirInteger;
end;
function TFhirIntegerList.IndexOf(value: TFhirInteger): Integer;
begin
result := IndexByReference(value);
end;
function TFhirIntegerList.Insert(index: Integer): TFhirInteger;
begin
result := TFhirInteger.create;
try
inherited insert(index, result.Link);
finally
result.free;
end;
end;
procedure TFhirIntegerList.InsertItem(index: Integer; value: TFhirInteger);
begin
assert(value is TFhirInteger);
Inherited Insert(index, value);
end;
function TFhirIntegerList.Item(index: Integer): TFhirInteger;
begin
result := TFhirInteger(ObjectByIndex[index]);
end;
function TFhirIntegerList.Link: TFhirIntegerList;
begin
result := TFhirIntegerList(inherited Link);
end;
procedure TFhirIntegerList.Remove(index: Integer);
begin
DeleteByIndex(index);
end;
procedure TFhirIntegerList.SetItemByIndex(index: Integer; value: TFhirInteger);
begin
assert(value is TFhirInteger);
FhirIntegers[index] := value;
end;
procedure TFhirIntegerList.SetItemN(index: Integer; value: TFhirInteger);
begin
assert(value is TFhirInteger);
ObjectByIndex[index] := value;
end;
{ TFhirUri }
Constructor TFhirUri.Create(value : String);
begin
Create;
FValue := value;
end;
destructor TFhirUri.Destroy;
begin
inherited;
end;
function TFhirUri.fhirType : string;
begin
result := 'uri';
end;
procedure TFhirUri.GetChildrenByName(child_name : string; list : TFHIRSelectionList);
begin
inherited;
if child_name = 'value' then
list.add(self.link, 'value', TFHIRObjectText.create(value));
end;
procedure TFhirUri.ListProperties(oList: TFHIRPropertyList; bInheritedProperties, bPrimitiveValues: Boolean);
begin
inherited;
if (bPrimitiveValues) then
oList.add(TFHIRProperty.create(self, 'value', 'uri', false, nil, FValue));
end;
procedure TFhirUri.Assign(oSource : TFslObject);
begin
inherited;
FValue := TFhirUri(oSource).Value;
end;
function TFhirUri.AsStringValue : string;
begin
result := FValue;
end;
procedure TFhirUri.SetStringValue(value : string);
begin
FValue := value;
end;
function TFhirUri.equals(other : TObject) : boolean;
var
o : TFhirUri;
begin
if (not inherited equals(other)) then
result := false
else if (not (other is TFhirUri)) then
result := false
else
begin
o := TFhirUri(other);
result := o.value = value;
end;
end;
function TFhirUri.isEmpty : boolean;
begin
result := inherited isEmpty and (FValue = '');
end;
function TFhirUri.Link : TFhirUri;
begin
result := TFhirUri(inherited Link);
end;
function TFhirUri.Clone : TFhirUri;
begin
result := TFhirUri(inherited Clone);
end;
procedure TFhirUri.setValue(value : String);
begin
FValue := value;
end;
{ TFhirUriListEnumerator }
Constructor TFhirUriListEnumerator.Create(list : TFhirUriList);
begin
inherited Create;
FIndex := -1;
FList := list;
end;
destructor TFhirUriListEnumerator.Destroy;
begin
FList.Free;
inherited;
end;
function TFhirUriListEnumerator.MoveNext : boolean;
begin
inc(FIndex);
Result := FIndex < FList.count;
end;
function TFhirUriListEnumerator.GetCurrent : TFhirUri;
begin
Result := FList[FIndex];
end;
{ TFhirUriList }
procedure TFhirUriList.AddItem(value: TFhirUri);
begin
assert(value.ClassName = 'TFhirUri', 'Attempt to add an item of type '+value.ClassName+' to a List of TFhirUri');
add(value);
end;
procedure TFhirUriList.AddItem(value: String);
begin
add(TFhirUri.create(value));
end;
function TFhirUriList.Append: TFhirUri;
begin
result := TFhirUri.create;
try
add(result.Link);
finally
result.free;
end;
end;
procedure TFhirUriList.ClearItems;
begin
Clear;
end;
function TFhirUriList.GetEnumerator : TFhirUriListEnumerator;
begin
result := TFhirUriListEnumerator.Create(self.link);
end;
function TFhirUriList.Clone: TFhirUriList;
begin
result := TFhirUriList(inherited Clone);
end;
function TFhirUriList.Count: Integer;
begin
result := Inherited Count;
end;
function TFhirUriList.GetItemN(index: Integer): TFhirUri;
begin
result := TFhirUri(ObjectByIndex[index]);
end;
function TFhirUriList.ItemClass: TFslObjectClass;
begin
result := TFhirUri;
end;
function TFhirUriList.IndexOf(value: TFhirUri): Integer;
begin
result := IndexByReference(value);
end;
function TFhirUriList.Insert(index: Integer): TFhirUri;
begin
result := TFhirUri.create;
try
inherited insert(index, result.Link);
finally
result.free;
end;
end;
procedure TFhirUriList.InsertItem(index: Integer; value: TFhirUri);
begin
assert(value is TFhirUri);
Inherited Insert(index, value);
end;
function TFhirUriList.Item(index: Integer): TFhirUri;
begin
result := TFhirUri(ObjectByIndex[index]);
end;
function TFhirUriList.Link: TFhirUriList;
begin
result := TFhirUriList(inherited Link);
end;
procedure TFhirUriList.Remove(index: Integer);
begin
DeleteByIndex(index);
end;
procedure TFhirUriList.SetItemByIndex(index: Integer; value: TFhirUri);
begin
assert(value is TFhirUri);
FhirUris[index] := value;
end;
procedure TFhirUriList.SetItemN(index: Integer; value: TFhirUri);
begin
assert(value is TFhirUri);
ObjectByIndex[index] := value;
end;
{ TFhirInstant }
Constructor TFhirInstant.Create(value : TFslDateTime);
begin
Create;
FValue := value;
end;
destructor TFhirInstant.Destroy;
begin
inherited;
end;
function TFhirInstant.fhirType : string;
begin
result := 'instant';
end;
function TFhirInstant.dateValue : TFslDateTime;
begin
result := FValue;
end;
procedure TFhirInstant.GetChildrenByName(child_name : string; list : TFHIRSelectionList);
begin
inherited;
if child_name = 'value' then
list.add(self.link, 'value', TFHIRObjectText.create(value));
end;
procedure TFhirInstant.ListProperties(oList: TFHIRPropertyList; bInheritedProperties, bPrimitiveValues: Boolean);
begin
inherited;
if (bPrimitiveValues) then
if (FValue.notNull) then
oList.add(TFHIRProperty.create(self, 'value', 'instant', false, nil, FValue.ToString));
end;
procedure TFhirInstant.Assign(oSource : TFslObject);
begin
inherited;
FValue := TFhirInstant(oSource).Value;
end;
function TFhirInstant.AsStringValue : string;
begin
if (FValue.null) then
result := ''
else
result := FValue.toXml;
end;
procedure TFhirInstant.SetStringValue(value : string);
begin
if (value = '') then
FValue := TFslDateTime.makeNull
else
FValue := TFslDateTime.fromXml(value);
end;
function TFhirInstant.equals(other : TObject) : boolean;
var
o : TFhirInstant;
begin
if (not inherited equals(other)) then
result := false
else if (not (other is TFhirInstant)) then
result := false
else
begin
o := TFhirInstant(other);
result := o.value.equal(value);
end;
end;
function TFhirInstant.isEmpty : boolean;
begin
result := inherited isEmpty and (FValue.null);
end;
function TFhirInstant.Link : TFhirInstant;
begin
result := TFhirInstant(inherited Link);
end;
function TFhirInstant.Clone : TFhirInstant;
begin
result := TFhirInstant(inherited Clone);
end;
procedure TFhirInstant.setValue(value : TFslDateTime);
begin
FValue := value;
end;
{ TFhirInstantListEnumerator }
Constructor TFhirInstantListEnumerator.Create(list : TFhirInstantList);
begin
inherited Create;
FIndex := -1;
FList := list;
end;
destructor TFhirInstantListEnumerator.Destroy;
begin
FList.Free;
inherited;
end;
function TFhirInstantListEnumerator.MoveNext : boolean;
begin
inc(FIndex);
Result := FIndex < FList.count;
end;
function TFhirInstantListEnumerator.GetCurrent : TFhirInstant;
begin
Result := FList[FIndex];
end;
{ TFhirInstantList }
procedure TFhirInstantList.AddItem(value: TFhirInstant);
begin
assert(value.ClassName = 'TFhirInstant', 'Attempt to add an item of type '+value.ClassName+' to a List of TFhirInstant');
add(value);
end;
procedure TFhirInstantList.AddItem(value: TFslDateTime);
begin
add(TFhirInstant.create(value));
end;
function TFhirInstantList.Append: TFhirInstant;
begin
result := TFhirInstant.create;
try
add(result.Link);
finally
result.free;
end;
end;
procedure TFhirInstantList.ClearItems;
begin
Clear;
end;
function TFhirInstantList.GetEnumerator : TFhirInstantListEnumerator;
begin
result := TFhirInstantListEnumerator.Create(self.link);
end;
function TFhirInstantList.Clone: TFhirInstantList;
begin
result := TFhirInstantList(inherited Clone);
end;
function TFhirInstantList.Count: Integer;
begin
result := Inherited Count;
end;
function TFhirInstantList.GetItemN(index: Integer): TFhirInstant;
begin
result := TFhirInstant(ObjectByIndex[index]);
end;
function TFhirInstantList.ItemClass: TFslObjectClass;
begin
result := TFhirInstant;
end;
function TFhirInstantList.IndexOf(value: TFhirInstant): Integer;
begin
result := IndexByReference(value);
end;
function TFhirInstantList.Insert(index: Integer): TFhirInstant;
begin
result := TFhirInstant.create;
try
inherited insert(index, result.Link);
finally
result.free;
end;
end;
procedure TFhirInstantList.InsertItem(index: Integer; value: TFhirInstant);
begin
assert(value is TFhirInstant);
Inherited Insert(index, value);
end;
function TFhirInstantList.Item(index: Integer): TFhirInstant;
begin
result := TFhirInstant(ObjectByIndex[index]);
end;
function TFhirInstantList.Link: TFhirInstantList;
begin
result := TFhirInstantList(inherited Link);
end;
procedure TFhirInstantList.Remove(index: Integer);
begin
DeleteByIndex(index);
end;
procedure TFhirInstantList.SetItemByIndex(index: Integer; value: TFhirInstant);
begin
assert(value is TFhirInstant);
FhirInstants[index] := value;
end;
procedure TFhirInstantList.SetItemN(index: Integer; value: TFhirInstant);
begin
assert(value is TFhirInstant);
ObjectByIndex[index] := value;
end;
{ TFhirXhtml }
Constructor TFhirXhtml.Create(value : String);
begin
Create;
FValue := value;
end;
destructor TFhirXhtml.Destroy;
begin
inherited;
end;
function TFhirXhtml.fhirType : string;
begin
result := 'xhtml';
end;
procedure TFhirXhtml.GetChildrenByName(child_name : string; list : TFHIRSelectionList);
begin
inherited;
if child_name = 'value' then
list.add(self.link, 'value', TFHIRObjectText.create(value));
end;
procedure TFhirXhtml.ListProperties(oList: TFHIRPropertyList; bInheritedProperties, bPrimitiveValues: Boolean);
begin
inherited;
if (bPrimitiveValues) then
oList.add(TFHIRProperty.create(self, 'value', 'xhtml', false, nil, FValue));
end;
procedure TFhirXhtml.Assign(oSource : TFslObject);
begin
inherited;
FValue := TFhirXhtml(oSource).Value;
end;
function TFhirXhtml.AsStringValue : string;
begin
result := FValue;
end;
procedure TFhirXhtml.SetStringValue(value : string);
begin
FValue := value;
end;
function TFhirXhtml.equals(other : TObject) : boolean;
var
o : TFhirXhtml;
begin
if (not inherited equals(other)) then
result := false
else if (not (other is TFhirXhtml)) then
result := false
else
begin
o := TFhirXhtml(other);
result := o.value = value;
end;
end;
function TFhirXhtml.isEmpty : boolean;
begin
result := inherited isEmpty and (FValue = '');
end;
function TFhirXhtml.Link : TFhirXhtml;
begin
result := TFhirXhtml(inherited Link);
end;
function TFhirXhtml.Clone : TFhirXhtml;
begin
result := TFhirXhtml(inherited Clone);
end;
procedure TFhirXhtml.setValue(value : String);
begin
FValue := value;
end;
{ TFhirXhtmlListEnumerator }
Constructor TFhirXhtmlListEnumerator.Create(list : TFhirXhtmlList);
begin
inherited Create;
FIndex := -1;
FList := list;
end;
destructor TFhirXhtmlListEnumerator.Destroy;
begin
FList.Free;
inherited;
end;
function TFhirXhtmlListEnumerator.MoveNext : boolean;
begin
inc(FIndex);
Result := FIndex < FList.count;
end;
function TFhirXhtmlListEnumerator.GetCurrent : TFhirXhtml;
begin
Result := FList[FIndex];
end;
{ TFhirXhtmlList }
procedure TFhirXhtmlList.AddItem(value: TFhirXhtml);
begin
assert(value.ClassName = 'TFhirXhtml', 'Attempt to add an item of type '+value.ClassName+' to a List of TFhirXhtml');
add(value);
end;
procedure TFhirXhtmlList.AddItem(value: String);
begin
add(TFhirXhtml.create(value));
end;
function TFhirXhtmlList.Append: TFhirXhtml;
begin
result := TFhirXhtml.create;
try
add(result.Link);
finally
result.free;
end;
end;
procedure TFhirXhtmlList.ClearItems;
begin
Clear;
end;
function TFhirXhtmlList.GetEnumerator : TFhirXhtmlListEnumerator;
begin
result := TFhirXhtmlListEnumerator.Create(self.link);
end;
function TFhirXhtmlList.Clone: TFhirXhtmlList;
begin
result := TFhirXhtmlList(inherited Clone);
end;
function TFhirXhtmlList.Count: Integer;
begin
result := Inherited Count;
end;
function TFhirXhtmlList.GetItemN(index: Integer): TFhirXhtml;
begin
result := TFhirXhtml(ObjectByIndex[index]);
end;
function TFhirXhtmlList.ItemClass: TFslObjectClass;
begin
result := TFhirXhtml;
end;
function TFhirXhtmlList.IndexOf(value: TFhirXhtml): Integer;
begin
result := IndexByReference(value);
end;
function TFhirXhtmlList.Insert(index: Integer): TFhirXhtml;
begin
result := TFhirXhtml.create;
try
inherited insert(index, result.Link);
finally
result.free;
end;
end;
procedure TFhirXhtmlList.InsertItem(index: Integer; value: TFhirXhtml);
begin
assert(value is TFhirXhtml);
Inherited Insert(index, value);
end;
function TFhirXhtmlList.Item(index: Integer): TFhirXhtml;
begin
result := TFhirXhtml(ObjectByIndex[index]);
end;
function TFhirXhtmlList.Link: TFhirXhtmlList;
begin
result := TFhirXhtmlList(inherited Link);
end;
procedure TFhirXhtmlList.Remove(index: Integer);
begin
DeleteByIndex(index);
end;
procedure TFhirXhtmlList.SetItemByIndex(index: Integer; value: TFhirXhtml);
begin
assert(value is TFhirXhtml);
FhirXhtmls[index] := value;
end;
procedure TFhirXhtmlList.SetItemN(index: Integer; value: TFhirXhtml);
begin
assert(value is TFhirXhtml);
ObjectByIndex[index] := value;
end;
{ TFhirBoolean }
Constructor TFhirBoolean.Create(value : Boolean);
begin
Create;
FValue := value;
end;
destructor TFhirBoolean.Destroy;
begin
inherited;
end;
function TFhirBoolean.fhirType : string;
begin
result := 'boolean';
end;
procedure TFhirBoolean.GetChildrenByName(child_name : string; list : TFHIRSelectionList);
begin
inherited;
if child_name = 'value' then
list.add(self.link, 'value', TFHIRObjectText.create(value));
end;
procedure TFhirBoolean.ListProperties(oList: TFHIRPropertyList; bInheritedProperties, bPrimitiveValues: Boolean);
begin
inherited;
if (bPrimitiveValues) then
oList.add(TFHIRProperty.create(self, 'value', 'boolean', false, nil, LCBooleanToString(FValue)));
end;
procedure TFhirBoolean.Assign(oSource : TFslObject);
begin
inherited;
FValue := TFhirBoolean(oSource).Value;
end;
function TFhirBoolean.AsStringValue : string;
begin
result := LCBooleanToString(FValue);
end;
procedure TFhirBoolean.SetStringValue(value : string);
begin
FValue := StringToBoolean(value);
end;
function TFhirBoolean.equals(other : TObject) : boolean;
var
o : TFhirBoolean;
begin
if (not inherited equals(other)) then
result := false
else if (not (other is TFhirBoolean)) then
result := false
else
begin
o := TFhirBoolean(other);
result := o.value = value;
end;
end;
function TFhirBoolean.isEmpty : boolean;
begin
result := false;
end;
function TFhirBoolean.Link : TFhirBoolean;
begin
result := TFhirBoolean(inherited Link);
end;
function TFhirBoolean.Clone : TFhirBoolean;
begin
result := TFhirBoolean(inherited Clone);
end;
procedure TFhirBoolean.setValue(value : Boolean);
begin
FValue := value;
end;
{ TFhirBooleanListEnumerator }
Constructor TFhirBooleanListEnumerator.Create(list : TFhirBooleanList);
begin
inherited Create;
FIndex := -1;
FList := list;
end;
destructor TFhirBooleanListEnumerator.Destroy;
begin
FList.Free;
inherited;
end;
function TFhirBooleanListEnumerator.MoveNext : boolean;
begin
inc(FIndex);
Result := FIndex < FList.count;
end;
function TFhirBooleanListEnumerator.GetCurrent : TFhirBoolean;
begin
Result := FList[FIndex];
end;
{ TFhirBooleanList }
procedure TFhirBooleanList.AddItem(value: TFhirBoolean);
begin
assert(value.ClassName = 'TFhirBoolean', 'Attempt to add an item of type '+value.ClassName+' to a List of TFhirBoolean');
add(value);
end;
procedure TFhirBooleanList.AddItem(value: Boolean);
begin
add(TFhirBoolean.create(value));
end;
function TFhirBooleanList.Append: TFhirBoolean;
begin
result := TFhirBoolean.create;
try
add(result.Link);
finally
result.free;
end;
end;
procedure TFhirBooleanList.ClearItems;
begin
Clear;
end;
function TFhirBooleanList.GetEnumerator : TFhirBooleanListEnumerator;
begin
result := TFhirBooleanListEnumerator.Create(self.link);
end;
function TFhirBooleanList.Clone: TFhirBooleanList;
begin
result := TFhirBooleanList(inherited Clone);
end;
function TFhirBooleanList.Count: Integer;
begin
result := Inherited Count;
end;
function TFhirBooleanList.GetItemN(index: Integer): TFhirBoolean;
begin
result := TFhirBoolean(ObjectByIndex[index]);
end;
function TFhirBooleanList.ItemClass: TFslObjectClass;
begin
result := TFhirBoolean;
end;
function TFhirBooleanList.IndexOf(value: TFhirBoolean): Integer;
begin
result := IndexByReference(value);
end;
function TFhirBooleanList.Insert(index: Integer): TFhirBoolean;
begin
result := TFhirBoolean.create;
try
inherited insert(index, result.Link);
finally
result.free;
end;
end;
procedure TFhirBooleanList.InsertItem(index: Integer; value: TFhirBoolean);
begin
assert(value is TFhirBoolean);
Inherited Insert(index, value);
end;
function TFhirBooleanList.Item(index: Integer): TFhirBoolean;
begin
result := TFhirBoolean(ObjectByIndex[index]);
end;
function TFhirBooleanList.Link: TFhirBooleanList;
begin
result := TFhirBooleanList(inherited Link);
end;
procedure TFhirBooleanList.Remove(index: Integer);
begin
DeleteByIndex(index);
end;
procedure TFhirBooleanList.SetItemByIndex(index: Integer; value: TFhirBoolean);
begin
assert(value is TFhirBoolean);
FhirBooleans[index] := value;
end;
procedure TFhirBooleanList.SetItemN(index: Integer; value: TFhirBoolean);
begin
assert(value is TFhirBoolean);
ObjectByIndex[index] := value;
end;
{ TFhirBase64Binary }
Constructor TFhirBase64Binary.Create(value : TBytes);
begin
Create;
FValue := value;
end;
destructor TFhirBase64Binary.Destroy;
begin
inherited;
end;
function TFhirBase64Binary.fhirType : string;
begin
result := 'base64Binary';
end;
procedure TFhirBase64Binary.GetChildrenByName(child_name : string; list : TFHIRSelectionList);
begin
inherited;
if child_name = 'value' then
list.add(self.link, 'value', TFHIRObjectText.create(value));
end;
procedure TFhirBase64Binary.ListProperties(oList: TFHIRPropertyList; bInheritedProperties, bPrimitiveValues: Boolean);
begin
inherited;
if (bPrimitiveValues) then
oList.add(TFHIRProperty.create(self, 'value', 'base64Binary', false, nil, FValue));
end;
procedure TFhirBase64Binary.Assign(oSource : TFslObject);
begin
inherited;
FValue := TFhirBase64Binary(oSource).Value;
end;
function TFhirBase64Binary.AsStringValue : string;
begin
if (length(FValue) = 0) then result := '' else result := string(EncodeBase64(FValue));
end;
procedure TFhirBase64Binary.SetStringValue(value : string);
begin
if (length(value) = 0) then SetLength(FValue, 0) else FValue := DecodeBase64(wideString(value));
end;
function TFhirBase64Binary.equals(other : TObject) : boolean;
var
o : TFhirBase64Binary;
begin
if (not inherited equals(other)) then
result := false
else if (not (other is TFhirBase64Binary)) then
result := false
else
begin
o := TFhirBase64Binary(other);
result := o.value = value;
end;
end;
function TFhirBase64Binary.isEmpty : boolean;
begin
result := inherited isEmpty and (length(FValue) = 0);
end;
function TFhirBase64Binary.Link : TFhirBase64Binary;
begin
result := TFhirBase64Binary(inherited Link);
end;
function TFhirBase64Binary.Clone : TFhirBase64Binary;
begin
result := TFhirBase64Binary(inherited Clone);
end;
procedure TFhirBase64Binary.setValue(value : TBytes);
begin
FValue := value;
end;
{ TFhirBase64BinaryListEnumerator }
Constructor TFhirBase64BinaryListEnumerator.Create(list : TFhirBase64BinaryList);
begin
inherited Create;
FIndex := -1;
FList := list;
end;
destructor TFhirBase64BinaryListEnumerator.Destroy;
begin
FList.Free;
inherited;
end;
function TFhirBase64BinaryListEnumerator.MoveNext : boolean;
begin
inc(FIndex);
Result := FIndex < FList.count;
end;
function TFhirBase64BinaryListEnumerator.GetCurrent : TFhirBase64Binary;
begin
Result := FList[FIndex];
end;
{ TFhirBase64BinaryList }
procedure TFhirBase64BinaryList.AddItem(value: TFhirBase64Binary);
begin
assert(value.ClassName = 'TFhirBase64Binary', 'Attempt to add an item of type '+value.ClassName+' to a List of TFhirBase64Binary');
add(value);
end;
procedure TFhirBase64BinaryList.AddItem(value: TBytes);
begin
add(TFhirBase64Binary.create(value));
end;
function TFhirBase64BinaryList.Append: TFhirBase64Binary;
begin
result := TFhirBase64Binary.create;
try
add(result.Link);
finally
result.free;
end;
end;
procedure TFhirBase64BinaryList.ClearItems;
begin
Clear;
end;
function TFhirBase64BinaryList.GetEnumerator : TFhirBase64BinaryListEnumerator;
begin
result := TFhirBase64BinaryListEnumerator.Create(self.link);
end;
function TFhirBase64BinaryList.Clone: TFhirBase64BinaryList;
begin
result := TFhirBase64BinaryList(inherited Clone);
end;
function TFhirBase64BinaryList.Count: Integer;
begin
result := Inherited Count;
end;
function TFhirBase64BinaryList.GetItemN(index: Integer): TFhirBase64Binary;
begin
result := TFhirBase64Binary(ObjectByIndex[index]);
end;
function TFhirBase64BinaryList.ItemClass: TFslObjectClass;
begin
result := TFhirBase64Binary;
end;
function TFhirBase64BinaryList.IndexOf(value: TFhirBase64Binary): Integer;
begin
result := IndexByReference(value);
end;
function TFhirBase64BinaryList.Insert(index: Integer): TFhirBase64Binary;
begin
result := TFhirBase64Binary.create;
try
inherited insert(index, result.Link);
finally
result.free;
end;
end;
procedure TFhirBase64BinaryList.InsertItem(index: Integer; value: TFhirBase64Binary);
begin
assert(value is TFhirBase64Binary);
Inherited Insert(index, value);
end;
function TFhirBase64BinaryList.Item(index: Integer): TFhirBase64Binary;
begin
result := TFhirBase64Binary(ObjectByIndex[index]);
end;
function TFhirBase64BinaryList.Link: TFhirBase64BinaryList;
begin
result := TFhirBase64BinaryList(inherited Link);
end;
procedure TFhirBase64BinaryList.Remove(index: Integer);
begin
DeleteByIndex(index);
end;
procedure TFhirBase64BinaryList.SetItemByIndex(index: Integer; value: TFhirBase64Binary);
begin
assert(value is TFhirBase64Binary);
FhirBase64Binaries[index] := value;
end;
procedure TFhirBase64BinaryList.SetItemN(index: Integer; value: TFhirBase64Binary);
begin
assert(value is TFhirBase64Binary);
ObjectByIndex[index] := value;
end;
{ TFhirTime }
Constructor TFhirTime.Create(value : String);
begin
Create;
FValue := value;
end;
destructor TFhirTime.Destroy;
begin
inherited;
end;
function TFhirTime.fhirType : string;
begin
result := 'time';
end;
procedure TFhirTime.GetChildrenByName(child_name : string; list : TFHIRSelectionList);
begin
inherited;
if child_name = 'value' then
list.add(self.link, 'value', TFHIRObjectText.create(value));
end;
procedure TFhirTime.ListProperties(oList: TFHIRPropertyList; bInheritedProperties, bPrimitiveValues: Boolean);
begin
inherited;
if (bPrimitiveValues) then
oList.add(TFHIRProperty.create(self, 'value', 'time', false, nil, FValue));
end;
procedure TFhirTime.Assign(oSource : TFslObject);
begin
inherited;
FValue := TFhirTime(oSource).Value;
end;
function TFhirTime.AsStringValue : string;
begin
result := FValue;
end;
procedure TFhirTime.SetStringValue(value : string);
begin
FValue := value;
end;
function TFhirTime.equals(other : TObject) : boolean;
var
o : TFhirTime;
begin
if (not inherited equals(other)) then
result := false
else if (not (other is TFhirTime)) then
result := false
else
begin
o := TFhirTime(other);
result := o.value = value;
end;
end;
function TFhirTime.isEmpty : boolean;
begin
result := inherited isEmpty and (FValue = '');
end;
function TFhirTime.Link : TFhirTime;
begin
result := TFhirTime(inherited Link);
end;
function TFhirTime.Clone : TFhirTime;
begin
result := TFhirTime(inherited Clone);
end;
procedure TFhirTime.setValue(value : String);
begin
FValue := value;
end;
{ TFhirTimeListEnumerator }
Constructor TFhirTimeListEnumerator.Create(list : TFhirTimeList);
begin
inherited Create;
FIndex := -1;
FList := list;
end;
destructor TFhirTimeListEnumerator.Destroy;
begin
FList.Free;
inherited;
end;
function TFhirTimeListEnumerator.MoveNext : boolean;
begin
inc(FIndex);
Result := FIndex < FList.count;
end;
function TFhirTimeListEnumerator.GetCurrent : TFhirTime;
begin
Result := FList[FIndex];
end;
{ TFhirTimeList }
procedure TFhirTimeList.AddItem(value: TFhirTime);
begin
assert(value.ClassName = 'TFhirTime', 'Attempt to add an item of type '+value.ClassName+' to a List of TFhirTime');
add(value);
end;
procedure TFhirTimeList.AddItem(value: String);
begin
add(TFhirTime.create(value));
end;
function TFhirTimeList.Append: TFhirTime;
begin
result := TFhirTime.create;
try
add(result.Link);
finally
result.free;
end;
end;
procedure TFhirTimeList.ClearItems;
begin
Clear;
end;
function TFhirTimeList.GetEnumerator : TFhirTimeListEnumerator;
begin
result := TFhirTimeListEnumerator.Create(self.link);
end;
function TFhirTimeList.Clone: TFhirTimeList;
begin
result := TFhirTimeList(inherited Clone);
end;
function TFhirTimeList.Count: Integer;
begin
result := Inherited Count;
end;
function TFhirTimeList.GetItemN(index: Integer): TFhirTime;
begin
result := TFhirTime(ObjectByIndex[index]);
end;
function TFhirTimeList.ItemClass: TFslObjectClass;
begin
result := TFhirTime;
end;
function TFhirTimeList.IndexOf(value: TFhirTime): Integer;
begin
result := IndexByReference(value);
end;
function TFhirTimeList.Insert(index: Integer): TFhirTime;
begin
result := TFhirTime.create;
try
inherited insert(index, result.Link);
finally
result.free;
end;
end;
procedure TFhirTimeList.InsertItem(index: Integer; value: TFhirTime);
begin
assert(value is TFhirTime);
Inherited Insert(index, value);
end;
function TFhirTimeList.Item(index: Integer): TFhirTime;
begin
result := TFhirTime(ObjectByIndex[index]);
end;
function TFhirTimeList.Link: TFhirTimeList;
begin
result := TFhirTimeList(inherited Link);
end;
procedure TFhirTimeList.Remove(index: Integer);
begin
DeleteByIndex(index);
end;
procedure TFhirTimeList.SetItemByIndex(index: Integer; value: TFhirTime);
begin
assert(value is TFhirTime);
FhirTimes[index] := value;
end;
procedure TFhirTimeList.SetItemN(index: Integer; value: TFhirTime);
begin
assert(value is TFhirTime);
ObjectByIndex[index] := value;
end;
{ TFhirDecimal }
Constructor TFhirDecimal.Create(value : String);
begin
Create;
FValue := value;
end;
destructor TFhirDecimal.Destroy;
begin
inherited;
end;
function TFhirDecimal.fhirType : string;
begin
result := 'decimal';
end;
procedure TFhirDecimal.GetChildrenByName(child_name : string; list : TFHIRSelectionList);
begin
inherited;
if child_name = 'value' then
list.add(self.link, 'value', TFHIRObjectText.create(value));
end;
procedure TFhirDecimal.ListProperties(oList: TFHIRPropertyList; bInheritedProperties, bPrimitiveValues: Boolean);
begin
inherited;
if (bPrimitiveValues) then
oList.add(TFHIRProperty.create(self, 'value', 'decimal', false, nil, FValue));
end;
procedure TFhirDecimal.Assign(oSource : TFslObject);
begin
inherited;
FValue := TFhirDecimal(oSource).Value;
end;
function TFhirDecimal.AsStringValue : string;
begin
result := FValue;
end;
procedure TFhirDecimal.SetStringValue(value : string);
begin
FValue := value;
end;
function TFhirDecimal.equals(other : TObject) : boolean;
var
o : TFhirDecimal;
begin
if (not inherited equals(other)) then
result := false
else if (not (other is TFhirDecimal)) then
result := false
else
begin
o := TFhirDecimal(other);
result := o.value = value;
end;
end;
function TFhirDecimal.isEmpty : boolean;
begin
result := inherited isEmpty and (FValue = '');
end;
function TFhirDecimal.Link : TFhirDecimal;
begin
result := TFhirDecimal(inherited Link);
end;
function TFhirDecimal.Clone : TFhirDecimal;
begin
result := TFhirDecimal(inherited Clone);
end;
procedure TFhirDecimal.setValue(value : String);
begin
FValue := value;
end;
{ TFhirDecimalListEnumerator }
Constructor TFhirDecimalListEnumerator.Create(list : TFhirDecimalList);
begin
inherited Create;
FIndex := -1;
FList := list;
end;
destructor TFhirDecimalListEnumerator.Destroy;
begin
FList.Free;
inherited;
end;
function TFhirDecimalListEnumerator.MoveNext : boolean;
begin
inc(FIndex);
Result := FIndex < FList.count;
end;
function TFhirDecimalListEnumerator.GetCurrent : TFhirDecimal;
begin
Result := FList[FIndex];
end;
{ TFhirDecimalList }
procedure TFhirDecimalList.AddItem(value: TFhirDecimal);
begin
assert(value.ClassName = 'TFhirDecimal', 'Attempt to add an item of type '+value.ClassName+' to a List of TFhirDecimal');
add(value);
end;
procedure TFhirDecimalList.AddItem(value: String);
begin
add(TFhirDecimal.create(value));
end;
function TFhirDecimalList.Append: TFhirDecimal;
begin
result := TFhirDecimal.create;
try
add(result.Link);
finally
result.free;
end;
end;
procedure TFhirDecimalList.ClearItems;
begin
Clear;
end;
function TFhirDecimalList.GetEnumerator : TFhirDecimalListEnumerator;
begin
result := TFhirDecimalListEnumerator.Create(self.link);
end;
function TFhirDecimalList.Clone: TFhirDecimalList;
begin
result := TFhirDecimalList(inherited Clone);
end;
function TFhirDecimalList.Count: Integer;
begin
result := Inherited Count;
end;
function TFhirDecimalList.GetItemN(index: Integer): TFhirDecimal;
begin
result := TFhirDecimal(ObjectByIndex[index]);
end;
function TFhirDecimalList.ItemClass: TFslObjectClass;
begin
result := TFhirDecimal;
end;
function TFhirDecimalList.IndexOf(value: TFhirDecimal): Integer;
begin
result := IndexByReference(value);
end;
function TFhirDecimalList.Insert(index: Integer): TFhirDecimal;
begin
result := TFhirDecimal.create;
try
inherited insert(index, result.Link);
finally
result.free;
end;
end;
procedure TFhirDecimalList.InsertItem(index: Integer; value: TFhirDecimal);
begin
assert(value is TFhirDecimal);
Inherited Insert(index, value);
end;
function TFhirDecimalList.Item(index: Integer): TFhirDecimal;
begin
result := TFhirDecimal(ObjectByIndex[index]);
end;
function TFhirDecimalList.Link: TFhirDecimalList;
begin
result := TFhirDecimalList(inherited Link);
end;
procedure TFhirDecimalList.Remove(index: Integer);
begin
DeleteByIndex(index);
end;
procedure TFhirDecimalList.SetItemByIndex(index: Integer; value: TFhirDecimal);
begin
assert(value is TFhirDecimal);
FhirDecimals[index] := value;
end;
procedure TFhirDecimalList.SetItemN(index: Integer; value: TFhirDecimal);
begin
assert(value is TFhirDecimal);
ObjectByIndex[index] := value;
end;
{ TFhirCode }
Constructor TFhirCode.Create(value : String);
begin
Create;
FValue := value;
end;
destructor TFhirCode.Destroy;
begin
inherited;
end;
function TFhirCode.fhirType : string;
begin
result := 'code';
end;
function TFhirCode.Link : TFhirCode;
begin
result := TFhirCode(inherited Link);
end;
function TFhirCode.Clone : TFhirCode;
begin
result := TFhirCode(inherited Clone);
end;
{ TFhirCodeListEnumerator }
Constructor TFhirCodeListEnumerator.Create(list : TFhirCodeList);
begin
inherited Create;
FIndex := -1;
FList := list;
end;
destructor TFhirCodeListEnumerator.Destroy;
begin
FList.Free;
inherited;
end;
function TFhirCodeListEnumerator.MoveNext : boolean;
begin
inc(FIndex);
Result := FIndex < FList.count;
end;
function TFhirCodeListEnumerator.GetCurrent : TFhirCode;
begin
Result := FList[FIndex];
end;
{ TFhirCodeList }
procedure TFhirCodeList.AddItem(value: TFhirCode);
begin
assert(value.ClassName = 'TFhirCode', 'Attempt to add an item of type '+value.ClassName+' to a List of TFhirCode');
add(value);
end;
procedure TFhirCodeList.AddItem(value: String);
begin
add(TFhirCode.create(value));
end;
function TFhirCodeList.Append: TFhirCode;
begin
result := TFhirCode.create;
try
add(result.Link);
finally
result.free;
end;
end;
procedure TFhirCodeList.ClearItems;
begin
Clear;
end;
function TFhirCodeList.GetEnumerator : TFhirCodeListEnumerator;
begin
result := TFhirCodeListEnumerator.Create(self.link);
end;
function TFhirCodeList.Clone: TFhirCodeList;
begin
result := TFhirCodeList(inherited Clone);
end;
function TFhirCodeList.Count: Integer;
begin
result := Inherited Count;
end;
function TFhirCodeList.GetItemN(index: Integer): TFhirCode;
begin
result := TFhirCode(ObjectByIndex[index]);
end;
function TFhirCodeList.ItemClass: TFslObjectClass;
begin
result := TFhirCode;
end;
function TFhirCodeList.IndexOf(value: TFhirCode): Integer;
begin
result := IndexByReference(value);
end;
function TFhirCodeList.Insert(index: Integer): TFhirCode;
begin
result := TFhirCode.create;
try
inherited insert(index, result.Link);
finally
result.free;
end;
end;
procedure TFhirCodeList.InsertItem(index: Integer; value: TFhirCode);
begin
assert(value is TFhirCode);
Inherited Insert(index, value);
end;
function TFhirCodeList.Item(index: Integer): TFhirCode;
begin
result := TFhirCode(ObjectByIndex[index]);
end;
function TFhirCodeList.Link: TFhirCodeList;
begin
result := TFhirCodeList(inherited Link);
end;
procedure TFhirCodeList.Remove(index: Integer);
begin
DeleteByIndex(index);
end;
procedure TFhirCodeList.SetItemByIndex(index: Integer; value: TFhirCode);
begin
assert(value is TFhirCode);
FhirCodes[index] := value;
end;
procedure TFhirCodeList.SetItemN(index: Integer; value: TFhirCode);
begin
assert(value is TFhirCode);
ObjectByIndex[index] := value;
end;
{ TFhirCanonical }
Constructor TFhirCanonical.Create(value : String);
begin
Create;
FValue := value;
end;
destructor TFhirCanonical.Destroy;
begin
inherited;
end;
function TFhirCanonical.fhirType : string;
begin
result := 'canonical';
end;
function TFhirCanonical.Link : TFhirCanonical;
begin
result := TFhirCanonical(inherited Link);
end;
function TFhirCanonical.Clone : TFhirCanonical;
begin
result := TFhirCanonical(inherited Clone);
end;
{ TFhirCanonicalListEnumerator }
Constructor TFhirCanonicalListEnumerator.Create(list : TFhirCanonicalList);
begin
inherited Create;
FIndex := -1;
FList := list;
end;
destructor TFhirCanonicalListEnumerator.Destroy;
begin
FList.Free;
inherited;
end;
function TFhirCanonicalListEnumerator.MoveNext : boolean;
begin
inc(FIndex);
Result := FIndex < FList.count;
end;
function TFhirCanonicalListEnumerator.GetCurrent : TFhirCanonical;
begin
Result := FList[FIndex];
end;
{ TFhirCanonicalList }
procedure TFhirCanonicalList.AddItem(value: TFhirCanonical);
begin
assert(value.ClassName = 'TFhirCanonical', 'Attempt to add an item of type '+value.ClassName+' to a List of TFhirCanonical');
add(value);
end;
procedure TFhirCanonicalList.AddItem(value: String);
begin
add(TFhirCanonical.create(value));
end;
function TFhirCanonicalList.Append: TFhirCanonical;
begin
result := TFhirCanonical.create;
try
add(result.Link);
finally
result.free;
end;
end;
procedure TFhirCanonicalList.ClearItems;
begin
Clear;
end;
function TFhirCanonicalList.GetEnumerator : TFhirCanonicalListEnumerator;
begin
result := TFhirCanonicalListEnumerator.Create(self.link);
end;
function TFhirCanonicalList.Clone: TFhirCanonicalList;
begin
result := TFhirCanonicalList(inherited Clone);
end;
function TFhirCanonicalList.Count: Integer;
begin
result := Inherited Count;
end;
function TFhirCanonicalList.GetItemN(index: Integer): TFhirCanonical;
begin
result := TFhirCanonical(ObjectByIndex[index]);
end;
function TFhirCanonicalList.ItemClass: TFslObjectClass;
begin
result := TFhirCanonical;
end;
function TFhirCanonicalList.IndexOf(value: TFhirCanonical): Integer;
begin
result := IndexByReference(value);
end;
function TFhirCanonicalList.Insert(index: Integer): TFhirCanonical;
begin
result := TFhirCanonical.create;
try
inherited insert(index, result.Link);
finally
result.free;
end;
end;
procedure TFhirCanonicalList.InsertItem(index: Integer; value: TFhirCanonical);
begin
assert(value is TFhirCanonical);
Inherited Insert(index, value);
end;
function TFhirCanonicalList.Item(index: Integer): TFhirCanonical;
begin
result := TFhirCanonical(ObjectByIndex[index]);
end;
function TFhirCanonicalList.Link: TFhirCanonicalList;
begin
result := TFhirCanonicalList(inherited Link);
end;
procedure TFhirCanonicalList.Remove(index: Integer);
begin
DeleteByIndex(index);
end;
procedure TFhirCanonicalList.SetItemByIndex(index: Integer; value: TFhirCanonical);
begin
assert(value is TFhirCanonical);
FhirCanonicals[index] := value;
end;
procedure TFhirCanonicalList.SetItemN(index: Integer; value: TFhirCanonical);
begin
assert(value is TFhirCanonical);
ObjectByIndex[index] := value;
end;
{ TFhirOid }
Constructor TFhirOid.Create(value : String);
begin
Create;
FValue := value;
end;
destructor TFhirOid.Destroy;
begin
inherited;
end;
function TFhirOid.fhirType : string;
begin
result := 'oid';
end;
function TFhirOid.Link : TFhirOid;
begin
result := TFhirOid(inherited Link);
end;
function TFhirOid.Clone : TFhirOid;
begin
result := TFhirOid(inherited Clone);
end;
{ TFhirOidListEnumerator }
Constructor TFhirOidListEnumerator.Create(list : TFhirOidList);
begin
inherited Create;
FIndex := -1;
FList := list;
end;
destructor TFhirOidListEnumerator.Destroy;
begin
FList.Free;
inherited;
end;
function TFhirOidListEnumerator.MoveNext : boolean;
begin
inc(FIndex);
Result := FIndex < FList.count;
end;
function TFhirOidListEnumerator.GetCurrent : TFhirOid;
begin
Result := FList[FIndex];
end;
{ TFhirOidList }
procedure TFhirOidList.AddItem(value: TFhirOid);
begin
assert(value.ClassName = 'TFhirOid', 'Attempt to add an item of type '+value.ClassName+' to a List of TFhirOid');
add(value);
end;
procedure TFhirOidList.AddItem(value: String);
begin
add(TFhirOid.create(value));
end;
function TFhirOidList.Append: TFhirOid;
begin
result := TFhirOid.create;
try
add(result.Link);
finally
result.free;
end;
end;
procedure TFhirOidList.ClearItems;
begin
Clear;
end;
function TFhirOidList.GetEnumerator : TFhirOidListEnumerator;
begin
result := TFhirOidListEnumerator.Create(self.link);
end;
function TFhirOidList.Clone: TFhirOidList;
begin
result := TFhirOidList(inherited Clone);
end;
function TFhirOidList.Count: Integer;
begin
result := Inherited Count;
end;
function TFhirOidList.GetItemN(index: Integer): TFhirOid;
begin
result := TFhirOid(ObjectByIndex[index]);
end;
function TFhirOidList.ItemClass: TFslObjectClass;
begin
result := TFhirOid;
end;
function TFhirOidList.IndexOf(value: TFhirOid): Integer;
begin
result := IndexByReference(value);
end;
function TFhirOidList.Insert(index: Integer): TFhirOid;
begin
result := TFhirOid.create;
try
inherited insert(index, result.Link);
finally
result.free;
end;
end;
procedure TFhirOidList.InsertItem(index: Integer; value: TFhirOid);
begin
assert(value is TFhirOid);
Inherited Insert(index, value);
end;
function TFhirOidList.Item(index: Integer): TFhirOid;
begin
result := TFhirOid(ObjectByIndex[index]);
end;
function TFhirOidList.Link: TFhirOidList;
begin
result := TFhirOidList(inherited Link);
end;
procedure TFhirOidList.Remove(index: Integer);
begin
DeleteByIndex(index);
end;
procedure TFhirOidList.SetItemByIndex(index: Integer; value: TFhirOid);
begin
assert(value is TFhirOid);
FhirOids[index] := value;
end;
procedure TFhirOidList.SetItemN(index: Integer; value: TFhirOid);
begin
assert(value is TFhirOid);
ObjectByIndex[index] := value;
end;
{ TFhirUuid }
Constructor TFhirUuid.Create(value : String);
begin
Create;
FValue := value;
end;
destructor TFhirUuid.Destroy;
begin
inherited;
end;
function TFhirUuid.fhirType : string;
begin
result := 'uuid';
end;
function TFhirUuid.Link : TFhirUuid;
begin
result := TFhirUuid(inherited Link);
end;
function TFhirUuid.Clone : TFhirUuid;
begin
result := TFhirUuid(inherited Clone);
end;
{ TFhirUuidListEnumerator }
Constructor TFhirUuidListEnumerator.Create(list : TFhirUuidList);
begin
inherited Create;
FIndex := -1;
FList := list;
end;
destructor TFhirUuidListEnumerator.Destroy;
begin
FList.Free;
inherited;
end;
function TFhirUuidListEnumerator.MoveNext : boolean;
begin
inc(FIndex);
Result := FIndex < FList.count;
end;
function TFhirUuidListEnumerator.GetCurrent : TFhirUuid;
begin
Result := FList[FIndex];
end;
{ TFhirUuidList }
procedure TFhirUuidList.AddItem(value: TFhirUuid);
begin
assert(value.ClassName = 'TFhirUuid', 'Attempt to add an item of type '+value.ClassName+' to a List of TFhirUuid');
add(value);
end;
procedure TFhirUuidList.AddItem(value: String);
begin
add(TFhirUuid.create(value));
end;
function TFhirUuidList.Append: TFhirUuid;
begin
result := TFhirUuid.create;
try
add(result.Link);
finally
result.free;
end;
end;
procedure TFhirUuidList.ClearItems;
begin
Clear;
end;
function TFhirUuidList.GetEnumerator : TFhirUuidListEnumerator;
begin
result := TFhirUuidListEnumerator.Create(self.link);
end;
function TFhirUuidList.Clone: TFhirUuidList;
begin
result := TFhirUuidList(inherited Clone);
end;
function TFhirUuidList.Count: Integer;
begin
result := Inherited Count;
end;
function TFhirUuidList.GetItemN(index: Integer): TFhirUuid;
begin
result := TFhirUuid(ObjectByIndex[index]);
end;
function TFhirUuidList.ItemClass: TFslObjectClass;
begin
result := TFhirUuid;
end;
function TFhirUuidList.IndexOf(value: TFhirUuid): Integer;
begin
result := IndexByReference(value);
end;
function TFhirUuidList.Insert(index: Integer): TFhirUuid;
begin
result := TFhirUuid.create;
try
inherited insert(index, result.Link);
finally
result.free;
end;
end;
procedure TFhirUuidList.InsertItem(index: Integer; value: TFhirUuid);
begin
assert(value is TFhirUuid);
Inherited Insert(index, value);
end;
function TFhirUuidList.Item(index: Integer): TFhirUuid;
begin
result := TFhirUuid(ObjectByIndex[index]);
end;
function TFhirUuidList.Link: TFhirUuidList;
begin
result := TFhirUuidList(inherited Link);
end;
procedure TFhirUuidList.Remove(index: Integer);
begin
DeleteByIndex(index);
end;
procedure TFhirUuidList.SetItemByIndex(index: Integer; value: TFhirUuid);
begin
assert(value is TFhirUuid);
FhirUuids[index] := value;
end;
procedure TFhirUuidList.SetItemN(index: Integer; value: TFhirUuid);
begin
assert(value is TFhirUuid);
ObjectByIndex[index] := value;
end;
{ TFhirUrl }
Constructor TFhirUrl.Create(value : String);
begin
Create;
FValue := value;
end;
destructor TFhirUrl.Destroy;
begin
inherited;
end;
function TFhirUrl.fhirType : string;
begin
result := 'url';
end;
function TFhirUrl.Link : TFhirUrl;
begin
result := TFhirUrl(inherited Link);
end;
function TFhirUrl.Clone : TFhirUrl;
begin
result := TFhirUrl(inherited Clone);
end;
{ TFhirUrlListEnumerator }
Constructor TFhirUrlListEnumerator.Create(list : TFhirUrlList);
begin
inherited Create;
FIndex := -1;
FList := list;
end;
destructor TFhirUrlListEnumerator.Destroy;
begin
FList.Free;
inherited;
end;
function TFhirUrlListEnumerator.MoveNext : boolean;
begin
inc(FIndex);
Result := FIndex < FList.count;
end;
function TFhirUrlListEnumerator.GetCurrent : TFhirUrl;
begin
Result := FList[FIndex];
end;
{ TFhirUrlList }
procedure TFhirUrlList.AddItem(value: TFhirUrl);
begin
assert(value.ClassName = 'TFhirUrl', 'Attempt to add an item of type '+value.ClassName+' to a List of TFhirUrl');
add(value);
end;
procedure TFhirUrlList.AddItem(value: String);
begin
add(TFhirUrl.create(value));
end;
function TFhirUrlList.Append: TFhirUrl;
begin
result := TFhirUrl.create;
try
add(result.Link);
finally
result.free;
end;
end;
procedure TFhirUrlList.ClearItems;
begin
Clear;
end;
function TFhirUrlList.GetEnumerator : TFhirUrlListEnumerator;
begin
result := TFhirUrlListEnumerator.Create(self.link);
end;
function TFhirUrlList.Clone: TFhirUrlList;
begin
result := TFhirUrlList(inherited Clone);
end;
function TFhirUrlList.Count: Integer;
begin
result := Inherited Count;
end;
function TFhirUrlList.GetItemN(index: Integer): TFhirUrl;
begin
result := TFhirUrl(ObjectByIndex[index]);
end;
function TFhirUrlList.ItemClass: TFslObjectClass;
begin
result := TFhirUrl;
end;
function TFhirUrlList.IndexOf(value: TFhirUrl): Integer;
begin
result := IndexByReference(value);
end;
function TFhirUrlList.Insert(index: Integer): TFhirUrl;
begin
result := TFhirUrl.create;
try
inherited insert(index, result.Link);
finally
result.free;
end;
end;
procedure TFhirUrlList.InsertItem(index: Integer; value: TFhirUrl);
begin
assert(value is TFhirUrl);
Inherited Insert(index, value);
end;
function TFhirUrlList.Item(index: Integer): TFhirUrl;
begin
result := TFhirUrl(ObjectByIndex[index]);
end;
function TFhirUrlList.Link: TFhirUrlList;
begin
result := TFhirUrlList(inherited Link);
end;
procedure TFhirUrlList.Remove(index: Integer);
begin
DeleteByIndex(index);
end;
procedure TFhirUrlList.SetItemByIndex(index: Integer; value: TFhirUrl);
begin
assert(value is TFhirUrl);
FhirUrls[index] := value;
end;
procedure TFhirUrlList.SetItemN(index: Integer; value: TFhirUrl);
begin
assert(value is TFhirUrl);
ObjectByIndex[index] := value;
end;
{ TFhirMarkdown }
Constructor TFhirMarkdown.Create(value : String);
begin
Create;
FValue := value;
end;
destructor TFhirMarkdown.Destroy;
begin
inherited;
end;
function TFhirMarkdown.fhirType : string;
begin
result := 'markdown';
end;
function TFhirMarkdown.Link : TFhirMarkdown;
begin
result := TFhirMarkdown(inherited Link);
end;
function TFhirMarkdown.Clone : TFhirMarkdown;
begin
result := TFhirMarkdown(inherited Clone);
end;
{ TFhirMarkdownListEnumerator }
Constructor TFhirMarkdownListEnumerator.Create(list : TFhirMarkdownList);
begin
inherited Create;
FIndex := -1;
FList := list;
end;
destructor TFhirMarkdownListEnumerator.Destroy;
begin
FList.Free;
inherited;
end;
function TFhirMarkdownListEnumerator.MoveNext : boolean;
begin
inc(FIndex);
Result := FIndex < FList.count;
end;
function TFhirMarkdownListEnumerator.GetCurrent : TFhirMarkdown;
begin
Result := FList[FIndex];
end;
{ TFhirMarkdownList }
procedure TFhirMarkdownList.AddItem(value: TFhirMarkdown);
begin
assert(value.ClassName = 'TFhirMarkdown', 'Attempt to add an item of type '+value.ClassName+' to a List of TFhirMarkdown');
add(value);
end;
procedure TFhirMarkdownList.AddItem(value: String);
begin
add(TFhirMarkdown.create(value));
end;
function TFhirMarkdownList.Append: TFhirMarkdown;
begin
result := TFhirMarkdown.create;
try
add(result.Link);
finally
result.free;
end;
end;
procedure TFhirMarkdownList.ClearItems;
begin
Clear;
end;
function TFhirMarkdownList.GetEnumerator : TFhirMarkdownListEnumerator;
begin
result := TFhirMarkdownListEnumerator.Create(self.link);
end;
function TFhirMarkdownList.Clone: TFhirMarkdownList;
begin
result := TFhirMarkdownList(inherited Clone);
end;
function TFhirMarkdownList.Count: Integer;
begin
result := Inherited Count;
end;
function TFhirMarkdownList.GetItemN(index: Integer): TFhirMarkdown;
begin
result := TFhirMarkdown(ObjectByIndex[index]);
end;
function TFhirMarkdownList.ItemClass: TFslObjectClass;
begin
result := TFhirMarkdown;
end;
function TFhirMarkdownList.IndexOf(value: TFhirMarkdown): Integer;
begin
result := IndexByReference(value);
end;
function TFhirMarkdownList.Insert(index: Integer): TFhirMarkdown;
begin
result := TFhirMarkdown.create;
try
inherited insert(index, result.Link);
finally
result.free;
end;
end;
procedure TFhirMarkdownList.InsertItem(index: Integer; value: TFhirMarkdown);
begin
assert(value is TFhirMarkdown);
Inherited Insert(index, value);
end;
function TFhirMarkdownList.Item(index: Integer): TFhirMarkdown;
begin
result := TFhirMarkdown(ObjectByIndex[index]);
end;
function TFhirMarkdownList.Link: TFhirMarkdownList;
begin
result := TFhirMarkdownList(inherited Link);
end;
procedure TFhirMarkdownList.Remove(index: Integer);
begin
DeleteByIndex(index);
end;
procedure TFhirMarkdownList.SetItemByIndex(index: Integer; value: TFhirMarkdown);
begin
assert(value is TFhirMarkdown);
FhirMarkdowns[index] := value;
end;
procedure TFhirMarkdownList.SetItemN(index: Integer; value: TFhirMarkdown);
begin
assert(value is TFhirMarkdown);
ObjectByIndex[index] := value;
end;
{ TFhirUnsignedInt }
Constructor TFhirUnsignedInt.Create(value : String);
begin
Create;
FValue := value;
end;
destructor TFhirUnsignedInt.Destroy;
begin
inherited;
end;
function TFhirUnsignedInt.fhirType : string;
begin
result := 'unsignedInt';
end;
function TFhirUnsignedInt.Link : TFhirUnsignedInt;
begin
result := TFhirUnsignedInt(inherited Link);
end;
function TFhirUnsignedInt.Clone : TFhirUnsignedInt;
begin
result := TFhirUnsignedInt(inherited Clone);
end;
{ TFhirUnsignedIntListEnumerator }
Constructor TFhirUnsignedIntListEnumerator.Create(list : TFhirUnsignedIntList);
begin
inherited Create;
FIndex := -1;
FList := list;
end;
destructor TFhirUnsignedIntListEnumerator.Destroy;
begin
FList.Free;
inherited;
end;
function TFhirUnsignedIntListEnumerator.MoveNext : boolean;
begin
inc(FIndex);
Result := FIndex < FList.count;
end;
function TFhirUnsignedIntListEnumerator.GetCurrent : TFhirUnsignedInt;
begin
Result := FList[FIndex];
end;
{ TFhirUnsignedIntList }
procedure TFhirUnsignedIntList.AddItem(value: TFhirUnsignedInt);
begin
assert(value.ClassName = 'TFhirUnsignedInt', 'Attempt to add an item of type '+value.ClassName+' to a List of TFhirUnsignedInt');
add(value);
end;
procedure TFhirUnsignedIntList.AddItem(value: String);
begin
add(TFhirUnsignedInt.create(value));
end;
function TFhirUnsignedIntList.Append: TFhirUnsignedInt;
begin
result := TFhirUnsignedInt.create;
try
add(result.Link);
finally
result.free;
end;
end;
procedure TFhirUnsignedIntList.ClearItems;
begin
Clear;
end;
function TFhirUnsignedIntList.GetEnumerator : TFhirUnsignedIntListEnumerator;
begin
result := TFhirUnsignedIntListEnumerator.Create(self.link);
end;
function TFhirUnsignedIntList.Clone: TFhirUnsignedIntList;
begin
result := TFhirUnsignedIntList(inherited Clone);
end;
function TFhirUnsignedIntList.Count: Integer;
begin
result := Inherited Count;
end;
function TFhirUnsignedIntList.GetItemN(index: Integer): TFhirUnsignedInt;
begin
result := TFhirUnsignedInt(ObjectByIndex[index]);
end;
function TFhirUnsignedIntList.ItemClass: TFslObjectClass;
begin
result := TFhirUnsignedInt;
end;
function TFhirUnsignedIntList.IndexOf(value: TFhirUnsignedInt): Integer;
begin
result := IndexByReference(value);
end;
function TFhirUnsignedIntList.Insert(index: Integer): TFhirUnsignedInt;
begin
result := TFhirUnsignedInt.create;
try
inherited insert(index, result.Link);
finally
result.free;
end;
end;
procedure TFhirUnsignedIntList.InsertItem(index: Integer; value: TFhirUnsignedInt);
begin
assert(value is TFhirUnsignedInt);
Inherited Insert(index, value);
end;
function TFhirUnsignedIntList.Item(index: Integer): TFhirUnsignedInt;
begin
result := TFhirUnsignedInt(ObjectByIndex[index]);
end;
function TFhirUnsignedIntList.Link: TFhirUnsignedIntList;
begin
result := TFhirUnsignedIntList(inherited Link);
end;
procedure TFhirUnsignedIntList.Remove(index: Integer);
begin
DeleteByIndex(index);
end;
procedure TFhirUnsignedIntList.SetItemByIndex(index: Integer; value: TFhirUnsignedInt);
begin
assert(value is TFhirUnsignedInt);
FhirUnsignedInts[index] := value;
end;
procedure TFhirUnsignedIntList.SetItemN(index: Integer; value: TFhirUnsignedInt);
begin
assert(value is TFhirUnsignedInt);
ObjectByIndex[index] := value;
end;
{ TFhirId }
Constructor TFhirId.Create(value : String);
begin
Create;
FValue := value;
end;
destructor TFhirId.Destroy;
begin
inherited;
end;
function TFhirId.fhirType : string;
begin
result := 'id';
end;
function TFhirId.Link : TFhirId;
begin
result := TFhirId(inherited Link);
end;
function TFhirId.Clone : TFhirId;
begin
result := TFhirId(inherited Clone);
end;
{ TFhirIdListEnumerator }
Constructor TFhirIdListEnumerator.Create(list : TFhirIdList);
begin
inherited Create;
FIndex := -1;
FList := list;
end;
destructor TFhirIdListEnumerator.Destroy;
begin
FList.Free;
inherited;
end;
function TFhirIdListEnumerator.MoveNext : boolean;
begin
inc(FIndex);
Result := FIndex < FList.count;
end;
function TFhirIdListEnumerator.GetCurrent : TFhirId;
begin
Result := FList[FIndex];
end;
{ TFhirIdList }
procedure TFhirIdList.AddItem(value: TFhirId);
begin
assert(value.ClassName = 'TFhirId', 'Attempt to add an item of type '+value.ClassName+' to a List of TFhirId');
add(value);
end;
procedure TFhirIdList.AddItem(value: String);
begin
add(TFhirId.create(value));
end;
function TFhirIdList.Append: TFhirId;
begin
result := TFhirId.create;
try
add(result.Link);
finally
result.free;
end;
end;
procedure TFhirIdList.ClearItems;
begin
Clear;
end;
function TFhirIdList.GetEnumerator : TFhirIdListEnumerator;
begin
result := TFhirIdListEnumerator.Create(self.link);
end;
function TFhirIdList.Clone: TFhirIdList;
begin
result := TFhirIdList(inherited Clone);
end;
function TFhirIdList.Count: Integer;
begin
result := Inherited Count;
end;
function TFhirIdList.GetItemN(index: Integer): TFhirId;
begin
result := TFhirId(ObjectByIndex[index]);
end;
function TFhirIdList.ItemClass: TFslObjectClass;
begin
result := TFhirId;
end;
function TFhirIdList.IndexOf(value: TFhirId): Integer;
begin
result := IndexByReference(value);
end;
function TFhirIdList.Insert(index: Integer): TFhirId;
begin
result := TFhirId.create;
try
inherited insert(index, result.Link);
finally
result.free;
end;
end;
procedure TFhirIdList.InsertItem(index: Integer; value: TFhirId);
begin
assert(value is TFhirId);
Inherited Insert(index, value);
end;
function TFhirIdList.Item(index: Integer): TFhirId;
begin
result := TFhirId(ObjectByIndex[index]);
end;
function TFhirIdList.Link: TFhirIdList;
begin
result := TFhirIdList(inherited Link);
end;
procedure TFhirIdList.Remove(index: Integer);
begin
DeleteByIndex(index);
end;
procedure TFhirIdList.SetItemByIndex(index: Integer; value: TFhirId);
begin
assert(value is TFhirId);
FhirIds[index] := value;
end;
procedure TFhirIdList.SetItemN(index: Integer; value: TFhirId);
begin
assert(value is TFhirId);
ObjectByIndex[index] := value;
end;
{ TFhirPositiveInt }
Constructor TFhirPositiveInt.Create(value : String);
begin
Create;
FValue := value;
end;
destructor TFhirPositiveInt.Destroy;
begin
inherited;
end;
function TFhirPositiveInt.fhirType : string;
begin
result := 'positiveInt';
end;
function TFhirPositiveInt.Link : TFhirPositiveInt;
begin
result := TFhirPositiveInt(inherited Link);
end;
function TFhirPositiveInt.Clone : TFhirPositiveInt;
begin
result := TFhirPositiveInt(inherited Clone);
end;
{ TFhirPositiveIntListEnumerator }
Constructor TFhirPositiveIntListEnumerator.Create(list : TFhirPositiveIntList);
begin
inherited Create;
FIndex := -1;
FList := list;
end;
destructor TFhirPositiveIntListEnumerator.Destroy;
begin
FList.Free;
inherited;
end;
function TFhirPositiveIntListEnumerator.MoveNext : boolean;
begin
inc(FIndex);
Result := FIndex < FList.count;
end;
function TFhirPositiveIntListEnumerator.GetCurrent : TFhirPositiveInt;
begin
Result := FList[FIndex];
end;
{ TFhirPositiveIntList }
procedure TFhirPositiveIntList.AddItem(value: TFhirPositiveInt);
begin
assert(value.ClassName = 'TFhirPositiveInt', 'Attempt to add an item of type '+value.ClassName+' to a List of TFhirPositiveInt');
add(value);
end;
procedure TFhirPositiveIntList.AddItem(value: String);
begin
add(TFhirPositiveInt.create(value));
end;
function TFhirPositiveIntList.Append: TFhirPositiveInt;
begin
result := TFhirPositiveInt.create;
try
add(result.Link);
finally
result.free;
end;
end;
procedure TFhirPositiveIntList.ClearItems;
begin
Clear;
end;
function TFhirPositiveIntList.GetEnumerator : TFhirPositiveIntListEnumerator;
begin
result := TFhirPositiveIntListEnumerator.Create(self.link);
end;
function TFhirPositiveIntList.Clone: TFhirPositiveIntList;
begin
result := TFhirPositiveIntList(inherited Clone);
end;
function TFhirPositiveIntList.Count: Integer;
begin
result := Inherited Count;
end;
function TFhirPositiveIntList.GetItemN(index: Integer): TFhirPositiveInt;
begin
result := TFhirPositiveInt(ObjectByIndex[index]);
end;
function TFhirPositiveIntList.ItemClass: TFslObjectClass;
begin
result := TFhirPositiveInt;
end;
function TFhirPositiveIntList.IndexOf(value: TFhirPositiveInt): Integer;
begin
result := IndexByReference(value);
end;
function TFhirPositiveIntList.Insert(index: Integer): TFhirPositiveInt;
begin
result := TFhirPositiveInt.create;
try
inherited insert(index, result.Link);
finally
result.free;
end;
end;
procedure TFhirPositiveIntList.InsertItem(index: Integer; value: TFhirPositiveInt);
begin
assert(value is TFhirPositiveInt);
Inherited Insert(index, value);
end;
function TFhirPositiveIntList.Item(index: Integer): TFhirPositiveInt;
begin
result := TFhirPositiveInt(ObjectByIndex[index]);
end;
function TFhirPositiveIntList.Link: TFhirPositiveIntList;
begin
result := TFhirPositiveIntList(inherited Link);
end;
procedure TFhirPositiveIntList.Remove(index: Integer);
begin
DeleteByIndex(index);
end;
procedure TFhirPositiveIntList.SetItemByIndex(index: Integer; value: TFhirPositiveInt);
begin
assert(value is TFhirPositiveInt);
FhirPositiveInts[index] := value;
end;
procedure TFhirPositiveIntList.SetItemN(index: Integer; value: TFhirPositiveInt);
begin
assert(value is TFhirPositiveInt);
ObjectByIndex[index] := value;
end;
{ TFhirInteger64 }
Constructor TFhirInteger64.Create(value : String);
begin
Create;
FValue := value;
end;
destructor TFhirInteger64.Destroy;
begin
inherited;
end;
function TFhirInteger64.fhirType : string;
begin
result := 'Integer64';
end;
function TFhirInteger64.Link : TFhirInteger64;
begin
result := TFhirInteger64(inherited Link);
end;
function TFhirInteger64.Clone : TFhirInteger64;
begin
result := TFhirInteger64(inherited Clone);
end;
{ TFhirInteger64ListEnumerator }
Constructor TFhirInteger64ListEnumerator.Create(list : TFhirInteger64List);
begin
inherited Create;
FIndex := -1;
FList := list;
end;
destructor TFhirInteger64ListEnumerator.Destroy;
begin
FList.Free;
inherited;
end;
function TFhirInteger64ListEnumerator.MoveNext : boolean;
begin
inc(FIndex);
Result := FIndex < FList.count;
end;
function TFhirInteger64ListEnumerator.GetCurrent : TFhirInteger64;
begin
Result := FList[FIndex];
end;
{ TFhirInteger64List }
procedure TFhirInteger64List.AddItem(value: TFhirInteger64);
begin
assert(value.ClassName = 'TFhirInteger64', 'Attempt to add an item of type '+value.ClassName+' to a List of TFhirInteger64');
add(value);
end;
procedure TFhirInteger64List.AddItem(value: String);
begin
add(TFhirInteger64.create(value));
end;
function TFhirInteger64List.Append: TFhirInteger64;
begin
result := TFhirInteger64.create;
try
add(result.Link);
finally
result.free;
end;
end;
procedure TFhirInteger64List.ClearItems;
begin
Clear;
end;
function TFhirInteger64List.GetEnumerator : TFhirInteger64ListEnumerator;
begin
result := TFhirInteger64ListEnumerator.Create(self.link);
end;
function TFhirInteger64List.Clone: TFhirInteger64List;
begin
result := TFhirInteger64List(inherited Clone);
end;
function TFhirInteger64List.Count: Integer;
begin
result := Inherited Count;
end;
function TFhirInteger64List.GetItemN(index: Integer): TFhirInteger64;
begin
result := TFhirInteger64(ObjectByIndex[index]);
end;
function TFhirInteger64List.ItemClass: TFslObjectClass;
begin
result := TFhirInteger64;
end;
function TFhirInteger64List.IndexOf(value: TFhirInteger64): Integer;
begin
result := IndexByReference(value);
end;
function TFhirInteger64List.Insert(index: Integer): TFhirInteger64;
begin
result := TFhirInteger64.create;
try
inherited insert(index, result.Link);
finally
result.free;
end;
end;
procedure TFhirInteger64List.InsertItem(index: Integer; value: TFhirInteger64);
begin
assert(value is TFhirInteger64);
Inherited Insert(index, value);
end;
function TFhirInteger64List.Item(index: Integer): TFhirInteger64;
begin
result := TFhirInteger64(ObjectByIndex[index]);
end;
function TFhirInteger64List.Link: TFhirInteger64List;
begin
result := TFhirInteger64List(inherited Link);
end;
procedure TFhirInteger64List.Remove(index: Integer);
begin
DeleteByIndex(index);
end;
procedure TFhirInteger64List.SetItemByIndex(index: Integer; value: TFhirInteger64);
begin
assert(value is TFhirInteger64);
FhirInteger64s[index] := value;
end;
procedure TFhirInteger64List.SetItemN(index: Integer; value: TFhirInteger64);
begin
assert(value is TFhirInteger64);
ObjectByIndex[index] := value;
end;
{{type.concrete.impl}}
function asEnum(systems, values: array of String; obj : TFHIRObject) : TFHIREnum;
begin
if obj is TFHIREnum then
result := obj as TFHIREnum
else if obj is TFHIRCode then
begin
result := TFHIREnum.create(systems[StringArrayIndexOf(values, TFHIRCode(obj).value)], TFHIRCode(obj).value);
obj.Free;
end
else if obj is TFHIRString then
begin
result := TFHIREnum.create(systems[StringArrayIndexOf(values, TFHIRString(obj).value)], TFHIRString(obj).value);
obj.Free;
end
else
begin
obj.Free;
raise EFhirException.Create('Type mismatch: cannot convert from "'+obj.className+'" to "TFHIRCode"')
end;
end;
function asDate(obj : TFHIRObject) : TFHIRDate;
begin
if obj is TFHIRDate then
result := obj as TFHIRDate
else if obj is TFHIRMMElement then
begin
result := TFHIRDate.create(TFslDateTime.fromXml(TFHIRMMElement(obj).value));
obj.Free;
end
else if (obj is TFHIRObject) and (TFHIRObject(obj).isPrimitive) then
begin
result := TFHIRDate.create(TFslDateTime.fromXml(TFHIRObject(obj).primitiveValue));
obj.Free;
end
else
begin
obj.Free;
raise EFhirException.Create('Type mismatch: cannot convert from "'+obj.className+'" to "TFHIRDate"')
end;
end;
function asDateTime(obj : TFHIRObject) : TFHIRDateTime;
begin
if obj is TFHIRDateTime then
result := obj as TFHIRDateTime
else if obj is TFHIRMMElement then
begin
result := TFHIRDateTime.create(TFslDateTime.fromXml(TFHIRMMElement(obj).value));
obj.Free;
end
else if (obj is TFHIRObject) and (TFHIRObject(obj).isPrimitive) then
begin
result := TFHIRDateTime.create(TFslDateTime.fromXml(TFHIRObject(obj).primitiveValue));
obj.Free;
end
else
begin
obj.Free;
raise EFhirException.Create('Type mismatch: cannot convert from "'+obj.className+'" to "TFHIRDateTime"')
end;
end;
function asString(obj : TFHIRObject) : TFHIRString;
begin
if obj is TFHIRString then
result := obj as TFHIRString
else if obj is TFHIRMMElement then
begin
result := TFHIRString.create(TFHIRMMElement(obj).value);
obj.Free;
end
else if (obj is TFHIRObject) and (TFHIRObject(obj).isPrimitive) then
begin
result := TFHIRString.create(TFHIRObject(obj).primitiveValue);
obj.Free;
end
else
begin
obj.Free;
raise EFhirException.Create('Type mismatch: cannot convert from "'+obj.className+'" to "TFHIRString"')
end;
end;
function asInteger(obj : TFHIRObject) : TFHIRInteger;
begin
if obj is TFHIRInteger then
result := obj as TFHIRInteger
else if obj is TFHIRMMElement then
begin
result := TFHIRInteger.create(TFHIRMMElement(obj).value);
obj.Free;
end
else if (obj is TFHIRObject) and (TFHIRObject(obj).isPrimitive) then
begin
result := TFHIRInteger.create(TFHIRObject(obj).primitiveValue);
obj.Free;
end
else
begin
obj.Free;
raise EFhirException.Create('Type mismatch: cannot convert from "'+obj.className+'" to "TFHIRInteger"')
end;
end;
function asUri(obj : TFHIRObject) : TFHIRUri;
begin
if obj is TFHIRUri then
result := obj as TFHIRUri
else if obj is TFHIRMMElement then
begin
result := TFHIRUri.create(TFHIRMMElement(obj).value);
obj.Free;
end
else if (obj is TFHIRObject) and (TFHIRObject(obj).isPrimitive) then
begin
result := TFHIRUri.create(TFHIRObject(obj).primitiveValue);
obj.Free;
end
else
begin
obj.Free;
raise EFhirException.Create('Type mismatch: cannot convert from "'+obj.className+'" to "TFHIRUri"')
end;
end;
function asInstant(obj : TFHIRObject) : TFHIRInstant;
begin
if obj is TFHIRInstant then
result := obj as TFHIRInstant
else if obj is TFHIRMMElement then
begin
result := TFHIRInstant.create(TFslDateTime.fromXml(TFHIRMMElement(obj).value));
obj.Free;
end
else if (obj is TFHIRObject) and (TFHIRObject(obj).isPrimitive) then
begin
result := TFHIRInstant.create(TFslDateTime.fromXml(TFHIRObject(obj).primitiveValue));
obj.Free;
end
else
begin
obj.Free;
raise EFhirException.Create('Type mismatch: cannot convert from "'+obj.className+'" to "TFHIRInstant"')
end;
end;
function asXhtml(obj : TFHIRObject) : TFHIRXhtml;
begin
if obj is TFHIRXhtml then
result := obj as TFHIRXhtml
else if obj is TFHIRMMElement then
begin
result := TFHIRXhtml.create(TFHIRMMElement(obj).value);
obj.Free;
end
else if (obj is TFHIRObject) and (TFHIRObject(obj).isPrimitive) then
begin
result := TFHIRXhtml.create(TFHIRObject(obj).primitiveValue);
obj.Free;
end
else
begin
obj.Free;
raise EFhirException.Create('Type mismatch: cannot convert from "'+obj.className+'" to "TFHIRXhtml"')
end;
end;
function asBoolean(obj : TFHIRObject) : TFHIRBoolean;
begin
if obj is TFHIRBoolean then
result := obj as TFHIRBoolean
else if obj is TFHIRMMElement then
begin
result := TFHIRBoolean.create(TFHIRMMElement(obj).value = 'true');
obj.Free;
end
else if (obj is TFHIRObject) and (TFHIRObject(obj).isPrimitive) then
begin
result := TFHIRBoolean.create(TFHIRObject(obj).primitiveValue = 'true');
obj.Free;
end
else
begin
obj.Free;
raise EFhirException.Create('Type mismatch: cannot convert from "'+obj.className+'" to "TFHIRBoolean"')
end;
end;
function asBase64Binary(obj : TFHIRObject) : TFHIRBase64Binary;
begin
if obj is TFHIRBase64Binary then
result := obj as TFHIRBase64Binary
else if obj is TFHIRMMElement then
begin
result := TFHIRBase64Binary.create(DecodeBase64(TFHIRMMElement(obj).value));
obj.Free;
end
else if (obj is TFHIRObject) and (TFHIRObject(obj).isPrimitive) then
begin
result := TFHIRBase64Binary.create(DecodeBase64(TFHIRObject(obj).primitiveValue));
obj.Free;
end
else
begin
obj.Free;
raise EFhirException.Create('Type mismatch: cannot convert from "'+obj.className+'" to "TFHIRBase64Binary"')
end;
end;
function asTime(obj : TFHIRObject) : TFHIRTime;
begin
if obj is TFHIRTime then
result := obj as TFHIRTime
else if obj is TFHIRMMElement then
begin
result := TFHIRTime.create(TFHIRMMElement(obj).value);
obj.Free;
end
else if (obj is TFHIRObject) and (TFHIRObject(obj).isPrimitive) then
begin
result := TFHIRTime.create(TFHIRObject(obj).primitiveValue);
obj.Free;
end
else
begin
obj.Free;
raise EFhirException.Create('Type mismatch: cannot convert from "'+obj.className+'" to "TFHIRTime"')
end;
end;
function asDecimal(obj : TFHIRObject) : TFHIRDecimal;
begin
if obj is TFHIRDecimal then
result := obj as TFHIRDecimal
else if obj is TFHIRMMElement then
begin
result := TFHIRDecimal.create(TFHIRMMElement(obj).value);
obj.Free;
end
else if (obj is TFHIRObject) and (TFHIRObject(obj).isPrimitive) then
begin
result := TFHIRDecimal.create(TFHIRObject(obj).primitiveValue);
obj.Free;
end
else
begin
obj.Free;
raise EFhirException.Create('Type mismatch: cannot convert from "'+obj.className+'" to "TFHIRDecimal"')
end;
end;
function asCode(obj : TFHIRObject) : TFHIRCode;
begin
if obj is TFHIRCode then
result := obj as TFHIRCode
else if obj is TFHIRMMElement then
begin
result := TFHIRCode.create(TFHIRMMElement(obj).value);
obj.Free;
end
else if (obj is TFHIRObject) and (TFHIRObject(obj).isPrimitive) then
begin
result := TFHIRCode.create(TFHIRObject(obj).primitiveValue);
obj.Free;
end
else
begin
obj.Free;
raise EFhirException.Create('Type mismatch: cannot convert from "'+obj.className+'" to "TFHIRCode"')
end;
end;
function asCanonical(obj : TFHIRObject) : TFHIRCanonical;
begin
if obj is TFHIRCanonical then
result := obj as TFHIRCanonical
else if obj is TFHIRMMElement then
begin
result := TFHIRCanonical.create(TFHIRMMElement(obj).value);
obj.Free;
end
else if (obj is TFHIRObject) and (TFHIRObject(obj).isPrimitive) then
begin
result := TFHIRCanonical.create(TFHIRObject(obj).primitiveValue);
obj.Free;
end
else
begin
obj.Free;
raise EFhirException.Create('Type mismatch: cannot convert from "'+obj.className+'" to "TFHIRCanonical"')
end;
end;
function asOid(obj : TFHIRObject) : TFHIROid;
begin
if obj is TFHIROid then
result := obj as TFHIROid
else if obj is TFHIRMMElement then
begin
result := TFHIROid.create(TFHIRMMElement(obj).value);
obj.Free;
end
else if (obj is TFHIRObject) and (TFHIRObject(obj).isPrimitive) then
begin
result := TFHIROid.create(TFHIRObject(obj).primitiveValue);
obj.Free;
end
else
begin
obj.Free;
raise EFhirException.Create('Type mismatch: cannot convert from "'+obj.className+'" to "TFHIROid"')
end;
end;
function asUuid(obj : TFHIRObject) : TFHIRUuid;
begin
if obj is TFHIRUuid then
result := obj as TFHIRUuid
else if obj is TFHIRMMElement then
begin
result := TFHIRUuid.create(TFHIRMMElement(obj).value);
obj.Free;
end
else if (obj is TFHIRObject) and (TFHIRObject(obj).isPrimitive) then
begin
result := TFHIRUuid.create(TFHIRObject(obj).primitiveValue);
obj.Free;
end
else
begin
obj.Free;
raise EFhirException.Create('Type mismatch: cannot convert from "'+obj.className+'" to "TFHIRUuid"')
end;
end;
function asUrl(obj : TFHIRObject) : TFHIRUrl;
begin
if obj is TFHIRUrl then
result := obj as TFHIRUrl
else if obj is TFHIRMMElement then
begin
result := TFHIRUrl.create(TFHIRMMElement(obj).value);
obj.Free;
end
else if (obj is TFHIRObject) and (TFHIRObject(obj).isPrimitive) then
begin
result := TFHIRUrl.create(TFHIRObject(obj).primitiveValue);
obj.Free;
end
else
begin
obj.Free;
raise EFhirException.Create('Type mismatch: cannot convert from "'+obj.className+'" to "TFHIRUrl"')
end;
end;
function asMarkdown(obj : TFHIRObject) : TFHIRMarkdown;
begin
if obj is TFHIRMarkdown then
result := obj as TFHIRMarkdown
else if obj is TFHIRMMElement then
begin
result := TFHIRMarkdown.create(TFHIRMMElement(obj).value);
obj.Free;
end
else if (obj is TFHIRObject) and (TFHIRObject(obj).isPrimitive) then
begin
result := TFHIRMarkdown.create(TFHIRObject(obj).primitiveValue);
obj.Free;
end
else
begin
obj.Free;
raise EFhirException.Create('Type mismatch: cannot convert from "'+obj.className+'" to "TFHIRMarkdown"')
end;
end;
function asUnsignedInt(obj : TFHIRObject) : TFHIRUnsignedInt;
begin
if obj is TFHIRUnsignedInt then
result := obj as TFHIRUnsignedInt
else if obj is TFHIRMMElement then
begin
result := TFHIRUnsignedInt.create(TFHIRMMElement(obj).value);
obj.Free;
end
else if (obj is TFHIRObject) and (TFHIRObject(obj).isPrimitive) then
begin
result := TFHIRUnsignedInt.create(TFHIRObject(obj).primitiveValue);
obj.Free;
end
else
begin
obj.Free;
raise EFhirException.Create('Type mismatch: cannot convert from "'+obj.className+'" to "TFHIRUnsignedInt"')
end;
end;
function asId(obj : TFHIRObject) : TFHIRId;
begin
if obj is TFHIRId then
result := obj as TFHIRId
else if obj is TFHIRMMElement then
begin
result := TFHIRId.create(TFHIRMMElement(obj).value);
obj.Free;
end
else if (obj is TFHIRObject) and (TFHIRObject(obj).isPrimitive) then
begin
result := TFHIRId.create(TFHIRObject(obj).primitiveValue);
obj.Free;
end
else
begin
obj.Free;
raise EFhirException.Create('Type mismatch: cannot convert from "'+obj.className+'" to "TFHIRId"')
end;
end;
function asPositiveInt(obj : TFHIRObject) : TFHIRPositiveInt;
begin
if obj is TFHIRPositiveInt then
result := obj as TFHIRPositiveInt
else if obj is TFHIRMMElement then
begin
result := TFHIRPositiveInt.create(TFHIRMMElement(obj).value);
obj.Free;
end
else if (obj is TFHIRObject) and (TFHIRObject(obj).isPrimitive) then
begin
result := TFHIRPositiveInt.create(TFHIRObject(obj).primitiveValue);
obj.Free;
end
else
begin
obj.Free;
raise EFhirException.Create('Type mismatch: cannot convert from "'+obj.className+'" to "TFHIRPositiveInt"')
end;
end;
function asInteger64(obj : TFHIRObject) : TFHIRInteger64;
begin
if obj is TFHIRInteger64 then
result := obj as TFHIRInteger64
else if obj is TFHIRMMElement then
begin
result := TFHIRInteger64.create(TFHIRMMElement(obj).value);
obj.Free;
end
else if (obj is TFHIRObject) and (TFHIRObject(obj).isPrimitive) then
begin
result := TFHIRInteger64.create(TFHIRObject(obj).primitiveValue);
obj.Free;
end
else
begin
obj.Free;
raise EFhirException.Create('Type mismatch: cannot convert from "'+obj.className+'" to "TFHIRInteger64"')
end;
end;
end.
| 24.96438 | 134 | 0.706084 |
477708660f36a8c595d693edfa021f723dcb53be | 1,299 | dfm | Pascal | Array/GridUnit.dfm | rustkas/dephi_do | 96025a01d5cb49136472b7e6bb5f037b27145fba | [
"MIT"
]
| null | null | null | Array/GridUnit.dfm | rustkas/dephi_do | 96025a01d5cb49136472b7e6bb5f037b27145fba | [
"MIT"
]
| null | null | null | Array/GridUnit.dfm | rustkas/dephi_do | 96025a01d5cb49136472b7e6bb5f037b27145fba | [
"MIT"
]
| null | null | null | object GridForm: TGridForm
Left = 0
Top = 0
Caption = #1055#1088#1080#1084#1077#1088' '#1088#1072#1073#1086#1090#1099' '#1089' '#1089#1077#1090#1082#1086#1081' Grid'
ClientHeight = 293
ClientWidth = 426
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
OnShow = FormShow
PixelsPerInch = 96
TextHeight = 13
object StringGrid1: TStringGrid
Left = 0
Top = 0
Width = 426
Height = 293
Align = alClient
DefaultRowHeight = 16
Options = [goFixedVertLine, goFixedHorzLine, goVertLine, goHorzLine, goRangeSelect, goColSizing, goEditing, goTabs]
ScrollBars = ssNone
TabOrder = 0
OnDrawCell = StringGrid1DrawCell
ExplicitWidth = 385
ExplicitHeight = 129
ColWidths = (
64
64
64
64
114)
end
object DateEdit: TMaskEdit
Left = 8
Top = 135
Width = 116
Height = 21
EditMask = '!00/00/0000;1;_'
MaxLength = 10
TabOrder = 1
Text = ' . . '
Visible = False
OnChange = DateEditChange
end
object CheckBox1: TCheckBox
Left = 132
Top = 137
Width = 97
Height = 17
TabOrder = 2
Visible = False
OnClick = CheckBox1Click
end
end
| 22.016949 | 123 | 0.634334 |
472fce2aaf919c6629aaf70f3559718b3d326d76 | 1,760 | pas | Pascal | data/pascal/395baee1296ae86483df3041b372fdf9_DAStoredProcEditor.pas | maxim5/code-inspector | 14812dfbc7bac1d76c4d9e5be2cdf83fc1c391a1 | [
"Apache-2.0"
]
| 5 | 2018-01-03T06:43:07.000Z | 2020-07-30T13:15:29.000Z | data/pascal/395baee1296ae86483df3041b372fdf9_DAStoredProcEditor.pas | maxim5/code-inspector | 14812dfbc7bac1d76c4d9e5be2cdf83fc1c391a1 | [
"Apache-2.0"
]
| null | null | null | data/pascal/395baee1296ae86483df3041b372fdf9_DAStoredProcEditor.pas | maxim5/code-inspector | 14812dfbc7bac1d76c4d9e5be2cdf83fc1c391a1 | [
"Apache-2.0"
]
| 2 | 2019-11-04T02:54:49.000Z | 2020-04-24T17:50:46.000Z |
//////////////////////////////////////////////////
// Data Access Components
// Copyright 1998-2005 Core Lab. All right reserved.
// StoredProc Editor
//////////////////////////////////////////////////
{$IFNDEF CLR}
{$I Dac.inc}
unit DAStoredProcEditor;
{$ENDIF}
interface
uses
{$IFDEF MSWINDOWS}
Windows, Messages, Graphics, Controls, Forms, Dialogs,
ComCtrls, StdCtrls, ExtCtrls, Buttons,
{$ENDIF}
{$IFDEF LINUX}
Types, QGraphics, QControls, QForms, QDialogs, QStdCtrls,
QExtCtrls, QComCtrls, QButtons,
{$ENDIF}
SysUtils, DB, Classes,
DBAccess, MemUtils,
CREditor, CRTabEditor, DASQLFrame, DAParamsFrame, DAMacrosFrame, DASPCallFrame,
DASQLEditor, DAUpdateSQLFrame, DASQLGeneratorFrame, DAQueryEditor;
type
TDAStoredProcEditorForm = class(TDAQueryEditorForm)
protected
procedure DoInit; override;
function GetStoredProc: TCustomDADataSet;
procedure SetStoredProc(Value: TCustomDADataSet);
property StoredProc: TCustomDADataSet read GetStoredProc write SetStoredProc;
end;
implementation
uses
DADesignUtils;
{$IFDEF IDE}
{$R *.dfm}
{$ENDIF}
{$IFDEF MSWINDOWS}
{$R DAStoredProcEditor.dfm}
{$ENDIF}
{$IFDEF LINUX}
{$R *.xfm}
{$ENDIF}
procedure TDAStoredProcEditorForm.DoInit;
begin
try
inherited;
finally
Assert(FSQLFrame is TDASPCallFrame);
TDASPCallFrame(FSQLFrame).Mode := spSQLSP;
FSPCallFrame.Mode := spQuerySP;
TDASPCallFrame(FSQLFrame).SetSPName(FDADesignUtilsClass.GetStoredProcName(LocalComponent as TCustomDADataSet));
end;
end;
function TDAStoredProcEditorForm.GetStoredProc: TCustomDADataSet;
begin
Result := FComponent as TCustomDADataSet;
end;
procedure TDAStoredProcEditorForm.SetStoredProc(Value: TCustomDADataSet);
begin
FComponent := Value;
end;
end.
| 22 | 115 | 0.719318 |
85d6096114a30c5633d873efc548e996a6727bb9 | 15,282 | pas | Pascal | textfile/0074.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| 11 | 2015-12-12T05:13:15.000Z | 2020-10-14T13:32:08.000Z | textfile/0074.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| null | null | null | textfile/0074.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| 8 | 2017-05-05T05:24:01.000Z | 2021-07-03T20:30:09.000Z | {$A+,B-,D+,E-,F-,I-,L+,N-,O-,R-,S-,V-}
{$M 16384,0,655360}
Unit RLINE;
(*********************************************************************
Fast disk file text reading operations.
Address comments, complaints, suggestions on CompuServe to
Don Strenczewilk [72617,132]
This unit contains a fast reading object designed for high speed
reading standard ASCII disk files.
The RLINE unit uses about 600 bytes of your programs code space,
and 0 data.
All of RLobject's methods return the result of their operation in
the RFerror field, except for methods: FFilePos and FClose, which
have no error codes. RFerror should be checked after each call to
one of the methods that set it, because it is re-set with each
method call.
**********************************************************************)
Interface
(*********************************************************************)
USES
DOS;
TYPE
RFobject = OBJECT
_Handle : Word; { File handle }
_BufPtr : Pointer; { BufOfs, BufSeg}
_Bpo, { Current buffer position }
_BSize, { Buffer size in bytes }
_BLeft, { Bytes left in buffer to scan }
_NBufs : Word; { Number of buffers read. = 0 if none. }
_TotBytesInBuf : Word; { Total bytes that were read into current buffer.}
RFerror : Word; { RFobject's IOResult }
PROCEDURE FOpen(Fn : STRING; { Name of file to open. }
DBSize : Word; { Size of buffer. 512 bytes minimum. }
VAR BufP); { Disk buffer to use. }
PROCEDURE FClose;
PROCEDURE FReadLn(VAR S : STRING); { String variable to read next line to. }
PROCEDURE FRead(VAR Ch : Char); { Char variable to read next line to. }
FUNCTION FFilePos : LongInt;
PROCEDURE FSeek(FPo : LongInt);
END;
RFextendedP = ^RFextended;
RFextended = Object(RFobject)
FileName : string[80];
CONSTRUCTOR Init(Fn : STRING; { Name of file to open. }
DBSize : Word; { Size of buffer. }
VAR BufP); { Address of disk buffer }
Destructor Done;
FUNCTION FileSize : LongInt;
Function RFerrorString : string;
PROCEDURE Reset;
END;
TYPE
BufRec = Record
Lno : LongInt; { The first line number in the buffer }
FP : LongInt; { file position of first line in buffer. }
END;
CONST
MaxBufs = 8191;
TYPE
BufferArray = Array[1..MaxBufs] OF BufRec;
{ When FileOfLines is initialized with SizeForBuffer = 256, it can index
files up to 2,096,896 bytes long.
{ With SizeForBuffer = 4096, it will handle files up to 33,550,336 bytes. }
FileOfLinesPtr = ^FileOfLines;
FileOfLines = Object(RFextended)
TBuf : Pointer; { Disk buffer pointer. }
BufSize : Integer; { Disk buffer size. }
LastLineNum : LongInt; { Last line number accessed. }
LastLine : String; { Last line read. }
TotalLines : LongInt; { Total lines in file. }
BufRay : ^BufferArray; { Index of buffers for paging. }
NBuffers : Integer;
Constructor Init(FN : String;
SizeForBuffer : Word);
Destructor Done;
PROCEDURE SeekLine(Row : LongInt);
END;
(*---------------------------------------------------------------------
PROCEDURE RFobject.FOpen
A file must first be successfully opened with a call to FOpen, before any of
the other routines are used.
A buffer must be declared to be passed the FOpen. There are no restrictions
on the location of the buffer, so it can be a global or local variable, or
allocated with New() or GetMem().
PROCEDURE FOpen(Fn : STRING; { Name of file to open. }
DBSize : Word; { Size of buffer. 512 bytes minimum. }
VAR BufP); { Disk buffer to use. }
If successful:
Sets RFerror to 0.
If not successful:
Sets RFerror to DOS error code if a DOS error occured,
or error 12 (Invalid File Access Code) if the buffer size is 0.
NOTES:
The SYSTEM unit FileMode variable is used as the DOS File Access Mode
passed to DOS function $3D, to open the file. Actually, the low 3 bits
are set to zero, specifying Read-Only access, but the high 5 file
sharing bits are passed.
TRAPS:
If using a buffer allocated with New() or GetMem(), be sure to use the
caret after it for the BufP parameter. Ie. RF.FOpen(Fn, BSize, BufP^);
Never call FOpen twice with the same RFobject variable without calling
FCLOSE first.
EXAMPLE:
VAR
RF : RFobject;
Buffer : Array[1..2048] of Char;
BEGIN
System.FileMode := 0;
RF.FOpen('HELLO.PAS', Sizeof(Buffer), Buffer);
If RFerror = 0
THEN Writeln('Success')
ELSE Writeln('Error: ', i);
...
--------------------------------------------------------------------------
PROCEDURE RFobject.FClose - When done with the file, it must be closed
with a call to FClose:
PROCEDURE FClose;
Closes previously opened RFrec.
Returns nothing.
This procedure attempts to identify whether the file has been previously
opened before it attempts to ask DOS to close it. It does not attempt to
close the file if:
a) RF.BSize = 0. PROCEDURE FOpen sets RF.BSize to 0 if DOS open failed.
or
b) RF.Handle < 5, in which case it would be a standard DOS handle, which
shouln't be closed.
TRAP: A problem that could occur with this scheme would be if (the file was
never even attempted to be opened by FOpen) AND (the handle = the handle of
a file that is currently opened somewhere else in the program).
----------------------------------------------------------------------
PROCEDURE RFobject.FReadLn
FReadLn - Reads a string of characters up to the next ^M, or
the physical end of file, whichever comes first.
^Z is ignored if it occurs at the end of the file.
If a ^Z appears before the end of the file, it is passed
on to "S".
VAR "S", which receives the string, MUST be of TYPE STRING
or STRING[255].
The maximum length of the string returned to caller is 255
characters. If more than 255 characters are passed in the
file before ^M or <EOF>, the remaining characters are
discarded.
PROCEDURE FReadLn(VAR S : STRING); { String variable to read next line to. }
On success:
Sets RFerror to 0.
S = next string read from file RF.Handle.
On failure:
Sets RFerror to DOS error code,
or $FFFF if End of File
Works like a Turbo Pascal Readln(F, S); except:
(1) It works only with disk files.
(2) Only reads type STRING. ie. not integers, words, or any other type.
(3) It is much faster.
(4) Doesn't stop when a ^Z is encountered before end of file. If a ^Z
is encountered AT the end of file, it is stripped. Any ^Z's
encountered before the physical end of the file are passed on
to the string.
(5) RFerror is set to $FFFF after calling this if the physical
end of file is reached. The value of "S" is invalid when the
$FFFF end of file result is set.
----------------------------------------------------------------------
PROCEDURE RFobject.FRead - Reads the next character from the file:
PROCEDURE FRead(VAR Ch : Char); { Char variable to read next line to. }
Works the same as FReadLn but returns one character instead of a string.
All characters are passed on to Ch except ^Z if it occurs at end of file.
Any ^Z found before the physical end of file is passed on to Ch.
If successful:
Sets RFerror to 0.
Ch = next character in the file.
If failed:
Sets RFerror to either DOS error code,
or $FFFF if physical End of File
----------------------------------------------------------------------
Function RFobject.FFilePos - Returns current file position for use with FSeek.
FUNCTION FFilePos : LongInt;
Returns current file position. RF must have been previously opened.
If FFilePos is called before FOpen is called successfully, the results
will be meaningless.
----------------------------------------------------------------------
PROCEDURE RFobject.FSeek - Seeks to position FPo in previously opened RF.
PROCEDURE FSeek(FPo : LongInt) : Word;
If successful,
RFerror is set to 0.
If failed,
RFerror is set to DOS error code.
To Reset the file, call RFSeek with FPo := 0. Ie. FSeek(0);
On a normal ^M^J ascii file, FFilePos will most often return the position of
the ^J after a call to FReadLn. Because FReadLn strips leading ^J's, this
shouldn't be a problem. But, bear that in mind if using the FFilePos
results for your own untyped file routines.
(****************************************************************************)
Implementation
(****************************************************************************)
{ RFOBJECT ----------------------------------------------------------------}
{$L RLINE.OBJ}
PROCEDURE RFobject.FOpen(Fn : STRING;
DBSize : Word;
VAR BufP); EXTERNAL;
PROCEDURE RFobject.FClose; EXTERNAL;
PROCEDURE RFobject.FReadLn(VAR S : STRING); EXTERNAL;
PROCEDURE RFobject.FRead(VAR Ch : Char); EXTERNAL;
PROCEDURE RFobject.FSeek(FPo : LongInt); EXTERNAL;
FUNCTION RFobject.FFilePos : LongInt; EXTERNAL;
{ RFEXTENDED --------------------------------------------------------------}
CONSTRUCTOR RFextended.Init(Fn : STRING; { Name of file to open. }
DBSize : Word; { Size of buffer. }
VAR BufP); { Address of disk buffer }
BEGIN
FileName := FExpand(Fn);
FOpen(Fn, DBSize, BufP);
END;
FUNCTION RFextended.FileSize : LongInt;
VAR
r : registers;
Fpos : LongInt;
BEGIN
FPos := FFilePos; { save current file position }
with r do begin
ax := $4202;
bx := _handle;
cx := 0;
dx := 0;
msdos(r);
if flags and fcarry <> 0
then RFerror := ax
else FileSize := (longint(dx) shl 16) or ax;
end;
_TotBytesInBuf := 0; { Force FSeek to move file pointer. }
FSeek(FPos); { restore current file position }
END;
Function RFextended.RFerrorString : string;
{ Converts RFerror to a string. }
VAR
S : STRING[80];
BEGIN
CASE RFerror OF
0 : S := 'Success'; { it's not an error. }
100 : S := 'Attempted to read past End Of File.';
101 : S := 'Disk write error.';
102 : S := 'File not assigned.';
103 : S := 'File not opened.';
104 : S := 'File not open for input.';
2 : S := 'File not found.';
3 : S := 'Path not found.';
4 : S := 'Too many files opened.';
5 : S := 'File access denied.';
6 : S := 'Invalid file handle.';
$FFFF : S := 'End Of File.'; { special EOF number, unique to FRead and FReadln }
200 : s := 'Divide by zero. Buffersize = 0?';
ELSE BEGIN
Str(RFerror, S);
S := 'IOerror '+S;
END;
END;
RFerrorString := S;
END;
PROCEDURE RFextended.Reset;
BEGIN
FSeek(0);
END;
DESTRUCTOR RFextended.Done;
BEGIN
Fclose;
END;
{ FILEOFLINES -------------------------------------------------------}
Constructor FileOfLines.Init(FN : string; SizeForBuffer : Word);
VAR
F : File;
L, RamNeeded, FSize : LongInt;
BufNum : Word;
BEGIN
TBuf := nil;
BufRay := nil;
LastLineNum := 0;
LastLine := '';
TotalLines := 0;
If MaxAvail > SizeForBuffer { create the disk buffer }
THEN BufSize := SizeForBuffer
ELSE BufSize := MaxAvail;
If BufSize >= 256
Then GetMem(TBuf,BufSize)
Else Fail;
FileName := FExpand(Fn); { open the file. }
FOpen(FileName, BufSize, TBuf^);
IF RFError = 0
THEN FSize := FileSize;
IF RFerror <> 0 THEN
Exit; { Don't fail so RFerror can be polled in calling routine. }
NBuffers := ((FSize DIV BufSize) + 1); { allocate ram for bufferarray }
RamNeeded := NBuffers * SizeOf(BufRec);
If (MaxAvail < RamNeeded) OR (NBuffers > MaxBufs) THEN BEGIN
Done;
Fail;
END;
GetMem(BufRay, RamNeeded);
{ Index the file. }
BufNum := 1;
With BufRay^[1] Do BEGIN
Lno := 1;
FP := 0;
END;
FReadLn(LastLine);
While RFerror = 0 DO BEGIN
Inc(TotalLines);
IF (_NBufs > BufNum) AND (BufNum < NBuffers) Then BEGIN
Inc(BufNum);
With BufRay^[BufNum] DO BEGIN
Lno := Succ(TotalLines);
FP := FFilePos;
END;
END;
FReadLn(LastLine);
END;
IF RFError = $FFFF { make it to EOF with no problems? }
THEN Reset;
END;
Destructor FileOfLines.Done;
BEGIN
If BufRay <> nil Then Freemem(BufRay,NBuffers * SizeOf(BufRec));
If TBuf <> nil Then FreeMem(TBuf,BufSize);
BufRay := nil;
TBuf := nil;
FClose;
END;
PROCEDURE FileOfLines.SeekLine(Row : LongInt);
{ Seeks and reads row and puts in string LastLine }
VAR
i : Integer;
BEGIN
If Row > TotalLines THEN BEGIN
RFerror := 100; { Attempt to read past end of file. }
Exit;
END;
IF (Row <> LastLineNum+1) THEN BEGIN
i := 2;
While (i <= NBuffers) AND (BufRay^[i].Lno < Row) Do Inc(i);
Dec(i);
With BufRay^[i] DO BEGIN
FSeek(FP);
IF RFerror = 0 THEN BEGIN
FReadLn(LastLine);
LastLineNum := Lno;
END;
END;
END;
While (RFerror = 0) AND (LastLineNum < Row) DO
BEGIN
FReadLn(LastLine);
Inc(LastLineNum);
END;
END;
END.
{ --------------------- RLINE.OBJ needed for this unit ------------ }
{ cut this block out. Save as RLINE.XX. decode with XX3402 :
{ XX3402 d RLINE.XX }
{ the file RLINE.OBJ will be created }
*XX3402-000883-310792--72--85-14039-------RLINE.OBJ--1-OF--1
U+g+0J7AGIt39Y3HHSC66++++3FpQa7j623nQqJhMalZQW+UJaJmQqZjPW+l9X+lW6UF+21d
xId42kZGH2ZCFGt-IooIW+A+ECZAZU6++4WK-U+2F23IEIOM-k-6+++0+E2JZUM+-2BDF2J3
a+Q+81o0+k2-xMk9++V4GIl3HIx2FE+QY-I+++6CIYNDEYd3EpF+FYxEFIs8+++uY-M+++6D
IYNDEYd3EpF+FYBAHpB3Pk++Xt+L+++02374Ho78FIBIE2NGFI32H2s++E0vY-I+++6CIYND
EYd3EpF+FZ73EIFU+E1tY-I+++6CIYNDEYd3EpF+FZB3FIiX+E0eY-U+++6FIYNDEYd3EpF+
FYN7H2JEHpAH+U-7W+E+E86-YO--+U6++3Qnk9Y7+DCfLwBJWym1v349p-u85U++UCDslLME
z8mtI++ukLA0WgW9yVM5wuEaW+oK5wFy-iX5znZ41bI3i+k+um48kvExnG3m4GO7-Mh41WO7
FEX3RUcaWLI0XBUaWII2Aw+aWIIE5sjZLQcC+3K9vAFy-WO1TEU+R+waWlrcTjy1ykFq-9Ey
nG49tJr8-+09wchD06hL+cjuWlyAk6vMh1zB6MjKlJs4QVu9mCAKzoQAVxYaU5bz4cTNRE37
WIwCsk9skvXzzzb15iAO7c+w0bI2GLEFFctT-9Xz+0j0R-kvm5M0WwX2TUe8kU9-eiAA+ze8
oB5dwuLFoTCY5wBJWykSz1DGWwf3LUO9TkOCFkE9Hkdo2cjrIP+BwetMR0K9mCWZzst5-CVZ
zrDdDTzzRGA8obETE6Z50chD+UBD1cZD-igEWLw4WIw88w36WwXcRzwnk6Z52-y9tJr80+-J
WymAqjn3LUMnmEhD0bERWrQ4zow8zoQ4XZw2l5s8d1D+WIQEXhe9tJr80+1c+Txmw2a7Hkca
WUJ5WLw4l5s8eijRJMjg5gJq-XD70ok6REKsm+1fIsh40chK1DTlE1Z215I4UrkC+5IYIYW7
F+knojRY06gQWwW5mfU+EgoVKb6bXYE2Wxvcdzu9wr6PWoECCw7r-PVY+CgD8w87F+e9F+61
kcZ2-XD+WIEE5sjZLQc6+3K9vAFy-XDG7ch31+j+R-F67chB0DTV7chB-WMfHE61kMDG+6jZ
LQc2+CeQ-U123EM-+Lq8+U++R+++
***** END OF BLOCK 1 *****
| 33.149675 | 87 | 0.60038 |
f180a57627b559e18327c386e8d3b04e3ee35257 | 5,945 | pas | Pascal | library/fhir3/tests/fhir3_tests_worker.pas | danka74/fhirserver | 1fc53b6fba67a54be6bee39159d3db28d42eb8e2 | [
"BSD-3-Clause"
]
| null | null | null | library/fhir3/tests/fhir3_tests_worker.pas | danka74/fhirserver | 1fc53b6fba67a54be6bee39159d3db28d42eb8e2 | [
"BSD-3-Clause"
]
| null | null | null | library/fhir3/tests/fhir3_tests_worker.pas | danka74/fhirserver | 1fc53b6fba67a54be6bee39159d3db28d42eb8e2 | [
"BSD-3-Clause"
]
| null | null | null | unit FHIR.R3.Tests.Worker;
{.$.DEFINE DIFF}
{
Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
interface
uses
SysUtils, Classes, Windows, WinAPI.ShellAPI, Soap.EncdDecd,
fsl_utilities,
fhir_objects, fhir_factory,
FHIR.Version.Parser,
fhir3_types, fhir3_resources, fhir3_constants, fhir3_context, fhir3_profiles, fhir3_pathengine,
fsl_json, DUnitX.TestFramework;
var
PUB_HOME : String;
Type
FHIRFolderBasedTestCaseAttribute = class (CustomTestCaseSourceAttribute)
private
FFolder : String;
FFilter : String;
FCount : integer;
protected
function GetCaseInfoArray : TestCaseInfoArray; override;
public
constructor Create(folder, filter : String; count : integer);
end;
TTestingWorkerContext = class (TBaseWorkerContext)
public
function expand(vs : TFhirValueSet; options : TExpansionOperationOptionSet = []) : TFHIRValueSet; override;
function supportsSystem(system, version : string) : boolean; override;
function validateCode(system, version, code, display : String) : TValidationResult; overload; override;
function validateCode(system, version, code : String; vs : TFhirValueSet) : TValidationResult; overload; override;
function validateCode(code : TFHIRCoding; vs : TFhirValueSet) : TValidationResult; overload; override;
function validateCode(code : TFHIRCodeableConcept; vs : TFhirValueSet) : TValidationResult; overload; override;
class function Use : TFHIRWorkerContext;
class procedure closeUp;
end;
implementation
uses
fsl_stream, IdGlobalProtocols;
{ TTestingWorkerContext }
var
GWorkerContext : TBaseWorkerContext;
class procedure TTestingWorkerContext.closeUp;
begin
GWorkerContext.Free;
GWorkerContext := nil;
end;
function TTestingWorkerContext.expand(vs: TFhirValueSet; options : TExpansionOperationOptionSet = []): TFHIRValueSet;
begin
raise EFHIRTodo.create('Not done for testing');;
end;
function TTestingWorkerContext.supportsSystem(system, version: string): boolean;
begin
raise EFHIRTodo.create('Not done for testing');;
end;
class function TTestingWorkerContext.Use: TFHIRWorkerContext;
begin
if GWorkerContext = nil then
begin
GWorkerContext := TTestingWorkerContext.create;
// GWorkerContext.LoadFromDefinitions(IncludeTrailingBackslash(PUB_HOME)+'build\\publish\\validation-min.xml.zip');
GWorkerContext.LoadFromFile(IncludeTrailingBackslash(PUB_HOME)+'build\\publish\\profiles-types.xml');
GWorkerContext.LoadFromFile(IncludeTrailingBackslash(PUB_HOME)+'build\\publish\\profiles-resources.xml');
end;
result := GWorkerContext.link;
end;
function TTestingWorkerContext.validateCode(system, version, code: String; vs: TFhirValueSet): TValidationResult;
begin
raise EFHIRTodo.create('Not done for testing');;
end;
function TTestingWorkerContext.validateCode(system, version, code, display: String): TValidationResult;
begin
raise EFHIRTodo.create('Not done for testing');;
end;
function TTestingWorkerContext.validateCode(code: TFHIRCodeableConcept; vs: TFhirValueSet): TValidationResult;
begin
raise EFHIRTodo.create('Not done for testing');;
end;
function TTestingWorkerContext.validateCode(code: TFHIRCoding; vs: TFhirValueSet): TValidationResult;
begin
raise EFHIRTodo.create('Not done for testing');;
end;
{ FHIRFolderBasedTestCaseAttribute }
constructor FHIRFolderBasedTestCaseAttribute.Create(folder, filter: String; count : integer);
begin
inherited Create;
FFolder := folder;
FFilter := filter;
FCount := count;
end;
function FHIRFolderBasedTestCaseAttribute.GetCaseInfoArray: TestCaseInfoArray;
var
sl : TStringlist;
sr : TSearchRec;
s : String;
i : integer;
begin
sl := TStringList.create;
try
if FindFirst(FFolder+'\*.*', faAnyFile, SR) = 0 then
repeat
s := sr.Name;
if ((FFilter = '') or s.endsWith(FFilter)) and ((FCount = 0) or (sl.count < FCount)) then
sl.Add(sr.Name);
until FindNext(SR) <> 0;
setLength(result, sl.Count);
for i := 0 to sl.Count - 1 do
begin
result[i].Name := sl[i];
SetLength(result[i].Values, 1);
result[i].Values[0] := IncludeTrailingPathDelimiter(FFolder) + sl[i];
end;
finally
sl.Free;
end;
end;
initialization
finalization
TTestingWorkerContext.closeUp;
end.
| 33.971429 | 119 | 0.744491 |
f1dfe6ebb3f4e392436db6b6fff5c2a4b90bfe38 | 1,173 | pas | Pascal | 16/first.pas | madetara/advent2020 | 39492ef746baa8e49de880cb2604b5b67a5792ac | [
"MIT"
]
| null | null | null | 16/first.pas | madetara/advent2020 | 39492ef746baa8e49de880cb2604b5b67a5792ac | [
"MIT"
]
| null | null | null | 16/first.pas | madetara/advent2020 | 39492ef746baa8e49de880cb2604b5b67a5792ac | [
"MIT"
]
| null | null | null | type
Constraint = class
private
a: integer;
b: integer;
c: integer;
d: integer;
public
constructor Create(a, b, c, d: integer);
begin
self.a := a;
self.b := b;
self.c := c;
self.d := d;
end;
function isCompliant(x: integer): boolean;
begin
Result := ((self.a <= x) and (x <= self.b))
or
((self.c <= x) and (x <= self.d));
end;
end;
begin
var fileName := 'input.txt';
var separator := new string[1](''#10#10'');
var input := ReadAllText(fileName)
.Split(separator, System.StringSplitOptions.RemoveEmptyEntries);
var constraints := input[0]
.Matches('(\w+ ?\w+): (\d+)-(\d+) or (\d+)-(\d+)')
.Select(m -> new Constraint(
m.Groups[2].Value.ToInteger(),
m.Groups[3].Value.ToInteger(),
m.Groups[4].Value.ToInteger(),
m.Groups[5].Value.ToInteger()))
.ToArray();
input[2]
.Split(new string[1](''#10''), System.StringSplitOptions.RemoveEmptyEntries)
.Skip(1)
.SelectMany(l -> l.Split(',').Select(c -> c.ToInteger()))
.Where(x -> not constraints.Any(c -> c.isCompliant(x)))
.Sum()
.Print;
end.
| 24.4375 | 80 | 0.547315 |
477b9b362dec7807bef0e8e24a2b5b26a81b47ac | 895 | dfm | Pascal | Source/dlgReplaceText.dfm | CloudDelphi/FExplorer | cb2c1a3145245535915e63b7da1bfb02525bd350 | [
"Apache-2.0"
]
| 63 | 2021-02-05T15:47:56.000Z | 2022-03-09T11:36:39.000Z | Source/dlgReplaceText.dfm | CloudDelphi/FExplorer | cb2c1a3145245535915e63b7da1bfb02525bd350 | [
"Apache-2.0"
]
| 13 | 2021-02-11T08:39:38.000Z | 2022-03-28T22:48:09.000Z | Source/dlgReplaceText.dfm | CloudDelphi/FExplorer | cb2c1a3145245535915e63b7da1bfb02525bd350 | [
"Apache-2.0"
]
| 5 | 2021-02-12T15:35:55.000Z | 2021-07-11T02:34:40.000Z | inherited TextReplaceDialog: TTextReplaceDialog
Caption = 'Replace text'
ClientHeight = 206
OldCreateOrder = True
ExplicitHeight = 235
PixelsPerInch = 96
TextHeight = 13
object ReplaceWidthLabel: TLabel [0]
Left = 8
Top = 41
Width = 82
Height = 13
Alignment = taRightJustify
AutoSize = False
Caption = '&Replace with:'
end
inherited cbSearchText: TComboBox
TabOrder = 5
end
inherited FSearchOptions: TGroupBox
Top = 70
ExplicitTop = 70
end
inherited FSearchDirection: TRadioGroup
Top = 70
ExplicitTop = 70
end
inherited btnOK: TButton
Top = 174
ExplicitTop = 174
end
object cbReplaceText: TComboBox [6]
Left = 96
Top = 37
Width = 228
Height = 21
TabOrder = 0
end
inherited btnCancel: TButton
Top = 174
ExplicitTop = 174
end
end
| 20.340909 | 48 | 0.632402 |
f1c711abfc36a5480e385efe44f8352633022550 | 1,542 | pas | Pascal | turtle/rekpic06.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| 11 | 2015-12-12T05:13:15.000Z | 2020-10-14T13:32:08.000Z | turtle/rekpic06.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| null | null | null | turtle/rekpic06.pas | nickelsworth/swag | 7c21c0da2291fc249b9dc5cfe121a7672a4ffc08 | [
"BSD-2-Clause"
]
| 8 | 2017-05-05T05:24:01.000Z | 2021-07-03T20:30:09.000Z | (* ┌───────────────────────────────────────────────────────────┐
│ Programated by Vladimir Zahoransky │
│ Vladko software │
│ Contact : zahoran@cezap.ii.fmph.uniba.sk │
│ Program tema : general version of squard effect inside │
└───────────────────────────────────────────────────────────┘ *)
{ This program is general version of rekpic04.pas. It is easy to udestand}
uses oKor,crt;
Const l=7;
type MyKor=object(Kor)
procedure Squard (n:integer; s:real);
procedure Squard1(n:integer; s:real);
end;
procedure MyKor.Squard(n:integer; s:real);
var i:integer;
begin
For i:=1 to l do Begin
ZmenFP(i); {If you don't wand colors Clr this line}
Squard1(n,s);
Vlavo(360/l);
End;
end;
procedure MyKor.Squard1(n:integer; s:real);
begin
if n=1 then Dopredu(s)
else
begin
Squard1(n-1,s/3);
Vlavo(90);
Squard1(n-1,s/3);
Vpravo(90);
Squard1(n-1,s/3);
Vpravo(90);
Squard1(n-1,s/3);
Vlavo(90);
Squard1(n-1,s/3);
end
end;
var k:MyKor;
i:integer;
begin
with k do Begin
For i:=1 to 9 do
Begin
Init(0,0,0);
Squard(i,750/l);
PresunXY(-300,230); Pis('Snee flake of level '+chr(i+48));
CakajKlaves;
Zmaz1;
End;
Koniec;
End;
End.
| 24.47619 | 75 | 0.449416 |
471ab32952c7ad1629b9a59b3f0045de1d1fabbb | 26,317 | pas | Pascal | Samples/FirestoreSimpleChat/ChatMainFmx.pas | RafaelWerner/FB4D | 45368f95b605722dedc98819127107e5323ae067 | [
"Apache-2.0"
]
| 146 | 2018-12-05T08:29:45.000Z | 2022-03-18T23:44:54.000Z | Samples/FirestoreSimpleChat/ChatMainFmx.pas | RafaelWerner/FB4D | 45368f95b605722dedc98819127107e5323ae067 | [
"Apache-2.0"
]
| 89 | 2018-12-07T08:47:19.000Z | 2022-03-17T07:05:48.000Z | Samples/FirestoreSimpleChat/ChatMainFmx.pas | RafaelWerner/FB4D | 45368f95b605722dedc98819127107e5323ae067 | [
"Apache-2.0"
]
| 45 | 2018-10-25T07:55:26.000Z | 2022-03-08T17:51:50.000Z | {******************************************************************************}
{ }
{ Delphi FB4D Library }
{ Copyright (c) 2018-2021 Christoph Schneider }
{ Schneider Infosystems AG, Switzerland }
{ https://github.com/SchneiderInfosystems/FB4D }
{ }
{******************************************************************************}
{ }
{ 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 ChatMainFmx;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
System.ImageList, System.Generics.Collections,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects,
FMX.Controls.Presentation, FMX.Edit, FMX.TabControl,FMX.ListView.Types,
FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.Layouts,
FMX.ListView, FMX.StdCtrls, FMX.MultiResBitmap, FMX.ImgList, FMX.TextLayout,
FB4D.Interfaces, FB4D.Configuration, FB4D.SelfRegistrationFra;
type
TfmxChatMain = class(TForm)
TabControl: TTabControl;
tabChat: TTabItem;
tabLogin: TTabItem;
edtKey: TEdit;
Text2: TText;
edtProjectID: TEdit;
Text3: TText;
lsvChat: TListView;
layPushMessage: TLayout;
edtMessage: TEdit;
btnPushMessage: TButton;
lblVersionInfo: TLabel;
layUserInfo: TLayout;
btnSignOut: TButton;
lblUserInfo: TLabel;
FraSelfRegistration: TFraSelfRegistration;
txtUpdate: TText;
txtError: TText;
btnDeleteMessage: TButton;
btnEditMessage: TButton;
layFBConfig: TLayout;
edtBucket: TEdit;
Text1: TText;
shpProfile: TCircle;
ImageList: TImageList;
imgCloudOff: TImage;
layVirtualKeyboardSpace: TLayout;
rctBack: TRectangle;
tmrWatchdog: TTimer;
txtWatchdog: TText;
tmrTesting: TTimer;
chbTesting: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure btnSignOutClick(Sender: TObject);
procedure btnPushMessageClick(Sender: TObject);
procedure edtMessageKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char;
Shift: TShiftState);
procedure lsvChatItemClick(const Sender: TObject;
const AItem: TListViewItem);
procedure btnEditMessageClick(Sender: TObject);
procedure btnDeleteMessageClick(Sender: TObject);
procedure FraSelfRegistrationbtnCheckEMailClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure lsvChatUpdateObjects(const Sender: TObject;
const AItem: TListViewItem);
procedure FormVirtualKeyboard(Sender: TObject;
KeyboardVisible: Boolean; const Bounds: TRect);
procedure tmrWatchdogTimer(Sender: TObject);
procedure chbTestingChange(Sender: TObject);
procedure tmrTestingTimer(Sender: TObject);
private type
TPendingProfile = class
Items: TList<TListViewItem>;
Stream: TStream;
constructor Create(FirstItem: TListViewItem);
destructor Destroy; override;
end;
private type
TMsgType = (myMsg, foreignMsg);
private
fConfig: TFirebaseConfiguration;
fUID: string;
fUserName: string;
fMyImgIndex: integer;
fEditDocID: string;
fPendingProfiles: TDictionary<string {UID}, TPendingProfile>;
fStressTestCounter: cardinal;
function GetAuth: IFirebaseAuthentication;
function GetStorage: IFirebaseStorage;
function GetSettingFilename: string;
function GetCacheFolder: string;
procedure SaveSettings;
procedure OnTokenRefresh(TokenRefreshed: boolean);
procedure OnUserLogin(const Info: string; User: IFirebaseUser);
procedure StartChat;
procedure WipeToTab(ActiveTab: TTabItem);
procedure EnterEditMode(const DocPath: string);
procedure ExitEditMode(ClearEditBox: boolean);
function GetMsgTextName(MsgType: TMsgType): string;
function GetDetailTextName(MsgType: TMsgType): string;
function GetProfileImgName(MsgType: TMsgType): string;
procedure OnAuthRevoked(TokenRenewPassed: boolean);
procedure OnChangedColDocument(Document: IFirestoreDocument);
procedure OnDeletedColDocument(const DeleteDocumentPath: string;
TimeStamp: TDateTime);
procedure OnListenerError(const RequestID, ErrMsg: string);
procedure OnStopListening(Sender: TObject);
procedure OnConnectionStateChange(ListenerConnected: boolean);
function SearchItem(const DocId: string): TListViewItem;
procedure OnDocWrite(const Info: string; Document: IFirestoreDocument);
procedure OnDocWriteError(const RequestID, ErrMsg: string);
procedure OnDocDelete(const RequestID: string; Response: IFirebaseResponse);
procedure OnDocDeleteError(const RequestID, ErrMsg: string);
function AddProfileImgToImageList(const UID: string; Img: TBitmap): integer;
procedure DownloadProfileImgAndAddToImageList(const UID: string;
Item: TListViewItem);
procedure OnStorageDownload(Obj: IStorageObject);
procedure OnGetStorageError(const ObjectName: TObjectName;
const ErrMsg: string);
end;
var
fmxChatMain: TfmxChatMain;
implementation
uses
System.IniFiles, System.IOUtils, System.JSON, System.Math,
FB4D.Helpers, FB4D.Firestore, FB4D.Document, FB4D.Storage;
{$R *.fmx}
{$R *.LgXhdpiPh.fmx ANDROID}
const
cDocID = 'Chat';
// Install the following Firestore Rule:
// rules_version = '2';
// service cloud.firestore {
// match /databases/{database}/documents {
// match /Chat/{document=**} {
// allow read, write: if request.auth != null;}}
{ TfmxChatMain }
procedure TfmxChatMain.FormCreate(Sender: TObject);
var
IniFile: TIniFile;
LastEMail: string;
LastToken: string;
begin
Caption := Caption + ' - ' + TFirebaseHelpers.GetConfigAndPlatform +
' [' + TFirebaseConfiguration.GetLibVersionInfo + ']';
IniFile := TIniFile.Create(GetSettingFilename);
try
edtKey.Text := IniFile.ReadString('FBProjectSettings', 'APIKey', '');
edtProjectID.Text :=
IniFile.ReadString('FBProjectSettings', 'ProjectID', '');
edtBucket.Text := IniFile.ReadString('FBProjectSettings', 'Bucket', '');
LastEMail := IniFile.ReadString('Authentication', 'User', '');
LastToken := IniFile.ReadString('Authentication', 'Token', '');
finally
IniFile.Free;
end;
fPendingProfiles := TDictionary<string, TPendingProfile>.Create;
TabControl.ActiveTab := tabLogin;
FraSelfRegistration.InitializeAuthOnDemand(GetAuth, OnUserLogin, LastToken,
LastEMail, true, false, true);
FraSelfRegistration.RequestProfileImg(GetStorage);
if edtProjectID.Text.IsEmpty then
edtProjectID.SetFocus;
end;
procedure TfmxChatMain.FormDestroy(Sender: TObject);
begin
fPendingProfiles.Free;
FreeAndNil(fConfig);
end;
procedure TfmxChatMain.FraSelfRegistrationbtnCheckEMailClick(Sender: TObject);
begin
FraSelfRegistration.btnCheckEMailClick(Sender);
end;
procedure TfmxChatMain.SaveSettings;
var
IniFile: TIniFile;
begin
IniFile := TIniFile.Create(GetSettingFilename);
try
IniFile.WriteString('FBProjectSettings', 'APIKey', edtKey.Text);
IniFile.WriteString('FBProjectSettings', 'ProjectID', edtProjectID.Text);
IniFile.WriteString('FBProjectSettings', 'Bucket', edtBucket.Text);
IniFile.WriteString('Authentication', 'User', FraSelfRegistration.GetEMail);
if assigned(fConfig) and fConfig.Auth.Authenticated then
IniFile.WriteString('Authentication', 'Token',
fConfig.Auth.GetRefreshToken)
else
IniFile.DeleteKey('Authentication', 'Token');
finally
IniFile.Free;
end;
end;
procedure TfmxChatMain.OnTokenRefresh(TokenRefreshed: boolean);
begin
SaveSettings;
end;
function TfmxChatMain.GetAuth: IFirebaseAuthentication;
begin
fConfig := TFirebaseConfiguration.Create(edtKey.Text, edtProjectID.Text);
result := fConfig.Auth;
result.InstallTokenRefreshNotification(OnTokenRefresh);
edtKey.Enabled := false;
edtProjectID.Enabled := false;
end;
function TfmxChatMain.GetStorage: IFirebaseStorage;
begin
Assert(assigned(fConfig), 'FirebaseConfiguration not initialized');
if not edtBucket.Text.IsEmpty and edtBucket.Enabled then
begin
edtBucket.Enabled := false;
fConfig.SetBucket(edtBucket.Text);
fConfig.Storage.SetupCacheFolder(GetCacheFolder);
end;
result := fConfig.Storage;
end;
function TfmxChatMain.GetSettingFilename: string;
var
FileName: string;
begin
FileName := ChangeFileExt(ExtractFileName(ParamStr(0)), '');
result := IncludeTrailingPathDelimiter(
{$IFDEF IOS}
TPath.GetDocumentsPath
{$ELSE}
TPath.GetHomePath
{$ENDIF}
) + FileName + TFirebaseHelpers.GetPlatform + '.ini';
end;
function TfmxChatMain.GetCacheFolder: string;
var
FileName: string;
begin
FileName := ChangeFileExt(ExtractFileName(ParamStr(0)), '');
result := IncludeTrailingPathDelimiter(
{$IFDEF IOS}
TPath.GetDocumentsPath
{$ELSE}
TPath.GetHomePath
{$ENDIF}
) + IncludeTrailingPathDelimiter(FileName);
end;
procedure TfmxChatMain.OnUserLogin(const Info: string; User: IFirebaseUser);
begin
fUID := User.UID;
fUserName := User.DisplayName;
if assigned(FraSelfRegistration.ProfileImg) then
shpProfile.Fill.Bitmap.Bitmap.Assign(FraSelfRegistration.ProfileImg);
SaveSettings;
StartChat;
end;
procedure TfmxChatMain.btnSignOutClick(Sender: TObject);
begin
fConfig.Database.StopListener;
fConfig.Auth.SignOut;
fUID := '';
fUserName := '';
FraSelfRegistration.StartEMailEntering;
WipeToTab(tabLogin);
end;
procedure TfmxChatMain.WipeToTab(ActiveTab: TTabItem);
var
c: integer;
begin
if TabControl.ActiveTab <> ActiveTab then
begin
ActiveTab.Visible := true;
{$IFDEF ANDROID}
TabControl.ActiveTab := ActiveTab;
{$ELSE}
TabControl.GotoVisibleTab(ActiveTab.Index, TTabTransition.Slide,
TTabTransitionDirection.Normal);
{$ENDIF}
for c := 0 to TabControl.TabCount - 1 do
TabControl.Tabs[c].Visible := TabControl.Tabs[c] = ActiveTab;
end;
end;
procedure TfmxChatMain.StartChat;
begin
GetStorage;
while not fConfig.Storage.IsCacheScanFinished do
begin
FraSelfRegistration.InformDelayedStart('starting...');
if Application.Terminated then
exit
else
TFirebaseHelpers.SleepAndMessageLoop(1);
end;
FraSelfRegistration.StopDelayedStart;
lblUserInfo.Text := fUserName + ' logged in';
edtMessage.Text := '';
fConfig.Database.SubscribeQuery(TStructuredQuery.CreateForCollection(cDocID).
OrderBy('DateTime', odAscending),
OnChangedColDocument, OnDeletedColDocument);
fConfig.Database.StartListener(OnStopListening, OnListenerError,
OnAuthRevoked, OnConnectionStateChange);
btnEditMessage.Visible := false;
btnDeleteMessage.Visible := false;
btnPushMessage.Visible := true;
fEditDocID := '';
fMyImgIndex := AddProfileImgToImageList(fUID, FraSelfRegistration.ProfileImg);
{$IFDEF DEBUG}
tmrWatchdog.Enabled := true;
chbTesting.Visible := true;
{$ENDIF}
WipeToTab(tabChat);
end;
function TfmxChatMain.SearchItem(const DocId: string): TListViewItem;
var
c: integer;
begin
result := nil;
for c := 0 to lsvChat.ItemCount - 1 do
if lsvChat.Items[c].Purpose = TListItemPurpose.None then
if lsvChat.Items[c].TagString = DocId then
exit(lsvChat.Items[c]);
end;
function TfmxChatMain.GetMsgTextName(MsgType: TMsgType): string;
begin
if MsgType = myMsg then
result := 'Text3'
else
result := 'Text5';
end;
function TfmxChatMain.GetDetailTextName(MsgType: TMsgType): string;
begin
if MsgType = myMsg then
result := 'Text4'
else
result := 'Text6';
end;
function TfmxChatMain.GetProfileImgName(MsgType: TMsgType): string;
begin
if MsgType = myMsg then
result := 'Image1'
else
result := 'Image2';
end;
procedure TfmxChatMain.OnChangedColDocument(Document: IFirestoreDocument);
var
Item: TListViewItem;
Edited: TDateTime;
UID: string;
DetailInfo: string;
ImgInd: integer;
MsgType, InvType: TMsgType;
begin
Item := SearchItem(Document.DocumentName(true));
lsvChat.BeginUpdate;
try
if not assigned(Item) then
begin
Item := lsvChat.Items.AddItem(lsvChat.ItemCount);
Item.TagString := Document.DocumentName(true);
end;
Item.Text := Document.GetStringValueDef('Message', '?');
DetailInfo := Document.GetStringValueDef('Sender', '?') + ' at ' +
DateTimeToStr(TFirebaseHelpers.ConvertToLocalDateTime(
Document.GetTimeStampValueDef('DateTime', now)));
Edited := Document.GetTimeStampValueDef('Edited', 0);
if Edited > 0 then
DetailInfo := DetailInfo + ' (edited ' +
DateTimeToStr(TFirebaseHelpers.ConvertToLocalDateTime(Edited)) + ')';
UID := Document.GetStringValueDef('UID', '?');
if UID = fUID then
begin
MsgType := myMsg;
InvType := foreignMsg;
ImgInd := fMyImgIndex;
end else begin
MsgType := foreignMsg;
InvType := myMsg;
ImgInd := ImageList.Source.IndexOf(UID);
if ImgInd < 0 then
begin
DownloadProfileImgAndAddToImageList(UID, Item);
ImgInd := 0; // set to default avatar
end else
dec(ImgInd);
end;
Item.Tag := ord(MsgType);
Item.Data[GetMsgTextName(MsgType)] := Item.Text;
Item.Data[GetDetailTextName(MsgType)] := DetailInfo;
Item.Data[GetProfileImgName(MsgType)] := ImgInd;
Item.Data[GetMsgTextName(InvType)] := ''; // After re-login with other
Item.Data[GetDetailTextName(InvType)] := ''; // other user the former
Item.Data[GetProfileImgName(InvType)] := -1; // MsgType must removed
finally
lsvChat.EndUpdate;
end;
lsvChat.ScrollTo(Item.Index);
txtUpdate.Text := 'Last message written at ' +
FormatDateTime('HH:NN:SS.ZZZ', Document.UpdateTime);
end;
procedure TfmxChatMain.OnConnectionStateChange(ListenerConnected: boolean);
begin
if ListenerConnected then
begin
txtUpdate.Text := 'Server reconnected at ' + TimeToStr(now);
imgCloudOff.Visible := false;
shpProfile.Visible := true;
end else begin
txtUpdate.Text := 'Server disconnected at ' +
TimeToStr(fConfig.Database.GetTimeStampOfLastAccess);
imgCloudOff.Visible := true;
shpProfile.Visible := false;
end;
end;
procedure TfmxChatMain.lsvChatItemClick(const Sender: TObject;
const AItem: TListViewItem);
begin
if AItem.Tag = ord(myMsg) then
begin
edtMessage.Text := AItem.Text;
EnterEditMode(AItem.TagString);
end else
ExitEditMode(not fEditDocID.IsEmpty);
end;
procedure TfmxChatMain.EnterEditMode(const DocPath: string);
begin
fEditDocID := copy(DocPath, DocPath.LastDelimiter('/') + 2);
btnEditMessage.Visible := true;
btnDeleteMessage.Visible := true;
btnPushMessage.Visible := false;
btnEditMessage.Enabled := true;
btnDeleteMessage.Enabled := true;
end;
procedure TfmxChatMain.ExitEditMode(ClearEditBox: boolean);
begin
if ClearEditBox then
edtMessage.Text := '';
fEditDocID := '';
btnEditMessage.Visible := false;
btnDeleteMessage.Visible := false;
btnPushMessage.Visible := true;
btnPushMessage.Enabled := true;
end;
procedure TfmxChatMain.OnDeletedColDocument(const DeleteDocumentPath: string;
TimeStamp: TDateTime);
var
Item: TListViewItem;
begin
Item := SearchItem(DeleteDocumentPath);
if assigned(Item) then
lsvChat.Items.Delete(Item.Index);
lsvChat.Selected := nil;
txtUpdate.Text := 'Last message deleted at ' +
FormatDateTime('HH:NN:SS.ZZZ', TimeStamp);
end;
procedure TfmxChatMain.btnPushMessageClick(Sender: TObject);
var
Doc: IFirestoreDocument;
begin
Doc := TFirestoreDocument.Create(TFirebaseHelpers.CreateAutoID);
Doc.AddOrUpdateField(TJSONObject.SetString('Message', edtMessage.Text));
Doc.AddOrUpdateField(TJSONObject.SetString('Sender', fUserName));
Doc.AddOrUpdateField(TJSONObject.SetString('UID', fUID));
Doc.AddOrUpdateField(TJSONObject.SetTimeStamp('DateTime', now));
{$IFDEF DEBUG}
TFirebaseHelpers.Log('Doc: ' + Doc.AsJSON.ToJSON);
{$ENDIF}
fConfig.Database.InsertOrUpdateDocument([cDocID, Doc.DocumentName(false)],
Doc, nil, OnDocWrite, OnDocWriteError);
btnPushMessage.Enabled := false;
end;
procedure TfmxChatMain.btnEditMessageClick(Sender: TObject);
var
Doc: IFirestoreDocument;
begin
Assert(not fEditDocID.IsEmpty, 'No doc ID to patch');
Doc := TFirestoreDocument.Create(fEditDocID);
Doc.AddOrUpdateField(TJSONObject.SetString('Message', edtMessage.Text));
Doc.AddOrUpdateField(TJSONObject.SetTimeStamp('Edited', now));
fConfig.Database.PatchDocument([cDocID, fEditDocID], Doc,
['Message', 'Edited'], OnDocWrite, OnDocWriteError);
btnEditMessage.Enabled := false;
btnDeleteMessage.Enabled := false;
end;
procedure TfmxChatMain.btnDeleteMessageClick(Sender: TObject);
begin
Assert(not fEditDocID.IsEmpty, 'No doc ID to patch');
fConfig.Database.Delete([cDocID, fEditDocID], nil, OnDocDelete,
OnDocDeleteError);
btnEditMessage.Enabled := false;
btnDeleteMessage.Enabled := false;
end;
procedure TfmxChatMain.edtMessageKeyUp(Sender: TObject; var Key: Word;
var KeyChar: Char; Shift: TShiftState);
begin
if Key = vkReturn then
if fEditDocID.IsEmpty then
btnPushMessageClick(Sender)
else
btnEditMessageClick(Sender);
end;
procedure TfmxChatMain.OnDocWriteError(const RequestID, ErrMsg: string);
begin
if btnPushMessage.Visible then
begin
txtError.Text := 'Failure while write message: ' + ErrMsg;
btnPushMessage.Enabled := true
end else begin
txtError.Text := 'Failure while update message: ' + ErrMsg;
btnEditMessage.Enabled := true;
btnDeleteMessage.Enabled := true;
end;
{$IFDEF DEBUG}
TFirebaseHelpers.Log('DocWriteError ' + txtError.Text);
{$ENDIF}
end;
procedure TfmxChatMain.OnDocWrite(const Info: string;
Document: IFirestoreDocument);
begin
if btnPushMessage.Visible then
txtUpdate.Text := 'Last message sent on ' +
DateTimeToStr(Document.UpdateTime)
else
txtUpdate.Text := 'Last message update on ' +
DateTimeToStr(Document.UpdateTime);
{$IFDEF DEBUG}
TFirebaseHelpers.Log('Written ID: ' + Document.DocumentName(false));
{$ENDIF}
ExitEditMode(true);
end;
procedure TfmxChatMain.OnDocDelete(const RequestID: string;
Response: IFirebaseResponse);
begin
txtUpdate.Text := 'Last message deleted on ' + DateTimeToStr(now);
ExitEditMode(true);
end;
procedure TfmxChatMain.OnDocDeleteError(const RequestID, ErrMsg: string);
begin
txtError.Text := 'Failure while deleted message ' + ErrMsg;
{$IFDEF DEBUG}
TFirebaseHelpers.Log('DocDeleteError ' + txtError.Text);
{$ENDIF}
end;
procedure TfmxChatMain.OnStopListening(Sender: TObject);
begin
txtUpdate.Text := 'Chat listener stopped';
{$IFDEF DEBUG}
TFirebaseHelpers.Log('UNEXPECTED StopListener');
{$ENDIF}
end;
procedure TfmxChatMain.OnAuthRevoked(TokenRenewPassed: boolean);
begin
if TokenRenewPassed then
txtUpdate.Text := 'Chat authorization renewed'
else
txtError.Text := 'Chat authorization renew failed';
end;
procedure TfmxChatMain.OnListenerError(const RequestID, ErrMsg: string);
begin
txtError.Text := 'Error in listener: ' + ErrMsg;
{$IFDEF DEBUG}
TFirebaseHelpers.Log('ListenerError ' + txtError.Text);
{$ENDIF}
end;
procedure TfmxChatMain.lsvChatUpdateObjects(const Sender: TObject;
const AItem: TListViewItem);
function CalcHeight(MsgText: TListItemText; const Text: string): Integer;
const
cMinItemHeight = 60;
var
Layout: TTextLayout;
begin
Layout := TTextLayoutManager.DefaultTextLayout.Create;
try
Layout.BeginUpdate;
try
Layout.Font.Assign(MsgText.Font);
Layout.VerticalAlign := MsgText.TextVertAlign;
Layout.HorizontalAlign := MsgText.TextAlign;
Layout.WordWrap := MsgText.WordWrap;
Layout.Trimming := MsgText.Trimming;
Layout.MaxSize :=
TPointF.Create(MsgText.Width, TTextLayout.MaxLayoutSize.Y);
Layout.Text := Text;
finally
Layout.EndUpdate;
end;
result := round(Layout.Height);
Layout.Text := 'm';
result := max(cMinItemHeight, result + round(Layout.Height));
finally
Layout.Free;
end;
end;
const
cOffsetMsg = 60 - 40;
cOffsetDetail = 60 - 42;
var
MsgType: TMsgType;
MsgTxt, DetTxt: TListItemText;
AvailableWidth: single;
begin
MsgType := TMsgType(AItem.Tag);
MsgTxt := TListItemText(AItem.View.FindDrawable(GetMsgTextName(MsgType)));
DetTxt := TListItemText(AItem.View.FindDrawable(GetDetailTextName(MsgType)));
AvailableWidth := lsvChat.Width - lsvChat.ItemSpaces.Left -
lsvChat.ItemSpaces.Right - abs(MsgTxt.PlaceOffset.X);
lsvChat.BeginUpdate;
try
MsgTxt.Width := AvailableWidth;
AItem.Height := CalcHeight(MsgTxt, AItem.Text);
MsgTxt.Width := AvailableWidth;
MsgTxt.Height := AItem.Height;
DetTxt.PlaceOffset.Y := AItem.Height - cOffsetDetail;
finally
lsvChat.EndUpdate;
end;
end;
function TfmxChatMain.AddProfileImgToImageList(const UID: string;
Img: TBitmap): integer;
var
SrcItem: TCustomSourceItem;
DstItem: TCustomDestinationItem;
BmpItem: TCustomBitmapItem;
begin
result := ImageList.Source.IndexOf(UID);
if result < 0 then // Profile already stored in case ro re-login?
begin
SrcItem := ImageList.Source.Add;
SrcItem.Name := UID;
BmpItem := SrcItem.MultiResBitmap.Add;
BmpItem.Scale := 1;
BmpItem.Bitmap.Assign(Img);
DstItem := ImageList.Destination.Add;
with DstItem.Layers.Add do
begin
Name := UID;
SourceRect.Rect := RectF(0, 0, BmpItem.Width, BmpItem.Height);
end;
with DstItem.Layers.Add do
begin
Name := 'ProfileMask';
SourceRect.Rect := RectF(0, 0, BmpItem.Width, BmpItem.Height);
end;
result := DstItem.Index;
end else
dec(result);
end;
procedure TfmxChatMain.DownloadProfileImgAndAddToImageList(const UID: string;
Item: TListViewItem);
var
Profile: TPendingProfile;
begin
if fPendingProfiles.TryGetValue(UID, Profile) then
Profile.Items.Add(Item)
else begin
Profile := TPendingProfile.Create(Item);
fPendingProfiles.Add(UID, Profile);
GetStorage; // Ensure that Bucket is sent to Config
fConfig.Storage.GetAndDownload(
TFraSelfRegistration.cDefaultStoragePathForProfileImg + '/' + UID,
Profile.Stream, OnStorageDownload, OnGetStorageError);
end;
end;
procedure TfmxChatMain.OnStorageDownload(Obj: IStorageObject);
var
Profile: TPendingProfile;
Bmp: TBitmap;
Ind: integer;
Item: TListViewItem;
UID: string;
begin
UID := Obj.ObjectName(false);
Profile := fPendingProfiles.Items[UID];
Assert(assigned(Profile), 'Invalid profile');
Profile.Stream.Position := 0;
Bmp := TBitmap.Create;
try
Bmp.LoadFromStream(Profile.Stream);
Ind := AddProfileImgToImageList(UID, Bmp);
finally
Bmp.Free;
end;
lsvChat.BeginUpdate;
try
for Item in Profile.Items do
Item.Data['Image2'] := Ind;
finally
lsvChat.EndUpdate;
end;
fPendingProfiles.Remove(UID);
Profile.Free;
end;
procedure TfmxChatMain.OnGetStorageError(const ObjectName: TObjectName;
const ErrMsg: string);
begin
// Do not remove the assoziated profile from fPendingProfiles to prevent retry
end;
procedure TfmxChatMain.FormVirtualKeyboard(Sender: TObject;
KeyboardVisible: Boolean; const Bounds: TRect);
begin
{$IFDEF ANDROID}
// Simple workaround for problem with covered controls from virtual keyboard
layVirtualKeyboardSpace.Height := Bounds.Height;
layVirtualKeyboardSpace.Visible := KeyboardVisible;
if TabControl.ActiveTab = tabChat then
lsvChat.ScrollTo(lsvChat.ItemCount - 1);
{$ENDIF}
end;
{$REGION 'DEBUG Version Only'}
procedure TfmxChatMain.tmrWatchdogTimer(Sender: TObject);
begin
txtWatchdog.Text := TimeToStr(fConfig.Database.GetTimeStampOfLastAccess) +
': ' + lsvChat.ItemCount.ToString + ' docs';
end;
procedure TfmxChatMain.chbTestingChange(Sender: TObject);
begin
fStressTestCounter := 0;
tmrTesting.Enabled := chbTesting.IsChecked;
end;
procedure TfmxChatMain.tmrTestingTimer(Sender: TObject);
var
c: integer;
Item: TListViewItem;
begin
inc(fStressTestCounter);
edtMessage.Text := 'Stress Test at ' + DateTimeToStr(now) + ': ' +
fStressTestCounter.ToString + ' sent messages from ' +
TFirebaseHelpers.GetConfigAndPlatform;
btnPushMessageClick(Sender);
if lsvChat.ItemCount > 10 then
begin
c := 0;
while c < lsvChat.ItemCount do
begin
Item := lsvChat.Items[c];
if Item.Purpose = TListItemPurpose.None then
if Item.Tag = ord(myMsg) then
begin
if Item.Text.StartsWith('Stress Test at ') then
begin
fEditDocID := copy(Item.TagString,
Item.TagString.LastDelimiter('/') + 2);
btnDeleteMessageClick(Sender);
exit;
end;
end;
inc(c);
end;
end;
end;
{$ENDREGION}
{ TfmxChatMain.TPendingProfile }
constructor TfmxChatMain.TPendingProfile.Create(FirstItem: TListViewItem);
begin
Items := TList<TListViewItem>.Create;
Items.Add(FirstItem);
Stream := TMemoryStream.Create;
end;
destructor TfmxChatMain.TPendingProfile.Destroy;
begin
Stream.Free;
Items.Free;
inherited;
end;
end.
| 31.555156 | 81 | 0.700916 |
f1524d08d05df9f7011756ae9a20f9a3dbadc06f | 68 | pas | Pascal | code/test.pas | petak5/INF4 | 6be309583ae4b743b0906c8c2b75392532bf48a4 | [
"MIT"
]
| null | null | null | code/test.pas | petak5/INF4 | 6be309583ae4b743b0906c8c2b75392532bf48a4 | [
"MIT"
]
| null | null | null | code/test.pas | petak5/INF4 | 6be309583ae4b743b0906c8c2b75392532bf48a4 | [
"MIT"
]
| null | null | null | program test;
uses crt;
begin
writeln('Vidis ma?');
clrscr;
end.
| 8.5 | 22 | 0.676471 |
f1ed8450b65cf73ce5ee94f4d1b31b59ff3df10d | 549 | dpr | Pascal | windows/src/buildtools/sentrytool/sentrytool.dpr | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 219 | 2017-06-21T03:37:03.000Z | 2022-03-27T12:09:28.000Z | windows/src/buildtools/sentrytool/sentrytool.dpr | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 4,451 | 2017-05-29T02:52:06.000Z | 2022-03-31T23:53:23.000Z | windows/src/buildtools/sentrytool/sentrytool.dpr | bravogeorge/keyman | c0797e36292de903d7313214d1f765e3d9a2bf4d | [
"MIT"
]
| 72 | 2017-05-26T04:08:37.000Z | 2022-03-03T10:26:20.000Z | program sentrytool;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
Keyman.System.SentryTool.SentryToolMain in 'Keyman.System.SentryTool.SentryToolMain.pas',
Keyman.System.MapToSym in 'Keyman.System.MapToSym.pas',
Keyman.System.AddPdbToPe in 'Keyman.System.AddPdbToPe.pas',
Keyman.System.SentryTool.DelphiSearchFile in 'Keyman.System.SentryTool.DelphiSearchFile.pas';
begin
try
ExitCode := main;
except
on E: Exception do
begin
Writeln(E.ClassName, ': ', E.Message);
ExitCode := 1;
end;
end;
end.
| 21.96 | 95 | 0.715847 |
f114e4d4445203017a85bef28f495db21406b1f9 | 3,142 | pas | Pascal | Libraries/Spring4D/Source/Core/Container/Spring.Container.Extensions.pas | jpluimers/Concepts | 78598ab6f1b4206bbc4ed9c7bc15705ad4ade1fe | [
"Apache-2.0"
]
| 2 | 2020-01-04T08:19:10.000Z | 2020-02-19T22:25:38.000Z | Libraries/Spring4D/Source/Core/Container/Spring.Container.Extensions.pas | jpluimers/Concepts | 78598ab6f1b4206bbc4ed9c7bc15705ad4ade1fe | [
"Apache-2.0"
]
| null | null | null | Libraries/Spring4D/Source/Core/Container/Spring.Container.Extensions.pas | jpluimers/Concepts | 78598ab6f1b4206bbc4ed9c7bc15705ad4ade1fe | [
"Apache-2.0"
]
| 1 | 2020-02-19T22:25:42.000Z | 2020-02-19T22:25:42.000Z | {***************************************************************************}
{ }
{ Spring Framework for Delphi }
{ }
{ Copyright (c) 2009-2016 Spring4D Team }
{ }
{ http://www.spring4d.org }
{ }
{***************************************************************************}
{ }
{ 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. }
{ }
{***************************************************************************}
{$I Spring.inc}
unit Spring.Container.Extensions;
interface
uses
Spring.Container.Core;
type
/// <summary>
/// Base class for all <see cref="TContainer" /> extension objects.
/// </summary>
TContainerExtension = class(TInterfacedObject, IContainerExtension)
private
fKernel: IKernel;
protected
/// <summary>
/// Initial the container with this extension's functionality.
/// </summary>
/// <remarks>
/// When overridden in a derived class, this method will modify the given
/// Kernel to install its functions into the container.
/// </remarks>
procedure Initialize; virtual; abstract;
/// <summary>
/// The container calls this method when the extension is added.
/// </summary>
/// <param name="kernel">
/// An <see cref="IKernel" /> instance that gives the extension access to
/// the internals of the container.
/// </param>
procedure InitializeExtension(const kernel: IKernel);
/// <summary>
/// The IKernel instance used to manipulate the inner state of the
/// container.
/// </summary>
property Kernel: IKernel read fKernel;
end;
implementation
{$REGION 'TContainerExtension'}
procedure TContainerExtension.InitializeExtension(
const kernel: IKernel);
begin
fKernel := kernel;
end;
{$ENDREGION}
end.
| 38.317073 | 79 | 0.440165 |
853b538a1c435afd79ed25777841daf630733a20 | 568 | dpr | Pascal | LabRabKompas/Sample1/ProjectKompas2D.dpr | pisfu/API | 3e0e39e6acee2d53079e6a703babc4e0e2eb0f19 | [
"MIT"
]
| 2 | 2018-05-20T03:17:03.000Z | 2020-12-16T07:25:39.000Z | LabRabKompas/Sample1/ProjectKompas2D.dpr | pisfu/API | 3e0e39e6acee2d53079e6a703babc4e0e2eb0f19 | [
"MIT"
]
| null | null | null | LabRabKompas/Sample1/ProjectKompas2D.dpr | pisfu/API | 3e0e39e6acee2d53079e6a703babc4e0e2eb0f19 | [
"MIT"
]
| 1 | 2020-12-16T07:25:40.000Z | 2020-12-16T07:25:40.000Z | program ProjectKompas2D;
uses
Forms,
MainFormUnit in 'MainFormUnit.pas' {MainForm},
Kompas6API2D5COM_TLB in 'Kompas6API2D5COM_TLB.pas',
Kompas6Constants_TLB in 'Kompas6Constants_TLB.pas',
Kompas6Constants3D_TLB in 'Kompas6Constants3D_TLB.pas',
KompasAPI7_TLB in 'KompasAPI7_TLB.pas',
ksAPI7 in 'ksAPI7.pas',
KsTLB in 'KsTLB.pas',
ksConstTLB in 'ksConstTLB.pas',
LDefin3D in 'LDefin3D.pas';
{$R *.res}
begin
Application.Initialize;
Application.MainFormOnTaskbar := True;
Application.CreateForm(TMainForm, MainForm);
Application.Run;
end.
| 24.695652 | 57 | 0.765845 |
85c4d65678b6b552707e5b006a6ce5d71bc839cc | 6,900 | pas | Pascal | references/embarcadero/rio/10_3_2/patched/fmx/FMX.Calendar.Android.pas | marlonnardi/alcinoe | 5e14b2fca7adcc38e483771055b5623501433334 | [
"Apache-2.0"
]
| 1 | 2019-01-27T14:00:28.000Z | 2019-01-27T14:00:28.000Z | references/embarcadero/rio/10_3_2/patched/fmx/FMX.Calendar.Android.pas | marlonnardi/alcinoe | 5e14b2fca7adcc38e483771055b5623501433334 | [
"Apache-2.0"
]
| 2 | 2019-06-23T00:02:43.000Z | 2019-10-12T22:39:28.000Z | references/embarcadero/rio/10_3_2/patched/fmx/FMX.Calendar.Android.pas | marlonnardi/alcinoe | 5e14b2fca7adcc38e483771055b5623501433334 | [
"Apache-2.0"
]
| null | null | null | {*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit FMX.Calendar.Android;
interface
{$SCOPEDENUMS ON}
uses
System.Types, System.UITypes, Androidapi.JNI.Widget, Androidapi.JNIBridge, Androidapi.JNI.GraphicsContentViewText,
FMX.Controls.Presentation, FMX.Controls.Model, FMX.Presentation.Messages, FMX.Calendar, FMX.Controls,
FMX.Presentation.Android;
type
{ TAndroidNativeCalendar }
TAndroidNativeCalendarListener = class;
TAndroidNativeCalendar = class(TAndroidNativeView)
private
FListener: TAndroidNativeCalendarListener;
function GetView: JCalendarView;
function GetModel: TCalendarModel;
procedure UpdateDate;
procedure UpdateWeekNumbers;
procedure UpdateFirstDayOfWeek;
protected
{ Messages From Model}
procedure MMDateChanged(var AMessage: TDispatchMessageWithValue<TDateTime>); message MM_DATE_CHANGED;
procedure MMWeekNumbersChanged(var AMessage: TDispatchMessageWithValue<Boolean>); message MM_WEEKNUMBERS_CHANGED;
procedure MMFirstDayOfWeekChanged(var AMessage: TDispatchMessageWithValue<TCalDayOfWeek>); message MM_FIRSTDAYOFWEEK_CHANGED;
{ Messages From Controller }
procedure PMInit(var AMessage: TDispatchMessage); message PM_INIT;
protected
function DefineModelClass: TDataModelClass; override;
function CreateView: JView; override;
public
constructor Create; override;
destructor Destroy; override;
/// <summary>Returns the first day of the week in the current locale.</summary>
class function GetCurrentLocaleFirstDayOfWeek: TCalDayOfWeek;
public
property Model: TCalendarModel read GetModel;
property View: JCalendarView read GetView;
end;
TAndroidNativeCalendarListener = class(TJavaLocal, JCalendarView_OnDateChangeListener)
private
[Weak] FCalendar: TAndroidNativeCalendar;
public
constructor Create(const ACalendar: TAndroidNativeCalendar);
{ JCalendarView_OnDateChangeListener }
procedure onSelectedDayChange(view: JCalendarView; year: Integer; month: Integer; dayOfMonth: Integer); cdecl;
end;
implementation
uses
System.SysUtils, System.DateUtils, Androidapi.Helpers, Androidapi.JNI.App, Androidapi.JNI.JavaTypes,
FMX.Presentation.Factory, FMX.Platform, FMX.Consts;
{ TAndroidNativeCalendar }
constructor TAndroidNativeCalendar.Create;
begin
inherited;
FListener := TAndroidNativeCalendarListener.Create(Self);
View.setOnDateChangeListener(FListener);
end;
function TAndroidNativeCalendar.CreateView: JView;
begin
Result := TJCalendarView.JavaClass.init(TAndroidHelper.Context);
end;
function TAndroidNativeCalendar.DefineModelClass: TDataModelClass;
begin
Result := TCalendarModel;
end;
destructor TAndroidNativeCalendar.Destroy;
begin
View.setOnDateChangeListener(nil);
FreeAndNil(FListener);
inherited;
end;
function TAndroidNativeCalendar.GetModel: TCalendarModel;
begin
Result := inherited GetModel<TCalendarModel>;
end;
class function TAndroidNativeCalendar.GetCurrentLocaleFirstDayOfWeek: TCalDayOfWeek;
var
LocaleService: IFMXLocaleService;
begin
if TPlatformServices.Current.SupportsPlatformService(IFMXLocaleService, LocaleService) then
Result := TCalDayOfWeek((LocaleService.GetFirstWeekday + DaysPerWeek - DayMonday) mod DaysPerWeek)
else
Result := TCalDayOfWeek.dowSunday;
end;
function TAndroidNativeCalendar.GetView: JCalendarView;
begin
Result := inherited GetView<JCalendarView>;
end;
procedure TAndroidNativeCalendar.MMDateChanged(var AMessage: TDispatchMessageWithValue<TDateTime>);
begin
UpdateDate;
end;
procedure TAndroidNativeCalendar.MMFirstDayOfWeekChanged(var AMessage: TDispatchMessageWithValue<TCalDayOfWeek>);
begin
UpdateFirstDayOfWeek;
end;
procedure TAndroidNativeCalendar.MMWeekNumbersChanged(var AMessage: TDispatchMessageWithValue<Boolean>);
begin
UpdateWeekNumbers;
end;
procedure TAndroidNativeCalendar.PMInit(var AMessage: TDispatchMessage);
begin
inherited;
UpdateDate;
UpdateWeekNumbers;
UpdateFirstDayOfWeek;
end;
procedure TAndroidNativeCalendar.UpdateDate;
begin
View.setDate(DateTimeToUnix(Model.DateTime) * MSecsPerSec);
end;
procedure TAndroidNativeCalendar.UpdateFirstDayOfWeek;
function CalDayOfWeekToInt(const ADayOfWeek: TCalDayOfWeek): Integer;
begin
case ADayOfWeek of
TCalDayOfWeek.dowMonday:
Result := TJCalendar.JavaClass.MONDAY;
TCalDayOfWeek.dowTuesday:
Result := TJCalendar.JavaClass.TUESDAY;
TCalDayOfWeek.dowWednesday:
Result := TJCalendar.JavaClass.WEDNESDAY;
TCalDayOfWeek.dowThursday:
Result := TJCalendar.JavaClass.THURSDAY;
TCalDayOfWeek.dowFriday:
Result := TJCalendar.JavaClass.FRIDAY;
TCalDayOfWeek.dowSaturday:
Result := TJCalendar.JavaClass.SATURDAY;
TCalDayOfWeek.dowSunday:
Result := TJCalendar.JavaClass.SUNDAY;
else
Result := TJCalendar.JavaClass.SUNDAY;
end;
end;
var
FirstDayOfWeek: TCalDayOfWeek;
begin
if Model.FirstDayOfWeek = TCalDayOfWeek.dowLocaleDefault then
FirstDayOfWeek := GetCurrentLocaleFirstDayOfWeek
else
FirstDayOfWeek := Model.FirstDayOfWeek;
View.setFirstDayOfWeek(CalDayOfWeekToInt(FirstDayOfWeek));
end;
procedure TAndroidNativeCalendar.UpdateWeekNumbers;
begin
View.setShowWeekNumber(Model.WeekNumbers);
end;
{ TAndroidNativeCalendarListener }
constructor TAndroidNativeCalendarListener.Create(const ACalendar: TAndroidNativeCalendar);
begin
if ACalendar = nil then
raise EArgumentNilException.CreateFmt(SWrongParameter, ['ACalendar']);
inherited Create;
FCalendar := ACalendar;
end;
procedure TAndroidNativeCalendarListener.onSelectedDayChange(view: JCalendarView; year, month, dayOfMonth: Integer);
var
OldDay, NewDay: Word;
begin
OldDay := DayOf(FCalendar.Model.DateTime);
NewDay := DayOf(Date);
FCalendar.Model.DisableNotify;
try
FCalendar.Model.DateTime := EncodeDate(year, month, dayOfMonth);
finally
FCalendar.Model.EnableNotify;
end;
if Assigned(FCalendar.Model.OnChange) then
FCalendar.Model.OnChange(FCalendar.Control);
if (OldDay <> NewDay) and Assigned(FCalendar.Model.OnDateSelected) then
FCalendar.Model.OnDateSelected(FCalendar.Control);
end;
initialization
TPresentationProxyFactory.Current.Register(TCalendar, TControlType.Platform, TAndroidPresentationProxy<TAndroidNativeCalendar>);
finalization
TPresentationProxyFactory.Current.Unregister(TCalendar, TControlType.Platform, TAndroidPresentationProxy<TAndroidNativeCalendar>);
end.
| 31.221719 | 132 | 0.754928 |
f179b96758a77c6c22d63a69762e5fc1c234b2e4 | 3,146 | pas | Pascal | Demo/FMX/UnitMain.pas | thecocce/Zint-Barcode-Generator-for-Delphi | 788dc543a19f8a55c0709a091c56034c6ff3f010 | [
"Apache-2.0"
]
| 1 | 2019-02-10T17:39:18.000Z | 2019-02-10T17:39:18.000Z | Demo/FMX/UnitMain.pas | thecocce/Zint-Barcode-Generator-for-Delphi | 788dc543a19f8a55c0709a091c56034c6ff3f010 | [
"Apache-2.0"
]
| null | null | null | Demo/FMX/UnitMain.pas | thecocce/Zint-Barcode-Generator-for-Delphi | 788dc543a19f8a55c0709a091c56034c6ff3f010 | [
"Apache-2.0"
]
| 1 | 2019-02-10T17:39:20.000Z | 2019-02-10T17:39:20.000Z | unit UnitMain;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Edit, FMX.ListBox, zint,
FMX.Objects;
type
TFormMain = class(TForm)
imgResult: TImage;
Panel1: TPanel;
comType: TComboBox;
edData: TEdit;
comPrinter: TComboBox;
btPrint: TButton;
procedure comTypeChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure GenBarcode;
procedure btPrintClick(Sender: TObject);
procedure edDataChange(Sender: TObject);
function GenSymbol: TZintSymbol;
public
{ Public-Deklarationen }
end;
var
FormMain: TFormMain;
implementation
{$R *.fmx}
uses zint_render_fmx_bmp, zint_render_fmx_canvas, fmx.printer;
procedure TFormMain.btPrintClick(Sender: TObject);
var
symbol : TZintSymbol;
rt : TZintCanvasRenderTarget;
begin
symbol := GenSymbol;
try
symbol.Encode(UTF8Encode(edData.Text), true);
Printer.ActivePrinter:=TPrinterDevice(comPrinter.Items.Objects[comPrinter.ItemIndex]);
Printer.ActivePrinter.SelectDPI(1200, 1200);
Printer.BeginDoc;
rt:=TZintCanvasRenderTarget.Create(nil);
rt.Canvas:=Printer.Canvas;
rt.RenderAdjustMode:=ramScale;
rt.XDesired:=Printer.Canvas.Width/3;
rt.YDesired:=Printer.Canvas.Height/3;
rt.WidthDesired:=Printer.Canvas.Width/3;
rt.HeightDesired:=Printer.Canvas.Height/3;
rt.ShowText:=True;
try
Symbol.Render(rt);
finally
rt.Free;
Printer.EndDoc;
end;
except
end;
symbol.Free;
end;
procedure TFormMain.comTypeChange(Sender: TObject);
begin
GenBarcode;
end;
procedure TFormMain.edDataChange(Sender: TObject);
begin
genBarcode
end;
procedure TFormMain.FormCreate(Sender: TObject);
var
i : Integer;
begin
for i := Low(ZintSymbologyInfos) to High(ZintSymbologyInfos) do
comType.Items.AddObject(ZintSymbologyInfos[i].DisplayName, TObject(ZintSymbologyInfos[i].Symbology));
comType.ItemIndex := 0;
try
for i := 0 to Printer.Count-1 do
comPrinter.Items.AddObject(Printer.Printers[i].Title, Printer.Printers[i]);
if comPrinter.Items.Count>0 then
comPrinter.ItemIndex:=0;
except
on E: Exception do
ShowMessage('Error at getting Printer list: '+E.Message);
end;
end;
function TFormMain.GenSymbol: TZintSymbol;
begin
Result := TZintSymbol.Create(nil);
Result.SymbolType := TZintSymbology(comType.Items.Objects[comType.ItemIndex]);
Result.input_mode := UNICODE_MODE;
Result.output_options:=Result.output_options or BARCODE_BOX;
Result.border_width:=1;
Result.whitespace_width:=10;
Result.Encode(edData.Text, true);
end;
procedure TFormMain.GenBarcode;
var
symbol : TZintSymbol;
bmp : TBitmap;
rt : TZintBMPRenderTarget;
begin
symbol := GenSymbol;
bmp:=TBitmap.Create(round(imgResult.Width), round(imgResult.Height));
rt:=TZintBMPRenderTarget.Create(nil);
rt.Bitmap:=bmp;
rt.RenderAdjustMode:=ramScale;
rt.Font.Family:='Courier New';
rt.ShowText:=True;
Symbol.Render(rt);
rt.Free;
imgResult.Bitmap:=bmp;
bmp.Free;
symbol.Free;
end;
end.
| 22.963504 | 105 | 0.724094 |
f1cf9a735480c6823b1f63a07f8965a48f0bd01e | 698 | dpr | Pascal | Publish/TestNDW.dpr | ecodistrict/DesignModule | edfb28b90e033ce5e8ad27c6054e5b5836654dd2 | [
"MIT"
]
| 3 | 2017-04-03T08:32:37.000Z | 2019-02-15T04:20:08.000Z | Publish/TestNDW.dpr | ecodistrict/DesignModule | edfb28b90e033ce5e8ad27c6054e5b5836654dd2 | [
"MIT"
]
| 70 | 2016-10-04T14:01:54.000Z | 2018-10-26T14:47:30.000Z | Publish/TestNDW.dpr | ecodistrict/DesignModule | edfb28b90e033ce5e8ad27c6054e5b5836654dd2 | [
"MIT"
]
| 2 | 2018-08-09T13:45:23.000Z | 2018-11-09T14:02:02.000Z | program TestNDW;
{$APPTYPE CONSOLE}
{$R *.res}
uses
Logger, LogFile, LogConsole,
NDWLib,
System.SysUtils;
procedure Test;
var
connection: TNDWConnection;
scenario: string;
begin
scenario := 'v7';
connection := TNDWConnection.Create(
'app-usmodel01.tsn.tno.nl', 4000, 'NDW',
'vps17642.public.cloudvps.com', 4000, 'us_ams_2017#'+scenario,
scenario+'#', 'us_ams_2017/us_ams_2017@139.63.116.164/uspsde');
try
WriteLn('Waiting for events');
ReadLn;
//connection.SaveLinkInfoToFile('c:\temp\ndw.world');
finally
connection.Free;
end;
end;
begin
try
Test;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
| 17.45 | 67 | 0.663324 |
471ec6b3370c2785572f2da8294568fe84bc9484 | 5,288 | pas | Pascal | Test/UInstantiateTests.pas | synapsea/DW-Script | b36c2e57f0285c217f8f0cae8e4e158d21127163 | [
"Condor-1.1"
]
| 1 | 2022-02-18T22:14:44.000Z | 2022-02-18T22:14:44.000Z | Test/UInstantiateTests.pas | synapsea/DW-Script | b36c2e57f0285c217f8f0cae8e4e158d21127163 | [
"Condor-1.1"
]
| null | null | null | Test/UInstantiateTests.pas | synapsea/DW-Script | b36c2e57f0285c217f8f0cae8e4e158d21127163 | [
"Condor-1.1"
]
| null | null | null | unit UInstantiateTests;
interface
uses
Windows, Classes, SysUtils,
dwsXPlatformTests, dwsComp, dwsCompiler, dwsExprs, dwsDataContext,
dwsTokenizer, dwsXPlatform, dwsFileSystem, dwsErrors, dwsUtils, Variants,
dwsSymbols, dwsPascalTokenizer, dwsStrings, dwsJSON;
type
TInstantiateTests = class (TTestCase)
private
FCompiler : TDelphiWebScript;
FUnit : TdwsUnit;
FFlag : Integer;
FFlagHigh : Integer;
FFlagNb : Integer;
public
procedure SetUp; override;
procedure TearDown; override;
procedure DoOnInstantiate(info: TProgramInfo; var ExtObject: TObject);
procedure DoOnInstantiateNil(info: TProgramInfo; var ExtObject: TObject);
published
procedure Basic;
procedure TwoExecs;
procedure NilTest;
procedure InfoAccess;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
type
TTestObj = class
FTests : TInstantiateTests;
FValue : Integer;
constructor Create(aTests : TInstantiateTests; aValue : Integer);
destructor Destroy; override;
end;
// Create
//
constructor TTestObj.Create(aTests : TInstantiateTests; aValue : Integer);
begin
FTests:=aTests;
FValue:=aValue;
end;
// Destroy
//
destructor TTestObj.Destroy;
begin
inherited;
Dec(FTests.FFlag);
end;
// ------------------
// ------------------ TInstantiateTests ------------------
// ------------------
// SetUp
//
procedure TInstantiateTests.SetUp;
var
inst : TdwsInstance;
begin
FCompiler:=TDelphiWebScript.Create(nil);
FUnit:=TdwsUnit.Create(nil);
FUnit.UnitName:='Instantiate';
FUnit.Script:=FCompiler;
inst:=FUnit.Instances.Add;
inst.DataType:='TObject';
inst.Name:='test';
inst.OnInstantiate:=DoOnInstantiate;
inst.AutoDestroyExternalObject:=True;
inst:=FUnit.Instances.Add;
inst.DataType:='TObject';
inst.Name:='testNil';
inst.OnInstantiate:=DoOnInstantiateNil;
end;
// TearDown
//
procedure TInstantiateTests.TearDown;
begin
FUnit.Free;
FCompiler.Free;
end;
// DoOnInstantiate
//
procedure TInstantiateTests.DoOnInstantiate(info: TProgramInfo; var ExtObject: TObject);
begin
ExtObject:=TTestObj.Create(Self, FFlag);
Inc(FFlag);
Inc(FFlagNb);
if FFlag>FFlagHigh then
FFlagHigh:=FFlag;
end;
// DoOnInstantiateNil
//
procedure TInstantiateTests.DoOnInstantiateNil(info: TProgramInfo; var ExtObject: TObject);
begin
ExtObject:=nil;
end;
// Basic
//
procedure TInstantiateTests.Basic;
var
prog : IdwsProgram;
exec : IdwsProgramExecution;
begin
FFlag:=0;
FFlagHigh:=0;
FFlagNb:=0;
prog:=FCompiler.Compile('Print(test.ClassName); Print(test.ClassName);');
CheckEquals('', prog.Msgs.AsInfo, 'compile');
exec:=prog.CreateNewExecution;
exec.Execute(0);
CheckEquals('', exec.Msgs.AsInfo, 'exec');
CheckEquals('TObjectTObject', exec.Result.ToString, 'Result');
exec:=nil;
CheckEquals(0, FFlag, 'Flag');
CheckEquals(1, FFlagHigh, 'FlagHigh');
CheckEquals(1, FFlagNb, 'FlagNb');
end;
// TwoExecs
//
procedure TInstantiateTests.TwoExecs;
var
prog : IdwsProgram;
exec1, exec2 : IdwsProgramExecution;
begin
FFlag:=0;
FFlagHigh:=0;
FFlagNb:=0;
prog:=FCompiler.Compile('Print(test.ClassName);Print(test.ClassName);');
CheckEquals('', prog.Msgs.AsInfo, 'compile');
exec1:=prog.CreateNewExecution;
exec2:=prog.CreateNewExecution;
exec1.BeginProgram;
exec2.BeginProgram;
exec1.RunProgram(0);
exec2.RunProgram(0);
exec1.EndProgram;
exec2.EndProgram;
CheckEquals(0, FFlag, 'Flag');
CheckEquals(2, FFlagHigh, 'FlagHigh');
CheckEquals(2, FFlagNb, 'FlagNb');
end;
// NilTest
//
procedure TInstantiateTests.NilTest;
var
prog : IdwsProgram;
exec : IdwsProgramExecution;
begin
prog:=FCompiler.Compile('if testNil=nil then Print("nil");');
CheckEquals('', prog.Msgs.AsInfo, 'compile');
exec:=prog.Execute(0);
CheckEquals('', exec.Msgs.AsInfo, 'exec');
CheckEquals('nil', exec.Result.ToString, 'Result');
end;
// InfoAccess
//
procedure TInstantiateTests.InfoAccess;
var
prog : IdwsProgram;
exec : IdwsProgramExecution;
begin
prog:=FCompiler.Compile('');
exec:=prog.CreateNewExecution;
exec.BeginProgram;
exec.RunProgram(0);
CheckEquals('TTestObj', exec.Info.Vars['test'].ExternalObject.ClassName);
exec.EndProgram;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
RegisterTest('CornerCasesTests', TInstantiateTests);
end.
| 22.891775 | 91 | 0.576778 |
f1453ad23e62af1b0ab9db5600ce920ebe1c5243 | 1,882 | pas | Pascal | libs/uChangePassword.pas | AndanTeknomedia/bazda-delphi-xe8 | 3cb9589e41bf7a7492323348a429a6ef7f357817 | [
"MIT"
]
| null | null | null | libs/uChangePassword.pas | AndanTeknomedia/bazda-delphi-xe8 | 3cb9589e41bf7a7492323348a429a6ef7f357817 | [
"MIT"
]
| null | null | null | libs/uChangePassword.pas | AndanTeknomedia/bazda-delphi-xe8 | 3cb9589e41bf7a7492323348a429a6ef7f357817 | [
"MIT"
]
| null | null | null | unit uChangePassword;
interface
uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, u_utils, JvExControls, JvEnterTab;
type
TPasswordDlg = class(TForm)
Label1: TLabel;
eOldP: TEdit;
OKBtn: TButton;
CancelBtn: TButton;
Label2: TLabel;
eNewP: TEdit;
Label3: TLabel;
eNewPC: TEdit;
JvEnterAsTab1: TJvEnterAsTab;
procedure CancelBtnClick(Sender: TObject);
procedure OKBtnClick(Sender: TObject);
procedure JvEnterAsTab1HandleEnter(Sender: TObject; AControl: TWinControl;
var Handled: Boolean);
private
{ Private declarations }
_OP: String;
public
{ Public declarations }
end;
function PromptChangePassword(const PassLama: String; var PasswordBaru: String): Boolean;
implementation
{$R *.dfm}
function PromptChangePassword;
begin
Result := False;
PasswordBaru := '';
with TPasswordDlg.Create(Application) do
begin
try
_OP := PassLama;
eOldP.Clear;
eNewP.Clear;
eNewPC.Clear;
Tag := mrNone;
ShowModal;
if Tag = mrOk then
begin
PasswordBaru := eNewP.Text;
Result := True;
end;
finally
Free;
end;
end;
end;
procedure TPasswordDlg.CancelBtnClick(Sender: TObject);
begin
Tag := mrCancel;
Close;
end;
procedure TPasswordDlg.JvEnterAsTab1HandleEnter(Sender: TObject;
AControl: TWinControl; var Handled: Boolean);
begin
Handled := AControl is TButton;
end;
procedure TPasswordDlg.OKBtnClick(Sender: TObject);
begin
if eOldP.Text<>_OP then
begin
Warn('Password lama tidak cocok.', handle);
exit;
end;
if eNewP.Text <> eNewPC.Text then
begin
Warn('Password baru tidak sama dengan konfirmasinya.', handle);
FocusTo(eNewP);
exit;
end;
if eNewP.WarnForEmpty('Password baru tidak boleh kosong.') then
exit;
Tag := mrOk;
Close;
end;
end.
| 20.236559 | 89 | 0.681722 |
f1d4380f7ffa839cb5bc5eba9b33864c909a8d8c | 172 | pas | Pascal | UnorganisedCode/FindKey.pas | RossMeikleham/Pascal-Code | 97fbbc75d39cbc85dec47b754e9a34c945df29c1 | [
"MIT"
]
| 1 | 2020-07-05T13:14:16.000Z | 2020-07-05T13:14:16.000Z | UnorganisedCode/FindKey.pas | RossMeikleham/Pascal-Code | 97fbbc75d39cbc85dec47b754e9a34c945df29c1 | [
"MIT"
]
| null | null | null | UnorganisedCode/FindKey.pas | RossMeikleham/Pascal-Code | 97fbbc75d39cbc85dec47b754e9a34c945df29c1 | [
"MIT"
]
| null | null | null | PROGRAM FindKey;
USES CRT;
VAR key:CHAR;
BEGIN
TEXTCOLOR(WHITE);
WRITELN('Enter Key to find');
READLN;
Key:=UPCASE(READKEY);
WRITE(key);
WRITELN('< key');
READLN;
END.
| 10.117647 | 29 | 0.697674 |
f17d40404d77337b5c96c552277f4c4d1987fda0 | 14,946 | pas | Pascal | Sources/NxThemesSupport.pas | KashaketCompany/soulengine | 767d18b53fa882b1a9d797761e5165cfb58c47ad | [
"FTL"
]
| 6 | 2019-03-03T17:30:22.000Z | 2019-07-18T11:56:57.000Z | Sources/NxThemesSupport.pas | gzwplato/soulengine | 767d18b53fa882b1a9d797761e5165cfb58c47ad | [
"FTL"
]
| 16 | 2019-02-02T19:54:54.000Z | 2019-02-28T05:22:36.000Z | Sources/NxThemesSupport.pas | suwermave/soulengine | 767d18b53fa882b1a9d797761e5165cfb58c47ad | [
"FTL"
]
| 1 | 2021-09-11T05:41:08.000Z | 2021-09-11T05:41:08.000Z | {
ThemesSupport
Copyright (C) 1996-2002 by Berg
All rights reserved.
$id:NxThemesSupport.pas v1.0 bn
}
{$I NxSuite.inc}
unit NxThemesSupport;
{$HPPEMIT ''}
{$HPPEMIT '#include "uxtheme.h"'}
{$HPPEMIT ''}
interface
uses
Windows, SysUtils, Graphics, Classes, Controls, NxConsts;
const
teButton = 'button';
teComboBox = 'combobox';
teHeader = 'header';
teEdit = 'edit';
teExplorerBar = 'explorerbar';
teListView = 'listview';
teTab = 'tab';
teToolbar = 'toolbar';
teTrackBar = 'trackbar';
teTreeView = 'treeview';
teRebar = 'rebar';
teScrollBar = 'scrollbar';
teSpin = 'spin';
{ teTreeView }
tcExpandingButton = 2;
{ teToolbar }
tcToolbarButton = 1;
tcToolbarButtonHover = 2;
tcToolbarButtonDown = 3;
{ teButton }
tcCheckBox = 3;
tcRadioButton = 2;
{ teButton & tcRadioButton }
tiRadioCheckedDisabled = 8;
tiRadioCheckedDown = 7;
tiRadioCheckedHover = 6;
tiRadioChecked = 5;
tiRadioDisabled = 4;
tiCollapsed = 1;
tiExpanded = 2;
{ teHeader }
tcHeader = 1;
tiHeaderNormal = 1;
tiHeaderHover = 2;
tiHeaderPasive = 7;
{ teScrollBar }
tcHorzGrip = 9;
{ teSpin }
tcSpinUp = 1;
tcSpinDown = 2;
{ teTab }
tcTab = 1;
tcTabPage = 9;
{ tcTab }
tiTab = 1;
tiTabActive = 3;
type
HIMAGELIST = THandle;
HTHEME = THandle;
{$EXTERNALSYM HTHEME}
var
{ External DLL's }
OpenThemeData: function(hwnd: HWND; pszClassList: LPCWSTR): HTHEME; stdcall;
{$EXTERNALSYM OpenThemeData}
CloseThemeData: function(hTheme: HTHEME): HRESULT; stdcall;
{$EXTERNALSYM CloseThemeData}
DrawThemeBackground: function(hTheme: HTHEME; hdc: HDC; iPartId, iStateId: Integer;
const Rect: TRect; pClipRect: PRect): HRESULT; stdcall;
{$EXTERNALSYM DrawThemeBackground}
DrawThemeEdge: function(hTheme: HTHEME; hdc: HDC; iPartId, iStateId: Integer;
const pDestRect: TRect; uEdge, uFlags: UINT; pContentRect: PRECT): HRESULT; stdcall;
{$EXTERNALSYM DrawThemeEdge}
GetThemeSysSize: function(hTheme: HTHEME; iSizeId: Integer): Integer; stdcall;
{$EXTERNALSYM GetThemeSysSize}
IsThemeActive: function: BOOL; stdcall;
{$EXTERNALSYM IsThemeActive}
IsAppThemed: function: BOOL; stdcall;
{$EXTERNALSYM IsAppThemed}
function IsStyled: Boolean;
function IsThemed: Boolean;
procedure InitThemes;
procedure ReleaseThemes;
{ Custom procedures }
procedure ThemeRect(Handle: HWND; DC: HDC; ARect: TRect; Element: PWideChar;
Category, Item: Integer);
type
TColorScheme = (csDefault, csBlack, csBlue, csSilver, csBlue2010, csSilver2010, csBlack2010);
TColorSchemes = csBlack..csBlack2010;
TColorSchemeElement = (
seBackgroundGradientStart,
seBackgroundGradientEnd,
seBorder,
seBtnFace,
seBtnFaceDark,
seDown,
seGridHeaderGradientStart,
seGridHeaderGradientEnd,
seGroupHeader,
seHeaderFont,
seHeaderDivider,
seHeaderGradientEnd,
seHeaderGradientStart,
seHeaderShadow,
seHighlight,
seHover,
seHighlightHoverFore,
seHighlightDownFore,
seInactiveDockCaption,
seMenuHighlight,
seMenuSelectionBorder,
seMenuSelectionBorderDown,
seSplitterGradientStart,
seSplitterGradientEnd);
TSchemeColors = array[TColorScheme, TColorSchemeElement] of TColor;
TNxColorScheme = class(TComponent)
private
FColorScheme: TColorSchemes;
FOnChange: TNotifyEvent;
procedure SetColorScheme(const Value: TColorSchemes);
protected
procedure DoChange; dynamic;
public
constructor Create(AOwner: TComponent); override;
published
property ColorScheme: TColorSchemes read FColorScheme write SetColorScheme default csBlue;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
var
ShemeColors: TSchemeColors;
ColorScheme: TColorSchemes = csBlue;
ControlsList: TList;
{ Remove AControl from ControlsList }
procedure RemoveSchemeNotification(AControl: TControl);
{ Return scheme color based on element }
function SchemeColor(Element: TColorSchemeElement; Scheme: TColorScheme = csDefault): TColor; overload;
{ Add AControl into ControlsList (TList) }
procedure SchemeNotification(AControl: TControl);
implementation
uses
{$IFDEF CUSTOM_STYLES}
Themes,
{$ENDIF}
Forms, Math;
const
dllUxTheme = 'uxtheme.dll';
var
FDllHandle: THandle;
{ Windows XP/Vista Themes }
procedure InitThemes;
begin
if FDllHandle = 0 then
begin
FDllHandle := LoadLibrary(dllUxTheme);
if FDllHandle > 0 then
begin
CloseThemeData := GetProcAddress(FDllHandle, 'CloseThemeData');
DrawThemeBackground := GetProcAddress(FDllHandle, 'DrawThemeBackground');
DrawThemeEdge := GetProcAddress(FDllHandle, 'DrawThemeEdge');
GetThemeSysSize := GetProcAddress(FDllHandle, 'GetThemeSysSize');
IsThemeActive := GetProcAddress(FDllHandle, 'IsThemeActive');
IsAppThemed := GetProcAddress(FDllHandle, 'IsAppThemed');
OpenThemeData := GetProcAddress(FDllHandle, 'OpenThemeData');
end;
end;
end;
function IsThemed: Boolean;
begin
try
Result := (FDllHandle > 0) and IsAppThemed and IsThemeActive;
{ note: uncomment for debug }
// Result := False;
except
raise Exception.Create('Error in Themes');
end;
end;
function IsStyled: Boolean;
begin
Result := False;
{$IFDEF CUSTOM_STYLES}
Result := StyleServices.Enabled;
{$ENDIF}
end;
function IsThemesSupported: Boolean;
begin
Result := (FDllHandle > 0) and IsAppThemed;
end;
procedure ReleaseThemes;
begin
if FDllHandle <> 0 then
begin
FreeLibrary(FDllHandle);
FDllHandle := 0;
CloseThemeData := nil;
DrawThemeBackground := nil;
DrawThemeEdge := nil;
GetThemeSysSize := nil;
IsThemeActive := nil;
IsAppThemed := nil;
OpenThemeData := nil;
end;
end;
procedure ThemeRect(Handle: HWND; DC: HDC; ARect: TRect; Element: PWideChar;
Category, Item: Integer);
var
Theme: THandle;
begin
Theme := OpenThemeData(Handle, Element);
if Theme <> 0 then
try
DrawThemeBackground(Theme, DC, Category, Item, ARect, @ARect);
finally
CloseThemeData(Theme);
end;
end;
{ ColorScheme }
procedure RemoveSchemeNotification(AControl: TControl);
var
Index: Integer;
begin
if Assigned(ControlsList) then
begin
Index := ControlsList.IndexOf(AControl);
if InRange(Index, 0, Pred(ControlsList.Count))
then ControlsList.Delete(Index);
end;
end;
function SchemeColor(Element: TColorSchemeElement; Scheme: TColorScheme = csDefault): TColor;
begin
if Scheme = csDefault then Scheme := ColorScheme;
Result := ShemeColors[Scheme, Element];
end;
procedure SchemeNotification(AControl: TControl);
begin
if Assigned(ControlsList) then ControlsList.Add(AControl);
end;
{ TNxColorCheme }
constructor TNxColorScheme.Create(AOwner: TComponent);
begin
inherited;
FColorScheme := NxThemesSupport.ColorScheme;
end;
procedure TNxColorScheme.DoChange;
begin
if Assigned(FOnChange) then FOnChange(Self);
end;
procedure TNxColorScheme.SetColorScheme(const Value: TColorSchemes);
var
i: Integer;
R: TRect;
AControl: TControl;
begin
FColorScheme := Value;
if FColorScheme <> NxThemesSupport.ColorScheme then
begin
NxThemesSupport.ColorScheme := FColorScheme;
DoChange;
end;
for i := 0 to Pred(ControlsList.Count) do
begin
AControl := ControlsList[i];
if AControl is TWinControl then
begin
R := AControl.ClientRect;
RedrawWindow(TWinControl(AControl).Handle, @R, 0, RDW_FRAME or RDW_INVALIDATE or RDW_NOCHILDREN);
end else AControl.Invalidate;
end;
end;
initialization
{ Blue }
ShemeColors[csBlue, seBackgroundGradientEnd] := $00CE9266;
ShemeColors[csBlue, seBorder] := $00CF9365;
ShemeColors[csBlue, seBtnFace] := $00FFEFE3;
ShemeColors[csBlue, seBtnFaceDark] := $00F0D9C2; // info panel
ShemeColors[csBlue, seGridHeaderGradientStart] := $00ffffff;
ShemeColors[csBlue, seGridHeaderGradientEnd] := $00FFD2AF;
ShemeColors[csBlue, seGroupHeader] := $00EEE7DD;
ShemeColors[csBlue, seHeaderDivider] := $00ffc69a;
ShemeColors[csBlue, seHeaderFont] := $008B4215;
ShemeColors[csBlue, seHeaderGradientEnd] := $00FFD2AF;
ShemeColors[csBlue, seHeaderGradientStart] := $00FFEFE3;
ShemeColors[csBlue, seHeaderShadow] := ShemeColors[csBlue, seBorder];
ShemeColors[csBlue, seHighlight] := $00c9b0a7;
ShemeColors[csBlue, seInactiveDockCaption] := $00E9CFB8;
ShemeColors[csBlue, seMenuHighlight] := $00A2E7FF;
ShemeColors[csBlue, seMenuSelectionBorder] := $0069BDFF; //info panel hover
ShemeColors[csBlue, seMenuSelectionBorderDown] := $003C8CFB; //info panel down
ShemeColors[csBlue, seSplitterGradientStart] := $00FFEFE3;
ShemeColors[csBlue, seSplitterGradientEnd] := $00FFD6B6;
{ Silver }
ShemeColors[csSilver, seBackgroundGradientEnd] := $00A69F9B;
ShemeColors[csSilver, seBorder] := $0074706F;
ShemeColors[csSilver, seBtnFace] := $00F2F1F0;
ShemeColors[csSilver, seBtnFaceDark] := $00E1D6D2; // info panel
ShemeColors[csSilver, seGroupHeader] := $00EBEBEB;
ShemeColors[csSilver, seGridHeaderGradientStart] := $00ffffff;
ShemeColors[csSilver, seGridHeaderGradientEnd] := $00E7DFDA;
ShemeColors[csSilver, seHeaderDivider] := $008f6d6e;
ShemeColors[csSilver, seHeaderFont] := $008B4215;
ShemeColors[csSilver, seHeaderGradientEnd] := $00E7DFDA;
ShemeColors[csSilver, seHeaderGradientStart] := $00F8F7F6;
ShemeColors[csSilver, seHeaderShadow] := ShemeColors[csSilver, seBorder];
ShemeColors[csSilver, seHighlight] := $00c9b0a7;
ShemeColors[csSilver, seInactiveDockCaption] := $00C2B7B2;
ShemeColors[csSilver, seMenuHighlight] := $00C2EEFF;
ShemeColors[csSilver, seMenuSelectionBorder] := $006FC0FF; //info panel hover
ShemeColors[csSilver, seMenuSelectionBorderDown] := $003E80FE; //info panel down
ShemeColors[csSilver, seSplitterGradientStart] := $00BFA7A8;
ShemeColors[csSilver, seSplitterGradientEnd] := $00977778;
{ Black }
ShemeColors[csBlack, seBackgroundGradientEnd] := $000A0A0A;
ShemeColors[csBlack, seBorder] := $005C534C;
ShemeColors[csBlack, seBtnFace] := $00F2F1F0;
ShemeColors[csBlack, seBtnFaceDark] := $00E1D6D2; // info panel
ShemeColors[csBlack, seDown] := $003C8CFB;
ShemeColors[csBlack, seGridHeaderGradientStart] := $00ffffff;
ShemeColors[csBlack, seGridHeaderGradientEnd] := $00C9C2BD;
ShemeColors[csBlack, seGroupHeader] := $00EBEBEB; // menu groups header
ShemeColors[csBlack, seHeaderDivider] := $00a49991;
ShemeColors[csBlack, seHeaderFont] := $00000000;
ShemeColors[csBlack, seHeaderGradientEnd] := $00C9C2BD;
ShemeColors[csBlack, seHeaderGradientStart] := $00F2F1F0;
ShemeColors[csBlack, seHeaderShadow] := $00B6ADA7;
ShemeColors[csBlack, seHighlight] := $00c9b0a7;
ShemeColors[csBlack, seInactiveDockCaption] := $00A0A09E;
ShemeColors[csBlack, seMenuHighlight] := $00A2E7FF;
ShemeColors[csBlack, seMenuSelectionBorder] := $0069BDFF; //info panel hover
ShemeColors[csBlack, seMenuSelectionBorderDown] := $003C8CFB; //info panel down
ShemeColors[csBlack, seSplitterGradientStart] := $00F2F1F0;
ShemeColors[csBlack, seSplitterGradientEnd] := $00CEC8C4;
{ Blue 2010 }
ShemeColors[csBlue2010, seBackgroundGradientEnd] := $00CE9266;
ShemeColors[csBlue2010, seBorder] := $00bd9d84;
ShemeColors[csBlue2010, seBtnFace] := $00e5d0bf;
ShemeColors[csBlue2010, seBtnFaceDark] := $00F0D9C2; // info panel
ShemeColors[csBlue2010, seGridHeaderGradientStart] := $00fbf5ef;
ShemeColors[csBlue2010, seGridHeaderGradientEnd] := $00faece1;
ShemeColors[csBlue2010, seGroupHeader] := $00f5f2f0;
ShemeColors[csBlue2010, seHeaderDivider] := $00bd9d84;
ShemeColors[csBlue2010, seHeaderFont] := $008B4215;
ShemeColors[csBlue2010, seHeaderGradientEnd] := $00E7DFDA;
ShemeColors[csBlue2010, seHeaderGradientStart] := $00F8F7F6;
ShemeColors[csBlue2010, seHeaderShadow] := ShemeColors[csBlue2010, seBorder];
ShemeColors[csBlue2010, seHighlight] := $00f0cda7;
ShemeColors[csBlue2010, seInactiveDockCaption] := $00C2B7B2;
ShemeColors[csBlue2010, seMenuHighlight] := $00C2EEFF;
ShemeColors[csBlue2010, seMenuSelectionBorder] := $006FC0FF; //info panel hover
ShemeColors[csBlue2010, seMenuSelectionBorderDown] := $003E80FE; //info panel down
ShemeColors[csBlue2010, seSplitterGradientStart] := $00BFA7A8;
ShemeColors[csBlue2010, seSplitterGradientEnd] := $00977778;
{ Silver 2010 }
ShemeColors[csSilver2010, seBackgroundGradientEnd] := $00A69F9B;
ShemeColors[csSilver2010, seBorder] := $00b5aca5;
ShemeColors[csSilver2010, seBtnFace] := $00e0dbd6;
ShemeColors[csSilver2010, seBtnFaceDark] := $00E1D6D2; // info panel
ShemeColors[csSilver2010, seGridHeaderGradientStart] := $00f9f7f5;
ShemeColors[csSilver2010, seGridHeaderGradientEnd] := $00f6f2ef;
ShemeColors[csSilver2010, seGroupHeader] := $00EBEBEB;
ShemeColors[csSilver2010, seHeaderDivider] := $00b5aca5;
ShemeColors[csSilver2010, seHeaderFont] := $008B4215;
ShemeColors[csSilver2010, seHeaderGradientEnd] := $00E7DFDA;
ShemeColors[csSilver2010, seHeaderGradientStart] := $00F8F7F6;
ShemeColors[csSilver2010, seHeaderShadow] := ShemeColors[csSilver2010, seBorder];
ShemeColors[csSilver2010, seHighlight] := $00f0cda7;
ShemeColors[csSilver2010, seInactiveDockCaption] := $00C2B7B2;
ShemeColors[csSilver2010, seMenuHighlight] := $00C2EEFF;
ShemeColors[csSilver2010, seMenuSelectionBorder] := $006FC0FF; //info panel hover
ShemeColors[csSilver2010, seMenuSelectionBorderDown] := $003E80FE; //info panel down
ShemeColors[csSilver2010, seSplitterGradientStart] := $00BFA7A8;
ShemeColors[csSilver2010, seSplitterGradientEnd] := $00977778;
{ Black 2010 }
ShemeColors[csBlack2010, seBackgroundGradientEnd] := $00A69F9B;
ShemeColors[csBlack2010, seBorder] := $003b3b3b;
ShemeColors[csBlack2010, seBtnFace] := $00858585;
ShemeColors[csBlack2010, seBtnFaceDark] := $00E1D6D2; // info panel
ShemeColors[csBlack2010, seGridHeaderGradientStart] := $00f9f7f5;
ShemeColors[csBlack2010, seGridHeaderGradientEnd] := $00f6f2ef;
ShemeColors[csBlack2010, seGroupHeader] := $00f5f2f0;
ShemeColors[csBlack2010, seHeaderDivider] := $00b5aca5;
ShemeColors[csBlack2010, seHeaderFont] := $008B4215;
ShemeColors[csBlack2010, seHeaderGradientEnd] := $00E7DFDA;
ShemeColors[csBlack2010, seHeaderGradientStart] := $00F8F7F6;
ShemeColors[csBlack2010, seHeaderShadow] := ShemeColors[csBlack2010, seBorder];
ShemeColors[csBlack2010, seHighlight] := $00f0cda7;
ShemeColors[csBlack2010, seInactiveDockCaption] := $00C2B7B2;
ShemeColors[csBlack2010, seMenuHighlight] := $00C2EEFF;
ShemeColors[csBlack2010, seMenuSelectionBorder] := $006FC0FF; //info panel hover
ShemeColors[csBlack2010, seMenuSelectionBorderDown] := $003E80FE; //info panel down
ShemeColors[csBlack2010, seSplitterGradientStart] := $00BFA7A8;
ShemeColors[csBlack2010, seSplitterGradientEnd] := $00977778;
InitThemes;
ControlsList := TList.Create;
finalization
FreeAndNil(ControlsList);
end.
| 29.772908 | 105 | 0.743677 |
f1f4569a9e0339a4d8780ea5619214fee2e7bfbf | 2,553 | pas | Pascal | UDlgHistory.pas | nikchis/smartnote | 5bb8f7b5397565008f49426f2201a244ba6227c0 | [
"MIT"
]
| null | null | null | UDlgHistory.pas | nikchis/smartnote | 5bb8f7b5397565008f49426f2201a244ba6227c0 | [
"MIT"
]
| null | null | null | UDlgHistory.pas | nikchis/smartnote | 5bb8f7b5397565008f49426f2201a244ba6227c0 | [
"MIT"
]
| null | null | null | unit UDlgHistory;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, dxSkinsCore, dxSkinDevExpressDarkStyle,
dxSkinDevExpressStyle, dxSkinFoggy, dxSkinLondonLiquidSky, dxSkinMcSkin,
dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray,
dxSkinOffice2013White, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus,
dxSkinsDefaultPainters, dxSkinVS2010, dxSkinWhiteprint, dxSkinscxPCPainter,
dxLayoutContainer, dxLayoutControl, Data.DB, DBAccess, LiteAccess, MemDS,
cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator,
cxDBData, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGrid, cxCalendar, cxButtonEdit,
dxSkinBlack;
type
TFormHistory = class(TForm)
dxLayoutControlGroup_Root: TdxLayoutGroup;
dxLayoutControl: TdxLayoutControl;
LQNoteHsts: TLiteQuery;
LDSNoteHsts: TLiteDataSource;
cxGridNotes: TcxGrid;
cxGridNotesDBTableView1: TcxGridDBTableView;
cxGridNotesLevel1: TcxGridLevel;
dxLayoutControlItem1: TdxLayoutItem;
LQNoteHstsnote_hst_id: TIntegerField;
LQNoteHstscreated: TDateTimeField;
cxGridNotesDBTableView1note_hst_id: TcxGridDBColumn;
cxGridNotesDBTableView1created: TcxGridDBColumn;
cxGridNotesDBTableView1Column1: TcxGridDBColumn;
LQNoteHstsinfo: TMemoField;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cxGridNotesDBTableView1Column1PropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
private
_note_id:integer;
_info: string;
{ Private declarations }
public
property NoteId:integer write _note_id;
property Info:string read _info;
{ Public declarations }
end;
var
FormHistory: TFormHistory;
implementation
{$R *.dfm}
uses UDMMain;
procedure TFormHistory.cxGridNotesDBTableView1Column1PropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
_info:= LQNoteHsts.FieldByName('info').AsString;
ModalResult:= mrOk;
end;
procedure TFormHistory.FormClose(Sender: TObject; var Action: TCloseAction);
begin
LQNoteHsts.Close;
end;
procedure TFormHistory.FormShow(Sender: TObject);
begin
LQNoteHsts.ParamByName('note_id').AsInteger:= _note_id;
LQNoteHsts.Open;
end;
end.
| 33.155844 | 99 | 0.773991 |
f1e2820c645f7810e67b66ff641a43c6fa2b2388 | 12,679 | dfm | Pascal | Production7/Export/Export.dfm | kadavris/ok-sklad | f9cd84be7bf984104d9af93d83c0719f2d5668c5 | [
"MIT"
]
| 1 | 2016-04-04T18:11:56.000Z | 2016-04-04T18:11:56.000Z | Production7/Export/Export.dfm | kadavris/ok-sklad | f9cd84be7bf984104d9af93d83c0719f2d5668c5 | [
"MIT"
]
| null | null | null | Production7/Export/Export.dfm | kadavris/ok-sklad | f9cd84be7bf984104d9af93d83c0719f2d5668c5 | [
"MIT"
]
| 5 | 2016-02-15T02:08:05.000Z | 2021-04-05T08:57:58.000Z | object frmExport: TfrmExport
Left = 315
Top = 108
BorderStyle = bsDialog
Caption = 'frmExport'
ClientHeight = 424
ClientWidth = 408
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -13
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
Position = poScreenCenter
OnCloseQuery = FormCloseQuery
OnCreate = FormCreate
DesignSize = (
408
424)
PixelsPerInch = 96
TextHeight = 16
object btnLock: TssSpeedButton
Left = 334
Top = 1
Width = 23
Height = 23
Alignment = taLeftJustify
AllwaysShowFrame = False
Anchors = [akTop, akRight]
ButtonType = ssbtStandard
Checked = False
GroupIndex = 0
ImageIndex = 90
Images = dmData.Images
LeftMargin = 4
ParentShowHint = False
ShowHint = True
Style = ssbsUser
ViewStyle = ssvsGlyphOnly
OnClick = btnLockClick
end
object btnHelp: TssSpeedButton
Left = 380
Top = 1
Width = 23
Height = 23
Alignment = taLeftJustify
AllwaysShowFrame = False
Anchors = [akTop, akRight]
ButtonType = ssbtStandard
Checked = False
GroupIndex = 0
ImageIndex = 10
Images = dmData.Images
LeftMargin = 3
ParentShowHint = False
ShowHint = True
Style = ssbsUser
ViewStyle = ssvsGlyphOnly
OnClick = btnHelpClick
end
object btnSendErrMessage: TssSpeedButton
Left = 357
Top = 1
Width = 23
Height = 23
Alignment = taLeftJustify
AllwaysShowFrame = False
Anchors = [akTop, akRight]
ButtonType = ssbtStandard
Checked = False
GroupIndex = 0
ImageIndex = 129
Images = dmData.Images
LeftMargin = 4
ParentShowHint = False
ShowHint = True
Style = ssbsUser
ViewStyle = ssvsGlyphOnly
OnClick = btnSendErrMessageClick
end
object panButtons: TPanel
Left = 0
Top = 389
Width = 408
Height = 35
Align = alBottom
BevelOuter = bvNone
ParentBackground = False
TabOrder = 0
DesignSize = (
408
35)
object btnOK: TxButton
Left = 239
Top = 9
Width = 80
Height = 22
Action = aOK
Anchors = [akRight, akBottom]
ColorInner = clBtnShadow
Gradient.ColorEnd = clWindow
Gradient.Direction = gdVertical
Gradient.Enabled = True
TabOrder = 0
end
object btnCancel: TxButton
Left = 324
Top = 9
Width = 80
Height = 22
Action = aCancel
Anchors = [akRight, akBottom]
ColorInner = clBtnShadow
Gradient.ColorEnd = clWindow
Gradient.Direction = gdVertical
Gradient.Enabled = True
TabOrder = 1
end
end
object panMain: TPanel
Left = 4
Top = 28
Width = 400
Height = 362
Anchors = [akLeft, akTop, akRight, akBottom]
BevelOuter = bvNone
ParentBackground = False
TabOrder = 1
DesignSize = (
400
362)
object bvlMain: TssBevel
Left = 0
Top = 0
Width = 400
Height = 362
Align = alClient
ColorGrBegin = clBtnFace
ColorGrEnd = clBtnFace
ColorInner = clBtnShadow
ColorOuter = clBtnShadow
Edges = [beLeft, beRight, beTop, beBottom]
GradientDirection = gdHorizontal
HotTrack = False
ImageIndex = 0
UseGradient = False
end
object lName: TLabel
Left = 32
Top = 9
Width = 35
Height = 13
Caption = 'lName'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = [fsBold]
ParentFont = False
end
object btnUp: TssSpeedButton
Left = 372
Top = 148
Width = 23
Height = 23
Action = aUp
Alignment = taLeftJustify
AllwaysShowFrame = False
Anchors = [akTop, akRight]
ButtonType = ssbtStandard
Checked = False
GroupIndex = 0
ImageIndex = 56
Images = dmData.Images
LeftMargin = 4
ParentShowHint = False
ShowHint = True
Style = ssbsUser
ViewStyle = ssvsGlyphOnly
end
object btnDown: TssSpeedButton
Left = 372
Top = 176
Width = 23
Height = 23
Action = aDown
Alignment = taLeftJustify
AllwaysShowFrame = False
Anchors = [akTop, akRight]
ButtonType = ssbtStandard
Checked = False
GroupIndex = 0
ImageIndex = 55
Images = dmData.Images
LeftMargin = 4
ParentShowHint = False
ShowHint = True
Style = ssbsUser
ViewStyle = ssvsGlyphOnly
end
object imgFun: TImage
Left = 8
Top = 7
Width = 16
Height = 16
Transparent = True
end
object chbShowExcel: TcxCheckBox
Left = 3
Top = 335
Width = 301
Height = 24
Properties.DisplayUnchecked = 'False'
Properties.Caption = #1055#1086#1082#1072#1079#1072#1090#1100' '#1076#1086#1082#1091#1084#1077#1085#1090' '#1087#1086#1089#1083#1077' '#1086#1082#1086#1085#1095#1072#1085#1080#1103' '#1101#1082#1089#1087#1086#1088#1090#1072
State = cbsChecked
Style.StyleController = dmData.scMain
TabOrder = 0
ImeName = 'Russian'
end
object grdE: TssDBGrid
Left = 8
Top = 28
Width = 360
Height = 303
Hint = #1053#1072#1079#1074#1072#1085#1080#1077
DrawDragFrame = False
Bands = <
item
end>
DefaultLayout = True
HeaderPanelRowCount = 1
KeyField = 'colname'
SummaryGroups = <>
SummarySeparator = ', '
ParentShowHint = False
ShowHint = True
TabOrder = 1
OnMouseDown = grdEMouseDown
DataSource = srcCols
Filter.Criteria = {00000000}
HideFocusRect = True
LookAndFeel = lfUltraFlat
OptionsDB = [edgoCancelOnExit, edgoCanNavigation, edgoConfirmDelete, edgoLoadAllRecords, edgoUseBookmarks]
OptionsView = [edgoAutoWidth, edgoBandHeaderWidth, edgoHideFocusRect, edgoRowSelect, edgoUseBitmap]
OnColumnSorting = grdEColumnSorting
Anchors = [akLeft, akTop, akRight, akBottom]
LangManager = dmData.Lng
object colIndex: TdxDBGridColumn
Alignment = taCenter
Width = 30
BandIndex = 0
RowIndex = 0
OnGetText = colIndexGetText
end
object colName: TdxDBGridColumn
Tag = 1
Alignment = taLeftJustify
Caption = #1053#1072#1079#1074#1072#1085#1080#1077
HeaderAlignment = taCenter
Width = 250
BandIndex = 0
RowIndex = 0
FieldName = 'NAME'
end
object colColName: TdxDBGridColumn
Visible = False
BandIndex = 0
RowIndex = 0
FieldName = 'colname'
end
object colVisible: TdxDBGridImageColumn
Alignment = taRightJustify
HeaderAlignment = taCenter
MinWidth = 16
Width = 80
BandIndex = 0
RowIndex = 0
FieldName = 'vis'
Images = dmData.Images
ImageIndexes.Strings = (
'0'
'1'
'2'
'3'
'4'
'5'
'6'
'7'
'8'
'9'
'10'
'11'
'12'
'13'
'14'
'15'
'16'
'17'
'18'
'19'
'20'
'21'
'22'
'23'
'24'
'25'
'26'
'27'
'28'
'29'
'30'
'31'
'32'
'33'
'34'
'35'
'36'
'37'
'38'
'39'
'40'
'41'
'42'
'43'
'44'
'45'
'46'
'47'
'48'
'49'
'50'
'51'
'52'
'53'
'54'
'55'
'56'
'57'
'58'
'59'
'60'
'61'
'62'
'63'
'64'
'65'
'66'
'67'
'68'
'69'
'70'
'71'
'72'
'73'
'74'
'75'
'76'
'77'
'78'
'79'
'80'
'81'
'82'
'83'
'84'
'85'
'86'
'87'
'88'
'89'
'90'
'91'
'92'
'93'
'94'
'95'
'96'
'97'
'98'
'99'
'100'
'101'
'102'
'103'
'104'
'105'
'106'
'107'
'108'
'109'
'110'
'111'
'112'
'113'
'114'
'115'
'116'
'117'
'118'
'119'
'120'
'121'
'122'
'123'
'124'
'125'
'126'
'127'
'128'
'129'
'130'
'131'
'132'
'133'
'134'
'135'
'136'
'137'
'138'
'139'
'140'
'141'
'142'
'143'
'144'
'145'
'146'
'147'
'148'
'149'
'150'
'151'
'152'
'153'
'154'
'155'
'156'
'157'
'158'
'159'
'160'
'161'
'162'
'163'
'164'
'165'
'166'
'167'
'168'
'169'
'170'
'171'
'172'
'173'
'174'
'175'
'176'
'177'
'178'
'179'
'180'
'181'
'182'
'183'
'184'
'185'
'186'
'187'
'188'
'189'
'190'
'191'
'192'
'193'
'194'
'195'
'196'
'197'
'198'
'199'
'200'
'201'
'202'
'203'
'204'
'205'
'206')
Values.Strings = (
''
''
''
''
''
''
''
''
''
''
''
''
''
''
''
''
''
''
''
''
''
''
''
''
''
''
''
''
''
''
''
'1')
end
object colColName2: TdxDBGridColumn
Visible = False
BandIndex = 0
RowIndex = 0
FieldName = 'colname2'
end
end
end
object ActionList: TActionList
Images = dmData.Images
OnUpdate = ActionListUpdate
Left = 40
Top = 136
object aApply: TAction
Caption = #1055#1088#1080#1084#1077#1085#1080#1090#1100
end
object aOK: TAction
Caption = 'Export'
OnExecute = aOKExecute
end
object aCancel: TAction
Caption = #1054#1090#1084#1077#1085#1080#1090#1100
OnExecute = aCancelExecute
end
object aUp: TAction
ImageIndex = 56
OnExecute = aUpExecute
end
object aDown: TAction
ImageIndex = 55
OnExecute = aDownExecute
end
end
object mdCols: TssMemoryData
FieldDefs = <>
Left = 232
Top = 200
object mdColsname: TStringField
FieldName = 'name'
Size = 48
end
object mdColscolname: TStringField
FieldName = 'colname'
Size = 48
end
object mdColsvis: TIntegerField
FieldName = 'vis'
end
object mdColsen: TIntegerField
FieldName = 'en'
end
object mdColscolindex: TIntegerField
FieldName = 'colindex'
end
object mdColscolname2: TStringField
FieldName = 'colname2'
end
end
object srcCols: TDataSource
DataSet = mdCols
Left = 260
Top = 200
end
end
| 21.562925 | 230 | 0.450745 |
6ae895bcde2a89095e8be07fb089877bda9ce1b0 | 1,725 | dfm | Pascal | Projects/CL.Ag5/Source/_CommonSources/UUpdateAppForm.dfm | iclinicadoleite/controle-ag5 | 2e315c4a7c9bcb841a8d2f2390ae9d7c2c2cb721 | [
"Apache-2.0"
]
| 1 | 2020-05-07T07:51:27.000Z | 2020-05-07T07:51:27.000Z | Projects/CL.Ag5/Source/_CommonSources/UUpdateAppForm.dfm | iclinicadoleite/controle-ag5 | 2e315c4a7c9bcb841a8d2f2390ae9d7c2c2cb721 | [
"Apache-2.0"
]
| null | null | null | Projects/CL.Ag5/Source/_CommonSources/UUpdateAppForm.dfm | iclinicadoleite/controle-ag5 | 2e315c4a7c9bcb841a8d2f2390ae9d7c2c2cb721 | [
"Apache-2.0"
]
| 3 | 2020-02-17T18:01:52.000Z | 2020-05-07T07:51:28.000Z | object UpdateAppForm: TUpdateAppForm
AlignWithMargins = True
Left = 1207
Top = 679
Margins.Top = 10
Margins.Right = 10
BorderIcons = []
BorderStyle = bsNone
Caption = 'UpdateAppForm'
ClientHeight = 101
ClientWidth = 339
Color = clBlack
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
Position = poDesigned
OnCreate = FormCreate
OnShow = FormShow
DesignSize = (
339
101)
PixelsPerInch = 96
TextHeight = 13
object Panel1: TPanel
Left = 0
Top = 0
Width = 339
Height = 101
Anchors = [akRight, akBottom]
Color = clWhite
ParentBackground = False
TabOrder = 0
object LbInfo: TLabel
Left = 34
Top = 20
Width = 281
Height = 26
Caption =
'H'#225' uma nova vers'#227'o do sistema pronta para ser instalada. Deseja ' +
'instalar agora ?'
WordWrap = True
end
object Shape1: TShape
AlignWithMargins = True
Left = 6
Top = 6
Width = 327
Height = 89
Margins.Left = 5
Margins.Top = 5
Margins.Right = 5
Margins.Bottom = 5
Align = alClient
Brush.Style = bsClear
Pen.Color = 9474192
ExplicitLeft = -2
ExplicitTop = -2
ExplicitWidth = 339
ExplicitHeight = 102
end
object BtnYes: TBitBtn
Left = 85
Top = 57
Width = 75
Height = 25
Caption = 'Sim'
ModalResult = 1
TabOrder = 0
end
object BtnNo: TBitBtn
Left = 166
Top = 57
Width = 75
Height = 25
Caption = 'N'#227'o'
ModalResult = 2
TabOrder = 1
end
end
end
| 20.535714 | 86 | 0.582609 |
477ed9b0196978ca326b76ff08576a1020ef5324 | 7,074 | pas | Pascal | Source/SectorProperties.pas | damieng/DiskImageManager | 83dacaf8d817eccab16198e6a41532dbace5b0a4 | [
"Apache-2.0"
]
| 29 | 2015-01-17T10:24:09.000Z | 2022-01-31T19:55:17.000Z | Source/SectorProperties.pas | damieng/DiskImageManager | 83dacaf8d817eccab16198e6a41532dbace5b0a4 | [
"Apache-2.0"
]
| 1 | 2017-01-03T01:20:37.000Z | 2017-01-03T02:51:02.000Z | Source/SectorProperties.pas | damieng/DiskImageManager | 83dacaf8d817eccab16198e6a41532dbace5b0a4 | [
"Apache-2.0"
]
| 3 | 2017-11-13T14:30:48.000Z | 2021-06-03T16:05:38.000Z | unit SectorProperties;
{$MODE Delphi}
{
Disk Image Manager - Sector properties window
Copyright (c) Damien Guard. All rights reserved.
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
}
interface
uses
DskImage, Utils,
SysUtils, Classes, Forms, StdCtrls, ComCtrls, ExtCtrls, CheckLst, Dialogs;
type
{ TfrmSector }
TfrmSector = class(TForm)
bevIdentity: TBevel;
pnlTab: TPanel;
pnlButtons: TPanel;
pagTabs: TPageControl;
tabSector: TTabSheet;
btnOK: TButton;
btnCancel: TButton;
btnApply: TButton;
lblStatus: TLabel;
lblSize: TLabel;
lblImage: TLabel;
cklFDC2: TCheckListBox;
cklFDC1: TCheckListBox;
lblFDC1: TLabel;
lblFDC2: TLabel;
lblSectorID: TLabel;
edtSectorID: TEdit;
udSectorID: TUpDown;
cboStatus: TComboBox;
edtSize: TEdit;
udSize: TUpDown;
lblPhysical: TLabel;
edtImage: TEdit;
edtPhysical: TEdit;
bevDetails: TBevel;
bevFDC: TBevel;
lblFDC: TLabel;
lblDetails: TLabel;
lblIdentity: TLabel;
lblFill: TLabel;
edtFill: TEdit;
udFill: TUpDown;
lblFillHex: TLabel;
lblSizeBytes: TLabel;
lblPad: TLabel;
edtPad: TEdit;
udPad: TUpDown;
lblPadHex: TLabel;
lblFDCSize: TLabel;
edtFDCSize: TEdit;
udFDCSize: TUpDown;
procedure btnCancelClick(Sender: TObject);
procedure btnApplyClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure edtFillChange(Sender: TObject);
procedure cboStatusChange(Sender: TObject);
procedure edtSizeChange(Sender: TObject);
procedure edtPadChange(Sender: TObject);
private
FSector: TDSKSector;
SecStat: TDSKSectorStatus;
procedure MakeChanges;
procedure UpdateFill;
procedure UpdatePad;
public
constructor Create(AOwner: TComponent; Sector: TDSKSector); reintroduce;
procedure Refresh;
end;
var
frmSector: TfrmSector;
implementation
uses Main;
{$R *.lfm}
constructor TfrmSector.Create(AOwner: TComponent; Sector: TDSKSector);
begin
inherited Create(AOwner);
//udSize.Max := MaxSectorSize;
FSector := Sector;
Refresh;
Show;
end;
procedure TfrmSector.Refresh;
var
SIdx: TDSKSectorStatus;
FIdx: integer;
begin
// Physical
edtImage.Text := ExtractFileName(
FSector.ParentTrack.ParentSide.ParentDisk.ParentImage.FileName);
edtPhysical.Text := 'Side ' + IntToStr(FSector.Side + 1) + ' > Track ' +
IntToStr(FSector.Track) + ' > Sector ' +
IntToStr(FSector.Sector);
Caption := edtPhysical.Text;
// Details
udSectorID.Position := FSector.ID;
udSize.Position := FSector.DataSize;
if (FSector.GetFillByte >= 0) then
udFill.Position := FSector.ParentTrack.Filler
else
udFill.Position := FSector.GetFillByte;
udPad.Position := udFill.Position;
cboStatus.Items.Clear;
for SIdx := ssUnformatted to ssFormattedInUse do
cboStatus.Items.Add(DSKSectorStatus[SIdx]);
SecStat := FSector.Status;
cboStatus.ItemIndex := Ord(FSector.Status);
// FDC
for FIdx := 0 to 7 do
begin
cklFDC1.Checked[FIdx] :=
(FSector.FDCStatus[1] and Power2[FIdx + 1]) = Power2[FIdx + 1];
cklFDC2.Checked[FIdx] :=
(FSector.FDCStatus[2] and Power2[FIdx + 1]) = Power2[FIdx + 1];
end;
end;
procedure TfrmSector.btnCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfrmSector.btnApplyClick(Sender: TObject);
begin
MakeChanges;
end;
procedure TfrmSector.btnOKClick(Sender: TObject);
begin
MakeChanges;
Close;
end;
procedure TfrmSector.MakeChanges;
var
FIdx: integer;
OldLength: word;
SecData: array[0..MaxSectorSize] of byte;
begin
if frmMain.ConfirmChange('change', 'sector') then
with FSector do
begin
// Details
ID := udSectorID.Position;
// Status
if (SecStat = ssFormattedBlank) or (SecStat = ssFormattedFilled) then
FillSector(udFill.Position);
// Changing size?
if DataSize <> word(udSize.Position) then
begin
if (DataSize < word(udSize.Position)) and (DataSize > 0) then
begin
Move(Data, SecData, DataSize);
OldLength := DataSize;
DataSize := word(udSize.Position);
FillSector(udPad.Position);
Move(SecData, Data, OldLength);
end
else
begin
DataSize := udSize.Position;
end;
end;
// FDC data Size
if FDCSize <> byte(udFDCSize.Position) then
begin
FDCSize := byte(udFDCSize.Position);
end;
// FDC status
FDCStatus[1] := 0;
for FIdx := 0 to 7 do
if cklFDC1.Checked[FIdx] then
FDCStatus[1] := FDCStatus[1] + Power2[FIdx + 1];
FDCStatus[2] := 0;
for FIdx := 0 to 7 do
if cklFDC2.Checked[FIdx] then
FDCStatus[2] := FDCStatus[2] + Power2[FIdx + 1];
end;
frmMain.RefreshList;
end;
procedure TfrmSector.edtFillChange(Sender: TObject);
begin
lblFillHex.Caption := IntToHex(udFill.Position, 2);
end;
procedure TfrmSector.cboStatusChange(Sender: TObject);
begin
SecStat := TDSKSectorStatus(cboStatus.ItemIndex);
if (SecStat = ssFormattedInUse) and (FSector.Status <> ssFormattedInUse) then
begin
ShowMessage('Sector can not be made in-use when it was not previously');
cboStatus.ItemIndex := Ord(FSector.Status);
end;
if SecStat = ssUnformatted then
udSize.Position := 0
else
if udSize.Position = 0 then
if FSector.DataSize <> 0 then
udSize.Position := FSector.DataSize
else
udSize.Position := FSector.ParentTrack.SectorSize * 256;
UpdateFill;
end;
procedure TfrmSector.edtSizeChange(Sender: TObject);
begin
if (udSize.Position > 0) and (FSector.DataSize = 0) then
cboStatus.ItemIndex := Ord(ssFormattedBlank);
if udSize.Position = 0 then
cboStatus.ItemIndex := Ord(ssUnformatted);
UpdatePad;
end;
procedure TfrmSector.UpdatePad;
var
ShowPad: boolean;
begin
ShowPad := (word(udSize.Position) > FSector.DataSize) and (FSector.DataSize > 0);
lblPad.Visible := ShowPad;
edtPad.Visible := ShowPad;
udPad.Visible := ShowPad;
lblPadHex.Visible := ShowPad;
end;
procedure TfrmSector.UpdateFill;
var
ShowFill: boolean;
begin
ShowFill := ((SecStat = ssFormattedBlank) or (SecStat = ssFormattedFilled)) or
(word(udSize.Position) > FSector.DataSize);
if (cboStatus.ItemIndex = 1) then
udFill.Position := FSector.ParentTrack.Filler;
lblFill.Visible := ShowFill;
edtFill.Visible := ShowFill;
udFill.Visible := ShowFill;
lblFillHex.Visible := ShowFill;
end;
procedure TfrmSector.edtPadChange(Sender: TObject);
begin
lblPadHex.Caption := IntToHex(udPad.Position, 2);
end;
end.
| 25.354839 | 85 | 0.657619 |
f192fd6fb9a98aa3840abdbedaea3535a8fbdbc5 | 3,141 | pas | Pascal | DCPconst.pas | SnakeDoctor/DCPcrypt | f31981742bef7c91a56c36099488f1079206b0c8 | [
"MIT"
]
| 9 | 2015-03-15T07:38:08.000Z | 2021-07-21T15:34:19.000Z | DCPconst.pas | SnakeDoctor/DCPcrypt | f31981742bef7c91a56c36099488f1079206b0c8 | [
"MIT"
]
| null | null | null | DCPconst.pas | SnakeDoctor/DCPcrypt | f31981742bef7c91a56c36099488f1079206b0c8 | [
"MIT"
]
| 8 | 2015-05-15T12:37:13.000Z | 2020-04-30T02:51:11.000Z | {******************************************************************************}
{* DCPcrypt v2.0 written by David Barton (crypto@cityinthesky.co.uk) **********}
{******************************************************************************}
{* Constants for use with DCPcrypt ********************************************}
{******************************************************************************}
{* Copyright (c) 1999-2002 David Barton *}
{* Permission is hereby granted, free of charge, to any person obtaining a *}
{* copy of this software and associated documentation files (the "Software"), *}
{* to deal in the Software without restriction, including without limitation *}
{* the rights to use, copy, modify, merge, publish, distribute, sublicense, *}
{* and/or sell copies of the Software, and to permit persons to whom the *}
{* Software is furnished to do so, subject to the following conditions: *}
{* *}
{* The above copyright notice and this permission notice shall be included in *}
{* all copies or substantial portions of the Software. *}
{* *}
{* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *}
{* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *}
{* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *}
{* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *}
{* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *}
{* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *}
{* DEALINGS IN THE SOFTWARE. *}
{******************************************************************************}
unit DCPconst;
interface
{******************************************************************************}
const
{ Component registration }
DCPcipherpage = 'DCPciphers';
DCPhashpage = 'DCPhashes';
{ ID values }
DCP_rc2 = 1;
DCP_sha1 = 2;
DCP_rc5 = 3;
DCP_rc6 = 4;
DCP_blowfish = 5;
DCP_twofish = 6;
DCP_cast128 = 7;
DCP_gost = 8;
DCP_rijndael = 9;
DCP_ripemd160 = 10;
DCP_misty1 = 11;
DCP_idea = 12;
DCP_mars = 13;
DCP_haval = 14;
DCP_cast256 = 15;
DCP_md5 = 16;
DCP_md4 = 17;
DCP_tiger = 18;
DCP_rc4 = 19;
DCP_ice = 20;
DCP_thinice = 21;
DCP_ice2 = 22;
DCP_des = 23;
DCP_3des = 24;
DCP_tea = 25;
DCP_serpent = 26;
DCP_ripemd128 = 27;
DCP_sha256 = 28;
DCP_sha384 = 29;
DCP_sha512 = 30;
{******************************************************************************}
{******************************************************************************}
implementation
end.
| 42.445946 | 80 | 0.437759 |
f16679c075d7f93ce97f0c6f4bfc7d6a97dfcdf1 | 167 | pas | Pascal | compilador/in/teste6.pas | thiagorcdl/Compilador | 05cf9874c8dbd0ec89e826f392fb5b6b2dc50d31 | [
"BSD-2-Clause"
]
| null | null | null | compilador/in/teste6.pas | thiagorcdl/Compilador | 05cf9874c8dbd0ec89e826f392fb5b6b2dc50d31 | [
"BSD-2-Clause"
]
| null | null | null | compilador/in/teste6.pas | thiagorcdl/Compilador | 05cf9874c8dbd0ec89e826f392fb5b6b2dc50d31 | [
"BSD-2-Clause"
]
| null | null | null | program teste6 (input, output);
var i : integer;
begin
i := 10;
writeln(i);
writeln("como e bom poder ",i," escrever"," \'tudo\':\n\t",458*22)
end.
| 18.555556 | 70 | 0.562874 |
4766457ab6c9bd754ea8af2e2fa2b51a2c05f487 | 3,358 | pas | Pascal | API/DW.Androidapi.JNI.Lang.pas | barlone/Kastri | fb12d9eba242e67efd87eb1cb7acd123601a58ed | [
"MIT"
]
| 3 | 2021-02-11T21:54:24.000Z | 2021-08-11T12:51:05.000Z | API/DW.Androidapi.JNI.Lang.pas | talentedexpert0057/Kastri | aacc0db96957ea850abb7b407be5a0722462eb5a | [
"MIT"
]
| null | null | null | API/DW.Androidapi.JNI.Lang.pas | talentedexpert0057/Kastri | aacc0db96957ea850abb7b407be5a0722462eb5a | [
"MIT"
]
| null | null | null | unit DW.Androidapi.JNI.Lang;
{*******************************************************}
{ }
{ Kastri }
{ }
{ Delphi Worlds Cross-Platform Library }
{ }
{ Copyright 2020-2021 Dave Nottage under MIT license }
{ which is located in the root folder of this library }
{ }
{*******************************************************}
{$I DW.GlobalDefines.inc}
interface
uses
// Android
Androidapi.JNIBridge, Androidapi.JNI.JavaTypes;
type
Jlang_Process = interface;
JRuntime = interface;
Jlang_ProcessClass = interface(JObjectClass)
['{F57F6F1A-B4A2-4CD0-9ACB-06CBEBDCA561}']
{class} function init: Jlang_Process; cdecl;
end;
[JavaSignature('java/lang/Process')]
Jlang_Process = interface(JObject)
['{1B505DDF-5BE4-40C8-BC81-75AAA5158B02}']
procedure destroy; cdecl;
function exitValue: Integer; cdecl;
function getErrorStream: JInputStream; cdecl;
function getInputStream: JInputStream; cdecl;
function getOutputStream: JOutputStream; cdecl;
function waitFor: Integer; cdecl;
end;
TJlang_Process = class(TJavaGenericImport<Jlang_ProcessClass, Jlang_Process>) end;
JRuntimeClass = interface(JObjectClass)
['{5F789EE2-7243-47D9-B950-F8B638DD3076}']
{class} function getRuntime: JRuntime; cdecl;
{class} procedure runFinalizersOnExit(run: Boolean); cdecl;
end;
[JavaSignature('java/lang/Runtime')]
JRuntime = interface(JObject)
['{D56F91EA-6432-4391-ABBA-885F22C2E21A}']
procedure addShutdownHook(hook: JThread); cdecl;
function availableProcessors: Integer; cdecl;
procedure gc; cdecl;
function getLocalizedInputStream(stream: JInputStream): JInputStream; cdecl;
function getLocalizedOutputStream(stream: JOutputStream): JOutputStream; cdecl;
function exec(prog: JString): Jlang_Process; cdecl; overload;
function exec(prog: JString; envp: TJavaObjectArray<JString>): Jlang_Process; cdecl; overload;
function exec(prog: JString; envp: TJavaObjectArray<JString>; directory: JFile): Jlang_Process; cdecl; overload;
function exec(progArray: TJavaObjectArray<JString>): Jlang_Process; cdecl; overload;
function exec(progArray: TJavaObjectArray<JString>; envp: TJavaObjectArray<JString>): Jlang_Process; cdecl; overload;
function exec(progArray: TJavaObjectArray<JString>; envp: TJavaObjectArray<JString>; directory: JFile): Jlang_Process; cdecl; overload;
procedure exit(code: Integer); cdecl;
function freeMemory: Int64; cdecl;
procedure halt(code: Integer); cdecl;
procedure load(absolutePath: JString); cdecl;
procedure loadLibrary(nickname: JString); cdecl;
function maxMemory: Int64; cdecl;
function removeShutdownHook(hook: JThread): Boolean; cdecl;
procedure runFinalization; cdecl;
function totalMemory: Int64; cdecl;
procedure traceInstructions(enable: Boolean); cdecl;
procedure traceMethodCalls(enable: Boolean); cdecl;
end;
TJRuntime = class(TJavaGenericImport<JRuntimeClass, JRuntime>) end;
implementation
end.
| 41.45679 | 140 | 0.642347 |
83697ff62df9c1f59899bdc605f33ee45468a744 | 14,655 | dfm | Pascal | TORSUMY_Player/Main.dfm | delphi-pascal-archive/torsumy-player | eb33b0c45ac7f279e40a0abbc78167c04390d566 | [
"Unlicense"
]
| 1 | 2021-11-06T23:49:45.000Z | 2021-11-06T23:49:45.000Z | TORSUMY_Player/Main.dfm | delphi-pascal-archive/torsumy-player | eb33b0c45ac7f279e40a0abbc78167c04390d566 | [
"Unlicense"
]
| null | null | null | TORSUMY_Player/Main.dfm | delphi-pascal-archive/torsumy-player | eb33b0c45ac7f279e40a0abbc78167c04390d566 | [
"Unlicense"
]
| 1 | 2021-11-06T23:49:46.000Z | 2021-11-06T23:49:46.000Z | object Form1: TForm1
Left = 254
Top = 128
Cursor = crHandPoint
HorzScrollBar.Color = clBlack
HorzScrollBar.ParentColor = False
VertScrollBar.Color = clBlack
VertScrollBar.ParentColor = False
BorderIcons = [biSystemMenu, biMinimize]
BorderStyle = bsSingle
Caption = 'TORSUMY Player'
ClientHeight = 554
ClientWidth = 595
Color = clBlack
TransparentColor = True
TransparentColorValue = clFuchsia
Font.Charset = DEFAULT_CHARSET
Font.Color = clRed
Font.Height = -15
Font.Name = 'Arial'
Font.Style = [fsBold]
OldCreateOrder = False
Position = poScreenCenter
OnClose = FormClose
OnCreate = FormCreate
PixelsPerInch = 120
TextHeight = 18
object Label5: TLabel
Left = 476
Top = 289
Width = 90
Height = 18
Caption = ' '#1063#1040#1057#1058#1054#1058#1067
end
object Label6: TLabel
Left = 467
Top = 446
Width = 31
Height = 18
Caption = #1053#1048#1047
end
object Label7: TLabel
Left = 506
Top = 446
Width = 32
Height = 18
Caption = #1057#1056#1044
end
object Label8: TLabel
Left = 544
Top = 446
Width = 37
Height = 18
Caption = #1042#1067#1057
end
object Bevel1: TBevel
Left = 8
Top = 476
Width = 141
Height = 71
end
object Bevel2: TBevel
Left = 452
Top = 258
Width = 134
Height = 211
end
object Bevel3: TBevel
Left = 305
Top = 258
Width = 140
Height = 211
end
object Lire: TSpeedButton
Left = 8
Top = 8
Width = 63
Height = 24
Caption = #1057#1058#1040#1056#1058
Flat = True
OnClick = LireClick
end
object Resumer: TSpeedButton
Left = 149
Top = 8
Width = 86
Height = 24
Caption = #1042#1054#1047#1054#1041#1053#1054#1042#1048#1058#1068
Flat = True
Font.Charset = DEFAULT_CHARSET
Font.Color = clRed
Font.Height = -10
Font.Name = 'Arial'
Font.Style = [fsBold]
ParentFont = False
OnClick = ResumerClick
end
object Stopper: TSpeedButton
Left = 78
Top = 8
Width = 64
Height = 24
Caption = #1057#1058#1054#1055
Flat = True
OnClick = StopperClick
end
object Charger: TSpeedButton
Left = 250
Top = 10
Width = 87
Height = 20
Caption = #1054#1058#1050#1056#1067#1058#1068
Flat = True
OnClick = ChargerClick
end
object Bevel4: TBevel
Left = 156
Top = 258
Width = 142
Height = 211
end
object Bevel5: TBevel
Left = 8
Top = 258
Width = 141
Height = 211
end
object Bevel6: TBevel
Left = 156
Top = 476
Width = 142
Height = 71
end
object Label2: TLabel
Left = 56
Top = 43
Width = 97
Height = 18
Caption = #1043#1056#1054#1052#1050#1054#1057#1058#1068
Transparent = True
end
object Label4: TLabel
Left = 56
Top = 82
Width = 86
Height = 18
Hint = ' '
Caption = #1057#1050#1054#1056#1054#1057#1058#1068
ParentShowHint = False
ShowHint = True
Transparent = True
OnClick = Label4Click
end
object LabFreqS1: TLabel
Left = 211
Top = 97
Width = 8
Height = 18
Caption = '0'
Transparent = True
end
object LabVolS1: TLabel
Left = 211
Top = 59
Width = 8
Height = 18
Caption = '0'
Transparent = True
end
object Label9: TLabel
Left = 66
Top = 120
Width = 62
Height = 18
Caption = #1041#1040#1051#1040#1053#1057
Transparent = True
end
object LabBalanceS1: TLabel
Left = 211
Top = 136
Width = 8
Height = 18
Caption = '0'
Transparent = True
end
object Bevel7: TBevel
Left = 305
Top = 476
Width = 140
Height = 71
end
object Bevel8: TBevel
Left = 452
Top = 476
Width = 134
Height = 71
end
object Label11: TLabel
Left = 187
Top = 196
Width = 55
Height = 18
Caption = #1042#1056#1045#1052#1071
end
object TpsS1: TLabel
Left = 248
Top = 172
Width = 8
Height = 18
Caption = '0'
end
object Label1: TLabel
Left = 391
Top = 217
Width = 180
Height = 26
Caption = 'www.torsumy.at.ua'
Font.Charset = RUSSIAN_CHARSET
Font.Color = clFuchsia
Font.Height = -22
Font.Name = 'MS Sans Serif'
Font.Style = []
ParentFont = False
Transparent = False
end
object Label3: TLabel
Left = 84
Top = 217
Width = 108
Height = 26
Caption = 'TORSUMY'
Font.Charset = RUSSIAN_CHARSET
Font.Color = clFuchsia
Font.Height = -22
Font.Name = 'MS Sans Serif'
Font.Style = []
ParentFont = False
Transparent = False
end
object Label12: TLabel
Left = 17
Top = 217
Width = 54
Height = 26
Caption = 'Artem'
Font.Charset = RUSSIAN_CHARSET
Font.Color = clFuchsia
Font.Height = -22
Font.Name = 'MS Sans Serif'
Font.Style = []
ParentFont = False
Transparent = False
end
object Label13: TLabel
Left = 199
Top = 217
Width = 48
Height = 26
Caption = '2009'
Font.Charset = RUSSIAN_CHARSET
Font.Color = clFuchsia
Font.Height = -22
Font.Name = 'MS Sans Serif'
Font.Style = []
ParentFont = False
Transparent = False
end
object LabNomS1: TLabel
Left = 584
Top = 16
Width = 4
Height = 18
Alignment = taRightJustify
Transparent = False
end
object TpsSon1: TScrollBar
Left = 250
Top = 196
Width = 336
Height = 15
PageSize = 0
TabOrder = 0
OnScroll = TpsSon1Scroll
end
object Flanger: TCheckBox
Left = 312
Top = 265
Width = 116
Height = 24
Caption = #1060#1051#1069#1053#1046#1045#1056
TabOrder = 1
OnClick = FlangerClick
end
object Gargle: TCheckBox
Left = 184
Top = 484
Width = 96
Height = 24
Caption = #1060#1051#1040#1053#1045#1062
TabOrder = 2
OnClick = GargleClick
end
object Chorus: TCheckBox
Left = 164
Top = 265
Width = 93
Height = 24
Caption = #1061#1054#1056
TabOrder = 3
OnClick = ChorusClick
end
object Reverb: TCheckBox
Left = 463
Top = 500
Width = 114
Height = 21
Caption = #1056#1045#1042#1045#1056#1041#1045#1056#1040#1058#1054#1056
Font.Charset = DEFAULT_CHARSET
Font.Color = clRed
Font.Height = -10
Font.Name = 'Arial'
Font.Style = [fsBold]
ParentFont = False
TabOrder = 4
OnClick = ReverbClick
end
object Echo: TCheckBox
Left = 352
Top = 502
Width = 60
Height = 21
Caption = #1069#1061#1054
TabOrder = 5
OnClick = EchoClick
end
object Compressor: TCheckBox
Left = 16
Top = 484
Width = 129
Height = 24
Caption = #1050#1054#1052#1055#1056#1045#1057#1057#1048#1071
TabOrder = 6
OnClick = CompressorClick
end
object Disto: TCheckBox
Left = 16
Top = 265
Width = 120
Height = 22
Caption = #1048#1057#1050#1040#1046#1045#1053#1048#1045
TabOrder = 7
OnClick = DistoClick
end
object ParaEQLOW: TTrackBar
Left = 476
Top = 312
Width = 20
Height = 126
Max = 15
Min = -15
Orientation = trVertical
Frequency = 10
TabOrder = 8
ThumbLength = 7
OnChange = ParaEQLOWChange
end
object ParaEQMED: TTrackBar
Left = 515
Top = 312
Width = 19
Height = 126
Max = 15
Min = -15
Orientation = trVertical
Frequency = 10
TabOrder = 9
ThumbLength = 7
OnChange = ParaEQMEDChange
end
object ParaEQHIGH: TTrackBar
Left = 554
Top = 312
Width = 18
Height = 126
Max = 15
Min = -15
Orientation = trVertical
Frequency = 10
TabOrder = 10
ThumbLength = 7
OnChange = ParaEQHIGHChange
end
object Equaliseur: TCheckBox
Left = 461
Top = 264
Width = 123
Height = 20
Caption = #1069#1050#1042#1040#1051#1040#1049#1047#1045#1056
TabOrder = 11
OnClick = EqualiseurClick
end
object CompressorBar: TTrackBar
Left = 16
Top = 515
Width = 126
Height = 17
Max = 60
Frequency = 10
TabOrder = 12
ThumbLength = 7
OnChange = CompressorBarChange
end
object FWetS1: TTrackBar
Left = 320
Top = 296
Width = 18
Height = 158
Max = 99
Orientation = trVertical
TabOrder = 13
ThumbLength = 7
TickMarks = tmBoth
TickStyle = tsNone
OnChange = FlangerChange
end
object FDeptS1: TTrackBar
Left = 343
Top = 296
Width = 24
Height = 158
Max = 99
Orientation = trVertical
Position = 25
TabOrder = 14
ThumbLength = 7
TickMarks = tmBoth
TickStyle = tsNone
OnChange = FlangerChange
end
object FFeedS1: TTrackBar
Left = 367
Top = 296
Width = 29
Height = 158
Max = 99
Min = -99
Orientation = trVertical
TabOrder = 15
ThumbLength = 7
TickMarks = tmBoth
TickStyle = tsNone
OnChange = FlangerChange
end
object FFreqS1: TTrackBar
Left = 390
Top = 296
Width = 24
Height = 158
Orientation = trVertical
TabOrder = 16
ThumbLength = 7
TickMarks = tmBoth
TickStyle = tsNone
OnChange = FlangerChange
end
object FDelayS1: TTrackBar
Left = 414
Top = 296
Width = 24
Height = 158
Max = 4
Orientation = trVertical
TabOrder = 17
ThumbLength = 7
TickMarks = tmBoth
TickStyle = tsNone
OnChange = FlangerChange
end
object CdelayS1: TTrackBar
Left = 265
Top = 296
Width = 24
Height = 158
Max = 20
Orientation = trVertical
Position = 20
TabOrder = 18
ThumbLength = 7
TickMarks = tmBoth
TickStyle = tsNone
OnChange = ChorusChange
end
object CFreqS1: TTrackBar
Left = 242
Top = 296
Width = 16
Height = 158
Orientation = trVertical
Position = 10
TabOrder = 19
ThumbLength = 7
TickMarks = tmBoth
TickStyle = tsNone
OnChange = ChorusChange
end
object CfeedS1: TTrackBar
Left = 218
Top = 296
Width = 24
Height = 158
Max = 99
Min = -99
Orientation = trVertical
TabOrder = 20
ThumbLength = 7
TickMarks = tmBoth
TickStyle = tsNone
OnChange = ChorusChange
end
object CDeptS1: TTrackBar
Left = 196
Top = 296
Width = 15
Height = 158
Max = 99
Orientation = trVertical
Position = 75
TabOrder = 21
ThumbLength = 7
TickMarks = tmBoth
TickStyle = tsNone
OnChange = ChorusChange
end
object CWetS1: TTrackBar
Left = 172
Top = 296
Width = 16
Height = 158
Max = 99
Orientation = trVertical
Position = 99
TabOrder = 22
ThumbLength = 7
TickMarks = tmBoth
TickStyle = tsNone
OnChange = ChorusChange
end
object DiGainS1: TTrackBar
Left = 24
Top = 296
Width = 16
Height = 158
Orientation = trVertical
TabOrder = 23
ThumbLength = 7
OnChange = DistoChange
end
object DiEdgeS1: TTrackBar
Left = 44
Top = 296
Width = 20
Height = 158
Orientation = trVertical
TabOrder = 24
ThumbLength = 7
OnChange = DistoChange
end
object DiPEqCFreqS1: TTrackBar
Left = 71
Top = 296
Width = 13
Height = 158
Orientation = trVertical
TabOrder = 25
ThumbLength = 7
OnChange = DistoChange
end
object DiPostEqBS1: TTrackBar
Left = 94
Top = 296
Width = 16
Height = 158
Orientation = trVertical
TabOrder = 26
ThumbLength = 7
OnChange = DistoChange
end
object DiPreLowOffS1: TTrackBar
Left = 118
Top = 296
Width = 15
Height = 158
Orientation = trVertical
TabOrder = 27
ThumbLength = 7
OnChange = DistoChange
end
object GadwRateHzS1: TTrackBar
Left = 164
Top = 516
Width = 125
Height = 20
Frequency = 10
TabOrder = 28
ThumbLength = 7
OnChange = GadwRateHzS1Change
end
object Volume: TTrackBar
Left = 8
Top = 62
Width = 196
Height = 15
Max = 100
Frequency = 10
TabOrder = 29
ThumbLength = 7
OnChange = VolumeChange
end
object Frequence: TTrackBar
Left = 8
Top = 101
Width = 196
Height = 14
Frequency = 10
TabOrder = 30
ThumbLength = 7
OnChange = FrequenceChange
end
object Balance: TTrackBar
Left = 8
Top = 139
Width = 196
Height = 15
Frequency = 10
TabOrder = 31
ThumbLength = 7
OnChange = BalanceChange
end
object Bibliotheque: TListBox
Left = 250
Top = 37
Width = 336
Height = 127
Color = clBlack
Font.Charset = DEFAULT_CHARSET
Font.Color = clWhite
Font.Height = -13
Font.Name = 'Arial'
Font.Style = [fsBold]
ItemHeight = 16
ParentFont = False
PopupMenu = PopupMenu1
TabOrder = 32
OnClick = BibliothequeClick
end
object Bdd: TOpenDialog
Filter = #1052#1059#1047#1054#1053'|*.wav;*.mp3|'#1057#1055#1048#1057#1054#1050' '#1052#1059#1047#1054#1053#1040'|*.dat'
Left = 296
Top = 48
end
object Timer1: TTimer
OnTimer = Timer1Timer
Left = 264
Top = 48
end
object PopupMenu1: TPopupMenu
Left = 360
Top = 48
object Sauver: TMenuItem
Caption = '-='#1057#1054#1061#1056#1040#1053#1048#1058#1068' '#1057#1055#1048#1057#1054#1050'=-'
OnClick = SauverClick
end
object Effacer: TMenuItem
Caption = '-='#1054#1063#1048#1057#1058#1048#1058#1068' '#1057#1055#1048#1057#1054#1050'=-'
OnClick = EffacerClick
end
object Charge: TMenuItem
Caption = '-='#1054#1050#1056#1067#1058#1068' '#1057#1055#1048#1057#1054#1050'=-'
OnClick = ChargeClick
end
object Effacer1: TMenuItem
Caption = '-='#1059#1044#1040#1051#1048#1058#1068' '#1057#1055#1048#1057#1054#1050'=-'
OnClick = Effacer1Click
end
object TORSUMY: TMenuItem
Caption = '-=TORSUMYPlayer=-'
end
end
object BddS: TSaveDialog
Filter = #1057#1055#1048#1057#1054#1050'|*.dat'
Left = 328
Top = 48
end
end
| 21.086331 | 125 | 0.581372 |
85c3869ac93805e368832c0c37baf4ec83ec1c27 | 19,110 | pas | Pascal | library/wp/FHIR.WP.Icons.pas | danka74/fhirserver | 1fc53b6fba67a54be6bee39159d3db28d42eb8e2 | [
"BSD-3-Clause"
]
| null | null | null | library/wp/FHIR.WP.Icons.pas | danka74/fhirserver | 1fc53b6fba67a54be6bee39159d3db28d42eb8e2 | [
"BSD-3-Clause"
]
| null | null | null | library/wp/FHIR.WP.Icons.pas | danka74/fhirserver | 1fc53b6fba67a54be6bee39159d3db28d42eb8e2 | [
"BSD-3-Clause"
]
| null | null | null | Unit FHIR.WP.Icons;
{
Copyright (c) 2001+, Kestral Computing Pty Ltd (http://www.kestral.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
Interface
Uses
Windows, SysUtils, Vcl.Graphics, Forms,
fsl_base, fsl_graphics, fsl_utilities,
FHIR.Uix.Images, FHIR.WP.Widgets;
Type
TWPIconModule = Class(TFslObject)
Private
FImages : TUixImages;
FToolbarWidgetImageIndexArray : TWPToolbarWidgetImageArray;
FCURSOR_PEN : Integer;
FCURSOR_BOX : Integer;
FCURSOR_MARK : Integer;
FCURSOR_ZOOM : Integer;
FCURSOR_CIRCLE : Integer;
FCheck_Unchecked : TFslBitmapGraphic;
FCheck_Checked : TFslBitmapGraphic;
FCheck_Unchecked_High : TFslBitmapGraphic;
FCheck_Checked_High : TFslBitmapGraphic;
{$IFOPT C+}
Function INVALID : Integer; Overload;
{$ENDIF}
Public
constructor Create; Override;
destructor Destroy; Override;
Function NONE : Integer; Overload;
Function CUT : Integer; Overload;
Function Copy : Integer; Overload;
Function PASTE : Integer; Overload;
Function UNDO : Integer; Overload;
Function REDO : Integer; Overload;
Function SEARCH : Integer; Overload;
Function MACRO : Integer; Overload;
Function BOLD : Integer; Overload;
Function ITALIC : Integer; Overload;
Function UNDERLINE : Integer; Overload;
Function SUPERSCRIPT : Integer; Overload;
Function SUBSCRIPT : Integer; Overload;
Function ALIGN_LEFT : Integer; Overload;
Function ALIGN_CENTRE : Integer; Overload;
Function ALIGN_RIGHT : Integer; Overload;
Function ALIGN_JUSTIFY : Integer; Overload;
Function NUMBERS : Integer; Overload;
Function BULLETS : Integer; Overload;
Function INDENT : Integer; Overload;
Function OUTDENT : Integer; Overload;
Function INSERT_TABLE : Integer; Overload;
Function INSERT_IMAGE : Integer; Overload;
Function INSERT_PDF : Integer; Overload;
Function INSERT_TEMPLATE : Integer; Overload;
Function INSERT_PAGEBREAK : Integer; Overload;
Function INSERT_LINE : Integer; Overload;
Function SHOW_HINTS : Integer; Overload;
Function SPELLING : Integer; Overload;
Function FORMAT_FONT : Integer; Overload;
Function FORMAT_PARA : Integer; Overload;
Function PASTE_SPECIAL : Integer; Overload;
Function INSERT_FIELD : Integer; Overload;
Function INSERT_SECTION_FIELD : Integer; Overload;
Function INSERT_SYMBOL : Integer; Overload;
Function OBJECT_PROPERTIES : Integer; Overload;
Function FIELD_NEXT : Integer; Overload;
Function FIELD_PREVIOUS : Integer; Overload;
Function FIELD_DELETE : Integer; Overload;
Function COPIED_ROW_ABOVE : Integer; Overload;
Function COPIED_ROW_BELOW : Integer; Overload;
Function ROW_ABOVE : Integer; Overload;
Function ROW_BELOW : Integer; Overload;
Function SORT_TABLE : Integer; Overload;
Function COLUMN_LEFT : Integer; Overload;
Function COLUMN_RIGHT : Integer; Overload;
Function SELECT_ROW : Integer; Overload;
Function SELECT_TABLE : Integer; Overload;
Function DELETE_TABLE : Integer; Overload;
Function DELETE_ROW : Integer; Overload;
Function DELETE_COLUMN : Integer; Overload;
Function VOICE : Integer; Overload;
Function CONVERTTOTABLE : Integer; Overload;
Function CHANGE_CASE : Integer; Overload;
Function INSERT_HOTSPOT : Integer; Overload;
Function IMAGE_SELECT : Integer; Overload;
Function IMAGE_PEN : Integer; Overload;
Function IMAGE_BOX : Integer; Overload;
Function IMAGE_MARK : Integer; Overload;
Function IMAGE_ZOOM : Integer; Overload;
Function IMAGE_SELECT_ON: Integer; Overload;
Function IMAGE_PEN_ON: Integer; Overload;
Function IMAGE_BOX_ON: Integer; Overload;
Function IMAGE_MARK_ON: Integer; Overload;
Function IMAGE_ZOOM_ON: Integer; Overload;
Function IMAGE_CIRCLE: Integer; Overload;
Function IMAGE_CIRCLE_ON: Integer; Overload;
Function INSERT_COMMENT : Integer; Overload;
Function FIRST : Integer; Overload;
Function PREV : Integer; Overload;
Function NEXT : Integer; Overload;
Function LAST : Integer; Overload;
Function SNOMED : Integer; Overload;
Function EXT_NEW : Integer; Overload;
Function EXT_OPEN : Integer; Overload;
Function EXT_SAVE : Integer; Overload;
Function EXT_PRINT : Integer; Overload;
Function EXT_IMPORT : Integer; Overload;
Function EXT_EXPORT : Integer; Overload;
Function EXT_PAGEDESIGN : Integer; Overload;
Function EXT_EMAIL : Integer; Overload;
Property Images : TUixImages Read FImages;
Property TOOLBARWIDGET : TWPToolbarWidgetImageArray Read FToolbarWidgetImageIndexArray;
Function CURSOR_PEN : Integer;
Function CURSOR_BOX : Integer;
Function CURSOR_MARK : Integer;
Function CURSOR_ZOOM : Integer;
Function CURSOR_CIRCLE : Integer;
Property Check_Unchecked : TFslBitmapGraphic read FCheck_Unchecked;
Property Check_Checked : TFslBitmapGraphic read FCheck_Checked;
Property Check_Unchecked_High : TFslBitmapGraphic read FCheck_Unchecked_High;
Property Check_Checked_High : TFslBitmapGraphic read FCheck_Checked_High;
End;
Function WPIconModule : TWPIconModule;
Implementation
{$R resources\FHIR.WP.Icons.RES}
Constructor TWPIconModule.Create;
{$IFOPT C+}
Var
aIndex : TWPToolbarWidget;
{$ENDIF}
Begin
Inherited;
FImages := TUixImages.Create(Nil);
FImages.LoadBitmapFromResource('WPIconModuleBMP', clFuchsia);
FImages.Name := 'WPToolbarImageList';
{$IFOPT C+}
For aIndex := Low(FToolbarWidgetImageIndexArray) To High(FToolbarWidgetImageIndexArray) Do
FToolbarWidgetImageIndexArray[aIndex] := INVALID;
{$ENDIF}
FToolbarWidgetImageIndexArray[tbwCut] := CUT;
FToolbarWidgetImageIndexArray[tbwCopy] := Copy;
FToolbarWidgetImageIndexArray[tbwCopyAll] := None;
FToolbarWidgetImageIndexArray[tbwPaste] := PASTE;
FToolbarWidgetImageIndexArray[tbwPasteSpecial] := PASTE_SPECIAL;
FToolbarWidgetImageIndexArray[tbwUndo] := UNDO;
FToolbarWidgetImageIndexArray[tbwRedo] := REDO;
FToolbarWidgetImageIndexArray[tbwSearch] := SEARCH;
FToolbarWidgetImageIndexArray[tbwMacro] := MACRO;
FToolbarWidgetImageIndexArray[tbwPlayback] := VOICE;
FToolbarWidgetImageIndexArray[tbwSpelling] := SPELLING;
FToolbarWidgetImageIndexArray[tbwStyle] := NONE;
FToolbarWidgetImageIndexArray[tbwFontName] := NONE;
FToolbarWidgetImageIndexArray[tbwFontSize] := NONE;
FToolbarWidgetImageIndexArray[tbwFontColour] := NONE;
FToolbarWidgetImageIndexArray[tbwBackColor] := NONE;
FToolbarWidgetImageIndexArray[tbwBold] := BOLD;
FToolbarWidgetImageIndexArray[tbwItalic] := ITALIC;
FToolbarWidgetImageIndexArray[tbwUnderline] := UNDERLINE;
FToolbarWidgetImageIndexArray[tbwSuperscript] := SUPERSCRIPT;
FToolbarWidgetImageIndexArray[tbwChangeCase] := CHANGE_CASE;
FToolbarWidgetImageIndexArray[tbwSubscript] := SUBSCRIPT;
FToolbarWidgetImageIndexArray[tbwLeft] := ALIGN_LEFT;
FToolbarWidgetImageIndexArray[tbwCentre] := ALIGN_CENTRE;
FToolbarWidgetImageIndexArray[tbwRight] := ALIGN_RIGHT;
FToolbarWidgetImageIndexArray[tbwJustify] := ALIGN_JUSTIFY;
FToolbarWidgetImageIndexArray[tbwBullet] := BULLETS;
FToolbarWidgetImageIndexArray[tbwNumber] := NUMBERS;
FToolbarWidgetImageIndexArray[tbwIndent] := INDENT;
FToolbarWidgetImageIndexArray[tbwOutdent] := OUTDENT;
FToolbarWidgetImageIndexArray[tbwInsertTable] := INSERT_TABLE;
FToolbarWidgetImageIndexArray[tbwInsertImage] := INSERT_IMAGE;
FToolbarWidgetImageIndexArray[tbwInsertLine] := INSERT_LINE;
FToolbarWidgetImageIndexArray[tbwInsertPageBreak] := INSERT_PAGEBREAK;
FToolbarWidgetImageIndexArray[tbwEditHints] := SHOW_HINTS;
FToolbarWidgetImageIndexArray[tbwInsertField] := INSERT_FIELD;
FToolbarWidgetImageIndexArray[tbwInsertTemplate] := INSERT_TEMPLATE;
FToolbarWidgetImageIndexArray[tbwInsertSymbol] := INSERT_SYMBOL;
FToolbarWidgetImageIndexArray[tbwNew] := EXT_New;
FToolbarWidgetImageIndexArray[tbwOpen] := EXT_Open;
FToolbarWidgetImageIndexArray[tbwSave] := EXT_Save;
FToolbarWidgetImageIndexArray[tbwSaveAs] := EXT_Save;
FToolbarWidgetImageIndexArray[tbwPrint] := EXT_Print;
FToolbarWidgetImageIndexArray[tbwImport] := EXT_Import;
FToolbarWidgetImageIndexArray[tbwExport] := EXT_Export;
FToolbarWidgetImageIndexArray[tbwPageDesign] := EXT_PageDesign;
{$IFOPT C+}
For aIndex := Low(FToolbarWidgetImageIndexArray) To High(FToolbarWidgetImageIndexArray) Do
Begin
If FToolbarWidgetImageIndexArray[aIndex] = INVALID Then
Invariant('Create', StringFormat('Toolbar Widget ''%s'' does not have a specified image index.', [CAPTIONS_TOOLBARWIDGET[aIndex]]));
End;
{$ENDIF}
FCURSOR_PEN := 1001;
FCURSOR_BOX := FCURSOR_PEN + 1;
FCURSOR_MARK := FCURSOR_BOX + 1;
FCURSOR_ZOOM := FCURSOR_MARK + 1;
FCURSOR_CIRCLE := FCURSOR_ZOOM + 1;
Screen.Cursors[FCURSOR_PEN] := LoadCursor(hInstance, 'CURSOR_PEN');
Screen.Cursors[FCURSOR_BOX] := LoadCursor(hInstance, 'CURSOR_BOX');
Screen.Cursors[FCURSOR_MARK] := LoadCursor(hInstance, 'CURSOR_MARK');
Screen.Cursors[FCURSOR_ZOOM] := LoadCursor(hInstance, 'CURSOR_ZOOM');
Screen.Cursors[FCURSOR_CIRCLE] := LoadCursor(hInstance, 'CURSOR_CIRCLE');
FCheck_Unchecked := TFslBitmapGraphic.Create;
FCheck_Unchecked.LoadFromResource('check_unchecked');
FCheck_Unchecked.Transparent := true;
FCheck_Checked := TFslBitmapGraphic.Create;
FCheck_Checked.LoadFromResource('check_checked');
FCheck_Checked.Transparent := true;
FCheck_Unchecked_High := TFslBitmapGraphic.Create;
FCheck_Unchecked_High.LoadFromResource('check_unchecked_high');
FCheck_Unchecked_High.Transparent := true;
FCheck_Checked_High := TFslBitmapGraphic.Create;
FCheck_Checked_High.LoadFromResource('check_checked_high');
FCheck_Checked_High.Transparent := true;
End;
Destructor TWPIconModule.Destroy;
Begin
FCheck_Checked.Free;
FCheck_UnChecked.Free;
FCheck_Checked_High.Free;
FCheck_UnChecked_High.Free;
FImages.Free;
Inherited;
End;
{$IFOPT C+}
Function TWPIconModule.INVALID: Integer;
Begin
Result := -2;
End;
{$ENDIF}
Function TWPIconModule.NONE : Integer;
Begin
Result := -1;
End;
Function TWPIconModule.CUT : Integer;
Begin
Result := 0;
End;
Function TWPIconModule.Copy : Integer;
Begin
Result := 1;
End;
Function TWPIconModule.PASTE : Integer;
Begin
Result := 2;
End;
Function TWPIconModule.UNDO : Integer;
Begin
Result := 3;
End;
Function TWPIconModule.REDO : Integer;
Begin
Result := 4;
End;
Function TWPIconModule.SEARCH : Integer;
Begin
Result := 5;
End;
Function TWPIconModule.BOLD : Integer;
Begin
Result := 6;
End;
Function TWPIconModule.ITALIC : Integer;
Begin
Result := 7;
End;
Function TWPIconModule.UNDERLINE : Integer;
Begin
Result := 8;
End;
Function TWPIconModule.SUPERSCRIPT : Integer;
Begin
Result := 9;
End;
Function TWPIconModule.SUBSCRIPT : Integer;
Begin
Result := 10;
End;
Function TWPIconModule.ALIGN_LEFT : Integer;
Begin
Result := 11;
End;
Function TWPIconModule.ALIGN_CENTRE : Integer;
Begin
Result := 12;
End;
Function TWPIconModule.ALIGN_RIGHT : Integer;
Begin
Result := 13;
End;
Function TWPIconModule.ALIGN_JUSTIFY : Integer;
Begin
Result := 14;
End;
Function TWPIconModule.NUMBERS : Integer;
Begin
Result := 15;
End;
Function TWPIconModule.BULLETS : Integer;
Begin
Result := 16;
End;
Function TWPIconModule.INDENT : Integer;
Begin
Result := 17;
End;
Function TWPIconModule.OUTDENT : Integer;
Begin
Result := 18;
End;
Function TWPIconModule.INSERT_TABLE : Integer;
Begin
Result := 19;
End;
Function TWPIconModule.INSERT_IMAGE : Integer;
Begin
Result := 20;
End;
Function TWPIconModule.INSERT_PAGEBREAK : Integer;
Begin
Result := 21;
End;
function TWPIconModule.INSERT_PDF: Integer;
begin
result := 79;
end;
Function TWPIconModule.INSERT_LINE : Integer;
Begin
Result := 22;
End;
Function TWPIconModule.SHOW_HINTS : Integer;
Begin
Result := 23;
End;
Function TWPIconModule.SPELLING : Integer;
Begin
Result := 24;
End;
Function TWPIconModule.FORMAT_FONT : Integer;
Begin
Result := 25;
End;
Function TWPIconModule.FORMAT_PARA : Integer;
Begin
Result := 26;
End;
Function TWPIconModule.PASTE_SPECIAL : Integer;
Begin
Result := 27;
End;
Function TWPIconModule.INSERT_FIELD : Integer;
Begin
Result := 28;
End;
Function TWPIconModule.INSERT_SYMBOL : Integer;
Begin
Result := 45;
End;
Function TWPIconModule.OBJECT_PROPERTIES : Integer;
Begin
Result := 29;
End;
Function TWPIconModule.FIELD_NEXT : Integer;
Begin
Result := 30;
End;
Function TWPIconModule.FIELD_PREVIOUS : Integer;
Begin
Result := 31;
End;
Function TWPIconModule.FIELD_DELETE : Integer;
Begin
Result := 32;
End;
Function TWPIconModule.COPIED_ROW_ABOVE : Integer;
Begin
Result := 33;
End;
Function TWPIconModule.COPIED_ROW_BELOW : Integer;
Begin
Result := 34;
End;
Function TWPIconModule.ROW_ABOVE : Integer;
Begin
Result := 35;
End;
Function TWPIconModule.ROW_BELOW : Integer;
Begin
Result := 36;
End;
Function TWPIconModule.SORT_TABLE : Integer;
Begin
Result := 37;
End;
Function TWPIconModule.COLUMN_LEFT : Integer;
Begin
Result := 38;
End;
Function TWPIconModule.COLUMN_RIGHT : Integer;
Begin
Result := 39;
End;
Function TWPIconModule.SELECT_ROW : Integer;
Begin
Result := 40;
End;
Function TWPIconModule.SELECT_TABLE : Integer;
Begin
Result := 41;
End;
Function TWPIconModule.DELETE_TABLE : Integer;
Begin
Result := 42;
End;
Function TWPIconModule.DELETE_ROW : Integer;
Begin
Result := 43;
End;
Function TWPIconModule.DELETE_COLUMN : Integer;
Begin
Result := 44;
End;
Function TWPIconModule.VOICE : Integer;
Begin
Result := 45;
End;
Function TWPIconModule.CONVERTTOTABLE : Integer;
Begin
Result := 46;
End;
Function TWPIconModule.MACRO : Integer;
Begin
Result := 47;
End;
Function TWPIconModule.INSERT_SECTION_FIELD : Integer;
Begin
Result := 48;
End;
Function TWPIconModule.INSERT_TEMPLATE: Integer;
Begin
Result := 49;
End;
Function TWPIconModule.CHANGE_CASE: Integer;
Begin
Result := 50;
End;
Function TWPIconModule.INSERT_HOTSPOT: Integer;
Begin
Result := 51;
End;
Function TWPIconModule.IMAGE_SELECT : Integer;
Begin
Result := 52;
End;
Function TWPIconModule.IMAGE_PEN : Integer;
Begin
Result := 53;
End;
Function TWPIconModule.IMAGE_BOX : Integer;
Begin
Result := 54;
End;
Function TWPIconModule.IMAGE_MARK : Integer;
Begin
Result := 55;
End;
Function TWPIconModule.IMAGE_ZOOM : Integer;
Begin
Result := 56;
End;
Function TWPIconModule.IMAGE_SELECT_ON: Integer;
Begin
Result := 57;
End;
Function TWPIconModule.IMAGE_PEN_ON: Integer;
Begin
Result := 58;
End;
Function TWPIconModule.IMAGE_BOX_ON: Integer;
Begin
Result := 59;
End;
Function TWPIconModule.IMAGE_MARK_ON: Integer;
Begin
Result := 60;
End;
Function TWPIconModule.IMAGE_ZOOM_ON: Integer;
Begin
Result := 61;
End;
function TWPIconModule.IMAGE_CIRCLE: Integer;
begin
Result := 62;
end;
function TWPIconModule.IMAGE_CIRCLE_ON: Integer;
begin
Result := 63;
end;
function TWPIconModule.INSERT_COMMENT: Integer;
begin
Result := 64;
end;
function TWPIconModule.FIRST: Integer;
begin
Result := 65;
end;
function TWPIconModule.LAST: Integer;
begin
Result := 66;
end;
function TWPIconModule.NEXT: Integer;
begin
Result := 67;
end;
function TWPIconModule.PREV: Integer;
begin
Result := 68;
end;
function TWPIconModule.SNOMED: Integer;
begin
Result := 69;
end;
Function TWPIconModule.EXT_NEW : Integer;
Begin
Result := 70;
End;
Function TWPIconModule.EXT_OPEN : Integer;
Begin
Result := 71;
End;
Function TWPIconModule.EXT_SAVE : Integer;
Begin
Result := 72;
End;
Function TWPIconModule.EXT_PRINT : Integer;
Begin
Result := 73;
End;
Function TWPIconModule.EXT_IMPORT : Integer;
Begin
Result := 74;
End;
Function TWPIconModule.EXT_EXPORT : Integer;
Begin
Result := 75;
End;
Function TWPIconModule.EXT_PAGEDESIGN : Integer;
Begin
Result := 76;
End;
Function TWPIconModule.EXT_EMAIL : Integer;
Begin
Result := 77;
End;
Var
gWPIconModule : TWPIconModule = Nil;
Function WPIconModule : TWPIconModule;
Begin
If Not Assigned(gWPIconModule) Then
gWPIconModule := TWPIconModule.Create;
Result := gWPIconModule;
End;
function TWPIconModule.CURSOR_BOX: Integer;
begin
Result := FCURSOR_BOX;
end;
function TWPIconModule.CURSOR_MARK: Integer;
begin
result := FCURSOR_MARK;
end;
function TWPIconModule.CURSOR_PEN: Integer;
begin
result := FCURSOR_PEN;
end;
function TWPIconModule.CURSOR_ZOOM: Integer;
begin
result := FCURSOR_ZOOM;
end;
function TWPIconModule.CURSOR_CIRCLE: Integer;
begin
result := FCURSOR_CIRCLE;
end;
Initialization
Finalization
gWPIconModule.Free;
gWPIconModule:= Nil;
End.
| 24.159292 | 139 | 0.720984 |
6a979265ac7acdd7c56b451c6c44989a9dcddbbb | 89,268 | pas | Pascal | MozaaEXT_DOS_Emulator/IODEV/vga.pas | delphi-pascal-archive/mozaa-ext-dos-emulator | 392778470d9a0a612de90bf78bfd7f6b29535ade | [
"Unlicense"
]
| null | null | null | MozaaEXT_DOS_Emulator/IODEV/vga.pas | delphi-pascal-archive/mozaa-ext-dos-emulator | 392778470d9a0a612de90bf78bfd7f6b29535ade | [
"Unlicense"
]
| null | null | null | MozaaEXT_DOS_Emulator/IODEV/vga.pas | delphi-pascal-archive/mozaa-ext-dos-emulator | 392778470d9a0a612de90bf78bfd7f6b29535ade | [
"Unlicense"
]
| null | null | null |
(* ***** *)
unit vga;
interface
uses Config, iodev, cmos;
const
VGA_MEMORY_SIZE = 256 * 1024;
{$if BX_SUPPORT_VBE=1}
VBE_DISPI_TOTAL_VIDEO_MEMORY_MB = 4;
VBE_DISPI_BANK_ADDRESS = $A0000;
VBE_DISPI_BANK_SIZE_KB = 54;
VBE_DISPI_MAX_XRES = 1024;
VBE_DISPI_MAX_YRES = 768;
VBE_DISPI_IOPORT_INDEX = $FF80;
VBE_DISPI_IOPORT_DATA = $FF81;
VBE_DISPI_INDEX_ID = $0;
VBE_DISPI_INDEX_XRES = $1;
VBE_DISPI_INDEX_YRES = $2;
VBE_DISPI_INDEX_BPP = $3;
VBE_DISPI_INDEX_ENABLE = $4;
VBE_DISPI_INDEX_BANK = $5;
VBE_DISPI_ID0 = $B0C0;
VBE_DISPI_BPP_8 = $0;
// The following is not support yet, but just for reference available.
// VBE_DISPI_BPP_RGB565 $1
// VBE_DISPI_BPP_RGB555 $2
VBE_DISPI_DISABLED = $00;
VBE_DISPI_ENABLED = $01;
BX_MAX_XRES = VBE_DISPI_MAX_XRES;
BX_MAX_YRES = VBE_DISPI_MAX_YRES;
{$else}
BX_MAX_XRES = 640;
BX_MAX_YRES = 480;
{$ifend} //BX_SUPPORT_VBE
//CGA_TEXT_ADDR(row, column) ($18000 + ((row)*80 + (column))*2)
X_TILESIZE = 16;
Y_TILESIZE = 16;
BX_NUM_X_TILES = (BX_MAX_XRES div X_TILESIZE);
BX_NUM_Y_TILES = (BX_MAX_YRES div Y_TILESIZE);
// Support varying number of rows of text. self used to
// be limited to only 25 lines.
BX_MAX_TEXT_LINES = 260;
type
pbx_vga_c=^bx_vga_c;
bx_vga_c = class
public
s : record
misc_output : record
color_emulation:Bool; // 1=color emulation, base address = 3Dx
// 0=mono emulation, base address = 3Bx
enable_ram:Bool; // enable CPU access to video memory if set
clock_select:Bit8u; // 0=25Mhz 1=28Mhz
select_high_bank:Bool; // when in odd/even modes, select
// high 64k bank if set
horiz_sync_pol:Bool; // bit6: negative if set
vert_sync_pol:Bool; // bit7: negative if set
// bit7,bit6 represent number of lines on display:
// 0 = reserved
// 1 = 400 lines
// 2 = 350 lines
// 3 - 480 lines
end;
CRTC : record
address:Bit8u;
reg:array[0..$19] of Bit8u;
end;
attribute_ctrl:record
flip_flop:Bool; (* 0 = address, 1 = data-write *)
address:unsigned; (* register number *)
video_enabled:Bool;
palette_reg:array[0..16] of Bit8u;
overscan_color:Bit8u;
color_plane_enable:Bit8u;
horiz_pel_panning:Bit8u;
color_select:Bit8u;
mode_ctrl : record
graphics_alpha:Bool;
display_type:Bool;
enable_line_graphics:Bool;
blink_intensity:Bool;
pixel_panning_compat:Bool;
pixel_clock_select:Bool;
internal_palette_size:Bool;
end;
end;
pel:record
write_data_register:Bit8u;
write_data_cycle:Bit8u; (* 0, 1, 2 *)
read_data_register:Bit8u;
read_data_cycle:Bit8u; (* 0, 1, 2 *)
data:array[0..256] of record
red:Bit8u;
green:Bit8u;
blue:Bit8u;
end;
mask:Bit8u;
end;
graphics_ctrl : record
index:Bit8u;
set_reset:Bit8u;
enable_set_reset:Bit8u;
color_compare:Bit8u;
data_rotate:Bit8u;
raster_op:Bit8u;
read_map_select:Bit8u;
write_mode:Bit8u;
read_mode:Bool;
odd_even:Bool;
chain_odd_even:Bool;
shift_reg:Bit8u;
graphics_alpha:Bool;
memory_mapping:Bit8u; (* 0 = use A0000-BFFFF
* 1 = use A0000-AFFFF EGA/VGA graphics modes
* 2 = use B0000-B7FFF Monochrome modes
* 3 = use B8000-BFFFF CGA modes
*)
color_dont_care:Bit8u;
bitmask:Bit8u;
latch:array[0..4] of Bit8u;
end;
sequencer : record
index:Bit8u;
map_mask:Bit8u;
map_mask_bit:array[0..4] of bit8u;
bit0:Bool;
bit1:Bool;
reg1:Bit8u;
char_map_select:Bit8u;
extended_mem:Bool;
odd_even:Bool;
chain_four:Bool;
end;
vga_mem_updated:Bool;
x_tilesize:unsigned;
y_tilesize:unsigned;
scan_bits:unsigned;
vga_tile_updated:array[0..BX_NUM_X_TILES,0..BX_NUM_Y_TILES] of Bool;
vga_memory:array[0..VGA_MEMORY_SIZE] of Bit8u;
text_snapshot:array[0..2 * 80 * BX_MAX_TEXT_LINES] of bit8u; // current text snapshot
horiz_tick:unsigned;
vert_tick:unsigned;
rgb:array[0..3 * 256] of Bit8u;
tile:array[0..X_TILESIZE * Y_TILESIZE] of Bit8u;
{$if BX_SUPPORT_VBE=1}
vbe_memory:array[0..VBE_DISPI_TOTAL_VIDEO_MEMORY_MB *1024 * 1024] of Bit8u;
vbe_xres:Bit16u;
vbe_yres:Bit16u;
vbe_bpp:Bit16u;
vbe_bank:Bit16u;
vbe_enabled:Bool;
vbe_curindex:Bit16u;
vbe_visable_screen_size:Bit32u; // in bytes
{$ifend}
end;
devices:pbx_devices_c;
constructor Create;
//destructor Destroy; override;
procedure init(d:pbx_devices_c ; cmos:pbx_cmos_c);
function mem_read(addr:Bit32u):Bit8u;
// Note: either leave value of type Bit8u, or mask it when
// used to 8 bits, in memory.cc
procedure mem_write(addr:Bit32u; value:Bit8u);
{$if BX_SUPPORT_VBE=1}
function vbe_mem_read(addr:Bit32u):bit8u;
procedure vbe_mem_write(addr:Bit32u; value:Bit8u);
{$ifend}
//procedure redraw_area(x0:unsigned; y0:unsigned; width:unsigned; height:unsigned);
private
function read_handler(self_ptr:pointer; address:Bit32u; io_len:unsigned):Bit32u;
procedure write_handler(self_ptr:Pointer; address:Bit32u; dvalue:Bit32u; io_len:unsigned);
class procedure write_handler_no_log(self_ptr:Pointer; address:Bit32u; dvalue:Bit32u; io_len:unsigned);
{$if BX_SUPPORT_VBE=1}
function vbe_read_handler(self_ptr:Pointer; address: Bit32u; io_len:unsigned):Bit32u;
procedure vbe_write_handler(self_ptr:pointer; address:Bit32u; value:Bit32u; io_len:unsigned);
{$ifend}
{$if BX_USE_VGA_SMF=0}
Bit32u read(Bit32u address, unsigned io_len);
void write(Bit32u address, Bit32u value, unsigned io_len, Boolean no_log);
{$else}
procedure write(address:Bit32u; value:Bit32u; io_len:unsigned; no_log:Bool);
{$ifend}
{$if BX_SUPPORT_VBE=1}
{$if BX_USE_VGA_SMF=0}
Bit32u vbe_read(Bit32u address, unsigned io_len);
void vbe_write(Bit32u address, Bit32u value, unsigned io_len, Boolean no_log);
{$else}
//procedure vbe_write(address:Bit32u; value:Bit32u; io_len:unsigned; no_log:Bool);
{$ifend}
{$ifend}
public
timer_id:Integer;
procedure timer_handler(self_ptr:pointer);
procedure timer;
procedure set_update_interval (interval:unsigned);
//procedure get_text_snapshot(Bit8u **text_snapshot, unsigned *txHeight,
// unsigned *txWidth);
procedure update;
//procedure dump_status;
procedure determine_screen_dimensions(piHeight:punsigned;piWidth:punsigned);
end;
var
bx_vga:bx_vga_c;
old_iHeight, old_iWidth:unsigned ;
function SetEvent(hEvent: THandle): BOOL; stdcall;
function SetEvent; external 'kernel32.dll' name 'SetEvent';
implementation
uses Service, SysUtils, cpu, Gui32;
function CGA_TEXT_ADDR(row:Integer; column:Integer):Integer;
begin
Result:=($18000 + ((row)*80 + (column))*2);
end;
constructor bx_vga_c.Create;
begin
old_iHeight := 0; old_iWidth := 0;
self.s.vga_mem_updated := 0;
self.s.x_tilesize := X_TILESIZE;
self.s.y_tilesize := Y_TILESIZE;
//self.put('VGA');
end;
procedure bx_vga_c.init(d:pbx_devices_c ; cmos:pbx_cmos_c);
var
i:unsigned;
x,y:unsigned;
addr:unsigned;
begin
self.devices := d;
addr:=$03b4;
while addr<=$03B5 do
begin
self.devices^.register_io_read_handler(self, read_handler,
addr, 'vga video');
self.devices^.register_io_write_handler(self, write_handler,
addr, 'vga video');
Inc(Addr);
end;
addr:=$03BA;
while addr<=$03BA do
begin
self.devices^.register_io_read_handler(self, read_handler,
addr, 'vga video');
self.devices^.register_io_write_handler(self, write_handler,
addr, 'vga video');
Inc(Addr);
end;
addr:=$03C0;
while addr<=$03CF do
begin
self.devices^.register_io_read_handler(self, read_handler,
addr, 'vga video');
self.devices^.register_io_write_handler(self, write_handler,
addr, 'vga video');
Inc(Addr);
end;
addr:=$03D4;
while addr<=$03D5 do
begin
self.devices^.register_io_read_handler(self, read_handler,
addr, 'vga video');
self.devices^.register_io_write_handler(self, write_handler,
addr, 'vga video');
Inc(Addr);
end;
addr:=$03DA;
while addr<=$03DA do
begin
self.devices^.register_io_read_handler(self, read_handler,
addr, 'vga video');
self.devices^.register_io_write_handler(self, write_handler,
addr, 'vga video');
Inc(Addr);
end;
self.s.misc_output.color_emulation := 1;
self.s.misc_output.enable_ram := 1;
self.s.misc_output.clock_select := 0;
self.s.misc_output.select_high_bank := 0;
self.s.misc_output.horiz_sync_pol := 1;
self.s.misc_output.vert_sync_pol := 1;
self.s.CRTC.address := 0;
self.s.attribute_ctrl.mode_ctrl.graphics_alpha := 0;
self.s.attribute_ctrl.mode_ctrl.display_type := 0;
self.s.attribute_ctrl.mode_ctrl.enable_line_graphics := 1;
self.s.attribute_ctrl.mode_ctrl.blink_intensity := 0;
self.s.attribute_ctrl.mode_ctrl.pixel_panning_compat := 0;
self.s.attribute_ctrl.mode_ctrl.pixel_clock_select := 0;
self.s.attribute_ctrl.mode_ctrl.internal_palette_size := 0;
self.s.scan_bits:=640;
i:=0;
i:=0;
while i < $18 do
begin
self.s.CRTC.reg[i] := 0;
Inc(I);
end;
self.s.CRTC.address := 0;
self.s.attribute_ctrl.flip_flop := 0;
self.s.attribute_ctrl.address := 0;
self.s.attribute_ctrl.video_enabled := 1;
i:=0;
while i < 16 do
begin
self.s.attribute_ctrl.palette_reg[i] := 0;
Inc(I);
end;
self.s.attribute_ctrl.overscan_color := 0;
self.s.attribute_ctrl.color_plane_enable := $0f;
self.s.attribute_ctrl.horiz_pel_panning := 0;
self.s.attribute_ctrl.color_select := 0;
I:=0;
while i < 256 do
begin
self.s.pel.data[i].red := 0;
self.s.pel.data[i].green := 0;
self.s.pel.data[i].blue := 0;
Inc(i);
end;
self.s.pel.write_data_register := 0;
self.s.pel.write_data_cycle := 0;
self.s.pel.read_data_register := 0;
self.s.pel.read_data_cycle := 0;
self.s.pel.mask := $ff;
self.s.graphics_ctrl.index := 0;
self.s.graphics_ctrl.set_reset := 0;
self.s.graphics_ctrl.enable_set_reset := 0;
self.s.graphics_ctrl.color_compare := 0;
self.s.graphics_ctrl.data_rotate := 0;
self.s.graphics_ctrl.raster_op := 0;
self.s.graphics_ctrl.read_map_select := 0;
self.s.graphics_ctrl.write_mode := 0;
self.s.graphics_ctrl.read_mode := 0;
self.s.graphics_ctrl.odd_even := 0;
self.s.graphics_ctrl.chain_odd_even := 0;
self.s.graphics_ctrl.shift_reg := 0;
self.s.graphics_ctrl.graphics_alpha := 0;
self.s.graphics_ctrl.memory_mapping := 2; // monochrome text mode
self.s.graphics_ctrl.color_dont_care := 0;
self.s.graphics_ctrl.bitmask := 0;
i:=0;
while i < 4 do
begin
self.s.graphics_ctrl.latch[i] := 0;
Inc(i);
end;
self.s.sequencer.index := 0;
self.s.sequencer.map_mask := 0;
i:=0;
while i < 4 do
begin
self.s.sequencer.map_mask_bit[i] := 0;
Inc(i);
end;
self.s.sequencer.bit0 := 0;
self.s.sequencer.bit1 := 0;
self.s.sequencer.reg1 := 0;
self.s.sequencer.char_map_select := 0;
self.s.sequencer.extended_mem := 1; // display mem greater than 64K
self.s.sequencer.odd_even := 1; // use sequential addressing mode
self.s.sequencer.chain_four := 0; // use map mask and read map select
FillChar(self.s.vga_memory, sizeof(self.s.vga_memory), 0);
self.s.vga_mem_updated := 0;
for y:=0 to 480 div Y_TILESIZE do
for x:=0 to 640 div X_TILESIZE do
self.s.vga_tile_updated[x,y] := 0;
//begin
(* ??? should redo self to pass X args *)
//bx_gui.init(1, @argv[0], self.s.x_tilesize, self.s.y_tilesize); !!!
//end;
BX_INFO(Format('interval:=%u',[2000]));
self.timer_id := bx_pc_system.register_timer(@bx_vga, timer_handler,
30000, 1, 1);
cmos^.s.reg[$14] := (cmos^.s.reg[$14] and $cf) or $00; (* video card with BIOS ROM *)
self.s.horiz_tick := 0;
self.s.vert_tick := 0;
{$if BX_SUPPORT_VBE=1}
// The following is for the vbe display extension
// FIXME: change $ff80 and $ff81 into some nice constants
addr:=$ff80;
while addr<=$ff81 do
begin
self.devices^.register_io_read_handler(self, vbe_read_handler,
addr, 'vga video');
self.devices^.register_io_write_handler(self, vbe_write_handler,
addr, 'vga video');
Inc(addr);
end;
self.s.vbe_xres:=640;
self.s.vbe_yres:=400;
self.s.vbe_bpp:=8;
self.s.vbe_bank:=0;
self.s.vbe_enabled:=0;
self.s.vbe_curindex:=0;
BX_INFO(('VBE Bochs Display Extension Enabled'));
{$ifend}
end;
procedure bx_vga_c.determine_screen_dimensions(piHeight:punsigned;piWidth:punsigned);
var
ai:array[0..$20] of integer;
i:integer;
begin
self.s.scan_bits:=640;
i:=0;
while i < $20 do
begin
ai[i] := self.s.CRTC.reg[i];
Inc(i);
end;
(*
switch ( ( self.s.misc_output.vert_sync_pol shl 1)orself.s.misc_output.horiz_sync_pol )
begin
case 0: *piHeight := 200; break;
case 1: *piHeight := 400; break;
case 2: *piHeight := 350; break;
case 3: *piHeight := 480; break;
end;
*)
if ( self.s.graphics_ctrl.shift_reg = 0 ) then
begin
piWidth^ := 640;
piHeight^ := 480;
if ( self.s.CRTC.reg[6] = $BF ) then
begin
if ((self.s.CRTC.reg[23] = $A3) and (self.s.CRTC.reg[20] = $40) and
(self.s.CRTC.reg[9] = $41)) then
begin
piWidth^ := 320;
piHeight^ := 240;
end;
if ((self.s.CRTC.reg[23] = $E3) and (self.s.CRTC.reg[20] = $F) and
(self.s.CRTC.reg[9] = $40)) then
begin
piWidth^ := 640;
piHeight^ := 352;
end;
if ((self.s.CRTC.reg[23] = $E3) and (self.s.CRTC.reg[20] = 0) and
(self.s.CRTC.reg[9] = $C0)) then
begin
if (self.s.CRTC.reg[19] = $14) then
begin
self.s.scan_bits:=320;
piWidth^ := 320;
piHeight^ := 192;
end
else
begin
piWidth^ := 640;
piHeight^ := 208;
end;
end;
end;
end
else if ( self.s.graphics_ctrl.shift_reg = 2 ) then
begin
piWidth^ := 320;
if ( self.s.sequencer.chain_four )<>0 then
begin
piHeight^ := 208;
end
else
begin
piHeight^ := 240;
if ((self.s.CRTC.reg[23] = $E3) and (self.s.CRTC.reg[20] = 0) and
(self.s.CRTC.reg[9] = $40)) then
piHeight^ := 400;
end;
end
else
begin
piWidth^ := 640;
piHeight^ := 400;
end;
end;
// static IO port read callback handler
// redirects to non-static class handler to aprocedure virtual functions
function bx_vga_c.read_handler(self_ptr:pointer; address:Bit32u; io_len:unsigned):Bit32u;
var
horiz_retrace, vert_retrace:Bool;
retval:Bit8u;
ret:Bit32u;
label read_exit;
begin
//#define RETURN(x) do begin ret := (x); goto read_exit; end; while (0) !!!
ret:= 0;
if (io_len > 1) then
BX_PANIC(Format('io read from address %08x, len:=%u',[address, io_len]));
if ( (address >= $03b0) and (address <= $03bf) and
(self.s.misc_output.color_emulation<>0) ) then begin
repeat
ret := $ff; goto read_exit; until (false);
end;
if ( (address >= $03d0) and (address <= $03df) and
(self.s.misc_output.color_emulation=0) ) then begin
repeat ret := $ff; goto read_exit; until (false);
end;
case (address) of
$03ba, (* Input Status 1 (monochrome emulation modes) *)
$03ca, (* Feature Control ??? *)
$03da: (* Input Status 1 (color emulation modes) *)
// bit3: Vertical Retrace
// 0 := display is in the display mode
// 1 := display is in the vertical retrace mode
// bit0: Display Enable
// 0 := display is in the display mode
// 1 := display is not in the display mode; either the
// horizontal or vertical retrace period is active
// printf('horiz := %d, vert := %d', self.s.horiz_tick, self.s.vert_tick);
begin
if(self.s.misc_output.clock_select = 0) then begin // 25.175 clock 112.5% the length of 28.32
if (self.s.horiz_tick >= 112) then begin
self.s.horiz_tick := 0;
horiz_retrace := 1;
end
else begin
inc(self.s.horiz_tick);
horiz_retrace := 0;
end;
if (self.s.vert_tick >= 112) then begin
self.s.vert_tick := 0;
vert_retrace := 1;
end
else begin
Inc(self.s.vert_tick);
vert_retrace := 0;
end;
end else begin // clock_select 1 is assumed to be the 28.32 clock in XF86_VGA16
if (self.s.horiz_tick >= 100) then begin // ??? bogus # 100
self.s.horiz_tick := 0;
horiz_retrace := 1;
end
else begin
Inc(self.s.horiz_tick);
horiz_retrace := 0;
end;
if (self.s.vert_tick >= 100) then begin // ??? bogus # 100
self.s.vert_tick := 0;
vert_retrace := 1;
end
else begin
Inc(self.s.vert_tick);
vert_retrace := 0;
end;
end; // probably add more clock modes here for diffrent resolutions
retval := 0;
if (horiz_retrace<>0) or (vert_retrace<>0) then
retval := $01;
if (vert_retrace)<>0 then
retval := retval or $08;
(* reading self port resets the flip-flop to address mode *)
self.s.attribute_ctrl.flip_flop := 0;
repeat ret := retval; goto read_exit; until (false);
end;
$03c0: (* *)
begin
if (self.s.attribute_ctrl.flip_flop = 0) then begin
//BX_INFO(('vga_io_read: 3c0: flip_flop := 0'));
retval :=
(self.s.attribute_ctrl.video_enabled shl 5) or self.s.attribute_ctrl.address;
repeat ret := retval; goto read_exit; until (false);
end
else begin
BX_ERROR(('io_read: $3c0: flip_flop !:= 0'));
Result:=0;
Exit;
end;
end;
$03c1: (* *)
begin
case (self.s.attribute_ctrl.address) of
$00, $01, $02, $03,
$04, $05, $06, $07,
$08, $09, $0a, $0b,
$0c, $0d, $0e, $0f:
begin
retval := self.s.attribute_ctrl.palette_reg[self.s.attribute_ctrl.address];
repeat ret := retval; goto read_exit; until (false);
end;
$10: (* mode control register *)
begin
retval :=
(self.s.attribute_ctrl.mode_ctrl.graphics_alpha shl 0) or
(self.s.attribute_ctrl.mode_ctrl.display_type shl 1) or
(self.s.attribute_ctrl.mode_ctrl.enable_line_graphics shl 2) or
(self.s.attribute_ctrl.mode_ctrl.blink_intensity shl 3) or
(self.s.attribute_ctrl.mode_ctrl.pixel_panning_compat shl 5) or
(self.s.attribute_ctrl.mode_ctrl.pixel_clock_select shl 6) or
(self.s.attribute_ctrl.mode_ctrl.internal_palette_size shl 7);
repeat ret := retval; goto read_exit; until (false);
end;
$11: (* overscan color register *)
begin
repeat ret := self.s.attribute_ctrl.overscan_color; goto read_exit; until (false);
end;
$12: (* color plane enable *)
begin
repeat ret := self.s.attribute_ctrl.color_plane_enable; goto read_exit; until (false);
end;
$13: (* horizontal PEL panning register *)
begin
repeat ret := self.s.attribute_ctrl.horiz_pel_panning; goto read_exit; until (false);
end;
$14: (* color select register *)
begin
repeat ret := self.s.attribute_ctrl.color_select; goto read_exit; until (false);
end;
else
begin
BX_INFO(Format('vga_io_read: 3c1: address %02xh?',[self.s.attribute_ctrl.address]));
repeat ret := 0; goto read_exit; until (false);
end;
end;
end;
$03c2: (* Input Status 0 *)
begin
BX_DEBUG(('io read 3c2: input status #0: ignoring'));
repeat ret := 0; goto read_exit; until (false);
end;
$03c3: (* VGA Enable Register *)
begin
repeat ret := 1; goto read_exit; until (false);
end;
$03c4: (* Sequencer Index Register *)
begin
repeat ret := self.s.sequencer.index; goto read_exit; until (false);
end;
$03c5: (* Sequencer Registers 00..04 *)
begin
case (self.s.sequencer.index) of
0: (* sequencer: reset *)
begin
BX_DEBUG(('io read 3c5 case 0: sequencer reset'));
repeat ret := self.s.sequencer.bit0 or (self.s.sequencer.bit1 shl 1); goto read_exit; until (false);
end;
1: (* sequencer: clocking mode *)
begin
BX_DEBUG(('io read 3c5 case 1: sequencer clocking mode'));
repeat ret := self.s.sequencer.reg1; goto read_exit; until (false);
end;
2: (* sequencer: map mask register *)
begin
repeat ret := self.s.sequencer.map_mask; goto read_exit; until (false);
end;
3: (* sequencer: character map select register *)
begin
repeat ret := self.s.sequencer.char_map_select; goto read_exit; until (false);
end;
4: (* sequencer: memory mode register *)
begin
retval :=
(self.s.sequencer.extended_mem shl 1) or
(self.s.sequencer.odd_even shl 2) or
(self.s.sequencer.chain_four shl 3);
repeat ret := retval; goto read_exit; until (false);
end;
else
begin
BX_DEBUG(Format('io read 3c5: index %u unhandled',[self.s.sequencer.index]));
repeat ret := 0; goto read_exit; until (false);
end;
end;
end; //Case
$03c6: (* PEL mask ??? *)
begin
repeat ret := self.s.pel.mask; goto read_exit; until (false);
end;
$03c9: (* PEL Data Register, colors 00..FF *)
begin
case (self.s.pel.read_data_cycle) of
0:
begin
retval := self.s.pel.data[self.s.pel.read_data_register].red;
end;
1:
begin
retval := self.s.pel.data[self.s.pel.read_data_register].green;
end;
2:
begin
retval := self.s.pel.data[self.s.pel.read_data_register].blue;
end;
else
retval := 0; // keep compiler happy
end;
inc(self.s.pel.read_data_cycle);
if (self.s.pel.read_data_cycle >= 3) then begin
self.s.pel.read_data_cycle := 0;
inc(self.s.pel.read_data_register);
end;
repeat ret := retval; goto read_exit; until (false);
end;
$03cc: (* Miscellaneous Output / Graphics 1 Position ??? *)
begin
retval :=
((self.s.misc_output.color_emulation and $01) shl 0) or
((self.s.misc_output.enable_ram and $01) shl 1) or
((self.s.misc_output.clock_select and $03) shl 2) or
((self.s.misc_output.select_high_bank and $01) shl 5) or
((self.s.misc_output.horiz_sync_pol and $01) shl 6) or
((self.s.misc_output.vert_sync_pol and $01) shl 7);
repeat ret := retval; goto read_exit; until (false);
end;
$03ce: (* Graphics Controller Index Register *)
begin
repeat ret := self.s.graphics_ctrl.index; goto read_exit; until (false);
end;
$03cd: (* ??? *)
begin
BX_DEBUG(('io read from 03cd'));
repeat ret := $00; goto read_exit; until (false);
end;
$03cf: (* Graphics Controller Registers 00..08 *)
begin
case (self.s.graphics_ctrl.index) of
0: (* Set/Reset *)
begin
repeat ret := self.s.graphics_ctrl.set_reset; goto read_exit; until (false);
end;
1: (* Enable Set/Reset *)
begin
repeat ret := self.s.graphics_ctrl.enable_set_reset; goto read_exit; until (false);
end;
2: (* Color Compare *)
begin
repeat ret := self.s.graphics_ctrl.color_compare; goto read_exit; until (false);
end;
3: (* Data Rotate *)
begin
retval :=
((self.s.graphics_ctrl.raster_op and $03) shl 3) or
((self.s.graphics_ctrl.data_rotate and $07) shl 0);
repeat ret := retval; goto read_exit; until (false);
end;
4: (* Read Map Select *)
begin
repeat ret := self.s.graphics_ctrl.read_map_select; goto read_exit; until (false);
end;
5: (* mode *)
begin
retval :=
((self.s.graphics_ctrl.shift_reg and $03) shl 5) or
((self.s.graphics_ctrl.odd_even and $01 ) shl 4) or
((self.s.graphics_ctrl.read_mode and $01) shl 3) or
((self.s.graphics_ctrl.write_mode and $03) shl 0);
if ((self.s.graphics_ctrl.odd_even<>0) or
(self.s.graphics_ctrl.shift_reg<>0)) then
BX_DEBUG(Format('read 3cf: reg 05 := %02x', [retval]));
repeat ret := RetVal; goto read_exit; until (false);
end;
6: (* Miscellaneous *)
begin
retval :=
((self.s.graphics_ctrl.memory_mapping and $03 ) shl 2) or
((self.s.graphics_ctrl.odd_even and $01) shl 1) or
((self.s.graphics_ctrl.graphics_alpha and $01) shl 0);
repeat ret := RetVal; goto read_exit; until (false);
end;
7: (* Color Don't Care *)
begin
repeat ret := self.s.graphics_ctrl.color_dont_care; goto read_exit; until (false);
end;
8: (* Bit Mask *)
begin
repeat ret := self.s.graphics_ctrl.bitmask; goto read_exit; until (false);
end;
else
begin
(* ??? *)
BX_DEBUG(Format('io read: 3cf: index %u unhandled',[self.s.graphics_ctrl.index]));
repeat ret := 0; goto read_exit; until (false);
end;
end;
end;
$03d4: (* CRTC Index Register (color emulation modes) *)
begin
repeat ret := self.s.CRTC.address; goto read_exit; until (false);
end;
$03b5, (* CRTC Registers (monochrome emulation modes) *)
$03d5: (* CRTC Registers (color emulation modes) *)
begin
if (self.s.CRTC.address > $18) then
BX_DEBUG(Format('vga_io_read: 3d5: address := %02xh',[self.s.CRTC.address]));
repeat ret := self.s.CRTC.reg[self.s.CRTC.address]; goto read_exit; until (false);
end;
$03b4, (* CRTC Index Register (monochrome emulation modes) *)
$03c7, (* not sure but OpenBSD reads it a lot *)
$03cb, (* not sure but OpenBSD reads it a lot *)
$03c8: (* *)
begin
BX_INFO(Format('*** io read from vga port %x',[address]));
repeat ret := 0; goto read_exit; until (false);
end;
else
begin
BX_INFO(Format('*** io read from vga port %x',[address]));
repeat ret := 0; goto read_exit; until (false);
end;
end;
read_exit:
{$if VGA_TRACE_FEATURE=1}
BX_DEBUG(Format('8-bit read from %04x := %02x',[unsigned(address), ret]));
Result:=ret;
{$ifend}
end;
// static IO port write callback handler
// redirects to non-static class handler to aprocedure virtual functions
procedure bx_vga_c.write_handler(self_ptr:Pointer; address:Bit32u; dvalue:Bit32u; io_len:unsigned);
begin
{$if BX_USE_VGA_SMF=0}
bx_vga_c *class_ptr := (bx_vga_c *) self_ptr;
class_ptr^.write(address, value, io_len, 0);
{$else}
//UNUSED(self_ptr);
bx_vga.write(address, dvalue, io_len, 0);
{$ifend}
end;
class procedure bx_vga_c.write_handler_no_log(self_ptr:Pointer; address:Bit32u; dvalue:Bit32u; io_len:unsigned);
begin
{$if BX_USE_VGA_SMF=0}
bx_vga_c *class_ptr := (bx_vga_c *) self_ptr;
class_ptr^.write(address, value, io_len, 1);
{$else}
//UNUSED(self_ptr);
bx_vga.write(address, dvalue, io_len, 1);
{$ifend}
end;
procedure bx_vga_c.write(address:Bit32u; value:Bit32u; io_len:unsigned; no_log:Bool);
var
i:unsigned;
prev_video_enabled:Bool;
charmap1, charmap2, prev_memory_mapping:Bit8u;
prev_graphics_alpha, prev_chain_odd_even:Bool;
needs_update:Bool;
xti,yti:Integer;
iHeight, iWidth:unsigned;
label flipflop;
begin
{$if VGA_TRACE_FEATURE=1}
if (no_log=0) then
case (io_len) of
1:
BX_DEBUG(Format('8-bit write to %04x := %02x',[address, value]));
2:
BX_DEBUG(Format('16-bit write to %04x := %04x',[address,value]));
else
BX_PANIC(('Weird VGA write size'));
end;
{$ifend}
{$if VGA_TRACE_FEATURE=0}
BX_DEBUG(Format('vga_io_write(%04x):=%02x!',[address,value]));
{$ifend}
if (io_len = 2) then begin
{$if BX_USE_VGA_SMF=1}
bx_vga_c.write_handler_no_log(0, address, value and $ff, 1);
bx_vga_c.write_handler_no_log(0, address+1, (value shr 8) and $ff, 1);
{$else}
bx_vga_c.write(address, value and $ff, 1, 1);
bx_vga_c.write(address+1, (value shr 8) and $ff, 1, 1);
{$ifend}
exit;
end;
if ( (address >= $03b0) and (address <= $03bf) and
(self.s.misc_output.color_emulation<>0) ) then
exit;
if ( (address >= $03d0) and (address <= $03df) and
(self.s.misc_output.color_emulation=0) ) then
exit;
case (address) of
$03b4: (* CRTC Index Register (monochrome emulation modes) *)
begin
if (value > $18) then BX_PANIC(('io write 3b4: value > 18h'));
self.s.CRTC.address := value;
end;
$03b5: (* CRTC Registers (monochrome emulation modes) *)
begin
if (self.s.CRTC.address > $18) then BX_PANIC(('io write 3b5: CRTC reg > 18h'));
self.s.CRTC.reg[self.s.CRTC.address] := value;
{$if VGA_TRACE_FEATURE=0}
BX_DEBUG(Format('mono CRTC Reg[%u] := %02x',[self.s.CRTC.address, value]));
{$ifend}
end;
$03ba: (* Feature Control (monochrome emulation modes) *)
begin
{$if VGA_TRACE_FEATURE=0}
BX_DEBUG(('io write 3ba: feature control: ignoring'));
{$ifend}
end;
$03c0: (* Attribute Controller *)
begin
if (self.s.attribute_ctrl.flip_flop = 0) then begin (* address mode *)
prev_video_enabled := self.s.attribute_ctrl.video_enabled;
self.s.attribute_ctrl.video_enabled := (value shr 5) and $01;
if (self.s.attribute_ctrl.video_enabled = 0) then
clear_screen
else
if (prev_video_enabled=0) then begin
// Mark all video as updated so the color changes will go through
FillChar(self.s.text_snapshot, sizeof(self.s.text_snapshot),0 );
self.s.vga_mem_updated := 1;
for xti := 0 to BX_NUM_X_TILES do begin
for yti := 0 to BX_NUM_Y_TILES do begin
self.s.vga_tile_updated[xti][yti] := 1;
end;
end;
end;
value := value and $1f; (* address := bits 0..4 *)
self.s.attribute_ctrl.address := value;
case (value) of
$00, $01, $02, $03,
$04, $05, $06, $07,
$08, $09, $0a, $0b,
$0c, $0d, $0e, $0f:
goto flipflop;
else
BX_DEBUG(Format('io write 3c0: address mode reg:=%u',[value]));
end;
end
else begin (* data-write mode *)
case (self.s.attribute_ctrl.address) of
$00, $01, $02, $03,
$04, $05, $06, $07,
$08, $09, $0a, $0b,
$0c, $0d, $0e, $0f:
begin
self.s.attribute_ctrl.palette_reg[self.s.attribute_ctrl.address] := value;
//BX_DEBUG(('io write: 3c0 palette reg[%u] := %02x',
// (unsigned) self.s.attribute_ctrl.address,
// (unsigned) value);
end;
$10: // mode control register
begin
self.s.attribute_ctrl.mode_ctrl.graphics_alpha := (value shr 0) and $01;
self.s.attribute_ctrl.mode_ctrl.display_type := (value shr 1) and $01;
self.s.attribute_ctrl.mode_ctrl.enable_line_graphics := (value shr 2) and $01;
self.s.attribute_ctrl.mode_ctrl.blink_intensity := (value shr 3) and $01;
self.s.attribute_ctrl.mode_ctrl.pixel_panning_compat := (value shr 5) and $01;
self.s.attribute_ctrl.mode_ctrl.pixel_clock_select := (value shr 6) and $01;
self.s.attribute_ctrl.mode_ctrl.internal_palette_size := (value shr 7) and $01;
end;
$11: // Overscan Color Register
begin
self.s.attribute_ctrl.overscan_color := (value and $3f);
end;
$12: // Color Plane Enable Register
begin
self.s.attribute_ctrl.color_plane_enable := (value and $0f);
end;
$13: // Horizontal Pixel Panning Register
begin
self.s.attribute_ctrl.horiz_pel_panning := (value and $0f);
end;
$14: // Color Select Register
begin
self.s.attribute_ctrl.color_select := (value and $0f);
end;
else
BX_DEBUG(Format('io write 3c0: data-write mode %02x h',[self.s.attribute_ctrl.address]));
end;
end;
flipflop:
self.s.attribute_ctrl.flip_flop := word(self.s.attribute_ctrl.flip_flop=0);
end;
$03c2: // Miscellaneous Output Register
begin
self.s.misc_output.color_emulation := (value shr 0) and $01;
self.s.misc_output.enable_ram := (value shr 1) and $01;
self.s.misc_output.clock_select := (value shr 2) and $03;
self.s.misc_output.select_high_bank := (value shr 5) and $01;
self.s.misc_output.horiz_sync_pol := (value shr 6) and $01;
self.s.misc_output.vert_sync_pol := (value shr 7) and $01;
(*#if !defined(VGA_TRACE_FEATURE)
BX_DEBUG(('io write 3c2:'));
BX_DEBUG((' color_emulation (attempted) := %u',
(value shr 0) and $01 );
BX_DEBUG((' enable_ram := %u',
(unsigned) self.s.misc_output.enable_ram);
BX_DEBUG((' clock_select := %u',
(unsigned) self.s.misc_output.clock_select);
BX_DEBUG((' select_high_bank := %u',
(unsigned) self.s.misc_output.select_high_bank);
BX_DEBUG((' horiz_sync_pol := %u',
(unsigned) self.s.misc_output.horiz_sync_pol);
BX_DEBUG((' vert_sync_pol := %u',
(unsigned) self.s.misc_output.vert_sync_pol);
{$ifend}*)
end;
$03c3: // VGA enable
begin
// bit0: enables VGA display if set
end;
$03c4: (* Sequencer Index Register *)
begin
if (value > 4) then begin
BX_DEBUG(('io write 3c4: value > 4'));
end;
self.s.sequencer.index := value;
end;
$03c5: (* Sequencer Registers 00..04 *)
begin
case (self.s.sequencer.index) of
0: (* sequencer: reset *)
begin
self.s.sequencer.bit0 := (value shr 0) and $01;
self.s.sequencer.bit1 := (value shr 1) and $01;
end;
1: (* sequencer: clocking mode *)
begin
self.s.sequencer.reg1 := value and $3f;
end;
2: (* sequencer: map mask register *)
begin
self.s.sequencer.map_mask := (value and $0f);
i:=0;
while (i < 4) do
begin
self.s.sequencer.map_mask_bit[i] := (value shr i) and $01;
Inc(I);
end;
end;
3: (* sequencer: character map select register *)
begin
self.s.sequencer.char_map_select := value;
charmap1 := value and $13;
if (charmap1 > 3) then charmap1 := (charmap1 and 3) + 4;
charmap2 := (value and $2C) shr 2;
if (charmap2 > 3) then charmap2 := (charmap2 and 3) + 4;
BX_INFO(Format('char map select: #1:=%d / #2:=%d (unused)',[charmap1, charmap2]));
end;
4: (* sequencer: memory mode register *)
begin
self.s.sequencer.extended_mem := (value shr 1) and $01;
self.s.sequencer.odd_even := (value shr 2) and $01;
self.s.sequencer.chain_four := (value shr 3) and $01;
end;
else
BX_DEBUG(Format('io write 3c5: index %u unhandled',[self.s.sequencer.index]));
end;
end;
$03c6: (* PEL mask *)
begin
self.s.pel.mask := value;
if (self.s.pel.mask <> $ff) then
BX_DEBUG(('io write 3c6: PEL mask:=$%02x !:= $FF'));
// self.s.pel.mask should be and'd with final value before
// indexing into color registerself.s.
end;
$03c7: // PEL address, read mode
begin
self.s.pel.read_data_register := value;
self.s.pel.read_data_cycle := 0;
end;
$03c8: (* PEL address write mode *)
begin
self.s.pel.write_data_register := value;
self.s.pel.write_data_cycle := 0;
end;
$03c9: (* PEL Data Register, colors 00..FF *)
begin
case (self.s.pel.write_data_cycle) of
0:
self.s.pel.data[self.s.pel.write_data_register].red := value;
1:
self.s.pel.data[self.s.pel.write_data_register].green := value;
2:
begin
self.s.pel.data[self.s.pel.write_data_register].blue := value;
if (self.s.vbe_enabled)<>0 then
begin
iWidth := self.s.vbe_xres;
old_iWidth := iWidth;
iHeight := self.s.vbe_yres;
old_iHeight := iHeight;
end
else
begin
// 'normal vga' operation
determine_screen_dimensions(@iHeight, @iWidth);
if( (iWidth <> old_iWidth) or (iHeight <> old_iHeight) ) then
begin
dimension_update(iWidth, iHeight);
old_iWidth := iWidth;
old_iHeight := iHeight;
end;
end;
needs_update := palette_change(self.s.pel.write_data_register,
self.s.pel.data[self.s.pel.write_data_register].red shl 2,
self.s.pel.data[self.s.pel.write_data_register].green shl 2,
self.s.pel.data[self.s.pel.write_data_register].blue shl 2);
if (needs_update)<>0 then begin
// Mark all video as updated so the color changes will go through
self.s.vga_mem_updated := 1;
for xti := 0 to BX_NUM_X_TILES do begin
for yti := 0 to BX_NUM_Y_TILES do begin
self.s.vga_tile_updated[xti][yti] := 1;
end;
end;
end;
end;
end;
inc(self.s.pel.write_data_cycle);
if (self.s.pel.write_data_cycle >= 3) then begin
//BX_INFO(('self.s.pel.data[%u] beginr:=%u, g:=%u, b:=%uend;',
// (unsigned) self.s.pel.write_data_register,
// (unsigned) self.s.pel.data[self.s.pel.write_data_register].red,
// (unsigned) self.s.pel.data[self.s.pel.write_data_register].green,
// (unsigned) self.s.pel.data[self.s.pel.write_data_register].blue);
self.s.pel.write_data_cycle := 0;
inc(self.s.pel.write_data_register);
end;
end;
$03ca: (* Graphics 2 Position (EGA) *)
begin
// ignore, EGA only???
end;
$03cc: (* Graphics 1 Position (EGA) *)
begin
// ignore, EGA only???
end;
$03ce: (* Graphics Controller Index Register *)
begin
if (value > $08) then
BX_DEBUG(('io write: 3ce: value > 8'));
self.s.graphics_ctrl.index := value;
end;
$03cd: (* ??? *)
begin
BX_DEBUG(Format('io write to 03cd := %02x',[value]));
end;
$03cf: (* Graphics Controller Registers 00..08 *)
begin
case (self.s.graphics_ctrl.index) of
0: (* Set/Reset *)
begin
self.s.graphics_ctrl.set_reset := value and $0f;
end;
1: (* Enable Set/Reset *)
begin
self.s.graphics_ctrl.enable_set_reset := value and $0f;
end;
2: (* Color Compare *)
begin
self.s.graphics_ctrl.color_compare := value and $0f;
end;
3: (* Data Rotate *)
begin
self.s.graphics_ctrl.data_rotate := value and $07;
(* ??? is self bits 3..4 or 4..5 *)
self.s.graphics_ctrl.raster_op := (value shr 3) and $03; (* ??? *)
end;
4: (* Read Map Select *)
begin
self.s.graphics_ctrl.read_map_select := value and $03;
end;
5: (* mode *)
begin
self.s.graphics_ctrl.write_mode := value and $03;
self.s.graphics_ctrl.read_mode := (value shr 3) and $01;
self.s.graphics_ctrl.odd_even := (value shr 4) and $01;
self.s.graphics_ctrl.shift_reg := (value shr 5) and $03;
if (self.s.graphics_ctrl.odd_even)<>0 then
BX_DEBUG(Format('io write: 3cf: reg 05: value := %02xh',[value]));
if (self.s.graphics_ctrl.shift_reg)<>0 then
BX_DEBUG(Format('io write: 3cf: reg 05: value := %02xh',[value]));
end;
6: (* Miscellaneous *)
begin
prev_graphics_alpha := self.s.graphics_ctrl.graphics_alpha;
prev_chain_odd_even := self.s.graphics_ctrl.chain_odd_even;
prev_memory_mapping := self.s.graphics_ctrl.memory_mapping;
self.s.graphics_ctrl.graphics_alpha := value and $01;
self.s.graphics_ctrl.chain_odd_even := (value shr 1) and $01;
self.s.graphics_ctrl.memory_mapping := (value shr 2) and $03;
if (prev_memory_mapping <> self.s.graphics_ctrl.memory_mapping) then
self.s.vga_mem_updated := 1;
// other checks here ???
// check for transition from graphics to alpha mode and clear
// old snapshot memory
end;
7: (* Color Don't Care *)
begin
self.s.graphics_ctrl.color_dont_care := value and $0f;
end;
8: (* Bit Mask *)
begin
self.s.graphics_ctrl.bitmask := value;
end;
else
(* ??? *)
BX_DEBUG(Format('io write: 3cf: index %u unhandled',[self.s.graphics_ctrl.index]));
end;
end;
$03d4: (* CRTC Index Register (color emulation modes) *)
begin
self.s.CRTC.address := value;
if (self.s.CRTC.address > $18) then
BX_DEBUG(Format('vga_io_write: 3d4: address := %02xh',[self.s.CRTC.address]));
end;
$03d5: (* CRTC Registers (color emulation modes) *)
begin
if (self.s.CRTC.address > $18) then
BX_DEBUG(Format('vga_io_write: 3d5: address := %02xh',[self.s.CRTC.address]));
self.s.CRTC.reg[self.s.CRTC.address] := value;
//BX_DEBUG(('color CRTC Reg[%u] := %02x',
// (unsigned) self.s.CRTC.address, (unsigned) value);
if ((self.s.CRTC.address>=$0C) or (self.s.CRTC.address<=$0F)) then begin
// Start Address or Cursor Location change
self.s.vga_mem_updated := 1;
end;
end;
$03da: (* Feature Control (color emulation modes) *)
begin
BX_DEBUG(('io write: 3da: ignoring: feature ctrl and vert sync'));
end;
$03c1: (* *)
begin
BX_ERROR(Format('unsupported io write to port $%04x, val:=$%02x',[address, value]));
end;
else
BX_ERROR(Format('unsupported io write to port $%04x, val:=$%02x',[address,value]));
end;
end;
procedure bx_vga_c.set_update_interval(interval:unsigned);
begin
BX_INFO (Format('Changing timer interval to %d\n', [interval]));
self.timer ();
bx_pc_system.activate_timer (self.timer_id, interval, 1);
end;
procedure bx_vga_c.timer_handler(self_ptr:pointer);
var
class_ptr:pbx_vga_c;
begin
class_ptr := pbx_vga_c(self_ptr);
class_ptr^.timer();
end;
procedure bx_vga_c.timer;
begin
update();
FlushGui();
end;
procedure bx_vga_c.update;
var
iHeight, iWidth:unsigned;
xti, yti:unsigned;
color:Bit8u;
r, c:unsigned;
byte_offset:LongWord;
fbyte_offset:real;
pixely, pixelx:LongWord;
bit_no:unsigned ;
attribute, palette_reg_val, DAC_regno:Bit8u;
plane:LongWord;
start_addr:LongWord;
start_address:LongWord;
cursor_address, cursor_x, cursor_y:LongWord;
cursor_state:Bit16u;
VDE, MSL, rows:unsigned;
begin
{$if BX_GUI_ENABLED=0}
Exit;
{$ifend}
self.s.vga_mem_updated := 0;
{$if BX_SUPPORT_VBE=1}
if (self.s.vbe_enabled)<>0 then
begin
// specific VBE code display update code
// self is partly copied/mod_ified from the 32$20$8 update more below
iWidth:=self.s.vbe_xres;
iHeight:=self.s.vbe_yres;
for yti:=0 to iHeight div Y_TILESIZE do
for xti:=0 to iWidth div X_TILESIZE do
begin
if (self.s.vga_tile_updated[xti][yti])<>0 then
begin
for r:=0 to Y_TILESIZE do
begin
for c:=0 to X_TILESIZE do
begin
pixely := ((yti*Y_TILESIZE) + r);
pixelx := ((xti*X_TILESIZE) + c);
byte_offset := (pixely*iHeight) + (pixelx);
color := self.s.vbe_memory[byte_offset];
self.s.tile[r*X_TILESIZE + c] := color;
end;
end;
graphics_tile_update(@self.s.tile, xti*X_TILESIZE, yti*Y_TILESIZE);
self.s.vga_tile_updated[xti][yti] := 0;
end;
end;
// after a vbe display update, don't try to do any 'normal vga' updates anymore
exit;
end;
{$ifend}
// fields that effect the way video memory is serialized into screen output:
// GRAPHICS CONTROLLER:
// self.s.graphics_ctrl.shift_reg:
// 0: output data in standard VGA format
// 1: output data in CGA-compatible 32$200 4 color graphics mode
// (modes 4 and 5)
// 2: output data 8 bits at a time from the 4 bit planes
// (mode 13 and variants like modeX)
//fprintf(stderr, '# update()');
// if (self.s.vga_mem_updated=0 or self.s.attribute_ctrl.video_enabled = 0)
if (self.s.graphics_ctrl.graphics_alpha)<>0 then begin
//BX_DEBUG(('update: shiftreg:=%u, chain4:=%u, mapping:=%u',
// (unsigned) self.s.graphics_ctrl.shift_reg,
// (unsigned) self.s.sequencer.chain_four,
// (unsigned) self.s.graphics_ctrl.memory_mapping);
case ( self.s.graphics_ctrl.shift_reg ) of
0: // output data in serial fashion with each display plane
begin
// output on its associated serial output. Standard EGA/VGA format
determine_screen_dimensions(@iHeight, @iWidth);
//BX_DEBUG(('update(): mode 12h: 64$48$16colors'));
if( (iWidth <> old_iWidth) or (iHeight <> old_iHeight) ) then
begin
dimension_update(iWidth, iHeight);
old_iWidth := iWidth;
old_iHeight := iHeight;
end;
for yti:=0 to iHeight div Y_TILESIZE do begin
for xti:=0 to iWidth div X_TILESIZE do begin
if (self.s.vga_tile_updated[xti][yti])<>0 then begin
for r:=0 to Y_TILESIZE do begin
for c:=0 to X_TILESIZE do begin
bit_no := 7 - (c mod 8); /// !!! %
byte_offset := Trunc((yti*Y_TILESIZE+r) * (self.s.scan_bits/8) + (xti*X_TILESIZE+c)/8);
attribute :=
(((self.s.vga_memory[0*65536 + byte_offset] shr bit_no) and $01) shl 0) or
(((self.s.vga_memory[1*65536 + byte_offset] shr bit_no) and $01) shl 1) or
(((self.s.vga_memory[2*65536 + byte_offset] shr bit_no) and $01) shl 2) or
(((self.s.vga_memory[3*65536 + byte_offset] shr bit_no) and $01) shl 3);
attribute := attribute and self.s.attribute_ctrl.color_plane_enable;
palette_reg_val := self.s.attribute_ctrl.palette_reg[attribute];
if (self.s.attribute_ctrl.mode_ctrl.internal_palette_size)<>0 then begin
// use 4 lower bits from palette register
// use 4 higher bits from color select register
// 16 banks of 16-color registers
DAC_regno := (palette_reg_val and $0f) or (self.s.attribute_ctrl.color_select shl 4);
end
else begin
// use 6 lower bits from palette register
// use 2 higher bits from color select register
// 4 banks of 64-color registers
DAC_regno := (palette_reg_val and $3f) or((self.s.attribute_ctrl.color_select and $0c) shl 4);
end;
// DAC_regno @:= video DAC mask register ???
self.s.tile[r*X_TILESIZE + c] := DAC_regno;
end;
end;
graphics_tile_update(@self.s.tile, xti*X_TILESIZE, yti*Y_TILESIZE);
self.s.vga_tile_updated[xti][yti] := 0;
end;
end;
end; // case 0
end;
1: // output the data in a CGA-compatible 32$200 4 color graphics
// mode. (modes 4 and 5)
(* CGA 32$20$4 start *)
begin
iHeight:=200; iWidth:=320;
if( (iWidth <> old_iWidth) or (iHeight <> old_iHeight) ) then
begin
dimension_update(iWidth, iHeight);
old_iWidth := iWidth;
old_iHeight := iHeight;
end;
for yti:=0 to iHeight div Y_TILESIZE do
for xti:=0 to iWidth div X_TILESIZE do begin
if (self.s.vga_tile_updated[xti][yti])<>0 then begin
for r:=0 to Y_TILESIZE do begin
for c:=0 to X_TILESIZE do begin
(* 0 or $2000 *)
byte_offset := ((yti*Y_TILESIZE + r) and 1) shl 13;
(* to the start of the line *)
byte_offset := byte_offset + (320 div 4) * ((yti*Y_TILESIZE + r) div 2);
(* to the byte start *)
byte_offset := byte_offset + ((xti*X_TILESIZE + c) div 4);
attribute := 6 - 2*((xti*X_TILESIZE + c) mod 4);
palette_reg_val := (self.s.vga_memory[byte_offset]) shr attribute;
palette_reg_val := palette_reg_val and 3;
palette_reg_val := palette_reg_val or self.s.attribute_ctrl.mode_ctrl.enable_line_graphics shl 2;
// palette_reg_val |:= self.s.attribute_ctrl.mode_ctrl.blink_intensity shl 3;
DAC_regno := self.s.attribute_ctrl.palette_reg[palette_reg_val];
self.s.tile[r*X_TILESIZE + c] := DAC_regno;
end;
end;
graphics_tile_update(@self.s.tile, xti*X_TILESIZE, yti*Y_TILESIZE);
self.s.vga_tile_updated[xti][yti] := 0;
end;
end;
(* CGA 32$20$4 end *)
end; // case 1
2: // output the data eight bits at a time from the 4 bit planeself.s.
// (format for VGA mode 13 hex)
begin
determine_screen_dimensions(@iHeight, @iWidth);
if ( self.s.sequencer.chain_four )<>0 then begin
// bx_vga_dump_status();
if (self.s.misc_output.select_high_bank <> 1) then
BX_PANIC(('update: select_high_bank !:= 1'));
if( (iHeight <> old_iHeight) or (iWidth <> old_iWidth) ) then
begin
dimension_update(iWidth, iHeight);
old_iHeight := iHeight;
old_iWidth := iWidth;
end;
for yti:=0 to iHeight div Y_TILESIZE do
for xti:=0 to iWidth div X_TILESIZE do begin
if (self.s.vga_tile_updated[xti][yti])<>0 then begin // end;
// if (1) then begin
for r:=0 to Y_TILESIZE do begin
for c:=0 to X_TILESIZE do begin
pixely := ((yti*Y_TILESIZE) + r);
pixelx := ((xti*X_TILESIZE) + c);
plane := (pixelx mod 4);
//byte_offset := (plane * 65536) + (pixely * 320) + (pixelx and ~$03);
byte_offset := (plane * 65536) + (pixely * 320) + (pixelx and not $03);
// simulate wrap of upper two address bits into low order bits
//byte_offset |:= ((byte_offset and $c000) shr 14);
color := self.s.vga_memory[byte_offset];
self.s.tile[r*X_TILESIZE + c] := color;
end;
end;
graphics_tile_update(@self.s.tile, xti*X_TILESIZE, yti*Y_TILESIZE);
self.s.vga_tile_updated[xti][yti] := 0;
end;
end;
end
else begin // chain_four = 0, modeX
if( (iWidth <> old_iWidth) or (iHeight <> old_iHeight) ) then
begin
dimension_update(iWidth, iHeight);
old_iWidth := iWidth;
old_iHeight := iHeight;
end;
start_addr := (self.s.CRTC.reg[$0c] shl 8) or self.s.CRTC.reg[$0d];
for yti:=0 to iHeight div Y_TILESIZE do
for xti:=0 to iWidth div X_TILESIZE do begin
// if (self.s.vga_tile_updated[xti][yti]) then begin // end;
if (self.s.vga_tile_updated[xti][yti])<>0 then begin
for r:=0 to Y_TILESIZE do begin
for c:=0 to X_TILESIZE do begin
pixely := ((yti*Y_TILESIZE) + r);
pixelx := ((xti*X_TILESIZE) + c);
plane := (pixelx mod 4);
byte_offset := (plane * 65536) +
(pixely * 80) + (pixelx shr 2);
color := self.s.vga_memory[start_addr + byte_offset];
self.s.tile[r*X_TILESIZE + c] := color;
end;
end;
graphics_tile_update(@self.s.tile, xti*X_TILESIZE, yti*Y_TILESIZE);
self.s.vga_tile_updated[xti][yti] := 0;
end;
end;
end;
end; // case 2
else
BX_PANIC(Format('update: shift_reg = %u', [self.s.graphics_ctrl.shift_reg]));
end;
self.s.vga_mem_updated := 0;
exit;
end
else begin // text mode
case (self.s.graphics_ctrl.memory_mapping) of
2: // B0000 .. B7FFF
begin
iWidth := 8*80; // TODO: should use font size
iHeight := 16*25;
if( (iWidth <> old_iWidth) or (iHeight <> old_iHeight) ) then
begin
dimension_update(iWidth, iHeight);
old_iWidth := iWidth;
old_iHeight := iHeight;
end;
//BX_DEBUG(('update(): case 2'));
(* pass old text snapshot and new VGA memory contents *)
start_address := 2*((self.s.CRTC.reg[12] shl 8) + self.s.CRTC.reg[13]);
cursor_address := 2*((self.s.CRTC.reg[$0e] shl 8) or self.s.CRTC.reg[$0f]);
if (cursor_address < start_address) then begin
cursor_x := $ffff;
cursor_y := $ffff;
end
else begin
cursor_x := Trunc(((cursor_address - start_address)/2) / 80);
cursor_y := Trunc(((cursor_address - start_address)/2)) div 80;
end;
cursor_state := (bx_vga.s.CRTC.reg[$0a] shl 8) or bx_vga.s.CRTC.reg[$0b];
text_update(PChar(@self.s.text_snapshot),
PChar(@self.s.vga_memory[start_address]),cursor_x, cursor_y, cursor_state, 25);
// screen updated, copy new VGA memory contents into text snapshot
Move(self.s.vga_memory[start_address], self.s.text_snapshot, 2*80*25); //!!!
self.s.vga_mem_updated := 0;
end;
3: // B8000 .. BFFFF
begin
// Verticle Display End: find out how many lines are displayed
VDE := bx_vga.s.CRTC.reg[$12] or ((bx_vga.s.CRTC.reg[$07] shl 7) and $100) or ((bx_vga.s.CRTC.reg[$07] shl 3) and $200);
// Maximum Scan Line: height of character cell
MSL := bx_vga.s.CRTC.reg[$09] and $1f;
rows := Trunc((VDE+1)/(MSL+1));
if (rows > BX_MAX_TEXT_LINES) then
BX_PANIC(Format('text rows>%d: %d',[BX_MAX_TEXT_LINES,rows]));
iWidth := 8*80; // TODO: should use font size
iHeight := 16*rows;
if( (iWidth <> old_iWidth) or (iHeight <> old_iHeight) ) then
begin
dimension_update(iWidth, iHeight);
old_iWidth := iWidth;
old_iHeight := iHeight;
end;
// pass old text snapshot and new VGA memory contents
start_address := 2*((self.s.CRTC.reg[12] shl 8) + self.s.CRTC.reg[13]);
cursor_address := 2*((self.s.CRTC.reg[$0e] shl 8) or self.s.CRTC.reg[$0f]);
if (cursor_address < start_address) then begin
cursor_x := $ffff;
cursor_y := $ffff;
end
else begin
cursor_x := Trunc(((cursor_address - start_address)/2)) mod 80;
cursor_y := trunc(((cursor_address - start_address)/2)) div 80;
end;
cursor_state := (bx_vga.s.CRTC.reg[$0a] shl 8) or bx_vga.s.CRTC.reg[$0b];
text_update(PChar(@self.s.text_snapshot),
PChar(@self.s.vga_memory[start_address]), cursor_x, cursor_y, cursor_state, rows);
// screen updated, copy new VGA memory contents into text snapshot
move(self.s.vga_memory[start_address], self.s.text_snapshot, 2*80*rows);
self.s.vga_mem_updated := 0;
end;
else
BX_DEBUG(Format('update(): color text mode: mem map is %u',[self.s.graphics_ctrl.memory_mapping]));
end;
end;
end;
function bx_vga_c.mem_read(addr:Bit32u):Bit8u;
var
offset:Bit32u;
color_compare, color_dont_care:Bit8u;
latch0, latch1, latch2, latch3, retval, pixel_val:Bit8u;
b:unsigned;
begin
{$if BX_SUPPORT_VBE=1}
// if in a vbe enabled mode, read from the vbe_memory
if (self.s.vbe_enabled)<>0 then
begin
Result:=vbe_mem_read(addr);
exit;
end;
{$ifend}
// ??? should get rid of references to shift_reg in self function
if (self.s.graphics_ctrl.graphics_alpha)<>0 then begin
if (self.s.graphics_ctrl.memory_mapping = 3) then begin // $B8000 .. $BFFFF
if (addr < $B8000) then
begin
result:=($ff);
Exit;
end;
offset := addr - $B8000;
if ( (self.s.graphics_ctrl.shift_reg <> 1) and (self.s.graphics_ctrl.shift_reg <> 2) ) then
BX_PANIC(Format('vga_mem_read: shift_reg := %u',[self.s.graphics_ctrl.shift_reg]));
Result:=(self.s.vga_memory[offset]);
Exit;
end;
if (self.s.graphics_ctrl.memory_mapping <> 1) then begin
BX_DEBUG(Format(' location %08x',[addr]));
BX_PANIC(Format('vga_mem_read: graphics: mapping := %u?',[self.s.graphics_ctrl.memory_mapping]));
Result:=(0);
Exit;
end;
if (addr > $AFFFF) then
begin
Result:=($ff);
Exit;
end;
// addr between $A0000 and $AFFFF
offset := addr - $A0000;
if ( self.s.sequencer.chain_four )<>0 then begin
// mode 13h: 320 x 200 256 color mode: chained pixel representation
Result:=( self.s.vga_memory[(offset and not $03) + (offset mod 4)*65536] );
//Result:=( self.s.vga_memory[(offset and ~$03) + (offset % 4)*65536] ); !!!
Exit;
end;
end
else begin
case (self.s.graphics_ctrl.memory_mapping) of
1: // $A0000 .. $AFFFF
begin
if (addr > $AFFFF) then
begin
Result:=($ff);
Exit;
end;
offset := addr - $A0000;
end;
2: // $B0000 .. $B7FFF
begin
if ((addr < $B0000) or (addr > $B7FFF)) then
begin
Result:=($ff);
Exit;
end;
offset := addr - $B0000;
end;
3: // $B8000 .. $BFFFF
begin
if (addr < $B8000) then
begin
Result:=($ff);
Exit;
end;
offset := addr - $B8000;
end;
else // $A0000 .. $BFFFF
offset := addr - $A0000;
end;
if (self.s.graphics_ctrl.memory_mapping <> 1) then
Result:=(self.s.vga_memory[offset]);
end;
(* addr between $A0000 and $AFFFF *)
case (self.s.graphics_ctrl.read_mode) of
0: (* read mode 0 *)
begin
self.s.graphics_ctrl.latch[0] := self.s.vga_memory[ offset];
self.s.graphics_ctrl.latch[1] := self.s.vga_memory[1*65536 + offset];
self.s.graphics_ctrl.latch[2] := self.s.vga_memory[2*65536 + offset];
self.s.graphics_ctrl.latch[3] := self.s.vga_memory[3*65536 + offset];
Result:=(self.s.graphics_ctrl.latch[self.s.graphics_ctrl.read_map_select]);
Exit;
end;
1: (* read mode 1 *)
begin
color_compare := self.s.graphics_ctrl.color_compare and $0f;
color_dont_care := self.s.graphics_ctrl.color_dont_care and $0f;
self.s.graphics_ctrl.latch[0] := self.s.vga_memory[ offset];
latch0 := self.s.graphics_ctrl.latch[0];
self.s.graphics_ctrl.latch[1] := self.s.vga_memory[1*65536 + offset];
latch1 :=self.s.graphics_ctrl.latch[1];
self.s.graphics_ctrl.latch[2] := self.s.vga_memory[2*65536 + offset];
latch2 := self.s.graphics_ctrl.latch[2];
self.s.graphics_ctrl.latch[3] := self.s.vga_memory[3*65536 + offset];
latch3 := self.s.graphics_ctrl.latch[3];
retval := 0;
for b:=0 to 8 do
begin
pixel_val :=
((latch0 shl 0) and $01) or
((latch1 shl 1) and $02) or
((latch2 shl 2) and $04) or
((latch3 shl 3) and $08);
latch0 := latch0 shr 1;
latch1 := latch1 shr 1;
latch2 := latch2 shr 1;
latch3 := latch3 shr 1;
if ( (pixel_val and color_dont_care) = (color_compare and color_dont_care) ) then
retval := retval or (1 shl b);
end;
Result:=(retval);
Exit;
end;
else
begin
Result:=(0);
Exit;
end;
end;
end;
procedure bx_vga_c.mem_write(addr:Bit32u; value:Bit8u);
var
offset:Bit32u;
new_val:array[0..4] of Bit8u;
cpu_data_b:array[0..4] of Bit8u;
new_bit:Bit8u;
x_tileno, y_tileno, isEven:unsigned ;
and_mask, bitmask:Bit8u;
set_reset_b:array[0..4] of Bit8u;
i, b:unsigned;
begin
{$if BX_SUPPORT_VBE=1}
// if in a vbe enabled mode, write to the vbe_memory
if (self.s.vbe_enabled)<>0 then
begin
vbe_mem_write(addr,value);
exit;
end;
{$ifend}
if (self.s.graphics_ctrl.graphics_alpha)<>0 then begin
if (self.s.graphics_ctrl.memory_mapping = 1) then begin // $A0000 .. $AFFFF
// unsigned x_tileno, y_tileno;
if ( (addr < $A0000) or (addr > $AFFFF) )then
exit;
offset := addr - $A0000;
end
else if (self.s.graphics_ctrl.memory_mapping = 3) then begin // $B8000 .. $BFFFF
if ( (addr < $B8000) or (addr > $BFFFF) ) then
exit;
offset := addr - $B8000;
(* CGA 32$20$4 start *)
if (offset>=$2000) then isEven:=1 else isEven:=0;
if (isEven)<>0 then begin
y_tileno := offset - $2000;
y_tileno := y_tileno div (320 div 4);
y_tileno := y_tileno shl 1; //2 * y_tileno;
Inc(y_tileno);
x_tileno := (offset - $2000) mod (320 div 4);
x_tileno := x_tileno shl 2; //:= 4;
end else begin
y_tileno := offset div (320 div 4);
y_tileno := offset shl 1; //2 * offset;
x_tileno := offset mod (320 div 4);
x_tileno := x_tileno shl 2; ///:=4;
end;
x_tileno:=x_tileno DIV X_TILESIZE;
y_tileno:=y_tileno div Y_TILESIZE;
self.s.vga_mem_updated := 1;
self.s.vga_tile_updated[x_tileno][y_tileno] := 1;
(* CGA 32$20$4 end *)
end
else begin
BX_PANIC(Format('vga_mem_write: graphics: mapping := %u',[self.s.graphics_ctrl.memory_mapping]));
exit;
end;
if ( self.s.sequencer.chain_four )<>0 then begin
offset := addr - $A0000;
//self.s.vga_memory[(offset and ~$03) + (offset % 4)*65536] := value; !!!!
self.s.vga_memory[(offset and not $03) + (offset mod 4)*65536] := value;
// 320 x 200 256 color mode: chained pixel representation
y_tileno := Trunc((offset / 320) / Y_TILESIZE);
x_tileno := Trunc((offset mod 320) / X_TILESIZE);
self.s.vga_mem_updated := 1;
self.s.vga_tile_updated[x_tileno][y_tileno] := 1;
exit;
end;
end
else begin
case (self.s.graphics_ctrl.memory_mapping) of
1: // $A0000 .. $AFFFF
begin
if (addr > $AFFFF) then exit;
offset := addr - $A0000;
end;
2: // $B0000 .. $B7FFF
begin
if ((addr < $B0000) or (addr > $B7FFF)) then exit;
offset := addr - $B0000;
end;
3: // $B8000 .. $BFFFF
begin
if (addr < $B8000) then exit;
offset := addr - $B8000;
end;
else // $A0000 .. $BFFFF
offset := addr - $A0000;
end;
if (self.s.graphics_ctrl.memory_mapping <> 1) then begin
self.s.vga_memory[offset] := value;
self.s.vga_mem_updated := 1;
exit;
end;
end;
(* addr between $A0000 and $AFFFF *)
case (self.s.graphics_ctrl.write_mode) of
0: (* write mode 0 *)
begin
(* perform rotate on CPU data in case its needed *)
value := (value shr self.s.graphics_ctrl.data_rotate) or (value shl (8 - self.s.graphics_ctrl.data_rotate));
bitmask := self.s.graphics_ctrl.bitmask;
for i:=0 to 4 do begin
new_val[i] := 0;
end;
set_reset_b[0] := (self.s.graphics_ctrl.set_reset shr 0) and $01;
set_reset_b[1] := (self.s.graphics_ctrl.set_reset shr 1) and $01;
set_reset_b[2] := (self.s.graphics_ctrl.set_reset shr 2) and $01;
set_reset_b[3] := (self.s.graphics_ctrl.set_reset shr 3) and $01;
and_mask := 1;
for b:=0 to 7 do begin
if (bitmask and $01)<>0 then begin (* bit-mask bit set, perform op *)
for i:=0 to 4 do begin
(* derive bit from set/reset register *)
if ( (self.s.graphics_ctrl.enable_set_reset shr i) and $01 )<>0 then begin
new_bit := (set_reset_b[i] shl b);
end
(* derive bit from rotated CPU data *)
else begin
new_bit := (value and and_mask);
end;
case (self.s.graphics_ctrl.raster_op) of
0: (* replace *)
new_val[i] := new_val[i] or new_bit;
1: (* AND with latch data *)
new_val[i] := new_val[i] or (new_bit and (self.s.graphics_ctrl.latch[i] and and_mask));
2: (* OR with latch data *)
new_val[i] := new_val[i] or (new_bit or (self.s.graphics_ctrl.latch[i] and and_mask));
3: (* XOR with latch data *)
new_val[i] := new_val[i] or (new_bit xor (self.s.graphics_ctrl.latch[i] and and_mask));
else
BX_PANIC(Format('vga_mem_write: write mode 0: op := %u',[self.s.graphics_ctrl.raster_op]));
end;
end;
end
else begin (* bit-mask bit clear, pass data thru from latch *)
new_val[0] := new_val[0] or (self.s.graphics_ctrl.latch[0] and and_mask);
new_val[1] := new_val[1] or (self.s.graphics_ctrl.latch[1] and and_mask);
new_val[2] := new_val[2] or (self.s.graphics_ctrl.latch[2] and and_mask);
new_val[3] := new_val[3] or (self.s.graphics_ctrl.latch[3] and and_mask);
end;
bitmask := bitmask shr 1;
and_mask := and_mask shl 1;
end;
end;
1: (* write mode 1 *)
begin
for i:=0 to 3 do begin
new_val[i] := self.s.graphics_ctrl.latch[i];
end;
end;
2: (* write mode 2 *)
begin
if (self.s.graphics_ctrl.raster_op)<>0 then
BX_PANIC(Format('vga_mem_write: write mode 2: op := %u',[self.s.graphics_ctrl.raster_op]));
bitmask := self.s.graphics_ctrl.bitmask;
for i:=0 to 4 do begin
new_val[i] := 0;
end;
cpu_data_b[0] := (value shr 0) and $01;
cpu_data_b[1] := (value shr 1) and $01;
cpu_data_b[2] := (value shr 2) and $01;
cpu_data_b[3] := (value shr 3) and $01;
and_mask := 1;
for b:=0 to 7 do begin
if (bitmask and $01)<>0 then begin (* bit-mask bit set, perform op *)
case (self.s.graphics_ctrl.raster_op) of
0: (* replace: write cpu data unmod_ified *)
begin
new_val[0] := new_val[0] or new_val[0] or cpu_data_b[0] shl b;
new_val[1] := new_val[1] or cpu_data_b[1] shl b;
new_val[2] := new_val[2] or cpu_data_b[2] shl b;
new_val[3] := new_val[3] or cpu_data_b[3] shl b;
end;
1, (* AND *)
2, (* OR *)
3: (* XOR *)
begin
BX_PANIC(Format('vga_mem_write: raster_op := %u?',[self.s.graphics_ctrl.raster_op]));
end;
else
BX_PANIC(Format('vga_mem_write: raster_op := %u?',[self.s.graphics_ctrl.raster_op]));
end;
end
else begin (* bit-mask bit clear, pass data thru from latch *)
new_val[0] := new_val[0] or (self.s.graphics_ctrl.latch[0] and and_mask);
new_val[1] := new_val[1] or (self.s.graphics_ctrl.latch[1] and and_mask);
new_val[2] := new_val[2] or (self.s.graphics_ctrl.latch[2] and and_mask);
new_val[3] := new_val[3] or (self.s.graphics_ctrl.latch[3] and and_mask);
end;
bitmask := bitmask shr 1;
and_mask := and_mask shl 1;
end;
end;
3: (* write mode 3 *)
begin
(* perform rotate on CPU data *)
value := (value shr self.s.graphics_ctrl.data_rotate) or
(value shl (8 - self.s.graphics_ctrl.data_rotate));
bitmask := (value and self.s.graphics_ctrl.bitmask);
for i:=0 to 4 do begin
new_val[i] := 0;
end;
set_reset_b[0] := (self.s.graphics_ctrl.set_reset shr 0) and $01;
set_reset_b[1] := (self.s.graphics_ctrl.set_reset shr 1) and $01;
set_reset_b[2] := (self.s.graphics_ctrl.set_reset shr 2) and $01;
set_reset_b[3] := (self.s.graphics_ctrl.set_reset shr 3) and $01;
and_mask := 1;
for b:=0 to 7 do begin
if (bitmask and $01)<>0 then begin (* bit-mask bit set, perform op *)
for i:=0 to 3 do begin
(* derive bit from set/reset register *)
(* (mch) I can't find any justification for self... *)
if ( (* (mch) *) 1 or ((self.s.graphics_ctrl.enable_set_reset shr i) and $01 ))<>0 then begin
// (mch) My guess is that the function select logic should go here
case (self.s.graphics_ctrl.raster_op) of
0: // write
begin
new_val[i] := new_val[i] or (set_reset_b[i] shl b);
end;
1: // AND
begin
new_val[i] := new_val[i] or ((set_reset_b[i] shl b) and
self.s.graphics_ctrl.latch[i] and (1 shl b));
end;
2: // OR
begin
new_val[i] := new_val[i] or (set_reset_b[i] shl b) or
(self.s.graphics_ctrl.latch[i] and (1 shl b));
end;
3: // XOR
begin
new_val[i] := new_val[i] or ((set_reset_b[i] shl b) xor
self.s.graphics_ctrl.latch[i] and (1 shl b));
end;
end;
end
(* derive bit from rotated CPU data *)
else begin
new_val[i] := new_val[i] or (value and and_mask);
end;
end;
end
else begin (* bit-mask bit clear, pass data thru from latch *)
new_val[0] := new_val[0] or (self.s.graphics_ctrl.latch[0] and and_mask);
new_val[1] := new_val[1] or (self.s.graphics_ctrl.latch[1] and and_mask);
new_val[2] := new_val[2] or (self.s.graphics_ctrl.latch[2] and and_mask);
new_val[3] := new_val[3] or (self.s.graphics_ctrl.latch[3] and and_mask);
end;
bitmask := bitmask shr 1;
and_mask := and_mask shl 1;
end;
end;
else
BX_PANIC(Format('vga_mem_write: write mode %u ?',[self.s.graphics_ctrl.write_mode]));
end;
if (self.s.sequencer.map_mask and $0f)<>0 then begin
self.s.vga_mem_updated := 1;
if (self.s.sequencer.map_mask_bit[0])<>0 then
self.s.vga_memory[0*65536 + offset] := new_val[0];
if (self.s.sequencer.map_mask_bit[1])<>0 then
self.s.vga_memory[1*65536 + offset] := new_val[1];
if (self.s.sequencer.map_mask_bit[2])<>0 then
self.s.vga_memory[2*65536 + offset] := new_val[2];
if (self.s.sequencer.map_mask_bit[3])<>0 then
self.s.vga_memory[3*65536 + offset] := new_val[3];
//x_tileno := (offset % (self.s.scan_bits/8)) / (X_TILESIZE / 8);!!!
x_tileno := (offset mod (self.s.scan_bits div 8)) div (X_TILESIZE div 8);
y_tileno := (offset div (self.s.scan_bits div 8)) div Y_TILESIZE;
self.s.vga_tile_updated[x_tileno][y_tileno] := 1;
end;
end;
(*procedure bx_vga_c.get_text_snapshot(Bit8u **text_snapshot, unsigned *txHeight,
unsigned *txWidth)
begin
unsigned VDE, MSL;
if (!self.s.graphics_ctrl.graphics_alpha) then begin
*text_snapshot := @self.s.text_snapshot[0];
VDE := bx_vga.s.CRTC.reg[$12] |
((bx_vga.s.CRTC.reg[$07]shl7)@$100) |
((bx_vga.s.CRTC.reg[$07]shl3)@$200);
MSL := bx_vga.s.CRTC.reg[$09] and $1f;
*txHeight := (VDE+1)/(MSL+1);
*txWidth := self.s.CRTC.reg[1] + 1;
end; else begin
*txHeight := 0;
*txWidth := 0;
end;
end; *)
{ procedure
bx_vga_c.dump_status(procedure)
begin
BX_INFO(('s.misc_output.color_emulation := %u',
(unsigned) self.s.misc_output.color_emulation));
BX_INFO(('s.misc_output.enable_ram := %u',
(unsigned) self.s.misc_output.enable_ram));
BX_INFO(('s.misc_output.clock_select := %u',
(unsigned) self.s.misc_output.clock_select));
if (self.s.misc_output.clock_select = 0)
BX_INFO((' 25Mhz 640 horiz pixel clock'));
else
BX_INFO((' 28Mhz 720 horiz pixel clock'));
BX_INFO(('s.misc_output.select_high_bank := %u',
(unsigned) self.s.misc_output.select_high_bank));
BX_INFO(('s.misc_output.horiz_sync_pol := %u',
(unsigned) self.s.misc_output.horiz_sync_pol));
BX_INFO(('s.misc_output.vert_sync_pol := %u',
(unsigned) self.s.misc_output.vert_sync_pol));
switch ( (self.s.misc_output.vert_sync_pol shl 1) |
self.s.misc_output.horiz_sync_pol ) then begin
case 0: BX_INFO((' (reserved')); break;
case 1: BX_INFO((' 400 lines')); break;
case 2: BX_INFO((' 350 lines')); break;
case 3: BX_INFO((' 480 lines')); break;
default: BX_INFO((' ???'));
end;
BX_INFO(('s.graphics_ctrl.odd_even := %u',
(unsigned) self.s.graphics_ctrl.odd_even));
BX_INFO(('s.graphics_ctrl.chain_odd_even := %u',
(unsigned) self.s.graphics_ctrl.chain_odd_even));
BX_INFO(('s.graphics_ctrl.shift_reg := %u',
(unsigned) self.s.graphics_ctrl.shift_reg));
BX_INFO(('s.graphics_ctrl.graphics_alpha := %u',
(unsigned) self.s.graphics_ctrl.graphics_alpha));
BX_INFO(('s.graphics_ctrl.memory_mapping := %u',
(unsigned) self.s.graphics_ctrl.memory_mapping));
switch (self.s.graphics_ctrl.memory_mapping) then begin
case 0: BX_INFO((' A0000-BFFFF')); break;
case 1: BX_INFO((' A0000-AFFFF')); break;
case 2: BX_INFO((' B0000-B7FFF')); break;
case 3: BX_INFO((' B8000-BFFFF')); break;
default: BX_INFO((' ???'));
end;
BX_INFO(('s.sequencer.extended_mem := %u',
(unsigned) self.s.sequencer.extended_mem));
BX_INFO(('s.sequencer.odd_even := %u (inverted)',
(unsigned) self.s.sequencer.odd_even));
BX_INFO(('s.sequencer.chain_four := %u',
(unsigned) self.s.sequencer.chain_four));
BX_INFO(('s.attribute_ctrl.video_enabled := %u',
(unsigned) self.s.attribute_ctrl.video_enabled));
BX_INFO(('s.attribute_ctrl.mode_ctrl.graphics_alpha := %u',
(unsigned) self.s.attribute_ctrl.mode_ctrl.graphics_alpha));
BX_INFO(('s.attribute_ctrl.mode_ctrl.display_type := %u',
(unsigned) self.s.attribute_ctrl.mode_ctrl.display_type));
BX_INFO(('s.attribute_ctrl.mode_ctrl.internal_palette_size := %u',
(unsigned) self.s.attribute_ctrl.mode_ctrl.internal_palette_size));
BX_INFO(('s.attribute_ctrl.mode_ctrl.pixel_clock_select := %u',
(unsigned) self.s.attribute_ctrl.mode_ctrl.pixel_clock_select));
end;
}
(* procedure
bx_vga_c.redraw_area(unsigned x0, unsigned y0, unsigned width,
unsigned height)
begin
unsigned xi, yi, x1, y1;
self.s.vga_mem_updated := 1;
if (self.s.graphics_ctrl.graphics_alpha) then begin
// graphics mode
self.s.vga_mem_updated := 1;
x1 := x0 + width - 1;
y1 := y0 + height - 1;
for (yi:=0; yi<480; yi+:=Y_TILESIZE) then begin
for (xi:=0; xi<640; xi+:=X_TILESIZE) then begin
// is redraw rectangle outside x boundaries of self tile?
if (x1 < xi) continue;
if (x0 > (xi+X_TILESIZE-1)) continue;
// is redraw rectangle outside y boundaries of self tile?
if (y1 < yi) continue;
if (y0 > (yi+X_TILESIZE-1)) continue;
self.s.vga_tile_updated[xi/X_TILESIZE][yi/Y_TILESIZE] := 1;
end;
end;
end;
else begin
// text mode
memset(self.s.text_snapshot, 0,
sizeof(self.s.text_snapshot));
self.s.vga_mem_updated := 1;
end;
end;*)
{$if BX_SUPPORT_VBE=1}
function bx_vga_c.vbe_mem_read(addr:Bit32u):Bit8u;
var
offset:Bit32u;
begin
offset := addr - $A0000;
Result:=(self.s.vbe_memory[self.s.vbe_bank*65536 + offset]);
end;
procedure bx_vga_c.vbe_mem_write(addr:Bit32u;value:Bit8u);
var
offset:Bit32u;
x_tileno, y_tileno:unsigned;
count:Integer;
begin
offset := self.s.vbe_bank*65536 + (addr - $A0000);
// check for out of memory write
if (offset < sizeof(self.s.vbe_memory)) then
begin
self.s.vbe_memory[offset]:=value;
end
else
begin
// make sure we don't flood the logfile
if (count<100) then
begin
Inc(count);
BX_INFO(Format('VBE_mem_write out of video memory write at %x',[offset]));
end;
end;
// only update the UI when writing 'onscreen'
// FIXME: deal with logical scan lengths and display start sometime (when new DISPI)
if (offset < self.s.vbe_visable_screen_size) then
begin
y_tileno := (offset div self.s.vbe_xres) div Y_TILESIZE;
x_tileno := (offset mod self.s.vbe_xres) div X_TILESIZE;
self.s.vga_mem_updated := 1;
self.s.vga_tile_updated[x_tileno][y_tileno] := 1;
end;
end;
function bx_vga_c.vbe_read_handler(self_ptr:Pointer; address: Bit32u; io_len:unsigned):Bit32u;
begin
{$if BX_USE_VGA_SMF=0}
bx_vga_c *class_ptr := (bx_vga_c *) self_ptr;
return( class_ptr^.vbe_read(address, io_len) );
end;
Bit32u
bx_vga_c.vbe_read(Bit32u address, unsigned io_len)
begin
{$else}
//UNUSED(self_ptr);
{$ifend} // !BX_USE_VGA_SMF
// BX_INFO(('VBE_read %x (len %x)', address, io_len));
if (address=VBE_DISPI_IOPORT_INDEX) then
begin
// index register
Result := self.s.vbe_curindex;
Exit;
end
else
begin
// data register read
case (self.s.vbe_curindex) of
VBE_DISPI_INDEX_ID: // Display Interface ID check
begin
Result:=VBE_DISPI_ID0;
Exit;
end;
VBE_DISPI_INDEX_XRES: // x resolution
begin
Result:=self.s.vbe_xres;
Exit;
end;
VBE_DISPI_INDEX_YRES: // y resolution
begin
Result:=self.s.vbe_yres;
Exit;
end;
VBE_DISPI_INDEX_BPP: // bpp
begin
Result:=self.s.vbe_bpp;
Exit;
end;
VBE_DISPI_INDEX_ENABLE: // vbe enabled
begin
Result:=self.s.vbe_enabled;
Exit;
end;
VBE_DISPI_INDEX_BANK: // current bank
begin
Result:=self.s.vbe_bank;
Exit;
end;
else
begin
BX_PANIC(Format('VBE unknown data read index $%x',[self.s.vbe_curindex]));
end;
end;
end;
BX_PANIC(('VBE_read shouldn''t reach self'));
end;
procedure
bx_vga_c.vbe_write_handler(self_ptr:pointer; address:Bit32u; value:Bit32u; io_len:unsigned);
var
count:integer;
begin
{$if BX_USE_VGA_SMF=0}
bx_vga_c *class_ptr := (bx_vga_c *) self_ptr;
class_ptr^.vbe_write(address, value, io_len);
end;
Bit32u
bx_vga_c.vbe_write(Bit32u address, Bit32u value, unsigned io_len)
begin
{$else}
//UNUSED(self_ptr);
{$ifend}
// BX_INFO(('VBE_write %x := %x (len %x)', address, value, io_len));
if (address=VBE_DISPI_IOPORT_INDEX) then
begin
// index register
self.s.vbe_curindex := Bit16u(value);
end
else
begin
// data register
// FIXME: maybe do some 'sanity' checks on received data?
case (self.s.vbe_curindex) of
VBE_DISPI_INDEX_ID: // Display Interface ID check
begin
if (value <> VBE_DISPI_ID0) then
begin
BX_PANIC(Format('VBE unknown Display Interface %x',[value]));
end
else
begin
// make sure we don't flood the logfile
if (count < 100) then
begin
inc(count);
BX_INFO(Format('VBE known Display Interface %x',[value]));
end;
end;
end;
VBE_DISPI_INDEX_XRES: // set xres
begin
// check that we don't set xres during vbe enabled
if (self.s.vbe_enabled=0) then
begin
// check for within max xres range
if (value <= VBE_DISPI_MAX_XRES) then
begin
self.s.vbe_xres:=Bit16u(value);
end
else
begin
BX_INFO(Format('VBE set xres more then max xres (%d)',[value]));
end;
end
else
begin
BX_INFO(('VBE set xres during vbe enabled!'));
end;
end;
VBE_DISPI_INDEX_YRES: // set yres
begin
// check that we don't set yres during vbe enabled
if (self.s.vbe_enabled=0) then
begin
// check for within max yres range
if (value <= VBE_DISPI_MAX_YRES) then
begin
self.s.vbe_yres:=Bit16u(value);
end
else
begin
BX_INFO(Format('VBE set yres more then max yres (%d)',[value]));
end;
end
else
begin
BX_INFO(('VBE set yres during vbe enabled!'));
end;
end;
VBE_DISPI_INDEX_BPP: // set bpp
begin
// check that we don't set bpp during vbe enabled
if (self.s.vbe_enabled=0) then
begin
// check for correct bpp range
if (value = VBE_DISPI_BPP_8) then
begin
self.s.vbe_bpp:=Bit16u(value);
end
else
begin
BX_INFO(Format('VBE set bpp with unknown bpp (%d)',[value]));
end;
end
else
begin
BX_INFO(('VBE set bpp during vbe enabled!'));
end;
end;
VBE_DISPI_INDEX_BANK: // set bank
begin
value:=value and $ff ; // FIXME lobyte := vbe bank A?
// check for max bank nr
if (value < (VBE_DISPI_TOTAL_VIDEO_MEMORY_MB * 1024 div 64)) then
begin
BX_INFO(Format('VBE set bank to %d', [value]));
self.s.vbe_bank:=value;
end
else
begin
BX_INFO(Format('VBE set invalid bank (%d)',[value]));
end;
end;
VBE_DISPI_INDEX_ENABLE: // enable video
begin
if (value)<>0 then
begin
// FIXME: VBE allows for *not* clearing the screen when setting a mode
// FIXME: make dependant on bpp (currently only 8bpp := 1byte)
self.s.vbe_visable_screen_size := (self.s.vbe_xres) * (self.s.vbe_yres) * 1;
FillChar(self.s.vbe_memory, self.s.vbe_visable_screen_size,0);
BX_INFO(Format('VBE enabling x %d, y %d, bpp %d (0:=8bpp)',[self.s.vbe_xres, self.s.vbe_yres, self.s.vbe_bpp]));
dimension_update(self.s.vbe_xres, self.s.vbe_yres);
end
else
begin
BX_INFO(('VBE disabling'));
end;
self.s.vbe_enabled:=Bool(value);
end;
else
begin
BX_PANIC(Format('VBE unknown data write index $%x',[self.s.vbe_curindex]));
end;
end;
end;
end;
{$ifend}
end.
| 35.103421 | 129 | 0.553502 |
47271c6d7201c174201f5b31d2fb20ee5478f5d0 | 1,788 | pas | Pascal | Lab_2/Unit3.pas | Alex-Kostukov/mpei_labs_1course_2sem | 66c62faac13e34d834e8b0b166a304b513c8193c | [
"MIT"
]
| null | null | null | Lab_2/Unit3.pas | Alex-Kostukov/mpei_labs_1course_2sem | 66c62faac13e34d834e8b0b166a304b513c8193c | [
"MIT"
]
| 1 | 2018-03-10T15:47:10.000Z | 2018-03-12T19:34:51.000Z | Lab_2/Unit3.pas | Alex-Kostukov/mpei_labs_1course_2sem | 66c62faac13e34d834e8b0b166a304b513c8193c | [
"MIT"
]
| null | null | null | unit Unit3;
interface
type
func = function(x: real): real;
function f26(x: real): real;
function f13(x: real): real;
function f5(x: real): real;
function f18(x: real): real;
procedure SolutionSec(x1, x2, e: real; f: func; var x: real; var n: integer);
procedure SolutionIt(x0, factor, e: real; f: func; var x: real; var n: integer);
procedure SolutionN(x0, e: real; f: func; var x: real; var n: integer);
implementation
function f26(x: real): real;
begin
Result := exp(sqr(-sin(x))) + (3 / (7 * x)) / (1 + sqrt(x)) - x;
end;
function f13(x: real): real;
begin
Result := 1 / ((1.2 * sin(x) / cos(x)) + sqrt(x + 1)) - x;
end;
function f5(x: real): real;
begin
Result := 1 / ((sqrt(5) + sin(0.1 * x) + ln(1 + x)) - x);
end;
function f18(x: real): real;
begin
Result := sqrt(exp(x / 3) - (6 * x * sin(x) / 7) - 0.3) - x;
end;
procedure SolutionSec(x1, x2, e: real; f: func; var x: real; var n: integer);
var
x3: real;
begin
x := 0;
n := 0;
repeat
x3 := x2 - f(x2) * (x2 - x1) / (f(x2) - f(x1));
x1 := x2;
x2 := x3;
n := n + 1;
until (abs(x1 - x2) < e) or (n > 10000);
x := x1;
end;
procedure SolutionIt(x0, factor, e: real; f: func; var x: real; var n: integer);
var
x1: real;
begin
x := 0;
n := 0;
repeat
x1 := x0;
x0 := factor * f(x1) + x1;
n := n + 1;
until (abs(x1 - x0) < e) or (n > 10000);
x := (x1 + x0) / 2;
end;
procedure SolutionN(x0, e: real; f: func; var x: real; var n: integer);
var
x1: real;
begin
x := 0;
n := 0;
repeat
x1 := x0;
x0 := x1 - f(x1) * e / (f(x1 + e / 2) - f(x1 - e / 2));
n := n + 1;
until (abs(x1 - x0) < e) or (n > 10000);
x := (x1 + x0) / 2;
end;
end.
| 18.625 | 81 | 0.501119 |
476f0a2102be17c45bf7e1d84ef0f6e9f0a94279 | 2,928 | pas | Pascal | Source/Services/SimpleNotificationService/Base/Transform/AWS.SNS.Transform.PlatformApplicationDisabledExceptionUnmarshaller.pas | gabrielbaltazar/aws-sdk-delphi | ea1713b227a49cbbc5a2e1bf04cbf2de1f9b611a | [
"Apache-2.0"
]
| 1 | 2021-08-18T21:02:27.000Z | 2021-08-18T21:02:27.000Z | Source/Services/SimpleNotificationService/Base/Transform/AWS.SNS.Transform.PlatformApplicationDisabledExceptionUnmarshaller.pas | gabrielbaltazar/aws-sdk-delphi | ea1713b227a49cbbc5a2e1bf04cbf2de1f9b611a | [
"Apache-2.0"
]
| null | null | null | Source/Services/SimpleNotificationService/Base/Transform/AWS.SNS.Transform.PlatformApplicationDisabledExceptionUnmarshaller.pas | gabrielbaltazar/aws-sdk-delphi | ea1713b227a49cbbc5a2e1bf04cbf2de1f9b611a | [
"Apache-2.0"
]
| null | null | null | unit AWS.SNS.Transform.PlatformApplicationDisabledExceptionUnmarshaller;
interface
uses
AWS.Transform.IErrorResponseUnmarshaller,
AWS.Transform.UnmarshallerContext,
AWS.SNS.Model.PlatformApplicationDisabledException,
AWS.Internal.ErrorResponse,
AWS.Transform.SimpleTypeUnmarshaller;
type
IPlatformApplicationDisabledExceptionUnmarshaller = IErrorResponseUnmarshaller<EPlatformApplicationDisabledException, TXmlUnmarshallerContext>;
TPlatformApplicationDisabledExceptionUnmarshaller = class(TInterfacedObject, IErrorResponseUnmarshaller<EPlatformApplicationDisabledException, TXmlUnmarshallerContext>)
strict private
class var FInstance: IPlatformApplicationDisabledExceptionUnmarshaller;
class constructor Create;
public
function Unmarshall(AContext: TXmlUnmarshallerContext): EPlatformApplicationDisabledException; overload;
function Unmarshall(AContext: TXmlUnmarshallerContext; AErrorResponse: TErrorResponse): EPlatformApplicationDisabledException; overload;
class function Instance: IPlatformApplicationDisabledExceptionUnmarshaller; static;
end;
implementation
{ TPlatformApplicationDisabledExceptionUnmarshaller }
function TPlatformApplicationDisabledExceptionUnmarshaller.Unmarshall(AContext: TXmlUnmarshallerContext): EPlatformApplicationDisabledException;
var
ErrorResponse: TErrorResponse;
begin
ErrorResponse := TErrorResponse.Create;
try
Result := Unmarshall(AContext, ErrorResponse);
finally
ErrorResponse.Free;
end;
end;
function TPlatformApplicationDisabledExceptionUnmarshaller.Unmarshall(AContext: TXmlUnmarshallerContext; AErrorResponse: TErrorResponse): EPlatformApplicationDisabledException;
var
OriginalDepth: Integer;
TargetDepth: Integer;
Response: EPlatformApplicationDisabledException;
begin
Response := EPlatformApplicationDisabledException.Create(AErrorResponse.Message, AErrorResponse.InnerException, AErrorResponse.ErrorType, AErrorResponse.Code, AErrorResponse.RequestId, AErrorResponse.StatusCode);
try
OriginalDepth := AContext.CurrentDepth;
TargetDepth := OriginalDepth + 1;
if AContext.IsStartOfDocument then
Inc(TargetDepth, 2);
while AContext.ReadAtDepth(OriginalDepth) do
if AContext.IsStartElement or AContext.IsAttribute then
if AContext.TestExpression('message', TargetDepth) then
begin
var Unmarshaller := TStringUnmarshaller.Instance;
Response.Message := Unmarshaller.Unmarshall(AContext);
Continue;
end;
Result := Response;
Response := nil;
finally
Response.Free;
end;
end;
class constructor TPlatformApplicationDisabledExceptionUnmarshaller.Create;
begin
FInstance := TPlatformApplicationDisabledExceptionUnmarshaller.Create;
end;
class function TPlatformApplicationDisabledExceptionUnmarshaller.Instance: IPlatformApplicationDisabledExceptionUnmarshaller;
begin
Result := FInstance;
end;
end.
| 37.063291 | 214 | 0.82377 |
f1ac5d00265501a3b354132e61a59443de0ce829 | 2,785 | dfm | Pascal | SettingsUnit.dfm | SuperIzzo/Formula-Wizard | adec6b4c6f98bb018c49604eced86a7e007993e6 | [
"MIT"
]
| null | null | null | SettingsUnit.dfm | SuperIzzo/Formula-Wizard | adec6b4c6f98bb018c49604eced86a7e007993e6 | [
"MIT"
]
| null | null | null | SettingsUnit.dfm | SuperIzzo/Formula-Wizard | adec6b4c6f98bb018c49604eced86a7e007993e6 | [
"MIT"
]
| null | null | null | object SettingsBox: TSettingsBox
Left = 160
Top = 101
Width = 518
Height = 401
Caption = 'Settings'
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
OnCreate = FormCreate
OnShow = FormShow
PixelsPerInch = 96
TextHeight = 13
object Button2: TButton
Left = 240
Top = 336
Width = 75
Height = 25
Caption = 'Ok'
TabOrder = 0
OnClick = Button2Click
end
object Button3: TButton
Left = 416
Top = 336
Width = 75
Height = 25
Cancel = True
Caption = 'Cancel'
TabOrder = 1
OnClick = Button3Click
end
object Button5: TButton
Left = 328
Top = 336
Width = 75
Height = 25
Caption = 'Apply'
TabOrder = 2
OnClick = Button5Click
end
object PageControl1: TPageControl
Left = 0
Top = 0
Width = 510
Height = 329
ActivePage = AppSetPG
Align = alCustom
TabOrder = 3
object AppSetPG: TTabSheet
Caption = 'General'
object Label2: TLabel
Left = 8
Top = 80
Width = 72
Height = 13
Caption = 'Temp Directory'
end
object Label1: TLabel
Left = 8
Top = 48
Width = 72
Height = 13
Caption = 'Desktop Image'
end
object Label3: TLabel
Left = 8
Top = 112
Width = 42
Height = 13
Caption = 'Languge'
end
object Edit2: TEdit
Left = 88
Top = 80
Width = 289
Height = 21
TabOrder = 0
end
object Button4: TButton
Left = 384
Top = 80
Width = 75
Height = 25
Caption = 'Browse'
TabOrder = 1
OnClick = Button4Click
end
object CheckBox1: TCheckBox
Left = 8
Top = 144
Width = 369
Height = 17
Caption = 'Load most recently used database on startup'
TabOrder = 2
end
object CheckBox2: TCheckBox
Left = 8
Top = 168
Width = 369
Height = 17
Caption = 'Load unexpectedly closed database'
Checked = True
State = cbChecked
TabOrder = 3
end
object Edit1: TEdit
Left = 88
Top = 48
Width = 289
Height = 21
TabOrder = 4
end
object Button1: TButton
Left = 384
Top = 48
Width = 75
Height = 25
Caption = 'Browse'
TabOrder = 5
OnClick = Button1Click
end
object ComboBox1: TComboBox
Left = 88
Top = 112
Width = 289
Height = 21
ItemHeight = 13
TabOrder = 6
end
end
end
end
| 20.181159 | 63 | 0.52711 |
61b86c856ac6888c0eb04c616c1cacc9c9cfb9c0 | 3,066 | dfm | Pascal | net.ssa/Editors/LevelEditor/FrameSound.dfm | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
]
| 1 | 2022-03-26T17:00:19.000Z | 2022-03-26T17:00:19.000Z | net.ssa/Editors/LevelEditor/FrameSound.dfm | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
]
| null | null | null | net.ssa/Editors/LevelEditor/FrameSound.dfm | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
]
| 1 | 2022-03-26T17:00:21.000Z | 2022-03-26T17:00:21.000Z | object fraSound: TfraSound
Left = 0
Top = 0
Width = 443
Height = 277
VertScrollBar.Visible = False
Align = alClient
Constraints.MaxWidth = 154
Constraints.MinWidth = 123
Color = 10528425
Font.Charset = DEFAULT_CHARSET
Font.Color = clBlack
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
ParentColor = False
ParentFont = False
TabOrder = 0
object paAppend: TPanel
Left = 0
Top = 0
Width = 443
Height = 48
Align = alTop
Constraints.MaxWidth = 123
Constraints.MinWidth = 123
ParentColor = True
TabOrder = 0
object APHeadLabel1: TLabel
Left = 1
Top = 1
Width = 441
Height = 13
Align = alTop
Alignment = taCenter
Caption = 'Append Sound'
Color = clGray
ParentColor = False
OnClick = ExpandClick
end
object ExtBtn2: TExtBtn
Left = 110
Top = 2
Width = 11
Height = 11
Align = alNone
CloseButton = False
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
Glyph.Data = {
DE000000424DDE00000000000000360000002800000007000000070000000100
180000000000A8000000120B0000120B00000000000000000000FFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000FFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFF000000FFFFFFFFFFFFFFFFFF000000FFFFFFFFFFFFFFFFFF00
0000FFFFFFFFFFFF000000000000000000FFFFFFFFFFFF000000FFFFFF000000
000000000000000000000000FFFFFF0000000000000000000000000000000000
00000000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00
0000}
ParentFont = False
OnClick = PaneMinClick
end
object ebTypeStaticSource: TExtBtn
Left = 2
Top = 16
Width = 120
Height = 15
Align = alNone
BevelShow = False
HotTrack = True
HotColor = 15790320
CloseButton = False
GroupIndex = 1
Down = True
Caption = 'Static Source'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
ParentFont = False
end
object ebTypeEnvironment: TExtBtn
Left = 2
Top = 31
Width = 120
Height = 15
Align = alNone
BevelShow = False
HotTrack = True
HotColor = 15790320
CloseButton = False
GroupIndex = 1
Caption = 'Environment'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
ParentFont = False
end
end
object fsStorage: TFormStorage
IniSection = 'FrameShape'
Options = []
Version = 3
StoredProps.Strings = (
'paAppend.Tag'
'paAppend.Height'
'ebTypeEnvironment.Down'
'ebTypeStaticSource.Down')
StoredValues = <>
end
end
| 26.205128 | 73 | 0.615134 |
470fa154c10db582e353d0d451b6691e911a7647 | 1,212 | pas | Pascal | src/Tasks/Implementations/Project/Cgi/CreateCgiReadmeFileTaskImpl.pas | atkins126/fano-cli | 29db4dfba28b164d3acf6de33075f88753731eaf | [
"MIT"
]
| 10 | 2018-11-10T22:58:49.000Z | 2022-03-09T23:36:18.000Z | src/Tasks/Implementations/Project/Cgi/CreateCgiReadmeFileTaskImpl.pas | atkins126/fano-cli | 29db4dfba28b164d3acf6de33075f88753731eaf | [
"MIT"
]
| 8 | 2019-09-24T03:30:27.000Z | 2021-09-14T02:15:06.000Z | src/Tasks/Implementations/Project/Cgi/CreateCgiReadmeFileTaskImpl.pas | atkins126/fano-cli | 29db4dfba28b164d3acf6de33075f88753731eaf | [
"MIT"
]
| 2 | 2020-07-06T12:35:11.000Z | 2021-11-30T05:35:09.000Z | (*!------------------------------------------------------------
* Fano CLI Application (https://fanoframework.github.io)
*
* @link https://github.com/fanoframework/fano-cli
* @copyright Copyright (c) 2018 - 2020 Zamrony P. Juhara
* @license https://github.com/fanoframework/fano-cli/blob/master/LICENSE (MIT)
*------------------------------------------------------------- *)
unit CreateCgiReadmeFileTaskImpl;
interface
{$MODE OBJFPC}
{$H+}
uses
TaskOptionsIntf,
TaskIntf,
CreateReadmeFileTaskImpl;
type
(*!--------------------------------------
* Task that create web application project
* custom README file for CGI project
*
* @author Zamrony P. Juhara <zamronypj@yahoo.com>
*---------------------------------------*)
TCreateCgiReadmeFileTask = class(TCreateReadmeFileTask)
protected
procedure createReadmeFile(const dir : string); override;
end;
implementation
uses
sysutils;
procedure TCreateCgiReadmeFileTask.createReadmeFile(const dir : string);
var
{$INCLUDE src/Tasks/Implementations/Project/Cgi/Includes/readme.md.inc}
begin
createTextFile(dir + '/README.md', strReadme);
end;
end.
| 25.25 | 81 | 0.574257 |
f17750c2469a80dad72e74a8262d7e1127680af5 | 3,895 | pas | Pascal | Lib/PngComponents/Source/PngButtonFunctions.pas | natvincent/stock | b6d9b084ae7bf71d10a1c3cac1b4fa4730d233cc | [
"CC-BY-3.0"
]
| null | null | null | Lib/PngComponents/Source/PngButtonFunctions.pas | natvincent/stock | b6d9b084ae7bf71d10a1c3cac1b4fa4730d233cc | [
"CC-BY-3.0"
]
| null | null | null | Lib/PngComponents/Source/PngButtonFunctions.pas | natvincent/stock | b6d9b084ae7bf71d10a1c3cac1b4fa4730d233cc | [
"CC-BY-3.0"
]
| null | null | null | unit PngButtonFunctions;
interface
uses
Types, Windows, Buttons, Graphics, pngimage;
{$IF RTLVersion < 20.0 }
type
TPngImage = TPNGObject;
{$IFEND}
procedure CalcButtonLayout(Canvas: TCanvas; PngImage: TPngImage; const Client:
TRect; Pressed, Down: Boolean; const Caption: string; Layout: TButtonLayout;
Margin, Spacing: Integer; var GlyphPos, TextPos: TPoint; BiDiFlags: LongInt);
implementation
uses
Classes;
procedure CalcButtonLayout(Canvas: TCanvas; PngImage: TPngImage; const Client:
TRect; Pressed, Down: Boolean; const Caption: string; Layout: TButtonLayout;
Margin, Spacing: Integer; var GlyphPos, TextPos: TPoint; BiDiFlags: LongInt);
var
ClientSize, GlyphSize, TextSize, TotalSize: TPoint;
TextBounds: TRect;
begin
if (BiDiFlags and DT_RIGHT) = DT_RIGHT then begin
if Layout = blGlyphLeft then
Layout := blGlyphRight
else if Layout = blGlyphRight then
Layout := blGlyphLeft;
end;
//Calculate the item sizes
ClientSize := Point(Client.Right - Client.Left, Client.Bottom - Client.Top);
if PngImage <> nil then
GlyphSize := Point(PngImage.Width, PngImage.Height)
else
GlyphSize := Point(0, 0);
if Length(Caption) > 0 then begin
TextBounds := Rect(0, 0, Client.Right - Client.Left, 0);
DrawText(Canvas.Handle, PChar(Caption), Length(Caption), TextBounds,
DT_CALCRECT or BiDiFlags);
TextSize := Point(TextBounds.Right - TextBounds.Left, TextBounds.Bottom -
TextBounds.Top);
end
else begin
TextBounds := Rect(0, 0, 0, 0);
TextSize := Point(0, 0);
end;
//If the layout has the glyph on the right or the left, then both the
//text and the glyph are centered vertically. If the glyph is on the top
//or the bottom, then both the text and the glyph are centered horizontally.
if Layout in [blGlyphLeft, blGlyphRight] then
GlyphPos.Y := (ClientSize.Y - GlyphSize.Y + 1) div 2
else
GlyphPos.X := (ClientSize.X - GlyphSize.X + 1) div 2;
//If there is no text or no bitmap, then Spacing is irrelevant
if (TextSize.X = 0) or (GlyphSize.X = 0) then
Spacing := 0;
//Adjust Margin and Spacing
if Margin = -1 then begin
if Spacing = -1 then begin
TotalSize := Point(GlyphSize.X + TextSize.X, GlyphSize.Y + TextSize.Y);
if Layout in [blGlyphLeft, blGlyphRight] then
Margin := (ClientSize.X - TotalSize.X) div 3
else
Margin := (ClientSize.Y - TotalSize.Y) div 3;
end
else begin
TotalSize := Point(GlyphSize.X + Spacing + TextSize.X, GlyphSize.Y +
Spacing + TextSize.Y);
if Layout in [blGlyphLeft, blGlyphRight] then
Margin := (ClientSize.X - TotalSize.X) div 2
else
Margin := (ClientSize.Y - TotalSize.Y) div 2;
end
end
else if Spacing = -1 then begin
TotalSize := Point(ClientSize.X - (Margin + GlyphSize.X), ClientSize.Y -
(Margin + GlyphSize.Y));
end;
case Layout of
blGlyphLeft: GlyphPos.X := Margin;
blGlyphRight: GlyphPos.X := ClientSize.X - Margin - GlyphSize.X;
blGlyphTop: GlyphPos.Y := Margin;
blGlyphBottom: GlyphPos.Y := ClientSize.Y - Margin - GlyphSize.Y;
end;
if Layout in [blGlyphLeft, blGlyphRight] then
TextPos.Y := (ClientSize.Y - TextSize.Y) div 2
else
TextPos.X := (ClientSize.X - TextSize.X) div 2;
case Layout of
blGlyphLeft: TextPos.X := GlyphPos.X + GlyphSize.X + Spacing;
blGlyphRight: TextPos.X := GlyphPos.X - Spacing - TextSize.X;
blGlyphTop: TextPos.Y := GlyphPos.Y + GlyphSize.Y + Spacing;
blGlyphBottom: TextPos.Y := GlyphPos.Y - Spacing - TextSize.Y;
end;
//Fixup the result variables
with GlyphPos do begin
Inc(X, Client.Left + Integer(Pressed or Down));
Inc(Y, Client.Top + Integer(Pressed or Down));
end;
with TextPos do begin
Inc(X, Client.Left + Integer(Pressed or Down));
Inc(Y, Client.Top + Integer(Pressed or Down));
end;
end;
end.
| 32.190083 | 79 | 0.679332 |
6a6924295705e8123ac914c7c9d7e0176f22365f | 5,817 | pas | Pascal | SH02/FB/RiggVar.FB.ActionMap.pas | federgraph/SudokuHelper | 331e9069232350cd5454b2fb01b82f17382e1d36 | [
"CC0-1.0"
]
| null | null | null | SH02/FB/RiggVar.FB.ActionMap.pas | federgraph/SudokuHelper | 331e9069232350cd5454b2fb01b82f17382e1d36 | [
"CC0-1.0"
]
| null | null | null | SH02/FB/RiggVar.FB.ActionMap.pas | federgraph/SudokuHelper | 331e9069232350cd5454b2fb01b82f17382e1d36 | [
"CC0-1.0"
]
| null | null | null | unit RiggVar.FB.ActionMap;
(*
-
- F
- * * *
- * * G
- * * * *
- E - - - H - - - I
- * * * *
- * * * *
- * * * *
- D-------A---------------B
- *
- (C) federgraph.de
-
*)
interface
uses
RiggVar.FB.ActionConst,
System.SysUtils,
System.Classes,
System.UITypes;
type
TCornerLocation = (TopLeft, TopRight, BottomRight, BottomLeft);
TInitActionProc = procedure (BtnID: Integer; Action: TFederAction) of object;
TInitActionColorProc = procedure (BtnID: Integer; Action: TFederAction; cla: TAlphaColor) of object;
TActionMapBase = class
private
FActionProc: TInitActionProc;
FActionColorProc: TInitActionColorProc;
procedure SetActionColorProc(const Value: TInitActionColorProc);
procedure SetActionProc(const Value: TInitActionProc);
procedure SetPageCount(const Value: Integer);
protected
TestName: string;
FPageCount: Integer;
procedure InitAction(BtnID: Integer; Action: TFederAction);
procedure IAC(BtnID: Integer; Action: TFederAction; cla: TAlphaColor); virtual;
public
class var CurrentPageCaption: string;
constructor Create;
procedure InitActions(Layout: Integer); virtual;
property ActionProc: TInitActionProc read FActionProc write SetActionProc;
property ActionColorProc: TInitActionColorProc read FActionColorProc write SetActionColorProc;
property PageCount: Integer read FPageCount write SetPageCount;
end;
TCollectibleActionMap = class(TActionMapBase)
private
procedure TestProcAll(BtnID: Integer; Action: TFederAction);
procedure TestProcOne(BtnID: Integer; Action: TFederAction);
procedure DoCollectMappings;
procedure TestProcOneIAC(BtnID: Integer; Action: TFederAction; cla: TAlphaColor);
procedure TestProcAllIAC(BtnID: Integer; Action: TFederAction; cla: TAlphaColor);
protected
TestAction: TFederAction;
TestPage: Integer;
TestList: TStrings;
TestProc: TInitActionProc;
TestProcIAC: TInitActionColorProc;
public
procedure CollectOne(fa: TFederAction; ML: TStrings);
procedure CollectAll(ML: TStrings);
end;
TEscapableActionMap = class(TCollectibleActionMap)
private
function GetEscapeIndex: Integer;
procedure SetEscapeIndex(const Value: Integer);
procedure SetMaxIndex(const Value: Integer);
function GetMaxIndex: Integer;
protected
FMaxIndex: Integer;
FEscapeIndex: Integer;
public
constructor Create;
property MaxIndex: Integer read GetMaxIndex write SetMaxIndex;
property EscapeIndex: Integer read GetEscapeIndex write SetEscapeIndex;
end;
TActionMap = TEscapableActionMap;
implementation
uses
RiggVar.FB.ActionShort,
RiggVar.FB.ActionLong;
{ TActionMapBase }
procedure TActionMapBase.InitActions(Layout: Integer);
begin
//virtual
end;
constructor TActionMapBase.Create;
begin
FPageCount := 1;
end;
procedure TActionMapBase.InitAction(BtnID: Integer; Action: TFederAction);
begin
if Assigned(ActionProc) then
ActionProc(BtnID, Action);
end;
procedure TActionMapBase.IAC(BtnID: Integer; Action: TFederAction; cla: TAlphaColor);
begin
if Assigned(ActionColorProc) then
ActionColorProc(BtnID, Action, cla);
end;
procedure TActionMapBase.SetActionColorProc(const Value: TInitActionColorProc);
begin
FActionColorProc := Value;
end;
procedure TActionMapBase.SetActionProc(const Value: TInitActionProc);
begin
FActionProc := Value;
end;
procedure TActionMapBase.SetPageCount(const Value: Integer);
begin
FPageCount := Value;
end;
{ TEscapableActionMap }
constructor TEscapableActionMap.Create;
begin
inherited;
FEscapeIndex := 2;
end;
function TEscapableActionMap.GetEscapeIndex: Integer;
begin
if FEscapeIndex <= 0 then
result := FPageCount + 1
else if FEscapeIndex > FPageCount + 1 then
result := FPageCount + 1
else
result := FEscapeIndex;
end;
procedure TEscapableActionMap.SetEscapeIndex(const Value: Integer);
begin
FEscapeIndex := Value;
end;
function TEscapableActionMap.GetMaxIndex: Integer;
begin
if (FMaxIndex > 0) and (FMaxIndex <= PageCount) then
result := FMaxIndex
else
result := FPageCount;
end;
procedure TEscapableActionMap.SetMaxIndex(const Value: Integer);
begin
FMaxIndex := Value;
end;
{ TCollectibleActionMap }
procedure TCollectibleActionMap.DoCollectMappings;
var
p: Integer;
iap: TInitActionProc;
iacp: TInitActionColorProc;
begin
iap := ActionProc;
iacp := ActionColorProc;
ActionProc := TestProc;
ActionColorProc := TestProcIAC;
for p := 1 to PageCount do
begin
TestPage := p;
InitActions(p);
end;
ActionProc := iap;
ActionColorProc := iacp;
end;
procedure TCollectibleActionMap.CollectAll(ML: TStrings);
begin
TestList := ML;
TestProc := TestProcAll;
TestProcIAC := TestProcAllIAC;
DoCollectMappings;
end;
procedure TCollectibleActionMap.CollectOne(fa: TFederAction; ML: TStrings);
begin
TestAction := fa;
TestList := ML;
TestProc := TestProcOne;
TestProcIAC := TestProcOneIAC;
DoCollectMappings;
end;
procedure TCollectibleActionMap.TestProcOne(BtnID: Integer; Action: TFederAction);
begin
if Action = TestAction then
TestList.Add(Format('%s %d/%d', [TestName, TestPage, BtnID]));
end;
procedure TCollectibleActionMap.TestProcOneIAC(BtnID: Integer; Action: TFederAction; cla: TAlphaColor);
begin
TestProcOne(BtnID, Action);
end;
procedure TCollectibleActionMap.TestProcAll(BtnID: Integer; Action: TFederAction);
begin
TestList.Add(Format('%s %d/%d %s = %s', [
TestName,
TestPage,
BtnID,
GetFederActionLong(Action),
GetFederActionShort(Action)
]));
end;
procedure TCollectibleActionMap.TestProcAllIAC(BtnID: Integer; Action: TFederAction; cla: TAlphaColor);
begin
TestProcAll(BtnID, Action);
end;
end.
| 24.544304 | 103 | 0.731649 |
f1a6311184beda5846df1770eda5209f5fce5bd1 | 2,896 | pas | Pascal | Libraries/TzObjectInspector/zGraphicDialog.pas | jomael/Concepts | 82d18029e41d55e897d007f826c021cdf63e53f8 | [
"Apache-2.0"
]
| 62 | 2016-01-20T16:26:25.000Z | 2022-02-28T14:25:52.000Z | Libraries/TzObjectInspector/zGraphicDialog.pas | jomael/Concepts | 82d18029e41d55e897d007f826c021cdf63e53f8 | [
"Apache-2.0"
]
| null | null | null | Libraries/TzObjectInspector/zGraphicDialog.pas | jomael/Concepts | 82d18029e41d55e897d007f826c021cdf63e53f8 | [
"Apache-2.0"
]
| 20 | 2016-09-08T00:15:22.000Z | 2022-01-26T13:13:08.000Z | // **************************************************************************************************
// The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the
// License at http://www.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either express or implied. See the License for the specific language governing rights
// and limitations under the License.
//
// The Original Code is zGraphicDialog.pas.
//
// The Initial Developer of the Original Code is Mahdi Safsafi [SMP3].
// Portions created by Mahdi Safsafi . are Copyright (C) 2013-2017 Mahdi Safsafi .
// All Rights Reserved.
//
// **************************************************************************************************
unit zGraphicDialog;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
zObjInspector;
type
TGraphicDialog = class(TzInspDialog)
BtnSave: TButton;
BtnCancel: TButton;
BtnLoad: TButton;
opd: TOpenDialog;
Panel1: TPanel;
Image1: TImage;
procedure BtnLoadClick(Sender: TObject);
procedure BtnSaveClick(Sender: TObject);
procedure BtnCancelClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
FUserGraphic: TGraphic;
FGraphic: TGraphic;
FFilter: string;
public
{ Public declarations }
protected
procedure InitDialog; override;
procedure DisplayGraphic(AGraphic: TGraphic);
end;
implementation
uses Types;
{$R *.dfm}
procedure TGraphicDialog.BtnCancelClick(Sender: TObject);
begin
ModalResult := mrNone;
Close;
end;
procedure TGraphicDialog.BtnLoadClick(Sender: TObject);
begin
opd.Filter := FFilter;
if opd.Execute then
begin
FUserGraphic.LoadFromFile(opd.FileName);
DisplayGraphic(FUserGraphic);
end;
end;
procedure TGraphicDialog.BtnSaveClick(Sender: TObject);
begin
FGraphic.Assign(FUserGraphic);
ModalResult := mrOk;
Close;
end;
procedure TGraphicDialog.DisplayGraphic(AGraphic: TGraphic);
var
LBMP: TBitmap;
begin
LBMP := TBitmap.Create;
LBMP.Assign(AGraphic);
Image1.Picture.Bitmap := LBMP;
LBMP.Free;
end;
procedure TGraphicDialog.FormDestroy(Sender: TObject);
begin
FreeAndNil(FUserGraphic);
end;
procedure TGraphicDialog.InitDialog;
begin
FGraphic := TGraphic(PropItem.Value.AsObject);
if FGraphic is TBitmap then
FFilter := 'Bitmaps|*.bmp'
else if FGraphic is TIcon then
FFilter := 'Icons|*.ico'
else
FFilter := '';
FUserGraphic := TGraphicClass(FGraphic.ClassType).Create;
FUserGraphic.Assign(FGraphic);
DisplayGraphic(FUserGraphic);
end;
end.
| 26.327273 | 101 | 0.6875 |
f1c44881ba0afd57ee8dd4e750e646f920dba9f8 | 261 | pas | Pascal | Test/SimpleScripts/const_array4.pas | skolkman/dwscript | b9f99d4b8187defac3f3713e2ae0f7b83b63d516 | [
"Condor-1.1"
]
| 79 | 2015-03-18T10:46:13.000Z | 2022-03-17T18:05:11.000Z | Test/SimpleScripts/const_array4.pas | skolkman/dwscript | b9f99d4b8187defac3f3713e2ae0f7b83b63d516 | [
"Condor-1.1"
]
| 6 | 2016-03-29T14:39:00.000Z | 2020-09-14T10:04:14.000Z | Test/SimpleScripts/const_array4.pas | skolkman/dwscript | b9f99d4b8187defac3f3713e2ae0f7b83b63d516 | [
"Condor-1.1"
]
| 25 | 2016-05-04T13:11:38.000Z | 2021-09-29T13:34:31.000Z | type TEnum = (en1, en2, en3);
type TEnumArray = array [TEnum] of string;
const ac : TEnumArray = ('one', 'two', 'three');
const ac2 : TEnumArray = ac;
var i : TEnum;
for i in TEnum do
PrintLn(ac[i]);
for i in TEnum do
PrintLn(ac2[i]); | 18.642857 | 49 | 0.590038 |
8564122e846feeeffe0ea5c1fc00a0c729f44d7c | 6,267 | pas | Pascal | App/Views/READCOM.Views.Menu.HUD.pas | atkins126/READCOM_App | 8425eaa5c134caee33a89dc77b57593a418a4eda | [
"MIT"
]
| null | null | null | App/Views/READCOM.Views.Menu.HUD.pas | atkins126/READCOM_App | 8425eaa5c134caee33a89dc77b57593a418a4eda | [
"MIT"
]
| null | null | null | App/Views/READCOM.Views.Menu.HUD.pas | atkins126/READCOM_App | 8425eaa5c134caee33a89dc77b57593a418a4eda | [
"MIT"
]
| null | null | null | unit READCOM.Views.Menu.HUD;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.Controls.Presentation, System.ImageList, FMX.ImgList,
FMX.Layouts, System.Actions, FMX.ActnList,
FMX.MultiView, SubjectStand, FrameStand,
READCOM.Views.About, //for TAboutFrame
READCOM.App.Globals;
type
TEditModeChangedEvent = procedure (Sender: TObject; const Value: Boolean) of object;
TStructureVisibleChangedEvent = procedure (Sender: TObject; const Value: Boolean) of object;
TTargetsVisibleChangedEvent = procedure (Sender: TObject; const Value: Boolean) of object;
TStoryHUD = class(TFrame)
btnAddTextStoryItem: TSpeedButton;
btnPrevious: TSpeedButton;
btnToggleEditMode: TSpeedButton;
BtnMenu: TSpeedButton;
btnNext: TSpeedButton;
layoutButtonsNavigation: TLayout;
ActionList: TActionList;
actionPrevious: TAction;
actionNext: TAction;
actionAddTextStoryItem: TAction;
actionAbout: TAction;
actionMenu: TAction;
layoutButtons: TLayout;
MultiView: TMultiView;
btnToggleStructureVisible: TSpeedButton;
MultiViewFrameStand: TFrameStand;
layoutContent: TLayout;
btnToggleTargetsVisible: TSpeedButton;
layoutButtonsMain: TFlowLayout;
layoutButtonsEdit: TFlowLayout;
actionLoad: TAction;
actionSave: TAction;
btnLoad: TSpeedButton;
btnSave: TSpeedButton;
actionNew: TAction;
btnNew: TSpeedButton;
actionHome: TAction;
btnHome: TSpeedButton;
actionHelp: TAction;
btnHelp: TSpeedButton;
btnAbout: TSpeedButton;
actionCopy: TAction;
actionPaste: TAction;
btnCopy: TSpeedButton;
btnPaste: TSpeedButton;
actionDelete: TAction;
btnDelete: TSpeedButton;
procedure actionAboutExecute(Sender: TObject);
procedure actionMenuExecute(Sender: TObject);
procedure actionHelpExecute(Sender: TObject);
procedure btnToggleStructureVisibleClick(Sender: TObject);
procedure btnToggleEditModeClick(Sender: TObject);
procedure btnToggleTargetsVisibleClick(Sender: TObject);
protected
FAboutFrame: TAboutFrame;
FMultiViewOpenedWidth: Single;
FEditMode: Boolean;
FStructureVisible: Boolean;
FTargetsVisible: Boolean;
FEditModeChanged: TEditModeChangedEvent;
FStructureVisibleChanged: TStructureVisibleChangedEvent;
FTargetsVisibleChanged: TTargetsVisibleChangedEvent;
{EditMode}
procedure SetEditMode(const Value: Boolean); virtual;
{StructureVisible}
procedure SetStructureVisible(const Value: Boolean);
{TargetsVisible}
procedure SetTargetsVisible(const Value: Boolean);
public
constructor Create(AOwner: TComponent); override;
published
property EditMode: Boolean read FEditMode write SetEditMode default false;
property StructureVisible: Boolean read FStructureVisible write SetStructureVisible default false;
property TargetsVisible: Boolean read FTargetsVisible write SetTargetsVisible default false;
property OnEditModeChanged: TEditModeChangedEvent read FEditModeChanged write FEditModeChanged;
property OnStructureVisibleChanged: TStructureVisibleChangedEvent read FStructureVisibleChanged write FStructureVisibleChanged;
property OnTargetsVisibleChanged: TTargetsVisibleChangedEvent read FTargetsVisibleChanged write FTargetsVisibleChanged;
end;
implementation
uses
u_UrlOpen; //for url_Open_In_Browser
{$R *.fmx}
constructor TStoryHUD.Create(AOwner: TComponent);
begin
inherited;
FEditMode := false;
FMultiViewOpenedWidth := MultiView.Width;
FTargetsVisible := false;
StructureVisible := false; //calling the "setter" to hide the side panel (which is open in design mode to define its width)
end;
{$REGION 'Properties'}
{$region 'EditMode'}
procedure TStoryHUD.SetEditMode(const Value: Boolean);
begin
FEditMode := Value;
btnToggleEditMode.IsPressed := Value; //don't use "Pressed", need to use "IsPressed"
layoutButtonsEdit.Visible := Value; //show Edit-related buttons
if not Value then
StructureVisible := false; //hide StructureView when existing EditMode
if Assigned(FEditModeChanged) then
FEditModeChanged(Self, Value);
end;
{$endregion}
{$region 'StrucureViewVisible'}
procedure TStoryHUD.SetStructureVisible(const Value: Boolean);
begin
FStructureVisible := Value;
btnToggleStructureVisible.IsPressed := Value; //don't use "Pressed", need to use "IsPressed"
if Value then
MultiView.Width := FMultiViewOpenedWidth
else
MultiView.Width := 0;
if Assigned(FStructureVisibleChanged) then
FStructureVisibleChanged(Self, Value);
end;
{$endregion}
{$region 'TargetsVisible'}
procedure TStoryHUD.SetTargetsVisible(const Value: Boolean);
begin
FTargetsVisible := Value;
btnToggleTargetsVisible.IsPressed := Value; //don't use "Pressed", need to use "IsPressed"
if Assigned(FTargetsVisibleChanged) then
FTargetsVisibleChanged(Self, Value);
end;
{$endregion}
{$ENDREGION}
{$REGION 'Actions'}
procedure TStoryHUD.actionMenuExecute(Sender: TObject);
begin
layoutButtons.Visible := actionMenu.Checked;
end;
{$region 'Edit actions'}
procedure TStoryHUD.btnToggleEditModeClick(Sender: TObject);
begin
EditMode := not EditMode; //don't use "btnToggleEditMode.Pressed", returns inconsistent values
end;
{$endregion}
{$region 'View actions'}
procedure TStoryHUD.btnToggleStructureVisibleClick(Sender: TObject);
begin
StructureVisible := not StructureVisible; //don't use "btnToggleStructureVisible.Pressed", returns inconsistent values
end;
procedure TStoryHUD.btnToggleTargetsVisibleClick(Sender: TObject);
begin
TargetsVisible := not TargetsVisible; //don't use "btnToggleTargetsVisible.Pressed", returns inconsistent values
end;
{$endregion}
{$region 'Help actions'}
procedure TStoryHUD.actionHelpExecute(Sender: TObject);
begin
url_Open_In_Browser(URL_HELP);
end;
procedure TStoryHUD.actionAboutExecute(Sender: TObject);
begin
if not Assigned(FAboutFrame) then
begin
FAboutFrame := TAboutFrame.Create(Self);
FAboutFrame.Align := TAlignLayout.Center;
end;
FAboutFrame.Parent := Self;
FAboutFrame.Visible := true;
end;
{$endregion}
{$ENDREGION}
end.
| 28.103139 | 131 | 0.768948 |
83006aa8502166c26812f4731ca978850ee2afbb | 714 | pas | Pascal | Source/TestedUnit1.pas | interestingitems/DelphiCodeCoveragePlugin | 2bb32123ae1ea575f072d452d71fe68661a2b0c4 | [
"MIT"
]
| 5 | 2021-10-21T04:30:29.000Z | 2022-01-20T20:37:53.000Z | Source/TestedUnit1.pas | interestingitems/DelphiCodeCoveragePlugin | 2bb32123ae1ea575f072d452d71fe68661a2b0c4 | [
"MIT"
]
| 3 | 2021-10-21T09:20:10.000Z | 2021-11-09T13:14:35.000Z | Source/TestedUnit1.pas | interestingitems/DelphiCodeCoveragePlugin | 2bb32123ae1ea575f072d452d71fe68661a2b0c4 | [
"MIT"
]
| 1 | 2021-10-21T04:32:39.000Z | 2021-10-21T04:32:39.000Z | unit TestedUnit1;
interface
type
TTestedClass = class
public
procedure TestedMethod1(A, B: Integer; out C: Integer);
procedure TestedMethod2(A, B: Integer; out C: Integer);
end;
implementation
procedure TTestedClass.TestedMethod1(A, B: Integer; out C: Integer);
begin
if A < 0 then begin
A := -A;
end;
if B < 0 then
begin
B := -B;
end;
if B < A then begin
C := A - B;
end
else begin
C := B - A;
end;
end;
procedure TTestedClass.TestedMethod2(A, B: Integer; out C: Integer);
begin
if A < 0 then begin
A := -A;
end;
if B < 0 then
begin
B := -B;
end;
if B < A then begin
C := A - B;
end
else begin
C := B - A;
end;
end;
end.
| 13.471698 | 68 | 0.586835 |
83f53138a9b7a21c3904549f4fe3c82d16eedfda | 7,743 | pas | Pascal | Source/Data/FireDAC/WiRL.Data.FireDAC.Updates.pas | MARS-library/mars | 2fc30f0ef0154fb9ba30c650dc85d3f9b94ec0dc | [
"Apache-2.0"
]
| 147 | 2016-11-28T15:22:48.000Z | 2022-03-25T05:36:48.000Z | Source/Data/FireDAC/WiRL.Data.FireDAC.Updates.pas | eStreamSoftware/WiRL | 4bd105af425c65797791480426dffe6bc4e0d73b | [
"Apache-2.0"
]
| 14 | 2017-10-18T23:28:07.000Z | 2021-08-03T15:14:35.000Z | Source/Data/FireDAC/WiRL.Data.FireDAC.Updates.pas | eStreamSoftware/WiRL | 4bd105af425c65797791480426dffe6bc4e0d73b | [
"Apache-2.0"
]
| 57 | 2016-11-28T08:17:43.000Z | 2022-03-28T10:24:57.000Z | unit WiRL.Data.FireDAC.Updates;
interface
uses
System.Classes, System.SysUtils, System.Generics.Collections, Data.DB,
FireDAC.Comp.Client, FireDAC.Stan.StorageBin, FireDAC.Stan.Error, FireDAC.Dats,
FireDAC.Stan.Option, FireDAC.Comp.DataSet, FireDAC.Stan.Intf, FireDAC.DApt.Intf,
WiRL.Core.JSON,
WiRL.Data.FireDAC.Persistence;
type
// Only for reference
//TFDUpdateErrorEvent = procedure (ASender: TDataSet; AException: EFDException;
//ARow: TFDDatSRow; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction) of object;
/// <summary>
/// Mantains a list of errors, this class can be used in response to OnUpdateError FDDataSet events
/// </summary>
TFireDACUpdateErrors = class
private
FErrors: TStringList;
function GetCount: Integer;
public
constructor Create;
destructor Destroy; override;
procedure SetErrorHandler(ASender: TFDMemTable); virtual;
procedure ClearErrorHandler(ASender: TFDMemTable); virtual;
procedure Clear;
/// <remarks>
/// Same signature of TFDUpdateErrorEvent type
/// </remarks>
procedure UpdateError(ASender: TDataSet; AException: EFDException;
ARow: TFDDatSRow; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction); virtual;
property Errors: TStringList read FErrors;
property Count: Integer read GetCount;
end;
/// <summary>Delta list payload to apply updates.</summary>
TFireDACApplyUpdates = class
private
FDataSets: TFireDACDataSets;
FErrors: TFireDACUpdateErrors;
function GetValue(AIndex: Integer): TFDMemTable;
function GetValueByName(const AName: string): TFDMemTable;
procedure CopyDataSet(ASource, ADest: TFDAdaptedDataSet);
function InternalApplyUpdates(ADelta: TFDMemTable; AAdapter: TFDTableAdapter;
AMaxErrors: Integer): Integer;
public
function ApplyUpdates(ADelta: TFDMemTable; ASelectCommand: TFDCustomCommand): Integer; overload;
function ApplyUpdates(const AKey: string; ASelectCommand: TFDCustomCommand): Integer; overload;
function ApplyUpdates(AIndex: Integer; ASelectCommand: TFDCustomCommand): Integer; overload;
function ApplyUpdates(const AKey: string; AAdapter: TFDTableAdapter): Integer; overload;
function ApplyUpdates(AIndex: Integer; AAdapter: TFDTableAdapter): Integer; overload;
public
constructor Create(const ADataSets: TFireDACDataSets);
destructor Destroy; override;
property DataSets: TFireDACDataSets read FDataSets;
property Errors: TFireDACUpdateErrors read FErrors;
end;
implementation
{ TFireDACUpdateErrors }
procedure TFireDACUpdateErrors.Clear;
begin
FErrors.Clear;
end;
constructor TFireDACUpdateErrors.Create;
begin
FErrors := TStringList.Create;
end;
destructor TFireDACUpdateErrors.Destroy;
begin
FErrors.Free;
inherited;
end;
procedure TFireDACUpdateErrors.SetErrorHandler(ASender: TFDMemTable);
begin
if not Assigned(ASender.OnUpdateError) then
ASender.OnUpdateError := UpdateError;
end;
procedure TFireDACUpdateErrors.ClearErrorHandler(ASender: TFDMemTable);
var
LCurrentEvent: TFDUpdateErrorEvent;
begin
LCurrentEvent := UpdateError;
if Addr(ASender.OnUpdateError) = Addr(LCurrentEvent) then
ASender.OnUpdateError := nil;
end;
function TFireDACUpdateErrors.GetCount: Integer;
begin
Result := FErrors.Count;
end;
procedure TFireDACUpdateErrors.UpdateError(ASender: TDataSet; AException: EFDException;
ARow: TFDDatSRow; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction);
begin
FErrors.Add(Format('%s %s', [AException.ClassName, AException.Message]));
end;
{ TFireDACApplyUpdates }
function TFireDACApplyUpdates.ApplyUpdates(AIndex: Integer;
ASelectCommand: TFDCustomCommand): Integer;
var
LDelta: TFDMemTable;
LAdapter: TFDTableAdapter;
begin
Assert(ASelectCommand <> nil);
LDelta := GetValue(AIndex);
LAdapter := TFDTableAdapter.Create(nil);
try
LAdapter.SelectCommand := ASelectCommand;
Result := InternalApplyUpdates(LDelta, LAdapter, -1);
finally
LAdapter.Free;
end;
end;
function TFireDACApplyUpdates.ApplyUpdates(const AKey: string;
ASelectCommand: TFDCustomCommand): Integer;
var
LDelta: TFDMemTable;
LAdapter: TFDTableAdapter;
begin
Assert(ASelectCommand <> nil);
LDelta := GetValueByName(AKey);
LAdapter := TFDTableAdapter.Create(nil);
try
LAdapter.SelectCommand := ASelectCommand;
Result := InternalApplyUpdates(LDelta, LAdapter, -1);
finally
LAdapter.Free;
end;
end;
function TFireDACApplyUpdates.ApplyUpdates(const AKey: string;
AAdapter: TFDTableAdapter): Integer;
var
LDelta: TFDMemTable;
begin
LDelta := GetValueByName(AKey);
Result := InternalApplyUpdates(LDelta, AAdapter, -1);
end;
function TFireDACApplyUpdates.ApplyUpdates(AIndex: Integer;
AAdapter: TFDTableAdapter): Integer;
var
LDelta: TFDMemTable;
begin
LDelta := GetValue(AIndex);
Result := InternalApplyUpdates(LDelta, AAdapter, -1);
end;
function TFireDACApplyUpdates.ApplyUpdates(ADelta: TFDMemTable;
ASelectCommand: TFDCustomCommand): Integer;
var
LAdapter: TFDTableAdapter;
begin
Assert(ASelectCommand <> nil);
LAdapter := TFDTableAdapter.Create(nil);
try
LAdapter.SelectCommand := ASelectCommand;
Result := InternalApplyUpdates(ADelta, LAdapter, -1);
finally
LAdapter.Free;
end;
end;
procedure TFireDACApplyUpdates.CopyDataSet(ASource, ADest: TFDAdaptedDataSet);
var
LStream: TStream;
begin
LStream := TMemoryStream.Create;
try
ASource.SaveToStream(LStream, TFDStorageFormat.sfBinary);
LStream.Seek(0, TSeekOrigin.soBeginning);
ADest.LoadFromStream(LStream, TFDStorageFormat.sfBinary);
finally
LStream.Free;
end;
end;
constructor TFireDACApplyUpdates.Create(const ADataSets: TFireDACDataSets);
begin
FErrors := TFireDACUpdateErrors.Create;
FDataSets := ADataSets;
end;
destructor TFireDACApplyUpdates.Destroy;
begin
FErrors.Free;
inherited;
end;
function TFireDACApplyUpdates.GetValue(AIndex: Integer): TFDMemTable;
begin
Result := FDataSets.Items[AIndex].Value as TFDMemTable;
end;
function TFireDACApplyUpdates.GetValueByName(const AName: string): TFDMemTable;
begin
Result := FDataSets.DataSet[AName] as TFDMemTable;
end;
function TFireDACApplyUpdates.InternalApplyUpdates(ADelta: TFDMemTable;
AAdapter: TFDTableAdapter; AMaxErrors: Integer): Integer;
var
LFDMemTable: TFDMemTable;
LFDAdapter: TFDTableAdapter;
LStoreItems: TFDStoreItems;
begin
Assert(AAdapter <> nil);
LFDMemTable := TFDMemTable.Create(nil);
LStoreItems := LFDMemTable.ResourceOptions.StoreItems;
LFDAdapter := TFDTableAdapter.Create(nil);
try
if Assigned(AAdapter.SelectCommand) then
LFDAdapter.SelectCommand := AAdapter.SelectCommand;
if Assigned(AAdapter.InsertCommand) then
LFDAdapter.InsertCommand := AAdapter.InsertCommand;
if Assigned(AAdapter.UpdateCommand) then
LFDAdapter.UpdateCommand := AAdapter.UpdateCommand;
if Assigned(AAdapter.DeleteCommand) then
LFDAdapter.DeleteCommand := AAdapter.DeleteCommand;
LFDAdapter.UpdateTableName := AAdapter.UpdateTableName;
if LFDAdapter.UpdateTableName = '' then
LFDAdapter.UpdateTableName := LFDAdapter.SelectCommand.UpdateOptions.UpdateTableName;
LStoreItems := LFDMemTable.ResourceOptions.StoreItems;
LFDMemTable.ResourceOptions.StoreItems := [siMeta, siDelta];
LFDMemTable.CachedUpdates := True;
LFDMemTable.Adapter := LFDAdapter;
CopyDataSet(ADelta, LFDMemTable);
FErrors.SetErrorHandler(LFDMemTable);
try
Result := LFDMemTable.ApplyUpdates(AMaxErrors);
finally
FErrors.ClearErrorHandler(LFDMemTable);
end;
finally
LFDMemTable.ResourceOptions.StoreItems := LStoreItems;
LFDMemTable.Free;
LFDAdapter.Free;
end;
end;
end.
| 28.259124 | 103 | 0.765207 |
f1b63781856499c6c21b47624066efbc07430511 | 230 | dpr | Pascal | tools/Gabber/src/GabServ/GabServ.dpr | denis-ryzhkov/antiques | 6a67bf606c1b49cc413df26bfdf00d392b605f88 | [
"MIT"
]
| null | null | null | tools/Gabber/src/GabServ/GabServ.dpr | denis-ryzhkov/antiques | 6a67bf606c1b49cc413df26bfdf00d392b605f88 | [
"MIT"
]
| null | null | null | tools/Gabber/src/GabServ/GabServ.dpr | denis-ryzhkov/antiques | 6a67bf606c1b49cc413df26bfdf00d392b605f88 | [
"MIT"
]
| null | null | null | program GabServ;
uses
Forms,
GSMain in 'GSMain.pas' {GSMainF};
{$R *.RES}
begin
Application.Initialize;
Application.Title := 'GabServ';
Application.CreateForm(TGSMainF, GSMainF);
Application.Run;
end.
| 15.333333 | 45 | 0.665217 |
85e811532d2a4e439e4cfccd0346981cfe2e7d6f | 23,818 | dfm | Pascal | InfoEdit/Base/uMain.dfm | wzguo/TreeEditDemo | aaf13a1b2c7cf35b90548889a370d5c3d065d95a | [
"MIT"
]
| 1 | 2021-07-20T09:34:59.000Z | 2021-07-20T09:34:59.000Z | InfoEdit/Base/uMain.dfm | wuzguo/TreeEditDemo | aaf13a1b2c7cf35b90548889a370d5c3d065d95a | [
"MIT"
]
| null | null | null | InfoEdit/Base/uMain.dfm | wuzguo/TreeEditDemo | aaf13a1b2c7cf35b90548889a370d5c3d065d95a | [
"MIT"
]
| null | null | null | object FrmMain: TFrmMain
Left = 473
Top = 266
BorderIcons = [biSystemMenu, biMinimize]
Caption = 'FrmMain'
ClientHeight = 503
ClientWidth = 726
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
Position = poScreenCenter
OnClose = FormClose
OnCreate = FormCreate
OnShow = FormShow
PixelsPerInch = 96
TextHeight = 13
object PanelMain: TPanel
Left = 0
Top = 0
Width = 726
Height = 503
Align = alClient
Caption = 'PanelMain'
TabOrder = 0
object GroupBoxMain: TGroupBox
Left = 1
Top = 1
Width = 724
Height = 501
Align = alClient
Caption = #20449#24687#26597#35810
TabOrder = 0
object PanelLeft: TPanel
Left = 2
Top = 15
Width = 223
Height = 484
Align = alLeft
Caption = 'PanelLeft'
TabOrder = 0
object TreeViewMain: TTreeView
Left = 1
Top = 1
Width = 221
Height = 482
Align = alClient
Images = ImageList
Indent = 19
ReadOnly = True
TabOrder = 0
OnChange = TreeViewMainChange
OnClick = TreeViewMainClick
OnCollapsing = TreeViewMainCollapsing
OnDblClick = TreeViewMainDblClick
OnExpanding = TreeViewMainExpanding
end
end
object PanelRight: TPanel
Left = 225
Top = 15
Width = 497
Height = 484
Align = alClient
TabOrder = 1
object cxgrd1: TcxGrid
Left = 1
Top = 1
Width = 495
Height = 482
Hint = #20449#24687#20462#25913#23436#25104#21518#35831#28857#20987#8220#20445#23384#20462#25913#8221#25353#38062#65292#20462#25913#29983#25928#12290
Align = alClient
TabOrder = 0
LookAndFeel.Kind = lfFlat
LookAndFeel.NativeStyle = True
object cxgrdbtblvwGrid1DBTableViewList: TcxGridDBTableView
PopupMenu = PopupMenuMain
NavigatorButtons.ConfirmDelete = False
DataController.DataSource = dsDetail
DataController.Summary.DefaultGroupSummaryItems = <>
DataController.Summary.FooterSummaryItems = <
item
Format = #25968#30446#32479#35745':,0'
Kind = skCount
end
item
end>
DataController.Summary.SummaryGroups = <>
OptionsData.Deleting = False
OptionsData.Editing = False
OptionsSelection.MultiSelect = True
OptionsView.Footer = True
OptionsView.GroupByBox = False
object cxgrdbclmnGrid1DBTableViewListID: TcxGridDBColumn
Caption = #32534#21495'ID'
DataBinding.FieldName = 'Det.PID'
Width = 89
end
object cxgrdbclmnGrid1DBTableViewListName: TcxGridDBColumn
Caption = #21517#31216
DataBinding.FieldName = 'DetName'
Width = 78
end
object cxgrdbclmnGrid1DBTableViewListClassify: TcxGridDBColumn
Caption = #20998#31867
DataBinding.FieldName = 'TypeName'
Width = 70
end
object cxgrdbclmnGrid1DBTableViewListPrice: TcxGridDBColumn
Caption = #21333#20215
DataBinding.FieldName = 'Price'
Width = 73
end
object cxgrdbtblvwGrid1DBTableViewListProducingArea: TcxGridDBColumn
Caption = #20135#22320
DataBinding.FieldName = 'ProducingArea'
Width = 204
end
end
object cxgrdlvlGrid1LevelList: TcxGridLevel
GridView = cxgrdbtblvwGrid1DBTableViewList
end
end
end
end
end
object ImageList: TImageList
Left = 32
Top = 312
Bitmap = {
494C010105000900040010001000FFFFFFFFFF10FFFFFFFFFFFFFFFF424D3600
0000000000003600000028000000400000002000000001002000000000000020
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000800000008000000080
0000008000000080000000800000008000000080000000800000008000000080
0000008000000080000000800000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000800000008000000080
0000008000000080000000800000008000000080000000800000008000000080
0000008000000080000000800000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000800000FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF000080000000800000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000800000FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF000080000000800000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000800000FFFFFF000080
0000008000000080000000800000008000000080000000800000008000000080
0000008000000080000000800000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000800000FFFFFF000080
000000800000008000000080000000800000FFFFFF0000800000008000000080
0000FFFFFF000080000000800000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000800000FFFFFF00FFFF
FF00008000000080000000800000FFFFFF000080000000800000008000000080
0000FFFFFF000080000000800000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000800000FFFFFF00FFFF
FF00FFFFFF0000800000FFFFFF00008000000080000000800000FFFFFF00FFFF
FF00FFFFFF000080000000800000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000800000FFFFFF00FFFF
FF00FFFFFF00FFFFFF0000800000008000000080000000800000FFFFFF00FFFF
FF00FFFFFF000080000000800000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000800000FFFFFF00FFFF
FF00FFFFFF00008000000080000000800000008000000080000000800000FFFF
FF00FFFFFF000080000000800000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000800000FFFFFF00FFFF
FF00008000000080000000800000FFFFFF000080000000800000008000000080
0000FFFFFF000080000000800000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000800000FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF000080000000800000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000800000FFFFFF00FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFF
FF00FFFFFF000080000000800000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000800000008000000080
0000008000000080000000800000008000000080000000800000008000000080
0000008000000080000000800000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000EEEEEE00D0D0
D000D0D0D000D0D0D000D0D0D000D0D0D000D0D0D000D0D0D000D0D0D000D0D0
D000D0D0D000D0D0D000F4F4F400000000000000000000000000EFF4F5009BA1
A200979D9E00989E9F00989E9F00989FA000999FA000999FA000999FA00099A0
A0009AA0A000979D9E00D6D6D600000000000000000000000000CEDBE0008F82
7E00BAADA800E7DEDB00FFFBF900000000000000000000000000000000000000
00000000000000000000000000000000000000000000FBF3F000ECE4E200FFFD
FB00000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000FAFAFA00C3C3C300C7947E00C491
7B00BF8C7900BB887700B7847500B3807300AF7C7100AB786F00A8756D00A471
6B009F6C6A009C696700D0D0D000000000000000000080008000AB816B00EAAD
A100E3A69D00E0A49C00DFA39C00DB9F9B00DA9E9B00D79C9A00D59A9A00D298
9900D2989D00B4746B008B91920000000000000000000000000048B5DA0031B8
EC001C8BB4001D6A840039626F007E757100AD9F9A00DBD1CE00FDF7F5000000
0000000000000000000000000000000000000000000069B6D000246A83004661
6A00897C7900B8ABA700E6DDDA00FFFBF9000000000000000000000000000000
000000000000000000000000000000000000B7B7B70071718E00C5968A00FFEA
D400FFE7CF00FFE4C900FFE1C400FFDFBF00FFDCB900FFD9B400FFD6AD00FFD3
A800FFD0A2009C696700D0D0D00000000000E4E0DA000000FF0080008000F9F3
E100FFF2D800FFEDD100FFE9CA00FFE7C500FFE4BE00FFE1B800FFDDB100FFDA
AB00FFDEA700D09784008E94960000000000000000000000000043AFD4008BE4
FF0078DFFF007AE3FF0064D9FF0039C6F800249BC4001F739000275D7000696D
6F00A4948E00E7E7E70000000000000000000000000041B0D600D2FEFF0050D0
FF0031BCEF002390B5001A6A8600365E6C007E747100AC9F9A00DBD1CE00FDF8
F60000000000000000000000000000000000ABD7F2003B8EEA00817BA500F3DC
CD00FFEAD400FFE7CF00FFE4C900FFE1C400FFDFBF00FFDCB900FFD9B300FFD6
AD00FFD3A8009C696700D0D0D00000000000F7FDFF00800080000000FF008000
8000FFF9DE00FFEAD200FFE5CB00FFE2C600FFE0C100FFDDBB00FFDAB500FFD7
AF00FFDBAD00CD9585008E94960000000000000000000000000021A0CB0099EC
FF0079E0FF007BE1FF007DE2FF0080E4FF0082E8FF0083ECFF007AE9FF004DD4
FE000389B700AA9C97000000000000000000000000004DB6E200B8E6F40074DF
FF007EE2FF007FE6FF0081EAFF006CE1FF003DCBF800299EC5001E7490002D56
6300CFC8C600000000000000000000000000000000007ED1FD003C8BE600817B
A500F3DCCD00FFEAD400FFE7CF00FFE4C900FFE1C400FFDFBF00FFDCB900FFD9
B300FFD6AD009C696700D0D0D0000000000000000000F1FEFF00800080000000
FF0080008000FFF3DB00FFEFD700FFEAD000FFE6CA00FFE1C200FFDDBB00FFD9
B400FFDEB300CD9787008E9496000000000000000000000000000596C800ABF4
FF0081EAFF0084EAFF0084EAFF0084EAFF0084EAFF0084EAFF0085EBFF0090F2
FF0037C3F90090817C000000000000000000000000003FB4E2008ED0E9008BED
FF0081E8FF0083E9FF0083E9FF0084EAFF0088ECFF008AEFFF0090F8FF003EC6
F3006E676500000000000000000000000000000000000000000079C2E8003C85
DF007D79A500FFECD900F3DAC700F1D2C000FBDFC500FFE1C400FFDFBF00FFDB
B800FFD9B3009F6C6800D0D0D000000000000000000000000000E8E1D5008000
80000000FF00FF00FF000000FF000000FF000000FF000000FF00FFE4C500FFDD
BA00FFE0B800CF9989008E9496000000000000000000000000001EA0D200BAFC
FF0089F2FF008CF2FF008CF2FF008CF2FF008CF2FF008CF2FF008CF2FF0092F7
FF0056D3FD006674780000000000000000000000000068C3EA003BB2E200CFFF
FF0087F2FF008DF3FF008DF3FF008DF3FF008DF3FF008DF3FF008DF4FF0099F9
FF0021617600DFD7D50000000000000000000000000000000000DBA887007DCE
FB009B9B9B00D1A28F00FFF0C200FFFFD900FFFFDB00C2999000FFE1C400FFDE
BE00FFDBB800A4716B00D0D0D000000000000000000000000000F2CCB300D9ED
F400FF00FF000000FF00FF00FF00FFFFDC00FFFFE5000000FF000000FF00FFE2
C300FFE3BE00D39E8D008D939500000000000000000000000000059AD100B2F9
FE0093FEFF0095FCFF0095FCFF0095FCFF0095FCFF0095FCFF0095FCFF0098FF
FF007CE6FF003E687600FFFCFA00000000000000000043B8E60038B7F200D3F7
F8008CFEFF0092FDFF0094FDFF0095FDFF0095FDFF0095FDFF0094FFFF009EEF
FF0065C8DB00867A770000000000000000000000000000000000DEAB8900FFF7
EF00D1A29800FFFBCA00FFFFCC00FFFFE400FFFFF900FFFFFF00CAA19500FFE1
C400FFDEBE00AA766E00D0D0D000000000000000000000000000EDCDB800FAF9
F5000000FF00FF00FF00FFF3BD00FFFFE000FFFFFD00000000000000FF004080
FF00FFE6C400D7A291008D93950000000000000000000000000044B4E100BBF8
FC00A8FFFF00A5FFFF00A1FFFF00A3FFFF00A3FFFF00A3FFFF00A3FFFF00A4FF
FF00AAF8FF001E627900FDF6F300000000000000000068C8F10066CFFF007BC7
E400F0FFFF00CFFFFF00BCFFFF00A8FFFF00A9FFFF00A9FFFF00AAFFFF00A0E8
FF00DEFFFF0020526300EEE8E700000000000000000000000000E2AF8A00FFFA
F500FBE3B800FFDBA800FFFFCC00FFFFE400FFFFF400FFFFE400CCB39900FFE4
C900FFE1C300AF7C7000D0D0D000000000000000000000000000EFCFB800F7FA
FD000000FF004080FF00FFEEB900FFFFDF00FFFFF000FFFFEA000000FF004080
FF00FFEACB00DAA795008D9294000000000000000000EBF2F5005EC7EB005ABC
E00094D6EC00BDEDF600EAFFFF00BFFFFF00BEFFFF00BFFFFF00BFFFFF00C2FF
FF00B2F5FF0030798F00E9E1DF0000000000F8F8F8006DCCF00079E0FF0068D8
FC004BC4EC0063C7E90085CFEC00E0F2F700D3FFFF00CFFFFF00CEFFFF00A5E6
FF00FAFFFF005AABC2009E939000000000000000000000000000E5B38C00FFFD
FB00FFF0BD00FFD9A800FFF2C000FFFFD300FFFFDC00FFFFD300D2B29600FFE7
CF00FFE3C800B5827300D0D0D000000000000000000000000000F0D1B900F9FF
FF000000FF00FFF4C200FFDCA700FFFFCC00FFFFD700FFFFD5000000FF001153
EE00FFECD100DDAB98008C9294000000000000000000DBECF200A5EBFA0095FF
FF0083F2FB005CD9EE0026B5DA00E4F5FB00F2FFFF00EBFFFF00E7FFFF00EAFF
FF00C1F5FF00458DA500CCC4C10000000000E2EEF3008BDEF50089F2FF008BF1
FF008DF2FF008BF2FF008AF3FF0060D6EF00A1D8EB00AEDAEC00DAF0F700F6FF
FF0000000000F4FFFF003A5F6B00FFFEFC000000000000000000E9B68E00FFFF
FF00E1C1A700FFFAEC00FFDCB100FFE8B500FFECB900FFF6C300B6898000FFEA
D400FFE7CE00BA877600D0D0D000000000000000000000000000F3D3BA00FAFF
FF000000FF00FF00FF00FFEFE0004080FF004080FF00FFFDC3000000FF00FF00
FF00FFEED400E1AD99008C9194000000000000000000E9F3F800A0E5F50092FF
FF0098FFFF009AFFFF00B7FFFF006AD3EB0066CEE7006AD1E80076CFE70087CE
E600B1E5F90053A9C600D9D0CD0000000000D9EBF300A9EEFA0096FFFF0099FF
FF0099FFFF0095FFFF0098FFFF009BFFFF0093FFFF0090FFFF0078F5FD000075
9B00A3D1E100AADDEF00ADD6E400000000000000000000000000EEBB9000FFFF
FF00F4EAEA00FBF6EE00FFFCE600FFECB900FFFBCA00E0AD8D00FFEFDF00FFEA
D500FFE8D000C08D7900D0D0D000000000000000000000000000F6D5BB00FAFE
FF00000000000000FF00FF00FF00FFFAC300FFF6C0000000FF001153EE00FFED
D800FFF4DA00E4B39C008B9193000000000000000000000000008ACBE400D1FF
FF00B3FFFF00ACFFFF009DCBDE009BC2D100B9E3F300ACDAEB0098D9EA0084E0
F100399FBF00CBDFE6000000000000000000000000008ED1E9009BFFFF0098FF
FF0090FFFF00C7F3FB008ACFE4008CDFF100AFF4FB00BFFFFF00B6FFFF00327C
9200FFF6F2000000000000000000000000000000000000000000F1BE9200FFFF
FF00FFFFFF00FAF7F700BF9A9700D4AB9E00D8B5B200FFF4EA00FFF3E600FFE4
D500FFD1C500C4917B00D0D0D000000000000000000000000000F7D8BC00FBFE
FF0000000000000000000000FF000000FF000000FF000000FF00FFF8EC00FFF4
E500FFC6C800ECA090008A929400000000000000000000000000E4F3F90099D2
E700AAD9EC00ABD8EA00B5D4DF00000000000000000000000000000000000000
0000000000000000000000000000000000000000000090D0E7009BD4E90091DC
EE00C7F7FD0065A4BC00FFFAF500FFFEFF00C8E4EF00A6D5E700A3D5EA00CDE7
F000000000000000000000000000000000000000000000000000F6C39400FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFCFA00FFFAF400FFF7EF00FFF5EC009B6A
69009B6A69009B6A6900E5E5E500000000000000000000000000FBDABC00FDFF
FF0000000000000000000000000000000000FFFFFC00FFF9F200FFFFFB00A26C
5D00BD8155009C685E00D4DADB00000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000FFFF
FE00D5EAF3000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000F9C69600FFFF
FF00FFFFFF00FFFFFF00FFFFFF00FFFFFF00FFFCFA00FFFAF400FFF8F100FDE6
B000D19E8200D6D6D60000000000000000000000000000000000FCDDBE00FEFF
FF000000000000000000000000000000000000000000FFFFFC0000000000C69A
7C00CF977400D4D3D20000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000FECB9800FFFF
FF00FEFEFE00FCFCFC00FBFBFB00FAFAFA00F9F7F700F7F4F100F7F3EF00DAA7
8600D6D6D6000000000000000000000000000000000000000000FDE0C500FADE
C500F8DCC400F4D9C300EED4C200E8D0C000E3CCBF00DEC7BC00DFCBC200B07B
6C00DFE0DE00000000000000000000000000424D3E000000000000003E000000
2800000040000000200000000100010000000000000100000000000000000000
000000000000000000000000FFFFFF00FFFF0000000000008001000000000000
8001000000000000800100000000000080010000000000008001000000000000
8001000000000000800100000000000080010000000000008001000000000000
8001000000000000800100000000000080010000000000008001000000000000
8001000000000000FFFF000000000000FFFFFFFFC001C001C1FF8FFF00018001
C01F80FF00010001C003800F00010001C003800780018001C0038007C001C001
C0038003C001C001C0018003C001C041C0018001C001C00180010001C001C001
80010008C001C00180010001C001C801C0038007C001CC01C1FF800FC001CF01
FFFFE7FFC003CFA3FFFFFFFFC007C00700000000000000000000000000000000
000000000000}
end
object PopupMenuMain: TPopupMenu
Left = 330
Top = 232
object AddNew: TMenuItem
Caption = #26032#22686
OnClick = AddNewClick
end
object AddModify: TMenuItem
Caption = #20462#25913
OnClick = AddModifyClick
end
object N3: TMenuItem
Caption = '-'
end
object InfoCancel: TMenuItem
Caption = #21024#38500
OnClick = InfoCancelClick
end
end
object PopupMenuLeft: TPopupMenu
Left = 67
Top = 128
object AddType: TMenuItem
Caption = #22686#21152#20998#31867
OnClick = AddTypeClick
end
end
object dsDetail: TDataSource
Left = 388
Top = 152
end
end
| 54.503432 | 159 | 0.838232 |
Subsets and Splits
HTML Code Excluding Scripts
The query retrieves a limited set of HTML content entries that are longer than 8 characters and do not contain script tags, offering only basic filtering with minimal analytical value.